@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
@@ -57,7 +57,7 @@ exports.terrenoStatements = {
57
57
  announcementImpression: ["list", "read"],
58
58
  configuration: ["read", "update"],
59
59
  consentForm: MODEL_CRUD,
60
- consentResponse: ["list", "read"],
60
+ consentResponse: ["list", "read", "signOnBehalf"],
61
61
  featureFlag: MODEL_CRUD,
62
62
  organization: exports.ORGANIZATION_ACTIONS,
63
63
  rbac: ["read", "manageRoles", "assignRoles"],
@@ -70,6 +70,8 @@ exports.terrenoStatements = {
70
70
  "impersonate",
71
71
  "setPassword",
72
72
  "updateIdentity",
73
+ "manageSecurity",
74
+ "issueSignInLink",
73
75
  ],
74
76
  };
75
77
  exports.READ_ACTIONS = ["read", "list", "view"];
@@ -125,7 +127,14 @@ exports.terrenoStatementDescriptions = {
125
127
  list: "List traces and observability status",
126
128
  read: "View trace detail and run trace test helpers",
127
129
  },
130
+ consentResponse: {
131
+ list: "List consent responses",
132
+ read: "View consent responses",
133
+ signOnBehalf: "Record, view, and void provisional consent signatures for other users",
134
+ },
128
135
  user: {
136
+ issueSignInLink: "Create a sign-in account for a legacy user and hand them a set-password link (AccountSecurityApp)",
137
+ manageSecurity: "View any user's sign-in methods and run account recovery (AccountSecurityApp)",
129
138
  updateIdentity: "Change another user's email, disabled flag, email verification, or linked Better Auth and GitHub ids",
130
139
  },
131
140
  };
