@adaptic/backend-legacy 0.0.1037 → 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 (101) 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__/credential-field-guard.harness.d.ts +34 -0
  37. package/esm/middleware/__tests__/credential-field-guard.harness.d.ts.map +1 -0
  38. package/esm/middleware/__tests__/credential-field-guard.harness.js.map +1 -0
  39. package/esm/middleware/__tests__/credential-field-guard.harness.mjs +212 -0
  40. package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +49 -0
  41. package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts.map +1 -0
  42. package/esm/middleware/__tests__/mutation-auth-guard.harness.js.map +1 -0
  43. package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +402 -0
  44. package/esm/middleware/__tests__/ts-node-harness.d.ts +10 -0
  45. package/esm/middleware/__tests__/ts-node-harness.d.ts.map +1 -0
  46. package/esm/middleware/__tests__/ts-node-harness.js.map +1 -0
  47. package/esm/middleware/__tests__/ts-node-harness.mjs +71 -0
  48. package/esm/middleware/audit-logger.d.ts +18 -1
  49. package/esm/middleware/audit-logger.d.ts.map +1 -1
  50. package/esm/middleware/audit-logger.js.map +1 -1
  51. package/esm/middleware/audit-logger.mjs +36 -13
  52. package/esm/middleware/audit-payload-guard.d.ts +85 -0
  53. package/esm/middleware/audit-payload-guard.d.ts.map +1 -0
  54. package/esm/middleware/audit-payload-guard.js.map +1 -0
  55. package/esm/middleware/audit-payload-guard.mjs +97 -0
  56. package/esm/middleware/credential-field-guard.d.ts +160 -0
  57. package/esm/middleware/credential-field-guard.d.ts.map +1 -0
  58. package/esm/middleware/credential-field-guard.js.map +1 -0
  59. package/esm/middleware/credential-field-guard.mjs +479 -0
  60. package/esm/middleware/generated-type-names.d.ts +44 -0
  61. package/esm/middleware/generated-type-names.d.ts.map +1 -0
  62. package/esm/middleware/generated-type-names.js.map +1 -0
  63. package/esm/middleware/generated-type-names.mjs +73 -0
  64. package/esm/middleware/guard-log-throttle.d.ts +80 -0
  65. package/esm/middleware/guard-log-throttle.d.ts.map +1 -0
  66. package/esm/middleware/guard-log-throttle.js.map +1 -0
  67. package/esm/middleware/guard-log-throttle.mjs +87 -0
  68. package/esm/middleware/mutation-account-facts.d.ts +140 -0
  69. package/esm/middleware/mutation-account-facts.d.ts.map +1 -0
  70. package/esm/middleware/mutation-account-facts.js.map +1 -0
  71. package/esm/middleware/mutation-account-facts.mjs +212 -0
  72. package/esm/middleware/mutation-auth-guard.d.ts +82 -0
  73. package/esm/middleware/mutation-auth-guard.d.ts.map +1 -0
  74. package/esm/middleware/mutation-auth-guard.js.map +1 -0
  75. package/esm/middleware/mutation-auth-guard.mjs +425 -0
  76. package/esm/middleware/mutation-tenant-facts.d.ts +58 -0
  77. package/esm/middleware/mutation-tenant-facts.d.ts.map +1 -0
  78. package/esm/middleware/mutation-tenant-facts.js.map +1 -0
  79. package/esm/middleware/mutation-tenant-facts.mjs +75 -0
  80. package/esm/middleware/trading-policy-audit.d.ts +172 -0
  81. package/esm/middleware/trading-policy-audit.d.ts.map +1 -0
  82. package/esm/middleware/trading-policy-audit.js.map +1 -0
  83. package/esm/middleware/trading-policy-audit.mjs +309 -0
  84. package/esm/resolvers/custom/BrokerageAccountCredentialStatusResolver.d.ts +22 -0
  85. package/esm/resolvers/custom/BrokerageAccountCredentialStatusResolver.d.ts.map +1 -0
  86. package/esm/resolvers/custom/BrokerageAccountCredentialStatusResolver.js.map +1 -0
  87. package/esm/resolvers/custom/BrokerageAccountCredentialStatusResolver.mjs +63 -0
  88. package/esm/resolvers/custom/index.d.ts +1 -0
  89. package/esm/resolvers/custom/index.d.ts.map +1 -1
  90. package/esm/resolvers/custom/index.js.map +1 -1
  91. package/esm/resolvers/custom/index.mjs +1 -0
  92. package/package.json +1 -1
  93. package/resolvers/custom/BrokerageAccountCredentialStatusResolver.cjs +100 -0
  94. package/resolvers/custom/BrokerageAccountCredentialStatusResolver.d.ts +22 -0
  95. package/resolvers/custom/BrokerageAccountCredentialStatusResolver.d.ts.map +1 -0
  96. package/resolvers/custom/BrokerageAccountCredentialStatusResolver.js.map +1 -0
  97. package/resolvers/custom/index.cjs +4 -1
  98. package/resolvers/custom/index.d.ts +1 -0
  99. package/resolvers/custom/index.d.ts.map +1 -1
  100. package/resolvers/custom/index.js.map +1 -1
  101. package/server.cjs +40 -3
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Bounded once-per-window throttle for guard decision log lines.
3
+ *
4
+ * A guard that logs every refused or would-refuse access floods the log for a
5
+ * caller that repeats one query all day, so each distinct caller key is logged
6
+ * once per window. The key has to carry caller-supplied values (operation
7
+ * name, user agent, `X-Forwarded-For`) because those are what tell two callers
8
+ * behind one edge address apart. That makes the key space caller-controlled:
9
+ * a caller rotating any of those values mints a new key per request. An
10
+ * unbounded map then grows until something clears it, and clearing a shared
11
+ * map on size is worse than growth — one caller's rotation erases every other
12
+ * caller's throttle state, so the flood re-logs everyone.
13
+ *
14
+ * So keys are counted per SCOPE — the principal kind plus the address this
15
+ * process accepted the connection from, neither of which the caller can set in
16
+ * a header — and each scope gets a fixed budget of distinct keys per window.
17
+ * The first key past the budget yields one overflow notice for that scope;
18
+ * later ones are dropped until the window ends. A caller rotating headers can
19
+ * therefore spend its own scope's budget and nothing else: other scopes keep
20
+ * their state, and the log volume per window is bounded by
21
+ * `(maxScopes + 1) * (keysPerScope + 1)` whatever the caller sends. Scopes are
22
+ * capped as well, because the connection address becomes caller-influenced if
23
+ * `trust proxy` is ever widened; scopes past the cap share one overflow scope.
24
+ *
25
+ * State resets when a window elapses (a tumbling window), which is time-driven
26
+ * and the same for every caller. The guard's counters are not throttled, so a
27
+ * dropped line loses attribution for that window, never a count.
28
+ *
29
+ * @module middleware/guard-log-throttle
30
+ */
31
+ /** Scope that every scope past `maxScopes` shares within a window. */
32
+ export declare const OVERFLOW_SCOPE = "<scope-overflow>";
33
+ /** Bounds for a {@link GuardLogThrottle}. */
34
+ export interface GuardLogThrottleOptions {
35
+ /** Window length; a key is logged at most once per window. */
36
+ windowMs: number;
37
+ /** Distinct keys one scope may log per window. */
38
+ keysPerScope: number;
39
+ /** Distinct scopes tracked per window before new ones share one scope. */
40
+ maxScopes: number;
41
+ }
42
+ /**
43
+ * What the caller should do with one decision.
44
+ *
45
+ * - `log` — first time this key is seen in this scope this window.
46
+ * - `overflow` — the scope has spent its budget this window; log one notice
47
+ * saying so, in place of the line.
48
+ * - `drop` — already logged, or the scope's overflow notice is already out.
49
+ */
50
+ export type GuardLogVerdict = {
51
+ action: 'log';
52
+ scope: string;
53
+ } | {
54
+ action: 'overflow';
55
+ scope: string;
56
+ } | {
57
+ action: 'drop';
58
+ };
59
+ /** A bounded, windowed, per-scope once-per-key log throttle. */
60
+ export declare class GuardLogThrottle {
61
+ private readonly options;
62
+ private windowStartMs;
63
+ private readonly keysByScope;
64
+ private readonly overflowedScopes;
65
+ constructor(options: GuardLogThrottleOptions);
66
+ /**
67
+ * Decide whether a decision for `key`, from `scope`, is logged.
68
+ *
69
+ * @param scope - Principal kind plus connection address; never a header.
70
+ * @param key - The caller key within the scope.
71
+ * @param nowMs - Current time.
72
+ * @returns The verdict; the scope it names is the one that was charged.
73
+ */
74
+ admit(scope: string, key: string, nowMs: number): GuardLogVerdict;
75
+ /** Forget all state (tests). */
76
+ reset(): void;
77
+ /** Start a new window once the current one has elapsed (or the clock stepped back). */
78
+ private rollWindow;
79
+ }
80
+ //# sourceMappingURL=guard-log-throttle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guard-log-throttle.d.ts","sourceRoot":"","sources":["../../../src/middleware/guard-log-throttle.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,sEAAsE;AACtE,eAAO,MAAM,cAAc,qBAAqB,CAAC;AAEjD,6CAA6C;AAC7C,MAAM,WAAW,uBAAuB;IACtC,8DAA8D;IAC9D,QAAQ,EAAE,MAAM,CAAC;IACjB,kDA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,EAAE,CAAC;IAChC,CAAC;IAED,uFAAuF;IAC/E,UAAU,CAAC,KAAa;QAC9B,MAAM,KAAK,GAAG,IAAI,CAAC,aAAa,CAAC;QACjC,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,IAAI,KAAK,IAAI,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ;YAAE,OAAO;QAC3F,IAAI,CAAC,aAAa,GAAG,KAAK,CAAC;QAC3B,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;QACzB,IAAI,CAAC,gBAAgB,CAAC,KAAK,EAAE,CAAC;IAChC,CAAC;CACF"}
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Bounded once-per-window throttle for guard decision log lines.
3
+ *
4
+ * A guard that logs every refused or would-refuse access floods the log for a
5
+ * caller that repeats one query all day, so each distinct caller key is logged
6
+ * once per window. The key has to carry caller-supplied values (operation
7
+ * name, user agent, `X-Forwarded-For`) because those are what tell two callers
8
+ * behind one edge address apart. That makes the key space caller-controlled:
9
+ * a caller rotating any of those values mints a new key per request. An
10
+ * unbounded map then grows until something clears it, and clearing a shared
11
+ * map on size is worse than growth — one caller's rotation erases every other
12
+ * caller's throttle state, so the flood re-logs everyone.
13
+ *
14
+ * So keys are counted per SCOPE — the principal kind plus the address this
15
+ * process accepted the connection from, neither of which the caller can set in
16
+ * a header — and each scope gets a fixed budget of distinct keys per window.
17
+ * The first key past the budget yields one overflow notice for that scope;
18
+ * later ones are dropped until the window ends. A caller rotating headers can
19
+ * therefore spend its own scope's budget and nothing else: other scopes keep
20
+ * their state, and the log volume per window is bounded by
21
+ * `(maxScopes + 1) * (keysPerScope + 1)` whatever the caller sends. Scopes are
22
+ * capped as well, because the connection address becomes caller-influenced if
23
+ * `trust proxy` is ever widened; scopes past the cap share one overflow scope.
24
+ *
25
+ * State resets when a window elapses (a tumbling window), which is time-driven
26
+ * and the same for every caller. The guard's counters are not throttled, so a
27
+ * dropped line loses attribution for that window, never a count.
28
+ *
29
+ * @module middleware/guard-log-throttle
30
+ */
31
+ /** Scope that every scope past `maxScopes` shares within a window. */
32
+ export const OVERFLOW_SCOPE = '<scope-overflow>';
33
+ /** A bounded, windowed, per-scope once-per-key log throttle. */
34
+ export class GuardLogThrottle {
35
+ options;
36
+ windowStartMs;
37
+ keysByScope = new Map();
38
+ overflowedScopes = new Set();
39
+ constructor(options) {
40
+ this.options = options;
41
+ }
42
+ /**
43
+ * Decide whether a decision for `key`, from `scope`, is logged.
44
+ *
45
+ * @param scope - Principal kind plus connection address; never a header.
46
+ * @param key - The caller key within the scope.
47
+ * @param nowMs - Current time.
48
+ * @returns The verdict; the scope it names is the one that was charged.
49
+ */
50
+ admit(scope, key, nowMs) {
51
+ this.rollWindow(nowMs);
52
+ const charged = this.keysByScope.has(scope) || this.keysByScope.size < this.options.maxScopes
53
+ ? scope
54
+ : OVERFLOW_SCOPE;
55
+ let keys = this.keysByScope.get(charged);
56
+ if (!keys) {
57
+ keys = new Set();
58
+ this.keysByScope.set(charged, keys);
59
+ }
60
+ if (keys.has(key))
61
+ return { action: 'drop' };
62
+ if (keys.size < this.options.keysPerScope) {
63
+ keys.add(key);
64
+ return { action: 'log', scope: charged };
65
+ }
66
+ if (this.overflowedScopes.has(charged))
67
+ return { action: 'drop' };
68
+ this.overflowedScopes.add(charged);
69
+ return { action: 'overflow', scope: charged };
70
+ }
71
+ /** Forget all state (tests). */
72
+ reset() {
73
+ this.windowStartMs = undefined;
74
+ this.keysByScope.clear();
75
+ this.overflowedScopes.clear();
76
+ }
77
+ /** Start a new window once the current one has elapsed (or the clock stepped back). */
78
+ rollWindow(nowMs) {
79
+ const start = this.windowStartMs;
80
+ if (start !== undefined && nowMs >= start && nowMs - start < this.options.windowMs)
81
+ return;
82
+ this.windowStartMs = nowMs;
83
+ this.keysByScope.clear();
84
+ this.overflowedScopes.clear();
85
+ }
86
+ }
87
+ //# sourceMappingURL=guard-log-throttle.js.map
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Database facts the mutation guard needs: which brokerage accounts a
3
+ * TradingPolicy / AlpacaAccount write touches, who owns them, and — for the
4
+ * audit trail — each touched policy's switch values before the write.
5
+ *
6
+ * One read serves both purposes, so a policy write costs the guard a single
7
+ * `findUnique` (or a bounded `findMany` for a bulk write) plus, for a user
8
+ * principal, the entitlement read the tenancy scoping already performs.
9
+ *
10
+ * Every read here fails CLOSED at the caller: an account the guard cannot
11
+ * resolve is `unresolved`, which a user principal is refused on, and the
12
+ * failure is logged rather than turned into an ownership answer.
13
+ *
14
+ * @module middleware/mutation-account-facts
15
+ */
16
+ import type { AccountOwnership, MutationTarget } from '../auth/mutation-authorization';
17
+ import type { NestedWrite } from '../auth/nested-write-inspector';
18
+ import type { TenantScopePrisma } from './mutation-tenant-facts';
19
+ import type { AuditedPolicyRow, AuditLogWriter } from './trading-policy-audit';
20
+ /** Most rows a bulk policy write records in its audit row. */
21
+ export declare const MAX_AUDITED_BULK_ROWS = 200;
22
+ declare const ACCOUNT_SELECT: {
23
+ readonly id: true;
24
+ readonly userId: true;
25
+ readonly type: true;
26
+ readonly brokerageAccount: {
27
+ readonly select: {
28
+ readonly fundId: true;
29
+ };
30
+ };
31
+ };
32
+ declare const POLICY_SELECT: {
33
+ readonly id: true;
34
+ readonly alpacaAccountId: true;
35
+ readonly realtimeTradingEnabled: true;
36
+ readonly paperTradingOnly: true;
37
+ readonly killSwitchEnabled: true;
38
+ readonly autonomyMode: true;
39
+ readonly alpacaAccount: {
40
+ readonly select: {
41
+ readonly id: true;
42
+ readonly userId: true;
43
+ readonly type: true;
44
+ readonly brokerageAccount: {
45
+ readonly select: {
46
+ readonly fundId: true;
47
+ };
48
+ };
49
+ };
50
+ };
51
+ };
52
+ /** The account columns the guard reads. */
53
+ export interface AccountFacts {
54
+ readonly id: string;
55
+ readonly userId: string;
56
+ readonly type: string;
57
+ readonly brokerageAccount: {
58
+ readonly fundId: string;
59
+ } | null;
60
+ }
61
+ /** The policy columns the guard reads. */
62
+ export interface PolicyFacts {
63
+ readonly id: string;
64
+ readonly alpacaAccountId: string;
65
+ readonly realtimeTradingEnabled: boolean;
66
+ readonly paperTradingOnly: boolean;
67
+ readonly killSwitchEnabled: boolean;
68
+ readonly autonomyMode: string;
69
+ readonly alpacaAccount: AccountFacts;
70
+ }
71
+ type Where = Record<string, unknown>;
72
+ /**
73
+ * The slice of the Prisma client the guard uses. Declared structurally so the
74
+ * guard can be exercised against a fake, the pattern the tenancy scoping uses.
75
+ */
76
+ export interface MutationAuthPrisma extends AuditLogWriter, TenantScopePrisma {
77
+ tradingPolicy: {
78
+ findUnique(args: {
79
+ where: Where;
80
+ select: typeof POLICY_SELECT;
81
+ }): Promise<PolicyFacts | null>;
82
+ findMany(args: {
83
+ where: Where;
84
+ select: typeof POLICY_SELECT;
85
+ take: number;
86
+ }): Promise<PolicyFacts[]>;
87
+ };
88
+ alpacaAccount: {
89
+ findUnique(args: {
90
+ where: Where;
91
+ select: typeof ACCOUNT_SELECT;
92
+ }): Promise<AccountFacts | null>;
93
+ };
94
+ }
95
+ /** The accounts a write touches, with policy rows where they already exist. */
96
+ export interface TouchedAccounts {
97
+ readonly accounts: readonly AccountFacts[];
98
+ readonly policies: readonly AuditedPolicyRow[];
99
+ /**
100
+ * For an `AlpacaAccount` create: the owner the payload assigns. No account
101
+ * row exists yet, so ownership is decided from this.
102
+ */
103
+ readonly assignedOwnerId?: string | null;
104
+ }
105
+ /**
106
+ * The accounts (and existing policy rows) a mutation on `TradingPolicy` or
107
+ * `AlpacaAccount` touches. Any other root model touches no account the guard
108
+ * can resolve from its arguments, and yields an empty result.
109
+ *
110
+ * @throws Whatever the database raised; the caller fails closed on it.
111
+ */
112
+ export declare function loadTouchedAccounts(prisma: MutationAuthPrisma, target: MutationTarget, args: Record<string, unknown>): Promise<TouchedAccounts>;
113
+ /**
114
+ * Whether `userId` owns every account a write touches, or is entitled to the
115
+ * fund each is bound to.
116
+ *
117
+ * An account the caller neither owns nor is fund-entitled to makes the whole
118
+ * write `other`; a write whose accounts could not be resolved is
119
+ * `unresolved`. Both refuse a user principal.
120
+ *
121
+ * @throws Whatever the entitlement read raised; the caller fails closed on it.
122
+ */
123
+ export declare function ownershipOf(prisma: MutationAuthPrisma, userId: string, touched: TouchedAccounts): Promise<AccountOwnership>;
124
+ /**
125
+ * The policy row each nested TradingPolicy write reaches, resolved from THAT
126
+ * write's own path — never from the root. A policy container is resolved when
127
+ * its parent is an AlpacaAccount row the arguments name by a unique selector
128
+ * (the root `where`, or a to-many `update` / `upsert` entry's `where`); one
129
+ * whose account is created in the same mutation is `new_account`; anything
130
+ * else (a to-one hop through another model, whose row the arguments do not
131
+ * name) is `unresolved`, recorded as such rather than attributed to a guess.
132
+ *
133
+ * @param prisma - The database client.
134
+ * @param writes - The nested TradingPolicy containers, outermost first.
135
+ * @throws Whatever the database raised; the caller records the before-state
136
+ * as unread.
137
+ */
138
+ export declare function resolveNestedPolicyRows(prisma: MutationAuthPrisma, writes: readonly NestedWrite[]): Promise<AuditedPolicyRow[]>;
139
+ export {};
140
+ //# sourceMappingURL=mutation-account-facts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mutation-account-facts.d.ts","sourceRoot":"","sources":["../../../src/middleware/mutation-account-facts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACvF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAClE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AACjE,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAE/E,8DAA8D;AAC9D,eAAO,MAAM,qBAAqB,MAAM,CAAC;AAEzC,QAAA,MAAM,cAAc;;;;;;;;;CAKV,CAAC;AAEX,QAAA,MAAM,aAAa;;;;;;;;;;;;;;;;;;;CAQT,CAAC;AA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Policy / AlpacaAccount write touches, who owns them, and — for the
4
+ * audit trail — each touched policy's switch values before the write.
5
+ *
6
+ * One read serves both purposes, so a policy write costs the guard a single
7
+ * `findUnique` (or a bounded `findMany` for a bulk write) plus, for a user
8
+ * principal, the entitlement read the tenancy scoping already performs.
9
+ *
10
+ * Every read here fails CLOSED at the caller: an account the guard cannot
11
+ * resolve is `unresolved`, which a user principal is refused on, and the
12
+ * failure is logged rather than turned into an ownership answer.
13
+ *
14
+ * @module middleware/mutation-account-facts
15
+ */
16
+ import { resolveEntitlement } from '../auth/tenancy-scope.mjs';
17
+ /** Most rows a bulk policy write records in its audit row. */
18
+ export const MAX_AUDITED_BULK_ROWS = 200;
19
+ const ACCOUNT_SELECT = {
20
+ id: true,
21
+ userId: true,
22
+ type: true,
23
+ brokerageAccount: { select: { fundId: true } },
24
+ };
25
+ const POLICY_SELECT = {
26
+ id: true,
27
+ alpacaAccountId: true,
28
+ realtimeTradingEnabled: true,
29
+ paperTradingOnly: true,
30
+ killSwitchEnabled: true,
31
+ autonomyMode: true,
32
+ alpacaAccount: { select: ACCOUNT_SELECT },
33
+ };
34
+ function asRecord(value) {
35
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
36
+ ? value
37
+ : undefined;
38
+ }
39
+ function stringAt(value, ...path) {
40
+ let cursor = value;
41
+ for (const key of path)
42
+ cursor = asRecord(cursor)?.[key];
43
+ return typeof cursor === 'string' && cursor.length > 0 ? cursor : undefined;
44
+ }
45
+ /** The account a TradingPolicy create payload attaches to. */
46
+ function policyAccountIdIn(data) {
47
+ return stringAt(data, 'alpacaAccountId') ?? stringAt(data, 'alpacaAccount', 'connect', 'id');
48
+ }
49
+ function policyRow(row, nestedPath = null) {
50
+ return {
51
+ nestedPath,
52
+ resolution: 'resolved',
53
+ policyId: row.id,
54
+ alpacaAccountId: row.alpacaAccountId,
55
+ accountType: row.alpacaAccount.type,
56
+ before: {
57
+ realtimeTradingEnabled: row.realtimeTradingEnabled,
58
+ paperTradingOnly: row.paperTradingOnly,
59
+ killSwitchEnabled: row.killSwitchEnabled,
60
+ autonomyMode: row.autonomyMode,
61
+ },
62
+ };
63
+ }
64
+ function newPolicyRow(account, nestedPath = null) {
65
+ return {
66
+ nestedPath,
67
+ resolution: 'resolved',
68
+ policyId: null,
69
+ alpacaAccountId: account.id,
70
+ accountType: account.type,
71
+ before: null,
72
+ };
73
+ }
74
+ /** A policy write whose account the arguments do not identify. */
75
+ function unidentifiedPolicyRow(nestedPath, resolution) {
76
+ return { nestedPath, resolution, policyId: null, alpacaAccountId: null, accountType: null, before: null };
77
+ }
78
+ async function accountById(prisma, id) {
79
+ return prisma.alpacaAccount.findUnique({ where: { id }, select: ACCOUNT_SELECT });
80
+ }
81
+ async function touchedByPolicyWrite(prisma, target, args) {
82
+ const where = asRecord(args.where);
83
+ if (target.cardinality === 'many') {
84
+ if (target.action === 'create') {
85
+ const items = Array.isArray(args.data) ? args.data : [args.data];
86
+ const accounts = [];
87
+ for (const item of items.slice(0, MAX_AUDITED_BULK_ROWS)) {
88
+ const id = policyAccountIdIn(item);
89
+ const account = id ? await accountById(prisma, id) : null;
90
+ if (account)
91
+ accounts.push(account);
92
+ }
93
+ return { accounts, policies: accounts.map((a) => newPolicyRow(a)) };
94
+ }
95
+ const rows = await prisma.tradingPolicy.findMany({
96
+ where: where ?? {},
97
+ select: POLICY_SELECT,
98
+ take: MAX_AUDITED_BULK_ROWS,
99
+ });
100
+ return { accounts: rows.map((r) => r.alpacaAccount), policies: rows.map((r) => policyRow(r)) };
101
+ }
102
+ const existing = where && target.action !== 'create'
103
+ ? await prisma.tradingPolicy.findUnique({ where, select: POLICY_SELECT })
104
+ : null;
105
+ if (existing) {
106
+ return { accounts: [existing.alpacaAccount], policies: [policyRow(existing)] };
107
+ }
108
+ const createData = target.action === 'upsert' ? args.create : args.data;
109
+ const accountId = target.action === 'create' || target.action === 'upsert'
110
+ ? policyAccountIdIn(createData)
111
+ : undefined;
112
+ const account = accountId ? await accountById(prisma, accountId) : null;
113
+ return account ? { accounts: [account], policies: [newPolicyRow(account)] } : { accounts: [], policies: [] };
114
+ }
115
+ async function touchedByAccountWrite(prisma, target, args) {
116
+ if (target.action === 'create') {
117
+ const owner = stringAt(args.data, 'userId') ?? stringAt(args.data, 'user', 'connect', 'id') ?? null;
118
+ return { accounts: [], policies: [], assignedOwnerId: owner };
119
+ }
120
+ const where = asRecord(args.where);
121
+ if (!where || target.cardinality === 'many')
122
+ return { accounts: [], policies: [] };
123
+ const account = await prisma.alpacaAccount.findUnique({ where, select: ACCOUNT_SELECT });
124
+ if (!account)
125
+ return { accounts: [], policies: [] };
126
+ const policy = await prisma.tradingPolicy.findUnique({
127
+ where: { alpacaAccountId: account.id },
128
+ select: POLICY_SELECT,
129
+ });
130
+ return { accounts: [account], policies: policy ? [policyRow(policy)] : [] };
131
+ }
132
+ /**
133
+ * The accounts (and existing policy rows) a mutation on `TradingPolicy` or
134
+ * `AlpacaAccount` touches. Any other root model touches no account the guard
135
+ * can resolve from its arguments, and yields an empty result.
136
+ *
137
+ * @throws Whatever the database raised; the caller fails closed on it.
138
+ */
139
+ export async function loadTouchedAccounts(prisma, target, args) {
140
+ if (target.model === 'TradingPolicy')
141
+ return touchedByPolicyWrite(prisma, target, args);
142
+ if (target.model === 'AlpacaAccount')
143
+ return touchedByAccountWrite(prisma, target, args);
144
+ return { accounts: [], policies: [] };
145
+ }
146
+ /**
147
+ * Whether `userId` owns every account a write touches, or is entitled to the
148
+ * fund each is bound to.
149
+ *
150
+ * An account the caller neither owns nor is fund-entitled to makes the whole
151
+ * write `other`; a write whose accounts could not be resolved is
152
+ * `unresolved`. Both refuse a user principal.
153
+ *
154
+ * @throws Whatever the entitlement read raised; the caller fails closed on it.
155
+ */
156
+ export async function ownershipOf(prisma, userId, touched) {
157
+ if (touched.assignedOwnerId !== undefined) {
158
+ if (touched.assignedOwnerId === null)
159
+ return { kind: 'unresolved' };
160
+ return touched.assignedOwnerId === userId ? { kind: 'owner' } : { kind: 'other' };
161
+ }
162
+ if (touched.accounts.length === 0)
163
+ return { kind: 'unresolved' };
164
+ if (touched.accounts.every((a) => a.userId === userId))
165
+ return { kind: 'owner' };
166
+ const entitlement = await resolveEntitlement(prisma, userId);
167
+ const funds = new Set(entitlement.fundIds);
168
+ const allowed = touched.accounts.every((a) => a.userId === userId || (a.brokerageAccount !== null && funds.has(a.brokerageAccount.fundId)));
169
+ return allowed ? { kind: 'fund_entitled' } : { kind: 'other' };
170
+ }
171
+ /**
172
+ * The policy row each nested TradingPolicy write reaches, resolved from THAT
173
+ * write's own path — never from the root. A policy container is resolved when
174
+ * its parent is an AlpacaAccount row the arguments name by a unique selector
175
+ * (the root `where`, or a to-many `update` / `upsert` entry's `where`); one
176
+ * whose account is created in the same mutation is `new_account`; anything
177
+ * else (a to-one hop through another model, whose row the arguments do not
178
+ * name) is `unresolved`, recorded as such rather than attributed to a guess.
179
+ *
180
+ * @param prisma - The database client.
181
+ * @param writes - The nested TradingPolicy containers, outermost first.
182
+ * @throws Whatever the database raised; the caller records the before-state
183
+ * as unread.
184
+ */
185
+ export async function resolveNestedPolicyRows(prisma, writes) {
186
+ const rows = [];
187
+ for (const write of writes.slice(0, MAX_AUDITED_BULK_ROWS)) {
188
+ if (write.parentModel === 'AlpacaAccount' && write.parentMode === 'create') {
189
+ rows.push(unidentifiedPolicyRow(write.path, 'new_account'));
190
+ continue;
191
+ }
192
+ if (write.parentModel !== 'AlpacaAccount' || !write.parentRowWhere) {
193
+ rows.push(unidentifiedPolicyRow(write.path, 'unresolved'));
194
+ continue;
195
+ }
196
+ const account = await prisma.alpacaAccount.findUnique({
197
+ where: { ...write.parentRowWhere },
198
+ select: ACCOUNT_SELECT,
199
+ });
200
+ if (!account) {
201
+ rows.push(unidentifiedPolicyRow(write.path, 'unresolved'));
202
+ continue;
203
+ }
204
+ const policy = await prisma.tradingPolicy.findUnique({
205
+ where: { alpacaAccountId: account.id },
206
+ select: POLICY_SELECT,
207
+ });
208
+ rows.push(policy ? policyRow(policy, write.path) : newPolicyRow(account, write.path));
209
+ }
210
+ return rows;
211
+ }
212
+ //# sourceMappingURL=mutation-account-facts.js.map
@@ -0,0 +1,82 @@
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 facts a
8
+ * user principal's write needs, counts and logs every decision, and writes the
9
+ * attributed TradingPolicy audit rows (`./trading-policy-audit.ts`).
10
+ *
11
+ * ## Why it wraps the Mutation fields instead of being a global middleware
12
+ *
13
+ * A TypeGraphQL global middleware is dispatched on EVERY field of every query.
14
+ * Measured on 500 rows x 8 fields, one extra global middleware — even one that
15
+ * returns after a single comparison — added ~0.35 us per field (4.2 → 5.6 ms
16
+ * per query), a cost the platform's read-heavy traffic would pay for a check
17
+ * that only ever applies to root Mutation fields. So the guard wraps the
18
+ * `resolve` of each root Mutation field on the built schema: reads pay nothing,
19
+ * and every mutation — generated or hand-written — is covered, because the
20
+ * set wrapped is the schema's own Mutation type, not a list someone maintains.
21
+ *
22
+ * Each root field of a multi-field (batched or aliased) operation is its own
23
+ * resolver call, so each is decided on its own: an allowed field never carries
24
+ * a refused sibling through with it. The guard runs outside the TypeGraphQL
25
+ * middleware chain, so it decides before the credential-field guard and the
26
+ * tenancy scoping see the field.
27
+ *
28
+ * ## Nested writes and modes
29
+ *
30
+ * A root field's arguments can write far beyond its own model (nested
31
+ * `create` / `update` / `connect` along relations). Every nested container is
32
+ * decided on its own hop (`src/auth/nested-write-policy.ts`), and the mutation
33
+ * is decided at the strictest mode among every model it writes, so an
34
+ * escalated model cannot be written through a shadow-mode root.
35
+ *
36
+ * @module middleware/mutation-auth-guard
37
+ */
38
+ import { type GraphQLSchema } from 'graphql';
39
+ import { Counter } from 'prom-client';
40
+ import { type MutationAuthMode } from '../auth/mutation-authorization';
41
+ import { type RelationFacts } from '../auth/nested-write-policy';
42
+ import type { BackendPrincipal } from '../auth/token-verifier';
43
+ import { type ActorRequest } from './trading-policy-audit';
44
+ /**
45
+ * Mutation decisions by mutation field, principal kind, decision and reason.
46
+ * Every label is bounded: the mutation field must exist in the schema to
47
+ * reach a resolver, and the other three are closed enums. The `would_deny`
48
+ * series is the list of callers enforcement would break.
49
+ */
50
+ export declare const mutationAuthorizationTotal: Counter<"mutation" | "reason" | "decision" | "principal_kind">;
51
+ /** GraphQL context shape the guard reads. */
52
+ export interface MutationAuthGuardContext {
53
+ principal?: BackendPrincipal | null;
54
+ prisma?: unknown;
55
+ req?: ActorRequest;
56
+ }
57
+ /** Options for {@link createMutationAuthGuardMiddleware}; defaults read the environment. */
58
+ export interface MutationAuthGuardOptions {
59
+ modeProvider?: () => MutationAuthMode;
60
+ enforcedModelsProvider?: () => ReadonlySet<string>;
61
+ models?: readonly string[];
62
+ /** Foreign-key placement per relation; defaults to the Prisma data model. */
63
+ relations?: RelationFacts;
64
+ now?: () => number;
65
+ }
66
+ /**
67
+ * Foreign-key placement read from the Prisma data model: `Model.relation`
68
+ * holds the key when its `relationFromFields` is non-empty.
69
+ */
70
+ export declare function prismaRelationFacts(): RelationFacts;
71
+ /** @internal Test hook: forget the log throttle state. */
72
+ export declare function resetMutationAuthLogThrottle(): void;
73
+ /**
74
+ * Wrap every root Mutation field of a built schema with the guard.
75
+ *
76
+ * @param schema - The schema `buildSchema` returned; mutated in place.
77
+ * @param options - Optional overrides for tests.
78
+ * @returns How many Mutation fields are guarded (for the boot log; zero means
79
+ * the schema has no Mutation type and nothing is protected).
80
+ */
81
+ export declare function installMutationAuthGuard(schema: GraphQLSchema, options?: MutationAuthGuardOptions): number;
82
+ //# sourceMappingURL=mutation-auth-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mutation-auth-guard.d.ts","sourceRoot":"","sources":["../../../src/middleware/mutation-auth-guard.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;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