@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,333 @@
1
+ "use strict";
2
+ /**
3
+ * Security notification emails: one email to the affected user for every recorded security
4
+ * action, whether an administrator ran it or the user did.
5
+ *
6
+ * HIPAA posture: the emails are generic. They name the change and who made it ("you" or "an
7
+ * administrator", never the admin's name or email), never include tokens, links that sign in,
8
+ * passkey names, or other user-chosen text, and name the organization only when the app opts in
9
+ * with `notifications.includeOrgName` (on a shared inbox an org name can reveal care).
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.flushSecurityNotificationsForTests = exports.createSecurityNotificationListener = exports.renderSecurityMail = exports.escapeMailHtml = exports.buildSecurityMailData = exports.DEFAULT_SECURITY_NOTIFICATION_THROTTLE_MINUTES = exports.SECURITY_NOTIFICATION_TEMPLATES = exports.DEFAULT_SECURITY_MAIL_TEMPLATES = exports.SECURITY_MAIL_TEMPLATE_IDS = void 0;
13
+ const luxon_1 = require("luxon");
14
+ const logger_1 = require("../logger");
15
+ const plugins_1 = require("../plugins");
16
+ /** The template ids security notifications render, one per kind of change. */
17
+ exports.SECURITY_MAIL_TEMPLATE_IDS = [
18
+ "securityAccountDisabled",
19
+ "securityAccountEnabled",
20
+ "securityMembershipSuspended",
21
+ "securityOtherSessionsRevoked",
22
+ "securityPasskeyAdded",
23
+ "securityPasskeyRemoved",
24
+ "securityPasswordChanged",
25
+ "securityPasswordReset",
26
+ "securityPasswordSet",
27
+ "securityProviderLinked",
28
+ "securityProviderUnlinked",
29
+ "securitySessionsRevoked",
30
+ "securitySignInLinkIssued",
31
+ "securityTwoFactorDisabled",
32
+ "securityTwoFactorEnabled",
33
+ ];
34
+ const paragraphs = (...lines) => lines.map((line) => `<p>${line}</p>`).join("");
35
+ /**
36
+ * The default notification templates. `@terreno/comms` `DEFAULT_AUTH_MAIL_TEMPLATES` includes
37
+ * them, so `renderAuthMail` renders them too. Data: `actor` ("You" / "An administrator"),
38
+ * `orgClause` ("" or " at {org}"), `orgReference` ("{org}" or "an organization"),
39
+ * `providerName`, `occurredAt`, `appUrl`, and `secureAccountLine`.
40
+ */
41
+ exports.DEFAULT_SECURITY_MAIL_TEMPLATES = {
42
+ securityAccountDisabled: {
43
+ html: paragraphs("{{actor}}{{orgClause}} disabled your account on {{occurredAt}}. You can no longer sign in.", "{{secureAccountLine}}"),
44
+ subject: "Your account was disabled",
45
+ text: "{{actor}}{{orgClause}} disabled your account on {{occurredAt}}. You can no longer sign in.\n\n{{secureAccountLine}}",
46
+ },
47
+ securityAccountEnabled: {
48
+ html: paragraphs("{{actor}}{{orgClause}} re-enabled your account on {{occurredAt}}. You can sign in again.", "{{secureAccountLine}}"),
49
+ subject: "Your account was re-enabled",
50
+ text: "{{actor}}{{orgClause}} re-enabled your account on {{occurredAt}}. You can sign in again.\n\n{{secureAccountLine}}",
51
+ },
52
+ securityMembershipSuspended: {
53
+ html: paragraphs("{{actor}} suspended your membership in {{orgReference}} on {{occurredAt}}. You can still sign in.", "{{secureAccountLine}}"),
54
+ subject: "Your organization membership was suspended",
55
+ text: "{{actor}} suspended your membership in {{orgReference}} on {{occurredAt}}. You can still sign in.\n\n{{secureAccountLine}}",
56
+ },
57
+ securityOtherSessionsRevoked: {
58
+ html: paragraphs("{{actor}}{{orgClause}} signed your account out of every other device on {{occurredAt}}.", "{{secureAccountLine}}"),
59
+ subject: "Your other sessions were signed out",
60
+ text: "{{actor}}{{orgClause}} signed your account out of every other device on {{occurredAt}}.\n\n{{secureAccountLine}}",
61
+ },
62
+ securityPasskeyAdded: {
63
+ html: paragraphs("{{actor}}{{orgClause}} added a passkey to your account on {{occurredAt}}.", "{{secureAccountLine}}"),
64
+ subject: "A passkey was added to your account",
65
+ text: "{{actor}}{{orgClause}} added a passkey to your account on {{occurredAt}}.\n\n{{secureAccountLine}}",
66
+ },
67
+ securityPasskeyRemoved: {
68
+ html: paragraphs("{{actor}}{{orgClause}} removed a passkey from your account on {{occurredAt}}.", "{{secureAccountLine}}"),
69
+ subject: "A passkey was removed from your account",
70
+ text: "{{actor}}{{orgClause}} removed a passkey from your account on {{occurredAt}}.\n\n{{secureAccountLine}}",
71
+ },
72
+ securityPasswordChanged: {
73
+ html: paragraphs("{{actor}}{{orgClause}} changed the password for your account on {{occurredAt}}.", "{{secureAccountLine}}"),
74
+ subject: "Your password was changed",
75
+ text: "{{actor}}{{orgClause}} changed the password for your account on {{occurredAt}}.\n\n{{secureAccountLine}}",
76
+ },
77
+ securityPasswordReset: {
78
+ html: paragraphs("The password for your account was reset with a reset link on {{occurredAt}}.", "{{secureAccountLine}}"),
79
+ subject: "Your password was reset",
80
+ text: "The password for your account was reset with a reset link on {{occurredAt}}.\n\n{{secureAccountLine}}",
81
+ },
82
+ securityPasswordSet: {
83
+ html: paragraphs("{{actor}}{{orgClause}} added a password to your account on {{occurredAt}}. It can now be used to sign in.", "{{secureAccountLine}}"),
84
+ subject: "A password was added to your account",
85
+ text: "{{actor}}{{orgClause}} added a password to your account on {{occurredAt}}. It can now be used to sign in.\n\n{{secureAccountLine}}",
86
+ },
87
+ securityProviderLinked: {
88
+ html: paragraphs("{{actor}}{{orgClause}} connected {{providerName}} to your account on {{occurredAt}}. It can now be used to sign in.", "{{secureAccountLine}}"),
89
+ subject: "A sign-in method was connected to your account",
90
+ text: "{{actor}}{{orgClause}} connected {{providerName}} to your account on {{occurredAt}}. It can now be used to sign in.\n\n{{secureAccountLine}}",
91
+ },
92
+ securityProviderUnlinked: {
93
+ html: paragraphs("{{actor}}{{orgClause}} disconnected {{providerName}} from your account on {{occurredAt}}.", "{{secureAccountLine}}"),
94
+ subject: "A sign-in method was disconnected from your account",
95
+ text: "{{actor}}{{orgClause}} disconnected {{providerName}} from your account on {{occurredAt}}.\n\n{{secureAccountLine}}",
96
+ },
97
+ securitySessionsRevoked: {
98
+ html: paragraphs("{{actor}}{{orgClause}} signed your account out of every device on {{occurredAt}}.", "{{secureAccountLine}}"),
99
+ subject: "You were signed out everywhere",
100
+ text: "{{actor}}{{orgClause}} signed your account out of every device on {{occurredAt}}.\n\n{{secureAccountLine}}",
101
+ },
102
+ securitySignInLinkIssued: {
103
+ html: paragraphs("{{actor}}{{orgClause}} created a sign-in link for your account on {{occurredAt}}. The link was given to the administrator, not sent to you.", "{{secureAccountLine}}"),
104
+ subject: "A sign-in link was created for your account",
105
+ 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}}",
106
+ },
107
+ securityTwoFactorDisabled: {
108
+ html: paragraphs("{{actor}}{{orgClause}} turned off two-step verification for your account on {{occurredAt}}.", "{{secureAccountLine}}"),
109
+ subject: "Two-step verification was turned off",
110
+ text: "{{actor}}{{orgClause}} turned off two-step verification for your account on {{occurredAt}}.\n\n{{secureAccountLine}}",
111
+ },
112
+ securityTwoFactorEnabled: {
113
+ html: paragraphs("{{actor}}{{orgClause}} turned on two-step verification for your account on {{occurredAt}}.", "{{secureAccountLine}}"),
114
+ subject: "Two-step verification was turned on",
115
+ text: "{{actor}}{{orgClause}} turned on two-step verification for your account on {{occurredAt}}.\n\n{{secureAccountLine}}",
116
+ },
117
+ };
118
+ /**
119
+ * Which template each security action sends; every action is listed. `null` sends nothing:
120
+ * `send-password-reset`'s own reset email is the notice, and a second email would be noise.
121
+ * `issue-sign-in-link` emails the user (who always has an email; the action refuses users
122
+ * without one) that a link exists, never the link itself.
123
+ */
124
+ exports.SECURITY_NOTIFICATION_TEMPLATES = {
125
+ disable: "securityAccountDisabled",
126
+ enable: "securityAccountEnabled",
127
+ "issue-sign-in-link": "securitySignInLinkIssued",
128
+ "other-sessions-revoked": "securityOtherSessionsRevoked",
129
+ "passkey-added": "securityPasskeyAdded",
130
+ "passkey-removed": "securityPasskeyRemoved",
131
+ "password-changed": "securityPasswordChanged",
132
+ "password-reset": "securityPasswordReset",
133
+ "password-set": "securityPasswordSet",
134
+ "provider-linked": "securityProviderLinked",
135
+ "provider-unlinked": "securityProviderUnlinked",
136
+ "remove-passkey": "securityPasskeyRemoved",
137
+ "reset-two-factor": "securityTwoFactorDisabled",
138
+ "revoke-sessions": "securitySessionsRevoked",
139
+ "send-password-reset": null,
140
+ "suspend-membership": "securityMembershipSuspended",
141
+ "two-factor-disabled": "securityTwoFactorDisabled",
142
+ "two-factor-enabled": "securityTwoFactorEnabled",
143
+ "unlink-provider": "securityProviderUnlinked",
144
+ };
145
+ /** Default `throttleMinutes`. */
146
+ exports.DEFAULT_SECURITY_NOTIFICATION_THROTTLE_MINUTES = 10;
147
+ const PROVIDER_NAMES = {
148
+ apple: "Apple",
149
+ credential: "a password",
150
+ facebook: "Facebook",
151
+ github: "GitHub",
152
+ google: "Google",
153
+ microsoft: "Microsoft",
154
+ };
155
+ const DEFAULT_PROVIDER_NAME = "a sign-in provider";
156
+ const OCCURRED_AT_FORMAT = "LLLL d, yyyy 'at' HH:mm 'UTC'";
157
+ const providerNameOf = (details) => {
158
+ const providerId = details?.providerId;
159
+ if (typeof providerId !== "string") {
160
+ return DEFAULT_PROVIDER_NAME;
161
+ }
162
+ return PROVIDER_NAMES[providerId] ?? DEFAULT_PROVIDER_NAME;
163
+ };
164
+ const occurredAtOf = (occurredAt) => {
165
+ const parsed = luxon_1.DateTime.fromISO(occurredAt, { zone: "utc" });
166
+ return parsed.isValid ? parsed.toFormat(OCCURRED_AT_FORMAT) : occurredAt;
167
+ };
168
+ const secureAccountLineOf = (appUrl) => appUrl
169
+ ? `If you did not expect this change, contact support right away. You can review your account security at ${appUrl}.`
170
+ : "If you did not expect this change, contact support right away.";
171
+ /**
172
+ * The placeholder values for one event. Only fixed phrases, the time, the app URL, a known
173
+ * provider name, and (with `includeOrgName`) the organization name: nothing user-chosen, no
174
+ * tokens, and no admin identity.
175
+ */
176
+ const buildSecurityMailData = ({ event, includeOrgName = false, publicAppUrl, }) => {
177
+ const isAdmin = event.origin === "admin";
178
+ const orgName = isAdmin && includeOrgName ? (event.org?.name ?? "") : "";
179
+ const appUrl = (publicAppUrl ?? "").replace(/\/$/, "");
180
+ return {
181
+ actor: isAdmin ? "An administrator" : "You",
182
+ appUrl,
183
+ occurredAt: occurredAtOf(event.occurredAt),
184
+ orgClause: orgName ? ` at ${orgName}` : "",
185
+ orgReference: orgName || "an organization",
186
+ providerName: providerNameOf(event.details),
187
+ secureAccountLine: secureAccountLineOf(appUrl),
188
+ };
189
+ };
190
+ exports.buildSecurityMailData = buildSecurityMailData;
191
+ const HTML_ESCAPES = {
192
+ "'": "&#39;",
193
+ '"': "&quot;",
194
+ "&": "&amp;",
195
+ "<": "&lt;",
196
+ ">": "&gt;",
197
+ };
198
+ /** Escapes a value for an HTML body, so an org name cannot inject markup. */
199
+ const escapeMailHtml = (value) => value.replace(/[&<>"']/g, (char) => HTML_ESCAPES[char] ?? char);
200
+ exports.escapeMailHtml = escapeMailHtml;
201
+ const fill = (value, data) => value.replace(/{{\s*([A-Za-z0-9_]+)\s*}}/g, (_match, key) => Object.hasOwn(data, key) ? (data[key] ?? "") : "");
202
+ /**
203
+ * Renders a security notification without `@terreno/comms`, from `templates` or the defaults.
204
+ * HTML bodies get HTML-escaped values. Matches `renderAuthMail` output for the same input.
205
+ */
206
+ const renderSecurityMail = ({ data, templateId, templates, }) => {
207
+ const template = templates?.[templateId] ?? exports.DEFAULT_SECURITY_MAIL_TEMPLATES[templateId];
208
+ const htmlData = Object.fromEntries(Object.entries(data).map(([key, value]) => [key, (0, exports.escapeMailHtml)(value)]));
209
+ return {
210
+ ...(template.html === undefined ? {} : { html: fill(template.html, htmlData) }),
211
+ subject: fill(template.subject, data),
212
+ ...(template.text === undefined ? {} : { text: fill(template.text, data) }),
213
+ };
214
+ };
215
+ exports.renderSecurityMail = renderSecurityMail;
216
+ /**
217
+ * Renders with `render` when the app opted in, falling back to the built-in renderer when there
218
+ * is none or it cannot render the template (throws or returns no subject).
219
+ */
220
+ const renderNotification = ({ config, data, render, templateId, }) => {
221
+ if (render) {
222
+ try {
223
+ const rendered = render({
224
+ data,
225
+ publicAppUrl: config.publicAppUrl ?? "",
226
+ templateId,
227
+ templates: config.authMailTemplates,
228
+ });
229
+ if (rendered?.subject) {
230
+ return rendered;
231
+ }
232
+ }
233
+ catch (error) {
234
+ logger_1.logger.warn(`[AccountSecurity] notifications.render could not render ${templateId}: ${error}`);
235
+ }
236
+ }
237
+ return (0, exports.renderSecurityMail)({ data, templateId, templates: config.authMailTemplates });
238
+ };
239
+ /** Notifications still being sent, so tests can wait for delivery. */
240
+ const pendingNotifications = new Set();
241
+ const emailOf = (user) => {
242
+ const email = user?.email;
243
+ return typeof email === "string" ? email.trim() : "";
244
+ };
245
+ /**
246
+ * Builds the `onSecurityAction` listener that emails the target. Repeats are throttled per
247
+ * target, template, origin (self or admin), and org, so a burst of one change is one email. It sends nothing for actions
248
+ * without a template, when `sendMail` is unset, or when the user has no email. A delivery
249
+ * failure is logged (with the action and user id, never the address) and never fails the action.
250
+ */
251
+ const createSecurityNotificationListener = ({ getMailConfig, getUserModel, includeOrgName = false, now = () => luxon_1.DateTime.now().toMillis(), render, throttleMinutes = exports.DEFAULT_SECURITY_NOTIFICATION_THROTTLE_MINUTES, }) => {
252
+ // When each throttle key last got an email, in epoch milliseconds.
253
+ const lastSentAt = new Map();
254
+ const throttleMillis = luxon_1.Duration.fromObject({ minutes: Math.max(0, throttleMinutes) }).toMillis();
255
+ /** Forgets keys whose window has passed, so the map holds only recent senders. */
256
+ const pruneExpired = (current) => {
257
+ for (const [key, sentAt] of lastSentAt) {
258
+ if (current - sentAt >= throttleMillis) {
259
+ lastSentAt.delete(key);
260
+ }
261
+ }
262
+ };
263
+ /** Claims the key's slot; false while an email for it went out too recently. */
264
+ const claimSlot = (key) => {
265
+ if (throttleMillis === 0) {
266
+ return true;
267
+ }
268
+ const current = now();
269
+ pruneExpired(current);
270
+ if (lastSentAt.has(key)) {
271
+ return false;
272
+ }
273
+ lastSentAt.set(key, current);
274
+ return true;
275
+ };
276
+ const notify = async (event) => {
277
+ const templateId = exports.SECURITY_NOTIFICATION_TEMPLATES[event.action];
278
+ if (!templateId) {
279
+ return;
280
+ }
281
+ const config = getMailConfig();
282
+ if (!config.sendMail) {
283
+ return;
284
+ }
285
+ // Who acted is part of the key: an administrator's change must never be swallowed by the
286
+ // user's own change to the same thing a minute earlier (or by another org's admin).
287
+ const slotKey = [event.target.id, templateId, event.origin, event.org?.id ?? ""].join(":");
288
+ if (!claimSlot(slotKey)) {
289
+ return;
290
+ }
291
+ try {
292
+ const user = await (0, plugins_1.findOneOrNoneFor)(getUserModel(), { _id: event.target.id });
293
+ const to = emailOf(user);
294
+ if (!to) {
295
+ return;
296
+ }
297
+ const data = (0, exports.buildSecurityMailData)({
298
+ event,
299
+ includeOrgName,
300
+ publicAppUrl: config.publicAppUrl,
301
+ });
302
+ const rendered = renderNotification({ config, data, render, templateId });
303
+ await config.sendMail({
304
+ ...(rendered.html === undefined ? {} : { html: rendered.html }),
305
+ subject: rendered.subject,
306
+ text: rendered.text ?? "",
307
+ to,
308
+ });
309
+ }
310
+ catch (error) {
311
+ // A failed send frees the slot, so the next change can still reach the user.
312
+ lastSentAt.delete(slotKey);
313
+ logger_1.logger.error(`[AccountSecurity] Security notification failed action=${event.action} userId=${event.target.id}: ${error}`);
314
+ }
315
+ };
316
+ const listener = (event) => {
317
+ const sending = notify(event);
318
+ pendingNotifications.add(sending);
319
+ void sending.finally(() => {
320
+ pendingNotifications.delete(sending);
321
+ });
322
+ return sending;
323
+ };
324
+ return Object.assign(listener, { throttleEntryCount: () => lastSentAt.size });
325
+ };
326
+ exports.createSecurityNotificationListener = createSecurityNotificationListener;
327
+ /** Resolves once every notification started so far has been sent (or failed and been logged). */
328
+ const flushSecurityNotificationsForTests = async () => {
329
+ while (pendingNotifications.size > 0) {
330
+ await Promise.all(Array.from(pendingNotifications));
331
+ }
332
+ };
333
+ exports.flushSecurityNotificationsForTests = flushSecurityNotificationsForTests;
package/dist/api.js CHANGED
@@ -838,13 +838,14 @@ const _buildModelRouter = (model, options, routePath) => {
838
838
  });
839
839
  }
