@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/dist/client.js CHANGED
@@ -1,10 +1,10 @@
1
- import { emailChallengeResponseSchema, emailVerifyResponseSchema, err, meIdentityLinkResponseSchema, mePasskeyDeleteResponseSchema, mePasskeyRegistrationOptionsResponseSchema, mePasskeyRegistrationVerifyResponseSchema, mePasskeysListResponseSchema, meSessionRevokeResponseSchema, meSessionsListResponseSchema, meSessionsRevokeAllResponseSchema, meUpdateResponseSchema, meUserSchema, ok, passkeyAuthenticationCredentialSchema, passkeyAuthenticationOptionsResponseSchema, passkeyAuthenticationVerifyResponseSchema, passkeyRegistrationCredentialSchema, revocationResponseSchema, socialStartResponseSchema, tokenResponseSchema, transactionCompleteResponseSchema, transactionCreateResponseSchema, } from "@smartcrab/contracts-public";
1
+ import { emailChallengeResponseSchema, meIdentityLinkCompleteResponseSchema, emailVerifyResponseSchema, err, meIdentityLinkResponseSchema, mePasskeyDeleteResponseSchema, mePasskeyRegistrationOptionsResponseSchema, mePasskeyRegistrationVerifyResponseSchema, mePasskeysListResponseSchema, meSessionRevokeResponseSchema, meSessionsListResponseSchema, meSessionsRevokeAllResponseSchema, meUpdateResponseSchema, meRecoveryCompleteResponseSchema, meUserSchema, ok, passkeyAuthenticationCredentialSchema, passkeyAuthenticationOptionsResponseSchema, passkeyAuthenticationVerifyResponseSchema, passkeyRegistrationCredentialSchema, revocationResponseSchema, socialStartResponseSchema, tokenResponseSchema, transactionCompleteResponseSchema, transactionCreateResponseSchema, } from "@smartcrab/contracts-public";
2
2
  import { ReactNativeAuthClientError } from "./errors.js";
3
3
  import { buildUrl, requestJson } from "./http.js";
4
4
  import { base64UrlEncodeBytes } from "./base64url.js";
5
5
  import { decodeJwtSubClaim } from "./jwt.js";
6
- import { constantTimeEqual, generatePkcePair, generateState } from "./pkce.js";
7
- import { parsePersistedPendingTransaction, parsePersistedRefreshRecord, pendingTransactionKey, refreshRecordKey, } from "./secure-store.js";
6
+ import { constantTimeEqual, generateNonce, generatePkcePair, generateState } from "./pkce.js";
7
+ import { parsePersistedPendingIdentityLink, parsePersistedPendingTransaction, parsePersistedRefreshRecord, pendingIdentityLinkKey, pendingTransactionKey, refreshRecordKey, } from "./secure-store.js";
8
8
  /**
9
9
  * `createReactNativeAuthClient` (design.md §21.3, §21.8).
10
10
  *
@@ -48,6 +48,8 @@ import { parsePersistedPendingTransaction, parsePersistedRefreshRecord, pendingT
48
48
  const DEFAULT_SCOPES = ["openid", "profile", "email", "offline_access"];
49
49
  /** design.md §21.6: "期限60秒未満でrefreshする." */
50
50
  const ACCESS_TOKEN_REFRESH_SKEW_MS = 60_000;
51
+ /** Identity-link flow: ten-minute begin authorization plus the callback's five-minute code. */
52
+ const PENDING_IDENTITY_LINK_TTL_MS = 15 * 60 * 1000;
51
53
  const ISSUER_PATTERN = /^(https:\/\/[^/]+)\/e\/([A-Za-z0-9_-]+)\/?$/;
52
54
  const parseIssuer = (issuer) => {
53
55
  const match = ISSUER_PATTERN.exec(issuer);
@@ -80,6 +82,19 @@ const notify = (ctx) => {
80
82
  listener(ctx.snapshot);
81
83
  }
82
84
  };
