create-substrat 0.13.24 → 0.14.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/index.js CHANGED
@@ -16,34 +16,12 @@ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync
16
16
  import { basename, dirname, join, resolve } from 'node:path';
17
17
  import { fileURLToPath } from 'node:url';
18
18
 
19
- import { DEV_SERVERS } from './dev-servers.js';
20
- import { TEST_RUNNER, TSCONFIG, VITEST_CONFIG } from './project-files.js';
19
+ import { TSCONFIG, VITEST_CONFIG, packageJson } from './project-files.js';
21
20
  import { offerLongPaths } from './windows.js';
22
21
 
23
22
  const HERE = dirname(fileURLToPath(import.meta.url));
24
23
  const TEMPLATE = join(HERE, 'template');
25
24
 
26
- // Substrat is 0.x, so these are caret ranges on the current minor — a caret on 0.x
27
- // locks the minor, which is what makes a stale pin here a scaffold four minors behind
28
- // rather than a scaffold that quietly upgrades.
29
- //
30
- // EMITTED, NOT EDITED. `pnpm lint:pins` writes this block from each package's own
31
- // version and `--check` fails CI on drift; `version-packages` runs the write, so a
32
- // bump and its pins land in the same PR. Hand-maintained, they went stale twice: once
33
- // resolving nothing (`^0.3.37` after workorder moved to 0.4.x), and once resolving
34
- // fine but freezing the template against packages nobody ships, which is worse — the
35
- // scaffold's own tests stayed green while the surface moved underneath them.
36
- //
37
- // The runtime packages release together off one version line (the changesets `fixed`
38
- // group), so one constant is right for all of them. Engines do NOT share a line —
39
- // each versions on its own, so one pin per engine, deliberately.
40
- const SUBSTRAT = '^0.185.0';
41
- const ENGINE_WORKORDER = '^0.13.10';
42
- const ENGINE_INVOICING = '^0.11.69';
43
- const BOUNDARY_LINT = '^0.8.2';
44
- const DEV_ISSUER = '^0.3.5';
45
- const ATTACHMENT_EXTRACTORS = '^0.2.46';
46
-
47
25
  const DOCS = 'https://substrat.net';
48
26
 
