@adaptic/backend 0.0.1038 → 0.0.1039

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 (81) hide show
  1. package/esm/auth/credential-fields.d.ts +19 -0
  2. package/esm/auth/credential-fields.d.ts.map +1 -0
  3. package/esm/auth/credential-fields.js.map +1 -0
  4. package/esm/auth/credential-fields.mjs +42 -0
  5. package/esm/auth/credential-redaction.d.ts +56 -0
  6. package/esm/auth/credential-redaction.d.ts.map +1 -0
  7. package/esm/auth/credential-redaction.js.map +1 -0
  8. package/esm/auth/credential-redaction.mjs +99 -0
  9. package/esm/auth/mutation-authorization.d.ts +206 -0
  10. package/esm/auth/mutation-authorization.d.ts.map +1 -0
  11. package/esm/auth/mutation-authorization.js.map +1 -0
  12. package/esm/auth/mutation-authorization.mjs +271 -0
  13. package/esm/auth/nested-write-inspector.d.ts +94 -0
  14. package/esm/auth/nested-write-inspector.d.ts.map +1 -0
  15. package/esm/auth/nested-write-inspector.js.map +1 -0
  16. package/esm/auth/nested-write-inspector.mjs +185 -0
  17. package/esm/auth/nested-write-policy.d.ts +95 -0
  18. package/esm/auth/nested-write-policy.d.ts.map +1 -0
  19. package/esm/auth/nested-write-policy.js.map +1 -0
  20. package/esm/auth/nested-write-policy.mjs +154 -0
  21. package/esm/auth/service-token.d.ts +11 -1
  22. package/esm/auth/service-token.d.ts.map +1 -1
  23. package/esm/auth/service-token.js.map +1 -1
  24. package/esm/auth/service-token.mjs +31 -5
  25. package/esm/auth/token-verifier.d.ts +9 -1
  26. package/esm/auth/token-verifier.d.ts.map +1 -1
  27. package/esm/auth/token-verifier.js.map +1 -1
  28. package/esm/auth/user-write-content.d.ts +41 -0
  29. package/esm/auth/user-write-content.d.ts.map +1 -0
  30. package/esm/auth/user-write-content.js.map +1 -0
  31. package/esm/auth/user-write-content.mjs +100 -0
  32. package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts +55 -0
  33. package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts.map +1 -0
  34. package/esm/middleware/__tests__/credential-field-coverage.harness.js.map +1 -0
  35. package/esm/middleware/__tests__/credential-field-coverage.harness.mjs +438 -0
  36. package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +49 -0
  37. package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts.map +1 -0
  38. package/esm/middleware/__tests__/mutation-auth-guard.harness.js.map +1 -0
  39. package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +402 -0
  40. package/esm/middleware/__tests__/ts-node-harness.d.ts +10 -0
  41. package/esm/middleware/__tests__/ts-node-harness.d.ts.map +1 -0
  42. package/esm/middleware/__tests__/ts-node-harness.js.map +1 -0
  43. package/esm/middleware/__tests__/ts-node-harness.mjs +71 -0
  44. package/esm/middleware/audit-logger.d.ts +18 -1
  45. package/esm/middleware/audit-logger.d.ts.map +1 -1
  46. package/esm/middleware/audit-logger.js.map +1 -1
  47. package/esm/middleware/audit-logger.mjs +36 -13
  48. package/esm/middleware/audit-payload-guard.d.ts +85 -0
  49. package/esm/middleware/audit-payload-guard.d.ts.map +1 -0
  50. package/esm/middleware/audit-payload-guard.js.map +1 -0
  51. package/esm/middleware/audit-payload-guard.mjs +97 -0
  52. package/esm/middleware/credential-field-guard.d.ts +55 -7
  53. package/esm/middleware/credential-field-guard.d.ts.map +1 -1
  54. package/esm/middleware/credential-field-guard.js.map +1 -1
  55. package/esm/middleware/credential-field-guard.mjs +275 -106
  56. package/esm/middleware/generated-type-names.d.ts +44 -0
  57. package/esm/middleware/generated-type-names.d.ts.map +1 -0
  58. package/esm/middleware/generated-type-names.js.map +1 -0
  59. package/esm/middleware/generated-type-names.mjs +73 -0
  60. package/esm/middleware/guard-log-throttle.d.ts +80 -0
  61. package/esm/middleware/guard-log-throttle.d.ts.map +1 -0
  62. package/esm/middleware/guard-log-throttle.js.map +1 -0
  63. package/esm/middleware/guard-log-throttle.mjs +87 -0
  64. package/esm/middleware/mutation-account-facts.d.ts +140 -0
  65. package/esm/middleware/mutation-account-facts.d.ts.map +1 -0
  66. package/esm/middleware/mutation-account-facts.js.map +1 -0
  67. package/esm/middleware/mutation-account-facts.mjs +212 -0
  68. package/esm/middleware/mutation-auth-guard.d.ts +82 -0
  69. package/esm/middleware/mutation-auth-guard.d.ts.map +1 -0
  70. package/esm/middleware/mutation-auth-guard.js.map +1 -0
  71. package/esm/middleware/mutation-auth-guard.mjs +425 -0
  72. package/esm/middleware/mutation-tenant-facts.d.ts +58 -0
  73. package/esm/middleware/mutation-tenant-facts.d.ts.map +1 -0
  74. package/esm/middleware/mutation-tenant-facts.js.map +1 -0
  75. package/esm/middleware/mutation-tenant-facts.mjs +75 -0
  76. package/esm/middleware/trading-policy-audit.d.ts +172 -0
  77. package/esm/middleware/trading-policy-audit.d.ts.map +1 -0
  78. package/esm/middleware/trading-policy-audit.js.map +1 -0
  79. package/esm/middleware/trading-policy-audit.mjs +309 -0
  80. package/package.json +1 -1
  81. package/server.cjs +27 -2
