Public: anyone can read this; the crew can change it.
Cut-over: move an app's domain from the platform to the forge with a preview check, a receipt and one-step undo #13605
Check · Review · Land · Live done — Landed and live in production.
mason/forge:mason/648-cut-over-move-an-app-s-domain-from-the-p → main 8 commits fork 3 threads · 3 unresolved
24 files
changed +1057
−10
docs/MCP.md +1 −1
| @@ -60,7 +60,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`; | ||
| 60 | 60 | | `agents` | — | Agents you may see, as GET /api/v1/agents | 160 | |
| 61 | 61 | | `app_data_import` | — | Load a SQL dump into an app's database and report per-table counts and checksums; admins only | 339 | |
| 62 | 62 | | `app_deploy` | `redeploy`, `stop`, `pull`, `schedules`, `run_schedule`, `pause_schedule`, `resume_schedule`, `jobs`, `cancel_job`, `retry_job` | Redeploy or stop an env, pull, list and steer schedules and jobs | 408 | |
| 63 | | `app_domains` | — | App domains: list, add, check, keep, remove; dns_proof, dns_cut, dns_revert | 266 | | |
| 63 | | `app_domains` | — | App domains: list, add, check, keep, remove; dns_proof, dns_cut, dns_revert | 293 | | |
| 64 | 64 | | `app_env` | `list`, `set`, `unset`, `variable`, `secret` | An app's environment variables: list, set or unset by scope; a secret is write-only, a variable is shown | 474 | |
| 65 | 65 | | `app_members` | — | People a private app names, who may enter it and its previews | 297 | |
| 66 | 66 | | `app_notes` | `hide`, `ban`, `unban` | Notes from an app's forge button and banned senders; hide a note, ban or unban its sender | 306 | |
docs/features/README.md +1
| @@ -41,6 +41,7 @@ Read with the guide page [What a forge is](../guide-what-a-forge-is.md). | ||
| 41 | 41 | - [](front-milestones.md) |
| 42 | 42 | - [](migration-mode.md) |
| 43 | 43 | - [](data-move.md) |
| 44 | - [](cut-over.md) | |
| 44 | 45 | - [](now-pages.md) |
| 45 | 46 | - [](pixel.md) |
| 46 | 47 | - [](home-plans.md) |
docs/features/cut-over.md added +21
| @@ -0,0 +1,21 @@ | ||
| 1 | # Cutting a domain over (#648) | |
| 2 | ||
| 3 | Move an app's domain from the platform to the forge app, checked first, with a receipt, and undone in | |
| 4 | one step. It is the last line of the migration checklist (`docs/features/migration-mode.md`). | |
| 5 | ||
| 6 | ## The path | |
| 7 | 1. **Verify the domain** on the app (`docs/features/platform-app-move.md`) and tick every line of | |
| 8 | `MIGRATION.md`: the app must be at parity. | |
| 9 | 2. **Check** at `/<owner>/<name>/cut-over` (or `c` on the terminal screen). The same paths asked of the | |
| 10 | platform and of the forge app must answer with the same status codes | |
| 11 | (`src/apps/parity_probe.ts`). Check changes nothing. | |
| 12 | 3. **Cut over** (`o` in the terminal). The name is pointed at the app: a registrar edit when the | |
| 13 | repository holds the secret `DNS_API_TOKEN`, else the receipt names the one record to publish. The | |
| 14 | records the name carried are kept with the domain. The receipt says what changed and the | |
| 15 | certificate's state. The platform app keeps running, unrouted. | |
| 16 | 4. **Undo** (`u`) puts the kept records back and forgets the cut-over. With nothing kept a cut-over | |
| 17 | is refused ("no way back"): keep the old records first, or set `DNS_API_TOKEN`. | |
| 18 | ||
| 19 | Admins of the repository only, like every domain action. The terminal door is | |
| 20 | `src/tui/screens/cutover.ts`, a palette command while an administered repository is open. | |
| 21 | Events: `app.domain.cut_over`, `app.domain.cut_undone`. |
forge.json +2 −2
| @@ -5,8 +5,8 @@ | ||
| 5 | 5 | "lab--forge-trevato-apps.open-platform.sh" |
| 6 | 6 | ], |
| 7 | 7 | "app": { |
| 8 | "looks": ["/", "/docs", "/explore", "/board", "/notes", "/review", "/releases", "/apps", "/security", "/system", "/maintenance", "/talk", "/flow", "/resilience", "/boards?help", "/settings/crew", "/settings/crew?help", "/settings/security/controls", "/settings/grants", "/preview-admin/sample", "/preview-admin/sample/drop", "/preview-admin/sample/data-move", "/preview-admin/sample/pulls/3", "/preview-admin/sample/next?pick", "/preview-admin/sample/bets", "/preview-admin/sample/waves", "/preview-admin/sample/space", "/looks/missing", "/looks/failed"], | |
| 9 | "looksAsOwner": ["/", "/board", "/flow", "/boards?help", "/settings/crew", "/settings/crew?help", "/settings/security/controls", "/settings/grants", "/talk", "/system", "/maintenance", "/resilience", "/preview-admin/sample", "/preview-admin/sample/drop", "/preview-admin/sample/data-move", "/preview-admin/sample/pulls/3", "/preview-admin/sample/next?pick", "/preview-admin/sample/bets", "/preview-admin/sample/waves", "/preview-admin/sample/space"], | |
| 8 | "looks": ["/", "/docs", "/explore", "/board", "/notes", "/review", "/releases", "/apps", "/security", "/system", "/maintenance", "/talk", "/flow", "/resilience", "/boards?help", "/settings/crew", "/settings/crew?help", "/settings/security/controls", "/settings/grants", "/preview-admin/sample", "/preview-admin/sample/drop", "/preview-admin/sample/data-move", "/preview-admin/sample/cut-over", "/preview-admin/sample/pulls/3", "/preview-admin/sample/next?pick", "/preview-admin/sample/bets", "/preview-admin/sample/waves", "/preview-admin/sample/space", "/looks/missing", "/looks/failed"], | |
| 9 | "looksAsOwner": ["/", "/board", "/flow", "/boards?help", "/settings/crew", "/settings/crew?help", "/settings/security/controls", "/settings/grants", "/talk", "/system", "/maintenance", "/resilience", "/preview-admin/sample", "/preview-admin/sample/drop", "/preview-admin/sample/data-move", "/preview-admin/sample/cut-over", "/preview-admin/sample/pulls/3", "/preview-admin/sample/next?pick", "/preview-admin/sample/bets", "/preview-admin/sample/waves", "/preview-admin/sample/space"], | |
| 10 | 10 | "run": "bun run src/main.ts", |
| 11 | 11 | "install": "", |
| 12 | 12 | "health": "/healthz", |
src/actions/cutover.ts added +187
| @@ -0,0 +1,187 @@ | ||
| 1 | /** | |
| 2 | * Cut over (#648): move an app's domain from the platform to the forge app, checked first and | |
| 3 | * undoable. In order: the app is at parity (`MIGRATION.md`), the domain is one the forge verified, | |
| 4 | * and the preview check passes: the same paths asked of the platform (the name as it resolves | |
| 5 | * today) and of the forge app answer with the same status codes (`apps/parity_probe.ts`). Without | |
| 6 | * `apply` that is all it does and it shows the list. With it the name is pointed at the app | |
| 7 | * (a registrar edit when the repository holds `DNS_API_TOKEN`, else the owner publishes the one | |
| 8 | * record the receipt names), the records it carried are kept with the domain, and the receipt | |
| 9 | * says what changed. The platform app is not touched: it keeps running, unrouted. Undo puts the | |
| 10 | * kept records back and forgets the cut-over. Admin of the repository, like every domain action. | |
| 11 | */ | |
| 12 | ||
| 13 | import type { App } from "../app.ts"; | |
| 14 | import { certificateSaid, probeCertificate } from "../apps/certificate.ts"; | |
| 15 | import type { DnsProvider } from "../apps/dns_provider.ts"; | |
| 16 | import { compareStatuses, pathsFrom, type PathCheck } from "../apps/parity_probe.ts"; | |
| 17 | import { readProgress } from "../apps/migration_mode.ts"; | |
| 18 | import { appsRuntime } from "../apps/runtime.ts"; | |
| 19 | import { getAppByRepo } from "../core/apps.ts"; | |
| 20 | import { getDomain, normalizeHost, setCutOver, setOldRecords, type OldRecord } from "../core/domains.ts"; | |
| 21 | import type { Repo } from "../core/repos.ts"; | |
| 22 | import type { User } from "../core/users.ts"; | |
| 23 | import { repoDir } from "../git/repos.ts"; | |
| 24 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 25 | import { requireRepoAdmin } from "./access.ts"; | |
| 26 | import { editAppDomainDns, recordsInWords, type DnsEditError, type DnsLost } from "./domain_dns.ts"; | |
| 27 | ||
| 28 | export type CutOverError = | |
| 29 | | "not_found" | |
| 30 | | "no_runtime" | |
| 31 | | "no_such_domain" | |
| 32 | | "not_verified" | |
| 33 | | "not_at_parity" | |
| 34 | | "not_cut_over" | |
| 35 | | "already_cut_over" | |
| 36 | | "no_way_back" | |
| 37 | | "dns_failed"; | |
| 38 | ||
| 39 | /** What a cut-over's check and, when it applied, its receipt say. */ | |
| 40 | export interface CutOver { | |
| 41 | readonly host: string; | |
| 42 | readonly checks: readonly PathCheck[]; | |
| 43 | /** Every path answered the same on both sides. */ | |
| 44 | readonly passed: boolean; | |
| 45 | readonly applied: boolean; | |
| 46 | /** What changed, one sentence each; empty until applied. */ | |
| 47 | readonly receipt: readonly string[]; | |
| 48 | /** The records the name carried, kept as the way back. */ | |
| 49 | readonly oldRecords: readonly OldRecord[]; | |
| 50 | } | |
| 51 | ||
| 52 | export interface CutOverDeps { | |
| 53 | /** Tests hand in the registrar; otherwise the repository's own `DNS_API_TOKEN`. */ | |
| 54 | readonly provider?: DnsProvider | undefined; | |
| 55 | } | |
| 56 | ||
| 57 | const MESSAGES: Readonly<Record<CutOverError, string>> = { | |
| 58 | not_found: "no such app or repository (owner/name)", | |
| 59 | no_runtime: "Nothing is serving apps on this forge.", | |
| 60 | no_such_domain: "No domain by that name.", | |
| 61 | not_verified: "Check the domain until it is verified before cutting it over.", | |
| 62 | not_at_parity: "The app is not at parity yet: every line of MIGRATION.md must be checked.", | |
| 63 | not_cut_over: "This domain has not been cut over.", | |
| 64 | already_cut_over: "This domain is already cut over: undo it first to run it again.", | |
| 65 | no_way_back: | |
| 66 | "Nothing is kept of how the name routes today, so a cut-over could not be undone. Keep the old records first (the domain's `keep`), or set the secret DNS_API_TOKEN so they are read from the registrar.", | |
| 67 | dns_failed: "The registrar did not take the change.", | |
| 68 | }; | |
| 69 | ||
| 70 | export const cutOverMessage = (error: CutOverError): string => MESSAGES[error]; | |
| 71 | ||
| 72 | function gate(app: App, actor: User | undefined, repo: Repo, host: string) { | |
| 73 | const admin = requireRepoAdmin(app, actor, repo); | |
| 74 | if (!admin.ok) return admin; | |
| 75 | const record = getAppByRepo(app.db, repo.id); | |
| 76 | if (!record) return err("not_found" as const); | |
| 77 | const runtime = appsRuntime(app); | |
| 78 | if (runtime === undefined) return err("no_runtime" as const); | |
| 79 | const domain = getDomain(app.db, normalizeHost(host)); | |
| 80 | if (domain === undefined || domain.appId !== record.id) return err("no_such_domain" as const); | |
| 81 | return ok({ admin: admin.value, record, runtime, domain }); | |
| 82 | } | |
| 83 | ||
| 84 | const asOld = (r: { type: string; name: string; value: string; ttl?: number | undefined }): OldRecord => | |
| 85 | r.ttl === undefined ? { type: r.type, name: r.name, value: r.value } : { type: r.type, name: r.name, value: r.value, ttl: r.ttl }; | |
| 86 | ||
| 87 | /** Whether the registrar would be asked: the repository holds a token, or a test's provider. */ | |
| 88 | function dnsFailure(error: DnsEditError | DnsLost): CutOverError { | |
| 89 | return error === "no_credential" ? "no_way_back" : "dns_failed"; | |
| 90 | } | |
| 91 | ||
| 92 | /** The check, and with `apply` the move. */ | |
| 93 | export async function cutOver( | |
| 94 | app: App, | |
| 95 | actor: User | undefined, | |
| 96 | repo: Repo, | |
| 97 | host: string, | |
| 98 | apply: boolean, | |
| 99 | deps: CutOverDeps = {}, | |
| 100 | ): Promise<Result<CutOver, CutOverError>> { | |
| 101 | const g = gate(app, actor, repo, host); | |
| 102 | if (!g.ok) return g; | |
| 103 | const { admin, record, runtime, domain } = g.value; | |
| 104 | if (domain.verifiedAt === null) return err("not_verified"); | |
| 105 | if (apply && domain.cutOverAt !== null) return err("already_cut_over"); | |
| 106 | const progress = await readProgress(repoDir(app.reposRoot, repo.ownerName, repo.name), repo.defaultBranch); | |
| 107 | if (!progress.atParity) return err("not_at_parity"); | |
| 108 | const checks = await compareStatuses( | |
| 109 | pathsFrom(progress.items.map((i) => i.text)), | |
| 110 | `https://${domain.host}`, | |
| 111 | runtime.hostUrlFor(record, domain.env), | |
| 112 | runtime.options.probe, | |
| 113 | ); | |
| 114 | const passed = checks.every((c) => c.same); | |
| 115 | const shown: CutOver = { host: domain.host, checks, passed, applied: false, receipt: [], oldRecords: domain.oldRecords }; | |
| 116 | if (!apply || !passed) return ok(shown); | |
| 117 | ||
| 118 | const target = runtime.hostFor(record.slug, domain.env); | |
| 119 | let kept = domain.oldRecords; | |
| 120 | let how: string; | |
| 121 | const cut = await editAppDomainDns(app, admin, repo, domain.host, "cut", undefined, deps.provider); | |
| 122 | if (cut.ok) { | |
| 123 | // The registrar has changed: from here on nothing returns an error, whatever it said back is | |
| 124 | // saved. | |
| 125 | if (cut.value.removed.length > 0) kept = cut.value.removed.map(asOld); | |
| 126 | how = `${domain.host} now points at ${target} (a CNAME set at the registrar, replacing ${recordsInWords(cut.value.removed) || "nothing"}).`; | |
| 127 | } else if (cut.error === "no_credential" && kept.length > 0) { | |
| 128 | how = `Publish a CNAME from ${domain.host} to ${target} where the name's DNS is kept; it replaces ${kept.map((r) => `${r.type} ${r.value}`).join("; ")}.`; | |
| 129 | } else { | |
| 130 | return err(dnsFailure(cut.error)); | |
| 131 | } | |
| 132 | setOldRecords(app.db, domain.host, kept); | |
| 133 | setCutOver(app.db, domain.host, new Date().toISOString()); | |
| 134 | const certificate = certificateSaid( | |
| 135 | await (runtime.options.certificate ?? ((h: string) => probeCertificate(h)))(domain.host), | |
| 136 | new Date(), | |
| 137 | ); | |
| 138 | const receipt = [ | |
| 139 | how, | |
| 140 | certificate, | |
| 141 | "The platform app is left running, unrouted: nothing was stopped or deleted there.", | |
| 142 | kept.length > 0 | |
| 143 | ? `Undo puts back ${kept.map((r) => `${r.type} ${r.value}`).join("; ")}.` | |
| 144 | : "The name carried no address record, so undo has nothing to put back: it only forgets the cut-over.", | |
| 145 | ]; | |
| 146 | app.bus.append({ | |
| 147 | kind: "app.domain.cut_over", | |
| 148 | repoId: repo.id, | |
| 149 | actorId: admin.id, | |
| 150 | payload: { host: domain.host, slug: record.slug, paths: checks.length }, | |
| 151 | }); | |
| 152 | return ok({ ...shown, applied: true, receipt, oldRecords: kept }); | |
| 153 | } | |
| 154 | ||
| 155 | /** Put the kept records back and forget the cut-over: one step. */ | |
| 156 | export async function undoCutOver( | |
| 157 | app: App, | |
| 158 | actor: User | undefined, | |
| 159 | repo: Repo, | |
| 160 | host: string, | |
| 161 | deps: CutOverDeps = {}, | |
| 162 | ): Promise<Result<{ host: string; says: string; restored: readonly OldRecord[] }, CutOverError>> { | |
| 163 | const g = gate(app, actor, repo, host); | |
| 164 | if (!g.ok) return g; | |
| 165 | const { admin, record, domain } = g.value; | |
| 166 | if (domain.cutOverAt === null) return err("not_cut_over"); | |
| 167 | let by = | |
| 168 | domain.oldRecords.length === 0 | |
| 169 | ? `${domain.host} carried no address record before the cut-over: remove its CNAME where the name's DNS is kept.` | |
| 170 | : `Publish ${domain.oldRecords.map((r) => `${r.type} ${r.value}`).join("; ")} at ${domain.host} to send traffic back to the platform.`; | |
| 171 | const wholeSet = domain.oldRecords.length > 0 && domain.oldRecords.every((r) => r.type === "A" || r.type === "AAAA" || r.type === "CNAME"); | |
| 172 | if (wholeSet && (deps.provider !== undefined || domain.verifiedAt !== null)) { | |
| 173 | const back = await editAppDomainDns(app, admin, repo, domain.host, "revert", domain.oldRecords, deps.provider); | |
| 174 | if (back.ok) by = back.value.says; | |
| 175 | else if (back.error !== "no_credential") return err(dnsFailure(back.error)); | |
| 176 | } | |
| 177 | const restored = domain.oldRecords; | |
| 178 | setOldRecords(app.db, domain.host, []); | |
| 179 | setCutOver(app.db, domain.host, null); | |
| 180 | app.bus.append({ | |
| 181 | kind: "app.domain.cut_undone", | |
| 182 | repoId: repo.id, | |
| 183 | actorId: admin.id, | |
| 184 | payload: { host: domain.host, slug: record.slug, restored: restored.length }, | |
| 185 | }); | |
| 186 | return ok({ host: domain.host, says: by, restored }); | |
| 187 | } |
src/actions/domains.ts +3
| @@ -39,6 +39,8 @@ export interface AppDomainView { | ||
| 39 | 39 | readonly records: DnsRecord[]; |
| 40 | 40 | /** What the name carried before the cut-over: put these back to revert. */ |
| 41 | 41 | readonly oldRecords: readonly OldRecord[]; |
| 42 | /** The name was moved to the app by a cut-over, and not undone since. */ | |
| 43 | readonly cutOver: boolean; | |
| 42 | 44 | } |
| 43 | 45 | |
| 44 | 46 | export type DomainError = "not_found" | "no_runtime"; |
| @@ -91,6 +93,7 @@ function view( | ||
| 91 | 93 | checkedAt: domain.checkedAt, |
| 92 | 94 | said: domain.said, |
| 93 | 95 | oldRecords: domain.oldRecords, |
| 96 | cutOver: domain.cutOverAt !== null, | |
| 94 | 97 | records: recordsFor( |
| 95 | 98 | domain.host, |
| 96 | 99 | domain.token, |
src/apps/parity_probe.ts added +67
| @@ -0,0 +1,67 @@ | ||
| 1 | /** | |
| 2 | * The preview check of a cut-over (#648): the same paths asked of the platform (the name as it | |
| 3 | * resolves today) and of the forge app (its own hostname), and the status codes compared. The | |
| 4 | * paths are `/` and the GET routes the crew listed in `MIGRATION.md`. A redirect is not followed: | |
| 5 | * the status the visitor would see first is the one compared. Plain data in, plain data out; the | |
| 6 | * fetch is handed in, so the forge's outbound rules (`kernel/outbound.ts`) hold and a test needs | |
| 7 | * no network. | |
| 8 | */ | |
| 9 | ||
| 10 | import { outboundFetch } from "../kernel/outbound.ts"; | |
| 11 | ||
| 12 | /** How many paths a check asks, `/` included. */ | |
| 13 | export const MAX_PATHS = 8; | |
| 14 | const TIMEOUT_MS = 5_000; | |
| 15 | ||
| 16 | export type Probe = (url: string) => Promise<number | null>; | |
| 17 | ||
| 18 | /** One path as the check shows it: `null` is a side that did not answer. */ | |
| 19 | export interface PathCheck { | |
| 20 | readonly path: string; | |
| 21 | readonly platform: number | null; | |
| 22 | readonly forge: number | null; | |
| 23 | readonly same: boolean; | |
| 24 | } | |
| 25 | ||
| 26 | /** | |
| 27 | * `/` first, then each checklist line that names a path to GET: `GET /pricing`, `/about`, | |
| 28 | * `` `/docs` ``. A line for another method, a path with a query or one with a parameter is left | |
| 29 | * out: a check must be a request that changes nothing and means the same on both sides. | |
| 30 | */ | |
| 31 | export function pathsFrom(lines: readonly string[]): string[] { | |
| 32 | const out = ["/"]; | |
| 33 | for (const line of lines) { | |
| 34 | const found = /^[`*\s]*(?:GET\s+)?(\/[A-Za-z0-9._~\/-]*)[`*\s]*(?:\s|$)/i.exec(line); | |
| 35 | if (found === null || /^[`*\s]*(?:POST|PUT|PATCH|DELETE)\b/i.test(line)) continue; | |
| 36 | const path = found[1]!; | |
| 37 | if (!out.includes(path)) out.push(path); | |
| 38 | if (out.length >= MAX_PATHS) break; | |
| 39 | } | |
| 40 | return out; | |
| 41 | } | |
| 42 | ||
| 43 | /** The status of one request, or null when nothing answered in time. */ | |
| 44 | export const statusOf: Probe = async (url) => { | |
| 45 | try { | |
| 46 | const response = await outboundFetch(url, { redirect: "manual", signal: AbortSignal.timeout(TIMEOUT_MS) }); | |
| 47 | void response.body?.cancel(); | |
| 48 | return response.status; | |
| 49 | } catch { | |
| 50 | return null; | |
| 51 | } | |
| 52 | }; | |
| 53 | ||
| 54 | /** Ask both sides every path, one pair at a time per path, and say where they differ. */ | |
| 55 | export async function compareStatuses( | |
| 56 | paths: readonly string[], | |
| 57 | platformBase: string, | |
| 58 | forgeBase: string, | |
| 59 | probe: Probe = statusOf, | |
| 60 | ): Promise<PathCheck[]> { | |
| 61 | return Promise.all( | |
| 62 | paths.map(async (path) => { | |
| 63 | const [platform, forge] = await Promise.all([probe(`${platformBase}${path}`), probe(`${forgeBase}${path}`)]); | |
| 64 | return { path, platform, forge, same: platform !== null && platform === forge }; | |
| 65 | }), | |
| 66 | ); | |
| 67 | } |
src/apps/runtime.ts +12
| @@ -197,6 +197,11 @@ export interface RuntimeOptions { | ||
| 197 | 197 | * a TLS handshake unless a test hands in its own. |
| 198 | 198 | */ |
| 199 | 199 | readonly certificate?: CertificateProbe | undefined; |
| 200 | /** | |
| 201 | * What the cut-over's preview check asks of each side (`apps/parity_probe.ts`): a status per | |
| 202 | * URL, or null. The vetted outbound fetch unless a test hands in its own. | |
| 203 | */ | |
| 204 | readonly probe?: ((url: string) => Promise<number | null>) | undefined; | |
| 200 | 205 | /** |
| 201 | 206 | * Whether a cloud body can take a burst (`spawn/placement.ts`). Without |
| 202 | 207 | * one every environment is placed on owned metal and a burst queues. |
| @@ -573,6 +578,13 @@ export class AppsRuntime { | ||
| 573 | 578 | : primaryDomain(this.app.db, record.id)?.host; |
| 574 | 579 | if (host !== undefined) return `${this.options.scheme}://${host}`; |
| 575 | 580 | } |
| 581 | return this.hostUrlFor(record, env); | |
| 582 | } | |
| 583 | ||
| 584 | /** | |
| 585 | * `<slug>.<domain>`'s URL, whatever domain the app has taken: where the forge itself serves it. | |
| 586 | */ | |
| 587 | hostUrlFor(record: AppRecord, env: EnvName): string { | |
| 576 | 588 | const port = |
| 577 | 589 | this.options.publicPort === undefined || |
| 578 | 590 | (this.options.scheme === "http" && this.options.publicPort === 80) || |
src/core/domains.ts +13 −1
| @@ -26,6 +26,8 @@ export interface AppDomain { | ||
| 26 | 26 | readonly said: string; |
| 27 | 27 | /** The records the name carried before the cut-over: the way back. */ |
| 28 | 28 | readonly oldRecords: readonly OldRecord[]; |
| 29 | /** When a cut-over moved the name to the app; null until one did, and again after undo. */ | |
| 30 | readonly cutOverAt: string | null; | |
| 29 | 31 | } |
| 30 | 32 | |
| 31 | 33 | /** One DNS record as the old host served it, written down before the cut. */ |
| @@ -48,6 +50,7 @@ interface DomainRow { | ||
| 48 | 50 | checked_at: string | null; |
| 49 | 51 | said: string; |
| 50 | 52 | old_records: string; |
| 53 | cut_over_at: string | null; | |
| 51 | 54 | } |
| 52 | 55 | |
| 53 | 56 | function parseOldRecords(text: string): OldRecord[] { |
| @@ -86,7 +89,10 @@ export function parseRecordsInput(input: unknown): Result<OldRecord[], "invalid_ | ||
| 86 | 89 | return ok(out); |
| 87 | 90 | } |
| 88 | 91 | |
| 89 | /** `A app.example.com 203.0.113.7 300; CNAME www.example.com host.example.net`: the terminal's way to type records. */ | |
| 92 | /** | |
| 93 | * `A app.example.com 203.0.113.7 300; CNAME www.example.com host.example.net`: the terminal's way | |
| 94 | * to type records. | |
| 95 | */ | |
| 90 | 96 | export function recordsFromLine(line: string): unknown[] { |
| 91 | 97 | return line |
| 92 | 98 | .split(";") |
| @@ -104,6 +110,11 @@ export function setOldRecords(db: Database, host: string, records: readonly OldR | ||
| 104 | 110 | ); |
| 105 | 111 | } |
| 106 | 112 | |
| 113 | /** Mark the name cut over (`at`) or not (null). False when no such host. */ | |
| 114 | export function setCutOver(db: Database, host: string, at: string | null): boolean { | |
| 115 | return db.query("UPDATE app_domain SET cut_over_at = ?2 WHERE host = ?1").run(normalizeHost(host), at).changes > 0; | |
| 116 | } | |
| 117 | ||
| 107 | 118 | const toDomain = (r: DomainRow): AppDomain => ({ |
| 108 | 119 | host: r.host, |
| 109 | 120 | appId: r.app_id, |
| @@ -115,6 +126,7 @@ const toDomain = (r: DomainRow): AppDomain => ({ | ||
| 115 | 126 | checkedAt: r.checked_at, |
| 116 | 127 | said: r.said, |
| 117 | 128 | oldRecords: parseOldRecords(r.old_records), |
| 129 | cutOverAt: r.cut_over_at, | |
| 118 | 130 | }); |
| 119 | 131 | |
| 120 | 132 | const now = (): string => new Date().toISOString(); |
src/core/migration-pins/20261116100000-domain-cut-over.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 4c47fd99efd3523308feb851e6ef2b03c7bb51438f5082259c6a254233af376c |
src/core/migrations/20261116100000-domain-cut-over.ts added +6
| @@ -0,0 +1,6 @@ | ||
| 1 | // `app_domain.cut_over_at` (#648): when a cut-over moved the name to the forge app, null while it | |
| 2 | // has not. The kept old records alone cannot say so: they are also written down before any cut. | |
| 3 | // Additive: one nullable column. | |
| 4 | export default ` | |
| 5 | ALTER TABLE app_domain ADD COLUMN cut_over_at TEXT; | |
| 6 | `; |
src/http/mcp/tools/app_domains.ts +12 −3
| @@ -5,6 +5,7 @@ import { | ||
| 5 | 5 | listAppDomains, |
| 6 | 6 | removeAppDomain, |
| 7 | 7 | } from "../../../actions/domains.ts"; |
| 8 | import { cutOver, cutOverMessage, undoCutOver } from "../../../actions/cutover.ts"; | |
| 8 | 9 | import { |
| 9 | 10 | dnsRefusal, |
| 10 | 11 | DNS_STEPS, |
| @@ -21,7 +22,7 @@ import { type Answer, good, bad, type Tool, REPO_ARG, repoArg, isAnswer, str } f | ||
| 21 | 22 | |
| 22 | 23 | export const tool: Tool = { |
| 23 | 24 | name: "app_domains", |
| 24 | doc: "`{ repo, action, host?, records? }`: `list`, `add`, `check` (looks the DNS proof up now), `keep` (`records`: the old DNS records `[{type,name,value,ttl?}]` written down before a cut-over, shown back as `oldRecords` on `list`; `add` takes them too) or `remove` an app's own domains, with the records to publish, as `…/app/domains` answers; or edit its DNS with `dns_proof`, `dns_cut` (answers the records it replaced) or `dns_revert` (`records` `[{type,value,ttl?}]`; verified names only), using the repo's secret DNS_API_TOKEN; an admin of the repository with an admin-scope token", | |
| 25 | doc: "`{ repo, action, host?, records? }`: `list`, `add`, `check` (looks the DNS proof up now), `keep` (`records`: the old DNS records `[{type,name,value,ttl?}]` written down before a cut-over, shown back as `oldRecords` on `list`; `add` takes them too) or `remove` an app's own domains, with the records to publish, as `…/app/domains` answers; `cut_over` (`apply:true` moves the name to the app once the preview check passes; without it only the check's status list) and `undo_cut_over` (puts the kept records back); or edit its DNS with `dns_proof`, `dns_cut` (answers the records it replaced) or `dns_revert` (`records` `[{type,value,ttl?}]`; verified names only), using the repo's secret DNS_API_TOKEN; an admin of the repository with an admin-scope token", | |
| 25 | 26 | description: "App domains: list, add, check, keep, remove; dns_proof, dns_cut, dns_revert.", |
| 26 | 27 | inputSchema: { |
| 27 | 28 | type: "object", |
| @@ -30,6 +31,7 @@ export const tool: Tool = { | ||
| 30 | 31 | action: { type: "string" }, |
| 31 | 32 | host: { type: "string" }, |
| 32 | 33 | records: { type: "array", maxItems: 50 }, |
| 34 | apply: { type: "boolean" }, | |
| 33 | 35 | }, |
| 34 | 36 | }, |
| 35 | 37 | writes: true, |
| @@ -39,9 +41,9 @@ export const tool: Tool = { | ||
| 39 | 41 | if (isAnswer(repo)) return repo; |
| 40 | 42 | const action = args["action"]; |
| 41 | 43 | const dnsStep = DNS_STEPS.find((step) => `dns_${step}` === action); |
| 42 | const plain = ["list", "add", "check", "keep", "remove"].includes(String(action)); | |
| 44 | const plain = ["list", "add", "check", "keep", "remove", "cut_over", "undo_cut_over"].includes(String(action)); | |
| 43 | 45 | if (dnsStep === undefined && !plain) |
| 44 | return bad("invalid", "action is list, add, check, keep, remove, dns_proof, dns_cut or dns_revert"); | |
| 46 | return bad("invalid", "action is list, add, check, keep, remove, cut_over, undo_cut_over, dns_proof, dns_cut or dns_revert"); | |
| 45 | 47 | const host = str(args["host"]); |
| 46 | 48 | if (dnsStep !== undefined) { |
| 47 | 49 | if (host === "") return bad("invalid", "host is the domain name"); |
| @@ -50,6 +52,13 @@ export const tool: Tool = { | ||
| 50 | 52 | ? good({ says: edited.value.says, removed: edited.value.removed, put: edited.value.put }) |
| 51 | 53 | : bad(typeof edited.error === "string" ? edited.error : "left_half", dnsRefusal(edited.error)); |
| 52 | 54 | } |
| 55 | if ((action === "cut_over" || action === "undo_cut_over") && host !== "") { | |
| 56 | const moved = | |
| 57 | action === "cut_over" | |
| 58 | ? await cutOver(ctx.app, user, repo, host, args["apply"] === true) | |
| 59 | : await undoCutOver(ctx.app, user, repo, host); | |
| 60 | return moved.ok ? good(moved.value) : bad(moved.error, cutOverMessage(moved.error)); | |
| 61 | } | |
| 53 | 62 | if (action !== "list" && host === "") return bad("invalid", "host is the domain name"); |
| 54 | 63 | const refused = (error: string, fallback: string): Answer => |
| 55 | 64 | error === "not_found" |
src/http/server.ts +3
| @@ -274,6 +274,7 @@ import { adapterPull } from "../web/studio/adapter.ts"; | ||
| 274 | 274 | import { jobsPage, steerJobPage } from "../web/studio/jobs.ts"; |
| 275 | 275 | import { steerSchedulePage } from "../web/studio/schedules.ts"; |
| 276 | 276 | import { dataMoveAct, dataMovePage } from "../web/studio/data_move.ts"; |
| 277 | import { cutOverAct, cutOverPage } from "../web/studio/cut_over.ts"; | |
| 277 | 278 | import { dropPageGet, removeDropPage, uploadDropPage } from "../web/studio/drop.ts"; |
| 278 | 279 | import { noteModerate } from "../web/studio/notes.ts"; |
| 279 | 280 | import { tellPage } from "../web/studio/tell.ts"; |
| @@ -1560,6 +1561,8 @@ export function buildRouter(): Router<Handler> { | ||
| 1560 | 1561 | router.add("POST", "/:owner/:name/app/schedules/:schedule/:action", steerSchedulePage); |
| 1561 | 1562 | router.add("GET", "/:owner/:name/data-move", dataMovePage); |
| 1562 | 1563 | router.add("POST", "/:owner/:name/data-move", dataMoveAct); |
| 1564 | router.add("GET", "/:owner/:name/cut-over", cutOverPage); | |
| 1565 | router.add("POST", "/:owner/:name/cut-over", cutOverAct); | |
| 1563 | 1566 | router.add("GET", "/:owner/:name/drop", dropPageGet); |
| 1564 | 1567 | router.add("POST", "/:owner/:name/drop", uploadDropPage); |
| 1565 | 1568 | router.add("POST", "/:owner/:name/drop/remove", removeDropPage); |
src/origins/inventory.ts +1 −1
| @@ -128,7 +128,7 @@ export function stateOf( | ||
| 128 | 128 | if (repo === undefined || !canAdmin(db, repo, user)) continue; |
| 129 | 129 | const local = `/${repo.ownerName}/${repo.name}`; |
| 130 | 130 | const app = getAppByRepo(db, repo.id); |
| 131 | if (app !== undefined && listDomains(db, app.id).some((d) => d.verifiedAt !== null && d.oldRecords.length > 0)) | |
| 131 | if (app !== undefined && listDomains(db, app.id).some((d) => d.verifiedAt !== null && d.cutOverAt !== null)) | |
| 132 | 132 | return { state: "cut_over", local }; |
| 133 | 133 | const mirror = getMirrorTarget(db, repo.id); |
| 134 | 134 | if (mirror !== undefined && mirror.pushedAt !== "" && mirror.lastError === "") return { state: "at_parity", local }; |
src/spawn/preview-looks.ts +5
| @@ -40,6 +40,10 @@ export const PREVIEW_APP_PAGE = `/${PREVIEW_ADMIN}/${PREVIEW_APP}`; | ||
| 40 | 40 | export const PREVIEW_DROP_PAGE = `${PREVIEW_APP_PAGE}/drop`; |
| 41 | 41 | /** The seeded app's data move (#647): a Postgres dump from its drop, imported, with its receipt. */ |
| 42 | 42 | export const PREVIEW_DATA_MOVE_PAGE = `${PREVIEW_APP_PAGE}/data-move`; |
| 43 | /** The seeded app's cut-over (#648): one verified domain, still on the platform. */ | |
| 44 | export const PREVIEW_CUT_OVER_PAGE = `${PREVIEW_APP_PAGE}/cut-over`; | |
| 45 | /** The domain the sample app carries for it. */ | |
| 46 | export const PREVIEW_CUT_OVER_HOST = "www.hello-sample.example"; | |
| 43 | 47 | |
| 44 | 48 | /** |
| 45 | 49 | * The recently moved repository (#10195): made by the admin as `moved`, then |
| @@ -232,6 +236,7 @@ export const PREVIEW_OWNER_LOOKS: readonly OwnerLook[] = [ | ||
| 232 | 236 | PREVIEW_APP_PAGE, |
| 233 | 237 | PREVIEW_DROP_PAGE, |
| 234 | 238 | PREVIEW_DATA_MOVE_PAGE, |
| 239 | PREVIEW_CUT_OVER_PAGE, | |
| 235 | 240 | PREVIEW_MOVED_PAGE, |
| 236 | 241 | PREVIEW_TEMPLATE_PAGE, |
| 237 | 242 | PREVIEW_MOVE_LOOK, |
src/spawn/preview-seed.ts +11
| @@ -17,6 +17,8 @@ | ||
| 17 | 17 | import { putStream } from "../drop/store.ts"; |
| 18 | 18 | import { moveData } from "../actions/migrate_data.ts"; |
| 19 | 19 | import { setMigration } from "../apps/migration_mode.ts"; |
| 20 | import { addDomain, recordCheck } from "../core/domains.ts"; | |
| 21 | import { cutOverPage } from "../web/studio/cut_over.ts"; | |
| 20 | 22 | import { dataMovePage } from "../web/studio/data_move.ts"; |
| 21 | 23 | import { dropPageGet } from "../web/studio/drop.ts"; |
| 22 | 24 | import { existsSync, mkdirSync, writeFileSync } from "node:fs"; |
| @@ -68,6 +70,8 @@ import { | ||
| 68 | 70 | PREVIEW_APP, |
| 69 | 71 | PREVIEW_APP_PAGE, |
| 70 | 72 | PREVIEW_DROP_PAGE, |
| 73 | PREVIEW_CUT_OVER_HOST, | |
| 74 | PREVIEW_CUT_OVER_PAGE, | |
| 71 | 75 | PREVIEW_DATA_MOVE_PAGE, |
| 72 | 76 | PREVIEW_DISK_ALERT, |
| 73 | 77 | PREVIEW_FIXTURES, |
| @@ -995,6 +999,13 @@ async function seedApp(app: App, admin: User): Promise<Result<void, string>> { | ||
| 995 | 999 | const moveUrl = new URL(`https://preview.invalid${PREVIEW_DATA_MOVE_PAGE}`); |
| 996 | 1000 | const move = dataMovePage({ app, request: new Request(moveUrl.href), url: moveUrl, params: { owner: PREVIEW_ADMIN, name: PREVIEW_APP }, auth: { user: admin }, theme: undefined } as unknown as Ctx); |
| 997 | 1001 | if (move.status !== 200 || !(await move.text()).includes("parts")) return err(`${PREVIEW_DATA_MOVE_PAGE} does not show the sample receipt`); |
| 1002 | // Its cut-over (#648): a verified domain, not yet moved, so the page shows its row and button. | |
| 1003 | const domain = addDomain(app.db, { host: PREVIEW_CUT_OVER_HOST, appId: record.value.id, createdBy: admin.id }, { forgeHost: "preview.invalid" }); | |
| 1004 | if (!domain.ok) return err(`the sample app's domain: ${domain.error}`); | |
| 1005 | recordCheck(app.db, PREVIEW_CUT_OVER_HOST, { verified: true, said: "The proof record is published." }); | |
| 1006 | const cutUrl = new URL(`https://preview.invalid${PREVIEW_CUT_OVER_PAGE}`); | |
| 1007 | const cut = cutOverPage({ app, request: new Request(cutUrl.href), url: cutUrl, params: { owner: PREVIEW_ADMIN, name: PREVIEW_APP }, auth: { user: admin }, theme: undefined } as unknown as Ctx); | |
| 1008 | if (cut.status !== 200 || !(await cut.text()).includes(PREVIEW_CUT_OVER_HOST)) return err(`${PREVIEW_CUT_OVER_PAGE} does not show the sample domain`); | |
| 998 | 1009 | const dropUrl = new URL(`https://preview.invalid${PREVIEW_DROP_PAGE}`); |
| 999 | 1010 | const drop = dropPageGet({ app, request: new Request(dropUrl.href), url: dropUrl, params: { owner: PREVIEW_ADMIN, name: PREVIEW_APP }, auth: { user: admin }, theme: undefined } as unknown as Ctx); |
| 1000 | 1011 | return drop.status === 200 && (await drop.text()).includes("torque-spec.pdf") ? ok() : err(`${PREVIEW_DROP_PAGE} does not show the sample drop`); |
src/tui/screens/cutover.ts added +112
| @@ -0,0 +1,112 @@ | ||
| 1 | /** | |
No test covers this screen: the keys, the confirms, and the guest and non-admin refusal. Add one. |
||
| 2 | * Cut over, in the terminal (#648): the page's check and move (`web/studio/cut_over.ts`) from the | |
| 3 | * same actions (`actions/cutover.ts`), gated the same way: a repository's admins. `c` checks the | |
| 4 | * domain under the cursor against the platform, `o` cuts it over after a confirm, `u` undoes a | |
| 5 | * cut-over after a confirm. What the check found and the receipt show on the screen. | |
| 6 | */ | |
| 7 | ||
| 8 | import { cutOver, cutOverMessage, undoCutOver } from "../../actions/cutover.ts"; | |
| 9 | import { getAppByRepo } from "../../core/apps.ts"; | |
| 10 | import { listDomains, type AppDomain } from "../../core/domains.ts"; | |
| 11 | import { canAdmin, type Repo } from "../../core/repos.ts"; | |
| 12 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 13 | import { binding } from "../app/keys.ts"; | |
| 14 | import type { Command } from "../app/palette.ts"; | |
| 15 | import type { Session } from "../session.ts"; | |
| 16 | import { style } from "../term/style.ts"; | |
| 17 | import { truncate } from "../term/width.ts"; | |
| 18 | import { fill, len, split } from "../ui/layout.ts"; | |
| 19 | import { ListState, confirmScreen, drawList, later, type ListRow } from "./common.ts"; | |
| 20 | ||
| 21 | /** Cut over's gate: an admin of the repository. */ | |
| 22 | export const mayCutOver = (f: Session, repo: Repo): boolean => f.user !== undefined && canAdmin(f.db, repo, f.user); | |
| 23 | ||
| 24 | /** The repository's domains: none for anyone but an admin, none without an app. */ | |
| 25 | export function cutOverRows(f: Session, repo: Repo): AppDomain[] { | |
| 26 | if (!mayCutOver(f, repo)) return []; | |
| 27 | const record = getAppByRepo(f.db, repo.id); | |
| 28 | return record === undefined ? [] : listDomains(f.db, record.id); | |
| 29 | } | |
| 30 | ||
| 31 | export function cutOverScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | |
| 32 | const state = new ListState(); | |
| 33 | let said: string[] = []; | |
| 34 | const run = async (host: string, apply: boolean): Promise<void> => { | |
| 35 | const done = await cutOver(f.app, f.user, repo, host, apply); | |
| 36 | said = !done.ok | |
| 37 | ? [cutOverMessage(done.error)] | |
| 38 | : done.value.applied | |
| 39 | ? [...done.value.receipt] | |
| 40 | : [ | |
| 41 | done.value.passed ? "Every path answers the same on both sides." : "Some paths answer differently: nothing was changed.", | |
| 42 | ...done.value.checks.map((c) => `${c.same ? "same" : "differs"} ${c.path}`), | |
| 43 | ]; | |
| 44 | ctx.invalidate(); | |
| 45 | }; | |
| 46 | const screen: Screen = { | |
| 47 | title: `${repo.ownerName}/${repo.name} — Cut over`, | |
| 48 | keys: [binding(["j", "k"], "move cursor"), binding(["c"], "check against the platform"), binding(["o"], "cut over"), binding(["u"], "undo")], | |
| 49 | render(area, s) { | |
| 50 | const c = ctx.theme.c; | |
| 51 | const [head, list, out] = split(area, "v", [len(1), fill(1), len(Math.min(10, Math.max(1, said.length)))]); | |
| 52 | const intro = mayCutOver(f, repo) | |
| 53 | ? "c checks a domain against the platform, o moves it to this app, u puts the old records back." | |
| 54 | : "An admin of this repository cuts domains over."; | |
| 55 | s.text(head!.x, head!.y, truncate(intro, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); | |
| 56 | const rows: ListRow[] = cutOverRows(f, repo).map((d) => ({ | |
| 57 | title: d.host, | |
| 58 | note: d.verifiedAt === null ? "not verified yet" : d.cutOverAt !== null ? "cut over" : "verified", | |
| 59 | meta: d.oldRecords.length > 0 ? `${d.oldRecords.length} old records kept` : "", | |
| 60 | })); | |
| 61 | drawList(s, list!, c, state, rows); | |
| 62 | said.slice(0, out!.h).forEach((line, i) => s.text(out!.x, out!.y + i, truncate(line, out!.w), style(c.fg, c.bg), out!.x + out!.w)); | |
| 63 | }, | |
| 64 | key(e) { | |
| 65 | const all = cutOverRows(f, repo); | |
| 66 | if (state.key(e, all.length)) return true; | |
| 67 | if (e.ctrl || e.alt || (e.key !== "c" && e.key !== "o" && e.key !== "u")) return false; | |
| 68 | if (!mayCutOver(f, repo)) { | |
| 69 | ctx.toast("An admin of this repository cuts domains over.", "danger"); | |
| 70 | return true; | |
| 71 | } | |
| 72 | const at = all[state.index]; | |
| 73 | if (at === undefined) return true; | |
| 74 | if (e.key === "c") { | |
| 75 | void run(at.host, false); | |
| 76 | return true; | |
| 77 | } | |
| 78 | const undo = e.key === "u"; | |
| 79 | void later(ctx, () => | |
| 80 | confirmScreen(ctx, screen, { | |
| 81 | title: undo ? "Undo cut-over" : "Cut over", | |
| 82 | body: [undo ? `${at.host} goes back to the records it carried.` : `${at.host} is pointed at this app once the check passes. The platform app keeps running.`], | |
| 83 | actions: [{ label: "Cancel", variant: "ghost" }, { label: undo ? "Undo" : "Cut over" }], | |
| 84 | selected: 0, | |
| 85 | onChoose: (i) => { | |
| 86 | if (i !== 1) return; | |
| 87 | if (!undo) return void run(at.host, true); | |
| 88 | void undoCutOver(f.app, f.user, repo, at.host).then((done) => { | |
| 89 | said = [done.ok ? done.value.says : cutOverMessage(done.error)]; | |
| 90 | ctx.invalidate(); | |
| 91 | }); | |
| 92 | }, | |
| 93 | }), | |
| 94 | ); | |
| 95 | return true; | |
| 96 | }, | |
| 97 | }; | |
| 98 | return screen; | |
| 99 | } | |
| 100 | ||
| 101 | /** The palette's command while a repository the viewer administers is open. */ | |
| 102 | export function cutOverCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] { | |
| 103 | if (repo === undefined || !mayCutOver(f, repo)) return []; | |
| 104 | return [ | |
| 105 | { | |
| 106 | id: "cut-over", | |
| 107 | title: `${repo.ownerName}/${repo.name} — Cut over`, | |
| 108 | hint: "check a domain against the platform, move it here, undo in one step", | |
| 109 | run: () => ctx.push(cutOverScreen(f, ctx, repo)), | |
| 110 | }, | |
| 111 | ]; | |
| 112 | } |
src/tui/screens/workspace.ts +2
| @@ -185,6 +185,7 @@ import { variantsCommands } from "./variants.ts"; | ||
| 185 | 185 | import { autonomyCommands } from "./autonomy.ts"; |
| 186 | 186 | import { trafficCommands } from "./trafficview.ts"; |
| 187 | 187 | import { chaptersCommands } from "./chapters.ts"; |
| 188 | import { cutOverCommands } from "./cutover.ts"; | |
| 188 | 189 | import { outsideAgentsCommands } from "./outsideagents.ts"; |
| 189 | 190 | import { crewSwitchCommands } from "./crewswitch.ts"; |
| 190 | 191 | import { walletCapCommands } from "./wallet.ts"; |
| @@ -2205,6 +2206,7 @@ export function workspaceScreen( | ||
| 2205 | 2206 | ...recheckWindowCommands(f, ctx, repo, () => screen), |
| 2206 | 2207 | ...deskCommands(f, ctx, repo), |
| 2207 | 2208 | ...outsideAgentsCommands(f, ctx, repo), |
| 2209 | ...cutOverCommands(f, ctx, repo), | |
| 2208 | 2210 | ...crewSwitchCommands(f, ctx, repo), |
| 2209 | 2211 | ...walletCapCommands(f, ctx, repo), |
| 2210 | 2212 | ...templateCommands(f, ctx, repo), |
src/web/studio/cut_over.ts added +125
| @@ -0,0 +1,125 @@ | ||
| 1 | /** | |
| 2 | * Cut over, as a page (#648): `/:owner/:name/cut-over`, reached from the migration card at | |
| 3 | * parity. A domain at a time: **Check** asks the platform and the forge app the same paths and | |
| 4 | * lists the status codes side by side; when every pair is the same, **Cut over** moves the name | |
| 5 | * and the receipt says what changed; **Undo** puts the kept records back. Server-rendered, no | |
| 6 | * script; every button is a same-origin form POST, an admin's only. The words and the gate are | |
| 7 | * `actions/cutover.ts`'s, the same the MCP tool uses. | |
| 8 | */ | |
| 9 | ||
| 10 | import { cutOver, cutOverMessage, undoCutOver, type CutOver } from "../../actions/cutover.ts"; | |
| 11 | import { getAppByRepo } from "../../core/apps.ts"; | |
| 12 | import { listDomains } from "../../core/domains.ts"; | |
| 13 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; | |
| 14 | import type { Ctx } from "../../http/context.ts"; | |
| 15 | import { adminForm, loadAdminRepo } from "../admin_form.ts"; | |
| 16 | import { crumbsFor, notFoundPage, pageHead, repoBase, signInFirst } from "../chrome.ts"; | |
| 17 | import { field } from "../form.ts"; | |
| 18 | import { html, type Html } from "../html.ts"; | |
| 19 | import { flashTo, page } from "../layout.ts"; | |
| 20 | import { badge, btn } from "../ui.ts"; | |
| 21 | ||
| 22 | const status = (n: number | null): string => (n === null ? "no answer" : String(n)); | |
| 23 | ||
| 24 | /** | |
| 25 | * The status list: one row per path, the platform's code, the forge app's, and whether they match. | |
| 26 | */ | |
| 27 | export function checksTable(checks: CutOver["checks"]): Html { | |
| 28 | return html`<div class="table-scroll"> | |
| 29 | <table class="table" id="checks" data-dense> | |
| 30 | <caption class="sr-only">Status codes per path, on the platform and on the forge app</caption> | |
| 31 | <thead><tr><th scope="col">Path</th><th scope="col" class="num">Platform</th><th scope="col" class="num">Forge</th><th scope="col"></th></tr></thead> | |
| 32 | <tbody> | |
| 33 | ${checks.map( | |
| 34 | (c) => html`<tr> | |
| 35 | <td class="mono break">${c.path}</td> | |
| 36 | <td class="num">${status(c.platform)}</td> | |
| 37 | <td class="num">${status(c.forge)}</td> | |
| 38 | <td>${badge(c.same ? "same" : "differs", { tone: c.same ? "success" : "danger" })}</td> | |
| 39 | </tr>`, | |
| 40 | )} | |
| 41 | </tbody> | |
| 42 | </table> | |
| 43 | </div>`; | |
| 44 | } | |
| 45 | ||
| 46 | function shownCard(base: string, shown: CutOver): Html { | |
| 47 | return html`<section id="check"> | |
| 48 | <h2>${shown.applied ? "Receipt" : "Check"} · ${shown.host}</h2> | |
| 49 | ${checksTable(shown.checks)} | |
| 50 | ${shown.applied | |
| 51 | ? html`<ul class="list" id="receipt">${shown.receipt.map((line) => html`<li>${line}</li>`)}</ul>` | |
| 52 | : shown.passed | |
| 53 | ? html`<form method="post" action="${base}/cut-over"> | |
| 54 | <input type="hidden" name="host" value="${shown.host}" /> | |
| 55 | ${btn("Cut over", { name: "do", value: "cut", variant: "primary" })} | |
| 56 | </form>` | |
outdated
Principle 1: this repeats what the page sub-line and the button already say. Drop it. |
||
| 57 | : html`<p class="muted" id="blocked">The forge app answers differently on at least one path, so the name stays where it is. Fix the difference and check again.</p>`} | |
| 58 | </section>`; | |
| 59 | } | |
| 60 | ||
| 61 | function body(base: string, ctx: Ctx, repoName: string, shown: CutOver | undefined): Html { | |
| 62 | const repo = loadAdminRepo(ctx)!; | |
| 63 | const record = getAppByRepo(ctx.app.db, repo.id); | |
| 64 | const domains = record === undefined ? [] : listDomains(ctx.app.db, record.id).filter((d) => d.verifiedAt !== null); | |
| 65 | return html`${pageHead("Cut over", { sub: `Move ${repoName}'s domain from the platform to this app.` })} | |
| 66 | <section id="domains"> | |
| 67 | ${domains.length === 0 | |
| 68 | ? html`<p class="muted">No verified domain yet. Add one and check it in the <a href="${base}/settings/app">app's settings</a> first.</p>` | |
| 69 | : html`<ul class="list"> | |
| 70 | ${domains.map((d) => { | |
| 71 | const cut = d.cutOverAt !== null; | |
| 72 | return html`<li class="row"> | |
| 73 | <span class="mono break">${d.host}</span> | |
| 74 | ${badge(cut ? "cut over" : "on the platform", { tone: cut ? "success" : "default" })} | |
| 75 | <span class="spacer"></span> | |
| 76 | <form method="post" action="${base}/cut-over"> | |
| 77 | <input type="hidden" name="host" value="${d.host}" /> | |
| 78 | ${cut | |
| 79 | ? btn("Undo", { name: "do", value: "undo", variant: "outline" }) | |
| 80 | : btn("Check", { name: "do", value: "check", variant: "primary" })} | |
| 81 | </form> | |
| 82 | </li>`; | |
| 83 | })} | |
| 84 | </ul>`} | |
| 85 | </section> | |
| 86 | ${shown === undefined ? null : shownCard(base, shown)} | |
| 87 | <div class="row">${btn("Back to the checklist", { href: `${base}#app-migration`, variant: "outline" })}</div>`; | |
| 88 | } | |
| 89 | ||
| 90 | function draw(ctx: Ctx, shown: CutOver | undefined, status = 200, flash?: { tone: "danger"; message: string }): Response { | |
| 91 | const rendering = performance.now(); | |
| 92 | const repo = loadAdminRepo(ctx); | |
| 93 | if (!repo) return notFoundPage(ctx); | |
| 94 | const out = page( | |
| 95 | { ctx, title: `Cut over · ${repo.name}`, crumbs: crumbsFor(repo), body: body(repoBase(repo), ctx, repo.name, shown), ...(flash ? { flash } : {}) }, | |
| 96 | status, | |
| 97 | ); | |
| 98 | notePhase(ctx.request, "render", performance.now() - rendering); | |
| 99 | return out; | |
| 100 | } | |
| 101 | ||
| 102 | /** GET /:owner/:name/cut-over */ | |
| 103 | export function cutOverPage(ctx: Ctx): Response { | |
| 104 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 105 | if (ctx.auth.user === undefined) return signInFirst(ctx); | |
| 106 | return draw(ctx, undefined); | |
| 107 | } | |
| 108 | ||
| 109 | /** POST /:owner/:name/cut-over: `do` is check, cut or undo, for the `host` named. */ | |
| 110 | export async function cutOverAct(ctx: Ctx): Promise<Response> { | |
| 111 | const gate = await adminForm(ctx); | |
| 112 | if (gate instanceof Response) return gate; | |
| 113 | const { repo, form } = gate; | |
| 114 | const to = `${repoBase(repo)}/cut-over`; | |
| 115 | const what = field(form, "do"); | |
| 116 | const host = field(form, "host"); | |
| 117 | if (what === "undo") { | |
| 118 | const done = await undoCutOver(ctx.app, ctx.auth.user, repo, host); | |
| 119 | return flashTo(ctx, to, done.ok ? { message: done.value.says } : { tone: "danger", message: cutOverMessage(done.error) }); | |
| 120 | } | |
| 121 | if (what !== "check" && what !== "cut") return draw(ctx, undefined, 422, { tone: "danger", message: "do is check, cut or undo: nothing was changed." }); | |
| 122 | const done = await cutOver(ctx.app, ctx.auth.user, repo, host, what === "cut"); | |
| 123 | if (!done.ok) return draw(ctx, undefined, 422, { tone: "danger", message: cutOverMessage(done.error) }); | |
| 124 | return draw(ctx, done.value); | |
| 125 | } |
src/web/studio/migration.ts +1 −1
| @@ -72,5 +72,5 @@ export async function migrationRegion(ctx: Ctx, repo: Repo, owner: boolean): Pro | ||
| 72 | 72 | imported: last === undefined ? undefined : { tables: last.tables.length, rows: last.tables.reduce((n, t) => n + t.rows, 0) }, |
| 73 | 73 | } |
| 74 | 74 | : null; |
| 75 | return migrationCard(view.origin, view.progress, owner ? `${base}/settings/app` : null, data); | |
| 75 | return migrationCard(view.origin, view.progress, owner ? `${base}/cut-over` : null, data); | |
| 76 | 76 | } |
test/cutover-doors.test.ts added +68
| @@ -0,0 +1,68 @@ | ||
| 1 | /** The doors to cut over (#648): the MCP actions on `app_domains` and the page at `/cut-over`. */ | |
| 2 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 3 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 4 | import { tmpdir } from "node:os"; | |
| 5 | import { join } from "node:path"; | |
| 6 | import { createApp, type App } from "../src/app.ts"; | |
| 7 | import { newApp } from "../src/actions/apps.ts"; | |
| 8 | import { addAppDomain } from "../src/actions/domains.ts"; | |
| 9 | import { AppsRuntime } from "../src/apps/runtime.ts"; | |
| 10 | import { setMigration } from "../src/apps/migration_mode.ts"; | |
| 11 | import { getRepo } from "../src/core/repos.ts"; | |
| 12 | import { getUserByName } from "../src/core/users.ts"; | |
| 13 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 14 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 15 | import { tokenFor } from "./helpers/tokens.ts"; | |
| 16 | import { quietLogs } from "./helpers/globals.ts"; | |
| 17 | ||
| 18 | quietLogs(); | |
| 19 | let dataDir = ""; | |
| 20 | let app: App; | |
| 21 | let servers: Servers; | |
| 22 | let token = ""; | |
| 23 | let runtime: AppsRuntime; | |
| 24 | ||
| 25 | beforeAll(async () => { | |
| 26 | dataDir = await mkdtemp(join(tmpdir(), "forge-cutover-doors-")); | |
| 27 | app = createApp({ dataDir, port: 0 }); | |
| 28 | servers = await serve(app); | |
| 29 | runtime = new AppsRuntime(app, { domain: "apps.test", scheme: "http", publicPort: servers.port, forgeUrl: servers.url, concurrency: 1 }); | |
| 30 | await runtime.start(); | |
| 31 | await seedAdmin(app, { username: "alice", email: "[email protected]", password: "a-good-passphrase" }); | |
| 32 | const alice = getUserByName(app.db, "alice")!; | |
| 33 | const made = await newApp(app, alice, { name: "shop", visibility: "public" }); | |
| 34 | if (!made.ok) throw new Error(String(made.error)); | |
| 35 | const repo = getRepo(app.db, "alice", "shop")!; | |
| 36 | setMigration(app.db, repo.id, "https://old.example/shop", true); | |
| 37 | addAppDomain(app, alice, repo, "www.example.com"); | |
| 38 | token = tokenFor(app, "alice", "admin"); | |
| 39 | }, 30_000); | |
| 40 | afterAll(async () => { | |
| 41 | await runtime.stop(); | |
| 42 | servers.stop(); | |
| 43 | app.close(); | |
| 44 | await rm(dataDir, { recursive: true, force: true }); | |
| 45 | }); | |
| 46 | ||
| 47 | const call = async (args: object): Promise<any> => { | |
| 48 | const res = await fetch(`${servers.url}/mcp`, { | |
| 49 | method: "POST", | |
| 50 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` }, | |
| 51 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "app_domains", arguments: args } }), | |
| 52 | }); | |
| 53 | const body: any = await res.json(); | |
| 54 | return body.result.content[0].text; | |
| 55 | }; | |
| 56 | ||
| 57 | test("MCP cut_over refuses an unverified domain in words, undo says nothing was cut", async () => { | |
| 58 | expect(await call({ repo: "alice/shop", action: "cut_over", host: "www.example.com", apply: true })).toContain("Check the domain"); | |
| 59 | expect(await call({ repo: "alice/shop", action: "undo_cut_over", host: "www.example.com" })).toContain("not been cut over"); | |
| 60 | }); | |
| 61 | ||
| 62 | test("the page is the admin's and lists no verified domain yet", async () => { | |
| 63 | const anon = await fetch(`${servers.url}/alice/shop/cut-over`, { redirect: "manual" }); | |
| 64 | expect(anon.status).toBe(303); | |
| 65 | const page = await fetch(`${servers.url}/alice/shop/cut-over`, { headers: { authorization: `Bearer ${token}` } }); | |
| 66 | expect(page.status).toBe(200); | |
| 67 | expect(await page.text()).toContain("No verified domain yet"); | |
| 68 | }); |
test/cutover-flows.test.ts added +219
| @@ -0,0 +1,219 @@ | ||
| 1 | /** | |
| 2 | * The doors to cut over, end to end (#648): the page's POST flow, the terminal screen and the | |
| 3 | * MCP success path, against one app with a stand-in platform. The registrar is absent, so a cut | |
| 4 | * is the manual one: the receipt names the record to publish. | |
| 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 { newApp } from "../src/actions/apps.ts"; | |
| 12 | import { commitToBranch } from "../src/actions/repos.ts"; | |
| 13 | import { addAppDomain } from "../src/actions/domains.ts"; | |
| 14 | import { AppsRuntime } from "../src/apps/runtime.ts"; | |
| 15 | import { setMigration } from "../src/apps/migration_mode.ts"; | |
| 16 | import { getDomain, recordCheck, setOldRecords } from "../src/core/domains.ts"; | |
| 17 | import { getRepo, type Repo } from "../src/core/repos.ts"; | |
| 18 | import { createSession } from "../src/core/sessions.ts"; | |
| 19 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; | |
| 20 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 21 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 22 | import { cutOverScreen } from "../src/tui/screens/cutover.ts"; | |
| 23 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 24 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 25 | import { quietLogs } from "./helpers/globals.ts"; | |
| 26 | import { settleApp } from "./helpers/tui.ts"; | |
| 27 | import { tokenFor } from "./helpers/tokens.ts"; | |
| 28 | ||
| 29 | quietLogs(); | |
| 30 | ||
| 31 | const HOST = "www.example.com"; | |
| 32 | const OLD = [{ type: "A", name: HOST, value: "203.0.113.5", ttl: 60 }]; | |
| 33 | ||
| 34 | describe("cut over: the doors", () => { | |
| 35 | let dataDir: string; | |
| 36 | let app: App; | |
| 37 | let servers: Servers; | |
| 38 | let runtime: AppsRuntime; | |
| 39 | let alice: User; | |
| 40 | let bob: User; | |
| 41 | let cookie = ""; | |
| 42 | let bobCookie = ""; | |
| 43 | let token = ""; | |
| 44 | let forgeAnswer = 200; | |
| 45 | const repo = (): Repo => getRepo(app.db, "alice", "shop")!; | |
| 46 | const state = () => getDomain(app.db, HOST)!; | |
| 47 | ||
| 48 | const signin = async (username: string) => { | |
| 49 | const r = await fetch(`${servers.url}/signin`, { method: "POST", body: new URLSearchParams({ username, password: "a-good-passphrase" }), redirect: "manual" }); | |
| 50 | return `${(r.headers.get("set-cookie") ?? "").split(";")[0]!}; forge_mode=dev`; | |
| 51 | }; | |
| 52 | const post = (fields: Record<string, string>, who = cookie, extra: Record<string, string> = {}) => | |
| 53 | fetch(`${servers.url}/alice/shop/cut-over`, { method: "POST", headers: { cookie: who, ...extra }, body: new URLSearchParams(fields), redirect: "manual" }); | |
| 54 | const mcp = async (args: object): Promise<string> => { | |
| 55 | const res = await fetch(`${servers.url}/mcp`, { | |
| 56 | method: "POST", | |
| 57 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` }, | |
| 58 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "app_domains", arguments: args } }), | |
| 59 | }); | |
| 60 | return ((await res.json()) as any).result.content[0].text; | |
| 61 | }; | |
| 62 | ||
| 63 | beforeAll(async () => { | |
| 64 | dataDir = await mkdtemp(join(tmpdir(), "forge-cutover-flows-")); | |
| 65 | app = createApp({ dataDir, port: 0 }); | |
| 66 | servers = await serve(app); | |
| 67 | runtime = new AppsRuntime(app, { | |
| 68 | domain: "apps.test", scheme: "http", publicPort: servers.port, forgeUrl: servers.url, concurrency: 1, | |
| 69 | probe: async (url) => (url.startsWith(`https://${HOST}`) ? 200 : forgeAnswer), | |
| 70 | certificate: async () => ({ error: "not served yet" }), | |
| 71 | }); | |
| 72 | await runtime.start(); | |
| 73 | await seedAdmin(app, { username: "alice", email: "[email protected]", password: "a-good-passphrase" }); | |
| 74 | alice = getUserByName(app.db, "alice")!; | |
| 75 | const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); | |
| 76 | if (!b.ok) throw new Error(b.error); | |
| 77 | bob = b.value; | |
| 78 | createSession(app.db, bob.id); | |
| 79 | const made = await newApp(app, alice, { name: "shop", visibility: "public" }); | |
| 80 | if (!made.ok) throw new Error(String(made.error)); | |
| 81 | setMigration(app.db, repo().id, "https://old.example/shop", true); | |
| 82 | const c = await commitToBranch(app, alice, repo(), { branch: repo().defaultBranch, message: "list", files: [{ path: "MIGRATION.md", content: "## Routes\n- [x] GET /\n" }] }); | |
| 83 | if (!c.ok) throw new Error(JSON.stringify(c.error)); | |
| 84 | addAppDomain(app, alice, repo(), HOST); | |
| 85 | recordCheck(app.db, HOST, { verified: true, said: "ok" }); | |
| 86 | cookie = await signin("alice"); | |
| 87 | bobCookie = await signin("bob"); | |
| 88 | token = tokenFor(app, "alice", "admin"); | |
| 89 | }, 60_000); | |
| 90 | afterAll(async () => { | |
| 91 | await runtime.stop(); | |
| 92 | servers.stop(); | |
| 93 | app.close(); | |
| 94 | await rm(dataDir, { recursive: true, force: true }); | |
| 95 | }); | |
| 96 | ||
| 97 | test("the page lists the verified domain once, on the platform, with Check", async () => { | |
| 98 | const text = await (await fetch(`${servers.url}/alice/shop/cut-over`, { headers: { cookie } })).text(); | |
| 99 | expect(text).toContain(HOST); | |
| 100 | expect(text).toContain("on the platform"); | |
| 101 | expect(text).toContain("Check"); | |
| 102 | expect(text).not.toContain("Undo"); | |
| 103 | }); | |
| 104 | ||
| 105 | test("POST: a bad do is 422 and changes nothing; a non-admin finds nothing; a foreign origin is refused", async () => { | |
| 106 | const bad = await post({ do: "drop", host: HOST }); | |
| 107 | expect(bad.status).toBe(422); | |
| 108 | expect(await bad.text()).toContain("do is check, cut or undo"); | |
| 109 | expect((await post({ do: "check", host: HOST }, bobCookie)).status).toBe(404); | |
| 110 | expect((await post({ do: "check", host: HOST }, cookie, { origin: "https://evil.example" })).status).toBe(403); | |
| 111 | expect(state().cutOverAt).toBeNull(); | |
| 112 | }); | |
| 113 | ||
| 114 | test("POST check: the list shows, a differing path blocks the cut", async () => { | |
| 115 | const same = await post({ do: "check", host: HOST }); | |
| 116 | expect(same.status).toBe(200); | |
| 117 | const text = await same.text(); | |
| 118 | expect(text).toContain("same"); | |
| 119 | expect(text).toContain("Cut over"); | |
| 120 | forgeAnswer = 404; | |
| 121 | const differs = await (await post({ do: "cut", host: HOST })).text(); | |
| 122 | expect(differs).toContain("answers differently"); | |
| 123 | expect(state().cutOverAt).toBeNull(); | |
| 124 | forgeAnswer = 200; | |
| 125 | }); | |
| 126 | ||
| 127 | test("POST cut with nothing kept and no registrar is refused in words", async () => { | |
| 128 | const res = await post({ do: "cut", host: HOST }); | |
| 129 | expect(res.status).toBe(422); | |
| 130 | expect(await res.text()).toContain("Nothing is kept"); | |
| 131 | expect(state().cutOverAt).toBeNull(); | |
| 132 | }); | |
| 133 | ||
| 134 | test("POST cut, then Undo: the receipt, the mark, the way back, once", async () => { | |
| 135 | setOldRecords(app.db, HOST, OLD); | |
| 136 | expect(state().cutOverAt).toBeNull(); // kept records alone are not a cut-over | |
| 137 | const undoEarly = await post({ do: "undo", host: HOST }); | |
| 138 | expect(undoEarly.status).toBe(303); | |
| 139 | expect(state().oldRecords).toEqual(OLD); // refused: nothing was cut, nothing was rewritten | |
| 140 | const cut = await post({ do: "cut", host: HOST }); | |
| 141 | expect(cut.status).toBe(200); | |
| 142 | const receipt = await cut.text(); | |
| 143 | expect(receipt).toContain("Publish a CNAME"); | |
| 144 | expect(receipt).toContain("left running, unrouted"); | |
| 145 | expect(state().cutOverAt).not.toBeNull(); | |
| 146 | const page = await (await fetch(`${servers.url}/alice/shop/cut-over`, { headers: { cookie } })).text(); | |
| 147 | expect(page).toContain("cut over"); | |
| 148 | expect(page).toContain("Undo"); | |
| 149 | expect(await (await post({ do: "cut", host: HOST })).text()).toContain("already cut over"); | |
| 150 | expect((await post({ do: "undo", host: HOST })).status).toBe(303); | |
| 151 | expect(state().cutOverAt).toBeNull(); | |
| 152 | expect(state().oldRecords).toEqual([]); | |
| 153 | }); | |
| 154 | ||
| 155 | test("MCP: apply cuts a verified domain, undo_cut_over puts it back", async () => { | |
| 156 | setOldRecords(app.db, HOST, OLD); | |
| 157 | const said = await mcp({ repo: "alice/shop", action: "cut_over", host: HOST, apply: true }); | |
| 158 | expect(said).toContain("Publish a CNAME"); | |
| 159 | expect(state().cutOverAt).not.toBeNull(); | |
| 160 | const back = await mcp({ repo: "alice/shop", action: "undo_cut_over", host: HOST }); | |
| 161 | expect(back).toContain("203.0.113.5"); | |
| 162 | expect(state().cutOverAt).toBeNull(); | |
| 163 | }); | |
| 164 | ||
| 165 | describe("the terminal screen", () => { | |
| 166 | const key = (k: string) => ({ type: "key" as const, key: k, ctrl: false, alt: false, shift: false }); | |
| 167 | const open = (user: User) => { | |
| 168 | const { app: tui, session } = createForgeApp( | |
| 169 | app, | |
| 170 | { sshUsername: user.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user }, | |
| 171 | { terminal: headlessTerminal(120, 40), exitHooks: false }, | |
| 172 | ); | |
| 173 | tui.start(); | |
| 174 | tui.ctx.push(cutOverScreen(session, tui.ctx, repo())); | |
| 175 | return tui; | |
| 176 | }; | |
| 177 | ||
| 178 | test("c checks, o cuts after a confirm, u undoes after a confirm", async () => { | |
| 179 | setOldRecords(app.db, HOST, OLD); | |
| 180 | const tui = open(alice); | |
| 181 | await settleApp(tui); | |
| 182 | expect(tui.screen.toText()).toContain(HOST); | |
| 183 | tui.dispatch(key("c")); | |
| 184 | await settleApp(tui); | |
| 185 | expect(tui.screen.toText()).toContain("Every path answers the same"); | |
| 186 | tui.dispatch(key("o")); | |
| 187 | await settleApp(tui); | |
| 188 | expect(tui.screen.toText()).toContain("pointed at this app"); | |
| 189 | tui.dispatch(key("esc")); | |
| 190 | await settleApp(tui); | |
| 191 | expect(state().cutOverAt).toBeNull(); | |
| 192 | tui.dispatch(key("o")); | |
| 193 | await settleApp(tui); | |
| 194 | tui.dispatch(key("right")); | |
| 195 | tui.dispatch(key("enter")); | |
| 196 | await settleApp(tui); | |
| 197 | expect(state().cutOverAt).not.toBeNull(); | |
| 198 | expect(tui.screen.toText()).toContain("Publish a CNAME"); | |
| 199 | tui.dispatch(key("u")); | |
| 200 | await settleApp(tui); | |
| 201 | expect(tui.screen.toText()).toContain("goes back to the records"); | |
| 202 | tui.dispatch(key("right")); | |
| 203 | tui.dispatch(key("enter")); | |
| 204 | await settleApp(tui); | |
| 205 | expect(state().cutOverAt).toBeNull(); | |
| 206 | tui.stop?.(); | |
| 207 | }); | |
| 208 | ||
| 209 | test("a non-admin sees no domains and the keys do nothing", async () => { | |
| 210 | const tui = open(bob); | |
| 211 | await settleApp(tui); | |
| 212 | expect(tui.screen.toText()).not.toContain(HOST); | |
| 213 | tui.dispatch(key("o")); | |
| 214 | await settleApp(tui); | |
| 215 | expect(state().cutOverAt).toBeNull(); | |
| 216 | tui.stop?.(); | |
| 217 | }); | |
| 218 | }); | |
| 219 | }); |
test/cutover.test.ts added +181
| @@ -0,0 +1,181 @@ | ||
| 1 | /** | |
| 2 | * Cut over (#648): the preview check passes or blocks, apply moves the name and writes a receipt, | |
| 3 | * undo puts the kept records back, and the inventory's word follows. The platform and the registrar | |
| 4 | * are stand-ins; nothing leaves the process. | |
| 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 { newApp } from "../src/actions/apps.ts"; | |
| 12 | import { commitToBranch } from "../src/actions/repos.ts"; | |
| 13 | import { cutOver, undoCutOver } from "../src/actions/cutover.ts"; | |
| 14 | import { addAppDomain } from "../src/actions/domains.ts"; | |
| 15 | import type { DnsProvider, ZoneRecord } from "../src/apps/dns_provider.ts"; | |
| 16 | import { setMigration } from "../src/apps/migration_mode.ts"; | |
| 17 | import { compareStatuses, pathsFrom } from "../src/apps/parity_probe.ts"; | |
| 18 | import { AppsRuntime } from "../src/apps/runtime.ts"; | |
| 19 | import { getDomain, recordCheck } from "../src/core/domains.ts"; | |
| 20 | import { getRepo } from "../src/core/repos.ts"; | |
| 21 | import { createUser, type User } from "../src/core/users.ts"; | |
| 22 | import { quietLogs } from "./helpers/globals.ts"; | |
| 23 | ||
| 24 | quietLogs(); | |
| 25 | ||
| 26 | const HOST = "www.example.com"; | |
| 27 | const OLD: ZoneRecord = { type: "A", name: HOST, value: "203.0.113.5", ttl: 60 }; | |
| 28 | ||
| 29 | describe("cut over", () => { | |
| 30 | let dataDir: string; | |
| 31 | let app: App; | |
| 32 | let runtime: AppsRuntime; | |
| 33 | let alice: User; | |
| 34 | let bob: User; | |
| 35 | let platform: Record<string, number> = {}; | |
| 36 | let forge: Record<string, number> = {}; | |
| 37 | let zone: ZoneRecord[] = []; | |
| 38 | const registrar: DnsProvider = { | |
| 39 | async replace(_name, _types, put) { | |
| 40 | const removed = zone; | |
| 41 | zone = [...put]; | |
| 42 | return { ok: true, removed }; | |
| 43 | }, | |
| 44 | }; | |
| 45 | ||
| 46 | beforeAll(async () => { | |
| 47 | dataDir = await mkdtemp(join(tmpdir(), "forge-cutover-")); | |
| 48 | app = createApp({ dataDir, port: 0, host: "forge.test" }); | |
| 49 | runtime = new AppsRuntime(app, { | |
| 50 | domain: "apps.test", scheme: "http", publicPort: 1, forgeUrl: "http://forge.test", concurrency: 1, | |
| 51 | probe: async (url) => (url.startsWith(`https://${HOST}`) ? platform : forge)[new URL(url).pathname] ?? null, | |
| 52 | certificate: async () => ({ error: "not served yet" }), | |
| 53 | }); | |
| 54 | await runtime.start(); | |
| 55 | const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 56 | const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); | |
| 57 | if (!a.ok || !b.ok) throw new Error("users"); | |
| 58 | alice = a.value; | |
| 59 | bob = b.value; | |
| 60 | const made = await newApp(app, alice, { name: "shop", description: "x", visibility: "public" }); | |
| 61 | if (!made.ok) throw new Error(String(made.error)); | |
| 62 | setMigration(app.db, repo().id, "https://old.example/shop", true); | |
| 63 | addAppDomain(app, alice, repo(), HOST); | |
| 64 | }); | |
| 65 | afterAll(async () => { | |
| 66 | await runtime.stop(); | |
| 67 | await rm(dataDir, { recursive: true, force: true }); | |
| 68 | }); | |
| 69 | const repo = () => getRepo(app.db, "alice", "shop")!; | |
| 70 | const checklist = async (md: string) => { | |
| 71 | const r = await commitToBranch(app, alice, repo(), { branch: repo().defaultBranch, message: "list", files: [{ path: "MIGRATION.md", content: md }] }); | |
| 72 | if (!r.ok) throw new Error(JSON.stringify(r.error)); | |
| 73 | }; | |
| 74 | ||
| 75 | test("the paths come from the checklist: GET lines only, `/` first", () => { | |
| 76 | expect(pathsFrom(["GET /pricing", "POST /login", "`/about` page", "GET /item?id=1", "Sessions"])).toEqual(["/", "/pricing", "/about"]); | |
| 77 | }); | |
| 78 | ||
| 79 | test("a side that did not answer is not the same", async () => { | |
| 80 | const out = await compareStatuses(["/"], "https://a", "https://b", async () => null); | |
| 81 | expect(out[0]!.same).toBe(false); | |
| 82 | }); | |
| 83 | ||
| 84 | test("refused before parity and before the domain is verified", async () => { | |
| 85 | await checklist("## Routes\n- [x] GET /\n- [ ] GET /pricing\n"); | |
| 86 | expect(await cutOver(app, alice, repo(), HOST, false)).toEqual({ ok: false, error: "not_verified" }); | |
| 87 | recordCheck(app.db, HOST, { verified: true, said: "ok" }); | |
| 88 | expect(await cutOver(app, alice, repo(), HOST, false)).toEqual({ ok: false, error: "not_at_parity" }); | |
| 89 | }); | |
| 90 | ||
| 91 | test("a non-admin is refused", async () => { | |
| 92 | expect((await cutOver(app, bob, repo(), HOST, true)).ok).toBe(false); | |
| 93 | }); | |
| 94 | ||
| 95 | test("a differing path blocks: apply changes nothing", async () => { | |
| 96 | await checklist("## Routes\n- [x] GET /\n- [x] GET /pricing\n"); | |
| 97 | platform = { "/": 200, "/pricing": 200 }; | |
| 98 | forge = { "/": 200, "/pricing": 404 }; | |
| 99 | zone = [OLD]; | |
| 100 | const r = await cutOver(app, alice, repo(), HOST, true, { provider: registrar }); | |
| 101 | if (!r.ok) throw new Error(r.error); | |
| 102 | expect(r.value.passed).toBe(false); | |
| 103 | expect(r.value.applied).toBe(false); | |
| 104 | expect(r.value.checks.map((c) => [c.path, c.platform, c.forge, c.same])).toEqual([["/", 200, 200, true], ["/pricing", 200, 404, false]]); | |
| 105 | expect(zone).toEqual([OLD]); | |
| 106 | expect(getDomain(app.db, HOST)!.oldRecords).toEqual([]); | |
| 107 | }); | |
| 108 | ||
| 109 | test("a passing check without apply only shows the list", async () => { | |
| 110 | forge = { "/": 200, "/pricing": 200 }; | |
| 111 | const r = await cutOver(app, alice, repo(), HOST, false, { provider: registrar }); | |
| 112 | if (!r.ok) throw new Error(r.error); | |
| 113 | expect(r.value).toMatchObject({ passed: true, applied: false, receipt: [] }); | |
| 114 | expect(zone).toEqual([OLD]); | |
| 115 | }); | |
| 116 | ||
| 117 | test("apply moves the name, keeps the old records and writes the receipt", async () => { | |
| 118 | const r = await cutOver(app, alice, repo(), HOST, true, { provider: registrar }); | |
| 119 | if (!r.ok) throw new Error(r.error); | |
| 120 | expect(r.value.applied).toBe(true); | |
| 121 | expect(zone.map((z) => [z.type, z.value])).toEqual([["CNAME", runtime.hostFor("shop", "production")]]); | |
| 122 | expect(getDomain(app.db, HOST)!.oldRecords).toEqual([{ type: "A", name: HOST, value: "203.0.113.5", ttl: 60 }]); | |
| 123 | const text = r.value.receipt.join("\n"); | |
| 124 | expect(text).toContain("now points at"); | |
| 125 | expect(text).toContain("Certificate:"); | |
| 126 | expect(text).toContain("left running, unrouted"); | |
| 127 | }); | |
| 128 | ||
| 129 | test("undo restores the old routing in one step, and only once", async () => { | |
| 130 | const u = await undoCutOver(app, alice, repo(), HOST, { provider: registrar }); | |
| 131 | if (!u.ok) throw new Error(u.error); | |
| 132 | expect(zone.map((z) => [z.type, z.value])).toEqual([["A", "203.0.113.5"]]); | |
| 133 | expect(getDomain(app.db, HOST)!.oldRecords).toEqual([]); | |
| 134 | expect(await undoCutOver(app, alice, repo(), HOST, { provider: registrar })).toEqual({ ok: false, error: "not_cut_over" }); | |
| 135 | }); | |
| 136 | ||
| 137 | test("with nothing kept and no registrar there is no way back, so nothing moves", async () => { | |
| 138 | const r = await cutOver(app, alice, repo(), HOST, true); | |
| 139 | expect(r).toEqual({ ok: false, error: "no_way_back" }); | |
| 140 | }); | |
| 141 | }); | |
| 142 | ||
| 143 | describe("cut over: the registrar changed first", () => { | |
| 144 | test("a name with no address record is still cut over and marked; undo only forgets it", async () => { | |
| 145 | const dataDir = await mkdtemp(join(tmpdir(), "forge-cutover-bare-")); | |
| 146 | const app = createApp({ dataDir, port: 0, host: "forge.test" }); | |
| 147 | const runtime = new AppsRuntime(app, { | |
| 148 | domain: "apps.test", scheme: "http", publicPort: 1, forgeUrl: "http://forge.test", concurrency: 1, | |
| 149 | probe: async () => 200, | |
| 150 | certificate: async () => ({ error: "not served yet" }), | |
| 151 | }); | |
| 152 | await runtime.start(); | |
| 153 | try { | |
| 154 | const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 155 | if (!a.ok) throw new Error("user"); | |
| 156 | const made = await newApp(app, a.value, { name: "shop", description: "x", visibility: "public" }); | |
| 157 | if (!made.ok) throw new Error(String(made.error)); | |
| 158 | const repo = getRepo(app.db, "alice", "shop")!; | |
| 159 | setMigration(app.db, repo.id, "https://old.example/shop", true); | |
| 160 | const c = await commitToBranch(app, a.value, repo, { branch: repo.defaultBranch, message: "list", files: [{ path: "MIGRATION.md", content: "- [x] GET /\n" }] }); | |
| 161 | if (!c.ok) throw new Error("commit"); | |
| 162 | addAppDomain(app, a.value, repo, HOST); | |
| 163 | recordCheck(app.db, HOST, { verified: true, said: "ok" }); | |
| 164 | let zone: ZoneRecord[] = []; | |
| 165 | const bare: DnsProvider = { async replace(_n, _t, put) { const removed = zone; zone = [...put]; return { ok: true, removed }; } }; | |
| 166 | const r = await cutOver(app, a.value, repo, HOST, true, { provider: bare }); | |
| 167 | if (!r.ok) throw new Error(r.error); | |
| 168 | expect(zone.map((z) => z.type)).toEqual(["CNAME"]); | |
| 169 | expect(r.value.receipt.join("\n")).toContain("nothing to put back"); | |
| 170 | expect(getDomain(app.db, HOST)!.cutOverAt).not.toBeNull(); | |
| 171 | expect((await cutOver(app, a.value, repo, HOST, true, { provider: bare })).ok).toBe(false); | |
| 172 | const u = await undoCutOver(app, a.value, repo, HOST, { provider: bare }); | |
| 173 | expect(u.ok).toBe(true); | |
| 174 | expect(getDomain(app.db, HOST)!.cutOverAt).toBeNull(); | |
| 175 | } finally { | |
| 176 | await runtime.stop(); | |
| 177 | app.close(); | |
| 178 | await rm(dataDir, { recursive: true, force: true }); | |
| 179 | } | |
| 180 | }); | |
| 181 | }); |
test/origin-inventory.test.ts +3 −1
| @@ -11,7 +11,7 @@ import { createRepo } from "../src/actions/repos.ts"; | ||
| 11 | 11 | import { createApp, type App } from "../src/app.ts"; |
| 12 | 12 | import { setMirrorTarget } from "../src/core/migrate_mirror.ts"; |
| 13 | 13 | import { createApp as makeApp } from "../src/core/apps.ts"; |
| 14 | import { addDomain, recordCheck, setOldRecords } from "../src/core/domains.ts"; | |
| 14 | import { addDomain, recordCheck, setCutOver, setOldRecords } from "../src/core/domains.ts"; | |
| 15 | 15 | import { recordProvenance } from "../src/core/provenance.ts"; |
| 16 | 16 | import { createToken } from "../src/core/tokens.ts"; |
| 17 | 17 | import { serve, type Servers } from "../src/http/server.ts"; |
| @@ -164,5 +164,7 @@ test("states come from the forge's own records", async () => { | ||
| 164 | 164 | expect(added.ok).toBe(true); |
| 165 | 165 | recordCheck(app.db, "shop.example.com", { verified: true, said: "ok" }); |
| 166 | 166 | setOldRecords(app.db, "shop.example.com", [{ type: "A", name: "shop.example.com", value: "203.0.113.1" }]); |
| 167 | expect(stateOf(app.db, alice, row).state).not.toBe("cut_over"); // kept records alone are not a cut-over | |
| 168 | setCutOver(app.db, "shop.example.com", new Date().toISOString()); | |
| 167 | 169 | expect(stateOf(app.db, alice, row).state).toBe("cut_over"); |
| 168 | 170 | }); |
new above
offline
HIGH: the registrar was already edited at this point. Returning an error here leaves the name cut over, with no kept records and no event. Decide the way back before the edit, or save whatever came back first.