From a3f573561f1a6615d410210d59fce12dbd82e309 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:02:18 +0000 Subject: [PATCH] feat: fall back to Node.js unofficial builds for platforms like linux-arm64-musl nodejs.org ships no linux-arm64-musl build, but the Node.js unofficial-builds project publishes one with the same archive layout. When the official archive 404s, download it from unofficial-builds.nodejs.org instead. Every download is now checked against the release's SHASUMS256.txt, and when neither source has the platform the error lists the URLs that were tried. --- .github/workflows/build.yml | 3 + README.md | 21 +++++- package.json | 3 +- src/node-util.ts | 111 ++++++++++++++++++++++++++----- test/node-download.test.mjs | 127 ++++++++++++++++++++++++++++++++++++ 5 files changed, 247 insertions(+), 18 deletions(-) create mode 100644 test/node-download.test.mjs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7a9eba3..7030db4 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -76,6 +76,9 @@ jobs: run: | node dist/bin/cli.js + - name: Test Node.js download sources + run: npm test + - name: Test with asset (and V8 code cache acceptance) run: | cd test diff --git a/README.md b/README.md index 811d5f4..77e5748 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,23 @@ await fossilize( - `FOSSILIZE_PLATFORMS` (comma separated) - `FOSSILIZE_CONCURRENCY_LIMIT` +### Platforms + +Pass target platforms with `-p` (or `FOSSILIZE_PLATFORMS`) using the names from +the Node.js release archives, such as `darwin-arm64`, `linux-x64`, +`linux-arm64`, `linux-x64-musl` or `win-x64`. The default is the host's +`-`, which never picks a `-musl` build, so pass those explicitly. + +Fossilize downloads each platform's Node.js build from [nodejs.org][9]. When +nodejs.org has no build for a platform, it falls back to the Node.js +[unofficial builds][10], which is where `linux-arm64-musl` comes from. Every +download is checked against that release's `SHASUMS256.txt`. The unofficial +builds do not cover every release, so the build fails with the URLs it tried +when neither source has the platform for the chosen Node.js version. + +The musl binaries need `libstdc++` and `libatomic` at runtime. On Alpine: +`apk add libstdc++ libatomic`. + ## What is it? Fossilize is a tool to create Node SEAs (Single Executable Applications) @@ -130,7 +147,7 @@ build pipeline, optimize the image building process based on dependencies, learn how to minimize image size by deleting package manager caches etc. On the other hand, if you distribute your application as a Node SEA, then all you need to do is copy a single binary into a base Linux distro image -that has `libc` (sorry Alpine) and you are good to go. +that has `libc` (or `musl` with the `*-musl` platforms) and you are good to go. ### Why do I need `fossilize`? @@ -174,3 +191,5 @@ Further documentation will be added about how to obtain and use these. [6]: https://docs.deno.com/runtime/reference/cli/compile/ [7]: https://www.npmjs.com/package/postject [8]: https://nodejs.org/api/single-executable-applications.html#seagetrawassetkey +[9]: https://nodejs.org/dist/ +[10]: https://unofficial-builds.nodejs.org/download/release/ diff --git a/package.json b/package.json index 223d5f0..f4b4cae 100644 --- a/package.json +++ b/package.json @@ -39,7 +39,8 @@ "prebuild": "tsc -p src/tsconfig.json", "build": "tsup", "prepublishOnly": "npm run build", - "#postinstall": "npx @stricli/auto-complete@latest install fossilize __fossilize_bash_complete" + "#postinstall": "npx @stricli/auto-complete@latest install fossilize __fossilize_bash_complete", + "test": "node --test test/node-download.test.mjs" }, "tsup": { "entry": [ diff --git a/src/node-util.ts b/src/node-util.ts index 2be7cd5..7fbba51 100644 --- a/src/node-util.ts +++ b/src/node-util.ts @@ -1,9 +1,10 @@ -import { createWriteStream, openSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { createReadStream, createWriteStream, openSync } from "node:fs"; import * as fs from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { Readable } from "node:stream"; -import { finished } from "node:stream/promises"; +import { pipeline } from "node:stream/promises"; import { unsign } from "macho-unsign"; import { signatureSet } from "portable-executable-signature"; import { untar, unzip } from "./archive-util"; @@ -262,6 +263,85 @@ export function resolveNodeVersion(version: string): Promise { return _VERSION_CACHE.get(version)!; } +// Official builds come first. Platforms nodejs.org does not ship, such as +// `linux-arm64-musl`, are published by the Node.js unofficial-builds project +// with the same layout and archive names. +const NODE_DIST_BASE_URLS = [ + "https://nodejs.org/dist", + "https://unofficial-builds.nodejs.org/download/release", +]; + +async function downloadNodeArchive( + version: string, + archiveName: string, + targetFile: string +): Promise { + const triedUrls: string[] = []; + for (const baseUrl of NODE_DIST_BASE_URLS) { + const url = `${baseUrl}/v${version}/${archiveName}`; + const resp = await fetch(url); + if (resp.status === 404) { + triedUrls.push(url); + continue; + } + if (!resp.ok) + throw new Error( + `Failed to fetch ${url}: ${resp.status} ${resp.statusText}` + ); + if (!resp.body) + throw new Error( + `Response body is null for ${url}: ${resp.status} ${resp.statusText}` + ); + if (baseUrl !== NODE_DIST_BASE_URLS[0]) { + console.log(`Using unofficial Node.js build: ${url}`); + } + + const hash = createHash("sha256"); + await pipeline( + Readable.fromWeb(resp.body), + async function* (source: AsyncIterable) { + for await (const chunk of source) { + hash.update(chunk); + yield chunk; + } + }, + createWriteStream(targetFile) + ); + const actual = hash.digest("hex"); + const expected = await getExpectedSha256(baseUrl, version, archiveName); + if (actual !== expected) { + throw new Error( + `Checksum mismatch for ${url}: expected sha256 ${expected}, got ${actual}` + ); + } + return; + } + throw new Error( + `No Node.js v${version} build found for ${archiveName}. Tried:\n` + + triedUrls.map((url) => ` ${url}`).join("\n") + ); +} + +async function getExpectedSha256( + baseUrl: string, + version: string, + archiveName: string +): Promise { + const url = `${baseUrl}/v${version}/SHASUMS256.txt`; + const resp = await fetch(url); + if (!resp.ok) + throw new Error( + `Failed to fetch ${url}: ${resp.status} ${resp.statusText}` + ); + for (const line of (await resp.text()).split("\n")) { + const [hash, name] = line.trim().split(/\s+/); + if (name === archiveName && hash) { + return hash.toLowerCase(); + } + } + throw new Error(`No checksum for ${archiveName} in ${url}`); +} + export async function getNodeBinary( version: string, platform: string, @@ -298,16 +378,14 @@ export async function getNodeBinary( }`; await fs.mkdir(cacheDir, { recursive: true }); const nodeDir = await fs.mkdtemp(path.join(cacheDir, remoteArchiveName)); - const url = `https://nodejs.org/dist/v${resolvedVersion}/${remoteArchiveName}`; - const resp = await fetch(url); - if (!resp.ok) - throw new Error( - `Failed to fetch ${url}: ${resp.status} ${resp.statusText}` - ); - if (!resp.body) - throw new Error( - `Response body is null for ${url}: ${resp.status} ${resp.statusText}` - ); + const archivePath = path.join(nodeDir, remoteArchiveName); + try { + await downloadNodeArchive(resolvedVersion, remoteArchiveName, archivePath); + } catch (err) { + // Don't leave a partial or unverified archive behind in the cache dir. + await fs.rm(nodeDir, { recursive: true, force: true }); + throw err; + } const cacheTargetFile = path.join( cacheDir, @@ -319,10 +397,8 @@ export async function getNodeBinary( // fossilize instances try to write to the same file. We may add a try-catch // block here to recover but we'll cross that bridge when we get there. if (platform.startsWith("win")) { - const stream = createWriteStream(path.join(nodeDir, remoteArchiveName)); - await finished(Readable.fromWeb(resp.body).pipe(stream)); const data = await unzip( - stream.path as string, + archivePath, // Need `/` as path separator, even on Windows as that's how `unzip` works `node-v${resolvedVersion}-${platform}/node.exe` ); @@ -330,7 +406,10 @@ export async function getNodeBinary( } else { await fs.writeFile( cacheTargetFile, - await untar(resp.body, `node-v${resolvedVersion}-${platform}/bin/node`) + await untar( + Readable.toWeb(createReadStream(archivePath)) as ReadableStream, + `node-v${resolvedVersion}-${platform}/bin/node` + ) ); } await fs.chmod(cacheTargetFile, 0o755); diff --git a/test/node-download.test.mjs b/test/node-download.test.mjs new file mode 100644 index 0000000..4408626 --- /dev/null +++ b/test/node-download.test.mjs @@ -0,0 +1,127 @@ +// Network-backed tests for how fossilize finds and verifies Node.js builds. +// Run after `npm run build`: they drive the built package through its public +// `fossilize()` API, so they exercise the same code path as the CLI. +import assert from "node:assert/strict"; +import { mkdtemp, open, cp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, before, test } from "node:test"; +import { fileURLToPath } from "node:url"; +import { fossilize } from "../dist/index.js"; + +// nodejs.org ships no linux-arm64-musl build for this version; the Node.js +// unofficial-builds project does. +const NODE_VERSION = "24.16.0"; +const MUSL_PLATFORM = "linux-arm64-musl"; +const MUSL_ARCHIVE = `node-v${NODE_VERSION}-${MUSL_PLATFORM}.tar.xz`; +const EM_AARCH64 = 183; +const MUSL_INTERPRETER = "/lib/ld-musl-aarch64.so.1"; + +const testDir = path.dirname(fileURLToPath(import.meta.url)); +const entrypoint = path.join(testDir, "sample.cjs"); + +let workDir; +// Shared by the tests so the host Node.js binary (needed to build the SEA +// blob) and the musl build are downloaded once. +let cacheDir; + +before(async () => { + workDir = await mkdtemp(path.join(tmpdir(), "fossilize-test-")); + cacheDir = path.join(workDir, "cache"); +}); + +after(async () => { + await rm(workDir, { recursive: true, force: true }); +}); + +function outDirFor(platform) { + return path.join(workDir, `out-${platform}`); +} + +function build(platform, options = {}) { + return fossilize( + { + nodeVersion: NODE_VERSION, + platforms: [platform], + outDir: outDirFor(platform), + cacheDir, + noBundle: true, + noCodeCache: true, + sign: false, + holePunch: false, + concurrencyLimit: 1, + ...options, + }, + entrypoint + ); +} + +async function readHead(file, length) { + const handle = await open(file, "r"); + try { + const { buffer, bytesRead } = await handle.read( + Buffer.alloc(length), + 0, + length, + 0 + ); + return buffer.subarray(0, bytesRead); + } finally { + await handle.close(); + } +} + +test("builds linux-arm64-musl from the unofficial builds", async () => { + await build(MUSL_PLATFORM); + + const binary = path.join(outDirFor(MUSL_PLATFORM), `sample-${MUSL_PLATFORM}`); + const head = await readHead(binary, 64 * 1024); + assert.equal(head.subarray(0, 4).toString("latin1"), "\x7fELF"); + assert.equal(head.readUInt16LE(18), EM_AARCH64); + assert.ok( + head.includes(MUSL_INTERPRETER), + `expected ${MUSL_INTERPRETER} as the ELF interpreter` + ); +}); + +test("rejects a download that does not match SHASUMS256.txt", async (t) => { + // Start from the shared cache minus the musl build, so only that archive + // is downloaded again. + const tamperedCache = path.join(workDir, "cache-tampered"); + await cp(cacheDir, tamperedCache, { + recursive: true, + filter: (src) => !path.basename(src).includes(MUSL_PLATFORM), + }); + + const realFetch = globalThis.fetch; + t.mock.method(globalThis, "fetch", async (url, ...rest) => { + const resp = await realFetch(url, ...rest); + if (!String(url).endsWith("/SHASUMS256.txt")) { + return resp; + } + const sums = (await resp.text()) + .split("\n") + .map((line) => + line.endsWith(` ${MUSL_ARCHIVE}`) + ? `${"0".repeat(64)} ${MUSL_ARCHIVE}` + : line + ) + .join("\n"); + return new Response(sums, { status: 200 }); + }); + + await assert.rejects(build(MUSL_PLATFORM, { cacheDir: tamperedCache }), { + message: new RegExp(`^Checksum mismatch for .*/${MUSL_ARCHIVE}: `), + }); +}); + +test("fails clearly when no source has the platform", async () => { + await assert.rejects(build("linux-nope64-musl"), { + message: new RegExp( + `^No Node\\.js v${NODE_VERSION} build found for ` + + `node-v${NODE_VERSION}-linux-nope64-musl\\.tar\\.xz\\. Tried:\\n` + + " https://nodejs.org/dist/.*\\n" + + " https://unofficial-builds\\.nodejs\\.org/download/release/" + ), + }); +});