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

A tab-forge read-only link can be revoked by the person who made it #18402

opened this

Merged 2h 23m ago, live in production

scout/forge:scout/18398-a-tab-forge-read-only-link-can-be-revoke → main 0 commits fork 4 threads · 4 unresolved

  • Merged. scout/18398-a-tab-forge-read-only-link-can-be-revoke was merged into main as bfd96cb.

Review

Sign in to review this change.
12 files changed +274 −18
docs/features/tabforge.md +7 −1
@@ -18,6 +18,12 @@ The page is `src/web/pages/tabforge.ts`; the words are `src/web/tabforge/words.t
1818
1919 An app made in a tab (`/tab`, format `src/tab/blocks.ts`) can be sent to the forge as one read-only link that opens on any device, with no login. The app's page in the tab offers **Get a link** beside its source: a plain form whose hidden field carries the app's JSON, so it works with script off. `POST /tabforge-link` (`src/web/pages/tabforge-link.ts`, logic in `src/tab/share.ts`) checks it is same-origin, reads at most 80 KB, validates it with `decodeApp` (its `LIMITS` apply), stores the decoded app only, never its entries, in `tab_shared`, and answers a 16-character random id as `/tabforge-link/<id>`. A spec that does not decode stores nothing. `GET /tabforge-link/<id>` draws the app read-only (the preview renderer: no forms, no entries), escaped, with the floor's headers; an unknown or malformed id is the forge's one 404.
2020
21 The route sits outside `/tabforge/` and `/tab/f/` on purpose: a service worker in either scope would answer for it in a browser that started a tab forge. It is an open door for strangers, so it is limited by rate, not by count: 10 posts a minute per address (the `share` door in `src/http/strangers.ts`), taken before the body is read. Storage is bounded the other way: the forge keeps the newest 5000 links and the oldest go as a new one is made, so a link can stop opening once enough newer ones exist, and no one can fill the table and lock the door. It mints no account. Publishing is the one moment a person with no account becomes the visitor principal (#18216, `src/core/visitors.ts`): after the door and the body, the forge asks `may` for `visitor.make` (a refused credential is 403) and then `VISITOR_CAPS`, per visitor, per connection and per forge (429 past any), before anything is stored; once the link is made it is counted, and only then does the answer carry the signed `forge_maker` cookie. A spec that does not decode counts and mints nothing; `DNT: 1` or `Sec-GPC: 1` publishes and counts with no id kept; a signed-in person mints nothing. Reading or editing in the tab, and opening a link, mint nothing. There is no way to edit or delete a link yet.
21 The route sits outside `/tabforge/` and `/tab/f/` on purpose: a service worker in either scope would answer for it in a browser that started a tab forge. It is an open door for strangers, so it is limited by rate, not by count: 10 posts a minute per address (the `share` door in `src/http/strangers.ts`), taken before the body is read. Storage is bounded the other way: the forge keeps the newest 5000 links and the oldest go as a new one is made, so a link can stop opening once enough newer ones exist, and no one can fill the table and lock the door. It mints no account. Publishing is the one moment a person with no account becomes the visitor principal (#18216, `src/core/visitors.ts`): after the door and the body, the forge asks `may` for `visitor.make` (a refused credential is 403) and then `VISITOR_CAPS`, per visitor, per connection and per forge (429 past any), before anything is stored; once the link is made it is counted, and only then does the answer carry the signed `forge_maker` cookie. A spec that does not decode counts and mints nothing; `DNT: 1` or `Sec-GPC: 1` publishes and counts with no id kept; a signed-in person mints nothing. Reading or editing in the tab, and opening a link, mint nothing. A link cannot be edited.
22
23 ## Stop sharing (#18398)
24
25 Making a link also makes a revoke key (192 random bits), shown once on the page that answers and never in the link. Only its SHA-256 is stored, in `tab_shared.key_hash` (`src/tab/revoke_key.ts`); the column is nullable, so a link made before keys existed has no hash, stays openable and cannot be stopped. The answer page offers **Keep the key in my tab**, a form to the tab forge's own page for the app (`/tab/f/apps/<n>/links`), which stores the link and key in the tab's `kept_link` table. The app's page then lists its links under "Links you made", each with **Stop sharing**: a POST to `/tabforge-link/<id>/revoke` with the key (same-origin checked, its own `revoke` door applies, so stopping links is not throttled by making them). The list's form also sends the app's number, so the answer (stopped, or no longer there) offers **Remove it from my tab's list**, which drops the kept row; the list never keeps a dead link. The right key deletes the row, so the link answers the forge's one 404; a wrong or missing key, or a row with no hash, changes nothing and says "Nothing changed" (403); keys are compared as hashes in constant time. Clearing the site's data loses the keys, and the page says so. The key is not kept unless the person presses the button: with script off or no tab forge they copy it from the page.
26
27 The terminal says the same words (`TAB_REVOKE` in `src/tab/words.ts`, part of `tabLine()`); a terminal holds no tab's keys, so it has nothing to stop.
2228
2329 The terminal's twin is the tab forge's palette entry (`src/tui/screens/tab.ts`): `tabLine()` says the same words (`TAB_LINK` in `src/tab/words.ts`). The terminal cannot hold a tab's app, so it has nothing to send.
src/core/migration-pins/20261206090000-tab-shared-revoke.pin added +1
@@ -0,0 +1,1 @@
1 d132294724b2e9d42266743fc83c848a96c2dd09b61c4fe8c67c79c519bef508
src/core/migrations/20261206090000-tab-shared-revoke.ts added +6
@@ -0,0 +1,6 @@
1 // A read-only tab-forge link can be taken back by whoever made it (#18398): only the SHA-256 of
2 // the maker's revoke key is stored. Nullable on purpose: a row made before this has no hash, can
3 // never be revoked, and stays openable. Additive.
4 export default `
5 ALTER TABLE tab_shared ADD COLUMN key_hash TEXT;
6 `;
src/http/lazy_lists.ts +1
@@ -486,6 +486,7 @@ export const DISCOVERY_ROUTES = [
486486 ["GET", "/tabforge"],
487487 ["POST", "/tabforge-link"],
488488 ["GET", "/tabforge-link/:id"],
489 ["POST", "/tabforge-link/:id/revoke"],
489490 ["POST", "/tabforge-move"],
490491 ] as const;
491492
src/http/routes/discovery.ts +2 −1
@@ -14,7 +14,7 @@ import { machineTermAsset, ghosttyWasmAsset, wasmResponse } from "../../web/mach
1414 import { openSearch } from "../../web/opensearch.ts";
1515 import { agentsPage } from "../../web/pages/agents.ts";
1616 import { tabforgePage } from "../../web/pages/tabforge.ts";
17 import { tabLinkMake, tabLinkOpen, tabMoveIn } from "../../web/pages/tabforge-link.ts";
17 import { tabLinkMake, tabLinkOpen, tabLinkRevoke, tabMoveIn } from "../../web/pages/tabforge-link.ts";
1818 import { offlinePage } from "../../web/pages/offline.ts";
1919 import { tabPage } from "../../web/pages/tab.ts";
2020 import { tabFile, tabVendor } from "../../web/tab-asset.ts";
@@ -139,5 +139,6 @@ export function discoveryRoutes(router: Router<Handler>): void {
139139 // `/tab/f/` scopes, so no worker answers it.
140140 router.add("POST", "/tabforge-link", tabLinkMake);
141141 router.add("GET", "/tabforge-link/:id", tabLinkOpen);
142 router.add("POST", "/tabforge-link/:id/revoke", tabLinkRevoke);
142143 router.add("POST", "/tabforge-move", tabMoveIn);
143144 }
src/http/strangers.ts +3 −3
@@ -23,7 +23,7 @@ import { transferGate } from "../git/env.ts";
2323 import { bucketOf, clientBucket } from "./peer.ts";
2424
2525 /** A door a stranger is counted at, each with its own minute. */
26 export type Door = "api" | "git" | "code" | "plan" | "pay" | "share";
26 export type Door = "api" | "git" | "code" | "plan" | "pay" | "share" | "revoke";
2727
2828 export interface StrangerLimits {
2929 /** Requests per minute through each door, per client address. */
@@ -72,8 +72,8 @@ export interface StrangerLimits {
7272 }
7373
7474 export const STRANGER_LIMITS: StrangerLimits = {
75 perAddress: { api: 600, git: 60, code: 10, plan: 10, pay: 5, share: 10 },
76 forge: { api: 6000, git: 600, code: 60, plan: 60, pay: 60, share: 120 },
75 perAddress: { api: 600, git: 60, code: 10, plan: 10, pay: 5, share: 10, revoke: 10 },

The new revoke door has no test. Add one that makes 11 revoke posts from one address and sees a 429, while a make from the same address still answers.

76 forge: { api: 6000, git: 600, code: 60, plan: 60, pay: 60, share: 120, revoke: 60 },
7777 transfersPerAddress: 4,
7878 transferShare: 0.5,
7979 transferTimeoutMs: 7_200_000,
src/tab/apps.ts +27 −3
@@ -8,9 +8,9 @@ import { settle } from "./fill.ts";
88 import type { TabDb, TabReply, TabRequest } from "./forge.ts";
99 import { ROOT, renderApp, type Rec } from "./render.ts";
1010 import { fileName, openFile, saveFile, FILE_MAX } from "./file.ts";
11 import { linkForm, MOVE_PATH } from "./share.ts";
11 import { isShareId, keptLinkRow, linkForm, MOVE_PATH } from "./share.ts";
1212 import { shell } from "./shell.ts";
13 import { TAB_KEEP, TAB_KEEP_LABEL, TAB_LINK, TAB_LINK_LABEL } from "./words.ts";
13 import { TAB_KEEP, TAB_KEEP_LABEL, TAB_LINK, TAB_LINK_LABEL, TAB_REVOKE } from "./words.ts";
1414 import { decodeApp, entryText, SPEC_VERSION, type BlockApp } from "./blocks.ts";
1515
1616 export const SAY_MAX = 300;
@@ -20,6 +20,7 @@ export function migrateApps(db: TabDb): void {
2020 db.run("CREATE TABLE IF NOT EXISTS made (id INTEGER PRIMARY KEY, title TEXT NOT NULL, spec TEXT NOT NULL, why TEXT NOT NULL, created INTEGER NOT NULL)");
2121 db.run("CREATE TABLE IF NOT EXISTS rec (id INTEGER PRIMARY KEY, app INTEGER NOT NULL, block INTEGER NOT NULL, text TEXT NOT NULL, n REAL NOT NULL, col INTEGER NOT NULL, day TEXT NOT NULL, created INTEGER NOT NULL)");
2222 db.run("CREATE INDEX IF NOT EXISTS rec_app ON rec (app)");
23 db.run("CREATE TABLE IF NOT EXISTS kept_link (link TEXT PRIMARY KEY, app INTEGER NOT NULL, key TEXT NOT NULL, created INTEGER NOT NULL)");
2324 }
2425
2526 /** The device's local day, `YYYY-MM-DD`. */
@@ -67,6 +68,15 @@ export function appsHome(db: TabDb): string {
6768 const records = (db: TabDb, app: number): Rec[] =>
6869 db.all("SELECT id, block, text, n, col, day FROM rec WHERE app = ? ORDER BY id", [app]).map((r) => ({ id: Number(r.id), block: Number(r.block), text: String(r.text), n: Number(r.n), col: Number(r.col), day: String(r.day) }));
6970
71 /**
72 * The links this tab made for app `id`, with the keys that take them back (never sent anywhere
73 * else).
74 */
75 const keptLinks = (db: TabDb, id: number): string => {
76 const rows = db.all("SELECT link, key FROM kept_link WHERE app = ? ORDER BY created DESC", [id]);
77 return rows.length === 0 ? "" : `<h2>Links you made</h2><p class="muted">${esc(TAB_REVOKE)}</p><ul class="items">${rows.map((r) => keptLinkRow(String(r.link), String(r.key), id)).join("")}</ul>`;
78 };
79
7080 const notFound = (): TabReply => shell("Not found", "<p>No such app.</p>", 404);
7181 const back = (id: number): TabReply => ({ status: 303, html: "", location: `${ROOT}/apps/${id}` });
7282 const refuse = (why: string): TabReply => shell("Not saved", `<p>${esc(why)}</p>`, 422);
@@ -121,16 +131,30 @@ export function handleApps(db: TabDb, req: TabRequest, path: string, now: number
121131 if (req.method === "GET" && parts.length === 1)
122132 return found === null
123133 ? shell(title, `<h1>${esc(title)}</h1><p>This app's spec cannot be read, so it cannot be drawn. It can still be removed.</p>${removeForm(id, title)}`)
124 : shell(found.app.title, `${renderApp(found.app, { appId: id, records: records(db, id), today: dayOf(now) })}<p><a href="${ROOT}/apps/${id}/source">How this app was made</a></p><p class="muted">${esc(TAB_LINK)}</p>${linkForm(found.app, TAB_LINK_LABEL)}${saveLinks(id)}<p class="muted">${esc(TAB_KEEP)}</p>${linkForm(found.app, TAB_KEEP_LABEL, MOVE_PATH)}${removeForm(id, title)}`, 200, false);
134 : shell(found.app.title, `${renderApp(found.app, { appId: id, records: records(db, id), today: dayOf(now) })}<p><a href="${ROOT}/apps/${id}/source">How this app was made</a></p><p class="muted">${esc(TAB_LINK)}</p>${linkForm(found.app, TAB_LINK_LABEL, undefined, id)}${keptLinks(db, id)}${saveLinks(id)}<p class="muted">${esc(TAB_KEEP)}</p>${linkForm(found.app, TAB_KEEP_LABEL, MOVE_PATH)}${removeForm(id, title)}`, 200, false);
125135 if (req.method === "GET" && parts[1] === "file" && parts.length === 2 && found !== null) {
126136 const withRecords = ["1", "true"].includes(new URLSearchParams(req.query ?? "").get("records") ?? "");
127137 return { status: 200, html: saveFile(found.app, withRecords ? records(db, id) : undefined), file: { type: "application/json", name: fileName(found.app) } };
128138 }
129139 if (req.method === "GET" && parts[1] === "source" && parts.length === 2) return found === null ? notFound() : shell(`${found.app.title}: why`, source(found));
130140 if (req.method !== "POST") return shell("Not allowed", "<p>That is not something this forge does.</p>", 405);
141 if (parts[1] === "links" && parts.length === 2) {
142 const forget = req.form.forget ?? "";
143 if (forget !== "") {
144 if (!isShareId(forget)) return refuse("That link does not look right. Nothing was removed.");
145 db.run("DELETE FROM kept_link WHERE link = ? AND app = ?", [forget, id]);
146 return back(id);
147 }
148 const link = req.form.link ?? "";
149 const key = req.form.key ?? "";
150 if (!isShareId(link) || !/^[A-Za-z0-9_-]{1,64}$/.test(key)) return refuse("That link or key does not look right. Nothing was kept.");
151 db.run("INSERT OR REPLACE INTO kept_link (link, app, key, created) VALUES (?, ?, ?, ?)", [link, id, key, now]);
152 return back(id);
153 }
131154 if (parts[1] === "delete" && parts.length === 2) {
132155 if ((req.form.confirm ?? "").trim() !== title.trim()) return refuse("Type the app's title exactly to remove it and its entries. Nothing was removed.");
133156 db.run("DELETE FROM rec WHERE app = ?", [id]);
157 db.run("DELETE FROM kept_link WHERE app = ?", [id]);
134158 db.run("DELETE FROM made WHERE id = ?", [id]);
135159 return { status: 303, html: "", location: `${ROOT}/` };
136160 }
src/tab/revoke_key.ts added +32
@@ -0,0 +1,32 @@
1 /**
2 * The revoke key of a read-only link (#18398): made once, shown once, never in the link. Only its
3 * SHA-256 is stored in `tab_shared.key_hash`; a presented key is compared in constant time. Server
4 * side only (it uses node:crypto); the tab itself keeps the key as plain text it was shown.
5 */
6 import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
7 import type { TabDb } from "./forge.ts";
8 import { isShareId } from "./share.ts";
9
10 const hashOf = (key: string): Buffer => createHash("sha256").update(key).digest();
11
12 /** A new key (192 random bits) and the hash to store. */
13 export function newKey(): { readonly key: string; readonly hash: string } {
14 const key = randomBytes(24).toString("base64url");
15 return { key, hash: hashOf(key).toString("hex") };
16 }
17
18 export type Revoked = "gone" | "wrong" | "unknown";
19
20 /**
21 * Take the link back when `key` is the one it was made with. A row with no hash (made before keys)
22 * cannot be revoked and says "wrong"; an id that is not there is "unknown" (the forge's 404).
23 */
24 export function revokeShared(db: TabDb, id: string, key: string): Revoked {
25 if (!isShareId(id)) return "unknown";
26 const row = db.all("SELECT key_hash FROM tab_shared WHERE id = ?", [id])[0];
27 if (row === undefined) return "unknown";
28 const stored = typeof row.key_hash === "string" && /^[0-9a-f]{64}$/.test(row.key_hash) ? Buffer.from(row.key_hash, "hex") : null;
29 if (stored === null || key === "" || key.length > 200 || !timingSafeEqual(stored, hashOf(key))) return "wrong";
30 db.run("DELETE FROM tab_shared WHERE id = ?", [id]);
31 return "gone";
32 }
src/tab/share.ts +20 −5
@@ -8,7 +8,7 @@
88 import { decodeApp, LIMITS, type BlockApp } from "./blocks.ts";
99 import type { TabDb } from "./forge.ts";
1010 import { esc } from "./escape.ts";
11 import { pageOf, renderApp } from "./render.ts";
11 import { pageOf, renderApp, ROOT } from "./render.ts";
1212
1313 /** Where the link is made (POST) and opened (GET, with the id after a slash). */
1414 export const SHARE_PATH = "/tabforge-link";
@@ -30,12 +30,12 @@ const newId = (): string => Buffer.from(crypto.getRandomValues(new Uint8Array(12
3030 * Publish `input` (the app's JSON text) for the connection `bucket`. Stores nothing unless it
3131 * decodes; keeps the newest `KEPT` links and lets the older go.
3232 */
33 export function shareApp(db: TabDb, input: string, bucket: string, now: number): Shared {
33 export function shareApp(db: TabDb, input: string, bucket: string, now: number, keyHash: string | null = null): Shared {
3434 if (input.length > LIMITS.json) return { ok: false, status: 413, why: "This app is too large to send." };
3535 const decoded = decodeApp(input);
3636 if (!decoded.ok) return { ok: false, status: 422, why: decoded.why };
3737 const id = newId();
38 db.run("INSERT INTO tab_shared (id, spec, bucket, created) VALUES (?, ?, ?, ?)", [id, JSON.stringify(decoded.app), bucket, now]);
38 db.run("INSERT INTO tab_shared (id, spec, bucket, created, key_hash) VALUES (?, ?, ?, ?, ?)", [id, JSON.stringify(decoded.app), bucket, now, keyHash ?? ""]);
3939 db.run("DELETE FROM tab_shared WHERE rowid <= (SELECT max(rowid) FROM tab_shared) - ?", [KEPT]);
4040 return { ok: true, id };
4141 }
@@ -60,5 +60,20 @@ export const sharedPage = (app: BlockApp): string =>
6060 * A form the app's page offers, to `action` (the link or the move): the app's JSON travels in the
6161 * form, so it works with script off.
6262 */
63 export const linkForm = (app: BlockApp, label: string, action: string = SHARE_PATH): string =>
64 `<form method="post" action="${action}" target="_blank" class="link"><input type="hidden" name="app" value="${esc(JSON.stringify(app))}"><button>${esc(label)}</button></form>`;
63 export const linkForm = (app: BlockApp, label: string, action: string = SHARE_PATH, from?: number): string =>
64 `<form method="post" action="${action}" target="_blank" class="link"><input type="hidden" name="app" value="${esc(JSON.stringify(app))}">${from === undefined ? "" : `<input type="hidden" name="from" value="${from}">`}<button>${esc(label)}</button></form>`;
65
66 /**
67 * The answer's form that keeps the revoke key in the tab's own store (#18398): it posts to the
68 * tab forge's page for app `from`, which the service worker answers in a browser that runs one.
69 */
70 export const keepKeyForm = (from: number, link: string, key: string): string =>
71 `<form method="post" action="${ROOT}/apps/${from}/links" class="link"><input type="hidden" name="link" value="${esc(link)}"><input type="hidden" name="key" value="${esc(key)}"><button>Keep the key in my tab</button></form>`;
72
73 /** The answer's form that makes the tab drop a kept link that is gone (a same-origin POST). */
74 export const forgetKeyForm = (from: number, link: string): string =>
75 `<form method="post" action="${ROOT}/apps/${from}/links" class="link"><input type="hidden" name="forget" value="${esc(link)}"><button>Remove it from my tab's list</button></form>`;
76
77 /** One kept link as the app's page lists it, with its Stop sharing form (a same-origin POST). */
78 export const keptLinkRow = (link: string, key: string, from: number): string =>
79 `<li><a href="${SHARE_PATH}/${esc(link)}">${esc(link)}</a> <form method="post" action="${SHARE_PATH}/${esc(link)}/revoke" class="link"><input type="hidden" name="key" value="${esc(key)}"><input type="hidden" name="from" value="${from}"><button>Stop sharing</button></form></li>`;
src/tab/words.ts +7 −1
@@ -25,6 +25,12 @@ export const TAB_MOVE = "An app is one JSON file: download it from the forge's h
2525 export const TAB_LINK_LABEL = "Get a link";
2626 export const TAB_LINK = "Get a link: send an app to the forge and get one read-only address that opens it on any device, with no login. Only the app goes, never its entries; anyone with the address can read it, so share it only where you mean to.";
2727
28 /**
29 * Taking a link back (#18398): the key made with the link is shown once and kept in this tab, never
30 * in the link; the app's page lists the links this tab made, each with Stop sharing.
31 */
32 export const TAB_REVOKE = "Stop sharing: each link made here has a key, shown once and kept in this tab (never in the link). Stop sharing with the right key deletes the link, which then opens nothing; a wrong key changes nothing. Clearing this site's data loses the keys, and links made before keys existed cannot be stopped.";
33
2834 /**
2935 * The move an app's page offers (#18114): the app goes to this forge held by this browser's
3036 * visitor, and signing in or up offers it to the account. The Apple app's on-device mode sends the
@@ -50,4 +56,4 @@ export const TAB_MODEL: readonly string[] = [
5056 export const TAB_WHOLE = "Once started it fills the tab. Its What works page names every page of the hosted forge and says whether it works here, works differently or cannot work in a tab (and why); its Runners page says what a tab can and cannot run. It reopens where you were after a reload or a new tab, and asks the browser to keep its storage.";
5157
5258 /** The terminal's one sentence: the facts and where the page is. */
53 export const tabLine = (): string => `${TAB_FACTS.join(" ")} ${TAB_LEFT_OUT} ${TAB_MOVE} ${TAB_LINK} ${TAB_KEEP} ${TAB_MODEL.join(" ")} ${TAB_WHOLE} Open /tab in a browser to start it and to make an app from a sentence.`;
59 export const tabLine = (): string => `${TAB_FACTS.join(" ")} ${TAB_LEFT_OUT} ${TAB_MOVE} ${TAB_LINK} ${TAB_REVOKE} ${TAB_KEEP} ${TAB_MODEL.join(" ")} ${TAB_WHOLE} Open /tab in a browser to start it and to make an app from a sentence.`;
test/tab-share-revoke.test.ts added +131
@@ -0,0 +1,131 @@
1 /**
2 * A read-only link can be taken back by whoever made it (#18398): the key is shown once and only
3 * its hash is stored; the right key deletes the row; a wrong or no key, or an old row with no hash,
4 * changes nothing.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
12 import { setStrangerLimits, STRANGER_LIMITS } from "../src/http/strangers.ts";
13 import { compile } from "../src/tab/compile.ts";
14 import { handle, migrate } from "../src/tab/forge.ts";
15 import { TAB_REVOKE, tabLine } from "../src/tab/words.ts";
16 import { open } from "./support/tab-db.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18
19 quietLogs();
20
21 let dir = "";
22 let app: App;
23 let http: ForgeHttp;
24 const post = (path: string, body: Record<string, string>, origin = "http://forge.test") =>
25 http.handle(new Request(`http://forge.test${path}`, { method: "POST", body: new URLSearchParams(body).toString(), headers: { "content-type": "application/x-www-form-urlencoded", origin } }));
26 const open_ = async (id: string) => (await http.handle(new Request(`http://forge.test/tabforge-link/${id}`))).status;
27 const make = async () => {
28 const res = await post("/tabforge-link", { app: JSON.stringify(compile("a journal").app), from: "1" });
29 const text = await res.text();
30 return { id: /tabforge-link\/([A-Za-z0-9_-]{16})"/.exec(text)![1]!, key: /<code>([A-Za-z0-9_-]+)<\/code>/.exec(text)![1]!, text };
31 };
32
33 beforeAll(async () => {
34 dir = await mkdtemp(join(tmpdir(), "forge-tabrevoke-"));
35 app = createApp({ dataDir: dir, port: 0 });
36 http = forgeHttp(app);
37 });
38 afterAll(async () => {
39 http.close();
40 app.close();
41 await rm(dir, { recursive: true, force: true });
42 });
43
44 test("making a link shows a key once, stores only its hash, and the right key revokes", async () => {
45 const { id, key, text } = await make();
46 expect(text).toContain(`action="/tab/f/apps/1/links"`);
47 const row = app.db.query("SELECT key_hash FROM tab_shared WHERE id = ?").get(id) as { key_hash: string };
48 expect(row.key_hash).toMatch(/^[0-9a-f]{64}$/);
49 expect(row.key_hash).not.toContain(key);
50 expect(await open_(id)).toBe(200);
51 const res = await post(`/tabforge-link/${id}/revoke`, { key });
52 expect(res.status).toBe(200);
53 expect(await res.text()).toContain("Sharing stopped");
54 expect(await open_(id)).toBe(404);
55 });
56
57 test("a revoke from the tab's list offers to forget the row, and the list then drops it", async () => {
58 const { id, key } = await make();
59 const res = await post(`/tabforge-link/${id}/revoke`, { key, from: "1" });
60 const text = await res.text();
61 expect(text).toContain(`action="/tab/f/apps/1/links"`);
62 expect(text).toContain(`name="forget" value="${id}"`);
63 const again = await post(`/tabforge-link/${id}/revoke`, { key, from: "1" });
64 expect(again.status).toBe(404);
65 expect(await again.text()).toContain(`name="forget" value="${id}"`);
66 const db = open();
67 migrate(db);
68 handle(db, { method: "POST", path: "/apps", form: { say: "a shopping list" } }, 1);
69 handle(db, { method: "POST", path: "/apps/1/links", form: { link: id, key } }, 1);
70 expect(handle(db, { method: "GET", path: "/apps/1", form: {} }, 1).html).toContain(`/tabforge-link/${id}/revoke`);
71 expect(handle(db, { method: "POST", path: "/apps/1/links", form: { forget: "bad" } }, 1).status).toBe(422);
72 expect(handle(db, { method: "POST", path: "/apps/1/links", form: { forget: id } }, 1).status).toBe(303);
73 expect(handle(db, { method: "GET", path: "/apps/1", form: {} }, 1).html).not.toContain(`/tabforge-link/${id}/revoke`);
74 });
75
76 test("a wrong or missing key leaves the link and says so", async () => {
77 const { id } = await make();
78 for (const body of [{ key: "nope" }, {}]) {
79 const res = await post(`/tabforge-link/${id}/revoke`, body);
80 expect(res.status).toBe(403);
81 expect(await res.text()).toContain("Nothing changed");
82 }
83 expect(await open_(id)).toBe(200);
84 });
85
86 test("another origin cannot revoke, and an unknown link is the one 404", async () => {
87 const { id, key } = await make();
88 expect((await post(`/tabforge-link/${id}/revoke`, { key }, "http://evil.test")).status).toBe(403);
89 expect(await open_(id)).toBe(200);
90 expect((await post("/tabforge-link/AAAAAAAAAAAAAAAA/revoke", { key })).status).toBe(404);
91 });
92
93 test("an old row with no hash stays openable and cannot be revoked", async () => {
94 app.db.query("INSERT INTO tab_shared (id, spec, bucket, created) VALUES ('OLDOLDOLDOLDOLD1', ?, 'b', 1)").run(JSON.stringify(compile("a journal").app));
95 expect(await open_("OLDOLDOLDOLDOLD1")).toBe(200);
96 expect((await post("/tabforge-link/OLDOLDOLDOLDOLD1/revoke", { key: "" })).status).toBe(403);
97 expect((await post("/tabforge-link/OLDOLDOLDOLDOLD1/revoke", { key: "anything" })).status).toBe(403);
98 expect(await open_("OLDOLDOLDOLDOLD1")).toBe(200);
99 });
100
101 test("the tab keeps the key and its page lists the link with Stop sharing", () => {
102 const db = open();
103 migrate(db);
104 handle(db, { method: "POST", path: "/apps", form: { say: "a shopping list" } }, 1);
105 expect(handle(db, { method: "POST", path: "/apps/1/links", form: { link: "bad", key: "k" } }, 1).status).toBe(422);
106 const kept = handle(db, { method: "POST", path: "/apps/1/links", form: { link: "AAAAAAAAAAAAAAAA", key: "secretkey" } }, 1);
107 expect(kept.status).toBe(303);
108 const page = handle(db, { method: "GET", path: "/apps/1", form: {} }, 1).html;
109 expect(page).toContain('action="/tabforge-link/AAAAAAAAAAAAAAAA/revoke"');
110 expect(page).toContain("Stop sharing");
111 expect(page).toContain('name="from" value="1"');
112 expect(tabLine()).toContain(TAB_REVOKE);
113 });
114
115 test("revoke has its own door: the 11th try in a minute is 429, and making a link still answers", async () => {
116 setStrangerLimits(app, {});
117 const { id } = await make();
118 for (let i = 0; i < STRANGER_LIMITS.perAddress.revoke; i++) expect((await post(`/tabforge-link/${id}/revoke`, { key: "nope" })).status).toBe(403);
119 const refused = await post(`/tabforge-link/${id}/revoke`, { key: "nope" });
120 expect(refused.status).toBe(429);
121 expect(await refused.text()).toContain("Too many tries");
122 expect((await post("/tabforge-link", { app: JSON.stringify(compile("a journal").app) })).status).toBe(201);
123 setStrangerLimits(app, {});
124 });
125
126 test("with no app number, the answer page says once what the key is for", async () => {
127 const res = await post("/tabforge-link", { app: JSON.stringify(compile("a journal").app) });
128 const text = await res.text();
129 expect(text.split("the only way to take this link back").length).toBe(2);
130 expect(text).toContain("Keep it somewhere safe.");
131 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs