keryx 0.48.0 → 0.48.2

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keryx",
3
- "version": "0.48.0",
3
+ "version": "0.48.2",
4
4
  "module": "index.ts",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/servers/web.ts CHANGED
@@ -131,6 +131,13 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
131
131
  url: string = "";
132
132
  /** Per-connection message rate tracking (keyed by connection id). */
133
133
  private wsRateMap = new Map<string, { count: number; windowStart: number }>();
134
+ /**
135
+ * Tail of each connection's queue of subscribe/unsubscribe frames (keyed by connection id).
136
+ * Bun doesn't wait for one `message` callback to finish before calling the next, so channel
137
+ * operations are chained here to apply in the order the client sent them. The stored
138
+ * promise never rejects.
139
+ */
140
+ private wsChannelOpQueue = new Map<string, Promise<void>>();
134
141
  /** Set to true when the server is shutting down; rejects new WS upgrades. */
135
142
  private shuttingDown = false;
136
143
 
@@ -419,6 +426,17 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
419
426
  /**
420
427
  * Called when a WebSocket message arrives. Parses JSON, enforces per-connection rate limiting,
421
428
  * and dispatches to action, subscribe, or unsubscribe handlers based on `messageType`.
429
+ *
430
+ * Bun invokes this for each frame without waiting for the previous call to settle, so frames
431
+ * are ordered per connection: subscribe and unsubscribe frames run one at a time, in the order
432
+ * they were sent. An action frame waits for the channel operations sent before it, but doesn't
433
+ * hold up later frames, so actions (including long-running streams) still run concurrently.
434
+ *
435
+ * @param ws - The Bun WebSocket the frame arrived on. Its `data` identifies the {@link Connection}.
436
+ * @param message - The raw frame. Expected to be a JSON object with a `messageType` of
437
+ * `"action"`, `"subscribe"`, or `"unsubscribe"`; anything else gets an error frame back.
438
+ * @throws {TypedError} When no connection is registered for the socket, or rethrown from an
439
+ * `onMessage` hook.
422
440
  */
423
441
  async handleWebSocketConnectionMessage(
424
442
  ws: ServerWebSocket,
@@ -464,13 +482,58 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
464
482
  }
465
483
  }
466
484
 
485
+ // Parse up front (synchronously, in arrival order) so we know whether this frame
486
+ // joins the connection's channel-op queue. Parse errors are reported after the hooks run.
487
+ let parsedMessage: any;
488
+ let parseError: unknown;
489
+ try {
490
+ parsedMessage = JSON.parse(message.toString());
491
+ } catch (e) {
492
+ parseError = e;
493
+ }
494
+ const messageType = parsedMessage?.["messageType"];
495
+ const isChannelOp =
496
+ messageType === "subscribe" || messageType === "unsubscribe";
497
+
498
+ const previous = this.wsChannelOpQueue.get(connection.id);
499
+ const handled = this.processWebSocketMessage(
500
+ connection,
501
+ ws,
502
+ message,
503
+ parsedMessage,
504
+ parseError,
505
+ previous,
506
+ );
507
+ if (isChannelOp) {
508
+ this.wsChannelOpQueue.set(
509
+ connection.id,
510
+ handled.catch(() => {}),
511
+ );
512
+ }
513
+ await handled;
514
+ }
515
+
516
+ /**
517
+ * Runs one inbound WebSocket frame after the connection's earlier channel operations settle:
518
+ * the `onMessage` hooks, then the action / subscribe / unsubscribe handler.
519
+ */
520
+ private async processWebSocketMessage(
521
+ connection: Connection,
522
+ ws: ServerWebSocket,
523
+ message: string | Buffer,
524
+ parsedMessage: any,
525
+ parseError: unknown,
526
+ previous: Promise<void> | undefined,
527
+ ) {
528
+ if (previous) await previous;
529
+
467
530
  for (const hook of api.hooks.ws.onMessageHooks) {
468
531
  await hook(connection, message);
469
532
  }
470
533
 
471
534
  let messageId: unknown;
472
535
  try {
473
- const parsedMessage = JSON.parse(message.toString());
536
+ if (parseError) throw parseError;
474
537
  messageId = parsedMessage["messageId"];
475
538
  if (parsedMessage["messageType"] === "action") {
476
539
  await handleWebsocketAction(connection, ws, parsedMessage);
@@ -510,6 +573,11 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
510
573
  );
511
574
  if (!connection) return;
512
575
 
576
+ // Let in-flight subscribe/unsubscribe frames finish so presence cleanup sees the final set
577
+ const pendingChannelOps = this.wsChannelOpQueue.get(connection.id);
578
+ if (pendingChannelOps) await pendingChannelOps;
579
+ this.wsChannelOpQueue.delete(connection.id);
580
+
513
581
  for (const hook of api.hooks.ws.onDisconnectHooks) {
514
582
  await hook(connection);
515
583
  }
@@ -605,14 +673,23 @@ export class WebServer extends Server<ReturnType<typeof Bun.serve>> {
605
673
  rawBody,
606
674
  });
607
675
  } catch (e) {
608
- if (
609
- e instanceof TypedError &&
610
- e.message.startsWith("Payload Too Large")
611
- ) {
612
- connection.destroy();
613
- return { response: buildError(connection, e, 413, requestOrigin) };
614
- }
615
- throw e;
676
+ // An oversized or unparseable body is the client's fault: answer it with
677
+ // the JSON error envelope (and CORS headers) rather than letting it
678
+ // escape to Bun's default 500 handler, and never leak the connection.
679
+ connection.destroy();
680
+ const error =
681
+ e instanceof TypedError
682
+ ? e
683
+ : new TypedError({
684
+ message: `cannot parse request body: ${e}`,
685
+ type: ErrorType.CONNECTION_ACTION_PARAM_VALIDATION,
686
+ cause: e,
687
+ });
688
+ const status = error.message.startsWith("Payload Too Large") ? 413 : 400;
689
+ return {
690
+ response: buildError(connection, error, status, requestOrigin),
691
+ actionName: actionName ?? undefined,
692
+ };
616
693
  }
