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

Access 5: a visitor with no account is someone the forge knows, and what they made comes with them when they sign up #18069

opened this in answer to

Parked 3h 38m ago

mason/forge:mason/18051-access-5-a-visitor-with-no-account-is-so → main 21 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
31 files changed +940 −31
docs/ROLES.md +10 −9
@@ -11,7 +11,7 @@ Two words that sound alike are two different people, so each has one meaning:
1111 | member | A signed-in account with a `member` row | yes | role `member` below |
1212 | admin | A signed-in account with the `is_admin` flag | yes | role `admin` below |
1313
14 A visitor has no account and is never a user. Nothing is stored for one until
14 A visitor has no account and is never a user, though what they keep can be brought into an account when they sign up (#18051, `docs/features/visitor-carry.md`). Nothing is stored for one until
1515 they make something (a note on an app's page): then, and only then, the forge
1616 mints a signed visitor id in its own `forge_maker` cookie (`src/core/visitors.ts`),
1717 never the analytics `forge_visitor` id, and none at all when the browser sends
@@ -151,12 +151,13 @@ member has and a guest lacks, and the admin refusal's own words, so it cannot
151151 say less than the guards refuse (`test/people-role-limits.test.ts`).
152152
153153 <!-- roles-table -->
154 | Ability | guest | member | admin |
155 | --- | --- | --- | --- |
156 | Read what is public | yes | yes | yes |
157 | Comment and open issues | yes | yes | yes |
158 | Help build a public repository by forking it and sending a pull for review | yes | yes | yes |
159 | Create a repository or copy an app | no | yes | yes |
160 | Run a crew on a model allowance | no | yes | yes |
161 | Administer the forge | no | no | yes |
154 | Ability | visitor | guest | member | admin |
155 | --- | --- | --- | --- | --- |
156 | Read what is public | yes | yes | yes | yes |
157 | Keep what you make before you have an account, to bring into one when you sign up | yes | no | no | no |
158 | Comment and open issues | no | yes | yes | yes |
159 | Help build a public repository by forking it and sending a pull for review | no | yes | yes | yes |
160 | Create a repository or copy an app | no | no | yes | yes |
161 | Run a crew on a model allowance | no | no | yes | yes |
162 | Administer the forge | no | no | no | yes |
162163 <!-- /roles-table -->
docs/design/audit.md +1
@@ -63,6 +63,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
6363 - `/board/returns` — `pages/returns.ts` · what the window's dollars bought · `/settings/subscriptions` spend tables, `/settings/usage` · none seen.
6464 - `/big` — `pages/board.ts` (`bigRedirect`) · a redirect kept for old addresses into the board's wall mode · it is `/board` · none (no page of its own).
6565 - `/bring` — `pages/bring.ts` · bring an app whole from another forge, with its history, as a private linked app · `/new`, the palette · none seen.
66 - `/visitor/bring` — `pages/visitor_bring.ts` · what this device made before an account, and, for a signed-in person, offering it to their account with one confirmation and a day to undo it (#18051) · the terminal's visitor screen, the sign-in line · none seen.
6667 - `/boards` — `pages/boards-view.ts` · saved queries as panels · `/board` · none seen.
6768 - `/feed` — `studio/home.ts` · the composer and one timeline, what home was before it became the living pipeline (#8015) · `/` · none seen.
6869 - `/feed/likes` — `studio/ledger_page.ts` · one post's like ledger, rows and an Older link · the feed's "and N more" · none seen.
docs/features/may.md +1 −1
@@ -12,7 +12,7 @@ A client asks the forge what it may do instead of reading a role. One function,
1212 - **`forbidden`**: you are known, and it is not yours to do (or your token's scope is too low: `ro` reads, `rw` changes things).
1313
1414 Actions are named in one registry (`ACTIONS`), each with one sentence: `repo.read`, `repo.write`, `repo.admin` (over a
15 repository), `forge.read`, `forge.write` (any change at all, as your account: a session, or a token of scope `rw`), `forge.comment`, `forge.contribute`, `forge.make_it_yours`, `forge.run_crew`,
15 repository), `forge.read`, `forge.write` (any change at all, as your account: a session, or a token of scope `rw`), `forge.keep_work`, `forge.comment`, `forge.contribute`, `forge.make_it_yours`, `forge.run_crew`,
1616 `forge.administer`, and `account.manage` (the account itself, never a token).
1717
1818 **API.** `GET /api/v1/user` carries `can`: the forge-wide actions you may take.
docs/features/visitor-carry.md added +16
@@ -0,0 +1,16 @@
1 ---
2 topic: Backups and moving
3 row: Bring what you made without an account into the account you sign up for
4 ---
5 # A visitor, and what they made comes with them (#18051)
6
7 Someone with no account is a **visitor**, a role in the one table of who may do what (`CAN` in `src/core/roles.ts`, `docs/ROLES.md`): they read, and they may *keep* what they make (`keep_work`). Nothing else a person does is theirs yet.
8
9 - **The id.** The forge gives a visitor a signed id (cookie `forge_vp`, HttpOnly, six months) only when they keep something: an app made in a browser forge, a note, a game player. Reading mints nothing. It is not the analytics cookie (`forge_visitor`) and is never joined to it: its own name, shape (`v…`) and signing label, so one is no value of the other. `Sec-GPC: 1` and `DNT: 1` are honoured: no id is given and the door says to sign in. Code: `src/auth/visitor_principal.ts`. `POST /visitor/work` with `kind` (`tab_app`, `note` or `game_player`), `ref` and `label` is the one door.
10 - **The limits** (`/admin/limits`): `visitor.items_each` things for one visitor (20), `visitor.items_per_day` across all (1000), `visitor.minted_per_day` new ids (2000). Past one the door answers 429 and says to sign up.
11 - **Bringing it in.** `/visitor/bring` lists what this browser made. Signed in, the person chooses rows and presses one button; the form carries a confirmation bound to their account, session, device and the chosen rows, so a form made elsewhere cannot bring anything. The rows are re-pointed to the account in one transaction; a receipt says what moved and can be undone for a day (`Undo`), after which it is theirs. The front page says once that something waits. Nothing is brought by the cookie alone: an account that already holds a passkey is brought nothing without its own confirmation.
12 - **A browser forge moving in** (`/forges/move-in`, `docs/features/browser-forge-move.md`) presents the same visitor: the apps it kept as `tab_app` arrive owned by the account that moves in, with a receipt.
13 - **The terminal.** The palette entry *Brought in from a device* (`src/tui/screens/visitor.ts`) shows what the account was brought and the receipts, and `u` undoes the newest bringing still in its day. Only a browser holds the device's id, so bringing is the page's.
14 - **Not done.** Re-pointing the rows of the existing anonymous spawn (its own claim link, `src/spawn/claim.ts`); the tab forge's own call to `POST /visitor/work` and the Apple app's "Build on this device" (#18043, forge-apple #52) are the callers' side of the door; an API route or MCP tool.
15
16 Code: `src/core/visitor_work.ts`, `src/web/pages/visitor_bring.ts`. Test: `test/visitor-carry.test.ts` (with its red-team cases).
docs/threats/automated-attacker.md +9
@@ -135,3 +135,12 @@ Wants: accounts, spam, resources, or a way to exhaust the forge.
135135 loopback behind a proxy that serves its one name over HTTPS, and a scanner
136136 that finds it first gets the refusal any wrong code gets (#16217).
137137 Enforced by: `test/pinned-claim.test.ts`
138 - A visitor's id (`forge_vp`) is signed under its own label, given only to a visitor who keeps something
139 (never for reading, never under Do-Not-Track or Global Privacy Control), and capped per visitor, per
140 forge a day and in new ids a day; an id without its signature, or the analytics cookie's, names no one.
141 Enforced by: `test/visitor-carry.test.ts`
142 - What a visitor made is brought into an account only by that account: a signed-in person, a same-origin
143 form, the visitor's signed id, and a confirmation bound to the account, its session, the device and the
144 chosen rows, read from the page that account was shown. A forged, borrowed or missing confirmation into
145 an account that already has a passkey moves nothing; a bringing is undone for a day.
146 Enforced by: `test/visitor-carry.test.ts`
src/auth/visitor_principal.ts added +64
@@ -0,0 +1,64 @@
1 /**
2 * The visitor principal (#18051): a signed id the forge gives someone with no account, only when
3 * they do something that needs one (keep what they made, ask to share it), never for reading.
4 *
5 * It is not the analytics id (`perf/visitor_id.ts`, cookie `forge_visitor`) and is never joined to
6 * it: another cookie name, another id shape (`v…`, not `c…`) and another signing label, so a value
7 * of one is no value of the other. It names rows the visitor made (`core/visitor_work.ts`) so they
8 * can be brought into an account; it grants nothing a role does not (`visitor` in `core/roles.ts`).
9 * Do-Not-Track and Global Privacy Control are honoured as the analytics id honours them: no
10 * principal is given, and the door says to sign in to keep the work.
11 *
12 * Plain data in, plain data out; the key comes from `kernel/secret.ts`.
13 */
14
15 import { createHmac, timingSafeEqual } from "node:crypto";
16 import { cookieValue } from "../http/context.ts";
17 import { setCookie } from "./cookies.ts";
18 import { refusesTracking } from "../perf/visitor_id.ts";
19
20 export const PRINCIPAL_COOKIE = "forge_vp";
21 /** Six months, in seconds: long enough to come back and sign up, short enough to forget. */
22 export const PRINCIPAL_MAX_AGE = 183 * 86_400;
23 const VALUE = /^v[0-9a-f]{32}\.[0-9a-f]{32}$/;
24
25 const macOf = (key: Uint8Array, id: string): string =>
26 createHmac("sha256", key).update(`visitor-principal\0${id}`).digest("hex").slice(0, 32);
27
28 /** A new random principal and the cookie value that carries it. */
29 export function mintPrincipal(key: Uint8Array): { readonly id: string; readonly value: string } {
30 const id = `v${Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, "0")).join("")}`;
31 return { id, value: `${id}.${macOf(key, id)}` };
32 }
33
34 /**
35 * The id a signed value names, or undefined: an id without its signature, or signed by another
36 * label, names no one.
37 */
38 export function principalOf(value: string | undefined, key: Uint8Array): string | undefined {
39 if (value === undefined || !VALUE.test(value)) return undefined;
40 const [id, mac] = value.split(".") as [string, string];
41 return timingSafeEqual(Buffer.from(mac), Buffer.from(macOf(key, id))) ? id : undefined;
42 }
43
44 /** The signed principal a request carries, if any. */
45 export const requestPrincipal = (request: Request, key: Uint8Array): string | undefined => principalOf(cookieValue(request, PRINCIPAL_COOKIE), key);
46
47 /** Whether the request asked not to be tracked (`Sec-GPC` or `DNT`): then no principal is given. */
48 export const declinesPrincipal = (request: Request): boolean => refusesTracking(request.headers);
49
50 export const principalCookie = (value: string, secure: boolean): string => setCookie(PRINCIPAL_COOKIE, value, { maxAge: PRINCIPAL_MAX_AGE, secure });
51
52 /**
53 * The confirmation an account's own page carries into the form that brings work in: bound to the
54 * account, the principal and the chosen rows, so a form made elsewhere (another account, another
55 * choice) fails, and it is read only from a page the signed-in account was shown.
56 */
57 export const carryConfirm = (key: Uint8Array, userId: string, visitor: string, items: readonly string[]): string =>
58 createHmac("sha256", key).update(`visitor-carry\0${userId}\0${visitor}\0${[...items].sort().join(",")}`).digest("hex").slice(0, 32);
59
60 export const carryConfirmed = (given: string, key: Uint8Array, userId: string, visitor: string, items: readonly string[]): boolean => {
61 const want = Buffer.from(carryConfirm(key, userId, visitor, items));
62 const got = Buffer.from(given);
63 return got.length === want.length && timingSafeEqual(got, want);
64 };
src/core/event_audience.ts +4
@@ -435,6 +435,10 @@ export function classifiedAudience(kind: string): EventAudience | undefined {
435435 kind === "account.close_requested" ||
436436 kind === "account.close_kept" ||
437437 kind.startsWith("thought.") ||
438 // A person brought what their device made into their account, or gave it back
439 // (`web/pages/visitor_bring.ts`): their own receipt.
440 kind === "visitor.brought" ||
441 kind === "visitor.undone" ||
438442 // A conversation's own plan changed (`keep_plan` from Talk): the person's alone.
439443 kind === "conversation.plan" ||
440444 // A person's own dev cell changed state (`apps/dev_cell.ts`): theirs alone.
src/core/may.ts +3
@@ -45,6 +45,7 @@ export const ACTIONS = {
4545 "repo.admin": { says: "Administer a repository: its settings, webhooks, protection and deletion", over: "repo", scope: "rw" },
4646 "forge.read": forgeAction("read"),
4747 "forge.write": { says: "Change something as your account: any write, by a session or a token of scope rw", over: "forge", scope: "rw" },
48 "forge.keep_work": forgeAction("keep_work"),
4849 "forge.comment": forgeAction("comment"),
4950 "forge.contribute": forgeAction("contribute"),
5051 "forge.make_it_yours": forgeAction("make_it_yours"),
@@ -101,6 +102,8 @@ function forgeRuleHolds(db: Database, action: Action, p: Principal): boolean {
101102 // A visitor role: no account, nothing refused, or one already minted (`core/visitors.ts`).
102103 if (action === "visitor.make") return p.kind === "visitor" || (p.kind === "anonymous" && !p.refused);
103104 const user = userOf(p);
105 // What a visitor keeps is the visitor role's alone: an account has no use for it.
106 if (action === "forge.keep_work") return user === undefined;
104107 if (user === undefined) return false;
105108 if (ability === "administer") return user.isAdmin;
106109 // `forge.write`: any account may change what is its own to change; the scope says the rest.
src/core/migration-pins/20261204052000-visitor-principal.pin added +1
@@ -0,0 +1,1 @@
1 949590d1202410b45c187a2bbb77694adad84bceeb93976748a773a64095fda9
src/core/migrations/20261204052000-visitor-principal.ts added +33
@@ -0,0 +1,33 @@
1 // A visitor with no account (#18051): the signed principal the forge gave them
2 // (`visitor_principal`), what they made (`visitor_item`, `owner_id` null until brought into an
3 // account) and each bringing as a receipt with an undo window (`visitor_carry`). The principal is
4 // not the analytics id and holds no address, agent or time beyond the day it was made.
5 export default `
6 CREATE TABLE visitor_principal (
7 id TEXT PRIMARY KEY,
8 made_at TEXT NOT NULL
9 ) WITHOUT ROWID;
10 CREATE TABLE visitor_carry (
11 id TEXT PRIMARY KEY,
12 visitor_id TEXT NOT NULL REFERENCES visitor_principal(id) ON DELETE CASCADE,
13 user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
14 at TEXT NOT NULL,
15 undo_until TEXT NOT NULL,
16 undone_at TEXT
17 ) WITHOUT ROWID;
18 CREATE INDEX visitor_carry_user ON visitor_carry(user_id, at);
19 CREATE TABLE visitor_item (
20 id TEXT PRIMARY KEY,
21 visitor_id TEXT NOT NULL REFERENCES visitor_principal(id) ON DELETE CASCADE,
22 kind TEXT NOT NULL,
23 ref TEXT NOT NULL,
24 label TEXT NOT NULL,
25 made_at TEXT NOT NULL,
26 owner_id TEXT REFERENCES user(id) ON DELETE SET NULL,
27 carry_id TEXT REFERENCES visitor_carry(id) ON DELETE SET NULL,
28 UNIQUE (visitor_id, kind, ref)
29 ) WITHOUT ROWID;
30 CREATE INDEX visitor_item_visitor ON visitor_item(visitor_id);
31 CREATE INDEX visitor_item_owner ON visitor_item(owner_id);
32 CREATE INDEX visitor_item_made ON visitor_item(made_at);
33 `;
src/core/reserved.ts +1
@@ -37,6 +37,7 @@ export const SYSTEM_NAMES: readonly string[] = [
3737 "agent",
3838 "agents",
3939 "privacy",
40 "visitor",
4041 "terms",
4142 "security",
4243 "pricing",
src/core/roles.ts +7 −5
@@ -1,8 +1,8 @@
11 /**
2 * Roles: an account is a guest, a member or an admin. Admin is the `is_admin`
3 * flag, a member is a row in `member`, everyone else is a guest. `CAN` is the
4 * one table of what each role may do; `docs/ROLES.md` repeats it and a test
5 * fails when they differ. A guest is refused what the table withholds:
2 * Roles: someone with no account is a visitor (#18051, `auth/visitor_principal.ts`); an account is
3 * a guest, a member or an admin. Admin is the `is_admin` flag, a member is a row in `member`,
4 * everyone else is a guest. `CAN` is the one table of what each role may do; `docs/ROLES.md`
5 * repeats it and a test fails when they differ. A guest is refused what the table withholds:
66 * owning a repository beyond a contribution fork (`core/contribute.ts`), making
77 * an app one's own, starting a run (`requireAbility` in `actions/roles.ts`).
88 * Pure data; who may promote is the action's.
@@ -12,11 +12,12 @@ import { storedText } from "../kernel/blocked.ts";
1212 import type { Database } from "bun:sqlite";
1313 import { isUnclaimed } from "./starts.ts";
1414
15 export const ROLES = ["guest", "member", "admin"] as const;
15 export const ROLES = ["visitor", "guest", "member", "admin"] as const;
1616 export type Role = (typeof ROLES)[number];
1717
1818 export const ABILITIES = {
1919 read: "Read what is public",
20 keep_work: "Keep what you make before you have an account, to bring into one when you sign up",
2021 comment: "Comment and open issues",
2122 contribute: "Help build a public repository by forking it and sending a pull for review",
2223 make_it_yours: "Create a repository or copy an app",
@@ -27,6 +28,7 @@ export type Ability = keyof typeof ABILITIES;
2728
2829 /** What each role can do. */
2930 export const CAN: Readonly<Record<Role, readonly Ability[]>> = {
31 visitor: ["read", "keep_work"],
3032 guest: ["read", "comment", "contribute"],
3133 member: ["read", "comment", "contribute", "make_it_yours", "run_crew"],
3234 admin: ["read", "comment", "contribute", "make_it_yours", "run_crew", "administer"],
src/core/visitor_work.ts added +195
@@ -0,0 +1,195 @@
1 /**
2 * What a visitor made, and bringing it into an account (#18051). A visitor is someone with no
3 * account holding a signed principal (`auth/visitor_principal.ts`); what they keep is a row
4 * (`visitor_item`) naming a thing by kind and reference. At sign-up or sign-in the account is
5 * offered the list, chooses, and the chosen rows are re-pointed to it with a receipt
6 * (`visitor_carry`) that can be undone for a day.
7 *
8 * Limits are rows of `settings/limits.ts` (`visitor.*`): ids a day across the forge, things each
9 * visitor, things a day across all. What a visitor may do at all is the `visitor` column of
10 * `CAN` (`core/roles.ts`): the doors ask `can("visitor", "keep_work")`, not a list of their own.
11 *
12 * Nothing here trusts a principal's signature: the caller read it from a cookie it verified.
13 */
14
15 import type { Database } from "bun:sqlite";
16 import { err, ok, type Result } from "../kernel/result.ts";
17 import { limitValue } from "../settings/limits.ts";
18 import { can } from "./roles.ts";
19
20 /** What a visitor may keep: the tab forge's apps, a note left, a game player linked. */
21 export const WORK_KINDS = { tab_app: "app made in a browser forge", note: "note", game_player: "game player" } as const;
22 export type WorkKind = keyof typeof WORK_KINDS;
23 export const isWorkKind = (v: string): v is WorkKind => Object.hasOwn(WORK_KINDS, v);
24
25 /** The undo window of a bringing. */
26 export const UNDO_MS = 86_400_000;
27 const DAY_MS = 86_400_000;
28 const REF = /^[A-Za-z0-9._:-]{1,80}$/;
29 const LABEL_MAX = 80;
30 export const ITEM_ID = /^[0-9a-f-]{36}$/;
31
32 export interface WorkItem {
33 readonly id: string;
34 readonly kind: WorkKind;
35 readonly ref: string;
36 readonly label: string;
37 readonly madeAt: string;
38 }
39
40 export type KeepRefusal = "not_allowed" | "invalid" | "too_many_ids" | "too_many_things" | "forge_full";
41 export const KEEP_WORDS: Record<KeepRefusal, string> = {
42 not_allowed: "this is not something a visitor may do; sign in",
43 invalid: "name the kind (tab_app, note or game_player) and a reference of letters, digits and . _ : -",
44 too_many_ids: "the forge has given all the visitor ids it gives today; sign in to keep this, or try tomorrow",
45 too_many_things: "you have kept as many things as a visitor may; sign up to bring them into an account, then make more",
46 forge_full: "visitors have kept all the forge takes today; sign in to keep this, or try tomorrow",
47 };
48
49 const since = (now: Date, ms: number): string => new Date(now.getTime() - ms).toISOString();
50
51 /** Give a principal its row; false past the day's count of new ids. A known id costs nothing. */
52 export function admitPrincipal(db: Database, id: string, now: Date): boolean {
53 if (db.query("SELECT 1 FROM visitor_principal WHERE id = ?1").get(id) !== null) return true;
54 const n = db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM visitor_principal WHERE made_at > ?1").get(since(now, DAY_MS))!.n;
55 if (n >= limitValue(db, "visitor.minted_per_day")) return false;
56 db.query("INSERT INTO visitor_principal (id, made_at) VALUES (?1, ?2)").run(id, now.toISOString());
57 return true;
58 }
59
60 /** The role table, then the input: what a visitor may keep, or why not. */
61 export function checkWork(input: { kind: string; ref: string; label: string }): Result<{ kind: WorkKind; ref: string; label: string }, "not_allowed" | "invalid"> {
62 if (!can("visitor", "keep_work")) return err("not_allowed");
63 const label = input.label.trim().slice(0, LABEL_MAX);
64 if (!isWorkKind(input.kind) || !REF.test(input.ref) || label === "") return err("invalid");
65 return ok({ kind: input.kind, ref: input.ref, label });
66 }
67
68 /**
69 * Keep one thing for a visitor: `checkWork`, then the two ceilings. Keeping the same kind and
70 * reference again is the same row.
71 */
72 export function keepWork(db: Database, visitor: string, input: { kind: string; ref: string; label: string }, now: Date): Result<WorkItem, KeepRefusal> {
73 const checked = checkWork(input);
74 if (!checked.ok) return checked;
75 const { kind, label } = checked.value;
76 const held = db.query<WorkItem, [string, string, string]>("SELECT id, kind, ref, label, made_at AS madeAt FROM visitor_item WHERE visitor_id = ?1 AND kind = ?2 AND ref = ?3").get(visitor, kind, input.ref);
77 if (held !== null) return ok(held);
78 const mine = db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM visitor_item WHERE visitor_id = ?1 AND owner_id IS NULL").get(visitor)!.n;
79 if (mine >= limitValue(db, "visitor.items_each")) return err("too_many_things");
80 const day = db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM visitor_item WHERE made_at > ?1").get(since(now, DAY_MS))!.n;
81 if (day >= limitValue(db, "visitor.items_per_day")) return err("forge_full");
82 const item: WorkItem = { id: crypto.randomUUID(), kind, ref: input.ref, label, madeAt: now.toISOString() };
83 db.query("INSERT INTO visitor_item (id, visitor_id, kind, ref, label, made_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)").run(item.id, visitor, kind, item.ref, label, item.madeAt);
84 return ok(item);
85 }
86
87 /**
88 * What this visitor made and has not brought anywhere, oldest first: the list a sign-in is offered.
89 */
90 export function offered(db: Database, visitor: string): WorkItem[] {
91 return db
92 .query<WorkItem, [string]>("SELECT id, kind, ref, label, made_at AS madeAt FROM visitor_item WHERE visitor_id = ?1 AND owner_id IS NULL ORDER BY made_at, id")
93 .all(visitor);
94 }
95
96 /** What an account has been brought, newest first. */
97 export function broughtTo(db: Database, userId: string): WorkItem[] {
98 return db
99 .query<WorkItem, [string]>("SELECT id, kind, ref, label, made_at AS madeAt FROM visitor_item WHERE owner_id = ?1 ORDER BY made_at DESC, id")
100 .all(userId);
101 }
102
103 export interface Receipt {
104 readonly id: string;
105 readonly at: string;
106 readonly undoUntil: string;
107 readonly undone: boolean;
108 readonly items: readonly WorkItem[];
109 }
110
111 export type CarryRefusal = "no_account" | "nothing_chosen" | "not_theirs";
112 export const CARRY_WORDS: Record<CarryRefusal, string> = {
113 no_account: "bringing work in is for a person's own account; sign in or sign up first",
114 nothing_chosen: "choose at least one thing to bring",
115 not_theirs: "one of those things is not on this device's list",
116 };
117
118 /**
119 * Re-point the chosen rows of `visitor` to the account, in one transaction. A row not this
120 * visitor's, or already brought, refuses the whole bringing and moves nothing. Whether the account
121 * confirmed is the caller's (`carryConfirmed`): this cannot tell a person from a form.
122 */
123 export function bring(db: Database, input: { visitor: string; userId: string; accountKind: string; ids: readonly string[] }, now: Date): Result<Receipt, CarryRefusal> {
124 if (input.accountKind !== "user") return err("no_account");
125 const ids = [...new Set(input.ids)];
126 if (ids.length === 0) return err("nothing_chosen");
127 return db.transaction((): Result<Receipt, CarryRefusal> => {
128 const mine = new Set(offered(db, input.visitor).map((i) => i.id));
129 if (!ids.every((id) => mine.has(id))) return err("not_theirs");
130 const id = crypto.randomUUID();
131 const at = now.toISOString();
132 db.query("INSERT INTO visitor_carry (id, visitor_id, user_id, at, undo_until) VALUES (?1, ?2, ?3, ?4, ?5)").run(id, input.visitor, input.userId, at, new Date(now.getTime() + UNDO_MS).toISOString());
133 for (const item of ids) db.query("UPDATE visitor_item SET owner_id = ?1, carry_id = ?2 WHERE id = ?3 AND owner_id IS NULL").run(input.userId, id, item);
134 return ok(receiptOf(db, id)!);
135 })();
136 }
137
138 function receiptOf(db: Database, id: string): Receipt | undefined {
139 const row = db.query<{ id: string; at: string; undo_until: string; undone_at: string | null }, [string]>("SELECT id, at, undo_until, undone_at FROM visitor_carry WHERE id = ?1").get(id);
140 if (row === null) return undefined;
141 const items = db.query<WorkItem, [string]>("SELECT id, kind, ref, label, made_at AS madeAt FROM visitor_item WHERE carry_id = ?1 ORDER BY made_at, id").all(id);
142 return { id: row.id, at: row.at, undoUntil: row.undo_until, undone: row.undone_at !== null, items };
143 }
144
145 /** An account's bringings, newest first, each with the rows it moved (an undone one holds none). */
146 export function receiptsOf(db: Database, userId: string): Receipt[] {
147 return db
148 .query<{ id: string }, [string]>("SELECT id FROM visitor_carry WHERE user_id = ?1 ORDER BY at DESC, id LIMIT 20")
149 .all(userId)
150 .map((r) => receiptOf(db, r.id)!);
151 }
152
153 export type UndoRefusal = "not_found" | "late" | "done";
154 export const UNDO_WORDS: Record<UndoRefusal, string> = {
155 not_found: "no such bringing on this account",
156 late: "the day to undo that bringing has passed; what it brought is yours now",
157 done: "that bringing was already undone",
158 };
159
160 /** Give the rows of one of the account's own bringings back to the visitor, inside the window. */
161 export function undoBring(db: Database, userId: string, carryId: string, now: Date): Result<Receipt, UndoRefusal> {
162 return db.transaction((): Result<Receipt, UndoRefusal> => {
163 const row = db.query<{ undo_until: string; undone_at: string | null }, [string, string]>("SELECT undo_until, undone_at FROM visitor_carry WHERE id = ?1 AND user_id = ?2").get(carryId, userId);
164 if (row === null) return err("not_found");
165 if (row.undone_at !== null) return err("done");
166 if (row.undo_until <= now.toISOString()) return err("late");
167 const kept = receiptOf(db, carryId)!;
168 db.query("UPDATE visitor_item SET owner_id = NULL, carry_id = NULL WHERE carry_id = ?1 AND owner_id = ?2").run(carryId, userId);
169 db.query("UPDATE visitor_carry SET undone_at = ?1 WHERE id = ?2").run(now.toISOString(), carryId);
170 return ok({ ...kept, undone: true });
171 })();
172 }
173
174 /** The lines of a list, the same words the page and the terminal say. */
175 export const itemWords = (i: WorkItem): string => `${i.label} (${WORK_KINDS[i.kind]})`;
176
177 /**
178 * The page's and the terminal's rows for an account: what it was brought, and each receipt, in one
179 * list of lines.
180 */
181 export function broughtLines(db: Database, userId: string, now: Date): { readonly lines: readonly string[]; readonly undoable: string | undefined } {
182 const kept = broughtTo(db, userId);
183 const receipts = receiptsOf(db, userId);
184 const open = receipts.find((r) => !r.undone && r.undoUntil > now.toISOString());
185 const lines = [
186 kept.length === 0 ? "Nothing made as a visitor has been brought into this account." : "Brought into this account:",
187 ...kept.map((i) => ` ${itemWords(i)}`),
188 ...(receipts.length === 0 ? [] : ["", "Receipts:"]),
189 ...receipts.map((r) => ` ${r.at.slice(0, 16).replace("T", " ")}: ${r.items.length === 0 ? "nothing now" : r.items.map(itemWords).join(", ")}${r.undone ? " (undone)" : r.undoUntil > now.toISOString() ? ` (undo until ${r.undoUntil.slice(0, 16).replace("T", " ")} UTC)` : " (yours now)"}`),
190 ];
191 return { lines, undoable: open?.id };
192 }
193
194 /** Where what a device made is brought in: only a browser holds the device's id. */
195 export const BRING_FROM_BROWSER = "What a browser made before you signed in is offered on /visitor/bring in that browser, the one that holds its id.";
src/generated/marks.ts +4 −2
@@ -215,8 +215,9 @@ import k210 from "../http/marks/toolbar-lab.js.json";
215215 import k211 from "../http/marks/toolbar-lab.json";
216216 import k212 from "../http/marks/traces.json";
217217 import k213 from "../http/marks/verify.json";
218 import k214 from "../http/marks/welcome.json";
219 import k215 from "../http/marks/well-known.json";
218 import k214 from "../http/marks/visitor.json";
219 import k215 from "../http/marks/welcome.json";
220 import k216 from "../http/marks/well-known.json";
220221
221222 /** Each file of `http/marks/`, parsed, in name order. */
222223 export const MARK_FILES: readonly unknown[] = [
@@ -436,4 +437,5 @@ export const MARK_FILES: readonly unknown[] = [
436437 k213,
437438 k214,
438439 k215,
440 k216,
439441 ];
src/generated/screens.ts +7 −5
@@ -133,11 +133,12 @@ import * as s128 from "../tui/screens/traces.ts";
133133 import * as s129 from "../tui/screens/traffic.ts";
134134 import * as s130 from "../tui/screens/trafficview.ts";
135135 import * as s131 from "../tui/screens/valves.ts";
136 import * as s132 from "../tui/screens/waiting.ts";
137 import * as s133 from "../tui/screens/waiting_for_me.ts";
138 import * as s134 from "../tui/screens/wayback.ts";
139 import * as s135 from "../tui/screens/weekcard.ts";
140 import * as s136 from "../tui/screens/whocan.ts";
136 import * as s132 from "../tui/screens/visitor.ts";
137 import * as s133 from "../tui/screens/waiting.ts";
138 import * as s134 from "../tui/screens/waiting_for_me.ts";
139 import * as s135 from "../tui/screens/wayback.ts";
140 import * as s136 from "../tui/screens/weekcard.ts";
141 import * as s137 from "../tui/screens/whocan.ts";
141142
142143 /** Each screen file that declares palette entries: its module and the export names. */
143144 export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readonly string[]])[] = [
@@ -278,4 +279,5 @@ export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readon
278279 [s134, ["entry"]],
279280 [s135, ["entry"]],
280281 [s136, ["entry"]],
282 [s137, ["entry"]],
281283 ];
src/http/lazy_lists.ts +9
@@ -5,6 +5,14 @@
55 * order (which matters beside a `:name`). `test/boot-lazy.test.ts` fails when this is stale.
66 */
77
8 /** The `visitor` family. */
9 export const VISITOR_ROUTES = [
10 ["GET", "/visitor/bring"],
11 ["POST", "/visitor/bring"],
12 ["POST", "/visitor/bring/undo"],
13 ["POST", "/visitor/work"],
14 ] as const;
15
816 /** The `home-api` family. */
917 export const HOME_API_ROUTES = [
1018 ["GET", "/api/v1/home/lanes"],
@@ -1800,6 +1808,7 @@ export const API_PAGES_ROUTES = [
18001808
18011809 /** Each family's list by its name, as `lazyRoutes` reads it. */
18021810 export const LAZY_ROUTES: Readonly<Record<string, readonly (readonly [method: string, pattern: string])[]>> = {
1811 "visitor": VISITOR_ROUTES,
18031812 "home-api": HOME_API_ROUTES,
18041813 "MCP": MCP_ROUTES,
18051814 "settings": SETTINGS_ROUTES,
src/http/marks/visitor.json added +9
@@ -0,0 +1,9 @@
1 {
2 "head": "/visitor",
3 "mark": "open",
4 "routes": {
5 "/visitor/bring": "open",
6 "/visitor/bring/undo": "open",
7 "/visitor/work": "open"
8 }
9 }
src/http/routes/visitor.ts added +12
@@ -0,0 +1,12 @@
1 /** A visitor with no account: keep what they made, and bring it into an account (#18051). */
2
3 import { visitorBringPage, visitorBringSubmit, visitorKeepSubmit, visitorUndoSubmit } from "../../web/pages/visitor_bring.ts";
4 import type { Handler } from "../context.ts";
5 import type { Router } from "../router.ts";
6
7 export function visitorRoutes(router: Router<Handler>): void {
8 router.add("GET", "/visitor/bring", visitorBringPage);
9 router.add("POST", "/visitor/bring", visitorBringSubmit);
10 router.add("POST", "/visitor/bring/undo", visitorUndoSubmit);
11 router.add("POST", "/visitor/work", visitorKeepSubmit);
12 }
src/http/server.ts +1
@@ -260,6 +260,7 @@ export function buildRouter(): Router<Handler> {
260260 });
261261 lazyRoutes(router, "accounts", async () => (await import("./routes/accounts.ts")).accountsRoutes);
262262 lazyRoutes(router, "home", async () => (await import("./routes/home.ts")).homeRoutes);
263 lazyRoutes(router, "visitor", async () => (await import("./routes/visitor.ts")).visitorRoutes);
263264 forgesRoutes(router);
264265 lazyRoutes(router, "create", async () => (await import("./routes/create.ts")).createRoutes);
265266 lazyRoutes(router, "repo-display", async () => (await import("./routes/repo_display.ts")).repoDisplayRoutes);
src/settings/limits.ts +27
@@ -55,6 +55,9 @@ export type LimitKey =
5555 | "forges.storage_mb"
5656 | "spawn.anon_per_day"
5757 | "spawn.anon_global_per_day"
58 | "visitor.minted_per_day"
59 | "visitor.items_each"
60 | "visitor.items_per_day"
5861 | "spawn.births_at_once"
5962 | "spawn.birth_memory_mb"
6063 | "spawn.timers_max"
@@ -273,6 +276,30 @@ export const LIMITS: Record<LimitKey, LimitDef> = {
273276 max: 100_000,
274277 reason: "One address is not one person, so this is only enough to stop a client looping; a signed-in person is not counted here.",
275278 },
279 "visitor.minted_per_day": {
280 label: "Visitor ids the forge may give in a day",
281 unit: "ids",
282 default: 2_000,
283 min: 0,
284 max: 1_000_000,
285 reason: "An id is given only to a visitor who keeps something, never for reading, so this stops a client looping to fill the table, not a busy day.",
286 },
287 "visitor.items_each": {
288 label: "Things one visitor may keep before signing up",
289 unit: "things",
290 default: 20,
291 min: 0,
292 max: 1_000,
293 reason: "What a visitor keeps costs the forge a row until they sign up, so one visitor has a small, fixed number.",
294 },
295 "visitor.items_per_day": {
296 label: "Things all visitors together may keep in a day",
297 unit: "things",
298 default: 1_000,
299 min: 0,
300 max: 1_000_000,
301 reason: "Many visitors together, each under their own cap, can still fill a disk, so the forge has a daily ceiling across them.",
302 },
276303 "spawn.anon_global_per_day": {
277304 label: "Forges all strangers together may start a day",
278305 unit: "forges",
src/tui/screens/visitor.ts added +48
@@ -0,0 +1,48 @@
1 /**
2 * What was brought into this account from a visitor's device (#18051), in the terminal: the lines
3 * the page's lists and receipts say (`broughtLines`), and `u` undoes the newest bringing still
4 * inside its day. Bringing is the browser's: only it holds the device's signed id.
5 */
6
7 import { BRING_FROM_BROWSER, broughtLines, undoBring } from "../../core/visitor_work.ts";
8 import type { Ctx, Screen } from "../app/app.ts";
9 import { binding } from "../app/keys.ts";
10 import { style } from "../term/style.ts";
11 import { truncate, wrap } from "../term/width.ts";
12 import type { Session } from "../session.ts";
13 import type { PaletteEntry } from "./entries.ts";
14
15 export function visitorScreen(f: Session, ctx: Ctx): Screen {
16 const user = f.user;
17 return {
18 title: "Brought in from a device",
19 keys: [binding(["u"], "undo the newest bringing"), binding(["esc"], "back")],
20 render(area, s) {
21 const c = ctx.theme.c;
22 const w = Math.max(20, area.w);
23 const shown = user === undefined ? [] : broughtLines(f.app.db, user.id, new Date()).lines;
24 const rows = [...wrap(BRING_FROM_BROWSER, w), "", ...shown.flatMap((l) => wrap(l, w))];
25 rows.slice(0, area.h).forEach((text, i) => s.text(area.x, area.y + i, truncate(text, w), style(c.fg, c.bg), area.x + area.w));
26 },
27 key(e) {
28 if (e.key === "esc") {
29 ctx.pop();
30 return true;
31 }
32 if (e.key !== "u" || user === undefined) return false;
33 const open = broughtLines(f.app.db, user.id, new Date()).undoable;
34 const undone = open === undefined ? undefined : undoBring(f.app.db, user.id, open, new Date());
35 ctx.toast(undone?.ok === true ? "Given back to the device." : "Nothing to undo: a bringing can be undone for a day.", "default");
36 return true;
37 },
38 };
39 }
40
41 export const entry: PaletteEntry = {
42 rank: 915,
43 id: "visitor-brought",
44 title: "Brought in from a device",
45 hint: "what you made before signing in, and the receipts",
46 offered: (session) => session.user !== undefined && session.user.kind === "user",
47 run: (session, ctx) => ctx.push(visitorScreen(session, ctx)),
48 };
src/web/layout.ts +3 −1
@@ -7,6 +7,7 @@
77 * `/search`), and every dialog (a link to a real page).
88 */
99
10 import { visitorOffer } from "./visitor_offer.ts";
1011 import { repoOnRequest } from "../http/request_repo.ts";
1112 import { keyOf } from "./keymap.ts";
1213 import { requestHolds } from "../http/conditional.ts";
@@ -983,8 +984,9 @@ export function page(options: PageOptions, status = 200): Response {
983984 options.flash === undefined && cookieFlash === undefined && ctx.auth.noticeWaiting === true && ctx.auth.user !== undefined && ctx.request.method === "GET"
984985 ? takeNotice(ctx.app.db, ctx.auth.user.id, new Date())
985986 : undefined;
987 const offer = options.flash === undefined && cookieFlash === undefined && notice === undefined ? visitorOffer(ctx) : undefined;
986988 const flash: Flash | undefined =
987 options.flash ?? cookieFlash ?? (notice === undefined ? undefined : { tone: "attn", message: notice });
989 options.flash ?? cookieFlash ?? (notice === undefined ? (offer === undefined ? undefined : { tone: "attn", message: offer }) : { tone: "attn", message: notice });
988990 // A 404 names nothing, so it advertises no JSON twin of itself.
989991 const links = pageLinks(ctx).filter((l) => !(status === 404 && l.rel === "alternate"));
990992
src/web/pages/forge_move_in.ts +2 −1
@@ -16,6 +16,7 @@ import { html, type Html } from "../html.ts";
1616 import { page } from "../layout.ts";
1717 import { btn, field } from "../ui.ts";
1818 import { statusRow } from "./security.ts";
19 import { bringTabApps } from "./visitor_bring.ts";
1920
2021 const wrap = (title: string, body: Html) =>
2122 html`<div class="narrow-wide" data-forges>${pageHead(title)}<section class="settings-block">${body}<p class="mt">${btn("Back to your forges", { href: "/forges", size: "sm" })}</p></section></div>`;
@@ -64,7 +65,7 @@ export async function forgeMoveInSubmit(ctx: Ctx): Promise<Response> {
6465 [says, status, kind] = [planned.says, planned.kind === "not_found" ? 404 : 422, planned.kind];
6566 } else {
6667 const moved = await moveIn(ctx.app, user, { name, db: new Uint8Array(await db.arrayBuffer()), ...(file(git) && git.size > 0 ? { git: new Uint8Array(await git.arrayBuffer()) } : {}) });
67 says = moved.says;
68 says = moved.ok ? moved.says + bringTabApps(ctx) : moved.says;
6869 if (!moved.ok) [status, kind] = [moved.kind === "not_found" ? 404 : moved.kind === "invalid" ? 422 : 409, moved.kind];
6970 }
7071 const title = status === 200 ? "Forge moved" : "Forge not moved";
src/web/pages/visitor_bring.ts added +162
@@ -0,0 +1,162 @@
1 /**
2 * What someone made before they had an account, and bringing it in (#18051). `POST /visitor/work`
3 * is the one door a visitor keeps something through (the signed principal is given there and
4 * nowhere else); `GET /visitor/bring` lists what this device made and, for a signed-in person,
5 * offers it with one confirmation bound to their session; `POST /visitor/bring` re-points the
6 * chosen rows with a receipt; `POST /visitor/bring/undo` gives them back inside a day. The rows
7 * and words are `core/visitor_work.ts`'s, the same the terminal says.
8 */
9
10 import { carryConfirm, carryConfirmed, declinesPrincipal, mintPrincipal, principalCookie, requestPrincipal } from "../../auth/visitor_principal.ts";
11 import { isAccountItself, type Ctx } from "../../http/context.ts";
12 import { secureFor } from "../../http/cookie_secure.ts";
13 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
14 import { loadKey } from "../../kernel/secret.ts";
15 import {
16 admitPrincipal,
17 bring,
18 broughtTo,
19 CARRY_WORDS,
20 checkWork,
21 ITEM_ID,
22 itemWords,
23 KEEP_WORDS,
24 keepWork,
25 offered,
26 receiptsOf,
27 undoBring,
28 UNDO_WORDS,
29 type Receipt,
30 type WorkItem,
31 } from "../../core/visitor_work.ts";
32 import { notFoundPage, pageHead } from "../chrome.ts";
33 import { field, readForm } from "../form.ts";
34 import { html, type Html } from "../html.ts";
35 import { page } from "../layout.ts";
36 import { btn, row, rowList } from "../ui.ts";
37
38 const done = (response: Response): Response => {
39 response.headers.set("cache-control", "no-store");
40 return response;
41 };
42
43 const wrap = (title: string, body: Html) => html`<div class="narrow-wide" data-visitor>${pageHead(title)}<section class="settings-block">${body}</section></div>`;
44
45 /** A signed-in person acting as themselves, never a token or an agent. */
46 const person = (ctx: Ctx) => (ctx.auth.user !== undefined && ctx.auth.user.kind === "user" && isAccountItself(ctx.app.db, ctx.auth) ? ctx.auth.user : undefined);
47
48 const receiptView = (r: Receipt): Html =>
49 row({
50 id: `receipt-${r.id}`,
51 title: `${r.items.length === 0 ? "Nothing now" : r.items.map(itemWords).join(", ")} — brought ${r.at.slice(0, 16).replace("T", " ")}`,
52 trail: r.undone
53 ? html`Undone`
54 : r.undoUntil > new Date().toISOString()
55 ? html`<form method="post" action="/visitor/bring/undo">${btn("Undo", { name: "carry", value: r.id, size: "sm", title: `Give these back to the device before ${r.undoUntil.slice(0, 16)}` })}</form>`
56 : html`Yours now`,
57 });
58
59 const itemRow = (i: WorkItem): Html => row({ title: itemWords(i) });
60
61 export function visitorBringPage(ctx: Ctx): Response {
62 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
63 const key = loadKey(ctx.app.config.dataDir);
64 const visitor = requestPrincipal(ctx.request, key);
65 const user = person(ctx);
66 const waiting = visitor === undefined ? [] : offered(ctx.app.db, visitor);
67 const receipts = user === undefined ? [] : receiptsOf(ctx.app.db, user.id);
68 const kept = user === undefined ? [] : broughtTo(ctx.app.db, user.id);
69 let body: Html;
70 if (waiting.length === 0) body = html`<p role="status" data-visitor-state="none">Nothing made on this device is waiting to be brought in.</p>`;
71 else if (user === undefined)
72 body = html`<p role="status" data-visitor-state="signin">You made ${String(waiting.length)} ${waiting.length === 1 ? "thing" : "things"} on this device. Sign in or sign up, and you can bring ${waiting.length === 1 ? "it" : "them"} into your account.</p>
73 ${rowList(waiting.map(itemRow), { bare: true })}
74 <p>${btn("Sign in", { href: "/signin?next=%2Fvisitor%2Fbring", variant: "primary" })} ${btn("Sign up", { href: "/signup" })}</p>`;
75 else {
76 const confirm = carryConfirm(key, `${user.id}\0${ctx.auth.sessionId ?? ""}`, visitor!, waiting.map((i) => i.id));
77 body = html`<p role="status" data-visitor-state="offer">You made these on this device before signing in. Choose what to bring into @${user.username}'s account; you can undo it for a day.</p>
78 <form method="post" action="/visitor/bring">
79 <input type="hidden" name="confirm" value="${confirm}">
80 ${rowList(waiting.map((i) => row({ title: html`<label><input type="checkbox" name="item" value="${i.id}" checked> ${itemWords(i)}</label>` })), { bare: true })}
81 ${btn("Bring the chosen things into my account", { variant: "primary" })}
82 </form>`;
83 }
84 const brought = html`${kept.length === 0 ? null : html`<h2>Brought into this account</h2>${rowList(kept.map(itemRow), { bare: true })}`}${receipts.length === 0 ? null : html`<h2>Receipts</h2>${rowList(receipts.map(receiptView), { bare: true })}`}`;
85 return timePhase(ctx.request, "render", () => done(page({ ctx, title: "Bring in what you made", body: wrap("Bring in what you made", html`${body}${brought}`) })));
86 }
87
88 const say = (ctx: Ctx, title: string, says: string, status: number, state: string): Response =>
89 done(page({ ctx, title, body: wrap(title, html`<p role="status" data-visitor-state="${state}">${says}</p><p>${btn("Back", { href: "/visitor/bring", size: "sm" })}</p>`) }, status));
90
91 export async function visitorBringSubmit(ctx: Ctx): Promise<Response> {
92 const user = person(ctx);
93 if (user === undefined) return say(ctx, "Not brought", CARRY_WORDS.no_account, 401, "refused");
94 const form = await readForm(ctx);
95 if (form instanceof Response) return form;
96 const key = loadKey(ctx.app.config.dataDir);
97 const visitor = requestPrincipal(ctx.request, key);
98 if (visitor === undefined) return say(ctx, "Not brought", "this device holds no signed visitor id, so there is nothing of it to bring", 403, "refused");
99 const ids = form.getAll("item").filter((v): v is string => typeof v === "string");
100 if (ids.length > 100 || !ids.every((id) => ITEM_ID.test(id))) return say(ctx, "Not brought", CARRY_WORDS.not_theirs, 422, "refused");
101 // The confirmation is read from the page this account was shown, in this session, for this
102 // device and these rows; a form made elsewhere cannot carry it.
103 const offeredIds = offered(ctx.app.db, visitor).map((i) => i.id);
104 const given = field(form, "confirm");
105 const shown = carryConfirmed(given, key, `${user.id}\0${ctx.auth.sessionId ?? ""}`, visitor, offeredIds);
106 if (!shown) return say(ctx, "Not brought", "this account has not confirmed it: open the list from your own sign-in and press the button there", 403, "refused");
107 const result = bring(ctx.app.db, { visitor, userId: user.id, accountKind: user.kind, ids }, new Date());
108 if (!result.ok) return say(ctx, "Not brought", CARRY_WORDS[result.error], 422, "refused");
109 ctx.app.bus.append({ kind: "visitor.brought", actorId: user.id, payload: { carry: result.value.id, items: result.value.items.length } });
110 return done(page({ ctx, title: "Brought in", body: wrap("Brought in", html`<p role="status" data-visitor-state="brought">Brought ${String(result.value.items.length)} into @${user.username}'s account. You can undo it until ${result.value.undoUntil.slice(0, 16).replace("T", " ")} UTC.</p>${rowList([receiptView(result.value)], { bare: true })}`) }));
111 }
112
113 export async function visitorUndoSubmit(ctx: Ctx): Promise<Response> {
114 const user = person(ctx);
115 if (user === undefined) return notFoundPage(ctx);
116 const form = await readForm(ctx);
117 if (form instanceof Response) return form;
118 const result = undoBring(ctx.app.db, user.id, field(form, "carry"), new Date());
119 if (!result.ok) return say(ctx, "Not undone", UNDO_WORDS[result.error], result.error === "not_found" ? 404 : 409, "refused");
120 ctx.app.bus.append({ kind: "visitor.undone", actorId: user.id, payload: { carry: result.value.id } });
121 return say(ctx, "Undone", "Given back to this device: it is on the list again.", 200, "undone");
122 }
123
124 /** A visitor keeps one thing: the one door that gives a principal. Answers JSON. */
125 export async function visitorKeepSubmit(ctx: Ctx): Promise<Response> {
126 const json = (body: Record<string, unknown>, status: number, headers?: Record<string, string>) => done(Response.json(body, { status, ...(headers === undefined ? {} : { headers }) }));
127 if (ctx.auth.user !== undefined) return json({ error: "you are signed in: make it as yours" }, 409);
128 const form = await readForm(ctx);
129 if (form instanceof Response) return form;
130 const input = { kind: field(form, "kind"), ref: field(form, "ref"), label: field(form, "label") };
131 const checked = checkWork(input);
132 if (!checked.ok) return json({ error: KEEP_WORDS[checked.error] }, checked.error === "invalid" ? 422 : 403);
133 const key = loadKey(ctx.app.config.dataDir);
134 let id = requestPrincipal(ctx.request, key);
135 let minted: string | undefined;
136 if (id === undefined) {
137 if (declinesPrincipal(ctx.request)) return json({ error: "you asked not to be tracked, so no id is given; sign in to keep this" }, 403);
138 const fresh = mintPrincipal(key);
139 [id, minted] = [fresh.id, fresh.value];
140 }
141 if (!admitPrincipal(ctx.app.db, id, new Date())) return json({ error: KEEP_WORDS.too_many_ids }, 429, { "retry-after": "3600" });
142 const kept = keepWork(ctx.app.db, id, input, new Date());
143 if (!kept.ok) return json({ error: KEEP_WORDS[kept.error] }, 429, { "retry-after": "3600" });
144 return json({ id: kept.value.id, kind: kept.value.kind, ref: kept.value.ref }, 200, minted === undefined ? undefined : { "set-cookie": principalCookie(minted, secureFor(ctx.url, ctx.app.config.url)) });
145 }
146
147 /**
148 * A browser forge moving to this forge presents the visitor that made its apps (#18051): the
149 * signed id the request carries. The move is the account's own deliberate, same-origin act (its
150 * form is the confirmation), so the apps made in a tab arrive owned by it, with a receipt that
151 * can be undone. Nothing else the visitor made is touched. Returns the sentence to add, or "".
152 */
153 export function bringTabApps(ctx: Ctx): string {
154 const user = person(ctx);
155 const visitor = requestPrincipal(ctx.request, loadKey(ctx.app.config.dataDir));
156 if (user === undefined || visitor === undefined) return "";
157 const ids = offered(ctx.app.db, visitor).filter((i) => i.kind === "tab_app").map((i) => i.id);
158 const result = ids.length === 0 ? undefined : bring(ctx.app.db, { visitor, userId: user.id, accountKind: user.kind, ids }, new Date());
159 if (result?.ok !== true) return "";
160 ctx.app.bus.append({ kind: "visitor.brought", actorId: user.id, payload: { carry: result.value.id, items: result.value.items.length, by: "move_in" } });
161 return ` The ${String(ids.length)} ${ids.length === 1 ? "app" : "apps"} made in this browser without an account ${ids.length === 1 ? "is" : "are"} now yours (undo on /visitor/bring for a day).`;
162 }
src/web/visitor_offer.ts added +20
@@ -0,0 +1,20 @@
1 /**
2 * The one line a signed-in person is told on the front page when the browser holds a visitor id
3 * with things made on it (#18051): what they are offered, and where to choose. Nothing is looked
4 * up for a request with no such cookie, which is nearly all of them.
5 */
6
7 import { PRINCIPAL_COOKIE, requestPrincipal } from "../auth/visitor_principal.ts";
8 import { isAccountItself, type Ctx } from "../http/context.ts";
9 import { loadKey } from "../kernel/secret.ts";
10 import { offered } from "../core/visitor_work.ts";
11
12 export function visitorOffer(ctx: Ctx): string | undefined {
13 if (ctx.request.method !== "GET" || ctx.url.pathname !== "/") return undefined;
14 const user = ctx.auth.user;
15 if (user === undefined || user.kind !== "user" || !isAccountItself(ctx.app.db, ctx.auth)) return undefined;
16 if (!(ctx.request.headers.get("cookie") ?? "").includes(`${PRINCIPAL_COOKIE}=`)) return undefined;
17 const visitor = requestPrincipal(ctx.request, loadKey(ctx.app.config.dataDir));
18 const n = visitor === undefined ? 0 : offered(ctx.app.db, visitor).length;
19 return n === 0 ? undefined : `You made ${String(n)} ${n === 1 ? "thing" : "things"} on this device before signing in. Bring ${n === 1 ? "it" : "them"} into your account at /visitor/bring.`;
20 }
test/apps-ws.test.ts +3 −3
@@ -498,8 +498,8 @@ describe("apps: websockets through the proxy", () => {
498498
499499 test("a visitor's socket closes when their account is suspended; the app and others' sockets go on", async () => {
500500 const made = await createUser(app.db, { origin: "seed", trusted: true,
501 username: "visitor",
502 email: "visitor@forge.local",
501 username: "vera",
502 email: "vera@forge.local",
503503 password: "a-visitor-passphrase",
504504 });
505505 if (!made.ok) throw new Error(made.error);
@@ -516,7 +516,7 @@ describe("apps: websockets through the proxy", () => {
516516 expect(await stranger.opened).toBe(true);
517517 await seenBy(stranger.next);
518518
519 expect((await suspendAccount(app, alice, "visitor")).ok).toBe(true);
519 expect((await suspendAccount(app, alice, "vera")).ok).toBe(true);
520520 expect((await visitor.closed).code).toBe(1008);
521521 // Only that account's: the app is not the suspended one's, and a
522522 // stranger's socket on it still talks.
test/may.test.ts +3 −2
@@ -153,8 +153,9 @@ test("a token is not a person: account.manage is the account itself", () => {
153153
154154 test("the forge-wide actions follow the roles table", () => {
155155 const can = (who: string | undefined, scope?: "ro" | "rw" | "admin") => capabilities(app.db, scope === undefined ? principalOfUser(as(who)) : bearer(as(who), scope));
156 // No account may still make something as a visitor (`core/visitors.ts`, #18112).
157 expect(can(undefined)).toEqual(["forge.read", "visitor.make"]);
156 // No account may still make something as a visitor (`core/visitors.ts`, #18112), or keep it
157 // (#18051).
158 expect(can(undefined)).toEqual(["forge.read", "forge.keep_work", "visitor.make"]);
158159 expect(can("gina")).toEqual(["forge.read", "forge.write", "forge.comment", "forge.contribute"]);
159160 expect(can("nina")).toEqual(["forge.read", "forge.write", "forge.comment", "forge.contribute", "forge.make_it_yours", "forge.run_crew"]);
160161 expect(can("boss")).toContain("forge.administer");
test/mcp-forge-admin.test.ts +2 −2
@@ -258,11 +258,11 @@ describe("the forge over MCP: admin", () => {
258258 setMember(app.db, bob.id, false, alice.id, new Date());
259259 const guest = (await tool(bobRw, "whoami_can")).value;
260260 expect(guest.role).toBe("guest");
261 expect(guest.can).toEqual({ read: true, comment: true, contribute: true, make_it_yours: false, run_crew: false, administer: false });
261 expect(guest.can).toEqual({ read: true, keep_work: false, comment: true, contribute: true, make_it_yours: false, run_crew: false, administer: false });
262262 setMember(app.db, bob.id, true, alice.id, new Date());
263263 const member = (await tool(bobRw, "whoami_can")).value;
264264 expect(member.role).toBe("member");
265 expect(member.can).toEqual({ read: true, comment: true, contribute: true, make_it_yours: true, run_crew: true, administer: false });
265 expect(member.can).toEqual({ read: true, keep_work: false, comment: true, contribute: true, make_it_yours: true, run_crew: true, administer: false });
266266 const admin = (await tool(ro, "whoami_can")).value;
267267 expect(admin.role).toBe("admin");
268268 expect(admin.can.administer).toBe(true);
test/palette-roster.test.ts +2
@@ -259,6 +259,7 @@ test("a site-admin person is offered the whole roster", () => {
259259 ["domains", "Failure domains", "failure domains and their last drill"],
260260 ["feed", "Feed", "what happened, ranked; r replies on a post about an issue or pull, l likes, h who liked, p its permalink, o a run's log"],
261261 ["tab-forge", "A forge in a browser tab", "where it lives, when it stops, who can reach it, make an app from a sentence"],
262 ["visitor-brought", "Brought in from a device", "what you made before signing in, and the receipts"],
262263 ["feature-review", "Menu entries to review", "absorbed apps whose declared name or page changed: accept them"],
263264 ["feature-feed", "Feature feeds", "the feed items about an absorbed app, as Settings › Features shows them"],
264265 ["features", "Features", "apps that declare a feature: absorb one, change its settings"],
@@ -519,6 +520,7 @@ test("a member person is offered the signed-in roster without the admin entries"
519520 ["design-gallery", "Component gallery", "every component the design names"],
520521 ["feed", "Feed", "what happened, ranked; r replies on a post about an issue or pull, l likes, h who liked, p its permalink, o a run's log"],
521522 ["tab-forge", "A forge in a browser tab", "where it lives, when it stops, who can reach it, make an app from a sentence"],
523 ["visitor-brought", "Brought in from a device", "what you made before signing in, and the receipts"],
522524 ["feature-feed", "Feature feeds", "the feed items about an absorbed app, as Settings › Features shows them"],
523525 ["front", "Front page", "the apps a first visitor sees, ranked; an admin pins or hides"],
524526 ["origin-ahead", "New commits upstream", "mirrors whose origin has moved on: take them"],
test/visitor-carry.test.ts added +278
@@ -0,0 +1,278 @@
1 /**
2 * #18051: a visitor is someone the forge knows by a signed id given only when they keep something;
3 * what they made is brought into an account by the account's own confirmation, with a receipt and
4 * an undo window. Red team: an unsigned id, an analytics cookie, a forged or borrowed confirmation
5 * into an account that already has a passkey, a cross-site post and a flood all fail.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtempSync, readFileSync, rmSync } from "node:fs";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { carryConfirm, mintPrincipal, principalOf } from "../src/auth/visitor_principal.ts";
13 import { addPasskey } from "../src/core/passkeys.ts";
14 import { can, CAN, rolesTable } from "../src/core/roles.ts";
15 import { createSession } from "../src/core/sessions.ts";
16 import { createUser, getUserByName } from "../src/core/users.ts";
17 import { broughtTo, keepWork, offered, receiptsOf, undoBring, UNDO_MS } from "../src/core/visitor_work.ts";
18 import { serve, type Servers } from "../src/http/server.ts";
19 import { loadKey } from "../src/kernel/secret.ts";
20 import { mintId } from "../src/perf/visitor_id.ts";
21 import { setLimit } from "../src/settings/limits.ts";
22 import { createForgeApp } from "../src/tui/forge.ts";
23 import { headlessTerminal } from "../src/tui/term/terminal.ts";
24 import { adminCookie, seedAdmin } from "./helpers/admin.ts";
25 import { quietLogs } from "./helpers/globals.ts";
26 import { settleApp } from "./helpers/tui.ts";
27
28 quietLogs();
29
30 const root = mkdtempSync(join(tmpdir(), "visitor-carry-"));
31 let app: App;
32 let servers: Servers;
33 let key: Uint8Array;
34 const ORIGIN = "https://forge.test";
35
36 const account = async (username: string): Promise<{ id: string; cookie: string }> => {
37 const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@x.invalid`, password: "a-long-visitor-passphrase" });
38 if (!made.ok) throw new Error(username);
39 return { id: made.value.id, cookie: `forge_session=${createSession(app.db, made.value.id).token}` };
40 };
41 const keep = (body: Record<string, string>, headers: Record<string, string> = {}) =>
42 fetch(`${servers.url}/visitor/work`, { method: "POST", headers: { origin: ORIGIN, ...headers }, body: new URLSearchParams(body) });
43 const cookieOf = (res: Response): string => (res.headers.get("set-cookie") ?? "").split(";")[0]!;
44 const post = (path: string, cookie: string, body: URLSearchParams, origin = ORIGIN) => fetch(`${servers.url}${path}`, { method: "POST", headers: { cookie, origin }, body });
45 const confirmIn = (html: string): string => /name="confirm" value="([0-9a-f]+)"/.exec(html)![1]!;
46 const itemIn = (html: string): string[] => [...html.matchAll(/name="item" value="([0-9a-f-]{36})"/g)].map((m) => m[1]!);
47
48 beforeAll(async () => {
49 app = createApp({ dataDir: join(root, "forge"), url: "https://forge.test", port: 0 });
50 key = loadKey(app.config.dataDir);
51 servers = await serve(app);
52 }, 30_000);
53 afterAll(() => {
54 servers.stop();
55 app.close();
56 rmSync(root, { recursive: true, force: true });
57 });
58
59 describe("the principal", () => {
60 test("reading mints nothing; keeping a thing gives a signed HttpOnly id that is not the analytics one", async () => {
61 const read = await fetch(`${servers.url}/visitor/bring`);
62 expect(read.status).toBe(200);
63 expect(read.headers.get("set-cookie")).toBeNull();
64 const kept = await keep({ kind: "tab_app", ref: "notes", label: "Notes" });
65 expect(kept.status).toBe(200);
66 const line = kept.headers.get("set-cookie") ?? "";
67 expect(line).toMatch(/^forge_vp=v[0-9a-f]{32}\.[0-9a-f]{32};/);
68 expect(line).toContain("HttpOnly");
69 expect(line).not.toContain("forge_visitor");
70 expect(app.db.query("SELECT COUNT(*) AS n FROM visitor_principal").get()).toEqual({ n: 1 });
71 });
72
73 test("an id with no signature, a forged signature or an analytics value names no one", () => {
74 const real = mintPrincipal(key);
75 expect(principalOf(real.value, key)).toBe(real.id);
76 expect(principalOf(real.id, key)).toBeUndefined();
77 expect(principalOf(`${real.id}.${"0".repeat(32)}`, key)).toBeUndefined();
78 expect(principalOf(mintId(key).value, key)).toBeUndefined();
79 // The analytics cookie's signature does not make a principal of its id's shape either.
80 const analytics = mintId(key);
81 expect(principalOf(`v${analytics.id.slice(1)}.${analytics.value.split(".")[1]}`, key)).toBeUndefined();
82 expect(principalOf(real.value, new Uint8Array(32).fill(7))).toBeUndefined();
83 });
84
85 test("Global Privacy Control and Do-Not-Track are honoured: no id is given, and the door says why", async () => {
86 for (const header of [{ "sec-gpc": "1" }, { dnt: "1" }]) {
87 const res = await keep({ kind: "note", ref: "n1", label: "A note" }, header);
88 expect(res.status).toBe(403);
89 expect(res.headers.get("set-cookie")).toBeNull();
90 expect(await res.text()).toContain("not to be tracked");
91 }
92 });
93
94 test("a bad kind or reference keeps nothing and gives no id", async () => {
95 const before = app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM visitor_principal").get()!.n;
96 for (const bad of [{ kind: "repo", ref: "x", label: "x" }, { kind: "note", ref: "../x", label: "x" }, { kind: "note", ref: "x", label: " " }]) {
97 const res = await keep(bad);
98 expect(res.status).toBe(422);
99 expect(res.headers.get("set-cookie")).toBeNull();
100 }
101 expect(app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM visitor_principal").get()!.n).toBe(before);
102 expect((await keep({ kind: "note", ref: "x", label: "x" }, { origin: "https://evil.test" })).status).toBe(403);
103 });
104
105 test("a signed-in person keeps nothing as a visitor", async () => {
106 const me = await account("sia");
107 const res = await post("/visitor/work", me.cookie, new URLSearchParams({ kind: "note", ref: "s", label: "s" }));
108 expect(res.status).toBe(409);
109 });
110 });
111
112 describe("the role table", () => {
113 test("a visitor is a role of the one table: read and keep, nothing a person does", () => {
114 expect(CAN.visitor).toEqual(["read", "keep_work"]);
115 expect(can("visitor", "comment")).toBe(false);
116 expect(can("visitor", "make_it_yours")).toBe(false);
117 expect(can("guest", "keep_work")).toBe(false);
118 expect(rolesTable()).toContain("| visitor |");
119 });
120 });
121
122 describe("bringing it into an account", () => {
123 test("make as a visitor, sign up, bring it, and it is the account's", async () => {
124 const first = await keep({ kind: "tab_app", ref: "ledger", label: "Ledger" });
125 const vp = cookieOf(first);
126 await keep({ kind: "note", ref: "hello", label: "Hello" }, { cookie: vp });
127 const signedOut = await (await fetch(`${servers.url}/visitor/bring`, { headers: { cookie: vp } })).text();
128 expect(signedOut).toContain("Sign in or sign up");
129 expect(signedOut).toContain("Ledger");
130 const bea = await account("bea");
131 const front = await (await fetch(`${servers.url}/`, { headers: { cookie: `${bea.cookie}; ${vp}` } })).text();
132 expect(front).toContain("/visitor/bring");
133 const list = await (await fetch(`${servers.url}/visitor/bring`, { headers: { cookie: `${bea.cookie}; ${vp}` } })).text();
134 const ids = itemIn(list);
135 expect(ids.length).toBe(2);
136 const sent = await post("/visitor/bring", `${bea.cookie}; ${vp}`, new URLSearchParams([["confirm", confirmIn(list)], ["item", ids[0]!]]));
137 expect(sent.status).toBe(200);
138 const mine = broughtTo(app.db, bea.id);
139 expect(mine.length).toBe(1);
140 expect(app.db.query("SELECT owner_id FROM visitor_item WHERE id = ?1").get(ids[0]!)).toEqual({ owner_id: bea.id });
141 // What was not chosen stays the device's; nothing is the account's by cookie alone.
142 expect(offered(app.db, principalOfCookie(vp)).length).toBe(1);
143 expect(receiptsOf(app.db, bea.id)[0]!.items.length).toBe(1);
144 const after = await (await fetch(`${servers.url}/visitor/bring`, { headers: { cookie: `${bea.cookie}; ${vp}` } })).text();
145 expect(after).toContain("Receipts");
146 });
147
148 test("a second visitor presenting the first's id without its signature is refused", async () => {
149 const owner = await keep({ kind: "tab_app", ref: "mine", label: "Mine" });
150 const id = principalOfCookie(cookieOf(owner));
151 const thief = await account("thief");
152 const stolen = `forge_vp=${id}`;
153 const shown = await (await fetch(`${servers.url}/visitor/bring`, { headers: { cookie: `${thief.cookie}; ${stolen}` } })).text();
154 expect(shown).toContain("Nothing made on this device");
155 expect(shown).not.toContain("Mine");
156 const row = offered(app.db, id)[0]!;
157 const res = await post("/visitor/bring", `${thief.cookie}; ${stolen}`, new URLSearchParams([["confirm", carryConfirm(key, `${thief.id}\0`, id, [row.id])], ["item", row.id]]));
158 expect(res.status).toBe(403);
159 expect(offered(app.db, id).length).toBe(1);
160 expect(broughtTo(app.db, thief.id)).toEqual([]);
161 // Presenting it as a new keeper does not make it theirs either: a new id is given instead.
162 const again = await keep({ kind: "note", ref: "z", label: "Z" }, { cookie: stolen });
163 expect(cookieOf(again)).not.toContain(id);
164 });
165
166 test("a forged carry-over into an account that already has a passkey is refused", async () => {
167 const victim = await account("vera");
168 addPasskey(app.db, victim.id, "phone", { id: "cred-vera", alg: "ES256", key: { kty: "EC", crv: "P-256", x: "x", y: "y" }, signCount: 0 });
169 const attacker = await keep({ kind: "tab_app", ref: "planted", label: "Planted app" });
170 const vp = cookieOf(attacker);
171 const id = principalOfCookie(vp);
172 const row = offered(app.db, id)[0]!;
173 const victimCookie = `${victim.cookie}; ${vp}`;
174 const body = (confirm: string) => new URLSearchParams([["confirm", confirm], ["item", row.id]]);
175 // No confirmation, a guess, one made for another account, and one made for another session.
176 for (const confirm of ["", "0".repeat(32), carryConfirm(key, "someone-else\0", id, [row.id]), carryConfirm(key, `${victim.id}\0other-session`, id, [row.id])]) {
177 const res = await post("/visitor/bring", victimCookie, body(confirm));
178 expect(res.status).toBe(403);
179 }
180 // A cross-site post carrying the right cookies is refused before anything is read.
181 expect((await post("/visitor/bring", victimCookie, body("x"), "https://evil.test")).status).toBe(403);
182 // No session at all: the cookie of a device brings nothing into any account.
183 expect((await post("/visitor/bring", vp, body("x"))).status).toBe(401);
184 expect(offered(app.db, id).length).toBe(1);
185 expect(broughtTo(app.db, victim.id)).toEqual([]);
186 });
187
188 test("a bringing is undone inside its day and not after", async () => {
189 const vp = cookieOf(await keep({ kind: "game_player", ref: "p1", label: "Player one" }));
190 const id = principalOfCookie(vp);
191 const dan = await account("dan");
192 const list = await (await fetch(`${servers.url}/visitor/bring`, { headers: { cookie: `${dan.cookie}; ${vp}` } })).text();
193 await post("/visitor/bring", `${dan.cookie}; ${vp}`, new URLSearchParams([["confirm", confirmIn(list)], ["item", itemIn(list)[0]!]]));
194 const receipt = receiptsOf(app.db, dan.id)[0]!;
195 // Another account cannot undo it.
196 const other = await account("eve");
197 expect((await post("/visitor/bring/undo", other.cookie, new URLSearchParams({ carry: receipt.id }))).status).toBe(404);
198 expect(undoBring(app.db, dan.id, receipt.id, new Date(Date.now() + UNDO_MS + 1000)).ok).toBe(false);
199 expect(broughtTo(app.db, dan.id).length).toBe(1);
200 const undone = await post("/visitor/bring/undo", dan.cookie, new URLSearchParams({ carry: receipt.id }));
201 expect(undone.status).toBe(200);
202 expect(broughtTo(app.db, dan.id)).toEqual([]);
203 expect(offered(app.db, id).length).toBe(1);
204 expect((await post("/visitor/bring/undo", dan.cookie, new URLSearchParams({ carry: receipt.id }))).status).toBe(409);
205 });
206
207 test("the terminal shows what the account was brought and undoes the newest bringing", async () => {
208 const vp = cookieOf(await keep({ kind: "note", ref: "tn", label: "Terminal note" }));
209 const tess = await account("tess");
210 const list = await (await fetch(`${servers.url}/visitor/bring`, { headers: { cookie: `${tess.cookie}; ${vp}` } })).text();
211 await post("/visitor/bring", `${tess.cookie}; ${vp}`, new URLSearchParams([["confirm", confirmIn(list)], ["item", itemIn(list)[0]!]]));
212 const user = getUserByName(app.db, "tess")!;
213 const terminal = headlessTerminal(120, 30);
214 const { app: tui } = createForgeApp(app, { sshUsername: "t", remoteAddress: "127.0.0.1", user }, { terminal, exitHooks: false });
215 tui.start();
216 const key = (k: string, ctrl = false) => tui.dispatch({ type: "key", key: k, ctrl, alt: false, shift: false });
217 key("k", true);
218 await settleApp(tui);
219 for (const ch of "Brought in from") key(ch);
220 await settleApp(tui);
221 key("enter");
222 await settleApp(tui);
223 expect(tui.screen.toText()).toContain("Terminal note (note)");
224 key("u");
225 await settleApp(tui);
226 expect(broughtTo(app.db, tess.id)).toEqual([]);
227 tui.stop();
228 });
229 });
230
231 describe("limits", () => {
232 test("a visitor keeps only so many things, the forge only so many ids and so many things a day", () => {
233 const now = new Date();
234 const v = mintPrincipal(key).id;
235 app.db.query("INSERT INTO visitor_principal (id, made_at) VALUES (?1, ?2)").run(v, now.toISOString());
236 setLimit(app.db, "visitor.items_each", 2, "t");
237 expect(keepWork(app.db, v, { kind: "note", ref: "a", label: "a" }, now).ok).toBe(true);
238 expect(keepWork(app.db, v, { kind: "note", ref: "a", label: "a" }, now).ok).toBe(true);
239 expect(keepWork(app.db, v, { kind: "note", ref: "b", label: "b" }, now).ok).toBe(true);
240 const full = keepWork(app.db, v, { kind: "note", ref: "c", label: "c" }, now);
241 expect(full.ok ? "" : full.error).toBe("too_many_things");
242 setLimit(app.db, "visitor.items_each", 20, "t");
243 setLimit(app.db, "visitor.items_per_day", 1, "t");
244 const day = keepWork(app.db, v, { kind: "note", ref: "d", label: "d" }, now);
245 expect(day.ok ? "" : day.error).toBe("forge_full");
246 });
247
248 test("past the day's ids the door answers 429 and gives none", async () => {
249 setLimit(app.db, "visitor.items_per_day", 1_000, "t");
250 setLimit(app.db, "visitor.minted_per_day", 0, "t");
251 const res = await keep({ kind: "note", ref: "late", label: "Late" });
252 expect(res.status).toBe(429);
253 expect(res.headers.get("retry-after")).not.toBeNull();
254 });
255 });
256
257 describe("a browser forge moving in presents its visitor", () => {
258 test("the apps made in a tab arrive owned by the account that moves in", async () => {
259 setLimit(app.db, "visitor.minted_per_day", 2_000, "t");
260 const browser = createApp({ dataDir: join(root, "browser"), url: "https://browser.test", port: 0 });
261 const me = await seedAdmin(browser, { username: "bea2", email: "[email protected]" });
262 if (!me.ok) throw new Error("seed");
263 browser.db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
264 const db = new Uint8Array(readFileSync(join(root, "browser", "forge.db")));
265 browser.close();
266 const vp = cookieOf(await keep({ kind: "tab_app", ref: "tabby", label: "Tabby" }));
267 const keeper = await adminCookie(app, { username: "alice", email: "[email protected]" });
268 const form = new FormData();
269 form.set("name", "moved-tab");
270 form.set("db", new File([db], "forge.db"));
271 const res = await fetch(`${servers.url}/forges/move-in`, { method: "POST", headers: { cookie: `${keeper}; ${vp}`, origin: ORIGIN }, body: form });
272 expect(await res.text()).toContain("made in this browser without an account");
273 const alice = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'alice'").get()!;
274 expect(broughtTo(app.db, alice.id).map((i) => i.ref)).toEqual(["tabby"]);
275 });
276 });
277
278 const principalOfCookie = (cookie: string): string => principalOf(cookie.split("=")[1], key)!;

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

Keyboard shortcuts

Docs