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
@@ -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";
@@ -0,0 +1,148 @@
1
+ "use client"; // "use client" — loads Google's Identity Services script and handles its credential callback in the browser.
2
+
3
+ /**
4
+ * OneTap — Google One Tap on a spoke's signed-out account page (#11096 D10).
5
+ *
6
+ * Rendered by `SpokeSignIn` only when the spoke sets `AILK_HUB_ONE_TAP=on`
7
+ * and its hub reports a One Tap client id. On mount it asks this site's
8
+ * `POST /api/hub-session/one-tap/nonce` for a nonce, loads
9
+ * `https://accounts.google.com/gsi/client`, and calls
10
+ * `google.accounts.id.initialize({ client_id, nonce, callback,
11
+ * use_fedcm_for_prompt: true })` then `prompt()`. Google's callback hands the
12
+ * ID token to `POST /api/hub-session/one-tap`; only on `{ ok: true }` — the
13
+ * session cookie is set by then — does the page move, to `next`, on this
14
+ * site. Any other answer leaves the form as it is. Nothing here logs the
15
+ * token or the nonce.
16
+ */
17
+
18
+ import { type ReactElement, useEffect } from "react";
19
+
20
+ const GSI_SRC = "https://accounts.google.com/gsi/client";
21
+
22
+ interface GoogleIdentity {
23
+ accounts?: {
24
+ id?: {
25
+ initialize(options: {
26
+ client_id: string;
27
+ nonce: string;
28
+ callback: (response: { credential?: string }) => void;
29
+ use_fedcm_for_prompt: boolean;
30
+ }): void;
31
+ prompt(): void;
32
+ };
33
+ };
34
+ }
35
+
36
+ /** The one navigation the island makes — a test seam. */
37
+ export const oneTapNavigation = {
38
+ assign(url: string): void {
39
+ window.location.assign(url);
40
+ },
41
+ };
42
+
43
+ function googleIdentity(): GoogleIdentity | undefined {
44
+ return (window as unknown as { google?: GoogleIdentity }).google;
45
+ }
46
+
47
+ /** How long the island waits for Google's script before it gives up. */
48
+ const GSI_TIMEOUT_MS = 10_000;
49
+
50
+ /**
51
+ * Google's script, loaded once per page. Always settles: it rejects when the
52
+ * script fails, loads without `google.accounts.id`, or has not loaded within
53
+ * 10 s (a tag already on the page may have loaded before this listened). A
54
+ * rejection leaves the form as it is.
55
+ */
56
+ export function loadGoogle(): Promise<void> {
57
+ if (googleIdentity()?.accounts?.id) return Promise.resolve();
58
+ return new Promise((resolve, reject) => {
59
+ const fail = (): void => reject(new Error("gsi"));
60
+ const timer = setTimeout(fail, GSI_TIMEOUT_MS);
61
+ const existing = document.querySelector<HTMLScriptElement>(`script[src="${GSI_SRC}"]`);
62
+ const script = existing ?? document.createElement("script");
63
+ script.addEventListener(
64
+ "load",
65
+ () => {
66
+ clearTimeout(timer);
67
+ if (googleIdentity()?.accounts?.id) resolve();
68
+ else fail();
69
+ },
70
+ { once: true },
71
+ );
72
+ script.addEventListener(
73
+ "error",
74
+ () => {
75
+ clearTimeout(timer);
76
+ fail();
77
+ },
78
+ { once: true },
79
+ );
80
+ if (existing === null) {
81
+ script.src = GSI_SRC;
82
+ script.async = true;
83
+ document.head.appendChild(script);
84
+ }
85
+ });
86
+ }
87
+
88
+ async function postJson(url: string, body: unknown): Promise<unknown> {
89
+ const res = await fetch(url, {
90
+ method: "POST",
91
+ credentials: "same-origin",
92
+ headers: { "content-type": "application/json" },
93
+ body: JSON.stringify(body),
94
+ });
95
+ if (!res.ok) return null;
96
+ return res.json().catch(() => null);
97
+ }
98
+
99
+ export interface OneTapProps {
100
+ /** The hub's Google client id, from the hub's client info. */
101
+ clientId: string;
102
+ /** Where to land once signed in — a path on this site, already sanitized. */
103
+ next: string;
104
+ }
105
+
106
+ export function OneTap({ clientId, next }: OneTapProps): ReactElement {
107
+ useEffect(() => {
108
+ let cancelled = false;
109
+ const onCredential = async (response: { credential?: string }): Promise<void> => {
110
+ if (typeof response.credential !== "string") return;
111
+ const answer = await postJson("/api/hub-session/one-tap", {
112
+ credential: response.credential,
113
+ }).catch(() => null);
114
+ if (
115
+ typeof answer === "object" &&
116
+ answer !== null &&
117
+ (answer as { ok?: unknown }).ok === true
118
+ ) {
119
+ oneTapNavigation.assign(next);
120
+ }
121
+ };
122
+ const start = async (): Promise<void> => {
123
+ const minted = await postJson("/api/hub-session/one-tap/nonce", {});
124
+ const nonce =
125
+ typeof minted === "object" && minted !== null
126
+ ? (minted as { nonce?: unknown }).nonce
127
+ : undefined;
128
+ if (typeof nonce !== "string") return;
129
+ await loadGoogle();
130
+ const id = googleIdentity()?.accounts?.id;
131
+ if (cancelled || !id) return;
132
+ id.initialize({
133
+ client_id: clientId,
134
+ nonce,
135
+ callback: (response) => void onCredential(response),
136
+ use_fedcm_for_prompt: true,
137
+ });
138
+ id.prompt();
139
+ };
140
+ start().catch(() => undefined);
141
+ return () => {
142
+ cancelled = true;
143
+ };
144
+ }, [clientId, next]);
145
+
146
+ // Google draws its own prompt; this marker only names the island.
147
+ return <div hidden data-testid="spoke-sign-in-one-tap" data-client-id={clientId} />;
148
+ }
@@ -16,16 +16,22 @@
16
16
  * - `hubSessionBuyer(request)` — a customer the hub vouches for at buy time
