@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,438 @@
1
+ "use strict";
2
+ /**
3
+ * AccountSecurityApp: per-user security summary and recovery routes for platform staff.
4
+ *
5
+ * A framework plugin with its own Express router (the OrgsApp precedent), not modelRouter
6
+ * actions. `mountSecurityRoutes(router, authorize)` mounts the same handlers under any prefix,
7
+ * so the org-admin prefix (`/orgs/:orgId/members/:userId/security/*`) reuses them with its own
8
+ * authorizer. Each recovery action is one row in the action table; the summary lists only the
9
+ * actions this server supports and that apply to the user.
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.AccountSecurityApp = exports.defaultSecurityActions = exports.resetTwoFactorAction = exports.MANAGE_SECURITY_PERMISSION = void 0;
13
+ const express_1 = require("express");
14
+ const api_1 = require("../api");
15
+ const auditApp_1 = require("../audit/auditApp");
16
+ const record_1 = require("../audit/record");
17
+ const auth_1 = require("../auth");
18
+ const betterAuthApp_1 = require("../betterAuthApp");
19
+ const errors_1 = require("../errors");
20
+ const logger_1 = require("../logger");
21
+ const mcpOAuthToken_1 = require("../models/mcpOAuthToken");
22
+ const mcpServiceToken_1 = require("../models/mcpServiceToken");
23
+ const openApiBuilder_1 = require("../openApiBuilder");
24
+ const orgContext_1 = require("../orgs/orgContext");
25
+ const requestContext_1 = require("../requestContext");
26
+ const accessActions_1 = require("./accessActions");
27
+ const accountSecurityService_1 = require("./accountSecurityService");
28
+ const credentialActions_1 = require("./credentialActions");
29
+ const membershipActions_1 = require("./membershipActions");
30
+ const securityEvents_1 = require("./securityEvents");
31
+ const securityNotifications_1 = require("./securityNotifications");
32
+ /** The registration that currently owns security notification emails (see subscribeNotifications). */
33
+ let activeNotifications;
34
+ /** The RBAC statement that grants the platform security routes. */
35
+ exports.MANAGE_SECURITY_PERMISSION = { user: ["manageSecurity"] };
36
+ exports.resetTwoFactorAction = {
37
+ id: "reset-two-factor",
38
+ isApplicable: ({ state }) => state.twoFactor.enabled,
39
+ isSupported: (features) => features.twoFactor,
40
+ method: "post",
41
+ path: "/reset-two-factor",
42
+ run: async ({ service, target }) => service.resetTwoFactor(target),
43
+ };
44
+ /** The built-in action table, in display order. */
45
+ const defaultSecurityActions = () => [
46
+ exports.resetTwoFactorAction,
47
+ credentialActions_1.removePasskeyAction,
48
+ credentialActions_1.unlinkProviderAction,
49
+ accessActions_1.revokeSessionsAction,
50
+ accessActions_1.sendPasswordResetAction,
51
+ accessActions_1.disableAccountAction,
52
+ accessActions_1.enableAccountAction,
53
+ membershipActions_1.suspendMembershipAction,
54
+ accessActions_1.issueSignInLinkAction,
55
+ ];
56
+ exports.defaultSecurityActions = defaultSecurityActions;
57
+ /** The credentials that prove the caller is the person at the keyboard. */
58
+ const OWN_SESSION_CREDENTIALS = ["jwt", "better-auth-session"];
59
+ const DELEGATED_CREDENTIAL_TITLE = "Account security requires your own session";
60
+ const OUT_OF_REACH_TITLE = "Target holds permissions you lack";
61
+ const SELF_TARGET_TITLE = "Use your own security settings to change your account";
62
+ const bearerToken = (req) => {
63
+ const authorization = req.headers.authorization;
64
+ if (typeof authorization !== "string") {
65
+ return undefined;
66
+ }
67
+ return authorization.startsWith("Bearer ") ? authorization.slice(7) : authorization;
68
+ };
69
+ /** Refuses delegated agent bearers (MCP service tokens, MCP OAuth tokens) before auth runs. */
70
+ const rejectDelegatedBearer = (req, _res, next) => {
71
+ const token = bearerToken(req);
72
+ if (token?.startsWith(mcpServiceToken_1.MCP_SERVICE_TOKEN_PREFIX) ||
73
+ token?.startsWith(mcpOAuthToken_1.MCP_OAUTH_ACCESS_TOKEN_PREFIX)) {
74
+ next(new errors_1.ForbiddenError(DELEGATED_CREDENTIAL_TITLE));
75
+ return;
76
+ }
77
+ next();
78
+ };
79
+ /**
80
+ * The credential that authenticated the request. Outside TerrenoApp (setupServer has no request
81
+ * context) it is read from what the auth middleware left on the request.
82
+ */
83
+ const requestCredentialOf = (req) => {
84
+ const fromContext = (0, requestContext_1.getCurrentRequestContext)()?.credential;
85
+ if (fromContext) {
86
+ return fromContext;
87
+ }
88
+ const withAuth = req;
89
+ if (withAuth.betterAuthSession) {
90
+ return "better-auth-session";
91
+ }
92
+ if (withAuth.authTokenPayload) {
93
+ return "jwt";
94
+ }
95
+ return undefined;
96
+ };
97
+ /** Allows only the user's own session (a Terreno JWT or a Better Auth session). */
98
+ const requireOwnSession = (req, _res, next) => {
99
+ const credential = requestCredentialOf(req);
100
+ if (!credential || !OWN_SESSION_CREDENTIALS.includes(credential)) {
101
+ next(new errors_1.ForbiddenError(DELEGATED_CREDENTIAL_TITLE));
102
+ return;
103
+ }
104
+ next();
105
+ };
106
+ const rolesOf = (user) => user.roles ?? [];
107
+ const missingPermissions = (held, required) => {
108
+ const missing = [];
109
+ for (const [resource, actions] of Object.entries(required)) {
110
+ const heldActions = new Set(held[resource] ?? []);
111
+ for (const action of actions) {
112
+ if (!heldActions.has(action)) {
113
+ missing.push(`${resource}:${action}`);
114
+ }
115
+ }
116
+ }
117
+ return missing;
118
+ };
119
+ const permissionLabels = (permission) => Object.entries(permission ?? {}).flatMap(([resource, actions]) => actions.map((action) => `${resource}:${action}`));
120
+ const targetUserIdOf = (req) => {
121
+ const value = req.params.userId;
122
+ return typeof value === "string" ? value : "";
123
+ };
124
+ /** Two actions with one id would share a summary entry and an audit name, so refuse them. */
125
+ const assertUniqueActionIds = (actions) => {
126
+ const seen = new Set();
127
+ for (const action of actions) {
128
+ if (seen.has(action.id)) {
129
+ throw new errors_1.APIError({
130
+ detail: `Two security actions use the id "${action.id}"; give the custom action its own id.`,
131
+ status: 500,
132
+ title: "Duplicate security action id",
133
+ });
134
+ }
135
+ seen.add(action.id);
136
+ }
137
+ };
138
+ class AccountSecurityApp {
139
+ options;
140
+ actions;
141
+ terrenoApp;
142
+ openApi;
143
+ service;
144
+ registered = false;
145
+ warnedNoBetterAuth = false;
146
+ constructor(options = {}) {
147
+ this.options = options;
148
+ this.actions = [...(0, exports.defaultSecurityActions)(), ...(options.actions ?? [])];
149
+ assertUniqueActionIds(this.actions);
150
+ this.service = (0, accountSecurityService_1.createAccountSecurityService)({
151
+ getAuth: () => this.resolveBetterAuth(),
152
+ getPublicAppUrl: () => this.resolvePublicAppUrl(),
153
+ getUserModel: () => this.resolveUserModel(),
154
+ });
155
+ }
156
+ /** The recovery actions this plugin mounts, in display order. */
157
+ getActions() {
158
+ return this.actions;
159
+ }
160
+ /**
161
+ * Whether `register` has run. A mount elsewhere (OrgsApp) needs a registered instance: only
162
+ * registration checks for AuditApp and wires access control and the user model.
163
+ */
164
+ isRegistered() {
165
+ return this.registered;
166
+ }
167
+ register(app, openApi, terrenoApp) {
168
+ this.registered = true;
169
+ this.terrenoApp = terrenoApp;
170
+ this.openApi = openApi;
171
+ this.assertAuditRegistered();
172
+ this.resolveUserModel();
173
+ this.subscribeNotifications();
174
+ const router = (0, express_1.Router)();
175
+ this.mountSecurityRoutes(router, this.authorizePlatform, { includePlatformOnly: true });
176
+ app.use(this.options.basePath ?? "/users", router);
177
+ }
178
+ /**
179
+ * Mounts `GET {pathPrefix}/:userId/security` and every action route on `router`, each guarded
180
+ * by `authorize`. Pass a prefix's params (such as `/:orgId/members`) as `pathPrefix` so they
181
+ * reach the authorizer and the OpenAPI spec; a router nested under them instead needs
182
+ * `Router({mergeParams: true})` and leaves them out of the spec.
183
+ */
184
+ mountSecurityRoutes(router, authorize, { includeOrgOnly = false, includePlatformOnly = false, pathPrefix = "", } = {}) {
185
+ const guards = [rejectDelegatedBearer, (0, auth_1.authenticateMiddleware)(), requireOwnSession];
186
+ const actions = this.actions.filter((action) => (includePlatformOnly || !action.platformOnly) && (includeOrgOnly || !action.orgOnly));
187
+ router.get(`${pathPrefix}/:userId/security`, ...guards, this.docs("Get a user's sign-in security summary"), (0, api_1.asyncHandler)(async (req, res) => {
188
+ const { actor, org, target } = await this.resolveTarget(req, authorize);
189
+ const features = await this.service.readFeatures();
190
+ const state = await this.service.readState(target, features);
191
+ const permitted = await this.filterPermitted({ actions, actor, req });
192
+ const summary = {
193
+ ...state,
194
+ actions: this.listActions(permitted, { features, org, state }),
195
+ };
196
+ return res.json({ data: summary });
197
+ }));
198
+ for (const action of actions) {
199
+ router[action.method](`${pathPrefix}/:userId/security${action.path}`, ...guards, this.docs(securityEvents_1.SECURITY_ACTIONS[action.id].label), (0, api_1.asyncHandler)(async (req, res) => {
200
+ const { actor, org, target } = await this.resolveTarget(req, authorize);
201
+ if (!(await this.mayRun({ action, actor, req }))) {
202
+ throw new errors_1.ForbiddenError({
203
+ detail: `${action.id} needs ${permissionLabels(action.requiredPermission).join(", ")}`,
204
+ title: "Access denied",
205
+ });
206
+ }
207
+ const features = await this.service.readFeatures();
208
+ if (!action.isSupported(features)) {
209
+ throw new errors_1.NotFoundError({
210
+ detail: `${action.id} is not enabled on this server`,
211
+ title: "Security action not available",
212
+ });
213
+ }
214
+ const result = await action.run({
215
+ actor,
216
+ features,
217
+ org,
218
+ req,
219
+ service: this.service,
220
+ target,
221
+ });
222
+ if (result.changed) {
223
+ // An action such as suspend-membership can drop the target's grants, which must stop
224
+ // working at once rather than after the permission cache expires.
225
+ this.resolveAccessControl()?.invalidateCache({ userId: (0, accountSecurityService_1.userIdOf)(target) });
226
+ void (0, securityEvents_1.recordSecurityAction)({
227
+ action: action.id,
228
+ actor: { id: (0, accountSecurityService_1.userIdOf)(actor) },
229
+ details: result.audit,
230
+ org,
231
+ target: { id: (0, accountSecurityService_1.userIdOf)(target) },
232
+ });
233
+ }
234
+ return res.json({ data: { ...result.data, action: action.id, changed: result.changed } });
235
+ }));
236
+ }
237
+ }
238
+ /**
239
+ * The shared pipeline step every route runs before its handler: authorize the caller (403),
240
+ * load the target (404), then refuse a target the caller may not act on (403).
241
+ */
242
+ resolveTarget = async (req, authorize) => {
243
+ const authorization = await authorize({ req, targetUserId: targetUserIdOf(req) });
244
+ const target = await this.service.loadTarget(targetUserIdOf(req));
245
+ await this.assertWithinReach({
246
+ actor: authorization.actor,
247
+ orgScope: authorization.orgScope,
248
+ target,
249
+ });
250
+ return { ...authorization, target };
251
+ };
252
+ /**
253
+ * Refuses (403) acting on yourself, which belongs on your own security screen, and acting on
254
+ * someone who holds any permission you lack, such as a superadmin, so recovery cannot be used
255
+ * to take over a more privileged account.
256
+ */
257
+ assertWithinReach = async ({ actor, orgScope, target, }) => {
258
+ if ((0, accountSecurityService_1.userIdOf)(actor) === (0, accountSecurityService_1.userIdOf)(target)) {
259
+ throw new errors_1.ForbiddenError(SELF_TARGET_TITLE);
260
+ }
261
+ if (rolesOf(target).includes("superadmin") && !rolesOf(actor).includes("superadmin")) {
262
+ throw new errors_1.ForbiddenError({ detail: "The target is a superadmin", title: OUT_OF_REACH_TITLE });
263
+ }
264
+ if (target.admin === true && actor.admin !== true) {
265
+ throw new errors_1.ForbiddenError({ detail: "The target is an admin", title: OUT_OF_REACH_TITLE });
266
+ }
267
+ const accessControl = this.resolveAccessControl();
268
+ if (!accessControl) {
269
+ return;
270
+ }
271
+ // Resolve each user under their own org context. Org-scoped permission sources read the
272
+ // context's membership, so sharing one context would hand the target the actor's grants (or
273
+ // drop the target's own). Platform routes resolve both outside any org.
274
+ const [actorPermissions, targetPermissions] = await Promise.all([
275
+ (0, orgContext_1.runWithOrgContext)(orgScope ? { membership: orgScope.actorMembership, organization: orgScope.organization } : {}, () => accessControl.getPermissions({ user: actor })),
276
+ (0, orgContext_1.runWithOrgContext)(orgScope
277
+ ? { membership: orgScope.targetMembership, organization: orgScope.organization }
278
+ : {},
279
+ // A target missing a failed source's grants would look less privileged than it is and
280
+ // let the actor through, so an incomplete target set refuses with 503.
281
+ () => accessControl.getPermissions({ requireComplete: true, user: target })),
282
+ ]);
283
+ const missing = missingPermissions(actorPermissions, targetPermissions);
284
+ if (missing.length > 0) {
285
+ throw new errors_1.ForbiddenError({
286
+ detail: `The target holds ${missing.slice(0, 5).join(", ")}`,
287
+ title: OUT_OF_REACH_TITLE,
288
+ });
289
+ }
290
+ };
291
+ /** Platform staff: `user:manageSecurity` under RBAC, otherwise `admin: true`. */
292
+ authorizePlatform = async ({ req }) => {
293
+ const actor = req.user;
294
+ if (!actor) {
295
+ throw new errors_1.APIError({ status: 401, title: "Unauthorized" });
296
+ }
297
+ const accessControl = this.resolveAccessControl();
298
+ if (accessControl) {
299
+ const result = await accessControl.can({
300
+ context: { req },
301
+ permissions: exports.MANAGE_SECURITY_PERMISSION,
302
+ user: actor,
303
+ });
304
+ if (!result.allowed) {
305
+ throw new errors_1.ForbiddenError({ detail: result.reason, title: "Access denied" });
306
+ }
307
+ return { actor };
308
+ }
309
+ if (actor.admin !== true) {
310
+ throw new errors_1.ForbiddenError("Access denied");
311
+ }
312
+ return { actor };
313
+ };
314
+ /** Whether the actor holds the action's `requiredPermission` (or `admin: true` without RBAC). */
315
+ mayRun = async ({ action, actor, req, }) => {
316
+ if (!action.requiredPermission) {
317
+ return true;
318
+ }
319
+ const accessControl = this.resolveAccessControl();
320
+ if (!accessControl) {
321
+ return actor.admin === true;
322
+ }
323
+ const result = await accessControl.can({
324
+ context: { req },
325
+ permissions: action.requiredPermission,
326
+ user: actor,
327
+ });
328
+ return result.allowed;
329
+ };
330
+ filterPermitted = async ({ actions, actor, req, }) => {
331
+ const allowed = await Promise.all(actions.map((action) => this.mayRun({ action, actor, req })));
332
+ return actions.filter((_action, index) => allowed[index]);
333
+ };
334
+ listActions = (actions, args) => actions
335
+ .filter((action) => action.isSupported(args.features) && action.isApplicable(args))
336
+ .map((action) => ({
337
+ destructive: securityEvents_1.SECURITY_ACTIONS[action.id].destructive,
338
+ id: action.id,
339
+ label: securityEvents_1.SECURITY_ACTIONS[action.id].label,
340
+ method: action.method === "delete" ? "DELETE" : "POST",
341
+ path: action.path,
342
+ }));
343
+ docs = (summary) => (0, openApiBuilder_1.createOpenApiBuilder)({ openApi: this.openApi })
344
+ .withTags(["account-security"])
345
+ .withSummary(summary)
346
+ .build();
347
+ assertAuditRegistered = () => {
348
+ if (this.options.audit === false) {
349
+ return;
350
+ }
351
+ const auditRegistered = this.terrenoApp
352
+ ? this.terrenoApp.getRegistrations().some((registration) => registration instanceof auditApp_1.AuditApp)
353
+ : (0, record_1.isAuditRecorderInstalled)();
354
+ if (auditRegistered) {
355
+ return;
356
+ }
357
+ throw new errors_1.APIError({
358
+ detail: "Register AuditApp so every recovery action is audited, or pass audit: false to AccountSecurityApp.",
359
+ status: 500,
360
+ title: "AccountSecurityApp requires AuditApp",
361
+ });
362
+ };
363
+ /**
364
+ * Emails the affected user about each security action, unless `notifications.enabled` is
365
+ * false. Security actions are process-wide, so one registration owns the emails: the newest
366
+ * one replaces any earlier subscription, and two registered apps never email twice.
367
+ */
368
+ subscribeNotifications = () => {
369
+ activeNotifications?.stop();
370
+ activeNotifications = undefined;
371
+ const notifications = this.options.notifications ?? {};
372
+ if (notifications.enabled === false) {
373
+ return;
374
+ }
375
+ activeNotifications = {
376
+ owner: this,
377
+ stop: (0, securityEvents_1.onSecurityAction)((0, securityNotifications_1.createSecurityNotificationListener)({
378
+ getMailConfig: () => this.resolveMailConfig(),
379
+ getUserModel: () => this.resolveUserModel(),
380
+ includeOrgName: notifications.includeOrgName === true,
381
+ render: notifications.render,
382
+ throttleMinutes: notifications.throttleMinutes,
383
+ })),
384
+ };
385
+ };
386
+ /** Stops the security notification emails, when this instance owns them (on shutdown). */
387
+ unsubscribeNotifications() {
388
+ if (activeNotifications?.owner !== this) {
389
+ return;
390
+ }
391
+ activeNotifications.stop();
392
+ activeNotifications = undefined;
393
+ }
394
+ resolveMailConfig = () => {
395
+ const config = this.terrenoApp
396
+ ? (0, betterAuthApp_1.findBetterAuthProvider)(this.terrenoApp.getRegistrations())?.getBetterAuthConfig?.()
397
+ : undefined;
398
+ return {
399
+ authMailTemplates: config?.authMailTemplates,
400
+ publicAppUrl: this.resolvePublicAppUrl(),
401
+ sendMail: this.options.notifications?.sendMail ?? config?.sendMail,
402
+ };
403
+ };
404
+ resolveAccessControl = () => this.options.accessControl ?? this.terrenoApp?.getAccessControl();
405
+ resolvePublicAppUrl = () => {
406
+ if (this.options.publicAppUrl) {
407
+ return this.options.publicAppUrl;
408
+ }
409
+ const provider = this.terrenoApp
410
+ ? (0, betterAuthApp_1.findBetterAuthProvider)(this.terrenoApp.getRegistrations())
411
+ : undefined;
412
+ return provider?.getBetterAuthConfig?.().publicAppUrl;
413
+ };
414
+ resolveBetterAuth = () => {
415
+ const auth = this.options.getBetterAuth
416
+ ? this.options.getBetterAuth()
417
+ : this.terrenoApp
418
+ ? (0, betterAuthApp_1.getProvidedBetterAuth)((0, betterAuthApp_1.findBetterAuthProvider)(this.terrenoApp.getRegistrations()))
419
+ : undefined;
420
+ if (!auth && !this.warnedNoBetterAuth) {
421
+ this.warnedNoBetterAuth = true;
422
+ logger_1.logger.warn("AccountSecurityApp found no Better Auth instance; every Better Auth feature reads as off. Register BetterAuthApp or pass getBetterAuth.");
423
+ }
424
+ return auth;
425
+ };
426
+ resolveUserModel = () => {
427
+ const userModel = this.options.userModel ?? this.terrenoApp?.getUserModel();
428
+ if (!userModel) {
429
+ throw new errors_1.APIError({
430
+ detail: "Pass userModel to AccountSecurityApp, or register it on a TerrenoApp.",
431
+ status: 500,
432
+ title: "AccountSecurityApp requires a userModel",
433
+ });
434
+ }
435
+ return userModel;
436
+ };
437
+ }
438
+ exports.AccountSecurityApp = AccountSecurityApp;
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Reads and changes one user's sign-in security through Better Auth's internal adapter, so the
3
+ * same code works whatever collection names a consumer configures. Never returns secrets: no
4
+ * TOTP secret, no backup codes, no session or OAuth tokens.
5
+ */
6
+ import type { User, UserModel } from "../auth";
7
+ import { type BetterAuthInstance } from "../betterAuthSetup";
8
+ /** Which features this server has on. The Better Auth ones are all `false` without Better Auth. */
9
+ export interface AccountSecurityFeatures {
10
+ betterAuth: boolean;
11
+ /** Whether the app User model has `disabled` (`isDisabledPlugin`), so accounts can be disabled. */
12
+ disableAccount: boolean;
13
+ multiSession: boolean;
14
+ passkey: boolean;
15
+ twoFactor: boolean;
16
+ }
17
+ export interface AccountSecurityProvider {
18
+ /** ISO time the provider was linked, when known. */
19
+ linkedAt: string | null;
20
+ /** Better Auth provider id, such as `github`, `google`, or `mock-oidc`. */
21
+ providerId: string;
22
+ }
23
+ export interface AccountSecurityPasskey {
24
+ createdAt: string | null;
25
+ id: string;
26
+ name: string | null;
27
+ }
28
+ export interface AccountSecurityActionSummary {
29
+ destructive: boolean;
30
+ id: string;
31
+ label: string;
32
+ /** HTTP method of the action's route, such as `POST` or `DELETE`. */
33
+ method: "DELETE" | "POST";
34
+ /**
35
+ * Route path relative to the user's security base (`.../:userId/security`), with `:param`
36
+ * placeholders for values the caller fills from the summary, such as `/passkeys/:passkeyId`.
37
+ */
38
+ path: string;
39
+ }
40
+ /** The body of `GET /users/:id/security`. */
41
+ export interface AccountSecuritySummary {
42
+ /** Recovery actions available for this user on this server. */
43
+ actions: AccountSecurityActionSummary[];
44
+ /** Whether the app User is linked to a Better Auth user (`betterAuthId`). */
45
+ betterAuthLinked: boolean;
46
+ /** `User.disabled`. */
47
+ disabled: boolean;
48
+ /** Better Auth `emailVerified` (`false` without a Better Auth link). */
49
+ emailVerified: boolean;
50
+ /**
51
+ * Whether the app User has a legacy JWT (passport-local-mongoose) password hash. A user with
52
+ * neither this nor a Better Auth link (a GitHub-JWT user) needs an admin-issued sign-in link.
53
+ */
54
+ legacyPassword: boolean;
55
+ lastSignIn: {
56
+ /** ISO time of the most recent session start, when known. */
57
+ at: string | null;
58
+ /** Better Auth `lastLoginMethod` (`email`, `github`, `passkey`, ...), when stored. */
59
+ method: string | null;
60
+ };
61
+ passkeys: {
62
+ count: number;
63
+ items: AccountSecurityPasskey[];
64
+ };
65
+ /** Whether the user has a Better Auth email and password credential. */
66
+ password: boolean;
67
+ /** Linked OAuth providers (the password credential is reported as `password`). */
68
+ providers: AccountSecurityProvider[];
69
+ sessions: {
70
+ active: number;
71
+ };
72
+ twoFactor: {
73
+ /** Unused backup codes, or `null` when 2FA is off or the count cannot be read. */
74
+ backupCodesRemaining: number | null;
75
+ enabled: boolean;
76
+ };
77
+ userId: string;
78
+ }
79
+ /** The user-facing state the security actions read to decide whether they apply. */
80
+ export type AccountSecurityState = Omit<AccountSecuritySummary, "actions">;
81
+ export type VerificationStorageOption = "plain" | "hashed" | {
82
+ hash: (identifier: string) => unknown;
83
+ };
84
+ export type VerificationStoreIdentifier = VerificationStorageOption | {
85
+ default: VerificationStorageOption;
86
+ overrides?: Record<string, VerificationStorageOption>;
87
+ };
88
+ /** Better Auth's provider id for the email and password credential. */
89
+ export declare const PASSWORD_PROVIDER_ID = "credential";
90
+ /** The app User id as a string. */
91
+ export declare const userIdOf: (user: User) => string;
92
+ /**
93
+ * Whether Better Auth stores trusted-device identifiers as written (the default). With a hashed
94
+ * `verification.storeIdentifier` the prefix is gone, so rows can only be matched by user id.
95
+ */
96
+ export declare const storesTrustDeviceIdentifiersPlain: (storeIdentifier: VerificationStoreIdentifier | undefined) => boolean;
97
+ /** One user's sign-in methods as stored by Better Auth. Holds ids only, never key material. */
98
+ export interface AccountSecurityCredentials {
99
+ /** Account rows: one per linked provider account, plus `credential` for the password. */
100
+ accounts: {
101
+ id: string;
102
+ providerId: string;
103
+ }[];
104
+ betterAuthId: string;
105
+ /** Better Auth `emailVerified`. */
106
+ emailVerified: boolean;
107
+ /** Passkeys; always empty when the `passkey` feature is off. */
108
+ passkeys: {
109
+ id: string;
110
+ name: string | null;
111
+ }[];
112
+ }
113
+ /** Why a password reset was not sent. */
114
+ export type PasswordResetSkipReason = "not-configured" | "not-linked";
115
+ export type PasswordResetResult = {
116
+ sent: true;
117
+ } | {
118
+ reason: PasswordResetSkipReason;
119
+ sent: false;
120
+ };
121
+ /** Why a sign-in link was not issued. */
122
+ export type SignInLinkRefusal =
123
+ /** Better Auth is not running, or `publicAppUrl` is unset so there is no page to link to. */
124
+ "not-configured"
125
+ /** The User is linked to a Better Auth user that has a sign-in method or a verified email. */
126
+ | "linked"
127
+ /** The User has a legacy password; they can sign up with it instead (T3 migration). */
128
+ | "has-password"
129
+ /** The User has no email to create the Better Auth user with. */
130
+ | "no-email"
131
+ /** Another Better Auth user already uses the email. */
132
+ | "email-taken";
133
+ export type SignInLinkResult = {
134
+ betterAuthId: string;
135
+ expiresAt: string;
136
+ issued: true;
137
+ url: string;
138
+ } | {
139
+ issued: false;
140
+ reason: SignInLinkRefusal;
141
+ };
142
+ export interface AccountSecurityServiceOptions {
143
+ getAuth: () => BetterAuthInstance | undefined;
144
+ /** The app page base for set-password links (`BetterAuthConfig.publicAppUrl`). */
145
+ getPublicAppUrl?: () => string | undefined;
146
+ getUserModel: () => UserModel;
147
+ }
148
+ export interface AccountSecurityService {
149
+ /** Deletes the user's account rows for `providerId`. Returns how many were removed. */
150
+ deleteAccounts: (args: {
151
+ betterAuthId: string;
152
+ providerId: string;
153
+ }) => Promise<number>;
154
+ /** Deletes one passkey, only when it belongs to `betterAuthId`. Returns whether it existed. */
155
+ deletePasskey: (args: {
156
+ betterAuthId: string;
157
+ passkeyId: string;
158
+ }) => Promise<boolean>;
159
+ /**
160
+ * For a User with no Better Auth link and no legacy password: creates their Better Auth user
161
+ * (email unverified), links it by `betterAuthId`, and returns a single-use set-password link.
162
+ * A User whose link was never used (its Better Auth user still has no sign-in method and an
163
+ * unverified email) gets a fresh link for the same Better Auth user; earlier links stop working.
164
+ */
165
+ issueSignInLink: (target: User) => Promise<SignInLinkResult>;
166
+ /** The app User with this id, or 404 (an id that is not an ObjectId is also 404). */
167
+ loadTarget: (userId: string) => Promise<User>;
168
+ /** The user's sign-in methods, or `undefined` when the user has no Better Auth link. */
169
+ readCredentials: (target: User, features: AccountSecurityFeatures) => Promise<AccountSecurityCredentials | undefined>;
170
+ readFeatures: () => Promise<AccountSecurityFeatures>;
171
+ readState: (target: User, features: AccountSecurityFeatures) => Promise<AccountSecurityState>;
172
+ /**
173
+ * Removes the user's TOTP secret and backup codes and turns 2FA off. `changed` is false when
174
+ * 2FA was already off (or the user has no Better Auth link).
175
+ */
176
+ resetTwoFactor: (target: User) => Promise<{
177
+ changed: boolean;
178
+ }>;
179
+ /**
180
+ * Deletes every Better Auth session the user has (bearer tokens and cookie sessions alike) and,
181
+ * when the User model has `tokenEpoch`, bumps it so legacy JWT refresh tokens stop working.
182
+ * `revokedCount` is how many active sessions were deleted.
183
+ */
184
+ revokeSessions: (target: User) => Promise<{
185
+ jwtRefreshRevoked: boolean;
186
+ revokedCount: number;
187
+ }>;
188
+ /** Sets `User.disabled`. `changed` is false when it already had that value. */
189
+ setDisabled: (target: User, disabled: boolean) => Promise<{
190
+ changed: boolean;
191
+ }>;
192
+ /**
193
+ * Mails the user a Better Auth password-reset link through the configured
194
+ * `emailAndPassword.sendResetPassword` hook (Terreno's `sendMail` + `publicAppUrl`). The hook
195
+ * is awaited, so a delivery failure (such as the hook's 501 for a missing `publicAppUrl`)
196
+ * throws instead of being logged and dropped as Better Auth's own endpoint does.
197
+ */
198
+ sendPasswordReset: (target: User) => Promise<PasswordResetResult>;
199
+ }
200
+ export declare const createAccountSecurityService: ({ getAuth, getPublicAppUrl, getUserModel, }: AccountSecurityServiceOptions) => AccountSecurityService;