// THE STATE SYSTEM (docs/concepts/the-model.md): what a write does at the // head of a twin's log, and how the tree is kept current. Two implementations of one interface, // bound per twin per world: // simulated — apply appends the entry and the tree is the projection; refresh is nothing. That // is every twin with no root, and every line of the write path as it stands. // real — the twin has a ROOT: the vendor's real account. Apply performs the entry against // the vendor with the sealed credential (the pack's perform adapter over the kernel // executor) and lands the receipt on the parent log; refresh fills the parent log // from the vendor (the pack's refresh adapter). Reads never egress. // The binding is a file in the twin's state dir (`root.json`), written by `volter twin // root`, read here — no env var, no pack code. The adapters come from the pack's descriptor // (`stateSystem`), registered by whoever mounts the twin. // CHECKS run before any entry is performed: a check that fails lands the entry as `refused` with // its reason and the deploy stops there. Checks are the world's files; the runtime loads them. import { dirname, join } from 'node:path'; import type { TwinAuthStrategy } from './executor.ts'; import type { TwinAction } from './actions.ts'; import type { PerformAction } from './head.ts'; import type { RemoteExecute } from './remote-execute.ts'; import type { TwinResource } from './serve.ts'; import { worldPaths } from './storage.ts'; import { getActiveWorldStore } from './world-store.ts'; export type DeployPolicy = 'auto' | 'gated' | 'hold'; /** A twin's root: the vendor's real account. Key-free; the credential is sealed elsewhere. */ export type RootConfig = { /** the vendor's API, or the one resource the account is (`https://api.github.com/repos/o/r`) */ url: string; deploy: DeployPolicy; /** the world's override of the pack's refresh posture: an interval, and the least time between on-demand refreshes */ refresh?: { every?: string; webhook?: boolean; atMost?: string }; /** the one resource the account is, under `url` — `repos/acme/web` for GitHub — when the vendor's * adapters need it named; the adapters see `url/scope` as their origin */ scope?: string; /** every pull through this root is pseudonymized (architecture, "A real account's data"), with the key sealed in the * root's credential (its `pseudonymKey`); a pull is refused while the credential holds none */ pseudonymize?: true; }; export function rootPath(service: string, root?: string): string { return join(dirname(worldPaths(service, root).events), 'root.json'); } export function readRoot(service: string, root?: string): RootConfig | null { const raw = getActiveWorldStore().read(rootPath(service, root)); return raw === null ? null : (JSON.parse(raw) as RootConfig); } export function writeRoot(service: string, config: RootConfig, root?: string): void { const path = rootPath(service, root); getActiveWorldStore().mkdir(dirname(path)); getActiveWorldStore().writeAtomic(path, `${JSON.stringify(config, null, 2)}\n`); } export function clearRoot(service: string, root?: string): void { const path = rootPath(service, root); if (getActiveWorldStore().exists(path)) getActiveWorldStore().remove(path); } /** The pack's half of the real state system. `perform` applies one entry against the vendor; * `refresh` observes the vendor into the parent log (it folds through the kernel — a pack never * writes a root log by hand); `ingest` folds one signed webhook. All over the kernel executor. */ export type StateSystemAdapters = { perform?: PerformAction; refresh?: (execute: RemoteExecute, opts: { root?: string; origin?: string; credential?: string; scope?: string }) => Promise; ingest?: (request: Request, ctx: { root?: string; secret?: string }) => Response | Promise; /** Why a recorded write is the World's own and sent nowhere, or undefined when perform sends it: a unit of the pack that * declares `vendorBacked.none` beside lanes that are vendor-backed (PlanetScale's SQL wire beside its API lane). */ unsent?: (input: Record | undefined) => string | undefined; }; const adapters = new Map(); /** Register a twin's adapters (the mounting host does this from the pack's descriptor or its * anchored exports). Replaces any earlier registration for the service. */ export function registerStateSystem(service: string, a: StateSystemAdapters): void { adapters.set(service, a); } export function stateSystemFor(service: string): StateSystemAdapters | undefined { return adapters.get(service); } export function clearStateSystems(): void { adapters.clear(); authStrategies.clear(); } /** HOW EACH VENDOR AUTHENTICATES, registered from the pack's descriptor by `registerPack` — the * same shape as the adapters above, and it lives here rather than in the pack registry so the * head can read it without importing one (there is no cycle to argue about). Absent means header * replacement, which is what the executor has always done. */ const authStrategies = new Map(); export function registerAuthStrategy(service: string, a: TwinAuthStrategy): void { authStrategies.set(service, a); } export function authStrategyFor(service: string): TwinAuthStrategy | undefined { return authStrategies.get(service); } /** A check: deterministic, sees the entry and the tree, answers pass or fail with a reason. */ /** A check may answer at once or later: a hosted World runs its checks in an isolate of their own, * reached over RPC. */ export type CheckResult = { ok: true } | { ok: false; reason: string }; export type Check = { name: string; run: (entry: TwinAction, tree: TwinResource[]) => CheckResult | Promise }; export type CheckVerdict = { name: string; reason: string } | null; /** Run every check over one entry; the first failure is the verdict. */ export async function runChecks(checks: Check[], entry: TwinAction, tree: TwinResource[]): Promise { for (const check of checks) { const result = await check.run(entry, tree); if (!result.ok) return { name: check.name, reason: result.reason }; } return null; } /** The one check every world ships: no credential-shaped string leaves for a vendor. Looks at * every string field of the entry (and its projection), so a token in a message body, a title or * a description is caught wherever the vendor would have put it. */ export const NO_SECRETS_CHECK: Check = { name: 'no-secrets', run(entry) { const CREDENTIAL = /\b(?:sk|pk|rk)[_-](?:live|test|prod)[_-][A-Za-z0-9]{8,}|\bxox[abprs]-[A-Za-z0-9-]{10,}|\bgh[pousr]_[A-Za-z0-9]{20,}|\bAKIA[0-9A-Z]{16}\b|\bsk-[A-Za-z0-9]{20,}|\bsk-(?:proj|ant)-[A-Za-z0-9_-]{16,}|-----BEGIN [A-Z ]*PRIVATE KEY-----/; const hit = (value: unknown, path: string): string | null => { if (typeof value === 'string') return CREDENTIAL.test(value) ? path : null; if (Array.isArray(value)) { for (const [i, v] of value.entries()) { const h = hit(v, `${path}[${i}]`); if (h) return h; } return null; } if (value && typeof value === 'object') { for (const [k, v] of Object.entries(value)) { const h = hit(v, path ? `${path}.${k}` : k); if (h) return h; } return null; } return null; }; const where = hit(entry.fields, '') ?? hit(entry.projection, 'projection') ?? hit(entry.input, 'input'); return where === null ? { ok: true } : { ok: false, reason: `a credential-shaped string in ${where}` }; }, }; // DEPLOY and the deployable set live in head.ts (`performEntries`, `deployableEntries`): the same // code performs a wire write at an `auto` head, a pushed changeset and `volter world deploy`.