@terreno/api 57.20.0 → 58.0.0-beta.1

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 (183) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +1 -1
  3. package/biome.jsonc +3 -2
  4. package/dist/api.d.ts +3 -16
  5. package/dist/api.js +0 -9
  6. package/dist/auth.d.ts +3 -2
  7. package/dist/auth.js +95 -5
  8. package/dist/authRecovery.d.ts +2 -1
  9. package/dist/authRecovery.js +35 -17
  10. package/dist/collectionRegistry.d.ts +3 -4
  11. package/dist/collectionRegistry.js +0 -1
  12. package/dist/consentApp.d.ts +1 -1
  13. package/dist/consentApp.js +58 -2
  14. package/dist/frameworkModelNames.d.ts +4 -0
  15. package/dist/frameworkModelNames.js +4 -0
  16. package/dist/index.d.ts +8 -5
  17. package/dist/index.js +14 -20
  18. package/dist/mcp/adminTracking.d.ts +28 -0
  19. package/dist/mcp/adminTracking.js +80 -0
  20. package/dist/mcp/auth.d.ts +6 -0
  21. package/dist/mcp/auth.js +12 -2
  22. package/dist/mcp/server.d.ts +8 -0
  23. package/dist/mcp/server.js +48 -4
  24. package/dist/mcp/serviceTokens.d.ts +21 -1
  25. package/dist/mcp/serviceTokens.js +159 -183
  26. package/dist/migrations/builtin/mcpServiceTokenStringIds.d.ts +18 -0
  27. package/dist/migrations/builtin/mcpServiceTokenStringIds.js +67 -0
  28. package/dist/models/mcpOAuthToken.js +27 -0
  29. package/dist/models/mcpRequestLog.d.ts +2 -0
  30. package/dist/models/mcpRequestLog.js +73 -0
  31. package/dist/models/mcpServiceToken.js +40 -4
  32. package/dist/models/mcpToolSetting.d.ts +2 -0
  33. package/dist/models/mcpToolSetting.js +119 -0
  34. package/dist/models/versionConfig.d.ts +2 -0
  35. package/dist/openApiBuilder.d.ts +4 -0
  36. package/dist/openApiBuilder.js +2 -0
  37. package/dist/rbac/auditModel.d.ts +2 -1
  38. package/dist/rbac/realtimeAccess.d.ts +5 -4
  39. package/dist/rbac/realtimeAccess.js +17 -64
  40. package/dist/realtime/changeStreamWatcher.d.ts +8 -63
  41. package/dist/realtime/changeStreamWatcher.js +32 -391
  42. package/dist/realtime/realtimeApp.d.ts +14 -27
  43. package/dist/realtime/realtimeApp.js +14 -220
  44. package/dist/realtime/types.d.ts +0 -64
  45. package/dist/sync/executors.js +14 -2
  46. package/dist/sync/socketHandlers.d.ts +1 -1
  47. package/dist/sync/socketHandlers.js +1 -1
  48. package/dist/terrenoApp.d.ts +19 -5
  49. package/dist/terrenoApp.js +21 -14
  50. package/dist/tests/models.d.ts +17 -22
  51. package/dist/tests/models.js +7 -1
  52. package/dist/tests/openApiResponseSchema.d.ts +39 -0
  53. package/dist/tests/openApiResponseSchema.js +56 -0
  54. package/dist/tests/testHelper.d.ts +6 -12
  55. package/dist/tests.d.ts +2 -0
  56. package/dist/tests.js +6 -1
  57. package/dist/types/mcpAdmin.d.ts +58 -0
  58. package/dist/types/mcpAdmin.js +2 -0
  59. package/dist/types/mcpOAuth.d.ts +2 -0
  60. package/dist/types/mcpServiceToken.d.ts +9 -4
  61. package/dist/versionCheckPlugin.d.ts +1 -1
  62. package/dist/versionCheckPlugin.js +25 -2
  63. package/e2e/smoke.ts +193 -0
  64. package/package.json +14 -8
  65. package/src/__snapshots__/openApi.test.ts.snap +4986 -2478
  66. package/src/__snapshots__/openApiBuilder.test.ts.snap +836 -0
  67. package/src/__tests__/openApiResponseSchema.test.ts +148 -0
  68. package/src/__tests__/versionCheckPlugin.test.ts +72 -0
  69. package/src/adminModelRouter.test.ts +8 -6
  70. package/src/api.arrayOperations.test.ts +31 -22
  71. package/src/api.hooks.test.ts +12 -11
  72. package/src/api.query.test.ts +2 -2
  73. package/src/api.test.ts +17 -14
  74. package/src/api.ts +3 -27
  75. package/src/audit/auditApp.test.ts +1 -1
  76. package/src/audit/cloudTasksEnqueue.test.ts +19 -14
  77. package/src/auth.test.ts +21 -7
  78. package/src/auth.ts +116 -5
  79. package/src/authOpenApi.test.ts +316 -0
  80. package/src/authRecovery.test.ts +10 -10
  81. package/src/authRecovery.ts +47 -19
  82. package/src/authVerification.test.ts +7 -7
  83. package/src/betterAuthFeatures.test.ts +3 -2
  84. package/src/betterAuthLinking.test.ts +3 -1
  85. package/src/betterAuthOAuthHandoff.test.ts +13 -5
  86. package/src/betterAuthSetup.test.ts +77 -51
  87. package/src/collectionRegistry.test.ts +4 -4
  88. package/src/collectionRegistry.ts +3 -5
  89. package/src/consentApp.test.ts +98 -0
  90. package/src/consentApp.ts +67 -2
  91. package/src/frameworkModelNames.test.ts +8 -0
  92. package/src/frameworkModelNames.ts +4 -0
  93. package/src/githubAuth.test.ts +11 -11
  94. package/src/index.ts +14 -28
  95. package/src/isolated/migrateCliConnect.isolated.ts +3 -2
  96. package/src/mcp/actionTools.test.ts +13 -7
  97. package/src/mcp/adminTracking.test.ts +272 -0
  98. package/src/mcp/adminTracking.ts +104 -0
  99. package/src/mcp/auth.test.ts +7 -3
  100. package/src/mcp/auth.ts +18 -2
  101. package/src/mcp/oauth.test.ts +13 -13
  102. package/src/mcp/server.ts +67 -4
  103. package/src/mcp/serviceTokens.sync.test.ts +230 -0
  104. package/src/mcp/serviceTokens.test.ts +114 -62
  105. package/src/mcp/serviceTokens.ts +193 -212
  106. package/src/mcp/toolGenerator.test.ts +9 -5
  107. package/src/migrations/builtin/mcpServiceTokenStringIds.test.ts +194 -0
  108. package/src/migrations/builtin/mcpServiceTokenStringIds.ts +121 -0
  109. package/src/migrations/cli.test.ts +15 -14
  110. package/src/migrations/cli.ts +1 -1
  111. package/src/migrations/generate.test.ts +2 -2
  112. package/src/migrations/load.test.ts +1 -1
  113. package/src/migrations/lock.test.ts +8 -3
  114. package/src/migrations/runner.test.ts +16 -5
  115. package/src/migrations/schemaCatalog.test.ts +4 -1
  116. package/src/models/mcpOAuthToken.test.ts +42 -0
  117. package/src/models/mcpOAuthToken.ts +32 -0
  118. package/src/models/mcpRequestLog.ts +81 -0
  119. package/src/models/mcpServiceToken.test.ts +75 -5
  120. package/src/models/mcpServiceToken.ts +61 -14
  121. package/src/models/mcpToolSetting.test.ts +69 -0
  122. package/src/models/mcpToolSetting.ts +138 -0
  123. package/src/models/versionConfig.ts +2 -0
  124. package/src/notifications/notificationsApp.test.ts +5 -8
  125. package/src/notifiers/slackWebApi.test.ts +30 -8
  126. package/src/openApi.test.ts +4 -4
  127. package/src/openApiBuilder.test.ts +34 -1
  128. package/src/openApiBuilder.ts +5 -0
  129. package/src/openApiValidator.test.ts +3 -3
  130. package/src/orgs/orgPermissions.test.ts +2 -2
  131. package/src/orgs/orgPlugin.test.ts +4 -3
  132. package/src/orgs/orgSecurityDefects.test.ts +3 -1
  133. package/src/orgs/organizationSettings.test.ts +1 -1
  134. package/src/orgs/orgsApp.test.ts +5 -3
  135. package/src/permissions.test.ts +2 -2
  136. package/src/rateLimit/rateLimit.test.ts +25 -10
  137. package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
  138. package/src/rbac/assertAllowed.test.ts +1 -1
  139. package/src/rbac/auditModel.ts +10 -2
  140. package/src/rbac/realtimeAccess.test.ts +20 -171
  141. package/src/rbac/realtimeAccess.ts +17 -82
  142. package/src/rbac/routes.test.ts +1 -1
  143. package/src/rbac/userWriteGuards.test.ts +8 -5
  144. package/src/realtime/changeStreamWatcher.ts +43 -506
  145. package/src/realtime/realtime.test.ts +211 -2547
  146. package/src/realtime/realtimeApp.ts +16 -295
  147. package/src/realtime/types.ts +0 -72
  148. package/src/scrubAdminFields.test.ts +1 -1
  149. package/src/sync/adminWindowMutation.test.ts +4 -3
  150. package/src/sync/executors.test.ts +29 -1
  151. package/src/sync/executors.ts +23 -2
  152. package/src/sync/scripts/compactTombstones.test.ts +4 -3
  153. package/src/sync/socketHandlers.ts +1 -1
  154. package/src/sync/sync.test.ts +1 -1
  155. package/src/sync/syncPhaseC.test.ts +14 -11
  156. package/src/sync/syncRoutes.test.ts +8 -8
  157. package/src/sync/syncSeqPlugin.test.ts +1 -2
  158. package/src/sync/syncSocket.test.ts +78 -113
  159. package/src/terrenoApp.mcpServiceTokens.test.ts +16 -8
  160. package/src/terrenoApp.migrations.test.ts +8 -7
  161. package/src/terrenoApp.ts +38 -18
  162. package/src/tests/betterAuthStubs.ts +3 -2
  163. package/src/tests/bunSetup.ts +1 -1
  164. package/src/tests/models.ts +10 -0
  165. package/src/tests/openApiResponseSchema.ts +104 -0
  166. package/src/tests/testEnv.ts +7 -0
  167. package/src/tests.ts +8 -0
  168. package/src/types/mcpAdmin.ts +80 -0
  169. package/src/types/mcpOAuth.ts +5 -0
  170. package/src/types/mcpServiceToken.ts +12 -4
  171. package/src/versionCheckPlugin.ts +41 -2
  172. package/src/webhooks/verifiers/hmac.test.ts +1 -1
  173. package/tsconfig.typecheck.json +14 -0
  174. package/dist/realtime/deprecation.d.ts +0 -13
  175. package/dist/realtime/deprecation.js +0 -31
  176. package/dist/realtime/queryStore.d.ts +0 -37
  177. package/dist/realtime/queryStore.js +0 -103
  178. package/dist/realtime/registry.d.ts +0 -15
  179. package/dist/realtime/registry.js +0 -52
  180. package/src/realtime/deprecation.test.ts +0 -60
  181. package/src/realtime/deprecation.ts +0 -33
  182. package/src/realtime/queryStore.ts +0 -122
  183. package/src/realtime/registry.ts +0 -84
