Public: anyone can read this; the crew can change it.

A deployed forge can be retired: its machine and record go, its data only when told #16338

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

sold/retire → main 0 commits 2 threads · 2 unresolved

  • Merged. sold/retire was merged into main as 0a36151.

Review

Sign in to review this change.
23 files changed +1137 −38
docs/features/pinned-forge.md +4
@@ -71,6 +71,10 @@ An admin names the **domain for deployed forges** (`forges.example.com`) on Pinn
7171
7272 With a **Cloudflare** cloud account attached and writes allowed, the forge then writes the record itself: after the machine has an address (the deploy, and every Update, Roll back and new claim link), and again on Check, it upserts `<host> A <address>` in the zone that holds the name, through the first such account whose token can edit that zone: found by name and updated, or made, so a replaced machine's new address changes the record and never adds one; DNS only (not proxied, so the machine gets its own certificate), TTL 60. The calls go to `api.cloudflare.com` only (`upsertARecord`, `src/cloud/providers.ts`), the token in the Authorization header alone, each call audited as `pinned:dns` like the other cloud calls; the record's id and zone are kept (`pinned_dns`) with the account that wrote it. A zone the token cannot see or edit, a CNAME already at the name, or any refusal leaves the record for a person to make, and the deploy answer and Check say that instead (`dnsWrittenBy` is empty). The token needs DNS edit on the zone; the cloud account's check cannot tell that, so the first write is the proof.
7373
74 ## Retiring a forge (#16219)
75
76 A test forge, or one whose buyer left, would bill forever without a way out. **Retire** (`POST /api/v1/admin/pinned/:name/retire`, the `pinned_forge` tool's `retire` verb, Retire on `/pinned`, `x` in the terminal) deletes the forge's machine and the DNS record the forge wrote for it (job above), and keeps its data volume: the answer says what keeping it costs a month at list price. The row ends `retired`, and the account's ceiling counts it at that volume's price alone. The volume is deleted only by the second word: `withData` on the API and the tool, **Retire and delete its data** on the page (which asks for the forge's name), and a second choice and the name in the terminal. That call is the data-destroying one under the delete tier (`tier: "delete"` on the tool, `test/delete-tier.test.ts`): the forge's own agent is refused it with the page to use. A **retired forge** can be retired again with its data, and nothing else: Update, Roll back, a new claim link and Check refuse it. It is idempotent: a machine or volume already gone at the cloud (a 404) is done, so asking again finishes a retire whose volume the cloud would not delete (the machine is gone and the forge `retired` by then, its data kept). A forge its buyer has claimed, as the forge itself says when asked (or as recorded), is refused with the sentence that its data is on that volume, unless `despiteClaim` says the owner means it (the page's form for a claimed forge carries it; the terminal asks in its question). One event, `pinned.retired`, says who, whether the data went, and what became of the record.
77
7478 ## After the claim: what the host can still do (#16204)
7579
7680 Nobody marks a forge claimed by hand: the deployed forge says so. Check, and every Update, Roll back and request for a new claim link, asks it first; when one hears `claimed` (The claim, above), the selling forge records it once (`pinned_forge.claimed_at`, event `pinned.claimed`). From then it refuses `update`, `rollback` and a new claim link for that forge, each with the same sentence (`CLAIMED_REFUSAL`): updates are the buyer's to take, and no machine of theirs is replaced from here. A forge that cannot be asked is never recorded as claimed, and is not taken as unclaimed either: once its current machine has answered about its claim (`pinned_forge.reached`), silence from it (a broken DNS record, a forge that is down) refuses Update, Roll back and a new claim link, with a sentence saying the forge could not be reached to confirm nobody claimed it and to run Check until it answers. A forge whose current machine has never answered (still booting, DNS not pointed yet, a first boot that failed) may still be replaced, or it could never be recovered. The question starts with a read of the machine at its cloud: when the cloud refuses that read the change is refused with the cloud's answer, before anything is recorded; a machine that is gone (404) has nobody to ask and is replaced. `/pinned` (once, when any forge is claimed) and `/deploy-to` say what the host still can while the machine is in the host's cloud account (`HOST_CAN` in `src/core/pinned.ts`): open its console, boot it into rescue, snapshot its disk, read its boot data. It never says "no access". The path that gives the host none is the buyer's own cloud account: deploy there (the account picker on `/deploy-to`; choosing it at purchase is #16203).
scripts/pinned-canary.ts +47 −10
@@ -1,6 +1,6 @@
11 /**
22 * `bun scripts/pinned-canary.ts <forge url> --account <name> --host <dns name> --app <owner/name> --source <https git url>
3 * --version <40-hex or vX.Y.Z> --next <second version> [--name <pinned name>] [--budget <seconds>]`
3 * --version <40-hex or vX.Y.Z> --next <second version> [--name <pinned name>] [--budget <seconds>] [--keep]`
44 *
55 * The canary for pinned forges (#8746): one real Deploy, Update and Rollback
66 * through the forge's admin API against a real cloud account, each step timed,
@@ -14,8 +14,11 @@
1414 * calls and does not wait for DNS, a certificate or a claim, and it drops the
1515 * deploy's one-time claim link unread.
1616 *
17 * It creates a droplet and a volume the driver cannot delete: remove them in
18 * the cloud console afterwards (the report names the ids).
17 * It cleans up after itself (#16219): at the end, pass or fail, it retires its canary with its data
18 * (the volume holds nothing worth keeping) and confirms from the forge's own list that no machine or
19 * volume is left. When the retire fails it says so loudly with the ids and what is left billing, and
20 * exits 1. `--keep` leaves the canary for inspection; then it is yours to retire (Pinned forges, or
21 * `POST /api/v1/admin/pinned/<name>/retire` with `withData`).
1922 */
2023
2124 export interface Step {
@@ -34,7 +37,8 @@ export interface Report {
3437 readonly failure: string | undefined;
3538 }
3639
37 type Call = (path: string, body: unknown) => Promise<{ status: number; json: Record<string, unknown> }>;
40 /** A POST with `body`, or a GET without one. */
41 type Call = (path: string, body?: unknown) => Promise<{ status: number; json: Record<string, unknown> }>;
3842
3943 const text = (v: unknown): string => (typeof v === "string" ? v : "");
4044
@@ -86,6 +90,32 @@ export function invalid(o: { version: string; next: string; source: string }): s
8690 return undefined;
8791 }
8892
93 export interface Cleaned {
94 readonly ok: boolean;
95 readonly message: string;
96 }
97
98 /**
99 * Retire the canary with its data and confirm, from the forge's list, that it has no machine and no
100 * volume left. A forge that was never made (the deploy was refused) has nothing to clean.
101 */
102 export async function cleanup(call: Call, name: string): Promise<Cleaned> {
103 let said = "";
104 try {
105 const r = await call(`/api/v1/admin/pinned/${name}/retire`, { withData: true });
106 said = text(r.json.message) || text(r.json.error);
107 if (r.status >= 300) return said.includes("No such pinned forge") ? { ok: true, message: "nothing was made, so nothing to retire" } : { ok: false, message: `retire: HTTP ${r.status} ${said}`.trim() };
108 const list = await call("/api/v1/admin/pinned");
109 const items = Array.isArray(list.json.items) ? (list.json.items as Record<string, unknown>[]) : [];
110 const row = items.find((i) => i.name === name);
111 if (row && (row.state !== "retired" || text(row.remote) !== "" || text(row.volume) !== ""))
112 return { ok: false, message: `the forge still lists ${name} as ${text(row.state)} with machine "${text(row.remote)}" and volume "${text(row.volume)}"` };
113 return { ok: true, message: "retired with its data; the forge lists no machine or volume for it" };
114 } catch (e) {
115 return { ok: false, message: `retire: ${e instanceof Error ? e.message : "request failed"}` };
116 }
117 }
118
89119 /** What a failed run may have left billing: every droplet and volume id the steps recorded. */
90120 export function leftovers(r: Report): string {
91121 const droplets = [...new Set(r.steps.map((s) => s.remote).filter(Boolean))];
@@ -115,14 +145,14 @@ if (import.meta.main) {
115145 const [account, host, app, source, version, next] = ["--account", "--host", "--app", "--source", "--version", "--next"].map(flag);
116146 const budget = Number(flag("--budget") ?? 600);
117147 if (!base?.startsWith("http") || !token || !account || !host || !app || !source || !version || !next || !(budget > 0)) {
118 console.error("usage: FORGE_TOKEN=<admin token> bun scripts/pinned-canary.ts <forge url> --account <n> --host <dns name> --app <owner/name> --source <https url> --version <v> --next <v2> [--name <n>] [--budget <s>]");
148 console.error("usage: FORGE_TOKEN=<admin token> bun scripts/pinned-canary.ts <forge url> --account <n> --host <dns name> --app <owner/name> --source <https url> --version <v> --next <v2> [--name <n>] [--budget <s>] [--keep]");
119149 process.exit(2);
120150 }
121151 const call: Call = async (path, body) => {
122152 const res = await fetch(new URL(path, base), {
123 method: "POST",
153 method: body === undefined ? "GET" : "POST",
124154 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
125 body: JSON.stringify(body),
155 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
126156 });
127157 return { status: res.status, json: (await res.json().catch(() => ({}))) as Record<string, unknown> };
128158 };
@@ -134,8 +164,15 @@ if (import.meta.main) {
134164 const name = flag("--name") ?? `canary-${new Date().toISOString().slice(0, 19).replace(/\D/g, "").replace(/^(\d{8})/, "$1-")}`;
135165 const report = await canary(call, () => performance.now() / 1000, { name, host, account, app, source, version, next, budget });
136166 console.log(table(report));
137 if (report.failure) {
138 console.error(`FAILED: ${report.failure}\nStill billing, remove in the cloud console: ${leftovers(report)}`);
139 process.exit(1);
167 if (report.failure) console.error(`FAILED: ${report.failure}`);
168 if (args.includes("--keep")) console.error(`--keep: ${name} is left running; retire it with its data when done (it bills until then): ${leftovers(report)}`);
169 else {
170 const cleaned = await cleanup(call, name);
171 console.error(`cleanup: ${cleaned.message}`);
172 if (!cleaned.ok) {
173 console.error(`!!! THE CANARY IS STILL BILLING. Retire ${name} by hand (Pinned forges, or the retire route with withData), or in the cloud console: ${leftovers(report)}. A forge's machine and its 10 GiB volume cost about what a small pinned forge does, until removed.`);
174 process.exit(1);
175 }
140176 }
177 if (report.failure) process.exit(1);
141178 }
src/actions/pinned.ts +93 −5
@@ -27,19 +27,20 @@
2727 import { resolve4 } from "node:dns/promises";
2828 import type { App } from "../app.ts";
2929 import { gatedFetch } from "../cloud/gate.ts";
30 import { capped, CeilingRefusal } from "../cloud/ceiling.ts";
30 import { capped, CeilingRefusal, priced, rowCents } from "../cloud/ceiling.ts";
3131 import { driverOf } from "../cloud/drivers.ts";
32 import { orderable, provision, read, replace } from "../cloud/machine.ts";
32 import { orderable, provision, read, replace, retire } from "../cloud/machine.ts";
33 import { dollars } from "../cloud/prices.ts";
3334 import { chooseDefault, meets, type Place } from "../cloud/places.ts";
3435 import { MAX_ID, keptPlaces, pinOf } from "../cloud/places_read.ts";
3536 import { keptRate } from "../cloud/rates.ts";
36 import { upsertARecord, type Fetch } from "../cloud/providers.ts";
37 import { deleteARecord, upsertARecord, type Fetch } from "../cloud/providers.ts";
3738 import { target as targetOf } from "../cloud/targets.ts";
3839 import { getCloudAccount, listCloudAccounts, secretNameOf } from "../core/cloud_account.ts";
3940 import { FIRST_ADMIN_SEED_TTL_MS, firstAdminLink, newFirstAdminCode, type SeedState } from "../core/first_admin.ts";
4041 import {
4142 APP, CLAIMED_REFUSAL, NAME, changesOf, checkConfig, dnsRecordOf, getPinned, insertPinned, listPinned, placeIdOf, previousOf,
42 dnsOf, dropPinned, keepDns, markClaimed, markReached, recordChange, setClaim, setHost, setRemote, urlOf, validHost, validSource, validVersion, unconfirmedRefusal, type Change, type Pinned,
43 dnsOf, dropDns, dropPinned, keepDns, markClaimed, markReached, recordChange, setClaim, setHost, setRemote, urlOf, validHost, validSource, validVersion, unconfirmedRefusal, type Change, type Pinned,
4344 } from "../core/pinned.ts";
4445 import { resolveSecrets } from "../core/secret_store.ts";
4546 import { DOMAIN_WORDS, getBaseDomain, parseBaseDomain, setBaseDomain } from "../settings/pinned_domain.ts";
@@ -65,6 +66,11 @@ export interface PinnedView extends Omit<Pinned, "claimHash"> {
6566 * The DNS record its name needs, `<host> A <address>`, once the address is read; empty before.
6667 */
6768 readonly dns: string;
69 /**
70 * What keeping a retired forge's data volume costs a month, US cents at list price; zero while
71 * the forge runs, and once its volume is deleted.
72 */
73 readonly keepCents: number;
6874 /**
6975 * The cloud account whose token wrote that record (`cloudflare/main`), when this forge did; empty
7076 * while the record is for a person to make.
@@ -80,7 +86,8 @@ const view = (app: App, p: Pinned): PinnedView => {
8086 const { claimHash: _kept, ...shown } = p;
8187 const kept = dnsOf(app.db, p.id);
8288 const written = kept !== undefined && kept.host === p.host && kept.address === p.address;
83 return { ...shown, url: urlOf(p), dns: dnsRecordOf(p), dnsWrittenBy: written ? `cloudflare/${kept.account}` : "", crew: false, autoRelease: false, changes: changesOf(app.db, p.id) };
89 const keepCents = p.state === "retired" && p.volume !== "" ? rowCents(p, priced(app.db)) : 0;
90 return { ...shown, url: urlOf(p), dns: dnsRecordOf(p), keepCents, dnsWrittenBy: written ? `cloudflare/${kept.account}` : "", crew: false, autoRelease: false, changes: changesOf(app.db, p.id) };
8491 };
8592
8693 /** A claim just issued: the link is in this value and nowhere else, so it is shown once. */
@@ -127,6 +134,9 @@ export function deployPlaces(app: App, providers: readonly string[]): Place[] {
127134 }
128135
129136 const HOST_WORDS = "A hostname is a full DNS name you control, such as forge.example.com: lowercase letters, digits, dashes and dots.";
137 const RETIRED_REFUSAL = "This forge was retired: its machine is gone. Deploy it again, under a new name, to run it.";
138 const RETIRE_CLAIMED =
139 "This forge was handed to its buyer: its data is on that volume, and retiring it deletes their forge. If you mean to, retire it again and say so (despiteClaim); this forge will not retire it otherwise.";
130140 const HOST_NEEDED = "Name the host the forge is served on, such as forge.example.com; or set a domain for deployed forges on Pinned forges, and each is served on <name>.<domain> with no hostname given.";
131141 const NAMELESS = "This forge was deployed before forges had names: issue a claim for it with a hostname first.";
132142
@@ -215,6 +225,25 @@ async function followWithDns(app: App, who: User, name: string): Promise<void> {
215225 await writeDns(app, who, name);
216226 }
217227
228 /** The record the forge wrote is removed with the forge: "none" when it wrote none, else removed, or "kept" when Cloudflare would not let it. */
229 async function unwriteDns(app: App, who: User, name: string): Promise<"none" | "removed" | "kept"> {
230 const p = getPinned(app.db, name)!;
231 const kept = dnsOf(app.db, p.id);
232 if (kept === undefined) return "none";
233 // The account that wrote it first, then any other that may write.
234 const writers = dnsWriters(app).sort((a, b) => Number(b.name === kept.account) - Number(a.name === kept.account));
235 for (const a of writers) {
236 const secret = secretNameOf(a.provider, a.name);
237 const token = resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], { actor: who.id, run: "pinned:dns" })[secret];
238 if (token === undefined) continue;
239 const f = gatedFetch(app.db, { provider: a.provider, account: a.name }, "pinned:dns", net.fetch);
240 if ((await deleteARecord(f, token, kept.zone, kept.record)) === "refused") continue;
241 dropDns(app.db, p.id);
242 return "removed";
243 }
244 return "kept";
245 }
246
218247 /** Open the account's token and run `go` with a gated fetch; the token never leaves this scope. */
219248 async function withCloud<T>(app: App, who: User, p: Pinned, purpose: string, go: (f: Fetch, token: string) => Promise<T>, writes = true): Promise<Result<T, string>> {
220249 const account = getCloudAccount(app.db, p.target, p.account);
@@ -353,6 +382,7 @@ async function changeNow(
353382 if (!who.ok) return who;
354383 const before = getPinned(app.db, name);
355384 if (!before) return err("No such pinned forge.");
385 if (before.state === "retired") return err(RETIRED_REFUSAL);
356386 if (before.claimedAt !== "") return err(CLAIMED_REFUSAL);
357387 if (before.host === "") return err(NAMELESS);
358388 const to = next(before);
@@ -430,6 +460,7 @@ async function claimNow(app: App, actor: User | undefined, name: string, input:
430460 if (!who.ok) return who;
431461 const before = getPinned(app.db, name);
432462 if (!before) return err("No such pinned forge.");
463 if (before.state === "retired") return err(RETIRED_REFUSAL);
433464 if (before.claimedAt !== "") return err(CLAIMED_REFUSAL);
434465 const asked = (input.host ?? "").trim().toLowerCase();
435466 if (before.host === "" && asked === "" && getBaseDomain(app.db) === "") return err(NAMELESS);
@@ -534,6 +565,62 @@ async function sellersStill(app: App, who: User, name: string): Promise<Result<t
534565 return ok(true);
535566 }
536567
568 /** What retiring did, beside the forge's row: what became of the DNS record the forge had written. */
569 export type Retired = PinnedView & { readonly dnsRemoved: "none" | "removed" | "kept" };
570
571 /**
572 * Retire a forge: its machine is deleted and its volume kept, or deleted too with `withData`; the
573 * record the forge wrote for it is removed; the row ends `retired` and costs only the volume it
574 * kept. A machine or volume already gone at the provider is done, so the same call asked again
575 * finishes a failed one, and a retired forge asked again changes nothing. A forge the deployed
576 * forge says is claimed is refused unless `despiteClaim`: the buyer's data is on that volume. One
577 * change at a time per forge, like an Update.
578 */
579 export const retirePinned = (app: App, actor: User | undefined, name: string, o: { withData?: boolean | undefined; despiteClaim?: boolean | undefined } = {}): Promise<Result<Retired, string>> =>
580 oneChange(app, name, () => retireNow(app, actor, name, o));
581
582 async function retireNow(app: App, actor: User | undefined, name: string, o: { withData?: boolean | undefined; despiteClaim?: boolean | undefined }): Promise<Result<Retired, string>> {
583 const who = admin(actor);
584 if (!who.ok) return who;
585 const before = getPinned(app.db, name);
586 if (!before) return err("No such pinned forge.");
587 const withData = o.withData === true;
588 const done = (p: Pinned, dnsRemoved: Retired["dnsRemoved"]): Result<Retired, string> => ok({ ...view(app, p), dnsRemoved });
589 if (before.state === "retired" && (before.volume === "" || !withData)) return done(before, "none");
590 if (o.despiteClaim !== true) {
591 if (before.claimedAt !== "") return err(RETIRE_CLAIMED);
592 if (before.state !== "retired") {
593 const ours = await sellersStill(app, who.value, name);
594 if (!ours.ok) return err(ours.error === CLAIMED_REFUSAL ? RETIRE_CLAIMED : `${ours.error} If you mean to retire it anyway, say so (despiteClaim).`);
595 }
596 }
597 const p = getPinned(app.db, name)!;
598 const gone = await withCloud(app, who.value, p, "retire", (f, token) =>
599 retire(driverOf(p.target), f, token, p, { withData }, {
600 onMachineGone: () => setRemote(app.db, name, { remote: "", address: "", state: "retired" }),
601 onVolumeGone: () => setRemote(app.db, name, { volume: "" }),
602 }),
603 );
604 if (!gone.ok) {
605 // The machine went and the volume's delete was refused: the forge is retired, its data kept.
606 const now = getPinned(app.db, name)!;
607 return err(now.state === "retired" && before.state !== "retired" ? `${gone.error} Its machine is deleted and it is retired; its volume is kept: retire it with its data again to delete that.` : gone.error);
608 }
609 const dnsRemoved = await unwriteDns(app, who.value, name);
610 app.bus.append({ kind: "pinned.retired", actorId: who.value.id, payload: { name, withData, claimed: before.claimedAt !== "", dns: dnsRemoved } });
611 return done(getPinned(app.db, name)!, dnsRemoved);
612 }
613
614 /** What retiring did, in the one sentence every door says. */
615 export function retireWords(v: Retired): string {
616 const dns = v.dnsRemoved === "removed" ? ", and the DNS record the forge wrote for it is removed" : v.dnsRemoved === "kept" ? `; its DNS record ${v.host} could not be removed and is yours to delete` : "";
617 const data =
618 v.volume === ""
619 ? "Its data volume is deleted too: nothing of it is left to bill."
620 : `Its data volume is kept and ${v.keepCents > 0 ? `costs about ${dollars(v.keepCents)} a month at list price` : "is billed by its cloud"}; retire it with its data to delete it, which cannot be undone.`;
621 return `${v.name} is retired: its machine is deleted${dns}. ${data}`;
622 }
623
537624 export type Checked = PinnedView & { readonly healthy: boolean; readonly waiting: Waiting; readonly claim: ClaimState };
538625
539626 /** What a check found, in the one sentence every door says. */
@@ -575,6 +662,7 @@ export async function checkPinned(app: App, actor: User | undefined, name: strin
575662 if (!who.ok) return who;
576663 const p = getPinned(app.db, name);
577664 if (!p) return err("No such pinned forge.");
665 if (p.state === "retired") return err(RETIRED_REFUSAL);
578666 if (p.remote === "") return err("This forge has no droplet yet; deploy or update it first.");
579667 const read = await readAddress(app, who.value, name);
580668 if (!read.ok) return read;
src/cloud/ceiling.ts +28 −3
@@ -20,8 +20,9 @@ import type { App } from "../app.ts";
2020 import { getCloudAccount } from "../core/cloud_account.ts";
2121 import { getPinned, listPinned, placeIdOf, type Pinned } from "../core/pinned.ts";
2222 import type { Driver } from "./machine.ts";
23 import { DO_VOLUME_USD_PER_GIB, VOLUME_GIB } from "./places.ts";
2324 import { keptPlaces } from "./places_read.ts";
24 import { dollars, toUsd } from "./prices.ts";
25 import { dollars, toUsd, type Rate } from "./prices.ts";
2526 import { keptRate } from "./rates.ts";
2627
2728 export const DEFAULT_CEILING_DOLLARS = 50;
@@ -42,10 +43,31 @@ export interface Priced {
4243 /** The price of a Places id (`provider:datacenter:size`). */
4344 forge(id: string): number | undefined;
4445 dearest(cloud: string, datacenter?: string): number | undefined;
46 /** What keeping a forge's data volume alone costs a month on a cloud, in US cents rounded up. */
47 volume(cloud: string): number | undefined;
4548 /** Why a listed place cannot be ordered now; undefined when it can, or is not listed. */
4649 closed(id: string): string | undefined;
4750 }
4851
52 /**
53 * What a cloud charges a month for the forge's data volume alone, US cents rounded up: DigitalOcean's
54 * list price per GiB, Hetzner's own per-GiB price in its currency at `rate`, as the catalog last
55 * read them. Undefined when the cloud was not read, or has no price or no rate for a volume.
56 */
57 function keptVolumeCents(db: Database, provider: string, rate: Rate | undefined): number | undefined {
58 if (provider === "digitalocean") return toUsd(DO_VOLUME_USD_PER_GIB * VOLUME_GIB, "USD", undefined, "up").usdCents;
59 if (provider !== "hetzner") return undefined;
60 try {
61 const row = db.query<{ body: string }, [string]>("SELECT body FROM place_read WHERE provider = ?1").get(provider);
62 const pricing: any = (JSON.parse(row?.body ?? "{}") as any).pricing;
63 const body = pricing?.pricing ?? pricing;
64 const perGib = Number(body?.volume?.price_per_gb_month?.gross);
65 return Number.isFinite(perGib) ? toUsd(perGib * VOLUME_GIB, String(body?.currency ?? "EUR").toUpperCase(), rate, "up").usdCents : undefined;
66 } catch {
67 return undefined;
68 }
69 }
70
4971 export function priced(db: Database): Priced {
5072 const rate = keptRate(db, "EUR");
5173 const cents = new Map<string, { cloud: string; datacenter: string; cents: number }>();
@@ -61,6 +83,7 @@ export function priced(db: Database): Priced {
6183 }
6284 }
6385 return {
86 volume: (cloud) => keptVolumeCents(db, cloud, rate),
6487 forge: (id) => cents.get(id)?.cents,
6588 dearest: (cloud, datacenter) => {
6689 const mine = [...cents.values()].filter((c) => c.cloud === cloud);
@@ -72,7 +95,7 @@ export function priced(db: Database): Priced {
7295 };
7396 }
7497
75 type Row = Pick<Pinned, "target" | "remote" | "volume" | "datacenter" | "size">;
98 type Row = Pick<Pinned, "target" | "remote" | "volume" | "datacenter" | "size" | "state">;
7699
77100 /**
78101 * What one pinned row costs a month, cents. A row with a machine or a volume is counted as the
@@ -80,10 +103,12 @@ type Row = Pick<Pinned, "target" | "remote" | "volume" | "datacenter" | "size">;
80103 * its machine is about to be one. A place the catalog no longer lists is counted at the dearest
81104 * the cloud has in that datacenter: the reckoning errs high. Zero only for a row with nothing
82105 * made, or when the catalog holds nothing for the cloud at all (then nothing new is admitted
83 * either).
106 * either). A retired forge costs only the volume it kept (the whole forge's price when the catalog
107 * has none for volumes), and nothing once the volume is deleted.
84108 */
85109 export function rowCents(p: Row, prices: Priced): number {
86110 if (p.remote === "" && p.volume === "") return 0;
111 if (p.state === "retired") return p.volume === "" ? 0 : (prices.volume(p.target) ?? prices.forge(placeIdOf(p)) ?? prices.dearest(p.target, p.datacenter) ?? 0);
87112 return prices.forge(placeIdOf(p)) ?? prices.dearest(p.target, p.datacenter) ?? 0;
88113 }
89114
src/cloud/droplet.ts +3
@@ -43,6 +43,9 @@ export const digitalocean: Driver = {
4343 async deleteMachine(call, remote) {
4444 await call("DELETE", `/droplets/${remote}`);
4545 },
46 async deleteVolume(call, volume) {
47 await call("DELETE", `/volumes/${volume}`);
48 },
4649 async readMachine(call, remote) {
4750 const d = (await call("GET", `/droplets/${remote}`)).droplet;
4851 const v4: unknown[] = Array.isArray(d?.networks?.v4) ? d.networks.v4 : [];
src/cloud/hetzner.ts +3
@@ -46,6 +46,9 @@ export const hetzner: Driver = {
4646 async deleteMachine(call, remote) {
4747 await call("DELETE", `/servers/${remote}`);
4848 },
49 async deleteVolume(call, volume) {
50 await call("DELETE", `/volumes/${volume}`);
51 },
4952 async readMachine(call, remote) {
5053 const s = (await call("GET", `/servers/${remote}`)).server;
5154 return { status: String(s?.status ?? ""), address: ipv4(s?.public_net?.ipv4?.ip) };
src/cloud/machine.ts +35
@@ -155,6 +155,8 @@ export interface Driver {
155155 /** Make the machine with the volume attached; returns its id. */
156156 createMachine(call: Call, p: Pinned, volume: string): Promise<string>;
157157 deleteMachine(call: Call, remote: string): Promise<void>;
158 /** Delete the data volume: nothing of the forge's data is left once this answers. */
159 deleteVolume(call: Call, volume: string): Promise<void>;
158160 readMachine(call: Call, remote: string): Promise<{ status: string; address: string }>;
159161 }
160162
@@ -228,6 +230,39 @@ export async function orderable(d: Driver, p: Pinned): Promise<void> {
228230 d.admit?.(p);
229231 }
230232
233 /** What a volume's id may look like on the way into a path: DigitalOcean's are UUIDs, Hetzner's numbers. */
234 const VOLUME = /^[A-Za-z0-9-]{1,64}$/;
235
236 /** A delete that finds the thing already gone is a delete that is done. */
237 async function gone(go: () => Promise<void>): Promise<void> {
238 try {
239 await go();
240 } catch (e) {
241 if (!(e instanceof Error && e.message.endsWith("answered 404"))) throw e;
242 }
243 }
244
245 /**
246 * Retire a forge's machine, and with `withData` its volume too, in that order: the machine is
247 * deleted (`onMachineGone` clears the recorded id at once), then the volume only when asked. A
248 * machine or volume already gone at the provider (404) is done, so the same call asked again
249 * finishes what a failed one left. Makes nothing, so there is no ceiling to hold it to.
250 */
251 export async function retire(
252 d: Driver, f: Fetch, token: string, p: Pinned, o: { withData: boolean }, hooks: { onMachineGone(): void; onVolumeGone(): void },
253 ): Promise<void> {
254 const call = caller(d, f, token);
255 if (p.remote !== "") {
256 if (!ID.test(p.remote)) throw new Error("this forge has no machine to delete");
257 await gone(() => d.deleteMachine(call, p.remote));
258 }
259 hooks.onMachineGone();
260 if (!o.withData || p.volume === "") return;
261 if (!VOLUME.test(p.volume)) throw new Error("this forge's volume has no id the forge can delete");
262 await gone(() => d.deleteVolume(call, p.volume));
263 hooks.onVolumeGone();
264 }
265
231266 const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)$/;
232267 /** Only a well-formed IPv4 address is ever kept. */
233268 export const ipv4 = (v: unknown): string => (typeof v === "string" && IPV4.test(v) ? v : "");
src/cloud/providers.ts +15 −1
@@ -5,7 +5,7 @@
55 *
66 * cloudflare GET api.cloudflare.com/client/v4/user/tokens/verify, /zones
77 * a pinned forge's A record (`upsertARecord`): GET /zones?name=, GET, POST and PATCH
8 * /zones/{id}/dns_records
8 * /zones/{id}/dns_records, and DELETE of the one it wrote (`deleteARecord`)
99 * digitalocean GET api.digitalocean.com/v2/account, /projects, /droplets,
1010 * /volumes, /reserved_ips
1111 * hetzner GET api.hetzner.cloud/v1/servers, /volumes
@@ -134,6 +134,20 @@ async function cloudflare(f: Fetch, token: string, method: string, path: string,
134134 return { status: res.status, body: await res.json().catch(() => ({})) };
135135 }
136136
137 /**
138 * Delete the record a forge wrote (`upsertARecord` returned its zone and id): "deleted", "gone" when
139 * Cloudflare no longer has it, or "refused" (a token that cannot edit the zone, any other answer).
140 */
141 export async function deleteARecord(f: Fetch, token: string, zone: string, record: string): Promise<"deleted" | "gone" | "refused"> {
142 if (!CF_ID.test(zone) || !CF_ID.test(record)) return "refused";
143 try {
144 const r = await cloudflare(f, token, "DELETE", `/zones/${zone}/dns_records/${record}`);
145 return r.status === 200 ? "deleted" : r.status === 404 ? "gone" : "refused";
146 } catch {
147 return "refused";
148 }
149 }
150
137151 /**
138152 * Make `host` an A record for `address` in the Cloudflare zone that holds it: DNS only (never
139153 * proxied, so the forge's own certificate is issued), a one-minute TTL. The record is found by
src/contract/openapi/routes/index.ts +1
@@ -301,6 +301,7 @@ export { route as postApiV1AdminMaintenanceResume } from "./postApiV1AdminMainte
301301 export { route as postApiV1AdminPinned } from "./postApiV1AdminPinned.ts";
302302 export { route as postApiV1AdminPinnedNameCheck } from "./postApiV1AdminPinnedNameCheck.ts";
303303 export { route as postApiV1AdminPinnedNameClaim } from "./postApiV1AdminPinnedNameClaim.ts";
304 export { route as postApiV1AdminPinnedNameRetire } from "./postApiV1AdminPinnedNameRetire.ts";
304305 export { route as postApiV1AdminPinnedNameRollback } from "./postApiV1AdminPinnedNameRollback.ts";
305306 export { route as postApiV1AdminPinnedNameUpdate } from "./postApiV1AdminPinnedNameUpdate.ts";
306307 export { route as postApiV1AdminReleasesShaRollback } from "./postApiV1AdminReleasesShaRollback.ts";
src/contract/openapi/routes/postApiV1AdminPinnedNameRetire.ts added +16
@@ -0,0 +1,16 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: "/api/v1/admin/pinned/{name}/retire",
6 summary: "Retire a pinned forge: delete its machine, keep its data unless told",
7 detail:
8 "Retire a pinned forge: its machine is deleted and the DNS record the forge wrote for it is removed; the data volume is kept, and the answer says what keeping it costs a month, unless `withData` is true, which deletes the volume too and cannot be undone; the row ends `retired`. A machine or volume already gone at the provider is done, so asking again finishes a failed retire. A forge its buyer has claimed is refused unless `despiteClaim` is true: its data is on that volume. Answers the forge with { says, dnsRemoved, keepCents }",
9 auth: true,
10 role: "admin",
11 body: { withData: "boolean", despiteClaim: "boolean" },
12 refusals: {
13 not_found: "only a forge administrator sees this route",
14 refused: "the request was understood and refused; the message says why (422)",
15 },
16 };
src/core/pinned.ts +5
@@ -281,6 +281,11 @@ export function dnsOf(db: Database, pinnedId: string): DnsKept | undefined {
281281 return db.query<DnsKept, [string]>("SELECT account, zone, record, host, address FROM pinned_dns WHERE pinned_id = ?1").get(pinnedId) ?? undefined;
282282 }
283283
284 /** The forge's record is gone from the cloud: forget it. */
285 export function dropDns(db: Database, pinnedId: string): void {
286 db.query("DELETE FROM pinned_dns WHERE pinned_id = ?1").run(pinnedId);
287 }
288
284289 /** Keep the record this forge wrote; a forge has one row, so a new address replaces it. */
285290 export function keepDns(db: Database, pinnedId: string, d: DnsKept): void {
286291 db.query(
src/http/api/admin.ts +11 −1
@@ -23,7 +23,7 @@ import { inviteLink, list as listInviteLinks, mint as mintInviteLink, revoke as
2323 import { changeLimit, listLimits } from "../../actions/limits.ts";
2424 import { changePlans } from "../../actions/plans.ts";
2525 import { setAccountCeilings, setAccountGrant } from "../../actions/model_grant.ts";
26 import { DOMAIN_WORDS, changeBaseDomain, checkPinned, claimPinned, deployPinned, pinnedForges, readBaseDomain, rollbackPinned, updatePinned } from "../../actions/pinned.ts";
26 import { DOMAIN_WORDS, changeBaseDomain, checkPinned, claimPinned, deployPinned, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, updatePinned } from "../../actions/pinned.ts";
2727 import { TARGETS } from "../../cloud/targets.ts";
2828 import { changeQuotas, readQuotas } from "../../actions/quotas.ts";
2929 import { allowRequest, declineRequest, listRequests } from "../../actions/requests.ts";
@@ -122,6 +122,16 @@ export function adminRoutes(router: Router<Handler>): void {
122122 return done.ok ? json(done.value) : pinnedFail(done.error);
123123 });
124124
125 // Delete a forge's machine and keep its data; `withData` deletes the volume too, and
126 // `despiteClaim` retires a forge its buyer has claimed.
127 router.add("POST", "/api/v1/admin/pinned/:name/retire", async (ctx) => {
128 const denied = accountAdmin(ctx, "admin");
129 if (denied) return denied;
130 const i = await body(ctx.request);
131 const done = await retirePinned(ctx.app, ctx.auth.user, ctx.params.name!, { withData: i.withData === true, despiteClaim: i.despiteClaim === true });

HIGH. withData: true alone deletes the data volume. Require a confirm string equal to the forge's name for withData (and on the MCP tool), so deleting data always needs the name typed. Update the openapi body, the canary and the docs line with it.

132 return done.ok ? json({ ...done.value, says: retireWords(done.value) }) : pinnedFail(done.error);
133 });
134
125135 router.add("POST", "/api/v1/admin/pinned/:name/rollback", async (ctx) => {
126136 const denied = accountAdmin(ctx, "admin");
127137 if (denied) return denied;
src/http/mcp/tools/pinned_forge.ts +14 −5
@@ -1,4 +1,4 @@
1 import { DOMAIN_WORDS, changeBaseDomain, checkPinned, checkWords, claimPinned, claimWords, deployPinned, pinnedForges, readBaseDomain, rollbackPinned, updatePinned } from "../../../actions/pinned.ts";
1 import { DOMAIN_WORDS, changeBaseDomain, checkPinned, checkWords, claimPinned, claimWords, deployPinned, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, updatePinned } from "../../../actions/pinned.ts";
22 import { TARGETS } from "../../../cloud/targets.ts";
33 import { scopeAllows } from "../../../core/tokens.ts";
44 import { good, bad, type Tool, str } from "../shared.ts";
@@ -6,12 +6,17 @@ import { good, bad, type Tool, str } from "../shared.ts";
66 export const tool: Tool = {
77 name: "pinned_forge",
88 listedTo: "admin",
9 doc: "`{ verb, name?, host?, domain?, target?, account?, app?, source?, version?, place?, config? }`: a forge on the owner's cloud. `deploy`: `app` from `source` at `version` on a writable `account`, at `place` (default: the small plan's), on `host` (default `<name>.<domain>`; Cloudflare writes the record); answers once with `claim.link` and `dns`. `claim`: a fresh link while unclaimed. `update`: change `version` or `config`. `rollback`: back one. `domain`: read or set the domain. `check`: `waiting` or `url`, `healthy`, `claim`. `list`: all, with changes. A forge admin with an admin-scope token",
10 description: "Pinned forges on your cloud: list, deploy, claim, update, rollback, check (admin).",
9 doc: "`{ verb, name?, host?, domain?, withData?, despiteClaim?, target?, account?, app?, source?, version?, place?, config? }`: a forge on the owner's cloud. `deploy`: `app` from `source` at `version` on a writable `account`, at `place` (default: the small plan's), on `host` (default `<name>.<domain>`; Cloudflare writes the record); answers once with `claim.link` and `dns`. `claim`: a fresh link while unclaimed. `update`: change `version` or `config`. `rollback`: back one. `domain`: read or set the domain. `check`: `waiting` or `url`, `healthy`, `claim`. `retire`: delete the machine, keep the data (`withData` deletes it). `list`: all, with changes. A forge admin with an admin-scope token",
10 description: "Pinned forges on your cloud: list, deploy, claim, update, rollback, check, retire (admin).",
11 tier: "delete",
12 deletes: (args) => args["verb"] === "retire" && args["withData"] === true,
13 where: "on the Pinned forges page (/pinned), where Retire and delete its data asks for the forge's name",
1114 inputSchema: {
1215 type: "object",
1316 properties: {
14 verb: { type: "string", enum: ["list", "deploy", "claim", "update", "rollback", "check", "domain"] },
17 verb: { type: "string", enum: ["list", "deploy", "claim", "update", "rollback", "check", "domain", "retire"] },
18 withData: { type: "boolean", description: "Retire: delete the data too; no undo." },
19 despiteClaim: { type: "boolean", description: "Retire a forge its buyer claimed." },
1520 domain: { type: "string", maxLength: 253, description: "Domain for deployed forges; empty clears." },
1621 name: { type: "string", maxLength: 40 },
1722 host: { type: "string", maxLength: 253, description: "The DNS name it is served on over HTTPS." },
@@ -61,6 +66,10 @@ export const tool: Tool = {
6166 if (!made.ok) return bad("refused", made.error);
6267 return good({ says: `${verb} ${name}: now ${made.value.version}, ${made.value.state} at ${made.value.url}. ${claimWords(made.value)}`, claim: made.value.claim, forge: made.value });
6368 }
69 if (verb === "retire") {
70 const done = await retirePinned(ctx.app, user, name, { withData: args["withData"] === true, despiteClaim: args["despiteClaim"] === true });
71 return done.ok ? good({ says: retireWords(done.value), forge: done.value }) : bad("refused", done.error);
72 }
6473 if (verb === "check") {
6574 const seen = await checkPinned(ctx.app, user, name);
6675 return seen.ok ? good({ says: `check ${name}: now ${seen.value.version}. ${checkWords(seen.value)}`, forge: seen.value }) : bad("refused", seen.error);
@@ -74,7 +83,7 @@ export const tool: Tool = {
7483 : verb === "rollback"
7584 ? await rollbackPinned(ctx.app, user, name)
7685 : undefined;
77 if (done === undefined) return bad("bad_verb", "verb is list, deploy, claim, update, rollback, check or domain");
86 if (done === undefined) return bad("bad_verb", "verb is list, deploy, claim, update, rollback, check, retire or domain");
7887 if (!done.ok) return bad("refused", done.error);
7988 return good({ says: `${verb} ${name}: now ${done.value.version}, ${done.value.state}${done.value.url ? ` at ${done.value.url}` : ""}.`, forge: done.value });
8089 },
src/http/pinned_routes.ts +6 −1
@@ -7,7 +7,7 @@
77 * never through a redirect or a flash: it is shown once and stored nowhere.
88 */
99
10 import { DOMAIN_WORDS, changeBaseDomain, checkPinned, checkWords, claimPinned, deployPinned, deployPlaces, pinnedForges, rollbackPinned, updatePinned, type Issued } from "../actions/pinned.ts";
10 import { DOMAIN_WORDS, changeBaseDomain, checkPinned, checkWords, claimPinned, deployPinned, deployPlaces, pinnedForges, retirePinned, retireWords, rollbackPinned, updatePinned, type Issued } from "../actions/pinned.ts";
1111 import { TARGETS } from "../cloud/targets.ts";
1212 import { listCloudAccounts } from "../core/cloud_account.ts";
1313 import { lastCheckOf } from "../core/pinned.ts";
@@ -107,6 +107,11 @@ async function pinnedAct(ctx: Ctx): Promise<Response> {
107107 else if (act === "check") {
108108 const seen = await checkPinned(ctx.app, user, name);
109109 return flashTo(ctx, "/pinned", seen.ok ? { tone: seen.value.healthy ? "success" : "attn", message: checkWords(seen.value) } : { tone: "danger", message: seen.error });
110 } else if (act === "retire" || act === "retire-data") {
111 // Retire keeps the data; Retire and delete its data is its own act, behind the name typed on
112 // the confirm page. A claimed forge is retired only when the form says the owner means it.
113 const gone = await retirePinned(ctx.app, user, name, { withData: act === "retire-data", despiteClaim: field(form, "despite_claim") === "1" });

HIGH. retire-data deletes the volume with no check of a typed name here; only the confirm page's browser form asks for it. Read the typed name from the form and pass it down, so retirePinned can refuse withData unless it matches the forge's name. A direct POST must delete nothing.

114 return flashTo(ctx, "/pinned", gone.ok ? { tone: "success", message: retireWords(gone.value) } : { tone: "danger", message: gone.error });
110115 } else if (act === "claim") {
111116 const made = await claimPinned(ctx.app, user, name, { host: field(form, "host") });
112117 return made.ok ? shown(ctx, `A new claim link for ${name}`, made.value) : flashTo(ctx, "/pinned", { tone: "danger", message: made.error });
src/tui/screens/pinned.ts +47 −3
@@ -4,13 +4,14 @@
44 * updates (the only way its version or config move), `r` rolls back to the
55 * previous version, `c` reads the address back and probes it, `n` issues a
66 * new claim link (shown once, as a deploy's is), `b` sets the domain deployed forges are served on
7 * (a deploy then needs no hostname: `-` in its place), each through
7 * (a deploy then needs no hostname: `-` in its place), `x` retires a forge (its machine goes, its data
8 * is kept unless the name is typed to delete it too; a claimed forge is asked about twice), each through
89 * `actions/pinned.ts`, so the checks, the record of who and when and the events
910 * the web screens follow are the API's.
1011 * Anyone else sees nothing and does nothing.
1112 */
1213
13 import { DOMAIN_WORDS, changeBaseDomain, checkPinned, checkWords, claimPinned, claimWords, deployPinned, pinnedForges, readBaseDomain, rollbackPinned, updatePinned, type Issued } from "../../actions/pinned.ts";
14 import { DOMAIN_WORDS, changeBaseDomain, checkPinned, checkWords, claimPinned, claimWords, deployPinned, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, updatePinned, type Issued } from "../../actions/pinned.ts";
1415 import type { Ctx, Screen } from "../app/app.ts";
1516 import { binding } from "../app/keys.ts";
1617 import { style } from "../term/style.ts";
@@ -60,6 +61,48 @@ function offerClaim(f: Session, ctx: Ctx, screen: Screen, say: (text: string) =>
6061 );
6162 }
6263
64 /**
65 * `x`: retire. The machine goes and the data stays, unless the forge's name is typed to delete the
66 * data too (the page's confirm step); a forge its buyer has claimed says so in the question, and
67 * is retired only on that answer.
68 */
69 function offerRetire(f: Session, ctx: Ctx, screen: Screen, say: (text: string) => void, p: { name: string; claimedAt: string; state: string; volume: string }): void {
70 const claimed = p.claimedAt !== "";
71 const run = (withData: boolean): void => {
72 say(`Retiring ${p.name}…`);
73 void retirePinned(f.app, f.user, p.name, { withData, despiteClaim: claimed }).then((r) => say(r.ok ? retireWords(r.value) : r.error));
74 };
75 if (p.state === "retired" && p.volume === "") return say(`${p.name} is retired and has no data kept.`);
76 const deleteData = (): Screen =>
77 promptScreen(ctx, screen, {
78 title: `Delete ${p.name}'s data`,
79 label: `type ${p.name} to delete its machine and its data volume; this cannot be undone`,
80 onSubmit: (typed) => {
81 if (typed.trim() !== p.name) return "That is not its name; nothing was changed.";
82 run(true);
83 return undefined;
84 },
85 });
86 const keep = p.state === "retired";
87 ctx.push(
88 confirmScreen(ctx, screen, {
89 title: keep ? `Delete ${p.name}'s kept data?` : `Retire ${p.name}?`,
90 body: [
91 ...(claimed ? ["This forge was handed to its buyer: their data is on its volume, and retiring it deletes their forge."] : []),
92 keep ? "Its machine is already gone; its volume is kept." : "Its machine is deleted and its DNS record, if the forge wrote it, is removed. Its data volume is kept and keeps costing.",
93 ],
94 actions: [...(keep ? [] : [{ label: claimed ? "Retire the buyer's forge, keep data" : "Retire, keep its data" }]), { label: "Delete its data too…", variant: "danger" as const }, { label: "Cancel" }],
95 width: 100,
96 onChoose: (i) => {
97 if (i < 0) return;
98 const choice = keep ? i + 1 : i;
99 if (choice === 0) run(false);
100 else if (choice === 1) later(ctx, deleteData);
101 },
102 }),
103 );
104 }
105
63106 export function pinnedScreen(f: Session, ctx: Ctx): Screen {
64107 const state = new ListState();
65108 let note = "";
@@ -94,7 +137,7 @@ export function pinnedScreen(f: Session, ctx: Ctx): Screen {
94137
95138 const screen: Screen = {
96139 title: "Pinned forges",
97 keys: [binding(["j", "k"], "move cursor"), binding(["d"], "deploy"), binding(["u"], "update"), binding(["r"], "roll back"), binding(["c"], "check"), binding(["n"], "new claim link"), binding(["b"], "domain for forges")],
140 keys: [binding(["j", "k"], "move cursor"), binding(["d"], "deploy"), binding(["u"], "update"), binding(["r"], "roll back"), binding(["c"], "check"), binding(["n"], "new claim link"), binding(["b"], "domain for forges"), binding(["x"], "retire")],
98141 async load(signal) {
99142 live(f, signal, { kinds: ["pinned.deployed", "pinned.update", "pinned.rollback", "pinned.check", "pinned.claim_issued", "pinned.claimed"] }, () => ctx.invalidate());
100143 },
@@ -146,6 +189,7 @@ export function pinnedScreen(f: Session, ctx: Ctx): Screen {
146189 say(`Checking ${p.name}…`);
147190 void checkPinned(f.app, f.user, p.name).then((r) => say(r.ok ? checkWords(r.value) : r.error));
148191 } else if (e.key === "n") offerClaim(f, ctx, screen, say, p);
192 else if (e.key === "x") offerRetire(f, ctx, screen, say, p);
149193 else if (e.key === "u")
150194 ctx.push(
151195 promptScreen(ctx, screen, {
src/web/pages/pinned.ts +14 −1
@@ -5,6 +5,7 @@
55 */
66
77 import type { PinnedView } from "../../actions/pinned.ts";
8 import { dollars } from "../../cloud/prices.ts";
89 import { HOST_CAN } from "../../core/pinned.ts";
910 import { html, type Html } from "../html.ts";
1011 import { badge, btn, field, time, type Tone } from "../ui.ts";
@@ -33,7 +34,16 @@ function actions(p: PinnedView): Html {
3334 <input type="hidden" name="to" value="${to("check")}" />
3435 ${btn("Check", { variant: "ghost", label: `Check ${p.name}` })}
3536 </form>`;
36 if (p.claimedAt !== "") return html`<div class="form-actions">${check}</div>`;
37 // Retire asks the confirm page; a claimed forge's form says the owner means it (`despite_claim`).
38 const retire = (act: string, label: string, claimed: boolean): Html => html`<form method="get" action="/-/confirm">
39 <input type="hidden" name="to" value="${to(act)}" />
40 ${claimed ? html`<input type="hidden" name="despite_claim" value="1" />` : null}
41 ${btn(label, { variant: "ghost", label: `${label}: ${p.name}` })}
42 </form>`;
43 if (p.state === "retired")
44 return html`<div class="form-actions">${p.volume === "" ? null : retire("retire-data", "Delete its kept data", p.claimedAt !== "")}</div>`;
45 if (p.claimedAt !== "")
46 return html`<div class="form-actions">${check}${retire("retire", "Retire this buyer's forge", true)}${retire("retire-data", "Retire it and delete the buyer's data", true)}</div>`;
3747 return html`<div class="form-actions">
3848 <form method="get" action="/-/confirm">
3949 <input type="hidden" name="to" value="${to("update")}" />
@@ -50,6 +60,8 @@ function actions(p: PinnedView): Html {
5060 ${p.host === "" ? html`<input class="mono" name="host" placeholder="forge.example.com" maxlength="253" required spellcheck="false" autocomplete="off" aria-label="Hostname for ${p.name}" />` : null}
5161 ${btn("New claim link", { variant: "ghost", label: `New claim link for ${p.name}` })}
5262 </form>
63 ${retire("retire", "Retire", false)}
64 ${retire("retire-data", "Retire and delete its data", false)}
5365 </div>`;
5466 }
5567
@@ -64,6 +76,7 @@ function forge(p: PinnedView, f: PinnedFacts): Html {
6476 ${fact("Address", p.url === "" ? none("no name yet") : html`<a class="mono" href="${p.url}" rel="noopener noreferrer">${p.url}</a>`)}
6577 ${fact("DNS record", p.dns === "" ? none("Check reads the machine's address") : html`<span class="mono">${p.dns}</span> ${p.dnsWrittenBy === "" ? none("create it by hand") : none(`written by the forge in ${p.dnsWrittenBy}`)}`)}
6678 ${fact("Claim link", p.claimedAt !== "" ? html`used` : p.claimExpires === "" ? none("none issued") : html`shown once; works until ${time(p.claimExpires)} unless used. Check asks the forge whether it was.`)}
79 ${p.state === "retired" ? fact("Kept data", p.volume === "" ? none("deleted") : html`its volume is kept${p.keepCents > 0 ? html`, about ${dollars(p.keepCents)} a month at list price` : null}`) : null}
6780 ${fact("Health", badge(p.state, { tone: TONE[p.state] ?? "default" }))}
6881 ${fact("Last check", checked ? time(checked) : none("never checked"))}
6982 ${fact("Last change", last ? html`${last.kind} to <span class="mono">${last.toVersion.slice(0, 12)}</span>` : none("none"))}
src/web/pages/search.ts +21
@@ -1008,6 +1008,27 @@ const DESTRUCTIVE: {
10081008 };
10091009 },
10101010 },
1011 {
1012 pattern: /^\/pinned\/([a-z][a-z0-9-]*)\/(retire|retire-data)$/,
1013 describe: (m) => {
1014 const name = m[1]!;
1015 if (m[2] === "retire")
1016 return {
1017 verb: "Retire",
1018 title: `Retire ${name}?`,
1019 detail: "Its machine is deleted and stops billing, and the DNS record the forge wrote for it is removed. Its data volume is kept, and keeps costing what a volume costs; Retire and delete its data removes that later. A forge its buyer has claimed is refused unless the owner says they mean it.",
1020 phrase: "",
1021 carries: "despite_claim",
1022 };
1023 return {
1024 verb: "Retire and delete its data",
1025 title: `Retire ${name} and delete its data?`,
1026 detail: "Its machine and its data volume are both deleted. Everything on that volume is gone and cannot be recovered, including a buyer's repositories if the forge was claimed.",
1027 phrase: name,
1028 carries: "despite_claim",
1029 };
1030 },
1031 },
10111032 {
10121033 pattern: /^\/pinned\/([a-z][a-z0-9-]*)\/(update|rollback|check|claim)$/,
10131034 describe: (m) => {
test/delete-tier.test.ts +4
@@ -82,6 +82,10 @@ const SAMPLES: Readonly<
8282 destroys: { action: "remove", id: "o1" },
8383 spares: { action: "add", host: "git.example" },
8484 },
85 pinned_forge: {
86 destroys: { verb: "retire", withData: true },
87 spares: { verb: "retire" },
88 },
8589 prompts: {
8690 destroys: { repo: "alice/shop", action: "remove", id: "p1" },
8791 spares: { repo: "alice/shop", action: "run", id: "p1" },
test/openapi-errors.test.ts +1 −1
@@ -29,7 +29,7 @@ const BASE = "http://localhost";
2929 /** Not called: these would end the session, stop the forge or reach beyond the test's own data. */
3030 const NOT_CALLED = /\/(sessions|maintenance|migrate|first-admin|heartbeat|release|fleet-ops|drills|forges|sandbox|broker|admin\/(pinned|releases|accounts|settings))/;
3131 /** How many routes NOT_CALLED leaves out; a change to it changes this on purpose. */
32 const SKIPPED = 55;
32 const SKIPPED = 56;
3333
3434 let dataDir: string;
3535 let app: App;
test/pinned-canary.test.ts +25 −1
@@ -1,5 +1,5 @@
11 import { expect, test } from "bun:test";
2 import { canary, invalid, leftovers, table } from "../scripts/pinned-canary.ts";
2 import { canary, cleanup, invalid, leftovers, table } from "../scripts/pinned-canary.ts";
33
44 const A = "a".repeat(40);
55 const B = "b".repeat(40);
@@ -68,3 +68,27 @@ test("versions and source are checked before any paid call", () => {
6868 expect(invalid({ ...ok, source: "http://x/y.git" })).toContain("https");
6969 expect(invalid({ ...ok, source: "git@x:y.git" })).toContain("https");
7070 });
71
72 test("cleanup retires the canary with its data and confirms the forge lists nothing left", async () => {
73 const seen: string[] = [];
74 const call = async (path: string, body?: unknown) => {
75 seen.push(`${body === undefined ? "GET" : "POST"} ${path} ${JSON.stringify(body ?? "")}`);
76 return path.endsWith("/retire")
77 ? { status: 200, json: { state: "retired" } }
78 : { status: 200, json: { items: [{ name: "c", state: "retired", remote: "", volume: "" }] } };
79 };
80 expect(await cleanup(call, "c")).toMatchObject({ ok: true });
81 expect(seen).toEqual(['POST /api/v1/admin/pinned/c/retire {"withData":true}', "GET /api/v1/admin/pinned \"\""]);
82 });
83
84 test("cleanup says so when the retire fails or the forge still lists a volume; a forge never made is nothing to clean", async () => {
85 const refused = async () => ({ status: 422, json: { message: "The cloud refused: api.digitalocean.com answered 500" } });
86 expect(await cleanup(refused, "c")).toMatchObject({ ok: false, message: expect.stringContaining("retire: HTTP 422") });
87 const left = async (path: string) =>
88 path.endsWith("/retire") ? { status: 200, json: {} } : { status: 200, json: { items: [{ name: "c", state: "retired", remote: "", volume: "v1" }] } };
89 expect(await cleanup(left, "c")).toMatchObject({ ok: false, message: expect.stringContaining('volume "v1"') });
90 const never = async () => ({ status: 422, json: { message: "No such pinned forge." } });
91 expect(await cleanup(never, "c")).toMatchObject({ ok: true });
92 const thrown = async () => { throw new Error("ECONNRESET"); };
93 expect(await cleanup(thrown, "c")).toMatchObject({ ok: false, message: "retire: ECONNRESET" });
94 });
test/pinned-ceiling.test.ts +6 −6
@@ -337,8 +337,8 @@ describe("cloud account ceiling", () => {
337337 });
338338
339339 test("every use of a cloud driver that can make something is held to the ceiling", () => {
340 // A driver is only ever taken through `capped`, or handed to `read`, which makes nothing. A new
341 // call site that provisions or replaces with a bare driver fails here.
340 // A driver is only ever taken through `capped`, or handed to `read` or `retire`, which make
341 // nothing. A new call site that provisions or replaces with a bare driver fails here.
342342 const files = (dir: string): string[] =>
343343 readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? files(join(dir, e.name)) : e.name.endsWith(".ts") ? [join(dir, e.name)] : []));
344344 const src = join(import.meta.dir, "../src");
@@ -351,12 +351,12 @@ describe("cloud account ceiling", () => {
351351 if (/^import\b[^\n]*$/.test(text.slice(text.lastIndexOf("\n", m.index) + 1, m.index))) continue;
352352 uses++;
353353 const before = text.slice(Math.max(0, m.index - 80), m.index);
354 if (!/\bcapped\(app, [\w.]+, $/.test(before) && !/\bread\($/.test(before)) bare.push(`${file.slice(src.length + 1)}: …${before.slice(-40)}driverOf(`);
354 if (!/\bcapped\(app, [\w.]+, $/.test(before) && !/\b(?:read|retire)\($/.test(before)) bare.push(`${file.slice(src.length + 1)}: …${before.slice(-40)}driverOf(`);
355355 }
356356 }
357357 expect(bare).toEqual([]);
358 // Deploy, update or rollback (asked, then made), a new claim link, and the read: the five there
359 // are.
360 expect(uses).toBe(5);
358 // Deploy, update or rollback (asked, then made), a new claim link, the read and the retire: the
359 // six there are.
360 expect(uses).toBe(6);
361361 });
362362 });
test/pinned-retire-doors.test.ts added +287
@@ -0,0 +1,287 @@
1 /**
2 * Retire (#16219) at its doors: the confirm page and its form on /pinned, the API route and the
3 * MCP tool. Each is the same `retirePinned`; the data is deleted only with the second word.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import {
11 addAccount,
12 allowWrite,
13 net as cloudNet,
14 } from "../src/actions/cloud.ts";
15 import { setCeiling } from "../src/actions/cloud_ceiling.ts";
16 import { deployPinned, net } from "../src/actions/pinned.ts";
17 import { getPinned, markClaimed } from "../src/core/pinned.ts";
18 import { createToken } from "../src/core/tokens.ts";
19 import { createUser, getUserByName } from "../src/core/users.ts";
20 import { serve, type Servers } from "../src/http/server.ts";
21 import { quietLogs } from "./helpers/globals.ts";
22 import { seedPlaces } from "./helpers/places-fixture.ts";
23
24 quietLogs();
25
26 const V = "a".repeat(40);
27 const SOURCE = "https://forge.example.org/trevato/forge";
28
29 describe("retire at its doors", () => {
30 let dataDir = "";
31 let app: App;
32 let servers: Servers;
33 let adminTok = "";
34 let bobTok = "";
35 const deletes: string[] = [];
36 const headers = (tok: string, more: Record<string, string> = {}) => ({
37 authorization: `Bearer ${tok}`,
38 origin: servers.url,
39 ...more,
40 });
41 const make = async (name: string) => {
42 const r = await deployPinned(app, getUserByName(app.db, "alice"), {
43 name,
44 host: `${name}.forge.test`,
45 target: "digitalocean",
46 account: "main",
47 app: "alice/shop",
48 source: SOURCE,
49 version: V,
50 });
51 if (!r.ok) throw new Error(r.error);
52 // The deploy deletes its throwaway SSH key; only what a retire deletes is counted.
53 deletes.length = 0;
54 };
55 const form = (path: string, tok: string, body: Record<string, string> = {}) =>
56 fetch(servers.url + path, {
57 method: "POST",
58 redirect: "manual",
59 headers: headers(tok, {
60 "content-type": "application/x-www-form-urlencoded",
61 }),
62 body: new URLSearchParams(body),
63 });
64 const api = (name: string, tok: string, body: unknown = {}) =>
65 fetch(`${servers.url}/api/v1/admin/pinned/${name}/retire`, {
66 method: "POST",
67 headers: headers(tok, { "content-type": "application/json" }),
68 body: JSON.stringify(body),
69 });
70
71 beforeAll(async () => {
72 dataDir = await mkdtemp(join(tmpdir(), "forge-retire-doors-"));
73 app = createApp({ dataDir, port: 0 });
74 await seedPlaces(app.db);
75 servers = await serve(app);
76 for (const [username, adminIfFirst] of [
77 ["alice", true],
78 ["bob", false],
79 ] as const) {
80 const made = await createUser(app.db, {
81 origin: "seed",
82 trusted: true,
83 username,
84 email: `${username}@f.test`,
85 password: "a-good-passphrase",
86 adminIfFirst,
87 });
88 if (!made.ok) throw new Error(made.error);
89 }
90 adminTok = createToken(
91 app.db,
92 getUserByName(app.db, "alice")!.id,
93 "admin",
94 "admin",
95 ).token;
96 bobTok = createToken(
97 app.db,
98 getUserByName(app.db, "bob")!.id,
99 "admin",
100 "admin",
101 ).token;
102 cloudNet.fetch = async () =>
103 new Response(
104 JSON.stringify({ account: { email: "[email protected]", status: "active" } }),
105 { status: 200 },
106 );
107 const added = await addAccount(
108 app,
109 getUserByName(app.db, "alice"),
110 "digitalocean",
111 "main",
112 "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5",
113 );
114 if (!added.ok) throw new Error(String(added.error));
115 allowWrite(
116 app,
117 getUserByName(app.db, "alice"),
118 "digitalocean",
119 "main",
120 true,
121 );
122 expect(
123 setCeiling(
124 app,
125 getUserByName(app.db, "alice"),
126 "digitalocean",
127 "main",
128 500,
129 ).ok,
130 ).toBe(true);
131 net.resolve = async () => [];
132 net.fetch = async (url, init) => {
133 const u = new URL(url);
134 if (init?.method === "DELETE") {
135 deletes.push(u.pathname);
136 return new Response(null, { status: 204 });
137 }
138 if (u.pathname === "/v2/volumes")
139 return new Response(JSON.stringify({ volume: { id: "vol-1" } }), {
140 status: 201,
141 });
142 if (u.pathname === "/v2/account/keys" && init?.method === "POST")
143 return new Response(JSON.stringify({ ssh_key: { id: 4242 } }), {
144 status: 201,
145 });
146 return new Response(
147 JSON.stringify({
148 droplet: {
149 id: 7,
150 status: "active",
151 networks: { v4: [{ type: "public", ip_address: "203.0.113.7" }] },
152 },
153 }),
154 { status: 202 },
155 );
156 };
157 }, 30_000);
158
159 afterAll(async () => {
160 await servers.stop();
161 app.close();
162 await rm(dataDir, { recursive: true, force: true });
163 });
164
165 test("the confirm page asks, and for the data it asks for the forge's name", async () => {
166 const keep = await (
167 await fetch(`${servers.url}/-/confirm?to=/pinned/acme/retire`, {
168 headers: headers(adminTok),
169 })
170 ).text();
171 expect(keep).toContain("Retire acme?");
172 expect(keep).not.toContain("to continue");
173 const data = await (
174 await fetch(
175 `${servers.url}/-/confirm?to=/pinned/acme/retire-data&despite_claim=`,
176 { headers: headers(adminTok) },
177 )
178 ).text();
179 expect(data).toContain("Retire acme and delete its data?");
180 expect(data).toContain("Type acme to continue");
181 });
182
183 test("the page's form retires and keeps the data; its second act deletes it; a non-admin finds nothing", async () => {
184 await make("acme");
185 expect((await form("/pinned/acme/retire", bobTok)).status).toBe(403);
186 expect(getPinned(app.db, "acme")!.state).toBe("running");
187 expect((await form("/pinned/acme/retire", adminTok)).status).toBe(303);
188 expect(getPinned(app.db, "acme")).toMatchObject({
189 state: "retired",
190 volume: "vol-1",
191 });
192 expect(deletes).toEqual(["/v2/droplets/7"]);
193 expect((await form("/pinned/acme/retire-data", adminTok)).status).toBe(303);
194 expect(getPinned(app.db, "acme")).toMatchObject({
195 state: "retired",
196 volume: "",
197 });
198 expect(deletes).toEqual(["/v2/droplets/7", "/v2/volumes/vol-1"]);
199 const page = await (
200 await fetch(`${servers.url}/pinned`, { headers: headers(adminTok) })
201 ).text();
202 expect(page).toContain("retired");
203 expect(page).toContain("deleted");
204 });
205
206 test("a claimed forge's form carries the flag, and without it the page's post is refused", async () => {
207 await make("theirs");
208 expect(markClaimed(app.db, "theirs")).toBe(true);
209 const page = await (
210 await fetch(`${servers.url}/pinned`, { headers: headers(adminTok) })
211 ).text();
212 expect(page).toContain('name="despite_claim"');
213 expect(page).toContain("Retire this buyer");
214 expect((await form("/pinned/theirs/retire", adminTok)).status).toBe(303);
215 expect(getPinned(app.db, "theirs")!.state).toBe("running");
216 expect(
217 (await form("/pinned/theirs/retire", adminTok, { despite_claim: "1" }))
218 .status,
219 ).toBe(303);
220 expect(getPinned(app.db, "theirs")!.state).toBe("retired");
221 });
222
223 test("the API retires with withData as the second word, and refuses a claimed forge without despiteClaim", async () => {
224 await make("viaapi");
225 expect((await api("viaapi", bobTok)).status).toBeGreaterThanOrEqual(400);
226 const kept = await api("viaapi", adminTok);
227 expect(kept.status).toBe(200);
228 expect(await kept.json()).toMatchObject({
229 name: "viaapi",
230 state: "retired",
231 volume: "vol-1",
232 keepCents: 100,
233 dnsRemoved: "none",
234 });
235 const gone = await api("viaapi", adminTok, { withData: true });
236 expect(await gone.json()).toMatchObject({ state: "retired", volume: "" });
237 await make("claimed");
238 markClaimed(app.db, "claimed");
239 const refused = await api("claimed", adminTok);
240 expect(refused.status).toBe(422);
241 expect(JSON.stringify(await refused.json())).toContain(
242 "handed to its buyer",
243 );
244 expect(
245 (await api("claimed", adminTok, { despiteClaim: true })).status,
246 ).toBe(200);
247 });
248
249 test("the MCP tool retires, deletes the data only with withData, and an ro token cannot", async () => {
250 await make("viamcp");
251 const call = async (tok: string, args: Record<string, unknown>) => {
252 const res = await fetch(`${servers.url}/mcp`, {
253 method: "POST",
254 headers: headers(tok, {
255 "content-type": "application/json",
256 accept: "application/json, text/event-stream",
257 }),
258 body: JSON.stringify({
259 jsonrpc: "2.0",
260 id: 1,
261 method: "tools/call",
262 params: { name: "pinned_forge", arguments: args },
263 }),
264 });
265 return JSON.stringify(await res.json());
266 };
267 const ro = createToken(
268 app.db,
269 getUserByName(app.db, "alice")!.id,
270 "ro",
271 "ro",
272 ).token;
273 await call(ro, { verb: "retire", name: "viamcp" });
274 expect(getPinned(app.db, "viamcp")!.state).toBe("running");
275 expect(await call(adminTok, { verb: "retire", name: "viamcp" })).toContain(
276 "Its data volume is kept",
277 );
278 expect(getPinned(app.db, "viamcp")).toMatchObject({
279 state: "retired",
280 volume: "vol-1",
281 });
282 expect(
283 await call(adminTok, { verb: "retire", name: "viamcp", withData: true }),
284 ).toContain("Its data volume is deleted too");
285 expect(getPinned(app.db, "viamcp")!.volume).toBe("");
286 });
287 });
test/pinned-retire.test.ts added +451
@@ -0,0 +1,451 @@
1 /**
2 * Retiring a pinned forge (#16219): its machine is deleted, its data volume kept unless asked
3 * for, the DNS record the forge wrote is removed, and the row ends `retired`, costing only the
4 * volume it kept. A machine or volume already gone is done. A claimed forge is refused unless the
5 * owner says they mean it. A recorded fetch stands in for DigitalOcean, Hetzner and Cloudflare.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import {
13 addAccount,
14 allowWrite,
15 net as cloudNet,
16 } from "../src/actions/cloud.ts";
17 import { setCeiling } from "../src/actions/cloud_ceiling.ts";
18 import {
19 changeBaseDomain,
20 checkPinned,
21 claimPinned,
22 deployPinned,
23 net,
24 retirePinned,
25 retireWords,
26 rollbackPinned,
27 updatePinned,
28 } from "../src/actions/pinned.ts";
29 import { spendOf } from "../src/cloud/ceiling.ts";
30 import { dnsOf, getPinned, markClaimed } from "../src/core/pinned.ts";
31 import { createUser, getUserByName } from "../src/core/users.ts";
32 import { quietLogs } from "./helpers/globals.ts";
33 import { seedPlaces } from "./helpers/places-fixture.ts";
34
35 quietLogs();
36
37 const V1 = "a".repeat(40);
38 const SOURCE = "https://forge.example.org/trevato/forge";
39 const ZONE = "a".repeat(32);
40
41 describe("retiring a pinned forge", () => {
42 let dataDir = "";
43 let app: App;
44 const calls: string[] = [];
45 const records: { id: string; name: string; content: string }[] = [];
46 /** Answers for the next delete of each kind: 404 means it is gone already, 409 that the provider refuses. */
47 const answer = { machine: 204, volume: 204, record: 200 };
48 let seq = 1000;
49 let claimSaid: "waiting" | "claimed" = "waiting";
50
51 const admin = () => getUserByName(app.db, "alice")!;
52 const input = (name: string, over: Record<string, unknown> = {}) => ({
53 name,
54 host: "",
55 target: "digitalocean",
56 account: "main",
57 app: "alice/shop",
58 source: SOURCE,
59 version: V1,
60 config: {},
61 ...over,
62 });
63 const error = (r: unknown) => String((r as { error: unknown }).error);
64 const monthly = (provider: string) =>
65 spendOf(app.db, provider, "main").monthlyCents;
66 const deleted = (what: string) =>
67 calls.filter((c) => c.startsWith("DELETE") && c.includes(what));
68
69 beforeAll(async () => {
70 dataDir = await mkdtemp(join(tmpdir(), "forge-retire-"));
71 app = createApp({ dataDir, port: 0 });
72 await seedPlaces(app.db);
73 const made = await createUser(app.db, {
74 origin: "seed",
75 trusted: true,
76 username: "alice",
77 email: "[email protected]",
78 password: "a-good-passphrase",
79 adminIfFirst: true,
80 });
81 if (!made.ok) throw new Error(made.error);
82 cloudNet.fetch = async () =>
83 new Response(
84 JSON.stringify({
85 account: { email: "[email protected]", status: "active" },
86 result: [],
87 servers: [],
88 meta: { pagination: { total_entries: 0 } },
89 }),
90 { status: 200 },
91 );
92 for (const [provider, token] of [
93 ["digitalocean", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5"],
94 ["hetzner", "hcloud_Zq4TxLm7Kp2Vb8nWcR5Yd3Fg6Hj9"],
95 ["cloudflare", "cf_Zq4TxLm7Kp2Vb8nWcR5Yd3Fg6Hj9Lm2"],
96 ] as const) {
97 const added = await addAccount(app, admin(), provider, "main", token);
98 if (!added.ok) throw new Error(String(added.error));
99 allowWrite(app, admin(), provider, "main", true);
100 }
101 expect(setCeiling(app, admin(), "digitalocean", "main", 500).ok).toBe(true);
102 expect(changeBaseDomain(app, admin(), "forges.test").ok).toBe(true);
103 net.resolve = async () => [];
104 net.fetch = async (url, init) => {
105 const u = new URL(url);
106 const method = init?.method ?? "GET";
107 calls.push(`${method} ${u.host}${u.pathname}`);
108 const json = (o: unknown, status = 200) =>
109 new Response(JSON.stringify(o), { status });
110 if (u.host === "api.cloudflare.com") {
111 const body = init?.body ? JSON.parse(String(init.body)) : undefined;
112 if (u.pathname === "/client/v4/zones")
113 return json({
114 result:
115 u.searchParams.get("name") === "forges.test"
116 ? [{ id: ZONE, name: "forges.test" }]
117 : [],
118 });
119 const m = u.pathname.match(/dns_records(?:\/([0-9a-f]{32}))?$/);
120 if (method === "GET")
121 return json({
122 result: records
123 .filter((r) => r.name === u.searchParams.get("name"))
124 .map((r) => ({ ...r, type: "A", proxied: false, ttl: 60 })),
125 });
126 if (method === "POST") {
127 const r = {
128 id: (++seq).toString(16).padStart(32, "0"),
129 name: body.name,
130 content: body.content,
131 };
132 records.push(r);
133 return json({ result: r }, 200);
134 }
135 if (method === "DELETE") {
136 const at = records.findIndex((r) => r.id === m?.[1]);
137 if (answer.record !== 200) return json({}, answer.record);
138 if (at < 0) return json({}, 404);
139 records.splice(at, 1);
140 return json({ result: { id: m![1] } });
141 }
142 return json({ result: {} });
143 }
144 if (method === "DELETE" && u.pathname.includes("/volumes/"))
145 return answer.volume === 204
146 ? new Response(null, { status: 204 })
147 : json({}, answer.volume);
148 if (method === "DELETE" && /\/(droplets|servers)\//.test(u.pathname))
149 return answer.machine === 204
150 ? new Response(null, { status: 204 })
151 : json({}, answer.machine);
152 if (method === "DELETE") return new Response(null, { status: 204 });
153 if (u.pathname.endsWith("/volumes"))
154 return json(
155 { volume: { id: u.host === "api.hetzner.cloud" ? ++seq : "vol-1" } },
156 201,
157 );
158 if (
159 u.pathname.endsWith("/account/keys") ||
160 u.pathname.endsWith("/ssh_keys")
161 )
162 return json({ ssh_key: { id: 4242 } }, 201);
163 if (u.pathname === "/v1/servers")
164 return json({ server: { id: ++seq } }, 201);
165 if (method === "POST") return json({ droplet: { id: ++seq } }, 202);
166 const id = Number(u.pathname.split("/").at(-1));
167 if (u.host === "api.hetzner.cloud")
168 return json({
169 server: {
170 status: "running",
171 public_net: { ipv4: { ip: `198.51.100.${id % 250}` } },
172 },
173 });
174 return json({
175 droplet: {
176 id,
177 status: "active",
178 networks: {
179 v4: [{ type: "public", ip_address: `203.0.113.${id % 250}` }],
180 },
181 },
182 });
183 };
184 net.probe = async (url) =>
185 new URL(url).pathname === "/api/v1/first-admin/claim"
186 ? new Response(JSON.stringify({ state: claimSaid }), { status: 200 })
187 : new Response("ok", { status: 200 });
188 }, 30_000);
189
190 afterAll(async () => {
191 app.close();
192 await rm(dataDir, { recursive: true, force: true });
193 });
194
195 test("retire deletes the machine and the record the forge wrote, keeps the volume, and says what keeping it costs", async () => {
196 expect((await deployPinned(app, admin(), input("keeper"))).ok).toBe(true);
197 const was = getPinned(app.db, "keeper")!;
198 expect(records.map((r) => r.name)).toEqual(["keeper.forges.test"]);
199 expect(monthly("digitalocean")).toBe(1300);
200 calls.length = 0;
201 const r = await retirePinned(app, admin(), "keeper");
202 expect(r.ok).toBe(true);
203 expect(deleted("/droplets/")).toEqual([
204 `DELETE api.digitalocean.com/v2/droplets/${was.remote}`,
205 ]);
206 expect(deleted("/volumes/")).toEqual([]);
207 expect(getPinned(app.db, "keeper")).toMatchObject({
208 state: "retired",
209 remote: "",
210 address: "",
211 volume: "vol-1",
212 });
213 // The record the forge wrote is gone, and forgotten.
214 expect(records).toEqual([]);
215 expect(dnsOf(app.db, was.id)).toBeUndefined();
216 expect(r.ok && r.value.dnsRemoved).toBe("removed");
217 // The volume is all it costs now: DigitalOcean's list price, $1.00 for 10 GiB.
218 expect(monthly("digitalocean")).toBe(100);
219 expect(r.ok && r.value.keepCents).toBe(100);
220 expect(r.ok && retireWords(r.value)).toContain(
221 "its machine is deleted, and the DNS record the forge wrote for it is removed",
222 );
223 expect(r.ok && retireWords(r.value)).toContain(
224 "Its data volume is kept and costs about $1.00 a month at list price",
225 );
226 // A recorded event names who and what.
227 const event = app.db
228 .query<
229 { payload: string },
230 []
231 >("SELECT payload FROM event WHERE kind = 'pinned.retired'")
232 .get();
233 expect(JSON.parse(event!.payload)).toMatchObject({
234 name: "keeper",
235 withData: false,
236 claimed: false,
237 dns: "removed",
238 });
239 });
240
241 test("retiring again changes nothing and asks the cloud nothing", async () => {
242 calls.length = 0;
243 const again = await retirePinned(app, admin(), "keeper");
244 expect(again.ok).toBe(true);
245 expect(calls).toEqual([]);
246 expect(getPinned(app.db, "keeper")).toMatchObject({
247 state: "retired",
248 volume: "vol-1",
249 });
250 });
251
252 test("a retired forge is not updated, rolled back, given a claim link or checked", async () => {
253 for (const refused of [
254 await updatePinned(app, admin(), "keeper", { version: "b".repeat(40) }),
255 await rollbackPinned(app, admin(), "keeper"),
256 await claimPinned(app, admin(), "keeper"),
257 await checkPinned(app, admin(), "keeper"),
258 ])
259 expect(error(refused)).toContain("This forge was retired");
260 });
261
262 test("with data it deletes the volume too, from a retired forge or in one go, and the reckoning drops to nothing", async () => {
263 calls.length = 0;
264 const r = await retirePinned(app, admin(), "keeper", { withData: true });
265 expect(r.ok).toBe(true);
266 expect(deleted("/volumes/")).toEqual([
267 "DELETE api.digitalocean.com/v2/volumes/vol-1",
268 ]);
269 expect(getPinned(app.db, "keeper")).toMatchObject({
270 state: "retired",
271 volume: "",
272 });
273 expect(monthly("digitalocean")).toBe(0);
274 expect(r.ok && retireWords(r.value)).toContain(
275 "Its data volume is deleted too",
276 );
277 // Asked again, nothing is left to delete.
278 calls.length = 0;
279 expect(
280 (await retirePinned(app, admin(), "keeper", { withData: true })).ok,
281 ).toBe(true);
282 expect(calls).toEqual([]);
283 // In one go: the machine first, then the volume.
284 expect((await deployPinned(app, admin(), input("both"))).ok).toBe(true);
285 calls.length = 0;
286 expect(
287 (await retirePinned(app, admin(), "both", { withData: true })).ok,
288 ).toBe(true);
289 expect(
290 calls.filter((c) => c.startsWith("DELETE api.digitalocean.com")).map((c) => c.split("/")[2]),
291 ).toEqual(["droplets", "volumes"]);
292 expect(getPinned(app.db, "both")).toMatchObject({
293 state: "retired",
294 remote: "",
295 volume: "",
296 });
297 expect(monthly("digitalocean")).toBe(0);
298 });
299
300 test("a machine or volume already gone at the provider is success", async () => {
301 expect((await deployPinned(app, admin(), input("vanished"))).ok).toBe(true);
302 answer.machine = 404;
303 answer.volume = 404;
304 try {
305 const r = await retirePinned(app, admin(), "vanished", {
306 withData: true,
307 });
308 expect(r.ok).toBe(true);
309 expect(getPinned(app.db, "vanished")).toMatchObject({
310 state: "retired",
311 remote: "",
312 volume: "",
313 });
314 } finally {
315 answer.machine = 204;
316 answer.volume = 204;
317 }
318 });
319
320 test("a volume the provider will not delete leaves the forge retired with its data kept, and asking again finishes it", async () => {
321 expect((await deployPinned(app, admin(), input("stuck"))).ok).toBe(true);
322 answer.volume = 409;
323 const first = await retirePinned(app, admin(), "stuck", { withData: true });
324 answer.volume = 204;
325 expect(first).toMatchObject({ ok: false });
326 expect(error(first)).toContain(
327 "Its machine is deleted and it is retired; its volume is kept",
328 );
329 expect(getPinned(app.db, "stuck")).toMatchObject({
330 state: "retired",
331 remote: "",
332 volume: "vol-1",
333 });
334 expect(monthly("digitalocean")).toBe(100);
335 expect(
336 (await retirePinned(app, admin(), "stuck", { withData: true })).ok,
337 ).toBe(true);
338 expect(getPinned(app.db, "stuck")).toMatchObject({
339 state: "retired",
340 volume: "",
341 });
342 expect(monthly("digitalocean")).toBe(0);
343 });
344
345 test("a forge whose machine the cloud will not delete is not retired", async () => {
346 expect((await deployPinned(app, admin(), input("refused"))).ok).toBe(true);
347 answer.machine = 500;
348 const r = await retirePinned(app, admin(), "refused");
349 answer.machine = 204;
350 expect(error(r)).toContain("The cloud refused");
351 expect(getPinned(app.db, "refused")).toMatchObject({ state: "running" });
352 expect(getPinned(app.db, "refused")!.remote).not.toBe("");
353 });
354
355 test("a record Cloudflare will not let the forge delete is left, and said", async () => {
356 expect((await deployPinned(app, admin(), input("dnsleft"))).ok).toBe(true);
357 answer.record = 403;
358 const r = await retirePinned(app, admin(), "dnsleft");
359 answer.record = 200;
360 expect(r.ok && r.value.dnsRemoved).toBe("kept");
361 expect(r.ok && retireWords(r.value)).toContain(
362 "its DNS record dnsleft.forges.test could not be removed and is yours to delete",
363 );
364 expect(getPinned(app.db, "dnsleft")).toMatchObject({ state: "retired" });
365 });
366
367 test("a forge recorded as claimed is refused without the flag, with a sentence that says why, and nothing is called", async () => {
368 expect((await deployPinned(app, admin(), input("theirs"))).ok).toBe(true);
369 expect(markClaimed(app.db, "theirs")).toBe(true);
370 calls.length = 0;
371 const r = await retirePinned(app, admin(), "theirs");
372 expect(error(r)).toContain(
373 "This forge was handed to its buyer: its data is on that volume, and retiring it deletes their forge",
374 );
375 expect(calls).toEqual([]);
376 expect(getPinned(app.db, "theirs")).toMatchObject({ state: "running" });
377 // The flag says the owner means it.
378 const meant = await retirePinned(app, admin(), "theirs", {
379 despiteClaim: true,
380 });
381 expect(meant.ok).toBe(true);
382 expect(getPinned(app.db, "theirs")).toMatchObject({
383 state: "retired",
384 remote: "",
385 });
386 const event = app.db
387 .query<
388 { payload: string },
389 []
390 >("SELECT payload FROM event WHERE kind = 'pinned.retired' AND payload LIKE '%theirs%'")
391 .get();
392 expect(JSON.parse(event!.payload)).toMatchObject({ claimed: true });
393 });
394
395 test("a forge that says it was claimed is refused too, though this forge had not heard", async () => {
396 expect((await deployPinned(app, admin(), input("heard"))).ok).toBe(true);
397 const p = getPinned(app.db, "heard")!;
398 // The name resolves to the machine, so the deployed forge is asked, and it answers claimed.
399 net.resolve = async () => [p.address];
400 claimSaid = "claimed";
401 try {
402 const r = await retirePinned(app, admin(), "heard");
403 expect(error(r)).toContain("handed to its buyer");
404 expect(getPinned(app.db, "heard")).toMatchObject({ state: "running" });
405 expect(getPinned(app.db, "heard")!.claimedAt).not.toBe("");
406 } finally {
407 net.resolve = async () => [];
408 claimSaid = "waiting";
409 }
410 });
411
412 test("Hetzner: the server and the volume are deleted at their own paths, and keeping the volume is priced in euros at the day's rate", async () => {
413 expect(
414 (
415 await deployPinned(
416 app,
417 admin(),
418 input("het", { target: "hetzner", place: "hetzner:nbg1:cx23" }),
419 )
420 ).ok,
421 ).toBe(true);
422 const was = getPinned(app.db, "het")!;
423 calls.length = 0;
424 const kept = await retirePinned(app, admin(), "het");
425 expect(kept.ok).toBe(true);
426 expect(deleted("/servers/")).toEqual([
427 `DELETE api.hetzner.cloud/v1/servers/${was.remote}`,
428 ]);
429 // 10 GiB at 0.0572 EUR = 0.572 EUR, at 1.2 = 0.6864 dollars, up.
430 expect(kept.ok && kept.value.keepCents).toBe(69);
431 expect(monthly("hetzner")).toBe(69);
432 expect(
433 (await retirePinned(app, admin(), "het", { withData: true })).ok,
434 ).toBe(true);
435 expect(deleted("/volumes/")).toEqual([
436 `DELETE api.hetzner.cloud/v1/volumes/${was.volume}`,
437 ]);
438 expect(monthly("hetzner")).toBe(0);
439 });
440
441 test("only an admin retires, and a forge that is not there is refused", async () => {
442 expect(await retirePinned(app, undefined, "keeper")).toMatchObject({
443 ok: false,
444 error: "not_found",
445 });
446 expect(await retirePinned(app, admin(), "nothing-here")).toMatchObject({
447 ok: false,
448 error: "No such pinned forge.",
449 });
450 });
451 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs