@adaptic/backend-legacy 0.0.1057 → 0.0.1059
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/auth/authorization-map.cjs +306 -0
- package/auth/authorization-map.d.ts +143 -0
- package/auth/cortex-auth-checker.cjs +172 -0
- package/auth/cortex-auth-checker.d.ts +114 -0
- package/auth/credential-fields.cjs +51 -0
- package/auth/credential-fields.d.ts +19 -0
- package/auth/credential-redaction.cjs +134 -0
- package/auth/credential-redaction.d.ts +60 -0
- package/auth/graphql-auth-shadow.cjs +317 -0
- package/auth/graphql-auth-shadow.d.ts +194 -0
- package/auth/membership-write-authority.cjs +131 -0
- package/auth/membership-write-authority.d.ts +110 -0
- package/auth/mutation-authorization.cjs +376 -0
- package/auth/mutation-authorization.d.ts +261 -0
- package/auth/nested-write-inspector.cjs +189 -0
- package/auth/nested-write-inspector.d.ts +94 -0
- package/auth/nested-write-policy.cjs +189 -0
- package/auth/nested-write-policy.d.ts +99 -0
- package/auth/service-token.cjs +339 -0
- package/auth/service-token.d.ts +106 -0
- package/auth/tenancy-scope.cjs +736 -0
- package/auth/tenancy-scope.d.ts +347 -0
- package/auth/token-verifier.cjs +451 -0
- package/auth/token-verifier.d.ts +153 -0
- package/auth/totp.cjs +265 -0
- package/auth/totp.d.ts +111 -0
- package/auth/user-write-content.cjs +116 -0
- package/auth/user-write-content.d.ts +47 -0
- package/auth/ws-auth-context.cjs +75 -0
- package/auth/ws-auth-context.d.ts +69 -0
- package/config/jwtConfig.cjs +57 -0
- package/config/jwtConfig.d.ts +16 -0
- package/config/metrics.cjs +356 -0
- package/config/metrics.d.ts +128 -0
- package/config/persisted-queries.cjs +122 -0
- package/config/persisted-queries.d.ts +40 -0
- package/config/server-only-models.cjs +166 -0
- package/config/server-only-models.d.ts +89 -0
- package/config/tracing.d.ts +24 -0
- package/esm/auth/service-token.d.ts +12 -0
- package/esm/auth/service-token.mjs +27 -5
- package/esm/config/jwtConfig.mjs +5 -1
- package/generated/typegraphql-prisma/enhance.cjs +3 -3
- package/generated/typegraphql-prisma/index.cjs +6 -6
- package/generated/typegraphql-prisma/resolvers/crud/args.index.cjs +95 -95
- package/generated/typegraphql-prisma/resolvers/outputs/index.cjs +1 -1
- package/generated/typegraphql-prisma/resolvers/relations/args.index.cjs +32 -32
- package/middleware/audit-log-write-redaction.cjs +143 -0
- package/middleware/audit-log-write-redaction.d.ts +82 -0
- package/middleware/audit-logger.cjs +378 -0
- package/middleware/audit-logger.d.ts +158 -0
- package/middleware/audit-payload-guard.cjs +107 -0
- package/middleware/audit-payload-guard.d.ts +85 -0
- package/middleware/auth.cjs +66 -0
- package/middleware/auth.d.ts +41 -0
- package/middleware/credential-field-guard.cjs +514 -0
- package/middleware/credential-field-guard.d.ts +173 -0
- package/middleware/generated-type-names.cjs +77 -0
- package/middleware/generated-type-names.d.ts +44 -0
- package/middleware/graphql-validation-plugin.cjs +310 -0
- package/middleware/graphql-validation-plugin.d.ts +98 -0
- package/middleware/guard-log-throttle.cjs +89 -0
- package/middleware/guard-log-throttle.d.ts +80 -0
- package/middleware/index.cjs +57 -0
- package/middleware/index.d.ts +14 -0
- package/middleware/input-validator.cjs +220 -0
- package/middleware/input-validator.d.ts +63 -0
- package/middleware/mandate-version-validation.cjs +131 -0
- package/middleware/mandate-version-validation.d.ts +41 -0
- package/middleware/mutation-account-facts.cjs +223 -0
- package/middleware/mutation-account-facts.d.ts +143 -0
- package/middleware/mutation-auth-guard.cjs +536 -0
- package/middleware/mutation-auth-guard.d.ts +100 -0
- package/middleware/mutation-membership-facts.cjs +276 -0
- package/middleware/mutation-membership-facts.d.ts +133 -0
- package/middleware/mutation-tenant-facts.cjs +132 -0
- package/middleware/mutation-tenant-facts.d.ts +81 -0
- package/middleware/query-complexity.cjs +182 -0
- package/middleware/query-complexity.d.ts +56 -0
- package/middleware/rate-limiter.cjs +223 -0
- package/middleware/rate-limiter.d.ts +93 -0
- package/middleware/rate-tier.cjs +111 -0
- package/middleware/rate-tier.d.ts +56 -0
- package/middleware/soft-delete.cjs +175 -0
- package/middleware/soft-delete.d.ts +146 -0
- package/middleware/tenancy-scoping.cjs +229 -0
- package/middleware/tenancy-scoping.d.ts +67 -0
- package/middleware/trading-policy-audit.cjs +353 -0
- package/middleware/trading-policy-audit.d.ts +184 -0
- package/middleware/types.cjs +17 -0
- package/middleware/types.d.ts +87 -0
- package/middleware/validation-examples.cjs +398 -0
- package/middleware/validation-examples.d.ts +76 -0
- package/package.json +10 -2
- package/readers/index.cjs +15 -0
- package/readers/index.d.ts +10 -0
- package/readers/intraday-lane-prefs.cjs +76 -0
- package/readers/intraday-lane-prefs.d.ts +45 -0
- package/esm/config/__tests__/server-only-surface.harness.d.ts +0 -12
- package/esm/config/__tests__/server-only-surface.harness.mjs +0 -41
- package/esm/middleware/__tests__/audit-log-write-redaction.harness.d.ts +0 -144
- package/esm/middleware/__tests__/audit-log-write-redaction.harness.mjs +0 -920
- package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts +0 -55
- package/esm/middleware/__tests__/credential-field-coverage.harness.mjs +0 -440
- package/esm/middleware/__tests__/credential-field-guard.harness.d.ts +0 -34
- package/esm/middleware/__tests__/credential-field-guard.harness.mjs +0 -212
- package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +0 -56
- package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +0 -575
- package/esm/middleware/__tests__/rate-limit-test-utils.d.ts +0 -60
- package/esm/middleware/__tests__/rate-limit-test-utils.mjs +0 -85
- package/esm/middleware/__tests__/ts-node-harness.d.ts +0 -10
- package/esm/middleware/__tests__/ts-node-harness.mjs +0 -71
- package/health.cjs +0 -274
- package/server.cjs +0 -607
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Credential-field guard: stored credentials resolve, and can be filtered or
|
|
3
|
+
* sorted on, only for a verified service principal.
|
|
4
|
+
*
|
|
5
|
+
* ## Why this exists
|
|
6
|
+
*
|
|
7
|
+
* The `/graphql` context admits a request that presents no bearer token as a
|
|
8
|
+
* null principal — context-level enforcement is staged per
|
|
9
|
+
* `docs/security/2026-08-23-graphql-auth-enforcement-runbook.md` because live
|
|
10
|
+
* callers still depend on that path. The generated Prisma types expose every
|
|
11
|
+
* scalar column as a plain field, including the broker API key and secret on
|
|
12
|
+
* `AlpacaAccount` and the OAuth, session and invite tokens on the auth models.
|
|
13
|
+
* With a null principal admitted, those columns are readable by anyone who can
|
|
14
|
+
* reach the endpoint.
|
|
15
|
+
*
|
|
16
|
+
* Hiding the field alone is not enough. A filter, sort or cursor over a
|
|
17
|
+
* credential column is an oracle: `where: { APISecret: { startsWith: "a" } }`
|
|
18
|
+
* answers "does any row match" without ever selecting the field, and a caller
|
|
19
|
+
* can walk the whole secret one character at a time. `groupBy` and the
|
|
20
|
+
* `_min` / `_max` aggregates return the column's value directly. So the guard
|
|
21
|
+
* covers every way a query can observe a credential, not just the field.
|
|
22
|
+
*
|
|
23
|
+
* A stored credential is only ever needed by a service acting for the
|
|
24
|
+
* platform — the engine placing an order with an account's key. No end user,
|
|
25
|
+
* admin session or anonymous caller needs the raw value, so the read surface
|
|
26
|
+
* admits `kind: "server"` only. Writes of a credential are governed by the
|
|
27
|
+
* mutation authentication guard, not here.
|
|
28
|
+
*
|
|
29
|
+
* ## What is guarded
|
|
30
|
+
*
|
|
31
|
+
* 1. **Output** — a credential field on its model type and on that model's
|
|
32
|
+
* `GroupBy` / `MinAggregate` / `MaxAggregate` output types, and on the
|
|
33
|
+
* `CreateManyAndReturn…` / `UpdateManyAndReturn…` row types a bulk write
|
|
34
|
+
* returns.
|
|
35
|
+
* 2. **Filter and sort input** — any argument that names a credential field:
|
|
36
|
+
* a key in the model's own `…Where…`, `…OrderBy…` or `…Having…` input types
|
|
37
|
+
* at any nesting depth (AND / OR / NOT, relation filters reached from other
|
|
38
|
+
* models), and a `by` / `distinct` value of the model's `ScalarFieldEnum`.
|
|
39
|
+
* 3. **Copies in audit payloads** — `AuditLog` JSON payloads hold credentials
|
|
40
|
+
* copied from mutation variables. The same middleware serves them redacted
|
|
41
|
+
* to user and anonymous principals and refuses those principals predicates
|
|
42
|
+
* over them; the rules and their reasons are in `audit-payload-guard`.
|
|
43
|
+
*
|
|
44
|
+
* ## Modes (`CREDENTIAL_FIELD_GUARD_MODE`, read on every request)
|
|
45
|
+
*
|
|
46
|
+
* - `enforce` — deny with `FORBIDDEN`. This is the default, and the value any
|
|
47
|
+
* unset or unrecognised setting resolves to: a guard whose configuration
|
|
48
|
+
* cannot be read must refuse, never admit.
|
|
49
|
+
* - `shadow` — resolve unchanged, but count and log every access `enforce`
|
|
50
|
+
* would deny. Exists only to confirm, before enforcing, that no legitimate
|
|
51
|
+
* caller reads a credential without a service principal.
|
|
52
|
+
* - `off` — no-op.
|
|
53
|
+
*
|
|
54
|
+
* @module middleware/credential-field-guard
|
|
55
|
+
*/
|
|
56
|
+
import type { MiddlewareFn } from 'type-graphql';
|
|
57
|
+
import { GraphQLError, type GraphQLResolveInfo } from 'graphql';
|
|
58
|
+
import { Counter } from 'prom-client';
|
|
59
|
+
import { CREDENTIAL_FIELDS } from '../auth/credential-fields';
|
|
60
|
+
import type { BackendPrincipal } from '../auth/token-verifier';
|
|
61
|
+
/**
|
|
62
|
+
* The stored credential columns this guard serves to a service principal
|
|
63
|
+
* only. Defined in `auth/credential-fields`, re-exported for existing callers.
|
|
64
|
+
*/
|
|
65
|
+
export { CREDENTIAL_FIELDS };
|
|
66
|
+
/** The guard's operating mode. See the module doc. */
|
|
67
|
+
export type CredentialFieldGuardMode = 'enforce' | 'shadow' | 'off';
|
|
68
|
+
/**
|
|
69
|
+
* The credential fields an input type's keys can reference as a predicate,
|
|
70
|
+
* or `undefined` when it is not a credential model's predicate type.
|
|
71
|
+
*
|
|
72
|
+
* @internal Exported for the schema-coverage test, which walks every input
|
|
73
|
+
* type in the served schema and fails if a credential column appears in a
|
|
74
|
+
* predicate type this function does not claim.
|
|
75
|
+
*/
|
|
76
|
+
export declare function credentialPredicateFieldsFor(typeName: string): ReadonlySet<string> | undefined;
|
|
77
|
+
/**
|
|
78
|
+
* The credential fields an output type exposes as values, or `undefined`.
|
|
79
|
+
*
|
|
80
|
+
* @internal Exported for the schema-coverage test (see above).
|
|
81
|
+
*/
|
|
82
|
+
export declare function credentialOutputFieldsFor(typeName: string): ReadonlySet<string> | undefined;
|
|
83
|
+
/**
|
|
84
|
+
* The credential values a `<Model>ScalarFieldEnum` can name, or `undefined`.
|
|
85
|
+
*
|
|
86
|
+
* @internal Exported for the schema-coverage test (see above).
|
|
87
|
+
*/
|
|
88
|
+
export declare function credentialEnumValuesFor(typeName: string): ReadonlySet<string> | undefined;
|
|
89
|
+
/**
|
|
90
|
+
* Every guarded column an argument names, as `TypeName.field` strings, split
|
|
91
|
+
* by the rule that governs it.
|
|
92
|
+
*/
|
|
93
|
+
export interface GuardedArgumentReferences {
|
|
94
|
+
/** Stored credential columns: predicates admitted for a service principal only. */
|
|
95
|
+
credential: string[];
|
|
96
|
+
/** Audit payload columns: predicates admitted for the raw-read principals only. */
|
|
97
|
+
auditPayload: string[];
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Every guarded column a field's arguments name. Both lists are empty when
|
|
101
|
+
* the field takes no arguments or names no guarded column.
|
|
102
|
+
*/
|
|
103
|
+
export declare function findGuardedArgumentReferences(info: Pick<GraphQLResolveInfo, 'parentType' | 'fieldName'>, args: Record<string, unknown>): GuardedArgumentReferences;
|
|
104
|
+
/**
|
|
105
|
+
* Every credential reference in a field's arguments, as `TypeName.field`
|
|
106
|
+
* strings. Empty when the field takes no arguments or names no credential.
|
|
107
|
+
*/
|
|
108
|
+
export declare function findCredentialArgumentReferences(info: Pick<GraphQLResolveInfo, 'parentType' | 'fieldName'>, args: Record<string, unknown>): string[];
|
|
109
|
+
/** The credential field this resolver outputs, as `TypeName.field`, if any. */
|
|
110
|
+
export declare function findCredentialOutputField(info: Pick<GraphQLResolveInfo, 'parentType' | 'fieldName'>): string | undefined;
|
|
111
|
+
/**
|
|
112
|
+
* Resolve the guard mode from `CREDENTIAL_FIELD_GUARD_MODE`. Anything other
|
|
113
|
+
* than an explicit `shadow` or `off` enforces.
|
|
114
|
+
*/
|
|
115
|
+
export declare function getCredentialFieldGuardMode(): CredentialFieldGuardMode;
|
|
116
|
+
/**
|
|
117
|
+
* Credential-surface accesses by surface, decision and principal kind. The
|
|
118
|
+
* `would_deny` series in `shadow` is the list of callers that enforcement
|
|
119
|
+
* would break; it must be empty of legitimate callers before enforcing.
|
|
120
|
+
*/
|
|
121
|
+
export declare const credentialFieldAccessTotal: Counter<"decision" | "surface" | "principal_kind">;
|
|
122
|
+
/**
|
|
123
|
+
* Audit payload accesses by principals that read payloads redacted (user and
|
|
124
|
+
* anonymous). Reads (`output`) are counted by what redaction did to them;
|
|
125
|
+
* predicates (`argument`) by whether they were refused. In `shadow`,
|
|
126
|
+
* `would_redact` with `carried_value="true"` counts reads that served a stored
|
|
127
|
+
* credential value — the exposure enforcement closes.
|
|
128
|
+
*/
|
|
129
|
+
export declare const auditPayloadAccessTotal: Counter<"decision" | "surface" | "principal_kind" | "carried_value">;
|
|
130
|
+
/** The slice of the Express request the guard reads for its log line. */
|
|
131
|
+
interface GuardRequest {
|
|
132
|
+
ip?: string;
|
|
133
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
134
|
+
}
|
|
135
|
+
/** GraphQL context shape the guard reads. */
|
|
136
|
+
export interface CredentialFieldGuardContext {
|
|
137
|
+
principal?: BackendPrincipal | null;
|
|
138
|
+
req?: GuardRequest;
|
|
139
|
+
}
|
|
140
|
+
/** Options for {@link createCredentialFieldGuardMiddleware}, for tests. */
|
|
141
|
+
export interface CredentialFieldGuardOptions {
|
|
142
|
+
/** Override the mode resolver (defaults to the environment). */
|
|
143
|
+
modeProvider?: () => CredentialFieldGuardMode;
|
|
144
|
+
/** Clock for the log throttle. */
|
|
145
|
+
now?: () => number;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* What a refused credential reader should do next. The refusal is a
|
|
149
|
+
* deliberate, recorded control rather than a fault, and the text says so:
|
|
150
|
+
* callers who read it as an outage will otherwise ask for the guard to be
|
|
151
|
+
* relaxed instead of presenting a service identity.
|
|
152
|
+
*/
|
|
153
|
+
export declare const CREDENTIAL_READ_REMEDY: string;
|
|
154
|
+
/**
|
|
155
|
+
* The refusal for a credential column reached by a non-service principal.
|
|
156
|
+
* Exported for the mutation authorization guard, which applies the predicate
|
|
157
|
+
* rule itself, ahead of this middleware (see `mutation-auth-guard`).
|
|
158
|
+
*/
|
|
159
|
+
export declare function credentialAccessForbidden(references: string[]): GraphQLError;
|
|
160
|
+
/**
|
|
161
|
+
* Create the TypeGraphQL global middleware that guards credential columns.
|
|
162
|
+
*
|
|
163
|
+
* Runs on every field. The hot path — a non-credential field with no
|
|
164
|
+
* arguments, or any field for a service principal — returns after a map
|
|
165
|
+
* lookup.
|
|
166
|
+
*
|
|
167
|
+
* @param options - Optional overrides for tests.
|
|
168
|
+
* @returns A {@link MiddlewareFn} for `buildSchema({ globalMiddlewares })`.
|
|
169
|
+
*/
|
|
170
|
+
export declare function createCredentialFieldGuardMiddleware(options?: CredentialFieldGuardOptions): MiddlewareFn<CredentialFieldGuardContext>;
|
|
171
|
+
/** @internal Test hook: forget the log throttle state. */
|
|
172
|
+
export declare function resetCredentialFieldGuardLogThrottle(): void;
|
|
173
|
+
//# sourceMappingURL=credential-field-guard.d.ts.map
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Where the generated GraphQL schema exposes a Prisma model's columns, by
|
|
4
|
+
* type-name convention.
|
|
5
|
+
*
|
|
6
|
+
* typegraphql-prisma names every type after its model, so a guard that must
|
|
7
|
+
* cover "every way a query can observe column X of model M" can derive the
|
|
8
|
+
* whole surface from the model name: the output types that carry column
|
|
9
|
+
* VALUES, the input types that act as predicates over them, and the scalar
|
|
10
|
+
* enum that names them in `by` / `distinct`. The rules live here, once, so
|
|
11
|
+
* each guard that keys on a set of columns applies the same naming rules.
|
|
12
|
+
*
|
|
13
|
+
* @module middleware/generated-type-names
|
|
14
|
+
*/
|
|
15
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
16
|
+
exports.VALUE_OUTPUT_PREFIXES = exports.VALUE_OUTPUT_SUFFIXES = void 0;
|
|
17
|
+
exports.indexGeneratedTypes = indexGeneratedTypes;
|
|
18
|
+
/**
|
|
19
|
+
* Output types that carry a model's column VALUES, as name suffixes on the
|
|
20
|
+
* model. The `Count` aggregate is absent on purpose: it returns how many rows
|
|
21
|
+
* are non-null, never a value.
|
|
22
|
+
*/
|
|
23
|
+
exports.VALUE_OUTPUT_SUFFIXES = ['', 'GroupBy', 'MinAggregate', 'MaxAggregate'];
|
|
24
|
+
/**
|
|
25
|
+
* Output types that carry a model's column VALUES, as name prefixes on the
|
|
26
|
+
* model. `createManyAndReturn<Model>` / `updateManyAndReturn<Model>` return
|
|
27
|
+
* the written rows as their own generated type rather than as `<Model>`, so a
|
|
28
|
+
* guard keyed only on the model type would serve the guarded columns of every
|
|
29
|
+
* row such a mutation touches — including columns the caller did not write.
|
|
30
|
+
*/
|
|
31
|
+
exports.VALUE_OUTPUT_PREFIXES = ['CreateManyAndReturn', 'UpdateManyAndReturn'];
|
|
32
|
+
/**
|
|
33
|
+
* Input-type name fragments that make a type a read predicate (filter, sort,
|
|
34
|
+
* cursor, aggregate filter) rather than a write payload. A `…WhereUniqueInput`
|
|
35
|
+
* is also how a mutation selects its row, so a guarded key there is an oracle
|
|
36
|
+
* on a write path too.
|
|
37
|
+
*/
|
|
38
|
+
const PREDICATE_TYPE_FRAGMENTS = ['Where', 'OrderBy', 'Having'];
|
|
39
|
+
const SCALAR_FIELD_ENUM_SUFFIX = 'ScalarFieldEnum';
|
|
40
|
+
/**
|
|
41
|
+
* Index the generated types of every model in `fieldsByModel`.
|
|
42
|
+
*
|
|
43
|
+
* @param fieldsByModel - Guarded column names, by Prisma model name.
|
|
44
|
+
* @returns Lookups over the generated type names.
|
|
45
|
+
*/
|
|
46
|
+
function indexGeneratedTypes(fieldsByModel) {
|
|
47
|
+
const outputs = new Map([...fieldsByModel].flatMap(([model, fields]) => [
|
|
48
|
+
...exports.VALUE_OUTPUT_SUFFIXES.map((suffix) => [`${model}${suffix}`, fields]),
|
|
49
|
+
...exports.VALUE_OUTPUT_PREFIXES.map((prefix) => [`${prefix}${model}`, fields]),
|
|
50
|
+
]));
|
|
51
|
+
// Longest-first, so the prefix match attributes
|
|
52
|
+
// `AccountLinkingRequestWhereInput` to `AccountLinkingRequest`, not `Account`.
|
|
53
|
+
const modelsLongestFirst = [...fieldsByModel.keys()].sort((a, b) => b.length - a.length);
|
|
54
|
+
return {
|
|
55
|
+
outputFields: (typeName) => outputs.get(typeName),
|
|
56
|
+
// Generated names start with the model name followed by an upper-case
|
|
57
|
+
// letter (`AlpacaAccountWhereInput`), so a model named `Account` does not
|
|
58
|
+
// claim `AccountLinkingRequestWhereInput`.
|
|
59
|
+
predicateFields: (typeName) => {
|
|
60
|
+
for (const model of modelsLongestFirst) {
|
|
61
|
+
if (!typeName.startsWith(model))
|
|
62
|
+
continue;
|
|
63
|
+
const rest = typeName.slice(model.length);
|
|
64
|
+
if (!/^[A-Z]/.test(rest))
|
|
65
|
+
continue;
|
|
66
|
+
if (!PREDICATE_TYPE_FRAGMENTS.some((f) => rest.includes(f)))
|
|
67
|
+
return undefined;
|
|
68
|
+
return fieldsByModel.get(model);
|
|
69
|
+
}
|
|
70
|
+
return undefined;
|
|
71
|
+
},
|
|
72
|
+
enumFields: (typeName) => typeName.endsWith(SCALAR_FIELD_ENUM_SUFFIX)
|
|
73
|
+
? fieldsByModel.get(typeName.slice(0, -SCALAR_FIELD_ENUM_SUFFIX.length))
|
|
74
|
+
: undefined,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
//# sourceMappingURL=generated-type-names.js.map
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the generated GraphQL schema exposes a Prisma model's columns, by
|
|
3
|
+
* type-name convention.
|
|
4
|
+
*
|
|
5
|
+
* typegraphql-prisma names every type after its model, so a guard that must
|
|
6
|
+
* cover "every way a query can observe column X of model M" can derive the
|
|
7
|
+
* whole surface from the model name: the output types that carry column
|
|
8
|
+
* VALUES, the input types that act as predicates over them, and the scalar
|
|
9
|
+
* enum that names them in `by` / `distinct`. The rules live here, once, so
|
|
10
|
+
* each guard that keys on a set of columns applies the same naming rules.
|
|
11
|
+
*
|
|
12
|
+
* @module middleware/generated-type-names
|
|
13
|
+
*/
|
|
14
|
+
/**
|
|
15
|
+
* Output types that carry a model's column VALUES, as name suffixes on the
|
|
16
|
+
* model. The `Count` aggregate is absent on purpose: it returns how many rows
|
|
17
|
+
* are non-null, never a value.
|
|
18
|
+
*/
|
|
19
|
+
export declare const VALUE_OUTPUT_SUFFIXES: readonly ["", "GroupBy", "MinAggregate", "MaxAggregate"];
|
|
20
|
+
/**
|
|
21
|
+
* Output types that carry a model's column VALUES, as name prefixes on the
|
|
22
|
+
* model. `createManyAndReturn<Model>` / `updateManyAndReturn<Model>` return
|
|
23
|
+
* the written rows as their own generated type rather than as `<Model>`, so a
|
|
24
|
+
* guard keyed only on the model type would serve the guarded columns of every
|
|
25
|
+
* row such a mutation touches — including columns the caller did not write.
|
|
26
|
+
*/
|
|
27
|
+
export declare const VALUE_OUTPUT_PREFIXES: readonly ["CreateManyAndReturn", "UpdateManyAndReturn"];
|
|
28
|
+
/** Lookups from a generated type name to the guarded columns it exposes. */
|
|
29
|
+
export interface GeneratedTypeIndex {
|
|
30
|
+
/** Guarded columns an output type carries as values, if any. */
|
|
31
|
+
outputFields(typeName: string): ReadonlySet<string> | undefined;
|
|
32
|
+
/** Guarded columns an input type's keys can reference as a predicate, if any. */
|
|
33
|
+
predicateFields(typeName: string): ReadonlySet<string> | undefined;
|
|
34
|
+
/** Guarded columns a `<Model>ScalarFieldEnum` can name, if it is one. */
|
|
35
|
+
enumFields(typeName: string): ReadonlySet<string> | undefined;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Index the generated types of every model in `fieldsByModel`.
|
|
39
|
+
*
|
|
40
|
+
* @param fieldsByModel - Guarded column names, by Prisma model name.
|
|
41
|
+
* @returns Lookups over the generated type names.
|
|
42
|
+
*/
|
|
43
|
+
export declare function indexGeneratedTypes(fieldsByModel: ReadonlyMap<string, ReadonlySet<string>>): GeneratedTypeIndex;
|
|
44
|
+
//# sourceMappingURL=generated-type-names.d.ts.map
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.VALIDATION_RULES = exports.POSITIVE_NUMBER_FIELDS = exports.REQUIRED_NON_EMPTY_STRING_FIELDS = exports.BOUNDED_PERCENTAGE_FIELDS = exports.VALIDATION_MODE_ENV_VAR = void 0;
|
|
4
|
+
exports.resolveValidationMode = resolveValidationMode;
|
|
5
|
+
exports.createValidationPlugin = createValidationPlugin;
|
|
6
|
+
const graphql_1 = require("graphql");
|
|
7
|
+
const input_validator_1 = require("./input-validator.cjs");
|
|
8
|
+
const logger_1 = require("../utils/logger.cjs");
|
|
9
|
+
/**
|
|
10
|
+
* Environment variable controlling the plugin mode. Accepted values:
|
|
11
|
+
* `scoped` | `legacy` | `off`. Unset or unrecognized values resolve to
|
|
12
|
+
* `scoped`.
|
|
13
|
+
*/
|
|
14
|
+
exports.VALIDATION_MODE_ENV_VAR = 'GRAPHQL_VALIDATION_MODE';
|
|
15
|
+
/**
|
|
16
|
+
* Resolves the active validation mode from the environment.
|
|
17
|
+
*
|
|
18
|
+
* @returns The configured {@link ValidationMode}, defaulting to `scoped`.
|
|
19
|
+
*/
|
|
20
|
+
function resolveValidationMode() {
|
|
21
|
+
var _a;
|
|
22
|
+
const raw = (_a = process.env[exports.VALIDATION_MODE_ENV_VAR]) === null || _a === void 0 ? void 0 : _a.trim().toLowerCase();
|
|
23
|
+
if (raw === 'legacy' || raw === 'off' || raw === 'scoped') {
|
|
24
|
+
return raw;
|
|
25
|
+
}
|
|
26
|
+
if (raw !== undefined && raw !== '') {
|
|
27
|
+
logger_1.logger.warn(`Unrecognized ${exports.VALIDATION_MODE_ENV_VAR} value; defaulting to 'scoped'`, { value: raw });
|
|
28
|
+
}
|
|
29
|
+
return 'scoped';
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Exact schema field names whose domain is genuinely a bounded share-of-a-whole
|
|
33
|
+
* percentage in `[0, 100]`.
|
|
34
|
+
*
|
|
35
|
+
* This is intentionally an explicit allowlist rather than a `/.*Pct$/` name
|
|
36
|
+
* pattern: many `*Pct` / `*Percent` fields in the Prisma schema are NOT
|
|
37
|
+
* bounded percentages — `maxGrossExposurePct` / `maxNetExposurePct` are
|
|
38
|
+
* leverage-denominated (200 = 2x gross is a legitimate production value) and
|
|
39
|
+
* PnL/return/drawdown fields (`dailyPnlPct`, `netReturnPct`, `changePercent`,
|
|
40
|
+
* `peakToTroughPct`, …) are signed. A blanket 0-100 rule on the name pattern
|
|
41
|
+
* rejected 100% of AccountDecisionRecord writes embedding a leverage policy
|
|
42
|
+
* snapshot (TM-01, 2026-07-01).
|
|
43
|
+
*/
|
|
44
|
+
exports.BOUNDED_PERCENTAGE_FIELDS = new Set([
|
|
45
|
+
'maxBuyingPowerUtilPct',
|
|
46
|
+
'cashFloorPct',
|
|
47
|
+
'maxSymbolConcentrationPct',
|
|
48
|
+
'maxSectorConcentrationPct',
|
|
49
|
+
'perTradeEquityAllocationPct',
|
|
50
|
+
'perTradeCryptoAllocationPct',
|
|
51
|
+
'cryptoTradeAllocationPct',
|
|
52
|
+
'tradeAllocationPct',
|
|
53
|
+
'trafficSplitControlPercent',
|
|
54
|
+
'trafficSplitTreatmentPercent',
|
|
55
|
+
]);
|
|
56
|
+
/**
|
|
57
|
+
* Lower-cased field names that must be non-empty strings when present as
|
|
58
|
+
* top-level scalar inputs.
|
|
59
|
+
*/
|
|
60
|
+
exports.REQUIRED_NON_EMPTY_STRING_FIELDS = new Set([
|
|
61
|
+
'name',
|
|
62
|
+
'title',
|
|
63
|
+
'description',
|
|
64
|
+
'symbol',
|
|
65
|
+
'type',
|
|
66
|
+
'status',
|
|
67
|
+
]);
|
|
68
|
+
/**
|
|
69
|
+
* Lower-cased field names that must be strictly positive numbers when present
|
|
70
|
+
* as top-level scalar inputs. Note: `*Threshold` fields are deliberately NOT
|
|
71
|
+
* validated — thresholds are legitimately signed (e.g. reversal-blackout and
|
|
72
|
+
* drawdown-breach thresholds are negative).
|
|
73
|
+
*/
|
|
74
|
+
exports.POSITIVE_NUMBER_FIELDS = new Set([
|
|
75
|
+
'quantity',
|
|
76
|
+
]);
|
|
77
|
+
/**
|
|
78
|
+
* Legacy name-pattern validation rules. Preserved verbatim for the `legacy`
|
|
79
|
+
* rollback mode; the default `scoped` mode does NOT use these (the `.*Pct$`,
|
|
80
|
+
* `.*Percent$`, and `.*Threshold$` heuristics reject legitimate leverage-
|
|
81
|
+
* denominated and signed values).
|
|
82
|
+
*/
|
|
83
|
+
const VALIDATION_RULES = [
|
|
84
|
+
// Percentage fields (0-100)
|
|
85
|
+
{
|
|
86
|
+
pattern: /.*Pct$/i,
|
|
87
|
+
validator: (value, fieldName) => {
|
|
88
|
+
if (typeof value === 'number') {
|
|
89
|
+
(0, input_validator_1.validatePercentage)(value, fieldName);
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
description: 'Percentage fields ending with Pct',
|
|
93
|
+
},
|
|
94
|
+
{
|
|
95
|
+
pattern: /.*Percent(age)?$/i,
|
|
96
|
+
validator: (value, fieldName) => {
|
|
97
|
+
if (typeof value === 'number') {
|
|
98
|
+
(0, input_validator_1.validatePercentage)(value, fieldName);
|
|
99
|
+
}
|
|
100
|
+
},
|
|
101
|
+
description: 'Percentage fields ending with Percent or Percentage',
|
|
102
|
+
},
|
|
103
|
+
// Quantity fields (must be positive)
|
|
104
|
+
{
|
|
105
|
+
pattern: /^quantity$/i,
|
|
106
|
+
validator: (value, fieldName) => {
|
|
107
|
+
if (typeof value === 'number') {
|
|
108
|
+
(0, input_validator_1.validatePositiveNumber)(value, fieldName);
|
|
109
|
+
}
|
|
110
|
+
},
|
|
111
|
+
description: 'Quantity fields',
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
pattern: /.*Threshold$/i,
|
|
115
|
+
validator: (value, fieldName) => {
|
|
116
|
+
if (typeof value === 'number' && value !== 0) {
|
|
117
|
+
(0, input_validator_1.validatePositiveNumber)(value, fieldName);
|
|
118
|
+
}
|
|
119
|
+
},
|
|
120
|
+
description: 'Threshold fields',
|
|
121
|
+
},
|
|
122
|
+
{
|
|
123
|
+
pattern: /^count$/i,
|
|
124
|
+
validator: (value, fieldName) => {
|
|
125
|
+
if (typeof value === 'number') {
|
|
126
|
+
(0, input_validator_1.validatePositiveNumber)(value, fieldName);
|
|
127
|
+
}
|
|
128
|
+
},
|
|
129
|
+
description: 'Count fields',
|
|
130
|
+
},
|
|
131
|
+
// Required string fields (non-empty)
|
|
132
|
+
{
|
|
133
|
+
pattern: /^(name|title|description|symbol|type|status)$/i,
|
|
134
|
+
validator: (value, fieldName) => {
|
|
135
|
+
if (typeof value === 'string') {
|
|
136
|
+
(0, input_validator_1.validateNonEmpty)(value, fieldName);
|
|
137
|
+
}
|
|
138
|
+
},
|
|
139
|
+
description: 'Common required string fields',
|
|
140
|
+
},
|
|
141
|
+
];
|
|
142
|
+
exports.VALIDATION_RULES = VALIDATION_RULES;
|
|
143
|
+
/**
|
|
144
|
+
* Returns true when the value is a plain (non-array) object.
|
|
145
|
+
*/
|
|
146
|
+
function isPlainObject(value) {
|
|
147
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Collects a validator's {@link ValidationError} field details into `errors`.
|
|
151
|
+
*/
|
|
152
|
+
function collectValidation(errors, validate) {
|
|
153
|
+
try {
|
|
154
|
+
validate();
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
if (error instanceof input_validator_1.ValidationError) {
|
|
158
|
+
errors.push(...error.fields);
|
|
159
|
+
}
|
|
160
|
+
else {
|
|
161
|
+
throw error;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Validates ONLY the top-level scalar fields of a mutation input object
|
|
167
|
+
* (scoped mode). Prisma atomic update wrappers of the shape
|
|
168
|
+
* `{ set: <scalar> }` are unwrapped one level so `updateOne*` inputs receive
|
|
169
|
+
* the same scrutiny as `createOne*` inputs. All other nested objects and all
|
|
170
|
+
* arrays are out of scope by design: they are relation inputs or opaque
|
|
171
|
+
* Json-typed columns whose contents are validated by Prisma / the producing
|
|
172
|
+
* service, and name-pattern rules applied inside them reject legitimate data.
|
|
173
|
+
*/
|
|
174
|
+
function validateTopLevelFields(obj, path) {
|
|
175
|
+
const errors = [];
|
|
176
|
+
for (const [key, rawValue] of Object.entries(obj)) {
|
|
177
|
+
if (rawValue === null || rawValue === undefined) {
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
let value = rawValue;
|
|
181
|
+
if (isPlainObject(rawValue)) {
|
|
182
|
+
const keys = Object.keys(rawValue);
|
|
183
|
+
const isAtomicSetWrapper = keys.length === 1 &&
|
|
184
|
+
keys[0] === 'set' &&
|
|
185
|
+
!isPlainObject(rawValue.set) &&
|
|
186
|
+
!Array.isArray(rawValue.set);
|
|
187
|
+
if (!isAtomicSetWrapper) {
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
value = rawValue.set;
|
|
191
|
+
if (value === null || value === undefined) {
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
if (Array.isArray(value)) {
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
const fieldPath = path ? `${path}.${key}` : key;
|
|
199
|
+
const lowerKey = key.toLowerCase();
|
|
200
|
+
if (exports.BOUNDED_PERCENTAGE_FIELDS.has(key) && typeof value === 'number') {
|
|
201
|
+
collectValidation(errors, () => (0, input_validator_1.validatePercentage)(value, fieldPath));
|
|
202
|
+
}
|
|
203
|
+
else if (exports.POSITIVE_NUMBER_FIELDS.has(lowerKey) &&
|
|
204
|
+
typeof value === 'number') {
|
|
205
|
+
collectValidation(errors, () => (0, input_validator_1.validatePositiveNumber)(value, fieldPath));
|
|
206
|
+
}
|
|
207
|
+
else if (exports.REQUIRED_NON_EMPTY_STRING_FIELDS.has(lowerKey) &&
|
|
208
|
+
typeof value === 'string') {
|
|
209
|
+
collectValidation(errors, () => (0, input_validator_1.validateNonEmpty)(value, fieldPath));
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return errors;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Recursively validates an object's fields based on the legacy name-pattern
|
|
216
|
+
* rules (legacy mode only).
|
|
217
|
+
*/
|
|
218
|
+
function validateObject(obj, path = '') {
|
|
219
|
+
const errors = [];
|
|
220
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
221
|
+
const fieldPath = path ? `${path}.${key}` : key;
|
|
222
|
+
// Skip null or undefined values
|
|
223
|
+
if (value === null || value === undefined) {
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
// Recursively validate nested objects
|
|
227
|
+
if (typeof value === 'object' && !Array.isArray(value)) {
|
|
228
|
+
const nestedErrors = validateObject(value, fieldPath);
|
|
229
|
+
errors.push(...nestedErrors);
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
// Apply validation rules to the field
|
|
233
|
+
for (const rule of VALIDATION_RULES) {
|
|
234
|
+
if (rule.pattern.test(key)) {
|
|
235
|
+
collectValidation(errors, () => rule.validator(value, fieldPath));
|
|
236
|
+
break; // Only apply the first matching rule
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return errors;
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Apollo Server plugin that validates GraphQL mutation inputs before they
|
|
244
|
+
* reach the resolver.
|
|
245
|
+
*
|
|
246
|
+
* The active {@link ValidationMode} is resolved from the
|
|
247
|
+
* `GRAPHQL_VALIDATION_MODE` environment variable at request time (defaulting
|
|
248
|
+
* to `scoped`) unless an explicit `modeOverride` is supplied.
|
|
249
|
+
*
|
|
250
|
+
* @param modeOverride - Optional fixed mode, primarily for tests; when
|
|
251
|
+
* omitted the mode is re-resolved from the environment on each request so
|
|
252
|
+
* the toggle can be flipped without code changes.
|
|
253
|
+
*
|
|
254
|
+
* @example
|
|
255
|
+
* ```typescript
|
|
256
|
+
* const server = new ApolloServer({
|
|
257
|
+
* schema,
|
|
258
|
+
* plugins: [
|
|
259
|
+
* ApolloServerPluginDrainHttpServer({ httpServer }),
|
|
260
|
+
* createValidationPlugin(),
|
|
261
|
+
* ],
|
|
262
|
+
* });
|
|
263
|
+
* ```
|
|
264
|
+
*/
|
|
265
|
+
function createValidationPlugin(modeOverride) {
|
|
266
|
+
return {
|
|
267
|
+
async requestDidStart() {
|
|
268
|
+
return {
|
|
269
|
+
async didResolveOperation(requestContext) {
|
|
270
|
+
const mode = modeOverride !== null && modeOverride !== void 0 ? modeOverride : resolveValidationMode();
|
|
271
|
+
if (mode === 'off') {
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
const { operation, request } = requestContext;
|
|
275
|
+
// Only validate mutations
|
|
276
|
+
if (!operation || operation.operation !== 'mutation') {
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
const variables = request.variables || {};
|
|
280
|
+
const errors = [];
|
|
281
|
+
const validateFn = mode === 'legacy' ? validateObject : validateTopLevelFields;
|
|
282
|
+
// Validate each mutation's variables
|
|
283
|
+
for (const [variableName, variableValue] of Object.entries(variables)) {
|
|
284
|
+
if (variableValue && typeof variableValue === 'object') {
|
|
285
|
+
// Check if this is a data object (common pattern in mutations)
|
|
286
|
+
const dataObj = variableValue;
|
|
287
|
+
if ('data' in dataObj && typeof dataObj.data === 'object') {
|
|
288
|
+
errors.push(...validateFn(dataObj.data, variableName));
|
|
289
|
+
}
|
|
290
|
+
else {
|
|
291
|
+
errors.push(...validateFn(dataObj, variableName));
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
// If there are validation errors, throw before resolver execution
|
|
296
|
+
if (errors.length > 0) {
|
|
297
|
+
const fieldList = errors.map((e) => e.field).join(', ');
|
|
298
|
+
throw new graphql_1.GraphQLError(`Input validation failed for ${errors.length} field${errors.length > 1 ? 's' : ''}: ${fieldList}`, {
|
|
299
|
+
extensions: {
|
|
300
|
+
code: 'BAD_USER_INPUT',
|
|
301
|
+
validationErrors: errors,
|
|
302
|
+
},
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
},
|
|
306
|
+
};
|
|
307
|
+
},
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
//# sourceMappingURL=graphql-validation-plugin.js.map
|