import { createHash, randomUUID } from "node:crypto"; import { link, open, rm } from "node:fs/promises"; import { setTimeout as delay } from "node:timers/promises"; import { sha256File } from "./verifier-file-sha256.mjs"; const ATTEMPTS = 3; /** A release-host failure that another attempt may not repeat. */ class TransientDownloadError extends Error {} const messageOf = (cause) => cause instanceof Error ? cause.message : String(cause); /** * Place a pinned fixture at `path`, or verify the copy already there. * * Each attempt streams into a fresh partial file and hash. Network errors * (before or during the body), HTTP 429 and HTTP 5xx-or-above are retried with * a short backoff. Any other status, a size or SHA-256 mismatch, and local file * errors fail at once, so a retry can never admit different bytes. * * @param {{ url: string, path: string, sha256: string, bytes?: number, timeoutMs: number }} fixture */ export async function downloadFixture({ url, path, sha256, bytes, timeoutMs }) { try { const digest = await sha256File(path); if (digest !== sha256) throw new Error( `Existing ${path} has a different SHA-256; it was not overwritten`, ); console.log(`Verified existing ${path}: ${digest}`); return; } catch (cause) { if (!(cause instanceof Error && "code" in cause && cause.code === "ENOENT")) throw cause; } for (let attempt = 1; ; attempt += 1) { const temporary = `${path}.${randomUUID()}.partial`; try { const digest = await downloadOnce(url, temporary, bytes, timeoutMs); if (digest !== sha256) throw new Error( `SHA-256 mismatch for ${path}: expected ${sha256}, received ${digest}`, ); await link(temporary, path); console.log(`Downloaded and verified ${path}: ${digest}`); return; } catch (cause) { if (!(cause instanceof TransientDownloadError) || attempt >= ATTEMPTS) throw cause instanceof TransientDownloadError ? new Error(`Download failed: ${url}: ${cause.message}`) : cause; console.error(`Download of ${url} failed (${cause.message}); retrying`); } finally { await rm(temporary, { force: true }); } await delay(attempt * 2_000); } } /** Stream one response into `temporary` and return its SHA-256. */ async function downloadOnce(url, temporary, bytes, timeoutMs) { let response; try { response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) }); } catch (cause) { throw new TransientDownloadError(messageOf(cause)); } if (!response.ok || response.body === null) { await response.body?.cancel(); const failure = `HTTP ${response.status}`; if (response.status === 429 || response.status >= 500) throw new TransientDownloadError(failure); throw new Error(`Download failed: ${url}: ${failure}`); } const chunks = response.body[Symbol.asyncIterator](); const handle = await open(temporary, "wx", 0o600); const hash = createHash("sha256"); let received = 0; try { for (;;) { let step; try { step = await chunks.next(); } catch (cause) { throw new TransientDownloadError(messageOf(cause)); } if (step.done) break; received += step.value.length; if (bytes !== undefined && received > bytes) throw new Error(`Download exceeds the pinned ${bytes} bytes`); hash.update(step.value); await handle.writeFile(step.value); } } finally { // Release the connection; an errored stream rejects here, and the // failure that ended the loop is the one to report. await chunks.return?.().catch(() => {}); await handle.close(); } if (bytes !== undefined && received !== bytes) throw new Error( `Download size mismatch: expected ${bytes}, received ${received}`, ); return hash.digest("hex"); }