Skip to content

Add circular-reference guard to MessageRouter.sortObjectKeys #188

Closed

Description

@VikramAditya33

MessageRouter.sortObjectKeys and sortValue recurse into objects without tracking visited nodes. A circular reference in a message pattern or event object causes infinite recursion and a stack overflow.

MetadataScanner.sortObjectKeys already protects against this with a WeakSet tracker. MessageRouter should do the same.

Affected Code

src/websocket/routing/message-router.ts lines 167-187:

private sortObjectKeys(obj: Record<string, unknown>): Record<string, unknown> {
  const sorted: Record<string, unknown> = {};
  for (const key of Object.keys(obj).sort()) {
    sorted[key] = this.sortValue(obj[key]);
  }
  return sorted;
}

private sortValue(value: unknown): unknown {
  if (value === null || typeof value !== 'object') {
    return value;
  }
  if (Array.isArray(value)) {
    return value.map((item) => this.sortValue(item));
  }
  return this.sortObjectKeys(value as Record<string, unknown>);
}

Proposed Fix

Add a seen WeakSet parameter (mirroring MetadataScanner):

private sortObjectKeys(
  obj: Record<string, unknown>,
  seen = new WeakSet<object>()
): Record<string, unknown> {
  if (seen.has(obj)) {
    throw new Error('Circular reference detected in message pattern');
  }
  seen.add(obj);

  const sorted: Record<string, unknown> = {};
  for (const key of Object.keys(obj).sort()) {
    sorted[key] = this.sortValue(obj[key], seen);
  }
  seen.delete(obj);
  return sorted;
}

private sortValue(value: unknown, seen: WeakSet<object>): unknown {
  if (value === null || typeof value !== 'object') {
    return value;
  }
  if (Array.isArray(value)) {
    return value.map((item) => this.sortValue(item, seen));
  }
  return this.sortObjectKeys(value as Record<string, unknown>, seen);
}

seen.delete(obj) allows the same object to appear multiple times in non-circular branches (e.g., shared sub-objects), matching MetadataScanner behavior.

Sequence

Unify sortObjectKeys implementations in MetadataScanner and MessageRouter. See #187

Description

Both MetadataScanner and MessageRouter maintain their own sortObjectKeys implementations for stable JSON serialization of message patterns. They have diverged in two ways:

  1. Array handling: MessageRouter recursively sorts objects inside arrays (via sortValue), but MetadataScanner skips arrays entirely.
  2. Circular-reference guard: MetadataScanner tracks visited objects with a WeakSet, but MessageRouter has no protection and will stack-overflow on circular references.

This inconsistency causes routing failures when message patterns contain objects nested inside arrays with keys in different orders.

Impact

  • Patterns like { cmd: 'batch', items: [{ b: 1, a: 2 }] } registered via MetadataScanner produce a different key than the same pattern routed via MessageRouter.
  • UwsAdapter.handleDecoratorBasedMessage uses messageRouter.hasHandler() (MessageRouter's key) and findHandlerForEvent() (MetadataScanner's key) in the same flow, so they can disagree and drop valid messages.

Sequence / Implementation Guide

Fix both problems #187 in a single PR by extracting a shared helper. Do not fix one file and leave the other, that perpetuates the duplication.

Step 1: Create shared utility

Create src/websocket/routing/pattern-key.ts:

/**
 * Recursively sorts object keys for stable JSON serialization.
 * Handles nested objects, arrays, and primitives.
 * Throws on circular references.
 */
export function sortObjectKeys(
  obj: Record<string, unknown>,
  seen = new WeakSet<object>()
): Record<string, unknown> {
  if (seen.has(obj)) {
    throw new Error('Circular reference detected in message pattern');
  }
  seen.add(obj);

  const sorted: Record<string, unknown> = {};
  for (const key of Object.keys(obj).sort()) {
    sorted[key] = sortValue(obj[key], seen);
  }
  seen.delete(obj);
  return sorted;
}

function sortValue(value: unknown, seen: WeakSet<object>): unknown {
  if (value === null || typeof value !== 'object') {
    return value;
  }
  if (Array.isArray(value)) {
    return value.map((item) => sortValue(item, seen));
  }
  return sortObjectKeys(value as Record<string, unknown>, seen);
}

Step 2: Replace private methods in both files

In MetadataScanner:

  • Remove the private sortObjectKeys method.
  • Import and use sortObjectKeys from ./pattern-key.

In MessageRouter:

  • Remove the private sortObjectKeys and sortValue methods.
  • Import and use sortObjectKeys from ./pattern-key.

Step 3: Add/update tests

  • metadata-scanner.spec.ts: Add test for object patterns containing arrays with out-of-order keys (matching message-router.spec.ts line 172).
  • message-router.spec.ts: Add test for circular-reference rejection.
  • pattern-key.ts: Add its own unit tests for edge cases (nested arrays, shared sub-objects, circular refs).

Activity

  1. added this to the v2.1.0 milestone on May 23, 2026
  2. added
    bug
    CRITICAL
    on May 23, 2026
  3. ambikeesshh commented on May 30, 2026

    @ambikeesshh
    Contributor

    fixed in #201

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

CRITICALbug

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions