8 Commits
Author SHA1 Message Date
yuez c2d1f1d960 chore: release 0.1.7 2026-10-29 16:54:54 +08:00
yuez 8fb535f7f3 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.
2026-10-29 16:42:57 +08:00
yuez 29aee26733 ci(release): unstick the asset pipeline and add SLSA attestations
- darwin-x64/darwin-arm64 move to macos-15-intel/macos-15: `macos-13` is
  retired, which left the v0.1.6 `darwin-x64` leg queued for 21h+ so
  `checksums` never ran and no tarballs or SHA256SUMS were attached.
- assert the exact six platform assets instead of a literal line count, which
  passed while a dropped leg was silently missing.
- `workflow_dispatch` with a `tag` input rebuilds assets for an existing
  release without touching npm, Homebrew or the AUR (publish/packaging stay on
  the tag-push path); `TAG` replaces `github.ref_name` throughout.
- `actions/attest-build-provenance` over the tarballs, so `pi2 update` can
  verify provenance with `gh attestation verify` rather than trusting a
  checksum shipped in the same release.
2026-10-29 15:28:15 +08:00
yuez d529b4cda7 docs(protocol): document the plugin bye record
§2 now shows the frame (`{"v":1,"type":"bye","payload":{"reason":"stopped"}}`)
and states the obligation: a plugin that stops on purpose writes one `bye` before
closing a live socket, so the daemon records `plugin said bye` instead of a
generic `socket closed` — which is what `src/instances/connection.ts` already does.
2026-10-29 14:32:47 +08:00
yuez 7130c69523 docs: document pi2 pairing --json
§8.5 said the CLI keeps only the human report; it now also emits the normalised
mint payload that :PiWebPair renders.
2026-10-29 14:11:10 +08:00
yuez 8a39e65def feat(cli): add --json to pi2 pairing
The Neovim plugin needs the mint payload (URL, code, expiry, QR matrix, every
advertised base) to draw a scannable code, but the CLI only printed a human
report — so `:PiWebPair` spoke HTTP itself, duplicating the CLI token handling
and requiring `curl` in the editor.

`pi2 pairing --json` prints the normalised payload instead:

  { url, code, expiresAt?, qr: { version, ecc, mask, size, rows }, bases[] }

Same fields the human report renders, so the terminal QR and the float always
agree, and `--base` still pins the link.
2026-10-29 14:11:10 +08:00
yuez f854ba8d4f docs: document pi2 service and the CLI-owned service control
- README/install: the plugin attaches → `pi2 service start` → spawn ladder,
  `:PiWebStop` detaches only the bridge, `:PiWebService`/`:PiWebLog` exist.
- deployment §8.6/§9: the new subcommand, its exit-code contract and the
  one-command `pi2 service enable` after `install-service --write`.
- ADR 0002: service-manager commands belong to the CLI (`pi2 service …`), the
  plugin's ladder gains $PI2_DAEMON_BIN, `:PiWebStop` never signals a
  service-managed daemon, and `:PiWebInstall` installs `@yuez/pi2d@latest`
  (optionally pinned by a <version> argument) after confirmation.
2026-10-29 14:00:48 +08:00
yuez 4eda2b9420 feat(cli): add pi2 service status|start|stop|enable|disable
`install-service` only renders the unit file; nothing in the CLI talked to
systemd/launchd. The editor plugin had no supported way to start a
service-managed daemon (it would have had to shell out to `systemctl` itself),
so add the explicit control surface ADR 0002 §2.2 assumes:

  pi2 service status [--json]   manager, unit path, installed/enabled/active, linger
  pi2 service start|stop        systemctl --user start|stop / launchctl kickstart|kill
  pi2 service enable|disable    systemctl --user enable|disable --now / launchctl bootstrap|bootout

