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

124 lines
5.1 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);
}
const workspacePackages = new Map();
for (const relative of actual.filter(
(file) => file === "package.json" || file.endsWith("/package.json"),
)) {
const workspacePackage = JSON.parse(await readFile(path.join(directory, relative), "utf8"));
if (typeof workspacePackage.name !== "string" || !workspacePackage.name)
throw new Error("Workspace package has no name: " + relative);
workspacePackages.set(workspacePackage.name, {
directory: path.posix.dirname(relative),
manifest: workspacePackage,
});
}
for (const [name, workspacePackage] of workspacePackages) {
for (const section of ["dependencies", "devDependencies", "optionalDependencies"]) {
for (const [dependency, range] of Object.entries(workspacePackage.manifest[section] ?? {})) {
if (typeof range !== "string" || !range.startsWith("workspace:")) continue;
const target = workspacePackages.get(dependency);
if (!target) {
throw new Error(
`Release is missing workspace dependency ${dependency} required by ${name}`,
);
}
if (target.directory === ".") {
throw new Error(`Workspace dependency ${dependency} cannot be the release root package`);
}
}
}
}
if (actual.includes("template-catalog.json")) {
const catalog = JSON.parse(
await readFile(path.join(directory, "template-catalog.json"), "utf8"),
);
if (catalog.formatVersion !== "1" || !Array.isArray(catalog.packages))
throw new Error("Invalid template catalog");
const keys = new Set();
for (const entry of catalog.packages) {
if (
typeof entry.packageKey !== "string" ||
typeof entry.version !== "string" ||
typeof entry.archiveChecksum !== "string" ||
typeof entry.archivePath !== "string"
)
throw new Error("Invalid template catalog entry");
if (keys.has(entry.packageKey))
throw new Error("Duplicate template package in catalog: " + entry.packageKey);
keys.add(entry.packageKey);
if (
path.isAbsolute(entry.archivePath) ||
entry.archivePath.split("/").includes("..") ||
!actual.includes(entry.archivePath)
)
throw new Error("Template archive is missing from release: " + entry.packageKey);
const digest = createHash("sha256")
.update(await readFile(path.join(directory, entry.archivePath)))
.digest("hex");
if (digest !== entry.archiveChecksum)
throw new Error("Template archive checksum mismatch: " + entry.packageKey);
}
}
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)");
}