@terreno/api 57.18.0 → 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 +2071 -2
  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,226 @@
1
+ import {beforeEach, describe, expect, it} from "bun:test";
2
+ import type {HydratedDocument} from "mongoose";
3
+ import mongoose from "mongoose";
4
+
5
+ import {getConsentStatuses} from "./consentStatus";
6
+ import {ConsentForm} from "./models/consentForm";
7
+ import {ConsentResponse} from "./models/consentResponse";
8
+ import {setupDb, type User} from "./tests";
9
+ import type {ConsentFormDocument} from "./types/consentForm";
10
+
11
+ describe("getConsentStatuses", () => {
12
+ let admin: HydratedDocument<User>;
13
+ let member: HydratedDocument<User>;
14
+ let form: ConsentFormDocument;
15
+
16
+ const respond = async (
17
+ overrides: Partial<Record<string, unknown>> = {}
18
+ ): Promise<mongoose.Types.ObjectId> => {
19
+ const response = await ConsentResponse.create({
20
+ agreed: true,
21
+ agreedAt: new Date("2026-02-01T00:00:00.000Z"),
22
+ consentFormId: form._id,
23
+ formVersionSnapshot: 2,
24
+ locale: "en",
25
+ userId: member._id,
26
+ ...overrides,
27
+ });
28
+ return response._id;
29
+ };
30
+
31
+ const signProvisionally = (
32
+ overrides: Partial<Record<string, unknown>> = {}
33
+ ): Promise<mongoose.Types.ObjectId> =>
34
+ respond({
35
+ agreedAt: new Date("2026-01-15T00:00:00.000Z"),
36
+ provisional: true,
37
+ provisionalNote: "Guardian agreed at intake",
38
+ provisionalSignedBy: admin._id,
39
+ ...overrides,
40
+ });
41
+
42
+ beforeEach(async () => {
43
+ [admin, member] = await setupDb();
44
+ await Promise.all([ConsentForm.deleteMany({}), ConsentResponse.deleteMany({})]);
45
+ form = await ConsentForm.create({
46
+ active: true,
47
+ content: new Map([["en", "# Treatment consent"]]),
48
+ order: 1,
49
+ slug: "treatment",
50
+ title: "Treatment consent",
51
+ type: "agreement",
52
+ version: 2,
53
+ });
54
+ });
55
+
56
+ it("returns pending when there are no responses", async () => {
57
+ const rows = await getConsentStatuses({userId: member._id.toString()});
58
+
59
+ expect(rows).toHaveLength(1);
60
+ expect(rows[0].form.title).toBe("Treatment consent");
61
+ expect(rows[0].form.content).toEqual({en: "# Treatment consent"});
62
+ expect(rows[0].status).toBe("pending");
63
+ expect(rows[0].isConsented).toBe(false);
64
+ expect(rows[0].respondedAt).toBeUndefined();
65
+ expect(rows[0].provisional).toBeUndefined();
66
+ });
67
+
68
+ it("returns provisional, counted as consented, with the signer and note", async () => {
69
+ const responseId = await signProvisionally();
70
+
71
+ const [row] = await getConsentStatuses({userId: member._id.toString()});
72
+
73
+ expect(row.status).toBe("provisional");
74
+ expect(row.isConsented).toBe(true);
75
+ expect(row.respondedAt?.toISOString()).toBe("2026-01-15T00:00:00.000Z");
76
+ expect(row.provisional).toEqual({
77
+ note: "Guardian agreed at intake",
78
+ responseId: responseId.toString(),
79
+ signedAt: new Date("2026-01-15T00:00:00.000Z"),
80
+ signedBy: {email: "admin@example.com", id: admin._id.toString(), name: "Admin"},
81
+ });
82
+ });
83
+
84
+ it("returns signed when the user agreed themselves", async () => {
85
+ await respond();
86
+
87
+ const [row] = await getConsentStatuses({userId: member._id.toString()});
88
+
89
+ expect(row.status).toBe("signed");
90
+ expect(row.isConsented).toBe(true);
91
+ expect(row.respondedAt?.toISOString()).toBe("2026-02-01T00:00:00.000Z");
92
+ });
93
+
94
+ it("returns declined when the user declined", async () => {
95
+ await respond({agreed: false});
96
+
97
+ const [row] = await getConsentStatuses({userId: member._id.toString()});
98
+
99
+ expect(row.status).toBe("declined");
100
+ expect(row.isConsented).toBe(false);
101
+ });
102
+
103
+ it("returns signed when the user agrees after a provisional signature", async () => {
104
+ await signProvisionally();
105
+ await respond({agreed: true});
106
+
107
+ const [row] = await getConsentStatuses({userId: member._id.toString()});
108
+
109
+ expect(row.status).toBe("signed");
110
+ expect(row.isConsented).toBe(true);
111
+ expect(row.provisional?.note).toBe("Guardian agreed at intake");
112
+ });
113
+
114
+ it("returns declined when the user declines after a provisional signature", async () => {
115
+ await signProvisionally();
116
+ await respond({agreed: false});
117
+
118
+ const [row] = await getConsentStatuses({userId: member._id.toString()});
119
+
120
+ expect(row.status).toBe("declined");
121
+ expect(row.isConsented).toBe(false);
122
+ });
123
+
124
+ it("uses the user's latest own response", async () => {
125
+ await respond({agreed: false, agreedAt: new Date("2026-02-01T00:00:00.000Z")});
126
+ await respond({agreed: true, agreedAt: new Date("2026-03-01T00:00:00.000Z")});
127
+
128
+ const [row] = await getConsentStatuses({userId: member._id.toString()});
129
+
130
+ expect(row.status).toBe("signed");
131
+ expect(row.respondedAt?.toISOString()).toBe("2026-03-01T00:00:00.000Z");
132
+ });
133
+
134
+ it("ignores responses to older form versions", async () => {
135
+ await respond({formVersionSnapshot: 1});
136
+ await signProvisionally({formVersionSnapshot: 1});
137
+
138
+ const [row] = await getConsentStatuses({userId: member._id.toString()});
139
+
140
+ expect(row.status).toBe("pending");
141
+ expect(row.provisional).toBeUndefined();
142
+ });
143
+
144
+ it("ignores voided provisional signatures", async () => {
145
+ await signProvisionally({
146
+ voidedAt: new Date("2026-01-16T00:00:00.000Z"),
147
+ voidedBy: admin._id,
148
+ voidReason: "Wrong member",
149
+ });
150
+
151
+ const [row] = await getConsentStatuses({userId: member._id.toString()});
152
+
153
+ expect(row.status).toBe("pending");
154
+ expect(row.isConsented).toBe(false);
155
+ expect(row.provisional).toBeUndefined();
156
+ });
157
+
158
+ it("falls back to an earlier provisional signature when the latest is voided", async () => {
159
+ const earlierId = await signProvisionally({agreedAt: new Date("2026-01-10T00:00:00.000Z")});
160
+ await signProvisionally({
161
+ voidedAt: new Date("2026-01-16T00:00:00.000Z"),
162
+ voidedBy: admin._id,
163
+ voidReason: "Wrong member",
164
+ });
165
+
166
+ const [row] = await getConsentStatuses({userId: member._id.toString()});
167
+
168
+ expect(row.status).toBe("provisional");
169
+ expect(row.provisional?.responseId).toBe(earlierId.toString());
170
+ });
171
+
172
+ it("ignores inactive forms and other users' responses", async () => {
173
+ await ConsentForm.create({
174
+ active: false,
175
+ content: new Map([["en", "# Old"]]),
176
+ order: 2,
177
+ slug: "retired",
178
+ title: "Retired",
179
+ type: "custom",
180
+ version: 1,
181
+ });
182
+ await respond({userId: admin._id});
183
+
184
+ const rows = await getConsentStatuses({userId: member._id.toString()});
185
+
186
+ expect(rows.map((row) => row.form.slug)).toEqual(["treatment"]);
187
+ expect(rows[0].status).toBe("pending");
188
+ });
189
+
190
+ it("lets the resolver filter forms for the target user", async () => {
191
+ await ConsentForm.create({
192
+ active: true,
193
+ content: new Map([["en", "# Research"]]),
194
+ order: 2,
195
+ slug: "research",
196
+ title: "Research",
197
+ type: "research",
198
+ version: 1,
199
+ });
200
+ const resolvedFor: string[] = [];
201
+
202
+ const rows = await getConsentStatuses({
203
+ resolveConsentForms: (user, forms) => {
204
+ resolvedFor.push(String(user.id));
205
+ return forms.filter((candidate) => candidate.slug !== "research");
206
+ },
207
+ userId: member._id.toString(),
208
+ });
209
+
210
+ expect(resolvedFor).toEqual([member._id.toString()]);
211
+ expect(rows.map((row) => row.form.slug)).toEqual(["treatment"]);
212
+ });
213
+
214
+ it("throws 404 for an unknown user", async () => {
215
+ await expect(
216
+ getConsentStatuses({userId: new mongoose.Types.ObjectId().toString()})
217
+ ).rejects.toMatchObject({status: 404, title: "User not found"});
218
+ });
219
+
220
+ it("throws 400 for a malformed user id", async () => {
221
+ await expect(getConsentStatuses({userId: "not-an-id"})).rejects.toMatchObject({
222
+ status: 400,
223
+ title: "userId is invalid",
224
+ });
225
+ });
226
+ });
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Consent status per form for one user: the "considered signed" contract apps build on.
3
+ * A provisional signature counts as consented until the user answers the form themselves.
4
+ */
5
+
6
+ import mongoose from "mongoose";
7
+
8
+ import type {User} from "./auth";
9
+ import {APIError} from "./errors";
10
+ import {ConsentForm} from "./models/consentForm";
11
+ import {ConsentResponse} from "./models/consentResponse";
12
+ import {findOneOrNoneFor} from "./plugins";
13
+ import type {ConsentFormDocument} from "./types/consentForm";
14
+ import type {ConsentResponseDocument} from "./types/consentResponse";
15
+ import {isValidObjectId} from "./utils";
16
+
17
+ export type ResolveConsentForms = (
18
+ user: User,
19
+ forms: ConsentFormDocument[]
20
+ ) => ConsentFormDocument[] | Promise<ConsentFormDocument[]>;
21
+
22
+ export type ConsentStatus = "pending" | "provisional" | "signed" | "declined";
23
+
24
+ /** A consent form as serialized to clients (`toJSON` with maps flattened). */
25
+ export interface ConsentStatusForm {
26
+ _id: string;
27
+ id: string;
28
+ title: string;
29
+ slug: string;
30
+ version: number;
31
+ type: string;
32
+ content: Record<string, string>;
33
+ [field: string]: unknown;
34
+ }
35
+
36
+ export interface ConsentStatusSigner {
37
+ id: string;
38
+ name?: string;
39
+ email?: string;
40
+ }
41
+
42
+ export interface ConsentStatusProvisional {
43
+ responseId: string;
44
+ signedAt: Date;
45
+ signedBy: ConsentStatusSigner | null;
46
+ note?: string;
47
+ }
48
+
49
+ export interface ConsentStatusRow {
50
+ form: ConsentStatusForm;
51
+ status: ConsentStatus;
52
+ isConsented: boolean;
53
+ respondedAt?: Date;
54
+ /** The latest provisional signature for the current version, whatever the status. */
55
+ provisional?: ConsentStatusProvisional;
56
+ }
57
+
58
+ /** Fields returned for the provisional signer on provisional consent responses. */
59
+ export const provisionalSignerPopulate = {path: "provisionalSignedBy", select: "name email"};
60
+
61
+ /** Load the consent forms that apply to a user: active forms, narrowed by the app's resolver. */
62
+ export const resolveFormsForUser = async (
63
+ user: User,
64
+ resolveConsentForms?: ResolveConsentForms
65
+ ): Promise<{activeForms: ConsentFormDocument[]; resolvedForms: ConsentFormDocument[]}> => {
66
+ const activeForms = await ConsentForm.find({active: true}).sort({order: 1});
67
+ if (!resolveConsentForms) {
68
+ return {activeForms, resolvedForms: activeForms};
69
+ }
70
+ const resolvedForms = await resolveConsentForms(user, activeForms);
71
+ return {activeForms, resolvedForms};
72
+ };
73
+
74
+ /** Load a user by id, or throw 400 for a malformed id and 404 for an unknown one. */
75
+ export const loadConsentTargetUser = async (userId: string): Promise<User> => {
76
+ if (!isValidObjectId(userId)) {
77
+ throw new APIError({status: 400, title: "userId is invalid"});
78
+ }
79
+ const user = await findOneOrNoneFor(mongoose.model("User"), {_id: userId});
80
+ if (!user) {
81
+ throw new APIError({status: 404, title: "User not found"});
82
+ }
83
+ return user as unknown as User;
84
+ };
85
+
86
+ const toSigner = (value: unknown): ConsentStatusSigner | null => {
87
+ if (!value || typeof value !== "object" || !("_id" in value)) {
88
+ return null;
89
+ }
90
+ const signer = value as {_id: mongoose.Types.ObjectId; email?: string; name?: string};
91
+ return {email: signer.email, id: signer._id.toString(), name: signer.name};
92
+ };
93
+
94
+ const statusForResponses = (
95
+ responses: ConsentResponseDocument[]
96
+ ): Pick<ConsentStatusRow, "isConsented" | "provisional" | "respondedAt" | "status"> => {
97
+ // Responses arrive newest first, so the first match is the latest.
98
+ const own = responses.find((response) => !response.provisional);
99
+ const provisional = responses.find((response) => response.provisional);
100
+ const provisionalSummary: ConsentStatusProvisional | undefined = provisional
101
+ ? {
102
+ note: provisional.provisionalNote,
103
+ responseId: provisional._id.toString(),
104
+ signedAt: provisional.agreedAt,
105
+ signedBy: toSigner(provisional.provisionalSignedBy),
106
+ }
107
+ : undefined;
108
+
109
+ if (own) {
110
+ return {
111
+ isConsented: own.agreed,
112
+ provisional: provisionalSummary,
113
+ respondedAt: own.agreedAt,
114
+ status: own.agreed ? "signed" : "declined",
115
+ };
116
+ }
117
+ if (provisional) {
118
+ return {
119
+ isConsented: true,
120
+ provisional: provisionalSummary,
121
+ respondedAt: provisional.agreedAt,
122
+ status: "provisional",
123
+ };
124
+ }
125
+ return {isConsented: false, status: "pending"};
126
+ };
127
+
128
+ /**
129
+ * Consent status for every active form that applies to the user, in form order. Only
130
+ * non-voided responses to each form's current version count. The user's own latest response decides
131
+ * (`signed` or `declined`); otherwise a provisional signature makes it `provisional`, which
132
+ * counts as consented; otherwise `pending`.
133
+ */
134
+ export const getConsentStatuses = async ({
135
+ userId,
136
+ resolveConsentForms,
137
+ }: {
138
+ userId: string;
139
+ resolveConsentForms?: ResolveConsentForms;
140
+ }): Promise<ConsentStatusRow[]> => {
141
+ const user = await loadConsentTargetUser(userId);
142
+ const {resolvedForms} = await resolveFormsForUser(user, resolveConsentForms);
143
+
144
+ const responses = await ConsentResponse.find({
145
+ consentFormId: {$in: resolvedForms.map((form) => form._id)},
146
+ userId,
147
+ voidedAt: null,
148
+ })
149
+ .sort({agreedAt: -1})
150
+ .populate(provisionalSignerPopulate);
151
+
152
+ return resolvedForms.map((form) => {
153
+ const current = responses.filter(
154
+ (response) =>
155
+ response.consentFormId.toString() === form._id.toString() &&
156
+ response.formVersionSnapshot === form.version
157
+ );
158
+ const row: ConsentStatusRow = {
159
+ // A JSON round trip gives the same shape clients receive: string ids, flattened maps.
160
+ form: JSON.parse(JSON.stringify(form)) as ConsentStatusForm,
161
+ ...statusForResponses(current),
162
+ };
163
+ if (!row.provisional) {
164
+ delete row.provisional;
165
+ }
166
+ if (!row.respondedAt) {
167
+ delete row.respondedAt;
168
+ }
169
+ return row;
170
+ });
171
+ };
@@ -7,8 +7,10 @@ import supertest from "supertest";
7
7
  import {
8
8
  APIError,
9
9
  apiErrorMiddleware,
10
+ apiFallthroughErrorMiddleware,
10
11
  apiUnauthorizedMiddleware,
11
12
  BadRequestError,
13
+ bodyParserErrorToAPIError,
12
14
  ConflictError,
13
15
  errorDetail,
14
16
  errorMessage,
@@ -620,3 +622,82 @@ describe("apiErrorMiddleware", () => {
620
622
  expect(next).not.toHaveBeenCalled();
621
623
  });
622
624
  });
