@hadoku/game-server 0.1.211 → 0.1.213

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.
@@ -12,8 +12,8 @@
12
12
  * them only when the shared secret checks out; otherwise we overwrite them with
13
13
  * the most restrictive identity.
14
14
  */
15
- import { TIER_ORDER, type Tier, rankOf, tierOf, edgeTierOf, callerIdOf, userIdOf, userKeyOf, accountIdOf, userNameOf, isAdmin, isOperator } from '@wolffm/service-kernel/auth';
16
- export { TIER_ORDER, rankOf, tierOf, edgeTierOf, callerIdOf, userIdOf, userKeyOf, accountIdOf, userNameOf, isAdmin, isOperator };
15
+ import { TIER_ORDER, type Tier, rankOf, tierOf, edgeTierOf, userIdOf, userKeyOf, accountIdOf, userNameOf, isAdmin, isOperator } from '@wolffm/service-kernel/auth';
16
+ export { TIER_ORDER, rankOf, tierOf, edgeTierOf, userIdOf, userKeyOf, accountIdOf, userNameOf, isAdmin, isOperator };
17
17
  export type { Tier };
18
18
  /**
19
19
  * The floor must be a tier this build knows, and never `public` here —
package/dist/edge-auth.js CHANGED
@@ -12,9 +12,9 @@
12
12
  * them only when the shared secret checks out; otherwise we overwrite them with
13
13
  * the most restrictive identity.
14
14
  */
15
- import { TIER_ORDER, assertFloor as kernelAssertFloor, rankOf, tierOf, edgeTierOf, callerIdOf, userIdOf, userKeyOf, accountIdOf, userNameOf, isAdmin, isOperator, } from '@wolffm/service-kernel/auth';
15
+ import { TIER_ORDER, assertFloor as kernelAssertFloor, rankOf, tierOf, edgeTierOf, userIdOf, userKeyOf, accountIdOf, userNameOf, isAdmin, isOperator, } from '@wolffm/service-kernel/auth';
16
16
  import { ENV_PREFIX, edgeAuth, gate } from './kernel.js';
17
- export { TIER_ORDER, rankOf, tierOf, edgeTierOf, callerIdOf, userIdOf, userKeyOf, accountIdOf, userNameOf, isAdmin, isOperator };
17
+ export { TIER_ORDER, rankOf, tierOf, edgeTierOf, userIdOf, userKeyOf, accountIdOf, userNameOf, isAdmin, isOperator };
18
18
  /**
19
19
  * The floor must be a tier this build knows, and never `public` here —
20
20
  * cardtable admits members and friends, never the public tier. An unknown
@@ -26,45 +26,13 @@
26
26
  * account's place in it exactly as above.
27
27
  */
28
28
  import type { ParticipantId } from '@wolffm/rooms-protocol';
29
+ import type { PlatformRoomView, RoomCreateInput, RoomLobby } from '../room/lobby.js';
29
30
  import type { EraseStep } from './index.js';
30
- import type { IdMove } from './anonymise.js';
31
31
  export interface LiveMatch {
32
32
  seatOf(participantId: ParticipantId): number | null;
33
33
  }
