@terreno/api 57.16.2 → 57.18.0

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.
Files changed (184) hide show
  1. package/dist/actions.d.ts +26 -3
  2. package/dist/actions.js +102 -16
  3. package/dist/api.d.ts +7 -0
  4. package/dist/api.js +59 -3
  5. package/dist/auth.d.ts +28 -4
  6. package/dist/auth.js +140 -15
  7. package/dist/authRecovery.d.ts +31 -0
  8. package/dist/authRecovery.js +86 -6
  9. package/dist/betterAuth.d.ts +86 -0
  10. package/dist/betterAuthApp.d.ts +17 -0
  11. package/dist/betterAuthApp.js +12 -1
  12. package/dist/betterAuthOAuthHandoff.d.ts +24 -0
  13. package/dist/betterAuthOAuthHandoff.js +305 -0
  14. package/dist/betterAuthSetup.d.ts +37 -2
  15. package/dist/betterAuthSetup.js +304 -24
  16. package/dist/expressServer.d.ts +16 -0
  17. package/dist/expressServer.js +61 -14
  18. package/dist/githubAuth.d.ts +9 -0
  19. package/dist/githubAuth.js +230 -31
  20. package/dist/index.d.ts +9 -1
  21. package/dist/index.js +27 -3
  22. package/dist/mcp/actionTools.d.ts +4 -0
  23. package/dist/mcp/actionTools.js +158 -0
  24. package/dist/mcp/auth.d.ts +30 -0
  25. package/dist/mcp/auth.js +83 -28
  26. package/dist/mcp/createMCPRequest.d.ts +5 -1
  27. package/dist/mcp/createMCPRequest.js +3 -3
  28. package/dist/mcp/handlers.d.ts +3 -0
  29. package/dist/mcp/handlers.js +43 -27
  30. package/dist/mcp/oauth.d.ts +14 -0
  31. package/dist/mcp/oauth.js +618 -0
  32. package/dist/mcp/oauthMetadata.d.ts +89 -0
  33. package/dist/mcp/oauthMetadata.js +137 -0
  34. package/dist/mcp/registry.d.ts +5 -0
  35. package/dist/mcp/registry.js +9 -1
  36. package/dist/mcp/server.d.ts +6 -0
  37. package/dist/mcp/server.js +44 -7
  38. package/dist/mcp/serviceTokens.js +12 -2
  39. package/dist/mcp/toolExecution.d.ts +12 -0
  40. package/dist/mcp/toolExecution.js +60 -0
  41. package/dist/mcp/toolGenerator.d.ts +4 -1
  42. package/dist/mcp/toolGenerator.js +26 -60
  43. package/dist/mcp/types.d.ts +4 -4
  44. package/dist/models/mcpOAuthAuthorization.d.ts +2 -0
  45. package/dist/models/mcpOAuthAuthorization.js +86 -0
  46. package/dist/models/mcpOAuthClient.d.ts +2 -0
  47. package/dist/models/mcpOAuthClient.js +42 -0
  48. package/dist/models/mcpOAuthRevokedFamily.d.ts +2 -0
  49. package/dist/models/mcpOAuthRevokedFamily.js +36 -0
  50. package/dist/models/mcpOAuthToken.d.ts +12 -0
  51. package/dist/models/mcpOAuthToken.js +159 -0
  52. package/dist/models/mcpServiceToken.d.ts +1 -0
  53. package/dist/models/mcpServiceToken.js +21 -4
  54. package/dist/permissions.d.ts +7 -0
  55. package/dist/permissions.js +18 -1
  56. package/dist/rateLimit/policies.d.ts +4 -0
  57. package/dist/rateLimit/policies.js +46 -7
  58. package/dist/rbac/access.js +1 -0
  59. package/dist/rbac/membershipOrgAdminSource.d.ts +4 -0
  60. package/dist/rbac/membershipOrgAdminSource.js +5 -0
  61. package/dist/rbac/modelRouterAccess.d.ts +7 -1
  62. package/dist/rbac/modelRouterAccess.js +37 -24
  63. package/dist/rbac/realtimeAccess.js +17 -3
  64. package/dist/rbac/resolve.js +66 -9
  65. package/dist/rbac/roleManager.js +60 -5
  66. package/dist/rbac/roleModel.js +1 -1
  67. package/dist/rbac/statements.d.ts +1 -1
  68. package/dist/rbac/statements.js +13 -1
  69. package/dist/rbac/types.d.ts +12 -0
  70. package/dist/rbac/userWriteGuards.d.ts +50 -0
  71. package/dist/rbac/userWriteGuards.js +156 -0
  72. package/dist/realtime/changeStreamWatcher.d.ts +4 -1
  73. package/dist/realtime/changeStreamWatcher.js +157 -73
  74. package/dist/realtime/queryMatcher.d.ts +3 -0
  75. package/dist/realtime/queryMatcher.js +25 -10
  76. package/dist/realtime/realtimeApp.d.ts +16 -1
  77. package/dist/realtime/realtimeApp.js +76 -8
  78. package/dist/realtime/socketAuth.d.ts +17 -6
  79. package/dist/realtime/socketAuth.js +77 -16
  80. package/dist/realtime/types.d.ts +8 -5
  81. package/dist/requestContext.d.ts +22 -0
  82. package/dist/requestContext.js +22 -1
  83. package/dist/seedRunner.js +3 -1
  84. package/dist/sortFields.d.ts +33 -0
  85. package/dist/sortFields.js +55 -0
  86. package/dist/sync/executors.js +140 -2
  87. package/dist/sync/models.d.ts +2 -0
  88. package/dist/sync/models.js +5 -0
  89. package/dist/sync/mutationHandler.js +70 -7
  90. package/dist/sync/routes.js +4 -2
  91. package/dist/sync/syncSeqPlugin.js +6 -5
  92. package/dist/terrenoApp.d.ts +14 -0
  93. package/dist/terrenoApp.js +21 -6
  94. package/dist/types/mcpOAuth.d.ts +101 -0
  95. package/dist/types/mcpOAuth.js +2 -0
  96. package/dist/types/mcpServiceToken.d.ts +8 -0
  97. package/package.json +3 -3
  98. package/src/actions.test.ts +118 -0
  99. package/src/actions.ts +139 -17
  100. package/src/api.arrayOperations.test.ts +78 -0
  101. package/src/api.test.ts +36 -0
  102. package/src/api.ts +76 -4
  103. package/src/auth.test.ts +521 -3
  104. package/src/auth.ts +171 -17
  105. package/src/authRecovery.test.ts +99 -0
  106. package/src/authRecovery.ts +117 -5
  107. package/src/authVerification.test.ts +3 -3
  108. package/src/betterAuth.ts +104 -1
  109. package/src/betterAuthApp.test.ts +634 -1
  110. package/src/betterAuthApp.ts +28 -0
  111. package/src/betterAuthOAuthHandoff.test.ts +946 -0
  112. package/src/betterAuthOAuthHandoff.ts +375 -0
  113. package/src/betterAuthSetup.test.ts +393 -4
  114. package/src/betterAuthSetup.ts +402 -29
  115. package/src/expressServer.test.ts +93 -0
  116. package/src/expressServer.ts +81 -14
  117. package/src/githubAuth.test.ts +448 -6
  118. package/src/githubAuth.ts +276 -34
  119. package/src/index.ts +35 -1
  120. package/src/mcp/actionTools.test.ts +498 -0
  121. package/src/mcp/actionTools.ts +220 -0
  122. package/src/mcp/auth.test.ts +114 -1
  123. package/src/mcp/auth.ts +122 -35
  124. package/src/mcp/createMCPRequest.ts +8 -2
  125. package/src/mcp/handlers.test.ts +27 -0
  126. package/src/mcp/handlers.ts +21 -6
  127. package/src/mcp/oauth.test.ts +1026 -0
  128. package/src/mcp/oauth.ts +798 -0
  129. package/src/mcp/oauthMetadata.ts +234 -0
  130. package/src/mcp/registry.ts +11 -0
  131. package/src/mcp/server.ts +54 -14
  132. package/src/mcp/serviceTokens.ts +16 -3
  133. package/src/mcp/toolExecution.ts +67 -0
  134. package/src/mcp/toolGenerator.ts +27 -83
  135. package/src/mcp/types.ts +4 -4
  136. package/src/models/mcpOAuthAuthorization.ts +97 -0
  137. package/src/models/mcpOAuthClient.ts +49 -0
  138. package/src/models/mcpOAuthRevokedFamily.ts +47 -0
  139. package/src/models/mcpOAuthToken.test.ts +82 -0
  140. package/src/models/mcpOAuthToken.ts +195 -0
  141. package/src/models/mcpServiceToken.ts +26 -2
  142. package/src/permissions.ts +17 -0
  143. package/src/rateLimit/policies.ts +54 -10
  144. package/src/rateLimit/rateLimit.test.ts +41 -0
  145. package/src/rbac/access.ts +1 -0
  146. package/src/rbac/membershipOrgAdminSource.ts +5 -0
  147. package/src/rbac/modelRouterAccess.ts +40 -23
  148. package/src/rbac/realtimeAccess.test.ts +43 -0
  149. package/src/rbac/realtimeAccess.ts +23 -3
  150. package/src/rbac/resolve.test.ts +179 -1
  151. package/src/rbac/resolve.ts +78 -9
  152. package/src/rbac/roleManager.test.ts +132 -0
  153. package/src/rbac/roleManager.ts +69 -5
  154. package/src/rbac/roleModel.ts +1 -1
  155. package/src/rbac/statements.ts +14 -1
  156. package/src/rbac/types.ts +12 -0
  157. package/src/rbac/userWriteGuards.test.ts +407 -0
  158. package/src/rbac/userWriteGuards.ts +185 -0
  159. package/src/realtime/changeStreamWatcher.ts +203 -75
  160. package/src/realtime/queryMatcher.ts +30 -13
  161. package/src/realtime/realtime.test.ts +132 -0
  162. package/src/realtime/realtimeApp.ts +94 -10
  163. package/src/realtime/realtimeAppSetup.test.ts +282 -1
  164. package/src/realtime/socketAuth.test.ts +140 -8
  165. package/src/realtime/socketAuth.ts +90 -19
  166. package/src/realtime/types.ts +8 -5
  167. package/src/requestContext.ts +52 -1
  168. package/src/requestCredential.test.ts +89 -0
  169. package/src/seedRunner.test.ts +21 -0
  170. package/src/seedRunner.ts +3 -1
  171. package/src/sortFields.ts +69 -0
  172. package/src/sync/executors.test.ts +382 -3
  173. package/src/sync/executors.ts +179 -4
  174. package/src/sync/models.ts +8 -0
  175. package/src/sync/mutationHandler.test.ts +166 -2
  176. package/src/sync/mutationHandler.ts +97 -5
  177. package/src/sync/routes.ts +4 -2
  178. package/src/sync/syncFrontier.test.ts +11 -0
  179. package/src/sync/syncPhaseC.test.ts +18 -0
  180. package/src/sync/syncSeqPlugin.ts +6 -5
  181. package/src/sync/syncSocket.test.ts +92 -0
  182. package/src/terrenoApp.ts +36 -21
  183. package/src/types/mcpOAuth.ts +129 -0
  184. package/src/types/mcpServiceToken.ts +6 -1
