@terreno/api 57.3.0 → 57.4.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 (293) hide show
  1. package/.ai/skills/mongoose-schema-safety/SKILL.md +23 -10
  2. package/README.md +6 -0
  3. package/dist/adminTypes.d.ts +7 -0
  4. package/dist/adminTypes.js +6 -1
  5. package/dist/api.d.ts +10 -0
  6. package/dist/api.js +99 -36
  7. package/dist/audit/auditApp.d.ts +30 -0
  8. package/dist/audit/auditApp.js +155 -0
  9. package/dist/audit/auditEventModel.d.ts +29 -0
  10. package/dist/audit/auditEventModel.js +102 -0
  11. package/dist/audit/cloudTasksEnqueue.d.ts +32 -0
  12. package/dist/audit/cloudTasksEnqueue.js +162 -0
  13. package/dist/audit/diff.d.ts +10 -0
  14. package/dist/audit/diff.js +230 -0
  15. package/dist/audit/processQueue.d.ts +6 -0
  16. package/dist/audit/processQueue.js +101 -0
  17. package/dist/audit/rbacSink.d.ts +2 -0
  18. package/dist/audit/rbacSink.js +82 -0
  19. package/dist/audit/record.d.ts +56 -0
  20. package/dist/audit/record.js +373 -0
  21. package/dist/betterAuth.d.ts +6 -0
  22. package/dist/betterAuthSetup.js +1 -1
  23. package/dist/collectionRegistry.d.ts +3 -1
  24. package/dist/collectionRegistry.js +25 -0
  25. package/dist/index.d.ts +26 -1
  26. package/dist/index.js +48 -2
  27. package/dist/mcp/query.d.ts +0 -13
  28. package/dist/mcp/query.js +8 -8
  29. package/dist/migrations/fixtures/all-down/20260910120000-one.d.ts +4 -0
  30. package/dist/migrations/fixtures/all-down/20260910120000-one.js +49 -0
  31. package/dist/migrations/fixtures/all-down/20260910120001-two.d.ts +4 -0
  32. package/dist/migrations/fixtures/all-down/20260910120001-two.js +49 -0
  33. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.d.ts +3 -0
  34. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.js +45 -0
  35. package/dist/migrations/fixtures/bad-name/not-a-migration.d.ts +3 -0
  36. package/dist/migrations/fixtures/bad-name/not-a-migration.js +45 -0
  37. package/dist/migrations/fixtures/missing-up/20260910120000-noup.d.ts +2 -0
  38. package/dist/migrations/fixtures/missing-up/20260910120000-noup.js +5 -0
  39. package/dist/migrations/fixtures/valid/20260910120000-alpha.d.ts +3 -0
  40. package/dist/migrations/fixtures/valid/20260910120000-alpha.js +45 -0
  41. package/dist/migrations/fixtures/valid/20260910120001-beta.d.ts +4 -0
  42. package/dist/migrations/fixtures/valid/20260910120001-beta.js +49 -0
  43. package/dist/migrations/generate.d.ts +17 -0
  44. package/dist/migrations/generate.js +277 -0
  45. package/dist/migrations/load.d.ts +20 -0
  46. package/dist/migrations/load.js +236 -0
  47. package/dist/migrations/lock.d.ts +13 -0
  48. package/dist/migrations/lock.js +145 -0
  49. package/dist/migrations/runner.d.ts +42 -0
  50. package/dist/migrations/runner.js +503 -0
  51. package/dist/migrations/schemaCatalog.d.ts +44 -0
  52. package/dist/migrations/schemaCatalog.js +326 -0
  53. package/dist/migrations/types.d.ts +87 -0
  54. package/dist/migrations/types.js +7 -0
  55. package/dist/models/notification.d.ts +2 -0
  56. package/dist/models/notification.js +62 -0
  57. package/dist/models/notificationPreference.d.ts +2 -0
  58. package/dist/models/notificationPreference.js +49 -0
  59. package/dist/notifications/notificationService.d.ts +40 -0
  60. package/dist/notifications/notificationService.js +323 -0
  61. package/dist/notifications/notificationsApp.d.ts +18 -0
  62. package/dist/notifications/notificationsApp.js +250 -0
  63. package/dist/notifications/notificationsBeforeSend.d.ts +14 -0
  64. package/dist/notifications/notificationsBeforeSend.js +77 -0
  65. package/dist/openApi.d.ts +1 -7
  66. package/dist/openApi.js +7 -6
  67. package/dist/openApiBuilder.d.ts +14 -3
  68. package/dist/openApiValidator.d.ts +13 -1
  69. package/dist/openApiValidator.js +200 -36
  70. package/dist/orgs/orgContext.d.ts +23 -0
  71. package/dist/orgs/orgContext.js +198 -0
  72. package/dist/orgs/orgPermissions.d.ts +4 -0
  73. package/dist/orgs/orgPermissions.js +77 -0
  74. package/dist/orgs/orgPlugin.d.ts +13 -0
  75. package/dist/orgs/orgPlugin.js +84 -0
  76. package/dist/orgs/organizationModel.d.ts +13 -0
  77. package/dist/orgs/organizationModel.js +301 -0
  78. package/dist/orgs/organizationSettings.d.ts +19 -0
  79. package/dist/orgs/organizationSettings.js +120 -0
  80. package/dist/orgs/orgsApp.d.ts +28 -0
  81. package/dist/orgs/orgsApp.js +678 -0
  82. package/dist/permissions.d.ts +7 -13
  83. package/dist/permissions.js +8 -31
  84. package/dist/rateLimit/middleware.d.ts +0 -8
  85. package/dist/rateLimit/middleware.js +2 -3
  86. package/dist/rateLimit/mongoStore.d.ts +1 -0
  87. package/dist/rateLimit/mongoStore.js +1 -0
  88. package/dist/rateLimit/policies.d.ts +0 -4
  89. package/dist/rateLimit/policies.js +5 -7
  90. package/dist/rateLimit/redisStore.d.ts +1 -0
  91. package/dist/rateLimit/redisStore.js +1 -0
  92. package/dist/rbac/access.js +30 -13
  93. package/dist/rbac/membershipOrgAdminSource.d.ts +6 -0
  94. package/dist/rbac/membershipOrgAdminSource.js +122 -0
  95. package/dist/rbac/modelRouterAccess.d.ts +3 -0
  96. package/dist/rbac/modelRouterAccess.js +3 -0
  97. package/dist/rbac/resolve.js +60 -31
  98. package/dist/rbac/roleModel.d.ts +2 -5
  99. package/dist/rbac/roleModel.js +18 -4
  100. package/dist/rbac/statements.d.ts +10 -1
  101. package/dist/rbac/statements.js +19 -2
  102. package/dist/rbac/types.d.ts +5 -0
  103. package/dist/realtime/changeStreamWatcher.d.ts +10 -4
  104. package/dist/realtime/changeStreamWatcher.js +110 -64
  105. package/dist/realtime/deprecation.d.ts +1 -0
  106. package/dist/realtime/deprecation.js +1 -0
  107. package/dist/realtime/realtimeApp.d.ts +1 -0
  108. package/dist/realtime/realtimeApp.js +1 -0
  109. package/dist/schemaMetadata.js +16 -5
  110. package/dist/sync/adminBroadcastScope.d.ts +40 -0
  111. package/dist/sync/adminBroadcastScope.js +194 -0
  112. package/dist/sync/adminWindowAccess.d.ts +13 -0
  113. package/dist/sync/adminWindowAccess.js +96 -0
  114. package/dist/sync/adminWindowMutation.d.ts +88 -0
  115. package/dist/sync/adminWindowMutation.js +247 -0
  116. package/dist/sync/executors.d.ts +9 -3
  117. package/dist/sync/executors.js +190 -159
  118. package/dist/sync/mutationHandler.d.ts +5 -2
  119. package/dist/sync/mutationHandler.js +191 -71
  120. package/dist/sync/registry.js +4 -0
  121. package/dist/sync/routes.d.ts +13 -0
  122. package/dist/sync/routes.js +113 -56
  123. package/dist/sync/socketHandlers.d.ts +8 -2
  124. package/dist/sync/socketHandlers.js +144 -50
  125. package/dist/sync/streams.d.ts +2 -0
  126. package/dist/sync/streams.js +7 -1
  127. package/dist/sync/syncApp.d.ts +2 -1
  128. package/dist/sync/syncApp.js +2 -1
  129. package/dist/sync/syncBatch.d.ts +5 -2
  130. package/dist/sync/syncBatch.js +4 -4
  131. package/dist/sync/types.d.ts +18 -0
  132. package/dist/terrenoApp.d.ts +29 -0
  133. package/dist/terrenoApp.js +91 -54
  134. package/dist/tests/createTestData.d.ts +1 -3
  135. package/dist/tests/createTestData.js +3 -5
  136. package/dist/tests/models.d.ts +1 -0
  137. package/dist/tests/models.js +9 -2
  138. package/dist/tests/testHelper.d.ts +0 -5
  139. package/dist/tests/testHelper.js +2 -9
  140. package/dist/types/authToken.d.ts +3 -3
  141. package/dist/types/mcpServiceToken.d.ts +2 -2
  142. package/dist/types/membership.d.ts +23 -0
  143. package/dist/types/membership.js +2 -0
  144. package/dist/types/notification.d.ts +28 -0
  145. package/dist/types/notification.js +2 -0
  146. package/dist/types/notificationPreference.d.ts +20 -0
  147. package/dist/types/notificationPreference.js +2 -0
  148. package/dist/types/organization.d.ts +36 -0
  149. package/dist/types/organization.js +2 -0
  150. package/dist/webhooks/idempotency/webhookReceipt.d.ts +4 -49
  151. package/dist/webhooks/idempotency/webhookReceipt.js +7 -7
  152. package/dist/webhooks/rawBody.d.ts +1 -0
  153. package/dist/webhooks/rawBody.js +1 -0
  154. package/package.json +31 -25
  155. package/src/__snapshots__/openApi.test.ts.snap +192 -54
  156. package/src/__snapshots__/openApiBuilder.test.ts.snap +0 -18
  157. package/src/__snapshots__/schemaMetadata.test.ts.snap +0 -1
  158. package/src/adminTypes.ts +8 -0
  159. package/src/api.test.ts +39 -2
  160. package/src/api.ts +68 -0
  161. package/src/audit/auditApp.test.ts +243 -0
  162. package/src/audit/auditApp.ts +139 -0
  163. package/src/audit/auditEventModel.ts +156 -0
  164. package/src/audit/auditRouter.test.ts +456 -0
  165. package/src/audit/cloudTasksEnqueue.test.ts +124 -0
  166. package/src/audit/cloudTasksEnqueue.ts +104 -0
  167. package/src/audit/diff.ts +163 -0
  168. package/src/audit/processQueue.ts +69 -0
  169. package/src/audit/rbacSink.test.ts +86 -0
  170. package/src/audit/rbacSink.ts +42 -0
  171. package/src/audit/record.test.ts +402 -0
  172. package/src/audit/record.ts +328 -0
  173. package/src/auth.test.ts +1 -1
  174. package/src/betterAuth.ts +7 -0
  175. package/src/betterAuthSetup.test.ts +27 -0
  176. package/src/betterAuthSetup.ts +1 -0
  177. package/src/collectionRegistry.test.ts +8 -9
  178. package/src/collectionRegistry.ts +21 -1
  179. package/src/express.d.ts +2 -0
  180. package/src/expressServer.test.ts +50 -2
  181. package/src/index.ts +69 -0
  182. package/src/mcp/handlers.test.ts +275 -0
  183. package/src/mcp/query.ts +3 -3
  184. package/src/mcp/toolGenerator.test.ts +81 -0
  185. package/src/migrations/cli.test.ts +376 -0
  186. package/src/migrations/cli.ts +283 -0
  187. package/src/migrations/fixtures/all-down/20260910120000-one.ts +6 -0
  188. package/src/migrations/fixtures/all-down/20260910120001-two.ts +6 -0
  189. package/src/migrations/fixtures/bad-id/20260910120000-mismatch.ts +4 -0
  190. package/src/migrations/fixtures/bad-name/not-a-migration.ts +4 -0
  191. package/src/migrations/fixtures/missing-up/20260910120000-noup.ts +2 -0
  192. package/src/migrations/fixtures/valid/20260910120000-alpha.ts +4 -0
  193. package/src/migrations/fixtures/valid/20260910120001-beta.ts +6 -0
  194. package/src/migrations/generate.test.ts +333 -0
  195. package/src/migrations/generate.ts +216 -0
  196. package/src/migrations/load.test.ts +103 -0
  197. package/src/migrations/load.ts +124 -0
  198. package/src/migrations/lock.test.ts +133 -0
  199. package/src/migrations/lock.ts +118 -0
  200. package/src/migrations/runner.test.ts +504 -0
  201. package/src/migrations/runner.ts +358 -0
  202. package/src/migrations/schemaCatalog.test.ts +159 -0
  203. package/src/migrations/schemaCatalog.ts +262 -0
  204. package/src/migrations/types.ts +94 -0
  205. package/src/models/notification.ts +68 -0
  206. package/src/models/notificationPreference.ts +62 -0
  207. package/src/notifications/notificationService.ts +254 -0
  208. package/src/notifications/notificationsApp.test.ts +505 -0
  209. package/src/notifications/notificationsApp.ts +200 -0
  210. package/src/notifications/notificationsBeforeSend.ts +51 -0
  211. package/src/openApi.test.ts +0 -1
  212. package/src/openApi.ts +2 -1
  213. package/src/openApiBuilder.ts +14 -3
  214. package/src/openApiValidator.test.ts +221 -2
  215. package/src/openApiValidator.ts +218 -33
  216. package/src/orgs/orgAccessOptIn.test.ts +87 -0
  217. package/src/orgs/orgContext.test.ts +259 -0
  218. package/src/orgs/orgContext.ts +151 -0
  219. package/src/orgs/orgPermissions.test.ts +105 -0
  220. package/src/orgs/orgPermissions.ts +40 -0
  221. package/src/orgs/orgPlugin.test.ts +130 -0
  222. package/src/orgs/orgPlugin.ts +70 -0
  223. package/src/orgs/orgRbac.test.ts +267 -0
  224. package/src/orgs/orgSecurityDefects.test.ts +415 -0
  225. package/src/orgs/organizationModel.test.ts +205 -0
  226. package/src/orgs/organizationModel.ts +257 -0
  227. package/src/orgs/organizationSettings.test.ts +113 -0
  228. package/src/orgs/organizationSettings.ts +126 -0
  229. package/src/orgs/orgsApp.test.ts +382 -0
  230. package/src/orgs/orgsApp.ts +563 -0
  231. package/src/permissions.test.ts +62 -36
  232. package/src/permissions.ts +8 -30
  233. package/src/rateLimit/middleware.ts +1 -1
  234. package/src/rateLimit/mongoStore.ts +1 -0
  235. package/src/rateLimit/policies.ts +2 -2
  236. package/src/rateLimit/redisStore.ts +1 -0
  237. package/src/rbac/access.ts +11 -3
  238. package/src/rbac/membershipOrgAdminSource.ts +59 -0
  239. package/src/rbac/modelRouterAccess.ts +3 -0
  240. package/src/rbac/permissionUtils.test.ts +26 -5
  241. package/src/rbac/resolve.test.ts +34 -2
  242. package/src/rbac/resolve.ts +26 -7
  243. package/src/rbac/roleModel.test.ts +34 -1
  244. package/src/rbac/roleModel.ts +17 -1
  245. package/src/rbac/statements.test.ts +19 -0
  246. package/src/rbac/statements.ts +19 -1
  247. package/src/rbac/types.ts +5 -0
  248. package/src/realtime/changeStreamWatcher.ts +73 -33
  249. package/src/realtime/deprecation.ts +1 -0
  250. package/src/realtime/realtime.test.ts +357 -185
  251. package/src/realtime/realtimeApp.ts +1 -0
  252. package/src/schemaMetadata.test.ts +14 -0
  253. package/src/schemaMetadata.ts +5 -5
  254. package/src/sync/adminBroadcastConfig.test.ts +96 -0
  255. package/src/sync/adminBroadcastScope.test.ts +155 -0
  256. package/src/sync/adminBroadcastScope.ts +123 -0
  257. package/src/sync/adminWindowAccess.test.ts +57 -0
  258. package/src/sync/adminWindowAccess.ts +32 -0
  259. package/src/sync/adminWindowMutation.test.ts +450 -0
  260. package/src/sync/adminWindowMutation.ts +283 -0
  261. package/src/sync/executors.ts +33 -6
  262. package/src/sync/mutationHandler.test.ts +277 -1
  263. package/src/sync/mutationHandler.ts +171 -29
  264. package/src/sync/registry.ts +4 -0
  265. package/src/sync/routes.ts +52 -8
  266. package/src/sync/socketHandlers.ts +154 -58
  267. package/src/sync/streams.ts +6 -0
  268. package/src/sync/sync.test.ts +3 -2
  269. package/src/sync/syncApp.ts +2 -1
  270. package/src/sync/syncBatch.ts +7 -2
  271. package/src/sync/syncRoutes.test.ts +297 -3
  272. package/src/sync/syncSocket.test.ts +229 -0
  273. package/src/sync/types.ts +20 -0
  274. package/src/terrenoApp.migrations.test.ts +114 -0
  275. package/src/terrenoApp.test.ts +41 -0
  276. package/src/terrenoApp.ts +94 -31
  277. package/src/tests/createTestData.ts +2 -2
  278. package/src/tests/models.ts +10 -2
  279. package/src/tests/testHelper.ts +1 -7
  280. package/src/types/authToken.ts +2 -4
  281. package/src/types/mcpServiceToken.ts +1 -7
  282. package/src/types/membership.ts +48 -0
  283. package/src/types/notification.ts +34 -0
  284. package/src/types/notificationPreference.ts +28 -0
  285. package/src/types/organization.ts +49 -0
  286. package/src/webhooks/idempotency/webhookReceipt.ts +4 -7
  287. package/src/webhooks/rawBody.test.ts +33 -0
  288. package/src/webhooks/rawBody.ts +1 -0
  289. package/tsconfig.json +1 -1
  290. package/tsconfig.typedoc.json +2 -1
  291. package/dist/vendor/wesleytodd-openapi/lib/convert-yaml.d.ts +0 -2
  292. package/dist/vendor/wesleytodd-openapi/lib/convert-yaml.js +0 -13
  293. package/src/vendor/wesleytodd-openapi/lib/convert-yaml.js +0 -13
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Tests for TerrenoApp `migrations.runOnStart` (wet up after connect, before listen).
3
+ */
4
+ import {beforeEach, describe, expect, it} from "bun:test";
5
+ import {join} from "node:path";
6
+ import mongoose from "mongoose";
7
+ import type {UserModel as UserModelType} from "./auth";
8
+ import {runStartupMigrations} from "./migrations/runner";
9
+ import {MIGRATION_LOCK_ID, MIGRATIONS_COLLECTION} from "./migrations/types";
10
+ import {TerrenoApp} from "./terrenoApp";
11
+ import {setupDb, UserModel} from "./tests";
12
+
13
+ const fixtures = (...parts: string[]): string => {
14
+ return join(import.meta.dir, "migrations", "fixtures", ...parts);
15
+ };
16
+
17
+ const appliedIds = async (): Promise<string[]> => {
18
+ const docs = await mongoose.connection
19
+ .collection(MIGRATIONS_COLLECTION)
20
+ .find({_id: {$ne: MIGRATION_LOCK_ID}})
21
+ .project({id: 1})
22
+ .toArray();
23
+ return docs.map((doc) => String(doc.id)).sort();
24
+ };
25
+
26
+ describe("runStartupMigrations", () => {
27
+ beforeEach(async () => {
28
+ await setupDb();
29
+ await mongoose.connection.collection(MIGRATIONS_COLLECTION).deleteMany({});
30
+ });
31
+
32
+ it("does not run when migrations option is omitted", async () => {
33
+ const result = await runStartupMigrations({
34
+ env: {NODE_ENV: "test"},
35
+ mongoose,
36
+ });
37
+ expect(result.ran).toBe(false);
38
+ expect(await appliedIds()).toEqual([]);
39
+ });
40
+
41
+ it("does not run when runOnStart is omitted", async () => {
42
+ const result = await runStartupMigrations({
43
+ env: {NODE_ENV: "test"},
44
+ migrations: {dir: fixtures("valid")},
45
+ mongoose,
46
+ });
47
+ expect(result.ran).toBe(false);
48
+ expect(await appliedIds()).toEqual([]);
49
+ });
50
+
51
+ it("applies pending files when runOnStart is true", async () => {
52
+ const result = await runStartupMigrations({
53
+ env: {NODE_ENV: "test"},
54
+ migrations: {dir: fixtures("valid"), runOnStart: true},
55
+ mongoose,
56
+ });
57
+ expect(result.ran).toBe(true);
58
+ expect(result.applied).toEqual(["20260910120000-alpha", "20260910120001-beta"]);
59
+ expect(await appliedIds()).toEqual(["20260910120000-alpha", "20260910120001-beta"]);
60
+ });
61
+
62
+ it("throws in production without ALLOW_MIGRATIONS before applying", async () => {
63
+ await expect(
64
+ runStartupMigrations({
65
+ env: {NODE_ENV: "production"},
66
+ migrations: {dir: fixtures("valid"), runOnStart: true},
67
+ mongoose,
68
+ })
69
+ ).rejects.toThrow("Migrations not allowed");
70
+ expect(await appliedIds()).toEqual([]);
71
+ });
72
+ });
73
+
74
+ describe("TerrenoApp start migrations", () => {
75
+ const typedUserModel = UserModel as unknown as UserModelType;
76
+
77
+ beforeEach(async () => {
78
+ await setupDb();
79
+ await mongoose.connection.collection(MIGRATIONS_COLLECTION).deleteMany({});
80
+ });
81
+
82
+ it("applies pending files through start() when runOnStart is true", async () => {
83
+ const app = new TerrenoApp({
84
+ migrations: {dir: fixtures("valid"), runOnStart: true},
85
+ skipListen: true,
86
+ userModel: typedUserModel,
87
+ });
88
+ app.start();
89
+ await app.whenReady();
90
+ expect(await appliedIds()).toEqual(["20260910120000-alpha", "20260910120001-beta"]);
91
+ });
92
+
93
+ it("rejects whenReady in production without ALLOW_MIGRATIONS and does not listen", async () => {
94
+ const previousNodeEnv = process.env.NODE_ENV;
95
+ process.env.NODE_ENV = "production";
96
+ Reflect.deleteProperty(process.env, "ALLOW_MIGRATIONS");
97
+ try {
98
+ const app = new TerrenoApp({
99
+ migrations: {dir: fixtures("valid"), runOnStart: true},
100
+ skipListen: true,
101
+ userModel: typedUserModel,
102
+ });
103
+ app.start();
104
+ await expect(app.whenReady()).rejects.toThrow("Migrations not allowed");
105
+ expect(await appliedIds()).toEqual([]);
106
+ } finally {
107
+ if (previousNodeEnv === undefined) {
108
+ Reflect.deleteProperty(process.env, "NODE_ENV");
109
+ } else {
110
+ process.env.NODE_ENV = previousNodeEnv;
111
+ }
112
+ }
113
+ });
114
+ });
@@ -9,6 +9,8 @@ import {configurationPlugin} from "./configurationPlugin";
9
9
  import {APIError} from "./errors";
