Public: anyone can read this; the crew can change it.
Apps without a login 3: an app made on one device opens on another, as a file or a read-only link #18079
Merged 9h 10m ago, live in production
scout/forge:scout/18045-apps-without-a-login-3-an-app-made-on-on → main 0 commits fork 5 threads · 5 unresolved
8 files
changed +311
−46
docs/features/tab.md +6
| @@ -20,3 +20,9 @@ What this forge serves is static: `src/web/pages/tab.ts` (the page), `src/web/ta | ||
| 20 | 20 | `src/tab/worker.ts` and `src/tab/sw.ts`, the vendored SQLite under `src/web/vendor/sqlite-wasm`, a stylesheet). Left |
| 21 | 21 | out: git, a shell and installs, which need real Linux (#16837). `test/tab.test.ts` runs the same routes over the wasm |
| 22 | 22 | SQLite, loaded as the browser loads it, and over `bun:sqlite`. |
| 23 | ||
| 24 | ## Take an app with you (#18045) | |
| 25 | ||
| 26 | The forge's home links its app as one file, `app.json` (`src/tab/spec.ts`): `{format: "forge-app", version: 1, kind: "issues", name, records?}`, a typed spec and never code, with the issues or without as the person chooses. Choosing the file (a multipart form the worker reads, `src/tab/wire.ts`) or pasting its text into *Import an app* validates it like a model's answer (shape, each field, no unknown keys, at most 200 records and 100,000 characters) and refuses one that does not fit in words, keeping nothing; one that fits sets the app's name and adds its records. The terminal says the same in `TAB_MOVE` (`src/tui/screens/tab.ts`). Tests: `test/tab.test.ts`. | |
| 27 | ||
| 28 | Not done: the Apple app reading the file; carrying apps to a shared forge on sign-in and read-only revocable links (they need an account on a shared forge, and the move in `browser-forge-move.md` carries the database file, not specs). A download holds the oldest 200 issues and the page says so; an import is one transaction, and a refusal gives the text back to correct. |
src/tab/forge.ts +44 −4
| @@ -1,3 +1,5 @@ | ||
| 1 | import { BODY_MAX, makeSpec, NAME_MAX, parseSpec, RECORDS_CAP, SPEC_MAX, TITLE_MAX } from "./spec.ts"; | |
| 2 | ||
| 1 | 3 | /** |
| 2 | 4 | * The forge in the tab, as a function: a request and a database in, a page out. It runs in the |
| 3 | 5 | * browser's database worker over SQLite wasm and, in tests, over bun:sqlite; it imports nothing |
| @@ -14,25 +16,30 @@ export interface TabRequest { | ||
| 14 | 16 | readonly method: string; |
| 15 | 17 | /** The path under the forge's prefix, with a leading slash. */ |
| 16 | 18 | readonly path: string; |
| 19 | /** The query string without its `?`. */ | |
| 20 | readonly query?: string; | |
| 17 | 21 | readonly form: Readonly<Record<string, string>>; |
| 18 | 22 | } |
| 19 | 23 | |
| 20 | 24 | export interface TabReply { |
| 21 | 25 | readonly status: number; |
| 22 | 26 | readonly html: string; |
| 27 | /** A reply that is a file to keep: its type and name. */ | |
| 28 | readonly file?: { readonly type: string; readonly name: string }; | |
| 23 | 29 | /** Where a successful write sends the reader. */ |
| 24 | 30 | readonly location?: string; |
| 25 | 31 | } |
| 26 | 32 | |
| 27 | export const TITLE_MAX = 200; | |
| 28 | export const BODY_MAX = 5000; | |
| 29 | ||
| 30 | 33 | export function migrate(db: TabDb): void { |
| 31 | 34 | db.run( |
| 32 | 35 | "CREATE TABLE IF NOT EXISTS issue (id INTEGER PRIMARY KEY, title TEXT NOT NULL, body TEXT NOT NULL, created INTEGER NOT NULL)", |
| 33 | 36 | ); |
| 37 | db.run("CREATE TABLE IF NOT EXISTS app (id INTEGER PRIMARY KEY CHECK (id = 1), name TEXT NOT NULL)"); | |
| 38 | db.run("INSERT OR IGNORE INTO app (id, name) VALUES (1, 'Your forge')"); | |
| 34 | 39 | } |
| 35 | 40 | |
| 41 | const appName = (db: TabDb): string => String(db.all("SELECT name FROM app WHERE id = 1")[0]?.name ?? "Your forge"); | |
| 42 | ||
| 36 | 43 | const ESCAPES: Record<string, string> = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }; |
| 37 | 44 | export const esc = (s: string | number | undefined): string => String(s ?? "").replace(/[&<>"']/g, (c) => ESCAPES[c]!); |
| 38 | 45 | |
| @@ -50,6 +57,18 @@ function list(items: ReturnType<typeof rows>): string { | ||
| 50 | 57 | return `<ul>${items.map((i) => `<li><a href="${ROOT}/issues/${Number(i.id)}">#${Number(i.id)} ${esc(i.title)}</a></li>`).join("")}</ul>`; |
| 51 | 58 | } |
| 52 | 59 | |
| 60 | /** | |
| 61 | * The import form: a file to choose, or its text pasted (what was pasted before comes back, to | |
| 62 | * correct). | |
| 63 | */ | |
| 64 | const specForm = (text: string): string => | |
| 65 | `<form method="post" action="${ROOT}/import" enctype="multipart/form-data"><label>Import an app: choose its file <input type="file" name="file" accept=".json,application/json"></label><label>or paste its text <textarea name="spec" maxlength="${SPEC_MAX}">${esc(text)}</textarea></label><button>Import app</button></form>`; | |
| 66 | ||
| 67 | const move = (issues: number): string => { | |
| 68 | const cut = issues > RECORDS_CAP ? ` A download holds the oldest ${RECORDS_CAP} of this app's ${issues} issues; the rest stay here.` : ""; | |
| 69 | return `<h2>Take this app with you</h2><p><a href="${ROOT}/app.json?records=1">Download the app and its issues</a> or <a href="${ROOT}/app.json">the app alone</a>: one file that any forge in a tab opens.${cut}</p>${specForm("")}`; | |
| 70 | }; | |
| 71 | ||
| 53 | 72 | const FORM = `<form method="post" action="${ROOT}/issues"><label>Title <input name="title" maxlength="${TITLE_MAX}" required></label><label>Description <textarea name="body" maxlength="${BODY_MAX}"></textarea></label><button>Open issue</button></form>`; |
| 54 | 73 | |
| 55 | 74 | export function handle(db: TabDb, req: TabRequest): TabReply { |
| @@ -57,7 +76,13 @@ export function handle(db: TabDb, req: TabRequest): TabReply { | ||
| 57 | 76 | if (req.method === "GET") { |
| 58 | 77 | if (path === "/") { |
| 59 | 78 | const n = Number(db.all("SELECT count(*) AS n FROM issue")[0]?.n ?? 0); |
| 60 | return shell("Your forge", `<p>${n} ${n === 1 ? "issue" : "issues"}, kept on this device.</p>${list(rows(db, 5))}${FORM}`); | |
| 79 | return shell(appName(db), `<p>${n} ${n === 1 ? "issue" : "issues"}, kept on this device.</p>${list(rows(db, 5))}${FORM}${move(n)}`); | |
| 80 | } | |
| 81 | if (path === "/app.json") { | |
| 82 | const withRecords = ["1", "true"].includes(new URLSearchParams(req.query ?? "").get("records") ?? ""); | |
| 83 | const all = withRecords ? db.all("SELECT title, body FROM issue ORDER BY id LIMIT ?", [RECORDS_CAP]) : []; | |
| 84 | const records = withRecords ? all.map((r) => ({ title: String(r.title), body: String(r.body) })) : undefined; | |
| 85 | return { status: 200, html: makeSpec(appName(db), records), file: { type: "application/json", name: "app.json" } }; | |
| 61 | 86 | } |
| 62 | 87 | if (path === "/issues") return shell("Issues", `${list(rows(db, 100))}${FORM}`); |
| 63 | 88 | const one = /^\/issues\/(\d{1,9})$/.exec(path); |
| @@ -77,5 +102,20 @@ export function handle(db: TabDb, req: TabRequest): TabReply { | ||
| 77 | 102 | const id = Number(db.all("SELECT max(id) AS id FROM issue")[0]?.id); |
| 78 | 103 | return { status: 303, html: "", location: `${ROOT}/issues/${id}` }; |
| 79 | 104 | } |
| 105 | if (req.method === "POST" && path === "/import") { | |
| 106 | const text = req.form.file !== undefined && req.form.file.trim() !== "" ? req.form.file : (req.form.spec ?? ""); | |
| 107 | const got = parseSpec(text); | |
| 108 | if (!got.ok) return shell("Not imported", `<p>${esc(got.why)} Nothing was kept; correct it and try again.</p>${specForm(text.slice(0, SPEC_MAX))}`, 422); | |
| 109 | db.run("BEGIN"); | |
| 110 | try { | |
| 111 | db.run("UPDATE app SET name = ? WHERE id = 1", [got.spec.name.slice(0, NAME_MAX)]); | |
| 112 | for (const r of got.spec.records ?? []) db.run("INSERT INTO issue (title, body, created) VALUES (?, ?, ?)", [r.title, r.body, Date.now()]); | |
| 113 | db.run("COMMIT"); | |
| 114 | } catch { | |
| 115 | db.run("ROLLBACK"); | |
| 116 | return shell("Not imported", "<p>The file could not be saved. Nothing was kept.</p>", 500); | |
| 117 | } | |
| 118 | return { status: 303, html: "", location: `${ROOT}/` }; | |
| 119 | } | |
| 80 | 120 | return shell("Not allowed", "<p>That is not something this forge does.</p>", 405); |
| 81 | 121 | } |
src/tab/spec.ts added +74
| @@ -0,0 +1,74 @@ | ||
| 1 | /** | |
| 2 | * An app made in a tab, as one plain file: a typed spec, never code. `parseSpec` checks a file the | |
| 3 | * way a model's answer is checked (the shape, each field, nothing unknown) and says in words what | |
| 4 | * does not fit; `makeSpec` writes it from the database. Pure: the same file serves the browser | |
| 5 | * worker and the tests. | |
| 6 | */ | |
| 7 | ||
| 8 | const SPEC_FORMAT = "forge-app"; | |
| 9 | const SPEC_VERSION = 1; | |
| 10 | export const NAME_MAX = 80; | |
| 11 | export const RECORDS_CAP = 200; | |
| 12 | export const TITLE_MAX = 200; | |
| 13 | export const BODY_MAX = 5000; | |
| 14 | export const SPEC_MAX = 100000; | |
| 15 | ||
| 16 | interface SpecRecord { | |
| 17 | readonly title: string; | |
| 18 | readonly body: string; | |
| 19 | } | |
| 20 | ||
| 21 | interface AppSpec { | |
| 22 | readonly format: typeof SPEC_FORMAT; | |
| 23 | readonly version: typeof SPEC_VERSION; | |
| 24 | readonly kind: "issues"; | |
| 25 | readonly name: string; | |
| 26 | readonly records?: readonly SpecRecord[]; | |
| 27 | } | |
| 28 | ||
| 29 | type Parsed = { readonly ok: true; readonly spec: AppSpec } | { readonly ok: false; readonly why: string }; | |
| 30 | ||
| 31 | const refuse = (why: string): Parsed => ({ ok: false, why }); | |
| 32 | const isObject = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v); | |
| 33 | ||
| 34 | function unknownKey(o: Record<string, unknown>, allowed: readonly string[]): string | undefined { | |
| 35 | return Object.keys(o).find((k) => !allowed.includes(k)); | |
| 36 | } | |
| 37 | ||
| 38 | export function parseSpec(text: string): Parsed { | |
| 39 | if (text.length > SPEC_MAX) return refuse(`An app file is at most ${SPEC_MAX} characters.`); | |
| 40 | let raw: unknown; | |
| 41 | try { | |
| 42 | raw = JSON.parse(text); | |
| 43 | } catch { | |
| 44 | return refuse("This is not a JSON file, so it is not an app."); | |
| 45 | } | |
| 46 | if (!isObject(raw)) return refuse("An app file is one JSON object."); | |
| 47 | const extra = unknownKey(raw, ["format", "version", "kind", "name", "records"]); | |
| 48 | if (extra !== undefined) return refuse(`The app file has a field this forge does not know: "${extra.slice(0, 40)}".`); | |
| 49 | if (raw.format !== SPEC_FORMAT) return refuse(`The file is not an app: its "format" must be "${SPEC_FORMAT}".`); | |
| 50 | if (raw.version !== SPEC_VERSION) return refuse(`This forge reads version ${SPEC_VERSION} of the app file.`); | |
| 51 | if (raw.kind !== "issues") return refuse('This forge draws one kind of app: "issues".'); | |
| 52 | const name = typeof raw.name === "string" ? raw.name.trim() : ""; | |
| 53 | if (name === "" || name.length > NAME_MAX) return refuse(`The app needs a "name" of 1 to ${NAME_MAX} characters.`); | |
| 54 | if (raw.records === undefined) return { ok: true, spec: { format: SPEC_FORMAT, version: SPEC_VERSION, kind: "issues", name } }; | |
| 55 | if (!Array.isArray(raw.records)) return refuse('"records" must be a list.'); | |
| 56 | if (raw.records.length > RECORDS_CAP) return refuse(`An app file holds at most ${RECORDS_CAP} records.`); | |
| 57 | const records: SpecRecord[] = []; | |
| 58 | for (const [i, r] of raw.records.entries()) { | |
| 59 | const at = `Record ${i + 1}`; | |
| 60 | if (!isObject(r)) return refuse(`${at} must be an object with a title and a body.`); | |
| 61 | if (unknownKey(r, ["title", "body"]) !== undefined) return refuse(`${at} has a field other than title and body.`); | |
| 62 | const title = typeof r.title === "string" ? r.title.trim() : ""; | |
| 63 | if (title === "" || title.length > TITLE_MAX) return refuse(`${at} needs a title of 1 to ${TITLE_MAX} characters.`); | |
| 64 | if (typeof r.body !== "string" || r.body.length > BODY_MAX) return refuse(`${at} needs a body of up to ${BODY_MAX} characters.`); | |
| 65 | records.push({ title, body: r.body.trim() }); | |
| 66 | } | |
| 67 | return { ok: true, spec: { format: SPEC_FORMAT, version: SPEC_VERSION, kind: "issues", name, records } }; | |
| 68 | } | |
| 69 | ||
| 70 | /** The spec's file text: with the records when asked, oldest first. */ | |
| 71 | export function makeSpec(name: string, records: readonly SpecRecord[] | undefined): string { | |
| 72 | const spec: AppSpec = { format: SPEC_FORMAT, version: SPEC_VERSION, kind: "issues", name, ...(records === undefined ? {} : { records }) }; | |
| 73 | return `${JSON.stringify(spec, null, 2)}\n`; | |
| 74 | } |
src/tab/sw.ts +8 −39
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | * With that page closed there is nobody to ask, and it says so: the forge has stopped. |
| 5 | 5 | */ |
| 6 | 6 | import type { TabReply } from "./forge.ts"; |
| 7 | import { forgeMessage, PREFIX, readForm, replyOf } from "./wire.ts"; | |
| 7 | 8 | |
| 8 | 9 | interface Client { |
| 9 | 10 | readonly url: string; |
| @@ -19,68 +20,36 @@ interface Scope { | ||
| 19 | 20 | } |
| 20 | 21 | declare const self: Scope; |
| 21 | 22 | const sw = self; |
| 22 | const PREFIX = "/tab/f"; | |
| 23 | 23 | const ASK_MS = 5000; |
| 24 | const FORM_MAX = 20000; | |
| 25 | const CSP = "default-src 'none'; style-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'self'"; | |
| 26 | ||
| 27 | function reply(r: TabReply): Response { | |
| 28 | const headers: Record<string, string> = { | |
| 29 | "content-type": "text/html; charset=utf-8", "cache-control": "no-store", | |
| 30 | "content-security-policy": CSP, "x-content-type-options": "nosniff", "referrer-policy": "no-referrer", | |
| 31 | }; | |
| 32 | if (r.location !== undefined) return new Response(null, { status: r.status, headers: { ...headers, location: r.location } }); | |
| 33 | return new Response(r.html, { status: r.status, headers }); | |
| 34 | } | |
| 35 | 24 | |
| 36 | 25 | const stopped = (): Response => |
| 37 | reply({ status: 503, html: "<!doctype html><title>Stopped</title><p>This forge stopped: the tab that held it was closed. Open /tab again to start it.</p>" }); | |
| 38 | ||
| 39 | /** The form body as text, counted as it arrives: null once it passes FORM_MAX bytes. */ | |
| 40 | async function formText(request: Request): Promise<string | null> { | |
| 41 | const reader = request.body?.getReader(); | |
| 42 | if (reader === undefined) return ""; | |
| 43 | const decoder = new TextDecoder(); | |
| 44 | let text = ""; | |
| 45 | let bytes = 0; | |
| 46 | for (;;) { | |
| 47 | const { done, value } = await reader.read(); | |
| 48 | if (done) return text + decoder.decode(); | |
| 49 | bytes += value.byteLength; | |
| 50 | if (bytes > FORM_MAX) { | |
| 51 | await reader.cancel(); | |
| 52 | return null; | |
| 53 | } | |
| 54 | text += decoder.decode(value, { stream: true }); | |
| 55 | } | |
| 56 | } | |
| 26 | replyOf({ status: 503, html: "<!doctype html><title>Stopped</title><p>This forge stopped: the tab that held it was closed. Open /tab again to start it.</p>" }); | |
| 57 | 27 | |
| 58 | 28 | async function answer(request: Request): Promise<Response> { |
| 59 | 29 | const url = new URL(request.url); |
| 60 | 30 | let form: Record<string, string> = {}; |
| 61 | 31 | if (request.method === "POST") { |
| 62 | if (request.headers.get("origin") !== sw.location.origin) return reply({ status: 403, html: "Refused: not from this forge's own page." }); | |
| 63 | const text = await formText(request); | |
| 64 | if (text === null) return reply({ status: 413, html: "Too large." }); | |
| 65 | form = Object.fromEntries(new URLSearchParams(text)); | |
| 32 | if (request.headers.get("origin") !== sw.location.origin) return replyOf({ status: 403, html: "Refused: not from this forge's own page." }); | |
| 33 | const read = await readForm(request); | |
| 34 | if (read === null) return replyOf({ status: 413, html: "Too large." }); | |
| 35 | form = read; | |
| 66 | 36 | } |
| 67 | 37 | // The /tab page lies outside this worker's scope (/tab/f/), so it is never one of the clients the |
| 68 | 38 | // worker controls: without includeUncontrolled the host is invisible and the forge reads as stopped. |
| 69 | 39 | const hosts = (await sw.clients.matchAll({ type: "window", includeUncontrolled: true })).filter((c) => new URL(c.url).pathname === "/tab"); |
| 70 | 40 | if (hosts.length === 0) return stopped(); |
| 71 | const path = url.pathname.slice(PREFIX.length) || "/"; | |
| 72 | 41 | // Ask every /tab window: only the one that started the forge answers, so the first reply is the |
| 73 | 42 | // host. |
| 74 | 43 | const waiting = new Promise<TabReply | null>((resolve) => { |
| 75 | 44 | for (const host of hosts) { |
| 76 | 45 | const channel = new MessageChannel(); |
| 77 | 46 | channel.port1.onmessage = (e) => resolve(e.data as TabReply); |
| 78 | host.postMessage({ forge: { method: request.method, path, form } }, [channel.port2]); | |
| 47 | host.postMessage(forgeMessage(request.method, url, form), [channel.port2]); | |
| 79 | 48 | } |
| 80 | 49 | setTimeout(() => resolve(null), ASK_MS); |
| 81 | 50 | }); |
| 82 | 51 | const got = await waiting; |
| 83 | return got === null ? stopped() : reply(got); | |
| 52 | return got === null ? stopped() : replyOf(got); | |
| 84 | 53 | } |
| 85 | 54 | |
| 86 | 55 | sw.addEventListener("install", () => void sw.skipWaiting()); |
src/tab/wire.ts added +76
| @@ -0,0 +1,76 @@ | ||
| 1 | /** | |
| 2 | * What crosses between the service worker and the page that holds the forge: a request in, a reply | |
| 3 | * out. Plain functions over web standards (no worker scope), so the tests run the same code the | |
| 4 | * worker does. | |
| 5 | */ | |
| 6 | import type { TabReply, TabRequest } from "./forge.ts"; | |
| 7 | ||
| 8 | const FORM_MAX = 300000; | |
| 9 | export const PREFIX = "/tab/f"; | |
| 10 | ||
| 11 | const CSP = "default-src 'none'; style-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'self'"; | |
| 12 | ||
| 13 | /** The reply as a Response: a page, a redirect, or a file to keep. */ | |
| 14 | export function replyOf(r: TabReply): Response { | |
| 15 | const headers: Record<string, string> = { | |
| 16 | "content-type": "text/html; charset=utf-8", "cache-control": "no-store", | |
| 17 | "content-security-policy": CSP, "x-content-type-options": "nosniff", "referrer-policy": "no-referrer", | |
| 18 | }; | |
| 19 | if (r.file !== undefined) | |
| 20 | return new Response(r.html, { status: r.status, headers: { ...headers, "content-type": `${r.file.type}; charset=utf-8`, "content-disposition": `attachment; filename="${r.file.name}"` } }); | |
| 21 | if (r.location !== undefined) return new Response(null, { status: r.status, headers: { ...headers, location: r.location } }); | |
| 22 | return new Response(r.html, { status: r.status, headers }); | |
| 23 | } | |
| 24 | ||
| 25 | /** | |
| 26 | * The message the worker posts to the page: the method, the path under the prefix, the query, the | |
| 27 | * form. | |
| 28 | */ | |
| 29 | export function forgeMessage(method: string, url: URL, form: Record<string, string>): { forge: TabRequest } { | |
| 30 | return { forge: { method, path: url.pathname.slice(PREFIX.length) || "/", query: url.search.slice(1), form } }; | |
| 31 | } | |
| 32 | ||
| 33 | /** The body's bytes, counted as they arrive: null once they pass FORM_MAX. */ | |
| 34 | async function bodyBytes(request: Request): Promise<Uint8Array | null> { | |
| 35 | const reader = request.body?.getReader(); | |
| 36 | if (reader === undefined) return new Uint8Array(); | |
| 37 | const chunks: Uint8Array[] = []; | |
| 38 | let bytes = 0; | |
| 39 | for (;;) { | |
| 40 | const { done, value } = await reader.read(); | |
| 41 | if (done) break; | |
| 42 | bytes += value.byteLength; | |
| 43 | if (bytes > FORM_MAX) { | |
| 44 | await reader.cancel(); | |
| 45 | return null; | |
| 46 | } | |
| 47 | chunks.push(value); | |
| 48 | } | |
| 49 | const all = new Uint8Array(bytes); | |
| 50 | let at = 0; | |
| 51 | for (const c of chunks) { | |
| 52 | all.set(c, at); | |
| 53 | at += c.byteLength; | |
| 54 | } | |
| 55 | return all; | |
| 56 | } | |
| 57 | ||
| 58 | /** | |
| 59 | * The form's fields as text: a urlencoded body, or a multipart one whose files are read as text. | |
| 60 | * null when the body is too large or is neither. | |
| 61 | */ | |
| 62 | export async function readForm(request: Request): Promise<Record<string, string> | null> { | |
| 63 | const type = request.headers.get("content-type") ?? ""; | |
| 64 | const bytes = await bodyBytes(request); | |
| 65 | if (bytes === null) return null; | |
| 66 | if (!type.startsWith("multipart/form-data")) return Object.fromEntries(new URLSearchParams(new TextDecoder().decode(bytes))); | |
| 67 | let data: Awaited<ReturnType<Response["formData"]>>; | |
| 68 | try { | |
| 69 | data = await new Response(bytes, { headers: { "content-type": type } }).formData(); | |
| 70 | } catch { | |
| 71 | return null; | |
| 72 | } | |
| 73 | const form: Record<string, string> = {}; | |
| 74 | for (const [name, value] of data.entries() as Iterable<[string, string | Blob]>) form[name] = typeof value === "string" ? value : await value.text(); | |
| 75 | return form; | |
| 76 | } |
src/tab/words.ts +4 −1
| @@ -14,5 +14,8 @@ export const TAB_FACTS: readonly string[] = [ | ||
| 14 | 14 | /** What is left out, said where the facts are. */ |
| 15 | 15 | export const TAB_LEFT_OUT = "No git, shell or installs here: those need a real Linux machine."; |
| 16 | 16 | |
| 17 | /** How an app leaves and enters: one file, checked on the way in. */ | |
| 18 | export const TAB_MOVE = "An app is one JSON file: download it from the forge's home (with its issues or without) and choose it (or paste it) in another tab forge, which refuses a file that does not fit."; | |
| 19 | ||
| 17 | 20 | /** The terminal's one sentence: the facts and where the page is. */ |
| 18 | export const tabLine = (): string => `${TAB_FACTS.join(" ")} ${TAB_LEFT_OUT} Open /tab in a browser to start it.`; | |
| 21 | export const tabLine = (): string => `${TAB_FACTS.join(" ")} ${TAB_LEFT_OUT} ${TAB_MOVE} Open /tab in a browser to start it.`; |
src/web/tab-asset.ts +1 −1
| @@ -19,7 +19,7 @@ import { noneMatch } from "../http/conditional.ts"; | ||
| 19 | 19 | |
| 20 | 20 | const VENDOR = join(import.meta.dir, "vendor", "sqlite-wasm"); |
| 21 | 21 | |
| 22 | const STYLE = `:root{color-scheme:light dark}body{margin:0;font:15px/1.5 system-ui,sans-serif}main{max-width:36rem;margin:0 auto;padding:16px}nav{display:flex;gap:12px}nav a{display:inline-flex;align-items:center;min-height:44px}h1{font-size:20px;margin:.75rem 0}.muted{opacity:.7}form{display:grid;gap:8px;margin-top:16px}input,textarea,button{font:inherit;font-size:16px;padding:6px 10px;min-height:44px;box-sizing:border-box}textarea{min-height:5rem}.body{white-space:pre-wrap}`; | |
| 22 | const STYLE = `:root{color-scheme:light dark}body{margin:0;font:15px/1.5 system-ui,sans-serif}main{max-width:36rem;margin:0 auto;padding:16px}nav{display:flex;gap:12px}nav a{display:inline-flex;align-items:center;min-height:44px}h1{font-size:20px;margin:.75rem 0}h2{font-size:16px;margin:1.5rem 0 .5rem}main{overflow-wrap:anywhere}label{display:grid;gap:4px}input,textarea{width:100%}.muted{opacity:.7}form{display:grid;gap:8px;margin-top:16px}input,textarea,button{font:inherit;font-size:16px;padding:6px 10px;min-height:44px;box-sizing:border-box}textarea{min-height:5rem}.body{white-space:pre-wrap}`; | |
| 23 | 23 | |
| 24 | 24 | /** The worker runs wasm, fetches the module and its binary from this origin, and nothing else. */ |
| 25 | 25 | const WORKER_CSP = "default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; connect-src 'self'"; |
test/tab.test.ts +98 −1
| @@ -11,7 +11,9 @@ import { join } from "node:path"; | ||
| 11 | 11 | import { createApp, type App } from "../src/app.ts"; |
| 12 | 12 | import { serve, type Servers } from "../src/http/server.ts"; |
| 13 | 13 | import { handle, migrate, type TabDb } from "../src/tab/forge.ts"; |
| 14 | import { TAB_FACTS, tabLine } from "../src/tab/words.ts"; | |
| 14 | import { forgeMessage, readForm, replyOf } from "../src/tab/wire.ts"; | |
| 15 | import { RECORDS_CAP } from "../src/tab/spec.ts"; | |
| 16 | import { TAB_FACTS, TAB_MOVE, tabLine } from "../src/tab/words.ts"; | |
| 15 | 17 | import { Session } from "../src/tui/session.ts"; |
| 16 | 18 | import { quietCtx } from "./helpers/tui-text.ts"; |
| 17 | 19 | import { entry } from "../src/tui/screens/tab.ts"; |
| @@ -60,6 +62,101 @@ for (const [name, open] of [["bun:sqlite", async () => viaBun()], ["SQLite wasm" | ||
| 60 | 62 | expect(get(db, "/issues/1").html).toContain("hello & goodbye"); |
| 61 | 63 | }); |
| 62 | 64 | |
| 65 | test("an app exported with its records imports into a fresh forge and draws the same", async () => { | |
| 66 | const a = await open(); | |
| 67 | migrate(a); | |
| 68 | post(a, "/issues", { title: "One <i>", body: "first" }); | |
| 69 | post(a, "/issues", { title: "Two", body: "" }); | |
| 70 | const file = handle(a, { method: "GET", path: "/app.json", query: "records=1", form: {} }); | |
| 71 | expect(file.file?.type).toBe("application/json"); | |
| 72 | const bare = handle(a, { method: "GET", path: "/app.json", form: {} }); | |
| 73 | expect(JSON.parse(bare.html).records).toBeUndefined(); | |
| 74 | const b = await open(); | |
| 75 | migrate(b); | |
| 76 | const done = post(b, "/import", { spec: file.html }); | |
| 77 | expect(done.status).toBe(303); | |
| 78 | expect(get(b, "/issues").html).toBe(get(a, "/issues").html); | |
| 79 | expect(get(b, "/").html).toBe(get(a, "/").html); | |
| 80 | expect(post(b, "/import", { spec: JSON.stringify({ ...JSON.parse(bare.html), name: "Renamed" }) }).status).toBe(303); | |
| 81 | expect(get(b, "/").html).toContain("<h1>Renamed</h1>"); | |
| 82 | }); | |
| 83 | ||
| 84 | test("a file that does not fit the schema is refused in words and keeps nothing", async () => { | |
| 85 | const db = await open(); | |
| 86 | migrate(db); | |
| 87 | const ok = { format: "forge-app", version: 1, kind: "issues", name: "X" }; | |
| 88 | const bad = ["nope", "[]", JSON.stringify({ ...ok, format: "x" }), JSON.stringify({ ...ok, extra: 1 }), JSON.stringify({ ...ok, name: "" }), | |
| 89 | JSON.stringify({ ...ok, records: [{ title: "fine", body: "" }, { title: 3, body: "" }] }), JSON.stringify({ ...ok, records: "no" }), | |
| 90 | JSON.stringify({ ...ok, kind: "code" }), JSON.stringify({ ...ok, version: 2 })]; | |
| 91 | for (const spec of bad) { | |
| 92 | const r = post(db, "/import", { spec }); | |
| 93 | expect(r.status).toBe(422); | |
| 94 | expect(r.html).toContain("<p>"); | |
| 95 | } | |
| 96 | expect(post(db, "/import", { spec: JSON.stringify({ ...ok, name: "<script>" }) }).status).toBe(303); | |
| 97 | expect(get(db, "/").html).toContain("<script>"); | |
| 98 | expect(get(db, "/issues").html).toContain("No issues yet"); | |
| 99 | }); | |
| 100 | ||
| 101 | test("records are asked for by the query's records field, however it is spelled around", async () => { | |
| 102 | const db = await open(); | |
| 103 | migrate(db); | |
| 104 | post(db, "/issues", { title: "One", body: "" }); | |
| 105 | const has = (query?: string) => JSON.parse(handle(db, { method: "GET", path: "/app.json", ...(query === undefined ? {} : { query }), form: {} }).html).records !== undefined; | |
| 106 | expect([has("records=1"), has("x=2&records=1"), has("records=1&x=2"), has("records=true")]).toEqual([true, true, true, true]); | |
| 107 | expect([has(), has("records=0"), has("xrecords=1")]).toEqual([false, false, false]); | |
| 108 | }); | |
| 109 | ||
| 110 | test("a refused import gives the text back to correct, and a failed one keeps nothing", async () => { | |
| 111 | const db = await open(); | |
| 112 | migrate(db); | |
| 113 | const r = post(db, "/import", { spec: "{ <b>oops" }); | |
| 114 | expect(r.status).toBe(422); | |
| 115 | expect(r.html).toContain("<b>oops"); | |
| 116 | expect(r.html).toContain('type="file"'); | |
| 117 | const file = post(db, "/import", { file: '{"bad":1}', spec: "ignored" }); | |
| 118 | expect(file.html).toContain(""bad""); | |
| 119 | const spec = JSON.stringify({ format: "forge-app", version: 1, kind: "issues", name: "Half", records: [{ title: "a", body: "" }, { title: "b", body: "" }] }); | |
| 120 | let inserts = 0; | |
| 121 | const failing: TabDb = { run: (sql, bind) => { if (sql.startsWith("INSERT INTO issue") && ++inserts === 2) throw new Error("disk"); db.run(sql, bind); }, all: (sql, bind) => db.all(sql, bind) }; | |
| 122 | expect(post(failing, "/import", { spec }).status).toBe(500); | |
| 123 | expect(get(db, "/").html).toContain("<h1>Your forge</h1>"); | |
| 124 | expect(get(db, "/issues").html).toContain("No issues yet"); | |
| 125 | }); | |
| 126 | ||
| 127 | test("the page says when a download holds fewer issues than the app has", async () => { | |
| 128 | const db = await open(); | |
| 129 | migrate(db); | |
| 130 | post(db, "/issues", { title: "One", body: "" }); | |
| 131 | expect(get(db, "/").html).not.toContain("oldest"); | |
| 132 | for (let i = 0; i < RECORDS_CAP; i++) db.run("INSERT INTO issue (title, body, created) VALUES ('x', '', 0)"); | |
| 133 | expect(get(db, "/").html).toContain(`oldest ${RECORDS_CAP} of this app's ${RECORDS_CAP + 1} issues`); | |
| 134 | }); | |
| 135 | ||
| 136 | test("the worker's wire: the query is forwarded, a file reply is an attachment, a chosen file is read", async () => { | |
| 137 | const url = new URL("https://x.test/tab/f/app.json?records=1"); | |
| 138 | expect(forgeMessage("GET", url, {})).toEqual({ forge: { method: "GET", path: "/app.json", query: "records=1", form: {} } }); | |
| 139 | expect(forgeMessage("GET", new URL("https://x.test/tab/f/"), {}).forge.path).toBe("/"); | |
| 140 | const got = replyOf({ status: 200, html: "{}", file: { type: "application/json", name: "app.json" } }); | |
| 141 | expect(got.headers.get("content-disposition")).toBe('attachment; filename="app.json"'); | |
| 142 | expect(got.headers.get("content-type")).toBe("application/json; charset=utf-8"); | |
| 143 | expect(got.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 144 | expect(replyOf({ status: 200, html: "x" }).headers.get("content-disposition")).toBeNull(); | |
| 145 | const body = new FormData(); | |
| 146 | body.set("file", new File(['{"a":1}'], "app.json", { type: "application/json" })); | |
| 147 | body.set("spec", "pasted"); | |
| 148 | expect(await readForm(new Request("https://x.test/tab/f/import", { method: "POST", body }))).toEqual({ file: '{"a":1}', spec: "pasted" }); | |
| 149 | const plain = new Request("https://x.test/tab/f/issues", { method: "POST", body: "title=a+b", headers: { "content-type": "application/x-www-form-urlencoded" } }); | |
| 150 | expect(await readForm(plain)).toEqual({ title: "a b" }); | |
| 151 | const huge = new Request("https://x.test/tab/f/issues", { method: "POST", body: "a=" + "x".repeat(300001), headers: { "content-type": "application/x-www-form-urlencoded" } }); | |
| 152 | expect(await readForm(huge)).toBeNull(); | |
| 153 | }); | |
| 154 | ||
| 155 | test("the terminal says how an app moves", () => { | |
| 156 | expect(tabLine()).toContain(TAB_MOVE); | |
| 157 | expect(TAB_MOVE).toContain("file"); | |
| 158 | }); | |
| 159 | ||
| 63 | 160 | test("bad input is refused at the boundary and unknown things are not found", async () => { |
| 64 | 161 | const db = await open(); |
| 65 | 162 | migrate(db); |
new above
offline
req.query === "records=1"is brittle (?records=1&x=2drops the records). Use URLSearchParams. The silent cap at 200 issues should be said on the page.