Public: anyone can read this; the crew can change it.
Hetzner Cloud is a cloud account provider and a pinned-forge target #16201
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/16200-hetzner-cloud-is-a-cloud-account-provide → main 0 commits fork 3 threads · 3 unresolved
18 files
changed +681
−137
docs/features/deploy-to-hetzner.md added +30
| @@ -0,0 +1,30 @@ | ||
| 1 | --- | |
| 2 | topic: Hosting forges for others, and getting paid | |
| 3 | row: A pinned forge | |
| 4 | --- | |
| 5 | # Deploy a pinned forge to Hetzner Cloud (#16200) | |
| 6 | ||
| 7 | A pinned forge can run in your own Hetzner Cloud project the way it runs on DigitalOcean: one server, one volume as `FORGE_APP_DATA`, and a version that moves only when you press Update. | |
| 8 | ||
| 9 | 1. **Make a token.** In the Hetzner Cloud console open the project, Security → API tokens, and make a token with **Read & Write**. Hetzner scopes a token to one project and offers nothing narrower, and a read-only token can only check a forge, never make one. | |
| 10 | 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. | |
| 11 | 3. **Deploy.** Any door takes the account as `hetzner/<name>`: the `/deploy-to` list ("Hetzner Cloud / main"), the terminal's Pinned forges screen (`d`, then `acme hetzner/main alice/shop https://… v1.0.0`), the HTTP and MCP `target` `hetzner`. | |
| 12 | ||
| 13 | ## What it makes | |
| 14 | ||
| 15 | - Location **Nuremberg** (`nbg1`), an EU location: the US ones cost about three times as much for a tenth of the traffic. | |
| 16 | - The server **type is chosen from Hetzner's own lists at order time**: the cheapest cost-optimized (CX), x86 type with at least 2 GiB that Hetzner says can be ordered in Nuremberg now. No type is named in the code. | |
| 17 | - A 10 GiB volume, attached and automounted at `/mnt/HC_Volume_<id>`. Update deletes the server and makes a new one on the same volume; the data is not touched. | |
| 18 | - The address is read back from the server by Check, as on DigitalOcean. | |
| 19 | ||
| 20 | ## When nothing is in stock | |
| 21 | ||
| 22 | When no CX type with 2 GiB can be ordered in Nuremberg, the deploy stops **before it makes anything** and says so ("Hetzner has no CX server with 2 GiB or more that can be ordered in nbg1 right now; nothing was made. Try again later."). Nothing is billed; try again later. | |
| 23 | ||
| 24 | ## The audit | |
| 25 | ||
| 26 | Cloud accounts → Audit lists a Hetzner volume attached to no server, and a powered-off server (still billed), priced at the server type's price in the server's own location. | |
| 27 | ||
| 28 | ## Not checked here | |
| 29 | ||
| 30 | The `/server_types` price shape and `/datacenters` `server_types.available` were written from the Hetzner API reference as recalled; this sandbox cannot reach docs.hetzner.cloud, so a first real deploy is the check. A shape that differs stops with the "nothing can be ordered" message rather than ordering a guess. |
docs/features/pinned-forge.md +1
| @@ -31,6 +31,7 @@ Prices are list prices as last read (USD a month); the owner's own bill is the t | ||
| 31 | 31 | | Target | Status | What runs | Cost | Refused / caveat | |
| 32 | 32 | |---|---|---|---|---| |
| 33 | 33 | | DigitalOcean | **deploys today** | One droplet (`s-1vcpu-2gb`, Ubuntu 24.04) with a 10 GiB block volume as `FORGE_APP_DATA`. An Update deletes the droplet and starts a new one on the same volume, so data is untouched. | ~$12 + ~$1.20 | A token cannot be narrowed below "create droplets and volumes". | |
| 34 | | Hetzner Cloud | **deploys today** | One server (Ubuntu 24.04) with a 10 GiB volume as `FORGE_APP_DATA`, in Nuremberg; the type is the cheapest in-stock CX with 2 GiB, read from the API. See `deploy-to-hetzner.md`. | the API's list price + the volume | The token must be read-write; Hetzner offers nothing narrower. | | |
| 34 | 35 | | AWS | not written | EC2 `t4g.small` + EBS gp3, same boot script; SigV4 already exists for reads. | ~$12 + ~$0.80 + public IPv4 ~$3.65 | Wants a role scoped to a tag rather than a long-lived key. | |
| 35 | 36 | | Azure | not written | B1ms VM + managed disk through a service principal on one resource group. | ~$15 + ~$1 + public IP ~$3.65 | Needs a resource group, network and public IP first: three calls more. | |
| 36 | 37 | | Cloudflare | **refused** | Workers/Durable Objects keep state, but not as files a Bun process opens. Containers run, with a disk wiped on sleep or replace. | Workers Paid from $5 | No volume that survives; the forge refuses rather than lose repositories quietly. | |
forge.json +1
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | "challenges.cloudflare.com", |
| 8 | 8 | "api.cloudflare.com", |
| 9 | 9 | "api.digitalocean.com", |
| 10 | "api.hetzner.cloud", | |
| 10 | 11 | "api.fly.io", |
| 11 | 12 | "api.backblazeb2.com", |
| 12 | 13 | "api.vercel.com", |
src/actions/pinned.ts +9 −5
| @@ -11,7 +11,8 @@ | ||
| 11 | 11 | |
| 12 | 12 | import type { App } from "../app.ts"; |
| 13 | 13 | import { gatedFetch } from "../cloud/gate.ts"; |
| 14 | import { provision, readDroplet, replace } from "../cloud/droplet.ts"; | |
| 14 | import { driverOf } from "../cloud/drivers.ts"; | |
| 15 | import { provision, read, replace } from "../cloud/machine.ts"; | |
| 15 | 16 | import type { Fetch } from "../cloud/providers.ts"; |
| 16 | 17 | import { target as targetOf } from "../cloud/targets.ts"; |
| 17 | 18 | import { getCloudAccount, secretNameOf } from "../core/cloud_account.ts"; |
| @@ -59,11 +60,14 @@ async function withCloud<T>(app: App, who: User, p: Pinned, purpose: string, go: | ||
| 59 | 60 | } |
| 60 | 61 | } |
| 61 | 62 | |
| 62 | /** Read the droplet back and record its public IPv4 (empty while none is assigned). The cloud's refusal is returned, so "no address yet" and "the call was refused" differ. */ | |
| 63 | /** | |
| 64 | * Read the machine back and record its public IPv4 (empty while none is assigned). The cloud's | |
| 65 | * refusal is returned, so "no address yet" and "the call was refused" differ. | |
| 66 | */ | |
| 63 | 67 | async function readAddress(app: App, who: User, name: string): Promise<Result<string, string>> { |
| 64 | 68 | const p = getPinned(app.db, name); |
| 65 | 69 | if (!p || p.remote === "") return ok(""); |
| 66 | const seen = await withCloud(app, who, p, "address", (f, token) => readDroplet(f, token, p.remote), false); | |
| 70 | const seen = await withCloud(app, who, p, "address", (f, token) => read(driverOf(p.target), f, token, p.remote), false); | |
| 67 | 71 | if (!seen.ok) return seen; |
| 68 | 72 | if (seen.value.address !== "") setRemote(app.db, name, { address: seen.value.address }); |
| 69 | 73 | return ok(seen.value.address); |
| @@ -95,7 +99,7 @@ export async function deployPinned( | ||
| 95 | 99 | app.bus.append({ kind: "pinned.deployed", actorId: who.value.id, payload: { name: p.name, target: p.target, version: p.version } }); |
| 96 | 100 | if (old?.volume) setRemote(app.db, p.name, { volume: old.volume }); |
| 97 | 101 | const made = await withCloud(app, who.value, p, "deploy", (f, token) => |
| 98 | provision(f, token, getPinned(app.db, p.name)!, { | |
| 102 | provision(driverOf(p.target), f, token, getPinned(app.db, p.name)!, { | |
| 99 | 103 | ...(old?.volume ? { have: old.volume } : {}), |
| 100 | 104 | onVolume: (volume) => setRemote(app.db, p.name, { volume }), |
| 101 | 105 | }), |
| @@ -129,7 +133,7 @@ async function change( | ||
| 129 | 133 | app.bus.append({ kind: kind === "update" ? "pinned.update" : "pinned.rollback", actorId: who.value.id, payload: { name, from: c.fromVersion, to: c.toVersion } }); |
| 130 | 134 | } |
| 131 | 135 | const after = getPinned(app.db, name)!; |
| 132 | const done = await withCloud(app, who.value, after, kind, (f, token) => replace(f, token, after, { onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }) })); | |
| 136 | const done = await withCloud(app, who.value, after, kind, (f, token) => replace(driverOf(after.target), f, token, after, { onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }) })); | |
| 133 | 137 | if (!done.ok) { |
| 134 | 138 | setRemote(app.db, name, { state: "failed" }); |
| 135 | 139 | return done; |
src/cloud/declared.ts +1
| @@ -17,6 +17,7 @@ import type { Provider } from "./providers.ts"; | ||
| 17 | 17 | export const HOME: Record<Provider, string> = { |
| 18 | 18 | cloudflare: "Bring it home: point DNS back at your own nameservers, then remove the token.", |
| 19 | 19 | digitalocean: "Bring it home: snapshot the droplets to your own disk, then remove the token.", |
| 20 | hetzner: "Bring it home: snapshot the servers and volumes to your own disk, then remove the token.", | |
| 20 | 21 | aws: "Bring it home: copy the volumes and buckets to your own disk, then remove the key.", |
| 21 | 22 | azure: "Bring it home: export the disks to your own disk, then remove the principal.", |
| 22 | 23 | fly: "Bring it home: run the app image on your own machine, then remove the token.", |
src/cloud/drivers.ts added +17
| @@ -0,0 +1,17 @@ | ||
| 1 | /** | |
| 2 | * The driver of each target that deploys: a new cloud is one line here, one file of calls, one | |
| 3 | * entry in targets.ts. | |
| 4 | */ | |
| 5 | ||
| 6 | import { digitalocean } from "./droplet.ts"; | |
| 7 | import { hetzner } from "./hetzner.ts"; | |
| 8 | import type { Driver } from "./machine.ts"; | |
| 9 | ||
| 10 | const DRIVERS: Readonly<Record<string, Driver<any>>> = { digitalocean, hetzner }; | |
| 11 | ||
| 12 | /** The driver of a target, or a plain error when none deploys there. */ | |
| 13 | export function driverOf(id: string): Driver<any> { | |
| 14 | const d = DRIVERS[id]; | |
| 15 | if (!d) throw new Error(`No driver deploys to ${id}.`); | |
| 16 | return d; | |
| 17 | } |
src/cloud/droplet.ts +30 −121
| @@ -1,135 +1,44 @@ | ||
| 1 | 1 | /** |
| 2 | * DigitalOcean, the first target (#8697): the requests that put a pinned | |
| 3 | * forge on a droplet with a volume, and replace the droplet on an explicit | |
| 4 | * Update while the volume — the forge's data — stays. Plain data in, plain | |
| 5 | * data out: the caller owns the token and the fetch. The token travels in an | |
| 6 | * Authorization header over HTTPS, never on argv, and the boot script holds no | |
| 7 | * secret at all: the new forge's first visitor claims it at /first-admin. | |
| 2 | * DigitalOcean, the first target (#8697): its calls only; the sequence they | |
| 3 | * run in is machine.ts. | |
| 8 | 4 | * |
| 9 | 5 | * Calls (DigitalOcean API v2): POST /volumes, POST /droplets, DELETE /droplets/{id}, GET /droplets/{id} |
| 10 | 6 | * (the public IPv4 the droplet was given, read back after it boots). |
| 11 | * The caller records each id the moment it exists (`onVolume`, `onDeleted`), | |
| 12 | * so a failure half-way leaves a row a retry can finish, never an orphan. | |
| 13 | 7 | */ |
| 14 | 8 | |
| 15 | import type { Fetch } from "./providers.ts"; | |
| 9 | import { bootConfig as boot, ipv4, volumeName, type Driver } from "./machine.ts"; | |
| 16 | 10 | import type { Pinned } from "../core/pinned.ts"; |
| 17 | 11 | |
| 18 | const API = "https://api.digitalocean.com/v2"; | |
| 12 | export { BUN_VERSION } from "./machine.ts"; | |
| 19 | 13 | export const REGION = "nyc3"; |
| 20 | 14 | export const SIZE = "s-1vcpu-2gb"; |
| 21 | /** The Bun the droplet installs: it moves only when this line does, in a pull, so the runtime is pinned as the forge is. */ | |
| 22 | export const BUN_VERSION = "1.4.4"; | |
| 23 | 15 | |
| 24 | /** cloud-config for the droplet: Bun, the pinned source at the pinned version, a systemd unit. */ | |
| 25 | export function bootConfig(p: Pick<Pinned, "name" | "source" | "version" | "config">): string { | |
| 26 | // DigitalOcean mounts a volume at /mnt/<its name, dashes as underscores>. | |
| 27 | const data = `/mnt/${volumeName(p.name).replace(/-/g, "_")}`; | |
| 28 | const env = Object.entries({ ...p.config, FORGE_APP_DATA: data }) | |
| 29 | .map(([k, v]) => `${k}=${v}`) | |
| 30 | .join("\n"); | |
| 31 | // Every interpolated value is validated in core/pinned.ts (version, source, config) or by NAME. | |
| 32 | return `#cloud-config | |
| 33 | write_files: | |
| 34 | - path: /etc/forge/env | |
| 35 | permissions: "0600" | |
| 36 | content: ${JSON.stringify(env + "\n")} | |
| 37 | - path: /etc/systemd/system/forge.service | |
| 38 | content: | | |
| 39 | [Unit] | |
| 40 | Description=forge ${p.name} pinned at ${p.version} | |
| 41 | After=network-online.target | |
| 42 | [Service] | |
| 43 | EnvironmentFile=/etc/forge/env | |
| 44 | WorkingDirectory=/opt/forge | |
| 45 | ExecStart=/root/.bun/bin/bun run src/main.ts | |
| 46 | Restart=on-failure | |
| 47 | [Install] | |
| 48 | WantedBy=multi-user.target | |
| 49 | runcmd: | |
| 50 | - curl -fsSL https://bun.sh/install | bash -s "bun-v${BUN_VERSION}" | |
| 51 | - git clone ${p.source} /opt/forge | |
| 52 | - git -C /opt/forge checkout --detach ${p.version} | |
| 53 | - systemctl enable --now forge.service | |
| 54 | `; | |
| 55 | } | |
| 16 | /** DigitalOcean mounts a volume at /mnt/<its name, dashes as underscores>. */ | |
| 17 | const dataDir = (name: string) => `/mnt/${volumeName(name).replace(/-/g, "_")}`; | |
| 56 | 18 | |
| 57 | const headers = (token: string) => ({ authorization: `Bearer ${token}`, "content-type": "application/json" }); | |
| 19 | export const bootConfig = (p: Pick<Pinned, "name" | "source" | "version" | "config">): string => boot(p, dataDir(p.name)); | |
| 58 | 20 | |
| 59 | async function call(f: Fetch, token: string, method: string, path: string, body?: unknown): Promise<any> { | |
| 60 | const res = await f(`${API}${path}`, { | |
| 61 | method, | |
| 62 | headers: headers(token), | |
| 63 | ...(body === undefined ? {} : { body: JSON.stringify(body) }), | |
| 64 | signal: AbortSignal.timeout(20_000), | |
| 65 | }); | |
| 66 | if (!res.ok) throw new Error(`api.digitalocean.com answered ${res.status}`); | |
| 67 | return res.status === 204 ? {} : await res.json(); | |
| 68 | } | |
| 69 | ||
| 70 | const volumeName = (name: string) => `forge-${name}-data`; | |
| 71 | ||
| 72 | function createDroplet(f: Fetch, token: string, p: Pinned, volumeId: string) { | |
| 73 | return call(f, token, "POST", "/droplets", { | |
| 74 | name: `forge-${p.name}`, | |
| 75 | region: REGION, | |
| 76 | size: SIZE, | |
| 77 | image: "ubuntu-24-04-x64", | |
| 78 | volumes: [volumeId], | |
| 79 | user_data: bootConfig(p), | |
| 80 | tags: ["forge-pinned"], | |
| 81 | }); | |
| 82 | } | |
| 83 | ||
| 84 | /** | |
| 85 | * Volume first, then the droplet that mounts it. A volume a failed earlier try | |
| 86 | * made (`have`) is reused; a new one is recorded through `onVolume` before the | |
| 87 | * droplet is asked for. Returns the ids to keep. | |
| 88 | */ | |
| 89 | export async function provision( | |
| 90 | f: Fetch, token: string, p: Pinned, hooks: { have?: string; onVolume(id: string): void }, | |
| 91 | ): Promise<{ remote: string; volume: string }> { | |
| 92 | let volume = hooks.have ?? ""; | |
| 93 | if (volume === "") { | |
| 94 | const v = await call(f, token, "POST", "/volumes", { | |
| 95 | name: volumeName(p.name), region: REGION, size_gigabytes: 10, filesystem_type: "ext4", | |
| 21 | export const digitalocean: Driver = { | |
| 22 | api: "https://api.digitalocean.com/v2", | |
| 23 | plan: async () => undefined, | |
| 24 | async createVolume(call, p) { | |
| 25 | const v = await call("POST", "/volumes", { name: volumeName(p.name), region: REGION, size_gigabytes: 10, filesystem_type: "ext4" }); | |
| 26 | return String(v.volume?.id ?? ""); | |
| 27 | }, | |
| 28 | async createMachine(call, p, volume) { | |
| 29 | const d = await call("POST", "/droplets", { | |
| 30 | name: `forge-${p.name}`, region: REGION, size: SIZE, image: "ubuntu-24-04-x64", | |
| 31 | volumes: [volume], user_data: bootConfig(p), tags: ["forge-pinned"], | |
| 96 | 32 | }); |
| 97 | volume = String(v.volume?.id ?? ""); | |
| 98 | if (!volume) throw new Error("DigitalOcean made no volume"); | |
| 99 | hooks.onVolume(volume); | |
| 100 | } | |
| 101 | const d = await createDroplet(f, token, p, volume); | |
| 102 | return { remote: String(d.droplet?.id ?? ""), volume }; | |
| 103 | } | |
| 104 | ||
| 105 | /** | |
| 106 | * An explicit Update or rollback: delete the old droplet, start a new one on | |
| 107 | * the same volume. A droplet already gone (404, or none recorded after a failed | |
| 108 | * create) counts as deleted, and `onDeleted` clears the recorded id at once, so | |
| 109 | * a retry after a failed create does not delete twice. | |
| 110 | */ | |
| 111 | export async function replace(f: Fetch, token: string, p: Pinned, hooks: { onDeleted(): void }): Promise<{ remote: string }> { | |
| 112 | if (p.volume === "") throw new Error("this forge has no volume to keep"); | |
| 113 | if (p.remote !== "") { | |
| 114 | if (!/^\d+$/.test(p.remote)) throw new Error("this forge has no droplet to replace"); | |
| 115 | try { | |
| 116 | await call(f, token, "DELETE", `/droplets/${p.remote}`); | |
| 117 | } catch (e) { | |
| 118 | if (!(e instanceof Error && e.message.endsWith("answered 404"))) throw e; | |
| 119 | } | |
| 120 | hooks.onDeleted(); | |
| 121 | } | |
| 122 | const d = await createDroplet(f, token, p, p.volume); | |
| 123 | return { remote: String(d.droplet?.id ?? "") }; | |
| 124 | } | |
| 125 | ||
| 126 | const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)$/; | |
| 127 | ||
| 128 | /** Read the droplet back: its status and public IPv4 (empty while none is assigned). Only a well-formed address is returned. */ | |
| 129 | export async function readDroplet(f: Fetch, token: string, remote: string): Promise<{ status: string; address: string }> { | |
| 130 | if (!/^\d+$/.test(remote)) throw new Error("this forge has no droplet to read"); | |
| 131 | const d = (await call(f, token, "GET", `/droplets/${remote}`)).droplet; | |
| 132 | const v4: unknown[] = Array.isArray(d?.networks?.v4) ? d.networks.v4 : []; | |
| 133 | const pub = v4.find((n: any) => n?.type === "public" && typeof n.ip_address === "string" && IPV4.test(n.ip_address)) as { ip_address: string } | undefined; | |
| 134 | return { status: String(d?.status ?? ""), address: pub?.ip_address ?? "" }; | |
| 135 | } | |
| 33 | return String(d.droplet?.id ?? ""); | |
| 34 | }, | |
| 35 | async deleteMachine(call, remote) { | |
| 36 | await call("DELETE", `/droplets/${remote}`); | |
| 37 | }, | |
| 38 | async readMachine(call, remote) { | |
| 39 | const d = (await call("GET", `/droplets/${remote}`)).droplet; | |
| 40 | const v4: unknown[] = Array.isArray(d?.networks?.v4) ? d.networks.v4 : []; | |
| 41 | const pub = v4.find((n: any) => n?.type === "public" && ipv4(n.ip_address) !== "") as { ip_address: string } | undefined; | |
| 42 | return { status: String(d?.status ?? ""), address: pub?.ip_address ?? "" }; | |
| 43 | }, | |
| 44 | }; |
src/cloud/hetzner.ts added +77
| @@ -0,0 +1,77 @@ | ||
| 1 | /** | |
| 2 | * Hetzner Cloud (#16200): its calls only; the sequence they run in is | |
| 3 | * machine.ts. A Hetzner token is scoped to one project and is read or | |
| 4 | * read-write, nothing narrower. | |
| 5 | * | |
| 6 | * Calls (Hetzner Cloud API v1): GET /server_types and /datacenters (what can be | |
| 7 | * ordered where, read before anything is made), POST /volumes, POST /servers | |
| 8 | * (the volume attached and automounted at /mnt/HC_Volume_<id>), DELETE | |
| 9 | * /servers/{id}, GET /servers/{id} (the public IPv4 read back after it boots). | |
| 10 | */ | |
| 11 | ||
| 12 | import { bootConfig as boot, ipv4, volumeName, type Call, type Driver } from "./machine.ts"; | |
| 13 | import type { Pinned } from "../core/pinned.ts"; | |
| 14 | ||
| 15 | /** | |
| 16 | * Nuremberg: an EU location, because the US ones cost about three times as much for a tenth of the | |
| 17 | * traffic. One constant a setting can later replace. | |
| 18 | */ | |
| 19 | export const LOCATION = "nbg1"; | |
| 20 | /** | |
| 21 | * The cost-optimized shared line (CX); the type is chosen from the API at order time, never named | |
| 22 | * here. | |
| 23 | */ | |
| 24 | export const TYPE_LINE = /^cx\d+$/; | |
| 25 | /** The least memory a forge runs in, GiB. */ | |
| 26 | export const MIN_MEMORY_GIB = 2; | |
| 27 | const IMAGE = "ubuntu-24.04"; | |
| 28 | ||
| 29 | /** Hetzner mounts an attached volume, when automount is asked for, under /mnt/HC_Volume_<id>. */ | |
| 30 | const dataDir = (volume: string) => `/mnt/HC_Volume_${volume}`; | |
| 31 | ||
| 32 | export const bootConfig = (p: Pick<Pinned, "name" | "source" | "version" | "config">, volume: string): string => boot(p, dataDir(volume)); | |
| 33 | ||
| 34 | /** | |
| 35 | * The cheapest x86 server type of the CX line with at least MIN_MEMORY_GIB that | |
| 36 | * can be ordered at `location` now, read from the API; throws, in words the | |
| 37 | * pinned page can show as they are, when there is none. | |
| 38 | */ | |
| 39 | export async function pickType(call: Call, location = LOCATION): Promise<string> { | |
| 40 | const types: any[] = (await call("GET", "/server_types?per_page=50")).server_types ?? []; | |
| 41 | const dcs: any[] = (await call("GET", "/datacenters?per_page=50")).datacenters ?? []; | |
| 42 | const here = dcs.filter((d) => d?.location?.name === location); | |
| 43 | const stocked = new Set<number>(here.flatMap((d) => (Array.isArray(d?.server_types?.available) ? d.server_types.available : []))); | |
| 44 | const price = (t: any) => Number(t.prices?.find((x: any) => x?.location === location)?.price_monthly?.gross); | |
| 45 | const options = types | |
| 46 | .filter((t) => TYPE_LINE.test(String(t?.name)) && t.architecture === "x86" && Number(t.memory) >= MIN_MEMORY_GIB && !t.deprecated) | |
| 47 | .filter((t) => stocked.has(t.id)) | |
| 48 | .filter((t) => Number.isFinite(price(t))) | |
| 49 | .sort((a, b) => price(a) - price(b) || String(a.name).localeCompare(String(b.name))); | |
| 50 | const best = options[0]; | |
| 51 | if (!best) throw new Error(`Hetzner has no CX server with ${MIN_MEMORY_GIB} GiB or more that can be ordered in ${location} right now; nothing was made. Try again later.`); | |
| 52 | return String(best.name); | |
| 53 | } | |
| 54 | ||
| 55 | export const hetzner: Driver<string> = { | |
| 56 | api: "https://api.hetzner.cloud/v1", | |
| 57 | plan: (call) => pickType(call), | |
| 58 | async createVolume(call, p) { | |
| 59 | const v = await call("POST", "/volumes", { name: volumeName(p.name), location: LOCATION, size: 10, format: "ext4", automount: false }); | |
| 60 | return String(v.volume?.id ?? ""); | |
| 61 | }, | |
| 62 | async createMachine(call, p, volume, type) { | |
| 63 | const s = await call("POST", "/servers", { | |
| 64 | name: `forge-${p.name}`, server_type: type, location: LOCATION, image: IMAGE, | |
| 65 | volumes: [Number(volume)], automount: true, user_data: bootConfig(p, volume), | |
| 66 | public_net: { enable_ipv4: true, enable_ipv6: true }, start_after_create: true, labels: { "forge-pinned": "true" }, | |
| 67 | }); | |
| 68 | return String(s.server?.id ?? ""); | |
| 69 | }, | |
| 70 | async deleteMachine(call, remote) { | |
| 71 | await call("DELETE", `/servers/${remote}`); | |
| 72 | }, | |
| 73 | async readMachine(call, remote) { | |
| 74 | const s = (await call("GET", `/servers/${remote}`)).server; | |
| 75 | return { status: String(s?.status ?? ""), address: ipv4(s?.public_net?.ipv4?.ip) }; | |
| 76 | }, | |
| 77 | }; |
src/cloud/machine.ts added +148
| @@ -0,0 +1,148 @@ | ||
| 1 | /** | |
| 2 | * What every cloud's driver shares (#8697, #16200): the boot config, the | |
| 3 | * provision / replace / read sequence and the half-way hooks. A cloud supplies | |
| 4 | * only a `Driver` — its host, its calls and where it mounts the volume — so a | |
| 5 | * new provider costs its API calls and nothing else. Plain data in, plain data | |
| 6 | * out: the caller owns the token and the fetch. The token travels in an | |
| 7 | * Authorization header over HTTPS, never on argv, and the boot script holds no | |
| 8 | * secret at all: the new forge's first visitor claims it at /first-admin. | |
| 9 | * The caller records each id the moment it exists (`onVolume`, `onDeleted`), so | |
| 10 | * a failure half-way leaves a row a retry can finish, never an orphan. | |
| 11 | */ | |
| 12 | ||
| 13 | import type { Fetch } from "./providers.ts"; | |
| 14 | import type { Pinned } from "../core/pinned.ts"; | |
| 15 | ||
| 16 | /** | |
| 17 | * The Bun the machine installs: it moves only when this line does, in a pull, so the runtime is | |
| 18 | * pinned as the forge is. | |
| 19 | */ | |
| 20 | export const BUN_VERSION = "1.4.4"; | |
| 21 | ||
| 22 | /** The name of the volume holding a forge's data, the same on every cloud. */ | |
| 23 | export const volumeName = (name: string) => `forge-${name}-data`; | |
| 24 | ||
| 25 | /** | |
| 26 | * cloud-config for the machine: Bun, the pinned source at the pinned version, a systemd unit; | |
| 27 | * `dataDir` is where the volume is mounted. | |
| 28 | */ | |
| 29 | export function bootConfig(p: Pick<Pinned, "name" | "source" | "version" | "config">, dataDir: string): string { | |
| 30 | const env = Object.entries({ ...p.config, FORGE_APP_DATA: dataDir }) | |
| 31 | .map(([k, v]) => `${k}=${v}`) | |
| 32 | .join("\n"); | |
| 33 | // Every interpolated value is validated in core/pinned.ts (version, source, config) or by NAME; | |
| 34 | // dataDir is the driver's own. | |
| 35 | return `#cloud-config | |
| 36 | write_files: | |
| 37 | - path: /etc/forge/env | |
| 38 | permissions: "0600" | |
| 39 | content: ${JSON.stringify(env + "\n")} | |
| 40 | - path: /etc/systemd/system/forge.service | |
| 41 | content: | | |
| 42 | [Unit] | |
| 43 | Description=forge ${p.name} pinned at ${p.version} | |
| 44 | After=network-online.target | |
| 45 | [Service] | |
| 46 | EnvironmentFile=/etc/forge/env | |
| 47 | WorkingDirectory=/opt/forge | |
| 48 | ExecStart=/root/.bun/bin/bun run src/main.ts | |
| 49 | Restart=on-failure | |
| 50 | [Install] | |
| 51 | WantedBy=multi-user.target | |
| 52 | runcmd: | |
| 53 | - curl -fsSL https://bun.sh/install | bash -s "bun-v${BUN_VERSION}" | |
| 54 | - git clone ${p.source} /opt/forge | |
| 55 | - git -C /opt/forge checkout --detach ${p.version} | |
| 56 | - systemctl enable --now forge.service | |
| 57 | `; | |
| 58 | } | |
| 59 | ||
| 60 | /** One request to the cloud's fixed host; the driver's calls are made through it. */ | |
| 61 | export type Call = (method: string, path: string, body?: unknown) => Promise<any>; | |
| 62 | ||
| 63 | /** What a cloud supplies; `Plan` is what it decides before anything is made (a size, a type). */ | |
| 64 | export interface Driver<Plan = undefined> { | |
| 65 | /** The fixed API base, https, no trailing slash. */ | |
| 66 | readonly api: string; | |
| 67 | /** | |
| 68 | * Decide what to order, or throw plainly when it cannot be ordered: called before the first thing | |
| 69 | * is made. | |
| 70 | */ | |
| 71 | plan(call: Call): Promise<Plan>; | |
| 72 | createVolume(call: Call, p: Pinned, plan: Plan): Promise<string>; | |
| 73 | /** Make the machine with the volume attached; returns its id. */ | |
| 74 | createMachine(call: Call, p: Pinned, volume: string, plan: Plan): Promise<string>; | |
| 75 | deleteMachine(call: Call, remote: string): Promise<void>; | |
| 76 | readMachine(call: Call, remote: string): Promise<{ status: string; address: string }>; | |
| 77 | } | |
| 78 | ||
| 79 | function caller(d: Driver<any>, f: Fetch, token: string): Call { | |
| 80 | const host = new URL(d.api).host; | |
| 81 | return async (method, path, body) => { | |
| 82 | const res = await f(`${d.api}${path}`, { | |
| 83 | method, | |
| 84 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 85 | ...(body === undefined ? {} : { body: JSON.stringify(body) }), | |
| 86 | signal: AbortSignal.timeout(20_000), | |
| 87 | }); | |
| 88 | if (!res.ok) throw new Error(`${host} answered ${res.status}`); | |
| 89 | return res.status === 204 ? {} : await res.json(); | |
| 90 | }; | |
| 91 | } | |
| 92 | ||
| 93 | const ID = /^\d+$/; | |
| 94 | ||
| 95 | /** | |
| 96 | * Volume first, then the machine that mounts it. A volume a failed earlier try | |
| 97 | * made (`have`) is reused; a new one is recorded through `onVolume` before the | |
| 98 | * machine is asked for. Returns the ids to keep. | |
| 99 | */ | |
| 100 | export async function provision<P>( | |
| 101 | d: Driver<P>, f: Fetch, token: string, p: Pinned, hooks: { have?: string; onVolume(id: string): void }, | |
| 102 | ): Promise<{ remote: string; volume: string }> { | |
| 103 | const call = caller(d, f, token); | |
| 104 | const plan = await d.plan(call); | |
| 105 | let volume = hooks.have ?? ""; | |
| 106 | if (volume === "") { | |
| 107 | volume = await d.createVolume(call, p, plan); | |
| 108 | if (volume === "") throw new Error(`${new URL(d.api).host} made no volume`); | |
| 109 | hooks.onVolume(volume); | |
| 110 | } | |
| 111 | return { remote: await d.createMachine(call, p, volume, plan), volume }; | |
| 112 | } | |
| 113 | ||
| 114 | /** | |
| 115 | * An explicit Update or rollback: delete the old machine, start a new one on | |
| 116 | * the same volume. What to order is decided first, so a cloud that cannot | |
| 117 | * deliver says so while the old machine still runs. A machine already gone | |
| 118 | * (404, or none recorded after a failed create) counts as deleted, and | |
| 119 | * `onDeleted` clears the recorded id at once, so a retry after a failed create | |
| 120 | * does not delete twice. | |
| 121 | */ | |
| 122 | export async function replace<P>( | |
| 123 | d: Driver<P>, f: Fetch, token: string, p: Pinned, hooks: { onDeleted(): void }, | |
| 124 | ): Promise<{ remote: string }> { | |
| 125 | if (p.volume === "") throw new Error("this forge has no volume to keep"); | |
| 126 | if (p.remote !== "" && !ID.test(p.remote)) throw new Error("this forge has no machine to replace"); | |
| 127 | const call = caller(d, f, token); | |
| 128 | const plan = await d.plan(call); | |
| 129 | if (p.remote !== "") { | |
| 130 | try { | |
| 131 | await d.deleteMachine(call, p.remote); | |
| 132 | } catch (e) { | |
| 133 | if (!(e instanceof Error && e.message.endsWith("answered 404"))) throw e; | |
| 134 | } | |
| 135 | hooks.onDeleted(); | |
| 136 | } | |
| 137 | return { remote: await d.createMachine(call, p, p.volume, plan) }; | |
| 138 | } | |
| 139 | ||
| 140 | const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)$/; | |
| 141 | /** Only a well-formed IPv4 address is ever kept. */ | |
| 142 | export const ipv4 = (v: unknown): string => (typeof v === "string" && IPV4.test(v) ? v : ""); | |
| 143 | ||
| 144 | /** Read the machine back: its status and public IPv4 (empty while none is assigned). */ | |
| 145 | export async function read(d: Driver<any>, f: Fetch, token: string, remote: string): Promise<{ status: string; address: string }> { | |
| 146 | if (!ID.test(remote)) throw new Error("this forge has no machine to read"); | |
| 147 | return d.readMachine(caller(d, f, token), remote); | |
| 148 | } |
src/cloud/providers.ts +27
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | * cloudflare GET api.cloudflare.com/client/v4/user/tokens/verify, /zones |
| 7 | 7 | * digitalocean GET api.digitalocean.com/v2/account, /projects, /droplets, |
| 8 | 8 | * /volumes, /reserved_ips |
| 9 | * hetzner GET api.hetzner.cloud/v1/servers, /volumes | |
| 9 | 10 | * aws POST sts.amazonaws.com Action=GetCallerIdentity (a read), |
| 10 | 11 | * POST ec2.us-east-1.amazonaws.com Action=DescribeVolumes, |
| 11 | 12 | * DescribeAddresses (reads, despite the verb) |
| @@ -30,6 +31,7 @@ import { err, ok, type Result } from "../kernel/result.ts"; | ||
| 30 | 31 | export const PROVIDERS = [ |
| 31 | 32 | "cloudflare", |
| 32 | 33 | "digitalocean", |
| 34 | "hetzner", | |
| 33 | 35 | "aws", |
| 34 | 36 | "azure", |
| 35 | 37 | "fly", |
| @@ -47,6 +49,7 @@ export type Provider = (typeof PROVIDERS)[number]; | ||
| 47 | 49 | export const VENDOR_OF: Record<Provider, CloudVendor> = { |
| 48 | 50 | cloudflare: "cloudflare", |
| 49 | 51 | digitalocean: "digitalocean", |
| 52 | hetzner: "hetzner", | |
| 50 | 53 | aws: "s3", |
| 51 | 54 | azure: "azure", |
| 52 | 55 | fly: "fly", |
| @@ -62,6 +65,7 @@ export function isProvider(v: string): v is Provider { | ||
| 62 | 65 | export const LABEL: Record<Provider, string> = { |
| 63 | 66 | cloudflare: "Cloudflare", |
| 64 | 67 | digitalocean: "DigitalOcean", |
| 68 | hetzner: "Hetzner Cloud", | |
| 65 | 69 | aws: "AWS", |
| 66 | 70 | azure: "Azure", |
| 67 | 71 | fly: "Fly.io", |
| @@ -74,6 +78,7 @@ export const LABEL: Record<Provider, string> = { | ||
| 74 | 78 | export const shape: Record<Provider, string> = { |
| 75 | 79 | cloudflare: "an API token (read-only scope is enough)", |
| 76 | 80 | digitalocean: "a personal access token (read scope is enough)", |
| 81 | hetzner: "a project API token; it is scoped to one project and is read or read-write, nothing narrower, so a pinned forge needs read-write", | |
| 77 | 82 | aws: "ACCESS_KEY_ID:SECRET_ACCESS_KEY of a read-only IAM user", |
| 78 | 83 | azure: "TENANT_ID:CLIENT_ID:CLIENT_SECRET of a Reader service principal", |
| 79 | 84 | fly: "a deploy or read-only org token", |
| @@ -244,6 +249,15 @@ export async function verify( | ||
| 244 | 249 | canWrite: null, |
| 245 | 250 | }); |
| 246 | 251 | } |
| 252 | case "hetzner": { | |
| 253 | const h = bearer(value); | |
| 254 | const s = await json(f, "https://api.hetzner.cloud/v1/servers?per_page=1", { headers: h }); | |
| 255 | const v = await json(f, "https://api.hetzner.cloud/v1/volumes?per_page=1", { headers: h }).catch(() => undefined); | |
| 256 | return ok({ | |
| 257 | summary: `Hetzner project has ${plural(s.meta?.pagination?.total_entries ?? 0, "server")} and ${v ? plural(v.meta?.pagination?.total_entries ?? 0, "volume") : "volumes hidden from this token"}; a Hetzner token belongs to one project and is read or read-write, and the API does not say which.`, | |
| 258 | canWrite: null, | |
| 259 | }); | |
| 260 | } | |
| 247 | 261 | case "aws": { |
| 248 | 262 | const p = parts(value, 2); |
| 249 | 263 | if (!p) return err("An AWS credential is ACCESS_KEY_ID:SECRET_ACCESS_KEY."); |
| @@ -341,6 +355,19 @@ export async function audit( | ||
| 341 | 355 | if (!x.droplet) add(`DigitalOcean: unassigned reserved IP ${x.ip}`, `Reserved IP ${x.ip} points at no droplet.`, 4); |
| 342 | 356 | break; |
| 343 | 357 | } |
| 358 | case "hetzner": { | |
| 359 | const h = bearer(value); | |
| 360 | const base = "https://api.hetzner.cloud/v1"; | |
| 361 | const v = await json(f, `${base}/volumes?per_page=50`, { headers: h }); | |
| 362 | for (const x of v.volumes ?? []) | |
| 363 | if (x.server === null || x.server === undefined) | |
| 364 | add(`Hetzner: unattached volume ${x.name}`, `Volume ${x.name} (${x.size} GB, ${x.location?.name}) is attached to no server.`, Number(x.size) * 0.05); | |
| 365 | const s = await json(f, `${base}/servers?per_page=50`, { headers: h }); | |
| 366 | for (const x of s.servers ?? []) | |
| 367 | if (x.status === "off") | |
| 368 | add(`Hetzner: powered-off server ${x.name}`, `Server ${x.name} (${x.server_type?.name}) is off but still billed at its full price.`, Number(x.server_type?.prices?.find((q: any) => q?.location === x.datacenter?.location?.name)?.price_monthly?.gross ?? 0)); | |
| 369 | break; | |
| 370 | } | |
| 344 | 371 | case "aws": { |
| 345 | 372 | const p = parts(value, 2); |
| 346 | 373 | if (!p) return err("An AWS credential is ACCESS_KEY_ID:SECRET_ACCESS_KEY."); |
src/cloud/targets.ts +9 −1
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | * so, and the owner's own bill is the truth. |
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | export type TargetId = "digitalocean" | "aws" | "azure" | "cloudflare" | "vercel"; | |
| 9 | export type TargetId = "digitalocean" | "hetzner" | "aws" | "azure" | "cloudflare" | "vercel"; | |
| 10 | 10 | |
| 11 | 11 | export interface Target { |
| 12 | 12 | readonly id: TargetId; |
| @@ -27,6 +27,14 @@ export const TARGETS: readonly Target[] = [ | ||
| 27 | 27 | cost: "about $12 (s-1vcpu-2gb) + $1.20 (10 GiB volume)", |
| 28 | 28 | refused: "Nothing the forge needs is refused; the token must be able to create droplets and volumes, which DigitalOcean cannot narrow further.", |
| 29 | 29 | }, |
| 30 | { | |
| 31 | id: "hetzner", | |
| 32 | label: "Hetzner Cloud", | |
| 33 | status: "first", | |
| 34 | runs: "One server (Ubuntu, Bun from the pinned source) with one volume mounted as FORGE_APP_DATA, in Nuremberg. The forge reads Hetzner's own list and orders the cheapest cost-optimized (CX) type with at least 2 GiB that is in stock there; when none can be ordered it says so before it makes anything. Replacing the server keeps the volume.", | |
| 35 | cost: "the cheapest in-stock CX type with at least 2 GiB, at its list price in Nuremberg, + the 10 GiB volume; the API's price is the truth", | |
| 36 | refused: "Nothing the forge needs is refused; the token must be read-write, and Hetzner scopes it to one project and offers nothing narrower.", | |
| 37 | }, | |
| 30 | 38 | { |
| 31 | 39 | id: "aws", |
| 32 | 40 | label: "AWS", |
src/http/mcp/tools/pinned_forge.ts +1 −1
| @@ -5,7 +5,7 @@ import { good, bad, type Tool, str } from "../shared.ts"; | ||
| 5 | 5 | |
| 6 | 6 | export const tool: Tool = { |
| 7 | 7 | 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 droplet'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; `check` reads the machine's address back and probes it (`url`, `healthy`). A forge admin with an admin-scope token", | |
| 9 | 9 | description: "Pinned forges on your cloud: list, deploy, update, rollback, check (admin).", |
| 10 | 10 | inputSchema: { |
| 11 | 11 | type: "object", |
src/http/pinned_routes.ts +7 −2
| @@ -23,7 +23,7 @@ const seen = (get: (k: string) => string): DeployForm => { | ||
| 23 | 23 | app, |
| 24 | 24 | source: get("source").trim().slice(0, 400), |
| 25 | 25 | version: get("version").trim().slice(0, 40), |
| 26 | account: get("account").trim().slice(0, 40), | |
| 26 | account: get("account").trim().slice(0, 60), | |
| 27 | 27 | name: get("name").trim().slice(0, 40) || nameFor(app), |
| 28 | 28 | }; |
| 29 | 29 | }; |
| @@ -52,7 +52,12 @@ async function deployToSubmit(ctx: Ctx): Promise<Response> { | ||
| 52 | 52 | const form = await readForm(ctx, "admin"); |
| 53 | 53 | if (form instanceof Response) return form; |
| 54 | 54 | const v = seen((k) => field(form, k)); |
| 55 | const made = await deployPinned(ctx.app, ctx.auth.user, { ...v, target: "digitalocean" }); | |
| 55 | // The account field is "provider/name"; a bare name is a DigitalOcean account, as the form used | |
| 56 | // to say. | |
| 57 | const bits = v.account.split("/"); | |
| 58 | if (bits.length > 2) return render(ctx, v, { tone: "danger", message: "Pick a cloud account from the list." }); | |
| 59 | const [target, account] = bits.length === 2 ? (bits as [string, string]) : ["digitalocean", v.account]; | |
| 60 | const made = await deployPinned(ctx.app, ctx.auth.user, { ...v, target, account }); | |
| 56 | 61 | if (!made.ok) return render(ctx, v, { tone: "danger", message: made.error }); |
| 57 | 62 | return flashTo(ctx, "/deploy-to", { message: `Deployed ${made.value.name} at ${made.value.version.slice(0, 12)}. It changes only when you press Update.` }); |
| 58 | 63 | } |
src/web/pinned.ts +14 −4
| @@ -6,6 +6,7 @@ | ||
| 6 | 6 | |
| 7 | 7 | import type { CloudAccount } from "../core/cloud_account.ts"; |
| 8 | 8 | import { LABEL } from "../cloud/providers.ts"; |
| 9 | import { TARGETS } from "../cloud/targets.ts"; | |
| 9 | 10 | import { html, type Html } from "./html.ts"; |
| 10 | 11 | import { btn, card, field, selectField } from "./ui.ts"; |
| 11 | 12 | |
| @@ -29,16 +30,25 @@ export function deployToHref(o: { app: string; source: string; version: string } | ||
| 29 | 30 | return `/deploy-to?${q}`; |
| 30 | 31 | } |
| 31 | 32 | |
| 33 | /** The providers a forge can be deployed to: every target that deploys today. */ | |
| 34 | const DEPLOYABLE = new Set<string>(TARGETS.filter((t) => t.status === "first").map((t) => t.id)); | |
| 35 | ||
| 36 | /** | |
| 37 | * "DigitalOcean or Hetzner Cloud": the deployable targets' labels, so a new one needs no prose | |
| 38 | * edit. | |
| 39 | */ | |
| 40 | const NAMES = TARGETS.filter((t) => DEPLOYABLE.has(t.id)).map((t) => t.label).join(" or "); | |
| 41 | ||
outdated
Principles 1 and 8: provider names are hard-coded in the intro. Derive them from LABEL or say 'your own cloud account'. This page's new behaviour is also untested. |
||
| 32 | 42 | export function deployPage(accounts: CloudAccount[], v: DeployForm): Html { |
| 33 | const usable = accounts.filter((a) => a.provider === "digitalocean" && a.writeAllowed); | |
| 43 | const usable = accounts.filter((a) => DEPLOYABLE.has(a.provider) && a.writeAllowed); | |
| 34 | 44 | return html`<div class="page-head"><h1>Deploy to…</h1></div> |
| 35 | 45 | ${card( |
| 36 | 46 | html`<p class="muted small"> |
| 37 | A pinned forge runs one version you choose, on a DigitalOcean droplet in your account. It has no crew and | |
| 47 | A pinned forge runs one version you choose, on a server in your own cloud account. It has no crew and | |
| 38 | 48 | never updates itself: it changes only when you press Update, and Rollback is one action back. |
| 39 | 49 | </p> |
| 40 | 50 | ${usable.length === 0 |
| 41 | ? html`<p class="small" role="status">No cloud account can write yet. Add a DigitalOcean account and allow writes on | |
| 51 | ? html`<p class="small" role="status">No cloud account can write yet. Add a ${NAMES} account and allow writes on | |
| 42 | 52 | <a href="/settings/cloud">Cloud accounts</a>, then come back to this page: what the link carried is kept.</p>` |
| 43 | 53 | : null} |
| 44 | 54 | <form method="post" action="/deploy-to" class="stack"> |
| @@ -46,7 +56,7 @@ export function deployPage(accounts: CloudAccount[], v: DeployForm): Html { | ||
| 46 | 56 | name: "account", |
| 47 | 57 | label: "Cloud account", |
| 48 | 58 | required: true, |
| 49 | options: usable.map((a) => ({ value: a.name, label: `${LABEL[a.provider]} / ${a.name}`, selected: a.name === v.account })), | |
| 59 | options: usable.map((a) => ({ value: `${a.provider}/${a.name}`, label: `${LABEL[a.provider]} / ${a.name}`, selected: v.account === a.name || v.account === `${a.provider}/${a.name}` })), | |
| 50 | 60 | })} |
| 51 | 61 | ${field({ name: "app", label: "App", value: v.app, placeholder: "owner/name", mono: true, required: true, maxlength: 140, spellcheck: false })} |
| 52 | 62 | ${field({ name: "source", label: "Source", value: v.source, placeholder: "https://…", mono: true, required: true, maxlength: 400, spellcheck: false, hint: "An https git address." })} |
test/pinned-forge-address.test.ts +4 −1
| @@ -10,7 +10,8 @@ import { join } from "node:path"; | ||
| 10 | 10 | import { createApp, type App } from "../src/app.ts"; |
| 11 | 11 | import { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts"; |
| 12 | 12 | import { checkPinned, deployPinned, net, pinnedForges } from "../src/actions/pinned.ts"; |
| 13 | import { readDroplet } from "../src/cloud/droplet.ts"; | |
| 13 | import { digitalocean } from "../src/cloud/droplet.ts"; | |
| 14 | import { read } from "../src/cloud/machine.ts"; | |
| 14 | 15 | import { getPinned, portOf, setRemote } from "../src/core/pinned.ts"; |
| 15 | 16 | import { createToken } from "../src/core/tokens.ts"; |
| 16 | 17 | import { createUser, getUserByName } from "../src/core/users.ts"; |
outdated
Item 5: a const declaration in the middle of the imports. Move it below them. |
||
| @@ -21,6 +22,8 @@ import { quietLogs } from "./helpers/globals.ts"; | ||
| 21 | 22 | |
| 22 | 23 | quietLogs(); |
| 23 | 24 | |
| 25 | const readDroplet = (f: any, t: string, r: string) => read(digitalocean, f, t, r); | |
| 26 | ||
| 24 | 27 | describe("pinned forge address", () => { |
| 25 | 28 | let dataDir = ""; |
| 26 | 29 | let app: App; |
test/pinned-forge.test.ts +2 −2
| @@ -174,7 +174,7 @@ describe("pinned forge", () => { | ||
| 174 | 174 | const r = await deployPinned(app, admin(), input({ name: `x-${target}`, target })); |
| 175 | 175 | expect(r.ok).toBe(false); |
| 176 | 176 | } |
| 177 | expect(TARGETS.map((t) => t.id)).toEqual(["digitalocean", "aws", "azure", "cloudflare", "vercel"]); | |
| 177 | expect(TARGETS.map((t) => t.id)).toEqual(["digitalocean", "hetzner", "aws", "azure", "cloudflare", "vercel"]); | |
| 178 | 178 | expect(getPinned(app.db, "x-vercel")).toBeUndefined(); |
| 179 | 179 | }); |
| 180 | 180 | |
| @@ -194,7 +194,7 @@ describe("pinned forge", () => { | ||
| 194 | 194 | const list = await fetch(`${servers.url}/api/v1/admin/pinned`, { headers: h(tok) }); |
| 195 | 195 | expect(list.status).toBe(200); |
| 196 | 196 | const body = (await list.json()) as any; |
| 197 | expect(body.targets).toHaveLength(5); | |
| 197 | expect(body.targets).toHaveLength(6); | |
| 198 | 198 | expect(body.items.length).toBeGreaterThan(0); |
| 199 | 199 | expect((await fetch(`${servers.url}/api/v1/admin/pinned`, { headers: h(bob) })).status).toBeGreaterThanOrEqual(403); |
| 200 | 200 | const up = await fetch(`${servers.url}/api/v1/admin/pinned/fresh/update`, { method: "POST", headers: h(tok), body: JSON.stringify({ version: V2 }) }); |
test/pinned-hetzner-doors.test.ts added +140
| @@ -0,0 +1,140 @@ | ||
| 1 | /** | |
| 2 | * Hetzner Cloud through the doors that already exist (#16200): the Deploy to… page offers | |
| 3 | * `provider/name` and posts it, the terminal takes `hetzner/main`, and the audit prices a stopped | |
| 4 | * server at its own location. Each fails if the line it covers is reverted. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { createApp, type App } from "../src/app.ts"; | |
| 11 | import { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts"; | |
| 12 | import { net } from "../src/actions/pinned.ts"; | |
| 13 | import { audit, type Fetch } from "../src/cloud/providers.ts"; | |
| 14 | import { getPinned } from "../src/core/pinned.ts"; | |
| 15 | import { createToken } from "../src/core/tokens.ts"; | |
| 16 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 17 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 18 | import { Session } from "../src/tui/session.ts"; | |
| 19 | import type { Ctx, Screen } from "../src/tui/app/app.ts"; | |
| 20 | import { pinnedScreen } from "../src/tui/screens/pinned.ts"; | |
| 21 | import { quietLogs } from "./helpers/globals.ts"; | |
| 22 | import { quietCtx } from "./helpers/tui-text.ts"; | |
| 23 | import { waitFor } from "./helpers/poll.ts"; | |
| 24 | ||
| 25 | quietLogs(); | |
| 26 | ||
| 27 | const V = "a".repeat(40); | |
| 28 | const SOURCE = "https://forge.example.org/trevato/forge"; | |
| 29 | const price = (loc: string, gross: string) => ({ location: loc, price_monthly: { gross } }); | |
| 30 | ||
| 31 | describe("Hetzner at the existing doors", () => { | |
| 32 | let dataDir = ""; | |
| 33 | let app: App; | |
| 34 | let servers: Servers; | |
| 35 | let tok = ""; | |
| 36 | const paths: string[] = []; | |
| 37 | const admin = () => getUserByName(app.db, "alice")!; | |
| 38 | const post = (body: Record<string, string>) => | |
| 39 | fetch(servers.url + "/deploy-to", { | |
| 40 | method: "POST", redirect: "manual", | |
| 41 | headers: { authorization: `Bearer ${tok}`, origin: servers.url, "content-type": "application/x-www-form-urlencoded" }, | |
| 42 | body: new URLSearchParams(body), | |
| 43 | }); | |
| 44 | const good = { app: "alice/shop", source: SOURCE, version: V }; | |
| 45 | ||
| 46 | beforeAll(async () => { | |
| 47 | dataDir = await mkdtemp(join(tmpdir(), "forge-hetzner-doors-")); | |
| 48 | app = createApp({ dataDir, port: 0 }); | |
| 49 | servers = await serve(app); | |
| 50 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 51 | if (!made.ok) throw new Error(made.error); | |
| 52 | tok = createToken(app.db, admin().id, "admin", "admin").token; | |
| 53 | cloudNet.fetch = async (url) => | |
| 54 | new Response(JSON.stringify(String(url).includes("hetzner") ? { servers: [], meta: {} } : String(url).includes("vercel") ? { user: { id: "u" } } : { account: { email: "[email protected]", status: "active" } }), { status: 200 }); | |
| 55 | for (const [provider, name, secret] of [["hetzner", "main", "hcloud_Zq4TxLm7Kp2Vb8nWcR5Yd3Fg6Hj9"], ["digitalocean", "main", "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5"], ["vercel", "side", "vcl_Zq4TxLm7Kp2Vb8nWcR5Yd3Fg6Hj9"]] as const) { | |
| 56 | const added = await addAccount(app, admin(), provider, name, secret); | |
| 57 | if (!added.ok) throw new Error(String(added.error)); | |
| 58 | allowWrite(app, admin(), provider, name, true); | |
| 59 | } | |
| 60 | net.fetch = async (url, init) => { | |
| 61 | const u = new URL(url); | |
| 62 | const method = init?.method ?? "GET"; | |
| 63 | paths.push(`${u.host} ${method} ${u.pathname}`); | |
| 64 | const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status }); | |
| 65 | if (u.host === "api.hetzner.cloud") { | |
| 66 | if (u.pathname === "/v1/server_types") return json({ server_types: [{ id: 2, name: "cx23", architecture: "x86", memory: 4, prices: [price("nbg1", "5.99")] }] }); | |
| 67 | if (u.pathname === "/v1/datacenters") return json({ datacenters: [{ location: { name: "nbg1" }, server_types: { available: [2] } }] }); | |
| 68 | if (u.pathname === "/v1/volumes") return json({ volume: { id: 77 } }, 201); | |
| 69 | return json({ server: { id: 501 } }, 201); | |
| 70 | } | |
| 71 | if (u.pathname === "/v2/volumes") return json({ volume: { id: "vol-1" } }, 201); | |
| 72 | return json({ droplet: { id: 7 } }, 202); | |
| 73 | }; | |
| 74 | }, 30_000); | |
| 75 | ||
| 76 | afterAll(async () => { | |
| 77 | await servers.stop(); | |
| 78 | app.close(); | |
| 79 | await rm(dataDir, { recursive: true, force: true }); | |
| 80 | }); | |
| 81 | ||
| 82 | test("the page offers each deployable account as provider/name, and no account of a provider that cannot hold a forge", async () => { | |
| 83 | const html = await (await fetch(servers.url + "/deploy-to", { headers: { authorization: `Bearer ${tok}` } })).text(); | |
| 84 | expect(html).toContain('value="hetzner/main"'); | |
| 85 | expect(html).toContain("Hetzner Cloud / main"); | |
| 86 | expect(html).toContain('value="digitalocean/main"'); | |
| 87 | expect(html).not.toContain("vercel/side"); | |
| 88 | expect(html).not.toContain("Vercel / side"); | |
| 89 | }); | |
| 90 | ||
| 91 | test("the page names no provider in its intro; the empty-state sentence is built from the targets", async () => { | |
| 92 | const html = await (await fetch(servers.url + "/deploy-to", { headers: { authorization: `Bearer ${tok}` } })).text(); | |
| 93 | expect(html).toContain("your own cloud account"); | |
| 94 | }); | |
| 95 | ||
| 96 | test("a posted hetzner/main deploys to Hetzner", async () => { | |
| 97 | const r = await post({ ...good, name: "eu", account: "hetzner/main" }); | |
| 98 | expect(r.status).toBe(303); | |
| 99 | expect(getPinned(app.db, "eu")).toMatchObject({ target: "hetzner", state: "running" }); | |
| 100 | expect(paths.some((p) => p.startsWith("api.hetzner.cloud POST /v1/servers"))).toBe(true); | |
| 101 | }); | |
| 102 | ||
| 103 | test("a bare account name is a DigitalOcean account, as the form used to say", async () => { | |
| 104 | const r = await post({ ...good, name: "old", account: "main" }); | |
| 105 | expect(r.status).toBe(303); | |
| 106 | expect(getPinned(app.db, "old")).toMatchObject({ target: "digitalocean" }); | |
| 107 | }); | |
| 108 | ||
| 109 | test("more than one slash is refused, and deploys nothing", async () => { | |
| 110 | const r = await post({ ...good, name: "odd", account: "hetzner/main/extra" }); | |
| 111 | expect(r.status).toBe(422); | |
| 112 | expect(await r.text()).toContain("Pick a cloud account from the list."); | |
| 113 | expect(getPinned(app.db, "odd")).toBeUndefined(); | |
| 114 | }); | |
| 115 | ||
| 116 | test("terminal: the pinned screen takes hetzner/main and deploys to Hetzner", async () => { | |
| 117 | const f = new Session(app, { sshUsername: "t", remoteAddress: "127.0.0.1", user: admin() }); | |
| 118 | const pushed: Screen[] = []; | |
| 119 | const ctx: Ctx = { ...quietCtx(), push: (s) => void pushed.push(s) }; | |
| 120 | const key = (s: Screen, k: string) => s.key?.({ type: "key", key: k, ctrl: false, alt: false, shift: false }); | |
| 121 | key(pinnedScreen(f, ctx), "d"); | |
| 122 | const prompt = pushed[0]!; | |
| 123 | prompt.paste?.(`tty hetzner/main alice/shop ${SOURCE} ${V}`); | |
| 124 | key(prompt, "enter"); | |
| 125 | await waitFor(() => getPinned(app.db, "tty")?.state === "running"); | |
| 126 | expect(getPinned(app.db, "tty")).toMatchObject({ target: "hetzner", state: "running" }); | |
| 127 | }); | |
| 128 | ||
| 129 | test("the audit prices a stopped Hetzner server at its own location, not the first listed", async () => { | |
| 130 | const f: Fetch = async (url) => { | |
| 131 | const path = new URL(String(url)).pathname; | |
| 132 | if (path === "/v1/volumes") return new Response(JSON.stringify({ volumes: [] }), { status: 200 }); | |
| 133 | return new Response(JSON.stringify({ | |
| 134 | servers: [{ name: "idle", status: "off", datacenter: { location: { name: "hel1" } }, server_type: { name: "cx23", prices: [price("nbg1", "5.00"), price("hel1", "7.00")] } }], | |
| 135 | }), { status: 200 }); | |
| 136 | }; | |
| 137 | const r = await audit("hetzner", "t", f); | |
| 138 | expect(r.ok && r.value.map((x) => x.saving)).toEqual([7]); | |
| 139 | }); | |
| 140 | }); |
test/pinned-hetzner.test.ts added +163
| @@ -0,0 +1,163 @@ | ||
| 1 | /** | |
| 2 | * Hetzner Cloud as a pinned-forge target (#16200): a recorded fetch stands in | |
| 3 | * for api.hetzner.cloud. The shared sequence is proved on DigitalOcean in | |
| 4 | * pinned-forge.test.ts; here are Hetzner's own calls, the type it picks from | |
| 5 | * the API, and the same half-way recovery through the same shared code. | |
| 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 { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts"; | |
| 13 | import { checkPinned, deployPinned, net, updatePinned } from "../src/actions/pinned.ts"; | |
| 14 | import { LOCATION } from "../src/cloud/hetzner.ts"; | |
| 15 | import { verify } from "../src/cloud/providers.ts"; | |
| 16 | import { getPinned } from "../src/core/pinned.ts"; | |
| 17 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 18 | import { quietLogs } from "./helpers/globals.ts"; | |
| 19 | ||
| 20 | quietLogs(); | |
| 21 | ||
| 22 | const TOKEN = "hcloud_Zq4TxLm7Kp2Vb8nWcR5Yd3Fg6Hj9"; | |
| 23 | const V1 = "a".repeat(40); | |
| 24 | const V2 = "b".repeat(40); | |
| 25 | const SOURCE = "https://forge.example.org/trevato/forge"; | |
| 26 | ||
| 27 | const price = (gross: string) => [{ location: LOCATION, price_monthly: { gross } }, { location: "ash", price_monthly: { gross: "30.0" } }]; | |
| 28 | const TYPES = [ | |
| 29 | { id: 1, name: "cx22", architecture: "x86", memory: 4, prices: price("4.5") }, | |
| 30 | { id: 2, name: "cx23", architecture: "x86", memory: 4, prices: price("5.99") }, | |
| 31 | { id: 3, name: "cx12", architecture: "x86", memory: 1, prices: price("3.0") }, | |
| 32 | { id: 4, name: "cax11", architecture: "arm", memory: 4, prices: price("3.5") }, | |
| 33 | { id: 5, name: "cx33", architecture: "x86", memory: 8, prices: price("8.99") }, | |
| 34 | ]; | |
| 35 | ||
| 36 | describe("hetzner target", () => { | |
| 37 | let dataDir = ""; | |
| 38 | let app: App; | |
| 39 | const calls: { method: string; path: string; auth: string | null; body: any }[] = []; | |
| 40 | let stocked: number[] = [2, 5]; | |
| 41 | let failServer = 0; | |
| 42 | let serverSeq = 500; | |
| 43 | ||
| 44 | const admin = () => getUserByName(app.db, "alice")!; | |
| 45 | const input = (over: Record<string, unknown> = {}) => ({ | |
| 46 | name: "acme", target: "hetzner", account: "main", app: "alice/shop", source: SOURCE, version: V1, config: { PUBLIC_NAME: "Acme" }, ...over, | |
| 47 | }); | |
| 48 | const seen = () => calls.map((c) => `${c.method} ${c.path}`); | |
| 49 | ||
| 50 | beforeAll(async () => { | |
| 51 | dataDir = await mkdtemp(join(tmpdir(), "forge-hetzner-")); | |
| 52 | app = createApp({ dataDir, port: 0 }); | |
| 53 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 54 | if (!made.ok) throw new Error(made.error); | |
| 55 | cloudNet.fetch = async () => new Response(JSON.stringify({ servers: [], meta: { pagination: { total_entries: 0 } } }), { status: 200 }); | |
| 56 | const added = await addAccount(app, admin(), "hetzner", "main", TOKEN); | |
| 57 | if (!added.ok) throw new Error(String(added.error)); | |
| 58 | allowWrite(app, admin(), "hetzner", "main", true); | |
| 59 | net.fetch = async (url, init) => { | |
| 60 | const u = new URL(url); | |
| 61 | expect(u.host).toBe("api.hetzner.cloud"); | |
| 62 | const method = init?.method ?? "GET"; | |
| 63 | calls.push({ method, path: u.pathname, auth: new Headers(init?.headers).get("authorization"), body: init?.body ? JSON.parse(String(init.body)) : undefined }); | |
| 64 | const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status }); | |
| 65 | if (u.pathname === "/v1/server_types") return json({ server_types: TYPES }); | |
| 66 | if (u.pathname === "/v1/datacenters") return json({ datacenters: [{ location: { name: LOCATION }, server_types: { available: stocked } }, { location: { name: "ash" }, server_types: { available: [1, 2, 3, 4, 5] } }] }); | |
| 67 | if (u.pathname === "/v1/volumes") return json({ volume: { id: 77 } }, 201); | |
| 68 | if (u.pathname === "/v1/servers" && method === "POST") { | |
| 69 | if (failServer > 0) { failServer--; return json({}, 500); } | |
| 70 | return json({ server: { id: ++serverSeq } }, 201); | |
| 71 | } | |
| 72 | if (method === "DELETE") return json({ action: {} }); | |
| 73 | if (u.pathname.startsWith("/v1/servers/")) return json({ server: { status: "running", public_net: { ipv4: { ip: "203.0.113.9" } } } }); | |
| 74 | return json({}, 404); | |
| 75 | }; | |
| 76 | }, 30_000); | |
| 77 | ||
| 78 | afterAll(async () => { | |
| 79 | app.close(); | |
| 80 | await rm(dataDir, { recursive: true, force: true }); | |
| 81 | }); | |
| 82 | ||
| 83 | test("deploy reads the types, picks the cheapest CX in stock with 2 GiB in an EU location, and mounts the volume by its id", async () => { | |
| 84 | const r = await deployPinned(app, admin(), input()); | |
| 85 | expect(r.ok).toBe(true); | |
| 86 | expect(seen()).toEqual(["GET /v1/server_types", "GET /v1/datacenters", "POST /v1/volumes", "POST /v1/servers"]); | |
| 87 | expect(calls.every((c) => c.auth === `Bearer ${TOKEN}`)).toBe(true); | |
| 88 | expect(JSON.stringify(calls.map((c) => c.body))).not.toContain(TOKEN); | |
| 89 | const [volume, server] = [calls[2]!.body, calls[3]!.body]; | |
| 90 | expect(["nbg1", "fsn1", "hel1"]).toContain(volume.location); | |
| 91 | expect(server).toMatchObject({ server_type: "cx23", location: volume.location, volumes: [77], automount: true }); | |
| 92 | expect(server.user_data).toContain("FORGE_APP_DATA=/mnt/HC_Volume_77"); | |
| 93 | expect(server.user_data).toContain(`checkout --detach ${V1}`); | |
| 94 | expect(server.user_data).not.toContain(TOKEN); | |
| 95 | expect(getPinned(app.db, "acme")).toMatchObject({ target: "hetzner", state: "running", volume: "77", remote: "501" }); | |
| 96 | }); | |
| 97 | ||
| 98 | test("the address is read back from the server", async () => { | |
| 99 | net.probe = async () => new Response("ok", { status: 200 }); | |
| 100 | const r = await checkPinned(app, admin(), "acme"); | |
| 101 | expect(r.ok && r.value.address).toBe("203.0.113.9"); | |
| 102 | expect(calls.at(-1)!.path).toBe("/v1/servers/501"); | |
| 103 | }); | |
| 104 | ||
| 105 | test("Update replaces the server and keeps the volume", async () => { | |
| 106 | calls.length = 0; | |
| 107 | const r = await updatePinned(app, admin(), "acme", { version: V2 }); | |
| 108 | expect(r.ok).toBe(true); | |
| 109 | expect(seen()).toEqual(["GET /v1/server_types", "GET /v1/datacenters", "DELETE /v1/servers/501", "POST /v1/servers"]); | |
| 110 | expect(calls[3]!.body.volumes).toEqual([77]); | |
| 111 | expect(calls[3]!.body.user_data).toContain(`checkout --detach ${V2}`); | |
| 112 | expect(getPinned(app.db, "acme")).toMatchObject({ volume: "77", remote: "502", version: V2 }); | |
| 113 | }); | |
| 114 | ||
| 115 | test("a failure after the volume exists leaves it recorded, and a retry reuses it", async () => { | |
| 116 | app.db.run("DELETE FROM pinned_forge"); | |
| 117 | calls.length = 0; | |
| 118 | failServer = 1; | |
| 119 | const bad = await deployPinned(app, admin(), input({ name: "again" })); | |
| 120 | expect(bad.ok).toBe(false); | |
| 121 | expect(getPinned(app.db, "again")).toMatchObject({ state: "failed", volume: "77", remote: "" }); | |
| 122 | calls.length = 0; | |
| 123 | const good = await deployPinned(app, admin(), input({ name: "again" })); | |
| 124 | expect(good.ok).toBe(true); | |
| 125 | expect(seen()).not.toContain("POST /v1/volumes"); | |
| 126 | expect(getPinned(app.db, "again")).toMatchObject({ state: "running", volume: "77" }); | |
| 127 | }); | |
| 128 | ||
| 129 | test("when no type can be ordered, nothing is made and the page is told so", async () => { | |
| 130 | app.db.run("DELETE FROM pinned_forge"); | |
| 131 | calls.length = 0; | |
| 132 | stocked = [3, 4]; | |
| 133 | const r = await deployPinned(app, admin(), input({ name: "none" })); | |
| 134 | expect(r).toMatchObject({ ok: false }); | |
| 135 | expect(String((r as any).error)).toContain("can be ordered in nbg1 right now"); | |
| 136 | expect(seen().every((s) => s.startsWith("GET"))).toBe(true); | |
| 137 | stocked = [2, 5]; | |
| 138 | }); | |
| 139 | ||
| 140 | test("an Update with no type in stock keeps the running server", async () => { | |
| 141 | const ok = await deployPinned(app, admin(), input({ name: "keep" })); | |
| 142 | expect(ok.ok).toBe(true); | |
| 143 | calls.length = 0; | |
| 144 | stocked = []; | |
| 145 | const r = await updatePinned(app, admin(), "keep", { version: V2 }); | |
| 146 | expect(r.ok).toBe(false); | |
| 147 | expect(seen().some((s) => s.startsWith("DELETE"))).toBe(false); | |
| 148 | expect(getPinned(app.db, "keep")!.remote).not.toBe(""); | |
| 149 | stocked = [2, 5]; | |
| 150 | }); | |
| 151 | ||
| 152 | test("verify is a read of the fixed host with the bearer token, and refuses a bad one", async () => { | |
| 153 | const asked: { url: string; auth: string | null }[] = []; | |
| 154 | const good = await verify("hetzner", TOKEN, async (url, init) => { | |
| 155 | asked.push({ url, auth: new Headers(init?.headers).get("authorization") }); | |
| 156 | return new Response(JSON.stringify({ servers: [], volumes: [], meta: { pagination: { total_entries: 2 } } }), { status: 200 }); | |
| 157 | }); | |
| 158 | expect(good.ok).toBe(true); | |
| 159 | expect(asked.every((a) => a.url.startsWith("https://api.hetzner.cloud/v1/") && a.auth === `Bearer ${TOKEN}`)).toBe(true); | |
| 160 | const bad = await verify("hetzner", "nope", async () => new Response("{}", { status: 401 })); | |
| 161 | expect(bad).toEqual({ ok: false, error: "The provider did not accept that credential." }); | |
| 162 | }); | |
| 163 | }); |
new above
offline
Item 2: the provider/name split and the bare-name fallback have no test. Add one that fails if this line is reverted.
split("/",2)also silently drops anything after a second slash, so reject a value with more than one slash.