NODEDC_PLATFORM/infra/deploy-runner/build-engine-provider-secur...

118 lines
4.4 KiB
JavaScript

#!/usr/bin/env node
import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const here = dirname(fileURLToPath(import.meta.url));
const platformRoot = resolve(here, "../..");
const artifactRoot = resolve(
process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(here, "../deploy-artifacts"),
);
const [transitionId = "20260719-006", ...extra] = process.argv.slice(2);
if (extra.length || !/^\d{8}-[0-9]{3}$/.test(transitionId)) {
throw new Error("usage: build-engine-provider-security-catalog-artifact.mjs [YYYYMMDD-NNN]");
}
const id = `engine-provider-security-catalog-${transitionId}`;
const target = join(artifactRoot, `nodedc-${id}.tgz`);
const file = "nodedc-source/server/assets/provider-packages/v1/catalog.json";
const expectedSha256 = "992159fc457ec76ce1f45aad337604c8a72b29252d44fbccda515f0fd6ea6428";
const catalogBytes = Buffer.from(`${JSON.stringify({
schemaVersion: "nodedc.engine.provider-security-catalog/v1",
packages: [{
id: "gelios.provider.v3",
version: "3.0.0",
providerId: "gelios",
providerCredential: {
authModeId: "gelios.rest-rotating-bearer.v3",
credentialType: "httpBearerAuth",
},
capabilities: [{
id: "gelios.units.current.read",
classification: "read",
status: "implemented",
request: {
method: "GET",
url: "https://api.geliospro.com/api/v1/units",
},
dataProductIds: ["fleet.positions.current.v2"],
}],
publisher: {
nodeType: "n8n-nodes-ndc.ndcDataProductPublish",
credentialType: "ndcDataProductWriterApi",
},
}],
}, null, 2)}\n`, "utf8");
await assertFresh(target);
if (sha(catalogBytes) !== expectedSha256) throw new Error(`pinned_catalog_sha256_mismatch:${file}`);
const stage = await mkdtemp(join(tmpdir(), "nodedc-engine-provider-security-catalog-"));
const payload = join(stage, "payload");
try {
await mkdir(dirname(join(payload, file)), { recursive: true });
await writeFile(join(payload, file), catalogBytes, { flag: "wx", mode: 0o644 });
await writeFile(join(stage, "manifest.env"), `id=${id}\ncomponent=engine\ntype=app-overlay\n`, "utf8");
await writeFile(join(stage, "files.txt"), `${file}\n`, "utf8");
await mkdir(artifactRoot, { recursive: true });
run("python3", ["-c", canonicalTarScript(), target, stage]);
console.log(JSON.stringify({
ok: true,
id,
artifact: target,
artifactSha256: sha(await readFile(target)),
services: ["nodedc-backend"],
providerPackage: "gelios.provider.v3",
providerCredential: "httpBearerAuth",
endpoint: "https://api.geliospro.com/api/v1/units",
dataProductId: "fleet.positions.current.v2",
preserved: ["n8n", "L1 graph", "Engine UI", "databases", "provider credential values"],
files: [file],
}, null, 2));
} finally {
await rm(stage, { recursive: true, force: true });
}
async function assertFresh(path) {
try {
await lstat(path);
} catch (error) {
if (error?.code === "ENOENT") return;
throw error;
}
throw new Error("artifact_already_exists");
}
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");
}
function sha(value) {
return createHash("sha256").update(value).digest("hex");
}
function run(command, args) {
const result = spawnSync(command, args, {
encoding: "utf8",
maxBuffer: 128 * 1024 * 1024,
stdio: ["ignore", "pipe", "pipe"],
});
if (result.status !== 0) throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
return result;
}