create-ailk 0.35.1 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +1 -1
  2. package/component-catalog.json +12 -1
  3. package/component-catalog.md +6 -5
  4. package/dist/lib/env-catalog.js +8 -0
  5. package/dist/surfaces.js +6 -3
  6. package/dist/topology.d.ts +4 -4
  7. package/dist/topology.js +104 -60
  8. package/package.json +3 -3
  9. package/templates/.env.example +21 -0
  10. package/templates/apps/api/.env.example +7 -0
  11. package/templates/apps/api/CLAUDE.md +9 -4
  12. package/templates/apps/mcp/CLAUDE.md +4 -2
  13. package/templates/apps/web/.env.example +16 -0
  14. package/templates/apps/web/CLAUDE.md +46 -5
  15. package/templates/apps/web/app/[locale]/(auth)/__tests__/password-reset.test.tsx +2 -0
  16. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/page.test.tsx +52 -1
  17. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/remembered-method.test.ts +43 -0
  18. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/sign-in-card.test.tsx +108 -1
  19. package/templates/apps/web/app/[locale]/(auth)/sign-in/page.tsx +36 -3
  20. package/templates/apps/web/app/[locale]/(auth)/sign-in/remembered-method.ts +37 -0
  21. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-card.tsx +90 -33
  22. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-text.ts +9 -4
  23. package/templates/apps/web/app/[locale]/(authed)/__tests__/gate.test.tsx +79 -348
  24. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/billing.test.tsx +12 -1
  25. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +55 -2
  26. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout-sign-out.test.tsx +10 -5
  27. package/templates/apps/web/app/[locale]/(authed)/account/account-frame.tsx +1 -1
  28. package/templates/apps/web/app/[locale]/(authed)/account/billing/page.tsx +60 -6
  29. package/templates/apps/web/app/[locale]/(authed)/account/billing-source.ts +32 -3
  30. package/templates/apps/web/app/[locale]/(authed)/account/connect/__tests__/page.test.tsx +8 -1
  31. package/templates/apps/web/app/[locale]/(authed)/account/connect/page.tsx +7 -3
  32. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/phone-verification.test.tsx +215 -0
  33. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/seam-imports.test.ts +65 -0
  34. package/templates/apps/web/app/[locale]/(authed)/account/general/page.tsx +47 -0
  35. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-actions.ts +122 -0
  36. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-verification.tsx +214 -0
  37. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/invitation-id.test.ts +35 -0
  38. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/page.test.tsx +266 -0
  39. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/actions.ts +116 -0
  40. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/invitation-id.ts +12 -0
  41. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/page.tsx +154 -0
  42. package/templates/apps/web/app/[locale]/(authed)/account/layout.tsx +6 -4
  43. package/templates/apps/web/app/[locale]/(authed)/account/security/page.tsx +3 -1
  44. package/templates/apps/web/app/[locale]/(authed)/layout.tsx +15 -13
  45. package/templates/apps/web/app/[locale]/(authed)/signed-out-gate.generated.tsx +20 -52
  46. package/templates/apps/web/app/[locale]/layout.tsx +24 -75
  47. package/templates/apps/web/app/[locale]/purchase/__tests__/success.test.tsx +50 -0
  48. package/templates/apps/web/app/[locale]/purchase/success/page.tsx +48 -7
  49. package/templates/apps/web/app/api/auth/hub/__tests__/entry-routes.test.ts +749 -0
  50. package/templates/apps/web/app/api/auth/hub/authorize/__tests__/route.test.ts +166 -7
  51. package/templates/apps/web/app/api/auth/hub/authorize/route.ts +96 -30
  52. package/templates/apps/web/app/api/auth/hub/continuation.ts +51 -2
  53. package/templates/apps/web/app/api/auth/hub/email/route.ts +111 -0
  54. package/templates/apps/web/app/api/auth/hub/entry-shared.ts +163 -0
  55. package/templates/apps/web/app/api/auth/hub/purchase/route.ts +230 -0
  56. package/templates/apps/web/app/api/auth/hub/purchase-link/route.ts +174 -0
  57. package/templates/apps/web/app/api/auth/hub/sign-up/route.ts +60 -0
  58. package/templates/apps/web/app/api/auth/hub/sign-up-evidence.ts +97 -0
  59. package/templates/apps/web/app/api/hub-session/__tests__/routes.test.ts +475 -7
  60. package/templates/apps/web/app/api/hub-session/callback/route.ts +13 -47
  61. package/templates/apps/web/app/api/hub-session/email/route.ts +125 -0
  62. package/templates/apps/web/app/api/hub-session/one-tap/nonce/route.ts +49 -0
  63. package/templates/apps/web/app/api/hub-session/one-tap/route.ts +106 -0
  64. package/templates/apps/web/app/api/hub-session/open/route.ts +111 -0
  65. package/templates/apps/web/app/api/hub-session/sign-in/route.ts +23 -40
  66. package/templates/apps/web/app/api/hub-session/sign-out/route.ts +1 -10
  67. package/templates/apps/web/auth.ts +133 -6
  68. package/templates/apps/web/components/sign-out-trigger.tsx +1 -1
  69. package/templates/apps/web/lib/__tests__/auth-email.test.ts +141 -0
  70. package/templates/apps/web/lib/__tests__/auth-phone.test.ts +445 -0
  71. package/templates/apps/web/lib/__tests__/auth-sms.test.ts +140 -0
  72. package/templates/apps/web/lib/__tests__/fixtures/tsconfig.flow.json +18 -0
  73. package/templates/apps/web/lib/__tests__/site-header.test.ts +13 -0
  74. package/templates/apps/web/lib/__tests__/telemetry-scrub.test.ts +19 -1
  75. package/templates/apps/web/lib/auth-email.ts +62 -6
  76. package/templates/apps/web/lib/auth-env.ts +13 -0
  77. package/templates/apps/web/lib/auth-sms.ts +180 -0
  78. package/templates/apps/web/lib/hub-session/__tests__/hub-session.test.ts +28 -0
  79. package/templates/apps/web/lib/hub-session/__tests__/spoke-sign-in.test.tsx +332 -0
  80. package/templates/apps/web/lib/hub-session/config.ts +7 -1
  81. package/templates/apps/web/lib/hub-session/entry.ts +238 -0
  82. package/templates/apps/web/lib/hub-session/index.ts +1 -4
  83. package/templates/apps/web/lib/hub-session/one-tap.tsx +148 -0
  84. package/templates/apps/web/lib/hub-session/session.ts +120 -2
  85. package/templates/apps/web/lib/hub-session/spoke-sign-in.tsx +277 -0
  86. package/templates/apps/web/lib/site-header.ts +14 -1
  87. package/templates/apps/web/lib/telemetry-scrub.ts +11 -0
  88. package/templates/apps/web/lib/topology.generated.ts +39 -0
  89. package/templates/apps/web/messages/en.json +112 -20
  90. package/templates/apps/web/middleware.ts +34 -2
  91. package/templates/apps/web/security-headers.config.ts +21 -0
  92. package/versions.json +47 -47
  93. package/templates/apps/web/app/[locale]/(authed)/sign-in-gate.tsx +0 -162
  94. package/templates/apps/web/components/signed-in-nav.tsx +0 -79
  95. package/templates/apps/web/lib/hub-session/__tests__/sign-in-gate.test.tsx +0 -180
  96. package/templates/apps/web/lib/hub-session/sign-in-gate.tsx +0 -162
