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,163 @@
1
+ /**
2
+ * What the hub web's spoke-facing entry routes share (#11096 D2, D9): the
3
+ * JSON answer, a bounded JSON body read, the spoke's forwarded client
4
+ * authentication, the refused-caller limit, and the mapping of a Better Auth
5
+ * refusal onto the wire.
6
+ *
7
+ * Nothing here logs. The forwarded `Authorization` and spoke key go only to
8
+ * the hub API's entry check — never to Better Auth, a log line or an error
9
+ * report (SEC-11096-12).
10
+ */
11
+ import type { HubForwardedClientAuth } from "@working-theory/api-client";
12
+
13
+ import {
14
+ clientIpFromHeaders,
15
+ UNKNOWN_VISITOR_FACTOR,
16
+ } from "../../../../src/lib/rate-limit";
17
+
18
+ /** A purchase claim's life: three days to open the account (#11096 D9). */
19
+ export const PURCHASE_CLAIM_TTL_SECONDS = 72 * 3600;
20
+
21
+ /** The name a purchase claim is sealed under — never `hub-continue`. */
22
+ export const PURCHASE_CLAIM_NAME = "hub-purchase";
23
+
24
+ /** The largest body an entry route reads. */
25
+ export const ENTRY_BODY_MAX_BYTES = 4096;
26
+
27
+ export function json(
28
+ status: number,
29
+ body: Record<string, unknown>,
30
+ headers: Record<string, string> = {},
31
+ ): Response {
32
+ return new Response(JSON.stringify(body), {
33
+ status,
34
+ headers: {
35
+ "Content-Type": "application/json",
36
+ "Cache-Control": "no-store",
37
+ ...headers,
38
+ },
39
+ });
40
+ }
41
+
42
+ export const refuse = (status: number, error: string): Response =>
43
+ json(status, { error });
44
+
45
+ /** The raw body as text, or `null` past 4 KB or on a read failure. */
46
+ export async function readRawBody(request: Request): Promise<string | null> {
47
+ const declared = Number(request.headers.get("content-length") ?? "0");
48
+ if (Number.isFinite(declared) && declared > ENTRY_BODY_MAX_BYTES) return null;
49
+ try {
50
+ const text = await request.text();
51
+ return Buffer.byteLength(text, "utf8") > ENTRY_BODY_MAX_BYTES ? null : text;
52
+ } catch {
53
+ return null;
54
+ }
55
+ }
56
+
57
+ /** The parsed JSON value of `raw`, or `undefined` when it does not parse. */
58
+ export function parseJson(raw: string): unknown {
59
+ try {
60
+ return JSON.parse(raw) as unknown;
61
+ } catch {
62
+ return undefined;
63
+ }
64
+ }
65
+
66
+ /** `Basic <base64>`: the only `Authorization` shape a spoke sends. */
67
+ const BASIC_AUTHORIZATION = /^Basic [A-Za-z0-9+/]{4,684}={0,2}$/;
68
+
69
+ /**
70
+ * The spoke's `Authorization` and `x-ailk-spoke-key`, as received, or `null`
71
+ * when either is missing or the `Authorization` is not `Basic <base64>`: the
72
+ * hub API decides whether they are good.
73
+ */
74
+ export function forwardedClientAuth(
75
+ request: Request,
76
+ ): HubForwardedClientAuth | null {
77
+ const authorization = request.headers.get("authorization");
78
+ const spokeKey = request.headers.get("x-ailk-spoke-key");
79
+ if (!authorization || !spokeKey) return null;
80
+ if (!BASIC_AUTHORIZATION.test(authorization) || spokeKey.length > 256) {
81
+ return null;
82
+ }
83
+ return { authorization, spokeKey };
84
+ }
85
+
86
+ // ── The refused-caller limit (SEC review of #11096) ─────────────────────────
87
+ //
88
+ // These routes are public, and every call that reaches the hub API arrives
89
+ // from this app's own egress address, which the API's per-IP limiter counts
90
+ // as one caller. So a caller sending credentials the API refuses could spend
91
+ // that budget for every spoke. The caller here is a spoke's SERVER, not a
92
+ // person, so a plain request cap would also cap a busy spoke's real sign-ins;
93
+ // what is limited instead is REFUSALS: a caller whose credentials were
94
+ // missing, malformed or refused by the API (401/403) ten times in ten minutes
95
+ // is answered 429 before any API call until the window ends. A spoke whose
96
+ // credentials are good never accrues one. The address is the per-visitor
97
+ // limiter's (`clientIpFromHeaders`); an unreadable one shares one bucket
98
+ // `UNKNOWN_VISITOR_FACTOR` times as wide. Per instance and best-effort, like
99
+ // that limiter.
100
+
101
+ const REFUSALS_PER_WINDOW = 10;
102
+ const REFUSAL_WINDOW_MS = 10 * 60_000;
103
+ const MAX_TRACKED_CALLERS = 5000;
104
+
105
+ const refusals = new Map<string, { count: number; resetAt: number }>();
106
+
107
+ /** Test seam: forget every caller's refusals. */
108
+ export function __resetRefusedCallers(): void {
109
+ refusals.clear();
110
+ }
111
+
112
+ function callerKey(request: Request): { key: string; limit: number } {
113
+ const address = clientIpFromHeaders(request.headers);
114
+ return address === "unknown"
115
+ ? { key: "unknown", limit: UNKNOWN_VISITOR_FACTOR * REFUSALS_PER_WINDOW }
116
+ : { key: address, limit: REFUSALS_PER_WINDOW };
117
+ }
118
+
119
+ /** A 429 when this caller has used up its refusals, else `null`. Counts nothing. */
120
+ export function refusedCallerLimit(request: Request): Response | null {
121
+ const { key, limit } = callerKey(request);
122
+ const now = Date.now();
123
+ const entry = refusals.get(key);
124
+ if (!entry || entry.resetAt <= now || entry.count < limit) return null;
125
+ return json(
126
+ 429,
127
+ { error: "rate_limited" },
128
+ { "Retry-After": String(Math.max(1, Math.ceil((entry.resetAt - now) / 1000))) },
129
+ );
130
+ }
131
+
132
+ /** Count one refusal against this caller. */
133
+ export function noteRefusedCaller(request: Request): void {
134
+ const { key } = callerKey(request);
135
+ const now = Date.now();
136
+ const entry = refusals.get(key);
137
+ if (entry && entry.resetAt > now) {
138
+ entry.count += 1;
139
+ return;
140
+ }
141
+ if (refusals.size >= MAX_TRACKED_CALLERS) {
142
+ for (const [k, v] of refusals) if (v.resetAt <= now) refusals.delete(k);
143
+ const oldest = refusals.keys().next().value;
144
+ if (refusals.size >= MAX_TRACKED_CALLERS && oldest !== undefined) {
145
+ refusals.delete(oldest);
146
+ }
147
+ }
148
+ refusals.set(key, { count: 1, resetAt: now + REFUSAL_WINDOW_MS });
149
+ }
150
+
151
+ /** The `error.code` of a refused api-client call, or `fallback`. */
152
+ export function apiErrorCode(body: unknown, fallback: string): string {
153
+ const code = (body as { error?: { code?: unknown } } | null)?.error?.code;
154
+ return typeof code === "string" && /^[a-z_]{1,64}$/.test(code)
155
+ ? code
156
+ : fallback;
157
+ }
158
+
159
+ /** The `code` a Better Auth `APIError` carries, or `null`. */
160
+ export function betterAuthCode(err: unknown): string | null {
161
+ const code = (err as { body?: { code?: unknown } } | null)?.body?.code;
162
+ return typeof code === "string" ? code : null;
163
+ }
@@ -0,0 +1,230 @@
1
+ /**
2
+ * `POST /api/auth/hub/purchase` — a spoke spends a buyer's purchase claim
3
+ * (#11096 D9, spec docs/specs/11096-the-spoke-hosts-the-sign-spec.md).
4
+ *
5
+ * The spoke's server posts the claim from its "Open my account" button with
6
+ * the six authorize keys of the flow it just started. In order:
7
+ *
8
+ * 1. The body, `.strict()`, ≤ 4 KB (`password` among the refused keys).
9
+ * 2. The claim opens under `hub-purchase` and has not expired, and was
10
+ * minted for this `client_id` — else 410 `claim_invalid`.
11
+ * 3. The hub API's entry check authenticates the spoke with its forwarded
12
+ * headers for the claim's email, charging the same buckets as D2.
13
+ * 4. The evidence is exactly `account_terms` at the claim's version, else
14
+ * 410 `terms_changed`: a bump since the purchase asks through the form
15
+ * instead (SEC-11096-2).
16
+ * 5. An existing account for the email is 409 `account_exists`: the claim
17
+ * never signs an existing account in (SEC-11096-4).
18
+ * 6. Single use: a `purchase-claim:<SHA-256 of the session id>` row (72 h)
19
+ * is written after reading that none is there; one there is 410
20
+ * `claim_used`.
21
+ * 7. Better Auth's `signInMagicLink`, as a sign-up request for
22
+ * `account_terms` with the continue path as its callback, inside
23
+ * `purchaseCapture`: the agreements are bound to the token as for any
24
+ * sign-up request, and the token comes back here instead of a mail.
25
+ * 8. 200 `{ verifyUrl }` — the hub's own verify for that token — `no-store`.
26
+ *
27
+ * The browser then runs verify (the user is created with a verified email
28
+ * and one `sign_up` grant for `account_terms`), continue, authorize and the
29
+ * spoke's callback: redirects only. The button's click, not the email link,
30
+ * is the mailbox owner's acceptance (SEC-11096-1). Nothing is logged.
31
+ */
32
+ import { createHash } from "node:crypto";
33
+
34
+ import { hubSignIn } from "@working-theory/api-client";
35
+ import { hubPurchaseBodySchema } from "@working-theory/validation";
36
+
37
+ import { auth, resolveSecret } from "../../../../../auth";
38
+ import {
39
+ purchaseCapture,
40
+ type PurchaseCaptureStore,
41
+ } from "../../../../../lib/auth-email";
42
+ import {
43
+ CONTINUE_PATH,
44
+ openContinuation,
45
+ pinnedOrigin,
46
+ sealQuery,
47
+ } from "../continuation";
48
+ import {
49
+ apiErrorCode,
50
+ betterAuthCode,
51
+ forwardedClientAuth,
52
+ json,
53
+ noteRefusedCaller,
54
+ parseJson,
55
+ PURCHASE_CLAIM_NAME,
56
+ PURCHASE_CLAIM_TTL_SECONDS,
57
+ readRawBody,
58
+ refusedCallerLimit,
59
+ refuse,
60
+ } from "../entry-shared";
61
+ import {
62
+ coversPurchaseTerms,
63
+ readHubSignUpEvidence,
64
+ } from "../sign-up-evidence";
65
+
66
+ interface Claim {
67
+ email: string;
68
+ clientId: string;
69
+ sessionId: string;
70
+ policyVersion: number;
71
+ locale: string;
72
+ }
73
+
74
+ /** The claim's five facts, or `null` when it does not open or is malformed. */
75
+ function openClaim(claim: string): Claim | null {
76
+ const query = openContinuation(
77
+ claim,
78
+ resolveSecret(),
79
+ Date.now(),
80
+ PURCHASE_CLAIM_NAME,
81
+ );
82
+ if (query === null) return null;
83
+ const params = new URLSearchParams(query);
84
+ const [email, clientId, sessionId, version, locale] = [
85
+ "e",
86
+ "c",
87
+ "s",
88
+ "v",
89
+ "l",
90
+ ].map((key) => params.get(key));
91
+ const policyVersion = Number(version);
92
+ if (
93
+ !email ||
94
+ !clientId ||
95
+ !sessionId ||
96
+ !locale ||
97
+ !Number.isInteger(policyVersion)
98
+ ) {
99
+ return null;
100
+ }
101
+ return { email, clientId, sessionId, policyVersion, locale };
102
+ }
103
+
104
+ /**
105
+ * Un-spend the claim and answer `response`. The single-use row is written
106
+ * before the token is minted, so two racing spends cannot both mint; a spend
107
+ * that then fails removes it, so a failure never burns the buyer's claim.
108
+ */
109
+ async function release(identifier: string, response: Response): Promise<Response> {
110
+ try {
111
+ const { internalAdapter } = await auth.$context;
112
+ await internalAdapter.deleteVerificationByIdentifier(identifier);
113
+ } catch {
114
+ // The claim stays spent; the buyer still signs up through the form.
115
+ }
116
+ return response;
117
+ }
118
+
119
+ // platform-decisions-waiver: api-versioning — a hub sign-in step, not a versioned API contract (spec 11096 § 6)
120
+ export async function POST(request: Request): Promise<Response> {
121
+ const origin = pinnedOrigin();
122
+ if (origin === null) return refuse(503, "temporarily_unavailable");
123
+
124
+ const raw = await readRawBody(request);
125
+ if (raw === null) return refuse(400, "invalid_request");
126
+ const parsed = hubPurchaseBodySchema.safeParse(parseJson(raw));
127
+ if (!parsed.success) return refuse(400, "invalid_request");
128
+ const body = parsed.data;
129
+
130
+ const claim = openClaim(body.claim);
131
+ if (claim === null || claim.clientId !== body.client_id) {
132
+ return refuse(410, "claim_invalid");
133
+ }
134
+
135
+ const limited = refusedCallerLimit(request);
136
+ if (limited !== null) return limited;
137
+ const client = forwardedClientAuth(request);
138
+ if (client === null) {
139
+ noteRefusedCaller(request);
140
+ return refuse(401, "invalid_client");
141
+ }
142
+ try {
143
+ const checked = await hubSignIn.entry(client, {
144
+ clientId: body.client_id,
145
+ redirectUri: body.redirect_uri,
146
+ email: claim.email,
147
+ });
148
+ if (!checked.ok) {
149
+ if (checked.status === 401 || checked.status === 403) {
150
+ noteRefusedCaller(request);
151
+ }
152
+ return refuse(
153
+ checked.status,
154
+ apiErrorCode(checked.body, "invalid_request"),
155
+ );
156
+ }
157
+ } catch {
158
+ return refuse(503, "temporarily_unavailable");
159
+ }
160
+
161
+ const evidence = await readHubSignUpEvidence(claim.locale);
162
+ if (evidence === null) return refuse(503, "temporarily_unavailable");
163
+ if (!coversPurchaseTerms(evidence, claim.policyVersion)) {
164
+ return refuse(410, "terms_changed");
165
+ }
166
+
167
+ const identifier = `purchase-claim:${createHash("sha256").update(claim.sessionId).digest("hex")}`;
168
+ try {
169
+ const { internalAdapter } = await auth.$context;
170
+ if (await internalAdapter.findUserByEmail(claim.email)) {
171
+ return refuse(409, "account_exists");
172
+ }
173
+ const used = await internalAdapter.findVerificationValue(identifier);
174
+ if (used && new Date(used.expiresAt).getTime() > Date.now()) {
175
+ return refuse(410, "claim_used");
176
+ }
177
+ await internalAdapter.createVerificationValue({
178
+ identifier,
179
+ value: "1",
180
+ expiresAt: new Date(Date.now() + PURCHASE_CLAIM_TTL_SECONDS * 1000),
181
+ });
182
+ } catch {
183
+ return refuse(503, "temporarily_unavailable");
184
+ }
185
+
186
+ const ref = sealQuery(
187
+ {
188
+ response_type: "code",
189
+ client_id: body.client_id,
190
+ redirect_uri: body.redirect_uri,
191
+ state: body.state,
192
+ code_challenge: body.code_challenge,
193
+ code_challenge_method: body.code_challenge_method,
194
+ },
195
+ resolveSecret(),
196
+ );
197
+ if (ref === null) return release(identifier, refuse(400, "invalid_request"));
198
+ const callbackURL = `${CONTINUE_PATH}/${ref}`;
199
+
200
+ const capture: PurchaseCaptureStore = { token: null };
201
+ try {
202
+ await purchaseCapture.run(capture, () =>
203
+ auth.api.signInMagicLink({
204
+ body: {
205
+ email: claim.email,
206
+ callbackURL,
207
+ metadata: { agreements: ["account_terms"], locale: claim.locale },
208
+ },
209
+ headers: new Headers({ origin }),
210
+ }),
211
+ );
212
+ } catch (err) {
213
+ const code = betterAuthCode(err);
214
+ if (code === "AGREEMENTS_REQUIRED") {
215
+ return release(identifier, refuse(410, "terms_changed"));
216
+ }
217
+ if (code === "SIGN_UP_CLOSED") {
218
+ return release(identifier, refuse(410, "sign_up_closed"));
219
+ }
220
+ return release(identifier, refuse(503, "temporarily_unavailable"));
221
+ }
222
+ if (capture.token === null) {
223
+ return release(identifier, refuse(503, "temporarily_unavailable"));
224
+ }
225
+
226
+ const verify = new URL("/api/auth/magic-link/verify", origin);
227
+ verify.searchParams.set("token", capture.token);
228
+ verify.searchParams.set("callbackURL", callbackURL);
229
+ return json(200, { verifyUrl: verify.toString() });
230
+ }
@@ -0,0 +1,174 @@
1
+ /**
2
+ * `POST /api/auth/hub/purchase-link` — the hub API's signed "a buyer paid"
3
+ * call (#11096 D8, D9, spec docs/specs/11096-the-spoke-hosts-the-sign-spec.md).
4
+ *
5
+ * The hub API's checkout buyer service posts `{ email, clientId, sessionId,
6
+ * policyVersion, locale }` after a paid Offerings session, signed with
7
+ * HMAC-SHA256 under `AUTH_EMAIL_WEBHOOK_SECRET` over
8
+ * `v0:purchase-link:{timestamp}:{rawBody}` — the `purchase-link` label keeps
9
+ * it apart from the auth-email relay's own base string. Refusals in the
10
+ * relay's order: 503 (no secret or no pinned origin) → 401 (a missing or bad
11
+ * signature, or a timestamp more than 300 s away, checked over the raw body
12
+ * BEFORE any parse) → 400 (a body the schema refuses). Then:
13
+ *
14
+ * - once per session: a `purchase-link:<SHA-256 of the session id>`
15
+ * verification row (72 h). One already there answers 202 and sends
16
+ * nothing, so a replayed body inside the skew mails nothing
17
+ * (SEC-11096-13);
18
+ * - the evidence must be exactly `account_terms` at the body's version,
19
+ * else 202 with nothing sent;
20
+ * - the spoke's origin comes from the registry (`hubSignIn.clientInfo`),
21
+ * else 202 with nothing sent;
22
+ * - the claim is the five facts sealed under `hub-purchase` for 72 h, so it
23
+ * never opens as a continuation and the reverse;
24
+ * - one `account-open` email to `<spoke origin>/account?claim=<claim>`.
25
+ *
26
+ * Every accepted body answers the same 202, sent or not. Nothing is logged
27
+ * but the outcome.
28
+ */
29
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
30
+
31
+ import { authEmail, hubSignIn } from "@working-theory/api-client";
32
+ import { hubPurchaseLinkBodySchema } from "@working-theory/validation";
33
+
34
+ import { auth, resolveSecret } from "../../../../../auth";
35
+ import { makeSendAccountOpen } from "../../../../../lib/auth-email";
36
+ import { mintContinuation, pinnedOrigin } from "../continuation";
37
+ import {
38
+ json,
39
+ parseJson,
40
+ PURCHASE_CLAIM_NAME,
41
+ PURCHASE_CLAIM_TTL_SECONDS,
42
+ readRawBody,
43
+ refuse,
44
+ } from "../entry-shared";
45
+ import {
46
+ coversPurchaseTerms,
47
+ normaliseEvidenceLocale,
48
+ readHubSignUpEvidence,
49
+ } from "../sign-up-evidence";
50
+
51
+ /** The longest a signed body may be in transit (the relay's own skew). */
52
+ const SKEW_SECONDS = 300;
53
+
54
+ function log(outcome: string): void {
55
+ console.info(`[hub-purchase-link] ${JSON.stringify({ outcome })}`);
56
+ }
57
+
58
+ /** Whether `signature` is `sha256=<hex>` of the base string under `secret`. */
59
+ function signatureValid(
60
+ secret: string,
61
+ timestamp: string,
62
+ rawBody: string,
63
+ signature: string,
64
+ ): boolean {
65
+ const expected = Buffer.from(
66
+ `sha256=${createHmac("sha256", secret)
67
+ .update(`v0:purchase-link:${timestamp}:${rawBody}`, "utf8")
68
+ .digest("hex")}`,
69
+ "utf8",
70
+ );
71
+ const given = Buffer.from(signature, "utf8");
72
+ return given.length === expected.length && timingSafeEqual(given, expected);
73
+ }
74
+
75
+ const accepted = (outcome: string): Response => {
76
+ log(outcome);
77
+ return json(202, { accepted: true });
78
+ };
79
+
80
+ // platform-decisions-waiver: api-versioning — a hub-internal signed hop, not a versioned API contract (spec 11096 § 6)
81
+ export async function POST(request: Request): Promise<Response> {
82
+ const secret = process.env.AUTH_EMAIL_WEBHOOK_SECRET;
83
+ const origin = pinnedOrigin();
84
+ if (!secret || origin === null) return refuse(503, "temporarily_unavailable");
85
+
86
+ const timestamp = request.headers.get("x-ailk-purchase-timestamp") ?? "";
87
+ const signature = request.headers.get("x-ailk-purchase-signature") ?? "";
88
+ const raw = await readRawBody(request);
89
+ const seconds = /^\d{1,12}$/.test(timestamp) ? Number(timestamp) : NaN;
90
+ if (
91
+ raw === null ||
92
+ !Number.isFinite(seconds) ||
93
+ Math.abs(Date.now() / 1000 - seconds) > SKEW_SECONDS ||
94
+ !signatureValid(secret, timestamp, raw, signature)
95
+ ) {
96
+ return refuse(401, "invalid_signature");
97
+ }
98
+
99
+ const parsed = hubPurchaseLinkBodySchema.safeParse(parseJson(raw));
100
+ if (!parsed.success) return refuse(400, "invalid_request");
101
+ const body = parsed.data;
102
+
103
+ const identifier = `purchase-link:${createHash("sha256").update(body.sessionId).digest("hex")}`;
104
+ try {
105
+ const { internalAdapter } = await auth.$context;
106
+ const seen = await internalAdapter.findVerificationValue(identifier);
107
+ if (seen && new Date(seen.expiresAt).getTime() > Date.now()) {
108
+ return accepted("already_sent");
109
+ }
110
+ } catch {
111
+ return refuse(503, "temporarily_unavailable");
112
+ }
113
+
114
+ // Every check that can send nothing runs before the marker is written, so
115
+ // a refusal or a failed read never stands in for a sent link.
116
+ const locale = normaliseEvidenceLocale(body.locale);
117
+ const evidence = await readHubSignUpEvidence(locale);
118
+ if (evidence === null) return refuse(503, "temporarily_unavailable");
119
+ if (!coversPurchaseTerms(evidence, body.policyVersion)) {
120
+ return accepted("terms_not_covering");
121
+ }
122
+
123
+ let spokeOrigin: string;
124
+ try {
125
+ const info = await hubSignIn.clientInfo(body.clientId);
126
+ if (!info.ok) return accepted("no_client");
127
+ spokeOrigin = new URL(info.body.origin).origin;
128
+ } catch {
129
+ return accepted("no_client");
130
+ }
131
+
132
+ try {
133
+ const { internalAdapter } = await auth.$context;
134
+ await internalAdapter.createVerificationValue({
135
+ identifier,
136
+ value: "1",
137
+ expiresAt: new Date(Date.now() + PURCHASE_CLAIM_TTL_SECONDS * 1000),
138
+ });
139
+ } catch {
140
+ return refuse(503, "temporarily_unavailable");
141
+ }
142
+
143
+ const claim = mintContinuation(
144
+ new URLSearchParams({
145
+ e: body.email,
146
+ c: body.clientId,
147
+ s: body.sessionId,
148
+ v: String(body.policyVersion),
149
+ l: locale,
150
+ }).toString(),
151
+ resolveSecret(),
152
+ Date.now(),
153
+ PURCHASE_CLAIM_NAME,
154
+ PURCHASE_CLAIM_TTL_SECONDS,
155
+ );
156
+ const url = new URL("/account", spokeOrigin);
157
+ url.searchParams.set("claim", claim);
158
+
159
+ const sent = await makeSendAccountOpen({
160
+ send: (rawBody, headers) => authEmail.send(rawBody, headers),
161
+ })({ to: body.email, url: url.toString() });
162
+ if (!sent) {
163
+ // Not sent: drop the marker so the next delivery of this purchase can.
164
+ try {
165
+ const { internalAdapter } = await auth.$context;
166
+ await internalAdapter.deleteVerificationByIdentifier(identifier);
167
+ } catch {
168
+ // The marker stays; this buyer opens an account through the form.
169
+ }
170
+ log("send_failed");
171
+ return refuse(503, "temporarily_unavailable");
172
+ }
173
+ return accepted("sent");
174
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * `GET /api/auth/hub/sign-up?locale=` — what a spoke's sign-in form shows a
3
+ * new person (#11096 D3, spec docs/specs/11096-the-spoke-hosts-the-sign-spec.md).
4
+ *
5
+ * `{ signUpOpen, google, agreements }`: whether this hub takes sign-ups,
6
+ * whether Google is an active provider, and each sign-up agreement from the
7
+ * same evidence the agreements plugin checks (`./sign-up-evidence.ts`), as
8
+ * `{ purposeId, statement, policies }`. The policies are the hub's, so each
9
+ * link is absolute on the pinned origin. No auth: the same evidence
10
+ * `GET /v1/consent/sign-up` serves anonymously. `public, max-age=60` on a
11
+ * 200; an evidence read that fails is a 503 (`no-store`), never an empty
12
+ * list a spoke could read as "no agreements needed".
13
+ */
14
+ import { localeSchema } from "@working-theory/validation";
15
+
16
+ import {
17
+ getActiveProviderIds,
18
+ isSignUpOpen,
19
+ } from "../../../../../lib/auth-env";
20
+ import { consentPoliciesFor } from "../../../../../lib/consent-policies";
21
+ import { pinnedOrigin } from "../continuation";
22
+ import { json, refuse } from "../entry-shared";
23
+ import {
24
+ normaliseEvidenceLocale,
25
+ readHubSignUpEvidence,
26
+ } from "../sign-up-evidence";
27
+
28
+ // platform-decisions-waiver: api-versioning — a hub sign-in step, not a versioned API contract (spec 11096 § 6)
29
+ export async function GET(request: Request): Promise<Response> {
30
+ const origin = pinnedOrigin();
31
+ if (origin === null) return refuse(503, "temporarily_unavailable");
32
+
33
+ const requested = new URL(request.url).searchParams.get("locale");
34
+ const locale = normaliseEvidenceLocale(
35
+ localeSchema.safeParse(requested).success ? requested : undefined,
36
+ );
37
+ const evidence = await readHubSignUpEvidence(locale);
38
+ if (evidence === null) return refuse(503, "temporarily_unavailable");
39
+
40
+ const policies = Object.fromEntries(
41
+ Object.entries(consentPoliciesFor(locale)).map(([key, path]) => [
42
+ key,
43
+ new URL(path, origin).toString(),
44
+ ]),
45
+ );
46
+
47
+ return json(
48
+ 200,
49
+ {
50
+ signUpOpen: isSignUpOpen(),
51
+ google: getActiveProviderIds().includes("google"),
52
+ agreements: evidence.agreements.map(({ purposeId, statement }) => ({
53
+ purposeId,
54
+ statement,
55
+ policies,
56
+ })),
57
+ },
58
+ { "Cache-Control": "public, max-age=60" },
59
+ );
60
+ }