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

Access 5c: the tab forge and the Apple app's on-device mode present the same visitor to a shared forge, so apps made without a login arrive owned #18275

opened this

Merged 24m ago, live in production

scout/forge:scout/18114-access-5c-the-tab-forge-and-the-apple-ap → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/18114-access-5c-the-tab-forge-and-the-apple-ap was merged into main as ec352f4.

Review

Sign in to review this change.
28 files changed +478 −52
docs/features/browser-forge-move.md +10
@@ -14,3 +14,13 @@ A forge that runs in a browser tab lives on that device and stops when the tab c
1414 - **Not done.** Files past 32 MiB together (the form is read whole to check it; a streamed upload would lift it toward the shared forge's 50 MiB); carrying the browser forge's own sign-in sessions to the new address; the browser forge's side of the button (checkpoint the WAL, tar `repos/`, post the form): this repository holds only the tab forge's storage worker (`src/web/tabforge`), with no page, no git data and no tar writer for a tab to run it from, so the form is what that button will post (#17377); an API or MCP route (a file does not go through a tool call); charging at a payment provider (the plan is the shared plan, billed as other shared forges are).
1515
1616 Code: `src/spawn/move_in.ts`, `src/web/pages/forge_move_in.ts`, `recordMovedIn` in `src/actions/spawn.ts`, the `moveIn` cap in `src/kernel/body_caps.ts`. Test: `test/move-in.test.ts`.
17
18 ## Apps made without a login come along (#18114)
19
20 Moving the whole forge is one way; an app made in the tab forge's *Make an app* (or the Apple app's "Build on this device", which writes the same Blocks JSON, #18079) moves alone. The app's page in the tab has **Keep it on my account**: a form that posts the app's JSON (field `app`) to `POST /tabforge-move` on this forge. The forge decodes it with the tab's own `decodeApp` (so the same limits apply; a spec that does not fit keeps nothing and says why), keeps the app (never its entries) in `tab_moved`, held by this browser's visitor (the signed `forge_maker` cookie, minted then if the browser has none, within the visitor's daily caps), and sends the person to **Settings › Brought in** (`/settings/bring`, the Access 5b list in `visitor-bring.md`).
21
22 There, not signed in, they sign in or up and come back; arriving brings nothing. The app is listed as "An app, *title*, moved from a tab", unticked beside any notes. Ticking it and pressing **Bring the ones ticked** makes it the account's: it is listed under **Apps from a tab** on that page, and in the terminal's **Brought in** screen. The receipt undoes it for 24 hours, as for notes. Another device's visitor never sees it: the list is by the visitor that moved it, and a pick of an id that is not that visitor's is passed over. Someone already signed in skips all of that: the account holds the app at once, with no visitor cookie and nothing to tick, and Brought in lists it under **Apps from a tab**. A browser that sends `Sec-GPC: 1` or `DNT: 1` while nobody is signed in has no visitor to hold it, so the forge says to sign in first and keeps nothing; signed in, it keeps the app on the account.
23
24 The terminal cannot move an app (it lives in a browser tab's storage) or pick one (the visitor is a browser cookie); its tab entry says the same words (`TAB_KEEP`, `src/tab/words.ts`) and **Brought in** lists the account's apps from a tab. Not done: opening or editing a moved app on the shared forge (it is kept as its spec, and listed); the Apple app's own button, which lives in forge-apple and posts the same field to the same address.
25
26 Code: `tabMoveIn` in `src/web/pages/tabforge-link.ts`, `keepMoved`, `madeBy` and `movedAppsOf` in `src/core/visitor_bring.ts`. Test: `test/visitor-move.test.ts`.
outdated

This Code: line belongs to the move-in section above. The new section was inserted before it, so it now trails the wrong section. Put the new section after it, or give each section its own line.

docs/features/tab.md +1 −1
@@ -49,7 +49,7 @@ the file.
4949
5050 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`.
5151
52 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.
52 Not done: the Apple app reading the file; read-only revocable links. Carrying an app to an account on sign-in is the app page's *Keep it on my account* (`browser-forge-move.md`, #18114). 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.
5353
5454 ## A small model fills the spec (#18044)
5555
docs/features/visitor-bring.md +4
@@ -19,6 +19,10 @@ replaces the earlier ticket: each visitor holds one live ticket. Each note becom
1919 account's own: you see its replies on that app when signed in. The issue that was filed is not
2020 rewritten. Notes the app's owner hid or banned do not come along.
2121
22 An app made without a login in the tab forge comes the same way: its **Keep it on my account**
23 holds it for this browser's visitor and opens this page, where it is listed beside the notes; once
24 brought it is under **Apps from a tab** (`browser-forge-move.md`, #18114).
25
2226 Every bring is a receipt under **Brought**, with **Undo** for 24 hours. Undo gives the notes back
2327 to the visitor. Both are events for you alone (`visitor.brought`, `visitor.undone`).
2428
src/actions/visitor_bring.ts +7 −1
@@ -15,7 +15,7 @@ import type { Auth } from "../http/context.ts";
1515 import { passkeyIds } from "../core/passkeys.ts";
1616 import { sessionStartedAt } from "../core/sessions.ts";
1717 import type { User } from "../core/users.ts";
18 import { bring, MADE_SHOWN, madeBy, receiptsOf, undoBring, type Made, type Receipt, type UndoRefusal } from "../core/visitor_bring.ts";
18 import { bring, MADE_SHOWN, madeBy, movedAppsOf, receiptsOf, undoBring, type Made, type MovedApp, type Receipt, type UndoRefusal } from "../core/visitor_bring.ts";
1919 import { carriedVisitor, heldVisitor, spendCarry } from "../core/visitors.ts";
2020 import { loadKey } from "../kernel/secret.ts";
2121 import { err, ok, type Result } from "../kernel/result.ts";
@@ -94,6 +94,12 @@ export function bringToAccount(
9494 return ok(receipt);
9595 }
9696
97 /** One receipt's count, in the words both doors use: notes and apps alike are things brought. */
98 export const broughtCount = (n: number): string => `${String(n)} ${n === 1 ? "thing" : "things"} brought`;
99
100 /** The apps this account holds, moved from a tab (#18114) and brought, newest first. */
101 export const movedApps = (app: App, user: User): MovedApp[] => movedAppsOf(app.db, user.id);
102
97103 /** This account's receipts, newest first. */
98104 export const broughtReceipts = (app: App, user: User): Receipt[] => receiptsOf(app.db, user.id);
99105
src/core/account_purge.ts +4
@@ -176,6 +176,7 @@ export const COVERED: Readonly<Record<string, Coverage>> = {
176176 "review.origin_author": { do: "none", why: "the outside author's name a mirrored review came with" },
177177 "review_thread.resolved_by": FORMER,
178178 "rp_login.link_user": DELETE,
179 "tab_moved.holder": { do: "none", why: "a keyed holder, `u:<id>` or `v:<visitor>`: `purgeAccount` deletes the person's `u:` rows" },
179180 "run.holder": { do: "none", why: "the process that holds a run's lease" },
180181 "secret_grant.granted_by": FORMER,
181182 "start_account.claimed_by": FORMER,
@@ -399,6 +400,9 @@ export function purgeAccount(db: Database, userId: string, now: Date, dataDir =
399400 // `entitlement.payer` is an address, not an id: an ended plan forgets who paid.
400401 const email = db.query<{ email: string }, [string]>("SELECT email FROM user WHERE id = ?1").get(userId)?.email ?? "";
401402 if (email !== "") kept += db.query("UPDATE entitlement SET payer = '' WHERE payer = ?1 COLLATE NOCASE").run(email).changes;
403 // An app they moved from the tab forge and brought to their account is theirs: it goes
404 // (#18114).
405 deleted += db.query("DELETE FROM tab_moved WHERE holder = ?1").run(`u:${userId}`).changes;
402406 // A read grant to this person (as a crew member) goes with them (#10521).
403407 db.query("DELETE FROM origin_read_grant WHERE grantee_id = ?1").run(userId);
404408 // The row itself; its cascades take emails, keys, tokens, sessions, passkeys and settings.
src/core/migration-pins/20261204130000-tab-moved-apps.pin added +1
@@ -0,0 +1,1 @@
1 7f3d27ae4bd7a939be82ce5872bc0c687bbee580751f893744782f2932cbc038
src/core/migrations/20261204130000-tab-moved-apps.ts added +14
@@ -0,0 +1,14 @@
1 // An app made without a login, moved from the tab forge (or the Apple app's on-device mode) to
2 // this forge (#18114): the decoded Blocks spec (#18079) and who holds it, keyed as a note is,
3 // `v:<visitor id>` until the person brings it to an account, then `u:<user id>`. Additive; the
4 // app's entries never come, only the app.
5 export default `
6 CREATE TABLE tab_moved (
7 id TEXT PRIMARY KEY,
8 holder TEXT NOT NULL,
9 spec TEXT NOT NULL,
10 title TEXT NOT NULL,
11 created_at TEXT NOT NULL
12 ) WITHOUT ROWID;
13 CREATE INDEX tab_moved_holder ON tab_moved(holder, created_at);
14 `;
src/core/reserved.ts +1
@@ -159,6 +159,7 @@ export const SYSTEM_NAMES: readonly string[] = [
159159 "talk",
160160 "tabforge",
161161 "tabforge-link",
162 "tabforge-move",
162163 "peek",
163164 "notes",
164165 "next",
src/core/visitor_bring.ts +53 −5
@@ -17,8 +17,13 @@ export const MADE_SHOWN = 200;
1717 /** How long a bring may be undone. */
1818 export const UNDO_MS = 24 * 3_600_000;
1919
20 /** One thing a visitor made, as the person deciding whether to bring it sees it. */
20 /**
21 * One thing a visitor made, as the person deciding whether to bring it sees it: a note on an app,
22 * or an app made without a login and moved here from a tab or the Apple app (#18114), whose `app`
23 * is its title and `issueNumber` 0.
24 */
2125 export interface Made {
26 readonly kind: "note" | "app";
2227 readonly noteId: string;
2328 readonly app: string;
2429 readonly issueNumber: number;
@@ -44,7 +49,7 @@ const userKey = (userId: string): string => `u:${userId}`;
4449 * at most `limit`.
4550 */
4651 export function madeBy(db: Database, visitorId: string, limit: number = MADE_SHOWN): Made[] {
47 return db
52 const notes = db
4853 .query<{ id: string; slug: string; issue_number: number; title: string | null; created_at: string }, [string, number]>(
4954 `SELECT n.id, a.slug, n.issue_number, i.title, n.created_at
5055 FROM app_note n
@@ -56,9 +61,48 @@ export function madeBy(db: Database, visitorId: string, limit: number = MADE_SHO
5661 LIMIT ?2`,
5762 )
5863 .all(visitorKey(visitorId), limit)
59 .map((r) => ({ noteId: r.id, app: r.slug, issueNumber: r.issue_number, title: r.title ?? "", createdAt: r.created_at }));
64 .map((r): Made => ({ kind: "note", noteId: r.id, app: r.slug, issueNumber: r.issue_number, title: r.title ?? "", createdAt: r.created_at }));
65 const apps = db
66 .query<{ id: string; title: string; created_at: string }, [string, number]>(
67 "SELECT id, title, created_at FROM tab_moved WHERE holder = ?1 ORDER BY created_at DESC, id DESC LIMIT ?2",
68 )
69 .all(visitorKey(visitorId), limit)
70 .map((r): Made => ({ kind: "app", noteId: r.id, app: r.title, issueNumber: 0, title: "", createdAt: r.created_at }));
71 return [...apps, ...notes].sort((a, b) => b.createdAt.localeCompare(a.createdAt)).slice(0, limit);
6072 }
6173
74 /** An app moved from a tab that an account holds (#18114). */
75 export interface MovedApp {
76 readonly id: string;
77 readonly title: string;
78 readonly createdAt: string;
79 }
80
81 /** Who holds a moved app: a visitor until they bring it, or straight away a signed-in account. */
82 export type MoveHolder = { readonly visitorId: string } | { readonly userId: string };
83
84 /** Keep an app moved from a tab, held by `holder`; its id. */
85 export function keepMoved(db: Database, holder: MoveHolder, spec: string, title: string, at: number = Date.now()): string {
86 const id = newId();
87 db.run("INSERT INTO tab_moved (id, holder, spec, title, created_at) VALUES (?, ?, ?, ?, ?)", [
88 id,
89 "userId" in holder ? userKey(holder.userId) : visitorKey(holder.visitorId),
90 spec,
91 title,
92 new Date(at).toISOString(),
93 ]);
94 return id;
95 }
96
97 /** The apps this account holds, moved from a tab and brought, newest first. */
98 export const movedAppsOf = (db: Database, userId: string, limit = MADE_SHOWN): MovedApp[] =>
99 db
100 .query<{ id: string; title: string; created_at: string }, [string, number]>(
101 "SELECT id, title, created_at FROM tab_moved WHERE holder = ?1 ORDER BY created_at DESC, id DESC LIMIT ?2",
102 )
103 .all(userKey(userId), limit)
104 .map((r) => ({ id: r.id, title: r.title, createdAt: r.created_at }));
105
62106 /**
63107 * Re-point the picked notes of this visitor to the account, and keep the receipt. A pick that is
64108 * not among `madeBy` (another visitor's, hidden, banned, already brought) is passed over; nothing
@@ -90,7 +134,8 @@ export function bring(
90134 receipt.undoUntil,
91135 ]);
92136 for (const noteId of chosen) {
93 const was = db.query<{ name: string }, [string]>("SELECT name FROM app_note WHERE id = ?").get(noteId)!;
137 // An app moved from a tab has no name to keep: its row is re-pointed and nothing else.
138 const was = db.query<{ name: string }, [string]>("SELECT name FROM app_note WHERE id = ?").get(noteId) ?? { name: "" };
94139 db.run("INSERT INTO visitor_bring_row (bring_id, note_id, was_visitor, was_name) VALUES (?, ?, ?, ?)", [
95140 receipt.id,
96141 noteId,
@@ -103,6 +148,7 @@ export function bring(
103148 noteId,
104149 visitorKey(visitorId),
105150 ]);
151 db.run("UPDATE tab_moved SET holder = ? WHERE id = ? AND holder = ?", [userKey(user.id), noteId, visitorKey(visitorId)]);
106152 }
107153 })();
108154 return receipt;
@@ -150,8 +196,10 @@ export function undoBring(db: Database, userId: string, bringId: string, at: num
150196 "SELECT note_id, was_visitor, was_name FROM visitor_bring_row WHERE bring_id = ?",
151197 )
152198 .all(bringId);
153 for (const r of rows)
199 for (const r of rows) {
154200 db.run("UPDATE app_note SET visitor = ?, name = ? WHERE id = ? AND visitor = ?", [r.was_visitor, r.was_name, r.note_id, userKey(userId)]);
201 db.run("UPDATE tab_moved SET holder = ? WHERE id = ? AND holder = ?", [r.was_visitor, r.note_id, userKey(userId)]);
202 }
155203 db.run("UPDATE visitor_bring SET undone_at = ? WHERE id = ?", [undoneAt, bringId]);
156204 })();
157205 return { ...found, undoneAt };
src/generated/marks.ts +15 −13
@@ -205,19 +205,20 @@ import k200 from "../http/marks/sw.js.json";
205205 import k201 from "../http/marks/system.json";
206206 import k202 from "../http/marks/tab.json";
207207 import k203 from "../http/marks/tabforge-link.json";
208 import k204 from "../http/marks/tabforge.json";
209 import k205 from "../http/marks/talk.json";
210 import k206 from "../http/marks/tell.json";
211 import k207 from "../http/marks/templates.json";
212 import k208 from "../http/marks/templates.json.json";
213 import k209 from "../http/marks/terms.json";
214 import k210 from "../http/marks/theme.json";
215 import k211 from "../http/marks/toolbar-lab.js.json";
216 import k212 from "../http/marks/toolbar-lab.json";
217 import k213 from "../http/marks/traces.json";
218 import k214 from "../http/marks/verify.json";
219 import k215 from "../http/marks/welcome.json";
220 import k216 from "../http/marks/well-known.json";
208 import k204 from "../http/marks/tabforge-move.json";
209 import k205 from "../http/marks/tabforge.json";
210 import k206 from "../http/marks/talk.json";
211 import k207 from "../http/marks/tell.json";
212 import k208 from "../http/marks/templates.json";
213 import k209 from "../http/marks/templates.json.json";
214 import k210 from "../http/marks/terms.json";
215 import k211 from "../http/marks/theme.json";
216 import k212 from "../http/marks/toolbar-lab.js.json";
217 import k213 from "../http/marks/toolbar-lab.json";
218 import k214 from "../http/marks/traces.json";
219 import k215 from "../http/marks/verify.json";
220 import k216 from "../http/marks/welcome.json";
221 import k217 from "../http/marks/well-known.json";
221222
222223 /** Each file of `http/marks/`, parsed, in name order. */
223224 export const MARK_FILES: readonly unknown[] = [
@@ -438,4 +439,5 @@ export const MARK_FILES: readonly unknown[] = [
438439 k214,
439440 k215,
440441 k216,
442 k217,
441443 ];
src/http/lazy_lists.ts +1
@@ -484,6 +484,7 @@ export const DISCOVERY_ROUTES = [
484484 ["GET", "/tabforge"],
485485 ["POST", "/tabforge-link"],
486486 ["GET", "/tabforge-link/:id"],
487 ["POST", "/tabforge-move"],
487488 ] as const;
488489
489490 /** `docsRoutes` (`routes/docs.ts`). */
src/http/marks/tabforge-move.json added +4
@@ -0,0 +1,4 @@
1 {
2 "head": "/tabforge-move",
3 "mark": "open"
4 }
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 } from "../../web/pages/tabforge-link.ts";
17 import { tabLinkMake, tabLinkOpen, 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,4 +139,5 @@ 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-move", tabMoveIn);
142143 }
src/tab/apps.ts +3 −3
@@ -7,9 +7,9 @@ import { esc } from "./escape.ts";
77 import { settle } from "./fill.ts";
88 import type { TabDb, TabReply, TabRequest } from "./forge.ts";
99 import { ROOT, renderApp, type Rec } from "./render.ts";
10 import { linkForm } from "./share.ts";
10 import { linkForm, MOVE_PATH } from "./share.ts";
1111 import { shell } from "./shell.ts";
12 import { TAB_LINK, TAB_LINK_LABEL } from "./words.ts";
12 import { TAB_KEEP, TAB_KEEP_LABEL, TAB_LINK, TAB_LINK_LABEL } from "./words.ts";
1313 import { decodeApp, entryText, SPEC_VERSION, type BlockApp } from "./blocks.ts";
1414
1515 export const SAY_MAX = 300;
@@ -95,7 +95,7 @@ export function handleApps(db: TabDb, req: TabRequest, path: string, now: number
9595 if (req.method === "GET" && parts.length === 1)
9696 return found === null
9797 ? 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)}`)
98 : 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)}${removeForm(id, title)}`, 200, false);
98 : 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)}<p class="muted">${esc(TAB_KEEP)}</p>${linkForm(found.app, TAB_KEEP_LABEL, MOVE_PATH)}${removeForm(id, title)}`, 200, false);
9999 if (req.method === "GET" && parts[1] === "source" && parts.length === 2) return found === null ? notFound() : shell(`${found.app.title}: why`, source(found));
100100 if (req.method !== "POST") return shell("Not allowed", "<p>That is not something this forge does.</p>", 405);
101101 if (parts[1] === "delete" && parts.length === 2) {
src/tab/share.ts +6 −3
@@ -12,6 +12,8 @@ import { pageOf, renderApp } 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";
15 /** Where an app is moved to this forge, to be brought to an account (#18114): POST only. */
16 export const MOVE_PATH = "/tabforge-move";
1517 /** The most bytes of a form that carries an app: the JSON, percent-encoded, with room. */
1618 export const SHARE_BODY_MAX = LIMITS.json * 4;
1719 /** Links the forge keeps; past this the oldest go as a new one comes in. */
@@ -55,7 +57,8 @@ export const sharedPage = (app: BlockApp): string =>
5557 pageOf(app.title, `${renderApp(app, { appId: null, records: [], today: "" })}<p class="muted">A read-only copy of an app made in a forge in a browser tab. <a href="/tab">Make your own</a>.</p>`);
5658
5759 /**
58 * The form the app's page offers: the app's JSON travels in the form, so it works with script off.
60 * A form the app's page offers, to `action` (the link or the move): the app's JSON travels in the
61 * form, so it works with script off.
5962 */
60 export const linkForm = (app: BlockApp, label: string): string =>
61 `<form method="post" action="${SHARE_PATH}" 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): 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>`;
src/tab/words.ts +9 −1
@@ -25,6 +25,14 @@ 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 * The move an app's page offers (#18114): the app goes to this forge held by this browser's
30 * visitor, and signing in or up offers it to the account. The Apple app's on-device mode sends the
31 * same Blocks JSON to the same door.
32 */
33 export const TAB_KEEP_LABEL = "Keep it on my account";
34 export const TAB_KEEP = "Keep it on my account: send this app to the forge, then sign in or sign up and tick it to make it your account's. Only the app goes, never its entries, and nobody else sees it; a browser that asks not to be tracked must sign in first.";
35
2836 /**
2937 * The optional model, said before anything is downloaded. It only fills the app's spec (a title, a
3038 * kind and a few words, checked against a schema); the compiler writes the spec when there is no
@@ -42,4 +50,4 @@ export const TAB_MODEL: readonly string[] = [
4250 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.";
4351
4452 /** The terminal's one sentence: the facts and where the page is. */
45 export const tabLine = (): string => `${TAB_FACTS.join(" ")} ${TAB_LEFT_OUT} ${TAB_MOVE} ${TAB_LINK} ${TAB_MODEL.join(" ")} ${TAB_WHOLE} Open /tab in a browser to start it and to make an app from a sentence.`;
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.`;
src/tui/screens/visitor_bring.ts +10 −6
@@ -6,7 +6,7 @@
66 * which a terminal never holds, so this screen says where to go instead.
77 */
88
9 import { BRING_WORDS, broughtReceipts, undoBrought } from "../../actions/visitor_bring.ts";
9 import { BRING_WORDS, broughtCount, broughtReceipts, movedApps, undoBrought } from "../../actions/visitor_bring.ts";
1010 import type { Receipt } from "../../core/visitor_bring.ts";
1111 import type { Ctx, Screen } from "../app/app.ts";
1212 import { binding } from "../app/keys.ts";
@@ -18,7 +18,10 @@ import { ListState, ago, confirmScreen, drawList, type ListRow } from "./common.
1818
1919 /** Where bringing starts, said when there is nothing here yet. */
2020 const BRING_FROM_BROWSER =
21 "Nothing brought yet. On an app, the forge button's \"Keep these on my account\" brings a visitor's notes.";
21 "Nothing brought yet. On an app, the forge button's \"Keep these on my account\" brings a visitor's notes; in a tab forge, an app's \"Keep it on my account\" brings the app.";
22
23 /** The apps this account holds from a tab, the page's "Apps from a tab", in one line. */
24 const appsLine = (titles: readonly string[]): string => (titles.length === 0 ? "" : ` Apps from a tab: ${titles.join(", ")}.`);
2225
2326 const undoable = (r: Receipt, now: number): boolean => r.undoneAt === null && Date.parse(r.undoUntil) > now;
2427
@@ -29,7 +32,7 @@ export function visitorBringScreen(f: Session, ctx: Ctx): Screen {
2932 const rows = (): ListRow[] => {
3033 const now = Date.now();
3134 return items().map((r) => ({
32 title: `${r.count} ${r.count === 1 ? "note" : "notes"} brought`,
35 title: broughtCount(r.count),
3336 meta: `${ago(r.at)} · ${r.undoneAt !== null ? "undone" : undoable(r, now) ? "u undoes, for 24 hours" : "kept"}`,
3437 }));
3538 };
@@ -40,7 +43,8 @@ export function visitorBringScreen(f: Session, ctx: Ctx): Screen {
4043 render(area, s) {
4144 const c = ctx.theme.c;
4245 const [head, body] = split(area, "v", [len(1), fill(1)]);
43 const text = note !== "" ? note : items().length === 0 ? BRING_FROM_BROWSER : "What you made before signing in, kept on your account.";
46 const apps = f.user === undefined ? "" : appsLine(movedApps(f.app, f.user).map((a) => a.title));

This adds terminal behaviour (the "Apps from a tab" line on Brought in) with no test that would fail without it. Add one.

47 const text = (note !== "" ? note : items().length === 0 ? BRING_FROM_BROWSER : "What you made before signing in, kept on your account.") + apps;
4448 s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
4549 drawList(s, body!, c, state, rows());
4650 },
@@ -56,13 +60,13 @@ export function visitorBringScreen(f: Session, ctx: Ctx): Screen {
5660 return true;
5761 }
5862 ctx.push(confirmScreen(ctx, screen, {
59 title: "Undo bringing", body: [`give ${r.count} ${r.count === 1 ? "note" : "notes"} back to the visitor? y/n`],
63 title: "Undo bringing", body: [`give ${r.count} ${r.count === 1 ? "thing" : "things"} back to the visitor? y/n`],
6064 actions: [{ label: "Undo", variant: "danger" }, { label: "Cancel", variant: "ghost" }],
6165 selected: 1, yesNo: true,
6266 onChoose: (i) => {
6367 if (i !== 0) return;
6468 const done = undoBrought(f.app, user, r.id);
65 note = done.ok ? "Undone: those notes are the visitor's again." : BRING_WORDS[done.error];
69 note = done.ok ? "Undone: those are the visitor's again." : BRING_WORDS[done.error];
6670 ctx.invalidate();
6771 },
6872 }));
src/web/pages/visitor_bring.ts +27 −12
@@ -9,8 +9,8 @@
99 * undoes them (`tui/screens/visitor_bring.ts`).
1010 */
1111
12 import { BRING_WORDS, bringable, bringToAccount, broughtReceipts, mayBring, undoBrought } from "../../actions/visitor_bring.ts";
13 import { MADE_SHOWN, type Made, type Receipt } from "../../core/visitor_bring.ts";
12 import { BRING_WORDS, broughtCount, bringable, bringToAccount, broughtReceipts, movedApps, mayBring, undoBrought } from "../../actions/visitor_bring.ts";
13 import { MADE_SHOWN, type Made, type MovedApp, type Receipt } from "../../core/visitor_bring.ts";
1414 import type { Ctx } from "../../http/context.ts";
1515 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1616 import { sshOn } from "../../settings/ssh.ts";
@@ -29,17 +29,25 @@ const MORE_WAITING = `Only the newest ${String(MADE_SHOWN)} are listed. Bring th
2929 const carryOf = (value: string | null): string => (value !== null && /^[0-9a-f]{64}$/.test(value) ? value : "");
3030
3131 const madeRow = (m: Made): Html =>
32 row({
33 lead: html`<input type="checkbox" name="pick" value="${m.noteId}" aria-label="Bring the note on ${m.app}, #${String(m.issueNumber)}" />`,
34 title: html`A note on <strong>${m.app}</strong>, #${String(m.issueNumber)}`,
35 meta: html`${m.title === "" ? null : html`${m.title} · `}${time(m.createdAt)}`,
36 });
32 m.kind === "app"
33 ? row({
34 lead: html`<input type="checkbox" name="pick" value="${m.noteId}" aria-label="Bring the app ${m.app}" />`,
35 title: html`An app, <strong>${m.app}</strong>, moved from a tab`,
36 meta: time(m.createdAt),
37 })
38 : row({
39 lead: html`<input type="checkbox" name="pick" value="${m.noteId}" aria-label="Bring the note on ${m.app}, #${String(m.issueNumber)}" />`,
40 title: html`A note on <strong>${m.app}</strong>, #${String(m.issueNumber)}`,
41 meta: html`${m.title === "" ? null : html`${m.title} · `}${time(m.createdAt)}`,
42 });
43
44 const movedRow = (a: MovedApp): Html => row({ title: html`<strong>${a.title}</strong>`, meta: html`moved from a tab · ${time(a.createdAt)}` });
3745
3846 const receiptRow = (r: Receipt, now: number): Html => {
3947 const open = r.undoneAt === null && Date.parse(r.undoUntil) > now;
4048 const said = r.undoneAt !== null ? "undone" : open ? html`undo until ${time(r.undoUntil)}` : "kept";
4149 return row({
42 title: html`${String(r.count)} ${r.count === 1 ? "note" : "notes"} brought`,
50 title: broughtCount(r.count),
4351 meta: html`${time(r.at)} · ${said}`,
4452 ...(open
4553 ? { trail: html`<form class="row-actions" method="post" action="${HERE}/${r.id}/undo">${btn("Undo", { size: "sm", label: `Undo bringing ${String(r.count)}` })}</form>` }
@@ -69,6 +77,7 @@ export function visitorBringPage(ctx: Ctx): Response {
6977 ${btn("Bring the ones ticked", { variant: "primary", size: "sm" })}
7078 </form>`;
7179 const receipts = broughtReceipts(ctx.app, user);
80 const apps = movedApps(ctx.app, user);
7281 const body = html`<section class="settings-block">
7382 <h2>Made as a visitor</h2>
7483 ${offer}
@@ -76,12 +85,18 @@ export function visitorBringPage(ctx: Ctx): Response {
7685 <section class="settings-block">
7786 <h2>Brought</h2>
7887 ${receipts.length === 0 ? emptyNote("nothingBroughtYet") : rowList(receipts.map((r) => receiptRow(r, now)), { bare: true, label: "Brought" })}
79 </section>`;
88 </section>
89 ${apps.length === 0
90 ? null
91 : html`<section class="settings-block">
92 <h2>Apps from a tab</h2>
93 ${rowList(apps.map(movedRow), { bare: true, label: "Apps from a tab" })}
94 </section>`}`;
8095 const rendering = performance.now();
8196 const response = page({
8297 ctx,
8398 title: "Brought in",
84 body: html`${pageHead("Brought in", { sub: "Notes you sent before signing in. Tick the ones that are yours to bring them to this account; you can undo for 24 hours." })}
99 body: html`${pageHead("Brought in", { sub: "Notes you sent and apps you made before signing in. Tick the ones that are yours to bring them to this account; you can undo for 24 hours." })}
85100 ${settingsLayout(accountSections("bring", { admin: user.isAdmin, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`,
86101 });
87102 notePhase(ctx.request, "render", performance.now() - rendering);
@@ -98,7 +113,7 @@ export async function visitorBringSubmit(ctx: Ctx): Promise<Response> {
98113 const done = bringToAccount(ctx.app, ctx.auth.user, ctx.auth, { carry, headers: ctx.request.headers }, picks);
99114 if (!done.ok) return flashTo(ctx, carry === "" ? HERE : `${HERE}?carry=${carry}`, { tone: "danger", message: BRING_WORDS[done.error] });
100115 const n = done.value.count;
101 return flashTo(ctx, HERE, { message: `Brought ${String(n)} ${n === 1 ? "note" : "notes"} to your account. You can undo this for 24 hours.` });
116 return flashTo(ctx, HERE, { message: `Brought ${String(n)} ${n === 1 ? "thing" : "things"} to your account. You can undo this for 24 hours.` });
102117 }
103118
104119 // POST /settings/bring/:id/undo
@@ -107,5 +122,5 @@ export async function visitorBringUndo(ctx: Ctx): Promise<Response> {
107122 const form = await readForm(ctx, "admin");
108123 if (form instanceof Response) return form;
109124 const done = undoBrought(ctx.app, ctx.auth.user, ctx.params["id"] ?? "");
110 return flashTo(ctx, HERE, done.ok ? { message: "Undone: those notes are the visitor's again." } : { tone: "danger", message: BRING_WORDS[done.error] });
125 return flashTo(ctx, HERE, done.ok ? { message: "Undone: those are the visitor's again." } : { tone: "danger", message: BRING_WORDS[done.error] });
111126 }
test/account-purge.test.ts +15
@@ -284,3 +284,18 @@ describe("every column that names a user is covered", () => {
284284 }
285285 });
286286 });
287
288 describe("an app moved from the tab forge", () => {
289 test("brought to an account goes with it; a visitor's and another's stay", async () => {
290 const ezra = await make("ezra");
291 const other = await make("ottoline");
292 app.db.run(
293 "INSERT INTO tab_moved (id, holder, spec, title, created_at) VALUES ('m1', ?1, '{}', 'a', 't'), ('m2', ?2, '{}', 'b', 't'), ('m3', 'v:visitor-1', '{}', 'c', 't')",
294 [`u:${ezra.id}`, `u:${other.id}`],
295 );
296 requestClose(app.db, ezra.id, T0);
297 await purgeDue(app, at(7));
298 const ids = app.db.query<{ id: string }, []>("SELECT id FROM tab_moved ORDER BY id").all().map((r) => r.id);
299 expect(ids).toEqual(["m2", "m3"]);
300 });
301 });
test/attention.test.ts +20
@@ -13,6 +13,7 @@ import { afterAll, beforeAll, expect, test } from "bun:test";
1313 import { readFileSync, writeFileSync } from "node:fs";
1414 import { firstView, WIDTHS, type Attention } from "../src/measure/attention.ts";
1515 import { noteKeeperAtBoot } from "../src/keeper/at_boot.ts";
16 import { askingSection, stallSection, worstStallsTable } from "../src/web/pages/system.ts";
1617 import { quietLogs } from "./helpers/globals.ts";
1718 import { freshStallState } from "./helpers/stall-state.ts";
1819 import { measure, openFirstViews, overBudget, pinnedSystem, type Budget, type FirstViews } from "./helpers/first-views.ts";
@@ -97,3 +98,22 @@ test("the budget file names every page at both widths and no other", () => {
9798 expect(Object.keys(budget).sort()).toEqual(Object.keys(pages).sort());
9899 for (const name of Object.keys(budget)) expect(widthsOf(budget[name]!)).toEqual(WIDTHS.map(String));
99100 });
101
102 test("a /system drawn on a loaded machine, its stalls and askers listed, counts as a quiet one (#18114)", async () => {
103 const raw = await views.get("/system");
104 expect(raw).toContain('<div id="sys-stalls">');
105 const stalls = stallSection(
106 [{ route: "/alice/vault", ms: 412, count: 2 }, { route: "/search", ms: 230, count: 1 }],
107 worstStallsTable([], 0, Date.now()),
108 );
109 const asking = askingSection([], { waited: 3, bounded: 1, longestMs: 40 });
110 const loaded = raw.replace(/<div id="sys-stalls">[\s\S]*?<\/section><\/div>/, `<div id="sys-stalls">${String(stalls)}</div>${String(asking)}`);
111 expect(loaded).toContain("Main-thread stalls by route");
112 expect(loaded).toContain('id="asking"');
113 const pinned = pinnedSystem(loaded);
114 for (const w of WIDTHS) {
115 const want = firstView(pages.system!, w);
116 const got = firstView(pinned, w);
117 expect({ words: got.words, blocks: got.blocks }).toEqual({ words: want.words, blocks: want.blocks });
118 }
119 });
test/forge-looks.test.ts +1
@@ -33,6 +33,7 @@ const NOT_A_PAGE: Record<string, string> = {
3333 "/pricing": "no picture: not in app.looks; the page is covered by test/pricing-order.test.ts",
3434 "/tabforge": "no picture: not in app.looks (its 32 slots are full); the page is covered by test/tabforge-page.test.ts",
3535 "/tabforge-link": "no picture: not in app.looks (its 32 slots are full); a POST that stores an app and answers a link, and /tabforge-link/<id> needs a stored app; covered by test/tab-share.test.ts",
36 "/tabforge-move": "no picture: not in app.looks (its 32 slots are full); a POST that keeps a moved app and redirects to /settings/bring; covered by test/visitor-move.test.ts",
3637 "/archive": "no picture: not in app.looks (its 32 slots are full); the page is covered by test/archive-page.test.ts, with a 390 px measure, and test/apps-archived.test.ts",
3738 "/templates": "no picture: not in app.looks; the page is covered by test/templates-page.test.ts",
3839 "/traces": "no picture: not in app.looks (its 32 slots are full); the page is covered by test/traces-list.test.ts",
test/helpers/first-views.ts +14 −3
@@ -26,6 +26,7 @@ import { serve } from "../../src/http/server.ts";
2626 import { firstView, WIDTHS, type Attention } from "../../src/measure/attention.ts";
2727 import { useLive, type Live } from "../../src/system/live.ts";
2828 import type { SystemView } from "../../src/system/view.ts";
29 import { stallSection } from "../../src/web/pages/system.ts";
2930 import { proveAll } from "./verified.ts";
3031
3132 /** page → width → what its first view holds. */
@@ -94,11 +95,21 @@ const fixedReads = (html: string): string =>
9495 // the budget counts the page as a fresh process draws it, with nothing noted.
9596 const noOutside = (html: string): string => html.replace(/<ul class="list small" id="sys-outside"[^>]*>[\s\S]*?<\/ul>/, "");
9697
98 // "Main-thread stalls" and "Who is asking" are this forge's own load: a runner busy enough that
99 // drawing the pages before /system passes 200 ms lists those stalls (+8 blocks, +36 words on the
100 // check's runner, #18114) and may name a heavy asker. The budget counts a quiet forge, so the
101 // pages pin the quiet form whatever the machine was doing.
102 const QUIET_STALLS = `<div id="sys-stalls">${String(stallSection([]))}</div>`;
103 const quietLoad = (html: string): string =>
104 html
105 .replace(/<div id="sys-stalls">[\s\S]*?<\/section><\/div>/, QUIET_STALLS)
106 .replace(/<section class="settings-block" id="asking">[\s\S]*?<\/section>/, "");
107
97108 /**
98 * /system as the budget counts it: the cap lines fixed, the background readings unmeasured, and
99 * no keeper line.
109 * /system as the budget counts it: the cap lines fixed, the background readings unmeasured, no
110 * keeper line, and the forge's own load quiet.
100111 */
101 export const pinnedSystem = (html: string): string => noOutside(fixedReads(fixedCaps(html)));
112 export const pinnedSystem = (html: string): string => quietLoad(noOutside(fixedReads(fixedCaps(html))));
102113
103114 /** The measured pages, and the forge they came from, still serving until `close`. */
104115 export interface FirstViews {
test/tui-visitor-bring.test.ts added +49
@@ -0,0 +1,49 @@
1 /**
2 * The terminal's Brought in screen lists the apps an account brought from a tab (#18114), as the
3 * page's "Apps from a tab" section does.
4 */
5 import { afterAll, beforeAll, 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 { createUser, type User } from "../src/core/users.ts";
11 import { bring, keepMoved } from "../src/core/visitor_bring.ts";
12 import { createForgeApp } from "../src/tui/forge.ts";
13 import { visitorBringScreen } from "../src/tui/screens/visitor_bring.ts";
14 import { headlessTerminal } from "../src/tui/term/terminal.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16 import { settleApp } from "./helpers/tui.ts";
17
18 quietLogs();
19
20 let dir: string;
21 let app: App;
22 let tess: User;
23
24 beforeAll(async () => {
25 dir = await mkdtemp(join(tmpdir(), "forge-tui-visitor-bring-"));
26 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
27 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "tess", email: "[email protected]", password: "a-good-passphrase" });
28 if (!made.ok) throw new Error(made.error);
29 tess = made.value;
30 });
31 afterAll(async () => {
32 app.db.close();
33 await rm(dir, { recursive: true, force: true });
34 });
35
36 test("an app brought from a tab is named on the terminal's Brought in screen", async () => {
37 const id = keepMoved(app.db, { visitorId: "visitor-one" }, "{}", "Grocery tracker");
38 expect(bring(app.db, "visitor-one", tess, [id])).toBeDefined();
39 const terminal = headlessTerminal(200, 20);
40 const { app: tui, session } = createForgeApp(app, { sshUsername: "tess", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: tess }, { terminal, exitHooks: false });
41 tui.start();
42 tui.ctx.push(visitorBringScreen(session, tui.ctx));
43 try {
44 await settleApp(tui);
45 expect(tui.screen.toText()).toContain("Apps from a tab: Grocery tracker.");
46 } finally {
47 tui.stop();
48 }
49 });
test/visitor-bring.test.ts +1 −1
@@ -152,7 +152,7 @@ describe("a visitor's note comes to the account they sign up to, only when they
152152 expect(carriedVisitor(app.db, carry)).toBeUndefined();
153153
154154 const page = await (await onForge("/settings/bring", cookie)).text();
155 expect(page).toContain("1 note brought");
155 expect(page).toContain("1 thing brought");
156156 const receipt = /action="\/settings\/bring\/([^/]+)\/undo"/.exec(page)![1]!;
157157 const undone = await onForge(`/settings/bring/${receipt}/undo`, cookie, new URLSearchParams());
158158 expect(undone.status).toBe(303);
test/visitor-move.test.ts added +153
@@ -0,0 +1,153 @@
1 /**
2 * Moving an app made without a login to this forge (#18114): the tab forge's "Keep it on my
3 * account" posts the app's Blocks JSON (the Apple app's format, #18079) to POST /tabforge-move; the
4 * forge keeps it held by this browser's visitor and sends the person to Settings › Brought in,
5 * where signing up and ticking it makes it the account's. Another device's visitor never sees it,
6 * a refused spec keeps nothing, a cross-site post is refused, and undo gives it back.
7 */
8
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { createApp, type App } from "../src/app.ts";
14 import { movedAppsOf } from "../src/core/visitor_bring.ts";
15 import { getUserByName } from "../src/core/users.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { compile } from "../src/tab/compile.ts";
18 import { MOVE_PATH } from "../src/tab/share.ts";
19 import { tabLine } from "../src/tab/words.ts";
20 import { quietLogs } from "./helpers/globals.ts";
21 import { LOOPBACK_PROXIES } from "./helpers/loopback-proxy.ts";
22
23 quietLogs();
24
25 describe("an app made in the tab forge, moved, arrives owned by the account that picks it", () => {
26 let dataDir: string;
27 let app: App;
28 let servers: Servers;
29
30 beforeAll(async () => {
31 dataDir = await mkdtemp(join(tmpdir(), "forge-visitor-move-"));
32 app = createApp({ dataDir, port: 0, host: "forge.test", trustedProxies: LOOPBACK_PROXIES });
33 servers = await serve(app);
34 });
35
36 afterAll(async () => {
37 servers.stop();
38 app.close();
39 await rm(dataDir, { recursive: true, force: true });
40 });
41
42 const spec = JSON.stringify(compile("track my groceries").app);
43 const move = (body: string, cookie = "", origin = servers.url) =>
44 fetch(`${servers.url}${MOVE_PATH}`, {
45 method: "POST",
46 headers: { origin, cookie, "content-type": "application/x-www-form-urlencoded" },
47 body: new URLSearchParams({ app: body }),
48 redirect: "manual",
49 });
50 const get = (path: string, cookie: string) => fetch(`${servers.url}${path}`, { headers: { cookie }, redirect: "manual" });
51 const post = (path: string, cookie: string, body: URLSearchParams) =>
52 fetch(`${servers.url}${path}`, { method: "POST", headers: { cookie, origin: servers.url }, body, redirect: "manual" });
53 const cookieOf = (res: Response, name: string): string => res.headers.getSetCookie().find((c) => c.startsWith(`${name}=`))!.split(";")[0]!;
54 const signUp = async (username: string): Promise<string> => {
55 const res = await fetch(`${servers.url}/signup`, {
56 method: "POST",
57 body: new URLSearchParams({ username, email: `${username}@f.dev`, password: "account-password" }),
58 redirect: "manual",
59 });
60 return cookieOf(res, "forge_session");
61 };
62 const tabMoved = (): number => app.db.query<{ n: number }, []>("SELECT count(*) AS n FROM tab_moved").get()!.n;
63
64 test("moved, signed up, ticked: the account owns it; a second device's visitor does not see it; undo gives it back", async () => {
65 const moved = await move(spec);
66 expect(moved.status).toBe(303);
67 expect(moved.headers.get("location")).toBe("/settings/bring");
68 const maker = cookieOf(moved, "forge_maker");
69
70 // Not signed in, Brought in sends them to sign in or up first.
71 expect((await get("/settings/bring", maker)).status).toBe(303);
72
73 const session = await signUp("tess");
74 const user = getUserByName(app.db, "tess")!;
75 const both = `${maker}; ${session}`;
76 const shown = await (await get("/settings/bring", both)).text();
77 const id = /name="pick" value="([^"]+)" aria-label="Bring the app/.exec(shown)?.[1];
78 expect(id).toBeDefined();
79 expect(shown).toContain("moved from a tab");
80 // Arriving brings nothing: it is still the visitor's.
81 expect(movedAppsOf(app.db, user.id)).toEqual([]);
82
83 // A second device: its own visitor and its own account see nothing of it.
84 const other = await move(JSON.stringify(compile("count push-ups").app));
85 const otherMaker = cookieOf(other, "forge_maker");
86 expect(otherMaker).not.toBe(maker);
87 const otherSession = await signUp("otto");
88 const theirs = await (await get("/settings/bring", `${otherMaker}; ${otherSession}`)).text();
89 expect(theirs).not.toContain(`value="${id!}"`);
90 // Picking someone else's app by id brings nothing.
91 await post("/settings/bring", `${otherMaker}; ${otherSession}`, new URLSearchParams({ pick: id! }));
92 expect(movedAppsOf(app.db, getUserByName(app.db, "otto")!.id).map((a) => a.id)).not.toContain(id!);
93
94 const brought = await post("/settings/bring", both, new URLSearchParams({ pick: id! }));
95 expect(brought.status).toBe(303);
96 const owned = movedAppsOf(app.db, user.id);
97 expect(owned.map((a) => a.id)).toEqual([id!]);
98 const page = await (await get("/settings/bring", both)).text();
99 expect(page).toContain("Apps from a tab");
100 expect(page).toContain(`<strong>${owned[0]!.title}</strong>`);
101 expect(page).toContain("1 thing brought");
102
103 const receipt = /action="\/settings\/bring\/([^/]+)\/undo"/.exec(page)![1]!;
104 expect((await post(`/settings/bring/${receipt}/undo`, both, new URLSearchParams())).status).toBe(303);
105 expect(movedAppsOf(app.db, user.id)).toEqual([]);
106 expect(await (await get("/settings/bring", both)).text()).toContain(`value="${id!}"`);
107 });
108
109 test("a spec that does not decode keeps nothing; a cross-site post is refused", async () => {
110 const before = tabMoved();
111 const bad = await move(JSON.stringify({ version: 9, title: "x", blocks: [] }));
112 expect(bad.status).toBe(422);
113 expect(bad.headers.getSetCookie().some((c) => c.startsWith("forge_maker="))).toBe(false);
114 const foreign = await move(spec, "", "https://evil.example");
115 expect(foreign.status).toBe(403);
116 expect(tabMoved()).toBe(before);
117 });
118
119 test("a browser that refuses tracking is told to sign in first, and nothing is kept", async () => {
120 const before = tabMoved();
121 const res = await fetch(`${servers.url}${MOVE_PATH}`, {
122 method: "POST",
123 headers: { origin: servers.url, "sec-gpc": "1" },
124 body: new URLSearchParams({ app: spec }),
125 redirect: "manual",
126 });
127 expect(res.status).toBe(403);
128 expect(await res.text()).toContain("Sign in first");
129 expect(tabMoved()).toBe(before);
130 });
131
132 test("someone signed in whose browser refuses tracking keeps the app on the account, with no visitor", async () => {
133 const session = await signUp("gwen");
134 const res = await fetch(`${servers.url}${MOVE_PATH}`, {
135 method: "POST",
136 headers: { origin: servers.url, "sec-gpc": "1", dnt: "1", cookie: session },
137 body: new URLSearchParams({ app: spec }),
138 redirect: "manual",
139 });
140 expect(res.status).toBe(303);
141 expect(res.headers.get("location")).toBe("/settings/bring");
142 expect(res.headers.getSetCookie().some((c) => c.startsWith("forge_maker="))).toBe(false);
143 const owned = movedAppsOf(app.db, getUserByName(app.db, "gwen")!.id);
144 expect(owned.length).toBe(1);
145 const page = await (await get("/settings/bring", session)).text();
146 expect(page).toContain("Apps from a tab");
147 expect(page).not.toContain('aria-label="Bring the app');
148 });
149
150 test("the terminal's tab line says the same move", () => {
151 expect(tabLine()).toContain("Keep it on my account");
152 });
153 });

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

Keyboard shortcuts

Docs