| 1 | #!/usr/bin/env node |
| 2 | // The GitHub Release asset set, checked as a whole. |
| 3 | // |
| 4 | // release.yml uploads into a DRAFT release, then runs this with |
| 5 | // --draft --asset-dir artifacts --publish |
| 6 | // which requires the draft to carry exactly the authoritative inventory |
| 7 | // (allReleaseAssetNames), every asset fully uploaded with the local byte |
| 8 | // size and SHA-256 digest, and only then flips draft -> published. A rerun |
| 9 | // can reuse draft assets only when their bytes match the verified local set. |
| 10 | // The whole set becomes public |
| 11 | // at once; an upload that dies halfway leaves a draft nobody can install from, |
| 12 | // not a public partial release. |
| 13 | // |
| 14 | // release-republish.yml runs it with --manifest: an older tag may predate the |
| 15 | // current inventory, so there the release's own checksum manifest is the |
| 16 | // inventory, and the release must carry exactly the manifest's assets, each |
| 17 | // with the SHA-256 digest the manifest lists, plus the manifest itself before |
| 18 | // any channel is derived from it. |
| 19 | // |
| 20 | // Set GH_BIN to choose the GitHub CLI binary (tests use a fake). |
| 21 | |
| 22 | const { execFileSync } = require("node:child_process"); |
| 23 | const crypto = require("node:crypto"); |
| 24 | const fs = require("node:fs"); |
| 25 | const path = require("node:path"); |
| 26 | |
| 27 | const { allReleaseAssetNames, CHECKSUM_MANIFEST, CHECKSUM_SIGNATURE } = require("../../npm/codewhale/scripts/artifacts"); |
| 28 | const compiledHosts = require("../../npm/codewhale/scripts/compiled-hosts"); |
| 29 | const { validateTarget } = require("./ensure-release-assets-absent"); |
| 30 | |
| 31 | function usage() { |
| 32 | return [ |
| 33 | "Usage:", |
| 34 | " node scripts/release/verify-release-inventory.js [--draft] [--asset-dir DIR] [--publish] OWNER/REPO vX.Y.Z", |
| 35 | " node scripts/release/verify-release-inventory.js --manifest OWNER/REPO vX.Y.Z", |
| 36 | ].join("\n"); |
| 37 | } |
| 38 | |
| 39 | function ghRunner(ghBin = process.env.GH_BIN || "gh", exec = execFileSync) { |
| 40 | return (args) => { |
| 41 | try { |
| 42 | return exec(ghBin, args, { |
| 43 | encoding: "utf8", |
| 44 | maxBuffer: 20 * 1024 * 1024, |
| 45 | stdio: ["ignore", "pipe", "pipe"], |
| 46 | }); |
| 47 | } catch (error) { |
| 48 | const detail = String(error && error.stderr ? error.stderr : error && error.message).trim(); |
| 49 | throw new Error(`gh ${args.slice(0, 2).join(" ")} failed${detail ? `: ${detail}` : ""}`); |
| 50 | } |
| 51 | }; |
| 52 | } |
| 53 | |
| 54 | /** The draft (listed, since drafts are invisible on the tags endpoint) or the published release. */ |
| 55 | function findRelease(repo, tag, { draft }, gh) { |
| 56 | validateTarget(repo, tag); |
| 57 | if (!draft) { |
| 58 | const release = JSON.parse(gh(["api", `repos/${repo}/releases/tags/${encodeURIComponent(tag)}`])); |
| 59 | if (!release || release.draft) throw new Error(`GitHub Release ${tag} is not published`); |
| 60 | return release; |
| 61 | } |
| 62 | const pages = JSON.parse(gh(["api", `repos/${repo}/releases?per_page=100`, "--paginate", "--slurp"])); |
| 63 | if (!Array.isArray(pages) || pages.some((page) => !Array.isArray(page))) { |
| 64 | throw new Error("GitHub did not return a paginated release list"); |
| 65 | } |
| 66 | const listed = pages.flat(); |
| 67 | const drafts = listed.filter((release) => release && release.draft === true && release.tag_name === tag); |
| 68 | if (drafts.length !== 1) { |
| 69 | throw new Error( |
| 70 | `Expected exactly one draft release for ${tag}; found ${drafts.length}. ` + |
| 71 | "A stale draft from an earlier failed run must be reviewed and deleted by a maintainer before rerunning.", |
| 72 | ); |
| 73 | } |
| 74 | return drafts[0]; |
| 75 | } |
| 76 | |
| 77 | /** Exact names, each fully uploaded, and matching local size and SHA-256. */ |
| 78 | function assertInventory(release, tag, expectedNames, assetDir, manifestDigests = null) { |
| 79 | if (!release || !Array.isArray(release.assets)) { |
| 80 | throw new Error(`GitHub Release ${tag} did not provide an asset inventory`); |
| 81 | } |
| 82 | const byName = new Map(); |
| 83 | for (const asset of release.assets) { |
| 84 | if (!asset || typeof asset.name !== "string" || byName.has(asset.name)) { |
| 85 | throw new Error(`GitHub Release ${tag} has a malformed or duplicate asset entry`); |
| 86 | } |
| 87 | byName.set(asset.name, asset); |
| 88 | } |
| 89 | const expected = new Set(expectedNames); |
| 90 | const missing = expectedNames.filter((name) => !byName.has(name)); |
| 91 | const unexpected = [...byName.keys()].filter((name) => !expected.has(name)); |
| 92 | if (missing.length > 0 || unexpected.length > 0) { |
| 93 | throw new Error( |
| 94 | `GitHub Release ${tag} does not carry the exact asset inventory` + |
| 95 | `${missing.length > 0 ? `; missing: ${missing.join(", ")}` : ""}` + |
| 96 | `${unexpected.length > 0 ? `; unexpected: ${unexpected.join(", ")}` : ""}`, |
| 97 | ); |
| 98 | } |
| 99 | for (const name of expectedNames) { |
| 100 | const asset = byName.get(name); |
| 101 | if (asset.state !== "uploaded" || !(asset.size > 0)) { |
| 102 | throw new Error(`GitHub Release ${tag} asset ${name} is not fully uploaded (state ${asset.state}, ${asset.size} bytes)`); |
| 103 | } |
| 104 | if (manifestDigests && manifestDigests.has(name) && asset.digest !== manifestDigests.get(name)) { |
| 105 | throw new Error(`GitHub Release ${tag} asset ${name} has a missing or mismatched SHA-256 digest against ${CHECKSUM_MANIFEST}; refusing a stale manifest`); |
| 106 | } |
| 107 | if (assetDir) { |
| 108 | const local = fs.statSync(path.join(assetDir, name)).size; |
| 109 | if (asset.size !== local) { |
| 110 | throw new Error(`GitHub Release ${tag} asset ${name} has ${asset.size} bytes; the verified local asset has ${local}`); |
| 111 | } |
| 112 | const digest = `sha256:${crypto.hash("sha256", fs.readFileSync(path.join(assetDir, name)))}`; |
| 113 | if (asset.digest !== digest) { |
| 114 | throw new Error(`GitHub Release ${tag} asset ${name} has a missing or mismatched SHA-256 digest; refusing stale draft bytes`); |
| 115 | } |
| 116 | } |
| 117 | } |
| 118 | return expectedNames.length; |
| 119 | } |
| 120 | |
| 121 | /** The SHA-256 digest the release's own checksum manifest lists for each asset, by name. */ |
| 122 | function manifestInventory(repo, tag, gh) { |
| 123 | const text = gh(["release", "download", tag, "--repo", repo, "--pattern", CHECKSUM_MANIFEST, "--output", "-"]); |
| 124 | const digests = new Map(); |
| 125 | for (const line of String(text).split(/\r?\n/)) { |
| 126 | const trimmed = line.trim(); |
| 127 | if (!trimmed) continue; |
| 128 | const match = trimmed.match(/^([a-fA-F0-9]{64})\s+\*?(.+)$/); |
| 129 | if (!match) throw new Error(`${CHECKSUM_MANIFEST} contains an invalid row: ${trimmed}`); |
| 130 | if (digests.has(match[2])) throw new Error(`${CHECKSUM_MANIFEST} lists ${match[2]} twice`); |
| 131 | digests.set(match[2], `sha256:${match[1].toLowerCase()}`); |
| 132 | } |
| 133 | if (digests.size === 0) throw new Error(`${CHECKSUM_MANIFEST} for ${tag} lists no assets`); |
| 134 | return digests; |
| 135 | } |
| 136 | |
| 137 | function run(argv, gh = ghRunner(), log = console.log) { |
| 138 | const flags = { draft: false, publish: false, manifest: false, assetDir: null }; |
| 139 | const positional = []; |
| 140 | for (let i = 0; i < argv.length; i++) { |
| 141 | const arg = argv[i]; |
| 142 | if (arg === "--draft") flags.draft = true; |
| 143 | else if (arg === "--publish") flags.publish = true; |
| 144 | else if (arg === "--manifest") flags.manifest = true; |
| 145 | else if (arg === "--asset-dir") flags.assetDir = argv[++i]; |
| 146 | else positional.push(arg); |
| 147 | } |
| 148 | if (positional.length !== 2 || (flags.publish && (!flags.draft || !flags.assetDir)) || (flags.manifest && (flags.draft || flags.assetDir))) { |
| 149 | throw new Error(usage()); |
| 150 | } |
| 151 | const [repo, tag] = positional; |
| 152 | const release = findRelease(repo, tag, { draft: flags.draft }, gh); |
| 153 | let catalog; |
| 154 | const hasRemoteAsset = (name) => Array.isArray(release.assets) && release.assets.some((asset) => asset.name === name); |
| 155 | const hasCatalog = !flags.manifest && (flags.assetDir |
| 156 | ? fs.existsSync(path.join(flags.assetDir, compiledHosts.HOST_CATALOG)) |
| 157 | : hasRemoteAsset(compiledHosts.HOST_CATALOG)); |
| 158 | if (hasCatalog) { |
| 159 | if (!flags.assetDir) throw new Error("compiled-host release verification requires --asset-dir; verify exact local qualification/catalog bytes before publication"); |
| 160 | catalog = compiledHosts.parseCatalog(fs.readFileSync(path.join(flags.assetDir, compiledHosts.HOST_CATALOG), "utf8"), tag.replace(/^v/, "")); |
| 161 | compiledHosts.verifyDirectory(flags.assetDir, catalog); |
| 162 | } |
| 163 | const manifestDigests = flags.manifest ? manifestInventory(repo, tag, gh) : null; |
| 164 | const expected = manifestDigests ? [...manifestDigests.keys(), CHECKSUM_MANIFEST] : allReleaseAssetNames(catalog); |
| 165 | const expectSignature = flags.assetDir |
| 166 | ? fs.existsSync(path.join(flags.assetDir, CHECKSUM_SIGNATURE)) |
| 167 | : hasRemoteAsset(CHECKSUM_SIGNATURE); |
| 168 | if (expectSignature) expected.push(CHECKSUM_SIGNATURE); |
| 169 | const count = assertInventory(release, tag, expected, flags.assetDir, manifestDigests); |
| 170 | log(`Verified ${count} assets on the ${flags.draft ? "draft" : "published"} release ${tag}`); |
| 171 | if (!flags.publish) return; |
| 172 | gh(["api", "-X", "PATCH", `repos/${repo}/releases/${release.id}`, "-F", "draft=false"]); |
| 173 | const published = findRelease(repo, tag, { draft: false }, gh); |
| 174 | if (published.id !== release.id) { |
| 175 | throw new Error(`Published release for ${tag} is ${published.id}, not the verified draft ${release.id}`); |
| 176 | } |
| 177 | assertInventory(published, tag, expected, flags.assetDir); |
| 178 | log(`Published ${tag} with its ${count} verified assets`); |
| 179 | } |
| 180 | |
| 181 | if (require.main === module) { |
| 182 | try { |
| 183 | run(process.argv.slice(2)); |
| 184 | } catch (error) { |
| 185 | console.error(error.message); |
| 186 | process.exit(1); |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | module.exports = { assertInventory, findRelease, manifestInventory, run }; |
| 191 |