625
+
626
+ describe("body-parser errors in the terrenoApp middleware order", () => {
627
+ const buildApp = (limit?: string): express.Express => {
628
+ const app = express();
629
+ app.use(express.json(limit ? {limit} : undefined));
630
+ app.post("/todos", (req, res) => {
631
+ res.json({data: req.body});
632
+ });
633
+ app.use(apiUnauthorizedMiddleware);
634
+ app.use(apiErrorMiddleware);
635
+ app.use(apiFallthroughErrorMiddleware);
636
+ return app;
637
+ };
638
+
639
+ it("returns 400 for a malformed JSON body", async () => {
640
+ const res = await supertest(buildApp())
641
+ .post("/todos")
642
+ .set("Content-Type", "application/json")
643
+ .send('{"title": broken json')
644
+ .expect(400);
645
+ expect(res.body.status).toBe(400);
646
+ expect(res.body.title).toBe("Malformed request body");
647
+ expect(typeof res.body.detail).toBe("string");
648
+ expect(res.body.detail.length).toBeGreaterThan(0);
649
+ });
650
+
651
+ it("returns 413 for a JSON body over the parser limit", async () => {
652
+ const res = await supertest(buildApp("10b"))
653
+ .post("/todos")
654
+ .set("Content-Type", "application/json")
655
+ .send(JSON.stringify({title: "this body is longer than ten bytes"}))
656
+ .expect(413);
657
+ expect(res.body).toEqual(
658
+ expect.objectContaining({status: 413, title: "Request body too large"})
659
+ );
660
+ });
661
+
662
+ it("returns 415 for an unsupported body charset", async () => {
663
+ const res = await supertest(buildApp())
664
+ .post("/todos")
665
+ .set("Content-Type", "application/json; charset=klingon")
666
+ .send('{"title": "x"}')
667
+ .expect(415);
668
+ expect(res.body).toEqual(
669
+ expect.objectContaining({status: 415, title: "Unsupported request body encoding"})
670
+ );
671
+ });
672
+
673
+ it("still parses a valid JSON body", async () => {
674
+ const res = await supertest(buildApp()).post("/todos").send({title: "ok"}).expect(200);
675
+ expect(res.body).toEqual({data: {title: "ok"}});
676
+ });
677
+ });
678
+
679
+ describe("bodyParserErrorToAPIError", () => {
680
+ it("returns null for errors that did not come from body-parser", () => {
681
+ expect(bodyParserErrorToAPIError(new Error("boom"))).toBeNull();
682
+ const notExposed = Object.assign(new Error("hidden"), {
683
+ expose: false,
684
+ status: 500,
685
+ type: "stream.encoding.set",
686
+ });
687
+ expect(bodyParserErrorToAPIError(notExposed)).toBeNull();
688
+ });
689
+
690
+ it("keeps the parser's status and message and skips Sentry", () => {
691
+ const parseError = Object.assign(new SyntaxError("Unexpected token b in JSON"), {
692
+ expose: true,
693
+ status: 400,
694
+ type: "entity.parse.failed",
695
+ });
696
+ const apiError = bodyParserErrorToAPIError(parseError);
697
+ expect(apiError?.status).toBe(400);
698
+ expect(apiError?.title).toBe("Malformed request body");
699
+ expect(apiError?.detail).toBe("Unexpected token b in JSON");
700
+ expect(apiError?.cause).toBe(parseError);
701
+ expect(apiError?.disableExternalErrorTracking).toBe(true);
702
+ });
703
+ });
package/src/errors.ts CHANGED
@@ -478,6 +478,53 @@ export const mongooseErrorToAPIError = (err: Error): APIError | null => {
478
478
  return null;
479
479
  };
480
480
 
481
+ // Stable titles for the client errors body-parser (express.json / express.urlencoded) raises
482
+ // before a route runs. The parser's own status and message are kept; only the title is mapped.
483
+ const BODY_PARSER_ERROR_TITLES: {[type: string]: string} = {
484
+ "charset.unsupported": "Unsupported request body encoding",
485
+ "encoding.unsupported": "Unsupported request body encoding",
486
+ "entity.parse.failed": "Malformed request body",
487
+ "entity.too.large": "Request body too large",
488
+ "parameters.too.many": "Request body too large",
489
+ "request.aborted": "Request body incomplete",
490
+ "request.size.invalid": "Request body incomplete",
491
+ };
492
+
493
+ interface BodyParserError extends Error {
494
+ expose: boolean;
495
+ status: number;
496
+ type: string;
497
+ }
498
+
499
+ const isBodyParserClientError = (err: Error): err is BodyParserError => {
500
+ const candidate = err as Partial<BodyParserError>;
501
+ return (
502
+ typeof candidate.type === "string" &&
503
+ candidate.expose === true &&
504
+ typeof candidate.status === "number" &&
505
+ candidate.status >= 400 &&
506
+ candidate.status < 500
507
+ );
508
+ };
509
+
510
+ /**
511
+ * Converts a body-parser client error (malformed JSON, oversized body, unsupported charset) into
512
+ * an APIError with the parser's 4xx status. Returns null for anything else, including parser
513
+ * errors body-parser marks as not exposable (server faults).
514
+ */
515
+ export const bodyParserErrorToAPIError = (err: Error): APIError | null => {
516
+ if (!isBodyParserClientError(err)) {
517
+ return null;
518
+ }
519
+ return new APIError({
520
+ cause: err,
521
+ detail: err.message,
522
+ disableExternalErrorTracking: true,
523
+ status: err.status,
524
+ title: BODY_PARSER_ERROR_TITLES[err.type] ?? "Invalid request body",
525
+ });
526
+ };
527
+
481
528
  /**
482
529
  * Picks the error to throw for something caught in a hook, transformer, or Mongoose middleware.
483
530
  * An `APIError` is passed through untouched so its status, code, detail, and meta reach the client;
@@ -544,7 +591,9 @@ export const apiErrorMiddleware = (
544
591
  res: Response,
545
592
  next: NextFunction
546
593
  ) => {
547
- const apiError = isAPIError(err) ? err : mongooseErrorToAPIError(err);
594
+ const apiError = isAPIError(err)
595
+ ? err
596
+ : (mongooseErrorToAPIError(err) ?? bodyParserErrorToAPIError(err));
548
597
  if (!apiError) {
549
598
  next(err);
550
599
  return;
@@ -225,6 +225,35 @@ describe("expressServer", () => {
225
225
  }
226
226
  });
227
227
 
228
+ it("redacts free-text note and reason fields that can hold PHI", () => {
229
+ const logged: string[] = [];
230
+ const originalDebug = logger.debug;
231
+ logger.debug = ((message: string) => {
232
+ logged.push(message);
233
+ }) as typeof logger.debug;
234
+ try {
235
+ const req = {
236
+ body: {
237
+ consentFormId: "form-1",
238
+ note: "Guardian Jane agreed by phone",
239
+ provisionalNote: "Also mentioned the diagnosis",
240
+ reason: "Signed for the wrong member",
241
+ },
242
+ method: "POST",
243
+ url: "/consent-responses/provisional",
244
+ };
245
+ logRequests(req as never, {locals: {}, on: () => {}} as never, () => {});
246
+ const combined = logged.join("\n");
247
+ expect(combined).not.toContain("Guardian Jane");
248
+ expect(combined).not.toContain("diagnosis");
249
+ expect(combined).not.toContain("wrong member");
250
+ expect(combined).toContain("form-1");
251
+ expect(req.body.note).toBe("Guardian Jane agreed by phone");
252
+ } finally {
253
+ logger.debug = originalDebug;
254
+ }
255
+ });
256
+
228
257
  it("redacts credentials under any key name and at any depth in logged bodies", () => {
229
258
  const logged: string[] = [];
230
259
  const originalDebug = logger.debug;
@@ -36,8 +36,9 @@ const SENSITIVE_KEY_FRAGMENTS = [
36
36
  ] as const;
37
37
 
38
38
  // Matched as whole words of a key, so `code` covers OAuth and verification codes without
39
- // matching unrelated words that merely contain the letters.
40
- const SENSITIVE_KEY_WORDS = new Set<string>(["code", "otp", "pin"]);
39
+ // matching unrelated words that merely contain the letters. `note` and `reason` are free text
40
+ // that can hold PHI, such as a provisional consent signer's note or a void reason.
41
+ const SENSITIVE_KEY_WORDS = new Set<string>(["code", "note", "otp", "pin", "reason"]);
41
42
 
42
43
  const keyWords = (key: string): string[] => {
43
44
  return key
package/src/index.ts CHANGED
@@ -1,8 +1,24 @@
1
+ export {ISSUE_SIGN_IN_LINK_PERMISSION} from "./accountSecurity/accessActions";
2
+ export * from "./accountSecurity/accountSecurityApp";
3
+ export * from "./accountSecurity/accountSecurityService";
4
+ export {suspendMembershipAction} from "./accountSecurity/membershipActions";
5
+ export {
6
+ createOrgSecurityAuthorizer,
7
+ mountOrgSecurityRoutes,
8
+ type OrgRecoveryOptions,
9
+ } from "./accountSecurity/orgSecurityRoutes";
10
+ export {
11
+ createSecurityEventsPlugin,
12
+ recordSelfSecurityAction,
13
+ } from "./accountSecurity/securityEventHooks";
14
+ export * from "./accountSecurity/securityEvents";
15
+ export * from "./accountSecurity/securityNotifications";
1
16
  export * from "./actions";
2
17
  export * from "./adminTypes";
3
18
  export * from "./api";
4
19
  export {AuditApp, type AuditAppOptions} from "./audit/auditApp";
5
20
  export {
21
+ AUDIT_EVENT_SOURCES,
6
22
  type AuditEventDocument,
7
23
  type AuditEventModel,
8
24
  type AuditEventOperation,
@@ -35,12 +51,24 @@ export * from "./authRecovery";
35
51
  export * from "./authTokens";
36
52
  export * from "./betterAuth";
37
53
  export * from "./betterAuthApp";
54
+ export * from "./betterAuthChallengeHeaders";
55
+ export * from "./betterAuthFeatures";
56
+ export * from "./betterAuthMethods";
38
57
  export * from "./betterAuthSetup";
39
58
  export * from "./browserLogsRoute";
40
59
  export * from "./config";
41
60
  export * from "./configurationApp";
42
61
  export * from "./configurationPlugin";
43
62
  export * from "./consentApp";
63
+ export {
64
+ type ConsentStatus,
65
+ type ConsentStatusForm,
66
+ type ConsentStatusProvisional,
67
+ type ConsentStatusRow,
68
+ type ConsentStatusSigner,
69
+ getConsentStatuses,
70
+ type ResolveConsentForms,
71
+ } from "./consentStatus";
44
72
  export * from "./envConfigurationPlugin";
45
73
  export * from "./errors";
46
74
  export * from "./expressServer";
@@ -323,8 +351,10 @@ export type {
323
351
  McpOAuthAuthorizationDocument,
324
352
  McpOAuthAuthorizationStatus,
325
353
  McpOAuthClientDocument,
354
+ McpOAuthConfidentialClientOptions,
326
355
  McpOAuthRevokedFamilyDocument,
327
356
  McpOAuthTokenDocument,
357
+ McpOAuthTokenEndpointAuthMethod,
328
358
  } from "./types/mcpOAuth";
329
359
  export * from "./utils";
330
360
  export * from "./versionCheckPlugin";