@hadoku/game-server 0.0.0-stage → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/LICENSE +21 -0
  2. package/dist/base-path.d.ts +29 -0
  3. package/dist/base-path.js +30 -0
  4. package/dist/busy.d.ts +40 -0
  5. package/dist/busy.js +23 -0
  6. package/dist/capacity.d.ts +9 -0
  7. package/dist/capacity.js +6 -0
  8. package/dist/config.d.ts +247 -0
  9. package/dist/config.js +271 -0
  10. package/dist/edge-auth.d.ts +43 -0
  11. package/dist/edge-auth.js +47 -0
  12. package/dist/erase/anonymise.d.ts +7 -0
  13. package/dist/erase/anonymise.js +7 -0
  14. package/dist/erase/index.d.ts +18 -0
  15. package/dist/erase/index.js +20 -0
  16. package/dist/erase/legacy-ids.d.ts +7 -0
  17. package/dist/erase/legacy-ids.js +24 -0
  18. package/dist/erase/recordings.d.ts +26 -0
  19. package/dist/erase/recordings.js +128 -0
  20. package/dist/erase/rooms.d.ts +63 -0
  21. package/dist/erase/rooms.js +67 -0
  22. package/dist/gate.d.ts +27 -0
  23. package/dist/gate.js +15 -0
  24. package/dist/http/client-events.d.ts +25 -0
  25. package/dist/http/client-events.js +15 -0
  26. package/dist/http/page.d.ts +26 -0
  27. package/dist/http/page.js +35 -0
  28. package/dist/http/prepared.d.ts +14 -0
  29. package/dist/http/prepared.js +16 -0
  30. package/dist/http/request.d.ts +59 -0
  31. package/dist/http/request.js +37 -0
  32. package/dist/http/room-core.d.ts +160 -0
  33. package/dist/http/room-core.js +278 -0
  34. package/dist/http/trim.d.ts +23 -0
  35. package/dist/http/trim.js +76 -0
  36. package/dist/http/usage.d.ts +22 -0
  37. package/dist/http/usage.js +16 -0
  38. package/dist/kernel.d.ts +4 -0
  39. package/dist/kernel.js +26 -0
  40. package/dist/log.d.ts +9 -0
  41. package/dist/log.js +9 -0
  42. package/dist/people.d.ts +105 -0
  43. package/dist/people.js +145 -0
  44. package/dist/play/clock.d.ts +39 -0
  45. package/dist/play/clock.js +81 -0
  46. package/dist/play/diagnostics.d.ts +21 -0
  47. package/dist/play/diagnostics.js +35 -0
  48. package/dist/play/engine-runtime.d.ts +200 -0
  49. package/dist/play/engine-runtime.js +309 -0
  50. package/dist/play/game-adapter.d.ts +158 -0
  51. package/dist/play/game-adapter.js +1 -0
  52. package/dist/play/host.d.ts +482 -0
  53. package/dist/play/host.js +950 -0
  54. package/dist/play/jvm-transport.d.ts +25 -0
  55. package/dist/play/jvm-transport.js +1 -0
  56. package/dist/play/local-jvm.d.ts +325 -0
  57. package/dist/play/local-jvm.js +829 -0
  58. package/dist/play/match/hosted.d.ts +92 -0
  59. package/dist/play/match/hosted.js +151 -0
  60. package/dist/play/match/outcome.d.ts +26 -0
  61. package/dist/play/match/outcome.js +21 -0
  62. package/dist/play/match/shell.d.ts +378 -0
  63. package/dist/play/match/shell.js +613 -0
  64. package/dist/play/recording/retention.d.ts +36 -0
  65. package/dist/play/recording/retention.js +89 -0
  66. package/dist/play/recording/writer.d.ts +185 -0
  67. package/dist/play/recording/writer.js +90 -0
  68. package/dist/play/relay-socket.d.ts +128 -0
  69. package/dist/play/relay-socket.js +194 -0
  70. package/dist/play/runtimes/in-process.d.ts +47 -0
  71. package/dist/play/runtimes/in-process.js +43 -0
  72. package/dist/play/runtimes/relay-match.d.ts +166 -0
  73. package/dist/play/runtimes/relay-match.js +240 -0
  74. package/dist/play/runtimes/relay.d.ts +128 -0
  75. package/dist/play/runtimes/relay.js +183 -0
  76. package/dist/play/runtimes/streamed.d.ts +116 -0
  77. package/dist/play/runtimes/streamed.js +148 -0
  78. package/dist/play/start-queue.d.ts +65 -0
  79. package/dist/play/start-queue.js +187 -0
  80. package/dist/room/avatar.d.ts +1 -0
  81. package/dist/room/avatar.js +28 -0
  82. package/dist/room/caller.d.ts +21 -0
  83. package/dist/room/caller.js +1 -0
  84. package/dist/room/constants.d.ts +27 -0
  85. package/dist/room/constants.js +27 -0
  86. package/dist/room/events.d.ts +59 -0
  87. package/dist/room/events.js +174 -0
  88. package/dist/room/identity.d.ts +89 -0
  89. package/dist/room/identity.js +98 -0
  90. package/dist/room/lobby.d.ts +426 -0
  91. package/dist/room/lobby.js +880 -0
  92. package/dist/room/membership.d.ts +64 -0
  93. package/dist/room/membership.js +76 -0
  94. package/dist/room/provisioning.d.ts +22 -0
  95. package/dist/room/provisioning.js +46 -0
  96. package/dist/room/record.d.ts +63 -0
  97. package/dist/room/record.js +39 -0
  98. package/dist/room/room-list.d.ts +67 -0
  99. package/dist/room/room-list.js +66 -0
  100. package/dist/room/seats.d.ts +39 -0
  101. package/dist/room/seats.js +58 -0
  102. package/dist/room/session.d.ts +91 -0
  103. package/dist/room/session.js +156 -0
  104. package/dist/room/socket-auth.d.ts +2 -0
  105. package/dist/room/socket-auth.js +10 -0
  106. package/dist/room/watching.d.ts +35 -0
  107. package/dist/room/watching.js +72 -0
  108. package/dist/room/watchparty-link.d.ts +1 -0
  109. package/dist/room/watchparty-link.js +17 -0
  110. package/dist/stream/alloc.d.ts +115 -0
  111. package/dist/stream/alloc.js +368 -0
  112. package/dist/stream/index.d.ts +66 -0
  113. package/dist/stream/index.js +293 -0
  114. package/dist/telemetry.d.ts +46 -0
  115. package/dist/telemetry.js +25 -0
  116. package/dist/testPort.d.ts +1 -0
  117. package/dist/testPort.js +28 -0
  118. package/package.json +36 -4
  119. package/README.md +0 -3
