create-ailk 0.34.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 (139) hide show
  1. package/README.md +1 -1
  2. package/component-catalog.json +37 -4
  3. package/component-catalog.md +11 -9
  4. package/dist/add-module.js +7 -2
  5. package/dist/derive-architecture.js +2 -0
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/lib/env-catalog.js +8 -0
  9. package/dist/module-architecture.js +9 -0
  10. package/dist/programmatic.js +5 -2
  11. package/dist/site-listing-path.d.ts +8 -0
  12. package/dist/site-listing-path.js +8 -0
  13. package/dist/surfaces.d.ts +20 -0
  14. package/dist/surfaces.js +32 -3
  15. package/dist/template-record.js +2 -0
  16. package/dist/topology.d.ts +4 -4
  17. package/dist/topology.js +104 -60
  18. package/dist/update.js +11 -0
  19. package/package.json +3 -3
  20. package/templates/.env.example +21 -0
  21. package/templates/apps/api/.env.example +7 -0
  22. package/templates/apps/api/CLAUDE.md +14 -9
  23. package/templates/apps/mcp/CLAUDE.md +18 -7
  24. package/templates/apps/web/.env.example +16 -0
  25. package/templates/apps/web/CLAUDE.md +46 -5
  26. package/templates/apps/web/app/[locale]/(auth)/__tests__/password-reset.test.tsx +2 -0
  27. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/page.test.tsx +52 -1
  28. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/remembered-method.test.ts +43 -0
  29. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/sign-in-card.test.tsx +108 -1
  30. package/templates/apps/web/app/[locale]/(auth)/sign-in/page.tsx +36 -3
  31. package/templates/apps/web/app/[locale]/(auth)/sign-in/remembered-method.ts +37 -0
  32. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-card.tsx +90 -33
  33. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-text.ts +9 -4
  34. package/templates/apps/web/app/[locale]/(authed)/__tests__/gate.test.tsx +79 -348
  35. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/billing.test.tsx +12 -1
  36. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +55 -2
  37. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/item.test.tsx +43 -0
  38. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout-sign-out.test.tsx +10 -5
  39. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/page.test.tsx +6 -5
  40. package/templates/apps/web/app/[locale]/(authed)/account/account-frame.tsx +1 -1
  41. package/templates/apps/web/app/[locale]/(authed)/account/billing/page.tsx +60 -6
  42. package/templates/apps/web/app/[locale]/(authed)/account/billing-source.ts +32 -3
  43. package/templates/apps/web/app/[locale]/(authed)/account/connect/__tests__/page.test.tsx +8 -1
  44. package/templates/apps/web/app/[locale]/(authed)/account/connect/page.tsx +7 -3
  45. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/phone-verification.test.tsx +215 -0
  46. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/seam-imports.test.ts +65 -0
  47. package/templates/apps/web/app/[locale]/(authed)/account/general/page.tsx +47 -0
  48. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-actions.ts +122 -0
  49. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-verification.tsx +214 -0
  50. package/templates/apps/web/app/[locale]/(authed)/account/inbox/[kind]/[id]/page.tsx +6 -1
  51. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/invitation-id.test.ts +35 -0
  52. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/page.test.tsx +266 -0
  53. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/actions.ts +116 -0
  54. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/invitation-id.ts +12 -0
  55. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/page.tsx +154 -0
  56. package/templates/apps/web/app/[locale]/(authed)/account/layout.tsx +6 -4
  57. package/templates/apps/web/app/[locale]/(authed)/account/security/page.tsx +3 -1
  58. package/templates/apps/web/app/[locale]/(authed)/layout.tsx +15 -13
  59. package/templates/apps/web/app/[locale]/(authed)/signed-out-gate.generated.tsx +20 -52
  60. package/templates/apps/web/app/[locale]/flows/[slug]/FlowStepperClient.tsx +43 -4
  61. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.deliverable.test.tsx +23 -9
  62. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.invite.test.tsx +15 -0
  63. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.permalink.test.tsx +74 -0
  64. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.test.tsx +34 -1
  65. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/magnet-page.test.tsx +257 -4
  66. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/save.actions.test.ts +72 -92
  67. package/templates/apps/web/app/[locale]/flows/[slug]/email-moment.ts +2 -2
  68. package/templates/apps/web/app/[locale]/flows/[slug]/magnet-page.tsx +164 -65
  69. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/LevelChart.tsx +100 -0
  70. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsCard.tsx +99 -0
  71. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsClient.tsx +415 -253
  72. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsEmailStep.tsx +113 -32
  73. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/ResultsClient.no-commerce.test.tsx +16 -17
  74. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/ResultsClient.report.test.tsx +284 -0
  75. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/by-result.test.tsx +52 -19
  76. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/cards.test.tsx +402 -0
  77. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/page.test.tsx +100 -12
  78. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/score.test.tsx +153 -101
  79. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/meeting-seam.ts +36 -0
  80. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/page.tsx +121 -33
  81. package/templates/apps/web/app/[locale]/flows/[slug]/save.actions.ts +27 -17
  82. package/templates/apps/web/app/[locale]/flows/[slug]/served-flow.ts +91 -0
  83. package/templates/apps/web/app/[locale]/layout.tsx +42 -76
  84. package/templates/apps/web/app/[locale]/purchase/__tests__/success.test.tsx +50 -0
  85. package/templates/apps/web/app/[locale]/purchase/success/page.tsx +48 -7
  86. package/templates/apps/web/app/api/auth/hub/__tests__/entry-routes.test.ts +749 -0
  87. package/templates/apps/web/app/api/auth/hub/authorize/__tests__/route.test.ts +189 -6
  88. package/templates/apps/web/app/api/auth/hub/authorize/route.ts +101 -31
  89. package/templates/apps/web/app/api/auth/hub/continuation.ts +51 -2
  90. package/templates/apps/web/app/api/auth/hub/email/route.ts +111 -0
  91. package/templates/apps/web/app/api/auth/hub/entry-shared.ts +163 -0
  92. package/templates/apps/web/app/api/auth/hub/purchase/route.ts +230 -0
  93. package/templates/apps/web/app/api/auth/hub/purchase-link/route.ts +174 -0
  94. package/templates/apps/web/app/api/auth/hub/sign-up/route.ts +60 -0
  95. package/templates/apps/web/app/api/auth/hub/sign-up-evidence.ts +97 -0
  96. package/templates/apps/web/app/api/hub-session/__tests__/routes.test.ts +475 -7
  97. package/templates/apps/web/app/api/hub-session/callback/route.ts +13 -47
  98. package/templates/apps/web/app/api/hub-session/email/route.ts +125 -0
  99. package/templates/apps/web/app/api/hub-session/one-tap/nonce/route.ts +49 -0
  100. package/templates/apps/web/app/api/hub-session/one-tap/route.ts +106 -0
  101. package/templates/apps/web/app/api/hub-session/open/route.ts +111 -0
  102. package/templates/apps/web/app/api/hub-session/sign-in/route.ts +23 -40
  103. package/templates/apps/web/app/api/hub-session/sign-out/route.ts +1 -10
  104. package/templates/apps/web/app/llms.txt/__tests__/site-listing.test.ts +122 -0
  105. package/templates/apps/web/app/llms.txt/route.ts +14 -2
  106. package/templates/apps/web/app/sitemap.xml/__tests__/site-listing.test.ts +98 -0
  107. package/templates/apps/web/app/sitemap.xml/route.ts +13 -2
  108. package/templates/apps/web/auth.ts +133 -6
  109. package/templates/apps/web/components/sign-out-trigger.tsx +1 -1
  110. package/templates/apps/web/lib/__tests__/auth-email.test.ts +141 -0
  111. package/templates/apps/web/lib/__tests__/auth-phone.test.ts +445 -0
  112. package/templates/apps/web/lib/__tests__/auth-sms.test.ts +140 -0
  113. package/templates/apps/web/lib/__tests__/fixtures/tsconfig.flow.json +18 -0
  114. package/templates/apps/web/lib/__tests__/site-header.test.ts +13 -0
  115. package/templates/apps/web/lib/__tests__/telemetry-scrub.test.ts +19 -1
  116. package/templates/apps/web/lib/account-config.ts +24 -9
  117. package/templates/apps/web/lib/auth-email.ts +62 -6
  118. package/templates/apps/web/lib/auth-env.ts +13 -0
  119. package/templates/apps/web/lib/auth-sms.ts +180 -0
  120. package/templates/apps/web/lib/hub-session/__tests__/hub-session.test.ts +28 -0
  121. package/templates/apps/web/lib/hub-session/__tests__/spoke-sign-in.test.tsx +332 -0
  122. package/templates/apps/web/lib/hub-session/config.ts +7 -1
  123. package/templates/apps/web/lib/hub-session/entry.ts +238 -0
  124. package/templates/apps/web/lib/hub-session/index.ts +1 -4
  125. package/templates/apps/web/lib/hub-session/one-tap.tsx +148 -0
  126. package/templates/apps/web/lib/hub-session/session.ts +120 -2
  127. package/templates/apps/web/lib/hub-session/spoke-sign-in.tsx +277 -0
  128. package/templates/apps/web/lib/site-header.ts +14 -1
  129. package/templates/apps/web/lib/site-listing.ts +7 -0
  130. package/templates/apps/web/lib/telemetry-scrub.ts +11 -0
  131. package/templates/apps/web/lib/topology.generated.ts +39 -0
  132. package/templates/apps/web/messages/en.json +125 -21
  133. package/templates/apps/web/middleware.ts +34 -2
  134. package/templates/apps/web/security-headers.config.ts +21 -0
  135. package/versions.json +47 -47
  136. package/templates/apps/web/app/[locale]/(authed)/sign-in-gate.tsx +0 -162
  137. package/templates/apps/web/components/signed-in-nav.tsx +0 -79
  138. package/templates/apps/web/lib/hub-session/__tests__/sign-in-gate.test.tsx +0 -180
  139. package/templates/apps/web/lib/hub-session/sign-in-gate.tsx +0 -162
