@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,516 @@
1
+ /**
2
+ * Security notification emails: one email to the affected user for every recorded security
3
+ * action, whether an administrator ran it or the user did.
4
+ *
5
+ * HIPAA posture: the emails are generic. They name the change and who made it ("you" or "an
6
+ * administrator", never the admin's name or email), never include tokens, links that sign in,
7
+ * passkey names, or other user-chosen text, and name the organization only when the app opts in
8
+ * with `notifications.includeOrgName` (on a shared inbox an org name can reveal care).
9
+ */
10
+
11
+ import {DateTime, Duration} from "luxon";
12
+
13
+ import type {User, UserModel} from "../auth";
14
+ import type {BetterAuthConfig} from "../betterAuth";
15
+ import {logger} from "../logger";
16
+ import {findOneOrNoneFor} from "../plugins";
17
+ import type {SecurityActionEvent, SecurityActionId} from "./securityEvents";
18
+
19
+ /** A mail template: `{{name}}` placeholders are filled from the render data. */
20
+ export interface SecurityMailTemplate {
21
+ html?: string;
22
+ subject: string;
23
+ text?: string;
24
+ }
25
+
26
+ /** The template ids security notifications render, one per kind of change. */
27
+ export const SECURITY_MAIL_TEMPLATE_IDS = [
28
+ "securityAccountDisabled",
29
+ "securityAccountEnabled",
30
+ "securityMembershipSuspended",
31
+ "securityOtherSessionsRevoked",
32
+ "securityPasskeyAdded",
33
+ "securityPasskeyRemoved",
34
+ "securityPasswordChanged",
35
+ "securityPasswordReset",
36
+ "securityPasswordSet",
37
+ "securityProviderLinked",
38
+ "securityProviderUnlinked",
39
+ "securitySessionsRevoked",
40
+ "securitySignInLinkIssued",
41
+ "securityTwoFactorDisabled",
42
+ "securityTwoFactorEnabled",
43
+ ] as const;
44
+
45
+ export type SecurityMailTemplateId = (typeof SECURITY_MAIL_TEMPLATE_IDS)[number];
46
+
47
+ const paragraphs = (...lines: string[]): string => lines.map((line) => `<p>${line}</p>`).join("");
48
+
49
+ /**
50
+ * The default notification templates. `@terreno/comms` `DEFAULT_AUTH_MAIL_TEMPLATES` includes
51
+ * them, so `renderAuthMail` renders them too. Data: `actor` ("You" / "An administrator"),
52
+ * `orgClause` ("" or " at {org}"), `orgReference` ("{org}" or "an organization"),
53
+ * `providerName`, `occurredAt`, `appUrl`, and `secureAccountLine`.
54
+ */
55
+ export const DEFAULT_SECURITY_MAIL_TEMPLATES: Record<SecurityMailTemplateId, SecurityMailTemplate> =
56
+ {
57
+ securityAccountDisabled: {
58
+ html: paragraphs(
59
+ "{{actor}}{{orgClause}} disabled your account on {{occurredAt}}. You can no longer sign in.",
60
+ "{{secureAccountLine}}"
61
+ ),
62
+ subject: "Your account was disabled",
63
+ text: "{{actor}}{{orgClause}} disabled your account on {{occurredAt}}. You can no longer sign in.\n\n{{secureAccountLine}}",
64
+ },
65
+ securityAccountEnabled: {
66
+ html: paragraphs(
67
+ "{{actor}}{{orgClause}} re-enabled your account on {{occurredAt}}. You can sign in again.",
68
+ "{{secureAccountLine}}"
69
+ ),
70
+ subject: "Your account was re-enabled",
71
+ text: "{{actor}}{{orgClause}} re-enabled your account on {{occurredAt}}. You can sign in again.\n\n{{secureAccountLine}}",
72
+ },
73
+ securityMembershipSuspended: {
74
+ html: paragraphs(
75
+ "{{actor}} suspended your membership in {{orgReference}} on {{occurredAt}}. You can still sign in.",
76
+ "{{secureAccountLine}}"
77
+ ),
78
+ subject: "Your organization membership was suspended",
79
+ text: "{{actor}} suspended your membership in {{orgReference}} on {{occurredAt}}. You can still sign in.\n\n{{secureAccountLine}}",
80
+ },
81
+ securityOtherSessionsRevoked: {
82
+ html: paragraphs(
83
+ "{{actor}}{{orgClause}} signed your account out of every other device on {{occurredAt}}.",
84
+ "{{secureAccountLine}}"
85
+ ),
86
+ subject: "Your other sessions were signed out",
87
+ text: "{{actor}}{{orgClause}} signed your account out of every other device on {{occurredAt}}.\n\n{{secureAccountLine}}",
88
+ },
89
+ securityPasskeyAdded: {
90
+ html: paragraphs(
91
+ "{{actor}}{{orgClause}} added a passkey to your account on {{occurredAt}}.",
92
+ "{{secureAccountLine}}"
93
+ ),
94
+ subject: "A passkey was added to your account",
95
+ text: "{{actor}}{{orgClause}} added a passkey to your account on {{occurredAt}}.\n\n{{secureAccountLine}}",
96
+ },
97
+ securityPasskeyRemoved: {
98
+ html: paragraphs(
99
+ "{{actor}}{{orgClause}} removed a passkey from your account on {{occurredAt}}.",
100
+ "{{secureAccountLine}}"
101
+ ),
102
+ subject: "A passkey was removed from your account",
103
+ text: "{{actor}}{{orgClause}} removed a passkey from your account on {{occurredAt}}.\n\n{{secureAccountLine}}",
104
+ },
105
+ securityPasswordChanged: {
106
+ html: paragraphs(
107
+ "{{actor}}{{orgClause}} changed the password for your account on {{occurredAt}}.",
108
+ "{{secureAccountLine}}"
109
+ ),
110
+ subject: "Your password was changed",
111
+ text: "{{actor}}{{orgClause}} changed the password for your account on {{occurredAt}}.\n\n{{secureAccountLine}}",
112
+ },
113
+ securityPasswordReset: {
114
+ html: paragraphs(
115
+ "The password for your account was reset with a reset link on {{occurredAt}}.",
116
+ "{{secureAccountLine}}"
117
+ ),
118
+ subject: "Your password was reset",
119
+ text: "The password for your account was reset with a reset link on {{occurredAt}}.\n\n{{secureAccountLine}}",
120
+ },
121
+ securityPasswordSet: {
122
+ html: paragraphs(
123
+ "{{actor}}{{orgClause}} added a password to your account on {{occurredAt}}. It can now be used to sign in.",
124
+ "{{secureAccountLine}}"
125
+ ),
126
+ subject: "A password was added to your account",
127
+ text: "{{actor}}{{orgClause}} added a password to your account on {{occurredAt}}. It can now be used to sign in.\n\n{{secureAccountLine}}",
128
+ },
129
+ securityProviderLinked: {
130
+ html: paragraphs(
131
+ "{{actor}}{{orgClause}} connected {{providerName}} to your account on {{occurredAt}}. It can now be used to sign in.",
132
+ "{{secureAccountLine}}"
133
+ ),
134
+ subject: "A sign-in method was connected to your account",
135
+ text: "{{actor}}{{orgClause}} connected {{providerName}} to your account on {{occurredAt}}. It can now be used to sign in.\n\n{{secureAccountLine}}",
136
+ },
137
+ securityProviderUnlinked: {
138
+ html: paragraphs(
139
+ "{{actor}}{{orgClause}} disconnected {{providerName}} from your account on {{occurredAt}}.",
140
+ "{{secureAccountLine}}"
141
+ ),
142
+ subject: "A sign-in method was disconnected from your account",
143
+ text: "{{actor}}{{orgClause}} disconnected {{providerName}} from your account on {{occurredAt}}.\n\n{{secureAccountLine}}",
144
+ },
145
+ securitySessionsRevoked: {
146
+ html: paragraphs(
147
+ "{{actor}}{{orgClause}} signed your account out of every device on {{occurredAt}}.",
148
+ "{{secureAccountLine}}"
149
+ ),
150
+ subject: "You were signed out everywhere",
151
+ text: "{{actor}}{{orgClause}} signed your account out of every device on {{occurredAt}}.\n\n{{secureAccountLine}}",
152
+ },
153
+ securitySignInLinkIssued: {
154
+ html: paragraphs(
155
+ "{{actor}}{{orgClause}} created a sign-in link for your account on {{occurredAt}}. The link was given to the administrator, not sent to you.",
156
+ "{{secureAccountLine}}"
157
+ ),
158
+ subject: "A sign-in link was created for your account",
159
+ text: "{{actor}}{{orgClause}} created a sign-in link for your account on {{occurredAt}}. The link was given to the administrator, not sent to you.\n\n{{secureAccountLine}}",
160
+ },
161
+ securityTwoFactorDisabled: {
162
+ html: paragraphs(
163
+ "{{actor}}{{orgClause}} turned off two-step verification for your account on {{occurredAt}}.",
164
+ "{{secureAccountLine}}"
165
+ ),
166
+ subject: "Two-step verification was turned off",
167
+ text: "{{actor}}{{orgClause}} turned off two-step verification for your account on {{occurredAt}}.\n\n{{secureAccountLine}}",
168
+ },
169
+ securityTwoFactorEnabled: {
170
+ html: paragraphs(
171
+ "{{actor}}{{orgClause}} turned on two-step verification for your account on {{occurredAt}}.",
172
+ "{{secureAccountLine}}"
173
+ ),
174
+ subject: "Two-step verification was turned on",
175
+ text: "{{actor}}{{orgClause}} turned on two-step verification for your account on {{occurredAt}}.\n\n{{secureAccountLine}}",
176
+ },
177
+ };
178
+
179
+ /**
180
+ * Which template each security action sends; every action is listed. `null` sends nothing:
181
+ * `send-password-reset`'s own reset email is the notice, and a second email would be noise.
182
+ * `issue-sign-in-link` emails the user (who always has an email; the action refuses users
183
+ * without one) that a link exists, never the link itself.
184
+ */
185
+ export const SECURITY_NOTIFICATION_TEMPLATES: Record<
186
+ SecurityActionId,
187
+ SecurityMailTemplateId | null
188
+ > = {
189
+ disable: "securityAccountDisabled",
190
+ enable: "securityAccountEnabled",
191
+ "issue-sign-in-link": "securitySignInLinkIssued",
192
+ "other-sessions-revoked": "securityOtherSessionsRevoked",
193
+ "passkey-added": "securityPasskeyAdded",
194
+ "passkey-removed": "securityPasskeyRemoved",
195
+ "password-changed": "securityPasswordChanged",
196
+ "password-reset": "securityPasswordReset",
197
+ "password-set": "securityPasswordSet",
198
+ "provider-linked": "securityProviderLinked",
199
+ "provider-unlinked": "securityProviderUnlinked",
200
+ "remove-passkey": "securityPasskeyRemoved",
201
+ "reset-two-factor": "securityTwoFactorDisabled",
202
+ "revoke-sessions": "securitySessionsRevoked",
203
+ "send-password-reset": null,
204
+ "suspend-membership": "securityMembershipSuspended",
205
+ "two-factor-disabled": "securityTwoFactorDisabled",
206
+ "two-factor-enabled": "securityTwoFactorEnabled",
207
+ "unlink-provider": "securityProviderUnlinked",
208
+ };
209
+
210
+ /** `notifications` on `AccountSecurityApp`. */
211
+ export interface SecurityNotificationsOptions {
212
+ /**
213
+ * Email the affected user about every security action. Defaults to `true`; nothing is sent
214
+ * while no `sendMail` is configured.
215
+ */
216
+ enabled?: boolean;
217
+ /**
218
+ * Name the organization in emails about actions an org-admin ran. Defaults to `false`: on a
219
+ * shared inbox the org name can reveal care.
220
+ */
221
+ includeOrgName?: boolean;
222
+ /**
223
+ * Renders the emails instead of the built-in renderer, for example `@terreno/comms`
224
+ * `renderAuthMail`. Not read from `BetterAuthConfig.renderAuthMail`: a renderer written only
225
+ * for reset and verify mail would answer every security id with one of those. Falls back to
226
+ * the built-in renderer when it throws or returns no subject.
227
+ */
228
+ render?: SecurityMailRenderer;
229
+ /**
230
+ * Send at most one email per user and template in this many minutes, so a burst of the same
231
+ * change (say, signing out other sessions five times) is one email. Defaults to 10; `0` sends
232
+ * every one. Every action is still recorded in the audit log.
233
+ */
234
+ throttleMinutes?: number;
235
+ /**
236
+ * Delivers the emails. Defaults to the registered `BetterAuthApp`'s `sendMail`. Set it with
237
+ * `setupServer`, where there is no `BetterAuthApp` to read.
238
+ */
239
+ sendMail?: BetterAuthConfig["sendMail"];
240
+ }
241
+
242
+ /** A renderer for security notification templates (`@terreno/comms` `renderAuthMail` fits). */
243
+ export type SecurityMailRenderer = (options: {
244
+ data: Record<string, string>;
245
+ publicAppUrl: string;
246
+ templateId: SecurityMailTemplateId;
247
+ templates?: Partial<Record<SecurityMailTemplateId, SecurityMailTemplate>>;
248
+ }) => SecurityMailTemplate;
249
+
250
+ /** Default `throttleMinutes`. */
251
+ export const DEFAULT_SECURITY_NOTIFICATION_THROTTLE_MINUTES = 10;
252
+
253
+ const PROVIDER_NAMES: Record<string, string> = {
254
+ apple: "Apple",
255
+ credential: "a password",
256
+ facebook: "Facebook",
257
+ github: "GitHub",
258
+ google: "Google",
259
+ microsoft: "Microsoft",
260
+ };
261
+
262
+ const DEFAULT_PROVIDER_NAME = "a sign-in provider";
263
+
264
+ const OCCURRED_AT_FORMAT = "LLLL d, yyyy 'at' HH:mm 'UTC'";
265
+
266
+ const providerNameOf = (details: Record<string, unknown> | undefined): string => {
267
+ const providerId = details?.providerId;
268
+ if (typeof providerId !== "string") {
269
+ return DEFAULT_PROVIDER_NAME;
270
+ }
271
+ return PROVIDER_NAMES[providerId] ?? DEFAULT_PROVIDER_NAME;
272
+ };
273
+
274
+ const occurredAtOf = (occurredAt: string): string => {
275
+ const parsed = DateTime.fromISO(occurredAt, {zone: "utc"});
276
+ return parsed.isValid ? parsed.toFormat(OCCURRED_AT_FORMAT) : occurredAt;
277
+ };
278
+
279
+ const secureAccountLineOf = (appUrl: string): string =>
280
+ appUrl
281
+ ? `If you did not expect this change, contact support right away. You can review your account security at ${appUrl}.`
282
+ : "If you did not expect this change, contact support right away.";
283
+
284
+ /**
285
+ * The placeholder values for one event. Only fixed phrases, the time, the app URL, a known
286
+ * provider name, and (with `includeOrgName`) the organization name: nothing user-chosen, no
287
+ * tokens, and no admin identity.
288
+ */
289
+ export const buildSecurityMailData = ({
290
+ event,
291
+ includeOrgName = false,
292
+ publicAppUrl,
293
+ }: {
294
+ event: SecurityActionEvent;
295
+ includeOrgName?: boolean;
296
+ publicAppUrl?: string;
297
+ }): Record<string, string> => {
298
+ const isAdmin = event.origin === "admin";
299
+ const orgName = isAdmin && includeOrgName ? (event.org?.name ?? "") : "";
300
+ const appUrl = (publicAppUrl ?? "").replace(/\/$/, "");
301
+ return {
302
+ actor: isAdmin ? "An administrator" : "You",
303
+ appUrl,
304
+ occurredAt: occurredAtOf(event.occurredAt),
305
+ orgClause: orgName ? ` at ${orgName}` : "",
306
+ orgReference: orgName || "an organization",
307
+ providerName: providerNameOf(event.details),
308
+ secureAccountLine: secureAccountLineOf(appUrl),
309
+ };
310
+ };
311
+
312
+ const HTML_ESCAPES: Record<string, string> = {
313
+ "'": "&#39;",
314
+ '"': "&quot;",
315
+ "&": "&amp;",
316
+ "<": "&lt;",
317
+ ">": "&gt;",
318
+ };
319
+
320
+ /** Escapes a value for an HTML body, so an org name cannot inject markup. */
321
+ export const escapeMailHtml = (value: string): string =>
322
+ value.replace(/[&<>"']/g, (char) => HTML_ESCAPES[char] ?? char);
323
+
324
+ const fill = (value: string, data: Record<string, string>): string =>
325
+ value.replace(/{{\s*([A-Za-z0-9_]+)\s*}}/g, (_match: string, key: string): string =>
326
+ Object.hasOwn(data, key) ? (data[key] ?? "") : ""
327
+ );
328
+
329
+ /**
330
+ * Renders a security notification without `@terreno/comms`, from `templates` or the defaults.
331
+ * HTML bodies get HTML-escaped values. Matches `renderAuthMail` output for the same input.
332
+ */
333
+ export const renderSecurityMail = ({
334
+ data,
335
+ templateId,
336
+ templates,
337
+ }: {
338
+ data: Record<string, string>;
339
+ templateId: SecurityMailTemplateId;
340
+ templates?: Partial<Record<string, SecurityMailTemplate>>;
341
+ }): SecurityMailTemplate => {
342
+ const template = templates?.[templateId] ?? DEFAULT_SECURITY_MAIL_TEMPLATES[templateId];
343
+ const htmlData = Object.fromEntries(
344
+ Object.entries(data).map(([key, value]) => [key, escapeMailHtml(value)])
345
+ );
346
+ return {
347
+ ...(template.html === undefined ? {} : {html: fill(template.html, htmlData)}),
348
+ subject: fill(template.subject, data),
349
+ ...(template.text === undefined ? {} : {text: fill(template.text, data)}),
350
+ };
351
+ };
352
+
353
+ /** The mail settings a notification reads when it is sent. */
354
+ export interface SecurityMailConfig {
355
+ authMailTemplates?: BetterAuthConfig["authMailTemplates"];
356
+ publicAppUrl?: string;
357
+ sendMail?: BetterAuthConfig["sendMail"];
358
+ }
359
+
360
+ /**
361
+ * Renders with `render` when the app opted in, falling back to the built-in renderer when there
362
+ * is none or it cannot render the template (throws or returns no subject).
363
+ */
364
+ const renderNotification = ({
365
+ config,
366
+ data,
367
+ render,
368
+ templateId,
369
+ }: {
370
+ config: SecurityMailConfig;
371
+ data: Record<string, string>;
372
+ render?: SecurityMailRenderer;
373
+ templateId: SecurityMailTemplateId;
374
+ }): SecurityMailTemplate => {
375
+ if (render) {
376
+ try {
377
+ const rendered = render({
378
+ data,
379
+ publicAppUrl: config.publicAppUrl ?? "",
380
+ templateId,
381
+ templates: config.authMailTemplates,
382
+ });
383
+ if (rendered?.subject) {
384
+ return rendered;
385
+ }
386
+ } catch (error: unknown) {
387
+ logger.warn(
388
+ `[AccountSecurity] notifications.render could not render ${templateId}: ${error}`
389
+ );
390
+ }
391
+ }
392
+ return renderSecurityMail({data, templateId, templates: config.authMailTemplates});
393
+ };
394
+
395
+ /** The `onSecurityAction` listener {@link createSecurityNotificationListener} builds. */
396
+ export interface SecurityNotificationListener {
397
+ (event: SecurityActionEvent): Promise<void>;
398
+ /** How many throttle keys are held (expired ones are pruned on each send). */
399
+ throttleEntryCount: () => number;
400
+ }
401
+
402
+ /** Notifications still being sent, so tests can wait for delivery. */
403
+ const pendingNotifications = new Set<Promise<void>>();
404
+
405
+ const emailOf = (user: User | null): string => {
406
+ const email = (user as (User & {email?: unknown}) | null)?.email;
407
+ return typeof email === "string" ? email.trim() : "";
408
+ };
409
+
410
+ /**
411
+ * Builds the `onSecurityAction` listener that emails the target. Repeats are throttled per
412
+ * target, template, origin (self or admin), and org, so a burst of one change is one email. It sends nothing for actions
413
+ * without a template, when `sendMail` is unset, or when the user has no email. A delivery
414
+ * failure is logged (with the action and user id, never the address) and never fails the action.
415
+ */
416
+ export const createSecurityNotificationListener = ({
417
+ getMailConfig,
418
+ getUserModel,
419
+ includeOrgName = false,
420
+ now = (): number => DateTime.now().toMillis(),
421
+ render,
422
+ throttleMinutes = DEFAULT_SECURITY_NOTIFICATION_THROTTLE_MINUTES,
423
+ }: {
424
+ getMailConfig: () => SecurityMailConfig;
425
+ getUserModel: () => UserModel;
426
+ includeOrgName?: boolean;
427
+ /** The current time in epoch milliseconds. Tests pass a fake clock. */
428
+ now?: () => number;
429
+ render?: SecurityMailRenderer;
430
+ throttleMinutes?: number;
431
+ }): SecurityNotificationListener => {
432
+ // When each throttle key last got an email, in epoch milliseconds.
433
+ const lastSentAt = new Map<string, number>();
434
+ const throttleMillis = Duration.fromObject({minutes: Math.max(0, throttleMinutes)}).toMillis();
435
+
436
+ /** Forgets keys whose window has passed, so the map holds only recent senders. */
437
+ const pruneExpired = (current: number): void => {
438
+ for (const [key, sentAt] of lastSentAt) {
439
+ if (current - sentAt >= throttleMillis) {
440
+ lastSentAt.delete(key);
441
+ }
442
+ }
443
+ };
444
+
445
+ /** Claims the key's slot; false while an email for it went out too recently. */
446
+ const claimSlot = (key: string): boolean => {
447
+ if (throttleMillis === 0) {
448
+ return true;
449
+ }
450
+ const current = now();
451
+ pruneExpired(current);
452
+ if (lastSentAt.has(key)) {
453
+ return false;
454
+ }
455
+ lastSentAt.set(key, current);
456
+ return true;
457
+ };
458
+
459
+ const notify = async (event: SecurityActionEvent): Promise<void> => {
460
+ const templateId = SECURITY_NOTIFICATION_TEMPLATES[event.action];
461
+ if (!templateId) {
462
+ return;
463
+ }
464
+ const config = getMailConfig();
465
+ if (!config.sendMail) {
466
+ return;
467
+ }
468
+ // Who acted is part of the key: an administrator's change must never be swallowed by the
469
+ // user's own change to the same thing a minute earlier (or by another org's admin).
470
+ const slotKey = [event.target.id, templateId, event.origin, event.org?.id ?? ""].join(":");
471
+ if (!claimSlot(slotKey)) {
472
+ return;
473
+ }
474
+ try {
475
+ const user = await findOneOrNoneFor(getUserModel(), {_id: event.target.id});
476
+ const to = emailOf(user as User | null);
477
+ if (!to) {
478
+ return;
479
+ }
480
+ const data = buildSecurityMailData({
481
+ event,
482
+ includeOrgName,
483
+ publicAppUrl: config.publicAppUrl,
484
+ });
485
+ const rendered = renderNotification({config, data, render, templateId});
486
+ await config.sendMail({
487
+ ...(rendered.html === undefined ? {} : {html: rendered.html}),
488
+ subject: rendered.subject,
489
+ text: rendered.text ?? "",
490
+ to,
491
+ });
492
+ } catch (error: unknown) {
493
+ // A failed send frees the slot, so the next change can still reach the user.
494
+ lastSentAt.delete(slotKey);
495
+ logger.error(
496
+ `[AccountSecurity] Security notification failed action=${event.action} userId=${event.target.id}: ${error}`
497
+ );
498
+ }
499
+ };
500
+ const listener = (event: SecurityActionEvent): Promise<void> => {
501
+ const sending = notify(event);
502
+ pendingNotifications.add(sending);
503
+ void sending.finally(() => {
504
+ pendingNotifications.delete(sending);
505
+ });
506
+ return sending;
507
+ };
508
+ return Object.assign(listener, {throttleEntryCount: (): number => lastSentAt.size});
509
+ };
510
+
511
+ /** Resolves once every notification started so far has been sent (or failed and been logged). */
512
+ export const flushSecurityNotificationsForTests = async (): Promise<void> => {
513
+ while (pendingNotifications.size > 0) {
514
+ await Promise.all(Array.from(pendingNotifications));
515
+ }
516
+ };
@@ -869,4 +869,75 @@ describe("array subdocument PATCH with a stripping preUpdate", () => {
869
869
  expect(stored?.categories?.[1]?.show).toBe(true);
870
870
  expect(String(stored?.categories?.[1]?._id)).toBe(String(categoryId));
871
871
  });
872
+
873
+ it("persists nested subdocument arrays across repeated PATCHes", async () => {
874
+ await mountStrippingRouter((body) => body);
875
+ const categoryId = apple.categories[0]._id;
876
+ await agent
877
+ .patch(`/food/${apple._id}/categories/${categoryId}`)
878
+ .send({categories: {addendums: [{text: "First"}]}})
879
+ .expect(200);
880
+
881
+ const secondPatch = await agent
882
+ .patch(`/food/${apple._id}/categories/${categoryId}`)
883
+ .send({categories: {addendums: [{text: "Second"}]}})
884
+ .expect(200);
885
+
886
+ expect(secondPatch.body.data.categories[0].addendums[0].text).toBe("Second");
887
+ const stored = await FoodModel.findById(apple._id).lean();
888
+ expect(stored?.categories?.[0]?.addendums?.[0]?.text).toBe("Second");
889
+ });
890
+
891
+ it("updates a sibling field when an array item already has nested subdocuments", async () => {
892
+ await mountStrippingRouter((body) => body);
893
+ const categoryId = apple.categories[0]._id;
894
+ await agent
895
+ .patch(`/food/${apple._id}/categories/${categoryId}`)
896
+ .send({categories: {addendums: [{text: "Existing"}]}})
897
+ .expect(200);
898
+ await agent
899
+ .patch(`/food/${apple._id}/categories/${categoryId}`)
900
+ .send({categories: {name: "Renamed"}})
901
+ .expect(200);
902
+
903
+ const stored = await FoodModel.findById(apple._id).lean();
904
+ expect(stored?.categories?.[0]?.name).toBe("Renamed");
905
+ expect(stored?.categories?.[0]?.addendums?.[0]?.text).toBe("Existing");
906
+ });
907
+
908
+ it("keeps nested subdocuments unchanged when preUpdate strips the array field", async () => {
909
+ await mountStrippingRouter((body) => {
910
+ const {categories: _categories, ...rest} = body;
911
+ return rest;
912
+ });
913
+ const categoryId = apple.categories[0]._id;
914
+ await FoodModel.updateOne(
915
+ {_id: apple._id},
916
+ {$set: {"categories.0.addendums": [{text: "Existing"}]}}
917
+ );
918
+
919
+ await agent
920
+ .patch(`/food/${apple._id}/categories/${categoryId}`)
921
+ .send({categories: {addendums: [{text: "Changed"}], name: "Renamed"}})
922
+ .expect(200);
923
+
924
+ const stored = await FoodModel.findById(apple._id).lean();
925
+ expect(stored?.categories?.[0]?.name).toBe("Fruit");
926
+ expect(stored?.categories?.[0]?.addendums?.[0]?.text).toBe("Existing");
927
+ });
928
+
929
+ it("applies nested subdocuments returned by preUpdate and keeps the item id", async () => {
930
+ await mountStrippingRouter((body) => ({...body}));
931
+ const categoryId = apple.categories[0]._id;
932
+ const res = await agent
933
+ .patch(`/food/${apple._id}/categories/${categoryId}`)
934
+ .send({categories: {addendums: [{text: "Applied"}]}})
935
+ .expect(200);
936
+
937
+ expect(res.body.data.categories[0]._id).toBe(String(categoryId));
938
+ expect(res.body.data.categories[0].addendums[0].text).toBe("Applied");
939
+ const stored = await FoodModel.findById(apple._id).lean();
940
+ expect(String(stored?.categories?.[0]?._id)).toBe(String(categoryId));
941
+ expect(stored?.categories?.[0]?.addendums?.[0]?.text).toBe("Applied");
942
+ });
872
943
  });
