create-substrat 0.13.25 → 0.15.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-substrat",
3
- "version": "0.13.25",
3
+ "version": "0.15.0",
4
4
  "description": "Scaffold a Substrat vertical — `npm create substrat <dir>`.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
package/project-files.js CHANGED
@@ -30,12 +30,12 @@ import { DEV_SERVERS } from './dev-servers.js';
30
30
  // The runtime packages release together off one version line (the changesets `fixed`
31
31
  // group), so one constant is right for all of them. Engines do NOT share a line —
32
32
  // each versions on its own, so one pin per engine, deliberately.
33
- const SUBSTRAT = '^0.186.0';
34
- const ENGINE_WORKORDER = '^0.13.11';
35
- const ENGINE_INVOICING = '^0.11.70';
33
+ const SUBSTRAT = '^0.188.0';
34
+ const ENGINE_WORKORDER = '^0.13.13';
35
+ const ENGINE_INVOICING = '^0.11.72';
36
36
  const BOUNDARY_LINT = '^0.8.2';
37
- const DEV_ISSUER = '^0.3.6';
38
- const ATTACHMENT_EXTRACTORS = '^0.2.47';
37
+ const DEV_ISSUER = '^0.4.1';
38
+ const ATTACHMENT_EXTRACTORS = '^0.2.49';
39
39
 