617
694
 
618
695
  const { response, error } = await connection.act(
@@ -178,8 +178,11 @@ export type ParseRequestParamsOptions = {
178
178
  * unread — nothing is consumed off `req`, so a later reader (typically the
179
179
  * action, via `connection.rawRequest`) still sees the bytes exactly as sent.
180
180
  * @returns A plain object containing all merged parameters.
181
- * @throws {TypedError} With type {@link ErrorType.CONNECTION_ACTION_RUN} when a
182
- * JSON body cannot be parsed, or when the body exceeds
181
+ * @throws {TypedError} With type
182
+ * {@link ErrorType.CONNECTION_ACTION_PARAM_VALIDATION} when a JSON or form
183
+ * body cannot be parsed (an empty or malformed JSON body, or one that is not
184
+ * a JSON object), or with type {@link ErrorType.CONNECTION_ACTION_RUN} and a
185
+ * "Payload Too Large" message when the body exceeds
183
186
  * {@link config.server.web.maxBodySize}.
184
187
  */
185
188
  export async function parseRequestParams(
@@ -203,23 +206,33 @@ export async function parseRequestParams(
203
206
  const contentType = options?.rawBody ? null : baseMediaType(req);
204
207
 
205
208
  if (req.method !== "GET" && contentType === "application/json") {
209
+ // Use streaming reader that aborts early if the body exceeds the
210
+ // configured limit — never allocates the full oversized payload.
211
+ const text = await readBodyWithLimit(req);
212
+ let bodyContent: unknown;
206
213
  try {
207
- // Use streaming reader that aborts early if the body exceeds the
208
- // configured limit — never allocates the full oversized payload.
209
- const text = await readBodyWithLimit(req);
210
- const bodyContent = JSON.parse(text) as Record<string, unknown>;
211
- // Merge JSON body directly — preserves types (objects, arrays, booleans, numbers)
212
- for (const [key, value] of Object.entries(bodyContent)) {
213
- params[key] = value;
214
- }
214
+ bodyContent = JSON.parse(text);
215
215
  } catch (e) {
216
- if (e instanceof TypedError) throw e;
217
216
  throw new TypedError({
218
217
  message: `cannot parse request body: ${e}`,
219
- type: ErrorType.CONNECTION_ACTION_RUN,
218
+ type: ErrorType.CONNECTION_ACTION_PARAM_VALIDATION,
220
219
  cause: e,
221
220
  });
222
221
  }
222
+ if (
223
+ bodyContent === null ||
224
+ typeof bodyContent !== "object" ||
225
+ Array.isArray(bodyContent)
226
+ ) {
227
+ throw new TypedError({
228
+ message: "cannot parse request body: a JSON body must be an object",
229
+ type: ErrorType.CONNECTION_ACTION_PARAM_VALIDATION,
230
+ });
231
+ }
232
+ // Merge JSON body directly — preserves types (objects, arrays, booleans, numbers)
233
+ for (const [key, value] of Object.entries(bodyContent)) {
234
+ params[key] = value;
235
+ }
223
236
  } else if (
224
237
  req.method !== "GET" &&
225
238
  (contentType === "multipart/form-data" ||
@@ -234,7 +247,13 @@ export async function parseRequestParams(
234
247
  await readBodyWithLimit(req.clone() as Request);
235
248
  }
236
249
 
237
- const f = await req.formData();
250
+ const f = await req.formData().catch((e: unknown) => {
251
+ throw new TypedError({
252
+ message: `cannot parse request body: ${e}`,
253
+ type: ErrorType.CONNECTION_ACTION_PARAM_VALIDATION,
254
+ cause: e,
255
+ });
256
+ });
238
257
  f.forEach((value, key) => appendParam(params, key, value));
239
258
  }
240
259