diff --git a/EXAMPLES.md b/EXAMPLES.md index f69e9583..d4eee600 100644 --- a/EXAMPLES.md +++ b/EXAMPLES.md @@ -108,6 +108,7 @@ - [Recovering Login After Process Death (Android)](#recovering-login-after-process-death-android) - [Using with Hooks](#recovering-login-using-hooks) - [Using with Auth0 Class](#recovering-login-using-the-auth0-class) +- [Token Exchange Retry (Android)](#token-exchange-retry-android) - [DPoP (Demonstrating Proof-of-Possession)](#dpop-demonstrating-proof-of-possession) - [Enabling DPoP](#enabling-dpop) - [Making API calls with DPoP](#making-api-calls-with-dpop) @@ -3152,6 +3153,28 @@ if (credentials) { } ``` +## Token Exchange Retry (Android) + +After the browser redirects back, the SDK exchanges the authorization code for tokens. On Android 15+ and on devices with aggressive battery optimization, the OS blocks network access for apps in the background and restores it a moment after the app returns to the foreground. If the exchange fails before reaching Auth0 for this reason, the SDK retries it 2 times, 2 seconds apart, so the login doesn't fail with a `NETWORK_ERROR`. Requests that may have reached Auth0 are never retried, because the authorization code can only be used once. + +You can change the number of retries (a whole number from 0 to 4, where `0` disables retrying) and the delay between them in seconds: + +```js +await authorize( + {}, + { + tokenExchangeMaxRetries: 3, + tokenExchangeRetryDelay: 3, + } +); +``` + +Values outside these ranges reject `authorize()` with an `INVALID_CONFIGURATION` error. + +> **Note:** If you use [`resumeSession()`](#recovering-login-after-process-death-android) to recover a login interrupted by process death, the restored token exchange uses the same retry settings, and `resumeSession()` waits up to 30 seconds for it when a login was in progress as the process died (5 seconds otherwise). The defaults (2 retries, 2 seconds apart) finish in about 4 seconds plus the request time. Keep any custom retries × delay well under 30 seconds, because a token exchange that succeeds after the wait is discarded. + +> **Platform Support:** Android only. These options are ignored on iOS and web. + ## DPoP (Demonstrating Proof-of-Possession) [DPoP](https://datatracker.ietf.org/doc/html/rfc9449) (Demonstrating Proof-of-Possession) is an OAuth 2.0 extension that cryptographically binds access and refresh tokens to a client-specific key pair. This prevents token theft and replay attacks by ensuring that even if a token is intercepted, it cannot be used from a different device. diff --git a/android/build.gradle b/android/build.gradle index 9eb71703..7308ead9 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -84,7 +84,7 @@ dependencies { implementation "com.facebook.react:react-android" implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" implementation "androidx.browser:browser:1.10.0" - implementation 'com.auth0.android:auth0:4.3.0' + implementation 'com.auth0.android:auth0:4.3.1' testImplementation 'junit:junit:4.13.2' testImplementation 'com.squareup.okhttp3:mockwebserver:4.12.0' diff --git a/android/src/main/java/com/auth0/react/A0Auth0Module.kt b/android/src/main/java/com/auth0/react/A0Auth0Module.kt index 86879612..d79a30ea 100644 --- a/android/src/main/java/com/auth0/react/A0Auth0Module.kt +++ b/android/src/main/java/com/auth0/react/A0Auth0Module.kt @@ -1,6 +1,7 @@ package com.auth0.react import android.app.Activity +import android.content.Context import android.content.Intent import android.content.pm.ApplicationInfo import android.os.Build @@ -53,6 +54,11 @@ class A0Auth0Module(private val reactContext: ReactApplicationContext) : A0Auth0 // Grace window (ms) for an in-flight restored token exchange to complete before // resumeWebAuthSession resolves null. private const val RESUME_SESSION_GRACE_MS = 5000L + // Used instead when a login was running as the process died: its restored token exchange + // may still be retrying (about 4 s with the default retry settings, plus the requests). + private const val RESTORED_EXCHANGE_GRACE_MS = 30000L + private const val LOGIN_PREFS = "a0_auth0_react_web_auth" + private const val KEY_LOGIN_ATTEMPT = "login_attempt" private const val MAX_CAUSE_DEPTH = 10 @@ -74,6 +80,12 @@ class A0Auth0Module(private val reactContext: ReactApplicationContext) : A0Auth0 private const val DPOP_MISSING_PARAMETER_CODE = "DPOP_MISSING_PARAMETER" private const val DPOP_CLEAR_KEY_FAILED_CODE = "DPOP_CLEAR_KEY_FAILED" + // JS numbers arrive as Double; toInt() would silently truncate 4.9 to 4 and -0.5 to 0. + internal fun wholeNumber(name: String, value: Double): Int { + require(value % 1.0 == 0.0) { "$name must be a whole number" } + return value.toInt() + } + // OkHttp throws IllegalArgumentException for a negative timeout, which would otherwise // surface after initialization has already stored the Auth0 instance. internal fun invalidTimeoutOption(options: ReadableMap): String? = @@ -213,6 +225,8 @@ class A0Auth0Module(private val reactContext: ReactApplicationContext) : A0Auth0 allowedBrowserPackages: ReadableArray?, useTrustedWebActivity: Boolean, useAuthTab: Boolean, + tokenExchangeMaxRetries: Double?, + tokenExchangeRetryDelay: Double?, promise: Promise ) { webAuthPromise = promise @@ -269,6 +283,15 @@ class A0Auth0Module(private val reactContext: ReactApplicationContext) : A0Auth0 builder.withParameters(cleanedParameters) + try { + tokenExchangeMaxRetries?.let { builder.withTokenExchangeMaxRetries(wholeNumber("tokenExchangeMaxRetries", it)) } + tokenExchangeRetryDelay?.let { builder.withTokenExchangeRetryDelay(wholeNumber("tokenExchangeRetryDelay", it)) } + } catch (e: IllegalArgumentException) { + promise.reject("a0.invalid_configuration", e.message, e) + webAuthPromise = null + return + } + val activity = reactContext.currentActivity if (activity == null) { promise.reject("a0.activity_not_available", "Current Activity is not available") @@ -278,15 +301,18 @@ class A0Auth0Module(private val reactContext: ReactApplicationContext) : A0Auth0 // start() registers a LifecycleObserver internally (Auth0.Android 3.19.0+ for // process-death recovery), which must happen on the main thread. UiThreadUtil.runOnUiThread { + val attempt = startLoginAttempt() builder.start(activity, object : com.auth0.android.callback.Callback { override fun onSuccess(result: Credentials) { + endLoginAttempt(attempt) val map = CredentialsParser.toMap(result) promise.resolve(map) webAuthPromise = null } override fun onFailure(error: AuthenticationException) { + endLoginAttempt(attempt) handleError(error, promise) webAuthPromise = null } @@ -303,6 +329,7 @@ class A0Auth0Module(private val reactContext: ReactApplicationContext) : A0Auth0 return } val lifecycleOwner = activity as LifecycleOwner + val attempt = loginPrefs.getLong(KEY_LOGIN_ATTEMPT, 0L) UiThreadUtil.runOnUiThread { val resolved = java.util.concurrent.atomic.AtomicBoolean(false) @@ -315,6 +342,7 @@ class A0Auth0Module(private val reactContext: ReactApplicationContext) : A0Auth0 override fun onSuccess(result: Credentials) { if (resolved.compareAndSet(false, true)) { timeoutHandler.removeCallbacksAndMessages(null) + endLoginAttempt(attempt) promise.resolve(CredentialsParser.toMap(result)) } } @@ -322,6 +350,7 @@ class A0Auth0Module(private val reactContext: ReactApplicationContext) : A0Auth0 override fun onFailure(error: AuthenticationException) { if (resolved.compareAndSet(false, true)) { timeoutHandler.removeCallbacksAndMessages(null) + endLoginAttempt(attempt) handleError(error, promise) } } @@ -338,18 +367,33 @@ class A0Auth0Module(private val reactContext: ReactApplicationContext) : A0Auth0 WebAuthProvider.registerCallbacks(lifecycleOwner, loginCallback, logoutCallback) // Safety net for the rare case where the restored token exchange is still in - // flight: give it a short grace window, then resolve null if nothing arrived. + // flight: give it a grace window, then resolve null if nothing arrived. // The login callback cancels this timeout if it settles first. if (!resolved.get()) { timeoutHandler.postDelayed({ if (resolved.compareAndSet(false, true)) { + endLoginAttempt(attempt) promise.resolve(null) } - }, RESUME_SESSION_GRACE_MS) + }, if (attempt != 0L) RESTORED_EXCHANGE_GRACE_MS else RESUME_SESSION_GRACE_MS) } } } + // Persisted so a restarted process knows a login was running when the previous one died. Each + // login stores its own id, and ending one only clears that id, so a recovery that finishes + // late can't clear the record of a newer login. + private val loginPrefs get() = reactContext.getSharedPreferences(LOGIN_PREFS, Context.MODE_PRIVATE) + + private fun startLoginAttempt(): Long = + System.currentTimeMillis().also { loginPrefs.edit().putLong(KEY_LOGIN_ATTEMPT, it).apply() } + + private fun endLoginAttempt(attempt: Long) { + if (loginPrefs.getLong(KEY_LOGIN_ATTEMPT, 0L) == attempt) { + loginPrefs.edit().remove(KEY_LOGIN_ATTEMPT).apply() + } + } + @ReactMethod override fun getBundleIdentifier(promise: Promise) { val packageName = reactContext.applicationInfo.packageName diff --git a/android/src/test/java/com/auth0/react/A0Auth0ModuleNetworkingOptionsTest.kt b/android/src/test/java/com/auth0/react/A0Auth0ModuleNetworkingOptionsTest.kt index 68e4e161..aa779005 100644 --- a/android/src/test/java/com/auth0/react/A0Auth0ModuleNetworkingOptionsTest.kt +++ b/android/src/test/java/com/auth0/react/A0Auth0ModuleNetworkingOptionsTest.kt @@ -9,6 +9,7 @@ import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue import org.junit.Assert.fail import org.junit.Before @@ -121,6 +122,23 @@ class A0Auth0ModuleNetworkingOptionsTest { assertEquals("readTimeout", A0Auth0Module.invalidTimeoutOption(options)) } + @Test + fun `wholeNumber keeps whole numbers, including zero and negatives, for the builder to validate`() { + assertEquals(0, A0Auth0Module.wholeNumber("option", 0.0)) + assertEquals(3, A0Auth0Module.wholeNumber("option", 3.0)) + assertEquals(-3, A0Auth0Module.wholeNumber("option", -3.0)) + } + + @Test + fun `wholeNumber rejects values that are not whole numbers instead of truncating them`() { + listOf(4.9, -0.5, -1.5, Double.NaN, Double.POSITIVE_INFINITY).forEach { value -> + val error = assertThrows(IllegalArgumentException::class.java) { + A0Auth0Module.wholeNumber("tokenExchangeRetryDelay", value) + } + assertEquals("tokenExchangeRetryDelay must be a whole number", error.message) + } + } + @Test fun `invalidTimeoutOption accepts zero, positive and missing timeouts`() { assertNull(A0Auth0Module.invalidTimeoutOption(JavaOnlyMap.of("connectTimeout", 0, "writeTimeout", 30))) diff --git a/ios/A0Auth0.mm b/ios/A0Auth0.mm index 11460353..86c16a6a 100644 --- a/ios/A0Auth0.mm +++ b/ios/A0Auth0.mm @@ -155,6 +155,8 @@ - (dispatch_queue_t)methodQueue allowedBrowserPackages:(NSArray * _Nullable)allowedBrowserPackages useTrustedWebActivity:(BOOL)useTrustedWebActivity useAuthTab:(BOOL)useAuthTab +tokenExchangeMaxRetries:(NSNumber * _Nullable)tokenExchangeMaxRetries +tokenExchangeRetryDelay:(NSNumber * _Nullable)tokenExchangeRetryDelay resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { NSInteger maxAgeValue = maxAge != nil ? (NSInteger)[maxAge doubleValue] : 0; diff --git a/src/platforms/native/bridge/NativeBridgeManager.ts b/src/platforms/native/bridge/NativeBridgeManager.ts index ec1caf65..2322f99e 100644 --- a/src/platforms/native/bridge/NativeBridgeManager.ts +++ b/src/platforms/native/bridge/NativeBridgeManager.ts @@ -127,7 +127,9 @@ export class NativeBridgeManager implements NativeBridge { parameters.additionalParameters ?? {}, options.allowedBrowserPackages, options.useTrustedWebActivity ?? false, - options.useAuthTab ?? false + options.useAuthTab ?? false, + options.tokenExchangeMaxRetries, + options.tokenExchangeRetryDelay ); return new CredentialsModel(credential); } diff --git a/src/platforms/native/bridge/__tests__/NativeBridgeManager.spec.ts b/src/platforms/native/bridge/__tests__/NativeBridgeManager.spec.ts index 6ffe586f..a68dae29 100644 --- a/src/platforms/native/bridge/__tests__/NativeBridgeManager.spec.ts +++ b/src/platforms/native/bridge/__tests__/NativeBridgeManager.spec.ts @@ -102,7 +102,9 @@ describe('NativeBridgeManager', () => { parameters.additionalParameters, undefined, // allowedBrowserPackages false, // useTrustedWebActivity - false // useAuthTab (default) + false, // useAuthTab (default) + undefined, // tokenExchangeMaxRetries + undefined // tokenExchangeRetryDelay ); }); @@ -133,7 +135,9 @@ describe('NativeBridgeManager', () => { {}, // additionalParameters undefined, // allowedBrowserPackages false, // useTrustedWebActivity - false // useAuthTab (default) + false, // useAuthTab (default) + undefined, // tokenExchangeMaxRetries + undefined // tokenExchangeRetryDelay ); }); @@ -168,7 +172,9 @@ describe('NativeBridgeManager', () => { {}, allowedBrowserPackages, false, // useTrustedWebActivity - false // useAuthTab (default) + false, // useAuthTab (default) + undefined, // tokenExchangeMaxRetries + undefined // tokenExchangeRetryDelay ); }); @@ -199,7 +205,9 @@ describe('NativeBridgeManager', () => { {}, undefined, // allowedBrowserPackages true, // useTrustedWebActivity - false // useAuthTab (default) + false, // useAuthTab (default) + undefined, // tokenExchangeMaxRetries + undefined // tokenExchangeRetryDelay ); }); @@ -230,7 +238,9 @@ describe('NativeBridgeManager', () => { {}, undefined, // allowedBrowserPackages false, // useTrustedWebActivity - false // useAuthTab (default) + false, // useAuthTab (default) + undefined, // tokenExchangeMaxRetries + undefined // tokenExchangeRetryDelay ); }); @@ -261,8 +271,28 @@ describe('NativeBridgeManager', () => { {}, undefined, // allowedBrowserPackages false, // useTrustedWebActivity - true // useAuthTab + true, // useAuthTab + undefined, // tokenExchangeMaxRetries + undefined // tokenExchangeRetryDelay + ); + }); + + it('should pass the token exchange retry options to native webAuth, including 0 retries', async () => { + MockedAuth0NativeModule.webAuth.mockResolvedValueOnce( + nativeSuccessCredentials as any + ); + + await bridge.authorize( + { redirectUrl: 'com.myapp://cb' }, + { + customScheme: 'com.myapp', + tokenExchangeMaxRetries: 0, + tokenExchangeRetryDelay: 3, + } ); + + const args = MockedAuth0NativeModule.webAuth.mock.calls[0]; + expect(args.slice(-2)).toEqual([0, 3]); }); it('should correctly transform the native response to a Credentials model', async () => { diff --git a/src/specs/NativeA0Auth0.ts b/src/specs/NativeA0Auth0.ts index 7ba8cd51..f4b71527 100644 --- a/src/specs/NativeA0Auth0.ts +++ b/src/specs/NativeA0Auth0.ts @@ -103,7 +103,9 @@ export interface Spec extends TurboModule { additionalParameters: { [key: string]: string } | undefined, allowedBrowserPackages: string[] | undefined, useTrustedWebActivity: boolean, - useAuthTab: boolean + useAuthTab: boolean, + tokenExchangeMaxRetries: Int32 | undefined, + tokenExchangeRetryDelay: Int32 | undefined ): Promise; /** diff --git a/src/types/platform-specific.ts b/src/types/platform-specific.ts index 3a783fdd..f2679c0a 100644 --- a/src/types/platform-specific.ts +++ b/src/types/platform-specific.ts @@ -224,6 +224,35 @@ export interface NativeAuthorizeOptions { * ``` */ useAuthTab?: boolean; + /** + * **Android only:** How many times the code exchange that follows the browser redirect is + * retried when it fails before reaching Auth0, for example because the OS hasn't restored + * the app's network access yet after it was in the background. Requests that may have + * reached Auth0 are never retried. Must be a whole number from 0 to 4; `0` disables retries. + * Invalid values reject `authorize()` with an `INVALID_CONFIGURATION` error. No effect on iOS or Web. + * + * If you recover logins interrupted by process death with `resumeSession()`, the restored + * exchange keeps retrying while `resumeSession()` waits for it, up to 30 seconds when a login + * was in progress as the process died. Keep the whole retry time (retries × delay, plus the + * request itself) under that, as a token exchange that succeeds later is discarded. + * + * @default 2 + * + * @example + * ```typescript + * await authorize({}, { tokenExchangeMaxRetries: 3, tokenExchangeRetryDelay: 3 }); + * ``` + */ + tokenExchangeMaxRetries?: number; + /** + * **Android only:** Seconds to wait between code exchange retries. See + * {@link NativeAuthorizeOptions.tokenExchangeMaxRetries}. Must be a whole number of 0 or + * more. No effect on iOS or Web. See the note on `tokenExchangeMaxRetries` about + * `resumeSession()`. + * + * @default 2 + */ + tokenExchangeRetryDelay?: number; } /**