Public: anyone can read this; the crew can change it.
The forge is a developer's file system: every app's database and the API spec, first-party (web, terminal app, MCP) #16743
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/7578-the-forge-is-a-developer-s-file-system-e → main 0 commits fork
10 files
changed +435
−15
docs/features/data-browser.md +6
| @@ -27,3 +27,9 @@ API and MCP by repository (`data/repo_scope.ts`, `http/api/data.ts`): `GET /api/ | ||
| 27 | 27 | Three doors, one body (`src/web/pages/data_view.ts`): `/data` (every file you may see), `/admin/data` (the forge's own database, admins; the Forge data button on `/data`) and `/:owner/:name/data` (an app's Data tab for its writers: environments → files → tables → rows; a reader gets the 404). Rows sort by header (`sort`, `dir`), filter by text on one column or all (`q`, `col`), JSON cells are pretty-printed, and a copy button per row puts it on the clipboard as JSON. Sealed columns show `••••••` and cannot be sorted or searched. The SQL box is a GET form (`sql`, capped at 4,000 characters), so a query is an address to share; it shows the rows and the elapsed ms. The sorted column carries `aria-sort` and a muted arrow from CSS; a wide grid scrolls sideways only. Not done: saved queries, export, editing rows. |
| 28 | 28 | |
| 29 | 29 | Cost of a query: `query` also returns `rowsRead` (rows the query produced, the one that tripped a cap included) and `elapsedMs` (at least 1). The page prints them as one muted line under the table (`N rows read · X ms`), the terminal's `:` result shows the same in its header line, and the MCP `data` answer with `sql` carries both fields. They count rows the query produced, not rows SQLite scanned. |
| 30 | ||
| 31 | ## The API spec as a file (#7578) | |
| 32 | ||
| 33 | MCP `data` with `spec: true` lists operations (`area`, `method`, `path`, `summary`; 300 at most, with `total` saying how many matched) for what the forge's contract says as your role may call it; add `q` to narrow by words, or `repo` for the document that app serves at `/openapi.json` (the same door as its API tab: a 404 where you may not enter the app, "serves no /openapi.json" when it has none). `src/data/spec_scope.ts` reads it through `reference` (`src/contract/reference.ts`), the reading the web `/api` page and the terminal API screen (`src/tui/screens/api.ts`) already use. | |
| 34 | ||
| 35 | Three doors, one reading. In the data tree the spec is a file named `openapi.json`: the forge's own at the bottom of `/data` and of the terminal's Data screen (only for someone who sees any file there), and each app's after its environments (the app's Data tab on the web, the app node in the terminal; Enter or `l` opens it, `y` yanks `METHOD /path`). On the web it is `?spec=1` on `/data` and on `/:owner/:name/data`; a reader and a guest get the same 404 or sign-in as for the databases, and an app's document is asked through `appSpec`, which still checks `canEnterApp`. It reads the app's production environment only; a preview's document is not read here. The canonical place to read and try operations stays `/api` and `/:owner/:name/api` (and the terminal's API screen): the `openapi.json` nodes and the MCP tool link to them and add no second listing, only the same `reference` rows. |
src/data/spec_scope.ts added +64
| @@ -0,0 +1,64 @@ | ||
| 1 | /** | |
| 2 | * The API spec as a file of the forge's tree (#7578): what the MCP `data` tool answers with | |
| 3 | * `spec: true`. Without a repository, the forge's own OpenAPI document as this account may see it; | |
| 4 | * with one, the document the app serves at `/openapi.json`, behind the same door as its API tab | |
| 5 | * (`canEnterApp`, a 404 otherwise). Plain rows out: area, method, path, summary, nothing from the | |
| 6 | * app that is not cut to the reader's length. | |
| 7 | * | |
| 8 | * One reading of the spec: `reference` (`contract/reference.ts`), which the web `/api` page and the | |
| 9 | * terminal API screen draw too. They stay the canonical places to read and try the operations; | |
| 10 | * this module only turns the same reading into rows for the MCP `data` tool and the data tree's | |
| 11 | * `openapi.json` nodes (web and terminal), and never lists operations by any other path. | |
| 12 | */ | |
| 13 | ||
| 14 | import type { App } from "../app.ts"; | |
| 15 | import { knownSpec, refreshSpec } from "../apps/api_spec.ts"; | |
| 16 | import { appsRuntime } from "../apps/runtime.ts"; | |
| 17 | import { narrow, reference, type Area } from "../contract/reference.ts"; | |
| 18 | import { openapiText, roleOf } from "../contract/served.ts"; | |
| 19 | import { getAppByRepo } from "../core/apps.ts"; | |
| 20 | import { cappedQuery } from "../core/query_limit.ts"; | |
| 21 | import { canEnterApp, type Repo } from "../core/repos.ts"; | |
| 22 | import type { User } from "../core/users.ts"; | |
| 23 | import { announcedOr } from "../kernel/version.ts"; | |
| 24 | ||
| 25 | /** Operations one answer lists: the rest is named, never silently dropped. */ | |
| 26 | export const SPEC_ROWS = 300; | |
| 27 | ||
| 28 | export interface SpecRow { | |
| 29 | readonly area: string; | |
| 30 | readonly method: string; | |
| 31 | readonly path: string; | |
| 32 | readonly summary: string; | |
| 33 | } | |
| 34 | ||
| 35 | export interface SpecAnswer { | |
| 36 | readonly total: number; | |
| 37 | readonly shown: number; | |
| 38 | readonly operations: readonly SpecRow[]; | |
| 39 | } | |
| 40 | ||
| 41 | const answer = (areas: readonly Area[], q: unknown): SpecAnswer => { | |
| 42 | const rows = narrow(areas, cappedQuery(typeof q === "string" ? q : null)).flatMap((a) => | |
| 43 | a.operations.map((o) => ({ area: a.name, method: o.method.toUpperCase(), path: o.path, summary: o.summary })), | |
| 44 | ); | |
| 45 | const operations = rows.slice(0, SPEC_ROWS); | |
| 46 | return { total: rows.length, shown: operations.length, operations }; | |
| 47 | }; | |
| 48 | ||
| 49 | /** The forge's own document, cut to what `user` may call. */ | |
| 50 | export const forgeSpec = (app: App, user: User, q?: unknown): SpecAnswer => | |
| 51 | answer(reference(JSON.parse(openapiText(app.config.url ?? "http://localhost", announcedOr(), roleOf({ user })).text)), q); | |
| 52 | ||
| 53 | /** | |
| 54 | * An app's own document: `undefined` when the viewer may not enter the app, the string `none` when | |
| 55 | * it serves no document. It asks the app's production environment (the port `envStatus` gives for | |
| 56 | * it): a preview's document is not read here. | |
| 57 | */ | |
| 58 | export async function appSpec(app: App, user: User, repo: Repo, q?: unknown): Promise<SpecAnswer | "none" | undefined> { | |
| 59 | const record = getAppByRepo(app.db, repo.id); | |
| 60 | if (record === undefined || !canEnterApp(app.db, repo, record, user)) return undefined; | |
| 61 | const known = knownSpec(record.id); | |
| 62 | const doc = known !== undefined ? known : await refreshSpec(record, appsRuntime(app)?.envStatus(record, "production")?.port); | |
| 63 | return doc === null ? "none" : answer(reference(doc), q); | |
| 64 | } |
src/data/tree.ts +29 −3
| @@ -5,9 +5,18 @@ | ||
| 5 | 5 | */ |
| 6 | 6 | import { PAGE_SIZE, rows as readRows, tables as readTables, type RowsResult, type TableInfo } from "./browse.ts"; |
| 7 | 7 | import { rowObject, cellLine, type Cell } from "./shape.ts"; |
| 8 | import type { SpecRow } from "./spec_scope.ts"; | |
| 8 | 9 | import type { Source } from "./sources.ts"; |
| 9 | 10 | |
| 10 | export type Kind = "repo" | "app" | "env" | "file" | "table" | "row"; | |
| 11 | export type Kind = "repo" | "app" | "env" | "file" | "table" | "row" | "spec" | "op"; | |
| 12 | ||
| 13 | /** | |
| 14 | * The API spec as files of the tree (#7578), when a door asks for them: the forge's (key `forge`) | |
| 15 | * and each app's (key `owner/name`), each read as plain rows, or `none` when the app serves none. | |
| 16 | * A key absent from the map is not read yet. A door that gives none shows no spec nodes, and a | |
| 17 | * viewer with no file at all sees none either. | |
| 18 | */ | |
| 19 | export type Specs = ReadonlyMap<string, readonly SpecRow[] | "none">; | |
| 11 | 20 | |
| 12 | 21 | export interface Node { |
| 13 | 22 | /** Unique path; a child's key starts with its parent's. */ |
| @@ -22,6 +31,10 @@ export interface Node { | ||
| 22 | 31 | readonly total?: number; |
| 23 | 32 | /** A row's JSON, masked as every read is. */ |
| 24 | 33 | readonly json?: Record<string, Cell>; |
| 34 | /** A spec node: the repository it belongs to (`owner/name`), undefined for the forge's own. */ | |
| 35 | readonly repo?: string; | |
| 36 | /** An operation's method and path, for `y`. */ | |
| 37 | readonly op?: SpecRow; | |
| 25 | 38 | } |
| 26 | 39 | |
| 27 | 40 | const SEP = "\u0001"; |
| @@ -52,8 +65,19 @@ export function visible( | ||
| 52 | 65 | open: ReadonlySet<string>, |
| 53 | 66 | reads: Reads = newReads(), |
| 54 | 67 | page: ReadonlyMap<string, number> = new Map(), |
| 68 | specs?: Specs, | |
| 55 | 69 | ): Node[] { |
| 56 | 70 | const out: Node[] = []; |
| 71 | const specNode = (key: string, depth: number, repo: string | undefined) => { | |
| 72 | const read = specs!.get(repo ?? "forge"); | |
| 73 | const node: Node = { key, kind: "spec", depth, label: "openapi.json", ...(repo === undefined ? {} : { repo }) }; | |
| 74 | out.push(node); | |
| 75 | if (!open.has(key)) return; | |
| 76 | if (read === undefined) return void out.push({ key: join(key, "…"), kind: "op", depth: depth + 1, label: "reading…" }); | |
| 77 | if (read === "none") return void out.push({ key: join(key, "none"), kind: "op", depth: depth + 1, label: "this app serves no /openapi.json right now" }); | |
| 78 | for (const [i, o] of read.entries()) | |
| 79 | out.push({ key: join(key, String(i)), kind: "op", depth: depth + 1, label: `${o.method.padEnd(6)}${o.path} ${o.summary}`.trimEnd(), op: o }); | |
| 80 | }; | |
| 57 | 81 | const tableNodes = (file: Node, depth: number) => { |
| 58 | 82 | const source = file.source!; |
| 59 | 83 | let list = reads.tables.get(file.key); |
| @@ -117,13 +141,15 @@ export function visible( | ||
| 117 | 141 | if (!open.has(ek)) continue; |
| 118 | 142 | for (const s of ofEnv) fileNode(s, join(ek, `file:${s.id}`), 3, s.where!.file); |
| 119 | 143 | } |
| 144 | if (specs) specNode(join(ak, "spec"), 2, repo); | |
| 120 | 145 | } |
| 121 | 146 | } |
| 147 | if (specs && sources.length > 0) specNode(join("", "spec:forge"), 0, undefined); | |
| 122 | 148 | return out; |
| 123 | 149 | } |
| 124 | 150 | |
| 125 | /** Whether a node opens at all (a row is a leaf). */ | |
| 126 | export const opens = (n: Node): boolean => n.kind !== "row"; | |
| 151 | /** Whether a node opens at all (a row or an operation is a leaf). */ | |
| 152 | export const opens = (n: Node): boolean => n.kind !== "row" && n.kind !== "op"; | |
| 127 | 153 | |
| 128 | 154 | /** |
| 129 | 155 | * `text` keeps the lines that contain it (any case) and the lines above |
src/http/mcp/tools/data.ts +14 −1
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | import { rows, tables } from "../../../data/browse.ts"; |
| 2 | 2 | import { findSource, listSources, type Source } from "../../../data/sources.ts"; |
| 3 | 3 | import { isFailure, parsePage, pickSource, repoSources, rowPage, runSql, sourceList, tableList } from "../../../data/repo_scope.ts"; |
| 4 | import { appSpec, forgeSpec } from "../../../data/spec_scope.ts"; | |
| 4 | 5 | import { exportCsv } from "../../../data/export_csv.ts"; |
| 5 | 6 | import { bad, good, isAnswer, repoArg, type Tool } from "../shared.ts"; |
| 6 | 7 | |
| @@ -9,7 +10,7 @@ const CSV_ROWS = 1000; | ||
| 9 | 10 | |
| 10 | 11 | export const tool: Tool = { |
| 11 | 12 | name: "data", |
| 12 | doc: "`{ repo, env?, file?, table?, sql? }` as `GET …/data`: an app's databases, then `env`+`file`: its tables, `table`: rows, `sql`: one read-only SELECT; its writers only. Without `repo`: the SQLite files you may read (the forge's own for an admin; each app's per environment for its writers), with `source`: its tables and row counts, with `table` (and `page`): a page of rows (`format` csv: 1,000 as CSV), with `sql`: a read-only SELECT (5 s, 1,000 rows); secret columns are masked", | |
| 13 | doc: "`{ repo, env?, file?, table?, sql? }` as `GET …/data`: an app's databases, then `env`+`file`: its tables, `table`: rows, `sql`: one read-only SELECT; its writers only. Without `repo`: the SQLite files you may read (the forge's own for an admin; each app's per environment for its writers), with `source`: its tables and row counts, with `table` (and `page`): a page of rows (`format` csv: 1,000 as CSV), with `sql`: a read-only SELECT (5 s, 1,000 rows); secret columns are masked; `spec: true` (+`q`, `repo`): the API operations, the forge's or the app's", | |
| 13 | 14 | description: "Read SQLite files you may see: tables, rows, read-only SQL; secrets masked.", |
| 14 | 15 | inputSchema: { |
| 15 | 16 | type: "object", |
| @@ -22,6 +23,8 @@ export const tool: Tool = { | ||
| 22 | 23 | page: { type: "integer" }, |
| 23 | 24 | sql: { type: "string" }, |
| 24 | 25 | format: { type: "string" }, |
| 26 | spec: { type: "boolean" }, | |
| 27 | q: { type: "string" }, | |
| 25 | 28 | }, |
| 26 | 29 | }, |
| 27 | 30 | writes: false, |
| @@ -41,6 +44,16 @@ export const tool: Tool = { | ||
| 41 | 44 | if (out.ok) return good({ format: "csv", rows: out.rows, truncated: out.truncated, csv: out.csv }); |
| 42 | 45 | return out.error === "rate" ? bad("rate_limited", `too many queries: try again in ${out.retryAfter} s`) : bad("not_found", "no such table"); |
| 43 | 46 | }; |
| 47 | if (args["spec"] !== undefined && typeof args["spec"] !== "boolean") return bad("invalid", "`spec` is true or false"); | |
| 48 | if (args["q"] !== undefined && typeof args["q"] !== "string") return bad("invalid", "`q` is text"); | |
| 49 | if (args["spec"] === true) { | |
| 50 | if (args["repo"] === undefined) return good(forgeSpec(ctx.app, user, args["q"])); | |
| 51 | const repo = repoArg(ctx, user, args); | |
| 52 | if (isAnswer(repo)) return repo; | |
| 53 | const spec = await appSpec(ctx.app, user, repo, args["q"]); | |
| 54 | if (spec === undefined) return bad("not_found", "no such app or repository (owner/name)"); | |
| 55 | return spec === "none" ? bad("not_found", "this app serves no /openapi.json right now") : good(spec); | |
| 56 | } | |
| 44 | 57 | const page = args["page"]; |
| 45 | 58 | const pageNo = page === undefined || typeof page !== "number" ? undefined : parsePage(page); |
| 46 | 59 | if (page !== undefined && pageNo === undefined) return bad("invalid", "`page` is a whole number from 0 to 1000"); |
src/tui/screens/data.ts +37 −6
| @@ -6,8 +6,10 @@ | ||
| 6 | 6 | * Keys: j/k move, l or Enter opens, h closes (or goes up), `/` filters the |
| 7 | 7 | * lines shown, `:` asks the file under the cursor a read-only question (the |
| 8 | 8 | * same SELECT-only caps as the tool), `y` yanks a row as JSON. Secrets stay |
| 9 | * masked: rows come from the masked reads. `e` copies the table under the cursor as CSV | |
| 10 | * (`exportCsv`, the page download's read, 1,000 rows at most here). | |
| 9 | * masked: rows come from the masked reads. An `openapi.json` node (the forge's, and one per app) | |
| 10 | * lists the API operations as plain rows (`spec_scope.ts`, behind the API tab's door); `y` yanks | |
| 11 | * one as `METHOD /path`. `e` copies the table under the cursor as CSV (`exportCsv`, the page | |
| 12 | * download's read, 1,000 rows at most here). | |
| 11 | 13 | */ |
| 12 | 14 | |
| 13 | 15 | import { query, type QueryResult } from "../../data/query.ts"; |
| @@ -16,7 +18,9 @@ import { listSources, maySeeData } from "../../data/sources.ts"; | ||
| 16 | 18 | import { sqlWindow } from "../../data/sql_window.ts"; |
| 17 | 19 | import { PAGE_SIZE, topValues, type TopValue } from "../../data/browse.ts"; |
| 18 | 20 | import { exportCsv } from "../../data/export_csv.ts"; |
| 21 | import { appSpec, forgeSpec, type SpecRow } from "../../data/spec_scope.ts"; | |
| 19 | 22 | import { filtered, newReads, opens, pageCount, parentKey, visible, type Node } from "../../data/tree.ts"; |
| 23 | import { getRepo } from "../../core/repos.ts"; | |
| 20 | 24 | import type { Ctx, Screen } from "../app/app.ts"; |
| 21 | 25 | import { binding } from "../app/keys.ts"; |
| 22 | 26 | import type { KeyEvent } from "../term/input.ts"; |
| @@ -129,6 +133,30 @@ export function dataScreen(session: Session, ctx: Ctx): Screen { | ||
| 129 | 133 | // Built once and rebuilt only when `open`, a page, the filter or a reload changes it. |
| 130 | 134 | const pages = new Map<string, number>(); |
| 131 | 135 | let reads = newReads(); |
| 136 | // The spec nodes' readings, by `forge` or `owner/name`; the forge's is sync, an app's is asked | |
| 137 | // once. | |
| 138 | const specs = new Map<string, readonly SpecRow[] | "none">(); | |
| 139 | const asking = new Set<string>(); | |
| 140 | /** Read the spec node's document once, behind the same door as the API tab. */ | |
| 141 | function readSpec(n: Node) { | |
| 142 | const key = n.repo ?? "forge"; | |
| 143 | if (specs.has(key) || asking.has(key)) return; | |
| 144 | if (n.repo === undefined) { | |
| 145 | specs.set(key, session.user ? forgeSpec(session.app, session.user).operations : []); | |
| 146 | return; | |
| 147 | } | |
| 148 | const [owner, name] = n.repo.split("/"); | |
| 149 | const repo = owner && name ? getRepo(session.app.db, owner, name) : undefined; | |
| 150 | if (!repo || !session.user) return void specs.set(key, "none"); | |
| 151 | asking.add(key); | |
| 152 | ctx.track( | |
| 153 | appSpec(session.app, session.user, repo).then((got) => { | |
| 154 | asking.delete(key); | |
| 155 | specs.set(key, got === undefined || got === "none" ? "none" : got.operations); | |
| 156 | dirty(true); | |
| 157 | }), | |
| 158 | ); | |
| 159 | } | |
| 132 | 160 | let files: ReturnType<typeof listSources> | undefined; |
| 133 | 161 | let built: Node[] | undefined; |
| 134 | 162 | let shown: Node[] | undefined; |
| @@ -139,7 +167,7 @@ export function dataScreen(session: Session, ctx: Ctx): Screen { | ||
| 139 | 167 | const lines = (): Node[] => { |
| 140 | 168 | if (shown) return shown; |
| 141 | 169 | files ??= listSources(session.app.db, session.app.config.dataDir, session.user); |
| 142 | built ??= visible(files, open, reads, pages); | |
| 170 | built ??= visible(files, open, reads, pages, specs); | |
| 143 | 171 | return (shown = filtered(built, filter)); |
| 144 | 172 | }; |
| 145 | 173 | const reload = () => { |
| @@ -213,7 +241,7 @@ export function dataScreen(session: Session, ctx: Ctx): Screen { | ||
| 213 | 241 | binding(["h", "l"], "close / open"), |
| 214 | 242 | binding("/", "filter"), |
| 215 | 243 | binding(":", "SQL"), |
| 216 | binding("y", "yank row as JSON"), | |
| 244 | binding("y", "yank row as JSON or operation"), | |
| 217 | 245 | binding("e", "export table as CSV"), |
| 218 | 246 | binding("v", "common values of a column"), |
| 219 | 247 | binding(["n", "p"], `page of ${PAGE_SIZE}`), |
| @@ -267,7 +295,7 @@ export function dataScreen(session: Session, ctx: Ctx): Screen { | ||
| 267 | 295 | else ctx.pop(); |
| 268 | 296 | } else if (e.key === "j" || e.key === "down") at = Math.min(Math.max(0, lines().length - 1), at + 1); |
| 269 | 297 | else if (e.key === "k" || e.key === "up") at = Math.max(0, at - 1); |
| 270 | else if ((e.key === "l" || e.key === "right" || e.key === "enter") && n && opens(n)) (open.add(n.key), dirty(true)); | |
| 298 | else if ((e.key === "l" || e.key === "right" || e.key === "enter") && n && opens(n)) (open.add(n.key), n.kind === "spec" && readSpec(n), dirty(true)); | |
| 271 | 299 | else if (e.key === "h" || e.key === "left") { |
| 272 | 300 | if (n && open.has(n.key)) (open.delete(n.key), dirty(true)); |
| 273 | 301 | else if (n) { |
| @@ -293,7 +321,10 @@ export function dataScreen(session: Session, ctx: Ctx): Screen { | ||
| 293 | 321 | ctx.toast("Reloaded."); |
| 294 | 322 | } else if (e.key === "e") exportTable(n); |
| 295 | 323 | else if (e.key === "y") { |
| 296 | if (n?.json) { | |
| 324 | if (n?.op) { | |
| 325 | ctx.copy(`${n.op.method} ${n.op.path}`); | |
| 326 | ctx.toast("Operation sent to your clipboard."); | |
| 327 | } else if (n?.json) { | |
| 297 | 328 | ctx.copy(JSON.stringify(n.json)); |
| 298 | 329 | ctx.toast("Row sent to your clipboard as JSON."); |
| 299 | 330 | } else ctx.toast("Move onto a row to yank it."); |
src/web/pages/data.ts +7 −2
| @@ -10,6 +10,7 @@ import { getAppByRepo } from "../../core/apps.ts"; | ||
| 10 | 10 | import { canWrite } from "../../core/repos.ts"; |
| 11 | 11 | import { EXPORT_ROWS } from "../../data/browse.ts"; |
| 12 | 12 | import { exportCsv } from "../../data/export_csv.ts"; |
| 13 | import { appSpec, forgeSpec } from "../../data/spec_scope.ts"; | |
| 13 | 14 | import { sqlWindow } from "../../data/sql_window.ts"; |
| 14 | 15 | import { listSources, maySeeData } from "../../data/sources.ts"; |
| 15 | 16 | import type { Ctx } from "../../http/context.ts"; |
| @@ -51,7 +52,8 @@ export async function dataPage(ctx: Ctx): Promise<Response> { | ||
| 51 | 52 | const { db, config } = ctx.app; |
| 52 | 53 | if (!maySeeData(db, viewer)) return refuse(ctx); |
| 53 | 54 | const sources = listSources(db, config.dataDir, viewer); |
| 54 | return draw(ctx, { path: "/data", sources, sqlWait: () => sqlWindow(ctx.app, viewer.id) }, "Data", pageHead("Data", { sub: PURPOSE, ...(viewer.isAdmin ? { actions: btn("Forge data", { href: "/admin/data", size: "sm" }) } : {}) })); | |
| 55 | const spec = { api: "/api", ...(ctx.url.searchParams.get("spec") === "1" ? { read: forgeSpec(ctx.app, viewer, ctx.url.searchParams.get("q")) } : {}) }; | |
| 56 | return draw(ctx, { path: "/data", sources, spec, sqlWait: () => sqlWindow(ctx.app, viewer.id) }, "Data", pageHead("Data", { sub: PURPOSE, ...(viewer.isAdmin ? { actions: btn("Forge data", { href: "/admin/data", size: "sm" }) } : {}) })); | |
| 55 | 57 | } |
| 56 | 58 | |
| 57 | 59 | // GET /admin/data — the forge's own database (the admin gate has already refused non-admins). |
| @@ -73,9 +75,12 @@ export async function appDataPage(ctx: Ctx): Promise<Response> { | ||
| 73 | 75 | const viewer = ctx.auth.user; |
| 74 | 76 | const sources = listSources(ctx.app.db, ctx.app.config.dataDir, viewer).filter((s) => s.id.startsWith(`app:${record.id}:`)); |
| 75 | 77 | const scope = localScope(ctx, repo); |
| 78 | const base = `/${repo.ownerName}/${repo.name}`; | |
| 79 | const read = ctx.url.searchParams.get("spec") === "1" ? await appSpec(ctx.app, viewer, repo) : undefined; | |
| 80 | if (read === undefined && ctx.url.searchParams.get("spec") === "1") return refuse(ctx); | |
| 76 | 81 | return draw( |
| 77 | 82 | ctx, |
| 78 | { path: `/${repo.ownerName}/${repo.name}/data`, sources, byEnv: true, sqlWait: () => sqlWindow(ctx.app, viewer.id) }, | |
| 83 | { path: `${base}/data`, sources, byEnv: true, spec: { api: `${base}/api`, ...(read === undefined ? {} : { read }) }, sqlWait: () => sqlWindow(ctx.app, viewer.id) }, | |
| 79 | 84 | `Data · ${repo.name}`, |
| 80 | 85 | scopeHeader(ctx, scope, "data"), |
| 81 | 86 | { crumbs: scope.crumbs, palette: scope.palette }, |
src/web/pages/data_view.ts +21 −3
| @@ -10,8 +10,9 @@ | ||
| 10 | 10 | import { PAGE_SIZE, rows, tables, topValues, type RowsResult } from "../../data/browse.ts"; |
| 11 | 11 | import { query } from "../../data/query.ts"; |
| 12 | 12 | import type { Source } from "../../data/sources.ts"; |
| 13 | import type { SpecAnswer } from "../../data/spec_scope.ts"; | |
| 13 | 14 | import { html, type Html } from "../html.ts"; |
| 14 | import { btn, field, iconBtn, pager, row } from "../ui.ts"; | |
| 15 | import { btn, field, iconBtn, pager, row, rowList } from "../ui.ts"; | |
| 15 | 16 | import { emptyList } from "../empty_words.ts"; |
| 16 | 17 | |
| 17 | 18 | /** Longest SQL an address may carry. */ |
| @@ -27,6 +28,12 @@ export interface DataView { | ||
| 27 | 28 | readonly byEnv?: boolean; |
| 28 | 29 | /** Asked before a SQL run: seconds to wait when this person has run too many, else undefined. */ |
| 29 | 30 | readonly sqlWait?: () => number | undefined; |
| 31 | /** | |
| 32 | * The `openapi.json` file of this door's tree (#7578): its operations as `spec_scope.ts` reads | |
| 33 | * them (`none`: the app serves no document), and where the canonical `/api` page for them is. | |
| 34 | * Read by the door only when `?spec=1` asks; a door with no spec gives none. | |
| 35 | */ | |
| 36 | readonly spec?: { readonly api: string; readonly read?: SpecAnswer | "none" }; | |
| 30 | 37 | } |
| 31 | 38 | |
| 32 | 39 | const url = (path: string, params: Record<string, string | number | undefined>): string => { |
| @@ -92,6 +99,17 @@ export async function dataBody(view: DataView, q: URLSearchParams): Promise<Html | ||
| 92 | 99 | const source = chosen === null ? undefined : sources.find((s) => s.id === chosen); |
| 93 | 100 | if (chosen !== null && !source) return undefined; |
| 94 | 101 | |
| 102 | if (view.spec !== undefined && q.get("spec") === "1") { | |
| 103 | const { read, api } = view.spec; | |
| 104 | const back = btn("Databases", { href: path, size: "sm", variant: "outline" }); | |
| 105 | if (read === undefined || read === "none") | |
| 106 | return html`<h2>openapi.json</h2><p class="muted">This app serves no /openapi.json right now.</p>${back}`; | |
| 107 | return html`<h2>openapi.json</h2> | |
| 108 | ${grid(["Area", "Method", "Path", "Summary"], read.operations.map((o) => [o.area, o.method, o.path, o.summary]), "API operations", (c) => html`<th scope="col">${c}</th>`, false)} | |
| 109 | <p class="muted small">${String(read.shown)} of ${String(read.total)} operations. Read and try them on <a href="${api}">the API page</a>.</p> | |
| 110 | ${back}`; | |
| 111 | } | |
| 112 | const specRow = view.spec === undefined ? null : rowList([row({ href: url(path, { spec: 1 }), title: "openapi.json", meta: html`The API operations` })]); | |
| 95 | 113 | const fileRow = (s: Source) => |
| 96 | 114 | row({ href: url(path, { source: s.id }), title: view.byEnv ? (s.id.split(":").slice(3).join(":") || s.label) : s.label, current: s.id === source?.id }); |
| 97 | 115 | const envOf = (s: Source) => s.id.split(":")[2] ?? ""; |
| @@ -105,12 +123,12 @@ export async function dataBody(view: DataView, q: URLSearchParams): Promise<Html | ||
| 105 | 123 | : sources.length === 1 && source |
| 106 | 124 | ? html`` |
| 107 | 125 | : html`<ul class="list">${sources.map(fileRow)}</ul>`; |
| 108 | if (!source) return files; | |
| 126 | if (!source) return html`${specRow}${files}`; | |
| 109 | 127 | |
| 110 | 128 | const tableName = q.get("table"); |
| 111 | 129 | const sql = (q.get("sql") ?? "").slice(0, SQL_MAX); |
| 112 | 130 | const list = tables(source); |
| 113 | let out = html`${files} | |
| 131 | let out = html`${specRow}${files} | |
| 114 | 132 | <h2>${source.label}</h2> |
| 115 | 133 | <ul class="list"> |
| 116 | 134 | ${list.map((t) => |
test/data-spec-door.test.ts added +121
| @@ -0,0 +1,121 @@ | ||
| 1 | /** | |
| 2 | * The spec as a file of the data tree (#7578): the web door and the MCP tool, gated as the API tab | |
| 3 | * is. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import { rememberSpec } from "../src/apps/api_spec.ts"; | |
| 11 | import { createApp as createAppRecord } from "../src/core/apps.ts"; | |
| 12 | import { createRepo } from "../src/core/repos.ts"; | |
| 13 | import { createSession } from "../src/core/sessions.ts"; | |
| 14 | import { createToken } from "../src/core/tokens.ts"; | |
| 15 | import { createUser } from "../src/core/users.ts"; | |
| 16 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 17 | import { quietLogs } from "./helpers/globals.ts"; | |
| 18 | import { mcpTool } from "./helpers/mcp.ts"; | |
| 19 | ||
| 20 | quietLogs(); | |
| 21 | ||
| 22 | describe("the spec door", () => { | |
| 23 | let dataDir: string; | |
| 24 | let app: App; | |
| 25 | let servers: Servers; | |
| 26 | const cookie: Record<string, string> = {}; | |
| 27 | const token: Record<string, string> = {}; | |
| 28 | const ids: string[] = []; | |
| 29 | ||
| 30 | beforeAll(async () => { | |
| 31 | dataDir = await mkdtemp(join(tmpdir(), "forge-spec-door-")); | |
| 32 | app = createApp({ dataDir, port: 0, host: "forge.test" }); | |
| 33 | servers = await serve(app); | |
| 34 | const users: Record<string, string> = {}; | |
| 35 | for (const name of ["owner1", "alice", "bob"]) { | |
| 36 | const made = await createUser(app.db, { | |
| 37 | origin: "seed", trusted: true, username: name, | |
| 38 | email: `${name}@forge.local`, password: "a-good-passphrase", adminIfFirst: name === "owner1", | |
| 39 | }); | |
| 40 | if (!made.ok) throw new Error(made.error); | |
| 41 | users[name] = made.value.id; | |
| 42 | cookie[name] = `forge_session=${createSession(app.db, made.value.id).token}`; | |
| 43 | token[name] = createToken(app.db, made.value.id, "t", "admin").token; | |
| 44 | } | |
| 45 | for (const [name, visibility] of [["notes", "public"], ["secret", "private"]] as const) { | |
| 46 | const repo = await createRepo(app.db, app.reposRoot, { ownerId: users["alice"]!, name, visibility }); | |
| 47 | if (!repo.ok) throw new Error(repo.error); | |
| 48 | const rec = createAppRecord(app.db, { repoId: repo.value.id, slug: name, access: visibility }); | |
| 49 | if (!rec.ok) throw new Error(rec.error); | |
| 50 | ids.push(rec.value.id); | |
| 51 | rememberSpec(rec.value.id, { paths: { [`/${name}-route`]: { get: { summary: `Only ${name}` } } } }); | |
| 52 | } | |
| 53 | }, 60_000); | |
| 54 | ||
| 55 | afterAll(async () => { | |
| 56 | servers.stop(); | |
| 57 | app.close(); | |
| 58 | await rm(dataDir, { recursive: true, force: true }); | |
| 59 | }); | |
| 60 | ||
| 61 | const get = (path: string, who?: string) => | |
| 62 | fetch(`${servers.url}${path}`, { headers: who ? { cookie: cookie[who]! } : {}, redirect: "manual" }); | |
| 63 | ||
| 64 | test("web: an app's Data tab offers openapi.json and lists its operations for a writer", async () => { | |
| 65 | const tab = await (await get("/alice/notes/data", "alice")).text(); | |
| 66 | expect(tab).toContain('href="/alice/notes/data?spec=1"'); | |
| 67 | const res = await get("/alice/notes/data?spec=1", "alice"); | |
| 68 | expect(res.status).toBe(200); | |
| 69 | const text = await res.text(); | |
| 70 | expect(text).toContain("/notes-route"); | |
| 71 | expect(text).toContain("Only notes"); | |
| 72 | expect(text).toContain('href="/alice/notes/api"'); | |
| 73 | expect(text).not.toContain("/secret-route"); | |
| 74 | }); | |
| 75 | ||
| 76 | test("web: /data?spec=1 lists the forge's operations as the viewer's role may call them", async () => { | |
| 77 | const text = await (await get("/data?spec=1", "alice")).text(); | |
| 78 | expect(text).toContain("/api/v1/openapi.json"); | |
| 79 | expect(text).toContain('href="/api"'); | |
| 80 | expect(await (await get("/data", "alice")).text()).toContain('href="/data?spec=1"'); | |
| 81 | }); | |
| 82 | ||
| 83 | test("web: a reader and a guest get nothing, a private app's spec stays private", async () => { | |
| 84 | expect((await get("/alice/notes/data?spec=1", "bob")).status).toBe(404); | |
| 85 | expect((await get("/alice/secret/data?spec=1", "bob")).status).toBe(404); | |
| 86 | expect((await get("/alice/secret/data?spec=1")).status).not.toBe(200); | |
| 87 | expect((await get("/data?spec=1", "bob")).status).toBe(404); | |
| 88 | const guest = await get("/data?spec=1"); | |
| 89 | expect(guest.status).not.toBe(200); | |
| 90 | expect(await guest.text()).not.toContain("secret-route"); | |
| 91 | expect(await (await get("/alice/secret/data?spec=1", "alice")).text()).toContain("/secret-route"); | |
| 92 | }); | |
| 93 | ||
| 94 | test("web: an app that serves no spec says so", async () => { | |
| 95 | rememberSpec(ids[0]!, null); | |
| 96 | const text = await (await get("/alice/notes/data?spec=1", "alice")).text(); | |
| 97 | expect(text).toContain("serves no /openapi.json"); | |
| 98 | rememberSpec(ids[0]!, { paths: { "/notes-route": { get: { summary: "Only notes" } } } }); | |
| 99 | }); | |
| 100 | ||
| 101 | test("MCP: data with spec true lists the forge's and an app's operations", async () => { | |
| 102 | const forge = await mcpTool(servers.url, token["bob"]!, "data", { spec: true, q: "openapi" }); | |
| 103 | expect(forge.value.operations.map((o: { path: string }) => o.path)).toContain("/api/v1/openapi.json"); | |
| 104 | const mine = await mcpTool(servers.url, token["alice"]!, "data", { spec: true, repo: "alice/secret" }); | |
| 105 | expect(mine.value).toMatchObject({ total: 1, operations: [{ method: "GET", path: "/secret-route" }] }); | |
| 106 | expect((await mcpTool(servers.url, token["bob"]!, "data", { spec: true, repo: "alice/notes" })).value.total).toBe(1); | |
| 107 | }); | |
| 108 | ||
| 109 | test("MCP: bad input, a private app seen by a stranger, an app with no spec", async () => { | |
| 110 | const a = await mcpTool(servers.url, token["alice"]!, "data", { spec: "yes" }); | |
| 111 | expect(a.error).toMatch(/^invalid/); | |
| 112 | const b = await mcpTool(servers.url, token["alice"]!, "data", { spec: true, q: 5 }); | |
| 113 | expect(b.error).toMatch(/^invalid/); | |
| 114 | const c = await mcpTool(servers.url, token["bob"]!, "data", { spec: true, repo: "alice/secret" }); | |
| 115 | expect(c.error).toBeDefined(); | |
| 116 | expect(JSON.stringify(c)).not.toContain("secret-route"); | |
| 117 | rememberSpec(ids[0]!, null); | |
| 118 | const d = await mcpTool(servers.url, token["alice"]!, "data", { spec: true, repo: "alice/notes" }); | |
| 119 | expect(d.error).toContain("serves no /openapi.json"); | |
| 120 | }); | |
| 121 | }); |
test/data-spec-scope.test.ts added +79
| @@ -0,0 +1,79 @@ | ||
| 1 | /** | |
| 2 | * spec_scope.ts: the API spec as a file of the tree (#7578): the forge's, and an app's behind its | |
| 3 | * door. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import { rememberSpec } from "../src/apps/api_spec.ts"; | |
| 11 | import { createApp as createAppRecord } from "../src/core/apps.ts"; | |
| 12 | import { createRepo, type Repo } from "../src/core/repos.ts"; | |
| 13 | import { createUser, type User } from "../src/core/users.ts"; | |
| 14 | import { appSpec, forgeSpec, SPEC_ROWS } from "../src/data/spec_scope.ts"; | |
| 15 | import { quietLogs } from "./helpers/globals.ts"; | |
| 16 | ||
| 17 | quietLogs(); | |
| 18 | ||
| 19 | describe("spec_scope", () => { | |
| 20 | let dataDir: string; | |
| 21 | let app: App; | |
| 22 | const user: Record<string, User> = {}; | |
| 23 | let pub: Repo; | |
| 24 | let priv: Repo; | |
| 25 | const ids: string[] = []; | |
| 26 | ||
| 27 | beforeAll(async () => { | |
| 28 | dataDir = await mkdtemp(join(tmpdir(), "forge-spec-scope-")); | |
| 29 | app = createApp({ dataDir, port: 0, host: "forge.test" }); | |
| 30 | for (const name of ["owner1", "alice", "bob"]) { | |
| 31 | const made = await createUser(app.db, { | |
| 32 | origin: "seed", trusted: true, username: name, | |
| 33 | email: `${name}@forge.local`, password: "a-good-passphrase", adminIfFirst: name === "owner1", | |
| 34 | }); | |
| 35 | if (!made.ok) throw new Error(made.error); | |
| 36 | user[name] = made.value; | |
| 37 | } | |
| 38 | const a = await createRepo(app.db, app.reposRoot, { ownerId: user["alice"]!.id, name: "notes", visibility: "public" }); | |
| 39 | const b = await createRepo(app.db, app.reposRoot, { ownerId: user["alice"]!.id, name: "secret", visibility: "private" }); | |
| 40 | if (!a.ok || !b.ok) throw new Error("repo"); | |
| 41 | pub = a.value; | |
| 42 | priv = b.value; | |
| 43 | for (const [repo, slug, access] of [[pub, "notes", "public"], [priv, "secret", "private"]] as const) { | |
| 44 | const rec = createAppRecord(app.db, { repoId: repo.id, slug, access }); | |
| 45 | if (!rec.ok) throw new Error("app"); | |
| 46 | ids.push(rec.value.id); | |
| 47 | rememberSpec(rec.value.id, { paths: { "/things": { get: { summary: "List things" } }, "/things/{id}": { delete: { summary: "Drop one" } } } }); | |
| 48 | } | |
| 49 | }, 60_000); | |
| 50 | ||
| 51 | afterAll(async () => { | |
| 52 | app.close(); | |
| 53 | await rm(dataDir, { recursive: true, force: true }); | |
| 54 | }); | |
| 55 | ||
| 56 | test("the forge's own spec lists operations, narrowed by a word, and cuts admin routes for a member", () => { | |
| 57 | const all = forgeSpec(app, user["bob"]!); | |
| 58 | expect(all.total).toBeGreaterThan(50); | |
| 59 | expect(all.shown).toBeLessThanOrEqual(SPEC_ROWS); | |
| 60 | expect(all.operations[0]).toMatchObject({ method: expect.any(String), path: expect.stringMatching(/^\//) }); | |
| 61 | const some = forgeSpec(app, user["bob"]!, "openapi"); | |
| 62 | expect(some.total).toBeLessThan(all.total); | |
| 63 | expect(some.operations.map((o) => o.path)).toContain("/api/v1/openapi.json"); | |
| 64 | expect(forgeSpec(app, user["owner1"]!).total).toBeGreaterThan(all.total); | |
| 65 | }); | |
| 66 | ||
| 67 | test("an app's spec is its own document; a stranger gets nothing from a private app", async () => { | |
| 68 | const got = await appSpec(app, user["bob"]!, pub); | |
| 69 | expect(got).toMatchObject({ total: 2 }); | |
| 70 | expect(typeof got === "object" && got.operations.map((o) => `${o.method} ${o.path}`)).toEqual(["GET /things", "DELETE /things/{id}"]); | |
| 71 | expect(await appSpec(app, user["bob"]!, priv)).toBeUndefined(); | |
| 72 | expect(await appSpec(app, user["alice"]!, priv)).toMatchObject({ total: 2 }); | |
| 73 | }); | |
| 74 | ||
| 75 | test("an app that serves no spec says so", async () => { | |
| 76 | rememberSpec(ids[0]!, null); | |
| 77 | expect(await appSpec(app, user["alice"]!, pub)).toBe("none"); | |
| 78 | }); | |
| 79 | }); |
test/tui-data.test.ts +57
| @@ -8,6 +8,7 @@ import { tmpdir } from "node:os"; | ||
| 8 | 8 | import { join } from "node:path"; |
| 9 | 9 | import { createApp, type App } from "../src/app.ts"; |
| 10 | 10 | import { envDataDir } from "../src/apps/data.ts"; |
| 11 | import { rememberSpec } from "../src/apps/api_spec.ts"; | |
| 11 | 12 | import { createApp as createAppRecord } from "../src/core/apps.ts"; |
| 12 | 13 | import { createRepo } from "../src/core/repos.ts"; |
| 13 | 14 | import { createUser, getUserByName } from "../src/core/users.ts"; |
| @@ -36,6 +37,13 @@ beforeAll(async () => { | ||
| 36 | 37 | if (!repo.ok) throw new Error(repo.error); |
| 37 | 38 | const rec = createAppRecord(app.db, { repoId: repo.value.id, slug: "notes", access: "public" }); |
| 38 | 39 | if (!rec.ok) throw new Error(rec.error); |
| 40 | const things = { paths: { "/things": { get: { summary: "List things" } } } }; | |
| 41 | rememberSpec(rec.value.id, things); | |
| 42 | const hidden = await createRepo(app.db, app.reposRoot, { ownerId: ids["alice"]!, name: "secret", visibility: "private" }); | |
| 43 | if (!hidden.ok) throw new Error(hidden.error); | |
| 44 | const hiddenApp = createAppRecord(app.db, { repoId: hidden.value.id, slug: "secret", access: "private" }); | |
| 45 | if (!hiddenApp.ok) throw new Error(hiddenApp.error); | |
| 46 | rememberSpec(hiddenApp.value.id, { paths: { "/hidden-route": { get: { summary: "Nobody else" } } } }); | |
| 39 | 47 | const where = envDataDir(dir, rec.value.id, "production"); |
| 40 | 48 | mkdirSync(where, { recursive: true }); |
| 41 | 49 | const d = new Database(join(where, "app.db")); |
| @@ -328,3 +336,52 @@ test("v spends the query budget: once it is spent, no list is read", async () => | ||
| 328 | 336 | expect(text).not.toContain("ann-visible 1"); |
| 329 | 337 | tui.stop?.(); |
| 330 | 338 | }); |
| 339 | ||
| 340 | test("openapi.json nodes: the forge's operations, then an app's own, for its writer", async () => { | |
| 341 | const { app: tui, session } = open("alice"); | |
| 342 | const copied: string[] = []; | |
| 343 | tui.ctx.copy = (t: string) => void copied.push(t); | |
| 344 | tui.start(); | |
| 345 | tui.ctx.push(dataScreen(session, tui.ctx)); | |
| 346 | await settleApp(tui); | |
| 347 | // repo alice/notes, repo alice/secret, then the forge's openapi.json last | |
| 348 | press(tui, "j"); | |
| 349 | press(tui, "j"); | |
| 350 | press(tui, "l"); | |
| 351 | await settleApp(tui); | |
| 352 | expect(tui.screen.toText()).toMatch(/GET\s+\/\S+/); | |
| 353 | press(tui, "j"); | |
| 354 | press(tui, "y"); | |
| 355 | expect(copied[0]).toMatch(/^[A-Z]+ \//); | |
| 356 | press(tui, "g"); | |
| 357 | for (let i = 0; i < 5; i++) press(tui, "k"); | |
| 358 | press(tui, "h"); | |
| 359 | press(tui, "h"); | |
| 360 | await settleApp(tui); | |
| 361 | // open alice/notes → its app → the app's openapi.json after production | |
| 362 | press(tui, "l"); | |
| 363 | press(tui, "j"); | |
| 364 | press(tui, "l"); | |
| 365 | press(tui, "j"); | |
| 366 | press(tui, "j"); | |
| 367 | press(tui, "l"); | |
| 368 | await settleApp(tui); | |
| 369 | const text = tui.screen.toText(); | |
| 370 | expect(text).toContain("GET /things List things"); | |
| 371 | expect(text).not.toContain("/hidden-route"); | |
| 372 | tui.stop?.(); | |
| 373 | }); | |
| 374 | ||
| 375 | test("a reader and a guest who reach the screen see no app and none of its spec", async () => { | |
| 376 | for (const who of ["bob", undefined]) { | |
| 377 | const { app: tui, session } = open(who); | |
| 378 | tui.start(); | |
| 379 | tui.ctx.push(dataScreen(session, tui.ctx)); | |
| 380 | await settleApp(tui); | |
| 381 | const text = tui.screen.toText(); | |
| 382 | expect(text).not.toContain("alice/"); | |
| 383 | expect(text).not.toContain("/things"); | |
| 384 | expect(text).not.toContain("/hidden-route"); | |
| 385 | tui.stop?.(); | |
| 386 | } | |
| 387 | }); |
new above
offline