create-ailk 0.35.1 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +1 -1
  2. package/component-catalog.json +12 -1
  3. package/component-catalog.md +6 -5
  4. package/dist/lib/env-catalog.js +8 -0
  5. package/dist/surfaces.js +6 -3
  6. package/dist/topology.d.ts +4 -4
  7. package/dist/topology.js +104 -60
  8. package/package.json +3 -3
  9. package/templates/.env.example +21 -0
  10. package/templates/apps/api/.env.example +7 -0
  11. package/templates/apps/api/CLAUDE.md +9 -4
  12. package/templates/apps/mcp/CLAUDE.md +4 -2
  13. package/templates/apps/web/.env.example +16 -0
  14. package/templates/apps/web/CLAUDE.md +46 -5
  15. package/templates/apps/web/app/[locale]/(auth)/__tests__/password-reset.test.tsx +2 -0
  16. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/page.test.tsx +52 -1
  17. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/remembered-method.test.ts +43 -0
  18. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/sign-in-card.test.tsx +108 -1
  19. package/templates/apps/web/app/[locale]/(auth)/sign-in/page.tsx +36 -3
  20. package/templates/apps/web/app/[locale]/(auth)/sign-in/remembered-method.ts +37 -0
  21. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-card.tsx +90 -33
  22. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-text.ts +9 -4
  23. package/templates/apps/web/app/[locale]/(authed)/__tests__/gate.test.tsx +79 -348
  24. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/billing.test.tsx +12 -1
  25. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +55 -2
  26. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout-sign-out.test.tsx +10 -5
  27. package/templates/apps/web/app/[locale]/(authed)/account/account-frame.tsx +1 -1
  28. package/templates/apps/web/app/[locale]/(authed)/account/billing/page.tsx +60 -6
  29. package/templates/apps/web/app/[locale]/(authed)/account/billing-source.ts +32 -3
  30. package/templates/apps/web/app/[locale]/(authed)/account/connect/__tests__/page.test.tsx +8 -1
  31. package/templates/apps/web/app/[locale]/(authed)/account/connect/page.tsx +7 -3
  32. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/phone-verification.test.tsx +215 -0
  33. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/seam-imports.test.ts +65 -0
  34. package/templates/apps/web/app/[locale]/(authed)/account/general/page.tsx +47 -0
  35. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-actions.ts +122 -0
  36. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-verification.tsx +214 -0
  37. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/invitation-id.test.ts +35 -0
  38. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/page.test.tsx +266 -0
  39. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/actions.ts +116 -0
  40. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/invitation-id.ts +12 -0
  41. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/page.tsx +154 -0
  42. package/templates/apps/web/app/[locale]/(authed)/account/layout.tsx +6 -4
  43. package/templates/apps/web/app/[locale]/(authed)/account/security/page.tsx +3 -1
  44. package/templates/apps/web/app/[locale]/(authed)/layout.tsx +15 -13
  45. package/templates/apps/web/app/[locale]/(authed)/signed-out-gate.generated.tsx +20 -52
  46. package/templates/apps/web/app/[locale]/layout.tsx +24 -75
  47. package/templates/apps/web/app/[locale]/purchase/__tests__/success.test.tsx +50 -0
  48. package/templates/apps/web/app/[locale]/purchase/success/page.tsx +48 -7
  49. package/templates/apps/web/app/api/auth/hub/__tests__/entry-routes.test.ts +749 -0
  50. package/templates/apps/web/app/api/auth/hub/authorize/__tests__/route.test.ts +166 -7
  51. package/templates/apps/web/app/api/auth/hub/authorize/route.ts +96 -30
  52. package/templates/apps/web/app/api/auth/hub/continuation.ts +51 -2
  53. package/templates/apps/web/app/api/auth/hub/email/route.ts +111 -0
  54. package/templates/apps/web/app/api/auth/hub/entry-shared.ts +163 -0
  55. package/templates/apps/web/app/api/auth/hub/purchase/route.ts +230 -0
  56. package/templates/apps/web/app/api/auth/hub/purchase-link/route.ts +174 -0
  57. package/templates/apps/web/app/api/auth/hub/sign-up/route.ts +60 -0
  58. package/templates/apps/web/app/api/auth/hub/sign-up-evidence.ts +97 -0
  59. package/templates/apps/web/app/api/hub-session/__tests__/routes.test.ts +475 -7
  60. package/templates/apps/web/app/api/hub-session/callback/route.ts +13 -47
  61. package/templates/apps/web/app/api/hub-session/email/route.ts +125 -0
  62. package/templates/apps/web/app/api/hub-session/one-tap/nonce/route.ts +49 -0
  63. package/templates/apps/web/app/api/hub-session/one-tap/route.ts +106 -0
  64. package/templates/apps/web/app/api/hub-session/open/route.ts +111 -0
  65. package/templates/apps/web/app/api/hub-session/sign-in/route.ts +23 -40
  66. package/templates/apps/web/app/api/hub-session/sign-out/route.ts +1 -10
  67. package/templates/apps/web/auth.ts +133 -6
  68. package/templates/apps/web/components/sign-out-trigger.tsx +1 -1
  69. package/templates/apps/web/lib/__tests__/auth-email.test.ts +141 -0
  70. package/templates/apps/web/lib/__tests__/auth-phone.test.ts +445 -0
  71. package/templates/apps/web/lib/__tests__/auth-sms.test.ts +140 -0
  72. package/templates/apps/web/lib/__tests__/fixtures/tsconfig.flow.json +18 -0
  73. package/templates/apps/web/lib/__tests__/site-header.test.ts +13 -0
  74. package/templates/apps/web/lib/__tests__/telemetry-scrub.test.ts +19 -1
  75. package/templates/apps/web/lib/auth-email.ts +62 -6
  76. package/templates/apps/web/lib/auth-env.ts +13 -0
  77. package/templates/apps/web/lib/auth-sms.ts +180 -0
  78. package/templates/apps/web/lib/hub-session/__tests__/hub-session.test.ts +28 -0
  79. package/templates/apps/web/lib/hub-session/__tests__/spoke-sign-in.test.tsx +332 -0
  80. package/templates/apps/web/lib/hub-session/config.ts +7 -1
  81. package/templates/apps/web/lib/hub-session/entry.ts +238 -0
  82. package/templates/apps/web/lib/hub-session/index.ts +1 -4
  83. package/templates/apps/web/lib/hub-session/one-tap.tsx +148 -0
  84. package/templates/apps/web/lib/hub-session/session.ts +120 -2
  85. package/templates/apps/web/lib/hub-session/spoke-sign-in.tsx +277 -0
  86. package/templates/apps/web/lib/site-header.ts +14 -1
  87. package/templates/apps/web/lib/telemetry-scrub.ts +11 -0
  88. package/templates/apps/web/lib/topology.generated.ts +39 -0
  89. package/templates/apps/web/messages/en.json +112 -20
  90. package/templates/apps/web/middleware.ts +34 -2
  91. package/templates/apps/web/security-headers.config.ts +21 -0
  92. package/versions.json +47 -47
  93. package/templates/apps/web/app/[locale]/(authed)/sign-in-gate.tsx +0 -162
  94. package/templates/apps/web/components/signed-in-nav.tsx +0 -79
  95. package/templates/apps/web/lib/hub-session/__tests__/sign-in-gate.test.tsx +0 -180
  96. package/templates/apps/web/lib/hub-session/sign-in-gate.tsx +0 -162
