@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.
Files changed (114) hide show
  1. package/auth/authorization-map.cjs +306 -0
  2. package/auth/authorization-map.d.ts +143 -0
  3. package/auth/cortex-auth-checker.cjs +172 -0
  4. package/auth/cortex-auth-checker.d.ts +114 -0
  5. package/auth/credential-fields.cjs +51 -0
  6. package/auth/credential-fields.d.ts +19 -0
  7. package/auth/credential-redaction.cjs +134 -0
  8. package/auth/credential-redaction.d.ts +60 -0
  9. package/auth/graphql-auth-shadow.cjs +317 -0
  10. package/auth/graphql-auth-shadow.d.ts +194 -0
  11. package/auth/membership-write-authority.cjs +131 -0
  12. package/auth/membership-write-authority.d.ts +110 -0
  13. package/auth/mutation-authorization.cjs +376 -0
  14. package/auth/mutation-authorization.d.ts +261 -0
  15. package/auth/nested-write-inspector.cjs +189 -0
  16. package/auth/nested-write-inspector.d.ts +94 -0
  17. package/auth/nested-write-policy.cjs +189 -0
  18. package/auth/nested-write-policy.d.ts +99 -0
  19. package/auth/service-token.cjs +339 -0
  20. package/auth/service-token.d.ts +106 -0
  21. package/auth/tenancy-scope.cjs +736 -0
  22. package/auth/tenancy-scope.d.ts +347 -0
  23. package/auth/token-verifier.cjs +451 -0
  24. package/auth/token-verifier.d.ts +153 -0
  25. package/auth/totp.cjs +265 -0
  26. package/auth/totp.d.ts +111 -0
  27. package/auth/user-write-content.cjs +116 -0
  28. package/auth/user-write-content.d.ts +47 -0
  29. package/auth/ws-auth-context.cjs +75 -0
  30. package/auth/ws-auth-context.d.ts +69 -0
  31. package/config/jwtConfig.cjs +57 -0
  32. package/config/jwtConfig.d.ts +16 -0
  33. package/config/metrics.cjs +356 -0
  34. package/config/metrics.d.ts +128 -0
  35. package/config/persisted-queries.cjs +122 -0
  36. package/config/persisted-queries.d.ts +40 -0
  37. package/config/server-only-models.cjs +166 -0
  38. package/config/server-only-models.d.ts +89 -0
  39. package/config/tracing.d.ts +24 -0
  40. package/esm/auth/service-token.d.ts +12 -0
  41. package/esm/auth/service-token.mjs +27 -5
  42. package/esm/config/jwtConfig.mjs +5 -1
  43. package/generated/typegraphql-prisma/enhance.cjs +3 -3
  44. package/generated/typegraphql-prisma/index.cjs +6 -6
  45. package/generated/typegraphql-prisma/resolvers/crud/args.index.cjs +95 -95
  46. package/generated/typegraphql-prisma/resolvers/outputs/index.cjs +1 -1
  47. package/generated/typegraphql-prisma/resolvers/relations/args.index.cjs +32 -32
  48. package/middleware/audit-log-write-redaction.cjs +143 -0
  49. package/middleware/audit-log-write-redaction.d.ts +82 -0
  50. package/middleware/audit-logger.cjs +378 -0
  51. package/middleware/audit-logger.d.ts +158 -0
  52. package/middleware/audit-payload-guard.cjs +107 -0
  53. package/middleware/audit-payload-guard.d.ts +85 -0
  54. package/middleware/auth.cjs +66 -0
  55. package/middleware/auth.d.ts +41 -0
  56. package/middleware/credential-field-guard.cjs +514 -0
  57. package/middleware/credential-field-guard.d.ts +173 -0
  58. package/middleware/generated-type-names.cjs +77 -0
  59. package/middleware/generated-type-names.d.ts +44 -0
  60. package/middleware/graphql-validation-plugin.cjs +310 -0
  61. package/middleware/graphql-validation-plugin.d.ts +98 -0
  62. package/middleware/guard-log-throttle.cjs +89 -0
  63. package/middleware/guard-log-throttle.d.ts +80 -0
  64. package/middleware/index.cjs +57 -0
  65. package/middleware/index.d.ts +14 -0
  66. package/middleware/input-validator.cjs +220 -0
  67. package/middleware/input-validator.d.ts +63 -0
  68. package/middleware/mandate-version-validation.cjs +131 -0
  69. package/middleware/mandate-version-validation.d.ts +41 -0
  70. package/middleware/mutation-account-facts.cjs +223 -0
  71. package/middleware/mutation-account-facts.d.ts +143 -0
  72. package/middleware/mutation-auth-guard.cjs +536 -0
  73. package/middleware/mutation-auth-guard.d.ts +100 -0
  74. package/middleware/mutation-membership-facts.cjs +276 -0
  75. package/middleware/mutation-membership-facts.d.ts +133 -0
  76. package/middleware/mutation-tenant-facts.cjs +132 -0
  77. package/middleware/mutation-tenant-facts.d.ts +81 -0
  78. package/middleware/query-complexity.cjs +182 -0
  79. package/middleware/query-complexity.d.ts +56 -0
  80. package/middleware/rate-limiter.cjs +223 -0
  81. package/middleware/rate-limiter.d.ts +93 -0
  82. package/middleware/rate-tier.cjs +111 -0
  83. package/middleware/rate-tier.d.ts +56 -0
  84. package/middleware/soft-delete.cjs +175 -0
  85. package/middleware/soft-delete.d.ts +146 -0
  86. package/middleware/tenancy-scoping.cjs +229 -0
  87. package/middleware/tenancy-scoping.d.ts +67 -0
  88. package/middleware/trading-policy-audit.cjs +353 -0
  89. package/middleware/trading-policy-audit.d.ts +184 -0
  90. package/middleware/types.cjs +17 -0
  91. package/middleware/types.d.ts +87 -0
  92. package/middleware/validation-examples.cjs +398 -0
  93. package/middleware/validation-examples.d.ts +76 -0
  94. package/package.json +10 -2
  95. package/readers/index.cjs +15 -0
  96. package/readers/index.d.ts +10 -0
  97. package/readers/intraday-lane-prefs.cjs +76 -0
  98. package/readers/intraday-lane-prefs.d.ts +45 -0
  99. package/esm/config/__tests__/server-only-surface.harness.d.ts +0 -12
  100. package/esm/config/__tests__/server-only-surface.harness.mjs +0 -41
  101. package/esm/middleware/__tests__/audit-log-write-redaction.harness.d.ts +0 -144
  102. package/esm/middleware/__tests__/audit-log-write-redaction.harness.mjs +0 -920
  103. package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts +0 -55
  104. package/esm/middleware/__tests__/credential-field-coverage.harness.mjs +0 -440
  105. package/esm/middleware/__tests__/credential-field-guard.harness.d.ts +0 -34
  106. package/esm/middleware/__tests__/credential-field-guard.harness.mjs +0 -212
  107. package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +0 -56
  108. package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +0 -575
  109. package/esm/middleware/__tests__/rate-limit-test-utils.d.ts +0 -60
  110. package/esm/middleware/__tests__/rate-limit-test-utils.mjs +0 -85
  111. package/esm/middleware/__tests__/ts-node-harness.d.ts +0 -10
  112. package/esm/middleware/__tests__/ts-node-harness.mjs +0 -71
  113. package/health.cjs +0 -274
  114. package/server.cjs +0 -607
