@adaptic/backend-legacy 0.0.1057 → 0.0.1059
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 +339 -0
- package/auth/service-token.d.ts +106 -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 +57 -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/esm/auth/service-token.d.ts +12 -0
- package/esm/auth/service-token.mjs +27 -5
- package/esm/config/jwtConfig.mjs +5 -1
- 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,353 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Attributed audit rows for every TradingPolicy write.
|
|
4
|
+
*
|
|
5
|
+
* `TradingPolicy` carries the switches that decide whether a brokerage account
|
|
6
|
+
* trades at all — `realtimeTradingEnabled`, `paperTradingOnly`,
|
|
7
|
+
* `killSwitchEnabled`, `autonomyMode` — and on a LIVE account flipping one is
|
|
8
|
+
* a capital decision. The generic mutation audit plugin cannot answer "who
|
|
9
|
+
* did this": it records a user id only for a UUID subject (so a service write
|
|
10
|
+
* or an anonymous one is `null`), records nothing for a mutation that failed
|
|
11
|
+
* or was refused, and reads the payload from `variables` (so an inline
|
|
12
|
+
* argument records as empty). A LIVE-flag change that nobody can attribute is
|
|
13
|
+
* the defect this module exists to close.
|
|
14
|
+
*
|
|
15
|
+
* Every TradingPolicy write — a root `…TradingPolicy` mutation or a nested
|
|
16
|
+
* `tradingPolicy: { … }` write under another model — produces:
|
|
17
|
+
*
|
|
18
|
+
* 1. an `attempt` row, written BEFORE the resolver runs, carrying the actor
|
|
19
|
+
* (principal kind, subject, email, IP, user agent, origin), the caller's
|
|
20
|
+
* stated reason (`X-Adaptic-Change-Reason` header), the authorization
|
|
21
|
+
* decision and its reason, the requested change, and each touched account's
|
|
22
|
+
* type and current switch values; and
|
|
23
|
+
* 2. a `result` row after it, carrying the outcome, linked by `attemptId`.
|
|
24
|
+
*
|
|
25
|
+
* Each touched policy is resolved from its OWN argument path: a nested write
|
|
26
|
+
* that reaches a different account than the root's is recorded against that
|
|
27
|
+
* account, and one whose account the arguments do not identify is recorded
|
|
28
|
+
* as `unresolved` — never attributed to the root's account.
|
|
29
|
+
*
|
|
30
|
+
* A refused write produces only the `attempt` row (its outcome is `denied`).
|
|
31
|
+
*
|
|
32
|
+
* Writing the attempt row first is what makes the record durable: if the
|
|
33
|
+
* attempt row cannot be written and the mutation is being enforced, the
|
|
34
|
+
* mutation is refused rather than executed unattributed. The caller decides
|
|
35
|
+
* that; this module reports the failure and never swallows it. The one
|
|
36
|
+
* exception is a write that only DISARMS ({@link isDisarmOnlyPolicyWrite}):
|
|
37
|
+
* refusing it during an AuditLog outage would block the protective direction
|
|
38
|
+
* (a kill switch, `realtimeTradingEnabled = false`) exactly when the system is
|
|
39
|
+
* degraded, so it is admitted, counted on
|
|
40
|
+
* `graphql_mutation_audit_bypassed_total`, and logged in full at error level.
|
|
41
|
+
*
|
|
42
|
+
* @module middleware/trading-policy-audit
|
|
43
|
+
*/
|
|
44
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
45
|
+
exports.mutationAuditWriteFailuresTotal = exports.mutationAuditBypassedTotal = exports.TRADING_SWITCH_FIELDS = exports.CHANGE_REASON_HEADER = void 0;
|
|
46
|
+
exports.mayTouchLiveAccount = mayTouchLiveAccount;
|
|
47
|
+
exports.sanitizeHeader = sanitizeHeader;
|
|
48
|
+
exports.actorFor = actorFor;
|
|
49
|
+
exports.changeReasonFor = changeReasonFor;
|
|
50
|
+
exports.touchesTradingSwitch = touchesTradingSwitch;
|
|
51
|
+
exports.writeAttemptRow = writeAttemptRow;
|
|
52
|
+
exports.writeResultRow = writeResultRow;
|
|
53
|
+
exports.isDisarmOnlyPolicyWrite = isDisarmOnlyPolicyWrite;
|
|
54
|
+
exports.wsActorRequest = wsActorRequest;
|
|
55
|
+
const prom_client_1 = require("prom-client");
|
|
56
|
+
const credential_redaction_1 = require("../auth/credential-redaction.cjs");
|
|
57
|
+
const metrics_1 = require("../config/metrics.cjs");
|
|
58
|
+
/** Header a caller uses to state why it is changing a policy. */
|
|
59
|
+
exports.CHANGE_REASON_HEADER = 'x-adaptic-change-reason';
|
|
60
|
+
/** Longest change reason recorded, in characters. */
|
|
61
|
+
const MAX_CHANGE_REASON_LENGTH = 500;
|
|
62
|
+
/** Longest free-text header value (user agent, origin) recorded. */
|
|
63
|
+
const MAX_HEADER_LENGTH = 300;
|
|
64
|
+
/**
|
|
65
|
+
* The switches whose change arms or disarms an account. `intradayLanePrefs`
|
|
66
|
+
* is the single carrier of the account's multi-lane opt-in (its `armed`
|
|
67
|
+
* member), so a write to it can arm the lanes exactly as a write to
|
|
68
|
+
* `realtimeTradingEnabled` can arm the account: it is audited, warned on and
|
|
69
|
+
* classified as a switch like the others.
|
|
70
|
+
*/
|
|
71
|
+
exports.TRADING_SWITCH_FIELDS = [
|
|
72
|
+
'realtimeTradingEnabled',
|
|
73
|
+
'paperTradingOnly',
|
|
74
|
+
'killSwitchEnabled',
|
|
75
|
+
'autonomyMode',
|
|
76
|
+
'intradayLanePrefs',
|
|
77
|
+
];
|
|
78
|
+
/**
|
|
79
|
+
* Whether a write may touch a LIVE account's switches: a resolved LIVE
|
|
80
|
+
* account, or any account the guard could not identify (which may be LIVE).
|
|
81
|
+
*/
|
|
82
|
+
function mayTouchLiveAccount(policies) {
|
|
83
|
+
return policies.some((p) => p.accountType === 'LIVE' || p.resolution !== 'resolved');
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Disarm-only TradingPolicy writes admitted without an attempt row because
|
|
87
|
+
* AuditLog was unavailable under enforce. Each is also logged in full.
|
|
88
|
+
*/
|
|
89
|
+
exports.mutationAuditBypassedTotal = new prom_client_1.Counter({
|
|
90
|
+
name: 'graphql_mutation_audit_bypassed_total',
|
|
91
|
+
help: 'TradingPolicy writes admitted under enforce without an attempt audit row, by reason. ' +
|
|
92
|
+
'Only disarm-only writes (kill switch on, trading off, paper only, safe autonomy) qualify.',
|
|
93
|
+
labelNames: ['reason'],
|
|
94
|
+
registers: [metrics_1.metricsRegistry],
|
|
95
|
+
});
|
|
96
|
+
/** Audit-row write failures, by phase. Non-zero means an unattributed write risk. */
|
|
97
|
+
exports.mutationAuditWriteFailuresTotal = new prom_client_1.Counter({
|
|
98
|
+
name: 'graphql_mutation_audit_write_failures_total',
|
|
99
|
+
help: 'TradingPolicy audit rows that could not be written, by phase (attempt | result). ' +
|
|
100
|
+
'An attempt failure under enforce refuses the mutation; under shadow the write proceeds unattributed.',
|
|
101
|
+
labelNames: ['phase'],
|
|
102
|
+
registers: [metrics_1.metricsRegistry],
|
|
103
|
+
});
|
|
104
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
105
|
+
/** C0 control characters and DEL: a header carrying them could forge log or row structure. */
|
|
106
|
+
const FIRST_PRINTABLE = 0x20;
|
|
107
|
+
const DELETE = 0x7f;
|
|
108
|
+
function isControlCharacter(ch) {
|
|
109
|
+
const code = ch.charCodeAt(0);
|
|
110
|
+
return code < FIRST_PRINTABLE || code === DELETE;
|
|
111
|
+
}
|
|
112
|
+
/** Collapse control characters and bound the length of a header value. */
|
|
113
|
+
function sanitizeHeader(value, max) {
|
|
114
|
+
const raw = Array.isArray(value) ? value.join(',') : value;
|
|
115
|
+
if (typeof raw !== 'string')
|
|
116
|
+
return null;
|
|
117
|
+
const clean = [...raw]
|
|
118
|
+
.map((ch) => (isControlCharacter(ch) ? ' ' : ch))
|
|
119
|
+
.join('')
|
|
120
|
+
.replace(/ {2,}/g, ' ')
|
|
121
|
+
.trim();
|
|
122
|
+
if (clean.length === 0)
|
|
123
|
+
return null;
|
|
124
|
+
return clean.length > max ? `${clean.slice(0, max)}…` : clean;
|
|
125
|
+
}
|
|
126
|
+
/** Build the actor record for a request. */
|
|
127
|
+
function actorFor(principal, req) {
|
|
128
|
+
var _a, _b, _c, _d;
|
|
129
|
+
const headers = (_a = req === null || req === void 0 ? void 0 : req.headers) !== null && _a !== void 0 ? _a : {};
|
|
130
|
+
const base = {
|
|
131
|
+
ip: (_b = req === null || req === void 0 ? void 0 : req.ip) !== null && _b !== void 0 ? _b : null,
|
|
132
|
+
userAgent: sanitizeHeader(headers['user-agent'], MAX_HEADER_LENGTH),
|
|
133
|
+
origin: sanitizeHeader(headers.origin, MAX_HEADER_LENGTH),
|
|
134
|
+
};
|
|
135
|
+
if (!principal)
|
|
136
|
+
return { principalKind: 'none', sub: null, email: null, ...base };
|
|
137
|
+
if (principal.kind === 'server') {
|
|
138
|
+
return { principalKind: 'server', sub: (_c = principal.sub) !== null && _c !== void 0 ? _c : null, email: null, ...base };
|
|
139
|
+
}
|
|
140
|
+
return { principalKind: principal.kind, sub: principal.sub, email: (_d = principal.email) !== null && _d !== void 0 ? _d : null, ...base };
|
|
141
|
+
}
|
|
142
|
+
/** The caller's stated reason for the change, if it gave one. */
|
|
143
|
+
function changeReasonFor(req) {
|
|
144
|
+
var _a;
|
|
145
|
+
return sanitizeHeader((_a = req === null || req === void 0 ? void 0 : req.headers) === null || _a === void 0 ? void 0 : _a[exports.CHANGE_REASON_HEADER], MAX_CHANGE_REASON_LENGTH);
|
|
146
|
+
}
|
|
147
|
+
/** Whether a requested payload names any trading switch at any depth. */
|
|
148
|
+
function touchesTradingSwitch(requested) {
|
|
149
|
+
if (requested === null || typeof requested !== 'object')
|
|
150
|
+
return false;
|
|
151
|
+
for (const [key, child] of Object.entries(requested)) {
|
|
152
|
+
if (isTradingSwitchField(key))
|
|
153
|
+
return true;
|
|
154
|
+
if (touchesTradingSwitch(child))
|
|
155
|
+
return true;
|
|
156
|
+
}
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
function operationTypeFor(action) {
|
|
160
|
+
if (action === 'create')
|
|
161
|
+
return 'CREATE';
|
|
162
|
+
if (action === 'delete')
|
|
163
|
+
return 'DELETE';
|
|
164
|
+
return 'UPDATE';
|
|
165
|
+
}
|
|
166
|
+
function recordIdFor(policies) {
|
|
167
|
+
if (policies.length === 1) {
|
|
168
|
+
const [row] = policies;
|
|
169
|
+
if (row.policyId)
|
|
170
|
+
return row.policyId;
|
|
171
|
+
return row.alpacaAccountId ? `alpacaAccount:${row.alpacaAccountId}` : row.resolution;
|
|
172
|
+
}
|
|
173
|
+
return policies.length === 0 ? 'unresolved' : `bulk:${policies.length}`;
|
|
174
|
+
}
|
|
175
|
+
function rowData(entry, phase, outcome, extra) {
|
|
176
|
+
const { actor } = entry;
|
|
177
|
+
return {
|
|
178
|
+
userId: actor.sub !== null && UUID.test(actor.sub) ? actor.sub : null,
|
|
179
|
+
operationType: operationTypeFor(entry.action),
|
|
180
|
+
modelName: 'TradingPolicy',
|
|
181
|
+
recordId: recordIdFor(entry.policies),
|
|
182
|
+
operationName: entry.mutation,
|
|
183
|
+
ipAddress: actor.ip ? actor.ip.slice(0, 45) : null,
|
|
184
|
+
changedFields: (0, credential_redaction_1.redactCredentials)({
|
|
185
|
+
requested: entry.requested,
|
|
186
|
+
nestedPaths: entry.nestedPaths,
|
|
187
|
+
}),
|
|
188
|
+
metadata: (0, credential_redaction_1.redactCredentials)({
|
|
189
|
+
source: 'mutation-auth-guard',
|
|
190
|
+
phase,
|
|
191
|
+
outcome,
|
|
192
|
+
actor,
|
|
193
|
+
changeReason: entry.changeReason,
|
|
194
|
+
decision: entry.decision,
|
|
195
|
+
authorizationReason: entry.authorizationReason,
|
|
196
|
+
effectiveMode: entry.effectiveMode,
|
|
197
|
+
graphqlOperationName: entry.graphqlOperationName,
|
|
198
|
+
tradingSwitchTouched: touchesTradingSwitch(entry.requested),
|
|
199
|
+
accounts: entry.policies,
|
|
200
|
+
...extra,
|
|
201
|
+
}),
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Write the pre-execution `attempt` row.
|
|
206
|
+
*
|
|
207
|
+
* @returns The new row's id.
|
|
208
|
+
* @throws Whatever the database raised; the caller decides whether that
|
|
209
|
+
* refuses the mutation. The failure is counted before it propagates.
|
|
210
|
+
*/
|
|
211
|
+
async function writeAttemptRow(prisma, entry, outcome) {
|
|
212
|
+
try {
|
|
213
|
+
const row = await prisma.auditLog.create({ data: rowData(entry, 'attempt', outcome, {}) });
|
|
214
|
+
return row.id;
|
|
215
|
+
}
|
|
216
|
+
catch (error) {
|
|
217
|
+
exports.mutationAuditWriteFailuresTotal.inc({ phase: 'attempt' });
|
|
218
|
+
throw error;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Write the post-execution `result` row, linked to its attempt.
|
|
223
|
+
*
|
|
224
|
+
* @throws Whatever the database raised, after counting it. The mutation has
|
|
225
|
+
* already run at this point; the caller logs the failure loudly because the
|
|
226
|
+
* attempt row, not this one, is the attribution of record.
|
|
227
|
+
*/
|
|
228
|
+
async function writeResultRow(prisma, entry, attemptId, outcome, errorCode) {
|
|
229
|
+
try {
|
|
230
|
+
await prisma.auditLog.create({
|
|
231
|
+
data: rowData(entry, 'result', outcome, { attemptId, errorCode }),
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
catch (error) {
|
|
235
|
+
exports.mutationAuditWriteFailuresTotal.inc({ phase: 'result' });
|
|
236
|
+
throw error;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Whether an `intradayLanePrefs` value leaves the account's lanes disarmed:
|
|
241
|
+
* a null (no preferences, which reads as disarmed) or an object whose `armed`
|
|
242
|
+
* member is exactly `false`. Any other value may arm, so it is not a disarm.
|
|
243
|
+
*/
|
|
244
|
+
function isDisarmedLanePrefs(value) {
|
|
245
|
+
if (value === null)
|
|
246
|
+
return true;
|
|
247
|
+
if (typeof value !== 'object' || Array.isArray(value))
|
|
248
|
+
return false;
|
|
249
|
+
return value.armed === false;
|
|
250
|
+
}
|
|
251
|
+
/** Whether a value is the one a write DISARMING each trading switch sets. */
|
|
252
|
+
const DISARMS = {
|
|
253
|
+
realtimeTradingEnabled: (value) => value === false,
|
|
254
|
+
killSwitchEnabled: (value) => value === true,
|
|
255
|
+
paperTradingOnly: (value) => value === true,
|
|
256
|
+
autonomyMode: (value) => value === 'ADVISORY_ONLY' || value === 'EMERGENCY_SAFE_MODE',
|
|
257
|
+
intradayLanePrefs: isDisarmedLanePrefs,
|
|
258
|
+
};
|
|
259
|
+
/**
|
|
260
|
+
* Switches whose generated update input carries the value itself rather than
|
|
261
|
+
* `{ set: value }`: a JSON column is written as its new value.
|
|
262
|
+
*/
|
|
263
|
+
const JSON_SWITCH_FIELDS = new Set(['intradayLanePrefs']);
|
|
264
|
+
/** Whether a data key names a trading switch. */
|
|
265
|
+
function isTradingSwitchField(key) {
|
|
266
|
+
return exports.TRADING_SWITCH_FIELDS.includes(key);
|
|
267
|
+
}
|
|
268
|
+
/** Bookkeeping fields a disarm write may also set. */
|
|
269
|
+
const DISARM_BOOKKEEPING_FIELDS = new Set(['lastModifiedBy', 'lastModifiedAt', 'version']);
|
|
270
|
+
/** The value a generated update input sets: `{ set: v }` → `v`; anything else is not a plain set. */
|
|
271
|
+
function setValueOf(value) {
|
|
272
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
273
|
+
return null;
|
|
274
|
+
const record = value;
|
|
275
|
+
const keys = Object.keys(record).filter((key) => record[key] !== undefined);
|
|
276
|
+
return keys.length === 1 && keys[0] === 'set' ? { value: record.set } : null;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Whether a root `updateOneTradingPolicy` only disarms: it sets at least one
|
|
280
|
+
* trading switch, every switch it sets moves to its disarmed value, and every
|
|
281
|
+
* other field it sets is bookkeeping (or re-states the row's own `id`). Any
|
|
282
|
+
* other shape — a nested write, an upsert (which may create an armed policy),
|
|
283
|
+
* a bulk write, a change to limits — is not disarm-only.
|
|
284
|
+
*
|
|
285
|
+
* @param target - The classified root mutation field.
|
|
286
|
+
* @param args - The field's arguments.
|
|
287
|
+
*/
|
|
288
|
+
function isDisarmOnlyPolicyWrite(target, args) {
|
|
289
|
+
if (target.model !== 'TradingPolicy' || target.action !== 'update' || target.cardinality !== 'one') {
|
|
290
|
+
return false;
|
|
291
|
+
}
|
|
292
|
+
const data = args.data;
|
|
293
|
+
if (data === null || typeof data !== 'object' || Array.isArray(data))
|
|
294
|
+
return false;
|
|
295
|
+
const where = args.where;
|
|
296
|
+
let disarmed = 0;
|
|
297
|
+
for (const [key, raw] of Object.entries(data)) {
|
|
298
|
+
if (raw === undefined)
|
|
299
|
+
continue;
|
|
300
|
+
const set = isTradingSwitchField(key) && JSON_SWITCH_FIELDS.has(key) ? { value: raw } : setValueOf(raw);
|
|
301
|
+
if (!set)
|
|
302
|
+
return false;
|
|
303
|
+
if (isTradingSwitchField(key)) {
|
|
304
|
+
if (!DISARMS[key](set.value))
|
|
305
|
+
return false;
|
|
306
|
+
disarmed += 1;
|
|
307
|
+
}
|
|
308
|
+
else if (!DISARM_BOOKKEEPING_FIELDS.has(key) && !(key === 'id' && (where === null || where === void 0 ? void 0 : where.id) === set.value)) {
|
|
309
|
+
return false;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return disarmed > 0;
|
|
313
|
+
}
|
|
314
|
+
/** Case-insensitive read of one key from a WebSocket `connectionParams` bag. */
|
|
315
|
+
function connectionParam(params, name) {
|
|
316
|
+
if (params === null || typeof params !== 'object')
|
|
317
|
+
return undefined;
|
|
318
|
+
for (const [key, value] of Object.entries(params)) {
|
|
319
|
+
if (key.toLowerCase() === name && typeof value === 'string')
|
|
320
|
+
return value;
|
|
321
|
+
}
|
|
322
|
+
return undefined;
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* The actor request for a GraphQL-over-WebSocket operation, so a mutation
|
|
326
|
+
* sent over `/subscriptions` is attributed like an HTTP one: IP (socket
|
|
327
|
+
* remote address), user agent and origin from the upgrade request, and the
|
|
328
|
+
* change reason from the upgrade request's `X-Adaptic-Change-Reason` header
|
|
329
|
+
* or the connection's `connectionParams` (a browser cannot set headers on a
|
|
330
|
+
* WebSocket upgrade). The reason is per connection, not per operation.
|
|
331
|
+
*
|
|
332
|
+
* @param extra - graphql-ws `ctx.extra` (carries the upgrade `request`).
|
|
333
|
+
* @param connectionParams - graphql-ws `ctx.connectionParams`.
|
|
334
|
+
*/
|
|
335
|
+
function wsActorRequest(extra, connectionParams) {
|
|
336
|
+
var _a;
|
|
337
|
+
const request = extra !== null && typeof extra === 'object' ? extra.request : undefined;
|
|
338
|
+
const req = request !== null && typeof request === 'object' ? request : {};
|
|
339
|
+
const rawHeaders = req.headers !== null && typeof req.headers === 'object' ? req.headers : {};
|
|
340
|
+
const headers = {};
|
|
341
|
+
for (const name of ['user-agent', 'origin', exports.CHANGE_REASON_HEADER]) {
|
|
342
|
+
const value = rawHeaders[name];
|
|
343
|
+
if (typeof value === 'string' || Array.isArray(value))
|
|
344
|
+
headers[name] = value;
|
|
345
|
+
}
|
|
346
|
+
(_a = headers[exports.CHANGE_REASON_HEADER]) !== null && _a !== void 0 ? _a : (headers[exports.CHANGE_REASON_HEADER] = connectionParam(connectionParams, exports.CHANGE_REASON_HEADER));
|
|
347
|
+
const socket = req.socket !== null && typeof req.socket === 'object' ? req.socket : {};
|
|
348
|
+
return {
|
|
349
|
+
ip: typeof socket.remoteAddress === 'string' ? socket.remoteAddress : undefined,
|
|
350
|
+
headers,
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
//# sourceMappingURL=trading-policy-audit.js.map
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Attributed audit rows for every TradingPolicy write.
|
|
3
|
+
*
|
|
4
|
+
* `TradingPolicy` carries the switches that decide whether a brokerage account
|
|
5
|
+
* trades at all — `realtimeTradingEnabled`, `paperTradingOnly`,
|
|
6
|
+
* `killSwitchEnabled`, `autonomyMode` — and on a LIVE account flipping one is
|
|
7
|
+
* a capital decision. The generic mutation audit plugin cannot answer "who
|
|
8
|
+
* did this": it records a user id only for a UUID subject (so a service write
|
|
9
|
+
* or an anonymous one is `null`), records nothing for a mutation that failed
|
|
10
|
+
* or was refused, and reads the payload from `variables` (so an inline
|
|
11
|
+
* argument records as empty). A LIVE-flag change that nobody can attribute is
|
|
12
|
+
* the defect this module exists to close.
|
|
13
|
+
*
|
|
14
|
+
* Every TradingPolicy write — a root `…TradingPolicy` mutation or a nested
|
|
15
|
+
* `tradingPolicy: { … }` write under another model — produces:
|
|
16
|
+
*
|
|
17
|
+
* 1. an `attempt` row, written BEFORE the resolver runs, carrying the actor
|
|
18
|
+
* (principal kind, subject, email, IP, user agent, origin), the caller's
|
|
19
|
+
* stated reason (`X-Adaptic-Change-Reason` header), the authorization
|
|
20
|
+
* decision and its reason, the requested change, and each touched account's
|
|
21
|
+
* type and current switch values; and
|
|
22
|
+
* 2. a `result` row after it, carrying the outcome, linked by `attemptId`.
|
|
23
|
+
*
|
|
24
|
+
* Each touched policy is resolved from its OWN argument path: a nested write
|
|
25
|
+
* that reaches a different account than the root's is recorded against that
|
|
26
|
+
* account, and one whose account the arguments do not identify is recorded
|
|
27
|
+
* as `unresolved` — never attributed to the root's account.
|
|
28
|
+
*
|
|
29
|
+
* A refused write produces only the `attempt` row (its outcome is `denied`).
|
|
30
|
+
*
|
|
31
|
+
* Writing the attempt row first is what makes the record durable: if the
|
|
32
|
+
* attempt row cannot be written and the mutation is being enforced, the
|
|
33
|
+
* mutation is refused rather than executed unattributed. The caller decides
|
|
34
|
+
* that; this module reports the failure and never swallows it. The one
|
|
35
|
+
* exception is a write that only DISARMS ({@link isDisarmOnlyPolicyWrite}):
|
|
36
|
+
* refusing it during an AuditLog outage would block the protective direction
|
|
37
|
+
* (a kill switch, `realtimeTradingEnabled = false`) exactly when the system is
|
|
38
|
+
* degraded, so it is admitted, counted on
|
|
39
|
+
* `graphql_mutation_audit_bypassed_total`, and logged in full at error level.
|
|
40
|
+
*
|
|
41
|
+
* @module middleware/trading-policy-audit
|
|
42
|
+
*/
|
|
43
|
+
import type { Prisma } from '@prisma/client';
|
|
44
|
+
import { Counter } from 'prom-client';
|
|
45
|
+
import type { MutationAction, MutationAuthReason } from '../auth/mutation-authorization';
|
|
46
|
+
import type { BackendPrincipal } from '../auth/token-verifier';
|
|
47
|
+
/** Header a caller uses to state why it is changing a policy. */
|
|
48
|
+
export declare const CHANGE_REASON_HEADER = "x-adaptic-change-reason";
|
|
49
|
+
/**
|
|
50
|
+
* The switches whose change arms or disarms an account. `intradayLanePrefs`
|
|
51
|
+
* is the single carrier of the account's multi-lane opt-in (its `armed`
|
|
52
|
+
* member), so a write to it can arm the lanes exactly as a write to
|
|
53
|
+
* `realtimeTradingEnabled` can arm the account: it is audited, warned on and
|
|
54
|
+
* classified as a switch like the others.
|
|
55
|
+
*/
|
|
56
|
+
export declare const TRADING_SWITCH_FIELDS: readonly ["realtimeTradingEnabled", "paperTradingOnly", "killSwitchEnabled", "autonomyMode", "intradayLanePrefs"];
|
|
57
|
+
/** One trading switch's name. */
|
|
58
|
+
export type TradingSwitchField = (typeof TRADING_SWITCH_FIELDS)[number];
|
|
59
|
+
/**
|
|
60
|
+
* The switch values of one policy as they stood before the write. A JSON
|
|
61
|
+
* switch (`intradayLanePrefs`) is recorded as its stored value.
|
|
62
|
+
*/
|
|
63
|
+
export type TradingSwitches = Partial<Record<TradingSwitchField, boolean | string | Prisma.JsonValue | null>>;
|
|
64
|
+
/**
|
|
65
|
+
* How a touched policy's account was identified: read from the database
|
|
66
|
+
* (`resolved`), created by this same mutation (`new_account`), or not
|
|
67
|
+
* identifiable from the arguments (`unresolved`).
|
|
68
|
+
*/
|
|
69
|
+
export type PolicyResolution = 'resolved' | 'new_account' | 'unresolved';
|
|
70
|
+
/** A policy row the write will touch, as read before the write. */
|
|
71
|
+
export interface AuditedPolicyRow {
|
|
72
|
+
/** Argument path of the nested write that reaches it; `null` for a root write. */
|
|
73
|
+
readonly nestedPath: string | null;
|
|
74
|
+
readonly resolution: PolicyResolution;
|
|
75
|
+
readonly policyId: string | null;
|
|
76
|
+
readonly alpacaAccountId: string | null;
|
|
77
|
+
readonly accountType: string | null;
|
|
78
|
+
readonly before: TradingSwitches | null;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Whether a write may touch a LIVE account's switches: a resolved LIVE
|
|
82
|
+
* account, or any account the guard could not identify (which may be LIVE).
|
|
83
|
+
*/
|
|
84
|
+
export declare function mayTouchLiveAccount(policies: readonly AuditedPolicyRow[]): boolean;
|
|
85
|
+
/** Who is writing, as far as the request can prove and report it. */
|
|
86
|
+
export interface AuditActor {
|
|
87
|
+
readonly principalKind: BackendPrincipal['kind'] | 'none';
|
|
88
|
+
readonly sub: string | null;
|
|
89
|
+
readonly email: string | null;
|
|
90
|
+
readonly ip: string | null;
|
|
91
|
+
readonly userAgent: string | null;
|
|
92
|
+
readonly origin: string | null;
|
|
93
|
+
}
|
|
94
|
+
/** Outcome recorded on a row. */
|
|
95
|
+
export type AuditOutcome = 'pending' | 'denied' | 'succeeded' | 'failed';
|
|
96
|
+
/** Everything recorded about one TradingPolicy write attempt. */
|
|
97
|
+
export interface TradingPolicyAuditEntry {
|
|
98
|
+
readonly mutation: string;
|
|
99
|
+
readonly action: MutationAction | 'custom';
|
|
100
|
+
/** Argument paths of the nested TradingPolicy writes; empty for a root write. */
|
|
101
|
+
readonly nestedPaths: readonly string[];
|
|
102
|
+
readonly actor: AuditActor;
|
|
103
|
+
readonly changeReason: string | null;
|
|
104
|
+
readonly decision: 'allowed' | 'would_deny' | 'denied';
|
|
105
|
+
readonly authorizationReason: MutationAuthReason;
|
|
106
|
+
readonly effectiveMode: string;
|
|
107
|
+
readonly graphqlOperationName: string | null;
|
|
108
|
+
readonly requested: Record<string, unknown>;
|
|
109
|
+
readonly policies: readonly AuditedPolicyRow[];
|
|
110
|
+
}
|
|
111
|
+
/** The slice of the Prisma client this module writes through. */
|
|
112
|
+
export interface AuditLogWriter {
|
|
113
|
+
auditLog: {
|
|
114
|
+
create(args: {
|
|
115
|
+
data: Record<string, unknown>;
|
|
116
|
+
}): Promise<{
|
|
117
|
+
id: string;
|
|
118
|
+
}>;
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Disarm-only TradingPolicy writes admitted without an attempt row because
|
|
123
|
+
* AuditLog was unavailable under enforce. Each is also logged in full.
|
|
124
|
+
*/
|
|
125
|
+
export declare const mutationAuditBypassedTotal: Counter<"reason">;
|
|
126
|
+
/** Audit-row write failures, by phase. Non-zero means an unattributed write risk. */
|
|
127
|
+
export declare const mutationAuditWriteFailuresTotal: Counter<"phase">;
|
|
128
|
+
/** Collapse control characters and bound the length of a header value. */
|
|
129
|
+
export declare function sanitizeHeader(value: string | string[] | undefined, max: number): string | null;
|
|
130
|
+
/** The request slice the actor is read from. */
|
|
131
|
+
export interface ActorRequest {
|
|
132
|
+
ip?: string;
|
|
133
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
134
|
+
}
|
|
135
|
+
/** Build the actor record for a request. */
|
|
136
|
+
export declare function actorFor(principal: BackendPrincipal | null, req: ActorRequest | undefined): AuditActor;
|
|
137
|
+
/** The caller's stated reason for the change, if it gave one. */
|
|
138
|
+
export declare function changeReasonFor(req: ActorRequest | undefined): string | null;
|
|
139
|
+
/** Whether a requested payload names any trading switch at any depth. */
|
|
140
|
+
export declare function touchesTradingSwitch(requested: unknown): boolean;
|
|
141
|
+
/**
|
|
142
|
+
* Write the pre-execution `attempt` row.
|
|
143
|
+
*
|
|
144
|
+
* @returns The new row's id.
|
|
145
|
+
* @throws Whatever the database raised; the caller decides whether that
|
|
146
|
+
* refuses the mutation. The failure is counted before it propagates.
|
|
147
|
+
*/
|
|
148
|
+
export declare function writeAttemptRow(prisma: AuditLogWriter, entry: TradingPolicyAuditEntry, outcome: 'pending' | 'denied'): Promise<string>;
|
|
149
|
+
/**
|
|
150
|
+
* Write the post-execution `result` row, linked to its attempt.
|
|
151
|
+
*
|
|
152
|
+
* @throws Whatever the database raised, after counting it. The mutation has
|
|
153
|
+
* already run at this point; the caller logs the failure loudly because the
|
|
154
|
+
* attempt row, not this one, is the attribution of record.
|
|
155
|
+
*/
|
|
156
|
+
export declare function writeResultRow(prisma: AuditLogWriter, entry: TradingPolicyAuditEntry, attemptId: string | null, outcome: 'succeeded' | 'failed', errorCode: string | null): Promise<void>;
|
|
157
|
+
/**
|
|
158
|
+
* Whether a root `updateOneTradingPolicy` only disarms: it sets at least one
|
|
159
|
+
* trading switch, every switch it sets moves to its disarmed value, and every
|
|
160
|
+
* other field it sets is bookkeeping (or re-states the row's own `id`). Any
|
|
161
|
+
* other shape — a nested write, an upsert (which may create an armed policy),
|
|
162
|
+
* a bulk write, a change to limits — is not disarm-only.
|
|
163
|
+
*
|
|
164
|
+
* @param target - The classified root mutation field.
|
|
165
|
+
* @param args - The field's arguments.
|
|
166
|
+
*/
|
|
167
|
+
export declare function isDisarmOnlyPolicyWrite(target: {
|
|
168
|
+
readonly model: string;
|
|
169
|
+
readonly action: string;
|
|
170
|
+
readonly cardinality: string;
|
|
171
|
+
}, args: Record<string, unknown>): boolean;
|
|
172
|
+
/**
|
|
173
|
+
* The actor request for a GraphQL-over-WebSocket operation, so a mutation
|
|
174
|
+
* sent over `/subscriptions` is attributed like an HTTP one: IP (socket
|
|
175
|
+
* remote address), user agent and origin from the upgrade request, and the
|
|
176
|
+
* change reason from the upgrade request's `X-Adaptic-Change-Reason` header
|
|
177
|
+
* or the connection's `connectionParams` (a browser cannot set headers on a
|
|
178
|
+
* WebSocket upgrade). The reason is per connection, not per operation.
|
|
179
|
+
*
|
|
180
|
+
* @param extra - graphql-ws `ctx.extra` (carries the upgrade `request`).
|
|
181
|
+
* @param connectionParams - graphql-ws `ctx.connectionParams`.
|
|
182
|
+
*/
|
|
183
|
+
export declare function wsActorRequest(extra: unknown, connectionParams: unknown): ActorRequest;
|
|
184
|
+
//# sourceMappingURL=trading-policy-audit.d.ts.map
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Type definitions for validation middleware
|
|
4
|
+
*/
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.isValidationError = isValidationError;
|
|
7
|
+
const graphql_1 = require("graphql");
|
|
8
|
+
/**
|
|
9
|
+
* Type guard to check if an error is a ValidationError
|
|
10
|
+
*/
|
|
11
|
+
function isValidationError(error) {
|
|
12
|
+
var _a;
|
|
13
|
+
return (error instanceof graphql_1.GraphQLError &&
|
|
14
|
+
((_a = error.extensions) === null || _a === void 0 ? void 0 : _a.code) === 'BAD_USER_INPUT' &&
|
|
15
|
+
'validationErrors' in (error.extensions || {}));
|
|
16
|
+
}
|
|
17
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Type definitions for validation middleware
|
|
3
|
+
*/
|
|
4
|
+
import { GraphQLError } from 'graphql';
|
|
5
|
+
import { ValidationErrorDetail } from './input-validator';
|
|
6
|
+
/**
|
|
7
|
+
* Configuration options for the validation plugin
|
|
8
|
+
*/
|
|
9
|
+
export interface ValidationPluginOptions {
|
|
10
|
+
/**
|
|
11
|
+
* Whether to skip validation for specific operations
|
|
12
|
+
*/
|
|
13
|
+
skipOperations?: string[];
|
|
14
|
+
/**
|
|
15
|
+
* Custom validation rules to add to the default set
|
|
16
|
+
*/
|
|
17
|
+
customRules?: FieldValidationRule[];
|
|
18
|
+
/**
|
|
19
|
+
* Whether to log validation errors for debugging
|
|
20
|
+
*/
|
|
21
|
+
debug?: boolean;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Field validation rule definition
|
|
25
|
+
*/
|
|
26
|
+
export interface FieldValidationRule {
|
|
27
|
+
/**
|
|
28
|
+
* Regular expression pattern to match field names
|
|
29
|
+
*/
|
|
30
|
+
pattern: RegExp;
|
|
31
|
+
/**
|
|
32
|
+
* Validation function to apply to matching fields
|
|
33
|
+
* @param value - The field value to validate
|
|
34
|
+
* @param fieldName - The name of the field being validated
|
|
35
|
+
*/
|
|
36
|
+
validator: (value: unknown, fieldName: string) => void;
|
|
37
|
+
/**
|
|
38
|
+
* Human-readable description of what this rule validates
|
|
39
|
+
*/
|
|
40
|
+
description: string;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* GraphQL operation context with validation information
|
|
44
|
+
*/
|
|
45
|
+
export interface ValidationContext {
|
|
46
|
+
/**
|
|
47
|
+
* The GraphQL operation being executed
|
|
48
|
+
*/
|
|
49
|
+
operation: {
|
|
50
|
+
operation: 'query' | 'mutation' | 'subscription';
|
|
51
|
+
name?: {
|
|
52
|
+
value: string;
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* The request variables
|
|
57
|
+
*/
|
|
58
|
+
request: {
|
|
59
|
+
variables?: Record<string, unknown>;
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Result of a validation check
|
|
64
|
+
*/
|
|
65
|
+
export interface ValidationResult {
|
|
66
|
+
/**
|
|
67
|
+
* Whether validation passed
|
|
68
|
+
*/
|
|
69
|
+
valid: boolean;
|
|
70
|
+
/**
|
|
71
|
+
* Array of validation errors (empty if valid)
|
|
72
|
+
*/
|
|
73
|
+
errors: ValidationErrorDetail[];
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Type guard to check if an error is a ValidationError
|
|
77
|
+
*/
|
|
78
|
+
export declare function isValidationError(error: unknown): error is GraphQLError;
|
|
79
|
+
/**
|
|
80
|
+
* Type-safe validator function signature
|
|
81
|
+
*/
|
|
82
|
+
export type Validator<T> = (value: T, fieldName: string) => void;
|
|
83
|
+
/**
|
|
84
|
+
* Validation constraint types
|
|
85
|
+
*/
|
|
86
|
+
export type ValidationConstraint = 'isNumber' | 'isString' | 'range' | 'positive' | 'negative' | 'notEmpty' | 'email' | 'url' | 'minimum' | 'maximum' | 'sum' | 'comparison' | 'userLimit' | 'maxLength' | 'custom';
|
|
87
|
+
//# sourceMappingURL=types.d.ts.map
|