create-ailk 0.35.1 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/README.md +1 -1
  2. package/component-catalog.json +51 -1
  3. package/component-catalog.md +8 -5
  4. package/dist/lib/env-catalog.js +8 -0
  5. package/dist/surfaces.js +66 -22
  6. package/dist/topology.d.ts +4 -4
  7. package/dist/topology.js +104 -60
  8. package/dist/update.d.ts +19 -1
  9. package/dist/update.js +293 -35
  10. package/package.json +3 -3
  11. package/templates/.env.example +38 -0
  12. package/templates/apps/api/.env.example +45 -0
  13. package/templates/apps/api/CLAUDE.md +12 -4
  14. package/templates/apps/api/src/lib/__mocks__/prisma.ts +7 -0
  15. package/templates/apps/mcp/CLAUDE.md +4 -2
  16. package/templates/apps/web/.env.example +16 -0
  17. package/templates/apps/web/CLAUDE.md +73 -5
  18. package/templates/apps/web/app/[locale]/(auth)/__tests__/password-reset.test.tsx +2 -0
  19. package/templates/apps/web/app/[locale]/(auth)/reset-password/__tests__/return.test.tsx +179 -0
  20. package/templates/apps/web/app/[locale]/(auth)/reset-password/page.tsx +22 -2
  21. package/templates/apps/web/app/[locale]/(auth)/reset-password/reset-password-card.tsx +9 -2
  22. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/page.test.tsx +52 -1
  23. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/remembered-method.test.ts +43 -0
  24. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/sign-in-card.test.tsx +108 -1
  25. package/templates/apps/web/app/[locale]/(auth)/sign-in/page.tsx +36 -3
  26. package/templates/apps/web/app/[locale]/(auth)/sign-in/remembered-method.ts +37 -0
  27. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-card.tsx +90 -33
  28. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-text.ts +9 -4
  29. package/templates/apps/web/app/[locale]/(authed)/__tests__/gate.test.tsx +79 -348
  30. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/billing.test.tsx +241 -66
  31. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/general.test.tsx +242 -28
  32. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +377 -151
  33. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/item.test.tsx +26 -1
  34. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout-sign-out.test.tsx +10 -5
  35. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout.test.tsx +17 -6
  36. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/new-menu.test.tsx +51 -12
  37. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/new-popups.test.tsx +17 -2
  38. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/notifications.test.tsx +153 -2
  39. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/page.test.tsx +206 -23
  40. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/popups.test.tsx +150 -188
  41. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/privacy.test.tsx +235 -177
  42. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/rich-translator.ts +63 -0
  43. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/security.test.tsx +0 -3
  44. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/thread.test.tsx +340 -0
  45. package/templates/apps/web/app/[locale]/(authed)/account/account-data.ts +7 -5
  46. package/templates/apps/web/app/[locale]/(authed)/account/account-frame.tsx +20 -4
  47. package/templates/apps/web/app/[locale]/(authed)/account/actions.ts +8 -4
  48. package/templates/apps/web/app/[locale]/(authed)/account/appointments/[slug]/page.tsx +161 -0
  49. package/templates/apps/web/app/[locale]/(authed)/account/appointments/__tests__/page.test.tsx +426 -0
  50. package/templates/apps/web/app/[locale]/(authed)/account/appointments/appointments-data.ts +76 -0
  51. package/templates/apps/web/app/[locale]/(authed)/account/appointments/page.tsx +139 -0
  52. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/page.tsx +92 -24
  53. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/versions/[version]/file/route.ts +32 -1
  54. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/file-route.test.ts +76 -3
  55. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/page.test.tsx +290 -41
  56. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/artifact-data.ts +109 -11
  57. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/page.tsx +43 -44
  58. package/templates/apps/web/app/[locale]/(authed)/account/billing/__tests__/offerings.test.ts +99 -0
  59. package/templates/apps/web/app/[locale]/(authed)/account/billing/offerings.ts +123 -0
  60. package/templates/apps/web/app/[locale]/(authed)/account/billing/page.tsx +323 -73
  61. package/templates/apps/web/app/[locale]/(authed)/account/billing-source.ts +199 -43
  62. package/templates/apps/web/app/[locale]/(authed)/account/components/request-quote.tsx +52 -7
  63. package/templates/apps/web/app/[locale]/(authed)/account/connect/__tests__/page.test.tsx +8 -1
  64. package/templates/apps/web/app/[locale]/(authed)/account/connect/page.tsx +7 -3
  65. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/phone-verification.test.tsx +215 -0
  66. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/seam-imports.test.ts +65 -0
  67. package/templates/apps/web/app/[locale]/(authed)/account/general/account-name.ts +36 -0
  68. package/templates/apps/web/app/[locale]/(authed)/account/general/contact-actions.ts +70 -2
  69. package/templates/apps/web/app/[locale]/(authed)/account/general/contact-details.tsx +42 -0
  70. package/templates/apps/web/app/[locale]/(authed)/account/general/page.tsx +97 -53
  71. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-actions.ts +122 -0
  72. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-verification.tsx +215 -0
  73. package/templates/apps/web/app/[locale]/(authed)/account/general/photo-actions.ts +73 -0
  74. package/templates/apps/web/app/[locale]/(authed)/account/general/profile-form.tsx +12 -9
  75. package/templates/apps/web/app/[locale]/(authed)/account/general/profile-source.ts +18 -4
  76. package/templates/apps/web/app/[locale]/(authed)/account/inbox/[kind]/[id]/page.tsx +20 -2
  77. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/member-thread-composer.tsx +43 -0
  78. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/page.tsx +125 -0
  79. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/thread-data.ts +88 -0
  80. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/thread-write.ts +31 -0
  81. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/invitation-id.test.ts +35 -0
  82. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/page.test.tsx +266 -0
  83. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/actions.ts +116 -0
  84. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/invitation-id.ts +12 -0
  85. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/page.tsx +154 -0
  86. package/templates/apps/web/app/[locale]/(authed)/account/layout.tsx +9 -6
  87. package/templates/apps/web/app/[locale]/(authed)/account/new-menu.tsx +33 -8
  88. package/templates/apps/web/app/[locale]/(authed)/account/new-popups.tsx +31 -52
  89. package/templates/apps/web/app/[locale]/(authed)/account/notifications/page.tsx +44 -4
  90. package/templates/apps/web/app/[locale]/(authed)/account/page.tsx +69 -49
  91. package/templates/apps/web/app/[locale]/(authed)/account/privacy/__tests__/export-route.test.ts +173 -0
  92. package/templates/apps/web/app/[locale]/(authed)/account/privacy/actions.ts +42 -4
  93. package/templates/apps/web/app/[locale]/(authed)/account/privacy/export/route.ts +102 -0
  94. package/templates/apps/web/app/[locale]/(authed)/account/privacy/page.tsx +147 -137
  95. package/templates/apps/web/app/[locale]/(authed)/account/security/__tests__/hub-variant.test.tsx +258 -0
  96. package/templates/apps/web/app/[locale]/(authed)/account/security/page.tsx +21 -22
  97. package/templates/apps/web/app/[locale]/(authed)/account/security/security-panel.tsx +34 -6
  98. package/templates/apps/web/app/[locale]/(authed)/account/security/security-source.ts +37 -7
  99. package/templates/apps/web/app/[locale]/(authed)/account/settings/page.tsx +0 -2
  100. package/templates/apps/web/app/[locale]/(authed)/account/settings-frame.tsx +8 -5
  101. package/templates/apps/web/app/[locale]/(authed)/layout.tsx +15 -13
  102. package/templates/apps/web/app/[locale]/(authed)/signed-out-gate.generated.tsx +20 -52
  103. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsClient.tsx +3 -2
  104. package/templates/apps/web/app/[locale]/layout.tsx +24 -75
  105. package/templates/apps/web/app/[locale]/purchase/__tests__/success.test.tsx +50 -0
  106. package/templates/apps/web/app/[locale]/purchase/success/page.tsx +48 -7
  107. package/templates/apps/web/app/api/auth/hub/__tests__/entry-routes.test.ts +749 -0
  108. package/templates/apps/web/app/api/auth/hub/authorize/__tests__/route.test.ts +166 -7
  109. package/templates/apps/web/app/api/auth/hub/authorize/route.ts +96 -30
  110. package/templates/apps/web/app/api/auth/hub/continuation.ts +51 -2
  111. package/templates/apps/web/app/api/auth/hub/email/route.ts +111 -0
  112. package/templates/apps/web/app/api/auth/hub/entry-shared.ts +163 -0
  113. package/templates/apps/web/app/api/auth/hub/password/__tests__/return.test.ts +86 -0
  114. package/templates/apps/web/app/api/auth/hub/password/__tests__/route.test.ts +368 -0
  115. package/templates/apps/web/app/api/auth/hub/password/return.ts +86 -0
  116. package/templates/apps/web/app/api/auth/hub/password/route.ts +171 -0
  117. package/templates/apps/web/app/api/auth/hub/purchase/route.ts +230 -0
  118. package/templates/apps/web/app/api/auth/hub/purchase-link/route.ts +174 -0
  119. package/templates/apps/web/app/api/auth/hub/sign-up/route.ts +60 -0
  120. package/templates/apps/web/app/api/auth/hub/sign-up-evidence.ts +97 -0
  121. package/templates/apps/web/app/api/hub-session/__tests__/routes.test.ts +738 -7
  122. package/templates/apps/web/app/api/hub-session/callback/route.ts +13 -47
  123. package/templates/apps/web/app/api/hub-session/email/route.ts +125 -0
  124. package/templates/apps/web/app/api/hub-session/one-tap/nonce/route.ts +49 -0
  125. package/templates/apps/web/app/api/hub-session/one-tap/route.ts +106 -0
  126. package/templates/apps/web/app/api/hub-session/open/route.ts +111 -0
  127. package/templates/apps/web/app/api/hub-session/password/return/route.ts +69 -0
  128. package/templates/apps/web/app/api/hub-session/password/route.ts +106 -0
  129. package/templates/apps/web/app/api/hub-session/sign-in/route.ts +23 -40
  130. package/templates/apps/web/app/api/hub-session/sign-out/route.ts +1 -10
  131. package/templates/apps/web/auth.ts +133 -6
  132. package/templates/apps/web/components/sign-out-trigger.tsx +1 -1
  133. package/templates/apps/web/lib/__tests__/account-config.test.ts +129 -1
  134. package/templates/apps/web/lib/__tests__/auth-email.test.ts +141 -0
  135. package/templates/apps/web/lib/__tests__/auth-phone.test.ts +445 -0
  136. package/templates/apps/web/lib/__tests__/auth-sms.test.ts +140 -0
  137. package/templates/apps/web/lib/__tests__/fixtures/tsconfig.flow.json +18 -0
  138. package/templates/apps/web/lib/__tests__/offerings-pricing.test.ts +33 -0
  139. package/templates/apps/web/lib/__tests__/site-header.test.ts +13 -0
  140. package/templates/apps/web/lib/__tests__/telemetry-scrub.test.ts +19 -1
  141. package/templates/apps/web/lib/account-config.ts +132 -8
  142. package/templates/apps/web/lib/auth-email.ts +62 -6
  143. package/templates/apps/web/lib/auth-env.ts +13 -0
  144. package/templates/apps/web/lib/auth-routes.ts +11 -6
  145. package/templates/apps/web/lib/auth-sms.ts +180 -0
  146. package/templates/apps/web/lib/hub-session/__tests__/hub-session.test.ts +28 -0
  147. package/templates/apps/web/lib/hub-session/__tests__/spoke-sign-in.test.tsx +332 -0
  148. package/templates/apps/web/lib/hub-session/config.ts +7 -1
  149. package/templates/apps/web/lib/hub-session/entry.ts +238 -0
  150. package/templates/apps/web/lib/hub-session/index.ts +1 -4
  151. package/templates/apps/web/lib/hub-session/one-tap.tsx +148 -0
  152. package/templates/apps/web/lib/hub-session/session.ts +120 -2
  153. package/templates/apps/web/lib/hub-session/spoke-sign-in.tsx +277 -0
  154. package/templates/apps/web/lib/offerings-pricing.ts +4 -1
  155. package/templates/apps/web/lib/site-header.ts +14 -1
  156. package/templates/apps/web/lib/telemetry-scrub.ts +11 -0
  157. package/templates/apps/web/lib/topology.generated.ts +39 -0
  158. package/templates/apps/web/messages/en.json +264 -96
  159. package/templates/apps/web/middleware.ts +34 -2
  160. package/templates/apps/web/security-headers.config.ts +21 -0
  161. package/versions.json +48 -48
  162. package/templates/apps/web/app/[locale]/(authed)/account/components/schedule-service.tsx +0 -276
  163. package/templates/apps/web/app/[locale]/(authed)/account/components/send-message.tsx +0 -128
  164. package/templates/apps/web/app/[locale]/(authed)/account/settings/__tests__/theme-modes.test.ts +0 -42
  165. package/templates/apps/web/app/[locale]/(authed)/account/settings/theme-modes.ts +0 -40
  166. package/templates/apps/web/app/[locale]/(authed)/sign-in-gate.tsx +0 -162
  167. package/templates/apps/web/components/signed-in-nav.tsx +0 -79
  168. package/templates/apps/web/lib/hub-session/__tests__/sign-in-gate.test.tsx +0 -180
  169. package/templates/apps/web/lib/hub-session/sign-in-gate.tsx +0 -162
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Where the hub's set-password page returns a spoke's person (#11162).
3
+ *
4
+ * The link the hub mails for a spoke's Security tab lands on the hub's own
5
+ * `/reset-password` carrying `?ref=`: the spoke's REGISTERED origin (the
6
+ * hub API answered it from the client registry, never the spoke's request)
7
+ * and the Security tab's path, sealed under their own name so a continuation
8
+ * or a purchase claim never opens here and the reverse. The page opens the
9
+ * ref and sends a completed reset to the spoke's return route,
10
+ * `<origin>/api/hub-session/password/return?next=<path>`: saving a password
11
+ * ends every spoke credential (`onPasswordReset`), so the spoke drops its
12
+ * now-dead session there and the tab's gate shows the spoke's own sign-in,
13
+ * which brings the person back to the tab. A ref that does not open, or
14
+ * holds anything but an origin and a Security path, is ignored and the page
15
+ * falls back to the hub's sign-in — never to a URL it did not seal.
16
+ *
17
+ * The ref is opaque but not a secret: it carries only the two public facts.
18
+ * Nothing here logs one.
19
+ */
20
+ import { spokeSecurityReturnPathSchema } from "@working-theory/validation";
21
+
22
+ import { mintContinuation, openContinuation } from "../continuation";
23
+
24
+ /** The name the return is sealed under — never `hub-continue` or `hub-purchase`. */
25
+ export const SECURITY_RETURN_NAME = "hub-security-return";
26
+
27
+ /** Better Auth's `resetPasswordTokenExpiresIn` on this hub (`auth.ts`): the link's life. */
28
+ export const RESET_TOKEN_TTL_SECONDS = 3600;
29
+
30
+ /**
31
+ * The ref outlives the link by the time a person may spend on the page, so a
32
+ * link used in its last minutes still returns home.
33
+ */
34
+ export const SECURITY_RETURN_TTL_SECONDS = RESET_TOKEN_TTL_SECONDS + 600;
35
+
36
+ /** `origin` and `path` as a sealed return ref. */
37
+ export function mintSecurityReturn(
38
+ origin: string,
39
+ path: string,
40
+ secret: string,
41
+ now: number = Date.now(),
42
+ ): string {
43
+ return mintContinuation(
44
+ new URLSearchParams({ o: origin, p: path }).toString(),
45
+ secret,
46
+ now,
47
+ SECURITY_RETURN_NAME,
48
+ SECURITY_RETURN_TTL_SECONDS,
49
+ );
50
+ }
51
+
52
+ /** The spoke route a completed reset lands on, before the tab. */
53
+ export const SPOKE_RETURN_PATH = "/api/hub-session/password/return";
54
+
55
+ /**
56
+ * The absolute spoke URL a ref returns to — its return route carrying the
57
+ * Security path as `next` — or `null` when the ref does not open, has
58
+ * expired, or holds anything but an https (or loopback http) origin and a
59
+ * Security path.
60
+ */
61
+ export function openSecurityReturn(
62
+ ref: string,
63
+ secret: string,
64
+ now: number = Date.now(),
65
+ ): string | null {
66
+ const query = openContinuation(ref, secret, now, SECURITY_RETURN_NAME);
67
+ if (query === null) return null;
68
+ const params = new URLSearchParams(query);
69
+ const origin = params.get("o");
70
+ const path = params.get("p");
71
+ if (origin === null || path === null || [...params.keys()].length !== 2) return null;
72
+ if (!spokeSecurityReturnPathSchema.safeParse(path).success) return null;
73
+ let url: URL;
74
+ try {
75
+ url = new URL(origin);
76
+ } catch {
77
+ return null;
78
+ }
79
+ const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1";
80
+ if (url.origin !== origin || !(url.protocol === "https:" || (url.protocol === "http:" && loopback))) {
81
+ return null;
82
+ }
83
+ const landing = new URL(SPOKE_RETURN_PATH, origin);
84
+ landing.searchParams.set("next", path);
85
+ return landing.href;
86
+ }
@@ -0,0 +1,171 @@
1
+ /**
2
+ * `POST /api/auth/hub/password` — the hub web's half of a spoke-hosted Set /
3
+ * Change password (#11162).
4
+ *
5
+ * A spoke's server (never a browser) asks the hub to mail the person its
6
+ * Security tab signed in a link to set or change their one password. The
7
+ * person is named by their hub credential, never by an address in the body.
8
+ * In order:
9
+ *
10
+ * 1. `BETTER_AUTH_URL` pins the origin, else 503. Body ≤ 4 KB of JSON.
11
+ * 2. `hubPasswordEntryBodySchema` (`.strict()`): the client and its
12
+ * callback, the credential, the locale and the Security path to return
13
+ * to. Anything else — an `email` or a `password` among it — is 400.
14
+ * 3. A hub that cannot complete a reset (`resetSendConfigured()`) is 503
15
+ * here, before the API call — which charges the spoke's and the
16
+ * person's send budgets — and before anything is minted.
17
+ * 4. A caller refused ten times in ten minutes is 429 before any API call
18
+ * (`refusedCallerLimit`); a missing or non-`Basic` header is a refusal.
19
+ * The hub API's `POST /v1/hub-sign-in/password` authenticates the spoke
20
+ * with the `Authorization` and `x-ailk-spoke-key` it sent, as received,
21
+ * checks the callback is registered for it and the credential is a live
22
+ * grant of THIS client, and answers the person, their password state and
23
+ * the client's registered origin. A non-200 is passed on as its status
24
+ * with `{ error }`, and nothing is sent.
25
+ * 5. Better Auth's own `reset-password:<token>` row is written for the
26
+ * person (one hour, `resetPasswordTokenExpiresIn`), so the link is the
27
+ * one the hub's `/forgot-password` would mail and the hub's
28
+ * `/reset-password` page consumes it as any other. The credential's
29
+ * live session IS the person asking, so the anonymous-request guard
30
+ * `sendResetPassword` applies (#8431 D4) does not: a person with no
31
+ * password may set their first one from a spoke, as from the hub's tab.
32
+ * 6. The link's `callbackURL` is the hub's `/reset-password` under the
33
+ * body's locale carrying `?ref=`: the REGISTERED origin and the return
34
+ * path sealed (`./return.ts`), so a completed reset returns the person to
35
+ * the spoke's Security tab — never to a URL the spoke typed.
36
+ * 7. The `password-reset` email goes through the signed auth-email relay,
37
+ * as every reset mail does. A send that fails drops the row and is 503.
38
+ * 8. 202 `{ sent: true }`.
39
+ *
40
+ * Nothing here logs an email, a credential, a token or a ref — only the
41
+ * outcome. Under `app/api/auth`, a spoke removal seed, so no spoke carries it.
42
+ */
43
+ import { randomBytes } from "node:crypto";
44
+
45
+ import { authEmail, hubSignIn } from "@working-theory/api-client";
46
+ import { hubPasswordEntryBodySchema } from "@working-theory/validation";
47
+
48
+ import { auth } from "../../../../../auth";
49
+ import { buildAuthEmailRequest } from "../../../../../lib/auth-email";
50
+ import { resetSendConfigured } from "../../../../../lib/auth-env";
51
+ import { resolveSecret } from "../../../../../lib/auth-secret";
52
+ import { localeOfPath } from "../../../../../lib/hub-session/entry";
53
+ import { pinnedOrigin } from "../continuation";
54
+ import {
55
+ apiErrorCode,
56
+ forwardedClientAuth,
57
+ json,
58
+ noteRefusedCaller,
59
+ parseJson,
60
+ readRawBody,
61
+ refusedCallerLimit,
62
+ refuse,
63
+ } from "../entry-shared";
64
+
65
+ import { RESET_TOKEN_TTL_SECONDS, mintSecurityReturn } from "./return";
66
+
67
+ const DEFAULT_LOCALE = "en";
68
+
69
+ function log(outcome: string): void {
70
+ console.info(`[hub-password-link] ${JSON.stringify({ outcome })}`);
71
+ }
72
+
73
+ // platform-decisions-waiver: api-versioning — a hub sign-in step, not a versioned API contract (spec 11096 § 6)
74
+ export async function POST(request: Request): Promise<Response> {
75
+ const origin = pinnedOrigin();
76
+ if (origin === null) return refuse(503, "temporarily_unavailable");
77
+
78
+ const raw = await readRawBody(request);
79
+ if (raw === null) return refuse(400, "invalid_request");
80
+ const parsed = hubPasswordEntryBodySchema.safeParse(parseJson(raw));
81
+ if (!parsed.success) return refuse(400, "invalid_request");
82
+ const body = parsed.data;
83
+
84
+ // Before the API call, which charges the spoke's and the person's budgets.
85
+ // The relay secret the signing below needs is one of its conjuncts.
86
+ if (!resetSendConfigured()) {
87
+ log("reset_not_configured");
88
+ return refuse(503, "temporarily_unavailable");
89
+ }
90
+
91
+ const limited = refusedCallerLimit(request);
92
+ if (limited !== null) return limited;
93
+ const client = forwardedClientAuth(request);
94
+ if (client === null) {
95
+ noteRefusedCaller(request);
96
+ return refuse(401, "invalid_client");
97
+ }
98
+
99
+ let checked: Awaited<ReturnType<typeof hubSignIn.password>>;
100
+ try {
101
+ checked = await hubSignIn.password(client, {
102
+ clientId: body.client_id,
103
+ redirectUri: body.redirect_uri,
104
+ accessToken: body.access_token,
105
+ });
106
+ } catch {
107
+ return refuse(503, "temporarily_unavailable");
108
+ }
109
+ if (!checked.ok) {
110
+ if (checked.status === 401 || checked.status === 403) noteRefusedCaller(request);
111
+ return refuse(checked.status, apiErrorCode(checked.body, "invalid_request"));
112
+ }
113
+ const { user, origin: spokeOrigin } = checked.body;
114
+
115
+ const token = randomBytes(24).toString("base64url");
116
+ const identifier = `reset-password:${token}`;
117
+ // Better Auth's own base URL — the pinned origin plus its `/api/auth` path,
118
+ // as the library resolves it; `BETTER_AUTH_URL` alone is the bare origin.
119
+ let baseURL: string;
120
+ try {
121
+ const context = await auth.$context;
122
+ baseURL = context.baseURL;
123
+ await context.internalAdapter.createVerificationValue({
124
+ identifier,
125
+ value: user.id,
126
+ expiresAt: new Date(Date.now() + RESET_TOKEN_TTL_SECONDS * 1000),
127
+ });
128
+ } catch {
129
+ log("mint_failed");
130
+ return refuse(503, "temporarily_unavailable");
131
+ }
132
+
133
+ const locale = localeOfPath(`/${body.locale}`);
134
+ const page = new URL(`${locale === DEFAULT_LOCALE ? "" : `/${locale}`}/reset-password`, origin);
135
+ page.searchParams.set("ref", mintSecurityReturn(spokeOrigin, body.return_path, resolveSecret()));
136
+ // Better Auth's own link shape: its `/reset-password/:token` consumes the
137
+ // token's hour and redirects to `callbackURL` with `?token=`.
138
+ const url = `${baseURL}/reset-password/${token}?callbackURL=${encodeURIComponent(page.href)}`;
139
+
140
+ const mail = buildAuthEmailRequest(
141
+ {
142
+ kind: "password-reset",
143
+ userId: user.id,
144
+ to: user.email,
145
+ url,
146
+ expiresInMinutes: RESET_TOKEN_TTL_SECONDS / 60,
147
+ },
148
+ process.env.AUTH_EMAIL_WEBHOOK_SECRET ?? "",
149
+ );
150
+ let sent: boolean;
151
+ try {
152
+ const result = (await authEmail.send(mail.rawBody, mail.headers)) as { ok: boolean } | undefined;
153
+ sent = result?.ok !== false;
154
+ } catch {
155
+ sent = false;
156
+ }
157
+ if (!sent) {
158
+ // Not sent: drop the row, so the unused token never waits out its hour.
159
+ try {
160
+ const { internalAdapter } = await auth.$context;
161
+ await internalAdapter.deleteVerificationByIdentifier(identifier);
162
+ } catch {
163
+ // The row expires on its own; the person asks again.
164
+ }
165
+ log("send_failed");
166
+ return refuse(503, "temporarily_unavailable");
167
+ }
168
+
169
+ log("sent");
170
+ return json(202, { sent: true });
171
+ }
@@ -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
+ }