Public: anyone can read this; the crew can change it.
Access 5a: a visitor principal is minted only when a visitor creates something, signed, with a role in may() and per-visitor limits #18174
Merged 4h 19m ago, live in production
scout/forge:scout/18112-access-5a-a-visitor-principal-is-minted → main 0 commits fork 1 thread · 1 unresolved
15 files
changed +396
−314
- docs/ROLES.md
- docs/features/notes.md
- src/apps/feedback.ts
- src/core/may.ts
- src/core/principal.ts
- src/core/visitors.ts
- src/http/context.ts
- src/http/limits.ts
- src/http/server.ts
- test/apps-feedback.test.ts
- test/cookie-flags.test.ts
- test/cookie-floor.test.ts
- test/cookie-secure.test.ts
- test/may.test.ts
- test/visitors.test.ts
docs/ROLES.md +11 −3
| @@ -6,13 +6,21 @@ Two words that sound alike are two different people, so each has one meaning: | ||
| 6 | 6 | |
| 7 | 7 | | Word | Who | Has an account | Where it is held | |
| 8 | 8 | | --- | --- | --- | --- | |
| 9 | | visitor | Anyone who has not signed in, or whose credential matched nothing | no | `Principal` kind `anonymous` (`src/core/principal.ts`) | | |
| 9 | | visitor | Anyone who has not signed in, or whose credential matched nothing | no | `Principal` kind `anonymous`, or `visitor` once they have made something (`src/core/principal.ts`) | | |
| 10 | 10 | | guest | A signed-in account that is not a member | yes | role `guest` below | |
| 11 | 11 | | member | A signed-in account with a `member` row | yes | role `member` below | |
| 12 | 12 | | admin | A signed-in account with the `is_admin` flag | yes | role `admin` below | |
| 13 | 13 | |
| 14 | A visitor is not a role: nothing is stored for one. `principalOf(auth)` builds | |
| 15 | who is asking from today's `Auth`: `anonymous` (a visitor), `session` (the | |
| 14 | A visitor has no account and is never a user. Nothing is stored for one until | |
| 15 | they make something (a note on an app's page): then, and only then, the forge | |
| 16 | mints a signed visitor id in its own `forge_maker` cookie (`src/core/visitors.ts`), | |
| 17 | never the analytics `forge_visitor` id, and none at all when the browser sends | |
| 18 | `DNT: 1` or `Sec-GPC: 1`. A request carrying it is the principal `visitor`, which | |
| 19 | may do what anonymous may plus `visitor.make`, at most 200 things a day per | |
| 20 | visitor, 200 per connection (so one client dropping its cookie cannot spend the rest) and | |
| 21 | 5000 a day for all visitors together (`VISITOR_CAPS` in | |
| 22 | `src/http/limits.ts`). `principalOf(auth)` builds | |
| 23 | who is asking from today's `Auth`: `anonymous` (a visitor), `visitor`, `session` (the | |
| 16 | 24 | account itself), one of the token kinds (`ro_token`, `rw_token`, |
| 17 | 25 | `admin_token`, `proposal_token`, `run_token`, `contribute_token`, |
| 18 | 26 | `read_grant_token`, `via_token`), each with a subject (a person, an agent or an |
docs/features/notes.md +4
| @@ -35,6 +35,10 @@ A note sent from an app's forge button (or the terminal's "Tell the builders") f | ||
| 35 | 35 | |
| 36 | 36 | The issue also carries a closed fold, "Context" (`actions/note_context.ts`): the page (as a `Page:` line), the viewport, the build the app was serving and up to five recent console errors from the sender's page, each cut to 200 characters and scrubbed of anything shaped like a secret or a URL query. The `Source:` line above the fold names the app and environment. Markdown accepts one flat fold (`<details><summary>Title</summary>` … `</details>`, each on its own line, a title of plain characters); an unclosed one is closed, a nested one is text. |
| 37 | 37 | |
| 38 | A visitor with no account is known only once they send a note: that answer, and nothing before it, sets a signed `forge_maker` cookie on the app's host (`src/core/visitors.ts`), never the analytics `forge_visitor` id. Opening the button's list mints nothing; a visitor who has sent nothing sees an empty list. With `DNT: 1` or `Sec-GPC: 1` the note is still filed and no id is kept, so the list stays empty. A visitor may send at most 200 notes a day, one connection at most 200 whatever cookie it holds, and all visitors together 5000 (`VISITOR_CAPS`); past any of them the answer is 429, and only a note that was filed counts. A client that drops its cookie gets a fresh id with each note, so the visitor's cap never binds it: the per-connection cap is what does, and keeps one client from spending the forge's 5000 and refusing everyone else. | |
| 39 | ||
| 40 | A visitor who sent notes before this change holds only the old unsigned `forge_visitor` note cookie. It is not a visitor principal, so their list shows none of those notes; the notes themselves are filed and unchanged on the builders' side, and the next note they send starts a list of their own. In the terminal the sender is always the SSH user, so none of this applies there. | |
| 41 | ||
| 38 | 42 | The crew's answers come back to the sender: under each note the button's list (and the terminal's "Notes from the app", where picking a note shows them) carries the comments on its issue by the repository's crew and writers, with author and time, oldest first. Anyone else's comments stay on the forge. The button shows the latest five and says how many are earlier. |
| 39 | 43 | |
| 40 | 44 | The app's admin reads the same replies through MCP `app_notes` and |
src/apps/feedback.ts +32 −37
| @@ -16,7 +16,6 @@ | ||
| 16 | 16 | * keyed on the socket's client (`http/peer.ts`), never on a header the |
| 17 | 17 | * client wrote. |
| 18 | 18 | */ |
| 19 | import { setCookie } from "../auth/cookies.ts"; | |
| 20 | 19 | import { randomBytes } from "node:crypto"; |
| 21 | 20 | import type { App } from "../app.ts"; |
| 22 | 21 | import { notesFor, sendNote, type Sender } from "../actions/app_notes.ts"; |
| @@ -26,12 +25,13 @@ import { getNote } from "../core/app_notes.ts"; | ||
| 26 | 25 | import { PICTURE_MAX, savePicture, sniffPicture } from "../core/note_pictures.ts"; |
| 27 | 26 | import { getUserById, isActive, type User } from "../core/users.ts"; |
| 28 | 27 | import { sha256 } from "../kernel/hash.ts"; |
| 28 | import { loadKey } from "../kernel/secret.ts"; | |
| 29 | import { admitVisitor, countMake, heldVisitor } from "../core/visitors.ts"; | |
| 29 | 30 | import { parseNoteContext } from "../actions/note_context.ts"; |
| 30 | 31 | import { NOTE_FAILED } from "./note_words.ts"; |
| 31 | 32 | import { commentOnPull } from "./pull_comment.ts"; |
| 32 | 33 | |
| 33 | 34 | export const REQUEST_MAX = 16 * 1024; |
| 34 | export const VISITOR_COOKIE = "forge_visitor"; | |
| 35 | 35 | |
| 36 | 36 | export interface FeedbackAsk { |
| 37 | 37 | readonly app: App; |
| @@ -59,14 +59,6 @@ const json = (status: number, body: unknown, headers: Record<string, string> = { | ||
| 59 | 59 | headers: { "cache-control": "no-store", "x-content-type-options": "nosniff", ...headers }, |
| 60 | 60 | }); |
| 61 | 61 | |
| 62 | function cookieOf(request: Request, name: string): string | undefined { | |
| 63 | for (const part of (request.headers.get("cookie") ?? "").split(";")) { | |
| 64 | const at = part.indexOf("="); | |
| 65 | if (at !== -1 && part.slice(0, at).trim() === name) return part.slice(at + 1).trim(); | |
| 66 | } | |
| 67 | return undefined; | |
| 68 | } | |
| 69 | ||
| 70 | 62 | /** Same origin only: the Origin header names this very host. */ |
| 71 | 63 | function sameOrigin(request: Request): boolean { |
| 72 | 64 | const origin = request.headers.get("origin"); |
| @@ -177,21 +169,17 @@ export function spendProof(token: string | null, grantCookie: string | undefined | ||
| 177 | 169 | return spent!.expires > now; |
| 178 | 170 | } |
| 179 | 171 | |
| 180 | /** The sender: a person's key and name, or the anonymous cookie's. */ | |
| 181 | function senderOf(ask: FeedbackAsk, door: Door): { sender: Sender; fresh?: string } { | |
| 182 | if (door.viewer !== undefined) | |
| 183 | return { sender: { key: `u:${door.viewer.id}`, name: `@${door.viewer.username}`, person: true } }; | |
| 184 | const have = cookieOf(ask.request, VISITOR_COOKIE); | |
| 185 | const cookie = have !== undefined && /^[0-9a-f]{32}$/.test(have) ? have : undefined; | |
| 186 | const value = cookie ?? randomBytes(16).toString("hex"); | |
| 187 | return { | |
| 188 | sender: { key: `v:${value}`, name: `visitor-${sha256(value).slice(0, 6)}`, person: false }, | |
| 189 | ...(cookie === undefined ? { fresh: value } : {}), | |
| 190 | }; | |
| 191 | } | |
| 172 | const senderOfVisitor = (id: string): Sender => ({ key: `v:${id}`, name: `visitor-${sha256(id).slice(0, 6)}`, person: false }); | |
| 192 | 173 | |
| 193 | const visitorCookie = (value: string, secure: boolean): string => | |
| 194 | setCookie(VISITOR_COOKIE, value, { maxAge: 31536000, secure }); | |
| 174 | /** | |
| 175 | * The sender as far as a read or a picture knows: a person, or the visitor principal the request | |
| 176 | * holds (`core/visitors.ts`). Mints nothing; undefined for a visitor who has made nothing here yet. | |
| 177 | */ | |
| 178 | function heldSender(ask: FeedbackAsk, door: Door): Sender | undefined { | |
| 179 | if (door.viewer !== undefined) return { key: `u:${door.viewer.id}`, name: `@${door.viewer.username}`, person: true }; | |
| 180 | const held = heldVisitor(ask.request.headers, () => loadKey(ask.app.config.dataDir)); | |
| 181 | return held === undefined ? undefined : senderOfVisitor(held); | |
| 182 | } | |
| 195 | 183 | |
| 196 | 184 | /** The body as JSON, read no further than `REQUEST_MAX` bytes whatever it declares. */ |
| 197 | 185 | async function readJson(request: Request): Promise<Record<string, unknown> | undefined> { |
| @@ -244,8 +232,14 @@ async function send(ask: FeedbackAsk, door: Door): Promise<Response> { | ||
| 244 | 232 | const { request } = ask; |
| 245 | 233 | const body = await readJson(request); |
| 246 | 234 | if (body === undefined) return json(400, { error: "bad_request", message: NOTE_FAILED }); |
| 247 | const { sender, fresh } = senderOf(ask, door); | |
| 248 | const cookies = fresh === undefined ? {} : { "set-cookie": visitorCookie(fresh, ask.secure) }; | |
| 235 | // A visitor with no account is admitted, and minted an id only now that they make a note. | |
| 236 | const admitted = | |
| 237 | door.viewer === undefined ? admitVisitor(ask.app.db, () => loadKey(ask.app.config.dataDir), { headers: request.headers, secure: ask.secure, client: ask.source }) : undefined; | |
| 238 | if (admitted !== undefined && !admitted.ok) return json(admitted.status, { error: admitted.status === 429 ? "rate_limited" : "forbidden", message: admitted.says }); | |
| 239 | const sender = | |
| 240 | admitted === undefined | |
| 241 | ? heldSender(ask, door)! | |
| 242 | : senderOfVisitor(admitted.visitorId ?? `once-${randomBytes(16).toString("hex")}`); | |
| 249 | 243 | // The sender took the context off: only their words go. |
| 250 | 244 | const bare = body.bare === true; |
| 251 | 245 | const page = bare ? "" : pageOf(body.page, request.headers.get("host"), new URL(request.url).origin); |
| @@ -266,11 +260,11 @@ async function send(ask: FeedbackAsk, door: Door): Promise<Response> { | ||
| 266 | 260 | const r = sent.error; |
| 267 | 261 | const status = { empty: 400, too_long: 400, banned: 403, filtered: 422, rate_limited: 429, unavailable: 503 }[r.error]; |
| 268 | 262 | return json(status, { error: r.error, message: r.message }, { |
| 269 | ...cookies, | |
| 270 | 263 | ...(r.retryAfter === undefined ? {} : { "retry-after": String(r.retryAfter) }), |
| 271 | 264 | }); |
| 272 | 265 | } |
| 273 | return json(201, { note: sent.value, name: sender.name }, cookies); | |
| 266 | if (admitted !== undefined) countMake(ask.app.db, admitted.visitorId, ask.source); | |
| 267 | return json(201, { note: sent.value, name: sender.name }, admitted?.setCookie === undefined ? {} : { "set-cookie": admitted.setCookie }); | |
| 274 | 268 | } |
| 275 | 269 | |
| 276 | 270 | /** The body's bytes, read no further than `PICTURE_MAX`; `undefined` when it is longer. */ |
| @@ -294,11 +288,11 @@ async function readPicture(request: Request): Promise<Uint8Array | undefined> { | ||
| 294 | 288 | } |
| 295 | 289 | |
| 296 | 290 | async function picture(ask: FeedbackAsk, door: Door): Promise<Response> { |
| 297 | const { sender } = senderOf(ask, door); | |
| 291 | const sender = heldSender(ask, door); | |
| 298 | 292 | const asked = ask.url.searchParams.get("note") ?? ""; |
| 299 | 293 | const note = /^[0-9a-z]{10,40}$/.test(asked) ? getNote(ask.app.db, ask.record.id, asked) : undefined; |
| 300 | 294 | // Only the sender's own note takes a picture. |
| 301 | if (note === undefined || note.visitor !== sender.key || note.hidden) return json(404, { error: "not_found" }); | |
| 295 | if (note === undefined || sender === undefined || note.visitor !== sender.key || note.hidden) return json(404, { error: "not_found" }); | |
| 302 | 296 | const bytes = await readPicture(ask.request); |
| 303 | 297 | if (bytes === undefined) return json(413, { error: "too_large", message: "That picture is too big. It must be under 2 MB." }); |
| 304 | 298 | const kind = sniffPicture(bytes); |
| @@ -309,13 +303,14 @@ async function picture(ask: FeedbackAsk, door: Door): Promise<Response> { | ||
| 309 | 303 | } |
| 310 | 304 | |
| 311 | 305 | function list(ask: FeedbackAsk, door: Door, proven: boolean): Response { |
| 312 | const { sender, fresh } = senderOf(ask, door); | |
| 313 | const notes = notesFor(ask.app, ask.record, door.repo, ask.forgeUrl, sender, false, door.viewer); | |
| 314 | return json( | |
| 315 | 200, | |
| 316 | { name: sender.name, notes, admin: proven && door.viewer !== undefined && canAdmin(ask.app.db, door.repo, door.viewer) }, | |
| 317 | fresh === undefined ? {} : { "set-cookie": visitorCookie(fresh, ask.secure) }, | |
| 318 | ); | |
| 306 | // A read: a visitor who has made nothing has no id and no notes, and is given none. | |
| 307 | const sender = heldSender(ask, door); | |
| 308 | const notes = sender === undefined ? [] : notesFor(ask.app, ask.record, door.repo, ask.forgeUrl, sender, false, door.viewer); | |
| 309 | return json(200, { | |
| 310 | name: sender?.name ?? "visitor", | |
| 311 | notes, | |
| 312 | admin: proven && door.viewer !== undefined && canAdmin(ask.app.db, door.repo, door.viewer), | |
| 313 | }); | |
| 319 | 314 | } |
| 320 | 315 | |
| 321 | 316 | /** Answer a `/__forge/note*` request; `undefined` when the path is not one. */ |
src/core/may.ts +7
| @@ -50,6 +50,11 @@ export const ACTIONS = { | ||
| 50 | 50 | "forge.make_it_yours": forgeAction("make_it_yours"), |
| 51 | 51 | "forge.run_crew": forgeAction("run_crew"), |
| 52 | 52 | "forge.administer": forgeAction("administer"), |
| 53 | "visitor.make": { | |
| 54 | says: "Make something without an account: a note on an app's page", | |
| 55 | over: "forge", | |
| 56 | scope: "rw", | |
| 57 | }, | |
| 53 | 58 | "account.manage": { says: "Change your own account: password, profile and tokens, as yourself and not by a token", over: "forge", scope: "ro" }, |
| 54 | 59 | } as const satisfies Record<string, ActionRow>; |
| 55 | 60 | export type Action = keyof typeof ACTIONS; |
| @@ -93,6 +98,8 @@ function repoRuleHolds(db: Database, action: Action, repo: Repo, user: User | un | ||
| 93 | 98 | function forgeRuleHolds(db: Database, action: Action, p: Principal): boolean { |
| 94 | 99 | const ability = ABILITY_OF[action]; |
| 95 | 100 | if (ability === "read") return true; |
| 101 | // A visitor role: no account, nothing refused, or one already minted (`core/visitors.ts`). | |
| 102 | if (action === "visitor.make") return p.kind === "visitor" || (p.kind === "anonymous" && !p.refused); | |
| 96 | 103 | const user = userOf(p); |
| 97 | 104 | if (user === undefined) return false; |
| 98 | 105 | if (ability === "administer") return user.isAdmin; |
src/core/principal.ts +13 −3
| @@ -29,6 +29,15 @@ export interface Anonymous { | ||
| 29 | 29 | readonly retryAfter?: number; |
| 30 | 30 | } |
| 31 | 31 | |
| 32 | /** | |
| 33 | * A visitor with no account who has made something (`core/visitors.ts`): known by a signed id, | |
| 34 | * never a user, and never the analytics visitor (`perf/visitor_id.ts`). | |
| 35 | */ | |
| 36 | export interface VisitorPrincipal { | |
| 37 | readonly kind: "visitor"; | |
| 38 | readonly visitorId: string; | |
| 39 | } | |
| 40 | ||
| 32 | 41 | /** The account itself: a session cookie, the platform edge or the password. */ |
| 33 | 42 | export interface SessionPrincipal { |
| 34 | 43 | readonly kind: "session"; |
| @@ -57,7 +66,7 @@ export type TokenPrincipal = | ||
| 57 | 66 | /** The forge's own agent speaking for this person in one conversation. */ |
| 58 | 67 | | (TokenBase & { readonly kind: "via_token"; readonly through: string }); |
| 59 | 68 | |
| 60 | export type Principal = Anonymous | SessionPrincipal | TokenPrincipal; | |
| 69 | export type Principal = Anonymous | VisitorPrincipal | SessionPrincipal | TokenPrincipal; | |
| 61 | 70 | export type PrincipalKind = Principal["kind"]; |
| 62 | 71 | |
| 63 | 72 | function subjectOf(user: User, appId: string | undefined): Subject { |
| @@ -73,6 +82,7 @@ function subjectOf(user: User, appId: string | undefined): Subject { | ||
| 73 | 82 | export function principalOf(auth: Auth): Principal { |
| 74 | 83 | const user = auth.user; |
| 75 | 84 | if (user === undefined) { |
| 85 | if (auth.visitorId !== undefined && auth.refused !== true) return { kind: "visitor", visitorId: auth.visitorId }; | |
| 76 | 86 | return { |
| 77 | 87 | kind: "anonymous", |
| 78 | 88 | refused: auth.refused === true, |
| @@ -106,8 +116,8 @@ export function principalOfUser(user: User | undefined, via: SessionPrincipal["v | ||
| 106 | 116 | return principalOf({ user, scope: undefined, via }); |
| 107 | 117 | } |
| 108 | 118 | |
| 109 | /** The account behind a principal, when there is one: none for anonymous. */ | |
| 119 | /** The account behind a principal, when there is one: none for anonymous or a visitor. */ | |
| 110 | 120 | export function userOf(principal: Principal): User | undefined { |
| 111 | if (principal.kind === "anonymous") return undefined; | |
| 121 | if (principal.kind === "anonymous" || principal.kind === "visitor") return undefined; | |
| 112 | 122 | return principal.subject.user; |
| 113 | 123 | } |
src/core/visitors.ts added +141
| @@ -0,0 +1,141 @@ | ||
| 1 | /** | |
| 2 | * A visitor principal (#18112): someone with no account the forge knows, minted only at the moment | |
| 3 | * they make something (a note on an app's page), never on a | |
| 4 | * read. Only notes mint today (`apps/feedback.ts`); the shared app (#18188) and the game | |
| 5 | * player (#18189) follow. The id rides its own cookie, `forge_maker`, signed with a key derived for | |
| 6 | * this purpose alone (HKDF, "forge visitor principal v1"), so the analytics cookie | |
| 7 | * (`perf/visitor_id.ts`, `forge_visitor`) can never verify here and is never joined to it: the two | |
| 8 | * share no id, no key and no table. `Sec-GPC: 1` or `DNT: 1` mints nothing, as the analytics side | |
| 9 | * does. | |
| 10 | * | |
| 11 | * A visitor is not a user: `userOf` answers none for it, and `may` (`core/may.ts`) lets it do | |
| 12 | * exactly what anonymous may plus `visitor.make`, within `VISITOR_CAPS` (`http/limits.ts`). | |
| 13 | */ | |
| 14 | ||
| 15 | import type { Database } from "bun:sqlite"; | |
| 16 | import { createHmac, hkdfSync, timingSafeEqual } from "node:crypto"; | |
| 17 | import { setCookie } from "../auth/cookies.ts"; | |
| 18 | import { VISITOR_CAPS } from "../http/limits.ts"; | |
| 19 | import { refusesTracking } from "../perf/visitor_id.ts"; | |
| 20 | import { holds } from "./may.ts"; | |
| 21 | import type { Principal } from "./principal.ts"; | |
| 22 | ||
| 23 | const MAKER_COOKIE = "forge_maker"; | |
| 24 | /** A year, in seconds: what one made is theirs to come back to. */ | |
| 25 | const MAKER_MAX_AGE = 365 * 86_400; | |
| 26 | const DAY_MS = 86_400_000; | |
| 27 | /** `v<128 random bits in hex>.<32 hex of the HMAC>`; the analytics id starts with `c`. */ | |
| 28 | const MAKER_VALUE = /^v[0-9a-f]{32}\.[0-9a-f]{32}$/; | |
| 29 | ||
| 30 | const made = new WeakSet<Database>(); | |
| 31 | function table(db: Database): void { | |
| 32 | if (made.has(db)) return; | |
| 33 | // One row per thing a visitor made: the counts are the caps', the id is the principal's, and the | |
| 34 | // client is the socket's limit key (`clientBucket`), never a header the client wrote. | |
| 35 | db.run(`CREATE TABLE IF NOT EXISTS visitor_made ( | |
| 36 | visitor_id TEXT NOT NULL, | |
| 37 | client TEXT NOT NULL, | |
| 38 | at INTEGER NOT NULL | |
| 39 | )`); | |
| 40 | db.run("CREATE INDEX IF NOT EXISTS visitor_made_by ON visitor_made (visitor_id, at)"); | |
| 41 | db.run("CREATE INDEX IF NOT EXISTS visitor_made_client ON visitor_made (client, at)"); | |
| 42 | db.run("CREATE INDEX IF NOT EXISTS visitor_made_at ON visitor_made (at)"); | |
| 43 | made.add(db); | |
| 44 | } | |
| 45 | ||
| 46 | /** The signing key: derived from the forge's secret for this purpose only. */ | |
| 47 | const signer = (secret: Uint8Array): Buffer => Buffer.from(hkdfSync("sha256", secret, "", "forge visitor principal v1", 32)); | |
| 48 | ||
| 49 | const macOf = (secret: Uint8Array, id: string): string => | |
| 50 | createHmac("sha256", signer(secret)).update(`visitor-principal\0${id}`).digest("hex").slice(0, 32); | |
| 51 | ||
| 52 | /** | |
| 53 | * The visitor id a cookie value carries, only when this forge signed it for a visitor principal. | |
| 54 | */ | |
| 55 | function verifyVisitor(value: string | undefined, secret: Uint8Array | (() => Uint8Array)): string | undefined { | |
| 56 | if (value === undefined || !MAKER_VALUE.test(value)) return undefined; | |
| 57 | const [id, mac] = value.split(".") as [string, string]; | |
| 58 | const key = typeof secret === "function" ? secret() : secret; | |
| 59 | return timingSafeEqual(Buffer.from(mac), Buffer.from(macOf(key, id))) ? id : undefined; | |
| 60 | } | |
| 61 | ||
| 62 | /** | |
| 63 | * The visitor id a request's `forge_maker` cookie carries, when this forge signed it. A read: mints | |
| 64 | * nothing. The secret may be a thunk, read only when such a cookie is there: every request with no | |
| 65 | * credential asks, and none of them should touch the key file. | |
| 66 | */ | |
| 67 | export function heldVisitor(headers: Headers, secret: Uint8Array | (() => Uint8Array)): string | undefined { | |
| 68 | for (const pair of (headers.get("cookie") ?? "").split(";")) { | |
| 69 | const eq = pair.indexOf("="); | |
| 70 | if (eq !== -1 && pair.slice(0, eq).trim() === MAKER_COOKIE) return verifyVisitor(pair.slice(eq + 1).trim(), secret); | |
| 71 | } | |
| 72 | return undefined; | |
| 73 | } | |
| 74 | ||
| 75 | export type Admission = | |
| 76 | | { | |
| 77 | readonly ok: true; | |
| 78 | /** Undefined when the browser refuses tracking: the thing is made, and no id is kept. */ | |
| 79 | readonly visitorId: string | undefined; | |
| 80 | /** The cookie line of an id minted now; send it only once the thing is made. */ | |
| 81 | readonly setCookie: string | undefined; | |
| 82 | } | |
| 83 | | { readonly ok: false; readonly status: 403 | 429; readonly says: string }; | |
| 84 | ||
| 85 | const REFUSED_WORDS = "Sign in to make this."; | |
| 86 | const VISITOR_FULL = `A visitor may make ${VISITOR_CAPS.perVisitor.perDay} things a day; sign in to make more.`; | |
| 87 | const CLIENT_FULL = `One connection may make ${VISITOR_CAPS.perClient.perDay} things a day as a visitor; sign in to make more.`; | |
| 88 | const FORGE_FULL = "This forge has taken all it takes from visitors today; sign in, or try tomorrow."; | |
| 89 | ||
| 90 | /** | |
| 91 | * Whether a visitor with no account may make one thing now, and as whom: the id their request | |
| 92 | * holds, or one minted now (none when `Sec-GPC: 1` or `DNT: 1`). Asks `may` for `visitor.make`, | |
| 93 | * then the caps: the forge's, the client's (so one connection dropping its cookie cannot spend the | |
| 94 | * forge's alone) and the visitor's. The secret may be a thunk, read only to verify or mint. Stores | |
| 95 | * nothing: `countMake` records the thing once it is made. | |
| 96 | */ | |
| 97 | export function admitVisitor( | |
| 98 | db: Database, | |
| 99 | secret: Uint8Array | (() => Uint8Array), | |
| 100 | request: { readonly headers: Headers; readonly secure: boolean; readonly client: string }, | |
| 101 | at: number = Date.now(), | |
| 102 | ): Admission { | |
| 103 | const held = heldVisitor(request.headers, secret); | |
| 104 | const p: Principal = held === undefined ? { kind: "anonymous", refused: false } : { kind: "visitor", visitorId: held }; | |
| 105 | if (!holds(db, p, "visitor.make")) return { ok: false, status: 403, says: REFUSED_WORDS }; | |
| 106 | table(db); | |
| 107 | const since = at - DAY_MS; | |
| 108 | const forge = db.query<{ n: number }, [number]>("SELECT count(*) AS n FROM visitor_made WHERE at > ?").get(since)!.n; | |
| 109 | if (forge >= VISITOR_CAPS.perForge.perDay) return { ok: false, status: 429, says: FORGE_FULL }; | |
| 110 | const client = db | |
| 111 | .query<{ n: number }, [string, number]>("SELECT count(*) AS n FROM visitor_made WHERE client = ? AND at > ?") | |
| 112 | .get(request.client, since)!.n; | |
| 113 | if (client >= VISITOR_CAPS.perClient.perDay) return { ok: false, status: 429, says: CLIENT_FULL }; | |
| 114 | if (held !== undefined) { | |
| 115 | const mine = db | |
| 116 | .query<{ n: number }, [string, number]>("SELECT count(*) AS n FROM visitor_made WHERE visitor_id = ? AND at > ?") | |
| 117 | .get(held, since)!.n; | |
| 118 | if (mine >= VISITOR_CAPS.perVisitor.perDay) return { ok: false, status: 429, says: VISITOR_FULL }; | |
| 119 | return { ok: true, visitorId: held, setCookie: undefined }; | |
| 120 | } | |
| 121 | if (refusesTracking(request.headers)) return { ok: true, visitorId: undefined, setCookie: undefined }; | |
| 122 | const minted = mint(typeof secret === "function" ? secret() : secret); | |
| 123 | const line = setCookie(MAKER_COOKIE, minted.value, { maxAge: MAKER_MAX_AGE, secure: request.secure }); | |
| 124 | return { ok: true, visitorId: minted.id, setCookie: line }; | |
| 125 | } | |
| 126 | ||
| 127 | /** | |
| 128 | * One thing a visitor made, counted against `VISITOR_CAPS` once it is made, never on a refusal; a | |
| 129 | * visitor who refused tracking counts for the forge and the client only. | |
| 130 | */ | |
| 131 | export function countMake(db: Database, visitorId: string | undefined, client: string, at: number = Date.now()): void { | |
| 132 | table(db); | |
| 133 | db.run("INSERT INTO visitor_made (visitor_id, client, at) VALUES (?, ?, ?)", [visitorId ?? "", client, at]); | |
| 134 | db.run("DELETE FROM visitor_made WHERE at <= ?", [at - 30 * DAY_MS]); | |
| 135 | } | |
| 136 | ||
| 137 | function mint(secret: Uint8Array): { readonly id: string; readonly value: string } { | |
| 138 | const bytes = crypto.getRandomValues(new Uint8Array(16)); | |
| 139 | const id = `v${Buffer.from(bytes).toString("hex")}`; | |
| 140 | return { id, value: `${id}.${macOf(secret, id)}` }; | |
| 141 | } |
src/http/context.ts +5
| @@ -50,6 +50,11 @@ export interface Auth { | ||
| 50 | 50 | readonly retryAfter?: number; |
| 51 | 51 | /** Set when a bearer or basic credential was sent and matched nothing. */ |
| 52 | 52 | readonly refused?: true; |
| 53 | /** | |
| 54 | * Set for no account but a signed `forge_maker` cookie: a visitor who made something | |
| 55 | * (`core/visitors.ts`). Never set beside `user`. | |
| 56 | */ | |
| 57 | readonly visitorId?: string; | |
| 53 | 58 | } |
| 54 | 59 | |
| 55 | 60 | /** |
src/http/limits.ts +11
| @@ -59,6 +59,17 @@ export const RATE_CAPS = { | ||
| 59 | 59 | }, |
| 60 | 60 | } as const satisfies Record<string, { perClient: number; perForge: number; reason: string }>; |
| 61 | 61 | |
| 62 | /** | |
| 63 | * What a visitor with no account may make (`core/visitors.ts`, #18112), counted over the last day: | |
| 64 | * by one visitor id, by one connection (`clientBucket`), so dropping the cookie to mint new ids | |
| 65 | * gets round neither, and by every visitor of this forge together. | |
| 66 | */ | |
| 67 | export const VISITOR_CAPS = { | |
| 68 | perVisitor: { perDay: 200, reason: "twice what one app takes in a day (`PER_APP_DAY`), so an app's own bound speaks first; a person makes a handful" }, | |
| 69 | perClient: { perDay: 200, reason: "one connection (`clientBucket`) dropping its cookie mints a fresh id each time, so the visitor's cap never binds it; this one does, and keeps one client from spending the forge's cap alone" }, | |
| 70 | perForge: { perDay: 5000, reason: "every visitor together, fifty apps' worth of notes; past it, signing in is the way to make more" }, | |
| 71 | } as const; | |
| 72 | ||
| 62 | 73 | const closing = new WeakSet<Request>(); |
| 63 | 74 | const signedIn = new WeakSet<Request>(); |
| 64 | 75 |
src/http/server.ts +6 −1
| @@ -99,6 +99,8 @@ import { isProbe } from "../kernel/probe.ts"; | ||
| 99 | 99 | import { takeStrangerRead } from "./stranger_reads.ts"; |
| 100 | 100 | import { parseCidrs } from "../kernel/cidr.ts"; |
| 101 | 101 | import { cookieValue, publicUrl, type Auth, type Ctx, type Handler, parsable } from "./context.ts"; |
| 102 | import { heldVisitor } from "../core/visitors.ts"; | |
| 103 | import { loadKey } from "../kernel/secret.ts"; | |
| 102 | 104 | import { apiError, json, methodNotAllowed, noRoute, pageNotFoundAsJson, prefersHtml, prefersJson, asksForPage, securityFloor, stampConfig, BodyTooLarge, bodyTooLarge, invalidJson, privateWhenSignedIn, tooManyAttempts, tryAgain } from "./respond.ts"; |
| 103 | 105 | import { compress } from "./compress.ts"; |
| 104 | 106 | import { headOf, optionsAnswer } from "./head.ts"; |
| @@ -159,7 +161,10 @@ export async function resolveAuth(app: App, request: Request): Promise<Auth> { | ||
| 159 | 161 | } |
| 160 | 162 | |
| 161 | 163 | const header = request.headers.get("authorization"); |
| 162 | if (!header) return NO_AUTH; | |
| 164 | if (!header) { | |
| 165 | const visitorId = heldVisitor(request.headers, () => loadKey(app.config.dataDir)); | |
| 166 | return visitorId === undefined ? NO_AUTH : { ...NO_AUTH, visitorId }; | |
| 167 | } | |
| 163 | 168 | |
| 164 | 169 | // Bearer is always a token; so is `token <secret>`, the scheme a Gitea |
| 165 | 170 | // client sends — another forge connecting to this one as an origin. |
test/apps-feedback.test.ts +16 −2
| @@ -25,6 +25,7 @@ import { createUser, type User } from "../src/core/users.ts"; | ||
| 25 | 25 | import { serve, type Servers } from "../src/http/server.ts"; |
| 26 | 26 | import { taskPrompt, type TaskInput } from "../src/crew/brief.ts"; |
| 27 | 27 | import { quietLogs } from "./helpers/globals.ts"; |
| 28 | import * as secret from "../src/kernel/secret.ts"; | |
| 28 | 29 | import { LOOPBACK_PROXIES } from "./helpers/loopback-proxy.ts"; |
| 29 | 30 | |
| 30 | 31 | quietLogs(); |
| @@ -204,6 +205,18 @@ describe("the forge button takes notes from anyone", () => { | ||
| 204 | 205 | expect(other.notes).toEqual([]); |
| 205 | 206 | }); |
| 206 | 207 | |
| 208 | test("a list read with no maker cookie never reads the key file, so a bad key cannot fail it", async () => { | |
| 209 | const reads = spyOn(secret, "loadKey"); | |
| 210 | try { | |
| 211 | const res = await at("notes", "/__forge/notes", {}, "forge_visitor=" + "a".repeat(32)); | |
| 212 | expect(res.status).toBe(200); | |
| 213 | expect(((await res.json()) as { notes: unknown[] }).notes).toEqual([]); | |
| 214 | expect(reads).not.toHaveBeenCalled(); | |
| 215 | } finally { | |
| 216 | reads.mockRestore(); | |
| 217 | } | |
| 218 | }); | |
| 219 | ||
| 207 | 220 | test("only a finished note reads as shipped; the others say what they are", async () => { |
| 208 | 221 | const repo = getRepo(app.db, "alice", "notes")!; |
| 209 | 222 | for (const [reason, label] of [["dropped", /^Closed without a change/], ["parked", /^Set aside/], ["split", /^Split into/], ["done", /^Shipped on/]] as const) { |
| @@ -559,7 +572,8 @@ describe("the forge button takes notes from anyone", () => { | ||
| 559 | 572 | expect(((await bare.json()) as { name: string }).name).toMatch(/^visitor-/); |
| 560 | 573 | expect(bare.headers.get("x-forge-proof")).toBeNull(); |
| 561 | 574 | const seen = await list(owner); |
| 562 | expect(seen.name).toMatch(/^visitor-/); | |
| 575 | // The list is a read: it names a visitor and mints no id for one (#18112). | |
| 576 | expect(seen.name).toMatch(/^visitor/); | |
| 563 | 577 | expect(seen.admin).toBe(false); |
| 564 | 578 | |
| 565 | 579 | // Proven: @alice, the list is theirs, and the answer carries the next token. |
| @@ -585,7 +599,7 @@ describe("the forge button takes notes from anyone", () => { | ||
| 585 | 599 | if (!bob.ok) throw new Error(bob.error); |
| 586 | 600 | const bobs = await grantedCookie(app, servers.url, bob.value, record); |
| 587 | 601 | const foreignGrant = await page("notes", owner); |
| 588 | expect((await list(bobs, foreignGrant.proof)).name).toMatch(/^visitor-/); | |
| 602 | expect((await list(bobs, foreignGrant.proof)).name).toMatch(/^visitor/); | |
| 589 | 603 | const foreignHost = await page("notes", owner); |
| 590 | 604 | const onOther = await at("diary", "/__forge/notes", { headers: withProof(foreignHost.proof) }, await grantedCookie(app, servers.url, alice, getAppBySlug(app.db, "diary")!)); |
| 591 | 605 | expect(onOther.status).toBe(404); |
test/cookie-flags.test.ts +6 −6
| @@ -64,7 +64,7 @@ const COOKIES: Record<string, Spelled> = { | ||
| 64 | 64 | }, |
| 65 | 65 | "src/apps/proxy.ts grantCookieName(target)": { name: /^forge_grant_[0-9a-z]{8}$/, lines: 2, door: "app grant" }, |
| 66 | 66 | "src/apps/proxy.ts HIDE_COOKIE": { name: "forge-toolbar-hidden", lines: 1, why: "set by a same-origin POST to the toolbar door, tested in test/toolbar-hide.test.ts; HttpOnly, Lax, Secure over https" }, |
| 67 | "src/apps/feedback.ts VISITOR_COOKIE": { name: "forge_visitor", lines: 1, door: "app note" }, | |
| 67 | "src/core/visitors.ts MAKER_COOKIE": { name: "forge_maker", lines: 1, door: "app note" }, | |
| 68 | 68 | "src/perf/visitor_id.ts COOKIE": { name: "forge_visitor", lines: 1, door: "page-view beacon" }, |
| 69 | 69 | "src/web/studio/share_receive.ts STASH_COOKIE": { name: "forge_share", lines: 2, why: "set by a same-origin POST /tell/share and cleared on the GET that reads it; HttpOnly, Lax, Secure over https; tested in test/share-target.test.ts" }, |
| 70 | 70 | "src/web/gift_cookie.ts NAME": { name: "forge_gift", lines: 2, door: "gift link" }, |
| @@ -112,7 +112,7 @@ const WALKED: Record<string, number> = { | ||
| 112 | 112 | "src/http/session_renewal.ts": 1, // a renewed session re-set on a page read |
| 113 | 113 | "src/http/rp.ts": 6, // parent sign-in and link: state cookie set and cleared |
| 114 | 114 | "src/apps/proxy.ts": 3, // app grant, app sign-out, toolbar dismissal |
| 115 | "src/apps/feedback.ts": 2, // a stranger's note on an app host, both answers that may carry the visitor cookie | |
| 115 | "src/apps/feedback.ts": 1, // a stranger's note on an app host: only the answer to a note made mints a visitor id | |
| 116 | 116 | "src/web/pages/passkeys.ts": 5, // import, passkey sign-in, passkey add/recovery-link sign-in, access-link sign-in (+1 mention) |
| 117 | 117 | "src/web/pages/site.ts": 5, // sessionCookie() itself and its uses: password sign-in/sign-up, logout; the theme cookie; the closing flash on a sign-in (#15619) |
| 118 | 118 | "src/web/pages/first-admin.ts": 1, // the first admin made by passkey |
| @@ -331,7 +331,7 @@ for (const https of [false, true]) { | ||
| 331 | 331 | const granted = take("app grant", grant); |
| 332 | 332 | take("app sign-out", await via("/__forge/signout", granted.map((c) => c.split(";")[0]!).join("; "))); |
| 333 | 333 | |
| 334 | // A stranger's note from a public app's page: the anonymous visitor cookie. | |
| 334 | // A stranger's note from a public app's page: the signed visitor principal (#18112). | |
| 335 | 335 | const noted = await newApp(child, olive.user, { name: "cookienote", visibility: "public" }); |
| 336 | 336 | if (!noted.ok) throw new Error(noted.error); |
| 337 | 337 | const scheme = https ? "https" : "http"; |
| @@ -347,7 +347,7 @@ for (const https of [false, true]) { | ||
| 347 | 347 | body: JSON.stringify({ text: "The cookie note", page: `${scheme}://cookienote.apps.test/`, viewport: "390x844" }), |
| 348 | 348 | }); |
| 349 | 349 | expect(note.status).toBe(201); |
| 350 | take("app note", note, "forge_visitor"); | |
| 350 | take("app note", note, "forge_maker"); | |
| 351 | 351 | |
| 352 | 352 | // A gift link keeps its code in a cookie, out of the next address. |
| 353 | 353 | const gift = await fetch(`${cs.url}/?code=gift-cookie-1`, { redirect: "manual" }); |
| @@ -495,10 +495,10 @@ const BUILDERS: Record<string, string> = { | ||
| 495 | 495 | "flashCookie(": "src/web/flash.ts", |
| 496 | 496 | "clearFlashCookie(": "src/web/flash.ts", |
| 497 | 497 | "cookieHeader(": "src/http/rp.ts", |
| 498 | "visitorCookie(": "src/apps/feedback.ts", | |
| 499 | 498 | clear: "src/http/rp.ts, `cookieHeader` with Max-Age 0", |
| 500 | 499 | value: "src/apps/scaffold.ts, `redirectTo`'s cookies, each from `cookie`", |
| 501 | 500 | cookie: "src/http/measure.ts, the line `trackVisitor` returns, built by `cookieLine` in src/perf/visitor_id.ts", |
| 501 | "admitted.setCookie": "src/apps/feedback.ts, the visitor id `admitVisitor` mints with setCookie in src/core/visitors.ts", | |
| 502 | 502 | "clearCookie(": "src/spawn/origin_broker.ts, the connect ticket cleared with Max-Age 0", |
| 503 | 503 | "dropGift(": "src/web/gift_cookie.ts, the gift cookie cleared with Max-Age 0", |
| 504 | 504 | resumeLine: "src/web/pages/start-forge.ts, the resume key's line from keepResumeKey or dropResumeKey in src/web/resume_cookie.ts", |
| @@ -600,7 +600,7 @@ describe("cookie flags, walked in the source", () => { | ||
| 600 | 600 | |
| 601 | 601 | test("the walk finds the forge's cookies, including those no door above reaches", () => { |
| 602 | 602 | const where = new Set(calls.map((c) => c.file)); |
| 603 | for (const file of ["src/web/pages/site.ts", "src/web/flash.ts", "src/http/rp.ts", "src/http/server.ts", "src/apps/proxy.ts", "src/apps/feedback.ts", "src/web/pages/map.ts"]) | |
| 603 | for (const file of ["src/web/pages/site.ts", "src/web/flash.ts", "src/http/rp.ts", "src/http/server.ts", "src/apps/proxy.ts", "src/core/visitors.ts", "src/web/pages/map.ts"]) | |
| 604 | 604 | expect([file, where.has(file)]).toEqual([file, true]); |
| 605 | 605 | }); |
| 606 | 606 |
test/cookie-floor.test.ts +1
| @@ -26,6 +26,7 @@ const SCRIPT_READABLE: Record<string, string> = {}; | ||
| 26 | 26 | */ |
| 27 | 27 | const PASSED_IN: Record<string, string> = { |
| 28 | 28 | "src/web/layout.ts o.cookie": "a page's `cookie` option; each caller passes a line from setCookie (the theme in src/web/pages/site.ts)", |
| 29 | "src/apps/feedback.ts admitted.setCookie": "the visitor id `admitVisitor` mints, its line from setCookie in src/core/visitors.ts", | |
| 29 | 30 | "src/web/pages/start-forge.ts resumeLine": "withCookie's line; each caller passes keepResumeKey or dropResumeKey from src/web/resume_cookie.ts, which call setCookie and expireCookie", |
| 30 | 31 | }; |
| 31 | 32 |
test/cookie-secure.test.ts +7 −2
| @@ -64,7 +64,12 @@ describe("the visitor cookie on an app host", () => { | ||
| 64 | 64 | const visitor = async (forgeUrl: string) => { |
| 65 | 65 | (runtime.options as { forgeUrl: string }).forgeUrl = forgeUrl; |
| 66 | 66 | const host = `notes.apps.test:${servers.port}`; |
| 67 | const res = await fetch(`${servers.url}/__forge/notes`, { headers: { host } }); | |
| 67 | // Only a note made mints the visitor id; reading the list mints nothing (#18112). | |
| 68 | const res = await fetch(`${servers.url}/__forge/note`, { | |
| 69 | method: "POST", | |
| 70 | headers: { host, origin: `http://${host}`, "content-type": "application/json" }, | |
| 71 | body: JSON.stringify({ text: "A note", page: `http://${host}/`, viewport: "390x844" }), | |
| 72 | }); | |
| 68 | 73 | return res.headers.get("set-cookie") ?? ""; |
| 69 | 74 | }; |
| 70 | 75 | |
| @@ -73,7 +78,7 @@ describe("the visitor cookie on an app host", () => { | ||
| 73 | 78 | }); |
| 74 | 79 | test("not Secure on a plain-http forge", async () => { |
| 75 | 80 | const cookie = await visitor(servers.url); |
| 76 | expect(cookie).toContain("forge_visitor="); | |
| 81 | expect(cookie).toContain("forge_maker="); | |
| 77 | 82 | expect(cookie).not.toContain("Secure"); |
| 78 | 83 | }); |
| 79 | 84 | }); |
test/may.test.ts +2 −1
| @@ -153,7 +153,8 @@ test("a token is not a person: account.manage is the account itself", () => { | ||
| 153 | 153 | |
| 154 | 154 | test("the forge-wide actions follow the roles table", () => { |
| 155 | 155 | const can = (who: string | undefined, scope?: "ro" | "rw" | "admin") => capabilities(app.db, scope === undefined ? principalOfUser(as(who)) : bearer(as(who), scope)); |
| 156 | expect(can(undefined)).toEqual(["forge.read"]); | |
| 156 | // No account may still make something as a visitor (`core/visitors.ts`, #18112). | |
| 157 | expect(can(undefined)).toEqual(["forge.read", "visitor.make"]); | |
| 157 | 158 | expect(can("gina")).toEqual(["forge.read", "forge.write", "forge.comment", "forge.contribute"]); |
| 158 | 159 | expect(can("nina")).toEqual(["forge.read", "forge.write", "forge.comment", "forge.contribute", "forge.make_it_yours", "forge.run_crew"]); |
| 159 | 160 | expect(can("boss")).toContain("forge.administer"); |
test/visitors.test.ts +134 −259
| @@ -1,274 +1,149 @@ | ||
| 1 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 1 | /** | |
| 2 | * A visitor principal (#18112): minted only when a visitor makes something, signed with its own | |
| 3 | * key, never the analytics cookie, a role in `may`, and capped per visitor and per forge. | |
| 4 | */ | |
| 5 | ||
| 6 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 2 | 7 | import { mkdtemp, rm } from "node:fs/promises"; |
| 3 | 8 | import { tmpdir } from "node:os"; |
| 4 | 9 | import { join } from "node:path"; |
| 5 | 10 | import { createApp, type App } from "../src/app.ts"; |
| 6 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 7 | import { browserOf, cookieId, mintId, osOf, prefixOf, probableId } from "../src/perf/visitor_id.ts"; | |
| 8 | import { linkVisitor, noteVisitor, purgeVisitors, KEEP_MS } from "../src/perf/visitor_store.ts"; | |
| 9 | import { visitorsReport, probeVisitors } from "../src/perf/visitor_report.ts"; | |
| 10 | import { getReturning, setReturning } from "../src/settings/returning.ts"; | |
| 11 | import { createSession } from "../src/core/sessions.ts"; | |
| 12 | import { createUser } from "../src/core/users.ts"; | |
| 13 | import { linkRequestVisitor } from "../src/perf/visitor_link.ts"; | |
| 11 | import { may } from "../src/core/may.ts"; | |
| 12 | import { principalOf, userOf } from "../src/core/principal.ts"; | |
| 13 | import { admitVisitor, countMake, heldVisitor } from "../src/core/visitors.ts"; | |
| 14 | import { VISITOR_CAPS } from "../src/http/limits.ts"; | |
| 15 | import { resolveAuth, serve, type Servers } from "../src/http/server.ts"; | |
| 14 | 16 | import { loadKey } from "../src/kernel/secret.ts"; |
| 15 | import { returningLines } from "../src/tui/screens/returning.ts"; | |
| 16 | import type { Session } from "../src/tui/session.ts"; | |
| 17 | import { mintId } from "../src/perf/visitor_id.ts"; | |
| 17 | 18 | |
| 18 | let dir: string; | |
| 19 | let app: App; | |
| 20 | let servers: Servers; | |
| 21 | let base: string; | |
| 19 | let dataDir = ""; | |
| 20 | let app: App, servers: Servers; | |
| 22 | 21 | let key: Buffer; |
| 23 | 22 | |
| 24 | 23 | beforeAll(async () => { |
| 25 | dir = await mkdtemp(join(tmpdir(), "visitors-")); | |
| 26 | app = createApp({ dataDir: dir, port: 0 }); | |
| 24 | dataDir = await mkdtemp(join(tmpdir(), "forge-visitors-")); | |
| 25 | app = createApp({ dataDir, port: 0 }); | |
| 27 | 26 | servers = await serve(app); |
| 28 | base = `http://127.0.0.1:${servers.port}`; | |
| 29 | key = loadKey(dir); | |
| 27 | key = loadKey(dataDir); | |
| 30 | 28 | }); |
| 29 | ||
| 31 | 30 | afterAll(async () => { |
| 32 | await servers.stop(); | |
| 33 | await rm(dir, { recursive: true, force: true }); | |
| 31 | servers.stop(); | |
| 32 | app.db.close(); | |
| 33 | await rm(dataDir, { recursive: true, force: true }); | |
| 34 | 34 | }); |
| 35 | 35 | |
| 36 | const CHROME = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"; | |
| 37 | const DAY = 86_400_000; | |
| 38 | const T0 = Date.parse("2026-11-01T10:00:00Z"); | |
| 39 | const beacon = (headers: Record<string, string> = {}) => | |
| 40 | fetch(`${base}/_measure`, { | |
| 41 | method: "POST", | |
| 42 | headers: { origin: base, "user-agent": CHROME, "accept-language": "en-GB,en;q=0.8", ...headers }, | |
| 43 | body: JSON.stringify({ path: "/", ttfb: 40, load: 300, lcp: 250, inp: 80, cls: 0.02 }), | |
| 44 | }); | |
| 45 | const count = (table = "visitor") => (app.db.query(`SELECT COUNT(*) AS n FROM ${table}`).get() as { n: number }).n; | |
| 46 | const wipe = () => { | |
| 47 | app.db.exec("DELETE FROM visitor; DELETE FROM visitor_visit"); | |
| 48 | }; | |
| 49 | ||
| 50 | describe("a returning visitor", () => { | |
| 51 | test("every forge reads the setting off until its owner turns it on, and an owner can change it", () => { | |
| 52 | expect(getReturning(app.db)).toBe(false); | |
| 53 | expect(app.db.query("SELECT COUNT(*) AS n FROM forge_setting WHERE key = 'traffic.returning'").get()).toEqual({ n: 0 }); | |
| 54 | setReturning(app.db, true, "u"); | |
| 55 | expect(getReturning(app.db)).toBe(true); | |
| 56 | app.db.exec("DELETE FROM forge_setting WHERE key = 'traffic.returning'"); | |
| 57 | expect(getReturning(app.db)).toBe(false); | |
| 58 | setReturning(app.db, false, "u"); | |
| 59 | expect(getReturning(app.db)).toBe(false); | |
| 60 | }); | |
| 61 | ||
| 62 | test("with the setting off nothing is stored and no cookie is set", async () => { | |
| 63 | wipe(); | |
| 64 | const res = await beacon(); | |
| 65 | expect(res.status).toBe(204); | |
| 66 | expect(res.headers.get("set-cookie")).toBeNull(); | |
| 67 | expect(count()).toBe(0); | |
| 68 | }); | |
| 69 | ||
| 70 | test("the first view sets a first-party cookie with every attribute, and the same cookie on two days is one returning visitor with two visits", async () => { | |
| 71 | setReturning(app.db, true, "u"); | |
| 72 | wipe(); | |
| 73 | const first = await beacon(); | |
| 74 | const line = first.headers.get("set-cookie")!; | |
| 75 | expect(line).toMatch(/^forge_visitor=c[0-9a-f]{32}\.[0-9a-f]{32}; /); | |
| 76 | for (const part of ["Path=/", "HttpOnly", "SameSite=Lax", `Max-Age=${396 * 86_400}`]) expect(line).toContain(part); | |
| 77 | expect(line).not.toContain("Domain"); | |
| 78 | const id = cookieId(line, key)!; | |
| 79 | expect(id).toBeDefined(); | |
| 80 | // The same cookie, on two different days. | |
| 81 | noteVisitor(app.db, { id, kind: "cookie", path: "/", ref: "news.example", step: 1, at: T0 }); | |
| 82 | noteVisitor(app.db, { id, kind: "cookie", path: "/plans?x=1", ref: "", step: 2, at: T0 + 3 * DAY }); | |
| 83 | const r = visitorsReport(app.db, 30, T0 + 4 * DAY); | |
| 84 | const mine = r.returning.find((v) => v.id === id.slice(0, 9))!; | |
| 85 | expect(mine).toMatchObject({ visits: 2, daysSeen: 2, probable: false, firstRef: "news.example", step: "clicked a plan" }); | |
| 86 | expect(r.returningVisitors).toBe(1); | |
| 87 | const pages = app.db.query("SELECT pages FROM visitor_visit WHERE visitor = ? ORDER BY id").all(id) as { pages: string }[]; | |
| 88 | expect(pages.map((p) => JSON.parse(p.pages))).toEqual([["/"], ["/plans"]]); | |
| 89 | expect(probeVisitors(app.db, 30, T0 + 4 * DAY, r).agrees).toBe(true); | |
| 90 | }); | |
| 91 | ||
| 92 | test("a cookie-less repeat from the same network and browser is probable, and is not merged with a cookie id", async () => { | |
| 93 | wipe(); | |
| 94 | await beacon(); | |
| 95 | await beacon(); | |
| 96 | const rows = app.db.query("SELECT id, kind, visits FROM visitor").all() as { id: string; kind: string; visits: number }[]; | |
| 97 | expect(rows).toHaveLength(1); | |
| 98 | expect(rows[0]!.kind).toBe("probable"); | |
| 99 | expect(rows[0]!.id.startsWith("p")).toBe(true); | |
| 100 | // Two views within 30 minutes are one visit; the probable row still reads "probable". | |
| 101 | const r = visitorsReport(app.db, 30, Date.now()); | |
| 102 | expect(r.newVisitors).toBe(1); | |
| 103 | noteVisitor(app.db, { id: rows[0]!.id, kind: "probable", path: "/", ref: "", step: 0, at: Date.now() + 2 * DAY }); | |
| 104 | expect(visitorsReport(app.db, 30, Date.now() + 2 * DAY).returning[0]).toMatchObject({ probable: true, visits: 2 }); | |
| 105 | // A cookie arriving is a different visitor. | |
| 106 | await beacon({ cookie: `forge_visitor=${mintId(key).value}` }); | |
| 107 | expect(count()).toBe(2); | |
| 108 | }); | |
| 109 | ||
| 110 | test("only a cookie this forge signed is accepted: invented ids do not make rows", async () => { | |
| 111 | setReturning(app.db, true, "u"); | |
| 112 | wipe(); | |
| 113 | const real = mintId(key); | |
| 114 | expect(cookieId(`forge_visitor=${real.value}`, key)).toBe(real.id); | |
| 115 | expect(cookieId(`forge_visitor=${real.value}`, Buffer.from("another forge's key"))).toBeUndefined(); | |
| 116 | expect(cookieId(`forge_visitor=${real.id}.${"0".repeat(32)}`, key)).toBeUndefined(); | |
| 117 | expect(cookieId(`forge_visitor=${real.id}`, key)).toBeUndefined(); | |
| 118 | for (let i = 0; i < 20; i++) { | |
| 119 | const invented = `c${i.toString(16).padStart(32, "0")}.${"a".repeat(32)}`; | |
| 120 | const res = await beacon({ cookie: `forge_visitor=${invented}` }); | |
| 121 | expect(res.status).toBe(204); | |
| 122 | } | |
| 123 | // All twenty are one cookie-less probable visitor; none is a cookie row, and a fresh cookie is offered. | |
| 124 | const rows = app.db.query("SELECT kind FROM visitor").all() as { kind: string }[]; | |
| 125 | expect(rows).toEqual([{ kind: "probable" }]); | |
| 126 | }); | |
| 127 | ||
| 128 | test("a day takes at most the cap of new visitors; known visitors still count", () => { | |
| 129 | wipe(); | |
| 130 | const at = T0; | |
| 131 | const first = mintId(key).id; | |
| 132 | expect(noteVisitor(app.db, { id: first, kind: "cookie", path: "/", ref: "", step: 0, at }, 2)).toBe(true); | |
| 133 | expect(noteVisitor(app.db, { id: mintId(key).id, kind: "cookie", path: "/", ref: "", step: 0, at }, 2)).toBe(true); | |
| 134 | expect(noteVisitor(app.db, { id: mintId(key).id, kind: "cookie", path: "/", ref: "", step: 0, at }, 2)).toBe(false); | |
| 135 | expect(count()).toBe(2); | |
| 136 | expect(noteVisitor(app.db, { id: first, kind: "cookie", path: "/x", ref: "", step: 0, at: at + 1000 }, 2)).toBe(true); | |
| 137 | // The next day has its own allowance. | |
| 138 | expect(noteVisitor(app.db, { id: mintId(key).id, kind: "cookie", path: "/", ref: "", step: 0, at: at + DAY }, 2)).toBe(true); | |
| 139 | expect(count()).toBe(3); | |
| 140 | }); | |
| 141 | ||
| 142 | test("the terminal shows the same figures to an admin only, and its switch is the one the page reads", () => { | |
| 143 | wipe(); | |
| 144 | setReturning(app.db, false, "u"); | |
| 145 | const admin = { db: app.db, user: { id: "u", isAdmin: true, kind: "human" } } as unknown as Session; | |
| 146 | const other = { db: app.db, user: { id: "v", isAdmin: false, kind: "human" } } as unknown as Session; | |
| 147 | expect(returningLines(admin)[0]!.title).toContain("Off"); | |
| 148 | setReturning(app.db, true, "u"); | |
| 149 | const { id } = mintId(key); | |
| 150 | noteVisitor(app.db, { id, kind: "cookie", path: "/", ref: "news.example", step: 1, at: Date.now() - DAY }); | |
| 151 | noteVisitor(app.db, { id, kind: "cookie", path: "/", ref: "", step: 1, at: Date.now() }); | |
| 152 | const lines = returningLines(admin); | |
| 153 | expect(lines[0]!.title).toContain("1 returning"); | |
| 154 | expect(lines.some((l) => l.title.startsWith(id.slice(0, 9)))).toBe(true); | |
| 155 | expect(returningLines(other)).toEqual([]); | |
| 156 | }); | |
| 157 | ||
| 158 | test("a different browser or network is a different probable visitor, and a forged cookie is ignored", () => { | |
| 159 | const h = (ua: string) => new Headers({ "user-agent": ua, "accept-language": "en" }); | |
| 160 | const a = probableId("s", h(CHROME), "203.0.113.5"); | |
| 161 | expect(probableId("s", h(CHROME), "203.0.113.200")).toBe(a); | |
| 162 | expect(probableId("s", h(CHROME), "203.0.114.5")).not.toBe(a); | |
| 163 | expect(probableId("s", h(CHROME.replace("Chrome/120", "Chrome/121")), "203.0.113.5")).not.toBe(a); | |
| 164 | expect(probableId("t", h(CHROME), "203.0.113.5")).not.toBe(a); | |
| 165 | expect(cookieId("forge_visitor=../../etc", key)).toBeUndefined(); | |
| 166 | expect(prefixOf("203.0.113.5")).toBe("203.0.113/24"); | |
| 167 | expect(prefixOf("2001:db8:1:2:3:4:5:6")).toBe("2001:db8:1/48"); | |
| 168 | expect(browserOf(CHROME)).toBe("chrome/120"); | |
| 169 | expect(osOf(CHROME)).toBe("windows"); | |
| 170 | }); | |
| 171 | ||
| 172 | test("Sec-GPC and DNT get no cookie and no row, a scraper gets no id", async () => { | |
| 173 | wipe(); | |
| 174 | for (const headers of [{ "sec-gpc": "1" }, { dnt: "1" }]) { | |
| 175 | const res = await beacon(headers); | |
| 176 | expect(res.status).toBe(204); | |
| 177 | expect(res.headers.get("set-cookie")).toBeNull(); | |
| 178 | } | |
| 179 | const bot = await beacon({ "user-agent": "Googlebot/2.1 (+http://www.google.com/bot.html)" }); | |
| 180 | expect(bot.headers.get("set-cookie")).toBeNull(); | |
| 181 | const none = await beacon({ "user-agent": "" }); | |
| 182 | expect(none.headers.get("set-cookie")).toBeNull(); | |
| 183 | expect(count()).toBe(0); | |
| 184 | expect(count("visitor_visit")).toBe(0); | |
| 185 | }); | |
| 186 | ||
| 187 | test("the visitor who starts a forge is linked to it, with the visits that led there", () => { | |
| 188 | wipe(); | |
| 189 | const { id, value } = mintId(key); | |
| 190 | noteVisitor(app.db, { id, kind: "cookie", path: "/", ref: "news.example", step: 1, at: Date.now() - 6 * DAY }); | |
| 191 | noteVisitor(app.db, { id, kind: "cookie", path: "/agents", ref: "", step: 1, at: Date.now() - 3 * DAY }); | |
| 192 | noteVisitor(app.db, { id, kind: "cookie", path: "/spawn", ref: "", step: 2, at: Date.now() }); | |
| 193 | linkRequestVisitor(app, new Request(base, { headers: { cookie: `forge_visitor=${value}` } }), "acme", "started"); | |
| 194 | expect(linkVisitor(app.db, id, "other", "paid", Date.now())).toBe(false); | |
| 195 | const led = visitorsReport(app.db, 30, Date.now()).led[0]!; | |
| 196 | expect(led).toMatchObject({ forge: "acme", step: "started a forge", firstRef: "news.example" }); | |
| 197 | expect(led.visits).toHaveLength(3); | |
| 198 | linkRequestVisitor(app, new Request(base, { headers: { cookie: `forge_visitor=${value}`, "sec-gpc": "1" } }), "acme", "paid"); | |
| 199 | expect(visitorsReport(app.db, 30, Date.now()).led[0]!.step).toBe("started a forge"); | |
| 200 | linkRequestVisitor(app, new Request(base, { headers: { cookie: `forge_visitor=${value}` } }), "acme", "paid"); | |
| 201 | expect(visitorsReport(app.db, 30, Date.now()).led[0]!.step).toBe("paid"); | |
| 202 | }); | |
| 203 | ||
| 204 | test("rows past 13 months are removed, newer ones kept", () => { | |
| 205 | wipe(); | |
| 206 | const now = Date.now(); | |
| 207 | noteVisitor(app.db, { id: mintId(key).id, kind: "cookie", path: "/", ref: "", step: 0, at: now - KEEP_MS - DAY }); | |
| 208 | noteVisitor(app.db, { id: mintId(key).id, kind: "cookie", path: "/", ref: "", step: 0, at: now - 30 * DAY }); | |
| 209 | expect(purgeVisitors(app.db, now)).toBe(1); | |
| 210 | expect(count()).toBe(1); | |
| 211 | expect(count("visitor_visit")).toBe(1); | |
| 212 | }); | |
| 213 | ||
| 214 | test("no raw address or full user agent is in the store", async () => { | |
| 215 | wipe(); | |
| 216 | await fetch(`${base}/_measure`, { | |
| 217 | method: "POST", | |
| 218 | headers: { origin: base, "user-agent": `${CHROME} SecretMarker`, "x-forwarded-for": "198.51.100.77" }, | |
| 219 | body: JSON.stringify({ path: "/", ttfb: 40, load: 300, lcp: 250, inp: 80, cls: 0.02 }), | |
| 220 | }); | |
| 221 | expect(count()).toBe(1); | |
| 222 | const dump = JSON.stringify([ | |
| 223 | app.db.query("SELECT * FROM visitor").all(), | |
| 224 | app.db.query("SELECT * FROM visitor_visit").all(), | |
| 225 | app.db.query("SELECT * FROM visitor_salt").all(), | |
| 226 | ]); | |
| 227 | for (const needle of ["SecretMarker", "Mozilla", "198.51.100", "127.0.0.1", "203.0.113"]) expect(dump).not.toContain(needle); | |
| 228 | }); | |
| 229 | ||
| 230 | test("the privacy page says what is kept, and the visitors API is for admins only", async () => { | |
| 231 | const page = await (await fetch(`${base}/privacy`)).text(); | |
| 232 | expect(page).toContain("13 months"); | |
| 233 | expect(page).toContain("never leaves this forge"); | |
| 234 | expect([401, 404]).toContain((await fetch(`${base}/api/v1/admin/traffic/visitors?days=30`)).status); | |
| 235 | }); | |
| 236 | ||
| 237 | test("an admin reads the same figures from the API and the Traffic page, and flips the setting from it", async () => { | |
| 238 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "ada", email: "[email protected]", password: "correct-horse-battery", isAdmin: true }); | |
| 239 | if (!made.ok) throw new Error(made.error); | |
| 240 | const cookie = `forge_session=${createSession(app.db, made.value.id).token}`; | |
| 241 | wipe(); | |
| 242 | setReturning(app.db, true, "u"); | |
| 243 | const { id } = mintId(key); | |
| 244 | noteVisitor(app.db, { id, kind: "cookie", path: "/", ref: "news.example", step: 1, at: Date.now() - DAY }); | |
| 245 | noteVisitor(app.db, { id, kind: "cookie", path: "/", ref: "", step: 1, at: Date.now() }); | |
| 246 | const api = (await (await fetch(`${base}/api/v1/admin/traffic/visitors?days=30`, { headers: { cookie } })).json()) as { | |
| 247 | returning: { id: string; visits: number }[]; | |
| 248 | returning_visitors: number; | |
| 249 | probe: { agrees: boolean }; | |
| 250 | }; | |
| 251 | expect(api.returning_visitors).toBe(1); | |
| 252 | expect(api.returning[0]).toMatchObject({ id: id.slice(0, 9), visits: 2 }); | |
| 253 | expect(api.probe.agrees).toBe(true); | |
| 254 | const page = await (await fetch(`${base}/settings/traffic`, { headers: { cookie } })).text(); | |
| 255 | expect(page).toContain(id.slice(0, 9)); | |
| 256 | expect(page).toContain("news.example"); | |
| 257 | const off = await fetch(`${base}/settings/traffic/returning`, { | |
| 258 | method: "POST", | |
| 259 | redirect: "manual", | |
| 260 | headers: { cookie, origin: base, "content-type": "application/x-www-form-urlencoded" }, | |
| 261 | body: "returning=off", | |
| 262 | }); | |
| 263 | expect(off.status).toBe(303); | |
| 264 | expect(getReturning(app.db)).toBe(false); | |
| 265 | const cross = await fetch(`${base}/settings/traffic/returning`, { | |
| 266 | method: "POST", | |
| 267 | redirect: "manual", | |
| 268 | headers: { cookie, origin: "https://evil.example", "content-type": "application/x-www-form-urlencoded" }, | |
| 269 | body: "returning=on", | |
| 270 | }); | |
| 271 | expect(cross.status).not.toBe(303); | |
| 272 | expect(getReturning(app.db)).toBe(false); | |
| 273 | }); | |
| 36 | const MAKER = "forge_maker"; | |
| 37 | const plain = (cookie?: string, extra: Record<string, string> = {}, client = "203.0.113.1") => ({ | |
| 38 | headers: new Headers({ ...(cookie === undefined ? {} : { cookie: `${MAKER}=${cookie}` }), ...extra }), | |
| 39 | secure: false, | |
| 40 | client, | |
| 41 | }); | |
| 42 | const valueOf = (line: string): string => line.split(";")[0]!.slice(MAKER.length + 1); | |
| 43 | const held = (value: string): string | undefined => heldVisitor(new Headers({ cookie: `${MAKER}=${value}` }), key); | |
| 44 | const madeCount = (): number => | |
| 45 | app.db.query<{ n: number }, []>("SELECT count(*) AS n FROM sqlite_master WHERE name = 'visitor_made'").get()!.n === 0 | |
| 46 | ? 0 | |
| 47 | : app.db.query<{ n: number }, []>("SELECT count(*) AS n FROM visitor_made").get()!.n; | |
| 48 | ||
| 49 | /** A new visitor makes one thing: the cookie value of the id minted for it. */ | |
| 50 | function makeNew(at?: number, client = "203.0.113.1"): string { | |
| 51 | const made = admitVisitor(app.db, key, plain(undefined, {}, client), at); | |
| 52 | if (!made.ok || made.setCookie === undefined) throw new Error("not minted"); | |
| 53 | countMake(app.db, made.visitorId, client, at); | |
| 54 | return valueOf(made.setCookie); | |
| 55 | } | |
| 56 | ||
| 57 | test("a minted id verifies, and the request that carries it is a visitor, not a user", async () => { | |
| 58 | const made = admitVisitor(app.db, key, plain()); | |
| 59 | if (!made.ok) throw new Error(made.says); | |
| 60 | expect(made.setCookie).toContain(`${MAKER}=`); | |
| 61 | expect(made.setCookie).toContain("HttpOnly"); | |
| 62 | const value = valueOf(made.setCookie!); | |
| 63 | expect(held(value)).toBe(made.visitorId!); | |
| 64 | ||
| 65 | const auth = await resolveAuth(app, new Request("http://forge.test/", { headers: { cookie: `${MAKER}=${value}` } })); | |
| 66 | const p = principalOf(auth); | |
| 67 | expect(p).toEqual({ kind: "visitor", visitorId: made.visitorId! }); | |
| 68 | expect(userOf(p)).toBeUndefined(); | |
| 69 | expect(may(app.db, p, "visitor.make").ok).toBe(true); | |
| 70 | // A visitor may do no more than anyone with no account: it is not a guest. | |
| 71 | expect(may(app.db, p, "forge.comment")).toMatchObject({ ok: false, why: "unauthorized" }); | |
| 72 | ||
| 73 | // Making again with the id held mints nothing new. | |
| 74 | expect(admitVisitor(app.db, key, plain(value))).toEqual({ ok: true, visitorId: made.visitorId, setCookie: undefined }); | |
| 75 | }); | |
| 76 | ||
| 77 | test("the key is read only when a maker cookie is there, so a request with no credential never touches it", () => { | |
| 78 | let reads = 0; | |
| 79 | const thunk = () => { | |
| 80 | reads++; | |
| 81 | return key; | |
| 82 | }; | |
| 83 | expect(heldVisitor(new Headers(), thunk)).toBeUndefined(); | |
| 84 | expect(heldVisitor(new Headers({ cookie: "forge_visitor=x; other=y" }), thunk)).toBeUndefined(); | |
| 85 | expect(heldVisitor(new Headers({ cookie: `${MAKER}=not-a-maker-value` }), thunk)).toBeUndefined(); | |
| 86 | expect(reads).toBe(0); | |
| 87 | const value = makeNew(); | |
| 88 | expect(heldVisitor(new Headers({ cookie: `${MAKER}=${value}` }), thunk)).toBe(value.split(".")[0]); | |
| 89 | expect(reads).toBe(1); | |
| 90 | }); | |
| 91 | ||
| 92 | test("an unsigned, altered or analytics id is refused", async () => { | |
| 93 | const value = makeNew(); | |
| 94 | const [id, mac] = value.split(".") as [string, string]; | |
| 95 | const flip = (s: string) => (s.endsWith("0") ? s.slice(0, -1) + "1" : s.slice(0, -1) + "0"); | |
| 96 | expect(held(id)).toBeUndefined(); | |
| 97 | expect(held(`${flip(id)}.${mac}`)).toBeUndefined(); | |
| 98 | expect(held(`${id}.${flip(mac)}`)).toBeUndefined(); | |
| 99 | expect(heldVisitor(new Headers({ cookie: `${MAKER}=${value}` }), Buffer.alloc(32, 7))).toBeUndefined(); | |
| 100 | // The analytics cookie's value, signed by this forge, is still not a visitor principal. | |
| 101 | const analytics = mintId(key); | |
| 102 | expect(held(analytics.value)).toBeUndefined(); | |
| 103 | const auth = await resolveAuth(app, new Request("http://forge.test/", { headers: { cookie: `forge_visitor=${analytics.value}; ${MAKER}=${id}.${flip(mac)}` } })); | |
| 104 | expect(principalOf(auth).kind).toBe("anonymous"); | |
| 105 | // An altered id is admitted as a new visitor, never as the one it imitates. | |
| 106 | const again = admitVisitor(app.db, key, plain(`${id}.${flip(mac)}`)); | |
| 107 | expect(again.ok && again.visitorId !== id && again.setCookie !== undefined).toBe(true); | |
| 108 | }); | |
| 109 | ||
| 110 | test("a read mints nothing", async () => { | |
| 111 | const before = madeCount(); | |
| 112 | const res = await fetch(`${servers.url}/`); | |
| 113 | await res.arrayBuffer(); | |
| 114 | expect(res.headers.getSetCookie().some((c) => c.startsWith(`${MAKER}=`))).toBe(false); | |
| 115 | expect(madeCount()).toBe(before); | |
| 116 | }); | |
| 117 | ||
| 118 | test("Do Not Track and GPC mint no id; the thing is still made, counted for the forge", () => { | |
| 119 | for (const h of [{ dnt: "1" }, { "sec-gpc": "1" }]) | |
| 120 | expect(admitVisitor(app.db, key, plain(undefined, h))).toEqual({ ok: true, visitorId: undefined, setCookie: undefined }); | |
| 121 | }); | |
| 122 | ||
| 123 | test("the caps refuse the next make: per visitor, per client, then per forge", () => { | |
| 124 | const at = Date.now() + 40 * 86_400_000; // past the earlier tests' day, and their rows pruned | |
| 125 | const spread = (i: number) => `198.51.100.${i % 250}.${Math.floor(i / 250)}`; | |
| 126 | // One visitor, from many connections: their own cap binds. | |
| 127 | const value = makeNew(at, spread(0)); | |
| 128 | const id = held(value)!; | |
| 129 | for (let i = 1; i < VISITOR_CAPS.perVisitor.perDay; i++) { | |
| 130 | expect(admitVisitor(app.db, key, plain(value, {}, spread(i)), at).ok).toBe(true); | |
| 131 | countMake(app.db, id, spread(i), at); | |
| 132 | } | |
| 133 | expect(admitVisitor(app.db, key, plain(value, {}, "192.0.2.9"), at)).toMatchObject({ ok: false, status: 429, says: expect.stringContaining("A visitor may") }); | |
| 134 | ||
| 135 | // One connection dropping its cookie gets a fresh id each time, and its own cap binds it. | |
| 136 | for (let i = 0; i < VISITOR_CAPS.perClient.perDay; i++) makeNew(at, "192.0.2.7"); | |
| 137 | expect(admitVisitor(app.db, key, plain(undefined, {}, "192.0.2.7"), at)).toMatchObject({ ok: false, status: 429, says: expect.stringContaining("One connection") }); | |
| 138 | expect(admitVisitor(app.db, key, plain(undefined, {}, "192.0.2.8"), at).ok).toBe(true); | |
| 139 | ||
| 140 | // Fresh ids from fresh connections get round both only until the forge's is spent. | |
| 141 | // One transaction: thousands of separate commits outrun the test's time on a slow disk. | |
| 142 | app.db.transaction(() => { | |
| 143 | const already = VISITOR_CAPS.perVisitor.perDay + VISITOR_CAPS.perClient.perDay; | |
| 144 | for (let made = already; made < VISITOR_CAPS.perForge.perDay; made++) makeNew(at, spread(made)); | |
| 145 | })(); | |
| 146 | expect(admitVisitor(app.db, key, plain(undefined, {}, "192.0.2.8"), at)).toMatchObject({ ok: false, status: 429, says: expect.stringContaining("This forge") }); | |
| 147 | // A day on, the window has moved. | |
| 148 | expect(admitVisitor(app.db, key, plain(value), at + 86_400_001).ok).toBe(true); | |
| 274 | 149 | }); |
new above
offline
shared_appandgame_playerare never counted by anything, andkindis never read. Drop them until a route makes them.