feat(cli): add pi2 update with a versioned install layout
The standalone (curl installer) channel had no upgrade path of its own: the
documented one was 're-run the installer', which the Neovim plugin cannot do
safely and which re-downloads 35 MB without version arithmetic, provenance or
rollback. ADR 0003 records the design; this is the implementation.
- install.sh now installs one immutable tree per version
(`<prefix>/versions/<v>/{bin,share,LICENSE}`) behind a single atomically
swapped `current` symlink, writes `<prefix>/install.json` as the install
receipt, and migrates a pre-0.1.7 flat layout in place. Keeping `current` plus
one previous tree gives a one-step rollback for free.
- `pi2 update` (native TypeScript, no `curl | sh` subprocess) resolves the
release with an ETag-cached GitHub lookup, picks the asset from the
build-time `PI2_BUILD_TARGET` define instead of re-probing libc, verifies
SHA256SUMS, verifies SLSA provenance with `gh attestation verify`, runs the
new binary once, then swaps `current` and rewrites the receipt. Flags:
--check/--dry-run/--version/--force/--json/--require-attestation/
--skip-attestation. Downgrades need --force; restarts stay manual.
- the receipt is the only channel detection: npm, Homebrew and the AUR are
refused with the command that owns their tree, and a flat install is told to
re-run the installer once. No heuristics on `process.execPath`.
- `pi2 install-service` renders `<prefix>/current/bin/pi2`, so an update no
longer invalidates the unit.
- `scripts/build-binary.sh` injects `PI2_BUILD_TARGET`; `tarball.ts` is a
dependency-free ustar/PAX reader with traversal and symlink rejection.
Verified against the real release: install.sh into a scratch prefix, update
--check/--dry-run, a local 0.1.7 mirror upgrade (attestation warn path), then
`pi2 update --version 0.1.6 --force` (real download, real attestation
verified), plus boot-check and the refusal paths. typecheck + 567 daemon tests
+ web typecheck + 537 web tests + smoke are green.
This commit is contained in:
1 parent
29aee26733
commit
8fb535f7f3
20 files changed
+2557
-43
No files matched your search
@@ -0,0 +1,175 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
assetName,
|
||||
assetUrl,
|
||||
channelUpgradeCommand,
|
||||
checksumsUrl,
|
||||
compareVersions,
|
||||
matchesChecksum,
|
||||
normalizeVersion,
|
||||
parseChecksums,
|
||||
parseRedirectVersion,
|
||||
parseReleaseTag,
|
||||
resolveLatestVersion,
|
||||
sha256Hex,
|
||||
type UpdateCache,
|
||||
} from "../../src/core/release.js";
|
||||
|
||||
function jsonResponse(payload: unknown, init: { status?: number; headers?: Record<string, string> } = {}): Response {
|
||||
return new Response(JSON.stringify(payload), {
|
||||
status: init.status ?? 200,
|
||||
headers: { "content-type": "application/json", ...(init.headers ?? {}) },
|
||||
});
|
||||
}
|
||||
|
||||
describe("versions", () => {
|
||||
it("normalises a v prefix and orders triplets", () => {
|
||||
expect(normalizeVersion("v0.1.7")).toBe("0.1.7");
|
||||
expect(normalizeVersion("0.1.7")).toBe("0.1.7");
|
||||
expect(compareVersions("0.1.7", "0.1.6")).toBe(1);
|
||||
expect(compareVersions("0.1.6", "0.1.7")).toBe(-1);
|
||||
expect(compareVersions("v0.1.6", "0.1.6")).toBe(0);
|
||||
expect(compareVersions("0.10.0", "0.9.9")).toBe(1);
|
||||
expect(compareVersions("nonsense", "0.0.1")).toBe(-1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("asset naming", () => {
|
||||
it("matches scripts/build-binary.sh", () => {
|
||||
expect(assetName("0.1.7", "linux-x64")).toBe("pi2d-0.1.7-linux-x64.tar.gz");
|
||||
expect(assetName("v0.1.7", "linux-x64-musl")).toBe("pi2d-0.1.7-linux-x64-musl.tar.gz");
|
||||
});
|
||||
|
||||
it("prefers PI2_BASE_URL over github.com", () => {
|
||||
expect(assetUrl("0.1.7", "darwin-arm64")).toBe(
|
||||
"https://github.com/zgs225/pi2d/releases/download/v0.1.7/pi2d-0.1.7-darwin-arm64.tar.gz",
|
||||
);
|
||||
expect(assetUrl("0.1.7", "linux-x64", "http://127.0.0.1:9/fixture/")).toBe(
|
||||
"http://127.0.0.1:9/fixture/pi2d-0.1.7-linux-x64.tar.gz",
|
||||
);
|
||||
expect(checksumsUrl("0.1.7", "http://127.0.0.1:9/fixture")).toBe("http://127.0.0.1:9/fixture/SHA256SUMS");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseChecksums", () => {
|
||||
it("reads sha256sum -c output, binary markers, comments and CRLF", () => {
|
||||
const digest = "a".repeat(64);
|
||||
const text = [
|
||||
`# generated by the release workflow`,
|
||||
`${digest} pi2d-0.1.7-linux-x64.tar.gz`,
|
||||
`${digest.toUpperCase()} *pi2d-0.1.7-darwin-arm64.tar.gz`,
|
||||
`${digest} ./pi2d-0.1.7-linux-arm64.tar.gz`,
|
||||
"",
|
||||
"not a checksum line",
|
||||
].join("\r\n");
|
||||
const checksums = parseChecksums(text);
|
||||
expect(checksums.get("pi2d-0.1.7-linux-x64.tar.gz")).toBe(digest);
|
||||
expect(checksums.get("pi2d-0.1.7-darwin-arm64.tar.gz")).toBe(digest);
|
||||
expect(checksums.get("pi2d-0.1.7-linux-arm64.tar.gz")).toBe(digest);
|
||||
expect(checksums.size).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("digests", () => {
|
||||
it("verifies bytes against the published digest", () => {
|
||||
const bytes = Buffer.from("payload");
|
||||
const digest = sha256Hex(bytes);
|
||||
expect(digest).toHaveLength(64);
|
||||
expect(matchesChecksum(bytes, digest)).toBe(true);
|
||||
expect(matchesChecksum(bytes, digest.toUpperCase())).toBe(true);
|
||||
expect(matchesChecksum(Buffer.from("other"), digest)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("release payloads", () => {
|
||||
it("parses tag_name and the releases/latest redirect", () => {
|
||||
expect(parseReleaseTag({ tag_name: "v0.1.7" })).toBe("0.1.7");
|
||||
expect(parseReleaseTag({})).toBeUndefined();
|
||||
expect(parseReleaseTag(null)).toBeUndefined();
|
||||
expect(parseRedirectVersion("https://github.com/zgs225/pi2d/releases/tag/v0.1.7")).toBe("0.1.7");
|
||||
expect(parseRedirectVersion(undefined)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("maps a channel to the command that owns it", () => {
|
||||
expect(channelUpgradeCommand("brew")).toContain("brew upgrade pi2d");
|
||||
expect(channelUpgradeCommand("aur")).toContain("paru");
|
||||
expect(channelUpgradeCommand("npm")).toContain("npm i -g");
|
||||
expect(channelUpgradeCommand("unknown")).toContain("npm i -g");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveLatestVersion", () => {
|
||||
it("uses a fresh cache without touching the network", async () => {
|
||||
const cache: UpdateCache = { version: "0.1.7", checkedAt: new Date().toISOString() };
|
||||
let calls = 0;
|
||||
const result = await resolveLatestVersion({
|
||||
cache,
|
||||
fetchImpl: (async () => {
|
||||
calls += 1;
|
||||
return jsonResponse({ tag_name: "v9.9.9" });
|
||||
}) as unknown as typeof fetch,
|
||||
});
|
||||
expect(result.version).toBe("0.1.7");
|
||||
expect(result.source).toBe("cache");
|
||||
expect(calls).toBe(0);
|
||||
});
|
||||
|
||||
it("queries the API, caching the tag and the ETag", async () => {
|
||||
const result = await resolveLatestVersion({
|
||||
fetchImpl: (async () =>
|
||||
jsonResponse({ tag_name: "v0.1.7" }, { headers: { etag: 'W/"abc"' } })) as unknown as typeof fetch,
|
||||
now: new Date("2026-10-29T00:00:00Z"),
|
||||
});
|
||||
expect(result.version).toBe("0.1.7");
|
||||
expect(result.source).toBe("api");
|
||||
expect(result.cache.etag).toBe('W/"abc"');
|
||||
expect(result.cache.checkedAt).toBe("2026-10-29T00:00:00.000Z");
|
||||
});
|
||||
|
||||
it("reuses the version on 304 and refreshes the timestamp", async () => {
|
||||
const cache: UpdateCache = {
|
||||
version: "0.1.7",
|
||||
checkedAt: new Date("2026-10-01T00:00:00Z").toISOString(),
|
||||
etag: 'W/"abc"',
|
||||
};
|
||||
let sentEtag: string | undefined;
|
||||
const result = await resolveLatestVersion({
|
||||
cache,
|
||||
fetchImpl: (async (_input: unknown, init?: RequestInit) => {
|
||||
sentEtag = new Headers(init?.headers).get("if-none-match") ?? undefined;
|
||||
return new Response(null, { status: 304 });
|
||||
}) as unknown as typeof fetch,
|
||||
now: new Date("2026-10-29T00:00:00Z"),
|
||||
});
|
||||
expect(sentEtag).toBe('W/"abc"');
|
||||
expect(result.version).toBe("0.1.7");
|
||||
expect(result.source).toBe("api");
|
||||
expect(result.cache.etag).toBe('W/"abc"');
|
||||
expect(result.cache.checkedAt).toBe("2026-10-29T00:00:00.000Z");
|
||||
});
|
||||
|
||||
it("falls back to the releases/latest redirect when the API is rate-limited", async () => {
|
||||
const result = await resolveLatestVersion({
|
||||
fetchImpl: (async (input: unknown) => {
|
||||
const url = String(input);
|
||||
if (url.includes("api.github.com")) return new Response("rate limited", { status: 403 });
|
||||
return new Response(null, {
|
||||
status: 302,
|
||||
headers: { location: "https://github.com/zgs225/pi2d/releases/tag/v0.1.9" },
|
||||
});
|
||||
}) as unknown as typeof fetch,
|
||||
});
|
||||
expect(result.version).toBe("0.1.9");
|
||||
expect(result.source).toBe("redirect");
|
||||
});
|
||||
|
||||
it("reports both failures when nothing answers", async () => {
|
||||
await expect(
|
||||
resolveLatestVersion({
|
||||
fetchImpl: (async () => {
|
||||
throw new Error("network down");
|
||||
}) as unknown as typeof fetch,
|
||||
}),
|
||||
).rejects.toThrow(/could not reach GitHub/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,213 @@
|
||||
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
applyVersionedInstall,
|
||||
buildReceipt,
|
||||
currentVersion,
|
||||
pruneVersions,
|
||||
readReceipt,
|
||||
receiptPath,
|
||||
removeStaleStaging,
|
||||
stagingDir,
|
||||
switchCurrent,
|
||||
versionOfBinary,
|
||||
writeReceiptAtomic,
|
||||
} from "../../src/core/self-update.js";
|
||||
|
||||
let dirs: string[] = [];
|
||||
|
||||
function tmp(): string {
|
||||
const dir = mkdtempSync(join(tmpdir(), "pi2-selfupdate-"));
|
||||
dirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
|
||||
dirs = [];
|
||||
});
|
||||
|
||||
/** `<prefix>/versions/<version>/{bin,share,LICENSE}` + `current`, like install.sh writes it. */
|
||||
function makeInstall(prefix: string, version: string): { bin: string; versionDir: string } {
|
||||
const versionDir = join(prefix, "versions", version);
|
||||
mkdirSync(join(versionDir, "bin"), { recursive: true });
|
||||
mkdirSync(join(versionDir, "share", "pi2d", "web", "dist"), { recursive: true });
|
||||
const bin = join(versionDir, "bin", "pi2");
|
||||
writeFileSync(bin, `#!/bin/sh\necho "pi2 ${version}"\n`, { mode: 0o755 });
|
||||
writeFileSync(join(versionDir, "share", "pi2d", "web", "dist", "index.html"), "<html></html>\n");
|
||||
writeFileSync(join(versionDir, "LICENSE"), "MIT\n");
|
||||
return { bin, versionDir };
|
||||
}
|
||||
|
||||
function stagingTree(prefix: string, label: string): string {
|
||||
const dir = stagingDir(prefix, label);
|
||||
mkdirSync(join(dir, "bin"), { recursive: true });
|
||||
mkdirSync(join(dir, "share", "pi2d", "web", "dist"), { recursive: true });
|
||||
writeFileSync(join(dir, "bin", "pi2"), "#!/bin/sh\necho new\n", { mode: 0o755 });
|
||||
writeFileSync(join(dir, "share", "pi2d", "web", "dist", "index.html"), "<html>new</html>\n");
|
||||
return dir;
|
||||
}
|
||||
|
||||
describe("receipt", () => {
|
||||
it("round-trips through the atomic writer", () => {
|
||||
const prefix = tmp();
|
||||
const receipt = buildReceipt({
|
||||
prefix,
|
||||
version: "0.1.7",
|
||||
bin: join(prefix, "versions", "0.1.7", "bin", "pi2"),
|
||||
asset: "pi2d-0.1.7-linux-x64.tar.gz",
|
||||
sha256: "a".repeat(64),
|
||||
now: new Date("2026-10-29T08:00:00Z"),
|
||||
});
|
||||
writeReceiptAtomic(prefix, receipt);
|
||||
const read = readReceipt(prefix);
|
||||
expect(read.error).toBeUndefined();
|
||||
expect(read.receipt).toEqual({
|
||||
...receipt,
|
||||
installed_at: "2026-10-29T08:00:00Z",
|
||||
});
|
||||
expect(existsSync(receiptPath(prefix))).toBe(true);
|
||||
// Written through a temp file, so no residue is left next to it.
|
||||
expect(readdirSync(prefix).filter((entry) => entry.includes(".tmp."))).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports a missing receipt instead of throwing", () => {
|
||||
expect(readReceipt(tmp()).error).toMatch(/no install receipt/);
|
||||
});
|
||||
|
||||
it("reports invalid JSON and unknown shapes", () => {
|
||||
const prefix = tmp();
|
||||
writeFileSync(receiptPath(prefix), "{not json");
|
||||
expect(readReceipt(prefix).error).toMatch(/not valid JSON/);
|
||||
writeFileSync(receiptPath(prefix), JSON.stringify({ schema: 1, version: "0.1.7" }));
|
||||
expect(readReceipt(prefix).error).toMatch(/missing prefix\/version\/bin/);
|
||||
});
|
||||
|
||||
it("refuses a receipt written by a newer schema", () => {
|
||||
const prefix = tmp();
|
||||
writeFileSync(
|
||||
receiptPath(prefix),
|
||||
JSON.stringify({ schema: 99, prefix, version: "0.1.7", bin: join(prefix, "bin", "pi2") }),
|
||||
);
|
||||
expect(readReceipt(prefix).error).toMatch(/newer pi2/);
|
||||
});
|
||||
|
||||
it("defaults fields a hand-written receipt may omit", () => {
|
||||
const prefix = tmp();
|
||||
writeFileSync(
|
||||
receiptPath(prefix),
|
||||
JSON.stringify({ prefix, version: "0.1.7", bin: join(prefix, "bin", "pi2") }),
|
||||
);
|
||||
const receipt = readReceipt(prefix).receipt;
|
||||
expect(receipt?.schema).toBe(1);
|
||||
expect(receipt?.installer).toBe("unknown");
|
||||
expect(receipt?.layout).toBe("versioned");
|
||||
expect(receipt?.current).toBe(join(prefix, "current"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("current symlink", () => {
|
||||
it("switches atomically and reads back", () => {
|
||||
const prefix = tmp();
|
||||
makeInstall(prefix, "0.1.6");
|
||||
makeInstall(prefix, "0.1.7");
|
||||
switchCurrent(prefix, "versions/0.1.6");
|
||||
expect(currentVersion(prefix)).toBe("0.1.6");
|
||||
switchCurrent(prefix, "versions/0.1.7");
|
||||
expect(currentVersion(prefix)).toBe("0.1.7");
|
||||
expect(readlinkSync(join(prefix, "current"))).toBe("versions/0.1.7");
|
||||
// No temp symlink left behind.
|
||||
expect(existsSync(join(prefix, `.current.${process.pid}`))).toBe(false);
|
||||
});
|
||||
|
||||
it("ignores a current that points somewhere else", () => {
|
||||
const prefix = tmp();
|
||||
symlinkSync("/somewhere/else", join(prefix, "current"));
|
||||
expect(currentVersion(prefix)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyVersionedInstall", () => {
|
||||
it("installs a tree, switches current, writes the receipt and prunes", () => {
|
||||
const prefix = tmp();
|
||||
const previous = makeInstall(prefix, "0.1.6");
|
||||
writeReceiptAtomic(
|
||||
prefix,
|
||||
buildReceipt({ prefix, version: "0.1.6", bin: previous.bin }),
|
||||
);
|
||||
switchCurrent(prefix, "versions/0.1.6");
|
||||
|
||||
const staged = stagingTree(prefix, "test");
|
||||
const applied = applyVersionedInstall({
|
||||
prefix,
|
||||
version: "0.1.7",
|
||||
stagedDir: staged,
|
||||
asset: "pi2d-0.1.7-linux-x64.tar.gz",
|
||||
sha256: "b".repeat(64),
|
||||
now: new Date("2026-10-29T09:00:00Z"),
|
||||
});
|
||||
|
||||
expect(applied.previous).toBe("0.1.6");
|
||||
expect(currentVersion(prefix)).toBe("0.1.7");
|
||||
expect(readFileSync(join(prefix, "versions", "0.1.7", "bin", "pi2"), "utf8")).toContain("echo new");
|
||||
expect(existsSync(staged)).toBe(false);
|
||||
const receipt = readReceipt(prefix).receipt;
|
||||
expect(receipt?.version).toBe("0.1.7");
|
||||
expect(receipt?.sha256).toBe("b".repeat(64));
|
||||
expect(receipt?.asset).toBe("pi2d-0.1.7-linux-x64.tar.gz");
|
||||
// current + one previous survive.
|
||||
expect(existsSync(join(prefix, "versions", "0.1.6"))).toBe(true);
|
||||
});
|
||||
|
||||
it("replaces a tree when the same version is reinstalled", () => {
|
||||
const prefix = tmp();
|
||||
makeInstall(prefix, "0.1.7");
|
||||
switchCurrent(prefix, "versions/0.1.7");
|
||||
const staged = stagingTree(prefix, "reinstall");
|
||||
const applied = applyVersionedInstall({ prefix, version: "0.1.7", stagedDir: staged });
|
||||
expect(applied.previous).toBe("0.1.7");
|
||||
expect(readFileSync(join(prefix, "versions", "0.1.7", "bin", "pi2"), "utf8")).toContain("echo new");
|
||||
});
|
||||
|
||||
it("rolls back the symlink and the tree when the swap fails", () => {
|
||||
const prefix = tmp();
|
||||
const previous = makeInstall(prefix, "0.1.6");
|
||||
writeReceiptAtomic(prefix, buildReceipt({ prefix, version: "0.1.6", bin: previous.bin }));
|
||||
switchCurrent(prefix, "versions/0.1.6");
|
||||
|
||||
expect(() =>
|
||||
applyVersionedInstall({
|
||||
prefix,
|
||||
version: "0.1.7",
|
||||
stagedDir: join(prefix, "versions", "does-not-exist"),
|
||||
}),
|
||||
).toThrow();
|
||||
|
||||
expect(currentVersion(prefix)).toBe("0.1.6");
|
||||
expect(existsSync(join(prefix, "versions", "0.1.7"))).toBe(false);
|
||||
expect(readReceipt(prefix).receipt?.version).toBe("0.1.6");
|
||||
expect(readFileSync(previous.bin, "utf8")).toContain("pi2 0.1.6");
|
||||
});
|
||||
|
||||
it("prunes every tree except current and previous", () => {
|
||||
const prefix = tmp();
|
||||
for (const version of ["0.1.4", "0.1.5", "0.1.6"]) makeInstall(prefix, version);
|
||||
mkdirSync(join(prefix, "versions", ".staging-leftover"), { recursive: true });
|
||||
const removed = pruneVersions(prefix, ["0.1.6", "0.1.5"]);
|
||||
expect(removed).toEqual(["0.1.4"]);
|
||||
expect(existsSync(join(prefix, "versions", "0.1.4"))).toBe(false);
|
||||
expect(existsSync(join(prefix, "versions", "0.1.6"))).toBe(true);
|
||||
// Dot entries are staging, cleaned separately.
|
||||
expect(existsSync(join(prefix, "versions", ".staging-leftover"))).toBe(true);
|
||||
expect(removeStaleStaging(prefix)).toEqual([".staging-leftover"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("versionOfBinary", () => {
|
||||
it("recognises the versioned layout", () => {
|
||||
expect(versionOfBinary("/home/u/.local/lib/pi2d/versions/0.1.7/bin/pi2")).toBe("0.1.7");
|
||||
expect(versionOfBinary("/usr/bin/pi2")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* Tiny ustar writer for the update tests — the real artifacts come from
|
||||
* `tar -czf` in `scripts/build-binary.sh`, and `src/core/tarball.ts` has to read
|
||||
* that shape without a `tar` subprocess.
|
||||
*/
|
||||
import { gzipSync } from "node:zlib";
|
||||
|
||||
export interface FixtureEntry {
|
||||
name: string;
|
||||
data?: string;
|
||||
mode?: number;
|
||||
type?: "file" | "directory" | "symlink";
|
||||
}
|
||||
|
||||
const BLOCK = 512;
|
||||
|
||||
function octal(value: number, length: number): string {
|
||||
const text = value.toString(8);
|
||||
return "0".repeat(Math.max(0, length - 1 - text.length)) + text + "\0";
|
||||
}
|
||||
|
||||
function header(entry: FixtureEntry): Buffer {
|
||||
const buffer = Buffer.alloc(BLOCK);
|
||||
const typeflag = entry.type === "directory" ? "5" : entry.type === "symlink" ? "2" : "0";
|
||||
const data = Buffer.from(entry.data ?? "", "utf8");
|
||||
buffer.write(entry.name, 0, 100, "utf8");
|
||||
buffer.write(octal(entry.mode ?? (entry.type === "directory" ? 0o755 : 0o644), 8), 100, 8, "ascii");
|
||||
buffer.write(octal(0, 8), 108, 8, "ascii");
|
||||
buffer.write(octal(0, 8), 116, 8, "ascii");
|
||||
buffer.write(octal(entry.type === "directory" ? 0 : data.length, 12), 124, 12, "ascii");
|
||||
buffer.write(octal(1_700_000_000, 12), 136, 12, "ascii");
|
||||
buffer.write(" ", 148, 8, "ascii");
|
||||
buffer.write(typeflag, 156, 1, "ascii");
|
||||
buffer.write("ustar\0", 257, 6, "ascii");
|
||||
buffer.write("00", 263, 2, "ascii");
|
||||
let sum = 0;
|
||||
for (const byte of buffer) sum += byte;
|
||||
buffer.write(`${octal(sum, 7)} `, 148, 8, "ascii");
|
||||
return buffer;
|
||||
}
|
||||
|
||||
export function buildTar(entries: FixtureEntry[]): Buffer {
|
||||
const blocks: Buffer[] = [];
|
||||
for (const entry of entries) {
|
||||
blocks.push(header(entry));
|
||||
if (entry.type === "directory" || entry.type === "symlink") continue;
|
||||
const data = Buffer.from(entry.data ?? "", "utf8");
|
||||
const pad = (BLOCK - (data.length % BLOCK)) % BLOCK;
|
||||
blocks.push(data, Buffer.alloc(pad));
|
||||
}
|
||||
blocks.push(Buffer.alloc(BLOCK * 2));
|
||||
return Buffer.concat(blocks);
|
||||
}
|
||||
|
||||
export function buildTarGz(entries: FixtureEntry[]): Buffer {
|
||||
return gzipSync(buildTar(entries));
|
||||
}
|
||||
|
||||
/** The two trees `scripts/build-binary.sh` ships in a release asset. */
|
||||
export function buildReleaseArchive(version = "0.1.7"): Buffer {
|
||||
return buildTarGz([
|
||||
{ name: "bin/", type: "directory" },
|
||||
{ name: "bin/pi2", data: `#!/bin/sh\necho "pi2 ${version}"\n`, mode: 0o755 },
|
||||
{ name: "share/", type: "directory" },
|
||||
{ name: "share/pi2d/", type: "directory" },
|
||||
{ name: "share/pi2d/web/", type: "directory" },
|
||||
{ name: "share/pi2d/web/dist/", type: "directory" },
|
||||
{ name: "share/pi2d/web/dist/index.html", data: "<html></html>\n" },
|
||||
{ name: "LICENSE", data: "MIT\n" },
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { gunzipSync } from "node:zlib";
|
||||
import { extractTarGz, parseTar, safeEntryPath, TarError } from "../../src/core/tarball.js";
|
||||
import { buildReleaseArchive, buildTar, buildTarGz } from "./tar-fixture.js";
|
||||
|
||||
let dirs: string[] = [];
|
||||
|
||||
function tmp(): string {
|
||||
const dir = mkdtempSync(join(tmpdir(), "pi2-tar-"));
|
||||
dirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
|
||||
dirs = [];
|
||||
});
|
||||
|
||||
describe("parseTar", () => {
|
||||
it("reads a release asset: names, sizes, modes", () => {
|
||||
const entries = parseTar(gunzipSync(buildReleaseArchive()));
|
||||
const paths = entries.map((entry) => entry.path);
|
||||
expect(paths).toContain("bin/pi2");
|
||||
expect(paths).toContain("share/pi2d/web/dist/index.html");
|
||||
expect(paths).toContain("LICENSE");
|
||||
const bin = entries.find((entry) => entry.path === "bin/pi2");
|
||||
expect(bin?.type).toBe("file");
|
||||
expect(bin?.mode & 0o777).toBe(0o755);
|
||||
expect(bin?.data.toString("utf8")).toContain("pi2 0.1.7");
|
||||
expect(entries.find((entry) => entry.path === "share")?.type).toBe("directory");
|
||||
});
|
||||
|
||||
it("rejects a corrupted header checksum", () => {
|
||||
const archive = gunzipSync(buildReleaseArchive());
|
||||
// Flip a byte inside the first header's name field.
|
||||
archive[3] = (archive[3] ?? 0) ^ 0xff;
|
||||
expect(() => parseTar(archive)).toThrow(TarError);
|
||||
});
|
||||
|
||||
it("refuses symlink entries instead of skipping them", () => {
|
||||
const archive = buildTar([{ name: "bin/pi2", data: "x", type: "symlink" }]);
|
||||
expect(() => parseTar(archive)).toThrow(/unsupported entry type/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractTarGz", () => {
|
||||
it("writes the tree, keeping the executable bit", () => {
|
||||
const dest = join(tmp(), "tree");
|
||||
extractTarGz(buildReleaseArchive("0.1.8"), dest);
|
||||
expect(readFileSync(join(dest, "LICENSE"), "utf8")).toBe("MIT\n");
|
||||
expect(statSync(join(dest, "bin", "pi2")).mode & 0o777).toBe(0o755);
|
||||
expect(readFileSync(join(dest, "share", "pi2d", "web", "dist", "index.html"), "utf8")).toContain("<html>");
|
||||
});
|
||||
|
||||
it("rejects a path traversal", () => {
|
||||
const dest = join(tmp(), "tree");
|
||||
expect(() => extractTarGz(buildTarGz([{ name: "../../etc/passwd", data: "x" }]), dest)).toThrow(
|
||||
/path traversal/,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects an absolute path", () => {
|
||||
const dest = join(tmp(), "tree");
|
||||
expect(() => extractTarGz(buildTarGz([{ name: "/etc/passwd", data: "x" }]), dest)).toThrow(
|
||||
/absolute path/,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("safeEntryPath", () => {
|
||||
it("keeps nested entries under the destination", () => {
|
||||
expect(safeEntryPath("/tmp/x", "a/b/c")).toBe("/tmp/x/a/b/c");
|
||||
});
|
||||
|
||||
it("rejects escapes", () => {
|
||||
expect(() => safeEntryPath("/tmp/x", "../y")).toThrow(TarError);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user