@@ -339,6 +339,9 @@ export const serializeDoc = async (
339
339
  return ensureApiId(maskedFallback);
340
340
  };
341
341
 
342
+ /** Returned by a `buildPayload` callback to send nothing to that socket. */
343
+ const SKIP_EMISSION = Symbol("skipEmission");
344
+
342
345
  /**
343
346
  * Generalized authorized-room emitter: iterates the sockets in `room`, runs the per-socket
344
347
  * read-permission check against `fullDocument`, builds the payload per socket (so
@@ -361,7 +364,10 @@ export const emitPayloadToAuthorizedRoom = async ({
361
364
  eventName: string;
362
365
  entry: AuthorizedEmitEntry;
363
366
  fullDocument: Record<string, unknown> | undefined;
364
- /** Build the per-socket payload; a throw drops the emission for that socket only. */
367
+ /**
368
+ * Build the per-socket payload; a throw drops the emission for that socket only, and
369
+ * returning SKIP_EMISSION sends nothing to it.
370
+ */
365
371
  buildPayload: (user: User | undefined) => Promise<unknown> | unknown;
366
372
  logDebug: (msg: string) => void;
367
373
  }): Promise<void> => {
@@ -384,7 +390,10 @@ export const emitPayloadToAuthorizedRoom = async ({
384
390
  continue;
385
391
  }
386
392
  if (adminDecision === "allow") {
387
- socket.emit(eventName, await buildPayload(user));
393
+ const adminPayload = await buildPayload(user);
394
+ if (adminPayload !== SKIP_EMISSION) {
395
+ socket.emit(eventName, adminPayload);
396
+ }
388
397
  continue;
389
398
  }
390
399
  }
@@ -394,7 +403,11 @@ export const emitPayloadToAuthorizedRoom = async ({
394
403
  continue;
395
404
  }
396
405
 
397
- socket.emit(eventName, await buildPayload(user));
406
+ const payload = await buildPayload(user);
407
+ if (payload === SKIP_EMISSION) {
408
+ continue;
409
+ }
410
+ socket.emit(eventName, payload);
398
411
  } catch (error) {
399
412
  logger.error(
400
413
  `[realtime] Failed to emit ${eventName} for ${entry.modelName} to socket ${socket.id}: ${error}`
@@ -429,6 +442,167 @@ export const emitToAuthorizedRoom = async (
429
442
  room,
430
443
  });
431
444
 
445
+ /**
446
+ * Query-room fan-out for routers with RBAC field views. Each recipient's match is evaluated
447
+ * against the document as masked for that recipient, so a field hidden from them cannot
448
+ * decide whether they receive a create, update, or delete.
449
+ */
450
+ const emitMaskedQueryRoomEvent = async ({
451
+ io,
452
+ queryRoom,
453
+ event,
454
+ entry,
455
+ fullDocument,
456
+ query,
457
+ logDebug,
458
+ }: {
459
+ io: Server;
460
+ queryRoom: string;
461
+ event: RealtimeEvent;
462
+ entry: RealtimeRegistryEntry;
463
+ fullDocument: Record<string, unknown>;
464
+ query: Record<string, unknown>;
465
+ logDebug: (msg: string) => void;
466
+ }): Promise<void> =>
467
+ emitPayloadToAuthorizedRoom({
468
+ buildPayload: async (user) => {
469
+ const masked = await maskRealtimeDocument(entry, user, fullDocument, "read");
470
+ const matches =
471
+ typeof masked === "object" &&
472
+ masked !== null &&
473
+ !Array.isArray(masked) &&
474
+ matchesQuery(masked as Record<string, unknown>, query);
475
+ let method: RealtimeEvent["method"] | undefined;
476
+ if (event.method === "update") {
477
+ method = matches ? "update" : "delete";
478
+ } else if (matches) {
479
+ method = event.method;
480
+ }
481
+ if (!method) {
482
+ return SKIP_EMISSION;
483
+ }
484
+ const data = await serializeDoc(entry, fullDocument, method, user);
485
+ return {...event, data, method};
486
+ },
487
+ entry,
488
+ eventName: "sync",
489
+ fullDocument,
490
+ io,
491
+ logDebug,
492
+ room: queryRoom,
493
+ });
494
+
495
+ /** Fan one change out to one query room. */
496
+ const emitToQueryRoom = async ({
497
+ io,
498
+ queryRoom,
499
+ query,
500
+ event,
501
+ fullDocument,
502
+ entry,
503
+ hasFieldViews,
504
+ isOwnerStrategy,
505
+ logDebug,
506
+ }: {
507
+ io: Server;
508
+ queryRoom: string;
509
+ query: Record<string, unknown>;
510
+ event: RealtimeEvent;
511
+ fullDocument: Record<string, unknown> | undefined;
512
+ entry?: RealtimeRegistryEntry;
513
+ hasFieldViews: boolean;
514
+ isOwnerStrategy: boolean;
515
+ logDebug: (msg: string) => void;
516
+ }): Promise<void> => {
517
+ if (event.method === "delete") {
518
+ if (!fullDocument) {
519
+ // Hard delete with no document context. For owner-strategy collections we can't
520
+ // tell which query rooms belong to the owner without leaking activity to others,
521
+ // so skip query fanout entirely — subscribers will reconcile on next fetch.
522
+ if (isOwnerStrategy) {
523
+ logDebug(
524
+ `[realtime] Skipping hard delete fanout to ${queryRoom} (owner strategy, no fullDocument)`
525
+ );
526
+ return;
527
+ }
528
+ if (entry) {
529
+ await emitToAuthorizedRoom(io, queryRoom, event, entry, fullDocument, logDebug);
530
+ } else {
531
+ io.to(queryRoom).emit("sync", event);
532
+ }
533
+ logDebug(`[realtime] Emitted hard delete to ${queryRoom}`);
534
+ return;
535
+ }
536
+
537
+ if (entry && hasFieldViews) {
538
+ await emitMaskedQueryRoomEvent({
539
+ entry,
540
+ event,
541
+ fullDocument,
542
+ io,
543
+ logDebug,
544
+ query,
545
+ queryRoom,
546
+ });
547
+ return;
548
+ }
549
+
550
+ // Soft delete: only forward to query rooms whose filter the document satisfies.
551
+ if (matchesQuery(fullDocument, query)) {
552
+ if (entry) {
553
+ await emitToAuthorizedRoom(io, queryRoom, event, entry, fullDocument, logDebug);
554
+ } else {
555
+ io.to(queryRoom).emit("sync", event);
556
+ }
557
+ logDebug(`[realtime] Emitted soft delete to ${queryRoom} (query matched)`);
558
+ }
559
+ return;
560
+ }
561
+
562
+ if (!fullDocument) {
563
+ return;
564
+ }
565
+
566
+ if (entry && hasFieldViews) {
567
+ await emitMaskedQueryRoomEvent({entry, event, fullDocument, io, logDebug, query, queryRoom});
568
+ return;
569
+ }
570
+
571
+ const docMatches = matchesQuery(fullDocument, query);
572
+
573
+ if (event.method === "create" && docMatches) {
574
+ // New document matches the query — send create event
575
+ if (entry) {
576
+ await emitToAuthorizedRoom(io, queryRoom, event, entry, fullDocument, logDebug);
577
+ } else {
578
+ io.to(queryRoom).emit("sync", event);
579
+ }
580
+ logDebug(`[realtime] Emitted create to ${queryRoom} (query matched)`);
581
+ } else if (event.method === "update") {
582
+ if (docMatches) {
583
+ // Document still matches (or newly matches) — send update event
584
+ if (entry) {
585
+ await emitToAuthorizedRoom(io, queryRoom, event, entry, fullDocument, logDebug);
586
+ } else {
587
+ io.to(queryRoom).emit("sync", event);
588
+ }
589
+ logDebug(`[realtime] Emitted update to ${queryRoom} (query matched)`);
590
+ } else {
591
+ // Document no longer matches the query — send delete event so client removes it
592
+ const removeEvent: RealtimeEvent = {
593
+ ...event,
594
+ method: "delete",
595
+ };
596
+ if (entry) {
597
+ await emitToAuthorizedRoom(io, queryRoom, removeEvent, entry, fullDocument, logDebug);
598
+ } else {
599
+ io.to(queryRoom).emit("sync", removeEvent);
600
+ }
601
+ logDebug(`[realtime] Emitted delete to ${queryRoom} (query no longer matched)`);
602
+ }
603
+ }
604
+ };
605
+
432
606
  /**
433
607
  * Emit a sync event to document-specific and query rooms.
434
608
  *
@@ -464,80 +638,28 @@ export const emitToDocumentAndQueryRooms = async (
464
638
  logDebug(`[realtime] Emitted ${event.method} to ${docRoom}`);
465
639
 
466
640
  const isOwnerStrategy = entry?.config.roomStrategy === "owner";
641
+ const hasFieldViews = Boolean(entry?.options.access && entry?.options.accessControl);
467
642
 
468
643
  // Evaluate query subscriptions
469
644
  const querySubscriptions = getQuerySubscriptionsForCollection(collection);
470
- for (const {queryId, query} of querySubscriptions) {
471
- const queryRoom = `query:${queryId}`;
472
-
473
- if (event.method === "delete") {
474
- if (!fullDocument) {
475
- // Hard delete with no document context. For owner-strategy collections we can't
476
- // tell which query rooms belong to the owner without leaking activity to others,
477
- // so skip query fanout entirely — subscribers will reconcile on next fetch.
478
- if (isOwnerStrategy) {
479
- logDebug(
480
- `[realtime] Skipping hard delete fanout to ${queryRoom} (owner strategy, no fullDocument)`
481
- );
482
- continue;
483
- }
484
- if (entry) {
485
- await emitToAuthorizedRoom(io, queryRoom, event, entry, fullDocument, logDebug);
486
- } else {
487
- io.to(queryRoom).emit("sync", event);
488
- }
489
- logDebug(`[realtime] Emitted hard delete to ${queryRoom}`);
490
- continue;
491
- }
492
-
493
- // Soft delete: only forward to query rooms whose filter the document satisfies.
494
- if (matchesQuery(fullDocument, query)) {
495
- if (entry) {
496
- await emitToAuthorizedRoom(io, queryRoom, event, entry, fullDocument, logDebug);
497
- } else {
498
- io.to(queryRoom).emit("sync", event);
499
- }
500
- logDebug(`[realtime] Emitted soft delete to ${queryRoom} (query matched)`);
501
- }
502
- continue;
503
- }
504
-
505
- if (!fullDocument) {
506
- continue;
507
- }
508
-
509
- const docMatches = matchesQuery(fullDocument, query);
510
-
511
- if (event.method === "create" && docMatches) {
512
- // New document matches the query — send create event
513
- if (entry) {
514
- await emitToAuthorizedRoom(io, queryRoom, event, entry, fullDocument, logDebug);
515
- } else {
516
- io.to(queryRoom).emit("sync", event);
517
- }
518
- logDebug(`[realtime] Emitted create to ${queryRoom} (query matched)`);
519
- } else if (event.method === "update") {
520
- if (docMatches) {
521
- // Document still matches (or newly matches) — send update event
522
- if (entry) {
523
- await emitToAuthorizedRoom(io, queryRoom, event, entry, fullDocument, logDebug);
524
- } else {
525
- io.to(queryRoom).emit("sync", event);
526
- }
527
- logDebug(`[realtime] Emitted update to ${queryRoom} (query matched)`);
528
- } else {
529
- // Document no longer matches the query — send delete event so client removes it
530
- const removeEvent: RealtimeEvent = {
531
- ...event,
532
- method: "delete",
533
- };
534
- if (entry) {
535
- await emitToAuthorizedRoom(io, queryRoom, removeEvent, entry, fullDocument, logDebug);
536
- } else {
537
- io.to(queryRoom).emit("sync", removeEvent);
538
- }
539
- logDebug(`[realtime] Emitted delete to ${queryRoom} (query no longer matched)`);
540
- }
645
+ for (const subscription of querySubscriptions) {
646
+ try {
647
+ await emitToQueryRoom({
648
+ entry,
649
+ event,
650
+ fullDocument,
651
+ hasFieldViews,
652
+ io,
653
+ isOwnerStrategy,
654
+ logDebug,
655
+ query: subscription.query,
656
+ queryRoom: `query:${subscription.queryId}`,
657
+ });
658
+ } catch (error) {
659
+ // One subscription's failure must not stop the others or the change's sync:delta.
660
+ logger.warn(
661
+ `[realtime] Query subscription ${subscription.queryId} failed to evaluate; skipping it: ${error}`
662
+ );
541
663
  }
542
664
  }
543
665
  };
@@ -981,7 +1103,13 @@ const openChangeStream = ({
981
1103
  }
982
1104
 
983
1105
  if (entry) {
984
- await processRealtimeChange({change, docId, entry, io, logDebug, logInfo});
1106
+ // A legacy realtime failure must not skip the independent sync:delta emission.
1107
+ try {
1108
+ await processRealtimeChange({change, docId, entry, io, logDebug, logInfo});
1109
+ } catch (error) {
1110
+ logger.error(`[realtime] Error processing realtime change: ${error}`);
1111
+ Sentry.captureException(error);
1112
+ }
985
1113
  }
986
1114
 
987
1115
  if (syncEntry) {
@@ -149,24 +149,17 @@ const matchesCondition = (rawValue: unknown, condition: unknown): boolean => {
149
149
  return true;
150
150
  };
151
151
 
152
- /**
153
- * Check if a document matches a MongoDB-style query in memory.
154
- *
155
- * @param doc - The document to test (plain object or Mongoose document)
156
- * @param query - MongoDB-style query object
157
- * @returns true if the document matches all query conditions
158
- */
159
- export const matchesQuery = (
160
- doc: Record<string, unknown>,
161
- query: Record<string, unknown>
162
- ): boolean => {
152
+ const isPlainQuery = (value: unknown): value is Record<string, unknown> =>
153
+ typeof value === "object" && value !== null && !Array.isArray(value);
154
+
155
+ const evaluateQuery = (doc: Record<string, unknown>, query: Record<string, unknown>): boolean => {
163
156
  for (const [key, condition] of Object.entries(query)) {
164
157
  if (key === "$and") {
165
158
  if (!Array.isArray(condition)) {
166
159
  return false;
167
160
  }
168
161
  for (const subQuery of condition) {
169
- if (!matchesQuery(doc, subQuery as Record<string, unknown>)) {
162
+ if (!isPlainQuery(subQuery) || !evaluateQuery(doc, subQuery)) {
170
163
  return false;
171
164
  }
172
165
  }
@@ -179,7 +172,7 @@ export const matchesQuery = (
179
172
  }
180
173
  let matched = false;
181
174
  for (const subQuery of condition) {
182
- if (matchesQuery(doc, subQuery as Record<string, unknown>)) {
175
+ if (isPlainQuery(subQuery) && evaluateQuery(doc, subQuery)) {
183
176
  matched = true;
184
177
  break;
185
178
  }
@@ -198,3 +191,27 @@ export const matchesQuery = (
198
191
 
199
192
  return true;
200
193
  };
194
+
195
+ /**
196
+ * Check if a document matches a MongoDB-style query in memory.
197
+ *
198
+ * Fails closed: malformed clauses, and operands that cannot be compared (for example an
199
+ * object whose `toString` is not a function), count as a non-match instead of throwing.
200
+ *
201
+ * @param doc - The document to test (plain object or Mongoose document)
202
+ * @param query - MongoDB-style query object
203
+ * @returns true if the document matches all query conditions
204
+ */
205
+ export const matchesQuery = (
206
+ doc: Record<string, unknown>,
207
+ query: Record<string, unknown>
208
+ ): boolean => {
209
+ if (!isPlainQuery(query)) {
210
+ return false;
211
+ }
212
+ try {
213
+ return evaluateQuery(doc, query);
214
+ } catch {
215
+ return false;
216
+ }
217
+ };
@@ -88,6 +88,17 @@ const setConnectionDb = (db: unknown): void => {
88
88
  // ─────────────────────────────────────────────────────────────────────────────
89
89
 
90
90
  describe("matchesQuery", () => {
91
+ describe("malformed predicates", () => {
92
+ it("fails closed instead of throwing", () => {
93
+ expect(matchesQuery({a: 1}, {$and: [null]})).toBe(false);
94
+ expect(matchesQuery({a: 1}, {$and: [{a: 1}, 5]})).toBe(false);
95
+ expect(matchesQuery({a: 1}, {$or: [null, {a: 1}]})).toBe(true);
96
+ expect(matchesQuery({a: 1}, {$or: [null, "x"]})).toBe(false);
97
+ expect(matchesQuery({a: 1}, {a: {$eq: {toString: 1}}})).toBe(false);
98
+ expect(matchesQuery({a: 1}, null as unknown as Record<string, unknown>)).toBe(false);
99
+ });
100
+ });
101
+
91
102
  describe("direct equality", () => {
92
103
  it("matches string equality", () => {
93
104
  expect(matchesQuery({name: "Alice"}, {name: "Alice"})).toBe(true);
@@ -756,6 +767,7 @@ describe("installRealtimeSocketHandlers", () => {
756
767
  read: [() => true],
757
768
  update: [() => true],
758
769
  },
770
+ queryFields: ["completed", "priority"],
759
771
  },
760
772
  routePath: "/todos",
761
773
  });
@@ -774,6 +786,7 @@ describe("installRealtimeSocketHandlers", () => {
774
786
  read: [() => true],
775
787
  update: [() => true],
776
788
  },
789
+ queryFields: ["priority"],
777
790
  },
778
791
  routePath: "/broadcasts",
779
792
  });
@@ -792,6 +805,7 @@ describe("installRealtimeSocketHandlers", () => {
792
805
  read: [(_method: string, user?: {admin?: boolean}) => user?.admin === true],
793
806
  update: [(_method: string, user?: {admin?: boolean}) => user?.admin === true],
794
807
  },
808
+ queryFields: ["classification"],
795
809
  },
796
810
  routePath: "/secrets",
797
811
  });
@@ -1065,6 +1079,7 @@ describe("installRealtimeSocketHandlers", () => {
1065
1079
  read: [() => true],
1066
1080
  update: [() => true],
1067
1081
  },
1082
+ queryFields: ["status"],
1068
1083
  queryFilter: () => ({tenantId: "tenant-1"}),
1069
1084
  },
1070
1085
  routePath: "/filtered",
@@ -1093,6 +1108,7 @@ describe("installRealtimeSocketHandlers", () => {
1093
1108
  read: [() => true],
1094
1109
  update: [() => true],
1095
1110
  },
1111
+ queryFields: ["status"],
1096
1112
  queryFilter: () => {
1097
1113
  throw new Error("tenant lookup failed");
1098
1114
  },
@@ -1111,6 +1127,38 @@ describe("installRealtimeSocketHandlers", () => {
1111
1127
  expect(socket.emitted.some((e) => e.event === "query:subscribed")).toBe(false);
1112
1128
  });
1113
1129
 
1130
+ it("denies query keys outside the modelRouter queryFields allowlist", async () => {
1131
+ registerRealtime({
1132
+ collectionName: "charts",
1133
+ config: {methods: ["create", "update", "delete"], roomStrategy: "model"},
1134
+ modelName: "Chart",
1135
+ options: {...permissiveOptions, queryFields: ["status"]},
1136
+ routePath: "/charts",
1137
+ });
1138
+ const socket = createMockSocket({id: "user1"});
1139
+ installRealtimeSocketHandlers(socket);
1140
+ await socket.trigger("subscribe:query", {
1141
+ collection: "charts",
1142
+ query: {diagnosis: {$in: ["F32.1"]}},
1143
+ });
1144
+ await socket.trigger("subscribe:query", {
1145
+ collection: "charts",
1146
+ query: {$or: [{status: "open"}, {diagnosis: "F41.1"}]},
1147
+ });
1148
+ await socket.trigger("subscribe:query", {
1149
+ collection: "charts",
1150
+ query: {"diagnosis.code": "F41", status: "open"},
1151
+ });
1152
+ expect(getQuerySubscriptionsForCollection("charts")).toHaveLength(0);
1153
+ expect(socket.emitted.some((e) => e.event === "query:subscribed")).toBe(false);
1154
+
1155
+ await socket.trigger("subscribe:query", {
1156
+ collection: "charts",
1157
+ query: {$or: [{status: "open"}, {status: {$in: ["closed"]}}]},
1158
+ });
1159
+ expect(getQuerySubscriptionsForCollection("charts")).toHaveLength(1);
1160
+ });
1161
+
1114
1162
  it("ignores malformed query payloads", async () => {
1115
1163
  registerOwnerCollection();
1116
1164
  const socket = createMockSocket({id: "user1"});
@@ -1119,6 +1167,8 @@ describe("installRealtimeSocketHandlers", () => {
1119
1167
  await socket.trigger("subscribe:query", {});
1120
1168
  await socket.trigger("subscribe:query", {collection: "todos"});
1121
1169
  await socket.trigger("subscribe:query", {collection: "todos", query: [1, 2, 3]});
1170
+ await socket.trigger("subscribe:query", {collection: "todos", query: {$and: [null]}});
1171
+ await socket.trigger("subscribe:query", {collection: "todos", query: {$or: "priority"}});
1122
1172
  const queryRooms = Array.from(socket.rooms).filter((r) => r.startsWith("query:"));
1123
1173
  expect(queryRooms).toHaveLength(0);
1124
1174
  });
@@ -1517,6 +1567,40 @@ describe("emitToDocumentAndQueryRooms", () => {
1517
1567
  expect(emissions.some((e) => e.room === "document:todos:doc-1")).toBe(true);
1518
1568
  });
1519
1569
 
1570
+ it("keeps fanning out to later query rooms when one subscription fails", async () => {
1571
+ addQuerySubscription("socket-a", "todos", {priority: 1}, "failing");
1572
+ const healthyId = computeQueryId("todos", {priority: 1});
1573
+ addQuerySubscription("socket-b", "todos", {priority: 1}, healthyId);
1574
+ const {addSocketToRoom, emissions, io} = makeIo();
1575
+ addSocketToRoom(`query:${healthyId}`);
1576
+ const throwingIo = {
1577
+ ...io,
1578
+ to: (room: string) => {
1579
+ if (room === "query:failing") {
1580
+ throw new Error("emit failed");
1581
+ }
1582
+ return io.to(room);
1583
+ },
1584
+ } as unknown as Server;
1585
+ const event: RealtimeEvent = {
1586
+ collection: "todos",
1587
+ id: "doc-1",
1588
+ method: "create",
1589
+ model: "Todo",
1590
+ timestamp: 1,
1591
+ };
1592
+
1593
+ await emitToDocumentAndQueryRooms(
1594
+ throwingIo,
1595
+ "todos",
1596
+ event,
1597
+ {name: "x", priority: 1},
1598
+ () => {}
1599
+ );
1600
+
1601
+ expect(emissions.some((e) => e.room === `query:${healthyId}`)).toBe(true);
1602
+ });
1603
+
1520
1604
  it("forwards hard deletes to every query room for non-owner strategies", async () => {
1521
1605
  const queryId = computeQueryId("todos", {priority: 1});
1522
1606
  addQuerySubscription("socket-a", "todos", {priority: 1}, queryId);
@@ -1980,6 +2064,54 @@ describe("emitToDocumentAndQueryRooms", () => {
1980
2064
  expect(queryEmissions[0].payload).toMatchObject({method: "delete"});
1981
2065
  });
1982
2066
 
2067
+ it("matches query rooms against the recipient's RBAC-masked document", async () => {
2068
+ const fieldMaskRequests: unknown[] = [];
2069
+ const rbacEntry: RealtimeRegistryEntry = {
2070
+ ...modelEntry,
2071
+ options: {
2072
+ ...modelEntry.options,
2073
+ access: {resource: "chart"},
2074
+ accessControl: {
2075
+ can: async () => ({allowed: true}),
2076
+ fieldMask: async (args: unknown) => {
2077
+ fieldMaskRequests.push(args);
2078
+ return {omit: ["diagnosis"], read: "*", write: "*"};
2079
+ },
2080
+ statements: {chart: ["read", "list"]},
2081
+ } as unknown as NonNullable<RealtimeRegistryEntry["options"]["accessControl"]>,
2082
+ },
2083
+ };
2084
+ const matchingId = computeQueryId("todos", {diagnosis: "F32.1"});
2085
+ const otherId = computeQueryId("todos", {diagnosis: "F41.1"});
2086
+ addQuerySubscription("socket-a", "todos", {diagnosis: "F32.1"}, matchingId);
2087
+ addQuerySubscription("socket-b", "todos", {diagnosis: "F41.1"}, otherId);
2088
+ const {addSocketToRoom, emissions, io} = makeIo();
2089
+ addSocketToRoom(`query:${matchingId}`, {id: "scheduler"});
2090
+ addSocketToRoom(`query:${otherId}`, {id: "scheduler"});
2091
+
2092
+ await emitToDocumentAndQueryRooms(
2093
+ io,
2094
+ "todos",
2095
+ makeEvent("update"),
2096
+ {_id: "doc-1", diagnosis: "F32.1", status: "open"},
2097
+ () => {},
2098
+ rbacEntry
2099
+ );
2100
+
2101
+ const methodFor = (queryId: string): unknown =>
2102
+ (emissions.find((e) => e.room === `query:${queryId}`)?.payload as {method?: string})
2103
+ ?.method;
2104
+ // The hidden value must not decide which event each room receives.
2105
+ expect(methodFor(matchingId)).toBe(methodFor(otherId));
2106
+ expect(methodFor(matchingId)).toBe("delete");
2107
+ for (const emission of emissions) {
2108
+ expect((emission.payload as {data?: Record<string, unknown>}).data).not.toHaveProperty(
2109
+ "diagnosis"
2110
+ );
2111
+ }
2112
+ expect(fieldMaskRequests.length).toBeGreaterThan(0);
2113
+ });
2114
+
1983
2115
  it("skips query rooms whose subscribers cannot read the document", async () => {
1984
2116
  const queryId = computeQueryId("todos", {priority: 1});
1985
2117
  addQuerySubscription("socket-a", "todos", {priority: 1}, queryId);