@adaptic/backend 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,131 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Shape validation for the `MandateVersion` JSON columns on every write path.
|
|
4
|
+
*
|
|
5
|
+
* `autonomy`, `triggers` and `instruments` are JSONB, so the database accepts
|
|
6
|
+
* any value; their shapes are checked here before the resolver runs
|
|
7
|
+
* (`src/validators/mandate-version-json.ts`). The check is type-directed: it
|
|
8
|
+
* walks each root Mutation field's arguments along their GraphQL input types
|
|
9
|
+
* and validates every input object whose type is a MandateVersion data input
|
|
10
|
+
* — a `MandateVersion*` input object carrying `autonomy` as a JSON scalar. So
|
|
11
|
+
* `createOneMandateVersion`, `updateOneMandateVersion`, the upserts and the
|
|
12
|
+
* many-variants, and a version created or updated NESTED inside a Mandate
|
|
13
|
+
* write, are all held to the same shape; filter inputs (whose `autonomy` is a
|
|
14
|
+
* JSON filter, not the JSON scalar) are not.
|
|
15
|
+
*
|
|
16
|
+
* Installed like the mutation guard, by wrapping the Mutation fields of the
|
|
17
|
+
* built schema, so reads pay nothing. Install it BEFORE the mutation guard:
|
|
18
|
+
* the guard then wraps it, so authorization is decided before a caller learns
|
|
19
|
+
* anything from a validation message.
|
|
20
|
+
*
|
|
21
|
+
* @module middleware/mandate-version-validation
|
|
22
|
+
*/
|
|
23
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
|
+
exports.findMandateVersionViolations = findMandateVersionViolations;
|
|
25
|
+
exports.mandateVersionValidationError = mandateVersionValidationError;
|
|
26
|
+
exports.installMandateVersionValidation = installMandateVersionValidation;
|
|
27
|
+
const graphql_1 = require("graphql");
|
|
28
|
+
const mandate_version_json_1 = require("../validators/mandate-version-json.cjs");
|
|
29
|
+
/** Name prefix of every typegraphql-prisma input type for the model. */
|
|
30
|
+
const MODEL_INPUT_PREFIX = 'MandateVersion';
|
|
31
|
+
/** Whether an input object type is a MandateVersion DATA input (create/update), not a filter. */
|
|
32
|
+
function isMandateVersionDataInput(type) {
|
|
33
|
+
if (!type.name.startsWith(MODEL_INPUT_PREFIX))
|
|
34
|
+
return false;
|
|
35
|
+
const autonomy = type.getFields().autonomy;
|
|
36
|
+
return (autonomy !== undefined &&
|
|
37
|
+
(0, graphql_1.getNamedType)(autonomy.type) instanceof graphql_1.GraphQLScalarType);
|
|
38
|
+
}
|
|
39
|
+
function walk(value, type, path, violations) {
|
|
40
|
+
if (value === null || value === undefined)
|
|
41
|
+
return;
|
|
42
|
+
const nullable = (0, graphql_1.getNullableType)(type);
|
|
43
|
+
if (nullable instanceof graphql_1.GraphQLList) {
|
|
44
|
+
const itemType = nullable.ofType;
|
|
45
|
+
if (Array.isArray(value)) {
|
|
46
|
+
value.forEach((item, index) => walk(item, itemType, `${path}.${index}`, violations));
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
walk(value, itemType, path, violations);
|
|
50
|
+
}
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
if (!(nullable instanceof graphql_1.GraphQLInputObjectType))
|
|
54
|
+
return;
|
|
55
|
+
if (typeof value !== 'object' || Array.isArray(value))
|
|
56
|
+
return;
|
|
57
|
+
const record = value;
|
|
58
|
+
if (isMandateVersionDataInput(nullable)) {
|
|
59
|
+
violations.push(...(0, mandate_version_json_1.mandateVersionJsonViolations)(record, path));
|
|
60
|
+
}
|
|
61
|
+
const fields = nullable.getFields();
|
|
62
|
+
for (const [key, child] of Object.entries(record)) {
|
|
63
|
+
const field = fields[key];
|
|
64
|
+
if (!field)
|
|
65
|
+
continue;
|
|
66
|
+
walk(child, field.type, path.length > 0 ? `${path}.${key}` : key, violations);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Every MandateVersion JSON shape violation in a mutation's arguments.
|
|
71
|
+
*
|
|
72
|
+
* @param field - The root Mutation field.
|
|
73
|
+
* @param args - Its resolved arguments.
|
|
74
|
+
*/
|
|
75
|
+
function findMandateVersionViolations(field, args) {
|
|
76
|
+
const violations = [];
|
|
77
|
+
for (const arg of field.args) {
|
|
78
|
+
walk(args[arg.name], arg.type, arg.name, violations);
|
|
79
|
+
}
|
|
80
|
+
return violations;
|
|
81
|
+
}
|
|
82
|
+
/** The `BAD_USER_INPUT` error (HTTP 400) listing the violations. */
|
|
83
|
+
function mandateVersionValidationError(violations) {
|
|
84
|
+
return new graphql_1.GraphQLError(`Invalid MandateVersion JSON: ${violations.map((v) => `${v.path}: ${v.message}`).join('; ')}`, {
|
|
85
|
+
extensions: { code: 'BAD_USER_INPUT', violations, http: { status: 400 } },
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
const validatedFields = new WeakSet();
|
|
89
|
+
/**
|
|
90
|
+
* Wrap every root Mutation field of a built schema with the shape check.
|
|
91
|
+
*
|
|
92
|
+
* @param schema - The schema `buildSchema` returned; mutated in place.
|
|
93
|
+
* @returns How many Mutation fields can write a MandateVersion (zero means the
|
|
94
|
+
* check protects nothing and the codegen naming has drifted).
|
|
95
|
+
*/
|
|
96
|
+
function installMandateVersionValidation(schema) {
|
|
97
|
+
var _a;
|
|
98
|
+
const mutationType = schema.getMutationType();
|
|
99
|
+
if (!mutationType)
|
|
100
|
+
return 0;
|
|
101
|
+
let covered = 0;
|
|
102
|
+
for (const field of Object.values(mutationType.getFields())) {
|
|
103
|
+
if (validatedFields.has(field) || !reachesMandateVersionData(field))
|
|
104
|
+
continue;
|
|
105
|
+
covered += 1;
|
|
106
|
+
const original = (_a = field.resolve) !== null && _a !== void 0 ? _a : graphql_1.defaultFieldResolver;
|
|
107
|
+
field.resolve = (source, args, context, info) => {
|
|
108
|
+
const violations = findMandateVersionViolations(field, args);
|
|
109
|
+
if (violations.length > 0)
|
|
110
|
+
throw mandateVersionValidationError(violations);
|
|
111
|
+
return original(source, args, context, info);
|
|
112
|
+
};
|
|
113
|
+
validatedFields.add(field);
|
|
114
|
+
}
|
|
115
|
+
return covered;
|
|
116
|
+
}
|
|
117
|
+
/** Whether any argument of a field can (transitively) carry a MandateVersion data input. */
|
|
118
|
+
function reachesMandateVersionData(field) {
|
|
119
|
+
const seen = new Set();
|
|
120
|
+
const visit = (type) => {
|
|
121
|
+
const named = (0, graphql_1.getNamedType)(type);
|
|
122
|
+
if (!(named instanceof graphql_1.GraphQLInputObjectType) || seen.has(named.name))
|
|
123
|
+
return false;
|
|
124
|
+
seen.add(named.name);
|
|
125
|
+
if (isMandateVersionDataInput(named))
|
|
126
|
+
return true;
|
|
127
|
+
return Object.values(named.getFields()).some((f) => visit(f.type));
|
|
128
|
+
};
|
|
129
|
+
return field.args.some((arg) => visit(arg.type));
|
|
130
|
+
}
|
|
131
|
+
//# sourceMappingURL=mandate-version-validation.js.map
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shape validation for the `MandateVersion` JSON columns on every write path.
|
|
3
|
+
*
|
|
4
|
+
* `autonomy`, `triggers` and `instruments` are JSONB, so the database accepts
|
|
5
|
+
* any value; their shapes are checked here before the resolver runs
|
|
6
|
+
* (`src/validators/mandate-version-json.ts`). The check is type-directed: it
|
|
7
|
+
* walks each root Mutation field's arguments along their GraphQL input types
|
|
8
|
+
* and validates every input object whose type is a MandateVersion data input
|
|
9
|
+
* — a `MandateVersion*` input object carrying `autonomy` as a JSON scalar. So
|
|
10
|
+
* `createOneMandateVersion`, `updateOneMandateVersion`, the upserts and the
|
|
11
|
+
* many-variants, and a version created or updated NESTED inside a Mandate
|
|
12
|
+
* write, are all held to the same shape; filter inputs (whose `autonomy` is a
|
|
13
|
+
* JSON filter, not the JSON scalar) are not.
|
|
14
|
+
*
|
|
15
|
+
* Installed like the mutation guard, by wrapping the Mutation fields of the
|
|
16
|
+
* built schema, so reads pay nothing. Install it BEFORE the mutation guard:
|
|
17
|
+
* the guard then wraps it, so authorization is decided before a caller learns
|
|
18
|
+
* anything from a validation message.
|
|
19
|
+
*
|
|
20
|
+
* @module middleware/mandate-version-validation
|
|
21
|
+
*/
|
|
22
|
+
import { GraphQLError, type GraphQLField, type GraphQLSchema } from 'graphql';
|
|
23
|
+
import { type MandateJsonViolation } from '../validators/mandate-version-json';
|
|
24
|
+
/**
|
|
25
|
+
* Every MandateVersion JSON shape violation in a mutation's arguments.
|
|
26
|
+
*
|
|
27
|
+
* @param field - The root Mutation field.
|
|
28
|
+
* @param args - Its resolved arguments.
|
|
29
|
+
*/
|
|
30
|
+
export declare function findMandateVersionViolations(field: Pick<GraphQLField<unknown, unknown>, 'args'>, args: Record<string, unknown>): MandateJsonViolation[];
|
|
31
|
+
/** The `BAD_USER_INPUT` error (HTTP 400) listing the violations. */
|
|
32
|
+
export declare function mandateVersionValidationError(violations: readonly MandateJsonViolation[]): GraphQLError;
|
|
33
|
+
/**
|
|
34
|
+
* Wrap every root Mutation field of a built schema with the shape check.
|
|
35
|
+
*
|
|
36
|
+
* @param schema - The schema `buildSchema` returned; mutated in place.
|
|
37
|
+
* @returns How many Mutation fields can write a MandateVersion (zero means the
|
|
38
|
+
* check protects nothing and the codegen naming has drifted).
|
|
39
|
+
*/
|
|
40
|
+
export declare function installMandateVersionValidation(schema: GraphQLSchema): number;
|
|
41
|
+
//# sourceMappingURL=mandate-version-validation.d.ts.map
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Database facts the mutation guard needs: which brokerage accounts a
|
|
4
|
+
* TradingPolicy / AlpacaAccount write touches, who owns them, and — for the
|
|
5
|
+
* audit trail — each touched policy's switch values before the write.
|
|
6
|
+
*
|
|
7
|
+
* One read serves both purposes, so a policy write costs the guard a single
|
|
8
|
+
* `findUnique` (or a bounded `findMany` for a bulk write) plus, for a user
|
|
9
|
+
* principal, the entitlement read the tenancy scoping already performs.
|
|
10
|
+
*
|
|
11
|
+
* Every read here fails CLOSED at the caller: an account the guard cannot
|
|
12
|
+
* resolve is `unresolved`, which a user principal is refused on, and the
|
|
13
|
+
* failure is logged rather than turned into an ownership answer.
|
|
14
|
+
*
|
|
15
|
+
* @module middleware/mutation-account-facts
|
|
16
|
+
*/
|
|
17
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
|
+
exports.MAX_AUDITED_BULK_ROWS = void 0;
|
|
19
|
+
exports.loadTouchedAccounts = loadTouchedAccounts;
|
|
20
|
+
exports.ownershipOf = ownershipOf;
|
|
21
|
+
exports.resolveNestedPolicyRows = resolveNestedPolicyRows;
|
|
22
|
+
const tenancy_scope_1 = require("../auth/tenancy-scope.cjs");
|
|
23
|
+
/** Most rows a bulk policy write records in its audit row. */
|
|
24
|
+
exports.MAX_AUDITED_BULK_ROWS = 200;
|
|
25
|
+
const ACCOUNT_SELECT = {
|
|
26
|
+
id: true,
|
|
27
|
+
userId: true,
|
|
28
|
+
type: true,
|
|
29
|
+
brokerageAccount: { select: { fundId: true } },
|
|
30
|
+
};
|
|
31
|
+
const POLICY_SELECT = {
|
|
32
|
+
id: true,
|
|
33
|
+
alpacaAccountId: true,
|
|
34
|
+
realtimeTradingEnabled: true,
|
|
35
|
+
paperTradingOnly: true,
|
|
36
|
+
killSwitchEnabled: true,
|
|
37
|
+
autonomyMode: true,
|
|
38
|
+
intradayLanePrefs: true,
|
|
39
|
+
alpacaAccount: { select: ACCOUNT_SELECT },
|
|
40
|
+
};
|
|
41
|
+
function asRecord(value) {
|
|
42
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
43
|
+
? value
|
|
44
|
+
: undefined;
|
|
45
|
+
}
|
|
46
|
+
function stringAt(value, ...path) {
|
|
47
|
+
var _a;
|
|
48
|
+
let cursor = value;
|
|
49
|
+
for (const key of path)
|
|
50
|
+
cursor = (_a = asRecord(cursor)) === null || _a === void 0 ? void 0 : _a[key];
|
|
51
|
+
return typeof cursor === 'string' && cursor.length > 0 ? cursor : undefined;
|
|
52
|
+
}
|
|
53
|
+
/** The account a TradingPolicy create payload attaches to. */
|
|
54
|
+
function policyAccountIdIn(data) {
|
|
55
|
+
var _a;
|
|
56
|
+
return (_a = stringAt(data, 'alpacaAccountId')) !== null && _a !== void 0 ? _a : stringAt(data, 'alpacaAccount', 'connect', 'id');
|
|
57
|
+
}
|
|
58
|
+
function policyRow(row, nestedPath = null) {
|
|
59
|
+
return {
|
|
60
|
+
nestedPath,
|
|
61
|
+
resolution: 'resolved',
|
|
62
|
+
policyId: row.id,
|
|
63
|
+
alpacaAccountId: row.alpacaAccountId,
|
|
64
|
+
accountType: row.alpacaAccount.type,
|
|
65
|
+
before: {
|
|
66
|
+
realtimeTradingEnabled: row.realtimeTradingEnabled,
|
|
67
|
+
paperTradingOnly: row.paperTradingOnly,
|
|
68
|
+
killSwitchEnabled: row.killSwitchEnabled,
|
|
69
|
+
autonomyMode: row.autonomyMode,
|
|
70
|
+
intradayLanePrefs: row.intradayLanePrefs,
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
function newPolicyRow(account, nestedPath = null) {
|
|
75
|
+
return {
|
|
76
|
+
nestedPath,
|
|
77
|
+
resolution: 'resolved',
|
|
78
|
+
policyId: null,
|
|
79
|
+
alpacaAccountId: account.id,
|
|
80
|
+
accountType: account.type,
|
|
81
|
+
before: null,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
/** A policy write whose account the arguments do not identify. */
|
|
85
|
+
function unidentifiedPolicyRow(nestedPath, resolution) {
|
|
86
|
+
return { nestedPath, resolution, policyId: null, alpacaAccountId: null, accountType: null, before: null };
|
|
87
|
+
}
|
|
88
|
+
async function accountById(prisma, id) {
|
|
89
|
+
return prisma.alpacaAccount.findUnique({ where: { id }, select: ACCOUNT_SELECT });
|
|
90
|
+
}
|
|
91
|
+
async function touchedByPolicyWrite(prisma, target, args) {
|
|
92
|
+
const where = asRecord(args.where);
|
|
93
|
+
if (target.cardinality === 'many') {
|
|
94
|
+
if (target.action === 'create') {
|
|
95
|
+
const items = Array.isArray(args.data) ? args.data : [args.data];
|
|
96
|
+
const accounts = [];
|
|
97
|
+
for (const item of items.slice(0, exports.MAX_AUDITED_BULK_ROWS)) {
|
|
98
|
+
const id = policyAccountIdIn(item);
|
|
99
|
+
const account = id ? await accountById(prisma, id) : null;
|
|
100
|
+
if (account)
|
|
101
|
+
accounts.push(account);
|
|
102
|
+
}
|
|
103
|
+
return { accounts, policies: accounts.map((a) => newPolicyRow(a)) };
|
|
104
|
+
}
|
|
105
|
+
const rows = await prisma.tradingPolicy.findMany({
|
|
106
|
+
where: where !== null && where !== void 0 ? where : {},
|
|
107
|
+
select: POLICY_SELECT,
|
|
108
|
+
take: exports.MAX_AUDITED_BULK_ROWS,
|
|
109
|
+
});
|
|
110
|
+
return { accounts: rows.map((r) => r.alpacaAccount), policies: rows.map((r) => policyRow(r)) };
|
|
111
|
+
}
|
|
112
|
+
const existing = where && target.action !== 'create'
|
|
113
|
+
? await prisma.tradingPolicy.findUnique({ where, select: POLICY_SELECT })
|
|
114
|
+
: null;
|
|
115
|
+
if (existing) {
|
|
116
|
+
return { accounts: [existing.alpacaAccount], policies: [policyRow(existing)] };
|
|
117
|
+
}
|
|
118
|
+
const createData = target.action === 'upsert' ? args.create : args.data;
|
|
119
|
+
const accountId = target.action === 'create' || target.action === 'upsert'
|
|
120
|
+
? policyAccountIdIn(createData)
|
|
121
|
+
: undefined;
|
|
122
|
+
const account = accountId ? await accountById(prisma, accountId) : null;
|
|
123
|
+
return account ? { accounts: [account], policies: [newPolicyRow(account)] } : { accounts: [], policies: [] };
|
|
124
|
+
}
|
|
125
|
+
async function touchedByAccountWrite(prisma, target, args) {
|
|
126
|
+
var _a, _b;
|
|
127
|
+
if (target.action === 'create') {
|
|
128
|
+
const owner = (_b = (_a = stringAt(args.data, 'userId')) !== null && _a !== void 0 ? _a : stringAt(args.data, 'user', 'connect', 'id')) !== null && _b !== void 0 ? _b : null;
|
|
129
|
+
return { accounts: [], policies: [], assignedOwnerId: owner };
|
|
130
|
+
}
|
|
131
|
+
const where = asRecord(args.where);
|
|
132
|
+
if (!where || target.cardinality === 'many')
|
|
133
|
+
return { accounts: [], policies: [] };
|
|
134
|
+
const account = await prisma.alpacaAccount.findUnique({ where, select: ACCOUNT_SELECT });
|
|
135
|
+
if (!account)
|
|
136
|
+
return { accounts: [], policies: [] };
|
|
137
|
+
const policy = await prisma.tradingPolicy.findUnique({
|
|
138
|
+
where: { alpacaAccountId: account.id },
|
|
139
|
+
select: POLICY_SELECT,
|
|
140
|
+
});
|
|
141
|
+
return { accounts: [account], policies: policy ? [policyRow(policy)] : [] };
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* The accounts (and existing policy rows) a mutation on `TradingPolicy` or
|
|
145
|
+
* `AlpacaAccount` touches. Any other root model touches no account the guard
|
|
146
|
+
* can resolve from its arguments, and yields an empty result.
|
|
147
|
+
*
|
|
148
|
+
* @throws Whatever the database raised; the caller fails closed on it.
|
|
149
|
+
*/
|
|
150
|
+
async function loadTouchedAccounts(prisma, target, args) {
|
|
151
|
+
if (target.model === 'TradingPolicy')
|
|
152
|
+
return touchedByPolicyWrite(prisma, target, args);
|
|
153
|
+
if (target.model === 'AlpacaAccount')
|
|
154
|
+
return touchedByAccountWrite(prisma, target, args);
|
|
155
|
+
return { accounts: [], policies: [] };
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Whether `userId` owns every account a write touches, or is entitled to the
|
|
159
|
+
* fund each is bound to.
|
|
160
|
+
*
|
|
161
|
+
* An account the caller neither owns nor is fund-entitled to makes the whole
|
|
162
|
+
* write `other`; a write whose accounts could not be resolved is
|
|
163
|
+
* `unresolved`. Both refuse a user principal.
|
|
164
|
+
*
|
|
165
|
+
* @throws Whatever the entitlement read raised; the caller fails closed on it.
|
|
166
|
+
*/
|
|
167
|
+
async function ownershipOf(prisma, userId, touched) {
|
|
168
|
+
if (touched.assignedOwnerId !== undefined) {
|
|
169
|
+
if (touched.assignedOwnerId === null)
|
|
170
|
+
return { kind: 'unresolved' };
|
|
171
|
+
return touched.assignedOwnerId === userId ? { kind: 'owner' } : { kind: 'other' };
|
|
172
|
+
}
|
|
173
|
+
if (touched.accounts.length === 0)
|
|
174
|
+
return { kind: 'unresolved' };
|
|
175
|
+
if (touched.accounts.every((a) => a.userId === userId))
|
|
176
|
+
return { kind: 'owner' };
|
|
177
|
+
const entitlement = await (0, tenancy_scope_1.resolveEntitlement)(prisma, userId);
|
|
178
|
+
const funds = new Set(entitlement.fundIds);
|
|
179
|
+
const allowed = touched.accounts.every((a) => a.userId === userId || (a.brokerageAccount !== null && funds.has(a.brokerageAccount.fundId)));
|
|
180
|
+
return allowed ? { kind: 'fund_entitled' } : { kind: 'other' };
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* The policy row each nested TradingPolicy write reaches, resolved from THAT
|
|
184
|
+
* write's own path — never from the root. A policy container is resolved when
|
|
185
|
+
* its parent is an AlpacaAccount row the arguments name by a unique selector
|
|
186
|
+
* (the root `where`, or a to-many `update` / `upsert` entry's `where`); one
|
|
187
|
+
* whose account is created in the same mutation is `new_account`; anything
|
|
188
|
+
* else (a to-one hop through another model, whose row the arguments do not
|
|
189
|
+
* name) is `unresolved`, recorded as such rather than attributed to a guess.
|
|
190
|
+
*
|
|
191
|
+
* @param prisma - The database client.
|
|
192
|
+
* @param writes - The nested TradingPolicy containers, outermost first.
|
|
193
|
+
* @throws Whatever the database raised; the caller records the before-state
|
|
194
|
+
* as unread.
|
|
195
|
+
*/
|
|
196
|
+
async function resolveNestedPolicyRows(prisma, writes) {
|
|
197
|
+
const rows = [];
|
|
198
|
+
for (const write of writes.slice(0, exports.MAX_AUDITED_BULK_ROWS)) {
|
|
199
|
+
if (write.parentModel === 'AlpacaAccount' && write.parentMode === 'create') {
|
|
200
|
+
rows.push(unidentifiedPolicyRow(write.path, 'new_account'));
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
if (write.parentModel !== 'AlpacaAccount' || !write.parentRowWhere) {
|
|
204
|
+
rows.push(unidentifiedPolicyRow(write.path, 'unresolved'));
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
const account = await prisma.alpacaAccount.findUnique({
|
|
208
|
+
where: { ...write.parentRowWhere },
|
|
209
|
+
select: ACCOUNT_SELECT,
|
|
210
|
+
});
|
|
211
|
+
if (!account) {
|
|
212
|
+
rows.push(unidentifiedPolicyRow(write.path, 'unresolved'));
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
const policy = await prisma.tradingPolicy.findUnique({
|
|
216
|
+
where: { alpacaAccountId: account.id },
|
|
217
|
+
select: POLICY_SELECT,
|
|
218
|
+
});
|
|
219
|
+
rows.push(policy ? policyRow(policy, write.path) : newPolicyRow(account, write.path));
|
|
220
|
+
}
|
|
221
|
+
return rows;
|
|
222
|
+
}
|
|
223
|
+
//# sourceMappingURL=mutation-account-facts.js.map
|
|
@@ -0,0 +1,143 @@
|
|
|
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 { Prisma } from '@prisma/client';
|
|
17
|
+
import type { AccountOwnership, MutationTarget } from '../auth/mutation-authorization';
|
|
18
|
+
import type { NestedWrite } from '../auth/nested-write-inspector';
|
|
19
|
+
import type { TenantScopePrisma } from './mutation-tenant-facts';
|
|
20
|
+
import type { AuditedPolicyRow, AuditLogWriter } from './trading-policy-audit';
|
|
21
|
+
/** Most rows a bulk policy write records in its audit row. */
|
|
22
|
+
export declare const MAX_AUDITED_BULK_ROWS = 200;
|
|
23
|
+
declare const ACCOUNT_SELECT: {
|
|
24
|
+
readonly id: true;
|
|
25
|
+
readonly userId: true;
|
|
26
|
+
readonly type: true;
|
|
27
|
+
readonly brokerageAccount: {
|
|
28
|
+
readonly select: {
|
|
29
|
+
readonly fundId: true;
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
declare const POLICY_SELECT: {
|
|
34
|
+
readonly id: true;
|
|
35
|
+
readonly alpacaAccountId: true;
|
|
36
|
+
readonly realtimeTradingEnabled: true;
|
|
37
|
+
readonly paperTradingOnly: true;
|
|
38
|
+
readonly killSwitchEnabled: true;
|
|
39
|
+
readonly autonomyMode: true;
|
|
40
|
+
readonly intradayLanePrefs: true;
|
|
41
|
+
readonly alpacaAccount: {
|
|
42
|
+
readonly select: {
|
|
43
|
+
readonly id: true;
|
|
44
|
+
readonly userId: true;
|
|
45
|
+
readonly type: true;
|
|
46
|
+
readonly brokerageAccount: {
|
|
47
|
+
readonly select: {
|
|
48
|
+
readonly fundId: true;
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
/** The account columns the guard reads. */
|
|
55
|
+
export interface AccountFacts {
|
|
56
|
+
readonly id: string;
|
|
57
|
+
readonly userId: string;
|
|
58
|
+
readonly type: string;
|
|
59
|
+
readonly brokerageAccount: {
|
|
60
|
+
readonly fundId: string;
|
|
61
|
+
} | null;
|
|
62
|
+
}
|
|
63
|
+
/** The policy columns the guard reads. */
|
|
64
|
+
export interface PolicyFacts {
|
|
65
|
+
readonly id: string;
|
|
66
|
+
readonly alpacaAccountId: string;
|
|
67
|
+
readonly realtimeTradingEnabled: boolean;
|
|
68
|
+
readonly paperTradingOnly: boolean;
|
|
69
|
+
readonly killSwitchEnabled: boolean;
|
|
70
|
+
readonly autonomyMode: string;
|
|
71
|
+
readonly intradayLanePrefs: Prisma.JsonValue | null;
|
|
72
|
+
readonly alpacaAccount: AccountFacts;
|
|
73
|
+
}
|
|
74
|
+
type Where = Record<string, unknown>;
|
|
75
|
+
/**
|
|
76
|
+
* The slice of the Prisma client the guard uses. Declared structurally so the
|
|
77
|
+
* guard can be exercised against a fake, the pattern the tenancy scoping uses.
|
|
78
|
+
*/
|
|
79
|
+
export interface MutationAuthPrisma extends AuditLogWriter, TenantScopePrisma {
|
|
80
|
+
tradingPolicy: {
|
|
81
|
+
findUnique(args: {
|
|
82
|
+
where: Where;
|
|
83
|
+
select: typeof POLICY_SELECT;
|
|
84
|
+
}): Promise<PolicyFacts | null>;
|
|
85
|
+
findMany(args: {
|
|
86
|
+
where: Where;
|
|
87
|
+
select: typeof POLICY_SELECT;
|
|
88
|
+
take: number;
|
|
89
|
+
}): Promise<PolicyFacts[]>;
|
|
90
|
+
};
|
|
91
|
+
alpacaAccount: {
|
|
92
|
+
findUnique(args: {
|
|
93
|
+
where: Where;
|
|
94
|
+
select: typeof ACCOUNT_SELECT;
|
|
95
|
+
}): Promise<AccountFacts | null>;
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
/** The accounts a write touches, with policy rows where they already exist. */
|
|
99
|
+
export interface TouchedAccounts {
|
|
100
|
+
readonly accounts: readonly AccountFacts[];
|
|
101
|
+
readonly policies: readonly AuditedPolicyRow[];
|
|
102
|
+
/**
|
|
103
|
+
* For an `AlpacaAccount` create: the owner the payload assigns. No account
|
|
104
|
+
* row exists yet, so ownership is decided from this.
|
|
105
|
+
*/
|
|
106
|
+
readonly assignedOwnerId?: string | null;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* The accounts (and existing policy rows) a mutation on `TradingPolicy` or
|
|
110
|
+
* `AlpacaAccount` touches. Any other root model touches no account the guard
|
|
111
|
+
* can resolve from its arguments, and yields an empty result.
|
|
112
|
+
*
|
|
113
|
+
* @throws Whatever the database raised; the caller fails closed on it.
|
|
114
|
+
*/
|
|
115
|
+
export declare function loadTouchedAccounts(prisma: MutationAuthPrisma, target: MutationTarget, args: Record<string, unknown>): Promise<TouchedAccounts>;
|
|
116
|
+
/**
|
|
117
|
+
* Whether `userId` owns every account a write touches, or is entitled to the
|
|
118
|
+
* fund each is bound to.
|
|
119
|
+
*
|
|
120
|
+
* An account the caller neither owns nor is fund-entitled to makes the whole
|
|
121
|
+
* write `other`; a write whose accounts could not be resolved is
|
|
122
|
+
* `unresolved`. Both refuse a user principal.
|
|
123
|
+
*
|
|
124
|
+
* @throws Whatever the entitlement read raised; the caller fails closed on it.
|
|
125
|
+
*/
|
|
126
|
+
export declare function ownershipOf(prisma: MutationAuthPrisma, userId: string, touched: TouchedAccounts): Promise<AccountOwnership>;
|
|
127
|
+
/**
|
|
128
|
+
* The policy row each nested TradingPolicy write reaches, resolved from THAT
|
|
129
|
+
* write's own path — never from the root. A policy container is resolved when
|
|
130
|
+
* its parent is an AlpacaAccount row the arguments name by a unique selector
|
|
131
|
+
* (the root `where`, or a to-many `update` / `upsert` entry's `where`); one
|
|
132
|
+
* whose account is created in the same mutation is `new_account`; anything
|
|
133
|
+
* else (a to-one hop through another model, whose row the arguments do not
|
|
134
|
+
* name) is `unresolved`, recorded as such rather than attributed to a guess.
|
|
135
|
+
*
|
|
136
|
+
* @param prisma - The database client.
|
|
137
|
+
* @param writes - The nested TradingPolicy containers, outermost first.
|
|
138
|
+
* @throws Whatever the database raised; the caller records the before-state
|
|
139
|
+
* as unread.
|
|
140
|
+
*/
|
|
141
|
+
export declare function resolveNestedPolicyRows(prisma: MutationAuthPrisma, writes: readonly NestedWrite[]): Promise<AuditedPolicyRow[]>;
|
|
142
|
+
export {};
|
|
143
|
+
//# sourceMappingURL=mutation-account-facts.d.ts.map
|