import { execFile } from "node:child_process"; import { createHash } from "node:crypto"; import { createWriteStream, promises as fs } from "node:fs"; import path from "node:path"; import { Readable, Transform } from "node:stream"; import { pipeline } from "node:stream/promises"; import { promisify } from "node:util"; import { gt, valid } from "semver"; import { log } from "./log"; const exec = promisify(execFile); // Node 22 provides AbortSignal.any. The project's ambient Node types predate it. const signalClass = AbortSignal as typeof AbortSignal & { any(signals: AbortSignal[]): AbortSignal }; const releaseAPI = "https://api.github.com/repos/anchore/grype/releases/latest"; const releaseBase = "https://github.com/anchore/grype/releases/download"; const interval = 6 * 60 * 60 * 1000; const maxArchiveBytes = 100 * 1024 * 1024; interface Release { tag_name: string; assets: Array<{ name: string; digest: string; size: number }>; } export class GrypeUpdater { private readonly override = process.env.DOCKGE_GRYPE_PATH; private readonly shutdown = new AbortController(); private readonly architecture = process.platform === "linux" ? { x64: "amd64", arm64: "arm64" }[process.arch as "x64" | "arm64"] : undefined; private current = "grype"; private pending?: Promise; private timer?: NodeJS.Timeout; private nextCheck = 0; constructor(private readonly directory: string) {} start() { void this.executable(); this.timer ??= setInterval(() => void this.executable(), 15 * 60 * 1000).unref(); } async stop() { clearInterval(this.timer); this.shutdown.abort(); await this.pending; } async executable() { if (this.override || !this.architecture || this.shutdown.signal.aborted) { return this.override || this.current; } if (!this.pending && Date.now() >= this.nextCheck) { this.pending = this.refresh(this.architecture).then(() => { this.nextCheck = Date.now() + interval; }).catch(() => { this.nextCheck = Date.now() + 15 * 60 * 1000; if (!this.shutdown.signal.aborted) { log.warn("grype-update", "Could not refresh Grype from Anchore releases"); } }).finally(() => { this.pending = undefined; }); } await this.pending; return this.current; } private async version(binary: string): Promise { try { const { stdout } = await exec(binary, [ "version", "-o", "json" ], { env: { ...process.env, GRYPE_CHECK_FOR_APP_UPDATE: "false" }, signal: this.shutdown.signal, timeout: 5000, maxBuffer: 64 * 1024, }); return valid(JSON.parse(stdout).version); } catch { return null; } } private async refresh(arch: string) { const installed = path.join(this.directory, "grype"); const [ bundled, cached ] = await Promise.all([ this.version("grype"), this.version(installed) ]); const useCached = cached && (!bundled || gt(cached, bundled)); this.current = useCached ? installed : "grype"; const currentVersion = useCached ? cached : bundled; const response = await fetch(releaseAPI, { signal: signalClass.any([ this.shutdown.signal, AbortSignal.timeout(10000) ]), headers: { Accept: "application/vnd.github+json", "User-Agent": "Dockge-Grype-Updater" }, }); if (!response.ok) { throw new Error("Could not retrieve Grype release"); } const release = await response.json() as Release; const tag = release.tag_name; const version = /^v\d+\.\d+\.\d+$/.test(tag) ? valid(tag) : null; if (!version) { throw new Error("Invalid Grype release tag"); } if (currentVersion && !gt(version, currentVersion)) { return; } const filename = `grype_${version}_linux_${arch}.tar.gz`; const asset = release.assets?.find(asset => asset.name === filename); if (!asset || !/^sha256:[a-f0-9]{64}$/.test(asset.digest) || !Number.isSafeInteger(asset.size) || asset.size < 1 || asset.size > maxArchiveBytes) { throw new Error("Missing Grype release checksum"); } await fs.mkdir(this.directory, { recursive: true }); const temp = await fs.mkdtemp(path.join(this.directory, ".install-")); try { const archive = path.join(temp, "archive.tar.gz"); await this.download(`${releaseBase}/${tag}/${filename}`, archive, asset); const binary = path.join(temp, "grype"); const options = { signal: this.shutdown.signal, timeout: 15000, maxBuffer: 150 * 1024 * 1024, encoding: "buffer" as const }; const { stdout } = await exec("tar", [ "-xOzf", archive, "grype" ], options); await fs.writeFile(binary, stdout, { mode: 0o755 }); if (await this.version(binary) !== version) { throw new Error("Downloaded Grype could not be verified"); } const license = await exec("tar", [ "-xOzf", archive, "LICENSE" ], options); await fs.writeFile(path.join(temp, "LICENSE"), license.stdout); await fs.rename(path.join(temp, "LICENSE"), path.join(this.directory, "LICENSE")); await fs.rename(binary, installed); this.current = installed; log.info("grype-update", `Installed Grype ${version}`); } finally { await fs.rm(temp, { recursive: true, force: true }); } } private async download(url: string, archive: string, asset: { size: number; digest: string }) { const signal = signalClass.any([ this.shutdown.signal, AbortSignal.timeout(90000) ]); const response = await fetch(url, { signal }); if (!response.ok || !response.body) { throw new Error("Grype download failed"); } const hash = createHash("sha256"); let size = 0; const verify = new Transform({ transform(chunk: Buffer, encoding, callback) { size += chunk.length; if (size > asset.size) { callback(new Error("Grype archive exceeds release asset size")); return; } hash.update(chunk); callback(null, chunk); }, }); await pipeline(Readable.fromWeb(response.body as unknown as import("node:stream/web").ReadableStream), verify, createWriteStream(archive, { flags: "wx" }), { signal }); if (size !== asset.size || `sha256:${hash.digest("hex")}` !== asset.digest) { throw new Error("Grype archive checksum mismatch"); } } }