From 2fc5f99f598000d811f5d97410b021edd33039a3 Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Mon, 16 Nov 2026 15:31:00 +0100 Subject: [PATCH] feat(server): request updates through a systemd trigger (#15) The service stays unprivileged: POST /api/settings/update only writes the update-request file in the data directory, which a root-owned path unit watches. Status comes from systemctl show and the root-owned update log; the check fetches the tracked branch into FETCH_HEAD and lists new commits. --- apps/server/src/app.ts | 6 +- apps/server/src/update/index.ts | 180 ++++++++++++++++++++++++++++++++ apps/server/test/update.test.ts | 168 +++++++++++++++++++++++++++++ docs/spec.md | 8 ++ packages/core/src/protocol.ts | 27 +++++ 5 files changed, 388 insertions(+), 1 deletion(-) create mode 100644 apps/server/src/update/index.ts create mode 100644 apps/server/test/update.test.ts diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts index 69f0627..404b1e5 100644 --- a/apps/server/src/app.ts +++ b/apps/server/src/app.ts @@ -10,6 +10,7 @@ import { createNotebookWatcher } from "./watch"; import { registerAuth, type AuthOptions } from "./auth"; import { registerStatic } from "./static"; import { chatPlugin } from "./chat"; +import { defaultUpdateOptions, registerUpdate, type UpdateOptions } from "./update"; export interface AppOptions { logger?: boolean; @@ -26,6 +27,8 @@ export interface AppOptions { /** Watch workspace notebooks and publish file.changed/file.deleted on /api/events. */ watchNotebooks?: boolean; terminal?: Omit; + /** Overrides for the self-update trigger (tests). */ + update?: Partial; } /** @@ -33,7 +36,7 @@ export interface AppOptions { * src/auth/ login, persistent session secret (registered first: its hook guards every /api route) * src/workspace/ notebooks, hosts.yaml; src/ssh/, src/runs/ queue, audit, artifacts, /api/events * src/terminal/ node-pty + tmux, /api/terminal; src/watch/ file.changed events into the events hub - * src/static/ built web app with SPA fallback + * src/static/ built web app with SPA fallback; src/update/ self-update trigger (root runs it via systemd) */ export async function buildApp(options: AppOptions = {}): Promise { const config = loadConfig(options.config); @@ -41,6 +44,7 @@ export async function buildApp(options: AppOptions = {}): Promise builtinValues(config); await app.register(workspacePlugin, { config, builtins }); diff --git a/apps/server/src/update/index.ts b/apps/server/src/update/index.ts new file mode 100644 index 0000000..3989bcc --- /dev/null +++ b/apps/server/src/update/index.ts @@ -0,0 +1,180 @@ +import { execFile } from "node:child_process"; +import { access, mkdir, open, writeFile } from "node:fs/promises"; +import { dirname, join } from "node:path"; +import type { FastifyInstance } from "fastify"; +import type { + UpdateCheckResponse, + UpdateStartResponse, + UpdateState, + UpdateStatusResponse, +} from "@shellbook/core"; + +/** + * Self-update from the web UI (#15). The service never gains privileges: it only writes + * a request file. A root-owned systemd path unit (deploy/install.sh) watches that file + * and starts `shellbook-update.service`, which runs the fixed root-owned updater and + * writes its output to a root-owned log. Here we only read that state back. + */ +export interface UpdateOptions { + /** Written to request an update; watched by shellbook-update.path. */ + requestFile: string; + /** Present when the trigger units are installed. */ + triggerUnit: string; + /** Output of the last update run (StandardOutput of the update unit). */ + logFile: string; + /** The git checkout the server runs from. */ + repoDir: string; + /** Runs a program with argv (no shell) and returns stdout; rejects on failure. */ + run(file: string, args: string[], timeoutMs: number): Promise; +} + +const UNIT = "shellbook-update.service"; +const LOG_BYTES = 64 * 1024; +const LOG_LINES = 200; + +function run(file: string, args: string[], timeoutMs: number): Promise { + return new Promise((resolve, reject) => { + execFile( + file, + args, + // Never wait for credentials on a terminal that is not there. + { timeout: timeoutMs, maxBuffer: 1024 * 1024, windowsHide: true, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } }, + (error, stdout) => (error ? reject(error) : resolve(stdout)), + ); + }); +} + +export function defaultUpdateOptions(dataDir: string): UpdateOptions { + return { + requestFile: join(dataDir, "update-request"), + triggerUnit: "/etc/systemd/system/shellbook-update.path", + logFile: "/var/log/shellbook-update.log", + // systemd starts the service in the checkout (WorkingDirectory=/opt/shellbook). + repoDir: process.cwd(), + run, + }; +} + +/** `--timestamp=unix` prints `@`; empty or `n/a` means never. */ +function timestamp(value: string | undefined): string | null { + const match = value?.match(/^@(\d+)$/); + return match ? new Date(Number(match[1]) * 1000).toISOString() : null; +} + +/** The last lines of the log, reading at most LOG_BYTES from its end. */ +async function logTail(path: string): Promise { + let file; + try { + file = await open(path, "r"); + } catch { + return ""; + } + try { + const { size } = await file.stat(); + const length = Math.min(size, LOG_BYTES); + const buffer = Buffer.alloc(length); + await file.read(buffer, 0, length, size - length); + const lines = buffer.toString("utf8").split("\n"); + // Drop a partial first line when the read started mid-file. + if (length < size) lines.shift(); + if (lines.at(-1) === "") lines.pop(); + return lines.slice(-LOG_LINES).join("\n"); + } finally { + await file.close(); + } +} + +export function createUpdater(options: UpdateOptions) { + const git = (args: string[], timeoutMs = 5000) => + options.run("git", ["-C", options.repoDir, ...args], timeoutMs).then((out) => out.trim()); + const current = () => git(["rev-parse", "--short", "HEAD"]).catch(() => null); + const available = () => access(options.triggerUnit).then(() => true, () => false); + + async function unitState(): Promise> { + let output: string; + try { + output = await options.run( + "systemctl", + ["show", UNIT, "--timestamp=unix", "--property=ActiveState,Result,ExecMainStartTimestamp,ExecMainExitTimestamp"], + 5000, + ); + } catch { + return { state: "unknown", startedAt: null, finishedAt: null }; + } + const props: Record = Object.fromEntries( + output.split("\n").filter((line) => line.includes("=")).map((line) => { + const at = line.indexOf("="); + return [line.slice(0, at), line.slice(at + 1).trim()]; + }), + ); + const startedAt = timestamp(props.ExecMainStartTimestamp); + const finishedAt = timestamp(props.ExecMainExitTimestamp); + let state: UpdateState; + if (["activating", "active", "reloading", "deactivating"].includes(props.ActiveState ?? "")) state = "running"; + else if (props.ActiveState === "failed" || (startedAt && props.Result !== "success")) state = "failed"; + else state = startedAt ? "succeeded" : "idle"; + return { state, startedAt, finishedAt: state === "running" ? null : finishedAt }; + } + + return { + async status(): Promise { + const [isAvailable, commit] = await Promise.all([available(), current()]); + if (!isAvailable) + return { available: false, state: "idle", current: commit, startedAt: null, finishedAt: null, log: "" }; + return { available: true, current: commit, ...(await unitState()), log: await logTail(options.logFile) }; + }, + + /** Fetches the tracked branch (FETCH_HEAD only) and lists the commits an update would bring. */ + async check(): Promise { + const commit = await current(); + const branch = await git(["symbolic-ref", "-q", "--short", "HEAD"]).catch(() => null); + // A detached HEAD is a pinned SHELLBOOK_REF: the installer never pulls it. + if (!branch) return { current: commit, latest: null, pinned: true, changes: [] }; + const upstream = await git(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]); + const slash = upstream.indexOf("/"); + if (slash <= 0) throw new Error(`Unexpected upstream: ${upstream}`); + await git(["fetch", "--quiet", "--no-tags", "--", upstream.slice(0, slash), upstream.slice(slash + 1)], 30_000); + const latest = await git(["rev-parse", "--short", "FETCH_HEAD"]); + const log = await git(["log", "--format=%h%x09%s", "-n", "50", "HEAD..FETCH_HEAD"]); + const changes = log + ? log.split("\n").map((line) => { + const tab = line.indexOf("\t"); + return { commit: line.slice(0, tab), subject: line.slice(tab + 1) }; + }) + : []; + return { current: commit, latest, pinned: false, changes }; + }, + + /** Requests an update; systemd runs it as root. Returns null when it cannot start. */ + async start(): Promise<{ ok: true; response: UpdateStartResponse } | { ok: false; error: string }> { + if (!(await available())) return { ok: false, error: "Updating from the web UI is not installed here. Run shellbook-update as root." }; + if ((await unitState()).state === "running") return { ok: false, error: "An update is already running." }; + const requestedAt = new Date().toISOString(); + await mkdir(dirname(options.requestFile), { recursive: true }); + // Closing the written file is what triggers the path unit (PathChanged=). + await writeFile(options.requestFile, requestedAt + "\n", { mode: 0o600 }); + return { ok: true, response: { requestedAt } }; + }, + }; +} + +export async function registerUpdate(app: FastifyInstance, options: UpdateOptions): Promise { + const updater = createUpdater(options); + app.get("/api/settings/update", async (_request, reply) => + reply.header("Cache-Control", "no-store").send(await updater.status()), + ); + app.post("/api/settings/update/check", async (_request, reply) => { + if ((await updater.status()).state === "running") + return reply.code(409).send({ error: "An update is running." }); + try { + return reply.header("Cache-Control", "no-store").send(await updater.check()); + } catch (error) { + app.log.warn({ err: error }, "update check failed"); + return reply.code(502).send({ error: "Could not check the repository for updates." }); + } + }); + app.post("/api/settings/update", async (_request, reply) => { + const result = await updater.start(); + return result.ok ? reply.code(202).send(result.response) : reply.code(409).send({ error: result.error }); + }); +} diff --git a/apps/server/test/update.test.ts b/apps/server/test/update.test.ts new file mode 100644 index 0000000..025eaee --- /dev/null +++ b/apps/server/test/update.test.ts @@ -0,0 +1,168 @@ +import { afterEach, expect, it } from "vitest"; +import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { FastifyInstance } from "fastify"; +import { buildApp } from "../src/app"; +import type { UpdateOptions } from "../src/update"; + +const dirs: string[] = []; +const apps: FastifyInstance[] = []; +afterEach(async () => { + for (const app of apps.splice(0)) await app.close(); + for (const path of dirs.splice(0)) await rm(path, { recursive: true, force: true }); +}); + +type Reply = string | Error; +/** Fake for `git`/`systemctl`: answers by "file arg arg…" prefix and records every call. */ +function fakeRun(answers: Record) { + const calls: string[][] = []; + const run: UpdateOptions["run"] = async (file, args) => { + calls.push([file, ...args]); + const line = [file, ...args].join(" "); + const key = Object.keys(answers).sort((a, b) => b.length - a.length).find((k) => line.startsWith(k)); + if (key === undefined) throw new Error(`unexpected command: ${line}`); + const answer = answers[key]!; + if (answer instanceof Error) throw answer; + return answer; + }; + return { run, calls }; +} + +const show = (state: string, result = "success", start = "@1763300000", exit = "@1763300090") => + `ActiveState=${state}\nResult=${result}\nExecMainStartTimestamp=${start}\nExecMainExitTimestamp=${exit}\n`; +const git = (repo: string) => `git -C ${repo}`; + +async function setup(answers: Record, installed = true, withAuth = false) { + const root = await mkdtemp(join(tmpdir(), "update-")); + dirs.push(root); + const triggerUnit = join(root, "shellbook-update.path"); + if (installed) await writeFile(triggerUnit, "[Path]\n"); + const fake = fakeRun(answers); + const options: Partial = { + triggerUnit, + logFile: join(root, "update.log"), + repoDir: join(root, "repo"), + run: fake.run, + }; + const app = await buildApp({ config: { dataDir: join(root, "data") }, auth: withAuth ? undefined : false, update: options }); + apps.push(app); + return { app, root, repo: options.repoDir!, calls: fake.calls, requestFile: join(root, "data", "update-request"), logFile: options.logFile! }; +} + +it("reports the installed commit, the last run and the end of its log", async () => { + const { app, logFile, calls } = await setup({ + "git -C": "abc1234\n", + "systemctl show shellbook-update.service": show("inactive"), + }); + const lines = Array.from({ length: 400 }, (_, i) => `line ${i}`); + await writeFile(logFile, lines.join("\n") + "\n"); + const status = (await app.inject("/api/settings/update")).json(); + expect(status).toMatchObject({ + available: true, + state: "succeeded", + current: "abc1234", + startedAt: new Date(1763300000 * 1000).toISOString(), + finishedAt: new Date(1763300090 * 1000).toISOString(), + }); + // Only the end of a long log is returned. + expect(status.log.split("\n")[0]).toBe("line 200"); + expect(status.log).toContain("line 399"); + // Read-only queries only, with argv (no shell). + expect(calls.map((c) => c[0])).toEqual(expect.arrayContaining(["git", "systemctl"])); + expect(calls.find((c) => c[0] === "systemctl")).toEqual([ + "systemctl", "show", "shellbook-update.service", "--timestamp=unix", + "--property=ActiveState,Result,ExecMainStartTimestamp,ExecMainExitTimestamp", + ]); +}); + +it.each([ + [show("activating", "success", "@1763300000", ""), "running"], + [show("failed", "exit-code"), "failed"], + [show("inactive", "success", "", ""), "idle"], +])("maps unit state %#", async (output, state) => { + const { app } = await setup({ "git -C": "abc1234\n", "systemctl show": output }); + expect((await app.inject("/api/settings/update")).json().state).toBe(state); +}); + +it("says so when systemd cannot be asked, and is unavailable without the trigger unit", async () => { + const broken = await setup({ "git -C": new Error("no git"), "systemctl show": new Error("no systemd") }); + expect((await broken.app.inject("/api/settings/update")).json()).toMatchObject({ available: true, state: "unknown", current: null }); + const missing = await setup({ "git -C": "abc1234\n" }, false); + expect((await missing.app.inject("/api/settings/update")).json()).toMatchObject({ available: false, state: "idle", current: "abc1234" }); + // Never asks systemd or writes a request without the units. + expect(missing.calls.some((c) => c[0] === "systemctl")).toBe(false); + expect((await missing.app.inject({ method: "POST", url: "/api/settings/update", payload: {} })).statusCode).toBe(409); + await expect(stat(missing.requestFile)).rejects.toMatchObject({ code: "ENOENT" }); +}); + +it("starts an update only by writing the request file, and never twice at once", async () => { + const idle = await setup({ "git -C": "abc1234\n", "systemctl show": show("inactive") }); + const started = await idle.app.inject({ method: "POST", url: "/api/settings/update", payload: {} }); + expect(started.statusCode).toBe(202); + const { requestedAt } = started.json(); + expect(Date.parse(requestedAt)).not.toBeNaN(); + expect((await readFile(idle.requestFile, "utf8")).trim()).toBe(requestedAt); + // The server itself never starts units or runs the updater. + expect(idle.calls.filter((c) => c[0] === "systemctl").every((c) => c[1] === "show")).toBe(true); + const busy = await setup({ "git -C": "abc1234\n", "systemctl show": show("active", "success", "@1763300000", "") }); + expect((await busy.app.inject({ method: "POST", url: "/api/settings/update", payload: {} })).statusCode).toBe(409); +}); + +it("checks the tracked branch and lists the commits an update would bring", async () => { + const answers: Record = {}; + const target = await setup(answers); + Object.assign(answers, { + [`${git(target.repo)} rev-parse --short HEAD`]: "abc1234\n", + [`${git(target.repo)} symbolic-ref -q --short HEAD`]: "main\n", + [`${git(target.repo)} rev-parse --abbrev-ref --symbolic-full-name @{u}`]: "origin/main\n", + [`${git(target.repo)} fetch --quiet --no-tags -- origin main`]: "", + [`${git(target.repo)} rev-parse --short FETCH_HEAD`]: "def5678\n", + [`${git(target.repo)} log --format=%h%x09%s -n 50 HEAD..FETCH_HEAD`]: "def5678\tfeat(web): b\nbbb0000\tfix: a\ttab\n", + "systemctl show": show("inactive"), + }); + const result = await target.app.inject({ method: "POST", url: "/api/settings/update/check", payload: {} }); + expect(result.statusCode).toBe(200); + expect(result.json()).toEqual({ + current: "abc1234", + latest: "def5678", + pinned: false, + changes: [ + { commit: "def5678", subject: "feat(web): b" }, + { commit: "bbb0000", subject: "fix: a\ttab" }, + ], + }); +}); + +it("reports a pinned checkout without fetching, and a failed fetch as 502", async () => { + const pinnedAnswers: Record = {}; + const pinned = await setup(pinnedAnswers); + Object.assign(pinnedAnswers, { + [`${git(pinned.repo)} rev-parse --short HEAD`]: "abc1234\n", + [`${git(pinned.repo)} symbolic-ref -q --short HEAD`]: new Error("detached"), + "systemctl show": show("inactive"), + }); + const result = await pinned.app.inject({ method: "POST", url: "/api/settings/update/check", payload: {} }); + expect(result.json()).toEqual({ current: "abc1234", latest: null, pinned: true, changes: [] }); + expect(pinned.calls.some((c) => c.includes("fetch"))).toBe(false); + + const offlineAnswers: Record = {}; + const offline = await setup(offlineAnswers); + Object.assign(offlineAnswers, { + [`${git(offline.repo)} rev-parse --short HEAD`]: "abc1234\n", + [`${git(offline.repo)} symbolic-ref -q --short HEAD`]: "main\n", + [`${git(offline.repo)} rev-parse --abbrev-ref --symbolic-full-name @{u}`]: "origin/main\n", + [`${git(offline.repo)} fetch`]: new Error("Could not resolve host"), + "systemctl show": show("inactive"), + }); + const failed = await offline.app.inject({ method: "POST", url: "/api/settings/update/check", payload: {} }); + expect(failed.statusCode).toBe(502); + // The git error text stays in the server log, not in the response. + expect(failed.body).not.toContain("resolve host"); +}); + +it("requires a session", async () => { + const { app } = await setup({ "git -C": "abc1234\n", "systemctl show": show("inactive") }, true, true); + expect((await app.inject("/api/settings/update")).statusCode).toBe(401); + expect((await app.inject({ method: "POST", url: "/api/settings/update", payload: {} })).statusCode).toBe(401); +}); diff --git a/docs/spec.md b/docs/spec.md index 26d3b4e..fd8b3e1 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -276,6 +276,14 @@ checks and responses disable caching. service user home; credential contents are never read or returned. - Listens on `127.0.0.1` or LAN; intended behind Traefik + firewall (LAN/Tailscale only). - Terminal panel = shell as the service user: same trust level as the app itself. +- Self-update from Settings never gives the service privileges: POST + `/api/settings/update` only writes `/update-request`. A root-owned systemd + path unit starts the oneshot `shellbook-update.service`, which runs the fixed + root-owned `/usr/local/sbin/shellbook-update` (it fetches the installer from the + repository and never executes the service-writable checkout) and writes its output + to `/var/log/shellbook-update.log`. The server reads state only through + `systemctl show` and that log; "check for updates" runs `git fetch` into + `FETCH_HEAD` only. A request can only start that fixed updater, nothing else. - No secrets in notebooks, audit log or artifacts metadata. ## 8. Architecture diff --git a/packages/core/src/protocol.ts b/packages/core/src/protocol.ts index 013bb65..0aaf715 100644 --- a/packages/core/src/protocol.ts +++ b/packages/core/src/protocol.ts @@ -145,6 +145,33 @@ export interface SessionSettingsResponse { lifetimeSeconds: number } export interface ClaudeStatusResponse { available: boolean; version: string | null; loginAppearsPresent: boolean } export interface SystemInfoResponse { version: string; workspacePath: string; dataDirPath: string; nodeVersion: string } +// Self-update from the UI (#15). The service stays unprivileged: POST only touches a +// request file that a root-owned systemd path unit watches (deploy/install.sh). +// GET /api/settings/update +export type UpdateState = "idle" | "running" | "succeeded" | "failed" | "unknown"; +export interface UpdateStatusResponse { + /** The trigger units are installed; otherwise updates need `shellbook-update` as root. */ + available: boolean; + state: UpdateState; + /** Installed commit (short hash) when the app runs from a git checkout. */ + current: string | null; + startedAt: string | null; + finishedAt: string | null; + /** End of the last update's output. */ + log: string; +} +// POST /api/settings/update/check: fetches the tracked branch, changes nothing else. +export interface UpdateCheckResponse { + current: string | null; + latest: string | null; + /** The checkout is pinned to a ref (SHELLBOOK_REF) and is never pulled. */ + pinned: boolean; + /** Commits the update would bring, newest first (at most 50). */ + changes: { commit: string; subject: string }[]; +} +// POST /api/settings/update: 202, or 409 when unavailable or already running. +export interface UpdateStartResponse { requestedAt: string } + // ---- notebook management (#9) ------------------------------------------------ // Paths are relative to notebooks/. Mutations return 409 on stale versions or occupied targets. // POST /api/notebooks