@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
@@ -0,0 +1,138 @@
1
+ import {DateTime} from "luxon";
2
+ import mongoose from "mongoose";
3
+
4
+ import {logger} from "../logger";
5
+ import {createdUpdatedPlugin, findExactlyOne, findOneOrNone} from "../plugins";
6
+ import type {McpToolSettingDocument, McpToolSettingModel, McpToolSource} from "../types/mcpAdmin";
7
+
8
+ /**
9
+ * Registry of MCP tools with an admin on/off switch. Rows are written when the server mounts
10
+ * with `mcpToolSettings` on. A tool with no row, or with `enabled: true`, is served.
11
+ */
12
+ const mcpToolSettingSchema = new mongoose.Schema<McpToolSettingDocument, McpToolSettingModel>(
13
+ {
14
+ description: {
15
+ description: "Tool description as sent to MCP clients",
16
+ type: String,
17
+ },
18
+ enabled: {
19
+ default: true,
20
+ description: "When false, the tool is hidden from tools/list and tools/call rejects it",
21
+ type: Boolean,
22
+ },
23
+ lastRegisteredAt: {
24
+ description: "Last server start that registered this tool",
25
+ type: Date,
26
+ },
27
+ name: {
28
+ description: "MCP tool name",
29
+ required: true,
30
+ type: String,
31
+ unique: true,
32
+ },
33
+ registered: {
34
+ default: true,
35
+ description: "False when the running server no longer registers this tool",
36
+ type: Boolean,
37
+ },
38
+ source: {
39
+ description: "model (generated from a modelRouter) or custom (registerMCPTool)",
40
+ enum: ["model", "custom"],
41
+ required: true,
42
+ type: String,
43
+ },
44
+ },
45
+ {strict: "throw", toJSON: {virtuals: true}, toObject: {virtuals: true}}
46
+ );
47
+
48
+ /** How long one process reuses the disabled-tool set before reading it again. */
49
+ const DISABLED_NAMES_TTL_MS = 5000;
50
+
51
+ // Per-process cache so /mcp does not query Mongo on every request. Writes through this model
52
+ // clear it at once; other processes pick up a change within DISABLED_NAMES_TTL_MS.
53
+ const disabledNamesCache: {expiresAt: number; names?: Set<string>} = {expiresAt: 0};
54
+
55
+ const clearDisabledNamesCache = (): void => {
56
+ disabledNamesCache.expiresAt = 0;
57
+ disabledNamesCache.names = undefined;
58
+ };
59
+
60
+ for (const hook of [
61
+ "save",
62
+ "updateOne",
63
+ "updateMany",
64
+ "findOneAndUpdate",
65
+ "deleteOne",
66
+ "deleteMany",
67
+ "findOneAndDelete",
68
+ ] as const) {
69
+ mcpToolSettingSchema.post(hook, clearDisabledNamesCache);
70
+ }
71
+ mcpToolSettingSchema.post("bulkWrite", clearDisabledNamesCache);
72
+
73
+ mcpToolSettingSchema.plugin(createdUpdatedPlugin);
74
+ mcpToolSettingSchema.plugin(findOneOrNone);
75
+ mcpToolSettingSchema.plugin(findExactlyOne);
76
+
77
+ mcpToolSettingSchema.statics = {
78
+ ...mcpToolSettingSchema.statics,
79
+ async disabledNames(this: McpToolSettingModel): Promise<Set<string>> {
80
+ const now = DateTime.now().toMillis();
81
+ if (disabledNamesCache.names && now < disabledNamesCache.expiresAt) {
82
+ return disabledNamesCache.names;
83
+ }
84
+ try {
85
+ const rows = await this.find({enabled: false}).select({name: 1}).lean();
86
+ const names = new Set(rows.map((row) => row.name));
87
+ disabledNamesCache.names = names;
88
+ disabledNamesCache.expiresAt = now + DISABLED_NAMES_TTL_MS;
89
+ return names;
90
+ } catch (error) {
91
+ // Keep enforcing the last known switches rather than re-enabling every tool. With no
92
+ // known state, fail the request (closed) instead of serving tools an admin turned off.
93
+ if (disabledNamesCache.names) {
94
+ logger.warn(`[mcp] Tool settings read failed; using last known: ${String(error)}`);
95
+ return disabledNamesCache.names;
96
+ }
97
+ throw error;
98
+ }
99
+ },
100
+ async syncRegistered(
101
+ this: McpToolSettingModel,
102
+ tools: Array<{description: string; name: string; source: McpToolSource}>
103
+ ): Promise<void> {
104
+ const now = DateTime.now().toJSDate();
105
+ if (tools.length > 0) {
106
+ // `enabled` is only set on insert so a restart never undoes an admin's switch.
107
+ await this.bulkWrite(
108
+ tools.map((tool) => ({
109
+ updateOne: {
110
+ filter: {name: tool.name},
111
+ update: {
112
+ $set: {
113
+ description: tool.description,
114
+ lastRegisteredAt: now,
115
+ registered: true,
116
+ source: tool.source,
117
+ },
118
+ $setOnInsert: {enabled: true},
119
+ },
120
+ upsert: true,
121
+ },
122
+ }))
123
+ );
124
+ }
125
+ await this.updateMany(
126
+ {name: {$nin: tools.map((tool) => tool.name)}, registered: {$ne: false}},
127
+ {$set: {registered: false}}
128
+ );
129
+ },
130
+ };
131
+
132
+ export const McpToolSetting =
133
+ (mongoose.models.TerrenoMcpToolSetting as McpToolSettingModel | undefined) ??
134
+ mongoose.model<McpToolSettingDocument, McpToolSettingModel>(
135
+ "TerrenoMcpToolSetting",
136
+ mcpToolSettingSchema,
137
+ "mcptoolsettings"
138
+ );
@@ -13,6 +13,8 @@ export interface VersionConfigDocument extends mongoose.Document {
13
13
  updateUrl?: string;
14
14
  /** How often clients should poll for version updates, in minutes. Defaults to 1440 (24 hours). */
15
15
  pollingIntervalMinutes: number;
16
+ /** Singleton sentinel backing the unique index; not selected by default. */
17
+ _singleton?: "config";
16
18
  created?: Date;
17
19
  updated?: Date;
18
20
  }