@@ -11,8 +11,9 @@
11
11
  * the flow cookie's `next` — never on a value from this request's query.
12
12
  *
13
13
  * Every other outcome — no flow cookie, an expired one, a state mismatch, an
14
- * `error` from the hub, a failed exchange — lands on `/account` (its gate
15
- * offers to try again) after BURNING any code it received
14
+ * `error` from the hub, a failed exchange — lands on the site's home
15
+ * (#11095 D4; `/account` would redirect straight back into the sign-in, a
16
+ * loop) after BURNING any code it received
16
17
  * (`hubSignIn.revoke({ code })`, best-effort): a code this route cannot
17
18
  * complete must not stay live for someone else to complete (SEC-7894-4).
18
19
  * The log line names the reason only — never the query string, a code, a
@@ -27,21 +28,18 @@ import {
27
28
  type HubSessionConfig,
28
29
  hubSessionConfig,
29
30
  } from "../../../../lib/hub-session/config";
30
- import { seal, unseal } from "../../../../lib/hub-session/seal";
31
+ import { unseal } from "../../../../lib/hub-session/seal";
31
32
  import {
32
- HUB_SESSION_FALLBACK_PATH,
33
- type HubSessionPayload,
33
+ HUB_SESSION_HOME_PATH,
34
34
  cookieHeader,
35
35
  flowCookieName,
36
36
  hubNextPath,
37
37
  readCookie,
38
- sessionCookieName,
38
+ seeOther,
39
+ sessionCookieFor,
39
40
  } from "../../../../lib/hub-session/session";
40
41
  import { SIGN_IN_PROVIDER } from "../../../../lib/topology.generated";
41
42
 
42
- /** The longest session the spoke keeps — the hub's own credential lifetime (spec 7894 D5). */
43
- const MAX_SESSION_SECONDS = 86_400;
44
-
45
43
  /** What the sign-in route sealed into the flow cookie. */
46
44
  interface FlowPayload {
47
45
  v: 1;
@@ -63,16 +61,6 @@ function isFlow(value: unknown): value is FlowPayload {
63
61
  );
64
62
  }
65
63
 
