@terreno/api 57.19.2 → 57.20.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 (169) hide show
  1. package/CHANGELOG.md +393 -0
  2. package/dist/accountSecurity/accessActions.d.ts +38 -0
  3. package/dist/accountSecurity/accessActions.js +157 -0
  4. package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
  5. package/dist/accountSecurity/accountSecurityApp.js +438 -0
  6. package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
  7. package/dist/accountSecurity/accountSecurityService.js +481 -0
  8. package/dist/accountSecurity/credentialActions.d.ts +16 -0
  9. package/dist/accountSecurity/credentialActions.js +189 -0
  10. package/dist/accountSecurity/membershipActions.d.ts +15 -0
  11. package/dist/accountSecurity/membershipActions.js +81 -0
  12. package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
  13. package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
  14. package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
  15. package/dist/accountSecurity/securityEventHooks.js +223 -0
  16. package/dist/accountSecurity/securityEvents.d.ts +162 -0
  17. package/dist/accountSecurity/securityEvents.js +114 -0
  18. package/dist/accountSecurity/securityNotifications.d.ts +125 -0
  19. package/dist/accountSecurity/securityNotifications.js +333 -0
  20. package/dist/api.js +38 -6
  21. package/dist/audit/auditEventModel.d.ts +5 -3
  22. package/dist/audit/auditEventModel.js +8 -6
  23. package/dist/audit/processQueue.js +4 -2
  24. package/dist/audit/record.d.ts +2 -2
  25. package/dist/audit/record.js +3 -0
  26. package/dist/authRecovery.js +29 -1
  27. package/dist/betterAuth.d.ts +179 -10
  28. package/dist/betterAuthApp.d.ts +15 -0
  29. package/dist/betterAuthApp.js +23 -0
  30. package/dist/betterAuthChallengeHeaders.d.ts +37 -0
  31. package/dist/betterAuthChallengeHeaders.js +180 -0
  32. package/dist/betterAuthFeatures.d.ts +54 -0
  33. package/dist/betterAuthFeatures.js +239 -0
  34. package/dist/betterAuthMethods.d.ts +73 -0
  35. package/dist/betterAuthMethods.js +55 -0
  36. package/dist/betterAuthOAuthHandoff.d.ts +10 -2
  37. package/dist/betterAuthOAuthHandoff.js +222 -24
  38. package/dist/betterAuthSetPassword.d.ts +33 -0
  39. package/dist/betterAuthSetPassword.js +166 -0
  40. package/dist/betterAuthSetup.d.ts +57 -8
  41. package/dist/betterAuthSetup.js +327 -36
  42. package/dist/consentApp.d.ts +9 -4
  43. package/dist/consentApp.js +344 -28
  44. package/dist/consentStatus.d.ts +60 -0
  45. package/dist/consentStatus.js +111 -0
  46. package/dist/errors.d.ts +6 -0
  47. package/dist/errors.js +41 -2
  48. package/dist/expressServer.js +3 -2
  49. package/dist/index.d.ts +14 -2
  50. package/dist/index.js +23 -3
  51. package/dist/mcp/oauth.js +151 -11
  52. package/dist/mcp/oauthMetadata.d.ts +2 -1
  53. package/dist/mcp/oauthMetadata.js +7 -4
  54. package/dist/models/consentResponse.js +51 -0
  55. package/dist/models/mcpOAuthClient.js +78 -2
  56. package/dist/models/mcpOAuthToken.js +28 -4
  57. package/dist/orgs/membershipGuards.d.ts +7 -0
  58. package/dist/orgs/membershipGuards.js +32 -0
  59. package/dist/orgs/orgsApp.d.ts +19 -1
  60. package/dist/orgs/orgsApp.js +55 -24
  61. package/dist/rateLimit/policies.js +8 -0
  62. package/dist/rbac/access.js +2 -1
  63. package/dist/rbac/resolve.d.ts +9 -1
  64. package/dist/rbac/resolve.js +21 -16
  65. package/dist/rbac/roleManager.d.ts +6 -0
  66. package/dist/rbac/roleManager.js +8 -7
  67. package/dist/rbac/roleModel.d.ts +1 -0
  68. package/dist/rbac/roleModel.js +45 -3
  69. package/dist/rbac/statements.d.ts +2 -2
  70. package/dist/rbac/statements.js +10 -1
  71. package/dist/rbac/types.d.ts +6 -0
  72. package/dist/rbac/userWriteGuards.js +2 -1
  73. package/dist/schemaMetadata.js +8 -1
  74. package/dist/seedRunner.js +7 -2
  75. package/dist/terrenoApp.d.ts +4 -0
  76. package/dist/terrenoApp.js +15 -0
  77. package/dist/tests/models.d.ts +5 -0
  78. package/dist/tests/models.js +8 -0
  79. package/dist/types/consentResponse.d.ts +8 -0
  80. package/dist/types/mcpOAuth.d.ts +35 -2
  81. package/package.json +6 -3
  82. package/src/__snapshots__/openApi.test.ts.snap +288 -0
  83. package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
  84. package/src/accountSecurity/accessActions.test.ts +723 -0
  85. package/src/accountSecurity/accessActions.ts +173 -0
  86. package/src/accountSecurity/accountSecurity.test.ts +947 -0
  87. package/src/accountSecurity/accountSecurityApp.ts +720 -0
  88. package/src/accountSecurity/accountSecurityService.ts +826 -0
  89. package/src/accountSecurity/credentialActions.test.ts +867 -0
  90. package/src/accountSecurity/credentialActions.ts +260 -0
  91. package/src/accountSecurity/membershipActions.ts +89 -0
  92. package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
  93. package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
  94. package/src/accountSecurity/securityEventHooks.ts +294 -0
  95. package/src/accountSecurity/securityEvents.ts +165 -0
  96. package/src/accountSecurity/securityNotifications.test.ts +1323 -0
  97. package/src/accountSecurity/securityNotifications.ts +516 -0
  98. package/src/api.arrayOperations.test.ts +71 -0
  99. package/src/api.ts +38 -7
  100. package/src/audit/auditEventModel.ts +10 -7
  101. package/src/audit/processQueue.ts +4 -2
  102. package/src/audit/record.test.ts +15 -0
  103. package/src/audit/record.ts +10 -2
  104. package/src/authRecovery.test.ts +23 -0
  105. package/src/authRecovery.ts +34 -1
  106. package/src/authRecoveryBetterAuth.test.ts +169 -0
  107. package/src/betterAuth.ts +194 -8
  108. package/src/betterAuthApp.ts +32 -0
  109. package/src/betterAuthChallengeHeaders.test.ts +476 -0
  110. package/src/betterAuthChallengeHeaders.ts +227 -0
  111. package/src/betterAuthFeatures.test.ts +489 -0
  112. package/src/betterAuthFeatures.ts +283 -0
  113. package/src/betterAuthLinking.test.ts +844 -0
  114. package/src/betterAuthMethods.test.ts +138 -0
  115. package/src/betterAuthMethods.ts +98 -0
  116. package/src/betterAuthOAuthHandoff.test.ts +482 -69
  117. package/src/betterAuthOAuthHandoff.ts +293 -33
  118. package/src/betterAuthOAuthProxy.test.ts +421 -0
  119. package/src/betterAuthPasswordReset.test.ts +190 -0
  120. package/src/betterAuthSetPassword.test.ts +378 -0
  121. package/src/betterAuthSetPassword.ts +213 -0
  122. package/src/betterAuthSetup.test.ts +39 -7
  123. package/src/betterAuthSetup.ts +457 -38
  124. package/src/consentApp.test.ts +869 -2
  125. package/src/consentApp.ts +438 -36
  126. package/src/consentStatus.test.ts +226 -0
  127. package/src/consentStatus.ts +171 -0
  128. package/src/errors.test.ts +81 -0
  129. package/src/errors.ts +50 -1
  130. package/src/expressServer.test.ts +29 -0
  131. package/src/expressServer.ts +3 -2
  132. package/src/index.ts +30 -0
  133. package/src/mcp/oauth.test.ts +463 -2
  134. package/src/mcp/oauth.ts +184 -13
  135. package/src/mcp/oauthMetadata.ts +5 -2
  136. package/src/models/consentResponse.ts +53 -0
  137. package/src/models/mcpOAuthClient.ts +100 -3
  138. package/src/models/mcpOAuthToken.ts +30 -5
  139. package/src/orgs/membershipGuards.ts +39 -0
  140. package/src/orgs/orgRbac.test.ts +1 -1
  141. package/src/orgs/orgsApp.test.ts +101 -2
  142. package/src/orgs/orgsApp.ts +69 -28
  143. package/src/rateLimit/policies.test.ts +53 -0
  144. package/src/rateLimit/policies.ts +8 -0
  145. package/src/rbac/access.ts +4 -1
  146. package/src/rbac/resolve.test.ts +65 -0
  147. package/src/rbac/resolve.ts +37 -17
  148. package/src/rbac/roleManager.test.ts +64 -0
  149. package/src/rbac/roleManager.ts +15 -6
  150. package/src/rbac/roleModel.test.ts +174 -1
  151. package/src/rbac/roleModel.ts +66 -3
  152. package/src/rbac/routes.test.ts +58 -0
  153. package/src/rbac/statements.test.ts +4 -1
  154. package/src/rbac/statements.ts +11 -1
  155. package/src/rbac/types.ts +6 -1
  156. package/src/rbac/userWriteGuards.test.ts +48 -0
  157. package/src/rbac/userWriteGuards.ts +5 -2
  158. package/src/schemaMetadata.test.ts +39 -0
  159. package/src/schemaMetadata.ts +11 -1
  160. package/src/seedRunner.test.ts +56 -0
  161. package/src/seedRunner.ts +7 -2
  162. package/src/terrenoApp.ts +20 -0
  163. package/src/tests/accountSecurityTestApp.ts +290 -0
  164. package/src/tests/betterAuthStubs.ts +188 -0
  165. package/src/tests/mockOidcProvider.ts +105 -0
  166. package/src/tests/models.ts +13 -0
  167. package/src/tests/softwareAuthenticator.ts +183 -0
  168. package/src/types/consentResponse.ts +8 -0
  169. package/src/types/mcpOAuth.ts +39 -3