@@ -188,8 +188,14 @@ export interface TerrenoAccess<S extends Statements> {
188
188
  readonly statements: S;
189
189
  readonly ac: ReturnType<typeof createAccessControl<S>>;
190
190
  can: (args: AccessCheckArgs<S>) => Promise<AccessResult>;
191
+ /**
192
+ * The user's effective permissions. With `requireComplete`, a permission source that failed and
193
+ * whose grants are unknown throws 503 instead of leaving its grants out; use it for a user whose
194
+ * missing permissions would loosen a check (the target of "may the actor act on this user?").
195
+ */
191
196
  getPermissions: (args: {
192
197
  user: User;
198
+ requireComplete?: boolean;
193
199
  }) => Promise<PermissionSet>;
194
200
  queryFilter: (args: {
195
201
  user?: User;
@@ -73,7 +73,8 @@ const assertCanWriteTargetUser = async ({ accessControl, actor, modelName, targe
73
73
  return;
74
74
  }
75
75
  const actorPermissions = await getPermissions({ user: actor });
76
- const targetPermissions = await getPermissions({ user: target });
76
+ // A target missing a failed source's grants would look less privileged than it is.
77
+ const targetPermissions = await getPermissions({ requireComplete: true, user: target });
77
78
  if ((0, permissionUtils_1.isPermissionSubset)(actorPermissions, targetPermissions)) {
78
79
  return;
79
80
  }
@@ -65,6 +65,13 @@ const describeCaster = (caster) => {
65
65
  required: false,
66
66
  };
67
67
  };
68
+ /**
69
+ * Whether a path is required on every document. A conditional `required` (a function) only
70
+ * applies to some documents, so clients must not treat the field as always present.
71
+ */
72
+ const isAlwaysRequired = (schemaPath) => {
73
+ return Boolean(schemaPath.isRequired) && typeof schemaPath.originalRequiredValue !== "function";
74
+ };
68
75
  const describeSchemaPath = (path, schemaPath) => {
69
76
  const enumValues = schemaPath.enumValues?.length
70
77
  ? schemaPath.enumValues
@@ -75,7 +82,7 @@ const describeSchemaPath = (path, schemaPath) => {
75
82
  enum: enumValues?.length ? enumValues : undefined,
76
83
  kind: normalizeKind(schemaPath.instance),
77
84
  ref: schemaPath.options?.ref,
78
- required: Boolean(schemaPath.isRequired),
85
+ required: isAlwaysRequired(schemaPath),
79
86
  system: isSystemField(path),
80
87
  };
81
88
  if (schemaPath.instance === "Array") {
@@ -75,8 +75,13 @@ const seedBetterAuthUser = async ({ auth, user, userModel, }) => {
75
75
  });
76
76
  }
77
77
  // The seed created or signed in to this Better Auth account itself, so its email is trusted
78
- // for linking an existing app user (for example one seeded under the legacy JWT flow).
79
- return (0, betterAuthSetup_1.syncBetterAuthUser)(userModel, authUser, undefined, { trustEmail: true });
78
+ // for linking an existing app user (for example one seeded under the legacy JWT flow). With a
79
+ // `userModel` on `auth`, the sign-up itself is refused for a legacy User unless the seed
80
+ // password matches its passport hash, the same way a real sign-up is.
81
+ return (0, betterAuthSetup_1.syncBetterAuthUser)(userModel, authUser, undefined, {
82
+ password: user.password,
83
+ trustEmail: true,
84
+ });
80
85
  };
81
86
  exports.seedBetterAuthUser = seedBetterAuthUser;
82
87
  const selectSteps = (steps, only) => {
@@ -8,6 +8,7 @@ import { type ConfigurationAppOptions, type ConfigurationModelLike } from "./con
8
8
  import { type AddRoutes, type AuthOptions } from "./expressServer";
9
9
  import { type GitHubAuthOptions } from "./githubAuth";
10
10
  import { type LoggingOptions } from "./logger";
11
+ import { type McpRequestLogAppOption } from "./mcp/adminTracking";
11
12
  import { type McpOAuthAppOption } from "./mcp/oauthMetadata";
12
13
  import { type McpServiceTokensAppOption } from "./mcp/serviceTokens";
13
14
  import { type StartupMigrationsOption } from "./migrations/runner";
@@ -92,6 +93,17 @@ export interface TerrenoAppOptions {
92
93
  * [Enable MCP OAuth](../how-to/enable-mcp-oauth.md).
93
94
  */
94
95
  mcpOAuth?: McpOAuthAppOption;
96
+ /**
97
+ * Opt-in log of MCP tool calls for the admin panel. `true` keeps rows 30 days. Rows hold
98
+ * metadata only (tool, user, credential ids, duration, outcome, error class), never tool
99
+ * arguments, results, or error text. See [Manage MCP from the admin panel](../how-to/manage-mcp-in-admin.md).
100
+ */
101
+ mcpRequestLog?: McpRequestLogAppOption;
102
+ /**
103
+ * Opt-in MCP tool registry. When true, every tool is recorded in `McpToolSetting` at startup,
104
+ * and tools an admin switches off are hidden from `tools/list` and rejected by `tools/call`.
105
+ */
106
+ mcpToolSettings?: boolean;
95
107
  /**
96
108
  * Versioned MongoDB migrations. `runOnStart` defaults to false. When true, wet `up`
97
109
  * runs after listen and `ensureSyncIndexes`. Production still requires
@@ -199,6 +211,10 @@ export declare class TerrenoApp {
199
211
  * Returns registered model routers and plugins in mount order.
200
212
  */
201
213
  getRegistrations(): readonly (ModelRouterRegistration | TerrenoPlugin)[];
214
+ /**
215
+ * The RBAC access control passed as `accessControl`, if any.
216
+ */
217
+ getAccessControl(): TerrenoAppOptions["accessControl"];
202
218
  /**
203
219
  * The application user model this app authenticates against.
204
220
  */
@@ -44,6 +44,7 @@ const cors_1 = __importDefault(require("cors"));
44
44
  const express_1 = __importDefault(require("express"));
45
45
  const mongoose_1 = __importDefault(require("mongoose"));
46
46
  const qs_1 = __importDefault(require("qs"));
47
+ const accountSecurityApp_1 = require("./accountSecurity/accountSecurityApp");
47
48
  const auth_1 = require("./auth");
48
49
  const betterAuthApp_1 = require("./betterAuthApp");
49
50
  const betterAuthSetup_1 = require("./betterAuthSetup");
@@ -53,6 +54,7 @@ const errors_1 = require("./errors");
53
54
  const expressServer_1 = require("./expressServer");
54
55
  const githubAuth_1 = require("./githubAuth");
55
56
  const logger_1 = require("./logger");
57
+ const adminTracking_1 = require("./mcp/adminTracking");
56
58
  const oauth_1 = require("./mcp/oauth");
57
59
  const oauthMetadata_1 = require("./mcp/oauthMetadata");
58
60
  const server_1 = require("./mcp/server");
@@ -178,6 +180,12 @@ class TerrenoApp {
178
180
  getRegistrations() {
179
181
  return this.registrations;
180
182
  }
183
+ /**
184
+ * The RBAC access control passed as `accessControl`, if any.
185
+ */
186
+ getAccessControl() {
187
+ return this.options.accessControl;
188
+ }
181
189
  /**
182
190
  * The application user model this app authenticates against.
183
191
  */
@@ -277,6 +285,9 @@ class TerrenoApp {
277
285
  (0, logger_1.setupLogging)(this.options.loggingOptions);
278
286
  const app = (0, express_1.default)();
279
287
  const options = this.options;
288
+ // A BetterAuthApp registered without its own userModel uses the app's, before its Better Auth
289
+ // instance exists, so the app User guard and sync are installed with it.
290
+ (0, betterAuthApp_1.findBetterAuthProvider)(this.registrations)?.adoptUserModel?.(options.userModel);
280
291
  // Resolve first so a misconfigured issuer or consent URL fails at boot.
281
292
  const mcpOAuth = (0, oauthMetadata_1.resolveMcpOAuthOption)(options.mcpOAuth);
282
293
  // Record mount paths on layers for Express 5 → OpenAPI compat
@@ -420,6 +431,8 @@ class TerrenoApp {
420
431
  betterAuth,
421
432
  mcpOAuth,
422
433
  mcpServiceTokens: mcpServiceTokens.enabled,
434
+ requestLog: (0, adminTracking_1.resolveMcpRequestLogOption)(options.mcpRequestLog),
435
+ toolSettings: options.mcpToolSettings === true,
423
436
  userModel: options.userModel,
424
437
  });
425
438
  if (options.configureApp) {
@@ -466,9 +479,14 @@ class TerrenoApp {
466
479
  const hasOrgsPlugin = this.registrations.some((registration) => !this.isModelRouterRegistration(registration) && registration instanceof orgsApp_1.OrgsApp);
467
480
  if (!hasOrgsPlugin) {
468
481
  const orgConfig = typeof this.options.organizations === "object" ? this.options.organizations : {};
482
+ // Org-admins get member recovery routes only when the app registered AccountSecurityApp.
483
+ const accountSecurity = orgConfig.accountSecurity ??
484
+ this.registrations.find((registration) => !this.isModelRouterRegistration(registration) &&
485
+ registration instanceof accountSecurityApp_1.AccountSecurityApp);
469
486
  this.register(new orgsApp_1.OrgsApp({
470
487
  ...orgConfig,
471
488
  access: this.options.accessControl,
489
+ accountSecurity,
472
490
  userModel: this.options.userModel,
473
491
  }));
474
492
  }
@@ -1,5 +1,8 @@
1
1
  import mongoose, { type Model } from "mongoose";
2
+ import type { UserModel as AuthUserModel } from "../auth";
2
3
  export interface User {
4
+ _id: mongoose.Types.ObjectId;
5
+ id: string;
3
6
  admin: boolean;
4
7
  name?: string;
5
8
  username: string;
@@ -19,11 +22,15 @@ export interface StaffUser extends User {
19
22
  }
20
23
  export interface FoodCategory {
21
24
  _id?: string;
25
+ addendums?: FoodCategoryAddendum[];
22
26
  name: string;
23
27
  show: boolean;
24
28
  created: Date;
25
29
  updated: Date;
26
30
  }
31
+ interface FoodCategoryAddendum {
32
+ text: string;
33
+ }
27
34
  export interface Food {
28
35
  _id: string;
29
36
  name: string;
@@ -52,35 +59,27 @@ export interface RequiredField {
52
59
  name: string;
53
60
  about?: string;
54
61
  }
55
- export declare const UserModel: mongoose.Model<User, {}, {}, {}, mongoose.Document<unknown, {}, User, {}, mongoose.DefaultSchemaOptions> & User & {
62
+ export declare const UserModel: mongoose.Model<User, {}, {}, {}, mongoose.Document<unknown, {}, User, {}, mongoose.DefaultSchemaOptions> & User & Required<{
56
63
  _id: mongoose.Types.ObjectId;
57
- } & {
64
+ }> & {
58
65
  __v: number;
59
- } & {
60
- id: string;
61
66
  }, any, User>;
62
- export declare const SuperUserModel: mongoose.Model<User & SuperUser, {}, {}, {
63
- id: string;
64
- }, mongoose.Document<unknown, {}, User & SuperUser, {
65
- id: string;
66
- }, mongoose.DefaultSchemaOptions> & Omit<User & SuperUser & {
67
+ /**
68
+ * `UserModel` typed as the auth `UserModel` for `setupAuth`, `TerrenoApp({userModel})`, and
69
+ * friends. passport-local-mongoose adds the statics at runtime but ships no types, and the auth
70
+ * `User._id` uses mongoose's schema `ObjectId` type, so the models are not structurally related.
71
+ */
72
+ export declare const authUserModel: AuthUserModel;
73
+ export declare const SuperUserModel: mongoose.Model<User & SuperUser, {}, {}, {}, mongoose.Document<unknown, {}, User & SuperUser, {}, mongoose.DefaultSchemaOptions> & User & SuperUser & Required<{
67
74
  _id: mongoose.Types.ObjectId;
68
- } & {
75
+ }> & {
69
76
  __v: number;
70
- }, "id"> & mongoose.HydratedDocumentOverrides<{
71
- id: string;
72
- }>, any, User & SuperUser>;
73
- export declare const StaffUserModel: mongoose.Model<User & StaffUser, {}, {}, {
74
- id: string;
75
- }, mongoose.Document<unknown, {}, User & StaffUser, {
76
- id: string;
77
- }, mongoose.DefaultSchemaOptions> & Omit<User & StaffUser & {
77
+ }, any, User & SuperUser>;
78
+ export declare const StaffUserModel: mongoose.Model<User & StaffUser, {}, {}, {}, mongoose.Document<unknown, {}, User & StaffUser, {}, mongoose.DefaultSchemaOptions> & User & StaffUser & Required<{
78
79
  _id: mongoose.Types.ObjectId;
79
- } & {
80
+ }> & {
80
81
  __v: number;
81
- }, "id"> & mongoose.HydratedDocumentOverrides<{
82
- id: string;
83
- }>, any, User & StaffUser>;
82
+ }, any, User & StaffUser>;
84
83
  export declare const FoodModel: Model<Food>;
85
84
  export declare const RequiredModel: mongoose.Model<RequiredField, {}, {}, {}, mongoose.Document<unknown, {}, RequiredField, {}, mongoose.DefaultSchemaOptions> & RequiredField & {
86
85
  _id: mongoose.Types.ObjectId;
@@ -89,3 +88,4 @@ export declare const RequiredModel: mongoose.Model<RequiredField, {}, {}, {}, mo
89
88
  } & {
90
89
  id: string;
91
90
  }, any, RequiredField>;
91
+ export {};
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.RequiredModel = exports.FoodModel = exports.StaffUserModel = exports.SuperUserModel = exports.UserModel = void 0;
6
+ exports.RequiredModel = exports.FoodModel = exports.StaffUserModel = exports.SuperUserModel = exports.authUserModel = exports.UserModel = void 0;
7
7
  const mongoose_1 = require("mongoose");
8
8
  const passport_local_mongoose_1 = __importDefault(require("passport-local-mongoose"));
9
9
  const plugins_1 = require("../plugins");
@@ -47,6 +47,12 @@ userSchema.methods.postCreate = async function (body) {
47
47
  return this.save();
48
48
  };
49
49
  exports.UserModel = (0, mongoose_1.model)("User", userSchema);
50
+ /**
51
+ * `UserModel` typed as the auth `UserModel` for `setupAuth`, `TerrenoApp({userModel})`, and
52
+ * friends. passport-local-mongoose adds the statics at runtime but ships no types, and the auth
53
+ * `User._id` uses mongoose's schema `ObjectId` type, so the models are not structurally related.
54
+ */
55
+ exports.authUserModel = exports.UserModel;
50
56
  const superUserSchema = new mongoose_1.Schema({
51
57
  superTitle: { description: "The super user's title", required: true, type: String },
52
58
  });
@@ -60,6 +66,14 @@ const staffUserSchema = new mongoose_1.Schema({
60
66
  });
61
67
  exports.StaffUserModel = exports.UserModel.discriminator("Staff", staffUserSchema);
62
68
  const foodCategorySchema = new mongoose_1.Schema({
69
+ addendums: {
70
+ description: "Extra details about this food category",
71
+ type: [
72
+ new mongoose_1.Schema({
73
+ text: { description: "The additional category detail", type: String },
74
+ }),
75
+ ],
76
+ },
63
77
  name: { description: "The name of the food category", type: String },
64
78
  show: { description: "Whether this category is visible", type: Boolean },
65
79
  }, { timestamps: { createdAt: "created", updatedAt: "updated" } });
@@ -1,23 +1,17 @@
1
1
  import type { TestData } from "./types";
2
2
  /** Seeds only the standard users (legacy helper). */
3
- export declare const setupDb: () => Promise<readonly [import("mongoose").Document<unknown, {}, import("./models").User, {}, import("mongoose").DefaultSchemaOptions> & import("./models").User & {
3
+ export declare const setupDb: () => Promise<readonly [import("mongoose").Document<unknown, {}, import("./models").User, {}, import("mongoose").DefaultSchemaOptions> & import("./models").User & Required<{
4
4
  _id: import("mongoose").Types.ObjectId;
5
- } & {
5
+ }> & {
6
6
  __v: number;
7
- } & {
8
- id: string;
9
- }, import("mongoose").Document<unknown, {}, import("./models").User, {}, import("mongoose").DefaultSchemaOptions> & import("./models").User & {
7
+ }, import("mongoose").Document<unknown, {}, import("./models").User, {}, import("mongoose").DefaultSchemaOptions> & import("./models").User & Required<{
10
8
  _id: import("mongoose").Types.ObjectId;
11
- } & {
9
+ }> & {
12
10
  __v: number;
13
- } & {
14
- id: string;
15
- }, import("mongoose").Document<unknown, {}, import("./models").User, {}, import("mongoose").DefaultSchemaOptions> & import("./models").User & {
11
+ }, import("mongoose").Document<unknown, {}, import("./models").User, {}, import("mongoose").DefaultSchemaOptions> & import("./models").User & Required<{
16
12
  _id: import("mongoose").Types.ObjectId;
17
- } & {
13
+ }> & {
18
14
  __v: number;
19
- } & {
20
- id: string;
21
15
  }]>;
22
16
  /** Seeds users, foods, and required docs — the recommended API test baseline. */
23
17
  export declare const setupTestData: () => Promise<TestData>;
package/dist/tests.d.ts CHANGED
@@ -6,6 +6,7 @@ import { type Food, type FoodCategory, FoodModel, type RequiredField, RequiredMo
6
6
  import { loadTestDataFromCache, setupTestCache } from "./tests/mongoTestSetup";
7
7
  import { setupDb, setupTestData } from "./tests/testHelper";
8
8
  import type { TestData } from "./tests/types";
9
+ export { authUserModel } from "./tests/models";
9
10
  export type { Food, FoodCategory, RequiredField, StaffUser, SuperUser, TestData, User };
10
11
  export { createTestData, FoodModel, loadTestDataFromCache, RequiredModel, StaffUserModel, SuperUserModel, setupDb, setupTestCache, setupTestData, UserModel, };
11
12
  export declare const getBaseServer: () => Express;
package/dist/tests.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.loadTestData = exports.authAsUser = exports.getBaseServer = exports.UserModel = exports.setupTestData = exports.setupTestCache = exports.setupDb = exports.SuperUserModel = exports.StaffUserModel = exports.RequiredModel = exports.loadTestDataFromCache = exports.FoodModel = exports.createTestData = void 0;
3
+ exports.loadTestData = exports.authAsUser = exports.getBaseServer = exports.UserModel = exports.setupTestData = exports.setupTestCache = exports.setupDb = exports.SuperUserModel = exports.StaffUserModel = exports.RequiredModel = exports.loadTestDataFromCache = exports.FoodModel = exports.createTestData = exports.authUserModel = void 0;
4
4
  const test_1 = require("@terreno/test");
5
5
  const openApiCompat_1 = require("./openApiCompat");
6
6
  const createTestData_1 = require("./tests/createTestData");
@@ -17,6 +17,8 @@ Object.defineProperty(exports, "setupTestCache", { enumerable: true, get: functi
17
17
  const testHelper_1 = require("./tests/testHelper");
18
18
  Object.defineProperty(exports, "setupDb", { enumerable: true, get: function () { return testHelper_1.setupDb; } });
19
19
  Object.defineProperty(exports, "setupTestData", { enumerable: true, get: function () { return testHelper_1.setupTestData; } });
20
+ var models_2 = require("./tests/models");
21
+ Object.defineProperty(exports, "authUserModel", { enumerable: true, get: function () { return models_2.authUserModel; } });
20
22
  const getBaseServer = () => {
21
23
  return (0, test_1.getBaseServer)({
22
24
  patchOpenApiCompat: openApiCompat_1.patchAppUse,
@@ -20,6 +20,14 @@ export interface ConsentResponseDocument extends mongoose.Document {
20
20
  userAgent?: string;
21
21
  contentSnapshot?: string;
22
22
  formVersionSnapshot?: number;
23
+ provisional: boolean;
24
+ provisionalSignedBy?: mongoose.Types.ObjectId;
25
+ provisionalNote?: string;
26
+ provisionalSignerIp?: string;
27
+ provisionalSignerUserAgent?: string;
28
+ voidedAt?: Date;
29
+ voidedBy?: mongoose.Types.ObjectId;
30
+ voidReason?: string;
23
31
  created: Date;
24
32
  updated: Date;
25
33
  deleted: boolean;
@@ -0,0 +1,58 @@
1
+ import type mongoose from "mongoose";
2
+ import type { FindExactlyOnePlugin, FindOneOrNonePlugin } from "../plugins";
3
+ import type { RequestCredential } from "../requestContext";
4
+ /** Outcome of one MCP tool call. */
5
+ export type McpRequestLogOutcome = "ok" | "tool_error" | "exception";
6
+ /**
7
+ * Metadata for one MCP tool call. Holds no tool arguments, results, or error text, since those
8
+ * can carry personal data.
9
+ */
10
+ export interface McpRequestLogDocument extends mongoose.Document {
11
+ _id: mongoose.Types.ObjectId;
12
+ created: Date;
13
+ credential?: RequestCredential;
14
+ durationMs: number;
15
+ /** Error class name for an `exception` outcome, such as `ForbiddenError`. Never the message. */
16
+ errorName?: string;
17
+ expiresAt: Date;
18
+ oauthClientId?: string;
19
+ oauthFamilyId?: string;
20
+ outcome: McpRequestLogOutcome;
21
+ serviceTokenId?: mongoose.Types.ObjectId;
22
+ toolName: string;
23
+ updated: Date;
24
+ userId?: mongoose.Types.ObjectId;
25
+ }
26
+ export type McpRequestLogMethods = Record<string, never>;
27
+ export interface McpRequestLogStatics extends FindExactlyOnePlugin<McpRequestLogDocument>, FindOneOrNonePlugin<McpRequestLogDocument> {
28
+ }
29
+ export type McpRequestLogModel = mongoose.Model<McpRequestLogDocument> & McpRequestLogStatics;
30
+ export type McpRequestLogSchema = mongoose.Schema<McpRequestLogDocument, McpRequestLogModel, McpRequestLogMethods>;
31
+ /** Where an MCP tool comes from. */
32
+ export type McpToolSource = "model" | "custom";
33
+ /** Admin switch and registry entry for one MCP tool. A tool with no row is enabled. */
34
+ export interface McpToolSettingDocument extends mongoose.Document {
35
+ _id: mongoose.Types.ObjectId;
36
+ created: Date;
37
+ description?: string;
38
+ enabled: boolean;
39
+ /** False when the running server no longer registers this tool. */
40
+ registered: boolean;
41
+ lastRegisteredAt?: Date;
42
+ name: string;
43
+ source: McpToolSource;
44
+ updated: Date;
45
+ }
46
+ export type McpToolSettingMethods = Record<string, never>;
47
+ export interface McpToolSettingStatics extends FindExactlyOnePlugin<McpToolSettingDocument>, FindOneOrNonePlugin<McpToolSettingDocument> {
48
+ /** Names of tools an admin turned off. */
49
+ disabledNames: (this: McpToolSettingModel) => Promise<Set<string>>;
50
+ /** Upsert one row per registered tool and mark rows for tools that are gone. */
51
+ syncRegistered: (this: McpToolSettingModel, tools: Array<{
52
+ description: string;
53
+ name: string;
54
+ source: McpToolSource;
55
+ }>) => Promise<void>;
56
+ }
57
+ export type McpToolSettingModel = mongoose.Model<McpToolSettingDocument> & McpToolSettingStatics;
58
+ export type McpToolSettingSchema = mongoose.Schema<McpToolSettingDocument, McpToolSettingModel, McpToolSettingMethods>;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,18 +1,42 @@
1
1
  import type mongoose from "mongoose";
2
2
  import type { FindExactlyOnePlugin, FindOneOrNonePlugin } from "../plugins";
3
- /** A client registered through dynamic client registration (RFC 7591). Public clients only. */
3
+ export type McpOAuthTokenEndpointAuthMethod = "none" | "client_secret_basic" | "client_secret_post";
4
+ /** Options for `McpOAuthClient.issueConfidential`. The secret is returned once. */
5
+ export interface McpOAuthConfidentialClientOptions {
6
+ clientId?: string;
7
+ clientName: string;
8
+ scope?: string;
9
+ tokenEndpointAuthMethod: Exclude<McpOAuthTokenEndpointAuthMethod, "none">;
10
+ userId: mongoose.Types.ObjectId | string;
11
+ }
12
+ /**
13
+ * A public authorization-code client, or a confidential `client_credentials` client bound to a
14
+ * user. Public clients leave `tokenEndpointAuthMethod` unset.
15
+ */
4
16
  export interface McpOAuthClientDocument extends mongoose.Document {
5
17
  _id: mongoose.Types.ObjectId;
6
18
  clientId: string;
7
19
  clientName?: string;
20
+ /** SHA-256 hash of the client secret. Set only for confidential clients. */
21
+ clientSecretHash?: string;
8
22
  created: Date;
9
23
  grantTypes: string[];
10
24
  redirectUris: string[];
11
25
  responseTypes: string[];
26
+ revokedAt?: Date;
12
27
  scope?: string;
28
+ tokenEndpointAuthMethod?: McpOAuthTokenEndpointAuthMethod;
13
29
  updated: Date;
30
+ /** User a `client_credentials` token acts as. */
31
+ userId?: mongoose.Types.ObjectId;
14
32
  }
15
33
  interface McpOAuthClientStatics extends FindExactlyOnePlugin<McpOAuthClientDocument>, FindOneOrNonePlugin<McpOAuthClientDocument> {
34
+ issueConfidential: (this: McpOAuthClientModel, options: McpOAuthConfidentialClientOptions) => Promise<{
35
+ client: McpOAuthClientDocument;
36
+ clientSecret: string;
37
+ }>;
38
+ /** Mark the client revoked and end every token it holds. */
39
+ revoke: (this: McpOAuthClientModel, clientId: string) => Promise<McpOAuthClientDocument | null>;
16
40
  }
17
41
  export interface McpOAuthClientModel extends mongoose.Model<McpOAuthClientDocument>, McpOAuthClientStatics {
18
42
  }
@@ -66,6 +90,11 @@ export interface McpOAuthTokenDocument extends mongoose.Document {
66
90
  clientId: string;
67
91
  created: Date;
68
92
  familyId: string;
93
+ /**
94
+ * False for an access-only `client_credentials` token. The stored refresh hash is then of a
95
+ * discarded secret and must not be exchanged.
96
+ */
97
+ hasRefreshToken?: boolean;
69
98
  refreshExpiresAt: Date;
70
99
  refreshTokenHash: string;
71
100
  resource?: string;
@@ -80,6 +109,8 @@ export interface McpOAuthTokenIssueOptions {
80
109
  accessTokenTtlSeconds: number;
81
110
  clientId: string;
82
111
  familyId?: string;
112
+ /** When false, issue an access token only and do not return a refresh token. Default true. */
113
+ includeRefreshToken?: boolean;
83
114
  refreshTokenTtlSeconds: number;
84
115
  resource?: string;
85
116
  scope?: string;
@@ -91,9 +122,13 @@ interface McpOAuthTokenStatics extends FindExactlyOnePlugin<McpOAuthTokenDocumen
91
122
  issue: (this: McpOAuthTokenModel, options: McpOAuthTokenIssueOptions) => Promise<{
92
123
  accessToken: string;
93
124
  mcpOAuthToken: McpOAuthTokenDocument;
94
- refreshToken: string;
125
+ refreshToken?: string;
95
126
  }>;
127
+ /** Revoke every family issued to this client. */
128
+ revokeClient: (this: McpOAuthTokenModel, clientId: string) => Promise<void>;
96
129
  revokeFamily: (this: McpOAuthTokenModel, familyId: string) => Promise<void>;
130
+ /** Revoke every active token family the user holds. Returns how many families were revoked. */
131
+ revokeAllForUser: (this: McpOAuthTokenModel, userId: mongoose.Types.ObjectId | string) => Promise<number>;
97
132
  verifyAccessToken: (this: McpOAuthTokenModel, token: string) => Promise<McpOAuthTokenDocument | null>;
98
133
  }
99
134
  export interface McpOAuthTokenModel extends mongoose.Model<McpOAuthTokenDocument>, McpOAuthTokenStatics {
@@ -24,6 +24,8 @@ export interface McpServiceTokenStatics extends FindExactlyOnePlugin<McpServiceT
24
24
  };
25
25
  tokenEpoch?: number;
26
26
  }) => Promise<void>;
27
+ /** Revoke every active service token the user holds. Returns how many were revoked. */
28
+ revokeAllForUser: (this: McpServiceTokenModel, userId: mongoose.Types.ObjectId | string) => Promise<number>;
27
29
  revokeForUser: (this: McpServiceTokenModel, user: {
28
30
  _id: {
29
31
  toString(): string;