create-ailk 0.14.0 → 0.16.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 (184) hide show
  1. package/README.md +124 -0
  2. package/component-catalog.json +3 -3
  3. package/dist/add-module.d.ts +7 -0
  4. package/dist/add-module.js +80 -3
  5. package/dist/add-route.js +26 -2
  6. package/dist/adopt.d.ts +74 -0
  7. package/dist/adopt.js +314 -0
  8. package/dist/apply-design.d.ts +12 -1
  9. package/dist/apply-design.js +36 -4
  10. package/dist/cli.js +103 -3
  11. package/dist/derive-architecture.d.ts +37 -2
  12. package/dist/derive-architecture.js +92 -7
  13. package/dist/design-package.js +3 -2
  14. package/dist/index.d.ts +1 -1
  15. package/dist/index.js +1 -1
  16. package/dist/lib/chrome-readers.d.ts +21 -0
  17. package/dist/lib/chrome-readers.js +100 -0
  18. package/dist/lib/declared-env.d.ts +142 -0
  19. package/dist/lib/declared-env.js +985 -0
  20. package/dist/lib/env-catalog.d.ts +17 -0
  21. package/dist/lib/env-catalog.js +234 -0
  22. package/dist/lib/extract-module-bundle.d.ts +20 -0
  23. package/dist/lib/extract-module-bundle.js +53 -6
  24. package/dist/lib/license-key-files.d.ts +6 -1
  25. package/dist/lib/license-key-files.js +9 -4
  26. package/dist/lib/module-tier.d.ts +2 -0
  27. package/dist/lib/module-tier.js +4 -0
  28. package/dist/module-architecture.d.ts +9 -0
  29. package/dist/module-architecture.js +82 -0
  30. package/dist/parse-args.d.ts +27 -0
  31. package/dist/parse-args.js +89 -0
  32. package/dist/programmatic.d.ts +28 -0
  33. package/dist/programmatic.js +181 -11
  34. package/dist/seed-flows.d.ts +65 -0
  35. package/dist/seed-flows.js +350 -0
  36. package/dist/site-chrome.d.ts +4 -0
  37. package/dist/site-chrome.js +34 -3
  38. package/dist/site-manifest.d.ts +55 -5
  39. package/dist/site-manifest.js +121 -12
  40. package/dist/site-roster.d.ts +13 -0
  41. package/dist/site-roster.js +22 -8
  42. package/dist/spoke-checkout.d.ts +42 -0
  43. package/dist/spoke-checkout.js +359 -0
  44. package/dist/surfaces.js +7 -0
  45. package/dist/sync-routes.js +29 -5
  46. package/dist/topology.d.ts +246 -0
  47. package/dist/topology.js +942 -0
  48. package/package.json +3 -3
  49. package/site-templates/designs/minimalism/DESIGN.md +3 -3
  50. package/templates/.env.example +10 -0
  51. package/templates/apps/api/CLAUDE.md +21 -4
  52. package/templates/apps/api/package.json +1 -0
  53. package/templates/apps/api/src/__tests__/factories/agent-caller.ts +5 -1
  54. package/templates/apps/api/src/__tests__/factories/in-memory-prisma.ts +95 -16
  55. package/templates/apps/api/src/__tests__/openapi-keyless-hub.test.ts +122 -0
  56. package/templates/apps/api/src/__tests__/support/hub-sign-in-fake-db.ts +362 -0
  57. package/templates/apps/api/src/bin/spokes.ts +62 -1
  58. package/templates/apps/api/src/config/__tests__/hub-require-spoke-key.test.ts +75 -0
  59. package/templates/apps/api/src/config/index.ts +35 -0
  60. package/templates/apps/api/src/lib/__mocks__/prisma.ts +99 -0
  61. package/templates/apps/api/src/lib/__tests__/agent-store.test.ts +114 -1
  62. package/templates/apps/api/src/lib/__tests__/deliverable-asset-store.test.ts +66 -5
  63. package/templates/apps/api/src/lib/__tests__/hub-sign-in-store.test.ts +209 -0
  64. package/templates/apps/api/src/lib/__tests__/site.test.ts +54 -0
  65. package/templates/apps/api/src/lib/__tests__/spoke-store.test.ts +20 -0
  66. package/templates/apps/api/src/lib/agent-store.ts +95 -3
  67. package/templates/apps/api/src/lib/deliverable-asset-store.ts +24 -5
  68. package/templates/apps/api/src/lib/hub-sign-in-store.ts +419 -0
  69. package/templates/apps/api/src/lib/site.ts +37 -0
  70. package/templates/apps/api/src/lib/spoke-store.ts +41 -3
  71. package/templates/apps/api/src/middleware/__tests__/auth.bearer-path.test.ts +4 -0
  72. package/templates/apps/api/src/middleware/__tests__/auth.hub-session-path.test.ts +310 -0
  73. package/templates/apps/api/src/middleware/__tests__/default-tenant.test.ts +22 -0
  74. package/templates/apps/api/src/middleware/auth.ts +129 -0
  75. package/templates/apps/api/src/openapi/__tests__/openapi.test.ts +23 -0
  76. package/templates/apps/api/src/openapi/spec.ts +38 -2
  77. package/templates/apps/api/src/routes/auth/__tests__/hub-sign-in.test.ts +483 -0
  78. package/templates/apps/api/src/routes/auth/hub-sign-in.ts +201 -0
  79. package/templates/apps/api/src/routes/checkout/__tests__/sessions.test.ts +50 -2
  80. package/templates/apps/api/src/routes/checkout/sessions.ts +7 -0
  81. package/templates/apps/api/src/routes/leads/__tests__/index.test.ts +282 -0
  82. package/templates/apps/api/src/routes/leads/index.ts +69 -6
  83. package/templates/apps/api/src/routes/webhooks/README.md +39 -0
  84. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-flow-checkout.test.ts +105 -0
  85. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-site-filter.test.ts +366 -0
  86. package/templates/apps/api/src/routes/webhooks/stripe.ts +133 -2
  87. package/templates/apps/api/src/server.ts +105 -0
  88. package/templates/apps/api/src/services/__tests__/deliverable-fulfillment.test.ts +4 -4
  89. package/templates/apps/api/src/services/__tests__/hub-sign-in.test.ts +854 -0
  90. package/templates/apps/api/src/services/__tests__/lead-routing.test.ts +492 -0
  91. package/templates/apps/api/src/services/__tests__/person.test.ts +553 -0
  92. package/templates/apps/api/src/services/default-tenant.ts +41 -7
  93. package/templates/apps/api/src/services/hub-sign-in.ts +471 -0
  94. package/templates/apps/api/src/services/lead-routing.ts +278 -30
  95. package/templates/apps/api/src/services/person.ts +541 -0
  96. package/templates/apps/api/src/services/public-site-resolver.ts +48 -0
  97. package/templates/apps/mcp/__tests__/index.test.ts +5 -5
  98. package/templates/apps/mcp/src/index.ts +6 -4
  99. package/templates/apps/mcp/src/lib/content-adapter.ts +2 -2
  100. package/templates/apps/mcp/src/lib/topology.generated.ts +24 -0
  101. package/templates/apps/web/.env.example +58 -5
  102. package/templates/apps/web/CLAUDE.md +1 -0
  103. package/templates/apps/web/app/[locale]/(auth)/sign-in/next-path.ts +0 -0
  104. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +206 -0
  105. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/page.test.tsx +256 -3
  106. package/templates/apps/web/app/[locale]/(authed)/account/account-data.ts +5 -8
  107. package/templates/apps/web/app/[locale]/(authed)/account/inbox/message/[id]/file/__tests__/route.test.ts +205 -0
  108. package/templates/apps/web/app/[locale]/(authed)/account/inbox/message/[id]/file/route.ts +82 -0
  109. package/templates/apps/web/app/[locale]/(authed)/account/settings/page.tsx +98 -29
  110. package/templates/apps/web/app/[locale]/(authed)/account/support-actions.ts +6 -3
  111. package/templates/apps/web/app/[locale]/(authed)/layout.tsx +19 -101
  112. package/templates/apps/web/app/[locale]/(authed)/signed-out-gate.generated.tsx +90 -0
  113. package/templates/apps/web/app/[locale]/[slug]/[detail]/__tests__/page.test.tsx +3 -0
  114. package/templates/apps/web/app/[locale]/[slug]/__tests__/page.test.tsx +3 -0
  115. package/templates/apps/web/app/[locale]/contact/__tests__/page-renderer-migration.test.tsx +66 -14
  116. package/templates/apps/web/app/[locale]/contact/__tests__/site-contact-lines.test.ts +105 -11
  117. package/templates/apps/web/app/[locale]/contact/site-contact-lines.ts +12 -8
  118. package/templates/apps/web/app/[locale]/layout.tsx +83 -18
  119. package/templates/apps/web/app/[locale]/newsletter/__tests__/page.test.tsx +3 -0
  120. package/templates/apps/web/app/[locale]/projects/__tests__/page-renderer-migration.test.tsx +5 -2
  121. package/templates/apps/web/app/[locale]/thanks/[slug]/__tests__/page.test.tsx +3 -0
  122. package/templates/apps/web/app/api/auth/hub/authorize/__tests__/route.test.ts +295 -0
  123. package/templates/apps/web/app/api/auth/hub/authorize/route.ts +156 -0
  124. package/templates/apps/web/app/api/hub-session/__tests__/routes.test.ts +341 -0
  125. package/templates/apps/web/app/api/hub-session/callback/route.ts +168 -0
  126. package/templates/apps/web/app/api/hub-session/sign-in/route.ts +76 -0
  127. package/templates/apps/web/app/api/hub-session/sign-out/route.ts +63 -0
  128. package/templates/apps/web/app/openapi.json/__tests__/route.test.ts +104 -1
  129. package/templates/apps/web/app/openapi.json/route.ts +72 -7
  130. package/templates/apps/web/auth.ts +29 -2
  131. package/templates/apps/web/components/sign-out-trigger.tsx +20 -1
  132. package/templates/apps/web/components/signed-in-nav.tsx +17 -3
  133. package/templates/apps/web/instrumentation.ts +7 -4
  134. package/templates/apps/web/lib/__tests__/account-config.test.ts +5 -2
  135. package/templates/apps/web/lib/__tests__/closing-footer-path.test.ts +96 -0
  136. package/templates/apps/web/lib/__tests__/listings-config.test.ts +83 -0
  137. package/templates/apps/web/lib/__tests__/listings.test.tsx +49 -0
  138. package/templates/apps/web/lib/__tests__/meeting-slugs.test.ts +49 -1
  139. package/templates/apps/web/lib/__tests__/relay.test.ts +317 -0
  140. package/templates/apps/web/lib/__tests__/site-brand.test.ts +52 -0
  141. package/templates/apps/web/lib/account-config.ts +130 -1
  142. package/templates/apps/web/lib/api-origin.generated.ts +11 -0
  143. package/templates/apps/web/lib/closing-footer-path.ts +50 -0
  144. package/templates/apps/web/lib/hub-session/__tests__/hub-session.test.ts +262 -0
  145. package/templates/apps/web/lib/hub-session/config.ts +104 -0
  146. package/templates/apps/web/lib/hub-session/index.ts +23 -0
  147. package/templates/apps/web/lib/hub-session/seal.ts +82 -0
  148. package/templates/apps/web/lib/hub-session/session.ts +180 -0
  149. package/templates/apps/web/lib/hub-session/sign-in-gate.tsx +79 -0
  150. package/templates/apps/web/lib/listings-config.ts +31 -0
  151. package/templates/apps/web/lib/listings.tsx +7 -3
  152. package/templates/apps/web/lib/meeting-slugs.ts +11 -1
  153. package/templates/apps/web/lib/next-path.ts +35 -0
  154. package/templates/apps/web/lib/relay.ts +209 -3
  155. package/templates/apps/web/lib/server-api.ts +11 -1
  156. package/templates/apps/web/lib/site-brand.tsx +22 -1
  157. package/templates/apps/web/lib/site-chrome.ts +3 -0
  158. package/templates/apps/web/lib/topology.generated.ts +33 -0
  159. package/templates/apps/web/messages/en.json +32 -3
  160. package/templates/apps/web/package.json +1 -1
  161. package/templates/database/CHANGELOG.md +51 -0
  162. package/templates/database/__tests__/agents.db.test.ts +85 -0
  163. package/templates/database/__tests__/fixtures/person-backfill.json +264 -0
  164. package/templates/database/__tests__/lead-idempotency-key.db.test.ts +92 -0
  165. package/templates/database/__tests__/member-area.db.test.ts +245 -0
  166. package/templates/database/__tests__/person.db.test.ts +584 -0
  167. package/templates/database/auth/schema.prisma +24 -0
  168. package/templates/database/config/schema.prisma +13 -0
  169. package/templates/database/inbox/schema.prisma +111 -0
  170. package/templates/database/jest.config.cjs +7 -11
  171. package/templates/database/migrations/20261008120000_user_last_workspace/migration.sql +35 -0
  172. package/templates/database/migrations/20261008130000_lead_idempotency_key/migration.sql +20 -0
  173. package/templates/database/migrations/20261009120000_agent_grants/migration.sql +33 -0
  174. package/templates/database/migrations/20261010120000_person/migration.sql +106 -0
  175. package/templates/database/migrations/20261010121000_person_backfill/migration.sql +132 -0
  176. package/templates/database/migrations/20261010130000_agent_grants_people_read/migration.sql +20 -0
  177. package/templates/database/migrations/20261011120000_member_area/migration.sql +158 -0
  178. package/templates/database/migrations/20261011130000_agent_grants_member_pieces_manage/migration.sql +21 -0
  179. package/templates/database/package.json +1 -1
  180. package/templates/database/scripts/person-backfill.sql +132 -0
  181. package/templates/database/tenancy.ts +53 -0
  182. package/templates/tools/check-declared-env.ts +37 -0
  183. package/templates/tools/declared-env.ts +1163 -0
  184. package/versions.json +35 -34
@@ -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
+ }