840
840
  // For PATCHing an item by ID, we need to merge the objects so we don't override the _id or
841
- // other parts of the subdocument. Merge into a detached copy: the array elements are the
842
- // loaded document's live subdocuments, and only the body that survives the hooks below
843
- // may change the document.
841
+ // other parts of the subdocument. Merge plain data from the detached copy: $clone() loses
842
+ // the subdocument's parent, so assigning a nested document array to it can throw in
843
+ // Mongoose's setters. The loaded document's live subdocuments must not change until only
844
+ // the body that survives the hooks below is applied.
844
845
  if (operation === "PATCH" && (0, utils_1.isValidObjectId)(itemId)) {
845
846
  const current = array[index];
846
- const detached = typeof current.$clone === "function"
847
- ? current.$clone()
847
+ const detached = typeof current.toObject === "function"
848
+ ? current.toObject()
848
849
  : { ...current };
849
850
  Object.assign(detached, req.body[field]);
850
851
  array[index] = detached;
@@ -887,7 +888,38 @@ const _buildModelRouter = (model, options, routePath) => {
887
888
  // Using .save here runs the risk of a versioning error if you try to make two simultaneous
888
889
  // updates. We won't wind up with corrupted data, just an API error.
889
890
  try {
890
- Object.assign(doc, body);
891
+ const bodyRecord = body;
892
+ const finalArray = bodyRecord[field];
893
+ const liveArray = doc[field];
894
+ if (Array.isArray(finalArray) && Array.isArray(liveArray)) {
895
+ const mergedArray = finalArray.map((item) => {
896
+ if (!item || typeof item !== "object") {
897
+ return item;
898
+ }
899
+ const itemIdValue = item.id ?? item._id;
900
+ if (itemIdValue == null) {
901
+ return item;
902
+ }
903
+ const liveItem = liveArray.find((live) => {
904
+ if (!live || typeof live !== "object") {
905
+ return false;
906
+ }
907
+ const liveId = live.id ?? live._id;
908
+ return String(liveId) === String(itemIdValue);
909
+ });
910
+ if (liveItem && typeof liveItem === "object" && liveItem.$__) {
911
+ Object.assign(liveItem, item);
912
+ return liveItem;
913
+ }
914
+ return item;
915
+ });
916
+ doc[field] = mergedArray;
917
+ const { [field]: _arrayField, ...restBody } = bodyRecord;
918
+ Object.assign(doc, restBody);
919
+ }
920
+ else {
921
+ Object.assign(doc, body);
922
+ }
891
923
  await doc.save();
892
924
  }
893
925
  catch (error) {
@@ -1,8 +1,10 @@
1
1
  import mongoose from "mongoose";
2
2
  import { type FindExactlyOnePlugin, type FindOneOrNonePlugin } from "../plugins";
3
- export type AuditEventVerb = "created" | "deleted" | "updated";
4
- export type AuditEventSource = "admin" | "modelRouter" | "rbac";
5
- export type AuditEventOperation = "arrayPush" | "arrayRemove" | "arrayUpdate" | "create" | "delete" | "update";
3
+ export type AuditEventVerb = "created" | "deleted" | "updated" | "viewed";
4
+ /** Every framework surface that writes `AuditEvent` rows. `security` is AccountSecurityApp. */
5
+ export declare const AUDIT_EVENT_SOURCES: readonly ["admin", "modelRouter", "rbac", "security"];
6
+ export type AuditEventSource = (typeof AUDIT_EVENT_SOURCES)[number];
7
+ export type AuditEventOperation = "arrayPush" | "arrayRemove" | "arrayUpdate" | "create" | "delete" | "read" | "update";
6
8
  type AuditEventMethods = Record<string, never>;
7
9
  interface AuditEventStatics extends FindExactlyOnePlugin<AuditEventDocument>, FindOneOrNonePlugin<AuditEventDocument> {
8
10
  }
@@ -3,9 +3,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.createAuditEventModel = void 0;
6
+ exports.createAuditEventModel = exports.AUDIT_EVENT_SOURCES = void 0;
7
7
  const mongoose_1 = __importDefault(require("mongoose"));
8
8
  const plugins_1 = require("../plugins");
9
+ /** Every framework surface that writes `AuditEvent` rows. `security` is AccountSecurityApp. */
10
+ exports.AUDIT_EVENT_SOURCES = ["admin", "modelRouter", "rbac", "security"];
9
11
  const auditEventSchema = new mongoose_1.default.Schema({
10
12
  actorId: {
11
13
  description: "User who performed the mutation, when known",
@@ -29,8 +31,8 @@ const auditEventSchema = new mongoose_1.default.Schema({
29
31
  type: String,
30
32
  },
31
33
  operation: {
32
- description: "Fine-grained mutation kind",
33
- enum: ["arrayPush", "arrayRemove", "arrayUpdate", "create", "delete", "update"],
34
+ description: "Fine-grained mutation kind, or read for an audited read",
35
+ enum: ["arrayPush", "arrayRemove", "arrayUpdate", "create", "delete", "read", "update"],
34
36
  required: true,
35
37
  type: String,
36
38
  },
@@ -51,14 +53,14 @@ const auditEventSchema = new mongoose_1.default.Schema({
51
53
  },
52
54
  source: {
53
55
  description: "Which framework surface wrote this event",
54
- enum: ["admin", "modelRouter", "rbac"],
56
+ enum: [...exports.AUDIT_EVENT_SOURCES],
55
57
  index: true,
56
58
  required: true,
57
59
  type: String,
58
60
  },
59
61
  verb: {
60
- description: "Widget-compatible mutation verb",
61
- enum: ["created", "deleted", "updated"],
62
+ description: "Widget-compatible mutation verb, or viewed for an audited read",
63
+ enum: ["created", "deleted", "updated", "viewed"],
62
64
  index: true,
63
65
  required: true,
64
66
  type: String,
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.handleEnqueuedAuditWrite = void 0;
4
4
  const node_crypto_1 = require("node:crypto");
5
5
  const errors_1 = require("../errors");
6
+ const auditEventModel_1 = require("./auditEventModel");
6
7
  const cloudTasksEnqueue_1 = require("./cloudTasksEnqueue");
7
8
  const record_1 = require("./record");
8
9
  const secretsMatch = (provided, expected) => {
@@ -27,10 +28,11 @@ const isAuditEventWrite = (value) => {
27
28
  "arrayUpdate",
28
29
  "create",
29
30
  "delete",
31
+ "read",
30
32
  "update",
31
33
  ];
32
- const validSources = ["admin", "modelRouter", "rbac"];
33
- const validVerbs = ["created", "deleted", "updated"];
34
+ const validSources = auditEventModel_1.AUDIT_EVENT_SOURCES;
35
+ const validVerbs = ["created", "deleted", "updated", "viewed"];
34
36
  return (typeof record.modelName === "string" &&
35
37
  record.modelName.length > 0 &&
36
38
  typeof record.operation === "string" &&
@@ -1,5 +1,5 @@
1
1
  import type { Request } from "express";
2
- import type { AuditEventModel, AuditEventOperation, AuditEventVerb } from "./auditEventModel";
2
+ import type { AuditEventModel, AuditEventOperation, AuditEventSource, AuditEventVerb } from "./auditEventModel";
3
3
  export interface ModelRouterAuditOptions {
4
4
  redact?: string[];
5
5
  }
@@ -18,7 +18,7 @@ export interface AuditEventWrite {
18
18
  organizationId?: string;
19
19
  recordId?: string;
20
20
  recordLabel?: string;
21
- source: "admin" | "modelRouter" | "rbac";
21
+ source: AuditEventSource;
22
22
  verb: AuditEventVerb;
23
23
  }
24
24
  export declare const installAuditRecorder: (model: AuditEventModel, options?: AuditRecorderOptions) => void;
@@ -39,6 +39,9 @@ const operationFromVerb = (verb) => {
39
39
  if (verb === "deleted") {
40
40
  return "delete";
41
41
  }
42
+ if (verb === "viewed") {
43
+ return "read";
44
+ }
42
45
  return "update";
43
46
  };
44
47
  const maybeRecordAdminAudit = async ({ after, before, extraRedact = [], modelName, recordLabel, req, verb, }) => {
@@ -156,6 +156,13 @@ const sendEmailChangedNotice = async ({ authOptions, newEmail, previousEmail, })
156
156
  }
157
157
  };
158
158
  exports.sendEmailChangedNotice = sendEmailChangedNotice;
159
+ /** Whether the app User has a legacy JWT (passport) password. */
160
+ const hasLegacyPassword = async (userModel, user) => {
161
+ if (userModel.schema.path("hash") === undefined) {
162
+ return false;
163
+ }
164
+ return Boolean(await userModel.exists({ _id: user._id, hash: { $exists: true, $ne: null } }));
165
+ };
159
166
  const incrementTokenEpoch = (user) => {
160
167
  user.tokenEpoch = (user.tokenEpoch ?? 0) + 1;
161
168
  };
@@ -185,12 +192,25 @@ const addAuthRecoveryRoutes = (app, userModel, authOptions) => {
185
192
  if (authOptions) {
186
193
  app.locals[AUTH_OPTIONS_LOCAL_KEY] = authOptions;
187
194
  }
195
+ // With Better Auth registered (TerrenoApp wires syncPasswordResetToBetterAuth after these routes
196
+ // are added, so read it per request), the legacy routes only replace an existing JWT password:
197
+ // POST /auth/login has no second factor, so an account without one (such as a social-only
198
+ // account) must not gain a way to sign in there. Pure JWT apps keep today's behaviour.
199
+ const canResetWithLegacyRoute = async (user) => {
200
+ if (!authOptions?.syncPasswordResetToBetterAuth) {
201
+ return true;
202
+ }
203
+ return hasLegacyPassword(userModel, user);
204
+ };
188
205
  const forgotPassword = (0, api_1.asyncHandler)(async (req, res) => {
189
206
  const email = normalizeEmail(req.body?.email);
190
207
  if (email) {
191
208
  try {
192
209
  const user = await findUserByEmail(userModel, email);
193
- if (user) {
210
+ if (user && !(await canResetWithLegacyRoute(user))) {
211
+ logger_1.logger.info("[auth] Skipped legacy password reset mail for an account without a JWT password");
212
+ }
213
+ else if (user) {
194
214
  if (!authOptions?.publicAppUrl) {
195
215
  logger_1.logger.error("[auth] publicAppUrl is required to send password reset mail");
196
216
  }
@@ -237,6 +257,14 @@ const addAuthRecoveryRoutes = (app, userModel, authOptions) => {
237
257
  if ((0, auth_1.isUserDisabled)(user)) {
238
258
  throw new errors_1.APIError({ status: 401, title: "User is disabled" });
239
259
  }
260
+ if (!(await canResetWithLegacyRoute(user))) {
261
+ throw new errors_1.APIError({
262
+ code: "legacy-password-reset-unavailable",
263
+ detail: "Request a new reset link from the sign-in page.",
264
+ status: 400,
265
+ title: "This account cannot reset its password here",
266
+ });
267
+ }
240
268
  await (0, exports.changeUserPassword)(user, password, { authOptions });
241
269
  const tokens = await (0, auth_1.generateTokens)(user, authOptions);
242
270
  return res.json({