@@ -12,7 +12,7 @@ import {NotificationPreference} from "../models/notificationPreference";
12
12
  import {clearSyncRegistry} from "../sync/registry";
13
13
  import {SyncApp} from "../sync/syncApp";
14
14
  import {TerrenoApp} from "../terrenoApp";
15
- import {authAsUser, setupDb, UserModel} from "../tests";
15
+ import {authAsUser, authUserModel, setupDb, UserModel} from "../tests";
16
16
  import {configureNotificationService, getNotificationService} from "./notificationService";
17
17
  import {NotificationsApp} from "./notificationsApp";
18
18
  import {
@@ -23,7 +23,7 @@ import {
23
23
  interface FakeComms {
24
24
  mailCalls: Array<{html?: string; subject: string; to: string}>;
25
25
  mailUserIds: Array<string | undefined>;
26
- pushCalls: Array<{title: string; userId: string}>;
26
+ pushCalls: Array<{body: string; title: string; userId: string}>;
27
27
  smsCalls: Array<{body: string; to: string}>;
28
28
  smsUserIds: Array<string | undefined>;
29
29
  }
@@ -37,7 +37,7 @@ const buildFakeComms = (
37
37
  message: {html?: string; subject: string; to: string},
38
38
  options?: {userId?: string}
39
39
  ) => Promise<{accepted: boolean}>;
40
- sendPushToUser: (message: {title: string; userId: string}) => Promise<unknown[]>;
40
+ sendPushToUser: (message: {body: string; title: string; userId: string}) => Promise<unknown[]>;
41
41
  sendSms: (
42
42
  message: {body: string; to: string},
43
43
  options?: {userId?: string}
@@ -77,10 +77,7 @@ const buildFakeComms = (
77
77
  };
78
78
 
79
79
  const buildApp = (
80
- options: {
81
- getComms?: () => ReturnType<typeof buildFakeComms>["getComms"];
82
- retainDays?: number;
83
- } = {}
80
+ options: {getComms?: ReturnType<typeof buildFakeComms>["getComms"]; retainDays?: number} = {}
84
81
  ): express.Application => {
85
82
  clearSyncRegistry();
86
83
  return new TerrenoApp({
@@ -114,7 +111,7 @@ describe("NotificationsApp", () => {
114
111
  const app = buildApp();
115
112
  userAgent = await authAsUser(app, "notAdmin");
116
113
  await UserModel.deleteOne({email: "other-user@example.com"});
117
- await signupUser(UserModel, "other-user@example.com", "password");
114
+ await signupUser(authUserModel, "other-user@example.com", "password");
118
115
  otherUserAgent = await authWithCredentials(app, {
119
116
  email: "other-user@example.com",
120
117
  password: "password",
@@ -22,13 +22,35 @@ describe("normalizeSlackChannelName", () => {
22
22
  });
23
23
  });
24
24
 
25
+ /** The request body fields the Slack helpers send. */
26
+ interface SlackRequestBody {
27
+ blocks?: unknown[];
28
+ channel?: string;
29
+ force?: boolean;
30
+ name?: string;
31
+ text?: string;
32
+ users?: string;
33
+ }
34
+
35
+ /** Slack doubles return `data`, `status`, and sometimes `headers`, not a whole AxiosResponse. */
36
+ interface SlackResponseDouble {
37
+ data: unknown;
38
+ headers?: {get: (name: string) => string | undefined};
39
+ status: number;
40
+ }
41
+ type AxiosPostDouble = (url: string, body: SlackRequestBody) => Promise<SlackResponseDouble>;
42
+ type AxiosGetDouble = (
43
+ url: string,
44
+ config?: {params?: {types?: string}}
45
+ ) => Promise<SlackResponseDouble>;
46
+
25
47
  describe("Slack Web API", () => {
26
- let mockAxiosPost: Mock<typeof axios.post>;
27
- let mockAxiosGet: Mock<typeof axios.get>;
48
+ let mockAxiosPost: Mock<AxiosPostDouble>;
49
+ let mockAxiosGet: Mock<AxiosGetDouble>;
28
50
 
29
51
  beforeEach(() => {
30
- mockAxiosPost = spyOn(axios, "post");
31
- mockAxiosGet = spyOn(axios, "get");
52
+ mockAxiosPost = spyOn(axios, "post") as unknown as Mock<AxiosPostDouble>;
53
+ mockAxiosGet = spyOn(axios, "get") as unknown as Mock<AxiosGetDouble>;
32
54
  process.env.SLACK_BOT_TOKEN = "xoxb-test";
33
55
  (Sentry.captureException as Mock<typeof Sentry.captureException>).mockClear();
34
56
  });
@@ -40,7 +62,7 @@ describe("Slack Web API", () => {
40
62
  });
41
63
 
42
64
  it("creates a private channel, invites members, and posts the first message", async () => {
43
- mockAxiosPost.mockImplementation(async (url: string, body: {name?: string; text?: string}) => {
65
+ mockAxiosPost.mockImplementation(async (url: string, body: SlackRequestBody) => {
44
66
  if (String(url).endsWith("conversations.create")) {
45
67
  return {
46
68
  data: {channel: {id: "C012345678", is_private: true, name: body.name}, ok: true},
@@ -120,7 +142,7 @@ describe("Slack Web API", () => {
120
142
 
121
143
  expect(result.alreadyMemberUserIds).toEqual(["U012ABCDEF"]);
122
144
  expect(result.invitedUserIds).toEqual([]);
123
- const body = mockAxiosPost.mock.calls[0]?.[1] as {channel?: string; users?: string};
145
+ const body = mockAxiosPost.mock.calls[0]?.[1];
124
146
  expect(body).toEqual({channel: "C012345678", force: true, users: "U012ABCDEF"});
125
147
  });
126
148
 
@@ -211,8 +233,8 @@ describe("Slack Web API", () => {
211
233
 
212
234
  const found = await findSlackChannelByName({name: "case-123"});
213
235
  expect(found).toEqual({channelId: "C012345678", isPrivate: true, name: "case-123"});
214
- const firstParams = mockAxiosGet.mock.calls[0]?.[1] as {params?: {types?: string}};
215
- expect(firstParams.params?.types).toBe("public_channel,private_channel");
236
+ const firstParams = mockAxiosGet.mock.calls[0]?.[1];
237
+ expect(firstParams?.params?.types).toBe("public_channel,private_channel");
216
238
  });
217
239
 
218
240
  it("returns undefined when no visible channel has that name", async () => {
@@ -461,7 +461,7 @@ describe("openApi middleware no-op paths", () => {
461
461
  listOpenApiMiddleware(
462
462
  FoodModel,
463
463
  {
464
- openApi: createOpenApiStub((spec: Record<string, unknown>) => {
464
+ openApi: createOpenApiStub((spec?: Record<string, unknown>) => {
465
465
  captured = spec;
466
466
  return createPassThroughMiddleware();
467
467
  }),
@@ -482,7 +482,7 @@ describe("openApi middleware no-op paths", () => {
482
482
  it("listOpenApiMiddleware omits x-terreno-sync when sync is not configured", () => {
483
483
  let captured: Record<string, unknown> | undefined;
484
484
  listOpenApiMiddleware(FoodModel, {
485
- openApi: createOpenApiStub((spec: Record<string, unknown>) => {
485
+ openApi: createOpenApiStub((spec?: Record<string, unknown>) => {
486
486
  captured = spec;
487
487
  return createPassThroughMiddleware();
488
488
  }),
@@ -500,7 +500,7 @@ describe("openApi middleware no-op paths", () => {
500
500
  it("listOpenApiMiddleware falls back to the model collection name without routePath", () => {
501
501
  let captured: Record<string, unknown> | undefined;
502
502
  listOpenApiMiddleware(FoodModel, {
503
- openApi: createOpenApiStub((spec: Record<string, unknown>) => {
503
+ openApi: createOpenApiStub((spec?: Record<string, unknown>) => {
504
504
  captured = spec;
505
505
  return createPassThroughMiddleware();
506
506
  }),
@@ -521,7 +521,7 @@ describe("openApi middleware no-op paths", () => {
521
521
 
522
522
  it("listOpenApiMiddleware maps tenant and custom sync scopes", () => {
523
523
  let captured: Record<string, unknown> | undefined;
524
- const capturePath = (spec: Record<string, unknown>): express.RequestHandler => {
524
+ const capturePath = (spec?: Record<string, unknown>): express.RequestHandler => {
525
525
  captured = spec;
526
526
  return createPassThroughMiddleware();
527
527
  };
@@ -557,7 +557,7 @@ describe("openApiValidator", () => {
557
557
  const res = {} as Response;
558
558
  middleware(req, res, () => {});
559
559
 
560
- expect(req.query.page).toBe(3);
560
+ expect<unknown>(req.query.page).toBe(3);
561
561
  });
562
562
 
563
563
  it("throws validation error when query does not match", () => {
@@ -665,7 +665,7 @@ describe("openApiValidator", () => {
665
665
  });
666
666
 
667
667
  expect(nextCalled).toBe(true);
668
- expect(req.query.page).toBe(2);
668
+ expect<unknown>(req.query.page).toBe(2);
669
669
  });
670
670
 
671
671
  it("skips when neither body nor query schemas are provided", () => {
@@ -698,7 +698,7 @@ describe("openApiValidator", () => {
698
698
  });
699
699
 
700
700
  expect(nextCalled).toBe(true);
701
- expect(req.query.page).toBe(5);
701
+ expect<unknown>(req.query.page).toBe(5);
702
702
  });
703
703
 
704
704
  it("runs only body validation when no query schema is provided", () => {
@@ -0,0 +1,39 @@
1
+ import {APIError} from "../errors";
2
+ import type {MembershipDocument} from "../types/membership";
3
+ import {Membership} from "./organizationModel";
4
+
5
+ export const LAST_ORG_ADMIN_TITLE = "Cannot remove the last org-admin";
6
+
7
+ const countActiveOrgAdmins = async (
8
+ organizationId: MembershipDocument["organizationId"]
9
+ ): Promise<number> => {
10
+ return Membership.countDocuments({
11
+ organizationId,
12
+ roleName: "org-admin",
13
+ status: "active",
14
+ });
15
+ };
16
+
17
+ /**
18
+ * Refuses (400) a membership change that would leave the organization with no active org-admin,
19
+ * so an org can never lose every administrator through a role change, suspension, or removal.
20
+ */
21
+ export const assertNotLastOrgAdmin = async (
22
+ membership: MembershipDocument,
23
+ nextRoleName?: string,
24
+ nextStatus?: string
25
+ ): Promise<void> => {
26
+ const remainsOrgAdmin =
27
+ (nextRoleName ?? membership.roleName) === "org-admin" &&
28
+ (nextStatus ?? membership.status) === "active";
29
+ if (remainsOrgAdmin) {
30
+ return;
31
+ }
32
+ if (membership.roleName !== "org-admin" || membership.status !== "active") {
33
+ return;
34
+ }
35
+ const activeAdmins = await countActiveOrgAdmins(membership.organizationId);
36
+ if (activeAdmins <= 1) {
37
+ throw new APIError({status: 400, title: LAST_ORG_ADMIN_TITLE});
38
+ }
39
+ };
@@ -11,14 +11,14 @@ const platformUser = (roles: string[]): User =>
11
11
  admin: false,
12
12
  id: new mongoose.Types.ObjectId().toString(),
13
13
  roles,
14
- }) as User;
14
+ }) as unknown as User;
15
15
 
16
16
  const memberUser = (): User =>
17
17
  ({
18
18
  admin: false,
19
19
  id: new mongoose.Types.ObjectId().toString(),
20
20
  roles: [],
21
- }) as User;
21
+ }) as unknown as User;
22
22
 
23
23
  describe("OrgQueryFilter", () => {
24
24
  it("throws when organization context is missing", () => {
@@ -1,6 +1,6 @@
1
1
  import {beforeEach, describe, it} from "bun:test";
2
2
  import {assert} from "chai";
3
- import mongoose, {model, Schema} from "mongoose";
3
+ import mongoose, {model, Schema, type UpdateQuery} from "mongoose";
4
4
 
5
5
  import {orgScopedPlugin} from "./orgPlugin";
6
6
 
@@ -106,11 +106,12 @@ describe("orgScopedPlugin", () => {
106
106
  title: "Pinned",
107
107
  });
108
108
 
109
- for (const update of [
109
+ const updates: UpdateQuery<OrgScopedWidget>[] = [
110
110
  {$unset: {organizationId: 1}},
111
111
  {$rename: {organizationId: "formerOrganizationId"}},
112
112
  {$rename: {formerOrganizationId: "organizationId"}},
113
- ]) {
113
+ ];
114
+ for (const update of updates) {
114
115
  let error: unknown;
115
116
  try {
116
117
  await OrgScopedWidgetModel.updateOne({_id: widget._id}, update);
@@ -74,7 +74,7 @@ describe("organization RBAC", () => {
74
74
  assert.isTrue(operator.isLocked);
75
75
  assert.deepEqual(operator.permissions.organization, [...terrenoStatements.organization]);
76
76
  assert.deepEqual(operator.permissions.admin, ["access"]);
77
- assert.deepEqual(operator.permissions.user, ["list", "read", "update"]);
77
+ assert.deepEqual(operator.permissions.user, ["list", "read", "update", "manageSecurity"]);
78
78
 
79
79
  const orgAdminRole = await RbacRole.findOne({name: "org-admin"});
80
80
  assert.isNull(orgAdminRole);
@@ -18,6 +18,7 @@ import {createAccess} from "../rbac/access";
18
18
  import {terrenoStatements} from "../rbac/statements";
19
19
  import {getBaseServer} from "../tests";
20
20
  import {type User, UserModel} from "../tests/models";
21
+ import type {OrganizationDocument} from "../types/organization";
21
22
  import {Membership, Organization} from "./organizationModel";
22
23
  import {ORGANIZATION_DISABLED_TITLE, orgContextMiddleware, resolveOrgContext} from "./orgContext";
23
24
  import {isOrgMemberPermission, OrgQueryFilter} from "./orgPermissions";
@@ -96,7 +97,8 @@ describe("org security regressions", () => {
96
97
  update: [Permissions.IsAuthenticated, isOrgMemberPermission],
97
98
  },
98
99
  preCreate: async (body, req) => {
99
- const organizationId = req.organization?._id;
100
+ // orgContextMiddleware sets req.organization; the Express typing leaves it unknown.
101
+ const organizationId = (req.organization as OrganizationDocument | undefined)?._id;
100
102
  if (!organizationId) {
101
103
  throw new Error("organization context required");
102
104
  }
@@ -56,7 +56,7 @@ describe("organization settings schema", () => {
56
56
  assert.instanceOf(extraKeyError, ValidationError);
57
57
  assert.equal((extraKeyError as ValidationError).title, "Organization settings are invalid");
58
58
  assert.match(
59
- String((extraKeyError as ValidationError).meta?.fields?.settings),
59
+ String(((extraKeyError as ValidationError).meta?.fields as {settings?: unknown})?.settings),
60
60
  /Unknown settings field: plan/
61
61
  );
62
62
 
@@ -2,15 +2,22 @@ import {afterEach, beforeEach, describe, it} from "bun:test";
2
2
  import {authAsUser as loginWithPassword} from "@terreno/test";
3
3
  import {assert} from "chai";
4
4
  import type {Application} from "express";
5
- import mongoose from "mongoose";
5
+ import mongoose, {type HydratedDocument} from "mongoose";
6
6
  import type {PassportLocalMongooseDocument} from "passport-local-mongoose";
7
7
 
8
- import {type UserModel as AuthUserModel, addAuthRoutes, setupAuth} from "../auth";
8
+ import {
9
+ type User as AuthUser,
10
+ type UserModel as AuthUserModel,
11
+ addAuthRoutes,
12
+ setupAuth,
13
+ } from "../auth";
9
14
  import {apiErrorMiddleware, apiUnauthorizedMiddleware} from "../errors";
10
15
  import {createAccess} from "../rbac/access";
11
16
  import {terrenoStatements} from "../rbac/statements";
12
17
  import {getBaseServer} from "../tests";
13
18
  import {type User, UserModel} from "../tests/models";
19
+ import type {MembershipDocument} from "../types/membership";
20
+ import type {OrganizationDocument} from "../types/organization";
14
21
  import {Membership, Organization} from "./organizationModel";
15
22
  import {
16
23
  createOrganizationSettingsSchema,
@@ -38,6 +45,7 @@ const createUser = async (args: {email: string; roles?: string[]}): Promise<User
38
45
  describe("OrgsApp", () => {
39
46
  let app: Application;
40
47
  let auditEvents: OrgAuditEvent[];
48
+ let access: ReturnType<typeof createAccess>;
41
49
 
42
50
  beforeEach(async () => {
43
51
  await Promise.all([
@@ -46,7 +54,7 @@ describe("OrgsApp", () => {
46
54
  UserModel.deleteMany({}),
47
55
  ]);
48
56
  auditEvents = [];
49
- const access = createAccess({
57
+ access = createAccess({
50
58
  connection: mongoose.connection,
51
59
  organizations: true,
52
60
  statements: terrenoStatements,
@@ -246,6 +254,99 @@ describe("OrgsApp", () => {
246
254
  assert.equal(mixedCase.status, 409);
247
255
  });
248
256
 
257
+ it("applies a membership's org-admin grants at once, not after the permission cache expires", async () => {
258
+ const operator = await createUser({email: "operator@example.com", roles: ["operator"]});
259
+ const member = await createUser({email: "new-org-admin@example.com"});
260
+ const org = await Organization.create({name: "Acme", ownerId: operator._id});
261
+ const operatorAgent = await loginWithPassword(app, {
262
+ email: "operator@example.com",
263
+ password: PASSWORD,
264
+ });
265
+ const memberUser = member as unknown as AuthUser;
266
+ // Resolve (and cache) the user's permissions before they join.
267
+ assert.isUndefined((await access.getPermissions({user: memberUser})).admin);
268
+
269
+ const attached = await operatorAgent
270
+ .post(`/orgs/${org._id}/members`)
271
+ .send({email: "new-org-admin@example.com", roleName: "org-admin"});
272
+ assert.equal(attached.status, 201);
273
+ assert.deepEqual((await access.getPermissions({user: memberUser})).admin, ["access"]);
274
+
275
+ const demoted = await operatorAgent
276
+ .patch(`/orgs/${org._id}/members/${attached.body.data._id}`)
277
+ .send({roleName: "member"});
278
+ // The operator's attach left the new member as the only org-admin, so demoting is refused;
279
+ // suspend instead, which another active org-admin makes possible.
280
+ assert.equal(demoted.status, 400);
281
+ await Membership.create({organizationId: org._id, roleName: "org-admin", userId: operator._id});
282
+ const suspended = await operatorAgent
283
+ .patch(`/orgs/${org._id}/members/${attached.body.data._id}`)
284
+ .send({status: "suspended"});
285
+ assert.equal(suspended.status, 200);
286
+ assert.isUndefined((await access.getPermissions({user: memberUser})).admin);
287
+ });
288
+
289
+ describe("permission cache", () => {
290
+ const setUpOrgAdmins = async (): Promise<{
291
+ operatorAgent: Awaited<ReturnType<typeof loginWithPassword>>;
292
+ org: HydratedDocument<OrganizationDocument>;
293
+ orgAdmins: AuthUser[];
294
+ removable: HydratedDocument<MembershipDocument>;
295
+ }> => {
296
+ const operator = await createUser({email: "operator@example.com", roles: ["operator"]});
297
+ const first = await createUser({email: "first-org-admin@example.com"});
298
+ const second = await createUser({email: "second-org-admin@example.com"});
299
+ const org = await Organization.create({name: "Acme", ownerId: operator._id});
300
+ const removable = await Membership.create({
301
+ organizationId: org._id,
302
+ roleName: "org-admin",
303
+ userId: first._id,
304
+ });
305
+ await Membership.create({organizationId: org._id, roleName: "org-admin", userId: second._id});
306
+ const orgAdmins = [first, second] as unknown as AuthUser[];
307
+ // Resolve (and cache) each org-admin's permissions before the change.
308
+ for (const orgAdmin of orgAdmins) {
309
+ assert.deepEqual((await access.getPermissions({user: orgAdmin})).admin, ["access"]);
310
+ }
311
+ const operatorAgent = await loginWithPassword(app, {
312
+ email: "operator@example.com",
313
+ password: PASSWORD,
314
+ });
315
+ return {operatorAgent, org, orgAdmins, removable};
316
+ };
317
+
318
+ it("takes a removed org-admin's permissions away at once", async () => {
319
+ const {operatorAgent, org, orgAdmins, removable} = await setUpOrgAdmins();
320
+
321
+ const removed = await operatorAgent.delete(`/orgs/${org._id}/members/${removable._id}`);
322
+
323
+ assert.equal(removed.status, 204);
324
+ assert.isUndefined((await access.getPermissions({user: orgAdmins[0] as AuthUser})).admin);
325
+ });
326
+
327
+ it("takes every org-admin's permissions away at once when the organization is disabled", async () => {
328
+ const {operatorAgent, org, orgAdmins} = await setUpOrgAdmins();
329
+
330
+ const disabled = await operatorAgent.patch(`/orgs/${org._id}`).send({disabled: true});
331
+
332
+ assert.equal(disabled.status, 200);
333
+ for (const orgAdmin of orgAdmins) {
334
+ assert.isUndefined((await access.getPermissions({user: orgAdmin})).admin);
335
+ }
336
+ });
337
+
338
+ it("takes every org-admin's permissions away at once when the organization is deleted", async () => {
339
+ const {operatorAgent, org, orgAdmins} = await setUpOrgAdmins();
340
+
341
+ const deleted = await operatorAgent.delete(`/orgs/${org._id}`);
342
+
343
+ assert.equal(deleted.status, 204);
344
+ for (const orgAdmin of orgAdmins) {
345
+ assert.isUndefined((await access.getPermissions({user: orgAdmin})).admin);
346
+ }
347
+ });
348
+ });
349
+
249
350
  it("attaches an existing user by userId", async () => {
250
351
  const operator = await createUser({email: "operator@example.com", roles: ["operator"]});
251
352
  const member = await createUser({email: "member-id@example.com"});