create-ailk 0.15.0 → 0.17.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 (128) hide show
  1. package/README.md +124 -0
  2. package/dist/add-module.js +52 -7
  3. package/dist/add-route.js +8 -0
  4. package/dist/adopt.d.ts +74 -0
  5. package/dist/adopt.js +314 -0
  6. package/dist/cli.js +82 -2
  7. package/dist/derive-architecture.d.ts +22 -0
  8. package/dist/derive-architecture.js +58 -1
  9. package/dist/lib/declared-env.d.ts +142 -0
  10. package/dist/lib/declared-env.js +985 -0
  11. package/dist/lib/env-catalog.d.ts +17 -0
  12. package/dist/lib/env-catalog.js +234 -0
  13. package/dist/lib/extract-module-bundle.d.ts +9 -0
  14. package/dist/lib/extract-module-bundle.js +18 -1
  15. package/dist/lib/module-tier.d.ts +2 -0
  16. package/dist/lib/module-tier.js +4 -0
  17. package/dist/module-architecture.js +76 -0
  18. package/dist/parse-args.d.ts +5 -0
  19. package/dist/parse-args.js +17 -1
  20. package/dist/programmatic.d.ts +8 -0
  21. package/dist/programmatic.js +78 -9
  22. package/dist/seed-flows.d.ts +65 -0
  23. package/dist/seed-flows.js +350 -0
  24. package/dist/site-manifest.d.ts +43 -0
  25. package/dist/site-manifest.js +98 -3
  26. package/dist/site-roster.d.ts +13 -0
  27. package/dist/site-roster.js +22 -8
  28. package/dist/spoke-checkout.d.ts +67 -0
  29. package/dist/spoke-checkout.js +562 -0
  30. package/dist/surfaces.js +7 -0
  31. package/dist/sync-routes.js +23 -8
  32. package/dist/topology.d.ts +124 -9
  33. package/dist/topology.js +451 -40
  34. package/package.json +3 -3
  35. package/templates/.env.example +10 -0
  36. package/templates/apps/api/CLAUDE.md +19 -4
  37. package/templates/apps/api/src/__tests__/factories/in-memory-prisma.ts +95 -16
  38. package/templates/apps/api/src/__tests__/openapi-keyless-hub.test.ts +122 -0
  39. package/templates/apps/api/src/__tests__/support/hub-sign-in-fake-db.ts +362 -0
  40. package/templates/apps/api/src/bin/spokes.ts +62 -1
  41. package/templates/apps/api/src/config/__tests__/hub-require-spoke-key.test.ts +75 -0
  42. package/templates/apps/api/src/config/index.ts +35 -0
  43. package/templates/apps/api/src/lib/__mocks__/prisma.ts +89 -0
  44. package/templates/apps/api/src/lib/__tests__/deliverable-asset-store.test.ts +66 -5
  45. package/templates/apps/api/src/lib/__tests__/hub-sign-in-store.test.ts +209 -0
  46. package/templates/apps/api/src/lib/__tests__/spoke-store.test.ts +20 -0
  47. package/templates/apps/api/src/lib/deliverable-asset-store.ts +24 -5
  48. package/templates/apps/api/src/lib/hub-sign-in-store.ts +419 -0
  49. package/templates/apps/api/src/lib/spoke-store.ts +25 -3
  50. package/templates/apps/api/src/middleware/__tests__/auth.hub-session-path.test.ts +310 -0
  51. package/templates/apps/api/src/middleware/auth.ts +126 -0
  52. package/templates/apps/api/src/routes/auth/__tests__/hub-sign-in.test.ts +483 -0
  53. package/templates/apps/api/src/routes/auth/hub-sign-in.ts +201 -0
  54. package/templates/apps/api/src/routes/leads/__tests__/index.test.ts +7 -0
  55. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-flow-checkout.test.ts +105 -0
  56. package/templates/apps/api/src/routes/webhooks/stripe.ts +72 -1
  57. package/templates/apps/api/src/server.ts +105 -0
  58. package/templates/apps/api/src/services/__tests__/deliverable-fulfillment.test.ts +4 -4
  59. package/templates/apps/api/src/services/__tests__/hub-sign-in.test.ts +854 -0
  60. package/templates/apps/api/src/services/__tests__/lead-routing.test.ts +293 -0
  61. package/templates/apps/api/src/services/__tests__/person.test.ts +553 -0
  62. package/templates/apps/api/src/services/hub-sign-in.ts +471 -0
  63. package/templates/apps/api/src/services/lead-routing.ts +131 -2
  64. package/templates/apps/api/src/services/person.ts +541 -0
  65. package/templates/apps/web/.env.example +58 -5
  66. package/templates/apps/web/app/[locale]/(auth)/sign-in/next-path.ts +0 -0
  67. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +206 -0
  68. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/page.test.tsx +256 -3
  69. package/templates/apps/web/app/[locale]/(authed)/account/account-data.ts +5 -8
  70. package/templates/apps/web/app/[locale]/(authed)/account/inbox/message/[id]/file/__tests__/route.test.ts +205 -0
  71. package/templates/apps/web/app/[locale]/(authed)/account/inbox/message/[id]/file/route.ts +82 -0
  72. package/templates/apps/web/app/[locale]/(authed)/account/settings/page.tsx +98 -29
  73. package/templates/apps/web/app/[locale]/(authed)/account/support-actions.ts +6 -3
  74. package/templates/apps/web/app/[locale]/(authed)/layout.tsx +19 -101
  75. package/templates/apps/web/app/[locale]/(authed)/signed-out-gate.generated.tsx +90 -0
  76. package/templates/apps/web/app/[locale]/layout.tsx +28 -15
  77. package/templates/apps/web/app/api/auth/hub/authorize/__tests__/route.test.ts +295 -0
  78. package/templates/apps/web/app/api/auth/hub/authorize/route.ts +156 -0
  79. package/templates/apps/web/app/api/hub-session/__tests__/routes.test.ts +341 -0
  80. package/templates/apps/web/app/api/hub-session/callback/route.ts +168 -0
  81. package/templates/apps/web/app/api/hub-session/sign-in/route.ts +76 -0
  82. package/templates/apps/web/app/api/hub-session/sign-out/route.ts +63 -0
  83. package/templates/apps/web/app/openapi.json/__tests__/route.test.ts +57 -24
  84. package/templates/apps/web/app/openapi.json/route.ts +3 -6
  85. package/templates/apps/web/auth.ts +29 -2
  86. package/templates/apps/web/components/sign-out-trigger.tsx +20 -1
  87. package/templates/apps/web/components/signed-in-nav.tsx +17 -3
  88. package/templates/apps/web/lib/__tests__/account-config.test.ts +5 -2
  89. package/templates/apps/web/lib/__tests__/listings-config.test.ts +83 -0
  90. package/templates/apps/web/lib/__tests__/listings.test.tsx +49 -0
  91. package/templates/apps/web/lib/__tests__/meeting-slugs.test.ts +49 -1
  92. package/templates/apps/web/lib/__tests__/relay.test.ts +33 -0
  93. package/templates/apps/web/lib/__tests__/server-api.test.ts +37 -28
  94. package/templates/apps/web/lib/account-config.ts +130 -1
  95. package/templates/apps/web/lib/api-origin.generated.ts +11 -0
  96. package/templates/apps/web/lib/hub-session/__tests__/hub-session.test.ts +262 -0
  97. package/templates/apps/web/lib/hub-session/config.ts +104 -0
  98. package/templates/apps/web/lib/hub-session/index.ts +23 -0
  99. package/templates/apps/web/lib/hub-session/seal.ts +82 -0
  100. package/templates/apps/web/lib/hub-session/session.ts +180 -0
  101. package/templates/apps/web/lib/hub-session/sign-in-gate.tsx +79 -0
  102. package/templates/apps/web/lib/listings-config.ts +31 -0
  103. package/templates/apps/web/lib/listings.tsx +7 -3
  104. package/templates/apps/web/lib/meeting-slugs.ts +11 -1
  105. package/templates/apps/web/lib/next-path.ts +35 -0
  106. package/templates/apps/web/lib/relay.ts +3 -1
  107. package/templates/apps/web/lib/server-api.ts +11 -1
  108. package/templates/apps/web/lib/topology.generated.ts +15 -5
  109. package/templates/apps/web/messages/en.json +32 -3
  110. package/templates/database/CHANGELOG.md +26 -0
  111. package/templates/database/__tests__/agents.db.test.ts +25 -5
  112. package/templates/database/__tests__/fixtures/person-backfill.json +264 -0
  113. package/templates/database/__tests__/member-area.db.test.ts +245 -0
  114. package/templates/database/__tests__/person.db.test.ts +584 -0
  115. package/templates/database/auth/schema.prisma +3 -2
  116. package/templates/database/config/schema.prisma +13 -0
  117. package/templates/database/inbox/schema.prisma +98 -0
  118. package/templates/database/migrations/20261010120000_person/migration.sql +106 -0
  119. package/templates/database/migrations/20261010121000_person_backfill/migration.sql +132 -0
  120. package/templates/database/migrations/20261010130000_agent_grants_people_read/migration.sql +20 -0
  121. package/templates/database/migrations/20261011120000_member_area/migration.sql +158 -0
  122. package/templates/database/migrations/20261011130000_agent_grants_member_pieces_manage/migration.sql +21 -0
  123. package/templates/database/package.json +1 -1
  124. package/templates/database/scripts/person-backfill.sql +132 -0
  125. package/templates/database/tenancy.ts +53 -0
  126. package/templates/tools/check-declared-env.ts +37 -0
  127. package/templates/tools/declared-env.ts +1163 -0
  128. package/versions.json +35 -35
