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

Access 5c: a linked game player mints the visitor principal #18209

opened this

Merged 3h 33m ago, live in production

scout/forge:scout/18189-access-5c-a-linked-game-player-mints-the → main 0 commits fork

  • Merged. scout/18189-access-5c-a-linked-game-player-mints-the was merged into main as d46f453.

Review

Sign in to review this change.
8 files changed +136 −12
docs/features/games.md +1 −1

Diff not shown — a line 2,200 characters wide (limit 2,000). +1 −1

View file
src/core/visitors.ts +8 −8
@@ -1,12 +1,12 @@
11 /**
22 * A visitor principal (#18112): someone with no account the forge knows, minted only at the moment
33 * 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.
4 * read. Notes (`apps/feedback.ts`) and a game client link (#18189,
5 * `web/pages/games_client_pack.ts`) mint today; the shared app (#18188) follows. The id rides its
6 * own cookie, `forge_maker`, signed with a key derived for this purpose alone (HKDF, "forge visitor
7 * principal v1"), so the analytics cookie (`perf/visitor_id.ts`, `forge_visitor`) can never verify
8 * here and is never joined to it: the two share no id, no key and no table. `Sec-GPC: 1` or
9 * `DNT: 1` mints nothing, as the analytics side does.
1010 *
1111 * A visitor is not a user: `userOf` answers none for it, and `may` (`core/may.ts`) lets it do
1212 * exactly what anonymous may plus `visitor.make`, within `VISITOR_CAPS` (`http/limits.ts`).
@@ -97,11 +97,11 @@ const FORGE_FULL = "This forge has taken all it takes from visitors today; sign
9797 export function admitVisitor(
9898 db: Database,
9999 secret: Uint8Array | (() => Uint8Array),
100 request: { readonly headers: Headers; readonly secure: boolean; readonly client: string },
100 request: { readonly headers: Headers; readonly secure: boolean; readonly client: string; readonly refused?: boolean },
101101 at: number = Date.now(),
102102 ): Admission {
103103 const held = heldVisitor(request.headers, secret);
104 const p: Principal = held === undefined ? { kind: "anonymous", refused: false } : { kind: "visitor", visitorId: held };
104 const p: Principal = held === undefined ? { kind: "anonymous", refused: request.refused === true } : { kind: "visitor", visitorId: held };
105105 if (!holds(db, p, "visitor.make")) return { ok: false, status: 403, says: REFUSED_WORDS };
106106 table(db);
107107 const since = at - DAY_MS;
src/http/games_routes.ts +2 −1
@@ -24,7 +24,7 @@ import { BODY_CAPS } from "../kernel/body_caps.ts";
2424 import {
2525 gameBoxPage, gameCommandSubmit, gameCrashShare, gameEnvSubmit, gameGrantSubmit, gameLendSubmit, gameServersSubmit, gameJarDownload, gameJarSubmit, gameModInstall, gameModPack, gameModRemove, gameModUpdate, gamePeopleSubmit, gameHead, gameWorldSubmit, gamePowerSubmit, gameSleepSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gameTakeBackSubmit, gamesPage,
2626 } from "../web/pages/games.ts";
27 import { gamePackDownload, gamePackLink, gamePackRevoke } from "../web/pages/games_client_pack.ts";
27 import { gamePackDownload, gamePackLinked, gamePackLink, gamePackRevoke } from "../web/pages/games_client_pack.ts";
2828 import { gameMap, gameMapSlash } from "./games_map.ts";
2929 import { gameSparkLink, gameSparkOpen, gameSparkPost, gameSparkRead } from "../web/pages/games_spark.ts";
3030 import { gameConfigCommit, gameConfigPage, gameConfigPreview } from "../web/pages/games_config.ts";
@@ -165,6 +165,7 @@ export function gamesRoutes(router: Router<Handler>): void {
165165 router.add("GET", "/games/jar/:id/:name", gameJarDownload);
166166 // "@pack" is no box name, so a box named "pack" keeps its /games/pack/<service>/stream.
167167 router.add("GET", "/games/@pack/:token/:file", gamePackDownload);
168 router.add("POST", "/games/@pack/:token/:file", gamePackLinked);
168169 // A box's spark profiles (#18137): "@spark" is no box name, as "@pack".
169170 router.add("POST", "/games/@spark/:secret/post", gameSparkPost);
170171 router.add("GET", "/games/@spark/:secret/:key", gameSparkRead);
src/http/lazy_lists.ts +1
@@ -648,6 +648,7 @@ export const OPERATIONS_ROUTES = [
648648 ["GET", "/games"],
649649 ["GET", "/games/jar/:id/:name"],
650650 ["GET", "/games/@pack/:token/:file"],
651 ["POST", "/games/@pack/:token/:file"],
651652 ["POST", "/games/@spark/:secret/post"],
652653 ["GET", "/games/@spark/:secret/:key"],
653654 ["GET", "/games/head/:uuid"],
src/web/pages/games_client_pack.ts +55 −2
@@ -2,11 +2,18 @@
22 * The client pack's three routes (`games/client_pack.ts`): an operator makes a link or ends every
33 * link, and anyone holding a link downloads the pack. The link is shown once, in the flash.
44 */
5 import { admitVisitor, countMake } from "../../core/visitors.ts";
56 import { LINK_DAYS, clientPack, linkOf, makePackLink, revokeLinks } from "../../games/client_pack.ts";
67 import { boxById } from "../../games/store.ts";
78 import type { Ctx } from "../../http/context.ts";
9 import { clientBucket } from "../../http/peer.ts";
10 import { secureFor } from "../../http/cookie_secure.ts";
11 import { loadKey } from "../../kernel/secret.ts";
12 import { html } from "../html.ts";
813 import { readForm } from "../form.ts";
9 import { flashTo } from "../layout.ts";
14 import { pageHead } from "../chrome.ts";
15 import { flashTo, page } from "../layout.ts";
16 import { btn } from "../ui.ts";
1017 import { boxOf } from "./games.ts";
1118
1219 // POST /games/:box/:service/pack/link: a link for the service's pack, 30 days, shown once.
@@ -35,11 +42,57 @@ export async function gamePackRevoke(ctx: Ctx): Promise<Response> {
3542 return flashTo(ctx, `/games/${got.box.name}/${service}`, { message: n === 0 ? "No link was open." : `${n} link${n === 1 ? "" : "s"} ended.` });
3643 }
3744
38 // GET /games/@pack/:token/:file: the pack, for whoever holds the link.
45 /** The pack's own address, past the page: what a launcher fetches and what "Link me" ends at. */
46 const rawOf = (ctx: Ctx): string => `${ctx.url.pathname}?raw=1`;
47
48 function linkPage(ctx: Ctx, server: string, says?: string, status = 200): Response {
49 return page(
50 {
51 ctx,
52 title: `Join ${server}`,
53 share: false,
54 body: html`${pageHead(`Join ${server}`, { sub: "The mods your game needs, as one pack for your launcher." })}
55 ${says === undefined ? null : html`<p class="notice danger" role="alert">${says}</p>`}
56 <form method="post" action="${ctx.url.pathname}">${btn("Link me and get the pack", { variant: "primary" })}</form>
57 <p class="small">Linking makes you a visitor here, with a cookie to come back by. Or <a href="${rawOf(ctx)}">download the pack</a> without linking.</p>`,
58 },
59 status,
60 );
61 }
62
63 // POST /games/@pack/:token/:file: a player links themselves. A visitor is admitted (may, then the
64 // caps) and counted once the link is made; the cookie rides only then. A signed-in person is
65 // already someone: they get the pack and mint nothing.
66 export async function gamePackLinked(ctx: Ctx): Promise<Response> {
67 const form = await readForm(ctx);
68 if (form instanceof Response) return form;
69 const link = linkOf(ctx.app.db, ctx.params.token ?? "");
70 const box = link === undefined ? undefined : boxById(ctx.app.db, link.boxId);
71 if (link === undefined || box === undefined) return new Response("not found", { status: 404 });
72 const headers = new Headers({ location: rawOf(ctx), "cache-control": "private, no-store" });
73 if (ctx.auth.user === undefined) {
74 const client = clientBucket(ctx.request);
75 const admitted = admitVisitor(ctx.app.db, () => loadKey(ctx.app.config.dataDir), {
76 headers: ctx.request.headers,
77 secure: secureFor(ctx.url, ctx.app.config.url),
78 client,
79 refused: ctx.auth.refused === true,
80 });
81 if (!admitted.ok) return linkPage(ctx, link.service, admitted.says, admitted.status);
82 countMake(ctx.app.db, admitted.visitorId, client);
83 if (admitted.setCookie !== undefined) headers.append("set-cookie", admitted.setCookie);
84 }
85 return new Response(null, { status: 303, headers });
86 }
87
88 // GET /games/@pack/:token/:file: the pack, for whoever holds the link. A browser asking for a page
89 // is shown one with the choice to link; a launcher, or `?raw=1`, gets the file. A read mints
90 // nothing.
3991 export async function gamePackDownload(ctx: Ctx): Promise<Response> {
4092 const link = linkOf(ctx.app.db, ctx.params.token ?? "");
4193 const box = link === undefined ? undefined : boxById(ctx.app.db, link.boxId);
4294 if (link === undefined || box === undefined) return new Response("not found", { status: 404 });
95 if (ctx.url.searchParams.get("raw") !== "1" && (ctx.request.headers.get("accept") ?? "").includes("text/html")) return linkPage(ctx, link.service);
4396 const made = await clientPack(ctx.app, box, link.service);
4497 if (!made.ok) return new Response(made.error, { status: 409, headers: { "cache-control": "private, no-store" } });
4598 if (made.value.kind === "link") return new Response(null, { status: 302, headers: { location: made.value.url, "cache-control": "private, no-store" } });
test/game-client-pack.test.ts +67
@@ -14,6 +14,7 @@ import { getRepo } from "../src/core/repos.ts";
1414 import { createToken } from "../src/core/tokens.ts";
1515 import { createUser, getUserByName, type User } from "../src/core/users.ts";
1616 import { keptPath } from "../src/http/access_log.ts";
17 import { VISITOR_CAPS } from "../src/http/limits.ts";
1718 import { LINK_DAYS, clientPack, linkOf, loaderOf, makeLink, openLinks, packRow, revokeLinks, zipOne } from "../src/games/client_pack.ts";
1819 import { createSession } from "../src/core/sessions.ts";
1920 import type { Locked } from "../src/games/modrinth.ts";
@@ -287,6 +288,72 @@ describe("the client pack", () => {
287288 expect((await http.handle(new Request(`${ORIGIN}/games/@pack/${token}/survival.mrpack`))).status).toBe(404);
288289 });
289290
291 test("a player links themselves (#18189): a read mints nothing; linking mints, counts, and sets the cookie; DNT and the caps are kept", async () => {
292 const token = makeLink(app.db, box, "survival", "t");
293 const file = `${ORIGIN}/games/@pack/${token}/survival.mrpack`;
294 // The table is made by the first admission: before it, nothing was counted.
295 const made = () => (app.db.query("SELECT 1 FROM sqlite_master WHERE name = 'visitor_made'").get() === null ? 0 : app.db.query<{ n: number }, []>("SELECT count(*) AS n FROM visitor_made").get()!.n);
296 const link = (extra: Record<string, string> = {}, ip = "198.51.100.7") =>
297 http.handle(new Request(file, { method: "POST", headers: { "x-forwarded-for": ip, ...extra } }));
298 const none = made();
299 // A read, as a launcher or a browser: no cookie, nothing counted. A browser sees the choice.
300 const raw = await http.handle(new Request(file));
301 expect(raw.headers.get("content-type")).toBe("application/x-modrinth-modpack+zip");
302 const seen = await http.handle(new Request(file, { headers: { accept: "text/html" } }));
303 expect(await seen.text()).toContain("Link me and get the pack");
304 for (const r of [raw, seen]) expect(r.headers.get("set-cookie")).toBeNull();
305 expect(made()).toBe(none);
306 // Linking mints the cookie and counts once; the redirect ends at the file.
307 const r = await link();
308 expect(r.status).toBe(303);
309 expect(r.headers.get("location")).toBe(`/games/@pack/${token}/survival.mrpack?raw=1`);
310 expect(r.headers.get("set-cookie")).toMatch(/^forge_maker=v[0-9a-f]{32}\./);
311 expect(r.headers.get("set-cookie")).toMatch(/HttpOnly/i);
312 expect(made()).toBe(none + 1);
313 expect((await http.handle(new Request(`${file}?raw=1`, { headers: { accept: "text/html" } }))).status).toBe(200);
314 // Do Not Track: linked and counted, no id kept.
315 const dnt = await link({ dnt: "1" });
316 expect(dnt.status).toBe(303);
317 expect(dnt.headers.get("set-cookie")).toBeNull();
318 expect(made()).toBe(none + 2);
319 // A dead link mints nothing.
320 const gone = await http.handle(new Request(`${ORIGIN}/games/@pack/${token}x/survival.mrpack`, { method: "POST" }));
321 expect(gone.status).toBe(404);
322 expect(made()).toBe(none + 2);
323 // Past the client's cap the next link is refused with 429, no cookie, nothing counted.
324 const rows = app.db.prepare("INSERT INTO visitor_made (visitor_id, client, at) VALUES ('', ?, ?)");
325 const client = app.db.query<{ client: string }, []>("SELECT client FROM visitor_made ORDER BY rowid DESC LIMIT 1").get()!.client;
326 for (let i = 0; i < VISITOR_CAPS.perClient.perDay; i++) rows.run(client, Date.now());
327 const full = await link();
328 expect(full.status).toBe(429);
329 expect(full.headers.get("set-cookie")).toBeNull();
330 expect(await full.text()).toContain("sign in to make more");
331 });
332
333 test("a refused credential is refused by may (403), and a full forge by its cap (429): no cookie, nothing counted (#18189)", async () => {
334 const token = makeLink(app.db, box, "survival", "t2");
335 const file = `${ORIGIN}/games/@pack/${token}/survival.mrpack`;
336 const made = () => app.db.query<{ n: number }, [number]>("SELECT count(*) AS n FROM visitor_made WHERE at > ?").get(Date.now() - 86_400_000)!.n;
337 const before = made();
338 const link = (headers: Record<string, string>) => http.handle(new Request(file, { method: "POST", headers }));
339 // A credential sent and refused is a refused principal: not a visitor.
340 const bad = await link({ authorization: "Bearer not-a-token", "x-forwarded-for": "198.51.100.8" });
341 expect(bad.status).toBe(403);
342 expect(bad.headers.get("set-cookie")).toBeNull();
343 expect(await bad.text()).toContain("Sign in to make this.");
344 expect(made()).toBe(before);
345 // The forge's own cap, spent by other clients: the next link is refused whoever asks.
346 const rows = app.db.prepare("INSERT INTO visitor_made (visitor_id, client, at) VALUES ('', ?, ?)");
347 app.db.transaction(() => {
348 for (let i = before; i < VISITOR_CAPS.perForge.perDay; i++) rows.run(`other-${i}`, Date.now());
349 })();
350 const full = await link({ "x-forwarded-for": "198.51.100.9" });
351 expect(full.status).toBe(429);
352 expect(full.headers.get("set-cookie")).toBeNull();
353 expect(await full.text()).toContain("all it takes from visitors today");
354 expect(made()).toBe(VISITOR_CAPS.perForge.perDay);
355 });
356
290357 test("a link of 30 days ends at its time and when revoked; a viewer, and a server not theirs, cannot make one", async () => {
291358 const token = makeLink(app.db, box, "survival", "t", Date.now());
292359 expect(linkOf(app.db, token)).toEqual({ boxId: box.id, service: "survival" });

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

Keyboard shortcuts

Docs