@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,260 @@
1
+ /**
2
+ * Credential recovery actions: remove one of a user's passkeys, and unlink a sign-in provider.
3
+ *
4
+ * Unlinking never removes the password (`credential`) account. Neither action leaves a user with
5
+ * no way to sign in: removing the last sign-in method is allowed only when the user's email is
6
+ * verified, and then a password-reset link is mailed so they can set a password (Q5).
7
+ */
8
+
9
+ import type {Request} from "express";
10
+
11
+ import type {User} from "../auth";
12
+ import {BadRequestError, ConflictError, NotFoundError} from "../errors";
13
+ import {logger} from "../logger";
14
+ import type {
15
+ SecurityActionContext,
16
+ SecurityActionResult,
17
+ SecurityRouteAction,
18
+ } from "./accountSecurityApp";
19
+ import {
20
+ type AccountSecurityCredentials,
21
+ type AccountSecurityFeatures,
22
+ type AccountSecurityService,
23
+ PASSWORD_PROVIDER_ID,
24
+ userIdOf,
25
+ } from "./accountSecurityService";
26
+ import {recordSecurityAction} from "./securityEvents";
27
+
28
+ const PASSKEY_NOT_FOUND_TITLE = "Passkey not found";
29
+
30
+ const PROVIDER_NOT_LINKED_TITLE = "Provider not linked";
31
+
32
+ const LAST_METHOD_TITLE = "Cannot remove the last sign-in method";
33
+
34
+ const RESET_NOT_CONFIGURED_TITLE = "Password reset email is not configured";
35
+
36
+ const PASSWORD_NOT_UNLINKABLE_TITLE = "The password cannot be unlinked";
37
+
38
+ const routeParam = (req: Request, name: string): string => {
39
+ const value = req.params[name];
40
+ return typeof value === "string" ? value : "";
41
+ };
42
+
43
+ /** Every sign-in method the user still has: accounts (including the password) and passkeys. */
44
+ const signInMethodCount = (credentials: AccountSecurityCredentials): number =>
45
+ credentials.accounts.length + credentials.passkeys.length;
46
+
47
+ /**
48
+ * Before removing a sign-in method: refuses (409) to remove the user's last one unless their
49
+ * email is verified, and then mails a password reset first, so a delivery failure removes nothing.
50
+ * Returns whether a reset was sent.
51
+ */
52
+ const guardLastSignInMethod = async ({
53
+ remaining,
54
+ credentials,
55
+ service,
56
+ target,
57
+ }: {
58
+ credentials: AccountSecurityCredentials;
59
+ remaining: number;
60
+ service: AccountSecurityService;
61
+ target: User;
62
+ }): Promise<boolean> => {
63
+ if (remaining > 0) {
64
+ return false;
65
+ }
66
+ if (!credentials.emailVerified) {
67
+ throw new ConflictError({
68
+ detail: "The user's email is not verified, so a password reset cannot replace this method",
69
+ title: LAST_METHOD_TITLE,
70
+ });
71
+ }
72
+ const reset = await service.sendPasswordReset(target);
73
+ if (!reset.sent) {
74
+ throw new ConflictError({
75
+ detail:
76
+ "Configure sendMail and publicAppUrl in BetterAuthConfig so the user can set a password",
77
+ title: RESET_NOT_CONFIGURED_TITLE,
78
+ });
79
+ }
80
+ return true;
81
+ };
82
+
83
+ /**
84
+ * After removing a sign-in method: a concurrent removal may have taken the user's last other
85
+ * method after the guard counted it. When nothing is left and no reset went out yet, mail one now
86
+ * if the email is verified. The removal already happened, so a failed send is logged, not thrown.
87
+ * Returns whether a reset has been sent for this action.
88
+ */
89
+ const ensureRecoverable = async ({
90
+ features,
91
+ resetSent,
92
+ service,
93
+ target,
94
+ }: {
95
+ features: AccountSecurityFeatures;
96
+ resetSent: boolean;
97
+ service: AccountSecurityService;
98
+ target: User;
99
+ }): Promise<boolean> => {
100
+ if (resetSent) {
101
+ return true;
102
+ }
103
+ const after = await service.readCredentials(target, features);
104
+ if (!after || signInMethodCount(after) > 0) {
105
+ return false;
106
+ }
107
+ if (!after.emailVerified) {
108
+ logger.error(
109
+ `User ${userIdOf(target)} has no sign-in method left after concurrent recovery actions, and an unverified email`
110
+ );
111
+ return false;
112
+ }
113
+ try {
114
+ const reset = await service.sendPasswordReset(target);
115
+ return reset.sent;
116
+ } catch (error: unknown) {
117
+ logger.error(`Could not mail a password reset to user ${userIdOf(target)}`, error);
118
+ return false;
119
+ }
120
+ };
121
+
122
+ /**
123
+ * Records the reset mail of an action that then found nothing to remove (another request removed
124
+ * it first), so a reset link never goes out unaudited.
125
+ */
126
+ const recordOrphanedReset = ({
127
+ actor,
128
+ details,
129
+ org,
130
+ target,
131
+ }: Pick<SecurityActionContext, "actor" | "org" | "target"> & {
132
+ details: Record<string, unknown>;
133
+ }): void => {
134
+ void recordSecurityAction({
135
+ action: "send-password-reset",
136
+ actor: {id: userIdOf(actor)},
137
+ details: {...details, reason: "last-sign-in-method"},
138
+ org,
139
+ target: {id: userIdOf(target)},
140
+ });
141
+ };
142
+
143
+ const runRemovePasskey = async ({
144
+ actor,
145
+ features,
146
+ org,
147
+ req,
148
+ service,
149
+ target,
150
+ }: SecurityActionContext): Promise<SecurityActionResult> => {
151
+ const passkeyId = routeParam(req, "passkeyId");
152
+ const credentials = await service.readCredentials(target, features);
153
+ const passkey = credentials?.passkeys.find((item) => item.id === passkeyId);
154
+ if (!credentials || !passkey) {
155
+ throw new NotFoundError(PASSKEY_NOT_FOUND_TITLE);
156
+ }
157
+ const sentBefore = await guardLastSignInMethod({
158
+ credentials,
159
+ remaining: signInMethodCount(credentials) - 1,
160
+ service,
161
+ target,
162
+ });
163
+ const removed = await service.deletePasskey({
164
+ betterAuthId: credentials.betterAuthId,
165
+ passkeyId: passkey.id,
166
+ });
167
+ if (!removed) {
168
+ // Removed by someone else between the read and the delete.
169
+ if (sentBefore) {
170
+ recordOrphanedReset({actor, details: {passkeyId: passkey.id}, org, target});
171
+ }
172
+ throw new NotFoundError(PASSKEY_NOT_FOUND_TITLE);
173
+ }
174
+ const passwordResetSent = await ensureRecoverable({
175
+ features,
176
+ resetSent: sentBefore,
177
+ service,
178
+ target,
179
+ });
180
+ return {
181
+ audit: {passkeyId: passkey.id, passkeyName: passkey.name, passwordResetSent},
182
+ changed: true,
183
+ data: {passkeyId: passkey.id, passwordResetSent},
184
+ };
185
+ };
186
+
187
+ const runUnlinkProvider = async ({
188
+ actor,
189
+ features,
190
+ org,
191
+ req,
192
+ service,
193
+ target,
194
+ }: SecurityActionContext): Promise<SecurityActionResult> => {
195
+ const providerId = routeParam(req, "providerId");
196
+ if (providerId === PASSWORD_PROVIDER_ID) {
197
+ throw new BadRequestError({
198
+ detail: "Send a password reset instead; this route only unlinks sign-in providers",
199
+ title: PASSWORD_NOT_UNLINKABLE_TITLE,
200
+ });
201
+ }
202
+ const credentials = await service.readCredentials(target, features);
203
+ const accountCount =
204
+ credentials?.accounts.filter((account) => account.providerId === providerId).length ?? 0;
205
+ if (!credentials || accountCount === 0) {
206
+ throw new NotFoundError(PROVIDER_NOT_LINKED_TITLE);
207
+ }
208
+ const sentBefore = await guardLastSignInMethod({
209
+ credentials,
210
+ remaining: signInMethodCount(credentials) - accountCount,
211
+ service,
212
+ target,
213
+ });
214
+ const removed = await service.deleteAccounts({
215
+ betterAuthId: credentials.betterAuthId,
216
+ providerId,
217
+ });
218
+ if (removed === 0) {
219
+ // Unlinked by someone else between the read and the delete.
220
+ if (sentBefore) {
221
+ recordOrphanedReset({actor, details: {providerId}, org, target});
222
+ }
223
+ throw new NotFoundError(PROVIDER_NOT_LINKED_TITLE);
224
+ }
225
+ const passwordResetSent = await ensureRecoverable({
226
+ features,
227
+ resetSent: sentBefore,
228
+ service,
229
+ target,
230
+ });
231
+ return {
232
+ audit: {accountCount: removed, passwordResetSent, providerId},
233
+ changed: true,
234
+ data: {accountCount: removed, passwordResetSent, providerId},
235
+ };
236
+ };
237
+
238
+ /** `DELETE /:userId/security/passkeys/:passkeyId`: remove one of the user's passkeys. */
239
+ export const removePasskeyAction: SecurityRouteAction = {
240
+ id: "remove-passkey",
241
+ isApplicable: ({state}) => state.passkeys.count > 0,
242
+ isSupported: (features) => features.passkey,
243
+ method: "delete",
244
+ path: "/passkeys/:passkeyId",
245
+ run: runRemovePasskey,
246
+ };
247
+
248
+ /**
249
+ * `DELETE /:userId/security/accounts/:providerId`: unlink every account the user has with that
250
+ * provider. Provider account ids are never exposed, so a user who linked two accounts of one
251
+ * provider loses both.
252
+ */
253
+ export const unlinkProviderAction: SecurityRouteAction = {
254
+ id: "unlink-provider",
255
+ isApplicable: ({state}) => state.providers.length > 0,
256
+ isSupported: (features) => features.betterAuth,
257
+ method: "delete",
258
+ path: "/accounts/:providerId",
259
+ run: runUnlinkProvider,
260
+ };
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Org-scoped recovery actions: what an org-admin runs instead of the platform-only account
3
+ * actions. Under `/orgs/:orgId/members/:userId/security/*`, "disable" suspends the member's
4
+ * membership in that one organization (Q8); `User.disabled` stays platform-only, so one org can
5
+ * never lock a user out of every other org.
6
+ */
7
+
8
+ import {APIError, NotFoundError} from "../errors";
9
+ import {LAST_ORG_ADMIN_TITLE} from "../orgs/membershipGuards";
10
+ import {Membership} from "../orgs/organizationModel";
11
+ import type {MembershipDocument} from "../types/membership";
12
+ import type {SecurityActionResult, SecurityRouteAction} from "./accountSecurityApp";
13
+ import {userIdOf} from "./accountSecurityService";
14
+
15
+ /**
16
+ * Suspends the membership without ever leaving the org with no active org-admin, even when two
17
+ * admins suspend each other at once. A check-then-write would let both pass (each sees the other
18
+ * still active); a transaction alone would too (write skew), and needs a replica set. Instead
19
+ * suspend first with a conditional update, then count the active org-admins that remain and undo
20
+ * the suspension when none do. Every request counts after its own write, so the last one to count
21
+ * sees every suspension that stuck and undoes its own if it was the last admin. Returns false when
22
+ * another request suspended the membership first.
23
+ */
24
+ const suspendUnlessLastOrgAdmin = async (membership: MembershipDocument): Promise<boolean> => {
25
+ const result = await Membership.updateOne(
26
+ {_id: membership._id, status: "active"},
27
+ {$set: {status: "suspended"}}
28
+ );
29
+ if (result.modifiedCount === 0) {
30
+ return false;
31
+ }
32
+ if (membership.roleName !== "org-admin") {
33
+ return true;
34
+ }
35
+ const remainingAdmins = await Membership.countDocuments({
36
+ organizationId: membership.organizationId,
37
+ roleName: "org-admin",
38
+ status: "active",
39
+ });
40
+ if (remainingAdmins > 0) {
41
+ return true;
42
+ }
43
+ await Membership.updateOne(
44
+ {_id: membership._id, status: "suspended"},
45
+ {$set: {status: "active"}}
46
+ );
47
+ throw new APIError({status: 400, title: LAST_ORG_ADMIN_TITLE});
48
+ };
49
+
50
+ /**
51
+ * `POST /orgs/:orgId/members/:userId/security/suspend-membership`: suspend the member's active
52
+ * membership in `:orgId`. Their account, sessions, and other memberships are untouched, so they
53
+ * still sign in and keep using their other orgs. Suspending the last active org-admin is refused
54
+ * (400). Restore a suspended member with `PATCH /orgs/:orgId/members/:memberId {status: "active"}`;
55
+ * a suspended member is out of the recovery routes' reach (404).
56
+ */
57
+ export const suspendMembershipAction: SecurityRouteAction = {
58
+ id: "suspend-membership",
59
+ isApplicable: ({org}) => Boolean(org),
60
+ isSupported: () => true,
61
+ method: "post",
62
+ orgOnly: true,
63
+ path: "/suspend-membership",
64
+ run: async ({org, target}): Promise<SecurityActionResult> => {
65
+ if (!org) {
66
+ throw new NotFoundError({
67
+ detail: "suspend-membership runs only under an organization",
68
+ title: "Security action not available",
69
+ });
70
+ }
71
+ const membership = await Membership.findOneOrNone({
72
+ organizationId: org.id,
73
+ status: "active",
74
+ userId: userIdOf(target),
75
+ });
76
+ if (!membership) {
77
+ return {changed: false};
78
+ }
79
+ if (!(await suspendUnlessLastOrgAdmin(membership))) {
80
+ return {changed: false};
81
+ }
82
+ const membershipId = String(membership._id);
83
+ return {
84
+ audit: {membershipId, roleName: membership.roleName},
85
+ changed: true,
86
+ data: {membershipId, status: "suspended"},
87
+ };
88
+ },
89
+ };