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

A pinned forge has its own name, HTTPS and backups, with nothing routed throu… #16220

Merged opened this in answer to

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

Merged

scout/forge:scout/16204-a-pinned-forge-has-its-own-name-https-an → main 0 commits fork 4 threads · 4 unresolved

  • Merged. scout/16204-a-pinned-forge-has-its-own-name-https-an was merged into main as 8551560.

Review

Sign in to review this change.
17 files changed +330 −23
docs/features/pinned-forge.md +8 −3
@@ -8,11 +8,12 @@ A pinned forge is a forge the owner put on their own cloud. It has **no crew** a
88
99 ## Doors (forge admin, admin-scope token)
1010
11 - HTTP: `GET /api/v1/admin/pinned` (forges, their changes, the targets), `POST /api/v1/admin/pinned` (deploy), `POST /api/v1/admin/pinned/:name/update`, `POST /api/v1/admin/pinned/:name/rollback`.
12 - Terminal: palette → **Pinned forges** (forge admin): `d` deploy, `u` update, `r` roll back; it follows the bus, so a change made at any door shows at once (`src/tui/screens/pinned.ts`).
11 - HTTP: `GET /api/v1/admin/pinned` (forges, their changes, the targets), `POST /api/v1/admin/pinned` (deploy), `POST /api/v1/admin/pinned/:name/update`, `POST /api/v1/admin/pinned/:name/rollback`, `POST /api/v1/admin/pinned/:name/claim`.
12 - Terminal: palette → **Pinned forges** (forge admin): `d` deploy, `u` update, `r` roll back, `h` hand to buyer (after a confirm); it follows the bus, so a change made at any door shows at once (`src/tui/screens/pinned.ts`).
1313 - Web: `/deploy-to` (forge admin; linked from Cloud accounts) is a server-rendered form for cloud account, app, source, version and name. 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`).
1414 - 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 three buttons (Update, Roll back, Check), and each goes through the confirm page before it runs (Update also asks for the version). They post to `POST /pinned/:name/:act` (`act` is `update`, `rollback` or `check`; 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`).
15 - MCP: `pinned_forge` with `verb` `list`, `deploy`, `update`, `rollback` (and `check`) — the same words and the same checks (`src/actions/pinned.ts`).
15 - Web **Hand to buyer** on `/pinned` (confirm page, then `POST /pinned/:name/claim`) and MCP `pinned_forge` verb `claim` hand a forge over; see After the claim below.
16 - MCP: `pinned_forge` with `verb` `list`, `deploy`, `update`, `rollback`, `check` and `claim` — the same words and the same checks (`src/actions/pinned.ts`).
1617
1718 A deploy names a cloud account (Settings → Cloud accounts, **writes allowed**), the app (`owner/name`), a git `source` (https) and a `version` (a 40-character commit id or a tag like `v1.2.3` — never a branch, so nothing moves under it).
1819
@@ -24,6 +25,10 @@ A deploy names a cloud account (Settings → Cloud accounts, **writes allowed**)
2425
2526 The cloud token stays sealed. It is opened for the one call that needs it (a `secret.read` event names the run), sent as an `Authorization` header over HTTPS, and never reaches argv, a row, an event, a request body or the boot script. The boot script holds no secret: the new forge's first visitor claims it. Config refuses names that look like secrets.
2627
28 ## After the claim: what the host can still do (#16204)
29
30 `claim` (web `Hand to buyer` on `/pinned`, MCP `pinned_forge` verb `claim`, `POST /api/v1/admin/pinned/:name/claim`, terminal `h`) records that the forge was handed to its buyer (`pinned_forge.claimed_at`, event `pinned.claimed`). From then the selling forge refuses `update` and `rollback` for it: updates are the buyer's to take. `/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).
31
2732 ## Targets: what runs, what it costs, what is refused
2833
2934 Prices are list prices as last read (USD a month); the owner's own bill is the truth. Source of truth in code: `src/cloud/targets.ts`.
src/actions/pinned.ts +17 −2
@@ -17,8 +17,8 @@ import type { Fetch } from "../cloud/providers.ts";
1717 import { target as targetOf } from "../cloud/targets.ts";
1818 import { getCloudAccount, secretNameOf } from "../core/cloud_account.ts";
1919 import {
20 APP, NAME, changesOf, checkConfig, getPinned, insertPinned, listPinned, previousOf,
21 dropPinned, recordChange, setRemote, urlOf, validSource, validVersion, type Change, type Pinned,
20 APP, CLAIMED_REFUSAL, NAME, changesOf, checkConfig, getPinned, insertPinned, listPinned, previousOf,
21 dropPinned, markClaimed, recordChange, setRemote, urlOf, validSource, validVersion, type Change, type Pinned,
2222 } from "../core/pinned.ts";
2323 import { resolveSecrets } from "../core/secret_store.ts";
2424 import type { User } from "../core/users.ts";
@@ -123,6 +123,7 @@ async function change(
123123 if (!who.ok) return who;
124124 const before = getPinned(app.db, name);
125125 if (!before) return err("No such pinned forge.");
126 if (before.claimedAt !== "") return err(CLAIMED_REFUSAL);
126127 const to = next(before);
127128 if (!to.ok) return to;
128129 const same = to.value.version === before.version && JSON.stringify(to.value.config) === JSON.stringify(before.config);
@@ -142,6 +143,20 @@ async function change(
142143 return ok(view(app, getPinned(app.db, name)!));
143144 }
144145
146 /**
147 * The forge was handed to its buyer. From here Update and Rollback are refused for it; the buyer's
148 * forge fetches its own versions. Recorded with who and when; claiming twice says so.
149 */
150 export function claimPinned(app: App, actor: User | undefined, name: string): Result<PinnedView, string> {
151 const who = admin(actor);
152 if (!who.ok) return who;
153 const p = getPinned(app.db, name);
154 if (!p) return err("No such pinned forge.");
155 if (!markClaimed(app.db, name)) return err("That forge was handed over already.");
156 app.bus.append({ kind: "pinned.claimed", actorId: who.value.id, payload: { name } });
157 return ok(view(app, getPinned(app.db, name)!));
158 }
159
145160 /** The only door to a new version or config. Either may be left as it is. */
146161 export const updatePinned = (
147162 app: App,
src/contract/openapi/routes/index.ts +1
@@ -298,6 +298,7 @@ export { route as postApiV1AdminMaintenancePrepare } from "./postApiV1AdminMaint
298298 export { route as postApiV1AdminMaintenanceResume } from "./postApiV1AdminMaintenanceResume.ts";
299299 export { route as postApiV1AdminPinned } from "./postApiV1AdminPinned.ts";
300300 export { route as postApiV1AdminPinnedNameCheck } from "./postApiV1AdminPinnedNameCheck.ts";
301 export { route as postApiV1AdminPinnedNameClaim } from "./postApiV1AdminPinnedNameClaim.ts";
301302 export { route as postApiV1AdminPinnedNameRollback } from "./postApiV1AdminPinnedNameRollback.ts";
302303 export { route as postApiV1AdminPinnedNameUpdate } from "./postApiV1AdminPinnedNameUpdate.ts";
303304 export { route as postApiV1AdminReleasesShaRollback } from "./postApiV1AdminReleasesShaRollback.ts";
src/contract/openapi/routes/postApiV1AdminPinnedNameClaim.ts added +13
@@ -0,0 +1,13 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: "/api/v1/admin/pinned/{name}/claim",
6 summary: "Record that the forge was handed to its buyer, for good",
7 auth: true,
8 role: "admin",
9 refusals: {
10 not_found: "only a forge administrator sees this route",
11 refused: "the request was understood and refused; the message says why (422)",
12 },
13 };
src/core/migration-pins/20261124040000-pinned-claimed.pin added +1
@@ -0,0 +1,1 @@
1 9c2e6748112c46891eeccf8d797161e5efb3ee5d764af483378e0291f930d6c1
src/core/migrations/20261124040000-pinned-claimed.ts added +5
@@ -0,0 +1,5 @@
1 // When a pinned forge was handed to its buyer (#16204). After that the selling forge
2 // refuses Update and Rollback for it: its new version is the buyer's to take. Additive.
3 export default `
4 ALTER TABLE pinned_forge ADD COLUMN claimed_at TEXT NOT NULL DEFAULT '';
5 `;
src/core/pinned.ts +22 −2
@@ -22,6 +22,8 @@ export interface Pinned {
2222 readonly volume: string;
2323 readonly address: string;
2424 readonly state: string;
25 /** When the forge was handed to its buyer; empty while the seller still holds it. */
26 readonly claimedAt: string;
2527 readonly createdAt: string;
2628 }
2729
@@ -72,13 +74,13 @@ export function checkConfig(raw: unknown): Result<Record<string, string>, string
7274
7375 interface Row {
7476 id: string; name: string; target: string; account: string; app: string; source: string;
75 version: string; config: string; remote: string; volume: string; address: string; state: string; created_at: string;
77 version: string; config: string; remote: string; volume: string; address: string; state: string; claimed_at: string; created_at: string;
7678 }
7779
7880 const toPinned = (r: Row): Pinned => ({
7981 id: r.id, name: r.name, target: r.target, account: r.account, app: r.app, source: r.source,
8082 version: r.version, config: JSON.parse(r.config) as Record<string, string>,
81 remote: r.remote, volume: r.volume, address: r.address, state: r.state, createdAt: r.created_at,
83 remote: r.remote, volume: r.volume, address: r.address, state: r.state, claimedAt: r.claimed_at, createdAt: r.created_at,
8284 });
8385
8486 export const listPinned = (db: Database): Pinned[] =>
@@ -160,6 +162,24 @@ export function setRemote(db: Database, name: string, f: { remote?: string; volu
160162 .run(f.remote ?? null, f.volume ?? null, f.address ?? null, f.state ?? null, name);
161163 }
162164
165 /**
166 * Hand the forge to its buyer. Once only; returns false when it was claimed already or does not
167 * exist.
168 */
169 export function markClaimed(db: Database, name: string): boolean {
170 return db.query("UPDATE pinned_forge SET claimed_at = ?1 WHERE name = ?2 AND claimed_at = ''").run(new Date().toISOString(), name).changes === 1;
171 }
172
173 /**
174 * What the host can still do, in the words any honest host would use. Shown to the buyer and to the
175 * seller wherever a forge is sold; it never says "no access".
176 */
177 export const HOST_CAN =
178 "In its host's cloud account the host can open a forge's console, boot it into rescue, snapshot its disk and read its boot data; only the buyer's own cloud account gives the host none of that.";
179
180 /** The sentence a refused Update or Rollback gives after the claim. */
181 export const CLAIMED_REFUSAL = "This forge was handed to its buyer: its updates are theirs to take, and this forge no longer changes it.";
182
163183 /** The row of a deploy that never reached a droplet, so its name can be tried again; its recorded change stays as history. */
164184 export function dropPinned(db: Database, name: string): void {
165185 db.query("DELETE FROM pinned_forge WHERE name = ?1 AND remote = '' AND state = 'failed'").run(name);
src/http/api/admin.ts +8 −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 { checkPinned, deployPinned, pinnedForges, rollbackPinned, updatePinned } from "../../actions/pinned.ts";
26 import { checkPinned, claimPinned, deployPinned, pinnedForges, 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";
@@ -113,6 +113,13 @@ export function adminRoutes(router: Router<Handler>): void {
113113 return done.ok ? json(done.value) : pinnedFail(done.error);
114114 });
115115
116 router.add("POST", "/api/v1/admin/pinned/:name/claim", (ctx) => {
117 const denied = accountAdmin(ctx, "admin");
118 if (denied) return denied;
119 const done = claimPinned(ctx.app, ctx.auth.user, ctx.params.name!);
120 return done.ok ? json(done.value) : pinnedFail(done.error);
121 });
122
116123 // ---- accounts: the owner's view of who joined (#660) ----
117124 const accountError = (error: string): Response =>
118125 error === "not_found"
src/http/mcp/tools/pinned_forge.ts +7 −5
@@ -1,16 +1,16 @@
1 import { checkPinned, deployPinned, pinnedForges, rollbackPinned, updatePinned } from "../../../actions/pinned.ts";
1 import { checkPinned, claimPinned, deployPinned, pinnedForges, 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";
55
66 export const tool: Tool = {
77 name: "pinned_forge",
8 doc: "`{ verb, name?, target?, account?, app?, source?, version?, config? }`: a pinned forge on the owner's cloud has no crew and no automatic release. `list` shows them with every recorded change and the targets (what runs, what it costs, what is refused); `deploy` puts one on `target` with a cloud `account` (writes allowed) serving `app` owner/name from `source` at `version`; `update` is the only way its `version` or `config` change; `rollback` goes back one; `check` reads the machine's address back and probes it (`url`, `healthy`). A forge admin with an admin-scope token",
8 doc: "`{ verb, name?, target?, account?, app?, source?, version?, config? }`: a pinned forge on the owner's cloud has no crew and no automatic release. `list` shows them with every recorded change and the targets (what runs, what it costs, what is refused); `deploy` puts one on `target` with a cloud `account` (writes allowed) serving `app` owner/name from `source` at `version`; `update` is the only way its `version` or `config` change; `rollback` goes back one; `claim` records that the forge was handed to its buyer, after which update and rollback are refused; `check` reads the machine's address back and probes it (`url`, `healthy`). A forge admin with an admin-scope token",
99 description: "Pinned forges on your cloud: list, deploy, update, rollback, check (admin).",
1010 inputSchema: {
1111 type: "object",
1212 properties: {
13 verb: { type: "string", enum: ["list", "deploy", "update", "rollback", "check"] },
13 verb: { type: "string", enum: ["list", "deploy", "update", "rollback", "check", "claim"] },
1414 name: { type: "string", maxLength: 40 },
1515 target: { type: "string", enum: TARGETS.map((t) => t.id) },
1616 account: { type: "string", maxLength: 32 },
@@ -48,8 +48,10 @@ export const tool: Tool = {
4848 ? await rollbackPinned(ctx.app, user, name)
4949 : verb === "check"
5050 ? await checkPinned(ctx.app, user, name)
51 : undefined;
52 if (done === undefined) return bad("bad_verb", "verb is list, deploy, update, rollback or check");
51 : verb === "claim"
52 ? claimPinned(ctx.app, user, name)
53 : undefined;
54 if (done === undefined) return bad("bad_verb", "verb is list, deploy, update, rollback, check or claim");
5355 if (!done.ok) return bad("refused", done.error);
5456 return good({ says: `${verb} ${name}: now ${done.value.version}, ${done.value.state}${done.value.url ? ` at ${done.value.url}` : ""}.`, forge: done.value });
5557 },
src/http/pinned_routes.ts +5 −2
@@ -5,7 +5,7 @@
55 * `deployPinned` the API, MCP and terminal call, admin only and same-origin.
66 */
77
8 import { checkPinned, deployPinned, pinnedForges, rollbackPinned, updatePinned } from "../actions/pinned.ts";
8 import { checkPinned, claimPinned, deployPinned, pinnedForges, rollbackPinned, updatePinned } from "../actions/pinned.ts";
99 import { listCloudAccounts } from "../core/cloud_account.ts";
1010 import { lastCheckOf } from "../core/pinned.ts";
1111 import { getUsersByIds } from "../core/users.ts";
@@ -88,6 +88,7 @@ async function pinnedAct(ctx: Ctx): Promise<Response> {
8888 let done;
8989 if (act === "update") done = await updatePinned(ctx.app, user, name, { version: field(form, "version").trim().slice(0, 40) });
9090 else if (act === "rollback") done = await rollbackPinned(ctx.app, user, name);
91 else if (act === "claim") done = claimPinned(ctx.app, user, name);

The claim branch has no test: web POST, the confirm page, and a non-admin getting 404. Also no HTTP API route for claim, so the API door is missing.

9192 else if (act === "check") done = await checkPinned(ctx.app, user, name);
9293 else return notFoundPage(ctx);
9394 if (!done.ok) return flashTo(ctx, "/pinned", { tone: "danger", message: done.error });
@@ -95,7 +96,9 @@ async function pinnedAct(ctx: Ctx): Promise<Response> {
9596 const message =
9697 act === "check"
9798 ? `${name} ${"healthy" in done.value && done.value.healthy ? "answers" : "did not answer"}; it is ${done.value.state}.`
98 : act === "update"
99 : act === "claim"
100 ? `${name} is handed to its buyer; Update and Roll back are refused from now on.`
101 : act === "update"
99102 ? `Updated ${name} to ${at}.`
100103 : `Rolled ${name} back to ${at}.`;
101104 return flashTo(ctx, "/pinned", { tone: "success", message });
src/tui/screens/pinned.ts +18 −4
@@ -8,14 +8,14 @@
88 * Anyone else sees nothing and does nothing.
99 */
1010
11 import { checkPinned, deployPinned, pinnedForges, rollbackPinned, updatePinned } from "../../actions/pinned.ts";
11 import { checkPinned, claimPinned, deployPinned, pinnedForges, rollbackPinned, updatePinned } from "../../actions/pinned.ts";
1212 import type { Ctx, Screen } from "../app/app.ts";
1313 import { binding } from "../app/keys.ts";
1414 import { style } from "../term/style.ts";
1515 import { truncate } from "../term/width.ts";
1616 import type { Session } from "../session.ts";
1717 import { fill, len, split } from "../ui/layout.ts";
18 import { ListState, drawList, live, promptScreen, type ListRow } from "./common.ts";
18 import { ListState, confirmScreen, drawList, live, promptScreen, type ListRow } from "./common.ts";
1919 import type { PaletteEntry } from "./entries.ts";
2020
2121 const short = (v: string): string => (v.length === 40 ? v.slice(0, 10) : v);
@@ -53,9 +53,9 @@ export function pinnedScreen(f: Session, ctx: Ctx): Screen {
5353
5454 const screen: Screen = {
5555 title: "Pinned forges",
56 keys: [binding(["j", "k"], "move cursor"), binding(["d"], "deploy"), binding(["u"], "update"), binding(["r"], "roll back"), binding(["c"], "check")],
56 keys: [binding(["j", "k"], "move cursor"), binding(["d"], "deploy"), binding(["u"], "update"), binding(["r"], "roll back"), binding(["c"], "check"), binding(["h"], "hand to buyer")],
5757 async load(signal) {
58 live(f, signal, { kinds: ["pinned.deployed", "pinned.update", "pinned.rollback", "pinned.check"] }, () => ctx.invalidate());
58 live(f, signal, { kinds: ["pinned.deployed", "pinned.update", "pinned.rollback", "pinned.check", "pinned.claimed"] }, () => ctx.invalidate());
5959 },
6060 render(area, s) {
6161 const c = ctx.theme.c;
@@ -84,6 +84,20 @@ export function pinnedScreen(f: Session, ctx: Ctx): Screen {
8484 if (e.key === "r") {
8585 say(`Rolling ${p.name} back…`);
8686 void settle(rollbackPinned(f.app, f.user, p.name), "Rolled back");
87 } else if (e.key === "h") {
88 const name = p.name;
outdated

Irreversible claim on a single keypress, no confirm. The web door confirms first. Ask before running it, and add a test for this key.

89 ctx.push(
90 confirmScreen(ctx, screen, {
91 title: `Hand ${name} to its buyer`,
92 body: ["From now on this forge refuses Update and Roll back for it.", "This cannot be undone here."],
93 actions: [{ label: "Hand over", variant: "danger" }, { label: "Cancel" }],
94 onChoose: (i) => {
95 if (i !== 0) return;
96 const done = claimPinned(f.app, f.user, name);
97 say(done.ok ? `${name} is handed to its buyer; Update and Roll back are refused from now on.` : done.error);
98 },
99 }),
100 );
87101 } else if (e.key === "c") {
88102 say(`Checking ${p.name}…`);
89103 void checkPinned(f.app, f.user, p.name).then((r) => say(r.ok ? `${p.name} ${r.value.healthy ? "answers" : "does not answer"}${r.value.url ? ` at ${r.value.url}` : " yet: no address"}.` : r.error));
src/web/pages/pinned.ts +12 −2
@@ -5,6 +5,7 @@
55 */
66
77 import type { PinnedView } from "../../actions/pinned.ts";
8 import { HOST_CAN } from "../../core/pinned.ts";
89 import { html, type Html } from "../html.ts";
910 import { badge, btn, time, type Tone } from "../ui.ts";
1011
@@ -22,6 +23,11 @@ const none = (text: string): Html => html`<span class="muted">${text}</span>`;
2223 /** Update asks for the version, Roll back and Check for nothing; each goes through the confirm page, which posts to `/pinned/<name>/<act>`. */
2324 function actions(p: PinnedView): Html {
2425 const to = (act: string): string => `/pinned/${p.name}/${act}`;
26 const check = html`<form method="get" action="/-/confirm">
27 <input type="hidden" name="to" value="${to("check")}" />
28 ${btn("Check", { variant: "ghost", label: `Check ${p.name}` })}
29 </form>`;
30 if (p.claimedAt !== "") return html`<div class="form-actions">${check}</div>`;
2531 return html`<div class="form-actions">
2632 <form method="get" action="/-/confirm">
2733 <input type="hidden" name="to" value="${to("update")}" />
@@ -32,9 +38,10 @@ function actions(p: PinnedView): Html {
3238 <input type="hidden" name="to" value="${to("rollback")}" />
3339 ${btn("Roll back", { variant: "secondary", label: `Roll back ${p.name}` })}
3440 </form>
41 ${check}
3542 <form method="get" action="/-/confirm">
36 <input type="hidden" name="to" value="${to("check")}" />
37 ${btn("Check", { variant: "ghost", label: `Check ${p.name}` })}
43 <input type="hidden" name="to" value="${to("claim")}" />
44 ${btn("Hand to buyer", { variant: "ghost", label: `Hand ${p.name} to its buyer` })}
3845 </form>
3946 </div>`;
4047 }
@@ -51,8 +58,10 @@ function forge(p: PinnedView, f: PinnedFacts): Html {
5158 ${fact("Health", badge(p.state, { tone: TONE[p.state] ?? "default" }))}
5259 ${fact("Last check", checked ? time(checked) : none("never checked"))}
5360 ${fact("Last change", last ? html`${last.kind} to <span class="mono">${last.toVersion.slice(0, 12)}</span>` : none("none"))}
61 ${fact("Handed to buyer", p.claimedAt === "" ? none("not yet") : time(p.claimedAt))}
5462 ${last ? fact("Changed by", html`${f.names.get(last.by) ?? last.by} ${time(last.at)}`) : null}
5563 </dl>
64 ${p.claimedAt === "" ? null : html`<p class="muted small">Its updates are the buyer's to take; Update and Roll back are refused here.</p>`}
outdated

Principle 1: this long HOST_CAN paragraph repeats on every claimed forge. Show it once per page, shorter.

5665 ${actions(p)}
5766 </section>`;
5867 }
@@ -60,5 +69,6 @@ function forge(p: PinnedView, f: PinnedFacts): Html {
6069 export function pinnedListPage(forges: PinnedView[], f: PinnedFacts): Html {
6170 return html`<div class="page-head"><h1>Pinned forges</h1></div>
6271 <p><a href="/deploy-to">Deploy a pinned forge</a></p>
72 ${forges.some((p) => p.claimedAt !== "") ? html`<p class="muted small">${HOST_CAN}</p>` : null}
6373 ${forges.length === 0 ? html`<p role="status">No pinned forge yet. Deploy one to a cloud account that allows writes.</p>` : forges.map((p) => forge(p, f))}`;
6474 }
src/web/pages/search.ts +8 −1
@@ -1009,7 +1009,7 @@ const DESTRUCTIVE: {
10091009 },
10101010 },
10111011 {
1012 pattern: /^\/pinned\/([a-z][a-z0-9-]*)\/(update|rollback|check)$/,
1012 pattern: /^\/pinned\/([a-z][a-z0-9-]*)\/(update|rollback|check|claim)$/,
10131013 describe: (m) => {
10141014 const name = m[1]!;
10151015 if (m[2] === "update")
@@ -1027,6 +1027,13 @@ const DESTRUCTIVE: {
10271027 detail: "The forge is replaced with the version the latest change replaced. The change is recorded with your name.",
10281028 phrase: "",
10291029 };
1030 if (m[2] === "claim")
1031 return {
1032 verb: "Hand over",
1033 title: `Hand ${name} to its buyer?`,
1034 detail: "From now on this forge refuses Update and Roll back for it: its updates are the buyer's to take. This cannot be undone here.",
1035 phrase: "",
1036 };
10301037 return {
10311038 verb: "Check",
10321039 title: `Check ${name}?`,
src/web/pinned.ts +2
@@ -5,6 +5,7 @@
55 */
66
77 import type { CloudAccount } from "../core/cloud_account.ts";
8 import { HOST_CAN } from "../core/pinned.ts";
89 import { LABEL } from "../cloud/providers.ts";
910 import { TARGETS } from "../cloud/targets.ts";
1011 import { html, type Html } from "./html.ts";
@@ -47,6 +48,7 @@ export function deployPage(accounts: CloudAccount[], v: DeployForm): Html {
4748 A pinned forge runs one version you choose, on a server in your own cloud account. It has no crew and
4849 never updates itself: it changes only when you press Update, and Rollback is one action back.
4950 </p>
51 <p class="muted small">${HOST_CAN}</p>
outdated

Principle 1: the same host paragraph again on the deploy form, plus a second explanatory sentence. Cut it to one sentence.

5052 ${usable.length === 0
5153 ? html`<p class="small" role="status">No cloud account can write yet. Add a ${NAMES} account and allow writes on
5254 <a href="/settings/cloud">Cloud accounts</a>, then come back to this page: what the link carried is kept.</p>`
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 = 53;
32 const SKIPPED = 54;
3333
3434 let dataDir: string;
3535 let app: App;
test/pinned-claim.test.ts added +201
@@ -0,0 +1,201 @@
1 /**
2 * After the claim the selling forge refuses Update and Rollback, and says plainly what the host can
3 * still do (#16204).
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 { claimPinned, deployPinned, pinnedForges, net, rollbackPinned, updatePinned } from "../src/actions/pinned.ts";
12 import { HOST_CAN, getPinned } from "../src/core/pinned.ts";
13 import { createToken } from "../src/core/tokens.ts";
14 import { createUser, getUserByName } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { Session } from "../src/tui/session.ts";
17 import { pinnedScreen } from "../src/tui/screens/pinned.ts";
18 import type { Ctx, Screen } from "../src/tui/app/app.ts";
19 import { quietCtx } from "./helpers/tui-text.ts";
20 import { createToken as mkToken } from "../src/core/tokens.ts";
21 import { quietLogs } from "./helpers/globals.ts";
22
23 quietLogs();
24 const V = "a".repeat(40);
25 const V2 = "b".repeat(40);
26 let dir = "";
27 let app: App;
28 let servers: Servers;
29 let tok = "";
30
31 beforeAll(async () => {
32 dir = await mkdtemp(join(tmpdir(), "forge-pinned-claim-"));
33 app = createApp({ dataDir: dir, port: 0 });
34 servers = await serve(app);
35 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
36 if (!made.ok) throw new Error(made.error);
37 tok = createToken(app.db, getUserByName(app.db, "alice")!.id, "admin", "admin").token;
38 cloudNet.fetch = async () => new Response(JSON.stringify({ account: { email: "[email protected]", status: "active" } }), { status: 200 });
39 const alice = getUserByName(app.db, "alice");
40 await addAccount(app, alice, "digitalocean", "main", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5");
41 allowWrite(app, alice, "digitalocean", "main", true);
42 net.fetch = async (url, init) => {
43 if (new URL(url).pathname === "/v2/volumes") return new Response(JSON.stringify({ volume: { id: "vol-1" } }), { status: 201 });
44 if (init?.method === "DELETE") return new Response(null, { status: 204 });
45 return new Response(JSON.stringify({ droplet: { id: 7 } }), { status: 202 });
46 };
47 }, 30_000);
48 afterAll(async () => {
49 await servers.stop();
50 await rm(dir, { recursive: true, force: true });
51 });
52
53 test("a claimed forge refuses update and rollback, once, and says what the host can still do", async () => {
54 const alice = getUserByName(app.db, "alice");
55 const d = await deployPinned(app, alice, { name: "acme", target: "digitalocean", account: "main", app: "alice/shop", source: "https://forge.example.org/trevato/forge", version: V });
56 expect(d.ok).toBe(true);
57 expect((await updatePinned(app, alice, "acme", { version: V2 })).ok).toBe(true);
58
59 const page = async () => (await fetch(servers.url + "/pinned", { headers: { authorization: `Bearer ${tok}` } })).text();
60 const before = await page();
61 expect(before).toContain("Update");
62 expect(before).not.toContain("snapshot its disk");
63
64 expect(claimPinned(app, undefined, "acme").ok).toBe(false);
65 expect(claimPinned(app, alice, "acme").ok).toBe(true);
66 expect(getPinned(app.db, "acme")!.claimedAt).not.toBe("");
67 const again = claimPinned(app, alice, "acme");
68 expect(again.ok).toBe(false);
69
70 const u = await updatePinned(app, alice, "acme", { version: V });
71 const r = await rollbackPinned(app, alice, "acme");
72 expect(u.ok || r.ok).toBe(false);
73 expect(u.ok ? "" : u.error).toContain("handed to its buyer");
74 expect(r.ok ? "" : r.error).toContain("handed to its buyer");
75 expect(getPinned(app.db, "acme")!.version).toBe(V2);
76
77 const after = await page();
78 expect(after).toContain("snapshot its disk");
79 expect(after).not.toContain("no access");
80 expect(after.split("snapshot its disk").length).toBe(2);
81 expect(after).not.toContain(">Roll back<");
82 expect(HOST_CAN).toContain("own cloud account");
83 });
84
85 test("the deploy page says it and points to the buyer's own account", async () => {
86 const t = await (await fetch(servers.url + "/deploy-to", { headers: { authorization: `Bearer ${tok}` } })).text();
87 expect(t).toContain("boot it into rescue");
88 expect(t).toContain("own cloud account");
89 expect(t.split("boot it into rescue").length).toBe(2);
90 });
91
92 const mkForge = (name: string) =>
93 deployPinned(app, getUserByName(app.db, "alice"), { name, target: "digitalocean", account: "main", app: "alice/shop", source: "https://forge.example.org/trevato/forge", version: V });
94
95 test("web: Hand to buyer confirms first, posts same-origin, is admin only and shows the result", async () => {
96 expect((await mkForge("web1")).ok).toBe(true);
97 await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
98 const bob = mkToken(app.db, getUserByName(app.db, "bob")!.id, "admin", "admin").token;
99 const hdr = (t: string, origin = servers.url) => ({ authorization: `Bearer ${t}`, origin, "content-type": "application/x-www-form-urlencoded" });
100 const post = (t: string, origin?: string) => fetch(servers.url + "/pinned/web1/claim", { method: "POST", redirect: "manual", headers: hdr(t, origin), body: "" });
101
102 const list = await (await fetch(servers.url + "/pinned", { headers: { authorization: `Bearer ${tok}` } })).text();
103 expect(list).toContain("/pinned/web1/claim");
104 const conf = await (await fetch(servers.url + "/-/confirm?to=/pinned/web1/claim", { headers: { authorization: `Bearer ${tok}` } })).text();
105 expect(conf).toContain("Hand web1 to its buyer?");
106 expect(conf).toContain('action="/pinned/web1/claim"');
107
108 expect((await post(bob)).status).toBeGreaterThanOrEqual(403);
109 expect((await post(tok, "https://evil.example")).status).toBe(403);
110 expect(getPinned(app.db, "web1")!.claimedAt).toBe("");
111 expect((await fetch(servers.url + "/pinned", { headers: { authorization: `Bearer ${bob}` } })).status).toBeGreaterThanOrEqual(403);
112
113 expect((await post(tok)).status).toBe(303);
114 expect(getPinned(app.db, "web1")!.claimedAt).not.toBe("");
115 const again = await post(tok);
116 expect(again.status).toBe(303);
117 expect(getPinned(app.db, "web1")!.claimedAt).not.toBe("");
118 });
119
120 test("HTTP API: claim is admin-scope only, once, and 404s an unknown forge", async () => {
121 expect((await mkForge("api1")).ok).toBe(true);
122 const bob = mkToken(app.db, getUserByName(app.db, "bob")!.id, "admin", "admin").token;
123 const post = (name: string, t?: string) =>
124 fetch(`${servers.url}/api/v1/admin/pinned/${name}/claim`, { method: "POST", headers: { "content-type": "application/json", ...(t ? { authorization: `Bearer ${t}` } : {}) }, body: "{}" });
125 expect((await post("api1")).status).toBeGreaterThanOrEqual(401);
126 expect((await post("api1", bob)).status).toBe(403);
127 expect(getPinned(app.db, "api1")!.claimedAt).toBe("");
128 const ok = await post("api1", tok);
129 expect(ok.status).toBe(200);
130 expect(getPinned(app.db, "api1")!.claimedAt).not.toBe("");
131 expect((await post("api1", tok)).status).toBe(422);
132 expect((await post("nope", tok)).status).toBe(404);
133 });
134
135 test("MCP: the claim verb hands a forge over, and a read-only token cannot", async () => {
136 expect((await mkForge("mcp1")).ok).toBe(true);
137 const call = async (t: string, args: Record<string, unknown>) => {
138 const res = await fetch(`${servers.url}/mcp`, {
139 method: "POST",
140 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${t}` },
141 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "pinned_forge", arguments: args } }),
142 });
143 return ((await res.json()) as any).result.content[0].text as string;
144 };
145 const ro = mkToken(app.db, getUserByName(app.db, "alice")!.id, "ro", "ro").token;
146 await call(ro, { verb: "claim", name: "mcp1" });
147 expect(getPinned(app.db, "mcp1")!.claimedAt).toBe("");
148 const said = await call(tok, { verb: "claim", name: "mcp1" });
149 expect(said).toContain("claim mcp1");
150 expect(getPinned(app.db, "mcp1")!.claimedAt).not.toBe("");
151 expect(await call(tok, { verb: "claim", name: "mcp1" })).toContain("handed");
152 });
153
154 test("terminal: h asks first, hands over only on Hand over, and the view follows a claim made elsewhere", async () => {
155 expect((await mkForge("tui1")).ok).toBe(true);
156 expect((await mkForge("tui2")).ok).toBe(true);
157 const alice = getUserByName(app.db, "alice")!;
158 const mk = (u: typeof alice) => new Session(app, { sshUsername: "t", remoteAddress: "127.0.0.1", user: u });
159 const pushed: Screen[] = [];
160 let invalidated = 0;
161 let wake: () => void = () => {};
162 const ctx: Ctx = { ...quietCtx(), push: (s: Screen) => void pushed.push(s), invalidate: () => { invalidated++; wake(); } };
163 const key = (s: Screen, k: string) => s.key?.({ type: "key", key: k, ctrl: false, alt: false, shift: false });
164 const abort = new AbortController();
165 const screen = pinnedScreen(mk(alice), ctx);
166 await screen.load!(abort.signal);
167 // The cursor starts on the first forge in the list; find it by claiming whichever it is.
168 const listed = pinnedForges(app, alice);
169 const first = listed.ok ? listed.value.find((p) => p.claimedAt === "")! : undefined;
170 expect(first).toBeDefined();
171 // Move the cursor onto it.
172 for (let i = 0; i < 10; i++) {
173 const row = listed.ok ? listed.value[i] : undefined;
174 if (row?.name === first!.name) break;
175 key(screen, "j");
176 }
177 expect(key(screen, "h")).toBe(true);
178 expect(pushed.length).toBe(1);
179 expect(getPinned(app.db, first!.name)!.claimedAt).toBe("");
180 const dialog = pushed[0]!;
181 // Escape dismisses: nothing claimed.
182 key(dialog, "esc");
183 expect(getPinned(app.db, first!.name)!.claimedAt).toBe("");
184 // Enter on the first action hands it over.
185 expect(key(screen, "h")).toBe(true);
186 key(pushed[1]!, "enter");
187 expect(getPinned(app.db, first!.name)!.claimedAt).not.toBe("");
188
189 // A claim at another door reaches the live view.
190 const other = pinnedForges(app, alice);
191 const next = other.ok ? other.value.find((p) => p.claimedAt === "")! : undefined;
192 const n = invalidated;
193 const woke = new Promise<void>((r) => (wake = r));
194 claimPinned(app, alice, next!.name);
195 await woke;
196 expect(invalidated).toBeGreaterThan(n);
197
198 // A member does nothing.
199 expect(key(pinnedScreen(mk(getUserByName(app.db, "bob")!), ctx), "h")).toBeFalsy();
200 abort.abort();
201 });
test/private-by-default.test.ts +1
@@ -62,6 +62,7 @@ const DOORS: Readonly<Record<string, Door>> = {
6262 "POST /:owner/:name/pulls/new": { noRepository: "a pull" },
6363 "POST /admin/agent-start": { noRepository: "the setting that opens the start call" },
6464 "POST /api/v1/admin/app-templates": { noRepository: "marks a repository a template; its copies are walked as a template" },
65 "POST /api/v1/admin/pinned/:name/claim": { noRepository: "marks a pinned forge handed to its buyer" },
6566 "POST /api/v1/apps": { walked: API },
6667 "POST /api/v1/forges": { walked: SPAWN },
6768 "POST /api/v1/migrate": { proven: "test/migrate-trail.test.ts", says: "a migration that asks for no visibility is private" },

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs