Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 20 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
`<os>-<arch>`, 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)
Expand Down Expand Up @@ -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`?

Expand Down Expand Up @@ -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/
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
Expand Down
111 changes: 95 additions & 16 deletions src/node-util.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -262,6 +263,85 @@ export function resolveNodeVersion(version: string): Promise<string> {
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<void> {
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<Buffer>) {
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<string> {
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,
Expand Down Expand Up @@ -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,
Expand All @@ -319,18 +397,19 @@ 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`
);
await fs.writeFile(cacheTargetFile, data);
} 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);
Expand Down
127 changes: 127 additions & 0 deletions test/node-download.test.mjs
Original file line number Diff line number Diff line change
@@ -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/"
),
});
});
Loading