66
- function see(location: string, setCookies: readonly string[]): Response {
67
- const headers = new Headers({
68
- Location: location,
69
- "Cache-Control": "no-store",
70
- "Referrer-Policy": "no-referrer",
71
- });
72
- for (const value of setCookies) headers.append("Set-Cookie", value);
73
- return new Response(null, { status: 303, headers });
74
- }
75
-
76
64
  function sameState(a: string, b: string): boolean {
77
65
  const x = Buffer.from(a, "utf8");
78
66
  const y = Buffer.from(b, "utf8");
@@ -100,7 +88,7 @@ async function burn(config: HubSessionConfig, code: string | null): Promise<void
100
88
  export async function GET(request: Request): Promise<Response> {
101
89
  if (SIGN_IN_PROVIDER !== "hub") return new Response(null, { status: 404 });
102
90
  const config = hubSessionConfig();
103
- if (config === null) return see(HUB_SESSION_FALLBACK_PATH, []);
91
+ if (config === null) return seeOther(HUB_SESSION_HOME_PATH);
104
92
 
105
93
  const params = new URL(request.url).searchParams;
106
94
  const code = params.get("code");
@@ -110,7 +98,7 @@ export async function GET(request: Request): Promise<Response> {
110
98
  const refuse = async (reason: string): Promise<Response> => {
111
99
  await burn(config, code);
112
100
  console.warn(`[hub-session] sign-in not completed reason=${reason}`);
113
- return see(HUB_SESSION_FALLBACK_PATH, [clearFlow]);
101
+ return seeOther(HUB_SESSION_HOME_PATH, [clearFlow]);
114
102
  };
115
103
 
116
104
  const sealed = readCookie(request.headers.get("cookie"), flowName);
@@ -138,31 +126,9 @@ export async function GET(request: Request): Promise<Response> {
138
126
  }
139
127
  if (!exchanged.ok) return refuse(`exchange_status_${exchanged.status}`);
140
128
 
141
- const { accessToken, expiresIn, user } = exchanged.body;
142
129
  // The cookie's lifetime is the credential's: a malformed answer from the
143
- // hub must never yield a session that does not expire.
144
- if (!Number.isInteger(expiresIn) || expiresIn < 1 || expiresIn > MAX_SESSION_SECONDS) {
145
- return refuse("token_response_invalid");
146
- }
147
- const payload: HubSessionPayload = {
148
- v: 1,
149
- accessToken,
150
- expiresAt: Date.now() + expiresIn * 1000,
151
- user: {
152
- name: user.name,
153
- email: user.email,
154
- emailVerified: user.emailVerified,
155
- createdAt: user.createdAt,
156
- },
157
- };
158
- const sessionName = sessionCookieName(config);
159
- return see(hubNextPath(flow.next), [
160
- clearFlow,
161
- cookieHeader(
162
- sessionName,
163
- seal(payload, config.sessionSecret, "session", sessionName),
164
- expiresIn,
165
- config,
166
- ),
167
- ]);
130
+ // hub must never yield a session that does not expire (#11096 D6).
131
+ const session = sessionCookieFor(config, exchanged.body);
132
+ if (session === null) return refuse("token_response_invalid");
133
+ return seeOther(hubNextPath(flow.next), [clearFlow, session]);
168
134
  }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * The spoke's own sign-in form, posted (#11096 D2) — `POST /api/hub-session/email`.
3
+ *
4
+ * The signed-out `/account` of a spoke that signs in through its hub is the
5
+ * spoke's own form (`lib/hub-session/spoke-sign-in.tsx`): one email field, the
6
+ * hub's sign-up agreements, Continue with Google. Its email lands here as a
7
+ * native form POST; this route starts a flow and asks the hub web, server to
8
+ * server, to mail the hub's magic link for it. Using the link signs the person
9
+ * in on the hub and comes back through the callback, with no hub page shown.
10
+ *
11
+ * 1. 404 unless `SIGN_IN_PROVIDER` is `"hub"`; not configured → 303
12
+ * `/account?error=unavailable`.
13
+ * 2. Same-origin only (`Sec-Fetch-Site`, `Origin`), else 403.
14
+ * 3. 10 posts per visitor per 10 minutes, then the bot check; a refusal is
15
+ * 303 `/account?error=unavailable`.
16
+ * 4. The form is `spokeEmailFormSchema`: one `email`, an optional `next`,
17
+ * zero or more ticked `agreements`. Any other field — a `password` among
18
+ * them (D5) — or a repeated `email` or `next` is 400.
19
+ * 5. A flow starts as `GET /api/hub-session/sign-in` starts one.
20
+ * 6. The hub web's `POST /api/auth/hub/email` gets the authorize keys, the
21
+ * email, the locale and — only when one was ticked — the agreements.
22
+ * 7. 202 → 303 `/account?sent=1` with the flow cookie; `agreements_required`
23
+ * → `/account?error=agreements`; anything else → `?error=unavailable`.
24
+ * Only the 202 sets a cookie.
25
+ *
26
+ * The answer never says whether the address has an account. Nothing here logs
27
+ * the email, the agreements or the flow.
28
+ */
29
+ import { spokeEmailFormSchema } from "@working-theory/validation";
30
+
31
+ import { runBotCheck } from "../../../../lib/bot-check";
32
+ import { hubSessionConfig } from "../../../../lib/hub-session/config";
33
+ import {
34
+ accountPath,
35
+ hubError,
36
+ localeOfPath,
37
+ postToHub,
38
+ readFormFields,
39
+ } from "../../../../lib/hub-session/entry";
40
+ import {
41
+ hubNextPath,
42
+ isSameOrigin,
43
+ seeOther,
44
+ startHubFlow,
45
+ } from "../../../../lib/hub-session/session";
46
+ import { SIGN_IN_PROVIDER } from "../../../../lib/topology.generated";
47
+ import { takeVisitorLimit } from "../../../../src/lib/rate-limit";
48
+
49
+ /** The hub web's email route (D2). */
50
+ const HUB_EMAIL_PATH = "/api/auth/hub/email";
51
+
52
+ /** The per-visitor budget for this route. */
53
+ const VISITOR_LIMIT = 10;
54
+ const VISITOR_WINDOW_MS = 10 * 60_000;
55
+
56
+ /** The fields the form may carry, and which of them may repeat. */
57
+ const SINGLE_FIELDS = new Set(["email", "next"]);
58
+ const AGREEMENTS_FIELD = "agreements";
59
+
60
+ /** The form as `spokeEmailFormSchema` reads it, or `null` for a refused shape. */
61
+ function formBody(fields: Map<string, string[]>): Record<string, unknown> | null {
62
+ const body: Record<string, unknown> = {};
63
+ for (const [name, values] of fields) {
64
+ if (name === AGREEMENTS_FIELD) {
65
+ body[name] = values;
66
+ } else if (SINGLE_FIELDS.has(name)) {
67
+ if (values.length !== 1) return null;
68
+ body[name] = values[0];
69
+ } else {
70
+ // An unknown field (a password among them) is refused, never dropped.
71
+ return null;
72
+ }
73
+ }
74
+ return body;
75
+ }
76
+
77
+ function badRequest(): Response {
78
+ return new Response(null, { status: 400, headers: { "Cache-Control": "no-store" } });
79
+ }
80
+
81
+ // platform-decisions-waiver: api-versioning — sign-in form endpoint, not a versioned API contract (spec 11096 §6)
82
+ export async function POST(request: Request): Promise<Response> {
83
+ if (SIGN_IN_PROVIDER !== "hub") return new Response(null, { status: 404 });
84
+ const config = hubSessionConfig();
85
+ if (config === null) return seeOther(accountPath("en", "error=unavailable"));
86
+ if (!isSameOrigin(request, config.siteOrigin)) {
87
+ return new Response(null, { status: 403 });
88
+ }
89
+
90
+ if (!takeVisitorLimit("hub-session-email", request.headers, VISITOR_LIMIT, VISITOR_WINDOW_MS).allowed) {
91
+ return seeOther(accountPath("en", "error=unavailable"));
92
+ }
93
+ const bot = await runBotCheck({ source: "hub-session", target: "email", scope: "write" });
94
+ if (bot !== "pass") return seeOther(accountPath("en", "error=unavailable"));
95
+
96
+ const fields = await readFormFields(request);
97
+ const raw = fields === null ? null : formBody(fields);
98
+ const parsed = raw === null ? null : spokeEmailFormSchema.safeParse(raw);
99
+ if (parsed === null || !parsed.success) return badRequest();
100
+ const next = hubNextPath(parsed.data.next);
101
+ const locale = localeOfPath(next);
102
+
103
+ const flow = startHubFlow(config, next);
104
+ const answer = await postToHub(config, HUB_EMAIL_PATH, {
105
+ client_id: config.clientId,
106
+ redirect_uri: config.redirectUri,
107
+ state: flow.state,
108
+ code_challenge: flow.challenge,
109
+ code_challenge_method: "S256",
110
+ email: parsed.data.email,
111
+ locale,
112
+ ...(parsed.data.agreements ? { agreements: parsed.data.agreements } : {}),
113
+ });
114
+
115
+ if (answer?.status === 202) {
116
+ return seeOther(accountPath(locale, "sent=1"), [flow.cookie]);
117
+ }
118
+ if (answer?.status === 400 && hubError(answer) === "agreements_required") {
119
+ return seeOther(accountPath(locale, "error=agreements"));
120
+ }
121
+ console.warn(
122
+ `[hub-session] email entry not sent status=${answer === null ? "unreachable" : answer.status}`,
123
+ );
124
+ return seeOther(accountPath(locale, "error=unavailable"));
125
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * One Tap's nonce (#11096 D10) — `POST /api/hub-session/one-tap/nonce`.
3
+ *
4
+ * Before the spoke's sign-in page asks Google for a One Tap credential, it
5
+ * asks here for a nonce: 32 random bytes, answered to the page and sealed
6
+ * into a 300 s `HttpOnly` cookie. Google signs the nonce into the ID token,
7
+ * and `POST /api/hub-session/one-tap` hands the hub the cookie's copy, so a
8
+ * token minted for another page or another visitor does not verify.
9
+ *
10
+ * 404 unless this is a hub-sign-in spoke with `AILK_HUB_ONE_TAP=on`; 403
11
+ * unless same-origin. Nothing here logs the nonce.
12
+ */
13
+ import { randomBytes } from "node:crypto";
14
+
15
+ import { hubSessionConfig } from "../../../../../lib/hub-session/config";
16
+ import { seal } from "../../../../../lib/hub-session/seal";
17
+ import {
18
+ ONE_TAP_NONCE_TTL_SECONDS,
19
+ cookieHeader,
20
+ isSameOrigin,
21
+ oneTapCookieName,
22
+ } from "../../../../../lib/hub-session/session";
23
+ import { SIGN_IN_PROVIDER } from "../../../../../lib/topology.generated";
24
+
25
+ // platform-decisions-waiver: api-versioning — sign-in step, not a versioned API contract (spec 11096 §6)
26
+ export function POST(request: Request): Response {
27
+ const config = SIGN_IN_PROVIDER === "hub" ? hubSessionConfig() : null;
28
+ if (config === null || !config.oneTap) return new Response(null, { status: 404 });
29
+ if (!isSameOrigin(request, config.siteOrigin)) {
30
+ return new Response(null, { status: 403 });
31
+ }
32
+ const nonce = randomBytes(32).toString("base64url");
33
+ const name = oneTapCookieName(config);
34
+ const sealed = seal(
35
+ { v: 1, nonce, expiresAt: Date.now() + ONE_TAP_NONCE_TTL_SECONDS * 1000 },
36
+ config.sessionSecret,
37
+ "flow",
38
+ name,
39
+ );
40
+ return Response.json(
41
+ { nonce },
42
+ {
43
+ headers: {
44
+ "Cache-Control": "no-store",
45
+ "Set-Cookie": cookieHeader(name, sealed, ONE_TAP_NONCE_TTL_SECONDS, config),
46
+ },
47
+ },
48
+ );
49
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Google One Tap for a returning person (#11096 D10) — `POST /api/hub-session/one-tap`.
3
+ *
4
+ * The spoke's `OneTap` island posts Google's ID token here as
5
+ * `{ credential }`. This route reads and clears the nonce cookie the nonce
6
+ * route set, and forwards the token, that nonce and this site's own origin to
7
+ * the hub API's `POST /v1/hub-sign-in/google`, authenticated as this spoke's
8
+ * client. The hub verifies the token against Google's keys and mints the
9
+ * credential the code exchange mints; this route seals it into the session
10
+ * cookie (`sessionCookieFor`) and answers `{ ok: true }`. The page then
11
+ * navigates to `next` on this site. No hub page and no Google page is shown.
12
+ *
13
+ * - 404 unless this is a hub-sign-in spoke with `AILK_HUB_ONE_TAP=on`;
14
+ * - 403 unless same-origin;
15
+ * - 400 for a body other than `spokeOneTapBodySchema` (a `password` field
16
+ * among them, D5) or with no live nonce cookie — no hub call;
17
+ * - 401 `{ ok: false }` for every hub refusal, so the page leaves the form
18
+ * as it is.
19
+ *
20
+ * Nothing here logs the token, the nonce or the credential.
21
+ */
22
+ import { hubSignIn } from "@working-theory/api-client";
23
+ import { spokeOneTapBodySchema } from "@working-theory/validation";
24
+
25
+ import { hubSessionConfig } from "../../../../lib/hub-session/config";
26
+ import { readBodyText } from "../../../../lib/hub-session/entry";
27
+ import { unseal } from "../../../../lib/hub-session/seal";
28
+ import {
29
+ cookieHeader,
30
+ isSameOrigin,
31
+ oneTapCookieName,
32
+ readCookie,
33
+ sessionCookieFor,
34
+ } from "../../../../lib/hub-session/session";
35
+ import { SIGN_IN_PROVIDER } from "../../../../lib/topology.generated";
36
+ import { takeVisitorLimit } from "../../../../src/lib/rate-limit";
37
+
38
+ const VISITOR_LIMIT = 10;
39
+ const VISITOR_WINDOW_MS = 10 * 60_000;
40
+
41
+ function answer(status: number, ok: boolean, setCookies: readonly string[]): Response {
42
+ const headers = new Headers({ "Cache-Control": "no-store" });
43
+ for (const value of setCookies) headers.append("Set-Cookie", value);
44
+ return Response.json({ ok }, { status, headers });
45
+ }
46
+
47
+ /** `text` as JSON, or `null` when there is none or it does not parse. */
48
+ function parseJson(text: string | null): unknown {
49
+ if (text === null) return null;
50
+ try {
51
+ return JSON.parse(text) as unknown;
52
+ } catch {
53
+ return null;
54
+ }
55
+ }
56
+
57
+ /** The nonce the cookie seals, or `null` — absent, unreadable or expired. */
58
+ function sealedNonce(value: unknown): string | null {
59
+ if (typeof value !== "object" || value === null) return null;
60
+ const v = value as Record<string, unknown>;
61
+ if (v["v"] !== 1 || typeof v["nonce"] !== "string") return null;
62
+ if (typeof v["expiresAt"] !== "number" || v["expiresAt"] <= Date.now()) return null;
63
+ return v["nonce"];
64
+ }
65
+
66
+ // platform-decisions-waiver: api-versioning — sign-in step, not a versioned API contract (spec 11096 §6)
67
+ export async function POST(request: Request): Promise<Response> {
68
+ const config = SIGN_IN_PROVIDER === "hub" ? hubSessionConfig() : null;
69
+ if (config === null || !config.oneTap) return new Response(null, { status: 404 });
70
+ if (!isSameOrigin(request, config.siteOrigin)) {
71
+ return new Response(null, { status: 403 });
72
+ }
73
+ if (!takeVisitorLimit("hub-session-one-tap", request.headers, VISITOR_LIMIT, VISITOR_WINDOW_MS).allowed) {
74
+ return answer(429, false, []);
75
+ }
76
+
77
+ // The nonce is single use: cleared on every answer from here on.
78
+ const name = oneTapCookieName(config);
79
+ const clearNonce = cookieHeader(name, "", 0, config);
80
+ const sealed = readCookie(request.headers.get("cookie"), name);
81
+ const nonce =
82
+ sealed === undefined ? null : sealedNonce(unseal(sealed, config.sessionSecret, "flow", name));
83
+
84
+ const body = spokeOneTapBodySchema.safeParse(parseJson(await readBodyText(request)));
85
+ if (!body.success || nonce === null) return answer(400, false, [clearNonce]);
86
+
87
+ let res: Awaited<ReturnType<typeof hubSignIn.google>>;
88
+ try {
89
+ res = await hubSignIn.google(
90
+ { clientId: config.clientId, clientSecret: config.clientSecret },
91
+ { idToken: body.data.credential, nonce, origin: config.siteOrigin },
92
+ );
93
+ } catch (err) {
94
+ console.error(
95
+ `[hub-session] one tap failed errName=${err instanceof Error ? err.name : "unknown"}`,
96
+ );
97
+ return answer(401, false, [clearNonce]);
98
+ }
99
+ if (!res.ok) {
100
+ console.warn(`[hub-session] one tap refused status=${res.status}`);
101
+ return answer(401, false, [clearNonce]);
102
+ }
103
+ const session = sessionCookieFor(config, res.body);
104
+ if (session === null) return answer(401, false, [clearNonce]);
105
+ return answer(200, true, [clearNonce, session]);
106
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * "Open my account" from a purchase link (#11096 D9) — `POST /api/hub-session/open`.
3
+ *
4
+ * After a paid Checkout Session the hub mails the buyer one link to this
5
+ * spoke's `/account?claim=<claim>`. That page's GET changes nothing (a mail
6
+ * scanner that follows the link creates no account, SEC-11096-3): it shows
7
+ * the agreements and one "Open my account" button, whose form posts the
8
+ * claim here. This route starts a flow and spends the claim at the hub web's
9
+ * `POST /api/auth/hub/purchase`, server to server, as this spoke's client.
10
+ *
11
+ * - 200 `{ verifyUrl }` on the hub's own origin → 303 there, with the flow
12
+ * cookie: the hub's verify creates the account, and the redirects land on
13
+ * `/account` signed in;
14
+ * - 409 `account_exists` → 303 `/account?error=exists` (the form asks for
15
+ * the email instead: a claim never signs an existing account in);
16
+ * - anything else → 303 `/account?error=claim`.
17
+ *
18
+ * The checks in front are the email route's (D2 steps 1–3); the body is
19
+ * `spokeOpenFormSchema`, the one `claim` field. Nothing here logs the claim.
20
+ */
21
+ import { hubPurchaseResponseSchema, spokeOpenFormSchema } from "@working-theory/validation";
22
+
23
+ import { runBotCheck } from "../../../../lib/bot-check";
24
+ import { hubSessionConfig } from "../../../../lib/hub-session/config";
25
+ import {
26
+ accountPath,
27
+ hubError,
28
+ postToHub,
29
+ readFormFields,
30
+ } from "../../../../lib/hub-session/entry";
31
+ import {
32
+ HUB_SESSION_FALLBACK_PATH,
33
+ isSameOrigin,
34
+ seeOther,
35
+ startHubFlow,
36
+ } from "../../../../lib/hub-session/session";
37
+ import { SIGN_IN_PROVIDER } from "../../../../lib/topology.generated";
38
+ import { takeVisitorLimit } from "../../../../src/lib/rate-limit";
39
+
40
+ /** The hub web's claim-spending route (D9). */
41
+ const HUB_PURCHASE_PATH = "/api/auth/hub/purchase";
42
+
43
+ const VISITOR_LIMIT = 10;
44
+ const VISITOR_WINDOW_MS = 10 * 60_000;
45
+
46
+ /** The one `claim` field, or `null` for any other shape. */
47
+ function formBody(fields: Map<string, string[]>): Record<string, unknown> | null {
48
+ const body: Record<string, unknown> = {};
49
+ for (const [name, values] of fields) {
50
+ if (values.length !== 1) return null;
51
+ body[name] = values[0];
52
+ }
53
+ return body;
54
+ }
55
+
56
+ /** `raw` when it is a URL on `hubOrigin`, else `null`. */
57
+ function hubUrl(raw: string, hubOrigin: string): string | null {
58
+ try {
59
+ const url = new URL(raw);
60
+ return url.origin === hubOrigin ? url.toString() : null;
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+
66
+ // platform-decisions-waiver: api-versioning — sign-in form endpoint, not a versioned API contract (spec 11096 §6)
67
+ export async function POST(request: Request): Promise<Response> {
68
+ if (SIGN_IN_PROVIDER !== "hub") return new Response(null, { status: 404 });
69
+ const config = hubSessionConfig();
70
+ if (config === null) return seeOther(accountPath("en", "error=unavailable"));
71
+ if (!isSameOrigin(request, config.siteOrigin)) {
72
+ return new Response(null, { status: 403 });
73
+ }
74
+ const refused = seeOther(accountPath("en", "error=claim"));
75
+ if (!takeVisitorLimit("hub-session-open", request.headers, VISITOR_LIMIT, VISITOR_WINDOW_MS).allowed) {
76
+ return refused;
77
+ }
78
+ if ((await runBotCheck({ source: "hub-session", target: "open", scope: "write" })) !== "pass") {
79
+ return refused;
80
+ }
81
+
82
+ const fields = await readFormFields(request);
83
+ const raw = fields === null ? null : formBody(fields);
84
+ const parsed = raw === null ? null : spokeOpenFormSchema.safeParse(raw);
85
+ if (parsed === null || !parsed.success) {
86
+ return new Response(null, { status: 400, headers: { "Cache-Control": "no-store" } });
87
+ }
88
+
89
+ const flow = startHubFlow(config, HUB_SESSION_FALLBACK_PATH);
90
+ const answer = await postToHub(config, HUB_PURCHASE_PATH, {
91
+ claim: parsed.data.claim,
92
+ client_id: config.clientId,
93
+ redirect_uri: config.redirectUri,
94
+ state: flow.state,
95
+ code_challenge: flow.challenge,
96
+ code_challenge_method: "S256",
97
+ });
98
+
99
+ if (answer?.status === 200) {
100
+ const body = hubPurchaseResponseSchema.safeParse(answer.body);
101
+ const verifyUrl = body.success ? hubUrl(body.data.verifyUrl, config.hubOrigin) : null;
102
+ if (verifyUrl !== null) return seeOther(verifyUrl, [flow.cookie]);
103
+ }
104
+ if (answer?.status === 409 && hubError(answer) === "account_exists") {
105
+ return seeOther(accountPath("en", "error=exists"));
106
+ }
107
+ console.warn(
108
+ `[hub-session] purchase claim not opened status=${answer === null ? "unreachable" : answer.status} reason=${hubError(answer) ?? "none"}`,
109
+ );
110
+ return refused;
111
+ }
@@ -8,7 +8,8 @@
8
8
  * `/api/hub-session/callback` — never derived from the request's `Host`.
9
9
  *
10
10
  * - not a hub-mode spoke (`SIGN_IN_PROVIDER` is not `"hub"`): 404;
11
- * - hub mode but not configured: 303 to `/account`, whose gate says so.
11
+ * - hub mode but not configured: 303 to the site's home (#11095 D4) —
12
+ * `/account` would redirect straight back here.
12
13
  *
13
14
  * Hinted email (#8757 D9): a single `?email=` that `accountEmailHintSchema`
14
15
  * accepts rides to the hub as `login_hint`, so its sign-in form opens with
@@ -21,38 +22,27 @@
21
22
  * same. Any other value, an empty or a repeated one adds nothing, and the hint
22
23
  * never enters the flow cookie.
23
24
  *
25
+ * Google (#11096 D4): exactly one `?provider=google` (the spoke form's
26
+ * "Continue with Google") rides to the hub as `provider_hint=google`, which
27
+ * sends a visitor with no hub session straight to Google, with no sign-in
28
+ * card. Any other value, an empty or a repeated one adds nothing, and the
29
+ * hint never enters the flow cookie.
30
+ *
24
31
  * Nothing here logs the state, the verifier or the challenge.
25
32
  */
26
- import { createHash, randomBytes } from "node:crypto";
27
-
28
33
  import { accountEmailHintSchema } from "@working-theory/validation";
29
34
 
30
35
  import { hubSessionConfig } from "../../../../lib/hub-session/config";
31
- import { seal } from "../../../../lib/hub-session/seal";
32
36
  import {
33
- HUB_SESSION_FALLBACK_PATH,
34
- cookieHeader,
35
- flowCookieName,
36
- hubNextPath,
37
+ HUB_SESSION_HOME_PATH,
38
+ seeOther,
39
+ startHubFlow,
37
40
  } from "../../../../lib/hub-session/session";
38
41
  import { SIGN_IN_PROVIDER } from "../../../../lib/topology.generated";
39
42
 
40
- /** How long a sign-in may take on the hub before the flow cookie expires. */
41
- const FLOW_TTL_SECONDS = 600;
42
-
43
43
  /** The hub's browser step (spec 7894 D4). */
44
44
  const AUTHORIZE_PATH = "/api/auth/hub/authorize";
45
45
 
46
- function see(location: string, setCookie?: string): Response {
47
- const headers = new Headers({
48
- Location: location,
49
- "Cache-Control": "no-store",
50
- "Referrer-Policy": "no-referrer",
51
- });
52
- if (setCookie !== undefined) headers.append("Set-Cookie", setCookie);
53
- return new Response(null, { status: 303, headers });
54
- }
55
-
56
46
  /** #8757 D9 — the one `email` the hint schema accepts; repeated or refused → none. */
57
47
  function emailHint(params: URLSearchParams): string | undefined {
58
48
  const values = params.getAll("email");
@@ -67,42 +57,35 @@ function signUpHint(params: URLSearchParams): "create" | undefined {
67
57
  return values.length === 1 && values[0] === "create" ? "create" : undefined;
68
58
  }
69
59
 
60
+ /** #11096 D4 — `"google"` when the one `provider` is exactly that, else none. */
61
+ function providerHint(params: URLSearchParams): "google" | undefined {
62
+ const values = params.getAll("provider");
63
+ return values.length === 1 && values[0] === "google" ? "google" : undefined;
64
+ }
65
+
70
66
  // platform-decisions-waiver: api-versioning — sign-in redirect endpoint, not a versioned API contract (spec 7894 §7)
71
67
  export function GET(request: Request): Response {
72
68
  if (SIGN_IN_PROVIDER !== "hub") return new Response(null, { status: 404 });
73
69
  const config = hubSessionConfig();
74
- if (config === null) return see(HUB_SESSION_FALLBACK_PATH);
70
+ if (config === null) return seeOther(HUB_SESSION_HOME_PATH);
75
71
 
76
72
  const params = new URL(request.url).searchParams;
77
- const next = hubNextPath(params.get("next"));
78
- const state = randomBytes(32).toString("base64url");
79
- const verifier = randomBytes(32).toString("base64url");
80
- const challenge = createHash("sha256").update(verifier).digest("base64url");
81
-
82
- const name = flowCookieName(config);
83
- const flow = seal(
84
- { v: 1, state, verifier, next, expiresAt: Date.now() + FLOW_TTL_SECONDS * 1000 },
85
- config.sessionSecret,
86
- "flow",
87
- name,
88
- );
73
+ const flow = startHubFlow(config, params.get("next"));
89
74
 
90
75
  const authorize = new URL(AUTHORIZE_PATH, config.hubOrigin);
91
76
  const query = new URLSearchParams({
92
77
  response_type: "code",
93
78
  client_id: config.clientId,
94
79
  redirect_uri: config.redirectUri,
95
- state,
96
- code_challenge: challenge,
80
+ state: flow.state,
81
+ code_challenge: flow.challenge,
97
82
  code_challenge_method: "S256",
98
83
  });
99
84
  if (signUpHint(params) !== undefined) query.set("prompt", "create");
100
85
  const loginHint = emailHint(params);
101
86
  if (loginHint !== undefined) query.set("login_hint", loginHint);
87
+ if (providerHint(params) !== undefined) query.set("provider_hint", "google");
102
88
  authorize.search = query.toString();
103
89
 
104
- return see(
105
- authorize.toString(),
106
- cookieHeader(name, flow, FLOW_TTL_SECONDS, config),
107
- );
90
+ return seeOther(authorize.toString(), [flow.cookie]);
108
91
  }
@@ -16,21 +16,12 @@ import { hubSignIn } from "@working-theory/api-client";
16
16
  import { hubSessionConfig } from "../../../../lib/hub-session/config";
17
17
  import {
18
18
  cookieHeader,
19
+ isSameOrigin,
19
20
  readHubSessionPayload,
20
21
  sessionCookieName,
21
22
  } from "../../../../lib/hub-session/session";
22
23
  import { SIGN_IN_PROVIDER } from "../../../../lib/topology.generated";
23
24
 
24
- /** Whether `request` comes from a page on `siteOrigin`. */
25
- function isSameOrigin(request: Request, siteOrigin: string | null): boolean {
26
- const fetchSite = request.headers.get("sec-fetch-site");
27
- const origin = request.headers.get("origin");
28
- if (fetchSite === null && origin === null) return false;
29
- if (fetchSite !== null && fetchSite !== "same-origin") return false;
30
- if (origin !== null && origin !== siteOrigin) return false;
31
- return true;
32
- }
33
-
34
25
  // platform-decisions-waiver: api-versioning — sign-in redirect endpoint, not a versioned API contract (spec 7894 §7)
35
26
  export async function POST(request: Request): Promise<Response> {
36
27
  if (SIGN_IN_PROVIDER !== "hub") return new Response(null, { status: 404 });