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

+25
View File
@@ -70,6 +70,31 @@ only for a package that already exists, so the first publish is manual:
configuration expires.
3. Bump to a **higher** version for the first CI release — npm rejects republishing a version.
## Release assets (the curl channel)
`release.yml` also publishes six `pi2d-<version>-<target>.tar.gz` assets plus `SHA256SUMS` and
SLSA provenance (`actions/attest-build-provenance`), which `pi2 update` consumes. Two things to
know before debugging a missing asset:
- **Backfill an existing tag without re-publishing npm:**
`gh workflow run release.yml -f tag=v0.1.6` — `publish` and `packaging` are gated on
`github.event_name == 'push'`, so a dispatch run only rebuilds and re-attaches assets.
This is the repair path for "the release has no tarballs" (it happened to v0.1.6: the
`darwin-x64` leg sat queued on the retired `macos-13` image for 21 h and `checksums` never ran).
- **Runner labels matter more than the build.** `darwin-x64` needs `macos-15-intel` and
`darwin-arm64` needs `macos-15`; a retired or deprecated label leaves the leg queued forever
and the whole asset job blocked. Verify with
`gh api repos/zgs225/pi2d/actions/runs/<id>/jobs --jq '.jobs[] | "\(.name) \(.status)"'`.
Verify what actually landed, not that the run was green:
```bash
gh release view "v<x.y.z>" --repo zgs225/pi2d --json assets --jq '.assets[].name'
gh attestation verify pi2d-<x.y.z>-linux-x64.tar.gz --repo zgs225/pi2d
PI2_VERSION=<x.y.z> PI2_INSTALL_DIR=/tmp/pi2-check/lib PI2_BIN_DIR=/tmp/pi2-check/bin \
sh scripts/install.sh && sh scripts/boot-check.sh /tmp/pi2-check/bin/pi2 <x.y.z>
```
## Failure playbook
| Symptom | Cause / action |
+2 -2
View File
@@ -29,7 +29,7 @@ Adding bulk to this file is a mistake, not a contribution.
| `src/daemon/` | HTTP/WS/SSE, auth, static assets, routing, event relay |
| `src/instances/` | discovery, lazy spawn, one-instance-per-workspace, crash handling |
| `src/workspaces/` | registry, disk discovery, aliases/trust, visibility policy |
| `src/cli/` | `pi2` — `daemon`, `open`, `attach`, `status`, `doctor`, `pairing`, `install-service` |
| `src/cli/` | `pi2` — `daemon`, `open`, `attach`, `status`, `doctor`, `pairing`, `install-service`, `update` |
| `src/config.ts` | env-only configuration (`PI2_*`, `PI2_HOST`, `PI2_WORKSPACE_*`) |
| `src/core/network.ts` | reachable addresses: kind classification, `bases[]` order, CORS origins |
| `src/core/qr.ts` | zero-dependency QR encoder (pairing links; rows, no quiet zone) |
@@ -68,7 +68,7 @@ owner/repo/workflow filename, not the npm name).
| Doc | Contents |
|---|---|
| `docs/protocol.md` | the browser ↔ daemon ↔ plugin wire contract |
| `docs/install.md` | canonical CLI-first install guide, channels, run modes, services |
| `docs/install.md` | canonical CLI-first install guide, channels, run modes, services, `pi2 update` |
| `docs/session-dot.md` | the session-list status dot: the `:PiSessions` matrix, the unread flags, the one blink clock |
| `docs/deployment.md` | env vars, runtime files, ports, auth, services, troubleshooting |
| `docs/e2e.md` | scenario ids, isolation, skip conditions, report paths |
+4 -1
View File
@@ -42,7 +42,10 @@ For machines without Node, with an older distro Node (e.g. Debian 12 ships 18),
curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh
```
Installs the precompiled binary and web console to `~/.local/lib/pi2d` and symlinks the executable to `~/.local/bin/pi2`.
Installs the precompiled binary and web console into `~/.local/lib/pi2d/versions/<version>/`,
points `~/.local/lib/pi2d/current` at it, writes an install receipt and symlinks the executable to
`~/.local/bin/pi2`. After that, `pi2 update` upgrades it in place (verified download, SLSA
provenance check, atomic `current` switch, one-step rollback).
To uninstall:
+138
View File
@@ -0,0 +1,138 @@
# ADR 0003 — `pi2 update`: a versioned install layout and an install receipt
- Status: accepted (implementing)
- Date: 2026-10-29
- Extends: [ADR 0002](0002-install-and-run.md) §2.9.1 (the deferred `pi2 update`)
## Context
ADR 0002 deferred an in-place self-updater because "package managers already upgrade
well". That holds for Homebrew, the AUR and npm, but not for the **standalone channel**
(Channel B, `scripts/install.sh`): the upstream upgrade path there is "re-run the
installer", which the Neovim plugin cannot do safely and which forces a re-download of
the whole 35 MB artifact with no version arithmetic, no provenance check and no
rollback.
Two facts shaped the design:
1. **A compiled `bun build --compile` binary cannot be written in place** (`ETXTBSY`),
but `rename()` over the running executable works on both Linux and macOS, and the
running process keeps its old inode. So replacement must be a staged rename, never
an in-place write.
2. **The install is two trees** (`bin/` + `share/pi2d/web/dist`), and renaming two
directories is not atomic. A half-finished update would leave a new binary with an
old UI.
`pi2` cannot guess its channel reliably from its own path: `~/.local/bin/pi2`,
`$(brew --prefix)/bin/pi2`, `/usr/bin/pi2` and `<data>/pi2d/node_modules/.bin/pi2` all
look equally like "some binary". Guessing wrong means either corrupting a
package-manager-owned tree or refusing a legitimate update.
## Decision
### 1. The curl channel installs into a versioned layout
```
<prefix>/ default ~/.local/lib/pi2d (PI2_INSTALL_DIR)
versions/
0.1.6/
bin/pi2
share/pi2d/web/dist/…
LICENSE
0.1.7/ ← one immutable tree per version
current -> versions/0.1.7 ← relative symlink, the only thing that moves
install.json ← the receipt (never inside a version tree)
<bin dir>/pi2 -> <prefix>/current/bin/pi2
```
A version tree is immutable once written, so `current` is the single atomic switch and
`bin/` + `share/` can never disagree. Rollback is one symlink write, and the previous
tree stays on disk (pruned to `current` + 1 previous). `PI2_BIN_DIR/pi2` points at
`current`, so the plugin, the user's `PATH` and the rendered service unit all keep
working across an update — **`ExecStart` must use the `current` path, not
`<prefix>/versions/<v>/bin/pi2`**, or the unit breaks on every update.
The tarball keeps its flat `bin/` + `share/` shape: the version directory is created by
the installer, not by the release artifact.
### 2. The installer writes a receipt, and only the receipt authorises an update
`<prefix>/install.json`:
```json
{
"schema": 1,
"installer": "curl",
"layout": "versioned",
"prefix": "/home/u/.local/lib/pi2d",
"current": "/home/u/.local/lib/pi2d/current",
"version": "0.1.6",
"bin": "/home/u/.local/lib/pi2d/versions/0.1.6/bin/pi2",
"asset": "pi2d-0.1.6-linux-x64.tar.gz",
"sha256": "d560f84c…",
"installed_at": "2026-10-29T07:32:00Z"
}
```
`pi2 update` refuses unless **all** of these hold:
| Condition | Failure message points at |
|---|---|
| running as a compiled binary | `npm i -g @yuez/pi2d@latest` (npm channel) |
| `<prefix>/install.json` exists | `brew upgrade pi2d` / an AUR helper / "re-run the installer once" (legacy flat layout) |
| `installer == "curl"` | the channel's own command (`brew upgrade`, `paru -Syu pi2d-bin`, `npm i -g`) |
| `bin == realpath(process.execPath)` | "another copy of pi2 is installed" |
`installer` is written by whoever installed it: `install.sh` writes `curl`; the
Homebrew formula and the AUR `PKGBUILD` write `brew` / `aur` when they can, and their
absence merely lands in the "no receipt" row above. npm installs never write one.
This is the `uv` model (`load_receipt()` + "assume a package manager when no receipt is
found"), which is the only channel detection that cannot be spoofed by a stray binary
on `PATH`.
### 3. `pi2 update` implements the transfer itself (native TypeScript)
Not "download and pipe the installer into `sh`" (uv's approach): the updater must be
hermetic-testable (`AGENTS.md` hard rule 5), must not execute remote code, and has to
verify provenance — none of which a `curl | sh` subprocess gives us. So:
- release + asset resolution via the GitHub API, cached by ETag in
`<state>/update-check.json` (unauthenticated API is 60 req/h; `pi2 update --check`
must not burn it),
- asset selection from the build-time `PI2_BUILD_TARGET` define, not runtime libc
probing,
- `SHA256SUMS` verification, then **SLSA provenance** via `gh attestation verify`
(required with `--require-attestation`; otherwise a warning, because `gh` is not
guaranteed to be installed),
- extraction with a dependency-free tar reader, so no `tar`/`sh` subprocess,
- the staged binary is executed (`--version`) before anything is swapped.
### 4. Defaults
| Behaviour | Default | Override |
|---|---|---|
| restarts a running service | no, prints the command | — (`pi2 service stop && pi2 service start`) |
| downgrade | refused | `--force` |
| same version | "already up to date", no download | `--force` |
| attestation | verify when `gh` is available, else warn | `--require-attestation`, `--skip-attestation` |
| mirror / offline test | GitHub releases | `PI2_BASE_URL` (same knob as `install.sh`) |
| version lookups | cached 24 h | `PI2_UPDATE_CACHE_TTL` |
Restart stays manual on purpose: the daemon is shared by every Neovim instance and the
browser, and silently bouncing it mid-task is worse than asking.
## Consequences
- `scripts/install.sh` gains the versioned layout, the receipt and a migration from the
flat layout; `pi2 install-service` must render the `current` path.
- The flat layout is dead for the curl channel. An existing flat install keeps working
but cannot self-update until the installer runs once more.
- `pi2 update` is curl-only by design. Everything else is told to use its own package
manager, which is what ADR 0002 wanted.
- A future single-file artifact (embedding `web/dist` into the binary) would make the
swap a single rename, but `import … with { type: "file" }` gives no directory
listing and no `realpath`, which the static-file guard in `src/daemon/static.ts`
relies on. Not worth it today.
- Windows is out of scope: the whole release matrix is Linux/macOS, and an
in-process on Windows self-replace needs a helper process.
+10 -6
View File
@@ -141,15 +141,19 @@ second daemon cannot invalidate the running one.
1. **npm / Node package**: executed via Node (`node …/dist/cli/pi2.js`), where assets sit
next to the source tree.
2. **Compiled single binary**: compiled via Bun (`bun build --compile`) and installed as
`<prefix>/bin/pi2` with assets at `<prefix>/share/pi2d/web/dist`.
`<prefix>/versions/<version>/bin/pi2` with assets in
`<prefix>/versions/<version>/share/pi2d/web/dist`; `<prefix>/current` points at the live
version (see [ADR 0003](adr/0003-self-update.md), `pi2 update`).
How `pi2` discovers its own version and web UI (`src/core/install.ts`):
- **Version**: build-time define (`PI2_BUILD_VERSION`, injected by `scripts/build-binary.sh`)
→ on-disk `package.json` (`../../package.json` next to `dist/cli/` for npm/dev checkout)
→ `0.0.0` (`UNKNOWN_VERSION`).
- **Static UI directory** (`defaultStaticDir()`): probed in order, first with `index.html` wins:
1. `<exe>/../share/pi2d/web/dist` — release layout: `<prefix>/bin/pi2` plus
`<prefix>/share/pi2d/web/dist` (what the curl installer, Homebrew tap, and AUR `-bin` package install)
1. `<exe>/../share/pi2d/web/dist` — release layout: `<prefix>/versions/<v>/bin/pi2` plus
`<prefix>/versions/<v>/share/pi2d/web/dist` (what the curl installer writes; Homebrew and
the AUR `-bin` package use the flat `<prefix>/bin/pi2` + `<prefix>/share/pi2d/web/dist`,
which resolves to the same relative path)
2. `<exe>/web/dist` — portable unpacked directory (`pi2` next to its UI)
3. `<repo>/web/dist` — npm install or dev checkout relative to module location
- **Environment override**: `PI2_STATIC_DIR` still wins over all candidate paths when set.
@@ -519,8 +523,8 @@ After=network.target
[Service]
Type=simple
# For a compiled binary install:
ExecStart=/home/user/.local/lib/pi2d/bin/pi2 daemon --foreground
# For a compiled binary install (the `current` indirection survives `pi2 update`):
ExecStart=/home/user/.local/lib/pi2d/current/bin/pi2 daemon --foreground
# Or for an npm / Node install:
# ExecStart=/usr/bin/node /repo/dist/cli/pi2.js daemon --foreground
EnvironmentFile=-%h/.config/pi2/env
@@ -535,7 +539,7 @@ WantedBy=default.target
```
The `ExecStart` line adapts automatically to how `pi2` was invoked:
- **Compiled binary install**: `<prefix>/bin/pi2 daemon --foreground` (invokes the compiled executable directly).
- **Compiled binary install**: `<prefix>/current/bin/pi2 daemon --foreground` (invokes the compiled executable through the stable symlink, so an update does not break the unit; a flat Homebrew/AUR install renders its own binary path).
- **npm / Node install**: `<nodePath> <scriptPath> daemon --foreground` (e.g. `/usr/bin/node /repo/dist/cli/pi2.js daemon --foreground`).
The unit includes `EnvironmentFile=-%h/.config/pi2/env`, where the leading `-` tells systemd that a missing file is completely fine.
+37 -10
View File
@@ -13,7 +13,7 @@ Find your situation in the table below to choose the right installation command
| Situation | Recommended Command | What it gives you |
|---|---|---|
| **I have Node 20+** | `npm i -g @yuez/pi2d`<br>*(or `pnpm add -g`, `bun add -g`, `mise use -g npm:@yuez/pi2d`)* | The `pi2` CLI running directly on your existing Node.js environment, updated via standard package manager commands. |
| **no Node / old Node** | `curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh \| sh` | Standalone compiled binary in `~/.local/lib/pi2d` symlinked to `~/.local/bin/pi2`. Requires zero Node/npm dependencies and no root access. |
| **no Node / old Node** | `curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh \| sh` | Standalone compiled binary in `~/.local/lib/pi2d` symlinked to `~/.local/bin/pi2`, upgraded in place with `pi2 update`. Requires zero Node/npm dependencies and no root access. |
| **macOS** | `brew install zgs225/tap/pi2d`<br>*(or the curl installer)* | Native Homebrew formula. Places `pi2` in `$(brew --prefix)/bin` and web assets in `$(brew --prefix)/share/pi2d/web/dist`. |
| **Arch / EndeavourOS / Manjaro** | `curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh \| sh`<br>*(AUR `pi2d-bin` once AUR registration reopens)* | Standalone binary in `~/.local/lib/pi2d` + `~/.local/bin/pi2`. Package-manager channels are paused: the AUR is not accepting accounts, so the curl installer is the working path today. |
| **NixOS** | `curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh \| sh`<br>*(or dev checkout)* | Standalone binary in user home (`~/.local/bin/pi2`). Bun's `-musl` binaries are dynamically linked against the musl loader, so running a prebuilt binary on NixOS needs `nix-ld` (or an FHS env / `steam-run`-style wrapper). |
@@ -61,12 +61,20 @@ curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh
The script automatically detects OS (`linux`, `darwin`), architecture (`x64`, `arm64`), and C library (`glibc`, `musl`). It downloads the corresponding precompiled standalone archive from GitHub Releases, verifies its SHA256 checksum, and extracts it with zero root privileges needed.
**Where files land**:
- Base directory: `~/.local/lib/pi2d/`
- `~/.local/lib/pi2d/bin/pi2` (the compiled binary)
- `~/.local/lib/pi2d/share/pi2d/web/dist/` (the web console UI assets)
- `~/.local/lib/pi2d/LICENSE`
- Symlink: `~/.local/bin/pi2` points to `~/.local/lib/pi2d/bin/pi2`
**Where files land** (the versioned layout, see [ADR 0003](adr/0003-self-update.md)):
- Base directory (`<prefix>`): `~/.local/lib/pi2d/`
- `~/.local/lib/pi2d/versions/0.1.7/bin/pi2` (one immutable tree per version)
- `~/.local/lib/pi2d/versions/0.1.7/share/pi2d/web/dist/` (the web console UI assets)
- `~/.local/lib/pi2d/versions/0.1.7/LICENSE`
- `~/.local/lib/pi2d/current` → `versions/0.1.7` (the only thing an update moves)
- `~/.local/lib/pi2d/install.json` (the install receipt: installer, version, asset, SHA256)
- Symlink: `~/.local/bin/pi2` → `~/.local/lib/pi2d/current/bin/pi2`
Keeping one tree per version means `bin/` and `share/` can never disagree, an update is a
single symlink switch, and the previous version stays behind for one-step rollback (`pi2
update --version <old>`). The receipt is what authorises `pi2 update`: without one (npm,
Homebrew, AUR, or a flat install from before 0.1.7) it refuses and points at the command that
owns the tree.
Ensure `~/.local/bin` is in your `$PATH` (e.g. in your `~/.bashrc` or `~/.zshrc`):
```bash
@@ -141,7 +149,7 @@ pi2 install-service --write
```
The CLI inspects how it was installed:
- If running as a standalone compiled binary, `ExecStart` directly executes the binary (e.g. `/home/user/.local/lib/pi2d/bin/pi2 daemon --foreground`).
- If running as a standalone compiled binary, `ExecStart` directly executes the binary through the stable `current` symlink (e.g. `/home/user/.local/lib/pi2d/current/bin/pi2 daemon --foreground`), so `pi2 update` does not invalidate the unit.
- If running via Node, `ExecStart` points to `<node> <scriptPath> daemon --foreground`.
#### Linux (`systemd --user`)
@@ -313,10 +321,29 @@ systemctl --user restart pi2.service
```
- **Channel B (Standalone curl installer)**:
Re-run the installer. It replaces the binary and assets cleanly in `~/.local/lib/pi2d`:
```bash
curl -fsSL https://raw.githubusercontent.com/zgs225/pi2d/main/scripts/install.sh | sh
pi2 update
```
It downloads the release asset for this platform, checks it against the release's
`SHA256SUMS`, verifies its SLSA build provenance with `gh attestation verify` when the
GitHub CLI is installed, runs the new binary once, then switches
`~/.local/lib/pi2d/current` and rewrites the install receipt. The previous version is kept
for one-step rollback.
| Command | What it does |
|---|---|
| `pi2 update` | Upgrade to the latest release, then print the command to restart the daemon |
| `pi2 update --check` | Report the latest version and exit (24 h cached, one GitHub API call at most) |
| `pi2 update --dry-run` | Print the asset, URL and prefix it would use, change nothing |
| `pi2 update --version 0.1.6` | Pin a version (a downgrade also needs `--force`) |
| `pi2 update --force` | Reinstall even when already on that version |
| `pi2 update --require-attestation` | Fail unless the SLSA provenance verifies |
| `pi2 update --skip-attestation` | Never call `gh` (offline machines, no GitHub CLI) |
| `pi2 update --json` | Machine-readable result (stdout is pure JSON; progress goes to stderr) |
Setting `PI2_BASE_URL` points the download at a mirror (`PI2_UPDATE_CACHE_TTL` changes the
version-lookup cache, default 86400 s). Re-running the installer still works and stays the
recovery path when the tree is damaged.
- **Channel C (Homebrew)**:
```bash
+3
View File
@@ -166,6 +166,9 @@ BUN_CMD=(
--compile
--outfile "$OUTPUT_DIR/bin/pi2"
--define "PI2_BUILD_VERSION=\"$VERSION\""
# `pi2 update` picks the release asset named after what this binary was
# built for, instead of re-probing libc at runtime.
--define "PI2_BUILD_TARGET=\"$OS_ARCH\""
)
if [[ -n "$BUN_TARGET" ]]; then
BUN_CMD+=("--target=$BUN_TARGET")
+118 -19
View File
@@ -460,12 +460,27 @@ else
fi
# -----------------------------------------------------------------------------
# Unpack & Atomic Install
# Unpack & Atomic Install (versioned layout)
# -----------------------------------------------------------------------------
#
# <prefix>/versions/<version>/{bin,share,LICENSE}
# <prefix>/current -> versions/<version> (the only thing an update moves)
# <prefix>/install.json (the receipt, see docs/adr/0003)
# <bin dir>/pi2 -> <prefix>/current/bin/pi2
#
# A version tree is immutable once moved into place, so `bin/` and `share/` can
# never disagree and rolling back is one symlink write.
printf 'Installing pi2 to %s...\n' "$PI2_INSTALL_DIR"
mkdir -p "$PI2_INSTALL_DIR"
staging="$PI2_INSTALL_DIR/.staging.$$"
version_dir_name="$(printf '%s' "$version" | tr -cd '0-9A-Za-z._-')"
[ -n "$version_dir_name" ] || version_dir_name="custom"
versions_dir="$PI2_INSTALL_DIR/versions"
version_tree="$versions_dir/$version_dir_name"
staging="$versions_dir/.staging.$$"
mkdir -p "$versions_dir"
rm -rf "$staging"
mkdir -p "$staging"
@@ -491,27 +506,106 @@ if [ ! -x "$staging/bin/pi2" ]; then
exit 1
fi
# Atomic swap: move existing directories aside before moving staged directories
rm -rf "$PI2_INSTALL_DIR/bin.old.$$" "$PI2_INSTALL_DIR/share.old.$$" "$PI2_INSTALL_DIR/LICENSE.old.$$"
[ -d "$PI2_INSTALL_DIR/bin" ] && mv "$PI2_INSTALL_DIR/bin" "$PI2_INSTALL_DIR/bin.old.$$"
[ -d "$PI2_INSTALL_DIR/share" ] && mv "$PI2_INSTALL_DIR/share" "$PI2_INSTALL_DIR/share.old.$$"
[ -f "$PI2_INSTALL_DIR/LICENSE" ] && mv "$PI2_INSTALL_DIR/LICENSE" "$PI2_INSTALL_DIR/LICENSE.old.$$"
mv "$staging/bin" "$PI2_INSTALL_DIR/bin"
if [ -d "$staging/share" ]; then
mv "$staging/share" "$PI2_INSTALL_DIR/share"
# Move the staged tree into place under its version. Reinstalling the same
# version replaces that tree; every other version is left alone.
rm -rf "$version_tree.old.$$"
if [ -d "$version_tree" ]; then
mv "$version_tree" "$version_tree.old.$$"
fi
if [ -f "$staging/LICENSE" ]; then
mv "$staging/LICENSE" "$PI2_INSTALL_DIR/LICENSE"
if ! mv "$staging" "$version_tree"; then
[ -d "$version_tree.old.$$" ] && mv "$version_tree.old.$$" "$version_tree"
printf 'Error: Failed to move the staged tree into %s\n' "$version_tree" >&2
exit 1
fi
rm -rf "$PI2_INSTALL_DIR/bin.old.$$" "$PI2_INSTALL_DIR/share.old.$$" "$PI2_INSTALL_DIR/LICENSE.old.$$" "$staging"
staging=""
rm -rf "$version_tree.old.$$"
# Symlink executable into PI2_BIN_DIR
previous_tree=""
if [ -L "$PI2_INSTALL_DIR/current" ]; then
previous_tree="$(readlink "$PI2_INSTALL_DIR/current" 2>/dev/null || true)"
fi
# `rename(2)` replaces the symlink atomically; `-T` (GNU) and `-h` (BSD) both
# stop `mv` from moving into the directory an existing symlink points at.
switch_symlink() {
target="$1"
link="$2"
tmp="$link.tmp.$$"
rm -f "$tmp"
ln -s "$target" "$tmp" || return 1
if mv -T "$tmp" "$link" 2>/dev/null; then return 0; fi
if mv -h "$tmp" "$link" 2>/dev/null; then return 0; fi
rm -f "$link"
mv "$tmp" "$link"
}
if ! switch_symlink "versions/$version_dir_name" "$PI2_INSTALL_DIR/current"; then
if [ -n "$previous_tree" ]; then
switch_symlink "$previous_tree" "$PI2_INSTALL_DIR/current" || true
fi
printf 'Error: Failed to point %s/current at versions/%s\n' "$PI2_INSTALL_DIR" "$version_dir_name" >&2
exit 1
fi
# The receipt authorises `pi2 update`; write it atomically *after* the switch,
# so it always describes the tree `current` resolves to.
archive_sha256="${archive_sha256:-$(compute_sha256 "$archive_path")}"
json_escape() {
printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g'
}
receipt="$PI2_INSTALL_DIR/install.json"
receipt_tmp="$PI2_INSTALL_DIR/.install.json.$$"
cat > "$receipt_tmp" <<EOF_RECEIPT
{
"schema": 1,
"installer": "curl",
"layout": "versioned",
"prefix": "$(json_escape "$PI2_INSTALL_DIR")",
"current": "$(json_escape "$PI2_INSTALL_DIR/current")",
"version": "$(json_escape "$version")",
"bin": "$(json_escape "$version_tree/bin/pi2")",
"asset": "$(json_escape "$archive_name")",
"sha256": "$(json_escape "$archive_sha256")",
"installed_at": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
}
EOF_RECEIPT
if ! mv -f "$receipt_tmp" "$receipt"; then
rm -f "$receipt_tmp"
printf 'Error: Failed to write %s\n' "$receipt" >&2
exit 1
fi
# Migrate away from the pre-0.1.7 flat layout (<prefix>/bin, <prefix>/share).
legacy="$PI2_INSTALL_DIR/.legacy.$$"
for entry in bin share LICENSE; do
if [ -e "$PI2_INSTALL_DIR/$entry" ]; then
mkdir -p "$legacy"
mv "$PI2_INSTALL_DIR/$entry" "$legacy/"
fi
done
if [ -d "$legacy" ]; then
rm -rf "$legacy"
printf 'info: migrated the previous flat layout to %s\n' "$versions_dir"
fi
# Prune: keep `current` plus one previous tree (a one-step rollback), drop the rest.
keep_previous=""
if [ -n "$previous_tree" ]; then
keep_previous="$(basename "$previous_tree")"
fi
for dir in "$versions_dir"/*; do
[ -d "$dir" ] || continue
name="$(basename "$dir")"
case "$name" in .*) continue ;; esac
if [ "$name" != "$version_dir_name" ] && [ "$name" != "$keep_previous" ]; then
rm -rf "$dir"
fi
done
# Symlink executable into PI2_BIN_DIR, through `current` so it never goes stale.
mkdir -p "$PI2_BIN_DIR"
symlink="$PI2_BIN_DIR/pi2"
binary_target="$PI2_INSTALL_DIR/bin/pi2"
binary_target="$PI2_INSTALL_DIR/current/bin/pi2"
rm -f "$symlink"
ln -s "$binary_target" "$symlink"
@@ -522,7 +616,10 @@ ln -s "$binary_target" "$symlink"
printf '\npi2 %s (%s) installed successfully!\n\n' "$version" "$target"
printf 'Install location:\n'
printf ' - Directory: %s\n' "$PI2_INSTALL_DIR"
printf ' - Prefix: %s\n' "$PI2_INSTALL_DIR"
printf ' - Version: %s\n' "$version_tree"
printf ' - Current: %s -> %s\n' "$PI2_INSTALL_DIR/current" "versions/$version_dir_name"
printf ' - Receipt: %s\n' "$receipt"
printf ' - Executable: %s -> %s\n\n' "$symlink" "$binary_target"
printf 'Next steps:\n'
@@ -530,6 +627,8 @@ printf ' - Run in foreground:\n'
printf ' pi2 daemon\n'
printf ' - Run as background service (systemd user unit or macOS LaunchAgent):\n'
printf ' pi2 install-service --write\n'
printf ' - Upgrade later in place:\n'
printf ' pi2 update\n'
in_path=0
case ":$PATH:" in
+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;
}
+351
View File
@@ -0,0 +1,351 @@
import { existsSync, mkdirSync, mkdtempSync, 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 { buildReceipt, readReceipt, receiptPath, writeReceiptAtomic } from "../../src/core/self-update.js";
import { sha256Hex } from "../../src/core/release.js";
import {
parseUpdateArgs,
resolveInstall,
runUpdate,
type ExecResult,
type UpdateDeps,
} from "../../src/cli/update.js";
import { UsageError } from "../../src/cli/util.js";
import { buildReleaseArchive } from "../core/tar-fixture.js";
let dirs: string[] = [];
function tmp(): string {
const dir = mkdtempSync(join(tmpdir(), "pi2-update-"));
dirs.push(dir);
return dir;
}
afterEach(() => {
for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
dirs = [];
});
interface Install {
root: string;
prefix: string;
bin: string;
installer?: string;
}
/** A curl-channel install: `<prefix>/versions/<v>/…` + `current` + the receipt. */
function makeInstall(version: string, installer = "curl"): Install {
const root = tmp();
const prefix = join(root, "prefix");
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(receiptPath(prefix), "");
writeReceiptAtomic(prefix, buildReceipt({ prefix, version, bin, installer }));
symlinkSync(`versions/${version}`, join(prefix, "current"));
return { root, prefix, bin, installer };
}
function releaseFetch(version: string, options: { sums?: string; archive?: Buffer; apiStatus?: number } = {}) {
const archive = options.archive ?? buildReleaseArchive(version);
const asset = `pi2d-${version}-linux-x64.tar.gz`;
const sums = options.sums ?? `${sha256Hex(archive)} ${asset}\n`;
return (async (input: unknown) => {
const url = String(input);
if (url.includes("api.github.com")) {
return new Response(JSON.stringify({ tag_name: `v${version}` }), {
status: options.apiStatus ?? 200,
headers: { etag: '"etag-1"' },
});
}
if (url.endsWith("/SHA256SUMS")) return new Response(sums);
if (url.endsWith(asset)) return new Response(archive);
return new Response("not found", { status: 404 });
}) as unknown as typeof fetch;
}
function fakeExec(options: { version?: string; gh?: boolean; attestation?: number } = {}) {
const calls: string[][] = [];
const exec = (argv: readonly string[]): ExecResult => {
calls.push([...argv]);
if (argv[0] === "gh") {
if (argv[1] === "--version") {
return options.gh === false
? { code: 127, stdout: "", stderr: "gh: command not found" }
: { code: 0, stdout: "gh version 2.63.0 (2026-01-01)\n", stderr: "" };
}
return { code: options.attestation ?? 0, stdout: "Verified\n", stderr: options.attestation === 0 ? "" : "no attestation" };
}
const version = options.version ?? "0.1.7";
return { code: 0, stdout: `pi2 ${version}\n`, stderr: "" };
};
return { exec, calls };
}
function deps(install: Install, fetchImpl: typeof fetch, exec: UpdateDeps["exec"]): UpdateDeps {
return {
fetchImpl,
exec,
execPath: install.bin,
isBundled: () => true,
currentVersion: "0.1.6",
env: {},
stateDirPath: join(install.root, "state"),
print: () => {},
warn: () => {},
};
}
describe("parseUpdateArgs", () => {
it("defaults to a plain update", () => {
expect(parseUpdateArgs([])).toEqual({
check: false,
dryRun: false,
force: false,
json: false,
requireAttestation: false,
skipAttestation: false,
help: false,
});
});
it("normalises a pinned version and reads the modes", () => {
const parsed = parseUpdateArgs(["--check", "--version", "v0.1.7", "--json"]);
expect(parsed.check).toBe(true);
expect(parsed.version).toBe("0.1.7");
expect(parsed.json).toBe(true);
});
it("rejects unknown flags and positionals with the update usage", () => {
expect(() => parseUpdateArgs(["--nope"])).toThrow(UsageError);
try {
parseUpdateArgs(["0.1.7"]);
} catch (error) {
expect((error as UsageError).usage).toContain("pi2 update");
}
});
});
describe("resolveInstall", () => {
it("refuses an npm/Node run with the npm command", () => {
expect(() => resolveInstall("/usr/bin/pi2", false)).toThrow(/npm i -g @yuez\/pi2d/);
});
it("refuses the flat layout and points at the installer", () => {
expect(() => resolveInstall("/tmp/pi2d/bin/pi2", true)).toThrow(/re-run the installer/);
});
it("refuses a missing receipt", () => {
const root = tmp();
const prefix = join(root, "prefix");
const bin = join(prefix, "versions", "0.1.6", "bin", "pi2");
mkdirSync(join(prefix, "versions", "0.1.6", "bin"), { recursive: true });
writeFileSync(bin, "#!/bin/sh\n", { mode: 0o755 });
expect(() => resolveInstall(bin, true)).toThrow(/no install receipt/);
});
it("refuses a Homebrew-owned tree with the brew command", () => {
const install = makeInstall("0.1.6", "brew");
expect(() => resolveInstall(install.bin, true)).toThrow(/brew upgrade pi2d/);
});
it("refuses when the receipt describes another binary", () => {
const install = makeInstall("0.1.6");
const other = join(install.prefix, "versions", "0.1.6", "bin", "pi2-other");
writeFileSync(other, "#!/bin/sh\n", { mode: 0o755 });
writeReceiptAtomic(
install.prefix,
buildReceipt({ prefix: install.prefix, version: "0.1.6", bin: other }),
);
expect(() => resolveInstall(install.bin, true)).toThrow(/another copy of pi2/);
});
it("accepts a curl-channel install and returns its receipt", () => {
const install = makeInstall("0.1.6");
expect(resolveInstall(install.bin, true).receipt.installer).toBe("curl");
});
});
describe("runUpdate", () => {
it("--check reports the newer version without downloading", async () => {
const install = makeInstall("0.1.6");
const lines: string[] = [];
const code = await runUpdate({
argv: ["--check", "--json"],
...deps(install, releaseFetch("0.1.7"), fakeExec().exec),
print: (line) => lines.push(line),
});
expect(code).toBe(0);
const result = JSON.parse(lines.join("\n")) as { action: string; latest: string; updatable: boolean };
expect(result.action).toBe("checked");
expect(result.latest).toBe("0.1.7");
expect(result.updatable).toBe(true);
expect(readlinkSync(join(install.prefix, "current"))).toBe("versions/0.1.6");
});
it("reports up-to-date without --force", async () => {
const install = makeInstall("0.1.6");
const lines: string[] = [];
await runUpdate({
argv: ["--json"],
...deps(install, releaseFetch("0.1.6"), fakeExec().exec),
currentVersion: "0.1.6",
print: (line) => lines.push(line),
});
expect(JSON.parse(lines.join("\n")).action).toBe("up-to-date");
});
it("refuses a downgrade unless --force is passed", async () => {
const install = makeInstall("0.1.6");
await expect(
runUpdate({ argv: ["--version", "0.1.5"], ...deps(install, releaseFetch("0.1.5"), fakeExec().exec) }),
).rejects.toThrow(/refusing to downgrade/);
});
it("--dry-run changes nothing", async () => {
const install = makeInstall("0.1.6");
const before = readReceipt(install.prefix).receipt;
const lines: string[] = [];
await runUpdate({
argv: ["--dry-run"],
...deps(install, releaseFetch("0.1.7"), fakeExec().exec),
print: (line) => lines.push(line),
});
expect(lines.join("\n")).toContain("would install pi2 0.1.7");
expect(readReceipt(install.prefix).receipt).toEqual(before);
expect(readlinkSync(join(install.prefix, "current"))).toBe("versions/0.1.6");
expect(existsSync(join(install.prefix, "versions", "0.1.7"))).toBe(false);
});
it("installs, verifies provenance, smoke-tests and switches current", async () => {
const install = makeInstall("0.1.6");
const fake = fakeExec({ version: "0.1.7" });
const lines: string[] = [];
const code = await runUpdate({
argv: ["--json"],
...deps(install, releaseFetch("0.1.7"), fake.exec),
print: (line) => lines.push(line),
});
expect(code).toBe(0);
const result = JSON.parse(lines.join("\n")) as {
action: string;
attestation: string;
previous: string;
latest: string;
restart: string;
};
expect(result.action).toBe("installed");
expect(result.attestation).toBe("verified");
expect(result.previous).toBe("0.1.6");
expect(result.latest).toBe("0.1.7");
expect(result.restart).toContain("pi2");
expect(readlinkSync(join(install.prefix, "current"))).toBe("versions/0.1.7");
expect(existsSync(join(install.prefix, "versions", "0.1.6"))).toBe(true);
expect(readFileSync(join(install.prefix, "versions", "0.1.7", "bin", "pi2"), "utf8")).toContain("pi2 0.1.7");
const receipt = readReceipt(install.prefix).receipt;
expect(receipt?.version).toBe("0.1.7");
expect(receipt?.sha256).toHaveLength(64);
expect(receipt?.asset).toBe("pi2d-0.1.7-linux-x64.tar.gz");
// The staged binary was executed before the swap.
expect(fake.calls.some((argv) => argv[1] === "--version" && argv[0].includes(".staging-"))).toBe(true);
// No staging residue.
expect(existsSync(join(install.prefix, "versions", ".staging-update"))).toBe(false);
});
it("fails on a checksum mismatch and leaves the install alone", async () => {
const install = makeInstall("0.1.6");
const archive = buildReleaseArchive("0.1.7");
const sums = `${"c".repeat(64)} pi2d-0.1.7-linux-x64.tar.gz\n`;
await expect(
runUpdate({ argv: [], ...deps(install, releaseFetch("0.1.7", { sums, archive }), fakeExec().exec) }),
).rejects.toThrow(/checksum mismatch/);
expect(readlinkSync(join(install.prefix, "current"))).toBe("versions/0.1.6");
expect(existsSync(join(install.prefix, "versions", "0.1.7"))).toBe(false);
});
it("fails when the release does not publish this platform", async () => {
const install = makeInstall("0.1.6");
const sums = `${"d".repeat(64)} pi2d-0.1.7-darwin-arm64.tar.gz\n`;
await expect(
runUpdate({ argv: [], ...deps(install, releaseFetch("0.1.7", { sums }), fakeExec().exec) }),
).rejects.toThrow(/has no entry for pi2d-0\.1\.7-linux-x64\.tar\.gz/);
});
it("warns but continues when provenance cannot be verified", async () => {
const install = makeInstall("0.1.6");
const warnings: string[] = [];
const fake = fakeExec({ attestation: 1 });
const lines: string[] = [];
await runUpdate({
argv: ["--json"],
...deps(install, releaseFetch("0.1.7"), fake.exec),
warn: (line) => warnings.push(line),
print: (line) => lines.push(line),
});
expect(warnings.join("\n")).toContain("provenance");
expect(JSON.parse(lines.join("\n")).attestation).toBe("failed");
expect(readlinkSync(join(install.prefix, "current"))).toBe("versions/0.1.7");
});
it("--require-attestation fails when gh is missing", async () => {
const install = makeInstall("0.1.6");
const fake = fakeExec({ gh: false });
await expect(
runUpdate({
argv: ["--require-attestation"],
...deps(install, releaseFetch("0.1.7"), fake.exec),
}),
).rejects.toThrow(/gh` is not installed/);
expect(readlinkSync(join(install.prefix, "current"))).toBe("versions/0.1.6");
});
it("--skip-attestation never calls gh", async () => {
const install = makeInstall("0.1.6");
const fake = fakeExec();
const lines: string[] = [];
await runUpdate({
argv: ["--skip-attestation", "--json"],
...deps(install, releaseFetch("0.1.7"), fake.exec),
print: (line) => lines.push(line),
});
expect(fake.calls.some((argv) => argv[0] === "gh")).toBe(false);
expect(JSON.parse(lines.join("\n")).attestation).toBe("skipped");
});
it("rejects an asset whose binary reports another version", async () => {
const install = makeInstall("0.1.6");
const fake = fakeExec({ version: "0.1.5" });
await expect(
runUpdate({ argv: [], ...deps(install, releaseFetch("0.1.7"), fake.exec) }),
).rejects.toThrow(/reports 0\.1\.5, expected 0\.1\.7/);
expect(readlinkSync(join(install.prefix, "current"))).toBe("versions/0.1.6");
});
it("--version pins the asset without asking the API", async () => {
const install = makeInstall("0.1.6");
let apiCalls = 0;
const fetchImpl = (async (input: unknown) => {
const url = String(input);
if (url.includes("api.github.com")) {
apiCalls += 1;
return new Response("{}", { status: 500 });
}
const archive = buildReleaseArchive("0.1.7");
if (url.endsWith("/SHA256SUMS")) {
return new Response(`${sha256Hex(archive)} pi2d-0.1.7-linux-x64.tar.gz\n`);
}
return new Response(archive);
}) as unknown as typeof fetch;
await runUpdate({
argv: ["--version", "0.1.7", "--skip-attestation"],
...deps(install, fetchImpl, fakeExec().exec),
});
expect(apiCalls).toBe(0);
expect(readlinkSync(join(install.prefix, "current"))).toBe("versions/0.1.7");
});
});
+175
View File
@@ -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/);
});
});
+213
View File
@@ -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();
});
});
+71
View File
@@ -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" },
]);
}
+81
View File
@@ -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);
});
});