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

A deployed forge needs no hostname and no DNS work: the forge names it and writes the record #16337

Merged opened this

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

Merged

sold/dns-by-the-forge → main 0 commits

  • Merged. sold/dns-by-the-forge was merged into main as 3d0261a.

Review

Sign in to review this change.
19 files changed +948 −41
docs/features/deploy-to-hetzner.md +1 −1
@@ -10,7 +10,7 @@ A pinned forge can run in your own Hetzner Cloud project the way it runs on Digi
1010 2. **Attach it.** Settings → Cloud accounts (`/settings/cloud`), provider Hetzner Cloud, then **allow writes** on the account. The token is sealed; it is opened for one call at a time.
1111 3. **Deploy.** Any door takes the account as `hetzner/<name>` and the name the forge is served on: the `/deploy-to` list ("Hetzner Cloud / main") and its Hostname field, the terminal's Pinned forges screen (`src/tui/screens/pinned.ts`: `d`, then `acme forge.acme.com hetzner/main alice/shop https://… v1.0.0`), the HTTP and MCP `target` `hetzner` with `host`.
1212 4. **Keep the claim link.** The answer shows it once: it is the only way to become the new forge's first admin, it works once and for 7 days, and this forge keeps only its hash. Hand it to the person the forge is for.
13 5. **Create the DNS record** the answer names, `<host> A <address>`, DNS only. The server then gets its own certificate and the forge answers at `https://<host>/`; Check says what it is still waiting for.
13 5. **DNS.** With a Cloudflare account that allows writes and a domain for deployed forges (`pinned-forge.md`, "Pay and go"), the forge writes the record itself and there is nothing to create; otherwise create the record the answer names, `<host> A <address>`, DNS only. The server then gets its own certificate and the forge answers at `https://<host>/`; Check says what it is still waiting for.
1414
1515 ## What it makes
1616
docs/features/pinned-forge.md +9 −3
@@ -23,8 +23,8 @@ A forge is served at `https://<host>/` and nowhere else. `host` is a full lowerc
2323 - **The certificate is the machine's own.** The forge has no ACME client. Caddy is one of the machine's packages, from Ubuntu's repository, running as its own service under its own user (never inside the forge's unit), with a config that is the name, `reverse_proxy 127.0.0.1:<PORT or 3000>` and where certificates are kept (`proxyConfig` in `src/cloud/machine.ts`). Caddy gets a certificate for that name from Let's Encrypt, renews it, redirects port 80 to 443 and answers no other name. The config is written to `/etc/caddy/Caddyfile` before the package is installed (cloud-init writes files first, and dpkg keeps a config file that is already there), so Caddy never serves its welcome page.
2424 - **The certificate lives on the data volume**, in `<mount>/caddy`, owned by Caddy's user and skipped by the forge's ownership walk. An Update, Roll back or new claim link starts a machine that finds it there and asks Let's Encrypt for nothing; otherwise six replacements in a week would meet its limit of five certificates for one name. Caddy waits for the volume's mount (a `RequiresMountsFor` drop-in).
2525 - **The forge listens on loopback.** The machine's environment sets `FORGE_BIND=127.0.0.1`, `FORGE_URL=https://<host>`, `FORGE_HOST=<host>` and `FORGE_TRUSTED_PROXIES=127.0.0.1/32` (`servedEnv`); a deploy's config may not name them. So until the certificate exists nothing of the forge can be reached, and plain HTTP only ever gets the proxy's redirect and its ACME challenge. `FORGE_BIND` governs the web listener alone, and the SSH listener binds every interface, so the machine's environment also sets `FORGE_SSH_PORT=0`: a pinned forge has no SSH listener, and git and every door go over HTTPS.
26 - **You create one DNS record.** `<host> A <address>`, DNS only (not proxied). The deploy answer names it when the cloud has already assigned the address; otherwise Check reads the address and names it. Every view carries it as `dns`. Nothing here creates the record for you.
27 - **The address changes when the machine is replaced.** Update, Roll back and a new claim link each start a new machine on the same volume, and a new machine has a new address: Check says "waiting for DNS" with the new record until you change it.
26 - **One DNS record, written for you or by you.** `<host> A <address>`, DNS only (not proxied). With a Cloudflare account that allows writes whose token can edit the zone holding the name, the forge writes it itself (see "Pay and go" below) and the deploy answer and Check say so; otherwise the deploy answer names it when the cloud has already assigned the address, and Check reads the address and names it. Every view carries it as `dns`, and `dnsWrittenBy` says which account wrote it, empty when it is yours to make.
27 - **The address changes when the machine is replaced.** Update, Roll back and a new claim link each start a new machine on the same volume, and a new machine has a new address: the forge updates the record it wrote (the same record, never a second one); a record you made by hand is yours to change, and Check says "waiting for DNS" with the new record until you do.
2828
2929 ## The claim (#16217)
3030
@@ -65,6 +65,12 @@ A deploy is made at a place from the Places catalog (`GET /api/v1/places`): `pro
6565
6666 The row records its place (`datacenter` and `size`, in `pinned_size`); the volume and the machine are made in that datacenter, and every replace (Update, Roll back, a new claim link) orders the row's own place, never today's default, because the volume lives there. The ceiling prices that place. A forge deployed before places were kept has none recorded and is read as the place the drivers once hard-coded (DigitalOcean `nyc3` `s-1vcpu-2gb`, Hetzner `nbg1`).
6767
68 ## Pay and go: no DNS work for the buyer (#16205)
69
70 An admin names the **domain for deployed forges** (`forges.example.com`) on Pinned forges (`/pinned`; the terminal's `b`; `PATCH /api/v1/admin/settings` with `{"pinnedDomain": "forges.example.com"}`, `null` to clear; the MCP tool's `domain` verb). It is a forge setting (`settings/pinned_domain.ts`, `pinned.base_domain`, every change kept with who and when). With one set, a deploy needs no hostname: the forge is served on `<name>.<domain>`; a full hostname may still be given (the terminal's `-` takes the default).
71
72 With a **Cloudflare** cloud account attached and writes allowed, the forge then writes the record itself: after the machine has an address (the deploy, and every Update, Roll back and new claim link), and again on Check, it upserts `<host> A <address>` in the zone that holds the name, through the first such account whose token can edit that zone: found by name and updated, or made, so a replaced machine's new address changes the record and never adds one; DNS only (not proxied, so the machine gets its own certificate), TTL 60. The calls go to `api.cloudflare.com` only (`upsertARecord`, `src/cloud/providers.ts`), the token in the Authorization header alone, each call audited as `pinned:dns` like the other cloud calls; the record's id and zone are kept (`pinned_dns`) with the account that wrote it. A zone the token cannot see or edit, a CNAME already at the name, or any refusal leaves the record for a person to make, and the deploy answer and Check say that instead (`dnsWrittenBy` is empty). The token needs DNS edit on the zone; the cloud account's check cannot tell that, so the first write is the proof.
73
6874 ## After the claim: what the host can still do (#16204)
6975
7076 Nobody marks a forge claimed by hand: the deployed forge says so. Check, and every Update, Roll back and request for a new claim link, asks it first; when one hears `claimed` (The claim, above), the selling forge records it once (`pinned_forge.claimed_at`, event `pinned.claimed`). From then it refuses `update`, `rollback` and a new claim link for that forge, each with the same sentence (`CLAIMED_REFUSAL`): updates are the buyer's to take, and no machine of theirs is replaced from here. A forge that cannot be asked is never recorded as claimed, and is not taken as unclaimed either: once its current machine has answered about its claim (`pinned_forge.reached`), silence from it (a broken DNS record, a forge that is down) refuses Update, Roll back and a new claim link, with a sentence saying the forge could not be reached to confirm nobody claimed it and to run Check until it answers. A forge whose current machine has never answered (still booting, DNS not pointed yet, a first boot that failed) may still be replaced, or it could never be recovered. The question starts with a read of the machine at its cloud: when the cloud refuses that read the change is refused with the cloud's answer, before anything is recorded; a machine that is gone (404) has nobody to ask and is replaced. `/pinned` (once, when any forge is claimed) and `/deploy-to` say what the host still can while the machine is in the host's cloud account (`HOST_CAN` in `src/core/pinned.ts`): open its console, boot it into rescue, snapshot its disk, read its boot data. It never says "no access". The path that gives the host none is the buyer's own cloud account: deploy there (the account picker on `/deploy-to`; choosing it at purchase is #16203).
@@ -103,7 +109,7 @@ Each id is recorded the moment it exists. A first deploy that fails before a dro
103109 ## Not done
104110
105111 - No canary result on a real account yet: the script is written, the run needs an owner's token (#8746, see Canary).
106 - The DNS record is made by hand, and again after each Update, Roll back or new claim link, because a replaced machine has a new address. A reserved address, or writing the record through an attached Cloudflare account, would end that; neither is written.
112 - Without a Cloudflare account that can edit the name's zone, the DNS record is made by hand, and again after each Update, Roll back or new claim link, because a replaced machine has a new address. A reserved address would end that; it is not written. Nor are wildcard records, per-app subdomains or a DNS provider other than Cloudflare.
107113 - The boot config (the hardened unit, ufw, the sandbox profile, Caddy from Ubuntu 24.04's repository and its certificate) has not run on a real machine: it was written with no network. The first real deploy is the check, with the list above and the canary below.
108114 - A forge that answered and then stays unreachable for good (its machine broken, unclaimed) cannot be updated, rolled back or reissued from here: the forge will not guess that nobody claimed it. Nothing overrides that yet; the way out is to make it answer, or to deploy another.
109115 - A forge claimed on a machine that never answered this forge (the buyer used the link before the seller's DNS view or any Check or change reached it, and it is unreachable now) is not known to be claimed, and may still be replaced. Its data is on the volume and its admin stays; a new seed is ignored.
src/actions/pinned.ts +89 −9
@@ -33,15 +33,16 @@ import { orderable, provision, read, replace } from "../cloud/machine.ts";
3333 import { chooseDefault, meets, type Place } from "../cloud/places.ts";
3434 import { MAX_ID, keptPlaces, pinOf } from "../cloud/places_read.ts";
3535 import { keptRate } from "../cloud/rates.ts";
36 import type { Fetch } from "../cloud/providers.ts";
36 import { upsertARecord, type Fetch } from "../cloud/providers.ts";
3737 import { target as targetOf } from "../cloud/targets.ts";
38 import { getCloudAccount, secretNameOf } from "../core/cloud_account.ts";
38 import { getCloudAccount, listCloudAccounts, secretNameOf } from "../core/cloud_account.ts";
3939 import { FIRST_ADMIN_SEED_TTL_MS, firstAdminLink, newFirstAdminCode, type SeedState } from "../core/first_admin.ts";
4040 import {
4141 APP, CLAIMED_REFUSAL, NAME, changesOf, checkConfig, dnsRecordOf, getPinned, insertPinned, listPinned, placeIdOf, previousOf,
42 dropPinned, markClaimed, markReached, recordChange, setClaim, setHost, setRemote, urlOf, validHost, validSource, validVersion, unconfirmedRefusal, type Change, type Pinned,
42 dnsOf, dropPinned, keepDns, markClaimed, markReached, recordChange, setClaim, setHost, setRemote, urlOf, validHost, validSource, validVersion, unconfirmedRefusal, type Change, type Pinned,
4343 } from "../core/pinned.ts";
4444 import { resolveSecrets } from "../core/secret_store.ts";
45 import { DOMAIN_WORDS, getBaseDomain, parseBaseDomain, setBaseDomain } from "../settings/pinned_domain.ts";
4546 import type { User } from "../core/users.ts";
4647 import { err, ok, type Result } from "../kernel/result.ts";
4748 import { boundedSignal } from "../kernel/fetch_timeout.ts";
@@ -64,6 +65,11 @@ export interface PinnedView extends Omit<Pinned, "claimHash"> {
6465 * The DNS record its name needs, `<host> A <address>`, once the address is read; empty before.
6566 */
6667 readonly dns: string;
68 /**
69 * The cloud account whose token wrote that record (`cloudflare/main`), when this forge did; empty
70 * while the record is for a person to make.
71 */
72 readonly dnsWrittenBy: string;
6773 readonly crew: false;
6874 readonly autoRelease: false;
6975 readonly changes: Change[];
@@ -72,7 +78,9 @@ export interface PinnedView extends Omit<Pinned, "claimHash"> {
7278 const view = (app: App, p: Pinned): PinnedView => {
7379 // The hash stays in the row: it is what the deployed forge answers a claim question to.
7480 const { claimHash: _kept, ...shown } = p;
75 return { ...shown, url: urlOf(p), dns: dnsRecordOf(p), crew: false, autoRelease: false, changes: changesOf(app.db, p.id) };
81 const kept = dnsOf(app.db, p.id);
82 const written = kept !== undefined && kept.host === p.host && kept.address === p.address;
83 return { ...shown, url: urlOf(p), dns: dnsRecordOf(p), dnsWrittenBy: written ? `cloudflare/${kept.account}` : "", crew: false, autoRelease: false, changes: changesOf(app.db, p.id) };
7684 };
7785
7886 /** A claim just issued: the link is in this value and nowhere else, so it is shown once. */
@@ -119,11 +127,19 @@ export function deployPlaces(app: App, providers: readonly string[]): Place[] {
119127 }
120128
121129 const HOST_WORDS = "A hostname is a full DNS name you control, such as forge.example.com: lowercase letters, digits, dashes and dots.";
130 const HOST_NEEDED = "Name the host the forge is served on, such as forge.example.com; or set a domain for deployed forges on Pinned forges, and each is served on <name>.<domain> with no hostname given.";
122131 const NAMELESS = "This forge was deployed before forges had names: issue a claim for it with a hostname first.";
123132
124 /** The name asked for, or why it cannot be this forge's: one forge a name. */
133 /**
134 * The name asked for, or why it cannot be this forge's: one forge a name. With none asked for it is
135 * `<name>.<domain>` when the forge has a domain for deployed forges (`settings/pinned_domain.ts`),
136 * so a deploy needs no hostname and its buyer no DNS.
137 */
125138 function hostFor(app: App, name: string, raw: string): Result<string, string> {
126 const host = raw.trim().toLowerCase();
139 const asked = raw.trim().toLowerCase();
140 const base = getBaseDomain(app.db);
141 const host = asked !== "" ? asked : base !== "" ? `${name}.${base}` : "";
142 if (host === "") return err(HOST_NEEDED);
127143 if (!validHost(host)) return err(HOST_WORDS);
128144 if (listPinned(app.db).some((q) => q.host === host && q.name !== name)) return err("Another pinned forge is served on that name.");
129145 return ok(host);
@@ -143,6 +159,62 @@ export function pinnedForges(app: App, actor: User | undefined): Result<PinnedVi
143159 return who.ok ? ok(listPinned(app.db).map((p) => view(app, p))) : who;
144160 }
145161
162 /** The domain deployed forges are served on, for an admin: empty when none is set. */
163 export function readBaseDomain(app: App, actor: User | undefined): Result<string, "not_found"> {
164 const who = admin(actor);
165 return who.ok ? ok(getBaseDomain(app.db)) : err("not_found");
166 }
167
168 /** Set (or with null or empty clear) the domain deployed forges are served on. */
169 export function changeBaseDomain(app: App, actor: User | undefined, raw: unknown): Result<string, "not_found" | "invalid_pinned_domain"> {
170 const who = admin(actor);
171 if (!who.ok) return err("not_found");
172 const domain = parseBaseDomain(raw);
173 if (!domain.ok) return domain;
174 setBaseDomain(app.db, domain.value, who.value.id);
175 return ok(domain.value);
176 }
177
178 export { DOMAIN_WORDS };
179
180 /** The cloud accounts that may write a forge's DNS record: Cloudflare, with writes allowed. */
181 const dnsWriters = (app: App) => listCloudAccounts(app.db).filter((a) => a.provider === "cloudflare" && a.writeAllowed);
182
183 /**
184 * Once the machine has an address, write the forge's record `<host> A <address>` (DNS only) through
185 * the first attached Cloudflare account with writes allowed whose token can edit the zone holding
186 * the name: found by name and updated, or made, so a replaced machine's new address changes the
187 * record and never adds one. Done at a deploy, after every replace, and by Check, so an address
188 * that arrived late is written too. Nothing is written, and nothing asked of Cloudflare, with no
189 * such account, no name or no address; a token that cannot edit the zone leaves the record for a
190 * person to make, which the words of the deploy and of Check then say. Each call is audited like
191 * the other cloud calls (`pinned:dns`), and the token is opened for it alone.
192 */
193 async function writeDns(app: App, who: User, name: string): Promise<void> {
194 const p = getPinned(app.db, name);
195 if (!p || p.host === "" || p.address === "") return;
196 const kept = dnsOf(app.db, p.id);
197 if (kept !== undefined && kept.host === p.host && kept.address === p.address) return;
198 for (const a of dnsWriters(app)) {
199 const secret = secretNameOf(a.provider, a.name);
200 const token = resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], { actor: who.id, run: "pinned:dns" })[secret];
201 if (token === undefined) continue;
202 const f = gatedFetch(app.db, { provider: a.provider, account: a.name }, "pinned:dns", net.fetch);
203 const made = await upsertARecord(f, token, p.host, p.address);
204 if (made.done === "none") continue;
205 keepDns(app.db, p.id, { account: a.name, zone: made.zone, record: made.record, host: p.host, address: p.address });
206 app.bus.append({ kind: "pinned.dns", actorId: who.id, payload: { name, host: p.host, address: p.address, account: `cloudflare/${a.name}`, done: made.done } });
207 return;
208 }
209 }
210
211 /** After a replace the address is unknown: with a Cloudflare account to write it, read it and write the record. */
212 async function followWithDns(app: App, who: User, name: string): Promise<void> {
213 if (dnsWriters(app).length === 0) return;
214 await readAddress(app, who, name);
215 await writeDns(app, who, name);
216 }
217
146218 /** Open the account's token and run `go` with a gated fetch; the token never leaves this scope. */
147219 async function withCloud<T>(app: App, who: User, p: Pinned, purpose: string, go: (f: Fetch, token: string) => Promise<T>, writes = true): Promise<Result<T, string>> {
148220 const account = getCloudAccount(app.db, p.target, p.account);
@@ -258,6 +330,7 @@ export async function deployPinned(
258330 // One read for the address, so the answer can name the DNS record; a cloud that has not
259331 // assigned one yet (or refuses the read) leaves it to `check`.
260332 await readAddress(app, who.value, p.name);
333 await writeDns(app, who.value, p.name);
261334 return ok(issued(app, getPinned(app.db, p.name)!, claim.code));
262335 }
263336
@@ -305,6 +378,7 @@ async function changeNow(
305378 true,
306379 );
307380 if (!done.ok) return done;
381 await followWithDns(app, who.value, name);
308382 return ok(view(app, getPinned(app.db, name)!));
309383 }
310384
@@ -358,7 +432,7 @@ async function claimNow(app: App, actor: User | undefined, name: string, input:
358432 if (!before) return err("No such pinned forge.");
359433 if (before.claimedAt !== "") return err(CLAIMED_REFUSAL);
360434 const asked = (input.host ?? "").trim().toLowerCase();
361 if (before.host === "" && asked === "") return err(NAMELESS);
435 if (before.host === "" && asked === "" && getBaseDomain(app.db) === "") return err(NAMELESS);
362436 if (before.host !== "" && asked !== "" && asked !== before.host) return err(`This forge is served on ${before.host}; its name does not change.`);
363437 const host = before.host === "" ? hostFor(app, name, asked) : ok(before.host);
364438 if (!host.ok) return host;
@@ -383,6 +457,7 @@ async function claimNow(app: App, actor: User | undefined, name: string, input:
383457 if (!done.ok) return done;
384458 app.bus.append({ kind: "pinned.claim_issued", actorId: who.value.id, payload: { name, expires: claim.expires } });
385459 await readAddress(app, who.value, name);
460 await writeDns(app, who.value, name);
386461 return ok(issued(app, getPinned(app.db, name)!, claim.code));
387462 }
388463
@@ -465,7 +540,9 @@ export type Checked = PinnedView & { readonly healthy: boolean; readonly waiting
465540 export function checkWords(v: Checked): string {
466541 if (v.waiting === "name") return `${v.name} has no name to be served on: issue a claim for it with a hostname.`;
467542 if (v.waiting === "address") return `${v.name} has no address yet; check again in a minute.`;
468 if (v.waiting === "dns") return `${v.name} is waiting for DNS: create the record ${v.dns} (DNS only, not proxied), then check again.`;
543 if (v.waiting === "dns" && v.dnsWrittenBy !== "")
544 return `${v.name} is waiting for DNS: the forge wrote the record ${v.dns} in ${v.dnsWrittenBy} (DNS only, not proxied) and it has not reached the resolver yet; check again in a minute.`;
545 if (v.waiting === "dns") return `${v.name} is waiting for DNS: create the record ${v.dns} (DNS only, not proxied) by hand, then check again; no Cloudflare account that allows writes can edit its zone.`;
469546 if (v.waiting === "answer") return `${v.name} does not answer at ${v.url} yet: its certificate is issued once the name resolves to it, which takes a few minutes.`;
470547 const claim =
471548 v.claim === "claimed" ? " It has been claimed: it is its buyer's, and Update, Roll back and a new claim link are refused from here."
@@ -480,7 +557,9 @@ export function checkWords(v: Checked): string {
480557 * beside them.
481558 */
482559 export function claimWords(v: Issued): string {
483 const dns = v.dns !== "" ? `Create the DNS record ${v.dns} (DNS only, not proxied)` : `Check reads its address; then create the DNS record ${v.host} A <that address>`;
560 if (v.dnsWrittenBy !== "")
561 return `The forge wrote the DNS record ${v.dns} in ${v.dnsWrittenBy} (DNS only, not proxied): there is nothing to create. It gets its own certificate once the name resolves, and is served only at ${v.url}. The claim link makes its first admin: it works once, until ${v.claim.expiresAt}, and is shown only now.`;
562 const dns = v.dns !== "" ? `Create the DNS record ${v.dns} (DNS only, not proxied) by hand` : `Check reads its address; then create the DNS record ${v.host} A <that address>`;
484563 return `${dns}: the forge gets its own certificate once the name resolves, and is served only at ${v.url}. The claim link makes its first admin: it works once, until ${v.claim.expiresAt}, and is shown only now.`;
485564 }
486565
@@ -499,6 +578,7 @@ export async function checkPinned(app: App, actor: User | undefined, name: strin
499578 if (p.remote === "") return err("This forge has no droplet yet; deploy or update it first.");
500579 const read = await readAddress(app, who.value, name);
501580 if (!read.ok) return read;
581 await writeDns(app, who.value, name);
502582 const now = getPinned(app.db, name)!;
503583 const reached = await hear(app, who.value, now);
504584 const healthy = reached.waiting === "";
src/cloud/providers.ts +63
@@ -4,6 +4,8 @@
44 * identity lookup — nothing creates, changes or deletes. The complete list:
55 *
66 * cloudflare GET api.cloudflare.com/client/v4/user/tokens/verify, /zones
7 * a pinned forge's A record (`upsertARecord`): GET /zones?name=, GET, POST and PATCH
8 * /zones/{id}/dns_records
79 * digitalocean GET api.digitalocean.com/v2/account, /projects, /droplets,
810 * /volumes, /reserved_ips
911 * hetzner GET api.hetzner.cloud/v1/servers, /volumes
@@ -112,6 +114,67 @@ async function json(f: Fetch, url: string, init: RequestInit = {}): Promise<any>
112114 }
113115
114116 const bearer = (t: string) => ({ authorization: `Bearer ${t}` });
117
118 const CLOUDFLARE = "https://api.cloudflare.com/client/v4";
119 const CF_ID = /^[0-9a-f]{32}$/;
120
121 /** What writing a forge's DNS record came to: made, changed, already right, or not written and why. */
122 export type DnsWrite =
123 | { readonly done: "created" | "updated" | "unchanged"; readonly zone: string; readonly record: string }
124 | { readonly done: "none"; readonly why: string };
125
126 /** One Cloudflare call: the status and the body (an empty object when it is not JSON). */
127 async function cloudflare(f: Fetch, token: string, method: string, path: string, body?: unknown): Promise<{ status: number; body: any }> {
128 const res = await f(`${CLOUDFLARE}${path}`, {
129 method,
130 headers: { ...bearer(token), "content-type": "application/json" },
131 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
132 signal: AbortSignal.timeout(10_000),
133 });
134 return { status: res.status, body: await res.json().catch(() => ({})) };
135 }
136
137 /**
138 * Make `host` an A record for `address` in the Cloudflare zone that holds it: DNS only (never
139 * proxied, so the forge's own certificate is issued), a one-minute TTL. The record is found by
140 * name and updated, or made when there is none, so asking again never makes a second. The zone is
141 * the longest suffix of `host` the token can see; a token that cannot edit it, a CNAME already at
142 * the name, or any refusal is "none" with the reason in words, and nothing is thrown: the caller
143 * falls back to naming the record for a person to make.
144 */
145 export async function upsertARecord(f: Fetch, token: string, host: string, address: string): Promise<DnsWrite> {
146 const none = (why: string): DnsWrite => ({ done: "none", why });
147 try {
148 const labels = host.split(".");
149 let zone: { id: string; name: string } | undefined;
150 for (let i = 0; i < labels.length - 1 && zone === undefined; i++) {
151 const name = labels.slice(i).join(".");
152 const z = await cloudflare(f, token, "GET", `/zones?name=${encodeURIComponent(name)}&per_page=1`);
153 if (z.status === 401 || z.status === 403) return none("the token cannot read zones");
154 const hit = z.status === 200 ? (z.body?.result ?? [])[0] : undefined;
155 if (hit?.name === name && CF_ID.test(String(hit.id))) zone = { id: String(hit.id), name };
156 }
157 if (zone === undefined) return none(`no zone this token can see holds ${host}`);
158 const found = await cloudflare(f, token, "GET", `/zones/${zone.id}/dns_records?name=${encodeURIComponent(host)}&per_page=20`);
159 if (found.status !== 200) return none(`Cloudflare answered ${found.status} listing the records of ${zone.name}`);
160 const rows: any[] = found.body?.result ?? [];
161 if (rows.some((r) => r?.type === "CNAME")) return none(`${host} has a CNAME record, which cannot sit beside an address record`);
162 const mine = rows.find((r) => r?.type === "A");
163 const want = { content: address, ttl: 60, proxied: false };
164 if (mine !== undefined && CF_ID.test(String(mine.id))) {
165 if (mine.content === address && mine.proxied === false && mine.ttl === 60) return { done: "unchanged", zone: zone.id, record: String(mine.id) };
166 const r = await cloudflare(f, token, "PATCH", `/zones/${zone.id}/dns_records/${mine.id}`, want);
167 if (r.status === 401 || r.status === 403) return none(`the token cannot edit DNS records in ${zone.name}`);
168 return r.status === 200 ? { done: "updated", zone: zone.id, record: String(mine.id) } : none(`Cloudflare answered ${r.status} updating ${host}`);
169 }
170 const r = await cloudflare(f, token, "POST", `/zones/${zone.id}/dns_records`, { type: "A", name: host, ...want, comment: "a pinned forge, written by the forge that deployed it" });
171 if (r.status === 401 || r.status === 403) return none(`the token cannot edit DNS records in ${zone.name}`);
172 const made = String(r.body?.result?.id ?? "");
173 return (r.status === 200 || r.status === 201) && CF_ID.test(made) ? { done: "created", zone: zone.id, record: made } : none(`Cloudflare answered ${r.status} making ${host}`);
174 } catch (e) {
175 return none(`Cloudflare could not be reached: ${e instanceof Error ? e.message.slice(0, 100) : "failed"}`);
176 }
177 }
115178 const money = (n: number) => `$${n.toFixed(2)}`;
116179 const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? "" : "s"}`;
117180
src/contract/openapi/routes/getApiV1AdminSettings.ts +1 −1
@@ -6,7 +6,7 @@ export const route: Route = {
66 summary:
77 "Read the forge's signup mode, account quotas and own source repository",
88 detail:
9 "Read the forge's signup mode, account quotas and own source repository (a person admin's token, any scope); answers { quotas, signup, forgeRepo, forgeRepoInForce, signupChanges, changes }",
9 "Read the forge's signup mode, account quotas and own source repository (a person admin's token, any scope); answers { quotas, signup, forgeRepo, forgeRepoInForce, pinnedDomain, signupChanges, changes }",
1010 auth: true,
1111 role: "admin",
1212 refusals: { not_found: "the token is not a person who administers the forge" },
src/contract/openapi/routes/patchApiV1AdminSettings.ts +3 −2
@@ -6,13 +6,14 @@ export const route: Route = {
66 summary:
77 "Change the signup mode",
88 detail:
9 "Change the signup mode (open, invite or closed), the account quotas, or the forge's own source repository (forgeRepo: owner/name, null to clear; its app is then shown as the forge itself), one per call (a person admin's token, admin scope); answers { signup }, { quotas } or { forgeRepo }; a quota is a positive whole number, or null for no limit",
9 "Change the signup mode (open, invite or closed), the account quotas, or the forge's own source repository (forgeRepo: owner/name, null to clear; its app is then shown as the forge itself), or the domain deployed forges are served on (pinnedDomain: such as forges.example.com, null to clear; a pinned forge deployed with no hostname is served on <name>.<domain>), one per call (a person admin's token, admin scope); answers { signup }, { quotas }, { forgeRepo } or { pinnedDomain }; a quota is a positive whole number, or null for no limit",
1010 auth: true,
1111 role: "admin",
12 body: { signup: "string", quotas: "object", forgeRepo: "string" },
12 body: { signup: "string", quotas: "object", forgeRepo: "string", pinnedDomain: "string" },
1313 refusals: {
1414 invalid_body: "none of signup, quotas or forgeRepo was sent, or more than one was",
1515 invalid_forge_repo: "forgeRepo is not owner/name or null",
16 invalid_pinned_domain: "pinnedDomain is not a DNS name such as forges.example.com, or null",
1617 invalid_signup: "signup is not open, invite or closed",
1718 no_such_quota: "a quota key is unknown",
1819 invalid_quota: "a quota is not a positive whole number or null",
src/core/migration-pins/20261124191005-pinned-dns.pin added +1
@@ -0,0 +1,1 @@
1 bdd6deefdede8b57bd941af2657a7af2b16015fa147a97d21056b9c535de3622
src/core/migrations/20261124191005-pinned-dns.ts added +15
@@ -0,0 +1,15 @@
1 // The DNS record a forge wrote for a pinned forge (#16205): which Cloudflare account and zone, the
2 // record's id, and the name and address it was written for, so a replace (a new address) updates
3 // that record rather than making a second, and retiring the forge can remove it. One row a
4 // forge; none when its record is made by hand. Additive.
5 export default `
6 CREATE TABLE pinned_dns (
7 pinned_id TEXT PRIMARY KEY,
8 account TEXT NOT NULL,
9 zone TEXT NOT NULL,
10 record TEXT NOT NULL,
11 host TEXT NOT NULL,
12 address TEXT NOT NULL,
13 at TEXT NOT NULL
14 );
15 `;
src/core/pinned.ts +22
@@ -268,9 +268,31 @@ export const unconfirmedRefusal = (p: Pick<Pinned, "name" | "host" | "address">)
268268 /** The sentence a refused Update, Rollback or new claim link gives after the claim. */
269269 export const CLAIMED_REFUSAL = "This forge was handed to its buyer: its updates are theirs to take, and this forge no longer changes it.";
270270
271 /** The DNS record a forge wrote for a forge: where, and for which name and address. */
272 export interface DnsKept {
273 readonly account: string;
274 readonly zone: string;
275 readonly record: string;
276 readonly host: string;
277 readonly address: string;
278 }
279
280 export function dnsOf(db: Database, pinnedId: string): DnsKept | undefined {
281 return db.query<DnsKept, [string]>("SELECT account, zone, record, host, address FROM pinned_dns WHERE pinned_id = ?1").get(pinnedId) ?? undefined;
282 }
283
284 /** Keep the record this forge wrote; a forge has one row, so a new address replaces it. */
285 export function keepDns(db: Database, pinnedId: string, d: DnsKept): void {
286 db.query(
287 `INSERT INTO pinned_dns (pinned_id, account, zone, record, host, address, at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
288 ON CONFLICT (pinned_id) DO UPDATE SET account = excluded.account, zone = excluded.zone, record = excluded.record, host = excluded.host, address = excluded.address, at = excluded.at`,
289 ).run(pinnedId, d.account, d.zone, d.record, d.host, d.address, new Date().toISOString());
290 }
291
271292 /** The row of a deploy that never reached a droplet, so its name can be tried again; its recorded change stays as history. */
272293 export function dropPinned(db: Database, name: string): void {
273294 db.query("DELETE FROM pinned_size WHERE pinned_id IN (SELECT id FROM pinned_forge WHERE name = ?1 AND remote = '' AND state = 'failed')").run(name);
295 db.query("DELETE FROM pinned_dns WHERE pinned_id IN (SELECT id FROM pinned_forge WHERE name = ?1 AND remote = '' AND state = 'failed')").run(name);
274296 db.query("DELETE FROM pinned_forge WHERE name = ?1 AND remote = '' AND state = 'failed'").run(name);
275297 }
276298
src/http/api/admin.ts +13 −6
@@ -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, claimPinned, deployPinned, pinnedForges, rollbackPinned, updatePinned } from "../../actions/pinned.ts";
26 import { DOMAIN_WORDS, changeBaseDomain, checkPinned, claimPinned, deployPinned, pinnedForges, readBaseDomain, 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";
@@ -406,15 +406,16 @@ export function adminRoutes(router: Router<Handler>): void {
406406 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
407407 const denied = accountAdmin(ctx, "ro");
408408 if (denied) return denied;
409 const { read, signup, source, billing } = timePhase(ctx.request, "settings", () => ({
409 const { read, signup, source, billing, domain } = timePhase(ctx.request, "settings", () => ({
410410 billing: readBillingLinks(ctx.app, ctx.auth.user),
411 domain: readBaseDomain(ctx.app, ctx.auth.user),
411412 read: readQuotas(ctx.app, ctx.auth.user),
412413 signup: readSignup(ctx.app, ctx.auth.user),
413414 source: readForgeSource(ctx.app, ctx.auth.user),
414415 }));
415416 return timePhase(ctx.request, "render", () =>
416 read.ok && signup.ok && source.ok && billing.ok
417 ? json({ billingLinks: billing.value, ...read.value, ...signup.value, ...source.value, signupChanges: signup.value.changes, changes: read.value.changes })
417 read.ok && signup.ok && source.ok && billing.ok && domain.ok
418 ? json({ billingLinks: billing.value, pinnedDomain: domain.value === "" ? null : domain.value, ...read.value, ...signup.value, ...source.value, signupChanges: signup.value.changes, changes: read.value.changes })
418419 : notFound());
419420 });
420421
@@ -422,8 +423,14 @@ export function adminRoutes(router: Router<Handler>): void {
422423 const denied = accountAdmin(ctx, "admin");
423424 if (denied) return denied;
424425 const input = await body(ctx.request);
425 const sent = [input.signup, input.quotas, input.forgeRepo, input.billingLinks].filter((v) => v !== undefined).length;
426 if (sent > 1) return apiError("invalid_body", 422, "send one of signup, quotas, forgeRepo or billingLinks");
426 const sent = [input.signup, input.quotas, input.forgeRepo, input.billingLinks, input.pinnedDomain].filter((v) => v !== undefined).length;
427 if (sent > 1) return apiError("invalid_body", 422, "send one of signup, quotas, forgeRepo, billingLinks or pinnedDomain");
428 if (input.pinnedDomain !== undefined) {
429 const set = changeBaseDomain(ctx.app, ctx.auth.user, input.pinnedDomain);
430 if (set.ok) return json({ pinnedDomain: set.value === "" ? null : set.value });
431 if (set.error === "not_found") return notFound();
432 return apiError(set.error, 422, DOMAIN_WORDS);
433 }
427434 if (input.billingLinks !== undefined) {
428435 const set = changeBillingLinks(ctx.app, ctx.auth.user, input.billingLinks);
429436 if (set.ok) return json({ billingLinks: set.value });
src/http/mcp/tools/pinned_forge.ts +14 −5
@@ -1,4 +1,4 @@
1 import { checkPinned, checkWords, claimPinned, claimWords, deployPinned, pinnedForges, rollbackPinned, updatePinned } from "../../../actions/pinned.ts";
1 import { DOMAIN_WORDS, changeBaseDomain, checkPinned, checkWords, claimPinned, claimWords, deployPinned, pinnedForges, readBaseDomain, rollbackPinned, updatePinned } from "../../../actions/pinned.ts";
22 import { TARGETS } from "../../../cloud/targets.ts";
33 import { scopeAllows } from "../../../core/tokens.ts";
44 import { good, bad, type Tool, str } from "../shared.ts";
@@ -6,12 +6,13 @@ 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?, target?, account?, app?, source?, version?, place?, 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` on `host`, its own name over HTTPS, at `place` (provider:datacenter:size, from Places; the catalog's default for the small plan on that provider when left out; recorded on the forge, and every replace orders there), and answers once with `claim.link`, the only way to become its first admin, and `dns`, the record to create; `claim` issues a fresh link for a forge nobody has claimed (the machine is replaced, the old link stops); `update` is the only way its `version` or `config` change; `rollback` goes back one; `check` reads the machine's address back and says what the forge waits for (`waiting`: address, dns, answer) or that it answers and what became of its claim (`url`, `healthy`, `claim`). A forge admin with an admin-scope token",
9 doc: "`{ verb, name?, host?, domain?, target?, account?, app?, source?, version?, place?, config? }`: a forge on the owner's cloud. `deploy`: `app` from `source` at `version` on a writable `account`, at `place` (default: the small plan's), on `host` (default `<name>.<domain>`; Cloudflare writes the record); answers once with `claim.link` and `dns`. `claim`: a fresh link while unclaimed. `update`: change `version` or `config`. `rollback`: back one. `domain`: read or set the domain. `check`: `waiting` or `url`, `healthy`, `claim`. `list`: all, with changes. A forge admin with an admin-scope token",
1010 description: "Pinned forges on your cloud: list, deploy, claim, update, rollback, check (admin).",
1111 inputSchema: {
1212 type: "object",
1313 properties: {
14 verb: { type: "string", enum: ["list", "deploy", "claim", "update", "rollback", "check"] },
14 verb: { type: "string", enum: ["list", "deploy", "claim", "update", "rollback", "check", "domain"] },
15 domain: { type: "string", maxLength: 253, description: "Domain for deployed forges; empty clears." },
1516 name: { type: "string", maxLength: 40 },
1617 host: { type: "string", maxLength: 253, description: "The DNS name it is served on over HTTPS." },
1718 target: { type: "string", enum: TARGETS.map((t) => t.id) },
@@ -19,7 +20,7 @@ export const tool: Tool = {
1920 app: { type: "string", maxLength: 140 },
2021 source: { type: "string", maxLength: 300 },
2122 version: { type: "string", maxLength: 40, description: "Commit id or tag." },
22 place: { type: "string", maxLength: 200, description: "provider:datacenter:size, an orderable place of the account's provider; omit for the default." },
23 place: { type: "string", maxLength: 200, description: "provider:datacenter:size; omit for the default." },
2324 config: { type: "object", description: "NAME: value; no secrets." },
2425 },
2526 required: ["verb"],
@@ -36,8 +37,16 @@ export const tool: Tool = {
3637 const seen = pinnedForges(ctx.app, user);
3738 return seen.ok ? good({ items: seen.value, targets: TARGETS }) : bad("not_found", "no such tool here");
3839 }
40 if (verb === "domain" && args["domain"] === undefined) {
41 const now = readBaseDomain(ctx.app, user);
42 return now.ok ? good({ says: now.value === "" ? "No domain for deployed forges is set: each deploy names its host." : `Deployed forges are served on <name>.${now.value}.`, domain: now.value }) : bad("not_found", "no such tool here");
43 }
3944 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin"))
4045 return bad("forbidden", "changing a pinned forge needs an admin-scope token");
46 if (verb === "domain") {
47 const set = changeBaseDomain(ctx.app, user, str(args["domain"]));
48 return set.ok ? good({ says: set.value === "" ? "Domain for deployed forges cleared." : `Deployed forges are now served on <name>.${set.value}.`, domain: set.value }) : bad(set.error, DOMAIN_WORDS);
49 }
4150 const name = str(args["name"]);
4251 // A claim is shown once: the answer holds the link and the sentences that say what to do with
4352 // it.
@@ -65,7 +74,7 @@ export const tool: Tool = {
6574 : verb === "rollback"
6675 ? await rollbackPinned(ctx.app, user, name)
6776 : undefined;
68 if (done === undefined) return bad("bad_verb", "verb is list, deploy, claim, update, rollback or check");
77 if (done === undefined) return bad("bad_verb", "verb is list, deploy, claim, update, rollback, check or domain");
6978 if (!done.ok) return bad("refused", done.error);
7079 return good({ says: `${verb} ${name}: now ${done.value.version}, ${done.value.state}${done.value.url ? ` at ${done.value.url}` : ""}.`, forge: done.value });
7180 },
src/http/pinned_routes.ts +16 −3
@@ -7,10 +7,11 @@
77 * never through a redirect or a flash: it is shown once and stored nowhere.
88 */
99
10 import { checkPinned, checkWords, claimPinned, deployPinned, deployPlaces, pinnedForges, rollbackPinned, updatePinned, type Issued } from "../actions/pinned.ts";
10 import { DOMAIN_WORDS, changeBaseDomain, checkPinned, checkWords, claimPinned, deployPinned, deployPlaces, pinnedForges, 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";
14 import { getBaseDomain } from "../settings/pinned_domain.ts";
1415 import { getUsersByIds } from "../core/users.ts";
1516 import { notFoundPage, signInFirst } from "../web/chrome.ts";
1617 import { field, readForm } from "../web/form.ts";
@@ -45,7 +46,7 @@ function render(ctx: Ctx, v: DeployForm, flash?: { tone: "danger"; message: stri
4546 {
4647 ctx,
4748 title: "Deploy to…",
48 body: deployPage(listCloudAccounts(ctx.app.db), v, deployPlaces(ctx.app, TARGETS.map((t) => t.id))),
49 body: deployPage(listCloudAccounts(ctx.app.db), v, deployPlaces(ctx.app, TARGETS.map((t) => t.id)), getBaseDomain(ctx.app.db)),
4950 ...(flash ? { flash } : {}),
5051 },
5152 flash ? 422 : 200,
@@ -85,7 +86,7 @@ function listPage(ctx: Ctx): Response {
8586 const at = lastCheckOf(ctx.app.db, p.name);
8687 if (at) checks.set(p.name, at);
8788 }
88 return page({ ctx, title: "Pinned forges", body: pinnedListPage(forges.value, { names, checks }) });
89 return page({ ctx, title: "Pinned forges", body: pinnedListPage(forges.value, { names, checks, domain: getBaseDomain(ctx.app.db) }) });
8990 }
9091
9192 /**
@@ -116,8 +117,20 @@ async function pinnedAct(ctx: Ctx): Promise<Response> {
116117 return flashTo(ctx, "/pinned", { tone: "success", message });
117118 }
118119
120 /** Save the domain deployed forges are served on: the same change the API, MCP and terminal make. */
121 async function domainSubmit(ctx: Ctx): Promise<Response> {
122 if (!ctx.auth.user) return signInFirst(ctx);
123 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
124 const form = await readForm(ctx, "admin");
125 if (form instanceof Response) return form;
126 const set = changeBaseDomain(ctx.app, ctx.auth.user, field(form, "domain"));
127 if (!set.ok && set.error === "not_found") return notFoundPage(ctx);
128 return flashTo(ctx, "/pinned", set.ok ? { message: set.value === "" ? "Domain for deployed forges cleared." : `Deployed forges are served on <name>.${set.value}.` } : { tone: "danger", message: `${DOMAIN_WORDS}. Nothing was saved.` });
129 }
130
119131 export function pinnedRoutes(router: Router<Handler>): void {
120132 router.add("GET", "/pinned", listPage);
133 router.add("POST", "/pinned/domain", domainSubmit);
121134 router.add("POST", "/pinned/:name/:act", pinnedAct);
122135 router.add("GET", "/deploy-to", deployToPage);
123136 router.add("POST", "/deploy-to", deployToSubmit);
src/settings/pinned_domain.ts added +38
@@ -0,0 +1,38 @@
1 /**
2 * The base domain deployed forges are served on (#16205), such as `forges.example.com`: a forge
3 * deployed with no hostname is served on `<name>.<domain>`, so the person it is deployed for
4 * configures no DNS. Stored in `forge_setting` under `pinned.base_domain` by an admin
5 * (`PATCH /api/v1/admin/settings` with `{"pinnedDomain": "forges.example.com"}`, `null` to clear),
6 * every change kept with who and when; none until one is set. A full hostname may still be given.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import { validHost } from "../core/pinned.ts";
11 import { err, ok, type Result } from "../kernel/result.ts";
12 import { writeSetting } from "./limits.ts";
13
14 export const BASE_DOMAIN_KEY = "pinned.base_domain";
15
16 export const DOMAIN_WORDS =
17 "the domain for deployed forges is a DNS name such as forges.example.com (lowercase letters, digits, dashes and dots), or empty for none";
18
19 /** A domain from untrusted input: a valid DNS name, or the empty string (null clears). */
20 export function parseBaseDomain(raw: unknown): Result<string, "invalid_pinned_domain"> {
21 if (raw === null || raw === "") return ok("");
22 if (typeof raw !== "string") return err("invalid_pinned_domain");
23 const name = raw.trim().toLowerCase();
24 return name === "" ? ok("") : validHost(name) ? ok(name) : err("invalid_pinned_domain");
25 }
26
27 /** The stored domain, or the empty string when none is set. */
28 export function getBaseDomain(db: Database): string {
29 const row = db.query<{ value: string }, [string]>("SELECT value FROM forge_setting WHERE key = ?1").get(BASE_DOMAIN_KEY);
30 return row === null || !validHost(row.value) ? "" : row.value;
31 }
32
33 /** Keep the domain (empty clears it) with who changed it; the same value again keeps nothing. */
34 export function setBaseDomain(db: Database, value: string, actorId: string): void {
35 const from = getBaseDomain(db);
36 if (from === value) return;
37 writeSetting(db, BASE_DOMAIN_KEY, value === "" ? null : value, from === "" ? "unset" : from, value === "" ? "unset" : value, actorId);
38 }
src/tui/screens/pinned.ts +24 −5
@@ -3,13 +3,14 @@
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
55 * previous version, `c` reads the address back and probes it, `n` issues a
6 * new claim link (shown once, as a deploy's is), each through
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), each through
78 * `actions/pinned.ts`, so the checks, the record of who and when and the events
89 * the web screens follow are the API's.
910 * Anyone else sees nothing and does nothing.
1011 */
1112
12 import { checkPinned, checkWords, claimPinned, claimWords, deployPinned, pinnedForges, rollbackPinned, updatePinned, type Issued } from "../../actions/pinned.ts";
13 import { DOMAIN_WORDS, changeBaseDomain, checkPinned, checkWords, claimPinned, claimWords, deployPinned, pinnedForges, readBaseDomain, rollbackPinned, updatePinned, type Issued } from "../../actions/pinned.ts";
1314 import type { Ctx, Screen } from "../app/app.ts";
1415 import { binding } from "../app/keys.ts";
1516 import { style } from "../term/style.ts";
@@ -79,10 +80,11 @@ export function pinnedScreen(f: Session, ctx: Ctx): Screen {
7980 const deploy = (parent: Screen): Screen =>
8081 promptScreen(ctx, parent, {
8182 title: "Deploy a pinned forge",
82 label: "name hostname provider/account owner/app https-source version [place]",
83 label: "name hostname (- for <name>.<domain>) provider/account owner/app https-source version [place]",
8384 placeholder: "acme forge.acme.com digitalocean/main alice/shop https://host/alice/shop v1.0.0 digitalocean:sfo2:s-1vcpu-2gb",
8485 onSubmit: (raw) => {
85 const [name = "", host = "", cloud = "", app = "", source = "", version = "", place = "", ...rest] = raw.trim().split(/\s+/);
86 const [name = "", hostWord = "", cloud = "", app = "", source = "", version = "", place = "", ...rest] = raw.trim().split(/\s+/);
87 const host = hostWord === "-" ? "" : hostWord;
8688 const [target = "", account = "", ...more] = cloud.split("/");
8789 if (rest.length > 0 || more.length > 0 || version === "" || account === "") return "Write: name hostname provider/account owner/app source version [place]; a place is provider:datacenter:size, and left out it is the default.";
8890 say(`Deploying ${name}…`);
@@ -92,7 +94,7 @@ export function pinnedScreen(f: Session, ctx: Ctx): Screen {
9294
9395 const screen: Screen = {
9496 title: "Pinned forges",
95 keys: [binding(["j", "k"], "move cursor"), binding(["d"], "deploy"), binding(["u"], "update"), binding(["r"], "roll back"), binding(["c"], "check"), binding(["n"], "new claim link")],
97 keys: [binding(["j", "k"], "move cursor"), binding(["d"], "deploy"), binding(["u"], "update"), binding(["r"], "roll back"), binding(["c"], "check"), binding(["n"], "new claim link"), binding(["b"], "domain for forges")],
9698 async load(signal) {
9799 live(f, signal, { kinds: ["pinned.deployed", "pinned.update", "pinned.rollback", "pinned.check", "pinned.claim_issued", "pinned.claimed"] }, () => ctx.invalidate());
98100 },
@@ -118,6 +120,23 @@ export function pinnedScreen(f: Session, ctx: Ctx): Screen {
118120 ctx.push(deploy(screen));
119121 return true;
120122 }
123 if (e.key === "b") {
124 const now = readBaseDomain(f.app, f.user);
125 ctx.push(
126 promptScreen(ctx, screen, {
127 title: "Domain for deployed forges",
128 label: "such as forges.example.com; a forge deployed with no hostname is served on <name>.<domain>; empty for none",
129 value: now.ok ? now.value : "",
130 onSubmit: (v) => {
131 const set = changeBaseDomain(f.app, f.user, v.trim());
132 if (!set.ok) return set.error === "not_found" ? "You cannot change the domain." : `${DOMAIN_WORDS}.`;
133 say(set.value === "" ? "Domain for deployed forges cleared." : `Deployed forges are served on <name>.${set.value}.`);
134 return undefined;
135 },
136 }),
137 );
138 return true;
139 }
121140 const p = forges()[state.index];
122141 if (p === undefined) return false;
123142 if (e.key === "r") {
src/web/pages/pinned.ts +8 −2
@@ -7,7 +7,7 @@
77 import type { PinnedView } from "../../actions/pinned.ts";
88 import { HOST_CAN } from "../../core/pinned.ts";
99 import { html, type Html } from "../html.ts";
10 import { badge, btn, time, type Tone } from "../ui.ts";
10 import { badge, btn, field, time, type Tone } from "../ui.ts";
1111
1212 const TONE: Record<string, Tone> = { running: "success", failed: "danger" };
1313
@@ -15,6 +15,8 @@ const TONE: Record<string, Tone> = { running: "success", failed: "danger" };
1515 export interface PinnedFacts {
1616 readonly names: Map<string, string>;
1717 readonly checks: Map<string, string>;
18 /** The domain deployed forges are served on; empty when none is set. */
19 readonly domain: string;
1820 }
1921
2022 const fact = (label: string, value: Html): Html => html`<div class="status-row"><dt>${label}</dt><dd>${value}</dd></div>`;
@@ -60,7 +62,7 @@ function forge(p: PinnedView, f: PinnedFacts): Html {
6062 ${fact("App", html`<span class="mono">${p.app}</span>`)}
6163 ${fact("Version", html`<span class="mono" title="${p.version}">${p.version.slice(0, 12)}</span>`)}
6264 ${fact("Address", p.url === "" ? none("no name yet") : html`<a class="mono" href="${p.url}" rel="noopener noreferrer">${p.url}</a>`)}
63 ${fact("DNS record", p.dns === "" ? none("Check reads the machine's address") : html`<span class="mono">${p.dns}</span>`)}
65 ${fact("DNS record", p.dns === "" ? none("Check reads the machine's address") : html`<span class="mono">${p.dns}</span> ${p.dnsWrittenBy === "" ? none("create it by hand") : none(`written by the forge in ${p.dnsWrittenBy}`)}`)}
6466 ${fact("Claim link", p.claimedAt !== "" ? html`used` : p.claimExpires === "" ? none("none issued") : html`shown once; works until ${time(p.claimExpires)} unless used. Check asks the forge whether it was.`)}
6567 ${fact("Health", badge(p.state, { tone: TONE[p.state] ?? "default" }))}
6668 ${fact("Last check", checked ? time(checked) : none("never checked"))}
@@ -76,6 +78,10 @@ function forge(p: PinnedView, f: PinnedFacts): Html {
7678 export function pinnedListPage(forges: PinnedView[], f: PinnedFacts): Html {
7779 return html`<div class="page-head"><h1>Pinned forges</h1></div>
7880 <p><a href="/deploy-to">Deploy a pinned forge</a></p>
81 <form method="post" action="/pinned/domain" class="stack">
82 ${field({ name: "domain", label: "Domain for deployed forges", value: f.domain, placeholder: "forges.example.com", mono: true, maxlength: 253, spellcheck: false, hint: "A forge deployed with no hostname is served on <name>.<domain>, so its buyer configures no DNS. With a Cloudflare account that allows writes and a token that can edit the zone, the forge writes the record itself, after every replace too. Empty for none." })}
83 ${btn("Save", { variant: "secondary", label: "Save the domain for deployed forges" })}
84 </form>
7985 ${forges.some((p) => p.claimedAt !== "") ? html`<p class="muted small">${HOST_CAN}</p>` : null}
8086 ${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))}`;
8187 }
src/web/pinned.ts +2 −2
@@ -65,7 +65,7 @@ const DEPLOYABLE = new Set<string>(TARGETS.filter((t) => t.status === "first").m
6565 */
6666 const NAMES = TARGETS.filter((t) => DEPLOYABLE.has(t.id)).map((t) => t.label).join(" or ");
6767
68 export function deployPage(accounts: CloudAccount[], v: DeployForm, places: Place[]): Html {
68 export function deployPage(accounts: CloudAccount[], v: DeployForm, places: Place[], domain = ""): Html {
6969 const usable = accounts.filter((a) => DEPLOYABLE.has(a.provider) && a.writeAllowed);
7070 const providers = new Set<string>(usable.map((a) => a.provider));
7171 const offered = places.filter((p) => providers.has(p.provider));
@@ -101,7 +101,7 @@ export function deployPage(accounts: CloudAccount[], v: DeployForm, places: Plac
101101 ${field({ name: "source", label: "Source", value: v.source, placeholder: "https://…", mono: true, required: true, maxlength: 400, spellcheck: false, hint: "An https git address." })}
102102 ${field({ name: "version", label: "Version", value: v.version, mono: true, required: true, maxlength: 40, spellcheck: false, hint: "A full 40-character commit id or a tag like v1.2.3 — never a branch." })}
103103 ${field({ name: "name", label: "Name", value: v.name, mono: true, required: true, maxlength: 40, spellcheck: false, hint: "Lowercase letters, digits and dashes." })}
104 ${field({ name: "host", label: "Hostname", value: v.host, placeholder: "forge.example.com", mono: true, required: true, maxlength: 253, spellcheck: false, hint: "The name it is served on, over HTTPS only. You create its DNS record once the deploy says the address." })}
104 ${field({ name: "host", label: "Hostname", value: v.host, placeholder: domain === "" ? "forge.example.com" : `<name>.${domain}`, mono: true, required: domain === "", maxlength: 253, spellcheck: false, hint: domain === "" ? "The name it is served on, over HTTPS only. You create its DNS record once the deploy says the address, unless a Cloudflare account that allows writes can edit its zone and the forge writes it." : `Left empty it is the name above on ${domain}, and the forge writes its DNS record when a Cloudflare account that allows writes can edit the zone: nothing to configure. A full hostname may be given instead.` })}
105105 ${btn("Deploy", { variant: "primary", icon: "plus" })}
106106 </form>`,
107107 )}`;
test/pinned-claim.test.ts +3 −2
@@ -755,7 +755,7 @@ describe("claimed is what the deployed forge says, never what the seller says (#
755755 // The pages, drawn from the rows every door reads (#16220's assertions, kept).
756756 const page = (): string => {
757757 const rows = pinnedForges(app, alice);
758 return rows.ok ? String(pinnedListPage(rows.value, { names: new Map(), checks: new Map() })) : "";
758 return rows.ok ? String(pinnedListPage(rows.value, { names: new Map(), checks: new Map(), domain: "" })) : "";
759759 };
760760 const offered = (name: string): string[] =>
761761 ["update", "rollback", "claim", "check"].filter((act) => page().includes(`value="/pinned/${name}/${act}"`));
@@ -1090,7 +1090,8 @@ describe("the name and the boot config", () => {
10901090 version: V1,
10911091 });
10921092 expect(r).toMatchObject({ ok: false });
1093 expect(r.ok ? "" : r.error).toContain("A hostname is a full DNS name");
1093 // No hostname and no domain set is its own sentence; any other bad name is the old one.
1094 expect(r.ok ? "" : r.error).toContain(host === "" ? "Name the host the forge is served on" : "A hostname is a full DNS name");
10941095 }
10951096 expect(asked).toEqual([]);
10961097 expect(getPinned(app.db, "acme")).toBeUndefined();
test/pinned-dns.test.ts added +390
@@ -0,0 +1,390 @@
1 /**
2 * Pay and go (#16205): a forge deployed with no hostname is served on `<name>.<domain>`, and a
3 * Cloudflare account that allows writes and whose token can edit the zone has the forge write the
4 * record itself, after the machine has an address and after every replace. A recorded fetch stands
5 * in for DigitalOcean and Cloudflare.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import {
13 addAccount,
14 allowWrite,
15 net as cloudNet,
16 } from "../src/actions/cloud.ts";
17 import {
18 changeBaseDomain,
19 checkPinned,
20 checkWords,
21 claimPinned,
22 claimWords,
23 deployPinned,
24 net,
25 readBaseDomain,
26 updatePinned,
27 } from "../src/actions/pinned.ts";
28 import { setCeiling } from "../src/actions/cloud_ceiling.ts";
29 import { dnsOf, getPinned } from "../src/core/pinned.ts";
30 import { createUser, getUserByName } from "../src/core/users.ts";
31 import { getBaseDomain } from "../src/settings/pinned_domain.ts";
32 import { quietLogs } from "./helpers/globals.ts";
33 import { seedPlaces } from "./helpers/places-fixture.ts";
34
35 quietLogs();
36
37 const V1 = "a".repeat(40);
38 const V2 = "b".repeat(40);
39 const SOURCE = "https://forge.example.org/trevato/forge";
40 const CF_TOKEN = "cf_Zq4TxLm7Kp2Vb8nWcR5Yd3Fg6Hj9Lm2";
41 const ZONE = "a".repeat(32);
42
43 interface Entry {
44 id: string;
45 type: string;
46 name: string;
47 content: string;
48 proxied: boolean;
49 ttl: number;
50 }
51
52 describe("a deploy needs no DNS work from its buyer", () => {
53 let dataDir = "";
54 let app: App;
55 const cf: { method: string; path: string; auth: string | null; body: any }[] =
56 [];
57 const records: Entry[] = [];
58 /** Whether the Cloudflare token may edit the zone; reads always work. */
59 let mayEdit = true;
60 let seq = 0;
61 let droplets = 1000;
62
63 const admin = () => getUserByName(app.db, "alice")!;
64 const input = (name: string, over: Record<string, unknown> = {}) => ({
65 name,
66 host: "",
67 target: "digitalocean",
68 account: "main",
69 app: "alice/shop",
70 source: SOURCE,
71 version: V1,
72 config: {},
73 ...over,
74 });
75 const error = (r: unknown) => String((r as { error: unknown }).error);
76 const named = (host: string) => records.filter((r) => r.name === host);
77 const writes = () => cf.filter((c) => c.method !== "GET");
78
79 beforeAll(async () => {
80 dataDir = await mkdtemp(join(tmpdir(), "forge-dns-"));
81 app = createApp({ dataDir, port: 0 });
82 await seedPlaces(app.db);
83 const made = await createUser(app.db, {
84 origin: "seed",
85 trusted: true,
86 username: "alice",
87 email: "[email protected]",
88 password: "a-good-passphrase",
89 adminIfFirst: true,
90 });
91 if (!made.ok) throw new Error(made.error);
92 cloudNet.fetch = async () =>
93 new Response(
94 JSON.stringify({
95 account: { email: "[email protected]", status: "active" },
96 result: [],
97 servers: [],
98 }),
99 { status: 200 },
100 );
101 for (const [provider, token] of [
102 ["digitalocean", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5"],
103 ["cloudflare", CF_TOKEN],
104 ] as const) {
105 const added = await addAccount(app, admin(), provider, "main", token);
106 if (!added.ok) throw new Error(String(added.error));
107 }
108 allowWrite(app, admin(), "digitalocean", "main", true);
109 allowWrite(app, admin(), "cloudflare", "main", true);
110 expect(setCeiling(app, admin(), "digitalocean", "main", 500).ok).toBe(true);
111 net.resolve = async () => [];
112 net.fetch = async (url, init) => {
113 const u = new URL(url);
114 const method = init?.method ?? "GET";
115 const json = (o: unknown, status = 200) =>
116 new Response(JSON.stringify(o), { status });
117 if (u.host === "api.cloudflare.com") {
118 const body = init?.body ? JSON.parse(String(init.body)) : undefined;
119 cf.push({
120 method,
121 path: u.pathname + u.search,
122 auth: new Headers(init?.headers).get("authorization"),
123 body,
124 });
125 if (u.pathname === "/client/v4/zones")
126 return json({
127 success: true,
128 result:
129 u.searchParams.get("name") === "forges.test"
130 ? [{ id: ZONE, name: "forges.test" }]
131 : [],
132 });
133 const rows = u.pathname.match(
134 /^\/client\/v4\/zones\/([0-9a-f]{32})\/dns_records(?:\/([0-9a-f]{32}))?$/,
135 );
136 if (!rows || rows[1] !== ZONE) return json({ success: false }, 404);
137 if (method === "GET")
138 return json({
139 success: true,
140 result: named(u.searchParams.get("name") ?? ""),
141 });
142 if (!mayEdit)
143 return json({ success: false, errors: [{ code: 10000 }] }, 403);
144 if (method === "POST") {
145 const r: Entry = {
146 id: (++seq).toString(16).padStart(32, "0"),
147 type: body.type,
148 name: body.name,
149 content: body.content,
150 proxied: body.proxied,
151 ttl: body.ttl,
152 };
153 records.push(r);
154 return json({ success: true, result: r });
155 }
156 const r = records.find((x) => x.id === rows[2]);
157 if (!r || method !== "PATCH") return json({ success: false }, 404);
158 Object.assign(r, body);
159 return json({ success: true, result: r });
160 }
161 if (u.pathname.endsWith("/volumes"))
162 return json({ volume: { id: "vol-1" } }, 201);
163 if (u.pathname.endsWith("/account/keys"))
164 return json({ ssh_key: { id: 4242 } }, 201);
165 if (method === "DELETE") return new Response(null, { status: 204 });
166 if (method === "POST") return json({ droplet: { id: ++droplets } }, 202);
167 // Each machine has an address of its own, from its id.
168 const id = Number(u.pathname.split("/").at(-1));
169 return json({
170 droplet: {
171 id,
172 status: "active",
173 networks: {
174 v4: [{ type: "public", ip_address: `203.0.113.${id % 250}` }],
175 },
176 },
177 });
178 };
179 }, 30_000);
180
181 afterAll(async () => {
182 app.close();
183 await rm(dataDir, { recursive: true, force: true });
184 });
185
186 test("with no domain set and no hostname, a deploy is refused and says how to fix it", async () => {
187 const r = await deployPinned(app, admin(), input("nodomain"));
188 expect(error(r)).toContain("set a domain for deployed forges");
189 expect(getPinned(app.db, "nodomain")).toBeUndefined();
190 expect(cf).toEqual([]);
191 });
192
193 test("the domain is a setting an admin changes, kept with who, and nobody else reads or sets it", () => {
194 expect(readBaseDomain(app, undefined)).toMatchObject({ ok: false });
195 expect(changeBaseDomain(app, undefined, "forges.test")).toMatchObject({
196 ok: false,
197 error: "not_found",
198 });
199 for (const bad of [
200 "Forges",
201 "forges.test:8080",
202 "a b.test",
203 "*.forges.test",
204 7,
205 "1.2.3.4",
206 ])
207 expect(changeBaseDomain(app, admin(), bad)).toMatchObject({
208 ok: false,
209 error: "invalid_pinned_domain",
210 });
211 expect(getBaseDomain(app.db)).toBe("");
212 expect(changeBaseDomain(app, admin(), " Forges.Test ")).toEqual({
213 ok: true,
214 value: "forges.test",
215 });
216 expect(getBaseDomain(app.db)).toBe("forges.test");
217 expect(
218 app.db
219 .query(
220 "SELECT to_value, actor_id FROM forge_setting_change WHERE key = 'pinned.base_domain'",
221 )
222 .all(),
223 ).toEqual([{ to_value: "forges.test", actor_id: admin().id }]);
224 });
225
226 test("a deploy with no hostname is served on <name>.<domain>, and the forge writes its record: DNS only, a short TTL", async () => {
227 const r = await deployPinned(app, admin(), input("acme"));
228 expect(r.ok).toBe(true);
229 const p = getPinned(app.db, "acme")!;
230 expect(p.host).toBe("acme.forges.test");
231 expect(p.address).toBe(
232 `203.0.113.${p.remote.slice(-3).replace(/^0+/, "") ? Number(p.remote) % 250 : 0}`,
233 );
234 expect(named("acme.forges.test")).toHaveLength(1);
235 expect(named("acme.forges.test")[0]).toMatchObject({
236 type: "A",
237 content: p.address,
238 proxied: false,
239 ttl: 60,
240 });
241 // The token travels in the Authorization header alone, to the fixed host, and every call is audited.
242 expect(cf.every((c) => c.auth === `Bearer ${CF_TOKEN}`)).toBe(true);
243 expect(JSON.stringify(cf.map((c) => [c.path, c.body]))).not.toContain(
244 CF_TOKEN,
245 );
246 const audited = app.db
247 .query<
248 { target: string },
249 []
250 >("SELECT target FROM cloud_audit WHERE provider = 'cloudflare' AND purpose = 'pinned:dns'")
251 .all();
252 expect(audited.length).toBe(cf.length);
253 expect(
254 audited.every((a) =>
255 a.target.startsWith("api.cloudflare.com/client/v4/"),
256 ),
257 ).toBe(true);
258 // The answer says so, and names nothing to create.
259 expect(r.ok && r.value.dnsWrittenBy).toBe("cloudflare/main");
260 expect(r.ok && claimWords(r.value)).toContain(
261 "The forge wrote the DNS record acme.forges.test A",
262 );
263 expect(r.ok && claimWords(r.value)).toContain("there is nothing to create");
264 expect(dnsOf(app.db, p.id)).toMatchObject({
265 account: "main",
266 zone: ZONE,
267 host: "acme.forges.test",
268 address: p.address,
269 });
270 });
271
272 test("a full hostname may still be given, and one outside every zone is left for a person to make", async () => {
273 cf.length = 0;
274 const r = await deployPinned(
275 app,
276 admin(),
277 input("other", { host: "other.elsewhere.test" }),
278 );
279 expect(r.ok).toBe(true);
280 expect(getPinned(app.db, "other")!.host).toBe("other.elsewhere.test");
281 // Cloudflare was asked which zone holds it, found none, and wrote nothing.
282 expect(writes()).toEqual([]);
283 expect(r.ok && r.value.dnsWrittenBy).toBe("");
284 expect(r.ok && claimWords(r.value)).toContain(
285 "Create the DNS record other.elsewhere.test A",
286 );
287 expect(r.ok && claimWords(r.value)).toContain("by hand");
288 });
289
290 test("an Update replaces the machine and the same record is updated to its new address, never duplicated", async () => {
291 const before = getPinned(app.db, "acme")!;
292 const record = named("acme.forges.test")[0]!.id;
293 cf.length = 0;
294 const r = await updatePinned(app, admin(), "acme", { version: V2 });
295 expect(r.ok).toBe(true);
296 const after = getPinned(app.db, "acme")!;
297 expect(after.address).not.toBe("");
298 expect(after.address).not.toBe(before.address);
299 expect(named("acme.forges.test")).toHaveLength(1);
300 expect(named("acme.forges.test")[0]).toMatchObject({
301 id: record,
302 content: after.address,
303 proxied: false,
304 ttl: 60,
305 });
306 expect(writes().map((c) => c.method)).toEqual(["PATCH"]);
307 expect(r.ok && r.value.dnsWrittenBy).toBe("cloudflare/main");
308 });
309
310 test("a new claim link replaces the machine too, and the record follows it", async () => {
311 cf.length = 0;
312 const r = await claimPinned(app, admin(), "acme");
313 expect(r.ok).toBe(true);
314 const p = getPinned(app.db, "acme")!;
315 expect(named("acme.forges.test")).toHaveLength(1);
316 expect(named("acme.forges.test")[0]!.content).toBe(p.address);
317 expect(writes().map((c) => c.method)).toEqual(["PATCH"]);
318 });
319
320 test("Check says the record is the forge's own, and asking again writes nothing", async () => {
321 cf.length = 0;
322 const seen = await checkPinned(app, admin(), "acme");
323 expect(seen.ok).toBe(true);
324 expect(seen.ok && checkWords(seen.value)).toContain(
325 "the forge wrote the record acme.forges.test A",
326 );
327 expect(seen.ok && checkWords(seen.value)).toContain("in cloudflare/main");
328 expect(cf).toEqual([]);
329 expect(named("acme.forges.test")).toHaveLength(1);
330 });
331
332 test("a record that exists proxied or at another address is made right, not added to", async () => {
333 records.push({
334 id: "f".repeat(32),
335 type: "A",
336 name: "pre.forges.test",
337 content: "198.51.100.1",
338 proxied: true,
339 ttl: 1,
340 });
341 cf.length = 0;
342 const r = await deployPinned(app, admin(), input("pre"));
343 expect(r.ok).toBe(true);
344 expect(named("pre.forges.test")).toHaveLength(1);
345 expect(named("pre.forges.test")[0]).toMatchObject({
346 id: "f".repeat(32),
347 content: getPinned(app.db, "pre")!.address,
348 proxied: false,
349 ttl: 60,
350 });
351 expect(writes().map((c) => c.method)).toEqual(["PATCH"]);
352 });
353
354 test("a token that cannot edit the zone falls back to naming the record, on the deploy and on Check", async () => {
355 mayEdit = false;
356 cf.length = 0;
357 const r = await deployPinned(app, admin(), input("ro"));
358 expect(r.ok).toBe(true);
359 const p = getPinned(app.db, "ro")!;
360 expect(named("ro.forges.test")).toEqual([]);
361 expect(r.ok && r.value.dnsWrittenBy).toBe("");
362 expect(r.ok && claimWords(r.value)).toContain(
363 `Create the DNS record ro.forges.test A ${p.address} (DNS only, not proxied) by hand`,
364 );
365 expect(dnsOf(app.db, p.id)).toBeUndefined();
366 const seen = await checkPinned(app, admin(), "ro");
367 expect(seen.ok && checkWords(seen.value)).toContain(
368 `waiting for DNS: create the record ro.forges.test A ${p.address} (DNS only, not proxied) by hand`,
369 );
370 // The refusal is not a failure of the deploy: the forge is running and the answer carries its claim.
371 expect(p.state).toBe("running");
372 mayEdit = true;
373 // Once the token can edit the zone, Check writes it: nothing waits on a person.
374 const later = await checkPinned(app, admin(), "ro");
375 expect(named("ro.forges.test")).toHaveLength(1);
376 expect(later.ok && checkWords(later.value)).toContain(
377 "the forge wrote the record ro.forges.test A",
378 );
379 });
380
381 test("a Cloudflare account that does not allow writes is never asked to write", async () => {
382 allowWrite(app, admin(), "cloudflare", "main", false);
383 cf.length = 0;
384 const r = await deployPinned(app, admin(), input("off"));
385 expect(r.ok).toBe(true);
386 expect(cf).toEqual([]);
387 expect(r.ok && r.value.dnsWrittenBy).toBe("");
388 expect(r.ok && claimWords(r.value)).toContain("by hand");
389 });
390 });
test/pinned-domain-doors.test.ts added +236
@@ -0,0 +1,236 @@
1 /**
2 * The domain for deployed forges (#16205), at its doors: the settings API, the MCP tool, the
3 * Pinned forges page and the Deploy to… form. Each is the same `changeBaseDomain`, admin only.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import {
11 addAccount,
12 allowWrite,
13 net as cloudNet,
14 } from "../src/actions/cloud.ts";
15 import { net } from "../src/actions/pinned.ts";
16 import { getPinned } from "../src/core/pinned.ts";
17 import { createToken } from "../src/core/tokens.ts";
18 import { createUser, getUserByName } from "../src/core/users.ts";
19 import { serve, type Servers } from "../src/http/server.ts";
20 import { getBaseDomain } from "../src/settings/pinned_domain.ts";
21 import { quietLogs } from "./helpers/globals.ts";
22 import { seedPlaces } from "./helpers/places-fixture.ts";
23
24 quietLogs();
25
26 const V = "a".repeat(40);
27 const SOURCE = "https://forge.example.org/trevato/forge";
28
29 describe("the domain for deployed forges", () => {
30 let dataDir = "";
31 let app: App;
32 let servers: Servers;
33 let adminTok = "";
34 let bobTok = "";
35 const headers = (tok: string, more: Record<string, string> = {}) => ({
36 authorization: `Bearer ${tok}`,
37 origin: servers.url,
38 ...more,
39 });
40 const patch = (body: unknown, tok: string) =>
41 fetch(`${servers.url}/api/v1/admin/settings`, {
42 method: "PATCH",
43 headers: headers(tok, { "content-type": "application/json" }),
44 body: JSON.stringify(body),
45 });
46 const mcp = async (tok: string, args: Record<string, unknown>) => {
47 const res = await fetch(`${servers.url}/mcp`, {
48 method: "POST",
49 headers: headers(tok, {
50 "content-type": "application/json",
51 accept: "application/json, text/event-stream",
52 }),
53 body: JSON.stringify({
54 jsonrpc: "2.0",
55 id: 1,
56 method: "tools/call",
57 params: { name: "pinned_forge", arguments: args },
58 }),
59 });
60 return (await res.json()) as {
61 result?: { content: { text: string }[]; isError?: boolean };
62 };
63 };
64
65 beforeAll(async () => {
66 dataDir = await mkdtemp(join(tmpdir(), "forge-domain-doors-"));
67 app = createApp({ dataDir, port: 0 });
68 await seedPlaces(app.db);
69 servers = await serve(app);
70 for (const [username, adminIfFirst] of [
71 ["alice", true],
72 ["bob", false],
73 ] as const) {
74 const made = await createUser(app.db, {
75 origin: "seed",
76 trusted: true,
77 username,
78 email: `${username}@f.test`,
79 password: "a-good-passphrase",
80 adminIfFirst,
81 });
82 if (!made.ok) throw new Error(made.error);
83 }
84 adminTok = createToken(
85 app.db,
86 getUserByName(app.db, "alice")!.id,
87 "admin",
88 "admin",
89 ).token;
90 bobTok = createToken(
91 app.db,
92 getUserByName(app.db, "bob")!.id,
93 "admin",
94 "admin",
95 ).token;
96 cloudNet.fetch = async () =>
97 new Response(
98 JSON.stringify({ account: { email: "[email protected]", status: "active" } }),
99 { status: 200 },
100 );
101 const added = await addAccount(
102 app,
103 getUserByName(app.db, "alice"),
104 "digitalocean",
105 "main",
106 "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5",
107 );
108 if (!added.ok) throw new Error(String(added.error));
109 allowWrite(
110 app,
111 getUserByName(app.db, "alice"),
112 "digitalocean",
113 "main",
114 true,
115 );
116 net.fetch = async (url, init) => {
117 if (new URL(url).pathname === "/v2/volumes")
118 return new Response(JSON.stringify({ volume: { id: "vol-1" } }), {
119 status: 201,
120 });
121 if (
122 new URL(url).pathname === "/v2/account/keys" &&
123 init?.method === "POST"
124 )
125 return new Response(JSON.stringify({ ssh_key: { id: 4242 } }), {
126 status: 201,
127 });
128 if (init?.method === "DELETE") return new Response(null, { status: 204 });
129 return new Response(JSON.stringify({ droplet: { id: 7 } }), {
130 status: 202,
131 });
132 };
133 }, 30_000);
134
135 afterAll(async () => {
136 await servers.stop();
137 app.close();
138 await rm(dataDir, { recursive: true, force: true });
139 });
140
141 test("the settings API sets, reads and clears it; a bad name and a non-admin are refused", async () => {
142 expect((await patch({ pinnedDomain: "forges.test" }, bobTok)).status).toBeGreaterThanOrEqual(
143 400,
144 );
145 expect(getBaseDomain(app.db)).toBe("");
146 const bad = await patch({ pinnedDomain: "not a name" }, adminTok);
147 expect(bad.status).toBe(422);
148 expect(await bad.json()).toMatchObject({ error: "invalid_pinned_domain" });
149 const set = await patch({ pinnedDomain: "Forges.Test" }, adminTok);
150 expect(set.status).toBe(200);
151 expect(await set.json()).toEqual({ pinnedDomain: "forges.test" });
152 const read = await fetch(`${servers.url}/api/v1/admin/settings`, {
153 headers: headers(adminTok),
154 });
155 expect(
156 ((await read.json()) as { pinnedDomain: string | null }).pinnedDomain,
157 ).toBe("forges.test");
158 expect((await patch({ pinnedDomain: null }, adminTok)).status).toBe(200);
159 expect(getBaseDomain(app.db)).toBe("");
160 });
161
162 test("the Pinned forges page saves it with a form, and says what was saved", async () => {
163 const post = (domain: string) =>
164 fetch(`${servers.url}/pinned/domain`, {
165 method: "POST",
166 redirect: "manual",
167 headers: headers(adminTok, {
168 "content-type": "application/x-www-form-urlencoded",
169 }),
170 body: new URLSearchParams({ domain }),
171 });
172 expect((await post("forges.test")).status).toBe(303);
173 expect(getBaseDomain(app.db)).toBe("forges.test");
174 const page = await (
175 await fetch(`${servers.url}/pinned`, { headers: headers(adminTok) })
176 ).text();
177 expect(page).toContain('name="domain"');
178 expect(page).toContain('value="forges.test"');
179 const refused = await fetch(`${servers.url}/pinned/domain`, {
180 method: "POST",
181 redirect: "manual",
182 headers: headers(bobTok, {
183 "content-type": "application/x-www-form-urlencoded",
184 }),
185 body: new URLSearchParams({ domain: "evil.test" }),
186 });
187 expect(refused.status).toBe(403);
188 expect(getBaseDomain(app.db)).toBe("forges.test");
189 });
190
191 test("the Deploy to… form no longer needs a hostname, and a post without one is served on <name>.<domain>", async () => {
192 const form = await (
193 await fetch(`${servers.url}/deploy-to`, { headers: headers(adminTok) })
194 ).text();
195 expect(form).toContain("&lt;name&gt;.forges.test");
196 const r = await fetch(`${servers.url}/deploy-to`, {
197 method: "POST",
198 redirect: "manual",
199 headers: headers(adminTok, {
200 "content-type": "application/x-www-form-urlencoded",
201 }),
202 body: new URLSearchParams({
203 name: "acme",
204 host: "",
205 account: "main",
206 app: "alice/shop",
207 source: SOURCE,
208 version: V,
209 }),
210 });
211 expect(r.status).toBe(200);
212 expect(getPinned(app.db, "acme")!.host).toBe("acme.forges.test");
213 });
214
215 test("the MCP tool reads and sets it with the `domain` verb, and sets it only with an admin-scope token", async () => {
216 const ro = createToken(
217 app.db,
218 getUserByName(app.db, "alice")!.id,
219 "ro",
220 "ro",
221 ).token;
222 const read = await mcp(adminTok, { verb: "domain" });
223 expect(read.result?.content[0]?.text).toContain("forges.test");
224 const refused = await mcp(ro, { verb: "domain", domain: "other.test" });
225 expect(JSON.stringify(refused)).not.toContain(
226 "Deployed forges are now served",
227 );
228 expect(getBaseDomain(app.db)).toBe("forges.test");
229 const set = await mcp(adminTok, { verb: "domain", domain: "more.test" });
230 expect(set.result?.content[0]?.text).toContain("<name>.more.test");
231 expect(getBaseDomain(app.db)).toBe("more.test");
232 const cleared = await mcp(adminTok, { verb: "domain", domain: "" });
233 expect(cleared.result?.content[0]?.text).toContain("cleared");
234 expect(getBaseDomain(app.db)).toBe("");
235 });
236 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs