@adaptic/backend-legacy 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.
Files changed (111) hide show
  1. package/auth/authorization-map.cjs +306 -0
  2. package/auth/authorization-map.d.ts +143 -0
  3. package/auth/cortex-auth-checker.cjs +172 -0
  4. package/auth/cortex-auth-checker.d.ts +114 -0
  5. package/auth/credential-fields.cjs +51 -0
  6. package/auth/credential-fields.d.ts +19 -0
  7. package/auth/credential-redaction.cjs +134 -0
  8. package/auth/credential-redaction.d.ts +60 -0
  9. package/auth/graphql-auth-shadow.cjs +317 -0
  10. package/auth/graphql-auth-shadow.d.ts +194 -0
  11. package/auth/membership-write-authority.cjs +131 -0
  12. package/auth/membership-write-authority.d.ts +110 -0
  13. package/auth/mutation-authorization.cjs +376 -0
  14. package/auth/mutation-authorization.d.ts +261 -0
  15. package/auth/nested-write-inspector.cjs +189 -0
  16. package/auth/nested-write-inspector.d.ts +94 -0
  17. package/auth/nested-write-policy.cjs +189 -0
  18. package/auth/nested-write-policy.d.ts +99 -0
  19. package/auth/service-token.cjs +316 -0
  20. package/auth/service-token.d.ts +94 -0
  21. package/auth/tenancy-scope.cjs +736 -0
  22. package/auth/tenancy-scope.d.ts +347 -0
  23. package/auth/token-verifier.cjs +451 -0
  24. package/auth/token-verifier.d.ts +153 -0
  25. package/auth/totp.cjs +265 -0
  26. package/auth/totp.d.ts +111 -0
  27. package/auth/user-write-content.cjs +116 -0
  28. package/auth/user-write-content.d.ts +47 -0
  29. package/auth/ws-auth-context.cjs +75 -0
  30. package/auth/ws-auth-context.d.ts +69 -0
  31. package/config/jwtConfig.cjs +52 -0
  32. package/config/jwtConfig.d.ts +16 -0
  33. package/config/metrics.cjs +356 -0
  34. package/config/metrics.d.ts +128 -0
  35. package/config/persisted-queries.cjs +122 -0
  36. package/config/persisted-queries.d.ts +40 -0
  37. package/config/server-only-models.cjs +166 -0
  38. package/config/server-only-models.d.ts +89 -0
  39. package/config/tracing.d.ts +24 -0
  40. package/generated/typegraphql-prisma/enhance.cjs +3 -3
  41. package/generated/typegraphql-prisma/index.cjs +6 -6
  42. package/generated/typegraphql-prisma/resolvers/crud/args.index.cjs +95 -95
  43. package/generated/typegraphql-prisma/resolvers/outputs/index.cjs +1 -1
  44. package/generated/typegraphql-prisma/resolvers/relations/args.index.cjs +32 -32
  45. package/middleware/audit-log-write-redaction.cjs +143 -0
  46. package/middleware/audit-log-write-redaction.d.ts +82 -0
  47. package/middleware/audit-logger.cjs +378 -0
  48. package/middleware/audit-logger.d.ts +158 -0
  49. package/middleware/audit-payload-guard.cjs +107 -0
  50. package/middleware/audit-payload-guard.d.ts +85 -0
  51. package/middleware/auth.cjs +66 -0
  52. package/middleware/auth.d.ts +41 -0
  53. package/middleware/credential-field-guard.cjs +514 -0
  54. package/middleware/credential-field-guard.d.ts +173 -0
  55. package/middleware/generated-type-names.cjs +77 -0
  56. package/middleware/generated-type-names.d.ts +44 -0
  57. package/middleware/graphql-validation-plugin.cjs +310 -0
  58. package/middleware/graphql-validation-plugin.d.ts +98 -0
  59. package/middleware/guard-log-throttle.cjs +89 -0
  60. package/middleware/guard-log-throttle.d.ts +80 -0
  61. package/middleware/index.cjs +57 -0
  62. package/middleware/index.d.ts +14 -0
  63. package/middleware/input-validator.cjs +220 -0
  64. package/middleware/input-validator.d.ts +63 -0
  65. package/middleware/mandate-version-validation.cjs +131 -0
  66. package/middleware/mandate-version-validation.d.ts +41 -0
  67. package/middleware/mutation-account-facts.cjs +223 -0
  68. package/middleware/mutation-account-facts.d.ts +143 -0
  69. package/middleware/mutation-auth-guard.cjs +536 -0
  70. package/middleware/mutation-auth-guard.d.ts +100 -0
  71. package/middleware/mutation-membership-facts.cjs +276 -0
  72. package/middleware/mutation-membership-facts.d.ts +133 -0
  73. package/middleware/mutation-tenant-facts.cjs +132 -0
  74. package/middleware/mutation-tenant-facts.d.ts +81 -0
  75. package/middleware/query-complexity.cjs +182 -0
  76. package/middleware/query-complexity.d.ts +56 -0
  77. package/middleware/rate-limiter.cjs +223 -0
  78. package/middleware/rate-limiter.d.ts +93 -0
  79. package/middleware/rate-tier.cjs +111 -0
  80. package/middleware/rate-tier.d.ts +56 -0
  81. package/middleware/soft-delete.cjs +175 -0
  82. package/middleware/soft-delete.d.ts +146 -0
  83. package/middleware/tenancy-scoping.cjs +229 -0
  84. package/middleware/tenancy-scoping.d.ts +67 -0
  85. package/middleware/trading-policy-audit.cjs +353 -0
  86. package/middleware/trading-policy-audit.d.ts +184 -0
  87. package/middleware/types.cjs +17 -0
  88. package/middleware/types.d.ts +87 -0
  89. package/middleware/validation-examples.cjs +398 -0
  90. package/middleware/validation-examples.d.ts +76 -0
  91. package/package.json +10 -2
  92. package/readers/index.cjs +15 -0
  93. package/readers/index.d.ts +10 -0
  94. package/readers/intraday-lane-prefs.cjs +76 -0
  95. package/readers/intraday-lane-prefs.d.ts +45 -0
  96. package/esm/config/__tests__/server-only-surface.harness.d.ts +0 -12
  97. package/esm/config/__tests__/server-only-surface.harness.mjs +0 -41
  98. package/esm/middleware/__tests__/audit-log-write-redaction.harness.d.ts +0 -144
  99. package/esm/middleware/__tests__/audit-log-write-redaction.harness.mjs +0 -920
  100. package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts +0 -55
  101. package/esm/middleware/__tests__/credential-field-coverage.harness.mjs +0 -440
  102. package/esm/middleware/__tests__/credential-field-guard.harness.d.ts +0 -34
  103. package/esm/middleware/__tests__/credential-field-guard.harness.mjs +0 -212
  104. package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +0 -56
  105. package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +0 -575
  106. package/esm/middleware/__tests__/rate-limit-test-utils.d.ts +0 -60
  107. package/esm/middleware/__tests__/rate-limit-test-utils.mjs +0 -85
  108. package/esm/middleware/__tests__/ts-node-harness.d.ts +0 -10
  109. package/esm/middleware/__tests__/ts-node-harness.mjs +0 -71
  110. package/health.cjs +0 -274
  111. package/server.cjs +0 -607
