@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,15 @@
1
+ /**
2
+ * Org-scoped recovery actions: what an org-admin runs instead of the platform-only account
3
+ * actions. Under `/orgs/:orgId/members/:userId/security/*`, "disable" suspends the member's
4
+ * membership in that one organization (Q8); `User.disabled` stays platform-only, so one org can
5
+ * never lock a user out of every other org.
6
+ */
7
+ import type { SecurityRouteAction } from "./accountSecurityApp";
8
+ /**
9
+ * `POST /orgs/:orgId/members/:userId/security/suspend-membership`: suspend the member's active
10
+ * membership in `:orgId`. Their account, sessions, and other memberships are untouched, so they
11
+ * still sign in and keep using their other orgs. Suspending the last active org-admin is refused
12
+ * (400). Restore a suspended member with `PATCH /orgs/:orgId/members/:memberId {status: "active"}`;
13
+ * a suspended member is out of the recovery routes' reach (404).
14
+ */
15
+ export declare const suspendMembershipAction: SecurityRouteAction;
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ /**
3
+ * Org-scoped recovery actions: what an org-admin runs instead of the platform-only account
4
+ * actions. Under `/orgs/:orgId/members/:userId/security/*`, "disable" suspends the member's
5
+ * membership in that one organization (Q8); `User.disabled` stays platform-only, so one org can
6
+ * never lock a user out of every other org.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.suspendMembershipAction = void 0;
10
+ const errors_1 = require("../errors");
11
+ const membershipGuards_1 = require("../orgs/membershipGuards");
12
+ const organizationModel_1 = require("../orgs/organizationModel");
13
+ const accountSecurityService_1 = require("./accountSecurityService");
14
+ /**
15
+ * Suspends the membership without ever leaving the org with no active org-admin, even when two
16
+ * admins suspend each other at once. A check-then-write would let both pass (each sees the other
17
+ * still active); a transaction alone would too (write skew), and needs a replica set. Instead
18
+ * suspend first with a conditional update, then count the active org-admins that remain and undo
19
+ * the suspension when none do. Every request counts after its own write, so the last one to count
20
+ * sees every suspension that stuck and undoes its own if it was the last admin. Returns false when
21
+ * another request suspended the membership first.
22
+ */
23
+ const suspendUnlessLastOrgAdmin = async (membership) => {
24
+ const result = await organizationModel_1.Membership.updateOne({ _id: membership._id, status: "active" }, { $set: { status: "suspended" } });
25
+ if (result.modifiedCount === 0) {
26
+ return false;
27
+ }
28
+ if (membership.roleName !== "org-admin") {
29
+ return true;
30
+ }
31
+ const remainingAdmins = await organizationModel_1.Membership.countDocuments({
32
+ organizationId: membership.organizationId,
33
+ roleName: "org-admin",
34
+ status: "active",
35
+ });
36
+ if (remainingAdmins > 0) {
37
+ return true;
38
+ }
39
+ await organizationModel_1.Membership.updateOne({ _id: membership._id, status: "suspended" }, { $set: { status: "active" } });
40
+ throw new errors_1.APIError({ status: 400, title: membershipGuards_1.LAST_ORG_ADMIN_TITLE });
41
+ };
42
+ /**
43
+ * `POST /orgs/:orgId/members/:userId/security/suspend-membership`: suspend the member's active
44
+ * membership in `:orgId`. Their account, sessions, and other memberships are untouched, so they
45
+ * still sign in and keep using their other orgs. Suspending the last active org-admin is refused
46
+ * (400). Restore a suspended member with `PATCH /orgs/:orgId/members/:memberId {status: "active"}`;
47
+ * a suspended member is out of the recovery routes' reach (404).
48
+ */
49
+ exports.suspendMembershipAction = {
50
+ id: "suspend-membership",
51
+ isApplicable: ({ org }) => Boolean(org),
52
+ isSupported: () => true,
53
+ method: "post",
54
+ orgOnly: true,
55
+ path: "/suspend-membership",
56
+ run: async ({ org, target }) => {
57
+ if (!org) {
58
+ throw new errors_1.NotFoundError({
59
+ detail: "suspend-membership runs only under an organization",
60
+ title: "Security action not available",
61
+ });
62
+ }
63
+ const membership = await organizationModel_1.Membership.findOneOrNone({
64
+ organizationId: org.id,
65
+ status: "active",
66
+ userId: (0, accountSecurityService_1.userIdOf)(target),
67
+ });
68
+ if (!membership) {
69
+ return { changed: false };
70
+ }
71
+ if (!(await suspendUnlessLastOrgAdmin(membership))) {
72
+ return { changed: false };
73
+ }
74
+ const membershipId = String(membership._id);
75
+ return {
76
+ audit: { membershipId, roleName: membership.roleName },
77
+ changed: true,
78
+ data: { membershipId, status: "suspended" },
79
+ };
80
+ },
81
+ };
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Org-admin recovery routes: the AccountSecurityApp handlers mounted by OrgsApp at
3
+ * `/orgs/:orgId/members/:userId/security/*`, guarded by an org authorizer.
4
+ *
5
+ * Reach (D2): an org-admin of `:orgId` may act on any active member of that org, even one who
6
+ * also belongs to other orgs. Guards (D3): platform staff and `admin: true` users are never
7
+ * reachable through an org, and `orgRecovery.minMembershipDays` (default 0) can refuse members
8
+ * who joined too recently, so attaching an existing user by email and acting on them at once
9
+ * fails. The shared pipeline then applies D9 (no self-targeting, no target holding permissions
10
+ * the actor lacks). Platform staff holding `user:manageSecurity` always pass the org checks,
11
+ * and their reach check is the platform one: both sides are resolved outside the organization.
12
+ */
13
+ import type { Router } from "express";
14
+ import type { UserModel } from "../auth";
15
+ import type { AnyTerrenoAccess } from "../rbac/types";
16
+ import { type AccountSecurityApp, type SecurityAuthorizer } from "./accountSecurityApp";
17
+ /** Hardening for org-admin recovery (`OrgsAppOptions.orgRecovery`). */
18
+ export interface OrgRecoveryOptions {
19
+ /**
20
+ * Refuse (403) acting on a member whose membership in the org is younger than this many days.
21
+ * Defaults to 0 (off). It defends against an org-admin attaching an existing user by email and
22
+ * running recovery on them right away.
23
+ */
24
+ minMembershipDays?: number;
25
+ }
26
+ /**
27
+ * The org authorizer. Order: 401 without a user; 404 for an unknown org; 403 for a disabled org;
28
+ * 403 unless the actor is platform staff or an active org-admin of the org; 404 unless the
29
+ * target holds an active membership in the org (suspended members are out of reach); then, for
30
+ * org-admin actors, 403 for platform-role or `admin: true` targets and members younger than
31
+ * `minMembershipDays`. Platform staff omit `orgScope`, so the shared reach check resolves both
32
+ * users outside the organization, the same way `/users/:id/security` does.
33
+ */
34
+ export declare const createOrgSecurityAuthorizer: ({ access, orgRecovery, userModel, }: {
35
+ access: AnyTerrenoAccess;
36
+ orgRecovery?: OrgRecoveryOptions;
37
+ userModel: UserModel;
38
+ }) => SecurityAuthorizer;
39
+ /**
40
+ * Mounts the AccountSecurityApp routes on an OrgsApp router at
41
+ * `/:orgId/members/:userId/security/*`. Platform-only actions (`disable`, `enable`,
42
+ * `issue-sign-in-link`) are left out; org-only ones (`suspend-membership`) are added.
43
+ */
44
+ export declare const mountOrgSecurityRoutes: ({ access, accountSecurity, orgRecovery, router, userModel, }: {
45
+ access: AnyTerrenoAccess;
46
+ accountSecurity: AccountSecurityApp;
47
+ orgRecovery?: OrgRecoveryOptions;
48
+ router: Router;
49
+ userModel: UserModel;
50
+ }) => void;
@@ -0,0 +1,149 @@
1
+ "use strict";
2
+ /**
3
+ * Org-admin recovery routes: the AccountSecurityApp handlers mounted by OrgsApp at
4
+ * `/orgs/:orgId/members/:userId/security/*`, guarded by an org authorizer.
5
+ *
6
+ * Reach (D2): an org-admin of `:orgId` may act on any active member of that org, even one who
7
+ * also belongs to other orgs. Guards (D3): platform staff and `admin: true` users are never
8
+ * reachable through an org, and `orgRecovery.minMembershipDays` (default 0) can refuse members
9
+ * who joined too recently, so attaching an existing user by email and acting on them at once
10
+ * fails. The shared pipeline then applies D9 (no self-targeting, no target holding permissions
11
+ * the actor lacks). Platform staff holding `user:manageSecurity` always pass the org checks,
12
+ * and their reach check is the platform one: both sides are resolved outside the organization.
13
+ */
14
+ var __importDefault = (this && this.__importDefault) || function (mod) {
15
+ return (mod && mod.__esModule) ? mod : { "default": mod };
16
+ };
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.mountOrgSecurityRoutes = exports.createOrgSecurityAuthorizer = void 0;
19
+ const luxon_1 = require("luxon");
20
+ const mongoose_1 = __importDefault(require("mongoose"));
21
+ const errors_1 = require("../errors");
22
+ const organizationModel_1 = require("../orgs/organizationModel");
23
+ const orgContext_1 = require("../orgs/orgContext");
24
+ const plugins_1 = require("../plugins");
25
+ const accountSecurityApp_1 = require("./accountSecurityApp");
26
+ const accountSecurityService_1 = require("./accountSecurityService");
27
+ const ORG_NOT_FOUND_TITLE = "Organization not found";
28
+ const MEMBER_NOT_FOUND_TITLE = "Member not found";
29
+ const NOT_ORG_ADMIN_TITLE = "Only org-admins of this organization can manage member security";
30
+ const PLATFORM_TARGET_TITLE = "Platform staff are managed by platform staff";
31
+ const RECENT_MEMBER_TITLE = "Member joined too recently";
32
+ /** A canonical ObjectId string; anything else names no org or member, so it answers 404. */
33
+ const isObjectIdString = (id) => mongoose_1.default.isValidObjectId(id) && new mongoose_1.default.Types.ObjectId(id).toString() === id;
34
+ const rolesOf = (user) => user.roles ?? [];
35
+ const orgIdOf = (req) => {
36
+ const value = req.params.orgId;
37
+ return typeof value === "string" ? value : "";
38
+ };
39
+ /** Platform staff: the actor holds `user:manageSecurity` on its own roles (no org context). */
40
+ const isPlatformSecurityActor = async ({ access, actor, req, }) => {
41
+ const result = await (0, orgContext_1.runWithOrgContext)({}, () => access.can({
42
+ context: { req },
43
+ permissions: accountSecurityApp_1.MANAGE_SECURITY_PERMISSION,
44
+ user: actor,
45
+ }));
46
+ return result.allowed;
47
+ };
48
+ const assertNotPlatformTarget = async ({ targetUserId, userModel, }) => {
49
+ const target = await (0, plugins_1.findOneOrNoneFor)(userModel, { _id: targetUserId });
50
+ if (!target) {
51
+ throw new errors_1.NotFoundError(MEMBER_NOT_FOUND_TITLE);
52
+ }
53
+ const platformRole = rolesOf(target).find((role) => orgContext_1.PLATFORM_ORG_ROLE_NAMES.includes(role));
54
+ if (platformRole) {
55
+ throw new errors_1.ForbiddenError({
56
+ detail: `The member holds ${platformRole}`,
57
+ title: PLATFORM_TARGET_TITLE,
58
+ });
59
+ }
60
+ if (target.admin === true) {
61
+ throw new errors_1.ForbiddenError({ detail: "The member is an admin", title: PLATFORM_TARGET_TITLE });
62
+ }
63
+ };
64
+ const assertMembershipOldEnough = ({ joined, minMembershipDays, }) => {
65
+ if (minMembershipDays <= 0) {
66
+ return;
67
+ }
68
+ const oldEnoughAt = luxon_1.DateTime.fromJSDate(joined).plus({ days: minMembershipDays });
69
+ if (oldEnoughAt <= luxon_1.DateTime.now()) {
70
+ return;
71
+ }
72
+ throw new errors_1.ForbiddenError({
73
+ detail: `Org-admins can run recovery on a member ${minMembershipDays} days after they join`,
74
+ title: RECENT_MEMBER_TITLE,
75
+ });
76
+ };
77
+ /**
78
+ * The org authorizer. Order: 401 without a user; 404 for an unknown org; 403 for a disabled org;
79
+ * 403 unless the actor is platform staff or an active org-admin of the org; 404 unless the
80
+ * target holds an active membership in the org (suspended members are out of reach); then, for
81
+ * org-admin actors, 403 for platform-role or `admin: true` targets and members younger than
82
+ * `minMembershipDays`. Platform staff omit `orgScope`, so the shared reach check resolves both
83
+ * users outside the organization, the same way `/users/:id/security` does.
84
+ */
85
+ const createOrgSecurityAuthorizer = ({ access, orgRecovery = {}, userModel, }) => {
86
+ const minMembershipDays = orgRecovery.minMembershipDays ?? 0;
87
+ return async ({ req, targetUserId }) => {
88
+ const actor = req.user;
89
+ if (!actor?.id) {
90
+ throw new errors_1.APIError({ status: 401, title: "Unauthorized" });
91
+ }
92
+ const orgId = orgIdOf(req);
93
+ if (!isObjectIdString(orgId)) {
94
+ throw new errors_1.NotFoundError(ORG_NOT_FOUND_TITLE);
95
+ }
96
+ const organization = await organizationModel_1.Organization.findOneOrNone({ _id: orgId });
97
+ if (!organization) {
98
+ throw new errors_1.NotFoundError(ORG_NOT_FOUND_TITLE);
99
+ }
100
+ (0, orgContext_1.assertOrganizationEnabled)(organization);
101
+ const org = { id: String(organization._id), name: organization.name };
102
+ const isPlatform = await isPlatformSecurityActor({ access, actor, req });
103
+ const actorMembership = await organizationModel_1.Membership.findOneOrNone({
104
+ organizationId: organization._id,
105
+ status: "active",
106
+ userId: (0, accountSecurityService_1.userIdOf)(actor),
107
+ });
108
+ if (!isPlatform && actorMembership?.roleName !== "org-admin") {
109
+ throw new errors_1.ForbiddenError(NOT_ORG_ADMIN_TITLE);
110
+ }
111
+ if (!isObjectIdString(targetUserId)) {
112
+ throw new errors_1.NotFoundError(MEMBER_NOT_FOUND_TITLE);
113
+ }
114
+ const targetMembership = await organizationModel_1.Membership.findOneOrNone({
115
+ organizationId: organization._id,
116
+ status: "active",
117
+ userId: targetUserId,
118
+ });
119
+ if (!targetMembership) {
120
+ throw new errors_1.NotFoundError(MEMBER_NOT_FOUND_TITLE);
121
+ }
122
+ const orgScope = {
123
+ actorMembership: actorMembership ?? undefined,
124
+ organization,
125
+ targetMembership,
126
+ };
127
+ if (isPlatform) {
128
+ // An org-only grant must not block staff who can already recover this user on
129
+ // /users/:id/security. Passing orgScope would judge that grant against an actor
130
+ // who has no membership in the org.
131
+ return { actor, org };
132
+ }
133
+ await assertNotPlatformTarget({ targetUserId, userModel });
134
+ assertMembershipOldEnough({ joined: targetMembership.created, minMembershipDays });
135
+ return { actor, org, orgScope };
136
+ };
137
+ };
138
+ exports.createOrgSecurityAuthorizer = createOrgSecurityAuthorizer;
139
+ /**
140
+ * Mounts the AccountSecurityApp routes on an OrgsApp router at
141
+ * `/:orgId/members/:userId/security/*`. Platform-only actions (`disable`, `enable`,
142
+ * `issue-sign-in-link`) are left out; org-only ones (`suspend-membership`) are added.
143
+ */
144
+ const mountOrgSecurityRoutes = ({ access, accountSecurity, orgRecovery, router, userModel, }) => {
145
+ // Leaf routes carry the full `/:orgId/members/:userId/security/...` path so OpenAPI documents
146
+ // `orgId` as a path parameter.
147
+ accountSecurity.mountSecurityRoutes(router, (0, exports.createOrgSecurityAuthorizer)({ access, orgRecovery, userModel }), { includeOrgOnly: true, pathPrefix: "/:orgId/members" });
148
+ };
149
+ exports.mountOrgSecurityRoutes = mountOrgSecurityRoutes;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Records the security changes a user makes to their own account through Better Auth (linking a
3
+ * provider, adding a passkey, turning on 2FA, changing their password, ...) as security actions
4
+ * with `origin: "self"`. Each one writes a security `AuditEvent` (when AuditApp is registered) and
5
+ * reaches every `onSecurityAction` listener, such as the notification emails.
6
+ *
7
+ * Only successful requests are recorded. Admin recovery actions never pass through these hooks:
8
+ * they change Better Auth data through its adapters, not its endpoints, and record themselves.
9
+ */
10
+ import type { BetterAuthPlugin } from "better-auth";
11
+ import type { UserModel } from "../auth";
12
+ import { type SecurityActionId } from "./securityEvents";
13
+ /**
14
+ * Records a security action the user made themselves, by their Better Auth user id. Does nothing
15
+ * when no app User is linked yet. Never throws: a recording failure is logged.
16
+ */
17
+ export declare const recordSelfSecurityAction: ({ action, betterAuthUserId, details, userModel, }: {
18
+ action: SecurityActionId;
19
+ betterAuthUserId: string | undefined;
20
+ details?: Record<string, unknown>;
21
+ userModel: UserModel;
22
+ }) => Promise<void>;
23
+ /**
24
+ * The Better Auth plugin that records self-service security changes. `createBetterAuth` adds it
25
+ * whenever it has a `userModel` (security principals are app User ids).
26
+ *
27
+ * - Endpoint `hooks.after`: `/change-password` (password-changed), `/terreno/set-password`
28
+ * (password-set, a first password for an OAuth- or passkey-only user), `/revoke-other-sessions`
29
+ * (other-sessions-revoked), `/passkey/verify-registration` (passkey-added),
30
+ * `/passkey/delete-passkey` (passkey-removed), and a successful `/two-factor/*` request that
31
+ * changed the user's stored `twoFactorEnabled` (two-factor-enabled / two-factor-disabled). The
32
+ * change is detected by a `user.update.before` database hook that compares the value being
33
+ * written with the user row in the database, not with the (possibly cookie-cached) session.
34
+ * So enrolment counts once, the 2FA step of a sign-in never does, and admin resets (which run
35
+ * outside any Better Auth endpoint) are not mistaken for the user's own change.
36
+ * - Database hooks, because they see the account row: a non-password `account` created for a
37
+ * user who already had another sign-in method (provider-linked, from `/link-social`, the link
38
+ * callback, the OAuth handoff, or implicit linking on sign-in), and an account deleted by
39
+ * `/unlink-account` (provider-unlinked). A first account is a sign-up, not a link.
40
+ *
41
+ * A completed `/reset-password` is recorded from `onPasswordReset` in `createBetterAuth`
42
+ * (password-reset), which knows the user the token belonged to.
43
+ */
44
+ export declare const createSecurityEventsPlugin: (userModel: UserModel) => BetterAuthPlugin;
@@ -0,0 +1,223 @@
1
+ "use strict";
2
+ /**
3
+ * Records the security changes a user makes to their own account through Better Auth (linking a
4
+ * provider, adding a passkey, turning on 2FA, changing their password, ...) as security actions
5
+ * with `origin: "self"`. Each one writes a security `AuditEvent` (when AuditApp is registered) and
6
+ * reaches every `onSecurityAction` listener, such as the notification emails.
7
+ *
8
+ * Only successful requests are recorded. Admin recovery actions never pass through these hooks:
9
+ * they change Better Auth data through its adapters, not its endpoints, and record themselves.
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.createSecurityEventsPlugin = exports.recordSelfSecurityAction = void 0;
13
+ const api_1 = require("better-auth/api");
14
+ const logger_1 = require("../logger");
15
+ const plugins_1 = require("../plugins");
16
+ const securityEvents_1 = require("./securityEvents");
17
+ /** The app User linked to a Better Auth user, as a security principal id. */
18
+ const appUserIdFor = async (userModel, betterAuthUserId) => {
19
+ const user = await (0, plugins_1.findOneOrNoneFor)(userModel, { betterAuthId: betterAuthUserId });
20
+ return user ? String(user._id) : undefined;
21
+ };
22
+ /**
23
+ * Records a security action the user made themselves, by their Better Auth user id. Does nothing
24
+ * when no app User is linked yet. Never throws: a recording failure is logged.
25
+ */
26
+ const recordSelfSecurityAction = async ({ action, betterAuthUserId, details, userModel, }) => {
27
+ if (!betterAuthUserId) {
28
+ return;
29
+ }
30
+ try {
31
+ const userId = await appUserIdFor(userModel, betterAuthUserId);
32
+ if (!userId) {
33
+ return;
34
+ }
35
+ void (0, securityEvents_1.recordSecurityAction)({
36
+ action,
37
+ actor: { id: userId },
38
+ ...(details ? { details } : {}),
39
+ target: { id: userId },
40
+ });
41
+ }
42
+ catch (error) {
43
+ logger_1.logger.error(`[AccountSecurity] Recording ${action} failed: ${error}`);
44
+ }
45
+ };
46
+ exports.recordSelfSecurityAction = recordSelfSecurityAction;
47
+ /** The endpoints that can turn two-factor on or off for the signed-in user. */
48
+ const TWO_FACTOR_PATHS = new Set([
49
+ "/two-factor/disable",
50
+ "/two-factor/enable",
51
+ "/two-factor/verify-otp",
52
+ "/two-factor/verify-totp",
53
+ ]);
54
+ const isSuccess = (returned) => !(returned instanceof Error);
55
+ const stringOf = (value) => typeof value === "string" && value.length > 0 ? value : undefined;
56
+ /** The session user as it was when the request started (before the endpoint changed it). */
57
+ const sessionUserOf = (ctx) => ctx.context.session?.user ?? undefined;
58
+ /** The two-factor change this request made, read (and cleared) from the update hook's notes. */
59
+ const takeTwoFactorChange = (ctx, changes) => {
60
+ const userId = sessionUserOf(ctx)?.id;
61
+ if (!userId || !changes.has(userId)) {
62
+ return undefined;
63
+ }
64
+ const enabled = changes.get(userId);
65
+ changes.delete(userId);
66
+ if (!isSuccess(ctx.context.returned)) {
67
+ return undefined;
68
+ }
69
+ return { action: enabled ? "two-factor-enabled" : "two-factor-disabled" };
70
+ };
71
+ /** Which self-service action a successful request to `path` records, and its details. */
72
+ const actionFor = (ctx) => {
73
+ switch (ctx.path) {
74
+ case "/change-password":
75
+ return { action: "password-changed" };
76
+ case "/terreno/set-password":
77
+ return { action: "password-set" };
78
+ case "/revoke-other-sessions":
79
+ return { action: "other-sessions-revoked" };
80
+ case "/passkey/verify-registration": {
81
+ const passkeyId = stringOf(ctx.context.returned?.id);
82
+ return { action: "passkey-added", ...(passkeyId ? { details: { passkeyId } } : {}) };
83
+ }
84
+ case "/passkey/delete-passkey": {
85
+ const passkeyId = stringOf(ctx.body?.id);
86
+ return { action: "passkey-removed", ...(passkeyId ? { details: { passkeyId } } : {}) };
87
+ }
88
+ default:
89
+ return undefined;
90
+ }
91
+ };
92
+ const RECORDED_PATHS = new Set([
93
+ "/change-password",
94
+ "/passkey/delete-passkey",
95
+ "/passkey/verify-registration",
96
+ "/revoke-other-sessions",
97
+ "/terreno/set-password",
98
+ ...TWO_FACTOR_PATHS,
99
+ ]);
100
+ /**
101
+ * The Better Auth plugin that records self-service security changes. `createBetterAuth` adds it
102
+ * whenever it has a `userModel` (security principals are app User ids).
103
+ *
104
+ * - Endpoint `hooks.after`: `/change-password` (password-changed), `/terreno/set-password`
105
+ * (password-set, a first password for an OAuth- or passkey-only user), `/revoke-other-sessions`
106
+ * (other-sessions-revoked), `/passkey/verify-registration` (passkey-added),
107
+ * `/passkey/delete-passkey` (passkey-removed), and a successful `/two-factor/*` request that
108
+ * changed the user's stored `twoFactorEnabled` (two-factor-enabled / two-factor-disabled). The
109
+ * change is detected by a `user.update.before` database hook that compares the value being
110
+ * written with the user row in the database, not with the (possibly cookie-cached) session.
111
+ * So enrolment counts once, the 2FA step of a sign-in never does, and admin resets (which run
112
+ * outside any Better Auth endpoint) are not mistaken for the user's own change.
113
+ * - Database hooks, because they see the account row: a non-password `account` created for a
114
+ * user who already had another sign-in method (provider-linked, from `/link-social`, the link
115
+ * callback, the OAuth handoff, or implicit linking on sign-in), and an account deleted by
116
+ * `/unlink-account` (provider-unlinked). A first account is a sign-up, not a link.
117
+ *
118
+ * A completed `/reset-password` is recorded from `onPasswordReset` in `createBetterAuth`
119
+ * (password-reset), which knows the user the token belonged to.
120
+ */
121
+ const createSecurityEventsPlugin = (userModel) => {
122
+ const twoFactorChanges = new Map();
123
+ return {
124
+ hooks: {
125
+ after: [
126
+ {
127
+ handler: (0, api_1.createAuthMiddleware)(async (rawCtx) => {
128
+ const ctx = rawCtx;
129
+ const recorded = TWO_FACTOR_PATHS.has(ctx.path ?? "")
130
+ ? takeTwoFactorChange(ctx, twoFactorChanges)
131
+ : isSuccess(ctx.context.returned)
132
+ ? actionFor(ctx)
133
+ : undefined;
134
+ if (!recorded) {
135
+ return;
136
+ }
137
+ await (0, exports.recordSelfSecurityAction)({
138
+ ...recorded,
139
+ betterAuthUserId: sessionUserOf(ctx)?.id,
140
+ userModel,
141
+ });
142
+ }),
143
+ matcher: (context) => RECORDED_PATHS.has(context.path ?? ""),
144
+ },
145
+ ],
146
+ },
147
+ id: "terreno-security-events",
148
+ init: (authContext) => {
149
+ const { internalAdapter } = authContext;
150
+ return {
151
+ options: {
152
+ databaseHooks: {
153
+ account: {
154
+ create: {
155
+ after: async (account) => {
156
+ const row = account;
157
+ if (!row.userId || !row.providerId || row.providerId === "credential") {
158
+ return;
159
+ }
160
+ try {
161
+ const accounts = await internalAdapter.findAccounts(row.userId);
162
+ if (accounts.length < 2) {
163
+ return;
164
+ }
165
+ }
166
+ catch (error) {
167
+ logger_1.logger.error(`[AccountSecurity] Reading accounts for a new link failed: ${error}`);
168
+ return;
169
+ }
170
+ await (0, exports.recordSelfSecurityAction)({
171
+ action: "provider-linked",
172
+ betterAuthUserId: row.userId,
173
+ details: { providerId: row.providerId },
174
+ userModel,
175
+ });
176
+ },
177
+ },
178
+ delete: {
179
+ after: async (account, rawContext) => {
180
+ const context = rawContext;
181
+ if (context?.path !== "/unlink-account") {
182
+ return;
183
+ }
184
+ const row = account;
185
+ await (0, exports.recordSelfSecurityAction)({
186
+ action: "provider-unlinked",
187
+ betterAuthUserId: row.userId,
188
+ ...(row.providerId ? { details: { providerId: row.providerId } } : {}),
189
+ userModel,
190
+ });
191
+ },
192
+ },
193
+ },
194
+ user: {
195
+ update: {
196
+ before: async (data, rawContext) => {
197
+ const context = rawContext;
198
+ const next = data.twoFactorEnabled;
199
+ const userId = context?.context?.session?.user?.id;
200
+ if (typeof next !== "boolean" ||
201
+ !userId ||
202
+ !TWO_FACTOR_PATHS.has(context?.path ?? "")) {
203
+ return;
204
+ }
205
+ try {
206
+ const stored = await internalAdapter.findUserById(userId);
207
+ if ((stored?.twoFactorEnabled === true) !== next) {
208
+ twoFactorChanges.set(userId, next);
209
+ }
210
+ }
211
+ catch (error) {
212
+ logger_1.logger.error(`[AccountSecurity] Reading two-factor state failed: ${error}`);
213
+ }
214
+ },
215
+ },
216
+ },
217
+ },
218
+ },
219
+ };
220
+ },
221
+ };
222
+ };
223
+ exports.createSecurityEventsPlugin = createSecurityEventsPlugin;