`status` never fails: no manager, no unit and a dead service are reports, and
`--json` carries the same shape the plugin decodes. The four mutating actions
exit 1 with the manager's first stderr line, and refuse to run when the unit
file is missing. Every probe is injectable (exec/exists/platform/paths/uid/user)
so the tests never touch a real service manager.
2026-10-29 14:00:41 +08:00
27 changed files with 3531 additions and 87 deletions

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 |
+66 -12
View File
@@ -3,6 +3,16 @@ name: release
on:
push:
tags: ["v*"]
# Backfill (or rebuild) the release assets for a tag that already exists,
# without touching npm, Homebrew or the AUR: `gh workflow run release.yml -f
# tag=v0.1.6`. Publishing stays a tag-push-only operation (see the `publish`
# job's `if`).
workflow_dispatch:
inputs:
tag:
description: "Existing release tag to build assets for (e.g. v0.1.6)"
required: true
type: string
# Authentication is npm Trusted Publishing (OIDC): the npm CLI picks up the
# GitHub Actions OIDC token and exchanges it for a short-lived publish token.
@@ -10,13 +20,24 @@ on:
# See docs/releasing.md.
permissions:
contents: write # create GitHub release and upload binary assets
id-token: write # mint the OIDC token npm exchanges for publish rights
id-token: write # mint the OIDC token npm exchanges for publish rights, and the one `attest-build-provenance` signs with
attestations: write # SLSA build provenance for the binary tarballs
# `github.event.inputs` (not `inputs`) so this also evaluates on `push`, where
# the `inputs` context is not populated.
env:
TAG: ${{ github.event.inputs.tag || github.ref_name }}
jobs:
publish:
# A dispatch run only (re)builds assets for an existing tag; npm publishing
# must stay on the tag-push path so it never re-publishes a version.
if: github.event_name == 'push'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ env.TAG }}
- uses: pnpm/action-setup@v4
with:
@@ -33,10 +54,10 @@ jobs:
- name: Tag must match package.json version
run: |
tag="${GITHUB_REF_NAME#v}"
tag="${TAG#v}"
pkg="$(node -p 'require("./package.json").version')"
if [ "$tag" != "$pkg" ]; then
echo "tag $GITHUB_REF_NAME does not match package.json $pkg" >&2
echo "tag $TAG does not match package.json $pkg" >&2
exit 1
fi
@@ -125,8 +146,9 @@ jobs:
uses: softprops/action-gh-release@v2
with:
generate_release_notes: true
tag_name: ${{ env.TAG }}
body: |
`npm i -g @yuez/pi2d@${{ github.ref_name }}`
`npm i -g @yuez/pi2d@${{ env.TAG }}`
Compatible pi2.nvim: protocol v1 (see `docs/protocol.md`).
@@ -138,6 +160,11 @@ jobs:
# ubuntu-24.04-arm is GA for public repositories. Running linux-arm64 and
# linux-arm64-musl on native ARM64 runners lets us actually execute and
# boot-check the artifact before publishing it (all six legs are host-native).
#
# macOS labels are pinned to images that are neither retired nor
# deprecated (`macos-13` was retired and left `darwin-x64` queued for
# 21h+; `macos-14` is deprecated). `macos-15-intel` is the x64 image and
# `macos-15` the arm64 one — see actions/runner-images#README.
include:
- target: linux-x64
runner: ubuntu-latest
@@ -148,11 +175,13 @@ jobs:
- target: linux-arm64-musl
runner: ubuntu-24.04-arm
- target: darwin-x64
runner: macos-13
runner: macos-15-intel
- target: darwin-arm64
runner: macos-14
runner: macos-15
steps:
- uses: actions/checkout@v4
with:
ref: ${{ env.TAG }}
- uses: pnpm/action-setup@v4
with:
@@ -178,7 +207,7 @@ jobs:
- name: Boot check (host-native)
if: ${{ !contains(matrix.target, 'musl') }}
run: sh scripts/boot-check.sh dist-bin/bin/pi2 "${GITHUB_REF_NAME#v}"
run: sh scripts/boot-check.sh dist-bin/bin/pi2 "${TAG#v}"
- name: Boot check (Alpine, musl artifact)
# Bun's musl binaries link against musl's libstdc++; the glibc runner
@@ -189,7 +218,7 @@ jobs:
docker run --rm \
-v "${{ github.workspace }}/scripts:/s:ro" \
-v "${{ github.workspace }}/dist-bin:/b:ro" \
alpine:3.20 sh -c 'apk add --no-cache libstdc++ curl >/dev/null 2>&1 && sh /s/boot-check.sh /b/bin/pi2 "${GITHUB_REF_NAME#v}"'
alpine:3.20 sh -c 'apk add --no-cache libstdc++ curl >/dev/null 2>&1 && sh /s/boot-check.sh /b/bin/pi2 "${TAG#v}"'
- name: Upload binary tarball artifact
uses: actions/upload-artifact@v4
@@ -200,9 +229,14 @@ jobs:
checksums:
needs: [publish, binaries]
# `always()` keeps a dispatch run alive after the skipped `publish` job; the
# upload itself still requires a fully green `binaries` matrix.
if: always() && needs.binaries.result == 'success' && (needs.publish.result == 'success' || needs.publish.result == 'skipped')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ env.TAG }}
- name: Download all binary artifacts
uses: actions/download-artifact@v4
@@ -218,11 +252,28 @@ jobs:
echo "Generated SHA256SUMS:"
cat SHA256SUMS
sha256sum -c SHA256SUMS
COUNT="$(wc -l < SHA256SUMS)"
if [ "$COUNT" -ne 6 ]; then
echo "Expected 6 checksums, got $COUNT" >&2
# Assert the exact platform set instead of a line count: a bare `-ne 6`
# passed while a dropped leg (say darwin-x64) was silently missing.
version="${TAG#v}"
missing=0
for target in linux-x64 linux-arm64 linux-x64-musl linux-arm64-musl darwin-x64 darwin-arm64; do
asset="pi2d-${version}-${target}.tar.gz"
if ! grep -q " ${asset}$" SHA256SUMS; then
echo "::error::missing asset for ${target}: ${asset}"
missing=1
fi
done
if [ "$missing" -ne 0 ]; then
exit 1
fi
echo "all 6 platform assets present"
- name: Attest build provenance (SLSA)
# `pi2 update` verifies these with `gh attestation verify`; a checksum
# shipped in the same release only proves the download was intact.
uses: actions/attest-build-provenance@v2
with:
subject-path: dist-bin/*.tar.gz
- name: Upload SHA256SUMS artifact
uses: actions/upload-artifact@v4
@@ -234,13 +285,16 @@ jobs:
- name: Append artifacts to GitHub release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ github.ref_name }}
tag_name: ${{ env.TAG }}
files: |
dist-bin/*.tar.gz
dist-bin/SHA256SUMS
packaging:
needs: checksums
# Homebrew/AUR point at the assets this run just uploaded, so they stay on
# the tag-push path; a dispatch backfill must not bump a tap formula.
if: github.event_name == 'push'
runs-on: ubuntu-latest
# The two release credentials live in job-level env because GitHub does not
# expose the `secrets` context inside `if:` expressions (a step-level
+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 |
+6 -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:
@@ -121,6 +124,8 @@ pi2 daemon # foreground daemon
pi2 stop # stop running daemon (alias: pi2 daemon stop)
pi2 open # open browser console signed in (loopback only)
pi2 install-service --write # render and write user service file
pi2 service status # unit, enabled, active, linger (--json for machines)
pi2 service enable # daemon-reload + enable --now (start|stop|disable too)
pi2 uninstall-service --write # remove user service file
pi2 status # daemon status, active instances, and health
pi2 doctor # verify node/runtime, nvim, pi, curl, sockets, protocol
+22 -16
View File
@@ -105,34 +105,40 @@ Using `npx @yuez/pi2d@latest` or `npx` auto-execution is explicitly rejected:
daemon versions simultaneously, corrupting singleton socket expectations.
The plugin's `:PiWebInstall` becomes an explicit convenience command that prompts for
confirmation before installing a pinned version matching the plugin into
`<stdpath("data")>/pi2d`. It never runs `npx`.
confirmation before installing `@yuez/pi2d@latest` (an optional `<version>` argument
pins one) into `<stdpath("data")>/pi2d`. It never runs `npx`.
### 2.2 Run: the daemon owns its own lifecycle
| Mode | Who starts it | When to use |
|---|---|---|
| **user service (default)** | `pi2 install-service --write` → `systemctl --user` / `launchd`; `:PiWeb` only *uses* it | daily use, especially phone/another-browser access — the console has to be up when nvim is not |
| **user service (default)** | `pi2 install-service --write` + `pi2 service enable`; `:PiWeb` only *uses* it (`pi2 service start`) | daily use, especially phone/another-browser access — the console has to be up when nvim is not |
| **plugin spawn** | `:PiWeb` spawns a detached `pi2 daemon` if nothing runs (`web.autostart = "spawn"`) | a machine where the user does not want a service; logs to `PI2_STATE_DIR/daemon.log` |
| **foreground** | the user, in a terminal | debugging, `pi2 daemon --foreground` |
Service-manager commands belong to the CLI, not the editor: `pi2 service
status|start|stop|enable|disable` is the only thing that talks to
`systemctl`/`launchd` (and only when the user asks for it). `install-service`
stays pure file rendering.
#### `web.autostart = "auto"` semantics
The plugin setting `web.autostart = "auto"` follows strict three-step semantics:
1. **Attach if running**: Check if a daemon is already active (via `daemon.json` / `d.sock`).
If running, connect immediately — **never** spawn a second daemon.
2. **Start user service**: If an installed user service unit is found (`systemctl --user` or
`launchctl`), trigger unit start (`systemctl --user start pi2.service` or `launchctl kickstart`).
3. **Spawn detached**: If no service is installed, spawn a detached `pi2 daemon` process and
notify the user once in the editor.
1. **Attach if running**: Check if a daemon is already active (`daemon.json`).
If running, connect immediately — **never** spawn a second daemon, and never
require a resolvable `pi2` binary just to use one.
2. **Start user service**: If an installed user service unit is found (via
`pi2 service status`), run `pi2 service start`.
3. **Spawn detached**: If no service is installed, spawn a detached `pi2 daemon`
process and notify the user once in the editor.
#### `:PiWebStop` behavior in service mode
When the daemon is managed by a service manager (`systemd` or `launchd`), `:PiWebStop`
**must refuse** to stop the process. If a client terminates a service-managed daemon directly
via SIGTERM, `Restart=on-failure` (systemd) or `KeepAlive` (launchd) will immediately
attempt to restart it or enter an inconsistent state. The plugin must advise the user to
use `systemctl --user stop pi2` or `:PiWebService disable`.
`:PiWebStop` **only stops the editor-side bridge** (the WebSocket to the daemon);
it never signals the daemon process, so a service-managed daemon is not restarted
by `Restart=on-failure`/`KeepAlive` and an in-flight browser session is not broken.
Stopping the daemon is an explicit CLI action: `pi2 service stop`, `pi2 service
disable`, or `pi2 stop`.
### 2.3 The plugin is a client
@@ -144,7 +150,6 @@ winner:
3. `<stdpath("data")>/pi2d/node_modules/.bin/pi2` (only if `:PiWebInstall` created it)
4. repo checkout `dist/cli/pi2.js` / `node_modules/.bin/pi2` (developing pi2d)
5. **nothing** → one-line error with the install command, no `npx` fallback
Commands: `:PiWeb` (ensure + open), `:PiWebStatus`, `:PiWebStart`, `:PiWebStop`,
`:PiWebPair`, `:PiWebInstall`, `:PiWebService`, `:PiWebLog`. `:checkhealth pi` grows a
`web` section: binary source, version, daemon reachability, protocol match, service
@@ -300,7 +305,8 @@ The following items are deferred to future revisions:
- **Documentation rewrite**: `README.md`, `docs/deployment.md`, and `docs/install.md` are
rewritten to emphasize the CLI-first model and the compiled binary options.
- **Explicit `:PiWebInstall`**: `:PiWebInstall` remains available as an explicit fallback,
installing a pinned version strictly matching the plugin release after user confirmation.
installing `@yuez/pi2d@latest` (optionally pinned with a `<version>` argument) after user
confirmation.
- **Node floor lowered to >= 20**: broader compatibility for npm users without compromising
runtime stability.
- **Standalone binaries eliminate Node dependencies**: users of curl, Homebrew, and AUR
+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.
+41 -15
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.
@@ -472,20 +476,40 @@ raw module matrix without a quiet zone (`size` strings of `size` `1`/`0` charact
HTTP mint response carries the same matrix, so the console and a terminal draw the same
symbol. A URL too long for version 10 is printed without a QR, with a note.
Machines call `POST /api/v1/pair` directly — that is what `:PiWebPair` does — so the CLI
keeps only this human report; there is no `--json`.
Machines and editor plugins use `--json`, which prints the normalised mint payload
(`{url, code, expiresAt?, qr?, bases[]}`) instead of the human report. `:PiWebPair` in
pi2.nvim renders exactly that payload, so it no longer speaks HTTP itself.
### 8.6 `pi2 install-service` / `pi2 uninstall-service`
### 8.6 `pi2 install-service` / `pi2 service`
See [§9](#9-services-systemd--launchd). `--dry-run` (default) prints the file
and the follow-up commands; `--write` writes the file (`0644`) and prints the
commands. The CLI never executes `systemctl`/`launchctl`.
See [§9](#9-services-systemd--launchd). `install-service --dry-run` (default)
prints the file and the follow-up commands; `--write` writes the file (`0644`)
and prints the commands — it never executes `systemctl`/`launchctl`.
`pi2 service …` is the explicit control surface the editor plugin calls, so the
plugin never talks to a service manager itself:
```bash
pi2 service status [--json] # manager, unit path, installed/enabled/active, linger
pi2 service start # systemctl --user start pi2.service / launchctl kickstart -k
pi2 service stop # systemctl --user stop pi2.service / launchctl kill TERM
pi2 service enable # … enable --now / launchctl bootstrap + enable
pi2 service disable # … disable --now / launchctl bootout
```
`service status` always exits `0` and reports the world as it is (no manager,
no unit and a dead service are reports, not errors). The four mutating actions
exit `1` with the manager's first stderr line when it refuses; they refuse to
run at all when the unit file is missing (run `pi2 install-service --write`
first).
## 9. Services (systemd / launchd)
```bash
pi2 install-service --dry-run # inspect, nothing written
pi2 install-service --write # ~/.config/systemd/user/pi2.service
pi2 service enable # daemon-reload + enable --now (one explicit command)
# or, by hand:
systemctl --user daemon-reload
systemctl --user enable --now pi2.service
```
@@ -499,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
@@ -515,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.
@@ -534,9 +558,11 @@ Note: `launchd` on macOS has no direct equivalent for systemd's `EnvironmentFile
Environment variables on macOS must be set in the plist `EnvironmentVariables` dictionary
or via shell environment.
`uninstall-service --write` removes the file and prints the disable commands.
For a login-less service to keep running on Linux enable linger
(`loginctl enable-linger $USER`, `pi2 doctor` warns when it is off).
`uninstall-service --write` removes the file and prints the disable commands
(`pi2 service disable` runs the `--now` variant when you want the daemon stopped
too). For a login-less service to keep running on Linux enable linger
(`loginctl enable-linger $USER`, `pi2 doctor` warns when it is off;
`pi2 service status --json` reports `linger`).
## 10. Logs and health
+43 -13
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`)
@@ -173,7 +181,7 @@ The CLI inspects how it was installed:
systemctl --user stop pi2.service # stop daemon
```
> **Important**: When running under systemd with `Restart=on-failure`, do **not** use `:PiWebStop` inside Neovim or process kill signals to shut down the daemon. Always use `systemctl --user stop pi2.service` so systemd does not interpret the shutdown as a failure and immediately restart it.
> **Important**: When running under systemd with `Restart=on-failure`, stop the daemon with `pi2 service stop` (or `systemctl --user stop pi2.service`), never by signalling the process directly. `:PiWebStop` in Neovim only detaches the editor-side bridge and deliberately leaves the daemon alone.
#### macOS (`launchd`)
@@ -241,9 +249,12 @@ require("pi").setup({
})
```
When you run `:PiWeb`, the plugin discovers `pi2` on `$PATH`, spawns a detached `pi2 daemon` process, and monitors its health.
When you run `:PiWeb`, the plugin attaches to a running daemon, otherwise starts
the installed user service (`pi2 service start`), otherwise spawns a detached
`pi2 daemon` process — the three steps of `web.autostart = "auto"`.
- Logs are written to `$PI2_STATE_DIR/daemon.log` (`~/.local/state/pi2/daemon.log` on Linux, `~/Library/Logs/pi2/daemon.log` on macOS).
- Stop the spawned daemon with `:PiWebStop` in Neovim or `pi2 stop` from your terminal.
- `:PiWebStop` stops only the editor-side bridge; the daemon keeps running. Stop it with `pi2 service stop` (service mode) or `pi2 stop` (any mode).
- `:PiWebService` reports the unit and runs `pi2 service enable|disable|start|stop`; `:PiWebLog` shows the service manager's log or `daemon.log`.
---
@@ -310,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
+8
View File
@@ -56,6 +56,8 @@ The plugin dials the daemon (`<runtime>/d.sock`), sends `hello` first.
{"v":1,"type":"event","sessionId":"s1","epoch":"e1","seq":11,"ts":1733234400123,"payload":{"event":{ /* SessionEvent */ }}}
{"v":1,"type":"ack","id":"req-1","seq":12,"payload":{"disposition":"started"}}
{"v":1,"type":"error","id":"req-1","payload":{"code":"E_LEASE","message":"session is owned by instance i-2","retryable":false}}
// deliberate disconnect: sent once before the socket closes (`:PiWebStop`, VimLeavePre)
{"v":1,"type":"bye","payload":{"reason":"stopped"}}
// daemon → plugin
{"v":1,"type":"cmd","id":"req-1","sessionId":"s1","payload":{"method":"prompt.send","params":{"text":"hi"},"clientRequestId":"c-9"}}
@@ -69,6 +71,12 @@ The plugin dials the daemon (`<runtime>/d.sock`), sends `hello` first.
Plugin obligations:
- **Say `bye` when leaving on purpose.** A plugin that stops the bridge (`:PiWebStop`, `VimLeavePre`)
writes one framed `bye` (`payload.reason`) before closing the socket, and only when the connection
was live. The daemon records it as the instance's close reason (`plugin said bye`) instead of a
generic `socket closed`, so a deliberate disconnect is distinguishable from a crash; a plugin that
simply disappears stays a socket close.
- **`hello` requires `lua/pi/host.lua`.** A daemon-spawned instance is started as
`nvim --headless … -u <init> -c 'lua require("pi.host").start()'`, so the host module is what
answers on a spawned workspace. Without it the daemon cannot start a workspace from the web
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@yuez/pi2d",
"version": "0.1.6",
"version": "0.1.7",
"type": "module",
"license": "MIT",
"description": "pi2 web console daemon (`pi2 daemon`): HTTP/WS gateway, workspace registry and instance supervisor for pi2.nvim",
+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
+105 -3
View File
@@ -10,6 +10,7 @@
* pi2 pairing create a pairing code for another device
* pi2 install-service render/install a systemd user unit or LaunchAgent
* pi2 uninstall-service remove it again
* pi2 service … status/start/stop/enable/disable that unit
*
* Everything is discovered from the runtime dir: `daemon.json` carries the
* bound port, `cli.token` the local admin token (see docs/deployment.md).
@@ -48,10 +49,28 @@ 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,
SERVICE_USAGE,
type ExecResult as ServiceExecResult,
type ServiceAction,
} from "./service-control.js";
export { CliError } from "./util.js";
export { runStop, STOP_USAGE, type StopOptions } from "./stop.js";
export { runConfig, CONFIG_USAGE, type RunConfigOptions } from "./config.js";
export {
SERVICE_ACTIONS,
SERVICE_USAGE,
parseServiceArgs,
runServiceCommand,
serviceArgv,
serviceStatus,
type ServiceStatus,
type ServiceAction,
} from "./service-control.js";
export const USAGE = `pi2 — pi2 client
@@ -64,9 +83,11 @@ Usage:
pi2 open [--print] [--no-browser] open the web console signed in (local only)
pi2 config [--json] resolved configuration and sources
pi2 doctor [--json] environment checks
pi2 pairing [--base <url>] create a pairing code (URL + code + QR)
pi2 pairing [--base <url>] [--json] create a pairing code (URL + code + QR)
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
@@ -74,7 +95,9 @@ does not exit in time; -t, --timeout <sec> configures the wait timeout (default
\`pi2 open\` flags: --print prints the URL only; --no-browser prints it instead
of launching a browser (--print implies --no-browser).
\`pi2 pairing\` flags: --base <url> pins the link to one of the addresses the
daemon advertises (it prints the alternatives; anything else is rejected).
daemon advertises (it prints the alternatives; anything else is rejected);
--json prints the normalised mint payload ({url, code, expiresAt, qr, bases})
for tools and editor plugins instead of the human report.
The link prefers a phone-reachable address: the public URL when one is
configured, the primary LAN address, and loopback otherwise.
@@ -370,6 +393,8 @@ export interface PairingOptions {
print?: (line: string) => void;
/** `--base <url>`: pin the link to one of the addresses the daemon advertises. */
base?: string | null;
/** `--json`: emit the mint payload (url/code/expiry/QR matrix/bases) instead of a report. */
json?: boolean;
}
/** One address the daemon says it is reachable on (`bases[]` in the mint response). */
@@ -489,6 +514,25 @@ export async function runPairing(options: PairingOptions): Promise<number> {
const qr = pairingQrOf(response.body.qr);
const bases = pairingBasesOf(response.body.bases);
if (options.json === true) {
// The same payload the HTTP mint returned, normalised: `:PiWebPair` in
// pi2.nvim renders this instead of talking HTTP itself.
print(
JSON.stringify(
{
url,
code,
...(expiresAt === undefined ? {} : { expiresAt }),
...(qr === undefined ? {} : { qr }),
bases,
},
null,
2,
),
);
return 0;
}
print(`url ${url}`);
print(`code ${code}`);
if (expiresAt !== undefined) {
@@ -699,6 +743,12 @@ export interface Pi2Options {
isPidAlive?: (pid: number) => boolean;
kill?: (pid: number, signal: NodeJS.Signals) => void;
sleep?: (ms: number) => Promise<void>;
/** Injected service manager runner (defaults to `spawnSync`). */
serviceExec?: (argv: string[]) => ServiceExecResult;
/** Injected unit-file existence probe (defaults to `fs.existsSync`). */
serviceExists?: (path: string) => boolean;
serviceUid?: number;
serviceUser?: string;
}
export async function main(argv: readonly string[], options: Pi2Options = {}): Promise<number> {
@@ -812,7 +862,7 @@ export async function main(argv: readonly string[], options: Pi2Options = {}): P
case "pair": {
const parsed = parseArgs(rest, {
values: ["--base"],
booleans: ["--help"],
booleans: ["--json", "--help"],
aliases: { "-h": "--help" },
});
if (boolFlag(parsed.flags, "--help")) {
@@ -824,6 +874,7 @@ export async function main(argv: readonly string[], options: Pi2Options = {}): P
client,
print: out,
base: stringFlag(parsed.flags, "--base"),
json: boolFlag(parsed.flags, "--json"),
});
}
case "install-service":
@@ -845,6 +896,57 @@ 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) {
out(SERVICE_USAGE);
return 0;
}
const platform = options.platform ?? (osPlatform() === "darwin" ? "darwin" : "linux");
const paths = options.servicePaths ?? defaultServicePaths();
return await runServiceCommand(parsed.action as ServiceAction, {
platform,
paths,
print: out,
json: parsed.json,
...(options.env === undefined ? {} : { env: options.env }),
...(options.serviceExec === undefined ? {} : { exec: options.serviceExec }),
...(options.serviceExists === undefined ? {} : { exists: options.serviceExists }),
...(options.serviceUid === undefined ? {} : { uid: options.serviceUid }),
...(options.serviceUser === undefined ? {} : { user: options.serviceUser }),
});
}
default:
err(`pi2: unknown command "${command}"`);
err(USAGE);
+378
View File
@@ -0,0 +1,378 @@
/**
* `pi2 service status|start|stop|enable|disable` — user-service control.
*
* `pi2 install-service --write` renders the unit file and stops there
* (`src/cli/service.ts` is pure string generation). This module is the explicit
* counterpart: it talks to systemd / launchd, but only when the user asks for it
* (ADR 0002 §2.2). The Neovim plugin never shells out to a service manager
* itself — it calls `pi2 service …`, so the platform knowledge stays here.
*
* Two properties the callers depend on:
* 1. `status` never fails: no manager, no unit and a dead service are all
* reports, not errors (`--json` is the machine-readable form).
* 2. `start|stop|enable|disable` are the only paths that mutate state, and a
* manager refusal becomes a `CliError` with the manager's own first line.
*
* Everything is injected (`exec`, `exists`, `platform`, `paths`, `uid`, `user`,
* `env`) so the tests stay hermetic: nothing here runs a real systemctl.
*/
import { spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import { userInfo } from "node:os";
import { join } from "node:path";
import {
defaultServicePaths,
LAUNCHD_LABEL,
LAUNCHD_PLIST_NAME,
launchAgentDir,
SYSTEMD_UNIT_NAME,
systemdUserDir,
type ServicePaths,
type ServicePlatform,
} from "./service.js";
import { CliError, parseArgs, type FlagValue, UsageError } from "./util.js";
export type ServiceAction = "status" | "start" | "stop" | "enable" | "disable";
/** Every action the dispatcher accepts, in help order. */
export const SERVICE_ACTIONS: readonly ServiceAction[] = ["status", "start", "stop", "enable", "disable"];
export const SERVICE_USAGE = `pi2 service — control the user service that runs the daemon
Usage:
pi2 service status [--json] report the unit, enablement, activity and linger
pi2 service start start the installed unit
pi2 service stop stop it (disable the unit to keep it down)
pi2 service enable enable it (systemd: --now; launchd: bootstrap+enable)
pi2 service disable disable it (systemd: --now; launchd: bootout)
The unit is the one \`pi2 install-service --write\` renders
(\`pi2.service\` on Linux, \`com.pi2.daemon.plist\` on macOS).
\`--json\` is only valid for \`service status\`.`;
export interface ExecResult {
code: number;
stdout: string;
stderr: string;
}
/** One `systemctl`/`launchctl` invocation, injectable in tests. */
export type ServiceExec = (argv: string[]) => ExecResult;
export interface ServiceStatus {
platform: ServicePlatform;
manager: "systemd" | "launchd" | "none";
unit: { name: string; path: string; installed: boolean };
enabled: boolean | null;
active: boolean | null;
linger: boolean | null;
error: string | null;
}
export interface ServiceContext {
platform: ServicePlatform;
paths: ServicePaths;
uid: number;
user: string;
env: Record<string, string | undefined>;
}
export interface ServiceControlOptions {
platform?: ServicePlatform;
paths?: ServicePaths;
exec?: ServiceExec;
exists?: (path: string) => boolean;
uid?: number;
user?: string;
env?: Record<string, string | undefined>;
print?: (line: string) => void;
json?: boolean;
}
/** `spawnSync` wrapper: a missing binary is `code 127`, never a throw. */
export function defaultServiceExec(argv: string[]): ExecResult {
const [command, ...args] = argv;
if (command === undefined) {
return { code: 127, stdout: "", stderr: "empty command" };
}
const result = spawnSync(command, args, {
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
});
if (result.error !== undefined) {
return { code: 127, stdout: "", stderr: result.error.message };
}
return {
code: result.status ?? (result.signal === null ? 1 : 1),
stdout: result.stdout ?? "",
stderr: result.stderr ?? "",
};
}
/** Resolve the platform-specific bits once, honouring every injection point. */
export function serviceContext(options: ServiceControlOptions = {}): ServiceContext {
const platform =
options.platform ?? ((process.platform === "darwin" ? "darwin" : "linux") as ServicePlatform);
const paths = options.paths ?? defaultServicePaths();
const uid = options.uid ?? (typeof process.getuid === "function" ? process.getuid() : 0);
const user = options.user ?? (process.env.USER ?? process.env.LOGNAME ?? safeUserInfo());
const env = options.env ?? process.env;
return { platform, paths, uid, user, env };
}
function safeUserInfo(): string {
try {
return userInfo().username;
} catch {
return "user";
}
}
/** Unit name + absolute path for the platform (the file `install-service` writes). */
export function serviceUnit(ctx: ServiceContext): { name: string; path: string } {
if (ctx.platform === "darwin") {
return { name: LAUNCHD_PLIST_NAME, path: join(launchAgentDir(ctx.paths), LAUNCHD_PLIST_NAME) };
}
return { name: SYSTEMD_UNIT_NAME, path: join(systemdUserDir(ctx.paths), SYSTEMD_UNIT_NAME) };
}
/** `gui/<uid>/com.pi2.daemon` — the launchd job target. */
function launchdTarget(ctx: ServiceContext): string {
return `gui/${ctx.uid}/${LAUNCHD_LABEL}`;
}
/**
* The commands one action runs, in order. Pure: no process is started here, so
* the tests assert argv directly. `status` is a probe set, not a command list,
* and therefore returns `[]`.
*/
export function serviceArgv(action: ServiceAction, ctx: ServiceContext): string[][] {
if (action === "status") {
return [];
}
const unit = serviceUnit(ctx);
if (ctx.platform === "darwin") {
switch (action) {
case "start":
return [["launchctl", "kickstart", "-k", launchdTarget(ctx)]];
case "stop":
return [["launchctl", "kill", "TERM", launchdTarget(ctx)]];
case "enable":
// `bootstrap` registers a plist that is not loaded yet; the
// second call makes sure the job is also enabled at login.
return [
["launchctl", "bootstrap", `gui/${ctx.uid}`, unit.path],
["launchctl", "enable", launchdTarget(ctx)],
];
case "disable":
return [["launchctl", "bootout", `gui/${ctx.uid}`]];
}
}
switch (action) {
case "start":
return [["systemctl", "--user", "start", unit.name]];
case "stop":
return [["systemctl", "--user", "stop", unit.name]];
case "enable":
return [["systemctl", "--user", "enable", "--now", unit.name]];
case "disable":
return [["systemctl", "--user", "disable", "--now", unit.name]];
}
}
/** First non-empty line of stderr, else stdout, else a generic message. */
function firstLine(...texts: string[]): string {
for (const text of texts) {
const line = text
.split("\n")
.map((entry) => entry.trim())
.find((entry) => entry !== "");
if (line !== undefined) {
return line;
}
}
return "";
}
function shellLine(argv: string[]): string {
return argv.join(" ");
}
/** `Linger=yes` → true, `Linger=no` → false, anything else → null. */
function parseLinger(result: ExecResult): boolean | null {
if (result.code !== 0) {
return null;
}
const match = /^Linger=(yes|no)$/m.exec(result.stdout);
if (match === null) {
return null;
}
return match[1] === "yes";
}
/**
* Probe the unit without mutating anything. Never throws: an unavailable
* service manager yields `manager: "none"`, `null` flags and a one-line error.
*/
export function serviceStatus(options: ServiceControlOptions = {}): ServiceStatus {
const ctx = serviceContext(options);
const exec = options.exec ?? defaultServiceExec;
const exists = options.exists ?? existsSync;
const unit = serviceUnit(ctx);
const installed = exists(unit.path);
if (ctx.platform === "darwin") {
const probe = exec(["launchctl", "print", launchdTarget(ctx)]);
const managerMissing = probe.code === 127;
return {
platform: "darwin",
manager: managerMissing ? "none" : "launchd",
unit: { ...unit, installed },
enabled: managerMissing ? null : installed,
active: managerMissing ? null : probe.code === 0,
linger: null,
error: managerMissing ? firstLine(probe.stderr) || "launchctl not found on PATH" : null,
};
}
const available = exec(["systemctl", "--version"]);
if (available.code !== 0) {
return {
platform: "linux",
manager: "none",
unit: { ...unit, installed },
enabled: null,
active: null,
linger: null,
error: firstLine(available.stderr) || "systemctl not found on PATH",
};
}
const enabledProbe = exec(["systemctl", "--user", "is-enabled", unit.name]);
const activeProbe = exec(["systemctl", "--user", "is-active", unit.name]);
const lingerProbe = exec(["loginctl", "show-user", ctx.user, "-p", "Linger"]);
return {
platform: "linux",
manager: "systemd",
unit: { ...unit, installed },
// is-enabled exits 0 for enabled, non-zero for disabled/static/masked;
// a 127 here would mean systemd vanished between the two calls.
enabled: enabledProbe.code === 127 ? null : enabledProbe.code === 0,
active: activeProbe.code === 127 ? null : activeProbe.code === 0,
linger: parseLinger(lingerProbe),
error: null,
};
}
/** Human-readable `service status` report, one fact per line. */
export function formatServiceStatus(status: ServiceStatus): string[] {
const lines: string[] = [];
const manager = status.manager === "none" ? "none (no service manager available)" : status.manager;
lines.push(`manager ${manager}`);
lines.push(`unit ${status.unit.path}${status.unit.installed ? "" : " (missing)"}`);
const flag = (value: boolean | null): string => (value === null ? "unknown" : value ? "yes" : "no");
lines.push(`installed ${status.unit.installed ? "yes" : "no"}`);
lines.push(`enabled ${flag(status.enabled)}`);
lines.push(`active ${flag(status.active)}`);
if (status.platform === "linux") {
lines.push(`linger ${flag(status.linger)}`);
}
if (status.error !== null) {
lines.push(`error ${status.error}`);
}
if (!status.unit.installed) {
lines.push("# next: pi2 install-service --write, then pi2 service enable");
} else if (status.enabled !== true || status.active !== true) {
lines.push("# next: pi2 service enable");
}
return lines;
}
/** Machine-readable `service status --json` body. */
export function formatServiceStatusJson(status: ServiceStatus): string {
return JSON.stringify(status, null, 2);
}
/**
* Run one action.
*
* `status` prints a report and returns 0 whatever the state of the world.
* The four mutating actions return 0 on success and throw a `CliError` when a
* manager command fails (with that manager's first stderr line).
*/
export async function runServiceCommand(
action: ServiceAction,
options: ServiceControlOptions = {},
): Promise<number> {
const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`));
const ctx = serviceContext(options);
if (action === "status") {
const status = serviceStatus(options);
if (options.json === true) {
print(formatServiceStatusJson(status));
} else {
for (const line of formatServiceStatus(status)) {
print(line);
}
}
return 0;
}
const unit = serviceUnit(ctx);
const exists = options.exists ?? existsSync;
if (!exists(unit.path)) {
throw new CliError(
`no service unit at ${unit.path} — run \`pi2 install-service --write\` first`,
);
}
const exec = options.exec ?? defaultServiceExec;
const argvList = serviceArgv(action, ctx);
for (const argv of argvList) {
const result = exec(argv);
if (result.code !== 0) {
const detail = firstLine(result.stderr, result.stdout);
throw new CliError(
detail !== ""
? `${shellLine(argv)} failed: ${detail}`
: `${shellLine(argv)} failed (exit ${result.code})`,
);
}
}
print(`service ${action}: ${argvList.map(shellLine).join(" && ")}`);
if (action === "stop") {
print("# the unit is still enabled; run `pi2 service disable` to keep it down");
}
return 0;
}
// ---------------------------------------------------------------------------
// dispatcher glue
// ---------------------------------------------------------------------------
/** Parse `pi2 service …` argv into an action + flags. Throws `UsageError`. */
export function parseServiceArgs(argv: readonly string[]): { action: ServiceAction; json: boolean; help: boolean } {
const parsed = parseArgs(argv, {
booleans: ["--json", "--help"],
aliases: { "-h": "--help" },
});
const flags: Record<string, FlagValue> = parsed.flags;
const help = flags["--help"] === true;
const json = flags["--json"] === true;
if (help) {
return { action: "status", json, help };
}
const raw = parsed.positionals[0] ?? "status";
if (!SERVICE_ACTIONS.includes(raw as ServiceAction)) {
throw new UsageError(`unknown service action "${raw}"`, SERVICE_USAGE);
}
if (parsed.positionals.length > 1) {
throw new UsageError(`unexpected argument "${parsed.positionals[1]}"`, SERVICE_USAGE);
}
if (json && raw !== "status") {
throw new UsageError("--json is only valid for `pi2 service status`", SERVICE_USAGE);
}
return { action: raw as ServiceAction, json, 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;
}
+42
View File
@@ -398,6 +398,48 @@ describe("pi2 pairing", () => {
expect(lines.some((line) => /[█▀▄]/.test(line))).toBe(false);
});
it("emits the normalised mint payload with --json (no terminal art)", async () => {
const lines: string[] = [];
const client = fakeClient({ pair: minted() });
const code = await runPairing({ client, print: (line) => lines.push(line), json: true });
expect(code).toBe(0);
const payload = JSON.parse(lines.join("\n")) as Record<string, unknown>;
expect(payload.url).toBe("http://192.168.2.10:7712/pair/ABCD2345");
expect(payload.code).toBe("ABCD2345");
expect(typeof payload.expiresAt).toBe("number");
expect(payload.qr).toMatchObject({ version: 2, size: 25 });
expect((payload.qr as { rows: string[] }).rows).toHaveLength(25);
expect(payload.bases).toEqual([
{ kind: "lan", name: "wlan0", address: "192.168.2.10", url: "http://192.168.2.10:7712" },
{ kind: "loopback", name: "loopback", address: "127.0.0.1", url: "http://127.0.0.1:7712" },
]);
expect(lines.some((line) => /[█▀▄]/.test(line))).toBe(false);
});
it("omits qr/expiresAt from --json when the daemon sent none", async () => {
const lines: string[] = [];
const client = fakeClient({ pair: minted({ qr: null, expiresAt: undefined }) });
await runPairing({ client, print: (line) => lines.push(line), json: true });
const payload = JSON.parse(lines.join("\n")) as Record<string, unknown>;
expect(payload).not.toHaveProperty("qr");
expect(payload).not.toHaveProperty("expiresAt");
expect(payload.code).toBe("ABCD2345");
});
it("reaches --json through the dispatcher", async () => {
const lines: string[] = [];
const client = fakeClient({ pair: minted() });
const code = await main(["pairing", "--json"], { out: (line) => lines.push(line), client: () => client });
expect(code).toBe(0);
expect(JSON.parse(lines.join("\n"))).toMatchObject({ code: "ABCD2345" });
});
it("exits non-zero when the daemon rejects the request", async () => {
await expect(
runPairing({ client: fakeClient({ postError: new CliError("pair failed: E_UNAUTHORIZED") }) }),
+346
View File
@@ -0,0 +1,346 @@
import { describe, expect, it } from "vitest";
import { join } from "node:path";
import {
formatServiceStatus,
parseServiceArgs,
runServiceCommand,
serviceArgv,
serviceContext,
serviceStatus,
serviceUnit,
type ExecResult,
type ServiceControlOptions,
} from "../../src/cli/service-control.js";
import { LAUNCHD_LABEL, SYSTEMD_UNIT_NAME, type ServicePaths } from "../../src/cli/service.js";
import { main } from "../../src/cli/pi2.js";
import { CliError, UsageError } from "../../src/cli/util.js";
const paths: ServicePaths = {
bundled: true,
execPath: "/usr/local/bin/pi2",
envFile: "-%h/.config/pi2/env",
stateDir: "/home/u/.local/state/pi2",
homeDir: "/home/u",
pathEnv: "/usr/local/bin:/usr/bin:/bin",
};
const linux = serviceContext({ platform: "linux", paths, uid: 1000, user: "u" });
const darwin = serviceContext({ platform: "darwin", paths, uid: 501, user: "u" });
const OK: ExecResult = { code: 0, stdout: "", stderr: "" };
/** `exec` stub: a map from the exact argv (joined by spaces) to a result. */
function execMap(map: Record<string, ExecResult>): (argv: string[]) => ExecResult {
return (argv: string[]) => {
const key = argv.join(" ");
const hit = map[key];
if (hit !== undefined) {
return hit;
}
throw new Error(`unexpected command: ${key}`);
};
}
describe("serviceArgv", () => {
it("maps every action on systemd", () => {
expect(serviceArgv("start", linux)).toEqual([["systemctl", "--user", "start", SYSTEMD_UNIT_NAME]]);
expect(serviceArgv("stop", linux)).toEqual([["systemctl", "--user", "stop", SYSTEMD_UNIT_NAME]]);
expect(serviceArgv("enable", linux)).toEqual([
["systemctl", "--user", "enable", "--now", SYSTEMD_UNIT_NAME],
]);
expect(serviceArgv("disable", linux)).toEqual([
["systemctl", "--user", "disable", "--now", SYSTEMD_UNIT_NAME],
]);
expect(serviceArgv("status", linux)).toEqual([]);
});
it("maps every action on launchd", () => {
const target = `gui/501/${LAUNCHD_LABEL}`;
const plist = join(paths.homeDir, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
expect(serviceArgv("start", darwin)).toEqual([["launchctl", "kickstart", "-k", target]]);
expect(serviceArgv("stop", darwin)).toEqual([["launchctl", "kill", "TERM", target]]);
expect(serviceArgv("enable", darwin)).toEqual([
["launchctl", "bootstrap", "gui/501", plist],
["launchctl", "enable", target],
]);
expect(serviceArgv("disable", darwin)).toEqual([["launchctl", "bootout", "gui/501"]]);
});
it("puts the unit under the platform config dir", () => {
expect(serviceUnit(linux)).toEqual({
name: SYSTEMD_UNIT_NAME,
path: join(paths.homeDir, ".config", "systemd", "user", SYSTEMD_UNIT_NAME),
});
expect(serviceUnit(darwin).path).toBe(
join(paths.homeDir, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`),
);
});
});
describe("serviceStatus", () => {
const unitPath = join(paths.homeDir, ".config", "systemd", "user", SYSTEMD_UNIT_NAME);
const base: ServiceControlOptions = {
platform: "linux",
paths,
uid: 1000,
user: "u",
exists: () => true,
};
it("reports an enabled, active unit with linger on", () => {
const status = serviceStatus({
...base,
exec: execMap({
"systemctl --version": { code: 0, stdout: "systemd 255", stderr: "" },
[`systemctl --user is-enabled ${SYSTEMD_UNIT_NAME}`]: { code: 0, stdout: "enabled", stderr: "" },
[`systemctl --user is-active ${SYSTEMD_UNIT_NAME}`]: { code: 0, stdout: "active", stderr: "" },
"loginctl show-user u -p Linger": { code: 0, stdout: "Linger=yes\n", stderr: "" },
}),
});
expect(status).toEqual({
platform: "linux",
manager: "systemd",
unit: { name: SYSTEMD_UNIT_NAME, path: unitPath, installed: true },
enabled: true,
active: true,
linger: true,
error: null,
});
});
it("reports a disabled, inactive unit and keeps exit 0 semantics", async () => {
const status = serviceStatus({
...base,
exec: execMap({
"systemctl --version": { code: 0, stdout: "systemd 255", stderr: "" },
[`systemctl --user is-enabled ${SYSTEMD_UNIT_NAME}`]: { code: 1, stdout: "disabled", stderr: "" },
[`systemctl --user is-active ${SYSTEMD_UNIT_NAME}`]: { code: 3, stdout: "inactive", stderr: "" },
"loginctl show-user u -p Linger": { code: 0, stdout: "Linger=no\n", stderr: "" },
}),
});
expect(status.enabled).toBe(false);
expect(status.active).toBe(false);
expect(status.linger).toBe(false);
const out: string[] = [];
const code = await runServiceCommand("status", {
...base,
print: (line) => out.push(line),
json: true,
});
expect(code).toBe(0);
const decoded = JSON.parse(out.join("\n")) as Record<string, unknown>;
expect(decoded.manager).toBe("systemd");
expect(decoded.unit).toMatchObject({ name: SYSTEMD_UNIT_NAME, path: unitPath });
});
it("degrades to manager \"none\" when systemctl is unavailable", () => {
const status = serviceStatus({
...base,
exists: () => false,
exec: () => ({ code: 127, stdout: "", stderr: "spawnSync systemctl ENOENT" }),
});
expect(status.manager).toBe("none");
expect(status.enabled).toBeNull();
expect(status.active).toBeNull();
expect(status.linger).toBeNull();
expect(status.error).toContain("ENOENT");
expect(status.unit.installed).toBe(false);
});
it("probes launchd through `launchctl print`", () => {
const plist = join(paths.homeDir, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
const status = serviceStatus({
platform: "darwin",
paths,
uid: 501,
exists: (path) => path === plist,
exec: execMap({
[`launchctl print gui/501/${LAUNCHD_LABEL}`]: { code: 0, stdout: "state = running", stderr: "" },
}),
});
expect(status.manager).toBe("launchd");
expect(status.unit.installed).toBe(true);
expect(status.enabled).toBe(true);
expect(status.active).toBe(true);
expect(status.linger).toBeNull();
});
});
describe("formatServiceStatus", () => {
it("suggests install then enable when the unit is missing", () => {
const lines = formatServiceStatus({
platform: "linux",
manager: "systemd",
unit: { name: SYSTEMD_UNIT_NAME, path: "/home/u/.config/systemd/user/pi2.service", installed: false },
enabled: null,
active: null,
linger: null,
error: null,
});
expect(lines.join("\n")).toContain("pi2 install-service --write, then pi2 service enable");
expect(lines.join("\n")).toContain("(missing)");
});
it("suggests enable when the unit exists but is not running", () => {
const lines = formatServiceStatus({
platform: "darwin",
manager: "launchd",
unit: { name: `${LAUNCHD_LABEL}.plist`, path: "/x.plist", installed: true },
enabled: true,
active: false,
linger: null,
error: null,
});
const text = lines.join("\n");
expect(text).toContain("# next: pi2 service enable");
expect(text).not.toContain("linger");
});
});
describe("runServiceCommand", () => {
const unitPath = join(paths.homeDir, ".config", "systemd", "user", SYSTEMD_UNIT_NAME);
const out: string[] = [];
it("refuses to start a service that was never installed", async () => {
await expect(
runServiceCommand("start", {
platform: "linux",
paths,
print: () => {},
exists: () => false,
}),
).rejects.toBeInstanceOf(CliError);
});
it("runs the mapped commands for `enable`", async () => {
const ran: string[][] = [];
const code = await runServiceCommand("enable", {
platform: "linux",
paths,
print: (line) => out.push(line),
exists: () => true,
exec: (argv) => {
ran.push(argv);
return OK;
},
});
expect(code).toBe(0);
expect(ran).toEqual([["systemctl", "--user", "enable", "--now", SYSTEMD_UNIT_NAME]]);
expect(out.join("\n")).toContain("service enable: systemctl --user enable --now pi2.service");
});
it("turns a manager refusal into a CliError with its own first line", async () => {
const error = await runServiceCommand("start", {
platform: "linux",
paths,
print: () => {},
exists: () => true,
exec: () => ({
code: 1,
stdout: "",
stderr: "Failed to start pi2.service: Unit pi2.service not found.\nmore",
}),
}).catch((err: unknown) => err);
expect(error).toBeInstanceOf(CliError);
expect((error as CliError).message).toContain("Unit pi2.service not found.");
expect((error as CliError).message).toContain("systemctl --user start pi2.service");
});
it("mentions the still-enabled unit after a stop", async () => {
const notes: string[] = [];
await runServiceCommand("stop", {
platform: "linux",
paths,
print: (line) => notes.push(line),
exists: () => true,
exec: () => OK,
});
expect(notes.join("\n")).toContain("pi2 service disable");
});
});
describe("parseServiceArgs", () => {
it("defaults to status and accepts --json", () => {
expect(parseServiceArgs([])).toEqual({ action: "status", json: false, help: false });
expect(parseServiceArgs(["--json"])).toEqual({ action: "status", json: true, help: false });
expect(parseServiceArgs(["start"]).action).toBe("start");
});
it("rejects unknown actions, extra positionals and --json on a mutating action", () => {
expect(() => parseServiceArgs(["frobnicate"])).toThrow(UsageError);
expect(() => parseServiceArgs(["start", "extra"])).toThrow(UsageError);
expect(() => parseServiceArgs(["start", "--json"])).toThrow(UsageError);
});
});
describe("pi2 service (dispatch)", () => {
function collect(): { out: string[]; err: string[] } {
return { out: [], err: [] };
}
it("prints the JSON report and exits 0 with no unit installed", async () => {
const sink = collect();
const unit = join(paths.homeDir, ".config", "systemd", "user", SYSTEMD_UNIT_NAME);
const code = await main(["service", "status", "--json"], {
out: (line) => sink.out.push(line),
err: (line) => sink.err.push(line),
platform: "linux",
servicePaths: paths,
serviceUid: 1000,
serviceUser: "u",
serviceExists: () => false,
serviceExec: (argv) => {
const key = argv.join(" ");
if (key === "systemctl --version") {
return { code: 0, stdout: "systemd 255", stderr: "" };
}
if (key.startsWith("systemctl --user is-enabled")) {
return { code: 1, stdout: "disabled", stderr: "" };
}
if (key.startsWith("systemctl --user is-active")) {
return { code: 3, stdout: "inactive", stderr: "" };
}
if (key.startsWith("loginctl show-user")) {
return { code: 0, stdout: "Linger=no", stderr: "" };
}
throw new Error(`unexpected: ${key}`);
},
});
expect(code).toBe(0);
const decoded = JSON.parse(sink.out.join("\n")) as { unit: { path: string; installed: boolean } };
expect(decoded.unit).toEqual({ name: SYSTEMD_UNIT_NAME, path: unit, installed: false });
});
it("maps a failing start to exit code 1", async () => {
const sink = collect();
const code = await main(["service", "start"], {
out: (line) => sink.out.push(line),
err: (line) => sink.err.push(line),
platform: "linux",
servicePaths: paths,
serviceExists: () => true,
serviceExec: () => ({ code: 1, stdout: "", stderr: "Job failed. See system logs." }),
});
expect(code).toBe(1);
expect(sink.err.join("\n")).toContain("Job failed. See system logs.");
});
it("prints usage for an unknown action (exit 2)", async () => {
const sink = collect();
const code = await main(["service", "wat"], {
out: (line) => sink.out.push(line),
err: (line) => sink.err.push(line),
platform: "linux",
servicePaths: paths,
});
expect(code).toBe(2);
expect(sink.err.join("\n")).toContain("unknown service action");
});
it("documents itself in `pi2 --help`", async () => {
const sink = collect();
await main(["--help"], { out: (line) => sink.out.push(line), err: (line) => sink.err.push(line) });
expect(sink.out.join("\n")).toContain("pi2 service status|start|stop|enable|disable");
});
});
+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);
});
});