@hadoku/game-server 0.1.249 → 0.1.251

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.
@@ -21,7 +21,7 @@
21
21
  * hook `rooms.ts` passes in — never a second route, never `res.locals`.
22
22
  */
23
23
  import { Router, type Request, type Response } from 'express';
24
- import { type RateLimitConfig } from '@wolffm/rooms-server';
24
+ import type { RateLimitConfig } from '@wolffm/rooms-server';
25
25
  import type { Caller } from '../room/caller.js';
26
26
  import { bodyErrors, type BodySchema } from './request.js';
27
27
  /** The minimal room shape every route here touches; the real `RoomView` satisfies it and rides through untouched as `V`. */
@@ -21,7 +21,6 @@
21
21
  * hook `rooms.ts` passes in — never a second route, never `res.locals`.
22
22
  */
23
23
  import { Router } from 'express';
24
- import { MultiRateLimiter } from '@wolffm/rooms-server';
25
24
  import { isDurableParticipantId } from '@wolffm/rooms-protocol';
26
25
  import { SEATS_OPEN_BEFORE_MS } from '@wolffm/platform-wire/events';
27
26
  import { edgeTierOf, isAdmin } from '../edge-auth.js';
@@ -173,21 +172,17 @@ export function attachRoomCore(api, deps, opts = {}) {
173
172
  const { lobby, wire } = deps;
174
173
  const log = deps.log ?? jsonLogger('cardtable-rooms');
175
174
  const now = deps.now ?? Date.now;
176
- /** A per-caller budget: false once its 429 (with `Retry-After`) is sent. */
177
- const limitOf = (cfg, event, error) => {
178
- const limiter = new MultiRateLimiter(cfg);
179
- return (callerId, res) => {
180
- if (limiter.allow(callerId, 1, now()))
181
- return true;
182
- log({ event, reason: 'rate-limited' });
183
- res.setHeader('Retry-After', String(Math.ceil(cfg.refillIntervalMs / 1000)));
184
- res.status(429).json({ error });
185
- return false;
186
- };
187
- };
188
- const joinLimit = limitOf(deps.joinRateLimit ?? JOIN_RATE_LIMIT, 'room-join-refused', 'too many join attempts; wait a little and try again');
175
+ const joinLimit = perCallerLimit(deps.joinRateLimit ?? JOIN_RATE_LIMIT, 'too many join attempts; wait a little and try again', {
176
+ act: 'room-join',
177
+ now,
178
+ onRefused: () => log({ event: 'room-join-refused', reason: 'rate-limited' }),
179
+ });
189
180
  /** The leader's own limit, spent whether the op succeeds or is refused for any reason but a bad body — a flood of refusals is still a flood. */
190
- const seatOpLimit = limitOf(SEAT_OP_RATE_LIMIT, 'seat-op-refused', 'too many seat changes; wait a little and try again');
181
+ const seatOpLimit = perCallerLimit(SEAT_OP_RATE_LIMIT, 'too many seat changes; wait a little and try again', {
182
+ act: 'seat-op',
183
+ now,
184
+ onRefused: () => log({ event: 'seat-op-refused', reason: 'rate-limited' }),
185
+ });
191
186
  const roomBody = (room, callerId) => {
192
187
  const mine = room.members.find((m) => m.id === callerId);
193
188
  const games = deps.tableGames?.(room);
@@ -240,7 +235,7 @@ export function attachRoomCore(api, deps, opts = {}) {
240
235
  if (body === null)
241
236
  return;
242
237
  const caller = callerOf(req);
243
- if (!lobby.isMember(watchpartyRoomId(body.room), caller.id) && !joinLimit(caller.id, res))
238
+ if (!lobby.isMember(watchpartyRoomId(body.room), caller.id) && !joinLimit(req, res))
244
239
  return;
245
240
  const result = lobby.bindWatchparty(caller, body.room);
246
241
  if (!result.ok)
@@ -284,7 +279,7 @@ export function attachRoomCore(api, deps, opts = {}) {
284
279
  return res.json(roomBody(again.room, caller.id));
285
280
  }
286
281
  }
287
- if (!joinLimit(caller.id, res))
282
+ if (!joinLimit(req, res))
288
283
  return;
289
284
  const result = lobby.join(id, caller, body.password);
290
285
  if (!result.ok) {
@@ -380,7 +375,7 @@ export function attachRoomCore(api, deps, opts = {}) {
380
375
  if (!body.ok)
381
376
  return void res.status(400).json({ error: body.error });
382
377
  const caller = callerOf(req);
383
- if (how.limited && !seatOpLimit(caller.id, res))
378
+ if (how.limited && !seatOpLimit(req, res))
384
379
  return;
385
380
  const id = String(req.params.id);
386
381
  const override = how.leader && deps.operator?.(req) === true;
@@ -59,7 +59,7 @@
59
59
  * server importing UI source is the wrong direction for any app's layering.
60
60
  */
61
61
  import type { Server as SocketIOServer } from 'socket.io';
62
- import type { PresenceTracker } from '@wolffm/rooms-server';
62
+ import { type PresenceTracker, type RateLimitConfig } from '@wolffm/rooms-server';
63
63
  import { type RoomChatMessage } from '@wolffm/rooms-server/chat';
64
64
  import { type ServedRoom } from '@wolffm/rooms-server/room';
65
65
  import type { Look } from '@wolffm/platform-wire/look';
@@ -76,6 +76,12 @@ export declare const CHAT_RETENTION_MS: number;
76
76
  * still enforces the 90 days it was asked for.
77
77
  */
78
78
  export declare const CHAT_WIPE_DELAY_MS: number;
79
+ /** One person's chat lines: 3 a second, watchparty's limit for the same chat on the same `serveRoom`. */
80
+ export declare const CHAT_RATE_LIMIT: RateLimitConfig;
81
+ /** One person's reactions: 8 in 2 s, watchparty's; a bucket of their own, so reacting never costs a line. */
82
+ export declare const REACT_RATE_LIMIT: RateLimitConfig;
83
+ /** One person's name and character changes: 5 in 10 s, watchparty's, room for a join's two and a few corrections. */
84
+ export declare const IDENTITY_RATE_LIMIT: RateLimitConfig;
79
85
  /** The minimal room-view shape this file touches, whatever the game. The real `PlatformRoomView` (and Magic's `RoomView`) satisfy it. */
80
86
  export interface ServeRoomView {
81
87
  id: string;
@@ -59,12 +59,14 @@
59
59
  * server importing UI source is the wrong direction for any app's layering.
60
60
  */
61
61
  import { participantHandle } from '@wolffm/rooms-protocol';
62
+ import { MultiRateLimiter } from '@wolffm/rooms-server';
62
63
  import { createChatHistoryStore } from '@wolffm/rooms-server/chat';
63
64
  import { serveRoom } from '@wolffm/rooms-server/room';
64
65
  import { headerValue } from '@wolffm/service-kernel/auth';
65
66
  import { rankOf } from '../edge-auth.js';
66
67
  import { timerDelay } from '../timers.js';
67
68
  import { applyPerson } from '../people.js';
69
+ import { callerContext, report } from '../telemetry.js';
68
70
  import { handshakeEdgeTier, handshakeTier } from './socket-auth.js';
69
71
  import { roomAdmits } from './tier-floor.js';
70
72
  import { identityFromHeaders } from './identity.js';
@@ -84,6 +86,12 @@ export const CHAT_RETENTION_MS = 90 * 24 * 60 * 60 * 1000;
84
86
  * still enforces the 90 days it was asked for.
85
87
  */
86
88
  export const CHAT_WIPE_DELAY_MS = timerDelay(CHAT_RETENTION_MS);
89
+ /** One person's chat lines: 3 a second, watchparty's limit for the same chat on the same `serveRoom`. */
90
+ export const CHAT_RATE_LIMIT = { capacity: 3, refillAmount: 3, refillIntervalMs: 1_000 };
91
+ /** One person's reactions: 8 in 2 s, watchparty's; a bucket of their own, so reacting never costs a line. */
92
+ export const REACT_RATE_LIMIT = { capacity: 8, refillAmount: 8, refillIntervalMs: 2_000 };
93
+ /** One person's name and character changes: 5 in 10 s, watchparty's, room for a join's two and a few corrections. */
94
+ export const IDENTITY_RATE_LIMIT = { capacity: 5, refillAmount: 5, refillIntervalMs: 10_000 };
87
95
  /**
88
96
  * `<appId>-<id>` → the place it names, or null when it is not one of ours or names nothing live.
89
97
  * A table's key is `<roomId>-<tableId>`, or `<roomId>-<matchId>` when the screen's copy of the
@@ -146,7 +154,20 @@ export async function attachServedRoom(io, deps) {
146
154
  // lobby room's joined connections by socket id.
147
155
  const lobbyRoomOf = new WeakMap();
148
156
  const joined = new Map();
149
- gateRoomHandshake(io.of(deps.namespace ?? '/room'), deps.minTier, deps.onEvent);
157
+ const nsp = io.of(deps.namespace ?? '/room');
158
+ gateRoomHandshake(nsp, deps.minTier, deps.onEvent);
159
+ // Each limit is the person's (`admit`'s key), so a second tab gains no budget. serveRoom logs its own
160
+ // line for every refusal; telemetry hears of it here.
161
+ const limit = (cfg, act) => {
162
+ const limiter = new MultiRateLimiter(cfg);
163
+ return (socket) => {
164
+ if (socket === undefined || limiter.allow(identityFromHeaders(socket.request.headers, socket.id)))
165
+ return true;
166
+ report('rate-limited', { act, ...callerContext(socket.request.headers) });
167
+ return false;
168
+ };
169
+ };
170
+ const [chatLimit, reactLimit] = [limit(CHAT_RATE_LIMIT, 'room-chat'), limit(REACT_RATE_LIMIT, 'room-react')];
150
171
  const store = createChatHistoryStore({
151
172
  stateDir: deps.stateDir,
152
173
  maxMessages: MAX_MESSAGES_PER_ROOM,
@@ -163,6 +184,9 @@ export async function attachServedRoom(io, deps) {
163
184
  presence: deps.presence,
164
185
  ...(deps.namespace === undefined ? {} : { namespace: deps.namespace }),
165
186
  ...(deps.onEvent === undefined ? {} : { onEvent: deps.onEvent }),
187
+ allow: (socketId) => chatLimit(nsp.sockets.get(socketId)),
188
+ allowReact: (socketId) => reactLimit(nsp.sockets.get(socketId)),
189
+ allowIdentity: limit(IDENTITY_RATE_LIMIT, 'room-rename'),
166
190
  admit(socket, join) {
167
191
  // Provenance is sanitized engine-wide (`gate.ts`'s `gateSocketIo`, installed by the draft
168
192
  // socket on this same `io`) before any namespace's `connection` fires.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/game-server",
3
- "version": "0.1.249",
4
- "gitHead": "9c2dac66d560368dd8d4d53d05f72201ea7ddcb6",
3
+ "version": "0.1.251",
4
+ "gitHead": "36543654899f3773281c5233f333fc0376496c9e",
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,12 +16,12 @@
16
16
  "play/remote/"
17
17
  ],
18
18
  "dependencies": {
19
- "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.249",
20
- "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.249",
21
- "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.282",
19
+ "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.251",
20
+ "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.251",
21
+ "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.284",
22
22
  "@wolffm/prefs-client": "npm:@hadoku/prefs-client@^1.2.4",
23
- "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.156",
24
- "@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.156",
23
+ "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.157",
24
+ "@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.157",
25
25
  "express": "^5.3.0",
26
26
  "socket.io": "^4.8.4",
27
27
  "zod": "^4.6.7"