40
40
  export const TSCONFIG = `${JSON.stringify(
41
41
  {
@@ -56,7 +56,7 @@ export const TSCONFIG = `${JSON.stringify(
56
56
  // under their own config (tsconfig.worker.json) — the node config must not
57
57
  // see them. `src/routes.ts` is deliberately NOT excluded: the shared route
58
58
  // table must typecheck under both, which is what keeps it host-agnostic.
59
- exclude: ['src/worker.ts', 'src/config-do.ts'],
59
+ exclude: ['src/worker.ts'],
60
60
  },
61
61
  null,
62
62
  2,
@@ -82,6 +82,14 @@ export default defineConfig({
82
82
  */
83
83
  export const TEST_RUNNER = { vitest: '^5.0.0', '@vitest/ui': '^5.0.0' };
84
84
 
85
+ /**
86
+ * The pnpm a scaffold installs with: the one the platform's build runs, which is this workspace's
87
+ * own (`tools/template-sync.mjs` holds the two together). With no pin a project took whatever pnpm
88
+ * was installed, and pnpm 11 refuses one: it stops on better-sqlite3's ignored build, and holds
89
+ * back any release younger than its minimum age, which every fresh `@substrat-run` release is.
90
+ */
91
+ export const PACKAGE_MANAGER = 'pnpm@10.10.0';
92
+
85
93
  /** The package.json of a new project. */
86
94
  export function packageJson(name) {
87
95
  return `${JSON.stringify(
@@ -90,6 +98,7 @@ export function packageJson(name) {
90
98
  version: '0.0.0',
91
99
  private: true,
92
100
  type: 'module',
101
+ packageManager: PACKAGE_MANAGER,
93
102
  // What `substrat push` reads: the permission surface (the registry the
94
103
  // promotion checkpoint diffs) and the runtime needs the deploy config is
95
104
  // derived from — you never author wrangler config (src/worker.ts is the
@@ -104,10 +113,10 @@ export function packageJson(name) {
104
113
  { binding: 'SCOPE', class: 'ScopeDO' },
105
114
  // The scope-local sweep singleton — the deployment's own timer (#461).
106
115
  { binding: 'SWEEPER', class: 'SweeperDO' },
107
- // Per-instance config delivered by the platform (/internal/configure) —
108
- // one DO per tenant, rows per scope. Without it the app cannot receive
109
- // the settings the dashboard offers its users.
110
- { binding: 'CONFIG', class: 'ConfigDO' },
116
+ // The tenant's identity directory: who is bound to what, the owner seat,
117
+ // and the settings the platform delivers (/internal/configure). One DO per
118
+ // tenant, rows per scope.
119
+ { binding: 'AUTH', class: 'IdentityDO' },
111
120
  ],
112
121
  },
113
122
  // No envSpec copy here (#1206): the declared per-instance settings live in
@@ -161,8 +170,8 @@ export function packageJson(name) {
161
170
  ...TEST_RUNNER,
162
171
  },
163
172
  // Do NOT add `zod` here — import `z` from `@substrat-run/contracts` (AGENTS.md, rule 10).
164
- // better-sqlite3 >=13 ships prebuilt binaries for every supported platform and
165
- // declares no install script, so it needs no build allowlist entry.
173
+ // better-sqlite3 >=13 ships prebuilt binaries for every supported platform, so its build
174
+ // stays ignored and needs no allowlist entry: pnpm 10 names it as ignored, and it loads.
166
175
  },
167
176
  null,
168
177
  2,
@@ -50,7 +50,6 @@ src/personas.ts the dev cast, read by the issuer and the seed ← harness
50
50
  src/routes.ts the routes, DERIVED from the operations ← harness
51
51
  src/server.ts the dev entrypoint (node + persona picker) ← harness
52
52
  src/worker.ts the deployable Cloudflare worker ← harness
53
- src/config-do.ts per-instance config store (Cloudflare only) ← harness
54
53
  test/scenario.test.ts the scenario — including the denials
55
54
  test/entities.test.ts the registry, held to the tables it migrates
56
55
  test/setup.ts the 50-byte LIKE/GLOB pattern limit, on by default (vitest setupFiles)
@@ -79,10 +78,15 @@ modules defined anywhere else will run locally and silently not deploy.
79
78
  `worker.ts` **mounts** the platform's `/internal/*` management contract via
80
79
  `mountPlatformSurface` from `@substrat-run/vertical-host` (one call — the routes
81
80
  and the `{ error }` envelope are authored there, not here, so they can't drift or
82
- ship half-done). What `worker.ts` still owns is **the auth seam** — it resolves
83
- nobody until you wire real auth there, and every `/api/*` call is 401 until you do.
84
- That is deliberate: there is no dev header to forget to turn off. `src/server.ts`
85
- shows the shape, signing in against the local OIDC issuer `pnpm dev` starts.
81
+ ship half-done). Sign-in is `workerDoor`, from `@substrat-run/vertical-host/worker-door`:
82
+ the issuer the dashboard delivers, the tenant's identity directory, and the owner seat
83
+ the first person takes. Every route gets its stub through `door.scope`, which hands an
84
+ operation the caller's verified address as `ctx.verifiedEmail`. The first time a person
85
+ reaches the scope, the door runs your join if you name one (`workerDoor({ join })`), then
86
+ gives them every shape your `permissions` declare `bootstrap` with `holder: 'self'`, once.
87
+ That is what the seed does locally, so a vertical with a join operation names it there, or a
88
+ hosted person is never joined. There is no dev header to forget to turn off. `src/server.ts`
89
+ is the same shape, against the local OIDC issuer `pnpm dev` starts.
86
90
 
87
91
  **A UI ships as declared assets.** If `app/` exists, `substrat.runtimeNeeds.assets` must
88
92
  point at its build output and `runtimeNeeds.build` must produce it — otherwise the deployed
@@ -90,15 +94,15 @@ vertical serves the API and 404s on `/`, with every local gate green. Declare it
90
94
  change that creates `app/`, not at deploy time. (`substrat push` refuses an undeclared UI,
91
95
  but by then you are already deploying.)
92
96
 
93
- Among the hooks it passes, **`onConfigure` is the one you must not drop.** It is
97
+ Among the hooks `door.platform` passes, **`onConfigure` is the one you must not drop.** It is
94
98
  how per-instance settings reach the running app: the dashboard's Settings → Env
95
99
  and Identity tabs POST to `/internal/configure`, and a vertical that supplies no
96
100
  hook answers **501** to that call for its whole life — the setting is saved, the
97
101
  dashboard reports `delivered: false`, and the app never sees it. That includes the
98
102
  `substrat:auth` issuer choice, i.e. the difference between a working login and
99
- 401-on-everything. The starter stores deliveries in `config-do.ts` and reads them
100
- back through `resolveScopedEnvSpec` (`instanceConfig`). Read settings that way and
101
- never off `env` directly: an `envSpec` default rides as a worker binding shared by
103
+ 401-on-everything. Deliveries land in the tenant's identity directory, and
104
+ `door.settings(env, node)` reads them back. Read settings that way and never off
105
+ `env` directly: an `envSpec` default rides as a worker binding shared by
102
106
  every install of one serving script, so `env.FOO` is the same string for every
103
107
  tenant no matter what any of them saved. Declare a setting once, in
104
108
  `src/manifest.ts` (`SHOP_ENV`) — `src/provision.ts` re-exports it as `envSpec`,
@@ -91,7 +91,7 @@ app.get('/api/me', async (c) => {
91
91
  async function stub(c: Context): Promise<ScopeStub> {
92
92
  const caller = await login.caller(c.req.raw.headers);
93
93
  if (!caller) throw new HTTPException(401, { message: 'unauthorized' });
94
- return host.getScope(caller.principal, caller.tenantId, caller.scopeId);
94
+ return host.getScope(caller.principal, caller.tenantId, caller.scopeId, { verifiedEmail: caller.verifiedEmail });
95
95
  }
96
96
 
97
97
  // Everything else — including `/api/invoke` and the shared error envelope.
@@ -11,35 +11,16 @@
11
11
  * package.json (entry = this file, stores = the DO classes exported here) —
12
12
  * you never author wrangler config.
13
13
  *
14
- * ── THE AUTH SEAM ────────────────────────────────────────────────────────────
15
- * This starter ships NO auth in the worker: every /api/* call is 401 until you
16
- * wire `authenticatedPrincipal` below. That is deliberate and it is honest —
17
- * there is nothing here that resolves a caller, in any environment, so there is
18
- * nothing to accidentally deploy.
19
- *
20
- * It used to resolve a caller through an `x-principal` header gated on
21
- * ALLOW_DEV_HEADER. That is an impersonation bypass — a cross-tenant hole with a
22
- * UI, one environment variable from being live — and it is gone. `src/server.ts`
23
- * shows the shape you want instead: @substrat-run/vertical-auth's
24
- * `oidcRpAuthProvider` verifies the request against your issuer and hands you a
25
- * subject; an identity directory maps that subject to a PrincipalId. The dev
26
- * server can use `host.admin` as that directory. A hosted worker needs a durable
27
- * one — @substrat-run/vertical-auth's per-tenant `IdentityDO` is the platform's,
28
- * and it also gives you the owner-claim and invite flows a new install needs.
29
- * ───────────────────────────────────────────────────────────────────────────
14
+ * Sign-in is `workerDoor`'s, from @substrat-run/vertical-host: the issuer the dashboard delivers
15
+ * for this instance, the tenant's identity directory (the `AUTH` store), and the owner seat the
16
+ * first person takes. There is no credential store here and no dev header: a request names no
17
+ * caller, the session does. Member invites are yours to add: who may invite is your own rule, so
18
+ * mount `mountInviteRoutes` from @substrat-run/vertical-auth with your admin gate.
30
19
  */
31
20
  import { Hono } from 'hono';
32
21
  import type { Context } from 'hono';
33
22
  import { HTTPException } from 'hono/http-exception';
34
- import {
35
- resolveScopedEnvSpec,
36
- scopeId,
37
- tenantId,
38
- z,
39
- type PrincipalId,
40
- type ScopeId,
41
- type TenantId,
42
- } from '@substrat-run/contracts';
23
+ import { scopeId, tenantId, type ScopeId, type TenantId } from '@substrat-run/contracts';
43
24
  import {
44
25
  CloudflareScopeHost,
45
26
  defineScopeDO,
@@ -56,21 +37,22 @@ import {
56
37
  RouterAssertionError,
57
38
  invocationLog,
58
39
  } from '@substrat-run/vertical-host';
59
- import { MODULES, OWNER_ROLE_KEY, ROLES, permissions } from './provision.js';
60
- import { SHOP_ENV } from './manifest.js';
40
+ import { IdentityDO, workerDoor } from '@substrat-run/vertical-host/worker-door';
41
+ // Only from provision.ts, the file `substrat push` reads: so this worker fits any vertical whose
42
+ // provision.ts exports these five, and needs no edit beyond a `join`.
43
+ import { MODULES, OWNER_ROLE_KEY, ROLES, envSpec, permissions } from './provision.js';
61
44
  import { mountApi } from './routes.js';
62
- import { AUTH_CONFIG_KEY, ConfigDO, type ConfigDo } from './config-do.js';
63
45
 
64
46
  /** The scope-DO class = the app binary: kernel + engines + this vertical, bundled. */
65
47
  export const ScopeDO = defineScopeDO(MODULES, {}, { permissions });
66
48
 
67
49
  /**
68
- * The per-instance config store (`config-do.ts`) — one per tenant, rows keyed by scope.
69
- * Declared as a store in package.json `substrat.runtimeNeeds.stores`, like `ScopeDO`
70
- * above and `SweeperDO` below. Re-exported because workerd resolves a DO class from the
71
- * ENTRY module's exports; defining it in another file is fine, hiding it here is not.
50
+ * The tenant's identity directory: who is bound to what, the owner seat, and the settings the
51
+ * platform delivers. Declared as a store in package.json `substrat.runtimeNeeds.stores`, like
52
+ * `ScopeDO` above and `SweeperDO` below. Re-exported because workerd resolves a DO class from the
53
+ * ENTRY module's exports.
72
54
  */
73
- export { ConfigDO };
55
+ export { IdentityDO };
74
56
 
75
57
  /**
76
58
  * The deployment's own timer (#461): a roster-keeping singleton whose alarm runs
@@ -117,8 +99,8 @@ interface Env {
117
99
  SCOPE: DurableObjectNamespace;
118
100
  /** The roster-keeping sweep singleton — the deployment's own timer (#461). */
119
101
  SWEEPER: DurableObjectNamespace;
120
- /** Per-instance config delivered by the platform (`/internal/configure`). */
121
- CONFIG: DurableObjectNamespace;
102
+ /** The tenant's identity directory, and what the platform delivers to this instance. */
103
+ AUTH: DurableObjectNamespace<IdentityDO>;
122
104
  /** Local `wrangler dev` only: when 'true', fall back to DEV_NODE if no router
123
105
  * asserted a node. Addresses an instance; authenticates nobody. */
124
106
  ALLOW_DEV_NODE?: string;
@@ -152,75 +134,26 @@ function hostFor(env: Env): CloudflareScopeHost {
152
134
  return host;
153
135
  }
154
136
 
155
- /** This tenant's config DO — one per tenant, holding a row set per scope. */
156
- function configDo(env: Env, node: Node): DurableObjectStub & ConfigDo {
157
- return env.CONFIG.get(env.CONFIG.idFromName(node.tenantId)) as DurableObjectStub & ConfigDo;
158
- }
159
-
160
- /**
161
- * The scope's delivered auth choice. Parsed LENIENTLY on purpose: an absent or
162
- * malformed entry means "nothing delivered", never a throw, so a bad delivery can
163
- * never lock an instance out of its own login.
164
- */
165
- const authChoice = z.object({
166
- mode: z.literal('oidc'),
167
- issuer: z.string().min(1),
168
- clientId: z.string().min(1).optional(),
169
- clientSecret: z.string().min(1).optional(),
170
- });
171
-
172
- /**
173
- * Everything this instance was configured with, in ONE DO hop: the ordinary declared
174
- * settings (`SHOP_ENV`) resolved delivered > env > default, and the structured
175
- * `substrat:auth` choice the dashboard's Identity tab sends.
176
- *
177
- * Reading settings THROUGH this — rather than off `env` — is the whole reason the
178
- * `/internal/configure` hook exists: a spec `default` rides as a worker binding shared
179
- * by every install of one serving script, so `env.SHOP_NAME` is the same string for
180
- * every tenant no matter what any of them saved.
181
- */
182
- async function instanceConfig(env: Env, node: Node) {
183
- const delivered = await configDo(env, node).getScopeConfig(node.scopeId);
184
- const settings = resolveScopedEnvSpec(SHOP_ENV, env as unknown as Record<string, unknown>, delivered).values;
185
- let identity: z.infer<typeof authChoice> | null = null;
186
- const raw = delivered[AUTH_CONFIG_KEY];
187
- if (raw) {
188
- try {
189
- const parsed = authChoice.safeParse(JSON.parse(raw));
190
- identity = parsed.success ? parsed.data : null;
191
- } catch {
192
- identity = null;
193
- }
194
- }
195
- return { settings, identity };
196
- }
197
-
198
137
  /**
199
- * THE AUTH SEAM (see the header comment): resolve the caller to a PrincipalId, or
200
- * null for nobody. Two steps, and this starter ships neither:
138
+ * Who is calling, for every route below. It hands an operation the caller's verified address, and
139
+ * the first time a person reaches a scope it gives them every shape `permissions` declares
140
+ * `bootstrap` with `holder: 'self'`, on their own record. A vertical with a join operation names it
141
+ * here, so a person is joined when they first sign in, before that grant:
201
142
  *
202
- * 1. Verify the request → a subject. `instanceConfig` already reads the issuer
203
- * the dashboard delivered as `substrat:auth`, so this is
204
- * `oidcRpAuthProvider({ issuer, clientId, clientSecret, sessionSecret }).resolve(...)`
205
- * — and you mount the same provider's `handle` on `/api/auth/*` for the login
206
- * round-trip. `src/server.ts` does exactly this against the local dev issuer.
207
- * 2. Map that subject → a PrincipalId, per scope. This needs a durable store the
208
- * worker owns; @substrat-run/vertical-auth's `IdentityDO` is one, and carries
209
- * the owner-claim (first sign-in takes the seat) and invite flows with it.
143
+ * join: (scope, who) => scope.invoke('shop/join', { displayName: who.display }),
210
144
  *
211
- * Returning null unconditionally is the safe default, not an oversight: a starter
212
- * that guessed here would be a starter that let the wrong person in.
145
+ * This shop has neither: its people are added by staff, and its portal shape is a customer's.
213
146
  */
214
- async function authenticatedPrincipal(_req: Request, _env: Env): Promise<PrincipalId | null> {
215
- return null; // ← wire real auth here (see the two steps above)
216
- }
147
+ const door = workerDoor<Env>({
148
+ directory: (env, node) => env.AUTH.get(env.AUTH.idFromName(node.tenantId)),
149
+ nodeFor,
150
+ hostFor,
151
+ envSpec,
152
+ });
217
153
 
218
- /** Resolve caller + routed node → a scope stub. 401 if nobody. */
219
- async function stub(c: Context<{ Bindings: Env }>): Promise<ScopeStub> {
220
- const node = nodeFor(c.req.raw, c.env);
221
- const principal = await authenticatedPrincipal(c.req.raw, c.env);
222
- if (!principal) throw new HTTPException(401, { message: await unauthorizedReason(c.env, node) });
223
- return hostFor(c.env).getScope(principal, node.tenantId, node.scopeId, {
154
+ /** The caller's scope stub. 401 if nobody. */
155
+ function stub(c: Context<{ Bindings: Env }>): Promise<ScopeStub> {
156
+ return door.scope(c, {
224
157
  // An operation that called `ctx.requestPlatform`, or committed an event of a type this
225
158
  // vertical EXPORTS (whether or not another app imports it yet), flags its response. The
226
159
  // router then has the platform act on this scope within seconds instead of at the next
@@ -231,27 +164,6 @@ async function stub(c: Context<{ Bindings: Env }>): Promise<ScopeStub> {
231
164
  });
232
165
  }
233
166
 
234
- /**
235
- * Why the caller is nobody — a DIAGNOSIS, not a bare "unauthorized".
236
- *
237
- * The expensive case to debug is the one that looks like a platform bug and is not:
238
- * a tenant picks an identity provider in the dashboard, the platform delivers it here
239
- * successfully, and every request is still 401 — because this starter ships no auth.
240
- * Saying so, and naming the seam, is the difference between a five-minute fix and a
241
- * support thread. Only runs on the failure path, so it costs a DO hop on 401s alone.
242
- */
243
- async function unauthorizedReason(env: Env, node: Node): Promise<string> {
244
- try {
245
- const { identity } = await instanceConfig(env, node);
246
- if (identity) {
247
- return `unauthorized — this instance has an identity provider configured (${identity.issuer}), but this vertical has not wired it up yet: implement \`authenticatedPrincipal\` in src/worker.ts (the auth seam)`;
248
- }
249
- } catch {
250
- // The config store is unreachable — that is not the caller's problem to hear about.
251
- }
252
- return 'unauthorized';
253
- }
254
-
255
167
  const app = new Hono<{ Bindings: Env }>();
256
168
 
257
169
  // FIRST, before any route: Hono composes handlers in registration order and stops at the
@@ -269,16 +181,9 @@ app.use(
269
181
  }),
270
182
  );
271
183
 
272
- // Who am I, and what instance am I on — resolves the caller without invoking
273
- // anything. Auth-shaped and host-specific, so it stays OUT of the shared table;
274
- // `server.ts` answers the same question from its own login.
275
- app.get('/api/me', async (c) => {
276
- const node = nodeFor(c.req.raw, c.env);
277
- const principal = await authenticatedPrincipal(c.req.raw, c.env);
278
- if (!principal) return c.json({ error: await unauthorizedReason(c.env, node) }, 401);
279
- const { settings, identity } = await instanceConfig(c.env, node);
280
- return c.json({ principal, settings, identity: identity ? { issuer: identity.issuer } : null });
281
- });
184
+ // Sign-in: the login round-trip at `/api/auth/*`, who is signed in at `/api/me`, and the owner
185
+ // seat at `/api/claim-owner`. Accounts and passwords live at the issuer, not here.
186
+ door.mount(app);
282
187
 
283
188
  // ── The vertical's API — the SAME table `server.ts` mounts (src/routes.ts) ───
284
189
  // Including `/api/invoke`. Mounted BEFORE the platform surface: Hono keeps only the
@@ -293,35 +198,23 @@ mountApi(app, stub);
293
198
  // and bookmarks/rewind — plus the guaranteed { error } envelope is authored ONCE
294
199
  // in @substrat-run/vertical-host (issue #510); mount it and it cannot drift.
295
200
  //
296
- // This starter's hooks keep the deployment's sweep roster (#461) in step: a newly
297
- // provisioned scope joins it (so its schedules run), and a deleted one leaves it.
298
- // A full reconcile needs a durable owner-of-record to heal from — this starter keeps none
299
- // (that lives with real auth, the auth seam), so `resolveOwner` is omitted. The platform's
300
- // reconcile then only seats what each version declares (schedule, peer and connection
301
- // grants) and re-grants no owner, until you wire auth and supply one.
201
+ // The hooks keep the deployment's sweep roster (#461) in step: a newly provisioned scope joins it
202
+ // (so its schedules run), and a deleted one leaves it. The door's hooks do the rest: the owner seat
203
+ // at provision, and the settings the dashboard's Env and Identity tabs deliver.
302
204
  mountPlatformSurface<Env>(app, {
303
205
  platformSecret: (env) => env.PLATFORM_SECRET,
304
206
  hostFor,
305
207
  roles: ROLES,
306
208
  ownerRoleKey: OWNER_ROLE_KEY,
307
- // Both hooks are `Promise<void>`: the roster's own count is its business, and
308
- // returning it here would make the platform's response shape depend on what a
309
- // vertical happens to hand back. Await, discard.
209
+ ...door.platform,
310
210
  onProvision: async (env, b) => {
211
+ await door.platform.onProvision(env, b);
311
212
  await sweeper(env).noteScope(b.tenantId, b.scopeId);
312
213
  },
313
- onDeleteScope: async (env, s) => {
214
+ onDeleteScope: async (env, s, tenantId) => {
215
+ await door.platform.onDeleteScope(env, s, tenantId);
314
216
  await sweeper(env).forgetScope(s);
315
217
  },
316
- // Per-instance config delivery (the dashboard's Settings → Env and Identity tabs).
317
- // WITHOUT this hook `/internal/configure` answers 501 for the life of the app: the
318
- // dashboard saves the setting, reports `delivered: false`, and the running worker
319
- // never sees it — including the `substrat:auth` issuer choice that is the difference
320
- // between a working login and 401-on-everything. Store it; `instanceConfig` reads it
321
- // back. Idempotent, so the platform's reconciliation sweep can re-deliver safely.
322
- onConfigure: async (env, b) => {
323
- await configDo(env, { tenantId: b.tenantId, scopeId: b.scopeId }).setScopeConfig(b.scopeId, b.entries);
324
- },
325
218
  });
326
219
 
327
220
  // Unmatched /api/* fails as JSON; everything else gets a pointer, not a UI —
@@ -9,5 +9,5 @@
9
9
  "skipLibCheck": true,
10
10
  "noEmit": true
11
11
  },
12
- "include": ["src/worker.ts", "src/routes.ts", "src/config-do.ts", "src/provision.ts", "src/manifest.ts", "src/migrations.ts", "src/module.ts"]
12
+ "include": ["src/worker.ts", "src/routes.ts", "src/provision.ts", "src/manifest.ts", "src/migrations.ts", "src/module.ts"]
13
13
  }
@@ -1,86 +0,0 @@
1
- import { DurableObject } from 'cloudflare:workers';
2
-
3
- /**
4
- * The key the platform delivers a scope's identity-provider choice under.
5
- *
6
- * It lives HERE rather than in `worker.ts` for a runtime reason worth knowing: workerd
7
- * requires every named export of the entry module to be a handler or a Durable Object
8
- * class, so exporting a plain constant from `worker.ts` makes the whole worker fail to
9
- * boot — with a `tsc`-clean tree and a green test suite. Config vocabulary belongs with
10
- * the config store anyway.
11
- */
12
- export const AUTH_CONFIG_KEY = 'substrat:auth';
13
-
14
- /**
15
- * The vertical's own per-instance CONFIG store — the durable half of
16
- * `/internal/configure`.
17
- *
18
- * The platform delivers per-install settings (the dashboard's Settings → Env and
19
- * Identity tabs) by POSTing them to `/internal/configure` on this worker. A vertical
20
- * that supplies no `onConfigure` hook answers 501 to that call for its whole life:
21
- * the dashboard records the setting, reports `delivered: false`, and the running app
22
- * never sees it. This DO is what makes the hook answerable.
23
- *
24
- * It is a HARNESS store, not module code — the config a scope runs on is not domain
25
- * data, and it must survive a scope-DO storage wipe (a restore, a rebind), so it
26
- * deliberately lives outside the scope's own DO. One DO per TENANT, rows keyed by
27
- * scope; the table matches `scope_config` in `@substrat-run/vertical-auth`'s
28
- * `IdentityDO` exactly, so a project that later adopts vertical-auth for real logins
29
- * swaps the binding and keeps its rows.
30
- *
31
- * Sandbox-clean (D-18): this is one of the deployment's OWN Durable Object classes,
32
- * declared in package.json `substrat.runtimeNeeds.stores`. No control-plane binding,
33
- * no service binding — the platform refuses those.
34
- */
35
- export class ConfigDO extends DurableObject<Record<string, never>> {
36
- private ready = false;
37
-
38
- /** Lazily create the table — cheaper than a blockConcurrencyWhile on every wake. */
39
- private init(): void {
40
- if (this.ready) return;
41
- this.ctx.storage.sql.exec(
42
- `CREATE TABLE IF NOT EXISTS scope_config (
43
- scope_id TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL,
44
- PRIMARY KEY (scope_id, key))`,
45
- );
46
- this.ready = true;
47
- }
48
-
49
- /**
50
- * Upsert config delivered for one scope. Key-by-key rather than a replace, so a
51
- * partial delivery composes with what is already there; idempotent, so the
52
- * platform's reconciliation sweep can re-run it safely.
53
- */
54
- async setScopeConfig(scopeId: string, entries: Array<{ key: string; value: string }>): Promise<void> {
55
- this.init();
56
- for (const { key, value } of entries) {
57
- this.ctx.storage.sql.exec(
58
- 'INSERT OR REPLACE INTO scope_config (scope_id, key, value) VALUES (?, ?, ?)',
59
- scopeId, key, value,
60
- );
61
- }
62
- }
63
-
64
- /**
65
- * The config delivered to one scope, as a plain map — exactly the `delivered`
66
- * argument of `resolveScopedEnvSpec(spec, env, delivered)`. Reading it back is what
67
- * keeps the hook from being write-only: an env-spec key set per install must be
68
- * overlaid here, because env-spec defaults ride as worker bindings SHARED by every
69
- * install of one serving script, so reading `env` alone always yields the shared
70
- * default no matter what the tenant saved.
71
- */
72
- async getScopeConfig(scopeId: string): Promise<Record<string, string>> {
73
- this.init();
74
- const config: Record<string, string> = {};
75
- for (const row of this.ctx.storage.sql.exec('SELECT key, value FROM scope_config WHERE scope_id = ?', scopeId)) {
76
- config[row.key as string] = row.value as string;
77
- }
78
- return config;
79
- }
80
- }
81
-
82
- /** The typed stub surface — what `worker.ts` calls across the DO boundary. */
83
- export interface ConfigDo {
84
- setScopeConfig(scopeId: string, entries: Array<{ key: string; value: string }>): Promise<void>;
85
- getScopeConfig(scopeId: string): Promise<Record<string, string>>;
86
- }