@@ -0,0 +1,232 @@
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
+
14
+ import type {Request, Router} from "express";
15
+ import {DateTime} from "luxon";
16
+ import mongoose from "mongoose";
17
+
18
+ import type {User, UserModel} from "../auth";
19
+ import {APIError, ForbiddenError, NotFoundError} from "../errors";
20
+ import {Membership, Organization} from "../orgs/organizationModel";
21
+ import {
22
+ assertOrganizationEnabled,
23
+ PLATFORM_ORG_ROLE_NAMES,
24
+ runWithOrgContext,
25
+ } from "../orgs/orgContext";
26
+ import {findOneOrNoneFor} from "../plugins";
27
+ import type {AnyTerrenoAccess} from "../rbac/types";
28
+ import {
29
+ type AccountSecurityApp,
30
+ MANAGE_SECURITY_PERMISSION,
31
+ type SecurityAuthorizer,
32
+ } from "./accountSecurityApp";
33
+ import {userIdOf} from "./accountSecurityService";
34
+
35
+ /** Hardening for org-admin recovery (`OrgsAppOptions.orgRecovery`). */
36
+ export interface OrgRecoveryOptions {
37
+ /**
38
+ * Refuse (403) acting on a member whose membership in the org is younger than this many days.
39
+ * Defaults to 0 (off). It defends against an org-admin attaching an existing user by email and
40
+ * running recovery on them right away.
41
+ */
42
+ minMembershipDays?: number;
43
+ }
44
+
45
+ const ORG_NOT_FOUND_TITLE = "Organization not found";
46
+
47
+ const MEMBER_NOT_FOUND_TITLE = "Member not found";
48
+
49
+ const NOT_ORG_ADMIN_TITLE = "Only org-admins of this organization can manage member security";
50
+
51
+ const PLATFORM_TARGET_TITLE = "Platform staff are managed by platform staff";
52
+
53
+ const RECENT_MEMBER_TITLE = "Member joined too recently";
54
+
55
+ /** A canonical ObjectId string; anything else names no org or member, so it answers 404. */
56
+ const isObjectIdString = (id: string): boolean =>
57
+ mongoose.isValidObjectId(id) && new mongoose.Types.ObjectId(id).toString() === id;
58
+
59
+ const rolesOf = (user: User): string[] => (user as User & {roles?: string[]}).roles ?? [];
60
+
61
+ const orgIdOf = (req: Request): string => {
62
+ const value = req.params.orgId;
63
+ return typeof value === "string" ? value : "";
64
+ };
65
+
66
+ /** Platform staff: the actor holds `user:manageSecurity` on its own roles (no org context). */
67
+ const isPlatformSecurityActor = async ({
68
+ access,
69
+ actor,
70
+ req,
71
+ }: {
72
+ access: AnyTerrenoAccess;
73
+ actor: User;
74
+ req: Request;
75
+ }): Promise<boolean> => {
76
+ const result = await runWithOrgContext({}, () =>
77
+ access.can({
78
+ context: {req},
79
+ permissions: MANAGE_SECURITY_PERMISSION as never,
80
+ user: actor,
81
+ })
82
+ );
83
+ return result.allowed;
84
+ };
85
+
86
+ const assertNotPlatformTarget = async ({
87
+ targetUserId,
88
+ userModel,
89
+ }: {
90
+ targetUserId: string;
91
+ userModel: UserModel;
92
+ }): Promise<void> => {
93
+ const target = await findOneOrNoneFor(
94
+ userModel as unknown as mongoose.Model<User>,
95
+ {_id: targetUserId} as never
96
+ );
97
+ if (!target) {
98
+ throw new NotFoundError(MEMBER_NOT_FOUND_TITLE);
99
+ }
100
+ const platformRole = rolesOf(target).find((role) =>
101
+ (PLATFORM_ORG_ROLE_NAMES as readonly string[]).includes(role)
102
+ );
103
+ if (platformRole) {
104
+ throw new ForbiddenError({
105
+ detail: `The member holds ${platformRole}`,
106
+ title: PLATFORM_TARGET_TITLE,
107
+ });
108
+ }
109
+ if (target.admin === true) {
110
+ throw new ForbiddenError({detail: "The member is an admin", title: PLATFORM_TARGET_TITLE});
111
+ }
112
+ };
113
+
114
+ const assertMembershipOldEnough = ({
115
+ joined,
116
+ minMembershipDays,
117
+ }: {
118
+ joined: Date;
119
+ minMembershipDays: number;
120
+ }): void => {
121
+ if (minMembershipDays <= 0) {
122
+ return;
123
+ }
124
+ const oldEnoughAt = DateTime.fromJSDate(joined).plus({days: minMembershipDays});
125
+ if (oldEnoughAt <= DateTime.now()) {
126
+ return;
127
+ }
128
+ throw new ForbiddenError({
129
+ detail: `Org-admins can run recovery on a member ${minMembershipDays} days after they join`,
130
+ title: RECENT_MEMBER_TITLE,
131
+ });
132
+ };
133
+
134
+ /**
135
+ * The org authorizer. Order: 401 without a user; 404 for an unknown org; 403 for a disabled org;
136
+ * 403 unless the actor is platform staff or an active org-admin of the org; 404 unless the
137
+ * target holds an active membership in the org (suspended members are out of reach); then, for
138
+ * org-admin actors, 403 for platform-role or `admin: true` targets and members younger than
139
+ * `minMembershipDays`. Platform staff omit `orgScope`, so the shared reach check resolves both
140
+ * users outside the organization, the same way `/users/:id/security` does.
141
+ */
142
+ export const createOrgSecurityAuthorizer = ({
143
+ access,
144
+ orgRecovery = {},
145
+ userModel,
146
+ }: {
147
+ access: AnyTerrenoAccess;
148
+ orgRecovery?: OrgRecoveryOptions;
149
+ userModel: UserModel;
150
+ }): SecurityAuthorizer => {
151
+ const minMembershipDays = orgRecovery.minMembershipDays ?? 0;
152
+ return async ({req, targetUserId}) => {
153
+ const actor = req.user as User | undefined;
154
+ if (!actor?.id) {
155
+ throw new APIError({status: 401, title: "Unauthorized"});
156
+ }
157
+ const orgId = orgIdOf(req);
158
+ if (!isObjectIdString(orgId)) {
159
+ throw new NotFoundError(ORG_NOT_FOUND_TITLE);
160
+ }
161
+ const organization = await Organization.findOneOrNone({_id: orgId});
162
+ if (!organization) {
163
+ throw new NotFoundError(ORG_NOT_FOUND_TITLE);
164
+ }
165
+ assertOrganizationEnabled(organization);
166
+ const org = {id: String(organization._id), name: organization.name};
167
+
168
+ const isPlatform = await isPlatformSecurityActor({access, actor, req});
169
+ const actorMembership = await Membership.findOneOrNone({
170
+ organizationId: organization._id,
171
+ status: "active",
172
+ userId: userIdOf(actor),
173
+ });
174
+ if (!isPlatform && actorMembership?.roleName !== "org-admin") {
175
+ throw new ForbiddenError(NOT_ORG_ADMIN_TITLE);
176
+ }
177
+
178
+ if (!isObjectIdString(targetUserId)) {
179
+ throw new NotFoundError(MEMBER_NOT_FOUND_TITLE);
180
+ }
181
+ const targetMembership = await Membership.findOneOrNone({
182
+ organizationId: organization._id,
183
+ status: "active",
184
+ userId: targetUserId,
185
+ });
186
+ if (!targetMembership) {
187
+ throw new NotFoundError(MEMBER_NOT_FOUND_TITLE);
188
+ }
189
+ const orgScope = {
190
+ actorMembership: actorMembership ?? undefined,
191
+ organization,
192
+ targetMembership,
193
+ };
194
+ if (isPlatform) {
195
+ // An org-only grant must not block staff who can already recover this user on
196
+ // /users/:id/security. Passing orgScope would judge that grant against an actor
197
+ // who has no membership in the org.
198
+ return {actor, org};
199
+ }
200
+
201
+ await assertNotPlatformTarget({targetUserId, userModel});
202
+ assertMembershipOldEnough({joined: targetMembership.created, minMembershipDays});
203
+ return {actor, org, orgScope};
204
+ };
205
+ };
206
+
207
+ /**
208
+ * Mounts the AccountSecurityApp routes on an OrgsApp router at
209
+ * `/:orgId/members/:userId/security/*`. Platform-only actions (`disable`, `enable`,
210
+ * `issue-sign-in-link`) are left out; org-only ones (`suspend-membership`) are added.
211
+ */
212
+ export const mountOrgSecurityRoutes = ({
213
+ access,
214
+ accountSecurity,
215
+ orgRecovery,
216
+ router,
217
+ userModel,
218
+ }: {
219
+ access: AnyTerrenoAccess;
220
+ accountSecurity: AccountSecurityApp;
221
+ orgRecovery?: OrgRecoveryOptions;
222
+ router: Router;
223
+ userModel: UserModel;
224
+ }): void => {
225
+ // Leaf routes carry the full `/:orgId/members/:userId/security/...` path so OpenAPI documents
226
+ // `orgId` as a path parameter.
227
+ accountSecurity.mountSecurityRoutes(
228
+ router,
229
+ createOrgSecurityAuthorizer({access, orgRecovery, userModel}),
230
+ {includeOrgOnly: true, pathPrefix: "/:orgId/members"}
231
+ );
232
+ };
@@ -0,0 +1,294 @@
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
+
11
+ import type {BetterAuthPlugin} from "better-auth";
12
+ import {createAuthMiddleware} from "better-auth/api";
13
+
14
+ import type {UserModel} from "../auth";
15
+ import {logger} from "../logger";
16
+ import {findOneOrNoneFor} from "../plugins";
17
+ import {recordSecurityAction, type SecurityActionId} from "./securityEvents";
18
+
19
+ /** The app User linked to a Better Auth user, as a security principal id. */
20
+ const appUserIdFor = async (
21
+ userModel: UserModel,
22
+ betterAuthUserId: string
23
+ ): Promise<string | undefined> => {
24
+ const user = await findOneOrNoneFor(userModel, {betterAuthId: betterAuthUserId} as never);
25
+ return user ? String((user as {_id: unknown})._id) : undefined;
26
+ };
27
+
28
+ /**
29
+ * Records a security action the user made themselves, by their Better Auth user id. Does nothing
30
+ * when no app User is linked yet. Never throws: a recording failure is logged.
31
+ */
32
+ export const recordSelfSecurityAction = async ({
33
+ action,
34
+ betterAuthUserId,
35
+ details,
36
+ userModel,
37
+ }: {
38
+ action: SecurityActionId;
39
+ betterAuthUserId: string | undefined;
40
+ details?: Record<string, unknown>;
41
+ userModel: UserModel;
42
+ }): Promise<void> => {
43
+ if (!betterAuthUserId) {
44
+ return;
45
+ }
46
+ try {
47
+ const userId = await appUserIdFor(userModel, betterAuthUserId);
48
+ if (!userId) {
49
+ return;
50
+ }
51
+ void recordSecurityAction({
52
+ action,
53
+ actor: {id: userId},
54
+ ...(details ? {details} : {}),
55
+ target: {id: userId},
56
+ });
57
+ } catch (error: unknown) {
58
+ logger.error(`[AccountSecurity] Recording ${action} failed: ${error}`);
59
+ }
60
+ };
61
+
62
+ interface HookSessionUser {
63
+ id?: string;
64
+ twoFactorEnabled?: boolean | null;
65
+ }
66
+
67
+ interface HookContext {
68
+ body?: Record<string, unknown>;
69
+ context: {
70
+ getPlugin?: (id: string) => unknown;
71
+ returned?: unknown;
72
+ session?: {user?: HookSessionUser} | null;
73
+ };
74
+ path?: string;
75
+ }
76
+
77
+ interface AccountRow {
78
+ id?: string;
79
+ providerId?: string;
80
+ userId?: string;
81
+ }
82
+
83
+ interface AccountHookAdapter {
84
+ internalAdapter: {
85
+ findAccounts: (userId: string) => Promise<AccountRow[]>;
86
+ findUserById: (userId: string) => Promise<{twoFactorEnabled?: boolean | null} | null>;
87
+ };
88
+ }
89
+
90
+ /** The endpoint context Better Auth hands database hooks (null outside an endpoint). */
91
+ interface DatabaseHookContext {
92
+ context?: {session?: {user?: HookSessionUser} | null};
93
+ path?: string;
94
+ }
95
+
96
+ /** The endpoints that can turn two-factor on or off for the signed-in user. */
97
+ const TWO_FACTOR_PATHS = new Set([
98
+ "/two-factor/disable",
99
+ "/two-factor/enable",
100
+ "/two-factor/verify-otp",
101
+ "/two-factor/verify-totp",
102
+ ]);
103
+
104
+ const isSuccess = (returned: unknown): boolean => !(returned instanceof Error);
105
+
106
+ const stringOf = (value: unknown): string | undefined =>
107
+ typeof value === "string" && value.length > 0 ? value : undefined;
108
+
109
+ /** The session user as it was when the request started (before the endpoint changed it). */
110
+ const sessionUserOf = (ctx: HookContext): HookSessionUser | undefined =>
111
+ ctx.context.session?.user ?? undefined;
112
+
113
+ /**
114
+ * Two-factor changes seen by the `user.update.before` database hook, by Better Auth user id:
115
+ * the value the endpoint is writing, recorded only when it differs from the stored one. The
116
+ * endpoint's after hook takes the entry and records it if the request succeeded.
117
+ */
118
+ type TwoFactorChanges = Map<string, boolean>;
119
+
120
+ /** The two-factor change this request made, read (and cleared) from the update hook's notes. */
121
+ const takeTwoFactorChange = (
122
+ ctx: HookContext,
123
+ changes: TwoFactorChanges
124
+ ): {action: SecurityActionId} | undefined => {
125
+ const userId = sessionUserOf(ctx)?.id;
126
+ if (!userId || !changes.has(userId)) {
127
+ return undefined;
128
+ }
129
+ const enabled = changes.get(userId);
130
+ changes.delete(userId);
131
+ if (!isSuccess(ctx.context.returned)) {
132
+ return undefined;
133
+ }
134
+ return {action: enabled ? "two-factor-enabled" : "two-factor-disabled"};
135
+ };
136
+
137
+ /** Which self-service action a successful request to `path` records, and its details. */
138
+ const actionFor = (
139
+ ctx: HookContext
140
+ ): {action: SecurityActionId; details?: Record<string, unknown>} | undefined => {
141
+ switch (ctx.path) {
142
+ case "/change-password":
143
+ return {action: "password-changed"};
144
+ case "/terreno/set-password":
145
+ return {action: "password-set"};
146
+ case "/revoke-other-sessions":
147
+ return {action: "other-sessions-revoked"};
148
+ case "/passkey/verify-registration": {
149
+ const passkeyId = stringOf((ctx.context.returned as {id?: unknown} | undefined)?.id);
150
+ return {action: "passkey-added", ...(passkeyId ? {details: {passkeyId}} : {})};
151
+ }
152
+ case "/passkey/delete-passkey": {
153
+ const passkeyId = stringOf(ctx.body?.id);
154
+ return {action: "passkey-removed", ...(passkeyId ? {details: {passkeyId}} : {})};
155
+ }
156
+ default:
157
+ return undefined;
158
+ }
159
+ };
160
+
161
+ const RECORDED_PATHS = new Set([
162
+ "/change-password",
163
+ "/passkey/delete-passkey",
164
+ "/passkey/verify-registration",
165
+ "/revoke-other-sessions",
166
+ "/terreno/set-password",
167
+ ...TWO_FACTOR_PATHS,
168
+ ]);
169
+
170
+ /**
171
+ * The Better Auth plugin that records self-service security changes. `createBetterAuth` adds it
172
+ * whenever it has a `userModel` (security principals are app User ids).
173
+ *
174
+ * - Endpoint `hooks.after`: `/change-password` (password-changed), `/terreno/set-password`
175
+ * (password-set, a first password for an OAuth- or passkey-only user), `/revoke-other-sessions`
176
+ * (other-sessions-revoked), `/passkey/verify-registration` (passkey-added),
177
+ * `/passkey/delete-passkey` (passkey-removed), and a successful `/two-factor/*` request that
178
+ * changed the user's stored `twoFactorEnabled` (two-factor-enabled / two-factor-disabled). The
179
+ * change is detected by a `user.update.before` database hook that compares the value being
180
+ * written with the user row in the database, not with the (possibly cookie-cached) session.
181
+ * So enrolment counts once, the 2FA step of a sign-in never does, and admin resets (which run
182
+ * outside any Better Auth endpoint) are not mistaken for the user's own change.
183
+ * - Database hooks, because they see the account row: a non-password `account` created for a
184
+ * user who already had another sign-in method (provider-linked, from `/link-social`, the link
185
+ * callback, the OAuth handoff, or implicit linking on sign-in), and an account deleted by
186
+ * `/unlink-account` (provider-unlinked). A first account is a sign-up, not a link.
187
+ *
188
+ * A completed `/reset-password` is recorded from `onPasswordReset` in `createBetterAuth`
189
+ * (password-reset), which knows the user the token belonged to.
190
+ */
191
+ export const createSecurityEventsPlugin = (userModel: UserModel): BetterAuthPlugin => {
192
+ const twoFactorChanges: TwoFactorChanges = new Map();
193
+ return {
194
+ hooks: {
195
+ after: [
196
+ {
197
+ handler: createAuthMiddleware(async (rawCtx): Promise<void> => {
198
+ const ctx = rawCtx as unknown as HookContext;
199
+ const recorded = TWO_FACTOR_PATHS.has(ctx.path ?? "")
200
+ ? takeTwoFactorChange(ctx, twoFactorChanges)
201
+ : isSuccess(ctx.context.returned)
202
+ ? actionFor(ctx)
203
+ : undefined;
204
+ if (!recorded) {
205
+ return;
206
+ }
207
+ await recordSelfSecurityAction({
208
+ ...recorded,
209
+ betterAuthUserId: sessionUserOf(ctx)?.id,
210
+ userModel,
211
+ });
212
+ }),
213
+ matcher: (context): boolean => RECORDED_PATHS.has(context.path ?? ""),
214
+ },
215
+ ],
216
+ },
217
+ id: "terreno-security-events",
218
+ init: (authContext) => {
219
+ const {internalAdapter} = authContext as unknown as AccountHookAdapter;
220
+ return {
221
+ options: {
222
+ databaseHooks: {
223
+ account: {
224
+ create: {
225
+ after: async (account): Promise<void> => {
226
+ const row = account as AccountRow;
227
+ if (!row.userId || !row.providerId || row.providerId === "credential") {
228
+ return;
229
+ }
230
+ try {
231
+ const accounts = await internalAdapter.findAccounts(row.userId);
232
+ if (accounts.length < 2) {
233
+ return;
234
+ }
235
+ } catch (error: unknown) {
236
+ logger.error(
237
+ `[AccountSecurity] Reading accounts for a new link failed: ${error}`
238
+ );
239
+ return;
240
+ }
241
+ await recordSelfSecurityAction({
242
+ action: "provider-linked",
243
+ betterAuthUserId: row.userId,
244
+ details: {providerId: row.providerId},
245
+ userModel,
246
+ });
247
+ },
248
+ },
249
+ delete: {
250
+ after: async (account, rawContext): Promise<void> => {
251
+ const context = rawContext as {path?: string} | null;
252
+ if (context?.path !== "/unlink-account") {
253
+ return;
254
+ }
255
+ const row = account as AccountRow;
256
+ await recordSelfSecurityAction({
257
+ action: "provider-unlinked",
258
+ betterAuthUserId: row.userId,
259
+ ...(row.providerId ? {details: {providerId: row.providerId}} : {}),
260
+ userModel,
261
+ });
262
+ },
263
+ },
264
+ },
265
+ user: {
266
+ update: {
267
+ before: async (data, rawContext): Promise<void> => {
268
+ const context = rawContext as DatabaseHookContext | null;
269
+ const next = (data as {twoFactorEnabled?: unknown}).twoFactorEnabled;
270
+ const userId = context?.context?.session?.user?.id;
271
+ if (
272
+ typeof next !== "boolean" ||
273
+ !userId ||
274
+ !TWO_FACTOR_PATHS.has(context?.path ?? "")
275
+ ) {
276
+ return;
277
+ }
278
+ try {
279
+ const stored = await internalAdapter.findUserById(userId);
280
+ if ((stored?.twoFactorEnabled === true) !== next) {
281
+ twoFactorChanges.set(userId, next);
282
+ }
283
+ } catch (error: unknown) {
284
+ logger.error(`[AccountSecurity] Reading two-factor state failed: ${error}`);
285
+ }
286
+ },
287
+ },
288
+ },
289
+ },
290
+ },
291
+ };
292
+ },
293
+ } satisfies BetterAuthPlugin;
294
+ };
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Security actions: the names, labels, and recording of every account-security event.
3
+ *
4
+ * Admin recovery actions (AccountSecurityApp routes) and self-service changes (a user linking a
5
+ * provider or turning on 2FA) are recorded the same way: an `AuditEvent` with
6
+ * `source: "security"` through the existing audit recorder, plus an in-process event that
7
+ * listeners (security notification emails) subscribe to.
8
+ */
9
+
10
+ import {DateTime} from "luxon";
11
+
12
+ import {isAuditRecorderInstalled, recordAuditEvent} from "../audit/record";
13
+ import {logger} from "../logger";
14
+
15
+ /** Who started a security action: an administrator on someone else's account, or the user. */
16
+ export type SecurityActionOrigin = "admin" | "self";
17
+
18
+ export interface SecurityActionDefinition {
19
+ /** Whether the admin UI should confirm before running it. */
20
+ destructive: boolean;
21
+ /** Short label for buttons and audit views. */
22
+ label: string;
23
+ origin: SecurityActionOrigin;
24
+ }
25
+
26
+ /**
27
+ * Every security action name. Admin actions are the recovery routes under
28
+ * `/users/:id/security/*` (and the org-admin prefix); self-service actions are recorded when the
29
+ * user changes their own sign-in methods.
30
+ */
31
+ export const SECURITY_ACTIONS = {
32
+ disable: {destructive: true, label: "Disable account", origin: "admin"},
33
+ enable: {destructive: false, label: "Enable account", origin: "admin"},
34
+ "issue-sign-in-link": {destructive: false, label: "Issue sign-in link", origin: "admin"},
35
+ "other-sessions-revoked": {
36
+ destructive: false,
37
+ label: "Other sessions signed out",
38
+ origin: "self",
39
+ },
40
+ "passkey-added": {destructive: false, label: "Passkey added", origin: "self"},
41
+ "passkey-removed": {destructive: false, label: "Passkey removed", origin: "self"},
42
+ "password-changed": {destructive: false, label: "Password changed", origin: "self"},
43
+ "password-reset": {destructive: false, label: "Password reset with a link", origin: "self"},
44
+ "password-set": {destructive: false, label: "Password added", origin: "self"},
45
+ "provider-linked": {destructive: false, label: "Sign-in provider linked", origin: "self"},
46
+ "provider-unlinked": {destructive: false, label: "Sign-in provider unlinked", origin: "self"},
47
+ "remove-passkey": {destructive: true, label: "Remove passkey", origin: "admin"},
48
+ "reset-two-factor": {destructive: true, label: "Reset two-factor", origin: "admin"},
49
+ "revoke-sessions": {destructive: true, label: "Sign out everywhere", origin: "admin"},
50
+ "send-password-reset": {destructive: false, label: "Send password reset", origin: "admin"},
51
+ "suspend-membership": {destructive: true, label: "Suspend membership", origin: "admin"},
52
+ "two-factor-disabled": {destructive: false, label: "Two-factor turned off", origin: "self"},
53
+ "two-factor-enabled": {destructive: false, label: "Two-factor turned on", origin: "self"},
54
+ "unlink-provider": {destructive: true, label: "Unlink provider", origin: "admin"},
55
+ } as const satisfies Record<string, SecurityActionDefinition>;
56
+
57
+ export type SecurityActionId = keyof typeof SECURITY_ACTIONS;
58
+
59
+ /** A user named by its app User id. */
60
+ export interface SecurityPrincipal {
61
+ id: string;
62
+ }
63
+
64
+ /** The organization whose admin acted, for actions run under the org-admin prefix. */
65
+ export interface SecurityActionOrg {
66
+ id: string;
67
+ name?: string;
68
+ }
69
+
70
+ export interface RecordSecurityActionArgs {
71
+ action: SecurityActionId;
72
+ /** Who acted. Omit only when no user is known (a system job). */
73
+ actor?: SecurityPrincipal;
74
+ /** Extra fields for the AuditEvent `after`, such as which passkey or provider. No secrets. */
75
+ details?: Record<string, unknown>;
76
+ org?: SecurityActionOrg;
77
+ /** Whose account changed. */
78
+ target: SecurityPrincipal;
79
+ }
80
+
81
+ /** What listeners receive for every recorded security action. */
82
+ export interface SecurityActionEvent extends RecordSecurityActionArgs {
83
+ /** ISO timestamp of when the action was recorded. */
84
+ occurredAt: string;
85
+ origin: SecurityActionOrigin;
86
+ }
87
+
88
+ export type SecurityActionListener = (event: SecurityActionEvent) => void | Promise<void>;
89
+
90
+ const listeners = new Set<SecurityActionListener>();
91
+
92
+ /**
93
+ * Subscribes to every recorded security action (for example, to email the affected user).
94
+ * Returns the unsubscribe function. A throwing listener is logged and never fails the action.
95
+ */
96
+ export const onSecurityAction = (listener: SecurityActionListener): (() => void) => {
97
+ listeners.add(listener);
98
+ return (): void => {
99
+ listeners.delete(listener);
100
+ };
101
+ };
102
+
103
+ export const clearSecurityActionListenersForTests = (): void => {
104
+ listeners.clear();
105
+ };
106
+
107
+ const notifyListeners = (event: SecurityActionEvent): void => {
108
+ for (const listener of listeners) {
109
+ try {
110
+ const result = listener(event);
111
+ if (result instanceof Promise) {
112
+ result.catch((error: unknown) => {
113
+ logger.error(`Security action listener failed for ${event.action}`, error);
114
+ });
115
+ }
116
+ } catch (error: unknown) {
117
+ logger.error(`Security action listener failed for ${event.action}`, error);
118
+ }
119
+ }
120
+ };
121
+
122
+ /**
123
+ * Records a security action: one `AuditEvent` (`source: "security"`, `modelName: "User"`,
124
+ * `recordId` the target, `verb: "updated"`, `after: {...details, securityAction,
125
+ * organizationId?}`) when
126
+ * AuditApp is registered, and one event to every {@link onSecurityAction} listener.
127
+ *
128
+ * The audit write follows the recorder's fire-and-forget convention: the returned promise
129
+ * settles when it is persisted (or failed and logged); HTTP handlers do not await it.
130
+ */
131
+ export const recordSecurityAction = ({
132
+ action,
133
+ actor,
134
+ details,
135
+ org,
136
+ target,
137
+ }: RecordSecurityActionArgs): Promise<void> => {
138
+ const event: SecurityActionEvent = {
139
+ action,
140
+ ...(actor ? {actor} : {}),
141
+ ...(details ? {details} : {}),
142
+ occurredAt: DateTime.now().toUTC().toISO() ?? "",
143
+ ...(org ? {org} : {}),
144
+ origin: SECURITY_ACTIONS[action].origin,
145
+ target,
146
+ };
147
+ notifyListeners(event);
148
+ if (!isAuditRecorderInstalled()) {
149
+ return Promise.resolve();
150
+ }
151
+ return recordAuditEvent({
152
+ actorId: actor?.id,
153
+ after: {
154
+ ...details,
155
+ securityAction: action,
156
+ ...(org ? {organizationId: org.id} : {}),
157
+ },
158
+ modelName: "User",
159
+ operation: "update",
160
+ ...(org ? {organizationId: org.id} : {}),
161
+ recordId: target.id,
162
+ source: "security",
163
+ verb: "updated",
164
+ });
165
+ };