@terreno/api 57.19.2 → 57.21.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 (259) hide show
  1. package/CHANGELOG.md +443 -0
  2. package/biome.jsonc +1 -0
  3. package/dist/accountSecurity/accessActions.d.ts +38 -0
  4. package/dist/accountSecurity/accessActions.js +157 -0
  5. package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
  6. package/dist/accountSecurity/accountSecurityApp.js +438 -0
  7. package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
  8. package/dist/accountSecurity/accountSecurityService.js +481 -0
  9. package/dist/accountSecurity/credentialActions.d.ts +16 -0
  10. package/dist/accountSecurity/credentialActions.js +189 -0
  11. package/dist/accountSecurity/membershipActions.d.ts +15 -0
  12. package/dist/accountSecurity/membershipActions.js +81 -0
  13. package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
  14. package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
  15. package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
  16. package/dist/accountSecurity/securityEventHooks.js +223 -0
  17. package/dist/accountSecurity/securityEvents.d.ts +162 -0
  18. package/dist/accountSecurity/securityEvents.js +114 -0
  19. package/dist/accountSecurity/securityNotifications.d.ts +125 -0
  20. package/dist/accountSecurity/securityNotifications.js +333 -0
  21. package/dist/api.d.ts +3 -3
  22. package/dist/api.js +38 -6
  23. package/dist/audit/auditEventModel.d.ts +5 -3
  24. package/dist/audit/auditEventModel.js +8 -6
  25. package/dist/audit/processQueue.js +4 -2
  26. package/dist/audit/record.d.ts +2 -2
  27. package/dist/audit/record.js +3 -0
  28. package/dist/authRecovery.js +29 -1
  29. package/dist/betterAuth.d.ts +179 -10
  30. package/dist/betterAuthApp.d.ts +15 -0
  31. package/dist/betterAuthApp.js +23 -0
  32. package/dist/betterAuthChallengeHeaders.d.ts +37 -0
  33. package/dist/betterAuthChallengeHeaders.js +180 -0
  34. package/dist/betterAuthFeatures.d.ts +54 -0
  35. package/dist/betterAuthFeatures.js +239 -0
  36. package/dist/betterAuthMethods.d.ts +73 -0
  37. package/dist/betterAuthMethods.js +55 -0
  38. package/dist/betterAuthOAuthHandoff.d.ts +10 -2
  39. package/dist/betterAuthOAuthHandoff.js +222 -24
  40. package/dist/betterAuthSetPassword.d.ts +33 -0
  41. package/dist/betterAuthSetPassword.js +166 -0
  42. package/dist/betterAuthSetup.d.ts +57 -8
  43. package/dist/betterAuthSetup.js +327 -36
  44. package/dist/consentApp.d.ts +9 -4
  45. package/dist/consentApp.js +344 -28
  46. package/dist/consentStatus.d.ts +60 -0
  47. package/dist/consentStatus.js +111 -0
  48. package/dist/errors.d.ts +6 -0
  49. package/dist/errors.js +41 -2
  50. package/dist/expressServer.js +3 -2
  51. package/dist/frameworkModelNames.d.ts +4 -0
  52. package/dist/frameworkModelNames.js +4 -0
  53. package/dist/index.d.ts +18 -2
  54. package/dist/index.js +29 -3
  55. package/dist/mcp/adminTracking.d.ts +28 -0
  56. package/dist/mcp/adminTracking.js +80 -0
  57. package/dist/mcp/auth.d.ts +6 -0
  58. package/dist/mcp/auth.js +12 -2
  59. package/dist/mcp/oauth.js +151 -11
  60. package/dist/mcp/oauthMetadata.d.ts +2 -1
  61. package/dist/mcp/oauthMetadata.js +7 -4
  62. package/dist/mcp/server.d.ts +8 -0
  63. package/dist/mcp/server.js +48 -4
  64. package/dist/models/consentResponse.js +51 -0
  65. package/dist/models/mcpOAuthClient.js +78 -2
  66. package/dist/models/mcpOAuthToken.js +55 -4
  67. package/dist/models/mcpRequestLog.d.ts +2 -0
  68. package/dist/models/mcpRequestLog.js +73 -0
  69. package/dist/models/mcpServiceToken.js +4 -0
  70. package/dist/models/mcpToolSetting.d.ts +2 -0
  71. package/dist/models/mcpToolSetting.js +119 -0
  72. package/dist/models/versionConfig.d.ts +2 -0
  73. package/dist/orgs/membershipGuards.d.ts +7 -0
  74. package/dist/orgs/membershipGuards.js +32 -0
  75. package/dist/orgs/orgsApp.d.ts +19 -1
  76. package/dist/orgs/orgsApp.js +55 -24
  77. package/dist/rateLimit/policies.js +8 -0
  78. package/dist/rbac/access.js +2 -1
  79. package/dist/rbac/auditModel.d.ts +2 -1
  80. package/dist/rbac/resolve.d.ts +9 -1
  81. package/dist/rbac/resolve.js +21 -16
  82. package/dist/rbac/roleManager.d.ts +6 -0
  83. package/dist/rbac/roleManager.js +8 -7
  84. package/dist/rbac/roleModel.d.ts +1 -0
  85. package/dist/rbac/roleModel.js +45 -3
  86. package/dist/rbac/statements.d.ts +2 -2
  87. package/dist/rbac/statements.js +10 -1
  88. package/dist/rbac/types.d.ts +6 -0
  89. package/dist/rbac/userWriteGuards.js +2 -1
  90. package/dist/schemaMetadata.js +8 -1
  91. package/dist/seedRunner.js +7 -2
  92. package/dist/terrenoApp.d.ts +16 -0
  93. package/dist/terrenoApp.js +18 -0
  94. package/dist/tests/models.d.ts +22 -22
  95. package/dist/tests/models.js +15 -1
  96. package/dist/tests/testHelper.d.ts +6 -12
  97. package/dist/tests.d.ts +1 -0
  98. package/dist/tests.js +3 -1
  99. package/dist/types/consentResponse.d.ts +8 -0
  100. package/dist/types/mcpAdmin.d.ts +58 -0
  101. package/dist/types/mcpAdmin.js +2 -0
  102. package/dist/types/mcpOAuth.d.ts +37 -2
  103. package/dist/types/mcpServiceToken.d.ts +2 -0
  104. package/e2e/smoke.ts +193 -0
  105. package/package.json +10 -5
  106. package/src/__snapshots__/openApi.test.ts.snap +288 -0
  107. package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
  108. package/src/accountSecurity/accessActions.test.ts +723 -0
  109. package/src/accountSecurity/accessActions.ts +173 -0
  110. package/src/accountSecurity/accountSecurity.test.ts +947 -0
  111. package/src/accountSecurity/accountSecurityApp.ts +720 -0
  112. package/src/accountSecurity/accountSecurityService.ts +826 -0
  113. package/src/accountSecurity/credentialActions.test.ts +867 -0
  114. package/src/accountSecurity/credentialActions.ts +260 -0
  115. package/src/accountSecurity/membershipActions.ts +89 -0
  116. package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
  117. package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
  118. package/src/accountSecurity/securityEventHooks.ts +294 -0
  119. package/src/accountSecurity/securityEvents.ts +165 -0
  120. package/src/accountSecurity/securityNotifications.test.ts +1323 -0
  121. package/src/accountSecurity/securityNotifications.ts +516 -0
  122. package/src/adminModelRouter.test.ts +8 -6
  123. package/src/api.arrayOperations.test.ts +102 -22
  124. package/src/api.hooks.test.ts +12 -11
  125. package/src/api.query.test.ts +2 -2
  126. package/src/api.test.ts +8 -7
  127. package/src/api.ts +41 -10
  128. package/src/audit/auditApp.test.ts +1 -1
  129. package/src/audit/auditEventModel.ts +10 -7
  130. package/src/audit/cloudTasksEnqueue.test.ts +19 -14
  131. package/src/audit/processQueue.ts +4 -2
  132. package/src/audit/record.test.ts +15 -0
  133. package/src/audit/record.ts +10 -2
  134. package/src/auth.test.ts +21 -7
  135. package/src/authRecovery.test.ts +33 -10
  136. package/src/authRecovery.ts +34 -1
  137. package/src/authRecoveryBetterAuth.test.ts +169 -0
  138. package/src/authVerification.test.ts +7 -7
  139. package/src/betterAuth.ts +194 -8
  140. package/src/betterAuthApp.ts +32 -0
  141. package/src/betterAuthChallengeHeaders.test.ts +476 -0
  142. package/src/betterAuthChallengeHeaders.ts +227 -0
  143. package/src/betterAuthFeatures.test.ts +490 -0
  144. package/src/betterAuthFeatures.ts +283 -0
  145. package/src/betterAuthLinking.test.ts +846 -0
  146. package/src/betterAuthMethods.test.ts +138 -0
  147. package/src/betterAuthMethods.ts +98 -0
  148. package/src/betterAuthOAuthHandoff.test.ts +482 -69
  149. package/src/betterAuthOAuthHandoff.ts +293 -33
  150. package/src/betterAuthOAuthProxy.test.ts +421 -0
  151. package/src/betterAuthPasswordReset.test.ts +190 -0
  152. package/src/betterAuthSetPassword.test.ts +378 -0
  153. package/src/betterAuthSetPassword.ts +213 -0
  154. package/src/betterAuthSetup.test.ts +115 -57
  155. package/src/betterAuthSetup.ts +457 -38
  156. package/src/collectionRegistry.test.ts +4 -4
  157. package/src/consentApp.test.ts +869 -2
  158. package/src/consentApp.ts +438 -36
  159. package/src/consentStatus.test.ts +226 -0
  160. package/src/consentStatus.ts +171 -0
  161. package/src/errors.test.ts +81 -0
  162. package/src/errors.ts +50 -1
  163. package/src/expressServer.test.ts +29 -0
  164. package/src/expressServer.ts +3 -2
  165. package/src/frameworkModelNames.test.ts +8 -0
  166. package/src/frameworkModelNames.ts +4 -0
  167. package/src/githubAuth.test.ts +11 -11
  168. package/src/index.ts +38 -0
  169. package/src/isolated/migrateCliConnect.isolated.ts +3 -2
  170. package/src/mcp/actionTools.test.ts +11 -5
  171. package/src/mcp/adminTracking.test.ts +272 -0
  172. package/src/mcp/adminTracking.ts +104 -0
  173. package/src/mcp/auth.ts +18 -2
  174. package/src/mcp/oauth.test.ts +463 -2
  175. package/src/mcp/oauth.ts +184 -13
  176. package/src/mcp/oauthMetadata.ts +5 -2
  177. package/src/mcp/server.ts +67 -4
  178. package/src/mcp/serviceTokens.test.ts +2 -1
  179. package/src/mcp/toolGenerator.test.ts +9 -5
  180. package/src/migrations/cli.test.ts +15 -14
  181. package/src/migrations/cli.ts +1 -1
  182. package/src/migrations/generate.test.ts +2 -2
  183. package/src/migrations/load.test.ts +1 -1
  184. package/src/migrations/lock.test.ts +8 -3
  185. package/src/migrations/runner.test.ts +16 -5
  186. package/src/migrations/schemaCatalog.test.ts +4 -1
  187. package/src/models/consentResponse.ts +53 -0
  188. package/src/models/mcpOAuthClient.ts +100 -3
  189. package/src/models/mcpOAuthToken.test.ts +42 -0
  190. package/src/models/mcpOAuthToken.ts +62 -5
  191. package/src/models/mcpRequestLog.ts +81 -0
  192. package/src/models/mcpServiceToken.test.ts +23 -0
  193. package/src/models/mcpServiceToken.ts +10 -0
  194. package/src/models/mcpToolSetting.test.ts +69 -0
  195. package/src/models/mcpToolSetting.ts +138 -0
  196. package/src/models/versionConfig.ts +2 -0
  197. package/src/notifications/notificationsApp.test.ts +5 -8
  198. package/src/notifiers/slackWebApi.test.ts +30 -8
  199. package/src/openApi.test.ts +4 -4
  200. package/src/openApiValidator.test.ts +3 -3
  201. package/src/orgs/membershipGuards.ts +39 -0
  202. package/src/orgs/orgPermissions.test.ts +2 -2
  203. package/src/orgs/orgPlugin.test.ts +4 -3
  204. package/src/orgs/orgRbac.test.ts +1 -1
  205. package/src/orgs/orgSecurityDefects.test.ts +3 -1
  206. package/src/orgs/organizationSettings.test.ts +1 -1
  207. package/src/orgs/orgsApp.test.ts +104 -3
  208. package/src/orgs/orgsApp.ts +69 -28
  209. package/src/permissions.test.ts +2 -2
  210. package/src/rateLimit/policies.test.ts +53 -0
  211. package/src/rateLimit/policies.ts +8 -0
  212. package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
  213. package/src/rbac/access.ts +4 -1
  214. package/src/rbac/assertAllowed.test.ts +1 -1
  215. package/src/rbac/auditModel.ts +10 -2
  216. package/src/rbac/realtimeAccess.test.ts +3 -2
  217. package/src/rbac/resolve.test.ts +65 -0
  218. package/src/rbac/resolve.ts +37 -17
  219. package/src/rbac/roleManager.test.ts +64 -0
  220. package/src/rbac/roleManager.ts +15 -6
  221. package/src/rbac/roleModel.test.ts +174 -1
  222. package/src/rbac/roleModel.ts +66 -3
  223. package/src/rbac/routes.test.ts +58 -0
  224. package/src/rbac/statements.test.ts +4 -1
  225. package/src/rbac/statements.ts +11 -1
  226. package/src/rbac/types.ts +6 -1
  227. package/src/rbac/userWriteGuards.test.ts +56 -5
  228. package/src/rbac/userWriteGuards.ts +5 -2
  229. package/src/realtime/realtime.test.ts +35 -31
  230. package/src/schemaMetadata.test.ts +39 -0
  231. package/src/schemaMetadata.ts +11 -1
  232. package/src/scrubAdminFields.test.ts +1 -1
  233. package/src/seedRunner.test.ts +56 -0
  234. package/src/seedRunner.ts +7 -2
  235. package/src/sync/adminWindowMutation.test.ts +4 -3
  236. package/src/sync/executors.test.ts +1 -1
  237. package/src/sync/scripts/compactTombstones.test.ts +4 -3
  238. package/src/sync/sync.test.ts +1 -1
  239. package/src/sync/syncPhaseC.test.ts +14 -11
  240. package/src/sync/syncRoutes.test.ts +8 -8
  241. package/src/sync/syncSeqPlugin.test.ts +1 -2
  242. package/src/sync/syncSocket.test.ts +5 -4
  243. package/src/terrenoApp.mcpServiceTokens.test.ts +2 -2
  244. package/src/terrenoApp.migrations.test.ts +8 -7
  245. package/src/terrenoApp.ts +34 -0
  246. package/src/tests/accountSecurityTestApp.ts +290 -0
  247. package/src/tests/betterAuthStubs.ts +189 -0
  248. package/src/tests/bunSetup.ts +1 -1
  249. package/src/tests/mockOidcProvider.ts +105 -0
  250. package/src/tests/models.ts +23 -0
  251. package/src/tests/softwareAuthenticator.ts +183 -0
  252. package/src/tests/testEnv.ts +7 -0
  253. package/src/tests.ts +1 -0
  254. package/src/types/consentResponse.ts +8 -0
  255. package/src/types/mcpAdmin.ts +80 -0
  256. package/src/types/mcpOAuth.ts +44 -3
  257. package/src/types/mcpServiceToken.ts +5 -0
  258. package/src/webhooks/verifiers/hmac.test.ts +1 -1
  259. package/tsconfig.typecheck.json +14 -0