10
10
  import {Permissions} from "./permissions";
11
11
  import {createdUpdatedPlugin} from "./plugins";
12
+ import {createAccess} from "./rbac/access";
13
+ import {terrenoStatements} from "./rbac/statements";
12
14
  import {TerrenoApp} from "./terrenoApp";
13
15
  import type {TerrenoPlugin} from "./terrenoPlugin";
14
16
  import {authAsUser, FoodModel, setupDb, UserModel} from "./tests";
@@ -74,6 +76,45 @@ describe("TerrenoApp", () => {
74
76
 
75
77
  expect(app).toBeDefined();
76
78
  });
79
+
80
+ it("does not mount /orgs when organizations is omitted", async () => {
81
+ const app = new TerrenoApp({
82
+ skipListen: true,
83
+ userModel: typedUserModel,
84
+ }).start();
85
+
86
+ const res = await supertest(app).get("/orgs");
87
+ expect(res.status).toBe(404);
88
+ });
89
+
90
+ it("requires accessControl when organizations is true", () => {
91
+ expect(() =>
92
+ new TerrenoApp({
93
+ organizations: true,
94
+ skipListen: true,
95
+ userModel: typedUserModel,
96
+ }).start()
97
+ ).toThrow("organizations requires accessControl");
98
+ });
99
+
100
+ it("mounts /orgs when organizations is true", async () => {
101
+ await setupDb();
102
+ const access = createAccess({
103
+ connection: mongoose.connection,
104
+ organizations: true,
105
+ statements: terrenoStatements,
106
+ userModel: typedUserModel,
107
+ });
108
+ const app = new TerrenoApp({
109
+ accessControl: access,
110
+ organizations: true,
111
+ skipListen: true,
112
+ userModel: typedUserModel,
113
+ }).start();
114
+
115
+ const res = await supertest(app).get("/orgs");
116
+ expect(res.status).not.toBe(404);
117
+ });
77
118
  });