17
17
  * (D13): read live from `GET /v1/hub-sign-in/me`, never from the cookie.
18
18
  *
19
+ * And the two writers every route that starts or finishes a sign-in shares
20
+ * (#11096 D2, D6): `startHubFlow` seals a new flow, and `sessionCookieFor`
21
+ * seals a credential the hub answered into the session cookie.
22
+ *
19
23
  * Nothing here logs a credential, a cookie value or an email.
20
24
  */
21
25
 
22
- import { hubSignIn } from "@working-theory/api-client";
26
+ import { createHash, randomBytes } from "node:crypto";
27
+
28
+ import { type HubSignInTokenResponse, hubSignIn } from "@working-theory/api-client";
23
29
  import { headers as requestHeaders } from "next/headers";
24
30
 
25
31
  import { resolveNextPath } from "../next-path";
26
32
 
27
33
  import { type HubSessionConfig, hubSessionConfig } from "./config";
28
- import { unseal } from "./seal";
34
+ import { seal, unseal } from "./seal";
29
35
 
30
36
  /** The session cookie: `__Host-` on an https site, plain on a loopback one. */
31
37
  export function sessionCookieName(config: Pick<HubSessionConfig, "secure">): string {
@@ -37,6 +43,14 @@ export function flowCookieName(config: Pick<HubSessionConfig, "secure">): string
37
43
  return config.secure ? "__Host-ailk-hub-flow" : "ailk-hub-flow";
38
44
  }
39
45
 
46
+ /** One Tap's nonce cookie (#11096 D10), named as the other two are. */
47
+ export function oneTapCookieName(config: Pick<HubSessionConfig, "secure">): string {
48
+ return config.secure ? "__Host-ailk-hub-one-tap" : "ailk-hub-one-tap";
49
+ }
50
+
51
+ /** How long a One Tap nonce lives — Google's prompt and the person's tap. */
52
+ export const ONE_TAP_NONCE_TTL_SECONDS = 300;
53
+
40
54
  /** The person a hub session names — the fields the account area reads. */
41
55
  export interface HubSessionUser {
42
56
  name: string | null;
@@ -164,6 +178,13 @@ export async function hubSessionBuyer(
164
178
  /** Where to land after signing in, when `next` is missing or refused. */
165
179
  export const HUB_SESSION_FALLBACK_PATH = "/account";
166
180
 
181
+ /**
182
+ * Where a sign-in this site cannot complete lands (#11095 D4): the site's
183
+ * home. Never `/account`, whose signed-out gate redirects straight back into
184
+ * the sign-in — a loop.
185
+ */
186
+ export const HUB_SESSION_HOME_PATH = "/";
187
+
167
188
  /**
168
189
  * The post-sign-in path for `raw`: `resolveNextPath`'s same-origin rule,
169
190
  * printable ASCII only (it becomes a `Location` header), and never a path
@@ -178,3 +199,100 @@ export function hubNextPath(raw: unknown): string {
178
199
  ? HUB_SESSION_FALLBACK_PATH
179
200
  : next;
180
201
  }
202
+
203
+ /** How long a sign-in may take on the hub before the flow cookie expires. */
204
+ export const FLOW_TTL_SECONDS = 600;
205
+
206
+ /** The longest session the spoke keeps — the hub's own credential lifetime (spec 7894 D5). */
207
+ const MAX_SESSION_SECONDS = 86_400;
208
+
209
+ /** A sign-in flow just started: what the hub is sent, and the cookie that remembers it. */
210
+ export interface HubFlow {
211
+ /** The opaque `state` the hub echoes back. */
212
+ state: string;
213
+ /** The S256 challenge of the sealed verifier. */
214
+ challenge: string;
215
+ /** The `Set-Cookie` value of the sealed flow cookie (ten minutes). */
216
+ cookie: string;
217
+ }
218
+
219
+ /**
220
+ * Start a sign-in through the hub (#7894 D2; shared by every route that
221
+ * starts one, #11096 D2): a `state` and a PKCE verifier (32 random bytes
222
+ * each, base64url) sealed with the sanitized `next` into the flow cookie.
223
+ * Nothing here logs the state, the verifier or the challenge.
224
+ */
225
+ export function startHubFlow(config: HubSessionConfig, next: unknown): HubFlow {
226
+ const state = randomBytes(32).toString("base64url");
227
+ const verifier = randomBytes(32).toString("base64url");
228
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
229
+ const name = flowCookieName(config);
230
+ const flow = seal(
231
+ {
232
+ v: 1,
233
+ state,
234
+ verifier,
235
+ next: hubNextPath(next),
236
+ expiresAt: Date.now() + FLOW_TTL_SECONDS * 1000,
237
+ },
238
+ config.sessionSecret,
239
+ "flow",
240
+ name,
241
+ );
242
+ return { state, challenge, cookie: cookieHeader(name, flow, FLOW_TTL_SECONDS, config) };
243
+ }
244
+
245
+ /**
246
+ * The session cookie for a credential the hub answered (#11096 D6) — the
247
+ * callback's code exchange and One Tap's both mint one. `null` when
248
+ * `expiresIn` is not a whole number of seconds from 1 to a day: a malformed
249
+ * answer from the hub must never yield a session that does not expire.
250
+ */
251
+ export function sessionCookieFor(
252
+ config: HubSessionConfig,
253
+ token: Pick<HubSignInTokenResponse, "accessToken" | "expiresIn" | "user">,
254
+ ): string | null {
255
+ const { accessToken, expiresIn, user } = token;
256
+ if (!Number.isInteger(expiresIn) || expiresIn < 1 || expiresIn > MAX_SESSION_SECONDS) {
257
+ return null;
258
+ }
259
+ const payload: HubSessionPayload = {
260
+ v: 1,
261
+ accessToken,
262
+ expiresAt: Date.now() + expiresIn * 1000,
263
+ user: {
264
+ name: user.name,
265
+ email: user.email,
266
+ emailVerified: user.emailVerified,
267
+ createdAt: user.createdAt,
268
+ },
269
+ };
270
+ const name = sessionCookieName(config);
271
+ return cookieHeader(name, seal(payload, config.sessionSecret, "session", name), expiresIn, config);
272
+ }
273
+
274
+ /**
275
+ * Whether `request` comes from a page on `siteOrigin`: a `Sec-Fetch-Site`
276
+ * other than `same-origin`, an `Origin` other than the site's, or a request
277
+ * carrying neither is not. The check every state-changing POST of this
278
+ * module's routes makes before anything else.
279
+ */
280
+ export function isSameOrigin(request: Request, siteOrigin: string | null): boolean {
281
+ const fetchSite = request.headers.get("sec-fetch-site");
282
+ const origin = request.headers.get("origin");
283
+ if (fetchSite === null && origin === null) return false;
284
+ if (fetchSite !== null && fetchSite !== "same-origin") return false;
285
+ if (origin !== null && origin !== siteOrigin) return false;
286
+ return true;
287
+ }
288
+
289
+ /** A 303 with no cache and no referrer, carrying each `Set-Cookie` given. */
290
+ export function seeOther(location: string, setCookies: readonly string[] = []): Response {
291
+ const headers = new Headers({
292
+ Location: location,
293
+ "Cache-Control": "no-store",
294
+ "Referrer-Policy": "no-referrer",
295
+ });
296
+ for (const value of setCookies) headers.append("Set-Cookie", value);
297
+ return new Response(null, { status: 303, headers });
298
+ }