@smartcrab/react-native 0.3.2 → 0.4.0-next-20261016193833

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.ts CHANGED
@@ -1,7 +1,13 @@
1
1
  import type {
2
+ AdaptiveChallengeAction,
2
3
  AuthorizationCodeGrantRequest,
4
+ EmailResendRequest,
5
+ EmailStartRequest,
6
+ MeIdentityLinkCompleteRequest,
3
7
  MeIdentityLinkRequest,
4
8
  MePasskeyRegistrationVerifyRequest,
9
+ MeRecoveryCompleteRequest,
10
+ MeRecoveryCompleteResponse,
5
11
  MeUpdateRequest,
6
12
  MeUser,
7
13
  Outcome,
@@ -18,6 +24,7 @@ import type {
18
24
  } from "@smartcrab/contracts-public";
19
25
  import {
20
26
  emailChallengeResponseSchema,
27
+ meIdentityLinkCompleteResponseSchema,
21
28
  emailVerifyResponseSchema,
22
29
  err,
23
30
  meIdentityLinkResponseSchema,
@@ -29,6 +36,7 @@ import {
29
36
  meSessionsListResponseSchema,
30
37
  meSessionsRevokeAllResponseSchema,
31
38
  meUpdateResponseSchema,
39
+ meRecoveryCompleteResponseSchema,
32
40
  meUserSchema,
33
41
  ok,
34
42
  passkeyAuthenticationCredentialSchema,
@@ -51,17 +59,20 @@ import { base64UrlEncodeBytes } from "./base64url.js";
51
59
  import { decodeJwtSubClaim } from "./jwt.js";
52
60
  import type { AppStatePort, AppStateStatus, NetworkStatusPort } from "./lifecycle-ports.js";
53
61
  import type { LinkingPort } from "./linking-port.js";
54
- import { constantTimeEqual, generatePkcePair, generateState } from "./pkce.js";
62
+ import { constantTimeEqual, generateNonce, generatePkcePair, generateState } from "./pkce.js";
55
63
  import type { PkcePair } from "./pkce.js";
56
64
  import type { PasskeyNativeAdapter } from "./passkey-adapter.js";
57
65
  import type {
66
+ PersistedPendingIdentityLink,
58
67
  PersistedPendingTransaction,
59
68
  PersistedRefreshRecord,
60
69
  SecureStorePort,
61
70
  } from "./secure-store.js";
62
71
  import {
72
+ parsePersistedPendingIdentityLink,
63
73
  parsePersistedPendingTransaction,
64
74
  parsePersistedRefreshRecord,
75
+ pendingIdentityLinkKey,
65
76
  pendingTransactionKey,
66
77
  refreshRecordKey,
67
78
  } from "./secure-store.js";
@@ -126,6 +137,8 @@ const DEFAULT_SCOPES = ["openid", "profile", "email", "offline_access"] as const
126
137
 
127
138
  /** design.md §21.6: "期限60秒未満でrefreshする." */
128
139
  const ACCESS_TOKEN_REFRESH_SKEW_MS = 60_000;
140
+ /** Identity-link flow: ten-minute begin authorization plus the callback's five-minute code. */
141
+ const PENDING_IDENTITY_LINK_TTL_MS = 15 * 60 * 1000;
129
142
 
130
143
  const ISSUER_PATTERN = /^(https:\/\/[^/]+)\/e\/([A-Za-z0-9_-]+)\/?$/;
131
144
 
@@ -154,6 +167,13 @@ interface InMemorySession {
154
167
  readonly familyId: string;
155
168
  }
156
169
 
170
+ interface AdaptiveChallengeRetry {
171
+ readonly action: AdaptiveChallengeAction;
172
+ readonly transaction: BegunTransaction;
173
+ readonly payload: string;
174
+ readonly challenge: Extract<ReactNativeAuthError, { type: "adaptive_challenge_required" }>;
175
+ }
176
+
157
177
  /** Internal, mutable per-client state. Never exported — only `client.ts` touches it. */
158
178
  interface InternalContext {
159
179
  readonly config: ReactNativeAuthConfig;
@@ -173,11 +193,16 @@ interface InternalContext {
173
193
  readonly networkStatus: NetworkStatusPort | undefined;
174
194
  readonly refreshKey: string;
175
195
  readonly pendingKey: string;
196
+ readonly identityLinkKey: string;
176
197
  accessToken: InMemoryAccessToken | null;
177
198
  currentSession: InMemorySession | null;
178
199
  hasRefreshToken: boolean;
200
+ readonly refreshState: SharedRefreshState;
201
+ sessionGeneration: number;
179
202
  passkeySupported: boolean;
180
203
  pendingTransaction: PersistedPendingTransaction | null;
204
+ pendingIdentityLink: PersistedPendingIdentityLink | null;
205
+ adaptiveRetry: AdaptiveChallengeRetry | null;
181
206
  refreshInFlight: Promise<Outcome<AuthSession, ReactNativeAuthError>> | null;
182
207
  /**
183
208
  * A passkey ceremony (options → native → verify) is running (design.md
@@ -212,6 +237,20 @@ const notify = (ctx: InternalContext): void => {
212
237
  }
213
238
  };
214
239
 
240
+ const syncSessionGeneration = (ctx: InternalContext): void => {
241
+ if (ctx.sessionGeneration === ctx.refreshState.generation) return;
242
+ ctx.sessionGeneration = ctx.refreshState.generation;
243
+ ctx.accessToken = null;
244
+ ctx.currentSession = null;
245
+ ctx.hasRefreshToken = false;
246
+ notify(ctx);
247
+ };
248
+
249
+ const isCurrentSessionGeneration = (ctx: InternalContext, expectedGeneration: number): boolean => {
250
+ syncSessionGeneration(ctx);
251
+ return expectedGeneration === ctx.sessionGeneration;
252
+ };
253
+
215
254
  const toAuthSession = (ctx: InternalContext): AuthSession => {
216
255
  if (ctx.currentSession === null) {
217
256
  // Internal invariant: every caller of this checks `currentSession` first.
@@ -344,8 +383,37 @@ const runPasskeyGet = async (
344
383
  // SecureStore-backed persistence
345
384
  // ---------------------------------------------------------------------------
346
385
 
386
+ interface SharedRefreshState {
387
+ generation: number;
388
+ refreshStoreOperation: Promise<void>;
389
+ }
390
+
391
+ const refreshStatesByKey = new Map<string, SharedRefreshState>();
392
+
393
+ const getRefreshState = (refreshKey: string): SharedRefreshState => {
394
+ const existing = refreshStatesByKey.get(refreshKey);
395
+ if (existing !== undefined) return existing;
396
+ const state = { generation: 0, refreshStoreOperation: Promise.resolve() };
397
+ refreshStatesByKey.set(refreshKey, state);
398
+ return state;
399
+ };
400
+
401
+ const enqueueRefreshStoreOperation = <T>(
402
+ ctx: InternalContext,
403
+ operation: () => T | PromiseLike<T>,
404
+ ): Promise<T> => {
405
+ const pending = ctx.refreshState.refreshStoreOperation.then(operation);
406
+ ctx.refreshState.refreshStoreOperation = pending.then(
407
+ () => undefined,
408
+ () => undefined,
409
+ );
410
+ return pending;
411
+ };
412
+
347
413
  const loadRefreshRecord = async (ctx: InternalContext): Promise<PersistedRefreshRecord | null> => {
348
- const raw = await ctx.secureStore.getItemAsync(ctx.refreshKey);
414
+ const raw = await enqueueRefreshStoreOperation(ctx, () =>
415
+ ctx.secureStore.getItemAsync(ctx.refreshKey),
416
+ );
349
417
  if (raw === null) return null;
350
418
  return Promise.resolve()
351
419
  .then((): unknown => JSON.parse(raw))
@@ -358,9 +426,15 @@ const loadRefreshRecord = async (ctx: InternalContext): Promise<PersistedRefresh
358
426
  const saveRefreshRecord = async (
359
427
  ctx: InternalContext,
360
428
  record: PersistedRefreshRecord,
361
- ): Promise<void> => {
362
- await ctx.secureStore.setItemAsync(ctx.refreshKey, JSON.stringify(record));
429
+ expectedGeneration: number,
430
+ ): Promise<boolean> => {
431
+ const saved = await enqueueRefreshStoreOperation(ctx, () => {
432
+ if (!isCurrentSessionGeneration(ctx, expectedGeneration)) return false;
433
+ return ctx.secureStore.setItemAsync(ctx.refreshKey, JSON.stringify(record)).then(() => true);
434
+ });
435
+ if (!saved || !isCurrentSessionGeneration(ctx, expectedGeneration)) return false;
363
436
  ctx.hasRefreshToken = true;
437
+ return true;
364
438
  };
365
439
 
366
440
  const loadPendingTransaction = async (
@@ -392,12 +466,70 @@ const clearPendingTransaction = async (ctx: InternalContext): Promise<void> => {
392
466
  await ctx.secureStore.deleteItemAsync(ctx.pendingKey);
393
467
  };
394
468
 
395
- /** Full local session destruction (design.md §21.7: `invalid_grant` -> wipe entirely). */
396
- const wipeSession = async (ctx: InternalContext): Promise<void> => {
469
+ const loadPendingIdentityLink = async (
470
+ ctx: InternalContext,
471
+ ): Promise<PersistedPendingIdentityLink | null> => {
472
+ return Promise.resolve()
473
+ .then(() => ctx.secureStore.getItemAsync(ctx.identityLinkKey))
474
+ .then(
475
+ (raw) => {
476
+ if (raw === null) return null;
477
+ return Promise.resolve()
478
+ .then((): unknown => JSON.parse(raw))
479
+ .then(
480
+ (value) => parsePersistedPendingIdentityLink(value),
481
+ () => null,
482
+ );
483
+ },
484
+ () => null,
485
+ )
486
+ .then(async (pending) => {
487
+ if (pending === null || pending.clientId !== ctx.config.clientId) return null;
488
+ if (ctx.now() - pending.createdAt > PENDING_IDENTITY_LINK_TTL_MS) {
489
+ await clearPendingIdentityLink(ctx);
490
+ return null;
491
+ }
492
+ ctx.pendingIdentityLink = pending;
493
+ return pending;
494
+ });
495
+ };
496
+
497
+ const savePendingIdentityLink = async (
498
+ ctx: InternalContext,
499
+ pending: PersistedPendingIdentityLink,
500
+ ): Promise<boolean> =>
501
+ Promise.resolve()
502
+ .then(() => ctx.secureStore.setItemAsync(ctx.identityLinkKey, JSON.stringify(pending)))
503
+ .then(
504
+ () => {
505
+ ctx.pendingIdentityLink = pending;
506
+ return true;
507
+ },
508
+ () => false,
509
+ );
510
+
511
+ const clearPendingIdentityLink = async (ctx: InternalContext): Promise<boolean> => {
512
+ ctx.pendingIdentityLink = null;
513
+ return Promise.resolve()
514
+ .then(() => ctx.secureStore.deleteItemAsync(ctx.identityLinkKey))
515
+ .then(
516
+ () => true,
517
+ () => false,
518
+ );
519
+ };
520
+
521
+ const resetSessionState = (ctx: InternalContext): void => {
522
+ ctx.refreshState.generation += 1;
523
+ ctx.sessionGeneration = ctx.refreshState.generation;
397
524
  ctx.accessToken = null;
398
525
  ctx.currentSession = null;
399
526
  ctx.hasRefreshToken = false;
400
- await ctx.secureStore.deleteItemAsync(ctx.refreshKey);
527
+ };
528
+
529
+ /** Full local session destruction (design.md §21.7: `invalid_grant` -> wipe entirely). */
530
+ const wipeSession = async (ctx: InternalContext): Promise<void> => {
531
+ resetSessionState(ctx);
532
+ await enqueueRefreshStoreOperation(ctx, () => ctx.secureStore.deleteItemAsync(ctx.refreshKey));
401
533
  notify(ctx);
402
534
  };
403
535
 
@@ -409,7 +541,10 @@ const applySession = async (
409
541
  ctx: InternalContext,
410
542
  tokenResponse: TokenResponse,
411
543
  familyId: string,
544
+ expectedGeneration = ctx.sessionGeneration,
412
545
  ): Promise<Outcome<AuthSession, ReactNativeAuthError>> => {
546
+ if (!isCurrentSessionGeneration(ctx, expectedGeneration))
547
+ return err({ type: "not_authenticated" });
413
548
  const subOutcome = await Promise.resolve()
414
549
  .then(() => decodeJwtSubClaim(tokenResponse.access_token))
415
550
  .then(
@@ -424,6 +559,8 @@ const applySession = async (
424
559
  if (subOutcome.value === null) {
425
560
  return err({ type: "invalid_response", message: "access token is missing a `sub` claim" });
426
561
  }
562
+ if (!isCurrentSessionGeneration(ctx, expectedGeneration))
563
+ return err({ type: "not_authenticated" });
427
564
  const userId = subOutcome.value;
428
565
  const nowMs = ctx.now();
429
566
  ctx.accessToken = {
@@ -433,6 +570,8 @@ const applySession = async (
433
570
  ctx.currentSession = { userId, scope: tokenResponse.scope, familyId };
434
571
  if (tokenResponse.refresh_token !== undefined) {
435
572
  const existing = await loadRefreshRecord(ctx);
573
+ if (!isCurrentSessionGeneration(ctx, expectedGeneration))
574
+ return err({ type: "not_authenticated" });
436
575
  const record: PersistedRefreshRecord = {
437
576
  refreshToken: tokenResponse.refresh_token,
438
577
  familyId,
@@ -442,8 +581,11 @@ const applySession = async (
442
581
  createdAt: existing?.createdAt ?? nowMs,
443
582
  lastRefreshedAt: nowMs,
444
583
  };
445
- await saveRefreshRecord(ctx, record);
584
+ const saved = await saveRefreshRecord(ctx, record, expectedGeneration);
585
+ if (!saved) return err({ type: "not_authenticated" });
446
586
  }
587
+ if (!isCurrentSessionGeneration(ctx, expectedGeneration))
588
+ return err({ type: "not_authenticated" });
447
589
  const session = toAuthSession(ctx);
448
590
  notify(ctx);
449
591
  return ok(session);
@@ -469,7 +611,9 @@ const refreshFlightsByKey = new Map<string, RefreshFlight>();
469
611
  const performRefresh = async (
470
612
  ctx: InternalContext,
471
613
  ): Promise<Outcome<RefreshResult, ReactNativeAuthError>> => {
614
+ const generation = ctx.sessionGeneration;
472
615
  const record = await loadRefreshRecord(ctx);
616
+ if (!isCurrentSessionGeneration(ctx, generation)) return err({ type: "not_authenticated" });
473
617
  if (record === null) return err({ type: "not_authenticated" });
474
618
 
475
619
  const body: RefreshTokenGrantRequest = {
@@ -482,6 +626,7 @@ const performRefresh = async (
482
626
  { method: "POST", url: `${ctx.issuer}/oauth2/token`, body },
483
627
  tokenResponseSchema,
484
628
  );
629
+ if (!isCurrentSessionGeneration(ctx, generation)) return err({ type: "not_authenticated" });
485
630
  if (!outcome.ok) {
486
631
  if (outcome.error.type === "oauth_error" && outcome.error.code === "invalid_grant") {
487
632
  // design.md §21.7: "refresh 失敗が invalid_grant なら local session を完全削除."
@@ -493,7 +638,7 @@ const performRefresh = async (
493
638
  return outcome;
494
639
  }
495
640
 
496
- const sessionOutcome = await applySession(ctx, outcome.value, record.familyId);
641
+ const sessionOutcome = await applySession(ctx, outcome.value, record.familyId, generation);
497
642
  if (!sessionOutcome.ok) return sessionOutcome;
498
643
  return ok({
499
644
  familyId: record.familyId,
@@ -519,32 +664,34 @@ const getOrStartRefreshFlight = (ctx: InternalContext): RefreshFlight => {
519
664
  const performSharedRefresh = async (
520
665
  ctx: InternalContext,
521
666
  ): Promise<Outcome<AuthSession, ReactNativeAuthError>> => {
667
+ syncSessionGeneration(ctx);
668
+ const generation = ctx.sessionGeneration;
522
669
  const flight = getOrStartRefreshFlight(ctx);
523
670
  const outcome = await flight.promise;
524
671
  if (!outcome.ok) {
525
- if (
526
- flight.client !== ctx &&
527
- outcome.error.type === "oauth_error" &&
528
- outcome.error.code === "invalid_grant"
529
- ) {
672
+ if (flight.client === ctx) return outcome;
673
+ if (!isCurrentSessionGeneration(ctx, generation)) return err({ type: "not_authenticated" });
674
+ if (outcome.error.type === "oauth_error" && outcome.error.code === "invalid_grant") {
530
675
  await wipeSession(ctx);
531
676
  }
532
677
  return outcome;
533
678
  }
679
+ if (!isCurrentSessionGeneration(ctx, generation)) return err({ type: "not_authenticated" });
534
680
  if (flight.client === ctx) return ok(outcome.value.session);
535
- return applySession(ctx, outcome.value.tokenResponse, outcome.value.familyId);
681
+ return applySession(ctx, outcome.value.tokenResponse, outcome.value.familyId, generation);
536
682
  };
537
683
 
538
684
  /**
539
- * Serializes refresh attempts across client instances that share the same
540
- * Environment/client SecureStore key. Each waiting instance applies the
541
- * returned token response to its own in-memory session after the shared grant
542
- * has been persisted by the request owner.
685
+ * Serializes refresh attempts and SecureStore operations across client instances
686
+ * that share the same Environment/client SecureStore key. Each waiting instance
687
+ * applies the returned token response to its own in-memory session after the
688
+ * shared grant has been persisted by the request owner.
543
689
  */
544
690
  const ensureFreshAccessToken = (
545
691
  ctx: InternalContext,
546
692
  forceRefresh: boolean,
547
693
  ): Promise<Outcome<AuthSession, ReactNativeAuthError>> => {
694
+ syncSessionGeneration(ctx);
548
695
  if (
549
696
  !forceRefresh &&
550
697
  ctx.accessToken !== null &&
@@ -586,12 +733,15 @@ const beginTransaction = async (
586
733
  ): Promise<Outcome<BegunTransaction, ReactNativeAuthError>> => {
587
734
  const pkce = await generatePkcePair(ctx.crypto);
588
735
  const state = generateState(ctx.crypto);
736
+ // design.md §32.1: `openid` requests require a nonce on the headless create as well.
737
+ const nonce = generateNonce(ctx.crypto);
589
738
  const body: TransactionCreateRequest = {
590
739
  client_id: ctx.config.clientId,
591
740
  redirect_uri: ctx.config.redirectUri,
592
741
  code_challenge: pkce.challenge,
593
742
  code_challenge_method: "S256",
594
743
  state,
744
+ nonce,
595
745
  scope: ctx.scope,
596
746
  ...(ctx.resource !== undefined ? { resource: ctx.resource } : {}),
597
747
  response_mode: "native_return",
@@ -610,6 +760,84 @@ const beginTransaction = async (
610
760
  });
611
761
  };
612
762
 
763
+ const adaptiveTransaction = async (
764
+ ctx: InternalContext,
765
+ action: AdaptiveChallengeAction,
766
+ payload: Record<string, unknown>,
767
+ challengeToken: string | undefined,
768
+ existingTransaction?: BegunTransaction,
769
+ ): Promise<Outcome<BegunTransaction, ReactNativeAuthError>> => {
770
+ const payloadKey = JSON.stringify(payload);
771
+ const retry = ctx.adaptiveRetry;
772
+ if (retry !== null && retry.action === action && retry.payload === payloadKey) {
773
+ return challengeToken === undefined ? err(retry.challenge) : ok(retry.transaction);
774
+ }
775
+ if (challengeToken !== undefined) {
776
+ return err({
777
+ type: "invalid_flow_state",
778
+ message: "A challenge token can only retry its matching pending factor request",
779
+ });
780
+ }
781
+ if (retry !== null) {
782
+ ctx.adaptiveRetry = null;
783
+ const cleared = await Promise.resolve()
784
+ .then(() => clearPendingTransaction(ctx))
785
+ .then(
786
+ () => true,
787
+ () => false,
788
+ );
789
+ if (!cleared) {
790
+ return err({
791
+ type: "secure_storage_error",
792
+ message: "Could not clear pending challenge state",
793
+ });
794
+ }
795
+ }
796
+ return existingTransaction === undefined ? beginTransaction(ctx) : ok(existingTransaction);
797
+ };
798
+
799
+ const rememberAdaptiveChallenge = async (
800
+ ctx: InternalContext,
801
+ action: AdaptiveChallengeAction,
802
+ transaction: BegunTransaction,
803
+ payload: Record<string, unknown>,
804
+ challenge: Extract<ReactNativeAuthError, { type: "adaptive_challenge_required" }>,
805
+ existingPending?: PersistedPendingTransaction,
806
+ ): Promise<Outcome<never, ReactNativeAuthError>> => {
807
+ const pending = existingPending ?? {
808
+ transactionId: transaction.transactionId,
809
+ transactionSecret: transaction.transactionSecret,
810
+ state: transaction.state,
811
+ codeVerifier: transaction.pkce.verifier,
812
+ redirectUri: ctx.config.redirectUri,
813
+ createdAt: ctx.now(),
814
+ };
815
+ const saved = await Promise.resolve()
816
+ .then(() => savePendingTransaction(ctx, pending))
817
+ .then(
818
+ () => true,
819
+ () => false,
820
+ );
821
+ if (!saved) {
822
+ ctx.pendingTransaction = null;
823
+ return err({
824
+ type: "secure_storage_error",
825
+ message: "Could not persist pending challenge state",
826
+ });
827
+ }
828
+ ctx.adaptiveRetry = {
829
+ action,
830
+ transaction,
831
+ payload: JSON.stringify(payload),
832
+ challenge,
833
+ };
834
+ return err(challenge);
835
+ };
836
+
837
+ const forgetAdaptiveChallenge = (ctx: InternalContext): void => {
838
+ ctx.adaptiveRetry = null;
839
+ };
840
+
613
841
  /** Exchanges an authorization code returned by completion or native social redirect. */
614
842
  const exchangeAuthorizationCode = async (
615
843
  ctx: InternalContext,
@@ -730,15 +958,27 @@ const passkeyOptionsBody = (ctx: InternalContext): { rp_id?: string } =>
730
958
 
731
959
  const signInWithPasskeyInternal = (
732
960
  ctx: InternalContext,
961
+ input: { readonly challengeToken?: string } | undefined,
733
962
  ): Promise<Outcome<AuthResult, ReactNativeAuthError>> =>
734
- withPasskeyCeremony(ctx, () => runSignInWithPasskeyCeremony(ctx));
963
+ withPasskeyCeremony(ctx, () => runSignInWithPasskeyCeremony(ctx, input));
735
964
 
736
965
  const runSignInWithPasskeyCeremony = async (
737
966
  ctx: InternalContext,
967
+ input: { readonly challengeToken?: string } | undefined,
738
968
  ): Promise<Outcome<AuthResult, ReactNativeAuthError>> => {
739
- const txOutcome = await beginTransaction(ctx);
969
+ const requestBody = passkeyOptionsBody(ctx);
970
+ const txOutcome = await adaptiveTransaction(
971
+ ctx,
972
+ "passkey_auth_options",
973
+ requestBody,
974
+ input?.challengeToken,
975
+ );
740
976
  if (!txOutcome.ok) return txOutcome;
741
977
  const { transactionId, transactionSecret, pkce, state } = txOutcome.value;
978
+ const optionsBody = {
979
+ ...requestBody,
980
+ ...(input?.challengeToken !== undefined ? { challenge_token: input.challengeToken } : {}),
981
+ };
742
982
 
743
983
  const optionsOutcome = await requestJson(
744
984
  ctx.fetchPort,
@@ -748,12 +988,38 @@ const runSignInWithPasskeyCeremony = async (
748
988
  ctx.apiBaseUrl,
749
989
  `/v1/auth/transactions/${transactionId}/passkeys/authentication/options`,
750
990
  ),
751
- body: passkeyOptionsBody(ctx),
991
+ body: optionsBody,
752
992
  transactionSecret,
753
993
  },
754
994
  passkeyAuthenticationOptionsResponseSchema,
755
995
  );
756
- if (!optionsOutcome.ok) return optionsOutcome;
996
+ if (!optionsOutcome.ok) {
997
+ if (optionsOutcome.error.type === "adaptive_challenge_required") {
998
+ return rememberAdaptiveChallenge(
999
+ ctx,
1000
+ "passkey_auth_options",
1001
+ txOutcome.value,
1002
+ requestBody,
1003
+ optionsOutcome.error,
1004
+ );
1005
+ }
1006
+ return optionsOutcome;
1007
+ }
1008
+ if (ctx.adaptiveRetry?.transaction.transactionId === transactionId) {
1009
+ forgetAdaptiveChallenge(ctx);
1010
+ const cleared = await Promise.resolve()
1011
+ .then(() => clearPendingTransaction(ctx))
1012
+ .then(
1013
+ () => true,
1014
+ () => false,
1015
+ );
1016
+ if (!cleared) {
1017
+ return err({
1018
+ type: "secure_storage_error",
1019
+ message: "Could not clear completed challenge state",
1020
+ });
1021
+ }
1022
+ }
757
1023
 
758
1024
  const credentialOutcome = await runPasskeyGet(ctx, optionsOutcome.value);
759
1025
  if (!credentialOutcome.ok) return credentialOutcome;
@@ -834,24 +1100,45 @@ const runRegisterPasskeyCeremony = async (
834
1100
 
835
1101
  const sendEmailCodeInternal = async (
836
1102
  ctx: InternalContext,
837
- email: string,
1103
+ input: { readonly email: string; readonly challengeToken?: string },
838
1104
  ): Promise<Outcome<EmailCodeChallenge, ReactNativeAuthError>> => {
839
- const txOutcome = await beginTransaction(ctx);
1105
+ const originalBody = { email: input.email };
1106
+ const txOutcome = await adaptiveTransaction(
1107
+ ctx,
1108
+ "email_start",
1109
+ originalBody,
1110
+ input.challengeToken,
1111
+ );
840
1112
  if (!txOutcome.ok) return txOutcome;
841
1113
  const { transactionId, transactionSecret, pkce, state } = txOutcome.value;
842
-
1114
+ const body: EmailStartRequest = {
1115
+ ...originalBody,
1116
+ ...(input.challengeToken !== undefined ? { challenge_token: input.challengeToken } : {}),
1117
+ };
843
1118
  const startOutcome = await requestJson(
844
1119
  ctx.fetchPort,
845
1120
  {
846
1121
  method: "POST",
847
1122
  url: buildUrl(ctx.apiBaseUrl, `/v1/auth/transactions/${transactionId}/email/start`),
848
- body: { email },
1123
+ body,
849
1124
  transactionSecret,
850
1125
  },
851
1126
  emailChallengeResponseSchema,
852
1127
  );
853
- if (!startOutcome.ok) return startOutcome;
1128
+ if (!startOutcome.ok) {
1129
+ if (startOutcome.error.type === "adaptive_challenge_required") {
1130
+ return rememberAdaptiveChallenge(
1131
+ ctx,
1132
+ "email_start",
1133
+ txOutcome.value,
1134
+ originalBody,
1135
+ startOutcome.error,
1136
+ );
1137
+ }
1138
+ return startOutcome;
1139
+ }
854
1140
 
1141
+ forgetAdaptiveChallenge(ctx);
855
1142
  await savePendingTransaction(ctx, {
856
1143
  transactionId,
857
1144
  transactionSecret,
@@ -867,6 +1154,67 @@ const sendEmailCodeInternal = async (
867
1154
  });
868
1155
  };
869
1156
 
1157
+ const resendEmailCodeInternal = async (
1158
+ ctx: InternalContext,
1159
+ input: { readonly challengeId: string; readonly challengeToken?: string },
1160
+ ): Promise<Outcome<EmailCodeChallenge, ReactNativeAuthError>> => {
1161
+ const pending = await loadPendingTransaction(ctx);
1162
+ if (pending === null || pending.challengeId !== input.challengeId) {
1163
+ return err({
1164
+ type: "invalid_flow_state",
1165
+ message: "No pending email code challenge matches this challengeId",
1166
+ });
1167
+ }
1168
+ const transaction: BegunTransaction = {
1169
+ transactionId: pending.transactionId,
1170
+ transactionSecret: pending.transactionSecret,
1171
+ pkce: { verifier: pending.codeVerifier, challenge: "", method: "S256" },
1172
+ state: pending.state,
1173
+ };
1174
+ const originalBody = { challenge_id: input.challengeId };
1175
+ const txOutcome = await adaptiveTransaction(
1176
+ ctx,
1177
+ "email_resend",
1178
+ originalBody,
1179
+ input.challengeToken,
1180
+ transaction,
1181
+ );
1182
+ if (!txOutcome.ok) return txOutcome;
1183
+ const body: EmailResendRequest = {
1184
+ ...originalBody,
1185
+ ...(input.challengeToken !== undefined ? { challenge_token: input.challengeToken } : {}),
1186
+ };
1187
+ const outcome = await requestJson(
1188
+ ctx.fetchPort,
1189
+ {
1190
+ method: "POST",
1191
+ url: buildUrl(ctx.apiBaseUrl, `/v1/auth/transactions/${pending.transactionId}/email/resend`),
1192
+ body,
1193
+ transactionSecret: pending.transactionSecret,
1194
+ },
1195
+ emailChallengeResponseSchema,
1196
+ );
1197
+ if (!outcome.ok) {
1198
+ if (outcome.error.type === "adaptive_challenge_required") {
1199
+ return rememberAdaptiveChallenge(
1200
+ ctx,
1201
+ "email_resend",
1202
+ transaction,
1203
+ originalBody,
1204
+ outcome.error,
1205
+ pending,
1206
+ );
1207
+ }
1208
+ return outcome;
1209
+ }
1210
+ forgetAdaptiveChallenge(ctx);
1211
+ await savePendingTransaction(ctx, {
1212
+ ...pending,
1213
+ challengeId: outcome.value.challenge_id,
1214
+ });
1215
+ return ok({ challengeId: outcome.value.challenge_id, expiresAt: outcome.value.expires_at });
1216
+ };
1217
+
870
1218
  const verifyEmailCodeInternal = async (
871
1219
  ctx: InternalContext,
872
1220
  input: { challengeId: string; code: string },
@@ -933,38 +1281,56 @@ const openSystemBrowser = async (
933
1281
 
934
1282
  const signInWithSocialInternal = async (
935
1283
  ctx: InternalContext,
936
- provider: SocialProvider,
1284
+ input: { readonly provider: SocialProvider; readonly challengeToken?: string },
937
1285
  ): Promise<Outcome<AuthResult, ReactNativeAuthError>> => {
938
- const txOutcome = await beginTransaction(ctx);
1286
+ const originalBody = {};
1287
+ const txOutcome = await adaptiveTransaction(
1288
+ ctx,
1289
+ "social_start",
1290
+ originalBody,
1291
+ input.challengeToken,
1292
+ );
939
1293
  if (!txOutcome.ok) return txOutcome;
940
1294
  const { transactionId, transactionSecret, pkce, state } = txOutcome.value;
941
-
942
- await savePendingTransaction(ctx, {
1295
+ const pendingRecord: PersistedPendingTransaction = {
943
1296
  transactionId,
944
1297
  transactionSecret,
945
1298
  state,
946
1299
  codeVerifier: pkce.verifier,
947
1300
  redirectUri: ctx.config.redirectUri,
948
1301
  createdAt: ctx.now(),
949
- });
950
-
1302
+ };
1303
+ await savePendingTransaction(ctx, pendingRecord);
1304
+ const body = input.challengeToken === undefined ? {} : { challenge_token: input.challengeToken };
951
1305
  const startOutcome = await requestJson(
952
1306
  ctx.fetchPort,
953
1307
  {
954
1308
  method: "POST",
955
1309
  url: buildUrl(
956
1310
  ctx.apiBaseUrl,
957
- `/v1/auth/transactions/${transactionId}/social/${provider}/start`,
1311
+ `/v1/auth/transactions/${transactionId}/social/${input.provider}/start`,
958
1312
  ),
959
- body: {},
1313
+ body,
960
1314
  transactionSecret,
961
1315
  },
962
1316
  socialStartResponseSchema,
963
1317
  );
964
1318
  if (!startOutcome.ok) {
1319
+ if (startOutcome.error.type === "adaptive_challenge_required") {
1320
+ return rememberAdaptiveChallenge(
1321
+ ctx,
1322
+ "social_start",
1323
+ txOutcome.value,
1324
+ originalBody,
1325
+ startOutcome.error,
1326
+ pendingRecord,
1327
+ );
1328
+ }
965
1329
  await clearPendingTransaction(ctx);
1330
+ forgetAdaptiveChallenge(ctx);
966
1331
  return startOutcome;
967
1332
  }
1333
+ forgetAdaptiveChallenge(ctx);
968
1334
 
969
1335
  // design.md §20.6: system browser only — embedding a WebView is forbidden.
970
1336
  const browserOutcome = await openSystemBrowser(ctx, startOutcome.value.authorization_url);
@@ -984,7 +1350,10 @@ const signInWithSocialInternal = async (
984
1350
  }
985
1351
  const callbackParams = await Promise.resolve()
986
1352
  .then(() => ctx.linking.parse(callbackUrl).queryParams)
987
- .catch(() => undefined);
1353
+ .then(
1354
+ (params) => params,
1355
+ () => undefined,
1356
+ );
988
1357
  const callbackState = callbackParams?.["state"];
989
1358
  const authorizationCode = callbackParams?.["code"];
990
1359
  if (callbackState === undefined || authorizationCode === undefined) {
@@ -1010,29 +1379,190 @@ const signInWithSocialInternal = async (
1010
1379
  return ok({ session: sessionOutcome.value });
1011
1380
  };
1012
1381
 
1013
- const linkSocialAccountInternal = (
1382
+ const linkSocialAccountInternal = async (
1014
1383
  ctx: InternalContext,
1015
1384
  provider: SocialProvider,
1016
- ): Promise<Outcome<void, ReactNativeAuthError>> =>
1017
- withAccessToken(ctx, async (accessToken) => {
1018
- const body: MeIdentityLinkRequest = { redirect_uri: ctx.config.redirectUri };
1019
- const linkOutcome = await requestJson(
1020
- ctx.fetchPort,
1021
- {
1022
- method: "POST",
1023
- url: buildUrl(ctx.apiBaseUrl, `/v1/me/identities/${provider}/link`),
1024
- body,
1025
- accessToken,
1026
- },
1027
- meIdentityLinkResponseSchema,
1385
+ ): Promise<Outcome<void, ReactNativeAuthError>> => {
1386
+ const session = await ensureFreshAccessToken(ctx, false);
1387
+ if (!session.ok) return session;
1388
+ const accessToken = ctx.accessToken?.token;
1389
+ if (accessToken === undefined) return err({ type: "not_authenticated" });
1390
+
1391
+ const user = await requestJson(
1392
+ ctx.fetchPort,
1393
+ { method: "GET", url: buildUrl(ctx.apiBaseUrl, "/v1/me"), accessToken },
1394
+ meUserSchema,
1395
+ );
1396
+ if (!user.ok) return user;
1397
+
1398
+ const cleared = await clearPendingIdentityLink(ctx);
1399
+ if (!cleared) {
1400
+ return err({ type: "secure_storage_error", message: "Could not clear previous link state" });
1401
+ }
1402
+ const pkce = await generatePkcePair(ctx.crypto);
1403
+ const state = generateState(ctx.crypto);
1404
+ const pending: PersistedPendingIdentityLink = {
1405
+ provider,
1406
+ state,
1407
+ codeVerifier: pkce.verifier,
1408
+ redirectUri: ctx.config.redirectUri,
1409
+ clientId: ctx.config.clientId,
1410
+ userId: user.value.user_id,
1411
+ createdAt: ctx.now(),
1412
+ };
1413
+ if (!(await savePendingIdentityLink(ctx, pending))) {
1414
+ return err({
1415
+ type: "secure_storage_error",
1416
+ message: "Could not persist identity-link PKCE state",
1417
+ });
1418
+ }
1419
+
1420
+ const body: MeIdentityLinkRequest = {
1421
+ redirect_uri: ctx.config.redirectUri,
1422
+ code_challenge: pkce.challenge,
1423
+ code_challenge_method: "S256",
1424
+ state,
1425
+ };
1426
+ const linkOutcome = await requestJson(
1427
+ ctx.fetchPort,
1428
+ {
1429
+ method: "POST",
1430
+ url: buildUrl(ctx.apiBaseUrl, `/v1/me/identities/${provider}/link`),
1431
+ body,
1432
+ accessToken,
1433
+ },
1434
+ meIdentityLinkResponseSchema,
1435
+ );
1436
+ if (!linkOutcome.ok) {
1437
+ const removed = await clearPendingIdentityLink(ctx);
1438
+ return removed
1439
+ ? linkOutcome
1440
+ : err({ type: "secure_storage_error", message: "Could not clear failed link state" });
1441
+ }
1442
+
1443
+ const browserOutcome = await openSystemBrowser(ctx, linkOutcome.value.authorization_url);
1444
+ if (!browserOutcome.ok) {
1445
+ const removed = await clearPendingIdentityLink(ctx);
1446
+ return removed
1447
+ ? browserOutcome
1448
+ : err({ type: "secure_storage_error", message: "Could not clear cancelled link state" });
1449
+ }
1450
+ if (browserOutcome.value.type !== "success") {
1451
+ const removed = await clearPendingIdentityLink(ctx);
1452
+ return removed
1453
+ ? err({ type: "social_cancelled" })
1454
+ : err({ type: "secure_storage_error", message: "Could not clear cancelled link state" });
1455
+ }
1456
+ const callbackUrl = browserOutcome.value.url;
1457
+ if (
1458
+ callbackUrl === undefined ||
1459
+ !URL.canParse(callbackUrl) ||
1460
+ !URL.canParse(pending.redirectUri)
1461
+ ) {
1462
+ await clearPendingIdentityLink(ctx);
1463
+ return err({ type: "state_mismatch" });
1464
+ }
1465
+ const callback = new URL(callbackUrl);
1466
+ const redirect = new URL(pending.redirectUri);
1467
+ if (
1468
+ callback.protocol !== redirect.protocol ||
1469
+ callback.host !== redirect.host ||
1470
+ callback.pathname !== redirect.pathname
1471
+ ) {
1472
+ await clearPendingIdentityLink(ctx);
1473
+ return err({ type: "state_mismatch" });
1474
+ }
1475
+ const callbackParams = await Promise.resolve()
1476
+ .then(() => ctx.linking.parse(callbackUrl).queryParams)
1477
+ .then(
1478
+ (params) => params,
1479
+ () => null,
1028
1480
  );
1029
- if (!linkOutcome.ok) return linkOutcome;
1481
+ const storedPending = await loadPendingIdentityLink(ctx);
1482
+ if (
1483
+ storedPending === null ||
1484
+ storedPending.provider !== pending.provider ||
1485
+ storedPending.clientId !== pending.clientId ||
1486
+ storedPending.userId !== pending.userId ||
1487
+ !constantTimeEqual(storedPending.state, pending.state) ||
1488
+ !constantTimeEqual(storedPending.codeVerifier, pending.codeVerifier)
1489
+ ) {
1490
+ await clearPendingIdentityLink(ctx);
1491
+ return err({ type: "state_mismatch" });
1492
+ }
1493
+ if (callbackParams === null || callbackParams["state"] !== pending.state) {
1494
+ await clearPendingIdentityLink(ctx);
1495
+ return err({ type: "state_mismatch" });
1496
+ }
1497
+ if (callbackParams["reason"] !== undefined) {
1498
+ await clearPendingIdentityLink(ctx);
1499
+ return err({
1500
+ type: "invalid_response",
1501
+ message: `identity-link callback failed: ${callbackParams["reason"]}`,
1502
+ });
1503
+ }
1504
+ const linkCode = callbackParams["link_code"];
1505
+ if (linkCode === undefined || linkCode.length === 0) {
1506
+ await clearPendingIdentityLink(ctx);
1507
+ return err({
1508
+ type: "invalid_response",
1509
+ message: "identity-link callback is missing link_code",
1510
+ });
1511
+ }
1030
1512
 
1031
- const browserOutcome = await openSystemBrowser(ctx, linkOutcome.value.authorization_url);
1032
- if (!browserOutcome.ok) return browserOutcome;
1033
- if (browserOutcome.value.type !== "success") return err({ type: "social_cancelled" });
1034
- return ok(undefined);
1035
- });
1513
+ const currentSession = await ensureFreshAccessToken(ctx, false);
1514
+ if (!currentSession.ok) {
1515
+ await clearPendingIdentityLink(ctx);
1516
+ return currentSession;
1517
+ }
1518
+ const completionToken = ctx.accessToken?.token;
1519
+ if (completionToken === undefined) {
1520
+ await clearPendingIdentityLink(ctx);
1521
+ return err({ type: "not_authenticated" });
1522
+ }
1523
+ const currentUser = await requestJson(
1524
+ ctx.fetchPort,
1525
+ {
1526
+ method: "GET",
1527
+ url: buildUrl(ctx.apiBaseUrl, "/v1/me"),
1528
+ accessToken: completionToken,
1529
+ },
1530
+ meUserSchema,
1531
+ );
1532
+ if (!currentUser.ok) {
1533
+ await clearPendingIdentityLink(ctx);
1534
+ return currentUser;
1535
+ }
1536
+ if (
1537
+ currentUser.value.user_id !== pending.userId ||
1538
+ pending.clientId !== ctx.config.clientId ||
1539
+ pending.provider !== provider
1540
+ ) {
1541
+ await clearPendingIdentityLink(ctx);
1542
+ return err({ type: "state_mismatch" });
1543
+ }
1544
+
1545
+ const completionBody: MeIdentityLinkCompleteRequest = {
1546
+ code: linkCode,
1547
+ code_verifier: pending.codeVerifier,
1548
+ };
1549
+ const completed = await requestJson(
1550
+ ctx.fetchPort,
1551
+ {
1552
+ method: "POST",
1553
+ url: buildUrl(ctx.apiBaseUrl, `/v1/me/identities/${provider}/link/complete`),
1554
+ body: completionBody,
1555
+ accessToken: completionToken,
1556
+ },
1557
+ meIdentityLinkCompleteResponseSchema,
1558
+ );
1559
+ const removed = await clearPendingIdentityLink(ctx);
1560
+ if (!removed) {
1561
+ return err({ type: "secure_storage_error", message: "Could not clear completed link state" });
1562
+ }
1563
+ if (!completed.ok) return completed;
1564
+ return ok(undefined);
1565
+ };
1036
1566
 
1037
1567
  const listPasskeysInternal = (
1038
1568
  ctx: InternalContext,
@@ -1127,6 +1657,41 @@ const updateMeInternal = (
1127
1657
  return ok(toPublicUserProfile(outcome.value));
1128
1658
  });
1129
1659
 
1660
+ const completeRecoveryInternal = (
1661
+ ctx: InternalContext,
1662
+ input: { readonly idempotencyKey: string },
1663
+ ): Promise<Outcome<MeRecoveryCompleteResponse, ReactNativeAuthError>> =>
1664
+ withAccessToken(ctx, async (accessToken) => {
1665
+ const body: MeRecoveryCompleteRequest = { confirmed: true };
1666
+ const outcome = await requestJson(
1667
+ ctx.fetchPort,
1668
+ {
1669
+ method: "POST",
1670
+ url: buildUrl(ctx.apiBaseUrl, "/v1/me/recovery/complete"),
1671
+ body,
1672
+ accessToken,
1673
+ idempotencyKey: input.idempotencyKey,
1674
+ },
1675
+ meRecoveryCompleteResponseSchema,
1676
+ );
1677
+ if (!outcome.ok) return outcome;
1678
+ resetSessionState(ctx);
1679
+ notify(ctx);
1680
+ const cleared = await enqueueRefreshStoreOperation(ctx, () =>
1681
+ ctx.secureStore.deleteItemAsync(ctx.refreshKey),
1682
+ ).then(
1683
+ () => true,
1684
+ () => false,
1685
+ );
1686
+ if (!cleared) {
1687
+ return err({
1688
+ type: "secure_storage_error",
1689
+ message: "The recovery succeeded but the refresh-token store could not be cleared",
1690
+ });
1691
+ }
1692
+ return outcome;
1693
+ });
1694
+
1130
1695
  /** Best-effort revoke, then unconditional local wipe (design.md §21.7: sign-out is never blocked by the network). */
1131
1696
  const signOutInternal = async (ctx: InternalContext): Promise<void> => {
1132
1697
  const record = await loadRefreshRecord(ctx);
@@ -1251,6 +1816,9 @@ export const createReactNativeAuthClientFactory =
1251
1816
  ctx?.networkStatusUnsubscribe?.();
1252
1817
 
1253
1818
  const appState = config.appState ?? defaults.appState;
1819
+
1820
+ const refreshKey = refreshRecordKey(environmentId, config.clientId);
1821
+ const refreshState = getRefreshState(refreshKey);
1254
1822
  const newCtx: InternalContext = {
1255
1823
  config,
1256
1824
  apiBaseUrl,
@@ -1267,13 +1835,18 @@ export const createReactNativeAuthClientFactory =
1267
1835
  crypto: config.crypto ?? defaults.crypto,
1268
1836
  appState,
1269
1837
  networkStatus: config.networkStatus,
1270
- refreshKey: refreshRecordKey(environmentId, config.clientId),
1838
+ refreshKey,
1271
1839
  pendingKey: pendingTransactionKey(environmentId, config.clientId),
1840
+ identityLinkKey: pendingIdentityLinkKey(environmentId, config.clientId),
1272
1841
  accessToken: null,
1273
1842
  currentSession: null,
1274
1843
  hasRefreshToken: false,
1844
+ refreshState,
1845
+ sessionGeneration: refreshState.generation,
1275
1846
  passkeySupported: false,
1276
1847
  pendingTransaction: null,
1848
+ pendingIdentityLink: null,
1849
+ adaptiveRetry: null,
1277
1850
  refreshInFlight: null,
1278
1851
  passkeyInFlight: false,
1279
1852
  listeners: new Set(),
@@ -1299,9 +1872,11 @@ export const createReactNativeAuthClientFactory =
1299
1872
 
1300
1873
  getSession: async (): Promise<AuthSession | null> => {
1301
1874
  const activeCtx = requireConfigured();
1875
+ syncSessionGeneration(activeCtx);
1876
+ const generation = activeCtx.sessionGeneration;
1302
1877
  if (activeCtx.currentSession !== null) return toAuthSession(activeCtx);
1303
1878
  const record = await loadRefreshRecord(activeCtx);
1304
- if (record === null) return null;
1879
+ if (!isCurrentSessionGeneration(activeCtx, generation) || record === null) return null;
1305
1880
  activeCtx.currentSession = {
1306
1881
  userId: record.userId,
1307
1882
  scope: record.scope,
@@ -1311,7 +1886,6 @@ export const createReactNativeAuthClientFactory =
1311
1886
  notify(activeCtx);
1312
1887
  return toAuthSession(activeCtx);
1313
1888
  },
1314
-
1315
1889
  getAccessToken: async (input?: AccessTokenRequest): Promise<string> => {
1316
1890
  const activeCtx = requireConfigured();
1317
1891
  const outcome = await ensureFreshAccessToken(activeCtx, input?.forceRefresh ?? false);
@@ -1322,20 +1896,37 @@ export const createReactNativeAuthClientFactory =
1322
1896
  return activeCtx.accessToken.token;
1323
1897
  },
1324
1898
 
1325
- signInWithPasskey: async (): Promise<AuthResult> =>
1326
- resolveOrThrow(await signInWithPasskeyInternal(requireConfigured())),
1899
+ signInWithPasskey: async (input?: {
1900
+ readonly challengeToken?: string;
1901
+ }): Promise<AuthResult> =>
1902
+ resolveOrThrow(await signInWithPasskeyInternal(requireConfigured(), input)),
1327
1903
 
1328
1904
  registerPasskey: async (input?: RegisterPasskeyInput): Promise<Passkey> =>
1329
1905
  resolveOrThrow(await registerPasskeyInternal(requireConfigured(), input)),
1330
1906
 
1331
- sendEmailCode: async (input: { email: string }): Promise<EmailCodeChallenge> =>
1332
- resolveOrThrow(await sendEmailCodeInternal(requireConfigured(), input.email)),
1333
-
1334
- verifyEmailCode: async (input: { challengeId: string; code: string }): Promise<AuthResult> =>
1907
+ sendEmailCode: async (input: {
1908
+ readonly email: string;
1909
+ readonly challengeToken?: string;
1910
+ }): Promise<EmailCodeChallenge> =>
1911
+ resolveOrThrow(await sendEmailCodeInternal(requireConfigured(), input)),
1912
+
1913
+ resendEmailCode: async (input: {
1914
+ readonly challengeId: string;
1915
+ readonly challengeToken?: string;
1916
+ }): Promise<EmailCodeChallenge> =>
1917
+ resolveOrThrow(await resendEmailCodeInternal(requireConfigured(), input)),
1918
+
1919
+ verifyEmailCode: async (input: {
1920
+ readonly challengeId: string;
1921
+ readonly code: string;
1922
+ }): Promise<AuthResult> =>
1335
1923
  resolveOrThrow(await verifyEmailCodeInternal(requireConfigured(), input)),
1336
1924
 
1337
- signInWithSocial: async (input: { provider: SocialProvider }): Promise<AuthResult> =>
1338
- resolveOrThrow(await signInWithSocialInternal(requireConfigured(), input.provider)),
1925
+ signInWithSocial: async (input: {
1926
+ readonly provider: SocialProvider;
1927
+ readonly challengeToken?: string;
1928
+ }): Promise<AuthResult> =>
1929
+ resolveOrThrow(await signInWithSocialInternal(requireConfigured(), input)),
1339
1930
 
1340
1931
  linkSocialAccount: async (input: { provider: SocialProvider }): Promise<void> =>
1341
1932
  resolveOrThrow(await linkSocialAccountInternal(requireConfigured(), input.provider)),
@@ -1358,16 +1949,25 @@ export const createReactNativeAuthClientFactory =
1358
1949
 
1359
1950
  subscribe: (listener: AuthStateListener): (() => void) => {
1360
1951
  const activeCtx = requireConfigured();
1952
+ syncSessionGeneration(activeCtx);
1361
1953
  activeCtx.listeners.add(listener);
1362
1954
  return () => activeCtx.listeners.delete(listener);
1363
1955
  },
1364
-
1365
- getSnapshot: (): AuthStateSnapshot => requireConfigured().snapshot,
1956
+ getSnapshot: (): AuthStateSnapshot => {
1957
+ const activeCtx = requireConfigured();
1958
+ syncSessionGeneration(activeCtx);
1959
+ return activeCtx.snapshot;
1960
+ },
1366
1961
 
1367
1962
  getMe: async (): Promise<UserProfile> =>
1368
1963
  resolveOrThrow(await getMeInternal(requireConfigured())),
1369
1964
 
1370
1965
  updateMe: async (input: UpdateUserProfileInput): Promise<UserProfile> =>
1371
1966
  resolveOrThrow(await updateMeInternal(requireConfigured(), input)),
1967
+
1968
+ completeRecovery: async (input: {
1969
+ readonly idempotencyKey: string;
1970
+ }): Promise<MeRecoveryCompleteResponse> =>
1971
+ resolveOrThrow(await completeRecoveryInternal(requireConfigured(), input)),
1372
1972
  };
1373
1973
  };