@smartcrab/browser 0.3.2 → 0.4.0-next-20261017141739
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/base64url.d.ts +1 -9
- package/dist/base64url.js +11 -41
- package/dist/client.d.ts +14 -3
- package/dist/client.js +272 -18
- package/dist/errors.d.ts +14 -1
- package/dist/http.d.ts +1 -0
- package/dist/http.js +15 -0
- package/dist/index.d.ts +2 -2
- package/dist/pkce.js +1 -2
- package/package.json +2 -2
- package/src/base64url.ts +11 -41
- package/src/client-me.test.ts +520 -17
- package/src/client.test.ts +13 -5
- package/src/client.ts +354 -21
- package/src/errors.ts +18 -1
- package/src/http.ts +17 -0
- package/src/index.ts +5 -0
- package/src/pkce.ts +1 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@smartcrab/browser",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0-next-20261017141739",
|
|
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.
|
|
30
|
+
"@smartcrab/contracts-public": "0.4.0-next-20261017141739"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"typescript": "5.9.3",
|
package/src/base64url.ts
CHANGED
|
@@ -1,46 +1,16 @@
|
|
|
1
|
-
/**
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
* alphabet math would widen the published dependency surface for no
|
|
8
|
-
* behavioral gain. Implementations are byte-for-byte compatible.
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
const BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
12
|
-
|
|
13
|
-
export const base64UrlEncodeBytes = (bytes: Uint8Array): string => {
|
|
14
|
-
let out = "";
|
|
15
|
-
for (let i = 0; i < bytes.length; i += 3) {
|
|
16
|
-
const b0 = bytes[i] ?? 0;
|
|
17
|
-
const b1 = bytes[i + 1];
|
|
18
|
-
const b2 = bytes[i + 2];
|
|
19
|
-
out += BASE64URL_ALPHABET[b0 >> 2] ?? "";
|
|
20
|
-
out += BASE64URL_ALPHABET[((b0 & 0x03) << 4) | ((b1 ?? 0) >> 4)] ?? "";
|
|
21
|
-
if (b1 !== undefined) out += BASE64URL_ALPHABET[((b1 & 0x0f) << 2) | ((b2 ?? 0) >> 6)] ?? "";
|
|
22
|
-
if (b2 !== undefined) out += BASE64URL_ALPHABET[b2 & 0x3f] ?? "";
|
|
23
|
-
}
|
|
24
|
-
return out;
|
|
25
|
-
};
|
|
1
|
+
/** Local base64url (RFC 4648 §5, no padding) helpers. */
|
|
2
|
+
export const base64UrlEncodeBytes = (bytes: Uint8Array): string =>
|
|
3
|
+
btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join(""))
|
|
4
|
+
.replaceAll("+", "-")
|
|
5
|
+
.replaceAll("/", "_")
|
|
6
|
+
.replace(/=+$/, "");
|
|
26
7
|
|
|
27
8
|
export const base64UrlDecodeToBytes = (encoded: string): Uint8Array => {
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
if (index < 0) {
|
|
34
|
-
throw new Error(`Invalid base64url character: ${char}`);
|
|
35
|
-
}
|
|
36
|
-
buffer = (buffer << 6) | index;
|
|
37
|
-
bits += 6;
|
|
38
|
-
if (bits >= 8) {
|
|
39
|
-
bits -= 8;
|
|
40
|
-
out.push((buffer >>> bits) & 0xff);
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
return new Uint8Array(out);
|
|
9
|
+
const invalid = /[^A-Za-z0-9_-]/u.exec(encoded);
|
|
10
|
+
if (invalid !== null) throw new Error(`Invalid base64url character: ${invalid[0]}`);
|
|
11
|
+
const complete = encoded.length % 4 === 1 ? encoded.slice(0, -1) : encoded;
|
|
12
|
+
const standard = complete.replaceAll("-", "+").replaceAll("_", "/");
|
|
13
|
+
return Uint8Array.from(atob(standard), (char) => char.charCodeAt(0));
|
|
44
14
|
};
|
|
45
15
|
|
|
46
16
|
export const bufferToBase64Url = (buffer: ArrayBuffer): string =>
|
package/src/client-me.test.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import { describe, expect, test } from "vitest";
|
|
1
|
+
import { afterEach, describe, expect, test, vi } from "vitest";
|
|
2
|
+
import { base64UrlEncodeBytes } from "./base64url.js";
|
|
2
3
|
import { createBrowserAuthClient } from "./client.js";
|
|
4
|
+
import type { BrowserAuthClientConfig, RefreshTokenStoragePort } from "./client.js";
|
|
3
5
|
import type { FetchPort } from "./http.js";
|
|
4
6
|
|
|
5
7
|
/**
|
|
@@ -93,7 +95,7 @@ const createStub = (onMe: (req: CapturedRequest) => Response) => {
|
|
|
93
95
|
}),
|
|
94
96
|
);
|
|
95
97
|
}
|
|
96
|
-
if (url.endsWith("/complete")) {
|
|
98
|
+
if (url.includes("/v1/auth/transactions/") && url.endsWith("/complete")) {
|
|
97
99
|
const state = (
|
|
98
100
|
calls.find((c) => c.url.endsWith("/v1/auth/transactions"))?.body as Record<string, unknown>
|
|
99
101
|
)["state"];
|
|
@@ -107,6 +109,7 @@ const createStub = (onMe: (req: CapturedRequest) => Response) => {
|
|
|
107
109
|
access_token: "at_me",
|
|
108
110
|
token_type: "Bearer",
|
|
109
111
|
expires_in: 300,
|
|
112
|
+
refresh_token: "rt_me",
|
|
110
113
|
scope: "openid profile email",
|
|
111
114
|
}),
|
|
112
115
|
);
|
|
@@ -116,13 +119,17 @@ const createStub = (onMe: (req: CapturedRequest) => Response) => {
|
|
|
116
119
|
return { calls, fetchPort };
|
|
117
120
|
};
|
|
118
121
|
|
|
119
|
-
const createSignedInClient = async (
|
|
122
|
+
const createSignedInClient = async (
|
|
123
|
+
fetchPort: FetchPort,
|
|
124
|
+
overrides: Partial<BrowserAuthClientConfig> = {},
|
|
125
|
+
) => {
|
|
120
126
|
const client = createBrowserAuthClient({
|
|
121
127
|
baseUrl: BASE_URL,
|
|
122
128
|
clientId: CLIENT_ID,
|
|
123
129
|
redirectUri: REDIRECT_URI,
|
|
124
130
|
issuer: ISSUER,
|
|
125
131
|
fetch: fetchPort,
|
|
132
|
+
...overrides,
|
|
126
133
|
});
|
|
127
134
|
const created = await client.createTransaction();
|
|
128
135
|
if (!created.ok) throw new Error("setup failed");
|
|
@@ -136,6 +143,42 @@ const createSignedInClient = async (fetchPort: FetchPort) => {
|
|
|
136
143
|
return client;
|
|
137
144
|
};
|
|
138
145
|
|
|
146
|
+
afterEach(() => vi.unstubAllGlobals());
|
|
147
|
+
|
|
148
|
+
const createSessionStorage = () => {
|
|
149
|
+
const entries = new Map<string, string>();
|
|
150
|
+
return {
|
|
151
|
+
entries,
|
|
152
|
+
port: {
|
|
153
|
+
getItem: (key: string) => entries.get(key) ?? null,
|
|
154
|
+
setItem: (key: string, value: string) => {
|
|
155
|
+
entries.set(key, value);
|
|
156
|
+
},
|
|
157
|
+
removeItem: (key: string) => {
|
|
158
|
+
entries.delete(key);
|
|
159
|
+
},
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
const createRefreshStorage = () => {
|
|
165
|
+
let refreshToken: string | null = null;
|
|
166
|
+
const port: RefreshTokenStoragePort = {
|
|
167
|
+
load: () => refreshToken,
|
|
168
|
+
save: (token) => {
|
|
169
|
+
refreshToken = token;
|
|
170
|
+
},
|
|
171
|
+
clear: () => {
|
|
172
|
+
refreshToken = null;
|
|
173
|
+
},
|
|
174
|
+
};
|
|
175
|
+
return {
|
|
176
|
+
port,
|
|
177
|
+
get token() {
|
|
178
|
+
return refreshToken;
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
};
|
|
139
182
|
describe("/v1/me surface (design.md §16.2)", () => {
|
|
140
183
|
test("getMe sends the Bearer token and parses the profile", async () => {
|
|
141
184
|
const { calls, fetchPort } = createStub(() => jsonResponse(200, ME_USER));
|
|
@@ -165,6 +208,63 @@ describe("/v1/me surface (design.md §16.2)", () => {
|
|
|
165
208
|
if (!outcome.ok) expect(outcome.error.type).toBe("invalid_response");
|
|
166
209
|
});
|
|
167
210
|
|
|
211
|
+
test("adaptive challenge errors remain typed and the caller token is sent on the same OTP request", async () => {
|
|
212
|
+
let startAttempts = 0;
|
|
213
|
+
const { calls, fetchPort } = createStub((req) => {
|
|
214
|
+
if (req.url.endsWith("/email/start")) {
|
|
215
|
+
startAttempts += 1;
|
|
216
|
+
if (startAttempts === 1) {
|
|
217
|
+
return jsonResponse(403, {
|
|
218
|
+
type: "https://docs.zeroword.smartcrab.ai/errors/adaptive-challenge-required",
|
|
219
|
+
title: "Forbidden",
|
|
220
|
+
status: 403,
|
|
221
|
+
code: "adaptive_challenge_required",
|
|
222
|
+
request_id: "req_challenge",
|
|
223
|
+
challenge_id: "chlg_opaque",
|
|
224
|
+
site_key: "0x4AAAAA-public",
|
|
225
|
+
action: "email_start",
|
|
226
|
+
transaction_id: TXN_ID,
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
return jsonResponse(202, {
|
|
230
|
+
challenge_id: "email-challenge",
|
|
231
|
+
expires_at: "2026-08-05T08:15:00Z",
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
return jsonResponse(200, ME_USER);
|
|
235
|
+
});
|
|
236
|
+
const client = await createSignedInClient(fetchPort);
|
|
237
|
+
const transaction = await client.createTransaction();
|
|
238
|
+
expect(transaction.ok).toBe(true);
|
|
239
|
+
if (!transaction.ok) return;
|
|
240
|
+
const first = await client.startEmailOtp(transaction.value.transactionId, {
|
|
241
|
+
email: "user@example.com",
|
|
242
|
+
});
|
|
243
|
+
expect(first).toMatchObject({
|
|
244
|
+
ok: false,
|
|
245
|
+
error: {
|
|
246
|
+
type: "adaptive_challenge_required",
|
|
247
|
+
challengeId: "chlg_opaque",
|
|
248
|
+
siteKey: "0x4AAAAA-public",
|
|
249
|
+
action: "email_start",
|
|
250
|
+
transactionId: TXN_ID,
|
|
251
|
+
requestId: "req_challenge",
|
|
252
|
+
},
|
|
253
|
+
});
|
|
254
|
+
const retried = await client.startEmailOtp(transaction.value.transactionId, {
|
|
255
|
+
email: "user@example.com",
|
|
256
|
+
challenge_token: "turnstile-response-token",
|
|
257
|
+
});
|
|
258
|
+
expect(retried.ok).toBe(true);
|
|
259
|
+
const callsToStart = calls.filter((c) => c.url.endsWith("/email/start"));
|
|
260
|
+
expect(callsToStart).toHaveLength(2);
|
|
261
|
+
expect(callsToStart[0]?.body).toEqual({ email: "user@example.com" });
|
|
262
|
+
expect(callsToStart[1]?.body).toEqual({
|
|
263
|
+
email: "user@example.com",
|
|
264
|
+
challenge_token: "turnstile-response-token",
|
|
265
|
+
});
|
|
266
|
+
});
|
|
267
|
+
|
|
168
268
|
test("passkey list / register-verify / delete hit the contract routes", async () => {
|
|
169
269
|
const { calls, fetchPort } = createStub((req) => {
|
|
170
270
|
if (req.url.endsWith("/v1/me/passkeys"))
|
|
@@ -202,30 +302,91 @@ describe("/v1/me surface (design.md §16.2)", () => {
|
|
|
202
302
|
expect(deleteCall?.method).toBe("DELETE");
|
|
203
303
|
});
|
|
204
304
|
|
|
205
|
-
test("
|
|
305
|
+
test("identity linking persists PKCE state across reload and completes only after callback state matches", async () => {
|
|
306
|
+
const session = createSessionStorage();
|
|
307
|
+
vi.stubGlobal("sessionStorage", session.port);
|
|
308
|
+
const refreshStorage = createRefreshStorage();
|
|
309
|
+
const redirect = { assign: vi.fn() };
|
|
310
|
+
let persistedBeforeBegin = false;
|
|
206
311
|
const { calls, fetchPort } = createStub((req) => {
|
|
207
|
-
if (req.url.endsWith("/v1/me/identities"))
|
|
312
|
+
if (req.url.endsWith("/v1/me/identities")) {
|
|
208
313
|
return jsonResponse(200, { identities: [IDENTITY_SUMMARY] });
|
|
209
|
-
if (req.url.endsWith("/link")) {
|
|
210
|
-
return jsonResponse(200, {
|
|
211
|
-
authorization_url: "https://accounts.google.com/o/oauth2/v2/auth?x=1",
|
|
212
|
-
});
|
|
213
314
|
}
|
|
214
|
-
|
|
315
|
+
if (req.url.endsWith("/link/complete")) {
|
|
316
|
+
return jsonResponse(200, { identity_id: IDENTITY_ID });
|
|
317
|
+
}
|
|
318
|
+
if (req.url.endsWith("/v1/me/identities/google/link")) {
|
|
319
|
+
const state = (req.body as Record<string, unknown>)["state"];
|
|
320
|
+
persistedBeforeBegin =
|
|
321
|
+
typeof state === "string" &&
|
|
322
|
+
session.entries.has(`@smartcrab/browser:identity-link:${state}`);
|
|
323
|
+
return jsonResponse(200, { authorization_url: "https://accounts.google.com/authorize" });
|
|
324
|
+
}
|
|
325
|
+
if (req.method === "DELETE") {
|
|
326
|
+
return jsonResponse(200, { identity_id: IDENTITY_ID, unlinked: true });
|
|
327
|
+
}
|
|
328
|
+
return jsonResponse(200, ME_USER);
|
|
329
|
+
});
|
|
330
|
+
const client = await createSignedInClient(fetchPort, {
|
|
331
|
+
refreshTokenStorage: refreshStorage.port,
|
|
332
|
+
redirect,
|
|
215
333
|
});
|
|
216
|
-
const client = await createSignedInClient(fetchPort);
|
|
217
334
|
|
|
218
335
|
const list = await client.listMyIdentities();
|
|
219
336
|
expect(list.ok).toBe(true);
|
|
220
337
|
if (list.ok) expect(list.value.identities[0]?.provider).toBe("google");
|
|
221
338
|
|
|
222
|
-
const linked = await client.linkMyIdentity("google"
|
|
223
|
-
redirect_uri: "https://app.example.com/settings",
|
|
224
|
-
});
|
|
339
|
+
const linked = await client.linkMyIdentity("google");
|
|
225
340
|
expect(linked.ok).toBe(true);
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
expect(
|
|
341
|
+
if (!linked.ok) return;
|
|
342
|
+
const beginCall = calls.find((c) => c.url.endsWith("/v1/me/identities/google/link"));
|
|
343
|
+
expect(beginCall?.method).toBe("POST");
|
|
344
|
+
expect(beginCall?.body).toMatchObject({
|
|
345
|
+
redirect_uri: REDIRECT_URI,
|
|
346
|
+
code_challenge_method: "S256",
|
|
347
|
+
state: linked.value.state,
|
|
348
|
+
});
|
|
349
|
+
expect(persistedBeforeBegin).toBe(true);
|
|
350
|
+
const pendingKey = `@smartcrab/browser:identity-link:${linked.value.state}`;
|
|
351
|
+
const pending = JSON.parse(session.entries.get(pendingKey) ?? "null") as {
|
|
352
|
+
codeVerifier: string;
|
|
353
|
+
userId: string;
|
|
354
|
+
clientId: string;
|
|
355
|
+
};
|
|
356
|
+
expect(pending.userId).toBe(USER_ID);
|
|
357
|
+
expect(pending.clientId).toBe(CLIENT_ID);
|
|
358
|
+
const digest = await globalThis.crypto.subtle.digest(
|
|
359
|
+
"SHA-256",
|
|
360
|
+
new TextEncoder().encode(pending.codeVerifier),
|
|
361
|
+
);
|
|
362
|
+
expect((beginCall?.body as Record<string, unknown>)["code_challenge"]).toBe(
|
|
363
|
+
base64UrlEncodeBytes(new Uint8Array(digest)),
|
|
364
|
+
);
|
|
365
|
+
|
|
366
|
+
const reloadedClient = createBrowserAuthClient({
|
|
367
|
+
baseUrl: BASE_URL,
|
|
368
|
+
clientId: CLIENT_ID,
|
|
369
|
+
redirectUri: REDIRECT_URI,
|
|
370
|
+
issuer: ISSUER,
|
|
371
|
+
fetch: fetchPort,
|
|
372
|
+
refreshTokenStorage: refreshStorage.port,
|
|
373
|
+
});
|
|
374
|
+
const wrongState = await reloadedClient.completeMyIdentityLink(
|
|
375
|
+
"google",
|
|
376
|
+
`${REDIRECT_URI}?link_code=lc_test&state=wrong-state`,
|
|
377
|
+
);
|
|
378
|
+
expect(wrongState).toMatchObject({ ok: false, error: { type: "state_mismatch" } });
|
|
379
|
+
expect(calls.some((c) => c.url.endsWith("/link/complete"))).toBe(false);
|
|
380
|
+
|
|
381
|
+
const completed = await reloadedClient.completeMyIdentityLink(
|
|
382
|
+
"google",
|
|
383
|
+
`${REDIRECT_URI}?link_code=lc_test&state=${linked.value.state}`,
|
|
384
|
+
);
|
|
385
|
+
expect(completed).toEqual({ ok: true, value: { identity_id: IDENTITY_ID } });
|
|
386
|
+
const completeCall = calls.find((c) => c.url.endsWith("/link/complete"));
|
|
387
|
+
expect(completeCall?.body).toEqual({ code: "lc_test", code_verifier: pending.codeVerifier });
|
|
388
|
+
expect(completeCall?.headers["authorization"]).toBe("Bearer at_me");
|
|
389
|
+
expect(session.entries.has(pendingKey)).toBe(false);
|
|
229
390
|
|
|
230
391
|
const unlinked = await client.unlinkMyIdentity(IDENTITY_ID);
|
|
231
392
|
expect(unlinked.ok).toBe(true);
|
|
@@ -233,6 +394,348 @@ describe("/v1/me surface (design.md §16.2)", () => {
|
|
|
233
394
|
expect(unlinkCall?.method).toBe("DELETE");
|
|
234
395
|
});
|
|
235
396
|
|
|
397
|
+
test("identity-link continuation accepts the protocol's fifteen-minute upper bound", async () => {
|
|
398
|
+
const session = createSessionStorage();
|
|
399
|
+
vi.stubGlobal("sessionStorage", session.port);
|
|
400
|
+
const refreshStorage = createRefreshStorage();
|
|
401
|
+
const startedAt = 1_000_000;
|
|
402
|
+
let now = startedAt;
|
|
403
|
+
const { calls, fetchPort } = createStub((req) => {
|
|
404
|
+
if (req.url.endsWith("/v1/me/identities/google/link")) {
|
|
405
|
+
return jsonResponse(200, { authorization_url: "https://accounts.google.com/authorize" });
|
|
406
|
+
}
|
|
407
|
+
if (req.url.endsWith("/link/complete")) {
|
|
408
|
+
return jsonResponse(200, { identity_id: IDENTITY_ID });
|
|
409
|
+
}
|
|
410
|
+
return jsonResponse(200, ME_USER);
|
|
411
|
+
});
|
|
412
|
+
const client = await createSignedInClient(fetchPort, {
|
|
413
|
+
refreshTokenStorage: refreshStorage.port,
|
|
414
|
+
now: () => now,
|
|
415
|
+
redirect: { assign: () => {} },
|
|
416
|
+
});
|
|
417
|
+
const started = await client.linkMyIdentity("google");
|
|
418
|
+
expect(started.ok).toBe(true);
|
|
419
|
+
if (!started.ok) return;
|
|
420
|
+
|
|
421
|
+
now = startedAt + 15 * 60 * 1000 - 1;
|
|
422
|
+
const callbackClient = createBrowserAuthClient({
|
|
423
|
+
baseUrl: BASE_URL,
|
|
424
|
+
clientId: CLIENT_ID,
|
|
425
|
+
redirectUri: REDIRECT_URI,
|
|
426
|
+
issuer: ISSUER,
|
|
427
|
+
fetch: fetchPort,
|
|
428
|
+
refreshTokenStorage: refreshStorage.port,
|
|
429
|
+
now: () => now,
|
|
430
|
+
});
|
|
431
|
+
const completed = await callbackClient.completeMyIdentityLink(
|
|
432
|
+
"google",
|
|
433
|
+
`${REDIRECT_URI}?link_code=lc_test&state=${started.value.state}`,
|
|
434
|
+
);
|
|
435
|
+
expect(completed).toEqual({ ok: true, value: { identity_id: IDENTITY_ID } });
|
|
436
|
+
|
|
437
|
+
const next = await client.linkMyIdentity("google");
|
|
438
|
+
expect(next.ok).toBe(true);
|
|
439
|
+
if (!next.ok) return;
|
|
440
|
+
now += 15 * 60 * 1000 + 1;
|
|
441
|
+
const expired = await callbackClient.completeMyIdentityLink(
|
|
442
|
+
"google",
|
|
443
|
+
`${REDIRECT_URI}?link_code=lc_test&state=${next.value.state}`,
|
|
444
|
+
);
|
|
445
|
+
expect(expired).toMatchObject({ ok: false, error: { type: "state_mismatch" } });
|
|
446
|
+
expect(calls.filter((call) => call.url.endsWith("/link/complete"))).toHaveLength(1);
|
|
447
|
+
expect(session.entries.has(`@smartcrab/browser:identity-link:${next.value.state}`)).toBe(false);
|
|
448
|
+
});
|
|
449
|
+
|
|
450
|
+
test("a callback cannot complete identity linking for a different signed-in user", async () => {
|
|
451
|
+
const session = createSessionStorage();
|
|
452
|
+
vi.stubGlobal("sessionStorage", session.port);
|
|
453
|
+
const refreshStorage = createRefreshStorage();
|
|
454
|
+
let currentUser = ME_USER;
|
|
455
|
+
const { calls, fetchPort } = createStub((req) => {
|
|
456
|
+
if (req.url.endsWith("/v1/me/identities/google/link")) {
|
|
457
|
+
return jsonResponse(200, { authorization_url: "https://accounts.google.com/authorize" });
|
|
458
|
+
}
|
|
459
|
+
if (req.url.endsWith("/link/complete")) {
|
|
460
|
+
return jsonResponse(200, { identity_id: IDENTITY_ID });
|
|
461
|
+
}
|
|
462
|
+
return jsonResponse(200, currentUser);
|
|
463
|
+
});
|
|
464
|
+
const client = await createSignedInClient(fetchPort, {
|
|
465
|
+
refreshTokenStorage: refreshStorage.port,
|
|
466
|
+
redirect: { assign: () => {} },
|
|
467
|
+
});
|
|
468
|
+
const started = await client.linkMyIdentity("google");
|
|
469
|
+
expect(started.ok).toBe(true);
|
|
470
|
+
if (!started.ok) return;
|
|
471
|
+
currentUser = { ...ME_USER, user_id: `usr_${"z".repeat(32)}` };
|
|
472
|
+
|
|
473
|
+
const callbackClient = createBrowserAuthClient({
|
|
474
|
+
baseUrl: BASE_URL,
|
|
475
|
+
clientId: CLIENT_ID,
|
|
476
|
+
redirectUri: REDIRECT_URI,
|
|
477
|
+
issuer: ISSUER,
|
|
478
|
+
fetch: fetchPort,
|
|
479
|
+
refreshTokenStorage: refreshStorage.port,
|
|
480
|
+
});
|
|
481
|
+
const result = await callbackClient.completeMyIdentityLink(
|
|
482
|
+
"google",
|
|
483
|
+
`${REDIRECT_URI}?link_code=lc_test&state=${started.value.state}`,
|
|
484
|
+
);
|
|
485
|
+
expect(result).toMatchObject({ ok: false, error: { type: "state_mismatch" } });
|
|
486
|
+
expect(calls.some((call) => call.url.endsWith("/link/complete"))).toBe(false);
|
|
487
|
+
});
|
|
488
|
+
test("retryable session restoration preserves identity-link PKCE state for callback retry", async () => {
|
|
489
|
+
const session = createSessionStorage();
|
|
490
|
+
vi.stubGlobal("sessionStorage", session.port);
|
|
491
|
+
const storage = createRefreshStorage();
|
|
492
|
+
let refreshCalls = 0;
|
|
493
|
+
const { calls, fetchPort: baseFetch } = createStub((req) => {
|
|
494
|
+
if (req.url.endsWith("/v1/me/identities/google/link")) {
|
|
495
|
+
return jsonResponse(200, { authorization_url: "https://accounts.google.com/authorize" });
|
|
496
|
+
}
|
|
497
|
+
if (req.url.endsWith("/link/complete")) {
|
|
498
|
+
return jsonResponse(200, { identity_id: IDENTITY_ID });
|
|
499
|
+
}
|
|
500
|
+
return jsonResponse(200, ME_USER);
|
|
501
|
+
});
|
|
502
|
+
const fetchPort: FetchPort = (url, init) => {
|
|
503
|
+
if (url.endsWith("/oauth2/token") && typeof init.body === "string") {
|
|
504
|
+
const body = parseJson(init.body) as Record<string, unknown>;
|
|
505
|
+
if (body["grant_type"] === "refresh_token") {
|
|
506
|
+
refreshCalls += 1;
|
|
507
|
+
if (refreshCalls === 1) return Promise.reject(new TypeError("offline"));
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
return baseFetch(url, init);
|
|
511
|
+
};
|
|
512
|
+
const client = await createSignedInClient(fetchPort, {
|
|
513
|
+
refreshTokenStorage: storage.port,
|
|
514
|
+
redirect: { assign: () => {} },
|
|
515
|
+
});
|
|
516
|
+
const started = await client.linkMyIdentity("google");
|
|
517
|
+
expect(started.ok).toBe(true);
|
|
518
|
+
if (!started.ok) return;
|
|
519
|
+
const pendingKey = `@smartcrab/browser:identity-link:${started.value.state}`;
|
|
520
|
+
const pending = JSON.parse(session.entries.get(pendingKey) ?? "null") as {
|
|
521
|
+
readonly codeVerifier: string;
|
|
522
|
+
};
|
|
523
|
+
const callbackClient = createBrowserAuthClient({
|
|
524
|
+
baseUrl: BASE_URL,
|
|
525
|
+
clientId: CLIENT_ID,
|
|
526
|
+
redirectUri: REDIRECT_URI,
|
|
527
|
+
issuer: ISSUER,
|
|
528
|
+
fetch: fetchPort,
|
|
529
|
+
refreshTokenStorage: storage.port,
|
|
530
|
+
});
|
|
531
|
+
const callbackUrl = `${REDIRECT_URI}?link_code=lc_test&state=${started.value.state}`;
|
|
532
|
+
|
|
533
|
+
const firstAttempt = await callbackClient.completeMyIdentityLink("google", callbackUrl);
|
|
534
|
+
expect(firstAttempt).toMatchObject({ ok: false, error: { type: "network_error" } });
|
|
535
|
+
expect(session.entries.has(pendingKey)).toBe(true);
|
|
536
|
+
expect(calls.some((call) => call.url.endsWith("/link/complete"))).toBe(false);
|
|
537
|
+
|
|
538
|
+
const retry = await callbackClient.completeMyIdentityLink("google", callbackUrl);
|
|
539
|
+
expect(retry).toEqual({ ok: true, value: { identity_id: IDENTITY_ID } });
|
|
540
|
+
expect(refreshCalls).toBe(2);
|
|
541
|
+
expect(session.entries.has(pendingKey)).toBe(false);
|
|
542
|
+
expect(calls.find((call) => call.url.endsWith("/link/complete"))?.body).toEqual({
|
|
543
|
+
code: "lc_test",
|
|
544
|
+
code_verifier: pending.codeVerifier,
|
|
545
|
+
});
|
|
546
|
+
});
|
|
547
|
+
|
|
548
|
+
test("confirmed recovery sends a stable operation key and clears local refresh state", async () => {
|
|
549
|
+
const storage = createRefreshStorage();
|
|
550
|
+
const { calls, fetchPort } = createStub((req) => {
|
|
551
|
+
if (req.url.endsWith("/v1/me/recovery/complete")) {
|
|
552
|
+
return jsonResponse(200, { recovered: true, reauthentication_required: true });
|
|
553
|
+
}
|
|
554
|
+
return jsonResponse(200, ME_USER);
|
|
555
|
+
});
|
|
556
|
+
const client = await createSignedInClient(fetchPort, { refreshTokenStorage: storage.port });
|
|
557
|
+
const snapshots: string[] = [];
|
|
558
|
+
client.subscribe((snapshot) => snapshots.push(snapshot.status));
|
|
559
|
+
|
|
560
|
+
const result = await client.completeMyRecovery({ idempotencyKey: "recovery-operation-1" });
|
|
561
|
+
expect(result).toEqual({
|
|
562
|
+
ok: true,
|
|
563
|
+
value: { recovered: true, reauthentication_required: true },
|
|
564
|
+
});
|
|
565
|
+
const call = calls.find((request) => request.url.endsWith("/v1/me/recovery/complete"));
|
|
566
|
+
expect(call?.method).toBe("POST");
|
|
567
|
+
expect(call?.body).toEqual({ confirmed: true });
|
|
568
|
+
expect(call?.headers["idempotency-key"]).toBe("recovery-operation-1");
|
|
569
|
+
expect(storage.token).toBeNull();
|
|
570
|
+
expect(client.getSnapshot().status).toBe("signed_out");
|
|
571
|
+
expect(snapshots).toContain("signed_out");
|
|
572
|
+
});
|
|
573
|
+
|
|
574
|
+
test("recovery errors preserve the active local session", async () => {
|
|
575
|
+
const storage = createRefreshStorage();
|
|
576
|
+
const { fetchPort } = createStub((req) => {
|
|
577
|
+
if (req.url.endsWith("/v1/me/recovery/complete")) {
|
|
578
|
+
return jsonResponse(401, {
|
|
579
|
+
type: "https://docs.zeroword.smartcrab.ai/errors/recovery-reauthentication-required",
|
|
580
|
+
title: "Unauthorized",
|
|
581
|
+
status: 401,
|
|
582
|
+
code: "recovery_reauthentication_required",
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
return jsonResponse(200, ME_USER);
|
|
586
|
+
});
|
|
587
|
+
const client = await createSignedInClient(fetchPort, { refreshTokenStorage: storage.port });
|
|
588
|
+
|
|
589
|
+
const result = await client.completeMyRecovery({ idempotencyKey: "recovery-operation-2" });
|
|
590
|
+
expect(result).toMatchObject({
|
|
591
|
+
ok: false,
|
|
592
|
+
error: { type: "problem_details", code: "recovery_reauthentication_required" },
|
|
593
|
+
});
|
|
594
|
+
expect(storage.token).toBe("rt_me");
|
|
595
|
+
expect(client.getSnapshot().status).toBe("signed_in");
|
|
596
|
+
});
|
|
597
|
+
test("confirmed recovery discards an in-flight refresh response", async () => {
|
|
598
|
+
const storage = createRefreshStorage();
|
|
599
|
+
const { calls, fetchPort: baseFetch } = createStub((req) =>
|
|
600
|
+
req.url.endsWith("/v1/me/recovery/complete")
|
|
601
|
+
? jsonResponse(200, { recovered: true, reauthentication_required: true })
|
|
602
|
+
: jsonResponse(200, ME_USER),
|
|
603
|
+
);
|
|
604
|
+
let markRefreshStarted!: () => void;
|
|
605
|
+
const refreshStarted = new Promise<void>((resolve) => {
|
|
606
|
+
markRefreshStarted = resolve;
|
|
607
|
+
});
|
|
608
|
+
let releaseRefresh!: (response: Response) => void;
|
|
609
|
+
const delayedRefresh = new Promise<Response>((resolve) => {
|
|
610
|
+
releaseRefresh = resolve;
|
|
611
|
+
});
|
|
612
|
+
const fetchPort: FetchPort = (url, init) => {
|
|
613
|
+
if (url.endsWith("/oauth2/token") && typeof init.body === "string") {
|
|
614
|
+
const body = parseJson(init.body) as Record<string, unknown>;
|
|
615
|
+
if (body["grant_type"] === "refresh_token") {
|
|
616
|
+
markRefreshStarted();
|
|
617
|
+
return delayedRefresh;
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
return baseFetch(url, init);
|
|
621
|
+
};
|
|
622
|
+
const client = await createSignedInClient(fetchPort, { refreshTokenStorage: storage.port });
|
|
623
|
+
const snapshots: string[] = [];
|
|
624
|
+
client.subscribe((snapshot) => snapshots.push(snapshot.status));
|
|
625
|
+
|
|
626
|
+
const refresh = client.refreshSession();
|
|
627
|
+
await refreshStarted;
|
|
628
|
+
const recovered = await client.completeMyRecovery({ idempotencyKey: "recovery-race-1" });
|
|
629
|
+
expect(recovered.ok).toBe(true);
|
|
630
|
+
expect(client.getSnapshot().status).toBe("signed_out");
|
|
631
|
+
expect(storage.token).toBeNull();
|
|
632
|
+
const snapshotsAtRecovery = snapshots.length;
|
|
633
|
+
|
|
634
|
+
releaseRefresh(
|
|
635
|
+
jsonResponse(200, {
|
|
636
|
+
access_token: "at_rotated",
|
|
637
|
+
token_type: "Bearer",
|
|
638
|
+
expires_in: 300,
|
|
639
|
+
refresh_token: "rt_rotated",
|
|
640
|
+
scope: "openid profile email",
|
|
641
|
+
}),
|
|
642
|
+
);
|
|
643
|
+
expect(await refresh).toEqual({ ok: false, error: { type: "not_authenticated" } });
|
|
644
|
+
expect(client.getSnapshot().status).toBe("signed_out");
|
|
645
|
+
expect(storage.token).toBeNull();
|
|
646
|
+
expect(snapshots.slice(snapshotsAtRecovery)).not.toContain("signed_in");
|
|
647
|
+
expect(calls.some((call) => call.url.endsWith("/v1/me/recovery/complete"))).toBe(true);
|
|
648
|
+
});
|
|
649
|
+
|
|
650
|
+
test("confirmed recovery waits for an already-started refresh-token save before clearing", async () => {
|
|
651
|
+
const storage = createRefreshStorage();
|
|
652
|
+
const { fetchPort: baseFetch } = createStub((req) =>
|
|
653
|
+
req.url.endsWith("/v1/me/recovery/complete")
|
|
654
|
+
? jsonResponse(200, { recovered: true, reauthentication_required: true })
|
|
655
|
+
: jsonResponse(200, ME_USER),
|
|
656
|
+
);
|
|
657
|
+
const fetchPort: FetchPort = (url, init) => {
|
|
658
|
+
if (url.endsWith("/oauth2/token") && typeof init.body === "string") {
|
|
659
|
+
const body = parseJson(init.body) as Record<string, unknown>;
|
|
660
|
+
if (body["grant_type"] === "refresh_token") {
|
|
661
|
+
return Promise.resolve(
|
|
662
|
+
jsonResponse(200, {
|
|
663
|
+
access_token: "at_rotated",
|
|
664
|
+
token_type: "Bearer",
|
|
665
|
+
expires_in: 300,
|
|
666
|
+
refresh_token: "rt_rotated",
|
|
667
|
+
scope: "openid profile email",
|
|
668
|
+
}),
|
|
669
|
+
);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
return baseFetch(url, init);
|
|
673
|
+
};
|
|
674
|
+
const client = await createSignedInClient(fetchPort, { refreshTokenStorage: storage.port });
|
|
675
|
+
const originalSave = storage.port.save;
|
|
676
|
+
let markSaveStarted!: () => void;
|
|
677
|
+
const saveStarted = new Promise<void>((resolve) => {
|
|
678
|
+
markSaveStarted = resolve;
|
|
679
|
+
});
|
|
680
|
+
let releaseSave!: () => void;
|
|
681
|
+
const delayedSave = new Promise<void>((resolve) => {
|
|
682
|
+
releaseSave = resolve;
|
|
683
|
+
});
|
|
684
|
+
storage.port.save = (token) => {
|
|
685
|
+
if (token === "rt_rotated") {
|
|
686
|
+
markSaveStarted();
|
|
687
|
+
return delayedSave;
|
|
688
|
+
}
|
|
689
|
+
return originalSave(token);
|
|
690
|
+
};
|
|
691
|
+
|
|
692
|
+
const refresh = client.refreshSession();
|
|
693
|
+
await saveStarted;
|
|
694
|
+
const snapshots: string[] = [];
|
|
695
|
+
let markSignedOut!: () => void;
|
|
696
|
+
const signedOutNotified = new Promise<void>((resolve) => {
|
|
697
|
+
markSignedOut = resolve;
|
|
698
|
+
});
|
|
699
|
+
client.subscribe((snapshot) => {
|
|
700
|
+
snapshots.push(snapshot.status);
|
|
701
|
+
if (snapshot.status === "signed_out") markSignedOut();
|
|
702
|
+
});
|
|
703
|
+
let recoverySettled = false;
|
|
704
|
+
const recovery = client
|
|
705
|
+
.completeMyRecovery({ idempotencyKey: "recovery-race-2" })
|
|
706
|
+
.then((result) => {
|
|
707
|
+
recoverySettled = true;
|
|
708
|
+
return result;
|
|
709
|
+
});
|
|
710
|
+
await signedOutNotified;
|
|
711
|
+
expect(recoverySettled).toBe(false);
|
|
712
|
+
const snapshotsAtRecovery = snapshots.length;
|
|
713
|
+
|
|
714
|
+
releaseSave();
|
|
715
|
+
expect(await refresh).toEqual({ ok: false, error: { type: "not_authenticated" } });
|
|
716
|
+
expect((await recovery).ok).toBe(true);
|
|
717
|
+
expect(storage.token).toBeNull();
|
|
718
|
+
expect(client.getSnapshot().status).toBe("signed_out");
|
|
719
|
+
expect(snapshots.slice(snapshotsAtRecovery)).not.toContain("signed_in");
|
|
720
|
+
});
|
|
721
|
+
|
|
722
|
+
test("recovery reports refresh-storage cleanup failure while remaining locally signed out", async () => {
|
|
723
|
+
const storage = createRefreshStorage();
|
|
724
|
+
storage.port.clear = () => Promise.reject(new Error("storage unavailable"));
|
|
725
|
+
const { fetchPort } = createStub((req) =>
|
|
726
|
+
req.url.endsWith("/v1/me/recovery/complete")
|
|
727
|
+
? jsonResponse(200, { recovered: true, reauthentication_required: true })
|
|
728
|
+
: jsonResponse(200, ME_USER),
|
|
729
|
+
);
|
|
730
|
+
const client = await createSignedInClient(fetchPort, { refreshTokenStorage: storage.port });
|
|
731
|
+
|
|
732
|
+
const result = await client.completeMyRecovery({ idempotencyKey: "recovery-cleanup-failure" });
|
|
733
|
+
|
|
734
|
+
expect(result).toMatchObject({ ok: false, error: { type: "storage_error" } });
|
|
735
|
+
expect(client.getSnapshot().status).toBe("signed_out");
|
|
736
|
+
expect(storage.token).toBe("rt_me");
|
|
737
|
+
});
|
|
738
|
+
|
|
236
739
|
test("sessions list / revoke / revoke-all", async () => {
|
|
237
740
|
const { calls, fetchPort } = createStub((req) => {
|
|
238
741
|
if (req.url.endsWith("/v1/me/sessions") && req.method === "GET") {
|