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
Merged 35h 14m ago, live in production
sold/world-import → main 0 commits 5 threads · 5 unresolved
18 files
changed +780
−20
- docs/features/games.md
- src/core/empty_words.ts
- src/core/migration-pins/20261201230000-game-world-snapshots.pin
- src/core/migrations/20261201230000-game-world-snapshots.ts
- src/crew/conversation_ask.ts
- src/games/agent.sh
- src/games/snapshots.ts
- src/games/store.ts
- src/games/worlds.ts
- src/generated/migrations.ts
- src/http/games_routes.ts
- src/http/lazy_lists.ts
- src/http/mcp/tools/games.ts
- src/tui/screens/games.ts
- src/web/pages/games.ts
- test/conversation-ask.test.ts
- test/game-world.test.ts
- test/tui-games.test.ts
docs/features/games.md +10
| @@ -45,6 +45,16 @@ A service page has a People block (#17284), with no plugin on the game servers: | ||
| 45 | 45 | |
| 46 | 46 | 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. |
| 47 | 47 | |
| 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 | ||
| 48 | 58 | ## Secrets |
| 49 | 59 | |
| 50 | 60 | 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 = { | ||
| 100 | 100 | gameServices: { sentence: "Nothing has reported yet.", reason: "The box shows its services once its agent first syncs." }, |
| 101 | 101 | gamePlugins: { sentence: "Nothing is installed.", reason: "Add a URL, a Modrinth project or a jar below." }, |
| 102 | 102 | 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." }, | |
| 103 | 104 | } as const satisfies Readonly<Record<string, EmptyWords>>; |
| 104 | 105 | |
| 105 | 106 | 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 { | ||
| 136 | 136 | return `Build the infrastructure plan ${val(a, "id")} on your own cloud: it spends money each month`; |
| 137 | 137 | } |
| 138 | 138 | |
| 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 | ||
| 139 | 148 | export const ASKED_AS: Readonly<Record<string, Form>> = { |
| 140 | 149 | // The everyday work, the fence's undoable list first. |
| 141 | 150 | allocation: (a) => |
| @@ -345,6 +354,12 @@ export const ASKED_AS: Readonly<Record<string, Form>> = { | ||
| 345 | 354 | }; |
| 346 | 355 | return words[val(a, "op")] ?? `Change ${p} on ${on}`; |
| 347 | 356 | } |
| 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`; | |
| 348 | 363 | return `Change ${on}`; |
| 349 | 364 | }, |
| 350 | 365 | 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 | ||
| 267 | 267 | # One array, the real program and its flags: timeout(1) and `bash -c` both run it, which a shell |
| 268 | 268 | # function never could be. |
| 269 | 269 | COMPOSE=("" compose -p game --project-directory "" -f "/compose.yml") |
| 270 | # The same, as a function, for the world job's own bash (exported below; an array cannot be). | |
| 271 | compose() { "" compose -p game --project-directory "" -f "/compose.yml" "$@"; } | |
| 270 | 272 | now() { date -u +%Y-%m-%dT%H:%M:%SZ; } |
| 271 | 273 | # A quick command that must not hang the loop: at most 30 s where timeout(1) is there. |
| 272 | 274 | # Run a command for at most `secs` seconds, timeout(1) or not: a docker that hangs never holds the |
| @@ -474,6 +476,19 @@ run() { | ||
| 474 | 476 | touch "/.people.due" |
| 475 | 477 | fi |
| 476 | 478 | ;; |
| 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 ! [[ "" =~ ]] || ! jq -e '.op | IN("import", "restore", "snapshot")' >/dev/null 2>&1 <<<""; then | |
| 483 | out="refused: a world command is an import, a restore or a snapshot" | |
| 484 | ok=false | |
| 485 | else | |
| 486 | mkdir -p "" | |
| 487 | printf '%s' "" >"/.json" | |
| 488 | queue_job "" "world $(jq -r .op <<<"") " "" world "" "" | |
| 489 | return | |
| 490 | fi | |
| 491 | ;; | |
| 477 | 492 | *) |
| 478 | 493 | out="refused: is not a command this agent runs" |
| 479 | 494 | ok=false |
| @@ -553,7 +568,11 @@ job_tick() { | ||
| 553 | 568 | now >"/.job.since" |
| 554 | 569 | # Its own bash, named on its command line ($0), writing its exit status only when it ends. |
| 555 | 570 | # shellcheck disable=SC2086,SC2016 # the verb and its words, each a safe name; the script is single-quoted on purpose |
| 556 | DIR="" bash -c '"$@" >"$DIR/.up.log" 2>&1; echo $? >"$DIR/.job.rc"' "" "" & | |
| 571 | if [ "" = world ]; then | |
| 572 | DOCKER="" DIR="" bash -c 'world_job "$@" >"$DIR/.up.log" 2>&1; echo $? >"$DIR/.job.rc"' "" & | |
| 573 | else | |
| 574 | DIR="" bash -c '"$@" >"$DIR/.up.log" 2>&1; echo $? >"$DIR/.job.rc"' "" "" & | |
| 575 | fi | |
| 557 | 576 | echo $! >"/.job.pid" |
| 558 | 577 | } |
| 559 | 578 | |
| @@ -687,6 +706,138 @@ bounded_diag() { | ||
| 687 | 706 | if [ -s "" ] && jq -e . "" >/dev/null 2>&1; then cat ""; else echo '{}'; fi |
| 688 | 707 | } |
| 689 | 708 | |
| 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="/.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() { "" run --rm --volumes-from "$1" -v ":/in:ro" -w /data "" 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 "" "sed -n 's/^level-name=//p' server.properties 2>/dev/null | head -n 1" 2>/dev/null | tr -d '\r')" | |
| 730 | [[ "" =~ ^[A-Za-z0-9._-]{1,64}$ ]] && printf '%s' "" || 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 "" "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 "" --arg rows "" --slurpfile all <(cat "/snapshots.json" 2>/dev/null || echo '{}') ' | |
| 737 | ([0] // {}) + {(): [ | 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 "" "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 \"" | |
| 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 "/$2.json" "/$2.archive" "/$2.curl" | |
| 757 | return "" | |
| 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="/.json" | |
| 764 | op="$(jq -r '.op // ""' "" 2>/dev/null)" | |
| 765 | cid="$(world_cid "")" | |
| 766 | if [ -z "" ]; then echo " has no container yet: nothing to change"; return 1; fi | |
| 767 | level="$(world_level "")" | |
| 768 | stamp="$(date -u +%Y%m%dT%H%M%SZ)" | |
| 769 | "" image inspect "" >/dev/null 2>&1 || "" pull -q "" >/dev/null || { echo "could not fetch the helper image "; return 1; } | |
| 770 | case "" in | |
| 771 | import) | |
| 772 | url="$(jq -r '.url // ""' "")" | |
| 773 | # Said as host and path only: the query string of a signed link is its secret. | |
| 774 | shown="" | |
| 775 | echo "1/6 downloading the world from " | |
| 776 | rm -f "/.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' "" | sed 's/[\\"]/\\&/g')" >"$WORLDS/$id.curl" | |
| 779 | curl -fsSL --proto '=https,http' --max-filesize 8589934592 --retry 2 -K "/.curl" -o "/.archive" || { echo "the download failed: check the link (a signed link may have expired)"; return 1; } | |
| 780 | echo " $(du -h "/.archive" | cut -f1) downloaded" | |
| 781 | echo "2/6 checking it is a world" | |
| 782 | if ! world_sh "" "rm -rf .forge-import && mkdir .forge-import && cd .forge-import | |
| 783 | case \"\$(head -c 2 /in/.archive | od -An -tx1 | tr -d ' ')\" in | |
| 784 | 504b) unzip -q /in/.archive ;; | |
| 785 | 1f8b) tar xzf /in/.archive ;; | |
| 786 | *) tar xf /in/.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 "/.archive" | |
| 794 | world_sh "" "rm -rf .forge-import .forge-import.root" >/dev/null 2>&1 | |
| 795 | return 1 | |
| 796 | fi | |
| 797 | rm -f "/.archive" | |
| 798 | echo " level.dat found" | |
| 799 | echo "3/6 stopping " | |
| 800 | compose stop "" >/dev/null 2>&1 || { echo "could not stop "; return 1; } | |
| 801 | echo "4/6 keeping the world it had" | |
| 802 | world_snapshot "" "" "-before-import-" || { echo "the snapshot failed: the world is untouched"; compose start "" >/dev/null 2>&1; return 1; } | |
| 803 | echo "5/6 putting the new world in place as " | |
| 804 | world_sh "" "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\" '_nether' | |
| 807 | [ -d \".forge-import/\$parent/\${base}_the_end\" ] && mv \".forge-import/\$parent/\${base}_the_end\" '_the_end' | |
| 808 | if [ \"\$root\" = . ]; then mkdir '' && find .forge-import -mindepth 1 -maxdepth 1 -exec mv {} ''/ \; ; else mv \".forge-import/\$root\" ''; fi | |
| 809 | rm -f '$level/session.lock'; rm -rf .forge-import .forge-import.root | |
| 810 | " || ok=1 | |
| 811 | ;; | |
| 812 | restore) | |
| 813 | snap="$(jq -r '.snapshot // ""' "")" | |
| 814 | [[ "" =~ ^[A-Za-z0-9._-]{1,120}$ ]] || { echo "no such snapshot"; return 1; } | |
| 815 | echo "1/4 stopping " | |
| 816 | compose stop "" >/dev/null 2>&1 || { echo "could not stop "; return 1; } | |
| 817 | echo "2/4 keeping the world it has" | |
| 818 | world_snapshot "" "" "-before-restore-" || { echo "the snapshot failed: the world is untouched"; compose start "" >/dev/null 2>&1; return 1; } | |
| 819 | echo "3/4 putting back " | |
| 820 | world_sh "" "[ -f 'forge-snapshots/.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 | " || ok=1 | |
| 823 | ;; | |
| 824 | snapshot) | |
| 825 | echo "1/3 stopping , so the world on disk is whole" | |
| 826 | compose stop "" >/dev/null 2>&1 || { echo "could not stop "; return 1; } | |
| 827 | echo "2/3 keeping the world" | |
| 828 | world_snapshot "" "" "-$( jq -r '.name // "by-hand"' "" | 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 " | |
| 833 | compose start "" >/dev/null 2>&1 || { echo "could not start "; ok=1; } | |
| 834 | world_index "" "" | |
| 835 | [ "" = 0 ] && echo "done" || echo "it did not finish: the step above says why, and the snapshot is listed" | |
| 836 | return "" | |
| 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 | ||
| 690 | 841 | sync() { |
| 691 | 842 | local next answer |
| 692 | 843 | next="$(now)" |
| @@ -699,6 +850,7 @@ sync() { | ||
| 699 | 850 | bounded_diag | json_or '{}' >"/.sync.diag" |
| 700 | 851 | people | json_or '{}' >"/.sync.people" |
| 701 | 852 | metrics | json_or '{}' >"/.sync.metrics" |
| 853 | jq -c 'if type == "object" then . else {} end' "/snapshots.json" 2>/dev/null | json_or '{}' >"/.sync.snapshots" | |
| 702 | 854 | # Every string as plain text: real servers print colour escapes and control bytes (itzg's logs, |
| 703 | 855 | # rcon-cli's colours), and the forge takes none of them. |
| 704 | 856 | jq -cn \ |
| @@ -710,8 +862,9 @@ sync() { | ||
| 710 | 862 | --slurpfile diag "/.sync.diag" \ |
| 711 | 863 | --slurpfile people "/.sync.people" \ |
| 712 | 864 | --slurpfile metrics "/.sync.metrics" \ |
| 865 | --slurpfile snapshots "/.sync.snapshots" \ | |
| 713 | 866 | 'def plain: gsub("\u001b\\[[0-9;?]*[ -/]*[@-~]"; "") | gsub("\u001b[@-_]?"; "") | gsub("[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f]"; ""); |
| 714 | {agent: 1, composeSha: , services: [0], logs: [0], results: [0], host: [0], diag: [0], people: [0], metrics: [0]} | |
| 867 | {agent: 1, composeSha: , services: [0], logs: [0], results: [0], host: [0], diag: [0], people: [0], metrics: [0], snapshots: [0]} | |
| 715 | 868 | | walk(if type == "string" then plain else . end)' >"$DIR/.sync.body" || return 1 |
| 716 | 869 | answer="$(curl -fsS -m 20 -H "@" -H 'content-type: application/json' --data-binary "@/.sync.body" "/api/v1/games/agent/sync")" || return 1 |
| 717 | 870 | # 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 @@ | ||
| 9 | 9 | |
| 10 | 10 | import type { Database } from "bun:sqlite"; |
| 11 | 11 | import { keptDiag, readDiag, type Diag } from "./diag.ts"; |
| 12 | import { keptSnapshots, keptWorldText, readSnapshots, type Snapshot } from "./snapshots.ts"; | |
| 12 | 13 | import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"; |
| 13 | 14 | import { rm } from "node:fs/promises"; |
| 14 | 15 | import type { App } from "../app.ts"; |
| @@ -24,7 +25,7 @@ export const LOG_KEEP = 2_000; | ||
| 24 | 25 | const LINES_A_SYNC = 200; |
| 25 | 26 | /** The most of a command's output kept: a shell's 16 KB (`shell.ts`); the rest say far less. */ |
| 26 | 27 | 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; | |
| 28 | 29 | export type CommandKind = (typeof COMMAND_KINDS)[number]; |
| 29 | 30 | export type Role = "owner" | "operator" | "viewer"; |
| 30 | 31 | const RANK: Record<Role, number> = { viewer: 1, operator: 2, owner: 3 }; |
| @@ -46,6 +47,8 @@ export interface GameBox { | ||
| 46 | 47 | readonly boot: string; |
| 47 | 48 | /** The latest diagnosis the agent sent (`diag.ts`), replaced each sync. */ |
| 48 | 49 | 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[]>; | |
| 49 | 52 | } |
| 50 | 53 | |
| 51 | 54 | export interface GameService { |
| @@ -75,6 +78,7 @@ interface BoxRow { | ||
| 75 | 78 | created_at: string; |
| 76 | 79 | boot: string; |
| 77 | 80 | diag_json: string; |
| 81 | snapshots_json: string; | |
| 78 | 82 | } |
| 79 | 83 | const toBox = (r: BoxRow): GameBox => { |
| 80 | 84 | let host: Record<string, number> = {}; |
| @@ -96,6 +100,7 @@ const toBox = (r: BoxRow): GameBox => { | ||
| 96 | 100 | createdAt: r.created_at, |
| 97 | 101 | boot: r.boot, |
| 98 | 102 | diag: readDiag(r.diag_json), |
| 103 | snapshots: readSnapshots(r.snapshots_json), | |
| 99 | 104 | }; |
| 100 | 105 | }; |
| 101 | 106 | |
| @@ -255,7 +260,8 @@ export function queueCommand(db: Database, boxId: string, service: string, kind: | ||
| 255 | 260 | boxId, |
| 256 | 261 | service, |
| 257 | 262 | 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), | |
| 259 | 265 | by, |
| 260 | 266 | new Date().toISOString(), |
| 261 | 267 | ); |
| @@ -441,6 +447,8 @@ export interface SyncBody { | ||
| 441 | 447 | readonly boot?: string; |
| 442 | 448 | /** What the box sees of itself, about 8 KB (`diag.ts`): kept, replacing the last. */ |
| 443 | 449 | readonly diag?: unknown; |
| 450 | /** Each service's world snapshots (`worlds.ts`). */ | |
| 451 | readonly snapshots?: unknown; | |
| 444 | 452 | } |
| 445 | 453 | |
| 446 | 454 | const str = (v: unknown, max = 200): string => (typeof v === "string" ? v.slice(0, max) : ""); |
| @@ -470,6 +478,8 @@ export function recordSync( | ||
| 470 | 478 | str(body.composeSha, 80), |
| 471 | 479 | keptDiag(body.diag), |
| 472 | 480 | ); |
| 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)); | |
| 473 | 483 | for (const s of (body.services ?? []).slice(0, 64)) { |
| 474 | 484 | const name = str(s.name, 64); |
| 475 | 485 | if (!SERVICE_NAME.test(name)) continue; |
| @@ -506,5 +516,8 @@ export function recordSync( | ||
| 506 | 516 | >("SELECT id, kind, service, text FROM game_command WHERE box_id = ?1 AND handed_at = '' ORDER BY created_at LIMIT 32") |
| 507 | 517 | .all(box.id); |
| 508 | 518 | 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)); | |
| 509 | 522 | return due; |
| 510 | 523 | } |
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"; | ||
| 462 | 462 | import m458 from "../core/migrations/20261201190200-dep-accept.ts"; |
| 463 | 463 | import m459 from "../core/migrations/20261201190500-runner-machine.ts"; |
| 464 | 464 | 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"; | |
| 467 | 468 | |
| 468 | 469 | /** Each migration file's name and its default export, in name order. */ |
| 469 | 470 | export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [ |
| @@ -928,6 +929,7 @@ export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [ | ||
| 928 | 929 | ["20261201190200-dep-accept.ts", m458], |
| 929 | 930 | ["20261201190500-runner-machine.ts", m459], |
| 930 | 931 | ["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], | |
| 933 | 935 | ]; |
src/http/games_routes.ts +2 −1
| @@ -13,7 +13,7 @@ import { sleeping } from "../games/sleep.ts"; | ||
| 13 | 13 | import { boxByToken, envFiles, markAsleep, recordSync, signJarUrls, type SyncBody } from "../games/store.ts"; |
| 14 | 14 | import { BODY_CAPS } from "../kernel/body_caps.ts"; |
| 15 | 15 | 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, | |
| 17 | 17 | } from "../web/pages/games.ts"; |
| 18 | 18 | import type { Ctx, Handler } from "./context.ts"; |
| 19 | 19 | import { InvalidJson } from "./json_body.ts"; |
| @@ -88,6 +88,7 @@ export function gamesRoutes(router: Router<Handler>): void { | ||
| 88 | 88 | router.add("POST", "/games/:box/:service/plugin", gamePluginSubmit); |
| 89 | 89 | router.add("POST", "/games/:box/:service/sleep", gameSleepSubmit); |
| 90 | 90 | router.add("POST", "/games/:box/:service/people", gamePeopleSubmit); |
| 91 | router.add("POST", "/games/:box/:service/world", gameWorldSubmit); | |
| 91 | 92 | router.add("POST", "/games/:box/:service/jar", gameJarSubmit); |
| 92 | 93 | router.add("POST", "/games/:box/:service/settings", gameSettingsSubmit); |
| 93 | 94 | } |
src/http/lazy_lists.ts +1
| @@ -620,6 +620,7 @@ export const OPERATIONS_ROUTES = [ | ||
| 620 | 620 | ["POST", "/games/:box/:service/plugin"], |
| 621 | 621 | ["POST", "/games/:box/:service/sleep"], |
| 622 | 622 | ["POST", "/games/:box/:service/people"], |
| 623 | ["POST", "/games/:box/:service/world"], | |
| 623 | 624 | ["POST", "/games/:box/:service/jar"], |
| 624 | 625 | ["POST", "/games/:box/:service/settings"], |
| 625 | 626 | ["GET", "/resilience"], |
src/http/mcp/tools/games.ts +25 −5
| @@ -8,22 +8,26 @@ import { boxNamed, listBoxes, mayDo, queueCommand, roleOn, seesBox, SERVICE_NAME | ||
| 8 | 8 | import { good, bad, type Tool, str } from "../shared.ts"; |
| 9 | 9 | import { commitPolicy } from "../../../games/sleep.ts"; |
| 10 | 10 | 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"; | |
| 11 | 13 | |
| 12 | 14 | const POWER = ["start", "stop", "restart", "recreate", "pull"]; |
| 13 | 15 | |
| 14 | 16 | export const tool: Tool = { |
| 15 | 17 | name: "games", |
| 16 | 18 | 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.", | |
| 19 | 21 | inputSchema: { |
| 20 | 22 | type: "object", |
| 21 | 23 | 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"] }, | |
| 24 | 26 | player: { type: "string", maxLength: 17 }, |
| 25 | 27 | to: { type: "string", maxLength: 64 }, |
| 26 | 28 | window: { type: "string", enum: Object.keys(WINDOWS) }, |
| 29 | url: { type: "string", maxLength: 3800 }, | |
| 30 | snapshot: { type: "string", maxLength: 120 }, | |
| 27 | 31 | box: { type: "string", maxLength: 40 }, |
| 28 | 32 | service: { type: "string", maxLength: 64 }, |
| 29 | 33 | text: { type: "string", maxLength: 1000 }, |
| @@ -67,6 +71,7 @@ export const tool: Tool = { | ||
| 67 | 71 | status: (mayDo(roleOn(db, user, b.id), "owner") ? boxStatus(b.diag) : boxStatusShared(b.diag)).slice(0, 3), |
| 68 | 72 | ...(cloud[i] === undefined ? {} : { cloud: cloud[i] }), |
| 69 | 73 | 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)])), | |
| 70 | 75 | })), |
| 71 | 76 | }); |
| 72 | 77 | } |
| @@ -142,6 +147,21 @@ export const tool: Tool = { | ||
| 142 | 147 | const done = await commitPolicy(ctx.app, user, box, service, policy); |
| 143 | 148 | 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); |
| 144 | 149 | } |
| 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"); | |
| 146 | 166 | }, |
| 147 | 167 | }; |
src/tui/screens/games.ts +38 −4
| @@ -17,6 +17,7 @@ import { commitPolicy, policyOf, stateWords } from "../../games/sleep.ts"; | ||
| 17 | 17 | import { SHELL_SERVICE, queueShell } from "../../games/shell.ts"; |
| 18 | 18 | import { onSync } from "../../games/notify.ts"; |
| 19 | 19 | import { eventsOf, isBedrock, peopleOf, peopleWords, queuePeople } from "../../games/people.ts"; |
| 20 | import { queueWorld, worldWords, type WorldOp } from "../../games/worlds.ts"; | |
| 20 | 21 | import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts"; |
| 21 | 22 | import { cloudLine, pinnedOfBox } from "../../actions/cloud_says.ts"; |
| 22 | 23 | import { getUserByName } from "../../core/users.ts"; |
| @@ -24,6 +25,7 @@ import { addPlugin, commitServiceEnv, pluginSays, pluginsOf, readCompose, servic | ||
| 24 | 25 | import { commitSettings, planSettings, settingsOf, type SettingsPlan, type SettingValue } from "../../games/settings.ts"; |
| 25 | 26 | import { |
| 26 | 27 | SERVICE_NAME, |
| 28 | boxNamed, | |
| 27 | 29 | bootTroubled, |
| 28 | 30 | bootWords, |
| 29 | 31 | grant, |
| @@ -169,7 +171,7 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen { | ||
| 169 | 171 | return screen; |
| 170 | 172 | } |
| 171 | 173 | |
| 172 | const PARTS = ["console", "env", "plugins", "people"] as const; | |
| 174 | const PARTS = ["console", "env", "plugins", "people", "world"] as const; | |
| 173 | 175 | type Part = (typeof PARTS)[number]; |
| 174 | 176 | |
| 175 | 177 | /** |
| @@ -194,7 +196,8 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 194 | 196 | }; |
| 195 | 197 | const lines = (): string[] => { |
| 196 | 198 | 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]}`}`); | |
| 198 | 201 | return [...logsOf(f.app.db, box.id, service, 200).lines, ...done]; |
| 199 | 202 | } |
| 200 | 203 | if (part === "people") { |
| @@ -208,6 +211,20 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 208 | 211 | "p: op, deop, whitelist-add, whitelist-remove, ban, pardon, kick <player>, or move <player> <server>", |
| 209 | 212 | ]; |
| 210 | 213 | } |
| 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 | } | |
| 211 | 228 | if (!loaded) return ["Reading the compose file…"]; |
| 212 | 229 | if (compose === undefined) return [`No ${box.path} on ${box.repo}@${box.branch}.`]; |
| 213 | 230 | if (part === "env") { |
| @@ -238,12 +255,15 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 238 | 255 | const screen: Screen = { |
| 239 | 256 | title: `${box.name}/${service}`, |
| 240 | 257 | keys: [ |
| 241 | binding(["tab"], "console, env, plugins, people"), | |
| 258 | binding(["tab"], "console, env, plugins, people, world"), | |
| 242 | 259 | binding([":"], "rcon"), |
| 243 | 260 | binding(["e"], "set env"), |
| 244 | 261 | binding(["a"], "add plugin"), |
| 245 | 262 | binding(["c"], "settings"), |
| 246 | 263 | 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"), | |
| 247 | 267 | ], |
| 248 | 268 | render(area, s) { |
| 249 | 269 | const c = ctx.theme.c; |
| @@ -299,7 +319,21 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s | ||
| 299 | 319 | await load(); |
| 300 | 320 | return pluginSays(done, false); |
| 301 | 321 | }); |
| 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; | |
| 303 | 337 | return true; |
| 304 | 338 | }, |
| 305 | 339 | }; |
src/web/pages/games.ts +56 −1
| @@ -33,6 +33,7 @@ import { | ||
| 33 | 33 | storeJar, |
| 34 | 34 | dropJar, |
| 35 | 35 | type CommandKind, |
| 36 | type CommandState, | |
| 36 | 37 | type GameBox, |
| 37 | 38 | type Role, |
| 38 | 39 | } from "../../games/store.ts"; |
| @@ -52,6 +53,7 @@ import { CLOUD_EVENT, cloudFacts, GAME_CLOUD_EVENT, pinnedOfBox } from "../../ac | ||
| 52 | 53 | import { topologyBlock, TOPOLOGY_CSS } from "./games_topology.ts"; |
| 53 | 54 | import { defaultHeadResponse, headResponse } from "../../games/heads.ts"; |
| 54 | 55 | import { eventsOf, isBedrock, knowsPlayer, peopleOf, peopleWords, queuePeople, UNDO, type PeopleOp } from "../../games/people.ts"; |
| 56 | import { queueWorld, undoOf, worldWords } from "../../games/worlds.ts"; | |
| 55 | 57 | import { emptyLine } from "../empty_words.ts"; |
| 56 | 58 | import { metricsSeries, playerEvents, recentErrors, type Point } from "../../games/metrics.ts"; |
| 57 | 59 | import { daySpark } from "../studio/kpi_row.ts"; |
| @@ -353,7 +355,7 @@ ${tail.lines.join("\n")}${tail.lines.length > 0 ? "\n" : ""}</pre | ||
| 353 | 355 | : rowList( |
| 354 | 356 | commands.map((c) => |
| 355 | 357 | 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>`, | |
| 357 | 359 | meta: html`<span id="cmd-${c.id}" |
| 358 | 360 | >${c.done ? `${c.ok ? "ok" : "failed"}: ${c.output}` : c.handed ? "sent to the box" : "queued"}</span |
| 359 | 361 | >`, |
| @@ -362,6 +364,7 @@ ${tail.lines.join("\n")}${tail.lines.length > 0 ? "\n" : ""}</pre | ||
| 362 | 364 | )} |
| 363 | 365 | </section> |
| 364 | 366 | ${compose === undefined || !canSleep(compose.text, service) ? null : sleepBlock(box, service, compose.text, seen?.asleep === true, act)} |
| 367 | ${worldBlock(box, service, act, commands)} | |
| 365 | 368 | <section class="settings-block"> |
| 366 | 369 | <h2>Environment</h2> |
| 367 | 370 | ${Object.keys(env).length === 0 |
| @@ -447,6 +450,58 @@ export function gameServiceStream(ctx: Ctx): Response { | ||
| 447 | 450 | ); |
| 448 | 451 | } |
| 449 | 452 | |
| 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 | ||
| 450 | 505 | async function operatorForm(ctx: Ctx): Promise<{ box: GameBox; service: string; form: Form } | Response> { |
| 451 | 506 | const service = ctx.params.service ?? ""; |
| 452 | 507 | 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])[] = [ | ||
| 526 | 526 | ["games", { action: "sleep", box: "net", service: "hub", value: "warm" }, "Keep hub on net warm, a commit that redeploys it."], |
| 527 | 527 | ["games", { action: "people", box: "mc", service: "hub", op: "ban", player: "Griefer" }, "Ban Griefer from hub on mc."], |
| 528 | 528 | ["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."], | |
| 529 | 531 | ["crew_accounts", { repo: "marin/cakes", allow: "espo-corp" }, "Let the crew's runs for marin/cakes spend the account espo-corp."], |
| 530 | 532 | ["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."], |
| 531 | 533 | ["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"; | ||
| 14 | 14 | import { createApp, type App } from "../src/app.ts"; |
| 15 | 15 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; |
| 16 | 16 | 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"; | |
| 18 | 19 | import { createForgeApp } from "../src/tui/forge.ts"; |
| 19 | 20 | import { gameGrantsScreen, gameServiceScreen, gamesScreen } from "../src/tui/screens/games.ts"; |
| 20 | 21 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; |
| @@ -35,6 +36,7 @@ let dir = ""; | ||
| 35 | 36 | let app: App; |
| 36 | 37 | let alice: User; |
| 37 | 38 | let bob: User; |
| 39 | let carol: User; | |
| 38 | 40 | |
| 39 | 41 | beforeAll(async () => { |
| 40 | 42 | dir = await mkdtemp(join(tmpdir(), "forge-tui-games-")); |
| @@ -42,6 +44,7 @@ beforeAll(async () => { | ||
| 42 | 44 | for (const [username, adminIfFirst] of [ |
| 43 | 45 | ["alice", true], |
| 44 | 46 | ["bob", false], |
| 47 | ["carol", false], | |
| 45 | 48 | ] as const) { |
| 46 | 49 | const made = await createUser(app.db, { |
| 47 | 50 | origin: "seed", |
| @@ -55,6 +58,7 @@ beforeAll(async () => { | ||
| 55 | 58 | } |
| 56 | 59 | alice = getUserByName(app.db, "alice")!; |
| 57 | 60 | bob = getUserByName(app.db, "bob")!; |
| 61 | carol = getUserByName(app.db, "carol")!; | |
| 58 | 62 | const repo = await createRepo(app, alice, { name: "mc-network", visibility: "private" }); |
| 59 | 63 | if (!repo.ok) throw new Error(String(repo.error)); |
| 60 | 64 | 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 | ||
| 145 | 149 | tui.stop?.(); |
| 146 | 150 | }); |
| 147 | 151 | |
| 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 | ||
| 148 | 184 | test("grants: listed to the box's owner, set by them; a member who is not an owner is refused", async () => { |
| 149 | 185 | const box = boxNamed(app.db, "net")!; |
| 150 | 186 | const asBob = drive(bob); |
new above
offline