@@ -1,11 +1,12 @@
1
1
  import {beforeEach, describe, expect, it} from "bun:test";
2
2
  import type express from "express";
3
+ import type {Collection} from "mongodb";
3
4
  import {type Model, model, Schema} from "mongoose";
4
5
  import supertest from "supertest";
5
6
  import type TestAgent from "supertest/lib/agent";
6
- import type {ModelRouterOptions} from "../api";
7
+ import type {ModelRouterOptions, RESTMethod} from "../api";
7
8
  import {type UserModel as AuthUserModel, addAuthRoutes, setupAuth, type User} from "../auth";
8
- import {Permissions, type RESTMethod} from "../permissions";
9
+ import {Permissions} from "../permissions";
9
10
  import {createdUpdatedPlugin, type IsDeleted, isDeletedPlugin} from "../plugins";
10
11
  import {DEFAULT_IGNORED_COLLECTIONS} from "../realtime/changeStreamWatcher";
11
12
  import {authAsUser, getBaseServer, setupDb, UserModel} from "../tests";
@@ -247,7 +248,7 @@ describe("Phase C sync routes", () => {
247
248
  ownerId: notAdminId,
248
249
  title: `legacy-${String(i).padStart(4, "0")}`,
249
250
  }));
250
- await PhaseCTodoModel.collection.insertMany(legacy as unknown as PhaseCTodo[]);
251
+ await PhaseCTodoModel.collection.insertMany(legacy);
251
252
  // A couple of modern (stamped) docs after the legacy stratum.
