@smartcrab/react-native 0.2.1-next-20261009084044 → 0.3.0

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
@@ -364,29 +364,37 @@ const beginTransaction = async (ctx) => {
364
364
  const outcome = await requestJson(ctx.fetchPort, { method: "POST", url: buildUrl(ctx.apiBaseUrl, "/v1/auth/transactions"), body }, transactionCreateResponseSchema);
365
365
  if (!outcome.ok)
366
366
  return outcome;
367
- return ok({ transactionId: outcome.value.transaction_id, pkce, state });
367
+ return ok({
368
+ transactionId: outcome.value.transaction_id,
369
+ transactionSecret: outcome.value.transaction_secret,
370
+ pkce,
371
+ state,
372
+ });
368
373
  };
369
- /** `.../complete` + code exchange, shared by every sign-in path (design.md §16.3). */
370
- const completeAndExchange = async (ctx, transactionId, expectedState, codeVerifier) => {
371
- const completeOutcome = await requestJson(ctx.fetchPort, {
372
- method: "POST",
373
- url: buildUrl(ctx.apiBaseUrl, `/v1/auth/transactions/${transactionId}/complete`),
374
- body: {},
375
- }, transactionCompleteResponseSchema);
376
- if (!completeOutcome.ok)
377
- return completeOutcome;
378
- if (!constantTimeEqual(completeOutcome.value.state, expectedState)) {
374
+ /** Exchanges an authorization code returned by completion or native social redirect. */
375
+ const exchangeAuthorizationCode = async (ctx, code, expectedState, callbackState, codeVerifier) => {
376
+ if (!constantTimeEqual(callbackState, expectedState))
379
377
  return err({ type: "state_mismatch" });
380
- }
381
378
  const body = {
382
379
  grant_type: "authorization_code",
383
- code: completeOutcome.value.authorization_code,
380
+ code,
384
381
  redirect_uri: ctx.config.redirectUri,
385
382
  code_verifier: codeVerifier,
386
383
  client_id: ctx.config.clientId,
387
384
  };
388
385
  return requestJson(ctx.fetchPort, { method: "POST", url: `${ctx.issuer}/oauth2/token`, body }, tokenResponseSchema);
389
386
  };
387
+ const completeAndExchange = async (ctx, transactionId, transactionSecret, expectedState, codeVerifier) => {
388
+ const completeOutcome = await requestJson(ctx.fetchPort, {
389
+ method: "POST",
390
+ url: buildUrl(ctx.apiBaseUrl, `/v1/auth/transactions/${transactionId}/complete`),
391
+ body: {},
392
+ transactionSecret,
393
+ }, transactionCompleteResponseSchema);
394
+ if (!completeOutcome.ok)
395
+ return completeOutcome;
396
+ return exchangeAuthorizationCode(ctx, completeOutcome.value.authorization_code, expectedState, completeOutcome.value.state, codeVerifier);
397
+ };
390
398
  // ---------------------------------------------------------------------------
391
399
  // Public-method implementations (internal, Outcome-returning)
392
400
  // ---------------------------------------------------------------------------
@@ -451,11 +459,12 @@ const runSignInWithPasskeyCeremony = async (ctx) => {
451
459
  const txOutcome = await beginTransaction(ctx);
452
460
  if (!txOutcome.ok)
453
461
  return txOutcome;
454
- const { transactionId, pkce, state } = txOutcome.value;
462
+ const { transactionId, transactionSecret, pkce, state } = txOutcome.value;
455
463
  const optionsOutcome = await requestJson(ctx.fetchPort, {
456
464
  method: "POST",
457
465
  url: buildUrl(ctx.apiBaseUrl, `/v1/auth/transactions/${transactionId}/passkeys/authentication/options`),
458
466
  body: passkeyOptionsBody(ctx),
467
+ transactionSecret,
459
468
  }, passkeyAuthenticationOptionsResponseSchema);
460
469
  if (!optionsOutcome.ok)
461
470
  return optionsOutcome;
@@ -466,10 +475,11 @@ const runSignInWithPasskeyCeremony = async (ctx) => {
466
475
  method: "POST",
467
476
  url: buildUrl(ctx.apiBaseUrl, `/v1/auth/transactions/${transactionId}/passkeys/authentication/verify`),
468
477
  body: { credential: credentialOutcome.value },
478
+ transactionSecret,
469
479
  }, passkeyAuthenticationVerifyResponseSchema);
470
480
  if (!verifyOutcome.ok)
471
481
  return verifyOutcome;
472
- const tokenOutcome = await completeAndExchange(ctx, transactionId, state, pkce.verifier);
482
+ const tokenOutcome = await completeAndExchange(ctx, transactionId, transactionSecret, state, pkce.verifier);
473
483
  if (!tokenOutcome.ok)
474
484
  return tokenOutcome;
475
485
  const sessionOutcome = await applySession(ctx, tokenOutcome.value, generateFamilyId(ctx));
@@ -510,16 +520,18 @@ const sendEmailCodeInternal = async (ctx, email) => {
510
520
  const txOutcome = await beginTransaction(ctx);
511
521
  if (!txOutcome.ok)
512
522
  return txOutcome;
513
- const { transactionId, pkce, state } = txOutcome.value;
523
+ const { transactionId, transactionSecret, pkce, state } = txOutcome.value;
514
524
  const startOutcome = await requestJson(ctx.fetchPort, {
515
525
  method: "POST",
516
526
  url: buildUrl(ctx.apiBaseUrl, `/v1/auth/transactions/${transactionId}/email/start`),
517
527
  body: { email },
528
+ transactionSecret,
518
529
  }, emailChallengeResponseSchema);
519
530
  if (!startOutcome.ok)
520
531
  return startOutcome;
521
532
  await savePendingTransaction(ctx, {
522
533
  transactionId,
534
+ transactionSecret,
523
535
  state,
524
536
  codeVerifier: pkce.verifier,
525
537
  redirectUri: ctx.config.redirectUri,
@@ -543,12 +555,13 @@ const verifyEmailCodeInternal = async (ctx, input) => {
543
555
  method: "POST",
544
556
  url: buildUrl(ctx.apiBaseUrl, `/v1/auth/transactions/${pending.transactionId}/email/verify`),
545
557
  body: { challenge_id: input.challengeId, code: input.code },
558
+ transactionSecret: pending.transactionSecret,
546
559
  }, emailVerifyResponseSchema);
547
560
  if (!verifyOutcome.ok) {
548
561
  await clearPendingTransaction(ctx);
549
562
  return verifyOutcome;
550
563
  }
551
- const tokenOutcome = await completeAndExchange(ctx, pending.transactionId, pending.state, pending.codeVerifier);
564
+ const tokenOutcome = await completeAndExchange(ctx, pending.transactionId, pending.transactionSecret, pending.state, pending.codeVerifier);
552
565
  if (!tokenOutcome.ok) {
553
566
  await clearPendingTransaction(ctx);
554
567
  return tokenOutcome;
@@ -572,9 +585,10 @@ const signInWithSocialInternal = async (ctx, provider) => {
572
585
  const txOutcome = await beginTransaction(ctx);
573
586
  if (!txOutcome.ok)
574
587
  return txOutcome;
575
- const { transactionId, pkce, state } = txOutcome.value;
588
+ const { transactionId, transactionSecret, pkce, state } = txOutcome.value;
576
589
  await savePendingTransaction(ctx, {
577
590
  transactionId,
591
+ transactionSecret,
578
592
  state,
579
593
  codeVerifier: pkce.verifier,
580
594
  redirectUri: ctx.config.redirectUri,
@@ -584,6 +598,7 @@ const signInWithSocialInternal = async (ctx, provider) => {
584
598
  method: "POST",
585
599
  url: buildUrl(ctx.apiBaseUrl, `/v1/auth/transactions/${transactionId}/social/${provider}/start`),
586
600
  body: {},
601
+ transactionSecret,
587
602
  }, socialStartResponseSchema);
588
603
  if (!startOutcome.ok) {
589
604
  await clearPendingTransaction(ctx);
@@ -604,14 +619,16 @@ const signInWithSocialInternal = async (ctx, provider) => {
604
619
  await clearPendingTransaction(ctx);
605
620
  return err({ type: "state_mismatch" });
606
621
  }
607
- const callbackState = await Promise.resolve()
608
- .then(() => ctx.linking.parse(callbackUrl).queryParams["state"])
622
+ const callbackParams = await Promise.resolve()
623
+ .then(() => ctx.linking.parse(callbackUrl).queryParams)
609
624
  .catch(() => undefined);
610
- if (callbackState === undefined || !constantTimeEqual(callbackState, state)) {
625
+ const callbackState = callbackParams?.["state"];
626
+ const authorizationCode = callbackParams?.["code"];
627
+ if (callbackState === undefined || authorizationCode === undefined) {
611
628
  await clearPendingTransaction(ctx);
612
629
  return err({ type: "state_mismatch" });
613
630
  }
614
- const tokenOutcome = await completeAndExchange(ctx, transactionId, state, pkce.verifier);
631
+ const tokenOutcome = await exchangeAuthorizationCode(ctx, authorizationCode, state, callbackState, pkce.verifier);
615
632
  if (!tokenOutcome.ok) {
616
633
  await clearPendingTransaction(ctx);
617
634
  return tokenOutcome;
@@ -12,6 +12,7 @@ const ENVIRONMENT_ID = "env_abcdefghijklmnopqrstuvwxyzabcdef";
12
12
  const ISSUER = `https://id.example-auth.com/e/${ENVIRONMENT_ID}`;
13
13
  const CLIENT_ID = fakeId("cli");
14
14
  const REDIRECT_URI = "com.customer.app:/oauth/callback";
15
+ const TRANSACTION_SECRET = "s".repeat(43);
15
16
  /** design.md §15.1: OAuth2 endpoints hang off the issuer verbatim, `/e/<environmentId>` path included. */
16
17
  const TOKEN_PATH = `/e/${ENVIRONMENT_ID}/oauth2/token`;
17
18
  const REVOKE_PATH = `/e/${ENVIRONMENT_ID}/oauth2/revoke`;
@@ -41,7 +42,7 @@ const createFakeFetch = () => {
41
42
  : rawPath;
42
43
  const bodyText = typeof init.body === "string" ? init.body : undefined;
43
44
  const body = bodyText !== undefined ? JSON.parse(bodyText) : undefined;
44
- calls.push({ method, path, body });
45
+ calls.push({ method, path, body, headers: init.headers });
45
46
  const handler = routes.get(`${method} ${path}`);
46
47
  if (handler === undefined) {
47
48
  throw new Error(`Unhandled fake fetch route: ${method} ${path}`);
@@ -205,6 +206,13 @@ const createHarness = (overrides) => {
205
206
  };
206
207
  return harness;
207
208
  };
209
+ const transactionSecretHeaders = (harness) => harness.fetch.calls
210
+ .filter((call) => call.path.startsWith("/v1/auth/transactions/"))
211
+ .map((call) => new Headers(call.headers).get("x-transaction-secret"));
212
+ const createdTransactionState = (harness) => {
213
+ const createCall = harness.fetch.calls.find((call) => call.path === "/v1/auth/transactions");
214
+ return createCall?.body?.["state"];
215
+ };
208
216
  const seedRefreshRecord = async (harness, patch) => {
209
217
  const record = {
210
218
  refreshToken: "seeded-refresh-token",
@@ -230,6 +238,7 @@ describe("signInWithPasskey", () => {
230
238
  transaction_id: fakeId("txn"),
231
239
  expires_at: "2026-08-02T08:10:00Z",
232
240
  available_methods: ["passkey", "email_otp"],
241
+ transaction_secret: TRANSACTION_SECRET,
233
242
  }));
234
243
  harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/passkeys/authentication/options`, () => jsonResponse(200, {
235
244
  challenge: "challenge-value",
@@ -255,6 +264,11 @@ describe("signInWithPasskey", () => {
255
264
  const result = await client.signInWithPasskey();
256
265
  expect(result.session.userId).toBe(userId);
257
266
  expect(result.session.hasRefreshToken).toBe(true);
267
+ expect(transactionSecretHeaders(harness)).toEqual([
268
+ TRANSACTION_SECRET,
269
+ TRANSACTION_SECRET,
270
+ TRANSACTION_SECRET,
271
+ ]);
258
272
  const createCall = harness.fetch.calls.find((c) => c.method === "POST" && c.path === "/v1/auth/transactions");
259
273
  expect(createCall).toBeDefined();
260
274
  const createBody = createCall?.body;
@@ -292,6 +306,7 @@ describe("signInWithPasskey — passkey capability", () => {
292
306
  transaction_id: fakeId("txn"),
293
307
  expires_at: "2026-08-02T08:10:00Z",
294
308
  available_methods: ["passkey"],
309
+ transaction_secret: TRANSACTION_SECRET,
295
310
  }));
296
311
  harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/passkeys/authentication/options`, () => jsonResponse(200, {
297
312
  challenge: "challenge-value",
@@ -314,6 +329,7 @@ describe("signInWithPasskey — passkey capability", () => {
314
329
  transaction_id: fakeId("txn"),
315
330
  expires_at: "2026-08-02T08:10:00Z",
316
331
  available_methods: ["passkey"],
332
+ transaction_secret: TRANSACTION_SECRET,
317
333
  }));
318
334
  harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/passkeys/authentication/options`, () => jsonResponse(200, {
319
335
  challenge: "challenge-value",
@@ -332,6 +348,7 @@ describe("signInWithPasskey — passkey capability", () => {
332
348
  transaction_id: fakeId("txn"),
333
349
  expires_at: "2026-08-02T08:10:00Z",
334
350
  available_methods: ["passkey"],
351
+ transaction_secret: TRANSACTION_SECRET,
335
352
  }));
336
353
  harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/passkeys/authentication/options`, () => jsonResponse(200, {
337
354
  challenge: "challenge-value",
@@ -350,6 +367,7 @@ describe("signInWithPasskey — passkey capability", () => {
350
367
  transaction_id: fakeId("txn"),
351
368
  expires_at: "2026-08-02T08:10:00Z",
352
369
  available_methods: ["passkey"],
370
+ transaction_secret: TRANSACTION_SECRET,
353
371
  }));
354
372
  harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/passkeys/authentication/options`, () => jsonResponse(200, {
355
373
  challenge: "challenge-value",
@@ -437,6 +455,7 @@ describe("normalizePasskeyException", () => {
437
455
  transaction_id: fakeId("txn"),
438
456
  expires_at: "2026-08-02T08:10:00Z",
439
457
  available_methods: ["passkey"],
458
+ transaction_secret: TRANSACTION_SECRET,
440
459
  }));
441
460
  harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/passkeys/authentication/options`, () => jsonResponse(200, {
442
461
  challenge: "challenge-value",
@@ -455,6 +474,7 @@ describe("passkey ceremony guard", () => {
455
474
  transaction_id: fakeId("txn"),
456
475
  expires_at: "2026-08-02T08:10:00Z",
457
476
  available_methods: ["passkey"],
477
+ transaction_secret: TRANSACTION_SECRET,
458
478
  }));
459
479
  harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/passkeys/authentication/options`, () => jsonResponse(200, {
460
480
  challenge: "challenge-value",
@@ -548,6 +568,7 @@ describe("sendEmailCode / verifyEmailCode", () => {
548
568
  transaction_id: fakeId("txn"),
549
569
  expires_at: "2026-08-02T08:10:00Z",
550
570
  available_methods: ["email_otp"],
571
+ transaction_secret: TRANSACTION_SECRET,
551
572
  }));
552
573
  harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/email/start`, (init) => {
553
574
  const body = JSON.parse(String(init.body));
@@ -574,13 +595,19 @@ describe("sendEmailCode / verifyEmailCode", () => {
574
595
  const client = createReactNativeAuthClient(harness.config);
575
596
  const challenge = await client.sendEmailCode({ email: "user@example.com" });
576
597
  expect(challenge.challengeId).toBe("chal_1");
598
+ const resumedClient = createReactNativeAuthClient(harness.config);
577
599
  const createCall = harness.fetch.calls.find((c) => c.path === "/v1/auth/transactions");
578
600
  capturedState = (createCall?.body)["state"];
579
- const result = await client.verifyEmailCode({
601
+ const result = await resumedClient.verifyEmailCode({
580
602
  challengeId: challenge.challengeId,
581
603
  code: "123456",
582
604
  });
583
605
  expect(result.session.userId).toBe(userId);
606
+ expect(transactionSecretHeaders(harness)).toEqual([
607
+ TRANSACTION_SECRET,
608
+ TRANSACTION_SECRET,
609
+ TRANSACTION_SECRET,
610
+ ]);
584
611
  // design.md §21.6: only the refresh key was ever written, and its value
585
612
  // never contains an access token.
586
613
  expect([...harness.secureStore.store.keys()]).toEqual([
@@ -620,6 +647,7 @@ describe("sendEmailCode / verifyEmailCode", () => {
620
647
  transaction_id: fakeId("txn"),
621
648
  expires_at: "2026-08-02T08:10:00Z",
622
649
  available_methods: ["email_otp"],
650
+ transaction_secret: TRANSACTION_SECRET,
623
651
  }));
624
652
  harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/email/start`, () => jsonResponse(200, { nonsense: true }));
625
653
  const client = createReactNativeAuthClient(harness.config);
@@ -632,90 +660,96 @@ describe("sendEmailCode / verifyEmailCode", () => {
632
660
  // Social sign-in: system browser only, callback state pre-check
633
661
  // ---------------------------------------------------------------------------
634
662
  describe("signInWithSocial", () => {
635
- test("opens the system browser (never a WebView) and completes the transaction on success", async () => {
663
+ test("exchanges the authorization code from the system-browser callback", async () => {
636
664
  const harness = createHarness();
637
665
  const userId = fakeId("usr");
666
+ const authorizationCode = fakeId("ac");
638
667
  harness.fetch.on("POST", "/v1/auth/transactions", () => jsonResponse(200, {
639
668
  transaction_id: fakeId("txn"),
640
669
  expires_at: "2026-08-02T08:10:00Z",
641
670
  available_methods: ["google"],
671
+ transaction_secret: TRANSACTION_SECRET,
642
672
  }));
643
673
  harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/social/google/start`, () => jsonResponse(200, { authorization_url: "https://accounts.google.com/authorize?x=1" }));
644
- // Echoes back whatever state the transaction-create call just sent, exactly
645
- // like the real server would (design.md §16.1's MAC-verified round trip) —
646
- // this test does not need to predict the fake crypto's exact output.
647
- harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/complete`, () => {
648
- const createCall = harness.fetch.calls.find((c) => c.method === "POST" && c.path === "/v1/auth/transactions");
649
- const state = createCall?.body?.["state"];
650
- return jsonResponse(200, {
651
- authorization_code: fakeId("ac"),
652
- state,
653
- redirect_uri: REDIRECT_URI,
654
- });
674
+ harness.fetch.on("POST", TOKEN_PATH, (init) => {
675
+ const body = JSON.parse(String(init.body));
676
+ expect(body["grant_type"]).toBe("authorization_code");
677
+ expect(body["code"]).toBe(authorizationCode);
678
+ expect(body["redirect_uri"]).toBe(REDIRECT_URI);
679
+ expect(body["client_id"]).toBe(CLIENT_ID);
680
+ expect(typeof body["code_verifier"]).toBe("string");
681
+ return jsonResponse(200, tokenResponseBody(userId));
655
682
  });
656
- harness.fetch.on("POST", TOKEN_PATH, () => jsonResponse(200, tokenResponseBody(userId)));
657
683
  const openAuthSessionAsync = vi.fn((_url, redirectUrl) => Promise.resolve({
658
684
  type: "success",
659
- // The callback URL carries back the SAME state the client generated,
660
- // matching how the platform's own social callback redirect behaves.
661
- url: `${redirectUrl}?state=${harness.fetch.calls.find((c) => c.path === "/v1/auth/transactions")?.body?.["state"] ?? ""}`,
685
+ url: `${redirectUrl}?code=${authorizationCode}&state=${createdTransactionState(harness)}`,
662
686
  }));
663
687
  harness.browser = { openAuthSessionAsync };
664
688
  const client = createReactNativeAuthClient(harness.config);
665
689
  const result = await client.signInWithSocial({ provider: "google" });
666
690
  expect(result.session.userId).toBe(userId);
691
+ expect(transactionSecretHeaders(harness)).toEqual([TRANSACTION_SECRET]);
667
692
  expect(openAuthSessionAsync).toHaveBeenCalledWith("https://accounts.google.com/authorize?x=1", REDIRECT_URI);
693
+ expect(harness.fetch.calls.some((call) => call.path.endsWith("/complete"))).toBe(false);
668
694
  });
669
- test("a mismatched state on the callback URL itself rejects before calling complete", async () => {
695
+ test("a mismatched callback state is rejected without completing the transaction", async () => {
670
696
  const harness = createHarness();
671
697
  harness.fetch.on("POST", "/v1/auth/transactions", () => jsonResponse(200, {
672
698
  transaction_id: fakeId("txn"),
673
699
  expires_at: "2026-08-02T08:10:00Z",
674
700
  available_methods: ["google"],
701
+ transaction_secret: TRANSACTION_SECRET,
675
702
  }));
676
703
  harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/social/google/start`, () => jsonResponse(200, { authorization_url: "https://accounts.google.com/authorize?x=1" }));
677
- let completeCalled = false;
678
- harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/complete`, () => {
679
- completeCalled = true;
680
- return jsonResponse(200, {
681
- authorization_code: fakeId("ac"),
682
- state: "whatever",
683
- redirect_uri: REDIRECT_URI,
684
- });
685
- });
686
704
  harness.browser = createFakeBrowser({
687
705
  type: "success",
688
- url: `${REDIRECT_URI}?state=totally-wrong-state`,
706
+ url: `${REDIRECT_URI}?code=${fakeId("ac")}&state=totally-wrong-state`,
689
707
  });
690
708
  const client = createReactNativeAuthClient(harness.config);
691
709
  await expect(client.signInWithSocial({ provider: "google" })).rejects.toMatchObject({
692
710
  code: { type: "state_mismatch" },
693
711
  });
694
- expect(completeCalled).toBe(false);
712
+ expect(harness.fetch.calls.some((call) => call.path.endsWith("/complete"))).toBe(false);
695
713
  });
696
- test("a success callback without state is rejected before calling complete", async () => {
714
+ test("a callback without state is rejected without completing the transaction", async () => {
697
715
  const harness = createHarness();
698
716
  harness.fetch.on("POST", "/v1/auth/transactions", () => jsonResponse(200, {
699
717
  transaction_id: fakeId("txn"),
700
718
  expires_at: "2026-08-02T08:10:00Z",
701
719
  available_methods: ["google"],
720
+ transaction_secret: TRANSACTION_SECRET,
702
721
  }));
703
722
  harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/social/google/start`, () => jsonResponse(200, { authorization_url: "https://accounts.google.com/authorize?x=1" }));
704
- let completeCalled = false;
705
- harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/complete`, () => {
706
- completeCalled = true;
707
- return jsonResponse(200, {
708
- authorization_code: fakeId("ac"),
709
- state: "whatever",
710
- redirect_uri: REDIRECT_URI,
711
- });
723
+ harness.browser = createFakeBrowser({
724
+ type: "success",
725
+ url: `${REDIRECT_URI}?code=${fakeId("ac")}`,
726
+ });
727
+ const client = createReactNativeAuthClient(harness.config);
728
+ await expect(client.signInWithSocial({ provider: "google" })).rejects.toMatchObject({
729
+ code: { type: "state_mismatch" },
712
730
  });
713
- harness.browser = createFakeBrowser({ type: "success", url: REDIRECT_URI });
731
+ expect(harness.fetch.calls.some((call) => call.path.endsWith("/complete"))).toBe(false);
732
+ });
733
+ test("a callback without code is rejected without completing the transaction", async () => {
734
+ const harness = createHarness();
735
+ harness.fetch.on("POST", "/v1/auth/transactions", () => jsonResponse(200, {
736
+ transaction_id: fakeId("txn"),
737
+ expires_at: "2026-08-02T08:10:00Z",
738
+ available_methods: ["google"],
739
+ transaction_secret: TRANSACTION_SECRET,
740
+ }));
741
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/social/google/start`, () => jsonResponse(200, { authorization_url: "https://accounts.google.com/authorize?x=1" }));
742
+ harness.browser = {
743
+ openAuthSessionAsync: (_url, redirectUrl) => Promise.resolve({
744
+ type: "success",
745
+ url: `${redirectUrl}?state=${createdTransactionState(harness)}`,
746
+ }),
747
+ };
714
748
  const client = createReactNativeAuthClient(harness.config);
715
749
  await expect(client.signInWithSocial({ provider: "google" })).rejects.toMatchObject({
716
750
  code: { type: "state_mismatch" },
717
751
  });
718
- expect(completeCalled).toBe(false);
752
+ expect(harness.fetch.calls.some((call) => call.path.endsWith("/complete"))).toBe(false);
719
753
  });
720
754
  test("a cancelled/dismissed browser session rejects as social_cancelled", async () => {
721
755
  const harness = createHarness();
@@ -723,6 +757,7 @@ describe("signInWithSocial", () => {
723
757
  transaction_id: fakeId("txn"),
724
758
  expires_at: "2026-08-02T08:10:00Z",
725
759
  available_methods: ["google"],
760
+ transaction_secret: TRANSACTION_SECRET,
726
761
  }));
727
762
  harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/social/google/start`, () => jsonResponse(200, { authorization_url: "https://accounts.google.com/authorize?x=1" }));
728
763
  harness.browser = createFakeBrowser({ type: "dismiss" });
package/dist/http.d.ts CHANGED
@@ -28,6 +28,7 @@ export interface JsonRequest {
28
28
  readonly url: string;
29
29
  readonly body?: unknown;
30
30
  readonly accessToken?: string;
31
+ readonly transactionSecret?: string;
31
32
  }
32
33
  export declare const isOAuthErrorCode: (value: string) => value is OAuthErrorCode;
33
34
  /**
package/dist/http.js CHANGED
@@ -37,6 +37,9 @@ export const requestJson = async (fetchPort, request, schema) => {
37
37
  ...(request.accessToken !== undefined
38
38
  ? { authorization: `Bearer ${request.accessToken}` }
39
39
  : {}),
40
+ ...(request.transactionSecret !== undefined
41
+ ? { "x-transaction-secret": request.transactionSecret }
42
+ : {}),
40
43
  };
41
44
  const responseOutcome = await fetchPort(request.url, {
42
45
  method: request.method,
@@ -5,8 +5,8 @@
5
5
  * - refresh token
6
6
  * - token family id
7
7
  * - minimal session metadata (user id, scope, client id, timestamps)
8
- * - transient PKCE transaction data (verifier/state/transaction id), cleared
9
- * once the transaction is consumed or abandoned
8
+ * - transient PKCE transaction data (verifier/state/transaction id/transaction
9
+ * secret), cleared once the transaction is consumed or abandoned
10
10
  *
11
11
  * NEVER persisted: access token, full user profile, provider access tokens,
12
12
  * OTP codes. The access token lives in the client's in-memory closure only
@@ -42,6 +42,7 @@ export interface PersistedRefreshRecord {
42
42
  /** Transient PKCE state for an in-flight auth transaction (design.md §21.6, §16.1, §20.6). */
43
43
  export interface PersistedPendingTransaction {
44
44
  readonly transactionId: string;
45
+ readonly transactionSecret: string;
45
46
  readonly state: string;
46
47
  readonly codeVerifier: string;
47
48
  readonly redirectUri: string;
@@ -31,9 +31,11 @@ export const parsePersistedRefreshRecord = (value) => {
31
31
  export const parsePersistedPendingTransaction = (value) => {
32
32
  if (!isRecord(value))
33
33
  return null;
34
- const { transactionId, state, codeVerifier, redirectUri, createdAt, challengeId } = value;
34
+ const { transactionId, transactionSecret, state, codeVerifier, redirectUri, createdAt, challengeId, } = value;
35
35
  if (typeof transactionId !== "string" || transactionId.length === 0)
36
36
  return null;
37
+ if (typeof transactionSecret !== "string" || transactionSecret.length === 0)
38
+ return null;
37
39
  if (typeof state !== "string" || state.length === 0)
38
40
  return null;
39
41
  if (typeof codeVerifier !== "string" || codeVerifier.length === 0)
@@ -46,6 +48,7 @@ export const parsePersistedPendingTransaction = (value) => {
46
48
  return null;
47
49
  return {
48
50
  transactionId,
51
+ transactionSecret,
49
52
  state,
50
53
  codeVerifier,
51
54
  redirectUri,
@@ -46,6 +46,7 @@ describe("parsePersistedRefreshRecord", () => {
46
46
  });
47
47
  const VALID_PENDING = {
48
48
  transactionId: "txn_abc",
49
+ transactionSecret: "transaction-secret",
49
50
  state: "state-value",
50
51
  codeVerifier: "verifier-value",
51
52
  redirectUri: "com.customer.app:/oauth/callback",
@@ -62,6 +63,10 @@ describe("parsePersistedPendingTransaction", () => {
62
63
  test("rejects a record whose challengeId is the wrong type", () => {
63
64
  expect(parsePersistedPendingTransaction({ ...VALID_PENDING, challengeId: 123 })).toBeNull();
64
65
  });
66
+ test("rejects a pending transaction without its secret", () => {
67
+ const { transactionSecret: _transactionSecret, ...rest } = VALID_PENDING;
68
+ expect(parsePersistedPendingTransaction(rest)).toBeNull();
69
+ });
65
70
  test("rejects a record missing a required field", () => {
66
71
  const { state: _state, ...rest } = VALID_PENDING;
67
72
  expect(parsePersistedPendingTransaction(rest)).toBeNull();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smartcrab/react-native",
3
- "version": "0.2.1-next-20261009084044",
3
+ "version": "0.3.0",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -34,7 +34,7 @@
34
34
  "access": "public"
35
35
  },
36
36
  "dependencies": {
37
- "@smartcrab/contracts-public": "0.2.1-next-20261009084044"
37
+ "@smartcrab/contracts-public": "0.3.0"
38
38
  },
39
39
  "peerDependencies": {
40
40
  "react": ">=19",
@@ -22,6 +22,7 @@ const ENVIRONMENT_ID = "env_abcdefghijklmnopqrstuvwxyzabcdef";
22
22
  const ISSUER = `https://id.example-auth.com/e/${ENVIRONMENT_ID}`;
23
23
  const CLIENT_ID = fakeId("cli");
24
24
  const REDIRECT_URI = "com.customer.app:/oauth/callback";
25
+ const TRANSACTION_SECRET = "s".repeat(43);
25
26
  /** design.md §15.1: OAuth2 endpoints hang off the issuer verbatim, `/e/<environmentId>` path included. */
26
27
  const TOKEN_PATH = `/e/${ENVIRONMENT_ID}/oauth2/token`;
27
28
  const REVOKE_PATH = `/e/${ENVIRONMENT_ID}/oauth2/revoke`;
@@ -48,12 +49,22 @@ type RouteHandler = (init: RequestInit) => Response | Promise<Response>;
48
49
 
49
50
  interface FakeFetch {
50
51
  readonly fetchPort: (url: string, init: RequestInit) => Promise<Response>;
51
- readonly calls: { readonly method: string; readonly path: string; readonly body: unknown }[];
52
+ readonly calls: {
53
+ readonly method: string;
54
+ readonly path: string;
55
+ readonly body: unknown;
56
+ readonly headers: RequestInit["headers"];
57
+ }[];
52
58
  on(method: string, path: string, handler: RouteHandler): void;
53
59
  }
54
60
 
55
61
  const createFakeFetch = (): FakeFetch => {
56
- const calls: { method: string; path: string; body: unknown }[] = [];
62
+ const calls: {
63
+ method: string;
64
+ path: string;
65
+ body: unknown;
66
+ headers: RequestInit["headers"];
67
+ }[] = [];
57
68
  const routes = new Map<string, RouteHandler>();
58
69
  return {
59
70
  calls,
@@ -67,7 +78,7 @@ const createFakeFetch = (): FakeFetch => {
67
78
  : rawPath;
68
79
  const bodyText = typeof init.body === "string" ? init.body : undefined;
69
80
  const body: unknown = bodyText !== undefined ? JSON.parse(bodyText) : undefined;
70
- calls.push({ method, path, body });
81
+ calls.push({ method, path, body, headers: init.headers });
71
82
  const handler = routes.get(`${method} ${path}`);
72
83
  if (handler === undefined) {
73
84
  throw new Error(`Unhandled fake fetch route: ${method} ${path}`);
@@ -284,6 +295,16 @@ const createHarness = (overrides?: {
284
295
  return harness;
285
296
  };
286
297
 
298
+ const transactionSecretHeaders = (harness: TestHarness): (string | null)[] =>
299
+ harness.fetch.calls
300
+ .filter((call) => call.path.startsWith("/v1/auth/transactions/"))
301
+ .map((call) => new Headers(call.headers).get("x-transaction-secret"));
302
+
303
+ const createdTransactionState = (harness: TestHarness): string => {
304
+ const createCall = harness.fetch.calls.find((call) => call.path === "/v1/auth/transactions");
305
+ return (createCall?.body as Record<string, unknown> | undefined)?.["state"] as string;
306
+ };
307
+
287
308
  const seedRefreshRecord = async (
288
309
  harness: TestHarness,
289
310
  patch?: Partial<PersistedRefreshRecord>,
@@ -319,6 +340,7 @@ describe("signInWithPasskey", () => {
319
340
  transaction_id: fakeId("txn"),
320
341
  expires_at: "2026-08-02T08:10:00Z",
321
342
  available_methods: ["passkey", "email_otp"],
343
+ transaction_secret: TRANSACTION_SECRET,
322
344
  }),
323
345
  );
324
346
  harness.fetch.on(
@@ -357,6 +379,11 @@ describe("signInWithPasskey", () => {
357
379
  const result = await client.signInWithPasskey();
358
380
  expect(result.session.userId).toBe(userId);
359
381
  expect(result.session.hasRefreshToken).toBe(true);
382
+ expect(transactionSecretHeaders(harness)).toEqual([
383
+ TRANSACTION_SECRET,
384
+ TRANSACTION_SECRET,
385
+ TRANSACTION_SECRET,
386
+ ]);
360
387
 
361
388
  const createCall = harness.fetch.calls.find(
362
389
  (c) => c.method === "POST" && c.path === "/v1/auth/transactions",
@@ -402,6 +429,7 @@ describe("signInWithPasskey — passkey capability", () => {
402
429
  transaction_id: fakeId("txn"),
403
430
  expires_at: "2026-08-02T08:10:00Z",
404
431
  available_methods: ["passkey"],
432
+ transaction_secret: TRANSACTION_SECRET,
405
433
  }),
406
434
  );
407
435
  harness.fetch.on(
@@ -432,6 +460,7 @@ describe("signInWithPasskey — passkey capability", () => {
432
460
  transaction_id: fakeId("txn"),
433
461
  expires_at: "2026-08-02T08:10:00Z",
434
462
  available_methods: ["passkey"],
463
+ transaction_secret: TRANSACTION_SECRET,
435
464
  }),
436
465
  );
437
466
  harness.fetch.on(
@@ -458,6 +487,7 @@ describe("signInWithPasskey — passkey capability", () => {
458
487
  transaction_id: fakeId("txn"),
459
488
  expires_at: "2026-08-02T08:10:00Z",
460
489
  available_methods: ["passkey"],
490
+ transaction_secret: TRANSACTION_SECRET,
461
491
  }),
462
492
  );
463
493
  harness.fetch.on(
@@ -484,6 +514,7 @@ describe("signInWithPasskey — passkey capability", () => {
484
514
  transaction_id: fakeId("txn"),
485
515
  expires_at: "2026-08-02T08:10:00Z",
486
516
  available_methods: ["passkey"],
517
+ transaction_secret: TRANSACTION_SECRET,
487
518
  }),
488
519
  );
489
520
  harness.fetch.on(
@@ -583,6 +614,7 @@ describe("normalizePasskeyException", () => {
583
614
  transaction_id: fakeId("txn"),
584
615
  expires_at: "2026-08-02T08:10:00Z",
585
616
  available_methods: ["passkey"],
617
+ transaction_secret: TRANSACTION_SECRET,
586
618
  }),
587
619
  );
588
620
  harness.fetch.on(
@@ -609,6 +641,7 @@ describe("passkey ceremony guard", () => {
609
641
  transaction_id: fakeId("txn"),
610
642
  expires_at: "2026-08-02T08:10:00Z",
611
643
  available_methods: ["passkey"],
644
+ transaction_secret: TRANSACTION_SECRET,
612
645
  }),
613
646
  );
614
647
  harness.fetch.on(
@@ -731,6 +764,7 @@ describe("sendEmailCode / verifyEmailCode", () => {
731
764
  transaction_id: fakeId("txn"),
732
765
  expires_at: "2026-08-02T08:10:00Z",
733
766
  available_methods: ["email_otp"],
767
+ transaction_secret: TRANSACTION_SECRET,
734
768
  }),
735
769
  );
736
770
  harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/email/start`, (init) => {
@@ -762,14 +796,20 @@ describe("sendEmailCode / verifyEmailCode", () => {
762
796
 
763
797
  const challenge = await client.sendEmailCode({ email: "user@example.com" });
764
798
  expect(challenge.challengeId).toBe("chal_1");
799
+ const resumedClient = createReactNativeAuthClient(harness.config);
765
800
  const createCall = harness.fetch.calls.find((c) => c.path === "/v1/auth/transactions");
766
801
  capturedState = (createCall?.body as Record<string, unknown>)["state"] as string;
767
802
 
768
- const result = await client.verifyEmailCode({
803
+ const result = await resumedClient.verifyEmailCode({
769
804
  challengeId: challenge.challengeId,
770
805
  code: "123456",
771
806
  });
772
807
  expect(result.session.userId).toBe(userId);
808
+ expect(transactionSecretHeaders(harness)).toEqual([
809
+ TRANSACTION_SECRET,
810
+ TRANSACTION_SECRET,
811
+ TRANSACTION_SECRET,
812
+ ]);
773
813
 
774
814
  // design.md §21.6: only the refresh key was ever written, and its value
775
815
  // never contains an access token.
@@ -823,6 +863,7 @@ describe("sendEmailCode / verifyEmailCode", () => {
823
863
  transaction_id: fakeId("txn"),
824
864
  expires_at: "2026-08-02T08:10:00Z",
825
865
  available_methods: ["email_otp"],
866
+ transaction_secret: TRANSACTION_SECRET,
826
867
  }),
827
868
  );
828
869
  harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/email/start`, () =>
@@ -840,41 +881,35 @@ describe("sendEmailCode / verifyEmailCode", () => {
840
881
  // ---------------------------------------------------------------------------
841
882
 
842
883
  describe("signInWithSocial", () => {
843
- test("opens the system browser (never a WebView) and completes the transaction on success", async () => {
884
+ test("exchanges the authorization code from the system-browser callback", async () => {
844
885
  const harness = createHarness();
845
886
  const userId = fakeId("usr");
887
+ const authorizationCode = fakeId("ac");
846
888
  harness.fetch.on("POST", "/v1/auth/transactions", () =>
847
889
  jsonResponse(200, {
848
890
  transaction_id: fakeId("txn"),
849
891
  expires_at: "2026-08-02T08:10:00Z",
850
892
  available_methods: ["google"],
893
+ transaction_secret: TRANSACTION_SECRET,
851
894
  }),
852
895
  );
853
896
  harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/social/google/start`, () =>
854
897
  jsonResponse(200, { authorization_url: "https://accounts.google.com/authorize?x=1" }),
855
898
  );
856
- // Echoes back whatever state the transaction-create call just sent, exactly
857
- // like the real server would (design.md §16.1's MAC-verified round trip) —
858
- // this test does not need to predict the fake crypto's exact output.
859
- harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/complete`, () => {
860
- const createCall = harness.fetch.calls.find(
861
- (c) => c.method === "POST" && c.path === "/v1/auth/transactions",
862
- );
863
- const state = (createCall?.body as Record<string, unknown> | undefined)?.["state"];
864
- return jsonResponse(200, {
865
- authorization_code: fakeId("ac"),
866
- state,
867
- redirect_uri: REDIRECT_URI,
868
- });
899
+ harness.fetch.on("POST", TOKEN_PATH, (init) => {
900
+ const body = JSON.parse(String(init.body)) as Record<string, unknown>;
901
+ expect(body["grant_type"]).toBe("authorization_code");
902
+ expect(body["code"]).toBe(authorizationCode);
903
+ expect(body["redirect_uri"]).toBe(REDIRECT_URI);
904
+ expect(body["client_id"]).toBe(CLIENT_ID);
905
+ expect(typeof body["code_verifier"]).toBe("string");
906
+ return jsonResponse(200, tokenResponseBody(userId));
869
907
  });
870
- harness.fetch.on("POST", TOKEN_PATH, () => jsonResponse(200, tokenResponseBody(userId)));
871
908
 
872
909
  const openAuthSessionAsync = vi.fn((_url: string, redirectUrl: string) =>
873
910
  Promise.resolve<WebBrowserAuthResult>({
874
911
  type: "success",
875
- // The callback URL carries back the SAME state the client generated,
876
- // matching how the platform's own social callback redirect behaves.
877
- url: `${redirectUrl}?state=${(harness.fetch.calls.find((c) => c.path === "/v1/auth/transactions")?.body as Record<string, unknown> | undefined)?.["state"] ?? ""}`,
912
+ url: `${redirectUrl}?code=${authorizationCode}&state=${createdTransactionState(harness)}`,
878
913
  }),
879
914
  );
880
915
  harness.browser = { openAuthSessionAsync };
@@ -882,73 +917,90 @@ describe("signInWithSocial", () => {
882
917
  const client = createReactNativeAuthClient(harness.config);
883
918
  const result = await client.signInWithSocial({ provider: "google" });
884
919
  expect(result.session.userId).toBe(userId);
920
+ expect(transactionSecretHeaders(harness)).toEqual([TRANSACTION_SECRET]);
885
921
  expect(openAuthSessionAsync).toHaveBeenCalledWith(
886
922
  "https://accounts.google.com/authorize?x=1",
887
923
  REDIRECT_URI,
888
924
  );
925
+ expect(harness.fetch.calls.some((call) => call.path.endsWith("/complete"))).toBe(false);
889
926
  });
890
927
 
891
- test("a mismatched state on the callback URL itself rejects before calling complete", async () => {
928
+ test("a mismatched callback state is rejected without completing the transaction", async () => {
892
929
  const harness = createHarness();
893
930
  harness.fetch.on("POST", "/v1/auth/transactions", () =>
894
931
  jsonResponse(200, {
895
932
  transaction_id: fakeId("txn"),
896
933
  expires_at: "2026-08-02T08:10:00Z",
897
934
  available_methods: ["google"],
935
+ transaction_secret: TRANSACTION_SECRET,
898
936
  }),
899
937
  );
900
938
  harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/social/google/start`, () =>
901
939
  jsonResponse(200, { authorization_url: "https://accounts.google.com/authorize?x=1" }),
902
940
  );
903
- let completeCalled = false;
904
- harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/complete`, () => {
905
- completeCalled = true;
906
- return jsonResponse(200, {
907
- authorization_code: fakeId("ac"),
908
- state: "whatever",
909
- redirect_uri: REDIRECT_URI,
910
- });
911
- });
912
941
  harness.browser = createFakeBrowser({
913
942
  type: "success",
914
- url: `${REDIRECT_URI}?state=totally-wrong-state`,
943
+ url: `${REDIRECT_URI}?code=${fakeId("ac")}&state=totally-wrong-state`,
915
944
  });
916
945
 
917
946
  const client = createReactNativeAuthClient(harness.config);
918
947
  await expect(client.signInWithSocial({ provider: "google" })).rejects.toMatchObject({
919
948
  code: { type: "state_mismatch" },
920
949
  });
921
- expect(completeCalled).toBe(false);
950
+ expect(harness.fetch.calls.some((call) => call.path.endsWith("/complete"))).toBe(false);
922
951
  });
923
952
 
924
- test("a success callback without state is rejected before calling complete", async () => {
953
+ test("a callback without state is rejected without completing the transaction", async () => {
925
954
  const harness = createHarness();
926
955
  harness.fetch.on("POST", "/v1/auth/transactions", () =>
927
956
  jsonResponse(200, {
928
957
  transaction_id: fakeId("txn"),
929
958
  expires_at: "2026-08-02T08:10:00Z",
930
959
  available_methods: ["google"],
960
+ transaction_secret: TRANSACTION_SECRET,
931
961
  }),
932
962
  );
933
963
  harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/social/google/start`, () =>
934
964
  jsonResponse(200, { authorization_url: "https://accounts.google.com/authorize?x=1" }),
935
965
  );
936
- let completeCalled = false;
937
- harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/complete`, () => {
938
- completeCalled = true;
939
- return jsonResponse(200, {
940
- authorization_code: fakeId("ac"),
941
- state: "whatever",
942
- redirect_uri: REDIRECT_URI,
943
- });
966
+ harness.browser = createFakeBrowser({
967
+ type: "success",
968
+ url: `${REDIRECT_URI}?code=${fakeId("ac")}`,
969
+ });
970
+
971
+ const client = createReactNativeAuthClient(harness.config);
972
+ await expect(client.signInWithSocial({ provider: "google" })).rejects.toMatchObject({
973
+ code: { type: "state_mismatch" },
944
974
  });
945
- harness.browser = createFakeBrowser({ type: "success", url: REDIRECT_URI });
975
+ expect(harness.fetch.calls.some((call) => call.path.endsWith("/complete"))).toBe(false);
976
+ });
977
+
978
+ test("a callback without code is rejected without completing the transaction", async () => {
979
+ const harness = createHarness();
980
+ harness.fetch.on("POST", "/v1/auth/transactions", () =>
981
+ jsonResponse(200, {
982
+ transaction_id: fakeId("txn"),
983
+ expires_at: "2026-08-02T08:10:00Z",
984
+ available_methods: ["google"],
985
+ transaction_secret: TRANSACTION_SECRET,
986
+ }),
987
+ );
988
+ harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/social/google/start`, () =>
989
+ jsonResponse(200, { authorization_url: "https://accounts.google.com/authorize?x=1" }),
990
+ );
991
+ harness.browser = {
992
+ openAuthSessionAsync: (_url, redirectUrl) =>
993
+ Promise.resolve<WebBrowserAuthResult>({
994
+ type: "success",
995
+ url: `${redirectUrl}?state=${createdTransactionState(harness)}`,
996
+ }),
997
+ };
946
998
 
947
999
  const client = createReactNativeAuthClient(harness.config);
948
1000
  await expect(client.signInWithSocial({ provider: "google" })).rejects.toMatchObject({
949
1001
  code: { type: "state_mismatch" },
950
1002
  });
951
- expect(completeCalled).toBe(false);
1003
+ expect(harness.fetch.calls.some((call) => call.path.endsWith("/complete"))).toBe(false);
952
1004
  });
953
1005
 
954
1006
  test("a cancelled/dismissed browser session rejects as social_cancelled", async () => {
@@ -958,6 +1010,7 @@ describe("signInWithSocial", () => {
958
1010
  transaction_id: fakeId("txn"),
959
1011
  expires_at: "2026-08-02T08:10:00Z",
960
1012
  available_methods: ["google"],
1013
+ transaction_secret: TRANSACTION_SECRET,
961
1014
  }),
962
1015
  );
963
1016
  harness.fetch.on("POST", `/v1/auth/transactions/${fakeId("txn")}/social/google/start`, () =>
package/src/client.ts CHANGED
@@ -576,6 +576,7 @@ const withAccessToken = async <T>(
576
576
 
577
577
  interface BegunTransaction {
578
578
  readonly transactionId: string;
579
+ readonly transactionSecret: string;
579
580
  readonly pkce: PkcePair;
580
581
  readonly state: string;
581
582
  }
@@ -601,13 +602,41 @@ const beginTransaction = async (
601
602
  transactionCreateResponseSchema,
602
603
  );
603
604
  if (!outcome.ok) return outcome;
604
- return ok({ transactionId: outcome.value.transaction_id, pkce, state });
605
+ return ok({
606
+ transactionId: outcome.value.transaction_id,
607
+ transactionSecret: outcome.value.transaction_secret,
608
+ pkce,
609
+ state,
610
+ });
611
+ };
612
+
613
+ /** Exchanges an authorization code returned by completion or native social redirect. */
614
+ const exchangeAuthorizationCode = async (
615
+ ctx: InternalContext,
616
+ code: string,
617
+ expectedState: string,
618
+ callbackState: string,
619
+ codeVerifier: string,
620
+ ): Promise<Outcome<TokenResponse, ReactNativeAuthError>> => {
621
+ if (!constantTimeEqual(callbackState, expectedState)) return err({ type: "state_mismatch" });
622
+ const body: AuthorizationCodeGrantRequest = {
623
+ grant_type: "authorization_code",
624
+ code,
625
+ redirect_uri: ctx.config.redirectUri,
626
+ code_verifier: codeVerifier,
627
+ client_id: ctx.config.clientId,
628
+ };
629
+ return requestJson(
630
+ ctx.fetchPort,
631
+ { method: "POST", url: `${ctx.issuer}/oauth2/token`, body },
632
+ tokenResponseSchema,
633
+ );
605
634
  };
606
635
 
607
- /** `.../complete` + code exchange, shared by every sign-in path (design.md §16.3). */
608
636
  const completeAndExchange = async (
609
637
  ctx: InternalContext,
610
638
  transactionId: string,
639
+ transactionSecret: string,
611
640
  expectedState: string,
612
641
  codeVerifier: string,
613
642
  ): Promise<Outcome<TokenResponse, ReactNativeAuthError>> => {
@@ -617,24 +646,17 @@ const completeAndExchange = async (
617
646
  method: "POST",
618
647
  url: buildUrl(ctx.apiBaseUrl, `/v1/auth/transactions/${transactionId}/complete`),
619
648
  body: {},
649
+ transactionSecret,
620
650
  },
621
651
  transactionCompleteResponseSchema,
622
652
  );
623
653
  if (!completeOutcome.ok) return completeOutcome;
624
- if (!constantTimeEqual(completeOutcome.value.state, expectedState)) {
625
- return err({ type: "state_mismatch" });
626
- }
627
- const body: AuthorizationCodeGrantRequest = {
628
- grant_type: "authorization_code",
629
- code: completeOutcome.value.authorization_code,
630
- redirect_uri: ctx.config.redirectUri,
631
- code_verifier: codeVerifier,
632
- client_id: ctx.config.clientId,
633
- };
634
- return requestJson(
635
- ctx.fetchPort,
636
- { method: "POST", url: `${ctx.issuer}/oauth2/token`, body },
637
- tokenResponseSchema,
654
+ return exchangeAuthorizationCode(
655
+ ctx,
656
+ completeOutcome.value.authorization_code,
657
+ expectedState,
658
+ completeOutcome.value.state,
659
+ codeVerifier,
638
660
  );
639
661
  };
640
662
 
@@ -716,7 +738,7 @@ const runSignInWithPasskeyCeremony = async (
716
738
  ): Promise<Outcome<AuthResult, ReactNativeAuthError>> => {
717
739
  const txOutcome = await beginTransaction(ctx);
718
740
  if (!txOutcome.ok) return txOutcome;
719
- const { transactionId, pkce, state } = txOutcome.value;
741
+ const { transactionId, transactionSecret, pkce, state } = txOutcome.value;
720
742
 
721
743
  const optionsOutcome = await requestJson(
722
744
  ctx.fetchPort,
@@ -727,6 +749,7 @@ const runSignInWithPasskeyCeremony = async (
727
749
  `/v1/auth/transactions/${transactionId}/passkeys/authentication/options`,
728
750
  ),
729
751
  body: passkeyOptionsBody(ctx),
752
+ transactionSecret,
730
753
  },
731
754
  passkeyAuthenticationOptionsResponseSchema,
732
755
  );
@@ -744,12 +767,19 @@ const runSignInWithPasskeyCeremony = async (
744
767
  `/v1/auth/transactions/${transactionId}/passkeys/authentication/verify`,
745
768
  ),
746
769
  body: { credential: credentialOutcome.value },
770
+ transactionSecret,
747
771
  },
748
772
  passkeyAuthenticationVerifyResponseSchema,
749
773
  );
750
774
  if (!verifyOutcome.ok) return verifyOutcome;
751
775
 
752
- const tokenOutcome = await completeAndExchange(ctx, transactionId, state, pkce.verifier);
776
+ const tokenOutcome = await completeAndExchange(
777
+ ctx,
778
+ transactionId,
779
+ transactionSecret,
780
+ state,
781
+ pkce.verifier,
782
+ );
753
783
  if (!tokenOutcome.ok) return tokenOutcome;
754
784
 
755
785
  const sessionOutcome = await applySession(ctx, tokenOutcome.value, generateFamilyId(ctx));
@@ -808,7 +838,7 @@ const sendEmailCodeInternal = async (
808
838
  ): Promise<Outcome<EmailCodeChallenge, ReactNativeAuthError>> => {
809
839
  const txOutcome = await beginTransaction(ctx);
810
840
  if (!txOutcome.ok) return txOutcome;
811
- const { transactionId, pkce, state } = txOutcome.value;
841
+ const { transactionId, transactionSecret, pkce, state } = txOutcome.value;
812
842
 
813
843
  const startOutcome = await requestJson(
814
844
  ctx.fetchPort,
@@ -816,6 +846,7 @@ const sendEmailCodeInternal = async (
816
846
  method: "POST",
817
847
  url: buildUrl(ctx.apiBaseUrl, `/v1/auth/transactions/${transactionId}/email/start`),
818
848
  body: { email },
849
+ transactionSecret,
819
850
  },
820
851
  emailChallengeResponseSchema,
821
852
  );
@@ -823,6 +854,7 @@ const sendEmailCodeInternal = async (
823
854
 
824
855
  await savePendingTransaction(ctx, {
825
856
  transactionId,
857
+ transactionSecret,
826
858
  state,
827
859
  codeVerifier: pkce.verifier,
828
860
  redirectUri: ctx.config.redirectUri,
@@ -853,6 +885,7 @@ const verifyEmailCodeInternal = async (
853
885
  method: "POST",
854
886
  url: buildUrl(ctx.apiBaseUrl, `/v1/auth/transactions/${pending.transactionId}/email/verify`),
855
887
  body: { challenge_id: input.challengeId, code: input.code },
888
+ transactionSecret: pending.transactionSecret,
856
889
  },
857
890
  emailVerifyResponseSchema,
858
891
  );
@@ -864,6 +897,7 @@ const verifyEmailCodeInternal = async (
864
897
  const tokenOutcome = await completeAndExchange(
865
898
  ctx,
866
899
  pending.transactionId,
900
+ pending.transactionSecret,
867
901
  pending.state,
868
902
  pending.codeVerifier,
869
903
  );
@@ -903,10 +937,11 @@ const signInWithSocialInternal = async (
903
937
  ): Promise<Outcome<AuthResult, ReactNativeAuthError>> => {
904
938
  const txOutcome = await beginTransaction(ctx);
905
939
  if (!txOutcome.ok) return txOutcome;
906
- const { transactionId, pkce, state } = txOutcome.value;
940
+ const { transactionId, transactionSecret, pkce, state } = txOutcome.value;
907
941
 
908
942
  await savePendingTransaction(ctx, {
909
943
  transactionId,
944
+ transactionSecret,
910
945
  state,
911
946
  codeVerifier: pkce.verifier,
912
947
  redirectUri: ctx.config.redirectUri,
@@ -922,6 +957,7 @@ const signInWithSocialInternal = async (
922
957
  `/v1/auth/transactions/${transactionId}/social/${provider}/start`,
923
958
  ),
924
959
  body: {},
960
+ transactionSecret,
925
961
  },
926
962
  socialStartResponseSchema,
927
963
  );
@@ -946,15 +982,23 @@ const signInWithSocialInternal = async (
946
982
  await clearPendingTransaction(ctx);
947
983
  return err({ type: "state_mismatch" });
948
984
  }
949
- const callbackState = await Promise.resolve()
950
- .then(() => ctx.linking.parse(callbackUrl).queryParams["state"])
985
+ const callbackParams = await Promise.resolve()
986
+ .then(() => ctx.linking.parse(callbackUrl).queryParams)
951
987
  .catch(() => undefined);
952
- if (callbackState === undefined || !constantTimeEqual(callbackState, state)) {
988
+ const callbackState = callbackParams?.["state"];
989
+ const authorizationCode = callbackParams?.["code"];
990
+ if (callbackState === undefined || authorizationCode === undefined) {
953
991
  await clearPendingTransaction(ctx);
954
992
  return err({ type: "state_mismatch" });
955
993
  }
956
994
 
957
- const tokenOutcome = await completeAndExchange(ctx, transactionId, state, pkce.verifier);
995
+ const tokenOutcome = await exchangeAuthorizationCode(
996
+ ctx,
997
+ authorizationCode,
998
+ state,
999
+ callbackState,
1000
+ pkce.verifier,
1001
+ );
958
1002
  if (!tokenOutcome.ok) {
959
1003
  await clearPendingTransaction(ctx);
960
1004
  return tokenOutcome;
package/src/http.ts CHANGED
@@ -29,6 +29,7 @@ export interface JsonRequest {
29
29
  readonly url: string;
30
30
  readonly body?: unknown;
31
31
  readonly accessToken?: string;
32
+ readonly transactionSecret?: string;
32
33
  }
33
34
 
34
35
  const OAUTH_ERROR_CODE_SET: ReadonlySet<string> = new Set(OAUTH_ERROR_CODES);
@@ -86,6 +87,9 @@ export const requestJson = async <T>(
86
87
  ...(request.accessToken !== undefined
87
88
  ? { authorization: `Bearer ${request.accessToken}` }
88
89
  : {}),
90
+ ...(request.transactionSecret !== undefined
91
+ ? { "x-transaction-secret": request.transactionSecret }
92
+ : {}),
89
93
  };
90
94
 
91
95
  const responseOutcome = await fetchPort(request.url, {
@@ -64,6 +64,7 @@ describe("parsePersistedRefreshRecord", () => {
64
64
 
65
65
  const VALID_PENDING = {
66
66
  transactionId: "txn_abc",
67
+ transactionSecret: "transaction-secret",
67
68
  state: "state-value",
68
69
  codeVerifier: "verifier-value",
69
70
  redirectUri: "com.customer.app:/oauth/callback",
@@ -84,6 +85,11 @@ describe("parsePersistedPendingTransaction", () => {
84
85
  expect(parsePersistedPendingTransaction({ ...VALID_PENDING, challengeId: 123 })).toBeNull();
85
86
  });
86
87
 
88
+ test("rejects a pending transaction without its secret", () => {
89
+ const { transactionSecret: _transactionSecret, ...rest } = VALID_PENDING;
90
+ expect(parsePersistedPendingTransaction(rest)).toBeNull();
91
+ });
92
+
87
93
  test("rejects a record missing a required field", () => {
88
94
  const { state: _state, ...rest } = VALID_PENDING;
89
95
  expect(parsePersistedPendingTransaction(rest)).toBeNull();
@@ -5,8 +5,8 @@
5
5
  * - refresh token
6
6
  * - token family id
7
7
  * - minimal session metadata (user id, scope, client id, timestamps)
8
- * - transient PKCE transaction data (verifier/state/transaction id), cleared
9
- * once the transaction is consumed or abandoned
8
+ * - transient PKCE transaction data (verifier/state/transaction id/transaction
9
+ * secret), cleared once the transaction is consumed or abandoned
10
10
  *
11
11
  * NEVER persisted: access token, full user profile, provider access tokens,
12
12
  * OTP codes. The access token lives in the client's in-memory closure only
@@ -56,6 +56,7 @@ export interface PersistedRefreshRecord {
56
56
  /** Transient PKCE state for an in-flight auth transaction (design.md §21.6, §16.1, §20.6). */
57
57
  export interface PersistedPendingTransaction {
58
58
  readonly transactionId: string;
59
+ readonly transactionSecret: string;
59
60
  readonly state: string;
60
61
  readonly codeVerifier: string;
61
62
  readonly redirectUri: string;
@@ -84,8 +85,17 @@ export const parsePersistedPendingTransaction = (
84
85
  value: unknown,
85
86
  ): PersistedPendingTransaction | null => {
86
87
  if (!isRecord(value)) return null;
87
- const { transactionId, state, codeVerifier, redirectUri, createdAt, challengeId } = value;
88
+ const {
89
+ transactionId,
90
+ transactionSecret,
91
+ state,
92
+ codeVerifier,
93
+ redirectUri,
94
+ createdAt,
95
+ challengeId,
96
+ } = value;
88
97
  if (typeof transactionId !== "string" || transactionId.length === 0) return null;
98
+ if (typeof transactionSecret !== "string" || transactionSecret.length === 0) return null;
89
99
  if (typeof state !== "string" || state.length === 0) return null;
90
100
  if (typeof codeVerifier !== "string" || codeVerifier.length === 0) return null;
91
101
  if (typeof redirectUri !== "string" || redirectUri.length === 0) return null;
@@ -93,6 +103,7 @@ export const parsePersistedPendingTransaction = (
93
103
  if (challengeId !== undefined && typeof challengeId !== "string") return null;
94
104
  return {
95
105
  transactionId,
106
+ transactionSecret,
96
107
  state,
97
108
  codeVerifier,
98
109
  redirectUri,