85
+ const syncSessionGeneration = (ctx) => {
86
+ if (ctx.sessionGeneration === ctx.refreshState.generation)
87
+ return;
88
+ ctx.sessionGeneration = ctx.refreshState.generation;
89
+ ctx.accessToken = null;
90
+ ctx.currentSession = null;
91
+ ctx.hasRefreshToken = false;
92
+ notify(ctx);
93
+ };
94
+ const isCurrentSessionGeneration = (ctx, expectedGeneration) => {
95
+ syncSessionGeneration(ctx);
96
+ return expectedGeneration === ctx.sessionGeneration;
97
+ };
83
98
  const toAuthSession = (ctx) => {
84
99
  if (ctx.currentSession === null) {
85
100
  // Internal invariant: every caller of this checks `currentSession` first.
@@ -180,20 +195,38 @@ const runPasskeyGet = async (ctx, options) => {
180
195
  return rawOutcome;
181
196
  return parsePasskeyCredentialJson(rawOutcome.value, passkeyAuthenticationCredentialSchema);
182
197
  };
183
- // ---------------------------------------------------------------------------
184
- // SecureStore-backed persistence
185
- // ---------------------------------------------------------------------------
198
+ const refreshStatesByKey = new Map();
199
+ const getRefreshState = (refreshKey) => {
200
+ const existing = refreshStatesByKey.get(refreshKey);
201
+ if (existing !== undefined)
202
+ return existing;
203
+ const state = { generation: 0, refreshStoreOperation: Promise.resolve() };
204
+ refreshStatesByKey.set(refreshKey, state);
205
+ return state;
206
+ };
207
+ const enqueueRefreshStoreOperation = (ctx, operation) => {
208
+ const pending = ctx.refreshState.refreshStoreOperation.then(operation);
209
+ ctx.refreshState.refreshStoreOperation = pending.then(() => undefined, () => undefined);
210
+ return pending;
211
+ };
186
212
  const loadRefreshRecord = async (ctx) => {
187
- const raw = await ctx.secureStore.getItemAsync(ctx.refreshKey);
213
+ const raw = await enqueueRefreshStoreOperation(ctx, () => ctx.secureStore.getItemAsync(ctx.refreshKey));
188
214
  if (raw === null)
189
215
  return null;
190
216
  return Promise.resolve()
191
217
  .then(() => JSON.parse(raw))
192
218
  .then((parsed) => parsePersistedRefreshRecord(parsed), () => null);
193
219
  };
194
- const saveRefreshRecord = async (ctx, record) => {
195
- await ctx.secureStore.setItemAsync(ctx.refreshKey, JSON.stringify(record));
220
+ const saveRefreshRecord = async (ctx, record, expectedGeneration) => {
221
+ const saved = await enqueueRefreshStoreOperation(ctx, () => {
222
+ if (!isCurrentSessionGeneration(ctx, expectedGeneration))
223
+ return false;
224
+ return ctx.secureStore.setItemAsync(ctx.refreshKey, JSON.stringify(record)).then(() => true);
225
+ });
226
+ if (!saved || !isCurrentSessionGeneration(ctx, expectedGeneration))
227
+ return false;
196
228
  ctx.hasRefreshToken = true;
229
+ return true;
197
230
  };
198
231
  const loadPendingTransaction = async (ctx) => {
199
232
  if (ctx.pendingTransaction !== null)
@@ -216,17 +249,57 @@ const clearPendingTransaction = async (ctx) => {
216
249
  ctx.pendingTransaction = null;
217
250
  await ctx.secureStore.deleteItemAsync(ctx.pendingKey);
218
251
  };
219
- /** Full local session destruction (design.md §21.7: `invalid_grant` -> wipe entirely). */
220
- const wipeSession = async (ctx) => {
252
+ const loadPendingIdentityLink = async (ctx) => {
253
+ return Promise.resolve()
254
+ .then(() => ctx.secureStore.getItemAsync(ctx.identityLinkKey))
255
+ .then((raw) => {
256
+ if (raw === null)
257
+ return null;
258
+ return Promise.resolve()
259
+ .then(() => JSON.parse(raw))
260
+ .then((value) => parsePersistedPendingIdentityLink(value), () => null);
261
+ }, () => null)
262
+ .then(async (pending) => {
263
+ if (pending === null || pending.clientId !== ctx.config.clientId)
264
+ return null;
265
+ if (ctx.now() - pending.createdAt > PENDING_IDENTITY_LINK_TTL_MS) {
266
+ await clearPendingIdentityLink(ctx);
267
+ return null;
268
+ }
269
+ ctx.pendingIdentityLink = pending;
270
+ return pending;
271
+ });
272
+ };
273
+ const savePendingIdentityLink = async (ctx, pending) => Promise.resolve()
274
+ .then(() => ctx.secureStore.setItemAsync(ctx.identityLinkKey, JSON.stringify(pending)))
275
+ .then(() => {
276
+ ctx.pendingIdentityLink = pending;
277
+ return true;
278
+ }, () => false);
279
+ const clearPendingIdentityLink = async (ctx) => {
280
+ ctx.pendingIdentityLink = null;
281
+ return Promise.resolve()
282
+ .then(() => ctx.secureStore.deleteItemAsync(ctx.identityLinkKey))
283
+ .then(() => true, () => false);
284
+ };
285
+ const resetSessionState = (ctx) => {
286
+ ctx.refreshState.generation += 1;
287
+ ctx.sessionGeneration = ctx.refreshState.generation;
221
288
  ctx.accessToken = null;
222
289
  ctx.currentSession = null;
223
290
  ctx.hasRefreshToken = false;
224
- await ctx.secureStore.deleteItemAsync(ctx.refreshKey);
291
+ };
292
+ /** Full local session destruction (design.md §21.7: `invalid_grant` -> wipe entirely). */
293
+ const wipeSession = async (ctx) => {
294
+ resetSessionState(ctx);
295
+ await enqueueRefreshStoreOperation(ctx, () => ctx.secureStore.deleteItemAsync(ctx.refreshKey));
225
296
  notify(ctx);
226
297
  };
227
298
  const generateFamilyId = (ctx) => base64UrlEncodeBytes(ctx.crypto.getRandomBytes(16));
228
299
  /** Applies a successful token response to in-memory + persisted state (design.md §21.6). */
229
- const applySession = async (ctx, tokenResponse, familyId) => {
300
+ const applySession = async (ctx, tokenResponse, familyId, expectedGeneration = ctx.sessionGeneration) => {
301
+ if (!isCurrentSessionGeneration(ctx, expectedGeneration))
302
+ return err({ type: "not_authenticated" });
230
303
  const subOutcome = await Promise.resolve()
231
304
  .then(() => decodeJwtSubClaim(tokenResponse.access_token))
232
305
  .then((sub) => ok(sub), () => err({
@@ -238,6 +311,8 @@ const applySession = async (ctx, tokenResponse, familyId) => {
238
311
  if (subOutcome.value === null) {
239
312
  return err({ type: "invalid_response", message: "access token is missing a `sub` claim" });
240
313
  }
314
+ if (!isCurrentSessionGeneration(ctx, expectedGeneration))
315
+ return err({ type: "not_authenticated" });
241
316
  const userId = subOutcome.value;
242
317
  const nowMs = ctx.now();
243
318
  ctx.accessToken = {
@@ -247,6 +322,8 @@ const applySession = async (ctx, tokenResponse, familyId) => {
247
322
  ctx.currentSession = { userId, scope: tokenResponse.scope, familyId };
248
323
  if (tokenResponse.refresh_token !== undefined) {
249
324
  const existing = await loadRefreshRecord(ctx);
325
+ if (!isCurrentSessionGeneration(ctx, expectedGeneration))
326
+ return err({ type: "not_authenticated" });
250
327
  const record = {
251
328
  refreshToken: tokenResponse.refresh_token,
252
329
  familyId,
@@ -256,15 +333,22 @@ const applySession = async (ctx, tokenResponse, familyId) => {
256
333
  createdAt: existing?.createdAt ?? nowMs,
257
334
  lastRefreshedAt: nowMs,
258
335
  };
259
- await saveRefreshRecord(ctx, record);
336
+ const saved = await saveRefreshRecord(ctx, record, expectedGeneration);
337
+ if (!saved)
338
+ return err({ type: "not_authenticated" });
260
339
  }
340
+ if (!isCurrentSessionGeneration(ctx, expectedGeneration))
341
+ return err({ type: "not_authenticated" });
261
342
  const session = toAuthSession(ctx);
262
343
  notify(ctx);
263
344
  return ok(session);
264
345
  };
265
346
  const refreshFlightsByKey = new Map();
266
347
  const performRefresh = async (ctx) => {
348
+ const generation = ctx.sessionGeneration;
267
349
  const record = await loadRefreshRecord(ctx);
350
+ if (!isCurrentSessionGeneration(ctx, generation))
351
+ return err({ type: "not_authenticated" });
268
352
  if (record === null)
269
353
  return err({ type: "not_authenticated" });
270
354
  const body = {
@@ -273,6 +357,8 @@ const performRefresh = async (ctx) => {
273
357
  client_id: ctx.config.clientId,
274
358
  };
275
359
  const outcome = await requestJson(ctx.fetchPort, { method: "POST", url: `${ctx.issuer}/oauth2/token`, body }, tokenResponseSchema);
360
+ if (!isCurrentSessionGeneration(ctx, generation))
361
+ return err({ type: "not_authenticated" });
276
362
  if (!outcome.ok) {
277
363
  if (outcome.error.type === "oauth_error" && outcome.error.code === "invalid_grant") {
278
364
  // design.md §21.7: "refresh 失敗が invalid_grant なら local session を完全削除."
@@ -283,7 +369,7 @@ const performRefresh = async (ctx) => {
283
369
  // refresh token is left untouched (design.md §21.7).
284
370
  return outcome;
285
371
  }
286
- const sessionOutcome = await applySession(ctx, outcome.value, record.familyId);
372
+ const sessionOutcome = await applySession(ctx, outcome.value, record.familyId, generation);
287
373
  if (!sessionOutcome.ok)
288
374
  return sessionOutcome;
289
375
  return ok({
@@ -306,27 +392,34 @@ const getOrStartRefreshFlight = (ctx) => {
306
392
  return flight;
307
393
  };
308
394
  const performSharedRefresh = async (ctx) => {
395
+ syncSessionGeneration(ctx);
396
+ const generation = ctx.sessionGeneration;
309
397
  const flight = getOrStartRefreshFlight(ctx);
310
398
  const outcome = await flight.promise;
311
399
  if (!outcome.ok) {
312
- if (flight.client !== ctx &&
313
- outcome.error.type === "oauth_error" &&
314
- outcome.error.code === "invalid_grant") {
400
+ if (flight.client === ctx)
401
+ return outcome;
402
+ if (!isCurrentSessionGeneration(ctx, generation))
403
+ return err({ type: "not_authenticated" });
404
+ if (outcome.error.type === "oauth_error" && outcome.error.code === "invalid_grant") {
315
405
  await wipeSession(ctx);
316
406
  }
317
407
  return outcome;
318
408
  }
409
+ if (!isCurrentSessionGeneration(ctx, generation))
410
+ return err({ type: "not_authenticated" });
319
411
  if (flight.client === ctx)
320
412
  return ok(outcome.value.session);
321
- return applySession(ctx, outcome.value.tokenResponse, outcome.value.familyId);
413
+ return applySession(ctx, outcome.value.tokenResponse, outcome.value.familyId, generation);
322
414
  };
323
415
  /**
324
- * Serializes refresh attempts across client instances that share the same
325
- * Environment/client SecureStore key. Each waiting instance applies the
326
- * returned token response to its own in-memory session after the shared grant
327
- * has been persisted by the request owner.
416
+ * Serializes refresh attempts and SecureStore operations across client instances
417
+ * that share the same Environment/client SecureStore key. Each waiting instance
418
+ * applies the returned token response to its own in-memory session after the
419
+ * shared grant has been persisted by the request owner.
328
420
  */
329
421
  const ensureFreshAccessToken = (ctx, forceRefresh) => {
422
+ syncSessionGeneration(ctx);
330
423
  if (!forceRefresh &&
331
424
  ctx.accessToken !== null &&
332
425
  !isExpiringSoon(ctx.accessToken.expiresAt, ctx.now())) {
@@ -351,12 +444,15 @@ const withAccessToken = async (ctx, fn) => {
351
444
  const beginTransaction = async (ctx) => {
352
445
  const pkce = await generatePkcePair(ctx.crypto);
353
446
  const state = generateState(ctx.crypto);
447
+ // design.md §32.1: `openid` requests require a nonce on the headless create as well.
448
+ const nonce = generateNonce(ctx.crypto);
354
449
  const body = {
355
450
  client_id: ctx.config.clientId,
356
451
  redirect_uri: ctx.config.redirectUri,
357
452
  code_challenge: pkce.challenge,
358
453
  code_challenge_method: "S256",
359
454
  state,
455
+ nonce,
360
456
  scope: ctx.scope,
361
457
  ...(ctx.resource !== undefined ? { resource: ctx.resource } : {}),
362
458
  response_mode: "native_return",
@@ -371,6 +467,62 @@ const beginTransaction = async (ctx) => {
371
467
  state,
372
468
  });
373
469
  };
470
+ const adaptiveTransaction = async (ctx, action, payload, challengeToken, existingTransaction) => {
471
+ const payloadKey = JSON.stringify(payload);
472
+ const retry = ctx.adaptiveRetry;
473
+ if (retry !== null && retry.action === action && retry.payload === payloadKey) {
474
+ return challengeToken === undefined ? err(retry.challenge) : ok(retry.transaction);
475
+ }
476
+ if (challengeToken !== undefined) {
477
+ return err({
478
+ type: "invalid_flow_state",
479
+ message: "A challenge token can only retry its matching pending factor request",
480
+ });
481
+ }
482
+ if (retry !== null) {
483
+ ctx.adaptiveRetry = null;
484
+ const cleared = await Promise.resolve()
485
+ .then(() => clearPendingTransaction(ctx))
486
+ .then(() => true, () => false);
487
+ if (!cleared) {
488
+ return err({
489
+ type: "secure_storage_error",
490
+ message: "Could not clear pending challenge state",
491
+ });
492
+ }
493
+ }
494
+ return existingTransaction === undefined ? beginTransaction(ctx) : ok(existingTransaction);
495
+ };
496
+ const rememberAdaptiveChallenge = async (ctx, action, transaction, payload, challenge, existingPending) => {
497
+ const pending = existingPending ?? {
498
+ transactionId: transaction.transactionId,
499
+ transactionSecret: transaction.transactionSecret,
500
+ state: transaction.state,
501
+ codeVerifier: transaction.pkce.verifier,
502
+ redirectUri: ctx.config.redirectUri,
503
+ createdAt: ctx.now(),
504
+ };
505
+ const saved = await Promise.resolve()
506
+ .then(() => savePendingTransaction(ctx, pending))
507
+ .then(() => true, () => false);
508
+ if (!saved) {
509
+ ctx.pendingTransaction = null;
510
+ return err({
511
+ type: "secure_storage_error",
512
+ message: "Could not persist pending challenge state",
513
+ });
514
+ }
515
+ ctx.adaptiveRetry = {
516
+ action,
517
+ transaction,
518
+ payload: JSON.stringify(payload),
519
+ challenge,
520
+ };
521
+ return err(challenge);
522
+ };
523
+ const forgetAdaptiveChallenge = (ctx) => {
524
+ ctx.adaptiveRetry = null;
525
+ };
374
526
  /** Exchanges an authorization code returned by completion or native social redirect. */
375
527
  const exchangeAuthorizationCode = async (ctx, code, expectedState, callbackState, codeVerifier) => {
376
528
  if (!constantTimeEqual(callbackState, expectedState))
@@ -454,20 +606,41 @@ const withPasskeyCeremony = async (ctx, run) => {
454
606
  * domain never changes the RP a shipped build must use.
455
607
  */
456
608
  const passkeyOptionsBody = (ctx) => ctx.config.rpDomain === undefined ? {} : { rp_id: ctx.config.rpDomain };
457
- const signInWithPasskeyInternal = (ctx) => withPasskeyCeremony(ctx, () => runSignInWithPasskeyCeremony(ctx));
458
- const runSignInWithPasskeyCeremony = async (ctx) => {
459
- const txOutcome = await beginTransaction(ctx);
609
+ const signInWithPasskeyInternal = (ctx, input) => withPasskeyCeremony(ctx, () => runSignInWithPasskeyCeremony(ctx, input));
610
+ const runSignInWithPasskeyCeremony = async (ctx, input) => {
611
+ const requestBody = passkeyOptionsBody(ctx);
612
+ const txOutcome = await adaptiveTransaction(ctx, "passkey_auth_options", requestBody, input?.challengeToken);
460
613
  if (!txOutcome.ok)
461
614
  return txOutcome;
462
615
  const { transactionId, transactionSecret, pkce, state } = txOutcome.value;
616
+ const optionsBody = {
617
+ ...requestBody,
618
+ ...(input?.challengeToken !== undefined ? { challenge_token: input.challengeToken } : {}),
619
+ };
463
620
  const optionsOutcome = await requestJson(ctx.fetchPort, {
464
621
  method: "POST",
465
622
  url: buildUrl(ctx.apiBaseUrl, `/v1/auth/transactions/${transactionId}/passkeys/authentication/options`),
466
- body: passkeyOptionsBody(ctx),
623
+ body: optionsBody,
467
624
  transactionSecret,
468
625
  }, passkeyAuthenticationOptionsResponseSchema);
469
- if (!optionsOutcome.ok)
626
+ if (!optionsOutcome.ok) {
627
+ if (optionsOutcome.error.type === "adaptive_challenge_required") {
628
+ return rememberAdaptiveChallenge(ctx, "passkey_auth_options", txOutcome.value, requestBody, optionsOutcome.error);
629
+ }
470
630
  return optionsOutcome;
631
+ }
632
+ if (ctx.adaptiveRetry?.transaction.transactionId === transactionId) {
633
+ forgetAdaptiveChallenge(ctx);
634
+ const cleared = await Promise.resolve()
635
+ .then(() => clearPendingTransaction(ctx))
636
+ .then(() => true, () => false);
637
+ if (!cleared) {
638
+ return err({
639
+ type: "secure_storage_error",
640
+ message: "Could not clear completed challenge state",
641
+ });
642
+ }
643
+ }
471
644
  const credentialOutcome = await runPasskeyGet(ctx, optionsOutcome.value);
472
645
  if (!credentialOutcome.ok)
473
646
  return credentialOutcome;
@@ -516,19 +689,29 @@ const runRegisterPasskeyCeremony = async (ctx, input) => {
516
689
  return ok(toPublicPasskey(verifyOutcome.value.passkey));
517
690
  });
518
691
  };
519
- const sendEmailCodeInternal = async (ctx, email) => {
520
- const txOutcome = await beginTransaction(ctx);
692
+ const sendEmailCodeInternal = async (ctx, input) => {
693
+ const originalBody = { email: input.email };
694
+ const txOutcome = await adaptiveTransaction(ctx, "email_start", originalBody, input.challengeToken);
521
695
  if (!txOutcome.ok)
522
696
  return txOutcome;
523
697
  const { transactionId, transactionSecret, pkce, state } = txOutcome.value;
698
+ const body = {
699
+ ...originalBody,
700
+ ...(input.challengeToken !== undefined ? { challenge_token: input.challengeToken } : {}),
701
+ };
524
702
  const startOutcome = await requestJson(ctx.fetchPort, {
525
703
  method: "POST",
526
704
  url: buildUrl(ctx.apiBaseUrl, `/v1/auth/transactions/${transactionId}/email/start`),
527
- body: { email },
705
+ body,
528
706
  transactionSecret,
529
707
  }, emailChallengeResponseSchema);
530
- if (!startOutcome.ok)
708
+ if (!startOutcome.ok) {
709
+ if (startOutcome.error.type === "adaptive_challenge_required") {
710
+ return rememberAdaptiveChallenge(ctx, "email_start", txOutcome.value, originalBody, startOutcome.error);
711
+ }
531
712
  return startOutcome;
713
+ }
714
+ forgetAdaptiveChallenge(ctx);
532
715
  await savePendingTransaction(ctx, {
533
716
  transactionId,
534
717
  transactionSecret,
@@ -543,6 +726,47 @@ const sendEmailCodeInternal = async (ctx, email) => {
543
726
  expiresAt: startOutcome.value.expires_at,
544
727
  });
545
728
  };
729
+ const resendEmailCodeInternal = async (ctx, input) => {
730
+ const pending = await loadPendingTransaction(ctx);
731
+ if (pending === null || pending.challengeId !== input.challengeId) {
732
+ return err({
733
+ type: "invalid_flow_state",
734
+ message: "No pending email code challenge matches this challengeId",
735
+ });
736
+ }
737
+ const transaction = {
738
+ transactionId: pending.transactionId,
739
+ transactionSecret: pending.transactionSecret,
740
+ pkce: { verifier: pending.codeVerifier, challenge: "", method: "S256" },
741
+ state: pending.state,
742
+ };
743
+ const originalBody = { challenge_id: input.challengeId };
744
+ const txOutcome = await adaptiveTransaction(ctx, "email_resend", originalBody, input.challengeToken, transaction);
745
+ if (!txOutcome.ok)
746
+ return txOutcome;
747
+ const body = {
748
+ ...originalBody,
749
+ ...(input.challengeToken !== undefined ? { challenge_token: input.challengeToken } : {}),
750
+ };
751
+ const outcome = await requestJson(ctx.fetchPort, {
752
+ method: "POST",
753
+ url: buildUrl(ctx.apiBaseUrl, `/v1/auth/transactions/${pending.transactionId}/email/resend`),
754
+ body,
755
+ transactionSecret: pending.transactionSecret,
756
+ }, emailChallengeResponseSchema);
757
+ if (!outcome.ok) {
758
+ if (outcome.error.type === "adaptive_challenge_required") {
759
+ return rememberAdaptiveChallenge(ctx, "email_resend", transaction, originalBody, outcome.error, pending);
760
+ }
761
+ return outcome;
762
+ }
763
+ forgetAdaptiveChallenge(ctx);
764
+ await savePendingTransaction(ctx, {
765
+ ...pending,
766
+ challengeId: outcome.value.challenge_id,
767
+ });
768
+ return ok({ challengeId: outcome.value.challenge_id, expiresAt: outcome.value.expires_at });
769
+ };
546
770
  const verifyEmailCodeInternal = async (ctx, input) => {
547
771
  const pending = await loadPendingTransaction(ctx);
548
772
  if (pending === null || pending.challengeId !== input.challengeId) {
@@ -581,29 +805,37 @@ const openSystemBrowser = async (ctx, url) => Promise.resolve()
581
805
  message: cause instanceof Error ? cause.message : "Failed to open the system browser",
582
806
  retryable: true,
583
807
  }));
584
- const signInWithSocialInternal = async (ctx, provider) => {
585
- const txOutcome = await beginTransaction(ctx);
808
+ const signInWithSocialInternal = async (ctx, input) => {
809
+ const originalBody = {};
810
+ const txOutcome = await adaptiveTransaction(ctx, "social_start", originalBody, input.challengeToken);
586
811
  if (!txOutcome.ok)
587
812
  return txOutcome;
588
813
  const { transactionId, transactionSecret, pkce, state } = txOutcome.value;
589
- await savePendingTransaction(ctx, {
814
+ const pendingRecord = {
590
815
  transactionId,
591
816
  transactionSecret,
592
817
  state,
593
818
  codeVerifier: pkce.verifier,
594
819
  redirectUri: ctx.config.redirectUri,
595
820
  createdAt: ctx.now(),
596
- });
821
+ };
822
+ await savePendingTransaction(ctx, pendingRecord);
823
+ const body = input.challengeToken === undefined ? {} : { challenge_token: input.challengeToken };
597
824
  const startOutcome = await requestJson(ctx.fetchPort, {
598
825
  method: "POST",
599
- url: buildUrl(ctx.apiBaseUrl, `/v1/auth/transactions/${transactionId}/social/${provider}/start`),
600
- body: {},
826
+ url: buildUrl(ctx.apiBaseUrl, `/v1/auth/transactions/${transactionId}/social/${input.provider}/start`),
827
+ body,
601
828
  transactionSecret,
602
829
  }, socialStartResponseSchema);
603
830
  if (!startOutcome.ok) {
831
+ if (startOutcome.error.type === "adaptive_challenge_required") {
832
+ return rememberAdaptiveChallenge(ctx, "social_start", txOutcome.value, originalBody, startOutcome.error, pendingRecord);
833
+ }
604
834
  await clearPendingTransaction(ctx);
835
+ forgetAdaptiveChallenge(ctx);
605
836
  return startOutcome;
606
837
  }
838
+ forgetAdaptiveChallenge(ctx);
607
839
  // design.md §20.6: system browser only — embedding a WebView is forbidden.
608
840
  const browserOutcome = await openSystemBrowser(ctx, startOutcome.value.authorization_url);
609
841
  if (!browserOutcome.ok) {
@@ -621,7 +853,7 @@ const signInWithSocialInternal = async (ctx, provider) => {
621
853
  }
622
854
  const callbackParams = await Promise.resolve()
623
855
  .then(() => ctx.linking.parse(callbackUrl).queryParams)
624
- .catch(() => undefined);
856
+ .then((params) => params, () => undefined);
625
857
  const callbackState = callbackParams?.["state"];
626
858
  const authorizationCode = callbackParams?.["code"];
627
859
  if (callbackState === undefined || authorizationCode === undefined) {
@@ -639,23 +871,158 @@ const signInWithSocialInternal = async (ctx, provider) => {
639
871
  await clearPendingTransaction(ctx);
640
872
  return ok({ session: sessionOutcome.value });
641
873
  };
642
- const linkSocialAccountInternal = (ctx, provider) => withAccessToken(ctx, async (accessToken) => {
643
- const body = { redirect_uri: ctx.config.redirectUri };
874
+ const linkSocialAccountInternal = async (ctx, provider) => {
875
+ const session = await ensureFreshAccessToken(ctx, false);
876
+ if (!session.ok)
877
+ return session;
878
+ const accessToken = ctx.accessToken?.token;
879
+ if (accessToken === undefined)
880
+ return err({ type: "not_authenticated" });
881
+ const user = await requestJson(ctx.fetchPort, { method: "GET", url: buildUrl(ctx.apiBaseUrl, "/v1/me"), accessToken }, meUserSchema);
882
+ if (!user.ok)
883
+ return user;
884
+ const cleared = await clearPendingIdentityLink(ctx);
885
+ if (!cleared) {
886
+ return err({ type: "secure_storage_error", message: "Could not clear previous link state" });
887
+ }
888
+ const pkce = await generatePkcePair(ctx.crypto);
889
+ const state = generateState(ctx.crypto);
890
+ const pending = {
891
+ provider,
892
+ state,
893
+ codeVerifier: pkce.verifier,
894
+ redirectUri: ctx.config.redirectUri,
895
+ clientId: ctx.config.clientId,
896
+ userId: user.value.user_id,
897
+ createdAt: ctx.now(),
898
+ };
899
+ if (!(await savePendingIdentityLink(ctx, pending))) {
900
+ return err({
901
+ type: "secure_storage_error",
902
+ message: "Could not persist identity-link PKCE state",
903
+ });
904
+ }
905
+ const body = {
906
+ redirect_uri: ctx.config.redirectUri,
907
+ code_challenge: pkce.challenge,
908
+ code_challenge_method: "S256",
909
+ state,
910
+ };
644
911
  const linkOutcome = await requestJson(ctx.fetchPort, {
645
912
  method: "POST",
646
913
  url: buildUrl(ctx.apiBaseUrl, `/v1/me/identities/${provider}/link`),
647
914
  body,
648
915
  accessToken,
649
916
  }, meIdentityLinkResponseSchema);
650
- if (!linkOutcome.ok)
651
- return linkOutcome;
917
+ if (!linkOutcome.ok) {
918
+ const removed = await clearPendingIdentityLink(ctx);
919
+ return removed
920
+ ? linkOutcome
921
+ : err({ type: "secure_storage_error", message: "Could not clear failed link state" });
922
+ }
652
923
  const browserOutcome = await openSystemBrowser(ctx, linkOutcome.value.authorization_url);
653
- if (!browserOutcome.ok)
654
- return browserOutcome;
655
- if (browserOutcome.value.type !== "success")
656
- return err({ type: "social_cancelled" });
924
+ if (!browserOutcome.ok) {
925
+ const removed = await clearPendingIdentityLink(ctx);
926
+ return removed
927
+ ? browserOutcome
928
+ : err({ type: "secure_storage_error", message: "Could not clear cancelled link state" });
929
+ }
930
+ if (browserOutcome.value.type !== "success") {
931
+ const removed = await clearPendingIdentityLink(ctx);
932
+ return removed
933
+ ? err({ type: "social_cancelled" })
934
+ : err({ type: "secure_storage_error", message: "Could not clear cancelled link state" });
935
+ }
936
+ const callbackUrl = browserOutcome.value.url;
937
+ if (callbackUrl === undefined ||
938
+ !URL.canParse(callbackUrl) ||
939
+ !URL.canParse(pending.redirectUri)) {
940
+ await clearPendingIdentityLink(ctx);
941
+ return err({ type: "state_mismatch" });
942
+ }
943
+ const callback = new URL(callbackUrl);
944
+ const redirect = new URL(pending.redirectUri);
945
+ if (callback.protocol !== redirect.protocol ||
946
+ callback.host !== redirect.host ||
947
+ callback.pathname !== redirect.pathname) {
948
+ await clearPendingIdentityLink(ctx);
949
+ return err({ type: "state_mismatch" });
950
+ }
951
+ const callbackParams = await Promise.resolve()
952
+ .then(() => ctx.linking.parse(callbackUrl).queryParams)
953
+ .then((params) => params, () => null);
954
+ const storedPending = await loadPendingIdentityLink(ctx);
955
+ if (storedPending === null ||
956
+ storedPending.provider !== pending.provider ||
957
+ storedPending.clientId !== pending.clientId ||
958
+ storedPending.userId !== pending.userId ||
959
+ !constantTimeEqual(storedPending.state, pending.state) ||
960
+ !constantTimeEqual(storedPending.codeVerifier, pending.codeVerifier)) {
961
+ await clearPendingIdentityLink(ctx);
962
+ return err({ type: "state_mismatch" });
963
+ }
964
+ if (callbackParams === null || callbackParams["state"] !== pending.state) {
965
+ await clearPendingIdentityLink(ctx);
966
+ return err({ type: "state_mismatch" });
967
+ }
968
+ if (callbackParams["reason"] !== undefined) {
969
+ await clearPendingIdentityLink(ctx);
970
+ return err({
971
+ type: "invalid_response",
972
+ message: `identity-link callback failed: ${callbackParams["reason"]}`,
973
+ });
974
+ }
975
+ const linkCode = callbackParams["link_code"];
976
+ if (linkCode === undefined || linkCode.length === 0) {
977
+ await clearPendingIdentityLink(ctx);
978
+ return err({
979
+ type: "invalid_response",
980
+ message: "identity-link callback is missing link_code",
981
+ });
982
+ }
983
+ const currentSession = await ensureFreshAccessToken(ctx, false);
984
+ if (!currentSession.ok) {
985
+ await clearPendingIdentityLink(ctx);
986
+ return currentSession;
987
+ }
988
+ const completionToken = ctx.accessToken?.token;
989
+ if (completionToken === undefined) {
990
+ await clearPendingIdentityLink(ctx);
991
+ return err({ type: "not_authenticated" });
992
+ }
993
+ const currentUser = await requestJson(ctx.fetchPort, {
994
+ method: "GET",
995
+ url: buildUrl(ctx.apiBaseUrl, "/v1/me"),
996
+ accessToken: completionToken,
997
+ }, meUserSchema);
998
+ if (!currentUser.ok) {
999
+ await clearPendingIdentityLink(ctx);
1000
+ return currentUser;
1001
+ }
1002
+ if (currentUser.value.user_id !== pending.userId ||
1003
+ pending.clientId !== ctx.config.clientId ||
1004
+ pending.provider !== provider) {
1005
+ await clearPendingIdentityLink(ctx);
1006
+ return err({ type: "state_mismatch" });
1007
+ }
1008
+ const completionBody = {
1009
+ code: linkCode,
1010
+ code_verifier: pending.codeVerifier,
1011
+ };
1012
+ const completed = await requestJson(ctx.fetchPort, {
1013
+ method: "POST",
1014
+ url: buildUrl(ctx.apiBaseUrl, `/v1/me/identities/${provider}/link/complete`),
1015
+ body: completionBody,
1016
+ accessToken: completionToken,
1017
+ }, meIdentityLinkCompleteResponseSchema);
1018
+ const removed = await clearPendingIdentityLink(ctx);
1019
+ if (!removed) {
1020
+ return err({ type: "secure_storage_error", message: "Could not clear completed link state" });
1021
+ }
1022
+ if (!completed.ok)
1023
+ return completed;
657
1024
  return ok(undefined);
658
- });
1025
+ };
659
1026
  const listPasskeysInternal = (ctx) => withAccessToken(ctx, async (accessToken) => {
660
1027
  const outcome = await requestJson(ctx.fetchPort, { method: "GET", url: buildUrl(ctx.apiBaseUrl, "/v1/me/passkeys"), accessToken }, mePasskeysListResponseSchema);
661
1028
  if (!outcome.ok)
@@ -706,6 +1073,28 @@ const updateMeInternal = (ctx, input) => withAccessToken(ctx, async (accessToken
706
1073
  return outcome;
707
1074
  return ok(toPublicUserProfile(outcome.value));
708
1075
  });
1076
+ const completeRecoveryInternal = (ctx, input) => withAccessToken(ctx, async (accessToken) => {
1077
+ const body = { confirmed: true };
1078
+ const outcome = await requestJson(ctx.fetchPort, {
1079
+ method: "POST",
1080
+ url: buildUrl(ctx.apiBaseUrl, "/v1/me/recovery/complete"),
1081
+ body,
1082
+ accessToken,
1083
+ idempotencyKey: input.idempotencyKey,
1084
+ }, meRecoveryCompleteResponseSchema);
1085
+ if (!outcome.ok)
1086
+ return outcome;
1087
+ resetSessionState(ctx);
1088
+ notify(ctx);
1089
+ const cleared = await enqueueRefreshStoreOperation(ctx, () => ctx.secureStore.deleteItemAsync(ctx.refreshKey)).then(() => true, () => false);
1090
+ if (!cleared) {
1091
+ return err({
1092
+ type: "secure_storage_error",
1093
+ message: "The recovery succeeded but the refresh-token store could not be cleared",
1094
+ });
1095
+ }
1096
+ return outcome;
1097
+ });
709
1098
  /** Best-effort revoke, then unconditional local wipe (design.md §21.7: sign-out is never blocked by the network). */
710
1099
  const signOutInternal = async (ctx) => {
711
1100
  const record = await loadRefreshRecord(ctx);
@@ -795,6 +1184,8 @@ export const createReactNativeAuthClientFactory = (defaults) => (initialConfig)
795
1184
  ctx?.appStateSubscription?.remove();
796
1185
  ctx?.networkStatusUnsubscribe?.();
797
1186
  const appState = config.appState ?? defaults.appState;
1187
+ const refreshKey = refreshRecordKey(environmentId, config.clientId);
1188
+ const refreshState = getRefreshState(refreshKey);
798
1189
  const newCtx = {
799
1190
  config,
800
1191
  apiBaseUrl,
@@ -811,13 +1202,18 @@ export const createReactNativeAuthClientFactory = (defaults) => (initialConfig)
811
1202
  crypto: config.crypto ?? defaults.crypto,
812
1203
  appState,
813
1204
  networkStatus: config.networkStatus,
814
- refreshKey: refreshRecordKey(environmentId, config.clientId),
1205
+ refreshKey,
815
1206
  pendingKey: pendingTransactionKey(environmentId, config.clientId),
1207
+ identityLinkKey: pendingIdentityLinkKey(environmentId, config.clientId),
816
1208
  accessToken: null,
817
1209
  currentSession: null,
818
1210
  hasRefreshToken: false,
1211
+ refreshState,
1212
+ sessionGeneration: refreshState.generation,
819
1213
  passkeySupported: false,
820
1214
  pendingTransaction: null,
1215
+ pendingIdentityLink: null,
1216
+ adaptiveRetry: null,
821
1217
  refreshInFlight: null,
822
1218
  passkeyInFlight: false,
823
1219
  listeners: new Set(),
@@ -841,10 +1237,12 @@ export const createReactNativeAuthClientFactory = (defaults) => (initialConfig)
841
1237
  configure,
842
1238
  getSession: async () => {
843
1239
  const activeCtx = requireConfigured();
1240
+ syncSessionGeneration(activeCtx);
1241
+ const generation = activeCtx.sessionGeneration;
844
1242
  if (activeCtx.currentSession !== null)
845
1243
  return toAuthSession(activeCtx);
846
1244
  const record = await loadRefreshRecord(activeCtx);
847
- if (record === null)
1245
+ if (!isCurrentSessionGeneration(activeCtx, generation) || record === null)
848
1246
  return null;
849
1247
  activeCtx.currentSession = {
850
1248
  userId: record.userId,
@@ -864,11 +1262,12 @@ export const createReactNativeAuthClientFactory = (defaults) => (initialConfig)
864
1262
  }
865
1263
  return activeCtx.accessToken.token;
866
1264
  },
867
- signInWithPasskey: async () => resolveOrThrow(await signInWithPasskeyInternal(requireConfigured())),
1265
+ signInWithPasskey: async (input) => resolveOrThrow(await signInWithPasskeyInternal(requireConfigured(), input)),
868
1266
  registerPasskey: async (input) => resolveOrThrow(await registerPasskeyInternal(requireConfigured(), input)),
869
- sendEmailCode: async (input) => resolveOrThrow(await sendEmailCodeInternal(requireConfigured(), input.email)),
1267
+ sendEmailCode: async (input) => resolveOrThrow(await sendEmailCodeInternal(requireConfigured(), input)),
1268
+ resendEmailCode: async (input) => resolveOrThrow(await resendEmailCodeInternal(requireConfigured(), input)),
870
1269
  verifyEmailCode: async (input) => resolveOrThrow(await verifyEmailCodeInternal(requireConfigured(), input)),
871
- signInWithSocial: async (input) => resolveOrThrow(await signInWithSocialInternal(requireConfigured(), input.provider)),
1270
+ signInWithSocial: async (input) => resolveOrThrow(await signInWithSocialInternal(requireConfigured(), input)),
872
1271
  linkSocialAccount: async (input) => resolveOrThrow(await linkSocialAccountInternal(requireConfigured(), input.provider)),
873
1272
  listPasskeys: async () => resolveOrThrow(await listPasskeysInternal(requireConfigured())),
874
1273
  deletePasskey: async (passkeyId) => resolveOrThrow(await deletePasskeyInternal(requireConfigured(), passkeyId)),
@@ -878,11 +1277,17 @@ export const createReactNativeAuthClientFactory = (defaults) => (initialConfig)
878
1277
  signOutAll: async () => signOutAllInternal(requireConfigured()),
879
1278
  subscribe: (listener) => {
880
1279
  const activeCtx = requireConfigured();
1280
+ syncSessionGeneration(activeCtx);
881
1281
  activeCtx.listeners.add(listener);
882
1282
  return () => activeCtx.listeners.delete(listener);
883
1283
  },
884
- getSnapshot: () => requireConfigured().snapshot,
1284
+ getSnapshot: () => {
1285
+ const activeCtx = requireConfigured();
1286
+ syncSessionGeneration(activeCtx);
1287
+ return activeCtx.snapshot;
1288
+ },
885
1289
  getMe: async () => resolveOrThrow(await getMeInternal(requireConfigured())),
886
1290
  updateMe: async (input) => resolveOrThrow(await updateMeInternal(requireConfigured(), input)),
1291
+ completeRecovery: async (input) => resolveOrThrow(await completeRecoveryInternal(requireConfigured(), input)),
887
1292
  };
888
1293
  };