export type AccountKey = 'ingest' | 'query'; export type Account = { email: string; token: string }; export type Intent = { email: string; rawFile: string; captureId: string }; export type Capability = { role: string; searchHTTP: number; searchHasRows: boolean; ingestHTTP: number; adminRotateHTTP: number }; export type CreateResult = { status: number | null; body: any }; export type BootstrapPorts = { readIndex(): Promise | undefined>; readAccount(key: AccountKey): Promise; readIntent(key: AccountKey): Promise; makeIntent(key: AccountKey): Intent; claimIntent(key: AccountKey, intent: Intent): Promise; readCaptured(intent: Intent): Promise; create(key: AccountKey, intent: Intent): Promise; saveAccount(key: AccountKey, account: Account): Promise; verify(key: AccountKey, account: Account): Promise; publishIndex(accounts: Record): Promise; publishDerived(accounts: Record): Promise; }; export const accountEmail = (key: AccountKey) => 'vp6-' + key + '@lab.invalid'; export function createAccountBootstrap(ports: BootstrapPorts) { if (Object.values(ports).some(port => typeof port !== 'function')) throw new Error('Required bootstrap ports missing'); return async () => { let accounts = await ports.readIndex(); if (!accounts) { accounts = {} as Record; for (const key of ['ingest', 'query'] as const) { const response = await ports.create(key, ports.makeIntent(key)); if (response.status !== 200 || response.body?.code !== 200 || response.body?.user !== accountEmail(key) || typeof response.body?.token !== 'string') throw new Error('Native create shape invalid'); accounts[key] = { email: response.body.user, token: response.body.token }; } await ports.publishIndex(accounts); } const proofs = []; for (const key of ['ingest', 'query'] as const) { const proof = await ports.verify(key, accounts[key]); if (proof.adminRotateHTTP === 200) throw new Error('Administrative mutation unexpectedly allowed'); proofs.push({ principal: key, ...proof }); } await ports.publishDerived(accounts); return { accounts, proofs }; }; }