@@ -0,0 +1,332 @@
1
+ /**
2
+ * The spoke's own signed-out account page (#11096 D1, D3, D9, D10; spec
3
+ * docs/specs/11096-the-spoke-hosts-the-sign-spec.md AC-1, AC-4, AC-5, AC-6).
4
+ *
5
+ * `SpokeSignIn` is a server component the generated gate seam renders for
6
+ * every signed-out `(authed)` path on a spoke that signs in through its hub.
7
+ * It reads its state from the middleware's `x-search` and the hub web's
8
+ * sign-up facts (`GET /api/auth/hub/sign-up`, the mocked `fetch`); the hub
9
+ * API's client info (One Tap's client id) comes through the api-client.
10
+ * `OneTap` is the one client island; its own cases are at the end.
11
+ */
12
+ import { act, render, screen, waitFor } from "@testing-library/react";
13
+
14
+ jest.mock("next-intl/server", () => {
15
+ const msgs: unknown = require("../../../messages/en.json");
16
+ const dig = (obj: unknown, path: string): unknown =>
17
+ path.split(".").reduce<unknown>(
18
+ (acc, k) => (acc !== null && typeof acc === "object" ? (acc as Record<string, unknown>)[k] : undefined),
19
+ obj,
20
+ );
21
+ return {
22
+ __esModule: true,
23
+ getTranslations: async (arg: string | { namespace?: string }) => {
24
+ const ns = typeof arg === "string" ? arg : (arg.namespace ?? "");
25
+ const messages = dig(msgs, ns);
26
+ return (key: string, values?: Record<string, unknown>): string => {
27
+ const value = dig(messages, key);
28
+ if (typeof value !== "string") return `${ns}.${key}`;
29
+ return value.replace(/\{(\w+)\}/g, (m, name: string) =>
30
+ values && name in values ? String(values[name]) : m,
31
+ );
32
+ };
33
+ },
34
+ };
35
+ });
36
+
37
+ const mockClientInfo = jest.fn();
38
+ jest.mock("@working-theory/api-client", () => ({
39
+ __esModule: true,
40
+ hubSignIn: { clientInfo: (...args: unknown[]) => mockClientInfo(...args) },
41
+ }));
42
+
43
+ import { resetHubEntryReads } from "../entry";
44
+ import { loadGoogle, OneTap, oneTapNavigation } from "../one-tap";
45
+ import { SpokeSignIn } from "../spoke-sign-in";
46
+
47
+ const HUB = "https://hub.example";
48
+ const SITE = "https://spoke.example";
49
+ const ENV = process.env;
50
+
51
+ const AGREEMENT = {
52
+ purposeId: "account_terms",
53
+ statement: "I accept the [Terms](terms) and the [Privacy Policy](privacy).",
54
+ policies: { terms: `${HUB}/terms`, privacy: `${HUB}/privacy` },
55
+ };
56
+
57
+ const mockFetch = jest.fn();
58
+ const realFetch = global.fetch;
59
+
60
+ /** A `fetch` answer (jsdom has no `Response`): the two members the code reads. */
61
+ function signUpAnswer(body: unknown, status = 200): { ok: boolean; status: number; json: () => Promise<unknown> } {
62
+ return { ok: status >= 200 && status < 300, status, json: async () => body };
63
+ }
64
+
65
+ async function renderGate(search = "", pathname = "/account"): Promise<void> {
66
+ const headers = new Headers({ "x-pathname": pathname, "x-search": search });
67
+ render(await SpokeSignIn({ locale: "en", requestHeaders: headers }));
68
+ }
69
+
70
+ beforeEach(() => {
71
+ process.env = {
72
+ ...ENV,
73
+ AILK_HUB_SIGN_IN_URL: HUB,
74
+ AILK_HUB_CLIENT_ID: "spoke_0001",
75
+ AILK_HUB_CLIENT_SECRET: `ailk_hcs_${"c".repeat(43)}`,
76
+ AILK_HUB_SESSION_SECRET: "s".repeat(43),
77
+ NEXT_PUBLIC_BASE_URL: SITE,
78
+ };
79
+ resetHubEntryReads();
80
+ mockFetch.mockReset().mockResolvedValue(
81
+ signUpAnswer({ signUpOpen: true, google: true, agreements: [AGREEMENT] }),
82
+ );
83
+ // 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.
84
+ global.fetch = mockFetch as unknown as typeof fetch;
85
+ mockClientInfo.mockReset().mockResolvedValue({
86
+ ok: true,
87
+ body: { clientId: "spoke_0001", name: "Spoke", origin: SITE, oneTapClientId: "g-client.apps" },
88
+ });
89
+ });
90
+
91
+ afterEach(() => {
92
+ process.env = ENV;
93
+ global.fetch = realFetch;
94
+ });
95
+
96
+ describe("AC-1 — the spoke's own form", () => {
97
+ it("renders email, one agreement and Google, and no link to the hub's sign-in", async () => {
98
+ await renderGate();
99
+ expect(screen.getByTestId("auth-email")).toHaveAttribute("name", "email");
100
+ // The visible label names the field (Field's htmlFor → the input's id).
101
+ expect(screen.getByLabelText("Email")).toBe(screen.getByTestId("auth-email"));
102
+ expect(screen.getByTestId("spoke-sign-in-agreement-account_terms")).toBeInTheDocument();
103
+ expect(screen.getByTestId("spoke-sign-in-google")).toHaveAttribute(
104
+ "href",
105
+ "/api/hub-session/sign-in?next=%2Faccount&provider=google",
106
+ );
107
+ // The only hub URLs on the page are the agreement's own policy links
108
+ // (D3: the policies are the hub's); nothing links to a hub sign-in page.
109
+ const hubHrefs = Array.from(document.querySelectorAll("[href]"))
110
+ .filter((el) => (el.getAttribute("href") ?? "").includes("hub.example"))
111
+ .map((el) => el.getAttribute("data-testid"));
112
+ expect(hubHrefs).toEqual(["consent-policy-link-terms", "consent-policy-link-privacy"]);
113
+ expect(document.querySelector('[href*="hub.example/sign-in"]')).toBeNull();
114
+ expect(document.querySelector('[href*="/api/auth/hub/"]')).toBeNull();
115
+ expect(mockFetch).toHaveBeenCalledWith(
116
+ `${HUB}/api/auth/hub/sign-up?locale=en`,
117
+ expect.anything(),
118
+ );
119
+ });
120
+
121
+ it("the form posts natively to the spoke's email route, carrying next", async () => {
122
+ await renderGate("", "/account/inbox");
123
+ const form = screen.getByTestId("spoke-sign-in-form");
124
+ expect(form.tagName).toBe("FORM");
125
+ expect(form).toHaveAttribute("method", "post");
126
+ expect(form).toHaveAttribute("action", "/api/hub-session/email");
127
+ expect(form.querySelector('input[name="next"]')).toHaveAttribute("value", "/account/inbox");
128
+ // The ticked agreement posts its purpose id under `agreements`, unticked by default.
129
+ const box = screen.getByTestId("spoke-sign-in-agreement-account_terms");
130
+ expect(box).toHaveAttribute("aria-checked", "false");
131
+ expect(screen.getByTestId("spoke-sign-in-submit")).toHaveAttribute("type", "submit");
132
+ });
133
+
134
+ it("?sent=1 renders the sent state and no form", async () => {
135
+ await renderGate("?sent=1");
136
+ expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent("Check your email");
137
+ expect(screen.getByTestId("spoke-sign-in-sent")).toBeInTheDocument();
138
+ expect(screen.queryByTestId("spoke-sign-in-form")).not.toBeInTheDocument();
139
+ });
140
+
141
+ it.each([
142
+ ["?error=agreements", "spoke-sign-in-agreements-error"],
143
+ ["?error=unavailable", "spoke-sign-in-unavailable"],
144
+ ["?error=exists", "spoke-sign-in-exists"],
145
+ ["?error=claim", "spoke-sign-in-claim-error"],
146
+ ])("%s renders its line above the form", async (search, testId) => {
147
+ await renderGate(search);
148
+ expect(screen.getByTestId(testId)).toBeInTheDocument();
149
+ expect(screen.getByTestId("spoke-sign-in-form")).toBeInTheDocument();
150
+ });
151
+
152
+ it("a failed sign-up read renders the form with no agreements and no Google", async () => {
153
+ mockFetch.mockResolvedValue(signUpAnswer({ error: "x" }, 503));
154
+ await renderGate();
155
+ expect(screen.getByTestId("spoke-sign-in-form")).toBeInTheDocument();
156
+ expect(screen.queryByTestId("spoke-sign-in-agreement-account_terms")).not.toBeInTheDocument();
157
+ expect(screen.queryByTestId("spoke-sign-in-google")).not.toBeInTheDocument();
158
+ });
159
+
160
+ it("sign-up closed hides the agreements; Google off hides its button", async () => {
161
+ mockFetch.mockResolvedValue(signUpAnswer({ signUpOpen: false, google: false, agreements: [AGREEMENT] }));
162
+ await renderGate();
163
+ expect(screen.queryByTestId("spoke-sign-in-agreement-account_terms")).not.toBeInTheDocument();
164
+ expect(screen.queryByTestId("spoke-sign-in-google")).not.toBeInTheDocument();
165
+ });
166
+
167
+ it("not configured: says sign-in isn't available and renders no form", async () => {
168
+ delete process.env.AILK_HUB_CLIENT_SECRET;
169
+ await renderGate();
170
+ expect(screen.getByTestId("account-sign-in-gate")).toHaveTextContent("Sign-in isn't available yet");
171
+ expect(screen.queryByTestId("spoke-sign-in-form")).not.toBeInTheDocument();
172
+ expect(mockFetch).not.toHaveBeenCalled();
173
+ });
174
+ });
175
+
176
+ describe("AC-6 — no password on the spoke", () => {
177
+ it("the form has no password input", async () => {
178
+ await renderGate();
179
+ expect(document.querySelector("input[type=password]")).toBeNull();
180
+ expect(document.querySelector('[name="password"]')).toBeNull();
181
+ });
182
+ });
183
+
184
+ describe("AC-4 — the purchase link's open state (D9)", () => {
185
+ const CLAIM = "C".repeat(120);
186
+
187
+ it("renders Open my account under the statement, in a POST form to the open route, with no checkbox", async () => {
188
+ await renderGate(`?claim=${CLAIM}`);
189
+ const open = screen.getByTestId("spoke-sign-in-open");
190
+ const form = open.closest("form");
191
+ expect(form).toHaveAttribute("method", "post");
192
+ expect(form).toHaveAttribute("action", "/api/hub-session/open");
193
+ expect(form?.querySelector('input[name="claim"]')).toHaveAttribute("value", CLAIM);
194
+ expect(screen.getByTestId("spoke-sign-in-open-terms")).toHaveTextContent(
195
+ "I accept the Terms and the Privacy Policy.",
196
+ );
197
+ expect(document.querySelector('[role="checkbox"]')).toBeNull();
198
+ expect(screen.queryByTestId("spoke-sign-in-form")).not.toBeInTheDocument();
199
+ });
200
+
201
+ it("rendering it makes no hub call but the sign-up read", async () => {
202
+ await renderGate(`?claim=${CLAIM}`);
203
+ expect(mockFetch).toHaveBeenCalledTimes(1);
204
+ expect(String(mockFetch.mock.calls[0]?.[0])).toBe(`${HUB}/api/auth/hub/sign-up?locale=en`);
205
+ });
206
+
207
+ it("a malformed claim renders the form instead", async () => {
208
+ await renderGate("?claim=not%20a%20claim");
209
+ expect(screen.queryByTestId("spoke-sign-in-open")).not.toBeInTheDocument();
210
+ expect(screen.getByTestId("spoke-sign-in-form")).toBeInTheDocument();
211
+ });
212
+
213
+ it("without the hub's agreements it offers no button, only the unavailable line", async () => {
214
+ mockFetch.mockResolvedValue(signUpAnswer({}, 503));
215
+ await renderGate(`?claim=${CLAIM}`);
216
+ expect(screen.queryByTestId("spoke-sign-in-open")).not.toBeInTheDocument();
217
+ expect(screen.getByTestId("spoke-sign-in-unavailable")).toBeInTheDocument();
218
+ });
219
+ });
220
+
221
+ describe("AC-5 — One Tap on the spoke (D10)", () => {
222
+ it("with AILK_HUB_ONE_TAP=on and the hub's client id, renders the island with that id", async () => {
223
+ process.env.AILK_HUB_ONE_TAP = "on";
224
+ await renderGate();
225
+ expect(screen.getByTestId("spoke-sign-in-one-tap")).toHaveAttribute(
226
+ "data-client-id",
227
+ "g-client.apps",
228
+ );
229
+ });
230
+
231
+ it.each([
232
+ ["the spoke's setting off", () => undefined],
233
+ [
234
+ "the hub sending no client id",
235
+ () => {
236
+ process.env.AILK_HUB_ONE_TAP = "on";
237
+ mockClientInfo.mockResolvedValue({ ok: true, body: { clientId: "spoke_0001", name: "Spoke", origin: SITE } });
238
+ },
239
+ ],
240
+ ])("with %s, renders no island", async (_label, arrange) => {
241
+ arrange();
242
+ await renderGate();
243
+ expect(screen.queryByTestId("spoke-sign-in-one-tap")).not.toBeInTheDocument();
244
+ });
245
+
246
+ describe("the island", () => {
247
+ type Init = { client_id: string; nonce: string; callback: (r: { credential: string }) => void };
248
+ let initialize: jest.Mock;
249
+ let prompt: jest.Mock;
250
+ let assign: jest.SpyInstance;
251
+
252
+ /** Google's Identity Services global, as its script would leave it. */
253
+ const gsiWindow = window as Window & { google?: unknown };
254
+
255
+ beforeEach(() => {
256
+ initialize = jest.fn();
257
+ prompt = jest.fn();
258
+ gsiWindow.google = { accounts: { id: { initialize, prompt } } };
259
+ assign = jest.spyOn(oneTapNavigation, "assign").mockImplementation(() => undefined);
260
+ });
261
+
262
+ afterEach(() => {
263
+ delete gsiWindow.google;
264
+ assign.mockRestore();
265
+ });
266
+
267
+ async function started(): Promise<Init> {
268
+ mockFetch.mockReset().mockResolvedValueOnce(signUpAnswer({ nonce: "n".repeat(43) }));
269
+ render(<OneTap clientId="g-client.apps" next="/account/inbox" />);
270
+ await waitFor(() => expect(initialize).toHaveBeenCalledTimes(1));
271
+ expect(prompt).toHaveBeenCalledTimes(1);
272
+ return initialize.mock.calls[0]?.[0] as Init;
273
+ }
274
+
275
+ it("asks the nonce route, then initializes Google with the client id and that nonce", async () => {
276
+ const init = await started();
277
+ expect(String(mockFetch.mock.calls[0]?.[0])).toBe("/api/hub-session/one-tap/nonce");
278
+ expect(init.client_id).toBe("g-client.apps");
279
+ expect(init.nonce).toBe("n".repeat(43));
280
+ });
281
+
282
+ it("navigates to next only after the spoke route answers { ok: true }", async () => {
283
+ const init = await started();
284
+ mockFetch.mockResolvedValueOnce(signUpAnswer({ ok: false }, 401));
285
+ await act(async () => {
286
+ init.callback({ credential: "a.b.c" });
287
+ });
288
+ expect(assign).not.toHaveBeenCalled();
289
+
290
+ mockFetch.mockResolvedValueOnce(signUpAnswer({ ok: true }));
291
+ await act(async () => {
292
+ init.callback({ credential: "a.b.c" });
293
+ });
294
+ await waitFor(() => expect(assign).toHaveBeenCalledWith("/account/inbox"));
295
+ const [url, request] = mockFetch.mock.calls[2] as [string, RequestInit];
296
+ expect(url).toBe("/api/hub-session/one-tap");
297
+ expect(JSON.parse(String(request.body))).toEqual({ credential: "a.b.c" });
298
+ });
299
+ });
300
+
301
+ describe("loadGoogle always settles", () => {
302
+ const gsiWindow = window as Window & { google?: unknown };
303
+ const SRC = "https://accounts.google.com/gsi/client";
304
+
305
+ afterEach(() => {
306
+ jest.useRealTimers();
307
+ delete gsiWindow.google;
308
+ document.querySelectorAll(`script[src="${SRC}"]`).forEach((node) => node.remove());
309
+ });
310
+
311
+ it("resolves at once when Google's global is already there", async () => {
312
+ gsiWindow.google = { accounts: { id: { initialize: jest.fn(), prompt: jest.fn() } } };
313
+ await expect(loadGoogle()).resolves.toBeUndefined();
314
+ });
315
+
316
+ it("rejects when the script loads but leaves no google.accounts.id", async () => {
317
+ const loading = loadGoogle();
318
+ document.querySelector(`script[src="${SRC}"]`)?.dispatchEvent(new Event("load"));
319
+ await expect(loading).rejects.toThrow("gsi");
320
+ });
321
+
322
+ it("rejects after 10 s when a script tag already on the page never loads again", async () => {
323
+ jest.useFakeTimers();
324
+ const tag = document.createElement("script");
325
+ tag.setAttribute("src", SRC);
326
+ document.head.appendChild(tag);
327
+ const loading = loadGoogle();
328
+ jest.advanceTimersByTime(10_000);
329
+ await expect(loading).rejects.toThrow("gsi");
330
+ });
331
+ });
332
+ });
@@ -12,7 +12,10 @@
12
12
  * - `AILK_HUB_CLIENT_SECRET` — the secret `spokes sign-in-client` printed;
