@smartcrab/browser 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.d.ts CHANGED
@@ -13,6 +13,8 @@ import type { WebAuthnBrowserPort } from "./webauthn.js";
13
13
  * - Short-lived PKCE callback metadata is stored in `sessionStorage` (never `localStorage`) so a
14
14
  * top-level redirect can resume after the SPA reloads. It is consumed once and expires after
15
15
  * 10 minutes; when storage is unavailable, the current client falls back to its memory copy.
16
+ * - Transaction secrets are kept in `sessionStorage` for up to 10 minutes and sent with every
17
+ * transaction API call; successful cancellation or completion removes them.
16
18
  * - Refresh-token persistence is a separate explicit opt-in via `refreshTokenStorage`.
17
19
  * - No silent-iframe / third-party-cookie renewal. After reload, reauthorize top-level via
18
20
  * `beginHostedAuthorization()` against the existing Hosted Session, or call `restoreSession()`
package/dist/client.js CHANGED
@@ -18,6 +18,7 @@ const defaultRedirectPort = {
18
18
  },
19
19
  };
20
20
  const PENDING_AUTHORIZATION_STORAGE_PREFIX = "@smartcrab/browser:pending:";
21
+ const TRANSACTION_SECRET_STORAGE_PREFIX = "@smartcrab/browser:transaction-secret:";
21
22
  const isPendingAuthorization = (value) => {
22
23
  if (typeof value !== "object" || value === null || Array.isArray(value))
23
24
  return false;
@@ -29,6 +30,15 @@ const isPendingAuthorization = (value) => {
29
30
  typeof record["createdAt"] === "number" &&
30
31
  Number.isFinite(record["createdAt"]));
31
32
  };
33
+ const isPersistedTransactionSecret = (value) => {
34
+ if (typeof value !== "object" || value === null || Array.isArray(value))
35
+ return false;
36
+ const record = value;
37
+ return (typeof record["transactionId"] === "string" &&
38
+ typeof record["secret"] === "string" &&
39
+ typeof record["createdAt"] === "number" &&
40
+ Number.isFinite(record["createdAt"]));
41
+ };
32
42
  const encodeSegment = encodeURIComponent;
