// Fetching a runtime plugin's package file from npm, a GitHub release, or a file on disk. Which version // / asset to take is decided by pure functions over the registry's answer, so the choice is testable // without a network; the fetches around them only move bytes. import { createHash } from "node:crypto"; import { constants, open, type FileHandle } from "node:fs/promises"; import { isRecord } from "@mulmoclaude/common"; import { DownloadError, downloadBytes, downloadJson, matchesIntegrity, type FetchFn } from "./download.js"; import type { InstallSource } from "./installSource.js"; export const NPM_REGISTRY = "https://registry.npmjs.org"; export const GITHUB_API = "https://api.github.com"; const ONE_SECOND_MS = 1000; const ONE_MIB = 1024 * 1024; const METADATA_LIMITS = { timeoutMs: 30 * ONE_SECOND_MS, maxBytes: 32 * ONE_MIB }; const PACKAGE_LIMITS = { timeoutMs: 120 * ONE_SECOND_MS, maxBytes: 50 * ONE_MIB }; // GitHub's API refuses a request without a User-Agent; a generic one names no user or host. const USER_AGENT = "mulmo-runtime-plugins"; export interface FetchedPackage { bytes: Buffer; /** The npm version, GitHub tag or file path that was resolved, for the ledger's `source`. */ resolved: string; } export interface NpmRelease { version: string; tarball: string; integrity: string | null; } /** A decision that either holds a value or says why there is none. */ export type Resolved = { ok: true; value: T } | { ok: false; error: string }; const stringOrNull = (value: unknown): string | null => (typeof value === "string" ? value : null); const fail = (error: string): Resolved => ({ ok: false, error }); const isHttpsUrl = (value: string): boolean => value.startsWith("https://"); function resolveNpmVersion(packument: Record, versions: Record, spec: string | null): Resolved { const tags = isRecord(packument["dist-tags"]) ? packument["dist-tags"] : {}; if (spec !== null && Object.hasOwn(versions, spec)) return { ok: true, value: spec }; const tag = spec ?? "latest"; const fromTag = Object.hasOwn(tags, tag) ? stringOrNull(tags[tag]) : null; if (fromTag !== null) return { ok: true, value: fromTag }; return fail(spec === null ? "the package has no latest version" : `no version or dist-tag ${JSON.stringify(spec)}`); } function releaseOf(versions: Record, version: string): Resolved { const entry = Object.hasOwn(versions, version) ? versions[version] : undefined; const dist = isRecord(entry) && isRecord(entry.dist) ? entry.dist : null; const tarball = dist ? stringOrNull(dist.tarball) : null; if (dist === null || tarball === null || !isHttpsUrl(tarball)) return fail(`version ${version} has no https tarball`); return { ok: true, value: { version, tarball, integrity: stringOrNull(dist.integrity) } }; } /** The version a packument resolves `spec` to — exact, a dist-tag, or `latest` when absent. */ export function resolveNpmRelease(packument: unknown, spec: string | null): Resolved { if (!isRecord(packument) || !isRecord(packument.versions)) return fail("the registry did not answer with a package"); const version = resolveNpmVersion(packument, packument.versions, spec); return version.ok ? releaseOf(packument.versions, version.value) : version; } /** Whether the downloaded bytes are the ones the registry published, by its strongest hash. */ export function verifyNpmBytes(bytes: Uint8Array, release: NpmRelease): string | null { if (release.integrity === null) return `the registry publishes no sha512/sha384/sha256 integrity for ${release.version}, so the tarball cannot be checked`; return matchesIntegrity(bytes, release.integrity) ? null : `the tarball does not match the registry's integrity for ${release.version}`; } export interface GithubAsset { tag: string; name: string; /** The browser download URL, for an unauthenticated download. */ downloadUrl: string; /** The API URL of the asset, for a download with a token (private repositories). */ apiUrl: string; /** GitHub's own `sha256:` for the asset, when the API gives one (assets uploaded before GitHub * started recording digests have none). */ digest: string | null; } const assetsOf = (release: Record): Record[] => (Array.isArray(release.assets) ? release.assets.filter(isRecord) : []); /** The release's one `.tgz` asset. None, or several, is refused: guessing which file is the plugin * is exactly what a user should not have to trust. */ export function resolveGithubAsset(release: unknown): Resolved { if (!isRecord(release) || typeof release.tag_name !== "string") return fail("GitHub did not answer with a release"); const assets = assetsOf(release); const tgz = assets.filter((asset) => typeof asset.name === "string" && asset.name.endsWith(".tgz")); const names = assets.map((asset) => String(asset.name)).join(", ") || "none"; if (tgz.length !== 1) return fail(`release ${release.tag_name} has ${tgz.length} .tgz assets (assets: ${names}); exactly one is needed`); const [asset] = tgz; const downloadUrl = stringOrNull(asset?.browser_download_url); const apiUrl = stringOrNull(asset?.url); if (downloadUrl === null || apiUrl === null || !isHttpsUrl(downloadUrl) || !isHttpsUrl(apiUrl)) return fail(`release ${release.tag_name}'s .tgz asset has no https download URL`); return { ok: true, value: { tag: release.tag_name, name: String(asset?.name), downloadUrl, apiUrl, digest: stringOrNull(asset?.digest) } }; } const SHA256_DIGEST = /^sha256:([0-9a-f]{64})$/; /** Whether the bytes are the asset GitHub recorded. An asset with no digest is accepted — older * uploads carry none, and the bytes still came over https from GitHub — but a digest that is present * must be a sha256 and must match. */ export function verifyGithubBytes(bytes: Uint8Array, asset: GithubAsset): string | null { if (asset.digest === null) return null; const expected = SHA256_DIGEST.exec(asset.digest.toLowerCase())?.[1]; if (expected === undefined) return `release ${asset.tag}'s asset has an unrecognised digest ${JSON.stringify(asset.digest)}`; return createHash("sha256").update(bytes).digest("hex") === expected ? null : `the asset does not match GitHub's recorded digest for ${asset.tag}`; } export interface FetchDeps { fetch: FetchFn; /** Sent to GitHub when present: raises the rate limit and reaches private repositories. */ githubToken?: string | undefined; npmRegistry?: string | undefined; githubApi?: string | undefined; } // The metadata a base serves decides which bytes are trusted (npm's integrity, GitHub's asset URL), // and a GitHub token is sent to it, so a base reached over plain http is refused outright. function httpsBase(base: string, what: string): string { if (!isHttpsUrl(base)) throw new DownloadError(`${what} must be an https URL, not ${JSON.stringify(base)}`); return base.endsWith("/") ? base.slice(0, -1) : base; } // A scoped name keeps its `@` and has its `/` encoded, which is the form the registry routes. const packumentUrl = (registry: string, name: string): string => `${registry}/${name.replaceAll("/", "%2f")}`; async function fetchNpm(source: Extract, deps: FetchDeps): Promise { const accept = { accept: "application/vnd.npm.install-v1+json", "user-agent": USER_AGENT }; const packument = await downloadJson( deps.fetch, packumentUrl(httpsBase(deps.npmRegistry ?? NPM_REGISTRY, "the npm registry"), source.name), accept, METADATA_LIMITS, ); const resolved = resolveNpmRelease(packument, source.spec); if (!resolved.ok) throw new DownloadError(`${source.name}: ${resolved.error}`); const release = resolved.value; const bytes = await downloadBytes(deps.fetch, release.tarball, { "user-agent": USER_AGENT }, PACKAGE_LIMITS); const mismatch = verifyNpmBytes(bytes, release); if (mismatch !== null) throw new DownloadError(`${source.name}: ${mismatch}`); return { bytes, resolved: release.version }; } function githubHeaders(deps: FetchDeps, accept: string): Record { const headers: Record = { accept, "user-agent": USER_AGENT }; if (deps.githubToken) headers.authorization = `Bearer ${deps.githubToken}`; return headers; } // The token goes only to the API it was given for: an asset URL in the release's answer that names // another host is refused rather than handed the token, whatever scheme it uses. function assetUrl(asset: GithubAsset, deps: FetchDeps, apiBase: string): string { if (!deps.githubToken) return asset.downloadUrl; if (new URL(asset.apiUrl).origin !== new URL(apiBase).origin) throw new DownloadError(`release ${asset.tag}'s asset URL is not on ${apiBase}`); return asset.apiUrl; } async function fetchGithub(source: Extract, deps: FetchDeps): Promise { const repo = `${encodeURIComponent(source.owner)}/${encodeURIComponent(source.repo)}`; const which = source.tag === null ? "latest" : `tags/${encodeURIComponent(source.tag)}`; const apiBase = httpsBase(deps.githubApi ?? GITHUB_API, "the GitHub API"); const releaseUrl = `${apiBase}/repos/${repo}/releases/${which}`; const release = await downloadJson(deps.fetch, releaseUrl, githubHeaders(deps, "application/vnd.github+json"), METADATA_LIMITS); const resolved = resolveGithubAsset(release); if (!resolved.ok) throw new DownloadError(`${source.owner}/${source.repo}: ${resolved.error}`); const asset = resolved.value; const bytes = await downloadBytes(deps.fetch, assetUrl(asset, deps, apiBase), githubHeaders(deps, "application/octet-stream"), PACKAGE_LIMITS); const mismatch = verifyGithubBytes(bytes, asset); if (mismatch !== null) throw new DownloadError(`${source.owner}/${source.repo}: ${mismatch}`); return { bytes, resolved: asset.tag }; } const errorCode = (err: unknown): string => (err instanceof Error && "code" in err && typeof err.code === "string" ? err.code : String(err)); // Non-blocking, so opening a FIFO that ends in .tgz returns at once instead of waiting for a writer; // it has no effect on reading a regular file. Windows has no such flag, and no FIFOs to open this way. const READ_FLAGS = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0); const READ_CHUNK_BYTES = 64 * 1024; /** Something to read from in chunks: a FileHandle, or a stand-in in tests. */ export interface ChunkReader { read: (buffer: Buffer, offset: number, length: number, position: null) => Promise<{ bytesRead: number }>; } /** Reads to the end, refusing as soon as more than `maxBytes` arrive: never holds more than one chunk past it. * Once `signal` aborts, no further read is started. */ export async function readAtMost(reader: ChunkReader, maxBytes: number, what: string, signal?: AbortSignal): Promise { const chunks: Buffer[] = []; let received = 0; for (;;) { if (signal?.aborted) throw new DownloadError(`${what}: reading stopped at the deadline`); const chunk = Buffer.alloc(READ_CHUNK_BYTES); const { bytesRead } = await reader.read(chunk, 0, READ_CHUNK_BYTES, null); if (bytesRead === 0) return Buffer.concat(chunks, received); received += bytesRead; if (received > maxBytes) throw new DownloadError(`${what} is larger than ${maxBytes} bytes`); chunks.push(chunk.subarray(0, bytesRead)); } } /** Rejects with a DownloadError once `timeoutMs` pass, and aborts the signal `work` was given so it starts * nothing more. A read already stuck in the kernel cannot be cancelled from Node — closing its handle waits * for it — so at most that one read stays in flight, and its handle closes once it returns. */ export function withDeadline(work: (signal: AbortSignal) => Promise, timeoutMs: number, what: string): Promise { const controller = new AbortController(); let timer: ReturnType | undefined; const late = new Promise((_resolve, reject) => { timer = setTimeout(() => { controller.abort(); reject(new DownloadError(`${what} took longer than ${timeoutMs} ms to read`)); }, timeoutMs); }); return Promise.race([work(controller.signal), late]).finally(() => clearTimeout(timer)); } // Opened once, and the kind and size come from that handle: checking the path and then reading it // again would read whatever replaced it in between. async function readPackageFile(file: string, maxBytes: number, signal: AbortSignal): Promise { const handle: FileHandle = await open(file, READ_FLAGS).catch((err: unknown) => { throw new DownloadError(`${file} could not be read (${errorCode(err)})`); }); try { const info = await handle.stat(); if (!info.isFile()) throw new DownloadError(`${file} is not a file`); if (info.size > maxBytes) throw new DownloadError(`${file} is larger than ${maxBytes} bytes`); return await readAtMost(handle, maxBytes, file, signal); } finally { await handle.close().catch(() => undefined); } } // Held to a download's byte limit and deadline. async function fetchFile(source: Extract): Promise { const bytes = await withDeadline((signal) => readPackageFile(source.path, PACKAGE_LIMITS.maxBytes, signal), PACKAGE_LIMITS.timeoutMs, source.path); return { bytes, resolved: source.path }; } export function fetchPackage(source: InstallSource, deps: FetchDeps): Promise { if (source.kind === "npm") return fetchNpm(source, deps); if (source.kind === "github") return fetchGithub(source, deps); return fetchFile(source); }