@terreno/api 57.0.0 → 57.2.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 (175) hide show
  1. package/.ai/skills/mongoose-schema-safety/SKILL.md +8 -0
  2. package/dist/actions.d.ts +7 -2
  3. package/dist/actions.js +60 -25
  4. package/dist/adminModelRouter.d.ts +14 -0
  5. package/dist/adminModelRouter.js +199 -0
  6. package/dist/adminTypes.d.ts +182 -0
  7. package/dist/adminTypes.js +5 -0
  8. package/dist/api.d.ts +44 -3
  9. package/dist/api.js +74 -26
  10. package/dist/auth.d.ts +18 -1
  11. package/dist/auth.js +122 -20
  12. package/dist/consentApp.d.ts +2 -0
  13. package/dist/consentApp.js +98 -0
  14. package/dist/index.d.ts +22 -1
  15. package/dist/index.js +51 -7
  16. package/dist/mcp/auth.d.ts +11 -0
  17. package/dist/mcp/auth.js +133 -0
  18. package/dist/mcp/createMCPRequest.d.ts +16 -0
  19. package/dist/mcp/createMCPRequest.js +26 -0
  20. package/dist/mcp/handlers.d.ts +8 -0
  21. package/dist/mcp/handlers.js +793 -0
  22. package/dist/mcp/query.d.ts +32 -0
  23. package/dist/mcp/query.js +232 -0
  24. package/dist/mcp/registry.d.ts +21 -0
  25. package/dist/mcp/registry.js +54 -0
  26. package/dist/mcp/schemaGenerator.d.ts +14 -0
  27. package/dist/mcp/schemaGenerator.js +379 -0
  28. package/dist/mcp/server.d.ts +8 -0
  29. package/dist/mcp/server.js +133 -0
  30. package/dist/mcp/toolGenerator.d.ts +14 -0
  31. package/dist/mcp/toolGenerator.js +246 -0
  32. package/dist/mcp/types.d.ts +85 -0
  33. package/dist/mcp/types.js +2 -0
  34. package/dist/openApi.d.ts +1 -1
  35. package/dist/openApi.js +26 -8
  36. package/dist/permissions.js +15 -15
  37. package/dist/rbac/access.d.ts +3 -0
  38. package/dist/rbac/access.js +294 -0
  39. package/dist/rbac/auditModel.d.ts +31 -0
  40. package/dist/rbac/auditModel.js +112 -0
  41. package/dist/rbac/backfillAdmins.d.ts +18 -0
  42. package/dist/rbac/backfillAdmins.js +139 -0
  43. package/dist/rbac/fieldViews.d.ts +3 -0
  44. package/dist/rbac/fieldViews.js +201 -0
  45. package/dist/rbac/middleware.d.ts +21 -0
  46. package/dist/rbac/middleware.js +108 -0
  47. package/dist/rbac/modelRouterAccess.d.ts +42 -0
  48. package/dist/rbac/modelRouterAccess.js +388 -0
  49. package/dist/rbac/permissionUtils.d.ts +8 -0
  50. package/dist/rbac/permissionUtils.js +209 -0
  51. package/dist/rbac/realtimeAccess.d.ts +18 -0
  52. package/dist/rbac/realtimeAccess.js +173 -0
  53. package/dist/rbac/resolve.d.ts +28 -0
  54. package/dist/rbac/resolve.js +387 -0
  55. package/dist/rbac/roleManager.d.ts +20 -0
  56. package/dist/rbac/roleManager.js +741 -0
  57. package/dist/rbac/roleModel.d.ts +42 -0
  58. package/dist/rbac/roleModel.js +267 -0
  59. package/dist/rbac/routes.d.ts +9 -0
  60. package/dist/rbac/routes.js +211 -0
  61. package/dist/rbac/scopes.d.ts +15 -0
  62. package/dist/rbac/scopes.js +155 -0
  63. package/dist/rbac/statements.d.ts +30 -0
  64. package/dist/rbac/statements.js +126 -0
  65. package/dist/rbac/types.d.ts +202 -0
  66. package/dist/rbac/types.js +2 -0
  67. package/dist/rbac/userPlugin.d.ts +12 -0
  68. package/dist/rbac/userPlugin.js +41 -0
  69. package/dist/realtime/changeStreamWatcher.d.ts +1 -1
  70. package/dist/realtime/changeStreamWatcher.js +48 -39
  71. package/dist/realtime/realtimeApp.js +4 -8
  72. package/dist/realtime/registry.d.ts +5 -0
  73. package/dist/realtime/registry.js +13 -1
  74. package/dist/scrubAdminFields.d.ts +17 -0
  75. package/dist/scrubAdminFields.js +192 -0
  76. package/dist/sync/executors.d.ts +1 -1
  77. package/dist/sync/executors.js +63 -40
  78. package/dist/sync/loadHarness.js +4 -5
  79. package/dist/sync/registry.d.ts +5 -0
  80. package/dist/sync/registry.js +13 -1
  81. package/dist/sync/routes.js +41 -36
  82. package/dist/sync/serialize.js +5 -6
  83. package/dist/terrenoApp.d.ts +18 -0
  84. package/dist/terrenoApp.js +46 -3
  85. package/dist/terrenoPlugin.d.ts +8 -1
  86. package/dist/tests/createTestData.js +8 -0
  87. package/dist/tests/models.d.ts +1 -0
  88. package/dist/tests/models.js +5 -0
  89. package/dist/tests/testHelper.js +1 -2
  90. package/dist/transformers.js +16 -1
  91. package/package.json +17 -13
  92. package/src/__snapshots__/openApi.test.ts.snap +192 -0
  93. package/src/actions.test.ts +194 -1
  94. package/src/actions.ts +65 -8
  95. package/src/adminModelRouter.ts +154 -0
  96. package/src/adminTypes.ts +206 -0
  97. package/src/api.test.ts +66 -1
  98. package/src/api.ts +131 -12
  99. package/src/auth.test.ts +135 -1
  100. package/src/auth.ts +81 -3
  101. package/src/consentApp.test.ts +24 -0
  102. package/src/consentApp.ts +100 -0
  103. package/src/index.ts +56 -0
  104. package/src/mcp/auth.test.ts +197 -0
  105. package/src/mcp/auth.ts +100 -0
  106. package/src/mcp/createMCPRequest.test.ts +47 -0
  107. package/src/mcp/createMCPRequest.ts +32 -0
  108. package/src/mcp/customTools.test.ts +54 -0
  109. package/src/mcp/handlers.ts +639 -0
  110. package/src/mcp/integration.test.ts +1493 -0
  111. package/src/mcp/query.test.ts +172 -0
  112. package/src/mcp/query.ts +179 -0
  113. package/src/mcp/registry.ts +70 -0
  114. package/src/mcp/schemaGenerator.test.ts +182 -0
  115. package/src/mcp/schemaGenerator.ts +354 -0
  116. package/src/mcp/server.test.ts +226 -0
  117. package/src/mcp/server.ts +86 -0
  118. package/src/mcp/toolGenerator.test.ts +284 -0
  119. package/src/mcp/toolGenerator.ts +199 -0
  120. package/src/mcp/types.ts +95 -0
  121. package/src/openApi.test.ts +107 -0
  122. package/src/openApi.ts +32 -1
  123. package/src/permissions.ts +3 -2
  124. package/src/rbac/access.test.ts +357 -0
  125. package/src/rbac/access.ts +201 -0
  126. package/src/rbac/auditModel.ts +103 -0
  127. package/src/rbac/backfillAdmins.ts +54 -0
  128. package/src/rbac/fieldViews.test.ts +39 -0
  129. package/src/rbac/fieldViews.ts +122 -0
  130. package/src/rbac/middleware.ts +55 -0
  131. package/src/rbac/modelRouterAccess.test.ts +336 -0
  132. package/src/rbac/modelRouterAccess.ts +331 -0
  133. package/src/rbac/permissionUtils.test.ts +112 -0
  134. package/src/rbac/permissionUtils.ts +83 -0
  135. package/src/rbac/realtimeAccess.test.ts +242 -0
  136. package/src/rbac/realtimeAccess.ts +138 -0
  137. package/src/rbac/resolve.test.ts +358 -0
  138. package/src/rbac/resolve.ts +285 -0
  139. package/src/rbac/roleManager.test.ts +915 -0
  140. package/src/rbac/roleManager.ts +440 -0
  141. package/src/rbac/roleModel.test.ts +114 -0
  142. package/src/rbac/roleModel.ts +196 -0
  143. package/src/rbac/routes.ts +170 -0
  144. package/src/rbac/scopes.test.ts +105 -0
  145. package/src/rbac/scopes.ts +81 -0
  146. package/src/rbac/statements.test.ts +67 -0
  147. package/src/rbac/statements.ts +73 -0
  148. package/src/rbac/types.ts +198 -0
  149. package/src/rbac/userPlugin.test.ts +55 -0
  150. package/src/rbac/userPlugin.ts +25 -0
  151. package/src/realtime/changeStreamWatcher.ts +20 -15
  152. package/src/realtime/realtime.test.ts +25 -1
  153. package/src/realtime/realtimeApp.ts +2 -5
  154. package/src/realtime/registry.ts +15 -0
  155. package/src/scrubAdminFields.test.ts +113 -0
  156. package/src/scrubAdminFields.ts +158 -0
  157. package/src/sync/executors.ts +31 -1
  158. package/src/sync/loadHarness.ts +8 -7
  159. package/src/sync/models.test.ts +262 -0
  160. package/src/sync/registry.ts +15 -0
  161. package/src/sync/routes.ts +25 -11
  162. package/src/sync/scripts/compactTombstones.test.ts +4 -6
  163. package/src/sync/serialize.ts +17 -9
  164. package/src/sync/sync.test.ts +52 -0
  165. package/src/sync/syncRoutes.test.ts +5 -2
  166. package/src/sync/syncSocket.test.ts +28 -0
  167. package/src/terrenoApp.test.ts +100 -0
  168. package/src/terrenoApp.ts +65 -3
  169. package/src/terrenoPlugin.ts +10 -1
  170. package/src/tests/bunSetup.ts +2 -0
  171. package/src/tests/createTestData.ts +5 -1
  172. package/src/tests/models.ts +6 -0
  173. package/src/tests/testHelper.ts +1 -3
  174. package/src/transformers.test.ts +12 -0
  175. package/src/transformers.ts +7 -1
