@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
@@ -11,12 +11,16 @@ exports.ConsentApp = exports.consentResponsePopulatePaths = void 0;
11
11
  const express_1 = require("express");
12
12
  const luxon_1 = require("luxon");
13
13
  const api_1 = require("./api");
14
+ const record_1 = require("./audit/record");
14
15
  const auth_1 = require("./auth");
16
+ const consentStatus_1 = require("./consentStatus");
15
17
  const errors_1 = require("./errors");
16
18
  const logger_1 = require("./logger");
17
19
  const consentForm_1 = require("./models/consentForm");
18
20
  const consentResponse_1 = require("./models/consentResponse");
19
21
  const permissions_1 = require("./permissions");
22
+ const utils_1 = require("./utils");
23
+ const zodOpenApi_1 = require("./zodOpenApi");
20
24
  /** Shared populate config for consent response list/read endpoints. */
21
25
  exports.consentResponsePopulatePaths = [
22
26
  {
@@ -27,12 +31,131 @@ exports.consentResponsePopulatePaths = [
27
31
  fields: ["name", "email"],
28
32
  path: "userId",
29
33
  },
34
+ {
35
+ fields: ["name", "email"],
36
+ path: "provisionalSignedBy",
37
+ },
30
38
  ];
39
+ const PROVISIONAL_NOTE_MAX_LENGTH = 2000;
40
+ const provisionalSignBody = zodOpenApi_1.z
41
+ .object({
42
+ consentFormId: zodOpenApi_1.z.string().min(1, "consentFormId is required"),
43
+ locale: zodOpenApi_1.z.string().min(1).optional(),
44
+ note: zodOpenApi_1.z
45
+ .string()
46
+ .trim()
47
+ .min(1, "note is required")
48
+ .max(PROVISIONAL_NOTE_MAX_LENGTH, `note must be at most ${PROVISIONAL_NOTE_MAX_LENGTH} characters`),
49
+ userId: zodOpenApi_1.z.string().min(1, "userId is required"),
50
+ })
51
+ .strict();
52
+ const voidProvisionalBody = zodOpenApi_1.z
53
+ .object({
54
+ reason: zodOpenApi_1.z
55
+ .string()
56
+ .trim()
57
+ .min(1, "reason is required")
58
+ .max(PROVISIONAL_NOTE_MAX_LENGTH, `reason must be at most ${PROVISIONAL_NOTE_MAX_LENGTH} characters`),
59
+ })
60
+ .strict();
61
+ const voidedByPopulate = { path: "voidedBy", select: "name email" };
62
+ const consentStatusQuery = zodOpenApi_1.z.object({ userId: zodOpenApi_1.z.string().min(1, "userId is required") });
63
+ const consentStatusSigner = zodOpenApi_1.z.object({
64
+ email: zodOpenApi_1.z.string().optional(),
65
+ id: zodOpenApi_1.z.string(),
66
+ name: zodOpenApi_1.z.string().optional(),
67
+ });
68
+ /** OpenAPI shape of `ConsentStatusRow`, so generated SDKs type the status rows. */
69
+ const consentStatusRows = zodOpenApi_1.z.array(zodOpenApi_1.z.object({
70
+ form: zodOpenApi_1.z
71
+ .object({
72
+ _id: zodOpenApi_1.z.string(),
73
+ content: zodOpenApi_1.z.record(zodOpenApi_1.z.string(), zodOpenApi_1.z.string()),
74
+ id: zodOpenApi_1.z.string(),
75
+ slug: zodOpenApi_1.z.string(),
76
+ title: zodOpenApi_1.z.string(),
77
+ type: zodOpenApi_1.z.string(),
78
+ version: zodOpenApi_1.z.number(),
79
+ })
80
+ .passthrough(),
81
+ isConsented: zodOpenApi_1.z.boolean(),
82
+ provisional: zodOpenApi_1.z
83
+ .object({
84
+ note: zodOpenApi_1.z.string().optional(),
85
+ responseId: zodOpenApi_1.z.string(),
86
+ signedAt: zodOpenApi_1.z.string(),
87
+ signedBy: consentStatusSigner.nullable(),
88
+ })
89
+ .optional(),
90
+ respondedAt: zodOpenApi_1.z.string().optional(),
91
+ status: zodOpenApi_1.z.enum(["pending", "provisional", "signed", "declined"]),
92
+ }));
93
+ const consentResponseUser = zodOpenApi_1.z
94
+ .object({
95
+ _id: zodOpenApi_1.z.string(),
96
+ email: zodOpenApi_1.z.string().optional(),
97
+ id: zodOpenApi_1.z.string().optional(),
98
+ name: zodOpenApi_1.z.string().optional(),
99
+ })
100
+ .passthrough();
101
+ /** OpenAPI shape of the provisional `ConsentResponse` the sign and void actions return. */
102
+ const provisionalConsentResponse = zodOpenApi_1.z
103
+ .object({
104
+ _id: zodOpenApi_1.z.string(),
105
+ agreed: zodOpenApi_1.z.boolean(),
106
+ agreedAt: zodOpenApi_1.z.string(),
107
+ consentFormId: zodOpenApi_1.z.string(),
108
+ contentSnapshot: zodOpenApi_1.z.string().optional(),
109
+ formVersionSnapshot: zodOpenApi_1.z.number().optional(),
110
+ id: zodOpenApi_1.z.string(),
111
+ locale: zodOpenApi_1.z.string(),
112
+ provisional: zodOpenApi_1.z.boolean(),
113
+ provisionalNote: zodOpenApi_1.z.string().optional(),
114
+ provisionalSignedBy: consentResponseUser,
115
+ userId: zodOpenApi_1.z.string(),
116
+ voidedAt: zodOpenApi_1.z.string().optional(),
117
+ voidedBy: consentResponseUser.optional(),
118
+ voidReason: zodOpenApi_1.z.string().optional(),
119
+ })
120
+ .passthrough();
31
121
  const requireAdmin = (user) => {
32
122
  if (!user?.admin) {
33
123
  throw new errors_1.APIError({ status: 403, title: "Admin access required" });
34
124
  }
35
125
  };
126
+ /** The populated provisional signer, or null when unset or not populated. */
127
+ const populatedSigner = (value) => {
128
+ if (!value || typeof value !== "object" || !("_id" in value)) {
129
+ return null;
130
+ }
131
+ return value;
132
+ };
133
+ const signerDisplayName = (signer) => {
134
+ return signer?.name || signer?.email || "Staff";
135
+ };
136
+ /** The id of a ref that may or may not be populated. */
137
+ const idOf = (value) => {
138
+ if (value && typeof value === "object" && "_id" in value) {
139
+ return String(value._id);
140
+ }
141
+ return String(value);
142
+ };
143
+ /** Best-effort AuditEvent for sign-on-behalf actions; a no-op unless AuditApp is registered. */
144
+ const recordConsentAudit = ({ action, actorId, consentFormId, operation, recordId, recordLabel, userId, verb, }) => {
145
+ if (!(0, record_1.isAuditRecorderInstalled)()) {
146
+ return;
147
+ }
148
+ void (0, record_1.recordAuditEvent)({
149
+ actorId,
150
+ after: { action, userId, ...(consentFormId ? { consentFormId } : {}) },
151
+ modelName: "ConsentResponse",
152
+ operation,
153
+ recordId,
154
+ recordLabel,
155
+ source: "modelRouter",
156
+ verb,
157
+ });
158
+ };
36
159
  class ConsentApp {
37
160
  options;
38
161
  constructor(options = {}) {
@@ -122,12 +245,13 @@ class ConsentApp {
122
245
  displayName: "Consent Responses",
123
246
  filters: [
124
247
  { field: "agreed", kind: "boolean", label: "Agreed" },
248
+ { field: "provisional", kind: "boolean", label: "Provisional" },
125
249
  { field: "locale", kind: "text", label: "Locale" },
126
250
  ],
127
251
  group: "Compliance",
128
- listFields: ["userId", "agreed", "locale", "agreedAt"],
252
+ listFields: ["userId", "agreed", "provisional", "locale", "agreedAt"],
129
253
  searchFields: ["locale"],
130
- sortableFields: ["agreed", "locale", "agreedAt", "created"],
254
+ sortableFields: ["agreed", "provisional", "locale", "agreedAt", "created"],
131
255
  },
132
256
  model: consentResponse_1.ConsentResponse,
133
257
  populatePaths: exports.consentResponsePopulatePaths,
@@ -136,8 +260,15 @@ class ConsentApp {
136
260
  ],
137
261
  };
138
262
  }
139
- register(app) {
140
- const { auditTrail, resolveConsentForms, aiConfig } = this.options;
263
+ register(app, openApi) {
264
+ const { accessControl, auditTrail, resolveConsentForms, aiConfig } = this.options;
265
+ if (!accessControl) {
266
+ logger_1.logger.warn("ConsentApp registered without accessControl; only admins may sign consent on behalf of other users");
267
+ }
268
+ const canSignOnBehalf = accessControl
269
+ ? accessControl.permission({ consentResponse: ["signOnBehalf"] })
270
+ : permissions_1.Permissions.IsAdmin;
271
+ const signOnBehalfPermissions = [permissions_1.Permissions.IsAuthenticated, canSignOnBehalf];
141
272
  const collectionActions = {};
142
273
  if (aiConfig) {
143
274
  collectionActions.generate = {
@@ -239,8 +370,163 @@ class ConsentApp {
239
370
  queryFields: ["slug", "type", "active", "version"],
240
371
  sort: "order",
241
372
  }));
242
- // Admin read-only access to consent responses
373
+ // Admin read-only access to consent responses, plus provisional signing actions
243
374
  app.use("/consent-responses", (0, api_1.modelRouter)(consentResponse_1.ConsentResponse, {
375
+ // Documented in OpenAPI so client SDKs get the provisional signing actions. The admin
376
+ // list and read routes are documented too; they are the same admin-only CRUD reads.
377
+ ...(openApi ? { openApi: openApi } : {}),
378
+ collectionActions: {
379
+ provisional: {
380
+ body: provisionalSignBody,
381
+ description: "Record that another user agreed to a consent form on the target user's behalf. " +
382
+ "The form stays in the target user's pending list until they respond themselves.",
383
+ handler: async ({ body, req, user }) => {
384
+ const signer = user;
385
+ const { consentFormId, locale, note, userId } = body;
386
+ if (!(0, utils_1.isValidObjectId)(consentFormId)) {
387
+ throw new errors_1.APIError({ status: 400, title: "consentFormId is invalid" });
388
+ }
389
+ if (String(signer.id) === userId) {
390
+ throw new errors_1.APIError({ status: 400, title: "Cannot sign provisionally for yourself" });
391
+ }
392
+ const targetUser = await (0, consentStatus_1.loadConsentTargetUser)(userId);
393
+ const form = await consentForm_1.ConsentForm.findOneOrNone({ _id: consentFormId });
394
+ if (!form) {
395
+ throw new errors_1.APIError({ status: 404, title: "Consent form not found" });
396
+ }
397
+ if (!form.active) {
398
+ throw new errors_1.APIError({ status: 400, title: "Consent form is not active" });
399
+ }
400
+ const { resolvedForms } = await (0, consentStatus_1.resolveFormsForUser)(targetUser, resolveConsentForms);
401
+ if (!resolvedForms.some((resolved) => resolved._id.equals(form._id))) {
402
+ throw new errors_1.APIError({
403
+ status: 400,
404
+ title: "Consent form does not apply to this user",
405
+ });
406
+ }
407
+ const responseLocale = locale ?? form.defaultLocale;
408
+ const responseData = {
409
+ agreed: true,
410
+ agreedAt: luxon_1.DateTime.now().toJSDate(),
411
+ consentFormId: form._id,
412
+ formVersionSnapshot: form.version,
413
+ locale: responseLocale,
414
+ provisional: true,
415
+ provisionalNote: note,
416
+ provisionalSignedBy: signer.id,
417
+ userId,
418
+ };
419
+ if (auditTrail) {
420
+ responseData.contentSnapshot =
421
+ form.content.get(responseLocale) ?? form.content.get(form.defaultLocale);
422
+ responseData.provisionalSignerIp = req.ip;
423
+ responseData.provisionalSignerUserAgent = req.headers["user-agent"];
424
+ }
425
+ const response = await consentResponse_1.ConsentResponse.create(responseData);
426
+ recordConsentAudit({
427
+ action: "signOnBehalf",
428
+ actorId: String(signer.id),
429
+ consentFormId: form._id.toString(),
430
+ operation: "create",
431
+ recordId: response._id.toString(),
432
+ recordLabel: form.title,
433
+ userId,
434
+ verb: "created",
435
+ });
436
+ logger_1.logger.info("Provisional consent recorded", {
437
+ consentFormId: form._id.toString(),
438
+ signerId: String(signer.id),
439
+ userId,
440
+ });
441
+ return response.populate(consentStatus_1.provisionalSignerPopulate);
442
+ },
443
+ method: "POST",
444
+ permissions: signOnBehalfPermissions,
445
+ response: provisionalConsentResponse,
446
+ summary: "Sign a consent form provisionally on behalf of another user",
447
+ },
448
+ status: {
449
+ description: "Consent status of every form that applies to a user: pending, provisional, " +
450
+ "signed, or declined. Provisional counts as consented.",
451
+ handler: async ({ query, user }) => {
452
+ const { userId } = query;
453
+ const rows = await (0, consentStatus_1.getConsentStatuses)({ resolveConsentForms, userId });
454
+ recordConsentAudit({
455
+ action: "viewStatus",
456
+ actorId: String(user.id),
457
+ operation: "read",
458
+ recordLabel: "Consent status",
459
+ userId,
460
+ verb: "viewed",
461
+ });
462
+ return rows;
463
+ },
464
+ method: "GET",
465
+ permissions: signOnBehalfPermissions,
466
+ query: consentStatusQuery,
467
+ response: consentStatusRows,
468
+ summary: "List a user's consent status for each form",
469
+ },
470
+ },
471
+ instanceActions: {
472
+ void: {
473
+ body: voidProvisionalBody,
474
+ description: "Mark a provisional signature made in error as void. The record is kept for audit " +
475
+ "and no longer counts as consent.",
476
+ handler: async ({ body, doc, user }) => {
477
+ const response = doc;
478
+ const { reason } = body;
479
+ if (!response.provisional) {
480
+ throw new errors_1.APIError({
481
+ status: 400,
482
+ title: "Only provisional signatures can be voided",
483
+ });
484
+ }
485
+ if (response.voidedAt) {
486
+ throw new errors_1.APIError({
487
+ status: 400,
488
+ title: "Provisional signature is already voided",
489
+ });
490
+ }
491
+ const actorId = String(user.id);
492
+ const voided = await consentResponse_1.ConsentResponse.findOneAndUpdate({ _id: response._id, voidedAt: null }, {
493
+ $set: {
494
+ voidedAt: luxon_1.DateTime.now().toJSDate(),
495
+ voidedBy: actorId,
496
+ voidReason: reason,
497
+ },
498
+ }, { returnDocument: "after" });
499
+ if (!voided) {
500
+ throw new errors_1.APIError({
501
+ status: 400,
502
+ title: "Provisional signature is already voided",
503
+ });
504
+ }
505
+ const targetUserId = idOf(response.userId);
506
+ const consentFormId = idOf(response.consentFormId);
507
+ recordConsentAudit({
508
+ action: "voidProvisional",
509
+ actorId,
510
+ consentFormId,
511
+ operation: "update",
512
+ recordId: response._id.toString(),
513
+ userId: targetUserId,
514
+ verb: "updated",
515
+ });
516
+ logger_1.logger.info("Provisional consent voided", {
517
+ consentFormId,
518
+ responseId: response._id.toString(),
519
+ userId: targetUserId,
520
+ voidedBy: actorId,
521
+ });
522
+ return voided.populate([consentStatus_1.provisionalSignerPopulate, voidedByPopulate]);
523
+ },
524
+ method: "POST",
525
+ permissions: signOnBehalfPermissions,
526
+ response: provisionalConsentResponse,
527
+ summary: "Void a provisional consent signature",
528
+ },
529
+ },
244
530
  permissions: {
245
531
  create: [],
246
532
  delete: [],
@@ -259,10 +545,8 @@ class ConsentApp {
259
545
  throw new errors_1.APIError({ status: 401, title: "Authentication required" });
260
546
  }
261
547
  logger_1.logger.debug("Fetching pending consent forms", { userId: user.id });
262
- const activeForms = await consentForm_1.ConsentForm.find({ active: true }).sort({ order: 1 });
263
- let resolvedForms;
548
+ const { activeForms, resolvedForms } = await (0, consentStatus_1.resolveFormsForUser)(user, resolveConsentForms);
264
549
  if (resolveConsentForms) {
265
- resolvedForms = await resolveConsentForms(user, activeForms);
266
550
  logger_1.logger.debug("resolveConsentForms applied", {
267
551
  activeFormCount: activeForms.length,
268
552
  resolvedFormCount: resolvedForms.length,
@@ -270,21 +554,12 @@ class ConsentApp {
270
554
  userId: user.id,
271
555
  });
272
556
  }
273
- else {
274
- resolvedForms = activeForms;
275
- }
276
- const existingResponses = await consentResponse_1.ConsentResponse.find({ userId: user.id });
277
- const respondedFormVersions = new Map();
278
- for (const response of existingResponses) {
279
- const formId = response.consentFormId.toString();
280
- respondedFormVersions.set(formId, response.formVersionSnapshot ?? 0);
281
- }
282
- const respondedFormIds = existingResponses.map((r) => r.consentFormId);
283
- const respondedForms = await consentForm_1.ConsentForm.find({ _id: { $in: respondedFormIds } });
284
- const formVersionByFormId = new Map();
285
- for (const form of respondedForms) {
286
- formVersionByFormId.set(form._id.toString(), form.version);
287
- }
557
+ // Only the user's own responses clear a form. A provisional signature counts as
558
+ // consent for compliance, but the user still sees and signs the form themselves.
559
+ const existingResponses = await consentResponse_1.ConsentResponse.find({
560
+ provisional: { $ne: true },
561
+ userId: user.id,
562
+ });
288
563
  const pendingForms = resolvedForms.filter((form) => {
289
564
  const formId = form._id.toString();
290
565
  const matchingResponses = existingResponses.filter((r) => r.consentFormId.toString() === formId);
@@ -293,6 +568,30 @@ class ConsentApp {
293
568
  }
294
569
  return !matchingResponses.some((r) => r.formVersionSnapshot === form.version);
295
570
  });
571
+ // The user sees who signed provisionally and when, never the signer's note.
572
+ const provisionalResponses = await consentResponse_1.ConsentResponse.find({
573
+ consentFormId: { $in: pendingForms.map((form) => form._id) },
574
+ provisional: true,
575
+ userId: user.id,
576
+ voidedAt: null,
577
+ })
578
+ .sort({ agreedAt: -1 })
579
+ .populate(consentStatus_1.provisionalSignerPopulate);
580
+ const pendingData = pendingForms.map((form) => {
581
+ const latest = provisionalResponses.find((response) => response.consentFormId.toString() === form._id.toString() &&
582
+ response.formVersionSnapshot === form.version);
583
+ const formJson = form.toJSON();
584
+ if (!latest) {
585
+ return formJson;
586
+ }
587
+ return {
588
+ ...formJson,
589
+ provisionalSignature: {
590
+ signedAt: latest.agreedAt,
591
+ signedByName: signerDisplayName(populatedSigner(latest.provisionalSignedBy)),
592
+ },
593
+ };
594
+ });
296
595
  const filteredOutByResolverCount = Math.max(activeForms.length - resolvedForms.length, 0);
297
596
  const filteredOutByResponsesCount = Math.max(resolvedForms.length - pendingForms.length, 0);
298
597
  logger_1.logger.info("Pending consent forms fetched", {
@@ -305,7 +604,7 @@ class ConsentApp {
305
604
  userAdmin: Boolean(user.admin),
306
605
  userId: user.id,
307
606
  });
308
- return res.json({ data: pendingForms });
607
+ return res.json({ data: pendingData });
309
608
  }));
310
609
  // POST /consents/respond - submit a consent response
311
610
  router.post("/respond", (0, auth_1.authenticateMiddleware)(), (0, api_1.asyncHandler)(async (req, res) => {
@@ -384,7 +683,9 @@ class ConsentApp {
384
683
  if (!user) {
385
684
  throw new errors_1.APIError({ status: 401, title: "Authentication required" });
386
685
  }
387
- const responses = await consentResponse_1.ConsentResponse.find({ userId: user.id }).sort({ agreedAt: -1 });
686
+ const responses = await consentResponse_1.ConsentResponse.find({ userId: user.id })
687
+ .sort({ agreedAt: -1 })
688
+ .populate(consentStatus_1.provisionalSignerPopulate);
388
689
  const formIds = responses.map((r) => r.consentFormId);
389
690
  const forms = await consentForm_1.ConsentForm.find({ _id: { $in: formIds } });
390
691
  const formMap = new Map(forms.map((f) => [f._id.toString(), f]));
@@ -409,9 +710,15 @@ class ConsentApp {
409
710
  formVersionSnapshot: response.formVersionSnapshot,
410
711
  ipAddress: response.ipAddress,
411
712
  locale: response.locale,
713
+ provisional: Boolean(response.provisional),
714
+ // Name only: the signer's note and request metadata stay admin-only.
715
+ provisionalSignedBy: response.provisional
716
+ ? { name: signerDisplayName(populatedSigner(response.provisionalSignedBy)) }
717
+ : null,
412
718
  signature: response.signature,
413
719
  signedAt: response.signedAt,
414
720
  userAgent: response.userAgent,
721
+ voidedAt: response.voidedAt,
415
722
  };
416
723
  });
417
724
  return res.json({ data });
@@ -422,9 +729,10 @@ class ConsentApp {
422
729
  if (!user?.admin) {
423
730
  throw new errors_1.APIError({ status: 403, title: "Admin access required" });
424
731
  }
425
- const responses = await consentResponse_1.ConsentResponse.find({ userId: req.params.userId }).sort({
426
- agreedAt: -1,
427
- });
732
+ const responses = await consentResponse_1.ConsentResponse.find({ userId: req.params.userId })
733
+ .sort({ agreedAt: -1 })
734
+ .populate(consentStatus_1.provisionalSignerPopulate)
735
+ .populate(voidedByPopulate);
428
736
  const formIds = responses.map((r) => r.consentFormId);
429
737
  const forms = await consentForm_1.ConsentForm.find({ _id: { $in: formIds } });
430
738
  const formMap = new Map(forms.map((f) => [f._id.toString(), f]));
@@ -445,9 +753,17 @@ class ConsentApp {
445
753
  formVersionSnapshot: response.formVersionSnapshot,
446
754
  ipAddress: response.ipAddress,
447
755
  locale: response.locale,
756
+ provisional: Boolean(response.provisional),
757
+ provisionalNote: response.provisionalNote,
758
+ provisionalSignedBy: populatedSigner(response.provisionalSignedBy),
759
+ provisionalSignerIp: response.provisionalSignerIp,
760
+ provisionalSignerUserAgent: response.provisionalSignerUserAgent,
448
761
  responseId: response._id,
449
762
  signedAt: response.signedAt,
450
763
  userAgent: response.userAgent,
764
+ voidedAt: response.voidedAt,
765
+ voidedBy: populatedSigner(response.voidedBy),
766
+ voidReason: response.voidReason,
451
767
  };
452
768
  });
453
769
  return res.json({ data: auditEntries });
@@ -0,0 +1,60 @@
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
+ import type { User } from "./auth";
6
+ import type { ConsentFormDocument } from "./types/consentForm";
7
+ export type ResolveConsentForms = (user: User, forms: ConsentFormDocument[]) => ConsentFormDocument[] | Promise<ConsentFormDocument[]>;
8
+ export type ConsentStatus = "pending" | "provisional" | "signed" | "declined";
9
+ /** A consent form as serialized to clients (`toJSON` with maps flattened). */
10
+ export interface ConsentStatusForm {
11
+ _id: string;
12
+ id: string;
13
+ title: string;
14
+ slug: string;
15
+ version: number;
16
+ type: string;
17
+ content: Record<string, string>;
18
+ [field: string]: unknown;
19
+ }
20
+ export interface ConsentStatusSigner {
21
+ id: string;
22
+ name?: string;
23
+ email?: string;
24
+ }
25
+ export interface ConsentStatusProvisional {
26
+ responseId: string;
27
+ signedAt: Date;
28
+ signedBy: ConsentStatusSigner | null;
29
+ note?: string;
30
+ }
31
+ export interface ConsentStatusRow {
32
+ form: ConsentStatusForm;
33
+ status: ConsentStatus;
34
+ isConsented: boolean;
35
+ respondedAt?: Date;
36
+ /** The latest provisional signature for the current version, whatever the status. */
37
+ provisional?: ConsentStatusProvisional;
38
+ }
39
+ /** Fields returned for the provisional signer on provisional consent responses. */
40
+ export declare const provisionalSignerPopulate: {
41
+ path: string;
42
+ select: string;
43
+ };
44
+ /** Load the consent forms that apply to a user: active forms, narrowed by the app's resolver. */
45
+ export declare const resolveFormsForUser: (user: User, resolveConsentForms?: ResolveConsentForms) => Promise<{
46
+ activeForms: ConsentFormDocument[];
47
+ resolvedForms: ConsentFormDocument[];
48
+ }>;
49
+ /** Load a user by id, or throw 400 for a malformed id and 404 for an unknown one. */
50
+ export declare const loadConsentTargetUser: (userId: string) => Promise<User>;
51
+ /**
52
+ * Consent status for every active form that applies to the user, in form order. Only
53
+ * non-voided responses to each form's current version count. The user's own latest response decides
54
+ * (`signed` or `declined`); otherwise a provisional signature makes it `provisional`, which
55
+ * counts as consented; otherwise `pending`.
56
+ */
57
+ export declare const getConsentStatuses: ({ userId, resolveConsentForms, }: {
58
+ userId: string;
59
+ resolveConsentForms?: ResolveConsentForms;
60
+ }) => Promise<ConsentStatusRow[]>;
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ /**
3
+ * Consent status per form for one user: the "considered signed" contract apps build on.
4
+ * A provisional signature counts as consented until the user answers the form themselves.
5
+ */
6
+ var __importDefault = (this && this.__importDefault) || function (mod) {
7
+ return (mod && mod.__esModule) ? mod : { "default": mod };
8
+ };
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.getConsentStatuses = exports.loadConsentTargetUser = exports.resolveFormsForUser = exports.provisionalSignerPopulate = void 0;
11
+ const mongoose_1 = __importDefault(require("mongoose"));
12
+ const errors_1 = require("./errors");
13
+ const consentForm_1 = require("./models/consentForm");
14
+ const consentResponse_1 = require("./models/consentResponse");
15
+ const plugins_1 = require("./plugins");
16
+ const utils_1 = require("./utils");
17
+ /** Fields returned for the provisional signer on provisional consent responses. */
18
+ exports.provisionalSignerPopulate = { path: "provisionalSignedBy", select: "name email" };
19
+ /** Load the consent forms that apply to a user: active forms, narrowed by the app's resolver. */
20
+ const resolveFormsForUser = async (user, resolveConsentForms) => {
21
+ const activeForms = await consentForm_1.ConsentForm.find({ active: true }).sort({ order: 1 });
22
+ if (!resolveConsentForms) {
23
+ return { activeForms, resolvedForms: activeForms };
24
+ }
25
+ const resolvedForms = await resolveConsentForms(user, activeForms);
26
+ return { activeForms, resolvedForms };
27
+ };
28
+ exports.resolveFormsForUser = resolveFormsForUser;
29
+ /** Load a user by id, or throw 400 for a malformed id and 404 for an unknown one. */
30
+ const loadConsentTargetUser = async (userId) => {
31
+ if (!(0, utils_1.isValidObjectId)(userId)) {
32
+ throw new errors_1.APIError({ status: 400, title: "userId is invalid" });
33
+ }
34
+ const user = await (0, plugins_1.findOneOrNoneFor)(mongoose_1.default.model("User"), { _id: userId });
35
+ if (!user) {
36
+ throw new errors_1.APIError({ status: 404, title: "User not found" });
37
+ }
38
+ return user;
39
+ };
40
+ exports.loadConsentTargetUser = loadConsentTargetUser;
41
+ const toSigner = (value) => {
42
+ if (!value || typeof value !== "object" || !("_id" in value)) {
43
+ return null;
44
+ }
45
+ const signer = value;
46
+ return { email: signer.email, id: signer._id.toString(), name: signer.name };
47
+ };
48
+ const statusForResponses = (responses) => {
49
+ // Responses arrive newest first, so the first match is the latest.
50
+ const own = responses.find((response) => !response.provisional);
51
+ const provisional = responses.find((response) => response.provisional);
52
+ const provisionalSummary = provisional
53
+ ? {
54
+ note: provisional.provisionalNote,
55
+ responseId: provisional._id.toString(),
56
+ signedAt: provisional.agreedAt,
57
+ signedBy: toSigner(provisional.provisionalSignedBy),
58
+ }
59
+ : undefined;
60
+ if (own) {
61
+ return {
62
+ isConsented: own.agreed,
63
+ provisional: provisionalSummary,
64
+ respondedAt: own.agreedAt,
65
+ status: own.agreed ? "signed" : "declined",
66
+ };
67
+ }
68
+ if (provisional) {
69
+ return {
70
+ isConsented: true,
71
+ provisional: provisionalSummary,
72
+ respondedAt: provisional.agreedAt,
73
+ status: "provisional",
74
+ };
75
+ }
76
+ return { isConsented: false, status: "pending" };
77
+ };
78
+ /**
79
+ * Consent status for every active form that applies to the user, in form order. Only
80
+ * non-voided responses to each form's current version count. The user's own latest response decides
81
+ * (`signed` or `declined`); otherwise a provisional signature makes it `provisional`, which
82
+ * counts as consented; otherwise `pending`.
83
+ */
84
+ const getConsentStatuses = async ({ userId, resolveConsentForms, }) => {
85
+ const user = await (0, exports.loadConsentTargetUser)(userId);
86
+ const { resolvedForms } = await (0, exports.resolveFormsForUser)(user, resolveConsentForms);
87
+ const responses = await consentResponse_1.ConsentResponse.find({
88
+ consentFormId: { $in: resolvedForms.map((form) => form._id) },
89
+ userId,
90
+ voidedAt: null,
91
+ })
92
+ .sort({ agreedAt: -1 })
93
+ .populate(exports.provisionalSignerPopulate);
94
+ return resolvedForms.map((form) => {
95
+ const current = responses.filter((response) => response.consentFormId.toString() === form._id.toString() &&
96
+ response.formVersionSnapshot === form.version);
97
+ const row = {
98
+ // A JSON round trip gives the same shape clients receive: string ids, flattened maps.
99
+ form: JSON.parse(JSON.stringify(form)),
100
+ ...statusForResponses(current),
101
+ };
102
+ if (!row.provisional) {
103
+ delete row.provisional;
104
+ }
105
+ if (!row.respondedAt) {
106
+ delete row.respondedAt;
107
+ }
108
+ return row;
109
+ });
110
+ };
111
+ exports.getConsentStatuses = getConsentStatuses;
package/dist/errors.d.ts CHANGED
@@ -159,6 +159,12 @@ export declare const apiUnauthorizedMiddleware: (err: Error, _req: Request, res:
159
159
  * Converts Mongoose validation/cast errors into client-friendly APIErrors.
160
160
  */
161
161
  export declare const mongooseErrorToAPIError: (err: Error) => APIError | null;
162
+ /**
163
+ * Converts a body-parser client error (malformed JSON, oversized body, unsupported charset) into
164
+ * an APIError with the parser's 4xx status. Returns null for anything else, including parser
165
+ * errors body-parser marks as not exposable (server faults).
166
+ */
167
+ export declare const bodyParserErrorToAPIError: (err: Error) => APIError | null;
162
168
  /**
163
169
  * Picks the error to throw for something caught in a hook, transformer, or Mongoose middleware.
164
170
  * An `APIError` is passed through untouched so its status, code, detail, and meta reach the client;