@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.
- package/CHANGELOG.md +2071 -2
- package/dist/accountSecurity/accessActions.d.ts +38 -0
- package/dist/accountSecurity/accessActions.js +157 -0
- package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
- package/dist/accountSecurity/accountSecurityApp.js +438 -0
- package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
- package/dist/accountSecurity/accountSecurityService.js +481 -0
- package/dist/accountSecurity/credentialActions.d.ts +16 -0
- package/dist/accountSecurity/credentialActions.js +189 -0
- package/dist/accountSecurity/membershipActions.d.ts +15 -0
- package/dist/accountSecurity/membershipActions.js +81 -0
- package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
- package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
- package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
- package/dist/accountSecurity/securityEventHooks.js +223 -0
- package/dist/accountSecurity/securityEvents.d.ts +162 -0
- package/dist/accountSecurity/securityEvents.js +114 -0
- package/dist/accountSecurity/securityNotifications.d.ts +125 -0
- package/dist/accountSecurity/securityNotifications.js +333 -0
- package/dist/api.js +38 -6
- package/dist/audit/auditEventModel.d.ts +5 -3
- package/dist/audit/auditEventModel.js +8 -6
- package/dist/audit/processQueue.js +4 -2
- package/dist/audit/record.d.ts +2 -2
- package/dist/audit/record.js +3 -0
- package/dist/authRecovery.js +29 -1
- package/dist/betterAuth.d.ts +179 -10
- package/dist/betterAuthApp.d.ts +15 -0
- package/dist/betterAuthApp.js +23 -0
- package/dist/betterAuthChallengeHeaders.d.ts +37 -0
- package/dist/betterAuthChallengeHeaders.js +180 -0
- package/dist/betterAuthFeatures.d.ts +54 -0
- package/dist/betterAuthFeatures.js +239 -0
- package/dist/betterAuthMethods.d.ts +73 -0
- package/dist/betterAuthMethods.js +55 -0
- package/dist/betterAuthOAuthHandoff.d.ts +10 -2
- package/dist/betterAuthOAuthHandoff.js +222 -24
- package/dist/betterAuthSetPassword.d.ts +33 -0
- package/dist/betterAuthSetPassword.js +166 -0
- package/dist/betterAuthSetup.d.ts +57 -8
- package/dist/betterAuthSetup.js +327 -36
- package/dist/consentApp.d.ts +9 -4
- package/dist/consentApp.js +344 -28
- package/dist/consentStatus.d.ts +60 -0
- package/dist/consentStatus.js +111 -0
- package/dist/errors.d.ts +6 -0
- package/dist/errors.js +41 -2
- package/dist/expressServer.js +3 -2
- package/dist/index.d.ts +14 -2
- package/dist/index.js +23 -3
- package/dist/mcp/oauth.js +151 -11
- package/dist/mcp/oauthMetadata.d.ts +2 -1
- package/dist/mcp/oauthMetadata.js +7 -4
- package/dist/models/consentResponse.js +51 -0
- package/dist/models/mcpOAuthClient.js +78 -2
- package/dist/models/mcpOAuthToken.js +28 -4
- package/dist/orgs/membershipGuards.d.ts +7 -0
- package/dist/orgs/membershipGuards.js +32 -0
- package/dist/orgs/orgsApp.d.ts +19 -1
- package/dist/orgs/orgsApp.js +55 -24
- package/dist/rateLimit/policies.js +8 -0
- package/dist/rbac/access.js +2 -1
- package/dist/rbac/resolve.d.ts +9 -1
- package/dist/rbac/resolve.js +21 -16
- package/dist/rbac/roleManager.d.ts +6 -0
- package/dist/rbac/roleManager.js +8 -7
- package/dist/rbac/roleModel.d.ts +1 -0
- package/dist/rbac/roleModel.js +45 -3
- package/dist/rbac/statements.d.ts +2 -2
- package/dist/rbac/statements.js +10 -1
- package/dist/rbac/types.d.ts +6 -0
- package/dist/rbac/userWriteGuards.js +2 -1
- package/dist/schemaMetadata.js +8 -1
- package/dist/seedRunner.js +7 -2
- package/dist/terrenoApp.d.ts +4 -0
- package/dist/terrenoApp.js +15 -0
- package/dist/tests/models.d.ts +5 -0
- package/dist/tests/models.js +8 -0
- package/dist/types/consentResponse.d.ts +8 -0
- package/dist/types/mcpOAuth.d.ts +35 -2
- package/package.json +6 -3
- package/src/__snapshots__/openApi.test.ts.snap +288 -0
- package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
- package/src/accountSecurity/accessActions.test.ts +723 -0
- package/src/accountSecurity/accessActions.ts +173 -0
- package/src/accountSecurity/accountSecurity.test.ts +947 -0
- package/src/accountSecurity/accountSecurityApp.ts +720 -0
- package/src/accountSecurity/accountSecurityService.ts +826 -0
- package/src/accountSecurity/credentialActions.test.ts +867 -0
- package/src/accountSecurity/credentialActions.ts +260 -0
- package/src/accountSecurity/membershipActions.ts +89 -0
- package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
- package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
- package/src/accountSecurity/securityEventHooks.ts +294 -0
- package/src/accountSecurity/securityEvents.ts +165 -0
- package/src/accountSecurity/securityNotifications.test.ts +1323 -0
- package/src/accountSecurity/securityNotifications.ts +516 -0
- package/src/api.arrayOperations.test.ts +71 -0
- package/src/api.ts +38 -7
- package/src/audit/auditEventModel.ts +10 -7
- package/src/audit/processQueue.ts +4 -2
- package/src/audit/record.test.ts +15 -0
- package/src/audit/record.ts +10 -2
- package/src/authRecovery.test.ts +23 -0
- package/src/authRecovery.ts +34 -1
- package/src/authRecoveryBetterAuth.test.ts +169 -0
- package/src/betterAuth.ts +194 -8
- package/src/betterAuthApp.ts +32 -0
- package/src/betterAuthChallengeHeaders.test.ts +476 -0
- package/src/betterAuthChallengeHeaders.ts +227 -0
- package/src/betterAuthFeatures.test.ts +489 -0
- package/src/betterAuthFeatures.ts +283 -0
- package/src/betterAuthLinking.test.ts +844 -0
- package/src/betterAuthMethods.test.ts +138 -0
- package/src/betterAuthMethods.ts +98 -0
- package/src/betterAuthOAuthHandoff.test.ts +482 -69
- package/src/betterAuthOAuthHandoff.ts +293 -33
- package/src/betterAuthOAuthProxy.test.ts +421 -0
- package/src/betterAuthPasswordReset.test.ts +190 -0
- package/src/betterAuthSetPassword.test.ts +378 -0
- package/src/betterAuthSetPassword.ts +213 -0
- package/src/betterAuthSetup.test.ts +39 -7
- package/src/betterAuthSetup.ts +457 -38
- package/src/consentApp.test.ts +869 -2
- package/src/consentApp.ts +438 -36
- package/src/consentStatus.test.ts +226 -0
- package/src/consentStatus.ts +171 -0
- package/src/errors.test.ts +81 -0
- package/src/errors.ts +50 -1
- package/src/expressServer.test.ts +29 -0
- package/src/expressServer.ts +3 -2
- package/src/index.ts +30 -0
- package/src/mcp/oauth.test.ts +463 -2
- package/src/mcp/oauth.ts +184 -13
- package/src/mcp/oauthMetadata.ts +5 -2
- package/src/models/consentResponse.ts +53 -0
- package/src/models/mcpOAuthClient.ts +100 -3
- package/src/models/mcpOAuthToken.ts +30 -5
- package/src/orgs/membershipGuards.ts +39 -0
- package/src/orgs/orgRbac.test.ts +1 -1
- package/src/orgs/orgsApp.test.ts +101 -2
- package/src/orgs/orgsApp.ts +69 -28
- package/src/rateLimit/policies.test.ts +53 -0
- package/src/rateLimit/policies.ts +8 -0
- package/src/rbac/access.ts +4 -1
- package/src/rbac/resolve.test.ts +65 -0
- package/src/rbac/resolve.ts +37 -17
- package/src/rbac/roleManager.test.ts +64 -0
- package/src/rbac/roleManager.ts +15 -6
- package/src/rbac/roleModel.test.ts +174 -1
- package/src/rbac/roleModel.ts +66 -3
- package/src/rbac/routes.test.ts +58 -0
- package/src/rbac/statements.test.ts +4 -1
- package/src/rbac/statements.ts +11 -1
- package/src/rbac/types.ts +6 -1
- package/src/rbac/userWriteGuards.test.ts +48 -0
- package/src/rbac/userWriteGuards.ts +5 -2
- package/src/schemaMetadata.test.ts +39 -0
- package/src/schemaMetadata.ts +11 -1
- package/src/seedRunner.test.ts +56 -0
- package/src/seedRunner.ts +7 -2
- package/src/terrenoApp.ts +20 -0
- package/src/tests/accountSecurityTestApp.ts +290 -0
- package/src/tests/betterAuthStubs.ts +188 -0
- package/src/tests/mockOidcProvider.ts +105 -0
- package/src/tests/models.ts +13 -0
- package/src/tests/softwareAuthenticator.ts +183 -0
- package/src/types/consentResponse.ts +8 -0
- package/src/types/mcpOAuth.ts +39 -3
package/src/consentApp.ts
CHANGED
|
@@ -8,19 +8,33 @@
|
|
|
8
8
|
|
|
9
9
|
import {type Application, Router} from "express";
|
|
10
10
|
import {DateTime} from "luxon";
|
|
11
|
+
import type mongoose from "mongoose";
|
|
11
12
|
import type {CollectionActionConfig} from "./actions";
|
|
12
13
|
import type {AdminContribution} from "./adminTypes";
|
|
13
|
-
import {asyncHandler, modelRouter} from "./api";
|
|
14
|
+
import {asyncHandler, modelRouter, type OpenApiMiddleware} from "./api";
|
|
15
|
+
import type {AuditEventOperation, AuditEventVerb} from "./audit/auditEventModel";
|
|
16
|
+
import {isAuditRecorderInstalled, recordAuditEvent} from "./audit/record";
|
|
14
17
|
import type {User} from "./auth";
|
|
15
18
|
import {authenticateMiddleware} from "./auth";
|
|
19
|
+
import {
|
|
20
|
+
getConsentStatuses,
|
|
21
|
+
loadConsentTargetUser,
|
|
22
|
+
provisionalSignerPopulate,
|
|
23
|
+
type ResolveConsentForms,
|
|
24
|
+
resolveFormsForUser,
|
|
25
|
+
} from "./consentStatus";
|
|
16
26
|
import {APIError} from "./errors";
|
|
17
27
|
import {logger} from "./logger";
|
|
18
28
|
import {ConsentForm} from "./models/consentForm";
|
|
19
29
|
import {ConsentResponse} from "./models/consentResponse";
|
|
20
|
-
import {Permissions} from "./permissions";
|
|
30
|
+
import {type PermissionMethod, Permissions} from "./permissions";
|
|
21
31
|
import type {PopulatePath} from "./populate";
|
|
32
|
+
import type {AnyTerrenoAccess} from "./rbac/types";
|
|
22
33
|
import type {TerrenoPlugin} from "./terrenoPlugin";
|
|
23
34
|
import type {ConsentFormDocument} from "./types/consentForm";
|
|
35
|
+
import type {ConsentResponseDocument} from "./types/consentResponse";
|
|
36
|
+
import {isValidObjectId} from "./utils";
|
|
37
|
+
import {z} from "./zodOpenApi";
|
|
24
38
|
|
|
25
39
|
/** Shared populate config for consent response list/read endpoints. */
|
|
26
40
|
export const consentResponsePopulatePaths: PopulatePath[] = [
|
|
@@ -32,9 +46,123 @@ export const consentResponsePopulatePaths: PopulatePath[] = [
|
|
|
32
46
|
fields: ["name", "email"],
|
|
33
47
|
path: "userId",
|
|
34
48
|
},
|
|
49
|
+
{
|
|
50
|
+
fields: ["name", "email"],
|
|
51
|
+
path: "provisionalSignedBy",
|
|
52
|
+
},
|
|
35
53
|
];
|
|
36
54
|
|
|
55
|
+
const PROVISIONAL_NOTE_MAX_LENGTH = 2000;
|
|
56
|
+
|
|
57
|
+
const provisionalSignBody = z
|
|
58
|
+
.object({
|
|
59
|
+
consentFormId: z.string().min(1, "consentFormId is required"),
|
|
60
|
+
locale: z.string().min(1).optional(),
|
|
61
|
+
note: z
|
|
62
|
+
.string()
|
|
63
|
+
.trim()
|
|
64
|
+
.min(1, "note is required")
|
|
65
|
+
.max(
|
|
66
|
+
PROVISIONAL_NOTE_MAX_LENGTH,
|
|
67
|
+
`note must be at most ${PROVISIONAL_NOTE_MAX_LENGTH} characters`
|
|
68
|
+
),
|
|
69
|
+
userId: z.string().min(1, "userId is required"),
|
|
70
|
+
})
|
|
71
|
+
.strict();
|
|
72
|
+
|
|
73
|
+
type ProvisionalSignBody = z.infer<typeof provisionalSignBody>;
|
|
74
|
+
|
|
75
|
+
const voidProvisionalBody = z
|
|
76
|
+
.object({
|
|
77
|
+
reason: z
|
|
78
|
+
.string()
|
|
79
|
+
.trim()
|
|
80
|
+
.min(1, "reason is required")
|
|
81
|
+
.max(
|
|
82
|
+
PROVISIONAL_NOTE_MAX_LENGTH,
|
|
83
|
+
`reason must be at most ${PROVISIONAL_NOTE_MAX_LENGTH} characters`
|
|
84
|
+
),
|
|
85
|
+
})
|
|
86
|
+
.strict();
|
|
87
|
+
|
|
88
|
+
type VoidProvisionalBody = z.infer<typeof voidProvisionalBody>;
|
|
89
|
+
|
|
90
|
+
const voidedByPopulate = {path: "voidedBy", select: "name email"};
|
|
91
|
+
|
|
92
|
+
const consentStatusQuery = z.object({userId: z.string().min(1, "userId is required")});
|
|
93
|
+
|
|
94
|
+
type ConsentStatusQuery = z.infer<typeof consentStatusQuery>;
|
|
95
|
+
|
|
96
|
+
const consentStatusSigner = z.object({
|
|
97
|
+
email: z.string().optional(),
|
|
98
|
+
id: z.string(),
|
|
99
|
+
name: z.string().optional(),
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
/** OpenAPI shape of `ConsentStatusRow`, so generated SDKs type the status rows. */
|
|
103
|
+
const consentStatusRows = z.array(
|
|
104
|
+
z.object({
|
|
105
|
+
form: z
|
|
106
|
+
.object({
|
|
107
|
+
_id: z.string(),
|
|
108
|
+
content: z.record(z.string(), z.string()),
|
|
109
|
+
id: z.string(),
|
|
110
|
+
slug: z.string(),
|
|
111
|
+
title: z.string(),
|
|
112
|
+
type: z.string(),
|
|
113
|
+
version: z.number(),
|
|
114
|
+
})
|
|
115
|
+
.passthrough(),
|
|
116
|
+
isConsented: z.boolean(),
|
|
117
|
+
provisional: z
|
|
118
|
+
.object({
|
|
119
|
+
note: z.string().optional(),
|
|
120
|
+
responseId: z.string(),
|
|
121
|
+
signedAt: z.string(),
|
|
122
|
+
signedBy: consentStatusSigner.nullable(),
|
|
123
|
+
})
|
|
124
|
+
.optional(),
|
|
125
|
+
respondedAt: z.string().optional(),
|
|
126
|
+
status: z.enum(["pending", "provisional", "signed", "declined"]),
|
|
127
|
+
})
|
|
128
|
+
);
|
|
129
|
+
|
|
130
|
+
const consentResponseUser = z
|
|
131
|
+
.object({
|
|
132
|
+
_id: z.string(),
|
|
133
|
+
email: z.string().optional(),
|
|
134
|
+
id: z.string().optional(),
|
|
135
|
+
name: z.string().optional(),
|
|
136
|
+
})
|
|
137
|
+
.passthrough();
|
|
138
|
+
|
|
139
|
+
/** OpenAPI shape of the provisional `ConsentResponse` the sign and void actions return. */
|
|
140
|
+
const provisionalConsentResponse = z
|
|
141
|
+
.object({
|
|
142
|
+
_id: z.string(),
|
|
143
|
+
agreed: z.boolean(),
|
|
144
|
+
agreedAt: z.string(),
|
|
145
|
+
consentFormId: z.string(),
|
|
146
|
+
contentSnapshot: z.string().optional(),
|
|
147
|
+
formVersionSnapshot: z.number().optional(),
|
|
148
|
+
id: z.string(),
|
|
149
|
+
locale: z.string(),
|
|
150
|
+
provisional: z.boolean(),
|
|
151
|
+
provisionalNote: z.string().optional(),
|
|
152
|
+
provisionalSignedBy: consentResponseUser,
|
|
153
|
+
userId: z.string(),
|
|
154
|
+
voidedAt: z.string().optional(),
|
|
155
|
+
voidedBy: consentResponseUser.optional(),
|
|
156
|
+
voidReason: z.string().optional(),
|
|
157
|
+
})
|
|
158
|
+
.passthrough();
|
|
159
|
+
|
|
37
160
|
export interface ConsentAppOptions {
|
|
161
|
+
/**
|
|
162
|
+
* RBAC access control. When set, users whose roles grant `consentResponse:signOnBehalf` may
|
|
163
|
+
* record provisional signatures for other users. When unset, only `user.admin` may.
|
|
164
|
+
*/
|
|
165
|
+
accessControl?: AnyTerrenoAccess;
|
|
38
166
|
auditTrail?: boolean;
|
|
39
167
|
aiConfig?: {
|
|
40
168
|
generateContent: (params: {
|
|
@@ -48,10 +176,7 @@ export interface ConsentAppOptions {
|
|
|
48
176
|
toLocale: string;
|
|
49
177
|
}) => Promise<string>;
|
|
50
178
|
};
|
|
51
|
-
resolveConsentForms?:
|
|
52
|
-
user: User,
|
|
53
|
-
forms: ConsentFormDocument[]
|
|
54
|
-
) => ConsentFormDocument[] | Promise<ConsentFormDocument[]>;
|
|
179
|
+
resolveConsentForms?: ResolveConsentForms;
|
|
55
180
|
supportedLocales?: string[];
|
|
56
181
|
}
|
|
57
182
|
|
|
@@ -61,6 +186,67 @@ const requireAdmin = (user: User | undefined): void => {
|
|
|
61
186
|
}
|
|
62
187
|
};
|
|
63
188
|
|
|
189
|
+
interface PopulatedSigner {
|
|
190
|
+
_id: mongoose.Types.ObjectId;
|
|
191
|
+
email?: string;
|
|
192
|
+
name?: string;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** The populated provisional signer, or null when unset or not populated. */
|
|
196
|
+
const populatedSigner = (value: unknown): PopulatedSigner | null => {
|
|
197
|
+
if (!value || typeof value !== "object" || !("_id" in value)) {
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
return value as PopulatedSigner;
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
const signerDisplayName = (signer: PopulatedSigner | null): string => {
|
|
204
|
+
return signer?.name || signer?.email || "Staff";
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
/** The id of a ref that may or may not be populated. */
|
|
208
|
+
const idOf = (value: unknown): string => {
|
|
209
|
+
if (value && typeof value === "object" && "_id" in value) {
|
|
210
|
+
return String((value as {_id: unknown})._id);
|
|
211
|
+
}
|
|
212
|
+
return String(value);
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
/** Best-effort AuditEvent for sign-on-behalf actions; a no-op unless AuditApp is registered. */
|
|
216
|
+
const recordConsentAudit = ({
|
|
217
|
+
action,
|
|
218
|
+
actorId,
|
|
219
|
+
consentFormId,
|
|
220
|
+
operation,
|
|
221
|
+
recordId,
|
|
222
|
+
recordLabel,
|
|
223
|
+
userId,
|
|
224
|
+
verb,
|
|
225
|
+
}: {
|
|
226
|
+
action: "signOnBehalf" | "viewStatus" | "voidProvisional";
|
|
227
|
+
actorId: string;
|
|
228
|
+
consentFormId?: string;
|
|
229
|
+
operation: AuditEventOperation;
|
|
230
|
+
recordId?: string;
|
|
231
|
+
recordLabel?: string;
|
|
232
|
+
userId: string;
|
|
233
|
+
verb: AuditEventVerb;
|
|
234
|
+
}): void => {
|
|
235
|
+
if (!isAuditRecorderInstalled()) {
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
void recordAuditEvent({
|
|
239
|
+
actorId,
|
|
240
|
+
after: {action, userId, ...(consentFormId ? {consentFormId} : {})},
|
|
241
|
+
modelName: "ConsentResponse",
|
|
242
|
+
operation,
|
|
243
|
+
recordId,
|
|
244
|
+
recordLabel,
|
|
245
|
+
source: "modelRouter",
|
|
246
|
+
verb,
|
|
247
|
+
});
|
|
248
|
+
};
|
|
249
|
+
|
|
64
250
|
export class ConsentApp implements TerrenoPlugin {
|
|
65
251
|
private options: ConsentAppOptions;
|
|
66
252
|
|
|
@@ -152,12 +338,13 @@ export class ConsentApp implements TerrenoPlugin {
|
|
|
152
338
|
displayName: "Consent Responses",
|
|
153
339
|
filters: [
|
|
154
340
|
{field: "agreed", kind: "boolean", label: "Agreed"},
|
|
341
|
+
{field: "provisional", kind: "boolean", label: "Provisional"},
|
|
155
342
|
{field: "locale", kind: "text", label: "Locale"},
|
|
156
343
|
],
|
|
157
344
|
group: "Compliance",
|
|
158
|
-
listFields: ["userId", "agreed", "locale", "agreedAt"],
|
|
345
|
+
listFields: ["userId", "agreed", "provisional", "locale", "agreedAt"],
|
|
159
346
|
searchFields: ["locale"],
|
|
160
|
-
sortableFields: ["agreed", "locale", "agreedAt", "created"],
|
|
347
|
+
sortableFields: ["agreed", "provisional", "locale", "agreedAt", "created"],
|
|
161
348
|
},
|
|
162
349
|
model: ConsentResponse as unknown as import("mongoose").Model<unknown>,
|
|
163
350
|
populatePaths: consentResponsePopulatePaths,
|
|
@@ -167,8 +354,18 @@ export class ConsentApp implements TerrenoPlugin {
|
|
|
167
354
|
};
|
|
168
355
|
}
|
|
169
356
|
|
|
170
|
-
register(app: Application): void {
|
|
171
|
-
const {auditTrail, resolveConsentForms, aiConfig} = this.options;
|
|
357
|
+
register(app: Application, openApi?: unknown): void {
|
|
358
|
+
const {accessControl, auditTrail, resolveConsentForms, aiConfig} = this.options;
|
|
359
|
+
|
|
360
|
+
if (!accessControl) {
|
|
361
|
+
logger.warn(
|
|
362
|
+
"ConsentApp registered without accessControl; only admins may sign consent on behalf of other users"
|
|
363
|
+
);
|
|
364
|
+
}
|
|
365
|
+
const canSignOnBehalf: PermissionMethod<unknown> = accessControl
|
|
366
|
+
? accessControl.permission({consentResponse: ["signOnBehalf"]})
|
|
367
|
+
: Permissions.IsAdmin;
|
|
368
|
+
const signOnBehalfPermissions = [Permissions.IsAuthenticated, canSignOnBehalf];
|
|
172
369
|
|
|
173
370
|
const collectionActions: Record<string, CollectionActionConfig<unknown, unknown, unknown>> = {};
|
|
174
371
|
|
|
@@ -290,10 +487,183 @@ export class ConsentApp implements TerrenoPlugin {
|
|
|
290
487
|
})
|
|
291
488
|
);
|
|
292
489
|
|
|
293
|
-
// Admin read-only access to consent responses
|
|
490
|
+
// Admin read-only access to consent responses, plus provisional signing actions
|
|
294
491
|
app.use(
|
|
295
492
|
"/consent-responses",
|
|
296
493
|
modelRouter(ConsentResponse, {
|
|
494
|
+
// Documented in OpenAPI so client SDKs get the provisional signing actions. The admin
|
|
495
|
+
// list and read routes are documented too; they are the same admin-only CRUD reads.
|
|
496
|
+
...(openApi ? {openApi: openApi as OpenApiMiddleware} : {}),
|
|
497
|
+
collectionActions: {
|
|
498
|
+
provisional: {
|
|
499
|
+
body: provisionalSignBody,
|
|
500
|
+
description:
|
|
501
|
+
"Record that another user agreed to a consent form on the target user's behalf. " +
|
|
502
|
+
"The form stays in the target user's pending list until they respond themselves.",
|
|
503
|
+
handler: async ({body, req, user}) => {
|
|
504
|
+
const signer = user as User;
|
|
505
|
+
const {consentFormId, locale, note, userId} = body as ProvisionalSignBody;
|
|
506
|
+
|
|
507
|
+
if (!isValidObjectId(consentFormId)) {
|
|
508
|
+
throw new APIError({status: 400, title: "consentFormId is invalid"});
|
|
509
|
+
}
|
|
510
|
+
if (String(signer.id) === userId) {
|
|
511
|
+
throw new APIError({status: 400, title: "Cannot sign provisionally for yourself"});
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
const targetUser = await loadConsentTargetUser(userId);
|
|
515
|
+
const form = await ConsentForm.findOneOrNone({_id: consentFormId});
|
|
516
|
+
if (!form) {
|
|
517
|
+
throw new APIError({status: 404, title: "Consent form not found"});
|
|
518
|
+
}
|
|
519
|
+
if (!form.active) {
|
|
520
|
+
throw new APIError({status: 400, title: "Consent form is not active"});
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
const {resolvedForms} = await resolveFormsForUser(targetUser, resolveConsentForms);
|
|
524
|
+
if (!resolvedForms.some((resolved) => resolved._id.equals(form._id))) {
|
|
525
|
+
throw new APIError({
|
|
526
|
+
status: 400,
|
|
527
|
+
title: "Consent form does not apply to this user",
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
const responseLocale = locale ?? form.defaultLocale;
|
|
532
|
+
const responseData: Record<string, unknown> = {
|
|
533
|
+
agreed: true,
|
|
534
|
+
agreedAt: DateTime.now().toJSDate(),
|
|
535
|
+
consentFormId: form._id,
|
|
536
|
+
formVersionSnapshot: form.version,
|
|
537
|
+
locale: responseLocale,
|
|
538
|
+
provisional: true,
|
|
539
|
+
provisionalNote: note,
|
|
540
|
+
provisionalSignedBy: signer.id,
|
|
541
|
+
userId,
|
|
542
|
+
};
|
|
543
|
+
if (auditTrail) {
|
|
544
|
+
responseData.contentSnapshot =
|
|
545
|
+
form.content.get(responseLocale) ?? form.content.get(form.defaultLocale);
|
|
546
|
+
responseData.provisionalSignerIp = req.ip;
|
|
547
|
+
responseData.provisionalSignerUserAgent = req.headers["user-agent"];
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
const response = await ConsentResponse.create(responseData);
|
|
551
|
+
|
|
552
|
+
recordConsentAudit({
|
|
553
|
+
action: "signOnBehalf",
|
|
554
|
+
actorId: String(signer.id),
|
|
555
|
+
consentFormId: form._id.toString(),
|
|
556
|
+
operation: "create",
|
|
557
|
+
recordId: response._id.toString(),
|
|
558
|
+
recordLabel: form.title,
|
|
559
|
+
userId,
|
|
560
|
+
verb: "created",
|
|
561
|
+
});
|
|
562
|
+
|
|
563
|
+
logger.info("Provisional consent recorded", {
|
|
564
|
+
consentFormId: form._id.toString(),
|
|
565
|
+
signerId: String(signer.id),
|
|
566
|
+
userId,
|
|
567
|
+
});
|
|
568
|
+
|
|
569
|
+
return response.populate(provisionalSignerPopulate);
|
|
570
|
+
},
|
|
571
|
+
method: "POST",
|
|
572
|
+
permissions: signOnBehalfPermissions,
|
|
573
|
+
response: provisionalConsentResponse,
|
|
574
|
+
summary: "Sign a consent form provisionally on behalf of another user",
|
|
575
|
+
},
|
|
576
|
+
status: {
|
|
577
|
+
description:
|
|
578
|
+
"Consent status of every form that applies to a user: pending, provisional, " +
|
|
579
|
+
"signed, or declined. Provisional counts as consented.",
|
|
580
|
+
handler: async ({query, user}) => {
|
|
581
|
+
const {userId} = query as ConsentStatusQuery;
|
|
582
|
+
const rows = await getConsentStatuses({resolveConsentForms, userId});
|
|
583
|
+
recordConsentAudit({
|
|
584
|
+
action: "viewStatus",
|
|
585
|
+
actorId: String((user as User).id),
|
|
586
|
+
operation: "read",
|
|
587
|
+
recordLabel: "Consent status",
|
|
588
|
+
userId,
|
|
589
|
+
verb: "viewed",
|
|
590
|
+
});
|
|
591
|
+
return rows;
|
|
592
|
+
},
|
|
593
|
+
method: "GET",
|
|
594
|
+
permissions: signOnBehalfPermissions,
|
|
595
|
+
query: consentStatusQuery,
|
|
596
|
+
response: consentStatusRows,
|
|
597
|
+
summary: "List a user's consent status for each form",
|
|
598
|
+
},
|
|
599
|
+
},
|
|
600
|
+
instanceActions: {
|
|
601
|
+
void: {
|
|
602
|
+
body: voidProvisionalBody,
|
|
603
|
+
description:
|
|
604
|
+
"Mark a provisional signature made in error as void. The record is kept for audit " +
|
|
605
|
+
"and no longer counts as consent.",
|
|
606
|
+
handler: async ({body, doc, user}) => {
|
|
607
|
+
const response = doc as ConsentResponseDocument;
|
|
608
|
+
const {reason} = body as VoidProvisionalBody;
|
|
609
|
+
if (!response.provisional) {
|
|
610
|
+
throw new APIError({
|
|
611
|
+
status: 400,
|
|
612
|
+
title: "Only provisional signatures can be voided",
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
if (response.voidedAt) {
|
|
616
|
+
throw new APIError({
|
|
617
|
+
status: 400,
|
|
618
|
+
title: "Provisional signature is already voided",
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
const actorId = String((user as User).id);
|
|
623
|
+
const voided = await ConsentResponse.findOneAndUpdate(
|
|
624
|
+
{_id: response._id, voidedAt: null},
|
|
625
|
+
{
|
|
626
|
+
$set: {
|
|
627
|
+
voidedAt: DateTime.now().toJSDate(),
|
|
628
|
+
voidedBy: actorId,
|
|
629
|
+
voidReason: reason,
|
|
630
|
+
},
|
|
631
|
+
},
|
|
632
|
+
{returnDocument: "after"}
|
|
633
|
+
);
|
|
634
|
+
if (!voided) {
|
|
635
|
+
throw new APIError({
|
|
636
|
+
status: 400,
|
|
637
|
+
title: "Provisional signature is already voided",
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
const targetUserId = idOf(response.userId);
|
|
642
|
+
const consentFormId = idOf(response.consentFormId);
|
|
643
|
+
recordConsentAudit({
|
|
644
|
+
action: "voidProvisional",
|
|
645
|
+
actorId,
|
|
646
|
+
consentFormId,
|
|
647
|
+
operation: "update",
|
|
648
|
+
recordId: response._id.toString(),
|
|
649
|
+
userId: targetUserId,
|
|
650
|
+
verb: "updated",
|
|
651
|
+
});
|
|
652
|
+
logger.info("Provisional consent voided", {
|
|
653
|
+
consentFormId,
|
|
654
|
+
responseId: response._id.toString(),
|
|
655
|
+
userId: targetUserId,
|
|
656
|
+
voidedBy: actorId,
|
|
657
|
+
});
|
|
658
|
+
|
|
659
|
+
return voided.populate([provisionalSignerPopulate, voidedByPopulate]);
|
|
660
|
+
},
|
|
661
|
+
method: "POST",
|
|
662
|
+
permissions: signOnBehalfPermissions,
|
|
663
|
+
response: provisionalConsentResponse,
|
|
664
|
+
summary: "Void a provisional consent signature",
|
|
665
|
+
},
|
|
666
|
+
},
|
|
297
667
|
permissions: {
|
|
298
668
|
create: [],
|
|
299
669
|
delete: [],
|
|
@@ -320,35 +690,22 @@ export class ConsentApp implements TerrenoPlugin {
|
|
|
320
690
|
|
|
321
691
|
logger.debug("Fetching pending consent forms", {userId: user.id});
|
|
322
692
|
|
|
323
|
-
const activeForms = await
|
|
324
|
-
|
|
325
|
-
let resolvedForms: ConsentFormDocument[];
|
|
693
|
+
const {activeForms, resolvedForms} = await resolveFormsForUser(user, resolveConsentForms);
|
|
326
694
|
if (resolveConsentForms) {
|
|
327
|
-
resolvedForms = await resolveConsentForms(user, activeForms);
|
|
328
695
|
logger.debug("resolveConsentForms applied", {
|
|
329
696
|
activeFormCount: activeForms.length,
|
|
330
697
|
resolvedFormCount: resolvedForms.length,
|
|
331
698
|
userAdmin: Boolean(user.admin),
|
|
332
699
|
userId: user.id,
|
|
333
700
|
});
|
|
334
|
-
} else {
|
|
335
|
-
resolvedForms = activeForms;
|
|
336
701
|
}
|
|
337
702
|
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
const
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
const respondedFormIds = existingResponses.map((r) => r.consentFormId);
|
|
347
|
-
const respondedForms = await ConsentForm.find({_id: {$in: respondedFormIds}});
|
|
348
|
-
const formVersionByFormId = new Map<string, number>();
|
|
349
|
-
for (const form of respondedForms) {
|
|
350
|
-
formVersionByFormId.set(form._id.toString(), form.version);
|
|
351
|
-
}
|
|
703
|
+
// Only the user's own responses clear a form. A provisional signature counts as
|
|
704
|
+
// consent for compliance, but the user still sees and signs the form themselves.
|
|
705
|
+
const existingResponses = await ConsentResponse.find({
|
|
706
|
+
provisional: {$ne: true},
|
|
707
|
+
userId: user.id,
|
|
708
|
+
});
|
|
352
709
|
|
|
353
710
|
const pendingForms = resolvedForms.filter((form) => {
|
|
354
711
|
const formId = form._id.toString();
|
|
@@ -361,6 +718,34 @@ export class ConsentApp implements TerrenoPlugin {
|
|
|
361
718
|
return !matchingResponses.some((r) => r.formVersionSnapshot === form.version);
|
|
362
719
|
});
|
|
363
720
|
|
|
721
|
+
// The user sees who signed provisionally and when, never the signer's note.
|
|
722
|
+
const provisionalResponses = await ConsentResponse.find({
|
|
723
|
+
consentFormId: {$in: pendingForms.map((form) => form._id)},
|
|
724
|
+
provisional: true,
|
|
725
|
+
userId: user.id,
|
|
726
|
+
voidedAt: null,
|
|
727
|
+
})
|
|
728
|
+
.sort({agreedAt: -1})
|
|
729
|
+
.populate(provisionalSignerPopulate);
|
|
730
|
+
const pendingData = pendingForms.map((form) => {
|
|
731
|
+
const latest = provisionalResponses.find(
|
|
732
|
+
(response) =>
|
|
733
|
+
response.consentFormId.toString() === form._id.toString() &&
|
|
734
|
+
response.formVersionSnapshot === form.version
|
|
735
|
+
);
|
|
736
|
+
const formJson = form.toJSON();
|
|
737
|
+
if (!latest) {
|
|
738
|
+
return formJson;
|
|
739
|
+
}
|
|
740
|
+
return {
|
|
741
|
+
...formJson,
|
|
742
|
+
provisionalSignature: {
|
|
743
|
+
signedAt: latest.agreedAt,
|
|
744
|
+
signedByName: signerDisplayName(populatedSigner(latest.provisionalSignedBy)),
|
|
745
|
+
},
|
|
746
|
+
};
|
|
747
|
+
});
|
|
748
|
+
|
|
364
749
|
const filteredOutByResolverCount = Math.max(activeForms.length - resolvedForms.length, 0);
|
|
365
750
|
const filteredOutByResponsesCount = Math.max(resolvedForms.length - pendingForms.length, 0);
|
|
366
751
|
|
|
@@ -375,7 +760,7 @@ export class ConsentApp implements TerrenoPlugin {
|
|
|
375
760
|
userId: user.id,
|
|
376
761
|
});
|
|
377
762
|
|
|
378
|
-
return res.json({data:
|
|
763
|
+
return res.json({data: pendingData});
|
|
379
764
|
})
|
|
380
765
|
);
|
|
381
766
|
|
|
@@ -480,7 +865,9 @@ export class ConsentApp implements TerrenoPlugin {
|
|
|
480
865
|
throw new APIError({status: 401, title: "Authentication required"});
|
|
481
866
|
}
|
|
482
867
|
|
|
483
|
-
const responses = await ConsentResponse.find({userId: user.id})
|
|
868
|
+
const responses = await ConsentResponse.find({userId: user.id})
|
|
869
|
+
.sort({agreedAt: -1})
|
|
870
|
+
.populate(provisionalSignerPopulate);
|
|
484
871
|
|
|
485
872
|
const formIds = responses.map((r) => r.consentFormId);
|
|
486
873
|
const forms = await ConsentForm.find({_id: {$in: formIds}});
|
|
@@ -507,9 +894,15 @@ export class ConsentApp implements TerrenoPlugin {
|
|
|
507
894
|
formVersionSnapshot: response.formVersionSnapshot,
|
|
508
895
|
ipAddress: response.ipAddress,
|
|
509
896
|
locale: response.locale,
|
|
897
|
+
provisional: Boolean(response.provisional),
|
|
898
|
+
// Name only: the signer's note and request metadata stay admin-only.
|
|
899
|
+
provisionalSignedBy: response.provisional
|
|
900
|
+
? {name: signerDisplayName(populatedSigner(response.provisionalSignedBy))}
|
|
901
|
+
: null,
|
|
510
902
|
signature: response.signature,
|
|
511
903
|
signedAt: response.signedAt,
|
|
512
904
|
userAgent: response.userAgent,
|
|
905
|
+
voidedAt: response.voidedAt,
|
|
513
906
|
};
|
|
514
907
|
});
|
|
515
908
|
|
|
@@ -527,9 +920,10 @@ export class ConsentApp implements TerrenoPlugin {
|
|
|
527
920
|
throw new APIError({status: 403, title: "Admin access required"});
|
|
528
921
|
}
|
|
529
922
|
|
|
530
|
-
const responses = await ConsentResponse.find({userId: req.params.userId})
|
|
531
|
-
agreedAt: -1
|
|
532
|
-
|
|
923
|
+
const responses = await ConsentResponse.find({userId: req.params.userId})
|
|
924
|
+
.sort({agreedAt: -1})
|
|
925
|
+
.populate(provisionalSignerPopulate)
|
|
926
|
+
.populate(voidedByPopulate);
|
|
533
927
|
|
|
534
928
|
const formIds = responses.map((r) => r.consentFormId);
|
|
535
929
|
const forms = await ConsentForm.find({_id: {$in: formIds}});
|
|
@@ -552,9 +946,17 @@ export class ConsentApp implements TerrenoPlugin {
|
|
|
552
946
|
formVersionSnapshot: response.formVersionSnapshot,
|
|
553
947
|
ipAddress: response.ipAddress,
|
|
554
948
|
locale: response.locale,
|
|
949
|
+
provisional: Boolean(response.provisional),
|
|
950
|
+
provisionalNote: response.provisionalNote,
|
|
951
|
+
provisionalSignedBy: populatedSigner(response.provisionalSignedBy),
|
|
952
|
+
provisionalSignerIp: response.provisionalSignerIp,
|
|
953
|
+
provisionalSignerUserAgent: response.provisionalSignerUserAgent,
|
|
555
954
|
responseId: response._id,
|
|
556
955
|
signedAt: response.signedAt,
|
|
557
956
|
userAgent: response.userAgent,
|
|
957
|
+
voidedAt: response.voidedAt,
|
|
958
|
+
voidedBy: populatedSigner(response.voidedBy),
|
|
959
|
+
voidReason: response.voidReason,
|
|
558
960
|
};
|
|
559
961
|
});
|
|
560
962
|
|