Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(updates): fail-safe server updates driven by a signed manifest
Salman Qureshi1fbb48352bcf
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsindex 571bd00b..cb0e80ed 100644--- a/src/bots/bot-manager.ts+++ b/src/bots/bot-manager.ts@@ -1928,6 +1928,13 @@ export class BotManager {}/** Fire a bot's configured routine immediately, or send a bare wake turn. */+ /** How many bot turns are running right now (the updater waits for them). */+ runningJobs(): number {+ let n = 0;+ for (const set of this.running.values()) n += set.size;+ return n;+ }+runNow(botId: string, routineName?: string): { accepted: boolean; jobId?: string; reasonCode?: string } {const manifest = this.store.get(botId);if (!manifest) return { accepted: false, reasonCode: 'target_unknown' };diff --git a/src/channels/cli.ts b/src/channels/cli.tsindex 1c945449..90b8a7c5 100644--- a/src/channels/cli.ts+++ b/src/channels/cli.ts@@ -2426,16 +2426,20 @@ export class CLIChannel extends BaseChannel {private async announceVersionNotices(version: string): Promise<void> {if (process.env.VITEST || process.env.MERCURY_NO_UPDATE_CHECK === '1') return;try {- const { shouldShowWhatsNewHint, markWhatsNewHintShown, maybeCheckForUpdate } = await this.updateNoticeApi();+ const { shouldShowWhatsNewHint, markWhatsNewHintShown, getIgnoredUpdateVersion, shownMessageIds, rememberNotices } = await this.updateNoticeApi();if (shouldShowWhatsNewHint(version)) {markWhatsNewHintShown(version);this.sendSystemNotice(`☿ Mercury v${version} is here. Type \`/whatsnew\` to see what's new.`);}- const latest = await maybeCheckForUpdate(version);- if (latest) {- this.setUpdateAvailable(latest);- this.sendSystemNotice(`⬆ Update available: v${version} → v${latest}. Run \`mercury upgrade\` in your terminal when you're ready — or ignore this version with \`/update ignore\`.`);- }+ // The signed update manifest decides "required" and carries messages;+ // without it, the plain version look-up still offers updates.+ const { serverUpdateStatus } = await import('../updates/status.js');+ const { startupNotices } = await import('../updates/notices.js');+ const status = await serverUpdateStatus({ current: version });+ const out = startupNotices(status, getIgnoredUpdateVersion(), shownMessageIds());+ rememberNotices(out.shown, status.latest?.version);+ if (out.badge) this.setUpdateAvailable(out.badge);+ for (const n of out.notices) this.sendSystemNotice(n);} catch (err) {logger.debug({ err }, 'announceVersionNotices failed (non-fatal)');}diff --git a/src/cli/latest-version.test.ts b/src/cli/latest-version.test.tsindex 2d14da70..ac7c4acf 100644--- a/src/cli/latest-version.test.ts+++ b/src/cli/latest-version.test.ts@@ -17,14 +17,21 @@ describe('latest version resolution (mercury upgrade is a no-op when current)',expect(parseDevVersionFromReleaseName('Mercury Dev')).toBeNull();});- it('the launcher checks the channel version before stopping the daemon or running an installer', () => {- const index = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'index.ts'), 'utf8').replace(/\r\n/g, '\n');- const cmd = index.slice(index.indexOf(".command('upgrade')"), index.indexOf(".command('upgrade')") + 6000);- const check = cmd.indexOf('fetchLatestVersion(');- const stop = cmd.indexOf('await stopDaemon()');- expect(check).toBeGreaterThan(0);- expect(stop).toBeGreaterThan(check);- expect(cmd).toContain("Already on the latest");+ it('the launcher checks the newest version before stopping anything; only --force reinstalls the same one', () => {+ const here = dirname(fileURLToPath(import.meta.url));+ const index = readFileSync(join(here, '..', 'index.ts'), 'utf8').replace(/\r\n/g, '\n');+ const cmd = index.slice(index.indexOf(".command('upgrade')"), index.indexOf(".command('upgrade')") + 1200);expect(cmd).toContain("'--force'");+ expect(cmd).toContain('runUpgrade(');+ const cli = readFileSync(join(here, 'upgrade-cli.ts'), 'utf8').replace(/\r\n/g, '\n');+ const run = cli.slice(cli.indexOf('export async function runUpgrade('));+ const check = run.indexOf('serverUpdateStatus(');+ const reinstall = run.indexOf('legacyReinstall()');+ const update = run.indexOf('updateViaRunning(');+ expect(check).toBeGreaterThan(0);+ expect(reinstall).toBeGreaterThan(check);+ expect(update).toBeGreaterThan(check);+ expect(run).toContain('Already on the newest');+ expect(run.slice(0, reinstall)).toContain('if (opts.force)');});});diff --git a/src/cli/update-notice.ts b/src/cli/update-notice.tsindex 6a7273fb..f1abb674 100644--- a/src/cli/update-notice.ts+++ b/src/cli/update-notice.ts@@ -28,6 +28,8 @@ interface UpdateState {checkedAt?: number;/** Latest version observed by the last successful check. */latestSeen?: string;+ /** Manifest messages already shown in the terminal (by id). */+ shownMessages?: string[];}const STATE_PATH = () => join(getMercuryHome(), 'update-state.json');@@ -162,4 +164,16 @@ export function latestSeenUpdate(currentVersion: string): string | null {const state = loadUpdateState();if (state.latestSeen && isNewerVersion(state.latestSeen, currentVersion)) return state.latestSeen;return null;-}\ No newline at end of file+}+/** Manifest message ids the terminal already showed. */+export function shownMessageIds(): Set<string> {+ return new Set(loadUpdateState().shownMessages ?? []);+}++/** Remember shown messages, and the newest version seen (for `/update ignore`). */+export function rememberNotices(ids: string[], latest?: string | null): void {+ const state = loadUpdateState();+ if (ids.length) state.shownMessages = [...new Set([...(state.shownMessages ?? []), ...ids])].slice(-200);+ if (latest) state.latestSeen = latest;+ saveUpdateState(state);+}diff --git a/src/cli/upgrade-cli.ts b/src/cli/upgrade-cli.tsnew file mode 100644index 00000000..cf2556cc--- /dev/null+++ b/src/cli/upgrade-cli.ts@@ -0,0 +1,211 @@+import type { Command } from 'commander';+import chalk from 'chalk';+import { execFileSync } from 'node:child_process';+import { getWebPort, readAttachToken } from '../web/auth.js';+import { detectInstall, type InstallInfo } from '../updates/install-kind.js';+import { serverUpdateStatus, targetVersion, type ServerUpdateStatus } from '../updates/status.js';+import { HEALTH_TIMEOUT_MS, readJob, realWorkerSteps, runUpdateWorker, startServerUpdate, TERMINAL, type UpdateJob, type WorkerSteps } from '../updates/server-updater.js';++/**+ * `mercury upgrade` and `mercury update`: the same fail-safe update the+ * apps start (docs/updates.md §2), in a terminal, with a progress bar.+ *+ * mercury upgrade update to the newest version (waits for running work)+ * mercury upgrade --now don't wait for running work+ * mercury upgrade --check just say what's new+ * mercury upgrade --force reinstall even when already on the newest version+ * mercury update [check] what's new / is an update required+ *+ * With Mercury running, the running Mercury does it (so it can wait for+ * running work and come back as the new version). With it stopped, this+ * process does every step itself and leaves it stopped.+ */++const base = () => `http://127.0.0.1:${getWebPort()}`;++async function api<T>(path: string, init: RequestInit = {}): Promise<{ status: number; body: T } | null> {+ const token = readAttachToken();+ if (!token) return null;+ try {+ const res = await fetch(`${base()}${path}`, { ...init, headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, signal: AbortSignal.timeout(10_000) });+ return { status: res.status, body: await res.json().catch(() => ({})) as T };+ } catch {+ return null;+ }+}++function bar(percent: number | null, width = 24): string {+ if (percent === null) return chalk.dim('·'.repeat(width));+ const filled = Math.round((Math.max(0, Math.min(100, percent)) / 100) * width);+ return chalk.cyan('█'.repeat(filled)) + chalk.dim('░'.repeat(width - filled));+}++function mb(n?: number): string { return n ? `${(n / 1024 / 1024).toFixed(1)} MB` : ''; }++let lastLine = '';+function render(job: UpdateJob): void {+ const size = job.state === 'downloading' && job.bytes ? chalk.dim(` ${mb(job.bytes)}${job.total ? ` / ${mb(job.total)}` : ''}`) : '';+ const line = ` ${bar(job.percent)} ${String(job.percent ?? 0).padStart(3)}% ${job.message}${size}`;+ if (line === lastLine) return;+ lastLine = line;+ if (process.stdout.isTTY) process.stdout.write(`\r\x1b[2K${line}`);+ else console.log(line);+}++function endLine(): void { if (process.stdout.isTTY && lastLine) process.stdout.write('\n'); lastLine = ''; }++function printOutcome(job: UpdateJob): void {+ endLine();+ const colour = job.state === 'done' ? chalk.green(' ✓ ') : job.state === 'rolled-back' ? chalk.yellow(' ↺ ') : job.state === 'cancelled' ? chalk.dim(' · ') : chalk.red(' ✗ ');+ console.log(colour + job.message);+ if (job.state !== 'done' && job.state !== 'cancelled' && job.error && !job.message.includes(job.error)) console.log(chalk.dim(` ${job.error}`));+ if (job.state === 'failed' || job.state === 'rolled-back') console.log(chalk.dim(' Details: ~/.mercury/updates/job.json and worker.log'));+ console.log('');+}++/** "What's new" and whether an update is due. */+export function printStatus(s: ServerUpdateStatus): void {+ console.log(chalk.cyan(` Mercury ${chalk.white(`v${s.current}`)}`) + chalk.dim(` · ${s.install}${s.channel === 'dev' ? ' · dev channel' : ''}`));+ if (s.required) {+ console.log(chalk.red(` ⚠ Update required${s.required.severity === 'security' ? ' (security)' : ''}: ${s.required.reason}`));+ console.log(chalk.red(` Versions below ${s.required.version} must update. Run: mercury upgrade`));+ }+ if (!s.latest) console.log(chalk.dim(' Couldn\'t check for updates (offline?).'));+ else if (!s.updateAvailable) console.log(chalk.green(` ✓ This is the newest ${s.channel === 'dev' ? 'dev build' : 'version'}.`));+ else {+ console.log(chalk.yellow(` ⬆ Mercury ${s.latest.version} is available${s.latest.date ? chalk.dim(` (${s.latest.date})`) : ''}.`));+ if (s.latest.downloadable === false) console.log(chalk.dim(' It isn\'t downloadable yet; try again later.'));+ if (s.blocked) console.log(chalk.dim(` It failed to install ${s.blocked.failures} times (${s.blocked.lastError}). \`mercury upgrade\` tries again.`));+ if (s.latest.notes) {+ console.log('');+ for (const l of s.latest.notes.split('\n').slice(0, 30)) console.log(` ${l}`);+ if (s.latest.notes.split('\n').length > 30) console.log(chalk.dim(' …'));+ }+ if (s.latest.notesUrl) console.log(chalk.dim(` ${s.latest.notesUrl}`));+ if (s.canSelfUpdate) console.log(`\n Update with: ${chalk.white('mercury upgrade')}`);+ else console.log(chalk.dim(`\n ${s.cannotReason}`));+ }+ for (const m of s.messages) console.log(`\n ${m.level === 'critical' ? chalk.red('!') : m.level === 'warning' ? chalk.yellow('!') : chalk.cyan('i')} ${chalk.bold(m.title)}${m.body ? `\n ${m.body.split('\n').join('\n ')}` : ''}${m.link ? chalk.dim(`\n ${m.link.url}`) : ''}`);+ console.log('');+}++/** Through the running Mercury. Null when it isn't running or predates the update API. */+async function updateViaRunning(to: string, now: boolean): Promise<UpdateJob | null> {+ const health = await api<{ features?: string[] }>('/api/health');+ if (!health || !health.body.features?.includes('updates')) return null;+ const started = await api<{ job?: UpdateJob; error?: string }>('/api/updates/server', { method: 'POST', body: JSON.stringify({ version: to, now }) });+ if (!started) return null;+ if (started.status !== 202 || !started.body.job) {+ console.log(chalk.red(` ✗ ${started.body.error ?? `The update could not start (HTTP ${started.status}).`}`));+ if (started.body.job) console.log(chalk.dim(` ${started.body.job.message}`));+ console.log('');+ return started.body.job ?? ({ state: 'failed' } as UpdateJob);+ }+ let job = started.body.job;+ const id = job.id;+ render(job);+ // Mercury is down for a few seconds in between: the job file says how it's going.+ const until = Date.now() + 20 * 60_000;+ while (Date.now() < until) {+ await new Promise((r) => setTimeout(r, 600));+ const disk = readJob();+ if (disk && disk.id === id) job = disk;+ render(job);+ if (TERMINAL.has(job.state)) break;+ }+ printOutcome(job);+ return job;+}++/** Every step in this process. Mercury wasn't running, so it isn't started; the new version is checked with `--version`. */+async function updateHere(to: string, install: InstallInfo): Promise<UpdateJob> {+ const { getDaemonStatus, getForegroundRuntimeStatus } = await import('./daemon.js');+ const wasRunning = getDaemonStatus().running || getForegroundRuntimeStatus().running;+ const steps: WorkerSteps = wasRunning || process.env.MERCURY_UPDATE_DRY_RUN === '1'+ ? realWorkerSteps()+ : { ...realWorkerSteps(), start: async () => {}, health: async (version) => installedVersion(install) === version };+ const started = startServerUpdate({+ current: currentVersion,+ to, install, now: true, manual: true,+ steps: { handOver: async (job) => { void runUpdateWorker(job.id, steps, wasRunning ? HEALTH_TIMEOUT_MS : 30_000); return process.pid; } },+ });+ if (!started.ok) {+ console.log(chalk.red(` ✗ ${started.error}`));+ console.log('');+ return started.job ?? ({ state: 'failed' } as UpdateJob);+ }+ const id = started.job.id;+ let job = started.job;+ await started.done;+ for (;;) {+ const disk = readJob();+ if (disk && disk.id === id) job = disk;+ render(job);+ if (TERMINAL.has(job.state)) break;+ await new Promise((r) => setTimeout(r, 300));+ }+ printOutcome(job);+ return job;+}++let currentVersion = '';++function installedVersion(install: InstallInfo): string {+ try {+ const out = install.kind === 'binary' && install.binaryPath+ ? execFileSync(install.binaryPath, ['--version'], { encoding: 'utf-8', timeout: 30_000 })+ : execFileSync(process.execPath, [process.argv[1], '--version'], { encoding: 'utf-8', timeout: 30_000 });+ return out.trim().split(/\s+/).pop() ?? '';+ } catch {+ return '';+ }+}++export interface UpgradeOptions { force?: boolean; check?: boolean; now?: boolean }++export async function runUpgrade(version: string, opts: UpgradeOptions, legacyReinstall: () => Promise<void>): Promise<void> {+ currentVersion = version;+ console.log('');+ const status = await serverUpdateStatus({ current: version, force: true });+ if (opts.check) { printStatus(status); return; }++ console.log(chalk.cyan(` Mercury ${chalk.white(`v${version}`)}`));+ const install = detectInstall(version);+ if (!install.canSelfUpdate) {+ console.log(chalk.yellow(` ${install.cannotReason}`));+ console.log('');+ return;+ }+ const to = targetVersion(status);+ if (!to) {+ if (opts.force) { await legacyReinstall(); return; }+ if (!status.latest) console.log(chalk.yellow(' Couldn\'t reach the update server. Try again later, or use --force to reinstall.'));+ else console.log(chalk.green(` ✓ Already on the newest ${status.channel === 'dev' ? 'dev build' : 'version'} (v${version}). Nothing to do.`));+ console.log(chalk.dim(' Use mercury upgrade --force to reinstall anyway.'));+ console.log('');+ return;+ }+ console.log(chalk.dim(` Updating to v${to}${status.channel === 'dev' ? ' (dev channel)' : ''}. Mercury goes back on its own if the new version doesn't start.`));+ console.log('');+ const job = (await updateViaRunning(to, !!opts.now)) ?? (await updateHere(to, install));+ if (job.state === 'done' && status.latest?.notesUrl) console.log(chalk.dim(` What's new: ${status.latest.notesUrl}\n`));+ if (job.state !== 'done' && job.state !== 'cancelled') process.exitCode = 1;+}++export function registerUpdateCli(program: Command, version: string): void {+ program+ .command('update [what]')+ .description('Is there a newer Mercury, and what\'s in it (`mercury update check` asks again now)')+ .action(async (what?: string) => {+ console.log('');+ printStatus(await serverUpdateStatus({ current: version, force: what === 'check' }));+ });++ // The detached half of an update: stop, install, start, check, or go back.+ program+ .command('__update-worker <jobId>', { hidden: true })+ .action(async (jobId: string) => {+ const job = await runUpdateWorker(jobId);+ process.exit(job && job.state === 'done' ? 0 : 1);+ });+}diff --git a/src/core/agent.ts b/src/core/agent.tsindex c8d449bc..9c802c2b 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -1201,6 +1201,11 @@ export class Agent {}/** Is a turn for this session running, or waiting in the queue? */+ /** Messages waiting behind the running one (the updater waits for them). */+ get queuedCount(): number {+ return this.messageQueue.length;+ }+isBusyWith(sessionId: string): boolean {const of = (m: ChannelMessage | null | undefined) => m?.sessionId ?? (typeof m?.metadata?.sessionId === 'string' ? m.metadata.sessionId : undefined);if (this.processing && of(this.currentMessage) === sessionId) return true;diff --git a/src/core/commands/chat-command.ts b/src/core/commands/chat-command.tsindex 67b67b94..d77744a1 100644--- a/src/core/commands/chat-command.ts+++ b/src/core/commands/chat-command.ts@@ -163,7 +163,12 @@ export async function handleChatCommand(agent: Agent, content: string, channelTyconst runningVersion = channelType === 'cli' && channel instanceof CLIChannel? (channel.getTuiState().version || 'dev'): 'dev';- await channel.send(whatsNewText(runningVersion), channelId).catch((e) => logger.warn({ e }, 'channel send failed'));+ // The signed update manifest's notes for this version, when it has them.+ const { readManifestCache, latestFor } = await import('../../updates/manifest.js');+ const cached = readManifestCache().manifest;+ const release = [latestFor(cached, 'server', 'stable'), latestFor(cached, 'server', 'dev')].find((r) => r && r.version === runningVersion.replace(/^v/, '') && r.notes);+ const text = release?.notes ? `${release.notes}${release.notesUrl ? `\n\n${release.notesUrl}` : ''}` : whatsNewText(runningVersion);+ await channel.send(text, channelId).catch((e) => logger.warn({ e }, 'channel send failed'));return true;}@@ -174,6 +179,12 @@ export async function handleChatCommand(agent: Agent, content: string, channelTyconst runningVersion = channelType === 'cli' && channel instanceof CLIChannel? (channel.getTuiState().version || 'dev'): 'dev';+ const { readManifestCache, requiredFor } = await import('../../updates/manifest.js');+ const required = requiredFor(readManifestCache().manifest, 'server', runningVersion);+ if (required) {+ await channel.send(`This update is required and can't be ignored: ${required.reason} Run \`mercury upgrade\` in your terminal; it goes back on its own if anything fails.`, channelId);+ return true;+ }const target = latestSeenUpdate(runningVersion);if (!target) {await channel.send('Nothing to ignore — no update was offered for this version.', channelId);diff --git a/src/index.ts b/src/index.tsindex 0b15826f..639aef08 100644--- a/src/index.ts+++ b/src/index.ts@@ -61,6 +61,7 @@ import { registerPluginsCli } from './cli/plugins-cli.js';import { PersonVerifier, personCheckPrompt, parsePersonCheck } from './memory/person-verifier.js';import { setPersonVerifier } from './web/api/brain.js';import { registerDevicesCli } from './cli/devices-cli.js';+import { registerUpdateCli, runUpgrade } from './cli/upgrade-cli.js';import { registerServerCli } from './cli/server-cli.js';import { SECOND_BRAIN_UNAVAILABLE_MESSAGE } from './memory/second-brain-db.js';import { isSqliteAvailable } from './utils/sqlite-driver.js';@@ -3559,6 +3560,19 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {off: (id) => { if (agent.researchMode.armedForSession(id)) agent.researchMode.setOff(); webChannel.sendResearchArmed(false, id); },});setWebBudgetControls({ config: () => config, tokens: () => tokenBudget, saver: () => agent.saverMode });+ // Updates wait for running work: a reply, queued messages, bot turns.+ {+ const { setUpdateBusyProbe, reconcileUpdateJob } = await import('./updates/server-updater.js');+ const { versionString } = await import('./web/api/status.js');+ setUpdateBusyProbe(() => {+ if (agent.processing) return 'a reply';+ if (agent.queuedCount > 0) return agent.queuedCount === 1 ? 'a queued message' : `${agent.queuedCount} queued messages`;+ const bots = botManager?.runningJobs() ?? 0;+ if (bots > 0) return bots === 1 ? 'a bot run' : `${bots} bot runs`;+ return null;+ });+ try { reconcileUpdateJob(versionString()); } catch (err) { logger.debug({ err }, 'updates: reconcile failed'); }+ }// Titles made before they were checked: fix them once, quietly, after start-up.if (!daemonOwnsRuntime) {const titleRepair = setTimeout(() => { void agent.repairSessionTitles().catch(() => {}); }, 20_000);@@ -4257,6 +4271,13 @@ programconst line = ` Security: ${summary}${summary === 'All good' ? '' : ' — run `mercury doctor --security`'}`;console.log(findings.some((f) => f.level === 'risk') ? chalk.yellow(line) : chalk.dim(line));}+ try {+ // One line about updates: current, newest, required, blocked.+ const { serverUpdateStatus } = await import('./updates/status.js');+ const { updatesLine } = await import('./updates/notices.js');+ const u = updatesLine(await serverUpdateStatus({ current: pkgVersion }));+ console.log(u.level === 'risk' ? chalk.red(u.text) : u.level === 'note' ? chalk.yellow(u.text) : chalk.dim(u.text));+ } catch { /* offline: say nothing */ }if (opts.plugins) {const { runPluginDoctor } = await import('./cli/plugins-cli.js');await runPluginDoctor();@@ -5118,28 +5139,20 @@ serviceCmdregisterDevicesCli(program);registerServerCli(program);- program+registerUpdateCli(program, pkgVersion);++program.command('upgrade')- .description('Upgrade Mercury to the latest version')+ .description('Upgrade Mercury to the latest version (goes back on its own if the new version fails)').option('--force', 'Reinstall even when already on the latest version')- .action(async (opts: { force?: boolean }) => {- console.log('');- console.log(chalk.cyan(` Mercury ${chalk.white(`v${pkgVersion}`)}`));- // Already current? Say so and touch nothing — not the daemon, not the- // binary. (This used to stop the daemon and re-run the installer- // unconditionally: "upgrade" on the latest build was a restart.)- if (!opts.force) {- const { fetchLatestVersion } = await import('./cli/latest-version.js');- const channel = isDevBuild(pkgVersion) ? 'dev' : 'stable';- const latest = await fetchLatestVersion(channel);- if (latest && latest === pkgVersion) {- console.log(chalk.green(` ✓ Already on the latest ${channel === 'dev' ? 'dev build' : 'version'} (v${pkgVersion}). Nothing to do.`));- console.log(chalk.dim(' Use mercury upgrade --force to reinstall anyway.'));- console.log('');- return;- }- if (latest) console.log(chalk.dim(` Latest on the ${channel} channel: v${latest}`));- }+ .option('--check', 'Only show whether a newer version exists and what is in it')+ .option('--now', "Don't wait for running work to finish")+ .action(async (opts: { force?: boolean; check?: boolean; now?: boolean }) => {+ await runUpgrade(pkgVersion, opts, legacyReinstall);+ });++/** `--force` on the newest version: re-run the installer (binary) or npm (npm install), as before. */+async function legacyReinstall(): Promise<void> {// A dev binary upgrades itself in place on the same channel (re-running// the dev installer below); npm builds take the npm stable track.if (isDevBuild(pkgVersion)) {@@ -5269,7 +5282,7 @@ registerServerCli(program);}console.log('');- });+ }program.command('code')diff --git a/src/security/audit.ts b/src/security/audit.tsindex f860d766..384fd9d5 100644--- a/src/security/audit.ts+++ b/src/security/audit.ts@@ -13,7 +13,8 @@ export type AuditKind =| 'pair.requested' | 'pair.approved' | 'pair.denied' | 'pair.expired' | 'pair.local'| 'device.revoked' | 'device.expired' | 'device.new-location' | 'device.blocked'| 'action.requested' | 'action.allowed' | 'action.denied'- | 'remote.changed' | 'login.failed' | 'login.locked' | 'password.changed';+ | 'remote.changed' | 'login.failed' | 'login.locked' | 'password.changed'+ | 'update.started';export interface AuditEntry {at: string;diff --git a/src/updates/download.ts b/src/updates/download.tsnew file mode 100644index 00000000..0a698b68--- /dev/null+++ b/src/updates/download.ts@@ -0,0 +1,238 @@+import { createHash } from 'node:crypto';+import { createReadStream, existsSync, mkdirSync, openSync, closeSync, writeSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { getMercuryHome } from '../utils/config.js';++/**+ * Downloads that survive a bad connection: bytes go to `<file>.part` as they+ * arrive, and a retry (or the next attempt, even after a restart) asks for+ * the rest with an HTTP Range request. `If-Range` makes the server send the+ * whole file again if it changed in between, so two versions are never+ * stitched together. The finished file must match its SHA-256 from the+ * release's checksums.txt, or it's thrown away.+ */++export const REPO = 'cosmicstack-labs/mercury-agent';+const MAX_BYTES = 512 * 1024 * 1024;+const RETRIES = 5;+const STALL_MS = 30_000;++/** The file isn't there (404/410): the release isn't published yet, or never was. Not a failure of the update itself. */+export class NotAvailableError extends Error {+ readonly notAvailable = true;+}++export interface DownloadProgress { bytes: number; total: number | null }++export interface DownloadOptions {+ expectedSha256?: string;+ maxBytes?: number;+ retries?: number;+ stallMs?: number;+ signal?: AbortSignal;+ fetchImpl?: typeof fetch;+ onProgress?: (p: DownloadProgress) => void;+ /** Waits between retries (tests make it instant). */+ backoffMs?: (attempt: number) => number;+}++interface PartMeta { url: string; validator?: string; total?: number | null }++const sleep = (ms: number, signal?: AbortSignal) => new Promise<void>((resolve, reject) => {+ const t = setTimeout(resolve, ms);+ signal?.addEventListener('abort', () => { clearTimeout(t); reject(signal.reason ?? new Error('Cancelled')); }, { once: true });+});++export function sha256File(path: string): Promise<string> {+ return new Promise((resolve, reject) => {+ const h = createHash('sha256');+ createReadStream(path).on('data', (d) => h.update(d)).on('end', () => resolve(h.digest('hex'))).on('error', reject);+ });+}++function readMeta(path: string): PartMeta | null {+ try { return JSON.parse(readFileSync(path, 'utf-8')) as PartMeta; } catch { return null; }+}++class Permanent extends Error {}++/**+ * Download `url` to `dest`, resuming a `.part` left by an earlier try.+ * Returns the file's SHA-256. Throws NotAvailableError on 404/410.+ */+export async function downloadResumable(url: string, dest: string, opts: DownloadOptions = {}): Promise<string> {+ const fetchImpl = opts.fetchImpl ?? fetch;+ const maxBytes = opts.maxBytes ?? MAX_BYTES;+ const part = `${dest}.part`;+ const metaPath = `${dest}.part.json`;+ const backoff = opts.backoffMs ?? ((n: number) => Math.min(16_000, 1000 * 2 ** n));++ // Already here from an earlier attempt, and still the right file.+ if (existsSync(dest) && opts.expectedSha256) {+ const have = await sha256File(dest);+ if (have === opts.expectedSha256) {+ const size = statSync(dest).size;+ opts.onProgress?.({ bytes: size, total: size });+ return have;+ }+ rmSync(dest, { force: true });+ }++ let lastError: unknown = null;+ for (let attempt = 0; attempt <= (opts.retries ?? RETRIES); attempt++) {+ if (opts.signal?.aborted) throw opts.signal.reason ?? new Error('Cancelled');+ if (attempt > 0) await sleep(backoff(attempt - 1), opts.signal);+ try {+ await once(url, part, metaPath, fetchImpl, maxBytes, opts);+ const sum = await sha256File(part);+ if (opts.expectedSha256 && sum !== opts.expectedSha256) {+ // Corrupt or changed: start over, and count it as a try.+ rmSync(part, { force: true }); rmSync(metaPath, { force: true });+ throw new Error('The download did not match its checksum.');+ }+ renameSync(part, dest);+ rmSync(metaPath, { force: true });+ return sum;+ } catch (err) {+ if (err instanceof NotAvailableError || err instanceof Permanent || opts.signal?.aborted) throw err;+ lastError = err;+ }+ }+ throw lastError instanceof Error ? lastError : new Error('The download failed.');+}++async function once(url: string, part: string, metaPath: string, fetchImpl: typeof fetch, maxBytes: number, opts: DownloadOptions): Promise<void> {+ let meta = readMeta(metaPath);+ let have = existsSync(part) ? statSync(part).size : 0;+ if (have > 0 && (!meta || meta.url !== url)) { rmSync(part, { force: true }); have = 0; meta = null; }++ const headers: Record<string, string> = { 'user-agent': 'mercury-updater', accept: 'application/octet-stream' };+ if (have > 0) {+ headers.range = `bytes=${have}-`;+ if (meta?.validator) headers['if-range'] = meta.validator;+ }++ const stall = new AbortController();+ let stallTimer = setTimeout(() => stall.abort(new Error('The download stalled.')), opts.stallMs ?? STALL_MS);+ const onAbort = () => stall.abort(opts.signal?.reason ?? new Error('Cancelled'));+ opts.signal?.addEventListener('abort', onAbort, { once: true });+ try {+ const res = await fetchImpl(url, { headers, redirect: 'follow', signal: stall.signal });+ if (res.status === 404 || res.status === 410) throw new NotAvailableError(`Not found: ${url}`);+ if (res.status === 416 && meta?.total && have === meta.total) return; // already complete+ if (res.status === 416) { rmSync(part, { force: true }); throw new Error('The server refused to resume; starting over.'); }+ if (res.status === 401 || res.status === 403) throw new Permanent(`The server refused the download (${res.status}).`);+ if (!res.ok || !res.body) throw new Error(`The download failed (HTTP ${res.status}).`);++ const resumed = res.status === 206;+ if (!resumed) have = 0;+ const length = Number(res.headers.get('content-length') ?? '') || null;+ const total = length !== null ? length + (resumed ? have : 0) : meta?.total ?? null;+ if (total !== null && total > maxBytes) throw new Permanent('The download is larger than any Mercury release; refused.');+ const validator = res.headers.get('etag') ?? res.headers.get('last-modified') ?? undefined;+ if (!resumed || !meta) {+ mkdirSync(join(part, '..'), { recursive: true });+ writeFileSync(metaPath, JSON.stringify({ url, validator, total } satisfies PartMeta));+ }++ const fd = openSync(part, resumed ? 'a' : 'w');+ let bytes = have;+ opts.onProgress?.({ bytes, total });+ try {+ const reader = res.body.getReader();+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ clearTimeout(stallTimer);+ stallTimer = setTimeout(() => stall.abort(new Error('The download stalled.')), opts.stallMs ?? STALL_MS);+ bytes += value.byteLength;+ if (bytes > maxBytes) throw new Permanent('The download is larger than any Mercury release; refused.');+ writeSync(fd, value);+ opts.onProgress?.({ bytes, total });+ }+ } finally {+ closeSync(fd);+ }+ if (total !== null && bytes < total) throw new Error('The download ended early.');+ } finally {+ clearTimeout(stallTimer);+ opts.signal?.removeEventListener('abort', onAbort);+ }+}++// ─── Release assets ──────────────────────────────────────────────────────────++/** The release asset for this computer (same names as scripts/install.sh and the desktop installer). */+export function assetName(platform = process.platform, arch = process.arch): string | null {+ if (process.env.MERCURY_ASSET) return process.env.MERCURY_ASSET;+ if (platform === 'darwin') return arch === 'arm64' ? 'mercury-macos-arm64' : 'mercury-macos-x64';+ if (platform === 'linux') {+ if (arch === 'arm64') return 'mercury-linux-arm64';+ if (arch !== 'x64') return null;+ // Bun's x64 build needs AVX2; older CPUs take the baseline build.+ try { if (!/\bavx2\b/.test(readFileSync('/proc/cpuinfo', 'utf-8'))) return 'mercury-linux-x64-baseline'; } catch { /* assume modern */ }+ return 'mercury-linux-x64';+ }+ if (platform === 'win32' && arch === 'x64') return 'mercury-win-x64.exe';+ return null;+}++export function releaseBase(version: string, channel: 'stable' | 'dev'): string {+ const base = process.env.MERCURY_DOWNLOAD_BASE || `https://github.com/${REPO}/releases/download`;+ return channel === 'dev' ? `${base}/mercury-dev-latest` : `${base}/v${version.replace(/^v/, '')}`;+}++/** `sha256 name` lines → name → sha. */+export function parseChecksums(text: string): Map<string, string> {+ const out = new Map<string, string>();+ for (const line of text.split(/\r?\n/)) {+ const m = /^([0-9a-f]{64})\s+\*?(\S+)\s*$/i.exec(line.trim());+ if (m) out.set(m[2], m[1].toLowerCase());+ }+ return out;+}++export function downloadsDir(version: string): string {+ return join(getMercuryHome(), 'updates', 'downloads', version.replace(/[^\w.\-+]/g, '_'));+}++export interface ReleaseFiles { dir: string; binary: string; web: string; asset: string }++/**+ * Fetch a release's binary and web dashboard, both checked against+ * checksums.txt. Progress is over both files together.+ */+export async function downloadRelease(version: string, channel: 'stable' | 'dev', opts: Omit<DownloadOptions, 'expectedSha256' | 'onProgress'> & { onProgress?: (p: DownloadProgress) => void } = {}): Promise<ReleaseFiles> {+ const asset = assetName();+ if (!asset) throw new Permanent('Mercury has no prebuilt build for this computer.');+ const base = releaseBase(version, channel);+ const fetchImpl = opts.fetchImpl ?? fetch;++ let sums: Map<string, string> | null = null;+ for (let i = 0; i < 3 && !sums; i++) {+ try {+ const res = await fetchImpl(`${base}/checksums.txt`, { redirect: 'follow', signal: opts.signal, headers: { 'user-agent': 'mercury-updater' } });+ if (res.status === 404 || res.status === 410) throw new NotAvailableError(`${version} has no published files yet.`);+ if (!res.ok) throw new Error(`checksums.txt: HTTP ${res.status}`);+ sums = parseChecksums(await res.text());+ } catch (err) {+ if (err instanceof NotAvailableError || opts.signal?.aborted || i === 2) throw err;+ await sleep((opts.backoffMs ?? ((n) => 1000 * 2 ** n))(i), opts.signal);+ }+ }+ const binSum = sums!.get(asset);+ const webSum = sums!.get('web.tar.gz');+ if (!binSum || !webSum) throw new NotAvailableError(`${version} has no ${binSum ? 'web dashboard' : asset} build yet.`);++ const dir = downloadsDir(version);+ mkdirSync(dir, { recursive: true });+ // Sizes aren't known until each starts; weight the binary at ~95%.+ let binP: DownloadProgress = { bytes: 0, total: null };+ let webP: DownloadProgress = { bytes: 0, total: null };+ const report = () => opts.onProgress?.({ bytes: binP.bytes + webP.bytes, total: binP.total !== null && webP.total !== null ? binP.total + webP.total : binP.total });+ const binary = join(dir, asset);+ const web = join(dir, 'web.tar.gz');+ await downloadResumable(`${base}/${asset}`, binary, { ...opts, expectedSha256: binSum, onProgress: (p) => { binP = p; report(); } });+ await downloadResumable(`${base}/web.tar.gz`, web, { ...opts, expectedSha256: webSum, onProgress: (p) => { webP = p; report(); } });+ return { dir, binary, web, asset };+}diff --git a/src/updates/fixtures/fixture.json b/src/updates/fixtures/fixture.jsonnew file mode 100644index 00000000..5c6a6ca0--- /dev/null+++ b/src/updates/fixtures/fixture.json@@ -0,0 +1 @@+{"schema":1,"issuedAt":"2026-11-03T12:00:00Z"}diff --git a/src/updates/fixtures/fixture.json.sig b/src/updates/fixtures/fixture.json.signew file mode 100644index 00000000..7fd51a79--- /dev/null+++ b/src/updates/fixtures/fixture.json.sig@@ -0,0 +1 @@+dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVUemlkNzgvZEthQTZ5c25tZVNrSTdEczFIMDAyL3ZPcGRsODk2RFR6RlpHZkpmVUFtTFBNNlpMcGtGK0k5WnhpVHdWNlE1SW1HWThGalVJVFloLzVUYUg0U3Z1cExSYVFrPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkzNjgzNDYyCWZpbGU6Zml4dHVyZS5qc29uClFRWkdRTWdyVFNMbFBIZEo1UGZpb0tEYmtHRXRabDZOS3dTTERTNnpKY2RNZHF3QXNUY1dDeUdTR00yNnEzaGhYVmNSR0tLNmMzNEhWOTJsd2RXd0FRPT0K\ No newline at end of filediff --git a/src/updates/fixtures/throwaway.pub b/src/updates/fixtures/throwaway.pubnew file mode 100644index 00000000..cb0a4d96--- /dev/null+++ b/src/updates/fixtures/throwaway.pub@@ -0,0 +1 @@+dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDAzOUFEMkZERkNERTg5RjMKUldUemlkNzgvZEthQXlLYyt2L3NSK0RERTI5bVI3bE55RjJtQlpMQ01ZbW5aWC9QbG16emNzWTQK\ No newline at end of filediff --git a/src/updates/install-kind.ts b/src/updates/install-kind.tsnew file mode 100644index 00000000..f6a4f0c7--- /dev/null+++ b/src/updates/install-kind.ts@@ -0,0 +1,72 @@+import { existsSync } from 'node:fs';+import { dirname, join, resolve, sep } from 'node:path';+import { isStandaloneBinary } from '../cli/daemon.js';+import { isDevBuild } from '../utils/dev-build.js';++/**+ * How this Mercury was installed, which decides how it updates:+ *+ * - binary: the one-file build from the installer (~/.mercury/bin/mercury):+ * download the release asset, check its checksum, swap it in;+ * - npm: a global npm install: `npm i -g` the exact version;+ * - source: a git checkout — updating is `git pull` and a build, which+ * Mercury won't do to someone's working tree;+ * - unknown: anything else (a project-local install, an unusual runtime).+ */++export type InstallKind = 'binary' | 'npm' | 'source' | 'unknown';++export interface InstallInfo {+ kind: InstallKind;+ channel: 'stable' | 'dev';+ canSelfUpdate: boolean;+ cannotReason?: string;+ /** binary: the executable to replace. */+ binaryPath?: string;+ /** npm: the package directory. */+ packageDir?: string;+}++export const NPM_PACKAGE = '@cosmicstack/mercury-agent';++function findUp(start: string, name: string): string | null {+ let dir = resolve(start);+ for (let i = 0; i < 12; i++) {+ if (existsSync(join(dir, name))) return dir;+ const up = dirname(dir);+ if (up === dir) return null;+ dir = up;+ }+ return null;+}++function isGlobalNpmPath(p: string): boolean {+ const n = p.split(sep).join('/');+ // POSIX prefixes put globals in <prefix>/lib/node_modules; Windows in %AppData%\npm\node_modules; nvm/volta/fnm keep the same shapes.+ return /\/lib\/node_modules\/@cosmicstack\/mercury-agent\//.test(n) || /\/npm\/node_modules\/@cosmicstack\/mercury-agent\//i.test(n);+}++export function detectInstall(version: string, opts: { script?: string; execPath?: string; standalone?: boolean } = {}): InstallInfo {+ const channel = isDevBuild(version) ? 'dev' : 'stable';+ const forced = process.env.MERCURY_INSTALL_KIND as InstallKind | undefined;+ const standalone = opts.standalone ?? isStandaloneBinary();+ const execPath = opts.execPath ?? process.execPath;+ const script = opts.script ?? process.argv[1] ?? '';++ if (forced === 'binary' || (!forced && standalone)) {+ return { kind: 'binary', channel, canSelfUpdate: true, binaryPath: execPath };+ }+ if (forced === 'npm' || (!forced && script && isGlobalNpmPath(script))) {+ const n = script.split(sep).join('/');+ const at = n.indexOf('/@cosmicstack/mercury-agent/');+ const packageDir = at >= 0 ? script.slice(0, at + '/@cosmicstack/mercury-agent'.length) : undefined;+ return { kind: 'npm', channel, canSelfUpdate: true, packageDir };+ }+ if (forced === 'source' || (!forced && script && findUp(dirname(script), '.git'))) {+ return { kind: 'source', channel, canSelfUpdate: false, cannotReason: 'This Mercury runs from a source checkout. Update it with git pull and a build.' };+ }+ if (script.includes(`${sep}node_modules${sep}`) || script.includes('/node_modules/')) {+ return { kind: 'unknown', channel, canSelfUpdate: false, cannotReason: 'This Mercury is installed inside a project, not globally. Update it with that project\'s package manager.' };+ }+ return { kind: 'unknown', channel, canSelfUpdate: false, cannotReason: 'Mercury can\'t tell how it was installed, so it won\'t update itself. Reinstall from mercuryagent.sh.' };+}diff --git a/src/updates/manifest.ts b/src/updates/manifest.tsnew file mode 100644index 00000000..c6e0a3aa--- /dev/null+++ b/src/updates/manifest.ts@@ -0,0 +1,302 @@+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { getMercuryHome } from '../utils/config.js';+import { logger } from '../utils/logger.js';+import { verifyMinisign } from './minisign.js';+import { UPDATE_PUBLIC_KEY } from './public-key.js';++/**+ * The update manifest (docs/updates.md §1): one signed file that says what+ * the newest Mercury and Mercury Desktop are, which versions must update,+ * and what to tell people.+ *+ * Trust rules: a manifest whose signature doesn't verify is ignored (the+ * plain version look-ups take over, and nothing is ever "required" on their+ * word); one older than the newest we've seen is ignored (no replaying an+ * old file); no manifest at all never blocks anything (fail open).+ */++export const MANIFEST_URLS = [+ 'https://mercuryagent.sh/updates/manifest.json',+ 'https://raw.githubusercontent.com/cosmicstack-labs/mercury-agent/main/website/static/updates/manifest.json',+];++/** Refetch at most this often on our own. */+export const MANIFEST_TTL_MS = 6 * 60 * 60_000;+/** "Check for updates" bypasses the cache, at most this often. */+export const FORCED_CHECK_GAP_MS = 60_000;++export type UpdateApp = 'server' | 'desktop';++export interface ReleaseInfo {+ version: string;+ date?: string;+ notes?: string;+ notesUrl?: string;+}++export interface MinimumVersion {+ version: string;+ severity: 'security' | 'required';+ reason: string;+ since?: string;+}++export interface ManifestMessage {+ id: string;+ title: string;+ body?: string;+ level: 'info' | 'warning' | 'critical';+ apps?: UpdateApp[];+ versions?: string | null;+ startsAt?: string | null;+ endsAt?: string | null;+ link?: { label: string; url: string } | null;+ dismissible?: boolean;+}++export interface AppSection {+ channels?: { stable?: ReleaseInfo | null; dev?: ReleaseInfo | null };+ minimum?: MinimumVersion | null;+}++export interface UpdateManifest {+ schema: 1;+ issuedAt: string;+ server?: AppSection;+ desktop?: AppSection;+ messages?: ManifestMessage[];+}++// ─── Versions ────────────────────────────────────────────────────────────────++function parts(v: string): number[] {+ return v.trim().replace(/^v/, '').split(/[.\-+]/).map((p) => parseInt(p, 10) || 0);+}++/**+ * -1 / 0 / 1. Numeric part by part, the same way the CLI's update notice has+ * always compared: a dev build of 1.4.2 (`1.4.2-dev.20261103.abc`) counts as+ * newer than 1.4.2 itself, which is when dev builds are made.+ */+export function compareVersions(a: string, b: string): number {+ const [pa, pb] = [parts(a), parts(b)];+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);+ if (d !== 0) return d > 0 ? 1 : -1;+ }+ return 0;+}++/** Does `version` satisfy every comparator in `range` ("<1.5.0", ">=1.4 <1.5", "=1.4.2")? Empty matches all. */+export function versionMatches(version: string, range?: string | null): boolean {+ const comparators = String(range ?? '').trim().split(/\s+/).filter(Boolean);+ for (const c of comparators) {+ const m = /^(>=|<=|>|<|=)?\s*v?(\d[\w.\-+]*)$/.exec(c);+ if (!m) return false; // a range we can't read applies to nobody+ const cmp = compareVersions(version, m[2]);+ const op = m[1] ?? '=';+ const ok = op === '>=' ? cmp >= 0 : op === '<=' ? cmp <= 0 : op === '>' ? cmp > 0 : op === '<' ? cmp < 0 : cmp === 0;+ if (!ok) return false;+ }+ return true;+}++// ─── Reading the file ────────────────────────────────────────────────────────++const isStr = (v: unknown): v is string => typeof v === 'string' && v.trim() !== '';++function release(v: unknown): ReleaseInfo | null {+ if (!v || typeof v !== 'object') return null;+ const r = v as Record<string, unknown>;+ if (!isStr(r.version)) return null;+ return {+ version: r.version.trim().replace(/^v/, ''),+ ...(isStr(r.date) ? { date: r.date } : {}),+ ...(isStr(r.notes) ? { notes: r.notes } : {}),+ ...(isStr(r.notesUrl) && /^https:\/\//.test(r.notesUrl) ? { notesUrl: r.notesUrl } : {}),+ };+}++function minimum(v: unknown): MinimumVersion | null {+ if (!v || typeof v !== 'object') return null;+ const m = v as Record<string, unknown>;+ if (!isStr(m.version)) return null;+ return {+ version: m.version.trim().replace(/^v/, ''),+ severity: m.severity === 'security' ? 'security' : 'required',+ reason: isStr(m.reason) ? m.reason : 'This version must be updated.',+ ...(isStr(m.since) ? { since: m.since } : {}),+ };+}++function section(v: unknown): AppSection {+ const s = (v && typeof v === 'object' ? v : {}) as Record<string, unknown>;+ const ch = (s.channels && typeof s.channels === 'object' ? s.channels : {}) as Record<string, unknown>;+ return { channels: { stable: release(ch.stable), dev: release(ch.dev) }, minimum: minimum(s.minimum) };+}++function message(v: unknown): ManifestMessage | null {+ if (!v || typeof v !== 'object') return null;+ const m = v as Record<string, unknown>;+ if (!isStr(m.id) || !isStr(m.title)) return null;+ const level = m.level === 'critical' || m.level === 'warning' ? m.level : 'info';+ const apps = Array.isArray(m.apps) ? m.apps.filter((a): a is UpdateApp => a === 'server' || a === 'desktop') : undefined;+ const link = m.link && typeof m.link === 'object' && isStr((m.link as Record<string, unknown>).url) && /^https:\/\//.test(String((m.link as Record<string, unknown>).url))+ ? { label: isStr((m.link as Record<string, unknown>).label) ? String((m.link as Record<string, unknown>).label) : 'Read more', url: String((m.link as Record<string, unknown>).url) }+ : null;+ return {+ id: m.id, title: m.title, level,+ ...(isStr(m.body) ? { body: m.body } : {}),+ ...(apps ? { apps } : {}),+ versions: isStr(m.versions) ? m.versions : null,+ startsAt: isStr(m.startsAt) ? m.startsAt : null,+ endsAt: isStr(m.endsAt) ? m.endsAt : null,+ link,+ // Only a critical message may refuse to be dismissed.+ dismissible: level === 'critical' ? m.dismissible !== false : true,+ };+}++/** The manifest from its text, normalised; null when it isn't one. */+export function parseManifest(text: string): UpdateManifest | null {+ let raw: unknown;+ try { raw = JSON.parse(text); } catch { return null; }+ if (!raw || typeof raw !== 'object') return null;+ const r = raw as Record<string, unknown>;+ if (r.schema !== 1 || !isStr(r.issuedAt) || Number.isNaN(Date.parse(r.issuedAt))) return null;+ return {+ schema: 1,+ issuedAt: r.issuedAt,+ server: section(r.server),+ desktop: section(r.desktop),+ messages: Array.isArray(r.messages) ? r.messages.map(message).filter((m): m is ManifestMessage => !!m) : [],+ };+}++/** The manifest when `signature` (Tauri `.sig` text) verifies against `publicKey`; otherwise why not. */+export function verifyManifest(text: string, signature: string, publicKey = UPDATE_PUBLIC_KEY): { manifest: UpdateManifest } | { error: string } {+ const check = verifyMinisign(Buffer.from(text, 'utf8'), signature, publicKey);+ if (!check.ok) return { error: check.reason ?? 'The signature did not verify.' };+ const manifest = parseManifest(text);+ return manifest ? { manifest } : { error: 'The signed file is not an update manifest.' };+}++// ─── What applies to whom ────────────────────────────────────────────────────++export function latestFor(manifest: UpdateManifest | null, app: UpdateApp, channel: 'stable' | 'dev'): ReleaseInfo | null {+ return manifest?.[app]?.channels?.[channel] ?? null;+}++/** The required update when `version` is below the minimum; null otherwise. */+export function requiredFor(manifest: UpdateManifest | null, app: UpdateApp, version: string): MinimumVersion | null {+ const min = manifest?.[app]?.minimum;+ return min && compareVersions(version, min.version) < 0 ? min : null;+}++/** Messages for this app and version that are live now. */+export function messagesFor(manifest: UpdateManifest | null, app: UpdateApp, version: string, now = Date.now()): ManifestMessage[] {+ return (manifest?.messages ?? []).filter((m) => {+ if (m.apps && m.apps.length && !m.apps.includes(app)) return false;+ if (m.startsAt && Date.parse(m.startsAt) > now) return false;+ if (m.endsAt && Date.parse(m.endsAt) <= now) return false;+ return versionMatches(version, m.versions);+ });+}++// ─── Fetching and the cache ──────────────────────────────────────────────────++export interface ManifestCache {+ manifest: UpdateManifest | null;+ /** The newest issuedAt ever accepted (anti-replay). */+ highestIssuedAt?: string;+ checkedAt: number | null;+ forcedAt?: number;+ /** Why the last fetch didn't give a usable manifest. */+ error?: string;+}++function updatesDir(): string {+ return join(getMercuryHome(), 'updates');+}++function cachePath(): string {+ return join(updatesDir(), 'manifest.json');+}++export function readManifestCache(): ManifestCache {+ try {+ if (existsSync(cachePath())) {+ const c = JSON.parse(readFileSync(cachePath(), 'utf-8')) as ManifestCache;+ return { manifest: c.manifest ?? null, highestIssuedAt: c.highestIssuedAt, checkedAt: c.checkedAt ?? null, forcedAt: c.forcedAt, error: c.error };+ }+ } catch { /* corrupt → start clean */ }+ return { manifest: null, checkedAt: null };+}++function writeManifestCache(c: ManifestCache): void {+ try {+ mkdirSync(updatesDir(), { recursive: true });+ const tmp = `${cachePath()}.tmp`;+ writeFileSync(tmp, JSON.stringify(c, null, 2), 'utf-8');+ renameSync(tmp, cachePath());+ } catch (err) {+ logger.debug({ err }, 'updates: saving the manifest cache failed');+ }+}++async function fetchText(url: string, fetchImpl: typeof fetch, timeoutMs: number): Promise<string | null> {+ try {+ const res = await fetchImpl(url, { headers: { accept: 'application/json, text/plain' }, signal: AbortSignal.timeout(timeoutMs), cache: 'no-store' } as RequestInit);+ if (!res.ok) return null;+ const text = await res.text();+ return text.length > 512 * 1024 ? null : text;+ } catch {+ return null;+ }+}++export interface FetchManifestOptions {+ force?: boolean;+ fetchImpl?: typeof fetch;+ urls?: string[];+ publicKey?: string;+ now?: number;+ timeoutMs?: number;+}++/**+ * The manifest to act on: the cached one while it's fresh, otherwise a new+ * verified one (primary address, then the mirror). Never throws; a failure+ * keeps the last good manifest.+ */+export async function getManifest(opts: FetchManifestOptions = {}): Promise<ManifestCache> {+ const now = opts.now ?? Date.now();+ const cache = readManifestCache();+ const fresh = cache.checkedAt !== null && now - cache.checkedAt < MANIFEST_TTL_MS;+ if (!opts.force && fresh) return cache;+ if (opts.force && cache.forcedAt && now - cache.forcedAt < FORCED_CHECK_GAP_MS) return cache;++ const fetchImpl = opts.fetchImpl ?? fetch;+ let error = 'The update information could not be reached.';+ let accepted: UpdateManifest | null = null;+ for (const url of opts.urls ?? MANIFEST_URLS) {+ const [text, sig] = await Promise.all([fetchText(url, fetchImpl, opts.timeoutMs ?? 8000), fetchText(`${url}.sig`, fetchImpl, opts.timeoutMs ?? 8000)]);+ if (!text || !sig) continue;+ const v = verifyManifest(text, sig, opts.publicKey);+ if ('error' in v) { error = `The update information was not signed by Mercury (${v.error})`; continue; }+ if (cache.highestIssuedAt && Date.parse(v.manifest.issuedAt) < Date.parse(cache.highestIssuedAt)) {+ error = 'The update information was older than one already seen; ignored.';+ continue;+ }+ accepted = v.manifest;+ break;+ }++ const next: ManifestCache = accepted+ ? { manifest: accepted, highestIssuedAt: accepted.issuedAt, checkedAt: now, forcedAt: opts.force ? now : cache.forcedAt }+ : { ...cache, checkedAt: now, forcedAt: opts.force ? now : cache.forcedAt, error };+ if (!accepted) logger.debug({ error }, 'updates: no new manifest');+ writeManifestCache(next);+ return next;+}diff --git a/src/updates/minisign.ts b/src/updates/minisign.tsnew file mode 100644index 00000000..f930f29a--- /dev/null+++ b/src/updates/minisign.ts@@ -0,0 +1,88 @@+import { createHash, createPublicKey, verify } from 'node:crypto';++/**+ * Minisign signatures, in the form `tauri signer sign` writes them: the+ * `.sig` file and the public key are both base64 of the minisign text.+ * The same key signs Mercury Desktop's update packages and the update+ * manifest, so one key decides what "required" means everywhere.+ *+ * Two checks, both must pass:+ * - the signature over the data: Ed25519 over BLAKE2b-512 of the data+ * ("ED", what minisign and Tauri make) or over the data itself ("Ed");+ * - the global signature over that signature and the trusted comment, so+ * the comment (which names the file and time) can't be swapped either.+ */++export interface MinisignResult {+ ok: boolean;+ /** Why it failed, in plain words. */+ reason?: string;+ /** The signed trusted comment ("timestamp:… file:…") when ok. */+ trustedComment?: string;+}++interface PublicKey { keyId: Buffer; key: Buffer }++/** The text inside, when the value is base64 of a minisign file; otherwise the value as is. */+function unwrap(value: string): string {+ const v = value.trim();+ if (/^untrusted comment:/i.test(v)) return v;+ try {+ const text = Buffer.from(v, 'base64').toString('utf8');+ if (/^untrusted comment:/i.test(text)) return text;+ } catch { /* not base64 */ }+ return v;+}++function lines(text: string): string[] {+ return text.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);+}++export function parsePublicKey(value: string): PublicKey | null {+ const text = unwrap(value);+ const keyLine = lines(text).find((l) => !/^untrusted comment:/i.test(l));+ if (!keyLine) return null;+ const raw = Buffer.from(keyLine, 'base64');+ if (raw.length !== 42 || raw.subarray(0, 2).toString('latin1') !== 'Ed') return null;+ return { keyId: raw.subarray(2, 10), key: raw.subarray(10, 42) };+}++function edVerify(publicKey: Buffer, message: Buffer, signature: Buffer): boolean {+ try {+ const key = createPublicKey({ key: { kty: 'OKP', crv: 'Ed25519', x: publicKey.toString('base64url') }, format: 'jwk' });+ return verify(null, message, key, signature);+ } catch {+ return false;+ }+}++export function verifyMinisign(data: Buffer | string, signature: string, publicKey: string): MinisignResult {+ const pk = parsePublicKey(publicKey);+ if (!pk) return { ok: false, reason: 'The public key is not a minisign key.' };++ const sigLines = lines(unwrap(signature));+ const body = sigLines.filter((l) => !/^untrusted comment:/i.test(l));+ const sigLine = body[0];+ const trustedLine = body.find((l) => /^trusted comment:/i.test(l));+ const globalLine = trustedLine ? body[body.indexOf(trustedLine) + 1] : undefined;+ if (!sigLine || !trustedLine || !globalLine) return { ok: false, reason: 'The signature is incomplete.' };++ const sig = Buffer.from(sigLine, 'base64');+ if (sig.length !== 74) return { ok: false, reason: 'The signature is malformed.' };+ const alg = sig.subarray(0, 2).toString('latin1');+ const keyId = sig.subarray(2, 10);+ const edSig = sig.subarray(10, 74);+ if (alg !== 'ED' && alg !== 'Ed') return { ok: false, reason: 'Unknown signature algorithm.' };+ if (!keyId.equals(pk.keyId)) return { ok: false, reason: 'Signed with a different key.' };++ const bytes = Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf8');+ const message = alg === 'ED' ? createHash('blake2b512').update(bytes).digest() : bytes;+ if (!edVerify(pk.key, message, edSig)) return { ok: false, reason: 'The signature does not match the data.' };++ const trustedComment = trustedLine.replace(/^trusted comment:\s?/i, '');+ const globalSig = Buffer.from(globalLine, 'base64');+ if (globalSig.length !== 64 || !edVerify(pk.key, Buffer.concat([edSig, Buffer.from(trustedComment, 'utf8')]), globalSig)) {+ return { ok: false, reason: 'The signed comment was changed.' };+ }+ return { ok: true, trustedComment };+}diff --git a/src/updates/notices.ts b/src/updates/notices.tsnew file mode 100644index 00000000..66936e13--- /dev/null+++ b/src/updates/notices.ts@@ -0,0 +1,53 @@+import type { ServerUpdateStatus } from './status.js';++/**+ * What the terminal chat says about updates when it opens. Calm by default+ * (an available update is mentioned once per version and can be ignored),+ * firm when it matters (a required update is said every time and can't be+ * ignored), and messages from the manifest once each (a critical one that+ * can't be dismissed, every time).+ */++export interface StartupNotices {+ notices: string[];+ /** The version for the status bar's "update available" mark, or null. */+ badge: string | null;+ /** Message ids now shown (remember them so they don't repeat). */+ shown: string[];+}++export function startupNotices(s: ServerUpdateStatus, ignored: string | undefined, alreadyShown: ReadonlySet<string>): StartupNotices {+ const notices: string[] = [];+ const shown: string[] = [];+ let badge: string | null = null;++ if (s.required) {+ badge = s.latest?.version ?? s.required.version;+ const how = s.canSelfUpdate ? 'Run `mercury upgrade` in your terminal (it goes back on its own if anything fails).' : (s.cannotReason ?? 'Reinstall from mercuryagent.sh.');+ notices.push(`⛔ **Update required${s.required.severity === 'security' ? ' (security)' : ''}.** ${s.required.reason} Mercury v${s.current} is below v${s.required.version}. ${how}`);+ } else if (s.updateAvailable && s.latest && ignored !== s.latest.version && !s.blocked) {+ badge = s.latest.version;+ notices.push(`⬆ Update available: v${s.current} → v${s.latest.version}. Run \`mercury upgrade\` in your terminal when you're ready (\`mercury update\` shows what's new), or ignore this version with \`/update ignore\`.`);+ }++ for (const m of s.messages) {+ const sticky = m.level === 'critical' && m.dismissible === false;+ if (!sticky && alreadyShown.has(m.id)) continue;+ const icon = m.level === 'critical' ? '⛔' : m.level === 'warning' ? '⚠' : 'ℹ';+ notices.push(`${icon} **${m.title}**${m.body ? `\n${m.body}` : ''}${m.link ? `\n${m.link.label}: ${m.link.url}` : ''}`);+ if (!sticky) shown.push(m.id);+ }+ return { notices, badge, shown };+}++/** `mercury doctor`'s one line about updates. */+export function updatesLine(s: ServerUpdateStatus): { text: string; level: 'ok' | 'note' | 'risk' } {+ const head = ` Updates: v${s.current}`;+ if (s.required) return { level: 'risk', text: `${head} — update required${s.required.severity === 'security' ? ' (security)' : ''}: ${s.required.reason} Run \`mercury upgrade\`` };+ if (s.job && !['done', 'rolled-back', 'failed', 'cancelled'].includes(s.job.state)) return { level: 'note', text: `${head} — updating to v${s.job.to}: ${s.job.message}` };+ if (s.blocked) return { level: 'note', text: `${head} — v${s.blocked.version} failed to install ${s.blocked.failures} times (${s.blocked.lastError}); \`mercury upgrade\` tries again` };+ if (s.job?.state === 'rolled-back' && s.job.to === s.latest?.version) return { level: 'note', text: `${head} — the update to v${s.job.to} went back: ${s.job.error ?? 'it did not start'}` };+ if (s.updateAvailable && s.latest) return { level: 'note', text: `${head} — v${s.latest.version} is available (\`mercury upgrade\`)` };+ if (!s.latest) return { level: 'ok', text: `${head} — couldn't check for updates` };+ return { level: 'ok', text: `${head} — up to date` };+}diff --git a/src/updates/public-key.ts b/src/updates/public-key.tsnew file mode 100644index 00000000..f0799805--- /dev/null+++ b/src/updates/public-key.ts@@ -0,0 +1,8 @@+/**+ * The key that signs Mercury's update manifest and Mercury Desktop's update+ * packages (minisign, as `tauri signer` makes it). The same string is+ * `plugins.updater.pubkey` in apps/desktop/src-tauri/tauri.conf.json; a+ * test keeps the two equal. The private key never lives in this repository.+ */+export const UPDATE_PUBLIC_KEY =+ 'dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEVCNjg5RDJCNTMzMzc5RDYKUldUV2VUTlRLNTFvNjFKY2NMR2RRQXVjcXRIbVNiN2tYNkNQSUprMWJVM0NjeHRmL045Q3RUSDYK';diff --git a/src/updates/server-updater.ts b/src/updates/server-updater.tsnew file mode 100644index 00000000..819d9f48--- /dev/null+++ b/src/updates/server-updater.ts@@ -0,0 +1,653 @@+import { spawn, execFile, execFileSync } from 'node:child_process';+import { chmodSync, copyFileSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { randomUUID } from 'node:crypto';+import { basename, dirname, join } from 'node:path';+import { getMercuryHome } from '../utils/config.js';+import { logger } from '../utils/logger.js';+import { NotAvailableError, downloadRelease, downloadsDir, type DownloadProgress } from './download.js';+import { NPM_PACKAGE, type InstallInfo, type InstallKind } from './install-kind.js';++/**+ * Updating the server without breaking it (docs/updates.md §2).+ *+ * The running Mercury does the safe half: waits for running work, downloads+ * (resumable, checksum-verified) and backs up the settings files, all while+ * it keeps serving. Then a detached worker (`mercury __update-worker <id>`)+ * does the half Mercury can't do to itself: stop it, put the new version in+ * place (the old one kept beside it), start it and check it answers as the+ * new version. If it doesn't within 90 seconds, the worker puts the old+ * version and settings back and starts that: the update rolls itself back.+ *+ * The job lives in ~/.mercury/updates/job.json, so whichever Mercury is up+ * (new or restored) can say how it went. A version that fails three times is+ * "blocked": Mercury stops offering it on its own until someone retries.+ * A version that isn't downloadable yet is not a failure: nothing changed.+ */++export type JobState =+ | 'waiting-idle' | 'downloading' | 'verifying' | 'backing-up' | 'stopping'+ | 'installing' | 'starting' | 'checking'+ | 'done' | 'rolled-back' | 'failed' | 'cancelled';++export interface UpdateJob {+ id: string;+ from: string;+ to: string;+ state: JobState;+ percent: number | null;+ bytes?: number;+ total?: number;+ message: string;+ startedAt: number;+ updatedAt: number;+ error?: string;+ log: string[];+ attempt: number;+ install: InstallKind;+ channel: 'stable' | 'dev';+ /** The worker that owns the job from 'stopping' on. */+ workerPid?: number;+ /** The version isn't published (yet); nothing was changed. */+ notAvailable?: boolean;+ dryRun?: boolean;+ /** Where the downloaded release is (binary installs). */+ files?: { binary: string; web: string; asset: string };+ binaryPath?: string;+ packageDir?: string;+}++export const TERMINAL: ReadonlySet<JobState> = new Set(['done', 'rolled-back', 'failed', 'cancelled']);+const BEFORE_STOP: ReadonlySet<JobState> = new Set(['waiting-idle', 'downloading', 'verifying', 'backing-up']);+export const MAX_FAILURES = 3;+const IDLE_WAIT_MS = 10 * 60_000;+export const HEALTH_TIMEOUT_MS = 90_000;+const JUST_UPDATED_DAYS = 7;++/** Overall progress at the start of each step. Downloading fills 2→60. */+const STEP_PERCENT: Record<JobState, number> = {+ 'waiting-idle': 0, downloading: 2, verifying: 62, 'backing-up': 66, stopping: 70,+ installing: 78, starting: 86, checking: 92, done: 100, 'rolled-back': 100, failed: 100, cancelled: 100,+};++const STEP_MESSAGE: Partial<Record<JobState, string>> = {+ 'waiting-idle': 'Waiting for running work to finish',+ downloading: 'Downloading',+ verifying: 'Checking the download',+ 'backing-up': 'Backing up your settings',+ stopping: 'Stopping Mercury',+ installing: 'Installing',+ starting: 'Starting the new version',+ checking: 'Checking the new version works',+};++// ─── Files ───────────────────────────────────────────────────────────────────++export function updatesHome(): string { return join(getMercuryHome(), 'updates'); }+const jobPath = () => join(updatesHome(), 'job.json');+const statePath = () => join(updatesHome(), 'state.json');+export const backupDir = (version: string) => join(updatesHome(), 'backup', version.replace(/[^\w.\-+]/g, '_'));++function writeAtomic(path: string, data: unknown): void {+ mkdirSync(dirname(path), { recursive: true });+ const tmp = `${path}.${process.pid}.tmp`;+ writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf-8');+ renameSync(tmp, path);+}++export function readJob(): UpdateJob | null {+ try { return existsSync(jobPath()) ? JSON.parse(readFileSync(jobPath(), 'utf-8')) as UpdateJob : null; } catch { return null; }+}++function saveJob(job: UpdateJob): void {+ job.updatedAt = Date.now();+ try { writeAtomic(jobPath(), job); } catch (err) { logger.warn({ err: String(err) }, 'updates: saving the job failed'); }+}++export interface UpdateStateFile {+ failures: Record<string, { count: number; lastError: string; at: number }>;+ justUpdated?: { from: string; to: string; at: number; seen?: boolean } | null;+}++export function readUpdateState(): UpdateStateFile {+ try {+ if (existsSync(statePath())) {+ const s = JSON.parse(readFileSync(statePath(), 'utf-8')) as UpdateStateFile;+ return { failures: s.failures ?? {}, justUpdated: s.justUpdated ?? null };+ }+ } catch { /* corrupt → clean */ }+ return { failures: {} };+}++function saveUpdateState(s: UpdateStateFile): void {+ try { writeAtomic(statePath(), s); } catch { /* best effort */ }+}++function recordFailure(version: string, error: string): void {+ const s = readUpdateState();+ const f = s.failures[version] ?? { count: 0, lastError: '', at: 0 };+ s.failures[version] = { count: f.count + 1, lastError: error, at: Date.now() };+ saveUpdateState(s);+}++/** Three failures at this version: don't offer it on our own any more. */+export function blockedFor(version: string | null | undefined): { version: string; failures: number; lastError: string } | null {+ if (!version) return null;+ const f = readUpdateState().failures[version];+ return f && f.count >= MAX_FAILURES ? { version, failures: f.count, lastError: f.lastError } : null;+}++/** "Try again" by hand starts the count over. */+export function clearFailures(version: string): void {+ const s = readUpdateState();+ if (s.failures[version]) { delete s.failures[version]; saveUpdateState(s); }+}++/** The last successful update, for "what's new", until it's been seen (or a week passed). */+export function justUpdated(current: string): { from: string; to: string; at: number } | null {+ const j = readUpdateState().justUpdated;+ if (!j || j.seen || j.to !== current) return null;+ if (Date.now() - j.at > JUST_UPDATED_DAYS * 86_400_000) return null;+ return { from: j.from, to: j.to, at: j.at };+}++export function markJustUpdatedSeen(): void {+ const s = readUpdateState();+ if (s.justUpdated && !s.justUpdated.seen) { s.justUpdated.seen = true; saveUpdateState(s); }+}++// ─── Job bookkeeping ─────────────────────────────────────────────────────────++function step(job: UpdateJob, state: JobState, message?: string): void {+ job.state = state;+ job.percent = STEP_PERCENT[state];+ job.message = message ?? STEP_MESSAGE[state] ?? job.message;+ log(job, job.message);+ saveJob(job);+}++function log(job: UpdateJob, line: string): void {+ const stamp = new Date().toTimeString().slice(0, 8);+ job.log.push(`${stamp} ${line}`);+ if (job.log.length > 40) job.log.splice(0, job.log.length - 40);+}++function finish(job: UpdateJob, state: 'done' | 'rolled-back' | 'failed' | 'cancelled', message: string, error?: string): void {+ if (error) job.error = error;+ step(job, state, message);+}++const errText = (err: unknown) => (err instanceof Error ? err.message : String(err)).slice(0, 500);++function isAlive(pid: number | undefined): boolean {+ if (!pid) return false;+ try { process.kill(pid, 0); return true; } catch (err) { return (err as NodeJS.ErrnoException)?.code === 'EPERM'; }+}++/** A job is running when it isn't finished and whoever owns it is alive. */+export function runningJob(): UpdateJob | null {+ const job = readJob();+ if (!job || TERMINAL.has(job.state)) return null;+ if (BEFORE_STOP.has(job.state)) return active?.id === job.id ? job : null;+ // Just handed over: the worker hasn't written its pid yet.+ if (job.state === 'stopping' && !job.workerPid && Date.now() - job.updatedAt < 30_000) return job;+ return isAlive(job.workerPid) ? job : null;+}++// ─── Steps (replaceable in tests) ────────────────────────────────────────────++export interface PrepareSteps {+ /** What's still running ("a reply in Telegram"), or null when idle. */+ busy(): string | null;+ /** Fetch what the install needs, before anything is stopped. */+ download(job: UpdateJob, onProgress: (p: DownloadProgress) => void, signal: AbortSignal): Promise<void>;+ backup(job: UpdateJob): Promise<void>;+ /** Start the worker that stops, installs, starts and checks. Returns its pid. */+ handOver(job: UpdateJob): Promise<number>;+}++export interface WorkerSteps {+ stop(): Promise<boolean>;+ install(job: UpdateJob): Promise<void>;+ start(): Promise<void>;+ /** True once Mercury answers as `version`. */+ health(version: string, timeoutMs: number): Promise<boolean>;+ /** Put the old version and settings back. */+ restore(job: UpdateJob): Promise<void>;+}++let busyProbe: () => string | null = () => null;+/** The runtime says what counts as busy (a reply, research, a bot run). */+export function setUpdateBusyProbe(fn: () => string | null): void { busyProbe = fn; }++export const isDryRun = () => process.env.MERCURY_UPDATE_DRY_RUN === '1';++// ─── The running Mercury's half ─────────────────────────────────────────────++let active: { id: string; abort: AbortController } | null = null;++export interface StartOptions {+ current: string;+ to: string;+ install: InstallInfo;+ /** Don't wait for running work. */+ now?: boolean;+ /** Started by hand: a blocked version gets a fresh count. */+ manual?: boolean;+ steps?: Partial<PrepareSteps>;+ idleWaitMs?: number;+}++export type StartResult = { ok: true; job: UpdateJob; done: Promise<void> } | { ok: false; status: 400 | 409; error: string; job?: UpdateJob };++export function startServerUpdate(opts: StartOptions): StartResult {+ const running = runningJob();+ if (running) return { ok: false, status: 409, error: 'An update is already running.', job: running };+ if (!opts.install.canSelfUpdate) return { ok: false, status: 400, error: opts.install.cannotReason ?? 'This Mercury can\'t update itself.' };+ if (!opts.to) return { ok: false, status: 400, error: 'No newer version is known.' };+ if (opts.manual) clearFailures(opts.to);++ const prev = readJob();+ const job: UpdateJob = {+ id: randomUUID(),+ from: opts.current,+ to: opts.to,+ state: 'waiting-idle',+ percent: 0,+ message: STEP_MESSAGE['waiting-idle']!,+ startedAt: Date.now(),+ updatedAt: Date.now(),+ log: [],+ attempt: prev && prev.to === opts.to ? prev.attempt + 1 : 1,+ install: opts.install.kind,+ channel: opts.install.channel,+ binaryPath: opts.install.binaryPath,+ packageDir: opts.install.packageDir,+ ...(isDryRun() ? { dryRun: true } : {}),+ };+ log(job, `Update ${opts.current} → ${opts.to} (${opts.install.kind}${isDryRun() ? ', dry run' : ''})`);+ saveJob(job);+ const abort = new AbortController();+ active = { id: job.id, abort };+ const steps = { ...realPrepareSteps(), ...opts.steps };+ const done = prepare(job, steps, abort.signal, opts.now ? 0 : opts.idleWaitMs ?? IDLE_WAIT_MS).finally(() => {+ if (active?.id === job.id) active = null;+ });+ return { ok: true, job, done };+}++/** Cancel, only while nothing has been stopped yet. */+export function cancelServerUpdate(): { ok: boolean; error?: string; job?: UpdateJob } {+ const job = readJob();+ if (!job || TERMINAL.has(job.state)) return { ok: false, error: 'No update is running.' };+ if (!BEFORE_STOP.has(job.state) || active?.id !== job.id) return { ok: false, error: 'The update is already installing and can\'t be stopped now.', job };+ active.abort.abort(new Error('Cancelled'));+ return { ok: true, job };+}++async function prepare(job: UpdateJob, steps: PrepareSteps, signal: AbortSignal, idleWaitMs: number): Promise<void> {+ try {+ const until = Date.now() + idleWaitMs;+ let said = '';+ for (;;) {+ if (signal.aborted) throw signal.reason;+ const busy = steps.busy();+ if (!busy) break;+ if (Date.now() >= until) { log(job, `Still busy (${busy}) after waiting; updating anyway`); break; }+ const msg = `Waiting for ${busy} to finish`;+ if (msg !== said) { said = msg; job.message = msg; log(job, msg); saveJob(job); }+ await new Promise((r) => setTimeout(r, 1000));+ }++ step(job, 'downloading', `Downloading Mercury ${job.to}`);+ let lastSave = 0;+ await steps.download(job, (p) => {+ job.bytes = p.bytes;+ if (p.total) job.total = p.total;+ job.percent = p.total ? 2 + Math.round(Math.min(1, p.bytes / p.total) * 58) : 2;+ if (Date.now() - lastSave > 500) { lastSave = Date.now(); saveJob(job); }+ }, signal);+ if (signal.aborted) throw signal.reason;++ step(job, 'verifying');+ step(job, 'backing-up');+ await steps.backup(job);+ if (signal.aborted) throw signal.reason;++ step(job, 'stopping', 'Handing over to the updater');+ // From here the worker owns job.json; writing it again could undo its progress.+ await steps.handOver(job);+ } catch (err) {+ if (signal.aborted) { finish(job, 'cancelled', 'Update cancelled. Nothing was changed.'); return; }+ if (err instanceof NotAvailableError || (err as { notAvailable?: boolean })?.notAvailable) {+ job.notAvailable = true;+ finish(job, 'failed', `${job.to} isn't downloadable yet. Nothing was changed; try again later.`, errText(err));+ return;+ }+ recordFailure(job.to, errText(err));+ finish(job, 'failed', `The update failed before anything was changed: ${errText(err)}`, errText(err));+ }+}++// ─── The worker's half ───────────────────────────────────────────────────────++export async function runUpdateWorker(jobId: string, steps: WorkerSteps = realWorkerSteps(), healthMs = HEALTH_TIMEOUT_MS): Promise<UpdateJob | null> {+ const job = readJob();+ if (!job || job.id !== jobId || TERMINAL.has(job.state)) return job;+ job.workerPid = process.pid;+ if (isDryRun()) job.dryRun = true;+ saveJob(job);++ step(job, 'stopping');+ let stopped = false;+ try { stopped = await steps.stop(); } catch (err) { log(job, `Stop failed: ${errText(err)}`); }+ if (!stopped) {+ recordFailure(job.to, 'Mercury could not be stopped');+ finish(job, 'failed', 'Mercury could not be stopped, so nothing was changed.', 'Mercury could not be stopped');+ return job;+ }++ let failure = '';+ try {+ step(job, 'installing', `Installing Mercury ${job.to}`);+ await steps.install(job);+ step(job, 'starting');+ await steps.start();+ step(job, 'checking');+ if (await steps.health(job.to, healthMs)) {+ const s = readUpdateState();+ delete s.failures[job.to];+ if (!job.dryRun) s.justUpdated = { from: job.from, to: job.to, at: Date.now() };+ saveUpdateState(s);+ cleanupAfterSuccess(job);+ finish(job, 'done', job.dryRun ? `Dry run finished: every step ran, nothing was changed.` : `Mercury ${job.to} is running.`);+ return job;+ }+ failure = `Mercury ${job.to} did not start properly within ${Math.round(healthMs / 1000)} seconds.`;+ } catch (err) {+ failure = errText(err);+ }++ // Going back.+ log(job, failure);+ recordFailure(job.to, failure);+ job.message = `Going back to ${job.from}`;+ saveJob(job);+ try {+ await steps.stop().catch(() => false);+ await steps.restore(job);+ await steps.start();+ if (await steps.health(job.from, healthMs)) {+ finish(job, 'rolled-back', `The update didn't work, so Mercury went back to ${job.from}. Nothing was lost.`, failure);+ } else {+ finish(job, 'failed', `The update didn't work and Mercury ${job.from} didn't come back on its own. Run \`mercury start\`.`, failure);+ }+ } catch (err) {+ finish(job, 'failed', `The update didn't work and going back failed too (${errText(err)}). Run \`mercury upgrade --force\` or reinstall from mercuryagent.sh.`, failure);+ }+ return job;+}++function cleanupAfterSuccess(job: UpdateJob): void {+ // Keep the backup of the version we came from; drop older ones and finished downloads.+ try {+ const root = join(updatesHome(), 'backup');+ if (existsSync(root)) for (const d of readdirSync(root)) if (d !== basename(backupDir(job.from))) rmSync(join(root, d), { recursive: true, force: true });+ rmSync(downloadsDir(job.to), { recursive: true, force: true });+ } catch { /* best effort */ }+}++/**+ * At start-up: a job the last Mercury left half done. Before the stop, the+ * Mercury that ran it is gone, so it never got further (nothing changed).+ * After it, the worker owns it; if the worker is gone too, the version we+ * are running tells how it ended.+ */+export function reconcileUpdateJob(current: string): void {+ const job = readJob();+ if (!job || TERMINAL.has(job.state)) return;+ if (BEFORE_STOP.has(job.state)) {+ if (active?.id === job.id) return;+ finish(job, 'cancelled', 'Mercury restarted before the update was installed. Nothing was changed.');+ return;+ }+ if (isAlive(job.workerPid) && job.workerPid !== process.pid) return;+ if (job.state === 'stopping' && !job.workerPid && Date.now() - job.updatedAt < 30_000) return;+ if (current === job.to) {+ const s = readUpdateState();+ delete s.failures[job.to];+ s.justUpdated = { from: job.from, to: job.to, at: Date.now() };+ saveUpdateState(s);+ finish(job, 'done', `Mercury ${job.to} is running.`);+ } else {+ recordFailure(job.to, 'The updater stopped halfway');+ finish(job, 'failed', `The update stopped halfway; Mercury is still ${current}.`, 'The updater stopped halfway');+ }+}++// ─── Real steps ──────────────────────────────────────────────────────────────++function run(cmd: string, args: string[], job?: UpdateJob, timeoutMs = 10 * 60_000): Promise<string> {+ return new Promise((resolve, reject) => {+ execFile(cmd, args, { timeout: timeoutMs, encoding: 'utf-8', shell: process.platform === 'win32', maxBuffer: 8 * 1024 * 1024 }, (err, stdout, stderr) => {+ const out = `${stdout ?? ''}${stderr ?? ''}`.trim();+ if (job && out) for (const l of out.split('\n').slice(-6)) log(job, l.slice(0, 200));+ if (err) reject(Object.assign(new Error(out.split('\n').filter(Boolean).slice(-1)[0] || err.message), { output: out }));+ else resolve(out);+ });+ });+}++/** Settings files at the top of ~/.mercury (not folders, not databases). */+export function backupConfig(version: string, home = getMercuryHome()): number {+ const dest = backupDir(version);+ mkdirSync(dest, { recursive: true });+ let n = 0;+ for (const name of readdirSync(home)) {+ const src = join(home, name);+ if (!/(\.json|\.ya?ml|\.env|^\.env.*)$/i.test(name) && name !== '.env') continue;+ try {+ const st = statSync(src);+ if (!st.isFile() || st.size > 5 * 1024 * 1024) continue;+ copyFileSync(src, join(dest, name));+ n++;+ } catch { /* skip */ }+ }+ return n;+}++export function restoreConfig(version: string, home = getMercuryHome()): number {+ const src = backupDir(version);+ if (!existsSync(src)) return 0;+ let n = 0;+ for (const name of readdirSync(src)) {+ try { copyFileSync(join(src, name), join(home, name)); n++; } catch { /* skip */ }+ }+ return n;+}++function realPrepareSteps(): PrepareSteps {+ return {+ busy: () => { try { return busyProbe(); } catch { return null; } },+ async download(job, onProgress, signal) {+ if (job.install === 'binary') {+ const files = await downloadRelease(job.to, job.channel, { signal, onProgress });+ job.files = { binary: files.binary, web: files.web, asset: files.asset };+ return;+ }+ if (job.install === 'npm') {+ // The exact version must exist, and run on this Node, before anything stops.+ const spec = `${NPM_PACKAGE}@${job.to}`;+ let found = '';+ try { found = await run('npm', ['view', spec, 'version'], undefined, 60_000); } catch { /* checked below */ }+ if (!found.trim()) throw new NotAvailableError(`${job.to} isn't on npm yet.`);+ if (!process.versions.bun) {+ let required = '';+ try { required = await run('npm', ['view', spec, 'engines.node'], undefined, 60_000); } catch { /* unknown */ }+ const need = Number((required.match(/(\d+)/) || [])[1] || 0);+ const have = Number(process.versions.node.split('.')[0]);+ if (need && have < need) throw Object.assign(new Error(`${job.to} needs Node.js ${need}+; this is Node ${process.version}. Update Node first.`), { permanent: true });+ }+ onProgress({ bytes: 0, total: null });+ // Into npm's cache now, so the install itself is quick and works offline.+ await run('npm', ['cache', 'add', spec], job);+ onProgress({ bytes: 1, total: 1 });+ }+ },+ async backup(job) {+ const n = backupConfig(job.from);+ log(job, `Backed up ${n} settings file${n === 1 ? '' : 's'}`);+ },+ async handOver(job) {+ const { buildDaemonSpawnArgs } = await import('../cli/daemon.js');+ const { command, args } = buildDaemonSpawnArgs();+ let cmd = command;+ let argv = [...args.slice(0, -2), '__update-worker', job.id];+ // systemd stops everything in the service's group when Mercury exits;+ // the worker gets its own unit so it outlives the stop.+ if (process.platform === 'linux') {+ const { isServiceInstalled } = await import('../cli/service.js');+ if (isServiceInstalled() && existsSync('/usr/bin/systemd-run')) {+ argv = ['--user', '--collect', '--quiet', `--unit=mercury-update-${job.id.slice(0, 8)}`, cmd, ...argv];+ cmd = '/usr/bin/systemd-run';+ }+ }+ mkdirSync(updatesHome(), { recursive: true });+ const out = openSync(join(updatesHome(), 'worker.log'), 'a');+ const child = spawn(cmd, argv, { detached: true, stdio: ['ignore', out, out], env: { ...process.env }, windowsHide: true });+ child.unref();+ if (!child.pid) throw new Error('The updater could not be started.');+ log(job, `Updater started (pid ${child.pid})`);+ return child.pid;+ },+ };+}++async function healthVersion(): Promise<{ version: string; booting: boolean } | null> {+ const { getWebPort } = await import('../web/auth.js');+ try {+ const res = await fetch(`http://127.0.0.1:${getWebPort()}/api/health`, { signal: AbortSignal.timeout(3000) });+ if (!res.ok) return null;+ const b = await res.json() as { version?: string; booting?: boolean };+ return { version: String(b.version ?? ''), booting: !!b.booting };+ } catch {+ return null;+ }+}++export function realWorkerSteps(): WorkerSteps {+ if (isDryRun()) {+ return {+ stop: async () => true,+ install: async () => { await new Promise((r) => setTimeout(r, 300)); },+ start: async () => {},+ health: async () => true,+ restore: async () => {},+ };+ }+ return {+ async stop() {+ const d = await import('../cli/daemon.js');+ const s = await import('../cli/service.js');+ if (d.getDaemonStatus().running) await d.stopDaemon();+ if (d.getForegroundRuntimeStatus().running) await d.stopForegroundRuntime();+ if (s.isServiceRunning()) s.stopService();+ return !d.getDaemonStatus().running && !d.getForegroundRuntimeStatus().running;+ },+ async install(job) {+ if (job.install === 'binary') return installBinary(job);+ if (job.install === 'npm') return installNpm(job, job.to);+ throw new Error('This install can\'t be updated automatically.');+ },+ async start() {+ const s = await import('../cli/service.js');+ if (s.isServiceInstalled()) { s.restartService(); return; }+ const d = await import('../cli/daemon.js');+ d.ensureDaemonRunning();+ },+ async health(version, timeoutMs) {+ const until = Date.now() + timeoutMs;+ while (Date.now() < until) {+ const h = await healthVersion();+ if (h && h.version === version && !h.booting) return true;+ await new Promise((r) => setTimeout(r, 1000));+ }+ return false;+ },+ async restore(job) {+ if (job.install === 'binary') restoreBinary(job);+ else if (job.install === 'npm') await installNpm(job, job.from);+ const n = restoreConfig(job.from);+ log(job, `Restored ${n} settings file${n === 1 ? '' : 's'}`);+ },+ };+}++const prevOf = (p: string) => `${p}.prev`;++export function installBinary(job: UpdateJob, run = runTar): void {+ if (!job.files || !job.binaryPath) throw new Error('The download is missing.');+ const bin = job.binaryPath;+ const binDir = dirname(bin);+ const stage = join(dirname(job.files.web), 'stage');+ rmSync(stage, { recursive: true, force: true });+ mkdirSync(stage, { recursive: true });+ run(job.files.web, stage);+ if (!existsSync(join(stage, 'web'))) throw new Error('The web dashboard archive was empty.');++ // The old version stays beside the new one until the next update.+ rmSync(prevOf(bin), { force: true });+ renameSync(bin, prevOf(bin));+ try {+ copyFileSync(job.files.binary, bin);+ if (process.platform !== 'win32') chmodSync(bin, 0o755);+ } catch (err) {+ try { rmSync(bin, { force: true }); renameSync(prevOf(bin), bin); } catch { /* restore below */ }+ throw err;+ }+ const web = join(binDir, 'web');+ rmSync(prevOf(web), { recursive: true, force: true });+ if (existsSync(web)) renameSync(web, prevOf(web));+ renameSync(join(stage, 'web'), web);+ if (process.platform === 'darwin') {+ try { execFile('xattr', ['-d', 'com.apple.quarantine', bin], () => {}); } catch { /* not quarantined */ }+ }+ log(job, `Installed ${job.files.asset} at ${bin}`);+}++export function restoreBinary(job: UpdateJob): void {+ if (!job.binaryPath) return;+ const bin = job.binaryPath;+ if (existsSync(prevOf(bin))) {+ rmSync(bin, { force: true });+ renameSync(prevOf(bin), bin);+ }+ const web = join(dirname(bin), 'web');+ if (existsSync(prevOf(web))) {+ rmSync(web, { recursive: true, force: true });+ renameSync(prevOf(web), web);+ }+ log(job, `Restored ${basename(bin)} ${job.from}`);+}++function runTar(archive: string, dest: string): void {+ // Same as the installer: refuse absolute paths and `..` in the archive.+ const list = execFileSync('tar', ['-tzf', archive], { encoding: 'utf-8' });+ if (list.split('\n').some((l) => l.startsWith('/') || l.split('/').includes('..'))) throw new Error('The web dashboard archive has unsafe paths.');+ execFileSync('tar', ['-xzf', archive, '-C', dest]);+}++async function installNpm(job: UpdateJob, version: string): Promise<void> {+ const spec = `${NPM_PACKAGE}@${version}`;+ try {+ await run('npm', ['i', '-g', spec], job);+ } catch (err) {+ // A half-removed package dir makes npm fail with ENOTEMPTY; clear it and try once more.+ if (/ENOTEMPTY/.test(String((err as { output?: string }).output ?? err)) && job.packageDir) {+ log(job, 'Clearing a leftover package folder and retrying');+ rmSync(job.packageDir, { recursive: true, force: true });+ await run('npm', ['i', '-g', spec], job);+ return;+ }+ throw err;+ }+}diff --git a/src/updates/status.ts b/src/updates/status.tsnew file mode 100644index 00000000..93a36a96--- /dev/null+++ b/src/updates/status.ts@@ -0,0 +1,124 @@+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { fetchLatestVersion } from '../cli/latest-version.js';+import { fetchLatestFromRegistry } from '../cli/update-notice.js';+import { detectInstall, NPM_PACKAGE, type InstallInfo } from './install-kind.js';+import { compareVersions, getManifest, latestFor, messagesFor, readManifestCache, requiredFor, MANIFEST_TTL_MS, type ManifestCache, type ManifestMessage, type MinimumVersion } from './manifest.js';+import { blockedFor, justUpdated, markJustUpdatedSeen, readJob, updatesHome, type UpdateJob } from './server-updater.js';++/**+ * What GET /api/updates says (docs/updates.md §2): this server's version,+ * the newest one, whether it must update, and how an update is going.+ */++export interface LatestRelease {+ version: string;+ date?: string;+ notes?: string;+ notesUrl?: string;+ /** False when the last try found the release isn't published yet. */+ downloadable?: boolean;+}++export interface ServerUpdateStatus {+ current: string;+ channel: 'stable' | 'dev';+ install: InstallInfo['kind'];+ canSelfUpdate: boolean;+ cannotReason?: string;+ latest: LatestRelease | null;+ updateAvailable: boolean;+ required: { version: string; severity: MinimumVersion['severity']; reason: string } | null;+ manifestVerified: boolean;+ checkedAt: number | null;+ job: UpdateJob | null;+ blocked: { version: string; failures: number; lastError: string } | null;+ justUpdated: { from: string; to: string; at: number } | null;+ messages: ManifestMessage[];+}++const RELEASES = 'https://github.com/cosmicstack-labs/mercury-agent/releases';++// The plain look-up when there's no signed manifest: GitHub (binary, dev) or npm.+interface Fallback { version: string | null; checkedAt: number }+const fallbackPath = () => join(updatesHome(), 'fallback.json');++function readFallback(): Fallback | null {+ try { return existsSync(fallbackPath()) ? JSON.parse(readFileSync(fallbackPath(), 'utf-8')) as Fallback : null; } catch { return null; }+}++async function fallbackLatest(install: InstallInfo, force: boolean, now: number): Promise<Fallback> {+ const cached = readFallback();+ if (cached && !force && now - cached.checkedAt < MANIFEST_TTL_MS) return cached;+ const version = install.kind === 'npm' && install.channel === 'stable'+ ? await fetchLatestFromRegistry(NPM_PACKAGE)+ : await fetchLatestVersion(install.channel);+ const next = { version: version ?? cached?.version ?? null, checkedAt: now };+ try { mkdirSync(updatesHome(), { recursive: true }); writeFileSync(fallbackPath(), JSON.stringify(next)); } catch { /* best effort */ }+ return next;+}++let refreshing: Promise<unknown> | null = null;++export interface StatusOptions {+ current: string;+ /** "Check for updates": refetch now (the manifest rate-limits itself). */+ force?: boolean;+ /** The client showed "what's new": stop reporting justUpdated. */+ seen?: boolean;+ install?: InstallInfo;+ now?: number;+}++export async function serverUpdateStatus(opts: StatusOptions): Promise<ServerUpdateStatus> {+ const now = opts.now ?? Date.now();+ const install = opts.install ?? detectInstall(opts.current);++ // A stale cache answers now and refreshes behind; only a first-ever check waits.+ let cache: ManifestCache = readManifestCache();+ const stale = cache.checkedAt === null || now - cache.checkedAt >= MANIFEST_TTL_MS;+ if (opts.force || cache.checkedAt === null) {+ cache = await getManifest({ force: opts.force });+ } else if (stale && !refreshing) {+ refreshing = getManifest().finally(() => { refreshing = null; });+ }++ const manifest = cache.manifest;+ let latest: LatestRelease | null = latestFor(manifest, 'server', install.channel);+ let checkedAt = cache.checkedAt;+ if (!latest) {+ const fb = await fallbackLatest(install, !!opts.force, now);+ checkedAt = fb.checkedAt;+ if (fb.version) latest = { version: fb.version, notesUrl: install.channel === 'dev' ? `${RELEASES}/tag/mercury-dev-latest` : `${RELEASES}/tag/v${fb.version}` };+ }++ const job = readJob();+ if (latest && job?.notAvailable && job.to === latest.version && now - job.updatedAt < 60 * 60_000) latest = { ...latest, downloadable: false };++ const updateAvailable = !!latest && compareVersions(latest.version, opts.current) > 0;+ const req = requiredFor(manifest, 'server', opts.current);+ const just = justUpdated(opts.current);+ if (just && opts.seen) markJustUpdatedSeen();++ return {+ current: opts.current,+ channel: install.channel,+ install: install.kind,+ canSelfUpdate: install.canSelfUpdate,+ ...(install.cannotReason ? { cannotReason: install.cannotReason } : {}),+ latest,+ updateAvailable,+ required: req ? { version: req.version, severity: req.severity, reason: req.reason } : null,+ manifestVerified: !!manifest,+ checkedAt,+ job,+ blocked: updateAvailable ? blockedFor(latest?.version) : null,+ justUpdated: just,+ messages: messagesFor(manifest, 'server', opts.current, now),+ };+}++/** The version an update should go to: the newest known one, if newer. */+export function targetVersion(status: ServerUpdateStatus): string | null {+ return status.updateAvailable && status.latest ? status.latest.version : null;+}diff --git a/src/updates/updates.test.ts b/src/updates/updates.test.tsnew file mode 100644index 00000000..c84f5b13--- /dev/null+++ b/src/updates/updates.test.ts@@ -0,0 +1,433 @@+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { createHash, generateKeyPairSync, randomBytes, sign as edSign } from 'node:crypto';+import { createServer, type Server } from 'node:http';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { AddressInfo } from 'node:net';+import { verifyMinisign } from './minisign.js';+import { UPDATE_PUBLIC_KEY } from './public-key.js';+import { compareVersions, getManifest, messagesFor, parseManifest, requiredFor, verifyManifest, versionMatches, type UpdateManifest } from './manifest.js';+import { downloadResumable, NotAvailableError, parseChecksums } from './download.js';+import { backupConfig, blockedFor, installBinary, restoreBinary, cancelServerUpdate, clearFailures, justUpdated, markJustUpdatedSeen, readJob, readUpdateState, reconcileUpdateJob, runUpdateWorker, startServerUpdate, type PrepareSteps, type UpdateJob, type WorkerSteps } from './server-updater.js';+import { detectInstall, type InstallInfo } from './install-kind.js';+import { startupNotices, updatesLine } from './notices.js';+import type { ServerUpdateStatus } from './status.js';++const ROOT = join(__dirname, '..', '..');+const previousHome = process.env.MERCURY_HOME;+let home = '';++beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), 'mercury-updates-'));+ process.env.MERCURY_HOME = home;+});+afterEach(() => { rmSync(home, { recursive: true, force: true }); });+afterAll(() => { if (previousHome === undefined) delete process.env.MERCURY_HOME; else process.env.MERCURY_HOME = previousHome; });++// ─── A minisign signer for tests (the format `tauri signer` writes) ─────────++function testKey() {+ const { publicKey, privateKey } = generateKeyPairSync('ed25519');+ const raw = Buffer.from(publicKey.export({ format: 'jwk' }).x!, 'base64url');+ const keyId = randomBytes(8);+ const pub = Buffer.from(`untrusted comment: minisign public key\n${Buffer.concat([Buffer.from('Ed'), keyId, raw]).toString('base64')}\n`).toString('base64');+ const signFn = (data: string | Buffer) => {+ const bytes = Buffer.isBuffer(data) ? data : Buffer.from(data);+ const sig = edSign(null, createHash('blake2b512').update(bytes).digest(), privateKey);+ const trusted = 'timestamp:1793683429\tfile:manifest.json';+ const global = edSign(null, Buffer.concat([sig, Buffer.from(trusted)]), privateKey);+ const text = `untrusted comment: test\n${Buffer.concat([Buffer.from('ED'), keyId, sig]).toString('base64')}\ntrusted comment: ${trusted}\n${global.toString('base64')}\n`;+ return Buffer.from(text).toString('base64');+ };+ return { pub, sign: signFn };+}++describe('minisign', () => {+ it('verifies a signature made by `tauri signer sign`, and refuses changed data or another key', () => {+ const dir = join(__dirname, 'fixtures');+ const data = readFileSync(join(dir, 'fixture.json'));+ const sig = readFileSync(join(dir, 'fixture.json.sig'), 'utf8');+ const pub = readFileSync(join(dir, 'throwaway.pub'), 'utf8');+ expect(verifyMinisign(data, sig, pub)).toMatchObject({ ok: true });+ expect(verifyMinisign(Buffer.concat([data, Buffer.from(' ')]), sig, pub)).toMatchObject({ ok: false, reason: /does not match/ });+ expect(verifyMinisign(data, sig, UPDATE_PUBLIC_KEY)).toMatchObject({ ok: false, reason: /different key/ });+ });++ it('refuses a swapped trusted comment', () => {+ const k = testKey();+ const sig = Buffer.from(k.sign('hello'), 'base64').toString().replace('file:manifest.json', 'file:other.json');+ expect(verifyMinisign('hello', Buffer.from(sig).toString('base64'), k.pub)).toMatchObject({ ok: false, reason: /comment/ });+ });++ it('the published manifest verifies with Mercury\'s key', () => {+ const text = readFileSync(join(ROOT, 'website', 'static', 'updates', 'manifest.json'), 'utf8');+ const sig = readFileSync(join(ROOT, 'website', 'static', 'updates', 'manifest.json.sig'), 'utf8');+ const v = verifyManifest(text, sig);+ expect('manifest' in v && v.manifest.schema).toBe(1);+ });++ it('the runtime and the desktop app trust the same key', () => {+ const conf = JSON.parse(readFileSync(join(ROOT, 'apps', 'desktop', 'src-tauri', 'tauri.conf.json'), 'utf8'));+ expect(conf.plugins.updater.pubkey).toBe(UPDATE_PUBLIC_KEY);+ });+});++// ─── Versions and messages ───────────────────────────────────────────────────++describe('versions', () => {+ it('compares numerically, a dev build after its release', () => {+ expect(compareVersions('1.10.0', '1.9.9')).toBe(1);+ expect(compareVersions('v1.4.2', '1.4.2')).toBe(0);+ expect(compareVersions('1.4.2-dev.20261103.abc', '1.4.2')).toBe(1);+ expect(compareVersions('1.4.1', '1.4.2')).toBe(-1);+ });++ it('reads ranges; an unreadable range matches nobody', () => {+ expect(versionMatches('1.4.2', '<1.5.0')).toBe(true);+ expect(versionMatches('1.5.0', '<1.5.0')).toBe(false);+ expect(versionMatches('1.4.2', '>=1.4 <1.5')).toBe(true);+ expect(versionMatches('1.4.2', '=1.4.2')).toBe(true);+ expect(versionMatches('1.4.2', '')).toBe(true);+ expect(versionMatches('1.4.2', 'soon')).toBe(false);+ });++ const manifest = parseManifest(JSON.stringify({+ schema: 1, issuedAt: '2026-11-03T00:00:00Z',+ server: { channels: { stable: { version: '1.5.0' } }, minimum: { version: '1.4.2', severity: 'security', reason: 'Fixes a hole.' } },+ messages: [+ { id: 'a', title: 'For old servers', level: 'warning', apps: ['server'], versions: '<1.5.0' },+ { id: 'b', title: 'Desktop only', apps: ['desktop'] },+ { id: 'c', title: 'Later', startsAt: '2027-01-01T00:00:00Z' },+ { id: 'd', title: 'Over', endsAt: '2026-01-01T00:00:00Z' },+ { id: 'e', title: 'Sticky', level: 'info', dismissible: false },+ { id: 'f', title: 'Bad link', link: { url: 'javascript:alert(1)' } },+ ],+ }))!;++ it('says who must update', () => {+ expect(requiredFor(manifest, 'server', '1.4.1')).toMatchObject({ version: '1.4.2', severity: 'security' });+ expect(requiredFor(manifest, 'server', '1.4.2')).toBeNull();+ expect(requiredFor(manifest, 'desktop', '0.0.1')).toBeNull();+ });++ it('picks the messages for an app, version and time; only critical ones may refuse dismissal; links must be https', () => {+ const now = Date.parse('2026-11-03T12:00:00Z');+ expect(messagesFor(manifest, 'server', '1.4.2', now).map((m) => m.id)).toEqual(['a', 'e', 'f']);+ expect(messagesFor(manifest, 'server', '1.5.0', now).map((m) => m.id)).toEqual(['e', 'f']);+ expect(messagesFor(manifest, 'desktop', '0.1.0', now).map((m) => m.id)).toEqual(['b', 'e', 'f']);+ expect(manifest.messages!.find((m) => m.id === 'e')!.dismissible).toBe(true);+ expect(manifest.messages!.find((m) => m.id === 'f')!.link).toBeNull();+ });+});++// ─── Fetching the manifest ───────────────────────────────────────────────────++describe('getManifest', () => {+ const key = testKey();+ const make = (issuedAt: string, version = '1.5.0'): string => JSON.stringify({ schema: 1, issuedAt, server: { channels: { stable: { version } } } } satisfies Partial<UpdateManifest>);+ function fetchFrom(files: Record<string, string | number>) {+ return vi.fn(async (url: string | URL | Request) => {+ const v = files[String(url)];+ if (v === undefined || typeof v === 'number') return new Response('no', { status: typeof v === 'number' ? v : 404 });+ return new Response(v, { status: 200 });+ }) as unknown as typeof fetch;+ }+ const urls = ['https://a.test/m.json', 'https://b.test/m.json'];++ it('accepts a signed manifest and caches it for six hours', async () => {+ const text = make('2026-11-03T00:00:00Z');+ const f = fetchFrom({ [urls[0]]: text, [`${urls[0]}.sig`]: key.sign(text) });+ const c = await getManifest({ fetchImpl: f, urls, publicKey: key.pub, now: 1_000 });+ expect(c.manifest?.server?.channels?.stable?.version).toBe('1.5.0');+ await getManifest({ fetchImpl: f, urls, publicKey: key.pub, now: 1_000 + 60_000 });+ expect(f).toHaveBeenCalledTimes(2); // the file and its signature, once+ });++ it('ignores an unsigned or forged manifest, and uses the mirror when the first address fails', async () => {+ const text = make('2026-11-03T00:00:00Z');+ const forged = make('2026-11-03T00:00:00Z', '9.9.9');+ const f = fetchFrom({ [urls[0]]: forged, [`${urls[0]}.sig`]: key.sign(text), [urls[1]]: text, [`${urls[1]}.sig`]: key.sign(text) });+ const c = await getManifest({ fetchImpl: f, urls, publicKey: key.pub, now: 1_000 });+ expect(c.manifest?.server?.channels?.stable?.version).toBe('1.5.0');++ const none = await getManifest({ fetchImpl: fetchFrom({ [urls[0]]: forged, [`${urls[0]}.sig`]: key.sign(text) }), urls: [urls[0]], publicKey: key.pub, force: true, now: 1_000 + 120_000 });+ expect(none.manifest?.server?.channels?.stable?.version).toBe('1.5.0'); // the last good one stays+ expect(none.error).toMatch(/not signed/);+ });++ it('refuses to go back to an older manifest (replay)', async () => {+ const newer = make('2026-11-05T00:00:00Z', '1.6.0');+ const older = make('2026-11-01T00:00:00Z', '1.5.0');+ await getManifest({ fetchImpl: fetchFrom({ [urls[0]]: newer, [`${urls[0]}.sig`]: key.sign(newer) }), urls, publicKey: key.pub, now: 1 });+ const c = await getManifest({ fetchImpl: fetchFrom({ [urls[0]]: older, [`${urls[0]}.sig`]: key.sign(older) }), urls: [urls[0]], publicKey: key.pub, force: true, now: 1 + 120_000 });+ expect(c.manifest?.server?.channels?.stable?.version).toBe('1.6.0');+ expect(c.error).toMatch(/older/);+ });++ it('fails open offline, and limits forced checks to one a minute', async () => {+ const down = vi.fn(async () => { throw new Error('offline'); }) as unknown as typeof fetch;+ const c = await getManifest({ fetchImpl: down, urls, publicKey: key.pub, force: true, now: 10_000 });+ expect(c.manifest).toBeNull();+ const calls = (down as unknown as { mock: { calls: unknown[] } }).mock.calls.length;+ await getManifest({ fetchImpl: down, urls, publicKey: key.pub, force: true, now: 20_000 });+ expect((down as unknown as { mock: { calls: unknown[] } }).mock.calls.length).toBe(calls);+ });+});++// ─── Resumable downloads ─────────────────────────────────────────────────────++describe('downloadResumable', () => {+ const body = randomBytes(300_000);+ const sha = createHash('sha256').update(body).digest('hex');+ let server: Server;+ let base = '';+ let requests: Array<{ range?: string; ifRange?: string }> = [];+ let cutFirst = true;+ let etag = '"v1"';++ beforeEach(async () => {+ requests = []; cutFirst = true; etag = '"v1"';+ server = createServer((req, res) => {+ if (req.url === '/missing') { res.writeHead(404); res.end(); return; }+ requests.push({ range: req.headers.range, ifRange: req.headers['if-range'] as string | undefined });+ const m = /bytes=(\d+)-/.exec(req.headers.range ?? '');+ const honour = m && (!req.headers['if-range'] || req.headers['if-range'] === etag);+ const start = honour ? Number(m![1]) : 0;+ const chunk = body.subarray(start);+ res.writeHead(honour ? 206 : 200, { 'content-length': String(chunk.length), etag, 'accept-ranges': 'bytes' });+ if (cutFirst) {+ cutFirst = false;+ res.write(chunk.subarray(0, 100_000), () => res.destroy());+ return;+ }+ res.end(chunk);+ });+ await new Promise<void>((r) => server.listen(0, '127.0.0.1', r));+ base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+ });+ afterEach(() => new Promise<void>((r) => server.close(() => r())));++ it('picks up where a dropped connection stopped, and checks the result', async () => {+ const dest = join(home, 'file.bin');+ const seen: number[] = [];+ const got = await downloadResumable(`${base}/file`, dest, { expectedSha256: sha, backoffMs: () => 1, onProgress: (p) => seen.push(p.bytes) });+ expect(got).toBe(sha);+ expect(readFileSync(dest).equals(body)).toBe(true);+ expect(requests[1].range).toMatch(/^bytes=\d+-$/);+ expect(Number(/bytes=(\d+)-/.exec(requests[1].range!)![1])).toBeGreaterThan(0);+ expect(requests[1].ifRange).toBe('"v1"');+ expect(seen.at(-1)).toBe(body.length);+ expect(existsSync(`${dest}.part`)).toBe(false);+ });++ it('starts over when the file changed in between (If-Range)', async () => {+ const dest = join(home, 'file.bin');+ // A first try that leaves a .part, then the file changes on the server.+ await expect(downloadResumable(`${base}/file`, dest, { expectedSha256: sha, retries: 0 })).rejects.toThrow();+ expect(existsSync(`${dest}.part`)).toBe(true);+ etag = '"v2"';+ await downloadResumable(`${base}/file`, dest, { expectedSha256: sha, backoffMs: () => 1 });+ expect(readFileSync(dest).equals(body)).toBe(true);+ });++ it('says "not available" for a missing file instead of retrying', async () => {+ await expect(downloadResumable(`${base}/missing`, join(home, 'x'), { backoffMs: () => 1 })).rejects.toBeInstanceOf(NotAvailableError);+ });++ it('reads checksums.txt', () => {+ const m = parseChecksums(`${'a'.repeat(64)} mercury-macos-arm64\n${'b'.repeat(64)} *web.tar.gz\n`);+ expect(m.get('mercury-macos-arm64')).toBe('a'.repeat(64));+ expect(m.get('web.tar.gz')).toBe('b'.repeat(64));+ });+});++// ─── The update job ──────────────────────────────────────────────────────────++const INSTALL: InstallInfo = { kind: 'binary', channel: 'stable', canSelfUpdate: true, binaryPath: '/tmp/mercury-test-bin' };++function worker(over: Partial<WorkerSteps> = {}): WorkerSteps & { calls: string[] } {+ const calls: string[] = [];+ return {+ calls,+ stop: async () => { calls.push('stop'); return true; },+ install: async () => { calls.push('install'); },+ start: async () => { calls.push('start'); },+ health: async (v) => { calls.push(`health ${v}`); return true; },+ restore: async () => { calls.push('restore'); },+ ...over,+ };+}++function prep(w: WorkerSteps, over: Partial<PrepareSteps> = {}): Partial<PrepareSteps> {+ return {+ busy: () => null,+ download: async (_job, onProgress) => { onProgress({ bytes: 50, total: 100 }); onProgress({ bytes: 100, total: 100 }); },+ backup: async () => {},+ handOver: async (job: UpdateJob) => { await runUpdateWorker(job.id, w, 50); return process.pid; },+ ...over,+ };+}++async function update(w: WorkerSteps, over: Partial<PrepareSteps> = {}, to = '1.5.0') {+ const r = startServerUpdate({ current: '1.4.2', to, install: INSTALL, steps: prep(w, over), idleWaitMs: 2000 });+ if (!r.ok) throw new Error(r.error);+ await r.done;+ return readJob()!;+}++describe('server update job', () => {+ it('downloads, hands over, installs, starts and checks; then says what\'s new once', async () => {+ const w = worker();+ const job = await update(w);+ expect(job.state).toBe('done');+ expect(job.percent).toBe(100);+ expect(w.calls).toEqual(['stop', 'install', 'start', 'health 1.5.0']);+ expect(justUpdated('1.5.0')).toMatchObject({ from: '1.4.2', to: '1.5.0' });+ markJustUpdatedSeen();+ expect(justUpdated('1.5.0')).toBeNull();+ });++ it('goes back to the old version when the new one doesn\'t answer, and counts the failure', async () => {+ const w = worker({ health: async (v) => { w.calls.push(`health ${v}`); return v === '1.4.2'; } });+ const job = await update(w);+ expect(job.state).toBe('rolled-back');+ expect(job.message).toMatch(/went back to 1\.4\.2/);+ expect(w.calls).toEqual(['stop', 'install', 'start', 'health 1.5.0', 'stop', 'restore', 'start', 'health 1.4.2']);+ expect(readUpdateState().failures['1.5.0'].count).toBe(1);+ });++ it('goes back when installing throws', async () => {+ const w = worker({ install: async () => { throw new Error('disk full'); } });+ const job = await update(w);+ expect(job.state).toBe('rolled-back');+ expect(job.error).toBe('disk full');+ });++ it('stops offering a version after three failures; trying by hand starts the count over', async () => {+ const bad = () => worker({ health: async (v) => v === '1.4.2' });+ for (let i = 0; i < 3; i++) await update(bad());+ expect(blockedFor('1.5.0')).toMatchObject({ failures: 3 });+ clearFailures('1.5.0');+ expect(blockedFor('1.5.0')).toBeNull();+ });++ it('a release that isn\'t published yet is "not available", not a failure, and nothing is stopped', async () => {+ const w = worker();+ const job = await update(w, { download: async () => { throw new NotAvailableError('404'); } });+ expect(job.state).toBe('failed');+ expect(job.notAvailable).toBe(true);+ expect(job.message).toMatch(/isn't downloadable yet/);+ expect(w.calls).toEqual([]);+ expect(readUpdateState().failures['1.5.0']).toBeUndefined();+ });++ it('waits for running work, can be cancelled before anything stops, and refuses a second update meanwhile', async () => {+ const w = worker();+ const r = startServerUpdate({ current: '1.4.2', to: '1.5.0', install: INSTALL, steps: prep(w, { busy: () => 'a reply' }), idleWaitMs: 60_000 });+ if (!r.ok) throw new Error(r.error);+ await new Promise((res) => setTimeout(res, 50));+ expect(readJob()!.message).toBe('Waiting for a reply to finish');+ const again = startServerUpdate({ current: '1.4.2', to: '1.5.0', install: INSTALL, steps: prep(w) });+ expect(again).toMatchObject({ ok: false, status: 409 });+ expect(cancelServerUpdate().ok).toBe(true);+ await r.done;+ expect(readJob()!.state).toBe('cancelled');+ expect(w.calls).toEqual([]);+ });++ it('refuses installs that can\'t update themselves', () => {+ const r = startServerUpdate({ current: '1.4.2', to: '1.5.0', install: { kind: 'source', channel: 'stable', canSelfUpdate: false, cannotReason: 'git pull' } });+ expect(r).toMatchObject({ ok: false, status: 400, error: 'git pull' });+ });++ it('at start-up, settles a job its worker left behind', () => {+ const base: UpdateJob = { id: 'j', from: '1.4.2', to: '1.5.0', state: 'checking', percent: 92, message: '', startedAt: 1, updatedAt: 1, log: [], attempt: 1, install: 'binary', channel: 'stable', workerPid: 999_999 };+ mkdirSync(join(home, 'updates'), { recursive: true });+ writeFileSync(join(home, 'updates', 'job.json'), JSON.stringify(base));+ reconcileUpdateJob('1.5.0');+ expect(readJob()!.state).toBe('done');+ writeFileSync(join(home, 'updates', 'job.json'), JSON.stringify({ ...base, state: 'installing' }));+ reconcileUpdateJob('1.4.2');+ expect(readJob()!.state).toBe('failed');+ writeFileSync(join(home, 'updates', 'job.json'), JSON.stringify({ ...base, state: 'downloading' }));+ reconcileUpdateJob('1.4.2');+ expect(readJob()!.state).toBe('cancelled');+ });++ it('swaps the binary and dashboard in, keeping the old ones beside them, and puts them back', () => {+ const bin = join(home, 'bin'); mkdirSync(join(bin, 'web'), { recursive: true });+ writeFileSync(join(bin, 'mercury'), 'old'); writeFileSync(join(bin, 'web', 'index.html'), 'old web');+ const dl = join(home, 'dl'); mkdirSync(join(dl, 'src', 'web'), { recursive: true });+ writeFileSync(join(dl, 'mercury-new'), 'new'); writeFileSync(join(dl, 'src', 'web', 'index.html'), 'new web');+ execFileSync('tar', ['-czf', join(dl, 'web.tar.gz'), '-C', join(dl, 'src'), 'web']);+ const job = { id: 'b', from: '1.4.2', to: '1.5.0', state: 'installing', percent: 78, message: '', startedAt: 1, updatedAt: 1, log: [], attempt: 1, install: 'binary', channel: 'stable', binaryPath: join(bin, 'mercury'), files: { binary: join(dl, 'mercury-new'), web: join(dl, 'web.tar.gz'), asset: 'mercury-new' } } satisfies UpdateJob;+ installBinary(job);+ expect(readFileSync(join(bin, 'mercury'), 'utf8')).toBe('new');+ expect(readFileSync(join(bin, 'mercury.prev'), 'utf8')).toBe('old');+ expect(readFileSync(join(bin, 'web', 'index.html'), 'utf8')).toBe('new web');+ expect(readFileSync(join(bin, 'web.prev', 'index.html'), 'utf8')).toBe('old web');+ restoreBinary(job);+ expect(readFileSync(join(bin, 'mercury'), 'utf8')).toBe('old');+ expect(readFileSync(join(bin, 'web', 'index.html'), 'utf8')).toBe('old web');+ });++ it('backs up settings files only', () => {+ writeFileSync(join(home, 'mercury.yaml'), 'a: 1');+ writeFileSync(join(home, '.env'), 'K=1');+ writeFileSync(join(home, 'remote.json'), '{}');+ writeFileSync(join(home, 'queue.db'), 'x');+ mkdirSync(join(home, 'memory'));+ expect(backupConfig('1.4.2', home)).toBe(3);+ expect(existsSync(join(home, 'updates', 'backup', '1.4.2', 'queue.db'))).toBe(false);+ });+});++// ─── Install kinds and notices ───────────────────────────────────────────────++describe('install kind', () => {+ it('tells a binary, a global npm install, a source checkout and a project install apart', () => {+ expect(detectInstall('1.4.2', { standalone: true, execPath: '/Users/a/.mercury/bin/mercury' })).toMatchObject({ kind: 'binary', canSelfUpdate: true, binaryPath: '/Users/a/.mercury/bin/mercury' });+ expect(detectInstall('1.4.2', { standalone: false, script: '/usr/local/lib/node_modules/@cosmicstack/mercury-agent/dist/index.js' })).toMatchObject({ kind: 'npm', packageDir: '/usr/local/lib/node_modules/@cosmicstack/mercury-agent' });+ expect(detectInstall('1.4.2', { standalone: false, script: join(ROOT, 'dist', 'index.js') })).toMatchObject({ kind: 'source', canSelfUpdate: false });+ expect(detectInstall('1.4.2', { standalone: false, script: '/srv/app/node_modules/@cosmicstack/mercury-agent/dist/index.js' })).toMatchObject({ kind: 'unknown', canSelfUpdate: false });+ expect(detectInstall('1.4.2-dev.20261103.abc', { standalone: true }).channel).toBe('dev');+ });+});++describe('notices', () => {+ const status = (over: Partial<ServerUpdateStatus>): ServerUpdateStatus => ({+ current: '1.4.2', channel: 'stable', install: 'binary', canSelfUpdate: true, latest: { version: '1.5.0' }, updateAvailable: true,+ required: null, manifestVerified: true, checkedAt: 1, job: null, blocked: null, justUpdated: null, messages: [], ...over,+ });++ it('an available update can be ignored; a required one can\'t', () => {+ expect(startupNotices(status({}), undefined, new Set()).notices[0]).toMatch(/Update available/);+ expect(startupNotices(status({}), '1.5.0', new Set()).notices).toEqual([]);+ const req = startupNotices(status({ required: { version: '1.4.3', severity: 'security', reason: 'Fixes a hole.' } }), '1.5.0', new Set());+ expect(req.notices[0]).toMatch(/Update required \(security\)/);+ expect(req.badge).toBe('1.5.0');+ });++ it('a blocked version isn\'t offered on its own', () => {+ expect(startupNotices(status({ blocked: { version: '1.5.0', failures: 3, lastError: 'x' } }), undefined, new Set()).notices).toEqual([]);+ });++ it('shows each message once, a sticky critical one every time', () => {+ const messages = [+ { id: 'm1', title: 'Hello', level: 'info' as const, dismissible: true },+ { id: 'm2', title: 'Patch now', level: 'critical' as const, dismissible: false },+ ];+ const first = startupNotices(status({ updateAvailable: false, messages }), undefined, new Set());+ expect(first.notices).toHaveLength(2);+ expect(first.shown).toEqual(['m1']);+ expect(startupNotices(status({ updateAvailable: false, messages }), undefined, new Set(['m1'])).notices).toHaveLength(1);+ });++ it('doctor\'s line', () => {+ expect(updatesLine(status({ updateAvailable: false })).text).toMatch(/up to date/);+ expect(updatesLine(status({})).level).toBe('note');+ expect(updatesLine(status({ required: { version: '1.4.3', severity: 'required', reason: 'Old.' } })).level).toBe('risk');+ });+});diff --git a/src/web/api-contract.ts b/src/web/api-contract.tsindex 1a359e64..90762cc1 100644--- a/src/web/api-contract.ts+++ b/src/web/api-contract.ts@@ -55,6 +55,7 @@ export const API_FEATURES: readonly string[] = Object.freeze(['artifacts.folder', // GET /api/artifacts/folder (the output folder, loose files), POST /api/artifacts/folder/tidy'chat.favicon', // GET /api/chat/favicon?domain= — a site's icon (204 when it has none), fetched and cached by the runtime'security.remote', // device pairing needs the owner (202 + POST /api/auth/token/pending), sensitive remote actions 428 + X-Mercury-Approval, /api/security/* (this computer), SSE 'owner_approval' (local activity), expired devices 401 { expired }+ 'updates', // GET /api/updates[?seen=1], POST /api/updates/check, POST /api/updates/server { version?, now? } (202; remote → 428 owner), POST /api/updates/server/cancel — see docs/updates.md'chat.research', // SSE 'research' / 'research_plan' / 'research_plan_resolved' / 'notice'; GET /api/chat/threads/:id/research, POST …/research/finish, …/research/off, POST /api/chat/research/plan/:id; message.research; step_done { failed, reason }]);diff --git a/src/web/api/status.ts b/src/web/api/status.tsindex 6d7e5e66..8131c5d3 100644--- a/src/web/api/status.ts+++ b/src/web/api/status.ts@@ -44,7 +44,8 @@ export function getStatus(): AgentStatus {const status = new Hono();let runtimeVersion = '';-function versionString(): string {+/** The running Mercury's version (for display and the updater). */+export function versionString(): string {if (runtimeVersion) return runtimeVersion;try {// tsup bakes the version into the bundle (globalThis.__MERCURY_VERSION__);diff --git a/src/web/api/updates-route.test.ts b/src/web/api/updates-route.test.tsnew file mode 100644index 00000000..085d85fd--- /dev/null+++ b/src/web/api/updates-route.test.ts@@ -0,0 +1,117 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { Hono } from 'hono';++/**+ * Updating this Mercury from an app: anyone signed in sees the status; this+ * computer starts an update at once; another device waits for the owner.+ */++const status = {+ current: '1.4.2', channel: 'stable', install: 'binary', canSelfUpdate: true,+ latest: { version: '1.5.0', notes: 'New things' }, updateAvailable: true, required: null,+ manifestVerified: true, checkedAt: 1, job: null, blocked: null, justUpdated: null, messages: [],+};+const serverUpdateStatus = vi.fn(async (opts: unknown) => ({ ...status, ...(opts ? {} : {}) }));+vi.mock('../../updates/status.js', () => ({+ serverUpdateStatus: (o: unknown) => serverUpdateStatus(o),+ targetVersion: (s: typeof status) => (s.updateAvailable && s.latest ? s.latest.version : null),+}));+vi.mock('./status.js', () => ({ versionString: () => '1.4.2' }));+vi.mock('../../updates/install-kind.js', () => ({ detectInstall: () => ({ kind: 'binary', channel: 'stable', canSelfUpdate: true }) }));++const job = { id: 'j1', from: '1.4.2', to: '1.5.0', state: 'waiting-idle', percent: 0, message: 'Waiting', startedAt: 1, updatedAt: 1, log: [], attempt: 1, install: 'binary', channel: 'stable' };+const startServerUpdate = vi.fn();+const cancelServerUpdate = vi.fn();+vi.mock('../../updates/server-updater.js', () => ({+ startServerUpdate: (o: unknown) => startServerUpdate(o),+ cancelServerUpdate: () => cancelServerUpdate(),+}));++const LOCAL = { incoming: { socket: { remoteAddress: '127.0.0.1' } } };+const LAN = { incoming: { socket: { remoteAddress: '192.168.1.20' } } };+let home = '';+const previous = process.env.MERCURY_HOME;++beforeEach(async () => {+ home = mkdtempSync(join(tmpdir(), 'mercury-upd-route-'));+ process.env.MERCURY_HOME = home;+ const { OwnerApprovals, _setOwnerApprovals } = await import('../../security/owner-approvals.js');+ _setOwnerApprovals(new OwnerApprovals());+ startServerUpdate.mockReset();+ startServerUpdate.mockReturnValue({ ok: true, job, done: Promise.resolve() });+ serverUpdateStatus.mockClear();+});+afterEach(() => {+ if (previous === undefined) delete process.env.MERCURY_HOME; else process.env.MERCURY_HOME = previous;+ rmSync(home, { recursive: true, force: true });+});++async function app() {+ const { authGuard } = await import('../middleware.js');+ const { default: updates } = await import('./updates.js');+ const a = new Hono();+ a.use('*', authGuard);+ a.route('/', updates);+ return a;+}++async function phone() {+ const { createDevice, _resetDeviceState } = await import('../devices.js');+ _resetDeviceState();+ return createDevice('Phone', 'ios');+}++describe('/api/updates', () => {+ it('a signed-in device sees the status; "seen" is passed on', async () => {+ const a = await app();+ const p = await phone();+ const res = await a.request('http://127.0.0.1/api/updates?seen=1', { headers: { Authorization: `Bearer ${p.token}` } }, LAN);+ expect(res.status).toBe(200);+ expect(await res.json()).toMatchObject({ current: '1.4.2', latest: { version: '1.5.0' } });+ expect(serverUpdateStatus).toHaveBeenCalledWith(expect.objectContaining({ seen: true }));+ expect((await a.request('http://127.0.0.1/api/updates', {}, LAN)).status).toBe(401);+ });++ it('this computer starts an update: 202 with the job', async () => {+ const a = await app();+ const { readAttachToken, writeAttachToken } = await import('../auth.js');+ writeAttachToken();+ const token = readAttachToken();+ const res = await a.request('http://127.0.0.1/api/updates/server', { method: 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ now: true }) }, LOCAL);+ expect(res.status).toBe(202);+ expect(await res.json()).toMatchObject({ job: { id: 'j1', to: '1.5.0' } });+ expect(startServerUpdate).toHaveBeenCalledWith(expect.objectContaining({ current: '1.4.2', to: '1.5.0', now: true, manual: true }));+ });++ it('another device waits for the owner (428), then may start it once', async () => {+ const a = await app();+ const p = await phone();+ const auth = { Authorization: `Bearer ${p.token}`, 'Content-Type': 'application/json' };+ const first = await a.request('http://127.0.0.1/api/updates/server', { method: 'POST', headers: auth, body: '{}' }, LAN);+ expect(first.status).toBe(428);+ const ask = (await first.json()) as { approvalId: string; code: string };+ expect(startServerUpdate).not.toHaveBeenCalled();+ const { ownerApprovals } = await import('../../security/owner-approvals.js');+ ownerApprovals().decide(ask.code, 'allow', 'telegram');+ const ok = await a.request('http://127.0.0.1/api/updates/server', { method: 'POST', headers: { ...auth, 'X-Mercury-Approval': ask.approvalId }, body: '{}' }, LAN);+ expect(ok.status).toBe(202);+ });++ it('409 while an update runs; 400 when already current or for another version', async () => {+ const a = await app();+ const { readAttachToken, writeAttachToken } = await import('../auth.js');+ writeAttachToken();+ const token = readAttachToken();+ const post = (body: unknown) => a.request('http://127.0.0.1/api/updates/server', { method: 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify(body) }, LOCAL);+ startServerUpdate.mockReturnValue({ ok: false, status: 409, error: 'An update is already running.', job });+ const busy = await post({});+ expect(busy.status).toBe(409);+ expect(await busy.json()).toMatchObject({ job: { id: 'j1' } });+ expect((await post({ version: '9.9.9' })).status).toBe(400);+ serverUpdateStatus.mockResolvedValueOnce({ ...status, updateAvailable: false });+ expect(await (await post({})).json()).toMatchObject({ upToDate: true });+ });+});diff --git a/src/web/api/updates.ts b/src/web/api/updates.tsnew file mode 100644index 00000000..8edb8b11--- /dev/null+++ b/src/web/api/updates.ts@@ -0,0 +1,68 @@+import { Hono } from 'hono';+import { isThisComputer, principalLabel, principalOf } from '../middleware.js';+import { requireOwner } from '../owner-gate.js';+import { versionString } from './status.js';+import { audit } from '../../security/audit.js';+import { serverUpdateStatus, targetVersion } from '../../updates/status.js';+import { cancelServerUpdate, startServerUpdate, type UpdateJob } from '../../updates/server-updater.js';+import { compareVersions } from '../../updates/manifest.js';+import { detectInstall } from '../../updates/install-kind.js';++/**+ * Updating this Mercury (docs/updates.md §2):+ *+ * GET /api/updates[?seen=1] version, newest, required, the job+ * POST /api/updates/check the same, checked again now (rate limited)+ * POST /api/updates/server { version?, now? } → 202 { job }; a remote device asks the owner first+ * POST /api/updates/server/cancel only before the old version is stopped+ *+ * Anyone signed in can see the status; updating from another device needs+ * the owner's yes, like a restart.+ */++const updates = new Hono();+let lastCheck = 0;++updates.get('/api/updates', async (c) => {+ return c.json(await serverUpdateStatus({ current: versionString(), seen: c.req.query('seen') === '1' }));+});++updates.post('/api/updates/check', async (c) => {+ const force = Date.now() - lastCheck >= 60_000;+ if (force) lastCheck = Date.now();+ return c.json(await serverUpdateStatus({ current: versionString(), force }));+});++updates.post('/api/updates/server', async (c) => {+ const body = (await c.req.json().catch(() => ({}))) as { version?: unknown; now?: unknown };+ const current = versionString();+ const status = await serverUpdateStatus({ current });+ const requested = typeof body.version === 'string' && /^\d+\.\d+\.\d+([.+-][\w.-]+)?$/.test(body.version.replace(/^v/, '')) ? body.version.replace(/^v/, '') : null;+ // Only forward, and only to a version we know about: the newest one.+ const to = requested ?? targetVersion(status);+ if (!to) return c.json({ error: `Mercury ${current} is already the newest version.`, upToDate: true }, 400);+ if (compareVersions(to, current) <= 0) return c.json({ error: `${to} isn't newer than ${current}.` }, 400);+ if (status.latest && to !== status.latest.version) return c.json({ error: `Only the newest version (${status.latest.version}) can be installed.` }, 400);++ if (!isThisComputer(c)) {+ const wait = requireOwner(c, { id: 'server.update', title: `Update Mercury to ${to}`, detail: `From ${current}. Mercury restarts on its own (about a minute) and goes back if the new version doesn't start.` });+ if (wait) return wait;+ }+ const started = startServerUpdate({ current, to, install: detectInstall(current), now: body.now === true, manual: true });+ if (!started.ok) return c.json({ error: started.error, ...(started.job ? { job: started.job } : {}) }, started.status);+ started.done.catch(() => {});+ audit('update.started', { who: isThisComputer(c) ? 'this computer' : principalLabel(principalOf(c)), detail: `${current} → ${to}` });+ return c.json({ job: started.job satisfies UpdateJob }, 202);+});++updates.post('/api/updates/server/cancel', (c) => {+ if (!isThisComputer(c)) {+ const wait = requireOwner(c, { id: 'server.update.cancel', title: 'Cancel the Mercury update' });+ if (wait) return wait;+ }+ const r = cancelServerUpdate();+ if (!r.ok) return c.json({ error: r.error, ...(r.job ? { job: r.job } : {}) }, 409);+ return c.json({ ok: true, job: r.job });+});++export default updates;diff --git a/src/web/server.ts b/src/web/server.tsindex f70ffd6c..8efae9a8 100644--- a/src/web/server.ts+++ b/src/web/server.ts@@ -33,6 +33,7 @@ import pluginRoutes from './api/plugins.js';import voiceRoutes from './api/voice.js';import deviceRoutes from './api/devices.js';import securityRoutes from './api/security.js';+import updatesRoutes from './api/updates.js';import { bodyLimit } from 'hono/body-limit';import { migrateDevices } from './devices.js';import { BoardManager } from '../core/board-manager.js';@@ -136,6 +137,7 @@ app.route('/', pluginRoutes);app.route('/', voiceRoutes);app.route('/', deviceRoutes);app.route('/', securityRoutes);+app.route('/', updatesRoutes);// ── Legacy static assets (vendor fonts, icons, wasm — still needed by React SPA) ──app.get('/vendor/*', (c) => {