33
43
  export const createBrowserAuthClient = (config) => {
34
44
  // Programmer-error validation: fail fast at factory time (not a runtime
@@ -52,11 +62,12 @@ export const createBrowserAuthClient = (config) => {
52
62
  const redirectPort = config.redirect ?? defaultRedirectPort;
53
63
  const now = config.now ?? (() => Date.now());
54
64
  const storage = config.refreshTokenStorage;
55
- // Tokens stay in this closure; only short-lived PKCE callback state uses sessionStorage.
65
+ // Tokens stay in this closure; short-lived PKCE state and transaction secrets use sessionStorage.
56
66
  let tokenSet = null;
57
67
  let cachedIssuer = config.issuer ?? null;
58
68
  let inflightRefresh = null;
59
69
  const pendingByState = new Map();
70
+ const transactionSecrets = new Map();
60
71
  const listeners = new Set();
61
72
  let snapshot = { status: "signed_out", hasRefreshToken: false };
62
73
  const notify = () => {
@@ -110,6 +121,49 @@ export const createBrowserAuthClient = (config) => {
110
121
  }
111
122
  return pending;
112
123
  };
124
+ const registerTransactionSecret = async (transactionId, secret) => {
125
+ const persisted = { transactionId, secret, createdAt: now() };
126
+ transactionSecrets.set(transactionId, persisted);
127
+ await Promise.resolve()
128
+ .then(() => sessionStorage.setItem(`${TRANSACTION_SECRET_STORAGE_PREFIX}${transactionId}`, JSON.stringify(persisted)))
129
+ .then(undefined, () => undefined);
130
+ };
131
+ const getTransactionSecret = async (transactionId) => {
132
+ const inMemory = transactionSecrets.get(transactionId);
133
+ if (inMemory !== undefined) {
134
+ if (now() - inMemory.createdAt <= PENDING_AUTHORIZATION_TTL_MS)
135
+ return inMemory.secret;
136
+ transactionSecrets.delete(transactionId);
137
+ }
138
+ const key = `${TRANSACTION_SECRET_STORAGE_PREFIX}${transactionId}`;
139
+ const stored = await Promise.resolve()
140
+ .then(() => {
141
+ const serialized = sessionStorage.getItem(key);
142
+ if (serialized === null)
143
+ return null;
144
+ const parsed = JSON.parse(serialized);
145
+ return isPersistedTransactionSecret(parsed) && parsed.transactionId === transactionId
146
+ ? parsed
147
+ : null;
148
+ })
149
+ .then(undefined, () => null);
150
+ if (stored === null)
151
+ return null;
152
+ if (now() - stored.createdAt > PENDING_AUTHORIZATION_TTL_MS) {
153
+ await Promise.resolve()
154
+ .then(() => sessionStorage.removeItem(key))
155
+ .then(undefined, () => undefined);
156
+ return null;
157
+ }
158
+ transactionSecrets.set(transactionId, stored);
159
+ return stored.secret;
160
+ };
161
+ const forgetTransactionSecret = async (transactionId) => {
162
+ transactionSecrets.delete(transactionId);
163
+ await Promise.resolve()
164
+ .then(() => sessionStorage.removeItem(`${TRANSACTION_SECRET_STORAGE_PREFIX}${transactionId}`))
165
+ .then(undefined, () => undefined);
166
+ };
113
167
  const applyTokenResponse = async (tokenResponse) => {
114
168
  const refreshToken = tokenResponse.refresh_token ?? tokenSet?.refreshToken ?? null;
115
169
  tokenSet = {
@@ -141,12 +195,18 @@ export const createBrowserAuthClient = (config) => {
141
195
  }
142
196
  notify();
143
197
  };
144
- const request = (method, path, schema, options) => requestJson(fetchPort, {
145
- method,
146
- url: buildUrl(baseUrl, path, options?.query),
147
- ...(options?.body !== undefined ? { body: options.body } : {}),
148
- ...(options?.accessToken !== undefined ? { accessToken: options.accessToken } : {}),
149
- }, schema);
198
+ const request = async (method, path, schema, options) => {
199
+ const transactionSecret = options?.transactionId === undefined
200
+ ? null
201
+ : await getTransactionSecret(options.transactionId);
202
+ return requestJson(fetchPort, {
203
+ method,
204
+ url: buildUrl(baseUrl, path, options?.query),
205
+ ...(options?.body !== undefined ? { body: options.body } : {}),
206
+ ...(options?.accessToken !== undefined ? { accessToken: options.accessToken } : {}),
207
+ ...(transactionSecret !== null ? { transactionSecret } : {}),
208
+ }, schema);
209
+ };
150
210
  const getPublicConfig = () => request("GET", "/v1/config", publicConfigResponseSchema, {
151
211
  query: { client_id: config.clientId },
152
212
  });
@@ -188,6 +248,7 @@ export const createBrowserAuthClient = (config) => {
188
248
  redirectUri: config.redirectUri,
189
249
  createdAt: now(),
190
250
  });
251
+ await registerTransactionSecret(outcome.value.transaction_id, outcome.value.transaction_secret);
191
252
  return ok({
192
253
  transactionId: outcome.value.transaction_id,
193
254
  state,
@@ -196,23 +257,29 @@ export const createBrowserAuthClient = (config) => {
196
257
  });
197
258
  };
198
259
  const transactionPath = (transactionId) => `/v1/auth/transactions/${encodeSegment(transactionId)}`;
199
- const getTransaction = (transactionId) => request("GET", transactionPath(transactionId), transactionGetResponseSchema);
200
- const cancelTransaction = (transactionId) => request("POST", `${transactionPath(transactionId)}/cancel`, transactionCancelResponseSchema, {
201
- body: {},
202
- });
260
+ const getTransaction = (transactionId) => request("GET", transactionPath(transactionId), transactionGetResponseSchema, { transactionId });
261
+ const cancelTransaction = async (transactionId) => {
262
+ const outcome = await request("POST", `${transactionPath(transactionId)}/cancel`, transactionCancelResponseSchema, { body: {}, transactionId });
263
+ if (outcome.ok)
264
+ await forgetTransactionSecret(transactionId);
265
+ return outcome;
266
+ };
203
267
  // --- email OTP -----------------------------------------------------------------
204
268
  const startEmailOtp = (transactionId, input) => request("POST", `${transactionPath(transactionId)}/email/start`, emailChallengeResponseSchema, {
205
269
  body: input,
270
+ transactionId,
206
271
  });
207
- const resendEmailOtp = (transactionId, input) => request("POST", `${transactionPath(transactionId)}/email/resend`, emailChallengeResponseSchema, { body: input });
272
+ const resendEmailOtp = (transactionId, input) => request("POST", `${transactionPath(transactionId)}/email/resend`, emailChallengeResponseSchema, { body: input, transactionId });
208
273
  const verifyEmailOtp = (transactionId, input) => request("POST", `${transactionPath(transactionId)}/email/verify`, emailVerifyResponseSchema, {
209
274
  body: input,
275
+ transactionId,
210
276
  });
211
277
  // --- passkeys --------------------------------------------------------------------
212
278
  const getPasskeyRegistrationOptions = (transactionId) => request("POST", `${transactionPath(transactionId)}/passkeys/registration/options`, passkeyRegistrationOptionsResponseSchema, {
213
279
  body: {},
280
+ transactionId,
214
281
  });
215
- const verifyPasskeyRegistration = (transactionId, input) => request("POST", `${transactionPath(transactionId)}/passkeys/registration/verify`, transactionPasskeyRegistrationVerifyResponseSchema, { body: input });
282
+ const verifyPasskeyRegistration = (transactionId, input) => request("POST", `${transactionPath(transactionId)}/passkeys/registration/verify`, transactionPasskeyRegistrationVerifyResponseSchema, { body: input, transactionId });
216
283
  const startPasskeyRegistration = async (transactionId, input) => {
217
284
  if (!webAuthn.isAvailable()) {
218
285
  return err({
@@ -232,8 +299,8 @@ export const createBrowserAuthClient = (config) => {
232
299
  ...(input?.name !== undefined ? { name: input.name } : {}),
233
300
  });
234
301
  };
235
- const getPasskeyAuthenticationOptions = (transactionId, input) => request("POST", `${transactionPath(transactionId)}/passkeys/authentication/options`, passkeyAuthenticationOptionsResponseSchema, { body: input ?? {} });
236
- const verifyPasskeyAuthentication = (transactionId, input) => request("POST", `${transactionPath(transactionId)}/passkeys/authentication/verify`, passkeyAuthenticationVerifyResponseSchema, { body: input });
302
+ const getPasskeyAuthenticationOptions = (transactionId, input) => request("POST", `${transactionPath(transactionId)}/passkeys/authentication/options`, passkeyAuthenticationOptionsResponseSchema, { body: input ?? {}, transactionId });
303
+ const verifyPasskeyAuthentication = (transactionId, input) => request("POST", `${transactionPath(transactionId)}/passkeys/authentication/verify`, passkeyAuthenticationVerifyResponseSchema, { body: input, transactionId });
237
304
  const startPasskeyAuthentication = async (transactionId, input) => {
238
305
  if (!webAuthn.isAvailable()) {
239
306
  return err({
@@ -252,7 +319,7 @@ export const createBrowserAuthClient = (config) => {
252
319
  };
253
320
  // --- social -----------------------------------------------------------------------
254
321
  const startSocialSignIn = async (transactionId, provider) => {
255
- const outcome = await request("POST", `${transactionPath(transactionId)}/social/${encodeSegment(provider)}/start`, socialStartResponseSchema, { body: {} });
322
+ const outcome = await request("POST", `${transactionPath(transactionId)}/social/${encodeSegment(provider)}/start`, socialStartResponseSchema, { body: {}, transactionId });
256
323
  if (!outcome.ok)
257
324
  return outcome;
258
325
  // design.md §22.3/§20.6: top-level navigation only; the SPA resumes via
@@ -264,6 +331,7 @@ export const createBrowserAuthClient = (config) => {
264
331
  const completeTransaction = async (transactionId) => {
265
332
  const outcome = await request("POST", `${transactionPath(transactionId)}/complete`, transactionCompleteResponseSchema, {
266
333
  body: {},
334
+ transactionId,
267
335
  });
268
336
  if (!outcome.ok)
269
337
  return outcome;
@@ -275,6 +343,7 @@ export const createBrowserAuthClient = (config) => {
275
343
  message: "complete response redirect_uri does not match the configured redirectUri",
276
344
  });
277
345
  }
346
+ await forgetTransactionSecret(transactionId);
278
347
  return outcome;
279
348
  };
280
349
  const exchangeAuthorizationCode = async (input) => {
package/dist/http.d.ts CHANGED
@@ -35,6 +35,7 @@ export interface JsonRequest {
35
35
  readonly url: string;
36
36
  readonly body?: unknown;
37
37
  readonly accessToken?: string;
38
+ readonly transactionSecret?: string;
38
39
  }
39
40
  export declare const isOAuthErrorCode: (value: string) => value is OAuthErrorCode;
40
41
  /**
package/dist/http.js CHANGED
@@ -41,6 +41,9 @@ export const requestJson = async (fetchPort, request, schema) => {
41
41
  ...(request.accessToken !== undefined
42
42
  ? { authorization: `Bearer ${request.accessToken}` }
43
43
  : {}),
44
+ ...(request.transactionSecret !== undefined
45
+ ? { "x-transaction-secret": request.transactionSecret }
46
+ : {}),
44
47
  };
45
48
  const responseOutcome = await fetchPort(request.url, {
46
49
  method: request.method,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smartcrab/browser",
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",
@@ -27,7 +27,7 @@
27
27
  "access": "public"
28
28
  },
29
29
  "dependencies": {
30
- "@smartcrab/contracts-public": "0.2.1-next-20261009084044"
30
+ "@smartcrab/contracts-public": "0.3.0"
31
31
  },
32
32
  "devDependencies": {
33
33
  "typescript": "5.9.3",
@@ -87,6 +87,7 @@ const createStub = (onMe: (req: CapturedRequest) => Response) => {
87
87
  return Promise.resolve(
88
88
  jsonResponse(200, {
89
89
  transaction_id: TXN_ID,
90
+ transaction_secret: "s".repeat(43),
90
91
  expires_at: "2026-08-05T08:10:00Z",
91
92
  available_methods: ["email_otp"],
92
93
  }),
@@ -61,6 +61,7 @@ const createStub = (onApi: (req: CapturedRequest) => Response | Promise<Response
61
61
  return Promise.resolve(
62
62
  jsonResponse(200, {
63
63
  transaction_id: TXN_ID,
64
+ transaction_secret: "s".repeat(43),
64
65
  expires_at: "2026-08-05T08:10:00Z",
65
66
  available_methods: ["email_otp"],
66
67
  }),
@@ -140,7 +141,7 @@ describe("access token memory rules (design.md §22.3)", () => {
140
141
  Reflect.deleteProperty(globalThis, "sessionStorage");
141
142
  });
142
143
 
143
- test("only transient PKCE metadata, never tokens, reaches Web Storage", async () => {
144
+ test("only transient PKCE and transaction secrets, never tokens, reach Web Storage", async () => {
144
145
  const localSetItem = vi.fn((_key: string, _value: string): void => undefined);
145
146
  const sessionValues: string[] = [];
146
147
  const sessionSetItem = vi.fn((_key: string, value: string): void => {
@@ -170,7 +171,7 @@ describe("access token memory rules (design.md §22.3)", () => {
170
171
  expect(token).toEqual({ ok: true, value: "at_1" });
171
172
 
172
173
  expect(localSetItem).not.toHaveBeenCalled();
173
- expect(sessionSetItem).toHaveBeenCalledTimes(1);
174
+ expect(sessionSetItem).toHaveBeenCalledTimes(2);
174
175
  const pending = JSON.parse(sessionValues[0] ?? "{}") as Record<string, unknown>;
175
176
  expect(Object.keys(pending).sort()).toEqual([
176
177
  "codeVerifier",
@@ -179,6 +180,11 @@ describe("access token memory rules (design.md §22.3)", () => {
179
180
  "redirectUri",
180
181
  "state",
181
182
  ]);
183
+ const transactionSecret = JSON.parse(sessionValues[1] ?? "{}") as Record<string, unknown>;
184
+ expect(transactionSecret).toMatchObject({
185
+ transactionId: TXN_ID,
186
+ secret: "s".repeat(43),
187
+ });
182
188
  expect(sessionValues.join("")).not.toContain("at_1");
183
189
  expect(sessionValues.join("")).not.toContain("rt_1");
184
190
  });
@@ -58,8 +58,10 @@ const createFetchStub = (handler: (req: CapturedRequest) => Response | Promise<R
58
58
  const jsonResponse = (status: number, body: unknown, headers?: Record<string, string>): Response =>
59
59
  new Response(JSON.stringify(body), { status, ...(headers !== undefined ? { headers } : {}) });
60
60
 
61
+ const TRANSACTION_SECRET = "s".repeat(43);
61
62
  const CREATE_RESPONSE = {
62
63
  transaction_id: TXN_ID,
64
+ transaction_secret: TRANSACTION_SECRET,
63
65
  expires_at: "2026-08-05T08:10:00Z",
64
66
  available_methods: ["passkey", "email_otp", "google"],
65
67
  };
@@ -120,6 +122,7 @@ describe("createTransaction (design.md §16.1)", () => {
120
122
  if (request === undefined) throw new Error("expected a request");
121
123
  expect(request.method).toBe("POST");
122
124
  expect(request.url).toBe(`${BASE_URL}/v1/auth/transactions`);
125
+ expect(request.headers["x-transaction-secret"]).toBeUndefined();
123
126
  expect(request.body).toMatchObject({
124
127
  client_id: CLIENT_ID,
125
128
  redirect_uri: REDIRECT_URI,
@@ -187,6 +190,66 @@ describe("getTransaction / cancelTransaction (design.md §16.2)", () => {
187
190
  expect(calls[0]?.url).toBe(`${BASE_URL}/v1/auth/transactions/${TXN_ID}/cancel`);
188
191
  expect(calls[0]?.body).toEqual({});
189
192
  });
193
+
194
+ test("sends the transaction secret on every transaction-specific request", async () => {
195
+ const { calls, fetchPort } = createFetchStub((request) =>
196
+ request.url.endsWith("/v1/auth/transactions")
197
+ ? jsonResponse(200, CREATE_RESPONSE)
198
+ : jsonResponse(200, {}),
199
+ );
200
+ const client = makeClient(fetchPort);
201
+ const created = await client.createTransaction();
202
+ expect(created.ok).toBe(true);
203
+ if (!created.ok) return;
204
+ const transactionId = created.value.transactionId;
205
+
206
+ await client.getTransaction(transactionId);
207
+ await client.cancelTransaction(transactionId);
208
+ await client.startEmailOtp(transactionId, { email: "user@example.com" });
209
+ await client.resendEmailOtp(transactionId, { challenge_id: "chal_abc" });
210
+ await client.verifyEmailOtp(transactionId, { challenge_id: "chal_abc", code: "123456" });
211
+ await client.getPasskeyRegistrationOptions(transactionId);
212
+ await client.verifyPasskeyRegistration(transactionId, {
213
+ credential: {} as PasskeyRegistrationCredential,
214
+ });
215
+ await client.getPasskeyAuthenticationOptions(transactionId);
216
+ await client.verifyPasskeyAuthentication(transactionId, {
217
+ credential: {} as PasskeyAuthenticationCredential,
218
+ });
219
+ await client.startSocialSignIn(transactionId, "google");
220
+ await client.completeTransaction(transactionId);
221
+
222
+ expect(calls).toHaveLength(12);
223
+ expect(calls.slice(1).map((request) => request.headers["x-transaction-secret"])).toEqual(
224
+ Array(11).fill(TRANSACTION_SECRET),
225
+ );
226
+ });
227
+
228
+ test("restores the transaction secret from sessionStorage after reload", async () => {
229
+ const { entries, storage } = createTestSessionStorage();
230
+ vi.stubGlobal("sessionStorage", storage);
231
+ const { calls, fetchPort } = createFetchStub((request) => {
232
+ if (request.url.endsWith("/v1/auth/transactions")) {
233
+ return jsonResponse(200, CREATE_RESPONSE);
234
+ }
235
+ return jsonResponse(200, {
236
+ transaction_id: TXN_ID,
237
+ status: "challenge_issued",
238
+ expires_at: "2026-08-05T08:10:00Z",
239
+ available_methods: ["email_otp"],
240
+ pending_link: null,
241
+ });
242
+ });
243
+ const beforeReload = makeClient(fetchPort);
244
+ const created = await beforeReload.createTransaction();
245
+ expect(created.ok).toBe(true);
246
+ if (!created.ok) return;
247
+ expect(entries.size).toBe(2);
248
+
249
+ const afterReload = makeClient(fetchPort);
250
+ await afterReload.getTransaction(created.value.transactionId);
251
+ expect(calls[1]?.headers["x-transaction-secret"]).toBe(TRANSACTION_SECRET);
252
+ });
190
253
  });
191
254
 
192
255
  describe("email OTP (design.md §16.2, §18)", () => {
package/src/client.ts CHANGED
@@ -100,6 +100,8 @@ import type { WebAuthnBrowserPort } from "./webauthn.js";
100
100
  * - Short-lived PKCE callback metadata is stored in `sessionStorage` (never `localStorage`) so a
101
101
  * top-level redirect can resume after the SPA reloads. It is consumed once and expires after
102
102
  * 10 minutes; when storage is unavailable, the current client falls back to its memory copy.
103
+ * - Transaction secrets are kept in `sessionStorage` for up to 10 minutes and sent with every
104
+ * transaction API call; successful cancellation or completion removes them.
103
105
  * - Refresh-token persistence is a separate explicit opt-in via `refreshTokenStorage`.
104
106
  * - No silent-iframe / third-party-cookie renewal. After reload, reauthorize top-level via
105
107
  * `beginHostedAuthorization()` against the existing Hosted Session, or call `restoreSession()`
@@ -152,6 +154,12 @@ interface PendingAuthorization {
152
154
  readonly createdAt: number;
153
155
  }
154
156
 
157
+ interface PersistedTransactionSecret {
158
+ readonly transactionId: string;
159
+ readonly secret: string;
160
+ readonly createdAt: number;
161
+ }
162
+
155
163
  export interface BrowserAuthClientConfig {
156
164
  /** Public API origin, e.g. `https://id.example.com` (trailing slash tolerated). */
157
165
  readonly baseUrl: string;
@@ -391,6 +399,7 @@ const defaultRedirectPort: RedirectPort = {
391
399
  },
392
400
  };
393
401
  const PENDING_AUTHORIZATION_STORAGE_PREFIX = "@smartcrab/browser:pending:";
402
+ const TRANSACTION_SECRET_STORAGE_PREFIX = "@smartcrab/browser:transaction-secret:";
394
403
 
395
404
  const isPendingAuthorization = (value: unknown): value is PendingAuthorization => {
396
405
  if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
@@ -405,6 +414,17 @@ const isPendingAuthorization = (value: unknown): value is PendingAuthorization =
405
414
  );
406
415
  };
407
416
 
417
+ const isPersistedTransactionSecret = (value: unknown): value is PersistedTransactionSecret => {
418
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
419
+ const record = value as Record<string, unknown>;
420
+ return (
421
+ typeof record["transactionId"] === "string" &&
422
+ typeof record["secret"] === "string" &&
423
+ typeof record["createdAt"] === "number" &&
424
+ Number.isFinite(record["createdAt"])
425
+ );
426
+ };
427
+
408
428
  const encodeSegment = encodeURIComponent;
409
429
 
410
430
  export const createBrowserAuthClient = (config: BrowserAuthClientConfig): BrowserAuthClient => {
@@ -431,11 +451,12 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
431
451
  const now = config.now ?? (() => Date.now());
432
452
  const storage = config.refreshTokenStorage;
433
453
 
434
- // Tokens stay in this closure; only short-lived PKCE callback state uses sessionStorage.
454
+ // Tokens stay in this closure; short-lived PKCE state and transaction secrets use sessionStorage.
435
455
  let tokenSet: TokenSet | null = null;
436
456
  let cachedIssuer: string | null = config.issuer ?? null;
437
457
  let inflightRefresh: Promise<Outcome<AuthenticatedSession, BrowserAuthError>> | null = null;
438
458
  const pendingByState = new Map<string, PendingAuthorization>();
459
+ const transactionSecrets = new Map<string, PersistedTransactionSecret>();
439
460
  const listeners = new Set<BrowserAuthListener>();
440
461
  let snapshot: BrowserAuthSnapshot = { status: "signed_out", hasRefreshToken: false };
441
462
 
@@ -497,6 +518,57 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
497
518
  return pending;
498
519
  };
499
520
 
521
+ const registerTransactionSecret = async (
522
+ transactionId: string,
523
+ secret: string,
524
+ ): Promise<void> => {
525
+ const persisted = { transactionId, secret, createdAt: now() };
526
+ transactionSecrets.set(transactionId, persisted);
527
+ await Promise.resolve()
528
+ .then(() =>
529
+ sessionStorage.setItem(
530
+ `${TRANSACTION_SECRET_STORAGE_PREFIX}${transactionId}`,
531
+ JSON.stringify(persisted),
532
+ ),
533
+ )
534
+ .then(undefined, () => undefined);
535
+ };
536
+
537
+ const getTransactionSecret = async (transactionId: string): Promise<string | null> => {
538
+ const inMemory = transactionSecrets.get(transactionId);
539
+ if (inMemory !== undefined) {
540
+ if (now() - inMemory.createdAt <= PENDING_AUTHORIZATION_TTL_MS) return inMemory.secret;
541
+ transactionSecrets.delete(transactionId);
542
+ }
543
+ const key = `${TRANSACTION_SECRET_STORAGE_PREFIX}${transactionId}`;
544
+ const stored = await Promise.resolve()
545
+ .then((): PersistedTransactionSecret | null => {
546
+ const serialized = sessionStorage.getItem(key);
547
+ if (serialized === null) return null;
548
+ const parsed: unknown = JSON.parse(serialized);
549
+ return isPersistedTransactionSecret(parsed) && parsed.transactionId === transactionId
550
+ ? parsed
551
+ : null;
552
+ })
553
+ .then(undefined, () => null);
554
+ if (stored === null) return null;
555
+ if (now() - stored.createdAt > PENDING_AUTHORIZATION_TTL_MS) {
556
+ await Promise.resolve()
557
+ .then(() => sessionStorage.removeItem(key))
558
+ .then(undefined, () => undefined);
559
+ return null;
560
+ }
561
+ transactionSecrets.set(transactionId, stored);
562
+ return stored.secret;
563
+ };
564
+
565
+ const forgetTransactionSecret = async (transactionId: string): Promise<void> => {
566
+ transactionSecrets.delete(transactionId);
567
+ await Promise.resolve()
568
+ .then(() => sessionStorage.removeItem(`${TRANSACTION_SECRET_STORAGE_PREFIX}${transactionId}`))
569
+ .then(undefined, () => undefined);
570
+ };
571
+
500
572
  const applyTokenResponse = async (
501
573
  tokenResponse: TokenResponse,
502
574
  ): Promise<AuthenticatedSession> => {
@@ -532,7 +604,7 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
532
604
  notify();
533
605
  };
534
606
 
535
- const request = <T>(
607
+ const request = async <T>(
536
608
  method: "GET" | "POST" | "PATCH" | "DELETE",
537
609
  path: string,
538
610
  schema: WireSchema<T>,
@@ -540,18 +612,25 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
540
612
  readonly body?: unknown;
541
613
  readonly accessToken?: string;
542
614
  readonly query?: Record<string, string>;
615
+ readonly transactionId?: string;
543
616
  },
544
- ): Promise<Outcome<T, BrowserAuthError>> =>
545
- requestJson(
617
+ ): Promise<Outcome<T, BrowserAuthError>> => {
618
+ const transactionSecret =
619
+ options?.transactionId === undefined
620
+ ? null
621
+ : await getTransactionSecret(options.transactionId);
622
+ return requestJson(
546
623
  fetchPort,
547
624
  {
548
625
  method,
549
626
  url: buildUrl(baseUrl, path, options?.query),
550
627
  ...(options?.body !== undefined ? { body: options.body } : {}),
551
628
  ...(options?.accessToken !== undefined ? { accessToken: options.accessToken } : {}),
629
+ ...(transactionSecret !== null ? { transactionSecret } : {}),
552
630
  },
553
631
  schema,
554
632
  );
633
+ };
555
634
 
556
635
  const getPublicConfig = (): Promise<Outcome<PublicConfigResponse, BrowserAuthError>> =>
557
636
  request("GET", "/v1/config", publicConfigResponseSchema, {
@@ -602,6 +681,7 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
602
681
  redirectUri: config.redirectUri,
603
682
  createdAt: now(),
604
683
  });
684
+ await registerTransactionSecret(outcome.value.transaction_id, outcome.value.transaction_secret);
605
685
  return ok({
606
686
  transactionId: outcome.value.transaction_id,
607
687
  state,
@@ -614,18 +694,25 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
614
694
  `/v1/auth/transactions/${encodeSegment(transactionId)}`;
615
695
 
616
696
  const getTransaction = (transactionId: string) =>
617
- request("GET", transactionPath(transactionId), transactionGetResponseSchema);
697
+ request("GET", transactionPath(transactionId), transactionGetResponseSchema, { transactionId });
618
698
 
619
- const cancelTransaction = (transactionId: string) =>
620
- request("POST", `${transactionPath(transactionId)}/cancel`, transactionCancelResponseSchema, {
621
- body: {},
622
- });
699
+ const cancelTransaction = async (transactionId: string) => {
700
+ const outcome = await request(
701
+ "POST",
702
+ `${transactionPath(transactionId)}/cancel`,
703
+ transactionCancelResponseSchema,
704
+ { body: {}, transactionId },
705
+ );
706
+ if (outcome.ok) await forgetTransactionSecret(transactionId);
707
+ return outcome;
708
+ };
623
709
 
624
710
  // --- email OTP -----------------------------------------------------------------
625
711
 
626
712
  const startEmailOtp = (transactionId: string, input: EmailStartRequest) =>
627
713
  request("POST", `${transactionPath(transactionId)}/email/start`, emailChallengeResponseSchema, {
628
714
  body: input,
715
+ transactionId,
629
716
  });
630
717
 
631
718
  const resendEmailOtp = (transactionId: string, input: EmailResendRequest) =>
@@ -633,12 +720,13 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
633
720
  "POST",
634
721
  `${transactionPath(transactionId)}/email/resend`,
635
722
  emailChallengeResponseSchema,
636
- { body: input },
723
+ { body: input, transactionId },
637
724
  );
638
725
 
639
726
  const verifyEmailOtp = (transactionId: string, input: EmailVerifyRequest) =>
640
727
  request("POST", `${transactionPath(transactionId)}/email/verify`, emailVerifyResponseSchema, {
641
728
  body: input,
729
+ transactionId,
642
730
  });
643
731
 
644
732
  // --- passkeys --------------------------------------------------------------------
@@ -650,6 +738,7 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
650
738
  passkeyRegistrationOptionsResponseSchema,
651
739
  {
652
740
  body: {},
741
+ transactionId,
653
742
  },
654
743
  );
655
744
 
@@ -661,7 +750,7 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
661
750
  "POST",
662
751
  `${transactionPath(transactionId)}/passkeys/registration/verify`,
663
752
  transactionPasskeyRegistrationVerifyResponseSchema,
664
- { body: input },
753
+ { body: input, transactionId },
665
754
  );
666
755
 
667
756
  const startPasskeyRegistration = async (
@@ -693,7 +782,7 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
693
782
  "POST",
694
783
  `${transactionPath(transactionId)}/passkeys/authentication/options`,
695
784
  passkeyAuthenticationOptionsResponseSchema,
696
- { body: input ?? {} },
785
+ { body: input ?? {}, transactionId },
697
786
  );
698
787
 
699
788
  const verifyPasskeyAuthentication = (
@@ -704,7 +793,7 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
704
793
  "POST",
705
794
  `${transactionPath(transactionId)}/passkeys/authentication/verify`,
706
795
  passkeyAuthenticationVerifyResponseSchema,
707
- { body: input },
796
+ { body: input, transactionId },
708
797
  );
709
798
 
710
799
  const startPasskeyAuthentication = async (
@@ -735,7 +824,7 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
735
824
  "POST",
736
825
  `${transactionPath(transactionId)}/social/${encodeSegment(provider)}/start`,
737
826
  socialStartResponseSchema,
738
- { body: {} },
827
+ { body: {}, transactionId },
739
828
  );
740
829
  if (!outcome.ok) return outcome;
741
830
  // design.md §22.3/§20.6: top-level navigation only; the SPA resumes via
@@ -755,6 +844,7 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
755
844
  transactionCompleteResponseSchema,
756
845
  {
757
846
  body: {},
847
+ transactionId,
758
848
  },
759
849
  );
760
850
  if (!outcome.ok) return outcome;
@@ -766,6 +856,7 @@ export const createBrowserAuthClient = (config: BrowserAuthClientConfig): Browse
766
856
  message: "complete response redirect_uri does not match the configured redirectUri",
767
857
  });
768
858
  }
859
+ await forgetTransactionSecret(transactionId);
769
860
  return outcome;
770
861
  };
771
862
 
package/src/http.ts CHANGED
@@ -37,6 +37,7 @@ export interface JsonRequest {
37
37
  readonly url: string;
38
38
  readonly body?: unknown;
39
39
  readonly accessToken?: string;
40
+ readonly transactionSecret?: string;
40
41
  }
41
42
 
42
43
  const OAUTH_ERROR_CODE_SET: ReadonlySet<string> = new Set(OAUTH_ERROR_CODES);
@@ -94,6 +95,9 @@ export const requestJson = async <T>(
94
95
  ...(request.accessToken !== undefined
95
96
  ? { authorization: `Bearer ${request.accessToken}` }
96
97
  : {}),
98
+ ...(request.transactionSecret !== undefined
99
+ ? { "x-transaction-secret": request.transactionSecret }
100
+ : {}),
97
101
  };
98
102
 
99
103
  const responseOutcome = await fetchPort(request.url, {