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

Game door: lock automatically when the player leaves the network, as a setting (#18247) #18329

opened this

Merged 5h 50m ago, live in production

mason/forge:mason/18314-game-door-lock-automatically-when-the-pl → main 0 commits fork 4 threads · 4 unresolved

  • Merged. mason/18314-game-door-lock-automatically-when-the-pl was merged into main as f698c54.

Review

Sign in to review this change.
9 files changed +314 −6
docs/features/games.md +1 −1

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

View file
src/core/migration-pins/20261205012816-game-door-lock-on-leave.pin added +1
@@ -0,0 +1,1 @@
1 46ade3af1ca3f0818c32e3709ee9771206331f434b5b9d1a19d6b5d9810ef5f2
src/core/migrations/20261205012816-game-door-lock-on-leave.ts added +6
@@ -0,0 +1,6 @@
1 // The game door's lock-on-leave setting (#18314): per box, whether the door locks by itself when
2 // the player who opened the write window leaves the network. Off unless the owner turns it on.
3 // Additive.
4 export default `
5 ALTER TABLE game_door ADD COLUMN lock_on_leave INTEGER NOT NULL DEFAULT 0;
6 `;
src/games/door_leave.ts added +83
@@ -0,0 +1,83 @@
1 /**
2 * The door locks by itself when the player who opened the write window leaves the network
3 * (#18314), for a box whose owner turned that on (`write_window.ts`). Plain data in: the names
4 * that left in one sync. A window opens from the web with a passkey, so the player is the opener's
5 * linked Minecraft name on the box; a name that left while another of the opener's names, or the
6 * same name on another server, is still on the network does not lock. Only an open window is
7 * locked: a closed door already holds writes, and a locked one is locked.
8 */
9
10 import type { Database } from "bun:sqlite";
11 import { createLog } from "../kernel/log.ts";
12 import { networkOf, peopleOf } from "./people.ts";
13 import { SERVICE_NAME } from "./store.ts";
14 import { doorOf, lockDoor, locksOnLeave } from "./write_window.ts";
15
16 const log = createLog("games");
17
18 /** Said in the audit row for the lock. */
19 export const LEFT_WORDS = "locked: the player who opened the window left the network";
20
21 /** Names on any server of the box now, lowercase: each server's list, and the proxy's glist. */
22 function onNetwork(db: Database, boxId: string): Set<string> {
23 const names = new Set<string>();
24 const services = db.query<{ name: string }, [string]>("SELECT name FROM game_service WHERE box_id = ?1").all(boxId);
25 for (const s of services) if (SERVICE_NAME.test(s.name)) for (const p of peopleOf(db, boxId, s.name).online) names.add(p.name.toLowerCase());
26 for (const list of Object.values(networkOf(db, boxId))) for (const n of list) names.add(n.toLowerCase());
27 return names;
28 }
29
30 /**
31 * The names of the account that opened the window now open, lowercase; undefined when none is open.
32 */
33 function openerNames(db: Database, boxId: string, now: number): { by: string; names: string[] } | undefined {
34 const door = doorOf(db, boxId, now);
35 if (door.state !== "open") return undefined;
36 const names = db
37 .query<{ player: string }, [string, string]>("SELECT player FROM game_link WHERE box_id = ?1 AND user_id = ?2")
outdated

Empty case: an opener with no game_link row makes mine empty, so this returns undefined every time and the door never locks, while the page says it will. Surface that to the owner or lock on any leave.

38 .all(boxId, door.by)
39 .map((r) => r.player.toLowerCase());
40 return { by: door.by, names };
41 }
42
43 /**
44 * Whether the setting is on and the open window's opener has no linked name, so it can lock
45 * nothing.
46 */
47 export const leaveCannotLock = (db: Database, boxId: string, now = Date.now()): boolean =>
48 locksOnLeave(db, boxId) && openerNames(db, boxId, now)?.names.length === 0;
49
50 /**
51 * Locks the box's door when `left` (names that left in this sync) holds a name linked to the
52 * window's opener that is on no server now. Returns the name that locked it, or undefined.
53 */
54 export function lockWhenLeft(db: Database, boxId: string, left: readonly string[], now = Date.now()): string | undefined {
55 try {
56 return lockIfLeft(db, boxId, left, now);
57 } catch (e) {
58 // The sync's data is stored by now: a failed lock is logged, and the sync still succeeds.
59 log.warn("game door: lock on leave failed", { box: boxId, why: e instanceof Error ? e.message : String(e) });
60 return undefined;
61 }
62 }
63
64 function lockIfLeft(db: Database, boxId: string, left: readonly string[], now: number): string | undefined {
65 if (left.length === 0 || !locksOnLeave(db, boxId)) return undefined;
66 const opener = openerNames(db, boxId, now);
67 if (opener === undefined) return undefined;
68 const door = { by: opener.by };
69 const mine = opener.names;
70 const gone = left.find((n) => mine.includes(n.toLowerCase()));
71 if (gone === undefined) return undefined;
72 const here = onNetwork(db, boxId);
73 if (mine.some((n) => here.has(n))) return undefined;
74 lockDoor(db, boxId, door.by, now);
75 db.query("INSERT INTO game_chat (box_id, service, player, user_id, kind, words, outcome, at, door, write_window) VALUES (?1, '', ?2, ?3, 'lock', 'left the network', ?4, ?5, '', 'locked')").run(
76 boxId,
77 gone,
78 door.by,
79 LEFT_WORDS,
80 new Date(now).toISOString(),
81 );
82 return gone;
83 }
src/games/metrics.ts +3
@@ -12,6 +12,7 @@
1212 */
1313
1414 import type { Database } from "bun:sqlite";
15 import { lockWhenLeft } from "./door_leave.ts";
1516 import { noteReading } from "./lent_proof.ts";
1617 import { SERVICE_NAME, type GameBox } from "./store.ts";
1718 import type { SpareSample, SpareService } from "./spare.ts";
@@ -340,6 +341,8 @@ export function recordMetrics(db: Database, box: Pick<GameBox, "id">, body: Metr
340341 db.query("DELETE FROM game_player_event WHERE box_id = ?1 AND service = ?2 AND id <= (SELECT id FROM game_player_event WHERE box_id = ?1 AND service = ?2 ORDER BY id DESC LIMIT 1 OFFSET ?3)").run(box.id, service, EVENTS_KEPT);
341342 }
342343 })();
344 // The player who opened a write window leaving may lock the door (#18314).
345 lockWhenLeft(db, box.id, events.filter((e) => e.kind === "leave").map((e) => e.player), now.getTime());