@@ -1,10 +1,15 @@
1
- // noExplicitAny: serialization operates generically across registered models
2
- // biome-ignore-all lint/suspicious/noExplicitAny: serialization operates generically across registered models
3
1
  import type express from "express";
2
+ import type {Document} from "mongoose";
4
3
 
5
4
  import type {SyncRegistryEntry} from "./registry";
6
5
  import type {SyncMutationOperation} from "./types";
7
6
 
7
+ /** Optional Mongoose serialization hooks a payload may or may not carry. */
8
+ interface MaybeHydratedDoc {
9
+ toObject?: () => Record<string, unknown>;
10
+ toJSON?: () => unknown;
11
+ }
12
+
8
13
  /**
9
14
  * Shared serializer for sync payloads (snapshot entities, conflict server docs, and
10
15
  * change-stream deltas), applying the fallback chain:
@@ -27,10 +32,8 @@ export const serializeSyncPayload = async ({
27
32
  method?: SyncMutationOperation;
28
33
  req: express.Request;
29
34
  }): Promise<unknown> => {
30
- const plain =
31
- typeof (doc as any).toObject === "function"
32
- ? ((doc as any).toObject() as Record<string, unknown>)
33
- : doc;
35
+ const maybeHydrated = doc as MaybeHydratedDoc;
36
+ const plain = typeof maybeHydrated.toObject === "function" ? maybeHydrated.toObject() : doc;
34
37
  if (entry.config.responseHandler) {
35
38
  return entry.config.responseHandler(plain, method);
36
39
  }
@@ -39,10 +42,15 @@ export const serializeSyncPayload = async ({
39
42
  // modelRouter responseHandler must run with single-entity `"read"` semantics — not
40
43
  // the hardcoded `"list"`, which can trigger list-only shaping (field trimming, array
41
44
  // wrapping) that corrupts a single-doc payload.
42
- return entry.options.responseHandler(doc as any, "read", req, entry.options);
45
+ return entry.options.responseHandler(
46
+ doc as unknown as Document<unknown, unknown, unknown>,
47
+ "read",
48
+ req,
49
+ entry.options
50
+ );
43
51
  }
44
- if (typeof (doc as any).toJSON === "function") {
45
- return (doc as any).toJSON();
52
+ if (typeof maybeHydrated.toJSON === "function") {
53
+ return maybeHydrated.toJSON();
46
54
  }
47
55
  return plain;
48
56
  };
@@ -3,6 +3,7 @@
3
3
  import {beforeAll, beforeEach, describe, expect, it} from "bun:test";
4
4
  import {model, Schema} from "mongoose";
5
5
  import {type ModelRouterOptions, modelRouter} from "../api";
6
+ import {Permissions} from "../permissions";
6
7
  import {createdUpdatedPlugin, type IsDeleted, isDeletedPlugin} from "../plugins";
7
8
  import {setupDb} from "../tests";
8
9
  import {
@@ -18,6 +19,7 @@ import {
18
19
  findSyncEntryByModelName,
19
20
  getSyncRegistry,
20
21
  registerSync,
22
+ updateSyncRegistryOptions,
21
23
  warnOnSyncScopesWithoutUserModel,
22
24
  } from "./registry";
23
25
  import {
@@ -244,6 +246,20 @@ describe("registerSync validation", () => {
244
246
  expect(findSyncEntryByCollectionTag("syncStuff")?.modelName).toBe("SyncStuff");
245
247
  });
246
248
 
249
+ it("updateSyncRegistryOptions replaces options on an existing entry", () => {
250
+ registerStuff();
251
+ const updatedOptions = {permissions: {list: []}} as ModelRouterOptions<unknown>;
252
+ updateSyncRegistryOptions("/syncStuff", updatedOptions);
253
+ expect(getSyncRegistry()[0]?.options).toBe(updatedOptions);
254
+ });
255
+
256
+ it("updateSyncRegistryOptions no-ops when the route path is not registered", () => {
257
+ registerStuff();
258
+ const originalOptions = getSyncRegistry()[0]?.options;
259
+ updateSyncRegistryOptions("/missing", {permissions: {}} as ModelRouterOptions<unknown>);
260
+ expect(getSyncRegistry()[0]?.options).toBe(originalOptions);
261
+ });
262
+
247
263
  it("makes bulkWrite throw on the registered model (it bypasses every plugin guard)", () => {
248
264
  registerStuff();
249
265
  expect(() =>
@@ -295,6 +311,42 @@ describe("modelRouter sync option", () => {
295
311
  modelRouter(SyncStuffModel as any, {...stubOptions, sync: ownerConfig});
296
312
  expect(findSyncEntryByCollectionTag("syncStuff")).toBeUndefined();
297
313
  });
314
+
315
+ it("refreshes sync registry options when rebuilt with accessControl", () => {
316
+ const registration = modelRouter("/syncStuff", SyncStuffModel, {
317
+ access: {resource: "syncStuff"},
318
+ permissions: {
319
+ create: [Permissions.IsAny],
320
+ delete: [Permissions.IsAny],
321
+ list: [Permissions.IsAny],
322
+ read: [Permissions.IsAny],
323
+ update: [Permissions.IsAny],
324
+ },
325
+ sync: ownerConfig,
326
+ });
327
+ const before = findSyncEntryByCollectionTag("syncStuff")?.options.permissions.list;
328
+ expect(before).toEqual([Permissions.IsAny]);
329
+
330
+ const accessControl = {
331
+ can: async (): Promise<{allowed: boolean}> => ({allowed: true}),
332
+ fieldMask: async (): Promise<{omit: string[]; read: "*"; write: "*"}> => ({
333
+ omit: [],
334
+ read: "*",
335
+ write: "*",
336
+ }),
337
+ queryFilter: async (): Promise<Record<string, unknown>> => ({}),
338
+ statements: {syncStuff: ["list", "read", "create", "update", "delete"]},
339
+ };
340
+ (
341
+ registration as {_buildWithContext: (context: {accessControl: unknown}) => unknown}
342
+ )._buildWithContext({
343
+ accessControl,
344
+ });
345
+
346
+ const after = findSyncEntryByCollectionTag("syncStuff");
347
+ expect(after?.options.accessControl).toBe(accessControl);
348
+ expect(after?.options.permissions.list).not.toBe(before);
349
+ });
298
350
  });
299
351
 
300
352
  describe("syncPlugin seq stamping", () => {
@@ -413,10 +413,13 @@ describe("sync routes", () => {
413
413
 
414
414
  const loaded = await RouteProjectModel.findById(legacyId);
415
415
  expect(loaded?.title).toBe("legacy row");
416
+ if (!loaded) {
417
+ throw new Error("Expected legacy row to load");
418
+ }
416
419
 
417
420
  // Writing it, however, is still refused until the tenant field is supplied.
418
- loaded!.title = "renamed";
419
- await expect(loaded!.save()).rejects.toThrow(/missing tenant scope field "orgId"/);
421
+ loaded.title = "renamed";
422
+ await expect(loaded.save()).rejects.toThrow(/missing tenant scope field "orgId"/);
420
423
  });
421
424
 
422
425
  // A query-write can strip the tenant field off a document that already has one. The
@@ -22,6 +22,7 @@ import {
22
22
  } from "../realtime/changeStreamWatcher";
23
23
  import {clearRealtimeRegistry, registerRealtime} from "../realtime/registry";
24
24
  import {setupDb} from "../tests";
25
+ import {defaultResponseHandler} from "../transformers";
25
26
  import {SyncCounter, SyncMutation, SyncScopeMove} from "./models";
26
27
  import {MAX_SYNC_MUTATIONS_PER_BATCH} from "./mutationHandler";
27
28
  import {
@@ -995,6 +996,33 @@ describe("emitSyncDeltaForChange", () => {
995
996
  expect((delta.data as any).id).toBe("doc-1");
996
997
  });
997
998
 
999
+ it("emits a delta when the REST responseHandler serializes a BSON post-image", async () => {
1000
+ const entry = ownerEntry();
1001
+ entry.options = {
1002
+ ...ownerReadOptions,
1003
+ responseHandler: defaultResponseHandler as never,
1004
+ };
1005
+ const io = makeTrackedIo();
1006
+ io.addSocketToRoom(syncRoomForStream("sockStuff|owner:user1"), {admin: false, id: "user1"});
1007
+
1008
+ await emitSyncDeltaForChange({
1009
+ change: makeChange({
1010
+ fullDocument: {_id: "doc-bson", _syncSeq: 4, name: "from-change-stream", ownerId: "user1"},
1011
+ operationType: "insert",
1012
+ }),
1013
+ docId: "doc-bson",
1014
+ entry,
1015
+ io,
1016
+ logDebug: () => {},
1017
+ });
1018
+
1019
+ const deltas = io.emissions.filter((emission) => emission.event === "sync:delta");
1020
+ expect(deltas).toHaveLength(1);
1021
+ expect((deltas[0].payload as SyncDelta).data as {name?: string}).toMatchObject({
1022
+ name: "from-change-stream",
1023
+ });
1024
+ });
1025
+
998
1026
  it("does not emit to sockets whose read permission fails (owner isolation)", async () => {
999
1027
  const entry = ownerEntry();
1000
1028
  const io = makeTrackedIo();
@@ -329,6 +329,106 @@ describe("TerrenoApp", () => {
329
329
  });
330
330
  });
331
331
 
332
+ describe("plugin register context", () => {
333
+ it("passes TerrenoApp as the third register argument", async () => {
334
+ let receivedTerrenoApp: TerrenoApp | undefined;
335
+ const plugin: TerrenoPlugin = {
336
+ register(_app, _openApi, terrenoApp) {
337
+ receivedTerrenoApp = terrenoApp;
338
+ },
339
+ };
340
+
341
+ const terrenoApp = new TerrenoApp({
342
+ skipListen: true,
343
+ userModel: typedUserModel,
344
+ }).register(plugin);
345
+
346
+ terrenoApp.build();
347
+ expect(receivedTerrenoApp).toBe(terrenoApp);
348
+ });
349
+
350
+ it("exposes registrations and plugins", () => {
351
+ const plugin: TerrenoPlugin = {
352
+ register() {},
353
+ };
354
+ const foodRegistration = modelRouter("/food", FoodModel, {
355
+ permissions: {
356
+ create: [Permissions.IsAny],
357
+ delete: [Permissions.IsAny],
358
+ list: [Permissions.IsAny],
359
+ read: [Permissions.IsAny],
360
+ update: [Permissions.IsAny],
361
+ },
362
+ });
363
+
364
+ const terrenoApp = new TerrenoApp({
365
+ skipListen: true,
366
+ userModel: typedUserModel,
367
+ })
368
+ .register(foodRegistration)
369
+ .register(plugin);
370
+
371
+ expect(terrenoApp.getRegistrations()).toHaveLength(2);
372
+ expect(terrenoApp.getPlugins()).toEqual([plugin]);
373
+ });
374
+ });
375
+
376
+ describe("admin model change events", () => {
377
+ beforeEach(async () => {
378
+ await setupDb();
379
+ });
380
+
381
+ it("emits admin:model.changed when admin.realtime is enabled", async () => {
382
+ const [admin] = await setupDb();
383
+ const events: import("./adminTypes").AdminChangeEvent[] = [];
384
+ const terrenoApp = new TerrenoApp({
385
+ skipListen: true,
386
+ userModel: typedUserModel,
387
+ });
388
+
389
+ terrenoApp.on("admin:model.changed", (event) => {
390
+ events.push(event);
391
+ });
392
+
393
+ const foodRegistration = modelRouter("/food", FoodModel, {
394
+ admin: {
395
+ displayName: "Food",
396
+ hiddenFields: ["tags"],
397
+ listFields: ["name"],
398
+ realtime: true,
399
+ },
400
+ permissions: {
401
+ create: [Permissions.IsAny],
402
+ delete: [Permissions.IsAny],
403
+ list: [Permissions.IsAny],
404
+ read: [Permissions.IsAny],
405
+ update: [Permissions.IsAny],
406
+ },
407
+ });
408
+
409
+ const app = terrenoApp.register(foodRegistration).build();
410
+ const agent = await authAsUser(app, "admin");
411
+
412
+ await agent
413
+ .post("/food")
414
+ .send({
415
+ calories: 10,
416
+ likesIds: [],
417
+ name: "Apple",
418
+ ownerId: admin._id,
419
+ tags: ["fruit"],
420
+ })
421
+ .expect(201);
422
+
423
+ expect(events).toHaveLength(1);
424
+ expect(events[0]?.type).toBe("create");
425
+ expect(events[0]?.routePath).toBe("/food");
426
+ expect(events[0]?.document).toEqual(expect.objectContaining({calories: 10, name: "Apple"}));
427
+ const emittedDocument = events[0]?.document as Record<string, unknown> | undefined;
428
+ expect(emittedDocument?.tags).toBeUndefined();
429
+ });
430
+ });
431
+
332
432
  describe("modelRouter overload", () => {
333
433
  it("returns ModelRouterRegistration when path is provided", () => {
334
434
  const result = modelRouter("/food", FoodModel, {
package/src/terrenoApp.ts CHANGED
@@ -1,10 +1,13 @@
1
+ import {EventEmitter} from "node:events";
1
2
  import {createServer} from "node:http";
2
3
  import * as Sentry from "@sentry/bun";
3
4
  import cors from "cors";
4
5
  import express from "express";
5
6
  import qs from "qs";
7
+ import type {AdminChangeEvent, TerrenoAppAdminEvent} from "./adminTypes";
6
8
  import type {ModelRouterRegistration} from "./api";
7
9
  import {addAuthRoutes, addMeRoutes, setupAuth, type UserModel as UserMongooseModel} from "./auth";
10
+ import type {BetterAuthInstance} from "./betterAuthSetup";
8
11
  import {ConfigurationApp, type ConfigurationAppOptions} from "./configurationApp";
9
12
  import {
10
13
  apiErrorMiddleware,
@@ -14,6 +17,7 @@ import {
14
17
  import {type AddRoutes, type AuthOptions, logRequests} from "./expressServer";
15
18
  import {addGitHubAuthRoutes, type GitHubAuthOptions, setupGitHubAuth} from "./githubAuth";
16
19
  import {type LoggingOptions, logger, setupLogging} from "./logger";
20
+ import {mountMCPServer} from "./mcp/server";
17
21
  import {jsonResponseRequestIdMiddleware} from "./middleware";
18
22
  import {openApiCompatMiddleware, patchAppUse} from "./openApiCompat";
19
23
  import {openApiEtagMiddleware} from "./openApiEtag";
@@ -28,6 +32,11 @@ import {ensureSyncIndexes} from "./sync/registry";
28
32
  import type {TerrenoPlugin} from "./terrenoPlugin";
29
33
  import openapi from "./vendor/wesleytodd-openapi/index";
30
34
 
35
+ /** A registered plugin that exposes a Better Auth instance, e.g. BetterAuthApp. */
36
+ interface BetterAuthProvider {
37
+ getAuth: () => BetterAuthInstance | undefined;
38
+ }
39
+
31
40
  type CorsOrigin =
