@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,947 @@
1
+ import {afterEach, beforeAll, beforeEach, describe, expect, it, spyOn} from "bun:test";
2
+ import express from "express";
3
+ import mongoose from "mongoose";
4
+ import supertest from "supertest";
5
+
6
+ import {AuditApp} from "../audit/auditApp";
7
+ import {resetAuditRecorderForTests} from "../audit/record";
8
+ import {apiErrorMiddleware, NotFoundError} from "../errors";
9
+ import {logger} from "../logger";
10
+ import {McpServiceToken} from "../models/mcpServiceToken";
11
+ import {type RequestCredential, runWithRequestContext} from "../requestContext";
12
+ import {
13
+ AuditEvent,
14
+ access,
15
+ appUserId,
16
+ betterAuthCollection,
17
+ betterAuthIdFor,
18
+ buildApp,
19
+ getSummary,
20
+ resetAccountSecurityState,
21
+ resetTwoFactor,
22
+ SecurityUser,
23
+ securityEventsFor,
24
+ securityUserModel,
25
+ selfSecurityEventsFor,
26
+ signInWithPassword,
27
+ signUp,
28
+ } from "../tests/accountSecurityTestApp";
29
+ import {
30
+ enrollTwoFactor,
31
+ PASSWORD,
32
+ setCookies,
33
+ totpCode,
34
+ uniqueEmail,
35
+ } from "../tests/betterAuthStubs";
36
+ import {AccountSecurityApp, resetTwoFactorAction} from "./accountSecurityApp";
37
+ import {
38
+ type AccountSecuritySummary,
39
+ storesTrustDeviceIdentifiersPlain,
40
+ } from "./accountSecurityService";
41
+ import {
42
+ clearSecurityActionListenersForTests,
43
+ onSecurityAction,
44
+ recordSecurityAction,
45
+ type SecurityActionEvent,
46
+ } from "./securityEvents";
47
+
48
+ /**
49
+ * Signs in with the password and answers the 2FA challenge with "trust this device", returning
50
+ * the signed trust cookie the browser would keep.
51
+ */
52
+ const trustDevice = async (
53
+ app: express.Application,
54
+ email: string,
55
+ secret: Buffer
56
+ ): Promise<string> => {
57
+ const signIn = await signInWithPassword(app, email);
58
+ expect(signIn.body.twoFactorRedirect).toBe(true);
59
+ const verify = await supertest(app)
60
+ .post("/api/auth/two-factor/verify-totp")
61
+ .set("content-type", "application/json")
62
+ .set(
63
+ "cookie",
64
+ setCookies(signIn)
65
+ .map((cookie) => cookie.split(";")[0])
66
+ .join("; ")
67
+ )
68
+ .send({code: totpCode(secret), trustDevice: true});
69
+ expect(verify.status).toBe(200);
70
+ const trustCookie = setCookies(verify).find((cookie) => cookie.includes("trust_device="));
71
+ expect(trustCookie).toBeTruthy();
72
+ return (trustCookie ?? "").split(";")[0];
73
+ };
74
+
75
+ const BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
76
+
77
+ const base32Secret = (totpURI: string): Buffer => {
78
+ let bits = "";
79
+ const encoded = new URL(totpURI).searchParams.get("secret") ?? "";
80
+ for (const char of encoded.replace(/=+$/, "").toUpperCase()) {
81
+ bits += BASE32_ALPHABET.indexOf(char).toString(2).padStart(5, "0");
82
+ }
83
+ const bytes: number[] = [];
84
+ for (let index = 0; index + 8 <= bits.length; index += 8) {
85
+ bytes.push(Number.parseInt(bits.slice(index, index + 8), 2));
86
+ }
87
+ return Buffer.from(bytes);
88
+ };
89
+
90
+ /** Turns 2FA on again for a user who already has an account, as their own security screen does. */
91
+ const reEnrollTwoFactor = async (app: express.Application, email: string): Promise<Buffer> => {
92
+ const signIn = await signInWithPassword(app, email);
93
+ expect(signIn.status).toBe(200);
94
+ const bearer = `Bearer ${signIn.body.token}`;
95
+ const enable = await supertest(app)
96
+ .post("/api/auth/two-factor/enable")
97
+ .set("authorization", bearer)
98
+ .set("content-type", "application/json")
99
+ .send({password: PASSWORD});
100
+ expect(enable.status).toBe(200);
101
+ const secret = base32Secret(enable.body.totpURI as string);
102
+ const confirm = await supertest(app)
103
+ .post("/api/auth/two-factor/verify-totp")
104
+ .set("authorization", bearer)
105
+ .set("content-type", "application/json")
106
+ .send({code: totpCode(secret)});
107
+ expect(confirm.status).toBe(200);
108
+ return secret;
109
+ };
110
+
111
+ interface CustomHostOptions {
112
+ actorId: string;
113
+ authorizeTargetId: string;
114
+ credential?: RequestCredential | "service-account";
115
+ security: AccountSecurityApp;
116
+ }
117
+
118
+ /** Mounts the security routes under /custom on a bare host with an org authorizer. */
119
+ const buildCustomHost = ({
120
+ actorId,
121
+ authorizeTargetId,
122
+ credential = "jwt",
123
+ security,
124
+ }: CustomHostOptions): express.Application => {
125
+ const router = express.Router();
126
+ security.mountSecurityRoutes(router, async ({req, targetUserId}) => {
127
+ if (targetUserId !== authorizeTargetId) {
128
+ throw new NotFoundError("Member not found");
129
+ }
130
+ return {actor: req.user as never, org: {id: "org-1", name: "Org One"}};
131
+ });
132
+ const host = express();
133
+ host.use(express.json());
134
+ host.use((req, _res, next) => {
135
+ (req as {user?: unknown}).user = {_id: actorId, id: actorId};
136
+ runWithRequestContext({credential: credential as RequestCredential}, () => next());
137
+ });
138
+ host.use("/custom", router);
139
+ host.use(apiErrorMiddleware);
140
+ return host;
141
+ };
142
+
143
+ describe("AccountSecurityApp", () => {
144
+ beforeAll(async () => {
145
+ await access.roles.seedDefaults();
146
+ });
147
+
148
+ beforeEach(async () => {
149
+ await resetAccountSecurityState();
150
+ });
151
+
152
+ afterEach(() => {
153
+ resetAuditRecorderForTests();
154
+ clearSecurityActionListenersForTests();
155
+ });
156
+
157
+ describe("platform routes", () => {
158
+ it("an operator reads the summary and resets 2FA, and the user then signs in without a challenge", async () => {
159
+ const {app} = buildApp();
160
+ const operator = await signUp(app, "operator", ["operator"]);
161
+ const targetEmail = uniqueEmail("target");
162
+ const {enrollment, token: targetToken} = await enrollTwoFactor(app, targetEmail);
163
+ const targetId = await appUserId(targetEmail);
164
+
165
+ const before = await getSummary(app, operator.token, targetId);
166
+ expect(before.status).toBe(200);
167
+ const summary = before.body.data as AccountSecuritySummary;
168
+ expect(summary.userId).toBe(targetId);
169
+ expect(summary.betterAuthLinked).toBe(true);
170
+ expect(summary.password).toBe(true);
171
+ expect(summary.providers).toEqual([]);
172
+ expect(summary.twoFactor).toEqual({backupCodesRemaining: 10, enabled: true});
173
+ expect(summary.sessions.active).toBeGreaterThanOrEqual(1);
174
+ expect(summary.lastSignIn.at).toBeTruthy();
175
+ expect(summary.disabled).toBe(false);
176
+ expect(summary.actions).toEqual([
177
+ {
178
+ destructive: true,
179
+ id: "reset-two-factor",
180
+ label: "Reset two-factor",
181
+ method: "POST",
182
+ path: "/reset-two-factor",
183
+ },
184
+ {
185
+ destructive: true,
186
+ id: "revoke-sessions",
187
+ label: "Sign out everywhere",
188
+ method: "POST",
189
+ path: "/revoke-sessions",
190
+ },
191
+ {
192
+ destructive: false,
193
+ id: "send-password-reset",
194
+ label: "Send password reset",
195
+ method: "POST",
196
+ path: "/send-password-reset",
197
+ },
198
+ {
199
+ destructive: true,
200
+ id: "disable",
201
+ label: "Disable account",
202
+ method: "POST",
203
+ path: "/disable",
204
+ },
205
+ ]);
206
+
207
+ // The summary never carries the TOTP secret, backup codes, or session tokens.
208
+ const body = JSON.stringify(before.body);
209
+ const totpSecret = new URL(enrollment.totpURI).searchParams.get("secret") ?? "";
210
+ expect(body).not.toContain(totpSecret);
211
+ for (const code of enrollment.backupCodes) {
212
+ expect(body).not.toContain(code);
213
+ }
214
+ expect(body).not.toContain(targetToken);
215
+ expect(body).not.toContain(operator.token);
216
+
217
+ const challenged = await signInWithPassword(app, targetEmail);
218
+ expect(challenged.body.twoFactorRedirect).toBe(true);
219
+
220
+ const reset = await resetTwoFactor(app, operator.token, targetId);
221
+ expect(reset.status).toBe(200);
222
+ expect(reset.body.data).toEqual({action: "reset-two-factor", changed: true});
223
+
224
+ const signIn = await signInWithPassword(app, targetEmail);
225
+ expect(signIn.status).toBe(200);
226
+ expect(signIn.body.twoFactorRedirect).toBeUndefined();
227
+ expect(signIn.body.token).toBeTruthy();
228
+
229
+ const after = await getSummary(app, operator.token, targetId);
230
+ expect(after.body.data.twoFactor).toEqual({backupCodesRemaining: null, enabled: false});
231
+ expect(after.body.data.actions.map((action: {id: string}) => action.id)).toEqual([
232
+ "revoke-sessions",
233
+ "send-password-reset",
234
+ "disable",
235
+ ]);
236
+ const twoFactorRows = await mongoose.connection.db
237
+ ?.collection("twoFactor")
238
+ .countDocuments({});
239
+ expect(twoFactorRows).toBe(0);
240
+ });
241
+
242
+ it("each reset writes one security AuditEvent naming the actor and target", async () => {
243
+ const {app} = buildApp();
244
+ const operator = await signUp(app, "operator-audit", ["operator"]);
245
+ const targetEmail = uniqueEmail("audit-target");
246
+ await enrollTwoFactor(app, targetEmail);
247
+ const targetId = await appUserId(targetEmail);
248
+
249
+ const reset = await resetTwoFactor(app, operator.token, targetId);
250
+ expect(reset.status).toBe(200);
251
+
252
+ const securityEvents = await securityEventsFor(targetId);
253
+ expect(securityEvents).toHaveLength(1);
254
+ expect(securityEvents[0]).toMatchObject({
255
+ after: {securityAction: "reset-two-factor"},
256
+ modelName: "User",
257
+ operation: "update",
258
+ recordId: targetId,
259
+ source: "security",
260
+ verb: "updated",
261
+ });
262
+ expect(String(securityEvents[0].actorId)).toBe(operator.id);
263
+ });
264
+
265
+ it("resetting when 2FA is already off is a 200 no-op that is not audited", async () => {
266
+ const {app} = buildApp();
267
+ const operator = await signUp(app, "operator-noop", ["operator"]);
268
+ const target = await signUp(app, "no-two-factor");
269
+ const events: SecurityActionEvent[] = [];
270
+ onSecurityAction((event) => {
271
+ events.push(event);
272
+ });
273
+
274
+ const reset = await resetTwoFactor(app, operator.token, target.id);
275
+
276
+ expect(reset.status).toBe(200);
277
+ expect(reset.body.data).toEqual({action: "reset-two-factor", changed: false});
278
+ expect(await securityEventsFor(target.id)).toHaveLength(0);
279
+ expect(events).toHaveLength(0);
280
+ });
281
+
282
+ it("tells listeners about each recorded action", async () => {
283
+ const {app} = buildApp();
284
+ const operator = await signUp(app, "operator-listen", ["operator"]);
285
+ const targetEmail = uniqueEmail("listen-target");
286
+ await enrollTwoFactor(app, targetEmail);
287
+ const targetId = await appUserId(targetEmail);
288
+ const events: SecurityActionEvent[] = [];
289
+ onSecurityAction((event) => {
290
+ events.push(event);
291
+ });
292
+
293
+ await resetTwoFactor(app, operator.token, targetId).expect(200);
294
+
295
+ expect(events).toHaveLength(1);
296
+ expect(events[0]).toMatchObject({
297
+ action: "reset-two-factor",
298
+ actor: {id: operator.id},
299
+ origin: "admin",
300
+ target: {id: targetId},
301
+ });
302
+ expect(events[0].occurredAt).toBeTruthy();
303
+ });
304
+
305
+ it("lists passkey names and linked providers without their credentials", async () => {
306
+ const {app, betterAuthApp} = buildApp();
307
+ const operator = await signUp(app, "operator-passkeys", ["operator"]);
308
+ const target = await signUp(app, "passkey-owner");
309
+ const user = await SecurityUser.findById(target.id);
310
+ const context = await betterAuthApp.ensureAuth().$context;
311
+ await context.adapter.create({
312
+ data: {
313
+ backedUp: false,
314
+ counter: 0,
315
+ createdAt: new Date("2026-01-02T03:04:05.000Z"),
316
+ credentialID: "credential-id-secret",
317
+ deviceType: "singleDevice",
318
+ name: "Work laptop",
319
+ publicKey: "public-key-material",
320
+ userId: user?.betterAuthId ?? "",
321
+ },
322
+ model: "passkey",
323
+ });
324
+ await context.adapter.create({
325
+ data: {
326
+ backedUp: true,
327
+ counter: 0,
328
+ credentialID: "second-credential-id",
329
+ deviceType: "multiDevice",
330
+ publicKey: "second-public-key",
331
+ userId: user?.betterAuthId ?? "",
332
+ },
333
+ model: "passkey",
334
+ });
335
+ // A user whose sessions have all been removed has no last sign-in time.
336
+ await context.internalAdapter.deleteUserSessions(user?.betterAuthId ?? "");
337
+ await context.internalAdapter.createAccount({
338
+ accessToken: "github-access-token",
339
+ accountId: "github-account-1",
340
+ providerId: "github",
341
+ refreshToken: "github-refresh-token",
342
+ userId: user?.betterAuthId ?? "",
343
+ });
344
+
345
+ const res = await getSummary(app, operator.token, target.id);
346
+
347
+ expect(res.status).toBe(200);
348
+ expect(res.body.data.passkeys.count).toBe(2);
349
+ const items = res.body.data.passkeys.items as {
350
+ createdAt: string | null;
351
+ id: string;
352
+ name: string | null;
353
+ }[];
354
+ const laptop = items.find((item) => item.name === "Work laptop");
355
+ expect(laptop?.createdAt).toBe("2026-01-02T03:04:05.000Z");
356
+ expect(laptop?.id).toBeTruthy();
357
+ const unnamed = items.find((item) => item.name === null);
358
+ expect(unnamed?.createdAt).toBeNull();
359
+ expect(res.body.data.sessions).toEqual({active: 0});
360
+ expect(res.body.data.lastSignIn.at).toBeNull();
361
+ expect(res.body.data.providers).toHaveLength(1);
362
+ expect(res.body.data.providers[0].providerId).toBe("github");
363
+ const body = JSON.stringify(res.body);
364
+ for (const secret of [
365
+ "credential-id-secret",
366
+ "public-key-material",
367
+ "second-credential-id",
368
+ "second-public-key",
369
+ "github-access-token",
370
+ "github-refresh-token",
371
+ "github-account-1",
372
+ ]) {
373
+ expect(body).not.toContain(secret);
374
+ }
375
+ });
376
+
377
+ it("reports empty values for a legacy user with no Better Auth link", async () => {
378
+ const {app} = buildApp();
379
+ const operator = await signUp(app, "operator-legacy", ["operator"]);
380
+ const legacy = await SecurityUser.create({
381
+ disabled: true,
382
+ email: uniqueEmail("legacy"),
383
+ name: "Legacy",
384
+ });
385
+
386
+ const res = await getSummary(app, operator.token, String(legacy._id));
387
+
388
+ expect(res.status).toBe(200);
389
+ expect(res.body.data).toEqual({
390
+ // issue-sign-in-link also applies, but an operator lacks user:issueSignInLink.
391
+ actions: [
392
+ {
393
+ destructive: false,
394
+ id: "enable",
395
+ label: "Enable account",
396
+ method: "POST",
397
+ path: "/enable",
398
+ },
399
+ ],
400
+ betterAuthLinked: false,
401
+ disabled: true,
402
+ emailVerified: false,
403
+ lastSignIn: {at: null, method: null},
404
+ legacyPassword: false,
405
+ passkeys: {count: 0, items: []},
406
+ password: false,
407
+ providers: [],
408
+ sessions: {active: 0},
409
+ twoFactor: {backupCodesRemaining: null, enabled: false},
410
+ userId: String(legacy._id),
411
+ });
412
+
413
+ const reset = await resetTwoFactor(app, operator.token, String(legacy._id));
414
+ expect(reset.status).toBe(200);
415
+ expect(reset.body.data.changed).toBe(false);
416
+ });
417
+
418
+ it("treats a betterAuthId whose Better Auth user is gone like a legacy user", async () => {
419
+ const {app} = buildApp();
420
+ const operator = await signUp(app, "operator-dangling", ["operator"]);
421
+ const dangling = await SecurityUser.create({
422
+ betterAuthId: "missing-better-auth-user",
423
+ email: uniqueEmail("dangling"),
424
+ });
425
+ const id = String(dangling._id);
426
+
427
+ const summary = await getSummary(app, operator.token, id);
428
+ expect(summary.status).toBe(200);
429
+ expect(summary.body.data.betterAuthLinked).toBe(false);
430
+
431
+ const reset = await resetTwoFactor(app, operator.token, id);
432
+ expect(reset.status).toBe(200);
433
+ expect(reset.body.data.changed).toBe(false);
434
+ });
435
+
436
+ it("reports backup codes as unknown when Better Auth cannot read them", async () => {
437
+ const {app} = buildApp();
438
+ const operator = await signUp(app, "operator-codes", ["operator"]);
439
+ const targetEmail = uniqueEmail("codes-target");
440
+ await enrollTwoFactor(app, targetEmail);
441
+ const targetId = await appUserId(targetEmail);
442
+ await mongoose.connection.db
443
+ ?.collection("twoFactor")
444
+ .updateMany({}, {$set: {backupCodes: "not-encrypted-codes"}});
445
+
446
+ const res = await getSummary(app, operator.token, targetId);
447
+
448
+ expect(res.status).toBe(200);
449
+ expect(res.body.data.twoFactor).toEqual({backupCodesRemaining: null, enabled: true});
450
+ });
451
+
452
+ it("forgets trusted devices, so a trusted browser is challenged after the user re-enrolls", async () => {
453
+ const {app} = buildApp();
454
+ const operator = await signUp(app, "operator-trust", ["operator"]);
455
+ const targetEmail = uniqueEmail("trusted-target");
456
+ const {secret} = await enrollTwoFactor(app, targetEmail);
457
+ const targetId = await appUserId(targetEmail);
458
+ const betterAuthId = await betterAuthIdFor(targetId);
459
+ const trustCookie = await trustDevice(app, targetEmail, secret);
460
+ // The trusted browser skips the challenge before the reset.
461
+ const trusted = await signInWithPassword(app, targetEmail).set("cookie", trustCookie);
462
+ expect(trusted.body.twoFactorRedirect).toBeUndefined();
463
+ const trustRows = (): Promise<number> =>
464
+ betterAuthCollection("verification").countDocuments({
465
+ identifier: {$regex: "^trust-device-"},
466
+ value: betterAuthId,
467
+ });
468
+ expect(await trustRows()).toBe(1);
469
+
470
+ const reset = await resetTwoFactor(app, operator.token, targetId);
471
+ expect(reset.status).toBe(200);
472
+ expect(reset.body.data.changed).toBe(true);
473
+ expect(await trustRows()).toBe(0);
474
+
475
+ await reEnrollTwoFactor(app, targetEmail);
476
+ const challenged = await signInWithPassword(app, targetEmail).set("cookie", trustCookie);
477
+ expect(challenged.status).toBe(200);
478
+ expect(challenged.body.twoFactorRedirect).toBe(true);
479
+ });
480
+
481
+ it("forgets trusted devices when Better Auth hashes verification identifiers", async () => {
482
+ const {app} = buildApp({config: {options: {verification: {storeIdentifier: "hashed"}}}});
483
+ const operator = await signUp(app, "operator-hashed", ["operator"]);
484
+ const targetEmail = uniqueEmail("hashed-target");
485
+ const {secret} = await enrollTwoFactor(app, targetEmail);
486
+ const targetId = await appUserId(targetEmail);
487
+ const betterAuthId = await betterAuthIdFor(targetId);
488
+ await trustDevice(app, targetEmail, secret);
489
+ const rowsFor = (): Promise<number> =>
490
+ betterAuthCollection("verification").countDocuments({value: betterAuthId});
491
+ expect(await rowsFor()).toBeGreaterThan(0);
492
+
493
+ const reset = await resetTwoFactor(app, operator.token, targetId);
494
+
495
+ expect(reset.status).toBe(200);
496
+ expect(await rowsFor()).toBe(0);
497
+ });
498
+
499
+ it("leaves another enrolled user's 2FA alone", async () => {
500
+ const {app} = buildApp();
501
+ const operator = await signUp(app, "operator-other", ["operator"]);
502
+ const targetEmail = uniqueEmail("reset-target");
503
+ const bystanderEmail = uniqueEmail("bystander");
504
+ await enrollTwoFactor(app, targetEmail);
505
+ await enrollTwoFactor(app, bystanderEmail);
506
+ const targetId = await appUserId(targetEmail);
507
+ const bystanderBetterAuthId = await betterAuthIdFor(await appUserId(bystanderEmail));
508
+
509
+ const reset = await resetTwoFactor(app, operator.token, targetId);
510
+ expect(reset.status).toBe(200);
511
+
512
+ const twoFactorRows = betterAuthCollection("twoFactor");
513
+ expect(await twoFactorRows.countDocuments({})).toBe(1);
514
+ const remaining = await twoFactorRows.findOne({});
515
+ expect(String(remaining?.userId)).toBe(bystanderBetterAuthId);
516
+ const bystanderSignIn = await signInWithPassword(app, bystanderEmail);
517
+ expect(bystanderSignIn.body.twoFactorRedirect).toBe(true);
518
+ });
519
+
520
+ it("clears a half-finished enrollment (secret stored, 2FA not yet on)", async () => {
521
+ const {app} = buildApp();
522
+ const operator = await signUp(app, "operator-half", ["operator"]);
523
+ const target = await signUp(app, "half-enrolled");
524
+ const enable = await supertest(app)
525
+ .post("/api/auth/two-factor/enable")
526
+ .set("authorization", `Bearer ${target.token}`)
527
+ .set("content-type", "application/json")
528
+ .send({password: PASSWORD});
529
+ expect(enable.status).toBe(200);
530
+ const twoFactorRows = betterAuthCollection("twoFactor");
531
+ expect(await twoFactorRows.countDocuments({})).toBe(1);
532
+ const betterAuthUser = await betterAuthCollection("user").findOne({email: target.email});
533
+ expect(betterAuthUser?.twoFactorEnabled).toBe(false);
534
+
535
+ const reset = await resetTwoFactor(app, operator.token, target.id);
536
+
537
+ expect(reset.status).toBe(200);
538
+ expect(reset.body.data.changed).toBe(true);
539
+ expect(await securityEventsFor(target.id)).toHaveLength(1);
540
+ expect(await twoFactorRows.countDocuments({})).toBe(0);
541
+ });
542
+
543
+ it("reports the stored last sign-in method", async () => {
544
+ const {app} = buildApp({config: {lastLoginMethod: true}});
545
+ const operator = await signUp(app, "operator-method", ["operator"]);
546
+ const target = await signUp(app, "method-target");
547
+
548
+ const res = await getSummary(app, operator.token, target.id);
549
+
550
+ expect(res.body.data.lastSignIn.method).toBe("email");
551
+ });
552
+
553
+ it("answers 404 for an unknown user and for an id that is not an ObjectId", async () => {
554
+ const {app} = buildApp();
555
+ const operator = await signUp(app, "operator-404", ["operator"]);
556
+
557
+ const unknown = await getSummary(
558
+ app,
559
+ operator.token,
560
+ new mongoose.Types.ObjectId().toString()
561
+ );
562
+ expect(unknown.status).toBe(404);
563
+ expect(unknown.body.title).toBe("User not found");
564
+
565
+ const malformed = await resetTwoFactor(app, operator.token, "not-an-id");
566
+ expect(malformed.status).toBe(404);
567
+ });
568
+
569
+ it("answers 404 for reset when two-factor is not enabled on the server", async () => {
570
+ const {app} = buildApp({config: {passkey: undefined, twoFactor: undefined}});
571
+ const operator = await signUp(app, "operator-no-2fa", ["operator"]);
572
+ const target = await signUp(app, "target-no-2fa");
573
+
574
+ const summary = await getSummary(app, operator.token, target.id);
575
+ expect(summary.status).toBe(200);
576
+ expect(summary.body.data.actions.map((action: {id: string}) => action.id)).toEqual([
577
+ "revoke-sessions",
578
+ "send-password-reset",
579
+ "disable",
580
+ ]);
581
+ expect(summary.body.data.passkeys).toEqual({count: 0, items: []});
582
+
583
+ const reset = await resetTwoFactor(app, operator.token, target.id);
584
+ expect(reset.status).toBe(404);
585
+ expect(reset.body.title).toBe("Security action not available");
586
+ });
587
+ });
588
+
589
+ describe("authorization", () => {
590
+ it("refuses a member with 403", async () => {
591
+ const {app} = buildApp();
592
+ const member = await signUp(app, "member");
593
+ const target = await signUp(app, "member-target");
594
+
595
+ const summary = await getSummary(app, member.token, target.id);
596
+ expect(summary.status).toBe(403);
597
+ const reset = await resetTwoFactor(app, member.token, target.id);
598
+ expect(reset.status).toBe(403);
599
+ expect(await securityEventsFor(target.id)).toHaveLength(0);
600
+ });
601
+
602
+ it("refuses a member before revealing whether the target exists", async () => {
603
+ const {app} = buildApp();
604
+ const member = await signUp(app, "member-probe");
605
+
606
+ const res = await getSummary(app, member.token, new mongoose.Types.ObjectId().toString());
607
+
608
+ expect(res.status).toBe(403);
609
+ });
610
+
611
+ it("refuses an unauthenticated request with 401", async () => {
612
+ const {app} = buildApp();
613
+ const target = await signUp(app, "anon-target");
614
+
615
+ const res = await supertest(app).get(`/users/${target.id}/security`);
616
+
617
+ expect(res.status).toBe(401);
618
+ });
619
+
620
+ it("refuses an operator's MCP service token with 403", async () => {
621
+ const {app} = buildApp();
622
+ const operator = await signUp(app, "operator-mcp", ["operator"]);
623
+ const target = await signUp(app, "mcp-target");
624
+ const issued = await McpServiceToken.issueFor(
625
+ {_id: new mongoose.Types.ObjectId(operator.id)},
626
+ {name: "Agent"}
627
+ );
628
+
629
+ const summary = await getSummary(app, issued.token, target.id);
630
+ expect(summary.status).toBe(403);
631
+ expect(summary.body.title).toBe("Account security requires your own session");
632
+ const reset = await resetTwoFactor(app, issued.token, target.id);
633
+ expect(reset.status).toBe(403);
634
+ });
635
+
636
+ it("refuses an MCP OAuth access token with 403", async () => {
637
+ const {app} = buildApp();
638
+ const target = await signUp(app, "oauth-target");
639
+
640
+ const res = await getSummary(app, "mcpat_not-a-real-token", target.id);
641
+
642
+ expect(res.status).toBe(403);
643
+ });
644
+
645
+ it("refuses an actor acting on themselves", async () => {
646
+ const {app} = buildApp();
647
+ const operator = await signUp(app, "operator-self", ["operator"]);
648
+
649
+ const summary = await getSummary(app, operator.token, operator.id);
650
+ expect(summary.status).toBe(403);
651
+ expect(summary.body.title).toBe("Use your own security settings to change your account");
652
+ const reset = await resetTwoFactor(app, operator.token, operator.id);
653
+ expect(reset.status).toBe(403);
654
+ });
655
+
656
+ it("refuses an operator acting on a superadmin, and allows a superadmin", async () => {
657
+ const {app} = buildApp();
658
+ const operator = await signUp(app, "operator-up", ["operator"]);
659
+ const superadmin = await signUp(app, "superadmin-target", ["superadmin"]);
660
+ const otherSuperadmin = await signUp(app, "superadmin-actor", ["superadmin"]);
661
+
662
+ const refused = await resetTwoFactor(app, operator.token, superadmin.id);
663
+ expect(refused.status).toBe(403);
664
+ expect(refused.body.title).toBe("Target holds permissions you lack");
665
+ expect((await getSummary(app, operator.token, superadmin.id)).status).toBe(403);
666
+ expect((await getSummary(app, otherSuperadmin.token, superadmin.id)).status).toBe(200);
667
+ expect((await getSummary(app, superadmin.token, operator.id)).status).toBe(200);
668
+ });
669
+
670
+ it("refuses a target holding any permission the actor lacks", async () => {
671
+ const {app} = buildApp();
672
+ const operator = await signUp(app, "operator-reach", ["operator"]);
673
+ const peer = await signUp(app, "operator-peer", ["operator"]);
674
+ const roleAdmin = await signUp(app, "rbac-admin", ["admin"]);
675
+
676
+ const res = await getSummary(app, operator.token, roleAdmin.id);
677
+ expect(res.status).toBe(403);
678
+ expect(res.body.title).toBe("Target holds permissions you lack");
679
+ expect(res.body.detail).toContain("adminAnnouncement:read");
680
+ expect((await getSummary(app, operator.token, peer.id)).status).toBe(200);
681
+ });
682
+
683
+ it("refuses a non-admin acting on an admin: true user", async () => {
684
+ const {app} = buildApp();
685
+ const operator = await signUp(app, "operator-legacy-admin", ["operator"]);
686
+ const legacyAdmin = await signUp(app, "legacy-admin");
687
+ await SecurityUser.updateOne({_id: legacyAdmin.id}, {$set: {admin: true}});
688
+
689
+ const res = await getSummary(app, operator.token, legacyAdmin.id);
690
+
691
+ expect(res.status).toBe(403);
692
+ expect(res.body.title).toBe("Target holds permissions you lack");
693
+ });
694
+
695
+ it("refuses a request whose credential is not the user's own session", async () => {
696
+ const {app} = buildApp();
697
+ const target = await signUp(app, "credential-target");
698
+ const actor = await signUp(app, "credential-actor");
699
+ for (const credential of ["service-account", "mcp-service-token", "oauth"] as const) {
700
+ const host = buildCustomHost({
701
+ actorId: actor.id,
702
+ authorizeTargetId: target.id,
703
+ credential,
704
+ security: new AccountSecurityApp({audit: false, userModel: securityUserModel}),
705
+ });
706
+ const res = await supertest(host).get(`/custom/${target.id}/security`);
707
+ expect(res.status).toBe(403);
708
+ expect(res.body.title).toBe("Account security requires your own session");
709
+ }
710
+ });
711
+
712
+ it("grants superadmin through the wildcard role", async () => {
713
+ const {app} = buildApp();
714
+ const superadmin = await signUp(app, "superadmin", ["superadmin"]);
715
+ const target = await signUp(app, "superadmin-target");
716
+
717
+ const res = await getSummary(app, superadmin.token, target.id);
718
+
719
+ expect(res.status).toBe(200);
720
+ });
721
+
722
+ it("without RBAC, requires admin: true", async () => {
723
+ const {app} = buildApp({accessControl: false});
724
+ const member = await signUp(app, "plain-member");
725
+ const admin = await signUp(app, "plain-admin");
726
+ await SecurityUser.updateOne({_id: admin.id}, {$set: {admin: true}});
727
+
728
+ expect((await getSummary(app, member.token, admin.id)).status).toBe(403);
729
+ expect((await getSummary(app, admin.token, member.id)).status).toBe(200);
730
+ });
731
+
732
+ it("mounts the same handlers under another prefix with a custom authorizer", async () => {
733
+ const {app} = buildApp();
734
+ const target = await signUp(app, "custom-target");
735
+ const actor = await signUp(app, "custom-actor");
736
+ const warn = spyOn(logger, "warn");
737
+ const security = new AccountSecurityApp({audit: false, userModel: securityUserModel});
738
+ const host = buildCustomHost({
739
+ actorId: actor.id,
740
+ authorizeTargetId: target.id,
741
+ security,
742
+ });
743
+
744
+ const allowed = await supertest(host).get(`/custom/${target.id}/security`);
745
+ expect(allowed.status).toBe(200);
746
+ expect(allowed.body.data.betterAuthLinked).toBe(false);
747
+ expect(security.getActions().map((action) => action.id)).toEqual([
748
+ "reset-two-factor",
749
+ "remove-passkey",
750
+ "unlink-provider",
751
+ "revoke-sessions",
752
+ "send-password-reset",
753
+ "disable",
754
+ "enable",
755
+ "suspend-membership",
756
+ "issue-sign-in-link",
757
+ ]);
758
+ await supertest(host).get(`/custom/${target.id}/security`).expect(200);
759
+ const noBetterAuthWarnings = warn.mock.calls.filter((call) =>
760
+ String(call[0]).includes("AccountSecurityApp found no Better Auth instance")
761
+ );
762
+ warn.mockRestore();
763
+ expect(noBetterAuthWarnings).toHaveLength(1);
764
+
765
+ const refused = await supertest(host).get(`/custom/${actor.id}/security`);
766
+ expect(refused.status).toBe(404);
767
+ expect(refused.body.title).toBe("Member not found");
768
+ });
769
+
770
+ it("records the authorizer's org on a reset under another prefix", async () => {
771
+ const {app, betterAuthApp} = buildApp();
772
+ const actor = await signUp(app, "org-admin");
773
+ const targetEmail = uniqueEmail("org-member");
774
+ await enrollTwoFactor(app, targetEmail);
775
+ const targetId = await appUserId(targetEmail);
776
+ const security = new AccountSecurityApp({
777
+ getBetterAuth: () => betterAuthApp.ensureAuth(),
778
+ userModel: securityUserModel,
779
+ });
780
+ const host = buildCustomHost({actorId: actor.id, authorizeTargetId: targetId, security});
781
+
782
+ const reset = await supertest(host)
783
+ .post(`/custom/${targetId}/security/reset-two-factor`)
784
+ .send({});
785
+
786
+ expect(reset.status).toBe(200);
787
+ expect(reset.body.data.changed).toBe(true);
788
+ const events = await securityEventsFor(targetId);
789
+ expect(events).toHaveLength(1);
790
+ expect(events[0]).toMatchObject({
791
+ after: {organizationId: "org-1", securityAction: "reset-two-factor"},
792
+ organizationId: "org-1",
793
+ });
794
+ });
795
+
796
+ it("merges an action's audit fields into the AuditEvent", async () => {
797
+ const {app} = buildApp({
798
+ security: {
799
+ actions: [
800
+ {
801
+ id: "password-changed",
802
+ isApplicable: () => true,
803
+ isSupported: () => true,
804
+ method: "delete",
805
+ path: "/audit-details/:itemId",
806
+ run: async ({req}) => ({
807
+ audit: {itemId: req.params.itemId, securityAction: "spoofed"},
808
+ changed: true,
809
+ data: {itemId: req.params.itemId},
810
+ }),
811
+ },
812
+ ],
813
+ },
814
+ });
815
+ const operator = await signUp(app, "operator-details", ["operator"]);
816
+ const target = await signUp(app, "details-target");
817
+
818
+ const summary = await getSummary(app, operator.token, target.id);
819
+ expect(summary.status).toBe(200);
820
+ // Clients run a custom action from the summary alone: its method and placeholder path.
821
+ expect(summary.body.data.actions).toContainEqual({
822
+ destructive: false,
823
+ id: "password-changed",
824
+ label: "Password changed",
825
+ method: "DELETE",
826
+ path: "/audit-details/:itemId",
827
+ });
828
+ const res = await supertest(app)
829
+ .delete(`/users/${target.id}/security/audit-details/pk-123`)
830
+ .set("authorization", `Bearer ${operator.token}`);
831
+
832
+ expect(res.status).toBe(200);
833
+ expect(res.body.data).toEqual({
834
+ action: "password-changed",
835
+ changed: true,
836
+ itemId: "pk-123",
837
+ });
838
+ // The custom action reuses a self-service id, so its event is among the self events.
839
+ const events = await selfSecurityEventsFor(target.id);
840
+ expect(events).toHaveLength(1);
841
+ expect(events[0].after).toEqual({itemId: "pk-123", securityAction: "password-changed"});
842
+ });
843
+ });
844
+
845
+ describe("startup", () => {
846
+ it("throws when AuditApp is not registered", () => {
847
+ expect(() => buildApp({auditApp: false})).toThrow("AccountSecurityApp requires AuditApp");
848
+ });
849
+
850
+ it("boots without AuditApp when audit: false is passed, and records nothing", async () => {
851
+ const {app} = buildApp({auditApp: false, security: {audit: false}});
852
+ const operator = await signUp(app, "operator-unaudited", ["operator"]);
853
+ const targetEmail = uniqueEmail("unaudited-target");
854
+ await enrollTwoFactor(app, targetEmail);
855
+ const targetId = await appUserId(targetEmail);
856
+
857
+ const reset = await resetTwoFactor(app, operator.token, targetId);
858
+
859
+ expect(reset.status).toBe(200);
860
+ expect(reset.body.data.changed).toBe(true);
861
+ expect(await securityEventsFor(targetId)).toHaveLength(0);
862
+ });
863
+
864
+ it("throws when a custom action reuses an action id", () => {
865
+ expect(
866
+ () =>
867
+ new AccountSecurityApp({
868
+ actions: [{...resetTwoFactorAction, path: "/another-reset"}],
869
+ audit: false,
870
+ })
871
+ ).toThrow("Duplicate security action id");
872
+ });
873
+
874
+ it("throws without a user model", () => {
875
+ const security = new AccountSecurityApp({audit: false});
876
+ expect(() => security.register(express())).toThrow("AccountSecurityApp requires a userModel");
877
+ });
878
+ });
879
+ });
880
+
881
+ describe("storesTrustDeviceIdentifiersPlain", () => {
882
+ it("matches Better Auth's verification identifier storage rules", () => {
883
+ expect(storesTrustDeviceIdentifiersPlain(undefined)).toBe(true);
884
+ expect(storesTrustDeviceIdentifiersPlain("plain")).toBe(true);
885
+ expect(storesTrustDeviceIdentifiersPlain("hashed")).toBe(false);
886
+ expect(storesTrustDeviceIdentifiersPlain({default: "hashed"})).toBe(false);
887
+ expect(storesTrustDeviceIdentifiersPlain({default: "plain"})).toBe(true);
888
+ expect(
889
+ storesTrustDeviceIdentifiersPlain({default: "hashed", overrides: {"trust-device-": "plain"}})
890
+ ).toBe(true);
891
+ expect(
892
+ storesTrustDeviceIdentifiersPlain({default: "plain", overrides: {trust: "hashed"}})
893
+ ).toBe(false);
894
+ expect(
895
+ storesTrustDeviceIdentifiersPlain({default: "plain", overrides: {"reset-password": "hashed"}})
896
+ ).toBe(true);
897
+ });
898
+ });
899
+
900
+ describe("recordSecurityAction", () => {
901
+ beforeEach(async () => {
902
+ clearSecurityActionListenersForTests();
903
+ resetAuditRecorderForTests();
904
+ await AuditEvent.deleteMany({});
905
+ });
906
+
907
+ afterEach(() => {
908
+ resetAuditRecorderForTests();
909
+ clearSecurityActionListenersForTests();
910
+ });
911
+
912
+ it("records the org on the event and keeps going when a listener fails", async () => {
913
+ new AuditApp().register(express());
914
+ const received: SecurityActionEvent[] = [];
915
+ onSecurityAction(() => {
916
+ throw new Error("listener exploded");
917
+ });
918
+ onSecurityAction(async () => {
919
+ throw new Error("async listener exploded");
920
+ });
921
+ const unsubscribe = onSecurityAction((event) => {
922
+ received.push(event);
923
+ });
924
+ const actorId = new mongoose.Types.ObjectId().toString();
925
+ const targetId = new mongoose.Types.ObjectId().toString();
926
+
927
+ await recordSecurityAction({
928
+ action: "two-factor-enabled",
929
+ actor: {id: actorId},
930
+ org: {id: "org-7", name: "Org Seven"},
931
+ target: {id: targetId},
932
+ });
933
+
934
+ expect(received).toHaveLength(1);
935
+ expect(received[0]).toMatchObject({org: {id: "org-7"}, origin: "self"});
936
+ const event = await AuditEvent.findOne({recordId: targetId}).lean();
937
+ expect(event).toMatchObject({
938
+ after: {organizationId: "org-7", securityAction: "two-factor-enabled"},
939
+ organizationId: "org-7",
940
+ source: "security",
941
+ });
942
+
943
+ unsubscribe();
944
+ await recordSecurityAction({action: "password-changed", target: {id: targetId}});
945
+ expect(received).toHaveLength(1);
946
+ });
947
+ });