Public: anyone can read this; the crew can change it.
Stop and Delete a cloud machine or volume from the cost row, each confirmed only by typing its name #18187
Merged 14h 1m ago, live in production
scout/forge:scout/18182-stop-and-delete-a-cloud-machine-or-volum → main 0 commits fork 7 threads · 7 unresolved
- docs/design/areas/infra.md
- docs/features/cloud-end.md
- src/actions/cloud_end.ts
- src/core/event_audience.ts
- src/crew/conversation_ask.ts
- src/crew/conversation_confirm.ts
- src/http/infra_routes.ts
- src/http/mcp/tools/cloud_end.ts
- src/http/mcp/tools/index.ts
- src/http/mcp/tools/infra.ts
- src/tui/screens/cloud_end.ts
- src/web/pages/cloud_end.ts
- src/web/pages/cloud_tree.ts
- src/web/style/components.ts
- test/cloud-end.test.ts
- test/conversation-ask.test.ts
- test/conversation-confirm.test.ts
- test/delete-tier.test.ts
- test/mcp-cloud-cost.test.ts
- test/mcp-forge-protocol.test.ts
docs/design/areas/infra.md added +13
| @@ -0,0 +1,13 @@ | ||
| 1 | # Infrastructure | |
| 2 | ||
| 3 | The costliest table on `/infra` and a resource's own pane (`src/web/pages/cloud_tree.ts`) use the table component | |
| 4 | they already had. Ending a resource (#18182) adds one class. | |
| 5 | ||
| 6 | - `.row-ends` — Stop · Delete beside a cost row's name, on a machine or volume of a write-allowed account only: | |
| 7 | each is a plain link to that act's plan at `/infra/end/<act>/<path>`, and nothing runs from the row. The span | |
| 8 | is muted text, `white-space: nowrap`, its links alone in `--accent`. Where a pointer hovers | |
| 9 | (`(hover: hover) and (pointer: fine)`) it is transparent until its row is hovered or holds focus, so a dense | |
| 10 | table reads as names and figures; it never changes size, so the row never shifts. On touch, without hover, and | |
| 11 | without JavaScript it always shows, and its links stay in the tab order, each labelled "Plan to <act> <name>". | |
| 12 | The plan page itself is the confirm dialog's shape: Will, Cost now, Lost and Kept as `dl` rows, the name field | |
| 13 | and the danger button for Stop as for Delete. |
docs/features/cloud-end.md +3 −2
| @@ -5,10 +5,11 @@ row: Stop or delete a cloud resource | ||
| 5 | 5 | |
| 6 | 6 | # Stop or delete a machine or volume (#18102) |
| 7 | 7 | |
| 8 | On a machine's or a volume's page under /infra, an account the forge may write to offers **Stop…** (machines) and **Delete…**. Each opens a plan, in the same words on every door: what will stop or go, its cost now, what is lost (a volume's data, a machine's own disk and public address), and what is kept. A stop is one confirm; a delete asks for the resource's name typed back. A read-only account is offered neither, and the server refuses both with "read-only"; so is a resource that is a pinned forge's own machine or volume (end that forge instead), an attached volume, and a cloud whose driver has no such call. Every attempt, refused or done, writes a cloud audit row with who asked and the confirmed plan (Cloud accounts → Audit). | |
| 8 | On `/infra`'s costliest table (a Stop · Delete pair beside each row's name) and on a machine's or a volume's page, an account the forge may write to offers **Stop…** (machines) and **Delete…**. Each opens a plan, in the same words on every door: what will stop or go, its cost now, what is lost (a volume's data, a machine's own disk and public address), and what is kept. A stop deletes the machine and its own disk, so a stop and a delete each ask for the resource's name typed back. A read-only account is offered neither, and the server refuses both with "read-only", already when the plan is asked for (that refusal is audited then too); so is a resource that is a pinned forge's own machine or volume (end that forge instead), an attached volume, and a cloud whose driver has no such call. A plan can be confirmed for 30 minutes: its digest carries the time it was shown, keyed with the forge's per-boot secret (HMAC), so there is no store, a client cannot mint a fresh stamp for an old plan, and a restart expires every plan shown before it. The typed name, not the stamp, is what holds a stop or a delete. Every attempt, refused or done, writes a cloud audit row with who asked and the confirmed plan (Cloud accounts → Audit) and a `cloud.end` event (`ok: false` and `refused` when it was refused). | |
| 9 | 9 | |
| 10 | 10 | - **Web:** `/infra/end/<stop|delete>/<cloud>/<account>/<project>/<id>` (`src/web/pages/cloud_end.ts`, `src/http/infra_routes.ts`). |
| 11 | 11 | - **Terminal:** Cloud resources (`src/tui/screens/cloud_end.ts`): `x` plans a stop, `X` a delete, on the selected resource. |
| 12 | - **MCP:** `cloud_end` (`src/http/mcp/tools/cloud_end.ts`): `plan` an `act` on an `id` as `infra` `list` gives it, then `apply` with the plan's `digest` and the `name` typed back; an admin-scope token, and the forge's own agent never applies one. | |
| 12 | 13 | - **Rules:** `src/actions/cloud_end.ts`. A stopped machine is still billed by DigitalOcean, Hetzner and OVHcloud, and the plan says so. |
| 13 | - **MCP (#18103):** the `infra` tool's `cost` answers each cloud account against its ceiling and budget and the ten resources that cost most, each with the `id` the rest take (`src/actions/cloud_cost.ts`). `end` takes that `id` and `want: {act: stop|delete}` and returns the plan and its `digest`; the same call with `want.digest` (and a delete's `want.typed`, the resource's name) does it. From the forge's own agent that second call is held for the person's yes (`crew/conversation_confirm.ts`) and nothing reaches the cloud before it; a read-only account is refused by the same rules as the page. | |
| 14 | - **MCP (#18103):** the `infra` tool's `cost` answers each cloud account against its ceiling and budget and the ten resources that cost most, each with the `id` the rest take (`src/actions/cloud_cost.ts`). `end` takes that `id` and `want: {act: stop|delete}` and returns the plan and its `digest`; the same call with `want.digest` and `want.typed`, the resource's name (a stop's as a delete's), does it. From the forge's own agent that second call is held for the person's yes (`crew/conversation_confirm.ts`) and nothing reaches the cloud before it; a read-only account is refused by the same rules as the page. | |
| 14 | 15 | - **Terminal:** What the clouds cost (`src/tui/screens/cloudcost.ts`, palette, admins): the same account lines and the costliest resources. |
src/actions/cloud_end.ts +66 −19
| @@ -19,7 +19,7 @@ import { listPinned } from "../core/pinned.ts"; | ||
| 19 | 19 | import type { User } from "../core/users.ts"; |
| 20 | 20 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 21 | 21 | import { cloudResources } from "./infra.ts"; |
| 22 | import { admin, withCloud } from "./pinned.ts"; | |
| 22 | import { admin, type Who, withCloud } from "./pinned.ts"; | |
| 23 | 23 | |
| 24 | 24 | export interface EndLine { |
| 25 | 25 | readonly label: "Will" | "Cost now" | "Lost" | "Kept"; |
| @@ -82,33 +82,59 @@ const MACHINE_KEEPS = "These clouds bill a stopped machine for its disk and addr | ||
| 82 | 82 | * is called. |
| 83 | 83 | */ |
| 84 | 84 | export function planEnd(app: App, actor: User | undefined, act: EndAct, path: readonly string[]): Result<EndPlan, string> { |
| 85 | const planned = unaudited(app, actor, act, path); | |
| 86 | // A read-only account is refused when it is planned, and that refusal is audited then (#18182). | |
| 87 | const who = admin(actor); | |
| 88 | if (planned.ok && who.ok && planned.value.refusal === READ_ONLY) refused(app, who.value, planned.value, READ_ONLY); | |
| 89 | return planned; | |
| 90 | } | |
| 91 | ||
| 92 | /** The plan, unaudited: what both `planEnd` and `performEnd` read. */ | |
| 93 | function unaudited(app: App, actor: User | undefined, act: EndAct, path: readonly string[]): Result<EndPlan, string> { | |
| 85 | 94 | const who = admin(actor); |
| 86 | 95 | if (!who.ok) return who; |
| 87 | 96 | const view = cloudResources(app, actor, ""); |
| 88 | 97 | if (!view.ok) return view; |
| 89 | 98 | const r = nodeAt(view.value.whole, path)?.resource; |
| 90 | 99 | if (r === undefined) return err("No such resource."); |
| 91 | return ok(planOf(app, act, path, r)); | |
| 100 | return ok(planOf(app, act, path, r, Date.now())); | |
| 101 | } | |
| 102 | ||
| 103 | /** | |
| 104 | * One attempt's audit row: who, what, and the plan as it stood, with why it was refused if it was. | |
| 105 | */ | |
| 106 | const auditRow = (app: App, actor: Who, p: EndPlan, allowed: boolean, why = ""): void => | |
| 107 | recordAudit(app.db, { provider: p.provider, account: p.account, purpose: `${p.act}:${p.kind}`, target: `${p.kind}:${p.id}`.slice(0, 200), bytesOut: 0, allowed, actor: actor.id ?? "", plan: `${why}${planText(p)}` }); | |
| 108 | ||
| 109 | /** One attempt's `cloud.end` event; `refused` says why it did not run. */ | |
| 110 | const endEvent = (app: App, actor: Who, p: EndPlan, done: boolean, refused = ""): void => { | |
| 111 | app.bus.append({ kind: "cloud.end", actorId: actor.id, payload: { action: p.act, provider: p.provider, account: p.account, kind: p.kind, name: p.name, ok: done, ...(refused === "" ? {} : { refused }) } }); | |
| 112 | }; | |
| 113 | ||
| 114 | /** A refused attempt: its audit row and its event. */ | |
| 115 | function refused(app: App, actor: Who, p: EndPlan, why: string): void { | |
| 116 | auditRow(app, actor, p, false, `Refused: ${why} `); | |
| 117 | endEvent(app, actor, p, false, why); | |
| 92 | 118 | } |
| 93 | 119 | |
| 94 | 120 | /** |
| 95 | 121 | * What a resource's page offers: the acts its account lets the forge do, never one on a read-only |
| 96 | 122 | * account. |
| 97 | 123 | */ |
| 98 | export function offeredEnds(app: App, path: readonly string[], r: CloudResource | undefined): readonly { act: EndAct; href: string }[] { | |
| 99 | if (r === undefined || (r.kind !== "machine" && r.kind !== "volume") || getCloudAccount(app.db, r.provider, r.account)?.writeAllowed !== true) return []; | |
| 124 | export function offeredEnds(app: App, path: readonly string[], r: CloudResource | undefined, writable: (provider: string, account: string) => boolean = (p, a) => getCloudAccount(app.db, p, a)?.writeAllowed === true): readonly { act: EndAct; href: string }[] { | |
| 125 | if (r === undefined || (r.kind !== "machine" && r.kind !== "volume") || !writable(r.provider, r.account)) return []; | |
| 100 | 126 | if (endDriver(r.provider) === undefined) return []; |
| 101 | 127 | const acts: EndAct[] = r.kind === "machine" ? ["stop", "delete"] : ["delete"]; |
| 102 | 128 | return acts.map((act) => ({ act, href: `/infra/end/${act}/${path.map(encodeURIComponent).join("/")}` })); |
| 103 | 129 | } |
| 104 | 130 | |
| 105 | function planOf(app: App, act: EndAct, path: readonly string[], r: CloudResource): EndPlan { | |
| 131 | function planOf(app: App, act: EndAct, path: readonly string[], r: CloudResource, at: number): EndPlan { | |
| 106 | 132 | const kind = r.kind === "machine" || r.kind === "volume" ? r.kind : undefined; |
| 107 | 133 | const id = r.id.slice(r.id.indexOf(":") + 1); |
| 108 | 134 | const where = `${cloudName(r.provider)} / ${r.account}${r.region === "" ? "" : `, ${r.region}`}`; |
| 109 | 135 | const cost = r.cents === null ? "its cost is not known" : `${dollars(r.cents)} a month${r.costFrom === "billed" ? " billed" : " at list price"}`; |
| 110 | 136 | const base = { act, path, provider: r.provider, account: r.account, kind: kind ?? "machine", id, name: r.name, what: `${kind ?? r.kind} ${r.name} (${id}) on ${where}`, cost } as const; |
| 111 | const refuse = (refusal: string, lines: readonly EndLine[] = []): EndPlan => ({ ...base, lines, refusal, digest: digestOf(act, r.id, r.provider, r.account, lines) }); | |
| 137 | const refuse = (refusal: string, lines: readonly EndLine[] = []): EndPlan => ({ ...base, lines, refusal, digest: digestOf(app, at, act, r.id, r.provider, r.account, lines) }); | |
| 112 | 138 | |
| 113 | 139 | if (kind === undefined) return refuse(`The forge cannot ${act} a ${r.kind}: only machines and volumes.`); |
| 114 | 140 | const driver = endDriver(r.provider); |
| @@ -141,35 +167,55 @@ function planOf(app: App, act: EndAct, path: readonly string[], r: CloudResource | ||
| 141 | 167 | const held = listPinned(app.db).find((p) => p.target === r.provider && p.account === r.account && (p.remote === id || p.volume === id)); |
| 142 | 168 | if (held !== undefined) return refuse(`It is the ${kind} of the forge ${held.name}: end that forge from Infrastructure instead, so its row follows.`, lines); |
| 143 | 169 | if (act === "delete" && kind === "volume" && attached.length > 0) return refuse(`It is attached to ${attached.join(", ")}: delete that first, or the cloud refuses.`, lines); |
| 144 | return { ...base, lines, refusal: "", digest: digestOf(act, r.id, r.provider, r.account, lines) }; | |
| 170 | return { ...base, lines, refusal: "", digest: digestOf(app, at, act, r.id, r.provider, r.account, lines) }; | |
| 145 | 171 | } |
| 146 | 172 | |
| 147 | const digestOf = (act: string, id: string, provider: string, account: string, lines: readonly EndLine[]): string => | |
| 148 | new Bun.CryptoHasher("sha256").update(JSON.stringify([act, provider, account, id, lines])).digest("hex").slice(0, 16); | |
| 173 | /** How long a plan may be confirmed after it was shown. */ | |
| 174 | export const PLAN_MS = 30 * 60_000; | |
| 175 | ||
| 176 | /** | |
| 177 | * Keyed with the forge's per-boot secret, so a client cannot mint a fresh stamp for an old plan: | |
| 178 | * the expiry holds, and a restart expires every plan shown before it. The typed name stays the real | |
| 179 | * gate. | |
| 180 | */ | |
| 181 | const hashOf = (app: App, at: number, act: string, id: string, provider: string, account: string, lines: readonly EndLine[]): string => | |
| 182 | new Bun.CryptoHasher("sha256", `cloud-end\0${app.hookSecret}`).update(JSON.stringify([at, act, provider, account, id, lines])).digest("hex").slice(0, 32); | |
| 183 | ||
| 184 | /** `<time shown>.<mac>`: the stamp is inside the digest, so a plan expires without a store. */ | |
| 185 | const digestOf = (app: App, at: number, act: string, id: string, provider: string, account: string, lines: readonly EndLine[]): string => `${at}.${hashOf(app, at, act, id, provider, account, lines)}`; | |
| 186 | ||
| 187 | /** The stamp a digest carries, if it is one of ours. */ | |
| 188 | const stampOf = (digest: string): number => (/^\d{10,15}\./.test(digest) ? Number(digest.slice(0, digest.indexOf("."))) : 0); | |
| 149 | 189 | |
| 150 | 190 | /** The plan as one text: what the page shows and the audit row keeps. */ |
| 151 | 191 | export const planText = (p: EndPlan): string => p.lines.map((l) => `${l.label}: ${l.value}`).join(" "); |
The stamp comes from the client and the hash is unkeyed sha256, so the 30-minute expiry can be bypassed by minting a digest with the current time. The typed name is still the real gate, so this is not high severity. Either key the hash with a server secret (HMAC) or say in the docs that the expiry is a stale-page guard, not a security control. |
||
| 152 | 192 | |
| 153 | 193 | /** |
| 154 | * Do it. `digest` is the plan's, brought back by the confirm; a delete also needs the resource's | |
| 155 | * name typed back. Refused attempts are audited as refused, and an attempt is audited before the | |
| 156 | * cloud is called, so a failed call still leaves its row. | |
| 194 | * Do it. `digest` is the plan's, brought back by the confirm; a stop and a delete both need the | |
| 195 | * resource's name typed back (a stop deletes the machine and its own disk). Refused attempts (a | |
| 196 | * wrong name, an old plan, a read-only account) are audited as refused and write a `cloud.end` | |
| 197 | * event with `ok: false`, and an attempt is audited before the cloud is called, so a failed call | |
| 198 | * still leaves its row. | |
| 157 | 199 | */ |
| 158 | 200 | export async function performEnd(app: App, actor: User | undefined, act: EndAct, path: readonly string[], confirm: { digest: string; typed: string }): Promise<Result<string, string>> { |
| 159 | 201 | const who = admin(actor); |
| 160 | 202 | if (!who.ok) return who; |
| 161 | const planned = planEnd(app, actor, act, path); | |
| 203 | const planned = unaudited(app, actor, act, path); | |
| 162 | 204 | if (!planned.ok) return planned; |
| 163 | 205 | const p = planned.value; |
| 164 | const row = (allowed: boolean, why = ""): void => | |
| 165 | recordAudit(app.db, { provider: p.provider, account: p.account, purpose: `${act}:${p.kind}`, target: `${p.kind}:${p.id}`.slice(0, 200), bytesOut: 0, allowed, actor: who.value.id ?? "", plan: `${why}${planText(p)}` }); | |
| 166 | 206 | if (p.refusal !== "") { |
| 167 | row(false, `Refused: ${p.refusal} `); | |
| 207 | refused(app, who.value, p, p.refusal); | |
| 168 | 208 | return err(p.refusal); |
| 169 | 209 | } |
| 170 | if (confirm.digest !== p.digest) return err(`What ${p.name} is changed since it was planned: review the plan again.`); | |
| 171 | if (act === "delete" && confirm.typed.trim() !== p.name) return err(`Type ${p.name} to delete it: it cannot be undone.`); | |
| 172 | row(true); | |
| 210 | const at = stampOf(confirm.digest); | |
| 211 | const stale = at === 0 || Date.now() - at > PLAN_MS || Date.now() < at ? "That plan is more than 30 minutes old, or not one the forge showed: review the plan again." : confirm.digest !== digestOf(app, at, act, `${p.kind}:${p.id}`, p.provider, p.account, p.lines) ? `What ${p.name} is changed since it was planned: review the plan again.` : ""; | |
| 212 | const wrong = confirm.typed.trim() === p.name ? "" : `Type ${p.name} to ${act} it: ${act === "stop" ? "a stop deletes the machine and its own disk" : "it cannot be undone"}.`; | |
| 213 | if (stale !== "" || wrong !== "") { | |
| 214 | const why = stale !== "" ? stale : wrong; | |
| 215 | refused(app, who.value, p, why); | |
| 216 | return err(why); | |
| 217 | } | |
| 218 | auditRow(app, who.value, p, true); | |
| 173 | 219 | const d = endDriver(p.provider)!; |
| 174 | 220 | const done = await withCloud( |
| 175 | 221 | app, |
| @@ -183,6 +229,7 @@ export async function performEnd(app: App, actor: User | undefined, act: EndAct, | ||
| 183 | 229 | }, |
| 184 | 230 | false, |
| 185 | 231 | ); |
| 232 | endEvent(app, who.value, p, done.ok); | |
| 186 | 233 | if (!done.ok) return done; |
| 187 | 234 | return ok(act === "stop" ? `Stopping ${p.name}: it shows as stopped at the next read.` : `Deleted ${p.name}. It shows until the next read.`); |
| 188 | 235 | } |
src/core/event_audience.ts +3
| @@ -338,6 +338,9 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 338 | 338 | kind === "cloud.budget_notice" || |
| 339 | 339 | // An admin acknowledging a resource as not the forge's (`cloud/watch.ts`, #16329). |
| 340 | 340 | kind === "cloud.watch_acknowledged" || |
| 341 | // An admin stopping or deleting a cloud machine or volume names the owner's account | |
| 342 | // (`actions/cloud_end.ts`, #18182). | |
| 343 | kind === "cloud.end" || | |
| 341 | 344 | kind === "cloud.project" || |
| 342 | 345 | // How many prepared machines a plan keeps waiting is a spend choice (`cloud/warm_pool.ts`, |
| 343 | 346 | // #16362). |
src/crew/conversation_ask.ts +3
| @@ -340,6 +340,9 @@ export const ASKED_AS: Readonly<Record<string, Form>> = { | ||
| 340 | 340 | }, |
| 341 | 341 | pinned_forge: (a) => pinnedForge(a), |
| 342 | 342 | infra: (a) => infra(a), |
| 343 | // Its apply is the delete tier's, refused from a chat before it is asked; the form names it | |
| 344 | // anyway. | |
| 345 | cloud_end: (a) => `${a["act"] === "delete" ? "Delete" : "Stop"} the cloud resource ${val(a, "id")} on your own cloud, as the plan you were shown says`, | |
| 343 | 346 | games: (a) => { |
| 344 | 347 | const on = `${clause("", val(a, "service"), " on ")}${val(a, "box") || "a game box"}`; |
| 345 | 348 | if (a["action"] === "console") return `Run ${quote(a, "text") || "a command"} in the console of ${on}`; |
src/crew/conversation_confirm.ts +2
| @@ -150,6 +150,8 @@ export const ASKING: Readonly<Record<string, Asking>> = { | ||
| 150 | 150 | games: { asks: not("action", "list") }, |
| 151 | 151 | // A plan built on the owner's own cloud spends their money: the person says so first (#16696). |
| 152 | 152 | infra: { asks: (a) => a["action"] === "apply" || (a["action"] === "end" && typeof (a["want"] as Args | undefined)?.["digest"] === "string" && (a["want"] as Args | undefined)?.["act"] !== "delete") }, |
| 153 | // A machine or a volume stopped or deleted on the owner's cloud: its plan reads, its apply asks. | |
| 154 | cloud_end: { asks: (a) => a["action"] === "apply" }, | |
| 153 | 155 | outsiders: {}, |
| 154 | 156 | seal: {}, |
| 155 | 157 | migrate: {}, |
src/http/infra_routes.ts +16 −3
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | import { cloudFactsAll } from "../actions/cloud_says.ts"; |
| 9 | 9 | import { infraCode } from "../cloud/infra_read.ts"; |
| 10 | 10 | import { buildOf, cloudResources, machineOf, providerConsole, readProjectsNow, type ComposeChoices, composeChoices, domainOf, infraOf, nameFor, planCompose, planRecord, pointsOf, rebuild, recordAccounts, startBuild } from "../actions/infra.ts"; |
| 11 | import { getCloudAccount } from "../core/cloud_account.ts"; | |
| 11 | 12 | import { endActOf, offeredEnds, performEnd, planEnd } from "../actions/cloud_end.ts"; |
| 12 | 13 | import { endPage } from "../web/pages/cloud_end.ts"; |
| 13 | 14 | import { dropRecord } from "../actions/dns_record.ts"; |
| @@ -25,7 +26,7 @@ import { INFRA_CSS, cloudPage, consolePage, endingPage, restoringPage, buildTray | ||
| 25 | 26 | import { cloudBranch, cloudList, cloudOverview, cloudPane, cloudTotal, cloudTreeJs } from "../web/pages/cloud_tree.ts"; |
| 26 | 27 | import { filesByNode } from "../cloud/declared_read.ts"; |
| 27 | 28 | import { logsOfContainer } from "../cloud/containers.ts"; |
| 28 | import { nodeAt, tabOf, type CloudView } from "../cloud/tree.ts"; | |
| 29 | import { nodeAt, tabOf, type CloudNode, type CloudView } from "../cloud/tree.ts"; | |
| 29 | 30 | import { pinnedBlock } from "./pinned_routes.ts"; |
| 30 | 31 | import { containerConsole } from "../web/pages/games.ts"; |
| 31 | 32 | import { LOG_READER_CSS, logReaderJs } from "../web/log_reader.ts"; |
| @@ -147,6 +148,18 @@ function runningNow(ctx: Ctx): Html | undefined { | ||
| 147 | 148 | |
| 148 | 149 | // GET /infra: every resource, with where the money goes beside it. `?fragment=1` is that alone, for |
| 149 | 150 | // Back from a resource. |
| 151 | /** What each cost row may be ended by, for this forge and this account. */ | |
| 152 | const endsOf = (ctx: Ctx) => { | |
| 153 | // One read per account, not per row: a table of thousands answers in the same few statements. | |
| 154 | const seen = new Map<string, boolean>(); | |
| 155 | const writable = (provider: string, account: string): boolean => { | |
| 156 | const k = `${provider}/${account}`; | |
| 157 | if (!seen.has(k)) seen.set(k, getCloudAccount(ctx.app.db, provider, account)?.writeAllowed === true); | |
| 158 | return seen.get(k)!; | |
| 159 | }; | |
| 160 | return (n: CloudNode): readonly { act: string; href: string }[] => offeredEnds(ctx.app, n.path, n.resource, writable); | |
| 161 | }; | |
| 162 | ||
| 150 | 163 | function infraGet(ctx: Ctx): Response { |
| 151 | 164 | const denied = guard(ctx); |
| 152 | 165 | if (denied) return denied; |
| @@ -156,7 +169,7 @@ function infraGet(ctx: Ctx): Response { | ||
| 156 | 169 | const tree = timePhase(ctx.request, "tree", () => treeOf(ctx)); |
| 157 | 170 | const running = runningNow(ctx); |
| 158 | 171 | if (tree === undefined || running === undefined) return notFoundPage(ctx); |
| 159 | const pane = cloudOverview(tree, running); | |
| 172 | const pane = cloudOverview(tree, running, endsOf(ctx)); | |
| 160 | 173 | if (ctx.url.searchParams.get("fragment") === "1") return fragment(pane, { request: ctx.request }); |
| 161 | 174 | return page({ ctx, title: "All clouds · Infrastructure", wide: true, scriptJs: SCRIPT, styleCss: INFRA_CSS, body: resourcesPage(tree, [], pane), noDock: true }); |
| 162 | 175 | } |
| @@ -189,7 +202,7 @@ function infraLive(ctx: Ctx): Response { | ||
| 189 | 202 | if (tree === undefined) return fragment(html``, { status: 404 }); |
| 190 | 203 | const at = placeOf((ctx.url.searchParams.get("at") ?? "").slice(0, 600)) ?? []; |
| 191 | 204 | // What is open stays open under a new line; with nothing open the pane is what the line found. |
| 192 | return fragment(html`${cloudTotal(tree)}${cloudList(tree, at)}${at.length > 0 ? null : cloudOverview(tree, runningNow(ctx) ?? html``)}`, { request: ctx.request }); | |
| 205 | return fragment(html`${cloudTotal(tree)}${cloudList(tree, at)}${at.length > 0 ? null : cloudOverview(tree, runningNow(ctx) ?? html``, endsOf(ctx))}`, { request: ctx.request }); | |
| 193 | 206 | } |
| 194 | 207 | const running = runningNow(ctx); |
| 195 | 208 | return running === undefined ? fragment(html``, { status: 404 }) : fragment(running, { request: ctx.request }); |
src/http/mcp/tools/cloud_end.ts added +49
| @@ -0,0 +1,49 @@ | ||
| 1 | import { endActOf, performEnd, planEnd, planText } from "../../../actions/cloud_end.ts"; | |
| 2 | import { pathIn } from "../../../cloud/tree.ts"; | |
| 3 | import { scopeAllows } from "../../../core/tokens.ts"; | |
| 4 | import { good, bad, type Tool, str } from "../shared.ts"; | |
| 5 | ||
| 6 | /** | |
| 7 | * Stop or delete one machine or volume from the cost table (#18182): a thin door over | |
| 8 | * `planEnd` and `performEnd`, so it asks what the page and the terminal ask. `plan` reads; | |
| 9 | * `apply` brings back the plan's `digest` and the resource's `name`, typed, for a stop as for a | |
| 10 | * delete. The forge's own agent never applies one (`tier: "delete"`). | |
| 11 | */ | |
| 12 | export const tool: Tool = { | |
| 13 | name: "cloud_end", | |
| 14 | listedTo: "admin", | |
| 15 | doc: "`{ action, act, id, digest?, name? }`: stop or delete one machine or volume, `id` as `infra` `list` gives it. `plan` an `act` (`stop` or `delete`): what goes, what it costs now, what is lost and what keeps billing, and the `digest` to bring back; `refusal` says why it cannot be done. `apply` with that `digest` and the resource's `name` typed back, for a stop as for a delete (a stop deletes the machine's own disk); the plan expires after 30 minutes. A forge admin with an admin-scope token.", | |
| 16 | description: "Stop or delete a cloud machine or volume, after its plan (admin).", | |
| 17 | tier: "delete", | |
| 18 | deletes: (args) => args["action"] === "apply", | |
| 19 | where: "on the resource's plan at /infra, where Stop and Delete ask for its name", | |
| 20 | inputSchema: { | |
| 21 | type: "object", | |
| 22 | properties: { | |
| 23 | action: { type: "string", enum: ["plan", "apply"] }, | |
| 24 | act: { type: "string", enum: ["stop", "delete"] }, | |
| 25 | id: { type: "string", maxLength: 600 }, | |
| 26 | digest: { type: "string", maxLength: 80 }, | |
| 27 | name: { type: "string", maxLength: 200, description: "The resource's name, typed back." }, | |
| 28 | }, | |
| 29 | required: ["action", "act", "id"], | |
| 30 | }, | |
| 31 | // Marked a write so a `ro` token never reads the owner's cloud; a plan is only a read. | |
| 32 | writes: true, | |
| 33 | heldNotWhen: (args) => args["action"] === "plan", | |
| 34 | async run(ctx, user, args) { | |
| 35 | if (!user.isAdmin) return bad("not_found", "no such tool here"); | |
| 36 | const act = endActOf(str(args["act"])); | |
| 37 | if (act === undefined) return bad("bad_act", "act is stop or delete"); | |
| 38 | const path = pathIn(str(args["id"])); | |
| 39 | if (args["action"] === "plan") { | |
| 40 | const p = planEnd(ctx.app, user, act, path); | |
| 41 | if (!p.ok) return bad("refused", p.error); | |
| 42 | return good({ says: p.value.refusal === "" ? `${planText(p.value)} Apply with this digest and ${p.value.name} typed as name.` : p.value.refusal, ...p.value }); | |
| 43 | } | |
| 44 | if (args["action"] !== "apply") return bad("bad_action", "action is plan or apply"); | |
| 45 | if (!scopeAllows(ctx.auth.scope ?? "ro", "admin")) return bad("forbidden", "stopping or deleting a cloud resource needs an admin-scope token"); | |
| 46 | const done = await performEnd(ctx.app, user, act, path, { digest: str(args["digest"]), typed: str(args["name"]) }); | |
| 47 | return done.ok ? good({ says: done.value }) : bad("refused", done.error); | |
| 48 | }, | |
| 49 | }; |
src/http/mcp/tools/index.ts +1
| @@ -48,6 +48,7 @@ export { tool as claim_link } from "./claim_link.ts"; | ||
| 48 | 48 | export { tool as close } from "./close.ts"; |
| 49 | 49 | export { tool as cloud_account } from "./cloud_account.ts"; |
| 50 | 50 | export { tool as cloud_accounts } from "./cloud_accounts.ts"; |
| 51 | export { tool as cloud_end } from "./cloud_end.ts"; | |
| 51 | 52 | export { tool as commits } from "./commits.ts"; |
| 52 | 53 | export { tool as confirm_wait } from "./confirm_wait.ts"; |
| 53 | 54 | export { tool as contribute } from "./contribute.ts"; |
src/http/mcp/tools/infra.ts +5 −5
| @@ -50,12 +50,12 @@ function named(whole: CloudNode, nodes: readonly CloudNode[], args: Args, says: | ||
| 50 | 50 | } |
| 51 | 51 | |
| 52 | 52 | /** |
| 53 | * The `want` of an `end`: the act, the digest of the plan being confirmed, and a delete's typed | |
| 54 | * name. | |
| 53 | * The `want` of an `end`: the act, the digest of the plan being confirmed, and the resource's | |
| 54 | * typed name (a stop's as a delete's: a stop deletes the machine's own disk). | |
| 55 | 55 | */ |
| 56 | 56 | const endWant = (args: Args): { act: string; digest: string; typed: string } => { |
| 57 | 57 | const w = (typeof args["want"] === "object" && args["want"] !== null ? args["want"] : {}) as Record<string, unknown>; |
| 58 | return { act: s(w["act"], 10), digest: s(w["digest"], 32), typed: s(w["typed"], 200) }; | |
| 58 | return { act: s(w["act"], 10), digest: s(w["digest"], 80), typed: s(w["typed"], 200) }; | |
| 59 | 59 | }; |
| 60 | 60 | |
| 61 | 61 | /** |
| @@ -67,7 +67,7 @@ const endWant = (args: Args): { act: string; digest: string; typed: string } => | ||
| 67 | 67 | export const tool: Tool = { |
| 68 | 68 | name: "infra", |
| 69 | 69 | listedTo: "admin", |
| 70 | doc: "`{ action, id?, want?, question?, names?, result?, bucket?, cursor? }`: `list` (its `says` names every machine; with a filter line as `id`, like `kind:volume cost:>10 sort:-created`, the cloud resources it leaves, each with `partOf`, its app, and `attachedTo`; 50 a page, `cursor` for the next), `show` an `id` (a plan, an experiment or a machine's name), `plan` a `want` `{app, where, question?, experiment?, days?}` or a firewall `{firewall: name}` or a DNS record `{dns: true, name, account, type: A|SRV, host, value, port?}` or a game box `{game: true, where, repo, name?, host?}` or Minecraft Java `{design: minecraft, players, where, domain, dns, repo, eula: true, name?, version?}` (its `compose` comes back with the plan) or Postgres `{database: true, app, where: account@region, size?, secret?}` or dead `names`, `apply` its `id`, `check` DNS records, `code` (infra.json against the forge's record), `keep`, `begin`, `attach`, `record_result`; `cloud` a machine's name as `id` (its provider's view: power, size, IPs, actions) or a resource's `id` from `list` (as last read; a game box's machine names its `containers`, each by the `id` this takes; `file` is what declares a machine or a container, env names only); `price`/`bind` a `bucket` `{region, name, repo?, stored_gib?, out_gib?}`; `cost` (each account against its ceiling and budget, and what costs most); `end` a resource's `id` from `list` with `want` `{act: stop|delete}` for its plan and `digest`, then again with `want` `{act, digest, typed?}` to do it (held for the person's yes; `typed` is a delete's resource name).", | |
| 70 | doc: "`{ action, id?, want?, question?, names?, result?, bucket?, cursor? }`: `list` (its `says` names every machine; with a filter line as `id`, like `kind:volume cost:>10 sort:-created`, the cloud resources it leaves, each with `partOf`, its app, and `attachedTo`; 50 a page, `cursor` for the next), `show` an `id` (a plan, an experiment or a machine's name), `plan` a `want` `{app, where, question?, experiment?, days?}` or a firewall `{firewall: name}` or a DNS record `{dns: true, name, account, type: A|SRV, host, value, port?}` or a game box `{game: true, where, repo, name?, host?}` or Minecraft Java `{design: minecraft, players, where, domain, dns, repo, eula: true, name?, version?}` (its `compose` comes back with the plan) or Postgres `{database: true, app, where: account@region, size?, secret?}` or dead `names`, `apply` its `id`, `check` DNS records, `code` (infra.json against the forge's record), `keep`, `begin`, `attach`, `record_result`; `cloud` a machine's name as `id` (its provider's view: power, size, IPs, actions) or a resource's `id` from `list` (as last read; a game box's machine names its `containers`, each by the `id` this takes; `file` is what declares a machine or a container, env names only); `price`/`bind` a `bucket` `{region, name, repo?, stored_gib?, out_gib?}`; `cost` (each account against its ceiling and budget, and what costs most); `end` a resource's `id` from `list` with `want` `{act: stop|delete}` for its plan and `digest`, then again with `want` `{act, digest, typed}` to do it (held for the person's yes; `typed` is the resource's name, for a stop as for a delete; a plan expires after 30 minutes).", | |
| 71 | 71 | description: "Machines, spend.", |
| 72 | 72 | inputSchema: { |
| 73 | 73 | type: "object", |
| @@ -170,7 +170,7 @@ export const tool: Tool = { | ||
| 170 | 170 | const planned = planEnd(ctx.app, user, act, path); |
| 171 | 171 | if (!planned.ok) return bad("not_found", planned.error === "not_found" ? "no such tool here" : planned.error); |
| 172 | 172 | const p = planned.value; |
| 173 | return good({ says: p.refusal === "" ? `${planText(p)} Confirm with want.digest ${p.digest}${act === "delete" ? ` and want.typed ${p.name}` : ""}.` : p.refusal, what: p.what, lines: p.lines, refusal: p.refusal, digest: p.digest }); | |
| 173 | return good({ says: p.refusal === "" ? `${planText(p)} Confirm with want.digest ${p.digest} and want.typed ${p.name}.` : p.refusal, name: p.name, what: p.what, lines: p.lines, refusal: p.refusal, digest: p.digest }); | |
| 174 | 174 | } |
| 175 | 175 | const done = await performEnd(ctx.app, user, act, path, { digest: want.digest, typed: want.typed }); |
| 176 | 176 | return done.ok ? good({ says: done.value }) : bad("refused", done.error); |
src/tui/screens/cloud_end.ts +3 −4
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * Stop or delete the selected cloud resource from the terminal (#18102): the plan the page shows, |
| 3 | * a confirm, and for a delete the resource's name typed back (`actions/cloud_end.ts`). | |
| 3 | * a confirm, and the resource's name typed back for both (`actions/cloud_end.ts`). | |
| 4 | 4 | */ |
| 5 | 5 | |
| 6 | 6 | import { performEnd, planEnd, type EndAct } from "../../actions/cloud_end.ts"; |
| @@ -21,11 +21,10 @@ export function askEnd(f: Session, ctx: Ctx, parent: Screen, act: EndAct, n: Clo | ||
| 21 | 21 | title: `${verb} ${p.name}?`, |
| 22 | 22 | body: [p.what, ...p.lines.map((l) => `${l.label}: ${l.value}`)], |
| 23 | 23 | width: 96, |
| 24 | actions: [act === "delete" ? { label: verb, variant: "danger" as const } : { label: verb }, { label: "Cancel" }], | |
| 24 | actions: [{ label: verb, variant: "danger" as const }, { label: "Cancel" }], | |
| 25 | 25 | onChoose: (i) => { |
| 26 | 26 | if (i !== 0) return; |
| 27 | if (act === "stop") return run(""); | |
| 28 | ctx.push(promptScreen(ctx, parent, { title: `Delete ${p.name}`, label: `type ${p.name} to delete it`, onSubmit: (typed) => later(ctx, () => (run(typed), parent)) })); | |
| 27 | ctx.push(promptScreen(ctx, parent, { title: `${verb} ${p.name}`, label: `type ${p.name} to ${act} it`, onSubmit: (typed) => later(ctx, () => (run(typed), parent)) })); | |
| 29 | 28 | }, |
| 30 | 29 | }), |
| 31 | 30 | ); |
src/web/pages/cloud_end.ts +4 −4
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | /** |
| 2 | * The plan of a stop or a delete (#18102): what will stop or go, its cost now, what is lost. A | |
| 3 | * delete asks for the resource's name typed back; a refused plan shows why and offers nothing. | |
| 2 | * The plan of a stop or a delete (#18102): what will stop or go, its cost now, what is lost. Each | |
| 3 | * asks for the resource's name typed back; a refused plan shows why and offers nothing. | |
| 4 | 4 | */ |
| 5 | 5 | |
| 6 | 6 | import type { EndPlan } from "../../actions/cloud_end.ts"; |
| @@ -19,9 +19,9 @@ export function endPage(p: EndPlan): Html { | ||
| 19 | 19 | ${p.refusal === "" |
| 20 | 20 | ? html`<form method="post" action="/infra/end/${p.act}/${p.path.map(encodeURIComponent).join("/")}"> |
| 21 | 21 | <input type="hidden" name="plan" value="${p.digest}" /> |
| 22 | ${p.act === "delete" ? input({ label: `Type ${p.name} to delete it`, name: "confirm", required: true, mono: true, autocomplete: "off", spellcheck: false, autocorrect: false }) : null} | |
| 22 | ${input({ label: `Type ${p.name} to ${p.act} it`, name: "confirm", required: true, mono: true, autocomplete: "off", spellcheck: false, autocorrect: false })} | |
| 23 | 23 | <div class="form-actions"> |
| 24 | ${btn(`${verb} ${p.name}`, { variant: p.act === "delete" ? "danger" : "primary" })} | |
| 24 | ${btn(`${verb} ${p.name}`, { variant: "danger" })} | |
| 25 | 25 | ${btn("Cancel", { href: back, variant: "ghost" })} |
| 26 | 26 | </div> |
| 27 | 27 | </form>` |
src/web/pages/cloud_tree.ts +11 −4
| @@ -240,8 +240,15 @@ function listed(v: CloudView, n: CloudNode): Html { | ||
| 240 | 240 | ${all.length > PANE_ROWS ? html`<p class="muted small">The first ${PANE_ROWS}, ${orderSays(v.q)}: filter to see the rest.</p>` : null}`; |
| 241 | 241 | } |
| 242 | 242 | |
| 243 | /** The acts a row offers: none for what the forge cannot end, or on a read-only account. */ | |
| 244 | export type EndsOf = (n: CloudNode) => readonly { act: string; href: string }[]; | |
| 245 | ||
| 246 | /** Stop and Delete beside a cost row's name: each opens its plan, and nothing runs from here. */ | |
| 247 | const rowEnds = (n: CloudNode, acts: readonly { act: string; href: string }[]): Html | null => | |
| 248 | acts.length === 0 ? null : html` <span class="row-ends small">${acts.map((e, i) => html`${i > 0 ? " · " : ""}<a href="${e.href}" aria-label="Plan to ${e.act} ${n.name}">${e.act === "stop" ? "Stop" : "Delete"}</a>`)}</span>`; | |
Principle 7 and the design system: |
||
| 249 | ||
| 243 | 250 | /** The costliest resources in one table, in the tree's order, narrowed by the filter line. */ |
| 244 | function costliestTable(v: CloudView): Html { | |
| 251 | function costliestTable(v: CloudView, endsOf: EndsOf): Html { | |
| 245 | 252 | const all = listedOf(v, v.root); |
| 246 | 253 | if (all.length === 0) return html`<p>${v.q.text === "" ? "Nothing here." : "Nothing here matches the filter."}</p>`; |
| 247 | 254 | return html`<section data-costliest> |
| @@ -250,7 +257,7 @@ function costliestTable(v: CloudView): Html { | ||
| 250 | 257 | columns: FIRST_COLUMNS, |
| 251 | 258 | line: v.q.line, |
| 252 | 259 | rows: all.slice(0, PANE_ROWS), |
| 253 | cell: (c, field) => (field === "name" ? html`<a href="${cloudHref(c.path, v.q)}">${c.name}</a>` : field === "cost" ? costMark(c) : firstCell(c, field)), | |
| 260 | cell: (c, field) => (field === "name" ? html`<a href="${cloudHref(c.path, v.q)}">${c.name}</a>${rowEnds(c, endsOf(c))}` : field === "cost" ? costMark(c) : firstCell(c, field)), | |
| 254 | 261 | href: (text) => cloudHref([], { ...v.q, text }), |
| 255 | 262 | caption: `Resources, ${orderSays(v.q)}`, |
| 256 | 263 | })} |
| @@ -259,9 +266,9 @@ function costliestTable(v: CloudView): Html { | ||
| 259 | 266 | } |
| 260 | 267 | |
| 261 | 268 | /** With nothing open: where the money goes and what the forge runs, or what the filter found. */ |
| 262 | export function cloudOverview(v: CloudView, running: Html): Html { | |
| 269 | export function cloudOverview(v: CloudView, running: Html, endsOf: EndsOf = () => []): Html { | |
| 263 | 270 | return html`<section id="code-pane" data-path="All clouds" data-cloud-pane="all"> |
| 264 | ${costliestTable(v)}${v.q.text === "" ? running : null} | |
| 271 | ${costliestTable(v, endsOf)}${v.q.text === "" ? running : null} | |
| 265 | 272 | </section>`; |
| 266 | 273 | } |
| 267 | 274 |
src/web/style/components.ts +9
| @@ -635,6 +635,15 @@ details[open] > summary.row > .row-lead { transform: rotate(90deg); } | ||
| 635 | 635 | .row-actions { opacity: 0; transition: opacity 120ms var(--ease); } |
| 636 | 636 | .row:focus-within .row-actions { opacity: 1; } |
| 637 | 637 | @media (hover: hover) and (pointer: fine) { .row:hover .row-actions { opacity: 1; } } |
| 638 | /* Stop · Delete beside a cost row's name (docs/design/areas/infra.md): muted, the links alone in the | |
| 639 | accent. Where a pointer hovers they wait for the row's hover or focus, never moving it; on touch | |
| 640 | and without hover they always show, and they are links, so keyboard and no-JS reach them. */ | |
| 641 | .row-ends { color: var(--muted-fg); white-space: nowrap; } | |
| 642 | .row-ends a { color: var(--accent); } | |
| 643 | @media (hover: hover) and (pointer: fine) { | |
| 644 | .row-ends { opacity: 0; transition: opacity 120ms var(--ease); } | |
| 645 | tr:hover .row-ends, tr:focus-within .row-ends { opacity: 1; } | |
| 646 | } | |
| 638 | 647 | /* Settings controls are the point of their row, never revealed by hover: |
| 639 | 648 | they wrap under the text before they would clip, at any width. */ |
| 640 | 649 | .row-fields { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; } |
test/cloud-end.test.ts +83 −3
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | * on a read-only account (by the server, not only the page), done only after the confirm, and |
| 4 | 4 | * audited with who and the confirmed plan. |
| 5 | 5 | */ |
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 6 | import { afterAll, afterEach, beforeAll, describe, expect, setSystemTime, test } from "bun:test"; | |
| 7 | 7 | import { mkdtempSync } from "node:fs"; |
| 8 | 8 | import { rm } from "node:fs/promises"; |
| 9 | 9 | import { tmpdir } from "node:os"; |
| @@ -17,12 +17,14 @@ import { costliestOf } from "../src/cloud/tree.ts"; | ||
| 17 | 17 | import { READ_ONLY } from "../src/core/cloud_account.ts"; |
| 18 | 18 | import { auditToday } from "../src/core/cloud_audit.ts"; |
| 19 | 19 | import { createSession } from "../src/core/sessions.ts"; |
| 20 | import { createToken } from "../src/core/tokens.ts"; | |
| 20 | 21 | import { createUser, type User } from "../src/core/users.ts"; |
| 21 | 22 | import { serve, type Servers } from "../src/http/server.ts"; |
| 22 | 23 | import { createForgeApp } from "../src/tui/forge.ts"; |
| 23 | 24 | import { cloudTreeScreen } from "../src/tui/screens/cloudtree.ts"; |
| 24 | 25 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; |
| 25 | 26 | import { settleApp } from "./helpers/tui.ts"; |
| 27 | import { mcpTool } from "./helpers/mcp.ts"; | |
| 26 | 28 | |
| 27 | 29 | let dir = ""; |
| 28 | 30 | let app: App; |
| @@ -126,6 +128,18 @@ describe("a read-only account", () => { | ||
| 126 | 128 | expect(rows.map((r) => [r.purpose, r.allowed, r.actor])).toEqual([["delete:volume", false, admin.id], ["stop:machine", false, admin.id]]); |
| 127 | 129 | }); |
| 128 | 130 | |
| 131 | test("is refused when planned, with a refused audit row and a refused cloud.end event", () => { | |
| 132 | const before = auditToday(app.db).length; | |
| 133 | const p = planEnd(app, admin, "stop", nodeOf("machine:222")); | |
| 134 | expect(p.ok && p.value.refusal).toBe(READ_ONLY); | |
| 135 | const rows = auditToday(app.db); | |
| 136 | expect(rows.length).toBe(before + 1); | |
| 137 | expect(rows.find((r) => r.purpose === "stop:machine" && !r.allowed && r.plan.startsWith(`Refused: ${READ_ONLY}`))).toMatchObject({ account: "ro", actor: admin.id }); | |
| 138 | const last = app.db.query("SELECT payload FROM event WHERE kind = 'cloud.end' ORDER BY rowid DESC LIMIT 1").get() as { payload: string }; | |
| 139 | expect(JSON.parse(last.payload)).toMatchObject({ account: "ro", ok: false, refused: READ_ONLY }); | |
| 140 | expect(calls()).toEqual([]); | |
| 141 | }); | |
| 142 | ||
| 129 | 143 | test("the page shows the refusal and no form", async () => { |
| 130 | 144 | const path = nodeOf("volume:vol-7").map(encodeURIComponent).join("/"); |
| 131 | 145 | const res = await fetch(`${servers.url}/infra/end/delete/${path}`, { headers: { cookie: `forge_session=${createSession(app.db, admin.id).token}` } }); |
| @@ -137,21 +151,73 @@ describe("a read-only account", () => { | ||
| 137 | 151 | }); |
| 138 | 152 | |
| 139 | 153 | describe("a write-allowed account", () => { |
| 140 | test("a stop is done only with the plan's digest, and audited with who and the plan", async () => { | |
| 154 | test("a stop is done only with the plan's digest and the name typed, and audited with who and the plan", async () => { | |
| 141 | 155 | const path = nodeOf("machine:111"); |
| 142 | 156 | const p = planEnd(app, admin, "stop", path); |
| 143 | 157 | if (!p.ok) throw new Error(p.error); |
| 144 | 158 | const stale = await performEnd(app, admin, "stop", path, { digest: "0".repeat(16), typed: "" }); |
| 145 | 159 | expect(stale.ok).toBe(false); |
| 146 | 160 | expect(calls()).toEqual([]); |
| 147 | const done = await performEnd(app, admin, "stop", path, { digest: p.value.digest, typed: "" }); | |
| 161 | const none = await performEnd(app, admin, "stop", path, { digest: p.value.digest, typed: "" }); | |
| 162 | expect(none.ok).toBe(false); | |
| 163 | const wrong = await performEnd(app, admin, "stop", path, { digest: p.value.digest, typed: "nope" }); | |
| 164 | expect(wrong.ok).toBe(false); | |
| 165 | expect(calls()).toEqual([]); | |
| 166 | const done = await performEnd(app, admin, "stop", path, { digest: p.value.digest, typed: p.value.name }); | |
| 148 | 167 | expect(done.ok).toBe(true); |
| 168 | // Each refused attempt (the stale digest, no name, a wrong name) wrote its own event, and the | |
| 169 | // done one its. | |
| 170 | const events = (app.db.query("SELECT payload FROM event WHERE kind = 'cloud.end' ORDER BY rowid").all() as { payload: string }[]).map((e) => JSON.parse(e.payload) as { ok: boolean; refused?: string }); | |
| 171 | expect(events.slice(-4).map((e) => e.ok)).toEqual([false, false, false, true]); | |
| 172 | expect(events.at(-2)!.refused).toContain("Type web to stop it"); | |
| 149 | 173 | expect(calls().filter((c) => !c.startsWith("GET"))).toEqual(['POST /v2/droplets/111/actions {"type":"power_off"}']); |
| 150 | 174 | const row = auditToday(app.db).find((r) => r.purpose === "stop:machine" && r.allowed); |
| 151 | 175 | expect(row).toMatchObject({ provider: "digitalocean", account: "rw", actor: admin.id, target: "machine:111" }); |
| 152 | 176 | expect(row?.plan).toBe(planText(p.value)); |
| 153 | 177 | }); |
| 154 | 178 | |
| 179 | test("a plan older than 30 minutes is refused, and nothing reaches the vendor", async () => { | |
| 180 | const path = nodeOf("machine:111"); | |
| 181 | const p = planEnd(app, admin, "stop", path); | |
| 182 | if (!p.ok) throw new Error(p.error); | |
| 183 | setSystemTime(new Date(Date.now() + 31 * 60_000)); | |
| 184 | const late = await performEnd(app, admin, "stop", path, { digest: p.value.digest, typed: p.value.name }); | |
| 185 | setSystemTime(); | |
| 186 | expect(late.ok).toBe(false); | |
| 187 | if (!late.ok) expect(late.error).toContain("30 minutes"); | |
| 188 | expect(calls().filter((c) => !c.startsWith("GET"))).toEqual([]); | |
| 189 | }); | |
| 190 | ||
| 191 | test("a digest minted with a fresh stamp is refused: the stamp is keyed with the forge's secret", async () => { | |
| 192 | const path = nodeOf("machine:111"); | |
| 193 | const p = planEnd(app, admin, "stop", path); | |
| 194 | if (!p.ok) throw new Error(p.error); | |
| 195 | // What anyone could compute without the secret: the plan's words, hashed over a fresh stamp. | |
| 196 | const at = Date.now() + 1000; | |
| 197 | const minted = `${at}.${new Bun.CryptoHasher("sha256").update(JSON.stringify([at, "stop", "digitalocean", "rw", "machine:111", p.value.lines])).digest("hex").slice(0, 32)}`; | |
| 198 | setSystemTime(new Date(Date.now() + 2000)); | |
| 199 | const forged = await performEnd(app, admin, "stop", path, { digest: minted, typed: p.value.name }); | |
| 200 | setSystemTime(); | |
| 201 | expect(forged.ok).toBe(false); | |
| 202 | expect(calls().filter((c) => !c.startsWith("GET"))).toEqual([]); | |
| 203 | }); | |
| 204 | ||
| 205 | test("the MCP tool plans, and its apply with no name or a wrong one is refused before the vendor", async () => { | |
| 206 | const token = createToken(app.db, admin.id, "end", "admin").token; | |
| 207 | const id = nodeOf("machine:111").join("/"); | |
| 208 | const plan = await mcpTool(servers.url, token, "cloud_end", { action: "plan", act: "stop", id }); | |
| 209 | expect(plan.value?.refusal).toBe(""); | |
| 210 | const digest: string = plan.value.digest; | |
| 211 | const none = await mcpTool(servers.url, token, "cloud_end", { action: "apply", act: "stop", id, digest }); | |
| 212 | expect(none.error).toContain("Type web to stop it"); | |
| 213 | const wrong = await mcpTool(servers.url, token, "cloud_end", { action: "apply", act: "delete", id, digest, name: "nope" }); | |
| 214 | expect(wrong.error).toBeDefined(); | |
| 215 | expect(calls().filter((c) => !c.startsWith("GET"))).toEqual([]); | |
| 216 | const ro = createToken(app.db, admin.id, "end-ro", "ro").token; | |
| 217 | expect((await mcpTool(servers.url, ro, "cloud_end", { action: "apply", act: "stop", id, digest, name: "web" })).error).toBeDefined(); | |
| 218 | expect(calls().filter((c) => !c.startsWith("GET"))).toEqual([]); | |
| 219 | }); | |
| 220 | ||
| 155 | 221 | test("a delete needs the name typed back, then deletes and is audited", async () => { |
| 156 | 222 | const path = nodeOf("volume:vol-9"); |
| 157 | 223 | const p = planEnd(app, admin, "delete", path); |
| @@ -189,6 +255,17 @@ describe("a write-allowed account", () => { | ||
| 189 | 255 | }); |
| 190 | 256 | }); |
| 191 | 257 | |
| 258 | describe("the cost table on /infra", () => { | |
| 259 | afterEach(() => setSystemTime()); | |
| 260 | test("a write-allowed row has Stop and Delete links to their plans", async () => { | |
| 261 | const h = { cookie: `forge_session=${createSession(app.db, admin.id).token}` }; | |
| 262 | const page = await (await fetch(`${servers.url}/infra`, { headers: h })).text(); | |
| 263 | expect(page).toContain("/infra/end/stop/"); | |
| 264 | expect(page).toContain("/infra/end/delete/"); | |
| 265 | expect(page).toContain("Plan to stop web"); | |
| 266 | }); | |
| 267 | }); | |
| 268 | ||
| 192 | 269 | describe("the terminal", () => { |
| 193 | 270 | test("X on a resource shows the same plan, and a read-only account says why", async () => { |
| 194 | 271 | const terminal = headlessTerminal(160, 40); |
| @@ -225,6 +302,9 @@ describe("the plan as facts", () => { | ||
| 225 | 302 | expect(p.value.lines.map((l) => l.label)).toEqual(["Will", "Cost now", "Lost"]); |
| 226 | 303 | const { endPage } = await import("../src/web/pages/cloud_end.ts"); |
| 227 | 304 | const out = String(endPage(p.value)); |
| 305 | const stop = planEnd(app, admin, "stop", nodeOf("machine:111")); | |
| 306 | if (!stop.ok) throw new Error(stop.error); | |
| 307 | expect(String(endPage(stop.value))).toContain('name="confirm"'); | |
| 228 | 308 | expect(out).toContain("<dt>Will</dt>"); |
| 229 | 309 | expect(out).toContain("<dt>Cost now</dt>"); |
| 230 | 310 | expect(out).not.toContain("<p>Will"); |
test/conversation-ask.test.ts +2
| @@ -524,6 +524,7 @@ const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [ | ||
| 524 | 524 | ["wall", { repo: "marin/cakes", number: 2, answer: "send_back" }, "Send pull #2 in marin/cakes back at the access wall."], |
| 525 | 525 | ["infra", { action: "apply", id: "plan-0123456789abcdef" }, "Build the infrastructure plan plan-0123456789abcdef on your own cloud: it spends money each month."], |
| 526 | 526 | ["infra", { action: "apply", id: "plan-0123456789abcdef", names: ["canary1", "trevato"] }, "Clear the dead rows canary1, trevato: nothing exists at the provider for them, so only the forge's rows go and nothing is deleted there."], |
| 527 | ["cloud_end", { action: "apply", act: "stop", id: "hetzner/main/default/machine:7" }, "Stop the cloud resource hetzner/main/default/machine:7 on your own cloud, as the plan you were shown says."], | |
| 527 | 528 | ["games", { action: "power", box: "net", service: "hub", kind: "restart" }, "Restart hub on net."], |
| 528 | 529 | ["games", { action: "console", box: "net", service: "hub", text: "say hi" }, 'Run "say hi" in the console of hub on net.'], |
| 529 | 530 | ["games", { action: "take_back", box: "net", command: "01x" }, "Take back a command net was not handed yet."], |
| @@ -719,6 +720,7 @@ describe("the held action, in the person's words", () => { | ||
| 719 | 720 | const text = |
| 720 | 721 | "Record forge metrics over time so the forge can draw graphs\nThe health read gives only a snapshot: memory free, disk free"; |
| 721 | 722 | expect(confirmSentence("infra", { action: "end", id: "hetzner/main/vol1", want: { act: "stop", digest: "d" } })).toStartWith("Stop the cloud resource"); |
| 723 | expect(confirmSentence("cloud_end", { action: "apply", act: "delete", id: "hetzner/main/vol1" })).toStartWith("Delete the cloud resource hetzner/main/vol1"); | |
| 722 | 724 | expect(confirmSentence("tell", { text })).toBe( |
| 723 | 725 | 'Keep a note for you: "Record forge metrics over time so the forge can draw graphs".', |
| 724 | 726 | ); |
test/conversation-confirm.test.ts +1 −1
| @@ -143,7 +143,7 @@ describe("the one list of what asks first", () => { | ||
| 143 | 143 | expect(listed || NOT_ASKED.has(t.name), `${t.name} writes: ask first (ASKING) or name it in NOT_ASKED`).toBe(true); |
| 144 | 144 | expect(listed && NOT_ASKED.has(t.name), `${t.name} is on both lists`).toBe(false); |
| 145 | 145 | } |
| 146 | for (const name of ["land_past_gate", "share", "invites", "egress_grants", "sever", "parent_unlink", "quotas", "spawn", "app_deploy", "stop", "converge", "origins", "cloud_account", "pinned_forge", "infra", "outsiders", "seal", "migrate"]) | |
| 146 | for (const name of ["land_past_gate", "share", "invites", "egress_grants", "sever", "parent_unlink", "quotas", "spawn", "app_deploy", "stop", "converge", "origins", "cloud_account", "cloud_end", "pinned_forge", "infra", "outsiders", "seal", "migrate"]) | |
| 147 | 147 | expect(ASKING[name], name).toBeDefined(); |
| 148 | 148 | }); |
| 149 | 149 |
test/delete-tier.test.ts +4
| @@ -53,6 +53,10 @@ const SAMPLES: Readonly< | ||
| 53 | 53 | destroys: { repo: "alice/shop", name: "old", action: "delete" }, |
| 54 | 54 | spares: { repo: "alice/shop", name: "new", action: "create" }, |
| 55 | 55 | }, |
| 56 | cloud_end: { | |
| 57 | destroys: { action: "apply", act: "stop", id: "digitalocean/rw/default/machine:1" }, | |
| 58 | spares: { action: "plan", act: "stop", id: "digitalocean/rw/default/machine:1" }, | |
| 59 | }, | |
| 56 | 60 | cloud_account: { |
| 57 | 61 | destroys: { verb: "remove", provider: "hetzner", name: "main" }, |
| 58 | 62 | spares: { verb: "verify", provider: "hetzner", name: "main" }, |
test/mcp-cloud-cost.test.ts +6 −2
| @@ -118,7 +118,7 @@ describe("end", () => { | ||
| 118 | 118 | const plan = JSON.parse(out.text) as { digest: string; refusal: string; says: string }; |
| 119 | 119 | expect(plan.refusal).toBe(""); |
| 120 | 120 | expect(plan.says).toContain("$12.00 a month"); |
| 121 | expect(plan.digest).toMatch(/^[0-9a-f]{16}$/); | |
| 121 | expect(plan.digest).toMatch(/^\d+\.[0-9a-f]{32}$/); | |
| 122 | 122 | expect(asked).toEqual([]); |
| 123 | 123 | }); |
| 124 | 124 | |
| @@ -143,7 +143,11 @@ describe("end", () => { | ||
| 143 | 143 | expect(stale.error).toBe(true); |
| 144 | 144 | expect(asked).toEqual([]); |
| 145 | 145 | const plan = JSON.parse((await call(token, { action: "end", id, want: { act: "stop" } })).text) as { digest: string }; |
| 146 | const done = await call(token, { action: "end", id, want: { act: "stop", digest: plan.digest } }); | |
| 146 | // A stop deletes the machine's own disk: it wants the name typed, as a delete does. | |
| 147 | const untyped = await call(token, { action: "end", id, want: { act: "stop", digest: plan.digest } }); | |
| 148 | expect(untyped.error).toBe(true); | |
| 149 | expect(asked).toEqual([]); | |
| 150 | const done = await call(token, { action: "end", id, want: { act: "stop", digest: plan.digest, typed: "web" } }); | |
| 147 | 151 | expect(done.error).toBe(false); |
| 148 | 152 | expect(asked.filter((c) => !c.startsWith("GET"))).toEqual(["POST /v2/droplets/111/actions"]); |
| 149 | 153 | }); |
Good: the name is required for both acts and nothing reaches the vendor before it. Principle 8: the stop message is plain and says why. Please add the same check to the MCP apply path, with a test that fails without it.