@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
@@ -0,0 +1,278 @@
1
+ /**
2
+ * `/api/rooms`'s GENERIC surface: list, create, join, ready, leave, close, an
3
+ * admin's testing-room reset, the watchparty bind, "the room that started this
4
+ * match", and the `{ gameType }` arm of `PATCH /:id`. `rooms.ts` stays Magic:
5
+ * formats, pods, drafts, tournaments, and the `{ format }`/`{ settings }`/
6
+ * `{ mode }` arms of the same PATCH, mounted on this file's OWN router after it.
7
+ *
8
+ * This file imports no `Lobby`, no `RoomView`, no `@hadoku/shared` (the ratchet
9
+ * resolves `@hadoku/shared` as one package, magic even through `/platform`) —
10
+ * every real Magic type is a type PARAMETER instead (`V`, `C`, `P`, `G` below),
11
+ * and `rooms.ts` passes the real `Lobby`/schemas in structurally. `LobbyCore`'s
12
+ * methods use method syntax on purpose, for TypeScript's bivariant parameter
13
+ * checking — it's what lets the real, narrower-typed `Lobby` satisfy this
14
+ * interface with no cast.
15
+ *
16
+ * ## The PATCH seam
17
+ *
18
+ * ONE registration of `PATCH /:id` (the frozen `route-table.json` admits each
19
+ * method+path once): this file parses the body with `deps.wire.patchRoomBody`
20
+ * and answers `{ gameType }` itself; anything else goes to `opts.onPatch`, a
21
+ * hook `rooms.ts` passes in — never a second route, never `res.locals`.
22
+ */
23
+ import { Router } from 'express';
24
+ import { MultiRateLimiter } from '@wolffm/rooms-server';
25
+ import { isDurableParticipantId } from '@wolffm/rooms-protocol';
26
+ import { isAdmin } from '../edge-auth.js';
27
+ import { bodyErrors, callerOf, parseBody, perCallerLimit } from './request.js';
28
+ import { watchpartyRoomId } from '../room/watchparty-link.js';
29
+ import { jsonLogger } from '../log.js';
30
+ /** The single answer for "no such room" and "wrong password". Byte-identical by construction. */
31
+ export const NO_MATCH = { error: 'no room with that id and password' };
32
+ /** Join attempts per caller: a burst of 10, then one more every 30 s. Only NON-member attempts spend a token. */
33
+ export const JOIN_RATE_LIMIT = {
34
+ capacity: 10,
35
+ refillAmount: 1,
36
+ refillIntervalMs: 30_000,
37
+ };
38
+ /** Rooms made per caller: a burst of 10, then one a minute. `rooms.ts`'s own `/challenge` shares this SAME limiter instance. */
39
+ export const ROOM_CREATE_RATE_LIMIT = {
40
+ capacity: 10,
41
+ refillAmount: 1,
42
+ refillIntervalMs: 60_000,
43
+ };
44
+ export function badRequest(res, error) {
45
+ res.status(400).json({ error });
46
+ }
47
+ export function noMatch(res) {
48
+ res.status(404).json(NO_MATCH);
49
+ }
50
+ export function notDurable(res, verb = 'create or join') {
51
+ res.status(403).json({ error: `the edge did not name you, so you cannot ${verb} a room` });
52
+ }
53
+ /** The PATCH seam's own narrowing: `P` is otherwise opaque (`{ gameType?: unknown }` trips TS's "weak type" check). */
54
+ function hasGameType(v) {
55
+ return 'gameType' in v && typeof v.gameType === 'string';
56
+ }
57
+ /** A testing room, to a non-admin, is as if it did not exist — shared by this file's router and `rooms.ts`'s. */
58
+ export function hideTestingRoomsParam(lobby) {
59
+ return (req, res, next, id) => {
60
+ const room = lobby.get(id);
61
+ if (room !== undefined && room.testing && !isAdmin(req))
62
+ return noMatch(res);
63
+ next();
64
+ };
65
+ }
66
+ export function attachRoomCore(api, deps, opts = {}) {
67
+ const { lobby, wire } = deps;
68
+ const log = deps.log ?? jsonLogger('cardtable-rooms');
69
+ const now = deps.now ?? Date.now;
70
+ const joinLimiter = new MultiRateLimiter(deps.joinRateLimit ?? JOIN_RATE_LIMIT);
71
+ const roomBody = (room, callerId) => {
72
+ const mine = room.members.find((m) => m.id === callerId);
73
+ const games = deps.tableGames?.(room);
74
+ return { ...room, you: { id: callerId, leader: room.leader === callerId, ready: mine?.ready === true }, ...(games === undefined ? {} : { tableGames: games }) };
75
+ };
76
+ const rooms = Router();
77
+ rooms.param('id', hideTestingRoomsParam(lobby));
78
+ rooms.get('/', (req, res) => {
79
+ const me = callerOf(req).id;
80
+ const admin = isAdmin(req);
81
+ // A testing room is never offered to a non-admin.
82
+ const offered = lobby.offered().filter((room) => admin || !room.testing);
83
+ const pick = deps.featured?.(me) ?? null;
84
+ const featured = pick !== null && offered.some((room) => room.id === pick.roomId) ? pick : null;
85
+ res.json({ rooms: offered.map((room) => roomBody(room, me)), featured });
86
+ });
87
+ const createLimit = perCallerLimit(deps.createRateLimit === undefined ? ROOM_CREATE_RATE_LIMIT : deps.createRateLimit, 'too many new rooms; wait a little and try again', {
88
+ act: 'room-create',
89
+ now,
90
+ onRefused: () => log({ event: 'room-create-refused', reason: 'rate-limited' }),
91
+ });
92
+ rooms.post('/', (req, res) => {
93
+ const body = parseBody(wire.createRoomBody, req, res);
94
+ if (body === null || !createLimit(req, res))
95
+ return;
96
+ const caller = callerOf(req);
97
+ const result = lobby.create(caller, body);
98
+ if (!result.ok)
99
+ return notDurable(res);
100
+ deps.arrived?.(result.room.id, caller);
101
+ res.status(201).json(roomBody(result.room, caller.id));
102
+ });
103
+ // The embed's front door: the room bound to the watchparty room whose game slot this is.
104
+ rooms.post('/watchparty', (req, res) => {
105
+ const body = parseBody(wire.watchpartyBindBody, req, res);
106
+ if (body === null)
107
+ return;
108
+ const caller = callerOf(req);
109
+ if (!lobby.isMember(watchpartyRoomId(body.room), caller.id) && !joinLimiter.allow(caller.id, 1, now())) {
110
+ log({ event: 'room-join-refused', reason: 'rate-limited' });
111
+ res.setHeader('Retry-After', String(Math.ceil((deps.joinRateLimit ?? JOIN_RATE_LIMIT).refillIntervalMs / 1000)));
112
+ return res.status(429).json({ error: 'too many join attempts; wait a little and try again' });
113
+ }
114
+ const result = lobby.bindWatchparty(caller, body.room);
115
+ if (!result.ok)
116
+ return notDurable(res);
117
+ deps.arrived?.(result.room.id, caller);
118
+ res.json(roomBody(result.room, caller.id));
119
+ });
120
+ // The room a match was started from, for its own members only.
121
+ rooms.get('/of-match/:matchId', (req, res) => {
122
+ const matchId = String(req.params.matchId);
123
+ const room = wire.roomIdRe.test(matchId) ? lobby.roomOfMatch(matchId) : undefined;
124
+ const me = callerOf(req).id;
125
+ if (room === undefined || !lobby.isMember(room.id, me))
126
+ return noMatch(res);
127
+ res.json(roomBody(room, me));
128
+ });
129
+ // `rooms.ts`'s own exact-path GET routes (`/challenges`) MUST register here,
130
+ // BEFORE `GET /:id` below — a bare `:id` wildcard matches any one segment,
131
+ // "challenges" included, and Express tries routes in registration order.
132
+ opts.beforeWildcard?.(rooms);
133
+ rooms.get('/:id', (req, res) => {
134
+ const id = String(req.params.id);
135
+ const room = wire.roomIdRe.test(id) ? lobby.get(id) : undefined;
136
+ if (room === undefined)
137
+ return noMatch(res);
138
+ const me = callerOf(req).id;
139
+ lobby.touch(id, me);
140
+ res.json(roomBody(room, me));
141
+ });
142
+ rooms.post('/:id/join', (req, res) => {
143
+ const body = parseBody(wire.joinRoomBody, req, res);
144
+ if (body === null)
145
+ return;
146
+ const caller = callerOf(req);
147
+ const id = String(req.params.id);
148
+ // A member re-entering needs no password and spends no token.
149
+ if (wire.roomIdRe.test(id) && lobby.isMember(id, caller.id)) {
150
+ const again = lobby.join(id, caller);
151
+ if (again.ok) {
152
+ deps.arrived?.(id, caller);
153
+ return res.json(roomBody(again.room, caller.id));
154
+ }
155
+ }
156
+ if (!joinLimiter.allow(caller.id, 1, now())) {
157
+ log({ event: 'room-join-refused', reason: 'rate-limited' });
158
+ res.setHeader('Retry-After', String(Math.ceil((deps.joinRateLimit ?? JOIN_RATE_LIMIT).refillIntervalMs / 1000)));
159
+ return res.status(429).json({ error: 'too many join attempts; wait a little and try again' });
160
+ }
161
+ if (!wire.roomIdRe.test(id))
162
+ return noMatch(res);
163
+ const result = lobby.join(id, caller, body.password);
164
+ if (!result.ok) {
165
+ if (result.reason === 'not-durable')
166
+ return notDurable(res);
167
+ log({ event: 'room-join-refused', reason: 'no-match' });
168
+ return noMatch(res);
169
+ }
170
+ deps.arrived?.(id, caller);
171
+ res.json(roomBody(result.room, caller.id));
172
+ });
173
+ rooms.post('/:id/ready', (req, res) => {
174
+ const body = parseBody(wire.readyBody, req, res);
175
+ if (body === null)
176
+ return;
177
+ const caller = callerOf(req);
178
+ if (!isDurableParticipantId(caller.id))
179
+ return notDurable(res, 'take part in');
180
+ const id = String(req.params.id);
181
+ if (!wire.roomIdRe.test(id) || !lobby.setReady(id, caller.id, body.ready))
182
+ return noMatch(res);
183
+ const room = lobby.get(id);
184
+ if (room === undefined)
185
+ return noMatch(res);
186
+ res.json(roomBody(room, caller.id));
187
+ });
188
+ // A member steps out of their own room. A tournament entrant mid-round is a drop (`forfeited`).
189
+ rooms.post('/:id/leave', (req, res) => {
190
+ if (parseBody(wire.emptyBody, req, res) === null)
191
+ return;
192
+ const caller = callerOf(req);
193
+ if (!isDurableParticipantId(caller.id))
194
+ return notDurable(res, 'leave');
195
+ const id = String(req.params.id);
196
+ if (!wire.roomIdRe.test(id))
197
+ return noMatch(res);
198
+ const result = lobby.leave(id, caller.id);
199
+ if (!result.ok)
200
+ return noMatch(res);
201
+ if (result.forfeited !== undefined)
202
+ deps.forfeited?.(id, result.forfeited.tableId, caller.id, result.forfeited.matchIds);
203
+ res.json(roomBody(result.room, caller.id));
204
+ });
205
+ // The owner ends the room for everyone.
206
+ rooms.post('/:id/close', (req, res) => {
207
+ if (parseBody(wire.emptyBody, req, res) === null)
208
+ return;
209
+ const caller = callerOf(req);
210
+ if (!isDurableParticipantId(caller.id))
211
+ return notDurable(res, 'close');
212
+ const id = String(req.params.id);
213
+ if (!wire.roomIdRe.test(id) || !lobby.isMember(id, caller.id))
214
+ return noMatch(res);
215
+ const wasTesting = lobby.get(id)?.testing === true;
216
+ const result = lobby.close(id, caller.id);
217
+ if (!result.ok) {
218
+ if (result.reason === 'no-room')
219
+ return noMatch(res);
220
+ return res.status(403).json({ error: 'only the room owner can close it' });
221
+ }
222
+ deps.closed?.(id, result.matches);
223
+ if (wasTesting)
224
+ deps.reseedTesting?.();
225
+ res.json({ ok: true });
226
+ });
227
+ // An admin resets a testing room from the list without joining it.
228
+ rooms.post('/:id/reset', (req, res) => {
229
+ if (parseBody(wire.emptyBody, req, res) === null)
230
+ return;
231
+ const caller = callerOf(req);
232
+ const id = String(req.params.id);
233
+ if (!wire.roomIdRe.test(id) || !isAdmin(req) || lobby.get(id)?.testing !== true)
234
+ return noMatch(res);
235
+ const result = lobby.close(id, caller.id);
236
+ if (!result.ok)
237
+ return noMatch(res);
238
+ deps.closed?.(id, result.matches);
239
+ deps.reseedTesting?.();
240
+ res.json({ ok: true });
241
+ });
242
+ /**
243
+ * `{ gameType }` is this file's own: the game-type registry is platform.
244
+ * Everything else `P` can be (Magic's `{ format }`/`{ settings }`/`{ mode }`)
245
+ * goes to `opts.onPatch`. ONE registration either way — `route-table.json`
246
+ * admits `PATCH /:id` once.
247
+ */
248
+ rooms.patch('/:id', (req, res, next) => {
249
+ const v = parseBody(wire.patchRoomBody, req, res);
250
+ if (v === null)
251
+ return;
252
+ const id = String(req.params.id);
253
+ if (!wire.roomIdRe.test(id))
254
+ return noMatch(res);
255
+ if (!hasGameType(v)) {
256
+ if (opts.onPatch === undefined)
257
+ return next();
258
+ opts.onPatch(req, res, v, callerOf(req), id);
259
+ return;
260
+ }
261
+ const me = callerOf(req).id;
262
+ const result = lobby.setGameType(id, me, v.gameType);
263
+ if (!result.ok) {
264
+ if (result.reason === 'no-room')
265
+ return noMatch(res);
266
+ if (result.reason === 'draft-started')
267
+ return res.status(409).json({ error: 'this room is drafting; the game type cannot change now' });
268
+ if (result.reason === 'mode-locked') {
269
+ return res.status(409).json({ error: 'a game is under way or a seated player is ready; the game type cannot change now', reason: result.reason });
270
+ }
271
+ return res.status(403).json({ error: 'only the room leader can change the game type' });
272
+ }
273
+ res.json(roomBody(result.room, me));
274
+ });
275
+ api.use('/rooms', rooms);
276
+ return { router: rooms, roomBody, createLimit };
277
+ }
278
+ export { bodyErrors };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * `/api/trim` — the site's trim, one look for every player (the operator, 2026-10-21: "make it set
3
+ * the look for every player").
4
+ *
5
+ * GET /api/trim → 200 { trim: Record<family, option> | null, canEdit } (friend tier)
6
+ * PUT /api/trim { trim } → 200 { trim } | 400 | 403 (admin)
7
+ *
8
+ * `trim: null` is "never set": the client draws its own default. The catalogue of families and
9
+ * options is the UI's (`apps/ui/src/settings/trim.ts`), which draws only what it knows; this
10
+ * stores a small map of names and checks its shape, nothing more. One file, written atomically.
11
+ */
12
+ import { Router } from 'express';
13
+ import { type JsonLog } from '@wolffm/service-kernel/log';
14
+ export interface TrimDeps {
15
+ /** The file the site's trim is kept in. Created on the first PUT, never on a read. */
16
+ file: string;
17
+ log?: JsonLog;
18
+ }
19
+ type Trim = Record<string, string>;
20
+ /** A trim map, or `null` for anything that is not one. */
21
+ export declare function parseTrim(value: unknown): Trim | null;
22
+ export declare function attachTrim(api: Router, deps: TrimDeps): void;
23
+ export {};
@@ -0,0 +1,76 @@
1
+ /**
2
+ * `/api/trim` — the site's trim, one look for every player (the operator, 2026-10-21: "make it set
3
+ * the look for every player").
4
+ *
5
+ * GET /api/trim → 200 { trim: Record<family, option> | null, canEdit } (friend tier)
6
+ * PUT /api/trim { trim } → 200 { trim } | 400 | 403 (admin)
7
+ *
8
+ * `trim: null` is "never set": the client draws its own default. The catalogue of families and
9
+ * options is the UI's (`apps/ui/src/settings/trim.ts`), which draws only what it knows; this
10
+ * stores a small map of names and checks its shape, nothing more. One file, written atomically.
11
+ */
12
+ import { readFile } from 'node:fs/promises';
13
+ import { Router } from 'express';
14
+ import { rankOf, tierOf } from '../edge-auth.js';
15
+ import { jsonLogger } from '@wolffm/service-kernel/log';
16
+ import { atomicWriteJson } from '@wolffm/service-kernel/state';
17
+ import { bodyErrors } from './request.js';
18
+ const FAMILY = /^[a-z][a-zA-Z]{0,31}$/;
19
+ const OPTION = /^[a-z][a-z-]{0,31}$/;
20
+ const MAX_FAMILIES = 16;
21
+ /** A trim map, or `null` for anything that is not one. */
22
+ export function parseTrim(value) {
23
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
24
+ return null;
25
+ const entries = Object.entries(value);
26
+ if (entries.length > MAX_FAMILIES)
27
+ return null;
28
+ for (const [family, option] of entries) {
29
+ if (!FAMILY.test(family) || typeof option !== 'string' || !OPTION.test(option))
30
+ return null;
31
+ }
32
+ return Object.fromEntries(entries);
33
+ }
34
+ async function readTrim(file, log) {
35
+ let raw;
36
+ try {
37
+ raw = await readFile(file, 'utf8');
38
+ }
39
+ catch (err) {
40
+ if (err.code === 'ENOENT')
41
+ return null;
42
+ throw err;
43
+ }
44
+ let json;
45
+ try {
46
+ json = JSON.parse(raw);
47
+ }
48
+ catch {
49
+ log({ event: 'trim-file-corrupt', reason: 'invalid JSON' });
50
+ return null;
51
+ }
52
+ const trim = parseTrim(json?.trim);
53
+ if (trim === null)
54
+ log({ event: 'trim-file-corrupt', reason: 'not a trim' });
55
+ return trim;
56
+ }
57
+ export function attachTrim(api, deps) {
58
+ const { file } = deps;
59
+ const log = deps.log ?? jsonLogger('cardtable-trim');
60
+ const trim = Router();
61
+ trim.get('/', async (req, res) => {
62
+ res.json({ trim: await readTrim(file, log), canEdit: rankOf(tierOf(req)) >= rankOf('admin') });
63
+ });
64
+ trim.put('/', async (req, res) => {
65
+ if (rankOf(tierOf(req)) < rankOf('admin'))
66
+ return res.status(403).json({ error: 'admin tier required' });
67
+ const next = parseTrim(req.body?.trim);
68
+ if (next === null)
69
+ return res.status(400).json({ error: 'trim must be a map of family names to option names' });
70
+ await atomicWriteJson(file, { trim: next });
71
+ log({ event: 'trim-saved', trim: JSON.stringify(next) });
72
+ return res.json({ trim: next });
73
+ });
74
+ api.use('/trim', trim);
75
+ api.use('/trim', bodyErrors((name) => log({ event: 'trim-error', name })));
76
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Adapter: cardtable's binding of `@hadoku/service-kernel/relays`'s `attachUsage` (w93-K3).
3
+ * `POST /api/usage`: the browser's usage batches (`packages/game-ui/src/usage.ts`), counted here and posted
4
+ * to telemetry as one `usage` event per window — which screens were shown and which controls
5
+ * pressed, how often, by how many people, by tier. Nothing per click is kept, and nothing is
6
+ * answered but 204.
7
+ *
8
+ * Every export and signature below is unchanged from before this moved into the kernel:
9
+ * `index.ts` imports this path exactly as it did. The cardtable-specific bits are
10
+ * `@hadoku/platform-wire/telemetry`'s schema and path, bound here — the kernel itself never imports it.
11
+ */
12
+ import type { Router } from 'express';
13
+ import { MAX_BATCHES_PER_MINUTE, USAGE_TOP, USAGE_WINDOW_MS, type UsageCounter } from '@wolffm/service-kernel/relays';
14
+ import { type Report } from '../telemetry.js';
15
+ export { MAX_BATCHES_PER_MINUTE, USAGE_TOP, USAGE_WINDOW_MS };
16
+ export type { UsageCounter };
17
+ export interface UsageDeps {
18
+ report?: Report;
19
+ now?: () => number;
20
+ windowMs?: number;
21
+ }
22
+ export declare function attachUsage(api: Router, deps?: UsageDeps): UsageCounter;
@@ -0,0 +1,16 @@
1
+ import { USAGE_PATH, UsageBatchSchema } from '@wolffm/platform-wire/telemetry';
2
+ import { attachUsage as kernelAttachUsage, MAX_BATCHES_PER_MINUTE, USAGE_TOP, USAGE_WINDOW_MS, } from '@wolffm/service-kernel/relays';
3
+ import { tierOf, userIdOf } from '../edge-auth.js';
4
+ import { report as defaultReport } from '../telemetry.js';
5
+ export { MAX_BATCHES_PER_MINUTE, USAGE_TOP, USAGE_WINDOW_MS };
6
+ export function attachUsage(api, deps = {}) {
7
+ return kernelAttachUsage(api, {
8
+ schema: UsageBatchSchema,
9
+ path: USAGE_PATH,
10
+ tierOf,
11
+ userIdOf,
12
+ report: deps.report ?? defaultReport,
13
+ now: deps.now,
14
+ windowMs: deps.windowMs,
15
+ });
16
+ }
@@ -0,0 +1,4 @@
1
+ /** `assertFloor`'s env prefix (`edge-auth.ts`) — hadoku_site's wrapper sets `CARDTABLE_MIN_TIER`. */
2
+ export declare const ENV_PREFIX = "CARDTABLE";
3
+ export declare const edgeAuth: import("@wolffm/service-kernel/auth").EdgeAuth;
4
+ export declare const gate: import("@wolffm/service-kernel/http").Gate;
package/dist/kernel.js ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * cardtable's binding of `@hadoku/service-kernel`'s auth and gate: the env prefix and the one
3
+ * `createEdgeAuth`/`createGate` pair that `edge-auth.ts` and `gate.ts` share, built from `CONFIG`.
4
+ */
5
+ import { createEdgeAuth, rankOf, tierOf } from '@wolffm/service-kernel/auth';
6
+ import { createGate } from '@wolffm/service-kernel/http';
7
+ import { CONFIG } from './config.js';
8
+ import { reportSealRefused } from './telemetry.js';
9
+ /** `assertFloor`'s env prefix (`edge-auth.ts`) — hadoku_site's wrapper sets `CARDTABLE_MIN_TIER`. */
10
+ export const ENV_PREFIX = 'CARDTABLE';
11
+ export const edgeAuth = createEdgeAuth({
12
+ edgeAuthSecret: () => CONFIG.edgeAuthSecret,
13
+ allowUnverifiedEdge: () => CONFIG.allowUnverifiedEdge,
14
+ devTier: () => CONFIG.devTier,
15
+ });
16
+ export const gate = createGate({
17
+ sanitizeHeaders: edgeAuth.sanitizeHeaders,
18
+ edgeProvenance: edgeAuth.edgeProvenance,
19
+ tierOf,
20
+ rankOf,
21
+ // `reportSealRefused`'s own surface type is cardtable's closed set (`telemetry.ts`); the
22
+ // kernel's is an open `string` so it knows no game's surface names. Every surface this gate
23
+ // ever reports is in that set.
24
+ reportSealRefused: reportSealRefused,
25
+ minTier: () => CONFIG.minTier,
26
+ });
package/dist/log.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Adapter: cardtable's binding of `@hadoku/service-kernel/log`. `jsonLogger`
3
+ * and `JsonLog` are fully generic (no cardtable value baked in), so this is a
4
+ * pure re-export kept at this path for its one remaining importer,
5
+ * `http/rooms.ts` — claimed by another session (w95b) this wave, so its
6
+ * import line was not repointed. Every other importer now binds
7
+ * `@hadoku/service-kernel/log` directly (w93-Z).
8
+ */
9
+ export { jsonLogger, type JsonLog } from '@wolffm/service-kernel/log';
package/dist/log.js ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Adapter: cardtable's binding of `@hadoku/service-kernel/log`. `jsonLogger`
3
+ * and `JsonLog` are fully generic (no cardtable value baked in), so this is a
4
+ * pure re-export kept at this path for its one remaining importer,
5
+ * `http/rooms.ts` — claimed by another session (w95b) this wave, so its
6
+ * import line was not repointed. Every other importer now binds
7
+ * `@hadoku/service-kernel/log` directly (w93-Z).
8
+ */
9
+ export { jsonLogger } from '@wolffm/service-kernel/log';
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Who a person is and what they look like, from hadoku_site's prefs-api: their
3
+ * live display name, their avatar picture and the cosmetics they wear. One
4
+ * batched call (`resolveAvatars`) answers all three by userId.
5
+ *
6
+ * The operator, 2026-11-05: *"picture/character are the same thing and all
7
+ * over the entire site it's the same avatar. we must display all
8
+ * customizations everywhere."* A person picks all of it in the fleet's avatar
9
+ * settings, never here; this module only reads it.
10
+ *
11
+ * Resolved with this server's own service key. A failure answers nobody and
12
+ * is logged, never thrown: a missing look costs a face its dressing, not a
13
+ * join. Cached a minute, so a room's joins share one lookup; a person who has
14
+ * just changed theirs is read `fresh` (the served room's `account`, `room/serve.ts`).
15
+ * The picture URL is relayed, never fetched: the browser loads it from
16
+ * Discord, Steam or cdn.hadoku.me, all inside hadoku.me's img-src.
17
+ */
18
+ import { type ResolvedPerson } from '@wolffm/prefs-client/avatar';
19
+ import { type Look, type PersonFace } from '@wolffm/platform-wire/look';
20
+ /** One person, as a screen shows them. */
21
+ export interface Person {
22
+ /** Their display name now; null for an unknown or closed account. */
23
+ name: string | null;
24
+ /**
25
+ * Their watchparty character. prefs-api answers one for every account, drawing and keeping one for an
26
+ * account that never picked, so null only when an answer carried none.
27
+ */
28
+ sprite: string | null;
29
+ look: Look | undefined;
30
+ }
31
+ export interface People {
32
+ /** Every id in the answer; one the lookup could not reach is absent, not a default. */
33
+ resolve(userIds: readonly string[], opts?: {
34
+ fresh?: boolean;
35
+ }): Promise<Map<string, Person>>;
36
+ /** The cached answer for one id, or undefined when there is none fresh. */
37
+ peek(userId: string): Person | undefined;
38
+ }
39
+ /** What account erase asks of the lookup, beside what everyone else does. */
40
+ export interface ForgetfulPeople extends People {
41
+ /** Drop the cached answer for one id; 1 when one was held, else 0. */
42
+ forget(userId: string): number;
43
+ }
44
+ export interface PeopleOptions {
45
+ baseUrl: string;
46
+ serviceKey: string;
47
+ /** Look people up with no key: only the e2e stand-in answers that. Default: only with a key. */
48
+ keyless?: boolean;
49
+ log: (entry: Record<string, unknown>) => void;
50
+ now?: () => number;
51
+ fetch?: typeof fetch;
52
+ }
53
+ /** What one resolved entry means here. Exported for its test. */
54
+ export declare function personOf(r: ResolvedPerson | undefined): Person;
55
+ /** No key, no lookups: every answer is empty and nothing is called. */
56
+ export declare function createPeople(opts: PeopleOptions): ForgetfulPeople;
57
+ /** What a person is written into: the room registry (`room/lobby.ts`'s `Lobby`). */
58
+ interface PersonRooms {
59
+ get(roomId: string): {
60
+ members: readonly {
61
+ id: string;
62
+ }[];
63
+ } | undefined;
64
+ rename(caller: {
65
+ id: string;
66
+ name: string;
67
+ }): void;
68
+ setAvatar(roomId: string, memberId: string, avatarId: string | null): boolean;
69
+ setLook(roomId: string, memberId: string, look: Look | undefined): boolean;
70
+ }
71
+ /**
72
+ * Write `person` onto member `memberId` of `roomId`: their name in every room they are in, their
73
+ * character and their look in this one. The account is the one source of all three (the operator,
74
+ * 2026-11-05: *"all over the entire site it's the same avatar"*); a field the lookup has no answer
75
+ * for leaves what the room already holds.
76
+ */
77
+ export declare function applyPerson(rooms: PersonRooms, roomId: string, memberId: string, person: Person): void;
78
+ /** What `attachPeople` needs of the room registry. */
79
+ export interface PeopleRooms extends PersonRooms {
80
+ onChange(listener: (roomId: string) => void): () => void;
81
+ /** The rooms people have open now (`Lobby.offered`). */
82
+ offered(): readonly {
83
+ id: string;
84
+ }[];
85
+ usersOf(roomId: string): {
86
+ memberId: string;
87
+ userId: string;
88
+ }[];
89
+ }
90
+ /**
91
+ * Every member of a room that changes is written from their account (`applyPerson`, from the
92
+ * cache mostly), so a joiner and a member a restart left unnamed (R12) are named and dressed
93
+ * whether or not they have the room open. A change made while the room IS open reaches it live
94
+ * through the served room (`room/serve.ts`); `sweep` is the boot's one read of the restored rooms,
95
+ * and `arrived` reads one person fresh as they come into a room, so a change made since the
96
+ * cache's last answer is what the room gets (as the served room re-reads an account on its join).
97
+ */
98
+ export declare function attachPeople(rooms: PeopleRooms, people: People): {
99
+ sweep(): Promise<void>;
100
+ arrived(roomId: string, memberId: string, userId: string): Promise<void>;
101
+ stop(): void;
102
+ };
103
+ /** How a person is drawn in a record of the past: their character and their look, as they are now. */
104
+ export declare function faceOfPerson(person: Person | undefined): PersonFace;
105
+ export {};