@@ -0,0 +1,471 @@
1
+ /**
2
+ * The hub signs in its spokes — the service behind `routes/auth/hub-sign-in.ts`
3
+ * (#7894, spec docs/specs/7894-the-hub-signs-in-its-spec.md D2, D5).
4
+ *
5
+ * An authorization code with PKCE between a confidential client (a spoke) and
6
+ * its hub. Four operations:
7
+ *
8
+ * - `createCode` — a signed-in, email-verified person, a registered client
9
+ * and a registered callback mint a single-use 60 s code;
10
+ * - `exchange` — the client trades that code (plus its secret, its spoke
11
+ * key and the PKCE verifier) for a 24 h credential;
12
+ * - `revoke` — the client ends a credential, or burns a code it cannot
13
+ * complete;
14
+ * - `readMe` — the live read behind `GET /v1/hub-sign-in/me` (it may
15
+ * link the caller's Person, by the verified-email rule).
16
+ *
17
+ * Every refusal is a typed result, never a throw. The routes map a result to
18
+ * a status and an envelope; nothing here touches a request or a reply. No log
19
+ * line carries a code, a verifier, a secret, a credential or an email.
20
+ *
21
+ * WHAT STOPS A LEAKED CLIENT SECRET SIGNING SOMEBODY IN. The token route
22
+ * needs a code, and a code is minted only for a person who is signed in on the
23
+ * hub in a browser; the exchange then needs the PKCE verifier the spoke
24
+ * generated for that one flow, the client secret AND the spoke's own key. A
25
+ * secret alone mints nothing, a code alone mints nothing, and a credential is
26
+ * refused (at the preHandler) with any other spoke's key.
27
+ */
28
+ import { timingSafeEqual } from "node:crypto";
29
+
30
+ import { getClock } from "@working-theory/common";
31
+ import {
32
+ hubSignInCodeBodySchema,
33
+ hubSignInRevokeBodySchema,
34
+ hubSignInTokenBodySchema,
35
+ type HubSignInMeResponse,
36
+ type HubSignInRevokeResponse,
37
+ type HubSignInTokenResponse,
38
+ type HubSignInUser,
39
+ } from "@working-theory/validation";
40
+
41
+ import {
42
+ burnCode,
43
+ consumeCode,
44
+ deleteExpiredCodes,
45
+ findClientByClientId,
46
+ findSignInUser,
47
+ mintCode,
48
+ mintCredential,
49
+ revokeAuthorization,
50
+ sha256Hex,
51
+ upsertAuthorization,
52
+ writeCode,
53
+ type SignInClientRow,
54
+ type SignInUserRow,
55
+ } from "../lib/hub-sign-in-store.js";
56
+ import {
57
+ findSpokeById,
58
+ findSpokeByKeyHash,
59
+ hashSpokeKey,
60
+ } from "../lib/spoke-store.js";
61
+
62
+ import { resolveCallerBillingCustomerId } from "./person.js";
63
+
64
+ /** How long a code is valid: the browser redirect and the server exchange. */
65
+ export const CODE_TTL_MS = 60_000;
66
+
67
+ /** How long a credential is valid: 24 hours. */
68
+ export const CREDENTIAL_TTL_SECONDS = 86_400;
69
+
70
+ /** The per-user code budget (D5): 30 codes per 10 minutes. */
71
+ export const CODES_PER_USER = 30;
72
+ export const CODES_WINDOW_MS = 600_000;
73
+
74
+ /** The per-client exchange budget (D5): 120 exchanges per minute. */
75
+ export const EXCHANGES_PER_CLIENT = 120;
76
+ export const EXCHANGES_WINDOW_MS = 60_000;
77
+
78
+ /** Cap on distinct buckets per limiter — the oldest is evicted at capacity. */
79
+ const MAX_BUCKETS = 5_000;
80
+
81
+ export type ServiceStatus = 400 | 401 | 403 | 404 | 429;
82
+
83
+ export interface ServiceError {
84
+ status: ServiceStatus;
85
+ code: string;
86
+ message: string;
87
+ /** Seconds, on a 429. */
88
+ retryAfter?: number;
89
+ }
90
+
91
+ export type Result<T> =
92
+ { ok: true; value: T } | { ok: false; error: ServiceError };
93
+
94
+ function refuse<T = never>(
95
+ status: ServiceStatus,
96
+ code: string,
97
+ message: string,
98
+ retryAfter?: number,
99
+ ): Result<T> {
100
+ return {
101
+ ok: false,
102
+ error: {
103
+ status,
104
+ code,
105
+ message,
106
+ ...(retryAfter !== undefined ? { retryAfter } : {}),
107
+ },
108
+ };
109
+ }
110
+
111
+ // ── In-process fixed-window limiter, keyed on a VERIFIED identity ────────────
112
+ //
113
+ // In the service and not in an `onRequest` hook: a bucket must only ever be
114
+ // keyed on an identity the request has already proved (the user the cookie
115
+ // session resolved to; the client that passed secret AND spoke key), so an
116
+ // invented key never gets one (SEC-7894-8). The shape of `middleware/auth.ts`'s
117
+ // per-agent limiter. SINGLE-REPLICA, like every limiter in this app.
118
+
119
+ interface Bucket {
120
+ windowStartMs: number;
121
+ count: number;
122
+ }
123
+
124
+ interface WindowLimiter {
125
+ /** `undefined` when admitted; the seconds to wait when over budget. */
126
+ charge(key: string, now: number): number | undefined;
127
+ clear(): void;
128
+ }
129
+
130
+ function createWindowLimiter(limit: number, windowMs: number): WindowLimiter {
131
+ const buckets = new Map<string, Bucket>();
132
+
133
+ return {
134
+ charge(key, now) {
135
+ let bucket = buckets.get(key);
136
+ if (!bucket || now - bucket.windowStartMs >= windowMs) {
137
+ if (!buckets.has(key) && buckets.size >= MAX_BUCKETS) {
138
+ for (const [id, b] of buckets) {
139
+ if (now - b.windowStartMs >= windowMs) buckets.delete(id);
140
+ }
141
+ if (buckets.size >= MAX_BUCKETS) {
142
+ const oldest = buckets.keys().next().value;
143
+ if (oldest !== undefined) buckets.delete(oldest);
144
+ }
145
+ }
146
+ // Re-insert, so Map order stays oldest-window-first for the eviction.
147
+ buckets.delete(key);
148
+ bucket = { windowStartMs: now, count: 0 };
149
+ buckets.set(key, bucket);
150
+ }
151
+ bucket.count += 1;
152
+ if (bucket.count > limit) {
153
+ return Math.max(
154
+ 1,
155
+ Math.ceil((bucket.windowStartMs + windowMs - now) / 1_000),
156
+ );
157
+ }
158
+ return undefined;
159
+ },
160
+ clear() {
161
+ buckets.clear();
162
+ },
163
+ };
164
+ }
165
+
166
+ const codeLimiter = createWindowLimiter(CODES_PER_USER, CODES_WINDOW_MS);
167
+ const exchangeLimiter = createWindowLimiter(
168
+ EXCHANGES_PER_CLIENT,
169
+ EXCHANGES_WINDOW_MS,
170
+ );
171
+
172
+ /** Test-only reset. Not intended for production use. */
173
+ export function __resetHubSignInBuckets(): void {
174
+ codeLimiter.clear();
175
+ exchangeLimiter.clear();
176
+ }
177
+
178
+ // ── Shapes ───────────────────────────────────────────────────────────────────
179
+
180
+ function toWireUser(user: SignInUserRow): HubSignInUser {
181
+ return {
182
+ id: user.id,
183
+ name: user.name,
184
+ email: user.email,
185
+ emailVerified: user.emailVerified,
186
+ createdAt: user.createdAt.toISOString(),
187
+ };
188
+ }
189
+
190
+ // ── POST /v1/hub-sign-in/codes ───────────────────────────────────────────────
191
+
192
+ /**
193
+ * Mint a single-use code for a person the cookie session resolved. The caller
194
+ * (the route) has already refused every bearer; this is the cookie path only.
195
+ */
196
+ export async function createCode(params: {
197
+ userId: string;
198
+ body: unknown;
199
+ }): Promise<Result<{ code: string; redirectUri: string }>> {
200
+ const now = getClock().now();
201
+
202
+ const retryAfter = codeLimiter.charge(params.userId, now);
203
+ if (retryAfter !== undefined) {
204
+ return refuse(429, "rate_limited", "Too many requests", retryAfter);
205
+ }
206
+
207
+ const parsed = hubSignInCodeBodySchema.safeParse(params.body);
208
+ if (!parsed.success) {
209
+ return refuse(400, "invalid_request", "Invalid request");
210
+ }
211
+ const { clientId, redirectUri, codeChallenge } = parsed.data;
212
+
213
+ const client = await findClientByClientId(clientId);
214
+ if (!client || !client.enabled) {
215
+ return refuse(400, "invalid_client", "Unknown client");
216
+ }
217
+ // A client is a spoke's: a revoked spoke signs nobody in.
218
+ const spoke = await findSpokeById(client.clientId);
219
+ if (!spoke || spoke.revokedAt) {
220
+ return refuse(400, "invalid_client", "Unknown client");
221
+ }
222
+ // Exact match only — a callback not registered for this client is refused
223
+ // before anything is minted, and never redirected to.
224
+ if (!client.redirectUris.includes(redirectUri)) {
225
+ return refuse(400, "invalid_redirect_uri", "Redirect URI not registered");
226
+ }
227
+
228
+ const user = await findSignInUser(params.userId);
229
+ if (!user) return refuse(401, "unauthorized", "Authentication required");
230
+ if (user.emailVerified !== true) {
231
+ return refuse(403, "email_unverified", "Email address not verified");
232
+ }
233
+
234
+ const code = mintCode();
235
+ await writeCode({
236
+ code,
237
+ payload: {
238
+ userId: user.id,
239
+ clientId: client.clientId,
240
+ redirectUri,
241
+ codeChallenge,
242
+ },
243
+ expiresAt: new Date(now + CODE_TTL_MS),
244
+ });
245
+ return { ok: true, value: { code, redirectUri } };
246
+ }
247
+
248
+ // ── Client authentication (token and revoke) ─────────────────────────────────
249
+
250
+ const BASIC = /^Basic\s+([A-Za-z0-9+/]+={0,2})$/;
251
+
252
+ /** The stand-in compared against when the client is unknown, so timing is flat. */
253
+ const DUMMY_DIGEST = Buffer.alloc(32);
254
+
255
+ function parseBasic(
256
+ header: string | undefined,
257
+ ): { clientId: string; secret: string } | null {
258
+ if (!header) return null;
259
+ const match = BASIC.exec(header);
260
+ if (!match?.[1]) return null;
261
+ const decoded = Buffer.from(match[1], "base64").toString("utf8");
262
+ const colon = decoded.indexOf(":");
263
+ if (colon <= 0) return null;
264
+ const clientId = decoded.slice(0, colon);
265
+ const secret = decoded.slice(colon + 1);
266
+ if (!clientId || !secret) return null;
267
+ return { clientId, secret };
268
+ }
269
+
270
+ /**
271
+ * Authenticate a spoke as a sign-in client: the secret (compared as digests,
272
+ * constant time) AND its spoke key, which must resolve to an unrevoked spoke
273
+ * whose id is this client. Any failure is the one `401 invalid_client`.
274
+ */
275
+ async function authenticateClient(params: {
276
+ authorization: string | undefined;
277
+ spokeKey: string | undefined;
278
+ }): Promise<Result<SignInClientRow>> {
279
+ const failure = refuse<SignInClientRow>(
280
+ 401,
281
+ "invalid_client",
282
+ "Client authentication failed",
283
+ );
284
+
285
+ const basic = parseBasic(params.authorization);
286
+ if (!basic) return failure;
287
+
288
+ const client = await findClientByClientId(basic.clientId);
289
+
290
+ const provided = Buffer.from(sha256Hex(basic.secret), "hex");
291
+ const stored = client
292
+ ? Buffer.from(client.clientSecret, "hex")
293
+ : DUMMY_DIGEST;
294
+ const secretMatches =
295
+ stored.length === provided.length && timingSafeEqual(provided, stored);
296
+
297
+ const spokeKey = params.spokeKey?.trim();
298
+ const spoke = spokeKey
299
+ ? await findSpokeByKeyHash(hashSpokeKey(spokeKey)).catch(() => null)
300
+ : null;
301
+
302
+ if (
303
+ !client ||
304
+ !secretMatches ||
305
+ !client.enabled ||
306
+ !spoke ||
307
+ spoke.revokedAt ||
308
+ spoke.id !== client.clientId
309
+ ) {
310
+ return failure;
311
+ }
312
+ return { ok: true, value: client };
313
+ }
314
+
315
+ // ── POST /v1/hub-sign-in/token ───────────────────────────────────────────────
316
+
317
+ function base64urlSha256(value: string): string {
318
+ return Buffer.from(sha256Hex(value), "hex").toString("base64url");
319
+ }
320
+
321
+ /** True when two short strings are equal, in constant time. */
322
+ function safeEqual(a: string, b: string): boolean {
323
+ const left = Buffer.from(a);
324
+ const right = Buffer.from(b);
325
+ return left.length === right.length && timingSafeEqual(left, right);
326
+ }
327
+
328
+ /**
329
+ * Trade a single-use code for a 24 h credential (the token route). The order
330
+ * is the security argument:
331
+ *
332
+ * 1. authenticate the CLIENT — secret AND spoke key, or the one 401;
333
+ * 2. charge the per-client bucket (a verified identity only);
334
+ * 3. parse the body;
335
+ * 4. CONSUME the code — exactly once, before any check on it — so a failed
336
+ * verifier or a wrong callback also burns it;
337
+ * 5. only then check client, callback and PKCE, and the person's email;
338
+ * 6. mint the credential, stored only as a digest (one grant per person and
339
+ * spoke, so a new sign-in rotates the previous credential).
340
+ *
341
+ * Every failure after step 3 is the one `400 invalid_grant`.
342
+ */
343
+ export async function exchange(params: {
344
+ authorization: string | undefined;
345
+ spokeKey: string | undefined;
346
+ body: unknown;
347
+ }): Promise<Result<HubSignInTokenResponse>> {
348
+ const auth = await authenticateClient(params);
349
+ if (!auth.ok) return auth;
350
+ const client = auth.value;
351
+
352
+ const now = getClock().now();
353
+ const retryAfter = exchangeLimiter.charge(client.clientId, now);
354
+ if (retryAfter !== undefined) {
355
+ return refuse(429, "rate_limited", "Too many requests", retryAfter);
356
+ }
357
+
358
+ const parsed = hubSignInTokenBodySchema.safeParse(params.body);
359
+ if (!parsed.success) {
360
+ return refuse(400, "invalid_request", "Invalid request");
361
+ }
362
+ const { code, redirectUri, codeVerifier } = parsed.data;
363
+
364
+ const invalidGrant = () =>
365
+ refuse<HubSignInTokenResponse>(400, "invalid_grant", "Invalid grant");
366
+
367
+ // The code is consumed FIRST and exactly once — before any check — so a
368
+ // failed verifier or a wrong callback also burns it.
369
+ const row = await consumeCode(code);
370
+ if (!row || row.payload === null) return invalidGrant();
371
+ if (row.expiresAt.getTime() <= now) return invalidGrant();
372
+ const { payload } = row;
373
+ if (payload.clientId !== client.clientId) return invalidGrant();
374
+ if (payload.redirectUri !== redirectUri) return invalidGrant();
375
+ if (!safeEqual(base64urlSha256(codeVerifier), payload.codeChallenge)) {
376
+ return invalidGrant();
377
+ }
378
+
379
+ const user = await findSignInUser(payload.userId);
380
+ if (!user || user.emailVerified !== true) return invalidGrant();
381
+
382
+ const credential = mintCredential();
383
+ await upsertAuthorization({
384
+ userId: user.id,
385
+ clientRowId: client.id,
386
+ accessTokenHash: sha256Hex(credential),
387
+ expiresAt: new Date(now + CREDENTIAL_TTL_SECONDS * 1_000),
388
+ });
389
+ // Housekeeping: a failed sweep never fails a completed exchange.
390
+ await deleteExpiredCodes(new Date(now)).catch(() => undefined);
391
+
392
+ return {
393
+ ok: true,
394
+ value: {
395
+ accessToken: credential,
396
+ tokenType: "Bearer",
397
+ expiresIn: CREDENTIAL_TTL_SECONDS,
398
+ user: toWireUser(user),
399
+ },
400
+ };
401
+ }
402
+
403
+ // ── POST /v1/hub-sign-in/revoke ──────────────────────────────────────────────
404
+
405
+ /**
406
+ * End one of THIS client's credentials, or burn one of its unexpired codes
407
+ * (the spoke's callback burns every code it cannot complete, SEC-7894-4).
408
+ * Another client's credential or code is never touched. `{ revoked: false }`
409
+ * for a miss — never an error, so it is no oracle for what exists.
410
+ */
411
+ export async function revoke(params: {
412
+ authorization: string | undefined;
413
+ spokeKey: string | undefined;
414
+ body: unknown;
415
+ }): Promise<Result<HubSignInRevokeResponse>> {
416
+ const auth = await authenticateClient(params);
417
+ if (!auth.ok) return auth;
418
+ const client = auth.value;
419
+
420
+ const parsed = hubSignInRevokeBodySchema.safeParse(params.body);
421
+ if (!parsed.success) {
422
+ return refuse(400, "invalid_request", "Invalid request");
423
+ }
424
+
425
+ const now = new Date(getClock().now());
426
+ const revoked =
427
+ "accessToken" in parsed.data
428
+ ? await revokeAuthorization({
429
+ clientRowId: client.id,
430
+ accessTokenHash: sha256Hex(parsed.data.accessToken),
431
+ now,
432
+ })
433
+ : await burnCode({
434
+ code: parsed.data.code,
435
+ clientId: client.clientId,
436
+ now,
437
+ });
438
+ return { ok: true, value: { revoked } };
439
+ }
440
+
441
+ // ── GET /v1/hub-sign-in/me ───────────────────────────────────────────────────
442
+
443
+ /**
444
+ * The person a credential speaks for, read live, and the customer id the hub
445
+ * vouches for (D13): the `billingCustomerId` of the Person #852's service
446
+ * answers for the credential's spoke's workspace, only while that Person's
447
+ * `userId` is the caller, else `null`. It is read through `services/person.ts`
448
+ * and nowhere else (SEC-7894-6, -7). That service's one write applies here
449
+ * too: an unlinked Person whose email is the caller's verified email is linked
450
+ * to the caller on this read (`stampPersonUser`'s rule, as a member read does),
451
+ * and a refused link is logged under the member area's `member-person-stamp`
452
+ * event. The preHandler admitted the credential only for a verified email, so
453
+ * `user.email` is the verified address.
454
+ */
455
+ export async function readMe(
456
+ userId: string,
457
+ workspaceId: string,
458
+ log?: { warn: (obj: object, msg: string) => void },
459
+ ): Promise<Result<HubSignInMeResponse>> {
460
+ const user = await findSignInUser(userId);
461
+ if (!user) return refuse(404, "not_found", "Not found");
462
+ const billingCustomerId = user.emailVerified
463
+ ? await resolveCallerBillingCustomerId(
464
+ workspaceId,
465
+ user.id,
466
+ user.email,
467
+ log,
468
+ )
469
+ : null;
470
+ return { ok: true, value: { user: toWireUser(user), billingCustomerId } };
471
+ }
@@ -40,6 +40,29 @@
40
40
  * `(workspaceId, idempotencyKey)`, so a key can never reach another tenant's
