@smartcrab/react 0.4.0-next-20261107082009 → 0.4.0-next-20261111042553

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/hooks.js CHANGED
@@ -108,7 +108,8 @@ export const usePasskey = () => {
108
108
  return {
109
109
  isSupported: client.isPasskeySupported(),
110
110
  isCeremonyActive: state.step === "ceremony" ||
111
- (state.step === "challenge_required" && state.previousState.step === "ceremony"),
111
+ (state.step === "challenge_required" && state.previousState.step === "ceremony") ||
112
+ (state.step === "completing" && state.previousState?.step === "ceremony"),
112
113
  pendingAction: flowSnapshot.pendingAction,
113
114
  error: flowError(state),
114
115
  adaptiveChallenge: flowAdaptiveChallenge(state),
@@ -124,10 +125,13 @@ export const useEmailOtp = () => {
124
125
  const flowSnapshot = useStoreSnapshot(flow.subscribe, flow.getSnapshot);
125
126
  return useMemo(() => {
126
127
  const state = flowSnapshot.state;
128
+ const resumableState = state.step === "challenge_required" || state.step === "completing"
129
+ ? state.previousState
130
+ : null;
127
131
  const emailState = state.step === "email_challenge_sent"
128
132
  ? state
129
- : state.step === "challenge_required" && state.previousState.step === "email_challenge_sent"
130
- ? state.previousState
133
+ : resumableState?.step === "email_challenge_sent"
134
+ ? resumableState
131
135
  : null;
132
136
  return {
133
137
  challenge: emailState === null
@@ -55,6 +55,7 @@ export type SignInFlowState = {
55
55
  } | AwaitingMethodState | EmailChallengeSentState | CeremonyState | SignInFlowAdaptiveChallengeState | {
56
56
  readonly step: "completing";
57
57
  readonly transactionId: string;
58
+ readonly previousState?: SignInFlowChallengeResumeState;
58
59
  } | {
59
60
  readonly step: "signed_in";
60
61
  readonly session: AuthenticatedSession;
@@ -1,5 +1,6 @@
1
1
  import { err, ok } from "@smartcrab/browser";
2
2
  const invalidState = (expected, actual) => err({ type: "invalid_flow_state", expected, actual });
3
+ const SOCIAL_REDIRECT_PENDING_TIMEOUT_MS = 10_000;
3
4
  export const createSignInFlow = (client) => {
4
5
  let snapshot = { state: { step: "idle" }, pendingAction: null };
5
6
  let pendingAdaptiveChallenge = null;
@@ -11,6 +12,22 @@ export const createSignInFlow = (client) => {
11
12
  listener(snapshot);
12
13
  }
13
14
  };
15
+ const pendingActionError = () => snapshot.pendingAction === null
16
+ ? null
17
+ : invalidState("no pending action", snapshot.pendingAction);
18
+ const invokeClient = async (operation) => {
19
+ try {
20
+ return await operation();
21
+ }
22
+ catch (cause) {
23
+ // A rejected client request must not strand the flow in a pending state.
24
+ return err({
25
+ type: "network_error",
26
+ message: cause instanceof Error ? cause.message : "Authentication request failed",
27
+ retryable: true,
28
+ });
29
+ }
30
+ };
14
31
  const fail = (error) => {
15
32
  pendingAdaptiveChallenge = null;
16
33
  challengeAttemptId += 1;
@@ -35,17 +52,17 @@ export const createSignInFlow = (client) => {
35
52
  });
36
53
  };
37
54
  /** complete → exchange, shared by every verify path (design.md §16.3). */
38
- const finalize = async (transactionId) => {
39
- transition({ step: "completing", transactionId });
40
- const completed = await client.completeTransaction(transactionId);
55
+ const finalize = async (transactionId, pendingAction, previousState) => {
56
+ transition({ step: "completing", transactionId, previousState }, pendingAction);
57
+ const completed = await invokeClient(() => client.completeTransaction(transactionId));
41
58
  if (!completed.ok) {
42
59
  fail(completed.error);
43
60
  return completed;
44
61
  }
45
- const exchanged = await client.exchangeAuthorizationCode({
62
+ const exchanged = await invokeClient(() => client.exchangeAuthorizationCode({
46
63
  code: completed.value.authorization_code,
47
64
  state: completed.value.state,
48
- });
65
+ }));
49
66
  if (!exchanged.ok) {
50
67
  fail(exchanged.error);
51
68
  return exchanged;
@@ -54,12 +71,15 @@ export const createSignInFlow = (client) => {
54
71
  return ok(exchanged.value);
55
72
  };
56
73
  const begin = async () => {
74
+ const pendingError = pendingActionError();
75
+ if (pendingError !== null)
76
+ return pendingError;
57
77
  const { step } = snapshot.state;
58
78
  if (step !== "idle" && step !== "failed") {
59
79
  return invalidState("idle|failed", step);
60
80
  }
61
81
  transition({ step: "starting" }, "begin");
62
- const outcome = await client.createTransaction();
82
+ const outcome = await invokeClient(() => client.createTransaction());
63
83
  if (!outcome.ok) {
64
84
  fail(outcome.error);
65
85
  return outcome;
@@ -74,12 +94,15 @@ export const createSignInFlow = (client) => {
74
94
  };
75
95
  const sendEmailCode = async (email) => {
76
96
  const flowState = snapshot.state;
97
+ const pendingError = pendingActionError();
98
+ if (pendingError !== null)
99
+ return pendingError;
77
100
  if (flowState.step !== "awaiting_method") {
78
101
  return invalidState("awaiting_method", flowState.step);
79
102
  }
80
103
  const state = flowState;
81
104
  async function run(challengeToken, attemptId) {
82
- const outcome = await client.startEmailOtp(state.transactionId, challengeToken === undefined ? { email } : { email, challenge_token: challengeToken });
105
+ const outcome = await invokeClient(() => client.startEmailOtp(state.transactionId, challengeToken === undefined ? { email } : { email, challenge_token: challengeToken }));
83
106
  if (attemptId !== undefined && attemptId !== challengeAttemptId) {
84
107
  return invalidState("challenge_required", snapshot.state.step);
85
108
  }
@@ -101,15 +124,18 @@ export const createSignInFlow = (client) => {
101
124
  return run(undefined, challengeAttemptId);
102
125
  };
103
126
  const resendEmailCode = async () => {
127
+ const pendingError = pendingActionError();
128
+ if (pendingError !== null)
129
+ return pendingError;
104
130
  const flowState = snapshot.state;
105
131
  if (flowState.step !== "email_challenge_sent") {
106
132
  return invalidState("email_challenge_sent", flowState.step);
107
133
  }
108
134
  const state = flowState;
109
135
  async function run(challengeToken, attemptId) {
110
- const outcome = await client.resendEmailOtp(state.transactionId, challengeToken === undefined
136
+ const outcome = await invokeClient(() => client.resendEmailOtp(state.transactionId, challengeToken === undefined
111
137
  ? { challenge_id: state.challengeId }
112
- : { challenge_id: state.challengeId, challenge_token: challengeToken });
138
+ : { challenge_id: state.challengeId, challenge_token: challengeToken }));
113
139
  if (attemptId !== undefined && attemptId !== challengeAttemptId) {
114
140
  return invalidState("challenge_required", snapshot.state.step);
115
141
  }
@@ -130,22 +156,28 @@ export const createSignInFlow = (client) => {
130
156
  return run(undefined, challengeAttemptId);
131
157
  };
132
158
  const verifyEmailCode = async (code) => {
159
+ const pendingError = pendingActionError();
160
+ if (pendingError !== null)
161
+ return pendingError;
133
162
  const state = snapshot.state;
134
163
  if (state.step !== "email_challenge_sent") {
135
164
  return invalidState("email_challenge_sent", state.step);
136
165
  }
137
166
  transition(state, "verify_email");
138
- const outcome = await client.verifyEmailOtp(state.transactionId, {
167
+ const outcome = await invokeClient(() => client.verifyEmailOtp(state.transactionId, {
139
168
  challenge_id: state.challengeId,
140
169
  code,
141
- });
170
+ }));
142
171
  if (!outcome.ok) {
143
172
  fail(outcome.error);
144
173
  return outcome;
145
174
  }
146
- return finalize(state.transactionId);
175
+ return finalize(state.transactionId, "verify_email", state);
147
176
  };
148
177
  const signInWithPasskey = async () => {
178
+ const pendingError = pendingActionError();
179
+ if (pendingError !== null)
180
+ return pendingError;
149
181
  const flowState = snapshot.state;
150
182
  if (flowState.step !== "awaiting_method") {
151
183
  return invalidState("awaiting_method", flowState.step);
@@ -157,11 +189,11 @@ export const createSignInFlow = (client) => {
157
189
  ceremony: "passkey_authentication",
158
190
  };
159
191
  async function run(challengeToken, attemptId) {
160
- const outcome = challengeToken === undefined
161
- ? await client.startPasskeyAuthentication(state.transactionId)
162
- : await client.startPasskeyAuthentication(state.transactionId, {
192
+ const outcome = await invokeClient(() => challengeToken === undefined
193
+ ? client.startPasskeyAuthentication(state.transactionId)
194
+ : client.startPasskeyAuthentication(state.transactionId, {
163
195
  challenge_token: challengeToken,
164
- });
196
+ }));
165
197
  if (attemptId !== undefined && attemptId !== challengeAttemptId) {
166
198
  return invalidState("challenge_required", snapshot.state.step);
167
199
  }
@@ -170,36 +202,47 @@ export const createSignInFlow = (client) => {
170
202
  return outcome;
171
203
  }
172
204
  pendingAdaptiveChallenge = null;
173
- return finalize(state.transactionId);
205
+ return finalize(state.transactionId, "passkey", resumeState);
174
206
  }
175
207
  transition(resumeState, "passkey");
176
208
  return run(undefined, challengeAttemptId);
177
209
  };
178
210
  const registerPasskey = async (input) => {
179
211
  const state = snapshot.state;
212
+ const pendingError = pendingActionError();
213
+ if (pendingError !== null)
214
+ return pendingError;
180
215
  if (state.step !== "awaiting_method") {
181
216
  return invalidState("awaiting_method", state.step);
182
217
  }
183
- transition({ step: "ceremony", transactionId: state.transactionId, ceremony: "passkey_registration" }, "passkey");
184
- const outcome = await client.startPasskeyRegistration(state.transactionId, input ?? {});
218
+ const resumeState = {
219
+ step: "ceremony",
220
+ transactionId: state.transactionId,
221
+ ceremony: "passkey_registration",
222
+ };
223
+ transition(resumeState, "passkey");
224
+ const outcome = await invokeClient(() => client.startPasskeyRegistration(state.transactionId, input ?? {}));
185
225
  if (!outcome.ok) {
186
226
  fail(outcome.error);
187
227
  return outcome;
188
228
  }
189
- return finalize(state.transactionId);
229
+ return finalize(state.transactionId, "passkey", resumeState);
190
230
  };
191
231
  const signInWithSocial = async (provider) => {
192
232
  const flowState = snapshot.state;
233
+ const pendingError = pendingActionError();
234
+ if (pendingError !== null)
235
+ return pendingError;
193
236
  if (flowState.step !== "awaiting_method") {
194
237
  return invalidState("awaiting_method", flowState.step);
195
238
  }
196
239
  const state = flowState;
197
240
  async function run(challengeToken, attemptId) {
198
- const outcome = challengeToken === undefined
199
- ? await client.startSocialSignIn(state.transactionId, provider)
200
- : await client.startSocialSignIn(state.transactionId, provider, {
241
+ const outcome = await invokeClient(() => challengeToken === undefined
242
+ ? client.startSocialSignIn(state.transactionId, provider)
243
+ : client.startSocialSignIn(state.transactionId, provider, {
201
244
  challenge_token: challengeToken,
202
- });
245
+ }));
203
246
  if (attemptId !== undefined && attemptId !== challengeAttemptId) {
204
247
  return invalidState("challenge_required", snapshot.state.step);
205
248
  }
@@ -207,10 +250,24 @@ export const createSignInFlow = (client) => {
207
250
  handleOperationFailure(outcome.error, "social_start", state, "social", run);
208
251
  return outcome;
209
252
  }
210
- pendingAdaptiveChallenge = null;
211
- // Success = the browser is navigating away (top-level redirect). The flow
212
- // intentionally stays at method selection until the page reloads.
213
- transition(state);
253
+ // Clear pending if navigation is aborted, or when restored from bfcache.
254
+ transition(state, "social");
255
+ if (typeof window !== "undefined") {
256
+ let timeoutId;
257
+ const clearSocialPending = () => {
258
+ window.removeEventListener("pageshow", resetOnBackForwardCacheRestore);
259
+ clearTimeout(timeoutId);
260
+ if (attemptId === challengeAttemptId && snapshot.pendingAction === "social") {
261
+ transition(snapshot.state);
262
+ }
263
+ };
264
+ const resetOnBackForwardCacheRestore = (event) => {
265
+ if (event.persisted)
266
+ clearSocialPending();
267
+ };
268
+ timeoutId = setTimeout(clearSocialPending, SOCIAL_REDIRECT_PENDING_TIMEOUT_MS);
269
+ window.addEventListener("pageshow", resetOnBackForwardCacheRestore);
270
+ }
214
271
  return ok({ redirected: true });
215
272
  }
216
273
  transition(state, "social");
@@ -244,7 +301,7 @@ export const createSignInFlow = (client) => {
244
301
  return ok({ cancelled: true });
245
302
  }
246
303
  transition(state, "cancel");
247
- const outcome = await client.cancelTransaction(transactionId);
304
+ const outcome = await invokeClient(() => client.cancelTransaction(transactionId));
248
305
  if (!outcome.ok) {
249
306
  fail(outcome.error);
250
307
  return outcome;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smartcrab/react",
3
- "version": "0.4.0-next-20261107082009",
3
+ "version": "0.4.0-next-20261111042553",
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/browser": "0.4.0-next-20261107082009"
30
+ "@smartcrab/browser": "0.4.0-next-20261111042553"
31
31
  },
32
32
  "peerDependencies": {
33
33
  "react": ">=19"
package/src/hooks.ts CHANGED
@@ -211,7 +211,8 @@ export const usePasskey = (): UsePasskeyResult => {
211
211
  isSupported: client.isPasskeySupported(),
212
212
  isCeremonyActive:
213
213
  state.step === "ceremony" ||
214
- (state.step === "challenge_required" && state.previousState.step === "ceremony"),
214
+ (state.step === "challenge_required" && state.previousState.step === "ceremony") ||
215
+ (state.step === "completing" && state.previousState?.step === "ceremony"),
215
216
  pendingAction: flowSnapshot.pendingAction,
216
217
  error: flowError(state),
217
218
  adaptiveChallenge: flowAdaptiveChallenge(state),
@@ -246,11 +247,15 @@ export const useEmailOtp = (): UseEmailOtpResult => {
246
247
  const flowSnapshot = useStoreSnapshot(flow.subscribe, flow.getSnapshot);
247
248
  return useMemo<UseEmailOtpResult>(() => {
248
249
  const state = flowSnapshot.state;
250
+ const resumableState =
251
+ state.step === "challenge_required" || state.step === "completing"
252
+ ? state.previousState
253
+ : null;
249
254
  const emailState =
250
255
  state.step === "email_challenge_sent"
251
256
  ? state
252
- : state.step === "challenge_required" && state.previousState.step === "email_challenge_sent"
253
- ? state.previousState
257
+ : resumableState?.step === "email_challenge_sent"
258
+ ? resumableState
254
259
  : null;
255
260
  return {
256
261
  challenge:
@@ -126,6 +126,49 @@ describe("createSignInFlow — state machine (design.md §16)", () => {
126
126
  });
127
127
  });
128
128
 
129
+ test("rejects a second email start while the first is pending", async () => {
130
+ const client = createFakeClient();
131
+ let resolveStart!: (outcome: Awaited<ReturnType<SignInFlowClient["startEmailOtp"]>>) => void;
132
+ const pendingStart = new Promise<Awaited<ReturnType<SignInFlowClient["startEmailOtp"]>>>(
133
+ (resolve) => {
134
+ resolveStart = resolve;
135
+ },
136
+ );
137
+ client.startEmailOtp = vi.fn(() => pendingStart);
138
+ const flow = createSignInFlow(client);
139
+ await flow.begin();
140
+
141
+ const first = flow.sendEmailCode("user@example.com");
142
+ const second = await flow.sendEmailCode("other@example.com");
143
+ expect(second).toEqual({
144
+ ok: false,
145
+ error: { type: "invalid_flow_state", expected: "no pending action", actual: "send_email" },
146
+ });
147
+ expect(client.startEmailOtp).toHaveBeenCalledTimes(1);
148
+
149
+ resolveStart(ok({ challenge_id: "chal_1", expires_at: "2026-08-05T08:05:00Z" }));
150
+ await first;
151
+ });
152
+
153
+ test("a rejected client request clears pending state", async () => {
154
+ const client = createFakeClient();
155
+ client.startEmailOtp = vi.fn<SignInFlowClient["startEmailOtp"]>(async () => {
156
+ throw new Error("request failed");
157
+ });
158
+ const flow = createSignInFlow(client);
159
+ await flow.begin();
160
+
161
+ const outcome = await flow.sendEmailCode("user@example.com");
162
+ expect(outcome).toEqual({
163
+ ok: false,
164
+ error: { type: "network_error", message: "request failed", retryable: true },
165
+ });
166
+ expect(flow.getSnapshot()).toMatchObject({
167
+ state: { step: "failed", error: { type: "network_error" } },
168
+ pendingAction: null,
169
+ });
170
+ });
171
+
129
172
  test("a failed begin lands in failed with the client error", async () => {
130
173
  const client = createFakeClient();
131
174
  client.createTransaction = vi.fn<SignInFlowClient["createTransaction"]>(async () =>
@@ -175,6 +218,88 @@ describe("createSignInFlow — state machine (design.md §16)", () => {
175
218
  expect(flow.getSnapshot().state).toEqual({ step: "signed_in", session: SESSION });
176
219
  });
177
220
 
221
+ test("keeps the email challenge and verification pending while completing", async () => {
222
+ const client = createFakeClient();
223
+ let resolveComplete!: (
224
+ outcome: Awaited<ReturnType<SignInFlowClient["completeTransaction"]>>,
225
+ ) => void;
226
+ let markCompleteStarted!: () => void;
227
+ const completeStarted = new Promise<void>((resolve) => {
228
+ markCompleteStarted = resolve;
229
+ });
230
+ const pendingCompletion = new Promise<
231
+ Awaited<ReturnType<SignInFlowClient["completeTransaction"]>>
232
+ >((resolve) => {
233
+ resolveComplete = resolve;
234
+ });
235
+ client.completeTransaction = vi.fn(() => {
236
+ markCompleteStarted();
237
+ return pendingCompletion;
238
+ });
239
+ const flow = createSignInFlow(client);
240
+ await flow.begin();
241
+ await flow.sendEmailCode("user@example.com");
242
+
243
+ const verification = flow.verifyEmailCode("123456");
244
+ await completeStarted;
245
+ expect(flow.getSnapshot()).toEqual({
246
+ state: {
247
+ step: "completing",
248
+ transactionId: TXN_ID,
249
+ previousState: {
250
+ step: "email_challenge_sent",
251
+ transactionId: TXN_ID,
252
+ challengeId: "chal_1",
253
+ email: "user@example.com",
254
+ challengeExpiresAt: "2026-08-05T08:05:00Z",
255
+ },
256
+ },
257
+ pendingAction: "verify_email",
258
+ });
259
+
260
+ resolveComplete(ok(COMPLETE));
261
+ expect(await verification).toEqual({ ok: true, value: SESSION });
262
+ });
263
+
264
+ test("keeps passkey pending while completing", async () => {
265
+ const client = createFakeClient();
266
+ let resolveComplete!: (
267
+ outcome: Awaited<ReturnType<SignInFlowClient["completeTransaction"]>>,
268
+ ) => void;
269
+ let markCompleteStarted!: () => void;
270
+ const completeStarted = new Promise<void>((resolve) => {
271
+ markCompleteStarted = resolve;
272
+ });
273
+ const pendingCompletion = new Promise<
274
+ Awaited<ReturnType<SignInFlowClient["completeTransaction"]>>
275
+ >((resolve) => {
276
+ resolveComplete = resolve;
277
+ });
278
+ client.completeTransaction = vi.fn(() => {
279
+ markCompleteStarted();
280
+ return pendingCompletion;
281
+ });
282
+ const flow = createSignInFlow(client);
283
+ await flow.begin();
284
+
285
+ const signIn = flow.signInWithPasskey();
286
+ await completeStarted;
287
+ expect(flow.getSnapshot()).toMatchObject({
288
+ state: {
289
+ step: "completing",
290
+ transactionId: TXN_ID,
291
+ previousState: {
292
+ step: "ceremony",
293
+ ceremony: "passkey_authentication",
294
+ },
295
+ },
296
+ pendingAction: "passkey",
297
+ });
298
+
299
+ resolveComplete(ok(COMPLETE));
300
+ expect(await signIn).toEqual({ ok: true, value: SESSION });
301
+ });
302
+
178
303
  test("verifyEmailCode without a challenge is a guarded caller error", async () => {
179
304
  const flow = createSignInFlow(createFakeClient());
180
305
  const outcome = await flow.verifyEmailCode("123456");
@@ -228,15 +353,80 @@ describe("createSignInFlow — state machine (design.md §16)", () => {
228
353
  expect(client.startPasskeyRegistration).toHaveBeenCalledWith(TXN_ID, { name: "MacBook" });
229
354
  });
230
355
 
231
- test("signInWithSocial stays resumable after the top-level redirect", async () => {
356
+ test("signInWithSocial stays pending through redirect and resets on bfcache restore", async () => {
232
357
  const client = createFakeClient();
233
358
  const flow = createSignInFlow(client);
234
359
  await flow.begin();
235
360
  const outcome = await flow.signInWithSocial("google");
236
361
  expect(outcome).toEqual({ ok: true, value: { redirected: true } });
237
- expect(client.startSocialSignIn).toHaveBeenCalledWith(TXN_ID, "google");
238
- // The page is navigating away; the flow remains at method selection.
239
- expect(flow.getSnapshot().state).toMatchObject({ step: "awaiting_method" });
362
+ expect(client.startSocialSignIn).toHaveBeenCalledTimes(1);
363
+ expect(flow.getSnapshot()).toMatchObject({
364
+ state: { step: "awaiting_method" },
365
+ pendingAction: "social",
366
+ });
367
+
368
+ const duplicate = await flow.signInWithSocial("google");
369
+ expect(duplicate).toEqual({
370
+ ok: false,
371
+ error: { type: "invalid_flow_state", expected: "no pending action", actual: "social" },
372
+ });
373
+ expect(client.startSocialSignIn).toHaveBeenCalledTimes(1);
374
+ });
375
+
376
+ test("clears social pending state when restored from the back-forward cache", async () => {
377
+ const pageWindow = new EventTarget();
378
+ vi.stubGlobal("window", pageWindow);
379
+ try {
380
+ const flow = createSignInFlow(createFakeClient());
381
+ await flow.begin();
382
+ await flow.signInWithSocial("google");
383
+
384
+ const pageshow = new Event("pageshow");
385
+ Object.defineProperty(pageshow, "persisted", { value: true });
386
+ pageWindow.dispatchEvent(pageshow);
387
+
388
+ expect(flow.getSnapshot()).toMatchObject({
389
+ state: { step: "awaiting_method" },
390
+ pendingAction: null,
391
+ });
392
+ } finally {
393
+ vi.unstubAllGlobals();
394
+ }
395
+ });
396
+
397
+ test("releases social pending state after the redirect fallback timeout", async () => {
398
+ vi.useFakeTimers();
399
+ const pageWindow = new EventTarget();
400
+ const removeListener = vi.spyOn(pageWindow, "removeEventListener");
401
+ vi.stubGlobal("window", pageWindow);
402
+ try {
403
+ const client = createFakeClient();
404
+ const flow = createSignInFlow(client);
405
+ await flow.begin();
406
+ await flow.signInWithSocial("google");
407
+ expect(flow.getSnapshot().pendingAction).toBe("social");
408
+
409
+ vi.advanceTimersByTime(9_999);
410
+ expect(flow.getSnapshot().pendingAction).toBe("social");
411
+ vi.advanceTimersByTime(1);
412
+ expect(flow.getSnapshot().pendingAction).toBeNull();
413
+ expect(removeListener).toHaveBeenCalledTimes(1);
414
+ expect(removeListener).toHaveBeenCalledWith("pageshow", expect.any(Function));
415
+
416
+ const retry = await flow.signInWithSocial("google");
417
+ expect(retry).toEqual({ ok: true, value: { redirected: true } });
418
+ expect(client.startSocialSignIn).toHaveBeenCalledTimes(2);
419
+ expect(flow.getSnapshot().pendingAction).toBe("social");
420
+
421
+ const pageshow = new Event("pageshow");
422
+ Object.defineProperty(pageshow, "persisted", { value: true });
423
+ pageWindow.dispatchEvent(pageshow);
424
+ expect(removeListener).toHaveBeenCalledTimes(2);
425
+ expect(flow.getSnapshot().pendingAction).toBeNull();
426
+ } finally {
427
+ vi.unstubAllGlobals();
428
+ vi.useRealTimers();
429
+ }
240
430
  });
241
431
 
242
432
  test("cancel from a live transaction calls the server and resets to idle", async () => {
@@ -74,7 +74,11 @@ export type SignInFlowState =
74
74
  | EmailChallengeSentState
75
75
  | CeremonyState
76
76
  | SignInFlowAdaptiveChallengeState
77
- | { readonly step: "completing"; readonly transactionId: string }
77
+ | {
78
+ readonly step: "completing";
79
+ readonly transactionId: string;
80
+ readonly previousState?: SignInFlowChallengeResumeState;
81
+ }
78
82
  | { readonly step: "signed_in"; readonly session: AuthenticatedSession }
79
83
  | { readonly step: "failed"; readonly error: BrowserAuthError };
80
84
 
@@ -151,6 +155,7 @@ export interface SignInFlow {
151
155
 
152
156
  const invalidState = (expected: string, actual: string): Outcome<never, SignInFlowError> =>
153
157
  err({ type: "invalid_flow_state", expected, actual });
158
+ const SOCIAL_REDIRECT_PENDING_TIMEOUT_MS = 10_000;
154
159
  type AdaptiveChallengeRetry = (
155
160
  token: string,
156
161
  attemptId: number,
@@ -178,6 +183,25 @@ export const createSignInFlow = (client: SignInFlowClient): SignInFlow => {
178
183
  listener(snapshot);
179
184
  }
180
185
  };
186
+ const pendingActionError = (): Outcome<never, SignInFlowError> | null =>
187
+ snapshot.pendingAction === null
188
+ ? null
189
+ : invalidState("no pending action", snapshot.pendingAction);
190
+
191
+ const invokeClient = async <Value>(
192
+ operation: () => Promise<Outcome<Value, BrowserAuthError>>,
193
+ ): Promise<Outcome<Value, BrowserAuthError>> => {
194
+ try {
195
+ return await operation();
196
+ } catch (cause) {
197
+ // A rejected client request must not strand the flow in a pending state.
198
+ return err<Value, BrowserAuthError>({
199
+ type: "network_error",
200
+ message: cause instanceof Error ? cause.message : "Authentication request failed",
201
+ retryable: true,
202
+ });
203
+ }
204
+ };
181
205
 
182
206
  const fail = (error: BrowserAuthError): void => {
183
207
  pendingAdaptiveChallenge = null;
@@ -215,17 +239,21 @@ export const createSignInFlow = (client: SignInFlowClient): SignInFlow => {
215
239
  /** complete → exchange, shared by every verify path (design.md §16.3). */
216
240
  const finalize = async (
217
241
  transactionId: string,
242
+ pendingAction: Exclude<PendingAction, null>,
243
+ previousState: SignInFlowChallengeResumeState,
218
244
  ): Promise<Outcome<AuthenticatedSession, SignInFlowError>> => {
219
- transition({ step: "completing", transactionId });
220
- const completed = await client.completeTransaction(transactionId);
245
+ transition({ step: "completing", transactionId, previousState }, pendingAction);
246
+ const completed = await invokeClient(() => client.completeTransaction(transactionId));
221
247
  if (!completed.ok) {
222
248
  fail(completed.error);
223
249
  return completed;
224
250
  }
225
- const exchanged = await client.exchangeAuthorizationCode({
226
- code: completed.value.authorization_code,
227
- state: completed.value.state,
228
- });
251
+ const exchanged = await invokeClient(() =>
252
+ client.exchangeAuthorizationCode({
253
+ code: completed.value.authorization_code,
254
+ state: completed.value.state,
255
+ }),
256
+ );
229
257
  if (!exchanged.ok) {
230
258
  fail(exchanged.error);
231
259
  return exchanged;
@@ -235,12 +263,14 @@ export const createSignInFlow = (client: SignInFlowClient): SignInFlow => {
235
263
  };
236
264
 
237
265
  const begin = async (): Promise<Outcome<BrowserTransaction, SignInFlowError>> => {
266
+ const pendingError = pendingActionError();
267
+ if (pendingError !== null) return pendingError;
238
268
  const { step } = snapshot.state;
239
269
  if (step !== "idle" && step !== "failed") {
240
270
  return invalidState("idle|failed", step);
241
271
  }
242
272
  transition({ step: "starting" }, "begin");
243
- const outcome = await client.createTransaction();
273
+ const outcome = await invokeClient(() => client.createTransaction());
244
274
  if (!outcome.ok) {
245
275
  fail(outcome.error);
246
276
  return outcome;
@@ -258,6 +288,9 @@ export const createSignInFlow = (client: SignInFlowClient): SignInFlow => {
258
288
  email: string,
259
289
  ): Promise<Outcome<{ challengeId: string }, SignInFlowError>> => {
260
290
  const flowState = snapshot.state;
291
+ const pendingError = pendingActionError();
292
+ if (pendingError !== null) return pendingError;
293
+
261
294
  if (flowState.step !== "awaiting_method") {
262
295
  return invalidState("awaiting_method", flowState.step);
263
296
  }
@@ -266,9 +299,11 @@ export const createSignInFlow = (client: SignInFlowClient): SignInFlow => {
266
299
  challengeToken?: string,
267
300
  attemptId?: number,
268
301
  ): Promise<Outcome<{ challengeId: string }, SignInFlowError>> {
269
- const outcome = await client.startEmailOtp(
270
- state.transactionId,
271
- challengeToken === undefined ? { email } : { email, challenge_token: challengeToken },
302
+ const outcome = await invokeClient(() =>
303
+ client.startEmailOtp(
304
+ state.transactionId,
305
+ challengeToken === undefined ? { email } : { email, challenge_token: challengeToken },
306
+ ),
272
307
  );
273
308
  if (attemptId !== undefined && attemptId !== challengeAttemptId) {
274
309
  return invalidState("challenge_required", snapshot.state.step);
@@ -292,6 +327,8 @@ export const createSignInFlow = (client: SignInFlowClient): SignInFlow => {
292
327
  };
293
328
 
294
329
  const resendEmailCode = async (): Promise<Outcome<{ challengeId: string }, SignInFlowError>> => {
330
+ const pendingError = pendingActionError();
331
+ if (pendingError !== null) return pendingError;
295
332
  const flowState = snapshot.state;
296
333
  if (flowState.step !== "email_challenge_sent") {
297
334
  return invalidState("email_challenge_sent", flowState.step);
@@ -301,11 +338,13 @@ export const createSignInFlow = (client: SignInFlowClient): SignInFlow => {
301
338
  challengeToken?: string,
302
339
  attemptId?: number,
303
340
  ): Promise<Outcome<{ challengeId: string }, SignInFlowError>> {
304
- const outcome = await client.resendEmailOtp(
305
- state.transactionId,
306
- challengeToken === undefined
307
- ? { challenge_id: state.challengeId }
308
- : { challenge_id: state.challengeId, challenge_token: challengeToken },
341
+ const outcome = await invokeClient(() =>
342
+ client.resendEmailOtp(
343
+ state.transactionId,
344
+ challengeToken === undefined
345
+ ? { challenge_id: state.challengeId }
346
+ : { challenge_id: state.challengeId, challenge_token: challengeToken },
347
+ ),
309
348
  );
310
349
  if (attemptId !== undefined && attemptId !== challengeAttemptId) {
311
350
  return invalidState("challenge_required", snapshot.state.step);
@@ -330,23 +369,30 @@ export const createSignInFlow = (client: SignInFlowClient): SignInFlow => {
330
369
  const verifyEmailCode = async (
331
370
  code: string,
332
371
  ): Promise<Outcome<AuthenticatedSession, SignInFlowError>> => {
372
+ const pendingError = pendingActionError();
373
+ if (pendingError !== null) return pendingError;
333
374
  const state = snapshot.state;
334
375
  if (state.step !== "email_challenge_sent") {
335
376
  return invalidState("email_challenge_sent", state.step);
336
377
  }
337
378
  transition(state, "verify_email");
338
- const outcome = await client.verifyEmailOtp(state.transactionId, {
339
- challenge_id: state.challengeId,
340
- code,
341
- });
379
+ const outcome = await invokeClient(() =>
380
+ client.verifyEmailOtp(state.transactionId, {
381
+ challenge_id: state.challengeId,
382
+ code,
383
+ }),
384
+ );
342
385
  if (!outcome.ok) {
343
386
  fail(outcome.error);
344
387
  return outcome;
345
388
  }
346
- return finalize(state.transactionId);
389
+ return finalize(state.transactionId, "verify_email", state);
347
390
  };
348
391
 
349
392
  const signInWithPasskey = async (): Promise<Outcome<AuthenticatedSession, SignInFlowError>> => {
393
+ const pendingError = pendingActionError();
394
+ if (pendingError !== null) return pendingError;
395
+
350
396
  const flowState = snapshot.state;
351
397
  if (flowState.step !== "awaiting_method") {
352
398
  return invalidState("awaiting_method", flowState.step);
@@ -361,12 +407,13 @@ export const createSignInFlow = (client: SignInFlowClient): SignInFlow => {
361
407
  challengeToken?: string,
362
408
  attemptId?: number,
363
409
  ): Promise<Outcome<AuthenticatedSession, SignInFlowError>> {
364
- const outcome =
410
+ const outcome = await invokeClient(() =>
365
411
  challengeToken === undefined
366
- ? await client.startPasskeyAuthentication(state.transactionId)
367
- : await client.startPasskeyAuthentication(state.transactionId, {
412
+ ? client.startPasskeyAuthentication(state.transactionId)
413
+ : client.startPasskeyAuthentication(state.transactionId, {
368
414
  challenge_token: challengeToken,
369
- });
415
+ }),
416
+ );
370
417
  if (attemptId !== undefined && attemptId !== challengeAttemptId) {
371
418
  return invalidState("challenge_required", snapshot.state.step);
372
419
  }
@@ -375,7 +422,7 @@ export const createSignInFlow = (client: SignInFlowClient): SignInFlow => {
375
422
  return outcome;
376
423
  }
377
424
  pendingAdaptiveChallenge = null;
378
- return finalize(state.transactionId);
425
+ return finalize(state.transactionId, "passkey", resumeState);
379
426
  }
380
427
  transition(resumeState, "passkey");
381
428
  return run(undefined, challengeAttemptId);
@@ -385,25 +432,35 @@ export const createSignInFlow = (client: SignInFlowClient): SignInFlow => {
385
432
  readonly name?: string;
386
433
  }): Promise<Outcome<AuthenticatedSession, SignInFlowError>> => {
387
434
  const state = snapshot.state;
435
+ const pendingError = pendingActionError();
436
+ if (pendingError !== null) return pendingError;
437
+
388
438
  if (state.step !== "awaiting_method") {
389
439
  return invalidState("awaiting_method", state.step);
390
440
  }
391
- transition(
392
- { step: "ceremony", transactionId: state.transactionId, ceremony: "passkey_registration" },
393
- "passkey",
441
+ const resumeState: CeremonyState = {
442
+ step: "ceremony",
443
+ transactionId: state.transactionId,
444
+ ceremony: "passkey_registration",
445
+ };
446
+ transition(resumeState, "passkey");
447
+ const outcome = await invokeClient(() =>
448
+ client.startPasskeyRegistration(state.transactionId, input ?? {}),
394
449
  );
395
- const outcome = await client.startPasskeyRegistration(state.transactionId, input ?? {});
396
450
  if (!outcome.ok) {
397
451
  fail(outcome.error);
398
452
  return outcome;
399
453
  }
400
- return finalize(state.transactionId);
454
+ return finalize(state.transactionId, "passkey", resumeState);
401
455
  };
402
456
 
403
457
  const signInWithSocial = async (
404
458
  provider: SocialProvider,
405
459
  ): Promise<Outcome<{ redirected: true }, SignInFlowError>> => {
406
460
  const flowState = snapshot.state;
461
+ const pendingError = pendingActionError();
462
+ if (pendingError !== null) return pendingError;
463
+
407
464
  if (flowState.step !== "awaiting_method") {
408
465
  return invalidState("awaiting_method", flowState.step);
409
466
  }
@@ -412,12 +469,13 @@ export const createSignInFlow = (client: SignInFlowClient): SignInFlow => {
412
469
  challengeToken?: string,
413
470
  attemptId?: number,
414
471
  ): Promise<Outcome<{ redirected: true }, SignInFlowError>> {
415
- const outcome =
472
+ const outcome = await invokeClient(() =>
416
473
  challengeToken === undefined
417
- ? await client.startSocialSignIn(state.transactionId, provider)
418
- : await client.startSocialSignIn(state.transactionId, provider, {
474
+ ? client.startSocialSignIn(state.transactionId, provider)
475
+ : client.startSocialSignIn(state.transactionId, provider, {
419
476
  challenge_token: challengeToken,
420
- });
477
+ }),
478
+ );
421
479
  if (attemptId !== undefined && attemptId !== challengeAttemptId) {
422
480
  return invalidState("challenge_required", snapshot.state.step);
423
481
  }
@@ -425,10 +483,23 @@ export const createSignInFlow = (client: SignInFlowClient): SignInFlow => {
425
483
  handleOperationFailure(outcome.error, "social_start", state, "social", run);
426
484
  return outcome;
427
485
  }
428
- pendingAdaptiveChallenge = null;
429
- // Success = the browser is navigating away (top-level redirect). The flow
430
- // intentionally stays at method selection until the page reloads.
431
- transition(state);
486
+ // Clear pending if navigation is aborted, or when restored from bfcache.
487
+ transition(state, "social");
488
+ if (typeof window !== "undefined") {
489
+ let timeoutId: ReturnType<typeof setTimeout>;
490
+ const clearSocialPending = (): void => {
491
+ window.removeEventListener("pageshow", resetOnBackForwardCacheRestore);
492
+ clearTimeout(timeoutId);
493
+ if (attemptId === challengeAttemptId && snapshot.pendingAction === "social") {
494
+ transition(snapshot.state);
495
+ }
496
+ };
497
+ const resetOnBackForwardCacheRestore = (event: PageTransitionEvent): void => {
498
+ if (event.persisted) clearSocialPending();
499
+ };
500
+ timeoutId = setTimeout(clearSocialPending, SOCIAL_REDIRECT_PENDING_TIMEOUT_MS);
501
+ window.addEventListener("pageshow", resetOnBackForwardCacheRestore);
502
+ }
432
503
  return ok({ redirected: true });
433
504
  }
434
505
  transition(state, "social");
@@ -469,7 +540,7 @@ export const createSignInFlow = (client: SignInFlowClient): SignInFlow => {
469
540
  return ok({ cancelled: true });
470
541
  }
471
542
  transition(state, "cancel");
472
- const outcome = await client.cancelTransaction(transactionId);
543
+ const outcome = await invokeClient(() => client.cancelTransaction(transactionId));
473
544
  if (!outcome.ok) {
474
545
  fail(outcome.error);
475
546
  return outcome;