32
41
  | string
33
42
  | boolean
@@ -70,6 +79,10 @@ export interface TerrenoAppOptions {
70
79
  * Set to `true` for defaults, or pass a RealtimeAppOptions object for full control.
71
80
  */
72
81
  realtime?: boolean | RealtimeAppOptions;
82
+ /**
83
+ * RBAC access controller injected into model routers and `/auth/me` enrichment.
84
+ */
85
+ accessControl?: import("./rbac/types").AnyTerrenoAccess;
73
86
  /**
74
87
  * Runs after CORS and before the `addMiddleware` chain and JSON body parsing.
75
88
  * Use to attach early middleware via `app.use(...)` before JSON parsing.
@@ -149,6 +162,7 @@ export class TerrenoApp {
149
162
  private registrations: (ModelRouterRegistration | TerrenoPlugin)[] = [];
150
163
  private middlewareFns: (express.RequestHandler | ((app: express.Application) => void))[] = [];
151
164
  private configurationApp: ConfigurationApp | null = null;
165
+ private readonly adminEvents = new EventEmitter();
152
166
 
153
167
  /**
154
168
  * Create a new TerrenoApp builder.
@@ -157,6 +171,7 @@ export class TerrenoApp {
157
171
  */
158
172
  constructor(options: TerrenoAppOptions) {
159
173
  this.options = options;
174
+ this.adminEvents.setMaxListeners(50);
160
175
  }
161
176
 
162
177
  /**
@@ -184,6 +199,37 @@ export class TerrenoApp {
184
199
  return this;
185
200
  }
186
201
 
202
+ /**
203
+ * Returns registered model routers and plugins in mount order.
204
+ */
205
+ getRegistrations(): readonly (ModelRouterRegistration | TerrenoPlugin)[] {
206
+ return this.registrations;
207
+ }
208
+
209
+ /**
210
+ * Returns only TerrenoPlugin registrations (excludes model routers).
211
+ */
212
+ getPlugins(): TerrenoPlugin[] {
213
+ return this.registrations.filter(
214
+ (registration): registration is TerrenoPlugin => !this.isModelRouterRegistration(registration)
215
+ );
216
+ }
217
+
218
+ on(event: TerrenoAppAdminEvent, listener: (payload: AdminChangeEvent) => void): this {
219
+ this.adminEvents.on(event, listener);
220
+ return this;
221
+ }
222
+
223
+ off(event: TerrenoAppAdminEvent, listener: (payload: AdminChangeEvent) => void): this {
224
+ this.adminEvents.off(event, listener);
225
+ return this;
226
+ }
227
+
228
+ /** @internal Emits scrubbed admin model change events from modelRouter hooks. */
229
+ emitAdminModelChanged(payload: AdminChangeEvent): void {
230
+ this.adminEvents.emit("admin:model.changed", payload);
231
+ }
232
+
187
233
  /**
188
234
  * Add custom Express middleware to the application.
189
235
  *
@@ -365,20 +411,36 @@ export class TerrenoApp {
365
411
  // Mount registered model routers and plugins
366
412
  for (const registration of this.registrations) {
367
413
  if (this.isModelRouterRegistration(registration)) {
368
- const router = registration._buildWithOpenApi(oapi);
414
+ const router = registration._buildWithContext({
415
+ accessControl: options.accessControl,
416
+ openApi: oapi,
417
+ routePath: registration.path,
418
+ terrenoApp: this,
419
+ });
369
420
  app.use(registration.path, router);
370
421
  } else {
371
- registration.register(app, oapi);
422
+ registration.register(app, oapi, this);
372
423
  }
373
424
  }
374
425
 
426
+ // Mount MCP at POST /mcp when any model opted in or a custom tool was registered.
427
+ const betterAuthPlugin = this.registrations.find(
428
+ (registration) =>
429
+ "getAuth" in registration &&
430
+ typeof (registration as Partial<BetterAuthProvider>).getAuth === "function"
431
+ ) as BetterAuthProvider | undefined;
432
+ mountMCPServer(app, {
433
+ betterAuth: betterAuthPlugin?.getAuth(),
434
+ userModel: options.userModel,
435
+ });
436
+
375
437
  if (options.configureApp) {
376
438
  options.configureApp(app, {openApi: oapi});
377
439
  }
378
440
 
379
441
  // /auth/me must be registered after plugins so that session middleware
380
442
  // (e.g. Better Auth) has a chance to populate req.user first.
381
- addMeRoutes(app, options.userModel, options.authOptions);
443
+ addMeRoutes(app, options.userModel, options.authOptions, options.accessControl);
382
444
 
383
445
  Sentry.setupExpressErrorHandler(app);
384
446
 
@@ -1,6 +1,9 @@
1
1
  import type http from "node:http";
2
2
  import type express from "express";
3
3
 
4
+ import type {AdminContribution} from "./adminTypes";
5
+ import type {TerrenoApp} from "./terrenoApp";
6
+
4
7
  /**
5
8
  * Interface for plugins that can be registered with TerrenoApp.
6
9
  *
@@ -36,7 +39,7 @@ export interface TerrenoPlugin {
36
39
  *
37
40
  * @param app - The Express application instance to register with
38
41
  */
39
- register(app: express.Application, openApi?: unknown): void;
42
+ register(app: express.Application, openApi?: unknown, terrenoApp?: TerrenoApp): void;
40
43
 
41
44
  /**
42
45
  * Called after the HTTP server is created but before it starts listening.
@@ -48,4 +51,10 @@ export interface TerrenoPlugin {
48
51
  * @param server - The Node.js HTTP server instance
49
52
  */
50
53
  onServerCreated?(server: http.Server): void;
54
+
55
+ /**
56
+ * Optional admin metadata for {@link AdminApp} aggregation.
57
+ * Called during admin plugin registration to collect models, screens, widgets, and scripts.
58
+ */
59
+ adminContribution?(): AdminContribution;
51
60
  }
