@adaptic/backend 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.
- package/esm/auth/credential-fields.d.ts +19 -0
- package/esm/auth/credential-fields.d.ts.map +1 -0
- package/esm/auth/credential-fields.js.map +1 -0
- package/esm/auth/credential-fields.mjs +42 -0
- package/esm/auth/credential-redaction.d.ts +56 -0
- package/esm/auth/credential-redaction.d.ts.map +1 -0
- package/esm/auth/credential-redaction.js.map +1 -0
- package/esm/auth/credential-redaction.mjs +99 -0
- package/esm/auth/mutation-authorization.d.ts +206 -0
- package/esm/auth/mutation-authorization.d.ts.map +1 -0
- package/esm/auth/mutation-authorization.js.map +1 -0
- package/esm/auth/mutation-authorization.mjs +271 -0
- package/esm/auth/nested-write-inspector.d.ts +94 -0
- package/esm/auth/nested-write-inspector.d.ts.map +1 -0
- package/esm/auth/nested-write-inspector.js.map +1 -0
- package/esm/auth/nested-write-inspector.mjs +185 -0
- package/esm/auth/nested-write-policy.d.ts +95 -0
- package/esm/auth/nested-write-policy.d.ts.map +1 -0
- package/esm/auth/nested-write-policy.js.map +1 -0
- package/esm/auth/nested-write-policy.mjs +154 -0
- package/esm/auth/service-token.d.ts +11 -1
- package/esm/auth/service-token.d.ts.map +1 -1
- package/esm/auth/service-token.js.map +1 -1
- package/esm/auth/service-token.mjs +31 -5
- package/esm/auth/token-verifier.d.ts +9 -1
- package/esm/auth/token-verifier.d.ts.map +1 -1
- package/esm/auth/token-verifier.js.map +1 -1
- package/esm/auth/user-write-content.d.ts +41 -0
- package/esm/auth/user-write-content.d.ts.map +1 -0
- package/esm/auth/user-write-content.js.map +1 -0
- package/esm/auth/user-write-content.mjs +100 -0
- package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts +55 -0
- package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts.map +1 -0
- package/esm/middleware/__tests__/credential-field-coverage.harness.js.map +1 -0
- package/esm/middleware/__tests__/credential-field-coverage.harness.mjs +438 -0
- package/esm/middleware/__tests__/credential-field-guard.harness.d.ts +34 -0
- package/esm/middleware/__tests__/credential-field-guard.harness.d.ts.map +1 -0
- package/esm/middleware/__tests__/credential-field-guard.harness.js.map +1 -0
- package/esm/middleware/__tests__/credential-field-guard.harness.mjs +212 -0
- package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +49 -0
- package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts.map +1 -0
- package/esm/middleware/__tests__/mutation-auth-guard.harness.js.map +1 -0
- package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +402 -0
- package/esm/middleware/__tests__/ts-node-harness.d.ts +10 -0
- package/esm/middleware/__tests__/ts-node-harness.d.ts.map +1 -0
- package/esm/middleware/__tests__/ts-node-harness.js.map +1 -0
- package/esm/middleware/__tests__/ts-node-harness.mjs +71 -0
- package/esm/middleware/audit-logger.d.ts +18 -1
- package/esm/middleware/audit-logger.d.ts.map +1 -1
- package/esm/middleware/audit-logger.js.map +1 -1
- package/esm/middleware/audit-logger.mjs +36 -13
- package/esm/middleware/audit-payload-guard.d.ts +85 -0
- package/esm/middleware/audit-payload-guard.d.ts.map +1 -0
- package/esm/middleware/audit-payload-guard.js.map +1 -0
- package/esm/middleware/audit-payload-guard.mjs +97 -0
- package/esm/middleware/credential-field-guard.d.ts +160 -0
- package/esm/middleware/credential-field-guard.d.ts.map +1 -0
- package/esm/middleware/credential-field-guard.js.map +1 -0
- package/esm/middleware/credential-field-guard.mjs +479 -0
- package/esm/middleware/generated-type-names.d.ts +44 -0
- package/esm/middleware/generated-type-names.d.ts.map +1 -0
- package/esm/middleware/generated-type-names.js.map +1 -0
- package/esm/middleware/generated-type-names.mjs +73 -0
- package/esm/middleware/guard-log-throttle.d.ts +80 -0
- package/esm/middleware/guard-log-throttle.d.ts.map +1 -0
- package/esm/middleware/guard-log-throttle.js.map +1 -0
- package/esm/middleware/guard-log-throttle.mjs +87 -0
- package/esm/middleware/mutation-account-facts.d.ts +140 -0
- package/esm/middleware/mutation-account-facts.d.ts.map +1 -0
- package/esm/middleware/mutation-account-facts.js.map +1 -0
- package/esm/middleware/mutation-account-facts.mjs +212 -0
- package/esm/middleware/mutation-auth-guard.d.ts +82 -0
- package/esm/middleware/mutation-auth-guard.d.ts.map +1 -0
- package/esm/middleware/mutation-auth-guard.js.map +1 -0
- package/esm/middleware/mutation-auth-guard.mjs +425 -0
- package/esm/middleware/mutation-tenant-facts.d.ts +58 -0
- package/esm/middleware/mutation-tenant-facts.d.ts.map +1 -0
- package/esm/middleware/mutation-tenant-facts.js.map +1 -0
- package/esm/middleware/mutation-tenant-facts.mjs +75 -0
- package/esm/middleware/trading-policy-audit.d.ts +172 -0
- package/esm/middleware/trading-policy-audit.d.ts.map +1 -0
- package/esm/middleware/trading-policy-audit.js.map +1 -0
- package/esm/middleware/trading-policy-audit.mjs +309 -0
- package/esm/resolvers/custom/BrokerageAccountCredentialStatusResolver.d.ts +22 -0
- package/esm/resolvers/custom/BrokerageAccountCredentialStatusResolver.d.ts.map +1 -0
- package/esm/resolvers/custom/BrokerageAccountCredentialStatusResolver.js.map +1 -0
- package/esm/resolvers/custom/BrokerageAccountCredentialStatusResolver.mjs +63 -0
- package/esm/resolvers/custom/index.d.ts +1 -0
- package/esm/resolvers/custom/index.d.ts.map +1 -1
- package/esm/resolvers/custom/index.js.map +1 -1
- package/esm/resolvers/custom/index.mjs +1 -0
- package/package.json +1 -1
- package/resolvers/custom/BrokerageAccountCredentialStatusResolver.cjs +100 -0
- package/resolvers/custom/BrokerageAccountCredentialStatusResolver.d.ts +22 -0
- package/resolvers/custom/BrokerageAccountCredentialStatusResolver.d.ts.map +1 -0
- package/resolvers/custom/BrokerageAccountCredentialStatusResolver.js.map +1 -0
- package/resolvers/custom/index.cjs +4 -1
- package/resolvers/custom/index.d.ts +1 -0
- package/resolvers/custom/index.d.ts.map +1 -1
- package/resolvers/custom/index.js.map +1 -1
- package/server.cjs +40 -3
|
@@ -0,0 +1,479 @@
|
|
|
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 { GraphQLEnumType, GraphQLError, GraphQLInputObjectType, GraphQLList, getNullableType, } from 'graphql';
|
|
57
|
+
import { Counter } from 'prom-client';
|
|
58
|
+
import { CREDENTIAL_FIELDS } from '../auth/credential-fields.mjs';
|
|
59
|
+
import { metricsRegistry } from '../config/metrics.mjs';
|
|
60
|
+
import { logger } from '../utils/logger.mjs';
|
|
61
|
+
import { auditPayloadOutputField, auditPayloadEnumFieldsFor, auditPayloadPredicateFieldsFor, readsAuditPayloadRaw, redactAuditPayload, } from './audit-payload-guard.mjs';
|
|
62
|
+
import { indexGeneratedTypes } from './generated-type-names.mjs';
|
|
63
|
+
import { GuardLogThrottle } from './guard-log-throttle.mjs';
|
|
64
|
+
/**
|
|
65
|
+
* The stored credential columns this guard serves to a service principal
|
|
66
|
+
* only. Defined in `auth/credential-fields`, re-exported for existing callers.
|
|
67
|
+
*/
|
|
68
|
+
export { CREDENTIAL_FIELDS };
|
|
69
|
+
/** Where the generated schema exposes each credential column. */
|
|
70
|
+
const CREDENTIAL_TYPES = indexGeneratedTypes(CREDENTIAL_FIELDS);
|
|
71
|
+
/**
|
|
72
|
+
* The credential fields an input type's keys can reference as a predicate,
|
|
73
|
+
* or `undefined` when it is not a credential model's predicate type.
|
|
74
|
+
*
|
|
75
|
+
* @internal Exported for the schema-coverage test, which walks every input
|
|
76
|
+
* type in the served schema and fails if a credential column appears in a
|
|
77
|
+
* predicate type this function does not claim.
|
|
78
|
+
*/
|
|
79
|
+
export function credentialPredicateFieldsFor(typeName) {
|
|
80
|
+
return CREDENTIAL_TYPES.predicateFields(typeName);
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* The credential fields an output type exposes as values, or `undefined`.
|
|
84
|
+
*
|
|
85
|
+
* @internal Exported for the schema-coverage test (see above).
|
|
86
|
+
*/
|
|
87
|
+
export function credentialOutputFieldsFor(typeName) {
|
|
88
|
+
return CREDENTIAL_TYPES.outputFields(typeName);
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* The credential values a `<Model>ScalarFieldEnum` can name, or `undefined`.
|
|
92
|
+
*
|
|
93
|
+
* @internal Exported for the schema-coverage test (see above).
|
|
94
|
+
*/
|
|
95
|
+
export function credentialEnumValuesFor(typeName) {
|
|
96
|
+
return CREDENTIAL_TYPES.enumFields(typeName);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Walk one argument value alongside its GraphQL input type and collect every
|
|
100
|
+
* place it names a guarded column.
|
|
101
|
+
*
|
|
102
|
+
* Type-directed rather than key-directed: a key called `token` is a
|
|
103
|
+
* credential only inside a credential model's predicate type, so an unrelated
|
|
104
|
+
* input that happens to use the same key name is never flagged.
|
|
105
|
+
*/
|
|
106
|
+
function collectInputReferences(type, value, found) {
|
|
107
|
+
if (value === null || value === undefined)
|
|
108
|
+
return;
|
|
109
|
+
const nullable = getNullableType(type);
|
|
110
|
+
if (nullable instanceof GraphQLList) {
|
|
111
|
+
const inner = nullable.ofType;
|
|
112
|
+
const items = Array.isArray(value) ? value : [value];
|
|
113
|
+
for (const item of items)
|
|
114
|
+
collectInputReferences(inner, item, found);
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
if (nullable instanceof GraphQLEnumType) {
|
|
118
|
+
if (typeof value !== 'string')
|
|
119
|
+
return;
|
|
120
|
+
if (CREDENTIAL_TYPES.enumFields(nullable.name)?.has(value)) {
|
|
121
|
+
found.credential.push(`${nullable.name}.${value}`);
|
|
122
|
+
}
|
|
123
|
+
if (auditPayloadEnumFieldsFor(nullable.name)?.has(value)) {
|
|
124
|
+
found.auditPayload.push(`${nullable.name}.${value}`);
|
|
125
|
+
}
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (nullable instanceof GraphQLInputObjectType && typeof value === 'object') {
|
|
129
|
+
const credential = CREDENTIAL_TYPES.predicateFields(nullable.name);
|
|
130
|
+
const auditPayload = auditPayloadPredicateFieldsFor(nullable.name);
|
|
131
|
+
const fieldDefs = nullable.getFields();
|
|
132
|
+
for (const [key, child] of Object.entries(value)) {
|
|
133
|
+
if (child === undefined)
|
|
134
|
+
continue;
|
|
135
|
+
if (credential?.has(key))
|
|
136
|
+
found.credential.push(`${nullable.name}.${key}`);
|
|
137
|
+
if (auditPayload?.has(key))
|
|
138
|
+
found.auditPayload.push(`${nullable.name}.${key}`);
|
|
139
|
+
const def = fieldDefs[key];
|
|
140
|
+
if (def)
|
|
141
|
+
collectInputReferences(def.type, child, found);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Every guarded column a field's arguments name. Both lists are empty when
|
|
147
|
+
* the field takes no arguments or names no guarded column.
|
|
148
|
+
*/
|
|
149
|
+
export function findGuardedArgumentReferences(info, args) {
|
|
150
|
+
const found = { credential: [], auditPayload: [] };
|
|
151
|
+
if (!args || Object.keys(args).length === 0)
|
|
152
|
+
return found;
|
|
153
|
+
const fieldDef = info.parentType.getFields()[info.fieldName];
|
|
154
|
+
if (!fieldDef)
|
|
155
|
+
return found;
|
|
156
|
+
for (const argDef of fieldDef.args) {
|
|
157
|
+
collectInputReferences(argDef.type, args[argDef.name], found);
|
|
158
|
+
}
|
|
159
|
+
return found;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Every credential reference in a field's arguments, as `TypeName.field`
|
|
163
|
+
* strings. Empty when the field takes no arguments or names no credential.
|
|
164
|
+
*/
|
|
165
|
+
export function findCredentialArgumentReferences(info, args) {
|
|
166
|
+
return findGuardedArgumentReferences(info, args).credential;
|
|
167
|
+
}
|
|
168
|
+
/** The credential field this resolver outputs, as `TypeName.field`, if any. */
|
|
169
|
+
export function findCredentialOutputField(info) {
|
|
170
|
+
const fields = CREDENTIAL_TYPES.outputFields(info.parentType.name);
|
|
171
|
+
return fields?.has(info.fieldName)
|
|
172
|
+
? `${info.parentType.name}.${info.fieldName}`
|
|
173
|
+
: undefined;
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Resolve the guard mode from `CREDENTIAL_FIELD_GUARD_MODE`. Anything other
|
|
177
|
+
* than an explicit `shadow` or `off` enforces.
|
|
178
|
+
*/
|
|
179
|
+
export function getCredentialFieldGuardMode() {
|
|
180
|
+
const raw = (process.env.CREDENTIAL_FIELD_GUARD_MODE ?? '').trim().toLowerCase();
|
|
181
|
+
if (raw === 'shadow' || raw === 'off')
|
|
182
|
+
return raw;
|
|
183
|
+
return 'enforce';
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Credential-surface accesses by surface, decision and principal kind. The
|
|
187
|
+
* `would_deny` series in `shadow` is the list of callers that enforcement
|
|
188
|
+
* would break; it must be empty of legitimate callers before enforcing.
|
|
189
|
+
*/
|
|
190
|
+
export const credentialFieldAccessTotal = new Counter({
|
|
191
|
+
name: 'graphql_credential_field_access_total',
|
|
192
|
+
help: 'Reads of, or predicates over, stored credential columns on /graphql, by ' +
|
|
193
|
+
'surface (output | argument), decision (allowed | would_deny | denied) and ' +
|
|
194
|
+
'principal kind (server | admin | user | none). Only kind=server is allowed.',
|
|
195
|
+
labelNames: ['surface', 'decision', 'principal_kind'],
|
|
196
|
+
registers: [metricsRegistry],
|
|
197
|
+
});
|
|
198
|
+
/**
|
|
199
|
+
* Audit payload accesses by principals that read payloads redacted (user and
|
|
200
|
+
* anonymous). Reads (`output`) are counted by what redaction did to them;
|
|
201
|
+
* predicates (`argument`) by whether they were refused. In `shadow`,
|
|
202
|
+
* `would_redact` with `carried_value="true"` counts reads that served a stored
|
|
203
|
+
* credential value — the exposure enforcement closes.
|
|
204
|
+
*/
|
|
205
|
+
export const auditPayloadAccessTotal = new Counter({
|
|
206
|
+
name: 'graphql_audit_payload_access_total',
|
|
207
|
+
help: 'Reads of, or predicates over, AuditLog JSON payload columns on /graphql by a principal ' +
|
|
208
|
+
'that reads them redacted (user | none), by surface (output | argument), decision ' +
|
|
209
|
+
'(unchanged | redacted | would_redact | denied | would_deny), principal kind, and whether ' +
|
|
210
|
+
'a replaced value held anything (carried_value: true | false | n/a).',
|
|
211
|
+
labelNames: ['surface', 'decision', 'principal_kind', 'carried_value'],
|
|
212
|
+
registers: [metricsRegistry],
|
|
213
|
+
});
|
|
214
|
+
/**
|
|
215
|
+
* Longest caller-supplied value (forwarded chain, user agent, operation name,
|
|
216
|
+
* service subject) a log line or throttle key keeps, in characters.
|
|
217
|
+
*/
|
|
218
|
+
const MAX_ATTRIBUTION_LENGTH = 256;
|
|
219
|
+
/** Truncate a caller-supplied value so a padded one cannot bloat the log or the throttle. */
|
|
220
|
+
function bounded(value) {
|
|
221
|
+
return value.slice(0, MAX_ATTRIBUTION_LENGTH);
|
|
222
|
+
}
|
|
223
|
+
/** Throttle window for the identity log line, per distinct caller key. */
|
|
224
|
+
const LOG_THROTTLE_MS = 10 * 60 * 1000;
|
|
225
|
+
/**
|
|
226
|
+
* Distinct caller keys one scope (principal kind plus connection address) may
|
|
227
|
+
* log per window. Well above the handful of callers one edge address carries;
|
|
228
|
+
* a scope that spends it is rotating caller-supplied values, and says so.
|
|
229
|
+
*/
|
|
230
|
+
const LOG_KEYS_PER_SCOPE = 256;
|
|
231
|
+
/** Distinct scopes the throttle tracks per window. */
|
|
232
|
+
const LOG_MAX_SCOPES = 64;
|
|
233
|
+
const logThrottle = new GuardLogThrottle({
|
|
234
|
+
windowMs: LOG_THROTTLE_MS,
|
|
235
|
+
keysPerScope: LOG_KEYS_PER_SCOPE,
|
|
236
|
+
maxScopes: LOG_MAX_SCOPES,
|
|
237
|
+
});
|
|
238
|
+
/**
|
|
239
|
+
* Charge one decision line to the throttle. Returns whether to write the line;
|
|
240
|
+
* when the scope has just spent its budget, writes the scope's single overflow
|
|
241
|
+
* notice instead and returns false.
|
|
242
|
+
*/
|
|
243
|
+
function admitLogLine(scope, key, nowMs) {
|
|
244
|
+
const verdict = logThrottle.admit(scope, key, nowMs);
|
|
245
|
+
if (verdict.action === 'log')
|
|
246
|
+
return true;
|
|
247
|
+
if (verdict.action === 'overflow') {
|
|
248
|
+
logger.warn('[credential-field-guard] decision log budget spent for a caller scope', {
|
|
249
|
+
scope: verdict.scope,
|
|
250
|
+
keysPerScope: LOG_KEYS_PER_SCOPE,
|
|
251
|
+
dedupWindowMs: LOG_THROTTLE_MS,
|
|
252
|
+
consequence: 'further distinct callers in this scope are not logged until the window ends; ' +
|
|
253
|
+
'the decision counters still count every access',
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
return false;
|
|
257
|
+
}
|
|
258
|
+
/** Message for a credential column reached by a non-service principal. */
|
|
259
|
+
const CREDENTIAL_ACCESS_MESSAGE = '[credential-field-guard] credential access by a non-service principal';
|
|
260
|
+
/** Message for a predicate over an audit payload by a principal that reads it redacted. */
|
|
261
|
+
const AUDIT_PAYLOAD_PREDICATE_MESSAGE = '[credential-field-guard] audit payload predicate by a principal that reads payloads redacted';
|
|
262
|
+
/** Audit payload key paths one log line lists; the count is always logged. */
|
|
263
|
+
const MAX_LOGGED_PATHS = 16;
|
|
264
|
+
/** Log a denied or would-deny access at most once per caller key per window. */
|
|
265
|
+
function logDecision(message, decision, surface, references, principal, info, request, nowMs) {
|
|
266
|
+
const operationName = bounded(info.operation?.name?.value ?? '<unnamed>');
|
|
267
|
+
const userAgent = bounded(headerValue(request?.headers?.['user-agent']));
|
|
268
|
+
// The source is part of the key: two callers sending the same operation
|
|
269
|
+
// with the same user agent (every Node `fetch` sends `node`) are different
|
|
270
|
+
// callers, and a key without the source logs only the first of them per
|
|
271
|
+
// window — which is exactly the attribution a pre-enforcement review of the
|
|
272
|
+
// would-deny set depends on. The connection address scopes the key's budget
|
|
273
|
+
// (the caller cannot set it); the forwarded chain, which the caller can,
|
|
274
|
+
// only distinguishes keys inside that budget.
|
|
275
|
+
const source = callerSource(request);
|
|
276
|
+
const referenceKey = [...new Set(references)].sort().join(',');
|
|
277
|
+
const key = `${decision}|${surface}|${referenceKey}|${operationName}|${userAgent}|${source.forwardedFor}`;
|
|
278
|
+
if (!admitLogLine(`${principal}|${source.ip}`, key, nowMs))
|
|
279
|
+
return;
|
|
280
|
+
logger.warn(message, {
|
|
281
|
+
decision,
|
|
282
|
+
surface,
|
|
283
|
+
references,
|
|
284
|
+
principalKind: principal,
|
|
285
|
+
operationName,
|
|
286
|
+
ip: source.ip,
|
|
287
|
+
forwardedFor: source.forwardedFor,
|
|
288
|
+
userAgent,
|
|
289
|
+
dedupWindowMs: LOG_THROTTLE_MS,
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Log a service principal's credential read at most once per caller key per
|
|
294
|
+
* window.
|
|
295
|
+
*
|
|
296
|
+
* Every holder of the service secret is `kind: "server"`, so the metric alone
|
|
297
|
+
* cannot say WHICH holder read a broker key. The signed credential's `sub`
|
|
298
|
+
* (`adaptic-engine:<host>:<pid>`, `adaptic-platform:…`, an operator toolkit's
|
|
299
|
+
* `adaptic-audit:…`) can, and it is what an operator needs to tell a known
|
|
300
|
+
* service from a leaked secret. It goes to the log, not the metric label,
|
|
301
|
+
* because host:pid is unbounded. A static `SERVER_AUTH_TOKEN` names no caller
|
|
302
|
+
* and logs as `<unattributed>`.
|
|
303
|
+
*/
|
|
304
|
+
function logServiceRead(sub, reference, info, request, nowMs) {
|
|
305
|
+
const operationName = bounded(info.operation?.name?.value ?? '<unnamed>');
|
|
306
|
+
const caller = bounded(sub ?? '<unattributed>');
|
|
307
|
+
const source = callerSource(request);
|
|
308
|
+
const key = `allowed|${caller}|${reference}|${operationName}|${source.forwardedFor}`;
|
|
309
|
+
if (!admitLogLine(`server|${source.ip}`, key, nowMs))
|
|
310
|
+
return;
|
|
311
|
+
logger.info('[credential-field-guard] credential read by a service principal', {
|
|
312
|
+
decision: 'allowed',
|
|
313
|
+
serviceSub: caller,
|
|
314
|
+
reference,
|
|
315
|
+
operationName,
|
|
316
|
+
ip: source.ip,
|
|
317
|
+
forwardedFor: source.forwardedFor,
|
|
318
|
+
dedupWindowMs: LOG_THROTTLE_MS,
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Log an audit payload read that redaction changes, or would change, at most
|
|
323
|
+
* once per caller key per window. The line names the key paths that held
|
|
324
|
+
* credentials, never their values.
|
|
325
|
+
*/
|
|
326
|
+
function logAuditPayloadRead(decision, reference, paths, principal, info, request, nowMs) {
|
|
327
|
+
const operationName = bounded(info.operation?.name?.value ?? '<unnamed>');
|
|
328
|
+
const userAgent = bounded(headerValue(request?.headers?.['user-agent']));
|
|
329
|
+
const source = callerSource(request);
|
|
330
|
+
const key = `payload|${decision}|${reference}|${operationName}|${userAgent}|${source.forwardedFor}`;
|
|
331
|
+
if (!admitLogLine(`${principal}|${source.ip}`, key, nowMs))
|
|
332
|
+
return;
|
|
333
|
+
logger.warn('[credential-field-guard] audit payload holding credentials read by a principal that reads payloads redacted', {
|
|
334
|
+
decision,
|
|
335
|
+
reference,
|
|
336
|
+
credentialPaths: paths.slice(0, MAX_LOGGED_PATHS).map((p) => bounded(p.path)),
|
|
337
|
+
credentialPathCount: paths.length,
|
|
338
|
+
carriedValue: paths.some((p) => p.carriesValue),
|
|
339
|
+
principalKind: principal,
|
|
340
|
+
operationName,
|
|
341
|
+
ip: source.ip,
|
|
342
|
+
forwardedFor: source.forwardedFor,
|
|
343
|
+
userAgent,
|
|
344
|
+
dedupWindowMs: LOG_THROTTLE_MS,
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Where a request came from, as far as this process can tell.
|
|
349
|
+
*
|
|
350
|
+
* `req.ip` is the address `trust proxy` resolves, and behind the production
|
|
351
|
+
* edge it resolves to the edge's own pool (an operator's laptop and a hosted
|
|
352
|
+
* service log the same handful of addresses), so on its own it cannot tell
|
|
353
|
+
* callers apart. The raw `X-Forwarded-For` chain carries the hops the edge
|
|
354
|
+
* saw. It is caller-supplied at its left end, so it is attribution evidence
|
|
355
|
+
* for an operator reading the log, never an identity the guard decides on.
|
|
356
|
+
*/
|
|
357
|
+
function callerSource(request) {
|
|
358
|
+
return {
|
|
359
|
+
ip: bounded(request?.ip ?? '<none>'),
|
|
360
|
+
forwardedFor: bounded(headerValue(request?.headers?.['x-forwarded-for'])),
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
function headerValue(value) {
|
|
364
|
+
if (Array.isArray(value))
|
|
365
|
+
return value.join(',');
|
|
366
|
+
return value ?? '<none>';
|
|
367
|
+
}
|
|
368
|
+
function forbidden(references) {
|
|
369
|
+
return new GraphQLError('Forbidden: stored credentials are readable only by a service principal', {
|
|
370
|
+
extensions: {
|
|
371
|
+
code: 'FORBIDDEN',
|
|
372
|
+
references,
|
|
373
|
+
http: { status: 403 },
|
|
374
|
+
},
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
function forbiddenAuditPayloadPredicate(references) {
|
|
378
|
+
return new GraphQLError('Forbidden: audit payload columns can be filtered, sorted or grouped on only by a ' +
|
|
379
|
+
'service or admin principal', {
|
|
380
|
+
extensions: {
|
|
381
|
+
code: 'FORBIDDEN',
|
|
382
|
+
references,
|
|
383
|
+
http: { status: 403 },
|
|
384
|
+
},
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Create the TypeGraphQL global middleware that guards credential columns.
|
|
389
|
+
*
|
|
390
|
+
* Runs on every field. The hot path — a non-credential field with no
|
|
391
|
+
* arguments, or any field for a service principal — returns after a map
|
|
392
|
+
* lookup.
|
|
393
|
+
*
|
|
394
|
+
* @param options - Optional overrides for tests.
|
|
395
|
+
* @returns A {@link MiddlewareFn} for `buildSchema({ globalMiddlewares })`.
|
|
396
|
+
*/
|
|
397
|
+
export function createCredentialFieldGuardMiddleware(options = {}) {
|
|
398
|
+
const resolveMode = options.modeProvider ?? getCredentialFieldGuardMode;
|
|
399
|
+
const now = options.now ?? Date.now;
|
|
400
|
+
return async ({ context, args, info }, next) => {
|
|
401
|
+
const proceed = () => next();
|
|
402
|
+
const output = findCredentialOutputField(info);
|
|
403
|
+
const principal = context.principal ?? null;
|
|
404
|
+
if (principal?.kind === 'server') {
|
|
405
|
+
if (output && resolveMode() !== 'off') {
|
|
406
|
+
credentialFieldAccessTotal.inc({
|
|
407
|
+
surface: 'output',
|
|
408
|
+
decision: 'allowed',
|
|
409
|
+
principal_kind: 'server',
|
|
410
|
+
});
|
|
411
|
+
logServiceRead(principal.sub, output, info, context.req, now());
|
|
412
|
+
}
|
|
413
|
+
return proceed();
|
|
414
|
+
}
|
|
415
|
+
const references = findGuardedArgumentReferences(info, args);
|
|
416
|
+
// Admins read audit payloads as stored, so only user and anonymous
|
|
417
|
+
// principals reach the payload rules below.
|
|
418
|
+
const payloadReader = !readsAuditPayloadRaw(principal);
|
|
419
|
+
const payloadOutput = payloadReader ? auditPayloadOutputField(info) : undefined;
|
|
420
|
+
const payloadRefs = payloadReader ? references.auditPayload : [];
|
|
421
|
+
if (!output &&
|
|
422
|
+
references.credential.length === 0 &&
|
|
423
|
+
!payloadOutput &&
|
|
424
|
+
payloadRefs.length === 0) {
|
|
425
|
+
return proceed();
|
|
426
|
+
}
|
|
427
|
+
const mode = resolveMode();
|
|
428
|
+
if (mode === 'off')
|
|
429
|
+
return proceed();
|
|
430
|
+
const principalLabel = principal?.kind ?? 'none';
|
|
431
|
+
const nowMs = now();
|
|
432
|
+
const refusal = mode === 'enforce' ? 'denied' : 'would_deny';
|
|
433
|
+
if (output || references.credential.length > 0) {
|
|
434
|
+
const surface = output ? 'output' : 'argument';
|
|
435
|
+
const credentialRefs = output ? [output, ...references.credential] : references.credential;
|
|
436
|
+
credentialFieldAccessTotal.inc({
|
|
437
|
+
surface,
|
|
438
|
+
decision: refusal,
|
|
439
|
+
principal_kind: principalLabel,
|
|
440
|
+
});
|
|
441
|
+
logDecision(CREDENTIAL_ACCESS_MESSAGE, refusal, surface, credentialRefs, principalLabel, info, context.req, nowMs);
|
|
442
|
+
if (mode === 'enforce')
|
|
443
|
+
throw forbidden(credentialRefs);
|
|
444
|
+
}
|
|
445
|
+
if (payloadRefs.length > 0) {
|
|
446
|
+
auditPayloadAccessTotal.inc({
|
|
447
|
+
surface: 'argument',
|
|
448
|
+
decision: refusal,
|
|
449
|
+
principal_kind: principalLabel,
|
|
450
|
+
carried_value: 'n/a',
|
|
451
|
+
});
|
|
452
|
+
logDecision(AUDIT_PAYLOAD_PREDICATE_MESSAGE, refusal, 'argument', payloadRefs, principalLabel, info, context.req, nowMs);
|
|
453
|
+
if (mode === 'enforce')
|
|
454
|
+
throw forbiddenAuditPayloadPredicate(payloadRefs);
|
|
455
|
+
}
|
|
456
|
+
if (!payloadOutput)
|
|
457
|
+
return proceed();
|
|
458
|
+
const value = await proceed();
|
|
459
|
+
const { redacted, paths } = redactAuditPayload(value);
|
|
460
|
+
const decision = paths.length === 0 ? 'unchanged' : mode === 'enforce' ? 'redacted' : 'would_redact';
|
|
461
|
+
auditPayloadAccessTotal.inc({
|
|
462
|
+
surface: 'output',
|
|
463
|
+
decision,
|
|
464
|
+
principal_kind: principalLabel,
|
|
465
|
+
carried_value: String(paths.some((p) => p.carriesValue)),
|
|
466
|
+
});
|
|
467
|
+
if (paths.length > 0) {
|
|
468
|
+
logAuditPayloadRead(decision, payloadOutput, paths, principalLabel, info, context.req, nowMs);
|
|
469
|
+
}
|
|
470
|
+
// Under enforce the redacted copy is served even when no path was found:
|
|
471
|
+
// the copy is what the rule promises, the path list only describes it.
|
|
472
|
+
return mode === 'enforce' ? redacted : value;
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
/** @internal Test hook: forget the log throttle state. */
|
|
476
|
+
export function resetCredentialFieldGuardLogThrottle() {
|
|
477
|
+
logThrottle.reset();
|
|
478
|
+
}
|
|
479
|
+
//# sourceMappingURL=credential-field-guard.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 @@
|
|
|
1
|
+
{"version":3,"file":"generated-type-names.d.ts","sourceRoot":"","sources":["../../../src/middleware/generated-type-names.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,0DAA2D,CAAC;AAE9F;;;;;;GAMG;AACH,eAAO,MAAM,qBAAqB,yDAA0D,CAAC;AAY7F,4EAA4E;AAC5E,MAAM,WAAW,kBAAkB;IACjC,gEAAgE;IAChE,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC,GAAG,SAAS,CAAC;IAChE,iFAAiF;IACjF,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC,GAAG,SAAS,CAAC;IACnE,yEAAyE;IACzE,UAAU,CAAC,QAAQ,EAAE,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC,GAAG,SAAS,CAAC;CAC/D;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,aAAa,EAAE,WAAW,CAAC,MAAM,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC,GACtD,kBAAkB,CAoCpB"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generated-type-names.js","sourceRoot":"","sources":["../../../src/middleware/generated-type-names.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH;;;;GAIG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,EAAE,EAAE,SAAS,EAAE,cAAc,EAAE,cAAc,CAAU,CAAC;AAE9F;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,qBAAqB,EAAE,qBAAqB,CAAU,CAAC;AAE7F;;;;;GAKG;AACH,MAAM,wBAAwB,GAAG,CAAC,OAAO,EAAE,SAAS,EAAE,QAAQ,CAAU,CAAC;AAEzE,MAAM,wBAAwB,GAAG,iBAAiB,CAAC;AAYnD;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CACjC,aAAuD;IAEvD,MAAM,OAAO,GAA6C,IAAI,GAAG,CAC/D,CAAC,GAAG,aAAa,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,EAAE,MAAM,CAAC,EAAE,EAAE,CAAC;QAC9C,GAAG,qBAAqB,CAAC,GAAG,CAC1B,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,GAAG,KAAK,GAAG,MAAM,EAAE,EAAE,MAAM,CAAkC,CAC3E;QACD,GAAG,qBAAqB,CAAC,GAAG,CAC1B,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,GAAG,MAAM,GAAG,KAAK,EAAE,EAAE,MAAM,CAAkC,CAC3E;KACF,CAAC,CACH,CAAC;IAEF,gDAAgD;IAChD,+EAA+E;IAC/E,MAAM,kBAAkB,GAAG,CAAC,GAAG,aAAa,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC;IAEzF,OAAO;QACL,YAAY,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC;QACjD,sEAAsE;QACtE,0EAA0E;QAC1E,2CAA2C;QAC3C,eAAe,EAAE,CAAC,QAAQ,EAAE,EAAE;YAC5B,KAAK,MAAM,KAAK,IAAI,kBAAkB,EAAE,CAAC;gBACvC,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,KAAK,CAAC;oBAAE,SAAS;gBAC1C,MAAM,IAAI,GAAG,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;gBAC1C,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC;oBAAE,SAAS;gBACnC,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;oBAAE,OAAO,SAAS,CAAC;gBAC9E,OAAO,aAAa,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;YAClC,CAAC;YACD,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,UAAU,EAAE,CAAC,QAAQ,EAAE,EAAE,CACvB,QAAQ,CAAC,QAAQ,CAAC,wBAAwB,CAAC;YACzC,CAAC,CAAC,aAAa,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,wBAAwB,CAAC,MAAM,CAAC,CAAC;YACxE,CAAC,CAAC,SAAS;KAChB,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,73 @@
|
|
|
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 const VALUE_OUTPUT_SUFFIXES = ['', '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 const VALUE_OUTPUT_PREFIXES = ['CreateManyAndReturn', 'UpdateManyAndReturn'];
|
|
28
|
+
/**
|
|
29
|
+
* Input-type name fragments that make a type a read predicate (filter, sort,
|
|
30
|
+
* cursor, aggregate filter) rather than a write payload. A `…WhereUniqueInput`
|
|
31
|
+
* is also how a mutation selects its row, so a guarded key there is an oracle
|
|
32
|
+
* on a write path too.
|
|
33
|
+
*/
|
|
34
|
+
const PREDICATE_TYPE_FRAGMENTS = ['Where', 'OrderBy', 'Having'];
|
|
35
|
+
const SCALAR_FIELD_ENUM_SUFFIX = 'ScalarFieldEnum';
|
|
36
|
+
/**
|
|
37
|
+
* Index the generated types of every model in `fieldsByModel`.
|
|
38
|
+
*
|
|
39
|
+
* @param fieldsByModel - Guarded column names, by Prisma model name.
|
|
40
|
+
* @returns Lookups over the generated type names.
|
|
41
|
+
*/
|
|
42
|
+
export function indexGeneratedTypes(fieldsByModel) {
|
|
43
|
+
const outputs = new Map([...fieldsByModel].flatMap(([model, fields]) => [
|
|
44
|
+
...VALUE_OUTPUT_SUFFIXES.map((suffix) => [`${model}${suffix}`, fields]),
|
|
45
|
+
...VALUE_OUTPUT_PREFIXES.map((prefix) => [`${prefix}${model}`, fields]),
|
|
46
|
+
]));
|
|
47
|
+
// Longest-first, so the prefix match attributes
|
|
48
|
+
// `AccountLinkingRequestWhereInput` to `AccountLinkingRequest`, not `Account`.
|
|
49
|
+
const modelsLongestFirst = [...fieldsByModel.keys()].sort((a, b) => b.length - a.length);
|
|
50
|
+
return {
|
|
51
|
+
outputFields: (typeName) => outputs.get(typeName),
|
|
52
|
+
// Generated names start with the model name followed by an upper-case
|
|
53
|
+
// letter (`AlpacaAccountWhereInput`), so a model named `Account` does not
|
|
54
|
+
// claim `AccountLinkingRequestWhereInput`.
|
|
55
|
+
predicateFields: (typeName) => {
|
|
56
|
+
for (const model of modelsLongestFirst) {
|
|
57
|
+
if (!typeName.startsWith(model))
|
|
58
|
+
continue;
|
|
59
|
+
const rest = typeName.slice(model.length);
|
|
60
|
+
if (!/^[A-Z]/.test(rest))
|
|
61
|
+
continue;
|
|
62
|
+
if (!PREDICATE_TYPE_FRAGMENTS.some((f) => rest.includes(f)))
|
|
63
|
+
return undefined;
|
|
64
|
+
return fieldsByModel.get(model);
|
|
65
|
+
}
|
|
66
|
+
return undefined;
|
|
67
|
+
},
|
|
68
|
+
enumFields: (typeName) => typeName.endsWith(SCALAR_FIELD_ENUM_SUFFIX)
|
|
69
|
+
? fieldsByModel.get(typeName.slice(0, -SCALAR_FIELD_ENUM_SUFFIX.length))
|
|
70
|
+
: undefined,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
//# sourceMappingURL=generated-type-names.js.map
|