252
253
  await PhaseCTodoModel.create({ownerId: notAdminId, title: "modern-1"});
253
254
  await PhaseCTodoModel.create({ownerId: notAdminId, title: "modern-2"});
@@ -291,7 +292,7 @@ describe("Phase C sync routes", () => {
291
292
  await PhaseCTodoModel.collection.insertMany([
292
293
  {deleted: false, ownerId: notAdminId, title: "legacy-a"},
293
294
  {deleted: false, ownerId: notAdminId, title: "legacy-b"},
294
- ] as unknown as PhaseCTodo[]);
295
+ ]);
295
296
  await PhaseCTodoModel.create({ownerId: notAdminId, title: "stamped"});
296
297
 
297
298
  const page1 = await agent
@@ -319,7 +320,7 @@ describe("Phase C sync routes", () => {
319
320
  await PhaseCTodoModel.collection.insertMany([
320
321
  {deleted: true, ownerId: notAdminId, title: "DUMMY-deleted-legacy"},
321
322
  {deleted: false, ownerId: notAdminId, title: "DUMMY-live-legacy"},
322
- ] as unknown as PhaseCTodo[]);
323
+ ]);
323
324
 
324
325
  const page = await agent
325
326
  .get(`/sync/snapshot?stream=${enc(ownerStream())}&limit=10`)
@@ -341,13 +342,15 @@ describe("Phase C sync routes", () => {
341
342
  const noteStream = `phaseCNotes|owner:${notAdminId}`;
342
343
  const total = 25;
343
344
  const limit = 10;
344
- await PhaseCNoteModel.collection.insertMany(
345
+ // The driver collection defaults to ObjectId keys; this model mints string ids.
346
+ const rawNotes = PhaseCNoteModel.collection as unknown as Collection<PhaseCNote>;
347
+ await rawNotes.insertMany(
345
348
  Array.from({length: total}, (_v, i) => ({
346
349
  _id: `note-${String(i).padStart(3, "0")}`,
347
350
  deleted: false,
348
351
  ownerId: notAdminId,
349
352
  title: `legacy note ${i}`,
350
- })) as unknown as PhaseCNote[]
353
+ }))
351
354
  );
