@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,720 @@
1
+ /**
2
+ * AccountSecurityApp: per-user security summary and recovery routes for platform staff.
3
+ *
4
+ * A framework plugin with its own Express router (the OrgsApp precedent), not modelRouter
5
+ * actions. `mountSecurityRoutes(router, authorize)` mounts the same handlers under any prefix,
6
+ * so the org-admin prefix (`/orgs/:orgId/members/:userId/security/*`) reuses them with its own
7
+ * authorizer. Each recovery action is one row in the action table; the summary lists only the
8
+ * actions this server supports and that apply to the user.
9
+ */
10
+
11
+ import type express from "express";
12
+ import {type NextFunction, type Request, type Response, Router} from "express";
13
+
14
+ import {asyncHandler, type OpenApiMiddleware} from "../api";
15
+ import {AuditApp} from "../audit/auditApp";
16
+ import {isAuditRecorderInstalled} from "../audit/record";
17
+ import {authenticateMiddleware, type User, type UserModel} from "../auth";
18
+ import {findBetterAuthProvider, getProvidedBetterAuth} from "../betterAuthApp";
19
+ import type {BetterAuthInstance} from "../betterAuthSetup";
20
+ import {APIError, ForbiddenError, NotFoundError} from "../errors";
21
+ import {logger} from "../logger";
22
+ import {MCP_OAUTH_ACCESS_TOKEN_PREFIX} from "../models/mcpOAuthToken";
23
+ import {MCP_SERVICE_TOKEN_PREFIX} from "../models/mcpServiceToken";
24
+ import {createOpenApiBuilder} from "../openApiBuilder";
25
+ import {runWithOrgContext} from "../orgs/orgContext";
26
+ import type {PermissionSet} from "../rbac/statements";
27
+ import type {AnyTerrenoAccess} from "../rbac/types";
28
+ import {getCurrentRequestContext, type RequestCredential} from "../requestContext";
29
+ import type {TerrenoApp} from "../terrenoApp";
30
+ import type {TerrenoPlugin} from "../terrenoPlugin";
31
+ import type {MembershipDocument} from "../types/membership";
32
+ import type {OrganizationDocument} from "../types/organization";
33
+ import {
34
+ disableAccountAction,
35
+ enableAccountAction,
36
+ issueSignInLinkAction,
37
+ revokeSessionsAction,
38
+ sendPasswordResetAction,
39
+ } from "./accessActions";
40
+ import {
41
+ type AccountSecurityActionSummary,
42
+ type AccountSecurityFeatures,
43
+ type AccountSecurityService,
44
+ type AccountSecurityState,
45
+ type AccountSecuritySummary,
46
+ createAccountSecurityService,
47
+ userIdOf,
48
+ } from "./accountSecurityService";
49
+ import {removePasskeyAction, unlinkProviderAction} from "./credentialActions";
50
+ import {suspendMembershipAction} from "./membershipActions";
51
+ import {
52
+ onSecurityAction,
53
+ recordSecurityAction,
54
+ SECURITY_ACTIONS,
55
+ type SecurityActionId,
56
+ type SecurityActionOrg,
57
+ } from "./securityEvents";
58
+ import {
59
+ createSecurityNotificationListener,
60
+ type SecurityMailConfig,
61
+ type SecurityNotificationsOptions,
62
+ } from "./securityNotifications";
63
+
64
+ /** The registration that currently owns security notification emails (see subscribeNotifications). */
65
+ let activeNotifications: {owner: AccountSecurityApp; stop: () => void} | undefined;
66
+
67
+ /** The RBAC statement that grants the platform security routes. */
68
+ export const MANAGE_SECURITY_PERMISSION = {user: ["manageSecurity"]} as const;
69
+
70
+ /** Who is acting, and for org-admin routes, the org they act for. */
71
+ export interface SecurityAuthorization {
72
+ actor: User;
73
+ org?: SecurityActionOrg;
74
+ /**
75
+ * Org routes: the organization and each user's own membership in it. The D9 reach check then
76
+ * resolves the actor under `actorMembership` and the target under `targetMembership`, so both
77
+ * are judged with their org-scoped grants. Without it (platform routes) both are resolved
78
+ * outside any org context.
79
+ */
80
+ orgScope?: SecurityOrgScope;
81
+ }
82
+
83
+ /** Each user's own membership in the organization an org route acts for. */
84
+ export interface SecurityOrgScope {
85
+ /** Absent for platform staff acting through the org prefix without a membership. */
86
+ actorMembership?: MembershipDocument;
87
+ organization: OrganizationDocument;
88
+ targetMembership: MembershipDocument;
89
+ }
90
+
91
+ /**
92
+ * Decides whether `req.user` may act on `targetUserId`. Throws an `APIError` to refuse: 403 when
93
+ * the caller lacks the right, 404 when the target is out of their reach.
94
+ */
95
+ export type SecurityAuthorizer = (args: {
96
+ req: Request;
97
+ targetUserId: string;
98
+ }) => Promise<SecurityAuthorization>;
99
+
100
+ /** What a security action handler receives. */
101
+ export interface SecurityActionContext {
102
+ actor: User;
103
+ features: AccountSecurityFeatures;
104
+ org?: SecurityActionOrg;
105
+ req: Request;
106
+ service: AccountSecurityService;
107
+ target: User;
108
+ }
109
+
110
+ /**
111
+ * What a handler returns. A `changed: false` result (nothing to do) answers 200 and is not
112
+ * recorded; `data` is merged into the response body.
113
+ */
114
+ export interface SecurityActionResult {
115
+ /** Extra fields for the AuditEvent `after` (such as which passkey was removed). No secrets. */
116
+ audit?: Record<string, unknown>;
117
+ changed: boolean;
118
+ data?: Record<string, unknown>;
119
+ }
120
+
121
+ /** One row of the action table: a recovery route and the rules for listing it. */
122
+ export interface SecurityRouteAction {
123
+ id: SecurityActionId;
124
+ /** Whether the user's current state makes the action worth offering in the summary. */
125
+ isApplicable: (args: {
126
+ features: AccountSecurityFeatures;
127
+ org?: SecurityActionOrg;
128
+ state: AccountSecurityState;
129
+ }) => boolean;
130
+ /** Whether this server can run it at all. Unsupported actions answer 404. */
131
+ isSupported: (features: AccountSecurityFeatures) => boolean;
132
+ method: "delete" | "post";
133
+ /**
134
+ * Only org-admin prefixes run it (such as `suspend-membership`, which needs the `org`).
135
+ * `mountSecurityRoutes` skips it unless the mount passes `includeOrgOnly`, so the platform
136
+ * `/users` prefix never exposes it.
137
+ */
138
+ orgOnly?: boolean;
139
+ /** Path under `/:userId/security`, such as `/reset-two-factor` or `/passkeys/:passkeyId`. */
140
+ path: string;
141
+ /**
142
+ * Only platform staff may run it. `mountSecurityRoutes` skips it unless the mount passes
143
+ * `includePlatformOnly`, so org-admin prefixes never expose it.
144
+ */
145
+ platformOnly?: boolean;
146
+ /**
147
+ * An RBAC permission the actor needs on top of the route's authorizer, such as
148
+ * `{user: ["issueSignInLink"]}`. Without RBAC the actor needs `admin: true`. Actions the actor
149
+ * may not run answer 403 and are left out of the summary.
150
+ */
151
+ requiredPermission?: {readonly [resource: string]: readonly string[]};
152
+ run: (context: SecurityActionContext) => Promise<SecurityActionResult>;
153
+ }
154
+
155
+ export const resetTwoFactorAction: SecurityRouteAction = {
156
+ id: "reset-two-factor",
157
+ isApplicable: ({state}) => state.twoFactor.enabled,
158
+ isSupported: (features) => features.twoFactor,
159
+ method: "post",
160
+ path: "/reset-two-factor",
161
+ run: async ({service, target}) => service.resetTwoFactor(target),
162
+ };
163
+
164
+ /** The built-in action table, in display order. */
165
+ export const defaultSecurityActions = (): SecurityRouteAction[] => [
166
+ resetTwoFactorAction,
167
+ removePasskeyAction,
168
+ unlinkProviderAction,
169
+ revokeSessionsAction,
170
+ sendPasswordResetAction,
171
+ disableAccountAction,
172
+ enableAccountAction,
173
+ suspendMembershipAction,
174
+ issueSignInLinkAction,
175
+ ];
176
+
177
+ /** Options for {@link AccountSecurityApp.mountSecurityRoutes}. */
178
+ export interface MountSecurityRoutesOptions {
179
+ /**
180
+ * Mount and list actions marked `platformOnly` (such as `issue-sign-in-link`). Only the
181
+ * platform mount sets it; org-admin prefixes leave it off.
182
+ */
183
+ includePlatformOnly?: boolean;
184
+ /**
185
+ * Mount and list actions marked `orgOnly` (such as `suspend-membership`). Only the org-admin
186
+ * prefix (`OrgsApp`) sets it.
187
+ */
188
+ includeOrgOnly?: boolean;
189
+ /**
190
+ * Path in front of `/:userId/security` on `router`, such as `/:orgId/members`. Put a parent
191
+ * prefix's params here rather than mounting a nested router under them: OpenAPI documents only
192
+ * the params in each leaf route's own path.
193
+ */
194
+ pathPrefix?: string;
195
+ }
196
+
197
+ export interface AccountSecurityAppOptions {
198
+ /** Extra recovery actions, mounted and listed after the built-in ones. */
199
+ actions?: SecurityRouteAction[];
200
+ /**
201
+ * RBAC access control. Platform routes require `user:manageSecurity`. Defaults to the
202
+ * TerrenoApp's `accessControl`; without either, they require `admin: true`.
203
+ */
204
+ accessControl?: AnyTerrenoAccess;
205
+ /**
206
+ * Pass `false` to run without AuditApp. Otherwise registration throws unless AuditApp is
207
+ * registered, because every recovery action must leave an audit record.
208
+ */
209
+ audit?: boolean;
210
+ /** Prefix for the platform routes. Defaults to `/users`. */
211
+ basePath?: string;
212
+ /**
213
+ * Security notification emails: every recorded security action (admin recovery and the user's
214
+ * own changes) emails the affected user. On by default whenever `sendMail` is configured; the
215
+ * org name is left out unless `includeOrgName` is true.
216
+ */
217
+ notifications?: SecurityNotificationsOptions;
218
+ /**
219
+ * Better Auth instance. Defaults to the registered BetterAuthApp's. Required outside
220
+ * TerrenoApp (setupServer); without it every Better Auth feature reads as off.
221
+ */
222
+ getBetterAuth?: () => BetterAuthInstance | undefined;
223
+ /**
224
+ * App page base for `issue-sign-in-link` URLs (`{publicAppUrl}/resetPassword?token=`). Defaults
225
+ * to the registered BetterAuthApp's `publicAppUrl`.
226
+ */
227
+ publicAppUrl?: string;
228
+ /** App User model. Defaults to the TerrenoApp's `userModel`. */
229
+ userModel?: UserModel;
230
+ }
231
+
232
+ /** The credentials that prove the caller is the person at the keyboard. */
233
+ const OWN_SESSION_CREDENTIALS: readonly RequestCredential[] = ["jwt", "better-auth-session"];
234
+
235
+ const DELEGATED_CREDENTIAL_TITLE = "Account security requires your own session";
236
+
237
+ const OUT_OF_REACH_TITLE = "Target holds permissions you lack";
238
+
239
+ const SELF_TARGET_TITLE = "Use your own security settings to change your account";
240
+
241
+ const bearerToken = (req: Request): string | undefined => {
242
+ const authorization = req.headers.authorization;
243
+ if (typeof authorization !== "string") {
244
+ return undefined;
245
+ }
246
+ return authorization.startsWith("Bearer ") ? authorization.slice(7) : authorization;
247
+ };
248
+
249
+ /** Refuses delegated agent bearers (MCP service tokens, MCP OAuth tokens) before auth runs. */
250
+ const rejectDelegatedBearer = (req: Request, _res: Response, next: NextFunction): void => {
251
+ const token = bearerToken(req);
252
+ if (
253
+ token?.startsWith(MCP_SERVICE_TOKEN_PREFIX) ||
254
+ token?.startsWith(MCP_OAUTH_ACCESS_TOKEN_PREFIX)
255
+ ) {
256
+ next(new ForbiddenError(DELEGATED_CREDENTIAL_TITLE));
257
+ return;
258
+ }
259
+ next();
260
+ };
261
+
262
+ /**
263
+ * The credential that authenticated the request. Outside TerrenoApp (setupServer has no request
264
+ * context) it is read from what the auth middleware left on the request.
265
+ */
266
+ const requestCredentialOf = (req: Request): RequestCredential | undefined => {
267
+ const fromContext = getCurrentRequestContext()?.credential;
268
+ if (fromContext) {
269
+ return fromContext;
270
+ }
271
+ const withAuth = req as Request & {authTokenPayload?: unknown; betterAuthSession?: unknown};
272
+ if (withAuth.betterAuthSession) {
273
+ return "better-auth-session";
274
+ }
275
+ if (withAuth.authTokenPayload) {
276
+ return "jwt";
277
+ }
278
+ return undefined;
279
+ };
280
+
281
+ /** Allows only the user's own session (a Terreno JWT or a Better Auth session). */
282
+ const requireOwnSession = (req: Request, _res: Response, next: NextFunction): void => {
283
+ const credential = requestCredentialOf(req);
284
+ if (!credential || !OWN_SESSION_CREDENTIALS.includes(credential)) {
285
+ next(new ForbiddenError(DELEGATED_CREDENTIAL_TITLE));
286
+ return;
287
+ }
288
+ next();
289
+ };
290
+
291
+ const rolesOf = (user: User): string[] => (user as User & {roles?: string[]}).roles ?? [];
292
+
293
+ const missingPermissions = (held: PermissionSet, required: PermissionSet): string[] => {
294
+ const missing: string[] = [];
295
+ for (const [resource, actions] of Object.entries(required)) {
296
+ const heldActions = new Set(held[resource] ?? []);
297
+ for (const action of actions) {
298
+ if (!heldActions.has(action)) {
299
+ missing.push(`${resource}:${action}`);
300
+ }
301
+ }
302
+ }
303
+ return missing;
304
+ };
305
+
306
+ const permissionLabels = (permission: SecurityRouteAction["requiredPermission"]): string[] =>
307
+ Object.entries(permission ?? {}).flatMap(([resource, actions]) =>
308
+ actions.map((action) => `${resource}:${action}`)
309
+ );
310
+
311
+ const targetUserIdOf = (req: Request): string => {
312
+ const value = req.params.userId;
313
+ return typeof value === "string" ? value : "";
314
+ };
315
+
316
+ /** Two actions with one id would share a summary entry and an audit name, so refuse them. */
317
+ const assertUniqueActionIds = (actions: readonly SecurityRouteAction[]): void => {
318
+ const seen = new Set<string>();
319
+ for (const action of actions) {
320
+ if (seen.has(action.id)) {
321
+ throw new APIError({
322
+ detail: `Two security actions use the id "${action.id}"; give the custom action its own id.`,
323
+ status: 500,
324
+ title: "Duplicate security action id",
325
+ });
326
+ }
327
+ seen.add(action.id);
328
+ }
329
+ };
330
+
331
+ export class AccountSecurityApp implements TerrenoPlugin {
332
+ private readonly options: AccountSecurityAppOptions;
333
+ private readonly actions: SecurityRouteAction[];
334
+ private terrenoApp: TerrenoApp | undefined;
335
+ private openApi: OpenApiMiddleware | undefined;
336
+ private readonly service: AccountSecurityService;
337
+ private registered = false;
338
+ private warnedNoBetterAuth = false;
339
+
340
+ constructor(options: AccountSecurityAppOptions = {}) {
341
+ this.options = options;
342
+ this.actions = [...defaultSecurityActions(), ...(options.actions ?? [])];
343
+ assertUniqueActionIds(this.actions);
344
+ this.service = createAccountSecurityService({
345
+ getAuth: () => this.resolveBetterAuth(),
346
+ getPublicAppUrl: () => this.resolvePublicAppUrl(),
347
+ getUserModel: () => this.resolveUserModel(),
348
+ });
349
+ }
350
+
351
+ /** The recovery actions this plugin mounts, in display order. */
352
+ getActions(): readonly SecurityRouteAction[] {
353
+ return this.actions;
354
+ }
355
+
356
+ /**
357
+ * Whether `register` has run. A mount elsewhere (OrgsApp) needs a registered instance: only
358
+ * registration checks for AuditApp and wires access control and the user model.
359
+ */
360
+ isRegistered(): boolean {
361
+ return this.registered;
362
+ }
363
+
364
+ register(app: express.Application, openApi?: unknown, terrenoApp?: TerrenoApp): void {
365
+ this.registered = true;
366
+ this.terrenoApp = terrenoApp;
367
+ this.openApi = openApi as OpenApiMiddleware | undefined;
368
+ this.assertAuditRegistered();
369
+ this.resolveUserModel();
370
+ this.subscribeNotifications();
371
+ const router = Router();
372
+ this.mountSecurityRoutes(router, this.authorizePlatform, {includePlatformOnly: true});
373
+ app.use(this.options.basePath ?? "/users", router);
374
+ }
375
+
376
+ /**
377
+ * Mounts `GET {pathPrefix}/:userId/security` and every action route on `router`, each guarded
378
+ * by `authorize`. Pass a prefix's params (such as `/:orgId/members`) as `pathPrefix` so they
379
+ * reach the authorizer and the OpenAPI spec; a router nested under them instead needs
380
+ * `Router({mergeParams: true})` and leaves them out of the spec.
381
+ */
382
+ mountSecurityRoutes(
383
+ router: Router,
384
+ authorize: SecurityAuthorizer,
385
+ {
386
+ includeOrgOnly = false,
387
+ includePlatformOnly = false,
388
+ pathPrefix = "",
389
+ }: MountSecurityRoutesOptions = {}
390
+ ): void {
391
+ const guards = [rejectDelegatedBearer, authenticateMiddleware(), requireOwnSession];
392
+ const actions = this.actions.filter(
393
+ (action) =>
394
+ (includePlatformOnly || !action.platformOnly) && (includeOrgOnly || !action.orgOnly)
395
+ );
396
+
397
+ router.get(
398
+ `${pathPrefix}/:userId/security`,
399
+ ...guards,
400
+ this.docs("Get a user's sign-in security summary"),
401
+ asyncHandler(async (req, res) => {
402
+ const {actor, org, target} = await this.resolveTarget(req, authorize);
403
+ const features = await this.service.readFeatures();
404
+ const state = await this.service.readState(target, features);
405
+ const permitted = await this.filterPermitted({actions, actor, req});
406
+ const summary: AccountSecuritySummary = {
407
+ ...state,
408
+ actions: this.listActions(permitted, {features, org, state}),
409
+ };
410
+ return res.json({data: summary});
411
+ })
412
+ );
413
+
414
+ for (const action of actions) {
415
+ router[action.method](
416
+ `${pathPrefix}/:userId/security${action.path}`,
417
+ ...guards,
418
+ this.docs(SECURITY_ACTIONS[action.id].label),
419
+ asyncHandler(async (req, res) => {
420
+ const {actor, org, target} = await this.resolveTarget(req, authorize);
421
+ if (!(await this.mayRun({action, actor, req}))) {
422
+ throw new ForbiddenError({
423
+ detail: `${action.id} needs ${permissionLabels(action.requiredPermission).join(", ")}`,
424
+ title: "Access denied",
425
+ });
426
+ }
427
+ const features = await this.service.readFeatures();
428
+ if (!action.isSupported(features)) {
429
+ throw new NotFoundError({
430
+ detail: `${action.id} is not enabled on this server`,
431
+ title: "Security action not available",
432
+ });
433
+ }
434
+ const result = await action.run({
435
+ actor,
436
+ features,
437
+ org,
438
+ req,
439
+ service: this.service,
440
+ target,
441
+ });
442
+ if (result.changed) {
443
+ // An action such as suspend-membership can drop the target's grants, which must stop
444
+ // working at once rather than after the permission cache expires.
445
+ this.resolveAccessControl()?.invalidateCache({userId: userIdOf(target)});
446
+ void recordSecurityAction({
447
+ action: action.id,
448
+ actor: {id: userIdOf(actor)},
449
+ details: result.audit,
450
+ org,
451
+ target: {id: userIdOf(target)},
452
+ });
453
+ }
454
+ return res.json({data: {...result.data, action: action.id, changed: result.changed}});
455
+ })
456
+ );
457
+ }
458
+ }
459
+
460
+ /**
461
+ * The shared pipeline step every route runs before its handler: authorize the caller (403),
462
+ * load the target (404), then refuse a target the caller may not act on (403).
463
+ */
464
+ private resolveTarget = async (
465
+ req: Request,
466
+ authorize: SecurityAuthorizer
467
+ ): Promise<SecurityAuthorization & {target: User}> => {
468
+ const authorization = await authorize({req, targetUserId: targetUserIdOf(req)});
469
+ const target = await this.service.loadTarget(targetUserIdOf(req));
470
+ await this.assertWithinReach({
471
+ actor: authorization.actor,
472
+ orgScope: authorization.orgScope,
473
+ target,
474
+ });
475
+ return {...authorization, target};
476
+ };
477
+
478
+ /**
479
+ * Refuses (403) acting on yourself, which belongs on your own security screen, and acting on
480
+ * someone who holds any permission you lack, such as a superadmin, so recovery cannot be used
481
+ * to take over a more privileged account.
482
+ */
483
+ private assertWithinReach = async ({
484
+ actor,
485
+ orgScope,
486
+ target,
487
+ }: {
488
+ actor: User;
489
+ orgScope?: SecurityOrgScope;
490
+ target: User;
491
+ }): Promise<void> => {
492
+ if (userIdOf(actor) === userIdOf(target)) {
493
+ throw new ForbiddenError(SELF_TARGET_TITLE);
494
+ }
495
+ if (rolesOf(target).includes("superadmin") && !rolesOf(actor).includes("superadmin")) {
496
+ throw new ForbiddenError({detail: "The target is a superadmin", title: OUT_OF_REACH_TITLE});
497
+ }
498
+ if (target.admin === true && actor.admin !== true) {
499
+ throw new ForbiddenError({detail: "The target is an admin", title: OUT_OF_REACH_TITLE});
500
+ }
501
+ const accessControl = this.resolveAccessControl();
502
+ if (!accessControl) {
503
+ return;
504
+ }
505
+ // Resolve each user under their own org context. Org-scoped permission sources read the
506
+ // context's membership, so sharing one context would hand the target the actor's grants (or
507
+ // drop the target's own). Platform routes resolve both outside any org.
508
+ const [actorPermissions, targetPermissions] = await Promise.all([
509
+ runWithOrgContext(
510
+ orgScope ? {membership: orgScope.actorMembership, organization: orgScope.organization} : {},
511
+ () => accessControl.getPermissions({user: actor})
512
+ ),
513
+ runWithOrgContext(
514
+ orgScope
515
+ ? {membership: orgScope.targetMembership, organization: orgScope.organization}
516
+ : {},
517
+ // A target missing a failed source's grants would look less privileged than it is and
518
+ // let the actor through, so an incomplete target set refuses with 503.
519
+ () => accessControl.getPermissions({requireComplete: true, user: target})
520
+ ),
521
+ ]);
522
+ const missing = missingPermissions(actorPermissions, targetPermissions);
523
+ if (missing.length > 0) {
524
+ throw new ForbiddenError({
525
+ detail: `The target holds ${missing.slice(0, 5).join(", ")}`,
526
+ title: OUT_OF_REACH_TITLE,
527
+ });
528
+ }
529
+ };
530
+
531
+ /** Platform staff: `user:manageSecurity` under RBAC, otherwise `admin: true`. */
532
+ readonly authorizePlatform: SecurityAuthorizer = async ({req}) => {
533
+ const actor = req.user as User | undefined;
534
+ if (!actor) {
535
+ throw new APIError({status: 401, title: "Unauthorized"});
536
+ }
537
+ const accessControl = this.resolveAccessControl();
538
+ if (accessControl) {
539
+ const result = await accessControl.can({
540
+ context: {req},
541
+ permissions: MANAGE_SECURITY_PERMISSION as never,
542
+ user: actor,
543
+ });
544
+ if (!result.allowed) {
545
+ throw new ForbiddenError({detail: result.reason, title: "Access denied"});
546
+ }
547
+ return {actor};
548
+ }
549
+ if (actor.admin !== true) {
550
+ throw new ForbiddenError("Access denied");
551
+ }
552
+ return {actor};
553
+ };
554
+
555
+ /** Whether the actor holds the action's `requiredPermission` (or `admin: true` without RBAC). */
556
+ private mayRun = async ({
557
+ action,
558
+ actor,
559
+ req,
560
+ }: {
561
+ action: SecurityRouteAction;
562
+ actor: User;
563
+ req: Request;
564
+ }): Promise<boolean> => {
565
+ if (!action.requiredPermission) {
566
+ return true;
567
+ }
568
+ const accessControl = this.resolveAccessControl();
569
+ if (!accessControl) {
570
+ return actor.admin === true;
571
+ }
572
+ const result = await accessControl.can({
573
+ context: {req},
574
+ permissions: action.requiredPermission as never,
575
+ user: actor,
576
+ });
577
+ return result.allowed;
578
+ };
579
+
580
+ private filterPermitted = async ({
581
+ actions,
582
+ actor,
583
+ req,
584
+ }: {
585
+ actions: readonly SecurityRouteAction[];
586
+ actor: User;
587
+ req: Request;
588
+ }): Promise<SecurityRouteAction[]> => {
589
+ const allowed = await Promise.all(actions.map((action) => this.mayRun({action, actor, req})));
590
+ return actions.filter((_action, index) => allowed[index]);
591
+ };
592
+
593
+ private listActions = (
594
+ actions: readonly SecurityRouteAction[],
595
+ args: {
596
+ features: AccountSecurityFeatures;
597
+ org?: SecurityActionOrg;
598
+ state: AccountSecurityState;
599
+ }
600
+ ): AccountSecurityActionSummary[] =>
601
+ actions
602
+ .filter((action) => action.isSupported(args.features) && action.isApplicable(args))
603
+ .map((action) => ({
604
+ destructive: SECURITY_ACTIONS[action.id].destructive,
605
+ id: action.id,
606
+ label: SECURITY_ACTIONS[action.id].label,
607
+ method: action.method === "delete" ? "DELETE" : "POST",
608
+ path: action.path,
609
+ }));
610
+
611
+ private docs = (summary: string): express.RequestHandler =>
612
+ createOpenApiBuilder({openApi: this.openApi})
613
+ .withTags(["account-security"])
614
+ .withSummary(summary)
615
+ .build() as unknown as express.RequestHandler;
616
+
617
+ private assertAuditRegistered = (): void => {
618
+ if (this.options.audit === false) {
619
+ return;
620
+ }
621
+ const auditRegistered = this.terrenoApp
622
+ ? this.terrenoApp.getRegistrations().some((registration) => registration instanceof AuditApp)
623
+ : isAuditRecorderInstalled();
624
+ if (auditRegistered) {
625
+ return;
626
+ }
627
+ throw new APIError({
628
+ detail:
629
+ "Register AuditApp so every recovery action is audited, or pass audit: false to AccountSecurityApp.",
630
+ status: 500,
631
+ title: "AccountSecurityApp requires AuditApp",
632
+ });
633
+ };
634
+
635
+ /**
636
+ * Emails the affected user about each security action, unless `notifications.enabled` is
637
+ * false. Security actions are process-wide, so one registration owns the emails: the newest
638
+ * one replaces any earlier subscription, and two registered apps never email twice.
639
+ */
640
+ private subscribeNotifications = (): void => {
641
+ activeNotifications?.stop();
642
+ activeNotifications = undefined;
643
+ const notifications = this.options.notifications ?? {};
644
+ if (notifications.enabled === false) {
645
+ return;
646
+ }
647
+ activeNotifications = {
648
+ owner: this,
649
+ stop: onSecurityAction(
650
+ createSecurityNotificationListener({
651
+ getMailConfig: () => this.resolveMailConfig(),
652
+ getUserModel: () => this.resolveUserModel(),
653
+ includeOrgName: notifications.includeOrgName === true,
654
+ render: notifications.render,
655
+ throttleMinutes: notifications.throttleMinutes,
656
+ })
657
+ ),
658
+ };
659
+ };
660
+
661
+ /** Stops the security notification emails, when this instance owns them (on shutdown). */
662
+ unsubscribeNotifications(): void {
663
+ if (activeNotifications?.owner !== this) {
664
+ return;
665
+ }
666
+ activeNotifications.stop();
667
+ activeNotifications = undefined;
668
+ }
669
+
670
+ private resolveMailConfig = (): SecurityMailConfig => {
671
+ const config = this.terrenoApp
672
+ ? findBetterAuthProvider(this.terrenoApp.getRegistrations())?.getBetterAuthConfig?.()
673
+ : undefined;
674
+ return {
675
+ authMailTemplates: config?.authMailTemplates,
676
+ publicAppUrl: this.resolvePublicAppUrl(),
677
+ sendMail: this.options.notifications?.sendMail ?? config?.sendMail,
678
+ };
679
+ };
680
+
681
+ private resolveAccessControl = (): AnyTerrenoAccess | undefined =>
682
+ this.options.accessControl ?? this.terrenoApp?.getAccessControl();
683
+
684
+ private resolvePublicAppUrl = (): string | undefined => {
685
+ if (this.options.publicAppUrl) {
686
+ return this.options.publicAppUrl;
687
+ }
688
+ const provider = this.terrenoApp
689
+ ? findBetterAuthProvider(this.terrenoApp.getRegistrations())
690
+ : undefined;
691
+ return provider?.getBetterAuthConfig?.().publicAppUrl;
692
+ };
693
+
694
+ private resolveBetterAuth = (): BetterAuthInstance | undefined => {
695
+ const auth = this.options.getBetterAuth
696
+ ? this.options.getBetterAuth()
697
+ : this.terrenoApp
698
+ ? getProvidedBetterAuth(findBetterAuthProvider(this.terrenoApp.getRegistrations()))
699
+ : undefined;
700
+ if (!auth && !this.warnedNoBetterAuth) {
701
+ this.warnedNoBetterAuth = true;
702
+ logger.warn(
703
+ "AccountSecurityApp found no Better Auth instance; every Better Auth feature reads as off. Register BetterAuthApp or pass getBetterAuth."
704
+ );
705
+ }
706
+ return auth;
707
+ };
708
+
709
+ private resolveUserModel = (): UserModel => {
710
+ const userModel = this.options.userModel ?? this.terrenoApp?.getUserModel();
711
+ if (!userModel) {
712
+ throw new APIError({
713
+ detail: "Pass userModel to AccountSecurityApp, or register it on a TerrenoApp.",
714
+ status: 500,
715
+ title: "AccountSecurityApp requires a userModel",
716
+ });
717
+ }
718
+ return userModel;
719
+ };
720
+ }