package/dist/config.js ADDED
@@ -0,0 +1,271 @@
1
+ /**
2
+ * Runtime config for the Cardtable loopback-UI tunnel server.
3
+ *
4
+ * Every value is env-overridable so the PM2 wrapper (which pulls them from the
5
+ * vault broker) can inject them without a code edit.
6
+ */
7
+ import { homedir, tmpdir } from 'node:os';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
10
+ const HERE = dirname(fileURLToPath(import.meta.url));
11
+ /**
12
+ * The site's own directory (`apps/server`, whose `dist/` PM2 runs), whatever the process's working directory — PM2
13
+ * starts us from the repo root, `pnpm start` from the package dir, and the two must agree. Bundled,
14
+ * this module is part of `apps/server/dist/*.js`, so it is `dist/`'s parent; run as source (tests,
15
+ * tsx) it is `packages/game-server/src/`, and the app it configures is `apps/server` beside it.
16
+ */
17
+ export const APP_ROOT = basename(HERE) === 'dist' ? dirname(HERE) : resolve(HERE, '../../../apps/server');
18
+ /** Resolve a configured path against the package root unless it is absolute. */
19
+ const resolveDir = (value) => isAbsolute(value) ? value : resolve(APP_ROOT, value);
20
+ /**
21
+ * Where the server keeps what it writes (`CARDTABLE_STATE_DIR`): rooms, drafts,
22
+ * recordings and the rest of `data/` directly in it, and `logs/` beside them.
23
+ * Outside the clone, so a deploy can build a new clone aside and swap it in
24
+ * while this one serves. Unset (dev, tests, e2e) = the old in-clone layout,
25
+ * `logs/` and `data/` in the package. `state-dir.ts` moves the in-clone copy
26
+ * here on the first boot that has it.
27
+ */
28
+ const STATE_DIR = process.env.CARDTABLE_STATE_DIR ? resolveDir(process.env.CARDTABLE_STATE_DIR) : '';
29
+ const LOG_DIR = resolveDir(process.env.CARDTABLE_LOG_DIR || (STATE_DIR ? join(STATE_DIR, 'logs') : 'logs'));
30
+ const DATA_DIR = STATE_DIR || resolve(LOG_DIR, '../data');
31
+ /** The in-clone paths a state dir replaces, for the boot move (`state-dir.ts`). */
32
+ export const LEGACY_STATE = { dataDir: resolve(APP_ROOT, 'data'), logDir: resolve(APP_ROOT, 'logs') };
33
+ export const CONFIG = {
34
+ /** Port this server listens on. cloudflared points the tunnel hostname here. */
35
+ port: parseInt(process.env.CARDTABLE_PORT || '9008', 10),
36
+ /**
37
+ * Loopback only. The tunnel is the single ingress; binding 0.0.0.0 would put
38
+ * this on the LAN with no gate in front of it, because the gate is at the edge.
39
+ */
40
+ host: process.env.CARDTABLE_HOST || '127.0.0.1',
41
+ /**
42
+ * The public prefix the BROWSER sees: hadoku.me/cardtable/…
43
+ *
44
+ * Edge-router stripPrefixes it before forwarding, so THIS process is served
45
+ * root paths — but every URL the built bundle emits must still carry the
46
+ * prefix, or the browser requests /assets/x.js instead of /cardtable/assets/x.js
47
+ * and the page loads blank. assertBasePath() checks that at boot.
48
+ */
49
+ basePrefix: process.env.CARDTABLE_BASE_PREFIX || '/cardtable',
50
+ /**
51
+ * The built SPA this server serves off local disk. There is no GitHub-Pages
52
+ * shell and no published micro-frontend bundle for a loopback-UI app — this
53
+ * directory IS the front end, and `pnpm build` in the child repo produces it.
54
+ */
55
+ // `../ui/dist` because this repo splits the halves across workspace members:
56
+ // apps/ui builds the SPA, apps/server hands it out. The PM2 wrapper passes an
57
+ // absolute CARDTABLE_WEB_DIR in production; this default is what makes
58
+ // `pnpm --filter @hadoku/server dev` work straight after `pnpm -r build`.
59
+ webDir: resolveDir(process.env.CARDTABLE_WEB_DIR || '../ui/dist'),
60
+ /**
61
+ * Tier floor enforced here as a SECOND seal, independent of route-tiers.ts.
62
+ *
63
+ * The edge gate is the real one, but it lives in another repo on another
64
+ * deploy cadence, and the tunnel hostname is reachable without it. A floor
65
+ * here means a route-tiers edit cannot silently widen this app on its own.
66
+ */
67
+ minTier: process.env.CARDTABLE_MIN_TIER || 'friend',
68
+ /**
69
+ * Shared secret edge-router stamps as X-Edge-Auth on everything it proxies
70
+ * (workers/shared/edgeAuth.ts). Identity headers are believed ONLY when this
71
+ * matches. Unset = FAIL CLOSED: every request is degraded to public/anon.
72
+ */
73
+ edgeAuthSecret: process.env.EDGE_AUTH_SECRET || '',
74
+ /**
75
+ * Bare-local dev escape hatch. With EDGE_AUTH_SECRET unset this server fails
76
+ * closed and strips tier/identity from every request, which locks a local
77
+ * browser out of its own app. Never set where the tunnel host is reachable.
78
+ */
79
+ allowUnverifiedEdge: process.env.CARDTABLE_INSECURE_NO_EDGE_AUTH === '1',
80
+ /**
81
+ * Identity granted to a header-less caller while allowUnverifiedEdge is on.
82
+ * Defaults to the floor, so `pnpm dev` serves the app to a local browser
83
+ * instead of 404ing it. Read ONLY on that path — it grants nothing in
84
+ * production, where the hatch is off and provenance decides.
85
+ */
86
+ devTier: process.env.CARDTABLE_DEV_TIER || process.env.CARDTABLE_MIN_TIER || 'friend',
87
+ /**
88
+ * This server's own service-tier key for the game-stats store and for
89
+ * people's prefs rows, from the vault via the PM2 wrapper. Unset = match
90
+ * stats are off (logged once), and a music-review read or write is refused
91
+ * by prefs-api and answers 502.
92
+ */
93
+ serviceKey: process.env.CARDTABLE_SERVICE_KEY || '',
94
+ /**
95
+ * The prefs mount people's own rows are read and written on (`http/musicReviewStore.ts`),
96
+ * without `/api/v1`, with the same service key.
97
+ */
98
+ prefsBaseUrl: process.env.CARDTABLE_PREFS_BASE_URL || 'https://hadoku.me/prefs',
99
+ /**
100
+ * Where security telemetry is posted (`/health/api/telemetry` under it), with
101
+ * the same service key as the stats. Unset key = telemetry is off (logged once).
102
+ */
103
+ monitoringBaseUrl: process.env.CARDTABLE_MONITORING_BASE_URL || 'https://hadoku.me',
104
+ /** Watchparty's origin, whose sprites draw a member's character on a room's link preview (`http/preview.ts`). */
105
+ watchpartyBaseUrl: process.env.CARDTABLE_WATCHPARTY_BASE_URL || 'https://hadoku.me/watchparty',
106
+ /** Every user id this server has admitted, so `caller-first-seen` fires once per account. */
107
+ callersSeenFile: process.env.CARDTABLE_CALLERS_SEEN_FILE ?? join(DATA_DIR, 'callers-seen.json'),
108
+ /** The prefs mount the stats are reported to, without `/api/v1`. */
109
+ statsBaseUrl: process.env.CARDTABLE_STATS_BASE_URL || 'https://hadoku.me/prefs',
110
+ /**
111
+ * ArchiveBot's webhook secret for this app, from the vault via the PM2 wrapper. Prod's wrapper
112
+ * holds it and PPE's does not, which is what keeps release notes a prod-only post. Unset = the
113
+ * boot announcement is skipped (`announce.ts`).
114
+ */
115
+ archivebotSecret: process.env.ARCHIVEBOT_CARDTABLE_WEBHOOK_SECRET || '',
116
+ /** ArchiveBot's webhook server, on loopback beside this one. */
117
+ archivebotUrl: process.env.CARDTABLE_ARCHIVEBOT_URL || 'http://127.0.0.1:3004',
118
+ /** `CARDTABLE_STATE_DIR`, resolved; empty when unset (the in-clone layout). */
119
+ stateDir: STATE_DIR,
120
+ /** Structured access log destination (gitignored, created on boot). */
121
+ logDir: LOG_DIR,
122
+ /**
123
+ * The server's persisted state: the state dir itself when one is set, else
124
+ * `data/` beside the log directory. `data/` is gitignored, so a `git pull`
125
+ * deploy leaves it alone; e2e sets CARDTABLE_LOG_DIR and therefore gets its
126
+ * own directory rather than production's.
127
+ */
128
+ dataDir: DATA_DIR,
129
+ /** Every pod that played a round, kept past its room (`CARDTABLE_TOURNAMENTS_FILE`). */
130
+ tournamentsFile: process.env.CARDTABLE_TOURNAMENTS_FILE ?? join(DATA_DIR, 'tournaments.json'),
131
+ /** The front page's scheduled events (`CARDTABLE_EVENTS_FILE`). */
132
+ eventsFile: process.env.CARDTABLE_EVENTS_FILE ?? join(DATA_DIR, 'events.json'),
133
+ /** The lobby's rooms, one file each (`CARDTABLE_ROOMS_DIR`). */
134
+ roomsDir: process.env.CARDTABLE_ROOMS_DIR ?? join(DATA_DIR, 'rooms'),
135
+ /** The sound builder's uploads and assignments (`CARDTABLE_SOUNDS_DIR`). */
136
+ soundsDir: process.env.CARDTABLE_SOUNDS_DIR ?? join(DATA_DIR, 'sounds'),
137
+ /**
138
+ * How long a draft bot takes over a pick (`CARDTABLE_DRAFT_BOT_PICK_MS`): every
139
+ * bot holding a pack takes one card per turn. Long enough that bots do not
140
+ * drain a pod into the slowest human's pile at once, short enough that a
141
+ * quick drafter rarely waits on one.
142
+ */
143
+ draftBotPickMs: parseInt(process.env.CARDTABLE_DRAFT_BOT_PICK_MS || '1200', 10),
144
+ /**
145
+ * A CubeCobra draftbot service for the bots' picks (`room/draftbot.ts`), and its
146
+ * `X-Internal-Token`. Unset: no draftbot, every bot pick is the heuristic's.
147
+ */
148
+ draftbotUrl: process.env.CARDTABLE_DRAFTBOT_URL || '',
149
+ draftbotToken: process.env.CARDTABLE_DRAFTBOT_TOKEN || '',
150
+ /** Each draft's state, so a pod survives a restart (`CARDTABLE_DRAFTS_DIR`). */
151
+ draftsDir: process.env.CARDTABLE_DRAFTS_DIR ?? join(DATA_DIR, 'drafts'),
152
+ /** A friend's Cube Cobra imports, flat `<id>.json` (`CARDTABLE_CUBES_DIR`). */
153
+ cubesDir: process.env.CARDTABLE_CUBES_DIR ?? join(DATA_DIR, 'cubes'),
154
+ /** Every match's action log and public stream (`play/recording/`, `CARDTABLE_RECORDINGS_DIR`). */
155
+ recordingsDir: process.env.CARDTABLE_RECORDINGS_DIR ?? join(DATA_DIR, 'recordings'),
156
+ /** Every game both players walked away from, kept to be resumed (`play/parked.ts`, `CARDTABLE_PARKED_DIR`). */
157
+ parkedDir: process.env.CARDTABLE_PARKED_DIR ?? join(DATA_DIR, 'parked'),
158
+ /** The card catalog the pools resolve against (`CARDTABLE_CATALOG`). */
159
+ catalogPath: process.env.CARDTABLE_CATALOG ?? resolve(homedir(), '.local/share/cardtable/catalog/cards.json'),
160
+ /** The art mirror's log (`upload-art`, `CARDTABLE_ART_MIRROR`): which CDN object holds each card image. Missing, every image is Scryfall's. */
161
+ artMirrorPath: process.env.CARDTABLE_ART_MIRROR ?? resolve(homedir(), '.local/share/cardtable/art/mirror.jsonl'),
162
+ /**
163
+ * `CARDTABLE_NEW_ROOM_FORMAT=newest` pins every new room to the newest
164
+ * Standard era instead of a random one: the e2e harnesses set it, because
165
+ * their specs read a fresh room's pool and a run must not depend on a draw.
166
+ */
167
+ newRoomFormat: process.env.CARDTABLE_NEW_ROOM_FORMAT,
168
+ /**
169
+ * Where Forge matches run (`CARDTABLE_PLAY_HOSTS`): `local`, this machine, as always (the
170
+ * default until the claw acceptance run passes), or `claws`, placed across the hosting claws'
171
+ * agents with this machine as the backstop (`play/placement/`). Anything else is `local`.
172
+ */
173
+ playHosts: process.env.CARDTABLE_PLAY_HOSTS === 'claws' ? 'claws' : 'local',
174
+ /**
175
+ * The hosting alerts' Discord webhook, from the vault via the PM2 wrapper
176
+ * (`.devvault.json`: `DISCORD_CARDTABLE_ALERT_WEBHOOK`). Unset = alerts are logged, not posted.
177
+ */
178
+ alertWebhook: process.env.DISCORD_CARDTABLE_ALERT_WEBHOOK || '',
179
+ /** How long, past the fencing window, the claws' agents hold their JVMs for the next server on a restart. */
180
+ restartGraceMs: parseInt(process.env.CARDTABLE_PLAY_RESTART_GRACE_MS || '90000', 10),
181
+ /** The operator's time-boxed force of the backstop host onto the Forge backstop: a JSON file `{"until":"<ISO>"}`. */
182
+ backstopForceFile: process.env.CARDTABLE_BACKSTOP_FORCE_FILE ?? join(DATA_DIR, 'backstop-force.json'),
183
+ /** `CARDTABLE_PLAY_PROBE=1`: the e2e harness's dev diagnostics — the scenario routes and the frame and stop traces. Never on in production. */
184
+ playProbe: process.env.CARDTABLE_PLAY_PROBE === '1',
185
+ /**
186
+ * `CARDTABLE_PLAY_REJOIN_GRACE_MS`: how long a match nobody is at waits before it is parked
187
+ * (`play/socket.ts`'s `PlayDeps.rejoinGraceMs`). Unset is play's own five minutes; a spec that
188
+ * parks a game sets it shorter. Never set by the deploy path.
189
+ */
190
+ playRejoinGraceMs: process.env.CARDTABLE_PLAY_REJOIN_GRACE_MS === undefined ? undefined : parseInt(process.env.CARDTABLE_PLAY_REJOIN_GRACE_MS, 10),
191
+ /**
192
+ * `CARDTABLE_E2E_UNCHECKED_POOLS=1`: the jar-less e2e stack's own escape
193
+ * hatch, wave 73 §A follow-up (CI `check` run 39715510788: a jar-less
194
+ * server can never pass a plan's verdict, so `Lobby.startDraft` refused
195
+ * `plan-not-ready` forever and `draft.spec`'s "two friends draft a whole
196
+ * pod" never dealt).
197
+ *
198
+ * With it, `room/plan.ts`'s `checkCards` answers OK for a source whose
199
+ * cards all resolved (`missingText` still refuses — this is an escape from
200
+ * "no jar", never from "no catalog text") instead of refusing with "Forge
201
+ * is not available". A source checked WITH a jar is unaffected either way:
202
+ * nothing here ever stands in for a real `forge.check`.
203
+ *
204
+ * Nothing in this repo's own deploy path (the PM2 wrapper, the vault
205
+ * broker) ever sets this — `config.test.ts` pins that a config built from
206
+ * a bare `process.env` (nothing set) reads `false`. `e2e/harness.ts` sets
207
+ * it on its OWN jar-less server only (never `e2e/play/harness.ts`'s,
208
+ * which has a real jar and keeps running the real check regardless of
209
+ * this flag). `index.ts` logs a boot warning whenever it reads true, the
210
+ * same register `EDGE_AUTH_SECRET`'s own dev hatch warns at.
211
+ */
212
+ testUncheckedPools: process.env.CARDTABLE_E2E_UNCHECKED_POOLS === '1',
213
+ /**
214
+ * `CARDTABLE_E2E_NO_RATE_LIMITS=1`: both e2e stacks' escape from the
215
+ * per-caller limits on making rooms, organizing events and starting matches
216
+ * (`http/request.ts`'s `perCallerLimit`). One test identity makes every room
217
+ * and starts every match of a whole run, far past any limit a person meets.
218
+ * Never set by the deploy path; `config.test.ts` pins it false from a bare
219
+ * environment, and `index.ts` warns at boot whenever it reads true.
220
+ */
221
+ testNoRateLimits: process.env.CARDTABLE_E2E_NO_RATE_LIMITS === '1',
222
+ /**
223
+ * `CARDTABLE_E2E_PEOPLE_STAND_IN=1`: look people up (`people.ts`) without a
224
+ * service key, from the e2e edge's prefs-api stand-in at `prefsBaseUrl`. The
225
+ * e2e stacks hold no key, which is what keeps match stats off there, and
226
+ * without this no spec could see a look. Never set by the deploy path.
227
+ */
228
+ testPeopleStandIn: process.env.CARDTABLE_E2E_PEOPLE_STAND_IN === '1',
229
+ /**
230
+ * `CARDTABLE_CATALOG_REFRESH`: on by default, so production needs no
231
+ * cross-repo change to keep its catalog current with Scryfall's daily
232
+ * bulk file (`pools/refresh.ts`, wave 74 §G). `index.ts` starts the job
233
+ * only when this reads `true`.
234
+ *
235
+ * Off (`'0'`) is for every server that is NOT production: CI's forge-e2e
236
+ * on the claws, every dev/e2e server a session boots, and a lane's own
237
+ * manual smoke-boot. Each of those would otherwise run `createCatalogRefresh`
238
+ * against `CARDTABLE_SCRYFALL_DIR ?? ~/.local/share/cardtable/scryfall` at
239
+ * its own boot — a real Scryfall download, every time, into land.sh's
240
+ * SHARED art cache when the default path is in play (`e2e/harness.ts` and
241
+ * `e2e/play/harness.ts` set this to `'0'` in the server env they spawn,
242
+ * for exactly this reason — one lane's `.partial` file there is what
243
+ * found this).
244
+ */
245
+ catalogRefresh: process.env.CARDTABLE_CATALOG_REFRESH !== '0',
246
+ /**
247
+ * `CARDTABLE_PLAY_SEED`: fixes Forge's shuffles, the coin toss and the precon
248
+ * pick for every match this server starts, or undefined (production) for an
249
+ * unseeded one. Read at each start, not at boot, so a test can set it.
250
+ */
251
+ get playSeed() {
252
+ const raw = process.env.CARDTABLE_PLAY_SEED;
253
+ const seed = raw === undefined || raw === '' ? Number.NaN : Number(raw);
254
+ return Number.isFinite(seed) ? seed : undefined;
255
+ },
256
+ /** Container n's noVNC port is this plus n (the static bench publishes 127.0.0.1:6080+n). */
257
+ streamBasePort: Number(process.env.CARDTABLE_STREAM_PORT ?? 6080),
258
+ /** The first host port a room's seat stream may take — see `stream/alloc.ts`. */
259
+ roomStreamBasePort: Number(process.env.CARDTABLE_ROOM_STREAM_PORT ?? 6100),
260
+ /** The name every room stream container this server owns starts with; `scripts/stream/container.sh` reads the same variable. */
261
+ streamNamePrefix: process.env.CARDTABLE_STREAM_NAME_PREFIX ?? 'cardtable-room',
262
+ };
263
+ /**
264
+ * Where a Forge match's run directories go (`CARDTABLE_PLAY_WORK_DIR`). Takes the
265
+ * environment as an argument, as `play/host.ts`'s `jvmHostConfig` does, so a test
266
+ * can point one host at its own directory.
267
+ */
268
+ export function playWorkDir(env = process.env) {
269
+ return resolve(env.CARDTABLE_PLAY_WORK_DIR ?? join(tmpdir(), 'cardtable-play'));
270
+ }
271
+ export const INDEX_HTML = join(CONFIG.webDir, 'index.html');
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Edge provenance and the tier floor — cardtable's binding of the platform
3
+ * kernel (`@hadoku/service-kernel/auth`). The shared `createEdgeAuth`/`createGate`
4
+ * instances live in `kernel.ts` (w93-Z); this file keeps every export's old
5
+ * name and signature, so the rest of the app needs no edit.
6
+ *
7
+ * edge-router resolves the caller's tier once and stamps every request it
8
+ * proxies with X-Edge-Auth: <EDGE_AUTH_SECRET> plus X-Hadoku-Tier / X-User-Id /
9
+ * X-User-Key / X-User-Name / X-Hadoku-Verified. The tunnel hostname is reachable DIRECTLY,
10
+ * bypassing the edge — so a direct hit could forge those headers. We believe
11
+ * them only when the shared secret checks out; otherwise we overwrite them with
12
+ * the most restrictive identity.
13
+ */
14
+ import { TIER_ORDER, type Tier, rankOf, tierOf, verifiedOf, verifiedFromHeaders, callerIdOf, userIdOf, userKeyOf, accountIdOf, userNameOf, isAdmin } from '@wolffm/service-kernel/auth';
15
+ export { TIER_ORDER, rankOf, tierOf, verifiedOf, verifiedFromHeaders, callerIdOf, userIdOf, userKeyOf, accountIdOf, userNameOf, isAdmin };
16
+ export type { Tier };
17
+ /**
18
+ * The floor must be a tier this build knows, and never `public` here —
19
+ * cardtable admits members and friends, never the public tier. An unknown
20
+ * name ranks as public in `rankOf`, so a floor this build has not heard of
21
+ * (`CARDTABLE_MIN_TIER=member` on a build without `member`) would silently
22
+ * admit everyone, the direct tunnel hits included. Refusing to boot is the
23
+ * only safe answer.
24
+ */
25
+ export declare function assertFloor(tier: string): Tier;
26
+ /** Force a public/anon identity unless edge provenance is proven. */
27
+ export declare const sanitizeHeaders: (headers: Record<string, unknown>) => void;
28
+ /**
29
+ * Did this request carry the edge's own seal? Not the bare-local hatch, which
30
+ * believes any header: a route only the edge may call (the account-erase hook)
31
+ * asks this rather than a tier.
32
+ */
33
+ export declare const edgeSealed: (req: import("express").Request) => boolean;
34
+ /** Express middleware: sanitize provenance on every inbound request. */
35
+ export declare const edgeProvenance: (req: import("express").Request, res: import("express").Response, next: import("express").NextFunction) => void;
36
+ /**
37
+ * Express middleware: refuse anything below the configured floor.
38
+ *
39
+ * 404, not 403. A private app should not confirm its own existence to a caller
40
+ * who was never meant to reach it — and a browser that somehow arrives here
41
+ * unauthenticated gets the same answer as a scanner.
42
+ */
43
+ export declare const requireMinTier: (req: import("express").Request, res: import("express").Response, next: import("express").NextFunction) => void;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Edge provenance and the tier floor — cardtable's binding of the platform
3
+ * kernel (`@hadoku/service-kernel/auth`). The shared `createEdgeAuth`/`createGate`
4
+ * instances live in `kernel.ts` (w93-Z); this file keeps every export's old
5
+ * name and signature, so the rest of the app needs no edit.
6
+ *
7
+ * edge-router resolves the caller's tier once and stamps every request it
8
+ * proxies with X-Edge-Auth: <EDGE_AUTH_SECRET> plus X-Hadoku-Tier / X-User-Id /
9
+ * X-User-Key / X-User-Name / X-Hadoku-Verified. The tunnel hostname is reachable DIRECTLY,
10
+ * bypassing the edge — so a direct hit could forge those headers. We believe
11
+ * them only when the shared secret checks out; otherwise we overwrite them with
12
+ * the most restrictive identity.
13
+ */
14
+ import { TIER_ORDER, assertFloor as kernelAssertFloor, rankOf, tierOf, verifiedOf, verifiedFromHeaders, callerIdOf, userIdOf, userKeyOf, accountIdOf, userNameOf, isAdmin, } from '@wolffm/service-kernel/auth';
15
+ import { CONFIG } from './config.js';
16
+ import { ENV_PREFIX, edgeAuth, gate } from './kernel.js';
17
+ export { TIER_ORDER, rankOf, tierOf, verifiedOf, verifiedFromHeaders, callerIdOf, userIdOf, userKeyOf, accountIdOf, userNameOf, isAdmin };
18
+ /**
19
+ * The floor must be a tier this build knows, and never `public` here —
20
+ * cardtable admits members and friends, never the public tier. An unknown
21
+ * name ranks as public in `rankOf`, so a floor this build has not heard of
22
+ * (`CARDTABLE_MIN_TIER=member` on a build without `member`) would silently
23
+ * admit everyone, the direct tunnel hits included. Refusing to boot is the
24
+ * only safe answer.
25
+ */
26
+ export function assertFloor(tier) {
27
+ return kernelAssertFloor(tier, { envPrefix: ENV_PREFIX, allowPublic: false });
28
+ }
29
+ assertFloor(CONFIG.minTier);
30
+ /** Force a public/anon identity unless edge provenance is proven. */
31
+ export const sanitizeHeaders = edgeAuth.sanitizeHeaders;
32
+ /**
33
+ * Did this request carry the edge's own seal? Not the bare-local hatch, which
34
+ * believes any header: a route only the edge may call (the account-erase hook)
35
+ * asks this rather than a tier.
36
+ */
37
+ export const edgeSealed = edgeAuth.edgeSealed;
38
+ /** Express middleware: sanitize provenance on every inbound request. */
39
+ export const edgeProvenance = edgeAuth.edgeProvenance;
40
+ /**
41
+ * Express middleware: refuse anything below the configured floor.
42
+ *
43
+ * 404, not 403. A private app should not confirm its own existence to a caller
44
+ * who was never meant to reach it — and a browser that somehow arrives here
45
+ * unauthenticated gets the same answer as a scanner.
46
+ */
47
+ export const requireMinTier = gate.requireMinTier;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Adapter: cardtable's binding of `@hadoku/service-kernel/erase`'s `placeholderId`/`replaceIds`
3
+ * (w93-K3). Both are fully generic (no cardtable value baked in), so this is a pure re-export kept
4
+ * at this path for its importers (`erase/recordings.ts`, `room/draftRooms.ts`, `room/events.ts`,
5
+ * `room/lobby.ts`, `room/tournaments.ts`).
6
+ */
7
+ export { placeholderId, replaceIds } from '@wolffm/service-kernel/erase';
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Adapter: cardtable's binding of `@hadoku/service-kernel/erase`'s `placeholderId`/`replaceIds`
3
+ * (w93-K3). Both are fully generic (no cardtable value baked in), so this is a pure re-export kept
4
+ * at this path for its importers (`erase/recordings.ts`, `room/draftRooms.ts`, `room/events.ts`,
5
+ * `room/lobby.ts`, `room/tournaments.ts`).
6
+ */
7
+ export { placeholderId, replaceIds } from '@wolffm/service-kernel/erase';
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Cardtable's binding of `@hadoku/service-kernel/erase` — `POST /api/_account/erase`.
3
+ *
4
+ * The edge calls it on the tunnel origin with `X-Edge-Auth` (its seal), `X-Hadoku-Tier: member`
5
+ * and `X-User-Id`. Only the seal admits it (`createGameServer` passes `edgeAuth.edgeSealed`), never
6
+ * a tier: the bare-local escape hatch believes any header and so does NOT open this route. The
7
+ * kernel mounts it above the floor and `firstSeen`: the edge sends `member`, which a wrapper that
8
+ * lost `CARDTABLE_MIN_TIER` would 404, and `firstSeen` would record the person again on the very
9
+ * call that erases them.
10
+ *
11
+ * What stays here is the `fk:` id a person is also known by (`room/identity.ts`), which the
12
+ * kernel is handed as `deriveParticipantId`, and the steps' shared types.
13
+ */
14
+ import { ERASE_PATH, type AccountErase, type EraseCounts, type ErasedPerson, type EraseStep } from '@wolffm/service-kernel/erase';
15
+ export { ERASE_PATH };
16
+ export type { AccountErase, EraseCounts, ErasedPerson, EraseStep };
17
+ export declare const fkOf: (userId: string) => string;
18
+ export declare function personOf(userId: string): ErasedPerson;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Cardtable's binding of `@hadoku/service-kernel/erase` — `POST /api/_account/erase`.
3
+ *
4
+ * The edge calls it on the tunnel origin with `X-Edge-Auth` (its seal), `X-Hadoku-Tier: member`
5
+ * and `X-User-Id`. Only the seal admits it (`createGameServer` passes `edgeAuth.edgeSealed`), never
6
+ * a tier: the bare-local escape hatch believes any header and so does NOT open this route. The
7
+ * kernel mounts it above the floor and `firstSeen`: the edge sends `member`, which a wrapper that
8
+ * lost `CARDTABLE_MIN_TIER` would 404, and `firstSeen` would record the person again on the very
9
+ * call that erases them.
10
+ *
11
+ * What stays here is the `fk:` id a person is also known by (`room/identity.ts`), which the
12
+ * kernel is handed as `deriveParticipantId`, and the steps' shared types.
13
+ */
14
+ import { ERASE_PATH, personOf as kernelPersonOf, } from '@wolffm/service-kernel/erase';
15
+ import { deriveParticipantId } from '../room/identity.js';
16
+ export { ERASE_PATH };
17
+ export const fkOf = (userId) => deriveParticipantId({ accountId: userId, socketId: '' });
18
+ export function personOf(userId) {
19
+ return kernelPersonOf(userId, fkOf);
20
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * `legacy-ids.done.json`: the record the R12 identity reset's one-off remap left behind on
3
+ * prod (old key-derived id → the userId it was moved to). Nothing reads it any more, but it
4
+ * names people by userId, so an erase removes the person's entries from it. Absent is fine.
5
+ */
6
+ import type { EraseStep } from './index.js';
7
+ export declare function legacyIdsStep(file: string): EraseStep;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * `legacy-ids.done.json`: the record the R12 identity reset's one-off remap left behind on
3
+ * prod (old key-derived id → the userId it was moved to). Nothing reads it any more, but it
4
+ * names people by userId, so an erase removes the person's entries from it. Absent is fine.
5
+ */
6
+ import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
7
+ export function legacyIdsStep(file) {
8
+ return {
9
+ what: 'legacyIds',
10
+ erase: ({ userId }) => {
11
+ if (!existsSync(file))
12
+ return 0;
13
+ const map = JSON.parse(readFileSync(file, 'utf8'));
14
+ const theirs = Object.keys(map).filter((old) => map[old] === userId);
15
+ if (theirs.length === 0)
16
+ return 0;
17
+ for (const old of theirs)
18
+ delete map[old];
19
+ writeFileSync(`${file}.tmp`, JSON.stringify(map));
20
+ renameSync(`${file}.tmp`, file);
21
+ return theirs.length;
22
+ },
23
+ };
24
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Account erase in the match recordings (the operator's ruling, 2026-11-05: anonymise the
3
+ * seat). A recording keeps each seat holder's userId on an `end` line (the public stream's
4
+ * `seats`, or a by-seat `users`, which the 90-day action log may carry), and both files carry the seat's name as it was played: the public header's `players`, the action
5
+ * log's `spec.seats`, and Forge's own views, which name each player.
6
+ *
7
+ * So a recording whose end line, in either file, names the person loses that userId, and the name its seat was
8
+ * played under becomes the room's own word for an unnamed member (`UNNAMED`) everywhere in
9
+ * both files. Not blank: the action log's names are Forge's player names when a replay is
10
+ * rebuilt, and Forge is given a name. Each file keeps its mtime, which is what retention ages
11
+ * it by (`retention.ts`).
12
+ *
13
+ * A recording from before seats kept their userId names nobody this can match, and is left to
14
+ * its retention, as the ruling says.
15
+ *
16
+ * ## Off the event loop
17
+ *
18
+ * Every erase used to gunzip and parse every line of every recording, synchronously: 181–197 ms of
19
+ * blocked server for the 23 MB the archive held on 2026-11-10, growing with every match played,
20
+ * and prod's loop showed it on each of ~90 erases in an hour. Now the files are read and unzipped
21
+ * asynchronously (zlib on libuv's pool), and a recording is parsed only when its text holds the
22
+ * person's userId. An end line names them by that exact string, so a file without it cannot name
23
+ * them, and the screen costs a substring search.
24
+ */
25
+ import type { EraseStep } from './index.js';
26
+ export declare function recordingsStep(dir: string): EraseStep;
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Account erase in the match recordings (the operator's ruling, 2026-11-05: anonymise the
3
+ * seat). A recording keeps each seat holder's userId on an `end` line (the public stream's
4
+ * `seats`, or a by-seat `users`, which the 90-day action log may carry), and both files carry the seat's name as it was played: the public header's `players`, the action
5
+ * log's `spec.seats`, and Forge's own views, which name each player.
6
+ *
7
+ * So a recording whose end line, in either file, names the person loses that userId, and the name its seat was
8
+ * played under becomes the room's own word for an unnamed member (`UNNAMED`) everywhere in
9
+ * both files. Not blank: the action log's names are Forge's player names when a replay is
10
+ * rebuilt, and Forge is given a name. Each file keeps its mtime, which is what retention ages
11
+ * it by (`retention.ts`).
12
+ *
13
+ * A recording from before seats kept their userId names nobody this can match, and is left to
14
+ * its retention, as the ruling says.
15
+ *
16
+ * ## Off the event loop
17
+ *
18
+ * Every erase used to gunzip and parse every line of every recording, synchronously: 181–197 ms of
19
+ * blocked server for the 23 MB the archive held on 2026-11-10, growing with every match played,
20
+ * and prod's loop showed it on each of ~90 erases in an hour. Now the files are read and unzipped
21
+ * asynchronously (zlib on libuv's pool), and a recording is parsed only when its text holds the
22
+ * person's userId. An end line names them by that exact string, so a file without it cannot name
23
+ * them, and the screen costs a substring search.
24
+ */
25
+ import { readdir, readFile, rename, stat, utimes, writeFile } from 'node:fs/promises';
26
+ import { join } from 'node:path';
27
+ import { promisify } from 'node:util';
28
+ import { gunzip as gunzipCb, gzip as gzipCb } from 'node:zlib';
29
+ import { UNNAMED } from '../room/constants.js';
30
+ import { ACTIONS_SUFFIX, PUBLIC_SUFFIX } from '../play/recording/retention.js';
31
+ import { replaceIds } from './anonymise.js';
32
+ const gunzip = promisify(gunzipCb);
33
+ const gzip = promisify(gzipCb);
34
+ /** A recording file's text, read and unzipped off the event loop. */
35
+ async function readText(path) {
36
+ return (await gunzip(await readFile(path))).toString('utf8');
37
+ }
38
+ function parseLines(text) {
39
+ return text
40
+ .split('\n')
41
+ .filter((l) => l.length > 0)
42
+ .map((l) => JSON.parse(l));
43
+ }
44
+ /** Rewrite a recording file whole, keeping the mtime its retention reads. */
45
+ async function writeLines(path, lines) {
46
+ const { atime, mtime } = await stat(path);
47
+ const tmp = `${path}.erase.tmp`;
48
+ await writeFile(tmp, await gzip(Buffer.from(lines.map((l) => JSON.stringify(l)).join('\n') + '\n', 'utf8')));
49
+ await utimes(tmp, atime, mtime);
50
+ await rename(tmp, path);
51
+ }
52
+ /** The seats an end line names `userId` in: its recorded seats' `userId`, or its by-seat `users`. Drops each as it finds it. */
53
+ function dropUser(end, userId) {
54
+ if (end === undefined)
55
+ return [];
56
+ const found = [];
57
+ if (Array.isArray(end.seats)) {
58
+ for (const s of end.seats) {
59
+ if (s.userId !== userId)
60
+ continue;
61
+ delete s.userId;
62
+ found.push(s.seat);
63
+ }
64
+ }
65
+ if (Array.isArray(end.users)) {
66
+ const users = end.users;
67
+ users.forEach((u, seat) => {
68
+ if (u !== userId)
69
+ return;
70
+ users[seat] = null;
71
+ found.push(seat);
72
+ });
73
+ }
74
+ return found;
75
+ }
76
+ /** The name each of `seats` was played under, from either file's header. */
77
+ function seatNames(header, seats) {
78
+ const players = Array.isArray(header?.players) ? header.players : [];
79
+ const spec = header?.spec;
80
+ return seats.flatMap((seat) => [players[seat], spec?.seats?.[seat]?.name].filter((n) => typeof n === 'string' && n !== '' && n !== UNNAMED));
81
+ }
82
+ export function recordingsStep(dir) {
83
+ return {
84
+ what: 'recordings',
85
+ erase: async ({ userId }) => {
86
+ let files;
87
+ try {
88
+ files = await readdir(dir);
89
+ }
90
+ catch (err) {
91
+ if (err.code === 'ENOENT')
92
+ return 0;
93
+ throw err;
94
+ }
95
+ const matchIds = new Set(files.flatMap((f) => (f.endsWith(PUBLIC_SUFFIX) ? [f.slice(0, -PUBLIC_SUFFIX.length)] : f.endsWith(ACTIONS_SUFFIX) ? [f.slice(0, -ACTIONS_SUFFIX.length)] : [])));
96
+ let changed = 0;
97
+ for (const matchId of matchIds) {
98
+ const texts = [];
99
+ for (const suffix of [PUBLIC_SUFFIX, ACTIONS_SUFFIX]) {
100
+ if (!files.includes(matchId + suffix))
101
+ continue;
102
+ const path = join(dir, matchId + suffix);
103
+ const text = await readText(path).catch((err) => {
104
+ // Retention may age a file out between the listing and this read: it names no one now.
105
+ if (err.code === 'ENOENT')
106
+ return null;
107
+ throw err;
108
+ });
109
+ if (text !== null)
110
+ texts.push({ path, text });
111
+ }
112
+ if (!texts.some(({ text }) => text.includes(userId)))
113
+ continue;
114
+ const recording = texts.map(({ path, text }) => ({ path, lines: parseLines(text) }));
115
+ const seats = recording.flatMap(({ lines }) => dropUser(lines.findLast((l) => l.t === 'end'), userId));
116
+ if (seats.length === 0)
117
+ continue;
118
+ const names = new Set(recording.flatMap(({ lines }) => seatNames(lines.find((l) => l.t === 'header'), seats)));
119
+ for (const { path, lines } of recording) {
120
+ replaceIds(lines, names, UNNAMED);
121
+ await writeLines(path, lines);
122
+ }
123
+ changed++;
124
+ }
125
+ return changed;
126
+ },
127
+ };
128
+ }