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

The terminal's deploys screen lists an app's custom domains, adds, checks and removes one, as MCP `app_domains` does #7383

Parked opened this
Closed without merging

scout/forge:scout/7322-the-terminal-s-deploys-screen-lists-an-a → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
4 files changed +240 −26
src/actions/domain_words.ts added +30
@@ -0,0 +1,30 @@
1 /**
2 * What an app's domains say: the refusals and the records to publish, in the
3 * words the settings page and the terminal share.
4 */
5
6 import type { DnsRecord } from "../apps/domains.ts";
7
8 export const APP_DOMAIN_ERRORS: Record<string, string> = {
9 invalid_host:
10 "A domain is a hostname: letters, digits and hyphens in at least two labels, like app.example.com.",
11 reserved_host: "That name is the forge's own to hand out.",
12 taken: "Another app already answers to that domain.",
13 no_runtime: "Nothing is serving apps on this forge.",
14 };
15
16 /** The answer to a name that is not this app's, or a viewer who is not its admin. */
17 export const APP_DOMAIN_NO_SUCH = "No domain by that name.";
18
19 /** What the records say: type, name and value, in words. */
20 export function recordsInWords(records: readonly DnsRecord[]): string {
21 return records
22 .map((r) =>
23 r.type === "TXT"
24 ? `a TXT record at ${r.name} with the value ${r.value}`
25 : r.type === "CNAME"
26 ? `a CNAME from ${r.name} to ${r.value}`
27 : `an ALIAS from ${r.name} to ${r.value}`,
28 )
29 .join(" and ");
30 }
src/tui/screens/deploys.ts +115 −3
@@ -16,9 +16,18 @@
1616 * (`env_words.ts`). A stopped production offers only `D`; a reader sees
1717 * neither key.
1818 *
19 <<<<<<< HEAD
20 * An admin of the app also sees its own domains (`listAppDomains`), each with
21 * the action's words for its state. `+` adds one, `tab` moves the domain
22 * cursor, `k` checks the one under it and says the record still to publish,
23 * and `-` removes it after a confirm — as MCP `app_domains` does. `k` is the
24 * check, not "up", once a domain is listed; the arrow still moves up. Anyone
25 * else sees no domain and no key.
26 =======
1927 * A writer — whom the MCP tool `probe` lets knock — gets `p`: the same
2028 * `probeApp` against the running production app, every door tried as
2129 * nobody, a user and an admin, read-only, one line per door.
30 >>>>>>> origin/main
2231 */
2332
2433 import {
@@ -31,6 +40,8 @@ import {
3140 stopEnv,
3241 type AppPullLine,
3342 } from "../../actions/apps.ts";
43 import { addAppDomain, checkAppDomain, listAppDomains, removeAppDomain, type AppDomainView } from "../../actions/domains.ts";
44 import { APP_DOMAIN_ERRORS, APP_DOMAIN_NO_SUCH, recordsInWords } from "../../actions/domain_words.ts";
3445 import { envLabel, envRefusalText, redeployedText, stoppedText } from "../../actions/env_words.ts";
3546 import { trendLine, visitorsLine } from "../../apps/vitals.ts";
3647 import { listRepoRuns } from "../../actions/runs.ts";
@@ -45,10 +56,14 @@ import type { Ctx, Screen } from "../app/app.ts";
4556 import { binding } from "../app/keys.ts";
4657 import type { Session } from "../session.ts";
4758 import { style } from "../term/style.ts";
48 import { truncate } from "../term/width.ts";
59 import { truncate, wrap } from "../term/width.ts";
4960 import { fill, len, split } from "../ui/layout.ts";
5061 import { emptyState } from "../ui/widgets.ts";
62 <<<<<<< HEAD
63 import { confirmScreen, drawList, hitList, promptScreen, runAsync } from "./common.ts";
64 =======
5165 import { ListState, confirmScreen, drawList, hitList, runAsync, type ListRow } from "./common.ts";
66 >>>>>>> origin/main
5267 import { RunList, openRunLog, runRows } from "./runlist.ts";
5368
5469 const LIMIT = 50;
@@ -89,6 +104,12 @@ function pullLine(p: AppPullLine): string {
89104 return `#${p.number} ${title} · check ${p.check} · ${p.preview ?? "none"}`;
90105 }
91106
107 /** A domain's state in the action's words. */
108 function domainLine(d: AppDomainView, selected: boolean): string {
109 const state = d.verified ? "verified" : d.said === "" ? "Not checked yet." : d.said;
110 return `${selected ? ">" : " "} ${d.host} · ${state}`;
111 }
112
92113 export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
93114 const list = new RunList(f);
94115 let carries = new Map<string, number[]>();
@@ -99,6 +120,11 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
99120 let side: string[] = [];
100121 let pulls: AppPullLine[] = [];
101122 let production: Production = { state: "", redeploy: false, stop: false };
123 // Domains are an admin's: listing fails for anyone else, and no key shows.
124 let domains: AppDomainView[] = [];
125 let canDomains = false;
126 let at = 0;
127 let note = "";
102128
103129 const read = (): void => {
104130 const runs = readDeploys(f, repo);
@@ -114,6 +140,10 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
114140 side = appSideLines(f.app, f.user, repo);
115141 pulls = appPullLines(f.app, f.user, repo);
116142 production = readProduction(f, repo);
143 const listed = listAppDomains(f.app, f.user, repo);
144 canDomains = listed.ok;
145 domains = listed.ok ? listed.value : [];
146 at = Math.max(0, Math.min(at, domains.length - 1));
117147 loaded = true;
118148 ctx.invalidate();
119149 };
@@ -157,6 +187,57 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
157187 : { text: envRefusalText(stopped.error), refused: true };
158188 });
159189
190 const say = (text: string): void => {
191 note = text;
192 read();
193 };
194
195 const addDomain = (): Screen =>
196 promptScreen(ctx, screen, {
197 title: "Add a domain",
198 label: "the app's own address, like app.example.com",
199 onSubmit: (host) => {
200 if (host === "") return "A domain needs a name.";
201 const added = addAppDomain(f.app, f.user, repo, host);
202 if (!added.ok) return APP_DOMAIN_ERRORS[added.error] ?? "That domain could not be added.";
203 at = domains.length;
204 say(`${added.value.host} is added. Publish ${recordsInWords(added.value.records)}, then press k to check.`);
205 return undefined;
206 },
207 });
208
209 const checkDomain = (d: AppDomainView): void =>
210 runAsync(ctx, async () => {
211 const checked = await checkAppDomain(f.app, f.user, repo, d.host);
212 if (!checked.ok) return say(APP_DOMAIN_ERRORS[checked.error] ?? APP_DOMAIN_NO_SUCH);
213 const v = checked.value;
214 say(v.verified ? v.said : `${v.said} Publish ${recordsInWords(v.records)}.`);
215 });
216
217 const removeDomain = (d: AppDomainView): void => {
218 const onChoose = (choice: number): void => {
219 if (choice !== 1) return;
220 const removed = removeAppDomain(f.app, f.user, repo, d.host);
221 say(removed.ok ? `${d.host} is removed. The forge no longer answers there.` : APP_DOMAIN_NO_SUCH);
222 };
223 const ask = confirmScreen(ctx, screen, {
224 title: "Remove a domain",
225 body: [`remove ${d.host}? y/n`, "The forge stops answering there at once."],
226 actions: [{ label: "Keep", variant: "ghost" }, { label: "Remove", variant: "danger" }],
227 onChoose,
228 });
229 // `y` and `n` answer the question as the body asks it.
230 ctx.push({
231 ...ask,
232 key(e) {
233 if (e.ctrl || e.alt || (e.key !== "y" && e.key !== "n")) return ask.key!(e);
234 ctx.pop();
235 onChoose(e.key === "y" ? 1 : -1);
236 return true;
237 },
238 });
239 };
240
160241 const screen: Screen = {
161242 title: "Deploys",
162243 get keys() {
@@ -166,14 +247,25 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
166247 binding(["r"], "refresh (the open pulls below the deploys: check, preview)"),
167248 ...(production.redeploy ? [binding(["D"], "redeploy production")] : []),
168249 ...(production.stop ? [binding(["S"], "stop production")] : []),
250 <<<<<<< HEAD
251 ...(canDomains ? [binding(["+"], "add a domain")] : []),
252 ...(canDomains && domains.length > 0
253 ? [binding(["tab"], "next domain"), binding(["k"], "check the domain"), binding(["-"], "remove the domain")]
254 : []),
255 =======
169256 ...(mayProbe ? [binding(["p"], "probe the running app's doors")] : []),
257 >>>>>>> origin/main
170258 ];
171259 },
172260 load: async () => read(),
173261 render(area, s) {
174262 const c = ctx.theme.c;
263 const said = canDomains && note !== "" ? wrap(note, Math.max(1, area.w)).slice(0, 3) : [];
175264 const [head, upper, tail] = split(area, "v", [
176 len(1 + (visitors === "" ? 0 : 1) + (trend === "" ? 0 : 1) + (pace === "" ? 0 : 1) + side.length),
265 len(
266 1 + (visitors === "" ? 0 : 1) + (trend === "" ? 0 : 1) + (pace === "" ? 0 : 1) + side.length +
267 domains.length + said.length,
268 ),
177269 fill(1),
178270 len(pulls.length === 0 ? 0 : pulls.length + 1),
179271 ]);
@@ -199,7 +291,7 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
199291 style(c.mutedFg, c.bg),
200292 head!.x + head!.w,
201293 );
202 [visitors, trend, pace, ...side]
294 [visitors, trend, pace, ...side, ...domains.map((d, i) => domainLine(d, i === at)), ...said]
203295 .filter((line) => line !== "")
204296 .forEach((line, i) =>
205297 s.text(head!.x, head!.y + 1 + i, truncate(line, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w),
@@ -228,6 +320,26 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
228320 });
229321 },
230322 key(e) {
323 if (canDomains && !e.ctrl && !e.alt) {
324 const d = domains[at];
325 if (e.key === "+") {
326 ctx.push(addDomain());
327 return true;
328 }
329 if (d !== undefined && e.key === "tab") {
330 at = (at + 1) % domains.length;
331 ctx.invalidate();
332 return true;
333 }
334 if (d !== undefined && e.key === "k") {
335 checkDomain(d);
336 return true;
337 }
338 if (d !== undefined && e.key === "-") {
339 removeDomain(d);
340 return true;
341 }
342 }
231343 if (list.state.key(e, list.runs.length)) return true;
232344 if (e.key === "enter") {
233345 const run = list.selected;
src/web/pages/settings.ts +3 −23
@@ -8,6 +8,7 @@
88 * same-origin POST and every one of them says what happened.
99 */
1010
11 import { APP_DOMAIN_ERRORS, APP_DOMAIN_NO_SUCH, recordsInWords } from "../../actions/domain_words.ts";
1112 import { appLimitWords } from "../../actions/app_limit.ts";
1213 import { showProvenance } from "../../actions/provenance.ts";
1314 import { getProvenance, parentUrl, sourceLabel } from "../../core/provenance.ts";
@@ -1213,27 +1214,6 @@ export async function appEnvDelete(ctx: Ctx): Promise<Response> {
12131214 );
12141215 }
12151216
1216 const APP_DOMAIN_ERRORS: Record<string, string> = {
1217 invalid_host:
1218 "A domain is a hostname: letters, digits and hyphens in at least two labels, like app.example.com.",
1219 reserved_host: "That name is the forge's own to hand out.",
1220 taken: "Another app already answers to that domain.",
1221 no_runtime: "Nothing is serving apps on this forge.",
1222 };
1223
1224 /** What the records say, as one flash: type, name and value, in words. */
1225 function recordsInWords(records: DnsRecord[]): string {
1226 return records
1227 .map((r) =>
1228 r.type === "TXT"
1229 ? `a TXT record at ${r.name} with the value ${r.value}`
1230 : r.type === "CNAME"
1231 ? `a CNAME from ${r.name} to ${r.value}`
1232 : `an ALIAS from ${r.name} to ${r.value}`,
1233 )
1234 .join(" and ");
1235 }
1236
12371217 // POST /:owner/:name/settings/app/domains — add one.
12381218 export async function appDomainAdd(ctx: Ctx): Promise<Response> {
12391219 const gate = await adminForm(ctx);
@@ -1279,7 +1259,7 @@ export async function appDomainCheck(ctx: Ctx): Promise<Response> {
12791259 : {
12801260 tone: "danger",
12811261 message:
1282 APP_DOMAIN_ERRORS[checked.error] ?? "No domain by that name.",
1262 APP_DOMAIN_ERRORS[checked.error] ?? APP_DOMAIN_NO_SUCH,
12831263 },
12841264 );
12851265 }
@@ -1297,7 +1277,7 @@ export async function appDomainDelete(ctx: Ctx): Promise<Response> {
12971277 `${repoBase(repo)}/settings/app`,
12981278 removed.ok
12991279 ? { message: `${host} is removed. The forge no longer answers there.` }
1300 : { tone: "danger", message: "No domain by that name." },
1280 : { tone: "danger", message: APP_DOMAIN_NO_SUCH },
13011281 );
13021282 }
13031283
test/tui-deploys.test.ts +92
@@ -205,3 +205,95 @@ test("production's terminal names the newest open preview to a reader, and a gue
205205 await runtime.stop();
206206 }
207207 });
208
209 test("an app's admin adds, checks and removes a domain from the deploys screen; a non-admin sees none", async () => {
210 const { AppsRuntime } = await import("../src/apps/runtime.ts");
211 const { getDomain } = await import("../src/core/domains.ts");
212 const dns = {
213 txt: new Map<string, string[][]>(),
214 resolveTxt(name: string) {
215 const found = this.txt.get(name);
216 return found ? Promise.resolve(found) : Promise.reject(Object.assign(new Error("none"), { code: "ENODATA" }));
217 },
218 resolveCname: () => Promise.reject(Object.assign(new Error("none"), { code: "ENODATA" })),
219 };
220 const runtime = new AppsRuntime(forge, { domain: "apps.test", scheme: "https", forgeUrl: "https://forge.test", concurrency: 1, dns });
221 const r = await createRepo(forge, alice, { name: "atlas", visibility: "public" });
222 if (!r.ok) throw new Error("repo failed");
223 const made = createAppRecord(forge.db, { repoId: r.value.id, slug: "atlas", access: "public" });
224 if (!made.ok) throw new Error(made.error);
225 const bobUp = await signUp(forge, { username: "bob2", email: "[email protected]", password: "a-long-passphrase" }, { slot: fixtureSlot(forge) });
226 if (!bobUp.ok) throw new Error("signup failed");
227 try {
228 const { app, session } = createForgeApp(
229 forge,
230 { sshUsername: "alice", remoteAddress: "127.0.0.1", user: alice },
231 { terminal: headlessTerminal(140, 30), exitHooks: false },
232 );
233 app.start();
234 await settleApp(app);
235 app.push(deploysScreen(session, app.ctx, r.value));
236 await settleApp(app);
237 const press = async (...keys: string[]) => {
238 for (const key of keys) app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
239 await settleApp(app);
240 };
241 const type = (text: string) => press(...text.split(""));
242 expect(app.screen.toText()).not.toContain("shop.example.com");
243
244 // A bad name and a taken name are refused in the action's words, the prompt kept open.
245 await press("+");
246 await type("nodots");
247 await press("enter");
248 expect(app.screen.toText()).toContain("A domain is a hostname");
249 await press("esc");
250 await press("+");
251 await type("shop.example.com");
252 await press("enter");
253 let text = app.screen.toText();
254 expect(text).toContain("shop.example.com · Not checked yet.");
255 expect(text).toContain("is added. Publish a TXT record at _forge-verify.shop.example.com");
256 expect(getDomain(forge.db, "shop.example.com")?.appId).toBe(made.value.id);
257 await press("+");
258 await type("shop.example.com");
259 await press("enter");
260 expect(app.screen.toText()).toContain("Another app already answers to that domain.");
261 await press("esc");
262
263 // Check: the record still needed is named.
264 await press("k");
265 text = app.screen.toText();
266 expect(text).toContain("No TXT record at _forge-verify.shop.example.com yet.");
267 expect(text).toContain("Publish a TXT record");
268
269 // Remove asks, and `n` keeps it; `y` removes it.
270 await press("-");
271 expect(app.screen.toText()).toContain("remove shop.example.com? y/n");
272 await press("n");
273 expect(getDomain(forge.db, "shop.example.com")?.host).toBe("shop.example.com");
274 await press("-", "y");
275 expect(getDomain(forge.db, "shop.example.com")).toBeUndefined();
276 expect(app.screen.toText()).toContain("shop.example.com is removed.");
277 app.stop();
278
279 // A viewer who is not the app's admin sees the list without the keys, and `+` does nothing.
280 const other = createForgeApp(
281 forge,
282 { sshUsername: "bob2", remoteAddress: "127.0.0.1", user: bobUp.value },
283 { terminal: headlessTerminal(140, 30), exitHooks: false },
284 );
285 other.app.start();
286 await settleApp(other.app);
287 other.app.push(deploysScreen(other.session, other.app.ctx, r.value));
288 await settleApp(other.app);
289 other.app.dispatch({ type: "key", key: "+", ctrl: false, alt: false, shift: false });
290 await settleApp(other.app);
291 expect(other.app.screen.toText()).not.toContain("Add a domain");
292 expect(other.app.screen.toText()).toContain("alice/atlas · production deploys");
293 other.app.stop();
294 const { addAppDomain } = await import("../src/actions/domains.ts");
295 expect(addAppDomain(forge, bobUp.value, r.value, "x.example.com")).toEqual({ ok: false, error: "not_found" });
296 } finally {
297 await runtime.stop();
298 }
299 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs