create-ailk 0.35.1 → 0.37.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 (169) hide show
  1. package/README.md +1 -1
  2. package/component-catalog.json +51 -1
  3. package/component-catalog.md +8 -5
  4. package/dist/lib/env-catalog.js +8 -0
  5. package/dist/surfaces.js +66 -22
  6. package/dist/topology.d.ts +4 -4
  7. package/dist/topology.js +104 -60
  8. package/dist/update.d.ts +19 -1
  9. package/dist/update.js +293 -35
  10. package/package.json +3 -3
  11. package/templates/.env.example +38 -0
  12. package/templates/apps/api/.env.example +45 -0
  13. package/templates/apps/api/CLAUDE.md +12 -4
  14. package/templates/apps/api/src/lib/__mocks__/prisma.ts +7 -0
  15. package/templates/apps/mcp/CLAUDE.md +4 -2
  16. package/templates/apps/web/.env.example +16 -0
  17. package/templates/apps/web/CLAUDE.md +73 -5
  18. package/templates/apps/web/app/[locale]/(auth)/__tests__/password-reset.test.tsx +2 -0
  19. package/templates/apps/web/app/[locale]/(auth)/reset-password/__tests__/return.test.tsx +179 -0
  20. package/templates/apps/web/app/[locale]/(auth)/reset-password/page.tsx +22 -2
  21. package/templates/apps/web/app/[locale]/(auth)/reset-password/reset-password-card.tsx +9 -2
  22. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/page.test.tsx +52 -1
  23. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/remembered-method.test.ts +43 -0
  24. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/sign-in-card.test.tsx +108 -1
  25. package/templates/apps/web/app/[locale]/(auth)/sign-in/page.tsx +36 -3
  26. package/templates/apps/web/app/[locale]/(auth)/sign-in/remembered-method.ts +37 -0
  27. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-card.tsx +90 -33
  28. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-text.ts +9 -4
  29. package/templates/apps/web/app/[locale]/(authed)/__tests__/gate.test.tsx +79 -348
  30. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/billing.test.tsx +241 -66
  31. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/general.test.tsx +242 -28
  32. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +377 -151
  33. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/item.test.tsx +26 -1
  34. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout-sign-out.test.tsx +10 -5
  35. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout.test.tsx +17 -6
  36. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/new-menu.test.tsx +51 -12
  37. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/new-popups.test.tsx +17 -2
  38. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/notifications.test.tsx +153 -2
  39. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/page.test.tsx +206 -23
  40. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/popups.test.tsx +150 -188
  41. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/privacy.test.tsx +235 -177
  42. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/rich-translator.ts +63 -0
  43. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/security.test.tsx +0 -3
  44. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/thread.test.tsx +340 -0
  45. package/templates/apps/web/app/[locale]/(authed)/account/account-data.ts +7 -5
  46. package/templates/apps/web/app/[locale]/(authed)/account/account-frame.tsx +20 -4
  47. package/templates/apps/web/app/[locale]/(authed)/account/actions.ts +8 -4
  48. package/templates/apps/web/app/[locale]/(authed)/account/appointments/[slug]/page.tsx +161 -0
  49. package/templates/apps/web/app/[locale]/(authed)/account/appointments/__tests__/page.test.tsx +426 -0
  50. package/templates/apps/web/app/[locale]/(authed)/account/appointments/appointments-data.ts +76 -0
  51. package/templates/apps/web/app/[locale]/(authed)/account/appointments/page.tsx +139 -0
  52. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/page.tsx +92 -24
  53. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/versions/[version]/file/route.ts +32 -1
  54. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/file-route.test.ts +76 -3
  55. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/page.test.tsx +290 -41
  56. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/artifact-data.ts +109 -11
  57. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/page.tsx +43 -44
  58. package/templates/apps/web/app/[locale]/(authed)/account/billing/__tests__/offerings.test.ts +99 -0
  59. package/templates/apps/web/app/[locale]/(authed)/account/billing/offerings.ts +123 -0
  60. package/templates/apps/web/app/[locale]/(authed)/account/billing/page.tsx +323 -73
  61. package/templates/apps/web/app/[locale]/(authed)/account/billing-source.ts +199 -43
  62. package/templates/apps/web/app/[locale]/(authed)/account/components/request-quote.tsx +52 -7
  63. package/templates/apps/web/app/[locale]/(authed)/account/connect/__tests__/page.test.tsx +8 -1
  64. package/templates/apps/web/app/[locale]/(authed)/account/connect/page.tsx +7 -3
  65. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/phone-verification.test.tsx +215 -0
  66. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/seam-imports.test.ts +65 -0
  67. package/templates/apps/web/app/[locale]/(authed)/account/general/account-name.ts +36 -0
  68. package/templates/apps/web/app/[locale]/(authed)/account/general/contact-actions.ts +70 -2
  69. package/templates/apps/web/app/[locale]/(authed)/account/general/contact-details.tsx +42 -0
  70. package/templates/apps/web/app/[locale]/(authed)/account/general/page.tsx +97 -53
  71. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-actions.ts +122 -0
  72. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-verification.tsx +215 -0
  73. package/templates/apps/web/app/[locale]/(authed)/account/general/photo-actions.ts +73 -0
  74. package/templates/apps/web/app/[locale]/(authed)/account/general/profile-form.tsx +12 -9
  75. package/templates/apps/web/app/[locale]/(authed)/account/general/profile-source.ts +18 -4
  76. package/templates/apps/web/app/[locale]/(authed)/account/inbox/[kind]/[id]/page.tsx +20 -2
  77. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/member-thread-composer.tsx +43 -0
  78. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/page.tsx +125 -0
  79. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/thread-data.ts +88 -0
  80. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/thread-write.ts +31 -0
  81. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/invitation-id.test.ts +35 -0
  82. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/page.test.tsx +266 -0
  83. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/actions.ts +116 -0
  84. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/invitation-id.ts +12 -0
  85. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/page.tsx +154 -0
  86. package/templates/apps/web/app/[locale]/(authed)/account/layout.tsx +9 -6
  87. package/templates/apps/web/app/[locale]/(authed)/account/new-menu.tsx +33 -8
  88. package/templates/apps/web/app/[locale]/(authed)/account/new-popups.tsx +31 -52
  89. package/templates/apps/web/app/[locale]/(authed)/account/notifications/page.tsx +44 -4
  90. package/templates/apps/web/app/[locale]/(authed)/account/page.tsx +69 -49
  91. package/templates/apps/web/app/[locale]/(authed)/account/privacy/__tests__/export-route.test.ts +173 -0
  92. package/templates/apps/web/app/[locale]/(authed)/account/privacy/actions.ts +42 -4
  93. package/templates/apps/web/app/[locale]/(authed)/account/privacy/export/route.ts +102 -0
  94. package/templates/apps/web/app/[locale]/(authed)/account/privacy/page.tsx +147 -137
  95. package/templates/apps/web/app/[locale]/(authed)/account/security/__tests__/hub-variant.test.tsx +258 -0
  96. package/templates/apps/web/app/[locale]/(authed)/account/security/page.tsx +21 -22
  97. package/templates/apps/web/app/[locale]/(authed)/account/security/security-panel.tsx +34 -6
  98. package/templates/apps/web/app/[locale]/(authed)/account/security/security-source.ts +37 -7
  99. package/templates/apps/web/app/[locale]/(authed)/account/settings/page.tsx +0 -2
  100. package/templates/apps/web/app/[locale]/(authed)/account/settings-frame.tsx +8 -5
  101. package/templates/apps/web/app/[locale]/(authed)/layout.tsx +15 -13
  102. package/templates/apps/web/app/[locale]/(authed)/signed-out-gate.generated.tsx +20 -52
  103. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsClient.tsx +3 -2
  104. package/templates/apps/web/app/[locale]/layout.tsx +24 -75
  105. package/templates/apps/web/app/[locale]/purchase/__tests__/success.test.tsx +50 -0
  106. package/templates/apps/web/app/[locale]/purchase/success/page.tsx +48 -7
  107. package/templates/apps/web/app/api/auth/hub/__tests__/entry-routes.test.ts +749 -0
  108. package/templates/apps/web/app/api/auth/hub/authorize/__tests__/route.test.ts +166 -7
  109. package/templates/apps/web/app/api/auth/hub/authorize/route.ts +96 -30
  110. package/templates/apps/web/app/api/auth/hub/continuation.ts +51 -2
  111. package/templates/apps/web/app/api/auth/hub/email/route.ts +111 -0
  112. package/templates/apps/web/app/api/auth/hub/entry-shared.ts +163 -0
  113. package/templates/apps/web/app/api/auth/hub/password/__tests__/return.test.ts +86 -0
  114. package/templates/apps/web/app/api/auth/hub/password/__tests__/route.test.ts +368 -0
  115. package/templates/apps/web/app/api/auth/hub/password/return.ts +86 -0
  116. package/templates/apps/web/app/api/auth/hub/password/route.ts +171 -0
  117. package/templates/apps/web/app/api/auth/hub/purchase/route.ts +230 -0
  118. package/templates/apps/web/app/api/auth/hub/purchase-link/route.ts +174 -0
  119. package/templates/apps/web/app/api/auth/hub/sign-up/route.ts +60 -0
  120. package/templates/apps/web/app/api/auth/hub/sign-up-evidence.ts +97 -0
  121. package/templates/apps/web/app/api/hub-session/__tests__/routes.test.ts +738 -7
  122. package/templates/apps/web/app/api/hub-session/callback/route.ts +13 -47
  123. package/templates/apps/web/app/api/hub-session/email/route.ts +125 -0
  124. package/templates/apps/web/app/api/hub-session/one-tap/nonce/route.ts +49 -0
  125. package/templates/apps/web/app/api/hub-session/one-tap/route.ts +106 -0
  126. package/templates/apps/web/app/api/hub-session/open/route.ts +111 -0
  127. package/templates/apps/web/app/api/hub-session/password/return/route.ts +69 -0
  128. package/templates/apps/web/app/api/hub-session/password/route.ts +106 -0
  129. package/templates/apps/web/app/api/hub-session/sign-in/route.ts +23 -40
  130. package/templates/apps/web/app/api/hub-session/sign-out/route.ts +1 -10
  131. package/templates/apps/web/auth.ts +133 -6
  132. package/templates/apps/web/components/sign-out-trigger.tsx +1 -1
  133. package/templates/apps/web/lib/__tests__/account-config.test.ts +129 -1
  134. package/templates/apps/web/lib/__tests__/auth-email.test.ts +141 -0
  135. package/templates/apps/web/lib/__tests__/auth-phone.test.ts +445 -0
  136. package/templates/apps/web/lib/__tests__/auth-sms.test.ts +140 -0
  137. package/templates/apps/web/lib/__tests__/fixtures/tsconfig.flow.json +18 -0
  138. package/templates/apps/web/lib/__tests__/offerings-pricing.test.ts +33 -0
  139. package/templates/apps/web/lib/__tests__/site-header.test.ts +13 -0
  140. package/templates/apps/web/lib/__tests__/telemetry-scrub.test.ts +19 -1
  141. package/templates/apps/web/lib/account-config.ts +132 -8
  142. package/templates/apps/web/lib/auth-email.ts +62 -6
  143. package/templates/apps/web/lib/auth-env.ts +13 -0
  144. package/templates/apps/web/lib/auth-routes.ts +11 -6
  145. package/templates/apps/web/lib/auth-sms.ts +180 -0
  146. package/templates/apps/web/lib/hub-session/__tests__/hub-session.test.ts +28 -0
  147. package/templates/apps/web/lib/hub-session/__tests__/spoke-sign-in.test.tsx +332 -0
  148. package/templates/apps/web/lib/hub-session/config.ts +7 -1
  149. package/templates/apps/web/lib/hub-session/entry.ts +238 -0
  150. package/templates/apps/web/lib/hub-session/index.ts +1 -4
  151. package/templates/apps/web/lib/hub-session/one-tap.tsx +148 -0
  152. package/templates/apps/web/lib/hub-session/session.ts +120 -2
  153. package/templates/apps/web/lib/hub-session/spoke-sign-in.tsx +277 -0
  154. package/templates/apps/web/lib/offerings-pricing.ts +4 -1
  155. package/templates/apps/web/lib/site-header.ts +14 -1
  156. package/templates/apps/web/lib/telemetry-scrub.ts +11 -0
  157. package/templates/apps/web/lib/topology.generated.ts +39 -0
  158. package/templates/apps/web/messages/en.json +264 -96
  159. package/templates/apps/web/middleware.ts +34 -2
  160. package/templates/apps/web/security-headers.config.ts +21 -0
  161. package/versions.json +48 -48
  162. package/templates/apps/web/app/[locale]/(authed)/account/components/schedule-service.tsx +0 -276
  163. package/templates/apps/web/app/[locale]/(authed)/account/components/send-message.tsx +0 -128
  164. package/templates/apps/web/app/[locale]/(authed)/account/settings/__tests__/theme-modes.test.ts +0 -42
  165. package/templates/apps/web/app/[locale]/(authed)/account/settings/theme-modes.ts +0 -40
  166. package/templates/apps/web/app/[locale]/(authed)/sign-in-gate.tsx +0 -162
  167. package/templates/apps/web/components/signed-in-nav.tsx +0 -79
  168. package/templates/apps/web/lib/hub-session/__tests__/sign-in-gate.test.tsx +0 -180
  169. package/templates/apps/web/lib/hub-session/sign-in-gate.tsx +0 -162
