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

Games: someone not linked is told each step to link, and everyone signed in has the button #17785

opened this

Merged 7h 31m ago, live in production

sold/game-link-words → main 0 commits 1 thread · 1 unresolved

  • Merged. sold/game-link-words was merged into main as 361c49e.

Review

Sign in to review this change.
7 files changed +157 −42
docs/features/games.md +2 −2
@@ -82,7 +82,7 @@ Creating it is one commit to the network's compose file: the service from the Pa
8282
8383 ## From in the game
8484
85 A player can ask the forge from a server's chat (#17284). Link the name first: **Link your Minecraft name** under Minecraft on the account page (`/settings`), or `L` on the terminal's Games screen (`src/tui/screens/games.ts`), gives a one-time code (6 characters, 10 minutes, kept only as its hash) shown only to the person signed in. In chat on any server of the box, type `!forge link 4F7QXZ`. The link binds the account to the name and to the player's UUID as the server itself lists it (`list uuids`, the same answer People keeps as who is online), never to anything typed in chat; a Bedrock name (`.Name`) links the same way. A name the server does not list yet is told to stay on and try again, and the code stays good. Five wrong codes for a name lock it out for an hour. The account page lists the linked names with Unlink, and `/games/<box>` lists who is linked there to an operator of the box (anyone else sees their own links) and, to its owner, the last commands and what came of each. The forge's words to a player in game are not in the service's console.
85 A player can ask the forge from a server's chat (#17284). Link the name first: **Link your Minecraft name** under Minecraft on the account page (`/settings`), or `L` on the terminal's Games screen (`src/tui/screens/games.ts`), gives a one-time code (6 characters, 10 minutes, kept only as its hash) shown only to the person signed in. The block is there for everyone signed in once the forge has a game box, and neither door gives a code before that: a link gives no role. In chat on any server of the box, type `!forge link 4F7QXZ`. The link binds the account to the name and to the player's UUID as the server itself lists it (`list uuids`, the same answer People keeps as who is online), never to anything typed in chat; a Bedrock name (`.Name`) links the same way. A name the server does not list yet is told to stay on and try again, and the code stays good. Five wrong codes for a name lock it out for an hour. The account page lists the linked names with Unlink, and `/games/<box>` lists who is linked there to an operator of the box (anyone else sees their own links) and, to its owner, the last commands and what came of each. The forge's words to a player in game are not in the service's console.
8686
8787 A linked name that holds any role on the server it types on, viewer too, can ask (`src/games/ask.ts`): `!forge who is on`, `why could I not join`, `what does survival need`, `is survival asleep`, `what is the address`. The forge answers from what it keeps, with no crew turn and no change (what a server needs may be looked up on Modrinth). Only those words and no more are a question. An answer names only servers the account has a role on, and the player's own refused joins there and nobody else's: a refusal by a server the account has no role on is answered as if it never was. "Why" repeats the server's own words for the refusal, as the proxy logged them, with network addresses (IPv4 and IPv6) taken out; nothing else in an answer is from a log. Questions count in the limits below.
8888
@@ -92,7 +92,7 @@ A linked name that holds operator on the server it types on can also say:
9292 - `!forge help`.
9393 - `!forge <anything else>`: a new Talk conversation of the linked account. The crew's first answer comes back in chat (its first lines, then a link to the conversation): nothing the account could not read on the forge itself.
9494
95 Anyone else gets a line saying how to link, and nothing runs. Replies are RCON `tellraw` to the player, at most 6 lines of 200 characters. An account runs at most 5 commands a minute and 30 an hour; past that the reply says when to try again. A refusal is answered and kept once a minute for a name on a box (once a minute for a whole box that is off), and one sync reads at most 3 commands a player and 20 in all. A suspended account's link says nothing. Commands, links and unlinks are kept, a link code never in clear.
95 Anyone else is told how to link (the settings page's address on this forge, the button's name, `!forge link <code>` and the 10 minutes), and nothing runs. A wrong or old code, and a link dropped because another player has the name, are answered with the same steps. Replies are RCON `tellraw` to the player, at most 6 lines of 200 characters. An account runs at most 5 commands a minute and 30 an hour; past that the reply says when to try again. A refusal is answered and kept once a minute for a name on a box (once a minute for a whole box that is off), and one sync reads at most 3 commands a player and 20 in all. A suspended account's link says nothing. Commands, links and unlinks are kept, a link code never in clear.
9696
9797 The sync only checks and keeps a command (`game_chat_job`); a plan, a commit or a message to the crew runs after it, one at a time for each box, and the next sync takes up what a restart left. The agent sends a batch of chat again under the same `chatId` until a sync is answered, and the forge skips one it has; a yes whose commit landed is not committed again.
9898
src/games/chat.ts +34 −15
@@ -25,6 +25,7 @@
2525 import type { App } from "../app.ts";
2626 import { talk } from "../actions/talk.ts";
2727 import { createConversation, listTurns } from "../core/conversations.ts";
28 import { publicOrigin } from "../core/public_origin.ts";
2829 import { getUserById, isActive, type User } from "../core/users.ts";
2930 import { blockedBy, blockedText } from "../kernel/blocked.ts";
3031 import { sha256 } from "../kernel/hash.ts";
@@ -37,6 +38,8 @@ import { proxyOf } from "./sleep.ts";
3738 import { LINES_OUT, listBoxes, mayDo, roleOn, SERVICE_NAME, type GameBox } from "./store.ts";
3839
3940 export const CODE_MS = 10 * 60_000;
41 /** Said where `newLinkCode` gives none. */
42 export const NO_LINK_HERE = "This forge has no game box to link a name on.";
4043 export const PENDING_MS = 5 * 60_000;
4144 export const PER_MINUTE = 5;
4245 export const PER_HOUR = 30;
@@ -104,8 +107,12 @@ export function exposedBackend(compose: string): string | undefined {
104107 }
105108 }
106109
107 /** A new one-time link code for `user`: what they type in game as `!forge link <code>`. */
108 export function newLinkCode(app: App, user: User, now = Date.now()): string {
110 /**
111 * A new one-time link code for `user`: what they type in game as `!forge link <code>`. None where
112 * the account page has no Minecraft block (`accountLinks`), at any door.
113 */
114 export function newLinkCode(app: App, user: User, now = Date.now()): string | undefined {
115 if (accountLinks(app, user) === undefined) return undefined;
109116 const bytes = crypto.getRandomValues(new Uint8Array(6));
110117 const code = [...bytes].map((b) => CODE_CHARS[b % CODE_CHARS.length]).join("");
111118 app.db.query("DELETE FROM game_link_code WHERE user_id = ?1 OR expires_at < ?2").run(user.id, new Date(now).toISOString());
@@ -132,22 +139,22 @@ export const linksOf = (app: App, userId: string): { boxId: string; player: stri
132139 .all(userId);
133140
134141 /**
135 * The account page's links in one statement, each with its box's name; undefined for a person who
136 * holds none and sees no game box (as `seesBox` says), so the page has nothing to offer them.
142 * The account page's links in one statement, each with its box's name; undefined where there is no
143 * game box to link a name on. A link gives no role, so the button is for everyone signed in.
137144 */
138145 export function accountLinks(app: App, user: User): { boxId: string; box: string | null; player: string; uuid: string; createdAt: string }[] | undefined {
139146 const rows = app.db
140147 .query<
141148 { boxId: string; box: string | null; player: string | null; uuid: string; createdAt: string },
142 [string, number]
149 [string]
143150 >(
144151 `SELECT l.box_id AS boxId, b.name AS box, l.player, l.uuid, l.created_at AS createdAt
145152 FROM (SELECT 1) LEFT JOIN game_link l ON l.user_id = ?1 LEFT JOIN game_box b ON b.id = l.box_id
146153 WHERE l.player IS NOT NULL
147 OR EXISTS (SELECT 1 FROM game_box g WHERE ?2 = 1 OR EXISTS (SELECT 1 FROM game_grant a WHERE a.box_id = g.id AND a.user_id = ?1))
154 OR EXISTS (SELECT 1 FROM game_box)
148155 ORDER BY l.created_at`,
149156 )
150 .all(user.id, user.isAdmin ? 1 : 0);
157 .all(user.id);
151158 return rows.length === 0 ? undefined : rows.flatMap((r) => (r.player === null ? [] : [{ ...r, player: r.player }]));
152159 }
153160
@@ -198,6 +205,11 @@ const audit = (
198205 .run(box.id, service, player, userId, kind, words.slice(0, 300), outcome.slice(0, 300), new Date(now).toISOString());
199206 };
200207
208 /** What there is, for someone not linked: nothing of this box or its network. */
209 const UNLINKED_HELP = [
210 "Linked, you can ask: who is on, why could I not join, what a server needs, is it asleep, what is the address.",
211 "An operator can also plan a new server and ask the crew.",
212 ];
201213 const OPERATOR_HELP = [
202214 "!forge give me a new void world with FAWE and bedwars: plans it, then !forge yes builds it.",
203215 "!forge <anything else>: asks the crew; the answer comes here.",
@@ -321,7 +333,7 @@ function one(
321333 const shown = /^link\b/i.test(words) ? "link ****" : words;
322334 // A refusal is kept and answered once a minute for this name (for a whole box that is off, whose
323335 // names mean nothing), however often it is typed: spam costs a read, not a row and a tellraw.
324 const refuse = (by: string, outcome: string, line: string, color = "red", whole = false): void => {
336 const refuse = (by: string, outcome: string, line: string | readonly string[], color = "red", whole = false): void => {
325337 const last = db
326338 .query(
327339 `SELECT 1 FROM game_chat WHERE box_id = ?1 AND (?2 = '' OR player = ?2) AND kind = 'refused' AND at > ?3 AND at <= ?4 LIMIT 1`,
@@ -330,10 +342,19 @@ function one(
330342 // Through the proxy each request is answered: its plugin holds a player to six a minute.
331343 if (last !== null && door === undefined) return;
332344 if (last === null) audit(app, box, service, player, by, "refused", shown, outcome, now);
333 say(db, box, at, [line], by, color);
345 say(db, box, at, typeof line === "string" ? [line] : line, by, color);
334346 };
347 // Short lines: a phone's chat is narrow.
348 const howToLink = [
349 `Open ${publicOrigin(app.config.url, origin)}/settings and sign in.`,
350 "Under Minecraft, press Link your Minecraft name.",
351 `Then type !forge link <code> here within ${String(CODE_MS / 60_000)} minutes.`,
352 ...(door === undefined ? [] : ["You are then shown six digits: type !forge yes and those digits."]),
353 ];
354 const lower = words.toLowerCase();
355 const help = lower === "" || lower === "help";
335356 const exposed = exposedBackend(compose);
336 if (exposed !== undefined) return refuse("", `off: ${exposed}`, `!forge is off on this network: ${exposed}.`, "red", true);
357 if (exposed !== undefined) return refuse("", `off: ${exposed}`, "!forge is off on this network; its owner can see why on the forge.", "red", true);
337358 // Linking: the code from the forge, once, within ten minutes; five wrong codes an hour a name.
338359 const typed = /^link\s+([A-Za-z0-9]{6})$/i.exec(words)?.[1];
339360 const codeHash = confirmed?.action === "link" ? confirmed.words : typed === undefined ? undefined : sha256(typed.toUpperCase());
@@ -350,7 +371,7 @@ function one(
350371 .get(codeHash, new Date(now).toISOString());
351372 if (code === null) {
352373 audit(app, box, service, player, "", "link", "link ****", "wrong code", now);
353 return say(db, box, at, ["That code is not one the forge gave, or it ran out: get a new one in your forge settings."], "", "red");
374 return say(db, box, at, ["That code is not one the forge gave, or it ran out.", ...howToLink], "", "red");
354375 }
355376 // The UUID the server lists for this name now; not listed, the code stays good for another try.
356377 const uuid = uuidNow();
@@ -390,18 +411,16 @@ function one(
390411 if (uuid !== linked.uuid) {
391412 db.query("DELETE FROM game_link WHERE box_id = ?1 AND player = ?2").run(box.id, player);
392413 audit(app, box, service, player, user.id, "refused", shown, "another player has the name: link dropped", now);
393 return say(db, box, at, [`${player} was linked as another player, so that link is gone: link again with a new code.`], "", "red");
414 return say(db, box, at, [`${player} was linked as another player, so that link is gone.`, ...howToLink], "", "red");
394415 }
395416 }
396417 if (user === undefined)
397 return refuse("", "not linked", "Link your name first: get a code under Minecraft in your forge settings, then type !forge link <code>.", "gray");
418 return refuse("", "not linked", [...(help ? UNLINKED_HELP : []), "Your Minecraft name is not linked yet.", ...howToLink], "gray");
398419 const role = roleOn(db, user, box.id, service);
399420 if (!mayDo(role, "viewer")) {
400421 const says = `${user.username} has no role on ${service}.`;
401422 return refuse(user.id, "no role", blockedText(blockedBy({ says, readerCan: false, who: "an owner of this game box", can: "give you one" })));
402423 }
403 const lower = words.toLowerCase();
404 const help = lower === "" || lower === "help";
405424 // A question only reads (`ask.ts`), so a viewer may ask; the rest takes an operator.
406425 const question = questionOf(words, service, serversSeen(app, user, box, compose));
407426 if (question === undefined && !help && !mayDo(role, "operator")) return refuse(user.id, "not an operator", `${user.username} is not an operator of ${service}.`);
src/tui/screens/games.ts +5 −2
@@ -65,7 +65,7 @@ import type { Session } from "../session.ts";
6565 import { fill, len, split } from "../ui/layout.ts";
6666 import { ListState, confirmScreen, drawList, promptScreen, type ListRow } from "./common.ts";
6767 import { commitServer, planRemoveServer, planServer, wishOn, type ServerPlan } from "../../games/presets.ts";
68 import { CODE_MS, linksOf, newLinkCode } from "../../games/chat.ts";
68 import { CODE_MS, linksOf, newLinkCode, NO_LINK_HERE } from "../../games/chat.ts";
6969 import type { PaletteEntry } from "./entries.ts";
7070 import { gameConfigScreen } from "./game_config.ts";
7171 import { gameModsScreen } from "./game_mods.ts";
@@ -218,7 +218,10 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen {
218218 if (!e.ctrl && !e.alt && e.key === "L" && f.user !== undefined) {
219219 const code = newLinkCode(f.app, f.user);
220220 const names = linksOf(f.app, f.user.id).map((l) => `${l.player}${l.uuid === "" ? " (link again)" : ""}`);
221 note = `In game, on a server you operate, type: !forge link ${code} (once, within ${CODE_MS / 60_000} minutes).${names.length === 0 ? "" : ` Linked: ${names.join(", ")}.`}`;
221 note =
222 code === undefined
223 ? NO_LINK_HERE
224 : `In game, type: !forge link ${code} (once, within ${CODE_MS / 60_000} minutes).${names.length === 0 ? "" : ` Linked: ${names.join(", ")}.`}`;
222225 ctx.invalidate();
223226 return true;
224227 }
src/web/pages/games.ts +3 −2
@@ -65,7 +65,7 @@ import { LOG_GONE, logReader, LOG_READER_CSS, logReaderJs, logRows, logViewOf, p
6565 import { flashTo, page } from "../layout.ts";
6666 import { avatar, badge, btn, disclosure, field as input, row, rowList, time } from "../ui.ts";
6767 import { watchBox } from "../../games/notify.ts";
68 import { accountLinks, chatLog, newLinkCode, playersOn, unlink } from "../../games/chat.ts";
68 import { accountLinks, chatLog, newLinkCode, NO_LINK_HERE, playersOn, unlink } from "../../games/chat.ts";
6969 import { commitServer, planRemoveServer, planServer, wishOn } from "../../games/presets.ts";
7070 import { commitJar, heldWords, leftWords, ONLY_PINNED, pinOf, PINS, planJar } from "../../games/proxy_jars.ts";
7171 import { canSleep, commitPolicy, EMPTY_SECONDS, isGameServer, policyOf, proxyOf, proxyPort, STILL_BILLED } from "../../games/sleep.ts";
@@ -194,7 +194,7 @@ export function gamesPage(ctx: Ctx): Response {
194194
195195 /**
196196 * The account page's Minecraft block (#17284): the person's linked names with Unlink, and a code to
197 * link another. Shown to anyone who sees a game box or holds a link.
197 * link another. Shown to everyone signed in where the forge has a game box: a link gives no role.
198198 */
199199 export function minecraftBlock(ctx: Ctx): Html | null {
200200 const links = accountLinks(ctx.app, ctx.auth.user!);
@@ -224,6 +224,7 @@ export async function gameLinkCode(ctx: Ctx): Promise<Response> {
224224 const form = await readForm(ctx, "rw");
225225 if (form instanceof Response) return form;
226226 const code = newLinkCode(ctx.app, ctx.auth.user);
227 if (code === undefined) return flashTo(ctx, "/settings", { tone: "danger", message: NO_LINK_HERE });
227228 return flashTo(ctx, "/settings", { message: `In game, on any server of the box, type: !forge link ${code} (within 10 minutes, once).` });

Next: '(within 10 minutes, once)' is typed here while the terminal's L builds it from CODE_MS. Use CODE_MS in both so the number has one source.

228229 }
229230
test/game-chat.test.ts +69 −21
@@ -80,6 +80,13 @@ const listUuids = (players: Record<string, string>): string => {
8080 return `There are ${String(names.length)} of a max of 20 players online: ${names.join(", ")}`;
8181 };
8282
83 /** What a player who is not linked is told, after why. */
84 const HOW_TO_LINK = [
85 "Open http://forge.test/settings and sign in.",
86 "Under Minecraft, press Link your Minecraft name.",
87 "Then type !forge link <code> here within 10 minutes.",
88 ];
89
8390 describe("the chat line", () => {
8491 test("Paper's and Fabric's own chat lines are commands; Bedrock names too", () => {
8592 expect(chatCommand(paper("ada", "!forge help"), "paper")).toEqual({ player: "ada", words: "help" });
@@ -297,8 +304,8 @@ describe("on a forge", () => {
297304 const aMinuteOn = () => chatAged(app.db, 61_000, "refused");
298305 const link = async (user: User, player: string, service = "hub") => {
299306 const code = newLinkCode(app, user);
300 await sync({ [service]: [paper(player, `!forge link ${code.toLowerCase()}`)] });
301 return code;
307 await sync({ [service]: [paper(player, `!forge link ${code!.toLowerCase()}`)] });
308 return code!;
302309 };
303310
304311 beforeAll(async () => {
@@ -360,17 +367,31 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"The hub re
360367
361368 test("a name nobody linked is told how, and nothing runs", async () => {
362369 await sync({ hub: [paper("eve", "!forge give me a flat world called heist")] });
363 expect(told()).toEqual([
364 {
365 service: "hub",
366 to: "eve",
367 text: "Link your name first: get a code under Minecraft in your forge settings, then type !forge link <code>.",
368 color: "gray",
369 },
370 ]);
370 expect(told().map((t) => [t.service, t.to, t.text, t.color])).toEqual(
371 ["Your Minecraft name is not linked yet.", ...HOW_TO_LINK].map((text) => ["hub", "eve", text, "gray"]),
372 );
371373 expect(chatLog(app, box().id, 1)[0]).toMatchObject({ player: "eve", kind: "refused", outcome: "not linked" });
372374 });
373375
376 test("the address is the forge's configured one, not the one the box reached it at", async () => {
377 const config = app.config as { url?: string };
378 const was = config.url;
379 try {
380 config.url = "https://play.example/";
381 aMinuteOn();
382 await sync({ hub: [paper("eve", "!forge help")] });
383 } finally {
384 if (was === undefined) delete config.url;
385 else config.url = was;
386 }
387 const said = told().map((t) => t.text);
388 expect(said).toContain("Open https://play.example/settings and sign in.");
389 // Help with no link: what there is, then how to link, in the six lines chat has.
390 expect(said[0]).toStartWith("Linked, you can ask: ");
391 expect(said).toHaveLength(6);
392 expect(said.every((line) => line.length <= 120)).toBe(true);
393 });
394
374395 test("a code links the name once; a wrong code is counted, and no code is kept in clear", async () => {
375396 const code = await link(ada, "ada");
376397 expect(told()).toEqual([
@@ -380,7 +401,7 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"The hub re
380401 expect(playersOn(app, box().id)).toMatchObject([{ player: "ada", username: "ada" }]);
381402 // Used once: the same code from another name does nothing.
382403 await sync({ hub: [paper("mallory", `!forge link ${code}`)] });
383 expect(told()[0]!.text).toStartWith("That code is not one the forge gave");
404 expect(told().map((t) => t.text)).toEqual(["That code is not one the forge gave, or it ran out.", ...HOW_TO_LINK]);
384405 for (let i = 0; i < 5; i++) await sync({ hub: [paper("mallory", "!forge link ZZZZZZ")] });
385406 told();
386407 // Locked out after five, even with a good code.
@@ -487,7 +508,7 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"The hub re
487508 {
488509 service: "hub",
489510 to: "ada",
490 text: "!forge is off on this network: hub is reachable without the proxy, so a name in its chat cannot be trusted.",
511 text: "!forge is off on this network; its owner can see why on the forge.",
491512 color: "red",
492513 },
493514 ]);
@@ -514,13 +535,15 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"The hub re
514535 expect(linked("grace")).toHaveLength(1);
515536 // The name online as another player (a new owner of the name): refused, and the link dropped.
516537 await sync({ hub: [paper("grace", "!forge help")] }, { hub: { grace: "11111111-2222-4333-8444-555555555555" } });
517 expect(told()[0]!).toMatchObject({ to: "grace", text: "grace was linked as another player, so that link is gone: link again with a new code.", color: "red" });
538 const gone = told();
539 expect(gone[0]!).toMatchObject({ to: "grace", text: "grace was linked as another player, so that link is gone.", color: "red" });
540 expect(gone.slice(1).map((t) => t.text)).toEqual(HOW_TO_LINK);
518541 expect(linked("grace")).toEqual([]);
519542 expect(chatLog(app, box().id, 1)[0]).toMatchObject({ player: "grace", kind: "refused", outcome: "another player has the name: link dropped" });
520543 // A link from before UUIDs were bound has none, and goes the same way.
521544 app.db.query("INSERT INTO game_link (box_id, player, user_id, created_at) VALUES (?1, 'olden', ?2, ?3)").run(box().id, bob.id, new Date().toISOString());
522545 await sync({ hub: [paper("olden", "!forge help")] });
523 expect(told()[0]!.text).toBe("olden was linked as another player, so that link is gone: link again with a new code.");
546 expect(told()[0]!.text).toBe("olden was linked as another player, so that link is gone.");
524547 expect(linked("olden")).toEqual([]);
525548 // A UUID typed in chat is only words: the binding is the server's list.
526549 expect(chatCommand(paper("grace", `!forge link ${code} ${grace}`), "paper")?.words).toBe(`link ${code} ${grace}`);
@@ -583,13 +606,14 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"The hub re
583606 const rows = () => app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM game_chat").get()!.n;
584607 const before = rows();
585608 for (let i = 0; i < 10; i++) await sync({ hub: Array.from({ length: 20 }, () => paper("spam", "!forge hi")) });
586 expect(told()).toHaveLength(1);
609 // One answer, of four lines.
610 expect(told()).toHaveLength(4);
587611 expect(rows() - before).toBe(1);
588612 await sync({ hub: [...Array.from({ length: 19 }, () => paper("spam", "!forge hi")), paper("quiet", "!forge hi")] });
589 expect(told().map((t) => t.to)).toEqual(["quiet"]);
613 expect(told().map((t) => t.to)).toEqual(["quiet", "quiet", "quiet", "quiet"]);
590614 aMinuteOn();
591615 await sync({ hub: [paper("spam", "!forge hi")] });
592 expect(told()).toHaveLength(1);
616 expect(told()).toHaveLength(4);
593617 });
594618
595619 test("a slow plan does not hold the sync, and a batch sent twice runs once", async () => {
@@ -626,7 +650,7 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"The hub re
626650 expect((await readCompose(app, box()))!.sha).toBe(tip);
627651 });
628652
629 test("the account page's one read: every link with its box's name and UUID, none for who sees no box", async () => {
653 test("the account page's one read: every link with its box's name and UUID, the button for everyone signed in where there is a game box", async () => {
630654 const people = await Promise.all(
631655 ["cleo", "dan"].map((username) =>
632656 createUser(app.db, { username, email: `${username}@f.test`, password: "a-good-passphrase", origin: "seed", trusted: true }),
@@ -636,8 +660,27 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"The hub re
636660 if (!p.ok) throw new Error(p.error);
637661 return p.value;
638662 }) as [User, User];
639 // No grant and no link: nothing to offer. A grant alone: the block, with no link in it.
640 expect(accountLinks(app, cleo)).toBeUndefined();
663 // No grant and no link: the block, with no link in it, and nothing of the box. Without any game box: no block.
664 expect(accountLinks(app, cleo)).toEqual([]);
665 app.db.run("BEGIN");
666 try {
667 app.db.run("DELETE FROM game_box");
668 expect(accountLinks(app, cleo)).toBeUndefined();
669 expect(newLinkCode(app, cleo)).toBeUndefined();
670 } finally {
671 app.db.run("ROLLBACK");
672 }
673 const cleoCookie = { cookie: `forge_session=${createSession(app.db, cleo.id).token}` };
674 const hers = await (await http.handle(new Request("http://forge.test/settings", { headers: cleoCookie }))).text();
675 expect(hers).toContain('action="/settings/minecraft/code"');
676 const block = hers.slice(hers.indexOf("data-from-game"), hers.indexOf("</section>", hers.indexOf("data-from-game")));
677 for (const word of [">mc<", "on mc", "survival", "hub", "ada"]) expect(block).not.toContain(word);
678 // The button gives a code, and a link gives no role: what it may do stays with the account.
679 const made = await http.handle(new Request("http://forge.test/settings/minecraft/code", { method: "POST", headers: { ...cleoCookie, origin: "http://forge.test" }, body: new FormData() }));
680 expect(made.status).toBe(303);
681 // Signed out, the button's address makes no code.
682 const outside = await http.handle(new Request("http://forge.test/settings/minecraft/code", { method: "POST", headers: { origin: "http://forge.test" }, body: new FormData() }));
683 expect(outside.headers.get("location") ?? "").not.toStartWith("/settings");
641684 grant(app.db, box().id, cleo.id, "viewer", "hub");
642685 expect(accountLinks(app, cleo)).toEqual([]);
643686 // Two real links, in the order they were made; no grant needed to see one's own.
@@ -652,7 +695,12 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"The hub re
652695 expect(accountLinks(app, cleo)).toEqual([]);
653696 grant(app.db, box().id, cleo.id, "none", "hub");
654697 grant(app.db, "gone", cleo.id, "viewer");
655 expect(accountLinks(app, cleo)).toBeUndefined();
698 expect(accountLinks(app, cleo)).toEqual([]);
699 await link(cleo, "cleo_mc");
700 told();
701 aMinuteOn();
702 await sync({ hub: [paper("cleo_mc", "!forge help")] });
703 expect(told()[0]!.text).toStartWith("cleo has no role on hub.");
656704 // The page shows them.
657705 const cookie = `forge_session=${createSession(app.db, dan.id).token}`;
658706 const page = await (await http.handle(new Request("http://forge.test/settings", { headers: { cookie } }))).text();
test/game-door.test.ts +18
@@ -116,6 +116,24 @@ test("a question is answered at once, to its request, and a request sent again i
116116 expect(await send([ask])).toEqual([]);
117117 });
118118
119 test("help with no link says what there is and each step to link, with /forge and nothing of the network", async () => {
120 const kit = { uuid: "00000000-0000-4000-8000-00000000000c", name: "kit" };
121 const [answer] = await send([request("help", kit)]);
122 const lines = answer!.text.split("\n");
123 expect(lines[0]).toStartWith("Linked, you can ask: ");
124 expect(lines.slice(2)).toEqual([
125 "Your Minecraft name is not linked yet.",
126 "Open http://forge.test/settings and sign in.",
127 "Under Minecraft, press Link your Minecraft name.",
128 "Then type /forge link <code> here within 10 minutes.",
129 "You are then shown six digits: type /forge yes and those digits.",
130 ]);
131 for (const word of ["!forge", "mc", "hub", "survival", "ada", "play.example"]) expect(answer!.text).not.toContain(word);
132 // Anything else with no link is the steps alone.
133 const [other] = await send([request("who is on", kit)]);
134 expect(other!.text.split("\n")).toEqual(lines.slice(2));
135 });
136
119137 test("every request in a sync is answered, a repeated refusal too", async () => {
120138 const asks = Array.from({ length: 4 }, () => request("help", { uuid: EVE, name: "eve" }));
121139 expect((await send(asks)).map((a) => a.id)).toEqual(asks.map((a) => a.id));
test/tui-games.test.ts +26
@@ -285,6 +285,32 @@ test("L on the games list shows a one-time !forge link code to the person signed
285285 }
286286 });
287287
288 test("L gives a code to someone signed in with no role, and none where the forge has no game box, as the page", async () => {
289 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "dora", email: "[email protected]", password: "a-good-passphrase" });
290 if (!made.ok) throw new Error(made.error);
291 const { tui, session, terminal, type } = drive(made.value, 200);
292 try {
293 tui.ctx.push(gamesScreen(session, tui.ctx));
294 await settleApp(tui);
295 const codes = () => app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM game_link_code WHERE user_id = ?1").get(made.value.id)!.n;
296 app.db.run("BEGIN");
297 try {
298 app.db.run("DELETE FROM game_box");
299 terminal.feed("L");
300 expect(codes()).toBe(0);
301 } finally {
302 app.db.run("ROLLBACK");
303 }
304 await settleApp(tui);
305 expect(tui.screen.toText()).toContain("This forge has no game box to link a name on.");
306 await type("L");
307 expect(tui.screen.toText()).toMatch(/In game, type: !forge link [2-9A-Z]{6} \(once, within 10 minutes\)/);
308 expect(codes()).toBe(1);
309 } finally {
310 tui.stop?.();
311 }
312 });
313
288314 test("the terminal's box screen says what the page says about spare, unknown before a day of samples (#17576)", async () => {
289315 const { tui, session } = drive(alice, 200);
290316 tui.ctx.push(gameBoxScreen(session, tui.ctx, boxNamed(app.db, "net")!));

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

Keyboard shortcuts

Docs