@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,1323 @@
1
+ import {afterEach, beforeAll, beforeEach, describe, expect, it, mock, spyOn} from "bun:test";
2
+ import type express from "express";
3
+ import {DateTime, Duration} from "luxon";
4
+ import supertest from "supertest";
5
+
6
+ import {resetAuditRecorderForTests} from "../audit/record";
7
+ import type {BetterAuthConfig} from "../betterAuth";
8
+ import type {BetterAuthApp} from "../betterAuthApp";
9
+ import {logger} from "../logger";
10
+ import {
11
+ access,
12
+ betterAuthCollection,
13
+ betterAuthIdFor,
14
+ buildApp,
15
+ resetAccountSecurityState,
16
+ resetTokenFrom,
17
+ SecurityUser,
18
+ securityUserModel,
19
+ selfSecurityEventsFor,
20
+ signInWithPassword,
21
+ signUp,
22
+ } from "../tests/accountSecurityTestApp";
23
+ import {
24
+ API_ORIGIN,
25
+ PASSWORD,
26
+ setCookies,
27
+ stubGoogleIdTokenOptions,
28
+ totpCode,
29
+ totpSecretFromURI,
30
+ } from "../tests/betterAuthStubs";
31
+ import {createSoftwareAuthenticator} from "../tests/softwareAuthenticator";
32
+ import {
33
+ clearSecurityActionListenersForTests,
34
+ recordSecurityAction,
35
+ SECURITY_ACTIONS,
36
+ type SecurityActionEvent,
37
+ type SecurityActionId,
38
+ } from "./securityEvents";
39
+ import {
40
+ createSecurityNotificationListener,
41
+ DEFAULT_SECURITY_MAIL_TEMPLATES,
42
+ flushSecurityNotificationsForTests,
43
+ renderSecurityMail,
44
+ SECURITY_MAIL_TEMPLATE_IDS,
45
+ SECURITY_NOTIFICATION_TEMPLATES,
46
+ type SecurityNotificationsOptions,
47
+ } from "./securityNotifications";
48
+
49
+ const PUBLIC_APP_URL = "https://app.example.com";
50
+
51
+ const NEW_PASSWORD = "new-password-654321";
52
+
53
+ interface Mail {
54
+ html?: string;
55
+ subject: string;
56
+ text: string;
57
+ to: string;
58
+ }
59
+
60
+ const SECURITY_SUBJECTS = new Set(
61
+ Object.values(DEFAULT_SECURITY_MAIL_TEMPLATES).map((template) => template.subject)
62
+ );
63
+
64
+ interface MailingApp {
65
+ app: express.Application;
66
+ betterAuthApp: BetterAuthApp;
67
+ sent: Mail[];
68
+ }
69
+
70
+ /** An app with a capturing mailer and `publicAppUrl`, plus the given overrides. */
71
+ const buildMailingApp = ({
72
+ config = {},
73
+ notifications,
74
+ sendMail,
75
+ }: {
76
+ config?: Partial<BetterAuthConfig>;
77
+ notifications?: SecurityNotificationsOptions;
78
+ sendMail?: (message: Mail) => Promise<void>;
79
+ } = {}): MailingApp => {
80
+ const sent: Mail[] = [];
81
+ const {app, betterAuthApp} = buildApp({
82
+ config: {
83
+ publicAppUrl: PUBLIC_APP_URL,
84
+ sendMail:
85
+ sendMail ??
86
+ (async (message): Promise<void> => {
87
+ sent.push(message);
88
+ }),
89
+ ...config,
90
+ },
91
+ security: notifications ? {notifications} : {},
92
+ });
93
+ return {app, betterAuthApp, sent};
94
+ };
95
+
96
+ /** The security notifications delivered so far (not reset or verification mail). */
97
+ const notificationsIn = async (sent: Mail[], to?: string): Promise<Mail[]> => {
98
+ await flushSecurityNotificationsForTests();
99
+ return sent.filter(
100
+ (mail) => SECURITY_SUBJECTS.has(mail.subject) && (to === undefined || mail.to === to)
101
+ );
102
+ };
103
+
104
+ /** Waits for pending notifications from setup, then forgets every mail sent so far. */
105
+ const clearMail = async (sent: Mail[]): Promise<void> => {
106
+ await flushSecurityNotificationsForTests();
107
+ sent.length = 0;
108
+ };
109
+
110
+ const expectOneNotification = async (sent: Mail[], to: string, subject: string): Promise<Mail> => {
111
+ const all = await notificationsIn(sent);
112
+ expect(all.map((mail) => ({subject: mail.subject, to: mail.to}))).toEqual([{subject, to}]);
113
+ return all[0];
114
+ };
115
+
116
+ /** The self-service action ids recorded for the user, sorted. */
117
+ const selfActionsOf = async (userId: string): Promise<string[]> =>
118
+ (await selfSecurityEventsFor(userId))
119
+ .map((event) => (event.after as {securityAction: string}).securityAction)
120
+ .sort();
121
+
122
+ const runAction = (
123
+ app: express.Application,
124
+ token: string,
125
+ method: "delete" | "post",
126
+ path: string
127
+ ): supertest.Test => supertest(app)[method](path).set("authorization", `Bearer ${token}`).send({});
128
+
129
+ const betterAuthContext = async (
130
+ betterAuthApp: BetterAuthApp
131
+ ): Promise<Awaited<ReturnType<BetterAuthApp["ensureAuth"]>["$context"]>> =>
132
+ betterAuthApp.ensureAuth().$context;
133
+
134
+ /** Turns on 2FA through the user's own session; returns the new session token and secret. */
135
+ const enableTwoFactor = async (
136
+ app: express.Application,
137
+ token: string
138
+ ): Promise<{secret: Buffer; token: string}> => {
139
+ const bearer = `Bearer ${token}`;
140
+ const enable = await supertest(app)
141
+ .post("/api/auth/two-factor/enable")
142
+ .set("authorization", bearer)
143
+ .send({password: PASSWORD});
144
+ expect(enable.status).toBe(200);
145
+ const secret = totpSecretFromURI(enable.body.totpURI as string);
146
+ const verify = await supertest(app)
147
+ .post("/api/auth/two-factor/verify-totp")
148
+ .set("authorization", bearer)
149
+ .send({code: totpCode(secret)});
150
+ expect(verify.status).toBe(200);
151
+ // Enrolment replaces the session; the bearer plugin hands back the new token.
152
+ return {secret, token: String(verify.headers["set-auth-token"] ?? "")};
153
+ };
154
+
155
+ const addPasskeyRow = async (betterAuthApp: BetterAuthApp, userId: string): Promise<string> => {
156
+ const context = await betterAuthContext(betterAuthApp);
157
+ const row = await context.adapter.create<Record<string, unknown>, {id: string}>({
158
+ data: {
159
+ backedUp: false,
160
+ counter: 0,
161
+ credentialID: `credential-${userId}`,
162
+ deviceType: "singleDevice",
163
+ name: "Laptop",
164
+ publicKey: `public-key-${userId}`,
165
+ userId: await betterAuthIdFor(userId),
166
+ },
167
+ model: "passkey",
168
+ });
169
+ return String(row.id);
170
+ };
171
+
172
+ /** Registers a passkey with a software authenticator through the user's own session. */
173
+ const registerPasskey = async (app: express.Application, token: string): Promise<string> => {
174
+ const authenticator = createSoftwareAuthenticator({origin: API_ORIGIN, rpID: "localhost"});
175
+ const options = await supertest(app)
176
+ .get("/api/auth/passkey/generate-register-options")
177
+ .set("authorization", `Bearer ${token}`);
178
+ expect(options.status).toBe(200);
179
+ const registered = await supertest(app)
180
+ .post("/api/auth/passkey/verify-registration")
181
+ .set("authorization", `Bearer ${token}`)
182
+ .set(
183
+ "cookie",
184
+ setCookies(options)
185
+ .map((cookie) => cookie.split(";")[0])
186
+ .join("; ")
187
+ )
188
+ .send({name: "Laptop", response: authenticator.register(options.body)});
189
+ expect(registered.status).toBe(200);
190
+ return String(registered.body.id);
191
+ };
192
+
193
+ describe("security notification emails", () => {
194
+ beforeAll(async () => {
195
+ await access.roles.seedDefaults();
196
+ });
197
+
198
+ beforeEach(async () => {
199
+ await resetAccountSecurityState();
200
+ });
201
+
202
+ afterEach(async () => {
203
+ await flushSecurityNotificationsForTests();
204
+ // Restores every logger spy, even when a test failed before its own cleanup.
205
+ mock.restore();
206
+ resetAuditRecorderForTests();
207
+ clearSecurityActionListenersForTests();
208
+ });
209
+
210
+ describe("admin recovery actions", () => {
211
+ it("resetting 2FA emails the target once, naming an administrator and not the operator", async () => {
212
+ const {app, sent} = buildMailingApp();
213
+ const operator = await signUp(app, "operator", ["operator"]);
214
+ const target = await signUp(app, "target");
215
+ await enableTwoFactor(app, target.token);
216
+ await clearMail(sent);
217
+
218
+ const res = await runAction(
219
+ app,
220
+ operator.token,
221
+ "post",
222
+ `/users/${target.id}/security/reset-two-factor`
223
+ );
224
+
225
+ expect(res.status).toBe(200);
226
+ const mail = await expectOneNotification(
227
+ sent,
228
+ target.email,
229
+ "Two-step verification was turned off"
230
+ );
231
+ expect(mail.text).toContain("An administrator turned off two-step verification");
232
+ expect(mail.text).not.toContain(operator.email);
233
+ expect(mail.text).not.toContain("operator");
234
+ expect(mail.html).toContain("<p>An administrator turned off two-step verification");
235
+ // The admin reset is not mistaken for the user turning 2FA off themselves.
236
+ expect(await selfActionsOf(target.id)).toEqual(["two-factor-enabled"]);
237
+ });
238
+
239
+ it("removing a passkey emails the target once, without the passkey's name", async () => {
240
+ const {app, betterAuthApp, sent} = buildMailingApp();
241
+ const operator = await signUp(app, "operator", ["operator"]);
242
+ const target = await signUp(app, "target");
243
+ const passkeyId = await addPasskeyRow(betterAuthApp, target.id);
244
+ await clearMail(sent);
245
+
246
+ const res = await runAction(
247
+ app,
248
+ operator.token,
249
+ "delete",
250
+ `/users/${target.id}/security/passkeys/${passkeyId}`
251
+ );
252
+
253
+ expect(res.status).toBe(200);
254
+ const mail = await expectOneNotification(
255
+ sent,
256
+ target.email,
257
+ "A passkey was removed from your account"
258
+ );
259
+ expect(mail.text).toContain("An administrator removed a passkey");
260
+ expect(mail.text).not.toContain("Laptop");
261
+ expect(await selfActionsOf(target.id)).toEqual([]);
262
+ });
263
+
264
+ it("unlinking a provider emails the target once, naming the provider", async () => {
265
+ const {app, betterAuthApp, sent} = buildMailingApp();
266
+ const operator = await signUp(app, "operator", ["operator"]);
267
+ const target = await signUp(app, "target");
268
+ const context = await betterAuthContext(betterAuthApp);
269
+ await context.internalAdapter.createAccount({
270
+ accessToken: "google-access-token",
271
+ accountId: "google-account",
272
+ providerId: "google",
273
+ userId: await betterAuthIdFor(target.id),
274
+ });
275
+ await clearMail(sent);
276
+
277
+ const res = await runAction(
278
+ app,
279
+ operator.token,
280
+ "delete",
281
+ `/users/${target.id}/security/accounts/google`
282
+ );
283
+
284
+ expect(res.status).toBe(200);
285
+ const mail = await expectOneNotification(
286
+ sent,
287
+ target.email,
288
+ "A sign-in method was disconnected from your account"
289
+ );
290
+ expect(mail.text).toContain("An administrator disconnected Google from your account");
291
+ expect(mail.text).not.toContain("google-access-token");
292
+ // Only the test's own link setup; the admin unlink adds no self event.
293
+ expect(await selfActionsOf(target.id)).toEqual(["provider-linked"]);
294
+ });
295
+
296
+ it("signing the target out everywhere emails them once", async () => {
297
+ const {app, sent} = buildMailingApp();
298
+ const operator = await signUp(app, "operator", ["operator"]);
299
+ const target = await signUp(app, "target");
300
+ await clearMail(sent);
301
+
302
+ const res = await runAction(
303
+ app,
304
+ operator.token,
305
+ "post",
306
+ `/users/${target.id}/security/revoke-sessions`
307
+ );
308
+
309
+ expect(res.status).toBe(200);
310
+ const mail = await expectOneNotification(
311
+ sent,
312
+ target.email,
313
+ "You were signed out everywhere"
314
+ );
315
+ expect(mail.text).toContain("An administrator signed your account out of every device");
316
+ expect(await selfActionsOf(target.id)).toEqual([]);
317
+ });
318
+
319
+ it("disabling and enabling the account each email the target once", async () => {
320
+ const {app, sent} = buildMailingApp();
321
+ const operator = await signUp(app, "operator", ["operator"]);
322
+ const target = await signUp(app, "target");
323
+ await clearMail(sent);
324
+
325
+ const disable = await runAction(
326
+ app,
327
+ operator.token,
328
+ "post",
329
+ `/users/${target.id}/security/disable`
330
+ );
331
+ expect(disable.status).toBe(200);
332
+ await expectOneNotification(sent, target.email, "Your account was disabled");
333
+ await clearMail(sent);
334
+
335
+ const enable = await runAction(
336
+ app,
337
+ operator.token,
338
+ "post",
339
+ `/users/${target.id}/security/enable`
340
+ );
341
+ expect(enable.status).toBe(200);
342
+ const mail = await expectOneNotification(sent, target.email, "Your account was re-enabled");
343
+ expect(mail.text).toContain("An administrator re-enabled your account");
344
+ expect(await selfActionsOf(target.id)).toEqual([]);
345
+ });
346
+
347
+ it("sends only the reset email for send-password-reset, with no separate notification", async () => {
348
+ const {app, sent} = buildMailingApp();
349
+ const operator = await signUp(app, "operator", ["operator"]);
350
+ const target = await signUp(app, "target");
351
+ await clearMail(sent);
352
+
353
+ const res = await runAction(
354
+ app,
355
+ operator.token,
356
+ "post",
357
+ `/users/${target.id}/security/send-password-reset`
358
+ );
359
+
360
+ expect(res.status).toBe(200);
361
+ await flushSecurityNotificationsForTests();
362
+ expect(sent.map((mail) => ({subject: mail.subject, to: mail.to}))).toEqual([
363
+ {subject: "Reset your password", to: target.email},
364
+ ]);
365
+ });
366
+
367
+ it("sends nothing for a no-op action, which is not recorded", async () => {
368
+ const {app, sent} = buildMailingApp();
369
+ const operator = await signUp(app, "operator", ["operator"]);
370
+ const target = await signUp(app, "target");
371
+ await clearMail(sent);
372
+
373
+ const res = await runAction(
374
+ app,
375
+ operator.token,
376
+ "post",
377
+ `/users/${target.id}/security/enable`
378
+ );
379
+
380
+ expect(res.status).toBe(200);
381
+ expect(res.body.data.changed).toBe(false);
382
+ expect(await notificationsIn(sent)).toHaveLength(0);
383
+ });
384
+ });
385
+
386
+ describe("self-service changes", () => {
387
+ it("turning on 2FA emails the user once and records two-factor-enabled with the user as actor", async () => {
388
+ const {app, sent} = buildMailingApp();
389
+ const user = await signUp(app, "self-2fa");
390
+ await clearMail(sent);
391
+
392
+ await enableTwoFactor(app, user.token);
393
+
394
+ const mail = await expectOneNotification(
395
+ sent,
396
+ user.email,
397
+ "Two-step verification was turned on"
398
+ );
399
+ expect(mail.text).toContain("You turned on two-step verification");
400
+ const events = await selfSecurityEventsFor(user.id);
401
+ expect(events).toHaveLength(1);
402
+ expect(String(events[0].actorId)).toBe(user.id);
403
+ expect(events[0].after).toMatchObject({securityAction: "two-factor-enabled"});
404
+ });
405
+
406
+ it("does not record the 2FA step of a later sign-in", async () => {
407
+ const {app, sent} = buildMailingApp();
408
+ const user = await signUp(app, "self-2fa-sign-in");
409
+ const {secret} = await enableTwoFactor(app, user.token);
410
+ await clearMail(sent);
411
+
412
+ const signIn = await signInWithPassword(app, user.email);
413
+ expect(signIn.body.twoFactorRedirect).toBe(true);
414
+ const verify = await supertest(app)
415
+ .post("/api/auth/two-factor/verify-totp")
416
+ .set(
417
+ "cookie",
418
+ setCookies(signIn)
419
+ .map((cookie) => cookie.split(";")[0])
420
+ .join("; ")
421
+ )
422
+ .send({code: totpCode(secret)});
423
+
424
+ expect(verify.status).toBe(200);
425
+ expect(await notificationsIn(sent)).toHaveLength(0);
426
+ expect(await selfSecurityEventsFor(user.id)).toHaveLength(1);
427
+ });
428
+
429
+ it("turning off 2FA emails the user once", async () => {
430
+ const {app, sent} = buildMailingApp();
431
+ const user = await signUp(app, "self-2fa-off");
432
+ const {token} = await enableTwoFactor(app, user.token);
433
+ await clearMail(sent);
434
+
435
+ const res = await supertest(app)
436
+ .post("/api/auth/two-factor/disable")
437
+ .set("authorization", `Bearer ${token}`)
438
+ .send({password: PASSWORD});
439
+
440
+ expect(res.status).toBe(200);
441
+ const mail = await expectOneNotification(
442
+ sent,
443
+ user.email,
444
+ "Two-step verification was turned off"
445
+ );
446
+ expect(mail.text).toContain("You turned off two-step verification");
447
+ });
448
+
449
+ it("adding and removing a passkey each email the user once", async () => {
450
+ const {app, sent} = buildMailingApp();
451
+ const user = await signUp(app, "self-passkey");
452
+ await clearMail(sent);
453
+
454
+ const passkeyId = await registerPasskey(app, user.token);
455
+ await expectOneNotification(sent, user.email, "A passkey was added to your account");
456
+ await clearMail(sent);
457
+
458
+ const res = await supertest(app)
459
+ .post("/api/auth/passkey/delete-passkey")
460
+ .set("authorization", `Bearer ${user.token}`)
461
+ .send({id: passkeyId});
462
+
463
+ expect(res.status).toBe(200);
464
+ const mail = await expectOneNotification(
465
+ sent,
466
+ user.email,
467
+ "A passkey was removed from your account"
468
+ );
469
+ expect(mail.text).toContain("You removed a passkey");
470
+ const actions = (await selfSecurityEventsFor(user.id)).map(
471
+ (event) => (event.after as {securityAction: string}).securityAction
472
+ );
473
+ expect(actions.sort()).toEqual(["passkey-added", "passkey-removed"]);
474
+ });
475
+
476
+ it("linking and unlinking a provider each email the user once", async () => {
477
+ const email = `linker-${Date.now()}@example.com`;
478
+ const {app, betterAuthApp, sent} = buildMailingApp({
479
+ config: {
480
+ googleOAuth: {clientId: "google-client", clientSecret: "google-secret"},
481
+ options: stubGoogleIdTokenOptions({email, emailVerified: true, id: "google-sub-1"}),
482
+ },
483
+ });
484
+ const signUpRes = await supertest(app)
485
+ .post("/api/auth/sign-up/email")
486
+ .send({email, name: "Linker", password: PASSWORD});
487
+ expect(signUpRes.status).toBe(200);
488
+ const token = signUpRes.body.token as string;
489
+ await clearMail(sent);
490
+
491
+ const link = await supertest(app)
492
+ .post("/api/auth/link-social")
493
+ .set("authorization", `Bearer ${token}`)
494
+ .send({idToken: {token: "stub-id-token"}, provider: "google"});
495
+ expect(link.status).toBe(200);
496
+ const linked = await expectOneNotification(
497
+ sent,
498
+ email,
499
+ "A sign-in method was connected to your account"
500
+ );
501
+ expect(linked.text).toContain("You connected Google to your account");
502
+ await clearMail(sent);
503
+
504
+ const user = await SecurityUser.findOne({email});
505
+ const context = await betterAuthContext(betterAuthApp);
506
+ const accounts = await context.internalAdapter.findAccounts(String(user?.betterAuthId));
507
+ const google = accounts.find((account) => account.providerId === "google");
508
+ const unlink = await supertest(app)
509
+ .post("/api/auth/unlink-account")
510
+ .set("authorization", `Bearer ${token}`)
511
+ .send({accountId: google?.id});
512
+
513
+ expect(unlink.status).toBe(200);
514
+ const unlinked = await expectOneNotification(
515
+ sent,
516
+ email,
517
+ "A sign-in method was disconnected from your account"
518
+ );
519
+ expect(unlinked.text).toContain("You disconnected Google from your account");
520
+ });
521
+
522
+ it("detects turning 2FA off from the database, not a stale cookie-cached session", async () => {
523
+ const {app, sent} = buildMailingApp();
524
+ const user = await signUp(app, "stale-cache");
525
+ // A cookie sign-in caches the session user (twoFactorEnabled: false) in a cookie.
526
+ const signIn = await signInWithPassword(app, user.email);
527
+ expect(signIn.status).toBe(200);
528
+ const cookie = setCookies(signIn)
529
+ .map((entry) => entry.split(";")[0])
530
+ .join("; ");
531
+ expect(cookie).toContain("session_data=");
532
+ // 2FA is turned on elsewhere; the cached session still says it is off.
533
+ await betterAuthCollection("user").updateOne(
534
+ {email: user.email},
535
+ {$set: {twoFactorEnabled: true}}
536
+ );
537
+ await clearMail(sent);
538
+
539
+ const res = await supertest(app)
540
+ .post("/api/auth/two-factor/disable")
541
+ .set("cookie", cookie)
542
+ .send({password: PASSWORD});
543
+
544
+ expect(res.status).toBe(200);
545
+ await expectOneNotification(sent, user.email, "Two-step verification was turned off");
546
+ expect(await selfActionsOf(user.id)).toEqual(["two-factor-disabled"]);
547
+ });
548
+
549
+ it("sends nothing when /two-factor/disable changes nothing", async () => {
550
+ const {app, sent} = buildMailingApp();
551
+ const user = await signUp(app, "disable-noop");
552
+ await clearMail(sent);
553
+
554
+ const res = await supertest(app)
555
+ .post("/api/auth/two-factor/disable")
556
+ .set("authorization", `Bearer ${user.token}`)
557
+ .send({password: PASSWORD});
558
+
559
+ expect(res.status).toBe(200);
560
+ expect(await notificationsIn(sent)).toHaveLength(0);
561
+ expect(await selfActionsOf(user.id)).toEqual([]);
562
+ });
563
+
564
+ it("does not treat a first sign-in with Google as a link", async () => {
565
+ const email = `google-first-${Date.now()}@example.com`;
566
+ const {app, sent} = buildMailingApp({
567
+ config: {
568
+ googleOAuth: {clientId: "google-client", clientSecret: "google-secret"},
569
+ options: stubGoogleIdTokenOptions({email, emailVerified: true, id: "google-sub-2"}),
570
+ },
571
+ });
572
+
573
+ const signIn = await supertest(app)
574
+ .post("/api/auth/sign-in/social")
575
+ .send({idToken: {token: "stub-id-token"}, provider: "google"});
576
+
577
+ expect(signIn.status).toBe(200);
578
+ const user = await SecurityUser.findOne({email});
579
+ expect(user).toBeTruthy();
580
+ expect(await notificationsIn(sent)).toHaveLength(0);
581
+ expect(await selfActionsOf(String(user?._id))).toEqual([]);
582
+ });
583
+
584
+ it("emails once when an email user's Google sign-in links Google implicitly", async () => {
585
+ const email = `google-implicit-${Date.now()}@example.com`;
586
+ const {app, sent} = buildMailingApp({
587
+ config: {
588
+ googleOAuth: {clientId: "google-client", clientSecret: "google-secret"},
589
+ options: stubGoogleIdTokenOptions({email, emailVerified: true, id: "google-sub-3"}),
590
+ },
591
+ });
592
+ const signUpRes = await supertest(app)
593
+ .post("/api/auth/sign-up/email")
594
+ .send({email, name: "Implicit", password: PASSWORD});
595
+ expect(signUpRes.status).toBe(200);
596
+ await betterAuthCollection("user").updateOne({email}, {$set: {emailVerified: true}});
597
+ await clearMail(sent);
598
+
599
+ const signIn = await supertest(app)
600
+ .post("/api/auth/sign-in/social")
601
+ .send({idToken: {token: "stub-id-token"}, provider: "google"});
602
+
603
+ expect(signIn.status).toBe(200);
604
+ const mail = await expectOneNotification(
605
+ sent,
606
+ email,
607
+ "A sign-in method was connected to your account"
608
+ );
609
+ expect(mail.text).toContain("You connected Google to your account");
610
+ const user = await SecurityUser.findOne({email});
611
+ expect(await selfActionsOf(String(user?._id))).toEqual(["provider-linked"]);
612
+ });
613
+
614
+ it("does not treat a first sign-in method as a link", async () => {
615
+ const {app, sent} = buildMailingApp();
616
+ const user = await signUp(app, "first-method");
617
+
618
+ expect(await notificationsIn(sent)).toHaveLength(0);
619
+ expect(await selfSecurityEventsFor(user.id)).toHaveLength(0);
620
+ });
621
+
622
+ it("changing the password emails the user once; a failed change sends nothing", async () => {
623
+ const {app, sent} = buildMailingApp();
624
+ const user = await signUp(app, "self-password");
625
+ await clearMail(sent);
626
+
627
+ const wrong = await supertest(app)
628
+ .post("/api/auth/change-password")
629
+ .set("authorization", `Bearer ${user.token}`)
630
+ .send({currentPassword: "not-the-password-1", newPassword: NEW_PASSWORD});
631
+ expect(wrong.status).toBe(400);
632
+ expect(await notificationsIn(sent)).toHaveLength(0);
633
+
634
+ const res = await supertest(app)
635
+ .post("/api/auth/change-password")
636
+ .set("authorization", `Bearer ${user.token}`)
637
+ .send({currentPassword: PASSWORD, newPassword: NEW_PASSWORD});
638
+
639
+ expect(res.status).toBe(200);
640
+ const mail = await expectOneNotification(sent, user.email, "Your password was changed");
641
+ expect(mail.text).toContain("You changed the password for your account");
642
+ expect(mail.text).not.toContain(NEW_PASSWORD);
643
+ });
644
+
645
+ it("completing a password reset emails the user once, without the token", async () => {
646
+ const {app, sent} = buildMailingApp();
647
+ const user = await signUp(app, "self-reset");
648
+ await clearMail(sent);
649
+ const request = await supertest(app)
650
+ .post("/api/auth/request-password-reset")
651
+ .send({email: user.email});
652
+ expect(request.status).toBe(200);
653
+ const resetToken = resetTokenFrom(
654
+ sent.find((mail) => mail.subject === "Reset your password") as Mail
655
+ );
656
+ await clearMail(sent);
657
+
658
+ const res = await supertest(app)
659
+ .post("/api/auth/reset-password")
660
+ .send({newPassword: NEW_PASSWORD, token: resetToken});
661
+
662
+ expect(res.status).toBe(200);
663
+ const mail = await expectOneNotification(sent, user.email, "Your password was reset");
664
+ expect(mail.text).toContain("The password for your account was reset with a reset link");
665
+ expect(mail.text).not.toMatch(/^You /);
666
+ expect(mail.text).not.toContain(resetToken);
667
+ });
668
+
669
+ it("signing out other sessions emails the user once", async () => {
670
+ const {app, sent} = buildMailingApp();
671
+ const user = await signUp(app, "self-sessions");
672
+ await signInWithPassword(app, user.email);
673
+ await clearMail(sent);
674
+
675
+ const res = await supertest(app)
676
+ .post("/api/auth/revoke-other-sessions")
677
+ .set("authorization", `Bearer ${user.token}`)
678
+ .send({});
679
+
680
+ expect(res.status).toBe(200);
681
+ const mail = await expectOneNotification(
682
+ sent,
683
+ user.email,
684
+ "Your other sessions were signed out"
685
+ );
686
+ expect(mail.text).toContain("You signed your account out of every other device");
687
+ });
688
+ });
689
+
690
+ describe("every action", () => {
691
+ // Written out by hand, so a new action fails here until someone decides what it emails.
692
+ const EXPECTED_SUBJECTS: Record<SecurityActionId, string> = {
693
+ disable: "Your account was disabled",
694
+ enable: "Your account was re-enabled",
695
+ "issue-sign-in-link": "A sign-in link was created for your account",
696
+ "other-sessions-revoked": "Your other sessions were signed out",
697
+ "passkey-added": "A passkey was added to your account",
698
+ "passkey-removed": "A passkey was removed from your account",
699
+ "password-changed": "Your password was changed",
700
+ "password-reset": "Your password was reset",
701
+ "password-set": "A password was added to your account",
702
+ "provider-linked": "A sign-in method was connected to your account",
703
+ "provider-unlinked": "A sign-in method was disconnected from your account",
704
+ "remove-passkey": "A passkey was removed from your account",
705
+ "reset-two-factor": "Two-step verification was turned off",
706
+ "revoke-sessions": "You were signed out everywhere",
707
+ "send-password-reset": "silent",
708
+ "suspend-membership": "Your organization membership was suspended",
709
+ "two-factor-disabled": "Two-step verification was turned off",
710
+ "two-factor-enabled": "Two-step verification was turned on",
711
+ "unlink-provider": "A sign-in method was disconnected from your account",
712
+ };
713
+
714
+ it("covers every security action", () => {
715
+ expect(Object.keys(EXPECTED_SUBJECTS).sort()).toEqual(Object.keys(SECURITY_ACTIONS).sort());
716
+ expect(Object.keys(SECURITY_NOTIFICATION_TEMPLATES).sort()).toEqual(
717
+ Object.keys(SECURITY_ACTIONS).sort()
718
+ );
719
+ });
720
+
721
+ it.each(Object.keys(SECURITY_ACTIONS) as SecurityActionId[])(
722
+ "%s sends the expected email (or none) to the target",
723
+ async (action) => {
724
+ const expected = EXPECTED_SUBJECTS[action];
725
+ expect(expected).toBeDefined();
726
+ const {app, sent} = buildMailingApp();
727
+ const target = await signUp(app, "every-action");
728
+ await clearMail(sent);
729
+
730
+ void recordSecurityAction({
731
+ action,
732
+ actor: {id: target.id},
733
+ details: {providerId: "github"},
734
+ target: {id: target.id},
735
+ });
736
+
737
+ if (expected === "silent") {
738
+ expect(await notificationsIn(sent)).toHaveLength(0);
739
+ return;
740
+ }
741
+ await expectOneNotification(sent, target.email, expected);
742
+ }
743
+ );
744
+
745
+ it("tells the user an administrator created a sign-in link, without the link", async () => {
746
+ const {app, sent} = buildMailingApp();
747
+ const operator = await signUp(app, "operator");
748
+ const target = await signUp(app, "link-target");
749
+ await clearMail(sent);
750
+
751
+ void recordSecurityAction({
752
+ action: "issue-sign-in-link",
753
+ actor: {id: operator.id},
754
+ details: {expiresAt: "2026-10-30T00:00:00.000Z"},
755
+ target: {id: target.id},
756
+ });
757
+
758
+ const mail = await expectOneNotification(
759
+ sent,
760
+ target.email,
761
+ "A sign-in link was created for your account"
762
+ );
763
+ expect(mail.text).toContain("An administrator created a sign-in link for your account");
764
+ expect(mail.text).not.toContain("token=");
765
+ expect(mail.text).not.toContain("resetPassword");
766
+ });
767
+ });
768
+
769
+ describe("org name", () => {
770
+ const org = {id: "org-1", name: "Acme <Clinic>"};
771
+
772
+ it("leaves the org name out by default", async () => {
773
+ const {app, sent} = buildMailingApp();
774
+ const operator = await signUp(app, "operator");
775
+ const target = await signUp(app, "member");
776
+ await clearMail(sent);
777
+
778
+ void recordSecurityAction({
779
+ action: "remove-passkey",
780
+ actor: {id: operator.id},
781
+ org,
782
+ target: {id: target.id},
783
+ });
784
+
785
+ const mail = await expectOneNotification(
786
+ sent,
787
+ target.email,
788
+ "A passkey was removed from your account"
789
+ );
790
+ expect(mail.text).toContain("An administrator removed a passkey from your account");
791
+ expect(mail.text).not.toContain("Acme");
792
+ expect(mail.html).not.toContain("Acme");
793
+ });
794
+
795
+ it("names the org with includeOrgName, HTML-escaped in the HTML body", async () => {
796
+ const {app, sent} = buildMailingApp({notifications: {includeOrgName: true}});
797
+ const operator = await signUp(app, "operator");
798
+ const target = await signUp(app, "member");
799
+ await clearMail(sent);
800
+
801
+ void recordSecurityAction({
802
+ action: "remove-passkey",
803
+ actor: {id: operator.id},
804
+ org,
805
+ target: {id: target.id},
806
+ });
807
+
808
+ const mail = await expectOneNotification(
809
+ sent,
810
+ target.email,
811
+ "A passkey was removed from your account"
812
+ );
813
+ expect(mail.text).toContain("An administrator at Acme <Clinic> removed a passkey");
814
+ expect(mail.html).toContain("An administrator at Acme &lt;Clinic&gt; removed a passkey");
815
+ });
816
+
817
+ it("says which org suspended the membership only with includeOrgName", async () => {
818
+ const named = buildMailingApp({notifications: {includeOrgName: true}});
819
+ const target = await signUp(named.app, "suspended");
820
+ await clearMail(named.sent);
821
+
822
+ void recordSecurityAction({
823
+ action: "suspend-membership",
824
+ actor: {id: target.id},
825
+ org: {id: "org-2", name: "Acme Clinic"},
826
+ target: {id: target.id},
827
+ });
828
+
829
+ const mail = await expectOneNotification(
830
+ named.sent,
831
+ target.email,
832
+ "Your organization membership was suspended"
833
+ );
834
+ expect(mail.text).toContain("An administrator suspended your membership in Acme Clinic");
835
+
836
+ const unnamed = renderSecurityMail({
837
+ data: {actor: "An administrator", orgReference: "an organization"},
838
+ templateId: "securityMembershipSuspended",
839
+ });
840
+ expect(unnamed.text).toContain("suspended your membership in an organization");
841
+ });
842
+
843
+ it("never names an org on the user's own changes", async () => {
844
+ const {app, sent} = buildMailingApp({notifications: {includeOrgName: true}});
845
+ const user = await signUp(app, "self-org");
846
+ await clearMail(sent);
847
+
848
+ void recordSecurityAction({
849
+ action: "password-changed",
850
+ actor: {id: user.id},
851
+ org,
852
+ target: {id: user.id},
853
+ });
854
+
855
+ const mail = await expectOneNotification(sent, user.email, "Your password was changed");
856
+ expect(mail.text).toContain("You changed the password");
857
+ expect(mail.text).not.toContain("Acme");
858
+ });
859
+ });
860
+
861
+ describe("delivery rules", () => {
862
+ it("sends nothing, renders nothing, and logs no error when sendMail is unset", async () => {
863
+ const errorSpy = spyOn(logger, "error");
864
+ const render = mock(renderSecurityMail);
865
+ const {app} = buildApp({security: {notifications: {render}}});
866
+ const operator = await signUp(app, "operator", ["operator"]);
867
+ const target = await signUp(app, "target");
868
+
869
+ const res = await runAction(
870
+ app,
871
+ operator.token,
872
+ "post",
873
+ `/users/${target.id}/security/revoke-sessions`
874
+ );
875
+
876
+ expect(res.status).toBe(200);
877
+ await flushSecurityNotificationsForTests();
878
+ expect(render).not.toHaveBeenCalled();
879
+ expect(
880
+ errorSpy.mock.calls.filter((call) => String(call[0]).includes("Security notification"))
881
+ ).toHaveLength(0);
882
+
883
+ // The same action with a mailer renders and sends, so the check above is meaningful.
884
+ const sendMail = mock(async (_message: Mail): Promise<void> => {});
885
+ const mailing = buildApp({
886
+ config: {sendMail},
887
+ security: {notifications: {render}},
888
+ });
889
+ const operatorToken = (await signInWithPassword(mailing.app, operator.email)).body
890
+ .token as string;
891
+ await runAction(
892
+ mailing.app,
893
+ operatorToken,
894
+ "post",
895
+ `/users/${target.id}/security/revoke-sessions`
896
+ );
897
+ await flushSecurityNotificationsForTests();
898
+ expect(render).toHaveBeenCalledTimes(1);
899
+ expect(sendMail.mock.calls.map(([message]) => message.to)).toEqual([target.email]);
900
+ });
901
+
902
+ it("sends nothing with notifications.enabled false, leaving reset mail alone", async () => {
903
+ const {app, sent} = buildMailingApp({notifications: {enabled: false}});
904
+ const operator = await signUp(app, "operator", ["operator"]);
905
+ const target = await signUp(app, "target");
906
+ await clearMail(sent);
907
+
908
+ await runAction(app, operator.token, "post", `/users/${target.id}/security/revoke-sessions`);
909
+ await runAction(
910
+ app,
911
+ operator.token,
912
+ "post",
913
+ `/users/${target.id}/security/send-password-reset`
914
+ );
915
+
916
+ expect(await notificationsIn(sent)).toHaveLength(0);
917
+ expect(sent.map((mail) => mail.subject)).toEqual(["Reset your password"]);
918
+ });
919
+
920
+ it("stops emailing after unsubscribeNotifications", async () => {
921
+ const sent: Mail[] = [];
922
+ const {accountSecurityApp, app} = buildApp({
923
+ config: {
924
+ publicAppUrl: PUBLIC_APP_URL,
925
+ sendMail: async (message): Promise<void> => {
926
+ sent.push(message);
927
+ },
928
+ },
929
+ });
930
+ const user = await signUp(app, "unsubscribed");
931
+ await clearMail(sent);
932
+
933
+ accountSecurityApp?.unsubscribeNotifications();
934
+ void recordSecurityAction({
935
+ action: "password-changed",
936
+ actor: {id: user.id},
937
+ target: {id: user.id},
938
+ });
939
+
940
+ expect(await notificationsIn(sent)).toHaveLength(0);
941
+ });
942
+
943
+ it("uses notifications.sendMail when it is set", async () => {
944
+ const own: Mail[] = [];
945
+ const {app, sent} = buildMailingApp({
946
+ notifications: {
947
+ sendMail: async (message): Promise<void> => {
948
+ own.push(message);
949
+ },
950
+ },
951
+ });
952
+ const operator = await signUp(app, "operator", ["operator"]);
953
+ const target = await signUp(app, "target");
954
+ await clearMail(sent);
955
+
956
+ await runAction(app, operator.token, "post", `/users/${target.id}/security/revoke-sessions`);
957
+
958
+ expect(await notificationsIn(sent)).toHaveLength(0);
959
+ expect((await notificationsIn(own)).map((mail) => mail.to)).toEqual([target.email]);
960
+ });
961
+
962
+ it("skips a user with no email", async () => {
963
+ const {app, sent} = buildMailingApp();
964
+ const operator = await signUp(app, "operator", ["operator"]);
965
+ const target = await signUp(app, "target");
966
+ await SecurityUser.collection.updateOne(
967
+ {_id: (await SecurityUser.findById(target.id))?._id},
968
+ {$set: {email: ""}}
969
+ );
970
+ await clearMail(sent);
971
+
972
+ const res = await runAction(
973
+ app,
974
+ operator.token,
975
+ "post",
976
+ `/users/${target.id}/security/revoke-sessions`
977
+ );
978
+
979
+ expect(res.status).toBe(200);
980
+ expect(await notificationsIn(sent)).toHaveLength(0);
981
+ });
982
+
983
+ it("logs a failed delivery without the address and still completes the action", async () => {
984
+ const errorSpy = spyOn(logger, "error");
985
+ let isFailing = false;
986
+ const {app} = buildMailingApp({
987
+ sendMail: async (): Promise<void> => {
988
+ if (isFailing) {
989
+ throw new Error("SMTP down");
990
+ }
991
+ },
992
+ });
993
+ const operator = await signUp(app, "operator", ["operator"]);
994
+ const target = await signUp(app, "target");
995
+ isFailing = true;
996
+
997
+ const res = await runAction(
998
+ app,
999
+ operator.token,
1000
+ "post",
1001
+ `/users/${target.id}/security/revoke-sessions`
1002
+ );
1003
+
1004
+ expect(res.status).toBe(200);
1005
+ await flushSecurityNotificationsForTests();
1006
+ const failures = errorSpy.mock.calls
1007
+ .map((call) => String(call[0]))
1008
+ .filter((message) => message.includes("Security notification failed"));
1009
+ expect(failures).toHaveLength(1);
1010
+ expect(failures[0]).toContain("action=revoke-sessions");
1011
+ expect(failures[0]).toContain(`userId=${target.id}`);
1012
+ expect(failures[0]).not.toContain(target.email);
1013
+ });
1014
+
1015
+ it("points to publicAppUrl when set, and only to support without it", async () => {
1016
+ const withUrl = buildMailingApp();
1017
+ const user = await signUp(withUrl.app, "with-url");
1018
+ await clearMail(withUrl.sent);
1019
+ void recordSecurityAction({
1020
+ action: "password-changed",
1021
+ actor: {id: user.id},
1022
+ target: {id: user.id},
1023
+ });
1024
+ const linked = await expectOneNotification(
1025
+ withUrl.sent,
1026
+ user.email,
1027
+ "Your password was changed"
1028
+ );
1029
+ expect(linked.text).toContain(
1030
+ `contact support right away. You can review your account security at ${PUBLIC_APP_URL}.`
1031
+ );
1032
+ clearSecurityActionListenersForTests();
1033
+
1034
+ const withoutUrl = buildMailingApp({config: {publicAppUrl: undefined}});
1035
+ await clearMail(withoutUrl.sent);
1036
+ void recordSecurityAction({
1037
+ action: "password-changed",
1038
+ actor: {id: user.id},
1039
+ target: {id: user.id},
1040
+ });
1041
+ const bare = await expectOneNotification(
1042
+ withoutUrl.sent,
1043
+ user.email,
1044
+ "Your password was changed"
1045
+ );
1046
+ expect(bare.text).toContain("If you did not expect this change, contact support right away.");
1047
+ expect(bare.text).not.toContain("http");
1048
+ });
1049
+
1050
+ it("renders with notifications.render and authMailTemplates when the app opts in", async () => {
1051
+ const calls: string[] = [];
1052
+ const {app, sent} = buildMailingApp({
1053
+ config: {
1054
+ authMailTemplates: {
1055
+ securityPasswordChanged: {
1056
+ subject: "Custom: {{actor}} changed it",
1057
+ text: "{{occurredAt}}",
1058
+ },
1059
+ },
1060
+ },
1061
+ notifications: {
1062
+ render: (options) => {
1063
+ calls.push(options.templateId);
1064
+ const rendered = renderSecurityMail(options);
1065
+ return {...rendered, subject: `[App] ${rendered.subject}`};
1066
+ },
1067
+ },
1068
+ });
1069
+ const user = await signUp(app, "custom-render");
1070
+ await clearMail(sent);
1071
+
1072
+ void recordSecurityAction({
1073
+ action: "password-changed",
1074
+ actor: {id: user.id},
1075
+ target: {id: user.id},
1076
+ });
1077
+
1078
+ await flushSecurityNotificationsForTests();
1079
+ expect(calls).toEqual(["securityPasswordChanged"]);
1080
+ expect(sent.map((mail) => mail.subject)).toEqual(["[App] Custom: You changed it"]);
1081
+ });
1082
+
1083
+ it("never passes security ids to an old-style BetterAuthConfig.renderAuthMail", async () => {
1084
+ const calls: string[] = [];
1085
+ const {app, sent} = buildMailingApp({
1086
+ config: {
1087
+ // Written for two ids: anything but resetPassword gets the verify mail.
1088
+ renderAuthMail: ({templateId, token}) => {
1089
+ calls.push(templateId);
1090
+ return templateId === "resetPassword"
1091
+ ? {subject: "Reset your password", text: `reset ${token}`}
1092
+ : {subject: "Verify your email", text: `verify ${token}`};
1093
+ },
1094
+ },
1095
+ });
1096
+ const user = await signUp(app, "old-renderer");
1097
+ await clearMail(sent);
1098
+ calls.length = 0;
1099
+
1100
+ void recordSecurityAction({
1101
+ action: "password-changed",
1102
+ actor: {id: user.id},
1103
+ target: {id: user.id},
1104
+ });
1105
+
1106
+ await expectOneNotification(sent, user.email, "Your password was changed");
1107
+ expect(calls).toEqual([]);
1108
+ expect(sent.map((mail) => mail.subject)).toEqual(["Your password was changed"]);
1109
+ });
1110
+
1111
+ it("falls back to the built-in templates when notifications.render throws", async () => {
1112
+ const warnSpy = spyOn(logger, "warn");
1113
+ const {app, sent} = buildMailingApp({
1114
+ notifications: {
1115
+ render: () => {
1116
+ throw new Error("unknown template");
1117
+ },
1118
+ },
1119
+ });
1120
+ const user = await signUp(app, "throwing-render");
1121
+ await clearMail(sent);
1122
+
1123
+ void recordSecurityAction({
1124
+ action: "password-changed",
1125
+ actor: {id: user.id},
1126
+ target: {id: user.id},
1127
+ });
1128
+
1129
+ await expectOneNotification(sent, user.email, "Your password was changed");
1130
+ expect(warnSpy.mock.calls.some((call) => String(call[0]).includes("could not render"))).toBe(
1131
+ true
1132
+ );
1133
+ });
1134
+
1135
+ it("emails once when two apps register AccountSecurityApp: the newest owns the emails", async () => {
1136
+ const first = buildMailingApp();
1137
+ const second = buildMailingApp();
1138
+ const user = await signUp(second.app, "two-apps");
1139
+ await clearMail(first.sent);
1140
+ await clearMail(second.sent);
1141
+
1142
+ void recordSecurityAction({
1143
+ action: "password-changed",
1144
+ actor: {id: user.id},
1145
+ target: {id: user.id},
1146
+ });
1147
+
1148
+ expect(await notificationsIn(first.sent)).toHaveLength(0);
1149
+ await expectOneNotification(second.sent, user.email, "Your password was changed");
1150
+ });
1151
+
1152
+ it("collapses repeats of one change into one email per throttle window", async () => {
1153
+ const {app, sent} = buildMailingApp();
1154
+ const user = await signUp(app, "repeat-sessions");
1155
+ await clearMail(sent);
1156
+
1157
+ for (let attempt = 0; attempt < 3; attempt += 1) {
1158
+ await signInWithPassword(app, user.email);
1159
+ const res = await supertest(app)
1160
+ .post("/api/auth/revoke-other-sessions")
1161
+ .set("authorization", `Bearer ${user.token}`)
1162
+ .send({});
1163
+ expect(res.status).toBe(200);
1164
+ }
1165
+
1166
+ await expectOneNotification(sent, user.email, "Your other sessions were signed out");
1167
+ // Every change is still in the audit log.
1168
+ expect(await selfActionsOf(user.id)).toEqual([
1169
+ "other-sessions-revoked",
1170
+ "other-sessions-revoked",
1171
+ "other-sessions-revoked",
1172
+ ]);
1173
+ });
1174
+
1175
+ it("never lets the user's own change swallow an administrator's email about the same thing", async () => {
1176
+ const {app, sent} = buildMailingApp();
1177
+ const operator = await signUp(app, "operator");
1178
+ const target = await signUp(app, "target");
1179
+ await clearMail(sent);
1180
+
1181
+ void recordSecurityAction({
1182
+ action: "passkey-removed",
1183
+ actor: {id: target.id},
1184
+ target: {id: target.id},
1185
+ });
1186
+ void recordSecurityAction({
1187
+ action: "remove-passkey",
1188
+ actor: {id: operator.id},
1189
+ target: {id: target.id},
1190
+ });
1191
+
1192
+ const mails = await notificationsIn(sent, target.email);
1193
+ expect(mails.map((mail) => mail.subject)).toEqual([
1194
+ "A passkey was removed from your account",
1195
+ "A passkey was removed from your account",
1196
+ ]);
1197
+ expect(mails.map((mail) => mail.text.split(" removed")[0]).sort()).toEqual([
1198
+ "An administrator",
1199
+ "You",
1200
+ ]);
1201
+ });
1202
+
1203
+ it("emails once per org when admins of two orgs act on the same member", async () => {
1204
+ const {app, sent} = buildMailingApp();
1205
+ const operator = await signUp(app, "operator");
1206
+ const target = await signUp(app, "member");
1207
+ await clearMail(sent);
1208
+
1209
+ for (const org of [{id: "org-a"}, {id: "org-b"}, {id: "org-a"}]) {
1210
+ void recordSecurityAction({
1211
+ action: "reset-two-factor",
1212
+ actor: {id: operator.id},
1213
+ org,
1214
+ target: {id: target.id},
1215
+ });
1216
+ }
1217
+
1218
+ const mails = await notificationsIn(sent, target.email);
1219
+ expect(mails).toHaveLength(2);
1220
+ expect(mails.every((mail) => mail.text.startsWith("An administrator"))).toBe(true);
1221
+ });
1222
+
1223
+ it("prunes throttle entries once their window has passed", async () => {
1224
+ const sentTo: string[] = [];
1225
+ let clock = DateTime.fromISO("2026-10-23T12:00:00Z").toMillis();
1226
+ const listener = createSecurityNotificationListener({
1227
+ getMailConfig: () => ({
1228
+ sendMail: async (message): Promise<void> => {
1229
+ sentTo.push(message.to);
1230
+ },
1231
+ }),
1232
+ getUserModel: () => securityUserModel,
1233
+ now: () => clock,
1234
+ throttleMinutes: 10,
1235
+ });
1236
+ const {app} = buildApp();
1237
+ const [first, second, third] = [
1238
+ await signUp(app, "prune-a"),
1239
+ await signUp(app, "prune-b"),
1240
+ await signUp(app, "prune-c"),
1241
+ ];
1242
+ const eventFor = (userId: string): SecurityActionEvent => ({
1243
+ action: "password-changed",
1244
+ actor: {id: userId},
1245
+ occurredAt: DateTime.fromMillis(clock).toISO() ?? "",
1246
+ origin: "self",
1247
+ target: {id: userId},
1248
+ });
1249
+
1250
+ await listener(eventFor(first.id));
1251
+ clock += Duration.fromObject({minutes: 5}).toMillis();
1252
+ await listener(eventFor(second.id));
1253
+ await listener(eventFor(first.id));
1254
+ expect(listener.throttleEntryCount()).toBe(2);
1255
+ expect(sentTo).toEqual([first.email, second.email]);
1256
+
1257
+ clock += Duration.fromObject({minutes: 6}).toMillis();
1258
+ await listener(eventFor(third.id));
1259
+
1260
+ // The first user's entry (11 minutes old) is gone; the second's (6 minutes) stays.
1261
+ expect(listener.throttleEntryCount()).toBe(2);
1262
+ await listener(eventFor(first.id));
1263
+ expect(sentTo).toEqual([first.email, second.email, third.email, first.email]);
1264
+ });
1265
+
1266
+ it("throttles per user and template, and throttleMinutes 0 sends every one", async () => {
1267
+ const throttled = buildMailingApp();
1268
+ const user = await signUp(throttled.app, "throttle-keys");
1269
+ const other = await signUp(throttled.app, "throttle-other");
1270
+ await clearMail(throttled.sent);
1271
+ for (const action of ["password-changed", "password-changed", "passkey-added"] as const) {
1272
+ void recordSecurityAction({action, actor: {id: user.id}, target: {id: user.id}});
1273
+ }
1274
+ void recordSecurityAction({
1275
+ action: "password-changed",
1276
+ actor: {id: other.id},
1277
+ target: {id: other.id},
1278
+ });
1279
+ expect(
1280
+ (await notificationsIn(throttled.sent)).map((mail) => `${mail.to} ${mail.subject}`).sort()
1281
+ ).toEqual(
1282
+ [
1283
+ `${other.email} Your password was changed`,
1284
+ `${user.email} A passkey was added to your account`,
1285
+ `${user.email} Your password was changed`,
1286
+ ].sort()
1287
+ );
1288
+
1289
+ const unthrottled = buildMailingApp({notifications: {throttleMinutes: 0}});
1290
+ for (let attempt = 0; attempt < 2; attempt += 1) {
1291
+ void recordSecurityAction({
1292
+ action: "password-changed",
1293
+ actor: {id: user.id},
1294
+ target: {id: user.id},
1295
+ });
1296
+ }
1297
+ expect(await notificationsIn(unthrottled.sent)).toHaveLength(2);
1298
+ });
1299
+ });
1300
+
1301
+ describe("templates", () => {
1302
+ it.each([...SECURITY_MAIL_TEMPLATE_IDS])("%s renders subject, text, and html", (templateId) => {
1303
+ const rendered = renderSecurityMail({
1304
+ data: {
1305
+ actor: "You",
1306
+ appUrl: PUBLIC_APP_URL,
1307
+ occurredAt: "October 23, 2026 at 14:05 UTC",
1308
+ orgClause: "",
1309
+ orgReference: "an organization",
1310
+ providerName: "Google",
1311
+ secureAccountLine: "If you did not expect this change, contact support right away.",
1312
+ },
1313
+ templateId,
1314
+ });
1315
+ expect(rendered.subject.length).toBeGreaterThan(0);
1316
+ expect(rendered.text).toContain("October 23, 2026 at 14:05 UTC");
1317
+ expect(rendered.text).toContain("contact support");
1318
+ expect(rendered.text).not.toContain("{{");
1319
+ expect(rendered.html).toContain("<p>");
1320
+ expect(rendered.html).not.toContain("{{");
1321
+ });
1322
+ });
1323
+ });