@@ -0,0 +1,317 @@
1
+ "use strict";
2
+ /**
3
+ * GraphQL context-layer authentication SHADOW observer.
4
+ *
5
+ * This is the transport/context-level counterpart to the resolver-level
6
+ * {@link ../auth/cortex-auth-checker.cortexAuthChecker}. The two observe DIFFERENT
7
+ * populations and are complementary:
8
+ *
9
+ * - `cortexAuthChecker` runs ONLY for `@Authorized()`-decorated fields (today:
10
+ * the 5 investor-relations models + delete mutations). It cannot see an
11
+ * unauthenticated request to any of the hundreds of auto-generated,
12
+ * undecorated CRUD fields — which is the overwhelming majority of live
13
+ * traffic (the platform, the account-audit scripts, and the engine all reach
14
+ * undecorated resolvers).
15
+ * - THIS observer runs in the `/graphql` HTTP + WebSocket `context()` callback,
16
+ * BEFORE any resolver, on EVERY request. It records whether a request arrived
17
+ * with a verified principal, with no principal, or with an invalid token —
18
+ * the true, complete denominator+numerator the enforcement decision needs.
19
+ *
20
+ * WHY (audit context): the `/graphql` `context()` currently lets a request with
21
+ * NO bearer token fall through as `{ principal: null }` and ALLOWS it. Requiring
22
+ * a principal at this layer (rejecting `null`) is the change that would break the
23
+ * entire product today (cookie-authenticated platform, token-less audit scripts,
24
+ * the engine's `SERVER_AUTH_TOKEN` gate). Before that enforcement can ever be
25
+ * flipped, we must first MEASURE, in production, exactly who reaches `/graphql`
26
+ * without a verified principal. This module provides that measurement WITHOUT
27
+ * changing behaviour: it counts and (throttled) logs would-denies and always
28
+ * returns control to the caller.
29
+ *
30
+ * SAFETY CONTRACT — observe-only, never blocks:
31
+ * - The Prometheus counter {@link graphqlAuthContextEvaluationsTotal} increments
32
+ * on every context evaluation, labelled by transport + outcome. It is the
33
+ * primary quantitative signal and carries only BOUNDED labels (never the
34
+ * attacker-controllable operation name / origin / IP).
35
+ * - For the `no_principal` outcome — the would-deny — a structured identity log
36
+ * is emitted, THROTTLED to the first occurrence of each
37
+ * `(transport, operationName, origin)` per dedup window. Unthrottled logging
38
+ * of every unauthenticated request would flood Cloud Logging and bury real
39
+ * warnings (audit B01-backend-legacy-10); the counter carries the per-request
40
+ * cardinality instead.
41
+ * - The dedup store is capped and rotates novel keys into a shared overflow
42
+ * bucket so an attacker rotating spoofed origins/operation names cannot grow
43
+ * memory without bound (audit B01-backend-legacy-12).
44
+ *
45
+ * @see src/auth/cortex-auth-checker.ts for the resolver-level shadow checker.
46
+ * @see docs/security/2026-08-23-graphql-auth-enforcement-runbook.md for the
47
+ * staged enforcement plan this observer feeds.
48
+ */
49
+ Object.defineProperty(exports, "__esModule", { value: true });
50
+ exports.SHADOW_LOG_DEDUP_WINDOW_MS = exports.GRAPHQL_AUTH_SHADOW_LOG_DISABLED_ENV = exports.graphqlAuthShadowTrackedKeys = exports.graphqlAuthContextEvaluationsTotal = void 0;
51
+ exports.isShadowAuthLoggingDisabled = isShadowAuthLoggingDisabled;
52
+ exports.headerToString = headerToString;
53
+ exports.extractOperationName = extractOperationName;
54
+ exports.extractOperationNameFromArgs = extractOperationNameFromArgs;
55
+ exports.extractHeaderIdentityFromWsExtra = extractHeaderIdentityFromWsExtra;
56
+ exports.recordAuthContextOutcome = recordAuthContextOutcome;
57
+ exports.recordShadowAuthMiss = recordShadowAuthMiss;
58
+ exports._resetShadowAuthStateForTests = _resetShadowAuthStateForTests;
59
+ const prom_client_1 = require("prom-client");
60
+ const metrics_1 = require("../config/metrics.cjs");
61
+ const logger_1 = require("../utils/logger.cjs");
62
+ // -----------------------------------------------------------------------------
63
+ // Metrics
64
+ // -----------------------------------------------------------------------------
65
+ /**
66
+ * Counts EVERY `/graphql` context evaluation, labelled by {@link GraphqlTransport}
67
+ * and {@link AuthContextOutcome}. This single series is both the denominator
68
+ * (total requests seen) and the numerator (`outcome="no_principal"` = would-denies).
69
+ *
70
+ * Graduation rule for the runbook: the enforcement flip is safe to consider only
71
+ * once `outcome="no_principal"` has been driven to (effectively) zero for the
72
+ * transport being enforced, sustained across a full trading week — i.e. every
73
+ * legitimate caller has been migrated to presenting a verified principal.
74
+ *
75
+ * Labels are deliberately BOUNDED (2 transports x 3 outcomes = 6 series). The
76
+ * high-cardinality identity (operation name, origin, IP) lives only in the
77
+ * throttled log, never as a metric label — an unauthenticated caller controls
78
+ * those strings and could otherwise explode metric cardinality.
79
+ */
80
+ exports.graphqlAuthContextEvaluationsTotal = new prom_client_1.Counter({
81
+ name: 'graphql_auth_context_evaluations_total',
82
+ help: 'GraphQL /graphql context evaluations by transport and outcome (outcome="no_principal" is the shadow would-deny; observe-only, never blocks)',
83
+ labelNames: ['transport', 'outcome'],
84
+ registers: [metrics_1.metricsRegistry],
85
+ });
86
+ /**
87
+ * Current tracked-key cardinality of the throttled-log dedup store. Bounds
88
+ * visibility into the store ahead of the {@link MAX_TRACKED_SHADOW_KEYS} cap
89
+ * (audit B01-backend-legacy-12).
90
+ */
91
+ exports.graphqlAuthShadowTrackedKeys = new prom_client_1.Gauge({
92
+ name: 'graphql_auth_shadow_tracked_keys',
93
+ help: 'Current distinct (transport, operationName, origin) keys tracked by the shadow-auth log throttle',
94
+ registers: [metrics_1.metricsRegistry],
95
+ });
96
+ // -----------------------------------------------------------------------------
97
+ // Logging-enable flag (counter is always on; this only gates the detail log)
98
+ // -----------------------------------------------------------------------------
99
+ /**
100
+ * Environment variable that DISABLES the throttled identity log. Absent (the
101
+ * default) keeps logging ON. Set to `true`/`1` to silence the per-caller log
102
+ * lines if they ever become operationally noisy — the {@link
103
+ * graphqlAuthContextEvaluationsTotal} counter continues unaffected, so the
104
+ * quantitative signal is never lost.
105
+ */
106
+ exports.GRAPHQL_AUTH_SHADOW_LOG_DISABLED_ENV = 'GRAPHQL_AUTH_SHADOW_LOG_DISABLED';
107
+ /**
108
+ * Whether the throttled identity log is disabled. Read fresh each call (a cheap
109
+ * env read) so it can be toggled operationally without a restart — matching the
110
+ * shadow-flag convention used by the AuthChecker and rate limiter.
111
+ *
112
+ * @param env - Environment source (defaults to `process.env`); injectable for tests.
113
+ * @returns `true` only when the flag is explicitly `true`/`1`.
114
+ */
115
+ function isShadowAuthLoggingDisabled(env = process.env) {
116
+ var _a;
117
+ const raw = ((_a = env[exports.GRAPHQL_AUTH_SHADOW_LOG_DISABLED_ENV]) !== null && _a !== void 0 ? _a : '')
118
+ .trim()
119
+ .toLowerCase();
120
+ return raw === 'true' || raw === '1';
121
+ }
122
+ // -----------------------------------------------------------------------------
123
+ // Throttled-log dedup store (mirrors the rate-limiter's capped store pattern)
124
+ // -----------------------------------------------------------------------------
125
+ /**
126
+ * Dedup window for the identity log: at most one line per distinct
127
+ * `(transport, operationName, origin)` key per window. Sized long (10 min) so a
128
+ * high-volume unauthenticated caller (e.g. the whole platform) contributes ~one
129
+ * line per window rather than one per request.
130
+ */
131
+ exports.SHADOW_LOG_DEDUP_WINDOW_MS = 10 * 60 * 1000;
132
+ /** Sweep cadence for expired dedup windows. */
133
+ const STORE_SWEEP_INTERVAL_MS = 60000;
134
+ /**
135
+ * Cap on distinct dedup keys. Past the cap, novel keys aggregate into a single
136
+ * shared overflow bucket instead of allocating — bounding memory under an
137
+ * attacker rotating spoofed origins / operation names (audit B01-backend-legacy-12).
138
+ */
139
+ const MAX_TRACKED_SHADOW_KEYS = 10000;
140
+ /** Dedup key used once the store cardinality cap is reached. */
141
+ const OVERFLOW_KEY = 'overflow';
142
+ /** Max characters retained from a caller-supplied string used in a dedup key. */
143
+ const MAX_KEY_SEGMENT_LEN = 120;
144
+ /** Max characters retained from a `User-Agent` in the log body. */
145
+ const MAX_UA_LEN = 200;
146
+ const shadowLogStore = new Map();
147
+ // Sweep expired windows every minute. `unref()` so importing this module (tests,
148
+ // one-off scripts) never keeps the process alive on account of the sweeper.
149
+ setInterval(() => {
150
+ const now = Date.now();
151
+ for (const [key, entry] of shadowLogStore) {
152
+ if (entry.windowResetAt < now) {
153
+ shadowLogStore.delete(key);
154
+ }
155
+ }
156
+ exports.graphqlAuthShadowTrackedKeys.set(shadowLogStore.size);
157
+ }, STORE_SWEEP_INTERVAL_MS).unref();
158
+ /**
159
+ * Decide whether to emit an identity log line for `key` now: emit on the first
160
+ * occurrence within the current dedup window, then suppress until the window
161
+ * rolls over. Applies the cardinality cap + overflow bucket.
162
+ *
163
+ * @param key - The `(transport, operationName, origin)` dedup key.
164
+ * @returns `true` when this is the first sighting of the key in the window.
165
+ */
166
+ function shouldEmitIdentityLog(key) {
167
+ const now = Date.now();
168
+ let storeKey = key;
169
+ // Cardinality cap: fold novel keys into the shared overflow bucket rather than
170
+ // growing without bound.
171
+ if (!shadowLogStore.has(storeKey) &&
172
+ shadowLogStore.size >= MAX_TRACKED_SHADOW_KEYS) {
173
+ storeKey = OVERFLOW_KEY;
174
+ }
175
+ const existing = shadowLogStore.get(storeKey);
176
+ if (!existing || existing.windowResetAt < now) {
177
+ shadowLogStore.set(storeKey, {
178
+ count: 1,
179
+ windowResetAt: now + exports.SHADOW_LOG_DEDUP_WINDOW_MS,
180
+ });
181
+ return true;
182
+ }
183
+ existing.count += 1;
184
+ return false;
185
+ }
186
+ // -----------------------------------------------------------------------------
187
+ // Extraction helpers (accept `unknown` so callers pass framework objects without
188
+ // leaking `any` or coupling this module to Express / graphql-ws types)
189
+ // -----------------------------------------------------------------------------
190
+ /**
191
+ * Normalise a raw header value (`string | string[] | undefined`, arriving typed
192
+ * as `unknown`) to a single string. Node folds repeated headers into an array;
193
+ * we keep the first value.
194
+ *
195
+ * @param value - Raw header value.
196
+ * @returns The string value, or `undefined` when absent/unusable.
197
+ */
198
+ function headerToString(value) {
199
+ if (typeof value === 'string')
200
+ return value;
201
+ if (Array.isArray(value) && typeof value[0] === 'string')
202
+ return value[0];
203
+ return undefined;
204
+ }
205
+ /**
206
+ * Extract a GraphQL operation name from a parsed HTTP request body.
207
+ *
208
+ * @param body - The JSON-parsed `/graphql` POST body (typed `unknown`).
209
+ * @returns The `operationName`, or `undefined` when absent/empty.
210
+ */
211
+ function extractOperationName(body) {
212
+ if (typeof body !== 'object' || body === null)
213
+ return undefined;
214
+ const op = body.operationName;
215
+ return typeof op === 'string' && op.length > 0 ? op : undefined;
216
+ }
217
+ /**
218
+ * Extract a GraphQL operation name from graphql-ws `ExecutionArgs`.
219
+ *
220
+ * @param args - The third argument to the graphql-ws `context` callback (typed `unknown`).
221
+ * @returns The `operationName`, or `undefined` when absent/empty.
222
+ */
223
+ function extractOperationNameFromArgs(args) {
224
+ if (typeof args !== 'object' || args === null)
225
+ return undefined;
226
+ const op = args.operationName;
227
+ return typeof op === 'string' && op.length > 0 ? op : undefined;
228
+ }
229
+ /**
230
+ * Extract `origin` / `userAgent` / `ip` from the graphql-ws `ctx.extra` object
231
+ * (`{ request, socket }` for the `ws` integration), tolerating any shape.
232
+ *
233
+ * @param extra - The graphql-ws context `extra` (typed `unknown`).
234
+ * @returns Best-effort header identity for the WebSocket upgrade request.
235
+ */
236
+ function extractHeaderIdentityFromWsExtra(extra) {
237
+ if (typeof extra !== 'object' || extra === null)
238
+ return {};
239
+ const request = extra.request;
240
+ if (typeof request !== 'object' || request === null)
241
+ return {};
242
+ const headers = request.headers;
243
+ const socket = request.socket;
244
+ const headerBag = typeof headers === 'object' && headers !== null
245
+ ? headers
246
+ : {};
247
+ const remoteAddress = typeof socket === 'object' && socket !== null
248
+ ? socket.remoteAddress
249
+ : undefined;
250
+ return {
251
+ origin: headerToString(headerBag['origin']),
252
+ userAgent: headerToString(headerBag['user-agent']),
253
+ ip: typeof remoteAddress === 'string' ? remoteAddress : undefined,
254
+ };
255
+ }
256
+ /** Trim + length-cap a caller-supplied string for safe use in a dedup key. */
257
+ function capSegment(value, max) {
258
+ if (!value)
259
+ return '';
260
+ const trimmed = value.trim();
261
+ return trimmed.length > max ? trimmed.slice(0, max) : trimmed;
262
+ }
263
+ // -----------------------------------------------------------------------------
264
+ // Recording entry points (called from server.ts context callbacks)
265
+ // -----------------------------------------------------------------------------
266
+ /**
267
+ * Record a context evaluation outcome on {@link graphqlAuthContextEvaluationsTotal}.
268
+ * Use for the `authenticated` and `invalid_token` outcomes; the `no_principal`
269
+ * outcome is recorded (with identity logging) by {@link recordShadowAuthMiss}.
270
+ *
271
+ * @param transport - The transport the evaluation ran on.
272
+ * @param outcome - The evaluation outcome.
273
+ */
274
+ function recordAuthContextOutcome(transport, outcome) {
275
+ exports.graphqlAuthContextEvaluationsTotal.inc({ transport, outcome });
276
+ }
277
+ /**
278
+ * Record a would-deny (`no_principal`) request: increment the counter and, unless
279
+ * logging is disabled, emit a throttled structured identity log. NEVER blocks and
280
+ * NEVER throws — safe to call on the hot path of the `context()` callback.
281
+ *
282
+ * @param identity - Best-effort caller identity for the unauthenticated request.
283
+ */
284
+ function recordShadowAuthMiss(identity) {
285
+ exports.graphqlAuthContextEvaluationsTotal.inc({
286
+ transport: identity.transport,
287
+ outcome: 'no_principal',
288
+ });
289
+ if (isShadowAuthLoggingDisabled())
290
+ return;
291
+ const operationName = capSegment(identity.operationName, MAX_KEY_SEGMENT_LEN) || '<unnamed>';
292
+ const origin = capSegment(identity.origin, MAX_KEY_SEGMENT_LEN) || '<none>';
293
+ const key = `${identity.transport}|${operationName}|${origin}`;
294
+ if (!shouldEmitIdentityLog(key))
295
+ return;
296
+ logger_1.logger.warn('[graphql-auth-shadow] would-deny: unauthenticated /graphql request (allowing — no verified principal)', {
297
+ transport: identity.transport,
298
+ operationName,
299
+ origin,
300
+ ip: identity.ip,
301
+ userAgent: capSegment(identity.userAgent, MAX_UA_LEN) || undefined,
302
+ authHeaderPresent: identity.authHeaderPresent,
303
+ dedupWindowMs: exports.SHADOW_LOG_DEDUP_WINDOW_MS,
304
+ note: 'First occurrence of this (transport, operationName, origin) in the current dedup window. Every occurrence is counted on graphql_auth_context_evaluations_total{outcome="no_principal"}.',
305
+ });
306
+ }
307
+ /**
308
+ * Test-only reset of the throttled-log dedup store. Mirrors the token-verifier's
309
+ * `_resetGoogleAudienceCacheForTests` convention so tests can assert first-in-window
310
+ * emission deterministically without waiting out a real window.
311
+ *
312
+ * @internal
313
+ */
314
+ function _resetShadowAuthStateForTests() {
315
+ shadowLogStore.clear();
316
+ }
317
+ //# sourceMappingURL=graphql-auth-shadow.js.map
@@ -0,0 +1,194 @@
1
+ /**
2
+ * GraphQL context-layer authentication SHADOW observer.
3
+ *
4
+ * This is the transport/context-level counterpart to the resolver-level
5
+ * {@link ../auth/cortex-auth-checker.cortexAuthChecker}. The two observe DIFFERENT
6
+ * populations and are complementary:
7
+ *
8
+ * - `cortexAuthChecker` runs ONLY for `@Authorized()`-decorated fields (today:
9
+ * the 5 investor-relations models + delete mutations). It cannot see an
10
+ * unauthenticated request to any of the hundreds of auto-generated,
11
+ * undecorated CRUD fields — which is the overwhelming majority of live
12
+ * traffic (the platform, the account-audit scripts, and the engine all reach
13
+ * undecorated resolvers).
14
+ * - THIS observer runs in the `/graphql` HTTP + WebSocket `context()` callback,
15
+ * BEFORE any resolver, on EVERY request. It records whether a request arrived
16
+ * with a verified principal, with no principal, or with an invalid token —
17
+ * the true, complete denominator+numerator the enforcement decision needs.
18
+ *
19
+ * WHY (audit context): the `/graphql` `context()` currently lets a request with
20
+ * NO bearer token fall through as `{ principal: null }` and ALLOWS it. Requiring
21
+ * a principal at this layer (rejecting `null`) is the change that would break the
22
+ * entire product today (cookie-authenticated platform, token-less audit scripts,
23
+ * the engine's `SERVER_AUTH_TOKEN` gate). Before that enforcement can ever be
24
+ * flipped, we must first MEASURE, in production, exactly who reaches `/graphql`
25
+ * without a verified principal. This module provides that measurement WITHOUT
26
+ * changing behaviour: it counts and (throttled) logs would-denies and always
27
+ * returns control to the caller.
28
+ *
29
+ * SAFETY CONTRACT — observe-only, never blocks:
30
+ * - The Prometheus counter {@link graphqlAuthContextEvaluationsTotal} increments
31
+ * on every context evaluation, labelled by transport + outcome. It is the
32
+ * primary quantitative signal and carries only BOUNDED labels (never the
33
+ * attacker-controllable operation name / origin / IP).
34
+ * - For the `no_principal` outcome — the would-deny — a structured identity log
35
+ * is emitted, THROTTLED to the first occurrence of each
36
+ * `(transport, operationName, origin)` per dedup window. Unthrottled logging
37
+ * of every unauthenticated request would flood Cloud Logging and bury real
38
+ * warnings (audit B01-backend-legacy-10); the counter carries the per-request
39
+ * cardinality instead.
40
+ * - The dedup store is capped and rotates novel keys into a shared overflow
41
+ * bucket so an attacker rotating spoofed origins/operation names cannot grow
42
+ * memory without bound (audit B01-backend-legacy-12).
43
+ *
44
+ * @see src/auth/cortex-auth-checker.ts for the resolver-level shadow checker.
45
+ * @see docs/security/2026-08-23-graphql-auth-enforcement-runbook.md for the
46
+ * staged enforcement plan this observer feeds.
47
+ */
48
+ import { Counter, Gauge } from 'prom-client';
49
+ /** The GraphQL transport a context evaluation ran on. */
50
+ export type GraphqlTransport = 'http' | 'ws';
51
+ /**
52
+ * Outcome of a `/graphql` `context()` evaluation.
53
+ *
54
+ * - `authenticated` — a verified {@link ../auth/token-verifier.BackendPrincipal}
55
+ * was attached.
56
+ * - `no_principal` — no bearer token was presented; the request falls through
57
+ * with `principal: null`. This is the WOULD-DENY case under principal-required
58
+ * enforcement — the sole behaviour the enforcement flip changes.
59
+ * - `invalid_token` — a token was presented but failed verification. This is
60
+ * ALREADY rejected today (HTTP 401 / WS close); recorded here only to complete
61
+ * the denominator.
62
+ */
63
+ export type AuthContextOutcome = 'authenticated' | 'no_principal' | 'invalid_token';
64
+ /**
65
+ * Caller identity captured for a would-deny (`no_principal`) request. Every field
66
+ * is best-effort and may be absent (server-to-server callers send no `origin`;
67
+ * the WS operation name is not always known at context time). Nothing here is
68
+ * ever used as a Prometheus label — only in the throttled structured log.
69
+ */
70
+ export interface ShadowAuthIdentity {
71
+ /** Transport the request arrived on. */
72
+ transport: GraphqlTransport;
73
+ /** GraphQL operation name, when resolvable from the request body / args. */
74
+ operationName?: string;
75
+ /** `Origin` header — distinguishes browser callers (platform) from scripts. */
76
+ origin?: string;
77
+ /** Client IP, as resolved by the caller (Express `req.ip` honours trust-proxy). */
78
+ ip?: string;
79
+ /** `User-Agent` header, when present. */
80
+ userAgent?: string;
81
+ /**
82
+ * Whether an `Authorization` header was present at all. `true` here with a
83
+ * `no_principal` outcome means the header was present but not a `Bearer <token>`
84
+ * (or an empty bearer) — a distinct, actionable misconfiguration.
85
+ */
86
+ authHeaderPresent: boolean;
87
+ }
88
+ /**
89
+ * Counts EVERY `/graphql` context evaluation, labelled by {@link GraphqlTransport}
90
+ * and {@link AuthContextOutcome}. This single series is both the denominator
91
+ * (total requests seen) and the numerator (`outcome="no_principal"` = would-denies).
92
+ *
93
+ * Graduation rule for the runbook: the enforcement flip is safe to consider only
94
+ * once `outcome="no_principal"` has been driven to (effectively) zero for the
95
+ * transport being enforced, sustained across a full trading week — i.e. every
96
+ * legitimate caller has been migrated to presenting a verified principal.
97
+ *
98
+ * Labels are deliberately BOUNDED (2 transports x 3 outcomes = 6 series). The
99
+ * high-cardinality identity (operation name, origin, IP) lives only in the
100
+ * throttled log, never as a metric label — an unauthenticated caller controls
101
+ * those strings and could otherwise explode metric cardinality.
102
+ */
103
+ export declare const graphqlAuthContextEvaluationsTotal: Counter<"outcome" | "transport">;
104
+ /**
105
+ * Current tracked-key cardinality of the throttled-log dedup store. Bounds
106
+ * visibility into the store ahead of the {@link MAX_TRACKED_SHADOW_KEYS} cap
107
+ * (audit B01-backend-legacy-12).
108
+ */
109
+ export declare const graphqlAuthShadowTrackedKeys: Gauge<string>;
110
+ /**
111
+ * Environment variable that DISABLES the throttled identity log. Absent (the
112
+ * default) keeps logging ON. Set to `true`/`1` to silence the per-caller log
113
+ * lines if they ever become operationally noisy — the {@link
114
+ * graphqlAuthContextEvaluationsTotal} counter continues unaffected, so the
115
+ * quantitative signal is never lost.
116
+ */
117
+ export declare const GRAPHQL_AUTH_SHADOW_LOG_DISABLED_ENV = "GRAPHQL_AUTH_SHADOW_LOG_DISABLED";
118
+ /**
119
+ * Whether the throttled identity log is disabled. Read fresh each call (a cheap
120
+ * env read) so it can be toggled operationally without a restart — matching the
121
+ * shadow-flag convention used by the AuthChecker and rate limiter.
122
+ *
123
+ * @param env - Environment source (defaults to `process.env`); injectable for tests.
124
+ * @returns `true` only when the flag is explicitly `true`/`1`.
125
+ */
126
+ export declare function isShadowAuthLoggingDisabled(env?: Record<string, string | undefined>): boolean;
127
+ /**
128
+ * Dedup window for the identity log: at most one line per distinct
129
+ * `(transport, operationName, origin)` key per window. Sized long (10 min) so a
130
+ * high-volume unauthenticated caller (e.g. the whole platform) contributes ~one
131
+ * line per window rather than one per request.
132
+ */
133
+ export declare const SHADOW_LOG_DEDUP_WINDOW_MS: number;
134
+ /**
135
+ * Normalise a raw header value (`string | string[] | undefined`, arriving typed
136
+ * as `unknown`) to a single string. Node folds repeated headers into an array;
137
+ * we keep the first value.
138
+ *
139
+ * @param value - Raw header value.
140
+ * @returns The string value, or `undefined` when absent/unusable.
141
+ */
142
+ export declare function headerToString(value: unknown): string | undefined;
143
+ /**
144
+ * Extract a GraphQL operation name from a parsed HTTP request body.
145
+ *
146
+ * @param body - The JSON-parsed `/graphql` POST body (typed `unknown`).
147
+ * @returns The `operationName`, or `undefined` when absent/empty.
148
+ */
149
+ export declare function extractOperationName(body: unknown): string | undefined;
150
+ /**
151
+ * Extract a GraphQL operation name from graphql-ws `ExecutionArgs`.
152
+ *
153
+ * @param args - The third argument to the graphql-ws `context` callback (typed `unknown`).
154
+ * @returns The `operationName`, or `undefined` when absent/empty.
155
+ */
156
+ export declare function extractOperationNameFromArgs(args: unknown): string | undefined;
157
+ /**
158
+ * Extract `origin` / `userAgent` / `ip` from the graphql-ws `ctx.extra` object
159
+ * (`{ request, socket }` for the `ws` integration), tolerating any shape.
160
+ *
161
+ * @param extra - The graphql-ws context `extra` (typed `unknown`).
162
+ * @returns Best-effort header identity for the WebSocket upgrade request.
163
+ */
164
+ export declare function extractHeaderIdentityFromWsExtra(extra: unknown): {
165
+ origin?: string;
166
+ userAgent?: string;
167
+ ip?: string;
168
+ };
169
+ /**
170
+ * Record a context evaluation outcome on {@link graphqlAuthContextEvaluationsTotal}.
171
+ * Use for the `authenticated` and `invalid_token` outcomes; the `no_principal`
172
+ * outcome is recorded (with identity logging) by {@link recordShadowAuthMiss}.
173
+ *
174
+ * @param transport - The transport the evaluation ran on.
175
+ * @param outcome - The evaluation outcome.
176
+ */
177
+ export declare function recordAuthContextOutcome(transport: GraphqlTransport, outcome: AuthContextOutcome): void;
178
+ /**
179
+ * Record a would-deny (`no_principal`) request: increment the counter and, unless
180
+ * logging is disabled, emit a throttled structured identity log. NEVER blocks and
181
+ * NEVER throws — safe to call on the hot path of the `context()` callback.
182
+ *
183
+ * @param identity - Best-effort caller identity for the unauthenticated request.
184
+ */
185
+ export declare function recordShadowAuthMiss(identity: ShadowAuthIdentity): void;
186
+ /**
187
+ * Test-only reset of the throttled-log dedup store. Mirrors the token-verifier's
188
+ * `_resetGoogleAudienceCacheForTests` convention so tests can assert first-in-window
189
+ * emission deterministically without waiting out a real window.
190
+ *
191
+ * @internal
192
+ */
193
+ export declare function _resetShadowAuthStateForTests(): void;
194
+ //# sourceMappingURL=graphql-auth-shadow.d.ts.map
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ /**
3
+ * Who may write an entitlement row — pure decision logic.
4
+ *
5
+ * `OrgMembership.role` and `FundAssignment.role` are the authority the rest of
6
+ * the system reads: the platform derives a person's personas from them at
7
+ * sign-in, the tenancy scope derives which organizations and funds they reach,
8
+ * and fund entitlement admits writes to every brokerage account bridged to a
9
+ * fund. Being inside a tenant is therefore not enough to write one of these
10
+ * rows. A plain member who could write them could make themselves OWNER of
11
+ * their organization, or MANAGER of any fund in it, and every downstream
12
+ * authority would follow.
13
+ *
14
+ * A user principal may write an entitlement row only with authority over the
15
+ * tenant the row belongs to:
16
+ *
17
+ * - **OrgMembership** — the caller holds OWNER or ADMIN in that organization.
18
+ * A row whose role is OWNER, before or after the write, needs OWNER: an
19
+ * ADMIN who could grant OWNER could grant it to themselves, and an ADMIN who
20
+ * could demote or remove an OWNER could take the organization from them.
21
+ * - **FundAssignment** — the caller holds OWNER or ADMIN in the fund's
22
+ * organization, or a MANAGER assignment on that same fund. MANAGER is the
23
+ * highest fund role and is the role that runs the fund's team, so admitting
24
+ * it lets no one rise above what they already hold, and it confers nothing
25
+ * on any other fund.
26
+ *
27
+ * One self-service write is admitted without that authority, because the
28
+ * backend can prove from its own rows that nothing is being taken from
29
+ * anyone: the **first owner**. A caller makes themselves OWNER of an
30
+ * organization that is not deleted and has no members and no funds. That is
31
+ * the state an organization is in the moment its creator has written it; once
32
+ * anyone holds a membership, or the organization holds a fund, the exception
33
+ * closes, and an organization with neither has nothing in it to claim.
34
+ *
35
+ * Joining an organization any other way (an invitation, an email-domain
36
+ * match) rests on proof the backend cannot verify from rows the caller is
37
+ * unable to write — an invitation is a single-use token, and a user's email
38
+ * address is a column of their own row — so those memberships are written by
39
+ * a service principal after the platform has checked the proof.
40
+ *
41
+ * Everything here is decided from facts read from the database for this
42
+ * mutation (`src/middleware/mutation-membership-facts.ts`), never from the
43
+ * token's claims.
44
+ *
45
+ * @module auth/membership-write-authority
46
+ */
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.ADMITTING_MEMBERSHIP_VERDICTS = exports.FUND_MANAGER_ROLE = exports.ORG_MANAGEMENT_ROLES = exports.ORG_OWNER_ROLE = void 0;
49
+ exports.isMembershipModel = isMembershipModel;
50
+ exports.isFirstOwnerCandidate = isFirstOwnerCandidate;
51
+ exports.decideMembershipWrite = decideMembershipWrite;
52
+ /** Whether a model is one of the entitlement models this module decides. */
53
+ function isMembershipModel(model) {
54
+ return model === 'OrgMembership' || model === 'FundAssignment';
55
+ }
56
+ /** The organization role that owns an organization. */
57
+ exports.ORG_OWNER_ROLE = 'OWNER';
58
+ /** Organization roles that may manage memberships and fund assignments. */
59
+ exports.ORG_MANAGEMENT_ROLES = new Set([
60
+ exports.ORG_OWNER_ROLE,
61
+ 'ADMIN',
62
+ ]);
63
+ /** The fund role that may manage its own fund's assignments. */
64
+ exports.FUND_MANAGER_ROLE = 'MANAGER';
65
+ /** The verdicts that admit the write. */
66
+ exports.ADMITTING_MEMBERSHIP_VERDICTS = new Set([
67
+ 'membership_org_admin',
68
+ 'membership_fund_manager',
69
+ 'membership_first_owner',
70
+ ]);
71
+ /**
72
+ * Whether a write could be a first-owner create: the caller making
73
+ * themselves a member of an organization they do not belong to. The
74
+ * first-owner facts are read only for this shape.
75
+ */
76
+ function isFirstOwnerCandidate(model, write, callerId, standing) {
77
+ return (model === 'OrgMembership' &&
78
+ write.side === 'create' &&
79
+ write.memberUserId === callerId &&
80
+ standing.orgRole === null);
81
+ }
82
+ /** Whether a create makes the caller the plain first OWNER of an empty organization. */
83
+ function isFirstOwner(write, facts) {
84
+ return (write.rolesTouched.length === 1 &&
85
+ write.rolesTouched[0] === exports.ORG_OWNER_ROLE &&
86
+ !write.setsPermissions &&
87
+ !facts.organizationDeleted &&
88
+ facts.organizationMemberCount === 0 &&
89
+ facts.organizationFundCount === 0);
90
+ }
91
+ /**
92
+ * Decide one side of an entitlement write. Pure; performs no I/O.
93
+ *
94
+ * @param model - The entitlement model written.
95
+ * @param write - What the write does to the row.
96
+ * @param callerId - The user principal's subject.
97
+ * @param standing - What the caller holds in the row's tenant.
98
+ * @param firstOwner - The first-owner facts, read only for an
99
+ * {@link isFirstOwnerCandidate} write; `null` otherwise.
100
+ * @returns The verdict.
101
+ */
102
+ function decideMembershipWrite(model, write, callerId, standing, firstOwner) {
103
+ const { orgRole, fundRole } = standing;
104
+ if (model === 'OrgMembership') {
105
+ if (orgRole === exports.ORG_OWNER_ROLE)
106
+ return 'membership_org_admin';
107
+ if (orgRole !== null && exports.ORG_MANAGEMENT_ROLES.has(orgRole)) {
108
+ return write.rolesTouched.includes(exports.ORG_OWNER_ROLE)
109
+ ? 'membership_owner_requires_owner'
110
+ : 'membership_org_admin';
111
+ }
112
+ if (orgRole !== null)
113
+ return 'membership_role_insufficient';
114
+ if (firstOwner !== null &&
115
+ isFirstOwnerCandidate(model, write, callerId, standing) &&
116
+ isFirstOwner(write, firstOwner)) {
117
+ return 'membership_first_owner';
118
+ }
119
+ return 'tenant_out_of_scope';
120
+ }
121
+ if (orgRole !== null && exports.ORG_MANAGEMENT_ROLES.has(orgRole)) {
122
+ return 'membership_org_admin';
123
+ }
124
+ if (fundRole === exports.FUND_MANAGER_ROLE)
125
+ return 'membership_fund_manager';
126
+ if (orgRole !== null || fundRole !== null) {
127
+ return 'membership_role_insufficient';
128
+ }
129
+ return 'tenant_out_of_scope';
130
+ }
131
+ //# sourceMappingURL=membership-write-authority.js.map