create-ailk 0.38.0 → 0.39.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 (135) hide show
  1. package/dist/add-route.js +1 -1
  2. package/dist/derive-architecture.js +3 -1
  3. package/dist/remove-module.js +18 -14
  4. package/dist/routes.d.ts +29 -2
  5. package/dist/routes.js +269 -23
  6. package/dist/site-manifest.js +6 -4
  7. package/dist/site-roster.d.ts +11 -3
  8. package/dist/site-roster.js +42 -22
  9. package/dist/surfaces.d.ts +11 -3
  10. package/dist/surfaces.js +69 -22
  11. package/dist/sync-routes.js +22 -5
  12. package/dist/template-record.js +3 -1
  13. package/dist/topology.d.ts +11 -0
  14. package/dist/topology.js +253 -3
  15. package/package.json +3 -3
  16. package/templates/apps/web/CLAUDE.md +26 -4
  17. package/templates/apps/web/__tests__/__mocks__/next-intl-server.ts +5 -1
  18. package/templates/apps/web/__tests__/__mocks__/next-intl.ts +5 -1
  19. package/templates/apps/web/__tests__/auth/seam.test.ts +34 -0
  20. package/templates/apps/web/account.config.tsx +2 -3
  21. package/templates/apps/web/app/[locale]/(authed)/account/connect/__tests__/page.test.tsx +1 -1
  22. package/templates/apps/web/app/[locale]/(authed)/account/connect/page.tsx +1 -1
  23. package/templates/apps/web/app/[locale]/(authed)/signed-out-gate.generated.tsx +1 -1
  24. package/templates/apps/web/app/[locale]/layout.tsx +1 -1
  25. package/templates/apps/web/auth.config.tsx +107 -0
  26. package/templates/apps/web/auth.ts +2 -1
  27. package/templates/apps/web/i18n/request.ts +9 -2
  28. package/templates/apps/web/jest.config.cjs +4 -0
  29. package/templates/apps/web/lib/__tests__/fixtures/site-topology.ts +3 -0
  30. package/templates/apps/web/lib/__tests__/server-api.test.ts +1 -1
  31. package/templates/apps/web/lib/server-api.ts +1 -1
  32. package/templates/apps/web/lib/topology.generated.ts +5 -0
  33. package/templates/apps/web/messages/en.json +0 -152
  34. package/templates/apps/web/middleware.ts +12 -25
  35. package/templates/apps/web/next.config.mjs +8 -0
  36. package/templates/apps/web/package.json +1 -0
  37. package/templates/apps/web/types/messages.d.ts +6 -1
  38. package/versions.json +49 -48
  39. package/templates/apps/web/app/[locale]/(auth)/__tests__/auth-pages.test.tsx +0 -322
  40. package/templates/apps/web/app/[locale]/(auth)/__tests__/password-reset.test.tsx +0 -554
  41. package/templates/apps/web/app/[locale]/(auth)/consent/__tests__/consent-actions.test.ts +0 -56
  42. package/templates/apps/web/app/[locale]/(auth)/consent/__tests__/page.test.tsx +0 -164
  43. package/templates/apps/web/app/[locale]/(auth)/consent/consent-form.tsx +0 -132
  44. package/templates/apps/web/app/[locale]/(auth)/consent/consent.actions.ts +0 -51
  45. package/templates/apps/web/app/[locale]/(auth)/consent/page.tsx +0 -144
  46. package/templates/apps/web/app/[locale]/(auth)/forgot-password/forgot-password-card.tsx +0 -101
  47. package/templates/apps/web/app/[locale]/(auth)/forgot-password/page.tsx +0 -111
  48. package/templates/apps/web/app/[locale]/(auth)/layout.tsx +0 -81
  49. package/templates/apps/web/app/[locale]/(auth)/legal-footnote.tsx +0 -35
  50. package/templates/apps/web/app/[locale]/(auth)/reset-password/__tests__/return.test.tsx +0 -179
  51. package/templates/apps/web/app/[locale]/(auth)/reset-password/page.tsx +0 -157
  52. package/templates/apps/web/app/[locale]/(auth)/reset-password/reset-password-card.tsx +0 -126
  53. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/next-path.test.ts +0 -54
  54. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/page.test.tsx +0 -628
  55. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/remembered-method.test.ts +0 -43
  56. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/sign-in-card.test.tsx +0 -266
  57. package/templates/apps/web/app/[locale]/(auth)/sign-in/next-path.ts +0 -20
  58. package/templates/apps/web/app/[locale]/(auth)/sign-in/page.tsx +0 -234
  59. package/templates/apps/web/app/[locale]/(auth)/sign-in/remembered-method.ts +0 -37
  60. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-card.tsx +0 -323
  61. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-text.ts +0 -93
  62. package/templates/apps/web/app/[locale]/(auth)/sign-up/__tests__/page.test.tsx +0 -301
  63. package/templates/apps/web/app/[locale]/(auth)/sign-up/__tests__/sign-up-card.test.tsx +0 -309
  64. package/templates/apps/web/app/[locale]/(auth)/sign-up/page.tsx +0 -201
  65. package/templates/apps/web/app/[locale]/(auth)/sign-up/sign-up-card.tsx +0 -366
  66. package/templates/apps/web/app/[locale]/(auth)/use-auth-card-flow.ts +0 -116
  67. package/templates/apps/web/app/[locale]/(auth)/verify-email/__tests__/actions.test.ts +0 -94
  68. package/templates/apps/web/app/[locale]/(auth)/verify-email/actions.ts +0 -77
  69. package/templates/apps/web/app/[locale]/(auth)/verify-email/page.tsx +0 -154
  70. package/templates/apps/web/app/[locale]/(authed)/account/appointments/[slug]/page.tsx +0 -3
  71. package/templates/apps/web/app/[locale]/(authed)/account/appointments/page.tsx +0 -3
  72. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/page.tsx +0 -3
  73. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/versions/[version]/file/route.ts +0 -2
  74. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/page.tsx +0 -3
  75. package/templates/apps/web/app/[locale]/(authed)/account/billing/page.tsx +0 -12
  76. package/templates/apps/web/app/[locale]/(authed)/account/general/page.tsx +0 -12
  77. package/templates/apps/web/app/[locale]/(authed)/account/inbox/[kind]/[id]/page.tsx +0 -12
  78. package/templates/apps/web/app/[locale]/(authed)/account/inbox/message/[id]/file/route.ts +0 -2
  79. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/page.tsx +0 -12
  80. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/page.tsx +0 -3
  81. package/templates/apps/web/app/[locale]/(authed)/account/layout.tsx +0 -10
  82. package/templates/apps/web/app/[locale]/(authed)/account/notifications/page.tsx +0 -3
  83. package/templates/apps/web/app/[locale]/(authed)/account/onboarding/page.tsx +0 -3
  84. package/templates/apps/web/app/[locale]/(authed)/account/page.tsx +0 -12
  85. package/templates/apps/web/app/[locale]/(authed)/account/privacy/export/route.ts +0 -2
  86. package/templates/apps/web/app/[locale]/(authed)/account/privacy/page.tsx +0 -3
  87. package/templates/apps/web/app/[locale]/(authed)/account/security/page.tsx +0 -3
  88. package/templates/apps/web/app/[locale]/(authed)/account/settings/page.tsx +0 -2
  89. package/templates/apps/web/app/[locale]/(authed)/account/support/page.tsx +0 -3
  90. package/templates/apps/web/app/api/auth/[...all]/route.ts +0 -16
  91. package/templates/apps/web/app/api/auth/hub/__tests__/continuation.test.ts +0 -143
  92. package/templates/apps/web/app/api/auth/hub/__tests__/entry-routes.test.ts +0 -749
  93. package/templates/apps/web/app/api/auth/hub/authorize/__tests__/route.test.ts +0 -964
  94. package/templates/apps/web/app/api/auth/hub/authorize/route.ts +0 -390
  95. package/templates/apps/web/app/api/auth/hub/continuation.ts +0 -127
  96. package/templates/apps/web/app/api/auth/hub/continue/[ref]/__tests__/route.test.ts +0 -188
  97. package/templates/apps/web/app/api/auth/hub/continue/[ref]/route.ts +0 -53
  98. package/templates/apps/web/app/api/auth/hub/email/route.ts +0 -111
  99. package/templates/apps/web/app/api/auth/hub/entry-shared.ts +0 -163
  100. package/templates/apps/web/app/api/auth/hub/password/__tests__/return.test.ts +0 -86
  101. package/templates/apps/web/app/api/auth/hub/password/__tests__/route.test.ts +0 -368
  102. package/templates/apps/web/app/api/auth/hub/password/return.ts +0 -86
  103. package/templates/apps/web/app/api/auth/hub/password/route.ts +0 -171
  104. package/templates/apps/web/app/api/auth/hub/purchase/route.ts +0 -230
  105. package/templates/apps/web/app/api/auth/hub/purchase-link/route.ts +0 -174
  106. package/templates/apps/web/app/api/auth/hub/sign-up/route.ts +0 -60
  107. package/templates/apps/web/app/api/auth/hub/sign-up-evidence.ts +0 -97
  108. package/templates/apps/web/app/api/auth/mcp/__tests__/continuation.test.ts +0 -92
  109. package/templates/apps/web/app/api/auth/mcp/continuation.ts +0 -89
  110. package/templates/apps/web/app/api/auth/mcp/continue/[ref]/__tests__/route.test.ts +0 -59
  111. package/templates/apps/web/app/api/auth/mcp/continue/[ref]/route.ts +0 -41
  112. package/templates/apps/web/app/api/hub-session/__tests__/routes.test.ts +0 -1166
  113. package/templates/apps/web/app/api/hub-session/callback/route.ts +0 -134
  114. package/templates/apps/web/app/api/hub-session/email/route.ts +0 -125
  115. package/templates/apps/web/app/api/hub-session/one-tap/nonce/route.ts +0 -49
  116. package/templates/apps/web/app/api/hub-session/one-tap/route.ts +0 -106
  117. package/templates/apps/web/app/api/hub-session/open/route.ts +0 -111
  118. package/templates/apps/web/app/api/hub-session/password/return/route.ts +0 -69
  119. package/templates/apps/web/app/api/hub-session/password/route.ts +0 -106
  120. package/templates/apps/web/app/api/hub-session/sign-in/route.ts +0 -91
  121. package/templates/apps/web/app/api/hub-session/sign-out/route.ts +0 -54
  122. package/templates/apps/web/components/sign-out-trigger.tsx +0 -62
  123. package/templates/apps/web/lib/__tests__/auth-routes.test.ts +0 -140
  124. package/templates/apps/web/lib/auth-routes.ts +0 -125
  125. package/templates/apps/web/lib/hub-session/__tests__/hub-session.test.ts +0 -433
  126. package/templates/apps/web/lib/hub-session/__tests__/spoke-sign-in.test.tsx +0 -332
  127. package/templates/apps/web/lib/hub-session/config.ts +0 -110
  128. package/templates/apps/web/lib/hub-session/entry.ts +0 -238
  129. package/templates/apps/web/lib/hub-session/index.ts +0 -21
  130. package/templates/apps/web/lib/hub-session/one-tap.tsx +0 -148
  131. package/templates/apps/web/lib/hub-session/reseal.ts +0 -90
  132. package/templates/apps/web/lib/hub-session/seal.ts +0 -86
  133. package/templates/apps/web/lib/hub-session/session.ts +0 -298
  134. package/templates/apps/web/lib/hub-session/spoke-sign-in.tsx +0 -277
  135. package/templates/apps/web/lib/next-path.ts +0 -35