@@ -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";
@@ -1267,7 +1267,7 @@ describe("emitSyncDeltaForChange", () => {
1267
1267
  const deltas = io.emissions.filter((e) => e.event === "sync:delta");
1268
1268
  expect(deltas).toHaveLength(1);
1269
1269
  const receiver = io.sockets.sockets.get(deltas[0].socketId);
1270
- expect(receiver.decodedToken.id).toBe("user1");
1270
+ expect(receiver?.decodedToken.id).toBe("user1");
1271
1271
  });
1272
1272
 
1273
1273
  it("C7: soft delete emits a delete delta with deleted true and NO data (tombstone stripped)", async () => {
@@ -1697,9 +1697,10 @@ describe("sync:delta — change stream integration", () => {
1697
1697
  const docId = String(doc._id);
1698
1698
  await waitForDelta(io, (d) => d.id === docId);
1699
1699
 
1700
- const legacy = io.emissions.filter(
1701
- (e) => e.event === "sync" && e.payload?.id === docId && e.payload?.method === "create"
1702
- );
1700
+ const legacy = io.emissions.filter((e) => {
1701
+ const payload = e.payload as {id?: string; method?: string} | undefined;
1702
+ return e.event === "sync" && payload?.id === docId && payload?.method === "create";
1703
+ });
1703
1704
  const deltas = io.emissions.filter(
1704
1705
  (e) => e.event === "sync:delta" && (e.payload as SyncDelta).id === docId
1705
1706
  );
@@ -27,9 +27,9 @@ const getNoteModel = (): mongoose.Model<{title?: string}> => {
27
27
  if (mongoose.models.TokenMcpNote) {
28
28
  return mongoose.models.TokenMcpNote as mongoose.Model<{title?: string}>;
29
29
  }
30
- const schema = new Schema({title: {description: "Note title", type: String}});
30
+ const schema = new Schema<{title?: string}>({title: {description: "Note title", type: String}});
31
31
  schema.plugin(createdUpdatedPlugin);
32
- return model("TokenMcpNote", schema);
32
+ return model<{title?: string}>("TokenMcpNote", schema);
33
33
  };
34
34
 
35
35
  const TokenMcpNote = getNoteModel();
@@ -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
  })
package/src/terrenoApp.ts CHANGED
@@ -5,6 +5,7 @@ import cors from "cors";
5
5
  import express from "express";
6
6
  import mongoose from "mongoose";
7
7
  import qs from "qs";
8
+ import {AccountSecurityApp} from "./accountSecurity/accountSecurityApp";
8
9
  import type {AdminChangeEvent, TerrenoAppAdminEvent} from "./adminTypes";
9
10
  import type {ModelRouterRegistration} from "./api";
10
11
  import {addAuthRoutes, addMeRoutes, setupAuth, type UserModel as UserMongooseModel} from "./auth";
@@ -29,6 +30,7 @@ import {
29
30
  import {type AddRoutes, type AuthOptions, logRequests} from "./expressServer";
30
31
  import {addGitHubAuthRoutes, type GitHubAuthOptions, setupGitHubAuth} from "./githubAuth";
31
32
  import {type LoggingOptions, logger, setupLogging} from "./logger";
33
+ import {type McpRequestLogAppOption, resolveMcpRequestLogOption} from "./mcp/adminTracking";
32
34
  import {addMcpOAuthRoutes} from "./mcp/oauth";
33
35
  import {type McpOAuthAppOption, resolveMcpOAuthOption} from "./mcp/oauthMetadata";
34
36
  import {mountMCPServer} from "./mcp/server";
@@ -147,6 +149,17 @@ export interface TerrenoAppOptions {
147
149
  * [Enable MCP OAuth](../how-to/enable-mcp-oauth.md).
148
150
  */
149
151
  mcpOAuth?: McpOAuthAppOption;
152
+ /**
153
+ * Opt-in log of MCP tool calls for the admin panel. `true` keeps rows 30 days. Rows hold
154
+ * metadata only (tool, user, credential ids, duration, outcome, error class), never tool
155
+ * arguments, results, or error text. See [Manage MCP from the admin panel](../how-to/manage-mcp-in-admin.md).
156
+ */
157
+ mcpRequestLog?: McpRequestLogAppOption;
158
+ /**
159
+ * Opt-in MCP tool registry. When true, every tool is recorded in `McpToolSetting` at startup,
160
+ * and tools an admin switches off are hidden from `tools/list` and rejected by `tools/call`.
161
+ */
162
+ mcpToolSettings?: boolean;
150
163
  /**
151
164
  * Versioned MongoDB migrations. `runOnStart` defaults to false. When true, wet `up`
152
165
  * runs after listen and `ensureSyncIndexes`. Production still requires
@@ -267,6 +280,13 @@ export class TerrenoApp {
267
280
  return this.registrations;
268
281
  }
269
282
 
283
+ /**
284
+ * The RBAC access control passed as `accessControl`, if any.
285
+ */
286
+ getAccessControl(): TerrenoAppOptions["accessControl"] {
287
+ return this.options.accessControl;
288
+ }
289
+
270
290
  /**
271
291
  * The application user model this app authenticates against.
272
292
  */
@@ -376,6 +396,9 @@ export class TerrenoApp {
376
396
 
377
397
  const app = express();
378
398
  const options = this.options;
399
+ // A BetterAuthApp registered without its own userModel uses the app's, before its Better Auth
400
+ // instance exists, so the app User guard and sync are installed with it.
401
+ findBetterAuthProvider(this.registrations)?.adoptUserModel?.(options.userModel);
379
402
  // Resolve first so a misconfigured issuer or consent URL fails at boot.
380
403
  const mcpOAuth = resolveMcpOAuthOption(options.mcpOAuth);
381
404
 
@@ -545,6 +568,8 @@ export class TerrenoApp {
545
568
  betterAuth,
546
569
  mcpOAuth,
547
570
  mcpServiceTokens: mcpServiceTokens.enabled,
571
+ requestLog: resolveMcpRequestLogOption(options.mcpRequestLog),
572
+ toolSettings: options.mcpToolSettings === true,
548
573
  userModel: options.userModel,
549
574
  });
550
575
 
@@ -603,10 +628,19 @@ export class TerrenoApp {
603
628
  if (!hasOrgsPlugin) {
604
629
  const orgConfig =
605
630
  typeof this.options.organizations === "object" ? this.options.organizations : {};
631
+ // Org-admins get member recovery routes only when the app registered AccountSecurityApp.
632
+ const accountSecurity =
633
+ orgConfig.accountSecurity ??
634
+ this.registrations.find(
635
+ (registration): registration is AccountSecurityApp =>
636
+ !this.isModelRouterRegistration(registration) &&
637
+ registration instanceof AccountSecurityApp
638
+ );
606
639
  this.register(
607
640
  new OrgsApp({
608
641
  ...orgConfig,
609
642
  access: this.options.accessControl,
643
+ accountSecurity,
610
644
  userModel: this.options.userModel,
611
645
  })
612
646
  );
@@ -0,0 +1,290 @@
1
+ /**
2
+ * Shared setup for the AccountSecurityApp suites: a passport-backed test User model, RBAC
3
+ * access, a TerrenoApp with BetterAuthApp + AuditApp + AccountSecurityApp, and request helpers.
4
+ */
5
+
6
+ import {expect} from "bun:test";
7
+ import type express from "express";
8
+ import mongoose, {Schema} from "mongoose";
9
+ import passportLocalMongoose from "passport-local-mongoose";
10
+ import supertest from "supertest";
11
+
12
+ import {
13
+ AccountSecurityApp,
14
+ type AccountSecurityAppOptions,
15
+ } from "../accountSecurity/accountSecurityApp";
16
+ import {
17
+ clearSecurityActionListenersForTests,
18
+ SECURITY_ACTIONS,
19
+ } from "../accountSecurity/securityEvents";
20
+ import {AuditApp} from "../audit/auditApp";
21
+ import {createAuditEventModel} from "../audit/auditEventModel";
22
+ import {flushAuditRecorderForTests, resetAuditRecorderForTests} from "../audit/record";
23
+ import type {UserModel} from "../auth";
24
+ import type {BetterAuthConfig} from "../betterAuth";
25
+ import {BetterAuthApp} from "../betterAuthApp";
26
+ import type {AuthOptions} from "../expressServer";
27
+ import {clearMCPRegistry} from "../mcp/registry";
28
+ import {McpServiceToken} from "../models/mcpServiceToken";
29
+ import {createAccess} from "../rbac/access";
30
+ import {terrenoStatements} from "../rbac/statements";
31
+ import type {AnyTerrenoAccess} from "../rbac/types";
32
+ import {TerrenoApp, type TerrenoAppOptions} from "../terrenoApp";
33
+ import {API_ORIGIN, PASSWORD, SECRET, uniqueEmail} from "./betterAuthStubs";
34
+
35
+ interface SecurityUserFields {
36
+ admin?: boolean;
37
+ betterAuthId?: string;
38
+ disabled?: boolean;
39
+ email: string;
40
+ name?: string;
41
+ roles?: string[];
42
+ tokenEpoch?: number;
43
+ }
44
+
45
+ // TerrenoApp's JWT setup needs passport-local-mongoose's createStrategy on the user model.
46
+ const getSecurityUserModel = (): mongoose.Model<SecurityUserFields> => {
47
+ if (mongoose.models.AccountSecurityTestUser) {
48
+ return mongoose.models.AccountSecurityTestUser as mongoose.Model<SecurityUserFields>;
49
+ }
50
+ const schema = new Schema<SecurityUserFields>({
51
+ admin: {default: false, description: "Whether the user is an admin", type: Boolean},
52
+ betterAuthId: {description: "Linked Better Auth user id", index: true, type: String},
53
+ disabled: {default: false, description: "Whether the account is disabled", type: Boolean},
54
+ email: {description: "Email address", required: true, type: String},
55
+ name: {description: "Display name", type: String},
56
+ roles: {default: [], description: "RBAC role names", type: [String]},
57
+ tokenEpoch: {default: 0, description: "Bumped to invalidate JWT refresh tokens", type: Number},
58
+ });
59
+ schema.plugin(
60
+ passportLocalMongoose as unknown as (target: Schema, options?: Record<string, unknown>) => void,
61
+ {usernameField: "email"}
62
+ );
63
+ return mongoose.model<SecurityUserFields>("AccountSecurityTestUser", schema);
64
+ };
65
+
66
+ export const SecurityUser = getSecurityUserModel();
67
+ export const securityUserModel = SecurityUser as unknown as UserModel;
68
+ export const AuditEvent = createAuditEventModel(mongoose.connection);
69
+
70
+ export const access = createAccess({
71
+ connection: mongoose.connection,
72
+ organizations: true,
73
+ statements: terrenoStatements,
74
+ userModel: securityUserModel,
75
+ });
76
+
77
+ const baseConfig: BetterAuthConfig = {
78
+ baseURL: API_ORIGIN,
79
+ enabled: true,
80
+ passkey: {origin: [API_ORIGIN], rpID: "localhost", rpName: "Terreno"},
81
+ secret: SECRET,
82
+ twoFactor: {issuer: "Terreno"},
83
+ };
84
+
85
+ /** The Better Auth config every security test app uses, plus `overrides`. */
86
+ export const testBetterAuthConfig = (
87
+ overrides: Partial<BetterAuthConfig> = {}
88
+ ): BetterAuthConfig => ({
89
+ ...baseConfig,
90
+ ...overrides,
91
+ });
92
+
93
+ interface BuildOptions {
94
+ /** `false` builds without RBAC; an access instance replaces the shared {@link access}. */
95
+ accessControl?: boolean | AnyTerrenoAccess;
96
+ /** Pass `false` to build without AccountSecurityApp. */
97
+ accountSecurity?: boolean;
98
+ auditApp?: boolean;
99
+ /** TerrenoApp `authOptions` for the legacy JWT routes (for example recovery mail). */
100
+ authOptions?: AuthOptions;
101
+ config?: Partial<BetterAuthConfig>;
102
+ /** TerrenoApp `organizations`; set, the app is started (skipListen) so OrgsApp registers. */
103
+ organizations?: TerrenoAppOptions["organizations"];
104
+ security?: AccountSecurityAppOptions;
105
+ /** Another app User model (needs passport-local-mongoose). Defaults to `SecurityUser`. */
106
+ userModel?: UserModel;
107
+ }
108
+
109
+ interface SecurityTestApp {
110
+ /** The registered AccountSecurityApp, unless built with `accountSecurity: false`. */
111
+ accountSecurityApp?: AccountSecurityApp;
112
+ app: express.Application;
113
+ betterAuthApp: BetterAuthApp;
114
+ }
115
+
116
+ export const buildApp = ({
117
+ accessControl = true,
118
+ accountSecurity = true,
119
+ auditApp = true,
120
+ authOptions,
121
+ config = {},
122
+ organizations,
123
+ security = {},
124
+ userModel = securityUserModel,
125
+ }: BuildOptions = {}): SecurityTestApp => {
126
+ const betterAuthApp = new BetterAuthApp({
127
+ config: {...baseConfig, ...config},
128
+ userModel,
129
+ });
130
+ const terrenoApp = new TerrenoApp({
131
+ ...(accessControl ? {accessControl: accessControl === true ? access : accessControl} : {}),
132
+ ...(authOptions ? {authOptions} : {}),
133
+ mcpServiceTokens: true,
134
+ ...(organizations ? {organizations} : {}),
135
+ skipListen: true,
136
+ userModel,
137
+ }).register(betterAuthApp);
138
+ if (auditApp) {
139
+ terrenoApp.register(new AuditApp());
140
+ }
141
+ const accountSecurityApp = accountSecurity ? new AccountSecurityApp(security) : undefined;
142
+ if (accountSecurityApp) {
143
+ terrenoApp.register(accountSecurityApp);
144
+ }
145
+ const app = organizations ? terrenoApp.start() : terrenoApp.build();
146
+ return {accountSecurityApp, app, betterAuthApp};
147
+ };
148
+
149
+ /** A recovery mail captured by {@link captureMail}. */
150
+ export interface SentMail {
151
+ subject: string;
152
+ text: string;
153
+ to: string;
154
+ }
155
+
156
+ /** A `sendMail` that keeps every message, plus the `publicAppUrl` recovery links need. */
157
+ export const captureMail = (): {
158
+ config: Pick<BetterAuthConfig, "publicAppUrl" | "sendMail">;
159
+ sent: SentMail[];
160
+ } => {
161
+ const sent: SentMail[] = [];
162
+ return {
163
+ config: {
164
+ publicAppUrl: "https://app.example.com",
165
+ sendMail: async (message): Promise<void> => {
166
+ sent.push(message);
167
+ },
168
+ },
169
+ sent,
170
+ };
171
+ };
172
+
173
+ /** The reset token in a recovery mail's `?token=` link. */
174
+ export const resetTokenFrom = (mail: SentMail): string => {
175
+ const match = /[?&]token=([^&\s"]+)/.exec(mail.text);
176
+ return decodeURIComponent(match?.[1] ?? "");
177
+ };
178
+
179
+ interface SignedUpUser {
180
+ id: string;
181
+ token: string;
182
+ }
183
+
184
+ export const appUserId = async (email: string): Promise<string> => {
185
+ const user = await SecurityUser.findOne({email});
186
+ if (!user) {
187
+ throw new Error(`No app User for ${email}`);
188
+ }
189
+ return String(user._id);
190
+ };
191
+
192
+ export const signUp = async (
193
+ app: express.Application,
194
+ label: string,
195
+ roles: string[] = []
196
+ ): Promise<SignedUpUser & {email: string}> => {
197
+ const email = uniqueEmail(label);
198
+ const res = await supertest(app)
199
+ .post("/api/auth/sign-up/email")
200
+ .set("content-type", "application/json")
201
+ .send({email, name: label, password: PASSWORD});
202
+ expect(res.status).toBe(200);
203
+ const id = await appUserId(email);
204
+ if (roles.length > 0) {
205
+ await SecurityUser.updateOne({_id: id}, {$set: {roles}});
206
+ }
207
+ return {email, id, token: res.body.token as string};
208
+ };
209
+
210
+ export const signInWithPassword = (app: express.Application, email: string): supertest.Test =>
211
+ supertest(app)
212
+ .post("/api/auth/sign-in/email")
213
+ .set("content-type", "application/json")
214
+ .send({email, password: PASSWORD});
215
+
216
+ export const getSummary = (
217
+ app: express.Application,
218
+ token: string,
219
+ userId: string
220
+ ): supertest.Test =>
221
+ supertest(app).get(`/users/${userId}/security`).set("authorization", `Bearer ${token}`);
222
+
223
+ export const resetTwoFactor = (
224
+ app: express.Application,
225
+ token: string,
226
+ userId: string
227
+ ): supertest.Test =>
228
+ supertest(app)
229
+ .post(`/users/${userId}/security/reset-two-factor`)
230
+ .set("authorization", `Bearer ${token}`)
231
+ .send({});
232
+
233
+ const actionIdsWithOrigin = (origin: "admin" | "self"): string[] =>
234
+ Object.entries(SECURITY_ACTIONS)
235
+ .filter(([, definition]) => definition.origin === origin)
236
+ .map(([id]) => id);
237
+
238
+ /**
239
+ * The admin recovery events recorded for the user. Self-service events (such as the
240
+ * `two-factor-enabled` a test's 2FA enrolment records) are left out; see
241
+ * {@link selfSecurityEventsFor}.
242
+ */
243
+ export const securityEventsFor = async (
244
+ userId: string
245
+ ): Promise<{actorId?: unknown; after?: unknown}[]> => {
246
+ await flushAuditRecorderForTests();
247
+ return AuditEvent.find({
248
+ "after.securityAction": {$in: actionIdsWithOrigin("admin")},
249
+ recordId: userId,
250
+ source: "security",
251
+ }).lean();
252
+ };
253
+
254
+ /** The self-service security events (`origin: "self"`) recorded for the user. */
255
+ export const selfSecurityEventsFor = async (
256
+ userId: string
257
+ ): Promise<{actorId?: unknown; after?: unknown}[]> => {
258
+ await flushAuditRecorderForTests();
259
+ return AuditEvent.find({
260
+ "after.securityAction": {$in: actionIdsWithOrigin("self")},
261
+ recordId: userId,
262
+ source: "security",
263
+ }).lean();
264
+ };
265
+
266
+ export const betterAuthCollection = (name: string): ReturnType<mongoose.mongo.Db["collection"]> => {
267
+ const db = mongoose.connection.db;
268
+ if (!db) {
269
+ throw new Error("The test database is not connected");
270
+ }
271
+ return db.collection(name);
272
+ };
273
+
274
+ export const betterAuthIdFor = async (userId: string): Promise<string> => {
275
+ const user = await SecurityUser.findById(userId);
276
+ return user?.betterAuthId ?? "";
277
+ };
278
+
279
+ /** Clears every collection the security suites write, plus in-process recorder state. */
280
+ export const resetAccountSecurityState = async (): Promise<void> => {
281
+ clearMCPRegistry();
282
+ clearSecurityActionListenersForTests();
283
+ resetAuditRecorderForTests();
284
+ await SecurityUser.deleteMany({});
285
+ await AuditEvent.deleteMany({});
286
+ await McpServiceToken.deleteMany({});
287
+ for (const collection of ["user", "session", "account", "twoFactor", "passkey", "verification"]) {
288
+ await betterAuthCollection(collection).deleteMany({});
289
+ }
290
+ };