@@ -0,0 +1,97 @@
1
+ /**
2
+ * The hub's sign-up evidence, as the spoke-hosted entry reads it (#11096 D3,
3
+ * D9).
4
+ *
5
+ * The same source the sign-up agreements plugin checks a sign-up request
6
+ * against: `GET /v1/consent/sign-up` through `consent.signUpEvidence`, parsed
7
+ * with `consentSignUpResponseSchema`, for one of the site's enabled locales
8
+ * (anything else reads as `en`). So the agreements a spoke's form shows, and
9
+ * the version a purchase claim is checked at, are the ones the plugin
10
+ * enforces. It keeps its own per-process entry, fresh for 60 s, one per
11
+ * enabled locale; a read is bounded at 2 s and never throws — a failure is
12
+ * `null`, and a failed refresh serves nothing stale, so a caller that needs
13
+ * the evidence fails closed.
14
+ *
15
+ * A second reader rather than the plugin's own cache because
16
+ * `lib/sign-up-agreements.ts` is not this unit's to change; the two read the
17
+ * same API answer, and the plugin still refuses any request its own read
18
+ * does not cover.
19
+ */
20
+ import { consent } from "@working-theory/api-client";
21
+ import {
22
+ consentSignUpResponseSchema,
23
+ type ConsentSignUpResponse,
24
+ } from "@working-theory/validation";
25
+
26
+ const DEFAULT_LOCALE = "en";
27
+ const FRESH_MS = 60_000;
28
+ const READ_TIMEOUT_MS = 2_000;
29
+
30
+ const cache = new Map<
31
+ string,
32
+ { evidence: ConsentSignUpResponse; fetchedAt: number }
33
+ >();
34
+
35
+ /** Test seam: empties the per-process cache. */
36
+ export function resetHubSignUpEvidenceCache(): void {
37
+ cache.clear();
38
+ }
39
+
40
+ function enabledLocales(): string[] {
41
+ const enabled = (process.env.NEXT_PUBLIC_ENABLED_LOCALES ?? DEFAULT_LOCALE)
42
+ .split(",")
43
+ .map((locale) => locale.trim())
44
+ .filter((locale) => locale.length > 0);
45
+ return enabled.length > 0 ? enabled : [DEFAULT_LOCALE];
46
+ }
47
+
48
+ /** `raw` when it is one of the site's enabled locales, else `en`. */
49
+ export function normaliseEvidenceLocale(raw: unknown): string {
50
+ return typeof raw === "string" && enabledLocales().includes(raw)
51
+ ? raw
52
+ : DEFAULT_LOCALE;
53
+ }
54
+
55
+ /** The evidence for `locale` (normalised), or `null` when it cannot be read. */
56
+ export async function readHubSignUpEvidence(
57
+ locale: unknown,
58
+ ): Promise<ConsentSignUpResponse | null> {
59
+ const key = normaliseEvidenceLocale(locale);
60
+ const entry = cache.get(key);
61
+ if (entry && Date.now() - entry.fetchedAt < FRESH_MS) return entry.evidence;
62
+ let timer: ReturnType<typeof setTimeout> | undefined;
63
+ const timedOut = new Promise<null>((resolve) => {
64
+ timer = setTimeout(() => resolve(null), READ_TIMEOUT_MS);
65
+ });
66
+ try {
67
+ const res = await Promise.race([
68
+ consent.signUpEvidence({ locale: key }),
69
+ timedOut,
70
+ ]);
71
+ if (res === null || !res.ok) return null;
72
+ const parsed = consentSignUpResponseSchema.safeParse(res.body);
73
+ if (!parsed.success) return null;
74
+ cache.set(key, { evidence: parsed.data, fetchedAt: Date.now() });
75
+ return parsed.data;
76
+ } catch {
77
+ return null;
78
+ } finally {
79
+ clearTimeout(timer);
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Whether the evidence asks for exactly one agreement, `account_terms`, at
85
+ * `policyVersion` — the only shape a purchase claim covers (#11096 D9).
86
+ */
87
+ export function coversPurchaseTerms(
88
+ evidence: ConsentSignUpResponse,
89
+ policyVersion: number,
90
+ ): boolean {
91
+ const [only, ...rest] = evidence.agreements;
92
+ return (
93
+ rest.length === 0 &&
94
+ only?.purposeId === "account_terms" &&
95
+ only.policyVersion === policyVersion
96
+ );
97
+ }
@@ -20,20 +20,36 @@
20
20
  * #9912 D2 (AC-1): exactly one `?prompt=create` rides to the hub as
21
21
  * `prompt=create`, so the hub sends a visitor with no session to /sign-up;
22
22
  * any other value adds nothing, and the flow cookie's keys are unchanged.
23
+ *
24
+ * #11096 (spec docs/specs/11096-the-spoke-hosts-the-sign-spec.md): the
25
+ * spoke-hosted entry — the email form's POST (AC-1, AC-2, AC-6), Google's
26
+ * `provider` hint (AC-3), the purchase link's "Open my account" (AC-4) and
27
+ * One Tap's nonce and credential exchange (AC-5, AC-6). The hub web is
28
+ * reached with `fetch` (mocked); the hub API through the api-client.
23
29
  */
24
30
 
25
31
  import { createHash } from "node:crypto";
26
32
 
27
33
  const mockExchange = jest.fn();
28
34
  const mockRevoke = jest.fn();
35
+ const mockGoogle = jest.fn();
29
36
  jest.mock("@working-theory/api-client", () => ({
30
37
  __esModule: true,
31
38
  hubSignIn: {
32
39
  exchange: (...args: unknown[]) => mockExchange(...args),
33
40
  revoke: (...args: unknown[]) => mockRevoke(...args),
41
+ google: (...args: unknown[]) => mockGoogle(...args),
34
42
  },
35
43
  }));
36
44
 
45
+ // #11096 — the bot check's external boundary is Vercel BotID: it runs only
46
+ // with `VERCEL=1`, so a case that wants a verdict sets that and answers here.
47
+ const mockCheckBotId = jest.fn();
48
+ jest.mock("botid/server", () => ({
49
+ __esModule: true,
50
+ checkBotId: (...args: unknown[]) => mockCheckBotId(...args),
51
+ }));
52
+
37
53
  const mockProvider: { value: "site" | "hub" | "none" } = { value: "hub" };
38
54
  // eslint-disable-next-line no-restricted-syntax -- #507: the sign-in provider is a generated constant (#7894 D8), not a runtime input; the seam IS the boundary between a hub and a hub-mode spoke build, and no env or HTTP surface selects it.
39
55
  jest.mock("../../../../lib/topology.generated", () => ({
@@ -45,6 +61,10 @@ jest.mock("../../../../lib/topology.generated", () => ({
45
61
 
46
62
  import { seal, unseal } from "../../../../lib/hub-session/seal";
47
63
  import { GET as callback } from "../callback/route";
64
+ import { POST as email } from "../email/route";
65
+ import { POST as oneTapNonce } from "../one-tap/nonce/route";
66
+ import { POST as oneTap } from "../one-tap/route";
67
+ import { POST as open } from "../open/route";
48
68
  import { GET as signIn } from "../sign-in/route";
49
69
  import { POST as signOut } from "../sign-out/route";
50
70
 
@@ -108,10 +128,18 @@ function callbackRequest(query: string, cookie?: string): Request {
108
128
  });
109
129
  }
110
130
 
131
+ const mockFetch = jest.fn();
132
+ const realFetch = global.fetch;
133
+
111
134
  beforeEach(() => {
112
135
  configure();
113
136
  mockProvider.value = "hub";
114
137
  mockExchange.mockReset();
138
+ mockGoogle.mockReset();
139
+ mockCheckBotId.mockReset().mockResolvedValue({ isBot: false });
140
+ mockFetch.mockReset();
141
+ // eslint-disable-next-line no-restricted-syntax -- a jest.fn stands in for the global fetch, the hub web's HTTP boundary; its call signature is not fetch's own.
142
+ global.fetch = mockFetch as unknown as typeof fetch;
115
143
  mockRevoke.mockReset().mockResolvedValue({ ok: true, body: { revoked: true } });
116
144
  jest.spyOn(console, "warn").mockImplementation(() => undefined);
117
145
  jest.spyOn(console, "error").mockImplementation(() => undefined);
@@ -119,6 +147,7 @@ beforeEach(() => {
119
147
 
120
148
  afterEach(() => {
121
149
  jest.restoreAllMocks();
150
+ global.fetch = realFetch;
122
151
  });
123
152
 
124
153
  afterAll(() => {
@@ -154,11 +183,12 @@ describe("GET /api/hub-session/sign-in", () => {
154
183
  );
155
184
  });
156
185
 
157
- it("with no configuration 303s to /account and sets no cookie", () => {
186
+ // #11095 D4: /account now redirects here, so landing there would loop.
187
+ it("with no configuration 303s to the site's home and sets no cookie", () => {
158
188
  configure({ AILK_HUB_CLIENT_SECRET: undefined });
159
189
  const res = signIn(new Request(`${SITE}/api/hub-session/sign-in?next=/account`));
160
190
  expect(res.status).toBe(303);
161
- expect(res.headers.get("location")).toBe("/account");
191
+ expect(res.headers.get("location")).toBe("/");
162
192
  expect(setCookies(res)).toEqual([]);
163
193
  });
164
194
 
@@ -306,7 +336,7 @@ describe("GET /api/hub-session/callback", () => {
306
336
  it("AC-5: without its flow cookie, burns the code at the hub and exchanges nothing", async () => {
307
337
  const res = await callback(callbackRequest(`code=${CODE}&state=${"s".repeat(43)}`));
308
338
  expect(res.status).toBe(303);
309
- expect(res.headers.get("location")).toBe("/account");
339
+ expect(res.headers.get("location")).toBe("/");
310
340
  expect(mockExchange).not.toHaveBeenCalled();
311
341
  expect(mockRevoke).toHaveBeenCalledTimes(1);
312
342
  expect(mockRevoke).toHaveBeenCalledWith(CLIENT, { code: CODE });
@@ -318,8 +348,15 @@ describe("GET /api/hub-session/callback", () => {
318
348
  const state = authorize.searchParams.get("state") ?? "";
319
349
  const cookie = `ailk-hub-flow=${flow}`;
320
350
 
321
- await callback(callbackRequest(`code=${CODE}&state=${"x".repeat(43)}`, cookie));
322
- await callback(callbackRequest(`code=${CODE}&state=${state}&error=access_denied`, cookie));
351
+ // #11095 D4: every refusal lands on the site's home, never /account.
352
+ const mismatch = await callback(callbackRequest(`code=${CODE}&state=${"x".repeat(43)}`, cookie));
353
+ expect(mismatch.status).toBe(303);
354
+ expect(mismatch.headers.get("location")).toBe("/");
355
+ const hubError = await callback(
356
+ callbackRequest(`code=${CODE}&state=${state}&error=access_denied`, cookie),
357
+ );
358
+ expect(hubError.status).toBe(303);
359
+ expect(hubError.headers.get("location")).toBe("/");
323
360
  const expired = seal(
324
361
  { v: 1, state, verifier: "v".repeat(43), next: "/account", expiresAt: Date.now() - 1 },
325
362
  SESSION_SECRET,
@@ -331,7 +368,7 @@ describe("GET /api/hub-session/callback", () => {
331
368
 
332
369
  mockExchange.mockResolvedValue({ ok: false, status: 400, body: { error: "invalid_grant" } });
333
370
  const failed = await callback(callbackRequest(`code=${CODE}&state=${state}`, cookie));
334
- expect(failed.headers.get("location")).toBe("/account");
371
+ expect(failed.headers.get("location")).toBe("/");
335
372
  expect(mockRevoke).toHaveBeenCalledTimes(4);
336
373
  for (const call of mockRevoke.mock.calls) expect(call).toEqual([CLIENT, { code: CODE }]);
337
374
  });
@@ -346,7 +383,7 @@ describe("GET /api/hub-session/callback", () => {
346
383
  const { flow, authorize } = start();
347
384
  const state = authorize.searchParams.get("state") ?? "";
348
385
  const res = await callback(callbackRequest(`code=${CODE}&state=${state}`, `ailk-hub-flow=${flow}`));
349
- expect(res.headers.get("location")).toBe("/account");
386
+ expect(res.headers.get("location")).toBe("/");
350
387
  expect(setCookies(res).some((c) => c.startsWith("ailk-hub-session="))).toBe(false);
351
388
  },
352
389
  );
@@ -360,6 +397,14 @@ describe("GET /api/hub-session/callback", () => {
360
397
  expect(logged).not.toContain("s".repeat(43));
361
398
  });
362
399
 
400
+ it("with no configuration 303s to the site's home (#11095 D4)", async () => {
401
+ configure({ AILK_HUB_CLIENT_SECRET: undefined });
402
+ const res = await callback(callbackRequest(`code=${CODE}&state=x`));
403
+ expect(res.status).toBe(303);
404
+ expect(res.headers.get("location")).toBe("/");
405
+ expect(mockExchange).not.toHaveBeenCalled();
406
+ });
407
+
363
408
  it("does not try to burn a malformed code", async () => {
364
409
  await callback(callbackRequest("code=not-a-code&state=x"));
365
410
  expect(mockRevoke).not.toHaveBeenCalled();
@@ -433,3 +478,426 @@ describe("POST /api/hub-session/sign-out", () => {
433
478
  expect((await post({ "sec-fetch-site": "same-origin" })).status).toBe(404);
434
479
  });
435
480
  });
481
+
482
+ // ── #11096 — the spoke-hosted entry ─────────────────────────────────────────
483
+
484
+ const SPOKE_KEY = "ailk_spk_test_key";
485
+ const CLAIM = "C".repeat(120);
486
+
487
+ /** A hub web answer for the mocked `fetch`. */
488
+ function hubAnswer(status: number, body: unknown): Response {
489
+ return new Response(JSON.stringify(body), {
490
+ status,
491
+ headers: { "content-type": "application/json" },
492
+ });
493
+ }
494
+
495
+ /** A same-origin form POST to one of the spoke's routes. */
496
+ function formPost(
497
+ path: string,
498
+ fields: Array<[string, string]>,
499
+ headers: Record<string, string> = { "sec-fetch-site": "same-origin", origin: SITE },
500
+ ): Request {
501
+ const body = new URLSearchParams(fields);
502
+ return new Request(`${SITE}${path}`, {
503
+ method: "POST",
504
+ headers: { "content-type": "application/x-www-form-urlencoded", ...headers },
505
+ body: body.toString(),
506
+ });
507
+ }
508
+
509
+ /** The one hub web call the mocked `fetch` received. */
510
+ function hubCall(): { url: string; headers: Headers; body: Record<string, unknown> } {
511
+ expect(mockFetch).toHaveBeenCalledTimes(1);
512
+ const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit];
513
+ return {
514
+ url,
515
+ headers: new Headers(init.headers),
516
+ body: JSON.parse(String(init.body)) as Record<string, unknown>,
517
+ };
518
+ }
519
+
520
+ /** The flow a 303's flow cookie seals. */
521
+ function flowOf(res: Response): Record<string, unknown> {
522
+ const flow = cookieValue(res, "ailk-hub-flow");
523
+ if (flow === undefined) throw new Error("no flow cookie");
524
+ const payload = unseal(flow, SESSION_SECRET, "flow", "ailk-hub-flow");
525
+ if (payload === null || typeof payload !== "object") throw new Error("flow did not open");
526
+ return payload as Record<string, unknown>;
527
+ }
528
+
529
+ describe("POST /api/hub-session/email (#11096 D2)", () => {
530
+ beforeEach(() => {
531
+ process.env.AILK_SPOKE_KEY = SPOKE_KEY;
532
+ });
533
+
534
+ it("AC-1: a known email → the hub web's email route with the client's two headers; 303 /account?sent=1 with the flow cookie", async () => {
535
+ mockFetch.mockResolvedValue(hubAnswer(202, { sent: true }));
536
+ const res = await email(
537
+ formPost("/api/hub-session/email", [
538
+ ["email", "ada@example.com"],
539
+ ["next", "/account"],
540
+ ]),
541
+ );
542
+
543
+ expect(res.status).toBe(303);
544
+ expect(res.headers.get("location")).toBe("/account?sent=1");
545
+ expect(res.headers.get("cache-control")).toBe("no-store");
546
+ expect(res.headers.get("referrer-policy")).toBe("no-referrer");
547
+ expect(setCookies(res)).toHaveLength(1);
548
+ const flow = flowOf(res);
549
+ expect(flow.next).toBe("/account");
550
+
551
+ const call = hubCall();
552
+ expect(call.url).toBe(`${HUB}/api/auth/hub/email`);
553
+ expect(call.headers.get("authorization")).toBe(
554
+ `Basic ${Buffer.from(`${CLIENT.clientId}:${CLIENT.clientSecret}`).toString("base64")}`,
555
+ );
556
+ expect(call.headers.get("x-ailk-spoke-key")).toBe(SPOKE_KEY);
557
+ expect(call.body).toEqual({
558
+ client_id: CLIENT.clientId,
559
+ redirect_uri: `${SITE}/api/hub-session/callback`,
560
+ state: flow.state,
561
+ code_challenge: createHash("sha256").update(String(flow.verifier)).digest("base64url"),
562
+ code_challenge_method: "S256",
563
+ email: "ada@example.com",
564
+ locale: "en",
565
+ });
566
+ expect(call.body).not.toHaveProperty("agreements");
567
+ });
568
+
569
+ it("AC-2: ticked agreements ride to the hub web as their ids", async () => {
570
+ mockFetch.mockResolvedValue(hubAnswer(202, { sent: true }));
571
+ const res = await email(
572
+ formPost("/api/hub-session/email", [
573
+ ["email", "new@example.com"],
574
+ ["agreements", "account_terms"],
575
+ ]),
576
+ );
577
+ expect(res.headers.get("location")).toBe("/account?sent=1");
578
+ expect(hubCall().body.agreements).toEqual(["account_terms"]);
579
+ });
580
+
581
+ it("AC-2: the hub's agreements_required → 303 /account?error=agreements with no flow cookie", async () => {
582
+ mockFetch.mockResolvedValue(hubAnswer(400, { error: "agreements_required" }));
583
+ const res = await email(
584
+ formPost("/api/hub-session/email", [
585
+ ["email", "new@example.com"],
586
+ ["agreements", "account_terms"],
587
+ ]),
588
+ );
589
+ expect(res.status).toBe(303);
590
+ expect(res.headers.get("location")).toBe("/account?error=agreements");
591
+ expect(setCookies(res)).toEqual([]);
592
+ });
593
+
594
+ it.each([
595
+ ["sign_up_closed", () => mockFetch.mockResolvedValue(hubAnswer(400, { error: "sign_up_closed" }))],
596
+ ["a 401", () => mockFetch.mockResolvedValue(hubAnswer(401, { error: "invalid_client" }))],
597
+ ["a 429", () => mockFetch.mockResolvedValue(hubAnswer(429, { error: "rate_limited" }))],
598
+ ["a throw", () => mockFetch.mockRejectedValue(new Error("network"))],
599
+ ])("%s → 303 /account?error=unavailable with no flow cookie", async (_label, arrange) => {
600
+ arrange();
601
+ const res = await email(formPost("/api/hub-session/email", [["email", "ada@example.com"]]));
602
+ expect(res.headers.get("location")).toBe("/account?error=unavailable");
603
+ expect(setCookies(res)).toEqual([]);
604
+ });
605
+
606
+ it("returns to the locale's own account page", async () => {
607
+ configure({ NEXT_PUBLIC_ENABLED_LOCALES: "en,fr" });
608
+ process.env.AILK_SPOKE_KEY = SPOKE_KEY;
609
+ mockFetch.mockResolvedValue(hubAnswer(202, { sent: true }));
610
+ const res = await email(
611
+ formPost("/api/hub-session/email", [
612
+ ["email", "ada@example.com"],
613
+ ["next", "/fr/account/inbox"],
614
+ ]),
615
+ );
616
+ expect(res.headers.get("location")).toBe("/fr/account?sent=1");
617
+ expect(hubCall().body.locale).toBe("fr");
618
+ expect(flowOf(res).next).toBe("/fr/account/inbox");
619
+ });
620
+
621
+ it.each([
622
+ ["a password field (AC-6)", [["email", "ada@example.com"], ["password", "hunter22"]]],
623
+ ["a repeated email", [["email", "ada@example.com"], ["email", "eve@example.com"]]],
624
+ ["no email", [["next", "/account"]]],
625
+ ["a malformed email", [["email", "not-an-email"]]],
626
+ ["an unknown agreement shape", [["email", "ada@example.com"], ["agreements", "Not An Id"]]],
627
+ ] as Array<[string, Array<[string, string]>]>)("%s → 400, no hub call", async (_label, fields) => {
628
+ const res = await email(formPost("/api/hub-session/email", fields));
629
+ expect(res.status).toBe(400);
630
+ expect(mockFetch).not.toHaveBeenCalled();
631
+ expect(setCookies(res)).toEqual([]);
632
+ });
633
+
634
+ it.each([
635
+ ["cross-site", { "sec-fetch-site": "cross-site", origin: SITE }],
636
+ ["a foreign Origin", { "sec-fetch-site": "same-origin", origin: "https://evil.example.com" }],
637
+ ["neither header", {}],
638
+ ] as Array<[string, Record<string, string>]>)("refuses %s with 403, calling nothing", async (_label, headers) => {
639
+ const res = await email(formPost("/api/hub-session/email", [["email", "ada@example.com"]], headers));
640
+ expect(res.status).toBe(403);
641
+ expect(mockFetch).not.toHaveBeenCalled();
642
+ });
643
+
644
+ it("a visitor over the limit gets /account?error=unavailable and no hub call", async () => {
645
+ mockFetch.mockResolvedValue(hubAnswer(202, { sent: true }));
646
+ configure({ VERCEL: "1", AILK_BOT_CHECK: "off" });
647
+ const visitor = { "sec-fetch-site": "same-origin", origin: SITE, "x-vercel-forwarded-for": "203.0.113.77" };
648
+ for (let i = 0; i < 10; i++) {
649
+ await email(formPost("/api/hub-session/email", [["email", "ada@example.com"]], visitor));
650
+ }
651
+ mockFetch.mockClear();
652
+ const limited = await email(formPost("/api/hub-session/email", [["email", "ada@example.com"]], visitor));
653
+ expect(limited.headers.get("location")).toBe("/account?error=unavailable");
654
+ expect(mockFetch).not.toHaveBeenCalled();
655
+ });
656
+
657
+ it("a bot gets /account?error=unavailable and no hub call", async () => {
658
+ configure({ VERCEL: "1" });
659
+ mockCheckBotId.mockResolvedValue({ isBot: true, classificationReason: "test" });
660
+ const res = await email(
661
+ formPost("/api/hub-session/email", [["email", "ada@example.com"]], {
662
+ "sec-fetch-site": "same-origin",
663
+ origin: SITE,
664
+ "x-vercel-forwarded-for": "203.0.113.78",
665
+ }),
666
+ );
667
+ expect(res.headers.get("location")).toBe("/account?error=unavailable");
668
+ expect(mockFetch).not.toHaveBeenCalled();
669
+ });
670
+
671
+ it("with no configuration 303s to /account?error=unavailable", async () => {
672
+ configure({ AILK_HUB_CLIENT_SECRET: undefined });
673
+ const res = await email(formPost("/api/hub-session/email", [["email", "ada@example.com"]]));
674
+ expect(res.status).toBe(303);
675
+ expect(res.headers.get("location")).toBe("/account?error=unavailable");
676
+ expect(mockFetch).not.toHaveBeenCalled();
677
+ });
678
+
679
+ it("is 404 unless the provider is hub", async () => {
680
+ mockProvider.value = "site";
681
+ const res = await email(formPost("/api/hub-session/email", [["email", "ada@example.com"]]));
682
+ expect(res.status).toBe(404);
683
+ });
684
+
685
+ it("never logs the email", async () => {
686
+ const warn = jest.spyOn(console, "warn");
687
+ const error = jest.spyOn(console, "error");
688
+ mockFetch.mockRejectedValue(new Error("network"));
689
+ await email(formPost("/api/hub-session/email", [["email", "ada@example.com"]]));
690
+ const logged = [...warn.mock.calls, ...error.mock.calls].flat().join(" ");
691
+ expect(logged).not.toContain("ada@example.com");
692
+ });
693
+ });
694
+
695
+ describe("GET /api/hub-session/sign-in — Google's provider hint (#11096 D4, AC-3)", () => {
696
+ function startWith(query: string): { authorize: URL; payload: Record<string, unknown> } {
697
+ const res = signIn(new Request(`${SITE}/api/hub-session/sign-in?${query}`));
698
+ expect(res.status).toBe(303);
699
+ return { authorize: new URL(res.headers.get("location") ?? ""), payload: flowOf(res) };
700
+ }
701
+
702
+ it("?provider=google → provider_hint=google; the flow cookie keeps exactly its five keys", () => {
703
+ const { authorize, payload } = startWith("next=%2Faccount&provider=google");
704
+ expect(authorize.searchParams.getAll("provider_hint")).toEqual(["google"]);
705
+ expect(authorize.searchParams.get("code_challenge_method")).toBe("S256");
706
+ expect(Object.keys(payload).sort()).toEqual(["expiresAt", "next", "state", "v", "verifier"]);
707
+ expect(JSON.stringify(payload)).not.toContain("google");
708
+ });
709
+
710
+ it.each([
711
+ ["another provider", "next=/account&provider=github"],
712
+ ["an empty value", "next=/account&provider="],
713
+ ["a repeated value", "next=/account&provider=google&provider=google"],
714
+ ["no value", "next=/account"],
715
+ ])("%s → no provider_hint", (_label, query) => {
716
+ const { authorize } = startWith(query);
717
+ expect(authorize.searchParams.has("provider_hint")).toBe(false);
718
+ });
719
+ });
720
+
721
+ describe("POST /api/hub-session/open — the purchase link's one click (#11096 D9, AC-4)", () => {
722
+ beforeEach(() => {
723
+ process.env.AILK_SPOKE_KEY = SPOKE_KEY;
724
+ });
725
+
726
+ const VERIFY = `${HUB}/api/auth/magic-link/verify?token=t&callbackURL=%2Fapi%2Fauth%2Fhub%2Fcontinue%2Fr`;
727
+
728
+ it("spends the claim at the hub web and 303s to its verify URL with the flow cookie", async () => {
729
+ mockFetch.mockResolvedValue(hubAnswer(200, { verifyUrl: VERIFY }));
730
+ const res = await open(formPost("/api/hub-session/open", [["claim", CLAIM]]));
731
+ expect(res.status).toBe(303);
732
+ expect(res.headers.get("location")).toBe(VERIFY);
733
+ expect(res.headers.get("referrer-policy")).toBe("no-referrer");
734
+ const flow = flowOf(res);
735
+ expect(flow.next).toBe("/account");
736
+ const call = hubCall();
737
+ expect(call.url).toBe(`${HUB}/api/auth/hub/purchase`);
738
+ expect(call.headers.get("authorization")).toMatch(/^Basic /);
739
+ expect(call.headers.get("x-ailk-spoke-key")).toBe(SPOKE_KEY);
740
+ expect(call.body).toEqual({
741
+ claim: CLAIM,
742
+ client_id: CLIENT.clientId,
743
+ redirect_uri: `${SITE}/api/hub-session/callback`,
744
+ state: flow.state,
745
+ code_challenge: createHash("sha256").update(String(flow.verifier)).digest("base64url"),
746
+ code_challenge_method: "S256",
747
+ });
748
+ });
749
+
750
+ it("409 account_exists → 303 /account?error=exists, no flow cookie", async () => {
751
+ mockFetch.mockResolvedValue(hubAnswer(409, { error: "account_exists" }));
752
+ const res = await open(formPost("/api/hub-session/open", [["claim", CLAIM]]));
753
+ expect(res.headers.get("location")).toBe("/account?error=exists");
754
+ expect(setCookies(res)).toEqual([]);
755
+ });
756
+
757
+ it.each([
758
+ ["410 claim_used", () => mockFetch.mockResolvedValue(hubAnswer(410, { error: "claim_used" }))],
759
+ ["410 terms_changed", () => mockFetch.mockResolvedValue(hubAnswer(410, { error: "terms_changed" }))],
760
+ ["a verify URL off the hub", () => mockFetch.mockResolvedValue(hubAnswer(200, { verifyUrl: "https://evil.example.com/x" }))],
761
+ ["a throw", () => mockFetch.mockRejectedValue(new Error("network"))],
762
+ ])("%s → 303 /account?error=claim, no flow cookie", async (_label, arrange) => {
763
+ arrange();
764
+ const res = await open(formPost("/api/hub-session/open", [["claim", CLAIM]]));
765
+ expect(res.headers.get("location")).toBe("/account?error=claim");
766
+ expect(setCookies(res)).toEqual([]);
767
+ });
768
+
769
+ it.each([
770
+ ["an added field", [["claim", CLAIM], ["email", "ada@example.com"]]],
771
+ ["no claim", []],
772
+ ["a malformed claim", [["claim", "not a claim!"]]],
773
+ ] as Array<[string, Array<[string, string]>]>)("%s → 400, no hub call", async (_label, fields) => {
774
+ const res = await open(formPost("/api/hub-session/open", fields));
775
+ expect(res.status).toBe(400);
776
+ expect(mockFetch).not.toHaveBeenCalled();
777
+ });
778
+
779
+ it("refuses a cross-site POST with 403", async () => {
780
+ const res = await open(
781
+ formPost("/api/hub-session/open", [["claim", CLAIM]], { "sec-fetch-site": "cross-site" }),
782
+ );
783
+ expect(res.status).toBe(403);
784
+ expect(mockFetch).not.toHaveBeenCalled();
785
+ });
786
+ });
787
+
788
+ describe("POST /api/hub-session/one-tap and its nonce (#11096 D10, AC-5)", () => {
789
+ const ID_TOKEN = "header.payload.signature";
790
+ const SAME_ORIGIN = { "sec-fetch-site": "same-origin", origin: SITE };
791
+
792
+ function jsonPost(path: string, body: unknown, headers: Record<string, string> = SAME_ORIGIN): Request {
793
+ return new Request(`${SITE}${path}`, {
794
+ method: "POST",
795
+ headers: { "content-type": "application/json", ...headers },
796
+ body: JSON.stringify(body),
797
+ });
798
+ }
799
+
800
+ async function mintNonce(): Promise<{ nonce: string; cookie: string }> {
801
+ const res = await oneTapNonce(jsonPost("/api/hub-session/one-tap/nonce", {}));
802
+ expect(res.status).toBe(200);
803
+ const { nonce } = (await res.json()) as { nonce: string };
804
+ const value = cookieValue(res, "ailk-hub-one-tap");
805
+ if (value === undefined) throw new Error("no nonce cookie");
806
+ return { nonce, cookie: `ailk-hub-one-tap=${value}` };
807
+ }
808
+
809
+ beforeEach(() => {
810
+ configure({ AILK_HUB_ONE_TAP: "on" });
811
+ });
812
+
813
+ it("the nonce route mints 32 random bytes and seals them into a 300 s cookie", async () => {
814
+ const res = await oneTapNonce(jsonPost("/api/hub-session/one-tap/nonce", {}));
815
+ expect(res.status).toBe(200);
816
+ expect(res.headers.get("cache-control")).toBe("no-store");
817
+ const { nonce } = (await res.json()) as { nonce: string };
818
+ expect(nonce).toMatch(/^[A-Za-z0-9_-]{43}$/);
819
+ const line = setCookies(res).find((c) => c.startsWith("ailk-hub-one-tap="));
820
+ expect(line).toMatch(/; HttpOnly/);
821
+ expect(line).toMatch(/; Max-Age=300/);
822
+ expect(line).not.toContain(nonce);
823
+ });
824
+
825
+ it("AC-5: a valid credential and nonce cookie → 200 { ok: true }, the session cookie, the nonce cleared", async () => {
826
+ mockGoogle.mockResolvedValue({
827
+ ok: true,
828
+ body: { accessToken: CREDENTIAL, tokenType: "Bearer", expiresIn: 86400, user: USER },
829
+ });
830
+ const { nonce, cookie } = await mintNonce();
831
+ const res = await oneTap(
832
+ new Request(`${SITE}/api/hub-session/one-tap`, {
833
+ method: "POST",
834
+ headers: { "content-type": "application/json", cookie, ...SAME_ORIGIN },
835
+ body: JSON.stringify({ credential: ID_TOKEN }),
836
+ }),
837
+ );
838
+ expect(res.status).toBe(200);
839
+ expect(await res.json()).toEqual({ ok: true });
840
+ expect(mockGoogle).toHaveBeenCalledWith(CLIENT, { idToken: ID_TOKEN, nonce, origin: SITE });
841
+ const session = setCookies(res).find((c) => c.startsWith("ailk-hub-session="));
842
+ expect(session).toMatch(/; Max-Age=86400/);
843
+ expect(setCookies(res).find((c) => c.startsWith("ailk-hub-one-tap="))).toMatch(/Max-Age=0/);
844
+ expect(setCookies(res).join("\n")).not.toContain(CREDENTIAL);
845
+ });
846
+
847
+ it("no nonce cookie → 400 and no hub call", async () => {
848
+ const res = await oneTap(jsonPost("/api/hub-session/one-tap", { credential: ID_TOKEN }));
849
+ expect(res.status).toBe(400);
850
+ expect(mockGoogle).not.toHaveBeenCalled();
851
+ });
852
+
853
+ it.each([
854
+ ["a 404 (no Google account row)", { ok: false, status: 404, body: { error: "not_found" } }],
855
+ ["a 401", { ok: false, status: 401, body: { error: "invalid_grant" } }],
856
+ ])("the hub's %s → 401 { ok: false }, no session, the nonce cleared", async (_label, answer) => {
857
+ mockGoogle.mockResolvedValue(answer);
858
+ const { cookie } = await mintNonce();
859
+ const res = await oneTap(
860
+ new Request(`${SITE}/api/hub-session/one-tap`, {
861
+ method: "POST",
862
+ headers: { "content-type": "application/json", cookie, ...SAME_ORIGIN },
863
+ body: JSON.stringify({ credential: ID_TOKEN }),
864
+ }),
865
+ );
866
+ expect(res.status).toBe(401);
867
+ expect(await res.json()).toEqual({ ok: false });
868
+ expect(setCookies(res).some((c) => c.startsWith("ailk-hub-session="))).toBe(false);
869
+ expect(setCookies(res).find((c) => c.startsWith("ailk-hub-one-tap="))).toMatch(/Max-Age=0/);
870
+ });
871
+
872
+ it("AC-6: a body with a password field → 400, no hub call", async () => {
873
+ const { cookie } = await mintNonce();
874
+ const res = await oneTap(
875
+ new Request(`${SITE}/api/hub-session/one-tap`, {
876
+ method: "POST",
877
+ headers: { "content-type": "application/json", cookie, ...SAME_ORIGIN },
878
+ body: JSON.stringify({ credential: ID_TOKEN, password: "hunter22" }),
879
+ }),
880
+ );
881
+ expect(res.status).toBe(400);
882
+ expect(mockGoogle).not.toHaveBeenCalled();
883
+ });
884
+
885
+ it("refuses a cross-site POST with 403", async () => {
886
+ const nonce = await oneTapNonce(
887
+ jsonPost("/api/hub-session/one-tap/nonce", {}, { "sec-fetch-site": "cross-site" }),
888
+ );
889
+ expect(nonce.status).toBe(403);
890
+ const res = await oneTap(
891
+ jsonPost("/api/hub-session/one-tap", { credential: ID_TOKEN }, { "sec-fetch-site": "cross-site" }),
892
+ );
893
+ expect(res.status).toBe(403);
894
+ });
895
+
896
+ it("both routes 404 while AILK_HUB_ONE_TAP is not on", async () => {
897
+ configure();
898
+ expect((await oneTapNonce(jsonPost("/api/hub-session/one-tap/nonce", {}))).status).toBe(404);
899
+ expect(
900
+ (await oneTap(jsonPost("/api/hub-session/one-tap", { credential: ID_TOKEN }))).status,
901
+ ).toBe(404);
902
+ });
903
+ });