@adaptic/backend 0.0.1057 → 0.0.1058
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/auth/authorization-map.cjs +306 -0
- package/auth/authorization-map.d.ts +143 -0
- package/auth/cortex-auth-checker.cjs +172 -0
- package/auth/cortex-auth-checker.d.ts +114 -0
- package/auth/credential-fields.cjs +51 -0
- package/auth/credential-fields.d.ts +19 -0
- package/auth/credential-redaction.cjs +134 -0
- package/auth/credential-redaction.d.ts +60 -0
- package/auth/graphql-auth-shadow.cjs +317 -0
- package/auth/graphql-auth-shadow.d.ts +194 -0
- package/auth/membership-write-authority.cjs +131 -0
- package/auth/membership-write-authority.d.ts +110 -0
- package/auth/mutation-authorization.cjs +376 -0
- package/auth/mutation-authorization.d.ts +261 -0
- package/auth/nested-write-inspector.cjs +189 -0
- package/auth/nested-write-inspector.d.ts +94 -0
- package/auth/nested-write-policy.cjs +189 -0
- package/auth/nested-write-policy.d.ts +99 -0
- package/auth/service-token.cjs +316 -0
- package/auth/service-token.d.ts +94 -0
- package/auth/tenancy-scope.cjs +736 -0
- package/auth/tenancy-scope.d.ts +347 -0
- package/auth/token-verifier.cjs +451 -0
- package/auth/token-verifier.d.ts +153 -0
- package/auth/totp.cjs +265 -0
- package/auth/totp.d.ts +111 -0
- package/auth/user-write-content.cjs +116 -0
- package/auth/user-write-content.d.ts +47 -0
- package/auth/ws-auth-context.cjs +75 -0
- package/auth/ws-auth-context.d.ts +69 -0
- package/config/jwtConfig.cjs +52 -0
- package/config/jwtConfig.d.ts +16 -0
- package/config/metrics.cjs +356 -0
- package/config/metrics.d.ts +128 -0
- package/config/persisted-queries.cjs +122 -0
- package/config/persisted-queries.d.ts +40 -0
- package/config/server-only-models.cjs +166 -0
- package/config/server-only-models.d.ts +89 -0
- package/config/tracing.d.ts +24 -0
- package/generated/typegraphql-prisma/enhance.cjs +3 -3
- package/generated/typegraphql-prisma/index.cjs +6 -6
- package/generated/typegraphql-prisma/resolvers/crud/args.index.cjs +95 -95
- package/generated/typegraphql-prisma/resolvers/outputs/index.cjs +1 -1
- package/generated/typegraphql-prisma/resolvers/relations/args.index.cjs +32 -32
- package/middleware/audit-log-write-redaction.cjs +143 -0
- package/middleware/audit-log-write-redaction.d.ts +82 -0
- package/middleware/audit-logger.cjs +378 -0
- package/middleware/audit-logger.d.ts +158 -0
- package/middleware/audit-payload-guard.cjs +107 -0
- package/middleware/audit-payload-guard.d.ts +85 -0
- package/middleware/auth.cjs +66 -0
- package/middleware/auth.d.ts +41 -0
- package/middleware/credential-field-guard.cjs +514 -0
- package/middleware/credential-field-guard.d.ts +173 -0
- package/middleware/generated-type-names.cjs +77 -0
- package/middleware/generated-type-names.d.ts +44 -0
- package/middleware/graphql-validation-plugin.cjs +310 -0
- package/middleware/graphql-validation-plugin.d.ts +98 -0
- package/middleware/guard-log-throttle.cjs +89 -0
- package/middleware/guard-log-throttle.d.ts +80 -0
- package/middleware/index.cjs +57 -0
- package/middleware/index.d.ts +14 -0
- package/middleware/input-validator.cjs +220 -0
- package/middleware/input-validator.d.ts +63 -0
- package/middleware/mandate-version-validation.cjs +131 -0
- package/middleware/mandate-version-validation.d.ts +41 -0
- package/middleware/mutation-account-facts.cjs +223 -0
- package/middleware/mutation-account-facts.d.ts +143 -0
- package/middleware/mutation-auth-guard.cjs +536 -0
- package/middleware/mutation-auth-guard.d.ts +100 -0
- package/middleware/mutation-membership-facts.cjs +276 -0
- package/middleware/mutation-membership-facts.d.ts +133 -0
- package/middleware/mutation-tenant-facts.cjs +132 -0
- package/middleware/mutation-tenant-facts.d.ts +81 -0
- package/middleware/query-complexity.cjs +182 -0
- package/middleware/query-complexity.d.ts +56 -0
- package/middleware/rate-limiter.cjs +223 -0
- package/middleware/rate-limiter.d.ts +93 -0
- package/middleware/rate-tier.cjs +111 -0
- package/middleware/rate-tier.d.ts +56 -0
- package/middleware/soft-delete.cjs +175 -0
- package/middleware/soft-delete.d.ts +146 -0
- package/middleware/tenancy-scoping.cjs +229 -0
- package/middleware/tenancy-scoping.d.ts +67 -0
- package/middleware/trading-policy-audit.cjs +353 -0
- package/middleware/trading-policy-audit.d.ts +184 -0
- package/middleware/types.cjs +17 -0
- package/middleware/types.d.ts +87 -0
- package/middleware/validation-examples.cjs +398 -0
- package/middleware/validation-examples.d.ts +76 -0
- package/package.json +10 -2
- package/readers/index.cjs +15 -0
- package/readers/index.d.ts +10 -0
- package/readers/intraday-lane-prefs.cjs +76 -0
- package/readers/intraday-lane-prefs.d.ts +45 -0
- package/esm/config/__tests__/server-only-surface.harness.d.ts +0 -12
- package/esm/config/__tests__/server-only-surface.harness.mjs +0 -41
- package/esm/middleware/__tests__/audit-log-write-redaction.harness.d.ts +0 -144
- package/esm/middleware/__tests__/audit-log-write-redaction.harness.mjs +0 -920
- package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts +0 -55
- package/esm/middleware/__tests__/credential-field-coverage.harness.mjs +0 -440
- package/esm/middleware/__tests__/credential-field-guard.harness.d.ts +0 -34
- package/esm/middleware/__tests__/credential-field-guard.harness.mjs +0 -212
- package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +0 -56
- package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +0 -575
- package/esm/middleware/__tests__/rate-limit-test-utils.d.ts +0 -60
- package/esm/middleware/__tests__/rate-limit-test-utils.mjs +0 -85
- package/esm/middleware/__tests__/ts-node-harness.d.ts +0 -10
- package/esm/middleware/__tests__/ts-node-harness.mjs +0 -71
- package/health.cjs +0 -274
- package/server.cjs +0 -607
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Audit Logging Middleware
|
|
4
|
+
*
|
|
5
|
+
* Captures every generated write mutation (a create, update, upsert or
|
|
6
|
+
* delete of a Prisma model, except the excluded models below) and records an
|
|
7
|
+
* append-only audit trail. Each audit log entry includes: user ID (from JWT
|
|
8
|
+
* context), timestamp, operation type, model name, record ID, and changed
|
|
9
|
+
* fields. The changed fields are the executed field's own arguments, each
|
|
10
|
+
* under its schema path, with stored-credential values redacted.
|
|
11
|
+
*
|
|
12
|
+
* This middleware is implemented as an Apollo Server plugin that intercepts
|
|
13
|
+
* mutation operations and logs them to the AuditLog table.
|
|
14
|
+
*/
|
|
15
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
16
|
+
exports.createAuditLogPlugin = createAuditLogPlugin;
|
|
17
|
+
exports.parseMutationOperation = parseMutationOperation;
|
|
18
|
+
exports.extractUserId = extractUserId;
|
|
19
|
+
exports.extractRecordId = extractRecordId;
|
|
20
|
+
exports.extractChangedFields = extractChangedFields;
|
|
21
|
+
exports.operationVariables = operationVariables;
|
|
22
|
+
exports.resolveFieldArguments = resolveFieldArguments;
|
|
23
|
+
exports.collectRootFields = collectRootFields;
|
|
24
|
+
exports.principalMetadata = principalMetadata;
|
|
25
|
+
const client_1 = require("@prisma/client");
|
|
26
|
+
const graphql_1 = require("graphql");
|
|
27
|
+
const credential_redaction_1 = require("../auth/credential-redaction.cjs");
|
|
28
|
+
const mutation_authorization_1 = require("../auth/mutation-authorization.cjs");
|
|
29
|
+
const logger_1 = require("../utils/logger.cjs");
|
|
30
|
+
/** List of models that are excluded from audit logging (e.g., the audit log itself) */
|
|
31
|
+
const EXCLUDED_MODELS = new Set([
|
|
32
|
+
'AuditLog',
|
|
33
|
+
'Session',
|
|
34
|
+
'VerificationToken',
|
|
35
|
+
'Authenticator',
|
|
36
|
+
]);
|
|
37
|
+
/** Every Prisma model name; a generated write mutation names exactly one. */
|
|
38
|
+
const PRISMA_MODELS = new Set(Object.values(client_1.Prisma.ModelName));
|
|
39
|
+
/**
|
|
40
|
+
* The audit operation type recorded for each generated write. An upsert is
|
|
41
|
+
* recorded as a CREATE whose `changedFields.input` holds its `where`, `create`
|
|
42
|
+
* and `update` arguments.
|
|
43
|
+
*/
|
|
44
|
+
const AUDIT_OPERATION_TYPES = {
|
|
45
|
+
create: 'CREATE',
|
|
46
|
+
upsert: 'CREATE',
|
|
47
|
+
update: 'UPDATE',
|
|
48
|
+
delete: 'DELETE',
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Resolves a mutation field onto the model it writes and the audit operation
|
|
52
|
+
* type. TypeGraphQL-Prisma generates, per model, `createOne`, `createMany`,
|
|
53
|
+
* `createManyAndReturn`, `updateOne`, `updateMany`, `upsertOne`, `deleteOne`
|
|
54
|
+
* and `deleteMany` followed by the model name.
|
|
55
|
+
*
|
|
56
|
+
* The field is read with the classifier the mutation-authorization guard uses
|
|
57
|
+
* (`classifyMutationField`): prefixes are matched longest first and the
|
|
58
|
+
* remainder must be a Prisma model, so the audit row names the model the
|
|
59
|
+
* guard authorised. A leading-prefix match alone reads
|
|
60
|
+
* `createManyAndReturnSession` as `createMany` of a model `AndReturnSession`,
|
|
61
|
+
* which mislabels the row and lets the write of an excluded model (whose
|
|
62
|
+
* payload carries its tokens) into the audit trail.
|
|
63
|
+
*
|
|
64
|
+
* @param operationName - The name of the GraphQL field being executed
|
|
65
|
+
* @param models - Every Prisma model name; defaults to the generated client's
|
|
66
|
+
* @returns Parsed mutation data, or null for a field that is not a generated
|
|
67
|
+
* write of a model
|
|
68
|
+
*/
|
|
69
|
+
function parseMutationOperation(operationName, models = PRISMA_MODELS) {
|
|
70
|
+
const target = (0, mutation_authorization_1.classifyMutationField)(operationName, models);
|
|
71
|
+
if (target.action === 'custom')
|
|
72
|
+
return null;
|
|
73
|
+
return {
|
|
74
|
+
operationType: AUDIT_OPERATION_TYPES[target.action],
|
|
75
|
+
modelName: target.model,
|
|
76
|
+
operationName,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Extracts the user ID from the context user object.
|
|
81
|
+
* Handles both JWT-decoded objects and raw string tokens.
|
|
82
|
+
*
|
|
83
|
+
* The result must be a syntactically valid UUID because the
|
|
84
|
+
* `AuditLog.userId` column is typed `String? @db.Uuid` in the Prisma
|
|
85
|
+
* schema. Non-UUID values (e.g. Auth0-style `sub` like `auth0|abc`) are
|
|
86
|
+
* coerced to `null` so the downstream `auditLog.create()` does not fail
|
|
87
|
+
* at the Postgres boundary and abort the originating mutation.
|
|
88
|
+
*
|
|
89
|
+
* @param user - The user object from GraphQL context
|
|
90
|
+
* @returns The user ID string when a valid UUID, otherwise null
|
|
91
|
+
*/
|
|
92
|
+
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
93
|
+
function extractUserId(user) {
|
|
94
|
+
if (!user)
|
|
95
|
+
return null;
|
|
96
|
+
const rawId = typeof user === 'string' ? user : user.sub || user.id || null;
|
|
97
|
+
if (!rawId)
|
|
98
|
+
return null;
|
|
99
|
+
return UUID_REGEX.test(rawId) ? rawId : null;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Extracts the record ID from the mutation result data.
|
|
103
|
+
* Looks for 'id' field in the top-level result object.
|
|
104
|
+
*
|
|
105
|
+
* @param data - The result data from the mutation
|
|
106
|
+
* @param responseKey - The audited field's response key (its alias, else its
|
|
107
|
+
* name). An operation with several mutation fields returns one result per
|
|
108
|
+
* key; without a key the first result is read.
|
|
109
|
+
* @returns The record ID as a string, or 'unknown'
|
|
110
|
+
*/
|
|
111
|
+
function extractRecordId(data, responseKey) {
|
|
112
|
+
if (!data)
|
|
113
|
+
return 'unknown';
|
|
114
|
+
// The result is typically nested under the mutation name
|
|
115
|
+
const values = Object.values(data);
|
|
116
|
+
if (values.length === 0)
|
|
117
|
+
return 'unknown';
|
|
118
|
+
const result = responseKey === undefined ? values[0] : data[responseKey];
|
|
119
|
+
if (result &&
|
|
120
|
+
typeof result === 'object' &&
|
|
121
|
+
'id' in result) {
|
|
122
|
+
return String(result.id);
|
|
123
|
+
}
|
|
124
|
+
return 'unknown';
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Extracts changed fields from the audited field's arguments.
|
|
128
|
+
* For create operations, captures all input data.
|
|
129
|
+
* For update operations, captures the data being set.
|
|
130
|
+
* For delete operations, captures the where clause.
|
|
131
|
+
*
|
|
132
|
+
* Stored-credential values (broker keys, OAuth / session / invite tokens) are
|
|
133
|
+
* replaced with a placeholder: an audit row is readable far more widely than
|
|
134
|
+
* the credential column, so a key copied into one is an unguarded second copy
|
|
135
|
+
* of the secret. The replacement is directed by key name, so it holds only
|
|
136
|
+
* because every value here sits under its schema path (see
|
|
137
|
+
* {@link resolveFieldArguments}).
|
|
138
|
+
*
|
|
139
|
+
* @param operationType - The type of mutation operation
|
|
140
|
+
* @param args - The audited field's arguments, by schema argument name
|
|
141
|
+
* @returns A JSON-serializable object representing the changed fields
|
|
142
|
+
*/
|
|
143
|
+
function extractChangedFields(operationType, args) {
|
|
144
|
+
if (!args)
|
|
145
|
+
return {};
|
|
146
|
+
const fields = (() => {
|
|
147
|
+
switch (operationType) {
|
|
148
|
+
case 'CREATE':
|
|
149
|
+
return { input: args.data || args };
|
|
150
|
+
case 'UPDATE':
|
|
151
|
+
return {
|
|
152
|
+
where: args.where || {},
|
|
153
|
+
data: args.data || {},
|
|
154
|
+
};
|
|
155
|
+
case 'DELETE':
|
|
156
|
+
return { where: args.where || {} };
|
|
157
|
+
default:
|
|
158
|
+
return args;
|
|
159
|
+
}
|
|
160
|
+
})();
|
|
161
|
+
return (0, credential_redaction_1.redactCredentials)(fields);
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* The operation's variable values as execution sees them: the request's
|
|
165
|
+
* values, plus the operation's declared default for each variable the request
|
|
166
|
+
* omitted. Held in a prototype-free map so a variable reference can only ever
|
|
167
|
+
* read a value the request or the operation supplied.
|
|
168
|
+
*
|
|
169
|
+
* @param operation - The executed operation
|
|
170
|
+
* @param variables - The request's variable values
|
|
171
|
+
* @returns The effective variable values
|
|
172
|
+
*/
|
|
173
|
+
function operationVariables(operation, variables) {
|
|
174
|
+
var _a;
|
|
175
|
+
const values = Object.assign(Object.create(null), variables !== null && variables !== void 0 ? variables : {});
|
|
176
|
+
for (const definition of (_a = operation.variableDefinitions) !== null && _a !== void 0 ? _a : []) {
|
|
177
|
+
const name = definition.variable.name.value;
|
|
178
|
+
if (definition.defaultValue && !(name in values)) {
|
|
179
|
+
values[name] = (0, graphql_1.valueFromASTUntyped)(definition.defaultValue);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return values;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* The value of each argument the field passes, under the argument's schema
|
|
186
|
+
* name, with every variable reference replaced by its value.
|
|
187
|
+
*
|
|
188
|
+
* This is what the audit row records, rather than the request's variables
|
|
189
|
+
* map: a variable is named by the calling operation, not by the schema, so a
|
|
190
|
+
* credential passed as `$key` into `data: { apiKey: $key }` would be stored
|
|
191
|
+
* under `key`, where no key-directed redaction can recognise it. Resolved
|
|
192
|
+
* against the field, the same value sits at `data.apiKey`, the column's own
|
|
193
|
+
* name, whatever the operation called its variables. It also records
|
|
194
|
+
* arguments written inline, which a variables map does not carry at all.
|
|
195
|
+
*
|
|
196
|
+
* @param field - The audited root field
|
|
197
|
+
* @param variables - The effective variable values ({@link operationVariables})
|
|
198
|
+
* @returns The field's arguments, by schema argument name
|
|
199
|
+
*/
|
|
200
|
+
function resolveFieldArguments(field, variables) {
|
|
201
|
+
var _a;
|
|
202
|
+
const args = {};
|
|
203
|
+
for (const argument of (_a = field.arguments) !== null && _a !== void 0 ? _a : []) {
|
|
204
|
+
args[argument.name.value] = (0, graphql_1.valueFromASTUntyped)(argument.value, variables);
|
|
205
|
+
}
|
|
206
|
+
return args;
|
|
207
|
+
}
|
|
208
|
+
/** Whether `@skip` / `@include` leave a selection in the executed operation. */
|
|
209
|
+
function isIncluded(directives, variables) {
|
|
210
|
+
var _a;
|
|
211
|
+
for (const directive of directives !== null && directives !== void 0 ? directives : []) {
|
|
212
|
+
const name = directive.name.value;
|
|
213
|
+
if (name !== 'skip' && name !== 'include')
|
|
214
|
+
continue;
|
|
215
|
+
const condition = (_a = directive.arguments) === null || _a === void 0 ? void 0 : _a.find((argument) => argument.name.value === 'if');
|
|
216
|
+
const value = condition ? (0, graphql_1.valueFromASTUntyped)(condition.value, variables) : undefined;
|
|
217
|
+
if (name === 'skip' && value === true)
|
|
218
|
+
return false;
|
|
219
|
+
if (name === 'include' && value === false)
|
|
220
|
+
return false;
|
|
221
|
+
}
|
|
222
|
+
return true;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* The root fields an operation executes, by response key (alias, else name),
|
|
226
|
+
* in execution order, following the rules graphql-js applies when it collects
|
|
227
|
+
* them: inline fragments and fragment spreads are entered, `@skip` /
|
|
228
|
+
* `@include` are honoured, each fragment is entered once, and a response key
|
|
229
|
+
* keeps its first field node, which is the one graphql-js reads arguments
|
|
230
|
+
* from. Fragment type conditions are not checked: at the root of a validated
|
|
231
|
+
* operation every fragment is on the root type.
|
|
232
|
+
*
|
|
233
|
+
* @param selectionSet - The operation's (or a root fragment's) selection set
|
|
234
|
+
* @param fragments - The document's fragment definitions, by name
|
|
235
|
+
* @param variables - The effective variable values
|
|
236
|
+
* @param fields - Accumulator for the recursion
|
|
237
|
+
* @param visitedFragments - Fragments already entered
|
|
238
|
+
* @returns Each executed root field node, by response key
|
|
239
|
+
*/
|
|
240
|
+
function collectRootFields(selectionSet, fragments, variables, fields = new Map(), visitedFragments = new Set()) {
|
|
241
|
+
var _a, _b;
|
|
242
|
+
for (const selection of selectionSet.selections) {
|
|
243
|
+
if (!isIncluded(selection.directives, variables))
|
|
244
|
+
continue;
|
|
245
|
+
if (selection.kind === 'Field') {
|
|
246
|
+
const responseKey = (_b = (_a = selection.alias) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : selection.name.value;
|
|
247
|
+
if (!fields.has(responseKey))
|
|
248
|
+
fields.set(responseKey, selection);
|
|
249
|
+
}
|
|
250
|
+
else if (selection.kind === 'InlineFragment') {
|
|
251
|
+
collectRootFields(selection.selectionSet, fragments, variables, fields, visitedFragments);
|
|
252
|
+
}
|
|
253
|
+
else {
|
|
254
|
+
const fragmentName = selection.name.value;
|
|
255
|
+
const fragment = fragments.get(fragmentName);
|
|
256
|
+
if (fragment && !visitedFragments.has(fragmentName)) {
|
|
257
|
+
visitedFragments.add(fragmentName);
|
|
258
|
+
collectRootFields(fragment.selectionSet, fragments, variables, fields, visitedFragments);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
return fields;
|
|
263
|
+
}
|
|
264
|
+
/** The document's fragment definitions, by name. */
|
|
265
|
+
function fragmentsOf(document) {
|
|
266
|
+
const fragments = new Map();
|
|
267
|
+
for (const definition of document.definitions) {
|
|
268
|
+
if (definition.kind === 'FragmentDefinition') {
|
|
269
|
+
fragments.set(definition.name.value, definition);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return fragments;
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* The acting principal as recorded on an audit row. `userId` holds only a
|
|
276
|
+
* UUID subject, so a service or anonymous write needs its identity here or
|
|
277
|
+
* the row cannot say who made it.
|
|
278
|
+
*/
|
|
279
|
+
function principalMetadata(principal) {
|
|
280
|
+
var _a;
|
|
281
|
+
if (!principal)
|
|
282
|
+
return { principalKind: 'none', principalSub: null };
|
|
283
|
+
if (principal.kind === 'server') {
|
|
284
|
+
return { principalKind: 'server', principalSub: (_a = principal.sub) !== null && _a !== void 0 ? _a : null };
|
|
285
|
+
}
|
|
286
|
+
return { principalKind: principal.kind, principalSub: principal.sub };
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Creates an Apollo Server plugin that logs all mutations to the AuditLog table.
|
|
290
|
+
*
|
|
291
|
+
* The plugin intercepts the willSendResponse lifecycle event to capture
|
|
292
|
+
* mutation results after they have been processed by the resolvers.
|
|
293
|
+
* Only successful mutations are logged (errors are not audited here).
|
|
294
|
+
*
|
|
295
|
+
* @returns An Apollo Server plugin instance
|
|
296
|
+
*/
|
|
297
|
+
function createAuditLogPlugin() {
|
|
298
|
+
return {
|
|
299
|
+
async requestDidStart(_requestContext) {
|
|
300
|
+
return {
|
|
301
|
+
async willSendResponse(requestContext) {
|
|
302
|
+
var _a, _b, _c, _d;
|
|
303
|
+
const { contextValue, response, request, document, operation } = requestContext;
|
|
304
|
+
// Only audit mutations, and only the operation that executed: a
|
|
305
|
+
// document can define several, and `operationName` picks one.
|
|
306
|
+
if (!document || !operation || operation.operation !== 'mutation') {
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
// Skip if there were errors (we only audit successful mutations)
|
|
310
|
+
if (response.body.kind === 'single' &&
|
|
311
|
+
((_a = response.body.singleResult.errors) === null || _a === void 0 ? void 0 : _a.length)) {
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
const prisma = contextValue.prisma;
|
|
315
|
+
if (!prisma) {
|
|
316
|
+
logger_1.logger.warn('Audit logger: Prisma client not available in context');
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
const variables = operationVariables(operation, request.variables);
|
|
320
|
+
const rootFields = collectRootFields(operation.selectionSet, fragmentsOf(document), variables);
|
|
321
|
+
for (const [responseKey, field] of rootFields) {
|
|
322
|
+
const fieldName = field.name.value;
|
|
323
|
+
const auditData = parseMutationOperation(fieldName);
|
|
324
|
+
if (!auditData)
|
|
325
|
+
continue;
|
|
326
|
+
if (EXCLUDED_MODELS.has(auditData.modelName))
|
|
327
|
+
continue;
|
|
328
|
+
const userId = extractUserId(contextValue.user);
|
|
329
|
+
const changedFields = extractChangedFields(auditData.operationType, resolveFieldArguments(field, variables));
|
|
330
|
+
// Extract record ID from response data
|
|
331
|
+
let recordId = 'unknown';
|
|
332
|
+
if (response.body.kind === 'single' &&
|
|
333
|
+
response.body.singleResult.data) {
|
|
334
|
+
recordId = extractRecordId(response.body.singleResult.data, responseKey);
|
|
335
|
+
}
|
|
336
|
+
// Extract IP address from request context
|
|
337
|
+
const ipAddress = ((_b = contextValue.req) === null || _b === void 0 ? void 0 : _b.ip) ||
|
|
338
|
+
((_d = (_c = contextValue.req) === null || _c === void 0 ? void 0 : _c.headers) === null || _d === void 0 ? void 0 : _d['x-forwarded-for']) ||
|
|
339
|
+
null;
|
|
340
|
+
try {
|
|
341
|
+
const prismaRecord = prisma;
|
|
342
|
+
if (prismaRecord.auditLog) {
|
|
343
|
+
const auditLogDelegate = prismaRecord.auditLog;
|
|
344
|
+
await auditLogDelegate.create({
|
|
345
|
+
data: {
|
|
346
|
+
userId,
|
|
347
|
+
operationType: auditData.operationType,
|
|
348
|
+
modelName: auditData.modelName,
|
|
349
|
+
recordId,
|
|
350
|
+
changedFields,
|
|
351
|
+
operationName: auditData.operationName,
|
|
352
|
+
ipAddress,
|
|
353
|
+
metadata: {
|
|
354
|
+
graphqlOperationName: request.operationName || null,
|
|
355
|
+
...principalMetadata(contextValue.principal),
|
|
356
|
+
},
|
|
357
|
+
},
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
else {
|
|
361
|
+
logger_1.logger.warn('Audit logger: AuditLog model not available on Prisma client');
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
catch (error) {
|
|
365
|
+
// Audit logging failures should never break the main request
|
|
366
|
+
logger_1.logger.error('Audit logger: Failed to write audit log entry', {
|
|
367
|
+
error: error instanceof Error ? error.message : String(error),
|
|
368
|
+
modelName: auditData.modelName,
|
|
369
|
+
operationType: auditData.operationType,
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
},
|
|
374
|
+
};
|
|
375
|
+
},
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
//# sourceMappingURL=audit-logger.js.map
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Audit Logging Middleware
|
|
3
|
+
*
|
|
4
|
+
* Captures every generated write mutation (a create, update, upsert or
|
|
5
|
+
* delete of a Prisma model, except the excluded models below) and records an
|
|
6
|
+
* append-only audit trail. Each audit log entry includes: user ID (from JWT
|
|
7
|
+
* context), timestamp, operation type, model name, record ID, and changed
|
|
8
|
+
* fields. The changed fields are the executed field's own arguments, each
|
|
9
|
+
* under its schema path, with stored-credential values redacted.
|
|
10
|
+
*
|
|
11
|
+
* This middleware is implemented as an Apollo Server plugin that intercepts
|
|
12
|
+
* mutation operations and logs them to the AuditLog table.
|
|
13
|
+
*/
|
|
14
|
+
import type { ApolloServerPlugin } from '@apollo/server';
|
|
15
|
+
import { type PrismaClient } from '@prisma/client';
|
|
16
|
+
import { type FieldNode, type FragmentDefinitionNode, type OperationDefinitionNode, type SelectionSetNode } from 'graphql';
|
|
17
|
+
import type { BackendPrincipal } from '../auth/token-verifier';
|
|
18
|
+
/** Represents the user object decoded from JWT context */
|
|
19
|
+
interface AuditUser {
|
|
20
|
+
sub?: string;
|
|
21
|
+
id?: string;
|
|
22
|
+
name?: string;
|
|
23
|
+
role?: string;
|
|
24
|
+
provider?: string;
|
|
25
|
+
}
|
|
26
|
+
/** Context shape expected by the audit logger plugin */
|
|
27
|
+
interface AuditContext {
|
|
28
|
+
prisma: PrismaClient;
|
|
29
|
+
user?: AuditUser | string | null;
|
|
30
|
+
/** The verified principal, when the request presented one. */
|
|
31
|
+
principal?: BackendPrincipal | null;
|
|
32
|
+
req?: {
|
|
33
|
+
ip?: string;
|
|
34
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** Fields extracted from a GraphQL mutation for audit logging */
|
|
38
|
+
interface MutationAuditData {
|
|
39
|
+
operationType: 'CREATE' | 'UPDATE' | 'DELETE';
|
|
40
|
+
modelName: string;
|
|
41
|
+
operationName: string;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Resolves a mutation field onto the model it writes and the audit operation
|
|
45
|
+
* type. TypeGraphQL-Prisma generates, per model, `createOne`, `createMany`,
|
|
46
|
+
* `createManyAndReturn`, `updateOne`, `updateMany`, `upsertOne`, `deleteOne`
|
|
47
|
+
* and `deleteMany` followed by the model name.
|
|
48
|
+
*
|
|
49
|
+
* The field is read with the classifier the mutation-authorization guard uses
|
|
50
|
+
* (`classifyMutationField`): prefixes are matched longest first and the
|
|
51
|
+
* remainder must be a Prisma model, so the audit row names the model the
|
|
52
|
+
* guard authorised. A leading-prefix match alone reads
|
|
53
|
+
* `createManyAndReturnSession` as `createMany` of a model `AndReturnSession`,
|
|
54
|
+
* which mislabels the row and lets the write of an excluded model (whose
|
|
55
|
+
* payload carries its tokens) into the audit trail.
|
|
56
|
+
*
|
|
57
|
+
* @param operationName - The name of the GraphQL field being executed
|
|
58
|
+
* @param models - Every Prisma model name; defaults to the generated client's
|
|
59
|
+
* @returns Parsed mutation data, or null for a field that is not a generated
|
|
60
|
+
* write of a model
|
|
61
|
+
*/
|
|
62
|
+
declare function parseMutationOperation(operationName: string, models?: ReadonlySet<string>): MutationAuditData | null;
|
|
63
|
+
declare function extractUserId(user: AuditUser | string | null | undefined): string | null;
|
|
64
|
+
/**
|
|
65
|
+
* Extracts the record ID from the mutation result data.
|
|
66
|
+
* Looks for 'id' field in the top-level result object.
|
|
67
|
+
*
|
|
68
|
+
* @param data - The result data from the mutation
|
|
69
|
+
* @param responseKey - The audited field's response key (its alias, else its
|
|
70
|
+
* name). An operation with several mutation fields returns one result per
|
|
71
|
+
* key; without a key the first result is read.
|
|
72
|
+
* @returns The record ID as a string, or 'unknown'
|
|
73
|
+
*/
|
|
74
|
+
declare function extractRecordId(data: Record<string, unknown> | null | undefined, responseKey?: string): string;
|
|
75
|
+
/**
|
|
76
|
+
* Extracts changed fields from the audited field's arguments.
|
|
77
|
+
* For create operations, captures all input data.
|
|
78
|
+
* For update operations, captures the data being set.
|
|
79
|
+
* For delete operations, captures the where clause.
|
|
80
|
+
*
|
|
81
|
+
* Stored-credential values (broker keys, OAuth / session / invite tokens) are
|
|
82
|
+
* replaced with a placeholder: an audit row is readable far more widely than
|
|
83
|
+
* the credential column, so a key copied into one is an unguarded second copy
|
|
84
|
+
* of the secret. The replacement is directed by key name, so it holds only
|
|
85
|
+
* because every value here sits under its schema path (see
|
|
86
|
+
* {@link resolveFieldArguments}).
|
|
87
|
+
*
|
|
88
|
+
* @param operationType - The type of mutation operation
|
|
89
|
+
* @param args - The audited field's arguments, by schema argument name
|
|
90
|
+
* @returns A JSON-serializable object representing the changed fields
|
|
91
|
+
*/
|
|
92
|
+
declare function extractChangedFields(operationType: 'CREATE' | 'UPDATE' | 'DELETE', args: Record<string, unknown> | null | undefined): Record<string, unknown>;
|
|
93
|
+
/**
|
|
94
|
+
* The operation's variable values as execution sees them: the request's
|
|
95
|
+
* values, plus the operation's declared default for each variable the request
|
|
96
|
+
* omitted. Held in a prototype-free map so a variable reference can only ever
|
|
97
|
+
* read a value the request or the operation supplied.
|
|
98
|
+
*
|
|
99
|
+
* @param operation - The executed operation
|
|
100
|
+
* @param variables - The request's variable values
|
|
101
|
+
* @returns The effective variable values
|
|
102
|
+
*/
|
|
103
|
+
declare function operationVariables(operation: OperationDefinitionNode, variables: Record<string, unknown> | null | undefined): Record<string, unknown>;
|
|
104
|
+
/**
|
|
105
|
+
* The value of each argument the field passes, under the argument's schema
|
|
106
|
+
* name, with every variable reference replaced by its value.
|
|
107
|
+
*
|
|
108
|
+
* This is what the audit row records, rather than the request's variables
|
|
109
|
+
* map: a variable is named by the calling operation, not by the schema, so a
|
|
110
|
+
* credential passed as `$key` into `data: { apiKey: $key }` would be stored
|
|
111
|
+
* under `key`, where no key-directed redaction can recognise it. Resolved
|
|
112
|
+
* against the field, the same value sits at `data.apiKey`, the column's own
|
|
113
|
+
* name, whatever the operation called its variables. It also records
|
|
114
|
+
* arguments written inline, which a variables map does not carry at all.
|
|
115
|
+
*
|
|
116
|
+
* @param field - The audited root field
|
|
117
|
+
* @param variables - The effective variable values ({@link operationVariables})
|
|
118
|
+
* @returns The field's arguments, by schema argument name
|
|
119
|
+
*/
|
|
120
|
+
declare function resolveFieldArguments(field: FieldNode, variables: Record<string, unknown>): Record<string, unknown>;
|
|
121
|
+
/**
|
|
122
|
+
* The root fields an operation executes, by response key (alias, else name),
|
|
123
|
+
* in execution order, following the rules graphql-js applies when it collects
|
|
124
|
+
* them: inline fragments and fragment spreads are entered, `@skip` /
|
|
125
|
+
* `@include` are honoured, each fragment is entered once, and a response key
|
|
126
|
+
* keeps its first field node, which is the one graphql-js reads arguments
|
|
127
|
+
* from. Fragment type conditions are not checked: at the root of a validated
|
|
128
|
+
* operation every fragment is on the root type.
|
|
129
|
+
*
|
|
130
|
+
* @param selectionSet - The operation's (or a root fragment's) selection set
|
|
131
|
+
* @param fragments - The document's fragment definitions, by name
|
|
132
|
+
* @param variables - The effective variable values
|
|
133
|
+
* @param fields - Accumulator for the recursion
|
|
134
|
+
* @param visitedFragments - Fragments already entered
|
|
135
|
+
* @returns Each executed root field node, by response key
|
|
136
|
+
*/
|
|
137
|
+
declare function collectRootFields(selectionSet: SelectionSetNode, fragments: ReadonlyMap<string, FragmentDefinitionNode>, variables: Record<string, unknown>, fields?: Map<string, FieldNode>, visitedFragments?: Set<string>): Map<string, FieldNode>;
|
|
138
|
+
/**
|
|
139
|
+
* The acting principal as recorded on an audit row. `userId` holds only a
|
|
140
|
+
* UUID subject, so a service or anonymous write needs its identity here or
|
|
141
|
+
* the row cannot say who made it.
|
|
142
|
+
*/
|
|
143
|
+
declare function principalMetadata(principal: BackendPrincipal | null | undefined): {
|
|
144
|
+
principalKind: string;
|
|
145
|
+
principalSub: string | null;
|
|
146
|
+
};
|
|
147
|
+
/**
|
|
148
|
+
* Creates an Apollo Server plugin that logs all mutations to the AuditLog table.
|
|
149
|
+
*
|
|
150
|
+
* The plugin intercepts the willSendResponse lifecycle event to capture
|
|
151
|
+
* mutation results after they have been processed by the resolvers.
|
|
152
|
+
* Only successful mutations are logged (errors are not audited here).
|
|
153
|
+
*
|
|
154
|
+
* @returns An Apollo Server plugin instance
|
|
155
|
+
*/
|
|
156
|
+
export declare function createAuditLogPlugin(): ApolloServerPlugin<AuditContext>;
|
|
157
|
+
export { parseMutationOperation, extractUserId, extractRecordId, extractChangedFields, operationVariables, resolveFieldArguments, collectRootFields, principalMetadata, };
|
|
158
|
+
//# sourceMappingURL=audit-logger.d.ts.map
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Audit payload guard: credential values inside `AuditLog` JSON payloads
|
|
4
|
+
* reach only the principals allowed to read those payloads raw.
|
|
5
|
+
*
|
|
6
|
+
* ## Why this exists
|
|
7
|
+
*
|
|
8
|
+
* The audit trail records what each mutation asked for. An audit logger that
|
|
9
|
+
* copies mutation variables verbatim stores a broker-key update's key and
|
|
10
|
+
* secret in `changedFields` (`data.APIKey.set`, `data.APISecret.set`), and a
|
|
11
|
+
* user create's nested account keys under
|
|
12
|
+
* `input.alpacaAccounts.connectOrCreate[…].create`. Redacting payloads before
|
|
13
|
+
* they are written does not reach rows already stored, and `AuditLog` is
|
|
14
|
+
* readable by any principal the endpoint admits. Without this guard the
|
|
15
|
+
* credential-field guard's server-only rule for a column is bypassed by
|
|
16
|
+
* reading its copy in the audit trail.
|
|
17
|
+
*
|
|
18
|
+
* ## What it guards
|
|
19
|
+
*
|
|
20
|
+
* 1. **Output.** For a principal that may not read payloads raw, the value a
|
|
21
|
+
* payload column resolves to on any output type that carries it
|
|
22
|
+
* (`AuditLog`, `AuditLogGroupBy`, `CreateManyAndReturnAuditLog`, …) goes
|
|
23
|
+
* through {@link redactCredentials} before it leaves the resolver: each
|
|
24
|
+
* credential-named key's value is replaced and the rest of the payload is
|
|
25
|
+
* served as stored. The rule applies where the field resolves, so it covers
|
|
26
|
+
* root reads, aliases, fragments, bulk-write return rows and any type that
|
|
27
|
+
* nests `AuditLog`.
|
|
28
|
+
* 2. **Predicates.** A filter, sort, cursor, `having`, `by` or `distinct` over
|
|
29
|
+
* a payload column is an oracle over whatever the payload holds:
|
|
30
|
+
* `changedFields: { path: ["data", "APISecret", "set"], string_starts_with: "a" }`
|
|
31
|
+
* reads a secret one character at a time without selecting it. Nothing in
|
|
32
|
+
* a JSON filter alone shows that it cannot reach a credential inside the
|
|
33
|
+
* payload, so every predicate over a payload column is refused for the
|
|
34
|
+
* same principals.
|
|
35
|
+
*
|
|
36
|
+
* `server` and `admin` principals read payloads raw; `user` and anonymous
|
|
37
|
+
* callers read them redacted. The mode is the credential-field guard's
|
|
38
|
+
* (`CREDENTIAL_FIELD_GUARD_MODE`, read per request): `shadow` serves payloads
|
|
39
|
+
* as stored and counts every read that enforcement would change, `enforce`
|
|
40
|
+
* redacts and refuses, `off` does neither.
|
|
41
|
+
*
|
|
42
|
+
* @module middleware/audit-payload-guard
|
|
43
|
+
*/
|
|
44
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
45
|
+
exports.AUDIT_PAYLOAD_FIELDS = void 0;
|
|
46
|
+
exports.readsAuditPayloadRaw = readsAuditPayloadRaw;
|
|
47
|
+
exports.auditPayloadOutputFieldsFor = auditPayloadOutputFieldsFor;
|
|
48
|
+
exports.auditPayloadPredicateFieldsFor = auditPayloadPredicateFieldsFor;
|
|
49
|
+
exports.auditPayloadEnumFieldsFor = auditPayloadEnumFieldsFor;
|
|
50
|
+
exports.auditPayloadOutputField = auditPayloadOutputField;
|
|
51
|
+
exports.redactAuditPayload = redactAuditPayload;
|
|
52
|
+
const credential_redaction_1 = require("../auth/credential-redaction.cjs");
|
|
53
|
+
const generated_type_names_1 = require("./generated-type-names.cjs");
|
|
54
|
+
/** JSON payload columns that can hold a copy of a credential, by model. */
|
|
55
|
+
exports.AUDIT_PAYLOAD_FIELDS = new Map([['AuditLog', new Set(['changedFields', 'metadata'])]]);
|
|
56
|
+
/** Principal kinds that read audit payloads as stored. */
|
|
57
|
+
const RAW_READERS = new Set([
|
|
58
|
+
'server',
|
|
59
|
+
'admin',
|
|
60
|
+
]);
|
|
61
|
+
const AUDIT_PAYLOAD_TYPES = (0, generated_type_names_1.indexGeneratedTypes)(exports.AUDIT_PAYLOAD_FIELDS);
|
|
62
|
+
/** Whether `principal` reads audit payloads as stored. */
|
|
63
|
+
function readsAuditPayloadRaw(principal) {
|
|
64
|
+
return principal !== null && RAW_READERS.has(principal.kind);
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The payload columns an output type carries as values, or `undefined`.
|
|
68
|
+
*
|
|
69
|
+
* @internal Exported for the schema-coverage test.
|
|
70
|
+
*/
|
|
71
|
+
function auditPayloadOutputFieldsFor(typeName) {
|
|
72
|
+
return AUDIT_PAYLOAD_TYPES.outputFields(typeName);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The payload columns an input type's keys can reference as a predicate, or
|
|
76
|
+
* `undefined`.
|
|
77
|
+
*
|
|
78
|
+
* @internal Exported for the input walk and the schema-coverage test.
|
|
79
|
+
*/
|
|
80
|
+
function auditPayloadPredicateFieldsFor(typeName) {
|
|
81
|
+
return AUDIT_PAYLOAD_TYPES.predicateFields(typeName);
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* The payload columns a `<Model>ScalarFieldEnum` can name, or `undefined`.
|
|
85
|
+
*
|
|
86
|
+
* @internal Exported for the input walk and the schema-coverage test.
|
|
87
|
+
*/
|
|
88
|
+
function auditPayloadEnumFieldsFor(typeName) {
|
|
89
|
+
return AUDIT_PAYLOAD_TYPES.enumFields(typeName);
|
|
90
|
+
}
|
|
91
|
+
/** The payload column this resolver outputs, as `TypeName.field`, if any. */
|
|
92
|
+
function auditPayloadOutputField(info) {
|
|
93
|
+
var _a;
|
|
94
|
+
return ((_a = AUDIT_PAYLOAD_TYPES.outputFields(info.parentType.name)) === null || _a === void 0 ? void 0 : _a.has(info.fieldName))
|
|
95
|
+
? `${info.parentType.name}.${info.fieldName}`
|
|
96
|
+
: undefined;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Redact one payload value and say where its credentials were.
|
|
100
|
+
*
|
|
101
|
+
* @param value - The value a payload column resolved to.
|
|
102
|
+
* @returns The redacted copy and the replaced key paths.
|
|
103
|
+
*/
|
|
104
|
+
function redactAuditPayload(value) {
|
|
105
|
+
return { redacted: (0, credential_redaction_1.redactCredentials)(value), paths: (0, credential_redaction_1.credentialKeyPaths)(value) };
|
|
106
|
+
}
|
|
107
|
+
//# sourceMappingURL=audit-payload-guard.js.map
|