@@ -0,0 +1,172 @@
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 { Counter } from 'prom-client';
44
+ import type { MutationAction, MutationAuthReason } from '../auth/mutation-authorization';
45
+ import type { BackendPrincipal } from '../auth/token-verifier';
46
+ /** Header a caller uses to state why it is changing a policy. */
47
+ export declare const CHANGE_REASON_HEADER = "x-adaptic-change-reason";
48
+ /** The switches whose change arms or disarms an account. */
49
+ export declare const TRADING_SWITCH_FIELDS: readonly ["realtimeTradingEnabled", "paperTradingOnly", "killSwitchEnabled", "autonomyMode"];
50
+ /** The switch values of one policy as they stood before the write. */
51
+ export type TradingSwitches = Partial<Record<(typeof TRADING_SWITCH_FIELDS)[number], boolean | string | null>>;
52
+ /**
53
+ * How a touched policy's account was identified: read from the database
54
+ * (`resolved`), created by this same mutation (`new_account`), or not
55
+ * identifiable from the arguments (`unresolved`).
56
+ */
57
+ export type PolicyResolution = 'resolved' | 'new_account' | 'unresolved';
58
+ /** A policy row the write will touch, as read before the write. */
59
+ export interface AuditedPolicyRow {
60
+ /** Argument path of the nested write that reaches it; `null` for a root write. */
61
+ readonly nestedPath: string | null;
62
+ readonly resolution: PolicyResolution;
63
+ readonly policyId: string | null;
64
+ readonly alpacaAccountId: string | null;
65
+ readonly accountType: string | null;
66
+ readonly before: TradingSwitches | null;
67
+ }
68
+ /**
69
+ * Whether a write may touch a LIVE account's switches: a resolved LIVE
70
+ * account, or any account the guard could not identify (which may be LIVE).
71
+ */
72
+ export declare function mayTouchLiveAccount(policies: readonly AuditedPolicyRow[]): boolean;
73
+ /** Who is writing, as far as the request can prove and report it. */
74
+ export interface AuditActor {
75
+ readonly principalKind: BackendPrincipal['kind'] | 'none';
76
+ readonly sub: string | null;
77
+ readonly email: string | null;
78
+ readonly ip: string | null;
79
+ readonly userAgent: string | null;
80
+ readonly origin: string | null;
81
+ }
82
+ /** Outcome recorded on a row. */
83
+ export type AuditOutcome = 'pending' | 'denied' | 'succeeded' | 'failed';
84
+ /** Everything recorded about one TradingPolicy write attempt. */
85
+ export interface TradingPolicyAuditEntry {
86
+ readonly mutation: string;
87
+ readonly action: MutationAction | 'custom';
88
+ /** Argument paths of the nested TradingPolicy writes; empty for a root write. */
89
+ readonly nestedPaths: readonly string[];
90
+ readonly actor: AuditActor;
91
+ readonly changeReason: string | null;
92
+ readonly decision: 'allowed' | 'would_deny' | 'denied';
93
+ readonly authorizationReason: MutationAuthReason;
94
+ readonly effectiveMode: string;
95
+ readonly graphqlOperationName: string | null;
96
+ readonly requested: Record<string, unknown>;
97
+ readonly policies: readonly AuditedPolicyRow[];
98
+ }
99
+ /** The slice of the Prisma client this module writes through. */
100
+ export interface AuditLogWriter {
101
+ auditLog: {
102
+ create(args: {
103
+ data: Record<string, unknown>;
104
+ }): Promise<{
105
+ id: string;
106
+ }>;
107
+ };
108
+ }
109
+ /**
110
+ * Disarm-only TradingPolicy writes admitted without an attempt row because
111
+ * AuditLog was unavailable under enforce. Each is also logged in full.
112
+ */
113
+ export declare const mutationAuditBypassedTotal: Counter<"reason">;
114
+ /** Audit-row write failures, by phase. Non-zero means an unattributed write risk. */
115
+ export declare const mutationAuditWriteFailuresTotal: Counter<"phase">;
116
+ /** Collapse control characters and bound the length of a header value. */
117
+ export declare function sanitizeHeader(value: string | string[] | undefined, max: number): string | null;
118
+ /** The request slice the actor is read from. */
119
+ export interface ActorRequest {
120
+ ip?: string;
121
+ headers?: Record<string, string | string[] | undefined>;
122
+ }
123
+ /** Build the actor record for a request. */
124
+ export declare function actorFor(principal: BackendPrincipal | null, req: ActorRequest | undefined): AuditActor;
125
+ /** The caller's stated reason for the change, if it gave one. */
126
+ export declare function changeReasonFor(req: ActorRequest | undefined): string | null;
127
+ /** Whether a requested payload names any trading switch at any depth. */
128
+ export declare function touchesTradingSwitch(requested: unknown): boolean;
129
+ /**
130
+ * Write the pre-execution `attempt` row.
131
+ *
132
+ * @returns The new row's id.
133
+ * @throws Whatever the database raised; the caller decides whether that
134
+ * refuses the mutation. The failure is counted before it propagates.
135
+ */
136
+ export declare function writeAttemptRow(prisma: AuditLogWriter, entry: TradingPolicyAuditEntry, outcome: 'pending' | 'denied'): Promise<string>;
137
+ /**
138
+ * Write the post-execution `result` row, linked to its attempt.
139
+ *
140
+ * @throws Whatever the database raised, after counting it. The mutation has
141
+ * already run at this point; the caller logs the failure loudly because the
142
+ * attempt row, not this one, is the attribution of record.
143
+ */
144
+ export declare function writeResultRow(prisma: AuditLogWriter, entry: TradingPolicyAuditEntry, attemptId: string | null, outcome: 'succeeded' | 'failed', errorCode: string | null): Promise<void>;
145
+ /**
146
+ * Whether a root `updateOneTradingPolicy` only disarms: it sets at least one
147
+ * trading switch, every switch it sets moves to its disarmed value, and every
148
+ * other field it sets is bookkeeping (or re-states the row's own `id`). Any
149
+ * other shape — a nested write, an upsert (which may create an armed policy),
150
+ * a bulk write, a change to limits — is not disarm-only.
151
+ *
152
+ * @param target - The classified root mutation field.
153
+ * @param args - The field's arguments.
154
+ */
155
+ export declare function isDisarmOnlyPolicyWrite(target: {
156
+ readonly model: string;
157
+ readonly action: string;
158
+ readonly cardinality: string;
159
+ }, args: Record<string, unknown>): boolean;
160
+ /**
161
+ * The actor request for a GraphQL-over-WebSocket operation, so a mutation
162
+ * sent over `/subscriptions` is attributed like an HTTP one: IP (socket
163
+ * remote address), user agent and origin from the upgrade request, and the
164
+ * change reason from the upgrade request's `X-Adaptic-Change-Reason` header
165
+ * or the connection's `connectionParams` (a browser cannot set headers on a
166
+ * WebSocket upgrade). The reason is per connection, not per operation.
167
+ *
168
+ * @param extra - graphql-ws `ctx.extra` (carries the upgrade `request`).
169
+ * @param connectionParams - graphql-ws `ctx.connectionParams`.
170
+ */
171
+ export declare function wsActorRequest(extra: unknown, connectionParams: unknown): ActorRequest;
172
+ //# sourceMappingURL=trading-policy-audit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trading-policy-audit.d.ts","sourceRoot":"","sources":["../../../src/middleware/trading-policy-audit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAGtC,OAAO,KAAK,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACzF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAG/D,iEAAiE;AACjE,eAAO,MAAM,oBAAoB,4BAA4B,CAAC;AAQ9D,4DAA4D;AAC5D,eAAO,MAAM,qBAAqB,8FAKxB,CAAC;AAEX,sEAAsE;AACtE,MAAM,MAAM,eAAe,GAAG,OAAO,CACnC,MAAM,CAAC,CAAC,OAAO,qBAAqB,CAAC,CAAC,MAAM,CAAC,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAAC,CACxE,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,gBAAgB,GAAG,UAAU,GAAG,aAAa,GAAG,YAAY,CAAC;AAEzE,mEAAmE;AACnE,MAAM,WAAW,gBAAgB;IAC/B,kFAAkF;IAClF,QAAQ,CAAC,UAAU,E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AE,GAAG,CAAC,MAAsC,CAAC,CAAC,CAAC,EAAE,CAAC;IACxH,OAAO;QACL,EAAE,EAAE,OAAO,MAAM,CAAC,aAAa,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS;QAC/E,OAAO;KACR,CAAC;AACJ,CAAC"}
@@ -0,0 +1,309 @@
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 { Counter } from 'prom-client';
44
+ import { redactCredentials } from '../auth/credential-redaction.mjs';
45
+ import { metricsRegistry } from '../config/metrics.mjs';
46
+ /** Header a caller uses to state why it is changing a policy. */
47
+ export const CHANGE_REASON_HEADER = 'x-adaptic-change-reason';
48
+ /** Longest change reason recorded, in characters. */
49
+ const MAX_CHANGE_REASON_LENGTH = 500;
50
+ /** Longest free-text header value (user agent, origin) recorded. */
51
+ const MAX_HEADER_LENGTH = 300;
52
+ /** The switches whose change arms or disarms an account. */
53
+ export const TRADING_SWITCH_FIELDS = [
54
+ 'realtimeTradingEnabled',
55
+ 'paperTradingOnly',
56
+ 'killSwitchEnabled',
57
+ 'autonomyMode',
58
+ ];
59
+ /**
60
+ * Whether a write may touch a LIVE account's switches: a resolved LIVE
61
+ * account, or any account the guard could not identify (which may be LIVE).
62
+ */
63
+ export function mayTouchLiveAccount(policies) {
64
+ return policies.some((p) => p.accountType === 'LIVE' || p.resolution !== 'resolved');
65
+ }
66
+ /**
67
+ * Disarm-only TradingPolicy writes admitted without an attempt row because
68
+ * AuditLog was unavailable under enforce. Each is also logged in full.
69
+ */
70
+ export const mutationAuditBypassedTotal = new Counter({
71
+ name: 'graphql_mutation_audit_bypassed_total',
72
+ help: 'TradingPolicy writes admitted under enforce without an attempt audit row, by reason. ' +
73
+ 'Only disarm-only writes (kill switch on, trading off, paper only, safe autonomy) qualify.',
74
+ labelNames: ['reason'],
75
+ registers: [metricsRegistry],
76
+ });
77
+ /** Audit-row write failures, by phase. Non-zero means an unattributed write risk. */
78
+ export const mutationAuditWriteFailuresTotal = new Counter({
79
+ name: 'graphql_mutation_audit_write_failures_total',
80
+ help: 'TradingPolicy audit rows that could not be written, by phase (attempt | result). ' +
81
+ 'An attempt failure under enforce refuses the mutation; under shadow the write proceeds unattributed.',
82
+ labelNames: ['phase'],
83
+ registers: [metricsRegistry],
84
+ });
85
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
86
+ /** C0 control characters and DEL: a header carrying them could forge log or row structure. */
87
+ const FIRST_PRINTABLE = 0x20;
88
+ const DELETE = 0x7f;
89
+ function isControlCharacter(ch) {
90
+ const code = ch.charCodeAt(0);
91
+ return code < FIRST_PRINTABLE || code === DELETE;
92
+ }
93
+ /** Collapse control characters and bound the length of a header value. */
94
+ export function sanitizeHeader(value, max) {
95
+ const raw = Array.isArray(value) ? value.join(',') : value;
96
+ if (typeof raw !== 'string')
97
+ return null;
98
+ const clean = [...raw]
99
+ .map((ch) => (isControlCharacter(ch) ? ' ' : ch))
100
+ .join('')
101
+ .replace(/ {2,}/g, ' ')
102
+ .trim();
103
+ if (clean.length === 0)
104
+ return null;
105
+ return clean.length > max ? `${clean.slice(0, max)}…` : clean;
106
+ }
107
+ /** Build the actor record for a request. */
108
+ export function actorFor(principal, req) {
109
+ const headers = req?.headers ?? {};
110
+ const base = {
111
+ ip: req?.ip ?? null,
112
+ userAgent: sanitizeHeader(headers['user-agent'], MAX_HEADER_LENGTH),
113
+ origin: sanitizeHeader(headers.origin, MAX_HEADER_LENGTH),
114
+ };
115
+ if (!principal)
116
+ return { principalKind: 'none', sub: null, email: null, ...base };
117
+ if (principal.kind === 'server') {
118
+ return { principalKind: 'server', sub: principal.sub ?? null, email: null, ...base };
119
+ }
120
+ return { principalKind: principal.kind, sub: principal.sub, email: principal.email ?? null, ...base };
121
+ }
122
+ /** The caller's stated reason for the change, if it gave one. */
123
+ export function changeReasonFor(req) {
124
+ return sanitizeHeader(req?.headers?.[CHANGE_REASON_HEADER], MAX_CHANGE_REASON_LENGTH);
125
+ }
126
+ /** Whether a requested payload names any trading switch at any depth. */
127
+ export function touchesTradingSwitch(requested) {
128
+ if (requested === null || typeof requested !== 'object')
129
+ return false;
130
+ for (const [key, child] of Object.entries(requested)) {
131
+ if (TRADING_SWITCH_FIELDS.includes(key))
132
+ return true;
133
+ if (touchesTradingSwitch(child))
134
+ return true;
135
+ }
136
+ return false;
137
+ }
138
+ function operationTypeFor(action) {
139
+ if (action === 'create')
140
+ return 'CREATE';
141
+ if (action === 'delete')
142
+ return 'DELETE';
143
+ return 'UPDATE';
144
+ }
145
+ function recordIdFor(policies) {
146
+ if (policies.length === 1) {
147
+ const [row] = policies;
148
+ if (row.policyId)
149
+ return row.policyId;
150
+ return row.alpacaAccountId ? `alpacaAccount:${row.alpacaAccountId}` : row.resolution;
151
+ }
152
+ return policies.length === 0 ? 'unresolved' : `bulk:${policies.length}`;
153
+ }
154
+ function rowData(entry, phase, outcome, extra) {
155
+ const { actor } = entry;
156
+ return {
157
+ userId: actor.sub !== null && UUID.test(actor.sub) ? actor.sub : null,
158
+ operationType: operationTypeFor(entry.action),
159
+ modelName: 'TradingPolicy',
160
+ recordId: recordIdFor(entry.policies),
161
+ operationName: entry.mutation,
162
+ ipAddress: actor.ip ? actor.ip.slice(0, 45) : null,
163
+ changedFields: redactCredentials({
164
+ requested: entry.requested,
165
+ nestedPaths: entry.nestedPaths,
166
+ }),
167
+ metadata: redactCredentials({
168
+ source: 'mutation-auth-guard',
169
+ phase,
170
+ outcome,
171
+ actor,
172
+ changeReason: entry.changeReason,
173
+ decision: entry.decision,
174
+ authorizationReason: entry.authorizationReason,
175
+ effectiveMode: entry.effectiveMode,
176
+ graphqlOperationName: entry.graphqlOperationName,
177
+ tradingSwitchTouched: touchesTradingSwitch(entry.requested),
178
+ accounts: entry.policies,
179
+ ...extra,
180
+ }),
181
+ };
182
+ }
183
+ /**
184
+ * Write the pre-execution `attempt` row.
185
+ *
186
+ * @returns The new row's id.
187
+ * @throws Whatever the database raised; the caller decides whether that
188
+ * refuses the mutation. The failure is counted before it propagates.
189
+ */
190
+ export async function writeAttemptRow(prisma, entry, outcome) {
191
+ try {
192
+ const row = await prisma.auditLog.create({ data: rowData(entry, 'attempt', outcome, {}) });
193
+ return row.id;
194
+ }
195
+ catch (error) {
196
+ mutationAuditWriteFailuresTotal.inc({ phase: 'attempt' });
197
+ throw error;
198
+ }
199
+ }
200
+ /**
201
+ * Write the post-execution `result` row, linked to its attempt.
202
+ *
203
+ * @throws Whatever the database raised, after counting it. The mutation has
204
+ * already run at this point; the caller logs the failure loudly because the
205
+ * attempt row, not this one, is the attribution of record.
206
+ */
207
+ export async function writeResultRow(prisma, entry, attemptId, outcome, errorCode) {
208
+ try {
209
+ await prisma.auditLog.create({
210
+ data: rowData(entry, 'result', outcome, { attemptId, errorCode }),
211
+ });
212
+ }
213
+ catch (error) {
214
+ mutationAuditWriteFailuresTotal.inc({ phase: 'result' });
215
+ throw error;
216
+ }
217
+ }
218
+ /** The value each trading switch moves to when a write DISARMS it. */
219
+ const DISARMED_VALUES = {
220
+ realtimeTradingEnabled: new Set([false]),
221
+ killSwitchEnabled: new Set([true]),
222
+ paperTradingOnly: new Set([true]),
223
+ autonomyMode: new Set(['ADVISORY_ONLY', 'EMERGENCY_SAFE_MODE']),
224
+ };
225
+ /** Bookkeeping fields a disarm write may also set. */
226
+ const DISARM_BOOKKEEPING_FIELDS = new Set(['lastModifiedBy', 'lastModifiedAt', 'version']);
227
+ /** The value a generated update input sets: `{ set: v }` → `v`; anything else is not a plain set. */
228
+ function setValueOf(value) {
229
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
230
+ return null;
231
+ const record = value;
232
+ const keys = Object.keys(record).filter((key) => record[key] !== undefined);
233
+ return keys.length === 1 && keys[0] === 'set' ? { value: record.set } : null;
234
+ }
235
+ /**
236
+ * Whether a root `updateOneTradingPolicy` only disarms: it sets at least one
237
+ * trading switch, every switch it sets moves to its disarmed value, and every
238
+ * other field it sets is bookkeeping (or re-states the row's own `id`). Any
239
+ * other shape — a nested write, an upsert (which may create an armed policy),
240
+ * a bulk write, a change to limits — is not disarm-only.
241
+ *
242
+ * @param target - The classified root mutation field.
243
+ * @param args - The field's arguments.
244
+ */
245
+ export function isDisarmOnlyPolicyWrite(target, args) {
246
+ if (target.model !== 'TradingPolicy' || target.action !== 'update' || target.cardinality !== 'one') {
247
+ return false;
248
+ }
249
+ const data = args.data;
250
+ if (data === null || typeof data !== 'object' || Array.isArray(data))
251
+ return false;
252
+ const where = args.where;
253
+ let disarmed = 0;
254
+ for (const [key, raw] of Object.entries(data)) {
255
+ if (raw === undefined)
256
+ continue;
257
+ const set = setValueOf(raw);
258
+ if (!set)
259
+ return false;
260
+ if (key in DISARMED_VALUES) {
261
+ if (!DISARMED_VALUES[key].has(set.value))
262
+ return false;
263
+ disarmed += 1;
264
+ }
265
+ else if (!DISARM_BOOKKEEPING_FIELDS.has(key) && !(key === 'id' && where?.id === set.value)) {
266
+ return false;
267
+ }
268
+ }
269
+ return disarmed > 0;
270
+ }
271
+ /** Case-insensitive read of one key from a WebSocket `connectionParams` bag. */
272
+ function connectionParam(params, name) {
273
+ if (params === null || typeof params !== 'object')
274
+ return undefined;
275
+ for (const [key, value] of Object.entries(params)) {
276
+ if (key.toLowerCase() === name && typeof value === 'string')
277
+ return value;
278
+ }
279
+ return undefined;
280
+ }
281
+ /**
282
+ * The actor request for a GraphQL-over-WebSocket operation, so a mutation
283
+ * sent over `/subscriptions` is attributed like an HTTP one: IP (socket
284
+ * remote address), user agent and origin from the upgrade request, and the
285
+ * change reason from the upgrade request's `X-Adaptic-Change-Reason` header
286
+ * or the connection's `connectionParams` (a browser cannot set headers on a
287
+ * WebSocket upgrade). The reason is per connection, not per operation.
288
+ *
289
+ * @param extra - graphql-ws `ctx.extra` (carries the upgrade `request`).
290
+ * @param connectionParams - graphql-ws `ctx.connectionParams`.
291
+ */
292
+ export function wsActorRequest(extra, connectionParams) {
293
+ const request = extra !== null && typeof extra === 'object' ? extra.request : undefined;
294
+ const req = request !== null && typeof request === 'object' ? request : {};
295
+ const rawHeaders = req.headers !== null && typeof req.headers === 'object' ? req.headers : {};
296
+ const headers = {};
297
+ for (const name of ['user-agent', 'origin', CHANGE_REASON_HEADER]) {
298
+ const value = rawHeaders[name];
299
+ if (typeof value === 'string' || Array.isArray(value))
300
+ headers[name] = value;
301
+ }
302
+ headers[CHANGE_REASON_HEADER] ??= connectionParam(connectionParams, CHANGE_REASON_HEADER);
303
+ const socket = req.socket !== null && typeof req.socket === 'object' ? req.socket : {};
304
+ return {
305
+ ip: typeof socket.remoteAddress === 'string' ? socket.remoteAddress : undefined,
306
+ headers,
307
+ };
308
+ }
309
+ //# sourceMappingURL=trading-policy-audit.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adaptic/backend",
3
- "version": "0.0.1038",
3
+ "version": "0.0.1039",
4
4
  "description": "Backend executable CRUD functions with dynamic variables construction, and type definitions for the Adaptic AI platform.",