@@ -20,20 +20,42 @@
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.
29
+ *
30
+ * #11162 (AC-2): the Security tab's password link — a same-origin JSON POST
31
+ * for the sealed session's person, asked of the hub web as the spoke's
32
+ * client; no address and no password ever crosses this route.
23
33
  */
24
34
 
25
35
  import { createHash } from "node:crypto";
26
36
 
27
37
  const mockExchange = jest.fn();
28
38
  const mockRevoke = jest.fn();
39
+ const mockGoogle = jest.fn();
40
+ const mockMe = jest.fn();
29
41
  jest.mock("@working-theory/api-client", () => ({
30
42
  __esModule: true,
31
43
  hubSignIn: {
32
44
  exchange: (...args: unknown[]) => mockExchange(...args),
33
45
  revoke: (...args: unknown[]) => mockRevoke(...args),
46
+ google: (...args: unknown[]) => mockGoogle(...args),
47
+ me: (...args: unknown[]) => mockMe(...args),
34
48
  },
35
49
  }));
36
50
 
51
+ // #11096 — the bot check's external boundary is Vercel BotID: it runs only
52
+ // with `VERCEL=1`, so a case that wants a verdict sets that and answers here.
53
+ const mockCheckBotId = jest.fn();
54
+ jest.mock("botid/server", () => ({
55
+ __esModule: true,
56
+ checkBotId: (...args: unknown[]) => mockCheckBotId(...args),
57
+ }));
58
+
37
59
  const mockProvider: { value: "site" | "hub" | "none" } = { value: "hub" };
