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:
yuez committed 2026-10-29 16:42:57 +08:00
1 parent 29aee26733
commit 8fb535f7f3
20 files changed
+2557 -43

No files matched your search

+33
View File
@@ -49,6 +49,7 @@ import {
import { diagnose, formatReport, reportToJson, type DoctorReport } from "./doctor.js";
import { runStop, STOP_USAGE, type StopOptions } from "./stop.js";
import { runConfig, CONFIG_USAGE, type RunConfigOptions } from "./config.js";
import { runUpdate, UPDATE_USAGE } from "./update.js";
import {
parseServiceArgs,
runServiceCommand,
@@ -86,6 +87,7 @@ Usage:
pi2 install-service [--dry-run|--write] systemd user unit / LaunchAgent
pi2 uninstall-service [--dry-run|--write] remove the unit
pi2 service status|start|stop|enable|disable control that unit (status [--json])
pi2 update [--check|--dry-run] upgrade a standalone (curl installer) pi2 in place
pi2 --version | --help
\`pi2 stop\` / \`pi2 daemon stop\` flags: -f, --force sends SIGKILL if the daemon
@@ -894,6 +896,37 @@ export async function main(argv: readonly string[], options: Pi2Options = {}): P
};
return command === "install-service" ? runInstallService(serviceOptions) : runUninstallService(serviceOptions);
}
case "update": {
let parsed;
try {
parsed = parseArgs(rest, {
values: ["--version"],
booleans: [
"--check",
"--dry-run",
"--force",
"--json",
"--require-attestation",
"--skip-attestation",
"--help",
],
aliases: { "-h": "--help" },
});
} catch (error) {
if (error instanceof UsageError) throw new UsageError(error.message, UPDATE_USAGE);
throw error;
}
if (boolFlag(parsed.flags, "--help")) {
out(UPDATE_USAGE);
return 0;
}
return await runUpdate({
argv: rest,
print: out,
warn: err,
...(options.env === undefined ? {} : { env: options.env }),
});
}
case "service": {
const parsed = parseServiceArgs(rest);
if (parsed.help) {
+7 -2
View File
@@ -8,6 +8,8 @@
* Supports two install shapes:
* 1. Bundled binary (`bun build --compile`): invokes the compiled executable directly
* (`ExecStart=<execPath> daemon --foreground` or `ProgramArguments = [execPath, "daemon", "--foreground"]`).
* For a curl-channel install `defaultServicePaths()` passes `<prefix>/current/bin/pi2`,
* so the unit survives `pi2 update`.
* 2. Node / script: invokes node with the CLI entrypoint script
* (`ExecStart=<nodePath> <scriptPath> daemon --foreground`).
*
@@ -21,7 +23,7 @@ import { fileURLToPath } from "node:url";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { stateDir } from "../core/paths.js";
import { executablePath, isBundledRuntime } from "../core/install.js";
import { executablePath, isBundledRuntime, stableExecutablePath } from "../core/install.js";
export type ServicePlatform = "linux" | "darwin";
@@ -76,7 +78,10 @@ export function defaultScriptPath(): string {
export function defaultServicePaths(overrides: Partial<ServicePaths> = {}): ServicePaths {
return {
bundled: isBundledRuntime(),
execPath: executablePath(),
// The versioned layout's `<prefix>/current/bin/pi2`, so an update does
// not leave `ExecStart` pointing at a version directory that the pruner
// deletes two releases later. Flat installs resolve to the binary itself.
execPath: stableExecutablePath(),
nodePath: process.execPath,
scriptPath: defaultScriptPath(),
envFile: DEFAULT_SYSTEMD_ENV_FILE,
+502
View File
@@ -0,0 +1,502 @@
/**
* `pi2 update` — the standalone (curl installer) channel's self-updater.
*
* Scope is deliberate (ADR 0003): only a compiled binary installed by
* `scripts/install.sh` may update itself. npm, Homebrew and the AUR are told to
* use their own package manager — `pi2` cannot safely rewrite a tree it does not
* own, and the receipt says which tree that is.
*
* Property preserved throughout: **nothing is swapped until the download is
* verified, extracted, and executed once**. A failed update leaves `current`
* exactly where it was.
*/
import { spawnSync } from "node:child_process";
import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { realpathSync } from "node:fs";
import { join } from "node:path";
import {
buildTarget,
executablePath,
inferBuildTarget,
isBundledRuntime,
version as runningVersion,
versionedLayoutFor,
} from "../core/install.js";
import { stateDir } from "../core/paths.js";
import {
assetName,
assetUrl,
channelUpgradeCommand,
checksumsUrl,
compareVersions,
matchesChecksum,
normalizeVersion,
parseChecksums,
resolveLatestVersion,
RELEASE_REPO,
type UpdateCache,
} from "../core/release.js";
import {
applyVersionedInstall,
readReceipt,
removeStaleStaging,
stagingDir,
type InstallReceipt,
} from "../core/self-update.js";
import { extractTarGz } from "../core/tarball.js";
import { defaultServicePaths, launchAgentDir, LAUNCHD_PLIST_NAME, SYSTEMD_UNIT_NAME, systemdUserDir } from "./service.js";
import { boolFlag, CliError, parseArgs, stringFlag, UsageError } from "./util.js";
export const UPDATE_USAGE = `pi2 update — upgrade a standalone (curl installer) pi2 in place
Usage:
pi2 update [options]
pi2 update --check
Downloads the matching release asset into <prefix>/versions/<version>, verifies
its SHA256 digest (and, when \`gh\` is available, its SLSA build provenance),
runs the new binary once, then switches <prefix>/current and rewrites the install
receipt. The previous version is kept for one-step rollback.
Options:
--check report the latest version and exit (no download)
--dry-run print the download/verify/swap plan, change nothing
--version <version> update to (or back to) a specific version; a downgrade
also needs --force
--force reinstall even when the target is already installed
--json machine-readable result (for editors and scripts)
--require-attestation fail when the SLSA provenance cannot be verified
--skip-attestation never call \`gh attestation verify\`
-h, --help print this help and exit
Environment:
PI2_BASE_URL release asset base URL (mirror or local fixture)
PI2_UPDATE_CACHE_TTL seconds a version lookup stays cached (default 86400)
Only the standalone channel can self-update. npm (\`npm i -g @yuez/pi2d\`),
Homebrew (\`brew upgrade pi2d\`) and the AUR (paru/yay) own their own trees, and
\`pi2 update\` refuses them with the command to use instead.`;
const CACHE_FILE = "update-check.json";
export interface ExecResult {
code: number;
stdout: string;
stderr: string;
}
export type UpdateExec = (argv: readonly string[]) => ExecResult;
export interface UpdateDeps {
/** Injected in tests; defaults to the global `fetch`. */
fetchImpl?: typeof fetch;
/** Runs `gh attestation verify` and the staged `--version` smoke test. */
exec?: UpdateExec;
now?: () => Date;
execPath?: string;
isBundled?: () => boolean;
env?: NodeJS.ProcessEnv;
stateDirPath?: string;
/** Version of the running binary (defaults to the build-time/`package.json` version). */
currentVersion?: string;
print?: (line: string) => void;
warn?: (line: string) => void;
}
export interface UpdateOptions extends UpdateDeps {
argv: readonly string[];
}
export interface UpdateResult {
action: "checked" | "up-to-date" | "planned" | "installed";
current: string;
latest: string;
installer: string;
prefix: string;
asset: string;
url: string;
attestation: "verified" | "skipped" | "unavailable" | "failed";
previous?: string;
restart: string;
updatable: boolean;
}
export interface ParsedUpdateArgs {
check: boolean;
dryRun: boolean;
force: boolean;
json: boolean;
requireAttestation: boolean;
skipAttestation: boolean;
help: boolean;
version?: string;
}
export function parseUpdateArgs(argv: readonly string[]): ParsedUpdateArgs {
const parsed = parseArgs(argv, {
values: ["--version"],
booleans: [
"--check",
"--dry-run",
"--force",
"--json",
"--require-attestation",
"--skip-attestation",
"--help",
],
aliases: { "-h": "--help" },
});
if (parsed.positionals.length > 0) {
throw new UsageError(`unexpected argument "${parsed.positionals[0]}"`, UPDATE_USAGE);
}
const parsedArgs: ParsedUpdateArgs = {
check: boolFlag(parsed.flags, "--check"),
dryRun: boolFlag(parsed.flags, "--dry-run"),
force: boolFlag(parsed.flags, "--force"),
json: boolFlag(parsed.flags, "--json"),
requireAttestation: boolFlag(parsed.flags, "--require-attestation"),
skipAttestation: boolFlag(parsed.flags, "--skip-attestation"),
help: boolFlag(parsed.flags, "--help"),
};
const pinned = stringFlag(parsed.flags, "--version");
if (pinned !== undefined) parsedArgs.version = normalizeVersion(pinned);
return parsedArgs;
}
function realpathOrSelf(path: string): string {
try {
return realpathSync(path);
} catch {
return path;
}
}
/** How to restart whatever is running the old binary. */
export function restartHint(platform: string = process.platform): string {
if (platform === "linux" || platform === "darwin") {
const paths = defaultServicePaths();
const unit =
platform === "darwin"
? join(launchAgentDir(paths), LAUNCHD_PLIST_NAME)
: join(systemdUserDir(paths), SYSTEMD_UNIT_NAME);
if (existsSync(unit)) return "pi2 service stop && pi2 service start";
}
return "pi2 stop # :PiWeb starts a fresh daemon next time";
}
function readCache(file: string): UpdateCache | undefined {
try {
const parsed = JSON.parse(readFileSync(file, "utf8")) as Partial<UpdateCache>;
if (typeof parsed.version !== "string" || typeof parsed.checkedAt !== "string") return undefined;
const cache: UpdateCache = { version: parsed.version, checkedAt: parsed.checkedAt };
if (typeof parsed.etag === "string") cache.etag = parsed.etag;
return cache;
} catch {
return undefined;
}
}
function writeCache(file: string, cache: UpdateCache): void {
try {
writeFileSync(file, `${JSON.stringify(cache, null, 2)}\n`, "utf8");
} catch {
// A cache write failure must never fail an update.
}
}
/** Resolve the receipt, refusing every channel that is not ours. */
export function resolveInstall(execPath: string, bundled: boolean): { receipt: InstallReceipt } {
if (!bundled) {
throw new CliError(
"pi2 update only upgrades a standalone (curl installer) pi2; this one runs under Node.\n" +
"Upgrade it with the package manager that installed it: npm i -g @yuez/pi2d@latest",
);
}
const layout = versionedLayoutFor(execPath);
if (layout === undefined) {
throw new CliError(
"this pi2 is not in the standalone layout (<prefix>/versions/<version>/bin/pi2).\n" +
"If the curl installer put it here before 0.1.7, re-run the installer once to migrate:\n" +
" curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh",
);
}
const { receipt, error } = readReceipt(layout.prefix);
if (receipt === undefined) {
throw new CliError(
`cannot update: ${error ?? "no install receipt"}.\n` +
"Homebrew, the AUR and npm own their own trees; use the command that installed pi2:\n" +
` ${channelUpgradeCommand("unknown")}\n` +
"A curl install from before 0.1.7 has no receipt; re-run the installer once to migrate:\n" +
" curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh",
);
}
if (receipt.installer !== "curl") {
throw new CliError(
`pi2 was installed by ${receipt.installer}; let it upgrade itself:\n ${channelUpgradeCommand(receipt.installer)}`,
);
}
if (realpathOrSelf(receipt.bin) !== realpathOrSelf(execPath)) {
throw new CliError(
`another copy of pi2 is running: ${execPath} is not the binary the receipt describes (${receipt.bin}).\n` +
"Remove one of them, or re-run the installer to rewrite the receipt.",
);
}
return { receipt };
}
async function download(url: string, fetchImpl: typeof fetch, what: string): Promise<Uint8Array> {
let response: Response;
try {
response = await fetchImpl(url);
} catch (error) {
throw new CliError(`could not download ${what} from ${url}: ${error instanceof Error ? error.message : String(error)}`);
}
if (!response.ok) {
throw new CliError(
`could not download ${what} from ${url}: HTTP ${response.status} ${response.statusText}\n` +
"The release may not publish this platform; check https://github.com/" +
RELEASE_REPO +
"/releases",
);
}
return new Uint8Array(await response.arrayBuffer());
}
function verifyAttestation(
exec: UpdateExec,
file: string,
mode: ParsedUpdateArgs,
): "verified" | "skipped" | "unavailable" | "failed" {
if (mode.skipAttestation) return "skipped";
if (exec(["gh", "--version"]).code !== 0) {
if (mode.requireAttestation) {
throw new CliError(
"--require-attestation was passed but `gh` is not installed; install it from https://cli.github.com",
);
}
return "unavailable";
}
const result = exec(["gh", "attestation", "verify", file, "--repo", RELEASE_REPO]);
if (result.code === 0) return "verified";
if (mode.requireAttestation) {
throw new CliError(
`SLSA provenance verification failed for ${file}: ${result.stderr.trim() || `gh exited ${result.code}`}`,
);
}
return "failed";
}
function formatHuman(result: UpdateResult): string {
const lines: string[] = [];
if (result.action === "up-to-date") {
lines.push(`pi2 ${result.current} is up to date (latest release: ${result.latest}).`);
return lines.join("\n");
}
if (result.action === "checked") {
lines.push(`pi2 ${result.current} — latest release: ${result.latest}`);
lines.push(
result.updatable
? "Run `pi2 update` to install it."
: `Already on ${result.latest}; pass --force to reinstall.`,
);
return lines.join("\n");
}
if (result.action === "planned") {
lines.push(`would install pi2 ${result.latest} (current ${result.current})`);
lines.push(` asset: ${result.asset}`);
lines.push(` from: ${result.url}`);
lines.push(` prefix: ${result.prefix}`);
lines.push(` receipt: ${result.installer}`);
return lines.join("\n");
}
lines.push(`pi2 ${result.current} → ${result.latest} installed`);
lines.push(` prefix: ${result.prefix}`);
lines.push(` asset: ${result.asset}`);
lines.push(` digest: verified (SHA256SUMS)`);
lines.push(
` proof: ${
result.attestation === "verified"
? "SLSA build provenance verified"
: result.attestation === "skipped"
? "skipped (--skip-attestation)"
: result.attestation === "unavailable"
? "not checked (install the GitHub CLI to verify provenance)"
: "could not be verified; download the binary again if that is unexpected"
}`,
);
if (result.previous !== undefined && result.previous !== result.latest) {
lines.push(` kept: ${result.previous} for one-step rollback (--version ${result.previous})`);
}
lines.push("");
lines.push(`Restart the daemon to use it: ${result.restart}`);
return lines.join("\n");
}
async function performUpdate(parsed: ParsedUpdateArgs, deps: UpdateDeps): Promise<UpdateResult> {
const print = deps.print ?? ((line: string) => process.stdout.write(`${line}\n`));
const warn = deps.warn ?? ((line: string) => process.stderr.write(`${line}\n`));
const env = deps.env ?? process.env;
const fetchImpl = deps.fetchImpl ?? fetch;
const now = deps.now ?? (() => new Date());
const execPath = deps.execPath ?? executablePath();
const bundled = deps.isBundled === undefined ? isBundledRuntime() : deps.isBundled();
const exec = deps.exec ?? ((argv: readonly string[]) => {
const result = spawnSync(argv[0] as string, argv.slice(1), { encoding: "utf8" });
return {
code: result.status ?? 1,
stdout: result.stdout ?? "",
stderr: result.stderr ?? result.error?.message ?? "",
};
});
const current = deps.currentVersion ?? runningVersion();
const { receipt } = resolveInstall(execPath, bundled);
const prefix = receipt.prefix;
const target = buildTarget() ?? inferBuildTarget();
const asset = assetName(parsed.version ?? "0.0.0", target);
const restart = restartHint();
// 1. Which version are we aiming at?
let latest: string;
if (parsed.version !== undefined) {
latest = parsed.version;
} else {
const cacheFile = join(deps.stateDirPath ?? stateDir(), CACHE_FILE);
const cached = readCache(cacheFile);
const ttlRaw = env.PI2_UPDATE_CACHE_TTL;
const ttlSeconds = ttlRaw === undefined ? undefined : Number(ttlRaw);
const lookup = await resolveLatestVersion({
fetchImpl,
...(cached === undefined ? {} : { cache: cached }),
...(ttlSeconds !== undefined && Number.isFinite(ttlSeconds) ? { ttlMs: ttlSeconds * 1000 } : {}),
now: now(),
});
writeCache(cacheFile, lookup.cache);
latest = lookup.version;
}
const updatable = compareVersions(latest, current) > 0;
if (!parsed.force) {
if (compareVersions(latest, current) < 0) {
throw new CliError(
`refusing to downgrade pi2 ${current} → ${latest}; pass --force to do it anyway`,
);
}
if (compareVersions(latest, current) === 0) {
return {
action: "up-to-date",
current,
latest,
installer: String(receipt.installer),
prefix,
asset: assetName(latest, target),
url: assetUrl(latest, target, env.PI2_BASE_URL),
attestation: "skipped",
restart,
updatable: false,
};
}
}
const resolvedAsset = assetName(latest, target);
const url = assetUrl(latest, target, env.PI2_BASE_URL);
const base: UpdateResult = {
action: parsed.check ? "checked" : parsed.dryRun ? "planned" : "installed",
current,
latest,
installer: String(receipt.installer),
prefix,
asset: resolvedAsset,
url,
attestation: "skipped",
restart,
updatable,
};
if (parsed.check) return base;
if (parsed.dryRun) {
if (!parsed.json) print(formatHuman(base));
return base;
}
// 2. Fetch and verify.
// stderr: `--json` callers parse stdout
warn(`pi2 update: downloading ${resolvedAsset}…`);
const sumsBytes = await download(checksumsUrl(latest, env.PI2_BASE_URL), fetchImpl, "SHA256SUMS");
const checksums = parseChecksums(new TextDecoder().decode(sumsBytes));
const expected = checksums.get(resolvedAsset);
if (expected === undefined) {
throw new CliError(
`SHA256SUMS for ${latest} has no entry for ${resolvedAsset}; the release does not publish this platform`,
);
}
const archive = await download(url, fetchImpl, resolvedAsset);
if (!matchesChecksum(archive, expected)) {
throw new CliError(`checksum mismatch for ${resolvedAsset}: the download does not match ${expected}`);
}
// 3. Stage, verify provenance, smoke-test.
removeStaleStaging(prefix);
const staging = stagingDir(prefix);
const archiveFile = `${staging}.tar.gz`;
let attestation: UpdateResult["attestation"] = "skipped";
try {
writeFileSync(archiveFile, archive);
attestation = verifyAttestation(exec, archiveFile, parsed);
if (attestation === "failed") {
warn("pi2 update: SLSA provenance could not be verified; continuing (pass --require-attestation to make this fatal)");
}
extractTarGz(archive, staging);
const stagedBin = join(staging, "bin", "pi2");
if (!existsSync(stagedBin)) throw new CliError("the release asset has no bin/pi2");
const probe = exec([stagedBin, "--version"]);
const reported = /\b(\d+\.\d+\.\d+)\b/.exec(probe.stdout) ?? /\b(\d+\.\d+\.\d+)\b/.exec(probe.stderr);
if (probe.code !== 0) {
throw new CliError(`the downloaded binary does not run (exit ${probe.code}): ${probe.stderr.trim()}`);
}
if (reported?.[1] !== undefined && normalizeVersion(reported[1]) !== latest) {
throw new CliError(
`the downloaded binary reports ${reported[1]}, expected ${latest}; the release asset is inconsistent`,
);
}
// 4. Swap and record.
const applied = applyVersionedInstall({
prefix,
version: latest,
stagedDir: staging,
asset: resolvedAsset,
sha256: expected,
now: now(),
});
const result: UpdateResult = {
...base,
attestation,
...(applied.previous === undefined ? {} : { previous: applied.previous }),
};
if (!parsed.json) print(formatHuman(result));
return result;
} finally {
rmSync(staging, { recursive: true, force: true });
rmSync(archiveFile, { force: true });
}
}
/** `pi2 update …` */
export async function runUpdate(options: UpdateOptions): Promise<number> {
const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`));
let parsed: ParsedUpdateArgs;
try {
parsed = parseUpdateArgs(options.argv);
} catch (error) {
if (error instanceof UsageError) throw new UsageError(error.message, UPDATE_USAGE);
throw error;
}
if (parsed.help) {
print(UPDATE_USAGE);
return 0;
}
const result = await performUpdate(parsed, options);
if (parsed.json) print(JSON.stringify(result, null, 2));
else if (result.action === "checked" || result.action === "up-to-date") print(formatHuman(result));
return 0;
}
+89 -3
View File
@@ -13,8 +13,8 @@
* needs to answer "what am I, where are my files" lives here, so that no other
* module has to guess from `import.meta.url` alone.
*/
import { existsSync, readFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { existsSync, readFileSync, realpathSync } from "node:fs";
import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
/**
@@ -24,6 +24,15 @@ import { fileURLToPath } from "node:url";
*/
declare const PI2_BUILD_VERSION: string | undefined;
/**
* Replaced textually by `scripts/build-binary.sh`: the release asset suffix of
* this artifact (`linux-x64`, `linux-arm64-musl`, `darwin-arm64`, …).
*
* `pi2 update` downloads the asset its *own* build target names instead of
* re-probing libc at runtime — the binary already knows what it was built for.
*/
declare const PI2_BUILD_TARGET: string | undefined;
/** Fallback when neither the build-time define nor `package.json` is readable. */
export const UNKNOWN_VERSION = "0.0.0";
@@ -60,7 +69,84 @@ export function executablePath(): string {
return process.execPath;
}
/** `<repo>/package.json` next to `dist/cli/`. Absent inside a compiled binary. */
/** `linux-x64`, `darwin-arm64`, `linux-x64-musl` — the release asset suffix. */
export function buildTarget(): string | undefined {
return typeof PI2_BUILD_TARGET === "string" && PI2_BUILD_TARGET !== "" ? PI2_BUILD_TARGET : undefined;
}
/**
* Asset suffix for a runtime that has no `PI2_BUILD_TARGET` (a Node/npm run, or
* a binary built before the define existed). Only a fallback: a musl build is
* indistinguishable from a glibc one by `process.platform` alone, so every
* release artifact carries the define.
*/
export function inferBuildTarget(
platform: string = process.platform,
arch: string = process.arch,
musl = false,
): string {
const os = platform === "darwin" ? "darwin" : "linux";
const cpu = arch === "arm64" ? "arm64" : "x64";
return os === "linux" && musl ? `linux-${cpu}-musl` : `${os}-${cpu}`;
}
/**
* A curl-channel install: one immutable tree per version under `<prefix>/versions`
* with `<prefix>/current` pointing at the live one (see `docs/adr/0003-self-update.md`).
*/
export interface VersionedLayout {
/** `<prefix>` — `~/.local/lib/pi2d` by default. */
prefix: string;
versionsDir: string;
versionDir: string;
/** `<prefix>/current`, a relative symlink to `versions/<version>`. */
current: string;
version: string;
}
/** Resolve symlinks so `~/.local/bin/pi2` and `current/bin/pi2` all answer for themselves. */
function realpathOrSelf(path: string): string {
try {
return realpathSync(path);
} catch {
return resolve(path);
}
}
/**
* Recognise `<prefix>/versions/<version>/bin/pi2`, or `undefined` for the flat
* layout, a package-manager install or an npm checkout.
*/
export function versionedLayoutFor(execPath: string = executablePath()): VersionedLayout | undefined {
const exe = realpathOrSelf(execPath);
const versionDir = dirname(dirname(exe));
const versionsDir = dirname(versionDir);
if (basename(versionsDir) !== "versions") return undefined;
if (basename(exe) !== "pi2") return undefined;
const version = basename(versionDir);
if (version === "" || version.startsWith(".")) return undefined;
return {
prefix: dirname(versionsDir),
versionsDir,
versionDir,
current: join(dirname(versionsDir), "current"),
version,
};
}
/**
* The path a service unit and a symlink should point at: the `current/bin/pi2`
* indirection when this is a versioned install, otherwise the executable itself.
*
* Rendering `<prefix>/versions/<v>/bin/pi2` into `ExecStart` would break the
* unit on every update, so `pi2 install-service` must go through this.
*/
export function stableExecutablePath(execPath: string = executablePath()): string {
const layout = versionedLayoutFor(execPath);
return layout === undefined ? execPath : join(layout.current, "bin", "pi2");
}
/** `package.json` next to `dist/cli/`. Absent inside a compiled binary. */
function packageJsonVersion(): string | undefined {
try {
const file = fileURLToPath(new URL("../../package.json", import.meta.url));
+227
View File
@@ -0,0 +1,227 @@
/**
* Release metadata for `pi2 update`: which version is out, which asset belongs
* to this artifact, and does the download match its published digest.
*
* Everything here is pure or injectable (`fetchImpl`, `now`, `cache`) so the
* update path stays testable without a network, matching `test/`'s hermetic
* rule. The GitHub API is unauthenticated (60 requests/hour), which is why the
* version lookup is ETag-cached and has a redirect fallback: `pi2 update
* --check` must not be able to burn the budget on its own.
*/
/** `owner/repo` — also the identity `gh attestation verify` checks. */
export const RELEASE_REPO = "zgs225/pi2d";
export const RELEASES_API_URL = `https://api.github.com/repos/${RELEASE_REPO}/releases/latest`;
/** `https://github.com/<owner>/<repo>/releases` — assets live under `download/v<version>/`. */
export const RELEASE_DOWNLOAD_BASE = `https://github.com/${RELEASE_REPO}/releases/download`;
/** 24 h: a self-updater that phones home on every invocation is rude and rate-limited. */
export const DEFAULT_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
export interface UpdateCache {
etag?: string;
version: string;
/** ISO timestamp of the last check that produced `version`. */
checkedAt: string;
}
export interface LatestVersionOptions {
fetchImpl?: typeof fetch;
cache?: UpdateCache;
ttlMs?: number;
now?: Date;
apiUrl?: string;
downloadBase?: string;
}
export interface LatestVersionResult {
version: string;
/** Fresh cache state to persist (the caller owns the file). */
cache: UpdateCache;
source: "cache" | "api" | "redirect";
}
/** `v0.1.6` → `0.1.6`; already-bare versions pass through. */
export function normalizeVersion(raw: string): string {
const trimmed = raw.trim();
return trimmed.startsWith("v") ? trimmed.slice(1) : trimmed;
}
/** `0.1.6` → `[0,1,6]`; anything without three numbers is unparsable. */
export function parseVersionTriplet(raw: string | undefined): [number, number, number] | undefined {
if (raw === undefined) return undefined;
const match = /(\d+)\.(\d+)\.(\d+)/.exec(raw);
if (match === null) return undefined;
return [Number(match[1]), Number(match[2]), Number(match[3])];
}
/** Numeric triplet ordering; unparsable versions sort as `0.0.0`. */
export function compareVersions(left: string, right: string): -1 | 0 | 1 {
const a = parseVersionTriplet(left) ?? [0, 0, 0];
const b = parseVersionTriplet(right) ?? [0, 0, 0];
for (let index = 0; index < 3; index += 1) {
const x = a[index] ?? 0;
const y = b[index] ?? 0;
if (x !== y) return x < y ? -1 : 1;
}
return 0;
}
/** `pi2d-0.1.6-linux-x64.tar.gz` — the asset name `build-binary.sh` produces. */
export function assetName(version: string, target: string): string {
return `pi2d-${normalizeVersion(version)}-${target}.tar.gz`;
}
/** Asset URL: `PI2_BASE_URL` (mirror / offline fixture) wins over GitHub. */
export function assetUrl(version: string, target: string, baseUrl?: string): string {
const asset = assetName(version, target);
const base = (baseUrl ?? `${RELEASE_DOWNLOAD_BASE}/v${normalizeVersion(version)}`).replace(/\/+$/, "");
return `${base}/${asset}`;
}
export function checksumsUrl(version: string, baseUrl?: string): string {
const base = (baseUrl ?? `${RELEASE_DOWNLOAD_BASE}/v${normalizeVersion(version)}`).replace(/\/+$/, "");
return `${base}/SHA256SUMS`;
}
/**
* Parse a `sha256sum`-style file into `name → hex`. `sha256sum -c` writes
* `<hex> <name>`; a leading `*` marks binary mode (also accepted as
* `<hex> *<name>`), and `<name>` may carry a `./` prefix.
*/
export function parseChecksums(text: string): Map<string, string> {
const checksums = new Map<string, string>();
for (const rawLine of text.split(/\r?\n/)) {
const line = rawLine.trim();
if (line === "" || line.startsWith("#")) continue;
const match = /^([0-9a-fA-F]{64})\s+\*?(.+)$/.exec(line);
if (match === null) continue;
const [, digest, rawName] = match;
const name = (rawName ?? "").replace(/^\.\//, "");
if (digest !== undefined && name !== "") checksums.set(name, digest.toLowerCase());
}
return checksums;
}
/** Digest of the bytes, or `undefined` when it cannot be computed. */
export function sha256Hex(bytes: Uint8Array | string): string {
const { createHash } = require("node:crypto") as typeof import("node:crypto");
const hash = createHash("sha256");
hash.update(bytes);
return hash.digest("hex");
}
/** True when `bytes` matches the published digest (case-insensitive). */
export function matchesChecksum(bytes: Uint8Array | string, expected: string): boolean {
return sha256Hex(bytes) === expected.trim().toLowerCase();
}
/** `v0.1.6` out of a GitHub release payload. */
export function parseReleaseTag(payload: unknown): string | undefined {
if (typeof payload !== "object" || payload === null) return undefined;
const tag = (payload as { tag_name?: unknown }).tag_name;
if (typeof tag !== "string" || tag.trim() === "") return undefined;
return normalizeVersion(tag);
}
/** `…/releases/tag/v0.1.6` → `0.1.6` (the `releases/latest` redirect fallback). */
export function parseRedirectVersion(location: string | undefined): string | undefined {
if (location === undefined) return undefined;
const match = /\/releases\/tag\/([^/?#]+)/.exec(location);
return match?.[1] === undefined ? undefined : normalizeVersion(match[1]);
}
function freshCache(cache: UpdateCache | undefined, ttlMs: number, now: Date): boolean {
if (cache === undefined) return false;
const checkedAt = Date.parse(cache.checkedAt);
if (Number.isNaN(checkedAt)) return false;
return now.getTime() - checkedAt < ttlMs;
}
async function fetchLatestFromApi(
fetchImpl: typeof fetch,
apiUrl: string,
etag: string | undefined,
): Promise<{ tag?: string; etag?: string; notModified: boolean }> {
const headers: Record<string, string> = { Accept: "application/vnd.github+json" };
if (etag !== undefined) headers["If-None-Match"] = etag;
const response = await fetchImpl(apiUrl, { headers });
if (response.status === 304) return { notModified: true };
if (!response.ok) throw new Error(`GitHub API ${response.status} ${response.statusText}`);
const payload = (await response.json()) as unknown;
const tag = parseReleaseTag(payload);
if (tag === undefined) throw new Error("GitHub API response has no tag_name");
const nextEtag = response.headers.get("etag") ?? undefined;
return nextEtag === undefined ? { tag, notModified: false } : { tag, etag: nextEtag, notModified: false };
}
async function fetchLatestFromRedirect(fetchImpl: typeof fetch, repo: string): Promise<string> {
const response = await fetchImpl(`https://github.com/${repo}/releases/latest`, {
method: "HEAD",
redirect: "manual",
});
const version = parseRedirectVersion(response.headers.get("location") ?? undefined);
if (version === undefined) {
throw new Error("could not determine the latest release (GitHub API and redirect both failed)");
}
return version;
}
/**
* Latest published version, in this order: fresh cache → GitHub API (with
* `If-None-Match`) → the `releases/latest` redirect. Never throws for a stale
* cache: the caller decides how loud a failure should be.
*/
export async function resolveLatestVersion(options: LatestVersionOptions = {}): Promise<LatestVersionResult> {
const fetchImpl = options.fetchImpl ?? fetch;
const ttlMs = options.ttlMs ?? DEFAULT_CACHE_TTL_MS;
const now = options.now ?? new Date();
const apiUrl = options.apiUrl ?? RELEASES_API_URL;
const cache = options.cache;
if (freshCache(cache, ttlMs, now) && cache !== undefined) {
return { version: cache.version, cache, source: "cache" };
}
try {
const result = await fetchLatestFromApi(fetchImpl, apiUrl, cache?.etag);
if (result.notModified && cache !== undefined) {
const refreshed: UpdateCache = { version: cache.version, checkedAt: now.toISOString() };
if (cache.etag !== undefined) refreshed.etag = cache.etag;
return { version: cache.version, cache: refreshed, source: "api" };
}
const version = result.tag as string;
const next: UpdateCache = { version, checkedAt: now.toISOString() };
if (result.etag !== undefined) next.etag = result.etag;
return { version, cache: next, source: "api" };
} catch (apiError) {
try {
const version = await fetchLatestFromRedirect(fetchImpl, RELEASE_REPO);
return { version, cache: { version, checkedAt: now.toISOString() }, source: "redirect" };
} catch (redirectError) {
throw new Error(
`could not reach GitHub (${describe(apiError)}; ${describe(redirectError)})`,
);
}
}
}
function describe(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
/** The command a package manager owns, for the channels `pi2 update` refuses. */
export function channelUpgradeCommand(installer: string): string {
switch (installer) {
case "brew":
return "brew upgrade pi2d";
case "aur":
return "paru -Syu pi2d-bin # or: yay -Syu pi2d-bin";
case "npm":
return "npm i -g @yuez/pi2d@latest";
default:
return "npm i -g @yuez/pi2d@latest # or: brew upgrade pi2d";
}
}
+272
View File
@@ -0,0 +1,272 @@
/**
* On-disk state of a curl-channel install: the receipt at `<prefix>/install.json`
* and the versioned tree it describes (`docs/adr/0003-self-update.md`).
*
* ```
* <prefix>/versions/<version>/{bin,share,LICENSE} immutable once written
* <prefix>/current -> versions/<version> the only thing that moves
* <prefix>/install.json the receipt
* ```
*
* `install.sh` writes the same shapes with POSIX shell; the two must stay in
* step (a test pins the JSON keys, the installer is exercised by
* `scripts/install.sh`'s own smoke run).
*/
import { existsSync, mkdirSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { basename, dirname, join } from "node:path";
export const RECEIPT_FILE = "install.json";
export const RECEIPT_SCHEMA = 1;
export const VERSIONS_DIR = "versions";
export const CURRENT_LINK = "current";
/** Who installed this tree — the only channel detection that cannot be spoofed. */
export type InstallerChannel = "curl" | "brew" | "aur" | "npm" | "unknown";
export interface InstallReceipt {
schema: number;
installer: InstallerChannel | string;
layout: string;
/** Absolute `<prefix>`. */
prefix: string;
/** Absolute `<prefix>/current`. */
current: string;
version: string;
/** Absolute path of the installed binary *inside* the version tree. */
bin: string;
asset?: string;
sha256?: string;
installed_at?: string;
}
export interface ReceiptReadResult {
receipt?: InstallReceipt;
/** Why the receipt is unusable, when it is. */
error?: string;
}
export function receiptPath(prefix: string): string {
return join(prefix, RECEIPT_FILE);
}
function isString(value: unknown): value is string {
return typeof value === "string" && value !== "";
}
function asReceipt(value: unknown): InstallReceipt | undefined {
if (typeof value !== "object" || value === null) return undefined;
const raw = value as Record<string, unknown>;
if (!isString(raw.prefix) || !isString(raw.version) || !isString(raw.bin)) return undefined;
const receipt: InstallReceipt = {
schema: typeof raw.schema === "number" ? raw.schema : RECEIPT_SCHEMA,
installer: isString(raw.installer) ? raw.installer : "unknown",
layout: isString(raw.layout) ? raw.layout : "versioned",
prefix: raw.prefix,
current: isString(raw.current) ? raw.current : join(raw.prefix, CURRENT_LINK),
version: raw.version,
bin: raw.bin,
};
for (const key of ["asset", "sha256", "installed_at"] as const) {
const field = raw[key];
if (isString(field)) receipt[key] = field;
}
return receipt;
}
/** Read `<prefix>/install.json`. Never throws: a missing/broken receipt is a report. */
export function readReceipt(prefix: string): ReceiptReadResult {
const file = receiptPath(prefix);
if (!existsSync(file)) return { error: `no install receipt at ${file}` };
let parsed: unknown;
try {
parsed = JSON.parse(readFileSync(file, "utf8"));
} catch (error) {
return { error: `${file} is not valid JSON (${error instanceof Error ? error.message : String(error)})` };
}
const receipt = asReceipt(parsed);
if (receipt === undefined) return { error: `${file} is missing prefix/version/bin` };
if (receipt.schema > RECEIPT_SCHEMA) {
return { error: `${file} was written by a newer pi2 (schema ${receipt.schema})` };
}
return { receipt };
}
export interface BuildReceiptOptions {
prefix: string;
version: string;
bin: string;
asset?: string;
sha256?: string;
now?: Date;
installer?: InstallerChannel | string;
}
export function buildReceipt(options: BuildReceiptOptions): InstallReceipt {
const receipt: InstallReceipt = {
schema: RECEIPT_SCHEMA,
installer: options.installer ?? "curl",
layout: "versioned",
prefix: options.prefix,
current: join(options.prefix, CURRENT_LINK),
version: options.version,
bin: options.bin,
installed_at: (options.now ?? new Date()).toISOString().replace(/\.\d+Z$/, "Z"),
};
if (options.asset !== undefined) receipt.asset = options.asset;
if (options.sha256 !== undefined) receipt.sha256 = options.sha256;
return receipt;
}
/** Write the receipt through a temp file + rename, so it is never half-written. */
export function writeReceiptAtomic(prefix: string, receipt: InstallReceipt): string {
const file = receiptPath(prefix);
mkdirSync(dirname(file), { recursive: true });
const tmp = `${file}.tmp.${process.pid}.${Date.now()}`;
writeFileSync(tmp, `${JSON.stringify(receipt, null, 2)}\n`, "utf8");
renameSync(tmp, file);
return file;
}
function readCurrentTarget(prefix: string): string | undefined {
try {
return readlinkSync(join(prefix, CURRENT_LINK));
} catch {
return undefined;
}
}
/** `versions/<version>` → `<version>`; anything else is `undefined`. */
export function currentVersion(prefix: string): string | undefined {
const target = readCurrentTarget(prefix);
if (target === undefined) return undefined;
const parts = target.split("/").filter((part) => part !== "" && part !== ".");
if (parts.length !== 2 || parts[0] !== VERSIONS_DIR) return undefined;
return parts[1];
}
/**
* Point `<prefix>/current` at `target` atomically: a fresh symlink in the same
* directory, then `rename(2)` over the old one. The live daemon keeps its old
* inode, so a running process is never disturbed.
*/
export function switchCurrent(prefix: string, target: string): void {
const link = join(prefix, CURRENT_LINK);
const tmp = join(prefix, `.${CURRENT_LINK}.${process.pid}.${Date.now()}`);
rmSync(tmp, { force: true });
symlinkSync(target, tmp);
renameSync(tmp, link);
}
/** A staging directory inside `<prefix>/versions` — same filesystem, so renames are atomic. */
export function stagingDir(prefix: string, label = "update"): string {
return join(prefix, VERSIONS_DIR, `.staging-${label}-${process.pid}-${Date.now()}`);
}
/** Delete staging directories left behind by a crashed run. */
export function removeStaleStaging(prefix: string): string[] {
const dir = join(prefix, VERSIONS_DIR);
if (!existsSync(dir)) return [];
const removed: string[] = [];
for (const entry of readdirSync(dir)) {
if (!entry.startsWith(".staging-")) continue;
rmSync(join(dir, entry), { recursive: true, force: true });
removed.push(entry);
}
return removed;
}
export interface ApplyVersionedInstallOptions {
prefix: string;
version: string;
/** Directory holding a freshly extracted `bin/`, `share/`, `LICENSE`. */
stagedDir: string;
asset?: string;
sha256?: string;
now?: Date;
}
export interface ApplyVersionedInstallResult {
versionDir: string;
/** The version `current` pointed at before the switch, when it pointed anywhere. */
previous?: string;
receiptFile: string;
removed: string[];
}
/**
* Move an extracted tree into `<prefix>/versions/<version>`, switch `current`,
* write the receipt, prune. A failure at any step restores the previous
* `current` target and the tree it replaced, so an interrupted update cannot
* leave a half-installed version behind.
*/
export function applyVersionedInstall(options: ApplyVersionedInstallOptions): ApplyVersionedInstallResult {
const { prefix, version, stagedDir } = options;
const versionsDir = join(prefix, VERSIONS_DIR);
mkdirSync(versionsDir, { recursive: true });
const versionDir = join(versionsDir, version);
const previous = currentVersion(prefix);
const previousTarget = readCurrentTarget(prefix);
const backup = `${versionDir}.old.${process.pid}.${Date.now()}`;
const replaced = existsSync(versionDir);
if (replaced) renameSync(versionDir, backup);
let switched = false;
try {
renameSync(stagedDir, versionDir);
switchCurrent(prefix, `${VERSIONS_DIR}/${version}`);
switched = true;
const receipt = buildReceipt({
prefix,
version,
bin: join(versionDir, "bin", "pi2"),
...(options.asset === undefined ? {} : { asset: options.asset }),
...(options.sha256 === undefined ? {} : { sha256: options.sha256 }),
...(options.now === undefined ? {} : { now: options.now }),
});
const receiptFile = writeReceiptAtomic(prefix, receipt);
if (replaced) rmSync(backup, { recursive: true, force: true });
const keep = [version];
if (previous !== undefined && previous !== version) keep.push(previous);
const removed = pruneVersions(prefix, keep);
return {
versionDir,
...(previous === undefined ? {} : { previous }),
receiptFile,
removed,
};
} catch (error) {
if (switched && previousTarget !== undefined) {
try {
switchCurrent(prefix, previousTarget);
} catch {
// Best effort: the caller reports the original failure.
}
}
rmSync(versionDir, { recursive: true, force: true });
if (replaced && existsSync(backup)) renameSync(backup, versionDir);
throw error;
}
}
/** Delete every version tree except `keep`, skipping dot entries. */
export function pruneVersions(prefix: string, keep: readonly string[]): string[] {
const versionsDir = join(prefix, VERSIONS_DIR);
if (!existsSync(versionsDir)) return [];
const keepSet = new Set(keep);
const removed: string[] = [];
for (const entry of readdirSync(versionsDir)) {
if (entry.startsWith(".")) continue;
if (keepSet.has(entry)) continue;
rmSync(join(versionsDir, entry), { recursive: true, force: true });
removed.push(entry);
}
return removed;
}
/** `<prefix>/versions/<version>` → `<version>`; used to spot "another copy is running". */
export function versionOfBinary(bin: string): string | undefined {
const versionDir = dirname(dirname(bin));
if (basename(dirname(versionDir)) !== VERSIONS_DIR) return undefined;
return basename(versionDir);
}
+199
View File
@@ -0,0 +1,199 @@
/**
* A dependency-free `tar.gz` reader, for `pi2 update`.
*
* The standalone channel ships `<bin>/pi2` plus `<share>/pi2d/web/dist` inside a
* tarball, and the updater has to unpack it without a `tar` subprocess: tests
* must stay hermetic (`AGENTS.md` hard rule 5), and the binary should not depend
* on a shell tool being present.
*
* Only what `scripts/build-binary.sh` produces is supported: regular files and
* directories, ustar/PAX/GNU headers. Symlinks, hardlinks, devices and sparse
* entries are rejected rather than silently skipped — an archive that contains
* them is not one of ours.
*/
import { chmodSync, mkdirSync, writeFileSync } from "node:fs";
import { dirname, isAbsolute, join, normalize, sep } from "node:path";
import { gunzipSync } from "node:zlib";
const BLOCK = 512;
export class TarError extends Error {
constructor(message: string) {
super(message);
this.name = "TarError";
}
}
export interface TarEntry {
/** Relative path, without a leading `./` or `/`. */
path: string;
type: "file" | "directory";
mode: number;
mtime: number;
data: Buffer;
}
function readString(header: Buffer, offset: number, length: number): string {
const slice = header.subarray(offset, offset + length);
const end = slice.indexOf(0);
return (end === -1 ? slice : slice.subarray(0, end)).toString("utf8");
}
/** Octal field; GNU writes space/NUL padded values, `base-256` for huge sizes. */
function readNumber(header: Buffer, offset: number, length: number): number {
const slice = header.subarray(offset, offset + length);
if ((slice[0] ?? 0) & 0x80) {
// base-256 (GNU): the remaining bytes are a big-endian integer.
let value = 0;
for (let index = 1; index < slice.length; index += 1) value = value * 256 + (slice[index] ?? 0);
return value;
}
const text = readString(header, offset, length).trim();
if (text === "") return 0;
const parsed = Number.parseInt(text, 8);
if (Number.isNaN(parsed)) throw new TarError(`bad octal field at offset ${offset}: "${text}"`);
return parsed;
}
function headerChecksumMatches(header: Buffer): boolean {
const expected = readNumber(header, 148, 8);
let sum = 0;
for (let index = 0; index < BLOCK; index += 1) {
sum += index >= 148 && index < 156 ? 0x20 : (header[index] ?? 0);
}
return sum === expected;
}
/** `path=…` records out of a PAX extended header body. */
function parsePax(data: Buffer): Map<string, string> {
const records = new Map<string, string>();
let offset = 0;
while (offset < data.length) {
const space = data.indexOf(0x20, offset);
if (space === -1) break;
const length = Number.parseInt(data.subarray(offset, space).toString("utf8"), 10);
if (!Number.isFinite(length) || length <= 0) break;
const record = data.subarray(space + 1, offset + length).toString("utf8");
const end = record.indexOf("\n");
const body = end === -1 ? record : record.slice(0, end);
const equals = body.indexOf("=");
if (equals > 0) records.set(body.slice(0, equals), body.slice(equals + 1));
offset += length;
}
return records;
}
function joinPath(prefix: string, name: string): string {
return prefix === "" ? name : `${prefix}/${name}`;
}
/**
* Walk a tarball and return its entries in archive order. Throws `TarError` for
* anything structurally wrong (bad header checksum, truncated data, unsupported
* entry type).
*/
export function parseTar(archive: Buffer): TarEntry[] {
const entries: TarEntry[] = [];
let offset = 0;
// Carried over from a `x` (per-entry) / `L` (GNU long name) header.
let nextPax: Map<string, string> | undefined;
let nextLongName: string | undefined;
while (offset + BLOCK <= archive.length) {
const header = archive.subarray(offset, offset + BLOCK);
if (header.every((byte) => byte === 0)) break;
if (!headerChecksumMatches(header)) {
throw new TarError(`header checksum mismatch at offset ${offset}`);
}
const typeflag = String.fromCharCode(header[156] ?? 0);
const size = readNumber(header, 124, 12);
const mode = readNumber(header, 100, 8);
const mtime = readNumber(header, 136, 12);
const prefix = readString(header, 345, 155);
let name = readString(header, 0, 100);
const dataStart = offset + BLOCK;
const dataEnd = dataStart + size;
if (dataEnd > archive.length) throw new TarError(`truncated entry at offset ${offset}`);
const body = archive.subarray(dataStart, dataEnd);
const padded = dataStart + Math.ceil(size / BLOCK) * BLOCK;
if (typeflag === "x" || typeflag === "g") {
const records = parsePax(body);
if (typeflag === "x") nextPax = records;
offset = padded;
continue;
}
if (typeflag === "L") {
nextLongName = body.toString("utf8").replace(/\0+$/, "");
offset = padded;
continue;
}
if (typeflag === "K") {
offset = padded;
continue;
}
if (typeflag === "1" || typeflag === "2" || typeflag === "3" || typeflag === "4" || typeflag === "6") {
throw new TarError(`unsupported entry type "${typeflag}" for ${name}`);
}
if (typeflag === "S") throw new TarError(`sparse entries are not supported (${name})`);
if (nextLongName !== undefined) name = nextLongName;
const paxPath = nextPax?.get("path");
if (paxPath !== undefined) name = paxPath;
const fullPath = joinPath(prefix, name);
nextPax = undefined;
nextLongName = undefined;
const isDirectory = typeflag === "5" || fullPath.endsWith("/");
const clean = normalize(fullPath).replace(/^\.\//, "").replace(/\/+$/, "");
if (clean === "" || clean === ".") {
offset = padded;
continue;
}
entries.push({
path: clean,
type: isDirectory ? "directory" : "file",
mode: mode === 0 ? (isDirectory ? 0o755 : 0o644) : mode,
mtime,
data: isDirectory ? Buffer.alloc(0) : Buffer.from(body),
});
offset = padded;
}
return entries;
}
/** Reject absolute paths and `..` segments — an archive must not escape `root`. */
export function safeEntryPath(root: string, entryPath: string): string {
if (isAbsolute(entryPath)) throw new TarError(`absolute path in archive: ${entryPath}`);
const segments = entryPath.split("/");
if (segments.some((segment) => segment === "..")) {
throw new TarError(`path traversal in archive: ${entryPath}`);
}
const target = normalize(join(root, entryPath));
const prefix = root.endsWith(sep) ? root : root + sep;
if (target !== root && !target.startsWith(prefix)) {
throw new TarError(`entry escapes the destination: ${entryPath}`);
}
return target;
}
/**
* Extract a `.tar.gz` into `destDir` (created if missing) and return the
* entries that were written, in archive order.
*/
export function extractTarGz(archive: Uint8Array, destDir: string): TarEntry[] {
const entries = parseTar(gunzipSync(archive));
mkdirSync(destDir, { recursive: true });
for (const entry of entries) {
const target = safeEntryPath(destDir, entry.path);
if (entry.type === "directory") {
mkdirSync(target, { recursive: true });
continue;
}
mkdirSync(dirname(target), { recursive: true });
writeFileSync(target, entry.data);
chmodSync(target, entry.mode & 0o777);
}
return entries;
}