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

A deployed forge's machine and volume land in the cloud project meant for forges #16516

Merged opened this in answer to

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

Merged

scout/forge:scout/16340-a-deployed-forge-s-machine-and-volume-la → main 0 commits fork 4 threads · 4 unresolved

  • Merged. scout/16340-a-deployed-forge-s-machine-and-volume-la was merged into main as f1b4c2e.

Review

Sign in to review this change.
24 files changed +451 −44
docs/features/cloud.md +6 −1
@@ -7,7 +7,7 @@ row: Cloud accounts
77 The forge keeps the provider tokens (a cloud vendor's API token) its repositories use, sealed. Four doors show them, all a forge admin's alone; anyone else finds no such page, screen, tool or route. No door ever returns a secret: a token is typed once, checked, sealed, and never drawn, kept in a note or sent back.
88
99 - **Page**: Settings → Cloud accounts, `/settings/cloud`. Each account with what it is used for, when it was verified and last used, and today's vendor calls. Attach, verify, allow writes, rename, rotate, audit and remove are forms on the page.
10 - **Terminal**: the "Cloud accounts" screen (`src/tui/screens/cloud.ts`), opened from the palette. `a` attaches (token typed masked), `v` re-verifies, `r` rotates, `n` renames, `x` removes. The checks are the page's (`src/actions/cloud.ts`).
10 - **Terminal**: the "Cloud accounts" screen (`src/tui/screens/cloud.ts`), opened from the palette. `a` attaches (token typed masked), `v` re-verifies, `r` rotates, `n` renames, `x` removes, `P` sets the project its forges are filed in. The checks are the page's (`src/actions/cloud.ts`).
1111 - **MCP**: `cloud_accounts` takes no arguments and returns the accounts with each token's use, verification, write permission and today's calls. It counts as a write, so a `ro` token never lists them.
1212 - **HTTP**: `GET /api/v1/cloud/accounts` returns the same body as `cloud_accounts` (both build it with `cloudOverview`).
1313
@@ -19,6 +19,11 @@ Answers: `401` with no signed-in user, `403` for a read-only token (every vendor
1919
2020 Not done: the route only lists. Attaching, rotating and removing stay on the page and in the terminal, where the token can be typed masked.
2121
22 ## The project a forge is filed in (#16340)
23
24 - A DigitalOcean account can name the cloud **project** its forges go in: a text field on its row at `/settings/cloud`, `P` on the terminal screen, `set_project` on the MCP `cloud_account` tool. Empty is the provider's default project. An admin only; the name is checked, and the project must exist when a forge is deployed, or the deploy is refused before anything is made.
25 - A deploy files the droplet and volume in it and tags both with the forge's name. A forge made earlier is filed with `file` (see `docs/features/pinned-forge.md`). Hetzner shows no field: a Hetzner token already belongs to one project, so setting one is refused.
26
2227 ## Places and prices in US dollars (#16203)
2328
2429 `GET /api/v1/places` lists where a forge can run: provider + datacenter + machine size, each with vCPU, memory, disk, included traffic, city and country, `costCents` (machine + the 10 GiB volume + a public address, US dollars a month), the vendor's own `price` and the rate that converted it, `readAt`, `orderable` and, when not, `why`. Filters: `plan`, `provider`, `country`. `defaults` names each plan's default place and says why; the rule is: the cheapest place in the United States that can be ordered now and meets the plan's minimum, among providers with an account that allows writes (a provider with no such place in the United States falls back to its cheapest place anywhere); `PUT /api/v1/places/pin` (admin) pins one instead.
docs/features/pinned-forge.md +2 −1
@@ -9,7 +9,8 @@ A pinned forge is a forge the owner put on their own cloud. The forge that deplo
99 ## Doors (forge admin, admin-scope token)
1010
1111 - HTTP: `GET /api/v1/admin/pinned` (forges, their changes, the targets), `POST /api/v1/admin/pinned` (deploy; the answer holds `claim.link`), `POST /api/v1/admin/pinned/:name/update`, `POST /api/v1/admin/pinned/:name/rollback`, `POST /api/v1/admin/pinned/:name/claim` (a new claim link).
12 - Terminal: palette → **Pinned forges** (forge admin): `d` deploy, `u` update, `r` roll back, `n` a new claim link (asked first); a deploy and `n` show the link in a dialog to copy; it follows the bus, so a change made at any door shows at once (`src/tui/screens/pinned.ts`).
12 - Terminal: palette → **Pinned forges** (forge admin): `d` deploy, `u` update, `r` roll back, `f` files the forge's machine and volume in its account's cloud project, `n` a new claim link (asked first); a deploy and `n` show the link in a dialog to copy; it follows the bus, so a change made at any door shows at once (`src/tui/screens/pinned.ts`).
13 - File in a project (#16340): an account's project (set on Settings → Cloud accounts, `P` in the terminal, `set_project` over MCP; DigitalOcean only, since a Hetzner token already belongs to one project) is where a deploy files the machine and volume it makes, both tagged with the forge. A forge made before the project was set is filed by `file`: the **File in project** button on `/pinned`, `f` on the terminal screen, or the MCP `pinned_forge` verb `file`, all through `fileForge` in `src/actions/pinned.ts`; it is safe to repeat. A deploy into a project that does not exist is refused before anything is made. If the cloud refuses the filing after the machine exists, the machine is kept and a `pinned.unfiled` event says the forge stayed in the default project; run `file` to file it.
1314 - Web: `/deploy-to` (forge admin; linked from Cloud accounts) is a server-rendered form for cloud account, app, source, version, name and hostname. Its answer is a page with the claim link, sent `no-store`, not a redirect. The link `/deploy-to?app=owner/name&source=https://…&version=v1.2.3` (`deployToHref` in `src/web/pinned.ts`) lands on it with those filled in after one sign-in; nothing deploys until the button is pressed. The POST is same-origin checked and calls the same `deployPinned` (`src/http/pinned_routes.ts`).
1415 - Web list: `/pinned` (forge admin; 404 otherwise) is server-rendered, with actions; one block of plain rows per forge: name, app, version, address (a link), health (the state), when the last check ran (the newest `pinned.check` event; `never checked` before the first), and the last change with who and when, from the same `pinnedForges` read as the API (`src/web/pages/pinned.ts`). The intro links `/deploy-to`; an empty list says so. A person can update, roll back and check a forge from `/pinned`, as the terminal's `u`, `r` and `c` do: each row has four buttons (Update, Roll back, Check, New claim link), and each goes through the confirm page before it runs (Update also asks for the version). The row also shows the DNS record and when the claim link runs out. They post to `POST /pinned/:name/:act` (`act` is `update`, `rollback`, `check` or `claim`; admin only, same-origin, 404 for non-admins and unknown acts); the result, or the sentence that refuses it, is shown as a flash on `/pinned` (`src/http/pinned_routes.ts`).
1516 - MCP: `pinned_forge` with `verb` `list`, `deploy`, `claim`, `update`, `rollback` (and `check`) — the same words and the same checks (`src/actions/pinned.ts`).
src/actions/cloud_ceiling.ts +21 −1
@@ -5,7 +5,7 @@
55 */
66
77 import type { App } from "../app.ts";
8 import { getCloudAccount, setCeilingDollars } from "../core/cloud_account.ts";
8 import { getCloudAccount, setCeilingDollars, setProjectName } from "../core/cloud_account.ts";
99 import type { User } from "../core/users.ts";
1010 import { MAX_WARM, setWarmTarget, warmTargets } from "../cloud/warm_pool.ts";
1111 import { err, ok, type Result } from "../kernel/result.ts";
@@ -34,3 +34,23 @@ export function setWarm(app: App, actor: User | undefined, provider: string, nam
3434 app.bus.append({ kind: "cloud.warm_target", actorId: actor.id, payload: { provider, name, place, from, to: count } });
3535 return ok(count === 0 ? `no machine is kept warm at ${place}` : `up to ${count} machine${count === 1 ? "" : "s"} kept warm at ${place}, as purchases and the ceiling allow`);
3636 }
37
38 const PROJECT = /^[A-Za-z0-9][A-Za-z0-9 ._:-]{0,99}$/;
39
40 /** The words where a Hetzner account would name its project: its token already belongs to one. */
41 export const HETZNER_PROJECT_WORDS = "A Hetzner token already belongs to one project, so there is nothing to name: its forges land there.";
42
43 /**
44 * The cloud project an account's forges are filed in (DigitalOcean); empty goes back to the
45 * provider's default.
46 */
47 export function setProject(app: App, actor: User | undefined, provider: string, name: string, project: unknown): Result<string, string> {
48 if (actor?.isAdmin !== true) return err("not_found");
49 if (typeof project !== "string" || (project !== "" && !PROJECT.test(project))) return err("A project is the name it has at the provider: letters, digits, spaces and . _ : -, up to 100; empty for the default project.");
50 const before = getCloudAccount(app.db, provider, name);
51 if (!before) return err("No such credential.");
52 if (provider === "hetzner") return err(HETZNER_PROJECT_WORDS);
53 if (!setProjectName(app.db, provider, name, project)) return err("No such credential.");
54 app.bus.append({ kind: "cloud.project", actorId: actor.id, payload: { provider, name, from: before.project, to: project } });
55 return ok(project === "" ? "forges go in the provider's default project" : `forges are filed in the project "${project}"; a missing one refuses a deploy before anything is made`);
56 }
src/actions/pinned.ts +32 −3
@@ -29,7 +29,7 @@ import type { App } from "../app.ts";
2929 import { gatedFetch } from "../cloud/gate.ts";
3030 import { capped, CeilingRefusal, priced, refusalAt, rowCents } from "../cloud/ceiling.ts";
3131 import { driverOf } from "../cloud/drivers.ts";
32 import { orderable, provision, read, replace, retire } from "../cloud/machine.ts";
32 import { fileIn, orderable, provision, read, replace, retire } from "../cloud/machine.ts";
3333 import { dollars } from "../cloud/prices.ts";
3434 import { chooseDefault, isPlan, meets, type Chosen, type Place, type PlanName } from "../cloud/places.ts";
3535 import { inFlight } from "../billing/orders.ts";
@@ -292,6 +292,33 @@ async function unwriteDns(app: App, who: Who, name: string): Promise<"none" | "r
292292 return "kept";
293293 }
294294
295 /** The cloud project the row's account files its forges in; empty is the provider's default. */
296 const projectOf = (app: App, p: Pinned): string => getCloudAccount(app.db, p.target, p.account)?.project ?? "";
297
298 /**
299 * A machine made but not filed in its project stays in the provider's default one: the event says
300 * so, and that `file` files it, for the admin who reads the forge's changes.
301 */
302 const unfiled = (app: App, who: Who, name: string) => (why: string): void => {
303 app.bus.append({ kind: "pinned.unfiled", actorId: who.id, payload: { name, why, say: `${name} stayed in the provider's default project (${why}); \`file\` files it.`, ...orderOf(who) } });
304 };
305
306 /**
307 * File a forge's machine and volume in its account's project (#16340): the one action for a row
308 * made before the project was set, and the same call a deploy makes. Idempotent at the cloud.
309 */
310 export function fileForge(app: App, actor: User | undefined, name: string): Promise<Result<string, string>> {
311 const who = admin(actor);
312 if (!who.ok) return Promise.resolve(who);
313 const p = getPinned(app.db, name);
outdated

Both doors: fileForge is reachable only through MCP. Add a terminal entry in src/tui/ and a page action, and document it in docs/features/pinned-forge.md.

314 if (!p) return Promise.resolve(err("No such pinned forge."));
315 if (p.state === "retired") return Promise.resolve(err(RETIRED_REFUSAL));
316 const project = projectOf(app, p);
317 if (project === "") return Promise.resolve(err("Its cloud account names no project: set one on Settings → Cloud first."));
318 if (p.remote === "" || p.volume === "") return Promise.resolve(err("This forge has no machine and volume to file yet."));
319 return withCloud(app, who.value, p, "file", (f, token) => fileIn(capped(app, p.name, driverOf(p.target)), f, token, p, project)).then((r) => (r.ok ? ok(`${name} is filed in the project "${project}".`) : r));
320 }
321
295322 /** Open the account's token and run `go` with a gated fetch; the token never leaves this scope. */
296323 async function withCloud<T>(app: App, who: Who, p: Pinned, purpose: string, go: (f: Fetch, token: string) => Promise<T>, writes = true): Promise<Result<T, string>> {
297324 const account = getCloudAccount(app.db, p.target, p.account);
@@ -434,7 +461,9 @@ async function deployAs(app: App, who: Who, input: DeployInput): Promise<Result<
434461 (f, token) =>
435462 provision(capped(app, p.name, driverOf(p.target)), f, token, getPinned(app.db, p.name)!, {
436463 ...(old?.volume ? { have: old.volume } : {}),
464 project: projectOf(app, p),
437465 onVolume: (volume) => setRemote(app.db, p.name, { volume }),
466 onUnfiled: unfiled(app, who, p.name),
438467 }),
439468 (m) => setRemote(app.db, p.name, { ...m, state: "running" }),
440469 );
@@ -486,7 +515,7 @@ async function changeNow(
486515 const after = getPinned(app.db, name)!;
487516 const done = await create(
488517 app, who.value, after, kind,
489 (f, token) => replace(capped(app, after.name, driverOf(after.target)), f, token, after, { onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }) }),
518 (f, token) => replace(capped(app, after.name, driverOf(after.target)), f, token, after, { project: projectOf(app, after), onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }), onUnfiled: unfiled(app, who.value, name) }),
490519 (m) => setRemote(app.db, name, { ...m, address: "", state: "running" }),
491520 true,
492521 );
@@ -562,7 +591,7 @@ async function claimNow(app: App, who: Who, name: string, input: { host?: string
562591 const after: Pinned = { ...getPinned(app.db, name)!, claimHash: claim.hash, claimExpires: claim.expires };
563592 const done = await create(
564593 app, who, after, "claim",
565 (f, token) => replace(capped(app, after.name, driverOf(after.target)), f, token, after, { onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }) }),
594 (f, token) => replace(capped(app, after.name, driverOf(after.target)), f, token, after, { project: projectOf(app, after), onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }), onUnfiled: unfiled(app, who, name) }),
566595 (m) => {
567596 setClaim(app.db, name, { hash: claim.hash, expires: claim.expires });
568597 setRemote(app.db, name, { ...m, address: "", state: "running" });
src/cloud/droplet.ts +14 −4
@@ -4,11 +4,12 @@
44 *
55 * Calls (DigitalOcean API v2): POST /volumes, POST /account/keys and DELETE /account/keys/{id} (a
66 * throwaway key, so no root password is mailed), POST /droplets, DELETE /droplets/{id}, GET
7 * /droplets/{id} (the public IPv4 the droplet was given, read back after it boots).
7 * /droplets/{id} (the public IPv4 the droplet was given, read back after it boots), GET /projects
8 * and POST /projects/{id}/resources (file the droplet and volume in the account's project, #16340).
89 */
910
1011 import { dropThrowawayKey, makeThrowawayKey } from "./throwaway_key.ts";
11 import { bootConfig as boot, ipv4, volumeName, type Booted, type Driver } from "./machine.ts";
12 import { bootConfig as boot, forgeTag, ipv4, volumeName, type Booted, type Driver } from "./machine.ts";
1213
1314 export { BUN_VERSION } from "./machine.ts";
1415
@@ -24,7 +25,7 @@ const KEYS = "/account/keys";
2425 export const digitalocean: Driver = {
2526 api: "https://api.digitalocean.com/v2",
2627 async createVolume(call, p) {
27 const v = await call("POST", "/volumes", { name: volumeName(p.name), region: p.datacenter, size_gigabytes: 10, filesystem_type: "ext4" });
28 const v = await call("POST", "/volumes", { name: volumeName(p.name), region: p.datacenter, size_gigabytes: 10, filesystem_type: "ext4", tags: [forgeTag(p.name)] });
2829 return String(v.volume?.id ?? "");
2930 },
3031 async createMachine(call, p, volume) {
@@ -33,13 +34,22 @@ export const digitalocean: Driver = {
3334 try {
3435 const d = await call("POST", "/droplets", {
3536 name: `forge-${p.name}`, region: p.datacenter, size: p.size, image: "ubuntu-24-04-x64",
36 volumes: [volume], user_data: bootConfig(p), tags: ["forge-pinned"], ssh_keys: [Number(key)],
37 volumes: [volume], user_data: bootConfig(p), tags: ["forge-pinned", forgeTag(p.name)], ssh_keys: [Number(key)],
3738 });
3839 return String(d.droplet?.id ?? "");
3940 } finally {
4041 await dropThrowawayKey(call, KEYS, key);
4142 }
4243 },
44 async projectId(call, name) {
45 const all: any[] = (await call("GET", "/projects?per_page=200")).projects ?? [];
46 const found = all.find((x) => x?.name === name && typeof x.id === "string");
47 if (!found) throw new Error(`DigitalOcean has no project called "${name}": make it there, or change the account's project. Nothing was made.`);
48 return found.id;
49 },
50 async assign(call, project, t) {
51 await call("POST", `/projects/${encodeURIComponent(project)}/resources`, { resources: [`do:droplet:${t.machine}`, `do:volume:${t.volume}`] });
52 },
4353 async deleteMachine(call, remote) {
4454 await call("DELETE", `/droplets/${remote}`);
4555 },
src/cloud/hetzner.ts +4 −3
@@ -1,7 +1,8 @@
11 /**
22 * Hetzner Cloud (#16200): its calls only; the sequence they run in is
33 * machine.ts. A Hetzner token is scoped to one project and is read or
4 * read-write, nothing narrower.
4 * read-write, nothing narrower: it already belongs to one project, so a Hetzner account has no
5 * project to name (#16340) and every volume and server carries the label forge=<name> instead.
56 *
67 * Calls (Hetzner Cloud API v1): POST /volumes, POST /ssh_keys and DELETE
78 * /ssh_keys/{id} (a throwaway key, so no root password is mailed), POST /servers (the volume
@@ -26,7 +27,7 @@ const KEYS = "/ssh_keys";
2627 export const hetzner: Driver = {
2728 api: "https://api.hetzner.cloud/v1",
2829 async createVolume(call, p) {
29 const v = await call("POST", "/volumes", { name: volumeName(p.name), location: p.datacenter, size: 10, format: "ext4", automount: false });
30 const v = await call("POST", "/volumes", { name: volumeName(p.name), location: p.datacenter, size: 10, format: "ext4", automount: false, labels: { "forge-pinned": "true", forge: p.name } });
3031 return String(v.volume?.id ?? "");
3132 },
3233 async createMachine(call, p, volume) {
@@ -36,7 +37,7 @@ export const hetzner: Driver = {
3637 const s = await call("POST", "/servers", {
3738 name: `forge-${p.name}`, server_type: p.size, location: p.datacenter, image: IMAGE,
3839 volumes: [Number(volume)], automount: true, user_data: bootConfig(p, volume), ssh_keys: [Number(key)],
39 public_net: { enable_ipv4: true, enable_ipv6: true }, start_after_create: true, labels: { "forge-pinned": "true" },
40 public_net: { enable_ipv4: true, enable_ipv6: true }, start_after_create: true, labels: { "forge-pinned": "true", forge: p.name },
4041 });
4142 return String(s.server?.id ?? "");
4243 } finally {
src/cloud/machine.ts +50 −4
@@ -173,8 +173,19 @@ export interface Driver {
173173 /** Whether the volume is attached to no machine: a cloud detaches it after a delete answers, and refuses a new machine with it until then. */
174174 volumeFree(call: Call, volume: string): Promise<boolean>;
175175 readMachine(call: Call, remote: string): Promise<{ status: string; address: string }>;
176 /**
177 * The id of the cloud project called `name`, refused in plain words when there is none. Only a
178 * cloud whose resources land in a default project has it (DigitalOcean); a Hetzner token already
179 * belongs to one project.
180 */
181 projectId?(call: Call, name: string): Promise<string>;
182 /** File the machine and the volume in the project `projectId` named. */
183 assign?(call: Call, project: string, things: { machine: string; volume: string }): Promise<void>;
176184 }
177185
186 /** The tag or label that names a forge on everything the forge makes for it (#16340). */
187 export const forgeTag = (name: string) => `forge:${name}`;
188
178189 function caller(d: Driver, f: Fetch, token: string): Call {
179190 const host = new URL(d.api).host;
180191 return async (method, path, body) => {
@@ -197,17 +208,49 @@ const ID = /^\d+$/;
197208 * machine is asked for. Returns the ids to keep.
198209 */
199210 export async function provision(
200 d: Driver, f: Fetch, token: string, p: Pinned, hooks: { have?: string; onVolume(id: string): void },
211 d: Driver, f: Fetch, token: string, p: Pinned, hooks: { have?: string; project?: string; onVolume(id: string): void; onUnfiled?(why: string): void },
201212 ): Promise<{ remote: string; volume: string }> {
202213 const call = caller(d, f, token);
203214 d.admit?.(p);
215 // A project that does not exist refuses before anything is made.
216 const project = await projectOf(d, call, hooks.project);
204217 let volume = hooks.have ?? "";
205218 if (volume === "") {
206219 volume = await d.createVolume(call, p);
207220 if (volume === "") throw new Error(`${new URL(d.api).host} made no volume`);
208221 hooks.onVolume(volume);
209222 }
210 return { remote: await d.createMachine(call, p, volume), volume };
223 const remote = await d.createMachine(call, p, volume);
224 await file(d, call, project, remote, volume, hooks.onUnfiled);
225 return { remote, volume };
226 }
227
228 async function projectOf(d: Driver, call: Call, name: string | undefined): Promise<string> {
229 return name && d.projectId ? d.projectId(call, name) : "";
230 }
231
232 /**
233 * File what exists in the project. A refusal here never undoes or hides the machine, which is
234 * made and must be recorded: the forge stays in the default project until `fileIn` is asked again,
235 * and `onUnfiled` is told why so the caller can say so.
236 */
outdated

A failed assign is swallowed. The machine is recorded but nobody learns it sits in the default project. Surface it, for example in the deploy result or the event, and have file named in that message.

237 async function file(d: Driver, call: Call, project: string, machine: string, volume: string, onUnfiled?: (why: string) => void): Promise<void> {
238 if (project === "" || !d.assign) return;
239 try {
240 await d.assign(call, project, { machine, volume });
241 } catch (e) {
242 onUnfiled?.(e instanceof Error ? e.message.slice(0, 200) : "failed");
243 }
244 }
245
246 /**
247 * File a forge's machine and volume in the project `name` (a row made before the project was set).
248 */
249 export async function fileIn(d: Driver, f: Fetch, token: string, p: Pinned, name: string): Promise<void> {
250 if (!d.projectId || !d.assign) throw new Error("this cloud has no projects to file a forge in");
251 if (p.remote === "" || p.volume === "") throw new Error("this forge has no machine and volume to file");
252 const call = caller(d, f, token);
253 await d.assign(call, await d.projectId(call, name), { machine: p.remote, volume: p.volume });
211254 }
212255
213256 /**
@@ -219,12 +262,13 @@ export async function provision(
219262 * does not delete twice.
220263 */
221264 export async function replace(
222 d: Driver, f: Fetch, token: string, p: Pinned, hooks: { onDeleted(): void },
265 d: Driver, f: Fetch, token: string, p: Pinned, hooks: { project?: string; onDeleted(): void; onUnfiled?(why: string): void },
223266 ): Promise<{ remote: string }> {
224267 if (p.volume === "") throw new Error("this forge has no volume to keep");
225268 if (p.remote !== "" && !ID.test(p.remote)) throw new Error("this forge has no machine to replace");
226269 const call = caller(d, f, token);
227270 d.admit?.(p);
271 const project = await projectOf(d, call, hooks.project);
228272 if (p.remote !== "") {
229273 try {
230274 await d.deleteMachine(call, p.remote);
@@ -234,7 +278,9 @@ export async function replace(
234278 hooks.onDeleted();
235279 await untilFree(d, call, p.volume);
236280 }
237 return { remote: await d.createMachine(call, p, p.volume) };
281 const remote = await d.createMachine(call, p, p.volume);
282 await file(d, call, project, remote, p.volume, hooks.onUnfiled);
283 return { remote };
238284 }
239285
240286 /** How long a replace waits for the old machine to let go of the volume, and how often it asks. */
src/core/cloud_account.ts +12
@@ -52,6 +52,11 @@ export interface CloudAccount {
5252 readonly writeAllowed: boolean;
5353 /** The most the forge will let this account cost a month, whole US dollars (ceiling.ts). */
5454 readonly ceilingDollars: number;
55 /**
56 * The cloud project its machines and volumes are filed in (DigitalOcean); empty is the provider's
57 * default.
58 */
59 readonly project: string;
5560 }
5661
5762 interface Row {
@@ -61,6 +66,7 @@ interface Row {
6166 verified_at: string | null;
6267 write_allowed: number;
6368 ceiling_dollars: number;
69 project: string;
6470 }
6571
6672 const toAccount = (r: Row): CloudAccount => ({
@@ -70,6 +76,7 @@ const toAccount = (r: Row): CloudAccount => ({
7076 verifiedAt: r.verified_at,
7177 writeAllowed: r.write_allowed === 1,
7278 ceilingDollars: r.ceiling_dollars,
79 project: r.project ?? "",
7380 });
7481
7582 export function listCloudAccounts(db: Database): CloudAccount[] {
@@ -130,6 +137,11 @@ export function setCeilingDollars(db: Database, provider: string, name: string,
130137 return db.query("UPDATE cloud_account SET ceiling_dollars = ?3 WHERE provider = ?1 AND name = ?2").run(provider, name, dollars).changes > 0;
131138 }
132139
140 export function setProjectName(db: Database, provider: string, name: string, project: string): boolean {
141 table(db);
142 return db.query("UPDATE cloud_account SET project = ?3 WHERE provider = ?1 AND name = ?2").run(provider, name, project).changes > 0;
143 }
144
133145 export function renameCloudAccount(
134146 db: Database,
135147 provider: string,
src/core/event_audience.ts +1
@@ -307,6 +307,7 @@ export function classifiedAudience(kind: string): EventAudience | undefined {
307307 kind === "forge.updates_taken" ||
308308 kind === "cloud.write_allowed" ||
309309 kind === "cloud.ceiling" ||
310 kind === "cloud.project" ||
310311 // How many prepared machines a plan keeps waiting is a spend choice (`cloud/warm_pool.ts`,
311312 // #16362).
312313 kind === "cloud.warm_target" ||
src/core/migration-pins/20261127100000-cloud-account-project.pin added +1
@@ -0,0 +1,1 @@
1 e12b67a55c1d59558e90a98fee8bf24077db280c9420107dec62777a6b81b97b
src/core/migrations/20261127100000-cloud-account-project.ts added +5
@@ -0,0 +1,5 @@
1 // The cloud project a cloud account's forges are filed in (#16340): a name, empty until set, which
2 // means the provider's own default. Additive.
3 export default `
4 ALTER TABLE cloud_account ADD COLUMN project TEXT NOT NULL DEFAULT '';
5 `;
src/http/marks/settings.json +1
@@ -62,6 +62,7 @@
6262 "/settings/cloud/verify": "admin",
6363 "/settings/cloud/write": "admin",
6464 "/settings/cloud/ceiling": "admin",
65 "/settings/cloud/project": "admin",
6566 "/settings/cloud/audit": "admin",
6667 "/settings/cloud/rotate": "admin",
6768 "/settings/cloud/rename": "admin",
src/http/mcp/tools/cloud_account.ts +12 −9
@@ -1,5 +1,5 @@
11 import { addAccount, allowWrite, auditAccount, removeAccount, renameAccount, reverify, rotateAccount } from "../../../actions/cloud.ts";
2 import { setCeiling, setWarm } from "../../../actions/cloud_ceiling.ts";
2 import { setCeiling, setProject, setWarm } from "../../../actions/cloud_ceiling.ts";
33 import { PROVIDERS } from "../../../cloud/providers.ts";
44 import { scopeAllows } from "../../../core/tokens.ts";
55 import { good, bad, type Tool, str } from "../shared.ts";
@@ -7,13 +7,13 @@ import { good, bad, type Tool, str } from "../shared.ts";
77 export const tool: Tool = {
88 name: "cloud_account",
99 listedTo: "admin",
10 doc: "`{ verb, provider, name, value?, to?, allowed?, repo?, dollars?, place?, count? }`: change a cloud account: `attach` or `rotate` a token (`value`), `verify` it, `rename` it (`to`), `remove` it, `allow_writes` (`allowed` true or false), `set_ceiling` (`dollars`: the most the forge lets it cost a month, whole US dollars, 50 until changed) `set_warm` (`place`, `count`: how many prepared machines to keep booted and waiting at a place, 0 until set, counted against the ceiling and shown beside it), or `audit` (`repo` owner/name); a forge admin with an admin-scope token; answers a one-line `says`",
10 doc: "`{ verb, provider, name, value?, to?, allowed?, repo?, dollars?, place?, count?, project? }`: change a cloud account: `attach` or `rotate` a token (`value`), `verify` it, `rename` it (`to`), `remove` it, `allow_writes` (`allowed` true or false), `set_ceiling` (`dollars`: the most the forge lets it cost a month, whole US dollars, 50 until changed) `set_project` (`project`: the DigitalOcean project its forges are filed in, empty for the default; a Hetzner token already has one), `set_warm` (`place`, `count`: how many prepared machines to keep booted and waiting at a place, 0 until set, counted against the ceiling and shown beside it), or `audit` (`repo` owner/name); a forge admin with an admin-scope token; answers a one-line `says`",
1111 description:
1212 "Change a cloud account by `verb` (admin).",
1313 inputSchema: {
1414 type: "object",
1515 properties: {
16 verb: { type: "string", enum: ["attach", "verify", "rotate", "rename", "remove", "allow_writes", "set_ceiling", "set_warm", "audit"] },
16 verb: { type: "string", enum: ["attach", "verify", "rotate", "rename", "remove", "allow_writes", "set_ceiling", "set_project", "set_warm", "audit"] },
1717 provider: { type: "string", enum: [...PROVIDERS] },
1818 name: { type: "string", maxLength: 32 },
1919 value: { type: "string", maxLength: 4096, description: "For attach, rotate." },
@@ -22,6 +22,7 @@ export const tool: Tool = {
2222 repo: { type: "string", maxLength: 200 },
2323 place: { type: "string", maxLength: 100, description: "For set_warm: provider:datacenter:size." },
2424 count: { type: "integer", minimum: 0, maximum: 10, description: "For set_warm." },
25 project: { type: "string", maxLength: 100, description: "For set_project." },
2526 dollars: { type: "integer", minimum: 0, maximum: 100000, description: "For set_ceiling." },
2627 },
2728 required: ["verb", "provider", "name"],
@@ -54,12 +55,14 @@ export const tool: Tool = {
5455 ? allowWrite(ctx.app, user, provider, name, args["allowed"] === true)
5556 : verb === "set_ceiling"
5657 ? setCeiling(ctx.app, user, provider, name, args["dollars"])
57 : verb === "set_warm"
58 ? setWarm(ctx.app, user, provider, name, args["place"], args["count"])
59 : verb === "audit"
60 ? await auditAccount(ctx.app, user, provider, name, str(args["repo"]))
61 : undefined;
62 if (done === undefined) return bad("bad_verb", "verb is attach, verify, rotate, rename, remove, allow_writes, set_ceiling, set_warm or audit");
58 : verb === "set_project"
59 ? setProject(ctx.app, user, provider, name, args["project"])

The set_project branch is indented one level too shallow against the neighbouring branches. Fix the ternary layout.

60 : verb === "set_warm"
61 ? setWarm(ctx.app, user, provider, name, args["place"], args["count"])
62 : verb === "audit"
63 ? await auditAccount(ctx.app, user, provider, name, str(args["repo"]))
64 : undefined;
65 if (done === undefined) return bad("bad_verb", "verb is attach, verify, rotate, rename, remove, allow_writes, set_ceiling, set_project, set_warm or audit");
6366 if (!done.ok) return bad("refused", done.error);
6467 const v = done.value as unknown;
6568 const said =
src/http/mcp/tools/pinned_forge.ts +8 −4
@@ -1,4 +1,4 @@
1 import { DOMAIN_WORDS, changeBaseDomain, checkPinned, checkWords, claimPinned, claimWords, deployPinned, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, updatePinned } from "../../../actions/pinned.ts";
1 import { DOMAIN_WORDS, changeBaseDomain, checkPinned, checkWords, claimPinned, claimWords, deployPinned, fileForge, 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,7 +6,7 @@ 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?, 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",
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). `file`: put its machine and volume in its cloud account's project (a forge made before the project was set). `list`: all, with changes. A forge admin with an admin-scope token",
1010 description: "Pinned forges on your cloud: list, deploy, claim, update, rollback, check, retire (admin).",
1111 tier: "delete",
1212 deletes: (args) => args["verb"] === "retire" && args["withData"] === true,
@@ -14,7 +14,7 @@ export const tool: Tool = {
1414 inputSchema: {
1515 type: "object",
1616 properties: {
17 verb: { type: "string", enum: ["list", "deploy", "claim", "update", "rollback", "check", "domain", "retire"] },
17 verb: { type: "string", enum: ["list", "deploy", "claim", "update", "rollback", "check", "domain", "retire", "file"] },
1818 withData: { type: "boolean", description: "Retire: delete the data too; no undo." },
1919 despiteClaim: { type: "boolean", description: "Retire a forge its buyer claimed." },
2020 domain: { type: "string", maxLength: 253, description: "Domain for deployed forges; empty clears." },
@@ -70,6 +70,10 @@ export const tool: Tool = {
7070 const done = await retirePinned(ctx.app, user, name, { withData: args["withData"] === true, despiteClaim: args["despiteClaim"] === true });
7171 return done.ok ? good({ says: retireWords(done.value), forge: done.value }) : bad("refused", done.error);
7272 }
73 if (verb === "file") {
74 const filed = await fileForge(ctx.app, user, name);
75 return filed.ok ? good({ says: filed.value }) : bad("refused", filed.error);
76 }
7377 if (verb === "check") {
7478 const seen = await checkPinned(ctx.app, user, name);
7579 return seen.ok ? good({ says: `check ${name}: now ${seen.value.version}. ${checkWords(seen.value)}`, forge: seen.value }) : bad("refused", seen.error);
@@ -83,7 +87,7 @@ export const tool: Tool = {
8387 : verb === "rollback"
8488 ? await rollbackPinned(ctx.app, user, name)
8589 : undefined;
86 if (done === undefined) return bad("bad_verb", "verb is list, deploy, claim, update, rollback, check, retire or domain");
90 if (done === undefined) return bad("bad_verb", "verb is list, deploy, claim, update, rollback, check, retire, file or domain");
8791 if (!done.ok) return bad("refused", done.error);
8892 return good({ says: `${verb} ${name}: now ${done.value.version}, ${done.value.state}${done.value.url ? ` at ${done.value.url}` : ""}.`, forge: done.value });
8993 },
src/http/pinned_routes.ts +4 −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, PAID_PLACEMENT_WORDS, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, checkWords, claimPinned, deployPinned, deployPlaces, pinnedForges, retirePinned, retireWords, rollbackPinned, updatePinned, type Issued } from "../actions/pinned.ts";
10 import { DOMAIN_WORDS, PAID_PLACEMENT_WORDS, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, checkWords, claimPinned, deployPinned, fileForge, 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";
@@ -112,6 +112,9 @@ async function pinnedAct(ctx: Ctx): Promise<Response> {
112112 // the confirm page. A claimed forge is retired only when the form says the owner means it.
113113 const gone = await retirePinned(ctx.app, user, name, { withData: act === "retire-data", despiteClaim: field(form, "despite_claim") === "1" });
114114 return flashTo(ctx, "/pinned", gone.ok ? { tone: "success", message: retireWords(gone.value) } : { tone: "danger", message: gone.error });
115 } else if (act === "file") {
116 const filed = await fileForge(ctx.app, user, name);
117 return flashTo(ctx, "/pinned", filed.ok ? { tone: "success", message: filed.value } : { tone: "danger", message: filed.error });
115118 } else if (act === "claim") {
116119 const made = await claimPinned(ctx.app, user, name, { host: field(form, "host") });
117120 return made.ok ? shown(ctx, `A new claim link for ${name}`, made.value) : flashTo(ctx, "/pinned", { tone: "danger", message: made.error });
src/http/settings_routes.ts +2
@@ -69,6 +69,7 @@ import {
6969 cloudAudit,
7070 cloudAuditPage,
7171 cloudCeiling,
72 cloudProject,
7273 cloudRename,
7374 cloudRotate,
7475 cloudPage,
@@ -237,6 +238,7 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
237238 router.add("POST", "/settings/cloud/verify", cloudVerify);
238239 router.add("POST", "/settings/cloud/write", cloudWrite);
239240 router.add("POST", "/settings/cloud/ceiling", cloudCeiling);
241 router.add("POST", "/settings/cloud/project", cloudProject);
240242 router.add("POST", "/settings/cloud/audit", cloudAudit);
241243 router.add("GET", "/settings/cloud/audit", cloudAuditPage);
242244 router.add("POST", "/settings/cloud/rotate", cloudRotate);
src/tui/screens/cloud.ts +15
@@ -8,6 +8,7 @@
88 */
99
1010 import { addAccount, allowWrite, auditAccount, removeAccount, renameAccount, reverify, rotateAccount } from "../../actions/cloud.ts";
11 import { setProject } from "../../actions/cloud_ceiling.ts";
1112 import { usesByVendor, type VendorUse } from "../../cloud/declared.ts";
1213 import { cloudOverview } from "../../cloud/overview.ts";
1314 import { dollars } from "../../cloud/prices.ts";
@@ -120,6 +121,7 @@ export function cloudScreen(f: Session, ctx: Ctx): Screen {
120121 binding(["n"], "rename"),
121122 binding(["x"], "remove"),
122123 binding(["w"], "writes on/off"),
124 binding(["P"], "project for its forges"),
123125 binding(["A"], "audit"),
124126 binding(["c"], "calls today"),
125127 ],
@@ -178,6 +180,19 @@ export function cloudScreen(f: Session, ctx: Ctx): Screen {
178180 },
179181 }),
180182 );
183 else if (e.key === "P")
184 ctx.push(
185 promptScreen(ctx, screen, {
186 title: `Project for the forges of ${provider}/${name}`,
187 label: "the cloud project its machines and volumes are filed in; empty for the default",
188 onSubmit: (project) => {
189 const r = setProject(f.app, f.user, provider, name, project.trim());
190 if (!r.ok) return r.error;
191 say(`Saved: ${r.value}.`);
192 return undefined;
193 },
194 }),
195 );
181196 else if (e.key === "w") {
182197 const r = allowWrite(f.app, f.user, provider, name, !a.writeAllowed);
183198 say(r.ok ? `${provider}/${name}: ${a.writeAllowed ? "read-only" : "writes allowed"}.` : r.error);
src/tui/screens/pinned.ts +12 −9
@@ -2,16 +2,16 @@
22 * Pinned forges in the terminal, a forge admin's (#8697): each forge with its
33 * version, state and last changes, as the API lists them. `d` deploys, `u`
44 * updates (the only way its version or config move), `r` rolls back to the
5 * previous version, `c` reads the address back and probes it, `n` issues a
6 * 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), `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
9 * `actions/pinned.ts`, so the checks, the record of who and when and the events
10 * the web screens follow are the API's.
11 * Anyone else sees nothing and does nothing.
5 * previous version, `f` files its machine and volume in its account's cloud project, `c` reads the
6 * address back and probes it, `n` issues a new claim link (shown once, as a deploy's is), `b` sets
7 * the domain deployed forges are served on (a deploy then needs no hostname: `-` in its place), `x`
8 * retires a forge (its machine goes, its data is kept unless the name is typed to delete it too; a
9 * claimed forge is asked about twice), each through `actions/pinned.ts`, so the checks, the record
10 * of who and when and the events the web screens follow are the API's. Anyone else sees nothing and
11 * does nothing.
1212 */
1313
14 import { DOMAIN_WORDS, PAID_PLACEMENT_WORDS, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, checkWords, claimPinned, claimWords, deployPinned, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, updatePinned, type Issued } from "../../actions/pinned.ts";
14 import { DOMAIN_WORDS, PAID_PLACEMENT_WORDS, changeBaseDomain, changePaidPlacement, readPaidPlacement, checkPinned, checkWords, claimPinned, claimWords, deployPinned, fileForge, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, updatePinned, type Issued } from "../../actions/pinned.ts";
1515 import type { Ctx, Screen } from "../app/app.ts";
1616 import { binding } from "../app/keys.ts";
1717 import { style } from "../term/style.ts";
@@ -137,7 +137,7 @@ export function pinnedScreen(f: Session, ctx: Ctx): Screen {
137137
138138 const screen: Screen = {
139139 title: "Pinned 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(["p"], "paid forges run on"), binding(["x"], "retire")],
140 keys: [binding(["j", "k"], "move cursor"), binding(["d"], "deploy"), binding(["u"], "update"), binding(["r"], "roll back"), binding(["c"], "check"), binding(["f"], "file in its cloud project"), binding(["n"], "new claim link"), binding(["b"], "domain for forges"), binding(["p"], "paid forges run on"), binding(["x"], "retire")],
141141 async load(signal) {
142142 live(f, signal, { kinds: ["pinned.deployed", "pinned.update", "pinned.rollback", "pinned.check", "pinned.claim_issued", "pinned.claimed"] }, () => ctx.invalidate());
143143 },
@@ -205,6 +205,9 @@ export function pinnedScreen(f: Session, ctx: Ctx): Screen {
205205 } else if (e.key === "c") {
206206 say(`Checking ${p.name}…`);
207207 void checkPinned(f.app, f.user, p.name).then((r) => say(r.ok ? checkWords(r.value) : r.error));
208 } else if (e.key === "f") {
209 say(`Filing ${p.name} in its cloud project…`);
210 void fileForge(f.app, f.user, p.name).then((r) => say(r.ok ? r.value : r.error));
208211 } else if (e.key === "n") offerClaim(f, ctx, screen, say, p);
209212 else if (e.key === "x") offerRetire(f, ctx, screen, say, p);
210213 else if (e.key === "u")
src/web/pages/cloud.ts +19 −1
@@ -33,7 +33,7 @@ import { nameFrame, notePhase, takeSessionTime, timePhase, timePhaseAsync } from
3333 import type { Ctx } from "../../http/context.ts";
3434 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
3535 import { field, readForm } from "../form.ts";
36 import { setCeiling } from "../../actions/cloud_ceiling.ts";
36 import { setCeiling, setProject } from "../../actions/cloud_ceiling.ts";
3737 import { html, type Html } from "../html.ts";
3838 import { flashTo, page } from "../layout.ts";
3939 import { btn, confirmAction, icon, row, time } from "../ui.ts";
@@ -96,6 +96,14 @@ function accountsCard(db: Database, accounts: CloudAccount[], reads: CloudRead[]
9696 aria-label="Monthly ceiling in US dollars for ${a.name}" required />
9797 ${btn("Set ceiling", { size: "sm", label: `Set the ceiling of ${a.name}` })}
9898 </form>
99 ${a.provider === "digitalocean"
100 ? html`<form method="post" action="/settings/cloud/project" class="row-fields">
101 ${hidden(a.provider, a.name)}
102 <input class="input" type="text" name="project" value="${a.project}" placeholder="project for its forges"
103 aria-label="Cloud project for the forges of ${a.name}" maxlength="100" />
104 ${btn("Set project", { size: "sm", label: `Set the project of ${a.name}` })}
105 </form>`
106 : ""}
99107 <form method="post" action="/settings/cloud/audit" class="row-fields">
outdated

Principle 1: the same explanation is printed under every Hetzner account. Drop this branch; the refusal already says it if someone tries.

100108 ${hidden(a.provider, a.name)}
101109 <input class="input" type="text" name="repo" placeholder="owner/repo for findings"
@@ -236,6 +244,16 @@ export async function cloudCeiling(ctx: Ctx): Promise<Response> {
236244 return flashTo(ctx, "/settings/cloud", r.ok ? { message: `Saved: ${r.value}.` } : { tone: "danger", message: r.error });
237245 }
238246
247 // POST /settings/cloud/project: the cloud project an account's forges are filed in.
248 export async function cloudProject(ctx: Ctx): Promise<Response> {
249 const denied = requireAdmin(ctx);
250 if (denied) return denied;
251 const form = await readForm(ctx, "admin");
252 if (form instanceof Response) return form;
253 const r = setProject(ctx.app, ctx.auth.user, field(form, "provider"), field(form, "name"), field(form, "project").trim());
254 return flashTo(ctx, "/settings/cloud", r.ok ? { message: `Saved: ${r.value}.` } : { tone: "danger", message: r.error });
255 }
256
239257 // POST /settings/cloud/audit
240258 export async function cloudAudit(ctx: Ctx): Promise<Response> {
241259 const denied = requireAdmin(ctx);
src/web/pages/pinned.ts +5
@@ -36,6 +36,10 @@ function actions(p: PinnedView): Html {
3636 <input type="hidden" name="to" value="${to("check")}" />
3737 ${btn("Check", { variant: "ghost", label: `Check ${p.name}` })}
3838 </form>`;
39 const file = html`<form method="get" action="/-/confirm">
40 <input type="hidden" name="to" value="${to("file")}" />
41 ${btn("File in project", { variant: "ghost", label: `File ${p.name} in its cloud project` })}
42 </form>`;
3943 // Retire asks the confirm page; a claimed forge's form says the owner means it (`despite_claim`).
4044 const retire = (act: string, label: string, claimed: boolean): Html => html`<form method="get" action="/-/confirm">
4145 <input type="hidden" name="to" value="${to(act)}" />
@@ -57,6 +61,7 @@ function actions(p: PinnedView): Html {
5761 ${btn("Roll back", { variant: "secondary", label: `Roll back ${p.name}` })}
5862 </form>
5963 ${check}
64 ${p.volume === "" ? null : file}
6065 <form method="get" action="/-/confirm">
6166 <input type="hidden" name="to" value="${to("claim")}" />
6267 ${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}
test/cloud-page-shape.test.ts +13 −1
@@ -4,7 +4,8 @@ import { mkdtemp, rm } from "node:fs/promises";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
66 import { createApp, type App } from "../src/app.ts";
7 import { createUser } from "../src/core/users.ts";
7 import { addAccount, net as cloudNet } from "../src/actions/cloud.ts";
8 import { createUser, getUserByName } from "../src/core/users.ts";
89 import { serve, type Servers } from "../src/http/server.ts";
910 import { quietLogs } from "./helpers/globals.ts";
1011
@@ -71,3 +72,14 @@ test("a signed-in non-admin gets the gate's 403 for the vendor calls", async ()
7172 expect(res.status).toBe(403);
7273 expect(await res.text()).not.toContain("vendor call");
7374 });
75
76 test("a Hetzner row has no project field and no explanation; a DigitalOcean row has the field", async () => {
77 cloudNet.fetch = async () => new Response(JSON.stringify({ account: { email: "[email protected]", status: "active" }, servers: [] }), { status: 200 });
78 const alice = getUserByName(app.db, "alice")!;
79 await addAccount(app, alice, "hetzner", "main", "hcloud_Zq4TxLm7Kp2Vb8nWcR5Yd3Fg6Hj9");
80 await addAccount(app, alice, "digitalocean", "main", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5");
81 const page = await (await fetch(`${servers.url}/settings/cloud`, { headers: { cookie } })).text();
82 expect(page).toContain("Cloud project for the forges of main");
83 expect(page.match(/Cloud project for the forges of/g)).toHaveLength(1);
84 expect(page).not.toContain("already belongs to one project");
85 });
test/pinned-ceiling.test.ts +2 −2
@@ -369,8 +369,8 @@ describe("cloud account ceiling", () => {
369369 }
370370 expect(bare).toEqual([]);
371371 // Deploy, update or rollback (asked, then made), a new claim link, the read and the retire: the
372 // six there are.
373 expect(uses).toBe(6);
372 // and filing in a project (#16340): the seven there are.
373 expect(uses).toBe(7);
374374 });
375375 });
376376
test/pinned-project-actions.test.ts added +111
@@ -0,0 +1,111 @@
1 /**
2 * #16340 end to end through the actions: the account's project, a deploy that files, one that
3 * refuses, and `file`.
4 */
5 import { afterAll, beforeAll, 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 { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts";
11 import { setProject } from "../src/actions/cloud_ceiling.ts";
12 import { deployPinned, fileForge, net } from "../src/actions/pinned.ts";
13 import { getCloudAccount } from "../src/core/cloud_account.ts";
14 import { getPinned } from "../src/core/pinned.ts";
15 import { createUser, getUserByName } from "../src/core/users.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17 import { seedPlaces } from "./helpers/places-fixture.ts";
18
19 quietLogs();
20
21 let dataDir = "";
22 let app: App;
23 let projects: unknown[] = [{ id: "p1", name: "forges" }];
24 const calls: { method: string; path: string; body: any }[] = [];
25 const admin = () => getUserByName(app.db, "alice")!;
26 const input = (name: string) => ({ name, host: `${name}.forge.test`, target: "digitalocean", account: "main", app: "alice/shop", source: "https://forge.example.org/trevato/forge", version: "a".repeat(40), config: {} });
27
28 beforeAll(async () => {
29 dataDir = await mkdtemp(join(tmpdir(), "forge-project-"));
30 app = createApp({ dataDir, port: 0 });
31 await seedPlaces(app.db);
32 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
33 if (!made.ok) throw new Error(made.error);
34 cloudNet.fetch = async () => new Response(JSON.stringify({ account: { email: "[email protected]", status: "active" } }), { status: 200 });
35 const added = await addAccount(app, admin(), "digitalocean", "main", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5");
36 if (!added.ok) throw new Error(String(added.error));
37 allowWrite(app, admin(), "digitalocean", "main", true);
38 await addAccount(app, admin(), "hetzner", "main", "hcloud_Zq4TxLm7Kp2Vb8nWcR5Yd3Fg6Hj9");
39 let seq = 100;
40 net.fetch = async (url, init) => {
41 const u = new URL(url);
42 const method = init?.method ?? "GET";
43 calls.push({ method, path: u.pathname, body: init?.body ? JSON.parse(String(init.body)) : undefined });
44 const json = (o: unknown) => new Response(JSON.stringify(o), { status: 200 });
45 if (u.pathname === "/v2/projects") return json({ projects });
46 if (u.pathname === "/v2/volumes") return json({ volume: { id: `vol-${++seq}` } });
47 if (u.pathname === "/v2/account/keys" && method === "POST") return json({ ssh_key: { id: 4242 } });
48 if (method === "DELETE") return new Response(null, { status: 204 });
49 if (u.pathname === "/v2/droplets") return json({ droplet: { id: ++seq } });
50 return json({});
51 };
52 }, 30_000);
53
54 afterAll(async () => {
55 app.close();
56 await rm(dataDir, { recursive: true, force: true });
57 });
58
59 const creates = () => calls.filter((c) => c.method === "POST" && /\/(volumes|droplets)$/.test(c.path));
60
61 test("the project is a field of the account, set by an admin only, and Hetzner has none to name", () => {
62 expect(setProject(app, undefined, "digitalocean", "main", "forges")).toEqual({ ok: false, error: "not_found" });
63 expect(setProject(app, admin(), "digitalocean", "main", "bad<name>").ok).toBe(false);
64 expect(setProject(app, admin(), "digitalocean", "nope", "forges").ok).toBe(false);
65 const h = setProject(app, admin(), "hetzner", "main", "forges");
66 expect(h.ok === false && h.error).toContain("already belongs to one project");
67 expect(setProject(app, admin(), "digitalocean", "main", "forges").ok).toBe(true);
68 expect(getCloudAccount(app.db, "digitalocean", "main")!.project).toBe("forges");
69 });
70
71 test("a deploy into a project that does not exist is refused with zero creates", async () => {
72 projects = [{ id: "p0", name: "first-project" }];
73 calls.length = 0;
74 const r = await deployPinned(app, admin(), input("lost"));
75 expect(r.ok).toBe(false);
76 expect(String((r as { error: string }).error)).toContain('no project called "forges"');
77 expect(creates()).toEqual([]);
78 });
79
80 test("a deploy files its droplet and volume, and a forge made before can be filed by one call", async () => {
81 projects = [{ id: "p1", name: "forges" }];
82 calls.length = 0;
83 expect((await deployPinned(app, admin(), input("test1"))).ok).toBe(true);
84 const filed = calls.filter((c) => c.path === "/v2/projects/p1/resources");
85 expect(filed).toHaveLength(1);
86 const p = getPinned(app.db, "test1")!;
87 expect(filed[0]!.body.resources).toEqual([`do:droplet:${p.remote}`, `do:volume:${p.volume}`]);
88 calls.length = 0;
89 const again = await fileForge(app, admin(), "test1");
90 expect(again.ok).toBe(true);
91 expect(calls.filter((c) => c.path === "/v2/projects/p1/resources")).toHaveLength(1);
92 expect((await fileForge(app, undefined, "test1")).ok).toBe(false);
93 setProject(app, admin(), "digitalocean", "main", "");
94 expect((await fileForge(app, admin(), "test1")).ok).toBe(false);
95 });
96
97 test("a filing the cloud refuses leaves the forge made and says on the bus that it stayed unfiled", async () => {
98 setProject(app, admin(), "digitalocean", "main", "forges");
99 projects = [{ id: "p1", name: "forges" }];
100 const was = net.fetch;
101 net.fetch = (url, init) => (new URL(url).pathname.endsWith("/resources") ? Promise.resolve(new Response("{}", { status: 500 })) : was(url, init));
102 try {
103 expect((await deployPinned(app, admin(), input("test2"))).ok).toBe(true);
104 } finally {
105 net.fetch = was;
106 }
107 expect(getPinned(app.db, "test2")!.remote).not.toBe("");
108 const seen = app.db.query("SELECT payload FROM event WHERE kind = 'pinned.unfiled'").get() as { payload: string } | null;
109 expect(JSON.parse(seen!.payload)).toMatchObject({ name: "test2" });
110 expect(seen!.payload).toContain("`file`");
111 });
test/pinned-project.test.ts added +99
@@ -0,0 +1,99 @@
1 import { expect, test } from "bun:test";
2 import { digitalocean } from "../src/cloud/droplet.ts";
3 import { hetzner } from "../src/cloud/hetzner.ts";
4 import { DETACH, fileIn, provision, replace } from "../src/cloud/machine.ts";
5
6 // #16340: a forge's droplet and volume are filed in the account's cloud project, and carry a tag
7 // naming the forge; a project that is not there refuses before anything is made.
8 const p = { name: "test1", datacenter: "fra1", size: "s-1vcpu-1gb", remote: "11", volume: "vol-a", source: "https://x.test/r.git", version: "v1.0.0", config: {}, host: "t.example.test", claimHash: "", claimExpires: "" } as any;
9
10 function recorded(projects: unknown[]) {
11 const log: { method: string; path: string; body: any }[] = [];
12 const f = (async (url: string, init: any) => {
13 const path = String(url).replace("https://api.digitalocean.com/v2", "");
14 const body = init.body ? JSON.parse(init.body) : undefined;
15 log.push({ method: init.method, path, body });
16 const json = (o: unknown) => new Response(JSON.stringify(o), { status: 200 });
17 if (path.startsWith("/projects?")) return json({ projects });
18 if (path === "/volumes" && init.method === "POST") return json({ volume: { id: "vol-a" } });
19 if (path === "/account/keys" && init.method === "POST") return json({ ssh_key: { id: 5 } });
20 if (path === "/droplets" && init.method === "POST") return json({ droplet: { id: 22 } });
21 if (path.startsWith("/volumes/")) return json({ volume: { droplet_ids: [] } });
22 return json({});
23 }) as any;
24 return { f, log };
25 }
26 const FORGES = [{ id: "proj-1", name: "forges" }, { id: "proj-0", name: "first-project" }];
27 const assigns = (log: { method: string; path: string; body: any }[]) => log.filter((c) => c.path.endsWith("/resources"));
28
29 test("a deploy files the droplet and the volume in the named project and tags both", async () => {
30 const { f, log } = recorded(FORGES);
31 const made = await provision(digitalocean, f, "t", p, { project: "forges", onVolume() {} });
32 expect(made).toEqual({ remote: "22", volume: "vol-a" });
33 expect(assigns(log)).toEqual([{ method: "POST", path: "/projects/proj-1/resources", body: { resources: ["do:droplet:22", "do:volume:vol-a"] } }]);
34 expect(log.find((c) => c.path === "/volumes")!.body.tags).toEqual(["forge:test1"]);
35 expect(log.find((c) => c.path === "/droplets")!.body.tags).toContain("forge:test1");
36 expect(log.indexOf(assigns(log)[0]!)).toBeGreaterThan(log.findIndex((c) => c.path === "/droplets"));
37 });
38
39 test("a project that is not there refuses with nothing made", async () => {
40 const { f, log } = recorded([{ id: "proj-0", name: "first-project" }]);
41 await expect(provision(digitalocean, f, "t", p, { project: "forges", onVolume() {} })).rejects.toThrow('no project called "forges"');
42 expect(log.filter((c) => c.method === "POST")).toEqual([]);
43 });
44
45 test("a replace files the new droplet the same way, and refuses before deleting when the project is gone", async () => {
46 const keep = { ...DETACH };
47 DETACH.everyMs = 1;
48 try {
49 const { f, log } = recorded(FORGES);
50 expect((await replace(digitalocean, f, "t", p, { project: "forges", onDeleted() {} })).remote).toBe("22");
51 expect(assigns(log)[0]!.body).toEqual({ resources: ["do:droplet:22", "do:volume:vol-a"] });
52 const none = recorded([]);
53 await expect(replace(digitalocean, none.f, "t", p, { project: "forges", onDeleted() {} })).rejects.toThrow("no project");
54 expect(none.log.some((c) => c.method === "DELETE" || c.method === "POST")).toBe(false);
55 } finally { Object.assign(DETACH, keep); }
56 });
57
58 test("a refused filing keeps the machine that was made", async () => {
59 const { f, log } = recorded(FORGES);
60 const bad = ((url: string, init: any) => String(url).endsWith("/resources") ? Promise.resolve(new Response("{}", { status: 500 })) : f(url, init)) as any;
61 expect((await provision(digitalocean, bad, "t", p, { project: "forges", onVolume() {} })).remote).toBe("22");
62 expect(log.some((c) => c.path === "/droplets")).toBe(true);
63 });
64
65 test("a refused filing is told to onUnfiled, with the reason", async () => {
66 const { f } = recorded(FORGES);
67 const bad = ((url: string, init: any) => String(url).endsWith("/resources") ? Promise.resolve(new Response("{}", { status: 500 })) : f(url, init)) as any;
68 const told: string[] = [];
69 await provision(digitalocean, bad, "t", p, { project: "forges", onVolume() {}, onUnfiled: (why) => told.push(why) });
70 expect(told).toEqual(["api.digitalocean.com answered 500"]);
71 const ok = recorded(FORGES);
72 await provision(digitalocean, ok.f, "t", p, { project: "forges", onVolume() {}, onUnfiled: (why) => told.push(why) });
73 expect(told.length).toBe(1);
74 });
75
76 test("a row made before the project was set is filed by one call", async () => {
77 const { f, log } = recorded(FORGES);
78 await fileIn(digitalocean, f, "t", p, "forges");
79 expect(assigns(log)).toHaveLength(1);
80 expect(assigns(log)[0]!.body.resources).toEqual(["do:droplet:11", "do:volume:vol-a"]);
81 });
82
83 test("Hetzner has no project to name, and labels the server and the volume with the forge", async () => {
84 const log: { path: string; body: any }[] = [];
85 const f = (async (url: string, init: any) => {
86 const path = String(url).replace("https://api.hetzner.cloud/v1", "");
87 log.push({ path, body: init.body ? JSON.parse(init.body) : undefined });
88 const json = (o: unknown) => new Response(JSON.stringify(o), { status: 200 });
89 if (path === "/volumes") return json({ volume: { id: 7 } });
90 if (path === "/ssh_keys" && init.method === "POST") return json({ ssh_key: { id: 5 } });
91 if (path === "/servers") return json({ server: { id: 8 } });
92 return json({});
93 }) as any;
94 await provision(hetzner, f, "t", p, { project: "forges", onVolume() {} });
95 expect(log.some((c) => c.path.includes("project"))).toBe(false);
96 expect(log.find((c) => c.path === "/volumes")!.body.labels.forge).toBe("test1");
97 expect(log.find((c) => c.path === "/servers")!.body.labels.forge).toBe("test1");
98 await expect(fileIn(hetzner, f, "t", p, "forges")).rejects.toThrow("no projects");
99 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs