@terreno/api 57.19.2 → 57.21.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 (259) hide show
  1. package/CHANGELOG.md +443 -0
  2. package/biome.jsonc +1 -0
  3. package/dist/accountSecurity/accessActions.d.ts +38 -0
  4. package/dist/accountSecurity/accessActions.js +157 -0
  5. package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
  6. package/dist/accountSecurity/accountSecurityApp.js +438 -0
  7. package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
  8. package/dist/accountSecurity/accountSecurityService.js +481 -0
  9. package/dist/accountSecurity/credentialActions.d.ts +16 -0
  10. package/dist/accountSecurity/credentialActions.js +189 -0
  11. package/dist/accountSecurity/membershipActions.d.ts +15 -0
  12. package/dist/accountSecurity/membershipActions.js +81 -0
  13. package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
  14. package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
  15. package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
  16. package/dist/accountSecurity/securityEventHooks.js +223 -0
  17. package/dist/accountSecurity/securityEvents.d.ts +162 -0
  18. package/dist/accountSecurity/securityEvents.js +114 -0
  19. package/dist/accountSecurity/securityNotifications.d.ts +125 -0
  20. package/dist/accountSecurity/securityNotifications.js +333 -0
  21. package/dist/api.d.ts +3 -3
  22. package/dist/api.js +38 -6
  23. package/dist/audit/auditEventModel.d.ts +5 -3
  24. package/dist/audit/auditEventModel.js +8 -6
  25. package/dist/audit/processQueue.js +4 -2
  26. package/dist/audit/record.d.ts +2 -2
  27. package/dist/audit/record.js +3 -0
  28. package/dist/authRecovery.js +29 -1
  29. package/dist/betterAuth.d.ts +179 -10
  30. package/dist/betterAuthApp.d.ts +15 -0
  31. package/dist/betterAuthApp.js +23 -0
  32. package/dist/betterAuthChallengeHeaders.d.ts +37 -0
  33. package/dist/betterAuthChallengeHeaders.js +180 -0
  34. package/dist/betterAuthFeatures.d.ts +54 -0
  35. package/dist/betterAuthFeatures.js +239 -0
  36. package/dist/betterAuthMethods.d.ts +73 -0
  37. package/dist/betterAuthMethods.js +55 -0
  38. package/dist/betterAuthOAuthHandoff.d.ts +10 -2
  39. package/dist/betterAuthOAuthHandoff.js +222 -24
  40. package/dist/betterAuthSetPassword.d.ts +33 -0
  41. package/dist/betterAuthSetPassword.js +166 -0
  42. package/dist/betterAuthSetup.d.ts +57 -8
  43. package/dist/betterAuthSetup.js +327 -36
  44. package/dist/consentApp.d.ts +9 -4
  45. package/dist/consentApp.js +344 -28
  46. package/dist/consentStatus.d.ts +60 -0
  47. package/dist/consentStatus.js +111 -0
  48. package/dist/errors.d.ts +6 -0
  49. package/dist/errors.js +41 -2
  50. package/dist/expressServer.js +3 -2
  51. package/dist/frameworkModelNames.d.ts +4 -0
  52. package/dist/frameworkModelNames.js +4 -0
  53. package/dist/index.d.ts +18 -2
  54. package/dist/index.js +29 -3
  55. package/dist/mcp/adminTracking.d.ts +28 -0
  56. package/dist/mcp/adminTracking.js +80 -0
  57. package/dist/mcp/auth.d.ts +6 -0
  58. package/dist/mcp/auth.js +12 -2
  59. package/dist/mcp/oauth.js +151 -11
  60. package/dist/mcp/oauthMetadata.d.ts +2 -1
  61. package/dist/mcp/oauthMetadata.js +7 -4
  62. package/dist/mcp/server.d.ts +8 -0
  63. package/dist/mcp/server.js +48 -4
  64. package/dist/models/consentResponse.js +51 -0
  65. package/dist/models/mcpOAuthClient.js +78 -2
  66. package/dist/models/mcpOAuthToken.js +55 -4
  67. package/dist/models/mcpRequestLog.d.ts +2 -0
  68. package/dist/models/mcpRequestLog.js +73 -0
  69. package/dist/models/mcpServiceToken.js +4 -0
  70. package/dist/models/mcpToolSetting.d.ts +2 -0
  71. package/dist/models/mcpToolSetting.js +119 -0
  72. package/dist/models/versionConfig.d.ts +2 -0
  73. package/dist/orgs/membershipGuards.d.ts +7 -0
  74. package/dist/orgs/membershipGuards.js +32 -0
  75. package/dist/orgs/orgsApp.d.ts +19 -1
  76. package/dist/orgs/orgsApp.js +55 -24
  77. package/dist/rateLimit/policies.js +8 -0
  78. package/dist/rbac/access.js +2 -1
  79. package/dist/rbac/auditModel.d.ts +2 -1
  80. package/dist/rbac/resolve.d.ts +9 -1
  81. package/dist/rbac/resolve.js +21 -16
  82. package/dist/rbac/roleManager.d.ts +6 -0
  83. package/dist/rbac/roleManager.js +8 -7
  84. package/dist/rbac/roleModel.d.ts +1 -0
  85. package/dist/rbac/roleModel.js +45 -3
  86. package/dist/rbac/statements.d.ts +2 -2
  87. package/dist/rbac/statements.js +10 -1
  88. package/dist/rbac/types.d.ts +6 -0
  89. package/dist/rbac/userWriteGuards.js +2 -1
  90. package/dist/schemaMetadata.js +8 -1
  91. package/dist/seedRunner.js +7 -2
  92. package/dist/terrenoApp.d.ts +16 -0
  93. package/dist/terrenoApp.js +18 -0
  94. package/dist/tests/models.d.ts +22 -22
  95. package/dist/tests/models.js +15 -1
  96. package/dist/tests/testHelper.d.ts +6 -12
  97. package/dist/tests.d.ts +1 -0
  98. package/dist/tests.js +3 -1
  99. package/dist/types/consentResponse.d.ts +8 -0
  100. package/dist/types/mcpAdmin.d.ts +58 -0
  101. package/dist/types/mcpAdmin.js +2 -0
  102. package/dist/types/mcpOAuth.d.ts +37 -2
  103. package/dist/types/mcpServiceToken.d.ts +2 -0
  104. package/e2e/smoke.ts +193 -0
  105. package/package.json +10 -5
  106. package/src/__snapshots__/openApi.test.ts.snap +288 -0
  107. package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
  108. package/src/accountSecurity/accessActions.test.ts +723 -0
  109. package/src/accountSecurity/accessActions.ts +173 -0
  110. package/src/accountSecurity/accountSecurity.test.ts +947 -0
  111. package/src/accountSecurity/accountSecurityApp.ts +720 -0
  112. package/src/accountSecurity/accountSecurityService.ts +826 -0
  113. package/src/accountSecurity/credentialActions.test.ts +867 -0
  114. package/src/accountSecurity/credentialActions.ts +260 -0
  115. package/src/accountSecurity/membershipActions.ts +89 -0
  116. package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
  117. package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
  118. package/src/accountSecurity/securityEventHooks.ts +294 -0
  119. package/src/accountSecurity/securityEvents.ts +165 -0
  120. package/src/accountSecurity/securityNotifications.test.ts +1323 -0
  121. package/src/accountSecurity/securityNotifications.ts +516 -0
  122. package/src/adminModelRouter.test.ts +8 -6
  123. package/src/api.arrayOperations.test.ts +102 -22
  124. package/src/api.hooks.test.ts +12 -11
  125. package/src/api.query.test.ts +2 -2
  126. package/src/api.test.ts +8 -7
  127. package/src/api.ts +41 -10
  128. package/src/audit/auditApp.test.ts +1 -1
  129. package/src/audit/auditEventModel.ts +10 -7
  130. package/src/audit/cloudTasksEnqueue.test.ts +19 -14
  131. package/src/audit/processQueue.ts +4 -2
  132. package/src/audit/record.test.ts +15 -0
  133. package/src/audit/record.ts +10 -2
  134. package/src/auth.test.ts +21 -7
  135. package/src/authRecovery.test.ts +33 -10
  136. package/src/authRecovery.ts +34 -1
  137. package/src/authRecoveryBetterAuth.test.ts +169 -0
  138. package/src/authVerification.test.ts +7 -7
  139. package/src/betterAuth.ts +194 -8
  140. package/src/betterAuthApp.ts +32 -0
  141. package/src/betterAuthChallengeHeaders.test.ts +476 -0
  142. package/src/betterAuthChallengeHeaders.ts +227 -0
  143. package/src/betterAuthFeatures.test.ts +490 -0
  144. package/src/betterAuthFeatures.ts +283 -0
  145. package/src/betterAuthLinking.test.ts +846 -0
  146. package/src/betterAuthMethods.test.ts +138 -0
  147. package/src/betterAuthMethods.ts +98 -0
  148. package/src/betterAuthOAuthHandoff.test.ts +482 -69
  149. package/src/betterAuthOAuthHandoff.ts +293 -33
  150. package/src/betterAuthOAuthProxy.test.ts +421 -0
  151. package/src/betterAuthPasswordReset.test.ts +190 -0
  152. package/src/betterAuthSetPassword.test.ts +378 -0
  153. package/src/betterAuthSetPassword.ts +213 -0
  154. package/src/betterAuthSetup.test.ts +115 -57
  155. package/src/betterAuthSetup.ts +457 -38
  156. package/src/collectionRegistry.test.ts +4 -4
  157. package/src/consentApp.test.ts +869 -2
  158. package/src/consentApp.ts +438 -36
  159. package/src/consentStatus.test.ts +226 -0
  160. package/src/consentStatus.ts +171 -0
  161. package/src/errors.test.ts +81 -0
  162. package/src/errors.ts +50 -1
  163. package/src/expressServer.test.ts +29 -0
  164. package/src/expressServer.ts +3 -2
  165. package/src/frameworkModelNames.test.ts +8 -0
  166. package/src/frameworkModelNames.ts +4 -0
  167. package/src/githubAuth.test.ts +11 -11
  168. package/src/index.ts +38 -0
  169. package/src/isolated/migrateCliConnect.isolated.ts +3 -2
  170. package/src/mcp/actionTools.test.ts +11 -5
  171. package/src/mcp/adminTracking.test.ts +272 -0
  172. package/src/mcp/adminTracking.ts +104 -0
  173. package/src/mcp/auth.ts +18 -2
  174. package/src/mcp/oauth.test.ts +463 -2
  175. package/src/mcp/oauth.ts +184 -13
  176. package/src/mcp/oauthMetadata.ts +5 -2
  177. package/src/mcp/server.ts +67 -4
  178. package/src/mcp/serviceTokens.test.ts +2 -1
  179. package/src/mcp/toolGenerator.test.ts +9 -5
  180. package/src/migrations/cli.test.ts +15 -14
  181. package/src/migrations/cli.ts +1 -1
  182. package/src/migrations/generate.test.ts +2 -2
  183. package/src/migrations/load.test.ts +1 -1
  184. package/src/migrations/lock.test.ts +8 -3
  185. package/src/migrations/runner.test.ts +16 -5
  186. package/src/migrations/schemaCatalog.test.ts +4 -1
  187. package/src/models/consentResponse.ts +53 -0
  188. package/src/models/mcpOAuthClient.ts +100 -3
  189. package/src/models/mcpOAuthToken.test.ts +42 -0
  190. package/src/models/mcpOAuthToken.ts +62 -5
  191. package/src/models/mcpRequestLog.ts +81 -0
  192. package/src/models/mcpServiceToken.test.ts +23 -0
  193. package/src/models/mcpServiceToken.ts +10 -0
  194. package/src/models/mcpToolSetting.test.ts +69 -0
  195. package/src/models/mcpToolSetting.ts +138 -0
  196. package/src/models/versionConfig.ts +2 -0
  197. package/src/notifications/notificationsApp.test.ts +5 -8
  198. package/src/notifiers/slackWebApi.test.ts +30 -8
  199. package/src/openApi.test.ts +4 -4
  200. package/src/openApiValidator.test.ts +3 -3
  201. package/src/orgs/membershipGuards.ts +39 -0
  202. package/src/orgs/orgPermissions.test.ts +2 -2
  203. package/src/orgs/orgPlugin.test.ts +4 -3
  204. package/src/orgs/orgRbac.test.ts +1 -1
  205. package/src/orgs/orgSecurityDefects.test.ts +3 -1
  206. package/src/orgs/organizationSettings.test.ts +1 -1
  207. package/src/orgs/orgsApp.test.ts +104 -3
  208. package/src/orgs/orgsApp.ts +69 -28
  209. package/src/permissions.test.ts +2 -2
  210. package/src/rateLimit/policies.test.ts +53 -0
  211. package/src/rateLimit/policies.ts +8 -0
  212. package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
  213. package/src/rbac/access.ts +4 -1
  214. package/src/rbac/assertAllowed.test.ts +1 -1
  215. package/src/rbac/auditModel.ts +10 -2
  216. package/src/rbac/realtimeAccess.test.ts +3 -2
  217. package/src/rbac/resolve.test.ts +65 -0
  218. package/src/rbac/resolve.ts +37 -17
  219. package/src/rbac/roleManager.test.ts +64 -0
  220. package/src/rbac/roleManager.ts +15 -6
  221. package/src/rbac/roleModel.test.ts +174 -1
  222. package/src/rbac/roleModel.ts +66 -3
  223. package/src/rbac/routes.test.ts +58 -0
  224. package/src/rbac/statements.test.ts +4 -1
  225. package/src/rbac/statements.ts +11 -1
  226. package/src/rbac/types.ts +6 -1
  227. package/src/rbac/userWriteGuards.test.ts +56 -5
  228. package/src/rbac/userWriteGuards.ts +5 -2
  229. package/src/realtime/realtime.test.ts +35 -31
  230. package/src/schemaMetadata.test.ts +39 -0
  231. package/src/schemaMetadata.ts +11 -1
  232. package/src/scrubAdminFields.test.ts +1 -1
  233. package/src/seedRunner.test.ts +56 -0
  234. package/src/seedRunner.ts +7 -2
  235. package/src/sync/adminWindowMutation.test.ts +4 -3
  236. package/src/sync/executors.test.ts +1 -1
  237. package/src/sync/scripts/compactTombstones.test.ts +4 -3
  238. package/src/sync/sync.test.ts +1 -1
  239. package/src/sync/syncPhaseC.test.ts +14 -11
  240. package/src/sync/syncRoutes.test.ts +8 -8
  241. package/src/sync/syncSeqPlugin.test.ts +1 -2
  242. package/src/sync/syncSocket.test.ts +5 -4
  243. package/src/terrenoApp.mcpServiceTokens.test.ts +2 -2
  244. package/src/terrenoApp.migrations.test.ts +8 -7
  245. package/src/terrenoApp.ts +34 -0
  246. package/src/tests/accountSecurityTestApp.ts +290 -0
  247. package/src/tests/betterAuthStubs.ts +189 -0
  248. package/src/tests/bunSetup.ts +1 -1
  249. package/src/tests/mockOidcProvider.ts +105 -0
  250. package/src/tests/models.ts +23 -0
  251. package/src/tests/softwareAuthenticator.ts +183 -0
  252. package/src/tests/testEnv.ts +7 -0
  253. package/src/tests.ts +1 -0
  254. package/src/types/consentResponse.ts +8 -0
  255. package/src/types/mcpAdmin.ts +80 -0
  256. package/src/types/mcpOAuth.ts +44 -3
  257. package/src/types/mcpServiceToken.ts +5 -0
  258. package/src/webhooks/verifiers/hmac.test.ts +1 -1
  259. package/tsconfig.typecheck.json +14 -0