5
5
  "type": "module",
6
6
  "types": "index.d.ts",
package/server.cjs CHANGED
@@ -63,6 +63,8 @@ const rate_limiter_1 = require("./middleware/rate-limiter.cjs");
63
63
  const audit_logger_1 = require("./middleware/audit-logger.cjs");
64
64
  const tenancy_scoping_1 = require("./middleware/tenancy-scoping.cjs");
65
65
  const credential_field_guard_1 = require("./middleware/credential-field-guard.cjs");
66
+ const mutation_auth_guard_1 = require("./middleware/mutation-auth-guard.cjs");
67
+ const trading_policy_audit_1 = require("./middleware/trading-policy-audit.cjs");
66
68
  const cortex_auth_checker_1 = require("./auth/cortex-auth-checker.cjs");
67
69
  const authorization_map_1 = require("./auth/authorization-map.cjs");
68
70
  const http_status_mapper_1 = require("./plugins/http-status-mapper.cjs");
@@ -169,6 +171,20 @@ const startServer = async () => {
169
171
  // byte-identical live behaviour until enforcement is flipped on.
170
172
  authChecker: cortex_auth_checker_1.cortexAuthChecker,
171
173
  });
174
+ // Mutation authorization: every mutation is admitted only for a principal
175
+ // authorised to write that model — the engine's service principal and admins
176
+ // everywhere, a user only on an account, row or tenant it owns — and every
177
+ // TradingPolicy write leaves an attributed audit row. Installed on the built
178
+ // schema's Mutation fields (not as a global middleware, which would tax every
179
+ // read field), so it covers generated and custom mutations alike on both the
180
+ // HTTP and WebSocket transports. Gated by `MUTATION_AUTH_MODE` (unset =
181
+ // `shadow`) and the per-model escalation `MUTATION_AUTH_ENFORCE_MODELS`; see
182
+ // src/middleware/mutation-auth-guard.ts and
183
+ // docs/security/2026-09-24-mutation-authorization-runbook.md.
184
+ const guardedMutations = (0, mutation_auth_guard_1.installMutationAuthGuard)(schema);
185
+ logger_1.logger.info('[mutation-auth] guard installed on every root Mutation field', {
186
+ guardedMutations,
187
+ });
172
188
  const app = (0, express_1.default)();
