@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
@@ -282,6 +282,8 @@ const serializeDoc = async (entry, doc, method, user) => {
282
282
  return (0, exports.ensureApiId)(maskedFallback);
283
283
  };
284
284
  exports.serializeDoc = serializeDoc;
285
+ /** Returned by a `buildPayload` callback to send nothing to that socket. */
286
+ const SKIP_EMISSION = Symbol("skipEmission");
285
287
  /**
286
288
  * Generalized authorized-room emitter: iterates the sockets in `room`, runs the per-socket
287
289
  * read-permission check against `fullDocument`, builds the payload per socket (so
@@ -310,7 +312,10 @@ const emitPayloadToAuthorizedRoom = async ({ io, room, eventName, entry, fullDoc
310
312
  continue;
311
313
  }
312
314
  if (adminDecision === "allow") {
313
- socket.emit(eventName, await buildPayload(user));
315
+ const adminPayload = await buildPayload(user);
316
+ if (adminPayload !== SKIP_EMISSION) {
317
+ socket.emit(eventName, adminPayload);
318
+ }
314
319
  continue;
315
320
  }
316
321
  }
@@ -319,7 +324,11 @@ const emitPayloadToAuthorizedRoom = async ({ io, room, eventName, entry, fullDoc
319
324
  logDebug(`[realtime] Skipped ${room} for ${socket.id}: read permission denied`);
320
325
  continue;
321
326
  }
322
- socket.emit(eventName, await buildPayload(user));
327
+ const payload = await buildPayload(user);
328
+ if (payload === SKIP_EMISSION) {
329
+ continue;
330
+ }
331
+ socket.emit(eventName, payload);
323
332
  }
324
333
  catch (error) {
325
334
  logger_1.logger.error(`[realtime] Failed to emit ${eventName} for ${entry.modelName} to socket ${socket.id}: ${error}`);
@@ -345,6 +354,127 @@ const emitToAuthorizedRoom = async (io, room, event, entry, fullDocument, logDeb
345
354
  room,
346
355
  });
347
356
  exports.emitToAuthorizedRoom = emitToAuthorizedRoom;
357
+ /**
358
+ * Query-room fan-out for routers with RBAC field views. Each recipient's match is evaluated
359
+ * against the document as masked for that recipient, so a field hidden from them cannot
360
+ * decide whether they receive a create, update, or delete.
361
+ */
362
+ const emitMaskedQueryRoomEvent = async ({ io, queryRoom, event, entry, fullDocument, query, logDebug, }) => (0, exports.emitPayloadToAuthorizedRoom)({
363
+ buildPayload: async (user) => {
364
+ const masked = await (0, realtimeAccess_1.maskRealtimeDocument)(entry, user, fullDocument, "read");
365
+ const matches = typeof masked === "object" &&
366
+ masked !== null &&
367
+ !Array.isArray(masked) &&
368
+ (0, queryMatcher_1.matchesQuery)(masked, query);
369
+ let method;
370
+ if (event.method === "update") {
371
+ method = matches ? "update" : "delete";
372
+ }
373
+ else if (matches) {
374
+ method = event.method;
375
+ }
376
+ if (!method) {
377
+ return SKIP_EMISSION;
378
+ }
379
+ const data = await (0, exports.serializeDoc)(entry, fullDocument, method, user);
380
+ return { ...event, data, method };
381
+ },
382
+ entry,
383
+ eventName: "sync",
384
+ fullDocument,
385
+ io,
386
+ logDebug,
387
+ room: queryRoom,
388
+ });
389
+ /** Fan one change out to one query room. */
390
+ const emitToQueryRoom = async ({ io, queryRoom, query, event, fullDocument, entry, hasFieldViews, isOwnerStrategy, logDebug, }) => {
391
+ if (event.method === "delete") {
392
+ if (!fullDocument) {
393
+ // Hard delete with no document context. For owner-strategy collections we can't
394
+ // tell which query rooms belong to the owner without leaking activity to others,
395
+ // so skip query fanout entirely — subscribers will reconcile on next fetch.
396
+ if (isOwnerStrategy) {
397
+ logDebug(`[realtime] Skipping hard delete fanout to ${queryRoom} (owner strategy, no fullDocument)`);
398
+ return;
399
+ }
400
+ if (entry) {
401
+ await (0, exports.emitToAuthorizedRoom)(io, queryRoom, event, entry, fullDocument, logDebug);
402
+ }
403
+ else {
404
+ io.to(queryRoom).emit("sync", event);
405
+ }
406
+ logDebug(`[realtime] Emitted hard delete to ${queryRoom}`);
407
+ return;
408
+ }
409
+ if (entry && hasFieldViews) {
410
+ await emitMaskedQueryRoomEvent({
411
+ entry,
412
+ event,
413
+ fullDocument,
414
+ io,
415
+ logDebug,
416
+ query,
417
+ queryRoom,
418
+ });
419
+ return;
420
+ }
421
+ // Soft delete: only forward to query rooms whose filter the document satisfies.
422
+ if ((0, queryMatcher_1.matchesQuery)(fullDocument, query)) {
423
+ if (entry) {
424
+ await (0, exports.emitToAuthorizedRoom)(io, queryRoom, event, entry, fullDocument, logDebug);
425
+ }
426
+ else {
427
+ io.to(queryRoom).emit("sync", event);
428
+ }
429
+ logDebug(`[realtime] Emitted soft delete to ${queryRoom} (query matched)`);
430
+ }
431
+ return;
432
+ }
433
+ if (!fullDocument) {
434
+ return;
435
+ }
436
+ if (entry && hasFieldViews) {
437
+ await emitMaskedQueryRoomEvent({ entry, event, fullDocument, io, logDebug, query, queryRoom });
438
+ return;
439
+ }
440
+ const docMatches = (0, queryMatcher_1.matchesQuery)(fullDocument, query);
441
+ if (event.method === "create" && docMatches) {
442
+ // New document matches the query — send create event
443
+ if (entry) {
444
+ await (0, exports.emitToAuthorizedRoom)(io, queryRoom, event, entry, fullDocument, logDebug);
445
+ }
446
+ else {
447
+ io.to(queryRoom).emit("sync", event);
448
+ }
449
+ logDebug(`[realtime] Emitted create to ${queryRoom} (query matched)`);
450
+ }
451
+ else if (event.method === "update") {
452
+ if (docMatches) {
453
+ // Document still matches (or newly matches) — send update event
454
+ if (entry) {
455
+ await (0, exports.emitToAuthorizedRoom)(io, queryRoom, event, entry, fullDocument, logDebug);
456
+ }
457
+ else {
458
+ io.to(queryRoom).emit("sync", event);
459
+ }
460
+ logDebug(`[realtime] Emitted update to ${queryRoom} (query matched)`);
461
+ }
462
+ else {
463
+ // Document no longer matches the query — send delete event so client removes it
464
+ const removeEvent = {
465
+ ...event,
466
+ method: "delete",
467
+ };
468
+ if (entry) {
469
+ await (0, exports.emitToAuthorizedRoom)(io, queryRoom, removeEvent, entry, fullDocument, logDebug);
470
+ }
471
+ else {
472
+ io.to(queryRoom).emit("sync", removeEvent);
473
+ }
474
+ logDebug(`[realtime] Emitted delete to ${queryRoom} (query no longer matched)`);
475
+ }
476
+ }
477
+ };
348
478
  /**
349
479
  * Emit a sync event to document-specific and query rooms.
350
480
  *
@@ -373,79 +503,26 @@ const emitToDocumentAndQueryRooms = async (io, collection, event, fullDocument,
373
503
  }
374
504
  logDebug(`[realtime] Emitted ${event.method} to ${docRoom}`);
375
505
  const isOwnerStrategy = entry?.config.roomStrategy === "owner";
506
+ const hasFieldViews = Boolean(entry?.options.access && entry?.options.accessControl);
376
507
  // Evaluate query subscriptions
377
508
  const querySubscriptions = (0, queryStore_1.getQuerySubscriptionsForCollection)(collection);
378
- for (const { queryId, query } of querySubscriptions) {
379
- const queryRoom = `query:${queryId}`;
380
- if (event.method === "delete") {
381
- if (!fullDocument) {
382
- // Hard delete with no document context. For owner-strategy collections we can't
383
- // tell which query rooms belong to the owner without leaking activity to others,
384
- // so skip query fanout entirely — subscribers will reconcile on next fetch.
385
- if (isOwnerStrategy) {
386
- logDebug(`[realtime] Skipping hard delete fanout to ${queryRoom} (owner strategy, no fullDocument)`);
387
- continue;
388
- }
389
- if (entry) {
390
- await (0, exports.emitToAuthorizedRoom)(io, queryRoom, event, entry, fullDocument, logDebug);
391
- }
392
- else {
393
- io.to(queryRoom).emit("sync", event);
394
- }
395
- logDebug(`[realtime] Emitted hard delete to ${queryRoom}`);
396
- continue;
397
- }
398
- // Soft delete: only forward to query rooms whose filter the document satisfies.
399
- if ((0, queryMatcher_1.matchesQuery)(fullDocument, query)) {
400
- if (entry) {
401
- await (0, exports.emitToAuthorizedRoom)(io, queryRoom, event, entry, fullDocument, logDebug);
402
- }
403
- else {
404
- io.to(queryRoom).emit("sync", event);
405
- }
406
- logDebug(`[realtime] Emitted soft delete to ${queryRoom} (query matched)`);
407
- }
408
- continue;
409
- }
410
- if (!fullDocument) {
411
- continue;
412
- }
413
- const docMatches = (0, queryMatcher_1.matchesQuery)(fullDocument, query);
414
- if (event.method === "create" && docMatches) {
415
- // New document matches the query — send create event
416
- if (entry) {
417
- await (0, exports.emitToAuthorizedRoom)(io, queryRoom, event, entry, fullDocument, logDebug);
418
- }
419
- else {
420
- io.to(queryRoom).emit("sync", event);
421
- }
422
- logDebug(`[realtime] Emitted create to ${queryRoom} (query matched)`);
509
+ for (const subscription of querySubscriptions) {
510
+ try {
511
+ await emitToQueryRoom({
512
+ entry,
513
+ event,
514
+ fullDocument,
515
+ hasFieldViews,
516
+ io,
517
+ isOwnerStrategy,
518
+ logDebug,
519
+ query: subscription.query,
520
+ queryRoom: `query:${subscription.queryId}`,
521
+ });
423
522
  }
424
- else if (event.method === "update") {
425
- if (docMatches) {
426
- // Document still matches (or newly matches) — send update event
427
- if (entry) {
428
- await (0, exports.emitToAuthorizedRoom)(io, queryRoom, event, entry, fullDocument, logDebug);
429
- }
430
- else {
431
- io.to(queryRoom).emit("sync", event);
432
- }
433
- logDebug(`[realtime] Emitted update to ${queryRoom} (query matched)`);
434
- }
435
- else {
436
- // Document no longer matches the query — send delete event so client removes it
437
- const removeEvent = {
438
- ...event,
439
- method: "delete",
440
- };
441
- if (entry) {
442
- await (0, exports.emitToAuthorizedRoom)(io, queryRoom, removeEvent, entry, fullDocument, logDebug);
443
- }
444
- else {
445
- io.to(queryRoom).emit("sync", removeEvent);
446
- }
447
- logDebug(`[realtime] Emitted delete to ${queryRoom} (query no longer matched)`);
448
- }
523
+ catch (error) {
524
+ // One subscription's failure must not stop the others or the change's sync:delta.
525
+ logger_1.logger.warn(`[realtime] Query subscription ${subscription.queryId} failed to evaluate; skipping it: ${error}`);
449
526
  }
450
527
  }
451
528
  };
@@ -790,7 +867,14 @@ const openChangeStream = ({ config, debug, io, isReopen = false, }) => {
790
867
  return;
791
868
  }
792
869
  if (entry) {
793
- await processRealtimeChange({ change, docId, entry, io, logDebug, logInfo });
870
+ // A legacy realtime failure must not skip the independent sync:delta emission.
871
+ try {
872
+ await processRealtimeChange({ change, docId, entry, io, logDebug, logInfo });
873
+ }
874
+ catch (error) {
875
+ logger_1.logger.error(`[realtime] Error processing realtime change: ${error}`);
876
+ Sentry.captureException(error);
877
+ }
794
878
  }
795
879
  if (syncEntry) {
796
880
  // C8: serialize per entity so same-doc deltas emit in change-stream order;
@@ -7,6 +7,9 @@
7
7
  /**
8
8
  * Check if a document matches a MongoDB-style query in memory.
9
9
  *
10
+ * Fails closed: malformed clauses, and operands that cannot be compared (for example an
11
+ * object whose `toString` is not a function), count as a non-match instead of throwing.
12
+ *
10
13
  * @param doc - The document to test (plain object or Mongoose document)
11
14
  * @param query - MongoDB-style query object
12
15
  * @returns true if the document matches all query conditions
@@ -142,21 +142,15 @@ const matchesCondition = (rawValue, condition) => {
142
142
  }
143
143
  return true;
144
144
  };
145
- /**
146
- * Check if a document matches a MongoDB-style query in memory.
147
- *
148
- * @param doc - The document to test (plain object or Mongoose document)
149
- * @param query - MongoDB-style query object
150
- * @returns true if the document matches all query conditions
151
- */
152
- const matchesQuery = (doc, query) => {
145
+ const isPlainQuery = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
146
+ const evaluateQuery = (doc, query) => {
153
147
  for (const [key, condition] of Object.entries(query)) {
154
148
  if (key === "$and") {
155
149
  if (!Array.isArray(condition)) {
156
150
  return false;
157
151
  }
158
152
  for (const subQuery of condition) {
159
- if (!(0, exports.matchesQuery)(doc, subQuery)) {
153
+ if (!isPlainQuery(subQuery) || !evaluateQuery(doc, subQuery)) {
160
154
  return false;
161
155
  }
162
156
  }
@@ -168,7 +162,7 @@ const matchesQuery = (doc, query) => {
168
162
  }
169
163
  let matched = false;
170
164
  for (const subQuery of condition) {
171
- if ((0, exports.matchesQuery)(doc, subQuery)) {
165
+ if (isPlainQuery(subQuery) && evaluateQuery(doc, subQuery)) {
172
166
  matched = true;
173
167
  break;
174
168
  }
@@ -185,4 +179,25 @@ const matchesQuery = (doc, query) => {
185
179
  }
186
180
  return true;
187
181
  };
182
+ /**
183
+ * Check if a document matches a MongoDB-style query in memory.
184
+ *
185
+ * Fails closed: malformed clauses, and operands that cannot be compared (for example an
186
+ * object whose `toString` is not a function), count as a non-match instead of throwing.
187
+ *
188
+ * @param doc - The document to test (plain object or Mongoose document)
189
+ * @param query - MongoDB-style query object
190
+ * @returns true if the document matches all query conditions
191
+ */
192
+ const matchesQuery = (doc, query) => {
193
+ if (!isPlainQuery(query)) {
194
+ return false;
195
+ }
196
+ try {
197
+ return evaluateQuery(doc, query);
198
+ }
199
+ catch {
200
+ return false;
201
+ }
202
+ };
188
203
  exports.matchesQuery = matchesQuery;
@@ -1,6 +1,7 @@
1
1
  import type http from "node:http";
2
2
  import type express from "express";
3
3
  import { Server } from "socket.io";
4
+ import type { TerrenoApp } from "../terrenoApp";
4
5
  import type { TerrenoPlugin } from "../terrenoPlugin";
5
6
  import { type SocketWithDecodedToken } from "./socketUser";
6
7
  import type { RealtimeAppOptions } from "./types";
@@ -74,11 +75,25 @@ export declare class RealtimeApp implements TerrenoPlugin {
74
75
  private io;
75
76
  private config;
76
77
  private sessionRevalidation;
78
+ private terrenoApp;
77
79
  constructor(config?: RealtimeAppOptions);
78
80
  /**
79
81
  * Register routes and middleware. Adds a /realtime/health endpoint.
80
82
  */
81
- register(app: express.Application): void;
83
+ register(app: express.Application, _openApi?: unknown, terrenoApp?: TerrenoApp): void;
84
+ /**
85
+ * This RealtimeApp's `userModel`, else the TerrenoApp's, matching what `TerrenoApp({realtime})`
86
+ * passes to the RealtimeApp it registers.
87
+ */
88
+ private resolveUserModel;
89
+ /**
90
+ * The Better Auth instance for socket sessions: the explicit `betterAuth` option, else the
91
+ * one from a Better Auth plugin (such as BetterAuthApp) registered on the same TerrenoApp,
92
+ * so apps do not have to build the instance early and pass it to both plugins. The socket
93
+ * validator falls back to the resolved `userModel`, so the handshake and the revalidation
94
+ * sweep resolve the same users.
95
+ */
96
+ private resolveBetterAuth;
82
97
  /**
83
98
  * Called after the HTTP server is created. Sets up Socket.io, auth, rooms,
84
99
  * and starts the change stream watcher.
@@ -36,6 +36,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.RealtimeApp = exports.installRealtimeSocketHandlers = exports.redactCredentials = exports.MAX_QUERY_SUBSCRIPTIONS = exports.MAX_DOCUMENT_SUBSCRIPTIONS = exports.MAX_MODEL_SUBSCRIPTIONS = void 0;
37
37
  const Sentry = __importStar(require("@sentry/bun"));
38
38
  const socket_io_1 = require("socket.io");
39
+ const betterAuthApp_1 = require("../betterAuthApp");
39
40
  const errors_1 = require("../errors");
40
41
  const logger_1 = require("../logger");
41
42
  const realtimeAccess_1 = require("../rbac/realtimeAccess");
@@ -80,6 +81,37 @@ const redactCredentials = (url) => {
80
81
  }
81
82
  };
82
83
  exports.redactCredentials = redactCredentials;
84
+ const LOGICAL_QUERY_KEYS = new Set(["$and", "$or"]);
85
+ const isPlainQueryObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
86
+ /**
87
+ * Returns the first field a client query names outside `queryFields`, walking `$and` / `$or`
88
+ * clauses, or undefined when every field is allowed. A query room's event method reveals
89
+ * whether a document matches, so subscriptions may only filter on the fields REST list
90
+ * accepts.
91
+ */
92
+ const findDisallowedQueryField = (query, queryFields) => {
93
+ for (const [key, condition] of Object.entries(query)) {
94
+ if (LOGICAL_QUERY_KEYS.has(key)) {
95
+ if (!Array.isArray(condition)) {
96
+ return key;
97
+ }
98
+ for (const clause of condition) {
99
+ if (!isPlainQueryObject(clause)) {
100
+ return key;
101
+ }
102
+ const nested = findDisallowedQueryField(clause, queryFields);
103
+ if (nested) {
104
+ return nested;
105
+ }
106
+ }
107
+ continue;
108
+ }
109
+ if (!queryFields.includes(key)) {
110
+ return key;
111
+ }
112
+ }
113
+ return undefined;
114
+ };
83
115
  const canSubscribe = async (entry, method, user) => (0, realtimeAccess_1.canSubscribeRealtime)(entry, method, user);
84
116
  const getAuthorizedQuery = async (entry, query, user) => {
85
117
  if (!(await canSubscribe(entry, "list", user))) {
@@ -228,6 +260,12 @@ const installRealtimeSocketHandlers = (socket, options = {}) => {
228
260
  `collection "${payload.collection}" not registered`);
229
261
  return;
230
262
  }
263
+ const disallowedField = findDisallowedQueryField(payload.query, entry.options.queryFields ?? []);
264
+ if (disallowedField) {
265
+ logInfo(`[realtime] User ${userId} denied query subscription for ${payload.collection}: ` +
266
+ `${disallowedField} is not in queryFields`);
267
+ return;
268
+ }
231
269
  let query = await getAuthorizedQuery(entry, { ...payload.query }, currentUser());
232
270
  if (!query) {
233
271
  logInfo(`[realtime] User ${userId} denied query subscription for ${payload.collection}: ` +
@@ -294,14 +332,16 @@ class RealtimeApp {
294
332
  io = null;
295
333
  config;
296
334
  sessionRevalidation = null;
335
+ terrenoApp;
297
336
  constructor(config = {}) {
298
337
  this.config = config;
299
338
  }
300
339
  /**
301
340
  * Register routes and middleware. Adds a /realtime/health endpoint.
302
341
  */
303
- register(app) {
342
+ register(app, _openApi, terrenoApp) {
304
343
  this.app = app;
344
+ this.terrenoApp = terrenoApp;
305
345
  app.get("/realtime/health", (_req, res) => {
306
346
  const connected = this.io?.engine?.clientsCount ?? 0;
307
347
  res.json({
@@ -311,6 +351,31 @@ class RealtimeApp {
311
351
  });
312
352
  });
313
353
  }
354
+ /**
355
+ * This RealtimeApp's `userModel`, else the TerrenoApp's, matching what `TerrenoApp({realtime})`
356
+ * passes to the RealtimeApp it registers.
357
+ */
358
+ resolveUserModel() {
359
+ return this.config.userModel ?? this.terrenoApp?.getUserModel();
360
+ }
361
+ /**
362
+ * The Better Auth instance for socket sessions: the explicit `betterAuth` option, else the
363
+ * one from a Better Auth plugin (such as BetterAuthApp) registered on the same TerrenoApp,
364
+ * so apps do not have to build the instance early and pass it to both plugins. The socket
365
+ * validator falls back to the resolved `userModel`, so the handshake and the revalidation
366
+ * sweep resolve the same users.
367
+ */
368
+ resolveBetterAuth() {
369
+ const userModel = this.resolveUserModel();
370
+ if (this.config.betterAuth) {
371
+ return { ...this.config.betterAuth, userModel: this.config.betterAuth.userModel ?? userModel };
372
+ }
373
+ const auth = (0, betterAuthApp_1.getProvidedBetterAuth)((0, betterAuthApp_1.findBetterAuthProvider)(this.terrenoApp?.getPlugins() ?? []));
374
+ if (!auth) {
375
+ return undefined;
376
+ }
377
+ return { auth, userModel };
378
+ }
314
379
  /**
315
380
  * Called after the HTTP server is created. Sets up Socket.io, auth, rooms,
316
381
  * and starts the change stream watcher.
@@ -335,7 +400,9 @@ class RealtimeApp {
335
400
  });
336
401
  // Authentication middleware: legacy JWT first when configured, optionally Better Auth sessions.
337
402
  const tokenSecret = this.config.tokenSecret ?? process.env.TOKEN_SECRET;
338
- if (!tokenSecret && !this.config.betterAuth) {
403
+ const userModel = this.resolveUserModel();
404
+ const betterAuth = this.resolveBetterAuth();
405
+ if (!tokenSecret && !betterAuth) {
339
406
  throw new errors_1.APIError({
340
407
  status: 500,
341
408
  title: "[realtime] Socket authentication requires TOKEN_SECRET or Better Auth. " +
@@ -350,18 +417,19 @@ class RealtimeApp {
350
417
  // honored on every handshake, matching the HTTP path's per-request env read.
351
418
  const resolveTokenIssuer = () => this.config.tokenIssuer ?? process.env.TOKEN_ISSUER;
352
419
  this.io.use((0, socketAuth_1.createSocketAuthMiddleware)({
353
- betterAuth: this.config.betterAuth,
420
+ betterAuth,
354
421
  issuer: resolveTokenIssuer,
355
422
  tokenSecret,
423
+ userModel,
356
424
  }));
357
- const authKinds = [tokenSecret ? "JWT" : null, this.config.betterAuth ? "Better Auth" : null]
425
+ const authKinds = [tokenSecret ? "JWT" : null, betterAuth ? "Better Auth" : null]
358
426
  .filter(Boolean)
359
427
  .join(" + ");
360
428
  logInfo(`[realtime] Socket auth middleware added (${authKinds})`);
361
429
  // Task 9.21: tenant/custom sync scopes can only be resolved from the full user
362
430
  // document, so warn loudly here (once, at startup) rather than silently serving
363
431
  // empty tenant streams for the life of the process.
364
- (0, registry_1.warnOnSyncScopesWithoutUserModel)({ userModel: this.config.userModel });
432
+ (0, registry_1.warnOnSyncScopesWithoutUserModel)({ userModel });
365
433
  // Configure adapter for multi-instance deployments
366
434
  this.setupAdapter(logInfo);
367
435
  // Connection handling
@@ -372,7 +440,7 @@ class RealtimeApp {
372
440
  // it over the synthetic {_id, admin, id} shape for every authorization
373
441
  // check below. Fire-and-forget: handlers install synchronously and fall
374
442
  // back to the synthetic shape until this resolves.
375
- void (0, sessionRevalidation_1.loadFullUserForSocket)(socket, this.config.userModel);
443
+ void (0, sessionRevalidation_1.loadFullUserForSocket)(socket, userModel);
376
444
  // The auth middleware adds `decodedToken` at runtime; cast through
377
445
  // RealtimeSocketLike (a structural subset) to keep socket handler logic testable.
378
446
  (0, exports.installRealtimeSocketHandlers)(socket, { logInfo });
@@ -399,11 +467,11 @@ class RealtimeApp {
399
467
  // re-resolves sync room membership (D4) for sockets that remain valid.
400
468
  // A thunk (not a snapshot) reads this app's SyncApp options fresh on every sweep.
401
469
  this.sessionRevalidation = (0, sessionRevalidation_1.startSessionRevalidationSweep)(this.io, () => ({
402
- betterAuth: this.config.betterAuth,
470
+ betterAuth,
403
471
  intervalMs: this.config.sessionRevalidationIntervalMs,
404
472
  logInfo,
405
473
  sync: this.config.sync ?? (this.app ? (0, syncApp_1.getSyncAppOptions)(this.app) : undefined),
406
- userModel: this.config.userModel,
474
+ userModel,
407
475
  }));
408
476
  logInfo("[realtime] Socket.io server setup complete");
409
477
  }
@@ -1,6 +1,6 @@
1
1
  import type { Socket } from "socket.io";
2
- import type { UserModel } from "../auth";
3
- import type { BetterAuthInstance } from "../betterAuthSetup";
2
+ import { type UserModel } from "../auth";
3
+ import { type BetterAuthInstance } from "../betterAuthSetup";
4
4
  import type { SocketWithDecodedToken } from "./socketUser";
5
5
  /**
6
6
  * Pluggable socket authentication for RealtimeApp.
@@ -41,8 +41,10 @@ export interface BetterAuthSocketOptions {
41
41
  auth: BetterAuthInstance;
42
42
  /**
43
43
  * Optional application user model. When provided, the Better Auth user is resolved to
44
- * the app user (via `betterAuthId`) so `decodedToken.id`/`admin` match the identity the
45
- * REST layer uses. Without it, the Better Auth user id is used and `admin` is false.
44
+ * the app user (via `betterAuthId`, created on first contact) so `decodedToken.id`/`admin`
45
+ * match the identity the REST layer uses, and disabled users are refused. Without it, the
46
+ * Better Auth user id is used and `admin` is false. `RealtimeApp` fills this in from its own
47
+ * `userModel`, else the TerrenoApp's, when it is omitted.
46
48
  */
47
49
  userModel?: UserModel;
48
50
  }
@@ -68,8 +70,12 @@ export interface BetterAuthSocketOptions {
68
70
  * (e.g. test suites that mutate it between fixtures). Pass a thunk to preserve that
69
71
  * per-request freshness; a plain string is still supported for callers who intentionally
70
72
  * want a fixed value.
73
+ *
74
+ * When `userModel` is provided, the token's user is loaded after verification and the
75
+ * handshake is refused when that user is missing or disabled, matching the HTTP JWT
76
+ * middleware and the Better Auth validator. Without it, only the token is checked.
71
77
  */
72
- export declare const createLegacyJwtValidator: (tokenSecret: string, issuer?: string | (() => string | undefined)) => SocketAuthValidator;
78
+ export declare const createLegacyJwtValidator: (tokenSecret: string, issuer?: string | (() => string | undefined), userModel?: UserModel) => SocketAuthValidator;
73
79
  /**
74
80
  * Better Auth session validator: treats the handshake token as a Better Auth session token
75
81
  * and validates it via `auth.api.getSession` (the same lookup the HTTP session middleware
@@ -81,7 +87,7 @@ export declare const createBetterAuthValidator: (options: BetterAuthSocketOption
81
87
  * Build the Socket.io auth middleware from a validator chain: validators run in order and
82
88
  * the first success wins; when all fail the connection is rejected with the last error.
83
89
  */
84
- export declare const createSocketAuthMiddleware: ({ tokenSecret, issuer, betterAuth, extraValidators, }: {
90
+ export declare const createSocketAuthMiddleware: ({ tokenSecret, issuer, betterAuth, userModel, extraValidators, }: {
85
91
  /** Secret enabling the legacy JWT validator (same handling as before the refactor). */
86
92
  tokenSecret?: string;
87
93
  /**
@@ -92,6 +98,11 @@ export declare const createSocketAuthMiddleware: ({ tokenSecret, issuer, betterA
92
98
  issuer?: string | (() => string | undefined);
93
99
  /** Enables the Better Auth session validator after the legacy JWT validator. */
94
100
  betterAuth?: BetterAuthSocketOptions;
101
+ /**
102
+ * Application user model. When set, the legacy JWT validator refuses tokens whose user is
103
+ * missing or disabled.
104
+ */
105
+ userModel?: UserModel;
95
106
  /** Additional validators appended to the chain (after JWT and Better Auth). */
96
107
  extraValidators?: SocketAuthValidator[];
97
108
  }) => ((socket: Socket, next: (error?: Error) => void) => void);