返回 CodeWhale
verify-release-assets.js
根目录 / npm / codewhale / scripts / verify-release-assets.js
1 const https = require("https");
2 const http = require("http");
3 const {
4 allReleaseAssetNames,
5 BUNDLE_ASSET_NAMES,
6 BUNDLE_CHECKSUM_MANIFEST,
7 checksummedReleaseAssetNames,
8 checksumManifestUrl,
9 CNB_BINARY_ASSET_NAMES,
10 CNB_RELEASE_ASSET_NAMES,
11 redactUrl,
12 releaseAssetUrl,
13 usesCnbMirror,
14 validateReleaseUrl,
15 } = require("./artifacts");
16
17 const pkg = require("../package.json");
18
19 function resolveBinaryVersion() {
20 const configuredVersion =
21 process.env.CODEWHALE_VERSION ||
22 process.env.DEEPSEEK_TUI_VERSION ||
23 process.env.DEEPSEEK_VERSION ||
24 pkg.codewhaleBinaryVersion || pkg.deepseekBinaryVersion ||
25 pkg.version;
26 return String(configuredVersion).trim();
27 }
28
29 function resolveRepo() {
30 return (
31 process.env.CODEWHALE_GITHUB_REPO ||
32 process.env.DEEPSEEK_TUI_GITHUB_REPO ||
33 process.env.DEEPSEEK_GITHUB_REPO ||
34 "codewhale-hq/CodeWhale"
35 );
36 }
37
38 function hasReleaseBaseOverride() {
39 return Boolean(
40 process.env.CODEWHALE_RELEASE_BASE_URL ||
41 process.env.DEEPSEEK_TUI_RELEASE_BASE_URL ||
42 process.env.DEEPSEEK_RELEASE_BASE_URL ||
43 process.env.CODEWHALE_USE_CNB_MIRROR,
44 );
45 }
46
47 function packageVersionMatchesBinaryVersion(version) {
48 return String(pkg.version).trim() === version;
49 }
50
51 function assertPackageVersionMatchesBinaryVersion(version) {
52 if (packageVersionMatchesBinaryVersion(version)) {
53 return;
54 }
55 if (process.env.CODEWHALE_ALLOW_NPM_BINARY_MISMATCH === "1") {
56 console.log(
57 `npm package version ${pkg.version} points at binary release ${version} (allowed packaging-only mismatch).`,
58 );
59 return;
60 }
61 throw new Error(
62 `npm package version ${pkg.version} does not match codewhaleBinaryVersion ${version}. ` +
63 "Set CODEWHALE_ALLOW_NPM_BINARY_MISMATCH=1 only for an intentional packaging-only npm release.",
64 );
65 }
66
67 // Every request is bounded: `idleMs` covers connecting and any stall (it is
68 // the socket timeout, which starts before the socket connects), `totalMs` is a
69 // hard ceiling for one request including a body that keeps trickling, and a
70 // body larger than `maxBodyBytes` is cut off. Redirects are limited to ten, so
71 // a chain is bounded too. Tests shrink these through the exported object.
72 const limits = {
73 idleMs: 30_000,
74 totalMs: 120_000,
75 maxBodyBytes: 8 * 1024 * 1024,
76 };
77
78 // Reject first, then tear the request down: an error passed to `destroy()` can
79 // surface on an emitter nobody listens to once a response has started.
80 function armTotalTimeout(req, url, reject) {
81 const safeUrl = redactUrl(url);
82 const fail = (error) => {
83 reject(error);
84 req.destroy();
85 };
86 const timer = setTimeout(
87 () => fail(new Error(`Request exceeded ${limits.totalMs} ms: ${safeUrl}`)),
88 limits.totalMs,
89 );
90 timer.unref();
91 const clear = () => clearTimeout(timer);
92 req.on("close", clear);
93 req.on("error", clear);
94 req.on("timeout", () =>
95 fail(new Error(`Request timed out after ${limits.idleMs} ms without data: ${safeUrl}`)),
96 );
97 return { clear, fail };
98 }
99
100 function requestRelease(url, options = {}, redirects = 0) {
101 const method = options.method || "GET";
102 const readBody = Boolean(options.readBody);
103 const maxRedirects = options.maxRedirects == null ? 10 : options.maxRedirects;
104 const safeUrl = redactUrl(url);
105 if (redirects > maxRedirects) {
106 return Promise.reject(new Error(`Too many redirects while requesting ${safeUrl}`));
107 }
108 let parsedUrl;
109 try {
110 parsedUrl = validateReleaseUrl(url);
111 } catch (err) {
112 return Promise.reject(err);
113 }
114 const client = parsedUrl.protocol === "https:" ? https : http;
115 const headers = {
116 ...(options.headers || {}),
117 "User-Agent": "codewhale-npm-release-check",
118 };
119 if (options.attachGitHubToken) {
120 const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
121 if (token && parsedUrl.origin === "https://api.github.com") {
122 headers.Authorization = `Bearer ${token}`;
123 }
124 }
125 return new Promise((resolve, reject) => {
126 const onResponse = (res) => {
127 const status = res.statusCode || 0;
128 const location = res.headers && res.headers.location;
129 if (status >= 300 && status < 400 && location) {
130 res.resume();
131 clear();
132 let next;
133 try {
134 next = new URL(location, url).toString();
135 } catch (err) {
136 reject(new Error(`Invalid redirect location from ${safeUrl}: ${err.message}`));
137 return;
138 }
139 resolve(requestRelease(next, options, redirects + 1));
140 return;
141 }
142 if (!readBody) {
143 res.resume();
144 clear();
145 resolve({ status, url: safeUrl, body: "" });
146 return;
147 }
148 const chunks = [];
149 let size = 0;
150 res.setEncoding("utf8");
151 res.on("error", reject);
152 res.on("data", (chunk) => {
153 size += Buffer.byteLength(chunk);
154 if (size > limits.maxBodyBytes) {
155 guard.fail(new Error(`Response exceeds ${limits.maxBodyBytes} bytes: ${safeUrl}`));
156 return;
157 }
158 chunks.push(chunk);
159 });
160 res.on("end", () => resolve({ status, url: safeUrl, body: chunks.join("") }));
161 };
162 const req =
163 method === "GET"
164 ? client.get(url, { headers, timeout: limits.idleMs }, onResponse)
165 : client.request(url, { method, headers, timeout: limits.idleMs }, onResponse);
166 const guard = armTotalTimeout(req, url, reject);
167 const clear = guard.clear;
168 req.on("error", reject);
169 if (method !== "GET") {
170 req.end();
171 }
172 });
173 }
174
175 async function requestStatus(url, method = "HEAD", redirects = 0) {
176 const result = await requestRelease(url, { method, readBody: false }, redirects);
177 return result.status;
178 }
179
180 async function verifyAsset(url, label) {
181 let status = await requestStatus(url, "HEAD");
182 if (status === 403 || status === 405) {
183 status = await requestStatus(url, "GET");
184 }
185 if (status < 200 || status >= 400) {
186 throw new Error(`${label} returned HTTP ${status} (${redactUrl(url)})`);
187 }
188 }
189
190 async function downloadText(url, redirects = 0) {
191 const result = await requestRelease(url, { method: "GET", readBody: true }, redirects);
192 if (result.status !== 200) {
193 throw new Error(`Request failed with status ${result.status}: ${result.url}`);
194 }
195 return result.body;
196 }
197
198 async function downloadJson(url, redirects = 0) {
199 const result = await requestRelease(
200 url,
201 {
202 method: "GET",
203 readBody: true,
204 attachGitHubToken: true,
205 headers: {
206 Accept: "application/vnd.github+json",
207 "X-GitHub-Api-Version": "2022-11-28",
208 },
209 },
210 redirects,
211 );
212 let parsed;
213 try {
214 parsed = result.body ? JSON.parse(result.body) : {};
215 } catch (error) {
216 throw new Error(`Invalid JSON from ${result.url}: ${error.message}`);
217 }
218 if (result.status < 200 || result.status >= 300) {
219 const message = parsed.message ? `: ${parsed.message}` : "";
220 throw new Error(`GitHub API request failed with status ${result.status}${message} (${result.url})`);
221 }
222 return parsed;
223 }
224
225 function githubApiUrl(repo, path) {
226 return `https://api.github.com/repos/${repo}${path}`;
227 }
228
229 async function githubApi(repo, path) {
230 return downloadJson(githubApiUrl(repo, path));
231 }
232
233 async function resolveTagCommitSha(repo, tag) {
234 const ref = await githubApi(repo, `/git/ref/tags/${encodeURIComponent(tag)}`);
235 if (!ref.object || !ref.object.sha || !ref.object.type) {
236 throw new Error(`GitHub tag ref ${tag} did not include an object SHA`);
237 }
238 if (ref.object.type === "commit") {
239 return ref.object.sha;
240 }
241 if (ref.object.type !== "tag") {
242 throw new Error(`GitHub tag ref ${tag} points at ${ref.object.type}, not a commit or annotated tag`);
243 }
244 const tagObject = await githubApi(repo, `/git/tags/${ref.object.sha}`);
245 if (!tagObject.object || tagObject.object.type !== "commit" || !tagObject.object.sha) {
246 throw new Error(`Annotated tag ${tag} did not peel to a commit SHA`);
247 }
248 return tagObject.object.sha;
249 }
250
251 async function findReleaseWorkflowRun(repo, tag, tagSha, api = githubApi) {
252 const runs = await api(repo, "/actions/workflows/release.yml/runs?per_page=100");
253 const candidates = (runs.workflow_runs || [])
254 .filter((run) => run.head_sha === tagSha)
255 .filter((run) => run.event === "push" || run.event === "workflow_dispatch")
256 .sort((a, b) => String(b.updated_at).localeCompare(String(a.updated_at)));
257
258 const orderedCandidates = [
259 ...candidates.filter((run) => run.head_branch === tag),
260 ...candidates.filter((run) => run.head_branch !== tag),
261 ];
262 for (const candidate of orderedCandidates) {
263 const runId = candidate.database_id || candidate.id;
264 if (!runId) {
265 continue;
266 }
267 const jobs = await api(repo, `/actions/runs/${runId}/jobs?per_page=100`);
268 const releaseJob = (jobs.jobs || []).find(
269 (job) => job.name === "release" && job.conclusion === "success",
270 );
271 if (releaseJob) {
272 // #5429: pin asset freshness to the successful release job's own
273 // started_at, not the run-level run_started_at. A job-level rerun
274 // (`gh run rerun --failed`) bumps run_started_at past the asset upload
275 // timestamps even though this release job produced those assets.
276 return { ...candidate, release_job_started_at: releaseJob.started_at || null };
277 }
278 }
279
280 if (orderedCandidates.length === 0) {
281 throw new Error(
282 `No release.yml workflow run found for ${tag} at ${tagSha}. ` +
283 "Rerun the Release workflow before publishing npm, or increase the verifier's last-100-runs search window.",
284 );
285 }
286 throw new Error(
287 `No successful asset-publishing job found in release.yml workflow runs for ${tag} at ${tagSha}. ` +
288 "Repair the Release workflow before publishing npm.",
289 );
290 }
291
292 function parseGitHubTime(value, label) {
293 const timestamp = Date.parse(value);
294 if (!Number.isFinite(timestamp)) {
295 throw new Error(`GitHub ${label} timestamp is invalid: ${value}`);
296 }
297 return timestamp;
298 }
299
300 function assertReleaseAssetsFresh(release, expectedAssets, run) {
301 const assetsByName = new Map((release.assets || []).map((asset) => [asset.name, asset]));
302 const missing = expectedAssets.filter((asset) => !assetsByName.has(asset));
303 if (missing.length > 0) {
304 throw new Error(`GitHub Release is missing required release asset(s): ${missing.join(", ")}`);
305 }
306
307 // #5429: compare against the successful release job's started_at when the
308 // run record carries it; fall back to the run-level timestamp only when a
309 // job baseline is unavailable.
310 const baseline = run.release_job_started_at || run.run_started_at || run.created_at;
311 const baselineLabel = run.release_job_started_at ? "release job start" : "workflow run start";
312 const freshnessBaseline = parseGitHubTime(baseline, baselineLabel);
313 const stale = [];
314 for (const expected of expectedAssets) {
315 const asset = assetsByName.get(expected);
316 if (asset.state && asset.state !== "uploaded") {
317 stale.push(`${expected} has state ${asset.state}`);
318 continue;
319 }
320 const updatedAt = parseGitHubTime(asset.updated_at || asset.created_at, `${expected} update`);
321 if (updatedAt < freshnessBaseline) {
322 stale.push(`${expected} updated at ${asset.updated_at || asset.created_at}`);
323 }
324 }
325
326 if (stale.length > 0) {
327 throw new Error(
328 `GitHub Release asset set is stale for workflow run ${run.database_id || run.id}: ${stale.join("; ")}`,
329 );
330 }
331 }
332
333 async function verifyGitHubReleaseFreshness(repo, version, expectedAssets) {
334 const tag = `v${version}`;
335 const tagSha = await resolveTagCommitSha(repo, tag);
336 const release = await githubApi(repo, `/releases/tags/${encodeURIComponent(tag)}`);
337 const run = await findReleaseWorkflowRun(repo, tag, tagSha);
338 assertReleaseAssetsFresh(release, expectedAssets, run);
339 console.log(
340 `GitHub release asset freshness OK: ${expectedAssets.length} release assets for ${tag} were produced by run ${run.database_id || run.id} at ${tagSha.slice(0, 12)}.`,
341 );
342 }
343
344 function parseChecksumManifest(text) {
345 const checksums = new Map();
346 for (const line of text.split(/\r?\n/)) {
347 const trimmed = line.trim();
348 if (!trimmed) {
349 continue;
350 }
351 const match = trimmed.match(/^([a-fA-F0-9]{64})\s+\*?(.+)$/);
352 if (!match) {
353 throw new Error(`Invalid checksum manifest line: ${trimmed}`);
354 }
355 checksums.set(match[2], match[1].toLowerCase());
356 }
357 return checksums;
358 }
359
360 function assertChecksumManifestIncludes(checksums, expectedAssets, label) {
361 const missing = expectedAssets.filter((asset) => !checksums.has(asset));
362 if (missing.length > 0) {
363 throw new Error(`${label} is missing ${missing.join(", ")}`);
364 }
365 }
366
367 const compiledHosts = require("./compiled-hosts");
368
369 async function run() {
370 const version = resolveBinaryVersion();
371 const repo = resolveRepo();
372 const cnbMirror = usesCnbMirror();
373 const checksums = parseChecksumManifest(await downloadText(checksumManifestUrl(version, repo)));
374 let catalog;
375 if (checksums.has(compiledHosts.HOST_CATALOG)) {
376 const text = await downloadText(releaseAssetUrl(compiledHosts.HOST_CATALOG, version, repo));
377 compiledHosts.verifyBytes(Buffer.from(text), checksums.get(compiledHosts.HOST_CATALOG), compiledHosts.HOST_CATALOG);
378 catalog = compiledHosts.parseCatalog(text, version);
379 }
380 if (compiledHosts.requested() && !catalog) throw new Error("compiled host requested but this source has no qualified catalog");
381 const assets = cnbMirror ? [...CNB_RELEASE_ASSET_NAMES, ...compiledHosts.assets(catalog)] : allReleaseAssetNames(catalog);
382
383 assertPackageVersionMatchesBinaryVersion(version);
384
385 console.log(`Verifying ${assets.length} release assets for ${repo}@v${version}...`);
386 if (hasReleaseBaseOverride()) {
387 console.log("Skipping GitHub workflow freshness check because a release asset mirror/base URL override is set.");
388 } else {
389 await verifyGitHubReleaseFreshness(repo, version, assets);
390 }
391 for (const asset of assets) {
392 const url = releaseAssetUrl(asset, version, repo);
393 await verifyAsset(url, asset);
394 console.log(` ok ${asset}`);
395 }
396 assertChecksumManifestIncludes(
397 checksums,
398 cnbMirror ? [...CNB_BINARY_ASSET_NAMES, ...compiledHosts.assets(catalog)] : checksummedReleaseAssetNames(catalog),
399 "Canonical checksum manifest",
400 );
401 if (!cnbMirror) {
402 const bundleChecksums = parseChecksumManifest(
403 await downloadText(releaseAssetUrl(BUNDLE_CHECKSUM_MANIFEST, version, repo)),
404 );
405 assertChecksumManifestIncludes(
406 bundleChecksums,
407 BUNDLE_ASSET_NAMES,
408 "Bundle checksum manifest",
409 );
410 }
411 console.log("Release assets verified.");
412 }
413
414 if (require.main === module) {
415 run().catch((error) => {
416 console.error("Release asset verification failed:", error.message);
417 process.exit(1);
418 });
419 }
420
421 module.exports = {
422 downloadJson,
423 downloadText,
424 limits,
425 requestStatus,
426 assertChecksumManifestIncludes,
427 assertPackageVersionMatchesBinaryVersion,
428 assertReleaseAssetsFresh,
429 findReleaseWorkflowRun,
430 hasReleaseBaseOverride,
431 parseChecksumManifest,
432 };
433
433 lines JAVASCRIPT