78
119
 
79
120
  describe("register with modelRouter", () => {
package/src/terrenoApp.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import {EventEmitter} from "node:events";
2
- import {createServer} from "node:http";
2
+ import {createServer, type Server as HttpServer} from "node:http";
3
3
  import * as Sentry from "@sentry/bun";
4
4
  import cors from "cors";
5
5
  import express from "express";
6
+ import mongoose from "mongoose";
6
7
  import qs from "qs";
7
8
  import type {AdminChangeEvent, TerrenoAppAdminEvent} from "./adminTypes";
8
9
  import type {ModelRouterRegistration} from "./api";
@@ -18,6 +19,7 @@ import {
18
19
  type ConfigurationModelLike,
19
20
  } from "./configurationApp";
20
21
  import {
22
+ APIError,
21
23
  apiErrorMiddleware,
22
24
  apiFallthroughErrorMiddleware,
23
25
  apiUnauthorizedMiddleware,
@@ -32,8 +34,10 @@ import {
32
34
  resolveMcpServiceTokensOption,
33
35
  } from "./mcp/serviceTokens";
34
36
  import {jsonResponseRequestIdMiddleware} from "./middleware";
37
+ import {runStartupMigrations, type StartupMigrationsOption} from "./migrations/runner";
35
38
  import {openApiCompatMiddleware, patchAppUse} from "./openApiCompat";
36
39
  import {openApiEtagMiddleware} from "./openApiEtag";
40
+ import {OrgsApp, type OrgsAppOptions} from "./orgs/orgsApp";
37
41
  import {applyRateLimitTrustProxy} from "./rateLimit/applyTrustProxy";
38
42
  import {createRateLimitStore} from "./rateLimit/createStore";
39
43
  import {createRateLimitMiddleware} from "./rateLimit/middleware";
@@ -87,6 +91,12 @@ export interface TerrenoAppOptions {
87
91
  githubAuth?: GitHubAuthOptions;
88
92
  /** Skip calling app.listen() in start() method (useful for testing) */
89
93
  skipListen?: boolean;
94
+ /**
95
+ * Already-listening HTTP server. `start()` attaches the Express app to it
96
+ * instead of creating and binding a new server, so Cloud Run can see PORT
97
+ * before MongoDB connect and plugin registration finish.
98
+ */
99
+ httpServer?: HttpServer;
90
100
  /** Sentry configuration options */
91
101
  sentryOptions?: Sentry.BunOptions;
92
102
  /** Maximum number of array items in query parameters (default: 200) */
@@ -104,6 +114,13 @@ export interface TerrenoAppOptions {
104
114
  * RBAC access controller injected into model routers and `/auth/me` enrichment.
105
115
  */
106
116
  accessControl?: import("./rbac/types").AnyTerrenoAccess;
117
+ /**
118
+ * Multi-tenant organizations. Default off so existing single-tenant apps stay unchanged.
119
+ * New apps from `terreno_bootstrap_app` pass `true`. Requires `accessControl` from
120
+ * `createAccess({ organizations: true })`. Pass `{ settingsSchema }` to type and
121
+ * validate `Organization.settings`.
122
+ */
123
+ organizations?: boolean | Omit<OrgsAppOptions, "access" | "userModel">;
107
124
  /**
108
125
  * Runs after CORS and before the `addMiddleware` chain and JSON body parsing.
109
126
  * Use to attach early middleware via `app.use(...)` before JSON parsing.
@@ -125,6 +142,12 @@ export interface TerrenoAppOptions {
125
142
  * mounts `/mcp/service-tokens` and accepts `Authorization: Bearer mcp_…` on `/mcp`.
126
143
  */
127
144
  mcpServiceTokens?: McpServiceTokensAppOption;
145
+ /**
146
+ * Versioned MongoDB migrations. `runOnStart` defaults to false. When true, wet `up`
147
+ * runs after listen and `ensureSyncIndexes`. Production still requires
148
+ * `ALLOW_MIGRATIONS=true`.
149
+ */
150
+ migrations?: StartupMigrationsOption;
128
151
  }
129
152
 
130
153
  /**
@@ -195,6 +218,7 @@ export class TerrenoApp {
195
218
  private middlewareFns: (express.RequestHandler | ((app: express.Application) => void))[] = [];
196
219
  private configurationApp: ConfigurationApp | null = null;
197
220
  private readonly adminEvents = new EventEmitter();
221
+ private bootPromise: Promise<void> = Promise.resolve();
198
222
 
199
223
  /**
200
224
  * Create a new TerrenoApp builder.
@@ -546,6 +570,31 @@ export class TerrenoApp {
546
570
  * ```
547
571
  */
548
572
  start(): express.Application {
573
+ if (this.options.organizations) {
574
+ if (!this.options.accessControl) {
575
+ throw new APIError({
576
+ status: 500,
577
+ title:
578
+ "TerrenoApp organizations requires accessControl from createAccess({ organizations: true })",
579
+ });
580
+ }
581
+ const hasOrgsPlugin = this.registrations.some(
582
+ (registration) =>
583
+ !this.isModelRouterRegistration(registration) && registration instanceof OrgsApp
584
+ );
585
+ if (!hasOrgsPlugin) {
586
+ const orgConfig =
587
+ typeof this.options.organizations === "object" ? this.options.organizations : {};
588
+ this.register(
589
+ new OrgsApp({
590
+ ...orgConfig,
591
+ access: this.options.accessControl,
592
+ userModel: this.options.userModel,
593
+ })
594
+ );
595
+ }
596
+ }
597
+
549
598
  // If realtime option is set, auto-register the RealtimeApp plugin
550
599
  if (this.options.realtime) {
551
600
  const hasRealtimePlugin = this.registrations.some(
@@ -568,41 +617,55 @@ export class TerrenoApp {
568
617
  }
569
618
 
570
619
  const app = this.build();
620
+ this.bootPromise = this.completeStart(app);
621
+ if (!this.options.skipListen) {
622
+ void this.bootPromise.catch((error: unknown) => {
623
+ const stack = error instanceof Error ? error.stack : String(error);
624
+ logger.error(`Error trying to start HTTP server: ${error}\n${stack}`);
625
+ process.exit(1);
626
+ });
627
+ }
628
+ return app;
629
+ }
630
+
631
+ /**
632
+ * Resolves after startup migrations (and listen, unless `skipListen`).
633
+ * Tests with `skipListen` should await this instead of assuming `start()` is idle.
634
+ */
635
+ whenReady(): Promise<void> {
636
+ return this.bootPromise;
637
+ }
571
638
 
639
+ private completeStart = async (app: express.Application): Promise<void> => {
572
640
  if (!this.options.skipListen) {
573
641
  const port = process.env.PORT || "9000";
574
- // Await sync index creation before listening: the per-model snapshot indexes (a
575
- // failed createIndex degrades the snapshot/catch-up query to a table scan) and the
576
- // bookkeeping-model indexes enqueued by SyncApp (the unique mutationId index is what
577
- // makes duplicate mutation deliveries idempotent, and the unique stream index is what
578
- // keeps the counter upsert race from minting duplicate seqs). Either failure is a
579
- // loud startup error rather than a silent correctness cliff. No-op when no sync
580
- // models or SyncApp are registered. Detached because start() returns synchronously.
581
- void (async (): Promise<void> => {
582
- try {
583
- await ensureSyncIndexes();
584
- const server = createServer(app);
585
-
586
- // Notify plugins that need access to the HTTP server (e.g. WebSocket plugins)
587
- for (const reg of this.registrations) {
588
- if (!this.isModelRouterRegistration(reg) && typeof reg.onServerCreated === "function") {
589
- reg.onServerCreated(server);
590
- }
591
- }
592
-
593
- server.listen(port, () => {
594
- logger.info(`Listening on port ${port}`);
595
- });
596
- } catch (error) {
597
- const stack = error instanceof Error ? error.stack : String(error);
598
- logger.error(`Error trying to start HTTP server: ${error}\n${stack}`);
599
- process.exit(1);
642
+ const existingServer = this.options.httpServer;
643
+ const server = existingServer ?? createServer(app);
644
+ if (existingServer) {
645
+ existingServer.removeAllListeners("request");
646
+ existingServer.on("request", app);
647
+ }
648
+ for (const reg of this.registrations) {
649
+ if (!this.isModelRouterRegistration(reg) && typeof reg.onServerCreated === "function") {
650
+ reg.onServerCreated(server);
600
651
  }
601
- })();
652
+ }
653
+ // Bind PORT before index/migration work so Cloud Run's startup probe can
654
+ // succeed while `ensureSyncIndexes` still runs. whenReady() still waits.
655
+ if (!existingServer) {
656
+ server.listen(port, () => {
657
+ logger.info(`Listening on port ${port}`);
658
+ });
659
+ } else {
660
+ logger.info(`Listening on port ${port}`);
661
+ }
662
+ await ensureSyncIndexes();
602
663
  }
603
-
604
- return app;
605
- }
664
+ await runStartupMigrations({
665
+ migrations: this.options.migrations,
666
+ mongoose,
667
+ });
668
+ };
606
669
 
607
670
  private isModelRouterRegistration(
608
671
  registration: ModelRouterRegistration | TerrenoPlugin
@@ -40,7 +40,7 @@ export const createTestUsers = async (): Promise<TestUsers> => {
40
40
  return {admin, adminOther, notAdmin};
41
41
  };
42
42
 
43
- export const createStandardFoods = async (users: TestUsers): Promise<TestFoods> => {
43
+ const createStandardFoods = async (users: TestUsers): Promise<TestFoods> => {
44
44
  const {admin, adminOther, notAdmin} = users;
45
45
 
46
46
  const [spinach, apple, carrots, pizza] = await Promise.all([
@@ -106,7 +106,7 @@ export const createStandardFoods = async (users: TestUsers): Promise<TestFoods>
106
106
  return {apple, carrots, pizza, spinach};
107
107
  };
108
108
 
109
- export const createRequiredFixtures = async (): Promise<TestRequired> => {
109
+ const createRequiredFixtures = async (): Promise<TestRequired> => {
110
110
  const [sample, withAbout] = await Promise.all([
111
111
  RequiredModel.create({name: "Sample Required"}),
112
112
  RequiredModel.create({about: "Optional about text", name: "Required With About"}),
@@ -16,6 +16,7 @@ export interface User {
16
16
  age?: number;
17
17
  disabled?: boolean;
18
18
  organizationIds?: string[];
19
+ roles?: string[];
19
20
  tokenEpoch?: number;
20
21
  emailVerified?: boolean;
21
22
  }
@@ -70,6 +71,11 @@ const userSchema = new Schema<User>({
70
71
  description: "Organization memberships",
71
72
  type: [String],
72
73
  },
74
+ roles: {
75
+ default: [],
76
+ description: "RBAC role names assigned to this user",
77
+ type: [String],
78
+ },
73
79
  tokenEpoch: {
74
80
  default: 0,
75
81
  description: "Incremented on password reset to invalidate outstanding refresh tokens",
@@ -82,10 +88,12 @@ userSchema.plugin(
82
88
  passportLocalMongoose as unknown as (schema: Schema, options?: Record<string, unknown>) => void,
83
89
  {
84
90
  attemptsField: "attempts",
85
- interval: process.env.NODE_ENV === "test" ? 1 : 100,
91
+ interval: 1,
86
92
  limitAttempts: true,
87
93
  maxAttempts: 3,
88
- maxInterval: process.env.NODE_ENV === "test" ? 1 : 300000,
94
+ // Test-only schema: maxInterval 0 caps calculatedInterval at 0 so AttemptTooSoon
95
+ // never preempts maxAttempts lockout under rapid supertest logins.
96
+ maxInterval: 0,
89
97
  usernameCaseInsensitive: true,
90
98
  usernameField: "email",
91
99
  }
@@ -7,7 +7,7 @@ import type {TestData} from "./types";
7
7
 
8
8
  const defaultTestMongoUri = "mongodb://127.0.0.1/terreno?&connectTimeoutMS=360000";
9
9
 
10
- export const applyTestAuthEnv = (): void => {
10
+ const applyTestAuthEnv = (): void => {
11
11
  process.env.REFRESH_TOKEN_SECRET = "refresh_secret";
12
12
  process.env.TOKEN_SECRET = "secret";
13
13
  process.env.TOKEN_EXPIRES_IN = "30m";
@@ -47,9 +47,3 @@ export const setupTestData = async (): Promise<TestData> => {
47
47
 
48
48
  return createTestData();
49
49
  };
50
-
51
- /** Clears all API test collections without re-seeding. */
52
- export const resetTestCollections = clearTestCollections;
53
-
54
- export {createTestData} from "./createTestData";
55
- export {loadTestData} from "./mongoTestSetup";
@@ -3,9 +3,9 @@ import type {FindExactlyOnePlugin, FindOneOrNonePlugin} from "../plugins";
3
3
 
4
4
  export type AuthTokenType = "passwordReset" | "emailVerification";
5
5
 
6
- export type AuthTokenMethods = Record<string, never>;
6
+ type AuthTokenMethods = Record<string, never>;
7
7
 
8
- export interface AuthTokenStatics
8
+ interface AuthTokenStatics
9
9
  extends FindExactlyOnePlugin<AuthTokenDocument>,
10
10
  FindOneOrNonePlugin<AuthTokenDocument> {
11
11
  consume: (
@@ -29,8 +29,6 @@ export interface AuthTokenModel
29
29
  extends mongoose.Model<AuthTokenDocument, object, AuthTokenMethods>,
30
30
  AuthTokenStatics {}
31
31
 
32
- export type AuthTokenSchema = mongoose.Schema<AuthTokenDocument, AuthTokenModel, AuthTokenMethods>;
33
-
34
32
  export interface AuthTokenDocument extends mongoose.Document {
35
33
  _id: mongoose.Types.ObjectId;
36
34
  userId: mongoose.Types.ObjectId;
@@ -6,7 +6,7 @@ export interface McpServiceTokenIssueOptions {
6
6
  name: string;
7
7
  }
8
8
 
9
- export interface McpServiceTokenMethods {
9
+ interface McpServiceTokenMethods {
10
10
  deleteOne: (this: McpServiceTokenDocument) => Promise<McpServiceTokenDocument>;
11
11
  }
12
12
 
@@ -34,12 +34,6 @@ export interface McpServiceTokenModel
34
34
  extends mongoose.Model<McpServiceTokenDocument, object, McpServiceTokenMethods>,
35
35
  McpServiceTokenStatics {}
36
36
 
37
- export type McpServiceTokenSchema = mongoose.Schema<
38
- McpServiceTokenDocument,
39
- McpServiceTokenModel,
40
- McpServiceTokenMethods
41
- >;
42
-
43
37
  export interface McpServiceTokenDocument extends mongoose.Document {
44
38
  _id: mongoose.Types.ObjectId;
45
39
  created: Date;
@@ -0,0 +1,48 @@
1
+ import type mongoose from "mongoose";
2
+ import type {FindExactlyOnePlugin, FindOneOrNonePlugin} from "../plugins";
3
+
4
+ export type MembershipRoleName = "org-admin" | "member";
5
+ export type MembershipStatus = "active" | "suspended";
6
+
7
+ // biome-ignore lint/complexity/noBannedTypes: No instance methods.
8
+ export type MembershipMethods = {};
9
+
10
+ export interface MembershipStatics
11
+ extends FindExactlyOnePlugin<MembershipDocument>,
12
+ FindOneOrNonePlugin<MembershipDocument> {
13
+ findActiveForUser: (
14
+ this: MembershipModel,
15
+ userId: mongoose.Types.ObjectId | string
16
+ ) => Promise<MembershipDocument[]>;
17
+ isMember: (
18
+ this: MembershipModel,
19
+ userId: mongoose.Types.ObjectId | string,
20
+ organizationId: mongoose.Types.ObjectId | string
21
+ ) => Promise<boolean>;
22
+ isOrgAdmin: (
23
+ this: MembershipModel,
24
+ userId: mongoose.Types.ObjectId | string,
25
+ organizationId: mongoose.Types.ObjectId | string
26
+ ) => Promise<boolean>;
27
+ }
28
+
29
+ export interface MembershipModel
30
+ extends mongoose.Model<MembershipDocument, object, MembershipMethods>,
31
+ MembershipStatics {}
32
+
33
+ export type MembershipSchema = mongoose.Schema<
34
+ MembershipDocument,
35
+ MembershipModel,
36
+ MembershipMethods
37
+ >;
38
+
39
+ export interface MembershipDocument extends mongoose.Document {
40
+ _id: mongoose.Types.ObjectId;
41
+ created: Date;
42
+ deleted: boolean;
43
+ organizationId: mongoose.Types.ObjectId;
44
+ roleName: MembershipRoleName;
45
+ status: MembershipStatus;
46
+ updated: Date;
47
+ userId: mongoose.Types.ObjectId;
48
+ }
@@ -0,0 +1,34 @@
1
+ import type mongoose from "mongoose";
2
+ import type {FindExactlyOnePlugin, FindOneOrNonePlugin} from "../plugins";
3
+
4
+ type NotificationMethods = Record<never, never>;
5
+
6
+ interface NotificationStatics
7
+ extends FindExactlyOnePlugin<NotificationDocument>,
8
+ FindOneOrNonePlugin<NotificationDocument> {}
9
+
10
+ export interface NotificationModel
11
+ extends mongoose.Model<NotificationDocument, object, NotificationMethods>,
12
+ NotificationStatics {}
13
+
14
+ export interface NotificationDocument extends mongoose.Document<string>, NotificationMethods {
15
+ _id: string;
16
+ archivedAt: Date | null;
17
+ body: string;
18
+ href?: string;
19
+ kind?: string;
20
+ ownerId: mongoose.Types.ObjectId;
21
+ readAt: Date | null;
22
+ title: string;
23
+ created: Date;
24
+ updated: Date;
25
+ deleted: boolean;
26
+ }
27
+
28
+ export interface NotifyInput {
29
+ body: string;
30
+ href?: string;
31
+ kind?: string;
32
+ title: string;
33
+ userId: string;
34
+ }
@@ -0,0 +1,28 @@
1
+ import type mongoose from "mongoose";
2
+ import type {FindExactlyOnePlugin, FindOneOrNonePlugin} from "../plugins";
3
+
4
+ export type NotificationPreferenceChannel = "inapp" | "mail" | "push" | "sms";
5
+
6
+ type NotificationPreferenceMethods = Record<never, never>;
7
+
8
+ interface NotificationPreferenceStatics
9
+ extends FindExactlyOnePlugin<NotificationPreferenceDocument>,
10
+ FindOneOrNonePlugin<NotificationPreferenceDocument> {}
11
+
12
+ export interface NotificationPreferenceModel
13
+ extends mongoose.Model<NotificationPreferenceDocument, object, NotificationPreferenceMethods>,
14
+ NotificationPreferenceStatics {}
15
+
16
+ export interface NotificationPreferenceDocument
17
+ extends mongoose.Document<string>,
18
+ NotificationPreferenceMethods {
19
+ _id: string;
20
+ inapp: boolean;
21
+ mail: boolean;
22
+ ownerId: mongoose.Types.ObjectId;
23
+ push: boolean;
24
+ sms: boolean;
25
+ created: Date;
26
+ updated: Date;
27
+ deleted: boolean;
28
+ }
@@ -0,0 +1,49 @@
1
+ import type mongoose from "mongoose";
2
+ import type {FindExactlyOnePlugin, FindOneOrNonePlugin} from "../plugins";
3
+
4
+ // biome-ignore lint/complexity/noBannedTypes: No instance methods.
5
+ export type OrganizationMethods = {};
6
+
7
+ export interface OrganizationStatics
8
+ extends FindExactlyOnePlugin<OrganizationDocument>,
9
+ FindOneOrNonePlugin<OrganizationDocument> {}
10
+
11
+ export interface OrganizationModel
12
+ extends mongoose.Model<OrganizationDocument, object, OrganizationMethods>,
13
+ OrganizationStatics {}
14
+
15
+ export type OrganizationSchema = mongoose.Schema<
16
+ OrganizationDocument,
17
+ OrganizationModel,
18
+ OrganizationMethods
19
+ >;
20
+
21
+ /**
22
+ * App-defined `Organization.settings` shape.
23
+ *
24
+ * Augment in the consumer app:
25
+ *
26
+ * ```ts
27
+ * declare module "@terreno/api" {
28
+ * interface OrganizationSettings {
29
+ * timezone?: string;
30
+ * }
31
+ * }
32
+ * ```
33
+ *
34
+ * Or pass a generic to `organizationSettingsOf<MySettings>(organization)`.
35
+ */
36
+ // biome-ignore lint/suspicious/noEmptyInterface: Declaration merging for consumer settings.
37
+ export interface OrganizationSettings {}
38
+
39
+ export interface OrganizationDocument extends mongoose.Document {
40
+ _id: mongoose.Types.ObjectId;
41
+ created: Date;
42
+ deleted: boolean;
43
+ disabled: boolean;
44
+ name: string;
45
+ ownerId: mongoose.Types.ObjectId;
46
+ settings?: OrganizationSettings;
47
+ slug: string;
48
+ updated: Date;
49
+ }
@@ -6,9 +6,9 @@ import {findExactlyOne, findOneOrNone} from "../../plugins";
6
6
  export const WEBHOOK_RECEIPTS_COLLECTION = "webhookReceipts";
7
7
  export const DEFAULT_WEBHOOK_RECEIPT_TTL_DAYS = 7;
8
8
 
9
- export type WebhookReceiptMethods = Record<string, never>;
9
+ type WebhookReceiptMethods = Record<string, never>;
10
10
 
11
- export interface WebhookReceiptStatics
11
+ interface WebhookReceiptStatics
12
12
  extends FindExactlyOnePlugin<WebhookReceiptDocument>,
13
13
  FindOneOrNonePlugin<WebhookReceiptDocument> {}
14
14
 
@@ -16,7 +16,7 @@ export interface WebhookReceiptModel
16
16
  extends mongoose.Model<WebhookReceiptDocument, object, WebhookReceiptMethods>,
17
17
  WebhookReceiptStatics {}
18
18
 
19
- export interface WebhookReceiptDocument extends mongoose.Document {
19
+ interface WebhookReceiptDocument extends mongoose.Document {
20
20
  _id: mongoose.Types.ObjectId;
21
21
  created: Date;
22
22
  eventId: string;
@@ -25,10 +25,7 @@ export interface WebhookReceiptDocument extends mongoose.Document {
25
25
 
26
26
  const secondsPerDay = 86_400;
27
27
 
28
- export const webhookReceiptSchema = new mongoose.Schema<
29
- WebhookReceiptDocument,
30
- WebhookReceiptModel
31
- >(
28
+ const webhookReceiptSchema = new mongoose.Schema<WebhookReceiptDocument, WebhookReceiptModel>(
32
29
  {
33
30
  created: {
34
31
  default: () => DateTime.utc().toJSDate(),