@happyvertical/smrt-app-runtime 0.52.0 → 0.53.1
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/AGENTS.md +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +1 -1
- package/dist/smrt-knowledge.json +5 -5
- package/package.json +10 -10
package/AGENTS.md
CHANGED
|
@@ -30,6 +30,9 @@ Application infrastructure composition for the validated runtime profiles in
|
|
|
30
30
|
- Owner bootstrap creates normal `Person`, `User`, `Tenant`, owner `Role` /
|
|
31
31
|
`Membership`, and `Session` records in one transaction.
|
|
32
32
|
- Bootstrap is loopback-only. Only an HMAC of the short-lived token is stored.
|
|
33
|
+
A token that cannot claim fails a read-only preflight before role/catalog
|
|
34
|
+
seeding (#3323); the claim transaction's conditional UPDATE stays the
|
|
35
|
+
authority for single use, expiry, and concurrency.
|
|
33
36
|
- Background jobs and application-defined paid capabilities are default-off.
|
|
34
37
|
- The embedded runner reuses `TaskRunner`; it is not a second job contract.
|
|
35
38
|
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAoBH,OAAO,EACL,KAAK,0BAA0B,EAC/B,KAAK,wBAAwB,EAE9B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,UAAU,EAAE,KAAK,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAG7E,OAAO,EAML,cAAc,EAIf,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,KAAK,iBAAiB,EAAe,MAAM,oBAAoB,CAAC;AAEzE,cAAc,uBAAuB,CAAC;AACtC,cAAc,0BAA0B,CAAC;AAwDzC,yEAAyE;AACzE,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC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B;AAYD;;GAEG;AACH,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,+BAA+B,GACvC,iBAAiB,CAgCnB;AAED;;;;;;GAMG;AACH,wBAAsB,iCAAiC,CACrD,OAAO,EAAE,8BAA8B,GACtC,OAAO,CAAC,0BAA0B,CAAC,CAsFrC;AAeD,gFAAgF;AAChF,MAAM,WAAW,uBAAuB;IACtC,QAAQ,CAAC,EAAE,EAAE,iBAAiB,CAAC;IAC/B,QAAQ,CAAC,KAAK,EAAE,iBAAiB,CAAC;IAClC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,eAAe,EAAE,0BAA0B,CAAC;IACrD,QAAQ,CAAC,qBAAqB,EAAE,OAAO,CAAC;IACxC,QAAQ,CAAC,uBAAuB,EAAE,OAAO,CAAC;IAC1C,yBAAyB,IAAI,OAAO,CAAC,6BAA6B,GAAG,IAAI,CAAC,CAAC;IAC3E,yBAAyB,IAAI,OAAO,CAAC,6BAA6B,CAAC,CAAC;IACpE,UAAU,CAAC,KAAK,EAAE,oBAAoB,GAAG,OAAO,CAAC,qBAAqB,CAAC,CAAC;IACxE,cAAc,CACZ,SAAS,EAAE,MAAM,GAChB,UAAU,CAAC,cAAc,CAAC,oBAAoB,CAAC,CAAC,CAAC;IACpD,uBAAuB,CAAC,MAAM,CAAC,EAAE,gBAAgB,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;IACxE,WAAW,IAAI,OAAO,CAAC,uBAAuB,CAAC,CAAC;CACjD;AA43CD,6CAA6C;AAC7C,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAS3D;AAED,+EAA+E;AAC/E,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAczD"}
|
package/dist/index.js
CHANGED
|
@@ -1070,6 +1070,7 @@ var InitializedLocalApplicationRuntime = class {
|
|
|
1070
1070
|
const tokenHash = await this.hashBootstrapToken(input.token);
|
|
1071
1071
|
const now = this.now();
|
|
1072
1072
|
const nowIso = now.toISOString();
|
|
1073
|
+
if (!await isBootstrapTokenClaimable(this.db, tokenHash, nowIso)) await throwBootstrapClaimFailure(this.db, now);
|
|
1073
1074
|
await (await RoleCollection.create({ db: this.db })).seedSystemRoles({ seedPermissions: true });
|
|
1074
1075
|
return this.db.transaction(async (tx) => {
|
|
1075
1076
|
if ((await tx.query(`UPDATE ${BOOTSTRAP_TABLE}
|
|
@@ -1231,6 +1232,15 @@ async function throwBootstrapClaimFailure(db, now) {
|
|
|
1231
1232
|
if (!expiresAt || expiresAt.getTime() <= now.getTime()) throw new LocalRuntimeError("bootstrap_expired", "The local owner bootstrap invitation has expired.");
|
|
1232
1233
|
throw new LocalRuntimeError("bootstrap_invalid", "The local owner bootstrap token is invalid.");
|
|
1233
1234
|
}
|
|
1235
|
+
async function isBootstrapTokenClaimable(db, tokenHash, nowIso) {
|
|
1236
|
+
return (await db.query(`SELECT 1 AS claimable
|
|
1237
|
+
FROM ${BOOTSTRAP_TABLE}
|
|
1238
|
+
WHERE slot = 1
|
|
1239
|
+
AND token_hash = ?
|
|
1240
|
+
AND consumed_at IS NULL
|
|
1241
|
+
AND expires_at > ?
|
|
1242
|
+
LIMIT 1`, tokenHash, nowIso)).rows.length > 0;
|
|
1243
|
+
}
|
|
1234
1244
|
async function readBootstrapRow(db) {
|
|
1235
1245
|
return (await db.query(`SELECT expires_at, consumed_at
|
|
1236
1246
|
FROM ${BOOTSTRAP_TABLE}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/deployed-runtime.ts","../src/runtime-diagnostics.ts","../src/index.ts"],"sourcesContent":["/**\n * Application-side composition for public self-hosted and managed-cloud\n * runtimes. Provider credentials and vendor clients remain in their owning\n * adapters; this module validates the selected seams, owns the PostgreSQL\n * connection lifecycle, and exposes orchestration-safe diagnostics.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nimport {\n type ApplicationRuntimeProfile,\n type AssetStorageProvider,\n type AuthenticationProvider,\n type ResolvedApplicationRuntime,\n type RuntimeProviderOverrides,\n resolveApplicationRuntime,\n type SecretProvider,\n} from '@happyvertical/smrt-config';\nimport {\n ScheduleRunner,\n type ScheduleRunnerConfig,\n TaskRunner,\n type TaskRunnerConfig,\n} from '@happyvertical/smrt-jobs';\nimport { SessionService } from '@happyvertical/smrt-users';\nimport type { DatabaseInterface } from '@happyvertical/sql';\n\nexport type DeployedApplicationRuntimeProfile = Exclude<\n ApplicationRuntimeProfile,\n 'local'\n>;\n\nexport type PublicAuthenticationProvider = Exclude<\n AuthenticationProvider,\n 'owner-bootstrap'\n>;\n\nexport type DeployedRuntimeComponent =\n | 'database'\n | 'authentication'\n | 'assets'\n | 'secrets';\n\n/**\n * A provider-owned readiness boundary.\n *\n * The callback should prove that required configuration is present and that\n * the provider is usable. It must not return credentials or secret values.\n */\nexport interface DeployedProviderBinding<Provider extends string> {\n readonly provider: Provider;\n readonly readiness: () => Promise<void>;\n}\n\n/** PostgreSQL connection factory. URLs and credentials stay in this adapter. */\nexport interface DeployedDatabaseBinding {\n readonly engine: 'postgres';\n readonly connect: () => Promise<DatabaseInterface>;\n readonly readiness?: (db: DatabaseInterface) => Promise<void>;\n /**\n * Provider-owned cleanup boundary, required before a connection is opened.\n * Keeping cleanup on the binding also covers malformed connection handles.\n */\n readonly close: (db: DatabaseInterface) => Promise<void>;\n}\n\nexport interface DeployedApplicationRuntimeOptions {\n readonly profile: DeployedApplicationRuntimeProfile;\n /** Validated selector overrides; never put credentials in this object. */\n readonly providers?: RuntimeProviderOverrides;\n readonly database: DeployedDatabaseBinding;\n readonly authentication: DeployedProviderBinding<PublicAuthenticationProvider>;\n readonly assets: DeployedProviderBinding<AssetStorageProvider>;\n readonly secrets: DeployedProviderBinding<SecretProvider>;\n /** Explicit, idempotent application migration hook. */\n readonly prepareDatabase?: (db: DatabaseInterface) => Promise<void>;\n}\n\nexport interface DeployedProviderDiagnostic {\n readonly provider: string;\n readonly configured: true;\n}\n\nexport interface DeployedRuntimeDiagnostics {\n readonly schemaVersion: 1;\n readonly runtime: ResolvedApplicationRuntime;\n readonly providers: {\n readonly database: DeployedProviderDiagnostic;\n readonly authentication: DeployedProviderDiagnostic;\n readonly assets: DeployedProviderDiagnostic;\n readonly secrets: DeployedProviderDiagnostic;\n };\n readonly tenancy: {\n readonly mode: 'single-tenant' | 'multi-tenant';\n readonly context: 'defaulted' | 'required';\n readonly isolation: 'application' | 'database-rls';\n readonly rootTenantFallback: 'disabled';\n };\n readonly workers: {\n readonly topology: 'external' | 'scalable';\n readonly taskProcess: 'separate';\n readonly scheduleProcess: 'separate';\n readonly replicas: 'operator-managed' | 'horizontal';\n };\n readonly secretValuesIncluded: false;\n}\n\nexport interface DeployedRuntimeHealth {\n readonly schemaVersion: 1;\n readonly profile: DeployedApplicationRuntimeProfile;\n readonly status: 'healthy' | 'stopped';\n}\n\nexport interface DeployedComponentReadiness {\n readonly status: 'ready' | 'not-ready';\n}\n\nexport interface DeployedRuntimeReadiness {\n readonly schemaVersion: 1;\n readonly profile: DeployedApplicationRuntimeProfile;\n readonly status: 'ready' | 'not-ready';\n readonly components: Readonly<\n Record<DeployedRuntimeComponent, DeployedComponentReadiness>\n >;\n readonly secretValuesIncluded: false;\n}\n\nexport type DeployedRuntimeErrorCode =\n | 'invalid_configuration'\n | 'provider_mismatch'\n | 'provider_unavailable'\n | 'tenant_context_required'\n | 'tenant_context_unauthorized'\n | 'runtime_stopped';\n\n/** Stable failure that never includes a provider's underlying error text. */\nexport class DeployedRuntimeError extends Error {\n constructor(\n readonly code: DeployedRuntimeErrorCode,\n message: string,\n readonly component?: DeployedRuntimeComponent,\n ) {\n super(message);\n this.name = 'DeployedRuntimeError';\n }\n}\n\n/** Startup failure that retains the only safe retry path for database cleanup. */\nexport class DeployedRuntimeCleanupError extends DeployedRuntimeError {\n private cleaned = false;\n private cleanupAttempt?: Promise<void>;\n\n constructor(private readonly cleanup: () => Promise<void>) {\n super(\n 'provider_unavailable',\n \"The database connection could not be closed after startup failed; retry cleanup and inspect the provider's private logs.\",\n 'database',\n );\n this.name = 'DeployedRuntimeCleanupError';\n }\n\n async retryCleanup(): Promise<void> {\n if (this.cleaned) return;\n if (!this.cleanupAttempt) {\n this.cleanupAttempt = Promise.resolve()\n .then(() => this.cleanup())\n .then(() => {\n this.cleaned = true;\n })\n .catch(() => {\n throw this;\n })\n .finally(() => {\n this.cleanupAttempt = undefined;\n });\n }\n return this.cleanupAttempt;\n }\n}\n\nexport interface DeployedApplicationRuntime {\n readonly db: DatabaseInterface;\n readonly resolvedRuntime: ResolvedApplicationRuntime;\n restoreSession(\n sessionId: string,\n ): ReturnType<SessionService['loadSessionContext']>;\n createTaskWorker(config?: TaskRunnerConfig): Promise<TaskRunner>;\n createScheduleWorker(config?: ScheduleRunnerConfig): Promise<ScheduleRunner>;\n diagnostics(): DeployedRuntimeDiagnostics;\n health(): DeployedRuntimeHealth;\n readiness(): Promise<DeployedRuntimeReadiness>;\n close(): Promise<void>;\n}\n\ninterface ValidatedBindings {\n database: DeployedDatabaseBinding;\n authentication: DeployedProviderBinding<PublicAuthenticationProvider>;\n assets: DeployedProviderBinding<AssetStorageProvider>;\n secrets: DeployedProviderBinding<SecretProvider>;\n}\n\n/**\n * Initialize a self-hosted or cloud application composition.\n *\n * Configuration and provider identity are validated before a connection is\n * opened. Provider readiness and database migrations complete before the\n * runtime is returned. A failed initialization closes the acquired connection.\n */\nexport async function initializeDeployedApplicationRuntime(\n options: DeployedApplicationRuntimeOptions,\n): Promise<DeployedApplicationRuntime> {\n const resolvedRuntime = resolveDeployedRuntime(options);\n const bindings = validateBindings(options, resolvedRuntime);\n const prepareDatabase = snapshotPrepareDatabase(options);\n\n await checkProvider('authentication', () =>\n bindings.authentication.readiness(),\n );\n await checkProvider('assets', () => bindings.assets.readiness());\n await checkProvider('secrets', () => bindings.secrets.readiness());\n\n let db: DatabaseInterface | undefined;\n try {\n db = await bindings.database.connect();\n } catch {\n throw unavailable('database');\n }\n let validDatabase = false;\n try {\n validDatabase = isDatabaseInterface(db);\n } catch {\n // Treat throwing accessors on an untrusted handle as malformed.\n }\n if (!validDatabase) {\n await cleanupAfterStartupFailure(\n bindings.database,\n db,\n new DeployedRuntimeError(\n 'invalid_configuration',\n 'The database adapter did not return a valid database connection.',\n 'database',\n ),\n );\n }\n try {\n await checkDatabase(bindings.database, db);\n } catch (error) {\n await cleanupAfterStartupFailure(bindings.database, db, error);\n }\n try {\n await prepareDatabase?.(db);\n } catch {\n await cleanupAfterStartupFailure(\n bindings.database,\n db,\n new DeployedRuntimeError(\n 'provider_unavailable',\n 'The PostgreSQL migration step failed; inspect the application migration logs.',\n 'database',\n ),\n );\n }\n\n return new InitializedDeployedApplicationRuntime(\n db,\n resolvedRuntime,\n bindings,\n );\n}\n\nfunction resolveDeployedRuntime(\n options: DeployedApplicationRuntimeOptions,\n): ResolvedApplicationRuntime {\n let plainOptions = false;\n try {\n plainOptions = isPlainRecord(options);\n } catch {\n // Proxies and throwing prototype traps are invalid options.\n }\n if (!plainOptions) {\n throw new DeployedRuntimeError(\n 'invalid_configuration',\n 'Deployed runtime options must be an object.',\n );\n }\n let profile: unknown;\n let providers: RuntimeProviderOverrides | undefined;\n try {\n profile = options.profile;\n providers = options.providers;\n } catch {\n throw new DeployedRuntimeError(\n 'invalid_configuration',\n 'Deployed runtime options could not be read safely.',\n );\n }\n if (profile !== 'self-hosted' && profile !== 'cloud') {\n throw new DeployedRuntimeError(\n 'invalid_configuration',\n 'Deployed runtime initialization requires the self-hosted or cloud profile.',\n );\n }\n try {\n return resolveApplicationRuntime({ profile, providers });\n } catch {\n throw new DeployedRuntimeError(\n 'invalid_configuration',\n 'Deployed runtime provider options could not be read safely.',\n );\n }\n}\n\nfunction validateBindings(\n options: DeployedApplicationRuntimeOptions,\n runtime: ResolvedApplicationRuntime,\n): ValidatedBindings {\n const databaseSource = readBindingOption(options, 'database', 'database');\n const database = requireObjectBinding<DeployedDatabaseBinding>(\n databaseSource,\n 'database',\n );\n let engine: unknown;\n let connect: unknown;\n let readiness: unknown;\n let close: unknown;\n try {\n engine = database.engine;\n connect = database.connect;\n readiness = database.readiness;\n close = database.close;\n } catch {\n throw invalidBinding('database');\n }\n requireFunction(connect, 'database', 'connect');\n requireOptionalFunction(readiness, 'database', 'readiness');\n requireFunction(close, 'database', 'close');\n if (engine !== runtime.providers.database.engine) {\n throw mismatch('database', runtime.providers.database.engine);\n }\n const databaseSnapshot: DeployedDatabaseBinding = Object.freeze({\n engine: engine as 'postgres',\n connect: bindCallback(\n connect as DeployedDatabaseBinding['connect'],\n database,\n 'database',\n ),\n readiness:\n typeof readiness === 'function'\n ? bindCallback(\n readiness as NonNullable<DeployedDatabaseBinding['readiness']>,\n database,\n 'database',\n )\n : undefined,\n close: bindCallback(\n close as DeployedDatabaseBinding['close'],\n database,\n 'database',\n ),\n });\n\n const authentication = requireProviderBinding(\n readBindingOption(options, 'authentication', 'authentication'),\n 'authentication',\n runtime.providers.authentication.provider,\n ) as DeployedProviderBinding<PublicAuthenticationProvider>;\n const assets = requireProviderBinding(\n readBindingOption(options, 'assets', 'assets'),\n 'assets',\n runtime.providers.assets.provider,\n ) as DeployedProviderBinding<AssetStorageProvider>;\n const secrets = requireProviderBinding(\n readBindingOption(options, 'secrets', 'secrets'),\n 'secrets',\n runtime.providers.secrets.provider,\n ) as DeployedProviderBinding<SecretProvider>;\n\n return {\n database: databaseSnapshot,\n authentication,\n assets,\n secrets,\n };\n}\n\nfunction snapshotPrepareDatabase(\n options: DeployedApplicationRuntimeOptions,\n): DeployedApplicationRuntimeOptions['prepareDatabase'] {\n let prepareDatabase: unknown;\n try {\n prepareDatabase = options.prepareDatabase;\n } catch {\n throw invalidBinding('database');\n }\n requireOptionalFunction(prepareDatabase, 'database', 'prepareDatabase');\n return typeof prepareDatabase === 'function'\n ? bindCallback(\n prepareDatabase as NonNullable<\n DeployedApplicationRuntimeOptions['prepareDatabase']\n >,\n options,\n 'database',\n )\n : undefined;\n}\n\nfunction readBindingOption(\n options: DeployedApplicationRuntimeOptions,\n field: 'database' | 'authentication' | 'assets' | 'secrets',\n component: DeployedRuntimeComponent,\n): unknown {\n try {\n return options[field];\n } catch {\n throw invalidBinding(component);\n }\n}\n\nfunction requireProviderBinding(\n value: unknown,\n component: Exclude<DeployedRuntimeComponent, 'database'>,\n expectedProvider: string,\n): DeployedProviderBinding<string> {\n const binding = requireObjectBinding<DeployedProviderBinding<string>>(\n value,\n component,\n );\n let provider: unknown;\n let readiness: unknown;\n try {\n provider = binding.provider;\n readiness = binding.readiness;\n } catch {\n throw invalidBinding(component);\n }\n if (provider !== expectedProvider) {\n throw mismatch(component, expectedProvider);\n }\n requireFunction(readiness, component, 'readiness');\n return Object.freeze({\n provider: provider as string,\n readiness: bindCallback(\n readiness as DeployedProviderBinding<string>['readiness'],\n binding,\n component,\n ),\n });\n}\n\nfunction requireObjectBinding<T>(\n value: unknown,\n component: DeployedRuntimeComponent,\n): T {\n let valid = false;\n try {\n valid =\n typeof value === 'object' && value !== null && !Array.isArray(value);\n } catch {\n // Revoked proxies and throwing shape traps are invalid bindings.\n }\n if (!valid) {\n throw new DeployedRuntimeError(\n 'invalid_configuration',\n `The ${component} provider binding is required.`,\n component,\n );\n }\n return value as T;\n}\n\nfunction invalidBinding(\n component: DeployedRuntimeComponent,\n): DeployedRuntimeError {\n return new DeployedRuntimeError(\n 'invalid_configuration',\n `The ${component} provider binding could not be read safely.`,\n component,\n );\n}\n\nfunction bindCallback<T>(\n callback: T,\n receiver: unknown,\n component: DeployedRuntimeComponent,\n): T {\n try {\n return Reflect.apply(\n Function.prototype.bind,\n callback as (...args: never[]) => unknown,\n [receiver],\n ) as T;\n } catch {\n throw invalidBinding(component);\n }\n}\n\nfunction requireFunction(\n value: unknown,\n component: DeployedRuntimeComponent,\n field: string,\n): void {\n if (typeof value !== 'function') {\n throw new DeployedRuntimeError(\n 'invalid_configuration',\n `The ${component} provider requires a ${field} callback.`,\n component,\n );\n }\n}\n\nfunction requireOptionalFunction(\n value: unknown,\n component: DeployedRuntimeComponent,\n field: string,\n): void {\n if (value !== undefined) requireFunction(value, component, field);\n}\n\nfunction mismatch(\n component: DeployedRuntimeComponent,\n expectedProvider: string,\n): DeployedRuntimeError {\n return new DeployedRuntimeError(\n 'provider_mismatch',\n `The ${component} binding does not match the selected ${expectedProvider} provider.`,\n component,\n );\n}\n\nfunction unavailable(\n component: DeployedRuntimeComponent,\n): DeployedRuntimeError {\n return new DeployedRuntimeError(\n 'provider_unavailable',\n `The ${component} provider is not ready; inspect that provider's private logs.`,\n component,\n );\n}\n\nasync function checkProvider(\n component: Exclude<DeployedRuntimeComponent, 'database'>,\n check: () => Promise<void>,\n): Promise<void> {\n try {\n await check();\n } catch {\n throw unavailable(component);\n }\n}\n\nasync function checkDatabase(\n binding: DeployedDatabaseBinding,\n db: DatabaseInterface,\n): Promise<void> {\n try {\n await binding.readiness?.(db);\n const result = await db.query(\n \"SELECT current_setting('server_version_num') AS smrt_postgres_version\",\n );\n if (!isValidPostgresProbe(result)) throw new Error('invalid probe');\n } catch {\n throw unavailable('database');\n }\n}\n\nclass InitializedDeployedApplicationRuntime\n implements DeployedApplicationRuntime\n{\n private state: 'running' | 'closing' | 'close-failed' | 'stopped' = 'running';\n private closeAttempt?: Promise<void>;\n private readonly pendingReadinessChecks = new Set<Promise<unknown>>();\n private readonly pendingSessionRestorations = new Set<Promise<unknown>>();\n private readonly pendingWorkerInitializations = new Set<Promise<unknown>>();\n private readonly pendingWorkerOperations = new Set<Promise<unknown>>();\n private readonly lifecycleOperationContext = new AsyncLocalStorage<symbol>();\n private readonly activeLifecycleOperations = new Set<symbol>();\n private readonly workerCleanups = new Set<() => Promise<void>>();\n private readonly sessionService: SessionService;\n private sessionServiceReady?: Promise<void>;\n private readonly snapshot: DeployedRuntimeDiagnostics;\n\n constructor(\n readonly db: DatabaseInterface,\n readonly resolvedRuntime: ResolvedApplicationRuntime,\n private readonly bindings: ValidatedBindings,\n ) {\n this.snapshot = createDiagnostics(resolvedRuntime);\n this.sessionService = new SessionService({ db });\n }\n\n async restoreSession(sessionId: string) {\n this.assertRunning();\n const operation = this.beginLifecycleOperation(() =>\n this.restoreSessionWhileRunning(sessionId),\n );\n this.pendingSessionRestorations.add(operation);\n try {\n return await operation;\n } finally {\n this.pendingSessionRestorations.delete(operation);\n }\n }\n\n private async restoreSessionWhileRunning(sessionId: string) {\n let context: Awaited<ReturnType<SessionService['loadSessionContext']>>;\n try {\n await this.initializeSessionService();\n context = await this.sessionService.loadSessionContext(sessionId);\n } catch {\n throw unavailable('authentication');\n }\n this.assertRunning();\n if (\n context &&\n this.resolvedRuntime.providers.tenancy.context === 'required'\n ) {\n let tenantId: unknown;\n try {\n tenantId = context.tenantId;\n } catch {\n throw unavailable('authentication');\n }\n if (typeof tenantId !== 'string' || tenantId.trim().length === 0) {\n throw new DeployedRuntimeError(\n 'tenant_context_required',\n 'The authenticated session does not include the required tenant context.',\n 'authentication',\n );\n }\n let tenantAuthorized = false;\n try {\n const membership = context.membership;\n const authorization = context.tenantAuthorization;\n const membershipId = authorization?.membershipId;\n const validMembershipId =\n typeof membershipId === 'string' && membershipId.trim().length > 0;\n if (membership?.isActive() === true) {\n tenantAuthorized =\n validMembershipId &&\n membership.id === membershipId &&\n authorization?.inheritedFromTenantId === null;\n } else if (membership === null) {\n tenantAuthorized =\n validMembershipId &&\n typeof authorization?.inheritedFromTenantId === 'string' &&\n authorization.inheritedFromTenantId.trim().length > 0;\n }\n } catch {\n throw unavailable('authentication');\n }\n if (!tenantAuthorized) {\n throw new DeployedRuntimeError(\n 'tenant_context_unauthorized',\n 'The authenticated session is not authorized for its tenant context.',\n 'authentication',\n );\n }\n }\n return context;\n }\n\n async createTaskWorker(config: TaskRunnerConfig = {}): Promise<TaskRunner> {\n this.assertRunning();\n const operation = this.beginLifecycleOperation(() =>\n this.initializeTaskWorker(config),\n );\n this.pendingWorkerInitializations.add(operation);\n try {\n const runner = await operation;\n return this.retainWorker(runner);\n } finally {\n this.pendingWorkerInitializations.delete(operation);\n }\n }\n\n async createScheduleWorker(\n config: ScheduleRunnerConfig = {},\n ): Promise<ScheduleRunner> {\n this.assertRunning();\n const operation = this.beginLifecycleOperation(() =>\n this.initializeScheduleWorker(config),\n );\n this.pendingWorkerInitializations.add(operation);\n try {\n const runner = await operation;\n return this.retainWorker(runner);\n } finally {\n this.pendingWorkerInitializations.delete(operation);\n }\n }\n\n diagnostics(): DeployedRuntimeDiagnostics {\n return this.snapshot;\n }\n\n health(): DeployedRuntimeHealth {\n return Object.freeze({\n schemaVersion: 1 as const,\n profile: this.resolvedRuntime\n .profile as DeployedApplicationRuntimeProfile,\n status:\n this.state === 'running' ? ('healthy' as const) : ('stopped' as const),\n });\n }\n\n async readiness(): Promise<DeployedRuntimeReadiness> {\n if (this.state !== 'running')\n return createStoppedReadiness(this.resolvedRuntime.profile);\n\n const operation = this.beginLifecycleOperation(() =>\n this.checkReadinessWhileRunning(),\n );\n this.pendingReadinessChecks.add(operation);\n try {\n return await operation;\n } finally {\n this.pendingReadinessChecks.delete(operation);\n }\n }\n\n private async checkReadinessWhileRunning(): Promise<DeployedRuntimeReadiness> {\n const results = await Promise.all([\n probe(() => checkDatabase(this.bindings.database, this.db)),\n probe(() => this.bindings.authentication.readiness()),\n probe(() => this.bindings.assets.readiness()),\n probe(() => this.bindings.secrets.readiness()),\n ]);\n if (this.state !== 'running') {\n return createStoppedReadiness(this.resolvedRuntime.profile);\n }\n const [database, authentication, assets, secrets] = results;\n return freezeReadiness(\n this.resolvedRuntime.profile,\n { database, authentication, assets, secrets },\n results.every((result) => result.status === 'ready'),\n );\n }\n\n async close(): Promise<void> {\n const operationToken = this.lifecycleOperationContext.getStore();\n const requestedFromLifecycleOperation =\n operationToken !== undefined &&\n this.activeLifecycleOperations.has(operationToken);\n if (this.state === 'stopped') return;\n if (this.closeAttempt) {\n if (requestedFromLifecycleOperation) return;\n return this.closeAttempt;\n }\n\n this.state = 'closing';\n const pendingOperations = [\n ...this.pendingReadinessChecks,\n ...this.pendingSessionRestorations,\n ...this.pendingWorkerInitializations,\n ...this.pendingWorkerOperations,\n ];\n const shutdownToken = Symbol('deployed-runtime-shutdown');\n this.activeLifecycleOperations.add(shutdownToken);\n const attempt = Promise.resolve()\n .then(() =>\n this.lifecycleOperationContext.run(shutdownToken, async () => {\n await Promise.allSettled(pendingOperations);\n await this.cleanupWorkers();\n await this.closeConnection();\n }),\n )\n .finally(() => {\n this.activeLifecycleOperations.delete(shutdownToken);\n });\n this.closeAttempt = attempt.finally(() => {\n this.closeAttempt = undefined;\n });\n if (requestedFromLifecycleOperation) {\n // The lifecycle callback cannot await the shutdown pipeline without\n // deadlocking on itself. It receives an acknowledgement instead, but the\n // internally owned attempt still needs a rejection observer until an\n // outside caller can retry the failed cleanup.\n void this.closeAttempt.catch(() => undefined);\n return;\n }\n return this.closeAttempt;\n }\n\n private async initializeTaskWorker(\n config: TaskRunnerConfig,\n ): Promise<TaskRunner> {\n let runner: TaskRunner | undefined;\n try {\n runner = new TaskRunner(config);\n await runner.initialize(this.db);\n } catch {\n if (runner) await this.stopOrRetainUnreturnedWorker(runner);\n throw unavailable('database');\n }\n if (this.state !== 'running') {\n await this.stopOrRetainUnreturnedWorker(runner);\n this.assertRunning();\n }\n return runner;\n }\n\n private async initializeScheduleWorker(\n config: ScheduleRunnerConfig,\n ): Promise<ScheduleRunner> {\n let runner: ScheduleRunner | undefined;\n try {\n runner = new ScheduleRunner(config);\n await runner.initialize(this.db);\n } catch {\n if (runner) await this.stopOrRetainUnreturnedWorker(runner);\n throw unavailable('database');\n }\n if (this.state !== 'running') {\n await this.stopOrRetainUnreturnedWorker(runner);\n this.assertRunning();\n }\n return runner;\n }\n\n private async stopOrRetainUnreturnedWorker(runner: {\n stop(): Promise<void>;\n }): Promise<void> {\n const cleanup = () => runner.stop();\n try {\n await cleanup();\n } catch {\n this.workerCleanups.add(cleanup);\n }\n }\n\n private retainWorker<Runner extends TaskRunner | ScheduleRunner>(\n runner: Runner,\n ): Runner {\n const start = runner.start.bind(runner);\n const stop = runner.stop.bind(runner);\n let operationTail = Promise.resolve();\n const queueOperation = (callback: () => Promise<void>): Promise<void> => {\n const previous = operationTail;\n const operation = this.beginLifecycleOperation(async () => {\n await previous;\n await callback();\n });\n operationTail = operation.catch(() => undefined);\n this.pendingWorkerOperations.add(operation);\n void operation.then(\n () => {\n this.pendingWorkerOperations.delete(operation);\n },\n () => {\n this.pendingWorkerOperations.delete(operation);\n },\n );\n return operation;\n };\n const ownedStart = async (): Promise<void> => {\n this.assertRunning();\n return queueOperation(async () => {\n this.assertRunning();\n try {\n await start();\n this.assertRunning();\n } catch {\n // A runner can reject after it has made itself live (for example,\n // when a runner:started listener throws). Keep this cleanup inside\n // the tracked lifecycle operation so shutdown cannot call stop()\n // concurrently on the same runner.\n if (this.state === 'running') {\n try {\n await stop();\n } catch {\n // The runtime-owned cleanup is already retained in workerCleanups.\n }\n }\n if (this.state !== 'running') this.assertRunning();\n throw unavailable('database');\n }\n });\n };\n const ownedStop = (): Promise<void> =>\n queueOperation(async () => {\n try {\n await stop();\n } catch {\n throw unavailable('database');\n }\n });\n Object.defineProperties(runner, {\n start: {\n configurable: false,\n enumerable: false,\n value: ownedStart,\n writable: false,\n },\n stop: {\n configurable: false,\n enumerable: false,\n value: ownedStop,\n writable: false,\n },\n });\n this.workerCleanups.add(ownedStop);\n return runner;\n }\n\n private async cleanupWorkers(): Promise<void> {\n const cleanups = [...this.workerCleanups];\n const results = await Promise.allSettled(\n cleanups.map((cleanup) => Promise.resolve().then(cleanup)),\n );\n let cleanupFailed = false;\n for (const [index, result] of results.entries()) {\n if (result.status === 'fulfilled') {\n const cleanup = cleanups[index];\n if (cleanup) this.workerCleanups.delete(cleanup);\n } else cleanupFailed = true;\n }\n if (cleanupFailed) {\n this.state = 'close-failed';\n throw unavailable('database');\n }\n }\n\n private initializeSessionService(): Promise<void> {\n if (!this.sessionServiceReady) {\n this.sessionServiceReady = this.sessionService\n .initialize()\n .catch((error) => {\n this.sessionServiceReady = undefined;\n throw error;\n });\n }\n return this.sessionServiceReady;\n }\n\n private beginLifecycleOperation<T>(operation: () => Promise<T>): Promise<T> {\n const token = Symbol('deployed-runtime-operation');\n this.activeLifecycleOperations.add(token);\n return Promise.resolve()\n .then(() => this.lifecycleOperationContext.run(token, operation))\n .finally(() => {\n this.activeLifecycleOperations.delete(token);\n });\n }\n\n private async closeConnection(): Promise<void> {\n try {\n await this.bindings.database.close(this.db);\n this.state = 'stopped';\n } catch {\n this.state = 'close-failed';\n throw new DeployedRuntimeError(\n 'provider_unavailable',\n \"The database connection could not be closed; inspect the provider's private logs.\",\n 'database',\n );\n }\n }\n\n private assertRunning(): void {\n if (this.state !== 'running') {\n throw new DeployedRuntimeError(\n 'runtime_stopped',\n 'The deployed application runtime has already stopped.',\n );\n }\n }\n}\n\nfunction createDiagnostics(\n runtime: ResolvedApplicationRuntime,\n): DeployedRuntimeDiagnostics {\n const provider = (value: string): DeployedProviderDiagnostic =>\n Object.freeze({ provider: value, configured: true as const });\n return deepFreeze({\n schemaVersion: 1 as const,\n runtime,\n providers: {\n database: provider(runtime.providers.database.engine),\n authentication: provider(runtime.providers.authentication.provider),\n assets: provider(runtime.providers.assets.provider),\n secrets: provider(runtime.providers.secrets.provider),\n },\n tenancy: {\n mode: runtime.providers.tenancy.mode as 'single-tenant' | 'multi-tenant',\n context: runtime.providers.tenancy.context,\n isolation: runtime.providers.tenancy.isolation,\n rootTenantFallback: 'disabled' as const,\n },\n workers: {\n topology: runtime.providers.jobs.topology as 'external' | 'scalable',\n taskProcess: 'separate' as const,\n scheduleProcess: 'separate' as const,\n replicas:\n runtime.providers.jobs.topology === 'scalable'\n ? ('horizontal' as const)\n : ('operator-managed' as const),\n },\n secretValuesIncluded: false as const,\n });\n}\n\nasync function probe(\n check: () => Promise<void>,\n): Promise<DeployedComponentReadiness> {\n try {\n await check();\n return Object.freeze({ status: 'ready' as const });\n } catch {\n return Object.freeze({ status: 'not-ready' as const });\n }\n}\n\nfunction createStoppedReadiness(\n profile: ApplicationRuntimeProfile,\n): DeployedRuntimeReadiness {\n const stopped = Object.freeze({ status: 'not-ready' as const });\n return freezeReadiness(\n profile,\n {\n database: stopped,\n authentication: stopped,\n assets: stopped,\n secrets: stopped,\n },\n false,\n );\n}\n\nfunction freezeReadiness(\n profile: ApplicationRuntimeProfile,\n components: Record<DeployedRuntimeComponent, DeployedComponentReadiness>,\n ready: boolean,\n): DeployedRuntimeReadiness {\n return deepFreeze({\n schemaVersion: 1 as const,\n profile: profile as DeployedApplicationRuntimeProfile,\n status: ready ? ('ready' as const) : ('not-ready' as const),\n components,\n secretValuesIncluded: false as const,\n });\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isDatabaseInterface(value: unknown): value is DatabaseInterface {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { query?: unknown }).query === 'function'\n );\n}\n\nfunction isValidPostgresProbe(\n value: unknown,\n): value is { rows: Array<{ smrt_postgres_version: string }> } {\n if (typeof value !== 'object' || value === null) return false;\n const rows = (value as { rows?: unknown }).rows;\n if (!Array.isArray(rows) || rows.length !== 1) return false;\n const row = rows[0];\n if (typeof row !== 'object' || row === null) return false;\n const version = (row as { smrt_postgres_version?: unknown })\n .smrt_postgres_version;\n return typeof version === 'string' && /^\\d+$/.test(version);\n}\n\nasync function cleanupAfterStartupFailure(\n binding: DeployedDatabaseBinding,\n db: unknown,\n startupError: unknown,\n): Promise<never> {\n const cleanup = () => binding.close(db as DatabaseInterface);\n try {\n await cleanup();\n } catch {\n throw new DeployedRuntimeCleanupError(cleanup);\n }\n throw startupError;\n}\n\nfunction deepFreeze<T>(value: T, seen = new WeakSet<object>()): T {\n if (value && typeof value === 'object') {\n if (seen.has(value)) return value;\n seen.add(value);\n if (!Object.isFrozen(value)) Object.freeze(value);\n for (const child of Object.values(value as Record<string, unknown>)) {\n deepFreeze(child, seen);\n }\n }\n return value;\n}\n","import { createHash } from 'node:crypto';\n\nimport type { ApplicationRuntimeProfile } from '@happyvertical/smrt-config';\n\nexport const RUNTIME_DIAGNOSTICS_SCHEMA_VERSION = 1 as const;\nexport const MAX_RUNTIME_DIAGNOSTIC_TOOLS = 64;\nexport const MAX_RUNTIME_DIAGNOSTIC_ERRORS = 8;\nexport const RUNTIME_WORKER_FRESHNESS_SECONDS = 120;\n\nconst CAPABILITY_IDS = [\n 'asset-storage',\n 'authentication',\n 'background-jobs',\n 'database',\n 'paid-capabilities',\n 'secret-storage',\n] as const;\n\nconst ERROR_CODES = [\n 'authentication_unavailable',\n 'database_unavailable',\n 'migration_required',\n 'provider_unavailable',\n 'runtime_stopped',\n 'worker_stale',\n] as const;\n\nconst PROHIBITED_IDENTIFIER_PARTS = new Set([\n 'authorization',\n 'cookie',\n 'constructor',\n 'credential',\n 'email',\n 'hash',\n 'key',\n 'log',\n 'logs',\n 'password',\n 'path',\n 'record',\n 'prototype',\n 'secret',\n 'session',\n 'stack',\n 'tenant',\n 'token',\n 'url',\n 'user',\n]);\n\ntype CapabilityId = (typeof CAPABILITY_IDS)[number];\ntype CapabilityStatus = 'available' | 'disabled' | 'unavailable' | 'unknown';\ntype RuntimeDiagnosticErrorCode =\n | (typeof ERROR_CODES)[number]\n | 'runtime_error';\ntype WorkerTopology = 'embedded' | 'external' | 'inline' | 'scalable';\n\n/**\n * Versioned public diagnostics returned only after application authorization.\n * Every field is a fixed allowlist projection; this is intentionally not a\n * cleaned or serialized form of either private runtime diagnostics object.\n */\nexport interface RuntimeDiagnostics {\n readonly schemaVersion: 1;\n readonly profile: ApplicationRuntimeProfile | 'unknown';\n readonly health: 'healthy' | 'degraded' | 'stopped' | 'unknown';\n readonly schema: {\n readonly status: 'ready' | 'not-ready' | 'unknown';\n readonly migrations: 'current' | 'failed' | 'pending' | 'unknown';\n };\n readonly capabilities: readonly {\n readonly id: CapabilityId;\n readonly status: CapabilityStatus;\n }[];\n readonly tools: {\n readonly names: readonly string[];\n readonly count: number;\n readonly digest: string;\n };\n readonly operationalDifferences: {\n readonly backgroundJobs: 'disabled' | 'enabled';\n readonly workerTopology: WorkerTopology;\n };\n readonly worker: {\n readonly topology: WorkerTopology;\n readonly liveness: 'alive' | 'not-required' | 'stale' | 'unknown';\n readonly heartbeatAt: string | null;\n readonly observedAt: string;\n };\n readonly recentErrors: readonly {\n readonly code: RuntimeDiagnosticErrorCode;\n readonly at: string;\n }[];\n}\n\nexport interface RuntimeDiagnosticsProjectionInput {\n readonly profile?: unknown;\n readonly health?: unknown;\n readonly schema?: unknown;\n readonly capabilities?: unknown;\n readonly toolNames?: unknown;\n readonly worker?: unknown;\n readonly recentErrors?: unknown;\n /** Required explicit clock seam; the projector never reads the process clock. */\n readonly observedAt?: unknown;\n}\n\n/**\n * Project private local/deployed state into the deterministic public contract.\n * Unknown, oversized, nested, accessor-backed, or prohibited values are never\n * copied. Invalid error codes become `runtime_error` at ingestion.\n */\nexport function projectRuntimeDiagnostics(\n input: RuntimeDiagnosticsProjectionInput,\n): RuntimeDiagnostics {\n const source = plainRecord(input);\n const observedAtValue = read(source, 'observedAt');\n const observedAtMilliseconds = timestampMilliseconds(observedAtValue);\n const observedAt = coarseTimestamp(observedAtValue) ?? EPOCH;\n const profile = runtimeProfile(read(source, 'profile'));\n const worker = projectWorker(\n read(source, 'worker'),\n observedAt,\n observedAtMilliseconds,\n );\n const capabilities = projectCapabilities(read(source, 'capabilities'));\n const tools = canonicalTools(read(source, 'toolNames'));\n\n return deepFreeze({\n schemaVersion: RUNTIME_DIAGNOSTICS_SCHEMA_VERSION,\n profile,\n health: oneOf(read(source, 'health'), HEALTH_VALUES, 'unknown'),\n schema: projectSchema(read(source, 'schema')),\n capabilities,\n tools: {\n names: tools,\n count: tools.length,\n digest: createHash('sha256').update(tools.join('\\n')).digest('hex'),\n },\n operationalDifferences: {\n backgroundJobs:\n capabilityStatus(capabilities, 'background-jobs') === 'available'\n ? 'enabled'\n : 'disabled',\n workerTopology: worker.topology,\n },\n worker,\n recentErrors: projectErrors(read(source, 'recentErrors')),\n });\n}\n\nconst EPOCH = '1970-01-01T00:00:00.000Z';\nconst PROFILES = ['local', 'self-hosted', 'cloud', 'unknown'] as const;\nconst HEALTH_VALUES = ['healthy', 'degraded', 'stopped', 'unknown'] as const;\nconst SCHEMA_VALUES = ['ready', 'not-ready', 'unknown'] as const;\nconst MIGRATION_VALUES = ['current', 'failed', 'pending', 'unknown'] as const;\nconst CAPABILITY_VALUES = [\n 'available',\n 'disabled',\n 'unavailable',\n 'unknown',\n] as const;\nconst WORKER_TOPOLOGIES = [\n 'embedded',\n 'external',\n 'inline',\n 'scalable',\n] as const;\n\nfunction runtimeProfile(value: unknown): ApplicationRuntimeProfile | 'unknown' {\n return oneOf(value, PROFILES, 'unknown');\n}\n\nfunction projectSchema(value: unknown): RuntimeDiagnostics['schema'] {\n const source = plainRecord(value);\n return {\n status: oneOf(read(source, 'status'), SCHEMA_VALUES, 'unknown'),\n migrations: oneOf(read(source, 'migrations'), MIGRATION_VALUES, 'unknown'),\n };\n}\n\nfunction projectCapabilities(\n value: unknown,\n): RuntimeDiagnostics['capabilities'] {\n const source = plainRecord(value);\n return CAPABILITY_IDS.map((id) => ({\n id,\n status: oneOf(read(source, id), CAPABILITY_VALUES, 'unknown'),\n }));\n}\n\nfunction canonicalTools(value: unknown): readonly string[] {\n const names = new Set<string>();\n for (const candidate of safeArrayItems(\n value,\n MAX_RUNTIME_DIAGNOSTIC_TOOLS * 4,\n )) {\n if (typeof candidate !== 'string' || !isPublicIdentifier(candidate)) {\n continue;\n }\n names.add(candidate);\n }\n return [...names].sort().slice(0, MAX_RUNTIME_DIAGNOSTIC_TOOLS);\n}\n\nfunction isPublicIdentifier(value: string): boolean {\n if (\n value.length < 1 ||\n value.length > 80 ||\n !/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(value)\n ) {\n return false;\n }\n const parts = value.split(/[._-]/);\n return !parts.some((part) => PROHIBITED_IDENTIFIER_PARTS.has(part));\n}\n\nfunction projectWorker(\n value: unknown,\n observedAt: string,\n observedAtMilliseconds: number | null,\n): RuntimeDiagnostics['worker'] {\n const source = plainRecord(value);\n const topology = oneOf(read(source, 'topology'), WORKER_TOPOLOGIES, 'inline');\n const required = read(source, 'required') === true;\n const heartbeatValue = read(source, 'heartbeatAt');\n const heartbeatMilliseconds = timestampMilliseconds(heartbeatValue);\n const heartbeatAt = coarseTimestamp(heartbeatValue);\n let liveness: RuntimeDiagnostics['worker']['liveness'] = 'not-required';\n if (required) {\n liveness = 'unknown';\n if (heartbeatMilliseconds !== null && observedAtMilliseconds !== null) {\n const ageSeconds =\n (observedAtMilliseconds - heartbeatMilliseconds) / 1_000;\n if (ageSeconds >= 0) {\n liveness =\n ageSeconds <= RUNTIME_WORKER_FRESHNESS_SECONDS ? 'alive' : 'stale';\n }\n }\n }\n return { topology, liveness, heartbeatAt, observedAt };\n}\n\nfunction projectErrors(value: unknown): RuntimeDiagnostics['recentErrors'] {\n const errors: Array<RuntimeDiagnostics['recentErrors'][number]> = [];\n for (const candidate of safeArrayItems(\n value,\n MAX_RUNTIME_DIAGNOSTIC_ERRORS * 4,\n )) {\n const source = plainRecord(candidate);\n const at = coarseTimestamp(read(source, 'at'));\n if (!at) continue;\n const rawCode = read(source, 'code');\n const code: RuntimeDiagnosticErrorCode = ERROR_CODES.includes(\n rawCode as (typeof ERROR_CODES)[number],\n )\n ? (rawCode as (typeof ERROR_CODES)[number])\n : 'runtime_error';\n errors.push({ code, at });\n }\n return errors\n .sort((left, right) =>\n left.at === right.at\n ? left.code.localeCompare(right.code)\n : right.at.localeCompare(left.at),\n )\n .slice(0, MAX_RUNTIME_DIAGNOSTIC_ERRORS);\n}\n\nfunction capabilityStatus(\n capabilities: RuntimeDiagnostics['capabilities'],\n id: CapabilityId,\n): CapabilityStatus {\n return (\n capabilities.find((capability) => capability.id === id)?.status ?? 'unknown'\n );\n}\n\nfunction coarseTimestamp(value: unknown): string | null {\n const milliseconds = timestampMilliseconds(value);\n if (milliseconds === null) return null;\n const minute = Math.floor(milliseconds / 60_000) * 60_000;\n return new Date(minute).toISOString();\n}\n\nfunction timestampMilliseconds(value: unknown): number | null {\n try {\n if (!(typeof value === 'string' || value instanceof Date)) return null;\n const milliseconds =\n value instanceof Date ? value.getTime() : Date.parse(value);\n return Number.isFinite(milliseconds) ? milliseconds : null;\n } catch {\n return null;\n }\n}\n\nfunction oneOf<\n const Values extends readonly string[],\n Fallback extends Values[number],\n>(value: unknown, values: Values, fallback: Fallback): Values[number] {\n return typeof value === 'string' && values.includes(value as Values[number])\n ? (value as Values[number])\n : fallback;\n}\n\nfunction plainRecord(value: unknown): Record<string, unknown> | null {\n try {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return null;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null\n ? (value as Record<string, unknown>)\n : null;\n } catch {\n return null;\n }\n}\n\nfunction read(source: Record<string, unknown> | null, key: string): unknown {\n try {\n if (!source || !Object.hasOwn(source, key)) {\n return undefined;\n }\n return source[key];\n } catch {\n return undefined;\n }\n}\n\nfunction safeArrayItems(value: unknown, maximum: number): readonly unknown[] {\n try {\n if (!Array.isArray(value)) return [];\n const length = Math.min(value.length, maximum);\n if (!Number.isSafeInteger(length) || length < 0) return [];\n const items: unknown[] = [];\n for (let index = 0; index < length; index += 1) {\n try {\n items.push(value[index]);\n } catch {\n items.push(undefined);\n }\n }\n return items;\n } catch {\n return [];\n }\n}\n\nfunction deepFreeze<T>(value: T): T {\n if (value && typeof value === 'object') {\n Object.freeze(value);\n for (const child of Object.values(value as Record<string, unknown>)) {\n if (child && typeof child === 'object' && !Object.isFrozen(child)) {\n deepFreeze(child);\n }\n }\n }\n return value;\n}\n","/**\n * Safe, private, single-owner application runtime for the `local` profile.\n *\n * This Node-only subpath owns the small amount of operational composition that\n * does not belong in a generated application: user-owned paths, restrictive\n * local secret material, SQLite tuning, owner bootstrap, and an optional\n * embedded job runner. Domain schema preparation remains an explicit startup\n * step supplied by the application migration layer.\n */\n\nimport { execFile } from 'node:child_process';\nimport { createHash, createHmac, randomBytes } from 'node:crypto';\nimport {\n constants,\n type FileHandle,\n link,\n lstat,\n mkdir,\n open,\n readdir,\n realpath,\n rmdir,\n unlink,\n} from 'node:fs/promises';\nimport { homedir, platform } from 'node:os';\nimport { isAbsolute, parse, relative, resolve, sep } from 'node:path';\nimport { promisify } from 'node:util';\nimport { Worker } from 'node:worker_threads';\nimport {\n type ResolvedApplicationRuntime,\n type RuntimeProviderOverrides,\n resolveApplicationRuntime,\n} from '@happyvertical/smrt-config';\nimport { TaskRunner, type TaskRunnerConfig } from '@happyvertical/smrt-jobs';\nimport { Person, ProfileTypeCollection } from '@happyvertical/smrt-profiles';\nimport { withSystemContext } from '@happyvertical/smrt-tenancy';\nimport {\n DEFAULT_ROLE_SLUGS,\n MembershipCollection,\n MembershipStatus,\n RoleCollection,\n SessionCollection,\n SessionService,\n TenantService,\n UserCollection,\n UserStatus,\n} from '@happyvertical/smrt-users';\nimport { type DatabaseInterface, getDatabase } from '@happyvertical/sql';\n\nexport * from './deployed-runtime.js';\nexport * from './runtime-diagnostics.js';\n\nconst DEFAULT_BIND_HOST = '127.0.0.1';\nconst DEFAULT_BOOTSTRAP_TTL_SECONDS = 10 * 60;\nconst MAX_BOOTSTRAP_TTL_SECONDS = 15 * 60;\nconst DEFAULT_SESSION_TTL_SECONDS = 7 * 24 * 60 * 60;\nconst BOOTSTRAP_TABLE = '_smrt_local_owner_bootstrap';\nconst SECRET_FILE_NAME = 'application.secret';\nconst DATABASE_FILE_NAME = 'application.sqlite';\nconst ROOT_MARKER_PREFIX = '.smrt-local-runtime-';\nconst PREFLIGHT_RETRY_LIMIT = 4;\nconst INITIALIZATION_LOCK_TIMEOUT_MS = 120_000;\nconst INITIALIZATION_LOCK_WORKER = `\n const { parentPort, workerData } = require('node:worker_threads');\n let database;\n let transaction;\n (async () => {\n try {\n const { getDatabase } = await import(workerData.sqlModuleUrl);\n database = await getDatabase({\n type: 'sqlite',\n url: workerData.path,\n secureFile: {\n driver: 'node:sqlite',\n custody: 'trusted-parent',\n root: workerData.custodyRoot,\n },\n transactionQueueTimeout: workerData.timeout,\n });\n if (!database.beginTransaction) {\n throw new Error('Secure SQLite does not expose beginTransaction().');\n }\n await database.query('PRAGMA busy_timeout = ' + workerData.timeout);\n transaction = await database.beginTransaction();\n parentPort.postMessage({ type: 'acquired' });\n } catch (error) {\n try { await database?.close?.(); } catch {}\n parentPort.postMessage({ type: 'error', message: String(error) });\n parentPort.close();\n return;\n }\n parentPort.once('message', async (message) => {\n if (message?.type !== 'release') return;\n let releaseError;\n try { await transaction.rollback(); } catch (error) { releaseError = String(error); }\n try { await database.close?.(); } catch (error) { releaseError ??= String(error); }\n parentPort.postMessage({ type: 'released', error: releaseError });\n parentPort.close();\n });\n })().catch((error) => {\n parentPort.postMessage({ type: 'error', message: String(error) });\n parentPort.close();\n });\n`;\nconst execFileAsync = promisify(execFile);\n\n/** Paths owned by the local user, outside the source tree by default. */\nexport interface LocalRuntimePaths {\n readonly root: string;\n readonly database: string;\n readonly assets: string;\n readonly secrets: string;\n readonly applicationSecret: string;\n}\n\nexport interface ResolveLocalRuntimePathsOptions {\n /** Stable application identifier, e.g. `lolaus`. */\n appId: string;\n /** Explicit user-owned data directory. Defaults to the OS application-data directory. */\n dataDirectory?: string;\n /** Source checkout to protect from accidental data placement. Defaults to cwd. */\n sourceRoot?: string;\n /** Testable default-root and filesystem case-sensitivity override. */\n platform?: NodeJS.Platform;\n /** Testable home-directory override. */\n homeDirectory?: string;\n /** Testable environment override. */\n env?: NodeJS.ProcessEnv;\n}\n\nexport interface LocalApplicationRuntimeOptions\n extends ResolveLocalRuntimePathsOptions {\n /** Actual HTTP bind host. Owner bootstrap refuses non-loopback values. */\n bindHost?: string;\n /**\n * Explicit application migration/schema hook, invoked before identity access.\n * It must be idempotent; runtime code never synthesizes application tables.\n */\n prepareDatabase?: (db: DatabaseInterface) => Promise<void>;\n /** Local profile provider overrides (only validated local combinations survive). */\n providers?: RuntimeProviderOverrides;\n /** Short-lived bootstrap token lifetime. Range: 1..900 seconds. */\n bootstrapTtlSeconds?: number;\n /** Normal authenticated session lifetime in whole seconds. Minimum 1. */\n sessionTtlSeconds?: number;\n /** Explicit opt-in for persisted background work. Default false. */\n backgroundJobs?: boolean;\n /** Explicit opt-in for application-defined paid capabilities. Default false. */\n paidCapabilities?: boolean;\n /** Testable clock. */\n now?: () => Date;\n}\n\n/**\n * Claim the secure local database root before a standalone migration command\n * opens SQLite. This does not create application schema or bootstrap records.\n */\nexport async function prepareLocalDatabaseStorage(\n options: ResolveLocalRuntimePathsOptions,\n): Promise<LocalRuntimePaths> {\n const paths = resolveLocalRuntimePaths(options);\n const sourceRoot = resolve(options.sourceRoot ?? process.cwd());\n const appId = validateApplicationId(options.appId);\n await preflightLocalApplicationRoot(paths.root, sourceRoot, appId);\n const initializationLock = await acquireInitializationLock(paths.root);\n let db: DatabaseInterface | undefined;\n let failure: unknown;\n try {\n await preflightLocalApplicationRoot(paths.root, sourceRoot, appId);\n const acquired = await acquireLocalDatabase(paths, sourceRoot, appId);\n db = acquired.db;\n await db.close?.();\n db = undefined;\n } catch (error) {\n failure = db ? await closeDatabaseAfterFailure(db, error) : error;\n db = undefined;\n }\n try {\n await initializationLock.release();\n } catch (releaseError) {\n failure = failure\n ? preservePrimaryFailure(\n failure,\n releaseError,\n 'initializationLockReleaseError',\n 'Local database storage preparation and initialization-lock release both failed.',\n )\n : releaseError;\n }\n if (failure) throw failure;\n return paths;\n}\n\n/**\n * Verify an already-initialized local database root without creating or\n * changing any filesystem/database artifact. Operator read/copy/import paths\n * use this boundary before opening SQLite outside the runtime bootstrap.\n */\nexport async function validateLocalDatabaseStorage(\n options: ResolveLocalRuntimePathsOptions,\n): Promise<LocalRuntimePaths> {\n const paths = resolveLocalRuntimePaths(options);\n const sourceRoot = resolve(options.sourceRoot ?? process.cwd());\n const appId = validateApplicationId(options.appId);\n await preflightLocalApplicationRoot(paths.root, sourceRoot, appId);\n const canonicalSourceRoot = await realpath(sourceRoot);\n await validateRootMarker(\n resolve(paths.root, `${ROOT_MARKER_PREFIX}${appId}`),\n canonicalSourceRoot,\n );\n await validateExistingPathChain(paths.database, canonicalSourceRoot, 'file');\n const database = await lstat(paths.database);\n const currentUid = process.getuid?.();\n if (\n database.isSymbolicLink() ||\n !database.isFile() ||\n (currentUid !== undefined && database.uid !== currentUid) ||\n (database.mode & 0o777) !== 0o600\n ) {\n throw unsafeFilesystemEntry(\n `Local application database must be a current-user-owned mode-0600 file: ${paths.database}`,\n );\n }\n return paths;\n}\n\nexport interface LocalOwnerBootstrapInvitation {\n /** Plaintext is returned exactly when a new claim is issued; it is never persisted. */\n readonly token: string;\n readonly expiresAt: string;\n}\n\nexport interface LocalRuntimeInitialization {\n readonly runtime: LocalApplicationRuntime;\n readonly bootstrap: LocalOwnerBootstrapInvitation | null;\n readonly diagnostics: LocalRuntimeDiagnostics;\n}\n\nexport interface ClaimLocalOwnerInput {\n token: string;\n name: string;\n email: string;\n tenantName?: string;\n userAgent?: string;\n ipAddress?: string;\n}\n\nexport interface LocalOwnerClaimResult {\n readonly profileId: string;\n readonly userId: string;\n readonly tenantId: string;\n readonly membershipId: string;\n readonly sessionId: string;\n}\n\nexport type LocalBootstrapStatus =\n | 'available'\n | 'expired'\n | 'claimed'\n | 'unavailable';\n\n/** Secret-free, machine-readable local runtime state. */\nexport interface LocalRuntimeDiagnostics {\n readonly schemaVersion: 1;\n readonly runtime: ResolvedApplicationRuntime;\n readonly bind: {\n readonly host: string;\n readonly loopback: true;\n };\n readonly paths: LocalRuntimePaths;\n readonly storage: {\n readonly database: 'sqlite-file';\n readonly assets: 'user-owned-directory';\n readonly secrets: 'mode-0600-local-file';\n };\n readonly bootstrap: {\n readonly status: LocalBootstrapStatus;\n readonly expiresAt: string | null;\n readonly tokenValuesIncluded: false;\n readonly tokenHashesIncluded: false;\n };\n readonly tenancy: {\n readonly mode: 'real-default-tenant';\n readonly ui: 'hidden';\n };\n readonly jobs: {\n readonly topology: 'inline' | 'embedded';\n readonly backgroundEnabled: boolean;\n };\n readonly paidCapabilitiesEnabled: boolean;\n readonly secretValuesIncluded: false;\n}\n\nexport type LocalRuntimeErrorCode =\n | 'bootstrap_claimed'\n | 'bootstrap_expired'\n | 'bootstrap_invalid'\n | 'bootstrap_unavailable'\n | 'capability_disabled'\n | 'invalid_configuration'\n | 'migration_failed'\n | 'unsafe_public_exposure';\n\n/**\n * Fixed, secret-free surface for a failed application migration.\n *\n * A migration driver message is a likely carrier of a connection string,\n * credential, filesystem path, or environment value, so the caller's text is\n * never surfaced. The original error is retained as a non-enumerable `cause`\n * for private logs only.\n */\nexport const MIGRATION_FAILED_MESSAGE =\n 'The application migration step failed; run pnpm app:setup and inspect the private migration logs.';\n\n/** Stable, secret-free local-runtime failure. */\nexport class LocalRuntimeError extends Error {\n constructor(\n readonly code: LocalRuntimeErrorCode,\n message: string,\n ) {\n super(message);\n this.name = 'LocalRuntimeError';\n }\n}\n\ninterface BootstrapRow {\n expires_at?: unknown;\n consumed_at?: unknown;\n}\n\ninterface ExistingOwner {\n userId: string;\n tenantId: string;\n}\n\n/**\n * Resolve deterministic user-owned paths and reject source-tree placement.\n */\nexport function resolveLocalRuntimePaths(\n options: ResolveLocalRuntimePathsOptions,\n): LocalRuntimePaths {\n const appId = validateApplicationId(options.appId);\n const runtimePlatform = options.platform ?? platform();\n const runtimeHome = options.homeDirectory ?? homedir();\n const env = options.env ?? process.env;\n const defaultRoot = defaultApplicationDataRoot(\n runtimePlatform,\n runtimeHome,\n env,\n );\n const root = resolve(options.dataDirectory ?? resolve(defaultRoot, appId));\n const sourceRoot = resolve(options.sourceRoot ?? process.cwd());\n\n if (\n sameFilesystemPath(root, runtimeHome, runtimePlatform) ||\n sameFilesystemPath(root, parse(root).root, runtimePlatform) ||\n isInside(sourceRoot, root, runtimePlatform) ||\n isInside(root, sourceRoot, runtimePlatform)\n ) {\n throw new LocalRuntimeError(\n 'invalid_configuration',\n 'Local application data must be a dedicated directory that does not overlap the source tree.',\n );\n }\n\n return Object.freeze({\n root,\n database: resolve(root, DATABASE_FILE_NAME),\n assets: resolve(root, 'assets'),\n secrets: resolve(root, 'secrets'),\n applicationSecret: resolve(root, 'secrets', SECRET_FILE_NAME),\n });\n}\n\n/**\n * Initialize or reopen a local application runtime.\n *\n * A plaintext bootstrap token is returned only when this call creates a new\n * invitation. Existing unexpired invitations remain valid but cannot be read\n * back because only their HMAC is stored.\n */\nexport async function initializeLocalApplicationRuntime(\n options: LocalApplicationRuntimeOptions,\n): Promise<LocalRuntimeInitialization> {\n const bindHost = normalizeLoopbackHost(options.bindHost ?? DEFAULT_BIND_HOST);\n const bootstrapTtlSeconds = validateBootstrapTtl(\n options.bootstrapTtlSeconds ?? DEFAULT_BOOTSTRAP_TTL_SECONDS,\n );\n const sessionTtlSeconds = validateSessionTtl(\n options.sessionTtlSeconds ?? DEFAULT_SESSION_TTL_SECONDS,\n );\n const resolvedRuntime = resolveApplicationRuntime({\n profile: 'local',\n providers: options.providers,\n });\n const paths = resolveLocalRuntimePaths(options);\n const sourceRoot = resolve(options.sourceRoot ?? process.cwd());\n const appId = validateApplicationId(options.appId);\n await preflightLocalApplicationRoot(paths.root, sourceRoot, appId);\n const initializationLock = await acquireInitializationLock(paths.root);\n let db: DatabaseInterface | undefined;\n let initialization: LocalRuntimeInitialization | undefined;\n let initializationFailure: unknown;\n let initializationFailed = false;\n try {\n await preflightLocalApplicationRoot(paths.root, sourceRoot, appId);\n const acquired = await acquireLocalDatabase(paths, sourceRoot, appId);\n db = acquired.db;\n const { canonicalSourceRoot } = acquired;\n await prepareLocalFilesystem(paths, canonicalSourceRoot);\n await tuneLocalSqlite(db);\n try {\n await options.prepareDatabase?.(db);\n } catch (migrationFailure) {\n throw migrationFailed(migrationFailure);\n }\n await ensureBootstrapTable(db);\n\n const runtime = new InitializedLocalApplicationRuntime({\n db,\n paths,\n bindHost,\n resolvedRuntime,\n bootstrapTtlSeconds,\n sessionTtlSeconds,\n backgroundJobs: options.backgroundJobs === true,\n paidCapabilities: options.paidCapabilities === true,\n now: options.now ?? (() => new Date()),\n canonicalSourceRoot,\n });\n const bootstrap = await runtime.ensureBootstrapInvitation();\n initialization = {\n runtime,\n bootstrap,\n diagnostics: await runtime.diagnostics(),\n };\n } catch (error) {\n initializationFailed = true;\n initializationFailure = db\n ? await closeDatabaseAfterFailure(db, error)\n : error;\n db = undefined;\n }\n\n try {\n await initializationLock.release();\n } catch (releaseError) {\n if (initializationFailed) {\n initializationFailure = preservePrimaryFailure(\n initializationFailure,\n releaseError,\n 'initializationLockReleaseError',\n 'Local runtime initialization and initialization-lock release both failed.',\n );\n } else if (db) {\n initializationFailed = true;\n initializationFailure = await closeDatabaseAfterFailure(db, releaseError);\n db = undefined;\n } else {\n initializationFailed = true;\n initializationFailure = releaseError;\n }\n }\n\n if (initializationFailed) throw initializationFailure;\n if (!initialization) {\n throw new Error('Local runtime initialization completed without a result.');\n }\n return initialization;\n}\n\ninterface LocalApplicationRuntimeState {\n db: DatabaseInterface;\n paths: LocalRuntimePaths;\n bindHost: string;\n resolvedRuntime: ResolvedApplicationRuntime;\n bootstrapTtlSeconds: number;\n sessionTtlSeconds: number;\n backgroundJobs: boolean;\n paidCapabilities: boolean;\n now: () => Date;\n canonicalSourceRoot: string;\n}\n\n/** Initialized local runtime used by server startup and onboarding handlers. */\nexport interface LocalApplicationRuntime {\n readonly db: DatabaseInterface;\n readonly paths: LocalRuntimePaths;\n readonly bindHost: string;\n readonly resolvedRuntime: ResolvedApplicationRuntime;\n readonly backgroundJobsEnabled: boolean;\n readonly paidCapabilitiesEnabled: boolean;\n ensureBootstrapInvitation(): Promise<LocalOwnerBootstrapInvitation | null>;\n rotateBootstrapInvitation(): Promise<LocalOwnerBootstrapInvitation>;\n claimOwner(input: ClaimLocalOwnerInput): Promise<LocalOwnerClaimResult>;\n restoreSession(\n sessionId: string,\n ): ReturnType<SessionService['loadSessionContext']>;\n createEmbeddedJobRunner(config?: TaskRunnerConfig): Promise<TaskRunner>;\n diagnostics(): Promise<LocalRuntimeDiagnostics>;\n}\n\nclass InitializedLocalApplicationRuntime implements LocalApplicationRuntime {\n readonly db: DatabaseInterface;\n readonly paths: LocalRuntimePaths;\n readonly bindHost: string;\n readonly resolvedRuntime: ResolvedApplicationRuntime;\n readonly backgroundJobsEnabled: boolean;\n readonly paidCapabilitiesEnabled: boolean;\n private readonly bootstrapTtlSeconds: number;\n private readonly sessionTtlSeconds: number;\n private readonly now: () => Date;\n private readonly canonicalSourceRoot: string;\n\n constructor(state: LocalApplicationRuntimeState) {\n this.db = state.db;\n this.paths = state.paths;\n this.bindHost = state.bindHost;\n this.resolvedRuntime = state.resolvedRuntime;\n this.bootstrapTtlSeconds = state.bootstrapTtlSeconds;\n this.sessionTtlSeconds = state.sessionTtlSeconds;\n this.backgroundJobsEnabled = state.backgroundJobs;\n this.paidCapabilitiesEnabled = state.paidCapabilities;\n this.now = state.now;\n this.canonicalSourceRoot = state.canonicalSourceRoot;\n }\n\n /**\n * Issue the first short-lived owner invitation when none is active.\n * Repeated startup never rotates an unexpired token or duplicates an owner.\n */\n async ensureBootstrapInvitation(): Promise<LocalOwnerBootstrapInvitation | null> {\n if (await findExistingOwner(this.db)) return null;\n const current = await readBootstrapRow(this.db);\n if (current?.consumed_at != null) return null;\n const now = this.now();\n const currentExpiry = parseStoredDate(current?.expires_at);\n if (\n current &&\n current.consumed_at == null &&\n currentExpiry !== null &&\n currentExpiry.getTime() > now.getTime()\n ) {\n return null;\n }\n return this.issueBootstrapInvitation(false);\n }\n\n /** Explicit recovery when an installer lost the one-time plaintext token. */\n async rotateBootstrapInvitation(): Promise<LocalOwnerBootstrapInvitation> {\n if (await findExistingOwner(this.db)) {\n throw new LocalRuntimeError(\n 'bootstrap_claimed',\n 'The local owner has already been claimed.',\n );\n }\n if ((await readBootstrapRow(this.db))?.consumed_at != null) {\n throw new LocalRuntimeError(\n 'bootstrap_claimed',\n 'The local owner bootstrap invitation has already been consumed.',\n );\n }\n const invitation = await this.issueBootstrapInvitation(true);\n if (!invitation) {\n if ((await readBootstrapRow(this.db))?.consumed_at != null) {\n throw new LocalRuntimeError(\n 'bootstrap_claimed',\n 'The local owner bootstrap invitation has already been consumed.',\n );\n }\n throw new LocalRuntimeError(\n 'bootstrap_unavailable',\n 'A local owner bootstrap invitation could not be issued.',\n );\n }\n return invitation;\n }\n\n /**\n * Consume a bootstrap token and atomically create normal identity/RBAC/session\n * records. The token transition and every record write share one transaction.\n */\n async claimOwner(\n input: ClaimLocalOwnerInput,\n ): Promise<LocalOwnerClaimResult> {\n validateOwnerInput(input);\n if (await findExistingOwner(this.db)) {\n throw new LocalRuntimeError(\n 'bootstrap_claimed',\n 'The local owner has already been claimed.',\n );\n }\n if (typeof this.db.transaction !== 'function') {\n throw new LocalRuntimeError(\n 'bootstrap_unavailable',\n 'Owner bootstrap requires a database adapter with transaction support.',\n );\n }\n\n const tokenHash = await this.hashBootstrapToken(input.token);\n const now = this.now();\n const nowIso = now.toISOString();\n // Generated write routes require `<collection>.<action>` grants (#2977),\n // so the owner role must hold the default role matrix over the manifest\n // permission catalog, not only the role itself. Seeding is idempotent and\n // additive, and runs before the claim transaction because the catalog\n // sync uses its own collection connections.\n const roles = await RoleCollection.create({ db: this.db });\n await roles.seedSystemRoles({ seedPermissions: true });\n return this.db.transaction(async (tx) => {\n const claimed = await tx.query(\n `UPDATE ${BOOTSTRAP_TABLE}\n SET consumed_at = ?\n WHERE slot = 1\n AND token_hash = ?\n AND consumed_at IS NULL\n AND expires_at > ?\n RETURNING expires_at`,\n nowIso,\n tokenHash,\n nowIso,\n );\n if (claimed.rows.length === 0) {\n await throwBootstrapClaimFailure(tx, now);\n }\n\n const concurrentOwner = await findExistingOwner(tx);\n if (concurrentOwner) {\n throw new LocalRuntimeError(\n 'bootstrap_claimed',\n 'The local owner has already been claimed.',\n );\n }\n\n return createLocalOwnerRecords(tx, input, this.sessionTtlSeconds);\n });\n }\n\n /** Restore the normal server-side session created by owner bootstrap. */\n async restoreSession(sessionId: string) {\n const service = new SessionService({ db: this.db });\n await service.initialize();\n return service.loadSessionContext(sessionId);\n }\n\n /**\n * Create an in-process persisted-job runner. Background work is default-off\n * and must be explicitly enabled by runtime configuration.\n */\n async createEmbeddedJobRunner(\n config: TaskRunnerConfig = {},\n ): Promise<TaskRunner> {\n if (!this.backgroundJobsEnabled) {\n throw new LocalRuntimeError(\n 'capability_disabled',\n 'Background jobs are disabled; enable them explicitly for this local application.',\n );\n }\n if (this.resolvedRuntime.providers.jobs.topology !== 'embedded') {\n throw new LocalRuntimeError(\n 'invalid_configuration',\n 'An embedded runner requires the local embedded job topology.',\n );\n }\n const runner = new TaskRunner({\n concurrency: 1,\n retention: false,\n ...config,\n });\n await runner.initialize(this.db);\n return runner;\n }\n\n /** Return a deterministic snapshot that never reads secret file contents. */\n async diagnostics(): Promise<LocalRuntimeDiagnostics> {\n const owner = await findExistingOwner(this.db);\n const bootstrap = await readBootstrapRow(this.db);\n const now = this.now();\n const expiresAt = parseStoredDate(bootstrap?.expires_at);\n let status: LocalBootstrapStatus = 'unavailable';\n if (owner || bootstrap?.consumed_at != null) status = 'claimed';\n else if (expiresAt && expiresAt.getTime() > now.getTime())\n status = 'available';\n else if (expiresAt) status = 'expired';\n\n return Object.freeze({\n schemaVersion: 1,\n runtime: this.resolvedRuntime,\n bind: Object.freeze({ host: this.bindHost, loopback: true as const }),\n paths: this.paths,\n storage: Object.freeze({\n database: 'sqlite-file' as const,\n assets: 'user-owned-directory' as const,\n secrets: 'mode-0600-local-file' as const,\n }),\n bootstrap: Object.freeze({\n status,\n expiresAt: expiresAt?.toISOString() ?? null,\n tokenValuesIncluded: false as const,\n tokenHashesIncluded: false as const,\n }),\n tenancy: Object.freeze({\n mode: 'real-default-tenant' as const,\n ui: 'hidden' as const,\n }),\n jobs: Object.freeze({\n topology: this.resolvedRuntime.providers.jobs.topology as\n | 'inline'\n | 'embedded',\n backgroundEnabled: this.backgroundJobsEnabled,\n }),\n paidCapabilitiesEnabled: this.paidCapabilitiesEnabled,\n secretValuesIncluded: false as const,\n });\n }\n\n private async issueBootstrapInvitation(\n replaceActive: boolean,\n ): Promise<LocalOwnerBootstrapInvitation | null> {\n const token = randomBytes(32).toString('base64url');\n const tokenHash = await this.hashBootstrapToken(token);\n const now = this.now();\n const expiresAt = new Date(now.getTime() + this.bootstrapTtlSeconds * 1000);\n const stored = await this.db.query(\n `INSERT INTO ${BOOTSTRAP_TABLE}\n (slot, token_hash, expires_at, consumed_at, created_at)\n VALUES (1, ?, ?, NULL, ?)\n ON CONFLICT(slot) DO UPDATE SET\n token_hash = excluded.token_hash,\n expires_at = excluded.expires_at,\n consumed_at = NULL,\n created_at = excluded.created_at\n WHERE ${BOOTSTRAP_TABLE}.consumed_at IS NULL\n AND (? = 1 OR ${BOOTSTRAP_TABLE}.expires_at <= ?)\n RETURNING token_hash`,\n tokenHash,\n expiresAt.toISOString(),\n now.toISOString(),\n replaceActive ? 1 : 0,\n now.toISOString(),\n );\n const persistedHash = (\n stored.rows[0] as { token_hash?: unknown } | undefined\n )?.token_hash;\n if (persistedHash !== tokenHash) return null;\n return Object.freeze({ token, expiresAt: expiresAt.toISOString() });\n }\n\n private async hashBootstrapToken(token: string): Promise<string> {\n const secret = await validateApplicationSecret(\n this.paths.applicationSecret,\n this.canonicalSourceRoot,\n );\n return createHmac('sha256', secret.trim()).update(token).digest('hex');\n }\n}\n\nasync function createLocalOwnerRecords(\n db: DatabaseInterface,\n input: ClaimLocalOwnerInput,\n sessionTtlSeconds: number,\n): Promise<LocalOwnerClaimResult> {\n const profileTypes = await ProfileTypeCollection.create({ db });\n const personType = await withSystemContext(() =>\n profileTypes.getOrCreateGlobalBySlug('person', {\n name: 'Person',\n description: 'An individual person',\n }),\n );\n const person = new Person({\n db,\n typeId: requireId(personType.id, 'Person profile type'),\n tenantId: null,\n name: input.name.trim(),\n email: input.email.trim(),\n });\n await person.initialize();\n await person.save();\n\n const users = await UserCollection.create({ db });\n const user = await users.create({\n profileId: requireId(person.id, 'Person'),\n email: input.email.trim(),\n status: UserStatus.ACTIVE,\n lastLoginAt: new Date(),\n });\n await user.save();\n\n const tenantService = new TenantService(\n { db },\n {\n mode: 'required',\n maxTenants: 1,\n defaultName: input.tenantName?.trim() || 'My Workspace',\n },\n );\n await tenantService.initialize();\n const { tenant, membership } = await tenantService.createTenantWithOwnership(\n requireId(user.id, 'User'),\n input.tenantName?.trim() || 'My Workspace',\n { slug: 'default' },\n );\n\n const sessions = await SessionCollection.create({ db });\n const session = await sessions.createSession({\n userId: requireId(user.id, 'User'),\n tenantId: requireId(tenant.id, 'Tenant'),\n ttl: sessionTtlSeconds,\n userAgent: input.userAgent,\n ipAddress: input.ipAddress,\n data: { localOwner: true },\n });\n\n return Object.freeze({\n profileId: requireId(person.id, 'Person'),\n userId: requireId(user.id, 'User'),\n tenantId: requireId(tenant.id, 'Tenant'),\n membershipId: requireId(membership.id, 'Membership'),\n sessionId: requireId(session.id, 'Session'),\n });\n}\n\nasync function findExistingOwner(\n db: DatabaseInterface,\n): Promise<ExistingOwner | null> {\n const roles = await RoleCollection.create({ db });\n const ownerRole = await roles.findSystemRoleBySlug(DEFAULT_ROLE_SLUGS.OWNER);\n if (!ownerRole?.id) return null;\n const memberships = await MembershipCollection.create({ db });\n const ownerMemberships = await memberships.findByRole(ownerRole.id);\n const active = ownerMemberships.find(\n (membership) =>\n membership.status === MembershipStatus.ACTIVE &&\n typeof membership.userId === 'string' &&\n typeof membership.tenantId === 'string',\n );\n return active\n ? { userId: active.userId as string, tenantId: active.tenantId as string }\n : null;\n}\n\nasync function throwBootstrapClaimFailure(\n db: DatabaseInterface,\n now: Date,\n): Promise<never> {\n const row = await readBootstrapRow(db);\n if (!row) {\n throw new LocalRuntimeError(\n 'bootstrap_unavailable',\n 'No local owner bootstrap invitation is available.',\n );\n }\n if (row.consumed_at != null) {\n throw new LocalRuntimeError(\n 'bootstrap_claimed',\n 'The local owner bootstrap invitation has already been consumed.',\n );\n }\n const expiresAt = parseStoredDate(row.expires_at);\n if (!expiresAt || expiresAt.getTime() <= now.getTime()) {\n throw new LocalRuntimeError(\n 'bootstrap_expired',\n 'The local owner bootstrap invitation has expired.',\n );\n }\n throw new LocalRuntimeError(\n 'bootstrap_invalid',\n 'The local owner bootstrap token is invalid.',\n );\n}\n\nasync function readBootstrapRow(\n db: DatabaseInterface,\n): Promise<BootstrapRow | null> {\n const result = await db.query(\n `SELECT expires_at, consumed_at\n FROM ${BOOTSTRAP_TABLE}\n WHERE slot = 1\n LIMIT 1`,\n );\n return (result.rows[0] as BootstrapRow | undefined) ?? null;\n}\n\nasync function ensureBootstrapTable(db: DatabaseInterface): Promise<void> {\n await db.query(\n `CREATE TABLE IF NOT EXISTS ${BOOTSTRAP_TABLE} (\n slot INTEGER PRIMARY KEY CHECK (slot = 1),\n token_hash TEXT NOT NULL,\n expires_at TEXT NOT NULL,\n consumed_at TEXT NULL,\n created_at TEXT NOT NULL\n )`,\n );\n}\n\nasync function tuneLocalSqlite(db: DatabaseInterface): Promise<void> {\n await db.query('PRAGMA foreign_keys = ON');\n await db.query('PRAGMA journal_mode = WAL');\n await db.query('PRAGMA synchronous = FULL');\n await db.query('PRAGMA busy_timeout = 5000');\n}\n\ninterface PreparedLocalRoot {\n createdDirectories: string[];\n pendingMarker: string | null;\n pendingMarkerCreatedByAttempt: boolean;\n finalMarker: string;\n}\n\ninterface LocalInitializationLock {\n release(): Promise<void>;\n}\n\nasync function preflightLocalApplicationRoot(\n root: string,\n sourceRoot: string,\n appId: string,\n): Promise<void> {\n for (let attempt = 0; attempt < PREFLIGHT_RETRY_LIMIT; attempt += 1) {\n try {\n await preflightLocalApplicationRootOnce(root, sourceRoot, appId);\n return;\n } catch (error) {\n if (!isMissingFile(error) && !hasMissingFileCause(error)) throw error;\n if (attempt === PREFLIGHT_RETRY_LIMIT - 1) {\n throw unsafeFilesystemEntry(\n 'Local application data changed repeatedly during read-only preflight.',\n error,\n );\n }\n await new Promise<void>((resolveRetry) => setImmediate(resolveRetry));\n }\n }\n}\n\nasync function preflightLocalApplicationRootOnce(\n root: string,\n sourceRoot: string,\n appId: string,\n): Promise<void> {\n requireNoFollowSupport();\n const canonicalSourceRoot = await realpath(sourceRoot);\n const currentUid = process.getuid?.();\n if (currentUid === undefined) {\n throw unsafeFilesystemEntry(\n 'Local runtime storage requires a numeric current-user identity.',\n );\n }\n if (\n isInside(canonicalSourceRoot, root) ||\n isInside(root, canonicalSourceRoot)\n ) {\n throw unsafeFilesystemEntry(\n 'Local application data must remain outside the canonical source tree.',\n );\n }\n\n let rootExists = true;\n for (const component of absolutePathComponents(root)) {\n let details: Awaited<ReturnType<typeof lstat>>;\n try {\n details = await lstat(component);\n } catch (error) {\n if (!isMissingFile(error)) throw error;\n rootExists = false;\n break;\n }\n if (details.isSymbolicLink() || !details.isDirectory()) {\n throw unsafeFilesystemEntry(\n `Local runtime path component must be a real directory: ${component}`,\n );\n }\n await assertCanonicalEntry(component, canonicalSourceRoot);\n const sharedStickyRoot = details.uid === 0 && (details.mode & 0o1000) !== 0;\n if (\n (details.uid !== currentUid && details.uid !== 0) ||\n ((details.mode & 0o022) !== 0 && !sharedStickyRoot)\n ) {\n throw unsafeFilesystemEntry(\n `Local runtime path ancestry does not have trusted-parent custody: ${component}`,\n );\n }\n await assertNoPermissiveDarwinAcl(component);\n }\n\n if (!rootExists) return;\n const rootDetails = await lstat(root);\n if (rootDetails.uid !== currentUid || (rootDetails.mode & 0o777) !== 0o700) {\n throw unsafeFilesystemEntry(\n `Existing local application data root must already be owned by the current user with mode 0700: ${root}`,\n );\n }\n await preflightDedicatedRoot(root, canonicalSourceRoot, appId);\n}\n\nasync function preflightDedicatedRoot(\n root: string,\n canonicalSourceRoot: string,\n appId: string,\n): Promise<void> {\n const finalMarker = resolve(root, `${ROOT_MARKER_PREFIX}${appId}`);\n const pendingMarker = resolve(root, `${ROOT_MARKER_PREFIX}${appId}.pending`);\n const entries = await readdir(root);\n const finalMarkerName = finalMarker.slice(root.length + 1);\n const pendingMarkerName = pendingMarker.slice(root.length + 1);\n const hasFinalMarker = entries.includes(finalMarkerName);\n const hasPendingMarker = entries.includes(pendingMarkerName);\n\n if (hasFinalMarker) {\n await validateRootMarker(finalMarker, canonicalSourceRoot);\n if (hasPendingMarker) {\n await validateRootMarker(pendingMarker, canonicalSourceRoot);\n }\n return;\n }\n if (hasPendingMarker) {\n await validateRootMarker(pendingMarker, canonicalSourceRoot);\n const permittedInterruptedEntries = new Set([\n pendingMarkerName,\n DATABASE_FILE_NAME,\n `${DATABASE_FILE_NAME}-shm`,\n `${DATABASE_FILE_NAME}-wal`,\n ]);\n if (entries.some((entry) => !permittedInterruptedEntries.has(entry))) {\n throw unsafeFilesystemEntry(\n 'Interrupted local application root contains unexpected artifacts.',\n );\n }\n return;\n }\n if (entries.length > 0) {\n throw unsafeFilesystemEntry(\n 'Existing local application data root is populated but has no valid ownership marker.',\n );\n }\n}\n\nasync function assertNoPermissiveDarwinAcl(path: string): Promise<void> {\n if (platform() !== 'darwin') return;\n let listing: string;\n try {\n const result = await execFileAsync('/bin/ls', ['-lde', '--', path], {\n encoding: 'utf8',\n env: { ...process.env, LC_ALL: 'C' },\n });\n listing = result.stdout;\n } catch (error) {\n throw unsafeFilesystemEntry(\n `Local runtime could not inspect macOS access controls: ${path}`,\n error,\n );\n }\n for (const line of listing.split('\\n')) {\n if (!/^\\s*\\d+:/.test(line)) continue;\n const entry = line.match(/^\\s*\\d+:\\s+.+\\s+(allow|deny)\\s+\\S.*$/);\n if (entry?.[1] !== 'deny') {\n throw unsafeFilesystemEntry(\n `Local runtime path contains a permissive macOS access control list: ${path}`,\n );\n }\n }\n}\n\nasync function acquireLocalDatabase(\n paths: LocalRuntimePaths,\n sourceRoot: string,\n appId: string,\n): Promise<{\n canonicalSourceRoot: string;\n db: DatabaseInterface;\n}> {\n requireNoFollowSupport();\n const canonicalSourceRoot = await realpath(sourceRoot);\n const createdDirectories = await ensureSafeDirectoryTree(\n paths.root,\n canonicalSourceRoot,\n true,\n );\n const prepared = await prepareDedicatedRoot(\n paths.root,\n canonicalSourceRoot,\n appId,\n createdDirectories,\n );\n let db: DatabaseInterface | undefined;\n try {\n db = await getDatabase({\n type: 'sqlite',\n url: paths.database,\n secureFile: {\n driver: 'node:sqlite',\n custody: 'trusted-parent',\n root: paths.root,\n },\n });\n await enforcePrivateDatabaseMode(paths.database, canonicalSourceRoot);\n } catch (error) {\n if (db) throw await closeDatabaseAfterFailure(db, error);\n if (prepared.pendingMarkerCreatedByAttempt) {\n await removeMarkerIfPresent(prepared.pendingMarker, canonicalSourceRoot);\n await removeCreatedDirectories(createdDirectories);\n }\n throw error;\n }\n if (!db) {\n throw new Error('Local runtime database acquisition returned no database.');\n }\n\n // Once SQLite acquisition succeeds, the database is an authoritative\n // artifact. Keep the pending marker through every promotion failure so a\n // later startup can resume rather than seeing an unmarked populated root.\n try {\n await publishRootMarker(prepared.finalMarker, canonicalSourceRoot);\n await removeMarkerIfPresent(prepared.pendingMarker, canonicalSourceRoot);\n } catch (error) {\n throw await closeDatabaseAfterFailure(db, error);\n }\n return { canonicalSourceRoot, db };\n}\n\nasync function enforcePrivateDatabaseMode(\n path: string,\n canonicalSourceRoot: string,\n): Promise<void> {\n const database = await openSafeFile(\n path,\n constants.O_RDWR,\n 0o600,\n 'Local application database',\n canonicalSourceRoot,\n );\n try {\n await database.chmod(0o600);\n await database.sync();\n } finally {\n await database.close();\n }\n}\n\nasync function closeDatabaseAfterFailure(\n db: DatabaseInterface,\n primaryFailure: unknown,\n): Promise<unknown> {\n try {\n await db.close?.();\n } catch (cleanupFailure) {\n return preservePrimaryFailure(\n primaryFailure,\n cleanupFailure,\n 'databaseCleanupError',\n 'Local runtime initialization and database cleanup both failed.',\n );\n }\n return primaryFailure;\n}\n\nfunction migrationFailed(cause: unknown): LocalRuntimeError {\n const failure = new LocalRuntimeError(\n 'migration_failed',\n MIGRATION_FAILED_MESSAGE,\n );\n Object.defineProperty(failure, 'cause', {\n value: cause,\n configurable: true,\n });\n return failure;\n}\n\nfunction preservePrimaryFailure(\n primaryFailure: unknown,\n secondaryFailure: unknown,\n secondaryProperty: string,\n aggregateMessage: string,\n): unknown {\n if (primaryFailure instanceof Error) {\n try {\n Object.defineProperty(primaryFailure, secondaryProperty, {\n value: secondaryFailure,\n configurable: true,\n });\n } catch {\n // A frozen application error must remain primary even when secondary\n // failure context cannot be attached to it.\n }\n return primaryFailure;\n }\n return new AggregateError(\n [primaryFailure, secondaryFailure],\n aggregateMessage,\n );\n}\n\nasync function prepareLocalFilesystem(\n paths: LocalRuntimePaths,\n canonicalSourceRoot: string,\n): Promise<void> {\n await ensureSafeDirectoryTree(paths.assets, canonicalSourceRoot);\n await ensureSafeDirectoryTree(paths.secrets, canonicalSourceRoot);\n await ensureApplicationSecret(paths.applicationSecret, canonicalSourceRoot);\n}\n\nasync function prepareDedicatedRoot(\n path: string,\n canonicalSourceRoot: string,\n appId: string,\n createdDirectories: string[],\n): Promise<PreparedLocalRoot> {\n const finalMarker = resolve(path, `${ROOT_MARKER_PREFIX}${appId}`);\n const pendingMarker = resolve(path, `${ROOT_MARKER_PREFIX}${appId}.pending`);\n const entries = await readdir(path);\n const hasFinalMarker = entries.includes(finalMarker.slice(path.length + 1));\n const hasPendingMarker = entries.includes(\n pendingMarker.slice(path.length + 1),\n );\n\n if (hasFinalMarker) {\n await validateRootMarker(finalMarker, canonicalSourceRoot);\n if (hasPendingMarker) {\n await validateRootMarker(pendingMarker, canonicalSourceRoot);\n }\n return {\n createdDirectories,\n pendingMarker: hasPendingMarker ? pendingMarker : null,\n pendingMarkerCreatedByAttempt: false,\n finalMarker,\n };\n }\n\n if (hasPendingMarker) {\n await validateRootMarker(pendingMarker, canonicalSourceRoot);\n const permittedInterruptedEntries = new Set([\n pendingMarker.slice(path.length + 1),\n DATABASE_FILE_NAME,\n `${DATABASE_FILE_NAME}-shm`,\n `${DATABASE_FILE_NAME}-wal`,\n ]);\n if (entries.some((entry) => !permittedInterruptedEntries.has(entry))) {\n throw unsafeFilesystemEntry(\n 'Interrupted local application root contains unexpected artifacts.',\n );\n }\n return {\n createdDirectories,\n pendingMarker,\n pendingMarkerCreatedByAttempt: false,\n finalMarker,\n };\n }\n\n if (entries.length > 0) {\n throw unsafeFilesystemEntry(\n 'Existing local application data root is populated but has no valid ownership marker.',\n );\n }\n const pendingMarkerCreatedByAttempt = await publishRootMarker(\n pendingMarker,\n canonicalSourceRoot,\n );\n return {\n createdDirectories,\n pendingMarker,\n pendingMarkerCreatedByAttempt,\n finalMarker,\n };\n}\n\nasync function acquireInitializationLock(\n root: string,\n): Promise<LocalInitializationLock> {\n const currentUid = process.getuid?.();\n if (currentUid === undefined) {\n throw unsafeFilesystemEntry(\n 'Local runtime initialization locks require a numeric current-user identity.',\n );\n }\n const canonicalTemporaryRoot = await realpath('/tmp');\n const lockRoot = resolve(canonicalTemporaryRoot, `.smrt-${currentUid}`);\n try {\n await mkdir(lockRoot, { mode: 0o700 });\n } catch (error) {\n if (!isFileAlreadyExists(error)) throw error;\n }\n const lockRootDetails = await lstat(lockRoot);\n if (\n !lockRootDetails.isDirectory() ||\n lockRootDetails.isSymbolicLink() ||\n lockRootDetails.uid !== currentUid ||\n (lockRootDetails.mode & 0o777) !== 0o700\n ) {\n throw unsafeFilesystemEntry(\n `Local runtime lock directory must be current-user-owned with mode 0700: ${lockRoot}`,\n );\n }\n const lockKey = createHash('sha256')\n .update(normalizeFilesystemIdentity(root))\n .digest('hex')\n .slice(0, 32);\n const custodyRoot = resolve(lockRoot, lockKey);\n try {\n await mkdir(custodyRoot, { mode: 0o700 });\n } catch (error) {\n if (!isFileAlreadyExists(error)) throw error;\n }\n const path = resolve(custodyRoot, 'initialization.sqlite');\n return acquireInitializationDatabaseLease(path, custodyRoot);\n}\n\nasync function acquireInitializationDatabaseLease(\n path: string,\n custodyRoot: string,\n): Promise<LocalInitializationLock> {\n const worker = new Worker(INITIALIZATION_LOCK_WORKER, {\n eval: true,\n workerData: {\n path,\n custodyRoot,\n timeout: INITIALIZATION_LOCK_TIMEOUT_MS,\n sqlModuleUrl: import.meta.resolve('@happyvertical/sql'),\n },\n });\n const acquisitionFailure = (cause: unknown) => {\n const failure = new LocalRuntimeError(\n 'invalid_configuration',\n 'Could not acquire the local runtime initialization lease within two minutes.',\n );\n Object.defineProperty(failure, 'cause', { value: cause });\n return failure;\n };\n let workerError: unknown;\n const exited = new Promise<never>((_resolve, reject) => {\n worker.once('error', (error) => {\n workerError = error;\n });\n worker.once('exit', (code) => {\n reject(\n acquisitionFailure(\n workerError ??\n new Error(`Initialization lock worker exited ${code}.`),\n ),\n );\n });\n });\n const acquired = new Promise<void>((resolvePromise, reject) => {\n const onMessage = (message: { type?: string; message?: string }) => {\n if (message.type === 'acquired') {\n worker.off('message', onMessage);\n resolvePromise();\n } else if (message.type === 'error') {\n worker.off('message', onMessage);\n reject(acquisitionFailure(new Error(message.message)));\n }\n };\n worker.on('message', onMessage);\n });\n await Promise.race([acquired, exited]);\n\n let released = false;\n return {\n release: async () => {\n if (released) return;\n released = true;\n const releaseCompleted = new Promise<void>((resolvePromise, reject) => {\n const onMessage = (message: { type?: string; error?: string }) => {\n if (message.type !== 'released') return;\n worker.off('message', onMessage);\n if (message.error) reject(new Error(message.error));\n else resolvePromise();\n };\n worker.on('message', onMessage);\n worker.postMessage({ type: 'release' });\n });\n try {\n await Promise.race([releaseCompleted, exited]);\n } finally {\n await worker.terminate();\n }\n },\n };\n}\n\nasync function ensureSafeDirectoryTree(\n path: string,\n canonicalSourceRoot: string,\n dedicatedRoot = false,\n): Promise<string[]> {\n const components = absolutePathComponents(path);\n const createdDirectories: string[] = [];\n for (const component of components) {\n let created = false;\n try {\n const details = await lstat(component);\n if (details.isSymbolicLink() || !details.isDirectory()) {\n throw unsafeFilesystemEntry(\n `Local runtime path component must be a real directory: ${component}`,\n );\n }\n } catch (error) {\n if (!isMissingFile(error)) throw error;\n try {\n await mkdir(component, { mode: 0o700 });\n created = true;\n createdDirectories.push(component);\n } catch (mkdirError) {\n // A concurrent initializer may have created the component. It is still\n // opened and validated without following links below.\n if (!isFileAlreadyExists(mkdirError)) throw mkdirError;\n }\n }\n\n const directory = await openSafeDirectory(component, canonicalSourceRoot);\n try {\n await assertCanonicalEntry(component, canonicalSourceRoot);\n if (component === path && dedicatedRoot && !created) {\n await assertExistingDedicatedRoot(\n directory,\n component,\n canonicalSourceRoot,\n );\n }\n if (created || (component === path && !dedicatedRoot)) {\n await directory.chmod(0o700);\n }\n } finally {\n await directory.close();\n }\n }\n await validateExistingPathChain(path, canonicalSourceRoot, 'directory');\n return createdDirectories;\n}\n\nasync function assertExistingDedicatedRoot(\n directory: FileHandle,\n path: string,\n canonicalSourceRoot: string,\n): Promise<void> {\n const canonical = await realpath(path);\n if (\n isInside(canonicalSourceRoot, canonical) ||\n isInside(canonical, canonicalSourceRoot)\n ) {\n throw unsafeFilesystemEntry(\n 'Local application data must be a dedicated directory that does not overlap the canonical source tree.',\n );\n }\n\n const details = await directory.stat();\n const currentUid = process.getuid?.();\n if (\n currentUid === undefined ||\n details.uid !== currentUid ||\n (details.mode & 0o777) !== 0o700\n ) {\n throw unsafeFilesystemEntry(\n `Existing local application data root must already be owned by the current user with mode 0700: ${path}`,\n );\n }\n}\n\nasync function publishRootMarker(\n path: string,\n canonicalSourceRoot: string,\n): Promise<boolean> {\n let marker: FileHandle | undefined;\n let created = false;\n try {\n marker = await openSafeFile(\n path,\n constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL,\n 0o600,\n 'Local application root marker',\n canonicalSourceRoot,\n );\n created = true;\n await marker.sync();\n } catch (error) {\n if (!isFileAlreadyExists(error)) throw error;\n } finally {\n await marker?.close();\n }\n await validateRootMarker(path, canonicalSourceRoot);\n await syncDirectory(resolve(path, '..'), canonicalSourceRoot);\n return created;\n}\n\nasync function validateRootMarker(\n path: string,\n canonicalSourceRoot: string,\n): Promise<void> {\n await validateExistingPathChain(path, canonicalSourceRoot, 'file');\n const marker = await openSafeFile(\n path,\n constants.O_RDONLY,\n 0o600,\n 'Local application root marker',\n canonicalSourceRoot,\n );\n try {\n const details = await marker.stat();\n const currentUid = process.getuid?.();\n if (\n currentUid === undefined ||\n details.uid !== currentUid ||\n (details.mode & 0o777) !== 0o600 ||\n details.size !== 0\n ) {\n throw unsafeFilesystemEntry(\n `Local application root marker must be an empty current-user-owned mode-0600 file: ${path}`,\n );\n }\n } finally {\n await marker.close();\n }\n}\n\nasync function removeMarkerIfPresent(\n path: string | null,\n canonicalSourceRoot: string,\n): Promise<void> {\n if (path === null) return;\n try {\n await validateRootMarker(path, canonicalSourceRoot);\n await unlink(path);\n await syncDirectory(resolve(path, '..'), canonicalSourceRoot);\n } catch (error) {\n if (!isMissingFile(error) && !hasMissingFileCause(error)) throw error;\n }\n}\n\nasync function removeCreatedDirectories(paths: string[]): Promise<void> {\n for (const path of paths.toReversed()) {\n try {\n await rmdir(path);\n } catch (error) {\n if (!isMissingFile(error) && !isDirectoryNotEmpty(error)) throw error;\n }\n }\n}\n\nasync function ensureApplicationSecret(\n path: string,\n canonicalSourceRoot: string,\n): Promise<void> {\n const directoryPath = resolve(path, '..');\n const temporaryPath = resolve(\n directoryPath,\n `.${SECRET_FILE_NAME}.tmp-${randomBytes(16).toString('hex')}`,\n );\n let temporary: FileHandle | undefined;\n let failure: unknown;\n try {\n temporary = await openSafeFile(\n temporaryPath,\n constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL,\n 0o600,\n 'Temporary application secret',\n canonicalSourceRoot,\n );\n await temporary.writeFile(\n `${randomBytes(32).toString('base64url')}\\n`,\n 'utf8',\n );\n await temporary.sync();\n await temporary.close();\n temporary = undefined;\n\n try {\n await link(temporaryPath, path);\n } catch (error) {\n if (!isFileAlreadyExists(error)) throw error;\n }\n\n await validateApplicationSecret(path, canonicalSourceRoot);\n await syncDirectory(directoryPath, canonicalSourceRoot);\n } catch (error) {\n failure = error;\n }\n try {\n await temporary?.close();\n } catch (error) {\n failure ??= error;\n }\n try {\n await unlink(temporaryPath);\n } catch (error) {\n if (!isMissingFile(error)) failure ??= error;\n }\n if (failure !== undefined) throw failure;\n await removeStaleSecretTemps(directoryPath);\n}\n\nasync function validateApplicationSecret(\n path: string,\n canonicalSourceRoot: string,\n): Promise<string> {\n await validateExistingPathChain(path, canonicalSourceRoot, 'file');\n const file = await openSafeFile(\n path,\n constants.O_RDONLY,\n 0o600,\n 'Application secret',\n canonicalSourceRoot,\n );\n try {\n const details = await file.stat();\n const currentUid = process.getuid?.();\n const secret = await file.readFile('utf8');\n await validateExistingPathChain(path, canonicalSourceRoot, 'file');\n if (\n currentUid === undefined ||\n details.uid !== currentUid ||\n (details.mode & 0o777) !== 0o600 ||\n details.size !== 44 ||\n !/^[A-Za-z0-9_-]{43}\\n$/.test(secret)\n ) {\n throw unsafeFilesystemEntry(\n 'Application secret must be a complete current-user-owned mode-0600 value in the expected format.',\n );\n }\n return secret;\n } finally {\n await file.close();\n }\n}\n\nasync function syncDirectory(\n path: string,\n canonicalSourceRoot: string,\n): Promise<void> {\n const directory = await openSafeDirectory(path, canonicalSourceRoot);\n try {\n await directory.sync();\n } finally {\n await directory.close();\n }\n}\n\nasync function removeStaleSecretTemps(directoryPath: string): Promise<void> {\n const prefix = `.${SECRET_FILE_NAME}.tmp-`;\n for (const entry of await readdir(directoryPath)) {\n if (!entry.startsWith(prefix)) continue;\n try {\n await unlink(resolve(directoryPath, entry));\n } catch (error) {\n if (!isMissingFile(error)) throw error;\n }\n }\n}\n\nasync function openSafeDirectory(path: string, canonicalSourceRoot: string) {\n let directory: FileHandle | undefined;\n try {\n directory = await open(\n path,\n constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW,\n );\n await validateOpenHandlePath(\n directory,\n path,\n 'directory',\n canonicalSourceRoot,\n );\n return directory;\n } catch (error) {\n await directory?.close();\n if (error instanceof LocalRuntimeError) throw error;\n throw unsafeFilesystemEntry(\n `Could not safely open local runtime directory: ${path}`,\n error,\n );\n }\n}\n\nasync function openSafeFile(\n path: string,\n flags: number,\n mode: number,\n label: string,\n canonicalSourceRoot: string,\n) {\n let file: FileHandle | undefined;\n try {\n file = await open(path, flags | constants.O_NOFOLLOW, mode);\n await validateOpenHandlePath(file, path, 'file', canonicalSourceRoot);\n return file;\n } catch (error) {\n await file?.close();\n if (error instanceof LocalRuntimeError || isFileAlreadyExists(error)) {\n throw error;\n }\n throw unsafeFilesystemEntry(\n `${label} could not be opened without following symbolic links.`,\n error,\n );\n }\n}\n\nasync function validateOpenHandlePath(\n handle: FileHandle,\n path: string,\n expectedType: 'directory' | 'file',\n canonicalSourceRoot: string,\n): Promise<void> {\n const opened = await handle.stat();\n const current = await lstat(path);\n const expectedDirectory = expectedType === 'directory';\n if (\n current.isSymbolicLink() ||\n (expectedDirectory ? !opened.isDirectory() : !opened.isFile()) ||\n (expectedDirectory ? !current.isDirectory() : !current.isFile()) ||\n opened.dev !== current.dev ||\n opened.ino !== current.ino\n ) {\n throw unsafeFilesystemEntry(\n `Local runtime ${expectedType} changed while it was being opened: ${path}`,\n );\n }\n await validateExistingPathChain(path, canonicalSourceRoot, expectedType);\n const afterValidation = await lstat(path);\n if (\n afterValidation.isSymbolicLink() ||\n opened.dev !== afterValidation.dev ||\n opened.ino !== afterValidation.ino\n ) {\n throw unsafeFilesystemEntry(\n `Local runtime ${expectedType} changed during validation: ${path}`,\n );\n }\n}\n\nasync function validateExistingPathChain(\n path: string,\n canonicalSourceRoot: string,\n leafType: 'directory' | 'file',\n): Promise<void> {\n const components = absolutePathComponents(path);\n for (const [index, component] of components.entries()) {\n const details = await lstat(component);\n const expectedFile = index === components.length - 1 && leafType === 'file';\n if (\n details.isSymbolicLink() ||\n (expectedFile ? !details.isFile() : !details.isDirectory())\n ) {\n throw unsafeFilesystemEntry(\n `Local runtime path contains an unsafe component: ${component}`,\n );\n }\n await assertCanonicalEntry(component, canonicalSourceRoot);\n }\n}\n\nasync function assertCanonicalEntry(\n path: string,\n canonicalSourceRoot: string,\n): Promise<void> {\n const canonical = await realpath(path);\n if (!sameFilesystemPath(canonical, path)) {\n throw unsafeFilesystemEntry(\n `Local runtime path must not be redirected: ${path}`,\n );\n }\n if (isInside(canonicalSourceRoot, canonical)) {\n throw unsafeFilesystemEntry(\n 'Local application data must remain outside the canonical source tree.',\n );\n }\n}\n\nfunction absolutePathComponents(path: string): string[] {\n const absolute = resolve(path);\n const root = parse(absolute).root;\n const parts = absolute.slice(root.length).split(sep).filter(Boolean);\n const components = [root];\n for (const part of parts) {\n components.push(resolve(components.at(-1) as string, part));\n }\n return components;\n}\n\nfunction requireNoFollowSupport(): void {\n if (\n typeof constants.O_NOFOLLOW !== 'number' ||\n constants.O_NOFOLLOW === 0 ||\n typeof constants.O_DIRECTORY !== 'number' ||\n constants.O_DIRECTORY === 0\n ) {\n throw unsafeFilesystemEntry(\n 'This platform cannot safely initialize local storage without no-follow filesystem support.',\n );\n }\n}\n\nfunction sameFilesystemPath(\n left: string,\n right: string,\n runtimePlatform: NodeJS.Platform = platform(),\n): boolean {\n return (\n normalizeFilesystemIdentity(left, runtimePlatform) ===\n normalizeFilesystemIdentity(right, runtimePlatform)\n );\n}\n\nfunction usesCaseInsensitivePathGuards(\n runtimePlatform: NodeJS.Platform,\n): boolean {\n return runtimePlatform === 'win32' || runtimePlatform === 'darwin';\n}\n\nfunction normalizeFilesystemIdentity(\n value: string,\n runtimePlatform: NodeJS.Platform = platform(),\n): string {\n const normalized = resolve(value);\n return usesCaseInsensitivePathGuards(runtimePlatform)\n ? normalized.toLowerCase()\n : normalized;\n}\n\nfunction unsafeFilesystemEntry(message: string, cause?: unknown) {\n const error = new LocalRuntimeError('invalid_configuration', message);\n if (cause !== undefined)\n Object.defineProperty(error, 'cause', { value: cause });\n return error;\n}\n\nfunction validateBootstrapTtl(value: number): number {\n if (\n !Number.isInteger(value) ||\n value < 1 ||\n value > MAX_BOOTSTRAP_TTL_SECONDS\n ) {\n throw new LocalRuntimeError(\n 'invalid_configuration',\n `Owner bootstrap TTL must be an integer from 1 to ${MAX_BOOTSTRAP_TTL_SECONDS} seconds.`,\n );\n }\n return value;\n}\n\nfunction validateSessionTtl(value: number): number {\n if (!Number.isInteger(value) || value < 1) {\n throw new LocalRuntimeError(\n 'invalid_configuration',\n 'Session TTL must be a whole number of seconds greater than or equal to 1.',\n );\n }\n return value;\n}\n\nfunction validateOwnerInput(input: ClaimLocalOwnerInput): void {\n if (!input.token || !input.name.trim() || !input.email.trim()) {\n throw new LocalRuntimeError(\n 'bootstrap_invalid',\n 'Owner bootstrap requires a token, name, and email address.',\n );\n }\n}\n\nfunction normalizeLoopbackHost(value: string): string {\n const host = value\n .trim()\n .toLowerCase()\n .replace(/^\\[|\\]$/g, '');\n if (host === '::1') return host;\n const octets = host.split('.');\n if (\n octets.length === 4 &&\n octets.every((part) => /^\\d{1,3}$/.test(part) && Number(part) <= 255) &&\n Number(octets[0]) === 127\n ) {\n return host;\n }\n throw new LocalRuntimeError(\n 'unsafe_public_exposure',\n 'Owner bootstrap is restricted to a loopback IP literal. Use ::1 or 127.0.0.0/8.',\n );\n}\n\n/** Validate an explicit runtime identity. */\nexport function validateApplicationId(value: string): string {\n const appId = value.trim().toLowerCase();\n if (!/^[a-z0-9][a-z0-9.-]{0,62}$/.test(appId)) {\n throw new LocalRuntimeError(\n 'invalid_configuration',\n 'appId must contain only lowercase letters, digits, dots, or hyphens.',\n );\n }\n return appId;\n}\n\n/** Encode a package/project identity into a collision-resistant runtime ID. */\nexport function encodeApplicationId(value: string): string {\n const source = value.trim().toLowerCase();\n if (/^[a-z0-9][a-z0-9.-]{0,62}$/.test(source)) return source;\n const digest = createHash('sha256')\n .update(value.trim())\n .digest('hex')\n .slice(0, 10);\n const slug =\n source\n .replace(/[^a-z0-9.-]+/g, '-')\n .replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, '')\n .slice(0, 52)\n .replace(/[^a-z0-9]+$/g, '') || 'app';\n return validateApplicationId(`${slug}-${digest}`);\n}\n\nfunction defaultApplicationDataRoot(\n runtimePlatform: NodeJS.Platform,\n runtimeHome: string,\n env: NodeJS.ProcessEnv,\n): string {\n if (runtimePlatform === 'darwin') {\n return resolve(runtimeHome, 'Library', 'Application Support');\n }\n if (runtimePlatform === 'win32') {\n return resolve(env.LOCALAPPDATA ?? env.APPDATA ?? runtimeHome);\n }\n return resolve(env.XDG_DATA_HOME ?? resolve(runtimeHome, '.local', 'share'));\n}\n\nfunction isInside(\n parent: string,\n child: string,\n runtimePlatform: NodeJS.Platform = platform(),\n): boolean {\n const normalizedParent = normalizeFilesystemIdentity(parent, runtimePlatform);\n const normalizedChild = normalizeFilesystemIdentity(child, runtimePlatform);\n const path = relative(normalizedParent, normalizedChild);\n return path === '' || (!path.startsWith('..') && !isAbsolute(path));\n}\n\nfunction parseStoredDate(value: unknown): Date | null {\n if (!(typeof value === 'string' || value instanceof Date)) return null;\n const date = value instanceof Date ? value : new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\nfunction requireId(value: unknown, label: string): string {\n if (typeof value !== 'string' || value.length === 0) {\n throw new Error(`${label} was not persisted with an id.`);\n }\n return value;\n}\n\nfunction isMissingFile(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'ENOENT'\n );\n}\n\nfunction hasMissingFileCause(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'cause' in error &&\n isMissingFile((error as { cause?: unknown }).cause)\n );\n}\n\nfunction isFileAlreadyExists(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'EEXIST'\n );\n}\n\nfunction isDirectoryNotEmpty(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'ENOTEMPTY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AO,MAAM,KAAK,QAAQ,CAAC,IAAI,OAAO;AAC/C;AAEA,SAAS,UAAU,OAAgB,OAAuB;CACxD,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAChD,MAAM,IAAI,MAAM,GAAG,MAAK,+BAAgC;CAE1D,OAAO;AACT;AAEA,SAAS,cAAc,OAAyB;CAC9C,OACE,OAAO,UAAU,YACjB,UAAU,QACV,UAAU,SACT,MAA6B,SAAS;AAE3C;AAEA,SAAS,oBAAoB,OAAyB;CACpD,OACE,OAAO,UAAU,YACjB,UAAU,QACV,WAAW,SACX,cAAe,MAA8B,KAAK;AAEtD;AAEA,SAAS,oBAAoB,OAAyB;CACpD,OACE,OAAO,UAAU,YACjB,UAAU,QACV,UAAU,SACT,MAA6B,SAAS;AAE3C;AAEA,SAAS,oBAAoB,OAAyB;CACpD,OACE,OAAO,UAAU,YACjB,UAAU,QACV,UAAU,SACT,MAA6B,SAAS;AAE3C"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/deployed-runtime.ts","../src/runtime-diagnostics.ts","../src/index.ts"],"sourcesContent":["/**\n * Application-side composition for public self-hosted and managed-cloud\n * runtimes. Provider credentials and vendor clients remain in their owning\n * adapters; this module validates the selected seams, owns the PostgreSQL\n * connection lifecycle, and exposes orchestration-safe diagnostics.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nimport {\n type ApplicationRuntimeProfile,\n type AssetStorageProvider,\n type AuthenticationProvider,\n type ResolvedApplicationRuntime,\n type RuntimeProviderOverrides,\n resolveApplicationRuntime,\n type SecretProvider,\n} from '@happyvertical/smrt-config';\nimport {\n ScheduleRunner,\n type ScheduleRunnerConfig,\n TaskRunner,\n type TaskRunnerConfig,\n} from '@happyvertical/smrt-jobs';\nimport { SessionService } from '@happyvertical/smrt-users';\nimport type { DatabaseInterface } from '@happyvertical/sql';\n\nexport type DeployedApplicationRuntimeProfile = Exclude<\n ApplicationRuntimeProfile,\n 'local'\n>;\n\nexport type PublicAuthenticationProvider = Exclude<\n AuthenticationProvider,\n 'owner-bootstrap'\n>;\n\nexport type DeployedRuntimeComponent =\n | 'database'\n | 'authentication'\n | 'assets'\n | 'secrets';\n\n/**\n * A provider-owned readiness boundary.\n *\n * The callback should prove that required configuration is present and that\n * the provider is usable. It must not return credentials or secret values.\n */\nexport interface DeployedProviderBinding<Provider extends string> {\n readonly provider: Provider;\n readonly readiness: () => Promise<void>;\n}\n\n/** PostgreSQL connection factory. URLs and credentials stay in this adapter. */\nexport interface DeployedDatabaseBinding {\n readonly engine: 'postgres';\n readonly connect: () => Promise<DatabaseInterface>;\n readonly readiness?: (db: DatabaseInterface) => Promise<void>;\n /**\n * Provider-owned cleanup boundary, required before a connection is opened.\n * Keeping cleanup on the binding also covers malformed connection handles.\n */\n readonly close: (db: DatabaseInterface) => Promise<void>;\n}\n\nexport interface DeployedApplicationRuntimeOptions {\n readonly profile: DeployedApplicationRuntimeProfile;\n /** Validated selector overrides; never put credentials in this object. */\n readonly providers?: RuntimeProviderOverrides;\n readonly database: DeployedDatabaseBinding;\n readonly authentication: DeployedProviderBinding<PublicAuthenticationProvider>;\n readonly assets: DeployedProviderBinding<AssetStorageProvider>;\n readonly secrets: DeployedProviderBinding<SecretProvider>;\n /** Explicit, idempotent application migration hook. */\n readonly prepareDatabase?: (db: DatabaseInterface) => Promise<void>;\n}\n\nexport interface DeployedProviderDiagnostic {\n readonly provider: string;\n readonly configured: true;\n}\n\nexport interface DeployedRuntimeDiagnostics {\n readonly schemaVersion: 1;\n readonly runtime: ResolvedApplicationRuntime;\n readonly providers: {\n readonly database: DeployedProviderDiagnostic;\n readonly authentication: DeployedProviderDiagnostic;\n readonly assets: DeployedProviderDiagnostic;\n readonly secrets: DeployedProviderDiagnostic;\n };\n readonly tenancy: {\n readonly mode: 'single-tenant' | 'multi-tenant';\n readonly context: 'defaulted' | 'required';\n readonly isolation: 'application' | 'database-rls';\n readonly rootTenantFallback: 'disabled';\n };\n readonly workers: {\n readonly topology: 'external' | 'scalable';\n readonly taskProcess: 'separate';\n readonly scheduleProcess: 'separate';\n readonly replicas: 'operator-managed' | 'horizontal';\n };\n readonly secretValuesIncluded: false;\n}\n\nexport interface DeployedRuntimeHealth {\n readonly schemaVersion: 1;\n readonly profile: DeployedApplicationRuntimeProfile;\n readonly status: 'healthy' | 'stopped';\n}\n\nexport interface DeployedComponentReadiness {\n readonly status: 'ready' | 'not-ready';\n}\n\nexport interface DeployedRuntimeReadiness {\n readonly schemaVersion: 1;\n readonly profile: DeployedApplicationRuntimeProfile;\n readonly status: 'ready' | 'not-ready';\n readonly components: Readonly<\n Record<DeployedRuntimeComponent, DeployedComponentReadiness>\n >;\n readonly secretValuesIncluded: false;\n}\n\nexport type DeployedRuntimeErrorCode =\n | 'invalid_configuration'\n | 'provider_mismatch'\n | 'provider_unavailable'\n | 'tenant_context_required'\n | 'tenant_context_unauthorized'\n | 'runtime_stopped';\n\n/** Stable failure that never includes a provider's underlying error text. */\nexport class DeployedRuntimeError extends Error {\n constructor(\n readonly code: DeployedRuntimeErrorCode,\n message: string,\n readonly component?: DeployedRuntimeComponent,\n ) {\n super(message);\n this.name = 'DeployedRuntimeError';\n }\n}\n\n/** Startup failure that retains the only safe retry path for database cleanup. */\nexport class DeployedRuntimeCleanupError extends DeployedRuntimeError {\n private cleaned = false;\n private cleanupAttempt?: Promise<void>;\n\n constructor(private readonly cleanup: () => Promise<void>) {\n super(\n 'provider_unavailable',\n \"The database connection could not be closed after startup failed; retry cleanup and inspect the provider's private logs.\",\n 'database',\n );\n this.name = 'DeployedRuntimeCleanupError';\n }\n\n async retryCleanup(): Promise<void> {\n if (this.cleaned) return;\n if (!this.cleanupAttempt) {\n this.cleanupAttempt = Promise.resolve()\n .then(() => this.cleanup())\n .then(() => {\n this.cleaned = true;\n })\n .catch(() => {\n throw this;\n })\n .finally(() => {\n this.cleanupAttempt = undefined;\n });\n }\n return this.cleanupAttempt;\n }\n}\n\nexport interface DeployedApplicationRuntime {\n readonly db: DatabaseInterface;\n readonly resolvedRuntime: ResolvedApplicationRuntime;\n restoreSession(\n sessionId: string,\n ): ReturnType<SessionService['loadSessionContext']>;\n createTaskWorker(config?: TaskRunnerConfig): Promise<TaskRunner>;\n createScheduleWorker(config?: ScheduleRunnerConfig): Promise<ScheduleRunner>;\n diagnostics(): DeployedRuntimeDiagnostics;\n health(): DeployedRuntimeHealth;\n readiness(): Promise<DeployedRuntimeReadiness>;\n close(): Promise<void>;\n}\n\ninterface ValidatedBindings {\n database: DeployedDatabaseBinding;\n authentication: DeployedProviderBinding<PublicAuthenticationProvider>;\n assets: DeployedProviderBinding<AssetStorageProvider>;\n secrets: DeployedProviderBinding<SecretProvider>;\n}\n\n/**\n * Initialize a self-hosted or cloud application composition.\n *\n * Configuration and provider identity are validated before a connection is\n * opened. Provider readiness and database migrations complete before the\n * runtime is returned. A failed initialization closes the acquired connection.\n */\nexport async function initializeDeployedApplicationRuntime(\n options: DeployedApplicationRuntimeOptions,\n): Promise<DeployedApplicationRuntime> {\n const resolvedRuntime = resolveDeployedRuntime(options);\n const bindings = validateBindings(options, resolvedRuntime);\n const prepareDatabase = snapshotPrepareDatabase(options);\n\n await checkProvider('authentication', () =>\n bindings.authentication.readiness(),\n );\n await checkProvider('assets', () => bindings.assets.readiness());\n await checkProvider('secrets', () => bindings.secrets.readiness());\n\n let db: DatabaseInterface | undefined;\n try {\n db = await bindings.database.connect();\n } catch {\n throw unavailable('database');\n }\n let validDatabase = false;\n try {\n validDatabase = isDatabaseInterface(db);\n } catch {\n // Treat throwing accessors on an untrusted handle as malformed.\n }\n if (!validDatabase) {\n await cleanupAfterStartupFailure(\n bindings.database,\n db,\n new DeployedRuntimeError(\n 'invalid_configuration',\n 'The database adapter did not return a valid database connection.',\n 'database',\n ),\n );\n }\n try {\n await checkDatabase(bindings.database, db);\n } catch (error) {\n await cleanupAfterStartupFailure(bindings.database, db, error);\n }\n try {\n await prepareDatabase?.(db);\n } catch {\n await cleanupAfterStartupFailure(\n bindings.database,\n db,\n new DeployedRuntimeError(\n 'provider_unavailable',\n 'The PostgreSQL migration step failed; inspect the application migration logs.',\n 'database',\n ),\n );\n }\n\n return new InitializedDeployedApplicationRuntime(\n db,\n resolvedRuntime,\n bindings,\n );\n}\n\nfunction resolveDeployedRuntime(\n options: DeployedApplicationRuntimeOptions,\n): ResolvedApplicationRuntime {\n let plainOptions = false;\n try {\n plainOptions = isPlainRecord(options);\n } catch {\n // Proxies and throwing prototype traps are invalid options.\n }\n if (!plainOptions) {\n throw new DeployedRuntimeError(\n 'invalid_configuration',\n 'Deployed runtime options must be an object.',\n );\n }\n let profile: unknown;\n let providers: RuntimeProviderOverrides | undefined;\n try {\n profile = options.profile;\n providers = options.providers;\n } catch {\n throw new DeployedRuntimeError(\n 'invalid_configuration',\n 'Deployed runtime options could not be read safely.',\n );\n }\n if (profile !== 'self-hosted' && profile !== 'cloud') {\n throw new DeployedRuntimeError(\n 'invalid_configuration',\n 'Deployed runtime initialization requires the self-hosted or cloud profile.',\n );\n }\n try {\n return resolveApplicationRuntime({ profile, providers });\n } catch {\n throw new DeployedRuntimeError(\n 'invalid_configuration',\n 'Deployed runtime provider options could not be read safely.',\n );\n }\n}\n\nfunction validateBindings(\n options: DeployedApplicationRuntimeOptions,\n runtime: ResolvedApplicationRuntime,\n): ValidatedBindings {\n const databaseSource = readBindingOption(options, 'database', 'database');\n const database = requireObjectBinding<DeployedDatabaseBinding>(\n databaseSource,\n 'database',\n );\n let engine: unknown;\n let connect: unknown;\n let readiness: unknown;\n let close: unknown;\n try {\n engine = database.engine;\n connect = database.connect;\n readiness = database.readiness;\n close = database.close;\n } catch {\n throw invalidBinding('database');\n }\n requireFunction(connect, 'database', 'connect');\n requireOptionalFunction(readiness, 'database', 'readiness');\n requireFunction(close, 'database', 'close');\n if (engine !== runtime.providers.database.engine) {\n throw mismatch('database', runtime.providers.database.engine);\n }\n const databaseSnapshot: DeployedDatabaseBinding = Object.freeze({\n engine: engine as 'postgres',\n connect: bindCallback(\n connect as DeployedDatabaseBinding['connect'],\n database,\n 'database',\n ),\n readiness:\n typeof readiness === 'function'\n ? bindCallback(\n readiness as NonNullable<DeployedDatabaseBinding['readiness']>,\n database,\n 'database',\n )\n : undefined,\n close: bindCallback(\n close as DeployedDatabaseBinding['close'],\n database,\n 'database',\n ),\n });\n\n const authentication = requireProviderBinding(\n readBindingOption(options, 'authentication', 'authentication'),\n 'authentication',\n runtime.providers.authentication.provider,\n ) as DeployedProviderBinding<PublicAuthenticationProvider>;\n const assets = requireProviderBinding(\n readBindingOption(options, 'assets', 'assets'),\n 'assets',\n runtime.providers.assets.provider,\n ) as DeployedProviderBinding<AssetStorageProvider>;\n const secrets = requireProviderBinding(\n readBindingOption(options, 'secrets', 'secrets'),\n 'secrets',\n runtime.providers.secrets.provider,\n ) as DeployedProviderBinding<SecretProvider>;\n\n return {\n database: databaseSnapshot,\n authentication,\n assets,\n secrets,\n };\n}\n\nfunction snapshotPrepareDatabase(\n options: DeployedApplicationRuntimeOptions,\n): DeployedApplicationRuntimeOptions['prepareDatabase'] {\n let prepareDatabase: unknown;\n try {\n prepareDatabase = options.prepareDatabase;\n } catch {\n throw invalidBinding('database');\n }\n requireOptionalFunction(prepareDatabase, 'database', 'prepareDatabase');\n return typeof prepareDatabase === 'function'\n ? bindCallback(\n prepareDatabase as NonNullable<\n DeployedApplicationRuntimeOptions['prepareDatabase']\n >,\n options,\n 'database',\n )\n : undefined;\n}\n\nfunction readBindingOption(\n options: DeployedApplicationRuntimeOptions,\n field: 'database' | 'authentication' | 'assets' | 'secrets',\n component: DeployedRuntimeComponent,\n): unknown {\n try {\n return options[field];\n } catch {\n throw invalidBinding(component);\n }\n}\n\nfunction requireProviderBinding(\n value: unknown,\n component: Exclude<DeployedRuntimeComponent, 'database'>,\n expectedProvider: string,\n): DeployedProviderBinding<string> {\n const binding = requireObjectBinding<DeployedProviderBinding<string>>(\n value,\n component,\n );\n let provider: unknown;\n let readiness: unknown;\n try {\n provider = binding.provider;\n readiness = binding.readiness;\n } catch {\n throw invalidBinding(component);\n }\n if (provider !== expectedProvider) {\n throw mismatch(component, expectedProvider);\n }\n requireFunction(readiness, component, 'readiness');\n return Object.freeze({\n provider: provider as string,\n readiness: bindCallback(\n readiness as DeployedProviderBinding<string>['readiness'],\n binding,\n component,\n ),\n });\n}\n\nfunction requireObjectBinding<T>(\n value: unknown,\n component: DeployedRuntimeComponent,\n): T {\n let valid = false;\n try {\n valid =\n typeof value === 'object' && value !== null && !Array.isArray(value);\n } catch {\n // Revoked proxies and throwing shape traps are invalid bindings.\n }\n if (!valid) {\n throw new DeployedRuntimeError(\n 'invalid_configuration',\n `The ${component} provider binding is required.`,\n component,\n );\n }\n return value as T;\n}\n\nfunction invalidBinding(\n component: DeployedRuntimeComponent,\n): DeployedRuntimeError {\n return new DeployedRuntimeError(\n 'invalid_configuration',\n `The ${component} provider binding could not be read safely.`,\n component,\n );\n}\n\nfunction bindCallback<T>(\n callback: T,\n receiver: unknown,\n component: DeployedRuntimeComponent,\n): T {\n try {\n return Reflect.apply(\n Function.prototype.bind,\n callback as (...args: never[]) => unknown,\n [receiver],\n ) as T;\n } catch {\n throw invalidBinding(component);\n }\n}\n\nfunction requireFunction(\n value: unknown,\n component: DeployedRuntimeComponent,\n field: string,\n): void {\n if (typeof value !== 'function') {\n throw new DeployedRuntimeError(\n 'invalid_configuration',\n `The ${component} provider requires a ${field} callback.`,\n component,\n );\n }\n}\n\nfunction requireOptionalFunction(\n value: unknown,\n component: DeployedRuntimeComponent,\n field: string,\n): void {\n if (value !== undefined) requireFunction(value, component, field);\n}\n\nfunction mismatch(\n component: DeployedRuntimeComponent,\n expectedProvider: string,\n): DeployedRuntimeError {\n return new DeployedRuntimeError(\n 'provider_mismatch',\n `The ${component} binding does not match the selected ${expectedProvider} provider.`,\n component,\n );\n}\n\nfunction unavailable(\n component: DeployedRuntimeComponent,\n): DeployedRuntimeError {\n return new DeployedRuntimeError(\n 'provider_unavailable',\n `The ${component} provider is not ready; inspect that provider's private logs.`,\n component,\n );\n}\n\nasync function checkProvider(\n component: Exclude<DeployedRuntimeComponent, 'database'>,\n check: () => Promise<void>,\n): Promise<void> {\n try {\n await check();\n } catch {\n throw unavailable(component);\n }\n}\n\nasync function checkDatabase(\n binding: DeployedDatabaseBinding,\n db: DatabaseInterface,\n): Promise<void> {\n try {\n await binding.readiness?.(db);\n const result = await db.query(\n \"SELECT current_setting('server_version_num') AS smrt_postgres_version\",\n );\n if (!isValidPostgresProbe(result)) throw new Error('invalid probe');\n } catch {\n throw unavailable('database');\n }\n}\n\nclass InitializedDeployedApplicationRuntime\n implements DeployedApplicationRuntime\n{\n private state: 'running' | 'closing' | 'close-failed' | 'stopped' = 'running';\n private closeAttempt?: Promise<void>;\n private readonly pendingReadinessChecks = new Set<Promise<unknown>>();\n private readonly pendingSessionRestorations = new Set<Promise<unknown>>();\n private readonly pendingWorkerInitializations = new Set<Promise<unknown>>();\n private readonly pendingWorkerOperations = new Set<Promise<unknown>>();\n private readonly lifecycleOperationContext = new AsyncLocalStorage<symbol>();\n private readonly activeLifecycleOperations = new Set<symbol>();\n private readonly workerCleanups = new Set<() => Promise<void>>();\n private readonly sessionService: SessionService;\n private sessionServiceReady?: Promise<void>;\n private readonly snapshot: DeployedRuntimeDiagnostics;\n\n constructor(\n readonly db: DatabaseInterface,\n readonly resolvedRuntime: ResolvedApplicationRuntime,\n private readonly bindings: ValidatedBindings,\n ) {\n this.snapshot = createDiagnostics(resolvedRuntime);\n this.sessionService = new SessionService({ db });\n }\n\n async restoreSession(sessionId: string) {\n this.assertRunning();\n const operation = this.beginLifecycleOperation(() =>\n this.restoreSessionWhileRunning(sessionId),\n );\n this.pendingSessionRestorations.add(operation);\n try {\n return await operation;\n } finally {\n this.pendingSessionRestorations.delete(operation);\n }\n }\n\n private async restoreSessionWhileRunning(sessionId: string) {\n let context: Awaited<ReturnType<SessionService['loadSessionContext']>>;\n try {\n await this.initializeSessionService();\n context = await this.sessionService.loadSessionContext(sessionId);\n } catch {\n throw unavailable('authentication');\n }\n this.assertRunning();\n if (\n context &&\n this.resolvedRuntime.providers.tenancy.context === 'required'\n ) {\n let tenantId: unknown;\n try {\n tenantId = context.tenantId;\n } catch {\n throw unavailable('authentication');\n }\n if (typeof tenantId !== 'string' || tenantId.trim().length === 0) {\n throw new DeployedRuntimeError(\n 'tenant_context_required',\n 'The authenticated session does not include the required tenant context.',\n 'authentication',\n );\n }\n let tenantAuthorized = false;\n try {\n const membership = context.membership;\n const authorization = context.tenantAuthorization;\n const membershipId = authorization?.membershipId;\n const validMembershipId =\n typeof membershipId === 'string' && membershipId.trim().length > 0;\n if (membership?.isActive() === true) {\n tenantAuthorized =\n validMembershipId &&\n membership.id === membershipId &&\n authorization?.inheritedFromTenantId === null;\n } else if (membership === null) {\n tenantAuthorized =\n validMembershipId &&\n typeof authorization?.inheritedFromTenantId === 'string' &&\n authorization.inheritedFromTenantId.trim().length > 0;\n }\n } catch {\n throw unavailable('authentication');\n }\n if (!tenantAuthorized) {\n throw new DeployedRuntimeError(\n 'tenant_context_unauthorized',\n 'The authenticated session is not authorized for its tenant context.',\n 'authentication',\n );\n }\n }\n return context;\n }\n\n async createTaskWorker(config: TaskRunnerConfig = {}): Promise<TaskRunner> {\n this.assertRunning();\n const operation = this.beginLifecycleOperation(() =>\n this.initializeTaskWorker(config),\n );\n this.pendingWorkerInitializations.add(operation);\n try {\n const runner = await operation;\n return this.retainWorker(runner);\n } finally {\n this.pendingWorkerInitializations.delete(operation);\n }\n }\n\n async createScheduleWorker(\n config: ScheduleRunnerConfig = {},\n ): Promise<ScheduleRunner> {\n this.assertRunning();\n const operation = this.beginLifecycleOperation(() =>\n this.initializeScheduleWorker(config),\n );\n this.pendingWorkerInitializations.add(operation);\n try {\n const runner = await operation;\n return this.retainWorker(runner);\n } finally {\n this.pendingWorkerInitializations.delete(operation);\n }\n }\n\n diagnostics(): DeployedRuntimeDiagnostics {\n return this.snapshot;\n }\n\n health(): DeployedRuntimeHealth {\n return Object.freeze({\n schemaVersion: 1 as const,\n profile: this.resolvedRuntime\n .profile as DeployedApplicationRuntimeProfile,\n status:\n this.state === 'running' ? ('healthy' as const) : ('stopped' as const),\n });\n }\n\n async readiness(): Promise<DeployedRuntimeReadiness> {\n if (this.state !== 'running')\n return createStoppedReadiness(this.resolvedRuntime.profile);\n\n const operation = this.beginLifecycleOperation(() =>\n this.checkReadinessWhileRunning(),\n );\n this.pendingReadinessChecks.add(operation);\n try {\n return await operation;\n } finally {\n this.pendingReadinessChecks.delete(operation);\n }\n }\n\n private async checkReadinessWhileRunning(): Promise<DeployedRuntimeReadiness> {\n const results = await Promise.all([\n probe(() => checkDatabase(this.bindings.database, this.db)),\n probe(() => this.bindings.authentication.readiness()),\n probe(() => this.bindings.assets.readiness()),\n probe(() => this.bindings.secrets.readiness()),\n ]);\n if (this.state !== 'running') {\n return createStoppedReadiness(this.resolvedRuntime.profile);\n }\n const [database, authentication, assets, secrets] = results;\n return freezeReadiness(\n this.resolvedRuntime.profile,\n { database, authentication, assets, secrets },\n results.every((result) => result.status === 'ready'),\n );\n }\n\n async close(): Promise<void> {\n const operationToken = this.lifecycleOperationContext.getStore();\n const requestedFromLifecycleOperation =\n operationToken !== undefined &&\n this.activeLifecycleOperations.has(operationToken);\n if (this.state === 'stopped') return;\n if (this.closeAttempt) {\n if (requestedFromLifecycleOperation) return;\n return this.closeAttempt;\n }\n\n this.state = 'closing';\n const pendingOperations = [\n ...this.pendingReadinessChecks,\n ...this.pendingSessionRestorations,\n ...this.pendingWorkerInitializations,\n ...this.pendingWorkerOperations,\n ];\n const shutdownToken = Symbol('deployed-runtime-shutdown');\n this.activeLifecycleOperations.add(shutdownToken);\n const attempt = Promise.resolve()\n .then(() =>\n this.lifecycleOperationContext.run(shutdownToken, async () => {\n await Promise.allSettled(pendingOperations);\n await this.cleanupWorkers();\n await this.closeConnection();\n }),\n )\n .finally(() => {\n this.activeLifecycleOperations.delete(shutdownToken);\n });\n this.closeAttempt = attempt.finally(() => {\n this.closeAttempt = undefined;\n });\n if (requestedFromLifecycleOperation) {\n // The lifecycle callback cannot await the shutdown pipeline without\n // deadlocking on itself. It receives an acknowledgement instead, but the\n // internally owned attempt still needs a rejection observer until an\n // outside caller can retry the failed cleanup.\n void this.closeAttempt.catch(() => undefined);\n return;\n }\n return this.closeAttempt;\n }\n\n private async initializeTaskWorker(\n config: TaskRunnerConfig,\n ): Promise<TaskRunner> {\n let runner: TaskRunner | undefined;\n try {\n runner = new TaskRunner(config);\n await runner.initialize(this.db);\n } catch {\n if (runner) await this.stopOrRetainUnreturnedWorker(runner);\n throw unavailable('database');\n }\n if (this.state !== 'running') {\n await this.stopOrRetainUnreturnedWorker(runner);\n this.assertRunning();\n }\n return runner;\n }\n\n private async initializeScheduleWorker(\n config: ScheduleRunnerConfig,\n ): Promise<ScheduleRunner> {\n let runner: ScheduleRunner | undefined;\n try {\n runner = new ScheduleRunner(config);\n await runner.initialize(this.db);\n } catch {\n if (runner) await this.stopOrRetainUnreturnedWorker(runner);\n throw unavailable('database');\n }\n if (this.state !== 'running') {\n await this.stopOrRetainUnreturnedWorker(runner);\n this.assertRunning();\n }\n return runner;\n }\n\n private async stopOrRetainUnreturnedWorker(runner: {\n stop(): Promise<void>;\n }): Promise<void> {\n const cleanup = () => runner.stop();\n try {\n await cleanup();\n } catch {\n this.workerCleanups.add(cleanup);\n }\n }\n\n private retainWorker<Runner extends TaskRunner | ScheduleRunner>(\n runner: Runner,\n ): Runner {\n const start = runner.start.bind(runner);\n const stop = runner.stop.bind(runner);\n let operationTail = Promise.resolve();\n const queueOperation = (callback: () => Promise<void>): Promise<void> => {\n const previous = operationTail;\n const operation = this.beginLifecycleOperation(async () => {\n await previous;\n await callback();\n });\n operationTail = operation.catch(() => undefined);\n this.pendingWorkerOperations.add(operation);\n void operation.then(\n () => {\n this.pendingWorkerOperations.delete(operation);\n },\n () => {\n this.pendingWorkerOperations.delete(operation);\n },\n );\n return operation;\n };\n const ownedStart = async (): Promise<void> => {\n this.assertRunning();\n return queueOperation(async () => {\n this.assertRunning();\n try {\n await start();\n this.assertRunning();\n } catch {\n // A runner can reject after it has made itself live (for example,\n // when a runner:started listener throws). Keep this cleanup inside\n // the tracked lifecycle operation so shutdown cannot call stop()\n // concurrently on the same runner.\n if (this.state === 'running') {\n try {\n await stop();\n } catch {\n // The runtime-owned cleanup is already retained in workerCleanups.\n }\n }\n if (this.state !== 'running') this.assertRunning();\n throw unavailable('database');\n }\n });\n };\n const ownedStop = (): Promise<void> =>\n queueOperation(async () => {\n try {\n await stop();\n } catch {\n throw unavailable('database');\n }\n });\n Object.defineProperties(runner, {\n start: {\n configurable: false,\n enumerable: false,\n value: ownedStart,\n writable: false,\n },\n stop: {\n configurable: false,\n enumerable: false,\n value: ownedStop,\n writable: false,\n },\n });\n this.workerCleanups.add(ownedStop);\n return runner;\n }\n\n private async cleanupWorkers(): Promise<void> {\n const cleanups = [...this.workerCleanups];\n const results = await Promise.allSettled(\n cleanups.map((cleanup) => Promise.resolve().then(cleanup)),\n );\n let cleanupFailed = false;\n for (const [index, result] of results.entries()) {\n if (result.status === 'fulfilled') {\n const cleanup = cleanups[index];\n if (cleanup) this.workerCleanups.delete(cleanup);\n } else cleanupFailed = true;\n }\n if (cleanupFailed) {\n this.state = 'close-failed';\n throw unavailable('database');\n }\n }\n\n private initializeSessionService(): Promise<void> {\n if (!this.sessionServiceReady) {\n this.sessionServiceReady = this.sessionService\n .initialize()\n .catch((error) => {\n this.sessionServiceReady = undefined;\n throw error;\n });\n }\n return this.sessionServiceReady;\n }\n\n private beginLifecycleOperation<T>(operation: () => Promise<T>): Promise<T> {\n const token = Symbol('deployed-runtime-operation');\n this.activeLifecycleOperations.add(token);\n return Promise.resolve()\n .then(() => this.lifecycleOperationContext.run(token, operation))\n .finally(() => {\n this.activeLifecycleOperations.delete(token);\n });\n }\n\n private async closeConnection(): Promise<void> {\n try {\n await this.bindings.database.close(this.db);\n this.state = 'stopped';\n } catch {\n this.state = 'close-failed';\n throw new DeployedRuntimeError(\n 'provider_unavailable',\n \"The database connection could not be closed; inspect the provider's private logs.\",\n 'database',\n );\n }\n }\n\n private assertRunning(): void {\n if (this.state !== 'running') {\n throw new DeployedRuntimeError(\n 'runtime_stopped',\n 'The deployed application runtime has already stopped.',\n );\n }\n }\n}\n\nfunction createDiagnostics(\n runtime: ResolvedApplicationRuntime,\n): DeployedRuntimeDiagnostics {\n const provider = (value: string): DeployedProviderDiagnostic =>\n Object.freeze({ provider: value, configured: true as const });\n return deepFreeze({\n schemaVersion: 1 as const,\n runtime,\n providers: {\n database: provider(runtime.providers.database.engine),\n authentication: provider(runtime.providers.authentication.provider),\n assets: provider(runtime.providers.assets.provider),\n secrets: provider(runtime.providers.secrets.provider),\n },\n tenancy: {\n mode: runtime.providers.tenancy.mode as 'single-tenant' | 'multi-tenant',\n context: runtime.providers.tenancy.context,\n isolation: runtime.providers.tenancy.isolation,\n rootTenantFallback: 'disabled' as const,\n },\n workers: {\n topology: runtime.providers.jobs.topology as 'external' | 'scalable',\n taskProcess: 'separate' as const,\n scheduleProcess: 'separate' as const,\n replicas:\n runtime.providers.jobs.topology === 'scalable'\n ? ('horizontal' as const)\n : ('operator-managed' as const),\n },\n secretValuesIncluded: false as const,\n });\n}\n\nasync function probe(\n check: () => Promise<void>,\n): Promise<DeployedComponentReadiness> {\n try {\n await check();\n return Object.freeze({ status: 'ready' as const });\n } catch {\n return Object.freeze({ status: 'not-ready' as const });\n }\n}\n\nfunction createStoppedReadiness(\n profile: ApplicationRuntimeProfile,\n): DeployedRuntimeReadiness {\n const stopped = Object.freeze({ status: 'not-ready' as const });\n return freezeReadiness(\n profile,\n {\n database: stopped,\n authentication: stopped,\n assets: stopped,\n secrets: stopped,\n },\n false,\n );\n}\n\nfunction freezeReadiness(\n profile: ApplicationRuntimeProfile,\n components: Record<DeployedRuntimeComponent, DeployedComponentReadiness>,\n ready: boolean,\n): DeployedRuntimeReadiness {\n return deepFreeze({\n schemaVersion: 1 as const,\n profile: profile as DeployedApplicationRuntimeProfile,\n status: ready ? ('ready' as const) : ('not-ready' as const),\n components,\n secretValuesIncluded: false as const,\n });\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isDatabaseInterface(value: unknown): value is DatabaseInterface {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { query?: unknown }).query === 'function'\n );\n}\n\nfunction isValidPostgresProbe(\n value: unknown,\n): value is { rows: Array<{ smrt_postgres_version: string }> } {\n if (typeof value !== 'object' || value === null) return false;\n const rows = (value as { rows?: unknown }).rows;\n if (!Array.isArray(rows) || rows.length !== 1) return false;\n const row = rows[0];\n if (typeof row !== 'object' || row === null) return false;\n const version = (row as { smrt_postgres_version?: unknown })\n .smrt_postgres_version;\n return typeof version === 'string' && /^\\d+$/.test(version);\n}\n\nasync function cleanupAfterStartupFailure(\n binding: DeployedDatabaseBinding,\n db: unknown,\n startupError: unknown,\n): Promise<never> {\n const cleanup = () => binding.close(db as DatabaseInterface);\n try {\n await cleanup();\n } catch {\n throw new DeployedRuntimeCleanupError(cleanup);\n }\n throw startupError;\n}\n\nfunction deepFreeze<T>(value: T, seen = new WeakSet<object>()): T {\n if (value && typeof value === 'object') {\n if (seen.has(value)) return value;\n seen.add(value);\n if (!Object.isFrozen(value)) Object.freeze(value);\n for (const child of Object.values(value as Record<string, unknown>)) {\n deepFreeze(child, seen);\n }\n }\n return value;\n}\n","import { createHash } from 'node:crypto';\n\nimport type { ApplicationRuntimeProfile } from '@happyvertical/smrt-config';\n\nexport const RUNTIME_DIAGNOSTICS_SCHEMA_VERSION = 1 as const;\nexport const MAX_RUNTIME_DIAGNOSTIC_TOOLS = 64;\nexport const MAX_RUNTIME_DIAGNOSTIC_ERRORS = 8;\nexport const RUNTIME_WORKER_FRESHNESS_SECONDS = 120;\n\nconst CAPABILITY_IDS = [\n 'asset-storage',\n 'authentication',\n 'background-jobs',\n 'database',\n 'paid-capabilities',\n 'secret-storage',\n] as const;\n\nconst ERROR_CODES = [\n 'authentication_unavailable',\n 'database_unavailable',\n 'migration_required',\n 'provider_unavailable',\n 'runtime_stopped',\n 'worker_stale',\n] as const;\n\nconst PROHIBITED_IDENTIFIER_PARTS = new Set([\n 'authorization',\n 'cookie',\n 'constructor',\n 'credential',\n 'email',\n 'hash',\n 'key',\n 'log',\n 'logs',\n 'password',\n 'path',\n 'record',\n 'prototype',\n 'secret',\n 'session',\n 'stack',\n 'tenant',\n 'token',\n 'url',\n 'user',\n]);\n\ntype CapabilityId = (typeof CAPABILITY_IDS)[number];\ntype CapabilityStatus = 'available' | 'disabled' | 'unavailable' | 'unknown';\ntype RuntimeDiagnosticErrorCode =\n | (typeof ERROR_CODES)[number]\n | 'runtime_error';\ntype WorkerTopology = 'embedded' | 'external' | 'inline' | 'scalable';\n\n/**\n * Versioned public diagnostics returned only after application authorization.\n * Every field is a fixed allowlist projection; this is intentionally not a\n * cleaned or serialized form of either private runtime diagnostics object.\n */\nexport interface RuntimeDiagnostics {\n readonly schemaVersion: 1;\n readonly profile: ApplicationRuntimeProfile | 'unknown';\n readonly health: 'healthy' | 'degraded' | 'stopped' | 'unknown';\n readonly schema: {\n readonly status: 'ready' | 'not-ready' | 'unknown';\n readonly migrations: 'current' | 'failed' | 'pending' | 'unknown';\n };\n readonly capabilities: readonly {\n readonly id: CapabilityId;\n readonly status: CapabilityStatus;\n }[];\n readonly tools: {\n readonly names: readonly string[];\n readonly count: number;\n readonly digest: string;\n };\n readonly operationalDifferences: {\n readonly backgroundJobs: 'disabled' | 'enabled';\n readonly workerTopology: WorkerTopology;\n };\n readonly worker: {\n readonly topology: WorkerTopology;\n readonly liveness: 'alive' | 'not-required' | 'stale' | 'unknown';\n readonly heartbeatAt: string | null;\n readonly observedAt: string;\n };\n readonly recentErrors: readonly {\n readonly code: RuntimeDiagnosticErrorCode;\n readonly at: string;\n }[];\n}\n\nexport interface RuntimeDiagnosticsProjectionInput {\n readonly profile?: unknown;\n readonly health?: unknown;\n readonly schema?: unknown;\n readonly capabilities?: unknown;\n readonly toolNames?: unknown;\n readonly worker?: unknown;\n readonly recentErrors?: unknown;\n /** Required explicit clock seam; the projector never reads the process clock. */\n readonly observedAt?: unknown;\n}\n\n/**\n * Project private local/deployed state into the deterministic public contract.\n * Unknown, oversized, nested, accessor-backed, or prohibited values are never\n * copied. Invalid error codes become `runtime_error` at ingestion.\n */\nexport function projectRuntimeDiagnostics(\n input: RuntimeDiagnosticsProjectionInput,\n): RuntimeDiagnostics {\n const source = plainRecord(input);\n const observedAtValue = read(source, 'observedAt');\n const observedAtMilliseconds = timestampMilliseconds(observedAtValue);\n const observedAt = coarseTimestamp(observedAtValue) ?? EPOCH;\n const profile = runtimeProfile(read(source, 'profile'));\n const worker = projectWorker(\n read(source, 'worker'),\n observedAt,\n observedAtMilliseconds,\n );\n const capabilities = projectCapabilities(read(source, 'capabilities'));\n const tools = canonicalTools(read(source, 'toolNames'));\n\n return deepFreeze({\n schemaVersion: RUNTIME_DIAGNOSTICS_SCHEMA_VERSION,\n profile,\n health: oneOf(read(source, 'health'), HEALTH_VALUES, 'unknown'),\n schema: projectSchema(read(source, 'schema')),\n capabilities,\n tools: {\n names: tools,\n count: tools.length,\n digest: createHash('sha256').update(tools.join('\\n')).digest('hex'),\n },\n operationalDifferences: {\n backgroundJobs:\n capabilityStatus(capabilities, 'background-jobs') === 'available'\n ? 'enabled'\n : 'disabled',\n workerTopology: worker.topology,\n },\n worker,\n recentErrors: projectErrors(read(source, 'recentErrors')),\n });\n}\n\nconst EPOCH = '1970-01-01T00:00:00.000Z';\nconst PROFILES = ['local', 'self-hosted', 'cloud', 'unknown'] as const;\nconst HEALTH_VALUES = ['healthy', 'degraded', 'stopped', 'unknown'] as const;\nconst SCHEMA_VALUES = ['ready', 'not-ready', 'unknown'] as const;\nconst MIGRATION_VALUES = ['current', 'failed', 'pending', 'unknown'] as const;\nconst CAPABILITY_VALUES = [\n 'available',\n 'disabled',\n 'unavailable',\n 'unknown',\n] as const;\nconst WORKER_TOPOLOGIES = [\n 'embedded',\n 'external',\n 'inline',\n 'scalable',\n] as const;\n\nfunction runtimeProfile(value: unknown): ApplicationRuntimeProfile | 'unknown' {\n return oneOf(value, PROFILES, 'unknown');\n}\n\nfunction projectSchema(value: unknown): RuntimeDiagnostics['schema'] {\n const source = plainRecord(value);\n return {\n status: oneOf(read(source, 'status'), SCHEMA_VALUES, 'unknown'),\n migrations: oneOf(read(source, 'migrations'), MIGRATION_VALUES, 'unknown'),\n };\n}\n\nfunction projectCapabilities(\n value: unknown,\n): RuntimeDiagnostics['capabilities'] {\n const source = plainRecord(value);\n return CAPABILITY_IDS.map((id) => ({\n id,\n status: oneOf(read(source, id), CAPABILITY_VALUES, 'unknown'),\n }));\n}\n\nfunction canonicalTools(value: unknown): readonly string[] {\n const names = new Set<string>();\n for (const candidate of safeArrayItems(\n value,\n MAX_RUNTIME_DIAGNOSTIC_TOOLS * 4,\n )) {\n if (typeof candidate !== 'string' || !isPublicIdentifier(candidate)) {\n continue;\n }\n names.add(candidate);\n }\n return [...names].sort().slice(0, MAX_RUNTIME_DIAGNOSTIC_TOOLS);\n}\n\nfunction isPublicIdentifier(value: string): boolean {\n if (\n value.length < 1 ||\n value.length > 80 ||\n !/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(value)\n ) {\n return false;\n }\n const parts = value.split(/[._-]/);\n return !parts.some((part) => PROHIBITED_IDENTIFIER_PARTS.has(part));\n}\n\nfunction projectWorker(\n value: unknown,\n observedAt: string,\n observedAtMilliseconds: number | null,\n): RuntimeDiagnostics['worker'] {\n const source = plainRecord(value);\n const topology = oneOf(read(source, 'topology'), WORKER_TOPOLOGIES, 'inline');\n const required = read(source, 'required') === true;\n const heartbeatValue = read(source, 'heartbeatAt');\n const heartbeatMilliseconds = timestampMilliseconds(heartbeatValue);\n const heartbeatAt = coarseTimestamp(heartbeatValue);\n let liveness: RuntimeDiagnostics['worker']['liveness'] = 'not-required';\n if (required) {\n liveness = 'unknown';\n if (heartbeatMilliseconds !== null && observedAtMilliseconds !== null) {\n const ageSeconds =\n (observedAtMilliseconds - heartbeatMilliseconds) / 1_000;\n if (ageSeconds >= 0) {\n liveness =\n ageSeconds <= RUNTIME_WORKER_FRESHNESS_SECONDS ? 'alive' : 'stale';\n }\n }\n }\n return { topology, liveness, heartbeatAt, observedAt };\n}\n\nfunction projectErrors(value: unknown): RuntimeDiagnostics['recentErrors'] {\n const errors: Array<RuntimeDiagnostics['recentErrors'][number]> = [];\n for (const candidate of safeArrayItems(\n value,\n MAX_RUNTIME_DIAGNOSTIC_ERRORS * 4,\n )) {\n const source = plainRecord(candidate);\n const at = coarseTimestamp(read(source, 'at'));\n if (!at) continue;\n const rawCode = read(source, 'code');\n const code: RuntimeDiagnosticErrorCode = ERROR_CODES.includes(\n rawCode as (typeof ERROR_CODES)[number],\n )\n ? (rawCode as (typeof ERROR_CODES)[number])\n : 'runtime_error';\n errors.push({ code, at });\n }\n return errors\n .sort((left, right) =>\n left.at === right.at\n ? left.code.localeCompare(right.code)\n : right.at.localeCompare(left.at),\n )\n .slice(0, MAX_RUNTIME_DIAGNOSTIC_ERRORS);\n}\n\nfunction capabilityStatus(\n capabilities: RuntimeDiagnostics['capabilities'],\n id: CapabilityId,\n): CapabilityStatus {\n return (\n capabilities.find((capability) => capability.id === id)?.status ?? 'unknown'\n );\n}\n\nfunction coarseTimestamp(value: unknown): string | null {\n const milliseconds = timestampMilliseconds(value);\n if (milliseconds === null) return null;\n const minute = Math.floor(milliseconds / 60_000) * 60_000;\n return new Date(minute).toISOString();\n}\n\nfunction timestampMilliseconds(value: unknown): number | null {\n try {\n if (!(typeof value === 'string' || value instanceof Date)) return null;\n const milliseconds =\n value instanceof Date ? value.getTime() : Date.parse(value);\n return Number.isFinite(milliseconds) ? milliseconds : null;\n } catch {\n return null;\n }\n}\n\nfunction oneOf<\n const Values extends readonly string[],\n Fallback extends Values[number],\n>(value: unknown, values: Values, fallback: Fallback): Values[number] {\n return typeof value === 'string' && values.includes(value as Values[number])\n ? (value as Values[number])\n : fallback;\n}\n\nfunction plainRecord(value: unknown): Record<string, unknown> | null {\n try {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return null;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null\n ? (value as Record<string, unknown>)\n : null;\n } catch {\n return null;\n }\n}\n\nfunction read(source: Record<string, unknown> | null, key: string): unknown {\n try {\n if (!source || !Object.hasOwn(source, key)) {\n return undefined;\n }\n return source[key];\n } catch {\n return undefined;\n }\n}\n\nfunction safeArrayItems(value: unknown, maximum: number): readonly unknown[] {\n try {\n if (!Array.isArray(value)) return [];\n const length = Math.min(value.length, maximum);\n if (!Number.isSafeInteger(length) || length < 0) return [];\n const items: unknown[] = [];\n for (let index = 0; index < length; index += 1) {\n try {\n items.push(value[index]);\n } catch {\n items.push(undefined);\n }\n }\n return items;\n } catch {\n return [];\n }\n}\n\nfunction deepFreeze<T>(value: T): T {\n if (value && typeof value === 'object') {\n Object.freeze(value);\n for (const child of Object.values(value as Record<string, unknown>)) {\n if (child && typeof child === 'object' && !Object.isFrozen(child)) {\n deepFreeze(child);\n }\n }\n }\n return value;\n}\n","/**\n * Safe, private, single-owner application runtime for the `local` profile.\n *\n * This Node-only subpath owns the small amount of operational composition that\n * does not belong in a generated application: user-owned paths, restrictive\n * local secret material, SQLite tuning, owner bootstrap, and an optional\n * embedded job runner. Domain schema preparation remains an explicit startup\n * step supplied by the application migration layer.\n */\n\nimport { execFile } from 'node:child_process';\nimport { createHash, createHmac, randomBytes } from 'node:crypto';\nimport {\n constants,\n type FileHandle,\n link,\n lstat,\n mkdir,\n open,\n readdir,\n realpath,\n rmdir,\n unlink,\n} from 'node:fs/promises';\nimport { homedir, platform } from 'node:os';\nimport { isAbsolute, parse, relative, resolve, sep } from 'node:path';\nimport { promisify } from 'node:util';\nimport { Worker } from 'node:worker_threads';\nimport {\n type ResolvedApplicationRuntime,\n type RuntimeProviderOverrides,\n resolveApplicationRuntime,\n} from '@happyvertical/smrt-config';\nimport { TaskRunner, type TaskRunnerConfig } from '@happyvertical/smrt-jobs';\nimport { Person, ProfileTypeCollection } from '@happyvertical/smrt-profiles';\nimport { withSystemContext } from '@happyvertical/smrt-tenancy';\nimport {\n DEFAULT_ROLE_SLUGS,\n MembershipCollection,\n MembershipStatus,\n RoleCollection,\n SessionCollection,\n SessionService,\n TenantService,\n UserCollection,\n UserStatus,\n} from '@happyvertical/smrt-users';\nimport { type DatabaseInterface, getDatabase } from '@happyvertical/sql';\n\nexport * from './deployed-runtime.js';\nexport * from './runtime-diagnostics.js';\n\nconst DEFAULT_BIND_HOST = '127.0.0.1';\nconst DEFAULT_BOOTSTRAP_TTL_SECONDS = 10 * 60;\nconst MAX_BOOTSTRAP_TTL_SECONDS = 15 * 60;\nconst DEFAULT_SESSION_TTL_SECONDS = 7 * 24 * 60 * 60;\nconst BOOTSTRAP_TABLE = '_smrt_local_owner_bootstrap';\nconst SECRET_FILE_NAME = 'application.secret';\nconst DATABASE_FILE_NAME = 'application.sqlite';\nconst ROOT_MARKER_PREFIX = '.smrt-local-runtime-';\nconst PREFLIGHT_RETRY_LIMIT = 4;\nconst INITIALIZATION_LOCK_TIMEOUT_MS = 120_000;\nconst INITIALIZATION_LOCK_WORKER = `\n const { parentPort, workerData } = require('node:worker_threads');\n let database;\n let transaction;\n (async () => {\n try {\n const { getDatabase } = await import(workerData.sqlModuleUrl);\n database = await getDatabase({\n type: 'sqlite',\n url: workerData.path,\n secureFile: {\n driver: 'node:sqlite',\n custody: 'trusted-parent',\n root: workerData.custodyRoot,\n },\n transactionQueueTimeout: workerData.timeout,\n });\n if (!database.beginTransaction) {\n throw new Error('Secure SQLite does not expose beginTransaction().');\n }\n await database.query('PRAGMA busy_timeout = ' + workerData.timeout);\n transaction = await database.beginTransaction();\n parentPort.postMessage({ type: 'acquired' });\n } catch (error) {\n try { await database?.close?.(); } catch {}\n parentPort.postMessage({ type: 'error', message: String(error) });\n parentPort.close();\n return;\n }\n parentPort.once('message', async (message) => {\n if (message?.type !== 'release') return;\n let releaseError;\n try { await transaction.rollback(); } catch (error) { releaseError = String(error); }\n try { await database.close?.(); } catch (error) { releaseError ??= String(error); }\n parentPort.postMessage({ type: 'released', error: releaseError });\n parentPort.close();\n });\n })().catch((error) => {\n parentPort.postMessage({ type: 'error', message: String(error) });\n parentPort.close();\n });\n`;\nconst execFileAsync = promisify(execFile);\n\n/** Paths owned by the local user, outside the source tree by default. */\nexport interface LocalRuntimePaths {\n readonly root: string;\n readonly database: string;\n readonly assets: string;\n readonly secrets: string;\n readonly applicationSecret: string;\n}\n\nexport interface ResolveLocalRuntimePathsOptions {\n /** Stable application identifier, e.g. `lolaus`. */\n appId: string;\n /** Explicit user-owned data directory. Defaults to the OS application-data directory. */\n dataDirectory?: string;\n /** Source checkout to protect from accidental data placement. Defaults to cwd. */\n sourceRoot?: string;\n /** Testable default-root and filesystem case-sensitivity override. */\n platform?: NodeJS.Platform;\n /** Testable home-directory override. */\n homeDirectory?: string;\n /** Testable environment override. */\n env?: NodeJS.ProcessEnv;\n}\n\nexport interface LocalApplicationRuntimeOptions\n extends ResolveLocalRuntimePathsOptions {\n /** Actual HTTP bind host. Owner bootstrap refuses non-loopback values. */\n bindHost?: string;\n /**\n * Explicit application migration/schema hook, invoked before identity access.\n * It must be idempotent; runtime code never synthesizes application tables.\n */\n prepareDatabase?: (db: DatabaseInterface) => Promise<void>;\n /** Local profile provider overrides (only validated local combinations survive). */\n providers?: RuntimeProviderOverrides;\n /** Short-lived bootstrap token lifetime. Range: 1..900 seconds. */\n bootstrapTtlSeconds?: number;\n /** Normal authenticated session lifetime in whole seconds. Minimum 1. */\n sessionTtlSeconds?: number;\n /** Explicit opt-in for persisted background work. Default false. */\n backgroundJobs?: boolean;\n /** Explicit opt-in for application-defined paid capabilities. Default false. */\n paidCapabilities?: boolean;\n /** Testable clock. */\n now?: () => Date;\n}\n\n/**\n * Claim the secure local database root before a standalone migration command\n * opens SQLite. This does not create application schema or bootstrap records.\n */\nexport async function prepareLocalDatabaseStorage(\n options: ResolveLocalRuntimePathsOptions,\n): Promise<LocalRuntimePaths> {\n const paths = resolveLocalRuntimePaths(options);\n const sourceRoot = resolve(options.sourceRoot ?? process.cwd());\n const appId = validateApplicationId(options.appId);\n await preflightLocalApplicationRoot(paths.root, sourceRoot, appId);\n const initializationLock = await acquireInitializationLock(paths.root);\n let db: DatabaseInterface | undefined;\n let failure: unknown;\n try {\n await preflightLocalApplicationRoot(paths.root, sourceRoot, appId);\n const acquired = await acquireLocalDatabase(paths, sourceRoot, appId);\n db = acquired.db;\n await db.close?.();\n db = undefined;\n } catch (error) {\n failure = db ? await closeDatabaseAfterFailure(db, error) : error;\n db = undefined;\n }\n try {\n await initializationLock.release();\n } catch (releaseError) {\n failure = failure\n ? preservePrimaryFailure(\n failure,\n releaseError,\n 'initializationLockReleaseError',\n 'Local database storage preparation and initialization-lock release both failed.',\n )\n : releaseError;\n }\n if (failure) throw failure;\n return paths;\n}\n\n/**\n * Verify an already-initialized local database root without creating or\n * changing any filesystem/database artifact. Operator read/copy/import paths\n * use this boundary before opening SQLite outside the runtime bootstrap.\n */\nexport async function validateLocalDatabaseStorage(\n options: ResolveLocalRuntimePathsOptions,\n): Promise<LocalRuntimePaths> {\n const paths = resolveLocalRuntimePaths(options);\n const sourceRoot = resolve(options.sourceRoot ?? process.cwd());\n const appId = validateApplicationId(options.appId);\n await preflightLocalApplicationRoot(paths.root, sourceRoot, appId);\n const canonicalSourceRoot = await realpath(sourceRoot);\n await validateRootMarker(\n resolve(paths.root, `${ROOT_MARKER_PREFIX}${appId}`),\n canonicalSourceRoot,\n );\n await validateExistingPathChain(paths.database, canonicalSourceRoot, 'file');\n const database = await lstat(paths.database);\n const currentUid = process.getuid?.();\n if (\n database.isSymbolicLink() ||\n !database.isFile() ||\n (currentUid !== undefined && database.uid !== currentUid) ||\n (database.mode & 0o777) !== 0o600\n ) {\n throw unsafeFilesystemEntry(\n `Local application database must be a current-user-owned mode-0600 file: ${paths.database}`,\n );\n }\n return paths;\n}\n\nexport interface LocalOwnerBootstrapInvitation {\n /** Plaintext is returned exactly when a new claim is issued; it is never persisted. */\n readonly token: string;\n readonly expiresAt: string;\n}\n\nexport interface LocalRuntimeInitialization {\n readonly runtime: LocalApplicationRuntime;\n readonly bootstrap: LocalOwnerBootstrapInvitation | null;\n readonly diagnostics: LocalRuntimeDiagnostics;\n}\n\nexport interface ClaimLocalOwnerInput {\n token: string;\n name: string;\n email: string;\n tenantName?: string;\n userAgent?: string;\n ipAddress?: string;\n}\n\nexport interface LocalOwnerClaimResult {\n readonly profileId: string;\n readonly userId: string;\n readonly tenantId: string;\n readonly membershipId: string;\n readonly sessionId: string;\n}\n\nexport type LocalBootstrapStatus =\n | 'available'\n | 'expired'\n | 'claimed'\n | 'unavailable';\n\n/** Secret-free, machine-readable local runtime state. */\nexport interface LocalRuntimeDiagnostics {\n readonly schemaVersion: 1;\n readonly runtime: ResolvedApplicationRuntime;\n readonly bind: {\n readonly host: string;\n readonly loopback: true;\n };\n readonly paths: LocalRuntimePaths;\n readonly storage: {\n readonly database: 'sqlite-file';\n readonly assets: 'user-owned-directory';\n readonly secrets: 'mode-0600-local-file';\n };\n readonly bootstrap: {\n readonly status: LocalBootstrapStatus;\n readonly expiresAt: string | null;\n readonly tokenValuesIncluded: false;\n readonly tokenHashesIncluded: false;\n };\n readonly tenancy: {\n readonly mode: 'real-default-tenant';\n readonly ui: 'hidden';\n };\n readonly jobs: {\n readonly topology: 'inline' | 'embedded';\n readonly backgroundEnabled: boolean;\n };\n readonly paidCapabilitiesEnabled: boolean;\n readonly secretValuesIncluded: false;\n}\n\nexport type LocalRuntimeErrorCode =\n | 'bootstrap_claimed'\n | 'bootstrap_expired'\n | 'bootstrap_invalid'\n | 'bootstrap_unavailable'\n | 'capability_disabled'\n | 'invalid_configuration'\n | 'migration_failed'\n | 'unsafe_public_exposure';\n\n/**\n * Fixed, secret-free surface for a failed application migration.\n *\n * A migration driver message is a likely carrier of a connection string,\n * credential, filesystem path, or environment value, so the caller's text is\n * never surfaced. The original error is retained as a non-enumerable `cause`\n * for private logs only.\n */\nexport const MIGRATION_FAILED_MESSAGE =\n 'The application migration step failed; run pnpm app:setup and inspect the private migration logs.';\n\n/** Stable, secret-free local-runtime failure. */\nexport class LocalRuntimeError extends Error {\n constructor(\n readonly code: LocalRuntimeErrorCode,\n message: string,\n ) {\n super(message);\n this.name = 'LocalRuntimeError';\n }\n}\n\ninterface BootstrapRow {\n expires_at?: unknown;\n consumed_at?: unknown;\n}\n\ninterface ExistingOwner {\n userId: string;\n tenantId: string;\n}\n\n/**\n * Resolve deterministic user-owned paths and reject source-tree placement.\n */\nexport function resolveLocalRuntimePaths(\n options: ResolveLocalRuntimePathsOptions,\n): LocalRuntimePaths {\n const appId = validateApplicationId(options.appId);\n const runtimePlatform = options.platform ?? platform();\n const runtimeHome = options.homeDirectory ?? homedir();\n const env = options.env ?? process.env;\n const defaultRoot = defaultApplicationDataRoot(\n runtimePlatform,\n runtimeHome,\n env,\n );\n const root = resolve(options.dataDirectory ?? resolve(defaultRoot, appId));\n const sourceRoot = resolve(options.sourceRoot ?? process.cwd());\n\n if (\n sameFilesystemPath(root, runtimeHome, runtimePlatform) ||\n sameFilesystemPath(root, parse(root).root, runtimePlatform) ||\n isInside(sourceRoot, root, runtimePlatform) ||\n isInside(root, sourceRoot, runtimePlatform)\n ) {\n throw new LocalRuntimeError(\n 'invalid_configuration',\n 'Local application data must be a dedicated directory that does not overlap the source tree.',\n );\n }\n\n return Object.freeze({\n root,\n database: resolve(root, DATABASE_FILE_NAME),\n assets: resolve(root, 'assets'),\n secrets: resolve(root, 'secrets'),\n applicationSecret: resolve(root, 'secrets', SECRET_FILE_NAME),\n });\n}\n\n/**\n * Initialize or reopen a local application runtime.\n *\n * A plaintext bootstrap token is returned only when this call creates a new\n * invitation. Existing unexpired invitations remain valid but cannot be read\n * back because only their HMAC is stored.\n */\nexport async function initializeLocalApplicationRuntime(\n options: LocalApplicationRuntimeOptions,\n): Promise<LocalRuntimeInitialization> {\n const bindHost = normalizeLoopbackHost(options.bindHost ?? DEFAULT_BIND_HOST);\n const bootstrapTtlSeconds = validateBootstrapTtl(\n options.bootstrapTtlSeconds ?? DEFAULT_BOOTSTRAP_TTL_SECONDS,\n );\n const sessionTtlSeconds = validateSessionTtl(\n options.sessionTtlSeconds ?? DEFAULT_SESSION_TTL_SECONDS,\n );\n const resolvedRuntime = resolveApplicationRuntime({\n profile: 'local',\n providers: options.providers,\n });\n const paths = resolveLocalRuntimePaths(options);\n const sourceRoot = resolve(options.sourceRoot ?? process.cwd());\n const appId = validateApplicationId(options.appId);\n await preflightLocalApplicationRoot(paths.root, sourceRoot, appId);\n const initializationLock = await acquireInitializationLock(paths.root);\n let db: DatabaseInterface | undefined;\n let initialization: LocalRuntimeInitialization | undefined;\n let initializationFailure: unknown;\n let initializationFailed = false;\n try {\n await preflightLocalApplicationRoot(paths.root, sourceRoot, appId);\n const acquired = await acquireLocalDatabase(paths, sourceRoot, appId);\n db = acquired.db;\n const { canonicalSourceRoot } = acquired;\n await prepareLocalFilesystem(paths, canonicalSourceRoot);\n await tuneLocalSqlite(db);\n try {\n await options.prepareDatabase?.(db);\n } catch (migrationFailure) {\n throw migrationFailed(migrationFailure);\n }\n await ensureBootstrapTable(db);\n\n const runtime = new InitializedLocalApplicationRuntime({\n db,\n paths,\n bindHost,\n resolvedRuntime,\n bootstrapTtlSeconds,\n sessionTtlSeconds,\n backgroundJobs: options.backgroundJobs === true,\n paidCapabilities: options.paidCapabilities === true,\n now: options.now ?? (() => new Date()),\n canonicalSourceRoot,\n });\n const bootstrap = await runtime.ensureBootstrapInvitation();\n initialization = {\n runtime,\n bootstrap,\n diagnostics: await runtime.diagnostics(),\n };\n } catch (error) {\n initializationFailed = true;\n initializationFailure = db\n ? await closeDatabaseAfterFailure(db, error)\n : error;\n db = undefined;\n }\n\n try {\n await initializationLock.release();\n } catch (releaseError) {\n if (initializationFailed) {\n initializationFailure = preservePrimaryFailure(\n initializationFailure,\n releaseError,\n 'initializationLockReleaseError',\n 'Local runtime initialization and initialization-lock release both failed.',\n );\n } else if (db) {\n initializationFailed = true;\n initializationFailure = await closeDatabaseAfterFailure(db, releaseError);\n db = undefined;\n } else {\n initializationFailed = true;\n initializationFailure = releaseError;\n }\n }\n\n if (initializationFailed) throw initializationFailure;\n if (!initialization) {\n throw new Error('Local runtime initialization completed without a result.');\n }\n return initialization;\n}\n\ninterface LocalApplicationRuntimeState {\n db: DatabaseInterface;\n paths: LocalRuntimePaths;\n bindHost: string;\n resolvedRuntime: ResolvedApplicationRuntime;\n bootstrapTtlSeconds: number;\n sessionTtlSeconds: number;\n backgroundJobs: boolean;\n paidCapabilities: boolean;\n now: () => Date;\n canonicalSourceRoot: string;\n}\n\n/** Initialized local runtime used by server startup and onboarding handlers. */\nexport interface LocalApplicationRuntime {\n readonly db: DatabaseInterface;\n readonly paths: LocalRuntimePaths;\n readonly bindHost: string;\n readonly resolvedRuntime: ResolvedApplicationRuntime;\n readonly backgroundJobsEnabled: boolean;\n readonly paidCapabilitiesEnabled: boolean;\n ensureBootstrapInvitation(): Promise<LocalOwnerBootstrapInvitation | null>;\n rotateBootstrapInvitation(): Promise<LocalOwnerBootstrapInvitation>;\n claimOwner(input: ClaimLocalOwnerInput): Promise<LocalOwnerClaimResult>;\n restoreSession(\n sessionId: string,\n ): ReturnType<SessionService['loadSessionContext']>;\n createEmbeddedJobRunner(config?: TaskRunnerConfig): Promise<TaskRunner>;\n diagnostics(): Promise<LocalRuntimeDiagnostics>;\n}\n\nclass InitializedLocalApplicationRuntime implements LocalApplicationRuntime {\n readonly db: DatabaseInterface;\n readonly paths: LocalRuntimePaths;\n readonly bindHost: string;\n readonly resolvedRuntime: ResolvedApplicationRuntime;\n readonly backgroundJobsEnabled: boolean;\n readonly paidCapabilitiesEnabled: boolean;\n private readonly bootstrapTtlSeconds: number;\n private readonly sessionTtlSeconds: number;\n private readonly now: () => Date;\n private readonly canonicalSourceRoot: string;\n\n constructor(state: LocalApplicationRuntimeState) {\n this.db = state.db;\n this.paths = state.paths;\n this.bindHost = state.bindHost;\n this.resolvedRuntime = state.resolvedRuntime;\n this.bootstrapTtlSeconds = state.bootstrapTtlSeconds;\n this.sessionTtlSeconds = state.sessionTtlSeconds;\n this.backgroundJobsEnabled = state.backgroundJobs;\n this.paidCapabilitiesEnabled = state.paidCapabilities;\n this.now = state.now;\n this.canonicalSourceRoot = state.canonicalSourceRoot;\n }\n\n /**\n * Issue the first short-lived owner invitation when none is active.\n * Repeated startup never rotates an unexpired token or duplicates an owner.\n */\n async ensureBootstrapInvitation(): Promise<LocalOwnerBootstrapInvitation | null> {\n if (await findExistingOwner(this.db)) return null;\n const current = await readBootstrapRow(this.db);\n if (current?.consumed_at != null) return null;\n const now = this.now();\n const currentExpiry = parseStoredDate(current?.expires_at);\n if (\n current &&\n current.consumed_at == null &&\n currentExpiry !== null &&\n currentExpiry.getTime() > now.getTime()\n ) {\n return null;\n }\n return this.issueBootstrapInvitation(false);\n }\n\n /** Explicit recovery when an installer lost the one-time plaintext token. */\n async rotateBootstrapInvitation(): Promise<LocalOwnerBootstrapInvitation> {\n if (await findExistingOwner(this.db)) {\n throw new LocalRuntimeError(\n 'bootstrap_claimed',\n 'The local owner has already been claimed.',\n );\n }\n if ((await readBootstrapRow(this.db))?.consumed_at != null) {\n throw new LocalRuntimeError(\n 'bootstrap_claimed',\n 'The local owner bootstrap invitation has already been consumed.',\n );\n }\n const invitation = await this.issueBootstrapInvitation(true);\n if (!invitation) {\n if ((await readBootstrapRow(this.db))?.consumed_at != null) {\n throw new LocalRuntimeError(\n 'bootstrap_claimed',\n 'The local owner bootstrap invitation has already been consumed.',\n );\n }\n throw new LocalRuntimeError(\n 'bootstrap_unavailable',\n 'A local owner bootstrap invitation could not be issued.',\n );\n }\n return invitation;\n }\n\n /**\n * Consume a bootstrap token and atomically create normal identity/RBAC/session\n * records. The token transition and every record write share one transaction.\n */\n async claimOwner(\n input: ClaimLocalOwnerInput,\n ): Promise<LocalOwnerClaimResult> {\n validateOwnerInput(input);\n if (await findExistingOwner(this.db)) {\n throw new LocalRuntimeError(\n 'bootstrap_claimed',\n 'The local owner has already been claimed.',\n );\n }\n if (typeof this.db.transaction !== 'function') {\n throw new LocalRuntimeError(\n 'bootstrap_unavailable',\n 'Owner bootstrap requires a database adapter with transaction support.',\n );\n }\n\n const tokenHash = await this.hashBootstrapToken(input.token);\n const now = this.now();\n const nowIso = now.toISOString();\n // A token that cannot claim is rejected before seeding, so a wrong,\n // replayed, or expired token stays read-only and never pays for a\n // catalog-wide write (#3323). This is a preflight only: the conditional\n // UPDATE in the claim transaction below remains the single authority.\n if (!(await isBootstrapTokenClaimable(this.db, tokenHash, nowIso))) {\n await throwBootstrapClaimFailure(this.db, now);\n }\n // Generated write routes require `<collection>.<action>` grants (#2977),\n // so the owner role must hold the default role matrix over the manifest\n // permission catalog, not only the role itself. Seeding is idempotent and\n // additive, and commits in its own transaction before the claim\n // transaction.\n const roles = await RoleCollection.create({ db: this.db });\n await roles.seedSystemRoles({ seedPermissions: true });\n return this.db.transaction(async (tx) => {\n const claimed = await tx.query(\n `UPDATE ${BOOTSTRAP_TABLE}\n SET consumed_at = ?\n WHERE slot = 1\n AND token_hash = ?\n AND consumed_at IS NULL\n AND expires_at > ?\n RETURNING expires_at`,\n nowIso,\n tokenHash,\n nowIso,\n );\n if (claimed.rows.length === 0) {\n await throwBootstrapClaimFailure(tx, now);\n }\n\n const concurrentOwner = await findExistingOwner(tx);\n if (concurrentOwner) {\n throw new LocalRuntimeError(\n 'bootstrap_claimed',\n 'The local owner has already been claimed.',\n );\n }\n\n return createLocalOwnerRecords(tx, input, this.sessionTtlSeconds);\n });\n }\n\n /** Restore the normal server-side session created by owner bootstrap. */\n async restoreSession(sessionId: string) {\n const service = new SessionService({ db: this.db });\n await service.initialize();\n return service.loadSessionContext(sessionId);\n }\n\n /**\n * Create an in-process persisted-job runner. Background work is default-off\n * and must be explicitly enabled by runtime configuration.\n */\n async createEmbeddedJobRunner(\n config: TaskRunnerConfig = {},\n ): Promise<TaskRunner> {\n if (!this.backgroundJobsEnabled) {\n throw new LocalRuntimeError(\n 'capability_disabled',\n 'Background jobs are disabled; enable them explicitly for this local application.',\n );\n }\n if (this.resolvedRuntime.providers.jobs.topology !== 'embedded') {\n throw new LocalRuntimeError(\n 'invalid_configuration',\n 'An embedded runner requires the local embedded job topology.',\n );\n }\n const runner = new TaskRunner({\n concurrency: 1,\n retention: false,\n ...config,\n });\n await runner.initialize(this.db);\n return runner;\n }\n\n /** Return a deterministic snapshot that never reads secret file contents. */\n async diagnostics(): Promise<LocalRuntimeDiagnostics> {\n const owner = await findExistingOwner(this.db);\n const bootstrap = await readBootstrapRow(this.db);\n const now = this.now();\n const expiresAt = parseStoredDate(bootstrap?.expires_at);\n let status: LocalBootstrapStatus = 'unavailable';\n if (owner || bootstrap?.consumed_at != null) status = 'claimed';\n else if (expiresAt && expiresAt.getTime() > now.getTime())\n status = 'available';\n else if (expiresAt) status = 'expired';\n\n return Object.freeze({\n schemaVersion: 1,\n runtime: this.resolvedRuntime,\n bind: Object.freeze({ host: this.bindHost, loopback: true as const }),\n paths: this.paths,\n storage: Object.freeze({\n database: 'sqlite-file' as const,\n assets: 'user-owned-directory' as const,\n secrets: 'mode-0600-local-file' as const,\n }),\n bootstrap: Object.freeze({\n status,\n expiresAt: expiresAt?.toISOString() ?? null,\n tokenValuesIncluded: false as const,\n tokenHashesIncluded: false as const,\n }),\n tenancy: Object.freeze({\n mode: 'real-default-tenant' as const,\n ui: 'hidden' as const,\n }),\n jobs: Object.freeze({\n topology: this.resolvedRuntime.providers.jobs.topology as\n | 'inline'\n | 'embedded',\n backgroundEnabled: this.backgroundJobsEnabled,\n }),\n paidCapabilitiesEnabled: this.paidCapabilitiesEnabled,\n secretValuesIncluded: false as const,\n });\n }\n\n private async issueBootstrapInvitation(\n replaceActive: boolean,\n ): Promise<LocalOwnerBootstrapInvitation | null> {\n const token = randomBytes(32).toString('base64url');\n const tokenHash = await this.hashBootstrapToken(token);\n const now = this.now();\n const expiresAt = new Date(now.getTime() + this.bootstrapTtlSeconds * 1000);\n const stored = await this.db.query(\n `INSERT INTO ${BOOTSTRAP_TABLE}\n (slot, token_hash, expires_at, consumed_at, created_at)\n VALUES (1, ?, ?, NULL, ?)\n ON CONFLICT(slot) DO UPDATE SET\n token_hash = excluded.token_hash,\n expires_at = excluded.expires_at,\n consumed_at = NULL,\n created_at = excluded.created_at\n WHERE ${BOOTSTRAP_TABLE}.consumed_at IS NULL\n AND (? = 1 OR ${BOOTSTRAP_TABLE}.expires_at <= ?)\n RETURNING token_hash`,\n tokenHash,\n expiresAt.toISOString(),\n now.toISOString(),\n replaceActive ? 1 : 0,\n now.toISOString(),\n );\n const persistedHash = (\n stored.rows[0] as { token_hash?: unknown } | undefined\n )?.token_hash;\n if (persistedHash !== tokenHash) return null;\n return Object.freeze({ token, expiresAt: expiresAt.toISOString() });\n }\n\n private async hashBootstrapToken(token: string): Promise<string> {\n const secret = await validateApplicationSecret(\n this.paths.applicationSecret,\n this.canonicalSourceRoot,\n );\n return createHmac('sha256', secret.trim()).update(token).digest('hex');\n }\n}\n\nasync function createLocalOwnerRecords(\n db: DatabaseInterface,\n input: ClaimLocalOwnerInput,\n sessionTtlSeconds: number,\n): Promise<LocalOwnerClaimResult> {\n const profileTypes = await ProfileTypeCollection.create({ db });\n const personType = await withSystemContext(() =>\n profileTypes.getOrCreateGlobalBySlug('person', {\n name: 'Person',\n description: 'An individual person',\n }),\n );\n const person = new Person({\n db,\n typeId: requireId(personType.id, 'Person profile type'),\n tenantId: null,\n name: input.name.trim(),\n email: input.email.trim(),\n });\n await person.initialize();\n await person.save();\n\n const users = await UserCollection.create({ db });\n const user = await users.create({\n profileId: requireId(person.id, 'Person'),\n email: input.email.trim(),\n status: UserStatus.ACTIVE,\n lastLoginAt: new Date(),\n });\n await user.save();\n\n const tenantService = new TenantService(\n { db },\n {\n mode: 'required',\n maxTenants: 1,\n defaultName: input.tenantName?.trim() || 'My Workspace',\n },\n );\n await tenantService.initialize();\n const { tenant, membership } = await tenantService.createTenantWithOwnership(\n requireId(user.id, 'User'),\n input.tenantName?.trim() || 'My Workspace',\n { slug: 'default' },\n );\n\n const sessions = await SessionCollection.create({ db });\n const session = await sessions.createSession({\n userId: requireId(user.id, 'User'),\n tenantId: requireId(tenant.id, 'Tenant'),\n ttl: sessionTtlSeconds,\n userAgent: input.userAgent,\n ipAddress: input.ipAddress,\n data: { localOwner: true },\n });\n\n return Object.freeze({\n profileId: requireId(person.id, 'Person'),\n userId: requireId(user.id, 'User'),\n tenantId: requireId(tenant.id, 'Tenant'),\n membershipId: requireId(membership.id, 'Membership'),\n sessionId: requireId(session.id, 'Session'),\n });\n}\n\nasync function findExistingOwner(\n db: DatabaseInterface,\n): Promise<ExistingOwner | null> {\n const roles = await RoleCollection.create({ db });\n const ownerRole = await roles.findSystemRoleBySlug(DEFAULT_ROLE_SLUGS.OWNER);\n if (!ownerRole?.id) return null;\n const memberships = await MembershipCollection.create({ db });\n const ownerMemberships = await memberships.findByRole(ownerRole.id);\n const active = ownerMemberships.find(\n (membership) =>\n membership.status === MembershipStatus.ACTIVE &&\n typeof membership.userId === 'string' &&\n typeof membership.tenantId === 'string',\n );\n return active\n ? { userId: active.userId as string, tenantId: active.tenantId as string }\n : null;\n}\n\nasync function throwBootstrapClaimFailure(\n db: DatabaseInterface,\n now: Date,\n): Promise<never> {\n const row = await readBootstrapRow(db);\n if (!row) {\n throw new LocalRuntimeError(\n 'bootstrap_unavailable',\n 'No local owner bootstrap invitation is available.',\n );\n }\n if (row.consumed_at != null) {\n throw new LocalRuntimeError(\n 'bootstrap_claimed',\n 'The local owner bootstrap invitation has already been consumed.',\n );\n }\n const expiresAt = parseStoredDate(row.expires_at);\n if (!expiresAt || expiresAt.getTime() <= now.getTime()) {\n throw new LocalRuntimeError(\n 'bootstrap_expired',\n 'The local owner bootstrap invitation has expired.',\n );\n }\n throw new LocalRuntimeError(\n 'bootstrap_invalid',\n 'The local owner bootstrap token is invalid.',\n );\n}\n\nasync function isBootstrapTokenClaimable(\n db: DatabaseInterface,\n tokenHash: string,\n nowIso: string,\n): Promise<boolean> {\n const result = await db.query(\n `SELECT 1 AS claimable\n FROM ${BOOTSTRAP_TABLE}\n WHERE slot = 1\n AND token_hash = ?\n AND consumed_at IS NULL\n AND expires_at > ?\n LIMIT 1`,\n tokenHash,\n nowIso,\n );\n return result.rows.length > 0;\n}\n\nasync function readBootstrapRow(\n db: DatabaseInterface,\n): Promise<BootstrapRow | null> {\n const result = await db.query(\n `SELECT expires_at, consumed_at\n FROM ${BOOTSTRAP_TABLE}\n WHERE slot = 1\n LIMIT 1`,\n );\n return (result.rows[0] as BootstrapRow | undefined) ?? null;\n}\n\nasync function ensureBootstrapTable(db: DatabaseInterface): Promise<void> {\n await db.query(\n `CREATE TABLE IF NOT EXISTS ${BOOTSTRAP_TABLE} (\n slot INTEGER PRIMARY KEY CHECK (slot = 1),\n token_hash TEXT NOT NULL,\n expires_at TEXT NOT NULL,\n consumed_at TEXT NULL,\n created_at TEXT NOT NULL\n )`,\n );\n}\n\nasync function tuneLocalSqlite(db: DatabaseInterface): Promise<void> {\n await db.query('PRAGMA foreign_keys = ON');\n await db.query('PRAGMA journal_mode = WAL');\n await db.query('PRAGMA synchronous = FULL');\n await db.query('PRAGMA busy_timeout = 5000');\n}\n\ninterface PreparedLocalRoot {\n createdDirectories: string[];\n pendingMarker: string | null;\n pendingMarkerCreatedByAttempt: boolean;\n finalMarker: string;\n}\n\ninterface LocalInitializationLock {\n release(): Promise<void>;\n}\n\nasync function preflightLocalApplicationRoot(\n root: string,\n sourceRoot: string,\n appId: string,\n): Promise<void> {\n for (let attempt = 0; attempt < PREFLIGHT_RETRY_LIMIT; attempt += 1) {\n try {\n await preflightLocalApplicationRootOnce(root, sourceRoot, appId);\n return;\n } catch (error) {\n if (!isMissingFile(error) && !hasMissingFileCause(error)) throw error;\n if (attempt === PREFLIGHT_RETRY_LIMIT - 1) {\n throw unsafeFilesystemEntry(\n 'Local application data changed repeatedly during read-only preflight.',\n error,\n );\n }\n await new Promise<void>((resolveRetry) => setImmediate(resolveRetry));\n }\n }\n}\n\nasync function preflightLocalApplicationRootOnce(\n root: string,\n sourceRoot: string,\n appId: string,\n): Promise<void> {\n requireNoFollowSupport();\n const canonicalSourceRoot = await realpath(sourceRoot);\n const currentUid = process.getuid?.();\n if (currentUid === undefined) {\n throw unsafeFilesystemEntry(\n 'Local runtime storage requires a numeric current-user identity.',\n );\n }\n if (\n isInside(canonicalSourceRoot, root) ||\n isInside(root, canonicalSourceRoot)\n ) {\n throw unsafeFilesystemEntry(\n 'Local application data must remain outside the canonical source tree.',\n );\n }\n\n let rootExists = true;\n for (const component of absolutePathComponents(root)) {\n let details: Awaited<ReturnType<typeof lstat>>;\n try {\n details = await lstat(component);\n } catch (error) {\n if (!isMissingFile(error)) throw error;\n rootExists = false;\n break;\n }\n if (details.isSymbolicLink() || !details.isDirectory()) {\n throw unsafeFilesystemEntry(\n `Local runtime path component must be a real directory: ${component}`,\n );\n }\n await assertCanonicalEntry(component, canonicalSourceRoot);\n const sharedStickyRoot = details.uid === 0 && (details.mode & 0o1000) !== 0;\n if (\n (details.uid !== currentUid && details.uid !== 0) ||\n ((details.mode & 0o022) !== 0 && !sharedStickyRoot)\n ) {\n throw unsafeFilesystemEntry(\n `Local runtime path ancestry does not have trusted-parent custody: ${component}`,\n );\n }\n await assertNoPermissiveDarwinAcl(component);\n }\n\n if (!rootExists) return;\n const rootDetails = await lstat(root);\n if (rootDetails.uid !== currentUid || (rootDetails.mode & 0o777) !== 0o700) {\n throw unsafeFilesystemEntry(\n `Existing local application data root must already be owned by the current user with mode 0700: ${root}`,\n );\n }\n await preflightDedicatedRoot(root, canonicalSourceRoot, appId);\n}\n\nasync function preflightDedicatedRoot(\n root: string,\n canonicalSourceRoot: string,\n appId: string,\n): Promise<void> {\n const finalMarker = resolve(root, `${ROOT_MARKER_PREFIX}${appId}`);\n const pendingMarker = resolve(root, `${ROOT_MARKER_PREFIX}${appId}.pending`);\n const entries = await readdir(root);\n const finalMarkerName = finalMarker.slice(root.length + 1);\n const pendingMarkerName = pendingMarker.slice(root.length + 1);\n const hasFinalMarker = entries.includes(finalMarkerName);\n const hasPendingMarker = entries.includes(pendingMarkerName);\n\n if (hasFinalMarker) {\n await validateRootMarker(finalMarker, canonicalSourceRoot);\n if (hasPendingMarker) {\n await validateRootMarker(pendingMarker, canonicalSourceRoot);\n }\n return;\n }\n if (hasPendingMarker) {\n await validateRootMarker(pendingMarker, canonicalSourceRoot);\n const permittedInterruptedEntries = new Set([\n pendingMarkerName,\n DATABASE_FILE_NAME,\n `${DATABASE_FILE_NAME}-shm`,\n `${DATABASE_FILE_NAME}-wal`,\n ]);\n if (entries.some((entry) => !permittedInterruptedEntries.has(entry))) {\n throw unsafeFilesystemEntry(\n 'Interrupted local application root contains unexpected artifacts.',\n );\n }\n return;\n }\n if (entries.length > 0) {\n throw unsafeFilesystemEntry(\n 'Existing local application data root is populated but has no valid ownership marker.',\n );\n }\n}\n\nasync function assertNoPermissiveDarwinAcl(path: string): Promise<void> {\n if (platform() !== 'darwin') return;\n let listing: string;\n try {\n const result = await execFileAsync('/bin/ls', ['-lde', '--', path], {\n encoding: 'utf8',\n env: { ...process.env, LC_ALL: 'C' },\n });\n listing = result.stdout;\n } catch (error) {\n throw unsafeFilesystemEntry(\n `Local runtime could not inspect macOS access controls: ${path}`,\n error,\n );\n }\n for (const line of listing.split('\\n')) {\n if (!/^\\s*\\d+:/.test(line)) continue;\n const entry = line.match(/^\\s*\\d+:\\s+.+\\s+(allow|deny)\\s+\\S.*$/);\n if (entry?.[1] !== 'deny') {\n throw unsafeFilesystemEntry(\n `Local runtime path contains a permissive macOS access control list: ${path}`,\n );\n }\n }\n}\n\nasync function acquireLocalDatabase(\n paths: LocalRuntimePaths,\n sourceRoot: string,\n appId: string,\n): Promise<{\n canonicalSourceRoot: string;\n db: DatabaseInterface;\n}> {\n requireNoFollowSupport();\n const canonicalSourceRoot = await realpath(sourceRoot);\n const createdDirectories = await ensureSafeDirectoryTree(\n paths.root,\n canonicalSourceRoot,\n true,\n );\n const prepared = await prepareDedicatedRoot(\n paths.root,\n canonicalSourceRoot,\n appId,\n createdDirectories,\n );\n let db: DatabaseInterface | undefined;\n try {\n db = await getDatabase({\n type: 'sqlite',\n url: paths.database,\n secureFile: {\n driver: 'node:sqlite',\n custody: 'trusted-parent',\n root: paths.root,\n },\n });\n await enforcePrivateDatabaseMode(paths.database, canonicalSourceRoot);\n } catch (error) {\n if (db) throw await closeDatabaseAfterFailure(db, error);\n if (prepared.pendingMarkerCreatedByAttempt) {\n await removeMarkerIfPresent(prepared.pendingMarker, canonicalSourceRoot);\n await removeCreatedDirectories(createdDirectories);\n }\n throw error;\n }\n if (!db) {\n throw new Error('Local runtime database acquisition returned no database.');\n }\n\n // Once SQLite acquisition succeeds, the database is an authoritative\n // artifact. Keep the pending marker through every promotion failure so a\n // later startup can resume rather than seeing an unmarked populated root.\n try {\n await publishRootMarker(prepared.finalMarker, canonicalSourceRoot);\n await removeMarkerIfPresent(prepared.pendingMarker, canonicalSourceRoot);\n } catch (error) {\n throw await closeDatabaseAfterFailure(db, error);\n }\n return { canonicalSourceRoot, db };\n}\n\nasync function enforcePrivateDatabaseMode(\n path: string,\n canonicalSourceRoot: string,\n): Promise<void> {\n const database = await openSafeFile(\n path,\n constants.O_RDWR,\n 0o600,\n 'Local application database',\n canonicalSourceRoot,\n );\n try {\n await database.chmod(0o600);\n await database.sync();\n } finally {\n await database.close();\n }\n}\n\nasync function closeDatabaseAfterFailure(\n db: DatabaseInterface,\n primaryFailure: unknown,\n): Promise<unknown> {\n try {\n await db.close?.();\n } catch (cleanupFailure) {\n return preservePrimaryFailure(\n primaryFailure,\n cleanupFailure,\n 'databaseCleanupError',\n 'Local runtime initialization and database cleanup both failed.',\n );\n }\n return primaryFailure;\n}\n\nfunction migrationFailed(cause: unknown): LocalRuntimeError {\n const failure = new LocalRuntimeError(\n 'migration_failed',\n MIGRATION_FAILED_MESSAGE,\n );\n Object.defineProperty(failure, 'cause', {\n value: cause,\n configurable: true,\n });\n return failure;\n}\n\nfunction preservePrimaryFailure(\n primaryFailure: unknown,\n secondaryFailure: unknown,\n secondaryProperty: string,\n aggregateMessage: string,\n): unknown {\n if (primaryFailure instanceof Error) {\n try {\n Object.defineProperty(primaryFailure, secondaryProperty, {\n value: secondaryFailure,\n configurable: true,\n });\n } catch {\n // A frozen application error must remain primary even when secondary\n // failure context cannot be attached to it.\n }\n return primaryFailure;\n }\n return new AggregateError(\n [primaryFailure, secondaryFailure],\n aggregateMessage,\n );\n}\n\nasync function prepareLocalFilesystem(\n paths: LocalRuntimePaths,\n canonicalSourceRoot: string,\n): Promise<void> {\n await ensureSafeDirectoryTree(paths.assets, canonicalSourceRoot);\n await ensureSafeDirectoryTree(paths.secrets, canonicalSourceRoot);\n await ensureApplicationSecret(paths.applicationSecret, canonicalSourceRoot);\n}\n\nasync function prepareDedicatedRoot(\n path: string,\n canonicalSourceRoot: string,\n appId: string,\n createdDirectories: string[],\n): Promise<PreparedLocalRoot> {\n const finalMarker = resolve(path, `${ROOT_MARKER_PREFIX}${appId}`);\n const pendingMarker = resolve(path, `${ROOT_MARKER_PREFIX}${appId}.pending`);\n const entries = await readdir(path);\n const hasFinalMarker = entries.includes(finalMarker.slice(path.length + 1));\n const hasPendingMarker = entries.includes(\n pendingMarker.slice(path.length + 1),\n );\n\n if (hasFinalMarker) {\n await validateRootMarker(finalMarker, canonicalSourceRoot);\n if (hasPendingMarker) {\n await validateRootMarker(pendingMarker, canonicalSourceRoot);\n }\n return {\n createdDirectories,\n pendingMarker: hasPendingMarker ? pendingMarker : null,\n pendingMarkerCreatedByAttempt: false,\n finalMarker,\n };\n }\n\n if (hasPendingMarker) {\n await validateRootMarker(pendingMarker, canonicalSourceRoot);\n const permittedInterruptedEntries = new Set([\n pendingMarker.slice(path.length + 1),\n DATABASE_FILE_NAME,\n `${DATABASE_FILE_NAME}-shm`,\n `${DATABASE_FILE_NAME}-wal`,\n ]);\n if (entries.some((entry) => !permittedInterruptedEntries.has(entry))) {\n throw unsafeFilesystemEntry(\n 'Interrupted local application root contains unexpected artifacts.',\n );\n }\n return {\n createdDirectories,\n pendingMarker,\n pendingMarkerCreatedByAttempt: false,\n finalMarker,\n };\n }\n\n if (entries.length > 0) {\n throw unsafeFilesystemEntry(\n 'Existing local application data root is populated but has no valid ownership marker.',\n );\n }\n const pendingMarkerCreatedByAttempt = await publishRootMarker(\n pendingMarker,\n canonicalSourceRoot,\n );\n return {\n createdDirectories,\n pendingMarker,\n pendingMarkerCreatedByAttempt,\n finalMarker,\n };\n}\n\nasync function acquireInitializationLock(\n root: string,\n): Promise<LocalInitializationLock> {\n const currentUid = process.getuid?.();\n if (currentUid === undefined) {\n throw unsafeFilesystemEntry(\n 'Local runtime initialization locks require a numeric current-user identity.',\n );\n }\n const canonicalTemporaryRoot = await realpath('/tmp');\n const lockRoot = resolve(canonicalTemporaryRoot, `.smrt-${currentUid}`);\n try {\n await mkdir(lockRoot, { mode: 0o700 });\n } catch (error) {\n if (!isFileAlreadyExists(error)) throw error;\n }\n const lockRootDetails = await lstat(lockRoot);\n if (\n !lockRootDetails.isDirectory() ||\n lockRootDetails.isSymbolicLink() ||\n lockRootDetails.uid !== currentUid ||\n (lockRootDetails.mode & 0o777) !== 0o700\n ) {\n throw unsafeFilesystemEntry(\n `Local runtime lock directory must be current-user-owned with mode 0700: ${lockRoot}`,\n );\n }\n const lockKey = createHash('sha256')\n .update(normalizeFilesystemIdentity(root))\n .digest('hex')\n .slice(0, 32);\n const custodyRoot = resolve(lockRoot, lockKey);\n try {\n await mkdir(custodyRoot, { mode: 0o700 });\n } catch (error) {\n if (!isFileAlreadyExists(error)) throw error;\n }\n const path = resolve(custodyRoot, 'initialization.sqlite');\n return acquireInitializationDatabaseLease(path, custodyRoot);\n}\n\nasync function acquireInitializationDatabaseLease(\n path: string,\n custodyRoot: string,\n): Promise<LocalInitializationLock> {\n const worker = new Worker(INITIALIZATION_LOCK_WORKER, {\n eval: true,\n workerData: {\n path,\n custodyRoot,\n timeout: INITIALIZATION_LOCK_TIMEOUT_MS,\n sqlModuleUrl: import.meta.resolve('@happyvertical/sql'),\n },\n });\n const acquisitionFailure = (cause: unknown) => {\n const failure = new LocalRuntimeError(\n 'invalid_configuration',\n 'Could not acquire the local runtime initialization lease within two minutes.',\n );\n Object.defineProperty(failure, 'cause', { value: cause });\n return failure;\n };\n let workerError: unknown;\n const exited = new Promise<never>((_resolve, reject) => {\n worker.once('error', (error) => {\n workerError = error;\n });\n worker.once('exit', (code) => {\n reject(\n acquisitionFailure(\n workerError ??\n new Error(`Initialization lock worker exited ${code}.`),\n ),\n );\n });\n });\n const acquired = new Promise<void>((resolvePromise, reject) => {\n const onMessage = (message: { type?: string; message?: string }) => {\n if (message.type === 'acquired') {\n worker.off('message', onMessage);\n resolvePromise();\n } else if (message.type === 'error') {\n worker.off('message', onMessage);\n reject(acquisitionFailure(new Error(message.message)));\n }\n };\n worker.on('message', onMessage);\n });\n await Promise.race([acquired, exited]);\n\n let released = false;\n return {\n release: async () => {\n if (released) return;\n released = true;\n const releaseCompleted = new Promise<void>((resolvePromise, reject) => {\n const onMessage = (message: { type?: string; error?: string }) => {\n if (message.type !== 'released') return;\n worker.off('message', onMessage);\n if (message.error) reject(new Error(message.error));\n else resolvePromise();\n };\n worker.on('message', onMessage);\n worker.postMessage({ type: 'release' });\n });\n try {\n await Promise.race([releaseCompleted, exited]);\n } finally {\n await worker.terminate();\n }\n },\n };\n}\n\nasync function ensureSafeDirectoryTree(\n path: string,\n canonicalSourceRoot: string,\n dedicatedRoot = false,\n): Promise<string[]> {\n const components = absolutePathComponents(path);\n const createdDirectories: string[] = [];\n for (const component of components) {\n let created = false;\n try {\n const details = await lstat(component);\n if (details.isSymbolicLink() || !details.isDirectory()) {\n throw unsafeFilesystemEntry(\n `Local runtime path component must be a real directory: ${component}`,\n );\n }\n } catch (error) {\n if (!isMissingFile(error)) throw error;\n try {\n await mkdir(component, { mode: 0o700 });\n created = true;\n createdDirectories.push(component);\n } catch (mkdirError) {\n // A concurrent initializer may have created the component. It is still\n // opened and validated without following links below.\n if (!isFileAlreadyExists(mkdirError)) throw mkdirError;\n }\n }\n\n const directory = await openSafeDirectory(component, canonicalSourceRoot);\n try {\n await assertCanonicalEntry(component, canonicalSourceRoot);\n if (component === path && dedicatedRoot && !created) {\n await assertExistingDedicatedRoot(\n directory,\n component,\n canonicalSourceRoot,\n );\n }\n if (created || (component === path && !dedicatedRoot)) {\n await directory.chmod(0o700);\n }\n } finally {\n await directory.close();\n }\n }\n await validateExistingPathChain(path, canonicalSourceRoot, 'directory');\n return createdDirectories;\n}\n\nasync function assertExistingDedicatedRoot(\n directory: FileHandle,\n path: string,\n canonicalSourceRoot: string,\n): Promise<void> {\n const canonical = await realpath(path);\n if (\n isInside(canonicalSourceRoot, canonical) ||\n isInside(canonical, canonicalSourceRoot)\n ) {\n throw unsafeFilesystemEntry(\n 'Local application data must be a dedicated directory that does not overlap the canonical source tree.',\n );\n }\n\n const details = await directory.stat();\n const currentUid = process.getuid?.();\n if (\n currentUid === undefined ||\n details.uid !== currentUid ||\n (details.mode & 0o777) !== 0o700\n ) {\n throw unsafeFilesystemEntry(\n `Existing local application data root must already be owned by the current user with mode 0700: ${path}`,\n );\n }\n}\n\nasync function publishRootMarker(\n path: string,\n canonicalSourceRoot: string,\n): Promise<boolean> {\n let marker: FileHandle | undefined;\n let created = false;\n try {\n marker = await openSafeFile(\n path,\n constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL,\n 0o600,\n 'Local application root marker',\n canonicalSourceRoot,\n );\n created = true;\n await marker.sync();\n } catch (error) {\n if (!isFileAlreadyExists(error)) throw error;\n } finally {\n await marker?.close();\n }\n await validateRootMarker(path, canonicalSourceRoot);\n await syncDirectory(resolve(path, '..'), canonicalSourceRoot);\n return created;\n}\n\nasync function validateRootMarker(\n path: string,\n canonicalSourceRoot: string,\n): Promise<void> {\n await validateExistingPathChain(path, canonicalSourceRoot, 'file');\n const marker = await openSafeFile(\n path,\n constants.O_RDONLY,\n 0o600,\n 'Local application root marker',\n canonicalSourceRoot,\n );\n try {\n const details = await marker.stat();\n const currentUid = process.getuid?.();\n if (\n currentUid === undefined ||\n details.uid !== currentUid ||\n (details.mode & 0o777) !== 0o600 ||\n details.size !== 0\n ) {\n throw unsafeFilesystemEntry(\n `Local application root marker must be an empty current-user-owned mode-0600 file: ${path}`,\n );\n }\n } finally {\n await marker.close();\n }\n}\n\nasync function removeMarkerIfPresent(\n path: string | null,\n canonicalSourceRoot: string,\n): Promise<void> {\n if (path === null) return;\n try {\n await validateRootMarker(path, canonicalSourceRoot);\n await unlink(path);\n await syncDirectory(resolve(path, '..'), canonicalSourceRoot);\n } catch (error) {\n if (!isMissingFile(error) && !hasMissingFileCause(error)) throw error;\n }\n}\n\nasync function removeCreatedDirectories(paths: string[]): Promise<void> {\n for (const path of paths.toReversed()) {\n try {\n await rmdir(path);\n } catch (error) {\n if (!isMissingFile(error) && !isDirectoryNotEmpty(error)) throw error;\n }\n }\n}\n\nasync function ensureApplicationSecret(\n path: string,\n canonicalSourceRoot: string,\n): Promise<void> {\n const directoryPath = resolve(path, '..');\n const temporaryPath = resolve(\n directoryPath,\n `.${SECRET_FILE_NAME}.tmp-${randomBytes(16).toString('hex')}`,\n );\n let temporary: FileHandle | undefined;\n let failure: unknown;\n try {\n temporary = await openSafeFile(\n temporaryPath,\n constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL,\n 0o600,\n 'Temporary application secret',\n canonicalSourceRoot,\n );\n await temporary.writeFile(\n `${randomBytes(32).toString('base64url')}\\n`,\n 'utf8',\n );\n await temporary.sync();\n await temporary.close();\n temporary = undefined;\n\n try {\n await link(temporaryPath, path);\n } catch (error) {\n if (!isFileAlreadyExists(error)) throw error;\n }\n\n await validateApplicationSecret(path, canonicalSourceRoot);\n await syncDirectory(directoryPath, canonicalSourceRoot);\n } catch (error) {\n failure = error;\n }\n try {\n await temporary?.close();\n } catch (error) {\n failure ??= error;\n }\n try {\n await unlink(temporaryPath);\n } catch (error) {\n if (!isMissingFile(error)) failure ??= error;\n }\n if (failure !== undefined) throw failure;\n await removeStaleSecretTemps(directoryPath);\n}\n\nasync function validateApplicationSecret(\n path: string,\n canonicalSourceRoot: string,\n): Promise<string> {\n await validateExistingPathChain(path, canonicalSourceRoot, 'file');\n const file = await openSafeFile(\n path,\n constants.O_RDONLY,\n 0o600,\n 'Application secret',\n canonicalSourceRoot,\n );\n try {\n const details = await file.stat();\n const currentUid = process.getuid?.();\n const secret = await file.readFile('utf8');\n await validateExistingPathChain(path, canonicalSourceRoot, 'file');\n if (\n currentUid === undefined ||\n details.uid !== currentUid ||\n (details.mode & 0o777) !== 0o600 ||\n details.size !== 44 ||\n !/^[A-Za-z0-9_-]{43}\\n$/.test(secret)\n ) {\n throw unsafeFilesystemEntry(\n 'Application secret must be a complete current-user-owned mode-0600 value in the expected format.',\n );\n }\n return secret;\n } finally {\n await file.close();\n }\n}\n\nasync function syncDirectory(\n path: string,\n canonicalSourceRoot: string,\n): Promise<void> {\n const directory = await openSafeDirectory(path, canonicalSourceRoot);\n try {\n await directory.sync();\n } finally {\n await directory.close();\n }\n}\n\nasync function removeStaleSecretTemps(directoryPath: string): Promise<void> {\n const prefix = `.${SECRET_FILE_NAME}.tmp-`;\n for (const entry of await readdir(directoryPath)) {\n if (!entry.startsWith(prefix)) continue;\n try {\n await unlink(resolve(directoryPath, entry));\n } catch (error) {\n if (!isMissingFile(error)) throw error;\n }\n }\n}\n\nasync function openSafeDirectory(path: string, canonicalSourceRoot: string) {\n let directory: FileHandle | undefined;\n try {\n directory = await open(\n path,\n constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW,\n );\n await validateOpenHandlePath(\n directory,\n path,\n 'directory',\n canonicalSourceRoot,\n );\n return directory;\n } catch (error) {\n await directory?.close();\n if (error instanceof LocalRuntimeError) throw error;\n throw unsafeFilesystemEntry(\n `Could not safely open local runtime directory: ${path}`,\n error,\n );\n }\n}\n\nasync function openSafeFile(\n path: string,\n flags: number,\n mode: number,\n label: string,\n canonicalSourceRoot: string,\n) {\n let file: FileHandle | undefined;\n try {\n file = await open(path, flags | constants.O_NOFOLLOW, mode);\n await validateOpenHandlePath(file, path, 'file', canonicalSourceRoot);\n return file;\n } catch (error) {\n await file?.close();\n if (error instanceof LocalRuntimeError || isFileAlreadyExists(error)) {\n throw error;\n }\n throw unsafeFilesystemEntry(\n `${label} could not be opened without following symbolic links.`,\n error,\n );\n }\n}\n\nasync function validateOpenHandlePath(\n handle: FileHandle,\n path: string,\n expectedType: 'directory' | 'file',\n canonicalSourceRoot: string,\n): Promise<void> {\n const opened = await handle.stat();\n const current = await lstat(path);\n const expectedDirectory = expectedType === 'directory';\n if (\n current.isSymbolicLink() ||\n (expectedDirectory ? !opened.isDirectory() : !opened.isFile()) ||\n (expectedDirectory ? !current.isDirectory() : !current.isFile()) ||\n opened.dev !== current.dev ||\n opened.ino !== current.ino\n ) {\n throw unsafeFilesystemEntry(\n `Local runtime ${expectedType} changed while it was being opened: ${path}`,\n );\n }\n await validateExistingPathChain(path, canonicalSourceRoot, expectedType);\n const afterValidation = await lstat(path);\n if (\n afterValidation.isSymbolicLink() ||\n opened.dev !== afterValidation.dev ||\n opened.ino !== afterValidation.ino\n ) {\n throw unsafeFilesystemEntry(\n `Local runtime ${expectedType} changed during validation: ${path}`,\n );\n }\n}\n\nasync function validateExistingPathChain(\n path: string,\n canonicalSourceRoot: string,\n leafType: 'directory' | 'file',\n): Promise<void> {\n const components = absolutePathComponents(path);\n for (const [index, component] of components.entries()) {\n const details = await lstat(component);\n const expectedFile = index === components.length - 1 && leafType === 'file';\n if (\n details.isSymbolicLink() ||\n (expectedFile ? !details.isFile() : !details.isDirectory())\n ) {\n throw unsafeFilesystemEntry(\n `Local runtime path contains an unsafe component: ${component}`,\n );\n }\n await assertCanonicalEntry(component, canonicalSourceRoot);\n }\n}\n\nasync function assertCanonicalEntry(\n path: string,\n canonicalSourceRoot: string,\n): Promise<void> {\n const canonical = await realpath(path);\n if (!sameFilesystemPath(canonical, path)) {\n throw unsafeFilesystemEntry(\n `Local runtime path must not be redirected: ${path}`,\n );\n }\n if (isInside(canonicalSourceRoot, canonical)) {\n throw unsafeFilesystemEntry(\n 'Local application data must remain outside the canonical source tree.',\n );\n }\n}\n\nfunction absolutePathComponents(path: string): string[] {\n const absolute = resolve(path);\n const root = parse(absolute).root;\n const parts = absolute.slice(root.length).split(sep).filter(Boolean);\n const components = [root];\n for (const part of parts) {\n components.push(resolve(components.at(-1) as string, part));\n }\n return components;\n}\n\nfunction requireNoFollowSupport(): void {\n if (\n typeof constants.O_NOFOLLOW !== 'number' ||\n constants.O_NOFOLLOW === 0 ||\n typeof constants.O_DIRECTORY !== 'number' ||\n constants.O_DIRECTORY === 0\n ) {\n throw unsafeFilesystemEntry(\n 'This platform cannot safely initialize local storage without no-follow filesystem support.',\n );\n }\n}\n\nfunction sameFilesystemPath(\n left: string,\n right: string,\n runtimePlatform: NodeJS.Platform = platform(),\n): boolean {\n return (\n normalizeFilesystemIdentity(left, runtimePlatform) ===\n normalizeFilesystemIdentity(right, runtimePlatform)\n );\n}\n\nfunction usesCaseInsensitivePathGuards(\n runtimePlatform: NodeJS.Platform,\n): boolean {\n return runtimePlatform === 'win32' || runtimePlatform === 'darwin';\n}\n\nfunction normalizeFilesystemIdentity(\n value: string,\n runtimePlatform: NodeJS.Platform = platform(),\n): string {\n const normalized = resolve(value);\n return usesCaseInsensitivePathGuards(runtimePlatform)\n ? normalized.toLowerCase()\n : normalized;\n}\n\nfunction unsafeFilesystemEntry(message: string, cause?: unknown) {\n const error = new LocalRuntimeError('invalid_configuration', message);\n if (cause !== undefined)\n Object.defineProperty(error, 'cause', { value: cause });\n return error;\n}\n\nfunction validateBootstrapTtl(value: number): number {\n if (\n !Number.isInteger(value) ||\n value < 1 ||\n value > MAX_BOOTSTRAP_TTL_SECONDS\n ) {\n throw new LocalRuntimeError(\n 'invalid_configuration',\n `Owner bootstrap TTL must be an integer from 1 to ${MAX_BOOTSTRAP_TTL_SECONDS} seconds.`,\n );\n }\n return value;\n}\n\nfunction validateSessionTtl(value: number): number {\n if (!Number.isInteger(value) || value < 1) {\n throw new LocalRuntimeError(\n 'invalid_configuration',\n 'Session TTL must be a whole number of seconds greater than or equal to 1.',\n );\n }\n return value;\n}\n\nfunction validateOwnerInput(input: ClaimLocalOwnerInput): void {\n if (!input.token || !input.name.trim() || !input.email.trim()) {\n throw new LocalRuntimeError(\n 'bootstrap_invalid',\n 'Owner bootstrap requires a token, name, and email address.',\n );\n }\n}\n\nfunction normalizeLoopbackHost(value: string): string {\n const host = value\n .trim()\n .toLowerCase()\n .replace(/^\\[|\\]$/g, '');\n if (host === '::1') return host;\n const octets = host.split('.');\n if (\n octets.length === 4 &&\n octets.every((part) => /^\\d{1,3}$/.test(part) && Number(part) <= 255) &&\n Number(octets[0]) === 127\n ) {\n return host;\n }\n throw new LocalRuntimeError(\n 'unsafe_public_exposure',\n 'Owner bootstrap is restricted to a loopback IP literal. Use ::1 or 127.0.0.0/8.',\n );\n}\n\n/** Validate an explicit runtime identity. */\nexport function validateApplicationId(value: string): string {\n const appId = value.trim().toLowerCase();\n if (!/^[a-z0-9][a-z0-9.-]{0,62}$/.test(appId)) {\n throw new LocalRuntimeError(\n 'invalid_configuration',\n 'appId must contain only lowercase letters, digits, dots, or hyphens.',\n );\n }\n return appId;\n}\n\n/** Encode a package/project identity into a collision-resistant runtime ID. */\nexport function encodeApplicationId(value: string): string {\n const source = value.trim().toLowerCase();\n if (/^[a-z0-9][a-z0-9.-]{0,62}$/.test(source)) return source;\n const digest = createHash('sha256')\n .update(value.trim())\n .digest('hex')\n .slice(0, 10);\n const slug =\n source\n .replace(/[^a-z0-9.-]+/g, '-')\n .replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, '')\n .slice(0, 52)\n .replace(/[^a-z0-9]+$/g, '') || 'app';\n return validateApplicationId(`${slug}-${digest}`);\n}\n\nfunction defaultApplicationDataRoot(\n runtimePlatform: NodeJS.Platform,\n runtimeHome: string,\n env: NodeJS.ProcessEnv,\n): string {\n if (runtimePlatform === 'darwin') {\n return resolve(runtimeHome, 'Library', 'Application Support');\n }\n if (runtimePlatform === 'win32') {\n return resolve(env.LOCALAPPDATA ?? env.APPDATA ?? runtimeHome);\n }\n return resolve(env.XDG_DATA_HOME ?? resolve(runtimeHome, '.local', 'share'));\n}\n\nfunction isInside(\n parent: string,\n child: string,\n runtimePlatform: NodeJS.Platform = platform(),\n): boolean {\n const normalizedParent = normalizeFilesystemIdentity(parent, runtimePlatform);\n const normalizedChild = normalizeFilesystemIdentity(child, runtimePlatform);\n const path = relative(normalizedParent, normalizedChild);\n return path === '' || (!path.startsWith('..') && !isAbsolute(path));\n}\n\nfunction parseStoredDate(value: unknown): Date | null {\n if (!(typeof value === 'string' || value instanceof Date)) return null;\n const date = value instanceof Date ? value : new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\nfunction requireId(value: unknown, label: string): string {\n if (typeof value !== 'string' || value.length === 0) {\n throw new Error(`${label} was not persisted with an id.`);\n }\n return value;\n}\n\nfunction isMissingFile(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'ENOENT'\n );\n}\n\nfunction hasMissingFileCause(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'cause' in error &&\n isMissingFile((error as { cause?: unknown }).cause)\n );\n}\n\nfunction isFileAlreadyExists(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'EEXIST'\n );\n}\n\nfunction isDirectoryNotEmpty(error: unknown): boolean {\n return (\n typeof error === 'object' &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B,QAAQ,eAEvC,GADE,4BAA4B,OAAO,eACnB,CAAe;CACvD,OAAO,SAAS,MAAO,CAAC,KAAK,WAAW,IAAI,KAAK,CAAC,WAAW,IAAI;AACnE;AAEA,SAAS,gBAAgB,OAA6B;CACpD,IAAI,EAAE,OAAO,UAAU,YAAY,iBAAiB,OAAO,OAAO;CAClE,MAAM,OAAO,iBAAiB,OAAO,QAAQ,IAAI,KAAK,KAAK;CAC3D,OAAO,OAAO,MAAM,KAAK,QAAQ,CAAC,IAAI,OAAO;AAC/C;AAEA,SAAS,UAAU,OAAgB,OAAuB;CACxD,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAChD,MAAM,IAAI,MAAM,GAAG,MAAK,+BAAgC;CAE1D,OAAO;AACT;AAEA,SAAS,cAAc,OAAyB;CAC9C,OACE,OAAO,UAAU,YACjB,UAAU,QACV,UAAU,SACT,MAA6B,SAAS;AAE3C;AAEA,SAAS,oBAAoB,OAAyB;CACpD,OACE,OAAO,UAAU,YACjB,UAAU,QACV,WAAW,SACX,cAAe,MAA8B,KAAK;AAEtD;AAEA,SAAS,oBAAoB,OAAyB;CACpD,OACE,OAAO,UAAU,YACjB,UAAU,QACV,UAAU,SACT,MAA6B,SAAS;AAE3C;AAEA,SAAS,oBAAoB,OAAyB;CACpD,OACE,OAAO,UAAU,YACjB,UAAU,QACV,UAAU,SACT,MAA6B,SAAS;AAE3C"}
|
package/dist/manifest.json
CHANGED
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,13 +3,13 @@
|
|
|
3
3
|
"sensitiveFieldsExcluded": true,
|
|
4
4
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
5
5
|
"packageName": "@happyvertical/smrt-app-runtime",
|
|
6
|
-
"packageVersion": "0.
|
|
6
|
+
"packageVersion": "0.53.1",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
12
|
-
"agents": "
|
|
10
|
+
"manifest": "da2a2cd0f5d02270fdd51827add37e560c895b34a4676caa478ebeba83124800",
|
|
11
|
+
"packageJson": "3040959d9bf43f6bdf831b96cf099d1f6deff5b0720d28dd7b78b70a4cf8acf4",
|
|
12
|
+
"agents": "f209485465cd0e0f48385f49f0785443a717f2563a9d0a6ca811ca0f24940cc2"
|
|
13
13
|
},
|
|
14
14
|
"exports": [
|
|
15
15
|
"."
|
|
@@ -63,5 +63,5 @@
|
|
|
63
63
|
"polymorphicAssociations": 0,
|
|
64
64
|
"uuidColumns": 0
|
|
65
65
|
},
|
|
66
|
-
"agentDoc": "# @happyvertical/smrt-app-runtime\n\nApplication infrastructure composition for the validated runtime profiles in\n`@happyvertical/smrt-config`.\n\n## Local profile\n\n- `validateApplicationId()` is the canonical strict validator for explicit app\n IDs. `encodeApplicationId()` derives a length-bounded, collision-resistant\n ID from package names; generated operational surfaces must share these APIs.\n- `initializeLocalApplicationRuntime()` owns user data paths, SQLite tuning,\n local application-secret creation, and the single-use owner bootstrap flow.\n- SQLite is acquired through `@happyvertical/sql`'s explicit\n `{ driver: 'node:sqlite', custody: 'trusted-parent' }` boundary after the\n runtime establishes its user-owned mode-0700 data root.\n- Application migrations are explicit through `prepareDatabase`; runtime never\n creates application model tables implicitly. A rejected `prepareDatabase` is\n normalized into `LocalRuntimeError` with the stable `migration_failed` code\n and the fixed recovery message `MIGRATION_FAILED_MESSAGE` (\"run pnpm\n app:setup and inspect the private migration logs\"). The caller's error text\n is never surfaced — it is retained only as a non-enumerable `cause` for\n private logs — and the same application root stays retryable.\n- Standalone migration commands must call `prepareLocalDatabaseStorage()`\n before opening SQLite so custody is established without creating schema or\n bootstrap records.\n- Read-only/copy/import operator commands must call\n `validateLocalDatabaseStorage()` before opening SQLite; it verifies the\n app-bound marker, source separation, real path chain, ownership, and mode\n without creating or repairing storage.\n- Owner bootstrap creates normal `Person`, `User`, `Tenant`, owner `Role` /\n `Membership`, and `Session` records in one transaction.\n- Bootstrap is loopback-only. Only an HMAC of the short-lived token is stored.\n- Background jobs and application-defined paid capabilities are default-off.\n- The embedded runner reuses `TaskRunner`; it is not a second job contract.\n\n## Deployed profiles\n\n- `initializeDeployedApplicationRuntime()` composes only `self-hosted` and\n `cloud`; it rejects local initialization and provider/binding mismatches.\n- Provider bindings own credentials, vendor clients, and readiness checks.\n Runtime diagnostics contain selectors and status only.\n- The database binding must expose a provider-owned `close` callback before\n `connect` can run. The runtime owns that cleanup boundary and runs the\n application's explicit, idempotent `prepareDatabase` hook.\n- A failed startup cleanup throws `DeployedRuntimeCleanupError`; callers retain\n and retry its idempotent `retryCleanup()` boundary until it succeeds.\n- Public authentication, asset storage, and secret bindings are mandatory and\n readiness-checked before startup succeeds.\n- `createTaskWorker()` and `createScheduleWorker()` initialize the normal jobs\n package runners against the shared PostgreSQL database. They are intended for\n separate processes; the web process does not start them automatically. The\n worker process must import the app's compiled registration\n (`.smrt/runtime/register.js`, #3117) first; runners resolve `objectType`\n through the registry and never load application source themselves.\n- `close()` drains in-flight readiness/session/worker initialization and\n serialized runner start/stop operations, stops every runner returned by the\n runtime, and then closes PostgreSQL. Returned runners must not be restarted\n after runtime shutdown begins.\n- A tracked operation may await a re-entrant `close()` request without\n deadlocking; external `close()` callers still await complete cleanup.\n- `health()` is process liveness. `readiness()` probes database/auth/assets/\n secrets; it does not claim that an external worker fleet is running.\n- Database-provider readiness is additive; a PostgreSQL-specific server-version\n probe always gates startup and live readiness.\n- Cloud must keep required tenant context and must never introduce a root or\n unscoped tenant fallback. RLS remains an explicit deployment/migration choice.\n\n## Public runtime diagnostics\n\n- `projectRuntimeDiagnostics()` is the only public diagnostic projection. It\n constructs the schema-version-1 allowlist and never serializes the private\n local or deployed diagnostics objects.\n- The allowlist is limited to active profile/coarse health, schema and\n migration readiness, six fixed capability statuses, a sorted/capped public\n tool inventory plus digest, explicit operational topology differences,\n coarse worker heartbeat state, and eight stable code/timestamp errors.\n- Callers supply an explicit clock and worker-heartbeat seam. A missing\n heartbeat is `unknown`; web-process liveness never proves worker liveness.\n- Error ingestion maps unknown codes to `runtime_error`, truncates timestamps\n to the minute, and ignores messages, stacks, logs, records, and nested state.\n- Authentication and diagnostics-read authorization belong before every call\n to the projector or its runtime probes.\n\n## Invariants\n\n- Never expose application-secret bytes or bootstrap token hashes in diagnostics.\n- Never include migration or provider error text in a local or deployed startup\n error message; migration driver text is a likely credential carrier.\n- Never include provider error text, URLs, tokens, or credentials in deployed\n errors, diagnostics, health, or readiness payloads.\n- Keep local data, assets, database, and secrets outside the source tree.\n- Do not reach into collection/database private fields. Add an upstream public\n API if composition cannot be expressed through exported surfaces.\n- Keep profile selection out of domain models, generated APIs, MCP/WebMCP\n surfaces, effects, approvals, and authorization records.\n\n## Validation\n\n```bash\npnpm --filter @happyvertical/smrt-app-runtime test\npnpm --filter @happyvertical/smrt-app-runtime typecheck\npnpm --filter @happyvertical/smrt-app-runtime build\n```\n"
|
|
66
|
+
"agentDoc": "# @happyvertical/smrt-app-runtime\n\nApplication infrastructure composition for the validated runtime profiles in\n`@happyvertical/smrt-config`.\n\n## Local profile\n\n- `validateApplicationId()` is the canonical strict validator for explicit app\n IDs. `encodeApplicationId()` derives a length-bounded, collision-resistant\n ID from package names; generated operational surfaces must share these APIs.\n- `initializeLocalApplicationRuntime()` owns user data paths, SQLite tuning,\n local application-secret creation, and the single-use owner bootstrap flow.\n- SQLite is acquired through `@happyvertical/sql`'s explicit\n `{ driver: 'node:sqlite', custody: 'trusted-parent' }` boundary after the\n runtime establishes its user-owned mode-0700 data root.\n- Application migrations are explicit through `prepareDatabase`; runtime never\n creates application model tables implicitly. A rejected `prepareDatabase` is\n normalized into `LocalRuntimeError` with the stable `migration_failed` code\n and the fixed recovery message `MIGRATION_FAILED_MESSAGE` (\"run pnpm\n app:setup and inspect the private migration logs\"). The caller's error text\n is never surfaced — it is retained only as a non-enumerable `cause` for\n private logs — and the same application root stays retryable.\n- Standalone migration commands must call `prepareLocalDatabaseStorage()`\n before opening SQLite so custody is established without creating schema or\n bootstrap records.\n- Read-only/copy/import operator commands must call\n `validateLocalDatabaseStorage()` before opening SQLite; it verifies the\n app-bound marker, source separation, real path chain, ownership, and mode\n without creating or repairing storage.\n- Owner bootstrap creates normal `Person`, `User`, `Tenant`, owner `Role` /\n `Membership`, and `Session` records in one transaction.\n- Bootstrap is loopback-only. Only an HMAC of the short-lived token is stored.\n A token that cannot claim fails a read-only preflight before role/catalog\n seeding (#3323); the claim transaction's conditional UPDATE stays the\n authority for single use, expiry, and concurrency.\n- Background jobs and application-defined paid capabilities are default-off.\n- The embedded runner reuses `TaskRunner`; it is not a second job contract.\n\n## Deployed profiles\n\n- `initializeDeployedApplicationRuntime()` composes only `self-hosted` and\n `cloud`; it rejects local initialization and provider/binding mismatches.\n- Provider bindings own credentials, vendor clients, and readiness checks.\n Runtime diagnostics contain selectors and status only.\n- The database binding must expose a provider-owned `close` callback before\n `connect` can run. The runtime owns that cleanup boundary and runs the\n application's explicit, idempotent `prepareDatabase` hook.\n- A failed startup cleanup throws `DeployedRuntimeCleanupError`; callers retain\n and retry its idempotent `retryCleanup()` boundary until it succeeds.\n- Public authentication, asset storage, and secret bindings are mandatory and\n readiness-checked before startup succeeds.\n- `createTaskWorker()` and `createScheduleWorker()` initialize the normal jobs\n package runners against the shared PostgreSQL database. They are intended for\n separate processes; the web process does not start them automatically. The\n worker process must import the app's compiled registration\n (`.smrt/runtime/register.js`, #3117) first; runners resolve `objectType`\n through the registry and never load application source themselves.\n- `close()` drains in-flight readiness/session/worker initialization and\n serialized runner start/stop operations, stops every runner returned by the\n runtime, and then closes PostgreSQL. Returned runners must not be restarted\n after runtime shutdown begins.\n- A tracked operation may await a re-entrant `close()` request without\n deadlocking; external `close()` callers still await complete cleanup.\n- `health()` is process liveness. `readiness()` probes database/auth/assets/\n secrets; it does not claim that an external worker fleet is running.\n- Database-provider readiness is additive; a PostgreSQL-specific server-version\n probe always gates startup and live readiness.\n- Cloud must keep required tenant context and must never introduce a root or\n unscoped tenant fallback. RLS remains an explicit deployment/migration choice.\n\n## Public runtime diagnostics\n\n- `projectRuntimeDiagnostics()` is the only public diagnostic projection. It\n constructs the schema-version-1 allowlist and never serializes the private\n local or deployed diagnostics objects.\n- The allowlist is limited to active profile/coarse health, schema and\n migration readiness, six fixed capability statuses, a sorted/capped public\n tool inventory plus digest, explicit operational topology differences,\n coarse worker heartbeat state, and eight stable code/timestamp errors.\n- Callers supply an explicit clock and worker-heartbeat seam. A missing\n heartbeat is `unknown`; web-process liveness never proves worker liveness.\n- Error ingestion maps unknown codes to `runtime_error`, truncates timestamps\n to the minute, and ignores messages, stacks, logs, records, and nested state.\n- Authentication and diagnostics-read authorization belong before every call\n to the projector or its runtime probes.\n\n## Invariants\n\n- Never expose application-secret bytes or bootstrap token hashes in diagnostics.\n- Never include migration or provider error text in a local or deployed startup\n error message; migration driver text is a likely credential carrier.\n- Never include provider error text, URLs, tokens, or credentials in deployed\n errors, diagnostics, health, or readiness payloads.\n- Keep local data, assets, database, and secrets outside the source tree.\n- Do not reach into collection/database private fields. Add an upstream public\n API if composition cannot be expressed through exported surfaces.\n- Keep profile selection out of domain models, generated APIs, MCP/WebMCP\n surfaces, effects, approvals, and authorization records.\n\n## Validation\n\n```bash\npnpm --filter @happyvertical/smrt-app-runtime test\npnpm --filter @happyvertical/smrt-app-runtime typecheck\npnpm --filter @happyvertical/smrt-app-runtime build\n```\n"
|
|
67
67
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@happyvertical/smrt-app-runtime",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.53.1",
|
|
4
4
|
"description": "Validated local, self-hosted, and cloud runtime composition for s-m-r-t applications",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -17,23 +17,23 @@
|
|
|
17
17
|
"AGENTS.md"
|
|
18
18
|
],
|
|
19
19
|
"dependencies": {
|
|
20
|
-
"@happyvertical/smrt-config": "0.
|
|
21
|
-
"@happyvertical/smrt-core": "0.
|
|
22
|
-
"@happyvertical/smrt-jobs": "0.
|
|
23
|
-
"@happyvertical/smrt-profiles": "0.
|
|
24
|
-
"@happyvertical/smrt-tenancy": "0.
|
|
25
|
-
"@happyvertical/smrt-users": "0.
|
|
26
|
-
"@happyvertical/sql": "^0.
|
|
20
|
+
"@happyvertical/smrt-config": "0.53.1",
|
|
21
|
+
"@happyvertical/smrt-core": "0.53.1",
|
|
22
|
+
"@happyvertical/smrt-jobs": "0.53.1",
|
|
23
|
+
"@happyvertical/smrt-profiles": "0.53.1",
|
|
24
|
+
"@happyvertical/smrt-tenancy": "0.53.1",
|
|
25
|
+
"@happyvertical/smrt-users": "0.53.1",
|
|
26
|
+
"@happyvertical/sql": "^0.98.0"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
|
-
"@happyvertical/smrt-vitest": "0.
|
|
29
|
+
"@happyvertical/smrt-vitest": "0.53.1",
|
|
30
30
|
"@types/node": "24.13.6",
|
|
31
31
|
"typescript": "6.0.3",
|
|
32
32
|
"vite": "8.1.4",
|
|
33
33
|
"vitest": "4.1.10"
|
|
34
34
|
},
|
|
35
35
|
"engines": {
|
|
36
|
-
"node": ">=
|
|
36
|
+
"node": ">=26.0.0"
|
|
37
37
|
},
|
|
38
38
|
"publishConfig": {
|
|
39
39
|
"registry": "https://registry.npmjs.org",
|