@hadoku/game-server 0.1.23 → 0.1.25

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.
@@ -116,6 +116,14 @@ export interface LobbyCore<V extends RoomViewCore, C> {
116
116
  ok: false;
117
117
  reason: string;
118
118
  };
119
+ /** The leader hands the room's leadership to another member (`room/lobby.ts`'s `passLeader`). */
120
+ passLeader(roomId: string, callerId: string, targetId: string): {
121
+ ok: true;
122
+ room: V;
123
+ } | {
124
+ ok: false;
125
+ reason: string;
126
+ };
119
127
  }
120
128
  /** Every one of the leader's three seat ops, per caller: a burst of 10, then one every 10 s — the same shape as a join attempt, spent only by a leader who is actually a member of the room (checked before this is asked). */
121
129
  export declare const SEAT_OP_RATE_LIMIT: RateLimitConfig;
@@ -343,6 +343,20 @@ export function attachRoomCore(api, deps, opts = {}) {
343
343
  return seatOpStatus(res, result.reason);
344
344
  res.json({ ...roomBody(result.room, caller.id), evicted: result.evicted });
345
345
  });
346
+ // The leader hands the room to another member, seated or watching. Spends the seat-op limit.
347
+ rooms.post('/:id/leader', (req, res) => {
348
+ const body = parseBody(removeFromSeatBody, req, res);
349
+ if (body === null || !seatOpLimit(req, res))
350
+ return;
351
+ const caller = callerOf(req);
352
+ const id = String(req.params.id);
353
+ if (!wire.roomIdRe.test(id))
354
+ return noMatch(res);
355
+ const result = lobby.passLeader(id, caller.id, body.memberId);
356
+ if (!result.ok)
357
+ return seatOpStatus(res, result.reason);
358
+ res.json(roomBody(result.room, caller.id));
359
+ });
346
360
  /**
347
361
  * `{ gameType }` is this file's own: the game-type registry is platform.
348
362
  * Everything else `P` can be (Magic's `{ format }`/`{ settings }`/`{ mode }`)
@@ -37,7 +37,7 @@
37
37
  import type { Server as SocketIOServer } from 'socket.io';
38
38
  import type { ParticipantId } from '@wolffm/rooms-protocol';
39
39
  import type { RateLimitConfig } from '@wolffm/rooms-server';
40
- import type { Gate } from '@wolffm/service-kernel/http';
40
+ import { type Gate } from '@wolffm/service-kernel/http';
41
41
  import { type RelayOutcome, type RelaySession, type RelaySink } from './runtimes/relay.js';
42
42
  export declare const RELAY_EVENTS: {
43
43
  readonly join: "relay:join";
@@ -101,8 +101,14 @@ export interface RelayDeps {
101
101
  /** The tier floor; `CONFIG.minTier` in production. */
102
102
  minTier: string;
103
103
  /**
104
- * The handshake gate: the game's own binding of the kernel's `createGate` (its edge secret, its
105
- * bare-local hatch, its seal-refusal report). Absent: cardtable's (`../gate.ts`).
104
+ * The handshake gate: the CONSUMER's own binding of the kernel's `createGate` (its edge
105
+ * secret, its bare-local hatch, its seal-refusal report) — bomberman builds its own
106
+ * (`floorGateFor`) and passes it here for exactly this reason. Absent: {@link defaultRelayGate},
107
+ * built fresh from nothing but the shared, unprefixed `EDGE_AUTH_SECRET` and `deps` — never
108
+ * `../gate.ts`'s own binding, which is cardtable's `CONFIG` (envPrefix `CARDTABLE`) and, inside
109
+ * a SECOND app built on this package, is still bound to that same prefix regardless of that
110
+ * app's own env (bm1-BS, `docs/planning/s3-2026-11-17.md` §G.3: omitting `gate` sanitized every
111
+ * bomberman handshake to public under bomberman's own env and refused every tier, measured).
106
112
  */
107
113
  gate?: Pick<Gate, 'gateSocketIo'>;
108
114
  /** This match's roster, or `undefined` for a matchId nothing is running — refused as `unknown-match`. */
@@ -34,7 +34,8 @@
34
34
  * every `relay:ended`): no new event and no reconnect. Until it does, that socket speaks for
35
35
  * nothing — its sends and its disconnect belong to the match it joined, which is over.
36
36
  */
37
- import { gateSocketIo } from '../gate.js';
37
+ import { createEdgeAuth, rankOf, tierOf } from '@wolffm/service-kernel/auth';
38
+ import { createGate } from '@wolffm/service-kernel/http';
38
39
  import { identityFromHeaders } from '../room/identity.js';
