Public: anyone can read this; the crew can change it.
Access 5b: at sign-up or sign-in a person is shown what this visitor made and chooses to bring it, with a receipt and an undo window #18217
Merged 54m ago, live in production
mason/forge:mason/18113-access-5b-at-sign-up-or-sign-in-a-person → main 0 commits fork 3 threads · 3 unresolved
27 files
changed +948
−11
- docs/design/attention-budget.json
- docs/design/audit.md
- docs/features/visitor-bring.md
- docs/threats/stolen-token.md
- src/actions/visitor_bring.ts
- src/apps/feedback.ts
- src/apps/toolbar.ts
- src/core/empty_words.ts
- src/core/event_audience.ts
- src/core/migration-pins/20261204120000-visitor-bring.pin
- src/core/migrations/20261204120000-visitor-bring.ts
- src/core/sessions.ts
- src/core/visitor_bring.ts
- src/core/visitors.ts
- src/http/lazy_lists.ts
- src/http/marks/settings.json
- src/http/settings_routes.ts
- src/tui/forge_parts.ts
- src/tui/screens/visitor_bring.ts
- src/web/pages/origins.ts
- src/web/pages/visitor_bring.ts
- test/apps-toolbar-draft.test.ts
- test/apps-toolbar-state.test.ts
- test/palette-roster.test.ts
- test/toolbar-budget.test.ts
- test/toolbar-size.test.ts
- test/visitor-bring.test.ts
docs/design/attention-budget.json +3 −3
| @@ -115,16 +115,16 @@ | ||
| 115 | 115 | }, |
| 116 | 116 | "settings": { |
| 117 | 117 | "390": { |
| 118 | "words": 155, | |
| 118 | "words": 157, | |
| 119 | 119 | "blocks": 32, |
| 120 | 120 | "colours": 1 |
| 121 | 121 | }, |
| 122 | 122 | "1280": { |
| 123 | "words": 155, | |
| 123 | "words": 157, | |
| 124 | 124 | "blocks": 32, |
| 125 | 125 | "colours": 1 |
| 126 | 126 | }, |
| 127 | "note": "146 words since #13308 (2026-11-15, Settings \u203a Connected agents): its side-nav entry added two words to the 144 main had; 147 since the forge dataset (Settings \u203a Dataset), one word; 148 since the Tables page (#6002), one word; 149 since Settings \u203a Infrastructure, one word: an admin looked for the cloud bill here and found no way to it; 153 since Settings › Who may do what (#18105), four words: every account sees what it may do and through which grant, so the row is on every account's nav. 155 since Settings › Proven emails (#18108), two words: its side-nav entry, so a person finds where their verified addresses are kept." | |
| 127 | "note": "146 words since #13308 (2026-11-15, Settings \u203a Connected agents): its side-nav entry added two words to the 144 main had; 147 since the forge dataset (Settings \u203a Dataset), one word; 148 since the Tables page (#6002), one word; 149 since Settings \u203a Infrastructure, one word: an admin looked for the cloud bill here and found no way to it; 153 since Settings › Who may do what (#18105), four words: every account sees what it may do and through which grant, so the row is on every account's nav. 155 since Settings › Proven emails (#18108), two words: its side-nav entry, so a person finds where their verified addresses are kept. 157 since Settings › Brought in (#18113), two words: its side-nav entry, so a person finds what they brought from a visitor and its undo." | |
| 128 | 128 | }, |
| 129 | 129 | "search": { |
| 130 | 130 | "390": { |
docs/design/audit.md +1
| @@ -196,6 +196,7 @@ Machine routes are not pages and have no entry: `/audit.csv`, | ||
| 196 | 196 | - `/settings/teams` — `pages/teams.ts` · the named crew teams, each with a charter, a dial and members · `/settings/crew` · none seen. |
| 197 | 197 | - `/settings/devices` — `settings/devices.ts` · LAN printers the owner declares, with model, state and supplies · `/settings/origins` (the same account sections) · none seen. |
| 198 | 198 | - `/settings/origins` — `pages/origins.ts` (1,497 lines) · other forges this one reads and mirrors from · `/migrate` · none seen. |
| 199 | - `/settings/bring` — `pages/visitor_bring.ts` · what a visitor made on this device, picked and brought to the account, and the receipts with a day's undo · the forge button's "Keep these on my account" on an app · none seen. | |
| 199 | 200 | - `/settings/identities` — `pages/identities.ts` · the verified addresses connected to your account, each with its state and the one that is in use · `/settings/origins` (the same account sections) · none seen. |
| 200 | 201 | - `/settings/security` — `pages/security.ts` · the Shield and the evidence an admin needs to act with no AI · `/settings/traffic`, `/settings/backups` · none seen. |
| 201 | 202 | - `/settings/security/controls` — `pages/security_controls.ts` · one line per RED-TEAM control and when it was last checked · `/settings/security` · none seen. |
docs/features/visitor-bring.md added +32
| @@ -0,0 +1,32 @@ | ||
| 1 | --- | |
| 2 | topic: Every setting, by topic | |
| 3 | row: Bring what you made before signing in: a visitor's notes, picked, brought to your account, undone for a day | |
| 4 | --- | |
| 5 | # Bring what you made as a visitor | |
| 6 | ||
| 7 | Someone with no account who sends a note from an app's forge button is a visitor: the app's | |
| 8 | host keeps a signed `forge_maker` cookie for them (`src/core/visitors.ts`). Once they have notes, | |
| 9 | the button's list offers **Keep these on my account**. It opens the forge's | |
| 10 | `/settings/bring` page (`src/web/pages/visitor_bring.ts`) with a one-time carry ticket: the | |
| 11 | cookie never leaves the app's host, and the ticket lasts 30 minutes. | |
| 12 | ||
| 13 | Not signed in, the page sends you to sign in or sign up and back. Arriving brings nothing. The | |
| 14 | page lists what this visitor made: each note, its app and the issue it became, none ticked. Tick | |
| 15 | the ones that are yours and press **Bring the ones ticked**; nothing ticked brings nothing, so a | |
| 16 | ticket link someone else sends you cannot put their notes on your account by one press. Only the | |
| 17 | newest 200 are listed at once; bring those and press Keep again for the rest. Pressing Keep again | |
| 18 | replaces the earlier ticket: each visitor holds one live ticket. Each note becomes the | |
| 19 | account's own: you see its replies on that app when signed in. The issue that was filed is not | |
| 20 | rewritten. Notes the app's owner hid or banned do not come along. | |
| 21 | ||
| 22 | Every bring is a receipt under **Brought**, with **Undo** for 24 hours. Undo gives the notes back | |
| 23 | to the visitor. Both are events for you alone (`visitor.brought`, `visitor.undone`). | |
| 24 | ||
| 25 | Only you, signed in in a browser, can bring. A token or an agent cannot. If your account has a | |
| 26 | passkey, bring within 15 minutes of signing in, or the page asks you to sign in again. | |
| 27 | ||
| 28 | In the terminal, **Brought in** (`src/tui/screens/visitor_bring.ts`) lists the same | |
| 29 | receipts and `u` undoes one after a y/n. The terminal cannot see or pick what to bring: the | |
| 30 | visitor is a cookie in the browser that made the notes, which a terminal never holds, and there | |
| 31 | is no visitor-less way to prove whose notes they are. With nothing brought yet the screen says | |
| 32 | where bringing starts. Seeing and picking are the browser's alone. |
docs/threats/stolen-token.md +11
| @@ -100,3 +100,14 @@ Wants: to act as the person or agent it was issued to, for as long as it works. | ||
| 100 | 100 | - Revoking every token of one account at once, and telling its owner a token was |
| 101 | 101 | used from somewhere new. |
| 102 | 102 | Enforced by: none yet |
| 103 | - A visitor's id is never a way into an account (#18113). What a visitor made comes to an | |
| 104 | account only when that account, signed in in a browser as itself (never a token, never an | |
| 105 | agent), picks it and presses Bring; an account with a passkey presses it within 15 minutes of | |
| 106 | signing in. The visitor is named only by proof: the signed `forge_maker` cookie, or a one-time | |
| 107 | carry ticket its holder mints on the app's host (a hash kept, 30 minutes, spent by the bring), | |
| 108 | so an id without its signature, a made-up or spent ticket, or another visitor's note named in | |
| 109 | the form brings nothing. A note hidden or banned by the app's owner never comes along. A | |
| 110 | ticket leaked from the address bar moves only that visitor's notes on that one app, and the | |
| 111 | app's own code, which can already read them, can mint one; every bring has a receipt and is | |
| 112 | undone for a day. | |
| 113 | Enforced by: `test/visitor-bring.test.ts` |
src/actions/visitor_bring.ts added +106
| @@ -0,0 +1,106 @@ | ||
| 1 | /** | |
| 2 | * Bringing what a visitor made to an account (#18113), for the page and the terminal alike. | |
| 3 | * | |
| 4 | * Who the visitor is comes only from proof: a carry ticket minted by the holder of the signed | |
| 5 | * `forge_maker` cookie on the app's host (`core/visitors.ts` `mintCarry`), or that signed cookie on | |
| 6 | * the forge's own host. A visitor id with no signature names nobody, and the form's own fields | |
| 7 | * never name one. Nothing is brought at sign-in: the account presses Bring, from a browser signed | |
| 8 | * in as itself, never a token or an agent; an account that has a passkey presses it within | |
| 9 | * `FRESH_MS` of signing in, so its passkey (or password) has just said yes. Each bring keeps a | |
| 10 | * receipt and may be undone for `UNDO_MS`. | |
| 11 | */ | |
| 12 | ||
| 13 | import type { App } from "../app.ts"; | |
| 14 | import type { Auth } from "../http/context.ts"; | |
| 15 | import { passkeyIds } from "../core/passkeys.ts"; | |
| 16 | import { sessionStartedAt } from "../core/sessions.ts"; | |
| 17 | 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"; | |
| 19 | import { carriedVisitor, heldVisitor, spendCarry } from "../core/visitors.ts"; | |
| 20 | import { loadKey } from "../kernel/secret.ts"; | |
| 21 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 22 | ||
| 23 | /** How recently an account with a passkey must have signed in to bring anything in. */ | |
| 24 | export const FRESH_MS = 15 * 60_000; | |
| 25 | ||
| 26 | export type BringRefusal = "browser_only" | "sign_in_again" | "nothing" | UndoRefusal; | |
| 27 | ||
| 28 | /** What each refusal says, on the page and in the terminal. */ | |
| 29 | export const BRING_WORDS: Record<BringRefusal, string> = { | |
| 30 | browser_only: "Only you, signed in in a browser, can bring things into your account.", | |
| 31 | sign_in_again: "Your account has a passkey: sign in again on this browser, then bring them within 15 minutes.", | |
| 32 | nothing: "There is nothing here to bring: the link may be spent or more than 30 minutes old. Open your notes on the app again.", | |
| 33 | not_found: "No such receipt on your account.", | |
| 34 | undone: "That was already undone.", | |
| 35 | too_late: "The 24 hours to undo that have passed.", | |
| 36 | }; | |
| 37 | ||
| 38 | /** | |
| 39 | * Where the visitor is named from: a carry ticket from the app's host, and the request's cookies. | |
| 40 | */ | |
| 41 | export interface Carried { | |
| 42 | readonly carry: string; | |
| 43 | readonly headers: Headers; | |
| 44 | } | |
| 45 | ||
| 46 | /** The visitor this request proves it is, or undefined: a ticket first, then the signed cookie. */ | |
| 47 | export function provenVisitor(app: App, from: Carried): string | undefined { | |
| 48 | return carriedVisitor(app.db, from.carry) ?? heldVisitor(from.headers, () => loadKey(app.config.dataDir)); | |
| 49 | } | |
| 50 | ||
| 51 | /** | |
| 52 | * What the proven visitor made that may come to an account: the newest `MADE_SHOWN`, and whether | |
| 53 | * more wait. | |
| 54 | */ | |
| 55 | export function bringable(app: App, from: Carried): { readonly made: Made[]; readonly more: boolean } { | |
| 56 | const visitorId = provenVisitor(app, from); | |
| 57 | const made = visitorId === undefined ? [] : madeBy(app.db, visitorId, MADE_SHOWN + 1); | |
| 58 | return { made: made.slice(0, MADE_SHOWN), more: made.length > MADE_SHOWN }; | |
| 59 | } | |
| 60 | ||
| 61 | /** | |
| 62 | * Whether this signed-in browser may bring things in now: a person's own session (or the platform | |
| 63 | * edge that signs each request), and for an account with a passkey, one signed in moments ago. | |
| 64 | */ | |
| 65 | export function mayBring(app: App, user: User, auth: Pick<Auth, "via" | "sessionId">, at: number = Date.now()): Result<true, BringRefusal> { | |
| 66 | if (user.kind !== "user") return err("browser_only"); | |
| 67 | // The platform edge signs every request itself (`http/server.ts` `resolveAuth`): there is no | |
| 68 | // forge cookie to steal and no forge sign-in time to hold it to; a passkey-fresh rule is the | |
| 69 | // edge's own to keep. A stolen `forge_session` is still a session, and still held to `FRESH_MS`. | |
| 70 | if (auth.via === "edge") return ok(true); | |
| 71 | if (auth.via !== "session" || auth.sessionId === undefined) return err("browser_only"); | |
| 72 | if (passkeyIds(app.db, user.id).length === 0) return ok(true); | |
| 73 | const since = sessionStartedAt(app.db, user.id, auth.sessionId); | |
| 74 | return since !== undefined && at - Date.parse(since) <= FRESH_MS ? ok(true) : err("sign_in_again"); | |
| 75 | } | |
| 76 | ||
| 77 | /** Bring the picked things to the account, keep the receipt, spend the ticket, and say so. */ | |
| 78 | export function bringToAccount( | |
| 79 | app: App, | |
| 80 | user: User, | |
| 81 | auth: Pick<Auth, "via" | "sessionId">, | |
| 82 | from: Carried, | |
| 83 | picks: readonly string[], | |
| 84 | at: number = Date.now(), | |
| 85 | ): Result<Receipt, BringRefusal> { | |
| 86 | const may = mayBring(app, user, auth, at); | |
| 87 | if (!may.ok) return may; | |
| 88 | const visitorId = provenVisitor(app, from); | |
| 89 | if (visitorId === undefined) return err("nothing"); | |
| 90 | const receipt = bring(app.db, visitorId, user, picks, at); | |
| 91 | if (receipt === undefined) return err("nothing"); | |
| 92 | spendCarry(app.db, from.carry); | |
| 93 | app.bus.append({ kind: "visitor.brought", actorId: user.id, payload: { receipt: receipt.id, count: receipt.count } }); | |
| 94 | return ok(receipt); | |
| 95 | } | |
| 96 | ||
| 97 | /** This account's receipts, newest first. */ | |
| 98 | export const broughtReceipts = (app: App, user: User): Receipt[] => receiptsOf(app.db, user.id); | |
| 99 | ||
| 100 | /** Undo one bring of this account's, inside its window, and say so. */ | |
| 101 | export function undoBrought(app: App, user: User, receiptId: string, at: number = Date.now()): Result<Receipt, BringRefusal> { | |
| 102 | const undone = undoBring(app.db, user.id, receiptId, at); | |
| 103 | if (typeof undone === "string") return err(undone); | |
| 104 | app.bus.append({ kind: "visitor.undone", actorId: user.id, payload: { receipt: undone.id, count: undone.count } }); | |
| 105 | return ok(undone); | |
| 106 | } |
src/apps/feedback.ts +19 −2
| @@ -26,7 +26,7 @@ import { PICTURE_MAX, savePicture, sniffPicture } from "../core/note_pictures.ts | ||
| 26 | 26 | import { getUserById, isActive, type User } from "../core/users.ts"; |
| 27 | 27 | import { sha256 } from "../kernel/hash.ts"; |
| 28 | 28 | import { loadKey } from "../kernel/secret.ts"; |
| 29 | import { admitVisitor, countMake, heldVisitor } from "../core/visitors.ts"; | |
| 29 | import { admitVisitor, countMake, heldVisitor, mintCarry } from "../core/visitors.ts"; | |
| 30 | 30 | import { parseNoteContext } from "../actions/note_context.ts"; |
| 31 | 31 | import { NOTE_FAILED } from "./note_words.ts"; |
| 32 | 32 | import { commentOnPull } from "./pull_comment.ts"; |
| @@ -310,15 +310,31 @@ function list(ask: FeedbackAsk, door: Door, proven: boolean): Response { | ||
| 310 | 310 | name: sender?.name ?? "visitor", |
| 311 | 311 | notes, |
| 312 | 312 | admin: proven && door.viewer !== undefined && canAdmin(ask.app.db, door.repo, door.viewer), |
| 313 | // A visitor with notes is offered to keep them on an account (`/__forge/note/carry`). | |
| 314 | carry: sender !== undefined && !sender.person && notes.length > 0, | |
| 313 | 315 | }); |
| 314 | 316 | } |
| 315 | 317 | |
| 318 | /** | |
| 319 | * Take this visitor's notes to the forge to keep on an account (#18113): a one-time ticket naming | |
| 320 | * the visitor the signed cookie proves, handed to the forge's bring page in its address. The | |
| 321 | * cookie itself never leaves this host. A person signed in here, or a visitor with no id, has | |
| 322 | * nothing to carry. | |
| 323 | */ | |
| 324 | function carry(ask: FeedbackAsk, door: Door): Response { | |
| 325 | const held = door.viewer === undefined ? heldVisitor(ask.request.headers, () => loadKey(ask.app.config.dataDir)) : undefined; | |
| 326 | if (held === undefined) return json(404, { error: "not_found" }); | |
| 327 | const ticket = mintCarry(ask.app.db, held); | |
| 328 | const to = `${ask.forgeUrl.replace(/\/+$/, "")}/settings/bring?${new URLSearchParams({ carry: ticket })}`; | |
| 329 | return new Response(null, { status: 303, headers: { location: to, "cache-control": "no-store", "referrer-policy": "no-referrer" } }); | |
| 330 | } | |
| 331 | ||
| 316 | 332 | /** Answer a `/__forge/note*` request; `undefined` when the path is not one. */ |
| 317 | 333 | export async function feedback(ask: FeedbackAsk): Promise<Response | undefined> { |
| 318 | 334 | const path = ask.url.pathname; |
| 319 | 335 | const method = ask.request.method; |
| 320 | 336 | if (path === "/__forge/note/moderate") return json(404, { error: "not_found" }); |
| 321 | if (path !== "/__forge/note" && path !== "/__forge/notes" && path !== "/__forge/note/picture" && path !== "/__forge/comment") return undefined; | |
| 337 | if (path !== "/__forge/note" && path !== "/__forge/notes" && path !== "/__forge/note/picture" && path !== "/__forge/note/carry" && path !== "/__forge/comment") return undefined; | |
| 322 | 338 | const host = ask.request.headers.get("host"); |
| 323 | 339 | const proven = spendProof(ask.request.headers.get(PROOF_HEADER), ask.grantCookie, host); |
| 324 | 340 | const answer = await answerNote(proven ? ask : { ...ask, viewerId: undefined }, path, method, proven); |
| @@ -336,5 +352,6 @@ async function answerNote(ask: FeedbackAsk, path: string, method: string, proven | ||
| 336 | 352 | if (method !== "POST") return json(405, { error: "method" }, { allow: "POST" }); |
| 337 | 353 | if (!sameOrigin(ask.request)) return json(403, { error: "cross_origin" }); |
| 338 | 354 | if (path === "/__forge/comment") return comment(ask, door); |
| 355 | if (path === "/__forge/note/carry") return carry(ask, door); | |
| 339 | 356 | return path === "/__forge/note/picture" ? picture(ask, door) : send(ask, door); |
| 340 | 357 | } |
src/apps/toolbar.ts +12 −2
| @@ -287,13 +287,23 @@ const toolbarSource = `(function () { | ||
| 287 | 287 | whatLink.rel = "noopener"; |
| 288 | 288 | whatLink.style.cssText = "color:#8ab4ff"; |
| 289 | 289 | if (forgeOrigin) { whatLink.href = forgeOrigin + "/"; what.appendChild(whatLink); } |
| 290 | function show(notes) { | |
| 290 | function show(notes, carry) { | |
| 291 | 291 | mine.textContent = ""; |
| 292 | 292 | if (!notes.length) return; |
| 293 | 293 | var h = document.createElement("div"); |
| 294 | 294 | h.textContent = "Your notes"; |
| 295 | 295 | h.style.cssText = "font-weight:600;margin-top:4px"; |
| 296 | 296 | mine.appendChild(h); |
| 297 | // A visitor's notes can come to an account they sign in to, on the forge (#18113). | |
| 298 | if (carry === true) { | |
| 299 | var keep = document.createElement("form"); | |
| 300 | keep.method = "post"; keep.action = "/__forge/note/carry"; keep.target = "_blank"; keep.rel = "noopener"; | |
| 301 | var kb = document.createElement("button"); | |
| 302 | kb.textContent = "Keep these on my account"; | |
| 303 | kb.style.cssText = "all:unset;cursor:pointer;min-height:44px;color:#8ab4ff;text-decoration:underline"; | |
| 304 | ring(kb); | |
| 305 | mine.appendChild(keep).appendChild(kb); | |
| 306 | } | |
| 297 | 307 | notes.forEach(function (n) { |
| 298 | 308 | var row = document.createElement("div"); |
| 299 | 309 | row.style.cssText = "border-top:1px solid #444c56;padding-top:4px;overflow-wrap:anywhere"; |
| @@ -343,7 +353,7 @@ const toolbarSource = `(function () { | ||
| 343 | 353 | .then(function (r) { return r.ok ? r.json() : null; }) |
| 344 | 354 | .then(function (j) { |
| 345 | 355 | if (!j || !Array.isArray(j.notes)) return; |
| 346 | show(j.notes); | |
| 356 | show(j.notes, j.carry); | |
| 347 | 357 | // A browser that keeps no cookie cannot be told which notes are its own. |
| 348 | 358 | if (sent === true && !j.notes.length) tellSay.textContent = "Sent. Your browser is not keeping cookies, so your notes will not be listed here."; |
| 349 | 359 | }) |
src/core/empty_words.ts +3
| @@ -128,6 +128,9 @@ export function emptyText(kind: EmptyKind): string { | ||
| 128 | 128 | */ |
| 129 | 129 | export const NOTE_WORDS = { |
| 130 | 130 | nothingToApply: "Nothing to apply.", |
| 131 | // Settings › Brought in (#18113). | |
| 132 | nothingMadeAsAVisitor: "Nothing made as a visitor on this device is waiting.", | |
| 133 | nothingBroughtYet: "Nothing brought yet.", | |
| 131 | 134 | nothingIsRunning: "Nothing is running.", |
| 132 | 135 | nothingWaitsForYou: "Nothing waits.", |
| 133 | 136 | noDescription: "No description.", |
src/core/event_audience.ts +4
| @@ -430,6 +430,10 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 430 | 430 | // A person asked to close their account, or kept it (#15619): their own receipt. |
| 431 | 431 | kind === "account.close_requested" || |
| 432 | 432 | kind === "account.close_kept" || |
| 433 | // What a visitor made, brought to an account and put back (`actions/visitor_bring.ts`, #18113): | |
| 434 | // the person's own receipt, never the visitor's id. | |
| 435 | kind === "visitor.brought" || | |
| 436 | kind === "visitor.undone" || | |
| 433 | 437 | kind.startsWith("thought.") || |
| 434 | 438 | // A conversation's own plan changed (`keep_plan` from Talk): the person's alone. |
| 435 | 439 | kind === "conversation.plan" || |
src/core/migration-pins/20261204120000-visitor-bring.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 390fa6580430e71313df2ee378b712090c94f156d04a06b65ffde1d3134c2422 |
src/core/migrations/20261204120000-visitor-bring.ts added +31
| @@ -0,0 +1,31 @@ | ||
| 1 | // Bringing what a visitor made to an account (#18113). A carry is a one-time ticket the holder of | |
| 2 | // a signed `forge_maker` cookie mints on an app's host, so the forge's own host can name that | |
| 3 | // visitor without the cookie ever leaving its host: stored only as a hash, spent once, short-lived. | |
| 4 | // A bring is the receipt: which account took which rows from which visitor, and until when it may | |
| 5 | // be undone; each row remembers the key and name it had, so an undo puts back exactly that. | |
| 6 | // Additive. | |
| 7 | export default ` | |
| 8 | CREATE TABLE visitor_carry ( | |
| 9 | ticket_hash TEXT PRIMARY KEY, | |
| 10 | visitor_id TEXT NOT NULL, | |
| 11 | expires_at TEXT NOT NULL | |
| 12 | ) WITHOUT ROWID; | |
| 13 | ||
| 14 | CREATE TABLE visitor_bring ( | |
| 15 | id TEXT PRIMARY KEY, | |
| 16 | visitor_id TEXT NOT NULL, | |
| 17 | user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE, | |
| 18 | at TEXT NOT NULL, | |
| 19 | undo_until TEXT NOT NULL, | |
| 20 | undone_at TEXT | |
| 21 | ) WITHOUT ROWID; | |
| 22 | CREATE INDEX visitor_bring_by_user ON visitor_bring(user_id, at); | |
| 23 | ||
| 24 | CREATE TABLE visitor_bring_row ( | |
| 25 | bring_id TEXT NOT NULL REFERENCES visitor_bring(id) ON DELETE CASCADE, | |
| 26 | note_id TEXT NOT NULL, | |
| 27 | was_visitor TEXT NOT NULL, | |
| 28 | was_name TEXT NOT NULL, | |
| 29 | PRIMARY KEY (bring_id, note_id) | |
| 30 | ) WITHOUT ROWID; | |
| 31 | `; |
src/core/sessions.ts +10
| @@ -228,3 +228,13 @@ export function pruneSessions(db: Database): number { | ||
| 228 | 228 | ) |
| 229 | 229 | .run(now.toISOString(), idleSince(now)).changes; |
| 230 | 230 | } |
| 231 | ||
| 232 | /** | |
| 233 | * When this browser signed in, by the session's id (never its secret); undefined when it is gone. | |
| 234 | */ | |
| 235 | export function sessionStartedAt(db: Database, userId: string, id: string): string | undefined { | |
| 236 | return ( | |
| 237 | db.query<{ created_at: string }, [string, string]>("SELECT created_at FROM session WHERE id = ?1 AND user_id = ?2").get(id, userId) | |
| 238 | ?.created_at ?? undefined | |
| 239 | ); | |
| 240 | } |
src/core/visitor_bring.ts added +158
| @@ -0,0 +1,158 @@ | ||
| 1 | /** | |
| 2 | * What a visitor made, and the receipts of bringing it to an account (#18113). Pure data, no | |
| 3 | * authz: `actions/visitor_bring.ts` decides who may. A note is the one thing a visitor makes today | |
| 4 | * (`apps/feedback.ts`); its row is keyed `v:<visitor id>`, and bringing re-points it to | |
| 5 | * `u:<user id>`, the key a signed-in sender's notes have, so the account finds it as its own. The | |
| 6 | * filed issue is never rewritten: what was said stays as said, by whom it was said then. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { Database } from "bun:sqlite"; | |
| 10 | import { id as newId } from "../kernel/id.ts"; | |
| 11 | ||
| 12 | /** | |
| 13 | * The most notes a bring page lists at once; `madeBy` is asked for one more to know there are more. | |
| 14 | */ | |
| 15 | export const MADE_SHOWN = 200; | |
| 16 | ||
| 17 | /** How long a bring may be undone. */ | |
| 18 | export const UNDO_MS = 24 * 3_600_000; | |
| 19 | ||
| 20 | /** One thing a visitor made, as the person deciding whether to bring it sees it. */ | |
| 21 | export interface Made { | |
| 22 | readonly noteId: string; | |
| 23 | readonly app: string; | |
| 24 | readonly issueNumber: number; | |
| 25 | readonly title: string; | |
| 26 | readonly createdAt: string; | |
| 27 | } | |
| 28 | ||
| 29 | /** One bring: how many rows came, and until when it may be undone. */ | |
| 30 | export interface Receipt { | |
| 31 | readonly id: string; | |
| 32 | readonly at: string; | |
| 33 | readonly undoUntil: string; | |
| 34 | readonly undoneAt: string | null; | |
| 35 | readonly count: number; | |
| 36 | } | |
| 37 | ||
| 38 | const visitorKey = (visitorId: string): string => `v:${visitorId}`; | |
| 39 | const userKey = (userId: string): string => `u:${userId}`; | |
| 40 | ||
| 41 | /** | |
| 42 | * Every note this visitor made that may still come with them: not hidden by the app's owner, and | |
| 43 | * not on an app that banned them, so a bring never launders a ban into an account. Newest first, | |
| 44 | * at most `limit`. | |
| 45 | */ | |
| 46 | export function madeBy(db: Database, visitorId: string, limit: number = MADE_SHOWN): Made[] { | |
| 47 | return db | |
| 48 | .query<{ id: string; slug: string; issue_number: number; title: string | null; created_at: string }, [string, number]>( | |
| 49 | `SELECT n.id, a.slug, n.issue_number, i.title, n.created_at | |
| 50 | FROM app_note n | |
| 51 | JOIN app a ON a.id = n.app_id | |
| 52 | LEFT JOIN issue i ON i.repo_id = n.repo_id AND i.number = n.issue_number | |
| 53 | WHERE n.visitor = ?1 AND n.hidden = 0 | |
| 54 | AND NOT EXISTS (SELECT 1 FROM app_note_ban b WHERE b.app_id = n.app_id AND b.visitor = n.visitor) | |
| 55 | ORDER BY n.created_at DESC, n.id DESC | |
| 56 | LIMIT ?2`, | |
| 57 | ) | |
| 58 | .all(visitorKey(visitorId), limit) | |
| 59 | .map((r) => ({ noteId: r.id, app: r.slug, issueNumber: r.issue_number, title: r.title ?? "", createdAt: r.created_at })); | |
| 60 | } | |
| 61 | ||
| 62 | /** | |
| 63 | * Re-point the picked notes of this visitor to the account, and keep the receipt. A pick that is | |
| 64 | * not among `madeBy` (another visitor's, hidden, banned, already brought) is passed over; nothing | |
| 65 | * is written when none is left. One transaction: all the rows and their receipt, or none. | |
| 66 | */ | |
| 67 | export function bring( | |
| 68 | db: Database, | |
| 69 | visitorId: string, | |
| 70 | user: { readonly id: string; readonly username: string }, | |
| 71 | picks: readonly string[], | |
| 72 | at: number = Date.now(), | |
| 73 | ): Receipt | undefined { | |
| 74 | const mine = new Map(madeBy(db, visitorId).map((m) => [m.noteId, m])); | |
| 75 | const chosen = [...new Set(picks)].filter((p) => mine.has(p)); | |
| 76 | if (chosen.length === 0) return undefined; | |
| 77 | const receipt: Receipt = { | |
| 78 | id: newId(), | |
| 79 | at: new Date(at).toISOString(), | |
| 80 | undoUntil: new Date(at + UNDO_MS).toISOString(), | |
| 81 | undoneAt: null, | |
| 82 | count: chosen.length, | |
| 83 | }; | |
| 84 | db.transaction(() => { | |
| 85 | db.run("INSERT INTO visitor_bring (id, visitor_id, user_id, at, undo_until) VALUES (?, ?, ?, ?, ?)", [ | |
| 86 | receipt.id, | |
| 87 | visitorId, | |
| 88 | user.id, | |
| 89 | receipt.at, | |
| 90 | receipt.undoUntil, | |
| 91 | ]); | |
| 92 | for (const noteId of chosen) { | |
| 93 | const was = db.query<{ name: string }, [string]>("SELECT name FROM app_note WHERE id = ?").get(noteId)!; | |
| 94 | db.run("INSERT INTO visitor_bring_row (bring_id, note_id, was_visitor, was_name) VALUES (?, ?, ?, ?)", [ | |
| 95 | receipt.id, | |
| 96 | noteId, | |
| 97 | visitorKey(visitorId), | |
| 98 | was.name, | |
| 99 | ]); | |
| 100 | db.run("UPDATE app_note SET visitor = ?, name = ? WHERE id = ? AND visitor = ?", [ | |
| 101 | userKey(user.id), | |
| 102 | `@${user.username}`, | |
| 103 | noteId, | |
| 104 | visitorKey(visitorId), | |
| 105 | ]); | |
| 106 | } | |
| 107 | })(); | |
| 108 | return receipt; | |
| 109 | } | |
| 110 | ||
| 111 | interface ReceiptRow { | |
| 112 | id: string; | |
| 113 | at: string; | |
| 114 | undo_until: string; | |
| 115 | undone_at: string | null; | |
| 116 | n: number; | |
| 117 | } | |
| 118 | const RECEIPT_COLUMNS = | |
| 119 | "b.id, b.at, b.undo_until, b.undone_at, (SELECT count(*) FROM visitor_bring_row r WHERE r.bring_id = b.id) AS n"; | |
| 120 | const fromRow = (r: ReceiptRow): Receipt => ({ id: r.id, at: r.at, undoUntil: r.undo_until, undoneAt: r.undone_at, count: r.n }); | |
| 121 | ||
| 122 | /** This account's receipts, newest first. */ | |
| 123 | export function receiptsOf(db: Database, userId: string, limit = 20): Receipt[] { | |
| 124 | return db | |
| 125 | .query<ReceiptRow, [string, number]>( | |
| 126 | `SELECT ${RECEIPT_COLUMNS} FROM visitor_bring b WHERE b.user_id = ?1 ORDER BY b.at DESC, b.id DESC LIMIT ?2`, | |
| 127 | ) | |
| 128 | .all(userId, limit) | |
| 129 | .map(fromRow); | |
| 130 | } | |
| 131 | ||
| 132 | export type UndoRefusal = "not_found" | "undone" | "too_late"; | |
| 133 | ||
| 134 | /** | |
| 135 | * Put a bring back: each row this account still holds returns to the visitor key and name it had. | |
| 136 | * Only the account that brought it, only once, only inside its window. | |
| 137 | */ | |
| 138 | export function undoBring(db: Database, userId: string, bringId: string, at: number = Date.now()): Receipt | UndoRefusal { | |
| 139 | const row = db | |
| 140 | .query<ReceiptRow, [string, string]>(`SELECT ${RECEIPT_COLUMNS} FROM visitor_bring b WHERE b.id = ?1 AND b.user_id = ?2`) | |
| 141 | .get(bringId, userId); | |
| 142 | if (row === null) return "not_found"; | |
| 143 | const found = fromRow(row); | |
| 144 | if (found.undoneAt !== null) return "undone"; | |
| 145 | if (Date.parse(found.undoUntil) <= at) return "too_late"; | |
| 146 | const undoneAt = new Date(at).toISOString(); | |
| 147 | db.transaction(() => { | |
| 148 | const rows = db | |
| 149 | .query<{ note_id: string; was_visitor: string; was_name: string }, [string]>( | |
| 150 | "SELECT note_id, was_visitor, was_name FROM visitor_bring_row WHERE bring_id = ?", | |
| 151 | ) | |
| 152 | .all(bringId); | |
| 153 | for (const r of rows) | |
| 154 | db.run("UPDATE app_note SET visitor = ?, name = ? WHERE id = ? AND visitor = ?", [r.was_visitor, r.was_name, r.note_id, userKey(userId)]); | |
| 155 | db.run("UPDATE visitor_bring SET undone_at = ? WHERE id = ?", [undoneAt, bringId]); | |
| 156 | })(); | |
| 157 | return { ...found, undoneAt }; | |
| 158 | } |
src/core/visitors.ts +39
| @@ -17,6 +17,7 @@ import { createHmac, hkdfSync, timingSafeEqual } from "node:crypto"; | ||
| 17 | 17 | import { setCookie } from "../auth/cookies.ts"; |
| 18 | 18 | import { VISITOR_CAPS } from "../http/limits.ts"; |
| 19 | 19 | import { refusesTracking } from "../perf/visitor_id.ts"; |
| 20 | import { sha256 } from "../kernel/hash.ts"; | |
| 20 | 21 | import { holds } from "./may.ts"; |
| 21 | 22 | import type { Principal } from "./principal.ts"; |
| 22 | 23 | |
| @@ -139,3 +140,41 @@ function mint(secret: Uint8Array): { readonly id: string; readonly value: string | ||
| 139 | 140 | const id = `v${Buffer.from(bytes).toString("hex")}`; |
| 140 | 141 | return { id, value: `${id}.${macOf(secret, id)}` }; |
| 141 | 142 | } |
| 143 | ||
| 144 | /** | |
| 145 | * How long a carry ticket names its visitor: long enough to sign up, short enough to leak little. | |
| 146 | */ | |
| 147 | export const CARRY_MS = 30 * 60_000; | |
| 148 | const CARRY_VALUE = /^[0-9a-f]{64}$/; | |
| 149 | ||
| 150 | /** | |
| 151 | * A one-time ticket naming this visitor to the forge's own host (#18113). The signed cookie lives | |
| 152 | * on the app's host and never leaves it; only its holder mints a ticket (`apps/feedback.ts`), and | |
| 153 | * only its hash is kept. A new ticket replaces the visitor's earlier ones, so each visitor holds | |
| 154 | * one live ticket however often they press Keep. | |
| 155 | */ | |
| 156 | export function mintCarry(db: Database, visitorId: string, at: number = Date.now()): string { | |
| 157 | const ticket = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex"); | |
| 158 | db.run("DELETE FROM visitor_carry WHERE expires_at <= ? OR visitor_id = ?", [new Date(at).toISOString(), visitorId]); | |
| 159 | db.run("INSERT INTO visitor_carry (ticket_hash, visitor_id, expires_at) VALUES (?, ?, ?)", [ | |
| 160 | sha256(ticket), | |
| 161 | visitorId, | |
| 162 | new Date(at + CARRY_MS).toISOString(), | |
| 163 | ]); | |
| 164 | return ticket; | |
| 165 | } | |
| 166 | ||
| 167 | /** The visitor a carry ticket names while it lasts; undefined for a made-up, spent or old one. */ | |
| 168 | export function carriedVisitor(db: Database, ticket: string, at: number = Date.now()): string | undefined { | |
| 169 | if (!CARRY_VALUE.test(ticket)) return undefined; | |
| 170 | return ( | |
| 171 | db | |
| 172 | .query<{ visitor_id: string }, [string, string]>("SELECT visitor_id FROM visitor_carry WHERE ticket_hash = ? AND expires_at > ?") | |
| 173 | .get(sha256(ticket), new Date(at).toISOString())?.visitor_id ?? undefined | |
| 174 | ); | |
| 175 | } | |
| 176 | ||
| 177 | /** Spend a carry ticket: once something is brought with it, it names nobody again. */ | |
| 178 | export function spendCarry(db: Database, ticket: string): void { | |
| 179 | if (CARRY_VALUE.test(ticket)) db.run("DELETE FROM visitor_carry WHERE ticket_hash = ?", [sha256(ticket)]); | |
| 180 | } |
src/http/lazy_lists.ts +3
| @@ -87,6 +87,9 @@ export const SETTINGS_ROUTES = [ | ||
| 87 | 87 | ["POST", "/settings/identities/:id/confirm"], |
| 88 | 88 | ["POST", "/settings/identities/:id/use"], |
| 89 | 89 | ["POST", "/settings/identities/:id/delete"], |
| 90 | ["GET", "/settings/bring"], | |
| 91 | ["POST", "/settings/bring"], | |
| 92 | ["POST", "/settings/bring/:id/undo"], | |
| 90 | 93 | ["GET", "/settings/subscriptions"], |
| 91 | 94 | ["POST", "/settings/subscriptions"], |
| 92 | 95 | ["POST", "/settings/crew/key"], |
src/http/marks/settings.json +2
| @@ -61,6 +61,8 @@ | ||
| 61 | 61 | "/settings/identities/:id/confirm": "open", |
| 62 | 62 | "/settings/identities/:id/use": "open", |
| 63 | 63 | "/settings/identities/:id/delete": "open", |
| 64 | "/settings/bring": "open", | |
| 65 | "/settings/bring/:id/undo": "open", | |
| 64 | 66 | "/settings/subscriptions": "admin", |
| 65 | 67 | "/settings/crew/key": "admin", |
| 66 | 68 | "/settings/crew/budgets": "admin", |
src/http/settings_routes.ts +5
| @@ -52,6 +52,7 @@ import { captainAct, captainPage } from "../web/pages/captain.ts"; | ||
| 52 | 52 | import { packsSettingsPage, packsSettingsSave } from "../web/pages/packs-settings.ts"; |
| 53 | 53 | import { featureAccept, featurePage, featureRun, featureSave, featuresPage, featureSwitch } from "../web/pages/features.ts"; |
| 54 | 54 | import { identityAdd, identityConfirm, identityRemove, identitiesPage, identityUse } from "../web/pages/identities.ts"; |
| 55 | import { visitorBringPage, visitorBringSubmit, visitorBringUndo } from "../web/pages/visitor_bring.ts"; | |
| 55 | 56 | import { passkeyAdd, passkeyDelete, passkeyOptions, passkeysPage } from "../web/pages/passkeys.ts"; |
| 56 | 57 | import { deviceCap, deviceDeclare, deviceGrant, devicesPage, deviceRemove, deviceRevoke } from "../web/settings/devices.ts"; |
| 57 | 58 | import { mailAwsDo, mailAwsUndo, secretDelete, secretSet, secretsPage } from "../web/pages/secrets.ts"; |
| @@ -237,6 +238,10 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea | ||
| 237 | 238 | router.add("POST", "/settings/identities/:id/confirm", identityConfirm); |
| 238 | 239 | router.add("POST", "/settings/identities/:id/use", identityUse); |
| 239 | 240 | router.add("POST", "/settings/identities/:id/delete", identityRemove); |
| 241 | // What a visitor made, brought to the account it signs in to, and undone (#18113). | |
| 242 | router.add("GET", "/settings/bring", visitorBringPage); | |
| 243 | router.add("POST", "/settings/bring", visitorBringSubmit); | |
| 244 | router.add("POST", "/settings/bring/:id/undo", visitorBringUndo); | |
| 240 | 245 | // The crew: a forge admin's section, hidden from everyone else. |
| 241 | 246 | router.add("GET", "/settings/subscriptions", subscriptionsPage); |
| 242 | 247 | router.add("POST", "/settings/subscriptions", subscriptionAdd); |
src/tui/forge_parts.ts +9
| @@ -88,6 +88,7 @@ import { talkChatsScreen } from "./screens/talk_chats.ts"; | ||
| 88 | 88 | import { sshOn } from "../settings/ssh.ts"; |
| 89 | 89 | import { sshKeysScreen } from "./screens/sshkeys.ts"; |
| 90 | 90 | import { identitiesScreen } from "./screens/identities.ts"; |
| 91 | import { visitorBringScreen } from "./screens/visitor_bring.ts"; | |
| 91 | 92 | import { passkeysScreen } from "./screens/passkeys.ts"; |
| 92 | 93 | import { confirmsScreen } from "./screens/confirms.ts"; |
| 93 | 94 | import { receiptsScreen } from "./screens/receipts.ts"; |
| @@ -610,6 +611,14 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] { | ||
| 610 | 611 | hint: "the addresses I proved, and what each is for", |
| 611 | 612 | run: () => ctx.push(identitiesScreen(session, ctx)), |
| 612 | 613 | }); |
| 614 | // Settings › Brought in: the receipts, and undo (#18113). | |
| 615 | if (session.signedIn && session.user?.kind !== "agent") | |
| 616 | commands.push({ | |
| 617 | id: "visitor-bring", | |
| 618 | title: "Brought in", | |
| 619 | hint: "what I made before signing in; u undoes", | |
| 620 | run: () => ctx.push(visitorBringScreen(session, ctx)), | |
| 621 | }); | |
| 613 | 622 | if (session.signedIn) |
| 614 | 623 | commands.push( |
| 615 | 624 | { |
src/tui/screens/visitor_bring.ts added +73
| @@ -0,0 +1,73 @@ | ||
| 1 | /** | |
| 2 | * Brought in, in the terminal (#18113), as Settings › Brought in: each time | |
| 3 | * this account brought what a visitor made, how many notes, and whether it may still be undone; | |
| 4 | * `u` undoes the selected one after a y/n, through `undoBrought`, the page's own action and words. | |
| 5 | * Bringing itself starts in the browser that made them: the visitor is that browser's cookie, | |
| 6 | * which a terminal never holds, so this screen says where to go instead. | |
| 7 | */ | |
| 8 | ||
| 9 | import { BRING_WORDS, broughtReceipts, undoBrought } from "../../actions/visitor_bring.ts"; | |
| 10 | import type { Receipt } from "../../core/visitor_bring.ts"; | |
| 11 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 12 | import { binding } from "../app/keys.ts"; | |
| 13 | import { style } from "../term/style.ts"; | |
| 14 | import { truncate } from "../term/width.ts"; | |
| 15 | import type { Session } from "../session.ts"; | |
| 16 | import { fill, len, split } from "../ui/layout.ts"; | |
| 17 | import { ListState, ago, confirmScreen, drawList, type ListRow } from "./common.ts"; | |
| 18 | ||
| 19 | /** Where bringing starts, said when there is nothing here yet. */ | |
| 20 | 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."; | |
| 22 | ||
| 23 | const undoable = (r: Receipt, now: number): boolean => r.undoneAt === null && Date.parse(r.undoUntil) > now; | |
| 24 | ||
| 25 | export function visitorBringScreen(f: Session, ctx: Ctx): Screen { | |
| 26 | const state = new ListState(); | |
| 27 | let note = ""; | |
| 28 | const items = () => (f.user === undefined ? [] : broughtReceipts(f.app, f.user)); | |
| 29 | const rows = (): ListRow[] => { | |
| 30 | const now = Date.now(); | |
| 31 | return items().map((r) => ({ | |
| 32 | title: `${r.count} ${r.count === 1 ? "note" : "notes"} brought`, | |
| 33 | meta: `${ago(r.at)} · ${r.undoneAt !== null ? "undone" : undoable(r, now) ? "u undoes, for 24 hours" : "kept"}`, | |
| 34 | })); | |
| 35 | }; | |
| 36 | ||
| 37 | const screen: Screen = { | |
| 38 | title: "Brought in", | |
| 39 | keys: [binding(["j", "k"], "move cursor"), binding(["u"], "undo")], | |
| 40 | render(area, s) { | |
| 41 | const c = ctx.theme.c; | |
| 42 | 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."; | |
| 44 | s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); | |
| 45 | drawList(s, body!, c, state, rows()); | |
| 46 | }, | |
| 47 | key(e) { | |
| 48 | if (state.key(e, items().length)) return true; | |
| 49 | if (e.ctrl || e.alt || f.user === undefined) return false; | |
| 50 | const user = f.user; | |
| 51 | const r = items()[state.index]; | |
| 52 | if (r === undefined || e.key !== "u") return false; | |
| 53 | if (!undoable(r, Date.now())) { | |
| 54 | note = BRING_WORDS[r.undoneAt !== null ? "undone" : "too_late"]; | |
| 55 | ctx.invalidate(); | |
| 56 | return true; | |
| 57 | } | |
| 58 | ctx.push(confirmScreen(ctx, screen, { | |
| 59 | title: "Undo bringing", body: [`give ${r.count} ${r.count === 1 ? "note" : "notes"} back to the visitor? y/n`], | |
| 60 | actions: [{ label: "Undo", variant: "danger" }, { label: "Cancel", variant: "ghost" }], | |
| 61 | selected: 1, yesNo: true, | |
| 62 | onChoose: (i) => { | |
| 63 | if (i !== 0) return; | |
| 64 | const done = undoBrought(f.app, user, r.id); | |
| 65 | note = done.ok ? "Undone: those notes are the visitor's again." : BRING_WORDS[done.error]; | |
| 66 | ctx.invalidate(); | |
| 67 | }, | |
| 68 | })); | |
| 69 | return true; | |
| 70 | }, | |
| 71 | }; | |
| 72 | return screen; | |
| 73 | } |
src/web/pages/origins.ts +2
| @@ -100,6 +100,7 @@ import { | ||
| 100 | 100 | } from "../ui.ts"; |
| 101 | 101 | |
| 102 | 102 | export type AccountSection = |
| 103 | | "bring" | |
| 103 | 104 | | "billing" |
| 104 | 105 | | "adminflows" |
| 105 | 106 | | "security" |
| @@ -173,6 +174,7 @@ const SECTION_ROWS: readonly (readonly [ | ||
| 173 | 174 | ["Account", "Connected agents", "/settings/grants", "bot", (c) => c === "grants", false], |
| 174 | 175 | ["Account", "Who may do what", "/settings/who-can", "users", (c) => c === "who-can", false], |
| 175 | 176 | ["Account", "Confirms", "/settings/confirms", "check", (c) => c === "confirms", false], |
| 177 | ["Account", "Brought in", "/settings/bring", "download", (c) => c === "bring", false], | |
| 176 | 178 | ["Crew and AI", "Model", "/settings/model", "key", (c) => c === "model", false], |
| 177 | 179 | ["Crew and AI", "Crew", "/settings/crew", "bot", (c) => c === "crew", true], |
| 178 | 180 | ["Crew and AI", "Captain", "/settings/captain", "bot", (c) => c === "captain", true], |
src/web/pages/visitor_bring.ts added +111
| @@ -0,0 +1,111 @@ | ||
| 1 | /** | |
| 2 | * Settings › Brought in (#18113): what a visitor made on this device, offered to the | |
| 3 | * account it signs in or up to, and the receipts of what was brought, each undoable for a day. | |
| 4 | * | |
| 5 | * Reached from the forge button's "Keep these on my account" on an app (`apps/feedback.ts` mints | |
| 6 | * the one-time `carry` ticket), through sign-in or sign-up, which keep this address as `next`. | |
| 7 | * Nothing is brought by arriving: the account picks and presses Bring, a same-origin form, and | |
| 8 | * the action (`actions/visitor_bring.ts`) decides who may. The terminal shows the receipts and | |
| 9 | * undoes them (`tui/screens/visitor_bring.ts`). | |
| 10 | */ | |
| 11 | ||
| 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"; | |
| 14 | import type { Ctx } from "../../http/context.ts"; | |
| 15 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; | |
| 16 | import { sshOn } from "../../settings/ssh.ts"; | |
| 17 | import { pageHead, settingsLayout, signInFirst, signInHref } from "../chrome.ts"; | |
| 18 | import { emptyNote } from "../empty_words.ts"; | |
| 19 | import { field, readForm } from "../form.ts"; | |
| 20 | import { html, type Html } from "../html.ts"; | |
| 21 | import { flashTo, page } from "../layout.ts"; | |
| 22 | import { btn, row, rowList, time } from "../ui.ts"; | |
| 23 | import { accountSections } from "./origins.ts"; | |
| 24 | ||
| 25 | const HERE = "/settings/bring"; | |
| 26 | /** Said when a visitor made more than one page lists. */ | |
| 27 | const MORE_WAITING = `Only the newest ${String(MADE_SHOWN)} are listed. Bring these, then press "Keep these on my account" again for the rest.`; | |
| 28 | /** A ticket is 64 hex characters; anything else is carried as nothing. */ | |
| 29 | const carryOf = (value: string | null): string => (value !== null && /^[0-9a-f]{64}$/.test(value) ? value : ""); | |
| 30 | ||
| 31 | 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 | }); | |
| 37 | ||
| 38 | const receiptRow = (r: Receipt, now: number): Html => { | |
| 39 | const open = r.undoneAt === null && Date.parse(r.undoUntil) > now; | |
| 40 | const said = r.undoneAt !== null ? "undone" : open ? html`undo until ${time(r.undoUntil)}` : "kept"; | |
| 41 | return row({ | |
| 42 | title: html`${String(r.count)} ${r.count === 1 ? "note" : "notes"} brought`, | |
| 43 | meta: html`${time(r.at)} · ${said}`, | |
| 44 | ...(open | |
| 45 | ? { trail: html`<form class="row-actions" method="post" action="${HERE}/${r.id}/undo">${btn("Undo", { size: "sm", label: `Undo bringing ${String(r.count)}` })}</form>` } | |
| 46 | : {}), | |
| 47 | }); | |
| 48 | }; | |
| 49 | ||
| 50 | // GET /settings/bring | |
| 51 | export function visitorBringPage(ctx: Ctx): Response { | |
| 52 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 53 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 54 | const user = ctx.auth.user; | |
| 55 | const carry = carryOf(ctx.url.searchParams.get("carry")); | |
| 56 | const { made, more } = bringable(ctx.app, { carry, headers: ctx.request.headers }); | |
| 57 | const may = mayBring(ctx.app, user, ctx.auth); | |
| 58 | const now = Date.now(); | |
| 59 | const offer = | |
| 60 | made.length === 0 | |
| 61 | ? emptyNote("nothingMadeAsAVisitor") | |
| 62 | : !may.ok | |
| 63 | ? html`<p>${BRING_WORDS[may.error]}</p> | |
| 64 | ${may.error === "sign_in_again" ? html`<p><a class="btn btn-primary btn-sm" href="${signInHref(ctx)}">Sign in again</a></p>` : null}` | |
| 65 | : html`<form method="post" action="${HERE}"> | |
| 66 | <input type="hidden" name="carry" value="${carry}" /> | |
| 67 | ${rowList(made.map(madeRow), { bare: true, label: "Made as a visitor" })} | |
| 68 | ${more ? html`<p class="muted small">${MORE_WAITING}</p>` : null} | |
| 69 | ${btn("Bring the ones ticked", { variant: "primary", size: "sm" })} | |
| 70 | </form>`; | |
| 71 | const receipts = broughtReceipts(ctx.app, user); | |
| 72 | const body = html`<section class="settings-block"> | |
| 73 | <h2>Made as a visitor</h2> | |
| 74 | ${offer} | |
| 75 | </section> | |
| 76 | <section class="settings-block"> | |
| 77 | <h2>Brought</h2> | |
| 78 | ${receipts.length === 0 ? emptyNote("nothingBroughtYet") : rowList(receipts.map((r) => receiptRow(r, now)), { bare: true, label: "Brought" })} | |
| 79 | </section>`; | |
| 80 | const rendering = performance.now(); | |
| 81 | const response = page({ | |
| 82 | ctx, | |
| 83 | 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." })} | |
| 85 | ${settingsLayout(accountSections("bring", { admin: user.isAdmin, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`, | |
| 86 | }); | |
| 87 | notePhase(ctx.request, "render", performance.now() - rendering); | |
| 88 | return response; | |
| 89 | } | |
| 90 | ||
| 91 | // POST /settings/bring | |
| 92 | export async function visitorBringSubmit(ctx: Ctx): Promise<Response> { | |
| 93 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 94 | const form = await readForm(ctx, "admin"); | |
| 95 | if (form instanceof Response) return form; | |
| 96 | const carry = carryOf(field(form, "carry")); | |
| 97 | const picks = form.getAll("pick").filter((p): p is string => typeof p === "string" && /^[0-9a-z]{10,40}$/.test(p)); | |
| 98 | const done = bringToAccount(ctx.app, ctx.auth.user, ctx.auth, { carry, headers: ctx.request.headers }, picks); | |
| 99 | if (!done.ok) return flashTo(ctx, carry === "" ? HERE : `${HERE}?carry=${carry}`, { tone: "danger", message: BRING_WORDS[done.error] }); | |
| 100 | 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.` }); | |
| 102 | } | |
| 103 | ||
| 104 | // POST /settings/bring/:id/undo | |
| 105 | export async function visitorBringUndo(ctx: Ctx): Promise<Response> { | |
| 106 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 107 | const form = await readForm(ctx, "admin"); | |
| 108 | if (form instanceof Response) return form; | |
| 109 | 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] }); | |
| 111 | } |
test/apps-toolbar-draft.test.ts +1 −1
| @@ -8,7 +8,7 @@ import { toolbarJs } from "../src/apps/toolbar.ts"; | ||
| 8 | 8 | import { NOTE_FAILED } from "../src/apps/note_words.ts"; |
| 9 | 9 | |
| 10 | 10 | /** The toolbar budget of toolbar-budget.test.ts: 24 KB. */ |
| 11 | const TOOLBAR_BYTE_BUDGET = 24 * 1024 + 2528; // +1216 the tell context row (#15750), +288 the fold handle, +768 clearing the page's fixed bars (#16310) | |
| 11 | const TOOLBAR_BYTE_BUDGET = 24 * 1024 + 2912; // +1216 the tell context row (#15750), +288 the fold handle, +768 clearing the page's fixed bars (#16310), +384 keeping a visitor's notes on an account (#18113) | |
| 12 | 12 | const HOSTILE = "<img src=x onerror=alert(1)>"; |
| 13 | 13 | |
| 14 | 14 | interface El { tag: string; children: El[]; listeners: Record<string, ((e: object) => void)[]>; [k: string]: any } |
test/apps-toolbar-state.test.ts +3 −1
| @@ -50,9 +50,11 @@ const FOLD_ALLOWANCE = 280; | ||
| 50 | 50 | const BAR_ALLOWANCE = 670; |
| 51 | 51 | // The comment script is handed the pull's check state (#6381), allowed by name: 17 bytes. |
| 52 | 52 | const CHECK_HANDOFF_ALLOWANCE = 20; |
| 53 | // The "Keep these on my account" form under a visitor's own notes (#18113). | |
| 54 | const CARRY_ALLOWANCE = 420; | |
| 53 | 55 | |
| 54 | 56 | test("the addition stays under 300 bytes", () => { |
| 55 | expect(Buffer.byteLength(toolbarJs) - BASE_SCRIPT_BYTES).toBeLessThan(300 + DISMISSAL_ALLOWANCE + CHECK_SLOT_ALLOWANCE + TITLE_ALLOWANCE + YOURS_WHY_ALLOWANCE + TELL_CONTEXT_ALLOWANCE + HOME_ALLOWANCE + FOLD_ALLOWANCE + BAR_ALLOWANCE + CHECK_HANDOFF_ALLOWANCE); | |
| 57 | expect(Buffer.byteLength(toolbarJs) - BASE_SCRIPT_BYTES).toBeLessThan(300 + DISMISSAL_ALLOWANCE + CHECK_SLOT_ALLOWANCE + TITLE_ALLOWANCE + YOURS_WHY_ALLOWANCE + TELL_CONTEXT_ALLOWANCE + HOME_ALLOWANCE + FOLD_ALLOWANCE + BAR_ALLOWANCE + CHECK_HANDOFF_ALLOWANCE + CARRY_ALLOWANCE); | |
| 56 | 58 | const tag = toolbarTag("https://forge.test", where("x".repeat(CHANGE_MAX)), "p", "n"); |
| 57 | 59 | const bare = toolbarTag("https://forge.test", where(), "p", "n"); |
| 58 | 60 | expect(Buffer.byteLength(tag) - Buffer.byteLength(bare)).toBeLessThan(300); |
test/palette-roster.test.ts +2
| @@ -125,6 +125,7 @@ test("a site-admin person is offered the whole roster", () => { | ||
| 125 | 125 | ["fork-flows", "Fork flows", "what I follow, what I offered, what my forks offered me"], |
| 126 | 126 | ["passkeys", "Passkeys", "the passkeys that sign in as you"], |
| 127 | 127 | ["proven-emails", "Proven emails", "the addresses I proved, and what each is for"], |
| 128 | ["visitor-bring", "Brought in", "what I made before signing in; u undoes"], | |
| 128 | 129 | ["account", "Account settings", undefined], |
| 129 | 130 | ["signins", "Signed in", "your browsers and tokens; d signs a browser out"], |
| 130 | 131 | ["sentinel", "Sentinel", "the forge's open faults"], |
| @@ -480,6 +481,7 @@ test("a member person is offered the signed-in roster without the admin entries" | ||
| 480 | 481 | ["fork-flows", "Fork flows", "what I follow, what I offered, what my forks offered me"], |
| 481 | 482 | ["passkeys", "Passkeys", "the passkeys that sign in as you"], |
| 482 | 483 | ["proven-emails", "Proven emails", "the addresses I proved, and what each is for"], |
| 484 | ["visitor-bring", "Brought in", "what I made before signing in; u undoes"], | |
| 483 | 485 | ["account", "Account settings", undefined], |
| 484 | 486 | ["signins", "Signed in", "your browsers and tokens; d signs a browser out"], |
| 485 | 487 | ["oauth-grants", "Connected agents", "the agents you let in through OAuth; x revokes one"], |
test/toolbar-budget.test.ts +1 −1
| @@ -23,7 +23,7 @@ quietLogs(); | ||
| 23 | 23 | * The one budget (it loads on every app page): 24 KB, the script keeping the filed number and links |
| 24 | 24 | * of #10560. Raising it is a decision, not a fix. |
| 25 | 25 | */ |
| 26 | export const TOOLBAR_BYTE_BUDGET = 24 * 1024 + 2528; // +1216 the tell context row (#15750), +288 the fold handle, +768 clearing the page's fixed bars (#16310) | |
| 26 | export const TOOLBAR_BYTE_BUDGET = 24 * 1024 + 2912; // +1216 the tell context row (#15750), +288 the fold handle, +768 clearing the page's fixed bars (#16310), +384 keeping a visitor's notes on an account (#18113) | |
| 27 | 27 | /** The preview's comment box (#13664), fetched only when a preview's panel first opens. */ |
| 28 | 28 | export const COMMENT_BYTE_BUDGET = 4 * 1024; |
| 29 | 29 |
test/toolbar-size.test.ts +1 −1
| @@ -12,7 +12,7 @@ import { toolbarJs, toolbarTag } from "../src/apps/toolbar.ts"; | ||
| 12 | 12 | * The limit, in bytes, of the toolbar's tag plus gzipped script. Raising it is a decision, not a |
| 13 | 13 | * fix. |
| 14 | 14 | */ |
| 15 | export const TOOLBAR_WIRE_LIMIT = 8 * 1024 + 832; // +128 the pull title (#15169), +384 the tell context row (#15750), +64 the fold handle, +256 clearing the page's fixed bars (#16310) | |
| 15 | export const TOOLBAR_WIRE_LIMIT = 8 * 1024 + 960; // +128 the pull title (#15169), +384 the tell context row (#15750), +64 the fold handle, +256 clearing the page's fixed bars (#16310), +128 keeping a visitor's notes on an account (#18113) | |
| 16 | 16 | |
| 17 | 17 | test("the toolbar's injected bytes (tag plus gzipped script) stay under the stated limit", () => { |
| 18 | 18 | const tag = toolbarTag("https://forge.test", { app: "notes", repo: "a/b", env: "preview", pull: 7 }, "proof", "n0nce"); |
test/visitor-bring.test.ts added +305
| @@ -0,0 +1,305 @@ | ||
| 1 | /** | |
| 2 | * Bringing what a visitor made to an account (#18113): a visitor sends a note on an app, keeps it | |
| 3 | * through the forge button, signs up, picks it and brings it, and finds it the account's own; the | |
| 4 | * receipt undoes it for a day. The red team: a forged or spent carry, an unsigned visitor id, a | |
| 5 | * pick that is not theirs, a token, a cross-site form, an account with a passkey that has not just | |
| 6 | * signed in, an undo by someone else or too late, and a ban laundered through an account. | |
| 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 { newApp } from "../src/actions/apps.ts"; | |
| 15 | import { bringable, bringToAccount, FRESH_MS, mayBring, undoBrought } from "../src/actions/visitor_bring.ts"; | |
| 16 | import { AppsRuntime } from "../src/apps/runtime.ts"; | |
| 17 | import { getAppBySlug } from "../src/core/apps.ts"; | |
| 18 | import { banVisitor, getNote, insertNote, notesOf } from "../src/core/app_notes.ts"; | |
| 19 | import { classifiedAudience } from "../src/core/event_audience.ts"; | |
| 20 | import { addPasskey } from "../src/core/passkeys.ts"; | |
| 21 | import { createSession } from "../src/core/sessions.ts"; | |
| 22 | import { createToken } from "../src/core/tokens.ts"; | |
| 23 | import { MADE_SHOWN, madeBy, UNDO_MS } from "../src/core/visitor_bring.ts"; | |
| 24 | import { CARRY_MS, carriedVisitor, mintCarry } from "../src/core/visitors.ts"; | |
| 25 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; | |
| 26 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 27 | import { quietLogs } from "./helpers/globals.ts"; | |
| 28 | import { LOOPBACK_PROXIES } from "./helpers/loopback-proxy.ts"; | |
| 29 | ||
| 30 | quietLogs(); | |
| 31 | ||
| 32 | const DOMAIN = "apps.test"; | |
| 33 | ||
| 34 | describe("a visitor's note comes to the account they sign up to, only when they choose", () => { | |
| 35 | let dataDir: string; | |
| 36 | let app: App; | |
| 37 | let servers: Servers; | |
| 38 | let runtime: AppsRuntime; | |
| 39 | let owner: User; | |
| 40 | let appId = ""; | |
| 41 | let repoId = ""; | |
| 42 | ||
| 43 | beforeAll(async () => { | |
| 44 | dataDir = await mkdtemp(join(tmpdir(), "forge-visitor-bring-")); | |
| 45 | app = createApp({ dataDir, port: 0, host: "forge.test", trustedProxies: LOOPBACK_PROXIES }); | |
| 46 | servers = await serve(app); | |
| 47 | runtime = new AppsRuntime(app, { domain: DOMAIN, scheme: "http", publicPort: servers.port, forgeUrl: servers.url, concurrency: 1 }); | |
| 48 | await runtime.start(); | |
| 49 | const made = await createUser(app.db, { | |
| 50 | origin: "seed", | |
| 51 | trusted: true, | |
| 52 | username: "alice", | |
| 53 | email: "[email protected]", | |
| 54 | password: "a-good-passphrase", | |
| 55 | adminIfFirst: true, | |
| 56 | }); | |
| 57 | if (!made.ok) throw new Error(made.error); | |
| 58 | owner = made.value; | |
| 59 | const a = await newApp(app, owner, { name: "notes", description: "Words", visibility: "public" }); | |
| 60 | if (!a.ok) throw new Error(String(a.error)); | |
| 61 | const record = getAppBySlug(app.db, "notes")!; | |
| 62 | appId = record.id; | |
| 63 | repoId = record.repoId; | |
| 64 | }, 120_000); | |
| 65 | ||
| 66 | afterAll(async () => { | |
| 67 | await runtime.stop(); | |
| 68 | servers.stop(); | |
| 69 | app.close(); | |
| 70 | await rm(dataDir, { recursive: true, force: true }); | |
| 71 | }); | |
| 72 | ||
| 73 | const host = `notes.${DOMAIN}`; | |
| 74 | const onApp = (path: string, init: { method?: string; body?: string; cookie?: string; type?: string } = {}) => | |
| 75 | fetch(`${servers.url}${path}`, { | |
| 76 | method: init.method ?? "GET", | |
| 77 | ...(init.body === undefined ? {} : { body: init.body }), | |
| 78 | headers: { | |
| 79 | host: `${host}:${servers.port}`, | |
| 80 | ...(init.method === "POST" ? { origin: `http://${host}:${servers.port}`, "content-type": init.type ?? "application/json" } : {}), | |
| 81 | ...(init.cookie === undefined ? {} : { cookie: init.cookie }), | |
| 82 | }, | |
| 83 | redirect: "manual", | |
| 84 | }); | |
| 85 | const onForge = (path: string, cookie: string, body?: URLSearchParams, origin = servers.url) => | |
| 86 | fetch(`${servers.url}${path}`, { | |
| 87 | method: body === undefined ? "GET" : "POST", | |
| 88 | headers: { cookie, ...(body === undefined ? {} : { origin }) }, | |
| 89 | ...(body === undefined ? {} : { body }), | |
| 90 | redirect: "manual", | |
| 91 | }); | |
| 92 | const cookieOf = (res: Response, name: string): string => res.headers.getSetCookie().find((c) => c.startsWith(`${name}=`))!.split(";")[0]!; | |
| 93 | const signUp = async (username: string): Promise<{ cookie: string; user: User }> => { | |
| 94 | const res = await fetch(`${servers.url}/signup`, { | |
| 95 | method: "POST", | |
| 96 | body: new URLSearchParams({ username, email: `${username}@f.dev`, password: "account-password" }), | |
| 97 | redirect: "manual", | |
| 98 | }); | |
| 99 | return { cookie: cookieOf(res, "forge_session"), user: getUserByName(app.db, username)! }; | |
| 100 | }; | |
| 101 | /** An account and its browser's cookie, made in-process: the sign-up door limits by address. */ | |
| 102 | const seeded = async (username: string): Promise<{ cookie: string; user: User; sessionId: string }> => { | |
| 103 | const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.dev`, password: "account-password" }); | |
| 104 | if (!made.ok) throw new Error(made.error); | |
| 105 | const cookie = `forge_session=${createSession(app.db, made.value.id).token}`; | |
| 106 | const sessionId = app.db.query<{ id: string }, [string]>("SELECT id FROM session WHERE user_id = ?").get(made.value.id)!.id; | |
| 107 | return { cookie, user: made.value, sessionId }; | |
| 108 | }; | |
| 109 | /** A visitor sends a note on the app: their maker cookie and the note's id. */ | |
| 110 | const visitorNote = async (text: string, maker = ""): Promise<{ maker: string; noteId: string }> => { | |
| 111 | const res = await onApp("/__forge/note", { method: "POST", body: JSON.stringify({ text, bare: true }), ...(maker === "" ? {} : { cookie: maker }) }); | |
| 112 | expect(res.status).toBe(201); | |
| 113 | const body = (await res.json()) as { note: { id: string } }; | |
| 114 | return { maker: maker === "" ? cookieOf(res, "forge_maker") : maker, noteId: body.note.id }; | |
| 115 | }; | |
| 116 | /** The forge button's Keep: the carry ticket in the forge address it sends the visitor to. */ | |
| 117 | const keep = async (maker: string): Promise<string> => { | |
| 118 | const res = await onApp("/__forge/note/carry", { method: "POST", body: "", cookie: maker, type: "application/x-www-form-urlencoded" }); | |
| 119 | expect(res.status).toBe(303); | |
| 120 | const to = new URL(res.headers.get("location")!); | |
| 121 | expect(to.origin).toBe(servers.url); | |
| 122 | expect(to.pathname).toBe("/settings/bring"); | |
| 123 | return to.searchParams.get("carry")!; | |
| 124 | }; | |
| 125 | ||
| 126 | test("make a note as a visitor, sign up, bring it, find it the account's own; undo puts it back", async () => { | |
| 127 | const { maker, noteId } = await visitorNote("The button is hard to find"); | |
| 128 | const listed = (await (await onApp("/__forge/notes", { cookie: maker })).json()) as { carry: boolean }; | |
| 129 | expect(listed.carry).toBe(true); | |
| 130 | const carry = await keep(maker); | |
| 131 | ||
| 132 | // Not signed in: the page sends them to sign in, and back here with the ticket. | |
| 133 | const out = await onForge(`/settings/bring?carry=${carry}`, ""); | |
| 134 | expect(out.status).toBe(303); | |
| 135 | expect(decodeURIComponent(out.headers.get("location")!)).toContain(`/settings/bring?carry=${carry}`); | |
| 136 | ||
| 137 | const { cookie, user } = await signUp("vera"); | |
| 138 | // Arriving brings nothing: the note is still the visitor's until the account picks it. | |
| 139 | const shown = await (await onForge(`/settings/bring?carry=${carry}`, cookie)).text(); | |
| 140 | expect(shown).toContain(`value="${noteId}"`); | |
| 141 | expect(shown).toContain("<strong>notes</strong>"); | |
| 142 | expect(getNote(app.db, appId, noteId)!.visitor.startsWith("v:")).toBe(true); | |
| 143 | ||
| 144 | const brought = await onForge("/settings/bring", cookie, new URLSearchParams({ carry, pick: noteId })); | |
| 145 | expect(brought.status).toBe(303); | |
| 146 | const note = getNote(app.db, appId, noteId)!; | |
| 147 | expect(note.visitor).toBe(`u:${user.id}`); | |
| 148 | expect(note.name).toBe("@vera"); | |
| 149 | expect(notesOf(app.db, appId, `u:${user.id}`).map((n) => n.id)).toEqual([noteId]); | |
| 150 | // The visitor's own list is empty now, and the spent ticket names nobody. | |
| 151 | expect(((await (await onApp("/__forge/notes", { cookie: maker })).json()) as { notes: unknown[] }).notes).toEqual([]); | |
| 152 | expect(carriedVisitor(app.db, carry)).toBeUndefined(); | |
| 153 | ||
| 154 | const page = await (await onForge("/settings/bring", cookie)).text(); | |
| 155 | expect(page).toContain("1 note brought"); | |
| 156 | const receipt = /action="\/settings\/bring\/([^/]+)\/undo"/.exec(page)![1]!; | |
| 157 | const undone = await onForge(`/settings/bring/${receipt}/undo`, cookie, new URLSearchParams()); | |
| 158 | expect(undone.status).toBe(303); | |
| 159 | expect(getNote(app.db, appId, noteId)!.visitor.startsWith("v:")).toBe(true); | |
| 160 | expect(((await (await onApp("/__forge/notes", { cookie: maker })).json()) as { notes: unknown[] }).notes.length).toBe(1); | |
| 161 | // Both events are the person's own receipts. | |
| 162 | const kinds = app.db.query<{ kind: string }, []>("SELECT kind FROM event WHERE kind LIKE 'visitor.%' ORDER BY seq").all().map((r) => r.kind); | |
| 163 | expect(kinds).toEqual(["visitor.brought", "visitor.undone"]); | |
| 164 | expect(classifiedAudience("visitor.brought")).toBe("actor"); | |
| 165 | expect(classifiedAudience("visitor.undone")).toBe("actor"); | |
| 166 | }); | |
| 167 | ||
| 168 | test("a forged carry, an unsigned visitor id or a spent ticket brings nothing", async () => { | |
| 169 | const { maker, noteId } = await visitorNote("Forge me"); | |
| 170 | const { cookie } = await signUp("mallory"); | |
| 171 | const id = maker.slice("forge_maker=".length).split(".")[0]!; | |
| 172 | // A made-up ticket, and the visitor id with no signature, in the cookie or the form. | |
| 173 | for (const [carry, extra] of [ | |
| 174 | ["f".repeat(64), ""], | |
| 175 | ["", `; forge_maker=${id}`], | |
| 176 | ["", `; forge_maker=${id}.${"0".repeat(32)}`], | |
| 177 | ] as const) { | |
| 178 | const shown = await (await onForge(`/settings/bring?carry=${carry}`, cookie + extra)).text(); | |
| 179 | expect(shown).not.toContain(noteId); | |
| 180 | const res = await onForge("/settings/bring", cookie + extra, new URLSearchParams({ carry, pick: noteId, visitor: id })); | |
| 181 | expect(res.status).toBe(303); | |
| 182 | expect(getNote(app.db, appId, noteId)!.visitor).toBe(`v:${id}`); | |
| 183 | } | |
| 184 | // A carry from the app's host with no signed cookie mints nothing. | |
| 185 | expect((await onApp("/__forge/note/carry", { method: "POST", body: "", cookie: `forge_maker=${id}`, type: "application/x-www-form-urlencoded" })).status).toBe(404); | |
| 186 | }); | |
| 187 | ||
| 188 | test("a pick that is not the visitor's, a cross-site form and a token are refused", async () => { | |
| 189 | const mine = await visitorNote("Mine"); | |
| 190 | const theirs = await visitorNote("Theirs"); | |
| 191 | const { cookie, user } = await signUp("trent"); | |
| 192 | const carry = await keep(mine.maker); | |
| 193 | // Another visitor's note named in the form is passed over. | |
| 194 | await onForge("/settings/bring", cookie, new URLSearchParams({ carry, pick: theirs.noteId })); | |
| 195 | expect(getNote(app.db, appId, theirs.noteId)!.visitor.startsWith("v:")).toBe(true); | |
| 196 | // A form posted from another site is refused before it is read. | |
| 197 | const cross = await onForge("/settings/bring", cookie, new URLSearchParams({ carry, pick: mine.noteId }), "https://evil.test"); | |
| 198 | expect(cross.status).toBe(403); | |
| 199 | // A token is not the person in a browser. | |
| 200 | const token = createToken(app.db, user.id, "script", "admin"); | |
| 201 | const byToken = await fetch(`${servers.url}/settings/bring`, { | |
| 202 | method: "POST", | |
| 203 | headers: { authorization: `Bearer ${token.token}`, origin: servers.url }, | |
| 204 | body: new URLSearchParams({ carry, pick: mine.noteId }), | |
| 205 | redirect: "manual", | |
| 206 | }); | |
| 207 | expect([303, 403]).toContain(byToken.status); | |
| 208 | expect(getNote(app.db, appId, mine.noteId)!.visitor.startsWith("v:")).toBe(true); | |
| 209 | expect(mayBring(app, user, { via: "token" })).toEqual({ ok: false, error: "browser_only" }); | |
| 210 | // The ticket was never spent by a refusal: the person can still bring it. | |
| 211 | expect((await onForge("/settings/bring", cookie, new URLSearchParams({ carry, pick: mine.noteId }))).status).toBe(303); | |
| 212 | expect(getNote(app.db, appId, mine.noteId)!.visitor).toBe(`u:${user.id}`); | |
| 213 | }); | |
| 214 | ||
| 215 | test("an account with a passkey brings only right after signing in", async () => { | |
| 216 | const { maker, noteId } = await visitorNote("Passkey"); | |
| 217 | const { cookie, user } = await signUp("peggy"); | |
| 218 | addPasskey(app.db, user.id, "laptop", { id: "cred-peggy", alg: "ES256", key: { kty: "EC", crv: "P-256", x: "AA", y: "AA" }, signCount: 0 }); | |
| 219 | const sessionId = app.db.query<{ id: string }, [string]>("SELECT id FROM session WHERE user_id = ?").get(user.id)!.id; | |
| 220 | const carry = await keep(maker); | |
| 221 | const later = Date.now() + FRESH_MS + 60_000; | |
| 222 | expect(mayBring(app, user, { via: "session", sessionId }, later)).toEqual({ ok: false, error: "sign_in_again" }); | |
| 223 | const stale = bringToAccount(app, user, { via: "session", sessionId }, { carry, headers: new Headers() }, [noteId], later); | |
| 224 | expect(stale).toEqual({ ok: false, error: "sign_in_again" }); | |
| 225 | expect(getNote(app.db, appId, noteId)!.visitor.startsWith("v:")).toBe(true); | |
| 226 | // Just signed in: the passkey has said yes. | |
| 227 | const page = await (await onForge(`/settings/bring?carry=${carry}`, cookie)).text(); | |
| 228 | expect(page).toContain(`value="${noteId}"`); | |
| 229 | expect(bringToAccount(app, user, { via: "session", sessionId }, { carry, headers: new Headers() }, [noteId]).ok).toBe(true); | |
| 230 | }); | |
| 231 | ||
| 232 | test("an undo is the bringer's own, once, inside its day", async () => { | |
| 233 | const { maker, noteId } = await visitorNote("Undo me"); | |
| 234 | const { user } = await signUp("ursula"); | |
| 235 | const o = await createUser(app.db, { origin: "seed", trusted: true, username: "oscar", email: "[email protected]", password: "account-password" }); | |
| 236 | if (!o.ok) throw new Error(o.error); | |
| 237 | const other = o.value; | |
| 238 | const sessionId = app.db.query<{ id: string }, [string]>("SELECT id FROM session WHERE user_id = ?").get(user.id)!.id; | |
| 239 | const carry = await keep(maker); | |
| 240 | const done = bringToAccount(app, user, { via: "session", sessionId }, { carry, headers: new Headers() }, [noteId]); | |
| 241 | if (!done.ok) throw new Error(done.error); | |
| 242 | expect(undoBrought(app, other, done.value.id)).toEqual({ ok: false, error: "not_found" }); | |
| 243 | expect(undoBrought(app, user, done.value.id, Date.now() + UNDO_MS + 1)).toEqual({ ok: false, error: "too_late" }); | |
| 244 | expect(undoBrought(app, user, done.value.id).ok).toBe(true); | |
| 245 | expect(undoBrought(app, user, done.value.id)).toEqual({ ok: false, error: "undone" }); | |
| 246 | }); | |
| 247 | ||
| 248 | test("a ticket lasts half an hour; hidden and banned notes never come along", () => { | |
| 249 | const ticket = mintCarry(app.db, "v" + "a".repeat(32), 1_000); | |
| 250 | expect(carriedVisitor(app.db, ticket, 1_000 + CARRY_MS - 1)).toBe("v" + "a".repeat(32)); | |
| 251 | expect(carriedVisitor(app.db, ticket, 1_000 + CARRY_MS)).toBeUndefined(); | |
| 252 | const visitor = "v" + "b".repeat(32); | |
| 253 | const kept = insertNote(app.db, { appId, repoId, issueNumber: 1, visitor: `v:${visitor}`, name: "visitor-b" }); | |
| 254 | expect(madeBy(app.db, visitor).map((m) => m.noteId)).toEqual([kept.id]); | |
| 255 | banVisitor(app.db, appId, `v:${visitor}`); | |
| 256 | expect(madeBy(app.db, visitor)).toEqual([]); | |
| 257 | }); | |
| 258 | test("each visitor holds one live ticket: pressing Keep again replaces the last", async () => { | |
| 259 | const visitor = "v" + "d".repeat(32); | |
| 260 | const tickets = (): number => | |
| 261 | app.db.query<{ n: number }, [string]>("SELECT count(*) AS n FROM visitor_carry WHERE visitor_id = ?").get(visitor)!.n; | |
| 262 | const first = mintCarry(app.db, visitor); | |
| 263 | for (let i = 0; i < 5; i++) mintCarry(app.db, visitor); | |
| 264 | const last = mintCarry(app.db, visitor); | |
| 265 | expect(tickets()).toBe(1); | |
| 266 | expect(carriedVisitor(app.db, first)).toBeUndefined(); | |
| 267 | expect(carriedVisitor(app.db, last)).toBe(visitor); | |
| 268 | }); | |
| 269 | ||
| 270 | test("the page ticks nothing: its form, sent as it stands, brings nothing", async () => { | |
| 271 | // A ticket link someone else forwards cannot put their notes on this account with one press. | |
| 272 | const noteId = insertNote(app.db, { appId, repoId, issueNumber: 1, visitor: `v:${"v" + "e".repeat(32)}`, name: "visitor-e" }).id; | |
| 273 | const carry = mintCarry(app.db, "v" + "e".repeat(32)); | |
| 274 | const { cookie } = await seeded("fern"); | |
| 275 | const page = await (await onForge(`/settings/bring?carry=${carry}`, cookie)).text(); | |
| 276 | const box = new RegExp(`<input type="checkbox" name="pick" value="${noteId}"[^>]*>`).exec(page)![0]; | |
| 277 | expect(box).not.toContain("checked"); | |
| 278 | // What a browser sends for that form untouched: the hidden ticket, no pick. | |
| 279 | const hidden = /<input type="hidden" name="carry" value="([0-9a-f]+)"/.exec(page)![1]!; | |
| 280 | const sent = await onForge("/settings/bring", cookie, new URLSearchParams({ carry: hidden })); | |
| 281 | expect(sent.status).toBe(303); | |
| 282 | expect(getNote(app.db, appId, noteId)!.visitor.startsWith("v:")).toBe(true); | |
| 283 | expect(carriedVisitor(app.db, carry)).toBeDefined(); | |
| 284 | }); | |
| 285 | ||
| 286 | test("the edge skips the passkey's fifteen minutes: it holds no forge cookie to steal and no sign-in time", async () => { | |
| 287 | const { user, sessionId } = await seeded("edna"); | |
| 288 | addPasskey(app.db, user.id, "phone", { id: "cred-edna", alg: "ES256", key: { kty: "EC", crv: "P-256", x: "AA", y: "AA" }, signCount: 0 }); | |
| 289 | const later = Date.now() + FRESH_MS + 60_000; | |
| 290 | // The edge signs each request itself (resolveAuth); the forge keeps no session for it, so a | |
| 291 | // freshness rule here would refuse every edge account with a passkey, and guard nothing. | |
| 292 | expect(mayBring(app, user, { via: "edge" }, later)).toEqual({ ok: true, value: true }); | |
| 293 | // The forge's own cookie, which can be stolen, is held to the fifteen minutes. | |
| 294 | expect(mayBring(app, user, { via: "session", sessionId }, later)).toEqual({ ok: false, error: "sign_in_again" }); | |
| 295 | }); | |
| 296 | ||
| 297 | test("a page lists the newest MADE_SHOWN and says more wait; none is dropped unsaid", () => { | |
| 298 | const visitor = "v" + "c".repeat(32); | |
| 299 | for (let i = 0; i <= MADE_SHOWN; i++) insertNote(app.db, { appId, repoId, issueNumber: 1, visitor: `v:${visitor}`, name: "visitor-c" }); | |
| 300 | const ticket = mintCarry(app.db, visitor); | |
| 301 | const listed = bringable(app, { carry: ticket, headers: new Headers() }); | |
| 302 | expect(listed.made.length).toBe(MADE_SHOWN); | |
| 303 | expect(listed.more).toBe(true); | |
| 304 | }); | |
| 305 | }); |
new above
offline
Unbounded mint per visitor: each call adds a row. Delete this visitor's earlier tickets in mintCarry so there is one live ticket each.