import { readFile, readdir, stat } from "node:fs/promises"; import { createHash } from "node:crypto"; import { dirname, join, resolve } from "node:path"; const root = resolve(new URL("..", import.meta.url).pathname.replace(/^\/(.:)/, "$1")); const manifest = JSON.parse(await readFile(join(root, "PUBLIC_SOURCE_MANIFEST.json"), "utf8")); if (manifest.schemaVersion !== 1 || !/^[0-9a-f]{40}$/.test(manifest.sourceRevision) || !Array.isArray(manifest.files)) throw new Error("The public source manifest is malformed."); const expected = new Map(manifest.files.map(entry => [entry.path, entry])); if (expected.size !== manifest.files.length || !expected.has("LICENSE")) throw new Error("The public source manifest has duplicate entries or no LICENSE."); async function walk(directory, prefix = "") { const found = []; for (const entry of await readdir(directory, { withFileTypes: true })) { if (!prefix && entry.name === ".git") continue; const path = prefix ? `${prefix}/${entry.name}` : entry.name; if (entry.isDirectory()) found.push(...await walk(join(directory, entry.name), path)); else if (entry.isFile() && path !== "PUBLIC_SOURCE_MANIFEST.json") found.push(path); else if (!entry.isFile()) throw new Error(`Irregular public entry: ${path}`); } return found; } const actual = (await walk(root)).sort(); if (actual.length !== expected.size || actual.some(path => !expected.has(path))) throw new Error("Files outside the reviewed public manifest are present."); for (const path of actual) { const data = await readFile(join(root, path)); const entry = expected.get(path); if ((await stat(join(root, path))).size !== entry.bytes || createHash("sha256").update(data).digest("hex") !== entry.sha256) throw new Error(`Public source integrity check failed: ${path}`); } console.log(`Validated ${actual.length} public files from canonical revision ${manifest.sourceRevision}`);