38
60
  // 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
61
  jest.mock("../../../../lib/topology.generated", () => ({
@@ -45,6 +67,12 @@ jest.mock("../../../../lib/topology.generated", () => ({
45
67
 
46
68
  import { seal, unseal } from "../../../../lib/hub-session/seal";
47
69
  import { GET as callback } from "../callback/route";
70
+ import { POST as email } from "../email/route";
71
+ import { POST as oneTapNonce } from "../one-tap/nonce/route";
72
+ import { POST as oneTap } from "../one-tap/route";
73
+ import { POST as open } from "../open/route";
74
+ import { GET as passwordReturn } from "../password/return/route";
75
+ import { POST as password } from "../password/route";
48
76
  import { GET as signIn } from "../sign-in/route";
49
77
  import { POST as signOut } from "../sign-out/route";
50
78
 
@@ -108,10 +136,19 @@ function callbackRequest(query: string, cookie?: string): Request {
108
136
  });
109
137
  }
110
138
 
139
+ const mockFetch = jest.fn();
140
+ const realFetch = global.fetch;
141
+
111
142
  beforeEach(() => {
112
143
  configure();
113
144
  mockProvider.value = "hub";
114
145
  mockExchange.mockReset();
146
+ mockGoogle.mockReset();
147
+ mockMe.mockReset();
148
+ mockCheckBotId.mockReset().mockResolvedValue({ isBot: false });
149
+ mockFetch.mockReset();
150
+ // 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.
151
+ global.fetch = mockFetch as unknown as typeof fetch;
115
152
  mockRevoke.mockReset().mockResolvedValue({ ok: true, body: { revoked: true } });
116
153
  jest.spyOn(console, "warn").mockImplementation(() => undefined);
117
154
  jest.spyOn(console, "error").mockImplementation(() => undefined);
@@ -119,6 +156,7 @@ beforeEach(() => {
119
156
 
120
157
  afterEach(() => {
121
158
  jest.restoreAllMocks();
159
+ global.fetch = realFetch;
122
160
  });
123
161
 
124
162
  afterAll(() => {
@@ -154,11 +192,12 @@ describe("GET /api/hub-session/sign-in", () => {
154
192
  );
155
193
  });
156
194
 
157
- it("with no configuration 303s to /account and sets no cookie", () => {
195
+ // #11095 D4: /account now redirects here, so landing there would loop.
196
+ it("with no configuration 303s to the site's home and sets no cookie", () => {
158
197
  configure({ AILK_HUB_CLIENT_SECRET: undefined });
159
198
  const res = signIn(new Request(`${SITE}/api/hub-session/sign-in?next=/account`));
160
199
  expect(res.status).toBe(303);
161
- expect(res.headers.get("location")).toBe("/account");
200
+ expect(res.headers.get("location")).toBe("/");
162
201
  expect(setCookies(res)).toEqual([]);
163
202
  });
164
203
 
@@ -306,7 +345,7 @@ describe("GET /api/hub-session/callback", () => {
306
345
  it("AC-5: without its flow cookie, burns the code at the hub and exchanges nothing", async () => {
307
346
  const res = await callback(callbackRequest(`code=${CODE}&state=${"s".repeat(43)}`));
308
347
  expect(res.status).toBe(303);
309
- expect(res.headers.get("location")).toBe("/account");
348
+ expect(res.headers.get("location")).toBe("/");
310
349
  expect(mockExchange).not.toHaveBeenCalled();
311
350
  expect(mockRevoke).toHaveBeenCalledTimes(1);
312
351
  expect(mockRevoke).toHaveBeenCalledWith(CLIENT, { code: CODE });
@@ -318,8 +357,15 @@ describe("GET /api/hub-session/callback", () => {
318
357
  const state = authorize.searchParams.get("state") ?? "";
319
358
  const cookie = `ailk-hub-flow=${flow}`;
320
359
 
321
- await callback(callbackRequest(`code=${CODE}&state=${"x".repeat(43)}`, cookie));
322
- await callback(callbackRequest(`code=${CODE}&state=${state}&error=access_denied`, cookie));
360
+ // #11095 D4: every refusal lands on the site's home, never /account.
361
+ const mismatch = await callback(callbackRequest(`code=${CODE}&state=${"x".repeat(43)}`, cookie));
362
+ expect(mismatch.status).toBe(303);
363
+ expect(mismatch.headers.get("location")).toBe("/");
364
+ const hubError = await callback(
365
+ callbackRequest(`code=${CODE}&state=${state}&error=access_denied`, cookie),
366
+ );
367
+ expect(hubError.status).toBe(303);
368
+ expect(hubError.headers.get("location")).toBe("/");
323
369
  const expired = seal(
324
370
  { v: 1, state, verifier: "v".repeat(43), next: "/account", expiresAt: Date.now() - 1 },
325
371
  SESSION_SECRET,
@@ -331,7 +377,7 @@ describe("GET /api/hub-session/callback", () => {
331
377
 
332
378
  mockExchange.mockResolvedValue({ ok: false, status: 400, body: { error: "invalid_grant" } });
333
379
  const failed = await callback(callbackRequest(`code=${CODE}&state=${state}`, cookie));
334
- expect(failed.headers.get("location")).toBe("/account");
380
+ expect(failed.headers.get("location")).toBe("/");
335
381
  expect(mockRevoke).toHaveBeenCalledTimes(4);
336
382
  for (const call of mockRevoke.mock.calls) expect(call).toEqual([CLIENT, { code: CODE }]);
337
383
  });
@@ -346,7 +392,7 @@ describe("GET /api/hub-session/callback", () => {
346
392
  const { flow, authorize } = start();
347
393
  const state = authorize.searchParams.get("state") ?? "";
348
394
  const res = await callback(callbackRequest(`code=${CODE}&state=${state}`, `ailk-hub-flow=${flow}`));
349
- expect(res.headers.get("location")).toBe("/account");
395
+ expect(res.headers.get("location")).toBe("/");
350
396
  expect(setCookies(res).some((c) => c.startsWith("ailk-hub-session="))).toBe(false);
351
397
  },
352
398
  );
@@ -360,6 +406,14 @@ describe("GET /api/hub-session/callback", () => {
360
406
  expect(logged).not.toContain("s".repeat(43));
361
407
  });
362
408
 
409
+ it("with no configuration 303s to the site's home (#11095 D4)", async () => {
410
+ configure({ AILK_HUB_CLIENT_SECRET: undefined });
411
+ const res = await callback(callbackRequest(`code=${CODE}&state=x`));
412
+ expect(res.status).toBe(303);
413
+ expect(res.headers.get("location")).toBe("/");
414
+ expect(mockExchange).not.toHaveBeenCalled();
415
+ });
416
+
363
417
  it("does not try to burn a malformed code", async () => {
364
418
  await callback(callbackRequest("code=not-a-code&state=x"));
365
419
  expect(mockRevoke).not.toHaveBeenCalled();
@@ -433,3 +487,680 @@ describe("POST /api/hub-session/sign-out", () => {
433
487
  expect((await post({ "sec-fetch-site": "same-origin" })).status).toBe(404);
434
488
  });
435
489
  });
490
+
491
+ // ── #11096 — the spoke-hosted entry ─────────────────────────────────────────
492
+
493
+ const SPOKE_KEY = "ailk_spk_test_key";
494
+ const CLAIM = "C".repeat(120);
495
+
496
+ /** A hub web answer for the mocked `fetch`. */
497
+ function hubAnswer(status: number, body: unknown): Response {
498
+ return new Response(JSON.stringify(body), {
499
+ status,
500
+ headers: { "content-type": "application/json" },
501
+ });
502
+ }
503
+
504
+ /** A same-origin form POST to one of the spoke's routes. */
505
+ function formPost(
506
+ path: string,
507
+ fields: Array<[string, string]>,
508
+ headers: Record<string, string> = { "sec-fetch-site": "same-origin", origin: SITE },
509
+ ): Request {
510
+ const body = new URLSearchParams(fields);
511
+ return new Request(`${SITE}${path}`, {
512
+ method: "POST",
513
+ headers: { "content-type": "application/x-www-form-urlencoded", ...headers },
514
+ body: body.toString(),
515
+ });
516
+ }
517
+
518
+ /** The one hub web call the mocked `fetch` received. */
519
+ function hubCall(): { url: string; headers: Headers; body: Record<string, unknown> } {
520
+ expect(mockFetch).toHaveBeenCalledTimes(1);
521
+ const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit];
522
+ return {
523
+ url,
524
+ headers: new Headers(init.headers),
525
+ body: JSON.parse(String(init.body)) as Record<string, unknown>,
526
+ };
527
+ }
528
+
529
+ /** The flow a 303's flow cookie seals. */
530
+ function flowOf(res: Response): Record<string, unknown> {
531
+ const flow = cookieValue(res, "ailk-hub-flow");
532
+ if (flow === undefined) throw new Error("no flow cookie");
533
+ const payload = unseal(flow, SESSION_SECRET, "flow", "ailk-hub-flow");
534
+ if (payload === null || typeof payload !== "object") throw new Error("flow did not open");
535
+ return payload as Record<string, unknown>;
536
+ }
537
+
538
+ describe("POST /api/hub-session/email (#11096 D2)", () => {
539
+ beforeEach(() => {
540
+ process.env.AILK_SPOKE_KEY = SPOKE_KEY;
541
+ });
542
+
543
+ 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 () => {
544
+ mockFetch.mockResolvedValue(hubAnswer(202, { sent: true }));
545
+ const res = await email(
546
+ formPost("/api/hub-session/email", [
547
+ ["email", "ada@example.com"],
548
+ ["next", "/account"],
549
+ ]),
550
+ );
551
+
552
+ expect(res.status).toBe(303);
553
+ expect(res.headers.get("location")).toBe("/account?sent=1");
554
+ expect(res.headers.get("cache-control")).toBe("no-store");
555
+ expect(res.headers.get("referrer-policy")).toBe("no-referrer");
556
+ expect(setCookies(res)).toHaveLength(1);
557
+ const flow = flowOf(res);
558
+ expect(flow.next).toBe("/account");
559
+
560
+ const call = hubCall();
561
+ expect(call.url).toBe(`${HUB}/api/auth/hub/email`);
562
+ expect(call.headers.get("authorization")).toBe(
563
+ `Basic ${Buffer.from(`${CLIENT.clientId}:${CLIENT.clientSecret}`).toString("base64")}`,
564
+ );
565
+ expect(call.headers.get("x-ailk-spoke-key")).toBe(SPOKE_KEY);
566
+ expect(call.body).toEqual({
567
+ client_id: CLIENT.clientId,
568
+ redirect_uri: `${SITE}/api/hub-session/callback`,
569
+ state: flow.state,
570
+ code_challenge: createHash("sha256").update(String(flow.verifier)).digest("base64url"),
571
+ code_challenge_method: "S256",
572
+ email: "ada@example.com",
573
+ locale: "en",
574
+ });
575
+ expect(call.body).not.toHaveProperty("agreements");
576
+ });
577
+
578
+ it("AC-2: ticked agreements ride to the hub web as their ids", async () => {
579
+ mockFetch.mockResolvedValue(hubAnswer(202, { sent: true }));
580
+ const res = await email(
581
+ formPost("/api/hub-session/email", [
582
+ ["email", "new@example.com"],
583
+ ["agreements", "account_terms"],
584
+ ]),
585
+ );
586
+ expect(res.headers.get("location")).toBe("/account?sent=1");
587
+ expect(hubCall().body.agreements).toEqual(["account_terms"]);
588
+ });
589
+
590
+ it("AC-2: the hub's agreements_required → 303 /account?error=agreements with no flow cookie", async () => {
591
+ mockFetch.mockResolvedValue(hubAnswer(400, { error: "agreements_required" }));
592
+ const res = await email(
593
+ formPost("/api/hub-session/email", [
594
+ ["email", "new@example.com"],
595
+ ["agreements", "account_terms"],
596
+ ]),
597
+ );
598
+ expect(res.status).toBe(303);
599
+ expect(res.headers.get("location")).toBe("/account?error=agreements");
600
+ expect(setCookies(res)).toEqual([]);
601
+ });
602
+
603
+ it.each([
604
+ ["sign_up_closed", () => mockFetch.mockResolvedValue(hubAnswer(400, { error: "sign_up_closed" }))],
605
+ ["a 401", () => mockFetch.mockResolvedValue(hubAnswer(401, { error: "invalid_client" }))],
606
+ ["a 429", () => mockFetch.mockResolvedValue(hubAnswer(429, { error: "rate_limited" }))],
607
+ ["a throw", () => mockFetch.mockRejectedValue(new Error("network"))],
608
+ ])("%s → 303 /account?error=unavailable with no flow cookie", async (_label, arrange) => {
609
+ arrange();
610
+ const res = await email(formPost("/api/hub-session/email", [["email", "ada@example.com"]]));
611
+ expect(res.headers.get("location")).toBe("/account?error=unavailable");
612
+ expect(setCookies(res)).toEqual([]);
613
+ });
614
+
615
+ it("returns to the locale's own account page", async () => {
616
+ configure({ NEXT_PUBLIC_ENABLED_LOCALES: "en,fr" });
617
+ process.env.AILK_SPOKE_KEY = SPOKE_KEY;
618
+ mockFetch.mockResolvedValue(hubAnswer(202, { sent: true }));
619
+ const res = await email(
620
+ formPost("/api/hub-session/email", [
621
+ ["email", "ada@example.com"],
622
+ ["next", "/fr/account/inbox"],
623
+ ]),
624
+ );
625
+ expect(res.headers.get("location")).toBe("/fr/account?sent=1");
626
+ expect(hubCall().body.locale).toBe("fr");
627
+ expect(flowOf(res).next).toBe("/fr/account/inbox");
628
+ });
629
+
630
+ it.each([
631
+ ["a password field (AC-6)", [["email", "ada@example.com"], ["password", "hunter22"]]],
632
+ ["a repeated email", [["email", "ada@example.com"], ["email", "eve@example.com"]]],
633
+ ["no email", [["next", "/account"]]],
634
+ ["a malformed email", [["email", "not-an-email"]]],
635
+ ["an unknown agreement shape", [["email", "ada@example.com"], ["agreements", "Not An Id"]]],
636
+ ] as Array<[string, Array<[string, string]>]>)("%s → 400, no hub call", async (_label, fields) => {
637
+ const res = await email(formPost("/api/hub-session/email", fields));
638
+ expect(res.status).toBe(400);
639
+ expect(mockFetch).not.toHaveBeenCalled();
640
+ expect(setCookies(res)).toEqual([]);
641
+ });
642
+
643
+ it.each([
644
+ ["cross-site", { "sec-fetch-site": "cross-site", origin: SITE }],
645
+ ["a foreign Origin", { "sec-fetch-site": "same-origin", origin: "https://evil.example.com" }],
646
+ ["neither header", {}],
647
+ ] as Array<[string, Record<string, string>]>)("refuses %s with 403, calling nothing", async (_label, headers) => {
648
+ const res = await email(formPost("/api/hub-session/email", [["email", "ada@example.com"]], headers));
649
+ expect(res.status).toBe(403);
650
+ expect(mockFetch).not.toHaveBeenCalled();
651
+ });
652
+
653
+ it("a visitor over the limit gets /account?error=unavailable and no hub call", async () => {
654
+ mockFetch.mockResolvedValue(hubAnswer(202, { sent: true }));
655
+ configure({ VERCEL: "1", AILK_BOT_CHECK: "off" });
656
+ const visitor = { "sec-fetch-site": "same-origin", origin: SITE, "x-vercel-forwarded-for": "203.0.113.77" };
657
+ for (let i = 0; i < 10; i++) {
658
+ await email(formPost("/api/hub-session/email", [["email", "ada@example.com"]], visitor));
659
+ }
660
+ mockFetch.mockClear();
661
+ const limited = await email(formPost("/api/hub-session/email", [["email", "ada@example.com"]], visitor));
662
+ expect(limited.headers.get("location")).toBe("/account?error=unavailable");
663
+ expect(mockFetch).not.toHaveBeenCalled();
664
+ });
665
+
666
+ it("a bot gets /account?error=unavailable and no hub call", async () => {
667
+ configure({ VERCEL: "1" });
668
+ mockCheckBotId.mockResolvedValue({ isBot: true, classificationReason: "test" });
669
+ const res = await email(
670
+ formPost("/api/hub-session/email", [["email", "ada@example.com"]], {
671
+ "sec-fetch-site": "same-origin",
672
+ origin: SITE,
673
+ "x-vercel-forwarded-for": "203.0.113.78",
674
+ }),
675
+ );
676
+ expect(res.headers.get("location")).toBe("/account?error=unavailable");
677
+ expect(mockFetch).not.toHaveBeenCalled();
678
+ });
679
+
680
+ it("with no configuration 303s to /account?error=unavailable", async () => {
681
+ configure({ AILK_HUB_CLIENT_SECRET: undefined });
682
+ const res = await email(formPost("/api/hub-session/email", [["email", "ada@example.com"]]));
683
+ expect(res.status).toBe(303);
684
+ expect(res.headers.get("location")).toBe("/account?error=unavailable");
685
+ expect(mockFetch).not.toHaveBeenCalled();
686
+ });
687
+
688
+ it("is 404 unless the provider is hub", async () => {
689
+ mockProvider.value = "site";
690
+ const res = await email(formPost("/api/hub-session/email", [["email", "ada@example.com"]]));
691
+ expect(res.status).toBe(404);
692
+ });
693
+
694
+ it("never logs the email", async () => {
695
+ const warn = jest.spyOn(console, "warn");
696
+ const error = jest.spyOn(console, "error");
697
+ mockFetch.mockRejectedValue(new Error("network"));
698
+ await email(formPost("/api/hub-session/email", [["email", "ada@example.com"]]));
699
+ const logged = [...warn.mock.calls, ...error.mock.calls].flat().join(" ");
700
+ expect(logged).not.toContain("ada@example.com");
701
+ });
702
+ });
703
+
704
+ describe("GET /api/hub-session/sign-in — Google's provider hint (#11096 D4, AC-3)", () => {
705
+ function startWith(query: string): { authorize: URL; payload: Record<string, unknown> } {
706
+ const res = signIn(new Request(`${SITE}/api/hub-session/sign-in?${query}`));
707
+ expect(res.status).toBe(303);
708
+ return { authorize: new URL(res.headers.get("location") ?? ""), payload: flowOf(res) };
709
+ }
710
+
711
+ it("?provider=google → provider_hint=google; the flow cookie keeps exactly its five keys", () => {
712
+ const { authorize, payload } = startWith("next=%2Faccount&provider=google");
713
+ expect(authorize.searchParams.getAll("provider_hint")).toEqual(["google"]);
714
+ expect(authorize.searchParams.get("code_challenge_method")).toBe("S256");
715
+ expect(Object.keys(payload).sort()).toEqual(["expiresAt", "next", "state", "v", "verifier"]);
716
+ expect(JSON.stringify(payload)).not.toContain("google");
717
+ });
718
+
719
+ it.each([
720
+ ["another provider", "next=/account&provider=github"],
721
+ ["an empty value", "next=/account&provider="],
722
+ ["a repeated value", "next=/account&provider=google&provider=google"],
723
+ ["no value", "next=/account"],
724
+ ])("%s → no provider_hint", (_label, query) => {
725
+ const { authorize } = startWith(query);
726
+ expect(authorize.searchParams.has("provider_hint")).toBe(false);
727
+ });
728
+ });
729
+
730
+ describe("POST /api/hub-session/open — the purchase link's one click (#11096 D9, AC-4)", () => {
731
+ beforeEach(() => {
732
+ process.env.AILK_SPOKE_KEY = SPOKE_KEY;
733
+ });
734
+
735
+ const VERIFY = `${HUB}/api/auth/magic-link/verify?token=t&callbackURL=%2Fapi%2Fauth%2Fhub%2Fcontinue%2Fr`;
736
+
737
+ it("spends the claim at the hub web and 303s to its verify URL with the flow cookie", async () => {
738
+ mockFetch.mockResolvedValue(hubAnswer(200, { verifyUrl: VERIFY }));
739
+ const res = await open(formPost("/api/hub-session/open", [["claim", CLAIM]]));
740
+ expect(res.status).toBe(303);
741
+ expect(res.headers.get("location")).toBe(VERIFY);
742
+ expect(res.headers.get("referrer-policy")).toBe("no-referrer");
743
+ const flow = flowOf(res);
744
+ expect(flow.next).toBe("/account");
745
+ const call = hubCall();
746
+ expect(call.url).toBe(`${HUB}/api/auth/hub/purchase`);
747
+ expect(call.headers.get("authorization")).toMatch(/^Basic /);
748
+ expect(call.headers.get("x-ailk-spoke-key")).toBe(SPOKE_KEY);
749
+ expect(call.body).toEqual({
750
+ claim: CLAIM,
751
+ client_id: CLIENT.clientId,
752
+ redirect_uri: `${SITE}/api/hub-session/callback`,
753
+ state: flow.state,
754
+ code_challenge: createHash("sha256").update(String(flow.verifier)).digest("base64url"),
755
+ code_challenge_method: "S256",
756
+ });
757
+ });
758
+
759
+ it("409 account_exists → 303 /account?error=exists, no flow cookie", async () => {
760
+ mockFetch.mockResolvedValue(hubAnswer(409, { error: "account_exists" }));
761
+ const res = await open(formPost("/api/hub-session/open", [["claim", CLAIM]]));
762
+ expect(res.headers.get("location")).toBe("/account?error=exists");
763
+ expect(setCookies(res)).toEqual([]);
764
+ });
765
+
766
+ it.each([
767
+ ["410 claim_used", () => mockFetch.mockResolvedValue(hubAnswer(410, { error: "claim_used" }))],
768
+ ["410 terms_changed", () => mockFetch.mockResolvedValue(hubAnswer(410, { error: "terms_changed" }))],
769
+ ["a verify URL off the hub", () => mockFetch.mockResolvedValue(hubAnswer(200, { verifyUrl: "https://evil.example.com/x" }))],
770
+ ["a throw", () => mockFetch.mockRejectedValue(new Error("network"))],
771
+ ])("%s → 303 /account?error=claim, no flow cookie", async (_label, arrange) => {
772
+ arrange();
773
+ const res = await open(formPost("/api/hub-session/open", [["claim", CLAIM]]));
774
+ expect(res.headers.get("location")).toBe("/account?error=claim");
775
+ expect(setCookies(res)).toEqual([]);
776
+ });
777
+
778
+ it.each([
779
+ ["an added field", [["claim", CLAIM], ["email", "ada@example.com"]]],
780
+ ["no claim", []],
781
+ ["a malformed claim", [["claim", "not a claim!"]]],
782
+ ] as Array<[string, Array<[string, string]>]>)("%s → 400, no hub call", async (_label, fields) => {
783
+ const res = await open(formPost("/api/hub-session/open", fields));
784
+ expect(res.status).toBe(400);
785
+ expect(mockFetch).not.toHaveBeenCalled();
786
+ });
787
+
788
+ it("refuses a cross-site POST with 403", async () => {
789
+ const res = await open(
790
+ formPost("/api/hub-session/open", [["claim", CLAIM]], { "sec-fetch-site": "cross-site" }),
791
+ );
792
+ expect(res.status).toBe(403);
793
+ expect(mockFetch).not.toHaveBeenCalled();
794
+ });
795
+ });
796
+
797
+ describe("POST /api/hub-session/one-tap and its nonce (#11096 D10, AC-5)", () => {
798
+ const ID_TOKEN = "header.payload.signature";
799
+ const SAME_ORIGIN = { "sec-fetch-site": "same-origin", origin: SITE };
800
+
801
+ function jsonPost(path: string, body: unknown, headers: Record<string, string> = SAME_ORIGIN): Request {
802
+ return new Request(`${SITE}${path}`, {
803
+ method: "POST",
804
+ headers: { "content-type": "application/json", ...headers },
805
+ body: JSON.stringify(body),
806
+ });
807
+ }
808
+
809
+ async function mintNonce(): Promise<{ nonce: string; cookie: string }> {
810
+ const res = await oneTapNonce(jsonPost("/api/hub-session/one-tap/nonce", {}));
811
+ expect(res.status).toBe(200);
812
+ const { nonce } = (await res.json()) as { nonce: string };
813
+ const value = cookieValue(res, "ailk-hub-one-tap");
814
+ if (value === undefined) throw new Error("no nonce cookie");
815
+ return { nonce, cookie: `ailk-hub-one-tap=${value}` };
816
+ }
817
+
818
+ beforeEach(() => {
819
+ configure({ AILK_HUB_ONE_TAP: "on" });
820
+ });
821
+
822
+ it("the nonce route mints 32 random bytes and seals them into a 300 s cookie", async () => {
823
+ const res = await oneTapNonce(jsonPost("/api/hub-session/one-tap/nonce", {}));
824
+ expect(res.status).toBe(200);
825
+ expect(res.headers.get("cache-control")).toBe("no-store");
826
+ const { nonce } = (await res.json()) as { nonce: string };
827
+ expect(nonce).toMatch(/^[A-Za-z0-9_-]{43}$/);
828
+ const line = setCookies(res).find((c) => c.startsWith("ailk-hub-one-tap="));
829
+ expect(line).toMatch(/; HttpOnly/);
830
+ expect(line).toMatch(/; Max-Age=300/);
831
+ expect(line).not.toContain(nonce);
832
+ });
833
+
834
+ it("AC-5: a valid credential and nonce cookie → 200 { ok: true }, the session cookie, the nonce cleared", async () => {
835
+ mockGoogle.mockResolvedValue({
836
+ ok: true,
837
+ body: { accessToken: CREDENTIAL, tokenType: "Bearer", expiresIn: 86400, user: USER },
838
+ });
839
+ const { nonce, cookie } = await mintNonce();
840
+ const res = await oneTap(
841
+ new Request(`${SITE}/api/hub-session/one-tap`, {
842
+ method: "POST",
843
+ headers: { "content-type": "application/json", cookie, ...SAME_ORIGIN },
844
+ body: JSON.stringify({ credential: ID_TOKEN }),
845
+ }),
846
+ );
847
+ expect(res.status).toBe(200);
848
+ expect(await res.json()).toEqual({ ok: true });
849
+ expect(mockGoogle).toHaveBeenCalledWith(CLIENT, { idToken: ID_TOKEN, nonce, origin: SITE });
850
+ const session = setCookies(res).find((c) => c.startsWith("ailk-hub-session="));
851
+ expect(session).toMatch(/; Max-Age=86400/);
852
+ expect(setCookies(res).find((c) => c.startsWith("ailk-hub-one-tap="))).toMatch(/Max-Age=0/);
853
+ expect(setCookies(res).join("\n")).not.toContain(CREDENTIAL);
854
+ });
855
+
856
+ it("no nonce cookie → 400 and no hub call", async () => {
857
+ const res = await oneTap(jsonPost("/api/hub-session/one-tap", { credential: ID_TOKEN }));
858
+ expect(res.status).toBe(400);
859
+ expect(mockGoogle).not.toHaveBeenCalled();
860
+ });
861
+
862
+ it.each([
863
+ ["a 404 (no Google account row)", { ok: false, status: 404, body: { error: "not_found" } }],
864
+ ["a 401", { ok: false, status: 401, body: { error: "invalid_grant" } }],
865
+ ])("the hub's %s → 401 { ok: false }, no session, the nonce cleared", async (_label, answer) => {
866
+ mockGoogle.mockResolvedValue(answer);
867
+ const { cookie } = await mintNonce();
868
+ const res = await oneTap(
869
+ new Request(`${SITE}/api/hub-session/one-tap`, {
870
+ method: "POST",
871
+ headers: { "content-type": "application/json", cookie, ...SAME_ORIGIN },
872
+ body: JSON.stringify({ credential: ID_TOKEN }),
873
+ }),
874
+ );
875
+ expect(res.status).toBe(401);
876
+ expect(await res.json()).toEqual({ ok: false });
877
+ expect(setCookies(res).some((c) => c.startsWith("ailk-hub-session="))).toBe(false);
878
+ expect(setCookies(res).find((c) => c.startsWith("ailk-hub-one-tap="))).toMatch(/Max-Age=0/);
879
+ });
880
+
881
+ it("AC-6: a body with a password field → 400, no hub call", async () => {
882
+ const { cookie } = await mintNonce();
883
+ const res = await oneTap(
884
+ new Request(`${SITE}/api/hub-session/one-tap`, {
885
+ method: "POST",
886
+ headers: { "content-type": "application/json", cookie, ...SAME_ORIGIN },
887
+ body: JSON.stringify({ credential: ID_TOKEN, password: "hunter22" }),
888
+ }),
889
+ );
890
+ expect(res.status).toBe(400);
891
+ expect(mockGoogle).not.toHaveBeenCalled();
892
+ });
893
+
894
+ it("refuses a cross-site POST with 403", async () => {
895
+ const nonce = await oneTapNonce(
896
+ jsonPost("/api/hub-session/one-tap/nonce", {}, { "sec-fetch-site": "cross-site" }),
897
+ );
898
+ expect(nonce.status).toBe(403);
899
+ const res = await oneTap(
900
+ jsonPost("/api/hub-session/one-tap", { credential: ID_TOKEN }, { "sec-fetch-site": "cross-site" }),
901
+ );
902
+ expect(res.status).toBe(403);
903
+ });
904
+
905
+ it("both routes 404 while AILK_HUB_ONE_TAP is not on", async () => {
906
+ configure();
907
+ expect((await oneTapNonce(jsonPost("/api/hub-session/one-tap/nonce", {}))).status).toBe(404);
908
+ expect(
909
+ (await oneTap(jsonPost("/api/hub-session/one-tap", { credential: ID_TOKEN }))).status,
910
+ ).toBe(404);
911
+ });
912
+ });
913
+
914
+ describe("POST /api/hub-session/password — the Security tab's password link (#11162 AC-2)", () => {
915
+ const SAME_ORIGIN = { "sec-fetch-site": "same-origin", origin: SITE };
916
+ const SESSION_COOKIE = "ailk-hub-session";
917
+
918
+ function sessionCookie(secret: string = SESSION_SECRET): string {
919
+ const sealed = seal(
920
+ { v: 1, accessToken: CREDENTIAL, expiresAt: Date.now() + 60_000, user: USER },
921
+ secret,
922
+ "session",
923
+ SESSION_COOKIE,
924
+ );
925
+ return `${SESSION_COOKIE}=${sealed}`;
926
+ }
927
+
928
+ function post(
929
+ body: unknown,
930
+ headers: Record<string, string> = { ...SAME_ORIGIN, cookie: sessionCookie() },
931
+ ): Request {
932
+ return new Request(`${SITE}/api/hub-session/password`, {
933
+ method: "POST",
934
+ headers: { "content-type": "application/json", ...headers },
935
+ body: typeof body === "string" ? body : JSON.stringify(body),
936
+ });
937
+ }
938
+
939
+ beforeEach(() => {
940
+ process.env.AILK_SPOKE_KEY = SPOKE_KEY;
941
+ });
942
+
943
+ it("asks the hub web as the spoke's client for the sealed session's person, never a body address; 202 { sent: true }", async () => {
944
+ mockFetch.mockResolvedValue(hubAnswer(202, { sent: true }));
945
+ const res = await password(post({ locale: "en" }));
946
+
947
+ expect(res.status).toBe(202);
948
+ expect(await res.json()).toEqual({ sent: true });
949
+ expect(res.headers.get("cache-control")).toBe("no-store");
950
+ expect(setCookies(res)).toEqual([]);
951
+
952
+ const call = hubCall();
953
+ expect(call.url).toBe(`${HUB}/api/auth/hub/password`);
954
+ expect(call.headers.get("authorization")).toBe(
955
+ `Basic ${Buffer.from(`${CLIENT.clientId}:${CLIENT.clientSecret}`).toString("base64")}`,
956
+ );
957
+ expect(call.headers.get("x-ailk-spoke-key")).toBe(SPOKE_KEY);
958
+ expect(call.body).toEqual({
959
+ client_id: CLIENT.clientId,
960
+ redirect_uri: `${SITE}/api/hub-session/callback`,
961
+ access_token: CREDENTIAL,
962
+ locale: "en",
963
+ return_path: "/account/security",
964
+ });
965
+ });
966
+
967
+ it("returns the person to the locale's own Security tab", async () => {
968
+ configure({ NEXT_PUBLIC_ENABLED_LOCALES: "en,fr" });
969
+ mockFetch.mockResolvedValue(hubAnswer(202, { sent: true }));
970
+ await password(post({ locale: "fr" }));
971
+ expect(hubCall().body).toMatchObject({ locale: "fr", return_path: "/fr/account/security" });
972
+ });
973
+
974
+ it("a locale this site does not enable reads as the default", async () => {
975
+ mockFetch.mockResolvedValue(hubAnswer(202, { sent: true }));
976
+ await password(post({ locale: "de" }));
977
+ expect(hubCall().body).toMatchObject({ locale: "en", return_path: "/account/security" });
978
+ });
979
+
980
+ it.each([
981
+ ["a password field (the spoke never accepts one)", { locale: "en", password: "hunter22" }],
982
+ ["an email field (the person is the session's)", { locale: "en", email: "eve@example.com" }],
983
+ ["no locale", {}],
984
+ ["a malformed locale", { locale: "english" }],
985
+ ["a body that is not JSON", "locale=en"],
986
+ ] as Array<[string, unknown]>)("%s → 400, no hub call", async (_label, body) => {
987
+ const res = await password(post(body));
988
+ expect(res.status).toBe(400);
989
+ expect(await res.json()).toEqual({ error: "invalid_request" });
990
+ expect(mockFetch).not.toHaveBeenCalled();
991
+ });
992
+
993
+ it("without a session cookie → 401, no hub call", async () => {
994
+ const res = await password(post({ locale: "en" }, SAME_ORIGIN));
995
+ expect(res.status).toBe(401);
996
+ expect(await res.json()).toEqual({ error: "no_session" });
997
+ expect(mockFetch).not.toHaveBeenCalled();
998
+ });
999
+
1000
+ it("a session sealed under another key → 401, no hub call", async () => {
1001
+ const res = await password(
1002
+ post({ locale: "en" }, { ...SAME_ORIGIN, cookie: sessionCookie("x".repeat(43)) }),
1003
+ );
1004
+ expect(res.status).toBe(401);
1005
+ expect(mockFetch).not.toHaveBeenCalled();
1006
+ });
1007
+
1008
+ it.each([
1009
+ ["cross-site", { "sec-fetch-site": "cross-site", origin: SITE }],
1010
+ ["a foreign Origin", { "sec-fetch-site": "same-origin", origin: "https://evil.example.com" }],
1011
+ ["neither header", {}],
1012
+ ] as Array<[string, Record<string, string>]>)("refuses %s with 403, calling nothing", async (_label, headers) => {
1013
+ const res = await password(post({ locale: "en" }, { ...headers, cookie: sessionCookie() }));
1014
+ expect(res.status).toBe(403);
1015
+ expect(mockFetch).not.toHaveBeenCalled();
1016
+ });
1017
+
1018
+ it("the hub's invalid_grant — a credential it no longer honours — → 401", async () => {
1019
+ mockFetch.mockResolvedValue(hubAnswer(400, { error: "invalid_grant" }));
1020
+ const res = await password(post({ locale: "en" }));
1021
+ expect(res.status).toBe(401);
1022
+ expect(await res.json()).toEqual({ error: "invalid_session" });
1023
+ });
1024
+
1025
+ it.each([
1026
+ ["a 401", () => mockFetch.mockResolvedValue(hubAnswer(401, { error: "invalid_client" }))],
1027
+ ["a 429", () => mockFetch.mockResolvedValue(hubAnswer(429, { error: "rate_limited" }))],
1028
+ ["a 503", () => mockFetch.mockResolvedValue(hubAnswer(503, { error: "temporarily_unavailable" }))],
1029
+ ["a throw", () => mockFetch.mockRejectedValue(new Error("network"))],
1030
+ ])("%s → 503 temporarily_unavailable", async (_label, arrange) => {
1031
+ arrange();
1032
+ const res = await password(post({ locale: "en" }));
1033
+ expect(res.status).toBe(503);
1034
+ expect(await res.json()).toEqual({ error: "temporarily_unavailable" });
1035
+ });
1036
+
1037
+ it("a visitor over the limit gets 429 and no hub call", async () => {
1038
+ configure({ VERCEL: "1", AILK_BOT_CHECK: "off" });
1039
+ mockFetch.mockResolvedValue(hubAnswer(202, { sent: true }));
1040
+ const visitor = { ...SAME_ORIGIN, cookie: sessionCookie(), "x-vercel-forwarded-for": "203.0.113.79" };
1041
+ for (let i = 0; i < 10; i++) {
1042
+ expect((await password(post({ locale: "en" }, visitor))).status).toBe(202);
1043
+ }
1044
+ mockFetch.mockClear();
1045
+ const limited = await password(post({ locale: "en" }, visitor));
1046
+ expect(limited.status).toBe(429);
1047
+ expect(mockFetch).not.toHaveBeenCalled();
1048
+ });
1049
+
1050
+ it("a bot gets 503 and no hub call", async () => {
1051
+ configure({ VERCEL: "1" });
1052
+ mockCheckBotId.mockResolvedValue({ isBot: true, classificationReason: "test" });
1053
+ const res = await password(
1054
+ post({ locale: "en" }, { ...SAME_ORIGIN, cookie: sessionCookie(), "x-vercel-forwarded-for": "203.0.113.80" }),
1055
+ );
1056
+ expect(res.status).toBe(503);
1057
+ expect(mockFetch).not.toHaveBeenCalled();
1058
+ });
1059
+
1060
+ it("with no configuration → 503, no hub call", async () => {
1061
+ configure({ AILK_HUB_CLIENT_SECRET: undefined });
1062
+ const res = await password(post({ locale: "en" }));
1063
+ expect(res.status).toBe(503);
1064
+ expect(mockFetch).not.toHaveBeenCalled();
1065
+ });
1066
+
1067
+ it("is 404 unless the provider is hub", async () => {
1068
+ mockProvider.value = "site";
1069
+ const res = await password(post({ locale: "en" }));
1070
+ expect(res.status).toBe(404);
1071
+ });
1072
+
1073
+ it("never logs the credential or the address", async () => {
1074
+ const warn = jest.spyOn(console, "warn");
1075
+ const error = jest.spyOn(console, "error");
1076
+ mockFetch.mockRejectedValue(new Error("network"));
1077
+ await password(post({ locale: "en" }));
1078
+ const logged = [...warn.mock.calls, ...error.mock.calls].flat().join(" ");
1079
+ expect(logged).not.toContain(CREDENTIAL);
1080
+ expect(logged).not.toContain(USER.email);
1081
+ });
1082
+ });
1083
+
1084
+ describe("GET /api/hub-session/password/return — where the hub's set-password page lands the person (#11162 AC-2)", () => {
1085
+ const SESSION_COOKIE = "ailk-hub-session";
1086
+ const CLEARED = /^ailk-hub-session=; Path=\/; HttpOnly; SameSite=Lax; Max-Age=0$/;
1087
+
1088
+ function sessionCookie(): string {
1089
+ const sealed = seal(
1090
+ { v: 1, accessToken: CREDENTIAL, expiresAt: Date.now() + 60_000, user: USER },
1091
+ SESSION_SECRET,
1092
+ "session",
1093
+ SESSION_COOKIE,
1094
+ );
1095
+ return `${SESSION_COOKIE}=${sealed}`;
1096
+ }
1097
+
1098
+ /** `cookie: null` is a request with no session cookie. */
1099
+ function get(next: string | null, cookie: string | null = sessionCookie()): Promise<Response> {
1100
+ const url = new URL("/api/hub-session/password/return", SITE);
1101
+ if (next !== null) url.searchParams.set("next", next);
1102
+ return passwordReturn(new Request(url.toString(), { headers: cookie === null ? {} : { cookie } }));
1103
+ }
1104
+
1105
+ it("a credential the hub no longer honours (the reset revoked it): the session cookie is cleared and the person lands on the tab, whose gate signs them back in", async () => {
1106
+ mockMe.mockResolvedValue({ ok: false, status: 401, body: { ok: false } });
1107
+ const res = await get("/account/security");
1108
+ expect(res.status).toBe(303);
1109
+ expect(res.headers.get("location")).toBe("/account/security");
1110
+ expect(res.headers.get("cache-control")).toBe("no-store");
1111
+ expect(setCookies(res)).toHaveLength(1);
1112
+ expect(setCookies(res)[0]).toMatch(CLEARED);
1113
+ expect(mockMe).toHaveBeenCalledWith({ headers: { authorization: `Bearer ${CREDENTIAL}` } });
1114
+ });
1115
+
1116
+ it("a credential the hub still honours keeps its cookie", async () => {
1117
+ mockMe.mockResolvedValue({ ok: true, status: 200, body: { user: USER, billingCustomerId: null, hasPassword: true } });
1118
+ const res = await get("/fr/account/security");
1119
+ expect(res.headers.get("location")).toBe("/fr/account/security");
1120
+ expect(setCookies(res)).toEqual([]);
1121
+ });
1122
+
1123
+ it.each([
1124
+ ["cannot be reached", () => mockMe.mockRejectedValue(new Error("network"))],
1125
+ ["answers a limit (429)", () => mockMe.mockResolvedValue({ ok: false, status: 429, body: { ok: false } })],
1126
+ ["answers an outage (503)", () => mockMe.mockResolvedValue({ ok: false, status: 503, body: { ok: false } })],
1127
+ ["refuses the spoke, not the credential (403)", () => mockMe.mockResolvedValue({ ok: false, status: 403, body: { ok: false } })],
1128
+ ])("a hub that %s clears nothing — only its 401 does", async (_label, arrange) => {
1129
+ arrange();
1130
+ const res = await get("/account/security");
1131
+ expect(res.headers.get("location")).toBe("/account/security");
1132
+ expect(setCookies(res)).toEqual([]);
1133
+ });
1134
+
1135
+ it("with no session cookie it only lands, asking the hub nothing", async () => {
1136
+ const res = await get("/account/security", null);
1137
+ expect(res.status).toBe(303);
1138
+ expect(res.headers.get("location")).toBe("/account/security");
1139
+ expect(setCookies(res)).toEqual([]);
1140
+ expect(mockMe).not.toHaveBeenCalled();
1141
+ });
1142
+
1143
+ it.each([
1144
+ ["an absolute URL", "https://evil.example.com/account/security"],
1145
+ ["a protocol-relative path", "//evil.example.com/account/security"],
1146
+ ["a route-handler path", "/api/hub-session/sign-out"],
1147
+ ["no next", null],
1148
+ ])("%s as next lands on /account", async (_label, next) => {
1149
+ mockMe.mockResolvedValue({ ok: true, status: 200, body: {} });
1150
+ const res = await get(next);
1151
+ expect(res.headers.get("location")).toBe("/account");
1152
+ });
1153
+
1154
+ it("with no configuration lands home", async () => {
1155
+ configure({ AILK_HUB_CLIENT_SECRET: undefined });
1156
+ const res = await get("/account/security");
1157
+ expect(res.headers.get("location")).toBe("/");
1158
+ expect(mockMe).not.toHaveBeenCalled();
1159
+ });
1160
+
1161
+ it("is 404 unless the provider is hub", async () => {
1162
+ mockProvider.value = "site";
1163
+ const res = await get("/account/security");
1164
+ expect(res.status).toBe(404);
1165
+ });
1166
+ });