39
40
  import { costlyActLimit } from '../http/request.js';
40
41
  export const RELAY_EVENTS = {
@@ -57,6 +58,34 @@ function readMatchId(payload) {
57
58
  const matchId = payload?.matchId;
58
59
  return typeof matchId === 'string' && matchId !== '' ? matchId : null;
59
60
  }
61
+ /**
62
+ * The gate used when a caller omits `deps.gate` — built fresh, every call, from nothing this
63
+ * package's own `CONFIG` owns: the shared `EDGE_AUTH_SECRET` (unprefixed, the edge's own secret,
64
+ * common to every app behind it — not per-game, same as `config.ts`'s own field of that name) and
65
+ * `deps.log` for refusals. `allowUnverifiedEdge` is always `false` here: the bare-local dev hatch
66
+ * is an explicit per-app opt-in (`CARDTABLE_INSECURE_NO_EDGE_AUTH`, `BOMBERMAN_INSECURE_NO_EDGE_AUTH`,
67
+ * …, each its OWN app's prefix), and a generic default has no prefix of its own to read one
68
+ * under — reading any ONE app's by guessing would be exactly the bug this replaces. A caller that
69
+ * wants the hatch passes its own `gate` (as bomberman's `floorGateFor` does).
70
+ */
71
+ function defaultRelayGate(deps) {
72
+ const edgeAuth = createEdgeAuth({
73
+ edgeAuthSecret: () => process.env.EDGE_AUTH_SECRET ?? '',
74
+ allowUnverifiedEdge: () => false,
75
+ devTier: () => deps.minTier,
76
+ });
77
+ return createGate({
78
+ sanitizeHeaders: edgeAuth.sanitizeHeaders,
79
+ edgeProvenance: edgeAuth.edgeProvenance,
80
+ tierOf,
81
+ rankOf,
82
+ reportSealRefused: (surface, headers, path) => {
83
+ const tier = headers['x-hadoku-tier'];
84
+ deps.log?.({ evt: 'seal-refused', surface, path, tier: typeof tier === 'string' ? tier : 'public' });
85
+ },
86
+ minTier: () => deps.minTier,
87
+ });
88
+ }
60
89
  /**
61
90
  * Attaches the relay's `connection`/`relay:join`/`relay:message` handlers to
62
91
  * `io`. Safe to call once per process; a second call on the same `io` would
@@ -64,7 +93,7 @@ function readMatchId(payload) {
64
93
  * a second, independent `live` map, so callers should not do that.
65
94
  */
66
95
  export function attachRelay(io, deps) {
67
- (deps.gate ?? { gateSocketIo }).gateSocketIo(io, { minTier: deps.minTier, surface: 'play-socket' });
96
+ (deps.gate ?? defaultRelayGate(deps)).gateSocketIo(io, { minTier: deps.minTier, surface: 'play-socket' });
68
97
  const log = deps.log ?? (() => { });
69
98
  const live = new Map();
70
99
  const joinLimit = costlyActLimit(deps.joinRateLimit === undefined ? RELAY_JOIN_RATE_LIMIT : deps.joinRateLimit, {
@@ -77,6 +77,15 @@ export declare class RelayMatch extends HostedMatch<RelayLine, RelayCommand> imp
77
77
  endedAt: number | null;
78
78
  private sessionRef;
79
79
  private readonly seatGrace;
80
+ /**
81
+ * Who started THIS round — the first seat (never a watcher) to join it, set once and never
82
+ * reassigned for this match's lifetime. `mayEnd` honours this seat's `over` the same as the
83
+ * leader's (§G.3): the leader is the ROOM's host, but a relay match has no separate "Start" a
84
+ * non-Magic room's UI ever presses (this file's own header) — the first seat to actually join
85
+ * IS the one who started this round, bomberman's own rule (`AGENTS.md`: "who started it"). A
86
+ * watcher never sets it: only a real seat starts a round.
87
+ */
88
+ private hostSeatRef;
80
89
  protected readonly deps: RelayMatchInternalDeps;
81
90
  constructor(id: string, seatCount: number, deps: RelayMatchInternalDeps, restore?: {
82
91
  epoch: string | null;
@@ -92,6 +101,8 @@ export declare class RelayMatch extends HostedMatch<RelayLine, RelayCommand> imp
92
101
  lastEnded(): RelayEnded | undefined;
93
102
  /** `RelayRoster.seatCount`. */
94
103
  get seatCount(): number;
104
+ /** Who started this round — see {@link hostSeatRef}'s own doc. Null until a seat has joined. */
105
+ get hostSeat(): number | null;
95
106
  /**
96
107
  * `RelayRoster.roleOf`: the seat the room has this participant in (`deps.roomSeatOf`), read
97
108
  * fresh on every join, or null — a watcher — for one the room seats nowhere. The seat's owner
@@ -107,7 +118,13 @@ export declare class RelayMatch extends HostedMatch<RelayLine, RelayCommand> imp
107
118
  * calls this at most once per roster — returns the session already built rather than replacing it.
108
119
  */
109
120
  attach(sink: RelaySink, onEnded: (outcome: RelayOutcome | null) => void): RelaySession;
110
- /** Only the leader's seat ends the match; anyone else's `over` is refused and logged. */
121
+ /**
122
+ * The leader's seat ends the match, same as before; so does the round's own HOST seat — the
123
+ * one who started it (§G.3: bm1-BR found a non-leader host's `over` refused). The two usually
124
+ * agree (the leader is almost always first to join their own room's match), but differ once the
125
+ * leader has moved on: the room's leadership can pass to someone who was never in this round at
126
+ * all (`Lobby.leave`'s ruling 6), while the round still belongs to whoever is actually playing it.
127
+ */
111
128
  private mayEnd;
112
129
  private applyEnded;
113
130
  /**
@@ -55,6 +55,15 @@ export class RelayMatch extends HostedMatch {
55
55
  endedAt = null;
56
56
  sessionRef = null;
57
57
  seatGrace = new Map();
58
+ /**
59
+ * Who started THIS round — the first seat (never a watcher) to join it, set once and never
60
+ * reassigned for this match's lifetime. `mayEnd` honours this seat's `over` the same as the
61
+ * leader's (§G.3): the leader is the ROOM's host, but a relay match has no separate "Start" a
62
+ * non-Magic room's UI ever presses (this file's own header) — the first seat to actually join
63
+ * IS the one who started this round, bomberman's own rule (`AGENTS.md`: "who started it"). A
64
+ * watcher never sets it: only a real seat starts a round.
65
+ */
66
+ hostSeatRef = null;
58
67
  constructor(id, seatCount, deps, restore) {
59
68
  super(id, relaySpec(seatCount), deps, restore);
60
69
  this.seats = Array.from({ length: seatCount }, (_, seat) => ({ seat, ai: false, owner: null, playerId: seat, departure: null, here: false, away: false }));
@@ -76,6 +85,10 @@ export class RelayMatch extends HostedMatch {
76
85
  get seatCount() {
77
86
  return this.seats.length;
78
87
  }
88
+ /** Who started this round — see {@link hostSeatRef}'s own doc. Null until a seat has joined. */
89
+ get hostSeat() {
90
+ return this.hostSeatRef;
91
+ }
79
92
  /**
80
93
  * `RelayRoster.roleOf`: the seat the room has this participant in (`deps.roomSeatOf`), read
81
94
  * fresh on every join, or null — a watcher — for one the room seats nowhere. The seat's owner
@@ -97,6 +110,10 @@ export class RelayMatch extends HostedMatch {
97
110
  this.remember();
98
111
  this.deps.log({ evt: 'seat-claimed', matchId: this.id, seat: seat.seat, participantId });
99
112
  }
113
+ if (this.hostSeatRef === null) {
114
+ this.hostSeatRef = seat.seat;
115
+ this.deps.log({ evt: 'relay-host-seat', matchId: this.id, seat: seat.seat });
116
+ }
100
117
  return seat.seat;
101
118
  }
102
119
  /**
@@ -122,12 +139,18 @@ export class RelayMatch extends HostedMatch {
122
139
  this.armRejoinGrace();
123
140
  return session;
124
141
  }
125
- /** Only the leader's seat ends the match; anyone else's `over` is refused and logged. */
142
+ /**
143
+ * The leader's seat ends the match, same as before; so does the round's own HOST seat — the
144
+ * one who started it (§G.3: bm1-BR found a non-leader host's `over` refused). The two usually
145
+ * agree (the leader is almost always first to join their own room's match), but differ once the
146
+ * leader has moved on: the room's leadership can pass to someone who was never in this round at
147
+ * all (`Lobby.leave`'s ruling 6), while the round still belongs to whoever is actually playing it.
148
+ */
126
149
  mayEnd(seat) {
127
150
  const leaderSeat = this.deps.leaderSeat();
128
- if (seat === leaderSeat)
151
+ if (seat === leaderSeat || seat === this.hostSeatRef)
129
152
  return true;
130
- this.deps.log({ evt: 'relay-over-refused', matchId: this.id, seat, leaderSeat });
153
+ this.deps.log({ evt: 'relay-over-refused', matchId: this.id, seat, leaderSeat, hostSeat: this.hostSeatRef });
131
154
  return false;
132
155
  }
133
156
  applyEnded(outcome) {
@@ -162,6 +185,14 @@ export class RelayMatch extends HostedMatch {
162
185
  clearTimeout(timer);
163
186
  this.seatGrace.delete(seat);
164
187
  this.deps.log({ evt: 'relay-seat-back', matchId: this.id, seat });
188
+ return;
189
+ }
190
+ // The grace already fired (or none was armed at all): if the session had marked this seat
191
+ // gone for good, a reconnect to a match still running for whoever stayed is re-admitted,
192
+ // never muted forever (§G.3). A no-op when there was nothing to undo (a fresh join, or a
193
+ // seat that was never marked left), so this is safe to run on every connect unconditionally.
194
+ if (this.sessionRef?.readmit(seat) === true) {
195
+ this.deps.log({ evt: 'relay-seat-readmitted', matchId: this.id, seat });
165
196
  }
166
197
  }
167
198
  seatDisconnected(seat) {
@@ -211,6 +242,18 @@ export function createRelayMatch(id, seatCount, deps, previous) {
211
242
  export function createRelayMatchRegistry() {
212
243
  const matches = new Map();
213
244
  function register(id, seatCount, deps, previous) {
245
+ // Two concurrent starts (`docs/planning/s3-2026-11-17.md` §G.3): `register` called twice for
246
+ // the same id before either call's match has ended — the external caller never passes
247
+ // `previous` (only this function's own `ended` closure below does, once a match genuinely
248
+ // has one to carry) — gets the SAME, already-live match back rather than a second one that
249
+ // silently orphans whatever already attached to the first (a socket that already joined it
250
+ // would speak to a `RelayMatch` nothing else can ever find again). Once a match has ended
251
+ // (`status === 'over'`), registering the id again — the internal next-round call, or a late
252
+ // duplicate start arriving after the fact — DOES get a fresh one: idempotency only ever
253
+ // holds a match that is still live.
254
+ const existing = matches.get(id);
255
+ if (existing !== undefined && existing.status !== 'over' && previous === undefined)
256
+ return existing;
214
257
  const match = createRelayMatch(id, seatCount, {
215
258
  ...deps,
216
259
  ended: () => {
@@ -93,6 +93,17 @@ export declare class RelaySession implements GameSession<RelayLine, RelayCommand
93
93
  * has.
94
94
  */
95
95
  seatLeft(seat: number): void;
96
+ /**
97
+ * Undo a `seatLeft` for `seat`: a reconnect AFTER its hold already expired (`relay-match.ts`'s
98
+ * own grace timer already fired `seatLeft` by then), not one inside the grace — that path never
99
+ * calls `seatLeft` at all and so never needs this (`relay-match.ts`'s `seatConnected` clears the
100
+ * pending timer before it fires). Without this, a seat that comes back late to a match still
101
+ * running for whoever stayed stays muted forever: `fromSeat` drops anything it sends, silently,
102
+ * because `this.left` still has it (bm1-BR, `docs/planning/s3-2026-11-17.md` §G.3). A session
103
+ * already closed (every seat gone, or the leader's `over`) has nothing left to re-admit into —
104
+ * same no-op shape as every other method here once `closed`.
105
+ */
106
+ readmit(seat: number): boolean;
96
107
  private finish;
97
108
  onLine(_line: RelayLine): void;
98
109
  command(cmd: RelayCommand): void;
@@ -107,6 +107,22 @@ export class RelaySession {
107
107
  if (this.left.size >= this.seatCount)
108
108
  this.finish(null);
109
109
  }
110
+ /**
111
+ * Undo a `seatLeft` for `seat`: a reconnect AFTER its hold already expired (`relay-match.ts`'s
112
+ * own grace timer already fired `seatLeft` by then), not one inside the grace — that path never
113
+ * calls `seatLeft` at all and so never needs this (`relay-match.ts`'s `seatConnected` clears the
114
+ * pending timer before it fires). Without this, a seat that comes back late to a match still
115
+ * running for whoever stayed stays muted forever: `fromSeat` drops anything it sends, silently,
116
+ * because `this.left` still has it (bm1-BR, `docs/planning/s3-2026-11-17.md` §G.3). A session
117
+ * already closed (every seat gone, or the leader's `over`) has nothing left to re-admit into —
118
+ * same no-op shape as every other method here once `closed`.
119
+ */
120
+ readmit(seat) {
121
+ if (this.closed || !this.left.has(seat))
122
+ return false;
123
+ this.left.delete(seat);
124
+ return true;
125
+ }
110
126
  finish(outcome) {
111
127
  if (this.closed)
112
128
  return;
@@ -71,6 +71,26 @@ interface IdentityInputs {
71
71
  /** Fallback for a caller the edge could not name at all. */
72
72
  socketId: string;
73
73
  }
74
+ /**
75
+ * Swap the domain {@link deriveParticipantId}/{@link identityFromHeaders} close over, for a
76
+ * SECOND app built on this package (bomberman) whose own participant ids must not collide with
77
+ * — or be byte-identical to — cardtable's own (the exact thing {@link PARTICIPANT_ID_DOMAIN}'s
78
+ * domain separation exists to prevent, see this module's header). Cardtable itself never calls
79
+ * this: its ids are the default domain, unconfigured, exactly as before this function existed.
80
+ *
81
+ * Callable at most once per process, and only before this module has minted a single id under
82
+ * whichever domain is bound at the time — a swap after a derive would mean some callers already
83
+ * saw an id from one domain and the rest see another, the exact "two domains disagreeing" bug
84
+ * this whole scheme exists to rule out. Both failures throw rather than silently doing nothing,
85
+ * because a caller that thinks it configured the domain and did not would re-identify nobody
86
+ * visibly — it would simply mint cardtable's ids under its own app's name, forever.
87
+ *
88
+ * This is cardtable's own fix for the exact gap bomberman's
89
+ * `patches/@hadoku__game-server@0.1.15.patch` patched around (w120 carry-over,
90
+ * `docs/planning/s3-2026-11-17.md` §G.1): once this ships, that patch's job is done and bomberman
91
+ * drops it as part of its own version bump — no code change on either side beyond that.
92
+ */
93
+ export declare function configureParticipantIdDomain(domain: string): void;
74
94
  /**
75
95
  * Mint an id for one connection.
76
96
  *
@@ -68,8 +68,42 @@ export { participantHandle } from '@wolffm/rooms-protocol';
68
68
  * Bound once, at module scope. The factory shape is deliberate upstream: a
69
69
  * `(input, domain)` function would let a call site mint a second identity space
70
70
  * for the same person by passing a different string.
71
+ *
72
+ * `let`, not `const`: {@link configureParticipantIdDomain} is the one sanctioned way to
73
+ * rebind it, and only before this module has derived its first id.
74
+ */
75
+ let derive = createParticipantIdDeriver(PARTICIPANT_ID_DOMAIN);
76
+ let participantIdDomainConfigured = false;
77
+ let participantIdDerived = false;
78
+ /**
79
+ * Swap the domain {@link deriveParticipantId}/{@link identityFromHeaders} close over, for a
80
+ * SECOND app built on this package (bomberman) whose own participant ids must not collide with
81
+ * — or be byte-identical to — cardtable's own (the exact thing {@link PARTICIPANT_ID_DOMAIN}'s
82
+ * domain separation exists to prevent, see this module's header). Cardtable itself never calls
83
+ * this: its ids are the default domain, unconfigured, exactly as before this function existed.
84
+ *
85
+ * Callable at most once per process, and only before this module has minted a single id under
86
+ * whichever domain is bound at the time — a swap after a derive would mean some callers already
87
+ * saw an id from one domain and the rest see another, the exact "two domains disagreeing" bug
88
+ * this whole scheme exists to rule out. Both failures throw rather than silently doing nothing,
89
+ * because a caller that thinks it configured the domain and did not would re-identify nobody
90
+ * visibly — it would simply mint cardtable's ids under its own app's name, forever.
91
+ *
92
+ * This is cardtable's own fix for the exact gap bomberman's
93
+ * `patches/@hadoku__game-server@0.1.15.patch` patched around (w120 carry-over,
94
+ * `docs/planning/s3-2026-11-17.md` §G.1): once this ships, that patch's job is done and bomberman
95
+ * drops it as part of its own version bump — no code change on either side beyond that.
71
96
  */
72
- const derive = createParticipantIdDeriver(PARTICIPANT_ID_DOMAIN);
97
+ export function configureParticipantIdDomain(domain) {
98
+ if (participantIdDomainConfigured) {
99
+ throw new Error('configureParticipantIdDomain: already configured once for this process');
100
+ }
101
+ if (participantIdDerived) {
102
+ throw new Error('configureParticipantIdDomain: a participant id was already derived under the default domain; too late to swap it');
103
+ }
104
+ derive = createParticipantIdDeriver(domain);
105
+ participantIdDomainConfigured = true;
106
+ }
73
107
  /**
74
108
  * Mint an id for one connection.
75
109
  *
@@ -78,6 +112,7 @@ const derive = createParticipantIdDeriver(PARTICIPANT_ID_DOMAIN);
78
112
  * different question from which material the id was minted from.
79
113
  */
80
114
  export function deriveParticipantId(input) {
115
+ participantIdDerived = true;
81
116
  return derive(input).id;
82
117
  }
83
118
  function headerValue(headers, name) {
@@ -263,6 +263,11 @@ export type SitSeatResult<V> = {
263
263
  ok: false;
264
264
  reason: 'no-room' | 'not-member' | 'not-draft' | 'not-lobby' | 'not-open' | 'bad-seat' | 'seat-taken' | 'pod-full' | 'historical';
265
265
  };
266
+ /** `aiSeat`'s answer: a seat's answer, or `not-leader` — only the room's leader seats or unseats the AI. */
267
+ export type AiSeatResult<V> = SitSeatResult<V> | {
268
+ ok: false;
269
+ reason: 'not-leader';
270
+ };
266
271
  export type CloseSeatResult<V> = {
267
272
  ok: true;
268
273
  room: V;
@@ -287,6 +292,13 @@ export type StandSeatResult<V> = {
287
292
  * never a member acting on themselves. Built against cardtable's own `GameSeats`, not
288
293
  * `@wolffm/rooms-protocol`'s `SeatTable` — see `removeFromSeat`'s own doc for why.
289
294
  */
295
+ export type PassLeaderResult<V> = {
296
+ ok: true;
297
+ room: V;
298
+ } | {
299
+ ok: false;
300
+ reason: 'no-room' | 'not-member' | 'not-leader' | 'target-not-member';
301
+ };
290
302
  export type RemoveFromSeatResult<V> = {
291
303
  ok: true;
292
304
  room: V;
@@ -466,10 +478,15 @@ export declare class RoomLobby<V extends PlatformRoomView, I extends RoomCreateI
466
478
  sitSeat(roomId: string, memberId: string, seat?: number): SitSeatResult<V>;
467
479
  /** Give up a game seat. Idempotent: not seated is not a failure. */
468
480
  standSeat(roomId: string, memberId: string): StandSeatResult<V>;
469
- /** Put the AI in an open seat (`on`), or take it out. Any member. */
470
- aiSeat(roomId: string, memberId: string, seat: number, on: boolean): SitSeatResult<V>;
481
+ /** Put the AI in an open seat (`on`), or take it out. The leader's. */
482
+ aiSeat(roomId: string, memberId: string, seat: number, on: boolean): AiSeatResult<V>;
471
483
  /** Close an empty seat, or open a closed one: the leader's; never fewer than `MIN_OPEN_SEATS` open. */
472
484
  closeSeat(roomId: string, memberId: string, seat: number, closed: boolean): CloseSeatResult<V>;
485
+ /**
486
+ * The leader hands the room's leadership to `targetId`, another member, seated or watching.
487
+ * Passing it to yourself is answered `ok` and changes nothing.
488
+ */
489
+ passLeader(roomId: string, memberId: string, targetId: string): PassLeaderResult<V>;
473
490
  /**
474
491
  * The leader removes `targetId` from whatever game seat they hold, to the spectator row.
475
492
  * Idempotent: a target who holds none is still answered `ok`. Never touches membership — they
@@ -41,7 +41,7 @@ import { ROOM_ID_RE } from '@wolffm/platform-wire/room-feed';
41
41
  import { replaceIds } from "../erase/anonymise.js";
42
42
  import { avatarIdOf } from "./avatar.js";
43
43
  import { ROOM_STALE_MS, UNNAMED } from "./constants.js";
44
- import { addRoomMember, isMemberReady, isRoomMember, passwordAdmits, removeRoomMember, setMemberReady } from "./membership.js";
44
+ import { addRoomMember, isMemberReady, isRoomMember, passRoomLeader, passwordAdmits, removeRoomMember, setMemberReady } from "./membership.js";
45
45
  import { makeSecret, mintRoomId } from "./provisioning.js";
46
46
  import { AI_SEAT, CLOSED_SEAT, leaveGameSeat, memberSeats, setGameSeat, takeGameSeat } from "./record.js";
47
47
  import { isOfferedRoom, isSweepableRoom, NO_BUSY_HOOK, sortRoomsByCreation } from "./room-list.js";
@@ -690,12 +690,14 @@ export class RoomLobby {
690
690
  hooks.seatsChanged?.(room);
691
691
  return { ok: true, room: this.view(room) };
692
692
  }
693
- /** Put the AI in an open seat (`on`), or take it out. Any member. */
693
+ /** Put the AI in an open seat (`on`), or take it out. The leader's. */
694
694
  aiSeat(roomId, memberId, seat, on) {
695
695
  const found = this.#seatRoom(roomId, memberId);
696
696
  if ('refused' in found)
697
697
  return { ok: false, reason: found.refused };
698
698
  const { room, hooks } = found;
699
+ if (room.leader !== memberId)
700
+ return { ok: false, reason: 'not-leader' };
699
701
  if (hooks.fieldFixed?.(room) === true)
700
702
  return { ok: false, reason: 'historical' };
701
703
  if (on && this.seatsShut(room) !== null)
@@ -747,6 +749,26 @@ export class RoomLobby {
747
749
  this.log({ event: closed ? 'pod-seat-closed' : 'pod-seat-opened', roomId, memberId, seat, size: size() });
748
750
  return { ok: true, room: this.view(room) };
749
751
  }
752
+ /**
753
+ * The leader hands the room's leadership to `targetId`, another member, seated or watching.
754
+ * Passing it to yourself is answered `ok` and changes nothing.
755
+ */
756
+ passLeader(roomId, memberId, targetId) {
757
+ const room = this.#rooms.get(roomId);
758
+ if (room === undefined)
759
+ return { ok: false, reason: 'no-room' };
760
+ if (!isRoomMember(room, memberId))
761
+ return { ok: false, reason: 'not-member' };
762
+ if (room.leader !== memberId)
763
+ return { ok: false, reason: 'not-leader' };
764
+ if (targetId === memberId)
765
+ return { ok: true, room: this.view(room) };
766
+ if (!passRoomLeader(room, targetId))
767
+ return { ok: false, reason: 'target-not-member' };
768
+ this.persist(room);
769
+ this.log({ event: 'leader-passed', roomId, memberId, targetId });
770
+ return { ok: true, room: this.view(room) };
771
+ }
750
772
  /**
751
773
  * The leader removes `targetId` from whatever game seat they hold, to the spectator row.
752
774
  * Idempotent: a target who holds none is still answered `ok`. Never touches membership — they
@@ -51,6 +51,11 @@ export declare function addRoomMember<M extends MemberRow>(room: MembershipRoom<
51
51
  * seat, a series) and persisting the room.
52
52
  */
53
53
  export declare function removeRoomMember<M extends MemberRow>(room: MembershipRoom<M>, id: string): M | undefined;
54
+ /**
55
+ * Hand the room's leadership to the member `to`. Answers false, changing nothing, when `to` is not a
56
+ * member. The caller has checked the hand-off is the current leader's to make, and persists the room.
57
+ */
58
+ export declare function passRoomLeader<M extends MemberRow>(room: MembershipRoom<M>, to: string): boolean;
54
59
  /** `memberId`'s readiness for whatever the room is about to start. */
55
60
  export declare function isMemberReady(room: Pick<MembershipRoom<MemberRow>, 'ledger'>, memberId: string): boolean;
56
61
  /** Sets `memberId`'s readiness. The caller still owns every side effect a readiness change has on ITS game (a pod auto-seat, a tournament lock, …) and persisting the room. */
@@ -57,6 +57,17 @@ export function removeRoomMember(room, id) {
57
57
  room.leader = newLeader;
58
58
  return removed;
59
59
  }
60
+ /**
61
+ * Hand the room's leadership to the member `to`. Answers false, changing nothing, when `to` is not a
62
+ * member. The caller has checked the hand-off is the current leader's to make, and persists the room.
63
+ */
64
+ export function passRoomLeader(room, to) {
65
+ if (!isRoomMember(room, to))
66
+ return false;
67
+ room.ledger.leaderId = to;
68
+ room.leader = to;
69
+ return true;
70
+ }
60
71
  /** `memberId`'s readiness for whatever the room is about to start. */
61
72
  export function isMemberReady(room, memberId) {
62
73
  return isReady(room.ledger, memberId);
@@ -30,7 +30,7 @@ export interface PlatformRoomRecord<G, M extends PlatformMember = PlatformMember
30
30
  id: string;
31
31
  name: string;
32
32
  creator: string;
33
- /** Mirrors `ledger.leaderId`, kept non-null; it moves only when the leader leaves (`membership.ts`). */
33
+ /** Mirrors `ledger.leaderId`, kept non-null; it moves when the leader leaves or hands it on (`membership.ts`). */
34
34
  leader: string;
35
35
  gameType: string;
36
36
  /** A seeded, admin-only room: never swept (`room-list.ts`). */
@@ -96,9 +96,32 @@ function accountOfHeaders(headers) {
96
96
  const id = headers['x-user-id'];
97
97
  return typeof id === 'string' && id !== '' ? id : undefined;
98
98
  }
99
+ /**
100
+ * The `/room` handshake floor — refused HERE, a forged or headerless socket never reaches
101
+ * `connection` at all. `serveRoom`'s own `admit` is called only once a client has CONNECTED and
102
+ * sent `join`; before this existed, that was the one tier check this namespace had, so a socket
103
+ * that simply never sent `join` stayed connected with no refusal ever reaching it (bm1-BS: a
104
+ * headerless `socket.io-client` connect to this namespace succeeded). `gate.ts`'s own
105
+ * `gateSocketIo` cannot cover this either — `io.use` is Socket.IO's shortcut for
106
+ * `io.of('/').use`, the DEFAULT namespace only, never one this file names of its own
107
+ * (`docs/planning/s3-2026-11-17.md` §G.2). `next(new Error('not found'))` is the same refusal
108
+ * shape `gateSocketIo` uses for the default namespace: a `connect_error` on the client, never a
109
+ * reason string that confirms this namespace exists to a caller never meant to reach it.
110
+ */
111
+ function gateRoomHandshake(namespace, minTier, onEvent) {
112
+ namespace.use((socket, next) => {
113
+ if (rankOf(handshakeTier(socket.request.headers)) < rankOf(minTier)) {
114
+ onEvent?.('warn', 'room.refused', { sid: socket.id, gate: 'tier' });
115
+ next(new Error('not found'));
116
+ return;
117
+ }
118
+ next();
119
+ });
120
+ }
99
121
  /** Mount a game's rooms on `io` (see this file's header). */
100
122
  export async function attachServedRoom(io, deps) {
101
123
  const { lobby, people } = deps;
124
+ gateRoomHandshake(io.of(deps.namespace ?? '/room'), deps.minTier, deps.onEvent);
102
125
  const store = createChatHistoryStore({
103
126
  stateDir: deps.stateDir,
104
127
  maxMessages: MAX_MESSAGES_PER_ROOM,
@@ -120,12 +143,13 @@ export async function attachServedRoom(io, deps) {
120
143
  // socket on this same `io`) before any namespace's `connection` fires.
121
144
  const headers = socket.request.headers;
122
145
  // Which gate refused, and the key it refused: a refusal the log cannot explain is one nobody can fix.
146
+ // No 'tier' case here any more: `gateRoomHandshake` above refuses a below-floor socket before
147
+ // it ever reaches `connection`, so nothing that sends `join` at all can be under the floor —
148
+ // one gate for it, not two copies of "sanitize then rank" agreeing by construction.
123
149
  const refuse = (gate) => {
124
150
  deps.onEvent?.('warn', 'room.refused', { sid: socket.id, room_key: join.room_key, gate });
125
151
  return null;
126
152
  };
127
- if (rankOf(handshakeTier(headers)) < rankOf(deps.minTier))
128
- return refuse('tier');
129
153
  const place = placeOfKey(lobby, deps.isMatch, deps.appId, join.room_key, deps.roomIdRe);
130
154
  if (place === null)
131
155
  return refuse('no-place');
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/game-server",
3
- "version": "0.1.23",
4
- "gitHead": "101b951287734a3def291fb2c63eed921b98e65f",
3
+ "version": "0.1.25",
4
+ "gitHead": "7bd6f116fbcfe910127a8ca55b0e23e9b33a84c0",
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.",
@@ -16,9 +16,9 @@
16
16
  "play/remote/"
17
17
  ],
18
18
  "dependencies": {
19
- "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.23",
20
- "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.23",
21
- "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.56",
19
+ "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.25",
20
+ "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.25",
21
+ "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.58",
22
22
  "@wolffm/prefs-client": "npm:@hadoku/prefs-client@^1.1.27",
23
23
  "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.102",
24
24
  "@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.102",