Compare commits

...
Author SHA1 Message Date
ДмитрийandClaude Opus 5.5 3c26004e04 Custom races: switch in seconds (append-only journal, entry points only, hash cache)
V2 has 7,220 files. Switching rewrote the whole transaction journal with fsync after
every file (quadratic: minutes on fast disks, far longer with antivirus) and renamed
every file. Now:
- the journal is append-only JSON lines; recovery replays it, ignores a torn last
  line and still reads the old journal.json of 0.9.13;
- only what the stock client loads is hidden (Data/*.MPQ, root dll/exe/bat, addons,
  any file that replaced the player's own); Data/Retail, VulkanShaders and the
  Esteria data stay in place, and a client disabled by 0.9.13 is recognised;
- payload hashes are remembered for the run, keyed by name, size and times.
Real V2 archives, release build: disable 1.9 s, enable 2.2 s, 224 of 7,220 files moved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:10:43 +05:00
Corfirean e8ffa6efe3 Merge feat/custom-races-v2: Manager 0.9.13 with Custom Races V2 2026-11-15 08:14:40 +05:00
github-actions[bot] baeecd2ddf Update published Manager changelog 2026-11-15 02:08:39 +00:00
ДмитрийandClaude Opus 5.5 d352731280 Prepare Manager 0.9.13 with reviewed notes in six languages
Manager 0.9.13 carries the Custom Races V2 client. Its reviewed note and the 213 notes of the upcoming
server record (Custom Races V2: subclasses, Two-Players, the new races; collected with the pipeline's own
rules from the frozen sources of candidate run 43641984449) have Russian, German, French, Spanish and
Simplified Chinese translations. Bundled server history refreshed through 0.261114.106 from
coa-server-build 3308e3a.

Checks: release-history tests 5/5, check-i18n, npm run build, cargo check --locked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 02:27:37 +05:00
ДмитрийandClaude Opus 5.5 a0545286ee Install the Custom Races V2 client
The client update now takes ilusixn/CustomRacesCoa coa-custom-2.0: nine client archives plus the server
archive's client addons (subclass interface, dev menu, teleports, spell activation overlay), 76 race
archives and 7220 verified files in all, among them CoACustomRace.exe and its Vulkan renderer.

- The game starts CoACustomRace.exe when it is there; Ascension.exe is left alone, and a disabled V2
  falls back to it.
- Updating from 1.9.2 retires its patched Ascension.exe and puts the player's own back (1.9.2 replaced
  it; V2 does not ship one). Earlier installs keep their own hash lists, 1.9.2's included.
- Four V2 archives are byte-identical to 1.9.2's: a verified 1.9.2 copy in the cache or in Downloads
  is used instead of downloading it again.

Verified: unit tests (800 passed); against the real archives, every bundled hash, a full install,
disable, enable and uninstall in a disposable client, and an update of a client that Manager 0.9.12
had put 1.9.2 on (its own Ascension.exe comes back, and again after uninstalling).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 01:59:43 +05:00
ДмитрийandClaude Opus 5.5 6f8ed793a7 Merge integrate/release-0.9.12 (release 2026-11-14)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 09:56:41 +05:00
github-actions[bot] b3c88ce2a6 Update published Manager changelog 2026-11-14 04:41:00 +00:00
CorfireanandClaude Opus 5.5 d71c5635e3 Translate the auction house bot note of the upcoming server release
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 00:15:27 +05:00
CorfireanandClaude Opus 5.5 755761d0de Prepare Manager 0.9.12 with reviewed notes in six languages
Bundled server history refreshed through 0.261108.95 from coa-server-build ca04f96.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 00:05:14 +05:00
Corfirean 550e475962 Merge remote-tracking branch 'origin/feat/bot-scaling-settings' into integrate/release-0.9.12 2026-11-13 23:54:41 +05:00
github-actions[bot] b4dc30b84a Update published Manager changelog 2026-11-08 10:21:07 +00:00
Дмитрий 73a6cca753 Integrate the qualified November release sources [skip ci] 2026-11-08 15:09:20 +05:00
Corfirean 705bee7d56 Merge verified Custom Races download recovery [skip ci]
Recover interrupted Custom Races patch downloads
2026-11-08 01:44:09 +05:00
Corfirean 5aa9b32283 Merge release cold-cache preparation fix [skip ci]
release: build the frontend before the tests
2026-11-08 01:44:05 +05:00
Дмитрий 711f378ae8 Bind translated release notes to the exact candidate sources [skip ci] 2026-11-08 01:23:56 +05:00
Corfirean c29d56e2b3 Register local installer preparation workflow [skip ci] 2026-11-08 01:21:16 +05:00
Дмитрий d63e85bb18 Prepare Manager 0.9.10 with reviewed notes and signing of local installers [skip ci] 2026-11-08 01:20:32 +05:00
Дмитрий c513649beb Merge remote-tracking branch 'origin/fix/recover-client-patch-downloads' into release/20261108-manager 2026-11-08 01:09:43 +05:00
ДмитрийandClaude Sonnet 5.5 d2e6fef188 feat(bots): settings for bot strength scaling in dungeons and raids
Adds the CoaBots.Scaling.* keys (Enable, Dungeons, Raids, Battlegrounds,
World, DamageDone, HealingDone, DamageTaken, TankThreat, BossTuning) to the
bots schema under Combat, with defaults that change nothing (all multipliers 1,
boss tuning off), translations in five languages and a changelog fragment.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 16:22:47 +05:00
ДмитрийandClaude Opus 5.5 2224afd2ea release: build the frontend before the tests
tauri::generate_context! needs ../dist. The tests run before tauri-action builds the frontend, so a
run without a warm target cache cannot compile the app (seen on preview/modules-v2, run 42224568581).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 19:47:11 +05:00
github-actions[bot] 3a5558f388 Update published Manager changelog 2026-11-04 11:39:56 +00:00
Дмитрий 173248efbe Prepare Manager 0.9.9 with isolated login validation and translated release notes 2026-11-03 19:44:03 +05:00
Дмитрий 5697a1d36e Merge commit '076fba1' into release/20261103-manager 2026-11-03 19:41:07 +05:00
github-actions[bot] bc62ae206f Update published Manager changelog 2026-11-01 11:00:31 +00:00
Дмитрий 076fba185c Remove duplicate Dungeon Clear dependency translation key 2026-11-01 14:23:37 +05:00
Дмитрий 23cbb108ad Prepare Manager 0.9.8 with isolated validation and SQUID module controls 2026-10-31 20:00:11 +05:00
Дмитрий 1a1976d9ad Recover interrupted Custom Races patch downloads 2026-10-31 07:55:15 +05:00
github-actions[bot] dc3fcab7e1 Update published Manager changelog 2026-10-30 21:38:45 +00:00
Corfirean ba5816e3ae Merge pull request #191 from Corfirean/fix/reviewed-server-notes-20261030
Check all upcoming server-note translations before freezing the Manager
2026-10-30 20:57:37 +05:00
Дмитрий 56faaa3a2a Qualify translations against the exact upcoming server notes including SQUID 2.8.2 2026-10-30 20:32:31 +05:00
Corfirean 35084dbce8 Merge pull request #190 from Corfirean/fix/update-release-history-target-20261030
Show notes for the available update despite a fresh older history cache
2026-10-30 15:29:35 +05:00
Дмитрий 7e7216979a Refresh release notes for the offered update instead of reusing incomplete history 2026-10-30 15:08:29 +05:00
github-actions[bot] 7c0c4cda1f Update published Manager changelog 2026-10-30 09:47:37 +00:00
Corfirean 642da8fdc1 Merge pull request #189 from Corfirean/fix/stabilization-20261030
Stabilize server updates, shutdown, accounts and client settings
2026-10-30 14:12:59 +05:00
Дмитрий 30d2f56997 Stabilize server lifecycle, client settings and release qualification 2026-10-30 14:04:18 +05:00
Дмитрий 4d1a6e0b21 Retain experimental Portable Characters notice for Manager 0.9.4 2026-10-29 20:51:31 +05:00
github-actions[bot] bda38b9f26 Update published Manager changelog 2026-10-29 15:31:44 +00:00
Дмитрий c004b90c54 Translate reviewed server candidate notes for Manager 0.9.4 2026-10-29 16:29:04 +05:00
Corfirean d44e00f9ad Merge pull request #177 from Corfirean/feat/settings-update-history
Reorganize settings, stabilize window sizing and group update actions
2026-10-29 16:15:14 +05:00
Дмитрий dad10d8a5d Integrate settings and release history for Manager 0.9.4 2026-10-29 16:10:43 +05:00
Corfirean b33821e7eb Record reviewed Manager 0.9.3 release notes 2026-10-29 10:33:27 +05:00
Corfirean 1288a84da2 Merge pull request #184 from Corfirean/fix/world-startup-deadline
Release Manager 0.9.3 with slow world startup recovery
2026-10-29 10:15:48 +05:00
Дмитрий e7b76137d1 Prepare Manager 0.9.3 and verify platform-specific realm restriction 2026-10-29 10:07:33 +05:00
Дмитрий 7bb0ea9472 Wait for slow CoA worlds before update rollback 2026-10-29 08:33:11 +05:00
Дмитрий 1dab6154c7 Record reviewed 0.9.2 notes and experimental notice 2026-10-28 23:22:07 +05:00
github-actions[bot] 06a6302732 Update published Manager changelog 2026-10-28 18:20:57 +00:00
Corfirean 65631450ff Merge pull request #181 from Corfirean/fix/manager-092-issues
Manager 0.9.2: database startup, recovery and CoA settings
2026-10-28 23:20:11 +05:00
Дмитрий 2d9c6a65bb Recover safely when rollback restores a legacy world launcher 2026-10-28 22:57:00 +05:00
Дмитрий ce83f04d9d Prepare Manager 0.9.2 with database startup and configuration fixes 2026-10-28 22:17:26 +05:00
Corfirean 81f031b30f Keep experimental notice in Manager 0.9.1 hotfix notes 2026-10-28 18:21:36 +05:00
github-actions[bot] ee3ca2c517 Update published Manager changelog 2026-10-28 13:20:54 +00:00
Corfirean 50e858dcd5 Merge pull request #179 from Corfirean/fix/update-preexisting-character-starts
Manager 0.9.1 hotfix: preserve existing character gaps during server updates
2026-10-28 18:19:47 +05:00
Дмитрий 8bbf16ed4f Prepare Manager 0.9.1 hotfix without settings redesign 2026-10-28 17:46:38 +05:00
Дмитрий 324e9810cc Compare character start gaps against a saved pre-update baseline 2026-10-28 17:40:42 +05:00
Дмитрий a8ab201d7d Document required changelog translation preparation 2026-10-28 16:39:16 +05:00
Дмитрий 733d73ef76 Keep window density stable and group update and launch actions 2026-10-28 15:42:47 +05:00
Дмитрий 5525325160 Group Manager settings and add translated release history 2026-10-28 15:26:01 +05:00
Дмитрий 1aade1dcf9 Keep experimental portable character notice in Manager 0.9.0 notes 2026-10-28 12:38:12 +05:00
Corfirean 787549237f Merge pull request #173 from Corfirean/prepare/manager-20261028
Prepare Manager 0.9.0 with integrated realm, race and scaling controls
2026-10-28 12:37:13 +05:00
github-actions[bot] 088cd05e4f Update published Manager changelog 2026-10-28 07:36:47 +00:00
Дмитрий dc97095bd6 Prepare Manager 0.9.0 candidate and translate integrated realm controls 2026-10-28 08:25:41 +05:00
Дмитрий c6d8e5554d Integrate Manager features and preserve portable controls in the realm dialog 2026-10-28 08:23:35 +05:00
Дмитрий 0900a4a143 Merge remote-tracking branch 'origin/feat/publish-realms-dialog' into prepare/manager-20261028 2026-10-28 08:22:09 +05:00
Дмитрий eeb102e260 Merge remote-tracking branch 'origin/feat/realms-start-together' into prepare/manager-20261028 2026-10-28 08:22:09 +05:00
Дмитрий ea376a66d3 Merge remote-tracking branch 'origin/feat/progression-modes-setting' into prepare/manager-20261028 2026-10-28 08:22:09 +05:00
Дмитрий 88747c8da1 feat: portable play settings, improved offline messaging, and system tray support 2026-10-28 08:14:36 +05:00
ДмитрийandClaude Sonnet 5.5 8e1eb825df fix: clearer listing states, joining options chosen before publishing
Portable characters are on by default in a new listing; account creation and
portable characters are shown in the publish form (and in publish all) and
saved right after the realm is published.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 18:22:51 +05:00
ДмитрийandClaude Sonnet 5.5 4fcf0dde3f fix: changelog fragment without a byte order mark
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 18:02:54 +05:00
ДмитрийandClaude Sonnet 5.5 e4791fc45c feat: public listing as a realm list with a window, a publish-all button and a chip on each realm card
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 18:02:35 +05:00
Дмитрий f55a9fb42b docs: record new-race availability maintenance requirements 2026-10-27 17:35:14 +05:00
Дмитрий 8ad06fd78a feat(manager): configure per-race character creation 2026-10-27 17:24:50 +05:00
ДмитрийandClaude Sonnet 5.5 af82963f35 feat: open firewall ports for every running world and list every realm publicly
- Starting a server that is open to friends adds the firewall rules for the
  world ports of all realms that start together (only missing ones; a refused
  Windows prompt does not undo the start).
- Settings shows one public-listing block per realm that starts together. The
  main realm keeps its plain local id, so an existing listing is untouched.
- A realm that runs as an extra world is reached through that world's own
  console port, so its listing reports its own state and capabilities.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 15:29:09 +05:00
ДмитрийandClaude Sonnet 5.5 321ac597ce feat: start Wildcard and Warcraft Reborn together with Conquest of Azeroth
Settings gets two options, one per extra realm; turning on both runs all
three realms. Each extra world keeps its own folder, configs, logs and
ports (multiworld now handles a set of worlds instead of one second world),
and Warcraft Reborn gets its own status card, realm list entry and firewall
rule.

Starting a server also sets CoA.ClassModel of the realm chosen on Overview
to exactly that realm's model, so the shipped "coa wcr" default no longer
shows two class models on a Conquest of Azeroth realm.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 13:09:14 +05:00
Corfirean 925a81f4f2 Merge pull request #164 from Corfirean/feat/custom-races-report-target
Add Custom Races and Content Scaling report destinations
2026-10-27 11:02:46 +05:00
Corfirean df1901ea90 Merge pull request #163 from Corfirean/fix/issue-153-skill-controls
Add profession and defense skill gain controls
2026-10-27 10:28:06 +05:00
Corfirean 569d5fffc4 Merge pull request #162 from Corfirean/fix/issue-158-persistent-lan
Restore LAN realm addresses in Internet sharing mode
2026-10-27 10:28:02 +05:00
Дмитрий 7888dbc763 feat(reports): add separate Content Scaling destination 2026-10-27 10:25:10 +05:00
Дмитрий f0e8a8c12f feat(reports): add Custom Races upstream destination 2026-10-27 09:13:34 +05:00
Дмитрий af5a9717d4 feat(config): expose profession and defense skill gains (#153) 2026-10-27 08:38:08 +05:00
Дмитрий bf2fffcffa fix(friends): restore LAN realm address after restart (#158) 2026-10-27 08:34:02 +05:00
Дмитрий 4a99dd3a6a docs: review Manager 0.8.2 release history 2026-10-27 08:01:37 +05:00
github-actions[bot] 306003b698 Update published Manager changelog 2026-10-27 02:58:39 +00:00
Corfirean d9be2b9d82 Merge pull request #161 from Corfirean/prepare/races-192-20261026
Prepare CoA Custom 1.9.2 clients and preserve server migration order
2026-10-27 07:58:04 +05:00
Дмитрий 81b040ef02 Preserve database migration introduction order across merge commits 2026-10-27 00:30:08 +05:00
Дмитрий 5fdee1d658 Prepare matching CoA Custom 1.9.2 client installation 2026-10-26 23:14:39 +05:00
Дмитрий 4e1f548012 Retain the experimental portable-character notice in Manager 0.8.1 2026-10-25 18:04:13 +05:00
github-actions[bot] b3ee94071d Update published Manager changelog 2026-10-25 13:02:58 +00:00
Corfirean 76dc7452de Merge pull request #157 from Corfirean/prepare/races-191-20261025
Prepare CoA Custom 1.9.1 client installation for the new server
2026-10-25 18:02:16 +05:00
Дмитрий 02e3a9e4e6 Validate nested client assets and retain previous split-release hashes 2026-10-25 11:55:24 +05:00
Дмитрий 8addc97bc5 Prepare compatible CoA Custom 1.9.1 client installation 2026-10-25 11:41:15 +05:00
github-actions[bot] 57807b9769 Update published Manager changelog 2026-10-24 14:50:03 +00:00
Corfirean 7e29a9f2ec Keep the experimental portable-character notice in Manager 0.8.0 notes 2026-10-24 19:49:46 +05:00
github-actions[bot] af9f148889 Update published Manager changelog 2026-10-24 14:27:27 +00:00
Corfirean 92385cf569 Merge pull request #152 from Corfirean/fix/portable-host-activation-20261024
Prepare core portable sessions when the owner enables access
2026-10-24 16:46:12 +05:00
Дмитрий b00e732c7f fix(portable): reject occupied world ports across platforms 2026-10-24 16:37:52 +05:00
Дмитрий 594bdee594 fix(portable): prepare effective core configuration on owner opt-in 2026-10-24 16:32:55 +05:00
Corfirean d4408a0e92 Merge pull request #151 from Corfirean/integrate/complete-release-20261024
Prepare Manager 0.8.0 with rulesets, portable access and relay fixes
2026-10-24 11:19:40 +05:00
Дмитрий b61a186470 Restore remote portable progress and resilient relay connections 2026-10-24 11:12:01 +05:00
Дмитрий 9e9778af74 Keep external network gates reproducible and check all registry rulesets 2026-10-24 06:33:00 +05:00
Дмитрий d5f1e9cc83 Integrate isolated rulesets, portable admission, and compatible relay authentication 2026-10-24 06:04:26 +05:00
github-actions[bot] aa25e9c721 Update published Manager changelog 2026-10-23 20:19:26 +00:00
Corfirean 1fd3a5482e Merge pull request #150 from Corfirean/fix/portable-schema9-hotfix
Fix schema 9 portable stores in Manager 0.7.3
2026-10-24 01:09:25 +05:00
Дмитрий 2715170622 Fix portable schema 9 compatibility and prepare Manager 0.7.3 2026-10-24 01:00:27 +05:00
github-actions[bot] 8801c6f308 Update published Manager changelog 2026-10-23 19:20:08 +00:00
github-actions[bot] 341f2f0230 Update published Manager changelog 2026-10-23 14:18:59 +00:00
Дмитрий a48717340b chore(reborn): MR3.1 semantic audit, i18n localization, and fail-closed cleanup 2026-10-22 22:18:28 +05:00
Дмитрий 351ace1c56 feat(reborn): MR3 Warcraft Reborn portable character vertical slice and ruleset UI 2026-10-22 21:26:39 +05:00
Дмитрий ba143e1ccd fix(control): MR2.1 fail-closed world-port resolution and ruleset invariant verification
- Make world_port resolution fallible (Result<u16>) across LocalBackend, HostService, DirectRouteManager, and RelayLink without default fallbacks to 8085.
- Enforce strict 4-way invariant: local_id ruleset == RealmAccess.mode == Db.realm() == RealmInfo.ruleset. Malformed or unknown suffixes fail closed.
- If Wildcard is selected and world-port resolution fails (or simultaneous mode is disabled), Direct and Relay fail closed with actionable error and zero fallback to CoA.
- Fix documentation drift in docs/WILDCARD.md and docs/MULTIRULESET_PORTABLE_AUDIT.md regarding simultaneous execution, distinct ports, and current vs historical baseline.
2026-10-22 18:10:49 +05:00
Дмитрий 5343020bed feat(portable): MR2 Wildcard portable character vertical slice
- Enforce fail-closed backend resolution in LocalBackend::info (unknown ruleset = error).
- Implement strict three-space isolation (Wildcard != CoA != Reborn) across canonical store, host mappings, and collections.
- Isolate collection namespaces (wildcard:appearance, wildcard:vanity) and reject cross-ruleset collections in claim and import.
- Enforce Control Protocol v2 ruleset verification on TransferOffer, TransferCommit, and Claimed response.
- Route Direct Ingress and Relay Link dynamically according to realm world port (8085 for CoA, 8086 for Wildcard).
- Add runtime session attack rejection test suite (cross-ruleset session offers, checkpoints, owner acks, server IDs).
- Verify end-to-end Wildcard session lifecycle and documentation updates.
2026-10-22 17:24:15 +05:00
ДмитрийandClaude Sonnet 5.5 55b0087455 feat(modules): choose Parallel or Global scaling progression in module settings
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 15:59:29 +05:00
Дмитрий 9d135765cd feat(multiruleset): complete MR1.1 foundation correctness gate 2026-10-22 15:34:37 +05:00
Дмитрий 58a99f0a6d feat: multi-ruleset realms and strictly isolated portable characters 2026-10-22 13:04:57 +05:00
Дмитрий d9c10c4564 Merge released v0.7.1 into feat/multiruleset-realms-portable 2026-10-22 12:00:03 +05:00
280 changed files with 31067 additions and 2157 deletions

No files matched your search

+2
View File
@@ -25,4 +25,6 @@ jobs:
- run: npm ci - run: npm ci
- run: node tools/check-i18n.mjs - run: node tools/check-i18n.mjs
- run: npm run build - run: npm run build
- run: node --experimental-strip-types --test tools/*.test.mjs
- run: python -B -m unittest discover -s tools -p test_launcher_bridge.py
- run: cargo test --workspace --locked - run: cargo test --workspace --locked
+5 -1
View File
@@ -69,8 +69,12 @@ jobs:
with: with:
node-version: 22 node-version: 22
- run: npm ci - run: npm ci
# tauri::generate_context! needs ../dist; without a warm target cache the tests do not compile without it.
- run: npm run build
- name: Tests - name: Tests
run: cargo test --workspace -- --test-threads=1 run: cargo test --workspace --locked -- --test-threads=1
- run: node --experimental-strip-types --test tools/*.test.mjs
- run: python -B -m unittest discover -s tools -p test_launcher_bridge.py
- name: Build and sign (publish only when requested) - name: Build and sign (publish only when requested)
id: tauri id: tauri
uses: tauri-apps/tauri-action@v0 uses: tauri-apps/tauri-action@v0
@@ -0,0 +1,72 @@
name: sign-local-installer
on:
push:
branches: [release/20261108-manager]
workflow_dispatch:
inputs:
build_run_id:
description: Successful manager-local run in coa-server-build
required: true
permissions:
contents: read
actions: read
jobs:
sign:
if: github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v4
with:
node-version: 22
- name: Verify local build provenance
env:
GH_TOKEN: ${{ github.token }}
BUILD_RUN: ${{ inputs.build_run_id }}
run: |
python3 - <<'PY'
import json, os, subprocess
run = os.environ['BUILD_RUN']
if not run.isdigit():
raise RuntimeError('Invalid build run')
data = json.loads(subprocess.check_output(['gh', 'api', f'repos/Corfirean/coa-server-build/actions/runs/{run}']))
if data['conclusion'] != 'success' or data['path'] != '.github/workflows/manager-local.yml':
raise RuntimeError('Not a successful local Manager build')
subprocess.run(['gh', 'run', 'download', run, '-R', 'Corfirean/coa-server-build', '-n', 'unsigned-manager-windows', '-D', '_prepared-manager'], check=True)
from pathlib import Path
import hashlib
root = Path('_prepared-manager')
meta = json.loads((root / 'prepared-source.json').read_text())
version = json.loads(Path('package.json').read_text())['version']
name = meta['installer']
if Path(name).name != name or meta['source'] != os.environ['GITHUB_SHA'] or meta['version'] != version or str(meta['run']) != run:
raise RuntimeError('Installer identity differs')
if hashlib.sha256((root / name).read_bytes()).hexdigest() != meta['sha256']:
raise RuntimeError('Installer hash differs')
PY
- run: npm ci
- name: Sign exact locally compiled bytes
env:
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
run: |
node --input-type=module <<'JS'
import { readFileSync, writeFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
const root = '_prepared-manager/';
const meta = JSON.parse(readFileSync(root + 'prepared-source.json'));
execFileSync('node_modules/.bin/tauri', ['signer', 'sign', '--app-version', meta.version, root + meta.installer], {stdio: 'inherit'});
if (createHash('sha256').update(readFileSync(root + meta.installer)).digest('hex') !== meta.sha256) throw new Error('Signed bytes changed');
const signature = readFileSync(root + meta.installer + '.sig', 'utf8').trim();
const url = `https://github.com/Corfirean/coa-server-manager/releases/download/v${meta.version}/${encodeURIComponent(meta.installer)}`;
writeFileSync(root + 'latest.json', JSON.stringify({version: meta.version, notes: 'See the release notes.', pub_date: new Date().toISOString(), platforms: {'windows-x86_64': {signature, url}}}, null, 2) + '\n');
meta.signingRun = process.env.GITHUB_RUN_ID;
writeFileSync(root + 'prepared-source.json', JSON.stringify(meta, null, 2) + '\n');
JS
- uses: actions/upload-artifact@v4
with:
name: prepared-manager-windows
path: _prepared-manager/*
retention-days: 14
if-no-files-found: error
+10
View File
@@ -35,6 +35,16 @@ Every published Manager version, including a clearly marked Pre-release, belongs
CHANGELOG.md and changelog/history.json. Its GitHub release notes use the same reviewed record. CHANGELOG.md and changelog/history.json. Its GitHub release notes use the same reviewed record.
Promotion updates that entry without duplicating it; Manager and server histories remain separate. Promotion updates that entry without duplicating it; Manager and server histories remain separate.
Translated release notes are a required preparation step before freezing a new Manager source. Follow the
runbook's "Mandatory translated release notes during preparation" checklist: translate every new reviewed
Manager/server note into Russian, German, French, Spanish and Simplified Chinese in
`src/data/latest-note-translations.json`, keyed by exact canonical English text. Preserve existing translations
and released fragments. Refresh the bundled server-history snapshot from a pinned canonical commit and record
its provenance. Run `node --test tools/release-history.test.mjs`, `node tools/check-i18n.mjs` and `npm run build`;
verify each new record, all six viewer languages, English fallback and offline use. Save source/version and checks
in the handoff. Translations ship with Manager: a server-only release must record the carrying Manager version or
pending translation delivery, without forcing another Manager release or changing already signed installers.
Before preparing or publishing a Manager/server release, read the maintained Before preparing or publishing a Manager/server release, read the maintained
[release runbook](https://github.com/Corfirean/coa-server-build/blob/main/docs/server-release.md) [release runbook](https://github.com/Corfirean/coa-server-build/blob/main/docs/server-release.md)
and [build agent instructions](https://github.com/Corfirean/coa-server-build/blob/main/AGENTS.md). and [build agent instructions](https://github.com/Corfirean/coa-server-build/blob/main/AGENTS.md).
+161
View File
@@ -8,6 +8,167 @@ Published releases and previews. Pre-release entries do not change the stable up
Dates follow GitHub publication (UTC); legacy records retain their archived dates. Newest releases first. Dates follow GitHub publication (UTC); legacy records retain their archived dates. Newest releases first.
## 0.9.13 — 2026-11-15
- The custom races client is updated to Custom Races V2.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.13) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.12...v0.9.13)
## 0.9.12 — 2026-11-14
- Settings for how much help bots get in dungeons and raids.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.12) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.10...v0.9.12)
## 0.9.10 — 2026-11-08
- Custom Races patch installation recovers from interrupted downloads.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.10) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.9...v0.9.10)
## 0.9.9 — 2026-11-04
- Update and recovery checks use the temporary login port even with a Windows override.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.9) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.8...v0.9.9)
## 0.9.8 — 2026-11-01
- Dungeon Clear can be enabled when SQUID bots are active.
- Diagnostic exports include launcher stages and lock owner records.
- Choose normal logs, errors only or no server logs in maintenance settings.
- Update checks temporarily suspend bot population and restore your configuration.
- Update validation keeps MySQL running between compatible checks.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.8) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.7...v0.9.8)
## 0.9.7 — 2026-10-30
- Show available update notes even when release history is cached.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.7) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.5...v0.9.7)
## 0.9.5 — 2026-10-30
- Account creation verifies a lost console reply against the requested login.
- Abandoned game relay tunnels close their local connection immediately.
- Keep disabled graphics components disabled during client updates.
- Force-stop an unresponsive world after a failed normal shutdown.
- Crash history includes reports from every world and Windows text files.
- Show the online bot count for Playerbots on the overview.
- Disable public server browsing in Settings.
- Keep deliberate stops and update shutdowns from triggering crash restart.
- Server startup waits for a responsive console before reporting success.
- Restore the existing Manager window when launching it again.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.5) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.4...v0.9.5)
## 0.9.4 — 2026-10-29
**Portable Characters are experimental and may contain bugs.**
- Settings group updates, startup and maintenance with translated release history.
- Update and launch without updating share a divided button.
- Maximizing the window keeps text and controls at a comfortable size.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.4) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.3...v0.9.4)
## 0.9.3 — 2026-10-29
**Portable Characters are experimental and may contain bugs.**
- Slow server startup no longer triggers an early update rollback.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.3) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.2...v0.9.3)
## 0.9.2 — 2026-10-28
**Portable Characters are experimental and may contain bugs.**
- New server installation waits for slower database startup.
- Find and edit CoA options in the existing server settings.
- Simultaneous update checks share results or wait their turn.
- Recovery can stop an unfinished world startup after restoring an older launcher.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.2) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.1...v0.9.2)
## 0.9.1 — 2026-10-28
**Portable Characters are experimental and may contain bugs.**
- Existing unsupported character records no longer block unrelated server updates.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.1) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.0...v0.9.1)
## 0.9.0 — 2026-10-28
**Portable Characters are experimental and may contain bugs.**
- Choose Parallel or Global level scaling in module settings.
- Report Content Scaling problems directly to its repository.
- Send custom race problem reports directly to their maintainer.
- Internet sharing restores the LAN address after server restarts.
- Configure custom race availability for new characters.
- Public listing offers every realm that starts together, not just the main one.
- Public listing is a short list of realms with a window for the details.
- Configure profession and defense skill gains in server settings.
- Starting a server sets the character classes of the realm chosen on Overview.
- Start Wildcard and Warcraft Reborn together with Conquest of Azeroth.
- Control portable characters and keep Manager running in the system tray.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.0) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.8.2...v0.9.0)
## 0.8.2 — 2026-10-27
**Portable Characters are experimental and may contain bugs.**
- Installs the verified CoA Custom 1.9.2 client patches and quest safety addon, while recognizing existing 1.9.1 installations.
- Server updates preserve the order of database migrations introduced during merges, preventing older snapshots from overwriting newer progression.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.8.2) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.8.1...v0.8.2)
## 0.8.1 — 2026-10-25
**Portable Characters are experimental and may contain bugs.**
- Install the matching CoA Custom 1.9.1 client files.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.8.1) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.8.0...v0.8.1)
## 0.8.0 — 2026-10-24
**Portable Characters are experimental and may contain bugs.**
- Server owners can allow portable characters per realm.
- Allowing portable characters also prepares the server for portable sessions.
- Managers stay compatible with the public connection service.
- Relay connections recover and use the ports of the installed server.
- Portable progress resumes after reconnecting or restarting the Manager.
- Older copies on another host may require maintenance before returning.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.8.0) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.7.3...v0.8.0)
## 0.7.3 — 2026-10-23
**Portable Characters are experimental and may contain bugs.**
- Portable characters open again after using an experimental Manager.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.7.3) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.7.2...v0.7.3)
## 0.7.2 — 2026-10-23
- Advanced settings cover creature melee damage, spell damage and health by rank.
- Internet sharing accepts existing port forwards to the same server.
- The Auction House Bot card has a single switch.
- More character and server browser controls now use your selected language.
- Online player counts correctly separate random bots from players.
- Custom races work with shared addon folders on another drive.
- Configure the day and night cycle from the module settings.
- A stalled database inspection no longer blocks server maintenance indefinitely.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.7.2) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.7.1...v0.7.2)
## 0.7.1 — 2026-10-22 ## 0.7.1 — 2026-10-22
Close the game, then open Modules → Custom Races → Repair Client Patch to update existing patches, or Install Client Patch for a new installation. Updating the Manager does not automatically replace game files or update your server. Close the game, then open Modules → Custom Races → Repair Client Patch to update existing patches, or Install Client Patch for a new installation. Updating the Manager does not automatically replace game files or update your server.
Generated
+20 -3
View File
@@ -586,7 +586,7 @@ dependencies = [
[[package]] [[package]]
name = "coa-core" name = "coa-core"
version = "0.7.2" version = "0.9.13"
dependencies = [ dependencies = [
"base64 0.22.1", "base64 0.22.1",
"chrono", "chrono",
@@ -634,7 +634,7 @@ dependencies = [
[[package]] [[package]]
name = "coa-release" name = "coa-release"
version = "0.7.2" version = "0.9.13"
dependencies = [ dependencies = [
"chrono", "chrono",
"coa-core", "coa-core",
@@ -643,7 +643,7 @@ dependencies = [
[[package]] [[package]]
name = "coa-server-manager" name = "coa-server-manager"
version = "0.7.2" version = "0.9.13"
dependencies = [ dependencies = [
"coa-control-proto", "coa-control-proto",
"coa-core", "coa-core",
@@ -655,6 +655,7 @@ dependencies = [
"tauri-plugin-dialog", "tauri-plugin-dialog",
"tauri-plugin-opener", "tauri-plugin-opener",
"tauri-plugin-process", "tauri-plugin-process",
"tauri-plugin-single-instance",
"tauri-plugin-updater", "tauri-plugin-updater",
"tracing", "tracing",
] ]
@@ -4606,6 +4607,22 @@ dependencies = [
"tauri-plugin", "tauri-plugin",
] ]
[[package]]
name = "tauri-plugin-single-instance"
version = "2.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "726b6da0dd5bd1344f84f4108a622c07d01923baacb5c803a605189672c5352f"
dependencies = [
"serde",
"serde_json",
"tauri",
"thiserror 2.0.21",
"tokio",
"tracing",
"windows-sys 0.61.2",
"zbus",
]
[[package]] [[package]]
name = "tauri-plugin-updater" name = "tauri-plugin-updater"
version = "2.13.1" version = "2.13.1"
+1 -1
View File
@@ -4,7 +4,7 @@ members = ["crates/coa-core", "crates/coa-release", "crates/coa-registry-proto",
exclude = ["services/coa-registry", "services/coa-registry-e2e", "services/coa-coordinator", "services/coa-relay"] exclude = ["services/coa-registry", "services/coa-registry-e2e", "services/coa-coordinator", "services/coa-relay"]
[workspace.package] [workspace.package]
version = "0.7.2" version = "0.9.13"
edition = "2021" edition = "2021"
license = "AGPL-3.0-only" license = "AGPL-3.0-only"
+228
View File
@@ -0,0 +1,228 @@
# Per-race availability audit
Date: 2026-10-27. This is an internal implementation audit, not a supported-feature guide.
## Frozen sources
Separate `feat/per-race-toggles` branches and checkouts:
| Component | Checkout | Fetched base |
| --- | --- | --- |
| Manager | `C:/games/source/per-race-manager` | `origin/master`, `925a81f` |
| Core | `C:/games/source/per-race-core` | `origin/coa-bots`, `1c658cab46d5057a8972cebd84c840aa6fbc4a91` |
| CoA Companions | `C:/games/source/per-race-companions` | `origin/master`, `6a289fc2230ce9425924ca86dee02d0bb8d3d344` |
| Build | `C:/games/source/per-race-build` | `origin/main`, `89795b6` |
The build runbook explicitly selects `Corfirean/azerothcore-wotlk-coa:coa-bots`, not its `main`.
The old `C:/games/source/server/azerothcore-wotlk-coa` checkout instead tracks jealous-sound upstream
and has local modifications. It must not be used as the feature's release base.
The primary Manager and Companions checkouts also contain unrelated work and remain untouched.
SQUID is a separate repository, `Zyth45/mod-playerbots`, not `Corfirean/mod-coa-playerbots`.
Existing research checkout: `C:/games/source/squid-playerbots`. Its current local branch is
`fix/custom-races-existing-bots`, one commit ahead of `origin/coa`. Build policy selects the highest
stable numeric tag, so that local branch must not silently become the shipped dependency.
## Manager integration points
- `crates/coa-core/src/custom_races.rs`: package version `1.9.2`, release URLs, MPQ/root/addon lists,
hash manifests, client status, install, enable/disable and uninstall.
- `PatchTransaction`, `SavedFile`, `recover_patch_transaction`: shared client-relative journal in
`.coa-races-transaction/journal.json`, saved files and `committed` marker. Uncommitted changes roll back.
Paths use `fsx::safe_join`; file moves handle cross-volume addon locations.
- `patch_lock`: exclusive OS file lock on `.coa-races.lock`. The empty file's existence is normal and
does not prove another operation is active. Do not delete it as a stale-lock workaround.
- Client mutations reject `client::is_running`; reuse this gate and lock for availability changes.
- `patch_files`, `matches_patch`, `preserve_original`: ownership and preservation depend on manifests
and hashes, not just a filename. Availability overlay ownership needs its own verified record.
- `modules/catalog.json`: `custom-races` uses `coa_custom_races.conf` and `CoACustomRaces.Enable`.
Companions use `mod_coa_playerbots.conf` / `CoaBots.Enable`; SQUID uses
`playerbots.conf` / `AiPlayerbot.Enabled`.
- `crates/coa-core/src/modules.rs`: `toggle`, `settings_in`, `save_settings_in` write current module
configuration. Bot switches enforce stopped servers and the existing control lock.
- `src/screens/ModulesPage.tsx`: Custom Races card, master toggle, install/progress/status UI.
- `src/lib/api.ts` and `src-tauri/src/lib.rs`: existing `custom_races_status`,
`custom_races_install`, `custom_races_uninstall`, `custom_races_toggle_client` commands.
There is no per-race command or verified availability status yet.
- `src-tauri/src/lib.rs::play`: local launch reads `realms::state`, calls `client::sync_realm`, then
launches. Remote launch has a separate realmlist override path; it cannot infer a remote race policy.
- `crates/coa-core/src/realms.rs`: modes CoA, Wildcard and Warcraft Reborn; current configs are captured
under `Settings/realm-profiles/<mode>.json`. Use this mechanism rather than a parallel realm store.
Existing bot restrictions for non-CoA modes must remain effective.
- `crates/coa-core/src/clientdl.rs::apply`: manifest-based client updates, `keep_modified`, staging,
preservation of replaced files. No availability-overlay invalidation or rebuild exists today.
### Confirmed reconciliation risk
`custom_races.rs::sync_bot_races_config` writes a replacement `AiPlayerbot.ExcludedBotRaces` value:
recommended full exclusions or experimental `65,72,77,80,81`. It does not preserve arbitrary user
exclusions. `modules.rs` calls it from the master switch and BotsEnable saving; some callers discard
errors. Per-race integration cannot rely on this overwrite behavior.
`playerbots_conf_paths` can also copy a `.dist` file when no active config exists; it is not a purely
read-only discovery API. Status inspection should avoid adding more implicit writes.
## Core gates and bypasses
- `modules/mod-coa-custom-races/src/mod_coa_custom_races.cpp`: `WorldScript` loads the master switch;
`AccountScript::CanAccountCreateCharacter` accepts stock IDs 1–8, 10, 11 or an enabled master switch.
No disabled-ID list is implemented. Stock ID 9 is deliberately not included.
- `modules/mod-coa-custom-races/conf/coa_custom_races.conf.dist`: Enable and BotsEnable exist;
DisabledRaceIds does not.
- `src/server/game/Handlers/CharacterHandler.cpp`: normal character creation invokes
`sScriptMgr->CanAccountCreateCharacter` inside its finalization callback and rejects with
`CHAR_CREATE_DISABLED`. A packet from an unpatched client reaches that gate too.
- `src/server/game/Scripting/ScriptDefines/AccountScript.cpp`: hook aggregation must be preserved.
- `src/server/game/DataStores/DBCStores.cpp::LoadDBCStores`: chooses `DataDir/dbc_races/<file>` if
the master switch is enabled and that file exists, otherwise `DataDir/dbc/<file>`.
Per-race creation policy must not remove DBC rows or change login data.
- `.agents/docs/systems/ascension-character-creation.md`: native client compatibility depends on
`CharBaseInfo.dbc`; race button indices are not RaceIDs. Existing race/class checks must stay intact.
## Both bot systems
### CoA Companions
`module/src/BotSpawnRandom.cpp::GetValidBotRaces` reads the global and bot custom-race switches,
`CoaBots.CustomRaces.Enable`, and both AiPlayerbot/CoaBots exclusion lists. It checks DBC presence.
Its experimental defaults apply only when the combined exclusion set is empty: adding an owner list
to that set would silently remove those defaults. Keep those policies independent.
`CreateBotClone`, `CreateOneRandomBot`, and leveled spawning clone SQL character data directly;
they bypass the account creation hook. Enforce new-character policy at the common clone creation
entry as well as random selection. Preserve existing bots and faction selection via
`Player::TeamIdForRace`.
Additional confirmed callers: `module/src/BotBattlegroundFill.cpp::QueueBotForSide` and
`module/src/BotLfgFill.cpp` call `CreateOneRandomBot` after trying to reuse an existing bot.
The existing-bot reuse path must remain separate from creation restrictions.
`tools/offline_bot_factory.py` is another direct-SQL creation path. Its main loop chooses a
template by class and faction, then copies `template.race` into the new character overrides.
It currently does not read the custom-race creation policy. Reject or filter prohibited
templates before generating new accounts, GUIDs or SQL; do not rewrite their races.
### SQUID Playerbots
`src/PlayerbotAIConfig.cpp` loads `AiPlayerbot.ExcludedBotRaces` and adds
`AiPlayerbot.CrashingBotRaces`; it reads BotsEnable. `src/CoaBotRacePolicy.h` implements
`IsCoaBotRaceAllowed`. `src/Bot/Factory/RandomPlayerbotFactory.cpp::CreateRandomBot` applies
that policy before faction and race/class selection.
The same predicate also appears in `src/Bot/RandomPlayerbotMgr.cpp` and
`src/Bot/PlayerbotMgr.cpp`, including existing-character admission. Do not append owner creation
restrictions globally to this shared exclusion vector: that would also affect existing bots.
The predicate currently does not itself require `CoACustomRaces.Enable`.
`RandomPlayerbotFactory.cpp` calls `Player::Create` directly without the account hook.
Use a creation-only check in this factory, leaving existing-character admission unchanged.
## Portable Characters
Manager import code is under `crates/coa-core/src/portable/realm/`.
`import.rs` validates identity namespaces and race/class start data (`UnknownRaceClass`).
Availability policy must not become an import rejection or an identity rewrite. The inspected
creation hook is in the normal packet handler, not this importer. In the core,
`src/server/coa/CoAPortableImport.cpp` checks `GetPlayerInfo(model.Race, model.Class)` and writes
`model.Race` to the imported character and character cache. It does not invoke the account
creation hook. Preserve this separation. Live compatibility is still untested.
## Client experiment, actual observations
The owner updated `C:/games/Ascension` from 1.9.1 to 1.9.2 during this audit; its manifest now says
`# CoA Custom 1.9.2`. A separate physical client copy is being prepared under
`C:/games/source/per-race-evidence/client`; game assets are outside Git. The copy completed:
25646 files copied, zero failures. The separate server file copy also completed, but has not
been configured or started. No database service has been started for this task.
Read-only MPQ membership probing found ChrRaces in patch-ZZZF, ZZZE, ZZZC, ZZZ, ZZW, ZZV, ZZU,
ZZS, T, M and several locale archives. CharacterCreate.lua has multiple owners too.
The old `mpqprobe.py` precedence model explicitly admits an inference for Ascension multi-letter
archives. Therefore `patch-ZZZF.MPQ` is a candidate source, not runtime-confirmed effective data.
`patch-ZZZZ.MPQ` exists already; no overlay filename has been qualified.
Extracted from `patch-ZZZF.MPQ`:
- WDBC, 95 records, 69 fields, record size 276, string block 2428, total bytes 28668.
- SHA-256 `b78635b08bf0bd63d2898fce97c1fb162c8a9c41632703172eefa88bae79061f`.
- Actual rows: Sethrak 82, Gnoll 83, Saberon 97. Their Flags are 12.
- String block starts with `Hu`, not NUL; imposing an initial empty-string invariant incorrectly
rejects this real table. String boundaries and referenced offsets still need validation.
- Sethrak experiment changes only Flags 12 → 13. All other bytes compare equal.
- One generated MPQ was read back through StormLib; its DBC equals the expected patched bytes.
- The installed `pympq` Python extension crashed during interpreter finalization. The experimental
tool instead uses the installed Unicode StormLib DLL directly. It is not a runtime dependency
proposal for Manager or its users.
`tools/race_availability_poc.py` requires an explicit source archive and creates output only in a new
directory. It does not select an archive order, install an overlay or assert in-game success.
`tools/test_race_availability_poc.py` uses synthetic bytes only.
### Background verification after interactive testing was deferred
The owner requested no screen capture/input and no client/server/MySQL launches while other bot
tests run. These restrictions remain active. The owner reported that the copied client launches;
this does not confirm creation behavior or effective DBC loading.
- 17 DBC/fingerprint tests and 8 synthetic MPQ integration tests pass (25 total, none skipped).
- Native tests use the explicitly selected existing Unicode StormLib DLL, with no new install.
- Output is built and verified in a temporary directory before publishing the offline result folder.
Failures leave no published result; this is not the future client transaction implementation.
- One and fifty disabled races both produce one MPQ. StormLib adds an internal `(listfile)`;
the sole game payload is `DBFilesClient/ChrRaces.dbc`.
- Every referenced localized race-name offset is bounds-checked; invalid UTF-8 is rejected.
- The experimental fingerprint includes original DBC SHA-256, normalized IDs, algorithm version
and explicitly recorded profile. A profile label does not prove client compatibility.
- The real three-race offline experiment is in
`C:/games/source/per-race-evidence/multiple-races-offline/report.json`.
Source MPQ SHA-256: `40eac695cfcafb598b8376f3b9a61ecc037e4d445b87279cfe387a91edad32c3`.
Generated DBC SHA-256: `243fb36837b76ebd6943da574cc095be548b4530be7f06487debea6703db10d3`.
The first copy launch showed a missing-critical-files message and subsequently crashed on exit.
The crash report identifies `AMDXN32.DLL` in the AMD graphics driver at the fault address; this
does not establish the root cause. EXE, Extensions, dinput8, d3d9, dxgi, EsteriaAppearance and
patch-ZZZF hashes matched the primary client during comparison. The experimental overlay was
not installed. No graphics-driver or client-runtime changes were made to work around the crash.
## Reference implementations and update preservation
Inspected read-only reference clones:
- `aspollon/AFK-Realm` at `ea9c5bf691c98cace8cc03c06183c161022946de`.
- `aspollon/mod-custom-races` at `5a8f2ff8a0d494ffadf64e677a438aa7f5a6671b`.
`mod-custom-races/afk-realm.json` declares client patch generation and GlueXML Lua insertion.
`client/CustomRaces.lua` extends and lays out buttons, using race names/files and configured IDs.
This is a reference, not evidence of compatibility with the current CoA/Esteria UI or a reason
to replace CSM's prebuilt-server distribution.
`crates/coa-core/src/config/merge.rs` performs additive `.dist` merging: missing keys are added,
existing user values and unknown keys are retained. A new DisabledRaceIds key should use this
path. Existing realm snapshots already capture module `.conf` files. Neither mechanism currently
coordinates an availability overlay with client update/repair; that remains implementation work.
## Open gates
Update after the owner found the existing Hide Races panel: see
[existing-filter research](docs/PER_RACE_EXISTING_FILTER_RESEARCH.md). The inspected Lua already
supports personal name/index-based hiding, but it is not a realm-scoped RaceID policy. Nine
offline Lua 5.1 probes confirmed key behavior and limitations. Reusing its layout/UI is now a
candidate to investigate before choosing a production DBC implementation. This is not evidence
that the DBC approach failed, and it does not qualify client support.
The owner subsequently confirmed the GlueXML probe: restricted races disappeared from selection
and were grey, unchecked and disabled in Hide Races. The production client integration should
reuse this filter; changing DBC flags is no longer the selected implementation path.
Server controls, strict catalog-bound configuration, the core creation hook and both bot factory
guards are implemented and have passed offline checks and native builds. Existing-bot admission
and user/crashing exclusions remain separate from the new creation policy.
Remaining gates:
1. Integrate automatic client reconciliation, ownership and recovery with realm settings.
2. Qualify client update/repair and shared-client PLAY behavior.
3. Verify live creation rejection/re-enable, existing-character login, imports and both bot systems
when the owner's database test environment becomes available.
Status: **PARTIAL** — server implementation and builds pass; live server acceptance and production
client synchronization remain pending. See docs/PER_RACE_TOGGLES_TESTS.md for exact scope.
No existing character data, production service, release channel, or primary client archive was changed.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Choose Parallel or Global level scaling in module settings
---
Content Scaling progression can now be set to Parallel (Classic over 1 to the level cap, TBC and WotLK over 45 to the cap) or Global (all expansions over 1 to the cap) without editing the config file by hand.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Server owners can allow portable characters per realm
---
Portable admission is off until enabled by the realm owner. Export and import requests enforce the saved choice.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Allowing portable characters also prepares the server for portable sessions
---
Stop the server before enabling access for the first time. The Manager enables portable sessions in the effective module configuration and preserves the required database setting across restarts. Existing configuration is backed up.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: players
title: Portable characters open again after using an experimental Manager
---
Preserves saved characters and collections when opening a portable store upgraded by an experimental Manager.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Managers stay compatible with the public connection service
---
Coordinator authentication no longer changes when portable messages change. The publishing card shows game relay status separately.
+7
View File
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Relay connections recover and use the ports of the installed server
---
Dropped or unresponsive relay links reconnect automatically. Abandoned game connections close, and tunnels refresh when local ports become available or change. Custom authentication ports are respected.
+7
View File
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Portable progress resumes after reconnecting or restarting the Manager
---
The player Manager now saves remote baselines, checkpoints and logout progress durably. Repeated logins stay monitored, and transfer retries preserve the same character and session.
+7
View File
@@ -0,0 +1,7 @@
---
area: manager
type: known-issue
audience: admins
title: Older copies on another host may require maintenance before returning
---
Experimental portable play blocks an outdated existing copy on another host. Automatic refresh while that remote worldserver runs is not available. Your canonical character remains saved in your Manager.
+7
View File
@@ -0,0 +1,7 @@
---
area: client
type: changed
audience: players
title: Install the matching CoA Custom 1.9.1 client files
---
The races installer verifies and installs all five client archives, including the new races and appearance corrections.
+7
View File
@@ -0,0 +1,7 @@
---
area: manager
type: changed
audience: players
title: Install the CoA Custom 1.9.2 client patches
---
Installs the updated Hozen and Centaur assets and quest safety addon. Existing CoA Custom 1.9.1 installations remain recognized when updating or removing patches.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Report Content Scaling problems directly to its repository
---
The report form now includes a separate Content Scaling destination.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Send custom race problem reports directly to their maintainer
---
The report form now includes Custom Races as a separate destination.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Internet sharing restores the LAN address after server restarts
---
Friends on the local network receive the server's LAN address and network mask while internet players keep using its public address.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Server updates preserve the order of database migrations added during merges
---
Older database snapshots no longer run after newer updates when preparing server packages. This prevents outdated Manastorm reward ranges from overwriting newer progression data.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Configure custom race availability for new characters
---
Choose individual races in a compact table inside module settings using the installed server catalog. Saving requires a compatible server build and a stopped server. Client synchronization is not yet automatic.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Public listing offers every realm that starts together, not just the main one
---
With Wildcard or Warcraft Reborn started next to Conquest of Azeroth, Settings now has one listing block per realm, each with its own name, description and access options.
@@ -0,0 +1,7 @@
---
area: manager
type: changed
audience: admins
title: Public listing is a short list of realms with a window for the details
---
Settings shows one line per realm with its state, and publishing opens a window. Publish all realms at once. Account creation and portable characters are chosen before publishing; portable characters are on by default.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Configure profession and defense skill gains in server settings
---
Advanced rate settings now include prospecting and milling skill gains, plus the points gained from crafting, defense and gathering.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Starting a server sets the character classes of the realm chosen on Overview
---
A new Conquest of Azeroth server could show two class models, or none, on the character creation screen. The Manager now sets the model of the chosen realm before every start.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Start Wildcard and Warcraft Reborn together with Conquest of Azeroth
---
Settings now has two options, one for Wildcard and one for Warcraft Reborn. Turn on either one, or both to run all three realms at once, each with its own characters and port.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Find and edit CoA options in the existing server settings
---
Search includes the separate CoA configuration, including legacy mount flight. Changes go to the correct file; realm profile controls stay managed by the Manager.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Existing unsupported character records no longer block unrelated server updates
---
Updates compare each affected character with its saved pre-update state. Unchanged older problems are reported as warnings without changing characters. Newly missing race/class data still blocks the update and triggers recovery; schema and identity checks remain enforced.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Recovery can stop an unfinished world startup after restoring an older launcher
---
If the world console is unavailable, stop only the verified recorded world process. Keep MySQL running if ownership or shutdown cannot be confirmed.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: New server installation waits for slower database startup
---
Allow up to five minutes for MySQL to become ready. Failed installations stop their temporary database before cleaning up its files.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Control portable characters and keep Manager running in the system tray
---
Realm access settings can enable portable characters. Closing the window keeps Manager in the tray, with commands to reopen or exit. Offline realm messages explain why players cannot connect.
@@ -0,0 +1,7 @@
---
area: manager
type: changed
audience: admins
title: Settings group updates, startup and maintenance with translated release history
---
Server and Manager keep separate update controls. Read their published changes in one place, including translations of the latest releases in all six interface languages. Saved notes remain available offline. Find public realm controls under Play with friends.
@@ -0,0 +1,7 @@
---
area: manager
type: changed
audience: admins
title: Update and launch without updating share a divided button
---
Server and game client actions each use two adjacent segments of equal height. Both actions remain visible and keep their own availability checks.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Simultaneous update checks share results or wait their turn
---
Repeated checks no longer compete with another foreground or background check in the same Manager window. Maintenance and recovery locks remain enforced.
+7
View File
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Maximizing the window keeps text and controls at a comfortable size
---
The interface no longer enlarges with window width. System display scaling and browser zoom still work, and large action buttons use more compact spacing.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Slow server startup no longer triggers an early update rollback
---
World startup now allows up to 25 minutes with either bot system and waits for both game and console ports within one deadline. Servers that stop during startup still fail immediately.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Account creation verifies a lost console reply against the requested login
---
Confirm the requested credentials after a lost reply, block creation during another server action, and explicitly report accounts whose administrator access could not be confirmed.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Abandoned game relay tunnels close their local connection immediately
---
Dropping a tunnel shuts down its shared socket directly instead of relying only on a background message, releasing its local read and write connection.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Keep disabled graphics components disabled during client updates
---
Client settings can disable DXVK and graphics enhancements. Existing launcher DISABLED files are respected.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Force-stop an unresponsive world after a failed normal shutdown
---
Confirm the risk of unsaved progress before stopping verified server processes. Shared databases stay running until every owned world has stopped.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Crash history includes reports from every world and Windows text files
---
Create and verify the crash report folder before native startup, and include reports from simultaneous worlds and files containing Windows ANSI text.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Show the online bot count for Playerbots on the overview
---
The overview displays bot population for both supported bot systems.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Disable public server browsing in Settings
---
Turn off public server browsing to block catalog list and detail requests. When browsing is enabled, load the list with Refresh.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Keep deliberate stops and update shutdowns from triggering crash restart
---
Status checks no longer forget a stop request while the world is still shutting down. Update validation and recovery do not trigger automatic crash restarts.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Show available update notes even when release history is cached
---
Fetch the release notes for the offered update when they are missing from the cached history, including when an update becomes available while the history is open.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Server startup waits for a responsive console before reporting success
---
An open port no longer marks a loading world as ready. Account creation checks that the console processes commands before sending a create request.
+7
View File
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Restore the existing Manager window when launching it again
---
Choose whether closing the window exits the Manager or minimizes it to the tray. Tray actions restore the window on the UI thread.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Dungeon Clear can be enabled when SQUID bots are active
---
Dungeon Clear starts disabled. Switching SQUID bots off also switches Dungeon Clear off; enabling SQUID again leaves Dungeon Clear off until you choose to enable it.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Diagnostic exports include launcher stages and lock owner records
---
Support packages include recent launcher diagnostics for each realm, with sensitive fields removed. Recorded lock owners help diagnose overlapping startup and shutdown actions.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Custom Races patch installation recovers from interrupted downloads
---
Unfinished downloads resume automatically. Invalid archives in Downloads are skipped without changing them, and damaged cached archives are downloaded again.
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Choose normal logs, errors only or no server logs in maintenance settings
---
The logging preset updates both the game world and login server, including their configuration templates. Previous settings are saved in configuration snapshots. Restart the server to apply the change.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Update checks temporarily suspend bot population and restore your configuration
---
Validation preserves the selected bot system and its population limits. Original configuration files are restored after validation, including recovery from interrupted updates.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: admins
title: Update validation keeps MySQL running between compatible checks
---
Database checks and the temporary server startup share one MySQL session. The server still stops before files or database snapshots are replaced or restored.
@@ -0,0 +1,6 @@
---
area: manager
type: fixed
audience: admins
title: Update and recovery checks use the temporary login port even with a Windows override
---
@@ -0,0 +1,7 @@
---
area: manager
type: added
audience: admins
title: Settings for how much help bots get in dungeons and raids
---
Bot damage, healing, damage taken and tank threat can now be tuned under Bots, Combat. Everything defaults to 1 (no change); a switch turns the extra help for four hard bosses on.
@@ -0,0 +1,7 @@
---
area: manager
type: fixed
audience: players
title: Turning the custom races client patch on or off takes seconds again
---
V2 has over 7,000 files and switching it could run for many minutes. Now only the files the game itself loads are hidden, and the rest stays in place. A switch that was cut short is undone safely.
@@ -0,0 +1,7 @@
---
area: manager
type: changed
audience: players
title: The custom races client is updated to Custom Races V2
---
The client update installs V2 and starts its own CoACustomRace.exe; Ascension.exe is left as it was. Four archives are the same as in 1.9.2, so a game folder that already had 1.9.2 downloads only the rest.
+314 -1
View File
@@ -112,6 +112,8 @@
"Corfirean/coa-server-manager:20261016-preserve-core-migration-history.md", "Corfirean/coa-server-manager:20261016-preserve-core-migration-history.md",
"Corfirean/coa-server-manager:20261016-shared-auth-migration-history.md", "Corfirean/coa-server-manager:20261016-shared-auth-migration-history.md",
"Corfirean/coa-server-manager:20261016-update-compatibility-wording.md", "Corfirean/coa-server-manager:20261016-update-compatibility-wording.md",
"Corfirean/coa-server-manager:20261017-creature-difficulty-rates.md",
"Corfirean/coa-server-manager:20261017-existing-router-mapping.md",
"Corfirean/coa-server-manager:20261018-custom-races-client.md", "Corfirean/coa-server-manager:20261018-custom-races-client.md",
"Corfirean/coa-server-manager:20261019-portable-stop-diagnostics.md", "Corfirean/coa-server-manager:20261019-portable-stop-diagnostics.md",
"Corfirean/coa-server-manager:20261019-remote-character-class-names.md", "Corfirean/coa-server-manager:20261019-remote-character-class-names.md",
@@ -120,7 +122,63 @@
"Corfirean/coa-server-manager:20261021-portable-experimental.md", "Corfirean/coa-server-manager:20261021-portable-experimental.md",
"Corfirean/coa-server-manager:20261021-scaling-health-settings.md", "Corfirean/coa-server-manager:20261021-scaling-health-settings.md",
"Corfirean/coa-server-manager:20261021-warcraft-reborn-realm.md", "Corfirean/coa-server-manager:20261021-warcraft-reborn-realm.md",
"Corfirean/coa-server-manager:20261022-custom-races-client.md" "Corfirean/coa-server-manager:20261022-custom-races-client.md",
"Corfirean/coa-server-manager:20261022-scaling-progression-modes.md",
"Corfirean/coa-server-manager:20261023-ah-bot-single-switch.md",
"Corfirean/coa-server-manager:20261023-interface-language-coverage.md",
"Corfirean/coa-server-manager:20261023-online-players-exclude-squid-bots.md",
"Corfirean/coa-server-manager:20261023-shared-addons-links.md",
"Corfirean/coa-server-manager:20261023-time-is-time-settings.md",
"Corfirean/coa-server-manager:20261023-update-check-database-timeout.md",
"Corfirean/coa-server-manager:20261024-portable-admission.md",
"Corfirean/coa-server-manager:20261024-portable-owner-core-activation.md",
"Corfirean/coa-server-manager:20261024-portable-schema-nine.md",
"Corfirean/coa-server-manager:20261024-relay-authentication.md",
"Corfirean/coa-server-manager:20261024-relay-recovery.md",
"Corfirean/coa-server-manager:20261024-remote-progress.md",
"Corfirean/coa-server-manager:20261024-remote-refresh.md",
"Corfirean/coa-server-manager:20261025-custom-races-191.md",
"Corfirean/coa-server-manager:20261026-custom-races-192.md",
"Corfirean/coa-server-manager:20261027-content-scaling-reports.md",
"Corfirean/coa-server-manager:20261027-custom-races-reports.md",
"Corfirean/coa-server-manager:20261027-internet-lan-address.md",
"Corfirean/coa-server-manager:20261027-merged-database-migration-order.md",
"Corfirean/coa-server-manager:20261027-per-race-server-settings.md",
"Corfirean/coa-server-manager:20261027-public-list-shows-every-running-realm.md",
"Corfirean/coa-server-manager:20261027-public-listing-window.md",
"Corfirean/coa-server-manager:20261027-skill-gain-controls.md",
"Corfirean/coa-server-manager:20261027-start-checks-the-realm-class-setting.md",
"Corfirean/coa-server-manager:20261027-start-wildcard-and-reborn-with-coa.md",
"Corfirean/coa-server-manager:20261028-coa-config-search.md",
"Corfirean/coa-server-manager:20261028-existing-character-update-validation.md",
"Corfirean/coa-server-manager:20261028-legacy-world-shutdown.md",
"Corfirean/coa-server-manager:20261028-mysql-install-startup.md",
"Corfirean/coa-server-manager:20261028-portable-settings-and-tray.md",
"Corfirean/coa-server-manager:20261028-settings-release-history.md",
"Corfirean/coa-server-manager:20261028-split-update-actions.md",
"Corfirean/coa-server-manager:20261028-update-check-queue.md",
"Corfirean/coa-server-manager:20261028-window-density.md",
"Corfirean/coa-server-manager:20261029-slow-world-startup.md",
"Corfirean/coa-server-manager:20261030-account-console-confirmation.md",
"Corfirean/coa-server-manager:20261030-close-abandoned-relay-sockets.md",
"Corfirean/coa-server-manager:20261030-disabled-client-renderers.md",
"Corfirean/coa-server-manager:20261030-force-stop-unresponsive-world.md",
"Corfirean/coa-server-manager:20261030-native-crash-reports.md",
"Corfirean/coa-server-manager:20261030-playerbots-overview-count.md",
"Corfirean/coa-server-manager:20261030-public-server-browsing-control.md",
"Corfirean/coa-server-manager:20261030-stop-does-not-trigger-auto-restart.md",
"Corfirean/coa-server-manager:20261030-update-history-target-cache.md",
"Corfirean/coa-server-manager:20261030-wait-for-world-console-readiness.md",
"Corfirean/coa-server-manager:20261030-window-lifecycle.md",
"Corfirean/coa-server-manager:20261031-dungeon-clear-dependency.md",
"Corfirean/coa-server-manager:20261031-launcher-diagnostics-export.md",
"Corfirean/coa-server-manager:20261031-recover-client-patch-downloads.md",
"Corfirean/coa-server-manager:20261031-server-logging-controls.md",
"Corfirean/coa-server-manager:20261031-validation-bot-population.md",
"Corfirean/coa-server-manager:20261031-validation-mysql-reuse.md",
"Corfirean/coa-server-manager:20261103-isolated-login-port.md",
"Corfirean/coa-server-manager:20261107-bot-strength-scaling-settings.md",
"Corfirean/coa-server-manager:20261115-custom-races-v2-client.md"
], ],
"releases": [ "releases": [
{ {
@@ -623,6 +681,261 @@
"links": [ "links": [
"[Guides and screenshots](https://github.com/Corfirean/coa-server-manager/blob/master/docs/README.md)" "[Guides and screenshots](https://github.com/Corfirean/coa-server-manager/blob/master/docs/README.md)"
] ]
},
{
"tag": "v0.7.2",
"version": "0.7.2",
"date": "2026-10-23",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.7.2",
"notes": [
"Advanced settings cover creature melee damage, spell damage and health by rank",
"Internet sharing accepts existing port forwards to the same server",
"The Auction House Bot card has a single switch",
"More character and server browser controls now use your selected language",
"Online player counts correctly separate random bots from players",
"Custom races work with shared addon folders on another drive",
"Configure the day and night cycle from the module settings",
"A stalled database inspection no longer blocks server maintenance indefinitely"
],
"commit": "4d59ce8cb1d4abd7f4992370e9a7ba4dc6bd02f7",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.7.1...v0.7.2"
},
{
"tag": "v0.7.3",
"version": "0.7.3",
"date": "2026-10-23",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.7.3",
"notes": [
"Portable characters open again after using an experimental Manager"
],
"commit": "2715170622665f62c396fe1a79f7ef6504713ef1",
"experimentalFeatures": [
"portable-characters"
],
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.7.2...v0.7.3"
},
{
"tag": "v0.8.0",
"version": "0.8.0",
"date": "2026-10-24",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.8.0",
"notes": [
"Server owners can allow portable characters per realm",
"Allowing portable characters also prepares the server for portable sessions",
"Managers stay compatible with the public connection service",
"Relay connections recover and use the ports of the installed server",
"Portable progress resumes after reconnecting or restarting the Manager",
"Older copies on another host may require maintenance before returning"
],
"commit": "b00e732c7f53f33680aaf6bd520da64b70b26a5a",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.7.3...v0.8.0",
"experimentalFeatures": [
"portable-characters"
]
},
{
"tag": "v0.8.1",
"version": "0.8.1",
"date": "2026-10-25",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.8.1",
"notes": [
"Install the matching CoA Custom 1.9.1 client files"
],
"commit": "02e3a9e4e66870a627feeb0b4d3ec2d75a23973d",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.8.0...v0.8.1",
"experimentalFeatures": [
"portable-characters"
]
},
{
"tag": "v0.8.2",
"version": "0.8.2",
"date": "2026-10-27",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.8.2",
"notes": [
"Installs the verified CoA Custom 1.9.2 client patches and quest safety addon, while recognizing existing 1.9.1 installations",
"Server updates preserve the order of database migrations introduced during merges, preventing older snapshots from overwriting newer progression"
],
"commit": "81b040ef02763c7cf7a3a3da1424b73177e9d433",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.8.1...v0.8.2",
"experimentalFeatures": [
"portable-characters"
]
},
{
"tag": "v0.9.0",
"version": "0.9.0",
"date": "2026-10-28",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.0",
"notes": [
"Choose Parallel or Global level scaling in module settings",
"Report Content Scaling problems directly to its repository",
"Send custom race problem reports directly to their maintainer",
"Internet sharing restores the LAN address after server restarts",
"Configure custom race availability for new characters",
"Public listing offers every realm that starts together, not just the main one",
"Public listing is a short list of realms with a window for the details",
"Configure profession and defense skill gains in server settings",
"Starting a server sets the character classes of the realm chosen on Overview",
"Start Wildcard and Warcraft Reborn together with Conquest of Azeroth",
"Control portable characters and keep Manager running in the system tray"
],
"commit": "dc97095bd6b36d9b5111f04f0cfd88e1fb2ab1f1",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.8.2...v0.9.0",
"experimentalFeatures": [
"portable-characters"
]
},
{
"version": "0.9.1",
"tag": "v0.9.1",
"date": "2026-10-28",
"notes": [
"Existing unsupported character records no longer block unrelated server updates"
],
"experimentalFeatures": [
"portable-characters"
],
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.1",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.0...v0.9.1",
"commit": "8bbf16ed4f14e9b78c680783e4be5d8c580cc06b"
},
{
"tag": "v0.9.2",
"version": "0.9.2",
"date": "2026-10-28",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.2",
"notes": [
"New server installation waits for slower database startup",
"Find and edit CoA options in the existing server settings",
"Simultaneous update checks share results or wait their turn",
"Recovery can stop an unfinished world startup after restoring an older launcher"
],
"commit": "2d9c6a65bbb1e296dc919e4c9e5785ed9d4a070b",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.1...v0.9.2",
"experimentalFeatures": [
"portable-characters"
]
},
{
"tag": "v0.9.3",
"version": "0.9.3",
"date": "2026-10-29",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.3",
"notes": [
"Slow server startup no longer triggers an early update rollback"
],
"commit": "e7b76137d1b22a7596c2b1fa05ca9d12403b99d3",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.2...v0.9.3",
"experimentalFeatures": [
"portable-characters"
]
},
{
"tag": "v0.9.4",
"version": "0.9.4",
"date": "2026-10-29",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.4",
"notes": [
"Settings group updates, startup and maintenance with translated release history",
"Update and launch without updating share a divided button",
"Maximizing the window keeps text and controls at a comfortable size"
],
"commit": "c004b90c54fa358b3037c56b093cf019dfcf02b8",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.3...v0.9.4",
"experimentalFeatures": [
"portable-characters"
]
},
{
"tag": "v0.9.5",
"version": "0.9.5",
"date": "2026-10-30",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.5",
"notes": [
"Account creation verifies a lost console reply against the requested login",
"Abandoned game relay tunnels close their local connection immediately",
"Keep disabled graphics components disabled during client updates",
"Force-stop an unresponsive world after a failed normal shutdown",
"Crash history includes reports from every world and Windows text files",
"Show the online bot count for Playerbots on the overview",
"Disable public server browsing in Settings",
"Keep deliberate stops and update shutdowns from triggering crash restart",
"Server startup waits for a responsive console before reporting success",
"Restore the existing Manager window when launching it again"
],
"commit": "642da8fdc1a0165aea74fbd1ab1b46933fc7e589",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.4...v0.9.5"
},
{
"tag": "v0.9.7",
"version": "0.9.7",
"date": "2026-10-30",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.7",
"notes": [
"Show available update notes even when release history is cached"
],
"commit": "ba5816e3aea471d5b870e5f0db0b03920c071ed3",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.5...v0.9.7"
},
{
"tag": "v0.9.8",
"version": "0.9.8",
"date": "2026-11-01",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.8",
"notes": [
"Dungeon Clear can be enabled when SQUID bots are active",
"Diagnostic exports include launcher stages and lock owner records",
"Choose normal logs, errors only or no server logs in maintenance settings",
"Update checks temporarily suspend bot population and restore your configuration",
"Update validation keeps MySQL running between compatible checks"
],
"commit": "076fba185c4d96d74f7258d6ca0cae6a4ae4a613",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.7...v0.9.8"
},
{
"tag": "v0.9.9",
"version": "0.9.9",
"date": "2026-11-04",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.9",
"notes": [
"Update and recovery checks use the temporary login port even with a Windows override"
],
"commit": "173248efbe24da9b4c1b5ca12fa7580fcd1e8ea7",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.8...v0.9.9"
},
{
"tag": "v0.9.10",
"version": "0.9.10",
"date": "2026-11-08",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.10",
"notes": [
"Custom Races patch installation recovers from interrupted downloads"
],
"commit": "711f378ae82f75d3fc64368c042889c773315c54",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.9...v0.9.10"
},
{
"tag": "v0.9.12",
"version": "0.9.12",
"date": "2026-11-14",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.12",
"notes": [
"Settings for how much help bots get in dungeons and raids"
],
"commit": "d71c5635e3262a775b400a1c90ac81d7bddcbeaf",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.10...v0.9.12"
},
{
"tag": "v0.9.13",
"version": "0.9.13",
"date": "2026-11-15",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.13",
"notes": [
"The custom races client is updated to Custom Races V2"
],
"commit": "d3527312803fb5a3e1cd48e01496645a8bbc9dcf",
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.12...v0.9.13"
} }
] ]
} }
+115 -1
View File
@@ -15,6 +15,15 @@ pub const MAX_USERNAME: usize = 16;
pub const MIN_PASSWORD: usize = 8; pub const MIN_PASSWORD: usize = 8;
pub const MAX_PASSWORD: usize = 16; pub const MAX_PASSWORD: usize = 16;
pub const MAX_CHARACTERS: usize = 200; pub const MAX_CHARACTERS: usize = 200;
pub const MAX_SESSION_BYTES: usize = 12 * 1024 * 1024;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SessionMessageKind {
Started,
Checkpoint,
Collection,
}
/// A game account name: 3 to 16 ASCII letters, digits or `_`, not beginning or ending with `_`. /// A game account name: 3 to 16 ASCII letters, digits or `_`, not beginning or ending with `_`.
pub fn valid_username(s: &str) -> bool { pub fn valid_username(s: &str) -> bool {
@@ -103,6 +112,16 @@ pub enum Request {
TransferOffer { TransferOffer {
transfer_id: Uuid, transfer_id: Uuid,
character_id: Uuid, character_id: Uuid,
ruleset: String,
canonical_revision: u64,
content_hash: String,
total_size: usize,
collections: BTreeMap<String, Vec<u32>>,
},
OwnedTransferOffer {
transfer_id: Uuid,
character_id: Uuid,
ruleset: String,
canonical_revision: u64, canonical_revision: u64,
content_hash: String, content_hash: String,
total_size: usize, total_size: usize,
@@ -127,6 +146,24 @@ pub enum Request {
transfer_id: Uuid, transfer_id: Uuid,
character_id: Uuid, character_id: Uuid,
}, },
SessionPoll {
character_id: Uuid,
session_id: Uuid,
},
SessionRead {
character_id: Uuid,
session_id: Uuid,
message_hash: String,
offset: usize,
},
SessionAck {
character_id: Uuid,
session_id: Uuid,
message_hash: String,
offset: usize,
total_size: usize,
data: String,
},
/// Phase 13: Request a short-lived relay allocation for a relayed JOIN. /// Phase 13: Request a short-lived relay allocation for a relayed JOIN.
AllocateRelay { AllocateRelay {
player_id: Uuid, player_id: Uuid,
@@ -171,6 +208,22 @@ pub struct CharacterEntry {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")] #[serde(tag = "op", rename_all = "snake_case")]
pub enum Response { pub enum Response {
SessionPending {
kind: SessionMessageKind,
total_size: usize,
content_hash: String,
},
SessionIdle {
closed: bool,
},
SessionData {
offset: usize,
data: String,
},
SessionAcked {
received_size: usize,
complete: bool,
},
Welcome { Welcome {
realm_id: coa_registry_proto::RealmId, realm_id: coa_registry_proto::RealmId,
automatic: bool, automatic: bool,
@@ -189,6 +242,7 @@ pub enum Response {
/// appearance and vanity ids the Host holds for the account (kind -> ids). /// appearance and vanity ids the Host holds for the account (kind -> ids).
Claimed { Claimed {
character_id: Uuid, character_id: Uuid,
ruleset: String,
sha256: String, sha256: String,
payload: String, payload: String,
collections: BTreeMap<String, Vec<u32>>, collections: BTreeMap<String, Vec<u32>>,
@@ -245,7 +299,10 @@ pub fn decode_request(bytes: &[u8]) -> Result<Request> {
.map_err(|_| ControlError::Invalid("a request is not valid".into()))?; .map_err(|_| ControlError::Invalid("a request is not valid".into()))?;
if !matches!( if !matches!(
&r, &r,
Request::TransferOffer { .. } | Request::TransferChunk { .. } Request::TransferOffer { .. }
| Request::OwnedTransferOffer { .. }
| Request::TransferChunk { .. }
| Request::SessionAck { .. }
) && bytes.len() > MAX_CONTROL_REQUEST_BYTES ) && bytes.len() > MAX_CONTROL_REQUEST_BYTES
{ {
return Err(ControlError::Limit( return Err(ControlError::Limit(
@@ -253,6 +310,34 @@ pub fn decode_request(bytes: &[u8]) -> Result<Request> {
)); ));
} }
match &r { match &r {
Request::SessionRead {
message_hash,
offset,
..
} => {
if message_hash.len() != 64
|| !message_hash.bytes().all(|b| b.is_ascii_hexdigit())
|| *offset > MAX_SESSION_BYTES
{
return invalid("invalid portable session read");
}
}
Request::SessionAck {
message_hash,
offset,
total_size,
data,
..
} => {
if message_hash.len() != 64
|| !message_hash.bytes().all(|b| b.is_ascii_hexdigit())
|| *total_size > MAX_SESSION_BYTES
|| *offset > *total_size
|| data.len() > 48 * 1024
{
return invalid("invalid portable session acknowledgement chunk");
}
}
Request::Provision { Request::Provision {
desired, password, .. desired, password, ..
} => { } => {
@@ -273,11 +358,22 @@ pub fn decode_request(bytes: &[u8]) -> Result<Request> {
return invalid("the client name is too long") return invalid("the client name is too long")
} }
Request::TransferOffer { Request::TransferOffer {
ruleset,
content_hash,
total_size,
collections,
..
}
| Request::OwnedTransferOffer {
ruleset,
content_hash, content_hash,
total_size, total_size,
collections, collections,
.. ..
} => { } => {
if !matches!(ruleset.as_str(), "coa" | "wildcard" | "reborn") {
return invalid("transfer ruleset must be coa, wildcard, or reborn");
}
if content_hash.len() != 64 || !content_hash.chars().all(|c| c.is_ascii_hexdigit()) { if content_hash.len() != 64 || !content_hash.chars().all(|c| c.is_ascii_hexdigit()) {
return invalid("transfer content hash must be 64 hex characters"); return invalid("transfer content hash must be 64 hex characters");
} }
@@ -430,6 +526,7 @@ mod tests {
let offer = Request::TransferOffer { let offer = Request::TransferOffer {
transfer_id: tid, transfer_id: tid,
character_id: cid, character_id: cid,
ruleset: "coa".into(),
canonical_revision: 5, canonical_revision: 5,
content_hash: hash.clone(), content_hash: hash.clone(),
total_size: 1024, total_size: 1024,
@@ -442,6 +539,7 @@ mod tests {
let bad_hash = Request::TransferOffer { let bad_hash = Request::TransferOffer {
transfer_id: tid, transfer_id: tid,
character_id: cid, character_id: cid,
ruleset: "coa".into(),
canonical_revision: 5, canonical_revision: 5,
content_hash: "too_short".into(), content_hash: "too_short".into(),
total_size: 1024, total_size: 1024,
@@ -466,5 +564,21 @@ mod tests {
}; };
let resp_dec = decode_response(&encode_response(&resp)).unwrap(); let resp_dec = decode_response(&encode_response(&resp)).unwrap();
assert_eq!(resp, resp_dec); assert_eq!(resp, resp_dec);
// Control protocol v2 requires ruleset in TransferOffer; missing is rejected
let missing_ruleset_json = serde_json::json!({
"op": "transfer_offer",
"transfer_id": tid,
"character_id": cid,
"canonical_revision": 5,
"content_hash": hash,
"total_size": 1024,
"collections": {}
});
let encoded_missing = serde_json::to_vec(&missing_ruleset_json).unwrap();
assert!(
decode_request(&encoded_missing).is_err(),
"missing ruleset in v2 must be rejected"
);
} }
} }
+14 -2
View File
@@ -112,6 +112,10 @@ pub struct ProbeResponse {
pub all_reachable: bool, pub all_reachable: bool,
} }
/// Coordinator authentication is independent of the encrypted application protocol.
/// Changing portable messages must not invalidate deployed v1 host/player proofs.
pub const COORDINATOR_PROTOCOL_VERSION: u32 = 1;
pub fn challenge_nonce() -> String { pub fn challenge_nonce() -> String {
let mut n = [0u8; 32]; let mut n = [0u8; 32];
n[..16].copy_from_slice(Uuid::new_v4().as_bytes()); n[..16].copy_from_slice(Uuid::new_v4().as_bytes());
@@ -122,7 +126,7 @@ pub fn challenge_nonce() -> String {
fn host_input(realm: &RealmId, nonce: &str, ts: i64) -> Vec<u8> { fn host_input(realm: &RealmId, nonce: &str, ts: i64) -> Vec<u8> {
format!( format!(
"coa-coord-host-v1\n{}\n{realm}\n{nonce}\n{ts}", "coa-coord-host-v1\n{}\n{realm}\n{nonce}\n{ts}",
crate::CONTROL_PROTOCOL_VERSION COORDINATOR_PROTOCOL_VERSION
) )
.into_bytes() .into_bytes()
} }
@@ -130,7 +134,7 @@ fn host_input(realm: &RealmId, nonce: &str, ts: i64) -> Vec<u8> {
fn player_input(player: &Uuid, public_key: &str, realm: &RealmId, nonce: &str, ts: i64) -> Vec<u8> { fn player_input(player: &Uuid, public_key: &str, realm: &RealmId, nonce: &str, ts: i64) -> Vec<u8> {
format!( format!(
"coa-coord-player-v1\n{}\n{}\n{public_key}\n{realm}\n{nonce}\n{ts}", "coa-coord-player-v1\n{}\n{}\n{public_key}\n{realm}\n{nonce}\n{ts}",
crate::CONTROL_PROTOCOL_VERSION, COORDINATOR_PROTOCOL_VERSION,
player.hyphenated() player.hyphenated()
) )
.into_bytes() .into_bytes()
@@ -277,6 +281,14 @@ pub fn to_text(frame: &Frame) -> String {
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn deployed_coordinator_proofs_stay_v1_when_application_protocol_changes() {
let realm = RealmId::new();
let player = Uuid::now_v7();
assert_eq!(host_input(&realm, "nonce", 42), format!("coa-coord-host-v1\n1\n{realm}\nnonce\n42").into_bytes());
assert_eq!(player_input(&player, "public", &realm, "nonce", 42), format!("coa-coord-player-v1\n1\n{player}\npublic\n{realm}\nnonce\n42").into_bytes());
}
fn key(n: u8) -> SigningKey { fn key(n: u8) -> SigningKey {
SigningKey::from_bytes(&[n; 32]) SigningKey::from_bytes(&[n; 32])
} }
+1 -1
View File
@@ -16,7 +16,7 @@ pub mod coord;
pub mod noise; pub mod noise;
pub mod relay; pub mod relay;
pub const CONTROL_PROTOCOL_VERSION: u32 = 1; pub const CONTROL_PROTOCOL_VERSION: u32 = 2;
#[derive(Debug, thiserror::Error, PartialEq, Eq)] #[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum ControlError { pub enum ControlError {
@@ -90,6 +90,7 @@ fn test_app_request_hostile_limits_and_validation() {
let offer = Request::TransferOffer { let offer = Request::TransferOffer {
transfer_id: Uuid::now_v7(), transfer_id: Uuid::now_v7(),
character_id: Uuid::now_v7(), character_id: Uuid::now_v7(),
ruleset: "coa".into(),
canonical_revision: 1, canonical_revision: 1,
content_hash: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".into(), content_hash: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".into(),
total_size: 1024, total_size: 1024,
@@ -105,6 +106,7 @@ fn test_app_request_hostile_limits_and_validation() {
let bad_hash_offer = Request::TransferOffer { let bad_hash_offer = Request::TransferOffer {
transfer_id: Uuid::now_v7(), transfer_id: Uuid::now_v7(),
character_id: Uuid::now_v7(), character_id: Uuid::now_v7(),
ruleset: "coa".into(),
canonical_revision: 1, canonical_revision: 1,
content_hash: "not_a_valid_hex_hash".into(), content_hash: "not_a_valid_hex_hash".into(),
total_size: 1024, total_size: 1024,
@@ -112,6 +114,18 @@ fn test_app_request_hostile_limits_and_validation() {
}; };
assert!(decode_request(&encode_request(&bad_hash_offer)).is_err()); assert!(decode_request(&encode_request(&bad_hash_offer)).is_err());
// 4b. Invalid ruleset rejected
let bad_ruleset_offer = Request::TransferOffer {
transfer_id: Uuid::now_v7(),
character_id: Uuid::now_v7(),
ruleset: "invalid_ruleset".into(),
canonical_revision: 1,
content_hash: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".into(),
total_size: 1024,
collections: BTreeMap::new(),
};
assert!(decode_request(&encode_request(&bad_ruleset_offer)).is_err());
// 5. TransferChunk offset out of bounds // 5. TransferChunk offset out of bounds
let bad_offset_chunk = Request::TransferChunk { let bad_offset_chunk = Request::TransferChunk {
transfer_id: Uuid::now_v7(), transfer_id: Uuid::now_v7(),
@@ -0,0 +1,154 @@
use coa_core::{
db::{Account, Db},
driver::{self, Verb},
ra::Ra,
Result,
};
use std::path::PathBuf;
fn main() -> Result<()> {
let root = PathBuf::from(std::env::args().nth(1).expect("disposable fixture"));
assert!(root
.file_name()
.unwrap()
.to_string_lossy()
.starts_with("coa-update-recovery-fixture-"));
assert!(root.join("recovery-e2e-started").is_file());
let result = std::panic::catch_unwind(|| -> Result<()> {
let started = driver::run(&root, Verb::StartAll)?;
assert!(started.ok, "{}", started.output);
assert!(root.join("Core/Crashes").is_dir());
let db = Db::from_repack(&root, Account::Admin)?;
println!("Account acceptance: server started, connecting to RA");
let mut ra = Ra::connect(&root)?;
println!("Account acceptance: RA authenticated");
let name = "STABILITYACCT2";
assert_eq!(
db.query("SELECT COUNT(*) FROM acore_auth.account WHERE username='STABILITYACCT2';")?
.trim(),
"0"
);
println!("Account acceptance: sending create command");
coa_core::accounts::create(&root, name, "PrivateTest773", true)?;
println!("Account acceptance: created");
assert_eq!(db.query("SELECT COUNT(*) FROM acore_auth.account WHERE username='STABILITYACCT2' AND LENGTH(salt)=32 AND LENGTH(verifier)=32;")?.trim(), "1");
assert!(ra
.create_account(name, "PrivateTest773")
.unwrap_err()
.to_string()
.contains("already taken"));
ra.set_account_password(name, "PrivateTest774")?;
ra.set_account_access(name, 3)?;
assert_eq!(db.query("SELECT gmlevel FROM acore_auth.account_access WHERE id=(SELECT id FROM acore_auth.account WHERE username='STABILITYACCT2');")?.trim(), "3");
ra.delete_account(name)?;
assert_eq!(
db.query("SELECT COUNT(*) FROM acore_auth.account WHERE username='STABILITYACCT2';")?
.trim(),
"0"
);
lost_reply(&root, &db)?;
println!("PASS: native RA account create, SRP salt/verifier, duplicate refusal, password change, administrator access and deletion");
Ok(())
});
let stopped = driver::run(&root, Verb::StopAll)?;
assert!(stopped.ok, "{}", stopped.output);
result.map_err(|_| {
coa_core::Error::Invalid("Native account acceptance failed; fixture stopped".into())
})?
}
fn lost_reply(root: &std::path::Path, db: &Db) -> Result<()> {
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
let path = root.join("Settings/repack.json");
let original = std::fs::read(&path)?;
struct Restore(std::path::PathBuf, Vec<u8>);
impl Drop for Restore {
fn drop(&mut self) {
std::fs::write(&self.0, &self.1).expect("restore disposable fixture settings");
}
}
let restore = Restore(path.clone(), original.clone());
let actual = coa_core::layout::read_ports(root).ra;
for (name, forward, ready) in [
("STABLOSTREPLY", true, true),
("STABNOTCREATED", false, true),
("STABNOTREADY", false, false),
] {
assert_eq!(
db.query(&format!(
"SELECT COUNT(*) FROM acore_auth.account WHERE username='{name}';"
))?
.trim(),
"0"
);
let listener = TcpListener::bind(("127.0.0.1", 0))?;
let mut config: serde_json::Value = serde_json::from_slice(&original)?;
config["raPort"] = listener.local_addr()?.port().into();
coa_core::fsx::atomic_write_json(&path, &config)?;
let proxy = std::thread::spawn(move || {
fn until(s: &mut TcpStream, marker: &[u8]) -> Vec<u8> {
s.set_read_timeout(Some(std::time::Duration::from_secs(30)))
.unwrap();
let mut bytes = Vec::new();
let mut byte = [0];
while !bytes.ends_with(marker) {
s.read_exact(&mut byte).unwrap();
bytes.push(byte[0]);
}
bytes
}
let (mut client, _) = listener.accept().unwrap();
let mut server = TcpStream::connect(("127.0.0.1", actual)).unwrap();
for marker in [b"Username: ".as_slice(), b"Password: ".as_slice()] {
client.write_all(&until(&mut server, marker)).unwrap();
server.write_all(&until(&mut client, b"\r\n")).unwrap();
}
client.write_all(&until(&mut server, b"AC>")).unwrap();
let readiness = until(&mut client, b"\r\n");
assert_eq!(readiness, b"server info\r\n");
if !ready {
return;
}
server.write_all(&readiness).unwrap();
client.write_all(&until(&mut server, b"AC>")).unwrap();
let command = until(&mut client, b"\r\n");
if forward {
server.write_all(&command).unwrap();
let _ = until(&mut server, b"AC>");
}
});
let outcome = coa_core::accounts::create(root, name, "PrivateTest773", false);
proxy.join().unwrap();
std::fs::write(&path, &original)?;
if forward {
outcome?;
assert_eq!(
db.query(&format!(
"SELECT COUNT(*) FROM acore_auth.account WHERE username='{name}';"
))?
.trim(),
"1"
);
assert!(coa_core::accounts::create(root, name, "DifferentPass77", false).is_err());
Ra::connect(root)?.delete_account(name)?;
} else {
assert!(outcome.is_err());
if !ready {
assert!(outcome
.unwrap_err()
.to_string()
.contains("No create command was sent"));
}
assert_eq!(
db.query(&format!(
"SELECT COUNT(*) FROM acore_auth.account WHERE username='{name}';"
))?
.trim(),
"0"
);
}
}
drop(restore);
println!("PASS: a lost native console reply is reconciled by exact SRP credentials; a command that was never executed is rejected");
Ok(())
}
@@ -0,0 +1,11 @@
use coa_core::{crashes, Result};
fn main()->Result<()> {
let root=std::path::PathBuf::from(std::env::args().nth(1).expect("marked native fixture"));
assert!(root.join("recovery-e2e-started").is_file());
let reports=crashes::list(&root,30)?;
let matching:Vec<_>=reports.iter().filter(|r|r.full_log.contains("AllowableRaces")).collect();
assert!(!matching.is_empty());
assert!(matching.iter().all(|r|r.exception_code.as_deref()==Some("C0000420")));
println!("PASS: Manager discovered {} actual worldserver SQL assertion reports from Core/Crashes, including Windows ANSI text",matching.len());
Ok(())
}
@@ -0,0 +1,91 @@
use coa_core::{
db::{Account, Db},
driver::{self, Verb},
ra::Ra,
Result,
};
use std::{
path::PathBuf,
time::{Duration, Instant},
};
fn main() -> Result<()> {
let root = PathBuf::from(
std::env::args()
.nth(1)
.expect("disposable recovery fixture"),
);
assert!(root
.file_name()
.unwrap()
.to_string_lossy()
.starts_with("coa-update-recovery-fixture-"));
assert!(root.join("recovery-e2e-started").is_file());
let result = std::panic::catch_unwind(|| -> Result<()> {
let start = driver::run(&root, Verb::StartAll)?;
assert!(start.ok, "{}", start.output);
let db = Db::from_repack(&root, Account::Admin)?;
coa_core::companions::ensure_templates(&db)?;
let mut ra = Ra::connect(&root)?;
let before = coa_core::population::query(&root)?;
assert_eq!(before.bots_online, 0);
let rejected = db.query("SELECT name, at_login FROM acore_characters.characters WHERE guid=3030 AND account IN (SELECT id FROM acore_auth.account WHERE username LIKE 'COABOTHOST%');")?;
assert!(rejected.contains("Christian Shadowheart"));
assert_eq!(rejected.split_whitespace().last(), Some("1"));
println!("Repair reply: {}", ra.run("botcmd spawnbot 3030")?);
let repair_deadline = Instant::now() + Duration::from_secs(60);
loop {
let row = db.query(
"SELECT name, at_login, online FROM acore_characters.characters WHERE guid=3030;",
)?;
if row.trim().ends_with("0\t1") {
assert!(!row.contains("Christian Shadowheart"));
println!("PASS: the exact previously rejected companion was renamed by server validation and logged in");
break;
}
assert!(
Instant::now() < repair_deadline,
"previously rejected companion logged in"
);
std::thread::sleep(Duration::from_secs(1));
}
let _ = ra.despawn_all()?;
let clear_deadline = Instant::now() + Duration::from_secs(30);
while coa_core::population::query(&root)?.bots_online > 0 {
assert!(Instant::now() < clear_deadline);
std::thread::sleep(Duration::from_secs(1));
}
println!("Spawn reply: {}", ra.spawn_bots(21)?);
let deadline = Instant::now() + Duration::from_secs(180);
loop {
let pop = coa_core::population::query(&root)?;
if pop.bots_online >= 21 {
println!(
"PASS: {} companions logged in; real players={}",
pop.bots_online, pop.players_online
);
break;
}
if Instant::now() > deadline {
return Err(coa_core::Error::Invalid(format!(
"Only {} of 21 companion logins completed",
pop.bots_online
)));
}
std::thread::sleep(Duration::from_secs(2));
}
let _ = ra.cancel_spawning()?;
let _ = ra.despawn_all()?;
let deadline = Instant::now() + Duration::from_secs(30);
while coa_core::population::query(&root)?.bots_online > 0 {
assert!(Instant::now() < deadline, "companions despawned");
std::thread::sleep(Duration::from_secs(1));
}
println!("PASS: companion despawn completed");
Ok(())
});
let stopped = driver::run(&root, Verb::StopAll)?;
assert!(stopped.ok, "{}", stopped.output);
result.map_err(|_| {
coa_core::Error::Invalid("Companion native acceptance panicked; fixture stopped".into())
})?
}
@@ -0,0 +1,12 @@
use coa_core::{crashes, Result};
fn main() -> Result<()> {
let root = std::path::PathBuf::from(std::env::args().nth(1).expect("native crash evidence"));
assert!(root.join(".crash-report-evidence").is_file());
let reports = crashes::list(&root, 10)?;
assert_eq!(reports.len(), 1);
assert_eq!(reports[0].exception_code.as_deref(), Some("C0000005"));
assert_eq!(reports[0].category, "access_violation");
assert!(!reports[0].full_log.is_empty());
println!("PASS: Manager crash history discovers and classifies the actual native handler report from Core/Crashes");
Ok(())
}
@@ -0,0 +1,90 @@
use coa_core::{driver, fsx, process, Result};
#[cfg(windows)]
use std::os::windows::process::CommandExt;
use std::{
path::Path,
process::{Child, Command, Stdio},
};
struct OwnedChild(Child);
impl Drop for OwnedChild {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
fn copy_tree(source: &Path, target: &Path) -> Result<()> {
std::fs::create_dir_all(target)?;
for entry in std::fs::read_dir(source)? {
let entry = entry?;
let destination = target.join(entry.file_name());
if entry.file_type()?.is_dir() {
copy_tree(&entry.path(), &destination)?;
} else {
std::fs::copy(entry.path(), destination)?;
}
}
Ok(())
}
fn spawn(path: &Path) -> OwnedChild {
let mut cmd = Command::new(path);
cmd.args(["-t", "127.0.0.1"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
#[cfg(windows)]
cmd.creation_flags(0x0800_0000);
OwnedChild(cmd.spawn().unwrap())
}
fn main() -> Result<()> {
assert!(cfg!(windows));
let source = std::path::PathBuf::from(
std::env::args()
.nth(1)
.expect("marked disposable runtime source"),
);
assert_eq!(
std::fs::read(source.join(".release-schema-fixture"))?,
b"disposable release-schema fixture"
);
let temp = tempfile::tempdir()?;
let root = temp.path();
copy_tree(&source.join("Runtime"), &root.join("Runtime"))?;
std::fs::create_dir_all(root.join("Core"))?;
std::fs::create_dir_all(root.join("Scripts"))?;
let system =
std::path::PathBuf::from(std::env::var_os("SystemRoot").unwrap()).join("System32/ping.exe");
std::fs::copy(&system, root.join("Core/worldserver.exe"))?;
std::fs::copy(&system, root.join("foreign.exe"))?;
let mut ports = Vec::new();
let mut listeners = Vec::new();
for _ in 0..4 {
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
ports.push(listener.local_addr()?.port());
listeners.push(listener);
}
let config = serde_json::json!({"mysqlPort":ports[0],"authPort":ports[1],"worldPort":ports[2],"raPort":ports[3],"raUsername":"fixture","raPassword":"fixture"});
fsx::atomic_write_json(&root.join("Settings/repack.json"), &config)?;
drop(listeners);
let mut launcher = std::fs::read_to_string(source.join("Scripts/manage.py"))?;
launcher.push_str("\nfrom contextlib import nullcontext\ndef control_lock(): return nullcontext()\ndef stop_all(config):\n assert not process('world'), 'world must stop before database'\n (ROOT/'database-stage').write_text('safe')\n");
fsx::atomic_write(&root.join("Scripts/manage.py"), launcher.as_bytes())?;
let mut foreign = spawn(&root.join("foreign.exe"));
let foreign_identity = process::identity(foreign.0.id()).unwrap();
fsx::atomic_write_json(&root.join(".state/world.json"), &foreign_identity)?;
let rejected = driver::force_stop(root)?;
assert!(!rejected.ok, "a foreign world record must be rejected");
assert!(!root.join("database-stage").exists());
assert!(foreign.0.try_wait()?.is_none());
let mut owned = spawn(&root.join("Core/worldserver.exe"));
let stopped = driver::force_stop(root)?;
assert!(stopped.ok, "{}", stopped.output);
assert!(owned.0.try_wait()?.is_some());
assert!(
foreign.0.try_wait()?.is_none(),
"foreign process was untouched"
);
assert_eq!(std::fs::read(root.join("database-stage"))?, b"safe");
println!("PASS: native Windows forced-stop rejects foreign records, recovers the exact owned world identity, stops it before the database stage, and leaves the foreign process alive");
Ok(())
}
@@ -0,0 +1,199 @@
use base64::{engine::general_purpose::STANDARD, Engine};
use coa_core::{
backup,
db::Db,
driver::{self, Verb},
fsx,
manifest::{Kind, Migration},
package::{self, BuildOptions},
pkgsource::Source,
registry::MetaDir,
update::{self, RepackEnv},
Result,
};
use ed25519_dalek::{Signer, SigningKey};
use std::{collections::BTreeMap, path::PathBuf};
fn main() -> Result<()> {
let root = PathBuf::from(
std::env::args()
.nth(1)
.expect("qualified disposable fixture"),
);
let sql = std::fs::read(std::env::args().nth(2).expect("corrective SQL"))?;
assert_eq!(
root.file_name().unwrap(),
"coa-schema-fixture-stability-upgrade-76-85-20261030"
);
assert!(root.join(".release-schema-fixture").is_file());
assert!(!root.join("legacy-start-data-e2e-started").exists());
fsx::atomic_write(
&root.join("legacy-start-data-e2e-started"),
b"disposable regression test",
)?;
let result = std::panic::catch_unwind(|| -> Result<()> {
let meta = coa_core::registry::metadata_dir_for(&root)?;
let mut identities = String::new();
let mut custom = String::new();
backup::with_database(&root, |db| {
assert_eq!(
db.query(
"SELECT COUNT(*) FROM acore_world.playercreateinfo WHERE race IN (33,45);"
)?
.trim(),
"0"
);
let base: u32 = db
.query("SELECT MAX(guid)+100 FROM acore_characters.characters;")?
.trim()
.parse()
.unwrap();
clone_character(db, base, 33, 12, "Thinprobe")?;
clone_character(db, base + 1, 45, 30, "Leperprobe")?;
identities = db.query(&format!(
"SELECT * FROM acore_characters.characters WHERE guid IN ({base},{});",
base + 1
))?;
let missing = coa_core::character_start_check::missing(db)?;
assert!(missing
.iter()
.any(|c| c.guid == base && c.race == 33 && c.class == 12));
assert!(missing
.iter()
.any(|c| c.guid == base + 1 && c.race == 45 && c.class == 30));
db.query("INSERT INTO acore_world.playercreateinfo SELECT 33,class,map,zone,position_x+0.125,position_y,position_z,orientation FROM acore_world.playercreateinfo WHERE race=1 AND class=32;")?;
custom =
db.query("SELECT * FROM acore_world.playercreateinfo WHERE race=33 AND class=32;")?;
fsx::atomic_write(
&root.join("legacy-probe-guids.json"),
serde_json::to_string(&[base, base + 1])?.as_bytes(),
)?;
println!("PASS: reproduced missing starting data for existing race 33/class 12 and race 45/class 30 characters");
Ok(())
})?;
let source = root.join("legacy-start-data-source");
let pkg = root.join("legacy-start-data-package");
fsx::atomic_write(
&source.join("Core/legacy-start-data-proof.txt"),
b"corrective migration acceptance",
)?;
fsx::atomic_write(
&source.join("_migrations/world/stabilization_legacy_starts.sql"),
&sql,
)?;
let manifest = package::build(
&source,
&pkg,
&BuildOptions {
kind: Kind::Update,
version: "2.0.0".into(),
core_commit: None,
bots_commit: None,
built_at: "private regression acceptance".into(),
part_size: 1 << 20,
migrations: vec![Migration {
id: "stabilization_legacy_starts".into(),
db: "world".into(),
sha256: fsx::sha256_bytes(&sql),
compatible_sha256: vec![],
destructive: false,
}],
},
&|_| {},
)?;
let key = SigningKey::generate(&mut rand_core::OsRng);
fsx::atomic_write(
&pkg.join("manifest.json.sig"),
STANDARD
.encode(
key.sign(&std::fs::read(pkg.join("manifest.json"))?)
.to_bytes(),
)
.as_bytes(),
)?;
let trusted = STANDARD.encode(key.verifying_key().to_bytes());
let env = RepackEnv {
root: &root,
meta_dir: &meta,
};
let out = update::apply(
&update::Params {
root: &root,
meta_dir: &meta,
source: Source::Dir(pkg),
trusted_key: &trusted,
cancel: Default::default(),
resolutions: BTreeMap::new(),
env: &env,
fail_after_ops: None,
},
&|step, pct| println!("{pct}% {step}"),
)?;
assert_eq!(out.txn.state, update::State::Committed);
assert_eq!(
MetaDir::open(&meta)?.1.core.version.as_deref(),
Some("2.0.0")
);
backup::with_database(&root, |db| {
let guids: Vec<u32> =
serde_json::from_slice(&std::fs::read(root.join("legacy-probe-guids.json"))?)?;
assert_eq!(
db.query(&format!(
"SELECT * FROM acore_characters.characters WHERE guid IN ({},{});",
guids[0], guids[1]
))?,
identities
);
assert!(coa_core::character_start_check::missing(db)?
.iter()
.all(|c| !guids.contains(&c.guid)));
assert_eq!(
db.query("SELECT * FROM acore_world.playercreateinfo WHERE race=33 AND class=32;")?,
custom
);
assert!(coa_core::migrations::status(db, &manifest.migrations)?
.iter()
.all(|m| m.status == coa_core::migrations::Status::Applied));
let before = counts(db)?;
db.query(&format!(
"USE acore_world; {}",
String::from_utf8_lossy(&sql)
))?;
assert_eq!(counts(db)?, before);
assert_eq!(
db.query("SELECT * FROM acore_world.playercreateinfo WHERE race=33 AND class=32;")?,
custom
);
println!("PASS: signed Manager update restored legacy starts, preserved complete character rows and custom starts, and remained idempotent on a second SQL execution");
Ok(())
})?;
Ok(())
});
let stopped = driver::run(&root, Verb::StopAll)?;
assert!(stopped.ok, "{}", stopped.output);
result.map_err(|_| {
coa_core::Error::Invalid("Legacy start regression failed; fixture stopped".into())
})?
}
fn counts(db: &Db) -> Result<String> {
db.query("SELECT COUNT(*) FROM acore_world.playercreateinfo WHERE race IN (33,45); SELECT COUNT(*) FROM acore_world.playercreateinfo_item WHERE race IN (33,45); SELECT COUNT(*) FROM acore_world.playercreateinfo_action WHERE race IN (33,45); SELECT COUNT(*) FROM acore_world.player_race_stats WHERE Race IN (33,45); SELECT COUNT(*) FROM acore_world.ascension_custom_class_race WHERE race IN (33,45);")
}
fn clone_character(db: &Db, guid: u32, race: u32, class: u32, name: &str) -> Result<()> {
let columns = db.query("SHOW COLUMNS FROM acore_characters.characters;")?;
let names: Vec<_> = columns
.lines()
.map(|l| l.split('\t').next().unwrap())
.collect();
let values: Vec<String> = names
.iter()
.map(|c| match *c {
"guid" => guid.to_string(),
"name" => format!("'{name}'"),
"race" => race.to_string(),
"class" => class.to_string(),
"online" | "at_login" => "0".into(),
_ => format!("`{c}`"),
})
.collect();
db.query(&format!("INSERT INTO acore_characters.characters ({}) SELECT {} FROM acore_characters.characters WHERE class={class} LIMIT 1;",names.iter().map(|c|format!("`{c}`")).collect::<Vec<_>>().join(","),values.join(",")))?;
Ok(())
}
+120 -53
View File
@@ -1,57 +1,124 @@
//! Read-only audit, or explicit SQL checks on a disposable database fixture. //! Read-only audit, or explicit SQL checks on a disposable database fixture.
use coa_core::{db::{Account, Db}, migrations::{self, Store}, manifest::Manifest, realms::Mode}; use coa_core::{
db::{Account, Db},
manifest::Manifest,
migrations::{self, Store},
realms::Mode,
};
fn main() -> Result<(), Box<dyn std::error::Error>> { fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().collect(); let args: Vec<_> = std::env::args().collect();
if args.len() < 3 { return Err("usage: migration_plan <root> <signed-manifest> [--apply|--sql-only <migration-directory>]".into()); } if args.len() < 3 {
let root = std::path::Path::new(&args[1]); return Err("usage: migration_plan <root> <signed-manifest> [--apply|--sql-only <migration-directory>]".into());
let bytes = std::fs::read(&args[2])?;
let signature = std::fs::read_to_string(format!("{}.sig",args[2]))?;
coa_core::signing::verify(&bytes, &signature, coa_core::signing::EMBEDDED_PUBLIC_KEY)?;
let manifest = Manifest::parse(&bytes)?;
for (index,mode) in [Mode::Coa, Mode::Wildcard].into_iter().enumerate() {
let db = Db::from_repack(root, Account::Admin)?.for_realm(mode);
let rows = db.load_readonly()?;
let relevant: Vec<_> = rows.iter().filter(|r| r.id == "rev_20260903_01_live_class_baseline").map(|r| format!("{} {:?} {}",r.db,r.status,r.baseline)).collect();
println!("{} baseline history: {:?}",mode.name(),relevant);
let list: Vec<_> = manifest.migrations.iter().filter(|m|index==0 || m.db!="auth").cloned().collect();
let plan = migrations::status(&db,&list)?;
println!("{} pending: {:?}",mode.name(),plan.iter().filter(|m|m.status!=migrations::Status::Applied).map(|m|(&m.db,&m.id,m.status)).collect::<Vec<_>>());
}
if args.get(3).is_some_and(|s| s == "--apply" || s == "--sql-only") {
assert!(root.file_name().unwrap().to_string_lossy().starts_with("update-database-diagnosis-") && root.join(".coa-update-fixture").is_file(), "Only disposable fixture roots may be changed");
if args[3] == "--sql-only" {
let db = Db::from_repack(root, Account::Admin)?.for_realm(Mode::Coa);
let identity = || -> coa_core::Result<String> {
let mut rows = String::new();
for (schema,table,columns) in [("acore_auth","account","id,HEX(username)"),("acore_characters","characters","guid,account,HEX(name)"),("acore_characters_wildcard","characters","guid,account,HEX(name)")] {
rows.push_str(schema);
rows.push_str(&db.query(&format!("SELECT {columns} FROM {schema}.{table} ORDER BY 1;"))?);
} }
Ok(coa_core::fsx::sha256_bytes(rows.as_bytes())) let root = std::path::Path::new(&args[1]);
}; let bytes = std::fs::read(&args[2])?;
let before = identity()?; let signature = std::fs::read_to_string(format!("{}.sig", args[2]))?;
migrations::verify_files(&manifest.migrations,std::path::Path::new(&args[4]))?; coa_core::signing::verify(&bytes, &signature, coa_core::signing::EMBEDDED_PUBLIC_KEY)?;
for (index,mode) in [Mode::Coa,Mode::Wildcard].into_iter().enumerate() { let manifest = Manifest::parse(&bytes)?;
let realm_db = db.clone().for_realm(mode); for (index, mode) in [Mode::Coa, Mode::Wildcard].into_iter().enumerate() {
let list: Vec<_> = manifest.migrations.iter().filter(|m|index==0 || m.db!="auth").cloned().collect(); let db = Db::from_repack(root, Account::Admin)?.for_realm(mode);
let result = migrations::apply_pending(&realm_db,&list,std::path::Path::new(&args[4]),&||Ok("disposable fixture".into()))?; let rows = db.load_readonly()?;
println!("{} SQL result: {}",mode.name(),serde_json::to_string(&result)?); let relevant: Vec<_> = rows
if result.failed.is_some() {return Err("SQL failed; fixture preserved".into());} .iter()
} .filter(|r| r.id == "rev_20260903_01_live_class_baseline")
assert_eq!(before,identity()?,"Account or character identity changed"); .map(|r| format!("{} {:?} {}", r.db, r.status, r.baseline))
println!("Account and character identities preserved: {}",before); .collect();
let capture = root.join("captured-schema"); println!("{} baseline history: {:?}", mode.name(), relevant);
coa_core::schema_check::capture(&db,&capture)?; let list: Vec<_> = manifest
println!("Captured schema SHA256: {}",coa_core::fsx::sha256_file(&capture.join(coa_core::schema_check::CONTRACT))?); .migrations
return Ok(()); .iter()
} .filter(|m| index == 0 || m.db != "auth")
if args.len() != 5 { return Err("Migration directory required".into()); } .cloned()
use coa_core::update::{Env, RepackEnv}; .collect();
let meta = coa_core::registry::metadata_dir_for(root)?; let plan = migrations::status(&db, &list)?;
let env = RepackEnv { root, meta_dir: &meta }; println!(
let result = env.migrate(&manifest, std::path::Path::new(&args[4])); "{} pending: {:?}",
let _ = coa_core::driver::run(root, coa_core::driver::Verb::StopAll); mode.name(),
println!("Application result: {}",serde_json::to_string(&result?)?); plan.iter()
} .filter(|m| m.status != migrations::Status::Applied)
Ok(()) .map(|m| (&m.db, &m.id, m.status))
.collect::<Vec<_>>()
);
}
if args
.get(3)
.is_some_and(|s| s == "--apply" || s == "--sql-only")
{
assert!(
root.file_name()
.unwrap()
.to_string_lossy()
.starts_with("update-database-diagnosis-")
&& root.join(".coa-update-fixture").is_file(),
"Only disposable fixture roots may be changed"
);
if args[3] == "--sql-only" {
let db = Db::from_repack(root, Account::Admin)?.for_realm(Mode::Coa);
let identity = || -> coa_core::Result<String> {
let mut rows = String::new();
for (schema, table, columns) in [
("acore_auth", "account", "id,HEX(username)"),
("acore_characters", "characters", "guid,account,HEX(name)"),
(
"acore_characters_wildcard",
"characters",
"guid,account,HEX(name)",
),
] {
rows.push_str(schema);
rows.push_str(&db.query(&format!(
"SELECT {columns} FROM {schema}.{table} ORDER BY 1;"
))?);
}
Ok(coa_core::fsx::sha256_bytes(rows.as_bytes()))
};
let before = identity()?;
migrations::verify_files(&manifest.migrations, std::path::Path::new(&args[4]))?;
for (index, mode) in [Mode::Coa, Mode::Wildcard].into_iter().enumerate() {
let realm_db = db.clone().for_realm(mode);
let list: Vec<_> = manifest
.migrations
.iter()
.filter(|m| index == 0 || m.db != "auth")
.cloned()
.collect();
let result = migrations::apply_pending(
&realm_db,
&list,
std::path::Path::new(&args[4]),
&|| Ok("disposable fixture".into()),
)?;
println!(
"{} SQL result: {}",
mode.name(),
serde_json::to_string(&result)?
);
if result.failed.is_some() {
return Err("SQL failed; fixture preserved".into());
}
}
assert_eq!(before, identity()?, "Account or character identity changed");
println!("Account and character identities preserved: {}", before);
let capture = root.join("captured-schema");
coa_core::schema_check::capture(&db, &capture)?;
println!(
"Captured schema SHA256: {}",
coa_core::fsx::sha256_file(&capture.join(coa_core::schema_check::CONTRACT))?
);
return Ok(());
}
if args.len() != 5 {
return Err("Migration directory required".into());
}
use coa_core::update::{Env, RepackEnv};
let meta = coa_core::registry::metadata_dir_for(root)?;
let env = RepackEnv {
root,
meta_dir: &meta,
};
let result = env.migrate(&manifest, std::path::Path::new(&args[4]));
let _ = coa_core::driver::run(root, coa_core::driver::Verb::StopAll);
println!("Application result: {}", serde_json::to_string(&result?)?);
}
Ok(())
} }
+3 -3
View File
@@ -457,7 +457,7 @@ fn run() -> Result<(), String> {
} }
("collection-states", [out]) => { ("collection-states", [out]) => {
let states = OwnerService::new(&mut store) let states = OwnerService::new(&mut store)
.collection_states() .collection_states(coa_core::portable::Ruleset::Coa)
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
for s in &states { for s in &states {
println!( println!(
@@ -618,7 +618,7 @@ fn run() -> Result<(), String> {
let set = let set =
coa_core::portable::collection::IdSet::from_ids(ids).map_err(|e| e.to_string())?; coa_core::portable::collection::IdSet::from_ids(ids).map_err(|e| e.to_string())?;
let merge = store let merge = store
.merge_collection(profile, kind, &set) .merge_collection(profile, coa_core::portable::Ruleset::Coa, kind, &set)
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
println!( println!(
"{kind}: {} id(s) added{}", "{kind}: {} id(s) added{}",
@@ -633,7 +633,7 @@ fn run() -> Result<(), String> {
let profile = store.default_profile().map_err(|e| e.to_string())?; let profile = store.default_profile().map_err(|e| e.to_string())?;
for kind in coa_core::portable::session::protocol::COLLECTION_KINDS { for kind in coa_core::portable::session::protocol::COLLECTION_KINDS {
match store match store
.collection_info(profile, kind) .collection_info(profile, coa_core::portable::Ruleset::Coa, kind)
.map_err(|e| e.to_string())? .map_err(|e| e.to_string())?
{ {
Some(i) => println!( Some(i) => println!(
@@ -0,0 +1,8 @@
use coa_core::{backup, schema_check, Result};
fn main()->Result<()> {
let root=std::path::PathBuf::from(std::env::args().nth(1).unwrap());
let contract=std::path::PathBuf::from(std::env::args().nth(2).unwrap());
assert!(root.join("recovery-e2e-started").is_file());
assert!(contract.join(".release-schema-fixture").is_file());
backup::with_database(&root,|db| {for p in schema_check::check(db,&contract)? {println!("{}.{}.{}: {}",p.database,p.table,p.column,p.detail);} Ok(())})
}
@@ -0,0 +1,132 @@
use base64::{engine::general_purpose::STANDARD, Engine};
use coa_core::{
backup,
driver::{self, Verb},
fsx,
manifest::{Kind, Migration},
package::{self, BuildOptions},
pkgsource::Source,
update::{self, RepackEnv},
Result,
};
use ed25519_dalek::{Signer, SigningKey};
use std::{collections::BTreeMap, path::PathBuf};
fn main() -> Result<()> {
let root = PathBuf::from(std::env::args().nth(1).unwrap());
let core = PathBuf::from(std::env::args().nth(2).unwrap());
let release = PathBuf::from(std::env::args().nth(3).unwrap());
assert!(root.join("recovery-e2e-started").is_file());
let result = std::panic::catch_unwind(|| -> Result<()> {
let meta = coa_core::registry::metadata_dir_for(&root)?;
let source = root.join("schema-sync-source-v2");
let pkg = root.join("schema-sync-package-v2");
assert!(!pkg.exists());
fsx::atomic_write(
&source.join("Core/schema-sync-proof.txt"),
b"official schema migration acceptance",
)?;
let published =
coa_core::manifest::Manifest::parse(&std::fs::read(release.join("manifest.json"))?)?;
let contract_path = PathBuf::from("C:/games/source/coa-schema-fixture-stability-upgrade-76-85-20261030/Scripts/database-schema.json");
let contract = std::fs::read(contract_path)?;
let expected = published
.files
.iter()
.find(|f| f.path == "Scripts/database-schema.json")
.unwrap();
assert_eq!(fsx::sha256_bytes(&contract), expected.sha256);
fsx::atomic_write(&source.join("Scripts/database-schema.json"), &contract)?;
let mut migrations: Vec<Migration> = Vec::new();
for id in [
"rev_1793212891571528600",
"rev_20261027_18_coa_strange_piece_of_scrap_faction_diamond",
] {
let m = published
.migrations
.iter()
.find(|m| m.id == id)
.unwrap()
.clone();
let sql = std::fs::read(
core.join(format!("data/sql/updates/pending_db_{}/{}.sql", m.db, m.id)),
)?;
assert_eq!(fsx::sha256_bytes(&sql), m.sha256);
fsx::atomic_write(
&source.join(format!("_migrations/{}/{}.sql", m.db, m.id)),
&sql,
)?;
migrations.push(m);
}
package::build(
&source,
&pkg,
&BuildOptions {
kind: Kind::Update,
version: "3.0.0".into(),
core_commit: None,
bots_commit: None,
built_at: "private native fixture schema sync".into(),
part_size: 1 << 20,
migrations,
},
&|_| {},
)?;
let key = SigningKey::generate(&mut rand_core::OsRng);
fsx::atomic_write(
&pkg.join("manifest.json.sig"),
STANDARD
.encode(
key.sign(&std::fs::read(pkg.join("manifest.json"))?)
.to_bytes(),
)
.as_bytes(),
)?;
let trusted = STANDARD.encode(key.verifying_key().to_bytes());
let env = RepackEnv {
root: &root,
meta_dir: &meta,
};
let out = update::apply(
&update::Params {
root: &root,
meta_dir: &meta,
source: Source::Dir(pkg),
trusted_key: &trusted,
cancel: Default::default(),
resolutions: BTreeMap::from([(
"Scripts/database-schema.json".into(),
update::Resolution::Replace,
)]),
env: &env,
fail_after_ops: None,
},
&|step, pct| println!("{pct}% {step}"),
)?;
assert_eq!(out.txn.state, update::State::Committed);
backup::with_database(&root, |db| {
assert_eq!(
db.query("SELECT name,at_login FROM acore_characters.characters WHERE guid=3030;")?
.trim(),
"Christian Shadowheart\t1"
);
assert_eq!(
db.query("SELECT id FROM acore_characters.manager_recovery_probe;")?
.trim(),
"42"
);
assert_eq!(
db.query("SELECT id FROM acore_world.manager_recovery_probe;")?
.trim(),
"44"
);
Ok(())
})?;
println!("PASS: the exact two published migrations brought the old fixture schema forward through the Manager updater while preserving the rejected companion and recovery probes");
Ok(())
});
let stop = driver::run(&root, Verb::StopAll)?;
assert!(stop.ok, "{}", stop.output);
result.map_err(|_| {
coa_core::Error::Invalid("Schema sync acceptance failed; fixture stopped".into())
})?
}
@@ -0,0 +1,166 @@
use base64::{engine::general_purpose::STANDARD, Engine};
use coa_core::{
backup, driver, fsx,
manifest::{Kind, Migration},
package::{self, BuildOptions},
pkgsource::Source,
registry::MetaDir,
update::{self, RepackEnv},
Result,
};
use ed25519_dalek::{Signer, SigningKey};
use std::{collections::BTreeMap, path::PathBuf};
fn main() -> Result<()> {
let root = PathBuf::from(
std::env::args()
.nth(1)
.expect("disposable recovery fixture"),
);
assert!(root
.file_name()
.unwrap()
.to_string_lossy()
.starts_with("coa-update-recovery-fixture-"));
assert!(root.join("recovery-e2e-started").is_file());
let cycles_only = std::env::args().nth(2).as_deref() == Some("--cycles-only");
if !cycles_only {
assert!(!root.join("success-e2e-started").exists());
fsx::atomic_write(
&root.join("success-e2e-started"),
b"disposable success acceptance",
)?;
}
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
if cycles_only {
restart_cycles(&root)
} else {
exercise(&root)
}
}));
assert!(
driver::run(&root, driver::Verb::StopAll)?.ok,
"fixture shutdown"
);
result.map_err(|_| {
coa_core::Error::Invalid(
"Success acceptance assertion failed; fixture services stopped".into(),
)
})?
}
fn exercise(root: &std::path::Path) -> Result<()> {
let meta = coa_core::registry::metadata_dir_for(root)?;
assert!(update::unfinished(&meta).is_none());
assert!(driver::run(root, driver::Verb::StopAll)?.ok);
let source = root.join("success-source");
let pkg = root.join("success-package");
fsx::atomic_write(
&source.join("Core/stabilization-success.txt"),
b"verified update",
)?;
let sql = b"UPDATE manager_recovery_probe SET id=44 WHERE id=43;";
fsx::atomic_write(
&source.join("_migrations/world/stabilization_success.sql"),
sql,
)?;
let manifest = package::build(
&source,
&pkg,
&BuildOptions {
kind: Kind::Update,
version: "2.0.0".into(),
core_commit: None,
bots_commit: None,
built_at: "disposable acceptance".into(),
part_size: 1 << 20,
migrations: vec![Migration {
id: "stabilization_success".into(),
db: "world".into(),
sha256: fsx::sha256_bytes(sql),
compatible_sha256: vec![],
destructive: false,
}],
},
&|_| {},
)?;
let key = SigningKey::generate(&mut rand_core::OsRng);
fsx::atomic_write(
&pkg.join("manifest.json.sig"),
STANDARD
.encode(
key.sign(&std::fs::read(pkg.join("manifest.json"))?)
.to_bytes(),
)
.as_bytes(),
)?;
let trusted = STANDARD.encode(key.verifying_key().to_bytes());
let env = RepackEnv {
root,
meta_dir: &meta,
};
let outcome = update::apply(
&update::Params {
root,
meta_dir: &meta,
source: Source::Dir(pkg),
trusted_key: &trusted,
cancel: Default::default(),
resolutions: BTreeMap::new(),
env: &env,
fail_after_ops: None,
},
&|step, pct| println!("{pct}% {step}"),
)?;
assert_eq!(outcome.txn.state, update::State::Committed);
assert_eq!(
MetaDir::open(&meta)?.1.core.version.as_deref(),
Some("2.0.0")
);
assert!(update::unfinished(&meta).is_none());
assert_eq!(
std::fs::read(root.join("Core/stabilization-success.txt"))?,
b"verified update"
);
backup::with_database(root, |db| {
assert_eq!(
db.query("SELECT id FROM acore_characters.manager_recovery_probe;")?,
"42"
);
assert_eq!(
db.query("SELECT id FROM acore_characters.manager_recovery_view;")?,
"42"
);
assert_eq!(
db.query("SELECT id FROM acore_world.manager_recovery_probe;")?,
"44"
);
assert!(coa_core::migrations::status(db, &manifest.migrations)?
.iter()
.all(|m| m.status == coa_core::migrations::Status::Applied));
Ok(())
})?;
restart_cycles(root)?;
println!("PASS: signed update committed after failed rehearsal and recovery; SQL, files, metadata and player data verified; two native restart cycles passed");
Ok(())
}
fn restart_cycles(root: &std::path::Path) -> Result<()> {
for cycle in 0..2 {
let stopped = driver::run(root, driver::Verb::StopAll)?;
assert!(
stopped.ok,
"Stop cycle {cycle}: {}",
coa_core::diag::redact(&stopped.output)
);
let started = driver::run(root, driver::Verb::StartAll)?;
assert!(started.ok, "{}", started.output);
let pop = coa_core::population::query(root)?;
println!(
"Restart cycle {cycle}: world ready, players={}, bots={}",
pop.players_online, pop.bots_online
);
}
println!("PASS: two native restart cycles finished");
Ok(())
}
+32 -11
View File
@@ -30,15 +30,27 @@ fn main() -> Result<()> {
.unwrap() .unwrap()
.to_string_lossy() .to_string_lossy()
.starts_with("coa-update-recovery-fixture-")); .starts_with("coa-update-recovery-fixture-"));
assert!( let resume = std::env::args().nth(2).as_deref() == Some("--verify-recovered");
!root.join("recovery-e2e-started").exists(), let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
"Use a new fixture; never reuse an owned server" if resume {
); assert!(root.join("recovery-e2e-started").is_file());
fsx::atomic_write(&root.join("recovery-e2e-started"), b"disposable fixture")?; let manifest = coa_core::manifest::Manifest::parse(&std::fs::read(
let result = exercise(&root); root.join("fixture-package/manifest.json"),
let stopped = driver::run(&root, Verb::StopAll)?; )?)?;
assert!(stopped.ok); verify_recovered(&root, &manifest)
result } else {
assert!(
!root.join("recovery-e2e-started").exists(),
"Use a new fixture"
);
fsx::atomic_write(&root.join("recovery-e2e-started"), b"disposable fixture")?;
exercise(&root)
}
}));
assert!(driver::run(&root, Verb::StopAll)?.ok);
result.map_err(|_| {
Error::Invalid("Recovery acceptance assertion failed; owned services were stopped".into())
})?
} }
fn exercise(root: &Path) -> Result<()> { fn exercise(root: &Path) -> Result<()> {
@@ -122,9 +134,18 @@ fn exercise(root: &Path) -> Result<()> {
assert!( assert!(
error error
.to_string() .to_string()
.contains("private update rehearsal failed"), .contains("files and databases were restored to the recovery point"),
"{error}" "{error}"
); );
verify_recovered(root, &manifest)
}
fn verify_recovered(root: &Path, manifest: &coa_core::manifest::Manifest) -> Result<()> {
let meta = coa_core::registry::metadata_dir_for(root)?;
let env = RepackEnv {
root,
meta_dir: &meta,
};
assert!(!root.join("Core/recovery-probe.txt").exists()); assert!(!root.join("Core/recovery-probe.txt").exists());
assert!(update::unfinished(&meta).is_none()); assert!(update::unfinished(&meta).is_none());
assert_eq!( assert_eq!(
@@ -168,6 +189,6 @@ fn exercise(root: &Path) -> Result<()> {
Db::from_repack(root, Account::Admin)?.realm(), Db::from_repack(root, Account::Admin)?.realm(),
coa_core::realms::Mode::Coa coa_core::realms::Mode::Coa
); );
println!("PASS: private rehearsal caught failed SQL before changing the installed world, characters, ledger, objects, files or version; complete recovery succeeded"); println!("PASS: failed SQL was rolled back; characters, world, ledger, views, triggers, routines, files and version were verified; the saved recovery point was restored again");
Ok(()) Ok(())
} }
+60 -26
View File
@@ -1,28 +1,62 @@
//! Exercise the production updater only on a disposable copy of an installed server. //! Exercise the production updater only on a disposable copy of an installed server.
use coa_core::{registry::MetaDir, update::{self, Env, RepackEnv}}; use coa_core::{
fn main() -> Result<(),Box<dyn std::error::Error>> { registry::MetaDir,
let args:Vec<_>=std::env::args().collect(); update::{self, Env, RepackEnv},
if args.len()!=3 && args.len()!=4 {return Err("usage: upgrade_fixture <disposable-root> <signed-package-directory>".into());} };
let root=std::path::Path::new(&args[1]); fn main() -> Result<(), Box<dyn std::error::Error>> {
assert!(root.file_name().unwrap().to_string_lossy().starts_with("coa-schema-fixture-real") && root.join(".coa-update-fixture").is_file(),"Disposable fixture required"); let args: Vec<_> = std::env::args().collect();
let meta=coa_core::registry::metadata_dir_for(root)?; if args.len() != 3 && args.len() != 4 {
let (_,installed)=MetaDir::open(&meta)?; return Err("usage: upgrade_fixture <disposable-root> <signed-package-directory>".into());
assert_eq!(coa_core::fsx::canonicalize_lenient(std::path::Path::new(&installed.server_path))?,coa_core::fsx::canonicalize_lenient(root)?,"Fixture metadata must point to the copy"); }
assert!(installed.client_path.is_none(),"Detach the real client from fixture metadata"); let root = std::path::Path::new(&args[1]);
let env=RepackEnv{root,meta_dir:&meta}; assert!(
if args.get(3).is_some_and(|flag|flag=="--validate-only") { root.file_name()
let result=env.validate(); .unwrap()
let _=coa_core::driver::run(root,coa_core::driver::Verb::StopAll); .to_string_lossy()
result?; .starts_with("coa-schema-fixture-real")
println!("Startup and identity validation passed"); && root.join(".coa-update-fixture").is_file(),
return Ok(()); "Disposable fixture required"
} );
let outcome=update::apply(&update::Params{root,meta_dir:&meta,source:coa_core::pkgsource::Source::Dir(args[2].clone().into()),trusted_key:coa_core::signing::EMBEDDED_PUBLIC_KEY,cancel:Default::default(),resolutions:Default::default(),env:&env,fail_after_ops:None},&|phase,percent|println!("{percent}% {phase}")); let meta = coa_core::registry::metadata_dir_for(root)?;
let stopped=coa_core::driver::run(root,coa_core::driver::Verb::StopAll); let (_, installed) = MetaDir::open(&meta)?;
println!("Shutdown after test: {:?}",stopped.map(|r|r.ok)); assert_eq!(
let outcome=outcome?; coa_core::fsx::canonicalize_lenient(std::path::Path::new(&installed.server_path))?,
println!("Final transaction: {:?}",outcome.txn.state); coa_core::fsx::canonicalize_lenient(root)?,
env.ensure_stopped()?; "Fixture metadata must point to the copy"
assert_eq!(outcome.txn.state,update::State::Committed); );
Ok(()) assert!(
installed.client_path.is_none(),
"Detach the real client from fixture metadata"
);
let env = RepackEnv {
root,
meta_dir: &meta,
};
if args.get(3).is_some_and(|flag| flag == "--validate-only") {
let result = env.validate();
let _ = coa_core::driver::run(root, coa_core::driver::Verb::StopAll);
result?;
println!("Startup and identity validation passed");
return Ok(());
}
let outcome = update::apply(
&update::Params {
root,
meta_dir: &meta,
source: coa_core::pkgsource::Source::Dir(args[2].clone().into()),
trusted_key: coa_core::signing::EMBEDDED_PUBLIC_KEY,
cancel: Default::default(),
resolutions: Default::default(),
env: &env,
fail_after_ops: None,
},
&|phase, percent| println!("{percent}% {phase}"),
);
let stopped = coa_core::driver::run(root, coa_core::driver::Verb::StopAll);
println!("Shutdown after test: {:?}", stopped.map(|r| r.ok));
let outcome = outcome?;
println!("Final transaction: {:?}", outcome.txn.state);
env.ensure_stopped()?;
assert_eq!(outcome.txn.state, update::State::Committed);
Ok(())
} }
+67
View File
@@ -80,6 +80,60 @@ fn upper(name: &str) -> Result<String> {
Ok(name.to_ascii_uppercase()) Ok(name.to_ascii_uppercase())
} }
pub fn create(root: &Path, name: &str, password: &str, administrator: bool) -> Result<()> {
validate_account(name, password)?;
let name = name.to_ascii_uppercase();
let db = Db::from_repack(root, Account::Admin)?;
if db
.query(&format!(
"SELECT COUNT(*) FROM acore_auth.account WHERE username='{name}';"
))?
.trim()
!= "0"
{
return Err(Error::Invalid("That account name is already taken.".into()));
}
let mut ra = Ra::connect(root)?;
ra.performance().map_err(|error| Error::Invalid(format!("The server console is not ready for account creation. No create command was sent. {error}")))?;
let confirmed = ra.create_account(&name, password);
if let Err(error) = confirmed {
let stored = db.query(&format!(
"SELECT HEX(salt), HEX(verifier) FROM acore_auth.account WHERE username='{name}';"
))?;
if !matches_credentials(&stored, &name, password) {
return Err(Error::Invalid(format!("Account creation was not confirmed. Refresh the account list before retrying. {error}")));
}
if administrator {
ra = Ra::connect(root).map_err(|error| Error::Invalid(format!("The account was created, but administrator access was not confirmed. Refresh the account list and check its access level. {error}")))?;
}
}
if administrator {
if let Err(error) = ra.make_administrator(&name) {
let access = db.query(&format!("SELECT COUNT(*) FROM acore_auth.account_access WHERE id=(SELECT id FROM acore_auth.account WHERE username='{name}') AND gmlevel=3 AND RealmID=-1;"))?;
if access.trim() != "1" {
return Err(Error::Invalid(format!("The account was created, but administrator access was not confirmed. Refresh the account list and check its access level. {error}")));
}
}
}
Ok(())
}
fn matches_credentials(stored: &str, name: &str, password: &str) -> bool {
let Some((salt, verifier)) = stored.trim().split_once('\t') else {
return false;
};
let Ok(salt) = hex::decode(salt) else {
return false;
};
let Ok(salt): std::result::Result<[u8; 32], _> = salt.try_into() else {
return false;
};
let Ok(verifier) = hex::decode(verifier) else {
return false;
};
verifier.as_slice() == crate::srp6::verifier(name, password, &salt)
}
/// Give the account a new name. Needs the world console (the new password is what makes the login work again) and an /// Give the account a new name. Needs the world console (the new password is what makes the login work again) and an
/// account that is not logged in. The old name is put back if anything goes wrong. /// account that is not logged in. The old name is put back if anything goes wrong.
pub fn rename(root: &Path, ra: &mut Ra, old: &str, new: &str, password: &str) -> Result<()> { pub fn rename(root: &Path, ra: &mut Ra, old: &str, new: &str, password: &str) -> Result<()> {
@@ -165,6 +219,19 @@ pub fn delete(root: &Path, ra: &mut Ra, name: &str) -> Result<()> {
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn lost_reply_requires_the_exact_requested_credentials() {
let salt = [42; 32];
let verifier = crate::srp6::verifier("NewPlayer", "Password77", &salt);
let stored = format!("{}\t{}\n", hex::encode(salt), hex::encode(verifier));
assert!(matches_credentials(&stored, "NEWPLAYER", "password77"));
assert!(!matches_credentials(&stored, "NEWPLAYER", "wrongpass"));
assert!(!matches_credentials(&stored, "OTHERPLAYER", "Password77"));
for value in ["", "NULL\tNULL", "00\t00", "malformed"] {
assert!(!matches_credentials(value, "NewPlayer", "Password77"));
}
}
#[test] #[test]
fn rows_from_the_client_become_accounts() { fn rows_from_the_client_become_accounts() {
let out = "2\tALICE\t3\t0\t2026-09-30 21:04:11\t4\n5\tBOB\t0\t1\t\t0\n7\tBROKEN\n"; let out = "2\tALICE\t3\t0\t2026-09-30 21:04:11\t4\n5\tBOB\t0\t1\t\t0\n7\tBROKEN\n";
+220 -48
View File
@@ -1,5 +1,5 @@
//! Every setting of the world server's configuration, for people who want more than the curated list: the documented //! Every setting of the world server's configuration, for people who want more than the curated list: the documented
//! settings come from `worldserver.conf.dist` (the file that ships with the server and explains each one), the current //! settings come from `worldserver.conf.dist` and `modules/coa.conf.dist`, the current
//! values from the configuration the next start will use. Anything that holds a password, a port, an address, a folder or //! values from the configuration the next start will use. Anything that holds a password, a port, an address, a folder or
//! the database connection is left out; the Manager owns those. //! the database connection is left out; the Manager owns those.
@@ -10,7 +10,7 @@ use std::path::Path;
use serde::Serialize; use serde::Serialize;
use crate::config::parser::ConfFile; use crate::config::parser::ConfFile;
use crate::config::{take_snapshot, targets, Scope}; use crate::config::{take_snapshot, targets, Scope, Targets};
use crate::error::{Error, Result}; use crate::error::{Error, Result};
use crate::fsx; use crate::fsx;
@@ -39,6 +39,14 @@ fn hidden(key: &str) -> bool {
|| k.starts_with("logindatabase.") || k.starts_with("logindatabase.")
|| k.starts_with("worlddatabase.") || k.starts_with("worlddatabase.")
|| k.starts_with("characterdatabase.") || k.starts_with("characterdatabase.")
|| [
"coa.classmodel",
"coa.realmtype",
"coa.gamemodemask",
"coa.mapclass10towarrior",
"coa.clientbooleanconfigs",
]
.contains(&k.as_str())
|| [ || [
"bindip", "bindip",
"realmid", "realmid",
@@ -121,52 +129,85 @@ fn dist_path(root: &Path) -> std::path::PathBuf {
root.join("Core/configs/worldserver.conf.dist") root.join("Core/configs/worldserver.conf.dist")
} }
fn sources(root: &Path) -> Result<Vec<(std::path::PathBuf, Targets)>> {
let mut result = vec![(dist_path(root), targets(root, Scope::Server)?)];
let dist = root.join("Core/configs/modules/coa.conf.dist");
if dist.is_file() {
let active = root.join("Core/configs/modules/coa.conf");
result.push((
dist,
Targets {
read: active.clone(),
writes: vec![active],
generated: None,
},
));
}
Ok(result)
}
pub fn list(root: &Path) -> Result<Vec<Item>> { pub fn list(root: &Path) -> Result<Vec<Item>> {
let dist = fs::read_to_string(dist_path(root)).map_err(|_| { let mut items = Vec::new();
Error::Invalid( for (dist_path, t) in sources(root)? {
"The documented settings file (worldserver.conf.dist) was not found on this server." let dist = fs::read_to_string(&dist_path)?;
.into(), let active = ConfFile::parse_bytes(&if t.read.exists() {
) fs::read(&t.read)?
})?; } else {
let t = targets(root, Scope::Server)?; dist.as_bytes().to_vec()
let active = ConfFile::parse_bytes(&fs::read(&t.read)?)?; })?;
Ok(parse_dist(&dist) items.extend(
.into_iter() parse_dist(&dist)
.filter(|(k, _, _)| !hidden(k)) .into_iter()
.map(|(key, default, doc)| { .filter(|(k, _, _)| !hidden(k))
let value = active .map(|(key, default, doc)| {
.get(&key) let value = active
.map(|v| v.trim().to_string()) .get(&key)
.unwrap_or_else(|| default.clone()); .map(|v| v.trim().to_string())
let changed = value != default; .unwrap_or_else(|| default.clone());
Item { let changed = value != default;
key, Item {
value, key,
default, value,
doc, default,
changed, doc,
} changed,
}) }
.collect()) })
.collect::<Vec<_>>(),
);
}
Ok(items)
} }
/// Change settings that exist in the documented file. A value is one line of at most 500 characters. Returns the keys /// Change settings that exist in the documented file. A value is one line of at most 500 characters. Returns the keys
/// that actually changed; the previous files are snapshotted first (and can be restored from Settings). /// that actually changed; the previous files are snapshotted first (and can be restored from Settings).
pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Result<Vec<String>> { pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Result<Vec<String>> {
let known: BTreeMap<String, String> = let _lock = crate::update::operation_lock(meta)?;
parse_dist(&fs::read_to_string(dist_path(root)).map_err(|_| { crate::update::ensure_recovered(meta)?;
Error::Invalid("worldserver.conf.dist was not found on this server.".into()) let sources = sources(root)?;
})?) let mut known = BTreeMap::new();
.into_iter()
.map(|(k, d, _)| (k, d))
.collect();
let t = targets(root, Scope::Server)?;
let mut originals: Vec<(std::path::PathBuf, Vec<u8>)> = Vec::new(); let mut originals: Vec<(std::path::PathBuf, Vec<u8>)> = Vec::new();
let mut confs: Vec<ConfFile> = Vec::new(); let mut confs: Vec<ConfFile> = Vec::new();
for p in &t.writes { let mut owners = Vec::new();
let bytes = fs::read(p)?; for (index, (dist, t)) in sources.iter().enumerate() {
confs.push(ConfFile::parse_bytes(&bytes)?); let defaults = fs::read(dist)?;
originals.push((p.clone(), bytes)); for (key, default, _) in parse_dist(&String::from_utf8_lossy(&defaults)) {
if known.insert(key.clone(), (default, index)).is_some() {
return Err(Error::Invalid(format!(
"{key} is documented in more than one configuration file."
)));
}
}
for p in &t.writes {
let bytes = if p.exists() {
fs::read(p)?
} else {
defaults.clone()
};
confs.push(ConfFile::parse_bytes(&bytes)?);
originals.push((p.clone(), bytes));
owners.push(index);
}
} }
let mut changed = Vec::new(); let mut changed = Vec::new();
for (key, value) in changes { for (key, value) in changes {
@@ -181,10 +222,22 @@ pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Res
"The value of {key} must be one line of text." "The value of {key} must be one line of text."
))); )));
} }
let same = confs.iter().all(|c| match c.get(key) { let (default, owner) = &known[key];
Some(v) => v.trim() == value, if default.parse::<f64>().is_ok() && !value.parse::<f64>().is_ok_and(f64::is_finite)
None => known[key] == value, || key == "CoA.LegacyMountFlight" && !matches!(value, "0" | "1")
}); {
return Err(Error::Invalid(format!(
"The value of {key} must be a number matching its documented default."
)));
}
let same = confs
.iter()
.zip(&owners)
.filter(|(_, index)| *index == owner)
.all(|(c, _)| match c.get(key) {
Some(v) => v.trim() == value,
None => default == value,
});
if !same { if !same {
changed.push((key.clone(), value.to_string())); changed.push((key.clone(), value.to_string()));
} }
@@ -192,20 +245,31 @@ pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Res
if changed.is_empty() { if changed.is_empty() {
return Ok(Vec::new()); return Ok(Vec::new());
} }
for c in &mut confs { for (c, owner) in confs.iter_mut().zip(&owners) {
for (k, v) in &changed { for (k, v) in &changed {
c.set(k, v, &["Added by CoA Server Manager"]); if known[k].1 == *owner {
c.set(k, v, &["Added by CoA Server Manager"]);
}
} }
} }
let texts: Vec<String> = confs.iter().map(ConfFile::to_text).collect(); let texts: Vec<String> = confs.iter().map(ConfFile::to_text).collect();
for text in &texts { for (text, owner) in texts.iter().zip(&owners) {
let reread = ConfFile::parse(text); let reread = ConfFile::parse(text);
for (k, v) in &changed { for (k, v) in &changed {
if reread.get(k).map(str::trim) != Some(v.as_str()) { if known[k].1 == *owner && reread.get(k).map(str::trim) != Some(v.as_str()) {
return Err(Error::Invalid(format!("internal check failed for {k}"))); return Err(Error::Invalid(format!("internal check failed for {k}")));
} }
} }
} }
let affected: std::collections::BTreeSet<_> =
changed.iter().map(|(key, _)| known[key].1).collect();
let (originals, texts): (Vec<_>, Vec<_>) = originals
.into_iter()
.zip(texts)
.zip(owners)
.filter(|(_, owner)| affected.contains(owner))
.map(|(pair, _)| pair)
.unzip();
take_snapshot( take_snapshot(
meta, meta,
Scope::Server, Scope::Server,
@@ -232,6 +296,114 @@ pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Res
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn unrelated_saves_do_not_create_coa_files_and_existing_realm_values_are_preserved() {
let d = tempfile::tempdir().unwrap();
let (root, meta) = server(d.path());
let module = root.join("Core/configs/modules");
fs::create_dir_all(&module).unwrap();
fs::write(
module.join("coa.conf.dist"),
"CoA.LegacyMountFlight = 0\nCoA.ClassModel = \"coa\"\n",
)
.unwrap();
save(
&root,
&meta,
&BTreeMap::from([("Rate.Drop.Item.Rare".into(), "1.5".into())]),
)
.unwrap();
assert!(!module.join("coa.conf").exists());
fs::write(
module.join("coa.conf"),
"# Reborn realm\nCoA.ClassModel = \"wcr\"\nCustom.Preserved = 42\n",
)
.unwrap();
assert!(save(
&root,
&meta,
&BTreeMap::from([("CoA.ClassModel".into(), "\"coa\"".into())])
)
.is_err());
save(
&root,
&meta,
&BTreeMap::from([("CoA.LegacyMountFlight".into(), "1".into())]),
)
.unwrap();
let actual = fs::read_to_string(module.join("coa.conf")).unwrap();
assert!(
actual.contains("CoA.ClassModel = \"wcr\"") && actual.contains("Custom.Preserved = 42")
);
assert!(actual.contains("# Reborn realm"));
}
#[test]
fn coa_settings_are_found_saved_to_the_module_and_snapshotted_without_profile_overrides() {
let d = tempfile::tempdir().unwrap();
let (root, meta) = server(d.path());
let module = root.join("Core/configs/modules");
fs::create_dir_all(&module).unwrap();
let defaults = "[worldserver]\n# Mount flight rules\nCoA.LegacyMountFlight = 0\nCoA.ClassModel = \"coa\"\nCoA.RealmType = \"live\"\n";
fs::write(module.join("coa.conf.dist"), defaults).unwrap();
let original_world = fs::read(root.join("Core/configs/worldserver.conf")).unwrap();
let items = list(&root).unwrap();
assert!(items
.iter()
.any(|i| i.key == "CoA.LegacyMountFlight" && i.value == "0"));
assert!(!items
.iter()
.any(|i| i.key == "CoA.ClassModel" || i.key == "CoA.RealmType"));
for value in ["2", "invalid", "1\nInjected = 1"] {
assert!(save(
&root,
&meta,
&BTreeMap::from([("CoA.LegacyMountFlight".into(), value.into())])
)
.is_err());
}
assert!(!module.join("coa.conf").exists());
save(
&root,
&meta,
&BTreeMap::from([
("CoA.LegacyMountFlight".into(), "1".into()),
("Rate.Drop.Item.Rare".into(), "1.5".into()),
]),
)
.unwrap();
assert!(fs::read_to_string(module.join("coa.conf"))
.unwrap()
.contains("CoA.LegacyMountFlight = 1"));
let world = fs::read_to_string(root.join("Core/configs/worldserver.conf")).unwrap();
assert!(!world.contains("CoA.LegacyMountFlight"));
assert!(world.contains("Rate.Drop.Item.Rare = 1.5"));
assert!(!String::from_utf8(original_world)
.unwrap()
.contains("CoA.LegacyMountFlight"));
assert_eq!(
list(&root)
.unwrap()
.iter()
.find(|i| i.key == "CoA.LegacyMountFlight")
.unwrap()
.value,
"1"
);
assert!(!crate::config::list_snapshots(&meta).is_empty());
let saved = crate::config::list_snapshots(&meta).remove(0);
crate::config::restore_snapshot(&meta, &saved.id).unwrap();
assert_eq!(
list(&root)
.unwrap()
.iter()
.find(|i| i.key == "CoA.LegacyMountFlight")
.unwrap()
.value,
"0"
);
}
const DIST: &str = "[worldserver]\r\n\r\n###################\r\n# SECTION\r\n###################\r\n\r\n#\r\n# Rate.Drop.Item.Epic\r\n# Rate.Drop.Item.Rare\r\n# Description: Drop rates by quality.\r\n# Default: 1\r\n#\r\n\r\nRate.Drop.Item.Rare = 1\r\nRate.Drop.Item.Epic = 1\r\n\r\n#\r\n# LoginDatabaseInfo\r\n# Description: secret\r\n#\r\n\r\nLoginDatabaseInfo = \"127.0.0.1;3306;a;b;c\"\r\n\r\n#\r\n# Instance.ResetTimeHour\r\n# Description: Hour of the reset.\r\n# Important: Use 0-23.\r\n# Default: 4\r\n#\r\n\r\nInstance.ResetTimeHour = 4\r\n"; const DIST: &str = "[worldserver]\r\n\r\n###################\r\n# SECTION\r\n###################\r\n\r\n#\r\n# Rate.Drop.Item.Epic\r\n# Rate.Drop.Item.Rare\r\n# Description: Drop rates by quality.\r\n# Default: 1\r\n#\r\n\r\nRate.Drop.Item.Rare = 1\r\nRate.Drop.Item.Epic = 1\r\n\r\n#\r\n# LoginDatabaseInfo\r\n# Description: secret\r\n#\r\n\r\nLoginDatabaseInfo = \"127.0.0.1;3306;a;b;c\"\r\n\r\n#\r\n# Instance.ResetTimeHour\r\n# Description: Hour of the reset.\r\n# Important: Use 0-23.\r\n# Default: 4\r\n#\r\n\r\nInstance.ResetTimeHour = 4\r\n";
fn server(d: &Path) -> (std::path::PathBuf, std::path::PathBuf) { fn server(d: &Path) -> (std::path::PathBuf, std::path::PathBuf) {
+28 -9
View File
@@ -261,7 +261,9 @@ pub fn config_files(root: &Path) -> Vec<String> {
for e in rd.flatten() { for e in rd.flatten() {
let n = e.file_name().to_string_lossy().to_string(); let n = e.file_name().to_string_lossy().to_string();
// database.json holds generated database passwords; it is launcher state, not configuration. // database.json holds generated database passwords; it is launcher state, not configuration.
if e.path().is_file() && (n.contains(".template") || n == "repack.json" || n == "docker.json") { if e.path().is_file()
&& (n.contains(".template") || n == "repack.json" || n == "docker.json")
{
out.push(format!("Settings/{n}")); out.push(format!("Settings/{n}"));
} }
} }
@@ -381,12 +383,19 @@ pub fn create(
let build = || -> Result<Vec<Component>> { let build = || -> Result<Vec<Component>> {
let mut components = Vec::new(); let mut components = Vec::new();
let realm = crate::realms::state(root)?; let realm = crate::realms::state(root)?;
let mut databases: Vec<(String, &str)> = wanted_databases(kind).iter() let mut databases: Vec<(String, &str)> = wanted_databases(kind)
.map(|name| Ok((name.to_string(), realm.active.schema(name)?))).collect::<Result<_>>()?; .iter()
.map(|name| Ok((name.to_string(), realm.active.schema(name)?)))
.collect::<Result<_>>()?;
if kind != Kind::Config { if kind != Kind::Config {
for other in realm.modes().into_iter().filter(|m| *m != realm.active) { for other in realm.modes().into_iter().filter(|m| *m != realm.active) {
databases.push((format!("{}-characters", other.name()), other.schema("characters")?)); databases.push((
if kind == Kind::Full { databases.push((format!("{}-world", other.name()), other.schema("world")?)); } format!("{}-characters", other.name()),
other.schema("characters")?,
));
if kind == Kind::Full {
databases.push((format!("{}-world", other.name()), other.schema("world")?));
}
} }
} }
if kind != Kind::Config && with_database(root, |db| db.schema_exists("acore_playerbots"))? { if kind != Kind::Config && with_database(root, |db| db.schema_exists("acore_playerbots"))? {
@@ -427,16 +436,24 @@ pub fn create(
return Err(e); return Err(e);
} }
}; };
let mysql_snapshot = if kind == Kind::Full && matches!(trigger, Trigger::BeforeUpdate | Trigger::BeforeRepair) && cfg!(windows) && !crate::docker::is_docker(root) { let mysql_snapshot = if kind == Kind::Full
&& matches!(trigger, Trigger::BeforeUpdate | Trigger::BeforeRepair)
&& cfg!(windows)
&& !crate::docker::is_docker(root)
{
progress("Saving a complete stopped MySQL recovery copy"); progress("Saving a complete stopped MySQL recovery copy");
match crate::mysql_snapshot::capture(root, &partial) { match crate::mysql_snapshot::capture(root, &partial) {
Ok(snapshot) => Some(snapshot), Ok(snapshot) => Some(snapshot),
Err(error) => { Err(error) => {
if let Ok(owned) = fsx::ensure_within(&backups_dir(meta), &partial) { let _ = fs::remove_dir_all(owned); } if let Ok(owned) = fsx::ensure_within(&backups_dir(meta), &partial) {
let _ = fs::remove_dir_all(owned);
}
return Err(error); return Err(error);
} }
} }
} else { None }; } else {
None
};
let point = RecoveryPoint { let point = RecoveryPoint {
realm: crate::realms::state(root)?.active, realm: crate::realms::state(root)?.active,
schema: 1, schema: 1,
@@ -485,7 +502,9 @@ pub fn verify(meta: &Path, id: &str) -> Result<VerifyReport> {
let dir = point_dir(meta, id)?; let dir = point_dir(meta, id)?;
let mut problems = Vec::new(); let mut problems = Vec::new();
if let Some(snapshot) = &point.mysql_snapshot { if let Some(snapshot) = &point.mysql_snapshot {
if let Err(error) = crate::mysql_snapshot::verify(&dir, snapshot) { problems.push(error.to_string()); } if let Err(error) = crate::mysql_snapshot::verify(&dir, snapshot) {
problems.push(error.to_string());
}
} }
let mut names = std::collections::BTreeSet::new(); let mut names = std::collections::BTreeSet::new();
let mut schemas = std::collections::BTreeSet::new(); let mut schemas = std::collections::BTreeSet::new();
+48 -16
View File
@@ -1,7 +1,7 @@
//! Signed channel pointers select one immutable package for an entire transaction. //! Signed channel pointers select one immutable package for an entire transaction.
use serde::{Deserialize, Serialize};
use crate::{Error, Result};
use crate::pkgsource::{fetch_small, Source}; use crate::pkgsource::{fetch_small, Source};
use crate::{Error, Result};
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)] #[serde(rename_all = "camelCase", deny_unknown_fields)]
@@ -21,15 +21,22 @@ pub struct Envelope {
} }
pub fn verify(bytes: &[u8], channel: &str, key: &str) -> Result<Pointer> { pub fn verify(bytes: &[u8], channel: &str, key: &str) -> Result<Pointer> {
let envelope: Envelope = serde_json::from_slice(bytes).map_err(|e| Error::InvalidManifest(e.to_string()))?; let envelope: Envelope =
serde_json::from_slice(bytes).map_err(|e| Error::InvalidManifest(e.to_string()))?;
crate::signing::verify(envelope.payload.as_bytes(), &envelope.signature, key)?; crate::signing::verify(envelope.payload.as_bytes(), &envelope.signature, key)?;
let pointer: Pointer = serde_json::from_str(&envelope.payload).map_err(|e| Error::InvalidManifest(e.to_string()))?; let pointer: Pointer = serde_json::from_str(&envelope.payload)
if pointer.schema != 1 || pointer.channel != channel .map_err(|e| Error::InvalidManifest(e.to_string()))?;
if pointer.schema != 1
|| pointer.channel != channel
|| pointer.release_tag != format!("server-{}", pointer.version) || pointer.release_tag != format!("server-{}", pointer.version)
|| pointer.version.is_empty() || pointer.version.is_empty()
|| !pointer.version.bytes().all(|b| b.is_ascii_digit() || b == b'.') || !pointer
.version
.bytes()
.all(|b| b.is_ascii_digit() || b == b'.')
|| pointer.snapshot.len() != 64 || pointer.snapshot.len() != 64
|| !pointer.snapshot.bytes().all(|b| b.is_ascii_hexdigit()) { || !pointer.snapshot.bytes().all(|b| b.is_ascii_hexdigit())
{
return Err(Error::InvalidManifest("Invalid channel pointer".into())); return Err(Error::InvalidManifest("Invalid channel pointer".into()));
} }
Ok(pointer) Ok(pointer)
@@ -39,21 +46,37 @@ pub fn resolve(channel: &str) -> Result<Source> {
if channel != "stable" && channel != "edge" { if channel != "stable" && channel != "edge" {
return Err(Error::InvalidManifest("Unknown release channel".into())); return Err(Error::InvalidManifest("Unknown release channel".into()));
} }
let source = Source::Url("https://raw.githubusercontent.com/Corfirean/coa-server-build/channels".into()); let source =
Source::Url("https://raw.githubusercontent.com/Corfirean/coa-server-build/channels".into());
let bytes = fetch_small(&source, &format!("{channel}.json"))?; let bytes = fetch_small(&source, &format!("{channel}.json"))?;
let pointer = verify(&bytes, channel, crate::signing::EMBEDDED_PUBLIC_KEY)?; let pointer = verify(&bytes, channel, crate::signing::EMBEDDED_PUBLIC_KEY)?;
Ok(Source::Url(format!("https://github.com/Corfirean/coa-server-build/releases/download/{}", pointer.release_tag))) Ok(Source::Url(format!(
"https://github.com/Corfirean/coa-server-build/releases/download/{}",
pointer.release_tag
)))
} }
pub fn sign(pointer: &Pointer, seed: &str) -> Result<Vec<u8>> { pub fn sign(pointer: &Pointer, seed: &str) -> Result<Vec<u8>> {
use base64::{engine::general_purpose::STANDARD, Engine}; use base64::{engine::general_purpose::STANDARD, Engine};
use ed25519_dalek::{Signer, SigningKey}; use ed25519_dalek::{Signer, SigningKey};
let seed: [u8; 32] = STANDARD.decode(seed.trim()).map_err(|_| Error::Invalid("Invalid signing key".into()))? let seed: [u8; 32] = STANDARD
.try_into().map_err(|_| Error::Invalid("Invalid signing key length".into()))?; .decode(seed.trim())
.map_err(|_| Error::Invalid("Invalid signing key".into()))?
.try_into()
.map_err(|_| Error::Invalid("Invalid signing key length".into()))?;
let payload = serde_json::to_string(pointer).map_err(|e| Error::Invalid(e.to_string()))?; let payload = serde_json::to_string(pointer).map_err(|e| Error::Invalid(e.to_string()))?;
let signature = STANDARD.encode(SigningKey::from_bytes(&seed).sign(payload.as_bytes()).to_bytes()); let signature = STANDARD.encode(
let bytes = serde_json::to_vec(&Envelope { payload, signature }).map_err(|e| Error::Invalid(e.to_string()))?; SigningKey::from_bytes(&seed)
verify(&bytes, &pointer.channel, crate::signing::EMBEDDED_PUBLIC_KEY)?; .sign(payload.as_bytes())
.to_bytes(),
);
let bytes = serde_json::to_vec(&Envelope { payload, signature })
.map_err(|e| Error::Invalid(e.to_string()))?;
verify(
&bytes,
&pointer.channel,
crate::signing::EMBEDDED_PUBLIC_KEY,
)?;
Ok(bytes) Ok(bytes)
} }
@@ -67,12 +90,21 @@ mod tests {
let sk = SigningKey::from_bytes(&[17; 32]); let sk = SigningKey::from_bytes(&[17; 32]);
let payload = serde_json::to_string(pointer).unwrap(); let payload = serde_json::to_string(pointer).unwrap();
let signature = STANDARD.encode(sk.sign(payload.as_bytes()).to_bytes()); let signature = STANDARD.encode(sk.sign(payload.as_bytes()).to_bytes());
(serde_json::to_vec(&Envelope { payload, signature }).unwrap(), STANDARD.encode(sk.verifying_key().to_bytes())) (
serde_json::to_vec(&Envelope { payload, signature }).unwrap(),
STANDARD.encode(sk.verifying_key().to_bytes()),
)
} }
#[test] #[test]
fn verifies_identity_signature_and_immutable_tag() { fn verifies_identity_signature_and_immutable_tag() {
let mut p = Pointer { schema: 1, channel: "stable".into(), version: "0.261010.40".into(), release_tag: "server-0.261010.40".into(), snapshot: "a".repeat(64) }; let mut p = Pointer {
schema: 1,
channel: "stable".into(),
version: "0.261010.40".into(),
release_tag: "server-0.261010.40".into(),
snapshot: "a".repeat(64),
};
let (bytes, key) = signed(&p); let (bytes, key) = signed(&p);
assert_eq!(verify(&bytes, "stable", &key).unwrap().version, p.version); assert_eq!(verify(&bytes, "stable", &key).unwrap().version, p.version);
assert!(verify(&bytes, "edge", &key).is_err()); assert!(verify(&bytes, "edge", &key).is_err());
@@ -0,0 +1,124 @@
//! Update-only comparison of existing unsupported character starts. Never repairs or deletes rows.
use crate::{db::Db, Error, Result};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct MissingStart {
pub guid: u32,
pub race: u32,
pub class: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Baseline {
pub schema: u32,
pub realms: BTreeMap<String, BTreeSet<MissingStart>>,
}
pub fn parse_missing(text: &str) -> Result<BTreeSet<MissingStart>> {
text.lines()
.map(|line| {
let values = line
.split('\t')
.map(str::parse::<u32>)
.collect::<std::result::Result<Vec<_>, _>>()
.map_err(|_| {
Error::Invalid("Cannot read existing character start identities.".into())
})?;
if values.len() != 3 {
return Err(Error::Invalid(
"Incomplete character start identity.".into(),
));
}
Ok(MissingStart {
guid: values[0],
race: values[1],
class: values[2],
})
})
.collect()
}
pub fn missing(db: &Db) -> Result<BTreeSet<MissingStart>> {
parse_missing(&db.query("SELECT c.guid,c.race,c.class FROM acore_characters.characters c LEFT JOIN acore_world.playercreateinfo p ON p.race=c.race AND p.class=c.class WHERE p.race IS NULL;")?)
}
pub fn capture(db: &Db, root: &Path) -> Result<Baseline> {
let mut realms = BTreeMap::new();
for mode in crate::realms::state(root)?.modes() {
realms.insert(
mode.name().to_owned(),
missing(&db.clone().for_realm(mode))?,
);
}
Ok(Baseline { schema: 1, realms })
}
/// Match identity and race/class, never just totals: one new failure cannot replace an old one.
pub fn introduced(
current: &BTreeSet<MissingStart>,
before: &BTreeSet<MissingStart>,
) -> BTreeSet<MissingStart> {
current.difference(before).copied().collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn old_gaps_are_not_new_character_loss() {
let before = parse_missing("1\t44\t14\n2\t44\t14\n3\t44\t14").unwrap();
assert!(introduced(&before, &before).is_empty());
assert!(introduced(&BTreeSet::new(), &before).is_empty());
let replaced = parse_missing("1\t44\t14\n2\t44\t14\n4\t44\t14").unwrap();
assert_eq!(
introduced(&replaced, &before),
parse_missing("4\t44\t14").unwrap()
);
let changed = parse_missing("1\t44\t15").unwrap();
assert_eq!(introduced(&changed, &before), changed);
assert_eq!(introduced(&before, &BTreeSet::new()), before);
}
#[test]
fn malformed_identity_is_not_silently_ignored() {
for text in ["1\t44", "bad\t44\t14", "1\t44\t14\t0", "1\t44\t-1"] {
assert!(parse_missing(text).is_err());
}
assert!(parse_missing("").unwrap().is_empty());
}
#[test]
fn reported_174_old_records_cannot_mask_one_newly_hidden_character() {
// Reproduce the report's scale without shipping another person's diagnostics or identities.
let before: BTreeSet<_> = (1..=174)
.map(|guid| MissingStart {
guid,
race: 44,
class: 14,
})
.collect();
assert!(introduced(&before, &before).is_empty());
let mut after = before.clone();
after.remove(&MissingStart {
guid: 1,
race: 44,
class: 14,
});
after.insert(MissingStart {
guid: 175,
race: 44,
class: 14,
});
assert_eq!(after.len(), before.len());
assert_eq!(
introduced(&after, &before),
BTreeSet::from([MissingStart {
guid: 175,
race: 44,
class: 14
}])
);
}
}
+63 -15
View File
@@ -15,7 +15,8 @@ use crate::fsx;
pub use crate::glue_config; pub use crate::glue_config;
pub const ADDON_NAME: &str = "CoABotUI"; pub const ADDON_NAME: &str = "CoABotUI";
const EXECUTABLES: [&str; 3] = ["Ascension.exe", "Wow.exe", "WoW.exe"]; // CoA Custom Races V2 ships its own client (CoACustomRace.exe) next to Ascension.exe and must be started instead.
const EXECUTABLES: [&str; 4] = ["CoACustomRace.exe", "Ascension.exe", "Wow.exe", "WoW.exe"];
pub fn is_running(client: &Path) -> bool { pub fn is_running(client: &Path) -> bool {
if crate::platform::flavor() == crate::platform::Flavor::Docker { if crate::platform::flavor() == crate::platform::Flavor::Docker {
@@ -417,11 +418,21 @@ pub fn launch(client: &Path) -> Result<u32> {
return crate::wine::launch(client, exe); return crate::wine::launch(client, exe);
} }
let executable = client.join(exe); let executable = client.join(exe);
let spawn = || Command::new(&executable).current_dir(client).spawn().map(|child| child.id()); let spawn = || {
Command::new(&executable)
.current_dir(client)
.spawn()
.map(|child| child.id())
};
#[cfg(windows)] #[cfg(windows)]
{ launch_with_elevation_fallback(spawn, || launch_elevated(&executable, client)).map_err(Into::into) } {
launch_with_elevation_fallback(spawn, || launch_elevated(&executable, client))
.map_err(Into::into)
}
#[cfg(not(windows))] #[cfg(not(windows))]
{ spawn().map_err(Into::into) } {
spawn().map_err(Into::into)
}
} }
/// Start normally first; ask Windows for elevation only when the client requires it (ERROR_ELEVATION_REQUIRED, 740). /// Start normally first; ask Windows for elevation only when the client requires it (ERROR_ELEVATION_REQUIRED, 740).
@@ -443,9 +454,15 @@ fn launch_elevated(executable: &Path, directory: &Path) -> std::io::Result<u32>
use std::os::windows::ffi::OsStrExt; use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Threading::GetProcessId; use windows_sys::Win32::System::Threading::GetProcessId;
use windows_sys::Win32::UI::Shell::{ShellExecuteExW, SHELLEXECUTEINFOW, SEE_MASK_NOCLOSEPROCESS, SEE_MASK_NOASYNC}; use windows_sys::Win32::UI::Shell::{
ShellExecuteExW, SEE_MASK_NOASYNC, SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOW,
};
use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL; use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;
let file: Vec<u16> = executable.as_os_str().encode_wide().chain(Some(0)).collect(); let file: Vec<u16> = executable
.as_os_str()
.encode_wide()
.chain(Some(0))
.collect();
let cwd: Vec<u16> = directory.as_os_str().encode_wide().chain(Some(0)).collect(); let cwd: Vec<u16> = directory.as_os_str().encode_wide().chain(Some(0)).collect();
let verb: Vec<u16> = "runas".encode_utf16().chain(Some(0)).collect(); let verb: Vec<u16> = "runas".encode_utf16().chain(Some(0)).collect();
let mut info = SHELLEXECUTEINFOW { let mut info = SHELLEXECUTEINFOW {
@@ -457,12 +474,22 @@ fn launch_elevated(executable: &Path, directory: &Path) -> std::io::Result<u32>
nShow: SW_SHOWNORMAL, nShow: SW_SHOWNORMAL,
..Default::default() ..Default::default()
}; };
if unsafe { ShellExecuteExW(&mut info) } == 0 { return Err(std::io::Error::last_os_error()); } if unsafe { ShellExecuteExW(&mut info) } == 0 {
if info.hProcess.is_null() { return Err(std::io::Error::other("Windows did not return the game process handle.")); } return Err(std::io::Error::last_os_error());
}
if info.hProcess.is_null() {
return Err(std::io::Error::other(
"Windows did not return the game process handle.",
));
}
let pid = unsafe { GetProcessId(info.hProcess) }; let pid = unsafe { GetProcessId(info.hProcess) };
let error = std::io::Error::last_os_error(); let error = std::io::Error::last_os_error();
unsafe { CloseHandle(info.hProcess); } unsafe {
if pid == 0 { return Err(error); } CloseHandle(info.hProcess);
}
if pid == 0 {
return Err(error);
}
Ok(pid) Ok(pid)
} }
@@ -585,11 +612,29 @@ mod tests {
#[cfg(windows)] #[cfg(windows)]
#[test] #[test]
fn elevation_is_requested_only_when_windows_requires_it() { fn elevation_is_requested_only_when_windows_requires_it() {
assert_eq!(launch_with_elevation_fallback(|| Ok(17), || panic!("unneeded elevation")).unwrap(), 17); assert_eq!(
assert_eq!(launch_with_elevation_fallback(|| Err(std::io::Error::from_raw_os_error(740)), || Ok(23)).unwrap(), 23); launch_with_elevation_fallback(|| Ok(17), || panic!("unneeded elevation")).unwrap(),
let error = launch_with_elevation_fallback(|| Err(std::io::Error::from_raw_os_error(2)), || panic!("wrong error elevated")).unwrap_err(); 17
);
assert_eq!(
launch_with_elevation_fallback(
|| Err(std::io::Error::from_raw_os_error(740)),
|| Ok(23)
)
.unwrap(),
23
);
let error = launch_with_elevation_fallback(
|| Err(std::io::Error::from_raw_os_error(2)),
|| panic!("wrong error elevated"),
)
.unwrap_err();
assert_eq!(error.raw_os_error(), Some(2)); assert_eq!(error.raw_os_error(), Some(2));
let cancelled = launch_with_elevation_fallback(|| Err(std::io::Error::from_raw_os_error(740)), || Err(std::io::Error::from_raw_os_error(1223))).unwrap_err(); let cancelled = launch_with_elevation_fallback(
|| Err(std::io::Error::from_raw_os_error(740)),
|| Err(std::io::Error::from_raw_os_error(1223)),
)
.unwrap_err();
assert_eq!(cancelled.raw_os_error(), Some(1223)); assert_eq!(cancelled.raw_os_error(), Some(1223));
} }
@@ -620,7 +665,10 @@ mod tests {
assert!(sync_realm(&c, &meta, crate::realms::Mode::Wildcard).unwrap()); assert!(sync_realm(&c, &meta, crate::realms::Mode::Wildcard).unwrap());
assert_eq!(fs::read(c.join("WTF/Config.wtf")).unwrap(), original); assert_eq!(fs::read(c.join("WTF/Config.wtf")).unwrap(), original);
assert!(sync_realm(&c, &meta, crate::realms::Mode::Reborn).unwrap()); assert!(sync_realm(&c, &meta, crate::realms::Mode::Reborn).unwrap());
assert_eq!(fs::read(c.join("WTF/Config.wtf")).unwrap(), b"SET sound 1\r\nSET realmName \"Warcraft Reborn\"\r\n"); assert_eq!(
fs::read(c.join("WTF/Config.wtf")).unwrap(),
b"SET sound 1\r\nSET realmName \"Warcraft Reborn\"\r\n"
);
} }
#[test] #[test]
+134
View File
@@ -0,0 +1,134 @@
use crate::{fsx, Error, Result};
use serde::{Deserialize, Serialize};
use std::{fs, path::Path};
#[derive(Default, Serialize, Deserialize)]
pub struct Graphics {
pub dxvk_disabled: bool,
pub enhancements_disabled: bool,
}
fn preferences(client: &Path) -> Result<Option<Graphics>> {
match fs::read(client.join(".coa-manager/graphics.json")) {
Ok(bytes) => Ok(Some(serde_json::from_slice(&bytes)?)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}
pub fn status(client: &Path) -> Result<Graphics> {
let saved = preferences(client)?.unwrap_or_default();
let actual = |name: &str, remembered: bool| -> Result<bool> {
let active = client.join(name).is_file();
let inactive = client.join(format!("{name}.DISABLED")).is_file();
if active && inactive {
return Err(Error::Invalid(
"Both enabled and disabled renderer files exist.".into(),
));
}
Ok(inactive || (!active && remembered))
};
Ok(Graphics {
dxvk_disabled: actual("d3d9.dll", saved.dxvk_disabled)?,
enhancements_disabled: actual("dxgi.dll", saved.enhancements_disabled)?,
})
}
pub fn disabled(client: &Path, path: &str) -> Result<bool> {
let name = path.to_ascii_lowercase();
if !matches!(name.as_str(), "d3d9.dll" | "dxgi.dll") {
return Ok(false);
}
let state = status(client)?;
Ok(if name == "d3d9.dll" {
state.dxvk_disabled
} else {
state.enhancements_disabled
})
}
pub fn set(client: &Path, name: &str, disabled: bool) -> Result<Graphics> {
if !matches!(name, "d3d9.dll" | "dxgi.dll") {
return Err(Error::Invalid("Unknown graphics setting.".into()));
}
if crate::client::is_running(client) {
return Err(Error::Invalid(
"Close the game before changing graphics settings.".into(),
));
}
let active = fsx::safe_join(client, name)?;
let inactive = fsx::safe_join(client, &format!("{name}.DISABLED"))?;
if active.exists() && inactive.exists() {
return Err(Error::Invalid("Both enabled and disabled renderer files exist. Resolve the conflict before changing graphics settings.".into()));
}
let mut state = status(client)?;
if name == "d3d9.dll" {
state.dxvk_disabled = disabled;
} else {
state.enhancements_disabled = disabled;
}
let (source, target) = if disabled {
(&active, &inactive)
} else {
(&inactive, &active)
};
// The no-clobber link also preserves an existing destination if another app changes the setting.
if source.is_file() {
if let Err(error) = fs::hard_link(source, target) {
if error.kind() == std::io::ErrorKind::AlreadyExists {
return Err(error.into());
}
let mut output = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(target)?;
let copied = std::fs::File::open(source)
.and_then(|mut input| std::io::copy(&mut input, &mut output))
.and_then(|_| output.sync_all());
drop(output);
if let Err(error) = copied {
let _ = fs::remove_file(target);
return Err(error.into());
}
}
if let Err(error) = fs::remove_file(source) {
let _ = fs::remove_file(target);
return Err(error.into());
}
}
fsx::atomic_write_json(&client.join(".coa-manager/graphics.json"), &state)?;
Ok(state)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn toggles_preserve_bytes_and_refuse_conflicts() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
fs::write(root.join("d3d9.dll"), b"custom renderer").unwrap();
assert!(set(root, "d3d9.dll", true).unwrap().dxvk_disabled);
assert!(!root.join("d3d9.dll").exists());
assert_eq!(
fs::read(root.join("d3d9.dll.DISABLED")).unwrap(),
b"custom renderer"
);
assert!(!set(root, "d3d9.dll", false).unwrap().dxvk_disabled);
fs::write(root.join("d3d9.dll.DISABLED"), b"other").unwrap();
assert!(set(root, "d3d9.dll", false).is_err());
assert_eq!(fs::read(root.join("d3d9.dll")).unwrap(), b"custom renderer");
assert_eq!(fs::read(root.join("d3d9.dll.DISABLED")).unwrap(), b"other");
}
#[test]
fn remembers_missing_wrapper_and_imports_launcher_marker() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
assert!(set(root, "d3d9.dll", true).unwrap().dxvk_disabled);
assert!(disabled(root, "d3d9.dll").unwrap());
fs::write(root.join("dxgi.dll.DISABLED"), b"launcher disabled").unwrap();
assert!(disabled(root, "dxgi.dll").unwrap());
assert!(!disabled(root, "Data/d3d9.dll").unwrap());
}
}
+54
View File
@@ -299,6 +299,11 @@ pub fn plan(
bytes_per_sec: 0, bytes_per_sec: 0,
file: Some(f.path.clone()), file: Some(f.path.clone()),
}); });
if crate::client_graphics::disabled(client, &f.path)? {
kept += 1;
done += f.size;
continue;
}
let path = fsx::safe_join(client, &f.path)?; let path = fsx::safe_join(client, &f.path)?;
let meta = match fs::metadata(&path) { let meta = match fs::metadata(&path) {
Ok(meta) if meta.is_file() => meta, Ok(meta) if meta.is_file() => meta,
@@ -440,6 +445,9 @@ pub fn apply(a: &Apply, on_step: &dyn Fn(Step)) -> Result<()> {
let mut todo = Vec::new(); let mut todo = Vec::new();
for item in &a.plan.items { for item in &a.plan.items {
if crate::client_graphics::disabled(a.client, &item.path)? {
continue;
}
if item.kind == Kind::Modified && a.keep_modified { if item.kind == Kind::Modified && a.keep_modified {
let path = fsx::safe_join(a.client, &item.path)?; let path = fsx::safe_join(a.client, &item.path)?;
let meta = fs::metadata(&path)?; let meta = fs::metadata(&path)?;
@@ -777,6 +785,52 @@ mod tests {
); );
} }
#[test]
fn disabled_launcher_renderers_are_never_restored_even_with_a_stale_plan() {
let dir = tempfile::tempdir().unwrap();
let files: Vec<(&str, &[u8])> = vec![("d3d9.dll", b"dxvk"), ("dxgi.dll", b"enhancements")];
let manifest = manifest("v1", &files);
let cancel = Cancel::default();
let old_plan = plan(dir.path(), &manifest, &State::default(), &cancel, &|_| {}).unwrap();
fs::write(dir.path().join("d3d9.dll.DISABLED"), b"custom disabled").unwrap();
crate::client_graphics::set(dir.path(), "dxgi.dll", true).unwrap();
let server = Server::new(&files);
apply(
&Apply {
client: dir.path(),
manifest: &manifest,
plan: &old_plan,
keep_modified: false,
transport: &server,
objects_url: "https://x.invalid/objects",
cancel: &cancel,
},
&|_| {},
)
.unwrap();
assert!(server.requested.lock().unwrap().is_empty());
assert!(!dir.path().join("d3d9.dll").exists());
assert!(!dir.path().join("dxgi.dll").exists());
assert_eq!(
fs::read(dir.path().join("d3d9.dll.DISABLED")).unwrap(),
b"custom disabled"
);
let after = plan(
dir.path(),
&manifest,
&load_state(dir.path()).unwrap(),
&cancel,
&|_| {},
)
.unwrap();
assert!(after.items.is_empty());
crate::client_graphics::set(dir.path(), "d3d9.dll", false).unwrap();
assert_eq!(
fs::read(dir.path().join("d3d9.dll")).unwrap(),
b"custom disabled"
);
}
#[test] #[test]
fn renderer_files_configs_and_everything_not_in_the_manifest_survive_an_update_untouched() { fn renderer_files_configs_and_everything_not_in_the_manifest_survive_an_update_untouched() {
let d = tempfile::tempdir().unwrap(); let d = tempfile::tempdir().unwrap();
+26
View File
@@ -2,6 +2,7 @@
pub mod merge; pub mod merge;
pub mod parser; pub mod parser;
pub mod portable;
pub mod schema; pub mod schema;
use std::collections::{BTreeMap, BTreeSet}; use std::collections::{BTreeMap, BTreeSet};
@@ -1033,6 +1034,31 @@ Spellbook.New = 5
assert!(v.drift_keys.is_empty()); assert!(v.drift_keys.is_empty());
} }
#[test]
fn skill_controls_persist_and_reject_invalid_gains() {
let (_d, root, meta) = fixture();
let changes = BTreeMap::from([
("SkillChance.Prospecting".into(), json!(true)),
("SkillChance.Milling".into(), json!(true)),
("SkillGain.Crafting".into(), json!(3)),
("SkillGain.Defense".into(), json!(4)),
("SkillGain.Gathering".into(), json!(5)),
]);
let report = save(&root, &meta, Scope::Server, &changes).unwrap();
assert_eq!(report.changed.len(), 5);
assert_eq!(report.restart, Some(Restart::World));
for path in ["Settings/worldserver.conf.template", "Core/configs/worldserver.conf"] {
let conf = load_conf(&root.join(path)).unwrap();
for (key, expected) in [("SkillChance.Prospecting", "1"), ("SkillChance.Milling", "1"), ("SkillGain.Crafting", "3"), ("SkillGain.Defense", "4"), ("SkillGain.Gathering", "5")] {
assert_eq!(conf.get(key), Some(expected));
}
assert_eq!(conf.get("Unknown.Custom"), Some("\"keep me\""));
}
for value in [json!(-1), json!(1.5), json!(451)] {
assert!(save(&root, &meta, Scope::Server, &BTreeMap::from([("SkillGain.Crafting".into(), value)])).is_err());
}
}
#[test] #[test]
fn creature_rates_save_independently_in_template_and_active_config() { fn creature_rates_save_independently_in_template_and_active_config() {
let (_d, root, meta) = fixture(); let (_d, root, meta) = fixture();
+175
View File
@@ -0,0 +1,175 @@
//! Prepare the core side of the owner's portable-character opt-in.
use std::{fs, path::Path};
use super::{parser::ConfFile, take_snapshot, targets, Scope};
use crate::{fsx, Error, Result};
/// Configuration is changed only while the world is stopped. Disabling admission is
/// handled by the control service and must not disable an active session's core.
pub fn enable(root: &Path) -> Result<()> {
let meta = crate::registry::metadata_dir_for(root)?;
let _lock = crate::update::operation_lock_for(&meta, "configuring portable characters", false)?;
let module = root.join("Core/configs/modules/coa.conf");
let module_source = if module.is_file() {
module.clone()
} else {
root.join("Core/configs/modules/coa.conf.dist")
};
let bytes = fs::read(&module_source).map_err(|_| Error::Invalid(
"Update this server before enabling portable characters; its portable configuration is missing.".into()
))?;
let mut conf = ConfFile::parse_bytes(&bytes)?;
if conf.get("PortableSession.Enable").is_none() {
return Err(Error::Invalid("Update this server before enabling portable characters; its core configuration has no portable session support.".into()));
}
let mut writes = Vec::new();
if conf.get("PortableSession.Enable").map(str::trim) != Some("1")
|| conf.get("PortableImport.JobDir").map(str::trim) != Some("\"PortableImport\"")
|| !module.is_file()
{
conf.set(
"PortableSession.Enable",
"1",
&["Enabled by the realm owner's portable-character opt-in"],
);
conf.set(
"PortableImport.JobDir",
"\"PortableImport\"",
&["Shared working directory for the core and Manager"],
);
writes.push((
module.clone(),
module.is_file().then(|| bytes.clone()),
conf.to_text(),
));
}
for path in targets(root, Scope::Server)?.writes {
let bytes = fs::read(&path)?;
let mut conf = ConfFile::parse_bytes(&bytes)?;
if conf.get("CharacterDatabase.WorkerThreads").map(str::trim) != Some("1") {
conf.set(
"CharacterDatabase.WorkerThreads",
"1",
&["Portable sessions require ordered character database transactions"],
);
writes.push((path, Some(bytes), conf.to_text()));
}
}
if writes.is_empty() {
fs::create_dir_all(root.join("Core/PortableImport"))?;
return Ok(());
}
let observed = crate::process::observe(root, &crate::layout::read_ports(root));
if observed.world.state != crate::process::ServiceState::Stopped
|| observed.world.conflict.is_some()
|| std::net::TcpStream::connect_timeout(
&std::net::SocketAddr::from(([127, 0, 0, 1], crate::layout::read_ports(root).world)),
std::time::Duration::from_millis(100),
)
.is_ok()
|| crate::multiworld::is_running(root)
{
return Err(Error::Invalid("Stop this server, then enable portable characters and save again. The Manager must configure the core before its next start.".into()));
}
let originals = writes
.iter()
.filter_map(|(p, old, _)| old.clone().map(|bytes| (p.clone(), bytes)))
.collect::<Vec<_>>();
take_snapshot(
&meta,
Scope::Server,
"before enabling portable characters",
&originals,
)?;
for (index, (path, _, text)) in writes.iter().enumerate() {
if let Err(error) = fsx::atomic_write(path, text.as_bytes()) {
for (path, old, _) in writes.iter().take(index) {
if let Some(bytes) = old {
let _ = fsx::atomic_write(path, bytes);
} else {
let _ = fs::remove_file(path);
}
}
return Err(error);
}
}
fs::create_dir_all(root.join("Core/PortableImport"))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[test]
fn portable_opt_in_updates_the_effective_module_and_survives_launcher_rendering() {
let temp = tempdir().unwrap();
let root = temp.path().join("realm");
fs::create_dir_all(root.join("Core/configs/modules")).unwrap();
fs::create_dir_all(root.join("Settings")).unwrap();
fs::write(
root.join("Settings/repack.json"),
r#"{"worldPort":49143,"authPort":49144,"mysqlPort":49145,"raPort":49146}"#,
)
.unwrap();
fs::write(
root.join("Core/configs/modules/coa.conf"),
"# Owner setting\nCoA.Enable = 1\nPortableSession.Enable = 0\n",
)
.unwrap();
for name in [
"Settings/worldserver.conf.template",
"Core/configs/worldserver.conf",
] {
fs::write(
root.join(name),
"CharacterDatabase.WorkerThreads = 3\nMaxPlayerLevel = 80\n",
)
.unwrap();
}
enable(&root).unwrap();
assert!(root.join("Core/PortableImport").is_dir());
let module = fs::read_to_string(root.join("Core/configs/modules/coa.conf")).unwrap();
assert!(
module.contains("# Owner setting") && module.contains("PortableSession.Enable = 1")
);
for name in [
"Settings/worldserver.conf.template",
"Core/configs/worldserver.conf",
] {
let text = fs::read_to_string(root.join(name)).unwrap();
assert!(
text.contains("CharacterDatabase.WorkerThreads = 1")
&& text.contains("MaxPlayerLevel = 80")
);
}
let snapshots =
super::super::list_snapshots(&crate::registry::metadata_dir_for(&root).unwrap());
assert_eq!(snapshots.len(), 1);
enable(&root).unwrap();
assert_eq!(
super::super::list_snapshots(&crate::registry::metadata_dir_for(&root).unwrap()).len(),
1
);
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
fs::write(
root.join("Settings/repack.json"),
format!(
r#"{{"worldPort":{}}}"#,
listener.local_addr().unwrap().port()
),
)
.unwrap();
let disabled = "PortableSession.Enable = 0\n";
fs::write(root.join("Core/configs/modules/coa.conf"), disabled).unwrap();
assert!(enable(&root)
.unwrap_err()
.to_string()
.contains("Stop this server"));
assert_eq!(
fs::read_to_string(root.join("Core/configs/modules/coa.conf")).unwrap(),
disabled
);
}
}
+10 -2
View File
@@ -61,8 +61,16 @@ pub fn lines_from_text(text: &str, filter: Option<&str>, max_lines: usize) -> Ve
let out: Vec<Line> = text let out: Vec<Line> = text
.lines() .lines()
.filter(|l| !l.trim().is_empty()) .filter(|l| !l.trim().is_empty())
.filter(|l| needle.as_ref().map(|n| l.to_lowercase().contains(n)).unwrap_or(true)) .filter(|l| {
.map(|l| Line { level: classify(l), text: crate::diag::redact(l) }) needle
.as_ref()
.map(|n| l.to_lowercase().contains(n))
.unwrap_or(true)
})
.map(|l| Line {
level: classify(l),
text: crate::diag::redact(l),
})
.collect(); .collect();
let skip = out.len().saturating_sub(max_lines); let skip = out.len().saturating_sub(max_lines);
out.into_iter().skip(skip).collect() out.into_iter().skip(skip).collect()
+902 -2
View File
@@ -63,9 +63,47 @@ impl LocalBackend {
} }
} }
fn require_portable(&self, local_id: &str) -> Result<()> {
let settings = settings::load(&self.settings_dir)?;
if settings
.realms
.get(local_id)
.is_some_and(|cfg| cfg.allow_portable)
{
Ok(())
} else {
Err(Error::Invalid(
"The realm owner has disabled portable characters.".into(),
))
}
}
fn access(&self, local_id: &str) -> Result<RealmAccess> { fn access(&self, local_id: &str) -> Result<RealmAccess> {
find_access(&self.descriptors, &(self.installs)(), local_id) let access =
.ok_or_else(|| Error::Invalid("That realm is not known to this Manager.".into())) find_access(&self.descriptors, &(self.installs)(), local_id).ok_or_else(|| {
Error::Invalid(format!(
"That realm is not known to this Manager: {local_id}"
))
})?;
if let Some((_base, rs)) = local_id.split_once(':') {
let expected_mode = match rs {
"coa" => crate::realms::Mode::Coa,
"wildcard" => crate::realms::Mode::Wildcard,
"reborn" => crate::realms::Mode::Reborn,
_ => {
return Err(Error::Invalid(format!(
"Malformed or unknown ruleset suffix in local_id: {rs}"
)))
}
};
if access.mode != Some(expected_mode) {
return Err(Error::Invalid(format!(
"Realm access mode {:?} does not match expected ruleset in local_id {local_id}",
access.mode
)));
}
}
Ok(access)
} }
fn account(&self, local_id: &str, filter: &str) -> Result<Option<AccountRow>> { fn account(&self, local_id: &str, filter: &str) -> Result<Option<AccountRow>> {
@@ -84,11 +122,73 @@ impl LocalBackend {
} }
impl RealmBackend for LocalBackend { impl RealmBackend for LocalBackend {
fn session_message(
&self,
local_id: &str,
character: Uuid,
session: Uuid,
account: u32,
) -> Result<super::service::RemoteSessionState> {
let id = local_id.to_string();
self.portable
.call(move |service| service.remote_session_message(&id, character, session, account))
.map_err(|error| unavailable("portable engine", error))?
.map_err(|error| unavailable("portable session", error))
}
fn session_ack(
&self,
local_id: &str,
character: Uuid,
session: Uuid,
account: u32,
kind: app::SessionMessageKind,
bytes: &[u8],
) -> Result<()> {
let id = local_id.to_string();
let bytes = bytes.to_vec();
self.portable
.call(move |service| {
service.apply_remote_session_ack(&id, character, session, account, kind, &bytes)
})
.map_err(|error| unavailable("portable engine", error))?
.map_err(|error| unavailable("portable session", error))
}
fn info(&self, local_id: &str) -> Result<RealmInfo> { fn info(&self, local_id: &str) -> Result<RealmInfo> {
let cfg = settings::load(&self.settings_dir)?.realms.remove(local_id); let cfg = settings::load(&self.settings_dir)?.realms.remove(local_id);
let access = self.access(local_id)?;
let db = access.db()?;
let ruleset = realm::ruleset_of(&db).map_err(|e| Error::Invalid(e.to_string()))?;
// Explicit local-id -> ruleset invariant:
// local_id ruleset == RealmAccess.mode == Db.realm() == RealmInfo.ruleset
if let Some((_base, rs)) = local_id.split_once(':') {
let expected_ruleset: crate::portable::Ruleset = rs
.parse()
.map_err(|_| Error::Invalid(format!("Unknown ruleset in local_id: {rs}")))?;
if ruleset != expected_ruleset {
return Err(Error::Invalid(format!(
"Ruleset of realm DB ({ruleset:?}) does not match local_id {local_id}"
)));
}
if access.mode.map(|m| m.name()) != Some(expected_ruleset.as_str()) {
return Err(Error::Invalid(format!(
"RealmAccess mode ({:?}) does not match local_id {local_id}",
access.mode
)));
}
if db.realm().name() != expected_ruleset.as_str() {
return Err(Error::Invalid(format!(
"Db realm ({:?}) does not match local_id {local_id}",
db.realm()
)));
}
}
Ok(RealmInfo { Ok(RealmInfo {
automatic: cfg.as_ref().is_none_or(|c| !c.existing_only), automatic: cfg.as_ref().is_none_or(|c| !c.existing_only),
route: cfg.and_then(|c| c.route), route: cfg.and_then(|c| c.route),
ruleset,
}) })
} }
@@ -203,6 +303,7 @@ impl RealmBackend for LocalBackend {
} }
fn export(&self, local_id: &str, _account_id: u32, guid: u32) -> Result<ClaimExport> { fn export(&self, local_id: &str, _account_id: u32, guid: u32) -> Result<ClaimExport> {
self.require_portable(local_id)?;
let id = local_id.to_string(); let id = local_id.to_string();
let bundle = self let bundle = self
.portable .portable
@@ -211,6 +312,7 @@ impl RealmBackend for LocalBackend {
.map_err(|e| unavailable("export", e))?; .map_err(|e| unavailable("export", e))?;
Ok(ClaimExport { Ok(ClaimExport {
character_id: bundle.character_id.as_uuid(), character_id: bundle.character_id.as_uuid(),
ruleset: bundle.ruleset,
payload: bundle.payload, payload: bundle.payload,
sha256: bundle.content_hash, sha256: bundle.content_hash,
collections: bundle.collections, collections: bundle.collections,
@@ -223,6 +325,7 @@ impl RealmBackend for LocalBackend {
character_id: Uuid, character_id: Uuid,
revision: u64, revision: u64,
) -> Result<PreflightVerdict> { ) -> Result<PreflightVerdict> {
self.require_portable(local_id)?;
let id = local_id.to_string(); let id = local_id.to_string();
let cid = crate::portable::CharacterId::from_uuid(character_id) let cid = crate::portable::CharacterId::from_uuid(character_id)
.map_err(|e| unavailable("character id", e))?; .map_err(|e| unavailable("character id", e))?;
@@ -237,10 +340,807 @@ impl RealmBackend for LocalBackend {
local_id: &str, local_id: &str,
params: RemoteImportParams, params: RemoteImportParams,
) -> Result<RemoteImportOutcome> { ) -> Result<RemoteImportOutcome> {
self.require_portable(local_id)?;
let id = local_id.to_string(); let id = local_id.to_string();
self.portable self.portable
.call(move |s| s.import_remote_character(&id, params)) .call(move |s| s.import_remote_character(&id, params))
.map_err(|e| unavailable("portable engine", e))? .map_err(|e| unavailable("portable engine", e))?
.map_err(|e| unavailable("import remote", e)) .map_err(|e| unavailable("import remote", e))
} }
fn auth_port(&self, local_id: &str) -> Result<u16> {
let access = self.access(local_id)?;
let root = access
.root
.ok_or_else(|| Error::Invalid("The realm's auth port is unresolved.".into()))?;
let settings: serde_json::Value =
crate::fsx::read_json(&root.join("Settings/repack.json"))?;
match settings.get("authPort") {
None => Ok(coa_control_proto::relay::LOCAL_AUTH_PORT),
Some(value) => value
.as_u64()
.and_then(|port| u16::try_from(port).ok())
.filter(|port| *port != 0)
.ok_or_else(|| Error::Invalid("The realm's auth port is invalid.".into())),
}
}
fn world_port(&self, local_id: &str) -> Result<u16> {
if let Ok(override_port) = std::env::var("COA_OVERRIDE_LOCAL_WORLD_PORT") {
if let Ok(p) = override_port.parse::<u16>() {
return Ok(p);
}
}
let access = self.access(local_id)?;
let mode = if let Some(m) = access.mode {
m
} else if let Some((_base, _rs)) = local_id.split_once(':') {
return Err(Error::Invalid(format!(
"Unresolved mode for ruleset suffix in {local_id}"
)));
} else {
// Legacy unsuffixed CoA realm ONLY
crate::realms::Mode::Coa
};
if let Some(ref root) = access.root {
crate::realms::world_port_for_mode(root, mode)
} else {
Err(Error::Invalid(format!(
"No server installation root for {local_id} to resolve world port"
)))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::tempdir;
#[test]
fn portable_access_requires_owner_opt_in_and_revokes_immediately() {
let dir = tempdir().unwrap();
let rt =
PortableRuntime::start(&dir.path().join("portable"), Box::new(Vec::new), None).unwrap();
let backend = LocalBackend::new(Arc::new(rt), dir.path(), dir.path(), Arc::new(Vec::new));
assert!(backend.require_portable("srv-test").is_err());
let mut cfg = settings::RegistrySettings::default();
cfg.realms.insert(
"srv-test".into(),
settings::PublishConfig {
realm_id: None,
enabled: true,
display_name: "Test".into(),
description: String::new(),
language: "en".into(),
region: None,
existing_only: false,
allow_portable: true,
route: None,
},
);
settings::save(dir.path(), &cfg).unwrap();
assert!(backend.require_portable("srv-test").is_ok());
cfg.realms.get_mut("srv-test").unwrap().allow_portable = false;
settings::save(dir.path(), &cfg).unwrap();
assert!(backend
.export("srv-test", 1, 1)
.unwrap_err()
.to_string()
.contains("disabled portable"));
assert!(backend
.check_transfer("srv-test", Uuid::new_v4(), 1)
.unwrap_err()
.to_string()
.contains("disabled portable"));
}
#[test]
#[ignore = "Requires disposable A/B databases, B worldserver configuration and REGISTRY_URL"]
fn live_vps_transfer_uses_real_backend_and_preserves_the_working_copy() {
use crate::control::{
host_link::HostLink,
join::{PlayerControl, RealmTarget},
secrets::MemoryStore,
service::HostService,
store::ControlStore,
transport::coordinator_url,
};
use crate::portable::{
extension::ExtensionRegistry,
realm::{
live_import::{number, realms, reset_b},
live_projection::fixture_character,
profile::probe_capabilities,
},
session::live_session::{spec, Server},
store::Store,
};
use crate::realm_registry::{advert::advertise, client::RegistryClient};
use coa_registry_proto::{
AccountProvisioning, Listing, Population, Rates, RealmId, RegisterRequest,
REGISTRY_PROTOCOL_VERSION,
};
use std::collections::BTreeMap;
use std::sync::Mutex;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
let base = std::env::var("REGISTRY_URL").expect("REGISTRY_URL");
let root = std::path::PathBuf::from(
std::env::var("COA_REAL_CONTROL_ROOT").expect("disposable root"),
);
assert!(root.starts_with("C:/games/source/candidate-evidence-20261021"));
crate::config::portable::enable(&root).expect("owner portable-character opt-in");
let databases = realms().expect("disposable databases");
reset_b(&databases.b);
let server = Server::start(spec().expect("disposable worldserver"));
struct Auth(std::process::Child);
impl Drop for Auth {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
let auth_port = crate::layout::read_ports(&root).auth;
assert_eq!(
auth_port, 57637,
"Only the disposable auth port may be used"
);
assert!(std::net::TcpStream::connect(("127.0.0.1", auth_port)).is_err());
let mut command = std::process::Command::new(root.join("Core/authserver.exe"));
command
.arg("-c")
.arg(root.join("Core/configs/authserver.conf"))
.current_dir(root.join("Core"))
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x0800_0000);
}
let mut auth = Auth(command.spawn().unwrap());
let end = Instant::now() + Duration::from_secs(30);
while std::net::TcpStream::connect(("127.0.0.1", auth_port)).is_err() {
assert!(
auth.0.try_wait().unwrap().is_none(),
"Disposable authserver exited"
);
assert!(Instant::now() < end, "Disposable authserver did not listen");
std::thread::sleep(Duration::from_millis(100));
}
let mut ra = crate::ra::Ra::connect_to(
server.spec.ra_port,
&server.spec.user,
&server.spec.password,
)
.unwrap();
let caps = probe_capabilities(
&databases.b,
Some(&root.join("Data")),
Some(&mut ra),
&ExtensionRegistry::new(),
)
.unwrap();
let advertised = advertise(&caps).unwrap();
let realm = RealmId::new();
let mut seed = [0u8; 32];
seed[..16].copy_from_slice(Uuid::new_v4().as_bytes());
seed[16..].copy_from_slice(Uuid::new_v4().as_bytes());
let key = ed25519_dalek::SigningKey::from_bytes(&seed);
let clock = || {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs() as i64
};
let registry = RegistryClient::new(&base).unwrap();
let listing = Listing {
display_name: "Real portable candidate gate".into(),
description: "Disposable database and real worldserver test".into(),
language: "en".into(),
region: None,
rates: Rates::default(),
modules: vec![],
account_provisioning: AccountProvisioning {
automatic: true,
existing_only: false,
},
manager_version: crate::MANAGER_VERSION.into(),
};
registry
.register(
&key,
&RegisterRequest {
protocol_version: REGISTRY_PROTOCOL_VERSION,
realm_id: realm,
public_key: coa_registry_proto::sign::encode_public_key(&key.verifying_key()),
listing_hash: listing.hash(),
listing,
capabilities_hash: advertised.advert_hash(),
capabilities: advertised,
population: Population {
players: 0,
bots: 0,
capacity: None,
},
},
clock(),
)
.unwrap();
// Always unpublish this isolated identity, including after a failed assertion.
struct Lease(RegistryClient, RealmId, ed25519_dalek::SigningKey);
impl Drop for Lease {
fn drop(&mut self) {
let ts = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs() as i64;
let _ = self.0.unpublish(&self.2, &self.1, ts);
}
}
let _lease = Lease(registry, realm, key.clone());
let temporary = tempdir().unwrap();
let settings_dir = temporary.path().join("registry");
let local_id = "srv-live-candidate";
let mut cfg = settings::RegistrySettings::default();
cfg.realms.insert(
local_id.into(),
settings::PublishConfig {
realm_id: Some(realm),
enabled: true,
display_name: "Candidate".into(),
description: String::new(),
language: "en".into(),
region: None,
existing_only: false,
allow_portable: true,
route: None,
},
);
settings::save(&settings_dir, &cfg).unwrap();
let installed = root.clone();
let runtime = Arc::new(
PortableRuntime::start(
&temporary.path().join("portable"),
Box::new(move || vec![("live-candidate".into(), installed.clone())]),
None,
)
.unwrap(),
);
let installed = root.clone();
let backend = LocalBackend::new(
runtime.clone(),
&settings_dir,
temporary.path().join("descriptors"),
Arc::new(move || vec![("live-candidate".into(), installed.clone())]),
);
assert_eq!(
backend.info(local_id).unwrap().ruleset,
crate::portable::Ruleset::Coa
);
let service = Arc::new(HostService::new(
local_id,
realm,
Arc::new(Mutex::new(ControlStore::open_in_memory().unwrap())),
Arc::new(backend),
));
let relay = crate::control::relay_link::RelayLink::start_with_local_ports(
coordinator_url(&base, "/relay/v1/host").unwrap(),
realm,
key.clone(),
auth_port,
Some(57638),
);
service.set_relay(relay.clone());
let mut link = HostLink::start(
coordinator_url(&base, "/coord/v1/host").unwrap(),
realm,
key.clone(),
service,
Arc::new(clock),
);
let deadline = Instant::now() + Duration::from_secs(20);
while !link.status().connected && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(100));
}
assert!(link.status().connected, "{:?}", link.status());
let player_secrets = Arc::new(MemoryStore::default());
let player = Arc::new(
PlayerControl::open(&temporary.path().join("player"), player_secrets.clone()).unwrap(),
);
let target = RealmTarget {
realm_id: realm,
key: key.verifying_key(),
coordinator: coordinator_url(&base, "/coord/v1/player").unwrap(),
};
let mut channel = player.connect(&target).unwrap();
let account = player
.ensure_account(&mut channel, &realm, Some("REALPORTABLEGATE"))
.unwrap();
let until = Instant::now() + Duration::from_secs(20);
while !relay.status().connected && Instant::now() < until {
std::thread::sleep(Duration::from_millis(100));
}
assert!(relay.status().connected, "{:?}", relay.status());
let allocation = player.allocate_relay(&mut channel).unwrap();
use std::io::{Read, Write};
let mut auth_client =
std::net::TcpStream::connect((allocation.relay_host.as_str(), allocation.auth_port))
.unwrap();
auth_client
.set_read_timeout(Some(Duration::from_secs(10)))
.unwrap();
let username = account.username.to_ascii_uppercase();
let mut challenge = vec![0, 0];
challenge.extend_from_slice(&((30 + username.len()) as u16).to_le_bytes());
challenge.extend_from_slice(b"WoW\0");
challenge.extend_from_slice(&[3, 3, 5]);
challenge.extend_from_slice(&12340u16.to_le_bytes());
challenge.extend_from_slice(b"68x\0niW\0SUne");
challenge.extend_from_slice(&0u32.to_le_bytes());
challenge.extend_from_slice(&[127, 0, 0, 1]);
challenge.push(username.len() as u8);
challenge.extend_from_slice(username.as_bytes());
auth_client.write_all(&challenge).unwrap();
let mut response = [0u8; 35];
auth_client.read_exact(&mut response).unwrap();
assert_eq!(
&response[..3],
&[0, 0, 0],
"Real authserver must accept the relay challenge"
);
assert!(response[3..].iter().any(|byte| *byte != 0));
drop(auth_client);
let mut world_client =
std::net::TcpStream::connect((allocation.relay_host.as_str(), allocation.world_port))
.unwrap();
world_client
.set_read_timeout(Some(Duration::from_secs(10)))
.unwrap();
let mut response = [0u8; 44];
world_client.read_exact(&mut response).unwrap();
assert_eq!(
&response[2..4],
&[0xec, 0x01],
"Real worldserver authentication challenge must pass through relay"
);
drop(world_client);
let mut owner = Store::open_in_memory().unwrap();
let profile = owner.default_profile().unwrap();
let character = fixture_character(&databases, &mut owner, profile);
let mut model = owner.load_current(character).unwrap();
model.progression.level = 50;
model.progression.xp = 0;
let hidden_items = model.items.len();
let owner_path = temporary.path().join("player-portable");
let owner_runtime =
Arc::new(PortableRuntime::start(&owner_path, Box::new(Vec::new), None).unwrap());
owner_runtime
.call(move |service| {
let profile = service.owner_profile();
service
.owner_mut()
.host_install_copy(profile, &model, 1, "test-owner")
.unwrap();
})
.unwrap();
let public_realm = realm.to_string();
let (bundle, session, revision) = owner_runtime
.call(move |service| {
service.prepare_remote_transfer(&character.to_string(), &public_realm)
})
.unwrap()
.unwrap();
let transferred = player
.transfer_owned_character(
&mut channel,
session,
character.as_uuid(),
"coa",
revision,
&bundle.payload,
bundle.content_hash,
BTreeMap::new(),
)
.unwrap();
assert_eq!(transferred.session_id, session);
assert!(transferred.local_guid > 0);
assert_eq!(
number(
&databases.b,
&format!(
"SELECT level FROM acore_characters.characters WHERE guid = {}",
transferred.local_guid
)
),
50
);
let retry = player
.transfer_owned_character(
&mut channel,
session,
character.as_uuid(),
"coa",
revision,
&bundle.payload,
bundle.content_hash,
BTreeMap::new(),
)
.unwrap();
assert_eq!(
(retry.local_guid, retry.session_id),
(transferred.local_guid, transferred.session_id)
);
let pending = player.pending_remote_sessions().unwrap().pop().unwrap();
let mut console = server.ra();
console
.run(&format!("botcmd spawnbot {}", transferred.local_guid))
.unwrap();
let deadline = Instant::now() + Duration::from_secs(90);
let sid = crate::portable::SessionId::from_uuid(session).unwrap();
let mut playing = false;
while Instant::now() < deadline {
player
.sync_remote_session(&pending, &owner_runtime)
.unwrap();
let opened = owner_runtime
.call(move |service| {
service
.owner()
.owner_session_info(sid)
.unwrap()
.is_some_and(|row| row.0 == "open")
})
.unwrap();
if opened
&& crate::portable::session::live_session::online(
&databases.b,
transferred.local_guid,
)
&& console
.run(&format!("portable status {}", transferred.local_guid))
.unwrap_or_default()
.contains("gated 0")
{
playing = true;
break;
}
std::thread::sleep(Duration::from_millis(500));
}
assert!(
playing,
"The actual player never received the Owner's durable baseline acknowledgement"
);
let name =
crate::portable::session::live_session::name_of(&databases.b, transferred.local_guid);
console.run(&format!("character level {name} 51")).unwrap();
// Reopen both Player databases before receiving progress. Recovery uses the pinned realm key and durable session.
owner_runtime.shutdown();
drop(owner_runtime);
drop(player);
let owner_runtime =
Arc::new(PortableRuntime::start(&owner_path, Box::new(Vec::new), None).unwrap());
let player = Arc::new(
PlayerControl::open(&temporary.path().join("player"), player_secrets).unwrap(),
);
let pending = player.pending_remote_sessions().unwrap().pop().unwrap();
let deadline = Instant::now() + Duration::from_secs(90);
let mut saved = false;
while Instant::now() < deadline {
player
.sync_remote_session(&pending, &owner_runtime)
.unwrap();
saved = owner_runtime
.call(move |service| {
service
.owner()
.load_current(character)
.unwrap()
.progression
.level
== 51
})
.unwrap();
if saved {
break;
}
std::thread::sleep(Duration::from_millis(500));
}
assert!(saved, "Real in-game progress was not saved through the public coordinator after Manager restart");
assert!(crate::portable::session::live_session::online(
&databases.b,
transferred.local_guid
));
console
.run(&format!("botcmd despawn {}", transferred.local_guid))
.unwrap();
let deadline = Instant::now() + Duration::from_secs(90);
let mut completed = false;
while Instant::now() < deadline {
if player
.sync_remote_session(&pending, &owner_runtime)
.unwrap()
{
completed = true;
break;
}
std::thread::sleep(Duration::from_millis(500));
}
assert!(
completed,
"The final progress acknowledgement never completed"
);
let next = player.pending_remote_sessions().unwrap().pop().unwrap();
assert_ne!(
next.session_id, session,
"The next login must remain monitored"
);
assert!(owner_runtime
.call(move |service| service.remote_session_idle(next.session_id))
.unwrap()
.unwrap());
// A second login without pressing Play is still supervised and saved.
PlayerControl::start_remote_session_sync(&player, &owner_runtime);
console
.run(&format!("botcmd spawnbot {}", transferred.local_guid))
.unwrap();
let deadline = Instant::now() + Duration::from_secs(90);
let next_sid = crate::portable::SessionId::from_uuid(next.session_id).unwrap();
let mut opened = false;
while Instant::now() < deadline {
opened = owner_runtime
.call(move |service| {
service
.owner()
.owner_session_info(next_sid)
.unwrap()
.is_some_and(|row| row.0 == "open")
})
.unwrap();
if opened {
break;
}
std::thread::sleep(Duration::from_millis(500));
}
assert!(
opened
&& crate::portable::session::live_session::online(
&databases.b,
transferred.local_guid
)
);
console.run(&format!("character level {name} 52")).unwrap();
console
.run(&format!("botcmd despawn {}", transferred.local_guid))
.unwrap();
let deadline = Instant::now() + Duration::from_secs(90);
let mut completed = false;
while Instant::now() < deadline {
if player
.pending_remote_sessions()
.unwrap()
.iter()
.all(|pending| pending.session_id != next.session_id)
{
completed = true;
break;
}
std::thread::sleep(Duration::from_millis(500));
}
assert!(
completed,
"The second login's final checkpoint was not acknowledged"
);
player
.leave_idle_remote_session(character.as_uuid(), &owner_runtime)
.unwrap();
assert!(player.pending_remote_sessions().unwrap().is_empty());
owner_runtime
.call(move |service| {
assert!(service.remote_session_closed(session).unwrap());
let current = service.owner().load_current(character).unwrap();
assert_eq!(current.progression.level, 52);
assert!(
current.items.len() >= hidden_items,
"Hidden equipment was lost"
);
})
.unwrap();
owner_runtime.shutdown();
channel.close();
link.stop();
relay.stop();
runtime.shutdown();
drop(server);
}
#[test]
fn unreadable_or_unknown_realm_fails_closed_in_info() {
let dir = tempdir().unwrap();
let settings = dir.path().join("Settings");
fs::create_dir_all(&settings).unwrap();
fs::write(settings.join("registry.json"), "{}").unwrap();
let desc_dir = dir.path().join("descriptors");
fs::create_dir_all(&desc_dir).unwrap();
let portable_dir = dir.path().join("portable");
let rt = PortableRuntime::start(&portable_dir, Box::new(Vec::new), None).unwrap();
let backend = LocalBackend::new(Arc::new(rt), &settings, &desc_dir, Arc::new(Vec::new));
// Unknown realm id must return Err, never Ok(RealmInfo { ruleset: Ruleset::Coa, .. })
assert!(backend.info("srv-unknown").is_err());
assert!(backend.info("srv-unknown:wildcard").is_err());
assert!(backend.info("srv-unknown:reborn").is_err());
}
#[test]
fn world_port_for_mode_distinguishes_simultaneous_realms() {
let dir = tempdir().unwrap();
let root = dir.path().join("srv");
fs::create_dir_all(root.join("Settings")).unwrap();
fs::write(root.join("Settings/repack.json"), r#"{"worldPort": 8085}"#).unwrap();
fs::write(
root.join("Settings/realm-profile.json"),
r#"{"active": "coa", "wildcard_created": true, "simultaneous": true, "secondary_world_port": 8086}"#,
)
.unwrap();
assert_eq!(
crate::realms::world_port_for_mode(&root, crate::realms::Mode::Coa).unwrap(),
8085
);
assert_eq!(
crate::realms::world_port_for_mode(&root, crate::realms::Mode::Wildcard).unwrap(),
8086
);
let desc_dir = dir.path().join("descriptors");
let portable_dir = dir.path().join("portable");
let rt = PortableRuntime::start(&portable_dir, Box::new(Vec::new), None).unwrap();
let root_clone = root.clone();
let backend = LocalBackend::new(
Arc::new(rt),
root.join("Settings"),
&desc_dir,
Arc::new(move || vec![("test1".to_string(), root_clone.clone())]),
);
assert_eq!(backend.auth_port("srv-test1:coa").unwrap(), 3724);
fs::write(
root.join("Settings/repack.json"),
r#"{"worldPort":8085,"authPort":57324}"#,
)
.unwrap();
assert_eq!(backend.auth_port("srv-test1:coa").unwrap(), 57324);
assert_eq!(backend.auth_port("srv-test1:wildcard").unwrap(), 57324);
fs::write(
root.join("Settings/repack.json"),
r#"{"worldPort":8085,"authPort":0}"#,
)
.unwrap();
assert!(backend.auth_port("srv-test1:coa").is_err());
fs::write(
root.join("Settings/repack.json"),
r#"{"worldPort":8085,"authPort":57324}"#,
)
.unwrap();
assert_eq!(backend.world_port("srv-test1:coa").unwrap(), 8085);
assert_eq!(backend.world_port("srv-test1:wildcard").unwrap(), 8086);
// When simultaneous is false and active is CoA:
fs::write(
root.join("Settings/realm-profile.json"),
r#"{"active": "coa", "wildcard_created": true, "simultaneous": false}"#,
)
.unwrap();
// CoA succeeds with 8085
assert_eq!(backend.world_port("srv-test1:coa").unwrap(), 8085);
// Wildcard must FAIL CLOSED, never return 8085
let err_wc_mode =
crate::realms::world_port_for_mode(&root, crate::realms::Mode::Wildcard).unwrap_err();
assert!(
err_wc_mode.to_string().contains("not active"),
"Expected not active error, got: {err_wc_mode}"
);
assert!(backend.world_port("srv-test1:wildcard").is_err());
// Reborn must FAIL CLOSED
let err_reb_mode =
crate::realms::world_port_for_mode(&root, crate::realms::Mode::Reborn).unwrap_err();
assert!(
err_reb_mode.to_string().contains("not active"),
"Expected not active error, got: {err_reb_mode}"
);
assert!(backend.world_port("srv-test1:reborn").is_err());
// When active is Reborn:
fs::write(
root.join("Settings/realm-profile.json"),
r#"{"active": "reborn", "wildcard_created": true, "reborn_created": true, "simultaneous": false}"#,
)
.unwrap();
// Reborn succeeds with primary world port 8085
assert_eq!(backend.world_port("srv-test1:reborn").unwrap(), 8085);
// CoA must FAIL CLOSED when Reborn is active
assert!(backend.world_port("srv-test1:coa").is_err());
// Wildcard must FAIL CLOSED when Reborn is active
assert!(backend.world_port("srv-test1:wildcard").is_err());
// Malformed and unknown suffixes must fail closed
assert!(backend.access("srv-test1:unknown").is_err());
assert!(backend.access("srv-test1:garbage").is_err());
assert!(backend.access("srv-test1:coa:extra").is_err());
assert!(backend.world_port("srv-test1:unknown").is_err());
assert!(backend.world_port("srv-test1:garbage").is_err());
}
#[test]
fn world_port_lookup_failure_causes_direct_and_relay_to_fail_closed() {
let dir = tempdir().unwrap();
let root = dir.path().join("srv");
fs::create_dir_all(root.join("Settings")).unwrap();
fs::write(root.join("Settings/repack.json"), r#"{"worldPort": 8085}"#).unwrap();
// Server only has active CoA, simultaneous is off
fs::write(
root.join("Settings/realm-profile.json"),
r#"{"active": "coa", "wildcard_created": false, "simultaneous": false}"#,
)
.unwrap();
let desc_dir = dir.path().join("descriptors");
let portable_dir = dir.path().join("portable");
let rt = PortableRuntime::start(&portable_dir, Box::new(Vec::new), None).unwrap();
let root_clone = root.clone();
let backend = Arc::new(LocalBackend::new(
Arc::new(rt),
root.join("Settings"),
&desc_dir,
Arc::new(move || vec![("test1".to_string(), root_clone.clone())]),
));
let store = Arc::new(std::sync::Mutex::new(
crate::control::store::ControlStore::open_in_memory().unwrap(),
));
let service = Arc::new(crate::control::service::HostService::new(
"srv-test1:wildcard",
coa_registry_proto::sign::RealmId::new(),
store,
backend,
));
// 1. HostService::local_world_port fails closed
assert!(service.local_world_port().is_err());
// 2. Direct route manager cannot find a direct route because world port resolution failed
let mut direct_mgr =
crate::control::direct_route::DirectRouteManager::start(None, service.clone());
assert!(!direct_mgr.is_direct_ready());
assert!(service.direct_route().is_none());
direct_mgr.shutdown();
// 3. When relay link has no world port resolved, AllocateRelay refuses
let mut session = crate::control::service::Session::default();
let player = uuid::Uuid::now_v7();
let resp = service.handle(
&mut session,
&player,
"KEY",
coa_control_proto::app::Request::AllocateRelay { player_id: player },
);
assert!(matches!(
resp,
coa_control_proto::app::Response::Error {
code: coa_control_proto::app::AppError::NoAccount
| coa_control_proto::app::AppError::RelayUnavailable,
..
}
));
}
} }
+171 -47
View File
@@ -33,8 +33,13 @@ impl DirectIngress {
local_auth_port: u16, local_auth_port: u16,
local_world_port: u16, local_world_port: u16,
) -> Result<Self> { ) -> Result<Self> {
let auth_host = if auth_bind_port == 0 {
"127.0.0.1"
} else {
"0.0.0.0"
};
let auth_listener = let auth_listener =
TcpListener::bind(format!("0.0.0.0:{auth_bind_port}")).map_err(|e| { TcpListener::bind(format!("{auth_host}:{auth_bind_port}")).map_err(|e| {
Error::Invalid(format!( Error::Invalid(format!(
"Cannot bind direct auth listener on port {auth_bind_port}: {e}" "Cannot bind direct auth listener on port {auth_bind_port}: {e}"
)) ))
@@ -47,8 +52,13 @@ impl DirectIngress {
.map_err(|e| Error::Invalid(e.to_string()))? .map_err(|e| Error::Invalid(e.to_string()))?
.port(); .port();
let world_host = if world_bind_port == 0 {
"127.0.0.1"
} else {
"0.0.0.0"
};
let world_listener = let world_listener =
TcpListener::bind(format!("0.0.0.0:{world_bind_port}")).map_err(|e| { TcpListener::bind(format!("{world_host}:{world_bind_port}")).map_err(|e| {
Error::Invalid(format!( Error::Invalid(format!(
"Cannot bind direct world listener on port {world_bind_port}: {e}" "Cannot bind direct world listener on port {world_bind_port}: {e}"
)) ))
@@ -114,7 +124,11 @@ impl DirectIngress {
std::thread::Builder::new() std::thread::Builder::new()
.name("direct-world-worker".into()) .name("direct-world-worker".into())
.spawn(move || { .spawn(move || {
let _ = handle_world_client(client_stream, local_world_port); if let Err(e) =
handle_world_client(client_stream, local_world_port)
{
eprintln!("handle_world_client error: {e}");
}
}) })
.ok(); .ok();
} }
@@ -174,8 +188,21 @@ fn handle_auth_client(
local_auth_port: u16, local_auth_port: u16,
world_target: Arc<std::sync::RwLock<String>>, world_target: Arc<std::sync::RwLock<String>>,
) -> Result<()> { ) -> Result<()> {
let mut server = TcpStream::connect(format!("127.0.0.1:{local_auth_port}")) let mut server = None;
.map_err(|e| Error::Invalid(format!("Cannot connect to local authserver: {e}")))?; for _ in 0..5 {
match TcpStream::connect(format!("127.0.0.1:{local_auth_port}")) {
Ok(s) => {
server = Some(s);
break;
}
Err(_) => std::thread::sleep(Duration::from_millis(20)),
}
}
let mut server = server.ok_or_else(|| {
Error::Invalid(format!(
"Cannot connect to local authserver: {local_auth_port}"
))
})?;
let _ = client.set_read_timeout(Some(Duration::from_millis(500))); let _ = client.set_read_timeout(Some(Duration::from_millis(500)));
let _ = server.set_read_timeout(Some(Duration::from_millis(500))); let _ = server.set_read_timeout(Some(Duration::from_millis(500)));
@@ -213,7 +240,7 @@ fn handle_auth_client(
} }
done_c.store(true, Ordering::Relaxed); done_c.store(true, Ordering::Relaxed);
if let Some(s) = server_shutdown { if let Some(s) = server_shutdown {
let _ = s.shutdown(std::net::Shutdown::Both); let _ = s.shutdown(std::net::Shutdown::Write);
} }
}); });
@@ -261,8 +288,21 @@ fn handle_auth_client(
} }
fn handle_world_client(mut client: TcpStream, local_world_port: u16) -> Result<()> { fn handle_world_client(mut client: TcpStream, local_world_port: u16) -> Result<()> {
let mut server = TcpStream::connect(format!("127.0.0.1:{local_world_port}")) let mut server = None;
.map_err(|e| Error::Invalid(format!("Cannot connect to local worldserver: {e}")))?; for _ in 0..5 {
match TcpStream::connect(format!("127.0.0.1:{local_world_port}")) {
Ok(s) => {
server = Some(s);
break;
}
Err(_) => std::thread::sleep(Duration::from_millis(20)),
}
}
let mut server = server.ok_or_else(|| {
Error::Invalid(format!(
"Cannot connect to local worldserver: {local_world_port}"
))
})?;
let _ = client.set_nonblocking(false); let _ = client.set_nonblocking(false);
let _ = server.set_nonblocking(false); let _ = server.set_nonblocking(false);
@@ -278,11 +318,11 @@ fn handle_world_client(mut client: TcpStream, local_world_port: u16) -> Result<(
let t_c2s = std::thread::spawn(move || { let t_c2s = std::thread::spawn(move || {
let _ = std::io::copy(&mut client_read, &mut server_write); let _ = std::io::copy(&mut client_read, &mut server_write);
let _ = server_write.shutdown(std::net::Shutdown::Both); let _ = server_write.shutdown(std::net::Shutdown::Write);
}); });
let _ = std::io::copy(&mut server, &mut client); let _ = std::io::copy(&mut server, &mut client);
let _ = client.shutdown(std::net::Shutdown::Both); let _ = client.shutdown(std::net::Shutdown::Write);
let _ = t_c2s.join(); let _ = t_c2s.join();
Ok(()) Ok(())
@@ -320,6 +360,7 @@ mod tests {
let n = stream.read(&mut buf).unwrap(); let n = stream.read(&mut buf).unwrap();
assert_eq!(&buf[..n], b"WORLD_PING"); assert_eq!(&buf[..n], b"WORLD_PING");
stream.write_all(b"WORLD_PONG").unwrap(); stream.write_all(b"WORLD_PONG").unwrap();
stream.flush().unwrap();
let _ = stream.shutdown(std::net::Shutdown::Write); let _ = stream.shutdown(std::net::Shutdown::Write);
}); });
@@ -337,25 +378,27 @@ mod tests {
let mut buf = [0u8; 16]; let mut buf = [0u8; 16];
let _ = stream.read(&mut buf).unwrap(); let _ = stream.read(&mut buf).unwrap();
let mut fake_realm_list = vec![ let name_bytes = b"RealmOne\0";
0x10, // Opcode CMD_REALM_LIST let addr_bytes = b"127.0.0.1:8085\0";
0x00, 0x00, // Size placeholder let body_len = 4 + 2 + 3 + name_bytes.len() + addr_bytes.len() + 4 + 1 + 1 + 1 + 2;
0x00, 0x00, 0x00, 0x00, // Unused
0x01, 0x00, // Realm count: 1
0x01, 0x00, 0x00, 0x00, // Icon
0x00, // Lock
0x00, // Flags
];
fake_realm_list.extend_from_slice(b"RealmOne\0");
fake_realm_list.extend_from_slice(b"127.0.0.1:8085\0"); // original target
fake_realm_list.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // Population
fake_realm_list.extend_from_slice(&[0x01]); // Num characters
fake_realm_list.extend_from_slice(&[0x01]); // Timezone
fake_realm_list.extend_from_slice(&[0x00]); // Realm ID
fake_realm_list.extend_from_slice(&[0x02, 0x00]); // Footer
let body_len = (fake_realm_list.len() - 3) as u16; let mut fake_realm_list = Vec::new();
fake_realm_list[1..3].copy_from_slice(&body_len.to_le_bytes()); fake_realm_list.push(0x10); // Opcode
fake_realm_list.extend_from_slice(&(body_len as u16).to_le_bytes()); // Length
fake_realm_list.extend_from_slice(&0u32.to_le_bytes()); // Unused
fake_realm_list.extend_from_slice(&1u16.to_le_bytes()); // Realm count = 1
// Realm info:
fake_realm_list.extend_from_slice(&[1, 0, 0]); // type, lock, flag
fake_realm_list.extend_from_slice(name_bytes);
fake_realm_list.extend_from_slice(addr_bytes);
fake_realm_list.extend_from_slice(&[0, 0, 0, 0]); // pop
fake_realm_list.extend_from_slice(&[0]); // chars
fake_realm_list.extend_from_slice(&[1]); // timezone
fake_realm_list.extend_from_slice(&[1]); // realm id
// Footer:
fake_realm_list.extend_from_slice(&[0x10, 0x00]);
stream.write_all(&fake_realm_list).unwrap(); stream.write_all(&fake_realm_list).unwrap();
let _ = stream.shutdown(std::net::Shutdown::Write); let _ = stream.shutdown(std::net::Shutdown::Write);
@@ -386,7 +429,7 @@ mod tests {
let mock_world_port = mock_world.local_addr().unwrap().port(); let mock_world_port = mock_world.local_addr().unwrap().port();
// DirectIngress binds to ephemeral ports (0, 0), so actual ingress port != 8085 // DirectIngress binds to ephemeral ports (0, 0), so actual ingress port != 8085
let ingress = DirectIngress::start( let mut ingress = DirectIngress::start(
0, 0,
0, 0,
"198.51.100.1".to_string(), "198.51.100.1".to_string(),
@@ -415,25 +458,27 @@ mod tests {
let mut buf = [0u8; 16]; let mut buf = [0u8; 16];
let _ = stream.read(&mut buf).unwrap(); let _ = stream.read(&mut buf).unwrap();
let mut fake_realm_list = vec![ let name_bytes = b"RealmOne\0";
0x10, // Opcode CMD_REALM_LIST let addr_bytes = b"127.0.0.1:8085\0";
0x00, 0x00, // Size placeholder let body_len = 4 + 2 + 3 + name_bytes.len() + addr_bytes.len() + 4 + 1 + 1 + 1 + 2;
0x00, 0x00, 0x00, 0x00, // Unused
0x01, 0x00, // Realm count: 1
0x01, 0x00, 0x00, 0x00, // Icon
0x00, // Lock
0x00, // Flags
];
fake_realm_list.extend_from_slice(b"RealmOne\0");
fake_realm_list.extend_from_slice(b"127.0.0.1:8085\0");
fake_realm_list.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);
fake_realm_list.extend_from_slice(&[0x01]);
fake_realm_list.extend_from_slice(&[0x01]);
fake_realm_list.extend_from_slice(&[0x00]);
fake_realm_list.extend_from_slice(&[0x02, 0x00]);
let body_len = (fake_realm_list.len() - 3) as u16; let mut fake_realm_list = Vec::new();
fake_realm_list[1..3].copy_from_slice(&body_len.to_le_bytes()); fake_realm_list.push(0x10); // Opcode
fake_realm_list.extend_from_slice(&(body_len as u16).to_le_bytes()); // Length
fake_realm_list.extend_from_slice(&0u32.to_le_bytes()); // Unused
fake_realm_list.extend_from_slice(&1u16.to_le_bytes()); // Realm count = 1
// Realm info:
fake_realm_list.extend_from_slice(&[1, 0, 0]); // type, lock, flag
fake_realm_list.extend_from_slice(name_bytes);
fake_realm_list.extend_from_slice(addr_bytes);
fake_realm_list.extend_from_slice(&[0, 0, 0, 0]); // pop
fake_realm_list.extend_from_slice(&[0]); // chars
fake_realm_list.extend_from_slice(&[1]); // timezone
fake_realm_list.extend_from_slice(&[1]); // realm id
// Footer:
fake_realm_list.extend_from_slice(&[0x10, 0x00]);
stream.write_all(&fake_realm_list).unwrap(); stream.write_all(&fake_realm_list).unwrap();
let _ = stream.shutdown(std::net::Shutdown::Write); let _ = stream.shutdown(std::net::Shutdown::Write);
@@ -462,5 +507,84 @@ mod tests {
drop(client_auth); drop(client_auth);
t_auth.join().unwrap(); t_auth.join().unwrap();
ingress.stop();
}
#[test]
fn test_direct_ingress_wildcard_port_rewrites_to_mapped_port_and_never_advertises_coa_8085() {
let ext_wildcard_port = 48086;
let mock_auth = TcpListener::bind("127.0.0.1:0").unwrap();
let mock_auth_port = mock_auth.local_addr().unwrap().port();
let mock_world = TcpListener::bind("127.0.0.1:0").unwrap();
let mock_world_port = mock_world.local_addr().unwrap().port();
// DirectIngress configured for Wildcard (local_world = mock_world_port, ext_world = 48086)
let mut ingress = DirectIngress::start(
0,
0,
"198.51.100.1".to_string(),
ext_wildcard_port,
mock_auth_port,
mock_world_port,
)
.unwrap();
// Verify Auth rewrite rewrites to external port 48086 and never mentions 8085 or 8086
let t_auth = std::thread::spawn(move || {
let (mut stream, _) = mock_auth.accept().unwrap();
let mut buf = [0u8; 16];
let _ = stream.read(&mut buf).unwrap();
let name_bytes = b"Wildcard\0";
let addr_bytes = b"127.0.0.1:8086\0";
let body_len = 4 + 2 + 3 + name_bytes.len() + addr_bytes.len() + 4 + 1 + 1 + 1 + 2;
let mut fake_realm_list = Vec::new();
fake_realm_list.push(0x10); // Opcode
fake_realm_list.extend_from_slice(&(body_len as u16).to_le_bytes()); // Length
fake_realm_list.extend_from_slice(&0u32.to_le_bytes()); // Unused
fake_realm_list.extend_from_slice(&1u16.to_le_bytes()); // Realm count = 1
// Realm info:
fake_realm_list.extend_from_slice(&[1, 0, 0]); // type, lock, flag
fake_realm_list.extend_from_slice(name_bytes);
fake_realm_list.extend_from_slice(addr_bytes);
fake_realm_list.extend_from_slice(&[0, 0, 0, 0]); // pop
fake_realm_list.extend_from_slice(&[0]); // chars
fake_realm_list.extend_from_slice(&[1]); // timezone
fake_realm_list.extend_from_slice(&[1]); // realm id
// Footer:
fake_realm_list.extend_from_slice(&[0x10, 0x00]);
stream.write_all(&fake_realm_list).unwrap();
let _ = stream.shutdown(std::net::Shutdown::Write);
});
let mut client_auth =
TcpStream::connect(format!("127.0.0.1:{}", ingress.auth_port())).unwrap();
client_auth.write_all(b"AUTH_HELLO").unwrap();
let mut auth_buf = [0u8; 512];
let an = client_auth.read(&mut auth_buf).unwrap();
let payload = String::from_utf8_lossy(&auth_buf[..an]);
assert!(
payload.contains("198.51.100.1:48086"),
"Expected rewritten realm list to contain external port 48086, got: {payload}"
);
assert!(
!payload.contains("8085"),
"DirectIngress for Wildcard must never advertise CoA port 8085"
);
assert!(
!payload.contains(":8086"),
"DirectIngress for Wildcard must rewrite internal port 8086 to external 48086"
);
drop(client_auth);
t_auth.join().unwrap();
ingress.stop();
} }
} }
+33 -4
View File
@@ -303,11 +303,40 @@ fn attempt_route_discovery(
let local_auth = std::env::var("COA_OVERRIDE_LOCAL_AUTH_PORT") let local_auth = std::env::var("COA_OVERRIDE_LOCAL_AUTH_PORT")
.ok() .ok()
.and_then(|p| p.parse().ok()) .and_then(|p| p.parse().ok())
.unwrap_or(coa_control_proto::relay::LOCAL_AUTH_PORT); .map(Ok)
let local_world = std::env::var("COA_OVERRIDE_LOCAL_WORLD_PORT") .unwrap_or_else(|| service.local_auth_port());
let local_auth = match local_auth {
Ok(port) => port,
Err(error) => {
set_status(
status,
RouteStatus::RelayOnly {
reason: format!("Cannot resolve local auth port: {error}"),
},
);
service.set_direct_route(None);
return;
}
};
let local_world = match std::env::var("COA_OVERRIDE_LOCAL_WORLD_PORT")
.ok() .ok()
.and_then(|p| p.parse().ok()) .and_then(|p| p.parse().ok())
.unwrap_or(coa_control_proto::relay::LOCAL_WORLD_PORT); {
Some(p) => p,
None => match service.local_world_port() {
Ok(p) => p,
Err(e) => {
set_status(
status,
RouteStatus::RelayOnly {
reason: format!("Cannot resolve local world port: {e}"),
},
);
service.set_direct_route(None);
return;
}
},
};
let desired_auth_port: u16 = std::env::var("COA_DIRECT_AUTH_PORT") let desired_auth_port: u16 = std::env::var("COA_DIRECT_AUTH_PORT")
.ok() .ok()
@@ -316,7 +345,7 @@ fn attempt_route_discovery(
let desired_world_port: u16 = std::env::var("COA_DIRECT_WORLD_PORT") let desired_world_port: u16 = std::env::var("COA_DIRECT_WORLD_PORT")
.ok() .ok()
.and_then(|p| p.parse().ok()) .and_then(|p| p.parse().ok())
.unwrap_or(8085); .unwrap_or(local_world);
let ingress = match DirectIngress::start( let ingress = match DirectIngress::start(
desired_auth_port, desired_auth_port,
+1 -1
View File
@@ -159,7 +159,7 @@ fn session(
) -> Result<(), LinkError> { ) -> Result<(), LinkError> {
let mut ws = transport::connect(url, POLL)?; let mut ws = transport::connect(url, POLL)?;
let nonce = match transport::next_frame(&mut ws, Duration::from_secs(15))? { let nonce = match transport::next_frame(&mut ws, Duration::from_secs(15))? {
Frame::Challenge { nonce, .. } => nonce, Frame::Challenge { protocol, nonce } if protocol == coord::COORDINATOR_PROTOCOL_VERSION => nonce,
_ => return Err(LinkError::Protocol("a challenge was expected".into())), _ => return Err(LinkError::Protocol("a challenge was expected".into())),
}; };
transport::send_text( transport::send_text(
+28 -13
View File
@@ -24,6 +24,7 @@ pub struct HostControlRealm {
pub local_id: String, pub local_id: String,
pub realm_id: String, pub realm_id: String,
pub link: LinkStatus, pub link: LinkStatus,
pub relay: Option<crate::control::relay_link::RelayStatus>,
} }
pub struct HostControl { pub struct HostControl {
@@ -35,6 +36,7 @@ pub struct HostControl {
struct Running { struct Running {
realm_id: RealmId, realm_id: RealmId,
url: String, url: String,
ports: Option<(u16, u16)>,
link: HostLink, link: HostLink,
#[allow(dead_code)] #[allow(dead_code)]
relay_link: Option<Arc<crate::control::relay_link::RelayLink>>, relay_link: Option<Arc<crate::control::relay_link::RelayLink>>,
@@ -83,7 +85,7 @@ impl HostControl {
running.retain(|id, r| { running.retain(|id, r| {
wanted wanted
.get(id) .get(id)
.is_some_and(|(realm, url, _, _)| *realm == r.realm_id && *url == r.url) .is_some_and(|(realm, url, _, _)| *realm == r.realm_id && *url == r.url && backend.auth_port(id).ok().zip(backend.world_port(id).ok()) == r.ports)
}); });
for (local_id, (realm_id, url, base, key)) in wanted { for (local_id, (realm_id, url, base, key)) in wanted {
if running.contains_key(&local_id) { if running.contains_key(&local_id) {
@@ -95,18 +97,29 @@ impl HostControl {
store.clone(), store.clone(),
backend.clone(), backend.clone(),
)); ));
let relay_link = let ports = service.local_auth_port().ok().zip(service.local_world_port().ok());
crate::control::transport::relay_url(&base, "/relay/v1/host").map( let relay_link = match ports {
|r_url| { Some((auth_port, world_port)) => {
let rl = crate::control::relay_link::RelayLink::start( crate::control::transport::relay_url(&base, "/relay/v1/host").map(
r_url, |r_url| {
realm_id, let rl =
key.clone(), crate::control::relay_link::RelayLink::start_with_local_ports(
); r_url,
service.set_relay(rl.clone()); realm_id,
rl key.clone(),
}, auth_port,
); Some(world_port),
);
service.set_relay(rl.clone());
rl
},
)
}
None => {
tracing::warn!(%local_id, "relay is waiting for valid local auth and world ports");
None
}
};
let direct_route = let direct_route =
Some(crate::control::direct_route::DirectRouteManager::start( Some(crate::control::direct_route::DirectRouteManager::start(
Some(base.clone()), Some(base.clone()),
@@ -119,6 +132,7 @@ impl HostControl {
Running { Running {
realm_id, realm_id,
url, url,
ports,
link, link,
relay_link, relay_link,
direct_route, direct_route,
@@ -135,6 +149,7 @@ impl HostControl {
local_id: id.clone(), local_id: id.clone(),
realm_id: r.realm_id.to_string(), realm_id: r.realm_id.to_string(),
link: r.link.status(), link: r.link.status(),
relay: r.relay_link.as_ref().map(|relay| relay.status()),
}, },
) )
}) })
+46 -12
View File
@@ -20,6 +20,8 @@ use super::store::{AccountKind, ControlStore};
use super::transport::{self, LinkError}; use super::transport::{self, LinkError};
use crate::{Error, Result}; use crate::{Error, Result};
mod portable_sync;
/// Where and as whom to reach a realm. /// Where and as whom to reach a realm.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct RealmTarget { pub struct RealmTarget {
@@ -115,6 +117,7 @@ pub struct AccountOutcome {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Claimed { pub struct Claimed {
pub character_id: Uuid, pub character_id: Uuid,
pub ruleset: String,
pub payload: Vec<u8>, pub payload: Vec<u8>,
pub sha256: [u8; 32], pub sha256: [u8; 32],
pub collections: BTreeMap<String, Vec<u32>>, pub collections: BTreeMap<String, Vec<u32>>,
@@ -347,13 +350,14 @@ impl PlayerControl {
pub fn claim(&self, ch: &mut PlayerChannel, token: u32) -> R<Claimed> { pub fn claim(&self, ch: &mut PlayerChannel, token: u32) -> R<Claimed> {
let r = ch.request(&Request::Claim { token })?; let r = ch.request(&Request::Claim { token })?;
let (character_id, sha256, payload, collections) = expect(r, |r| match r { let (character_id, ruleset, sha256, payload, collections) = expect(r, |r| match r {
Response::Claimed { Response::Claimed {
character_id, character_id,
ruleset,
sha256, sha256,
payload, payload,
collections, collections,
} => Ok((character_id, sha256, payload, collections)), } => Ok((character_id, ruleset, sha256, payload, collections)),
other => Err(other), other => Err(other),
})?; })?;
let payload = base64::engine::general_purpose::STANDARD let payload = base64::engine::general_purpose::STANDARD
@@ -373,6 +377,7 @@ impl PlayerControl {
})?; })?;
Ok(Claimed { Ok(Claimed {
character_id, character_id,
ruleset,
payload, payload,
sha256: hash, sha256: hash,
collections, collections,
@@ -409,24 +414,39 @@ impl PlayerControl {
} }
/// Transfer a portable character to a remote realm over the verified control channel (Phase 12.1). /// Transfer a portable character to a remote realm over the verified control channel (Phase 12.1).
pub fn transfer_character( fn transfer_with_id(
&self, &self,
ch: &mut PlayerChannel, ch: &mut PlayerChannel,
transfer_id: Uuid,
owned_session: bool,
character_id: Uuid, character_id: Uuid,
ruleset: &str,
canonical_revision: u64, canonical_revision: u64,
payload: &[u8], payload: &[u8],
content_hash: [u8; 32], content_hash: [u8; 32],
collections: BTreeMap<String, Vec<u32>>, collections: BTreeMap<String, Vec<u32>>,
) -> R<RemoteTransferOutcome> { ) -> R<RemoteTransferOutcome> {
let transfer_id = Uuid::now_v7();
let content_hash_str = hex::encode(content_hash); let content_hash_str = hex::encode(content_hash);
let offer = Request::TransferOffer { let offer = if owned_session {
transfer_id, Request::OwnedTransferOffer {
character_id, transfer_id,
canonical_revision, character_id,
content_hash: content_hash_str.clone(), ruleset: ruleset.to_string(),
total_size: payload.len(), canonical_revision,
collections, content_hash: content_hash_str.clone(),
total_size: payload.len(),
collections,
}
} else {
Request::TransferOffer {
transfer_id,
character_id,
ruleset: ruleset.to_string(),
canonical_revision,
content_hash: content_hash_str.clone(),
total_size: payload.len(),
collections,
}
}; };
let r = ch.request(&offer)?; let r = ch.request(&offer)?;
let mut offset = match r { let mut offset = match r {
@@ -451,7 +471,21 @@ impl PlayerControl {
notes, notes,
}); });
} }
Response::Error { code, message } => return Err(ControlFail::App { code, message }), Response::Error { code, message } => {
if owned_session
&& matches!(
code,
AppError::Incompatible
| AppError::NotYours
| AppError::AlreadyClaimed
| AppError::Invalid
)
{
self.store()?
.player_remote_session_remove(character_id, transfer_id)?;
}
return Err(ControlFail::App { code, message });
}
_ => { _ => {
return Err(ControlFail::Link(LinkError::Protocol( return Err(ControlFail::Link(LinkError::Protocol(
"unexpected response to transfer offer".into(), "unexpected response to transfer offer".into(),
@@ -0,0 +1,290 @@
use super::*;
use crate::control::store::PlayerRemoteSession;
use crate::portable::service::PortableRuntime;
use base64::engine::general_purpose::STANDARD as B64;
use sha2::{Digest, Sha256};
fn protocol_error(message: &str) -> ControlFail {
ControlFail::Link(LinkError::Protocol(message.into()))
}
impl PlayerControl {
/// Compatibility helper for transport tests. Interactive play uses the Owner's durable session id.
pub fn transfer_character(
&self,
channel: &mut PlayerChannel,
character: Uuid,
ruleset: &str,
revision: u64,
payload: &[u8],
hash: [u8; 32],
collections: BTreeMap<String, Vec<u32>>,
) -> R<RemoteTransferOutcome> {
self.transfer_with_id(
channel,
Uuid::now_v7(),
false,
character,
ruleset,
revision,
payload,
hash,
collections,
)
}
pub fn transfer_owned_character(
&self,
channel: &mut PlayerChannel,
session: Uuid,
character: Uuid,
ruleset: &str,
revision: u64,
payload: &[u8],
hash: [u8; 32],
collections: BTreeMap<String, Vec<u32>>,
) -> R<RemoteTransferOutcome> {
self.store()?
.player_remote_session_set(&PlayerRemoteSession {
character_id: character,
realm_id: channel.realm_id.to_string(),
session_id: session,
public_key: coord::encode_public_key(&channel.realm_key),
coordinator: channel.coordinator.clone(),
})?;
let result = self.transfer_with_id(
channel,
session,
true,
character,
ruleset,
revision,
payload,
hash,
collections,
);
if let Ok(outcome) = &result {
if outcome.session_id != session {
return Err(protocol_error(
"The Host returned another portable session.",
));
}
}
result
}
pub fn pending_remote_sessions(&self) -> R<Vec<PlayerRemoteSession>> {
Ok(self.store()?.player_remote_sessions()?)
}
/// An idle, already-saved realm may be left; an uncertain or open session must finish first.
pub fn leave_idle_remote_session(&self, character: Uuid, runtime: &PortableRuntime) -> R<()> {
for pending in self
.pending_remote_sessions()?
.into_iter()
.filter(|pending| pending.character_id == character)
{
let sid = pending.session_id;
let idle = runtime
.call(move |service| service.remote_session_idle(sid))
.map_err(|error| ControlFail::Local(error.to_string()))?
.map_err(|error| ControlFail::Local(error.message))?;
if !idle {
return Err(ControlFail::Local("Progress from the previous realm is still being saved. Keep both Managers running until it finishes.".into()));
}
self.store()?.player_remote_session_remove(character, sid)?;
}
Ok(())
}
/// Persist the Owner's acknowledgement before acknowledging it to the Host. A lost reply is retried without making another revision.
pub fn sync_remote_session(
&self,
pending: &PlayerRemoteSession,
runtime: &PortableRuntime,
) -> R<bool> {
let mut channel = self.remote_session_channel(pending)?;
self.sync_remote_session_on_channel(pending, runtime, &mut channel)
}
fn remote_session_channel(&self, pending: &PlayerRemoteSession) -> R<PlayerChannel> {
let realm = RealmId::parse(&pending.realm_id)
.map_err(|error| ControlFail::Local(error.to_string()))?;
let key = coord::decode_public_key(&pending.public_key)
.map_err(|error| protocol_error(&error.to_string()))?;
let target = RealmTarget {
realm_id: realm,
key,
coordinator: pending.coordinator.clone(),
};
self.connect(&target)
}
fn sync_remote_session_on_channel(
&self,
pending: &PlayerRemoteSession,
runtime: &PortableRuntime,
channel: &mut PlayerChannel,
) -> R<bool> {
let character_id = pending.character_id;
let session_id = pending.session_id;
for _ in 0..16 {
let (kind, total_size, content_hash) = match channel.request(&Request::SessionPoll {
character_id,
session_id,
})? {
Response::SessionIdle { closed } => {
if closed {
let locally_closed = runtime
.call(move |service| service.remote_session_closed(session_id))
.map_err(|error| ControlFail::Local(error.to_string()))?
.map_err(|error| ControlFail::Local(error.message))?;
if !locally_closed {
return Err(protocol_error(
"The Host closed a session before the Owner saved it.",
));
}
let realm = pending.realm_id.clone();
let next = runtime
.call(move |service| service.next_remote_session(character_id, &realm))
.map_err(|error| ControlFail::Local(error.to_string()))?
.map_err(|error| ControlFail::Local(error.message))?;
if let Some(next) = next {
self.store()?.player_remote_session_advance(
character_id,
session_id,
next,
)?;
} else {
self.store()?
.player_remote_session_remove(character_id, session_id)?;
}
return Ok(true);
}
return Ok(false);
}
Response::SessionPending {
kind,
total_size,
content_hash,
} if total_size > 0
&& total_size <= app::MAX_SESSION_BYTES
&& content_hash.len() == 64 =>
{
(kind, total_size, content_hash)
}
Response::Error { code, message } => {
return Err(ControlFail::App { code, message })
}
_ => return Err(protocol_error("Invalid portable session metadata.")),
};
let mut bytes = Vec::with_capacity(total_size);
while bytes.len() < total_size {
match channel.request(&Request::SessionRead {
character_id,
session_id,
message_hash: content_hash.clone(),
offset: bytes.len(),
})? {
Response::SessionData { offset, data } if offset == bytes.len() => {
let chunk = B64
.decode(data)
.map_err(|_| protocol_error("Invalid portable session chunk."))?;
if chunk.is_empty() || chunk.len() > total_size - bytes.len() {
return Err(protocol_error("Invalid portable session chunk bounds."));
}
bytes.extend_from_slice(&chunk);
}
Response::Error { code, message } => {
return Err(ControlFail::App { code, message })
}
_ => return Err(protocol_error("Invalid portable session chunk offset.")),
}
}
if hex::encode(Sha256::digest(&bytes)) != content_hash {
return Err(protocol_error("The portable session message hash changed."));
}
let remote_realm = pending.realm_id.clone();
let ack = runtime
.call(move |service| {
service.apply_remote_session_message(
character_id,
session_id,
&remote_realm,
kind,
&bytes,
)
})
.map_err(|error| ControlFail::Local(error.to_string()))?
.map_err(|error| ControlFail::Local(error.message))?;
let mut offset = 0;
while offset < ack.len() {
let end = ack.len().min(offset + 24 * 1024);
match channel.request(&Request::SessionAck {
character_id,
session_id,
message_hash: content_hash.clone(),
offset,
total_size: ack.len(),
data: B64.encode(&ack[offset..end]),
})? {
Response::SessionAcked {
received_size,
complete,
} if received_size > offset
&& received_size <= ack.len()
&& (!complete || received_size == ack.len()) =>
{
offset = received_size
}
Response::Error { code, message } => {
return Err(ControlFail::App { code, message })
}
_ => return Err(protocol_error("Invalid portable acknowledgement offset.")),
}
}
}
Ok(false)
}
/// Independent of the visible page and the game process. Durable sessions resume after a Manager restart.
pub fn start_remote_session_sync(player: &Arc<Self>, runtime: &Arc<PortableRuntime>) {
let player = Arc::downgrade(player);
let runtime = Arc::downgrade(runtime);
let _ = std::thread::Builder::new().name("portable-remote-sync".into()).spawn(move || {
let mut errors = std::collections::HashMap::<Uuid, String>::new();
let mut channels = std::collections::HashMap::<String, PlayerChannel>::new();
loop {
{
let (Some(player), Some(runtime)) = (player.upgrade(), runtime.upgrade()) else { return };
if let Ok(sessions) = player.pending_remote_sessions() {
let wanted: std::collections::HashSet<_> = sessions.iter().map(|session| format!("{}|{}|{}", session.realm_id, session.public_key, session.coordinator)).collect();
channels.retain(|key, _| wanted.contains(key));
for session in sessions {
let key = format!("{}|{}|{}", session.realm_id, session.public_key, session.coordinator);
let result = (|| {
if !channels.contains_key(&key) {
if channels.len() >= 8 { channels.clear(); }
channels.insert(key.clone(), player.remote_session_channel(&session)?);
}
player.sync_remote_session_on_channel(&session, &runtime, channels.get_mut(&key).expect("inserted"))
})();
match result {
Ok(_) => { errors.remove(&session.character_id); },
Err(error) => {
channels.remove(&key);
let message = error.to_string();
if errors.get(&session.character_id) != Some(&message) {
tracing::warn!(character = %session.character_id, error = %message, "remote portable progress is pending; retrying");
errors.insert(session.character_id, message);
}
}
}
}
}
}
std::thread::sleep(std::time::Duration::from_secs(2));
}
});
}
}
+16 -2
View File
@@ -13,6 +13,9 @@ use super::identity::PlayerIdentity;
use super::transport::{self, LinkError, Ws}; use super::transport::{self, LinkError, Ws};
pub struct PlayerChannel { pub struct PlayerChannel {
pub(crate) realm_id: RealmId,
pub(crate) realm_key: VerifyingKey,
pub(crate) coordinator: String,
ws: Ws, ws: Ws,
channel: Channel, channel: Channel,
conn: u32, conn: u32,
@@ -35,7 +38,11 @@ impl PlayerChannel {
Duration::from_millis(500), Duration::from_millis(500),
)?; )?;
let nonce = match transport::next_frame(&mut ws, STEP)? { let nonce = match transport::next_frame(&mut ws, STEP)? {
Frame::Challenge { nonce, .. } => nonce, Frame::Challenge { protocol, nonce }
if protocol == coord::COORDINATOR_PROTOCOL_VERSION =>
{
nonce
}
_ => return Err(LinkError::Protocol("a challenge was expected".into())), _ => return Err(LinkError::Protocol("a challenge was expected".into())),
}; };
transport::send_text( transport::send_text(
@@ -67,7 +74,14 @@ impl PlayerChannel {
{ {
transport::send_binary(&mut ws, f)?; transport::send_binary(&mut ws, f)?;
} }
Ok(PlayerChannel { ws, channel, conn }) Ok(PlayerChannel {
ws,
channel,
conn,
realm_id: *realm,
realm_key: *realm_key,
coordinator: coordinator.into(),
})
} }
pub fn connection(&self) -> u32 { pub fn connection(&self) -> u32 {
+263 -13
View File
@@ -1,6 +1,6 @@
//! Outbound Host <-> Game Relay tunnel link (Phase 13). //! Outbound Host <-> Game Relay tunnel link (Phase 13).
//! Maintains outbound connectivity from Host Manager to the Game Relay, //! Maintains outbound connectivity from Host Manager to the Game Relay,
//! opening local TCP connections strictly to 127.0.0.1:3724 (Auth) and 127.0.0.1:8085 (World). //! opening local TCP connections only to the installed realm's configured loopback Auth and World ports.
use std::collections::HashMap; use std::collections::HashMap;
use std::io::{Read, Write}; use std::io::{Read, Write};
@@ -71,6 +71,31 @@ impl RelayProvider for RelayLink {
impl RelayLink { impl RelayLink {
pub fn start(url: String, realm_id: RealmId, key: SigningKey) -> Arc<Self> { pub fn start(url: String, realm_id: RealmId, key: SigningKey) -> Arc<Self> {
Self::start_with_ports(url, realm_id, key, None)
}
pub fn start_with_ports(
url: String,
realm_id: RealmId,
key: SigningKey,
local_world_port: Option<u16>,
) -> Arc<Self> {
Self::start_with_local_ports(
url,
realm_id,
key,
RelayTarget::Auth.local_port(),
local_world_port,
)
}
pub fn start_with_local_ports(
url: String,
realm_id: RealmId,
key: SigningKey,
local_auth_port: u16,
local_world_port: Option<u16>,
) -> Arc<Self> {
let stop = Arc::new(AtomicBool::new(false)); let stop = Arc::new(AtomicBool::new(false));
let status = Arc::new(Mutex::new(RelayStatus::default())); let status = Arc::new(Mutex::new(RelayStatus::default()));
let (alloc_tx, alloc_rx) = channel(); let (alloc_tx, alloc_rx) = channel();
@@ -79,7 +104,18 @@ impl RelayLink {
let st = status.clone(); let st = status.clone();
let join = std::thread::Builder::new() let join = std::thread::Builder::new()
.name("control-relay-host".into()) .name("control-relay-host".into())
.spawn(move || run(&url, realm_id, &key, alloc_rx, &s, &st)) .spawn(move || {
run(
&url,
realm_id,
&key,
alloc_rx,
&s,
&st,
local_auth_port,
local_world_port,
)
})
.ok(); .ok();
Arc::new(RelayLink { Arc::new(RelayLink {
@@ -127,11 +163,25 @@ fn run(
)>, )>,
stop: &AtomicBool, stop: &AtomicBool,
status: &Mutex<RelayStatus>, status: &Mutex<RelayStatus>,
local_auth_port: u16,
local_world_port: Option<u16>,
) { ) {
let mut failures = 0u32; let mut failures = 0u32;
while !stop.load(Ordering::SeqCst) { while !stop.load(Ordering::SeqCst) {
let began = Instant::now(); let began = Instant::now();
let result = session(url, realm, key, &alloc_rx, stop, status); let result = session(
url,
realm,
key,
&alloc_rx,
stop,
status,
local_auth_port,
local_world_port,
);
if let Err(error) = &result {
tracing::warn!(%realm, %error, "game relay connection lost; retrying");
}
set_status(status, |s| { set_status(status, |s| {
s.connected = false; s.connected = false;
s.active_streams = 0; s.active_streams = 0;
@@ -163,6 +213,17 @@ fn run(
struct StreamWorker { struct StreamWorker {
tx: Sender<TunnelMsg>, tx: Sender<TunnelMsg>,
reset_on_drop: bool,
shutdown: Arc<TcpStream>,
}
impl Drop for StreamWorker {
fn drop(&mut self) {
if self.reset_on_drop {
let _ = self.shutdown.shutdown(std::net::Shutdown::Both);
let _ = self.tx.send(TunnelMsg::Reset { stream_id: 0 });
}
}
} }
fn session( fn session(
@@ -176,6 +237,8 @@ fn session(
)>, )>,
stop: &AtomicBool, stop: &AtomicBool,
status: &Mutex<RelayStatus>, status: &Mutex<RelayStatus>,
local_auth_port: u16,
local_world_port: Option<u16>,
) -> Result<(), LinkError> { ) -> Result<(), LinkError> {
let mut ws = transport::connect(url, POLL)?; let mut ws = transport::connect(url, POLL)?;
@@ -243,6 +306,7 @@ fn session(
let (ws_out_tx, ws_out_rx) = channel::<TunnelMsg>(); let (ws_out_tx, ws_out_rx) = channel::<TunnelMsg>();
let mut last_ping = Instant::now(); let mut last_ping = Instant::now();
let mut last_pong = Instant::now();
while !stop.load(Ordering::SeqCst) { while !stop.load(Ordering::SeqCst) {
// Drain pending allocation requests // Drain pending allocation requests
@@ -263,10 +327,14 @@ fn session(
} }
// Keepalive // Keepalive
if last_pong.elapsed() > Duration::from_secs(90) {
return Err(LinkError::Timeout);
}
if last_ping.elapsed() > Duration::from_secs(30) { if last_ping.elapsed() > Duration::from_secs(30) {
let _ = ws.send(Message::Text( ws.send(Message::Text(
serde_json::to_string(&TunnelMsg::Ping).unwrap().into(), serde_json::to_string(&TunnelMsg::Ping).unwrap().into(),
)); ))
.map_err(|error| LinkError::Io(error.to_string()))?;
last_ping = Instant::now(); last_ping = Instant::now();
} }
@@ -305,16 +373,38 @@ fn session(
TunnelMsg::Connect { TunnelMsg::Connect {
stream_id, target, .. stream_id, target, ..
} => { } => {
// Strictly predefined local targets: Auth (3724) or World (8085) // Strictly predefined local targets: Auth (3724) or World (8085 or bound realm world port)
let local_port = target.local_port(); let local_port = match target {
RelayTarget::Auth => local_auth_port,
RelayTarget::World => match local_world_port {
Some(p) => p,
None => {
eprintln!("RelayLink cannot connect to World: local_world_port was not provided (fail-closed)");
let _ = ws_out_tx.send(TunnelMsg::ConnectErr {
stream_id,
error: "World port unresolved".into(),
});
continue;
}
},
};
match TcpStream::connect(("127.0.0.1", local_port)) { match TcpStream::connect(("127.0.0.1", local_port)) {
Ok(tcp) => { Ok(tcp) => {
let tcp = Arc::new(tcp);
let shutdown = tcp.clone();
let (stream_tx, stream_rx) = channel::<TunnelMsg>(); let (stream_tx, stream_rx) = channel::<TunnelMsg>();
let ws_tx = ws_out_tx.clone(); let ws_tx = ws_out_tx.clone();
// Spawn worker for this stream // Spawn worker for this stream
spawn_local_tcp_bridge(stream_id, tcp, stream_rx, ws_tx); spawn_local_tcp_bridge(stream_id, tcp, stream_rx, ws_tx);
streams.insert(stream_id, StreamWorker { tx: stream_tx }); streams.insert(
stream_id,
StreamWorker {
tx: stream_tx,
reset_on_drop: true,
shutdown,
},
);
// Reply ConnectOk // Reply ConnectOk
let ok_msg = TunnelMsg::ConnectOk { stream_id }; let ok_msg = TunnelMsg::ConnectOk { stream_id };
@@ -340,7 +430,8 @@ fn session(
} }
} }
TunnelMsg::Close { stream_id } => { TunnelMsg::Close { stream_id } => {
if let Some(w) = streams.remove(&stream_id) { if let Some(mut w) = streams.remove(&stream_id) {
w.reset_on_drop = false;
let _ = w.tx.send(TunnelMsg::Close { stream_id }); let _ = w.tx.send(TunnelMsg::Close { stream_id });
} }
set_status(status, |s| s.active_streams = streams.len()); set_status(status, |s| s.active_streams = streams.len());
@@ -351,7 +442,9 @@ fn session(
} }
set_status(status, |s| s.active_streams = streams.len()); set_status(status, |s| s.active_streams = streams.len());
} }
TunnelMsg::Pong => {} TunnelMsg::Pong => {
last_pong = Instant::now();
}
_ => {} _ => {}
} }
} }
@@ -368,19 +461,20 @@ fn session(
fn spawn_local_tcp_bridge( fn spawn_local_tcp_bridge(
stream_id: u32, stream_id: u32,
mut tcp: TcpStream, tcp: Arc<TcpStream>,
from_tunnel: Receiver<TunnelMsg>, from_tunnel: Receiver<TunnelMsg>,
to_tunnel: Sender<TunnelMsg>, to_tunnel: Sender<TunnelMsg>,
) { ) {
let _ = tcp.set_nonblocking(false); let _ = tcp.set_nonblocking(false);
let _ = tcp.set_nodelay(true); let _ = tcp.set_nodelay(true);
let mut tcp_read = tcp.try_clone().expect("tcp clone"); let tcp_read = tcp.clone();
let to_tunnel_read = to_tunnel.clone(); let to_tunnel_read = to_tunnel.clone();
// Local TCP read -> to tunnel // Local TCP read -> to tunnel
std::thread::Builder::new() std::thread::Builder::new()
.name(format!("relay-stream-{stream_id}-read")) .name(format!("relay-stream-{stream_id}-read"))
.spawn(move || { .spawn(move || {
let mut tcp_read = tcp_read.as_ref();
let mut buf = [0u8; 16384]; let mut buf = [0u8; 16384];
loop { loop {
match tcp_read.read(&mut buf) { match tcp_read.read(&mut buf) {
@@ -410,11 +504,12 @@ fn spawn_local_tcp_bridge(
std::thread::Builder::new() std::thread::Builder::new()
.name(format!("relay-stream-{stream_id}-write")) .name(format!("relay-stream-{stream_id}-write"))
.spawn(move || { .spawn(move || {
let mut tcp_write = tcp.as_ref();
while let Ok(msg) = from_tunnel.recv() { while let Ok(msg) = from_tunnel.recv() {
match msg { match msg {
TunnelMsg::Data { chunk, .. } => { TunnelMsg::Data { chunk, .. } => {
if let Ok(data) = base64::engine::general_purpose::STANDARD.decode(&chunk) { if let Ok(data) = base64::engine::general_purpose::STANDARD.decode(&chunk) {
if tcp.write_all(&data).is_err() { if tcp_write.write_all(&data).is_err() {
break; break;
} }
} }
@@ -433,3 +528,158 @@ fn spawn_local_tcp_bridge(
}) })
.ok(); .ok();
} }
#[cfg(test)]
mod tests {
use super::*;
use std::net::TcpListener;
use std::sync::atomic::AtomicUsize;
#[test]
fn relay_reconnects_after_a_dropped_link_and_clears_its_error() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let accepted = Arc::new(AtomicUsize::new(0));
let seen = accepted.clone();
let worker = std::thread::spawn(move || {
for turn in 0..2 {
let (tcp, _) = listener.accept().unwrap();
tcp.set_read_timeout(Some(Duration::from_secs(15))).unwrap();
let mut ws = tungstenite::accept(tcp).unwrap();
ws.send(Message::Text(
serde_json::to_string(&RelayChallenge {
nonce: "relay-reconnect-test".into(),
})
.unwrap()
.into(),
))
.unwrap();
let _: HostHello =
serde_json::from_str(ws.read().unwrap().to_text().unwrap()).unwrap();
ws.send(Message::Text(
serde_json::to_string(&RelayWelcome {
ok: true,
message: String::new(),
})
.unwrap()
.into(),
))
.unwrap();
seen.fetch_add(1, Ordering::SeqCst);
if turn == 0 {
continue;
}
while let Ok(message) = ws.read() {
let Ok(text) = message.to_text() else {
continue;
};
if let Ok(TunnelMsg::Allocate { request_id, .. }) = serde_json::from_str(text) {
ws.send(Message::Text(
serde_json::to_string(&TunnelMsg::AllocateOk {
request_id,
token: "test-only".into(),
relay_host: "127.0.0.1".into(),
auth_port: 41001,
world_port: 41002,
expires_at: i64::MAX,
})
.unwrap()
.into(),
))
.unwrap();
break;
}
}
}
});
let link = RelayLink::start_with_local_ports(
format!("ws://{addr}"),
RealmId::new(),
SigningKey::from_bytes(&[43; 32]),
57324,
Some(58085),
);
let until = Instant::now() + Duration::from_secs(20);
while accepted.load(Ordering::SeqCst) < 2 || !link.status().connected {
assert!(Instant::now() < until, "{:?}", link.status());
std::thread::sleep(Duration::from_millis(50));
}
assert!(link.status().last_error.is_none());
let allocation = link.allocate(&Uuid::now_v7(), None).unwrap();
assert_eq!(
(allocation.auth_port, allocation.world_port),
(41001, 41002)
);
link.stop();
worker.join().unwrap();
}
#[test]
fn local_tunnel_exchanges_data_in_both_directions_before_reset() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let tcp = Arc::new(TcpStream::connect(listener.local_addr().unwrap()).unwrap());
let shutdown = tcp.clone();
let (mut peer, _) = listener.accept().unwrap();
peer.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
let (tx, rx) = channel();
let (out, replies) = channel();
spawn_local_tcp_bridge(8, tcp, rx, out);
let worker = StreamWorker {
tx,
reset_on_drop: true,
shutdown,
};
worker
.tx
.send(TunnelMsg::Data {
stream_id: 8,
chunk: base64::engine::general_purpose::STANDARD.encode(b"request"),
})
.unwrap();
let mut request = [0; 7];
peer.read_exact(&mut request).unwrap();
assert_eq!(&request, b"request");
peer.write_all(b"response").unwrap();
let mut response = Vec::new();
while response.len() < 8 {
match replies.recv_timeout(Duration::from_secs(3)).unwrap() {
TunnelMsg::Data { chunk, .. } => response.extend(
base64::engine::general_purpose::STANDARD
.decode(chunk)
.unwrap(),
),
other => panic!("Expected the local reply, got {other:?}"),
}
}
assert_eq!(response, b"response");
drop(worker);
}
#[test]
fn dropping_a_tunnel_closes_its_local_tcp_stream() {
for _ in 0..32 {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let tcp = Arc::new(TcpStream::connect(listener.local_addr().unwrap()).unwrap());
let shutdown = tcp.clone();
let (mut peer, _) = listener.accept().unwrap();
peer.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
let (tx, rx) = channel();
let (out, _) = channel();
spawn_local_tcp_bridge(7, tcp, rx, out);
drop(StreamWorker {
tx,
reset_on_drop: true,
shutdown,
});
match peer.read(&mut [0u8; 1]) {
Ok(0) => {}
Err(error)
if matches!(
error.kind(),
std::io::ErrorKind::ConnectionReset | std::io::ErrorKind::ConnectionAborted
) => {}
other => panic!("The abandoned relay stream must close, got {other:?}"),
}
}
}
}
+528 -55
View File
@@ -20,12 +20,27 @@ use uuid::Uuid;
use super::store::{AccountKind, ClaimState, ControlStore, HostTransfer, TransferState}; use super::store::{AccountKind, ClaimState, ControlStore, HostTransfer, TransferState};
use crate::{Error, Result}; use crate::{Error, Result};
mod portable_sync;
#[derive(Clone, Debug)]
pub struct RemoteSessionMessage {
pub kind: app::SessionMessageKind,
pub bytes: Vec<u8>,
}
#[derive(Clone, Debug)]
pub struct RemoteSessionState {
pub message: Option<RemoteSessionMessage>,
pub closed: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
pub struct RealmInfo { pub struct RealmInfo {
/// Create accounts for joining players (the default). When false the realm only links accounts that exist. /// Create accounts for joining players (the default). When false the realm only links accounts that exist.
pub automatic: bool, pub automatic: bool,
/// An address a player's game client can reach right now, when the owner has stated one. Not a relay and not discovery. /// An address a player's game client can reach right now, when the owner has stated one. Not a relay and not discovery.
pub route: Option<String>, pub route: Option<String>,
pub ruleset: crate::portable::model::Ruleset,
} }
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
@@ -55,6 +70,7 @@ pub struct CharInfo {
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
pub struct ClaimExport { pub struct ClaimExport {
pub character_id: Uuid, pub character_id: Uuid,
pub ruleset: crate::portable::Ruleset,
pub payload: Vec<u8>, pub payload: Vec<u8>,
pub sha256: [u8; 32], pub sha256: [u8; 32],
pub collections: BTreeMap<String, Vec<u32>>, pub collections: BTreeMap<String, Vec<u32>>,
@@ -62,6 +78,7 @@ pub struct ClaimExport {
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct RemoteImportParams { pub struct RemoteImportParams {
pub session_id: Uuid,
pub character_id: Uuid, pub character_id: Uuid,
pub revision: u64, pub revision: u64,
pub payload: Vec<u8>, pub payload: Vec<u8>,
@@ -87,6 +104,30 @@ pub enum PreflightVerdict {
/// The realm itself: its login database, its console and the portable engine. /// The realm itself: its login database, its console and the portable engine.
pub trait RealmBackend: Send + Sync { pub trait RealmBackend: Send + Sync {
fn session_message(
&self,
_local_id: &str,
_character: Uuid,
_session: Uuid,
_account: u32,
) -> Result<RemoteSessionState> {
Err(Error::Invalid(
"Portable session synchronization is unavailable.".into(),
))
}
fn session_ack(
&self,
_local_id: &str,
_character: Uuid,
_session: Uuid,
_account: u32,
_kind: app::SessionMessageKind,
_bytes: &[u8],
) -> Result<()> {
Err(Error::Invalid(
"Portable session synchronization is unavailable.".into(),
))
}
fn info(&self, local_id: &str) -> Result<RealmInfo>; fn info(&self, local_id: &str) -> Result<RealmInfo>;
fn account_by_name(&self, local_id: &str, username: &str) -> Result<Option<AccountRow>>; fn account_by_name(&self, local_id: &str, username: &str) -> Result<Option<AccountRow>>;
fn account_by_id(&self, local_id: &str, id: u32) -> Result<Option<AccountRow>>; fn account_by_id(&self, local_id: &str, id: u32) -> Result<Option<AccountRow>>;
@@ -118,6 +159,11 @@ pub trait RealmBackend: Send + Sync {
local_id: &str, local_id: &str,
params: RemoteImportParams, params: RemoteImportParams,
) -> Result<RemoteImportOutcome>; ) -> Result<RemoteImportOutcome>;
/// Local world port for this realm. Must fail closed if the realm port cannot be resolved.
fn auth_port(&self, _local_id: &str) -> Result<u16> {
Ok(coa_control_proto::relay::LOCAL_AUTH_PORT)
}
fn world_port(&self, local_id: &str) -> Result<u16>;
} }
/// State of one channel. /// State of one channel.
@@ -144,7 +190,7 @@ impl Session {
} }
const MAX_REQUESTS_PER_SESSION: u32 = 60; const MAX_REQUESTS_PER_SESSION: u32 = 60;
const MAX_TRANSFER_CHUNKS_PER_SESSION: u32 = 128; const MAX_TRANSFER_CHUNKS_PER_SESSION: u32 = 2048;
const LINK_FAILURES: usize = 5; const LINK_FAILURES: usize = 5;
const LINK_WINDOW: Duration = Duration::from_secs(600); const LINK_WINDOW: Duration = Duration::from_secs(600);
@@ -177,6 +223,8 @@ fn err(code: AppError, message: &str) -> Response {
fn unavailable(what: &str, e: &Error) -> Response { fn unavailable(what: &str, e: &Error) -> Response {
tracing::warn!(error = %e, "{what}"); tracing::warn!(error = %e, "{what}");
#[cfg(test)]
eprintln!("{what}: {e}");
err( err(
AppError::Unavailable, AppError::Unavailable,
"The server could not do that right now.", "The server could not do that right now.",
@@ -218,6 +266,14 @@ impl HostService {
self.realm_id self.realm_id
} }
pub fn local_auth_port(&self) -> Result<u16> {
self.backend.auth_port(&self.local_id)
}
pub fn local_world_port(&self) -> Result<u16> {
self.backend.world_port(&self.local_id)
}
/// The player's public key is the one recorded for this player id when there is a record; `None` when the player is new here. /// The player's public key is the one recorded for this player id when there is a record; `None` when the player is new here.
pub fn key_matches(&self, player: &Uuid, public_key: &str) -> bool { pub fn key_matches(&self, player: &Uuid, public_key: &str) -> bool {
match self match self
@@ -238,7 +294,12 @@ impl HostService {
public_key: &str, public_key: &str,
request: Request, request: Request,
) -> Response { ) -> Response {
if matches!(request, Request::TransferChunk { .. }) { if matches!(
request,
Request::TransferChunk { .. }
| Request::SessionRead { .. }
| Request::SessionAck { .. }
) {
session.transfer_chunks += 1; session.transfer_chunks += 1;
if session.transfer_chunks > MAX_TRANSFER_CHUNKS_PER_SESSION { if session.transfer_chunks > MAX_TRANSFER_CHUNKS_PER_SESSION {
return err( return err(
@@ -303,6 +364,7 @@ impl HostService {
Request::TransferOffer { Request::TransferOffer {
transfer_id, transfer_id,
character_id, character_id,
ruleset,
canonical_revision, canonical_revision,
content_hash, content_hash,
total_size, total_size,
@@ -311,10 +373,31 @@ impl HostService {
player, player,
transfer_id, transfer_id,
character_id, character_id,
ruleset,
canonical_revision, canonical_revision,
content_hash, content_hash,
total_size, total_size,
collections, collections,
false,
),
Request::OwnedTransferOffer {
transfer_id,
character_id,
ruleset,
canonical_revision,
content_hash,
total_size,
collections,
} => self.transfer_offer(
player,
transfer_id,
character_id,
ruleset,
canonical_revision,
content_hash,
total_size,
collections,
true,
), ),
Request::TransferChunk { Request::TransferChunk {
transfer_id, transfer_id,
@@ -327,6 +410,32 @@ impl HostService {
transfer_id, transfer_id,
character_id, character_id,
} => self.transfer_ack(player, transfer_id, character_id), } => self.transfer_ack(player, transfer_id, character_id),
Request::SessionPoll {
character_id,
session_id,
} => self.session_poll(player, character_id, session_id),
Request::SessionRead {
character_id,
session_id,
message_hash,
offset,
} => self.session_read(player, character_id, session_id, &message_hash, offset),
Request::SessionAck {
character_id,
session_id,
message_hash,
offset,
total_size,
data,
} => self.session_ack_chunk(
player,
character_id,
session_id,
&message_hash,
offset,
total_size,
&data,
),
Request::AllocateRelay { player_id } => { Request::AllocateRelay { player_id } => {
self.allocate_relay(session, player, &player_id) self.allocate_relay(session, player, &player_id)
} }
@@ -691,6 +800,7 @@ impl HostService {
use base64::Engine; use base64::Engine;
Response::Claimed { Response::Claimed {
character_id: exported.character_id, character_id: exported.character_id,
ruleset: exported.ruleset.as_str().to_string(),
sha256: hex::encode(exported.sha256), sha256: hex::encode(exported.sha256),
payload: base64::engine::general_purpose::STANDARD.encode(&exported.payload), payload: base64::engine::general_purpose::STANDARD.encode(&exported.payload),
collections: exported.collections, collections: exported.collections,
@@ -726,10 +836,12 @@ impl HostService {
player: &Uuid, player: &Uuid,
transfer_id: Uuid, transfer_id: Uuid,
character_id: Uuid, character_id: Uuid,
ruleset: String,
canonical_revision: u64, canonical_revision: u64,
content_hash: String, content_hash: String,
total_size: usize, total_size: usize,
collections: BTreeMap<String, Vec<u32>>, collections: BTreeMap<String, Vec<u32>>,
owned_session: bool,
) -> Response { ) -> Response {
let Ok(_guard) = self.write.lock() else { let Ok(_guard) = self.write.lock() else {
return err(AppError::Unavailable, "Busy."); return err(AppError::Unavailable, "Busy.");
@@ -741,6 +853,30 @@ impl HostService {
); );
}; };
// 0. Strict ruleset isolation: target realm ruleset must match offer ruleset
let info = match self.backend.info(&self.local_id) {
Ok(i) => i,
Err(e) => return unavailable("reading realm info", &e),
};
let offer_ruleset = match crate::portable::model::Ruleset::parse(&ruleset) {
Ok(r) => r,
Err(_) => return err(AppError::Incompatible, "Invalid ruleset in transfer offer."),
};
if offer_ruleset != info.ruleset {
return err(
AppError::Incompatible,
"Character ruleset does not match this realm.",
);
}
for kind in collections.keys() {
if !crate::portable::session::protocol::carried_kind_for(kind, offer_ruleset) {
return err(
AppError::Incompatible,
"Collection kind does not belong to this ruleset.",
);
}
}
// 1. Ownership check: another player cannot overwrite a character claimed here // 1. Ownership check: another player cannot overwrite a character claimed here
if let Ok(Some(claim)) = self if let Ok(Some(claim)) = self
.store .store
@@ -756,6 +892,41 @@ impl HostService {
} }
} }
// An exact committed retry returns its saved result before transient presence or compatibility checks.
if let Ok(Some(existing)) = self
.store
.lock()
.map_err(|_| Error::Invalid("lock".into()))
.and_then(|s| s.host_transfer_latest(&self.local_id, &character_id))
{
if existing.player_id != *player {
return err(
AppError::NotYours,
"This character's transfer belongs to another player.",
);
}
if existing.state != TransferState::Receiving
&& (!owned_session || existing.transfer_id == transfer_id)
&& existing.player_id == *player
&& existing.ruleset == ruleset
&& existing.total_size == total_size
&& existing.collections == collections
&& existing.revision == canonical_revision
&& existing.content_hash == content_hash
{
if let (Some(guid), Some(sid)) = (existing.local_guid, existing.session_id) {
return Response::TransferCommitted {
transfer_id,
character_id,
local_guid: guid,
session_id: sid,
projected_level: existing.projected_level,
notes: existing.notes,
};
}
}
}
// 2. Active session conflict: if account is online with active characters // 2. Active session conflict: if account is online with active characters
match self.backend.presence(&self.local_id, m.account_id) { match self.backend.presence(&self.local_id, m.account_id) {
Ok(p) if p.account_online && p.online_characters > 0 => { Ok(p) if p.account_online && p.online_characters > 0 => {
@@ -783,30 +954,6 @@ impl HostService {
_ => {} _ => {}
} }
// 4. Idempotency / already committed check
if let Ok(Some(existing)) = self
.store
.lock()
.map_err(|_| Error::Invalid("lock".into()))
.and_then(|s| s.host_transfer_latest(&self.local_id, &character_id))
{
if existing.state != TransferState::Receiving
&& existing.revision == canonical_revision
&& existing.content_hash == content_hash
{
if let (Some(guid), Some(sid)) = (existing.local_guid, existing.session_id) {
return Response::TransferCommitted {
transfer_id,
character_id,
local_guid: guid,
session_id: sid,
projected_level: existing.projected_level,
notes: existing.notes,
};
}
}
}
// 5. Resume check for this specific transfer_id // 5. Resume check for this specific transfer_id
if let Ok(Some(cur)) = self if let Ok(Some(cur)) = self
.store .store
@@ -834,6 +981,7 @@ impl HostService {
realm_local_id: self.local_id.clone(), realm_local_id: self.local_id.clone(),
transfer_id, transfer_id,
character_id, character_id,
ruleset: offer_ruleset.as_str().to_string(),
player_id: *player, player_id: *player,
revision: canonical_revision, revision: canonical_revision,
content_hash, content_hash,
@@ -1008,23 +1156,61 @@ impl HostService {
Err(e) => return unavailable("reading transfer file", &Error::Invalid(e.to_string())), Err(e) => return unavailable("reading transfer file", &Error::Invalid(e.to_string())),
}; };
use sha2::{Digest, Sha256};
let hash = hex::encode(Sha256::digest(&payload));
if hash != t.content_hash {
let _ = std::fs::remove_file(&path);
return err(AppError::Invalid, "Content hash mismatch.");
}
let mut hash_bytes = [0u8; 32]; let mut hash_bytes = [0u8; 32];
if hex::decode_to_slice(&t.content_hash, &mut hash_bytes).is_err() { if hex::decode_to_slice(&t.content_hash, &mut hash_bytes).is_err() {
let _ = std::fs::remove_file(&path);
return err(AppError::Invalid, "Invalid content hash format."); return err(AppError::Invalid, "Invalid content hash format.");
} }
let decoded = match crate::portable::snapshot::decode(&payload, Some(&hash_bytes)) {
Ok(d) => d,
Err(e) => {
let _ = std::fs::remove_file(&path);
return err(AppError::Invalid, &format!("Corrupt snapshot: {e}"));
}
};
let transfer_ruleset: crate::portable::Ruleset = match t.ruleset.parse() {
Ok(r) => r,
Err(_) => {
let _ = std::fs::remove_file(&path);
return err(AppError::Incompatible, "Invalid transfer ruleset.");
}
};
if decoded.character_id.as_uuid() != t.character_id {
let _ = std::fs::remove_file(&path);
return err(
AppError::Invalid,
"Snapshot character id does not match TransferOffer.",
);
}
if decoded.ruleset != transfer_ruleset {
let _ = std::fs::remove_file(&path);
return err(
AppError::Incompatible,
"Snapshot ruleset does not match TransferOffer.",
);
}
let info = match self.backend.info(&self.local_id) {
Ok(i) => i,
Err(e) => {
let _ = std::fs::remove_file(&path);
return unavailable("reading realm info", &e);
}
};
if transfer_ruleset != info.ruleset {
let _ = std::fs::remove_file(&path);
return err(
AppError::Incompatible,
"Transfer ruleset does not match target realm ruleset.",
);
}
let Some(m) = self.mapping(player) else { let Some(m) = self.mapping(player) else {
return err(AppError::NoAccount, "Player has no account on this realm."); return err(AppError::NoAccount, "Player has no account on this realm.");
}; };
let params = RemoteImportParams { let params = RemoteImportParams {
session_id: t.transfer_id,
character_id: t.character_id, character_id: t.character_id,
revision: t.revision, revision: t.revision,
payload, payload,
@@ -1083,6 +1269,7 @@ impl HostService {
#[cfg(any(test, feature = "testkit"))] #[cfg(any(test, feature = "testkit"))]
pub mod fake { pub mod fake {
use super::*; use super::*;
use crate::portable::Ruleset;
#[derive(Default)] #[derive(Default)]
pub struct FakeRealm { pub struct FakeRealm {
@@ -1095,6 +1282,7 @@ pub mod fake {
pub seen_passwords: Mutex<Vec<String>>, pub seen_passwords: Mutex<Vec<String>>,
pub imported: Mutex<HashMap<Uuid, (u32, Uuid)>>, pub imported: Mutex<HashMap<Uuid, (u32, Uuid)>>,
pub incompatible: Mutex<std::collections::HashSet<Uuid>>, pub incompatible: Mutex<std::collections::HashSet<Uuid>>,
pub world_port: Mutex<Option<Result<u16>>>,
} }
impl FakeRealm { impl FakeRealm {
@@ -1141,6 +1329,7 @@ pub mod fake {
impl RealmBackend for FakeRealm { impl RealmBackend for FakeRealm {
fn info(&self, _: &str) -> Result<RealmInfo> { fn info(&self, _: &str) -> Result<RealmInfo> {
Ok(RealmInfo { Ok(RealmInfo {
ruleset: Ruleset::Coa,
automatic: *self.automatic.lock().unwrap(), automatic: *self.automatic.lock().unwrap(),
route: self.route.lock().unwrap().clone(), route: self.route.lock().unwrap().clone(),
}) })
@@ -1245,6 +1434,7 @@ pub mod fake {
.or_insert_with(Uuid::now_v7); .or_insert_with(Uuid::now_v7);
Ok(ClaimExport { Ok(ClaimExport {
character_id: id, character_id: id,
ruleset: crate::portable::Ruleset::Coa,
payload: format!("payload-{guid}").into_bytes(), payload: format!("payload-{guid}").into_bytes(),
sha256: [7; 32], sha256: [7; 32],
collections: BTreeMap::from([("coa:appearance".to_string(), vec![1, 2, 3])]), collections: BTreeMap::from([("coa:appearance".to_string(), vec![1, 2, 3])]),
@@ -1284,6 +1474,16 @@ pub mod fake {
notes: vec![], notes: vec![],
}) })
} }
fn world_port(&self, _: &str) -> Result<u16> {
if let Some(res) = self.world_port.lock().unwrap().as_ref() {
match res {
Ok(p) => Ok(*p),
Err(e) => Err(Error::Invalid(e.to_string())),
}
} else {
Ok(8085)
}
}
} }
} }
@@ -1424,7 +1624,7 @@ mod tests {
&Uuid::now_v7(), &Uuid::now_v7(),
"K", "K",
Request::Hello { Request::Hello {
protocol: 1, protocol: coa_control_proto::CONTROL_PROTOCOL_VERSION,
client: "t".into(), client: "t".into(),
}, },
) )
@@ -1655,6 +1855,7 @@ mod tests {
); );
let Response::Claimed { let Response::Claimed {
character_id, character_id,
ruleset,
sha256, sha256,
payload, payload,
collections, collections,
@@ -1662,6 +1863,7 @@ mod tests {
else { else {
panic!() panic!()
}; };
assert_eq!(ruleset, "coa");
assert_eq!(sha256, hex::encode([7u8; 32])); assert_eq!(sha256, hex::encode([7u8; 32]));
assert!(!payload.is_empty() && collections["coa:appearance"] == vec![1, 2, 3]); assert!(!payload.is_empty() && collections["coa:appearance"] == vec![1, 2, 3]);
// asking again returns the same character // asking again returns the same character
@@ -1857,6 +2059,14 @@ mod tests {
); );
} }
fn test_snapshot(cid: Uuid, ruleset: crate::portable::Ruleset) -> (Vec<u8>, String) {
let mut model = crate::portable::fixtures::geared_level_eighty();
model.character_id = crate::portable::CharacterId::from_uuid(cid).unwrap();
model.ruleset = ruleset;
let encoded = crate::portable::snapshot::encode(&model).unwrap();
(encoded.payload, hex::encode(encoded.content_hash))
}
#[test] #[test]
fn remote_transfer_lifecycle_empty_realm_import_and_ack() { fn remote_transfer_lifecycle_empty_realm_import_and_ack() {
let (realm, s, p, _acc) = claimed_setup(); let (realm, s, p, _acc) = claimed_setup();
@@ -1864,12 +2074,11 @@ mod tests {
let cid = Uuid::now_v7(); let cid = Uuid::now_v7();
let tid = Uuid::now_v7(); let tid = Uuid::now_v7();
let payload = b"portable_character_snapshot_payload_test_data".to_vec(); let (payload, hash) = test_snapshot(cid, crate::portable::Ruleset::Coa);
use sha2::{Digest, Sha256};
let hash = hex::encode(Sha256::digest(&payload));
// 1. Offer // 1. Offer
let offer = Request::TransferOffer { let offer = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid, transfer_id: tid,
character_id: cid, character_id: cid,
canonical_revision: 1, canonical_revision: 1,
@@ -1943,6 +2152,7 @@ mod tests {
realm.incompatible.lock().unwrap().insert(cid); realm.incompatible.lock().unwrap().insert(cid);
let offer = Request::TransferOffer { let offer = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid, transfer_id: tid,
character_id: cid, character_id: cid,
canonical_revision: 1, canonical_revision: 1,
@@ -1973,15 +2183,12 @@ mod tests {
let cid = Uuid::now_v7(); let cid = Uuid::now_v7();
let tid = Uuid::now_v7(); let tid = Uuid::now_v7();
let chunk1 = b"first_chunk_of_payload_"; let (full, hash) = test_snapshot(cid, crate::portable::Ruleset::Coa);
let chunk2 = b"second_chunk_of_payload"; let mid = full.len() / 2;
let mut full = chunk1.to_vec(); let (chunk1, chunk2) = full.split_at(mid);
full.extend_from_slice(chunk2);
use sha2::{Digest, Sha256};
let hash = hex::encode(Sha256::digest(&full));
let offer = Request::TransferOffer { let offer = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid, transfer_id: tid,
character_id: cid, character_id: cid,
canonical_revision: 1, canonical_revision: 1,
@@ -2071,11 +2278,10 @@ mod tests {
let cid = Uuid::now_v7(); let cid = Uuid::now_v7();
let tid = Uuid::now_v7(); let tid = Uuid::now_v7();
let payload = b"idempotency_test_payload".to_vec(); let (payload, hash) = test_snapshot(cid, crate::portable::Ruleset::Coa);
use sha2::{Digest, Sha256};
let hash = hex::encode(Sha256::digest(&payload));
let offer = Request::TransferOffer { let offer = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid, transfer_id: tid,
character_id: cid, character_id: cid,
canonical_revision: 1, canonical_revision: 1,
@@ -2138,6 +2344,7 @@ mod tests {
// Client starts a new transfer for the exact same committed revision: discovers committed state // Client starts a new transfer for the exact same committed revision: discovers committed state
let tid2 = Uuid::now_v7(); let tid2 = Uuid::now_v7();
let offer2 = Request::TransferOffer { let offer2 = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid2, transfer_id: tid2,
character_id: cid, character_id: cid,
canonical_revision: 1, canonical_revision: 1,
@@ -2163,17 +2370,92 @@ mod tests {
); );
} }
#[test]
fn committed_transfer_retry_survives_presence_and_compatibility_changes() {
let (realm, service, player, account) = claimed_setup();
let character = Uuid::now_v7();
let session_id = Uuid::now_v7();
let (payload, hash) = test_snapshot(character, crate::portable::Ruleset::Coa);
let transfer = HostTransfer {
realm_local_id: service.local_id.clone(),
transfer_id: Uuid::now_v7(),
character_id: character,
ruleset: "coa".into(),
player_id: player,
revision: 7,
content_hash: hash.clone(),
total_size: payload.len(),
received_size: payload.len(),
state: TransferState::Committed,
local_guid: Some(3012),
session_id: Some(session_id),
projected_level: Some(60),
notes: vec![],
collections: BTreeMap::new(),
};
service
.store
.lock()
.unwrap()
.host_transfer_save(&transfer)
.unwrap();
realm.incompatible.lock().unwrap().insert(character);
realm.online.lock().unwrap().insert(
account,
Presence {
account_online: true,
online_characters: 1,
},
);
let offer = || Request::TransferOffer {
transfer_id: Uuid::now_v7(),
character_id: character,
ruleset: "coa".into(),
canonical_revision: 7,
content_hash: hash.clone(),
total_size: payload.len(),
collections: BTreeMap::new(),
};
assert!(
matches!(service.handle(&mut Session::default(), &player, "K", offer()),
Response::TransferCommitted { local_guid: 3012, session_id: returned, .. } if returned == session_id)
);
let mut different = transfer;
different.player_id = Uuid::now_v7();
different.transfer_id = Uuid::now_v7();
different.character_id = Uuid::now_v7();
service
.store
.lock()
.unwrap()
.host_transfer_save(&different)
.unwrap();
let foreign_offer = Request::TransferOffer {
transfer_id: Uuid::now_v7(),
character_id: different.character_id,
ruleset: "coa".into(),
canonical_revision: 7,
content_hash: hash.clone(),
total_size: payload.len(),
collections: BTreeMap::new(),
};
assert!(matches!(
service.handle(&mut Session::default(), &player, "K", foreign_offer),
Response::Error { .. }
));
assert!(realm.imported.lock().unwrap().is_empty());
}
#[test] #[test]
fn wrong_player_identity_cannot_overwrite_another_players_realm_copy() { fn wrong_player_identity_cannot_overwrite_another_players_realm_copy() {
let (_realm, s, p, _acc) = claimed_setup(); let (_realm, s, p, _acc) = claimed_setup();
let cid = Uuid::now_v7(); let cid = Uuid::now_v7();
let tid = Uuid::now_v7(); let tid = Uuid::now_v7();
let payload = b"player_1_character_data".to_vec(); let (payload, hash) = test_snapshot(cid, crate::portable::Ruleset::Coa);
use sha2::{Digest, Sha256};
let hash = hex::encode(Sha256::digest(&payload));
let offer = Request::TransferOffer { let offer = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid, transfer_id: tid,
character_id: cid, character_id: cid,
canonical_revision: 1, canonical_revision: 1,
@@ -2240,6 +2522,7 @@ mod tests {
let tid_impostor = Uuid::now_v7(); let tid_impostor = Uuid::now_v7();
let impostor_offer = Request::TransferOffer { let impostor_offer = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid_impostor, transfer_id: tid_impostor,
character_id: cid, character_id: cid,
canonical_revision: 2, canonical_revision: 2,
@@ -2267,9 +2550,7 @@ mod tests {
let cid = Uuid::now_v7(); let cid = Uuid::now_v7();
let tid1 = Uuid::now_v7(); let tid1 = Uuid::now_v7();
let payload1 = b"character_revision_1_data".to_vec(); let (payload1, hash1) = test_snapshot(cid, crate::portable::Ruleset::Coa);
use sha2::{Digest, Sha256};
let hash1 = hex::encode(Sha256::digest(&payload1));
// Rev 1 // Rev 1
s.handle( s.handle(
@@ -2277,6 +2558,7 @@ mod tests {
&p, &p,
"K", "K",
Request::TransferOffer { Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid1, transfer_id: tid1,
character_id: cid, character_id: cid,
canonical_revision: 1, canonical_revision: 1,
@@ -2321,13 +2603,18 @@ mod tests {
// Rev 2 // Rev 2
let tid2 = Uuid::now_v7(); let tid2 = Uuid::now_v7();
let payload2 = b"character_revision_2_newer_data".to_vec(); let mut model2 = crate::portable::fixtures::geared_level_eighty();
let hash2 = hex::encode(Sha256::digest(&payload2)); model2.character_id = crate::portable::CharacterId::from_uuid(cid).unwrap();
model2.progression.money += 500;
let enc2 = crate::portable::snapshot::encode(&model2).unwrap();
let (payload2, hash2) = (enc2.payload, hex::encode(enc2.content_hash));
let r = s.handle( let r = s.handle(
&mut session, &mut session,
&p, &p,
"K", "K",
Request::TransferOffer { Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid2, transfer_id: tid2,
character_id: cid, character_id: cid,
canonical_revision: 2, canonical_revision: 2,
@@ -2377,4 +2664,190 @@ mod tests {
"update, not duplicate import" "update, not duplicate import"
); );
} }
#[test]
fn cross_ruleset_transfer_offers_are_rejected_before_mutation() {
let (realm, s, p, _acc) = claimed_setup();
let mut session = Session::default();
let cid = Uuid::now_v7();
let tid = Uuid::now_v7();
// 1. Host is CoA, offer is Wildcard -> Rejected
let wc_offer = Request::TransferOffer {
ruleset: "wildcard".into(),
transfer_id: tid,
character_id: cid,
canonical_revision: 1,
content_hash: "a".repeat(64),
total_size: 100,
collections: BTreeMap::new(),
};
let r = s.handle(&mut session, &p, "K", wc_offer);
assert!(matches!(
r,
Response::Error {
code: AppError::Incompatible,
..
}
));
// 2. Host is CoA, offer is Reborn -> Rejected
let rb_offer = Request::TransferOffer {
ruleset: "reborn".into(),
transfer_id: tid,
character_id: cid,
canonical_revision: 1,
content_hash: "a".repeat(64),
total_size: 100,
collections: BTreeMap::new(),
};
let r = s.handle(&mut session, &p, "K", rb_offer);
assert!(matches!(
r,
Response::Error {
code: AppError::Incompatible,
..
}
));
// 3. Collection kinds for another ruleset -> Rejected
let foreign_coll_offer = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid,
character_id: cid,
canonical_revision: 1,
content_hash: "a".repeat(64),
total_size: 100,
collections: BTreeMap::from([("wildcard:appearance".into(), vec![1, 2, 3])]),
};
let r = s.handle(&mut session, &p, "K", foreign_coll_offer);
assert!(matches!(
r,
Response::Error {
code: AppError::Incompatible,
..
}
));
// Ensure 0 DB imports happened
assert!(realm.imported.lock().unwrap().is_empty());
}
#[test]
fn tampered_payload_at_commit_aborts_with_zero_mutation() {
let (realm, s, p, _acc) = claimed_setup();
let mut session = Session::default();
let cid = Uuid::now_v7();
let tid = Uuid::now_v7();
// 1. Offer announces CoA
let (payload_coa, hash_coa) = test_snapshot(cid, crate::portable::Ruleset::Coa);
let offer = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid,
character_id: cid,
canonical_revision: 1,
content_hash: hash_coa,
total_size: payload_coa.len(),
collections: BTreeMap::new(),
};
s.handle(&mut session, &p, "K", offer);
// Attacker creates a Wildcard snapshot with the same CID, but uploads it under the CoA offer
let (payload_wc, hash_wc) = test_snapshot(cid, crate::portable::Ruleset::Wildcard);
// Uploading chunks of payload_wc will mismatch the offered hash
use base64::Engine;
let data = base64::engine::general_purpose::STANDARD.encode(&payload_wc);
s.handle(
&mut session,
&p,
"K",
Request::TransferChunk {
transfer_id: tid,
offset: 0,
data,
},
);
let commit = Request::TransferCommit { transfer_id: tid };
let r = s.handle(&mut session, &p, "K", commit);
assert!(matches!(
r,
Response::Error {
code: AppError::Invalid,
..
}
));
assert!(realm.imported.lock().unwrap().is_empty());
// 2. What if attacker offered hash_wc matching payload_wc, but offer.ruleset is "coa"?
let tid2 = Uuid::now_v7();
let offer2 = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid2,
character_id: cid,
canonical_revision: 1,
content_hash: hash_wc,
total_size: payload_wc.len(),
collections: BTreeMap::new(),
};
s.handle(&mut session, &p, "K", offer2);
let data2 = base64::engine::general_purpose::STANDARD.encode(&payload_wc);
s.handle(
&mut session,
&p,
"K",
Request::TransferChunk {
transfer_id: tid2,
offset: 0,
data: data2,
},
);
let commit2 = Request::TransferCommit { transfer_id: tid2 };
let r2 = s.handle(&mut session, &p, "K", commit2);
assert!(matches!(
r2,
Response::Error {
code: AppError::Incompatible,
..
}
));
assert!(realm.imported.lock().unwrap().is_empty());
// 3. What if snapshot contains a different character_id than offer?
let tid3 = Uuid::now_v7();
let other_cid = Uuid::now_v7();
let (payload_other, hash_other) = test_snapshot(other_cid, crate::portable::Ruleset::Coa);
let offer3 = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid3,
character_id: cid, // offered cid
canonical_revision: 1,
content_hash: hash_other,
total_size: payload_other.len(),
collections: BTreeMap::new(),
};
s.handle(&mut session, &p, "K", offer3);
let data3 = base64::engine::general_purpose::STANDARD.encode(&payload_other);
s.handle(
&mut session,
&p,
"K",
Request::TransferChunk {
transfer_id: tid3,
offset: 0,
data: data3,
},
);
let commit3 = Request::TransferCommit { transfer_id: tid3 };
let r3 = s.handle(&mut session, &p, "K", commit3);
assert!(matches!(
r3,
Response::Error {
code: AppError::Invalid,
..
}
));
assert!(realm.imported.lock().unwrap().is_empty());
}
} }
@@ -0,0 +1,209 @@
//! Authenticated, bounded transport for the existing Owner/Host session messages.
use super::*;
use base64::{engine::general_purpose::STANDARD as B64, Engine};
use sha2::{Digest, Sha256};
use std::io::Write;
fn digest(bytes: &[u8]) -> String {
hex::encode(Sha256::digest(bytes))
}
impl HostService {
fn session_account(&self, player: &Uuid, character: Uuid) -> Option<u32> {
let mapping = self.mapping(player)?;
let transfer = self
.store
.lock()
.ok()?
.host_transfer_latest(&self.local_id, &character)
.ok()??;
(transfer.player_id == *player && transfer.state != TransferState::Receiving)
.then_some(mapping.account_id)
}
pub(super) fn session_poll(&self, player: &Uuid, character: Uuid, session: Uuid) -> Response {
let Some(account) = self.session_account(player, character) else {
return err(
AppError::NotYours,
"This portable session does not belong to this player.",
);
};
match self
.backend
.session_message(&self.local_id, character, session, account)
{
Ok(RemoteSessionState {
message: Some(message),
..
}) => Response::SessionPending {
kind: message.kind,
total_size: message.bytes.len(),
content_hash: digest(&message.bytes),
},
Ok(state) => Response::SessionIdle {
closed: state.closed,
},
Err(error) => unavailable("reading portable session", &error),
}
}
pub(super) fn session_read(
&self,
player: &Uuid,
character: Uuid,
session: Uuid,
expected: &str,
offset: usize,
) -> Response {
let Some(account) = self.session_account(player, character) else {
return err(
AppError::NotYours,
"This portable session does not belong to this player.",
);
};
let message =
match self
.backend
.session_message(&self.local_id, character, session, account)
{
Ok(state) => match state.message {
Some(message) => message,
None => {
return err(
AppError::Conflict,
"The portable session message changed; retry.",
)
}
},
Err(error) => return unavailable("reading portable session", &error),
};
if digest(&message.bytes) != expected || offset > message.bytes.len() {
return err(
AppError::Conflict,
"The portable session message changed; retry.",
);
}
let end = message.bytes.len().min(offset.saturating_add(24 * 1024));
Response::SessionData {
offset,
data: B64.encode(&message.bytes[offset..end]),
}
}
pub(super) fn session_ack_chunk(
&self,
player: &Uuid,
character: Uuid,
session: Uuid,
expected: &str,
offset: usize,
total_size: usize,
data: &str,
) -> Response {
let Ok(_guard) = self.write.lock() else {
return err(AppError::Unavailable, "Busy.");
};
let Some(account) = self.session_account(player, character) else {
return err(
AppError::NotYours,
"This portable session does not belong to this player.",
);
};
if expected.len() != 64
|| !expected.bytes().all(|b| b.is_ascii_hexdigit())
|| total_size == 0
|| total_size > app::MAX_SESSION_BYTES
|| offset > total_size
|| data.len() > 48 * 1024
{
return err(AppError::Invalid, "Invalid acknowledgement bounds.");
}
let bytes = match B64.decode(data) {
Ok(bytes) if bytes.len() <= total_size - offset => bytes,
_ => return err(AppError::Invalid, "Invalid acknowledgement chunk."),
};
let directory = std::env::temp_dir()
.join("coa-session-acks")
.join(digest(self.local_id.as_bytes()));
if let Err(error) = std::fs::create_dir_all(&directory) {
return unavailable("preparing session acknowledgement", &Error::from(error));
}
let path = directory.join(format!("{character}-{session}.part"));
let state = match self
.backend
.session_message(&self.local_id, character, session, account)
{
Ok(state) => state,
Err(error) => return unavailable("reading portable session", &error),
};
let Some(message) = state.message else {
let _ = std::fs::remove_file(&path);
return Response::SessionAcked {
received_size: total_size,
complete: true,
};
};
if digest(&message.bytes) != expected {
return err(
AppError::Conflict,
"The portable session message changed; retry.",
);
}
// Bind one partial file to the precise message and acknowledgement length.
let mut header = expected.as_bytes().to_vec();
header.extend_from_slice(&(total_size as u64).to_le_bytes());
let write = (|| -> Result<usize> {
if offset == 0 {
let mut file = std::fs::File::create(&path)?;
file.write_all(&header)?;
}
let current = std::fs::read(&path)?;
if !current.starts_with(&header) {
return Err(Error::Invalid(
"The acknowledgement changed; restart it.".into(),
));
}
let received = current.len() - header.len();
if received != offset {
return Ok(received);
}
let mut file = std::fs::OpenOptions::new().append(true).open(&path)?;
file.write_all(&bytes)?;
file.sync_all()?;
Ok(received + bytes.len())
})();
let received = match write {
Ok(received) => received,
Err(error) => return unavailable("saving portable acknowledgement", &error),
};
if received != total_size {
return Response::SessionAcked {
received_size: received,
complete: false,
};
}
let complete = match std::fs::read(&path) {
Ok(bytes) => bytes,
Err(error) => {
return unavailable("reading portable acknowledgement", &Error::from(error))
}
};
match self.backend.session_ack(
&self.local_id,
character,
session,
account,
message.kind,
&complete[header.len()..],
) {
Ok(()) => {
let _ = std::fs::remove_file(&path);
Response::SessionAcked {
received_size: total_size,
complete: true,
}
}
Err(error) => unavailable("applying portable acknowledgement", &error),
}
}
}
+128 -4
View File
@@ -56,6 +56,7 @@ CREATE TABLE IF NOT EXISTS host_transfer(
realm_local_id TEXT NOT NULL, realm_local_id TEXT NOT NULL,
transfer_id TEXT NOT NULL PRIMARY KEY, transfer_id TEXT NOT NULL PRIMARY KEY,
character_id TEXT NOT NULL, character_id TEXT NOT NULL,
ruleset TEXT NOT NULL DEFAULT 'coa',
player_id TEXT NOT NULL, player_id TEXT NOT NULL,
revision INTEGER NOT NULL, revision INTEGER NOT NULL,
content_hash TEXT NOT NULL, content_hash TEXT NOT NULL,
@@ -71,6 +72,13 @@ CREATE TABLE IF NOT EXISTS host_transfer(
updated_at TEXT NOT NULL updated_at TEXT NOT NULL
); );
CREATE INDEX IF NOT EXISTS host_transfer_char ON host_transfer(realm_local_id, character_id); CREATE INDEX IF NOT EXISTS host_transfer_char ON host_transfer(realm_local_id, character_id);
CREATE TABLE IF NOT EXISTS player_remote_session(
character_id TEXT PRIMARY KEY,
realm_id TEXT NOT NULL,
session_id TEXT NOT NULL,
public_key TEXT NOT NULL,
coordinator TEXT NOT NULL
);
"; ";
fn now() -> String { fn now() -> String {
@@ -155,6 +163,7 @@ pub struct HostTransfer {
pub realm_local_id: String, pub realm_local_id: String,
pub transfer_id: Uuid, pub transfer_id: Uuid,
pub character_id: Uuid, pub character_id: Uuid,
pub ruleset: String,
pub player_id: Uuid, pub player_id: Uuid,
pub revision: u64, pub revision: u64,
pub content_hash: String, pub content_hash: String,
@@ -175,6 +184,15 @@ pub struct PlayerRealm {
pub kind: AccountKind, pub kind: AccountKind,
} }
#[derive(Clone, Debug)]
pub struct PlayerRemoteSession {
pub character_id: Uuid,
pub realm_id: String,
pub session_id: Uuid,
pub public_key: String,
pub coordinator: String,
}
pub struct ControlStore { pub struct ControlStore {
conn: Connection, conn: Connection,
} }
@@ -184,6 +202,66 @@ fn uuid(s: String) -> Result<Uuid> {
} }
impl ControlStore { impl ControlStore {
pub fn player_remote_sessions(&self) -> Result<Vec<PlayerRemoteSession>> {
let mut statement = self.conn.prepare("SELECT character_id, realm_id, session_id, public_key, coordinator FROM player_remote_session ORDER BY character_id").map_err(db)?;
let rows = statement
.query_map([], |row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
row.get::<_, String>(2)?,
row.get::<_, String>(3)?,
row.get::<_, String>(4)?,
))
})
.map_err(db)?;
rows.map(|row| {
let (character, realm_id, session, public_key, coordinator) = row.map_err(db)?;
Ok(PlayerRemoteSession {
character_id: uuid(character)?,
realm_id,
session_id: uuid(session)?,
public_key,
coordinator,
})
})
.collect()
}
pub fn player_remote_session_set(&self, session: &PlayerRemoteSession) -> Result<()> {
if self.player_remote_sessions()?.iter().any(|existing| {
existing.character_id == session.character_id
&& (existing.session_id != session.session_id
|| existing.realm_id != session.realm_id
|| existing.public_key != session.public_key)
}) {
return Err(Error::Invalid(
"The character's previous remote session must finish saving first.".into(),
));
}
self.conn.execute("INSERT INTO player_remote_session(character_id, realm_id, session_id, public_key, coordinator) VALUES(?1,?2,?3,?4,?5) ON CONFLICT(character_id) DO NOTHING", params![session.character_id.to_string(), session.realm_id, session.session_id.to_string(), session.public_key, session.coordinator]).map_err(db)?;
Ok(())
}
pub fn player_remote_session_advance(
&self,
character: Uuid,
previous: Uuid,
next: Uuid,
) -> Result<()> {
self.conn.execute("UPDATE player_remote_session SET session_id=?3 WHERE character_id=?1 AND session_id=?2", params![character.to_string(), previous.to_string(), next.to_string()]).map_err(db)?;
Ok(())
}
pub fn player_remote_session_remove(&self, character: Uuid, session: Uuid) -> Result<()> {
self.conn
.execute(
"DELETE FROM player_remote_session WHERE character_id=?1 AND session_id=?2",
params![character.to_string(), session.to_string()],
)
.map_err(db)?;
Ok(())
}
pub fn open(dir: &Path) -> Result<Self> { pub fn open(dir: &Path) -> Result<Self> {
std::fs::create_dir_all(dir)?; std::fs::create_dir_all(dir)?;
let conn = Connection::open(dir.join("control.sqlite")).map_err(db)?; let conn = Connection::open(dir.join("control.sqlite")).map_err(db)?;
@@ -199,6 +277,10 @@ impl ControlStore {
.map_err(db)?; .map_err(db)?;
let _ = conn.pragma_update(None, "journal_mode", "WAL"); let _ = conn.pragma_update(None, "journal_mode", "WAL");
conn.execute_batch(SCHEMA).map_err(db)?; conn.execute_batch(SCHEMA).map_err(db)?;
let _ = conn.execute(
"ALTER TABLE host_transfer ADD COLUMN ruleset TEXT NOT NULL DEFAULT 'coa'",
[],
);
Ok(Self { conn }) Ok(Self { conn })
} }
@@ -307,7 +389,7 @@ impl ControlStore {
pub fn host_transfer(&self, realm: &str, transfer_id: &Uuid) -> Result<Option<HostTransfer>> { pub fn host_transfer(&self, realm: &str, transfer_id: &Uuid) -> Result<Option<HostTransfer>> {
self.conn self.conn
.query_row( .query_row(
"SELECT realm_local_id, transfer_id, character_id, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections FROM host_transfer WHERE realm_local_id = ?1 AND transfer_id = ?2", "SELECT realm_local_id, transfer_id, character_id, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections, ruleset FROM host_transfer WHERE realm_local_id = ?1 AND transfer_id = ?2",
params![realm, transfer_id.to_string()], params![realm, transfer_id.to_string()],
row_transfer, row_transfer,
) )
@@ -323,7 +405,7 @@ impl ControlStore {
) -> Result<Option<HostTransfer>> { ) -> Result<Option<HostTransfer>> {
self.conn self.conn
.query_row( .query_row(
"SELECT realm_local_id, transfer_id, character_id, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections FROM host_transfer WHERE realm_local_id = ?1 AND character_id = ?2 ORDER BY updated_at DESC LIMIT 1", "SELECT realm_local_id, transfer_id, character_id, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections, ruleset FROM host_transfer WHERE realm_local_id = ?1 AND character_id = ?2 ORDER BY updated_at DESC LIMIT 1",
params![realm, character_id.to_string()], params![realm, character_id.to_string()],
row_transfer, row_transfer,
) )
@@ -337,8 +419,8 @@ impl ControlStore {
let coll_json = serde_json::to_string(&t.collections).unwrap_or_default(); let coll_json = serde_json::to_string(&t.collections).unwrap_or_default();
self.conn self.conn
.execute( .execute(
"INSERT INTO host_transfer(realm_local_id, transfer_id, character_id, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections, created_at, updated_at) "INSERT INTO host_transfer(realm_local_id, transfer_id, character_id, ruleset, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17)
ON CONFLICT(transfer_id) DO UPDATE SET ON CONFLICT(transfer_id) DO UPDATE SET
received_size = excluded.received_size, received_size = excluded.received_size,
state = excluded.state, state = excluded.state,
@@ -347,11 +429,13 @@ impl ControlStore {
projected_level = excluded.projected_level, projected_level = excluded.projected_level,
notes = excluded.notes, notes = excluded.notes,
collections = excluded.collections, collections = excluded.collections,
ruleset = excluded.ruleset,
updated_at = excluded.updated_at", updated_at = excluded.updated_at",
params![ params![
t.realm_local_id, t.realm_local_id,
t.transfer_id.to_string(), t.transfer_id.to_string(),
t.character_id.to_string(), t.character_id.to_string(),
t.ruleset,
t.player_id.to_string(), t.player_id.to_string(),
t.revision as i64, t.revision as i64,
t.content_hash, t.content_hash,
@@ -540,11 +624,13 @@ fn row_transfer(r: &rusqlite::Row<'_>) -> rusqlite::Result<Result<HostTransfer>>
let collections = coll_str let collections = coll_str
.and_then(|s| serde_json::from_str::<BTreeMap<String, Vec<u32>>>(&s).ok()) .and_then(|s| serde_json::from_str::<BTreeMap<String, Vec<u32>>>(&s).ok())
.unwrap_or_default(); .unwrap_or_default();
let ruleset: String = r.get(14).unwrap_or_else(|_| "coa".to_string());
Ok((|| { Ok((|| {
Ok(HostTransfer { Ok(HostTransfer {
realm_local_id, realm_local_id,
transfer_id: uuid(tid)?, transfer_id: uuid(tid)?,
character_id: uuid(cid)?, character_id: uuid(cid)?,
ruleset,
player_id: uuid(pid)?, player_id: uuid(pid)?,
revision: revision as u64, revision: revision as u64,
content_hash, content_hash,
@@ -564,6 +650,43 @@ fn row_transfer(r: &rusqlite::Row<'_>) -> rusqlite::Result<Result<HostTransfer>>
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn remote_session_survives_restart_and_cannot_be_replaced() {
let dir = tempfile::tempdir().unwrap();
let row = PlayerRemoteSession {
character_id: Uuid::now_v7(),
realm_id: "realm".into(),
session_id: Uuid::now_v7(),
public_key: "pinned-key".into(),
coordinator: "wss://example.test/coord/v1/player".into(),
};
{
let store = ControlStore::open(dir.path()).unwrap();
store.player_remote_session_set(&row).unwrap();
store.player_remote_session_set(&row).unwrap();
let mut other = row.clone();
other.session_id = Uuid::now_v7();
assert!(store.player_remote_session_set(&other).is_err());
other = row.clone();
other.public_key = "changed-key".into();
assert!(store.player_remote_session_set(&other).is_err());
}
let store = ControlStore::open(dir.path()).unwrap();
let recovered = store.player_remote_sessions().unwrap().pop().unwrap();
assert_eq!(
(recovered.session_id, recovered.public_key),
(row.session_id, row.public_key)
);
store
.player_remote_session_remove(row.character_id, Uuid::now_v7())
.unwrap();
assert_eq!(store.player_remote_sessions().unwrap().len(), 1);
store
.player_remote_session_remove(row.character_id, row.session_id)
.unwrap();
assert!(store.player_remote_sessions().unwrap().is_empty());
}
#[test] #[test]
fn a_player_owns_one_account_per_realm_and_an_account_one_player() { fn a_player_owns_one_account_per_realm_and_an_account_one_player() {
let s = ControlStore::open_in_memory().unwrap(); let s = ControlStore::open_in_memory().unwrap();
@@ -677,6 +800,7 @@ mod tests {
realm_local_id: "live".into(), realm_local_id: "live".into(),
transfer_id: t, transfer_id: t,
character_id: c, character_id: c,
ruleset: "coa".into(),
player_id: p, player_id: p,
revision: 3, revision: 3,
content_hash: "a".repeat(64), content_hash: "a".repeat(64),
Loaded 100 of 280 files, more files were not shown because too many files have changed in this diff. Show more