#!/usr/bin/env node import { createHash } from "node:crypto"; import { spawnSync } from "node:child_process"; import { cp, lstat, mkdir, mkdtemp, readFile, readdir, rm, writeFile, } from "node:fs/promises"; import { tmpdir } from "node:os"; import { basename, dirname, join, relative, resolve } from "node:path"; import { fileURLToPath } from "node:url"; const scriptDir = dirname(fileURLToPath(import.meta.url)); const platformRoot = resolve(scriptDir, "../.."); const sourceRoot = resolve(platformRoot, "device-plane"); const artifactDir = resolve( process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(scriptDir, "../deploy-artifacts"), ); const runtimeCache = resolve( process.env.NODEDC_DEVICE_EDGE_VPS_RUNTIME_DIR || "/tmp", ); const [phase, patchId, ...extra] = process.argv.slice(2); if ( extra.length || !["foundation", "backhaul", "relay", "core-channel"].includes(phase) || !/^[A-Za-z0-9._-]{1,96}$/.test(patchId || "") ) { throw new Error( "usage: build-device-edge-vps-artifact.mjs ", ); } const supersededTransportPhases = new Set(["backhaul", "relay"]); if ( supersededTransportPhases.has(phase) && process.env.NODEDC_ALLOW_SUPERSEDED_TRANSPORT !== "test-only" ) { throw new Error("vps_initiated_transport_frozen:ADR-0001"); } const nodeArchive = "node-v22.23.2-linux-x64.tar.xz"; const tailscaleArchive = "tailscale_1.102.2_amd64.tgz"; const runtimeDigests = new Map([ [nodeArchive, "d60acfe00a2932254bb0ad20e01b0d74397a0875595de719654b214f4b03f307"], [tailscaleArchive, "ad2cde12f8de95f7b93a1e0401e652291c603d42b9d60a33fb1741eb38ab04d8"], ]); const entriesByPhase = { foundation: [ "vps/config/00-nodedc-b2-vps.conf", "vps/config/nftables-foundation.conf", "vps/systemd/nodedc-b2-tailscaled.service", "deployment/device-edge-vps-foundation-v1.json", `vendor/${nodeArchive}`, `vendor/${tailscaleArchive}`, ], backhaul: [ "vps/config/backhaul_ssh_config", "vps/systemd/nodedc-b2-backhaul.service", "deployment/device-edge-vps-backhaul-v1.json", ], relay: [ "vps/config/nftables-relay.conf", "vps/systemd/nodedc-b2-relay.service", "services/device-edge-relay/src", "deployment/device-edge-vps-relay-v1.json", ], "core-channel": [ "packages/device-protocol-contract/package.json", "packages/device-protocol-contract/src", "packages/device-edge-channel-contract/package.json", "packages/device-edge-channel-contract/src", "services/device-edge-channel/package.json", "services/device-edge-channel/src", "vps/config/nftables-core-channel.conf", "vps/systemd/nodedc-device-edge-channel.service", "deployment/device-edge-vps-core-channel-v1.json", ], }; const entries = entriesByPhase[phase]; const ignoredBasenames = new Set([".DS_Store", ".git", "node_modules"]); const stage = await mkdtemp(join(tmpdir(), `nodedc-device-edge-vps-${phase}-`)); const payload = join(stage, "payload"); const target = join( artifactDir, `nodedc-device-edge-vps-${patchId}.tgz`, ); await assertBoundary(); try { await mkdir(payload, { recursive: true }); for (const entry of entries) { if (entry.startsWith("vendor/")) { const name = basename(entry); const source = resolve(runtimeCache, name); const actual = createHash("sha256").update(await readFile(source)).digest("hex"); if (actual !== runtimeDigests.get(name)) { throw new Error(`runtime_digest_mismatch:${name}:${actual}`); } await mkdir(dirname(join(payload, entry)), { recursive: true }); await cp(source, join(payload, entry), { force: true }); continue; } await copySafe(resolve(sourceRoot, entry), join(payload, entry)); } await writeFile( join(stage, "manifest.env"), `id=${patchId}\ncomponent=device-edge-vps\ntype=app-overlay\n`, "utf8", ); await writeFile(join(stage, "files.txt"), `${entries.join("\n")}\n`, "utf8"); await mkdir(artifactDir, { recursive: true }); const tar = spawnSync( "python3", ["-c", canonicalTarScript(), target, stage], { encoding: "utf8", maxBuffer: 256 * 1024 * 1024 }, ); if (tar.status !== 0) { throw new Error(`tar_failed:${tar.stderr || tar.stdout}`); } const bytes = await readFile(target); const digest = createHash("sha256").update(bytes).digest("hex"); console.log(JSON.stringify({ ok: true, patchId, phase, artifact: target, sha256: digest, size: bytes.length, component: "device-edge-vps", entries, publicIngress: phase === "relay" ? "tcp/9921" : phase === "core-channel" ? "tcp/8443-mtls-only" : "disabled", commandTransport: "disabled", gelios: "untouched", }, null, 2)); } finally { await rm(stage, { recursive: true, force: true }); } async function assertBoundary() { const descriptorPath = resolve( sourceRoot, `deployment/device-edge-vps-${phase}-v1.json`, ); const descriptor = JSON.parse(await readFile(descriptorPath, "utf8")); if ( descriptor.component !== "device-edge-vps" || descriptor.runtimeHost !== "koffyvngij" || descriptor.commandTransport !== "disabled" || descriptor.gelios !== "untouched" || !String(descriptor.rollback || "").length ) { throw new Error(`descriptor_boundary_mismatch:${phase}`); } const selectedText = await Promise.all( entries .filter((entry) => !entry.startsWith("vendor/") && !entry.endsWith("/src")) .map((entry) => readFile(resolve(sourceRoot, entry), "utf8")), ); const combined = selectedText.join("\n"); for (const forbidden of [ "PRIVATE KEY", "AuthKey", "TS_AUTHKEY", "PasswordAuthentication yes", "commandTransport\": \"enabled", "device.dc.ru", ]) { if (combined.includes(forbidden)) { throw new Error(`vps_boundary_violation:${forbidden}`); } } if (phase === "foundation") { for (const required of [ "PermitRootLogin prohibit-password", "PasswordAuthentication no", "AllowTcpForwarding no", "policy drop", "tcp dport 22", "--tun=userspace-networking", "--socks5-server=127.0.0.1:1055", ]) { if (!combined.includes(required)) { throw new Error(`foundation_boundary_missing:${required}`); } } if (combined.includes("tcp dport 9921")) { throw new Error("foundation_must_not_open_9921"); } } if (phase === "backhaul") { for (const required of [ "\"runtimeUser\": \"nodedc-backhaul\"", "User=nodedc-backhaul", "HostName 100.109.216.21", "Port 2222", "StrictHostKeyChecking yes", "LocalForward 127.0.0.1:19921 127.0.0.1:9921", "ProxyCommand /usr/bin/nc -X 5 -x 127.0.0.1:1055", "MemoryMax=64M", ]) { if (!combined.includes(required)) { throw new Error(`backhaul_boundary_missing:${required}`); } } } if (phase === "relay") { for (const required of [ "\"runtimeUser\": \"nodedc-relay\"", "User=nodedc-relay", "tcp dport 9921", "DEVICE_EDGE_RELAY_UPSTREAM_HOST=127.0.0.1", "DEVICE_EDGE_RELAY_UPSTREAM_PORT=19921", "DEVICE_EDGE_RELAY_SOURCE_POLICY=public-ipv4-only", "MemoryMax=192M", ]) { if (!combined.includes(required)) { throw new Error(`relay_boundary_missing:${required}`); } } } if (phase === "core-channel") { for (const required of [ "\"runtimeUser\": \"nodedc-channel\"", "\"trackerIngress\": \"disabled\"", "User=nodedc-channel", "node --jitless", "tcp dport 8443", "MemoryMax=128M", "MemorySwapMax=0", "CPUQuota=50%", "TasksMax=64", "LimitNOFILE=1024", ]) { if (!combined.includes(required)) { throw new Error(`core_channel_boundary_missing:${required}`); } } for (const forbidden of [ "tcp dport 9921", "LocalForward", "tailscale-userspace", "DEVICE_EDGE_RELAY_UPSTREAM", ]) { if (combined.includes(forbidden)) { throw new Error(`core_channel_boundary_violation:${forbidden}`); } } } } function canonicalTarScript() { return [ "import gzip,io,pathlib,sys,tarfile", "root=pathlib.Path(sys.argv[2])", "with open(sys.argv[1],'wb') as out:", " with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:", " with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:", " for top in ('manifest.env','files.txt','payload'):", " p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])", " for x in paths:", " info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())", " info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644", " with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)", ].join("\n"); } async function copySafe(source, destination) { const sourceStat = await lstat(source); if (sourceStat.isSymbolicLink()) { throw new Error(`source_symlink_rejected:${relative(sourceRoot, source)}`); } if (sourceStat.isFile()) { await mkdir(dirname(destination), { recursive: true }); await cp(source, destination, { force: true, verbatimSymlinks: true }); return; } if (!sourceStat.isDirectory()) { throw new Error(`source_type_rejected:${source}`); } await mkdir(destination, { recursive: true }); for (const entry of await readdir(source, { withFileTypes: true })) { if (ignoredBasenames.has(entry.name) || entry.name.startsWith(".env")) { continue; } const childSource = join(source, entry.name); const childDestination = join(destination, entry.name); if (entry.isSymbolicLink()) { throw new Error(`source_symlink_rejected:${relative(sourceRoot, childSource)}`); } await copySafe(childSource, childDestination); } }