@smartcrab/react 0.3.2 → 0.4.0-next-20261016193833
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/headless.d.ts +7 -0
- package/dist/headless.js +9 -3
- package/dist/hooks.d.ts +9 -1
- package/dist/hooks.js +33 -15
- package/dist/index.d.ts +1 -1
- package/dist/sign-in-flow.d.ts +33 -10
- package/dist/sign-in-flow.js +142 -54
- package/package.json +2 -2
- package/src/headless.tsx +26 -2
- package/src/hooks.ts +47 -15
- package/src/index.ts +3 -0
- package/src/sign-in-flow.adaptive.test.ts +374 -0
- package/src/sign-in-flow.ts +251 -78
package/src/headless.tsx
CHANGED
|
@@ -2,6 +2,7 @@ import type { AuthenticatedSession, BrowserAuthError, SocialProvider } from "@sm
|
|
|
2
2
|
import { useState } from "react";
|
|
3
3
|
import type { ReactNode } from "react";
|
|
4
4
|
import { useEmailOtp, usePasskey, useSocialSignIn } from "./hooks.js";
|
|
5
|
+
import type { SignInFlow, SignInFlowAdaptiveChallengeState } from "./sign-in-flow.js";
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* Headless UI components for the web (design.md §3.1: "React | Hooks、
|
|
@@ -27,6 +28,8 @@ export interface PasskeyButtonRenderProps {
|
|
|
27
28
|
readonly isSupported: boolean;
|
|
28
29
|
readonly pending: boolean;
|
|
29
30
|
readonly error: BrowserAuthError | null;
|
|
31
|
+
readonly adaptiveChallenge: SignInFlowAdaptiveChallengeState | null;
|
|
32
|
+
readonly retryAdaptiveChallenge: SignInFlow["retryAdaptiveChallenge"];
|
|
30
33
|
}
|
|
31
34
|
|
|
32
35
|
export interface PasskeyButtonProps {
|
|
@@ -52,6 +55,8 @@ export const PasskeyButton = ({
|
|
|
52
55
|
error,
|
|
53
56
|
signInWithPasskey,
|
|
54
57
|
registerPasskey,
|
|
58
|
+
adaptiveChallenge,
|
|
59
|
+
retryAdaptiveChallenge,
|
|
55
60
|
} = usePasskey();
|
|
56
61
|
const pending = isCeremonyActive || pendingAction === "passkey";
|
|
57
62
|
const onClick = (): void => {
|
|
@@ -69,6 +74,8 @@ export const PasskeyButton = ({
|
|
|
69
74
|
isSupported,
|
|
70
75
|
pending,
|
|
71
76
|
error,
|
|
77
|
+
adaptiveChallenge,
|
|
78
|
+
retryAdaptiveChallenge,
|
|
72
79
|
});
|
|
73
80
|
};
|
|
74
81
|
|
|
@@ -92,6 +99,8 @@ export interface EmailOtpFormRenderProps {
|
|
|
92
99
|
readonly pendingAction: "send_email" | "resend_email" | "verify_email" | null;
|
|
93
100
|
readonly error: BrowserAuthError | null;
|
|
94
101
|
/** Challenge metadata once sent (expiry drives resend cooldown UIs, design.md §18.2). */
|
|
102
|
+
readonly adaptiveChallenge: SignInFlowAdaptiveChallengeState | null;
|
|
103
|
+
readonly retryAdaptiveChallenge: SignInFlow["retryAdaptiveChallenge"];
|
|
95
104
|
readonly challengeExpiresAt: string | null;
|
|
96
105
|
}
|
|
97
106
|
|
|
@@ -106,7 +115,16 @@ export interface EmailOtpFormProps {
|
|
|
106
115
|
* All mutation goes through the render props.
|
|
107
116
|
*/
|
|
108
117
|
export const EmailOtpForm = ({ onSignedIn, children }: EmailOtpFormProps): ReactNode => {
|
|
109
|
-
const {
|
|
118
|
+
const {
|
|
119
|
+
challenge,
|
|
120
|
+
pendingAction,
|
|
121
|
+
error,
|
|
122
|
+
adaptiveChallenge,
|
|
123
|
+
retryAdaptiveChallenge,
|
|
124
|
+
send,
|
|
125
|
+
resend,
|
|
126
|
+
verify,
|
|
127
|
+
} = useEmailOtp();
|
|
110
128
|
const [email, setEmail] = useState("");
|
|
111
129
|
const [code, setCode] = useState("");
|
|
112
130
|
|
|
@@ -136,6 +154,8 @@ export const EmailOtpForm = ({ onSignedIn, children }: EmailOtpFormProps): React
|
|
|
136
154
|
? pendingAction
|
|
137
155
|
: null,
|
|
138
156
|
error,
|
|
157
|
+
adaptiveChallenge,
|
|
158
|
+
retryAdaptiveChallenge,
|
|
139
159
|
challengeExpiresAt: challenge?.expiresAt ?? null,
|
|
140
160
|
});
|
|
141
161
|
};
|
|
@@ -150,6 +170,8 @@ export interface SocialButtonsRenderProps {
|
|
|
150
170
|
readonly signIn: (provider: SocialProvider) => void;
|
|
151
171
|
readonly pending: boolean;
|
|
152
172
|
readonly error: BrowserAuthError | null;
|
|
173
|
+
readonly adaptiveChallenge: SignInFlowAdaptiveChallengeState | null;
|
|
174
|
+
readonly retryAdaptiveChallenge: SignInFlow["retryAdaptiveChallenge"];
|
|
153
175
|
}
|
|
154
176
|
|
|
155
177
|
export interface SocialButtonsProps {
|
|
@@ -160,7 +182,7 @@ export interface SocialButtonsProps {
|
|
|
160
182
|
|
|
161
183
|
/** Headless social provider list: redirect wiring only. */
|
|
162
184
|
export const SocialButtons = ({ providers, children }: SocialButtonsProps): ReactNode => {
|
|
163
|
-
const { signIn, pending, error } = useSocialSignIn();
|
|
185
|
+
const { signIn, pending, error, adaptiveChallenge, retryAdaptiveChallenge } = useSocialSignIn();
|
|
164
186
|
return children({
|
|
165
187
|
providers,
|
|
166
188
|
signIn: (provider) => {
|
|
@@ -168,5 +190,7 @@ export const SocialButtons = ({ providers, children }: SocialButtonsProps): Reac
|
|
|
168
190
|
},
|
|
169
191
|
pending,
|
|
170
192
|
error,
|
|
193
|
+
adaptiveChallenge,
|
|
194
|
+
retryAdaptiveChallenge,
|
|
171
195
|
});
|
|
172
196
|
};
|
package/src/hooks.ts
CHANGED
|
@@ -11,7 +11,12 @@ import type {
|
|
|
11
11
|
} from "@smartcrab/browser";
|
|
12
12
|
import { useEffect, useMemo, useSyncExternalStore } from "react";
|
|
13
13
|
import { useAuthContextValue } from "./context.js";
|
|
14
|
-
import type {
|
|
14
|
+
import type {
|
|
15
|
+
PendingAction,
|
|
16
|
+
SignInFlow,
|
|
17
|
+
SignInFlowAdaptiveChallengeState,
|
|
18
|
+
SignInFlowState,
|
|
19
|
+
} from "./sign-in-flow.js";
|
|
15
20
|
import type { SignInFlowError } from "./sign-in-flow.js";
|
|
16
21
|
import type { SessionListStatus } from "./sessions-controller.js";
|
|
17
22
|
import type { UserProfileStatus } from "./user-controller.js";
|
|
@@ -42,6 +47,9 @@ export const useAuthState = (): BrowserAuthSnapshot => {
|
|
|
42
47
|
const flowError = (state: SignInFlowState): BrowserAuthError | null =>
|
|
43
48
|
state.step === "failed" ? state.error : null;
|
|
44
49
|
|
|
50
|
+
const flowAdaptiveChallenge = (state: SignInFlowState): SignInFlowAdaptiveChallengeState | null =>
|
|
51
|
+
state.step === "challenge_required" ? state : null;
|
|
52
|
+
|
|
45
53
|
export interface UseAuthResult {
|
|
46
54
|
readonly snapshot: BrowserAuthSnapshot;
|
|
47
55
|
readonly isSignedIn: boolean;
|
|
@@ -49,6 +57,7 @@ export interface UseAuthResult {
|
|
|
49
57
|
readonly flowState: SignInFlowState;
|
|
50
58
|
readonly pendingAction: PendingAction;
|
|
51
59
|
readonly flowError: BrowserAuthError | null;
|
|
60
|
+
readonly adaptiveChallenge: SignInFlowAdaptiveChallengeState | null;
|
|
52
61
|
readonly begin: SignInFlow["begin"];
|
|
53
62
|
readonly sendEmailCode: SignInFlow["sendEmailCode"];
|
|
54
63
|
readonly resendEmailCode: SignInFlow["resendEmailCode"];
|
|
@@ -56,6 +65,7 @@ export interface UseAuthResult {
|
|
|
56
65
|
readonly signInWithPasskey: SignInFlow["signInWithPasskey"];
|
|
57
66
|
readonly registerPasskey: SignInFlow["registerPasskey"];
|
|
58
67
|
readonly signInWithSocial: SignInFlow["signInWithSocial"];
|
|
68
|
+
readonly retryAdaptiveChallenge: SignInFlow["retryAdaptiveChallenge"];
|
|
59
69
|
readonly cancelSignIn: SignInFlow["cancel"];
|
|
60
70
|
readonly resetSignIn: SignInFlow["reset"];
|
|
61
71
|
readonly getAccessToken: BrowserAuthClient["getAccessToken"];
|
|
@@ -78,6 +88,7 @@ export const useAuth = (): UseAuthResult => {
|
|
|
78
88
|
flowState: flowSnapshot.state,
|
|
79
89
|
pendingAction: flowSnapshot.pendingAction,
|
|
80
90
|
flowError: flowError(flowSnapshot.state),
|
|
91
|
+
adaptiveChallenge: flowAdaptiveChallenge(flowSnapshot.state),
|
|
81
92
|
begin: flow.begin,
|
|
82
93
|
sendEmailCode: flow.sendEmailCode,
|
|
83
94
|
resendEmailCode: flow.resendEmailCode,
|
|
@@ -88,6 +99,7 @@ export const useAuth = (): UseAuthResult => {
|
|
|
88
99
|
cancelSignIn: flow.cancel,
|
|
89
100
|
resetSignIn: flow.reset,
|
|
90
101
|
getAccessToken: client.getAccessToken,
|
|
102
|
+
retryAdaptiveChallenge: flow.retryAdaptiveChallenge,
|
|
91
103
|
refreshSession: client.refreshSession,
|
|
92
104
|
restoreSession: client.restoreSession,
|
|
93
105
|
signOut: client.signOut,
|
|
@@ -181,6 +193,8 @@ export interface UsePasskeyResult {
|
|
|
181
193
|
readonly isCeremonyActive: boolean;
|
|
182
194
|
readonly pendingAction: PendingAction;
|
|
183
195
|
readonly error: BrowserAuthError | null;
|
|
196
|
+
readonly adaptiveChallenge: SignInFlowAdaptiveChallengeState | null;
|
|
197
|
+
readonly retryAdaptiveChallenge: SignInFlow["retryAdaptiveChallenge"];
|
|
184
198
|
readonly signInWithPasskey: () => Promise<Outcome<AuthenticatedSession, SignInFlowError>>;
|
|
185
199
|
readonly registerPasskey: (input?: {
|
|
186
200
|
readonly name?: string;
|
|
@@ -191,17 +205,21 @@ export interface UsePasskeyResult {
|
|
|
191
205
|
export const usePasskey = (): UsePasskeyResult => {
|
|
192
206
|
const { client, flow } = useAuthContextValue();
|
|
193
207
|
const flowSnapshot = useStoreSnapshot(flow.subscribe, flow.getSnapshot);
|
|
194
|
-
return useMemo<UsePasskeyResult>(
|
|
195
|
-
|
|
208
|
+
return useMemo<UsePasskeyResult>(() => {
|
|
209
|
+
const state = flowSnapshot.state;
|
|
210
|
+
return {
|
|
196
211
|
isSupported: client.isPasskeySupported(),
|
|
197
|
-
isCeremonyActive:
|
|
212
|
+
isCeremonyActive:
|
|
213
|
+
state.step === "ceremony" ||
|
|
214
|
+
(state.step === "challenge_required" && state.previousState.step === "ceremony"),
|
|
198
215
|
pendingAction: flowSnapshot.pendingAction,
|
|
199
|
-
error: flowError(
|
|
216
|
+
error: flowError(state),
|
|
217
|
+
adaptiveChallenge: flowAdaptiveChallenge(state),
|
|
218
|
+
retryAdaptiveChallenge: flow.retryAdaptiveChallenge,
|
|
200
219
|
signInWithPasskey: flow.signInWithPasskey,
|
|
201
220
|
registerPasskey: flow.registerPasskey,
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
);
|
|
221
|
+
};
|
|
222
|
+
}, [client, flow, flowSnapshot]);
|
|
205
223
|
};
|
|
206
224
|
|
|
207
225
|
export interface EmailOtpChallenge {
|
|
@@ -215,6 +233,8 @@ export interface UseEmailOtpResult {
|
|
|
215
233
|
readonly challenge: EmailOtpChallenge | null;
|
|
216
234
|
readonly pendingAction: PendingAction;
|
|
217
235
|
readonly error: BrowserAuthError | null;
|
|
236
|
+
readonly adaptiveChallenge: SignInFlowAdaptiveChallengeState | null;
|
|
237
|
+
readonly retryAdaptiveChallenge: SignInFlow["retryAdaptiveChallenge"];
|
|
218
238
|
readonly send: (email: string) => Promise<Outcome<{ challengeId: string }, SignInFlowError>>;
|
|
219
239
|
readonly resend: () => Promise<Outcome<{ challengeId: string }, SignInFlowError>>;
|
|
220
240
|
readonly verify: (code: string) => Promise<Outcome<AuthenticatedSession, SignInFlowError>>;
|
|
@@ -226,17 +246,25 @@ export const useEmailOtp = (): UseEmailOtpResult => {
|
|
|
226
246
|
const flowSnapshot = useStoreSnapshot(flow.subscribe, flow.getSnapshot);
|
|
227
247
|
return useMemo<UseEmailOtpResult>(() => {
|
|
228
248
|
const state = flowSnapshot.state;
|
|
249
|
+
const emailState =
|
|
250
|
+
state.step === "email_challenge_sent"
|
|
251
|
+
? state
|
|
252
|
+
: state.step === "challenge_required" && state.previousState.step === "email_challenge_sent"
|
|
253
|
+
? state.previousState
|
|
254
|
+
: null;
|
|
229
255
|
return {
|
|
230
256
|
challenge:
|
|
231
|
-
|
|
232
|
-
?
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
257
|
+
emailState === null
|
|
258
|
+
? null
|
|
259
|
+
: {
|
|
260
|
+
challengeId: emailState.challengeId,
|
|
261
|
+
email: emailState.email,
|
|
262
|
+
expiresAt: emailState.challengeExpiresAt,
|
|
263
|
+
},
|
|
238
264
|
pendingAction: flowSnapshot.pendingAction,
|
|
239
265
|
error: flowError(state),
|
|
266
|
+
adaptiveChallenge: flowAdaptiveChallenge(state),
|
|
267
|
+
retryAdaptiveChallenge: flow.retryAdaptiveChallenge,
|
|
240
268
|
send: flow.sendEmailCode,
|
|
241
269
|
resend: flow.resendEmailCode,
|
|
242
270
|
verify: flow.verifyEmailCode,
|
|
@@ -250,6 +278,8 @@ export interface UseSocialSignInResult {
|
|
|
250
278
|
) => Promise<Outcome<{ redirected: true }, SignInFlowError>>;
|
|
251
279
|
readonly pending: boolean;
|
|
252
280
|
readonly error: BrowserAuthError | null;
|
|
281
|
+
readonly adaptiveChallenge: SignInFlowAdaptiveChallengeState | null;
|
|
282
|
+
readonly retryAdaptiveChallenge: SignInFlow["retryAdaptiveChallenge"];
|
|
253
283
|
}
|
|
254
284
|
|
|
255
285
|
/** Social sign-in via top-level redirect (design.md §21.4 `useSocialSignIn`, §20). */
|
|
@@ -261,6 +291,8 @@ export const useSocialSignIn = (): UseSocialSignInResult => {
|
|
|
261
291
|
signIn: flow.signInWithSocial,
|
|
262
292
|
pending: flowSnapshot.pendingAction === "social",
|
|
263
293
|
error: flowError(flowSnapshot.state),
|
|
294
|
+
adaptiveChallenge: flowAdaptiveChallenge(flowSnapshot.state),
|
|
295
|
+
retryAdaptiveChallenge: flow.retryAdaptiveChallenge,
|
|
264
296
|
}),
|
|
265
297
|
[flow, flowSnapshot],
|
|
266
298
|
);
|
package/src/index.ts
CHANGED
|
@@ -50,6 +50,9 @@ export type {
|
|
|
50
50
|
SignInFlowListener,
|
|
51
51
|
SignInFlowSnapshot,
|
|
52
52
|
SignInFlowState,
|
|
53
|
+
SignInFlowAdaptiveChallengeResult,
|
|
54
|
+
SignInFlowAdaptiveChallengeState,
|
|
55
|
+
SignInFlowChallengeResumeState,
|
|
53
56
|
} from "./sign-in-flow.js";
|
|
54
57
|
export { createUserProfileController } from "./user-controller.js";
|
|
55
58
|
export type {
|
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
import { describe, expect, test } from "vitest";
|
|
2
|
+
import type {
|
|
3
|
+
AdaptiveChallengeAction,
|
|
4
|
+
BrowserAuthClientConfig,
|
|
5
|
+
WebAuthnBrowserPort,
|
|
6
|
+
} from "@smartcrab/browser";
|
|
7
|
+
import { createBrowserAuthClient, err, ok } from "@smartcrab/browser";
|
|
8
|
+
import { createSignInFlow } from "./index.js";
|
|
9
|
+
import type { SignInFlow } from "./sign-in-flow.js";
|
|
10
|
+
|
|
11
|
+
const BASE_URL = "https://id.example.com";
|
|
12
|
+
const ISSUER = `${BASE_URL}/e/env_abcdefghij`;
|
|
13
|
+
const CLIENT_ID = `cli_${"a".repeat(32)}`;
|
|
14
|
+
const TRANSACTION_ID = `txn_${"b".repeat(32)}`;
|
|
15
|
+
const TRANSACTION_SECRET = "s".repeat(43);
|
|
16
|
+
const AUTHORIZATION_CODE = `ac_${"g".repeat(32)}`;
|
|
17
|
+
const REDIRECT_URI = "https://app.example.com/oauth/callback";
|
|
18
|
+
const PASSKEY_ASSERTION = {
|
|
19
|
+
id: "Y3JlZA",
|
|
20
|
+
rawId: "Y3JlZA",
|
|
21
|
+
type: "public-key",
|
|
22
|
+
response: { clientDataJSON: "Y2xpZW50", authenticatorData: "YXV0aA", signature: "c2ln" },
|
|
23
|
+
} as const;
|
|
24
|
+
|
|
25
|
+
interface CapturedRequest {
|
|
26
|
+
readonly url: string;
|
|
27
|
+
readonly body: unknown;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface HarnessOptions {
|
|
31
|
+
readonly challengeResponse?: (request: CapturedRequest, attempt: number) => Response | undefined;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const jsonResponse = (status: number, body: unknown): Response =>
|
|
35
|
+
new Response(JSON.stringify(body), { status });
|
|
36
|
+
|
|
37
|
+
const adaptiveChallengeResponse = (
|
|
38
|
+
action: AdaptiveChallengeAction,
|
|
39
|
+
challengeId: string,
|
|
40
|
+
): Response =>
|
|
41
|
+
jsonResponse(403, {
|
|
42
|
+
type: "https://docs.zeroword.smartcrab.ai/errors/adaptive-challenge-required",
|
|
43
|
+
title: "Forbidden",
|
|
44
|
+
status: 403,
|
|
45
|
+
code: "adaptive_challenge_required",
|
|
46
|
+
request_id: "req_challenge",
|
|
47
|
+
challenge_id: challengeId,
|
|
48
|
+
site_key: "0x4AAAAA-public",
|
|
49
|
+
action,
|
|
50
|
+
transaction_id: TRANSACTION_ID,
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
const createHarness = (options: HarnessOptions = {}) => {
|
|
54
|
+
const calls: CapturedRequest[] = [];
|
|
55
|
+
const attempts = new Map<string, number>();
|
|
56
|
+
const redirects: string[] = [];
|
|
57
|
+
const fetchPort: NonNullable<BrowserAuthClientConfig["fetch"]> = async (url, init) => {
|
|
58
|
+
const request: CapturedRequest = {
|
|
59
|
+
url,
|
|
60
|
+
body:
|
|
61
|
+
typeof init.body === "string" &&
|
|
62
|
+
new Headers(init.headers).get("content-type")?.includes("application/json")
|
|
63
|
+
? JSON.parse(init.body)
|
|
64
|
+
: undefined,
|
|
65
|
+
};
|
|
66
|
+
calls.push(request);
|
|
67
|
+
const path = new URL(url).pathname;
|
|
68
|
+
const attempt = (attempts.get(path) ?? 0) + 1;
|
|
69
|
+
attempts.set(path, attempt);
|
|
70
|
+
const challenged = options.challengeResponse?.(request, attempt);
|
|
71
|
+
if (challenged !== undefined) return challenged;
|
|
72
|
+
|
|
73
|
+
if (path === "/v1/auth/transactions") {
|
|
74
|
+
return jsonResponse(200, {
|
|
75
|
+
transaction_id: TRANSACTION_ID,
|
|
76
|
+
transaction_secret: TRANSACTION_SECRET,
|
|
77
|
+
expires_at: new Date(Date.now() + 10 * 60_000).toISOString(),
|
|
78
|
+
available_methods: ["passkey", "email_otp", "google"],
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
if (path.endsWith("/email/start")) {
|
|
82
|
+
return jsonResponse(200, {
|
|
83
|
+
challenge_id: `otp_${attempt}`,
|
|
84
|
+
expires_at: new Date(Date.now() + 5 * 60_000).toISOString(),
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
if (path.endsWith("/email/resend")) {
|
|
88
|
+
return jsonResponse(200, {
|
|
89
|
+
challenge_id: `otp_resend_${attempt}`,
|
|
90
|
+
expires_at: new Date(Date.now() + 5 * 60_000).toISOString(),
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
if (path.endsWith("/passkeys/authentication/options")) {
|
|
94
|
+
return jsonResponse(200, {
|
|
95
|
+
challenge: "Y2hhbGxlbmdl",
|
|
96
|
+
rpId: "example.com",
|
|
97
|
+
userVerification: "required",
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
if (path.endsWith("/passkeys/authentication/verify")) {
|
|
101
|
+
return jsonResponse(200, { transaction_id: TRANSACTION_ID, status: "authenticated" });
|
|
102
|
+
}
|
|
103
|
+
if (path.endsWith("/social/google/start")) {
|
|
104
|
+
return jsonResponse(200, { authorization_url: "https://accounts.google.com/authorize" });
|
|
105
|
+
}
|
|
106
|
+
if (path.endsWith("/complete")) {
|
|
107
|
+
const transactionRequest = calls.find(
|
|
108
|
+
(item) => new URL(item.url).pathname === "/v1/auth/transactions",
|
|
109
|
+
);
|
|
110
|
+
const state = (transactionRequest?.body as Record<string, unknown> | undefined)?.["state"];
|
|
111
|
+
return jsonResponse(200, {
|
|
112
|
+
authorization_code: AUTHORIZATION_CODE,
|
|
113
|
+
state,
|
|
114
|
+
redirect_uri: REDIRECT_URI,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
if (path === "/e/env_abcdefghij/oauth2/token") {
|
|
118
|
+
return jsonResponse(200, {
|
|
119
|
+
access_token: "access-token-for-test",
|
|
120
|
+
token_type: "Bearer",
|
|
121
|
+
expires_in: 300,
|
|
122
|
+
scope: "openid profile email",
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
if (path.endsWith("/cancel")) {
|
|
126
|
+
return jsonResponse(200, { transaction_id: TRANSACTION_ID, status: "failed" });
|
|
127
|
+
}
|
|
128
|
+
return jsonResponse(404, {
|
|
129
|
+
type: "https://docs.zeroword.smartcrab.ai/errors/not-found",
|
|
130
|
+
title: "Not Found",
|
|
131
|
+
status: 404,
|
|
132
|
+
code: "not_found",
|
|
133
|
+
});
|
|
134
|
+
};
|
|
135
|
+
const webAuthn: WebAuthnBrowserPort = {
|
|
136
|
+
isAvailable: () => true,
|
|
137
|
+
create: async () => err({ type: "webauthn_error", reason: "failed", message: "unused" }),
|
|
138
|
+
get: async () => ok(PASSKEY_ASSERTION),
|
|
139
|
+
};
|
|
140
|
+
const client = createBrowserAuthClient({
|
|
141
|
+
baseUrl: BASE_URL,
|
|
142
|
+
issuer: ISSUER,
|
|
143
|
+
clientId: CLIENT_ID,
|
|
144
|
+
redirectUri: REDIRECT_URI,
|
|
145
|
+
fetch: fetchPort,
|
|
146
|
+
webAuthn,
|
|
147
|
+
redirect: { assign: (url) => redirects.push(url) },
|
|
148
|
+
});
|
|
149
|
+
return { calls, attempts, redirects, flow: createSignInFlow(client) };
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const begin = async (flow: SignInFlow): Promise<void> => {
|
|
153
|
+
const outcome = await flow.begin();
|
|
154
|
+
expect(outcome.ok).toBe(true);
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
describe("createSignInFlow adaptive challenge replay through the public browser transport", () => {
|
|
158
|
+
test("retains email-start transaction and payload across a new challenge response", async () => {
|
|
159
|
+
const harness = createHarness({
|
|
160
|
+
challengeResponse: (request, attempt) =>
|
|
161
|
+
new URL(request.url).pathname.endsWith("/email/start") && attempt <= 2
|
|
162
|
+
? adaptiveChallengeResponse("email_start", `challenge_${attempt}`)
|
|
163
|
+
: undefined,
|
|
164
|
+
});
|
|
165
|
+
await begin(harness.flow);
|
|
166
|
+
|
|
167
|
+
const rejected = await harness.flow.sendEmailCode("user@example.com");
|
|
168
|
+
expect(rejected.ok).toBe(false);
|
|
169
|
+
expect(harness.flow.getSnapshot().state).toMatchObject({
|
|
170
|
+
step: "challenge_required",
|
|
171
|
+
challengeId: "challenge_1",
|
|
172
|
+
siteKey: "0x4AAAAA-public",
|
|
173
|
+
action: "email_start",
|
|
174
|
+
transactionId: TRANSACTION_ID,
|
|
175
|
+
previousState: { step: "awaiting_method", transactionId: TRANSACTION_ID },
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
const expiredProof = await harness.flow.retryAdaptiveChallenge("expired-proof");
|
|
179
|
+
expect(expiredProof.ok).toBe(false);
|
|
180
|
+
expect(harness.flow.getSnapshot().state).toMatchObject({
|
|
181
|
+
step: "challenge_required",
|
|
182
|
+
challengeId: "challenge_2",
|
|
183
|
+
action: "email_start",
|
|
184
|
+
});
|
|
185
|
+
expect(
|
|
186
|
+
harness.calls.filter((request) => new URL(request.url).pathname.endsWith("/email/start")),
|
|
187
|
+
).toEqual([
|
|
188
|
+
expect.objectContaining({ body: { email: "user@example.com" } }),
|
|
189
|
+
expect.objectContaining({
|
|
190
|
+
body: { email: "user@example.com", challenge_token: "expired-proof" },
|
|
191
|
+
}),
|
|
192
|
+
]);
|
|
193
|
+
|
|
194
|
+
const resumed = await harness.flow.retryAdaptiveChallenge("fresh-proof");
|
|
195
|
+
expect(resumed).toEqual({ ok: true, value: { challengeId: "otp_3" } });
|
|
196
|
+
expect(harness.flow.getSnapshot().state).toMatchObject({
|
|
197
|
+
step: "email_challenge_sent",
|
|
198
|
+
transactionId: TRANSACTION_ID,
|
|
199
|
+
email: "user@example.com",
|
|
200
|
+
});
|
|
201
|
+
expect(
|
|
202
|
+
harness.calls.filter((request) =>
|
|
203
|
+
new URL(request.url).pathname.endsWith("/v1/auth/transactions"),
|
|
204
|
+
),
|
|
205
|
+
).toHaveLength(1);
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
test("retains resend payload and preserves the existing email challenge state", async () => {
|
|
209
|
+
const harness = createHarness({
|
|
210
|
+
challengeResponse: (request, attempt) =>
|
|
211
|
+
new URL(request.url).pathname.endsWith("/email/resend") && attempt === 1
|
|
212
|
+
? adaptiveChallengeResponse("email_resend", "resend-proof-required")
|
|
213
|
+
: undefined,
|
|
214
|
+
});
|
|
215
|
+
await begin(harness.flow);
|
|
216
|
+
await harness.flow.sendEmailCode("user@example.com");
|
|
217
|
+
|
|
218
|
+
const rejected = await harness.flow.resendEmailCode();
|
|
219
|
+
expect(rejected.ok).toBe(false);
|
|
220
|
+
expect(harness.flow.getSnapshot().state).toMatchObject({
|
|
221
|
+
step: "challenge_required",
|
|
222
|
+
action: "email_resend",
|
|
223
|
+
previousState: {
|
|
224
|
+
step: "email_challenge_sent",
|
|
225
|
+
challengeId: "otp_1",
|
|
226
|
+
email: "user@example.com",
|
|
227
|
+
},
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
const resumed = await harness.flow.retryAdaptiveChallenge("resend-proof");
|
|
231
|
+
expect(resumed).toEqual({ ok: true, value: { challengeId: "otp_resend_2" } });
|
|
232
|
+
expect(
|
|
233
|
+
harness.calls.filter((request) => new URL(request.url).pathname.endsWith("/email/resend")),
|
|
234
|
+
).toEqual([
|
|
235
|
+
expect.objectContaining({ body: { challenge_id: "otp_1" } }),
|
|
236
|
+
expect.objectContaining({ body: { challenge_id: "otp_1", challenge_token: "resend-proof" } }),
|
|
237
|
+
]);
|
|
238
|
+
expect(harness.flow.getSnapshot().state).toMatchObject({
|
|
239
|
+
step: "email_challenge_sent",
|
|
240
|
+
challengeId: "otp_resend_2",
|
|
241
|
+
email: "user@example.com",
|
|
242
|
+
});
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
test("restarts the original passkey ceremony after challenge proof", async () => {
|
|
246
|
+
const harness = createHarness({
|
|
247
|
+
challengeResponse: (request, attempt) =>
|
|
248
|
+
new URL(request.url).pathname.endsWith("/passkeys/authentication/options") && attempt === 1
|
|
249
|
+
? adaptiveChallengeResponse("passkey_auth_options", "passkey-proof-required")
|
|
250
|
+
: undefined,
|
|
251
|
+
});
|
|
252
|
+
await begin(harness.flow);
|
|
253
|
+
|
|
254
|
+
const rejected = await harness.flow.signInWithPasskey();
|
|
255
|
+
expect(rejected.ok).toBe(false);
|
|
256
|
+
expect(harness.flow.getSnapshot().state).toMatchObject({
|
|
257
|
+
step: "challenge_required",
|
|
258
|
+
action: "passkey_auth_options",
|
|
259
|
+
previousState: { step: "ceremony", ceremony: "passkey_authentication" },
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
const resumed = await harness.flow.retryAdaptiveChallenge("passkey-proof");
|
|
263
|
+
expect(resumed).toMatchObject({ ok: true, value: { scope: "openid profile email" } });
|
|
264
|
+
expect(
|
|
265
|
+
harness.calls.filter((request) =>
|
|
266
|
+
new URL(request.url).pathname.endsWith("/passkeys/authentication/options"),
|
|
267
|
+
),
|
|
268
|
+
).toEqual([
|
|
269
|
+
expect.objectContaining({ body: {} }),
|
|
270
|
+
expect.objectContaining({ body: { challenge_token: "passkey-proof" } }),
|
|
271
|
+
]);
|
|
272
|
+
expect(
|
|
273
|
+
harness.calls.some((request) =>
|
|
274
|
+
new URL(request.url).pathname.endsWith("/passkeys/authentication/verify"),
|
|
275
|
+
),
|
|
276
|
+
).toBe(true);
|
|
277
|
+
expect(harness.flow.getSnapshot().state.step).toBe("signed_in");
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
test("retains social provider and transaction until proof-bearing redirect starts", async () => {
|
|
281
|
+
const harness = createHarness({
|
|
282
|
+
challengeResponse: (request, attempt) =>
|
|
283
|
+
new URL(request.url).pathname.endsWith("/social/google/start") && attempt === 1
|
|
284
|
+
? adaptiveChallengeResponse("social_start", "social-proof-required")
|
|
285
|
+
: undefined,
|
|
286
|
+
});
|
|
287
|
+
await begin(harness.flow);
|
|
288
|
+
|
|
289
|
+
const rejected = await harness.flow.signInWithSocial("google");
|
|
290
|
+
expect(rejected.ok).toBe(false);
|
|
291
|
+
expect(harness.flow.getSnapshot().state).toMatchObject({
|
|
292
|
+
step: "challenge_required",
|
|
293
|
+
action: "social_start",
|
|
294
|
+
previousState: { step: "awaiting_method", transactionId: TRANSACTION_ID },
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
const resumed = await harness.flow.retryAdaptiveChallenge("social-proof");
|
|
298
|
+
expect(resumed).toEqual({ ok: true, value: { redirected: true } });
|
|
299
|
+
expect(
|
|
300
|
+
harness.calls.filter((request) =>
|
|
301
|
+
new URL(request.url).pathname.endsWith("/social/google/start"),
|
|
302
|
+
),
|
|
303
|
+
).toEqual([
|
|
304
|
+
expect.objectContaining({ body: {} }),
|
|
305
|
+
expect.objectContaining({ body: { challenge_token: "social-proof" } }),
|
|
306
|
+
]);
|
|
307
|
+
expect(harness.redirects).toEqual(["https://accounts.google.com/authorize"]);
|
|
308
|
+
expect(harness.flow.getSnapshot().state.step).toBe("awaiting_method");
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
test("cancels the retained challenged transaction and disallows later proof retry", async () => {
|
|
312
|
+
const harness = createHarness({
|
|
313
|
+
challengeResponse: (request) =>
|
|
314
|
+
new URL(request.url).pathname.endsWith("/email/start")
|
|
315
|
+
? adaptiveChallengeResponse("email_start", "cancel-proof-required")
|
|
316
|
+
: undefined,
|
|
317
|
+
});
|
|
318
|
+
await begin(harness.flow);
|
|
319
|
+
await harness.flow.sendEmailCode("user@example.com");
|
|
320
|
+
|
|
321
|
+
const cancelled = await harness.flow.cancel();
|
|
322
|
+
expect(cancelled).toEqual({ ok: true, value: { cancelled: true } });
|
|
323
|
+
expect(
|
|
324
|
+
harness.calls.filter((request) => new URL(request.url).pathname.endsWith("/cancel")),
|
|
325
|
+
).toEqual([expect.objectContaining({ url: expect.stringContaining(TRANSACTION_ID) })]);
|
|
326
|
+
expect(harness.flow.getSnapshot().state).toEqual({ step: "idle" });
|
|
327
|
+
expect(await harness.flow.retryAdaptiveChallenge("proof")).toMatchObject({
|
|
328
|
+
ok: false,
|
|
329
|
+
error: { type: "invalid_flow_state", expected: "challenge_required", actual: "idle" },
|
|
330
|
+
});
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
test.each([
|
|
334
|
+
{
|
|
335
|
+
status: 429,
|
|
336
|
+
body: {
|
|
337
|
+
type: "https://docs.zeroword.smartcrab.ai/errors/rate-limited",
|
|
338
|
+
title: "Too Many Requests",
|
|
339
|
+
status: 429,
|
|
340
|
+
code: "rate_limited",
|
|
341
|
+
request_id: "req_rate_limited",
|
|
342
|
+
},
|
|
343
|
+
},
|
|
344
|
+
{
|
|
345
|
+
status: 503,
|
|
346
|
+
body: {
|
|
347
|
+
type: "https://docs.zeroword.smartcrab.ai/errors/adaptive-challenge-unavailable",
|
|
348
|
+
title: "Service Unavailable",
|
|
349
|
+
status: 503,
|
|
350
|
+
code: "adaptive_challenge_unavailable",
|
|
351
|
+
request_id: "req_challenge_unavailable",
|
|
352
|
+
},
|
|
353
|
+
},
|
|
354
|
+
])("does not turn HTTP $status into a challenge retry", async ({ status, body }) => {
|
|
355
|
+
const harness = createHarness({
|
|
356
|
+
challengeResponse: (request) =>
|
|
357
|
+
new URL(request.url).pathname.endsWith("/email/start")
|
|
358
|
+
? jsonResponse(status, body)
|
|
359
|
+
: undefined,
|
|
360
|
+
});
|
|
361
|
+
await begin(harness.flow);
|
|
362
|
+
|
|
363
|
+
const outcome = await harness.flow.sendEmailCode("user@example.com");
|
|
364
|
+
expect(outcome.ok).toBe(false);
|
|
365
|
+
expect(harness.flow.getSnapshot().state.step).toBe("failed");
|
|
366
|
+
expect(await harness.flow.retryAdaptiveChallenge("proof")).toMatchObject({
|
|
367
|
+
ok: false,
|
|
368
|
+
error: { type: "invalid_flow_state", expected: "challenge_required", actual: "failed" },
|
|
369
|
+
});
|
|
370
|
+
expect(
|
|
371
|
+
harness.calls.filter((request) => new URL(request.url).pathname.endsWith("/email/start")),
|
|
372
|
+
).toHaveLength(1);
|
|
373
|
+
});
|
|
374
|
+
});
|