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,419 @@
1
+ /**
2
+ * The hub's sign-in-client store — the ONE data-access boundary for a spoke's
3
+ * sign-in (#7894, spec docs/specs/7894-the-hub-signs-in-its-spec.md D3, D5, D6).
4
+ *
5
+ * A spoke signs its visitors in through this hub: the hub is the OAuth-style
6
+ * provider and each spoke a confidential client. This file is the only one in
7
+ * `apps/api` that names `prisma.oAuthClient` and `prisma.oAuthAuthorization`
8
+ * (the web app's `onPasswordReset` is the one other writer, through the Better
9
+ * Auth Prisma client it already holds). It also owns the short-lived
10
+ * authorization-code rows, which live in `Verification` — the table Better
11
+ * Auth already keeps short-lived, single-use secrets in.
12
+ *
13
+ * A SPOKE'S CLIENT IS ITS `Spoke` ROW'S ID. `OAuthClient.clientId` equals the
14
+ * `Spoke.id` it serves, so the binding is by value and no column is added.
15
+ * `OAuthAuthorization.clientId` is the FK to the client row's own `id`
16
+ * (`oauthc_…`), not to the public `clientId`.
17
+ *
18
+ * NOTHING SECRET IS STORED IN CLEAR. The client secret, every code and every
19
+ * credential are kept as lowercase hex SHA-256 digests: each carries 256 bits
20
+ * of entropy, so a fast digest of a lookup key leaks nothing usable.
21
+ *
22
+ * Three kinds of caller, kept apart:
23
+ * - the service (`services/hub-sign-in.ts`) calls the client reads, the code
24
+ * functions and the authorization writes;
25
+ * - the preHandler branch (`middleware/auth.ts`) calls
26
+ * `findAuthorizationByCredentialHash` only;
27
+ * - the operator CLI (`bin/spokes.ts`) calls `upsertSignInClient` and
28
+ * `disableSignInClient` only. No route imports those two.
29
+ *
30
+ * Nothing here caches a row: a revocation takes effect on the next request.
31
+ */
32
+ import { createHash, randomBytes } from "node:crypto";
33
+
34
+ import { prisma } from "./prisma.js";
35
+ import { findSpokeById } from "./spoke-store.js";
36
+
37
+ /** Every hub-issued credential starts with this, so a leaked one is recognisable. */
38
+ export const HUB_SESSION_PREFIX = "ailk_hst_";
39
+
40
+ /** Every sign-in client secret starts with this. */
41
+ export const HUB_CLIENT_SECRET_PREFIX = "ailk_hcs_";
42
+
43
+ /** The scope a spoke credential carries: the signed-in person's account area. */
44
+ export const HUB_SIGN_IN_SCOPE = "account";
45
+
46
+ /** The `Verification.identifier` prefix of an authorization-code row. */
47
+ const CODE_IDENTIFIER_PREFIX = "hub-sign-in-code:";
48
+
49
+ /** Lowercase hex SHA-256 — the stored form of every secret here. */
50
+ export function sha256Hex(value: string): string {
51
+ return createHash("sha256").update(value).digest("hex");
52
+ }
53
+
54
+ /** 32 random bytes in base64url (43 characters). */
55
+ function randomToken(): string {
56
+ return randomBytes(32).toString("base64url");
57
+ }
58
+
59
+ /** A new authorization code. */
60
+ export function mintCode(): string {
61
+ return randomToken();
62
+ }
63
+
64
+ /** A new credential: `ailk_hst_` + 32 random bytes in base64url. */
65
+ export function mintCredential(): string {
66
+ return `${HUB_SESSION_PREFIX}${randomToken()}`;
67
+ }
68
+
69
+ /** A new client secret: `ailk_hcs_` + 32 random bytes in base64url. */
70
+ export function mintClientSecret(): string {
71
+ return `${HUB_CLIENT_SECRET_PREFIX}${randomToken()}`;
72
+ }
73
+
74
+ // ── The client ───────────────────────────────────────────────────────────────
75
+
76
+ export interface SignInClientRow {
77
+ /** The row's own id (`oauthc_…`) — what an authorization's FK points at. */
78
+ id: string;
79
+ /** The public identifier: the `Spoke.id` this client serves. */
80
+ clientId: string;
81
+ /** SHA-256 hex of the client secret. */
82
+ clientSecret: string;
83
+ redirectUris: string[];
84
+ enabled: boolean;
85
+ }
86
+
87
+ const CLIENT_SELECT = {
88
+ id: true,
89
+ clientId: true,
90
+ clientSecret: true,
91
+ redirectUris: true,
92
+ enabled: true,
93
+ } as const;
94
+
95
+ /** The client for one spoke, or `null`. */
96
+ export async function findClientByClientId(
97
+ clientId: string,
98
+ ): Promise<SignInClientRow | null> {
99
+ return prisma.oAuthClient.findUnique({
100
+ where: { clientId },
101
+ select: CLIENT_SELECT,
102
+ });
103
+ }
104
+
105
+ /**
106
+ * Create or update a spoke's sign-in client (the operator CLI). Re-running
107
+ * rotates the secret: `clientSecret` is replaced by the new digest, so the
108
+ * previous secret stops working at once. Returns nothing secret — the CALLER
109
+ * minted `secret` and prints it once.
110
+ */
111
+ export async function upsertSignInClient(params: {
112
+ spokeId: string;
113
+ name: string;
114
+ redirectUri: string;
115
+ secret: string;
116
+ }): Promise<void> {
117
+ const data = {
118
+ name: params.name,
119
+ clientSecret: sha256Hex(params.secret),
120
+ redirectUris: [params.redirectUri],
121
+ scopes: [HUB_SIGN_IN_SCOPE],
122
+ trusted: true,
123
+ enabled: true,
124
+ };
125
+ await prisma.oAuthClient.upsert({
126
+ where: { clientId: params.spokeId },
127
+ create: { clientId: params.spokeId, ...data },
128
+ update: data,
129
+ });
130
+ }
131
+
132
+ /** The one path a spoke's sign-in callback lives at (spec 7894 D3, D7). */
133
+ export const HUB_CALLBACK_PATH = "/api/hub-session/callback";
134
+
135
+ const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1"]);
136
+
137
+ /**
138
+ * Validate a callback URL an operator registers for a spoke (D3): `https:`
139
+ * (or `http:` on a loopback host), the path EXACTLY `/api/hub-session/callback`,
140
+ * and no query, fragment or userinfo. Returns the canonical origin + path the
141
+ * spoke will send back, or `null`.
142
+ */
143
+ export function canonicalRedirectUri(raw: string): string | null {
144
+ let url: URL;
145
+ try {
146
+ url = new URL(raw);
147
+ } catch {
148
+ return null;
149
+ }
150
+ const secure =
151
+ url.protocol === "https:" ||
152
+ (url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname));
153
+ if (!secure) return null;
154
+ if (url.pathname !== HUB_CALLBACK_PATH) return null;
155
+ if (url.search !== "" || url.hash !== "") return null;
156
+ // `URL` drops an empty `?` / `#`, so the raw text is checked too.
157
+ if (raw.includes("?") || raw.includes("#")) return null;
158
+ if (url.username !== "" || url.password !== "") return null;
159
+ return `${url.origin}${HUB_CALLBACK_PATH}`;
160
+ }
161
+
162
+ export type RegisterSignInClientResult =
163
+ | { ok: true; spokeId: string; secret: string }
164
+ | { ok: false; reason: "invalid-redirect-uri" | "spoke-not-found" | "spoke-revoked" };
165
+
166
+ /**
167
+ * The operator CLI's `sign-in-client` (D3): refuse an invalid callback, an
168
+ * unknown spoke or a revoked one; otherwise upsert the client and return the
169
+ * freshly minted secret, which the caller prints ONCE. Re-running rotates it.
170
+ */
171
+ export async function registerSignInClient(params: {
172
+ spokeId: string;
173
+ redirectUri: string;
174
+ }): Promise<RegisterSignInClientResult> {
175
+ const redirectUri = canonicalRedirectUri(params.redirectUri);
176
+ if (redirectUri === null) return { ok: false, reason: "invalid-redirect-uri" };
177
+
178
+ const spoke = await findSpokeById(params.spokeId);
179
+ if (!spoke) return { ok: false, reason: "spoke-not-found" };
180
+ if (spoke.revokedAt) return { ok: false, reason: "spoke-revoked" };
181
+
182
+ const secret = mintClientSecret();
183
+ await upsertSignInClient({
184
+ spokeId: spoke.id,
185
+ name: spoke.name,
186
+ redirectUri,
187
+ secret,
188
+ });
189
+ return { ok: true, spokeId: spoke.id, secret };
190
+ }
191
+
192
+ /** Switch a spoke's client off. `false` when it has none. */
193
+ export async function disableSignInClient(spokeId: string): Promise<boolean> {
194
+ const { count } = await prisma.oAuthClient.updateMany({
195
+ where: { clientId: spokeId },
196
+ data: { enabled: false },
197
+ });
198
+ return count === 1;
199
+ }
200
+
201
+ // ── The person ───────────────────────────────────────────────────────────────
202
+
203
+ export interface SignInUserRow {
204
+ id: string;
205
+ name: string | null;
206
+ email: string;
207
+ emailVerified: boolean;
208
+ createdAt: Date;
209
+ }
210
+
211
+ const USER_SELECT = {
212
+ id: true,
213
+ name: true,
214
+ email: true,
215
+ emailVerified: true,
216
+ createdAt: true,
217
+ } as const;
218
+
219
+ /** The five fields a credential speaks for, read live. */
220
+ export async function findSignInUser(
221
+ userId: string,
222
+ ): Promise<SignInUserRow | null> {
223
+ return prisma.user.findUnique({
224
+ where: { id: userId },
225
+ select: USER_SELECT,
226
+ });
227
+ }
228
+
229
+ // ── Authorization codes (`Verification` rows) ────────────────────────────────
230
+
231
+ export interface CodePayload {
232
+ userId: string;
233
+ clientId: string;
234
+ redirectUri: string;
235
+ codeChallenge: string;
236
+ }
237
+
238
+ export interface CodeRow {
239
+ id: string;
240
+ expiresAt: Date;
241
+ payload: CodePayload | null;
242
+ }
243
+
244
+ function codeIdentifier(code: string): string {
245
+ return `${CODE_IDENTIFIER_PREFIX}${sha256Hex(code)}`;
246
+ }
247
+
248
+ /** Store one single-use code, valid until `expiresAt`. */
249
+ export async function writeCode(params: {
250
+ code: string;
251
+ payload: CodePayload;
252
+ expiresAt: Date;
253
+ }): Promise<void> {
254
+ await prisma.verification.create({
255
+ data: {
256
+ identifier: codeIdentifier(params.code),
257
+ value: JSON.stringify(params.payload),
258
+ expiresAt: params.expiresAt,
259
+ },
260
+ });
261
+ }
262
+
263
+ function parsePayload(value: string): CodePayload | null {
264
+ try {
265
+ const parsed: unknown = JSON.parse(value);
266
+ if (typeof parsed !== "object" || parsed === null) return null;
267
+ const { userId, clientId, redirectUri, codeChallenge } = parsed as Record<
268
+ string,
269
+ unknown
270
+ >;
271
+ if (
272
+ typeof userId === "string" &&
273
+ typeof clientId === "string" &&
274
+ typeof redirectUri === "string" &&
275
+ typeof codeChallenge === "string"
276
+ ) {
277
+ return { userId, clientId, redirectUri, codeChallenge };
278
+ }
279
+ return null;
280
+ } catch {
281
+ return null;
282
+ }
283
+ }
284
+
285
+ async function findCodeRow(code: string): Promise<CodeRow | null> {
286
+ const row = await prisma.verification.findFirst({
287
+ where: { identifier: codeIdentifier(code) },
288
+ select: { id: true, value: true, expiresAt: true },
289
+ });
290
+ if (!row) return null;
291
+ return {
292
+ id: row.id,
293
+ expiresAt: row.expiresAt,
294
+ payload: parsePayload(row.value),
295
+ };
296
+ }
297
+
298
+ /**
299
+ * Consume a code exactly once: read its row, then delete it by id and require
300
+ * a count of 1. Two concurrent exchanges of one code both read it, but only
301
+ * the one whose `deleteMany` removes the row gets it. `null` for an unknown
302
+ * code or a lost race — the code is gone either way.
303
+ */
304
+ export async function consumeCode(code: string): Promise<CodeRow | null> {
305
+ const row = await findCodeRow(code);
306
+ if (!row) return null;
307
+ const { count } = await prisma.verification.deleteMany({
308
+ where: { id: row.id },
309
+ });
310
+ return count === 1 ? row : null;
311
+ }
312
+
313
+ /**
314
+ * Delete one client's unexpired code without exchanging it (the spoke's
315
+ * callback burns every code it cannot complete, SEC-7894-4). A code minted for
316
+ * another client is left alone. `true` when a row was deleted.
317
+ */
318
+ export async function burnCode(params: {
319
+ code: string;
320
+ clientId: string;
321
+ now: Date;
322
+ }): Promise<boolean> {
323
+ const row = await findCodeRow(params.code);
324
+ if (!row || row.payload === null) return false;
325
+ if (row.payload.clientId !== params.clientId) return false;
326
+ if (row.expiresAt.getTime() <= params.now.getTime()) return false;
327
+ const { count } = await prisma.verification.deleteMany({
328
+ where: { id: row.id },
329
+ });
330
+ return count === 1;
331
+ }
332
+
333
+ /** Sweep expired code rows. Best-effort housekeeping on every exchange. */
334
+ export async function deleteExpiredCodes(now: Date): Promise<void> {
335
+ await prisma.verification.deleteMany({
336
+ where: {
337
+ identifier: { startsWith: CODE_IDENTIFIER_PREFIX },
338
+ expiresAt: { lte: now },
339
+ },
340
+ });
341
+ }
342
+
343
+ // ── The grant (`OAuthAuthorization`) ─────────────────────────────────────────
344
+
345
+ /**
346
+ * Issue the credential for (person, client): one row per pair, so a new
347
+ * sign-in rotates the previous credential (spec 7894 Clarifications). The
348
+ * digest replaces the old one and the row is un-revoked.
349
+ */
350
+ export async function upsertAuthorization(params: {
351
+ userId: string;
352
+ clientRowId: string;
353
+ accessTokenHash: string;
354
+ expiresAt: Date;
355
+ }): Promise<void> {
356
+ await prisma.oAuthAuthorization.upsert({
357
+ where: {
358
+ userId_clientId: { userId: params.userId, clientId: params.clientRowId },
359
+ },
360
+ create: {
361
+ userId: params.userId,
362
+ clientId: params.clientRowId,
363
+ scopes: [HUB_SIGN_IN_SCOPE],
364
+ accessToken: params.accessTokenHash,
365
+ expiresAt: params.expiresAt,
366
+ },
367
+ update: {
368
+ scopes: [HUB_SIGN_IN_SCOPE],
369
+ accessToken: params.accessTokenHash,
370
+ expiresAt: params.expiresAt,
371
+ revokedAt: null,
372
+ },
373
+ });
374
+ }
375
+
376
+ /** Revoke one client's credential by digest. `true` when a live row matched. */
377
+ export async function revokeAuthorization(params: {
378
+ clientRowId: string;
379
+ accessTokenHash: string;
380
+ now: Date;
381
+ }): Promise<boolean> {
382
+ const { count } = await prisma.oAuthAuthorization.updateMany({
383
+ where: {
384
+ clientId: params.clientRowId,
385
+ accessToken: params.accessTokenHash,
386
+ revokedAt: null,
387
+ },
388
+ data: { revokedAt: params.now },
389
+ });
390
+ return count === 1;
391
+ }
392
+
393
+ export interface AuthorizationLookupRow {
394
+ userId: string;
395
+ expiresAt: Date;
396
+ revokedAt: Date | null;
397
+ client: { clientId: string; enabled: boolean };
398
+ user: { emailVerified: boolean };
399
+ }
400
+
401
+ /**
402
+ * The preHandler's one read: a credential's digest to its grant, with the
403
+ * client's public id and enabled flag and the person's verified flag in the
404
+ * same query.
405
+ */
406
+ export async function findAuthorizationByCredentialHash(
407
+ accessTokenHash: string,
408
+ ): Promise<AuthorizationLookupRow | null> {
409
+ return prisma.oAuthAuthorization.findUnique({
410
+ where: { accessToken: accessTokenHash },
411
+ select: {
412
+ userId: true,
413
+ expiresAt: true,
414
+ revokedAt: true,
415
+ client: { select: { clientId: true, enabled: true } },
416
+ user: { select: { emailVerified: true } },
417
+ },
418
+ });
419
+ }
@@ -20,6 +20,14 @@
20
20
  * `currentSiteId()` async would edit every one of its dozen non-test call
