diff --git a/README.md b/README.md index 47c9571..335483c 100644 --- a/README.md +++ b/README.md @@ -202,6 +202,15 @@ headlines describe the result without internal outcome names or numeric codes. `--json` retains the stable envelope, including `outcome` and `exit_code`. Color follows terminal detection and `NO_COLOR`; piped output stays plain. +Terminal help and version output can show a cached update notice. At most once per +24 hours, a background worker checks npm's public `latest` tag; the command never +waits for the network. A newly discovered version appears on the next run. Failed +checks are silent and cached for the same interval. JSON, piped output and CI skip +both the notice and check. Set `METERGRAPH_NO_UPDATE_CHECK=1` to disable them. +The cache is `$XDG_CACHE_HOME/metergraph/update.json` (default +`~/.cache/metergraph/update.json`), or `%LOCALAPPDATA%\Metergraph\Cache\update.json` +on Windows. The check sends no project data or credentials. + The [CLI reference](https://github.com/metergraph/cli/blob/main/docs/reference.md) covers every option, what each command reads and writes, and full JSON examples. @@ -265,7 +274,8 @@ Exit codes are stable. Changing one is a breaking change. Codes 10 to 18 are not ## Security and privacy - **No usage telemetry.** The CLI collects no analytics about how you use it. It talks - only to the Metergraph origin you point it at. + to the Metergraph origin you point it at. The optional update check contacts + npm's public registry for this package's release tags. - **Least access.** Sign in grants only the Metadata scope, `agent:metadata`. The CLI never requests Debug or Replay access, never falls back to broader access, and the read commands never read retained prompts, responses or other content, whichever credential @@ -288,7 +298,8 @@ Exit codes are stable. Changing one is a breaking change. Codes 10 to 18 are not Public pricing lookup/calculation use unauthenticated `POST` with metadata-only inputs. Fixed paths, no redirects followed, bounded response sizes and fixed timeouts. Mistyped arguments are never echoed, since - they may hold a secret. `--help`, `--version` and `skill` make no network requests. + they may hold a secret. `skill` makes no network requests. Help and version work offline; interactive + output may start the optional background update check described above. The [CLI reference](https://github.com/metergraph/cli/blob/main/docs/reference.md) states what each command does and does not do. Report vulnerabilities privately through diff --git a/docs/reference.md b/docs/reference.md index 26696d7..e2b633f 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -55,8 +55,17 @@ metergraph experiments start --workload ID --treatment SPEC [--treatment SPEC].. metergraph experiments get --id UUID [read options] [--json] ``` -`--help`, `--version` and the `skill` commands work offline and make no network -requests. `login`, `logout`, `setup`, `verify` and the read commands are not in the published `0.1.0` +`--help` and `--version` work offline. For terminal output only, they may show a +cached update notice on stderr and launch a background check of npm's public +`latest` tag. Checks, including failed attempts, are cached for 24 hours and have +a 1.5-second network deadline; the foreground command does not wait. First-run +results appear on the next invocation. No project data or credentials are sent. +JSON, piped output and CI skip this behavior. Set `METERGRAPH_NO_UPDATE_CHECK=1` +to disable it entirely. Cache location: `$XDG_CACHE_HOME/metergraph/update.json` +(default `~/.cache/metergraph/update.json`), or +`%LOCALAPPDATA%\Metergraph\Cache\update.json` on Windows. + +The `skill` commands work offline and make no network requests. `login`, `logout`, `setup`, `verify` and the read commands are not in the published `0.1.0` package. ### Exact trace verification diff --git a/src/cli.js b/src/cli.js index 805e40f..bf1a528 100644 --- a/src/cli.js +++ b/src/cli.js @@ -1,3 +1,4 @@ +import { maybeUpdateNotice } from "./update-notice.js"; import { runPricing } from "./pricing.js"; import { pricingText, pricingHtml } from "./pricing-output.js"; import { READ_COMMANDS, parseArgs } from "./args.js"; @@ -58,6 +59,7 @@ export async function main(argv, { stdout, stderr, stdin = null }) { if (json) stdout.write(toJsonLine(result)); else stderr.write(`Error: ${result.error.message}\n`); } + if (result.ok) maybeUpdateNotice({ command: result.command, json, stdout, stderr }); return result.exit_code; } diff --git a/src/update-notice.js b/src/update-notice.js new file mode 100644 index 0000000..e3f39a2 --- /dev/null +++ b/src/update-notice.js @@ -0,0 +1,159 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawn } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import { fileURLToPath } from "node:url"; +import { VERSION } from "./constants.js"; +import { createStyle } from "./style.js"; + +export const UPDATE_TTL_MS = 24 * 60 * 60 * 1000; +const WORKER = fileURLToPath(import.meta.url); +const TAGS_URL = "https://registry.npmjs.org/-/package/metergraph-cli/dist-tags"; +const STABLE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/; + +// Only stable versions from npm's latest tag can appear in terminal output. +function stableParts(version) { + if (typeof version !== "string" || version.length > 64 || !STABLE.test(version)) return null; + const parts = version.split(".").map(Number); + return parts.every(Number.isSafeInteger) ? parts : null; +} + +export function isNewer(latest, current) { + const target = stableParts(latest); + const match = typeof current === "string" && current.match(/^(\d+\.\d+\.\d+)(-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/); + const installed = match && stableParts(match[1]); + if (!target || !installed) return false; + for (let i = 0; i < 3; i++) { + if (target[i] !== installed[i]) return target[i] > installed[i]; + } + return Boolean(match[2]); +} + +export function updateCacheDir(env = process.env) { + if (process.platform === "win32") { + const base = env.LOCALAPPDATA && path.isAbsolute(env.LOCALAPPDATA) ? env.LOCALAPPDATA : path.join(os.homedir(), "AppData", "Local"); + return path.join(base, "Metergraph", "Cache"); + } + const base = env.XDG_CACHE_HOME && path.isAbsolute(env.XDG_CACHE_HOME) ? env.XDG_CACHE_HOME : path.join(os.homedir(), ".cache"); + return path.join(base, "metergraph"); +} + +function readCache(dir) { + let fd; + try { + fd = fs.openSync(path.join(dir, "update.json"), fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0)); + const stat = fs.fstatSync(fd); + if (!stat.isFile() || stat.size > 4096) return null; + const data = JSON.parse(fs.readFileSync(fd, "utf8")); + if (!Number.isSafeInteger(data.checked_at) || data.checked_at < 0) return null; + if (data.latest !== null && !stableParts(data.latest)) return null; + return data; + } catch { + return null; + } finally { + if (fd !== undefined) fs.closeSync(fd); + } +} + +function fresh(cache, now) { + return cache && cache.checked_at <= now && now - cache.checked_at < UPDATE_TTL_MS; +} + +function startRefresh() { + const child = spawn(process.execPath, [WORKER], { detached: true, stdio: "ignore", windowsHide: true }); + child.on("error", () => {}); + child.unref(); +} + +// The foreground only reads a tiny cache. A detached worker does all network +// work; the first successful refresh can produce a notice on the next run. +export function maybeUpdateNotice({ command, json, stdout, stderr }, { + env = process.env, current = VERSION, now = Date.now(), dir = updateCacheDir(env), refresh = startRefresh, +} = {}) { + try { + if (!["help", "version"].includes(command) || json || !stdout?.isTTY || !stderr?.isTTY + || env.METERGRAPH_NO_UPDATE_CHECK || (env.CI && !["0", "false"].includes(env.CI.toLowerCase()))) return; + const cache = readCache(dir); + if (!fresh(cache, now)) { + refresh(); + return; + } + if (isNewer(cache.latest, current)) { + const style = createStyle(stderr, env); + stderr.write(`\n${style.cyan(`Update available: ${current} → ${cache.latest}`)}\nRun npm install -g metergraph-cli@latest\n`); + } + } catch { + // Optional presentation must never change the command result. + } +} + +// Fixed public endpoint: no project settings, credentials, or configured npm +// registry are read. Bound the response, deadline and redirects independently. +export async function latestVersion(fetcher = fetch) { + const signal = AbortSignal.timeout(1500); + const response = await fetcher(TAGS_URL, { signal, redirect: "error", credentials: "omit", headers: { accept: "application/json" } }); + if (!response.ok) { + await response.body?.cancel(); + return null; + } + const reader = response.body.getReader(); + const chunks = []; + let size = 0; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > 4096) return null; + chunks.push(Buffer.from(value)); + } + const data = JSON.parse(Buffer.concat(chunks).toString("utf8")); + return stableParts(data.latest) ? data.latest : null; + } finally { + await reader.cancel(); + } +} + +function writeCache(dir, data) { + const temp = path.join(dir, `update-${randomUUID()}.tmp`); + try { + fs.writeFileSync(temp, JSON.stringify(data), { mode: 0o600, flag: "wx" }); + fs.renameSync(temp, path.join(dir, "update.json")); + } finally { + try { fs.unlinkSync(temp); } catch { /* Renamed or unwritable. */ } + } +} + +export async function refreshUpdateCache({ dir = updateCacheDir(), now = Date.now(), load = latestVersion } = {}) { + let locked = false; + const lock = path.join(dir, "update.lock"); + try { + fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); + if (!fs.lstatSync(dir).isDirectory()) return; + try { + fs.mkdirSync(lock, { mode: 0o700 }); + } catch { + // Recover a worker killed before cleanup, without removing live locks. + const stat = fs.lstatSync(lock); + if (!stat.isDirectory() || now - stat.mtimeMs < 60000) return; + fs.rmdirSync(lock); + fs.mkdirSync(lock, { mode: 0o700 }); + } + locked = true; + if (fresh(readCache(dir), now)) return; + // Failures are cached too: an offline terminal does not spawn a request on + // every help invocation. A successful refresh replaces this same record. + writeCache(dir, { checked_at: now, latest: null }); + const latest = await load(); + if (stableParts(latest)) writeCache(dir, { checked_at: now, latest }); + } catch { + // Missing network or an unwritable cache is not a CLI error. + } finally { + if (locked) { try { fs.rmdirSync(lock); } catch { /* Best effort. */ } } + } +} + +if (process.argv[1] && path.resolve(process.argv[1]) === WORKER) { + if (!process.env.METERGRAPH_NO_UPDATE_CHECK) await refreshUpdateCache(); +} diff --git a/test/package/pack.test.js b/test/package/pack.test.js index 6a37e21..0eb92f3 100644 --- a/test/package/pack.test.js +++ b/test/package/pack.test.js @@ -90,6 +90,7 @@ const EXPECTED_FILES = [ "src/trace-contract.js", "src/trace-open.js", "src/transport.js", + "src/update-notice.js", "src/usage-aggregates.js", "src/verify-output.js", "src/verify.js", diff --git a/test/update-notice.test.js b/test/update-notice.test.js new file mode 100644 index 0000000..6b7f79a --- /dev/null +++ b/test/update-notice.test.js @@ -0,0 +1,176 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { isNewer, latestVersion, maybeUpdateNotice, refreshUpdateCache, UPDATE_TTL_MS } from "../src/update-notice.js"; +import { main } from "../src/cli.js"; +import { VERSION } from "../src/constants.js"; + +const dirs = []; +function temp() { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cli-update-")); + dirs.push(dir); + return dir; +} +after(() => dirs.forEach(dir => fs.rmSync(dir, { recursive: true, force: true }))); +function stream(isTTY = true) { return { isTTY, text: "", write(s) { this.text += s; } }; } +function cache(dir, checked_at, latest) { fs.writeFileSync(path.join(dir, "update.json"), JSON.stringify({ checked_at, latest })); } + +test("version ordering handles numeric components and stable vs prerelease without printing arbitrary tags", () => { + for (const [latest, current, expected] of [ + ["0.10.0", "0.9.9", true], ["1.0.0", "0.99.99", true], ["0.2.4", "0.2.3", true], + ["0.2.3", "0.2.3", false], ["0.2.2", "0.2.3", false], ["0.2.3", "0.2.3-beta.1", true], + ["0.2.3", "0.2.3+build.1", false], ["0.2.4-next.1", "0.2.3", false], + ["\u001b[31m9.0.0", "0.2.3", false], ["01.2.3", "0.2.3", false], + ["999999999999999999999.0.0", "0.2.3", false], ["1.0.0", "unknown", false], + ]) assert.equal(isNewer(latest, current), expected); +}); + +test("fresh cache shows a notice only for newer versions and never refreshes", () => { + const dir = temp(); + const now = Date.now(); + let refreshes = 0; + for (const latest of ["0.2.4", "0.2.3", "0.2.2", null]) { + cache(dir, now, latest); + const stdout = stream(), stderr = stream(); + maybeUpdateNotice({ command: "help", json: false, stdout, stderr }, + { dir, now, current: "0.2.3", env: { NO_COLOR: "1" }, refresh: () => refreshes++ }); + assert.equal(stdout.text, ""); + if (latest === "0.2.4") assert.match(stderr.text, /Update available: 0.2.3 → 0.2.4\nRun npm install -g metergraph-cli@latest/); + else assert.equal(stderr.text, ""); + } + assert.equal(refreshes, 0); +}); + +test("missing, corrupt, expired and future caches schedule a refresh without awaiting it", () => { + const dir = temp(), now = Date.now(); + let refreshes = 0; + const stdout = stream(), stderr = stream(); + const show = () => maybeUpdateNotice({ command: "version", stdout, stderr }, + { dir, now, env: {}, refresh: () => { refreshes++; return new Promise(() => {}); } }); + show(); + fs.writeFileSync(path.join(dir, "update.json"), "invalid"); show(); + cache(dir, now - UPDATE_TTL_MS, "9.0.0"); show(); + cache(dir, now + 1000, "9.0.0"); show(); + assert.equal(refreshes, 4); + assert.equal(stderr.text, ""); +}); + +test("opt-out, CI, JSON, pipes and other commands neither print nor schedule network work", () => { + let refreshes = 0; + for (const override of [ + { env: { METERGRAPH_NO_UPDATE_CHECK: "1" } }, { env: { CI: "true" } }, { json: true }, + { stdout: stream(false) }, { stderr: stream(false) }, { command: "status" }, + ]) { + const args = { command: "help", stdout: stream(), stderr: stream(), ...override }; + maybeUpdateNotice(args, { dir: temp(), env: override.env ?? {}, refresh: () => refreshes++ }); + assert.equal(args.stderr.text, ""); + } + assert.equal(refreshes, 0); +}); + +test("successful and failed checks are cached for 24 hours; retries happen after expiry", async () => { + const dir = temp(), now = Date.now(); + let calls = 0; + const load = async () => { calls++; return "0.2.4"; }; + await refreshUpdateCache({ dir, now, load }); + await refreshUpdateCache({ dir, now: now + 1, load }); + assert.equal(calls, 1); + assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir, "update.json"))), { checked_at: now, latest: "0.2.4" }); + await refreshUpdateCache({ dir, now: now + UPDATE_TTL_MS, load: async () => { calls++; throw Error("offline"); } }); + await refreshUpdateCache({ dir, now: now + UPDATE_TTL_MS + 1, load }); + assert.equal(calls, 2); + assert.equal(JSON.parse(fs.readFileSync(path.join(dir, "update.json"))).latest, null); + await refreshUpdateCache({ dir, now: now + 2 * UPDATE_TTL_MS, load }); + assert.equal(calls, 3); +}); + +test("concurrent workers share a lock and stale locks recover", async () => { + const dir = temp(), now = Date.now(); + let release, calls = 0; + const first = refreshUpdateCache({ dir, now, load: () => { calls++; return new Promise(resolve => { release = resolve; }); } }); + await refreshUpdateCache({ dir, now, load: async () => { calls++; return "0.2.4"; } }); + assert.equal(calls, 1); + release("0.2.4"); await first; + const lock = path.join(dir, "update.lock"); + fs.mkdirSync(lock); + fs.utimesSync(lock, new Date(now - 61000), new Date(now - 61000)); + await refreshUpdateCache({ dir, now: now + UPDATE_TTL_MS, load: async () => "0.2.5" }); + assert.equal(JSON.parse(fs.readFileSync(path.join(dir, "update.json"))).latest, "0.2.5"); +}); + +test("the registry request is anonymous, bounded and rejects unsafe latest tags", async () => { + let request; + const load = data => latestVersion(async (url, options) => { + request = { url, options }; + return new Response(JSON.stringify(data)); + }); + assert.equal(await load({ latest: "0.2.4", next: "1.0.0-next.1" }), "0.2.4"); + assert.equal(request.url, "https://registry.npmjs.org/-/package/metergraph-cli/dist-tags"); + assert.equal(request.options.redirect, "error"); + assert.equal(request.options.credentials, "omit"); + assert.deepEqual(request.options.headers, { accept: "application/json" }); + assert.ok(request.options.signal instanceof AbortSignal); + for (const latest of ["9.0.0\nmalicious", "0.3.0-beta.1", "bad", null]) assert.equal(await load({ latest }), null); + assert.equal(await latestVersion(async () => new Response("x".repeat(4097))), null); + assert.equal(await latestVersion(async () => new Response("", { status: 503 })), null); + await assert.rejects(latestVersion(async () => new Response("not json"))); +}); + +test("main keeps version and JSON stdout stable while cached notices go only to terminal stderr", async () => { + const base = temp(); + const saved = { ...process.env }; + try { + process.env.XDG_CACHE_HOME = base; + process.env.LOCALAPPDATA = base; + process.env.CI = ""; + process.env.NO_COLOR = "1"; + delete process.env.METERGRAPH_NO_UPDATE_CHECK; + const dir = process.platform === "win32" ? path.join(base, "Metergraph", "Cache") : path.join(base, "metergraph"); + fs.mkdirSync(dir, { recursive: true }); cache(dir, Date.now(), "999.0.0"); + const stdout = stream(), stderr = stream(); + assert.equal(await main(["--version"], { stdout, stderr }), 0); + assert.equal(stdout.text, `${VERSION}\n`); + assert.match(stderr.text, /Update available:/); + for (const argv of [["--help", "--json"], ["--version", "--json"]]) { + const stdout = stream(), stderr = stream(); + assert.equal(await main(argv, { stdout, stderr }), 0); + assert.equal(JSON.parse(stdout.text).ok, true); + assert.equal(stderr.text, ""); + } + const piped = stream(false), quiet = stream(); + assert.equal(await main(["--version"], { stdout: piped, stderr: quiet }), 0); + assert.equal(piped.text, `${VERSION}\n`); assert.equal(quiet.text, ""); + } finally { + for (const name of ["XDG_CACHE_HOME", "LOCALAPPDATA", "CI", "NO_COLOR", "METERGRAPH_NO_UPDATE_CHECK"]) { + if (saved[name] === undefined) delete process.env[name]; else process.env[name] = saved[name]; + } + } +}); + +test("a stalled response is aborted and cached without surfacing an error", async () => { + const dir = temp(); + let aborted = false; + // Keep the test alive: AbortSignal.timeout deliberately does not keep Node up. + const keepAlive = setInterval(() => {}, 100); + try { + await refreshUpdateCache({ dir, load: () => latestVersion(async (_url, { signal }) => new Response(new ReadableStream({ + start(controller) { + signal.addEventListener("abort", () => { aborted = true; controller.error(signal.reason); }, { once: true }); + }, + }))) }); + assert.equal(aborted, true); + assert.equal(JSON.parse(fs.readFileSync(path.join(dir, "update.json"))).latest, null); + } finally { clearInterval(keepAlive); } +}); + +test("broken or unwritable cache paths fail silently without requesting npm", async () => { + const dir = temp(); + const file = path.join(dir, "not-a-directory"); + fs.writeFileSync(file, "leave alone"); + let calls = 0; + await refreshUpdateCache({ dir: file, load: async () => { calls++; return "9.0.0"; } }); + assert.equal(calls, 0); + assert.equal(fs.readFileSync(file, "utf8"), "leave alone"); +});