352
355
  await PhaseCNoteModel.create({
353
356
  _id: "note-modern",
@@ -389,7 +392,7 @@ describe("Phase C sync routes", () => {
389
392
  it("Task 9.14: 400s (not 500s) on a malformed legacyCursor for an ObjectId-keyed model", async () => {
390
393
  await PhaseCTodoModel.collection.insertMany([
391
394
  {deleted: false, ownerId: notAdminId, title: "legacy-a"},
392
- ] as unknown as PhaseCTodo[]);
395
+ ]);
393
396
  await agent
394
397
  .get(`/sync/snapshot?stream=${enc(ownerStream())}&legacyCursor=not-an-object-id`)
395
398
  .expect(400);
@@ -475,7 +478,7 @@ describe("Phase C sync routes", () => {
475
478
  await PhaseCTodoModel.create({ownerId: notAdminId, title: "visible-2"});
476
479
 
477
480
  const res = await agent.get(`/sync/snapshot?stream=${enc(ownerStream())}`).expect(200);
478
- const titles = res.body.entities.map((e: SnapshotEntity) => e.data.title);
481
+ const titles = res.body.entities.map((e: SnapshotEntity) => e.data?.title);
479
482
  expect(titles).toEqual(["visible-1", "visible-2"]);
480
483
  // The cursor advanced past the denied doc (seq 3), so it is never re-fetched.
481
484
  expect(res.body.cursor).toBe(3);
@@ -496,7 +499,7 @@ describe("Phase C sync routes", () => {
496
499
  if (!doc) {
497
500
  return true;
498
501
  }
499
- return !String(doc.title).startsWith("denied-");
502
+ return !String((doc as {title?: string}).title).startsWith("denied-");
500
503
  },
501
504
  ],
502
505
  },
@@ -564,7 +567,7 @@ describe("Phase C sync routes", () => {
564
567
  // "other" is excluded by the $or filter; "mine" appears as a tombstone (data null).
565
568
  const titles = res.body.entities
566
569
  .filter((e: SnapshotEntity) => !e.deleted)
567
- .map((e: SnapshotEntity) => e.data.title)
570
+ .map((e: SnapshotEntity) => e.data?.title)
568
571
  .sort();
569
572
  expect(titles).toEqual(["shared"]);
570
573
  const tombstone = byTitle.get(String(mine._id));
@@ -95,7 +95,7 @@ interface SnapshotEntity {
95
95
  id: string;
96
96
  seq: number;
97
97
  deleted: boolean;
98
- data: {name: string} | null;
98
+ data: {name?: string; title?: string} | null;
99
99
  }
100
100
 
101
101
  interface StreamInfo {
@@ -287,7 +287,7 @@ describe("sync routes", () => {
287
287
  .expect(200);
288
288
  expect(res.body.stream).toBe(ownerStream());
289
289
  expect(res.body.entities).toHaveLength(2);
290
- expect(res.body.entities.map((e: SnapshotEntity) => e.data.name)).toEqual([
290
+ expect(res.body.entities.map((e: SnapshotEntity) => e.data?.name)).toEqual([
291
291
  "mine 1",
292
292
  "mine 2",
293
293
  ]);
@@ -349,7 +349,7 @@ describe("sync routes", () => {
349
349
  expect(page3.body.hasMore).toBe(false);
350
350
 
351
351
  const names = [...page1.body.entities, ...page2.body.entities, ...page3.body.entities].map(
352
- (e: SnapshotEntity) => e.data.name
352
+ (e: SnapshotEntity) => e.data?.name
353
353
  );
354
354
  expect(names).toEqual(["item 1", "item 2", "item 3", "item 4", "item 5"]);
355
355
  });
@@ -388,7 +388,7 @@ describe("sync routes", () => {
388
388
  clearSyncRegistry();
389
389
  registerSync({
390
390
  config: {
391
- responseHandler: (doc) => ({redactedName: `x-${(doc as RouteStuff).name}`}),
391
+ responseHandler: (doc) => ({redactedName: `x-${(doc as unknown as RouteStuff).name}`}),
392
392
  scope: {type: "owner"},
393
393
  },
394
394
  model: RouteStuffModel as unknown as Model<unknown>,
@@ -429,10 +429,10 @@ describe("sync routes", () => {
429
429
  tenantStream,
430
430
  ownerStream(),
431
431
  ]);
432
- expect(res.body.pages[0].entities.map((e: SnapshotEntity) => e.data.title)).toEqual([
432
+ expect(res.body.pages[0].entities.map((e: SnapshotEntity) => e.data?.title)).toEqual([
433
433
  "visible",
434
434
  ]);
435
- expect(res.body.pages[1].entities.map((e: SnapshotEntity) => e.data.name)).toEqual(["mine"]);
435
+ expect(res.body.pages[1].entities.map((e: SnapshotEntity) => e.data?.name)).toEqual(["mine"]);
436
436
  expect(res.body.pages[1].hasMore).toBe(false);
437
437
  expect(res.body.pages[1].cursor).toBe(res.body.pages[1].frontierSeq);
438
438
  });
@@ -457,7 +457,7 @@ describe("sync routes", () => {
457
457
  .post("/sync/snapshot/batch")
458
458
  .send({limit: 4, streams: [{cursor: ownerPage.cursor, stream: ownerStream()}]})
459
459
  .expect(200);
460
- expect(second.body.pages[0].entities.map((e: SnapshotEntity) => e.data.name)).toEqual([
460
+ expect(second.body.pages[0].entities.map((e: SnapshotEntity) => e.data?.name)).toEqual([
461
461
  "item 3",
462
462
  "item 4",
463
463
  "item 5",
@@ -1279,7 +1279,7 @@ describe("sync routes", () => {
1279
1279
  const res = await agent
1280
1280
  .get(`/sync/snapshot?stream=${encodeURIComponent(`routeStuff|owner:${notAdminId}`)}`)
1281
1281
  .expect(200);
1282
- expect(res.body.entities.map((e: SnapshotEntity) => e.data.name)).toEqual(["keep"]);
1282
+ expect(res.body.entities.map((e: SnapshotEntity) => e.data?.name)).toEqual(["keep"]);
1283
1283
  });
1284
1284
  });
1285
1285
  });
@@ -1,6 +1,5 @@
1
1
  import {beforeAll, beforeEach, describe, expect, it} from "bun:test";
2
2
  import {type Model, model, Schema} from "mongoose";
3
- import type {ModelRouterOptions} from "../api";
4
3
  import {createdUpdatedPlugin, type IsDeleted, isDeletedPlugin} from "../plugins";
5
4
  import {setupDb} from "../tests";
6
5
  import {SyncCounter, SyncScopeMove} from "./models";
@@ -85,7 +84,7 @@ const UnregisteredModel = model<SeqBroadcastThing>(
85
84
 
86
85
  const stubOptions = {
87
86
  permissions: {create: [], delete: [], list: [], read: [], update: []},
88
- } as unknown as ModelRouterOptions<SeqTenantThing>;
87
+ };
89
88
 
90
89
  const TENANT_TAG = "seqPluginTenantThings";
91
90
  const CUSTOM_TAG = "seqPluginCustomThings";
@@ -14,14 +14,13 @@ import mongoose, {type Model, model, Schema} from "mongoose";
14
14
  import type {Server} from "socket.io";
15
15
 
16
16
  import type {ModelRouterOptions} from "../api";
17
+ import {Permissions} from "../permissions";
17
18
  import {createdUpdatedPlugin, type IsDeleted, isDeletedPlugin} from "../plugins";
18
19
  import {
19
20
  emitSyncDeltaForChange,
20
21
  startChangeStreamWatcher,
21
22
  stopChangeStreamWatcher,
22
23
  } from "../realtime/changeStreamWatcher";
23
- import {addQuerySubscription, clearQueryStore, computeQueryId} from "../realtime/queryStore";
24
- import {clearRealtimeRegistry, registerRealtime} from "../realtime/registry";
25
24
  import {setupDb} from "../tests";
26
25
  import {defaultResponseHandler} from "../transformers";
27
26
  import {registerAdminBroadcastScope} from "./adminBroadcastScope";
@@ -72,6 +71,29 @@ sockStuffSchema.plugin(createdUpdatedPlugin);
72
71
  sockStuffSchema.plugin(syncPlugin);
73
72
  const SockStuffModel = model<SockStuff>("SockStuff", sockStuffSchema);
74
73
 
74
+ /** Owned through `userId`, with an `ownerId` virtual alias for `Permissions.IsOwner` (as GptHistory). */
75
+ interface SockNote extends IsDeleted {
76
+ _id: string;
77
+ text: string;
78
+ userId: string;
79
+ _syncSeq?: number;
80
+ }
81
+
82
+ const sockNoteSchema = new Schema<SockNote>(
83
+ {
84
+ text: {description: "The note text", required: true, type: String},
85
+ userId: {description: "The user who owns this note", type: String},
86
+ },
87
+ {toJSON: {virtuals: true}, toObject: {virtuals: true}}
88
+ );
89
+ sockNoteSchema.virtual("ownerId").get(function (this: SockNote) {
90
+ return this.userId;
91
+ });
92
+ sockNoteSchema.plugin(isDeletedPlugin);
93
+ sockNoteSchema.plugin(createdUpdatedPlugin);
94
+ sockNoteSchema.plugin(syncPlugin);
95
+ const SockNoteModel = model<SockNote>("SockNote", sockNoteSchema);
96
+
75
97
  interface SockProject extends IsDeleted {
76
98
  _id: string;
77
99
  title: string;
@@ -1126,6 +1148,50 @@ describe("emitSyncDeltaForChange", () => {
1126
1148
  expect((delta.data as Record<string, unknown>).id).toBe("doc-1");
1127
1149
  });
1128
1150
 
1151
+ it("checks read permissions against the model document, so virtual owner fields resolve", async () => {
1152
+ clearSyncRegistry();
1153
+ registerSync({
1154
+ config: {scope: {field: "userId", type: "owner"}},
1155
+ model: SockNoteModel as unknown as Model<unknown>,
1156
+ options: {
1157
+ permissions: {
1158
+ create: [Permissions.IsOwner],
1159
+ delete: [Permissions.IsOwner],
1160
+ list: [Permissions.IsAuthenticated],
1161
+ read: [Permissions.IsOwner],
1162
+ update: [Permissions.IsOwner],
1163
+ },
1164
+ } as unknown as ModelRouterOptions<unknown>,
1165
+ routePath: "/sock/notes",
1166
+ });
1167
+ const entry = findSyncEntryByCollectionTag("sock/notes") as SyncRegistryEntry;
1168
+ const io = makeTrackedIo();
1169
+ io.addSocketToRoom(syncRoomForStream("sock/notes|owner:user1"), {admin: false, id: "user1"});
1170
+ io.addSocketToRoom(syncRoomForStream("sock/notes|owner:user1"), {admin: false, id: "user2"});
1171
+
1172
+ await emitSyncDeltaForChange({
1173
+ change: makeChange({
1174
+ fullDocument: {_id: "note-1", _syncSeq: 3, text: "hi", userId: "user1"},
1175
+ ns: {coll: "socknotes"},
1176
+ operationType: "insert",
1177
+ }),
1178
+ docId: "note-1",
1179
+ entry,
1180
+ io,
1181
+ logDebug: () => {},
1182
+ });
1183
+
1184
+ const deltas = io.emissions.filter((e) => e.event === "sync:delta");
1185
+ expect(deltas.map((e) => e.socketId)).toHaveLength(1);
1186
+ const delta = deltas[0]?.payload as SyncDelta;
1187
+ expect(delta).toMatchObject({
1188
+ collection: "sock/notes",
1189
+ seq: 3,
1190
+ stream: "sock/notes|owner:user1",
1191
+ });
1192
+ expect((delta.data as Record<string, unknown>).text).toBe("hi");
1193
+ });
1194
+
1129
1195
  it("adminBroadcast true: create also emits to {collection}|admin", async () => {
1130
1196
  clearSyncRegistry();
1131
1197
  registerSync({
@@ -1267,7 +1333,7 @@ describe("emitSyncDeltaForChange", () => {
1267
1333
  const deltas = io.emissions.filter((e) => e.event === "sync:delta");
1268
1334
  expect(deltas).toHaveLength(1);
1269
1335
  const receiver = io.sockets.sockets.get(deltas[0].socketId);
1270
- expect(receiver.decodedToken.id).toBe("user1");
1336
+ expect(receiver?.decodedToken.id).toBe("user1");
1271
1337
  });
1272
1338
 
1273
1339
  it("C7: soft delete emits a delete delta with deleted true and NO data (tombstone stripped)", async () => {
@@ -1555,7 +1621,7 @@ describe("sync:delta — change stream integration", () => {
1555
1621
  });
1556
1622
 
1557
1623
  beforeEach(async () => {
1558
- clearRealtimeRegistry();
1624
+ clearSyncRegistry();
1559
1625
  registerAll();
1560
1626
  await Promise.all([
1561
1627
  SockStuffModel.collection.deleteMany({}),
@@ -1566,7 +1632,6 @@ describe("sync:delta — change stream integration", () => {
1566
1632
 
1567
1633
  afterEach(async () => {
1568
1634
  await stopChangeStreamWatcher();
1569
- clearRealtimeRegistry();
1570
1635
  clearSyncRegistry();
1571
1636
  });
1572
1637
 
@@ -1673,42 +1738,33 @@ describe("sync:delta — change stream integration", () => {
1673
1738
  expect((create.data as Record<string, unknown>).orgId).toBe("org2");
1674
1739
  });
1675
1740
 
1676
- it("a model with both realtime and sync configs emits both event types", async () => {
1741
+ it("never emits the legacy RTK sync event, even to legacy realtime rooms", async () => {
1677
1742
  if (!replicaSetAvailable) {
1678
1743
  return;
1679
1744
  }
1680
- registerRealtime({
1681
- collectionName: SockStuffModel.collection.collectionName,
1682
- config: {methods: ["create", "update", "delete"], roomStrategy: "model"},
1683
- modelName: "SockStuff",
1684
- options: permissiveOptions,
1685
- routePath: "/sockStuff",
1686
- });
1687
-
1688
1745
  const io = makeTrackedIo();
1689
1746
  io.addSocketToRoom("model:sockStuff", {admin: true, id: "admin"});
1690
- io.addSocketToRoom(syncRoomForStream("sockStuff|owner:both-user"), {
1747
+ io.addSocketToRoom("authenticated", {admin: true, id: "admin"});
1748
+ io.addSocketToRoom("user:legacy-user", {admin: false, id: "legacy-user"});
1749
+ io.addSocketToRoom(syncRoomForStream("sockStuff|owner:legacy-user"), {
1691
1750
  admin: false,
1692
- id: "both-user",
1751
+ id: "legacy-user",
1693
1752
  });
1694
1753
  await startWatcherAndSettle(io);
1695
1754
 
1696
- const doc = await SockStuffModel.create({name: "both", ownerId: "both-user"});
1755
+ const doc = await SockStuffModel.create({name: "legacy", ownerId: "legacy-user"});
1697
1756
  const docId = String(doc._id);
1698
1757
  await waitForDelta(io, (d) => d.id === docId);
1699
1758
 
1700
- const legacy = io.emissions.filter(
1701
- (e) => e.event === "sync" && e.payload?.id === docId && e.payload?.method === "create"
1702
- );
1703
1759
  const deltas = io.emissions.filter(
1704
1760
  (e) => e.event === "sync:delta" && (e.payload as SyncDelta).id === docId
1705
1761
  );
1706
- expect(legacy.length).toBeGreaterThanOrEqual(1);
1707
1762
  expect(deltas).toHaveLength(1);
1708
1763
  expect((deltas[0].payload as SyncDelta).seq).toBe(1);
1764
+ expect(io.emissions.filter((e) => e.event === "sync")).toHaveLength(0);
1709
1765
  });
1710
1766
 
1711
- it("a sync-only model emits deltas even without a realtime registry entry", async () => {
1767
+ it("a sync model emits deltas through its sync stream room", async () => {
1712
1768
  if (!replicaSetAvailable) {
1713
1769
  return;
1714
1770
  }
@@ -1727,94 +1783,3 @@ describe("sync:delta — change stream integration", () => {
1727
1783
  expect(io.emissions.filter((e) => e.event === "sync")).toHaveLength(0);
1728
1784
  });
1729
1785
  });
1730
-
1731
- // ─────────────────────────────────────────────────────────────────────────────
1732
- // change handler — realtime query fan-out failures stay isolated
1733
- // ─────────────────────────────────────────────────────────────────────────────
1734
-
1735
- describe("change handler isolation", () => {
1736
- let originalDb: typeof mongoose.connection.db;
1737
-
1738
- beforeAll(async () => {
1739
- await setupDb();
1740
- });
1741
-
1742
- beforeEach(() => {
1743
- originalDb = mongoose.connection.db;
1744
- clearRealtimeRegistry();
1745
- clearQueryStore();
1746
- clearSyncRegistry();
1747
- });
1748
-
1749
- afterEach(async () => {
1750
- await stopChangeStreamWatcher();
1751
- (mongoose.connection as unknown as {db: unknown}).db = originalDb;
1752
- clearRealtimeRegistry();
1753
- clearQueryStore();
1754
- clearSyncRegistry();
1755
- });
1756
-
1757
- it("an unevaluable query predicate does not block sync:delta or later query rooms", async () => {
1758
- const listeners = new Map<string, (...args: unknown[]) => unknown>();
1759
- const mockStream = {
1760
- close: async (): Promise<void> => {},
1761
- on(event: string, handler: (...args: unknown[]) => unknown) {
1762
- listeners.set(event, handler);
1763
- return this;
1764
- },
1765
- };
1766
- (mongoose.connection as unknown as {db: unknown}).db = {watch: () => mockStream};
1767
- // One registration carries both surfaces, as modelRouter does for realtime + sync.
1768
- registerSync({
1769
- config: {scope: {type: "owner"}},
1770
- model: SockStuffModel as unknown as Model<unknown>,
1771
- options: {
1772
- ...permissiveOptions,
1773
- realtime: {methods: ["create", "update", "delete"], roomStrategy: "model"},
1774
- },
1775
- routePath: "/sockStuff",
1776
- });
1777
- const poisoned = [{$and: [null]}, {name: {$eq: {toString: 1}}}] as Record<string, unknown>[];
1778
- for (const [index, query] of poisoned.entries()) {
1779
- addQuerySubscription(`attacker-${index}`, "sockStuff", query, `poisoned-${index}`);
1780
- }
1781
- const healthyQueryId = computeQueryId("sockStuff", {name: "poison-check"});
1782
- addQuerySubscription("victim", "sockStuff", {name: "poison-check"}, healthyQueryId);
1783
-
1784
- const io = makeTrackedIo();
1785
- io.addSocketToRoom(`query:${healthyQueryId}`, {admin: true, id: "admin"});
1786
- io.addSocketToRoom(syncRoomForStream("sockStuff|owner:victim-user"), {
1787
- admin: false,
1788
- id: "victim-user",
1789
- });
1790
- startChangeStreamWatcher(io, {}, true);
1791
- const changeHandler = listeners.get("change");
1792
- if (!changeHandler) {
1793
- throw new Error("expected change handler");
1794
- }
1795
-
1796
- await changeHandler(
1797
- makeChange({
1798
- documentKey: {_id: "poison-doc"},
1799
- fullDocument: {
1800
- _id: "poison-doc",
1801
- _syncSeq: 3,
1802
- name: "poison-check",
1803
- ownerId: "victim-user",
1804
- },
1805
- ns: {coll: SockStuffModel.collection.collectionName},
1806
- operationType: "insert",
1807
- })
1808
- );
1809
- await waitForDelta(io, (d) => d.id === "poison-doc", 2000);
1810
-
1811
- const deltas = io.emissions.filter(
1812
- (e) => e.event === "sync:delta" && (e.payload as SyncDelta).id === "poison-doc"
1813
- );
1814
- expect(deltas).toHaveLength(1);
1815
- const healthy = io.emissions.filter(
1816
- (e) => e.event === "sync" && e.room === `query:${healthyQueryId}`
1817
- );
1818
- expect(healthy).toHaveLength(1);
1819
- });
1820
- });
@@ -1,4 +1,4 @@
1
- import {beforeEach, describe, it} from "bun:test";
1
+ import {afterEach, beforeEach, describe, it} from "bun:test";
2
2
  import {assert} from "chai";
3
3
  import mongoose, {model, Schema} from "mongoose";
4
4
  import supertest from "supertest";
@@ -9,6 +9,7 @@ import {clearMCPRegistry} from "./mcp/registry";
9
9
  import {McpServiceToken} from "./models/mcpServiceToken";
10
10
  import {Permissions} from "./permissions";
11
11
  import {createdUpdatedPlugin} from "./plugins";
12
+ import {clearSyncRegistry} from "./sync/registry";
12
13
  import {TerrenoApp} from "./terrenoApp";
13
14
  import {authAsUser, setupDb, UserModel} from "./tests";
14
15
 
@@ -27,9 +28,9 @@ const getNoteModel = (): mongoose.Model<{title?: string}> => {
27
28
  if (mongoose.models.TokenMcpNote) {
28
29
  return mongoose.models.TokenMcpNote as mongoose.Model<{title?: string}>;
29
30
  }
30
- const schema = new Schema({title: {description: "Note title", type: String}});
31
+ const schema = new Schema<{title?: string}>({title: {description: "Note title", type: String}});
31
32
  schema.plugin(createdUpdatedPlugin);
32
- return model("TokenMcpNote", schema);
33
+ return model<{title?: string}>("TokenMcpNote", schema);
33
34
  };
34
35
 
35
36
  const TokenMcpNote = getNoteModel();
@@ -53,11 +54,15 @@ describe("TerrenoApp mcpServiceTokens", () => {
53
54
  beforeEach(async () => {
54
55
  const users = await setupDb();
55
56
  notAdminId = users[1]._id as mongoose.Types.ObjectId;
56
- await McpServiceToken.deleteMany({});
57
+ await McpServiceToken.collection.deleteMany({});
57
58
  await TokenMcpNote.deleteMany({});
58
59
  clearMCPRegistry();
59
60
  });
60
61
 
62
+ afterEach(() => {
63
+ clearSyncRegistry();
64
+ });
65
+
61
66
  it("does not serve token routes or accept mcp_ on /mcp when the flag is off", async () => {
62
67
  const app = new TerrenoApp({
63
68
  skipListen: true,
@@ -89,7 +94,7 @@ describe("TerrenoApp mcpServiceTokens", () => {
89
94
  .build();
90
95
 
91
96
  const agent = await authAsUser(app, "notAdmin");
92
- const created = await agent.post("/mcp/service-tokens").send({name: "Perplexity"});
97
+ const created = await agent.post("/mcp/service-tokens/create").send({name: "Perplexity"});
93
98
 
94
99
  assert.equal(created.status, 200);
95
100
  assert.match(created.body.data.token, /^mcp_[0-9a-f]{64}$/);
@@ -114,7 +119,7 @@ describe("TerrenoApp mcpServiceTokens", () => {
114
119
  }).build();
115
120
 
116
121
  const agent = await authAsUser(app, "notAdmin");
117
- const created = await agent.post("/mcp/service-tokens").send({name: "Named"});
122
+ const created = await agent.post("/mcp/service-tokens/create").send({name: "Named"});
118
123
 
119
124
  assert.equal(created.status, 200);
120
125
  assert.equal(created.body.data.mcpUrl, `${PUBLIC_MCP_URL}/mcp`);
@@ -128,7 +133,10 @@ describe("TerrenoApp mcpServiceTokens", () => {
128
133
  }).build();
129
134
 
130
135
  const res = await supertest(app).get("/openapi.json");
131
- assert.equal(res.body.paths["/mcp/service-tokens"].post.operationId, "createMcpServiceToken");
136
+ assert.equal(
137
+ res.body.paths["/mcp/service-tokens/create"].post.operationId,
138
+ "mcpServiceTokens_create"
139
+ );
132
140
  });
133
141
 
134
142
  it("lets a minted service token call tools as the owner while GET /mcp stays 405", async () => {
@@ -142,7 +150,7 @@ describe("TerrenoApp mcpServiceTokens", () => {
142
150
  .build();
143
151
 
144
152
  const agent = await authAsUser(app, "notAdmin");
145
- const created = await agent.post("/mcp/service-tokens").send({name: "Perplexity probe"});
153
+ const created = await agent.post("/mcp/service-tokens/create").send({name: "Perplexity probe"});
146
154
  const mcpToken = created.body.data.token as string;
147
155
 
148
156
  const jwtCall = await agent
@@ -6,17 +6,18 @@ import {join} from "node:path";
6
6
  import mongoose from "mongoose";
7
7
  import type {UserModel as UserModelType} from "./auth";
8
8
  import {runStartupMigrations} from "./migrations/runner";
9
- import {MIGRATION_LOCK_ID, MIGRATIONS_COLLECTION} from "./migrations/types";
9
+ import {MIGRATION_LOCK_ID, MIGRATIONS_COLLECTION, type MigrationStoreDoc} from "./migrations/types";
10
10
  import {TerrenoApp} from "./terrenoApp";
11
11
  import {setupDb, UserModel} from "./tests";
12
+ import {partialEnv} from "./tests/testEnv";
12
13
 
13
14
  const fixtures = (...parts: string[]): string => {
14
- return join(import.meta.dir, "migrations", "fixtures", ...parts);
15
+ return join(__dirname, "migrations", "fixtures", ...parts);
15
16
  };
16
17
 
17
18
  const appliedIds = async (): Promise<string[]> => {
18
19
  const docs = await mongoose.connection
19
- .collection(MIGRATIONS_COLLECTION)
20
+ .collection<MigrationStoreDoc>(MIGRATIONS_COLLECTION)
20
21
  .find({_id: {$ne: MIGRATION_LOCK_ID}})
21
22
  .project({id: 1})
22
23
  .toArray();
@@ -31,7 +32,7 @@ describe("runStartupMigrations", () => {
31
32
 
32
33
  it("does not run when migrations option is omitted", async () => {
33
34
  const result = await runStartupMigrations({
34
- env: {NODE_ENV: "test"},
35
+ env: partialEnv({NODE_ENV: "test"}),
35
36
  mongoose,
36
37
  });
37
38
  expect(result.ran).toBe(false);
@@ -40,7 +41,7 @@ describe("runStartupMigrations", () => {
40
41
 
41
42
  it("does not run when runOnStart is omitted", async () => {
42
43
  const result = await runStartupMigrations({
43
- env: {NODE_ENV: "test"},
44
+ env: partialEnv({NODE_ENV: "test"}),
44
45
  migrations: {dir: fixtures("valid")},
45
46
  mongoose,
46
47
  });
@@ -50,7 +51,7 @@ describe("runStartupMigrations", () => {
50
51
 
51
52
  it("applies pending files when runOnStart is true", async () => {
52
53
  const result = await runStartupMigrations({
53
- env: {NODE_ENV: "test"},
54
+ env: partialEnv({NODE_ENV: "test"}),
54
55
  migrations: {dir: fixtures("valid"), runOnStart: true},
55
56
  mongoose,
56
57
  });
@@ -62,7 +63,7 @@ describe("runStartupMigrations", () => {
62
63
  it("throws in production without ALLOW_MIGRATIONS before applying", async () => {
63
64
  await expect(
64
65
  runStartupMigrations({
65
- env: {NODE_ENV: "production"},
66
+ env: partialEnv({NODE_ENV: "production"}),
66
67
  migrations: {dir: fixtures("valid"), runOnStart: true},
67
68
  mongoose,
68
69
  })