import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; import { resolve, relative } from "node:path"; import { createHash } from "node:crypto"; import { root, local, run, compose, requireThat, privateWrite, safeFailure, } from "./runtime"; import { verifyCheckedRuntime } from "./checked-runtime"; import { acceptanceSession } from "./acceptance-session"; import { decrypt } from "./operator-crypto"; import { createBrowserLifecycle } from "./browser-lifecycle"; import { readCanonicalGitProof } from "./git-tracking-source"; import { type GitTrackingSource } from "./git-tracking-proof"; async function main() { requireThat( root === "/mnt/data/home/bench-saves/mtuci-vp7-security-20261115", "NATIVE_SECURITY_OWN_DIRECTORY_REQUIRED", ); const lease = await verifyCheckedRuntime(); const proofPath = Bun.argv[Bun.argv.indexOf("--git-proof") + 1]; const proofSHA = Bun.argv[Bun.argv.indexOf("--git-proof-sha") + 1]; requireThat( Bun.argv.includes("--git-proof") && Bun.argv.includes("--git-proof-sha") && /^[a-f0-9]{64}$/.test(proofSHA ?? ""), "CANONICAL_GIT_PROOF_REFERENCE_REQUIRED", ); const gitSource: GitTrackingSource = { kind: "canonical-proof", path: proofPath, sha256: proofSHA, }; const gitGuard = await readCanonicalGitProof(gitSource); requireThat( ( await run([ "docker", "ps", "--filter", "label=com.docker.compose.project=mtuci-vp7-security", "--format", "{{.ID}}", ]) ).out.trim() === "", "NATIVE_SECURITY_OWN_STAND_ALREADY_RUNNING", ); await compose(["config", "--quiet"]); if (Bun.argv.includes("--check")) { console.log( "PASS_NATIVE_SECURITY_INITIAL_SOURCE_BINARY_IMAGE_COMPOSE_GUARDS", ); return; } const operationId = crypto.randomUUID(), path = resolve( root, "evidence/openbao/native-acceptance-" + operationId + ".json", ); await mkdir(resolve(path, ".."), { recursive: true }); await writeFile( path, JSON.stringify({ state: "RUNNING", operation_id: operationId, stage: "PRESERVE_HISTORY", expected_git_proof: gitSource, source_generation_sha256: gitGuard.source_generation_sha256, }) + "\n", { flag: "wx", mode: 0o644 }, ); let stage = "PRESERVE_HISTORY", primary: unknown, failed = false, stopExit: number | null = null, postGuard = false, remaining: number | null = null, stopSeconds: number | null = null, inner: any = null; const prior: Record = {}, hash = (b: Uint8Array) => createHash("sha256").update(b).digest("hex"); try { // Reuse the tested generic required-port ownership helper; no browser dependency is loaded. await createBrowserLifecycle({ acquire: async () => operationId, run: async () => { const history = resolve(local, "native-history-" + operationId); async function preserve(dir: string) { for (const entry of await readdir(dir, { withFileTypes: true })) { const source = resolve(dir, entry.name), name = relative(resolve(root, "evidence/security"), source), target = resolve(history, "evidence/security", name); if (entry.isDirectory()) await preserve(source); else { requireThat(entry.isFile(), "NONREGULAR_SECURITY_EVIDENCE"); const bytes = await readFile(source); await mkdir(resolve(target, ".."), { recursive: true, mode: 0o700, }); await writeFile(target, bytes, { flag: "wx", mode: 0o600 }); prior[name] = hash(bytes); } } } await preserve(resolve(root, "evidence/security")); stage = "PRIVATE_OPERATOR_GUARD"; const password = await readFile( resolve(root, ".local-preflight-key"), "utf8", ); requireThat( /^[a-f0-9]{64}$/.test(password), "INVALID_PRIVATE_OPERATOR_KEY", ); decrypt( await readFile(resolve(local, "operator/services.enc"), "utf8"), password, ); stage = "NATIVE_BAO_SECURITY_ACCEPTANCE"; await acceptanceSession(password, "checked-cache", gitSource); inner = JSON.parse( await readFile( resolve(root, "evidence/security/session.json"), "utf8", ), ); requireThat( inner.state === "PASS" && inner.runtime_mode === "checked-cache" && /^[a-f0-9-]{36}$/.test(inner.operation_id), "NATIVE_ACCEPTANCE_RESULT_UNBOUND", ); stage = "POST_SOURCE_BINARY_IMAGE_GUARDS"; await lease.verify(); await readCanonicalGitProof(gitSource); postGuard = true; stage = "COMPLETE"; }, close: async () => { if (stage === "COMPLETE") stage = "OWN_TEARDOWN"; const stopStarted = Date.now(); const stopped = await compose(["--profile", "*", "stop"], { allowFailure: true, }); stopExit = stopped.code; stopSeconds = (Date.now() - stopStarted) / 1000; const ps = await run([ "docker", "ps", "--filter", "label=com.docker.compose.project=mtuci-vp7-security", "--format", "{{.ID}}", ]); remaining = ps.out.trim() ? ps.out.trim().split("\n").length : 0; requireThat( stopExit === 0 && remaining === 0, "NATIVE_SECURITY_TEARDOWN_FAILED", ); if (stage === "OWN_TEARDOWN") stage = "COMPLETE"; }, reportCleanupFailure: (error) => privateWrite( resolve( local, "diagnostics/native-security-cleanup-" + operationId + ".json", ), JSON.stringify({ message: error instanceof Error ? error.message : "UNKNOWN", }), ), })(); } catch (error) { failed = true; primary = error; await Promise.allSettled([ privateWrite( resolve( local, "diagnostics/native-security-primary-" + operationId + ".json", ), JSON.stringify({ stage, message: error instanceof Error ? error.message : "UNKNOWN", stack: error instanceof Error ? error.stack : null, }), ), ]); } try { await writeFile( path, JSON.stringify( { state: !failed && stopExit === 0 && remaining === 0 && postGuard ? "PASS_DEFINED_NATIVE_ACCEPTANCE" : "FAILED", operation_id: operationId, stage, runtime_mode: "checked112 cached app binaries; native Bao2.7.2/PebbleDB and Agent", provider: "native OpenBao cert auto-auth/Agent, not operator heartbeat", backend_files: 112, backend_sha256: lease.source_sha256, image_id: lease.image_id, binaries: lease.binaries, expected_git_proof: gitSource, source_generation_sha256: gitGuard.source_generation_sha256, post_source_binary_image_guards: postGuard, inner_acceptance_operation: inner?.operation_id ?? null, inner_acceptance_receipt: "evidence/security/session.json", preserved_previous_public_evidence_files: Object.keys(prior).length, preserved_history: relative( root, resolve(local, "native-history-" + operationId), ), preserved_history_hashes: prior, stop_exit: stopExit, stop_seconds: stopSeconds, remaining_owned_containers: remaining, full_security_complete: false, whole_telemetry_complete: false, grade_awarded: false, primary_details_private: failed, }, null, 2, ) + "\n", ); } catch (error) { if (!failed) { failed = true; primary = error; } await Promise.allSettled([ privateWrite( resolve( local, "diagnostics/native-security-receipt-" + operationId + ".json", ), JSON.stringify({ message: error instanceof Error ? error.message : "UNKNOWN", }), ), ]); } console.log( JSON.stringify({ receipt: path, state: !failed && stopExit === 0 && remaining === 0 && postGuard ? "PASS_DEFINED_NATIVE_ACCEPTANCE" : "FAILED", stage, stop_exit: stopExit, remaining_owned_containers: remaining, }), ); if (failed) throw primary; requireThat( stopExit === 0 && remaining === 0, "NATIVE_SECURITY_TEARDOWN_FAILED", ); } if (import.meta.main) try { await main(); } catch (error) { safeFailure(error); }