@@ -21,6 +21,7 @@ if (useFixtureCache) {
21
21
  },
22
22
  silenceLogs,
23
23
  testEnv: {
24
+ extra: {USE_SENTRY_LOGGING: "false"},
24
25
  tokenIssuer: "terreno-api.test",
25
26
  },
26
27
  useTransactions: true,
@@ -29,6 +30,7 @@ if (useFixtureCache) {
29
30
  registerSimpleMongoPreload({
30
31
  silenceLogs,
31
32
  testEnv: {
33
+ extra: {USE_SENTRY_LOGGING: "false"},
32
34
  tokenIssuer: "terreno-api.test",
33
35
  },
34
36
  });
@@ -1,9 +1,11 @@
1
1
  import {DateTime} from "luxon";
2
- import type {HydratedDocument} from "mongoose";
2
+ import mongoose, {type HydratedDocument} from "mongoose";
3
3
  import type {PassportLocalMongooseDocument} from "passport-local-mongoose";
4
4
 
5
5
  import {APIError} from "../errors";
6
6
  import {logger} from "../logger";
7
+ import {createRbacAuditModel} from "../rbac/auditModel";
8
+ import {createRbacRoleModel} from "../rbac/roleModel";
7
9
  import {FoodModel, RequiredModel, type User, UserModel} from "./models";
8
10
  import type {CachedTestData, TestData, TestFoods, TestRequired, TestUsers} from "./types";
9
11
 
@@ -17,6 +19,8 @@ export const clearTestCollections = async (): Promise<void> => {
17
19
  UserModel.deleteMany({}),
18
20
  FoodModel.deleteMany({}),
19
21
  RequiredModel.deleteMany({}),
22
+ createRbacRoleModel(mongoose.connection).deleteMany({}),
23
+ createRbacAuditModel(mongoose.connection).deleteMany({}),
20
24
  ]).catch(logger.catch);