@@ -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
+ };
@@ -2,7 +2,7 @@ import {describe, expect, it} from "bun:test";
2
2
  import mongoose from "mongoose";
3
3
 
4
4
  import {enrichModelRouterOptions} from "./adminModelRouter";
5
- import type {ModelRouterOptions} from "./api";
5
+ import type {ModelRouterOptions, OpenApiMiddleware} from "./api";
6
6
 
7
7
  interface Widget {
8
8
  secret?: string;
@@ -34,10 +34,9 @@ describe("enrichModelRouterOptions", () => {
34
34
  const options: ModelRouterOptions<Widget> = {
35
35
  permissions: {create: [], delete: [], list: [], read: [], update: []},
36
36
  };
37
- const enriched = enrichModelRouterOptions(WidgetModel, options, {
38
- openApi: {enabled: true} as never,
39
- });
40
- expect(enriched.openApi).toEqual({enabled: true});
37
+ const openApi = {enabled: true} as unknown as OpenApiMiddleware;
38
+ const enriched = enrichModelRouterOptions(WidgetModel, options, {openApi});
39
+ expect(enriched.openApi).toEqual(openApi);
41
40
  });
42
41
 
43
42
  it("scrubs admin fields in preCreate/preUpdate and honors user hooks", async () => {
@@ -49,7 +48,10 @@ describe("enrichModelRouterOptions", () => {
49
48
  listFields: ["title"],
50
49
  },
51
50
  permissions: {create: [], delete: [], list: [], read: [], update: []},
52
- preCreate: async (body) => ({...body, title: `${body.title}-created`}),
51
+ preCreate: async (body) => {
52
+ const widget = body as Partial<Widget>;
53
+ return {...widget, title: `${widget.title}-created`};
54
+ },
53
55
  preUpdate: async () => null,
54
56
  };
55
57
  const enriched = enrichModelRouterOptions(WidgetModel, options, {});