@@ -1,230 +0,0 @@
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
- }
@@ -1,174 +0,0 @@
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
- }
@@ -1,60 +0,0 @@
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
- }
@@ -1,97 +0,0 @@
1
- /**
2
- * The hub's sign-up evidence, as the spoke-hosted entry reads it (#11096 D3,
3
- * D9).
4
- *
5
- * The same source the sign-up agreements plugin checks a sign-up request
6
- * against: `GET /v1/consent/sign-up` through `consent.signUpEvidence`, parsed
7
- * with `consentSignUpResponseSchema`, for one of the site's enabled locales
8
- * (anything else reads as `en`). So the agreements a spoke's form shows, and
9
- * the version a purchase claim is checked at, are the ones the plugin
10
- * enforces. It keeps its own per-process entry, fresh for 60 s, one per
11
- * enabled locale; a read is bounded at 2 s and never throws — a failure is
12
- * `null`, and a failed refresh serves nothing stale, so a caller that needs
13
- * the evidence fails closed.
14
- *
15
- * A second reader rather than the plugin's own cache because
16
- * `lib/sign-up-agreements.ts` is not this unit's to change; the two read the
17
- * same API answer, and the plugin still refuses any request its own read
18
- * does not cover.
19
- */
20
- import { consent } from "@working-theory/api-client";
21
- import {
22
- consentSignUpResponseSchema,
23
- type ConsentSignUpResponse,
24
- } from "@working-theory/validation";
25
-
26
- const DEFAULT_LOCALE = "en";
27
- const FRESH_MS = 60_000;
28
- const READ_TIMEOUT_MS = 2_000;
29
-
30
- const cache = new Map<
31
- string,
32
- { evidence: ConsentSignUpResponse; fetchedAt: number }
33
- >();
34
-
35
- /** Test seam: empties the per-process cache. */
36
- export function resetHubSignUpEvidenceCache(): void {
37
- cache.clear();
38
- }
39
-
40
- function enabledLocales(): string[] {
41
- const enabled = (process.env.NEXT_PUBLIC_ENABLED_LOCALES ?? DEFAULT_LOCALE)
42
- .split(",")
43
- .map((locale) => locale.trim())
44
- .filter((locale) => locale.length > 0);
45
- return enabled.length > 0 ? enabled : [DEFAULT_LOCALE];
46
- }
47
-
48
- /** `raw` when it is one of the site's enabled locales, else `en`. */
49
- export function normaliseEvidenceLocale(raw: unknown): string {
50
- return typeof raw === "string" && enabledLocales().includes(raw)
51
- ? raw
52
- : DEFAULT_LOCALE;
53
- }
54
-
55
- /** The evidence for `locale` (normalised), or `null` when it cannot be read. */
56
- export async function readHubSignUpEvidence(
57
- locale: unknown,
58
- ): Promise<ConsentSignUpResponse | null> {
59
- const key = normaliseEvidenceLocale(locale);
60
- const entry = cache.get(key);
61
- if (entry && Date.now() - entry.fetchedAt < FRESH_MS) return entry.evidence;
62
- let timer: ReturnType<typeof setTimeout> | undefined;
63
- const timedOut = new Promise<null>((resolve) => {
64
- timer = setTimeout(() => resolve(null), READ_TIMEOUT_MS);
65
- });
66
- try {
67
- const res = await Promise.race([
68
- consent.signUpEvidence({ locale: key }),
69
- timedOut,
70
- ]);
71
- if (res === null || !res.ok) return null;
72
- const parsed = consentSignUpResponseSchema.safeParse(res.body);
73
- if (!parsed.success) return null;
74
- cache.set(key, { evidence: parsed.data, fetchedAt: Date.now() });
75
- return parsed.data;
76
- } catch {
77
- return null;
78
- } finally {
79
- clearTimeout(timer);
80
- }
81
- }
82
-
83
- /**
84
- * Whether the evidence asks for exactly one agreement, `account_terms`, at
85
- * `policyVersion` — the only shape a purchase claim covers (#11096 D9).
86
- */
87
- export function coversPurchaseTerms(
88
- evidence: ConsentSignUpResponse,
89
- policyVersion: number,
90
- ): boolean {
91
- const [only, ...rest] = evidence.agreements;
92
- return (
93
- rest.length === 0 &&
94
- only?.purposeId === "account_terms" &&
95
- only.policyVersion === policyVersion
96
- );
97
- }
@@ -1,92 +0,0 @@
1
- /**
2
- * @jest-environment node
3
- */
4
-
5
- /**
6
- * The MCP sign-in leg's continuation (#10479): the hub's sealed ref, under a
7
- * name of its own. Pure functions over `seal.ts`; no mocks.
8
- */
9
- import { mintContinuation } from "../../hub/continuation";
10
- import {
11
- MCP_CONTINUE_PATH,
12
- mintMcpContinuation,
13
- openMcpContinuation,
14
- sealMcpCallbacks,
15
- } from "../continuation";
16
-
17
- const SECRET = "k".repeat(43);
18
- const T = 1_790_000_000_000;
19
-
20
- const Q = new URLSearchParams({
21
- response_type: "code",
22
- client_id: "mcp-client",
23
- redirect_uri: "http://127.0.0.1:53682/callback",
24
- state: "s".repeat(43),
25
- code_challenge: "c".repeat(43),
26
- code_challenge_method: "S256",
27
- }).toString();
28
-
29
- it("pins the continue path", () => {
30
- expect(MCP_CONTINUE_PATH).toBe("/api/auth/mcp/continue");
31
- });
32
-
33
- it("round-trips the authorize query, scheme-bearing redirect_uri included", () => {
34
- expect(openMcpContinuation(mintMcpContinuation(Q, SECRET, T), SECRET, T + 1_000)).toBe(Q);
35
- });
36
-
37
- it("mints a ref no decode can change: base64url only, so no ':', '%', '?', '&' or '='", () => {
38
- expect(mintMcpContinuation(Q, SECRET, T)).toMatch(/^[A-Za-z0-9_-]+$/);
39
- });
40
-
41
- it("expires at 600 s", () => {
42
- expect(openMcpContinuation(mintMcpContinuation(Q, SECRET, T), SECRET, T + 600_000)).toBeNull();
43
- });
44
-
45
- it("never opens a hub ref, nor under another secret", () => {
46
- expect(openMcpContinuation(mintContinuation(Q, SECRET, T), SECRET, T)).toBeNull();
47
- expect(openMcpContinuation(mintMcpContinuation(Q, SECRET, T), "x".repeat(43), T)).toBeNull();
48
- });
49
-
50
- describe("sealMcpCallbacks — the sign-in body's MCP resume, sealed", () => {
51
- const next = `/api/auth/mcp/authorize?${Q}`;
52
- const refOf = (path: string | undefined) =>
53
- /^\/api\/auth\/mcp\/continue\/([A-Za-z0-9_-]+)$/.exec(path ?? "")?.[1] ?? "";
54
-
55
- it("seals callbackURL and the next inside the sign-in page's errorCallbackURL; both open to the query", () => {
56
- const sealed = sealMcpCallbacks(
57
- { callbackURL: next, errorCallbackURL: `/de/sign-in?next=${encodeURIComponent(next)}` },
58
- SECRET,
59
- );
60
- expect(openMcpContinuation(refOf(sealed?.callbackURL), SECRET)).toBe(Q);
61
- const error = new URL(sealed?.errorCallbackURL ?? "", "http://x.invalid");
62
- expect(error.pathname).toBe("/de/sign-in");
63
- expect(openMcpContinuation(refOf(error.searchParams.get("next") ?? ""), SECRET)).toBe(Q);
64
- // No decode of either value can produce a ':'.
65
- expect(decodeURIComponent(decodeURIComponent(sealed?.errorCallbackURL ?? ""))).not.toContain(":");
66
- });
67
-
68
- it.each([
69
- ["no callbacks", {}],
70
- ["an ordinary next", { callbackURL: "/account", errorCallbackURL: "/sign-in?next=%2Faccount" }],
71
- ["the hub's own authorize path", { callbackURL: `/api/auth/hub/authorize?${Q}` }],
72
- ["a foreign errorCallbackURL", { errorCallbackURL: `https://evil.example/?next=${encodeURIComponent(next)}` }],
73
- ["a non-string callbackURL", { callbackURL: [next] }],
74
- // Security review: URL's dot-segment collapse would emit //evil.example.
75
- ["a dot-segment errorCallbackURL", { errorCallbackURL: `/.//evil.example?next=${encodeURIComponent(next)}` }],
76
- ["an errorCallbackURL on another page", { errorCallbackURL: `/account?next=${encodeURIComponent(next)}` }],
77
- ["an errorCallbackURL with a second key", { errorCallbackURL: `/sign-in?next=${encodeURIComponent(next)}&x=1` }],
78
- ["a next holding CR/LF", { callbackURL: `${next}%0D%0A`.replace("%0D%0A", "\r\n") }],
79
- ["an undecodable next", { errorCallbackURL: "/sign-in?next=%E0%A4%A" }],
80
- ])("leaves %s alone (null)", (_name, body) => {
81
- expect(sealMcpCallbacks(body, SECRET)).toBeNull();
82
- });
83
-
84
- it("seals the sign-up page's errorCallbackURL the same way", () => {
85
- const sealed = sealMcpCallbacks({ errorCallbackURL: `/sign-up?next=${encodeURIComponent(next)}` }, SECRET);
86
- expect(sealed?.errorCallbackURL).toMatch(/^\/sign-up\?next=%2Fapi%2Fauth%2Fmcp%2Fcontinue%2F[A-Za-z0-9_-]+$/);
87
- });
88
-
89
- it("leaves a query too long to seal under the continue route's cap as it was", () => {
90
- expect(sealMcpCallbacks({ callbackURL: `${next}&state=${"s".repeat(4096)}` }, SECRET)).toBeNull();
91
- });
92
- });