34
- /** What this file reads off a room — `FileLobby.list()`'s own `RoomView[]` satisfies this structurally. */
35
- interface RoomSummary {
36
- id: string;
37
- members: readonly {
38
- id: string;
39
- }[];
40
- }
41
- /** `room/lobby.ts`'s own `LeaveResult`/`CloseRoomResult`, narrowed to what this file reads; `FileLobby` satisfies both structurally. */
42
- type RoomsLeaveResult = {
43
- ok: true;
44
- forfeited?: {
45
- tableId: string;
46
- matchIds: string[];
47
- };
48
- } | {
49
- ok: false;
50
- };
51
- type RoomsCloseResult = {
52
- ok: true;
53
- matches: string[];
54
- } | {
55
- ok: false;
56
- };
57
- /** A narrow slice of `room/lobby.ts`'s `Lobby` — declared here, not imported, so this platform file carries no edge into the tangled lobby. */
58
- interface RoomsLobby {
59
- list(): readonly RoomSummary[];
60
- leave(roomId: string, memberId: string): RoomsLeaveResult;
61
- close(roomId: string, callerId: string): RoomsCloseResult;
62
- anonymise(ids: ReadonlySet<string>, to: string): number;
63
- /** Account merge: every room naming the merged-away account, and not the kept one, names the kept one. */
64
- merge(move: IdMove): number;
65
- /** Every room written or deleted so far is on disk: a step answers only once what it changed is. */
66
- flushed(): Promise<void>;
67
- }
34
+ /** What the steps call on the lobby; `flushed` lets a step answer only once what it changed is on disk. */
35
+ type RoomsLobby = Pick<RoomLobby<PlatformRoomView, RoomCreateInput>, 'list' | 'leave' | 'close' | 'anonymise' | 'merge' | 'flushed'>;
68
36
  export interface RoomsEraseDeps<M extends LiveMatch> {
69
37
  lobby: RoomsLobby;
70
38
  /** Every match still being played. */
@@ -4,19 +4,13 @@
4
4
  * (routes, pools, play/socket.ts) need no edit.
5
5
  *
6
6
  * `httpCaller` binds the kernel's injected caller-id deriver to this app's own identity scheme
7
- * (`room/identity.ts`). `callerOf` builds the full `Caller` the room layer wants: it is NOT moved
8
- * into the kernel (`room/lobby.ts`'s `Caller` and `UNNAMED` stay app-side, by the wave's own
9
- * ruling), and `UNNAMED` is copied here rather than imported from `room/lobby.ts` — this file is
10
- * `platform` and `room/lobby.ts` is `tangled` (`scripts/layers/layers.json`), so importing it back
11
- * would restore the very `platform→tangled` edge this wave cuts
12
- * (`scripts/layers/ratchet.test.ts`, the `http/request.ts→../room/lobby.js` edge). The object
13
- * `callerOf` builds matches `room/lobby.ts`'s `Caller` shape structurally, which is all a caller
14
- * of `callerOf` needs — nothing here imports that type either.
7
+ * (`room/identity.ts`). `callerOf` builds the full `Caller` the room layer wants (`room/caller.ts`).
15
8
  */
16
9
  import type { ParticipantId } from '@wolffm/rooms-protocol';
17
10
  import type { RateLimitConfig } from '@wolffm/rooms-server';
18
11
  import type { Request, Response } from 'express';
19
12
  import { bodyErrors, parseBody, readBody, type BodySchema } from '@wolffm/service-kernel/limits';
13
+ import type { Caller } from '../room/caller.js';
20
14
  export { bodyErrors, parseBody, readBody };
21
15
  export type { BodySchema };
22
16
  /**
@@ -30,11 +24,7 @@ export declare const httpCaller: (req: Request) => ParticipantId;
30
24
  * userId — a roster is for humans; a key the edge sent no name for gets `UNNAMED`), and the userId
31
25
  * a saved room keeps instead of the name (R12).
32
26
  */
33
- export declare function callerOf(req: Request): {
34
- id: string;
35
- name: string;
36
- userId: string | null;
37
- };
27
+ export declare function callerOf(req: Request): Caller;
38
28
  /**
39
29
  * A per-caller token bucket for a costly step: each pass reports `costly-act` and each refusal
40
30
  * `rate-limited`, both named by `act`, so telemetry shows who is spending the expensive steps and
@@ -1,5 +1,6 @@
1
1
  import { bodyErrors, makeCallerId, parseBody, readBody, costlyActLimit as kernelCostlyActLimit, perCallerLimit as kernelPerCallerLimit, } from '@wolffm/service-kernel/limits';
2
2
  import { accountIdOf, userNameOf } from '../edge-auth.js';
3
+ import { UNNAMED } from '../room/constants.js';
3
4
  import { identityFromHeaders } from '../room/identity.js';
4
5
  export { bodyErrors, parseBody, readBody };
5
6
  /**
@@ -8,8 +9,6 @@ export { bodyErrors, parseBody, readBody };
8
9
  * for someone the edge could not name.
9
10
  */
10
11
  export const httpCaller = makeCallerId(identityFromHeaders);
11
- /** `room/lobby.ts`'s own word for an unnamed member. Kept in sync by hand — see this file's header. */
12
- const UNNAMED = 'friend';
13
12
  /**
14
13
  * Who is asking, for a lobby call: the id, the DISPLAY NAME (`X-User-Name`, never the opaque
15
14
  * userId — a roster is for humans; a key the edge sent no name for gets `UNNAMED`), and the userId
@@ -22,9 +22,8 @@
22
22
  */
23
23
  import { Router, type Request, type Response } from 'express';
24
24
  import { type RateLimitConfig } from '@wolffm/rooms-server';
25
- import { bodyErrors, callerOf, type BodySchema } from './request.js';
26
- /** Who is asking — exactly what `callerOf` returns, never a redeclared shape. */
27
- type CallerLike = ReturnType<typeof callerOf>;
25
+ import type { Caller } from '../room/caller.js';
26
+ import { bodyErrors, type BodySchema } from './request.js';
28
27
  /** The minimal room shape every route here touches; the real `RoomView` satisfies it and rides through untouched as `V`. */
29
28
  export interface RoomViewCore {
30
29
  id: string;
@@ -42,7 +41,7 @@ export interface LobbyCore<V extends RoomViewCore, C> {
42
41
  get(roomId: string): V | undefined;
43
42
  offered(): V[];
44
43
  isMember(roomId: string, callerId: string): boolean;
45
- create(caller: CallerLike, body: C): {
44
+ create(caller: Caller, body: C): {
46
45
  ok: true;
47
46
  room: V;
48
47
  } | {
@@ -50,7 +49,7 @@ export interface LobbyCore<V extends RoomViewCore, C> {
50
49
  };
51
50
  /** The tier floor a room made from `body` would have (`room/lobby.ts`'s `minTierOf`). */
52
51
  minTierOf(body: C): string | undefined;
53
- join(roomId: string, caller: CallerLike, password?: string): {
52
+ join(roomId: string, caller: Caller, password?: string): {
54
53
  ok: true;
55
54
  room: V;
56
55
  } | {
@@ -78,7 +77,7 @@ export interface LobbyCore<V extends RoomViewCore, C> {
78
77
  ok: false;
79
78
  reason: string;
80
79
  };
81
- bindWatchparty(caller: CallerLike, watchpartyRoom: string): {
80
+ bindWatchparty(caller: Caller, watchpartyRoom: string): {
82
81
  ok: true;
83
82
  room: V;
84
83
  } | {
@@ -247,7 +246,7 @@ export interface RoomCoreDeps<V extends RoomViewCore, C, P extends object, G = n
247
246
  here?: (roomId: string) => ReadonlySet<string>;
248
247
  /** "Reset = Close": runs AFTER `closed`, same as `index.ts`'s own `seedTestingRooms` boot call. */
249
248
  reseedTesting?: () => void;
250
- arrived?: (roomId: string, caller: CallerLike) => void;
249
+ arrived?: (roomId: string, caller: Caller) => void;
251
250
  /** Each table's game, by table id (`play/table-game.ts`). A hook: this file never inspects `G`'s shape. */
252
251
  tableGames?(room: V): Record<string, G>;
253
252
  /** The room as a browser is sent it, when the game draws less than its lobby holds (Magic's `podForPeople`). Absent: the room as it is. */
@@ -299,6 +298,6 @@ export interface RoomCoreHandle<V extends RoomViewCore, G = never> {
299
298
  export declare function attachRoomCore<V extends RoomViewCore, C, P extends object, G = never>(api: Router, deps: RoomCoreDeps<V, C, P, G>, opts?: {
300
299
  beforeWildcard?(router: Router): void;
301
300
  /** Every other PATCH variant (Magic's `{ format }`/`{ mode }`) — method syntax for bivariance, like `LobbyCore`. */
302
- onPatch?(req: Request, res: Response, body: P, caller: CallerLike, roomId: string): void;
301
+ onPatch?(req: Request, res: Response, body: P, caller: Caller, roomId: string): void;
303
302
  }): RoomCoreHandle<V, G>;
304
303
  export { bodyErrors };
package/dist/http/trim.js CHANGED
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import { readFile } from 'node:fs/promises';
13
13
  import { Router } from 'express';
14
- import { rankOf, tierOf } from '../edge-auth.js';
14
+ import { isAdmin } from '../edge-auth.js';
15
15
  import { jsonLogger } from '@wolffm/service-kernel/log';
16
16
  import { atomicWriteJson } from '@wolffm/service-kernel/state';
17
17
  import { bodyErrors } from './request.js';
@@ -59,10 +59,10 @@ export function attachTrim(api, deps) {
59
59
  const log = deps.log ?? jsonLogger('cardtable-trim');
60
60
  const trim = Router();
61
61
  trim.get('/', async (req, res) => {
62
- res.json({ trim: await readTrim(file, log), canEdit: rankOf(tierOf(req)) >= rankOf('admin') });
62
+ res.json({ trim: await readTrim(file, log), canEdit: isAdmin(req) });
63
63
  });
64
64
  trim.put('/', async (req, res) => {
65
- if (rankOf(tierOf(req)) < rankOf('admin'))
65
+ if (!isAdmin(req))
66
66
  return res.status(403).json({ error: 'admin tier required' });
67
67
  const next = parseTrim(req.body?.trim);
68
68
  if (next === null)
@@ -41,6 +41,7 @@
41
41
  * shown in a seat row; there is exactly one id per participant rather than an
42
42
  * internal id plus a wire handle to keep in sync.
43
43
  */
44
+ import { headerValue } from '@wolffm/service-kernel/auth';
44
45
  import { createParticipantIdDeriver } from '@wolffm/rooms-server';
45
46
  /**
46
47
  * Domain separation for the digest.
@@ -118,12 +119,6 @@ export function deriveParticipantId(input) {
118
119
  participantIdDerived = true;
119
120
  return derive(input).id;
120
121
  }
121
- function headerValue(headers, name) {
122
- const raw = headers[name];
123
- if (typeof raw === 'string' && raw !== '')
124
- return raw;
125
- return null;
126
- }
127
122
  /**
128
123
  * The identity of a handshake, from its SANITIZED headers.
129
124
  *
@@ -61,6 +61,7 @@
61
61
  import { participantHandle } from '@wolffm/rooms-protocol';
62
62
  import { createChatHistoryStore } from '@wolffm/rooms-server/chat';
63
63
  import { serveRoom } from '@wolffm/rooms-server/room';
64
+ import { headerValue } from '@wolffm/service-kernel/auth';
64
65
  import { rankOf } from '../edge-auth.js';
65
66
  import { timerDelay } from '../timers.js';
66
67
  import { applyPerson } from '../people.js';
@@ -116,10 +117,6 @@ function mayJoin(lobby, place, participantId, tier) {
116
117
  return true;
117
118
  return roomAdmits(lobby.get(place.roomId), lobby.isMember(place.roomId, participantId), tier);
118
119
  }
119
- function accountOfHeaders(headers) {
120
- const id = headers['x-user-id'];
121
- return typeof id === 'string' && id !== '' ? id : undefined;
122
- }
123
120
  /**
124
121
  * The `/room` handshake floor — refused HERE, a forged or headerless socket never reaches
125
122
  * `connection` at all. `serveRoom`'s own `admit` is called only once a client has CONNECTED and
@@ -187,7 +184,7 @@ export async function attachServedRoom(io, deps) {
187
184
  const roomId = place.roomId;
188
185
  if (roomId !== null)
189
186
  lobbyRoomOf.set(socket, roomId);
190
- const accountId = accountOfHeaders(headers);
187
+ const accountId = headerValue(headers, 'x-user-id') ?? undefined;
191
188
  return {
192
189
  roomId: place.served,
193
190
  key: participantId,
@@ -24,12 +24,8 @@
24
24
  */
25
25
  import type { Server as SocketIOServer } from 'socket.io';
26
26
  import { type RoomFeedHandle } from '@wolffm/rooms-server';
27
- /** A narrow slice of `room/lobby.ts`'s `Lobby` — declared here, not imported, so this platform file carries no edge into the tangled lobby. `FileLobby` satisfies it structurally. */
28
- interface RoomFeedLobby {
29
- touch(roomId: string, memberId: string): void;
30
- isMember(roomId: string, memberId: string): boolean;
31
- onChange(listener: (roomId: string) => void): () => void;
32
- }
27
+ import type { PlatformRoomView, RoomCreateInput, RoomLobby } from './lobby.js';
28
+ type RoomFeedLobby = Pick<RoomLobby<PlatformRoomView, RoomCreateInput>, 'touch' | 'isMember' | 'onChange'>;
33
29
  interface RoomFeedDeps {
34
30
  lobby: RoomFeedLobby;
35
31
  log?: (line: Record<string, unknown>) => void;
@@ -1,16 +1,3 @@
1
- /**
2
- * The first host port a room's seat may take, when `createRoomStreams`'s caller does not pass its
3
- * own `basePort`.
4
- *
5
- * Deliberately clear of everything else on this host: 6080–6081 are the static
6
- * bench, and the e2e harness picks its ports from 20000 up (`e2e/ports.ts`). `container.sh` refuses
7
- * anything below 6100 a second time, in case this constant is ever loosened.
8
- *
9
- * A literal, not `CONFIG.roomStreamBasePort` (w119 §C): the room-stream ports are Forge/Magic-only
10
- * (survey §3), so Magic's `MAGIC_CONFIG.roomStreamBasePort` is what `plugins/stream.ts` passes in
11
- * as `basePort` — this platform file reads no `CARDTABLE_*` env var itself any more.
12
- */
13
- export declare const ROOM_STREAM_BASE_PORT = 6100;
14
1
  /** Seats in one room. A pod is 8; a constructed table is 2. */
15
2
  export declare const MAX_ROOM_SEATS = 8;
16
3
  /** No websocket attached for this long → the containers go. See the header. */
@@ -62,10 +49,16 @@ export interface RoomStreamsOptions {
62
49
  script?: ContainerScript;
63
50
  /** Injectable so the idle window is tested with a fake clock, not a wait. */
64
51
  now?: () => number;
65
- basePort?: number;
52
+ /** The first host port a room's seat may take; `container.sh` refuses anything below 6100. */
53
+ basePort: number;
66
54
  poolSize?: number;
67
55
  idleMs?: number;
68
- namePrefix?: string;
56
+ /**
57
+ * Container names are `<namePrefix>-<roomKey>-<seat>`. The prefix is this server's ownership
58
+ * claim: `sweepOrphans()` destroys every container with it that this process does not own, so
59
+ * two servers on one host (an e2e run beside production) must never share one.
60
+ */
61
+ namePrefix: string;
69
62
  log?: (entry: Record<string, unknown>) => void;
70
63
  /**
71
64
  * A room's containers actually came down — through `release()`, the idle sweep, or `sweep()`
@@ -42,19 +42,6 @@ import { existsSync } from 'node:fs';
42
42
  import { dirname, join, resolve } from 'node:path';
43
43
  import { fileURLToPath } from 'node:url';
44
44
  import { ROOM_ID_RE } from '@wolffm/platform-wire/room-feed';
45
- /**
46
- * The first host port a room's seat may take, when `createRoomStreams`'s caller does not pass its
47
- * own `basePort`.
48
- *
49
- * Deliberately clear of everything else on this host: 6080–6081 are the static
50
- * bench, and the e2e harness picks its ports from 20000 up (`e2e/ports.ts`). `container.sh` refuses
51
- * anything below 6100 a second time, in case this constant is ever loosened.
52
- *
53
- * A literal, not `CONFIG.roomStreamBasePort` (w119 §C): the room-stream ports are Forge/Magic-only
54
- * (survey §3), so Magic's `MAGIC_CONFIG.roomStreamBasePort` is what `plugins/stream.ts` passes in
55
- * as `basePort` — this platform file reads no `CARDTABLE_*` env var itself any more.
56
- */
57
- export const ROOM_STREAM_BASE_PORT = 6100;
58
45
  /**
59
46
  * How many streamed seats may exist on this host AT ONCE, across all rooms.
60
47
  *
@@ -68,24 +55,6 @@ const ROOM_STREAM_POOL = 8;
68
55
  export const MAX_ROOM_SEATS = 8;
69
56
  /** No websocket attached for this long → the containers go. See the header. */
70
57
  export const IDLE_RECLAIM_MS = 30 * 60_000;
71
- /**
72
- * Container names: `<prefix>-<roomKey>-<seat>`. `container.sh` enforces it.
73
- *
74
- * **Env-settable because the prefix is this server's OWNERSHIP claim, and a
75
- * host can run more than one cardtable.** `sweepOrphans()` destroys every
76
- * container matching the prefix that this process's `live` map does not own —
77
- * which is right for reclaiming what a restart of THIS server left behind, and
78
- * catastrophic across two servers sharing one name. A `pnpm e2e` run boots a
79
- * second server on the machine that runs production: with one prefix its boot
80
- * sweep would delete a real player's containers mid-match. The e2e harness
81
- * therefore sets its own prefix, and `container.sh` already reads the same
82
- * variable, so the script and the server can never disagree about what this
83
- * server may touch.
84
- *
85
- * A literal default, like {@link ROOM_STREAM_BASE_PORT} — `plugins/stream.ts` passes its own
86
- * `namePrefix` from `MAGIC_CONFIG.streamNamePrefix` (`CARDTABLE_STREAM_NAME_PREFIX`).
87
- */
88
- const CONTAINER_NAME_PREFIX = 'cardtable-room';
89
58
  /**
90
59
  * Where `scripts/stream/container.sh` is, found by walking up from this file.
91
60
  *
@@ -147,10 +116,10 @@ export function isStaticIndexLike(roomKey) {
147
116
  }
148
117
  export function createRoomStreams(options) {
149
118
  const now = options.now ?? Date.now;
150
- const basePort = options.basePort ?? ROOM_STREAM_BASE_PORT;
119
+ const basePort = options.basePort;
151
120
  const poolSize = options.poolSize ?? ROOM_STREAM_POOL;
152
121
  const idleMs = options.idleMs ?? IDLE_RECLAIM_MS;
153
- const prefix = options.namePrefix ?? CONTAINER_NAME_PREFIX;
122
+ const prefix = options.namePrefix;
154
123
  const log = options.log ?? (() => { });
155
124
  const script = options.script ??
156
125
  (() => {
@@ -1,9 +1,12 @@
1
1
  import type { Server } from 'node:http';
2
2
  import type { Router } from 'express';
3
+ import type { gateUpgrade } from '../gate.js';
3
4
  import { type RoomStreams } from './alloc.js';
4
5
  export interface StreamDeps {
5
6
  /** The tier floor. `CONFIG.minTier` — never lower, never a new tier. */
6
7
  minTier: string;
8
+ /** The floor at the websocket upgrade: `@hadoku/game-server/gate`'s `gateUpgrade`. */
9
+ gateUpgrade: typeof gateUpgrade;
7
10
  /** Container n's noVNC port is `streamBasePort + n`. */
8
11
  streamBasePort: number;
9
12
  /** How many STATIC stream containers to expose. 0 → attach none of them. */
@@ -39,13 +42,13 @@ export interface RoomStreamPath {
39
42
  */
40
43
  export declare function roomStreamPathOf(url: string | undefined): RoomStreamPath | null;
41
44
  /**
42
- * How many containers to expose, read from `STREAMS` on disk.
45
+ * How many containers to expose, read from `<dir>/STREAMS` on disk.
43
46
  *
44
47
  * A malformed count is zero containers, not a guess — each container is a
45
48
  * proxy to a port, and guessing here is a port scan. Bounded because an
46
49
  * unbounded count is the same scan with more steps.
47
50
  */
48
- export declare function streamLayout(exists?: (p: string) => boolean, read?: (p: string) => string, dir?: string): {
51
+ export declare function streamLayout(dir: string, exists?: (p: string) => boolean, read?: (p: string) => string): {
49
52
  streamCount: number;
50
53
  };
51
54
  /**
@@ -61,6 +64,6 @@ export declare function attachStreamRoutes(app: Router, deps: StreamDeps): boole
61
64
  /**
62
65
  * The websocket half: noVNC talks RFB over a websocket to websockify.
63
66
  * express never sees an `upgrade`, so the tier floor is re-applied here by
64
- * hand, with `../gate.ts`'s `gateUpgrade`.
67
+ * hand, with the injected `gateUpgrade`.
65
68
  */
66
69
  export declare function attachStream(server: Server, deps: StreamDeps): StreamHandle | null;
@@ -37,7 +37,7 @@
37
37
  * ## The gate
38
38
  *
39
39
  * The HTTP half is mounted below `requireMinTier`. The websocket half
40
- * re-applies the floor itself — `../gate.ts`'s `gateUpgrade` — because an
40
+ * re-applies the floor itself — the injected `gateUpgrade` — because an
41
41
  * `upgrade` event runs no express middleware.
42
42
  *
43
43
  * **404, never 403.** A different answer for "exists but you may not" tells
@@ -46,12 +46,10 @@
46
46
  * the floor, so it tells a friend the truth and an outsider nothing.
47
47
  */
48
48
  import { existsSync, readFileSync } from 'node:fs';
49
- import { homedir } from 'node:os';
50
49
  import { join } from 'node:path';
51
50
  import { connect } from 'node:net';
52
51
  import { request as httpRequest } from 'node:http';
53
52
  import express from 'express';
54
- import { gateUpgrade } from '../gate.js';
55
53
  import { ROOM_ID_RE } from '@wolffm/platform-wire/room-feed';
56
54
  import { isStaticIndexLike } from './alloc.js';
57
55
  /** `/stream/3/websockify` → 3, or null when the path is not a stream path. */
@@ -85,25 +83,14 @@ export function roomStreamPathOf(url) {
85
83
  return { roomKey, seat: Number(m[2]), rest: query === undefined ? rest : `${rest}?${query}` };
86
84
  }
87
85
  /**
88
- * Where `STREAMS` lives, if `streamLayout`'s caller passes nothing: `~/.local/share/cardtable/
89
- * stream`, same as `CARDTABLE_STREAM_DIR`'s old default. A literal, not a `process.env` read (w119
90
- * §C, same reasoning as `alloc.ts`'s `ROOM_STREAM_BASE_PORT`/`CONTAINER_NAME_PREFIX`): this
91
- * platform file reads no `CARDTABLE_*` var itself any more. `games/magic/server/src/plugins/
92
- * stream.ts` passes `MAGIC_CONFIG.streamDir` (`CARDTABLE_STREAM_DIR`, so a second server on the
93
- * same machine still stays off this one's containers) as `streamLayout`'s `dir`.
94
- */
95
- function streamsFile(dir) {
96
- return join(dir ?? join(homedir(), '.local', 'share', 'cardtable', 'stream'), 'STREAMS');
97
- }
98
- /**
99
- * How many containers to expose, read from `STREAMS` on disk.
86
+ * How many containers to expose, read from `<dir>/STREAMS` on disk.
100
87
  *
101
88
  * A malformed count is zero containers, not a guess — each container is a
102
89
  * proxy to a port, and guessing here is a port scan. Bounded because an
103
90
  * unbounded count is the same scan with more steps.
104
91
  */
105
- export function streamLayout(exists = existsSync, read = (f) => readFileSync(f, 'utf8'), dir) {
106
- const streamsFilePath = streamsFile(dir);
92
+ export function streamLayout(dir, exists = existsSync, read = (f) => readFileSync(f, 'utf8')) {
93
+ const streamsFilePath = join(dir, 'STREAMS');
107
94
  try {
108
95
  const raw = exists(streamsFilePath) ? read(streamsFilePath).trim() : '0';
109
96
  const n = Number(raw);
@@ -229,7 +216,7 @@ export function attachStreamRoutes(app, deps) {
229
216
  /**
230
217
  * The websocket half: noVNC talks RFB over a websocket to websockify.
231
218
  * express never sees an `upgrade`, so the tier floor is re-applied here by
232
- * hand, with `../gate.ts`'s `gateUpgrade`.
219
+ * hand, with the injected `gateUpgrade`.
233
220
  */
234
221
  export function attachStream(server, deps) {
235
222
  const rooms = deps.rooms ?? null;
@@ -245,7 +232,7 @@ export function attachStream(server, deps) {
245
232
  refuse(socket, 400, 'expected a version-13 websocket upgrade');
246
233
  return;
247
234
  }
248
- const floor = gateUpgrade(req, { minTier: deps.minTier, surface: 'stream' });
235
+ const floor = deps.gateUpgrade(req, { minTier: deps.minTier, surface: 'stream' });
249
236
  if (!floor.ok) {
250
237
  refuse(socket, 404, 'not found');
251
238
  return;
@@ -1,42 +1,15 @@
1
1
  /**
2
- * Adapter: cardtable's binding of `@hadoku/service-kernel/telemetry` (w93-K3).
2
+ * Adapter: game-server's binding of `@hadoku/service-kernel/telemetry`.
3
3
  *
4
4
  * The plain re-exports stay because the published `@wolffm/game-server/telemetry` is a contract:
5
5
  * bomberman's server imports `callerContext`, `report`, `installTelemetry` and `Report` from it.
6
- * The cardtable-specific bits are the service id
7
- * (`cardtable`, stamped on every event's `context.service` and in the posting User-Agent), the
8
- * env var named in the disabled-reason log line (`CARDTABLE_SERVICE_KEY`), and the closed set of
9
- * surfaces a seal refusal ever names — the kernel's own `reportSealRefused` takes an open string,
10
- * since it knows no game's surface names.
6
+ * What is its own is the closed set of surfaces a seal refusal ever names — the kernel's own
7
+ * `reportSealRefused` takes an open string, since it knows no game's surface names.
11
8
  */
12
9
  import type { Request } from 'express';
13
- import type { JsonLog } from '@wolffm/service-kernel/log';
14
10
  import { callerContext, installTelemetry, report, reportingAlerts, type Level, type Report, type TelemetryContext } from '@wolffm/service-kernel/telemetry';
15
11
  export { callerContext, installTelemetry, report, reportingAlerts };
16
12
  export type { Level, Report, TelemetryContext };
17
- /**
18
- * Which deployment a base path is: `/cardtable` is prod, `/cardtable-<site>` that site
19
- * (`/cardtable-ppe` is ppe, as the PPE wrapper sets `CARDTABLE_BASE_PREFIX`). Any other
20
- * prefix names itself.
21
- */
22
- export declare function siteOf(basePrefix: string): string;
23
- export interface SinkOptions {
24
- /** `https://hadoku.me` — the telemetry route is `/health/api/telemetry` under it. */
25
- baseUrl: string;
26
- serviceKey: string;
27
- log: JsonLog;
28
- /** This deployment (`siteOf`), on every event. */
29
- site: string;
30
- /** One post per (event, caller, incident key) per this many ms. */
31
- windowMs?: number;
32
- now?: () => number;
33
- fetch?: typeof fetch;
34
- }
35
- /**
36
- * A reporter that posts to monitoring-api. Without a service key it posts
37
- * nothing and says so once, the way the stats reporter does.
38
- */
39
- export declare function monitoringSink(opts: SinkOptions): Report;
40
13
  type Headers = Request['headers'];
41
14
  /**
42
15
  * A seal below the edge refused a caller. With the edge in front this should
package/dist/telemetry.js CHANGED
@@ -1,20 +1,5 @@
1
- import { callerContext, installTelemetry, monitoringSink as kernelMonitoringSink, report, reportingAlerts, reportSealRefused as kernelReportSealRefused, siteOf as kernelSiteOf, } from '@wolffm/service-kernel/telemetry';
1
+ import { callerContext, installTelemetry, report, reportingAlerts, reportSealRefused as kernelReportSealRefused, } from '@wolffm/service-kernel/telemetry';
2
2
  export { callerContext, installTelemetry, report, reportingAlerts };
3
- /**
4
- * Which deployment a base path is: `/cardtable` is prod, `/cardtable-<site>` that site
5
- * (`/cardtable-ppe` is ppe, as the PPE wrapper sets `CARDTABLE_BASE_PREFIX`). Any other
6
- * prefix names itself.
7
- */
8
- export function siteOf(basePrefix) {
9
- return kernelSiteOf(basePrefix, 'cardtable');
10
- }
11
- /**
12
- * A reporter that posts to monitoring-api. Without a service key it posts
13
- * nothing and says so once, the way the stats reporter does.
14
- */
15
- export function monitoringSink(opts) {
16
- return kernelMonitoringSink({ ...opts, service: 'cardtable', serviceKeyEnvVar: 'CARDTABLE_SERVICE_KEY' });
17
- }
18
3
  /**
19
4
  * A seal below the edge refused a caller. With the edge in front this should
20
5
  * never fire: one means a direct hit on the tunnel host, or an edge rule wider
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/game-server",
3
- "version": "0.1.211",
4
- "gitHead": "0ea202e41619bdb176bbbc6c030ed3940611a093",
3
+ "version": "0.1.213",
4
+ "gitHead": "d8a95c3583ef6c967ef63ade32c57ae9a3b6272b",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "description": "The server parts any hosted game shares, above the kernel: the app config and edge auth, the room core (identity, seats, sessions, membership, the room list, the generic room routes), match hosting (the host contract, local and remote JVMs, placement, the start queue, recordings, the in-process and relay runtimes), streams, erase, telemetry and usage. Knows no game; Magic plugs in from apps/server. MIT; imports only node built-ins, express, socket.io, @wolffm/* and the platform packages.",
@@ -12,14 +12,13 @@
12
12
  }
13
13
  },
14
14
  "publishLeaveOut": [
15
- "announce.ts",
16
15
  "play/placement/",
17
16
  "play/remote/"
18
17
  ],
19
18
  "dependencies": {
20
- "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.211",
21
- "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.211",
22
- "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.244",
19
+ "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.213",
20
+ "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.213",
21
+ "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.246",
23
22
  "@wolffm/prefs-client": "npm:@hadoku/prefs-client@^1.2.3",
24
23
  "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.152",
25
24
  "@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.152",
@@ -1,25 +0,0 @@
1
- /**
2
- * The base-path contract, checked at boot — cardtable's binding of the
3
- * platform kernel (`@hadoku/service-kernel/http`).
4
- *
5
- * This is the one thing about a loopback-UI app that breaks SILENTLY, so it is
6
- * the one thing this server refuses to guess about.
7
- *
8
- * The edge gives us stripPrefix: hadoku.me/cardtable/assets/x.js arrives here
9
- * as /assets/x.js, which we serve happily. But the BROWSER is at
10
- * hadoku.me/cardtable/, so a bundle built with the default base emits
11
- * `src="/assets/x.js"` — an absolute URL with no prefix. The browser asks the
12
- * edge for hadoku.me/assets/x.js, which is not this app's route, and the page
13
- * renders blank with a 404 in the console and a 200 on every server-side probe.
14
- * games-host shipped exactly this: its edge stripPrefix and its backend's base
15
- * path are two independent declarations of one fact, and nothing compared them.
16
- *
17
- * So the kernel's `checkBundle` compares them once, at boot, and says precisely
18
- * what to change. What is cardtable's own in that check is here.
19
- */
20
- /**
21
- * The embed bundle's two fixed-name files (D21): `apps/ui/vite.embed.config.ts`
22
- * emits them, watchparty imports the `.js`. Every other file in the bundle is
23
- * content-hashed; these are the only ones whose bytes change under one name.
24
- */
25
- export declare const EMBED_ENTRIES: readonly ["cardtable-embed.js", "cardtable-embed.css"];
package/dist/base-path.js DELETED
@@ -1,25 +0,0 @@
1
- /**
2
- * The base-path contract, checked at boot — cardtable's binding of the
3
- * platform kernel (`@hadoku/service-kernel/http`).
4
- *
5
- * This is the one thing about a loopback-UI app that breaks SILENTLY, so it is
6
- * the one thing this server refuses to guess about.
7
- *
8
- * The edge gives us stripPrefix: hadoku.me/cardtable/assets/x.js arrives here
9
- * as /assets/x.js, which we serve happily. But the BROWSER is at
10
- * hadoku.me/cardtable/, so a bundle built with the default base emits
11
- * `src="/assets/x.js"` — an absolute URL with no prefix. The browser asks the
12
- * edge for hadoku.me/assets/x.js, which is not this app's route, and the page
13
- * renders blank with a 404 in the console and a 200 on every server-side probe.
14
- * games-host shipped exactly this: its edge stripPrefix and its backend's base
15
- * path are two independent declarations of one fact, and nothing compared them.
16
- *
17
- * So the kernel's `checkBundle` compares them once, at boot, and says precisely
18
- * what to change. What is cardtable's own in that check is here.
19
- */
20
- /**
21
- * The embed bundle's two fixed-name files (D21): `apps/ui/vite.embed.config.ts`
22
- * emits them, watchparty imports the `.js`. Every other file in the bundle is
23
- * content-hashed; these are the only ones whose bytes change under one name.
24
- */
25
- export const EMBED_ENTRIES = ['cardtable-embed.js', 'cardtable-embed.css'];
package/dist/busy.d.ts DELETED
@@ -1,39 +0,0 @@
1
- /**
2
- * Adapter: cardtable's binding of `@hadoku/service-kernel/lifecycle`'s busy probe (w93-K2).
3
- *
4
- * The kernel knows only the report's shape, `isLocalProbe` and the HTTP plumbing (fail-safe on
5
- * `report`'s own throw, 404 to anything proxied). What counts as cardtable's "destroyable work" —
6
- * a live match or a drafting pod, never a warm JVM or an idle lobby — stays here, unchanged from
7
- * before this moved (`docs` below is the same text as always).
8
- *
9
- * ## What counts as busy — destroyable work, not connections
10
- *
11
- * - a match that is `starting` or `running`: a Forge JVM with players seated;
12
- * - a draft that is `drafting`: picks made, packs mid-pass, held in memory.
13
- *
14
- * NOT counted, deliberately:
15
- *
16
- * - a match that is `over`, `failed` or `stopped` — finished, nothing left to lose;
17
- * - a `complete` draft;
18
- * - **the warm JVM.** `liveJvmCount()` includes it and would report busy every
19
- * minute of the day; it is a pre-booted process with nobody in it;
20
- * - **connected-but-idle clients and open lobbies.** They reconnect fine, they
21
- * never disconnect on their own, and counting them would make every deploy sit
22
- * until its deadline — at which point the deadline kills the real match anyway.
23
- */
24
- import type { BusyReport } from '@wolffm/service-kernel/lifecycle';
25
- export interface BusySources {
26
- matches(): ReadonlyArray<{
27
- id: string;
28
- status: string;
29
- seats: ReadonlyArray<unknown>;
30
- anyoneHere?: () => boolean;
31
- }>;
32
- drafts(): ReadonlyArray<{
33
- id: string;
34
- status: string | undefined;
35
- packNumber?: number;
36
- pickNumber?: number;
37
- }>;
38
- }
39
- export declare function busyReport(src: BusySources): BusyReport;
package/dist/busy.js DELETED
@@ -1,22 +0,0 @@
1
- const BUSY_MATCH = new Set(['starting', 'running']);
2
- export function busyReport(src) {
3
- const runs = [];
4
- for (const m of src.matches()) {
5
- if (!BUSY_MATCH.has(m.status))
6
- continue;
7
- // A running match whose seats have all gone (past the grace) holds nobody's game:
8
- // the zombie of m-09487f336215 held every deploy for hours on 2026-10-04.
9
- if (m.status === 'running' && m.anyoneHere !== undefined && !m.anyoneHere())
10
- continue;
11
- runs.push({ id: m.id, kind: 'match', label: `${m.seats.length} seats, ${m.status}` });
12
- }
13
- for (const d of src.drafts()) {
14
- if (d.status !== 'drafting')
15
- continue;
16
- const at = d.packNumber !== undefined && d.pickNumber !== undefined
17
- ? `pack ${d.packNumber} pick ${d.pickNumber}`
18
- : 'in progress';
19
- runs.push({ id: d.id, kind: 'draft', label: at });
20
- }
21
- return { busy: runs.length > 0, count: runs.length, runs };
22
- }
@@ -1,9 +0,0 @@
1
- /**
2
- * Cardtable's binding of the kernel's capacity sampler: a card image request (`http/card-art.ts`)
3
- * is a redirect to the art host, one per card a page draws, so it is counted on its own as
4
- * `artRedirects`, never timed nor logged a line each. `index.ts` hands it to `createGameServer`.
5
- */
6
- export declare const ART_REDIRECTS: {
7
- path: (path: string) => boolean;
8
- field: string;
9
- };
package/dist/capacity.js DELETED
@@ -1,6 +0,0 @@
1
- /**
2
- * Cardtable's binding of the kernel's capacity sampler: a card image request (`http/card-art.ts`)
3
- * is a redirect to the art host, one per card a page draws, so it is counted on its own as
4
- * `artRedirects`, never timed nor logged a line each. `index.ts` hands it to `createGameServer`.
5
- */
6
- export const ART_REDIRECTS = { path: (path) => path.startsWith('/api/art/'), field: 'artRedirects' };