Files
persionalBrand/scripts/deploy/check-package.mjs
T

64 lines
2.5 KiB
JavaScript

import { createHash } from "node:crypto";
import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
async function listFiles(directory, prefix = "") {
const files = [];
for (const entry of await readdir(directory, { withFileTypes: true })) {
const relative = path.posix.join(prefix, entry.name);
if (entry.isDirectory())
files.push(...(await listFiles(path.join(directory, entry.name), relative)));
else if (entry.isFile()) files.push(relative);
else throw new Error("Unsupported file: " + relative);
}
return files.sort();
}
export async function checkPackage(directory) {
const manifest = JSON.parse(await readFile(path.join(directory, "manifest.json"), "utf8"));
if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,100}$/.test(manifest.version))
throw new Error("Invalid release version");
const actual = await listFiles(directory);
const expected = manifest.files
.map((file) => file.path)
.concat("manifest.json")
.sort();
if (JSON.stringify(actual) !== JSON.stringify(expected))
throw new Error("Release file list mismatch");
const packagePath = path.join(directory, "package.json");
let releasePackage;
try {
releasePackage = JSON.parse(await readFile(packagePath, "utf8"));
} catch (error) {
if (error.code !== "ENOENT") throw error;
}
const patchedDependencies = releasePackage?.pnpm?.patchedDependencies ?? {};
for (const [dependency, patchPath] of Object.entries(patchedDependencies)) {
if (
typeof patchPath !== "string" ||
path.isAbsolute(patchPath) ||
patchPath.split("/").includes("..")
)
throw new Error("Invalid patched dependency path: " + dependency);
if (!actual.includes(patchPath))
throw new Error(`Release is missing patched dependency ${dependency}: ${patchPath}`);
}
for (const file of manifest.files) {
if (file.path.startsWith("/") || file.path.split("/").includes(".."))
throw new Error("Unsafe release path");
const content = await readFile(path.join(directory, file.path));
const digest = createHash("sha256").update(content).digest("hex");
if (content.byteLength !== file.bytes || digest !== file.sha256)
throw new Error("Release checksum mismatch: " + file.path);
}
return manifest;
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const manifest = await checkPackage(path.resolve(process.argv[2] ?? "."));
console.log("release verified: " + manifest.version + " (" + manifest.files.length + " files)");
}