diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c3ffab..a5fba39 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,26 @@ This file records user-visible changes to the BoxCompute CLI. GitHub Releases use the same notes and bind them to the exact source commit. +## [0.11.0] - 2026-10-15 + +Show early maintenance warnings without making every command noisy. + +### CLI users + +- Interactive commands show the active maintenance window, status and expected + Sandbox impact at most once per local day. JSON and piped commands stay clean. +- `bxc maintenance` shows the current notice on demand. Run + `bxc maintenance dismiss` to hide that revision; a changed status or window + is a new revision and appears again. +- Update with `bxc update` or + `npm install --global @boxcompute/cli@latest` after rollout. + +### Security + +- Notices are bounded public text from the unauthenticated same-origin metadata + endpoint. The CLI sends no credential, follows no redirect, and stores only + notice IDs and local display dates in its owner-only configuration directory. + ## [0.10.0] - 2026-10-10 Read remaining credits and wallet history without opening the web app. diff --git a/package.json b/package.json index cd9413f..cb38370 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@boxcompute/cli", - "version": "0.10.0", + "version": "0.11.0", "description": "Connect local AI agents to BoxCompute sandboxes", "keywords": [ "boxcompute", diff --git a/src/cli.ts b/src/cli.ts index 169c1ad..dee4aec 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -48,6 +48,12 @@ import { runProxy } from "./proxy.js"; import { runSsh } from "./ssh.js"; import { cooperativeConnectionApi } from "./cooperative-connection.js"; import { resumeSandbox } from "./resume.js"; +import { + dismissMaintenanceNotice, + fetchMaintenanceNotice, + formatMaintenanceNotice, + maintenanceMotd, +} from "./maintenance.js"; const DEFAULT_URL = "https://app.boxcompute.ai"; const CLI_VERSION = (JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version: string }).version; @@ -68,6 +74,7 @@ Commands: credits Show remaining credit, settled spending and pending costs billing Show credits or page wallet transactions usage Show activity counts for the last 1–90 days + maintenance Show or dismiss the current maintenance notice workspaces List workspaces that can own sandboxes sandboxes [aliases: list, ls] List sandbox instances sandbox Manage isolated BoxCompute sandboxes @@ -357,6 +364,7 @@ type DeviceAuthorization = { export type CliDependencies = { env?: NodeJS.ProcessEnv; io?: Io; + interactive?: boolean; fetch?: typeof fetch; now?: () => number; sleep?: (milliseconds: number) => Promise; @@ -969,6 +977,27 @@ export async function runCli(argv: string[], supplied: CliDependencies = {}): Pr return proxy(args[0]!, streamIo); } + if (command === "maintenance") { + const action = args.shift() ?? "show"; + if (args.length || (action !== "show" && action !== "dismiss")) { + throw new UsageError("maintenance accepts `show` or `dismiss`"); + } + const url = await savedUrl(env) ?? DEFAULT_URL; + const notice = await fetchMaintenanceNotice(url, fetchImpl, AbortSignal.timeout(5_000)); + if (action === "dismiss" && notice) await dismissMaintenanceNotice(notice, env); + emit( + io, + json, + { maintenance: notice, dismissed: action === "dismiss" && notice !== null }, + notice + ? action === "dismiss" + ? `Dismissed maintenance notice ${notice.id} revision ${notice.revision}. A changed update will be shown again.\n` + : formatMaintenanceNotice(notice) + : "No active maintenance notice.\n", + ); + return 0; + } + const canAutoSync = supplied.syncManagedSkills !== undefined || supplied.env === undefined || Boolean(env.HOME || env.USERPROFILE); if (command !== "skill" && canAutoSync) { @@ -1095,6 +1124,11 @@ export async function runCli(argv: string[], supplied: CliDependencies = {}): Pr if (command === "deleted" && !args.length) args.push("list"); const connection = await load(env); + const interactive = supplied.interactive ?? Boolean((io.stderr as NodeJS.WriteStream).isTTY); + if (interactive && !json) { + const motd = await maintenanceMotd({ baseUrl: connection.url, fetch: fetchImpl, env, now: now() }); + if (motd) write(io.stderr, motd); + } const client = createClient(connection, fetchImpl); if (command === "doctor") { const sandboxes = await client.sandboxes.list(); diff --git a/src/maintenance.ts b/src/maintenance.ts new file mode 100644 index 0000000..5943a88 --- /dev/null +++ b/src/maintenance.ts @@ -0,0 +1,158 @@ +import { randomUUID } from "node:crypto"; +import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { connectionPaths } from "./config.js"; + +export type MaintenanceNotice = { + id: string; + revision: number; + kind: "planned" | "urgent"; + status: "scheduled" | "in_progress" | "completed" | "cancelled"; + startsAt: string; + endsAt: string; + impact: string; +}; + +type NoticeState = { + shown: Array<{ key: string; day: string }>; + dismissed: string[]; +}; + +const EMPTY_STATE: NoticeState = { shown: [], dismissed: [] }; +const MAX_STATE_ENTRIES = 32; +const NOTICE_KEYS = ["endsAt", "id", "impact", "kind", "revision", "startsAt", "status"]; +const RFC3339 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/; + +export const maintenanceKey = (notice: MaintenanceNotice) => `${notice.id}:${notice.revision}`; + +const hasControlCharacter = (value: string) => + [...value].some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127); + +function validNotice(value: unknown): value is MaintenanceNotice { + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const notice = value as Record; + return Object.keys(notice).sort().join(",") === NOTICE_KEYS.join(",") + && typeof notice.id === "string" && notice.id.length <= 80 + && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(notice.id) + && Number.isSafeInteger(notice.revision) && (notice.revision as number) > 0 + && (notice.kind === "planned" || notice.kind === "urgent") + && ["scheduled", "in_progress", "completed", "cancelled"].includes(String(notice.status)) + && typeof notice.startsAt === "string" && RFC3339.test(notice.startsAt) + && Number.isFinite(Date.parse(notice.startsAt)) + && typeof notice.endsAt === "string" && RFC3339.test(notice.endsAt) + && Date.parse(notice.endsAt) > Date.parse(notice.startsAt) + && typeof notice.impact === "string" && notice.impact.trim() === notice.impact + && notice.impact.length > 0 && notice.impact.length <= 500 + && !hasControlCharacter(notice.impact); +} + +export async function fetchMaintenanceNotice( + baseUrl: string, + fetchImpl: typeof fetch, + signal?: AbortSignal, +): Promise { + const response = await fetchImpl(new URL("/api/meta", baseUrl), { + headers: { accept: "application/json" }, + redirect: "error", + signal, + }); + if (!response.ok) throw new Error(`Maintenance notice request failed (HTTP ${response.status})`); + const body = await response.json() as { maintenance?: unknown }; + if (body.maintenance === null || body.maintenance === undefined) return null; + if (!validNotice(body.maintenance)) throw new Error("BoxCompute returned an invalid maintenance notice"); + return body.maintenance; +} + +function statePath(env: NodeJS.ProcessEnv): string { + return path.join(connectionPaths(env).directory, "maintenance-notices.json"); +} + +async function readState(env: NodeJS.ProcessEnv): Promise { + try { + const value = JSON.parse(await readFile(statePath(env), "utf8")) as Partial; + return { + shown: Array.isArray(value.shown) + ? value.shown.filter((item): item is { key: string; day: string } => + Boolean(item) && typeof item.key === "string" && typeof item.day === "string").slice(-MAX_STATE_ENTRIES) + : [], + dismissed: Array.isArray(value.dismissed) + ? value.dismissed.filter((item): item is string => typeof item === "string").slice(-MAX_STATE_ENTRIES) + : [], + }; + } catch { + return { ...EMPTY_STATE }; + } +} + +async function writeState(env: NodeJS.ProcessEnv, state: NoticeState): Promise { + const paths = connectionPaths(env); + await mkdir(paths.directory, { recursive: true, mode: 0o700 }); + await chmod(paths.directory, 0o700); + const destination = statePath(env); + const temporary = `${destination}.${randomUUID()}.tmp`; + try { + await writeFile(temporary, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600, flag: "wx" }); + await rename(temporary, destination); + await chmod(destination, 0o600); + } finally { + await rm(temporary, { force: true }).catch(() => undefined); + } +} + +function localDay(now: number): string { + const date = new Date(now); + const part = (value: number) => String(value).padStart(2, "0"); + return `${date.getFullYear()}-${part(date.getMonth() + 1)}-${part(date.getDate())}`; +} + +const statusLabel: Record = { + scheduled: "Scheduled", + in_progress: "In progress", + completed: "Completed", + cancelled: "Cancelled", +}; + +export function formatMaintenanceNotice(notice: MaintenanceNotice, dismissHint = true): string { + const formatter = new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeStyle: "short" }); + const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; + const settled = notice.status === "completed" || notice.status === "cancelled"; + const title = notice.kind === "urgent" ? "URGENT MAINTENANCE" : "PLANNED MAINTENANCE"; + return [ + `\n${title} · ${statusLabel[notice.status]}`, + `Window: ${formatter.format(new Date(notice.startsAt))} – ${formatter.format(new Date(notice.endsAt))}${timezone ? ` (${timezone})` : ""}`, + `Expected impact: ${notice.impact}`, + ...(!settled ? [notice.status === "in_progress" ? "Save your work now." : "Save your work before the window begins."] : []), + ...(dismissHint ? ["Run `bxc maintenance dismiss` to hide this update."] : []), + "", + ].join("\n"); +} + +/** Return today's MOTD once per revision, or null when it is dismissed, already shown, or unavailable. */ +export async function maintenanceMotd(options: { + baseUrl: string; + fetch: typeof fetch; + env: NodeJS.ProcessEnv; + now: number; +}): Promise { + try { + const notice = await fetchMaintenanceNotice(options.baseUrl, options.fetch, AbortSignal.timeout(1_200)); + if (!notice) return null; + const state = await readState(options.env); + const key = maintenanceKey(notice); + const day = localDay(options.now); + if (state.dismissed.includes(key) || state.shown.some((item) => item.key === key && item.day === day)) return null; + state.shown = [...state.shown.filter((item) => item.key !== key), { key, day }].slice(-MAX_STATE_ENTRIES); + await writeState(options.env, state); + return formatMaintenanceNotice(notice); + } catch { + // A best-effort MOTD must never delay or break the command the user asked for. + return null; + } +} + +export async function dismissMaintenanceNotice(notice: MaintenanceNotice, env: NodeJS.ProcessEnv): Promise { + const state = await readState(env); + const key = maintenanceKey(notice); + state.dismissed = [...state.dismissed.filter((item) => item !== key), key].slice(-MAX_STATE_ENTRIES); + await writeState(env, state); +} diff --git a/test/maintenance.test.ts b/test/maintenance.test.ts new file mode 100644 index 0000000..3d0015c --- /dev/null +++ b/test/maintenance.test.ts @@ -0,0 +1,130 @@ +import { mkdtemp, readFile, rm, stat } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { PassThrough } from "node:stream"; +import { afterEach, describe, expect, it } from "bun:test"; +import { runCli } from "../src/cli.js"; +import { fetchMaintenanceNotice, type MaintenanceNotice } from "../src/maintenance.js"; + +const roots: string[] = []; +const notice = { + id: "core-host-2026-10-20", + revision: 1, + kind: "planned", + status: "scheduled", + startsAt: "2026-10-20T01:00:00Z", + endsAt: "2026-10-20T02:30:00Z", + impact: "Running Sandboxes may sleep and reconnect. Files are preserved.", +} as const; + +const streams = () => ({ stdout: new PassThrough(), stderr: new PassThrough() }); +function output(stream: PassThrough): string { + let value = "", chunk: Buffer | null; + while ((chunk = stream.read() as Buffer | null) !== null) value += chunk.toString(); + return value; +} + +async function fixture() { + const root = await mkdtemp(path.join(tmpdir(), "bxc-maintenance-")); + roots.push(root); + return { BOXCOMPUTE_CONFIG_DIR: root }; +} + +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); +}); + +describe("maintenance notice", () => { + it("prints an interactive MOTD once per local day and reappears for a new revision", async () => { + const env = await fixture(); + let active: MaintenanceNotice = notice; + const fetch = (async (input: string | URL | Request) => { + const url = new URL(String(input)); + if (url.pathname === "/api/meta") return Response.json({ maintenance: active }); + if (url.pathname === "/api/v2/sandboxes") return Response.json({ sandboxes: [] }); + throw new Error(`unexpected ${url}`); + }) as typeof globalThis.fetch; + const run = async (now: number) => { + const io = streams(); + expect(await runCli(["sandboxes"], { + io, env, fetch, now: () => now, interactive: true, + syncManagedSkills: async () => [], + loadConnection: async () => ({ url: "https://app.boxcompute.ai", token: "bc_live_test", tokenFile: "/credential" }), + })).toBe(0); + return output(io.stderr); + }; + + const day = Date.parse("2026-10-15T09:00:00Z"); + expect(await run(day)).toContain("PLANNED MAINTENANCE · Scheduled"); + expect(await run(day + 60_000)).toBe(""); + expect(await run(day + 86_400_000)).toContain("PLANNED MAINTENANCE"); + active = { ...notice, revision: 2, kind: "urgent", status: "in_progress" }; + expect(await run(day + 86_400_001)).toContain("URGENT MAINTENANCE · In progress"); + + const state = path.join(env.BOXCOMPUTE_CONFIG_DIR, "maintenance-notices.json"); + expect((await stat(state)).mode & 0o777).toBe(0o600); + expect(await readFile(state, "utf8")).not.toContain(active.impact); + }); + + it("dismisses one revision, shows a changed revision, and keeps JSON output clean", async () => { + const env = await fixture(); + let active: MaintenanceNotice = notice; + const fetch = (async (input: string | URL | Request) => { + const url = new URL(String(input)); + if (url.pathname === "/api/meta") return Response.json({ maintenance: active }); + if (url.pathname === "/api/v2/sandboxes") return Response.json({ sandboxes: [] }); + throw new Error(`unexpected ${url}`); + }) as typeof globalThis.fetch; + const shared = { + env, fetch, now: () => Date.parse("2026-10-15T09:00:00Z"), interactive: true, + syncManagedSkills: async () => [], + loadConnection: async () => ({ url: "https://app.boxcompute.ai", token: "bc_live_test", tokenFile: "/credential" }), + loadSavedUrl: async () => "https://app.boxcompute.ai", + }; + const dismissed = streams(); + expect(await runCli(["maintenance", "dismiss"], { ...shared, io: dismissed })).toBe(0); + expect(output(dismissed.stdout)).toContain("Dismissed maintenance notice"); + + const hidden = streams(); + expect(await runCli(["sandboxes"], { ...shared, io: hidden })).toBe(0); + expect(output(hidden.stderr)).toBe(""); + active = { ...notice, revision: 2 }; + const changed = streams(); + expect(await runCli(["sandboxes"], { ...shared, io: changed })).toBe(0); + expect(output(changed.stderr)).toContain("PLANNED MAINTENANCE"); + + const json = streams(); + expect(await runCli(["--json", "sandboxes"], { ...shared, io: json })).toBe(0); + expect(output(json.stderr)).toBe(""); + expect(JSON.parse(output(json.stdout))).toEqual({ sandboxes: [] }); + }); + + it("never blocks a command when the optional MOTD request fails", async () => { + const io = streams(); + expect(await runCli(["sandboxes"], { + io, env: await fixture(), interactive: true, syncManagedSkills: async () => [], + loadConnection: async () => ({ url: "https://app.boxcompute.ai", token: "bc_live_test", tokenFile: "/credential" }), + fetch: (async (input: string | URL | Request) => { + const url = new URL(String(input)); + if (url.pathname === "/api/meta") throw new Error("offline"); + return Response.json({ sandboxes: [] }); + }) as typeof globalThis.fetch, + })).toBe(0); + expect(output(io.stdout)).toContain("No sandboxes found"); + expect(output(io.stderr)).toBe(""); + }); + + it("rejects notices outside the strict public contract", async () => { + for (const maintenance of [ + { ...notice, impact: "Sandboxes may restart.\u001b[2J" }, + { ...notice, startsAt: "2026-10-20 01:00:00Z" }, + { ...notice, extra: "unreviewed customer copy" }, + ]) { + const fetch = (async (_input: string | URL | Request) => + Response.json({ maintenance })) as typeof globalThis.fetch; + await expect(fetchMaintenanceNotice("https://app.boxcompute.ai", fetch)).rejects.toThrow( + "invalid maintenance notice", + ); + } + }); +});