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

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