import { createHash } from "node:crypto"; import { isDeepStrictEqual } from "node:util"; import { z } from "zod"; import { databaseConfigurationSchema } from "./configuration-schema.js"; import { CATALOG_SECRET_IDS } from "./secrets.js"; import type { CatalogRepository } from "./types.js"; import type { CatalogService } from "./service.js"; import type { CatalogOperationCoordinator } from "./operation-coordinator.js"; import type { WorkspaceRegistry } from "../workspaces/registry.js"; import type { WorkspaceSecretStore } from "../workspaces/secret-store.js"; import { discoverWorkspaceSecretRequirements } from "../workspaces/secret-requirements.js"; const secret = z.string().min(1).refine(value => Buffer.byteLength(value, "utf8") <= 65536); export const installationBindingSchema = z.object({ schemaVersion: z.literal(1), revision: z.string().regex(/^[a-f0-9]{40}$/), configuration: databaseConfigurationSchema, secrets: z.object({ password: secret.optional(), apiKey: secret.optional(), sshPrivateKey: secret.optional(), sshPrivateKeyPassphrase: secret.optional(), sshKnownHosts: secret.optional(), tlsCa: secret.optional() }).strict(), evidenceSecrets: z.object({ "evidence.signed_urls": secret.optional(), "evidence.access_key": secret.optional(), "evidence.secret_key": secret.optional(), "evidence.session_token": secret.optional() }).strict(), }).strict(); export class InstallationReconciliationRequired extends Error {} const conflict = () => { throw new InstallationReconciliationRequired("Reconcile the prepared documents with current administrative state."); }; /** Only called behind the ordinary authenticated administration permission boundary. */ export class InstallationBindings { constructor(private readonly repository: CatalogRepository, private readonly catalog: CatalogService, private readonly registry: WorkspaceRegistry, private readonly secrets: WorkspaceSecretStore, private readonly operations: CatalogOperationCoordinator, private readonly installationId: string) {} async apply(raw: unknown) { const request = installationBindingSchema.parse(raw); const workspaceId = request.configuration.workspaceId; const { workspace, revision } = await this.registry.read(workspaceId); if (revision.commit !== request.revision) return conflict(); const input = await this.catalog.normalizeInput(request.configuration); const required = input.binding.transport === "rest_api" ? (input.binding.restAuth === "none" ? [] : ["apiKey"]) : input.binding.transport === "ssh_tunnel" ? ["password", "sshPrivateKey", "sshKnownHosts"] : ["password"]; if (required.some(name => !request.secrets[name as keyof typeof request.secrets])) return conflict(); const evidenceRequirements = discoverWorkspaceSecretRequirements(workspace, {}).filter(item => item.connector === "evidence" && item.required); if (evidenceRequirements.some(item => !(request.evidenceSecrets as Record)[item.id])) return conflict(); const values: Record = { ...request.evidenceSecrets }; for (const [name, value] of Object.entries(request.secrets)) values[CATALOG_SECRET_IDS[name as keyof typeof CATALOG_SECRET_IDS]] = value; // Stable installation-local identity is persisted atomically with the initial binding. // A crash before any host journal update is recoverable without adopting a manually created row. const hex = createHash("sha256").update(`thothii-installation-binding-v1\0${this.installationId}\0${workspaceId}`).digest("hex"); const id = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20, 32)}`; const applied = await this.operations.run(id, async () => { let current = await this.repository.getByWorkspace(workspaceId); let changed = false; if (!current) { current = await this.repository.create(input, id); changed = true; } if (current.id !== id || !isDeepStrictEqual(input, { workspaceId: current.workspaceId, engine: current.engine, databaseName: current.databaseName, schema: current.schema, binding: Object.fromEntries(Object.entries(current.binding).filter(([, value]) => value !== undefined)), })) return conflict(); const configured = this.secrets.configured(workspaceId).filter(name => name.startsWith("catalog.") || name.startsWith("evidence.")); if (configured.some(name => values[name] === undefined || !this.secrets.matches(workspaceId, name, values[name]))) return conflict(); const missing = Object.fromEntries(Object.entries(values).filter(([name]) => !configured.includes(name))); if (Object.keys(missing).length) { if (current.version !== 1) return conflict(); // Synchronous atomic vault update cannot interleave with another mutation in this core. this.secrets.putMany(workspaceId, missing); changed = true; } if (current.version === 1) { const touched = await this.repository.touch(id, current.version); if (!touched) return conflict(); current = touched; changed = true; } return { current, changed }; }); const tested = await this.catalog.test(applied.current); if (!tested || tested.version !== applied.current.version || (await this.registry.read(workspaceId)).revision.commit !== request.revision) return conflict(); return { schemaVersion: 1, workspaceId, databaseId: tested.id, version: tested.version, status: applied.changed ? "applied" : "unchanged", connectionStatus: tested.connectionStatus }; } }