49
27
  function fail(message) {
@@ -76,92 +54,6 @@ function toPackageName(dir) {
76
54
  return name || 'substrat-vertical';
77
55
  }
78
56
 
79
- function packageJson(name) {
80
- return `${JSON.stringify(
81
- {
82
- name,
83
- version: '0.0.0',
84
- private: true,
85
- type: 'module',
86
- // What `substrat push` reads: the permission surface (the registry the
87
- // promotion checkpoint diffs) and the runtime needs the deploy config is
88
- // derived from — you never author wrangler config (src/worker.ts is the
89
- // entry; ScopeDO is the store it exports). Also the client-neutral home of
90
- // the dev topology `.claude/launch.json` is emitted from — see
91
- // dev-servers.js for why the port is read from the code and never declared.
92
- substrat: {
93
- permissions: 'src/provision.ts',
94
- runtimeNeeds: {
95
- entry: 'src/worker.ts',
96
- stores: [
97
- { binding: 'SCOPE', class: 'ScopeDO' },
98
- // The scope-local sweep singleton — the deployment's own timer (#461).
99
- { binding: 'SWEEPER', class: 'SweeperDO' },
100
- // Per-instance config delivered by the platform (/internal/configure) —
101
- // one DO per tenant, rows per scope. Without it the app cannot receive
102
- // the settings the dashboard offers its users.
103
- { binding: 'CONFIG', class: 'ConfigDO' },
104
- ],
105
- },
106
- // No envSpec copy here (#1206): the declared per-instance settings live in
107
- // src/manifest.ts (`SHOP_ENV`), re-exported as `envSpec` from the permissions
108
- // entry — `substrat push` reads them off that same import. The dashboard
109
- // renders its Settings form from what the push uploads.
110
- devServers: DEV_SERVERS,
111
- },
112
- scripts: {
113
- // Two processes: the local OIDC issuer you sign in at, and the API.
114
- dev: 'concurrently -n issuer,api -c magenta,blue "pnpm run issuer" "tsx watch src/server.ts"',
115
- issuer: 'substrat-dev-issuer --personas src/personas.ts',
116
- server: 'tsx src/server.ts',
117
- test: 'vitest run',
118
- // The live test dashboard: the `tests` entry of .claude/launch.json, opened at the
119
- // tokenised URL vitest prints. `--watch` is explicit, since vitest runs once and exits without a TTY.
120
- 'test:ui': 'vitest --watch --ui --open=false -c vitest.ui.config.ts',
121
- typecheck: 'tsc --noEmit && tsc -p tsconfig.worker.json --noEmit',
122
- 'lint:boundaries': 'substrat-boundary-lint',
123
- },
124
- dependencies: {
125
- '@substrat-run/kernel': SUBSTRAT,
126
- '@substrat-run/contracts': SUBSTRAT,
127
- '@substrat-run/adapter-sqlite': SUBSTRAT,
128
- '@substrat-run/adapter-cloudflare': SUBSTRAT,
129
- '@substrat-run/vertical-host': SUBSTRAT,
130
- '@substrat-run/attachment-extractors': ATTACHMENT_EXTRACTORS,
131
- '@substrat-run/engine-workorder': ENGINE_WORKORDER,
132
- '@substrat-run/engine-invoicing': ENGINE_INVOICING,
133
- hono: '^4.6.0',
134
- '@hono/node-server': '^1.13.0',
135
- 'better-sqlite3': '^13.0.3',
136
- },
137
- devDependencies: {
138
- '@substrat-run/boundary-lint': BOUNDARY_LINT,
139
- // The local OIDC issuer `pnpm dev` signs you in at. A devDependency on
140
- // purpose: it is never imported by anything the worker bundles.
141
- '@substrat-run/dev-issuer': DEV_ISSUER,
142
- // What `substrat push` builds the Worker with. The CLI runs the project's own
143
- // wrangler and never downloads one, so a push builds with the version pinned here.
144
- wrangler: '^4.151.0',
145
- // Major 5, because wrangler 4.151+ peers on it: with 4 here, `npm install` of a new
146
- // project stops on ERESOLVE. The template compiles against 5 (checked by installing a
147
- // scaffold from npm); the workspace catalog, which template-check reads, is still on 4.
148
- '@cloudflare/workers-types': '^5.20261023.1',
149
- '@types/better-sqlite3': '^9.6.0',
150
- '@types/node': '^22.0.0',
151
- concurrently: '^9.0.0',
152
- tsx: '^4.19.0',
153
- typescript: '^5.6.0',
154
- ...TEST_RUNNER,
155
- },
156
- // Do NOT add `zod` here — import `z` from `@substrat-run/contracts` (AGENTS.md, rule 10).
157
- // better-sqlite3 >=13 ships prebuilt binaries for every supported platform and
158
- // declares no install script, so it needs no build allowlist entry.
159
- },
160
- null,
161
- 2,
162
- )}\n`;
163
- }
164
-
165
57
  const GITIGNORE = `node_modules/
166
58
  dist/
167
59
  *.sqlite
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-substrat",
3
- "version": "0.13.24",
3
+ "version": "0.14.0",
4
4
  "description": "Scaffold a Substrat vertical — `npm create substrat <dir>`.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -26,6 +26,7 @@
26
26
  "index.js",
27
27
  "dev-servers.js",
28
28
  "project-files.js",
29
+ "project-files.d.ts",
29
30
  "windows.js",
30
31
  "template"
31
32
  ],
@@ -0,0 +1,4 @@
1
+ export const TSCONFIG: string;
2
+ export const VITEST_CONFIG: string;
3
+ export const TEST_RUNNER: Readonly<Record<string, string>>;
4
+ export function packageJson(name: string): string;
package/project-files.js CHANGED
@@ -8,14 +8,35 @@
8
8
  * drift class this repo has been bitten by repeatedly, so there is one copy and
9
9
  * both readers import it.
10
10
  *
11
- * `packageJson()` deliberately stays in `index.js`: it interpolates the emitted
12
- * pin block, and `tools/pins-emit.mts` writes that block into `index.js` by path.
13
- * The workspace check does not want those pins anyway — resolving `@substrat-run/*`
14
- * from npm is exactly what it is NOT doing.
11
+ * The studio is the third reader: it serves these as part of its `template` reference, so a
12
+ * generated project starts from the files a scaffold gets instead of writing its own.
15
13
  *
16
- * Dependency-free, like everything else in this package.
14
+ * Dependency-free, like everything else in this package: the studio's worker bundles it.
17
15
  */
18
16
 
17
+ import { DEV_SERVERS } from './dev-servers.js';
18
+
19
+ // Substrat is 0.x, so these are caret ranges on the current minor — a caret on 0.x
20
+ // locks the minor, which is what makes a stale pin here a scaffold four minors behind
21
+ // rather than a scaffold that quietly upgrades.
22
+ //
23
+ // EMITTED, NOT EDITED. `pnpm lint:pins` writes this block from each package's own
24
+ // version and `--check` fails CI on drift; `version-packages` runs the write, so a
25
+ // bump and its pins land in the same PR. Hand-maintained, they went stale twice: once
26
+ // resolving nothing (`^0.3.37` after workorder moved to 0.4.x), and once resolving
27
+ // fine but freezing the template against packages nobody ships, which is worse — the
28
+ // scaffold's own tests stayed green while the surface moved underneath them.
29
+ //
30
+ // The runtime packages release together off one version line (the changesets `fixed`
31
+ // group), so one constant is right for all of them. Engines do NOT share a line —
32
+ // each versions on its own, so one pin per engine, deliberately.
33
+ const SUBSTRAT = '^0.187.0';
34
+ const ENGINE_WORKORDER = '^0.13.12';
35
+ const ENGINE_INVOICING = '^0.11.71';
36
+ const BOUNDARY_LINT = '^0.8.2';
37
+ const DEV_ISSUER = '^0.4.0';
38
+ const ATTACHMENT_EXTRACTORS = '^0.2.48';
39
+
19
40
  export const TSCONFIG = `${JSON.stringify(
20
41
  {
21
42
  compilerOptions: {
@@ -35,7 +56,7 @@ export const TSCONFIG = `${JSON.stringify(
35
56
  // under their own config (tsconfig.worker.json) — the node config must not
36
57
  // see them. `src/routes.ts` is deliberately NOT excluded: the shared route
37
58
  // table must typecheck under both, which is what keeps it host-agnostic.
38
- exclude: ['src/worker.ts', 'src/config-do.ts'],
59
+ exclude: ['src/worker.ts'],
39
60
  },
40
61
  null,
41
62
  2,
@@ -60,3 +81,90 @@ export default defineConfig({
60
81
  * on a different major is a project nothing on a PR has ever run.
61
82
  */
62
83
  export const TEST_RUNNER = { vitest: '^5.0.0', '@vitest/ui': '^5.0.0' };
84
+
85
+ /** The package.json of a new project. */
86
+ export function packageJson(name) {
87
+ return `${JSON.stringify(
88
+ {
89
+ name,
90
+ version: '0.0.0',
91
+ private: true,
92
+ type: 'module',
93
+ // What `substrat push` reads: the permission surface (the registry the
94
+ // promotion checkpoint diffs) and the runtime needs the deploy config is
95
+ // derived from — you never author wrangler config (src/worker.ts is the
96
+ // entry; ScopeDO is the store it exports). Also the client-neutral home of
97
+ // the dev topology `.claude/launch.json` is emitted from — see
98
+ // dev-servers.js for why the port is read from the code and never declared.
99
+ substrat: {
100
+ permissions: 'src/provision.ts',
101
+ runtimeNeeds: {
102
+ entry: 'src/worker.ts',
103
+ stores: [
104
+ { binding: 'SCOPE', class: 'ScopeDO' },
105
+ // The scope-local sweep singleton — the deployment's own timer (#461).
106
+ { binding: 'SWEEPER', class: 'SweeperDO' },
107
+ // The tenant's identity directory: who is bound to what, the owner seat,
108
+ // and the settings the platform delivers (/internal/configure). One DO per
109
+ // tenant, rows per scope.
110
+ { binding: 'AUTH', class: 'IdentityDO' },
111
+ ],
112
+ },
113
+ // No envSpec copy here (#1206): the declared per-instance settings live in
114
+ // src/manifest.ts (`SHOP_ENV`), re-exported as `envSpec` from the permissions
115
+ // entry — `substrat push` reads them off that same import. The dashboard
116
+ // renders its Settings form from what the push uploads.
117
+ devServers: DEV_SERVERS,
118
+ },
119
+ scripts: {
120
+ // Two processes: the local OIDC issuer you sign in at, and the API.
121
+ dev: 'concurrently -n issuer,api -c magenta,blue "pnpm run issuer" "tsx watch src/server.ts"',
122
+ issuer: 'substrat-dev-issuer --personas src/personas.ts',
123
+ server: 'tsx src/server.ts',
124
+ test: 'vitest run',
125
+ // The live test dashboard: the `tests` entry of .claude/launch.json, opened at the
126
+ // tokenised URL vitest prints. `--watch` is explicit, since vitest runs once and exits without a TTY.
127
+ 'test:ui': 'vitest --watch --ui --open=false -c vitest.ui.config.ts',
128
+ typecheck: 'tsc --noEmit && tsc -p tsconfig.worker.json --noEmit',
129
+ 'lint:boundaries': 'substrat-boundary-lint',
130
+ },
131
+ dependencies: {
132
+ '@substrat-run/kernel': SUBSTRAT,
133
+ '@substrat-run/contracts': SUBSTRAT,
134
+ '@substrat-run/adapter-sqlite': SUBSTRAT,
135
+ '@substrat-run/adapter-cloudflare': SUBSTRAT,
136
+ '@substrat-run/vertical-host': SUBSTRAT,
137
+ '@substrat-run/attachment-extractors': ATTACHMENT_EXTRACTORS,
138
+ '@substrat-run/engine-workorder': ENGINE_WORKORDER,
139
+ '@substrat-run/engine-invoicing': ENGINE_INVOICING,
140
+ hono: '^4.6.0',
141
+ '@hono/node-server': '^1.13.0',
142
+ 'better-sqlite3': '^13.0.3',
143
+ },
144
+ devDependencies: {
145
+ '@substrat-run/boundary-lint': BOUNDARY_LINT,
146
+ // The local OIDC issuer `pnpm dev` signs you in at. A devDependency on
147
+ // purpose: it is never imported by anything the worker bundles.
148
+ '@substrat-run/dev-issuer': DEV_ISSUER,
149
+ // What `substrat push` builds the Worker with. The CLI runs the project's own
150
+ // wrangler and never downloads one, so a push builds with the version pinned here.
151
+ wrangler: '^4.151.0',
152
+ // Major 5, because wrangler 4.151+ peers on it: with 4 here, `npm install` of a new
153
+ // project stops on ERESOLVE. The template compiles against 5 (checked by installing a
154
+ // scaffold from npm); the workspace catalog, which template-check reads, is still on 4.
155
+ '@cloudflare/workers-types': '^5.20261023.1',
156
+ '@types/better-sqlite3': '^9.6.0',
157
+ '@types/node': '^22.0.0',
158
+ concurrently: '^9.0.0',
159
+ tsx: '^4.19.0',
160
+ typescript: '^5.6.0',
161
+ ...TEST_RUNNER,
162
+ },
163
+ // 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.
166
+ },
167
+ null,
168
+ 2,
169
+ )}\n`;
170
+ }
@@ -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,12 @@ 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`. There is no dev header to
85
+ forget to turn off. `src/server.ts` is the same shape, against the local OIDC issuer
86
+ `pnpm dev` starts.
86
87
 
87
88
  **A UI ships as declared assets.** If `app/` exists, `substrat.runtimeNeeds.assets` must
88
89
  point at its build output and `runtimeNeeds.build` must produce it — otherwise the deployed
@@ -90,15 +91,15 @@ vertical serves the API and 404s on `/`, with every local gate green. Declare it
90
91
  change that creates `app/`, not at deploy time. (`substrat push` refuses an undeclared UI,
91
92
  but by then you are already deploying.)
92
93
 
93
- Among the hooks it passes, **`onConfigure` is the one you must not drop.** It is
94
+ Among the hooks `door.platform` passes, **`onConfigure` is the one you must not drop.** It is
94
95
  how per-instance settings reach the running app: the dashboard's Settings → Env
95
96
  and Identity tabs POST to `/internal/configure`, and a vertical that supplies no
96
97
  hook answers **501** to that call for its whole life — the setting is saved, the
97
98
  dashboard reports `delivered: false`, and the app never sees it. That includes the
98
99
  `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
100
+ 401-on-everything. Deliveries land in the tenant's identity directory, and
101
+ `door.settings(env, node)` reads them back. Read settings that way and never off
102
+ `env` directly: an `envSpec` default rides as a worker binding shared by
102
103
  every install of one serving script, so `env.FOO` is the same string for every
103
104
  tenant no matter what any of them saved. Declare a setting once, in
104
105
  `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,21 @@ import {
56
37
  RouterAssertionError,
57
38
  invocationLog,
58
39
  } from '@substrat-run/vertical-host';
40
+ import { IdentityDO, workerDoor } from '@substrat-run/vertical-host/worker-door';
59
41
  import { MODULES, OWNER_ROLE_KEY, ROLES, permissions } from './provision.js';
60
42
  import { SHOP_ENV } from './manifest.js';
61
43
  import { mountApi } from './routes.js';
62
- import { AUTH_CONFIG_KEY, ConfigDO, type ConfigDo } from './config-do.js';
63
44
 
64
45
  /** The scope-DO class = the app binary: kernel + engines + this vertical, bundled. */
65
46
  export const ScopeDO = defineScopeDO(MODULES, {}, { permissions });
66
47
 
67
48
  /**
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.
49
+ * The tenant's identity directory: who is bound to what, the owner seat, and the settings the
50
+ * platform delivers. Declared as a store in package.json `substrat.runtimeNeeds.stores`, like
51
+ * `ScopeDO` above and `SweeperDO` below. Re-exported because workerd resolves a DO class from the
52
+ * ENTRY module's exports.
72
53
  */
73
- export { ConfigDO };
54
+ export { IdentityDO };
74
55
 
75
56
  /**
76
57
  * The deployment's own timer (#461): a roster-keeping singleton whose alarm runs
@@ -117,8 +98,8 @@ interface Env {
117
98
  SCOPE: DurableObjectNamespace;
118
99
  /** The roster-keeping sweep singleton — the deployment's own timer (#461). */
119
100
  SWEEPER: DurableObjectNamespace;
120
- /** Per-instance config delivered by the platform (`/internal/configure`). */
121
- CONFIG: DurableObjectNamespace;
101
+ /** The tenant's identity directory, and what the platform delivers to this instance. */
102
+ AUTH: DurableObjectNamespace<IdentityDO>;
122
103
  /** Local `wrangler dev` only: when 'true', fall back to DEV_NODE if no router
123
104
  * asserted a node. Addresses an instance; authenticates nobody. */
124
105
  ALLOW_DEV_NODE?: string;
@@ -152,75 +133,17 @@ function hostFor(env: Env): CloudflareScopeHost {
152
133
  return host;
153
134
  }
154
135
 
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(),
136
+ /** Who is calling, for every route below. It hands an operation the caller's verified address. */
137
+ const door = workerDoor<Env>({
138
+ directory: (env, node) => env.AUTH.get(env.AUTH.idFromName(node.tenantId)),
139
+ nodeFor,
140
+ hostFor,
141
+ envSpec: SHOP_ENV,
170
142
  });
171
143
 
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
- /**
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:
201
- *
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.
210
- *
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.
213
- */
214
- async function authenticatedPrincipal(_req: Request, _env: Env): Promise<PrincipalId | null> {
215
- return null; // ← wire real auth here (see the two steps above)
216
- }
217
-
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, {
144
+ /** The caller's scope stub. 401 if nobody. */
145
+ function stub(c: Context<{ Bindings: Env }>): Promise<ScopeStub> {
146
+ return door.scope(c, {
224
147
  // An operation that called `ctx.requestPlatform`, or committed an event of a type this
225
148
  // vertical EXPORTS (whether or not another app imports it yet), flags its response. The
226
149
  // router then has the platform act on this scope within seconds instead of at the next
@@ -231,27 +154,6 @@ async function stub(c: Context<{ Bindings: Env }>): Promise<ScopeStub> {
231
154
  });
232
155
  }
233
156
 
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
157
  const app = new Hono<{ Bindings: Env }>();
256
158
 
257
159
  // FIRST, before any route: Hono composes handlers in registration order and stops at the
@@ -269,16 +171,9 @@ app.use(
269
171
  }),
270
172
  );
271
173
 
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
- });
174
+ // Sign-in: the login round-trip at `/api/auth/*`, who is signed in at `/api/me`, and the owner
175
+ // seat at `/api/claim-owner`. Accounts and passwords live at the issuer, not here.
176
+ door.mount(app);
282
177
 
283
178
  // ── The vertical's API — the SAME table `server.ts` mounts (src/routes.ts) ───
284
179
  // Including `/api/invoke`. Mounted BEFORE the platform surface: Hono keeps only the
@@ -293,35 +188,23 @@ mountApi(app, stub);
293
188
  // and bookmarks/rewind — plus the guaranteed { error } envelope is authored ONCE
294
189
  // in @substrat-run/vertical-host (issue #510); mount it and it cannot drift.
295
190
  //
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.
191
+ // The hooks keep the deployment's sweep roster (#461) in step: a newly provisioned scope joins it
192
+ // (so its schedules run), and a deleted one leaves it. The door's hooks do the rest: the owner seat
193
+ // at provision, and the settings the dashboard's Env and Identity tabs deliver.
302
194
  mountPlatformSurface<Env>(app, {
303
195
  platformSecret: (env) => env.PLATFORM_SECRET,
304
196
  hostFor,
305
197
  roles: ROLES,
306
198
  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.
199
+ ...door.platform,
310
200
  onProvision: async (env, b) => {
201
+ await door.platform.onProvision(env, b);
311
202
  await sweeper(env).noteScope(b.tenantId, b.scopeId);
312
203
  },
313
- onDeleteScope: async (env, s) => {
204
+ onDeleteScope: async (env, s, tenantId) => {
205
+ await door.platform.onDeleteScope(env, s, tenantId);
314
206
  await sweeper(env).forgetScope(s);
315
207
  },
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
208
  });
326
209
 
327
210
  // 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
- }