Runs outside the transaction, unguarded. A throw here fails the sync after the data is stored and the agent retries the same lines. Catch and log it.

343346 }
344347
345348 // ---- reading ----------------------------------------------------------------------------------
src/games/write_window.ts +24
@@ -76,6 +76,30 @@ export function lockDoor(db: Database, boxId: string, userId: string, now = Date
7676 return doorOf(db, boxId, now);
7777 }
7878
79 /**
80 * Whether the box's door locks by itself when the player who opened the window leaves the network
81 * (#18314).
82 */
83 export const locksOnLeave = (db: Database, boxId: string): boolean =>
84 db.query<{ lock_on_leave: number }, [string]>("SELECT lock_on_leave FROM game_door WHERE box_id = ?1").get(boxId)?.lock_on_leave === 1;
85
86 /**
87 * Sets whether the door locks when the player who opened the window leaves; off until the owner
88 * turns it on.
89 */
90 export function setLocksOnLeave(db: Database, boxId: string, on: boolean): void {
91 db.query("INSERT INTO game_door (box_id, lock_on_leave) VALUES (?1, ?2) ON CONFLICT (box_id) DO UPDATE SET lock_on_leave = ?2").run(boxId, on ? 1 : 0);
92 }
93
94 /**
95 * The setting in words, the same on the page and the terminal. `unlinked`: the window now open was
96 * opened by someone with no linked Minecraft name on the box, so leaving cannot lock it.
97 */
98 export const leaveWords = (on: boolean, unlinked = false): string =>
99 on
100 ? `Locks by itself when the player who opened the window, as their linked Minecraft name, leaves the network; a passkey opens it again.${unlinked ? " The open window was opened by someone with no linked name on this box, so nothing will lock it: lock it yourself." : ""}`
101 : "Off: the door does not lock when the player who opened the window leaves.";
102
79103 /**
80104 * The length of the next window, from what a person typed: whole minutes, 5 to 720. Undefined when
81105 * it is not one.
src/tui/screens/games.ts +6 −3
@@ -29,6 +29,7 @@ import { containersIn, figuresOf } from "../../cloud/containers.ts";
2929 import { joinAddress, NO_ADDRESS, nowWords, powerNow, PREVIEW_WORDS, privateWords, SAVE_WORDS } from "../../games/gist.ts";
3030 import { findingLine, findingsOf as kickFindingsOf } from "../../games/findings.ts";
3131 import { eventsOf, eventWords, isBedrock, peopleOf, peopleWords, queuePeople } from "../../games/people.ts";
32 import { leaveCannotLock } from "../../games/door_leave.ts";
3233 import { openDoorWords } from "../../games/reach.ts";
3334 import { findingsOf } from "../../games/player_events.ts";
3435 import { queueWorld, type WorldOp } from "../../games/worlds.ts";
@@ -42,7 +43,7 @@ import { heldLines, heldOn } from "../../games/hold.ts";
4243 import { askPower, refusesNow, type Power } from "../../games/power.ts";
4344 import { cloudLine, pinnedOfBox } from "../../actions/cloud_says.ts";
4445 import { getUserById, getUserByName } from "../../core/users.ts";
45 import { doorOf, doorWords, lockDoor, WINDOW_WHY } from "../../games/write_window.ts";
46 import { doorOf, doorWords, leaveWords, lockDoor, locksOnLeave, setLocksOnLeave, WINDOW_WHY } from "../../games/write_window.ts";
4647 import { commitServiceEnv, readCompose, serviceEnv } from "../../games/compose.ts";
4748 import { commitSettings, planSettings, settingsOf, type SettingsPlan, type SettingValue } from "../../games/settings.ts";
4849 import {
@@ -644,7 +645,7 @@ export function gameBoxScreen(f: Session, ctx: Ctx, box: GameBox): Screen {
644645 // The game door (#18296), as /games/<box>'s block: `w` locks it; a window opens on the web
645646 // alone, with a passkey.
646647 const door = mayDo(roleOn(f.app.db, f.user, b.id), "owner")
647 ? [`Game door: ${doorWords(doorOf(f.app.db, b.id), (id) => getUserById(f.app.db, id)?.username ?? "someone")}`, WINDOW_WHY, ""].flatMap((l) => (l === "" ? [""] : wrap(l, w)))
648 ? [`Game door: ${doorWords(doorOf(f.app.db, b.id), (id) => getUserById(f.app.db, id)?.username ?? "someone")}`, WINDOW_WHY, leaveWords(locksOnLeave(f.app.db, b.id), leaveCannotLock(f.app.db, b.id)), ""].flatMap((l) => (l === "" ? [""] : wrap(l, w)))
648649 : [];
649650 const spare = [spareRow(f.app.db, f.app.config.dataDir, b).map(([k, v]) => `${k}: ${v}.`).join(" "), ""];
650651 if (!mayDo(roleOn(f.app.db, f.user, b.id), "owner")) {
@@ -658,7 +659,7 @@ export function gameBoxScreen(f: Session, ctx: Ctx, box: GameBox): Screen {
658659 };
659660 return {
660661 title: `${box.name}: the box`,
661 keys: [binding(["j", "k"], "scroll"), binding(["l"], "run checks while servers sleep: switch"), binding(["w"], "lock the game door"), binding(["p"], "spark profiles")],
662 keys: [binding(["j", "k"], "scroll"), binding(["l"], "run checks while servers sleep: switch"), binding(["w"], "lock the game door"), binding(["a"], "lock when the player leaves: switch"), binding(["p"], "spark profiles")],
662663 render(area, s) {
663664 const c = ctx.theme.c;
664665 const all = lines(Math.max(10, area.w));
@@ -679,6 +680,8 @@ export function gameBoxScreen(f: Session, ctx: Ctx, box: GameBox): Screen {
679680 setLend(f.app.db, b, lentRunnerOf(f.app.db, b.id) === undefined, f.user.id);
680681 } else if (e.key === "w" && mayDo(roleOn(f.app.db, f.user, box.id), "owner") && f.user !== undefined) {
681682 lockDoor(f.app.db, box.id, f.user.id);
683 } else if (e.key === "a" && mayDo(roleOn(f.app.db, f.user, box.id), "owner")) {
684 setLocksOnLeave(f.app.db, box.id, !locksOnLeave(f.app.db, box.id));
682685 } else return false;
683686 ctx.invalidate();
684687 return true;
src/web/pages/games_door.ts +15 −2
@@ -8,7 +8,8 @@
88 import { passkeyProves, proofChallenge, PROOF_FIELDS } from "../../actions/passkey_proof.ts";
99 import { passkeyIds } from "../../core/passkeys.ts";
1010 import { getUserById } from "../../core/users.ts";
11 import { doorOf, doorWords, lockDoor, openWindow, setWindowMinutes, WINDOW_WHY, windowMinutes } from "../../games/write_window.ts";
11 import { doorOf, doorWords, leaveWords, lockDoor, locksOnLeave, openWindow, setLocksOnLeave, setWindowMinutes, WINDOW_WHY, windowMinutes } from "../../games/write_window.ts";
12 import { leaveCannotLock } from "../../games/door_leave.ts";
1213 import type { GameBox } from "../../games/store.ts";
1314 import { crossOrigin, type Ctx } from "../../http/context.ts";
1415 import { json } from "../../http/respond.ts";
@@ -31,6 +32,7 @@ export function doorBlock(ctx: Ctx, box: GameBox): { readonly html: Html; readon
3132 const d = doorOf(ctx.app.db, box.id);
3233 const passkey = passkeyIds(ctx.app.db, ctx.auth.user!.id).length > 0;
3334 const action = `/games/${box.name}/door`;
35 const leave = locksOnLeave(ctx.app.db, box.id);
3436 return {
3537 passkey,
3638 html: html`<section class="settings-block" id="door" data-door="${d.state}">
@@ -55,6 +57,12 @@ export function doorBlock(ctx: Ctx, box: GameBox): { readonly html: Html; readon
5557 ${btn("Save", { type: "submit", variant: "ghost" })}
5658 </form>
5759 <p class="muted small" data-door-why>${WINDOW_WHY}</p>
60 <form method="post" action="${action}" class="row-fields mt" data-door-leave="${leave ? "on" : "off"}">
61 <input type="hidden" name="op" value="leave" />
62 <input type="hidden" name="on" value="${leave ? "off" : "on"}" />
63 <p class="small" data-door-leave-says>${leaveWords(leave, leaveCannotLock(ctx.app.db, box.id))}</p>
64 ${btn(leave ? "Stop locking when the player leaves" : "Lock when the player leaves", { type: "submit", variant: "secondary" })}
65 </form>
outdated

Principle 1: leaveWords above and this LEAVE_WHY paragraph say the same thing twice. Keep one.

5866 </section>`,
5967 };
6068 }
@@ -83,13 +91,18 @@ export async function gameDoorSubmit(ctx: Ctx): Promise<Response> {
8391 lockDoor(ctx.app.db, box.id, user.id);
8492 return flashTo(ctx, back, { message: "Locked: the game door only reads now." });
8593 }
94 if (op === "leave") {
95 const on = field(form, "on") === "on";
96 setLocksOnLeave(ctx.app.db, box.id, on);
97 return flashTo(ctx, back, { message: leaveWords(on) });
98 }
8699 if (op === "minutes") {
87100 const minutes = windowMinutes(field(form, "minutes"));
88101 if (minutes === undefined) return flashTo(ctx, back, { tone: "danger", message: "A window is 5 to 720 whole minutes." });
89102 setWindowMinutes(ctx.app.db, box.id, minutes);
90103 return flashTo(ctx, back, { message: `The next write window lasts ${String(minutes)} minutes.` });
91104 }
92 if (op !== "open") return flashTo(ctx, back, { tone: "danger", message: "Lock, open or set the length." });
105 if (op !== "open") return flashTo(ctx, back, { tone: "danger", message: "Lock, open, set the length or choose whether it locks when the player leaves." });
93106 const answer = Object.fromEntries(PROOF_FIELDS.map((n) => [n, field(form, n)])) as Record<(typeof PROOF_FIELDS)[number], string>;
94107 if (answer.challenge === "" || !(await passkeyProves(ctx.app, user.id, answer, { origin: ctx.url.origin, rpId: ctx.url.hostname })))
95108 return flashTo(ctx, back, { tone: "danger", message: `${PASSKEY_REJECTED} The game door stays as it was.` });
test/game-door-lock-on-leave.test.ts added +175
@@ -0,0 +1,175 @@
1 /**
2 * The game door locks by itself when the player who opened the write window leaves the network
3 * (#18314), only when the owner turned that on; a passkey opens it again. Both doors set it.
4 */
5 import { afterAll, beforeAll, beforeEach, expect, test } from "bun:test";
6 import { mkdtempSync } from "node:fs";
7 import { rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { createSession } from "../src/core/sessions.ts";
12 import { createUser, type User } from "../src/core/users.ts";
13 import { recordMetrics } from "../src/games/metrics.ts";
14 import { boxNamed, createGameBox, grant, type GameBox } from "../src/games/store.ts";
15 import { doorOf, locksOnLeave, openWindow, setLocksOnLeave } from "../src/games/write_window.ts";
16 import { forgeHttp } from "../src/http/server.ts";
17 import { createForgeApp } from "../src/tui/forge.ts";
18 import { gameBoxScreen } from "../src/tui/screens/games.ts";
19 import { headlessTerminal } from "../src/tui/term/terminal.ts";
20 import { leaveCannotLock } from "../src/games/door_leave.ts";
21 import { settleApp } from "./helpers/tui.ts";
22 import { quietLogs } from "./helpers/globals.ts";
23
24 quietLogs();
25
26 let dir = "";
27 let app: App;
28 let ada: User;
29 let box: GameBox;
30 const paper = (rest: string): string => `[12:00:01 INFO]: ${rest}`;
31 const say = (...lines: string[]): void => recordMetrics(app.db, box, { logs: { hub: lines } });
32 const online = (...names: string[]): void => {
33 app.db.query("UPDATE game_service SET online_json = ?1 WHERE box_id = ?2").run(JSON.stringify(names.map((name) => ({ name, uuid: "" }))), box.id);
34 };
35
36 beforeAll(async () => {
37 dir = mkdtempSync(join(tmpdir(), "forge-door-leave-"));
38 app = createApp({ dataDir: dir, port: 0, host: "forge.test" });
39 const u = await createUser(app.db, { username: "ada", email: "[email protected]", password: "a-good-passphrase", origin: "seed", isAdmin: true, trusted: true });
40 if (!u.ok) throw new Error(u.error);
41 ada = u.value;
42 createGameBox(app.db, { name: "mc" });
43 box = boxNamed(app.db, "mc")!;
44 grant(app.db, box.id, ada.id, "owner");
45 app.db.query("INSERT INTO game_service (box_id, name) VALUES (?1, 'hub')").run(box.id);
46 });
47 beforeEach(() => {
48 app.db.query("DELETE FROM game_door").run();
49 app.db.query("DELETE FROM game_link").run();
50 app.db.query("DELETE FROM game_chat").run();
51 app.db.query("INSERT INTO game_link (box_id, player, user_id, uuid, created_at) VALUES (?1, 'Alice', ?2, 'u-1', '')").run(box.id, ada.id);
52 online();
53 });
54 afterAll(async () => {
55 app.close();
56 await rm(dir, { recursive: true, force: true });
57 });
58
59 test("off by default: the opener leaving leaves the window open", () => {
60 openWindow(app.db, box.id, ada.id);
61 expect(locksOnLeave(app.db, box.id)).toBe(false);
62 say(paper("Alice left the game"));
63 expect(doorOf(app.db, box.id).state).toBe("open");
64 });
65
66 test("on: the opener's linked name leaving locks the door, with an audit row", () => {
67 setLocksOnLeave(app.db, box.id, true);
68 openWindow(app.db, box.id, ada.id);
69 say(paper("Alice left the game"));
70 expect(doorOf(app.db, box.id).state).toBe("locked");
71 const row = app.db.query<{ kind: string; player: string; write_window: string; outcome: string }, [string]>("SELECT kind, player, write_window, outcome FROM game_chat WHERE box_id = ?1").get(box.id)!;
72 expect(row).toMatchObject({ kind: "lock", player: "Alice", write_window: "locked" });
73 expect(row.outcome).toContain("left the network");
74 });
75
76 test("on: someone else leaving, or the opener still on the network, locks nothing", () => {
77 setLocksOnLeave(app.db, box.id, true);
78 openWindow(app.db, box.id, ada.id);
79 say(paper("Bob left the game"));
80 expect(doorOf(app.db, box.id).state).toBe("open");
81 online("Alice");
82 say(paper("Alice left the game"));
83 expect(doorOf(app.db, box.id).state).toBe("open");
84 });
85
86 test("on: a closed door stays closed, and the setting survives opening a window", () => {
87 setLocksOnLeave(app.db, box.id, true);
88 say(paper("Alice left the game"));
89 expect(doorOf(app.db, box.id).state).toBe("closed");
90 openWindow(app.db, box.id, ada.id);
91 expect(locksOnLeave(app.db, box.id)).toBe(true);
outdated

The title says the terminal sets it but only the page is exercised. Add a test that presses a on the box screen, and that a non-owner's a and a non-owner's op=leave post change nothing.

92 });
93
94 test("the page sets it, and refuses another origin", async () => {
95 const http = forgeHttp(app);
96 const cookie = `forge_session=${createSession(app.db, ada.id).token}`;
97 const post = (form: Record<string, string>, origin = "http://forge.test") =>
98 http.handle(new Request("http://forge.test/games/mc/door", { method: "POST", headers: { cookie, origin, "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(form) }));
99 expect((await post({ op: "leave", on: "on" }, "http://evil.test")).status).toBeGreaterThanOrEqual(400);
100 expect(locksOnLeave(app.db, box.id)).toBe(false);
101 expect((await post({ op: "leave", on: "on" })).status).toBe(303);
102 expect(locksOnLeave(app.db, box.id)).toBe(true);
103 const page = await (await http.handle(new Request("http://forge.test/games/mc", { headers: { cookie } }))).text();
104 expect(page).toContain('data-door-leave="on"');
105 expect((await post({ op: "leave", on: "off" })).status).toBe(303);
106 expect(locksOnLeave(app.db, box.id)).toBe(false);
107 });
108
109 test("a non-owner's op=leave post changes nothing", async () => {
110 const bob = await createUser(app.db, { username: "bob", email: "[email protected]", password: "a-good-passphrase", origin: "seed" });
111 if (!bob.ok) throw new Error(bob.error);
112 grant(app.db, box.id, bob.value.id, "operator");
113 const cookie = `forge_session=${createSession(app.db, bob.value.id).token}`;
114 const res = await forgeHttp(app).handle(
115 new Request("http://forge.test/games/mc/door", { method: "POST", headers: { cookie, origin: "http://forge.test", "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ op: "leave", on: "on" }) }),
116 );
117 expect(res.status).not.toBe(303);
118 expect(locksOnLeave(app.db, box.id)).toBe(false);
119 });
120
121 const press = async (who: User, key: string): Promise<string> => {
122 const { app: tui, session } = createForgeApp(app, { sshUsername: who.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: who }, { terminal: headlessTerminal(110, 40), exitHooks: false });
123 tui.start();
124 const screen = gameBoxScreen(session, tui.ctx, box);
125 tui.ctx.push(screen);
126 await settleApp(tui);
127 screen.key?.({ type: "key", key, ctrl: false, alt: false, shift: false });
128 await settleApp(tui);
129 const text = tui.screen.toText().replace(/\s+/g, " ");
130 tui.stop?.();
131 return text;
132 };
133
134 test("the terminal's box screen: the owner's a switches it and says it; an operator's a does nothing", async () => {
135 expect(await press(ada, "a")).toContain("Locks by itself");
136 expect(locksOnLeave(app.db, box.id)).toBe(true);
137 expect(await press(ada, "a")).toContain("Off: the door does not lock");
138 expect(locksOnLeave(app.db, box.id)).toBe(false);
139 const bob = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'bob'").get()!;
140 const op = { ...ada, id: bob.id, username: "bob", isAdmin: false } as User;
141 await press(op, "a");
142 expect(locksOnLeave(app.db, box.id)).toBe(false);
143 });
144
145 test("an opener with no linked name: the page and the terminal say nothing will lock it", async () => {
146 app.db.query("DELETE FROM game_link").run();
147 setLocksOnLeave(app.db, box.id, true);
148 openWindow(app.db, box.id, ada.id);
149 expect(leaveCannotLock(app.db, box.id)).toBe(true);
150 say(paper("Alice left the game"));
151 expect(doorOf(app.db, box.id).state).toBe("open");
152 expect(await press(ada, "j")).toContain("nothing will lock it");
153 const cookie = `forge_session=${createSession(app.db, ada.id).token}`;
154 const page = await (await forgeHttp(app).handle(new Request("http://forge.test/games/mc", { headers: { cookie } }))).text();
155 expect(page).toContain("nothing will lock it");
156 });
157
158 test("a leave and a join in one sync: the opener is on the network again, so the door stays open", () => {
159 setLocksOnLeave(app.db, box.id, true);
160 openWindow(app.db, box.id, ada.id);
161 online("Alice");
162 say(paper("Alice left the game"), paper("Alice joined the game"));
163 expect(doorOf(app.db, box.id).state).toBe("open");
164 });
165
166 test("a failure in the lock is logged and the sync still stores its data", () => {
167 setLocksOnLeave(app.db, box.id, true);
168 openWindow(app.db, box.id, ada.id);
169 app.db.query("DROP TABLE game_chat").run();
170 try {
171 expect(() => say(paper("Alice left the game"))).not.toThrow();
172 } finally {
173 app.db.query("CREATE TABLE game_chat (id INTEGER PRIMARY KEY)").run();
174 }
175 });

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

Keyboard shortcuts

Docs