173
189
  const httpServer = (0, http_1.createServer)(app);
174
190
  // Trust the load-balancer proxy chain so `req.ip` resolves the CLIENT address
@@ -315,7 +331,10 @@ const startServer = async () => {
315
331
  },
316
332
  credentials: true,
317
333
  methods: ['GET', 'POST', 'OPTIONS'],
318
- allowedHeaders: ['Content-Type', 'Authorization', 'X-Request-ID'],
334
+ // X-Adaptic-Change-Reason is the stated reason recorded on every
335
+ // TradingPolicy audit row (src/middleware/trading-policy-audit.ts); a
336
+ // browser caller can only send it if preflight allows it.
337
+ allowedHeaders: ['Content-Type', 'Authorization', 'X-Request-ID', 'X-Adaptic-Change-Reason'],
319
338
  maxAge: 86400, // 24h preflight cache
320
339
  };
321
340
  app.use('/graphql', (0, cors_1.default)(corsOptions),
@@ -455,12 +474,18 @@ const startServer = async () => {
455
474
  userAgent: wsIdentity.userAgent,
456
475
  authHeaderPresent: authHeader.length > 0,
457
476
  });
458
- return { prisma: global.prisma, user: null, principal: null };
477
+ return {
478
+ prisma: global.prisma,
479
+ req: (0, trading_policy_audit_1.wsActorRequest)(ctx.extra, ctx.connectionParams),
480
+ user: null,
481
+ principal: null,
482
+ };
459
483
  }
460
484
  case 'authenticated': {
461
485
  (0, graphql_auth_shadow_1.recordAuthContextOutcome)('ws', 'authenticated');
462
486
  return {
463
487
  prisma: global.prisma,
488
+ req: (0, trading_policy_audit_1.wsActorRequest)(ctx.extra, ctx.connectionParams),
464
489
  user: principalToUser(decision.principal),
465
490
  principal: decision.principal,
466
491
  };