13
13
  * - `AILK_HUB_SESSION_SECRET` — this site's own cookie key material (at
14
14
  * least 32 characters). It never derives from
15
- * the client secret (`seal.ts`).
15
+ * the client secret (`seal.ts`);
16
+ * - `AILK_HUB_ONE_TAP` — `on` turns on Google One Tap for a
17
+ * returning person (#11096 D10); anything
18
+ * else, or unset, leaves it off.
16
19
  *
17
20
  * The site's own origin is `resolveBaseUrl()` — `NEXT_PUBLIC_BASE_URL`, else
18
21
  * the site's `baseUrl` — never a request header, so a forged `Host` cannot move
@@ -44,6 +47,8 @@ export interface HubSessionConfig {
44
47
  redirectUri: string;
45
48
  /** Whether the site origin is https — the cookies are then `__Host-` and `Secure`. */
46
49
  secure: boolean;
50
+ /** Whether Google One Tap is on for this spoke (`AILK_HUB_ONE_TAP=on`, #11096 D10). */
51
+ oneTap: boolean;
47
52
  }
48
53
 
49
54
  /**
@@ -100,5 +105,6 @@ export function hubSessionConfig(): HubSessionConfig | null {
100
105
  siteOrigin,
101
106
  redirectUri: `${siteOrigin}${HUB_SESSION_CALLBACK_PATH}`,
102
107
  secure: siteOrigin.startsWith("https:"),
108
+ oneTap: process.env.AILK_HUB_ONE_TAP === "on",
103
109
  };
104
110
  }
@@ -0,0 +1,238 @@
1
+ /**
2
+ * The spoke's server-to-server calls to its hub's WEB app (#11096 D2, D3, D9).
3
+ *
4
+ * The spoke-hosted entry form never sends a browser to the hub to type an
5
+ * email: the spoke's own routes post it here, server-side, and the hub web
6
+ * answers. Every call authenticates the spoke as its hub sign-in client —
7
+ * `Authorization: Basic <clientId:clientSecret>` beside the spoke key
8
+ * (`AILK_SPOKE_KEY`), the pair `POST /v1/hub-sign-in/token` already needs —
9
+ * and is bounded at 5 seconds. A refusal, a timeout or a throw is an answer
10
+ * the caller maps; nothing here throws, and nothing here logs a body, an
11
+ * email, a claim or a header.
12
+ *
13
+ * - `postToHub(config, path, body)` — the email route's
14
+ * `POST /api/auth/hub/email` and the open route's
15
+ * `POST /api/auth/hub/purchase`;
16
+ * - `readHubSignUp(config, locale)` — `GET /api/auth/hub/sign-up`, the
17
+ * hub's sign-up agreements and whether Google is on (D3), shared per
18
+ * instance for 60 seconds per locale;
19
+ * - `readOneTapClientId(config)` — the hub's One Tap client id from the
20
+ * client-info read (D10), shared the same way;
21
+ * - `localeOfPath(path)` — the enabled locale a site path is under.
22
+ */
23
+
24
+ import { hubSignIn } from "@working-theory/api-client";
25
+ import {
26
+ type HubSignUpInfoResponse,
27
+ hubSignUpInfoResponseSchema,
28
+ } from "@working-theory/validation";
29
+
30
+ import type { HubSessionConfig } from "./config";
31
+
32
+ /** The longest a hub web call may hold a spoke request. */
33
+ const HUB_CALL_TIMEOUT_MS = 5_000;
34
+
35
+ /** How long one read of the hub's sign-up facts or client info is shared. */
36
+ const SHARED_READ_MS = 60_000;
37
+
38
+ const DEFAULT_LOCALE = "en";
39
+
40
+ /** What a hub web call answered: its status and its JSON body (`null` when none). */
41
+ export interface HubAnswer {
42
+ status: number;
43
+ body: unknown;
44
+ }
45
+
46
+ function clientHeaders(config: HubSessionConfig): Record<string, string> {
47
+ const basic = Buffer.from(`${config.clientId}:${config.clientSecret}`, "utf8").toString("base64");
48
+ const spokeKey = process.env.AILK_SPOKE_KEY?.trim() ?? "";
49
+ return {
50
+ authorization: `Basic ${basic}`,
51
+ ...(spokeKey !== "" ? { "x-ailk-spoke-key": spokeKey } : {}),
52
+ };
53
+ }
54
+
55
+ /**
56
+ * POST `body` as JSON to `path` on the hub web, as this spoke's client.
57
+ * `null` on a throw or a timeout; a redirect is refused, never followed.
58
+ */
59
+ export async function postToHub(
60
+ config: HubSessionConfig,
61
+ path: string,
62
+ body: Record<string, unknown>,
63
+ ): Promise<HubAnswer | null> {
64
+ try {
65
+ const res = await fetch(new URL(path, config.hubOrigin).toString(), {
66
+ method: "POST",
67
+ headers: { ...clientHeaders(config), "content-type": "application/json" },
68
+ body: JSON.stringify(body),
69
+ redirect: "error",
70
+ cache: "no-store",
71
+ signal: AbortSignal.timeout(HUB_CALL_TIMEOUT_MS),
72
+ });
73
+ let parsed: unknown = null;
74
+ try {
75
+ parsed = await res.json();
76
+ } catch {
77
+ parsed = null;
78
+ }
79
+ return { status: res.status, body: parsed };
80
+ } catch {
81
+ return null;
82
+ }
83
+ }
84
+
85
+ /** The `error` code of a hub web refusal, or `null`. */
86
+ export function hubError(answer: HubAnswer | null): string | null {
87
+ const body = answer?.body;
88
+ if (typeof body !== "object" || body === null) return null;
89
+ const error = (body as Record<string, unknown>)["error"];
90
+ return typeof error === "string" ? error : null;
91
+ }
92
+
93
+ interface Shared<T> {
94
+ value: T;
95
+ at: number;
96
+ }
97
+
98
+ const signUpReads = new Map<string, Shared<HubSignUpInfoResponse | null>>();
99
+ const signUpPending = new Map<string, Promise<HubSignUpInfoResponse | null>>();
100
+ let oneTapRead: Shared<string | null> | null = null;
101
+ let oneTapPending: Promise<string | null> | null = null;
102
+
103
+ /** Test seam: forget every shared read. */
104
+ export function resetHubEntryReads(): void {
105
+ signUpReads.clear();
106
+ signUpPending.clear();
107
+ oneTapRead = null;
108
+ oneTapPending = null;
109
+ }
110
+
111
+ async function fetchSignUp(
112
+ config: HubSessionConfig,
113
+ locale: string,
114
+ ): Promise<HubSignUpInfoResponse | null> {
115
+ try {
116
+ const url = new URL("/api/auth/hub/sign-up", config.hubOrigin);
117
+ url.searchParams.set("locale", locale);
118
+ const res = await fetch(url.toString(), {
119
+ redirect: "error",
120
+ cache: "no-store",
121
+ signal: AbortSignal.timeout(HUB_CALL_TIMEOUT_MS),
122
+ });
123
+ if (!res.ok) return null;
124
+ const parsed = hubSignUpInfoResponseSchema.safeParse(await res.json());
125
+ return parsed.success ? parsed.data : null;
126
+ } catch {
127
+ return null;
128
+ }
129
+ }
130
+
131
+ /**
132
+ * The hub's sign-up facts for `locale` (D3): whether sign-up is open, whether
133
+ * Google is on, and the agreements a new person accepts, each policy link
134
+ * absolute on the hub. Shared per instance for 60 seconds per locale, a
135
+ * failed read included, and concurrent misses share one read. `null` when
136
+ * the hub cannot be read: the form then shows no agreements and no Google.
137
+ */
138
+ export function readHubSignUp(
139
+ config: HubSessionConfig,
140
+ locale: string,
141
+ ): Promise<HubSignUpInfoResponse | null> {
142
+ const shared = signUpReads.get(locale);
143
+ if (shared && Date.now() - shared.at < SHARED_READ_MS) return Promise.resolve(shared.value);
144
+ const pending = signUpPending.get(locale);
145
+ if (pending) return pending;
146
+ const read = fetchSignUp(config, locale)
147
+ .then((value) => {
148
+ signUpReads.set(locale, { value, at: Date.now() });
149
+ return value;
150
+ })
151
+ .finally(() => signUpPending.delete(locale));
152
+ signUpPending.set(locale, read);
153
+ return read;
154
+ }
155
+
156
+ /**
157
+ * The hub's Google client id for One Tap (D10), from the client-info read
158
+ * (`GET /v1/hub-sign-in/clients/:clientId`), or `null` when the hub has One
159
+ * Tap off or cannot be read. Shared per instance for 60 seconds.
160
+ */
161
+ export function readOneTapClientId(config: HubSessionConfig): Promise<string | null> {
162
+ if (oneTapRead && Date.now() - oneTapRead.at < SHARED_READ_MS) {
163
+ return Promise.resolve(oneTapRead.value);
164
+ }
165
+ if (oneTapPending) return oneTapPending;
166
+ oneTapPending = hubSignIn
167
+ .clientInfo(config.clientId)
168
+ .then((res) => (res.ok ? (res.body.oneTapClientId ?? null) : null))
169
+ .catch(() => null)
170
+ .then((value) => {
171
+ oneTapRead = { value, at: Date.now() };
172
+ return value;
173
+ })
174
+ .finally(() => {
175
+ oneTapPending = null;
176
+ });
177
+ return oneTapPending;
178
+ }
179
+
180
+ function enabledLocales(): string[] {
181
+ const enabled = (process.env.NEXT_PUBLIC_ENABLED_LOCALES ?? DEFAULT_LOCALE)
182
+ .split(",")
183
+ .map((locale) => locale.trim())
184
+ .filter((locale) => locale.length > 0);
185
+ return enabled.length > 0 ? enabled : [DEFAULT_LOCALE];
186
+ }
187
+
188
+ /**
189
+ * The enabled locale a site path sits under (`/fr/account` → `fr`), else the
190
+ * default — the enabled list and default locale `middleware.ts` routes with.
191
+ */
192
+ export function localeOfPath(path: string): string {
193
+ const segment = path.split("/")[1] ?? "";
194
+ return segment !== DEFAULT_LOCALE && enabledLocales().includes(segment)
195
+ ? segment
196
+ : DEFAULT_LOCALE;
197
+ }
198
+
199
+ /** `/account` under `locale`, with `query` — where every entry route lands. */
200
+ export function accountPath(locale: string, query: string): string {
201
+ return `${locale === DEFAULT_LOCALE ? "" : `/${locale}`}/account?${query}`;
202
+ }
203
+
204
+ /** The largest form or JSON body an entry route reads. */
205
+ const MAX_BODY_BYTES = 8_192;
206
+
207
+ /**
208
+ * The body of an entry route's POST as text, or `null` when it is larger than
209
+ * 8 KB or cannot be read.
210
+ */
211
+ export async function readBodyText(request: Request): Promise<string | null> {
212
+ const declared = Number(request.headers.get("content-length") ?? "0");
213
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) return null;
214
+ try {
215
+ const text = await request.text();
216
+ return Buffer.byteLength(text, "utf8") > MAX_BODY_BYTES ? null : text;
217
+ } catch {
218
+ return null;
219
+ }
220
+ }
221
+
222
+ /**
223
+ * An `application/x-www-form-urlencoded` POST as `{ name: values[] }`, or
224
+ * `null` when it is not one, is too large or cannot be read.
225
+ */
226
+ export async function readFormFields(
227
+ request: Request,
228
+ ): Promise<Map<string, string[]> | null> {
229
+ const type = request.headers.get("content-type") ?? "";
230
+ if (!type.toLowerCase().startsWith("application/x-www-form-urlencoded")) return null;
231
+ const text = await readBodyText(request);
232
+ if (text === null) return null;
233
+ const fields = new Map<string, string[]>();
234
+ for (const [name, value] of new URLSearchParams(text)) {
235
+ fields.set(name, [...(fields.get(name) ?? []), value]);
236
+ }
237
+ return fields;
238
+ }
@@ -2,10 +2,6 @@
2
2
  * The spoke's hub-client module (#7894 D7) — sign-in through the hub, with no
3
3
  * database. It imports no spoke removal seed and no `(auth)` file, so a spoke
4
4
  * keeps it (create-ailk's closure guard proves that, spec 7894 D9).
5
- *
6
- * The signed-out gate (`sign-in-gate.tsx`) is imported by its own path from
7
- * the generated gate seam, so the server-side readers below never pull a
8
- * React tree into the modules that call them.
9
5
  */
10
6
 
11
7
  export {
@@ -22,3 +18,4 @@ export {
22
18
  readHubSession,
23
19
  } from "./session";
24
20
  export { resealHubSession } from "./reseal";
21
+ export { SpokeSignIn, type SpokeSignInProps } from "./spoke-sign-in";