Public: anyone can read this; the crew can change it.
Saving a template validates its forge.json and names the first thing wrong #13335
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/13304-saving-a-template-validates-its-forge-js → main 3 commits fork
12 files
changed +313
−11
docs/features/repo-template.md +6
| @@ -9,3 +9,9 @@ An admin of a repository marks it as a template for new forges (#12431). This is | ||
| 9 | 9 | - List: `GET /api/v1/templates` (`limit`, `cursor`), only repositories the reader may see, by the same rule as the repository list. |
| 10 | 10 | |
| 11 | 11 | Only a person who administers the repository sets it; an agent is refused as `not_found`. Stored as `repo.is_template`; the change is in the `repo.settings_updated` event. |
| 12 | ||
| 13 | ## forge.json is checked when it is marked (#13304) | |
| 14 | ||
| 15 | Marking reads `forge.json` at the default branch's tip and runs it through the manifest's own checks (run command, egress, tty and the rest, `src/apps/template_problem.ts`). A file that is missing or wrong refuses the mark with the first failing field named (API 422 `template_invalid`, the page's flash, the terminal's toast, the MCP error), and nothing changes. A repository already marked is never blocked: when its file stops passing, Settings › App says "Flagged as a template: <the field>" and the terminal screen shows the same line under it. Unmarking is never refused. | |
| 16 | ||
| 17 | A `forge.json` with no `app` section (nothing for the forge to run) is refused too, as "forge.json: declares no app.run command"; add `app.run` before marking. The verdict is cached per commit, so the settings page reads the files once per head. |
src/actions/repos.ts +15 −2
| @@ -58,6 +58,7 @@ import { | ||
| 58 | 58 | type Webhook, |
| 59 | 59 | } from "../core/webhooks.ts"; |
| 60 | 60 | import { resolveOid } from "../git/merge.ts"; |
| 61 | import { templateProblem } from "../apps/template_problem.ts"; | |
| 61 | 62 | import { repoDir, setDefaultBranch } from "../git/repos.ts"; |
| 62 | 63 | import { isSafeRef } from "../git/guard.ts"; |
| 63 | 64 | import { |
| @@ -104,7 +105,8 @@ export type CreateRepoActionError = | ||
| 104 | 105 | * The repositories limit (#2093): when the owner has set one, an account at |
| 105 | 106 | * it makes no more, by create, fork or copy. Admins and agents are not held |
| 106 | 107 | * to it. Only a repository the account owns itself is counted and asked: creating |
| 107 | * under an organisation is not, since the quota is per account. Returns the refusal sentence ("10 of 10 repositories") or nothing. | |
| 108 | * under an organisation is not, since the quota is per account. Returns the refusal sentence ("10 | |
| 109 | * of 10 repositories") or nothing. | |
| 108 | 110 | */ |
| 109 | 111 | export function repositoryLimitRefusal(app: App, user: User, ownerId = user.id): string | undefined { |
| 110 | 112 | if (user.isAdmin || user.kind === "agent") return undefined; |
| @@ -311,6 +313,11 @@ export async function privateRepoForSealed( | ||
| 311 | 313 | |
| 312 | 314 | export type UpdateSettingsError = "not_found" | "unknown_branch" | "polish_share" | "origin_read_only"; |
| 313 | 315 | |
| 316 | /** | |
| 317 | * A mark refused because the template's forge.json fails: `message` names the first thing wrong. | |
| 318 | */ | |
| 319 | export type TemplateRefused = { readonly ok: false; readonly error: "template_invalid"; readonly message: string }; | |
| 320 | ||
| 314 | 321 | /** Each repository's archive transitions, one after another. */ |
| 315 | 322 | const archiveTurns = new WeakMap<App, Map<string, Promise<void>>>(); |
| 316 | 323 | |
| @@ -407,7 +414,7 @@ export async function updateRepoSettings( | ||
| 407 | 414 | actor: User | undefined, |
| 408 | 415 | repo: Repo, |
| 409 | 416 | settings: RepoSettings, |
| 410 | ): Promise<Result<Repo, UpdateSettingsError>> { | |
| 417 | ): Promise<Result<Repo, UpdateSettingsError> | TemplateRefused> { | |
| 411 | 418 | const admin = requireRepoAdmin(app, actor, repo); |
| 412 | 419 | if (!admin.ok) return admin; |
| 413 | 420 | // Who the crew obeys, and whether the repository is archived, are a |
| @@ -432,6 +439,12 @@ export async function updateRepoSettings( | ||
| 432 | 439 | return err("origin_read_only"); |
| 433 | 440 | if (settings.polishShare !== undefined && !validPolishShare(settings.polishShare)) |
| 434 | 441 | return err("polish_share"); |
| 442 | // Marking a template runs its forge.json through the manifest's own checks and names the | |
| 443 | // first thing wrong (`templateProblem`); one already marked is only flagged, never blocked. | |
| 444 | if (settings.template === true && !repo.template) { | |
| 445 | const message = await templateProblem(app, repo); | |
| 446 | if (message !== undefined) return { ok: false, error: "template_invalid", message }; | |
| 447 | } | |
| 435 | 448 | const branch = settings.defaultBranch; |
| 436 | 449 | if (branch !== undefined && branch !== repo.defaultBranch) { |
| 437 | 450 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); |
src/apps/template_problem.ts added +39
| @@ -0,0 +1,39 @@ | ||
| 1 | /** | |
| 2 | * What is wrong with a template's `forge.json` (#13304): the first failing field, named, or | |
| 3 | * `undefined` when the default branch's file is one the forge could run. Read from the | |
| 4 | * default branch's tip, the way a new forge copies it; a repository with no file, or no commit | |
| 5 | * yet, is told so, because a template nobody can run is not one to offer. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { App } from "../app.ts"; | |
| 9 | import type { Repo } from "../core/repos.ts"; | |
| 10 | import { repoDir } from "../git/repos.ts"; | |
| 11 | import { resolveOid } from "../git/merge.ts"; | |
| 12 | import { readFileAt } from "./checkout.ts"; | |
| 13 | import { parseManifest } from "./manifest.ts"; | |
| 14 | ||
| 15 | /** The verdict per commit: a commit never changes, so the settings page reads the files once. */ | |
| 16 | const kept = new WeakMap<App, Map<string, string | undefined>>(); | |
| 17 | const KEPT = 500; | |
| 18 | ||
| 19 | export async function templateProblem(app: App, repo: Repo): Promise<string | undefined> { | |
| 20 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 21 | const oid = await resolveOid(dir, `refs/heads/${repo.defaultBranch}`); | |
| 22 | if (!oid) return "forge.json: the default branch has no commit yet"; | |
| 23 | let verdicts = kept.get(app); | |
| 24 | if (!verdicts) kept.set(app, (verdicts = new Map())); | |
| 25 | const key = `${dir}@${oid}`; | |
| 26 | if (verdicts.has(key)) return verdicts.get(key); | |
| 27 | const said = await problemAt(dir, oid); | |
| 28 | if (verdicts.size >= KEPT) verdicts.clear(); | |
| 29 | verdicts.set(key, said); | |
| 30 | return said; | |
| 31 | } | |
| 32 | ||
| 33 | async function problemAt(dir: string, oid: string): Promise<string | undefined> { | |
| 34 | const forgeJson = await readFileAt(dir, oid, "forge.json"); | |
| 35 | if (forgeJson === undefined) return "forge.json: not found on the default branch"; | |
| 36 | const parsed = parseManifest(forgeJson, await readFileAt(dir, oid, "package.json")); | |
| 37 | if (parsed.ok) return undefined; | |
| 38 | return parsed.error.kind === "invalid" ? parsed.error.message : "forge.json: declares no app.run command"; | |
| 39 | } |
src/http/api.ts +1
| @@ -1782,6 +1782,7 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1782 | 1782 | : {}), |
| 1783 | 1783 | }); |
| 1784 | 1784 | if (!updated.ok && updated.error === "origin_read_only") return apiError("origin_read_only", 409, "this repository mirrors a read-only origin, so it stays private to its owner; nothing was changed"); |
| 1785 | if (!updated.ok && updated.error === "template_invalid") return apiError("template_invalid", 422, updated.message); | |
| 1785 | 1786 | if (!updated.ok) return respondAccess(updated.error, 422); |
| 1786 | 1787 | // "Show where this came from" (#3293): an admin's, never an agent's. |
| 1787 | 1788 | if (typeof input.showProvenance === "boolean") { |
src/http/mcp/tools/repo_settings.ts +2
| @@ -86,6 +86,8 @@ export const tool: Tool = { | ||
| 86 | 86 | ...(description !== undefined ? { description } : {}), |
| 87 | 87 | ...(template !== undefined ? { template } : {}), |
| 88 | 88 | }); |
| 89 | if (!updated.ok && updated.error === "template_invalid") | |
| 90 | return bad("invalid", updated.message); | |
| 89 | 91 | if (!updated.ok) |
| 90 | 92 | return bad(updated.error === "not_found" ? "not_found" : "forbidden", updated.error); |
| 91 | 93 | return good({ |
src/tui/screens/template.ts +14 −2
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | 9 | import { updateRepoSettings } from "../../actions/repos.ts"; |
| 10 | import { templateProblem } from "../../apps/template_problem.ts"; | |
| 10 | 11 | import { canAdmin, getRepoById, type Repo } from "../../core/repos.ts"; |
| 11 | 12 | import { templateSaid } from "../../core/template_words.ts"; |
| 12 | 13 | import type { Ctx, Screen } from "../app/app.ts"; |
| @@ -22,11 +23,19 @@ export const mayMarkTemplate = (f: Session, repo: Repo): boolean => f.user !== u | ||
| 22 | 23 | |
| 23 | 24 | export function templateScreen(f: Session, ctx: Ctx, repo: Repo): Screen { |
| 24 | 25 | const now = (): Repo => getRepoById(f.db, repo.id) ?? repo; |
| 26 | let flag: string | undefined; | |
| 27 | const look = async (signal: AbortSignal): Promise<void> => { | |
| 28 | const problem = now().template ? await templateProblem(f.app, now()) : undefined; | |
| 29 | if (signal.aborted) return; | |
| 30 | flag = problem; | |
| 31 | ctx.invalidate(); | |
| 32 | }; | |
| 25 | 33 | return { |
| 26 | 34 | title: `${repo.ownerName}/${repo.name} — Template`, |
| 27 | 35 | keys: [binding(["t"], "mark or unmark as a template")], |
| 28 | 36 | async load(signal) { |
| 29 | live(f, signal, { repoId: repo.id, kinds: ["repo.settings_updated"] }, () => ctx.invalidate()); | |
| 37 | live(f, signal, { repoId: repo.id, kinds: ["repo.settings_updated"] }, () => void look(signal)); | |
| 38 | await look(signal); | |
| 30 | 39 | }, |
| 31 | 40 | render(area, s) { |
| 32 | 41 | const c = ctx.theme.c; |
| @@ -37,6 +46,8 @@ export function templateScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | ||
| 37 | 46 | ? "New forges may start from this repository. t clears it." |
| 38 | 47 | : "Not a template. t lets new forges start from this repository."; |
| 39 | 48 | s.text(area.x, area.y, truncate(said, area.w), style(c.mutedFg, c.bg), area.x + area.w); |
| 49 | if (on && flag !== undefined && area.h > 1) | |
| 50 | s.text(area.x, area.y + 1, truncate(`Flagged: ${flag}`, area.w), style(c.mutedFg, c.bg), area.x + area.w); | |
| 40 | 51 | }, |
| 41 | 52 | key(e) { |
| 42 | 53 | if (e.ctrl || e.alt || e.key !== "t") return false; |
| @@ -44,7 +55,8 @@ export function templateScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | ||
| 44 | 55 | ? updateRepoSettings(f.app, f.user, now(), { template: !now().template }) |
| 45 | 56 | : undefined; |
| 46 | 57 | void Promise.resolve(set).then((r) => { |
| 47 | ctx.toast(r?.ok ? templateSaid(r.value.template) : "An admin of this repository marks it a template.", r?.ok ? undefined : "danger"); | |
| 58 | const why = r && !r.ok && r.error === "template_invalid" ? r.message : undefined; | |
| 59 | ctx.toast(r?.ok ? templateSaid(r.value.template) : why ?? "An admin of this repository marks it a template.", r?.ok ? undefined : "danger"); | |
| 48 | 60 | ctx.invalidate(); |
| 49 | 61 | }); |
| 50 | 62 | return true; |
src/web/pages/settings.ts +9 −2
| @@ -10,6 +10,7 @@ | ||
| 10 | 10 | |
| 11 | 11 | import { blockedWay } from "../blocked.ts"; |
| 12 | 12 | import { privateDestinationBlocked } from "../../actions/blocked_words.ts"; |
| 13 | import { templateProblem } from "../../apps/template_problem.ts"; | |
| 13 | 14 | import { templateSaid } from "../../core/template_words.ts"; |
| 14 | 15 | import { POLISH_SHARE_DEFAULT, POLISH_SHARE_MAX } from "../../crew/polish_share.ts"; |
| 15 | 16 | import { appLimitWords } from "../../actions/app_limit.ts"; |
| @@ -485,6 +486,8 @@ export async function settingsUpdate(ctx: Ctx): Promise<Response> { | ||
| 485 | 486 | message: |
| 486 | 487 | updated.error === "unknown_branch" |
| 487 | 488 | ? "That branch does not exist in this repository." |
| 489 | : updated.error === "template_invalid" | |
| 490 | ? `Not marked as a template. ${updated.message}` | |
| 488 | 491 | : updated.error === "polish_share" |
| 489 | 492 | ? `Polish share is a whole number of percent, 0 to ${POLISH_SHARE_MAX}.` |
| 490 | 493 | : "Those settings could not be saved.", |
| @@ -703,6 +706,7 @@ function appSettingsView( | ||
| 703 | 706 | egress?: EgressView, |
| 704 | 707 | blocked?: BlockedView, |
| 705 | 708 | needs?: { needs: readonly NeedRow[]; grantable: { name: string; scope: "forge" | "org" }[] }, |
| 709 | templateWhy?: string, | |
| 706 | 710 | ): Html { |
| 707 | 711 | const base = repoBase(repo); |
| 708 | 712 | const runtime = appsRuntime(ctx.app); |
| @@ -796,7 +800,9 @@ function appSettingsView( | ||
| 796 | 800 | <h2>Statement</h2> |
| 797 | 801 | <p><a href="${base}/settings/app/statement">This month's statement</a></p> |
| 798 | 802 | </section>`; |
| 799 | if (record === undefined) return html`${form}<div class="mt">${statement}</div>`; | |
| 803 | // A marked template whose forge.json no longer passes: one line, never a block. | |
| 804 | const flagged = templateWhy === undefined ? html`` : html`<p class="muted mt">Flagged as a template: ${templateWhy}</p>`; | |
| 805 | if (record === undefined) return html`${form}${flagged}<div class="mt">${statement}</div>`; | |
| 800 | 806 | const domains = timePhase(ctx.request, "domains", () => |
| 801 | 807 | listAppDomains(ctx.app, ctx.auth.user, repo), |
| 802 | 808 | ); |
| @@ -812,7 +818,7 @@ function appSettingsView( | ||
| 812 | 818 | ], |
| 813 | 819 | helpAsked(ctx.request.url), |
| 814 | 820 | ); |
| 815 | return html`${help}${form} | |
| 821 | return html`${help}${form}${flagged} | |
| 816 | 822 | ${when(listed?.ok === true, () => html`<div class="mt">${appMembersView(base, values.access, named)}</div>`)} |
| 817 | 823 | <div class="mt">${appVisitorsView(vitals)}</div> |
| 818 | 824 | <div class="mt">${statement}</div> |
| @@ -1149,6 +1155,7 @@ export async function appSettingsPage(ctx: Ctx): Promise<Response> { | ||
| 1149 | 1155 | egress?.ok ? egress.value : undefined, |
| 1150 | 1156 | blocked?.ok ? blocked.value : undefined, |
| 1151 | 1157 | needs?.ok ? needs.value : undefined, |
| 1158 | repo.template ? await templateProblem(ctx.app, repo) : undefined, | |
| 1152 | 1159 | ); |
| 1153 | 1160 | const rendering = performance.now(); |
| 1154 | 1161 | const response = settingsPageResponse(ctx, repo, "app", "App", view); |
test/repo-template-flag.test.ts +4 −2
| @@ -9,9 +9,9 @@ import { tmpdir } from "node:os"; | ||
| 9 | 9 | import { join } from "node:path"; |
| 10 | 10 | import { createApp, type App } from "../src/app.ts"; |
| 11 | 11 | import { addToCrew, createAgent } from "../src/actions/crew.ts"; |
| 12 | import { updateRepoSettings } from "../src/actions/repos.ts"; | |
| 12 | import { commitToBranch, updateRepoSettings } from "../src/actions/repos.ts"; | |
| 13 | 13 | import type { Agent } from "../src/core/agents.ts"; |
| 14 | import { createRepo, getRepoById, type Repo } from "../src/core/repos.ts"; | |
| 14 | import { createRepo, getRepo, getRepoById, type Repo } from "../src/core/repos.ts"; | |
| 15 | 15 | import { createToken } from "../src/core/tokens.ts"; |
| 16 | 16 | import { createUser, type User } from "../src/core/users.ts"; |
| 17 | 17 | import { templateSaid } from "../src/core/template_words.ts"; |
| @@ -95,6 +95,8 @@ beforeAll(async () => { | ||
| 95 | 95 | stranger = await make("stranger"); |
| 96 | 96 | pub = ok(await createRepo(app.db, app.reposRoot, { ownerId: owner.id, name: "starter", visibility: "public" })); |
| 97 | 97 | ok(await createRepo(app.db, app.reposRoot, { ownerId: owner.id, name: "secret", visibility: "private" })); |
| 98 | for (const r of [pub, getRepo(app.db, "maker", "secret")!]) | |
| 99 | ok(await commitToBranch(app, owner, r, { message: "seed", files: [{ path: "forge.json", content: '{"app":{"run":"bun main.ts"}}' }] })); | |
| 98 | 100 | bot = ok(await createAgent(app, founder, { username: "bot" })); |
| 99 | 101 | proveAll(app); |
| 100 | 102 | expect(addToCrew(app, founder, pub, "bot").ok).toBe(true); |
test/spawn-template-record.test.ts +1 −1
| @@ -53,7 +53,7 @@ describe("a forge remembers its template", () => { | ||
| 53 | 53 | auth.authorization = `Bearer ${rw}`; |
| 54 | 54 | const kit = await createRepo(app, a.value, { name: "kit", visibility: "public", description: "" }); |
| 55 | 55 | if (!kit.ok) throw new Error("repo"); |
| 56 | await commitToBranch(app, a.value, kit.value, { message: "seed", files: [{ path: "a.txt", content: "a" }] }); | |
| 56 | await commitToBranch(app, a.value, kit.value, { message: "seed", files: [{ path: "a.txt", content: "a" }, { path: "forge.json", content: '{"app":{"run":"bun main.ts"}}' }] }); | |
| 57 | 57 | const marked = await updateRepoSettings(app, a.value, kit.value, { template: true }); |
| 58 | 58 | if (!marked.ok) throw new Error("mark"); |
| 59 | 59 | const head = await runGit(["rev-parse", "HEAD"], { cwd: repoDir(app.reposRoot, "alice", "kit") }); |
test/spawn-template.test.ts +1 −1
| @@ -63,7 +63,7 @@ describe("a new forge from a template repository", () => { | ||
| 63 | 63 | for (const [name, visibility] of [["kit", "public"], ["plain", "public"], ["secret", "private"]] as const) { |
| 64 | 64 | const made = await createRepo(app, alice, { name, visibility }); |
| 65 | 65 | if (!made.ok) throw new Error(name); |
| 66 | await commitToBranch(app, alice, made.value, { message: "seed", files: [{ path: "kit.txt", content: name }] }); | |
| 66 | await commitToBranch(app, alice, made.value, { message: "seed", files: [{ path: "kit.txt", content: name }, { path: "forge.json", content: '{"app":{"run":"bun main.ts"}}' }] }); | |
| 67 | 67 | } |
| 68 | 68 | for (const name of ["kit", "secret"]) { |
| 69 | 69 | const r = getRepo(app.db, "alice", name)!; |
test/template-forge-json.test.ts added +219
| @@ -0,0 +1,219 @@ | ||
| 1 | /** | |
| 2 | * Marking a repository as a template runs its forge.json through the manifest's checks and names | |
| 3 | * the first thing wrong (#13304); one already marked is only flagged on its settings page. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, describe, expect, setDefaultTimeout, test } from "bun:test"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { commitToBranch, createRepo, updateRepoSettings } from "../src/actions/repos.ts"; | |
| 10 | import { templateProblem } from "../src/apps/template_problem.ts"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { getRepoById, type Repo } from "../src/core/repos.ts"; | |
| 13 | import { createUser, type User } from "../src/core/users.ts"; | |
| 14 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 15 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 16 | import { repoScreen } from "../src/tui/screens/repo.ts"; | |
| 17 | import { templateScreen } from "../src/tui/screens/template.ts"; | |
| 18 | import { local } from "../src/tui/screens/where.ts"; | |
| 19 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 20 | import { settleApp } from "./helpers/tui.ts"; | |
| 21 | import { quietLogs } from "./helpers/globals.ts"; | |
| 22 | import { tokenFor } from "./helpers/tokens.ts"; | |
| 23 | ||
| 24 | quietLogs(); | |
| 25 | setDefaultTimeout(30_000); | |
| 26 | ||
| 27 | let dir: string; | |
| 28 | let app: App; | |
| 29 | let servers: Servers; | |
| 30 | let admin: User; | |
| 31 | ||
| 32 | const make = async (name: string, forgeJson: string | undefined): Promise<Repo> => { | |
| 33 | const made = await createRepo(app, admin, { name, visibility: "public", description: "" }); | |
| 34 | if (!made.ok) throw new Error(name); | |
| 35 | const files = [{ path: "README.md", content: "x\n" }, ...(forgeJson === undefined ? [] : [{ path: "forge.json", content: forgeJson }])]; | |
| 36 | const done = await commitToBranch(app, admin, made.value, { message: "seed", files }); | |
| 37 | if (!done.ok) throw new Error(String(done.error)); | |
| 38 | return made.value; | |
| 39 | }; | |
| 40 | const fresh = (r: Repo): Repo => getRepoById(app.db, r.id)!; | |
| 41 | ||
| 42 | beforeAll(async () => { | |
| 43 | dir = await mkdtemp(join(tmpdir(), "forge-tplvalid-")); | |
| 44 | app = createApp({ dataDir: dir, port: 0 }); | |
| 45 | servers = await serve(app); | |
| 46 | const made = await createUser(app.db, { | |
| 47 | origin: "seed", trusted: true, username: "boss", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true, | |
| 48 | }); | |
| 49 | if (!made.ok) throw new Error(made.error); | |
| 50 | admin = made.value; | |
| 51 | }); | |
| 52 | ||
| 53 | afterAll(async () => { | |
| 54 | servers?.stop(); | |
| 55 | app?.close(); | |
| 56 | await rm(dir, { recursive: true, force: true }); | |
| 57 | }); | |
| 58 | ||
| 59 | describe("marking a template validates its forge.json", () => { | |
| 60 | test("a valid one is marked", async () => { | |
| 61 | const r = await make("good", '{"app":{"run":"bun main.ts","tty":"bun tui.ts"},"egress":["api.example.com"]}'); | |
| 62 | expect(await templateProblem(app, r)).toBeUndefined(); | |
| 63 | const done = await updateRepoSettings(app, admin, r, { template: true }); | |
| 64 | expect(done.ok).toBe(true); | |
| 65 | expect(fresh(r).template).toBe(true); | |
| 66 | }); | |
| 67 | ||
| 68 | test("an invalid one is refused, naming the first field, and stays unmarked", async () => { | |
| 69 | const r = await make("bad", '{"app":{"run":"bun main.ts"},"egress":["not a host!"]}'); | |
| 70 | const why = await templateProblem(app, r); | |
| 71 | expect(why).toContain("egress"); | |
| 72 | const done = await updateRepoSettings(app, admin, r, { template: true }); | |
| 73 | expect(!done.ok && done.error).toBe("template_invalid"); | |
| 74 | expect(fresh(r).template).toBe(false); | |
| 75 | const api = await fetch(`${servers.url}/api/v1/repos/boss/bad`, { | |
| 76 | method: "PATCH", | |
| 77 | headers: { authorization: `Bearer ${tokenFor(app, "boss", "admin")}`, "content-type": "application/json" }, | |
| 78 | body: JSON.stringify({ template: true }), | |
| 79 | }); | |
| 80 | expect(api.status).toBe(422); | |
| 81 | expect(JSON.stringify(await api.json())).toContain("egress"); | |
| 82 | expect(fresh(r).template).toBe(false); | |
| 83 | }); | |
| 84 | ||
| 85 | test("a bad run command is named", async () => { | |
| 86 | const r = await make("norun", '{"app":{"run":5}}'); | |
| 87 | expect(await templateProblem(app, r)).toMatch(/run/); | |
| 88 | expect((await updateRepoSettings(app, admin, r, { template: true })).ok).toBe(false); | |
| 89 | }); | |
| 90 | ||
| 91 | test("a missing forge.json is refused and says so", async () => { | |
| 92 | const r = await make("none", undefined); | |
| 93 | expect(await templateProblem(app, r)).toBe("forge.json: not found on the default branch"); | |
| 94 | expect((await updateRepoSettings(app, admin, r, { template: true })).ok).toBe(false); | |
| 95 | expect(fresh(r).template).toBe(false); | |
| 96 | }); | |
| 97 | ||
| 98 | test("unmarking is never refused, and a marked template that later fails is only flagged", async () => { | |
| 99 | const r = await make("later", '{"app":{"run":"bun main.ts"}}'); | |
| 100 | expect((await updateRepoSettings(app, admin, r, { template: true })).ok).toBe(true); | |
| 101 | const page = async (): Promise<string> => { | |
| 102 | const signin = await fetch(`${servers.url}/signin`, { | |
| 103 | method: "POST", headers: { origin: servers.url }, | |
| 104 | body: new URLSearchParams({ username: "boss", password: "a-good-passphrase" }), redirect: "manual", | |
| 105 | }); | |
| 106 | const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 107 | return await (await fetch(`${servers.url}/boss/later/settings/app`, { headers: { cookie } })).text(); | |
| 108 | }; | |
| 109 | expect(await page()).not.toContain("Flagged as a template:"); | |
| 110 | const broke = await commitToBranch(app, admin, fresh(r), { message: "break", files: [{ path: "forge.json", content: '{"app":{"run":5}}' }] }); | |
| 111 | expect(broke.ok).toBe(true); | |
| 112 | expect(fresh(r).template).toBe(true); | |
| 113 | const flagged = await page(); | |
| 114 | expect(flagged).toContain("Flagged as a template: forge.json"); | |
| 115 | // Saving settings that leave the mark alone is not blocked. | |
| 116 | expect((await updateRepoSettings(app, admin, fresh(r), { description: "still here" })).ok).toBe(true); | |
| 117 | expect((await updateRepoSettings(app, admin, fresh(r), { template: false })).ok).toBe(true); | |
| 118 | expect(fresh(r).template).toBe(false); | |
| 119 | }); | |
| 120 | }); | |
| 121 | ||
| 122 | describe("every door names the field", () => { | |
| 123 | const signedIn = async (): Promise<string> => { | |
| 124 | const signin = await fetch(`${servers.url}/signin`, { | |
| 125 | method: "POST", headers: { origin: servers.url }, | |
| 126 | body: new URLSearchParams({ username: "boss", password: "a-good-passphrase" }), redirect: "manual", | |
| 127 | }); | |
| 128 | return (signin.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 129 | }; | |
| 130 | const openTui = async (repo: Repo) => { | |
| 131 | const terminal = headlessTerminal(120, 40); | |
| 132 | const { app: tui, session } = createForgeApp( | |
| 133 | app, | |
| 134 | { sshUsername: admin.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: admin }, | |
| 135 | { terminal, exitHooks: false }, | |
| 136 | ); | |
| 137 | tui.start(); | |
| 138 | tui.ctx.push(repoScreen(session, tui.ctx, local(session, repo))); | |
| 139 | tui.ctx.push(templateScreen(session, tui.ctx, repo)); | |
| 140 | await settleApp(tui); | |
| 141 | return { | |
| 142 | text: () => tui.screen.toText(), | |
| 143 | press: async (k: string) => { terminal.feed(k); await settleApp(tui); }, | |
| 144 | stop: () => tui.stop?.(), | |
| 145 | }; | |
| 146 | }; | |
| 147 | ||
| 148 | test("the MCP repo_settings tool answers invalid with the field", async () => { | |
| 149 | const r = await make("mcpbad", '{"app":{"run":"bun main.ts"},"egress":["not a host!"]}'); | |
| 150 | const res = await fetch(`${servers.url}/mcp`, { | |
| 151 | method: "POST", | |
| 152 | headers: { | |
| 153 | "content-type": "application/json", accept: "application/json, text/event-stream", | |
| 154 | authorization: `Bearer ${tokenFor(app, "boss", "admin")}`, | |
| 155 | }, | |
| 156 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "repo_settings", arguments: { repo: "boss/mcpbad", template: true } } }), | |
| 157 | }); | |
| 158 | const body = (await res.json()) as any; | |
| 159 | expect(body.result.isError).toBe(true); | |
| 160 | const text: string = body.result.content[0].text; | |
| 161 | expect(text).toContain("egress"); | |
| 162 | expect(text).toContain("invalid"); | |
| 163 | expect(fresh(r).template).toBe(false); | |
| 164 | }); | |
| 165 | ||
| 166 | test("the settings form flashes why it did not mark", async () => { | |
| 167 | const r = await make("flashbad", '{"app":{"run":"bun main.ts"},"egress":["not a host!"]}'); | |
| 168 | const cookie = await signedIn(); | |
| 169 | const page = await fetch(`${servers.url}/boss/flashbad/settings/app`, { headers: { cookie } }); | |
| 170 | const html = await page.text(); | |
| 171 | const csrf = /name="csrf" value="([^"]+)"/.exec(html)?.[1]; | |
| 172 | const body = new URLSearchParams({ card: "template", templateShown: "1", template: "on", ...(csrf ? { csrf } : {}) }); | |
| 173 | const sent = await fetch(`${servers.url}/boss/flashbad/settings`, { | |
| 174 | method: "POST", headers: { cookie, origin: servers.url }, body, redirect: "manual", | |
| 175 | }); | |
| 176 | expect(sent.status).toBe(303); | |
| 177 | expect(decodeURIComponent(sent.headers.get("set-cookie") ?? "")).toContain("Not marked as a template. forge.json: egress"); | |
| 178 | expect(fresh(r).template).toBe(false); | |
| 179 | }); | |
| 180 | ||
| 181 | test("the terminal's t toasts the field, and a marked template that fails shows Flagged", async () => { | |
| 182 | const r = await make("tuibad", '{"app":{"run":"bun main.ts"},"egress":["not a host!"]}'); | |
| 183 | const h = await openTui(r); | |
| 184 | await h.press("t"); | |
| 185 | expect(h.text()).toContain("egress"); | |
| 186 | expect(fresh(r).template).toBe(false); | |
| 187 | h.stop(); | |
| 188 | ||
| 189 | const m = await make("tuiflag", '{"app":{"run":"bun main.ts"}}'); | |
| 190 | expect((await updateRepoSettings(app, admin, m, { template: true })).ok).toBe(true); | |
| 191 | const ok = await openTui(fresh(m)); | |
| 192 | expect(ok.text()).not.toContain("Flagged:"); | |
| 193 | ok.stop(); | |
| 194 | await commitToBranch(app, admin, fresh(m), { message: "break", files: [{ path: "forge.json", content: '{"app":{"run":5}}' }] }); | |
| 195 | const flagged = await openTui(fresh(m)); | |
| 196 | expect(flagged.text()).toContain("Flagged: forge.json"); | |
| 197 | flagged.stop(); | |
| 198 | }); | |
| 199 | ||
| 200 | test("a screen that is gone ignores a late look", async () => { | |
| 201 | const m = await make("tuigone", '{"app":{"run":"bun main.ts"}}'); | |
| 202 | expect((await updateRepoSettings(app, admin, m, { template: true })).ok).toBe(true); | |
| 203 | const terminal = headlessTerminal(120, 40); | |
| 204 | const { app: tui, session } = createForgeApp( | |
| 205 | app, | |
| 206 | { sshUsername: admin.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: admin }, | |
| 207 | { terminal, exitHooks: false }, | |
| 208 | ); | |
| 209 | tui.start(); | |
| 210 | let invalidated = 0; | |
| 211 | const screen = templateScreen(session, { ...tui.ctx, invalidate: () => void invalidated++ } as typeof tui.ctx, fresh(m)); | |
| 212 | const gone = new AbortController(); | |
| 213 | const loading = screen.load?.(gone.signal); | |
| 214 | gone.abort(); | |
| 215 | await loading; | |
| 216 | expect(invalidated).toBe(0); | |
| 217 | tui.stop?.(); | |
| 218 | }); | |
| 219 | }); |
test/tui-newforge.test.ts +2 −1
| @@ -6,7 +6,7 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | ||
| 6 | 6 | import { mkdtemp, readdir, rm } from "node:fs/promises"; |
| 7 | 7 | import { tmpdir } from "node:os"; |
| 8 | 8 | import { join } from "node:path"; |
| 9 | import { createRepo, updateRepoSettings } from "../src/actions/repos.ts"; | |
| 9 | import { commitToBranch, createRepo, updateRepoSettings } from "../src/actions/repos.ts"; | |
| 10 | 10 | import { createApp, type App } from "../src/app.ts"; |
| 11 | 11 | import { getRepo } from "../src/core/repos.ts"; |
| 12 | 12 | import { createUser, type User } from "../src/core/users.ts"; |
| @@ -62,6 +62,7 @@ beforeAll(async () => { | ||
| 62 | 62 | for (const [name, visibility] of [["kit", "public"], ["plain", "public"], ["secret", "private"]] as const) { |
| 63 | 63 | const made = await createRepo(app, admin, { name, visibility }); |
| 64 | 64 | if (!made.ok) throw new Error(name); |
| 65 | await commitToBranch(app, admin, made.value, { message: "seed", files: [{ path: "forge.json", content: '{"app":{"run":"bun main.ts"}}' }] }); | |
| 65 | 66 | } |
| 66 | 67 | for (const name of ["kit", "secret"]) { |
| 67 | 68 | const marked = await updateRepoSettings(app, admin, getRepo(app.db, "alice", name)!, { template: true }); |
new above
offline