21
21
  * sites across routes/services/bins, including the two route files NFR1
22
22
  * requires to stay byte-unchanged.
23
+ *
24
+ * The Checkout site stamp (#7868, spec D1/D2): `SITE_STAMP_KEY`,
25
+ * `siteStamp()` and `isForeignSiteStamp()` are the one definition of the
26
+ * `metadata.site` key every hub-created Checkout session carries and the
27
+ * Stripe webhook reads. The stamp is `currentSiteId()`, so writer and reader
28
+ * cannot disagree inside one deployment. A session is foreign only when its
29
+ * stamp is a non-empty string other than `currentSiteId()`; an unstamped
30
+ * session is the hub's own (roadmap D4).
23
31
  */
24
32
  import { resolvedAdapterKind } from "@working-theory/content-adapters";
25
33
  import {
@@ -35,6 +43,35 @@ export function currentSiteId(): string {
35
43
  return process.env.AILK_SITE_ID ?? "default";
36
44
  }
37
45
 
46
+ /** The Checkout session metadata key naming the site a session belongs to (#7868 D1). */
47
+ export const SITE_STAMP_KEY = "site";
48
+
49
+ /**
50
+ * The metadata a hub-created Checkout session carries (#7868 D1/D2):
51
+ * `{ [SITE_STAMP_KEY]: currentSiteId() }`, read per call. Empty when the alias
52
+ * is `""` (an `AILK_SITE_ID` set to the empty string), so Stripe is never sent
53
+ * an empty value (SEC-7868-5) — and the webhook treats that deployment's
54
+ * sessions as unstamped, exactly as today.
55
+ */
56
+ export function siteStamp(): Record<string, string> {
57
+ const site = currentSiteId();
58
+ return site === "" ? {} : { [SITE_STAMP_KEY]: site };
59
+ }
60
+
61
+ /**
62
+ * True only when `metadata[SITE_STAMP_KEY]` is a non-empty string that is not
63
+ * `currentSiteId()` — a session another site on the shared Stripe account
64
+ * opened (#7868 D2). An absent, empty or non-string stamp is the hub's own
65
+ * (roadmap D4: Payment Links, invoices, the portal and pre-stamp sessions
66
+ * carry none). Exact, case-sensitive comparison, as the spokes' own check.
67
+ */
68
+ export function isForeignSiteStamp(
69
+ metadata: Record<string, string> | null | undefined,
70
+ ): boolean {
71
+ const stamp: unknown = metadata?.[SITE_STAMP_KEY];
72
+ return typeof stamp === "string" && stamp !== "" && stamp !== currentSiteId();
73
+ }
74
+
38
75
  /**
39
76
  * The resolved workspace id, memoized after the first SUCCESSFUL resolution
40
77
  * ("resolves the alias once at startup", ownership brief § Layer 2 / #6155
@@ -16,13 +16,23 @@
16
16
  * anonymous visitor of that site, and every agent using its `apps/mcp`, acts
17
17
  * through it. It grants what the site's anonymous visitors can already do on
18
18
  * the hub — read that workspace's enabled meeting types and public content,
19
- * and write leads and bookings into it.
19
+ * and write leads and bookings into it. One opt-in addition (#7876 D3): while
20
+ * the hub's operator sets `AILK_SPOKE_FLOW_SEED`, a key may also write its
21
+ * own workspace's flow definitions (`PUT /v1/flows/:slug/definition`),
22
+ * limited to the blocks the site's own flow pages render — never emails,
23
+ * deliverables, pricing, registers or listings.
20
24
  *
21
- * Two kinds of caller, kept apart:
25
+ * Three kinds of caller, kept apart:
22
26
  * - the public resolver (`services/public-site-resolver.ts`) calls
23
27
  * `hashSpokeKey`, `findSpokeByKeyHash` and `hasRegisteredSpoke` only;
24
28
  * - the operator CLI (`bin/spokes.ts`) calls `registerSpoke`, `revokeSpoke`
25
- * and `listSpokes`. No route imports them.
29
+ * and `listSpokes` (and, through `lib/hub-sign-in-store.ts`'s
30
+ * `registerSignInClient`, `findSpokeById`). No route imports them;
31
+ * - the operator flow-copy service (`services/flow-copy.ts`, run only by
32
+ * `bin/flows-copy.ts`) calls `hasLiveSpokeForWorkspace` only (#7844 D7);
33
+ * - the hub sign-in service (`services/hub-sign-in.ts`) and the auth
34
+ * preHandler's hub-credential branch call `hashSpokeKey`,
35
+ * `findSpokeByKeyHash` and `findSpokeById` (#7894 D5, D6).
26
36
  *
27
37
  * Nothing here caches a row: a revocation takes effect on the next request
28
38
  * (NFR4). The resolver holds `hasRegisteredSpoke`'s answer itself (#7633 D3).
@@ -63,6 +73,20 @@ export async function findSpokeByKeyHash(
63
73
  });
64
74
  }
65
75
 
76
+ /**
77
+ * The sign-in client's read of its own spoke (#7894 D3, D5): a spoke is
78
+ * `Spoke.id`-bound to its `OAuthClient`, and the codes route — which has a
79
+ * cookie session and no spoke key — checks the spoke is still unrevoked by id.
80
+ */
81
+ export async function findSpokeById(
82
+ id: string,
83
+ ): Promise<(SpokeLookupRow & { name: string }) | null> {
84
+ return prisma.spoke.findUnique({
85
+ where: { id },
86
+ select: { id: true, workspaceId: true, revokedAt: true, name: true },
87
+ });
88
+ }
89
+
66
90
  /**
67
91
  * Whether this deployment is a hub: its registry holds at least one spoke,
68
92
  * revoked or not (#7633 D1). Reads every time; the resolver holds the
@@ -73,6 +97,20 @@ export async function hasRegisteredSpoke(): Promise<boolean> {
73
97
  return Boolean(row);
74
98
  }
75
99
 
100
+ /**
101
+ * Whether at least one unrevoked spoke is bound to this workspace (#7844 D7):
102
+ * the flow-copy tool's target check. Selects `id` only.
103
+ */
104
+ export async function hasLiveSpokeForWorkspace(
105
+ workspaceId: string,
106
+ ): Promise<boolean> {
107
+ const row = await prisma.spoke.findFirst({
108
+ where: { workspaceId, revokedAt: null },
109
+ select: { id: true },
110
+ });
111
+ return Boolean(row);
112
+ }
113
+
76
114
  // ── Operator functions — `bin/spokes.ts` only ────────────────────────────────
77
115
 
78
116
  export interface SpokeListRow {
@@ -194,6 +194,8 @@ const WS_A1 = "wksp_00000000-0000-7000-8000-0000000000a1";
194
194
 
195
195
  type AgentFixture = {
196
196
  id: string;
197
+ /** Absent → the row carries none (the double omits the column). */
198
+ grants?: string[];
197
199
  enabled?: boolean;
198
200
  keyIssuedToMembershipId?: string | null;
199
201
  lastActiveAt?: Date | null;
@@ -215,6 +217,7 @@ function installAgents(agents: Array<AgentFixture & { key: string }>): void {
215
217
  workspaceId: WS_A1,
216
218
  organizationId: ORG_A,
217
219
  permissionLevel: "member",
220
+ ...(a.grants === undefined ? {} : { grants: a.grants }),
218
221
  enabled: a.enabled ?? true,
219
222
  keyIssuedToMembershipId:
220
223
  a.keyIssuedToMembershipId === undefined ? ADMIN_MEMBERSHIP : a.keyIssuedToMembershipId,
@@ -298,6 +301,7 @@ describe("auth preHandler — agent branch (#3591)", () => {
298
301
  organizationId: ORG_A,
299
302
  responsibleMembershipId: PERSON_MEMBERSHIP,
300
303
  permissionLevel: "member",
304
+ grants: [],
301
305
  },
302
306
  actor: { type: "agent", agentId: AGENT_A, onBehalfOfUserId: PERSON },
303
307
  sessionTenant: null,