21
25
  };
22
26
 
@@ -10,6 +10,7 @@ export interface User {
10
10
  email: string;
11
11
  age?: number;
12
12
  disabled?: boolean;
13
+ organizationIds?: string[];
13
14
  }
14
15
 
15
16
  export interface SuperUser extends User {
@@ -57,6 +58,11 @@ const userSchema = new Schema<User>({
57
58
  admin: {default: false, description: "Whether the user has admin privileges", type: Boolean},
58
59
  age: {description: "The user's age", type: Number},
59
60
  name: {description: "The user's display name", type: String},
61
+ organizationIds: {
62
+ default: [],
63
+ description: "Organization memberships",
64
+ type: [String],
65
+ },
60
66
  username: {description: "The user's username", type: String},
61
67
  });
62
68
 
@@ -2,7 +2,6 @@ import {ensureTestMongooseConnected} from "@terreno/test";
2
2
 
3
3
  import {logger} from "../logger";
4
4
  import {clearTestCollections, createTestData, createTestUsers} from "./createTestData";
5
- import {FoodModel, UserModel} from "./models";
6
5
  import {loadTestData} from "./mongoTestSetup";
7
6
  import type {TestData} from "./types";
8
7
 
@@ -27,8 +26,7 @@ const ensureConnected = async (): Promise<void> => {
27
26
  /** Seeds only the standard users (legacy helper). */
28
27
  export const setupDb = async () => {
29
28
  await ensureConnected();
30
-
31
- await Promise.all([UserModel.deleteMany({}), FoodModel.deleteMany({})]).catch(logger.catch);
29
+ await clearTestCollections();
32
30
 
33
31
  try {
34
32
  const users = await createTestUsers();
@@ -225,6 +225,18 @@ describe("transform (deprecated helper)", () => {
225
225
  });
226
226
 
227
227
  describe("defaultResponseHandler", () => {
228
+ it("serializes change-stream BSON documents that have no toObject", async () => {
229
+ const options = {permissions: {}} as ModelRouterOptions<Food>;
230
+ const req = {} as express.Request;
231
+ const bsonDoc = {_id: "abc", name: "Pear"} as unknown as Document<unknown, unknown, unknown> &
232
+ Food;
233
+ const result = (await defaultResponseHandler(bsonDoc, "read", req, options)) as Food & {
234
+ id: string;
235
+ };
236
+ expect(result.name).toBe("Pear");
237
+ expect(result.id).toBe("abc");
238
+ });
239
+
228
240
  it("returns null when doc is null", async () => {
229
241
  const options = {permissions: {}} as ModelRouterOptions<Food>;
230
242
  const req = {} as express.Request;
@@ -123,7 +123,13 @@ export const serialize = <T>(
123
123
  serializeData: Document<unknown, unknown, unknown> & T,
124
124
  serializeUser?: User
125
125
  ) => {
126
- const dataObject = serializeData.toObject() as T;
126
+ // Change-stream post-images are plain BSON objects (no toObject). Calling
127
+ // toObject on them throws and used to drop every sync:delta / realtime emit.
128
+ const dataObject = (
129
+ typeof serializeData.toObject === "function"
130
+ ? serializeData.toObject()
131
+ : {...(serializeData as unknown as Record<string, unknown>)}
132
+ ) as T;
127
133
  (dataObject as unknown as {id: unknown}).id = serializeData._id;
128
134
 
129
135
  // Search for any value that is a Map and transform it to a plain object.