41
41
  * row. `email`, `local` and `none` deliveries ignore the key: there is no
42
42
  * row to dedupe against. The key itself is never logged.
43
+ *
44
+ * PERSON (#852 D6). Before a `submit` writes its `Lead`, `findOrCreatePerson`
45
+ * (`services/person.ts`, the only Person creator) resolves the client of
46
+ * this workspace for the lead's email, and its id joins the create as
47
+ * `personId`. Lead capture is a never-gate surface, so the Person step never
48
+ * throws, never refuses the lead and never changes `routeLead`'s result: an
49
+ * unstorable address or a failed step writes the lead with `personId: null`
50
+ * and logs one bare line (`person-skipped` / `person-failed`, never the
51
+ * email). `subscribe` and `callback` create no Person; the `email`, `local`
52
+ * and `none` deliveries never reach `persistToDb`.
53
+ *
54
+ * CHECKOUT PLAN (#7877 D10). A spoke's checkout fulfilment posts one
55
+ * `submit` with the Checkout Session id as its `Idempotency-Key`. When that
56
+ * lead is written (never on a replay) with a Person, and it is a LIVE,
57
+ * paid checkout lead from a registered spoke's server — `viaSpoke`, a
58
+ * `cs_live_` key, `source: "web"`, `payload.page: "checkout"`, a string
59
+ * `payload.offering` and `payload.site`, and an `amountTotal` that is
60
+ * absent, `null` or a positive integer — the Person's plan becomes the
61
+ * offering minus a leading `<site>_` (`setPersonPlanOffering`, the plan's
62
+ * only writer). No spoke file changes. The step never throws, never changes
63
+ * `routeLead`'s result, and logs one bare `checkout-plan` line — never the
64
+ * offering, the email or the key. A lead that does not qualify makes no
65
+ * Person call at all.
43
66
  */
44
67
 
45
68
  import { randomUUID } from "node:crypto";
@@ -47,7 +70,12 @@ import { isDeepStrictEqual } from "node:util";
47
70
 
48
71
  import type { Prisma } from "@working-theory/database";
49
72
  import { sendLeadNotification } from "@working-theory/email";
50
- import { leadInputSchema } from "@working-theory/validation";
73
+ import { logger } from "@working-theory/observability";
74
+ import {
75
+ LEAD_SITE_MARKER_KEY,
76
+ leadInputSchema,
77
+ planOfferingSchema,
78
+ } from "@working-theory/validation";
51
79
 
52
80
  import { writeLeadFallback } from "../lib/file-fallback.js";
53
81
  import { appendLeadRecord } from "../lib/lead-capture-store.js";
@@ -55,6 +83,7 @@ import { acceptsKind, resolveLeadDelivery } from "../lib/lead-delivery.js";
55
83
  import { prisma } from "../lib/prisma.js";
56
84
 
57
85
  import { enrichLead } from "./enrichment-shim.js";
86
+ import { findOrCreatePerson, setPersonPlanOffering } from "./person.js";
58
87
  import { requestConfirmSupersedesNotification } from "./request-confirm.js";
59
88
 
60
89
  // ─── Types ────────────────────────────────────────────────────────────────────
@@ -216,11 +245,104 @@ type PersistResult =
216
245
  | { ok: "keyed"; outcome: KeyedOutcome }
217
246
  | { ok: false; error: string };
218
247
 
248
+ /**
249
+ * The Person of a submitted lead (#852 D6) — its id, or `null` when the email
250
+ * is not a storable address or the step failed. Never throws: a Person step
251
+ * must never refuse, lose or delay a lead. Logs the outcome kind and the
252
+ * site only.
253
+ */
254
+ async function resolveLeadPersonId(input: SubmitInput): Promise<string | null> {
255
+ try {
256
+ const name = typeof input.payload["name"] === "string" ? input.payload["name"] : null;
257
+ const person = await findOrCreatePerson(input.siteId, { email: input.email, name });
258
+ if (person.ok) return person.value.personId;
259
+ if (person.error.kind === "invalid_email") {
260
+ logger.warn(
261
+ { event: "person-skipped", kind: person.error.kind, siteId: input.siteId },
262
+ "lead person skipped",
263
+ );
264
+ } else {
265
+ logger.error({ event: "person-failed", siteId: input.siteId }, "lead person failed");
266
+ }
267
+ } catch {
268
+ logger.error({ event: "person-failed", siteId: input.siteId }, "lead person failed");
269
+ }
270
+ return null;
271
+ }
272
+
273
+ /** A LIVE-mode Checkout Session id (#7877 D10, SEC-7877-C). */
274
+ const LIVE_CHECKOUT_SESSION_KEY = /^cs_live_[A-Za-z0-9]{1,250}$/;
275
+ const SITE_SLUG = /^[a-z0-9][a-z0-9-]{0,39}$/;
276
+
277
+ /**
278
+ * The raw offering of a lead that qualifies for the checkout plan rule, or
279
+ * `null` when it does not (#7877 D10). Reads the lead's own fields only.
280
+ */
281
+ function checkoutPlanCandidate(
282
+ input: SubmitInput,
283
+ idempotencyKey: string | undefined,
284
+ viaSpoke: boolean,
285
+ ): { offering: string; site: string } | null {
286
+ if (viaSpoke !== true) return null;
287
+ if (idempotencyKey === undefined || !LIVE_CHECKOUT_SESSION_KEY.test(idempotencyKey)) {
288
+ return null;
289
+ }
290
+ const { payload } = input;
291
+ const amountTotal = payload["amountTotal"];
292
+ if (
293
+ amountTotal !== undefined &&
294
+ amountTotal !== null &&
295
+ !(typeof amountTotal === "number" && Number.isInteger(amountTotal) && amountTotal > 0)
296
+ ) {
297
+ return null;
298
+ }
299
+ if (input.source !== "web" || payload["page"] !== "checkout") return null;
300
+ const offering = payload["offering"];
301
+ const site = payload[LEAD_SITE_MARKER_KEY];
302
+ if (typeof offering !== "string" || typeof site !== "string" || !SITE_SLUG.test(site)) {
303
+ return null;
304
+ }
305
+ return { offering, site };
306
+ }
307
+
308
+ /**
309
+ * Set the Person's plan from a qualifying checkout lead (#7877 D10). Never
310
+ * throws and never changes the lead's result; logs the outcome kind and the
311
+ * site only.
312
+ */
313
+ async function applyCheckoutPlan(
314
+ input: SubmitInput,
315
+ personId: string,
316
+ candidate: { offering: string; site: string },
317
+ ): Promise<void> {
318
+ const prefix = `${candidate.site}_`;
319
+ const offering = candidate.offering.startsWith(prefix)
320
+ ? candidate.offering.slice(prefix.length)
321
+ : candidate.offering;
322
+ let outcome: "set" | "skipped" | "failed";
323
+ // The operator's PUT accepts the same keys (`planOfferingSchema`).
324
+ if (!planOfferingSchema.safeParse(offering).success) {
325
+ outcome = "skipped";
326
+ } else {
327
+ try {
328
+ const result = await setPersonPlanOffering(input.siteId, personId, offering);
329
+ outcome = result === "set" ? "set" : "failed";
330
+ } catch {
331
+ outcome = "failed";
332
+ }
333
+ }
334
+ const line = { event: "checkout-plan", outcome, siteId: input.siteId };
335
+ if (outcome === "failed") logger.error(line, "checkout plan failed");
336
+ else logger.info(line, "checkout plan");
337
+ }
338
+
219
339
  async function persistToDb(
220
340
  input: RouteLeadInput,
221
341
  idempotencyKey?: string,
342
+ viaSpoke = false,
222
343
  ): Promise<PersistResult> {
223
344
  if (input.kind === "submit") {
345
+ const personId = await resolveLeadPersonId(input);
224
346
  let row: DbRow;
225
347
  try {
226
348
  row = (await prisma.lead.create({
@@ -246,6 +368,8 @@ async function persistToDb(
246
368
  source: input.source,
247
369
  email: input.email,
248
370
  payload: input.payload as Prisma.InputJsonValue,
371
+ // #852 D6 — the Person `resolveLeadPersonId` found or created.
372
+ personId,
249
373
  ...(idempotencyKey !== undefined && { idempotencyKey }),
250
374
  },
251
375
  select: { id: true },
@@ -261,6 +385,11 @@ async function persistToDb(
261
385
  if (!winner) throw err;
262
386
  return { ok: "keyed", outcome: classifyKeyedRow(winner, input) };
263
387
  }
388
+ // #7877 D10 — only after THIS request's own write, so a replay sets nothing.
389
+ const candidate = checkoutPlanCandidate(input, idempotencyKey, viaSpoke);
390
+ if (candidate !== null && personId !== null) {
391
+ await applyCheckoutPlan(input, personId, candidate);
392
+ }
264
393
  return { ok: true, id: row.id, source: "db", skipEmail: false };
265
394
  }
266
395
 
@@ -600,7 +729,7 @@ export async function routeLead(
600
729
  let skipReason: string | undefined;
601
730
 
602
731
  try {
603
- const dbResult = await persistToDb(input, idempotencyKey);
732
+ const dbResult = await persistToDb(input, idempotencyKey, sourceMeta.viaSpoke === true);
604
733
  // #7869 D5 — a lost race answers like the lookup above: no capture
605
734
  // record, no notification.
606
735
  if (dbResult.ok === "keyed") return keyedResult(dbResult.outcome);