import { readFile, writeFile, mkdir } from "node:fs/promises"; import { resolve } from "node:path"; import { root, local, compose, run, requireThat, safeFailure, privateWrite, } from "./runtime"; import { verifyBackendHandover } from "./preflight-build"; import { writeTopology } from "./topology"; import { issue } from "./pki"; import { prepareOpenObserve, provisionOpenObserve, openObserveRequest, } from "./openobserve"; async function main() { requireThat( root === "/mnt/data/home/bench-saves/mtuci-vp7-security-20261115", "OPENOBSERVE_SESSION_REMOTE_BOUNDARY_REQUIRED", ); const receipt = resolve( root, "evidence/openobserve", "native-session-" + crypto.randomUUID() + ".json", ); await mkdir(resolve(receipt, ".."), { recursive: true }); await writeFile( receipt, JSON.stringify({ state: "RUNNING", stage: "SOURCE_LEASE" }), { flag: "wx", mode: 0o600 }, ); let stage = "SOURCE_LEASE", started = false, failed = false; try { const lease = await verifyBackendHandover(); requireThat( lease.sha256 === "09fe19253582282e489406600f3ee20c1e52d786778d6ce90f9d9da4146e5609", "OPENOBSERVE_BACKEND_GENERATION_MISMATCH", ); stage = "OWN_STAND_IDLE"; requireThat( ( await run([ "docker", "ps", "--filter", "label=com.docker.compose.project=mtuci-vp7-security", "--format", "{{.ID}}", ]) ).out.trim() === "", "OPENOBSERVE_EXISTING_OWN_STAND_RUNNING", ); stage = "CACHED_IMAGE_FREEZE"; const freeze = JSON.parse( await readFile( resolve(root, "evidence/openobserve/image-freeze.json"), "utf8", ), ); for (const image of freeze.images) { const current = JSON.parse( (await run(["docker", "image", "inspect", image.target])).out, )[0]; requireThat( current.Id === image.image_id && current.Os === "linux" && current.Architecture === "amd64", "OPENOBSERVE_CACHED_IMAGE_DRIFT", ); } stage = "OPERATOR_KEY"; const password = await readFile( resolve(root, ".local-preflight-key"), "utf8", ); requireThat( /^[a-f0-9]{64}$/.test(password), "INVALID_PREFLIGHT_SESSION_KEY", ); stage = "PREPARE_OWN_CREDENTIALS"; await prepareOpenObserve(password); stage = "OPENOBSERVE_CERTIFICATE"; if ( !(await Bun.file( resolve(local, "pki/openobserve-gateway/server.pem"), ).exists()) ) await issue( resolve(local, "operator/ca"), resolve(local, "pki/openobserve-gateway"), "openobserve-gateway", password, ); stage = "COMPOSE_IMAGE_BINDINGS"; let environment = await readFile(resolve(root, ".env"), "utf8"); for (const image of freeze.images) { const key = image.name === "collector" ? "VP7_COLLECTOR_IMAGE" : "VP7_OPENOBSERVE_IMAGE"; const line = `${key}=${image.target}`; requireThat( !environment.includes(key + "=") || environment.split("\n").includes(line), "OPENOBSERVE_ENV_IMAGE_CONFLICT", ); if (!environment.split("\n").includes(line)) environment += "\n" + line + "\n"; } await privateWrite(resolve(root, ".env"), environment); stage = "GENERATE_CURRENT_TOPOLOGY"; await writeTopology(); stage = "COMPOSE_VALIDATE"; await compose(["config", "--quiet"]); stage = "OPENOBSERVE_START"; started = true; await compose(["up", "-d", "openobserve-gateway", "openobserve"]); stage = "OPENOBSERVE_AUTHENTICATED_BOOT"; let ready = false; const deadline = Date.now() + 60_000; while (Date.now() < deadline) { try { const response = await openObserveRequest("/api/default/streams", { password, }); if (response.status === 200) { ready = true; break; } } catch {} await Bun.sleep(500); } requireThat(ready, "OPENOBSERVE_AUTHENTICATED_BOOT_TIMEOUT"); stage = "PROVISION_NATIVE_SERVICE_ACCOUNTS"; await provisionOpenObserve(password); stage = "QUERY_SERVICE_ACCOUNT"; const query = await openObserveRequest("/api/default/streams", { password, account: "query", role: "grafana", }); requireThat(query.status === 200, "OPENOBSERVE_QUERY_PRINCIPAL_REJECTED"); stage = "COLLECTOR_CONFIG_VALIDATE"; await compose(["up", "-d", "collector-gateway"]); await compose([ "run", "--rm", "--no-deps", "collector", "validate", "--config=/etc/otelcol/config.yaml", ]); stage = "INITIAL_SOURCE_POSTGUARD"; requireThat( (await verifyBackendHandover()).sha256 === lease.sha256, "OPENOBSERVE_BACKEND_GENERATION_CHANGED", ); await writeFile( receipt, JSON.stringify( { state: "PASS_NATIVE_STORAGE_BOOTSTRAP_ONLY", stage, backend_sha256: lease.sha256, nativeOpenObserve: true, nativeCollectorConfig: true, nativeApplicationSignals: false, nativeGrafana: false, nativeBao: false, }, null, 2, ) + "\n", ); console.log("PASS_NATIVE_OPENOBSERVE_BOOTSTRAP_AND_COLLECTOR_CONFIG_ONLY"); } catch (error) { failed = true; await Promise.allSettled([ writeFile( receipt, JSON.stringify({ state: "FAILED", stage, code: error instanceof Error && /^[A-Z][A-Za-z0-9_:-]{0,240}$/.test(error.message) ? error.message : "PRIVATE_DETAILS_ONLY", }) + "\n", ), ]); throw error; } finally { if (started) { const outcomes = await Promise.allSettled([ compose( [ "stop", "collector", "collector-gateway", "openobserve", "openobserve-gateway", ], { allowFailure: true }, ), ]); const stopped = outcomes[0].status === "fulfilled" && outcomes[0].value.code === 0; console.log( stopped ? "OWN_OPENOBSERVE_SESSION_STOPPED" : "OWN_OPENOBSERVE_STOP_REQUIRES_INSPECTION", ); await Promise.allSettled([ Promise.resolve().then(async () => { const saved = JSON.parse(await readFile(receipt, "utf8")); saved.teardown = { stop_exit: outcomes[0].status === "fulfilled" ? outcomes[0].value.code : null, }; if (!stopped && !failed) saved.state = "FAILED_TEARDOWN"; await writeFile(receipt, JSON.stringify(saved, null, 2) + "\n"); }), ]); if (!stopped && !failed) throw new Error("OPENOBSERVE_SESSION_STOP_FAILED"); } } } if (import.meta.main) { try { await main(); } catch (error) { safeFailure(error); } }