@@ -0,0 +1,536 @@
1
+ "use strict";
2
+ /**
3
+ * Mutation authorization guard: every GraphQL mutation is admitted only for a
4
+ * principal authorised to write that model and, for a brokerage account's
5
+ * policy or account row, that account.
6
+ *
7
+ * The decision itself lives in `src/auth/mutation-authorization.ts` (pure);
8
+ * this module installs it on the built schema, resolves the ownership,
9
+ * tenancy and membership-role facts a user principal's write needs (read
10
+ * from the database for the mutation, never from the token), counts and logs
11
+ * every decision, and writes the
12
+ * attributed TradingPolicy audit rows (`./trading-policy-audit.ts`).
13
+ *
14
+ * ## Why it wraps the Mutation fields instead of being a global middleware
15
+ *
16
+ * A TypeGraphQL global middleware is dispatched on EVERY field of every query.
17
+ * Measured on 500 rows x 8 fields, one extra global middleware — even one that
18
+ * returns after a single comparison — added ~0.35 us per field (4.2 → 5.6 ms
19
+ * per query), a cost the platform's read-heavy traffic would pay for a check
20
+ * that only ever applies to root Mutation fields. So the guard wraps the
21
+ * `resolve` of each root Mutation field on the built schema: reads pay nothing,
22
+ * and every mutation — generated or hand-written — is covered, because the
23
+ * set wrapped is the schema's own Mutation type, not a list someone maintains.
24
+ *
25
+ * Each root field of a multi-field (batched or aliased) operation is its own
26
+ * resolver call, so each is decided on its own: an allowed field never carries
27
+ * a refused sibling through with it. The guard runs outside the TypeGraphQL
28
+ * middleware chain, so it decides before the credential-field guard and the
29
+ * tenancy scoping see the field.
30
+ *
31
+ * ## Credential predicates are refused before anything is read
32
+ *
33
+ * Deciding a mutation can read rows with the caller's own `where` (ownership
34
+ * and tenancy facts, the TradingPolicy before-state), and the audit rows
35
+ * record the ids and accounts that read matched. Because this guard runs
36
+ * first, a `where` over a stored credential would be executed here before the
37
+ * credential-field guard ever refused it, and the matched rows would land in
38
+ * AuditLog: an oracle over the credential, open in every mutation-auth mode,
39
+ * the denied branch included. So the guard applies the credential-field
40
+ * guard's predicate rule itself, as its first step: a non-service principal
41
+ * whose arguments name a credential column is refused before any read and
42
+ * before any audit row, whenever that guard enforces.
43
+ *
44
+ * ## Nested writes and modes
45
+ *
46
+ * A root field's arguments can write far beyond its own model (nested
47
+ * `create` / `update` / `connect` along relations). Every nested container is
48
+ * decided on its own hop (`src/auth/nested-write-policy.ts`), and the mutation
49
+ * is decided at the strictest mode among every model it writes, so an
50
+ * escalated model cannot be written through a shadow-mode root.
51
+ *
52
+ * @module middleware/mutation-auth-guard
53
+ */
54
+ Object.defineProperty(exports, "__esModule", { value: true });
55
+ exports.mutationAuthorizationTotal = void 0;
56
+ exports.prismaRelationFacts = prismaRelationFacts;
57
+ exports.resetMutationAuthLogThrottle = resetMutationAuthLogThrottle;
58
+ exports.installMutationAuthGuard = installMutationAuthGuard;
59
+ const client_1 = require("@prisma/client");
60
+ const graphql_1 = require("graphql");
61
+ const prom_client_1 = require("prom-client");
62
+ const credential_redaction_1 = require("../auth/credential-redaction.cjs");
63
+ const mutation_authorization_1 = require("../auth/mutation-authorization.cjs");
64
+ const membership_write_authority_1 = require("../auth/membership-write-authority.cjs");
65
+ const nested_write_inspector_1 = require("../auth/nested-write-inspector.cjs");
66
+ const nested_write_policy_1 = require("../auth/nested-write-policy.cjs");
67
+ const tenancy_scope_1 = require("../auth/tenancy-scope.cjs");
68
+ const user_write_content_1 = require("../auth/user-write-content.cjs");
69
+ const metrics_1 = require("../config/metrics.cjs");
70
+ const logger_1 = require("../utils/logger.cjs");
71
+ const credential_field_guard_1 = require("./credential-field-guard.cjs");
72
+ const mutation_account_facts_1 = require("./mutation-account-facts.cjs");
73
+ const mutation_membership_facts_1 = require("./mutation-membership-facts.cjs");
74
+ const mutation_tenant_facts_1 = require("./mutation-tenant-facts.cjs");
75
+ const trading_policy_audit_1 = require("./trading-policy-audit.cjs");
76
+ /**
77
+ * Mutation decisions by mutation field, principal kind, decision and reason.
78
+ * Every label is bounded: the mutation field must exist in the schema to
79
+ * reach a resolver, and the other three are closed enums. The `would_deny`
80
+ * series is the list of callers enforcement would break.
81
+ */
82
+ exports.mutationAuthorizationTotal = new prom_client_1.Counter({
83
+ name: 'graphql_mutation_authorization_total',
84
+ help: 'GraphQL mutation authorization decisions by mutation field, principal kind ' +
85
+ '(server | admin | user | none), decision (allowed | would_deny | denied) and reason.',
86
+ labelNames: ['mutation', 'principal_kind', 'decision', 'reason'],
87
+ registers: [metrics_1.metricsRegistry],
88
+ });
89
+ /**
90
+ * Foreign-key placement read from the Prisma data model: `Model.relation`
91
+ * holds the key when its `relationFromFields` is non-empty.
92
+ */
93
+ function prismaRelationFacts() {
94
+ var _a;
95
+ const onParent = new Map();
96
+ for (const model of client_1.Prisma.dmmf.datamodel.models) {
97
+ for (const field of model.fields) {
98
+ if (field.kind !== 'object')
99
+ continue;
100
+ onParent.set(`${model.name}.${field.name}`, ((_a = field.relationFromFields) !== null && _a !== void 0 ? _a : []).length > 0);
101
+ }
102
+ }
103
+ return { fkOnParent: (model, relation) => onParent.get(`${model}.${relation}`) };
104
+ }
105
+ const GOVERNED = new Set(tenancy_scope_1.GOVERNED_MODELS);
106
+ function isGovernedModel(model) {
107
+ return GOVERNED.has(model);
108
+ }
109
+ const LOG_THROTTLE_MS = 10 * 60 * 1000;
110
+ const LOG_THROTTLE_MAX_KEYS = 5000;
111
+ const lastLoggedAt = new Map();
112
+ /** @internal Test hook: forget the log throttle state. */
113
+ function resetMutationAuthLogThrottle() {
114
+ lastLoggedAt.clear();
115
+ }
116
+ function refusalError(evaluation) {
117
+ if (evaluation.refusal === 'unauthenticated') {
118
+ return new graphql_1.GraphQLError('Unauthenticated: this mutation requires a verified principal', {
119
+ extensions: { code: 'UNAUTHENTICATED', reason: evaluation.reason, http: { status: 401 } },
120
+ });
121
+ }
122
+ return new graphql_1.GraphQLError('Forbidden: this principal is not authorised for this mutation', {
123
+ extensions: { code: 'FORBIDDEN', reason: evaluation.reason, http: { status: 403 } },
124
+ });
125
+ }
126
+ function guardUnavailableError() {
127
+ return new graphql_1.GraphQLError('Service unavailable: this mutation could not be authorised', {
128
+ extensions: { code: 'MUTATION_AUTH_UNAVAILABLE', http: { status: 503 } },
129
+ });
130
+ }
131
+ function auditUnavailableError() {
132
+ return new graphql_1.GraphQLError('Service unavailable: the audit record for this trading-policy write could not be written', { extensions: { code: 'AUDIT_UNAVAILABLE', http: { status: 503 } } });
133
+ }
134
+ function errorCodeOf(error) {
135
+ var _a;
136
+ if (error instanceof graphql_1.GraphQLError && typeof ((_a = error.extensions) === null || _a === void 0 ? void 0 : _a.code) === 'string') {
137
+ return error.extensions.code;
138
+ }
139
+ if (error instanceof client_1.Prisma.PrismaClientKnownRequestError)
140
+ return error.code;
141
+ return error instanceof Error ? error.name : 'unknown';
142
+ }
143
+ function logRefusal(decision, target, evaluation, principal, info, req, nowMs) {
144
+ var _a, _b, _c;
145
+ const actor = (0, trading_policy_audit_1.actorFor)(principal, req);
146
+ const key = [decision, target.fieldName, actor.principalKind, evaluation.reason, actor.userAgent, actor.ip].join('|');
147
+ const previous = lastLoggedAt.get(key);
148
+ if (previous !== undefined && nowMs - previous < LOG_THROTTLE_MS)
149
+ return;
150
+ if (lastLoggedAt.size >= LOG_THROTTLE_MAX_KEYS)
151
+ lastLoggedAt.clear();
152
+ lastLoggedAt.set(key, nowMs);
153
+ logger_1.logger.warn('[mutation-auth] mutation refused by authorization policy', {
154
+ decision,
155
+ mutation: target.fieldName,
156
+ model: target.model,
157
+ reason: evaluation.reason,
158
+ principalKind: actor.principalKind,
159
+ principalSub: actor.sub,
160
+ operationName: (_c = (_b = (_a = info.operation) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.value) !== null && _c !== void 0 ? _c : '<unnamed>',
161
+ ip: actor.ip,
162
+ userAgent: actor.userAgent,
163
+ origin: actor.origin,
164
+ dedupWindowMs: LOG_THROTTLE_MS,
165
+ });
166
+ }
167
+ /**
168
+ * The credential columns a non-service principal's mutation arguments name as
169
+ * a predicate, when the credential-field guard enforces; empty otherwise. In
170
+ * `shadow` and `off` that guard admits the predicate itself, and counts it
171
+ * there, so this guard leaves it to it.
172
+ */
173
+ function refusedCredentialReferences(principal, info, args, credentialMode) {
174
+ if ((principal === null || principal === void 0 ? void 0 : principal.kind) === 'server')
175
+ return [];
176
+ const references = (0, credential_field_guard_1.findCredentialArgumentReferences)(info, args);
177
+ if (references.length === 0 || credentialMode() !== 'enforce')
178
+ return [];
179
+ return references;
180
+ }
181
+ function logCredentialRefusal(fieldName, references, principal, info, req, nowMs) {
182
+ var _a, _b, _c;
183
+ const actor = (0, trading_policy_audit_1.actorFor)(principal, req);
184
+ const key = ['credential_predicate', fieldName, actor.principalKind, actor.userAgent, actor.ip].join('|');
185
+ const previous = lastLoggedAt.get(key);
186
+ if (previous !== undefined && nowMs - previous < LOG_THROTTLE_MS)
187
+ return;
188
+ if (lastLoggedAt.size >= LOG_THROTTLE_MAX_KEYS)
189
+ lastLoggedAt.clear();
190
+ lastLoggedAt.set(key, nowMs);
191
+ logger_1.logger.warn('[mutation-auth] mutation refused: its arguments name a stored credential', {
192
+ mutation: fieldName,
193
+ references,
194
+ principalKind: actor.principalKind,
195
+ principalSub: actor.sub,
196
+ operationName: (_c = (_b = (_a = info.operation) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.value) !== null && _c !== void 0 ? _c : '<unnamed>',
197
+ ip: actor.ip,
198
+ userAgent: actor.userAgent,
199
+ origin: actor.origin,
200
+ dedupWindowMs: LOG_THROTTLE_MS,
201
+ });
202
+ }
203
+ /** Decide one mutation, resolving database facts only when the decision needs them. */
204
+ async function decide(principal, target, nested, args, touched, prisma, relations) {
205
+ const nestedModels = nested.map((n) => n.model);
206
+ if ((principal === null || principal === void 0 ? void 0 : principal.kind) !== 'user')
207
+ return (0, mutation_authorization_1.evaluateMutationAccess)(principal, target, { nestedModels });
208
+ const facts = {
209
+ nestedModels,
210
+ nestedRefusal: (0, nested_write_policy_1.firstNestedRefusal)(nested, principal.sub, relations),
211
+ contentRefusal: (0, user_write_content_1.userContentRefusal)(target, args, principal.sub),
212
+ targetsSelf: targetsSelf(principal, args),
213
+ };
214
+ const first = (0, mutation_authorization_1.evaluateMutationAccess)(principal, target, facts);
215
+ if (!prisma)
216
+ return first;
217
+ if (first.reason === 'account_unresolved') {
218
+ try {
219
+ const ownership = await (0, mutation_account_facts_1.ownershipOf)(prisma, principal.sub, await touched());
220
+ return (0, mutation_authorization_1.evaluateMutationAccess)(principal, target, { ...facts, ownership });
221
+ }
222
+ catch (error) {
223
+ logger_1.logger.error('[mutation-auth] account ownership could not be read; refusing as unresolved', {
224
+ mutation: target.fieldName,
225
+ error: error instanceof Error ? error.message : String(error),
226
+ });
227
+ return first;
228
+ }
229
+ }
230
+ if (first.reason === 'membership_authority_unresolved' && (0, membership_write_authority_1.isMembershipModel)(target.model)) {
231
+ try {
232
+ const membership = await (0, mutation_membership_facts_1.membershipWriteVerdict)(prisma, target.model, target, args, principal.sub);
233
+ const membershipAuthority = membership.kind === 'decided' ? membership.verdict : 'unresolved';
234
+ return (0, mutation_authorization_1.evaluateMutationAccess)(principal, target, { ...facts, membershipAuthority });
235
+ }
236
+ catch (error) {
237
+ logger_1.logger.error('[mutation-auth] membership authority could not be read; refusing as unresolved', {
238
+ mutation: target.fieldName,
239
+ error: error instanceof Error ? error.message : String(error),
240
+ });
241
+ return first;
242
+ }
243
+ }
244
+ if (first.reason === 'tenant_unresolved' && (isGovernedModel(target.model) || target.model === 'MandateVersion')) {
245
+ try {
246
+ const tenantScope = isGovernedModel(target.model)
247
+ ? await (0, mutation_tenant_facts_1.tenantScopeOf)(prisma, target.model, target, args, principal.sub)
248
+ : await (0, mutation_tenant_facts_1.mandateVersionScopeOf)(prisma, args, principal.sub);
249
+ return (0, mutation_authorization_1.evaluateMutationAccess)(principal, target, { ...facts, tenantScope });
250
+ }
251
+ catch (error) {
252
+ logger_1.logger.error('[mutation-auth] tenant scope could not be read; refusing as unresolved', {
253
+ mutation: target.fieldName,
254
+ error: error instanceof Error ? error.message : String(error),
255
+ });
256
+ return first;
257
+ }
258
+ }
259
+ return first;
260
+ }
261
+ function targetsSelf(principal, args) {
262
+ const where = args.where;
263
+ if (where === null || typeof where !== 'object')
264
+ return false;
265
+ const { id, email } = where;
266
+ if (id !== undefined)
267
+ return id === principal.sub;
268
+ return principal.email !== undefined && email === principal.email;
269
+ }
270
+ /** Fields already wrapped, so installing twice never double-guards a field. */
271
+ const guardedFields = new WeakSet();
272
+ /**
273
+ * Wrap every root Mutation field of a built schema with the guard.
274
+ *
275
+ * @param schema - The schema `buildSchema` returned; mutated in place.
276
+ * @param options - Optional overrides for tests.
277
+ * @returns How many Mutation fields are guarded (for the boot log; zero means
278
+ * the schema has no Mutation type and nothing is protected).
279
+ */
280
+ function installMutationAuthGuard(schema, options = {}) {
281
+ var _a;
282
+ const mutationType = schema.getMutationType();
283
+ if (!mutationType)
284
+ return 0;
285
+ const guard = createMutationGuard(options);
286
+ let guarded = 0;
287
+ for (const field of Object.values(mutationType.getFields())) {
288
+ guarded += 1;
289
+ if (guardedFields.has(field))
290
+ continue;
291
+ const original = (_a = field.resolve) !== null && _a !== void 0 ? _a : graphql_1.defaultFieldResolver;
292
+ field.resolve = (source, args, context, info) => guard(context, args, info, () => Promise.resolve(original(source, args, context, info)));
293
+ guardedFields.add(field);
294
+ }
295
+ return guarded;
296
+ }
297
+ /** The per-mutation decision + audit, closed over its configuration. */
298
+ function createMutationGuard(options) {
299
+ var _a, _b, _c, _d, _e, _f;
300
+ const resolveMode = (_a = options.modeProvider) !== null && _a !== void 0 ? _a : (() => (0, mutation_authorization_1.getMutationAuthMode)());
301
+ const resolveEnforced = (_b = options.enforcedModelsProvider) !== null && _b !== void 0 ? _b : (() => (0, mutation_authorization_1.getEnforcedModels)());
302
+ const models = new Set((_c = options.models) !== null && _c !== void 0 ? _c : Object.values(client_1.Prisma.ModelName));
303
+ const modelsLongestFirst = [...models].sort((a, b) => b.length - a.length);
304
+ const relations = (_d = options.relations) !== null && _d !== void 0 ? _d : prismaRelationFacts();
305
+ const resolveCredentialMode = (_e = options.credentialGuardModeProvider) !== null && _e !== void 0 ? _e : credential_field_guard_1.getCredentialFieldGuardMode;
306
+ const now = (_f = options.now) !== null && _f !== void 0 ? _f : Date.now;
307
+ /**
308
+ * Whether a mutation the guard could not evaluate is refused. It is when
309
+ * anything is being enforced — globally, or any escalated model (the guard
310
+ * cannot know the failed mutation was not one of them) — and when the
311
+ * escalation list itself cannot be read. Only a pure-shadow or off guard
312
+ * lets it through, because in those modes the guard refuses nothing anyway.
313
+ */
314
+ const failsClosedOnError = (baseMode) => {
315
+ if (baseMode === 'enforce')
316
+ return true;
317
+ if (baseMode === 'off')
318
+ return false;
319
+ try {
320
+ return resolveEnforced().size > 0;
321
+ }
322
+ catch (_a) {
323
+ return true;
324
+ }
325
+ };
326
+ return async (context, args, info, proceed) => {
327
+ var _a, _b, _c, _d, _e;
328
+ const principal = (_a = context.principal) !== null && _a !== void 0 ? _a : null;
329
+ const argRecord = (args !== null && args !== void 0 ? args : {});
330
+ // Cast justified: the context's `prisma` is the server's PrismaClient, whose
331
+ // delegates satisfy this structural slice; tests supply a fake of it.
332
+ const prisma = context.prisma;
333
+ // First, before any fact or before-state read and before any audit row:
334
+ // nothing below may execute the caller's `where` if it names a credential.
335
+ const credentialRefs = refusedCredentialReferences(principal, info, argRecord, resolveCredentialMode);
336
+ if (credentialRefs.length > 0) {
337
+ credential_field_guard_1.credentialFieldAccessTotal.inc({
338
+ surface: 'argument',
339
+ decision: 'denied',
340
+ principal_kind: (_b = principal === null || principal === void 0 ? void 0 : principal.kind) !== null && _b !== void 0 ? _b : 'none',
341
+ });
342
+ exports.mutationAuthorizationTotal.inc({
343
+ mutation: info.fieldName,
344
+ principal_kind: (_c = principal === null || principal === void 0 ? void 0 : principal.kind) !== null && _c !== void 0 ? _c : 'none',
345
+ decision: 'denied',
346
+ reason: 'credential_predicate',
347
+ });
348
+ logCredentialRefusal(info.fieldName, credentialRefs, principal, info, context.req, now());
349
+ throw (0, credential_field_guard_1.credentialAccessForbidden)(credentialRefs);
350
+ }
351
+ let baseMode = 'enforce';
352
+ let target;
353
+ let mode;
354
+ let nested;
355
+ let evaluation;
356
+ let touchedPromise;
357
+ const touched = () => {
358
+ touchedPromise !== null && touchedPromise !== void 0 ? touchedPromise : (touchedPromise = prisma
359
+ ? (0, mutation_account_facts_1.loadTouchedAccounts)(prisma, target, argRecord)
360
+ : Promise.resolve({ accounts: [], policies: [] }));
361
+ return touchedPromise;
362
+ };
363
+ try {
364
+ baseMode = resolveMode();
365
+ target = (0, mutation_authorization_1.classifyMutationField)(info.fieldName, models);
366
+ nested = (0, nested_write_inspector_1.findNestedWrites)(info, argRecord, modelsLongestFirst, target);
367
+ const written = nested.filter((n) => (0, nested_write_policy_1.writesNestedModelRows)(n, relations)).map((n) => n.model);
368
+ mode = (0, mutation_authorization_1.effectiveModeFor)([target.model, ...written], baseMode, resolveEnforced());
369
+ // A user-written row that places itself in a fund's ledger is refused in
370
+ // every mode, `off` included: the ledger is the fund's record of what
371
+ // happened (G-LED-01), its reader keys on fundId alone, and a forged row
372
+ // would be served as fact while the global guard sits in shadow.
373
+ if ((principal === null || principal === void 0 ? void 0 : principal.kind) === 'user' && (0, user_write_content_1.userContentRefusal)(target, argRecord, principal.sub) === 'ledger_fund_reserved') {
374
+ mode = 'enforce';
375
+ }
376
+ evaluation =
377
+ mode === 'off'
378
+ ? { allowed: true, reason: 'guard_off' }
379
+ : await decide(principal, target, nested, argRecord, touched, prisma, relations);
380
+ }
381
+ catch (error) {
382
+ const refuse = failsClosedOnError(baseMode) || (0, mutation_authorization_1.touchesAlwaysEnforced)([(0, mutation_authorization_1.classifyMutationField)(info.fieldName, models).model]);
383
+ exports.mutationAuthorizationTotal.inc({
384
+ mutation: info.fieldName,
385
+ principal_kind: (_d = principal === null || principal === void 0 ? void 0 : principal.kind) !== null && _d !== void 0 ? _d : 'none',
386
+ decision: refuse ? 'denied' : 'allowed',
387
+ reason: 'guard_error',
388
+ });
389
+ logger_1.logger.error('[mutation-auth] mutation could not be evaluated', {
390
+ mutation: info.fieldName,
391
+ refused: refuse,
392
+ error: error instanceof Error ? error.message : String(error),
393
+ });
394
+ if (refuse)
395
+ throw guardUnavailableError();
396
+ return proceed();
397
+ }
398
+ const decision = evaluation.allowed ? 'allowed' : mode === 'enforce' ? 'denied' : 'would_deny';
399
+ exports.mutationAuthorizationTotal.inc({
400
+ mutation: target.fieldName,
401
+ principal_kind: (_e = principal === null || principal === void 0 ? void 0 : principal.kind) !== null && _e !== void 0 ? _e : 'none',
402
+ decision,
403
+ reason: evaluation.reason,
404
+ });
405
+ if (decision !== 'allowed') {
406
+ logRefusal(decision, target, evaluation, principal, info, context.req, now());
407
+ }
408
+ const policyWrites = nested.filter((n) => n.model === 'TradingPolicy');
409
+ if (target.model !== 'TradingPolicy' && policyWrites.length === 0) {
410
+ if (decision === 'denied')
411
+ throw refusalError(evaluation);
412
+ return proceed();
413
+ }
414
+ return auditedPolicyWrite({
415
+ target,
416
+ policyWrites,
417
+ principal,
418
+ context,
419
+ info,
420
+ args: argRecord,
421
+ evaluation,
422
+ decision,
423
+ mode,
424
+ prisma,
425
+ touched,
426
+ next: proceed,
427
+ });
428
+ };
429
+ }
430
+ async function auditedPolicyWrite(input) {
431
+ var _a, _b, _c;
432
+ const { target, principal, context, evaluation, decision, mode, prisma } = input;
433
+ let policies = [];
434
+ let policyReadFailed = false;
435
+ try {
436
+ const root = target.model === 'TradingPolicy' ? (await input.touched()).policies : [];
437
+ const nestedRows = input.policyWrites.length > 0 && prisma ? await (0, mutation_account_facts_1.resolveNestedPolicyRows)(prisma, input.policyWrites) : [];
438
+ policies = [...root, ...nestedRows];
439
+ }
440
+ catch (error) {
441
+ policyReadFailed = true;
442
+ logger_1.logger.error('[mutation-auth] trading-policy before-state could not be read', {
443
+ mutation: target.fieldName,
444
+ error: error instanceof Error ? error.message : String(error),
445
+ });
446
+ }
447
+ const entry = {
448
+ mutation: target.fieldName,
449
+ action: target.action,
450
+ nestedPaths: input.policyWrites.map((w) => w.path),
451
+ actor: (0, trading_policy_audit_1.actorFor)(principal, context.req),
452
+ changeReason: (0, trading_policy_audit_1.changeReasonFor)(context.req),
453
+ decision,
454
+ authorizationReason: evaluation.reason,
455
+ effectiveMode: policyReadFailed ? `${mode}:before_state_unread` : mode,
456
+ graphqlOperationName: (_c = (_b = (_a = input.info.operation) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.value) !== null && _c !== void 0 ? _c : null,
457
+ requested: input.args,
458
+ policies,
459
+ };
460
+ if ((policyReadFailed || (0, trading_policy_audit_1.mayTouchLiveAccount)(policies)) && (0, trading_policy_audit_1.touchesTradingSwitch)(input.args)) {
461
+ logger_1.logger.warn('[mutation-auth] trading-switch write on a LIVE or unidentified account', {
462
+ mutation: target.fieldName,
463
+ decision,
464
+ reason: evaluation.reason,
465
+ actor: entry.actor,
466
+ changeReason: entry.changeReason,
467
+ accounts: policies,
468
+ });
469
+ }
470
+ if (!prisma) {
471
+ logger_1.logger.error('[mutation-auth] no database client on the context; trading-policy write is unaudited', {
472
+ mutation: target.fieldName,
473
+ });
474
+ if (decision === 'denied')
475
+ throw refusalError(evaluation);
476
+ if (mode === 'enforce')
477
+ throw auditUnavailableError();
478
+ return input.next();
479
+ }
480
+ if (decision === 'denied') {
481
+ try {
482
+ await (0, trading_policy_audit_1.writeAttemptRow)(prisma, entry, 'denied');
483
+ }
484
+ catch (error) {
485
+ logger_1.logger.error('[mutation-auth] audit row for a refused trading-policy write failed', {
486
+ mutation: target.fieldName,
487
+ error: error instanceof Error ? error.message : String(error),
488
+ });
489
+ }
490
+ throw refusalError(evaluation);
491
+ }
492
+ let attemptId = null;
493
+ try {
494
+ attemptId = await (0, trading_policy_audit_1.writeAttemptRow)(prisma, entry, 'pending');
495
+ }
496
+ catch (error) {
497
+ const disarmOnly = (0, trading_policy_audit_1.isDisarmOnlyPolicyWrite)(target, input.args);
498
+ logger_1.logger.error('[mutation-auth] trading-policy attempt row could not be written', {
499
+ mutation: target.fieldName,
500
+ refused: mode === 'enforce' && !disarmOnly,
501
+ error: error instanceof Error ? error.message : String(error),
502
+ });
503
+ if (mode === 'enforce') {
504
+ if (!disarmOnly)
505
+ throw auditUnavailableError();
506
+ trading_policy_audit_1.mutationAuditBypassedTotal.inc({ reason: 'disarm_during_audit_outage' });
507
+ logger_1.logger.error('[mutation-auth] AuditLog unavailable; admitting a disarm-only trading-policy write unaudited', {
508
+ entry: (0, credential_redaction_1.redactCredentials)(entry),
509
+ });
510
+ }
511
+ }
512
+ let result;
513
+ try {
514
+ result = await input.next();
515
+ }
516
+ catch (error) {
517
+ await recordResult(prisma, entry, attemptId, 'failed', errorCodeOf(error));
518
+ throw error;
519
+ }
520
+ await recordResult(prisma, entry, attemptId, 'succeeded', null);
521
+ return result;
522
+ }
523
+ async function recordResult(prisma, entry, attemptId, outcome, errorCode) {
524
+ try {
525
+ await (0, trading_policy_audit_1.writeResultRow)(prisma, entry, attemptId, outcome, errorCode);
526
+ }
527
+ catch (error) {
528
+ logger_1.logger.error('[mutation-auth] trading-policy result row could not be written', {
529
+ mutation: entry.mutation,
530
+ attemptId,
531
+ outcome,
532
+ error: error instanceof Error ? error.message : String(error),
533
+ });
534
+ }
535
+ }
536
+ //# sourceMappingURL=mutation-auth-guard.js.map
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Mutation authorization guard: every GraphQL mutation is admitted only for a
3
+ * principal authorised to write that model and, for a brokerage account's
4
+ * policy or account row, that account.
5
+ *
6
+ * The decision itself lives in `src/auth/mutation-authorization.ts` (pure);
7
+ * this module installs it on the built schema, resolves the ownership,
8
+ * tenancy and membership-role facts a user principal's write needs (read
9
+ * from the database for the mutation, never from the token), counts and logs
10
+ * every decision, and writes the
11
+ * attributed TradingPolicy audit rows (`./trading-policy-audit.ts`).
12
+ *
13
+ * ## Why it wraps the Mutation fields instead of being a global middleware
14
+ *
15
+ * A TypeGraphQL global middleware is dispatched on EVERY field of every query.
16
+ * Measured on 500 rows x 8 fields, one extra global middleware — even one that
17
+ * returns after a single comparison — added ~0.35 us per field (4.2 → 5.6 ms
18
+ * per query), a cost the platform's read-heavy traffic would pay for a check
19
+ * that only ever applies to root Mutation fields. So the guard wraps the
20
+ * `resolve` of each root Mutation field on the built schema: reads pay nothing,
21
+ * and every mutation — generated or hand-written — is covered, because the
22
+ * set wrapped is the schema's own Mutation type, not a list someone maintains.
23
+ *
24
+ * Each root field of a multi-field (batched or aliased) operation is its own
25
+ * resolver call, so each is decided on its own: an allowed field never carries
26
+ * a refused sibling through with it. The guard runs outside the TypeGraphQL
27
+ * middleware chain, so it decides before the credential-field guard and the
28
+ * tenancy scoping see the field.
29
+ *
30
+ * ## Credential predicates are refused before anything is read
31
+ *
32
+ * Deciding a mutation can read rows with the caller's own `where` (ownership
33
+ * and tenancy facts, the TradingPolicy before-state), and the audit rows
34
+ * record the ids and accounts that read matched. Because this guard runs
35
+ * first, a `where` over a stored credential would be executed here before the
36
+ * credential-field guard ever refused it, and the matched rows would land in
37
+ * AuditLog: an oracle over the credential, open in every mutation-auth mode,
38
+ * the denied branch included. So the guard applies the credential-field
39
+ * guard's predicate rule itself, as its first step: a non-service principal
40
+ * whose arguments name a credential column is refused before any read and
41
+ * before any audit row, whenever that guard enforces.
42
+ *
43
+ * ## Nested writes and modes
44
+ *
45
+ * A root field's arguments can write far beyond its own model (nested
46
+ * `create` / `update` / `connect` along relations). Every nested container is
47
+ * decided on its own hop (`src/auth/nested-write-policy.ts`), and the mutation
48
+ * is decided at the strictest mode among every model it writes, so an
49
+ * escalated model cannot be written through a shadow-mode root.
50
+ *
51
+ * @module middleware/mutation-auth-guard
52
+ */
53
+ import { type GraphQLSchema } from 'graphql';
54
+ import { Counter } from 'prom-client';
55
+ import { type MutationAuthMode } from '../auth/mutation-authorization';
56
+ import { type RelationFacts } from '../auth/nested-write-policy';
57
+ import type { BackendPrincipal } from '../auth/token-verifier';
58
+ import { type CredentialFieldGuardMode } from './credential-field-guard';
59
+ import { type ActorRequest } from './trading-policy-audit';
60
+ /**
61
+ * Mutation decisions by mutation field, principal kind, decision and reason.
62
+ * Every label is bounded: the mutation field must exist in the schema to
63
+ * reach a resolver, and the other three are closed enums. The `would_deny`
64
+ * series is the list of callers enforcement would break.
65
+ */
66
+ export declare const mutationAuthorizationTotal: Counter<"mutation" | "reason" | "decision" | "principal_kind">;
67
+ /** GraphQL context shape the guard reads. */
68
+ export interface MutationAuthGuardContext {
69
+ principal?: BackendPrincipal | null;
70
+ prisma?: unknown;
71
+ req?: ActorRequest;
72
+ }
73
+ /** Options for {@link createMutationAuthGuardMiddleware}; defaults read the environment. */
74
+ export interface MutationAuthGuardOptions {
75
+ modeProvider?: () => MutationAuthMode;
76
+ enforcedModelsProvider?: () => ReadonlySet<string>;
77
+ models?: readonly string[];
78
+ /** Foreign-key placement per relation; defaults to the Prisma data model. */
79
+ relations?: RelationFacts;
80
+ /** The credential-field guard's mode; defaults to `CREDENTIAL_FIELD_GUARD_MODE`. */
81
+ credentialGuardModeProvider?: () => CredentialFieldGuardMode;
82
+ now?: () => number;
83
+ }
84
+ /**
85
+ * Foreign-key placement read from the Prisma data model: `Model.relation`
86
+ * holds the key when its `relationFromFields` is non-empty.
87
+ */
88
+ export declare function prismaRelationFacts(): RelationFacts;
89
+ /** @internal Test hook: forget the log throttle state. */
90
+ export declare function resetMutationAuthLogThrottle(): void;
91
+ /**
92
+ * Wrap every root Mutation field of a built schema with the guard.
93
+ *
94
+ * @param schema - The schema `buildSchema` returned; mutated in place.
95
+ * @param options - Optional overrides for tests.
96
+ * @returns How many Mutation fields are guarded (for the boot log; zero means
97
+ * the schema has no Mutation type and nothing is protected).
98
+ */
99
+ export declare function installMutationAuthGuard(schema: GraphQLSchema, options?: MutationAuthGuardOptions): number;
100
+ //# sourceMappingURL=mutation-auth-guard.d.ts.map