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

Games G2: import a world from a link, snapshots before every swap, Restore and Undo (#17284) #17289

opened this

Merged 35h 14m ago, live in production

sold/world-import → main 0 commits 5 threads · 5 unresolved

  • Merged. sold/world-import was merged into main as 0702203.

Review

Sign in to review this change.
18 files changed +780 −20
docs/features/games.md +10
@@ -45,6 +45,16 @@ A service page has a People block (#17284), with no plugin on the game servers:
4545
4646 The agent reads `list uuids` each sync, and each server's whitelist.json, ops.json and banned-players.json and the proxy's `glist all` every 60 s or right after a change. Heads come from the player's UUID through the forge (`/games/head/<uuid>`), fetched once from mc-heads.net and kept on the forge's disk a week, so a page never calls out. Only a player the forge has seen on a server the person sees (on it now, or in its whitelist, ops or bans) has a head fetched; any other UUID gets the default head. A failed fetch is not tried again for 15 minutes, and at most four fetches are out at once. The terminal's service screen has a people tab (`p` takes "op Alice", "move Alice survival"), and the `games` tool has `people` with `op` list or a change.
4747
48 ## Worlds
49
50 A service page has a World block (#17284). **Import world** takes a link to a `.zip` or `.tar.gz` with a `level.dat` inside (a signed storage link works) and asks the box to bring it in as a job, each step shown under World as it runs: download, check for level.dat, stop the server, keep the world it has as a snapshot, put the new world in place under the server's level name (with its `_nether` and `_the_end` when the archive has them), start it again. The job's result lands under the console.
51
52 Snapshots live beside the world in the service's `/data/forge-snapshots`, on the same disk as the world (the volume once Docker's data is there), named for the change they came before (`20261201T230000Z-before-import-<id>`). Every snapshot is kept: nothing deletes one, and the World block and the terminal's world tab say how many there are and the disk they take. The box lists them every sync; each has a **Restore**, which keeps the current world first, and the last import or restore offers **Undo**, the restore of the snapshot it made. **Take a snapshot** stops the server while the world is copied. The terminal's service screen has a world tab (`i` imports, `u` restores by number, `n` snapshots), and the `games` tool has `world` with `op` import, restore or snapshot.
53
54 An import link is treated as a secret (a signed link is one): it reaches the box once, in the reply that hands it the command, and the forge then keeps only its host and path; the page, the terminal, the tool's answer and the job's log show host and path, never the query string. The agent passes it to curl in a mode-600 config file, never on a command line, and removes it when the job ends however it ends.
55
56 Uploading a world file is still to come: a link is how a world comes in today.
57
4858 ## Secrets
4959
5060 The Velocity forwarding secret (`forwarding.env`) and an RCON password a service (`rcon-<service>.env`) are generated once, sealed like every forge secret and sent only in the sync's `env`, never committed. A box token is shown once and stored hashed. An uploaded jar is kept by the forge at `/games/jar/<id>/<name>`; the compose a box gets carries it signed for 6 hours, and only for the box that uploaded it. A jar must be a `.jar` (a zip), at most 64 MiB, and a box keeps at most 20 jars and 256 MiB.
src/core/empty_words.ts +1
@@ -100,6 +100,7 @@ const TABLE = {
100100 gameServices: { sentence: "Nothing has reported yet.", reason: "The box shows its services once its agent first syncs." },
101101 gamePlugins: { sentence: "Nothing is installed.", reason: "Add a URL, a Modrinth project or a jar below." },
102102 cloudProjects: { sentence: "Nothing read yet.", reason: "Each DigitalOcean and Hetzner account is read into its projects every 5 minutes; Read now reads them at once." },
103 gameSnapshots: { sentence: "No snapshot yet.", reason: "One is taken before every import or restore." },
103104 } as const satisfies Readonly<Record<string, EmptyWords>>;
104105
105106 export type EmptyKind = keyof typeof TABLE;
src/core/migration-pins/20261201230000-game-world-snapshots.pin added +1
@@ -0,0 +1,1 @@
1 683de413e2845065862dceba86c4a7c7279c62b24cfc103dbc5ad906e6a4aecb
src/core/migrations/20261201230000-game-world-snapshots.ts added +6
@@ -0,0 +1,6 @@
1 // A game box's world snapshots (#17284 G2): what its agent last said each service keeps in
2 // /data/forge-snapshots (name, bytes, when), replaced each sync, so a page can list them with a
3 // Restore. Additive: one column.
4 export default `
5 ALTER TABLE game_box ADD COLUMN snapshots_json TEXT NOT NULL DEFAULT '{}';
6 `;
src/crew/conversation_ask.ts +15
@@ -136,6 +136,15 @@ function infra(a: Args): string {
136136 return `Build the infrastructure plan ${val(a, "id")} on your own cloud: it spends money each month`;
137137 }
138138
139 /** A link's host, or "a link" when it is not one. */
140 const hostOf = (url: string): string => {
141 try {
142 return new URL(url).host;
143 } catch {
144 return "a link";
145 }
146 };
147
139148 export const ASKED_AS: Readonly<Record<string, Form>> = {
140149 // The everyday work, the fence's undoable list first.
141150 allocation: (a) =>
@@ -345,6 +354,12 @@ export const ASKED_AS: Readonly<Record<string, Form>> = {
345354 };
346355 return words[val(a, "op")] ?? `Change ${p} on ${on}`;
347356 }
357 if (a["action"] === "world")
358 return a["op"] === "restore"
359 ? `Put back the world snapshot ${val(a, "snapshot")} on ${on}, keeping the world it has first`
360 : a["op"] === "snapshot"
361 ? `Take a snapshot of the world on ${on}, stopping it while it is copied`
362 : `Replace the world on ${on} with the one at ${hostOf(val(a, "url"))}, keeping the world it has first`;
348363 return `Change ${on}`;
349364 },
350365 crew_accounts: (a) => `Let the crew's runs for ${val(a, "repo") || val(a, "owner") || "your repositories"} spend the account ${val(a, "allow")}`,
src/games/agent.sh +155 −2
@@ -267,6 +267,8 @@ done
267267 # One array, the real program and its flags: timeout(1) and `bash -c` both run it, which a shell
268268 # function never could be.
269269 COMPOSE=("$DOCKER" compose -p game --project-directory "$DIR" -f "$DIR/compose.yml")
270 # The same, as a function, for the world job's own bash (exported below; an array cannot be).
271 compose() { "$DOCKER" compose -p game --project-directory "$DIR" -f "$DIR/compose.yml" "$@"; }
270272 now() { date -u +%Y-%m-%dT%H:%M:%SZ; }
271273 # A quick command that must not hang the loop: at most 30 s where timeout(1) is there.
272274 # Run a command for at most `secs` seconds, timeout(1) or not: a docker that hangs never holds the
@@ -474,6 +476,19 @@ run() {
474476 touch "$DIR/.people.due"
475477 fi
476478 ;;
479 # A world import, restore or snapshot: long (a download, a stop, a tar), so a job. Its
480 # parameters (a URL, a snapshot's name) wait in a file, never on a command line.
481 world)
482 if ! [[ "$id" =~ $SAFE ]] || ! jq -e '.op | IN("import", "restore", "snapshot")' >/dev/null 2>&1 <<<"$text"; then
483 out="refused: a world command is an import, a restore or a snapshot"
484 ok=false
485 else
486 mkdir -p "$WORLDS"
487 printf '%s' "$text" >"$WORLDS/$id.json"
488 queue_job "$id" "world $(jq -r .op <<<"$text") $service" "" world "$service" "$id"
489 return
490 fi
491 ;;
477492 *)
478493 out="refused: $kind is not a command this agent runs"
479494 ok=false
@@ -553,7 +568,11 @@ job_tick() {
553568 now >"$DIR/.job.since"
554569 # Its own bash, named on its command line ($0), writing its exit status only when it ends.
555570 # shellcheck disable=SC2086,SC2016 # the verb and its words, each a safe name; the script is single-quoted on purpose
556 DIR="$DIR" bash -c '"$@" >"$DIR/.up.log" 2>&1; echo $? >"$DIR/.job.rc"' "$JOB_MARK" "${COMPOSE[@]}" $args &
571 if [ "${args%% *}" = world ]; then
572 DOCKER="$DOCKER" DIR="$DIR" bash -c 'world_job "$@" >"$DIR/.up.log" 2>&1; echo $? >"$DIR/.job.rc"' "$JOB_MARK" ${args#world } &
573 else
574 DIR="$DIR" bash -c '"$@" >"$DIR/.up.log" 2>&1; echo $? >"$DIR/.job.rc"' "$JOB_MARK" "${COMPOSE[@]}" $args &
575 fi
557576 echo $! >"$DIR/.job.pid"
558577 }
559578
@@ -687,6 +706,138 @@ bounded_diag() {
687706 if [ -s "$out" ] && jq -e . "$out" >/dev/null 2>&1; then cat "$out"; else echo '{}'; fi
688707 }
689708
709 # ---- worlds: import from a link, restore a snapshot, take one. A world lives in its service's
710 # /data (the level named in server.properties, with its _nether and _the_end), and its snapshots
711 # beside it in /data/forge-snapshots: on the same disk as the world, the volume once Docker's data
712 # is there. A helper container sharing the service's volumes does the file work, stopped or not. ----
713
714 WORLDS="$DIR/.world"
715 HELPER="alpine:3.20"
716 # The helper runs as root, and an archive keeps whoever made it as owner: the world goes to /data's own
717 # owner (itzg runs as 1000), or the server could not write it. The shell line for level $1.
718 world_own_sh() {
719 printf '%s' "own=\$(ls -nd . | awk '{print \$3\":\"\$4}'); for d in '$1' '$1_nether' '$1_the_end'; do [ -d \"\$d\" ] && chown -R \"\$own\" \"\$d\"; done; true"
720 }
721
722 # The service's container, running or stopped.
723 world_cid() { compose ps -a -q "$1" 2>/dev/null | head -n 1; }
724 # A shell in the helper, at the service's /data; $WORLDS is at /in, read-only.
725 world_sh() { "$DOCKER" run --rm --volumes-from "$1" -v "$WORLDS:/in:ro" -w /data "$HELPER" sh -euc "$2"; }
726 # What the service names its world (server.properties' level-name), "world" when it does not say.
727 world_level() {
728 local name
729 name="$(world_sh "$1" "sed -n 's/^level-name=//p' server.properties 2>/dev/null | head -n 1" 2>/dev/null | tr -d '\r')"
730 [[ "$name" =~ ^[A-Za-z0-9._-]{1,64}$ ]] && printf '%s' "$name" || printf world
731 }
732 # Each service's snapshots as JSON, newest first, kept in $WORLDS/snapshots.json for the sync.
733 world_index() {
734 local service="$1" cid="$2" rows
735 rows="$(world_sh "$cid" "mkdir -p forge-snapshots; for f in forge-snapshots/*.tar.gz; do [ -e \"\$f\" ] && stat -c '%n %s %Y' \"\$f\"; done" 2>/dev/null)"
736 jq -cn --arg s "$service" --arg rows "$rows" --slurpfile all <(cat "$WORLDS/snapshots.json" 2>/dev/null || echo '{}') '
737 ($all[0] // {}) + {($s): [$rows | split("\n")[] | select(. != "") | split(" ")
738 | {name: (.[0] | ltrimstr("forge-snapshots/") | rtrimstr(".tar.gz")), bytes: (.[1] | tonumber), at: (.[2] | tonumber | todate)}]
739 | sort_by(.name) | reverse}' >"$WORLDS/snapshots.json.next" && mv "$WORLDS/snapshots.json.next" "$WORLDS/snapshots.json"
740 }
741 # A snapshot of the stopped service's world, named for the change it comes before.
742 world_snapshot() {
743 local cid="$1" level="$2" name="$3"
744 world_sh "$cid" "mkdir -p forge-snapshots
745 set -- ; for d in '$level' '${level}_nether' '${level}_the_end'; do [ -d \"\$d\" ] && set -- \"\$@\" \"\$d\"; done
746 if [ \$# -eq 0 ]; then echo 'no world yet: nothing to keep'; exit 0; fi
747 tar czf 'forge-snapshots/$name.tar.gz' \"\$@\"
748 echo \"kept as $name\""
749 }
750
751 # One world job; its parameters (an import's link is a signed URL) are gone when it ends, however it ends.
752 world_job() {
753 local rc
754 world_steps "$@"
755 rc=$?
756 rm -f "$WORLDS/$2.json" "$WORLDS/$2.archive" "$WORLDS/$2.curl"
757 return "$rc"
758 }
759
760 # A world job's steps, said as it goes (the forge shows the job's log): import, restore or snapshot.
761 world_steps() {
762 local service="$1" id="$2" p op cid level stamp url shown snap ok=0
763 p="$WORLDS/$id.json"
764 op="$(jq -r '.op // ""' "$p" 2>/dev/null)"
765 cid="$(world_cid "$service")"
766 if [ -z "$cid" ]; then echo "$service has no container yet: nothing to change"; return 1; fi
767 level="$(world_level "$cid")"
768 stamp="$(date -u +%Y%m%dT%H%M%SZ)"
769 "$DOCKER" image inspect "$HELPER" >/dev/null 2>&1 || "$DOCKER" pull -q "$HELPER" >/dev/null || { echo "could not fetch the helper image $HELPER"; return 1; }
770 case "$op" in
771 import)
772 url="$(jq -r '.url // ""' "$p")"
773 # Said as host and path only: the query string of a signed link is its secret.
774 shown="${url%%[?#]*}"
775 echo "1/6 downloading the world from ${shown#*://}"
776 rm -f "$WORLDS/$id.archive"
777 # The link to curl in a config file (mode 600), never on its command line where ps shows it.
778 printf 'url = "%s"\n' "$(printf '%s' "$url" | sed 's/[\\"]/\\&/g')" >"$WORLDS/$id.curl"
779 curl -fsSL --proto '=https,http' --max-filesize 8589934592 --retry 2 -K "$WORLDS/$id.curl" -o "$WORLDS/$id.archive" || { echo "the download failed: check the link (a signed link may have expired)"; return 1; }
780 echo " $(du -h "$WORLDS/$id.archive" | cut -f1) downloaded"
781 echo "2/6 checking it is a world"
782 if ! world_sh "$cid" "rm -rf .forge-import && mkdir .forge-import && cd .forge-import
783 case \"\$(head -c 2 /in/$id.archive | od -An -tx1 | tr -d ' ')\" in
784 504b) unzip -q /in/$id.archive ;;
785 1f8b) tar xzf /in/$id.archive ;;
786 *) tar xf /in/$id.archive ;;
787 esac
788 # The overworld: the shallowest level.dat outside a _nether or _the_end folder (find's order
789 # is the disk's, and a Bukkit nether carries a level.dat of its own).
790 found=\"\$(find . -maxdepth 4 -name level.dat -not -path '*/forge-snapshots/*' -not -path '*_nether/*' -not -path '*_the_end/*' | awk -F/ '{print NF, \$0}' | sort -n | head -n 1 | cut -d' ' -f2-)\"
791 [ -n \"\$found\" ] || { echo 'not a world: no level.dat in it'; exit 1; }
792 echo \"\$(dirname \"\$found\")\" > ../.forge-import.root"; then
793 rm -f "$WORLDS/$id.archive"
794 world_sh "$cid" "rm -rf .forge-import .forge-import.root" >/dev/null 2>&1
795 return 1
796 fi
797 rm -f "$WORLDS/$id.archive"
798 echo " level.dat found"
799 echo "3/6 stopping $service"
800 compose stop "$service" >/dev/null 2>&1 || { echo "could not stop $service"; return 1; }
801 echo "4/6 keeping the world it had"
802 world_snapshot "$cid" "$level" "$stamp-before-import-$id" || { echo "the snapshot failed: the world is untouched"; compose start "$service" >/dev/null 2>&1; return 1; }
803 echo "5/6 putting the new world in place as $level"
804 world_sh "$cid" "root=\"\$(cat .forge-import.root)\"; base=\"\$(basename \"\$root\")\"; parent=\"\$(dirname \"\$root\")\"
805 rm -rf '$level' '${level}_nether' '${level}_the_end'
806 [ -d \".forge-import/\$parent/\${base}_nether\" ] && mv \".forge-import/\$parent/\${base}_nether\" '${level}_nether'
807 [ -d \".forge-import/\$parent/\${base}_the_end\" ] && mv \".forge-import/\$parent/\${base}_the_end\" '${level}_the_end'
808 if [ \"\$root\" = . ]; then mkdir '$level' && find .forge-import -mindepth 1 -maxdepth 1 -exec mv {} '$level'/ \; ; else mv \".forge-import/\$root\" '$level'; fi
809 rm -f '$level/session.lock'; rm -rf .forge-import .forge-import.root
810 $(world_own_sh "$level")" || ok=1
811 ;;
812 restore)
813 snap="$(jq -r '.snapshot // ""' "$p")"
814 [[ "$snap" =~ ^[A-Za-z0-9._-]{1,120}$ ]] || { echo "no such snapshot"; return 1; }
815 echo "1/4 stopping $service"
816 compose stop "$service" >/dev/null 2>&1 || { echo "could not stop $service"; return 1; }
817 echo "2/4 keeping the world it has"
818 world_snapshot "$cid" "$level" "$stamp-before-restore-$id" || { echo "the snapshot failed: the world is untouched"; compose start "$service" >/dev/null 2>&1; return 1; }
819 echo "3/4 putting back $snap"
820 world_sh "$cid" "[ -f 'forge-snapshots/$snap.tar.gz' ] || { echo 'no such snapshot'; exit 1; }
821 rm -rf '$level' '${level}_nether' '${level}_the_end' && tar xzf 'forge-snapshots/$snap.tar.gz'
822 $(world_own_sh "$level")" || ok=1
823 ;;
824 snapshot)
825 echo "1/3 stopping $service, so the world on disk is whole"
826 compose stop "$service" >/dev/null 2>&1 || { echo "could not stop $service"; return 1; }
827 echo "2/3 keeping the world"
828 world_snapshot "$cid" "$level" "$stamp-$( jq -r '.name // "by-hand"' "$p" | tr -cd 'A-Za-z0-9._-' | head -c 40)" || ok=1
829 ;;
830 *) echo "a world command is an import, a restore or a snapshot"; return 1 ;;
831 esac
832 echo "last: starting $service"
833 compose start "$service" >/dev/null 2>&1 || { echo "could not start $service"; ok=1; }
834 world_index "$service" "$cid"
835 [ "$ok" = 0 ] && echo "done" || echo "it did not finish: the step above says why, and the snapshot is listed"
836 return "$ok"
837 }
838 export -f world_job world_steps world_cid world_sh world_level world_index world_snapshot world_own_sh compose capped
839 export WORLDS HELPER
840
690841 sync() {
691842 local next answer
692843 next="$(now)"
@@ -699,6 +850,7 @@ sync() {
699850 bounded_diag | json_or '{}' >"$DIR/.sync.diag"
700851 people | json_or '{}' >"$DIR/.sync.people"
701852 metrics | json_or '{}' >"$DIR/.sync.metrics"
853 jq -c 'if type == "object" then . else {} end' "$WORLDS/snapshots.json" 2>/dev/null | json_or '{}' >"$DIR/.sync.snapshots"
702854 # Every string as plain text: real servers print colour escapes and control bytes (itzg's logs,
703855 # rcon-cli's colours), and the forge takes none of them.
704856 jq -cn \
@@ -710,8 +862,9 @@ sync() {
710862 --slurpfile diag "$DIR/.sync.diag" \
711863 --slurpfile people "$DIR/.sync.people" \
712864 --slurpfile metrics "$DIR/.sync.metrics" \
865 --slurpfile snapshots "$DIR/.sync.snapshots" \
713866 'def plain: gsub("\u001b\\[[0-9;?]*[ -/]*[@-~]"; "") | gsub("\u001b[@-_]?"; "") | gsub("[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f]"; "");
714 {agent: 1, composeSha: $sha, services: $services[0], logs: $logs[0], results: $results[0], host: $host[0], diag: $diag[0], people: $people[0], metrics: $metrics[0]}
867 {agent: 1, composeSha: $sha, services: $services[0], logs: $logs[0], results: $results[0], host: $host[0], diag: $diag[0], people: $people[0], metrics: $metrics[0], snapshots: $snapshots[0]}
715868 | walk(if type == "string" then plain else . end)' >"$DIR/.sync.body" || return 1
716869 answer="$(curl -fsS -m 20 -H "@$AUTH" -H 'content-type: application/json' --data-binary "@$DIR/.sync.body" "${FORGE_URL%/}/api/v1/games/agent/sync")" || return 1
717870 # Delivered: the results and the log lines are the forge's now.
src/games/snapshots.ts added +58
@@ -0,0 +1,58 @@
1 /**
2 * A game box's world snapshots as its agent lists them each sync (`worlds.ts`): read and kept here,
3 * apart from the commands, so the store can keep them without importing what queues.
4 */
5
6 export interface Snapshot {
7 readonly name: string;
8 readonly bytes: number;
9 readonly at: string;
10 }
11
12 const SNAPSHOT = /^[A-Za-z0-9._-]{1,120}$/;
13 const PER_SERVICE = 20;
14
15 /** What the agent said each service keeps, cleaned: at most 32 services, 20 snapshots each. */
16 export function keptSnapshots(sent: unknown): string {
17 const out: Record<string, Snapshot[]> = {};
18 if (sent === null || typeof sent !== "object" || Array.isArray(sent)) return "{}";
19 for (const [service, list] of Object.entries(sent).slice(0, 32)) {
20 if (!/^[A-Za-z0-9._-]{1,64}$/.test(service) || !Array.isArray(list)) continue;
21 out[service] = list
22 .filter((s): s is Record<string, unknown> => s !== null && typeof s === "object")
23 .map((s) => ({ name: typeof s["name"] === "string" ? s["name"] : "", bytes: typeof s["bytes"] === "number" && Number.isFinite(s["bytes"]) ? s["bytes"] : 0, at: typeof s["at"] === "string" ? s["at"].slice(0, 40) : "" }))
24 .filter((s) => SNAPSHOT.test(s.name))
25 .slice(0, PER_SERVICE);
26 }
27 return JSON.stringify(out);
28 }
29
30 export function readSnapshots(json: string): Record<string, Snapshot[]> {
31 try {
32 const v = JSON.parse(json) as unknown;
33 return v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, Snapshot[]>) : {};
34 } catch {
35 return {};
36 }
37 }
38
39 /** A link without what makes it a secret: its host and path, the query string and any user part dropped. */
40 export function linkShown(url: string): string {
41 try {
42 const u = new URL(url);
43 return `${u.host}${u.pathname}`;
44 } catch {
45 return "a link";
46 }
47 }
48
49 /** A world command as kept once handed to the box: an import's link becomes `from` (host and path). */
50 export function keptWorldText(text: string): string {
51 try {
52 const v = JSON.parse(text) as { op?: unknown; url?: unknown };
53 if (v.op !== "import" || typeof v.url !== "string") return text;
54 return JSON.stringify({ op: "import", from: linkShown(v.url) });
55 } catch {
56 return text;
57 }
58 }
src/games/store.ts +15 −2
@@ -9,6 +9,7 @@
99
1010 import type { Database } from "bun:sqlite";
1111 import { keptDiag, readDiag, type Diag } from "./diag.ts";
12 import { keptSnapshots, keptWorldText, readSnapshots, type Snapshot } from "./snapshots.ts";
1213 import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
1314 import { rm } from "node:fs/promises";
1415 import type { App } from "../app.ts";
@@ -24,7 +25,7 @@ export const LOG_KEEP = 2_000;
2425 const LINES_A_SYNC = 200;
2526 /** The most of a command's output kept: a shell's 16 KB (`shell.ts`); the rest say far less. */
2627 const OUTPUT_MAX = 16_384;
27 export const COMMAND_KINDS = ["rcon", "restart", "stop", "start", "recreate", "pull", "shell", "people"] as const;
28 export const COMMAND_KINDS = ["rcon", "restart", "stop", "start", "recreate", "pull", "shell", "people", "world"] as const;
2829 export type CommandKind = (typeof COMMAND_KINDS)[number];
2930 export type Role = "owner" | "operator" | "viewer";
3031 const RANK: Record<Role, number> = { viewer: 1, operator: 2, owner: 3 };
@@ -46,6 +47,8 @@ export interface GameBox {
4647 readonly boot: string;
4748 /** The latest diagnosis the agent sent (`diag.ts`), replaced each sync. */
4849 readonly diag: Diag;
50 /** Each service's world snapshots, newest first, as the agent last listed them (`worlds.ts`). */
51 readonly snapshots: Record<string, Snapshot[]>;
4952 }
5053
5154 export interface GameService {
@@ -75,6 +78,7 @@ interface BoxRow {
7578 created_at: string;
7679 boot: string;
7780 diag_json: string;
81 snapshots_json: string;
7882 }
7983 const toBox = (r: BoxRow): GameBox => {
8084 let host: Record<string, number> = {};
@@ -96,6 +100,7 @@ const toBox = (r: BoxRow): GameBox => {
96100 createdAt: r.created_at,
97101 boot: r.boot,
98102 diag: readDiag(r.diag_json),
103 snapshots: readSnapshots(r.snapshots_json),
99104 };
100105 };
101106
@@ -255,7 +260,8 @@ export function queueCommand(db: Database, boxId: string, service: string, kind:
255260 boxId,
256261 service,
257262 kind,
258 text.slice(0, 1_000),
263 // A world import's link (a signed URL) can run long.
264 text.slice(0, 4_000),
259265 by,
260266 new Date().toISOString(),
261267 );
@@ -441,6 +447,8 @@ export interface SyncBody {
441447 readonly boot?: string;
442448 /** What the box sees of itself, about 8 KB (`diag.ts`): kept, replacing the last. */
443449 readonly diag?: unknown;
450 /** Each service's world snapshots (`worlds.ts`). */
451 readonly snapshots?: unknown;
444452 }
445453
446454 const str = (v: unknown, max = 200): string => (typeof v === "string" ? v.slice(0, max) : "");
@@ -470,6 +478,8 @@ export function recordSync(
470478 str(body.composeSha, 80),
471479 keptDiag(body.diag),
472480 );
481 // An agent from before world snapshots sends none: the last list stays.
482 if (body.snapshots !== undefined) db.query("UPDATE game_box SET snapshots_json = ?2 WHERE id = ?1").run(box.id, keptSnapshots(body.snapshots));
473483 for (const s of (body.services ?? []).slice(0, 64)) {
474484 const name = str(s.name, 64);
475485 if (!SERVICE_NAME.test(name)) continue;
@@ -506,5 +516,8 @@ export function recordSync(
506516 >("SELECT id, kind, service, text FROM game_command WHERE box_id = ?1 AND handed_at = '' ORDER BY created_at LIMIT 32")
507517 .all(box.id);
508518 for (const c of due) db.query("UPDATE game_command SET handed_at = ?2 WHERE id = ?1").run(c.id, at);
519 // A world import's link is a secret (a signed URL): it goes to the box once, in this reply, and
520 // what stays is its host and path (`worlds.ts`).
521 for (const c of due) if (c.kind === "world") db.query("UPDATE game_command SET text = ?2 WHERE id = ?1").run(c.id, keptWorldText(c.text));
509522 return due;
510523 }
src/games/worlds.ts added +67
@@ -0,0 +1,67 @@
1 /**
2 * Worlds you can't lose (#17284 G2): bring a world in from a link, take a snapshot, put one back.
3 * The forge queues a `world` command (an import, a restore or a snapshot); the box's agent does it
4 * as a job, saying each step (download, check for level.dat, stop, snapshot, swap, start), and keeps
5 * each snapshot beside the world in the service's /data/forge-snapshots, named for the change it
6 * came before. The agent reports the list every sync; Undo is the restore of the snapshot an
7 * import or a restore made first.
8 */
9
10 import type { Database } from "bun:sqlite";
11 import type { User } from "../core/users.ts";
12 import { linkShown, type Snapshot } from "./snapshots.ts";
13 import { mayDo, queueCommand, roleOn, type GameBox } from "./store.ts";
14
15 export type WorldOp = { op: "import"; url: string } | { op: "restore"; snapshot: string } | { op: "snapshot"; name?: string };
16
17 /** A link the box may fetch: http or https, no spaces or control characters, at most 3,800 characters. */
18 export function worldLinkRefusal(url: string): string | undefined {
19 if (url === "") return "Paste a link to the world: a .zip or .tar.gz with its level.dat inside.";
20 if (url.length > 3_800) return "That link is too long.";
21 let u: URL;
22 try {
23 u = new URL(url);
24 } catch {
25 return "That is not a link.";
26 }
27 if (u.protocol !== "https:" && u.protocol !== "http:") return "The link must start with https:// (or http://).";
28 if (/[\s\u0000-\u001f\u007f]/.test(url)) return "That link has a space or a control character in it.";
29 return undefined;
30 }
31
32 /**
33 * Queue a world command for `service` on `box`, after checking it: the command's id, or why not.
34 * Only an operator of the service may (each door asks here, so none can skip it); a restore names
35 * a snapshot the box has said it keeps.
36 */
37 export function queueWorld(db: Database, box: GameBox, service: string, op: WorldOp, user: User | undefined): { ok: true; id: string } | { ok: false; error: string } {
38 if (!mayDo(roleOn(db, user, box.id, service), "operator")) return { ok: false, error: `You are not an operator of ${service}.` };
39 const by = user!.id;
40 if (op.op === "import") {
41 const refused = worldLinkRefusal(op.url.trim());
42 if (refused !== undefined) return { ok: false, error: refused };
43 return { ok: true, id: queueCommand(db, box.id, service, "world", JSON.stringify({ op: "import", url: op.url.trim() }), by) };
44 }
45 if (op.op === "restore") {
46 if (!(box.snapshots[service] ?? []).some((s) => s.name === op.snapshot)) return { ok: false, error: `${service} keeps no snapshot called ${op.snapshot}.` };
47 return { ok: true, id: queueCommand(db, box.id, service, "world", JSON.stringify({ op: "restore", snapshot: op.snapshot }), by) };
48 }
49 const name = (op.name ?? "").replace(/[^A-Za-z0-9._-]+/g, "-").slice(0, 40) || "by-hand";
50 return { ok: true, id: queueCommand(db, box.id, service, "world", JSON.stringify({ op: "snapshot", name }), by) };
51 }
52
53 /** The snapshot a world command made before it changed anything: what its Undo puts back. */
54 export const undoOf = (box: GameBox, service: string, commandId: string): Snapshot | undefined =>
55 (box.snapshots[service] ?? []).find((s) => s.name.endsWith(`-before-import-${commandId}`) || s.name.endsWith(`-before-restore-${commandId}`));
56
57 /** A world command's words, a link only as host and path: "import a world from x.supabase.co/…/hub-world.tar.gz". */
58 export function worldWords(text: string): string {
59 try {
60 const v = JSON.parse(text) as { op?: string; url?: string; from?: string; snapshot?: string };
61 if (v.op === "import") return `import a world from ${v.from ?? (v.url === undefined ? "a link" : linkShown(v.url))}`;
62 if (v.op === "restore") return `restore ${v.snapshot ?? "a snapshot"}`;
63 return "take a snapshot";
64 } catch {
65 return "a world change";
66 }
67 }
src/generated/migrations.ts +6 −4
@@ -462,8 +462,9 @@ import m457 from "../core/migrations/20261201190000-working-edit.ts";
462462 import m458 from "../core/migrations/20261201190200-dep-accept.ts";
463463 import m459 from "../core/migrations/20261201190500-runner-machine.ts";
464464 import m460 from "../core/migrations/20261201200000-cloud-projects.ts";
465 import m461 from "../core/migrations/20261202000000-game-people.ts";
466 import m462 from "../core/migrations/20261202000000-mail-relay-scope.ts";
465 import m461 from "../core/migrations/20261201230000-game-world-snapshots.ts";
466 import m462 from "../core/migrations/20261202000000-game-people.ts";
467 import m463 from "../core/migrations/20261202000000-mail-relay-scope.ts";
467468
468469 /** Each migration file's name and its default export, in name order. */
469470 export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
@@ -928,6 +929,7 @@ export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
928929 ["20261201190200-dep-accept.ts", m458],
929930 ["20261201190500-runner-machine.ts", m459],
930931 ["20261201200000-cloud-projects.ts", m460],
931 ["20261202000000-game-people.ts", m461],
932 ["20261202000000-mail-relay-scope.ts", m462],
932 ["20261201230000-game-world-snapshots.ts", m461],
933 ["20261202000000-game-people.ts", m462],
934 ["20261202000000-mail-relay-scope.ts", m463],
933935 ];
src/http/games_routes.ts +2 −1
@@ -13,7 +13,7 @@ import { sleeping } from "../games/sleep.ts";
1313 import { boxByToken, envFiles, markAsleep, recordSync, signJarUrls, type SyncBody } from "../games/store.ts";
1414 import { BODY_CAPS } from "../kernel/body_caps.ts";
1515 import {
16 gameBoxPage, gameCommandSubmit, gameEnvSubmit, gameGrantSubmit, gameJarDownload, gameJarSubmit, gamePluginSubmit, gamePeopleSubmit, gameHead, gamePowerSubmit, gameSleepSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gamesPage,
16 gameBoxPage, gameCommandSubmit, gameEnvSubmit, gameGrantSubmit, gameJarDownload, gameJarSubmit, gamePluginSubmit, gamePeopleSubmit, gameHead, gameWorldSubmit, gamePowerSubmit, gameSleepSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gamesPage,
1717 } from "../web/pages/games.ts";
1818 import type { Ctx, Handler } from "./context.ts";
1919 import { InvalidJson } from "./json_body.ts";
@@ -88,6 +88,7 @@ export function gamesRoutes(router: Router<Handler>): void {
8888 router.add("POST", "/games/:box/:service/plugin", gamePluginSubmit);
8989 router.add("POST", "/games/:box/:service/sleep", gameSleepSubmit);
9090 router.add("POST", "/games/:box/:service/people", gamePeopleSubmit);
91 router.add("POST", "/games/:box/:service/world", gameWorldSubmit);
9192 router.add("POST", "/games/:box/:service/jar", gameJarSubmit);
9293 router.add("POST", "/games/:box/:service/settings", gameSettingsSubmit);
9394 }
src/http/lazy_lists.ts +1
@@ -620,6 +620,7 @@ export const OPERATIONS_ROUTES = [
620620 ["POST", "/games/:box/:service/plugin"],
621621 ["POST", "/games/:box/:service/sleep"],
622622 ["POST", "/games/:box/:service/people"],
623 ["POST", "/games/:box/:service/world"],
623624 ["POST", "/games/:box/:service/jar"],
624625 ["POST", "/games/:box/:service/settings"],
625626 ["GET", "/resilience"],
src/http/mcp/tools/games.ts +25 −5
@@ -8,22 +8,26 @@ import { boxNamed, listBoxes, mayDo, queueCommand, roleOn, seesBox, SERVICE_NAME
88 import { good, bad, type Tool, str } from "../shared.ts";
99 import { commitPolicy } from "../../../games/sleep.ts";
1010 import { eventsOf, networkOf, PEOPLE_OPS, peopleOf, peopleWords, queuePeople } from "../../../games/people.ts";
11 import { linkShown } from "../../../games/snapshots.ts";
12 import { queueWorld } from "../../../games/worlds.ts";
1113
1214 const POWER = ["start", "stop", "restart", "recreate", "pull"];
1315
1416 export const tool: Tool = {
1517 name: "games",
1618 listedTo: "admin",
17 doc: "`{ action, box?, service?, text?, kind?, key?, value?, modrinth?, preview?, dryRun?, window? }`: game boxes. `list`; `metrics` per service (now, 1h, 24h), or one `service` over `window` (1h to 30d); `sleep` sets a `service` to `value` warm or sleep (stops when empty, starts on join), a commit; `console` queues `text` as RCON; `power` `kind` (start, stop, restart); `env` commits `key`=`value` (empty removes); `plugin` adds a `modrinth` slug (`preview` true only says what it would add: the newest compatible version and its required dependencies; incompatible is refused with the reason, a lockfile with sha512 is committed); `people` with `op` list (online, whitelist, ops, bans, who is where, the latest joins, deaths and chat) or op, deop, whitelist-add, whitelist-remove, whitelist-on, whitelist-off, ban, pardon, kick for `player`, or move `player` to `to`; `config` lists a service's settings (server.properties, Paper's); `config_set` sets `key` to `value`, planned first (`dryRun: false` commits the plan on the commit it was planned on). Grants as on /games",
18 description: "Game boxes: list, metrics, console, power, env, plugins, people, settings, sleep.",
19 doc: "`{ action, box?, service?, text?, kind?, key?, value?, modrinth?, preview?, dryRun?, window?, url?, snapshot? }`: game boxes. `list` (with each service's world snapshots); `metrics` per service (now, 1h, 24h), or one `service` over `window` (1h to 30d); `sleep` sets a `service` to `value` warm or sleep (stops when empty, starts on join), a commit; `console` queues `text` as RCON; `power` `kind` (start, stop, restart); `env` commits `key`=`value` (empty removes); `plugin` adds a `modrinth` slug (`preview` true only says what it would add: the newest compatible version and its required dependencies; incompatible is refused with the reason, a lockfile with sha512 is committed); `world` `op` import (a world from `url`, a .zip or .tar.gz with level.dat; the world it had is kept first), restore (`snapshot`) or snapshot, a job whose steps the box reports; `people` with `op` list (online, whitelist, ops, bans, who is where, the latest joins, deaths and chat) or op, deop, whitelist-add, whitelist-remove, whitelist-on, whitelist-off, ban, pardon, kick for `player`, or move `player` to `to`; `config` lists a service's settings (server.properties, Paper's); `config_set` sets `key` to `value`, planned first (`dryRun: false` commits the plan on the commit it was planned on). Grants as on /games",
20 description: "Game boxes: list, metrics, console, power, env, plugins, people, settings, sleep, worlds.",
1921 inputSchema: {
2022 type: "object",
2123 properties: {
22 action: { type: "string", enum: ["list", "metrics", "console", "power", "env", "plugin", "people", "config", "config_set", "sleep"] },
23 op: { type: "string", enum: ["list", ...PEOPLE_OPS] },
24 action: { type: "string", enum: ["list", "metrics", "console", "power", "env", "plugin", "people", "config", "config_set", "sleep", "world"] },
25 op: { type: "string", enum: ["list", ...PEOPLE_OPS, "import", "restore", "snapshot"] },
2426 player: { type: "string", maxLength: 17 },
2527 to: { type: "string", maxLength: 64 },
2628 window: { type: "string", enum: Object.keys(WINDOWS) },
29 url: { type: "string", maxLength: 3800 },
30 snapshot: { type: "string", maxLength: 120 },
2731 box: { type: "string", maxLength: 40 },
2832 service: { type: "string", maxLength: 64 },
2933 text: { type: "string", maxLength: 1000 },
@@ -67,6 +71,7 @@ export const tool: Tool = {
6771 status: (mayDo(roleOn(db, user, b.id), "owner") ? boxStatus(b.diag) : boxStatusShared(b.diag)).slice(0, 3),
6872 ...(cloud[i] === undefined ? {} : { cloud: cloud[i] }),
6973 services: servicesOf(db, b.id).filter((s) => mayDo(roleOn(db, user, b.id, s.name), "viewer")),
74 snapshots: Object.fromEntries(Object.entries(b.snapshots).filter(([s]) => mayDo(roleOn(db, user, b.id, s), "viewer")).map(([s, list]) => [s, list.slice(0, 10)])),
7075 })),
7176 });
7277 }
@@ -142,6 +147,21 @@ export const tool: Tool = {
142147 const done = await commitPolicy(ctx.app, user, box, service, policy);
143148 return done.ok ? good({ says: `${service} ${policy === "sleep" ? "sleeps when empty" : "stays warm"} once the box redeploys (${done.sha.slice(0, 10)}).`, sha: done.sha }) : bad("refused", done.error);
144149 }
145 return bad("bad_action", "action is list, metrics, console, power, env, plugin, people, config, config_set or sleep");
150 if (action === "world") {
151 const op = str(args["op"]);
152 const queued =
153 op === "import"
154 ? queueWorld(ctx.app.db, box, service, { op: "import", url: str(args["url"]) }, user)
155 : op === "restore"
156 ? queueWorld(ctx.app.db, box, service, { op: "restore", snapshot: str(args["snapshot"]) }, user)
157 : op === "snapshot"
158 ? queueWorld(ctx.app.db, box, service, { op: "snapshot" }, user)
159 : ({ ok: false, error: "op is import, restore or snapshot" } as const);
160 // The link is a secret: only its host and path come back.
161 return queued.ok
162 ? good({ says: "Queued; the box runs it on its next sync and reports each step.", id: queued.id, ...(op === "import" ? { from: linkShown(str(args["url"])) } : {}) })
163 : bad("refused", queued.error);
164 }
165 return bad("bad_action", "action is list, metrics, console, power, env, plugin, people, config, config_set, sleep or world");
146166 },
147167 };
src/tui/screens/games.ts +38 −4
@@ -17,6 +17,7 @@ import { commitPolicy, policyOf, stateWords } from "../../games/sleep.ts";
1717 import { SHELL_SERVICE, queueShell } from "../../games/shell.ts";
1818 import { onSync } from "../../games/notify.ts";
1919 import { eventsOf, isBedrock, peopleOf, peopleWords, queuePeople } from "../../games/people.ts";
20 import { queueWorld, worldWords, type WorldOp } from "../../games/worlds.ts";
2021 import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts";
2122 import { cloudLine, pinnedOfBox } from "../../actions/cloud_says.ts";
2223 import { getUserByName } from "../../core/users.ts";
@@ -24,6 +25,7 @@ import { addPlugin, commitServiceEnv, pluginSays, pluginsOf, readCompose, servic
2425 import { commitSettings, planSettings, settingsOf, type SettingsPlan, type SettingValue } from "../../games/settings.ts";
2526 import {
2627 SERVICE_NAME,
28 boxNamed,
2729 bootTroubled,
2830 bootWords,
2931 grant,
@@ -169,7 +171,7 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen {
169171 return screen;
170172 }
171173
172 const PARTS = ["console", "env", "plugins", "people"] as const;
174 const PARTS = ["console", "env", "plugins", "people", "world"] as const;
173175 type Part = (typeof PARTS)[number];
174176
175177 /**
@@ -194,7 +196,8 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
194196 };
195197 const lines = (): string[] => {
196198 if (part === "console") {
197 const done = recentCommands(f.app.db, box.id, service, 5).map((c) => `> ${c.text} ${c.done ? (c.ok ? "ok" : "failed") : "waiting for the box"}${c.output === "" ? "" : `: ${c.output.split("\n")[0]}`}`);
199 // A world command's link shows as host and path only: its query string may be a signed secret.
200 const done = recentCommands(f.app.db, box.id, service, 5).map((c) => `> ${c.kind === "world" ? worldWords(c.text) : c.text} ${c.done ? (c.ok ? "ok" : "failed") : "waiting for the box"}${c.output === "" ? "" : `: ${c.output.split("\n")[0]}`}`);
198201 return [...logsOf(f.app.db, box.id, service, 200).lines, ...done];
199202 }
200203 if (part === "people") {
@@ -208,6 +211,20 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
208211 "p: op, deop, whitelist-add, whitelist-remove, ban, pardon, kick <player>, or move <player> <server>",
209212 ];
210213 }
214 if (part === "world") {
215 // As the box last said: a world job's steps while one runs, then the snapshots, numbered for `u`.
216 const now = boxNamed(f.app.db, box.name) ?? box;
217 const job = now.diag.job;
218 const running = job?.running === true && job.label?.startsWith("world ") === true && job.label.endsWith(` ${service}`);
219 const snaps = now.snapshots[service] ?? [];
220 return [
221 ...(running ? [`Working: ${job!.label}`, ...(now.diag.upLog ?? "").split("\n").filter(Boolean)] : []),
222 ...(snaps.length === 0
223 ? ["No snapshot yet: one is taken before every import or restore."]
224 : [`${snaps.length} ${snaps.length === 1 ? "snapshot" : "snapshots"}, ${Math.max(1, Math.round(snaps.reduce((n, s) => n + s.bytes, 0) / 1024 ** 2))} MB on the world's disk`, ...snaps.map((s, i) => `${i + 1}. ${s.name} ${Math.max(1, Math.round(s.bytes / 1024 ** 2))} MB`)]),
225 "i imports a world from a link · u puts a snapshot back (its number) · n takes one now",
226 ];
227 }
211228 if (!loaded) return ["Reading the compose file…"];
212229 if (compose === undefined) return [`No ${box.path} on ${box.repo}@${box.branch}.`];
213230 if (part === "env") {
@@ -238,12 +255,15 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
238255 const screen: Screen = {
239256 title: `${box.name}/${service}`,
240257 keys: [
241 binding(["tab"], "console, env, plugins, people"),
258 binding(["tab"], "console, env, plugins, people, world"),
242259 binding([":"], "rcon"),
243260 binding(["e"], "set env"),
244261 binding(["a"], "add plugin"),
245262 binding(["c"], "settings"),
246263 binding(["p"], "a player: op, ban, kick, move…"),
264 binding(["i"], "import a world"),
265 binding(["u"], "restore a snapshot"),
266 binding(["n"], "take a snapshot"),
247267 ],
248268 render(area, s) {
249269 const c = ctx.theme.c;
@@ -299,7 +319,21 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
299319 await load();
300320 return pluginSays(done, false);
301321 });
302 else return false;
322 else if (e.key === "i" || e.key === "u" || e.key === "n") {
323 const world = (op: WorldOp): string => {
324 const queued = queueWorld(f.app.db, boxNamed(f.app.db, box.name) ?? box, service, op, f.user);
325 part = "world";
326 return queued.ok ? "Asked: the box starts on its next sync, and its steps show here." : queued.error;
327 };
328 if (e.key === "i") ask("Import a world", "A link to a .zip or .tar.gz with its level.dat (the world it has is kept first)", async (url) => world({ op: "import", url }));
329 else if (e.key === "u")
330 ask("Restore a snapshot", "Its number in the world list", async (n) => {
331 const snap = (boxNamed(f.app.db, box.name) ?? box).snapshots[service]?.[Number(n.trim()) - 1];
332 return snap === undefined ? "No snapshot with that number." : world({ op: "restore", snapshot: snap.name });
333 });
334 else if (!operator()) say(`You are not an operator of ${service}.`);
335 else say(world({ op: "snapshot" }));
336 } else return false;
303337 return true;
304338 },
305339 };
src/web/pages/games.ts +56 −1
@@ -33,6 +33,7 @@ import {
3333 storeJar,
3434 dropJar,
3535 type CommandKind,
36 type CommandState,
3637 type GameBox,
3738 type Role,
3839 } from "../../games/store.ts";
@@ -52,6 +53,7 @@ import { CLOUD_EVENT, cloudFacts, GAME_CLOUD_EVENT, pinnedOfBox } from "../../ac
5253 import { topologyBlock, TOPOLOGY_CSS } from "./games_topology.ts";
5354 import { defaultHeadResponse, headResponse } from "../../games/heads.ts";
5455 import { eventsOf, isBedrock, knowsPlayer, peopleOf, peopleWords, queuePeople, UNDO, type PeopleOp } from "../../games/people.ts";
56 import { queueWorld, undoOf, worldWords } from "../../games/worlds.ts";
5557 import { emptyLine } from "../empty_words.ts";
5658 import { metricsSeries, playerEvents, recentErrors, type Point } from "../../games/metrics.ts";
5759 import { daySpark } from "../studio/kpi_row.ts";
@@ -353,7 +355,7 @@ ${tail.lines.join("\n")}${tail.lines.length > 0 ? "\n" : ""}</pre
353355 : rowList(
354356 commands.map((c) =>
355357 row({
356 title: html`<span class="mono">${c.kind} ${c.text}</span>`,
358 title: c.kind === "world" ? worldWords(c.text) : html`<span class="mono">${c.kind} ${c.text}</span>`,
357359 meta: html`<span id="cmd-${c.id}"
358360 >${c.done ? `${c.ok ? "ok" : "failed"}: ${c.output}` : c.handed ? "sent to the box" : "queued"}</span
359361 >`,
@@ -362,6 +364,7 @@ ${tail.lines.join("\n")}${tail.lines.length > 0 ? "\n" : ""}</pre
362364 )}
363365 </section>
364366 ${compose === undefined || !canSleep(compose.text, service) ? null : sleepBlock(box, service, compose.text, seen?.asleep === true, act)}
367 ${worldBlock(box, service, act, commands)}
365368 <section class="settings-block">
366369 <h2>Environment</h2>
367370 ${Object.keys(env).length === 0
@@ -447,6 +450,58 @@ export function gameServiceStream(ctx: Ctx): Response {
447450 );
448451 }
449452
453 const mb = (bytes: number): string => (bytes >= 1024 ** 3 ? `${(bytes / 1024 ** 3).toFixed(1)} GB` : `${Math.max(1, Math.round(bytes / 1024 ** 2))} MB`);
454
455 /**
456 * The service's world: a world job's steps while one runs, Import from a link, the snapshots with a
457 * Restore each, Take a snapshot, and Undo on a world change that kept one first.
458 */
459 function worldBlock(box: GameBox, service: string, act: boolean, commands: readonly CommandState[]): Html {
460 const job = box.diag.job;
461 const running = job?.running === true && job.label?.startsWith("world ") === true && job.label.endsWith(` ${service}`);
462 const snaps = box.snapshots[service] ?? [];
463 const base = `/games/${box.name}/${service}/world`;
464 const restore = (name: string, label: string): Html =>
465 html`<form method="post" action="${base}" class="row-fields"><input type="hidden" name="op" value="restore" /><input type="hidden" name="snapshot" value="${name}" />${btn(label, { variant: "secondary" })}</form>`;
466 const undo = commands.filter((c) => c.kind === "world" && c.done && c.ok).map((c) => undoOf(box, service, c.id)).find((s) => s !== undefined);
467 return html`<section class="settings-block">
468 <h2>World</h2>
469 ${running ? html`<p role="status">Working: ${job!.label}</p><pre class="run-log mono" tabindex="0" aria-label="World job steps">${box.diag.upLog ?? ""}</pre>` : null}
470 ${act && undo !== undefined ? html`<p>The last world change kept the world before it as ${undo.name}.</p>${restore(undo.name, "Undo")}` : null}
471 ${act
472 ? html`<form method="post" action="${base}" class="row-fields">
473 <input type="hidden" name="op" value="import" />
474 ${input({ name: "url", label: "Import a world from a link (.zip or .tar.gz with its level.dat)", required: true, mono: true })}
475 ${btn("Import world", { variant: "secondary" })}
476 </form>`
477 : null}
478 ${snaps.length === 0
479 ? emptyLine("gameSnapshots")
480 : html`<p>${snaps.length} ${snaps.length === 1 ? "snapshot" : "snapshots"}, ${mb(snaps.reduce((n, s) => n + s.bytes, 0))} on the world's disk</p>`}
481 ${snaps.length === 0
482 ? null
483 : rowList(snaps.map((s) => row({ title: html`<span class="mono">${s.name}</span>`, meta: html`${mb(s.bytes)}${s.at === "" ? "" : html` · ${time(s.at)}`}`, ...(act ? { after: restore(s.name, "Restore") } : {}) })))}
484 ${act ? html`<form method="post" action="${base}" class="row-fields"><input type="hidden" name="op" value="snapshot" />${btn("Take a snapshot", { variant: "secondary" })}</form>` : null}
485 </section>`;
486 }
487
488 // POST /games/:box/:service/world: an import from a link, a restore, or a snapshot, as a job on the box.
489 export async function gameWorldSubmit(ctx: Ctx): Promise<Response> {
490 const got = await operatorForm(ctx);
491 if (got instanceof Response) return got;
492 const op = field(got.form, "op");
493 const back = `/games/${got.box.name}/${got.service}`;
494 const queued =
495 op === "import"
496 ? queueWorld(ctx.app.db, got.box, got.service, { op: "import", url: field(got.form, "url") }, ctx.auth.user)
497 : op === "restore"
498 ? queueWorld(ctx.app.db, got.box, got.service, { op: "restore", snapshot: field(got.form, "snapshot") }, ctx.auth.user)
499 : op === "snapshot"
500 ? queueWorld(ctx.app.db, got.box, got.service, { op: "snapshot" }, ctx.auth.user)
501 : ({ ok: false, error: "Choose import, restore or snapshot." } as const);
502 return flashTo(ctx, back, queued.ok ? { message: "Asked: the box starts on its next sync, and its steps show under World." } : { tone: "danger", message: queued.error });
503 }
504
450505 async function operatorForm(ctx: Ctx): Promise<{ box: GameBox; service: string; form: Form } | Response> {
451506 const service = ctx.params.service ?? "";
452507 const got = boxOf(ctx, "operator", service);
test/conversation-ask.test.ts +2
@@ -526,6 +526,8 @@ const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [
526526 ["games", { action: "sleep", box: "net", service: "hub", value: "warm" }, "Keep hub on net warm, a commit that redeploys it."],
527527 ["games", { action: "people", box: "mc", service: "hub", op: "ban", player: "Griefer" }, "Ban Griefer from hub on mc."],
528528 ["games", { action: "people", box: "mc", service: "hub", op: "move", player: ".Steve", to: "survival" }, "Move .Steve to survival."],
529 ["games", { action: "world", box: "mc", service: "hub", op: "import", url: "https://x.supabase.co/hub-world.tar.gz?t=1" }, "Replace the world on hub on mc with the one at x.supabase.co, keeping the world it has first."],
530 ["games", { action: "world", box: "mc", service: "hub", op: "restore", snapshot: "20261201T230000Z-before-import-w1" }, "Put back the world snapshot 20261201T230000Z-before-import-w1 on hub on mc, keeping the world it has first."],
529531 ["crew_accounts", { repo: "marin/cakes", allow: "espo-corp" }, "Let the crew's runs for marin/cakes spend the account espo-corp."],
530532 ["subscriptions", { everywhere: "espo-corp" }, "Put the account espo-corp in the pool, so the crew uses it by default on every repository a forge admin owns."],
531533 ["subscriptions", { limit: "espo-corp" }, "Keep the account espo-corp to where it is allowed."],
test/game-world.test.ts added +285
@@ -0,0 +1,285 @@
1 /**
2 * Worlds you can't lose (#17284 G2): a world comes in from a link as a job on the box: download,
3 * check for level.dat, stop, keep the world it had as a snapshot, swap, start, each step said; the
4 * snapshots come back in the sync and are listed with a Restore; Undo is the restore of the one an
5 * import kept; and the page, the terminal's keys and the games tool all queue the same command.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { chmodSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
9 import { rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { createSession } from "../src/core/sessions.ts";
14 import { createToken } from "../src/core/tokens.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { keptSnapshots } from "../src/games/snapshots.ts";
17 import { boxNamed, commandOf, createGameBox, recentCommands } from "../src/games/store.ts";
18 import { queueWorld, undoOf, worldLinkRefusal, worldWords } from "../src/games/worlds.ts";
19 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
20 import { quietLogs } from "./helpers/globals.ts";
21
22 quietLogs();
23
24 const AGENT = join(import.meta.dir, "../src/games/agent.sh");
25 const TOKEN = "fgb_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG";
26
27 describe("the forge's side", () => {
28 test("a link the box may fetch, and nothing else", () => {
29 expect(worldLinkRefusal("https://x.supabase.co/storage/v1/object/sign/mc-worlds/hub-world.tar.gz?token=abc")).toBeUndefined();
30 expect(worldLinkRefusal("")).toContain("Paste a link");
31 expect(worldLinkRefusal("file:///etc/passwd")).toBe("The link must start with https:// (or http://).");
32 expect(worldLinkRefusal("not a link")).toBe("That is not a link.");
33 expect(worldLinkRefusal(`https://x.test/${"a".repeat(4_000)}`)).toBe("That link is too long.");
34 });
35
36 test("snapshots as the agent lists them are kept clean and bounded", () => {
37 const kept = JSON.parse(
38 keptSnapshots({
39 hub: [
40 { name: "20261201T230000Z-before-import-abc", bytes: 1024, at: "2026-12-01T23:00:00Z" },
41 { name: "../etc", bytes: 1, at: "" },
42 "junk",
43 ],
44 "bad name!": [],
45 survival: Array.from({ length: 40 }, (_, i) => ({ name: `s${i}`, bytes: 1, at: "" })),
46 }),
47 ) as Record<string, unknown[]>;
48 expect(kept["hub"]).toEqual([{ name: "20261201T230000Z-before-import-abc", bytes: 1024, at: "2026-12-01T23:00:00Z" }]);
49 expect(kept["bad name!"]).toBeUndefined();
50 expect(kept["survival"]!.length).toBe(20);
51 expect(worldWords(JSON.stringify({ op: "import", url: "https://u:[email protected]/a.tar.gz?token=t" }))).toBe("import a world from x.supabase.co/a.tar.gz");
52 });
53 });
54
55 describe("on a forge", () => {
56 let dataDir = "";
57 let app: App;
58 let http: ForgeHttp;
59 let ada: User;
60 let token = "";
61 let cookie = "";
62 beforeAll(async () => {
63 dataDir = mkdtempSync(join(tmpdir(), "forge-game-world-"));
64 app = createApp({ dataDir, port: 0 });
65 http = forgeHttp(app);
66 const u = await createUser(app.db, {
67 username: "ada",
68 email: "[email protected]",
69 password: "a-good-passphrase",
70 origin: "seed",
71 isAdmin: true,
72 trusted: true,
73 });
74 if (!u.ok) throw new Error(u.error);
75 ada = u.value;
76 token = createGameBox(app.db, { name: "mc" }).token;
77 cookie = `forge_session=${createSession(app.db, ada.id).token}`;
78 }, 30_000);
79 afterAll(async () => {
80 app.close();
81 await rm(dataDir, { recursive: true, force: true });
82 });
83 const sync = (body: unknown) =>
84 http.handle(
85 new Request("http://forge.test/api/v1/games/agent/sync", {
86 method: "POST",
87 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
88 body: JSON.stringify(body),
89 }),
90 );
91 const post = (path: string, form: Record<string, string>) =>
92 http.handle(
93 new Request(`http://forge.test${path}`, {
94 method: "POST",
95 headers: { cookie, origin: "http://forge.test", "content-type": "application/x-www-form-urlencoded" },
96 body: new URLSearchParams(form),
97 }),
98 );
99
100 test("the page's Import queues a world command; the sync's snapshots are listed with a Restore, and the import's is its Undo", async () => {
101 expect((await sync({ agent: 1, services: [{ name: "hub", state: "running" }] })).status).toBe(200);
102 const asked = await post("/games/mc/hub/world", { op: "import", url: "https://x.supabase.co/hub-world.tar.gz?token=t" });
103 expect(asked.status).toBe(303);
104 const cmd = recentCommands(app.db, boxNamed(app.db, "mc")!.id, "hub", 1)[0]!;
105 expect(cmd.kind).toBe("world");
106 expect(JSON.parse(cmd.text)).toEqual({ op: "import", url: "https://x.supabase.co/hub-world.tar.gz?token=t" });
107 // Handed to the box once, in a reply; what the forge keeps is the host and path.
108 const reply = (await (await sync({ agent: 1, services: [{ name: "hub", state: "running" }] })).json()) as { commands: { text: string }[] };
109 expect(reply.commands.map((c) => JSON.parse(c.text).url)).toContain("https://x.supabase.co/hub-world.tar.gz?token=t");
110 expect(JSON.parse(commandOf(app.db, cmd.id)!.text)).toEqual({ op: "import", from: "x.supabase.co/hub-world.tar.gz" });
111 const again = (await (await sync({ agent: 1 })).json()) as { commands: unknown[] };
112 expect(JSON.stringify(again)).not.toContain("token=t");
113 // A link the box may not fetch never reaches it.
114 expect((await post("/games/mc/hub/world", { op: "import", url: "file:///etc/shadow" })).status).toBe(303);
115 expect(recentCommands(app.db, boxNamed(app.db, "mc")!.id, "hub", 5).filter((c) => c.kind === "world").length).toBe(1);
116 // The box ends it and lists the snapshot it kept.
117 const snap = `20261201T230000Z-before-import-${cmd.id}`;
118 await sync({
119 agent: 1,
120 services: [{ name: "hub", state: "running" }],
121 results: [{ id: cmd.id, ok: true, output: "1/6 downloading the world\n…\ndone" }],
122 snapshots: { hub: [{ name: snap, bytes: 52_428_800, at: "2026-12-01T23:00:00Z" }] },
123 });
124 expect(commandOf(app.db, cmd.id)!.ok).toBe(true);
125 const box = boxNamed(app.db, "mc")!;
126 expect(undoOf(box, "hub", cmd.id)?.name).toBe(snap);
127 const page = await (await http.handle(new Request("http://forge.test/games/mc/hub", { headers: { cookie } }))).text();
128 expect(page).toContain("<h2>World</h2>");
129 expect(page).toContain(snap);
130 expect(page).toContain("50 MB");
131 expect(page).toMatch(/>\s*Undo\s*<\/button>/);
132 expect(page).toContain("import a world from x.supabase.co/hub-world.tar.gz");
133 expect(page).not.toContain("token=t");
134 // Restore names a snapshot the box keeps; any other is refused.
135 expect(queueWorld(app.db, box, "hub", { op: "restore", snapshot: "nope" }, ada)).toEqual({
136 ok: false,
137 error: "hub keeps no snapshot called nope.",
138 });
139 expect(queueWorld(app.db, box, "hub", { op: "restore", snapshot: snap }, ada).ok).toBe(true);
140 });
141
142 test("the games tool queues an import and lists each service's snapshots", async () => {
143 const call = async (args: Record<string, unknown>) => {
144 const res = await http.handle(
145 new Request("http://forge.test/mcp", {
146 method: "POST",
147 headers: {
148 "content-type": "application/json",
149 accept: "application/json, text/event-stream",
150 authorization: `Bearer ${createToken(app.db, ada.id, "w", "admin").token}`,
151 },
152 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "games", arguments: args } }),
153 }),
154 );
155 const body = (await res.json()) as { result: { content: { text: string }[] } };
156 return JSON.parse(body.result.content[0]!.text) as Record<string, any>;
157 };
158 const listed = await call({ action: "list" });
159 expect(listed["items"][0].snapshots.hub[0].name).toContain("before-import-");
160 const queued = await call({ action: "world", box: "mc", service: "hub", op: "import", url: "https://x.supabase.co/storage/v1/object/sign/mc-worlds/survival.zip?token=eyJsecret" });
161 expect(queued["id"]).toBeString();
162 // The answer names the link by host and path only.
163 expect(queued["from"]).toBe("x.supabase.co/storage/v1/object/sign/mc-worlds/survival.zip");
164 expect(JSON.stringify(queued)).not.toContain("eyJsecret");
165 expect(JSON.parse(commandOf(app.db, queued["id"])!.text).op).toBe("import");
166 });
167 });
168
169 describe("the agent", () => {
170 // The link is a .tar.gz, so the test needs tar, not unzip: unzip runs in the box's helper container.
171 const lacks = ["bash", "curl", "jq", "tar"].filter((t) => Bun.which(t) === null);
172 test.skipIf(lacks.length > 0)(
173 `imports a world from a link: download, level.dat, stop, snapshot, swap, start, and lists the snapshot${lacks.length > 0 ? ` (skipped: no ${lacks.join(", ")} here)` : ""}`,
174 async () => {
175 const root = mkdtempSync(join(tmpdir(), "forge-game-world-agent-"));
176 const box = join(root, "box");
177 const data = join(root, "data");
178 const calls = join(root, "calls");
179 mkdirSync(box);
180 // The world the server has: level.dat says "old".
181 mkdirSync(join(data, "world"), { recursive: true });
182 writeFileSync(join(data, "world", "level.dat"), "old");
183 // The world in the link: a folder with its level.dat, and its nether beside it.
184 const src = join(root, "src");
185 mkdirSync(join(src, "hub-world", "region"), { recursive: true });
186 writeFileSync(join(src, "hub-world", "level.dat"), "new");
187 writeFileSync(join(src, "hub-world", "region", "r.0.0.mca"), "chunks");
188 mkdirSync(join(src, "hub-world_nether"));
189 writeFileSync(join(src, "hub-world_nether", "level.dat"), "nether");
190 expect(Bun.spawnSync(["tar", "czf", join(root, "hub-world.tar.gz"), "-C", src, "hub-world", "hub-world_nether"]).exitCode).toBe(0);
191 // A docker whose helper container is a shell in the data folder, its /in the agent's world folder.
192 const fake = join(root, "docker");
193 writeFileSync(
194 fake,
195 `#!/usr/bin/env bash
196 echo "$*" >> "${calls}"
197 case "$*" in
198 *" ps -a -q hub") echo cid1 ;;
199 *" ps -a --format json") echo '{"Service":"hub","Name":"hub","State":"running"}' ;;
200 "image inspect "*) exit 0 ;;
201 run\\ *)
202 script="\${@: -1}"
203 script="\${script//\\/in\\//${join(box, ".world")}/}"
204 [ "$(uname)" = Darwin ] && script="\${script//stat -c \\'%n %s %Y\\'/stat -f \\'%N %z %m\\'}"
205 cd "${data}" && exec sh -euc "$script" ;;
206 esac
207 exit 0
208 `,
209 );
210 chmodSync(fake, 0o755);
211 const bodies: Record<string, any>[] = [];
212 const archive = readFileSync(join(root, "hub-world.tar.gz"));
213 const forge: ReturnType<typeof Bun.serve> = Bun.serve({
214 port: 0,
215 hostname: "127.0.0.1",
216 async fetch(req): Promise<Response> {
217 if (new URL(req.url).pathname === "/hub-world.tar.gz") return new Response(archive);
218 bodies.push((await req.json()) as Record<string, any>);
219 const url: string = `http://127.0.0.1:${String(forge.port)}/hub-world.tar.gz?token=sekrit`;
220 return Response.json(
221 bodies.length === 1
222 ? { composeSha: "", commands: [{ id: "w1", kind: "world", service: "hub", text: JSON.stringify({ op: "import", url }) }] }
223 : { composeSha: "", commands: [] },
224 );
225 },
226 });
227 try {
228 const run = async (): Promise<string> => {
229 const p = Bun.spawn(["bash", AGENT], {
230 env: {
231 PATH: process.env["PATH"] ?? "",
232 FORGE_URL: `http://127.0.0.1:${String(forge.port)}`,
233 FORGE_GAME_TOKEN: TOKEN,
234 FORGE_GAME_DIR: box,
235 FORGE_GAME_DOCKER: fake,
236 FORGE_GAME_ONCE: "1",
237 },
238 stdout: "pipe",
239 stderr: "pipe",
240 });
241 await p.exited;
242 return new Response(p.stderr).text();
243 };
244 const said = await run();
245 expect(bodies.length, `the agent sent nothing; it said: ${said}`).toBe(1);
246 // The job runs in the background; its exit status lands in .job.rc.
247 // The job runs in the background, its own process; its exit status lands in .job.rc (at most 60 s).
248 const rc = join(box, ".job.rc");
249 expect(Bun.spawnSync(["bash", "-c", `for i in $(seq 1 600); do [ -f "${rc}" ] && exit 0; sleep 0.1; done; exit 1`]).exitCode).toBe(0);
250 const log = readFileSync(join(box, ".up.log"), "utf8");
251 expect(log).toContain("1/6 downloading the world from 127.0.0.1:");
252 // The link's secret is nowhere: not in the job's log, docker's calls, or a file left behind.
253 expect(log).not.toContain("sekrit");
254 expect(readFileSync(calls, "utf8")).not.toContain("sekrit");
255 expect(Bun.spawnSync(["grep", "-r", "sekrit", box]).exitCode).toBe(1);
256 expect(log).toContain("2/6 checking it is a world");
257 expect(log).toContain("done");
258 expect(readFileSync(join(box, ".job.rc"), "utf8").trim()).toBe("0");
259 // The new world is in place under the server's level name, its nether beside it.
260 expect(readFileSync(join(data, "world", "level.dat"), "utf8")).toBe("new");
261 expect(readFileSync(join(data, "world", "region", "r.0.0.mca"), "utf8")).toBe("chunks");
262 expect(readFileSync(join(data, "world_nether", "level.dat"), "utf8")).toBe("nether");
263 // The old one is kept, named for the import, and the server stopped and started around the swap.
264 const kept = JSON.parse(readFileSync(join(box, ".world", "snapshots.json"), "utf8")) as { hub: { name: string; bytes: number }[] };
265 expect(kept.hub.length).toBe(1);
266 expect(kept.hub[0]!.name).toMatch(/^\d{8}T\d{6}Z-before-import-w1$/);
267 const listing = Bun.spawnSync(["tar", "tzf", join(data, "forge-snapshots", `${kept.hub[0]!.name}.tar.gz`)]).stdout.toString();
268 expect(listing).toContain("world/level.dat");
269 const docker = readFileSync(calls, "utf8");
270 expect(docker.indexOf(" stop hub")).toBeGreaterThan(-1);
271 expect(docker.indexOf(" start hub")).toBeGreaterThan(docker.indexOf(" stop hub"));
272 // The next sync carries the result and the snapshot list.
273 await run();
274 const last = bodies.at(-1)!;
275 expect(last["results"]).toEqual([expect.objectContaining({ id: "w1", ok: true })]);
276 expect(last["snapshots"].hub[0].name).toBe(kept.hub[0]!.name);
277 expect(JSON.stringify(bodies)).not.toContain("sekrit");
278 } finally {
279 forge.stop(true);
280 await rm(root, { recursive: true, force: true });
281 }
282 },
283 60_000,
284 );
285 });
test/tui-games.test.ts +37 −1
@@ -14,7 +14,8 @@ import { commitToBranch, createRepo } from "../src/actions/repos.ts";
1414 import { createApp, type App } from "../src/app.ts";
1515 import { createUser, getUserByName, type User } from "../src/core/users.ts";
1616 import { pluginsOf, readCompose, serviceEnv } from "../src/games/compose.ts";
17 import { boxNamed, createGameBox, grantsOf, recentCommands, recordSync } from "../src/games/store.ts";
17 import { boxNamed, createGameBox, grant, grantsOf, recentCommands, recordSync } from "../src/games/store.ts";
18 import { queueWorld } from "../src/games/worlds.ts";
1819 import { createForgeApp } from "../src/tui/forge.ts";
1920 import { gameGrantsScreen, gameServiceScreen, gamesScreen } from "../src/tui/screens/games.ts";
2021 import { headlessTerminal } from "../src/tui/term/terminal.ts";
@@ -35,6 +36,7 @@ let dir = "";
3536 let app: App;
3637 let alice: User;
3738 let bob: User;
39 let carol: User;
3840
3941 beforeAll(async () => {
4042 dir = await mkdtemp(join(tmpdir(), "forge-tui-games-"));
@@ -42,6 +44,7 @@ beforeAll(async () => {
4244 for (const [username, adminIfFirst] of [
4345 ["alice", true],
4446 ["bob", false],
47 ["carol", false],
4548 ] as const) {
4649 const made = await createUser(app.db, {
4750 origin: "seed",
@@ -55,6 +58,7 @@ beforeAll(async () => {
5558 }
5659 alice = getUserByName(app.db, "alice")!;
5760 bob = getUserByName(app.db, "bob")!;
61 carol = getUserByName(app.db, "carol")!;
5862 const repo = await createRepo(app, alice, { name: "mc-network", visibility: "private" });
5963 if (!repo.ok) throw new Error(String(repo.error));
6064 const seeded = await commitToBranch(app, alice, repo.value, {
@@ -145,6 +149,38 @@ test("a service's console shows its log and queues an rcon command; env and plug
145149 tui.stop?.();
146150 });
147151
152 test("a viewer's i and u are refused, here as on the page and in the tool: the same queueWorld check", async () => {
153 const box = boxNamed(app.db, "net")!;
154 grant(app.db, box.id, carol.id, "viewer", "hub");
155 const before = recentCommands(app.db, box.id, "hub", 50).length;
156 const { tui, session, type } = drive(carol);
157 tui.ctx.push(gameServiceScreen(session, tui.ctx, box, "hub"));
158 await settleApp(tui);
159 for (const key of ["i", "u", "n"]) {
160 await type(key);
161 expect(tui.screen.toText()).toContain("You are not an operator of hub.");
162 }
163 tui.stop?.();
164 expect(queueWorld(app.db, box, "hub", { op: "import", url: "https://x.example/w.zip" }, carol)).toEqual({ ok: false, error: "You are not an operator of hub." });
165 expect(queueWorld(app.db, box, "hub", { op: "snapshot" }, undefined)).toEqual({ ok: false, error: "You are not an operator of hub." });
166 expect(recentCommands(app.db, box.id, "hub", 50)).toHaveLength(before);
167 grant(app.db, box.id, carol.id, "none", "hub");
168 });
169
170 test("the console tab shows an import's link as host and path, never its query string", async () => {
171 const box = boxNamed(app.db, "net")!;
172 const queued = queueWorld(app.db, box, "hub", { op: "import", url: "https://x.supabase.co/storage/hub-world.tar.gz?token=s3cr3t&expires=9" }, alice);
173 expect(queued.ok).toBe(true);
174 const { tui, session } = drive(alice);
175 tui.ctx.push(gameServiceScreen(session, tui.ctx, box, "hub"));
176 await settleApp(tui);
177 const text = tui.screen.toText();
178 expect(text).toContain("> import a world from x.supabase.co/storage/hub-world.tar.gz");
179 expect(text).not.toContain("s3cr3t");
180 expect(text).not.toContain("?token");
181 tui.stop?.();
182 });
183
148184 test("grants: listed to the box's owner, set by them; a member who is not an owner is refused", async () => {
149185 const box = boxNamed(app.db, "net")!;
150186 const asBob = drive(bob);

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

Keyboard shortcuts

Docs