package/src/api.ts CHANGED
@@ -1373,14 +1373,15 @@ const _buildModelRouter = <T>(
1373
1373
  });
1374
1374
  }
1375
1375
  // For PATCHing an item by ID, we need to merge the objects so we don't override the _id or
1376
- // other parts of the subdocument. Merge into a detached copy: the array elements are the
1377
- // loaded document's live subdocuments, and only the body that survives the hooks below
1378
- // may change the document.
1376
+ // other parts of the subdocument. Merge plain data from the detached copy: $clone() loses
1377
+ // the subdocument's parent, so assigning a nested document array to it can throw in
1378
+ // Mongoose's setters. The loaded document's live subdocuments must not change until only
1379
+ // the body that survives the hooks below is applied.
1379
1380
  if (operation === "PATCH" && isValidObjectId(itemId)) {
1380
- const current = array[index] as {$clone?: () => object} | object;
1381
+ const current = array[index] as {toObject?: () => object} | object;
1381
1382
  const detached =
1382
- typeof (current as {$clone?: unknown}).$clone === "function"
1383
- ? (current as {$clone: () => object}).$clone()
1383
+ typeof (current as {toObject?: unknown}).toObject === "function"
1384
+ ? (current as {toObject: () => object}).toObject()
1384
1385
  : {...current};
1385
1386
  Object.assign(detached, req.body[field]);
1386
1387
  array[index] = detached;
@@ -1429,7 +1430,37 @@ const _buildModelRouter = <T>(
1429
1430
  // Using .save here runs the risk of a versioning error if you try to make two simultaneous
1430
1431
  // updates. We won't wind up with corrupted data, just an API error.
1431
1432
  try {
1432
- Object.assign(doc, body);
1433
+ const bodyRecord = body as Record<string, unknown>;
1434
+ const finalArray = bodyRecord[field];
1435
+ const liveArray = (doc as unknown as Record<string, unknown>)[field];
1436
+ if (Array.isArray(finalArray) && Array.isArray(liveArray)) {
1437
+ const mergedArray = finalArray.map((item) => {
1438
+ if (!item || typeof item !== "object") {
1439
+ return item;
1440
+ }
1441
+ const itemIdValue = (item as {id?: unknown}).id ?? (item as {_id?: unknown})._id;
1442
+ if (itemIdValue == null) {
1443
+ return item;
1444
+ }
1445
+ const liveItem = liveArray.find((live) => {
1446
+ if (!live || typeof live !== "object") {
1447
+ return false;
1448
+ }
1449
+ const liveId = (live as {id?: unknown}).id ?? (live as {_id?: unknown})._id;
1450
+ return String(liveId) === String(itemIdValue);
1451
+ });
1452
+ if (liveItem && typeof liveItem === "object" && (liveItem as {$__?: unknown}).$__) {
1453
+ Object.assign(liveItem, item);
1454
+ return liveItem;
1455
+ }
1456
+ return item;
1457
+ });
1458
+ (doc as unknown as Record<string, unknown>)[field] = mergedArray;
1459
+ const {[field]: _arrayField, ...restBody} = bodyRecord;
1460
+ Object.assign(doc, restBody);
1461
+ } else {
1462
+ Object.assign(doc, body);
1463
+ }
1433
1464
  await doc.save();
1434
1465
  } catch (error: unknown) {
1435
1466
  throw passthroughOrWrapWrite(error, {