@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,182 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.checkQueryComplexity = checkQueryComplexity;
4
+ exports.createQueryComplexityPlugin = createQueryComplexityPlugin;
5
+ const graphql_query_complexity_1 = require("graphql-query-complexity");
6
+ const logger_1 = require("../utils/logger.cjs");
7
+ /**
8
+ * Default query complexity limits per authentication level.
9
+ * These can be overridden via environment variables.
10
+ */
11
+ const DEFAULT_MAX_COMPLEXITY_AUTHENTICATED = 1000;
12
+ const DEFAULT_MAX_COMPLEXITY_UNAUTHENTICATED = 200;
13
+ const DEFAULT_MAX_DEPTH = 10;
14
+ /**
15
+ * Resolves the maximum allowed query complexity from environment variables or defaults.
16
+ *
17
+ * @param isAuthenticated - Whether the request is from an authenticated user
18
+ * @returns The maximum allowed complexity score
19
+ */
20
+ function getMaxComplexity(isAuthenticated) {
21
+ if (isAuthenticated) {
22
+ const envValue = process.env.GRAPHQL_MAX_COMPLEXITY_AUTH;
23
+ if (envValue) {
24
+ const parsed = parseInt(envValue, 10);
25
+ if (!isNaN(parsed) && parsed > 0)
26
+ return parsed;
27
+ }
28
+ return DEFAULT_MAX_COMPLEXITY_AUTHENTICATED;
29
+ }
30
+ const envValue = process.env.GRAPHQL_MAX_COMPLEXITY_UNAUTH;
31
+ if (envValue) {
32
+ const parsed = parseInt(envValue, 10);
33
+ if (!isNaN(parsed) && parsed > 0)
34
+ return parsed;
35
+ }
36
+ return DEFAULT_MAX_COMPLEXITY_UNAUTHENTICATED;
37
+ }
38
+ /**
39
+ * Resolves the maximum allowed query depth.
40
+ */
41
+ function getMaxDepth() {
42
+ const envValue = process.env.GRAPHQL_MAX_DEPTH;
43
+ if (envValue) {
44
+ const parsed = parseInt(envValue, 10);
45
+ if (!isNaN(parsed) && parsed > 0)
46
+ return parsed;
47
+ }
48
+ return DEFAULT_MAX_DEPTH;
49
+ }
50
+ /**
51
+ * Computes the complexity of a GraphQL document against a schema.
52
+ *
53
+ * Uses two estimators:
54
+ * 1. fieldExtensionsEstimator: Reads complexity from field extensions (set via schema directives)
55
+ * 2. simpleEstimator: Assigns a default cost of 1 per field as fallback
56
+ *
57
+ * @param schema - The GraphQL schema
58
+ * @param document - The parsed GraphQL document (AST)
59
+ * @param variables - Query variables (used for list size estimation)
60
+ * @param isAuthenticated - Whether the request is authenticated (affects limits)
61
+ * @returns The complexity check result
62
+ */
63
+ function checkQueryComplexity(schema, document, variables, isAuthenticated) {
64
+ const maxComplexity = getMaxComplexity(isAuthenticated);
65
+ try {
66
+ const complexity = (0, graphql_query_complexity_1.getComplexity)({
67
+ schema,
68
+ query: document,
69
+ variables,
70
+ estimators: [
71
+ (0, graphql_query_complexity_1.fieldExtensionsEstimator)(),
72
+ (0, graphql_query_complexity_1.simpleEstimator)({ defaultComplexity: 1 }),
73
+ ],
74
+ });
75
+ return {
76
+ complexity,
77
+ exceeded: complexity > maxComplexity,
78
+ maxComplexity,
79
+ };
80
+ }
81
+ catch (estimationError) {
82
+ logger_1.logger.warn('Failed to estimate query complexity', {
83
+ error: estimationError instanceof Error
84
+ ? estimationError.message
85
+ : String(estimationError),
86
+ });
87
+ // On failure, allow the query to proceed to avoid blocking legitimate requests
88
+ return {
89
+ complexity: 0,
90
+ exceeded: false,
91
+ maxComplexity,
92
+ };
93
+ }
94
+ }
95
+ /**
96
+ * Checks query depth by counting nested selections.
97
+ *
98
+ * @param document - The parsed GraphQL document (AST)
99
+ * @returns The maximum depth found in the query
100
+ */
101
+ function computeQueryDepth(document) {
102
+ let maxDepth = 0;
103
+ function traverse(node, depth) {
104
+ if (depth > maxDepth) {
105
+ maxDepth = depth;
106
+ }
107
+ if (node.selectionSet) {
108
+ for (const selection of node.selectionSet.selections) {
109
+ traverse(selection, depth + 1);
110
+ }
111
+ }
112
+ }
113
+ for (const definition of document.definitions) {
114
+ traverse(definition, 0);
115
+ }
116
+ return maxDepth;
117
+ }
118
+ /**
119
+ * Creates an Apollo Server plugin that enforces query complexity and depth limits.
120
+ *
121
+ * The plugin runs before query execution and rejects queries that exceed
122
+ * configured complexity or depth thresholds.
123
+ *
124
+ * Environment variables:
125
+ * - GRAPHQL_MAX_COMPLEXITY_AUTH: Max complexity for authenticated users (default: 1000)
126
+ * - GRAPHQL_MAX_COMPLEXITY_UNAUTH: Max complexity for unauthenticated users (default: 200)
127
+ * - GRAPHQL_MAX_DEPTH: Max query depth (default: 10)
128
+ * - GRAPHQL_COMPLEXITY_ENABLED: Explicit on/off ('true'/'false'). Defaults to on in production/staging.
129
+ *
130
+ * @param schema - The GraphQL schema to validate against
131
+ * @returns Apollo Server plugin configuration
132
+ */
133
+ function createQueryComplexityPlugin(schema) {
134
+ const isEnabled = () => {
135
+ const explicitSetting = process.env.GRAPHQL_COMPLEXITY_ENABLED;
136
+ if (explicitSetting !== undefined) {
137
+ return explicitSetting === 'true' || explicitSetting === '1';
138
+ }
139
+ const env = process.env.NODE_ENV || 'development';
140
+ return env === 'production' || env === 'staging';
141
+ };
142
+ return {
143
+ async requestDidStart() {
144
+ return {
145
+ async didResolveOperation(requestContext) {
146
+ if (!isEnabled())
147
+ return;
148
+ const { document, request, contextValue } = requestContext;
149
+ const variables = (request.variables || {});
150
+ const isAuthenticated = Boolean(contextValue.user);
151
+ // Check depth limit
152
+ const maxDepth = getMaxDepth();
153
+ const depth = computeQueryDepth(document);
154
+ if (depth > maxDepth) {
155
+ logger_1.logger.warn('Query depth exceeded', {
156
+ depth,
157
+ maxDepth,
158
+ isAuthenticated,
159
+ });
160
+ throw new Error(`Query depth of ${depth} exceeds maximum allowed depth of ${maxDepth}`);
161
+ }
162
+ // Check complexity limit
163
+ const result = checkQueryComplexity(schema, document, variables, isAuthenticated);
164
+ if (result.exceeded) {
165
+ logger_1.logger.warn('Query complexity exceeded', {
166
+ complexity: result.complexity,
167
+ maxComplexity: result.maxComplexity,
168
+ isAuthenticated,
169
+ });
170
+ throw new Error(`Query complexity of ${result.complexity} exceeds maximum allowed complexity of ${result.maxComplexity}`);
171
+ }
172
+ logger_1.logger.debug('Query complexity check passed', {
173
+ complexity: result.complexity,
174
+ maxComplexity: result.maxComplexity,
175
+ depth,
176
+ });
177
+ },
178
+ };
179
+ },
180
+ };
181
+ }
182
+ //# sourceMappingURL=query-complexity.js.map
@@ -0,0 +1,56 @@
1
+ import { GraphQLSchema, DocumentNode } from 'graphql';
2
+ /**
3
+ * Result of a query complexity check.
4
+ */
5
+ interface ComplexityCheckResult {
6
+ /** The computed complexity score */
7
+ complexity: number;
8
+ /** Whether the query exceeds the maximum allowed complexity */
9
+ exceeded: boolean;
10
+ /** The maximum allowed complexity for this request */
11
+ maxComplexity: number;
12
+ }
13
+ /**
14
+ * Computes the complexity of a GraphQL document against a schema.
15
+ *
16
+ * Uses two estimators:
17
+ * 1. fieldExtensionsEstimator: Reads complexity from field extensions (set via schema directives)
18
+ * 2. simpleEstimator: Assigns a default cost of 1 per field as fallback
19
+ *
20
+ * @param schema - The GraphQL schema
21
+ * @param document - The parsed GraphQL document (AST)
22
+ * @param variables - Query variables (used for list size estimation)
23
+ * @param isAuthenticated - Whether the request is authenticated (affects limits)
24
+ * @returns The complexity check result
25
+ */
26
+ export declare function checkQueryComplexity(schema: GraphQLSchema, document: DocumentNode, variables: Record<string, unknown>, isAuthenticated: boolean): ComplexityCheckResult;
27
+ /**
28
+ * Creates an Apollo Server plugin that enforces query complexity and depth limits.
29
+ *
30
+ * The plugin runs before query execution and rejects queries that exceed
31
+ * configured complexity or depth thresholds.
32
+ *
33
+ * Environment variables:
34
+ * - GRAPHQL_MAX_COMPLEXITY_AUTH: Max complexity for authenticated users (default: 1000)
35
+ * - GRAPHQL_MAX_COMPLEXITY_UNAUTH: Max complexity for unauthenticated users (default: 200)
36
+ * - GRAPHQL_MAX_DEPTH: Max query depth (default: 10)
37
+ * - GRAPHQL_COMPLEXITY_ENABLED: Explicit on/off ('true'/'false'). Defaults to on in production/staging.
38
+ *
39
+ * @param schema - The GraphQL schema to validate against
40
+ * @returns Apollo Server plugin configuration
41
+ */
42
+ export declare function createQueryComplexityPlugin(schema: GraphQLSchema): {
43
+ requestDidStart: () => Promise<{
44
+ didResolveOperation: (requestContext: {
45
+ document: DocumentNode;
46
+ request: {
47
+ variables?: Record<string, unknown> | null;
48
+ };
49
+ contextValue: {
50
+ user?: unknown;
51
+ };
52
+ }) => Promise<void>;
53
+ }>;
54
+ };
55
+ export {};
56
+ //# sourceMappingURL=query-complexity.d.ts.map
@@ -0,0 +1,223 @@
1
+ "use strict";
2
+ // CORTEX-P0-001: mounted in server.ts as
3
+ // app.use('/graphql', cors, graphqlRateLimiter, …) // GraphQL surface (after CORS)
4
+ // app.use('/api', authRateLimiter) // authenticated Express surface
5
+ // SHADOW-FIRST: 429 enforcement is gated behind CORTEX_RATE_LIMIT_ENFORCE.
6
+ // While OFF (default), the limiters observe + count requests that WOULD be
7
+ // blocked but never touch the response — live behaviour is byte-identical.
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.authRateLimiter = exports.graphqlRateLimiter = exports.cortexRateLimitStoreKeys = exports.cortexRateLimitBlockedTotal = exports.cortexRateLimitWouldBlockTotal = exports.CORTEX_RATE_LIMIT_ENFORCE_ENV = void 0;
10
+ exports.isRateLimitEnforced = isRateLimitEnforced;
11
+ exports.createRateLimiter = createRateLimiter;
12
+ const prom_client_1 = require("prom-client");
13
+ const metrics_1 = require("../config/metrics.cjs");
14
+ const logger_1 = require("../utils/logger.cjs");
15
+ const rate_tier_1 = require("./rate-tier.cjs");
16
+ /**
17
+ * Environment variable gating 429 enforcement. When set to `true`/`1`, the
18
+ * limiters block over-limit requests with HTTP 429. Unset or any other value
19
+ * keeps them in SHADOW mode (observe + count + always proceed).
20
+ */
21
+ exports.CORTEX_RATE_LIMIT_ENFORCE_ENV = 'CORTEX_RATE_LIMIT_ENFORCE';
22
+ /**
23
+ * Whether rate-limit 429 enforcement is ON. Read fresh on each request (a cheap
24
+ * env read) so the shadow→enforce graduation can be flipped operationally
25
+ * without a restart. Defaults to OFF (shadow) for any unset/unrecognised value.
26
+ *
27
+ * @param env - Environment source (defaults to `process.env`); injectable for tests.
28
+ * @returns `true` only when the flag is explicitly `true`/`1`.
29
+ */
30
+ function isRateLimitEnforced(env = process.env) {
31
+ var _a;
32
+ const raw = ((_a = env[exports.CORTEX_RATE_LIMIT_ENFORCE_ENV]) !== null && _a !== void 0 ? _a : '').trim().toLowerCase();
33
+ return raw === 'true' || raw === '1';
34
+ }
35
+ /**
36
+ * Counts requests that rate limiting WOULD block (HTTP 429) while in SHADOW
37
+ * mode. This is the signal proving whether flipping
38
+ * `CORTEX_RATE_LIMIT_ENFORCE` to enforce would reject legitimate traffic.
39
+ * Labelled by the `limiter` name (`graphql`/`auth`) and the request `tier`
40
+ * (`auth`/`anon`). Real enforce-mode denials count on
41
+ * {@link cortexRateLimitBlockedTotal} instead, keeping the observed-only and
42
+ * actually-blocked series distinct (audit B01-backend-legacy-14).
43
+ */
44
+ exports.cortexRateLimitWouldBlockTotal = new prom_client_1.Counter({
45
+ name: 'cortex_rate_limit_would_block_total',
46
+ help: 'Requests rate limiting would block (429), by limiter and tier (shadow mode only; real denials count on cortex_rate_limit_blocked_total)',
47
+ labelNames: ['limiter', 'tier'],
48
+ registers: [metrics_1.metricsRegistry],
49
+ });
50
+ /**
51
+ * Counts requests actually blocked with HTTP 429 in ENFORCE mode. Kept as a
52
+ * separate series from {@link cortexRateLimitWouldBlockTotal} so shadow
53
+ * observations and real blocks never mix (audit B01-backend-legacy-14).
54
+ */
55
+ exports.cortexRateLimitBlockedTotal = new prom_client_1.Counter({
56
+ name: 'cortex_rate_limit_blocked_total',
57
+ help: 'Requests actually blocked with HTTP 429, by limiter and tier (enforce mode only)',
58
+ labelNames: ['limiter', 'tier'],
59
+ registers: [metrics_1.metricsRegistry],
60
+ });
61
+ /**
62
+ * Tracked bucket-key cardinality per limiter store. Bounds memory ahead of the
63
+ * trust-proxy fix, after which the identifier derives from X-Forwarded-For and
64
+ * an attacker rotating spoofed values could otherwise mint unbounded entries
65
+ * (audit B01-backend-legacy-12).
66
+ */
67
+ exports.cortexRateLimitStoreKeys = new prom_client_1.Gauge({
68
+ name: 'cortex_rate_limit_store_keys',
69
+ help: 'Current tracked bucket-key cardinality per limiter store',
70
+ labelNames: ['limiter'],
71
+ registers: [metrics_1.metricsRegistry],
72
+ });
73
+ /** Sweep cadence for expired bucket entries. */
74
+ const STORE_SWEEP_INTERVAL_MS = 60000;
75
+ /**
76
+ * Default cap on distinct bucket keys per limiter store. Past the cap, new
77
+ * identifiers aggregate into a shared per-tier overflow bucket instead of
78
+ * allocating — bounding memory under identifier-rotation abuse.
79
+ */
80
+ const DEFAULT_MAX_TRACKED_KEYS = 100000;
81
+ /** Bucket-key prefix used once the store cardinality cap is reached. */
82
+ const OVERFLOW_KEY_PREFIX = 'overflow';
83
+ /**
84
+ * Creates an in-memory rate limiter middleware with separate limits for
85
+ * verified (auth) and anonymous requests.
86
+ *
87
+ * Bucketing: verified callers are keyed per principal (`sub:<sub>`); anonymous
88
+ * callers are keyed by client IP, which resolves correctly behind the LB only
89
+ * with `trust proxy` configured in server.ts (audit B01-backend-legacy-02).
90
+ * The `auth` tier requires actual offline verification — a fabricated
91
+ * JWT-shaped header no longer earns the higher budget (B01-backend-legacy-09).
92
+ * CORS preflights (`OPTIONS`) are never counted (B01-backend-legacy-11).
93
+ *
94
+ * Response headers (enforce mode only, when standardHeaders is enabled):
95
+ * X-RateLimit-Limit - maximum requests allowed in the current window
96
+ * X-RateLimit-Remaining - requests remaining in the current window
97
+ * X-RateLimit-Reset - seconds until the current window resets
98
+ * Retry-After - seconds to wait before retrying (only on 429)
99
+ *
100
+ * @param config - Rate limit configuration.
101
+ * @returns Express middleware function.
102
+ */
103
+ function createRateLimiter(config) {
104
+ var _a;
105
+ const store = new Map();
106
+ const maxTrackedKeys = (_a = config.maxTrackedKeys) !== null && _a !== void 0 ? _a : DEFAULT_MAX_TRACKED_KEYS;
107
+ // Sweep expired entries every minute. `unref()` so an importing process
108
+ // (tests, one-off scripts) is never kept alive by the sweeper
109
+ // (audit B01-backend-legacy-12).
110
+ setInterval(() => {
111
+ const now = Date.now();
112
+ for (const [key, entry] of store) {
113
+ if (entry.resetTime < now) {
114
+ store.delete(key);
115
+ }
116
+ }
117
+ exports.cortexRateLimitStoreKeys.set({ limiter: config.name }, store.size);
118
+ }, STORE_SWEEP_INTERVAL_MS).unref();
119
+ return (req, res, next) => {
120
+ var _a, _b;
121
+ // CORS preflights carry no credentials and must not consume rate budget
122
+ // (audit B01-backend-legacy-11).
123
+ if (req.method === 'OPTIONS') {
124
+ next();
125
+ return;
126
+ }
127
+ const { tier, principalKey } = (0, rate_tier_1.resolveRateTier)(req);
128
+ const identifier = (_b = (_a = principalKey !== null && principalKey !== void 0 ? principalKey : req.ip) !== null && _a !== void 0 ? _a : req.socket.remoteAddress) !== null && _b !== void 0 ? _b : 'unknown';
129
+ const effectiveMax = tier === 'auth' ? config.maxAuthenticated : config.maxUnauthenticated;
130
+ let storeKey = `${identifier}:${tier}`;
131
+ const now = Date.now();
132
+ // Cardinality cap: aggregate novel identifiers into a shared per-tier
133
+ // overflow bucket rather than growing without bound
134
+ // (audit B01-backend-legacy-12).
135
+ if (!store.has(storeKey) && store.size >= maxTrackedKeys) {
136
+ storeKey = `${OVERFLOW_KEY_PREFIX}:${tier}`;
137
+ }
138
+ const existing = store.get(storeKey);
139
+ let current;
140
+ if (!existing || existing.resetTime < now) {
141
+ current = { count: 1, resetTime: now + config.windowMs };
142
+ store.set(storeKey, current);
143
+ }
144
+ else {
145
+ existing.count += 1;
146
+ current = existing;
147
+ }
148
+ const remaining = Math.max(0, effectiveMax - current.count);
149
+ const resetSeconds = Math.ceil((current.resetTime - now) / 1000);
150
+ const overLimit = current.count > effectiveMax;
151
+ // SHADOW mode (default): observe + count over-limit requests but NEVER touch
152
+ // the response — no rate-limit headers, no 429. This keeps live behaviour
153
+ // byte-identical until CORTEX_RATE_LIMIT_ENFORCE is flipped on.
154
+ if (!isRateLimitEnforced()) {
155
+ if (overLimit) {
156
+ exports.cortexRateLimitWouldBlockTotal.inc({ limiter: config.name, tier });
157
+ // Log only the FIRST over-limit request per (bucket, window) — the
158
+ // counter carries per-request cardinality; unthrottled logging floods
159
+ // Cloud Logging and buries real warnings (audit B01-backend-legacy-10).
160
+ if (current.count === effectiveMax + 1) {
161
+ logger_1.logger.warn('[cortex-rate-limit] shadow would-block (allowing)', {
162
+ limiter: config.name,
163
+ identifier,
164
+ tier,
165
+ count: current.count,
166
+ limit: effectiveMax,
167
+ resetSeconds,
168
+ });
169
+ }
170
+ }
171
+ next();
172
+ return;
173
+ }
174
+ // ENFORCE mode: emit the informational rate-limit headers and block
175
+ // over-limit requests with HTTP 429.
176
+ if (config.standardHeaders !== false) {
177
+ res.setHeader('X-RateLimit-Limit', effectiveMax.toString());
178
+ res.setHeader('X-RateLimit-Remaining', remaining.toString());
179
+ res.setHeader('X-RateLimit-Reset', resetSeconds.toString());
180
+ }
181
+ if (overLimit) {
182
+ // Include Retry-After header on 429 responses (RFC 6585 / RFC 7231)
183
+ res.setHeader('Retry-After', resetSeconds.toString());
184
+ exports.cortexRateLimitBlockedTotal.inc({ limiter: config.name, tier });
185
+ res.status(429).json(config.message);
186
+ return;
187
+ }
188
+ next();
189
+ };
190
+ }
191
+ /**
192
+ * Rate limiter for GraphQL endpoint.
193
+ *
194
+ * Verified requests: 1000 requests per 15 minutes (configurable via RATE_LIMIT_MAX)
195
+ * Anonymous requests: 200 requests per 15 minutes (configurable via RATE_LIMIT_MAX_UNAUTH)
196
+ */
197
+ exports.graphqlRateLimiter = createRateLimiter({
198
+ name: 'graphql',
199
+ windowMs: 15 * 60 * 1000, // 15 minutes
200
+ maxAuthenticated: parseInt(process.env.RATE_LIMIT_MAX || '1000', 10),
201
+ maxUnauthenticated: parseInt(process.env.RATE_LIMIT_MAX_UNAUTH || '200', 10),
202
+ standardHeaders: true,
203
+ legacyHeaders: false,
204
+ message: {
205
+ errors: [{ message: 'Too many requests, please try again later.' }],
206
+ },
207
+ });
208
+ /**
209
+ * Rate limiter for authentication endpoints.
210
+ *
211
+ * Verified requests: 50 requests per 15 minutes
212
+ * Anonymous requests: 20 requests per 15 minutes
213
+ */
214
+ exports.authRateLimiter = createRateLimiter({
215
+ name: 'auth',
216
+ windowMs: 15 * 60 * 1000, // 15 minutes
217
+ maxAuthenticated: 50,
218
+ maxUnauthenticated: 20,
219
+ standardHeaders: true,
220
+ legacyHeaders: false,
221
+ message: { errors: [{ message: 'Too many authentication attempts.' }] },
222
+ });
223
+ //# sourceMappingURL=rate-limiter.js.map
@@ -0,0 +1,93 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+ import { Counter, Gauge } from 'prom-client';
3
+ /**
4
+ * Environment variable gating 429 enforcement. When set to `true`/`1`, the
5
+ * limiters block over-limit requests with HTTP 429. Unset or any other value
6
+ * keeps them in SHADOW mode (observe + count + always proceed).
7
+ */
8
+ export declare const CORTEX_RATE_LIMIT_ENFORCE_ENV = "CORTEX_RATE_LIMIT_ENFORCE";
9
+ /**
10
+ * Whether rate-limit 429 enforcement is ON. Read fresh on each request (a cheap
11
+ * env read) so the shadow→enforce graduation can be flipped operationally
12
+ * without a restart. Defaults to OFF (shadow) for any unset/unrecognised value.
13
+ *
14
+ * @param env - Environment source (defaults to `process.env`); injectable for tests.
15
+ * @returns `true` only when the flag is explicitly `true`/`1`.
16
+ */
17
+ export declare function isRateLimitEnforced(env?: Record<string, string | undefined>): boolean;
18
+ /**
19
+ * Counts requests that rate limiting WOULD block (HTTP 429) while in SHADOW
20
+ * mode. This is the signal proving whether flipping
21
+ * `CORTEX_RATE_LIMIT_ENFORCE` to enforce would reject legitimate traffic.
22
+ * Labelled by the `limiter` name (`graphql`/`auth`) and the request `tier`
23
+ * (`auth`/`anon`). Real enforce-mode denials count on
24
+ * {@link cortexRateLimitBlockedTotal} instead, keeping the observed-only and
25
+ * actually-blocked series distinct (audit B01-backend-legacy-14).
26
+ */
27
+ export declare const cortexRateLimitWouldBlockTotal: Counter<"limiter" | "tier">;
28
+ /**
29
+ * Counts requests actually blocked with HTTP 429 in ENFORCE mode. Kept as a
30
+ * separate series from {@link cortexRateLimitWouldBlockTotal} so shadow
31
+ * observations and real blocks never mix (audit B01-backend-legacy-14).
32
+ */
33
+ export declare const cortexRateLimitBlockedTotal: Counter<"limiter" | "tier">;
34
+ /**
35
+ * Tracked bucket-key cardinality per limiter store. Bounds memory ahead of the
36
+ * trust-proxy fix, after which the identifier derives from X-Forwarded-For and
37
+ * an attacker rotating spoofed values could otherwise mint unbounded entries
38
+ * (audit B01-backend-legacy-12).
39
+ */
40
+ export declare const cortexRateLimitStoreKeys: Gauge<"limiter">;
41
+ /** Configuration for one rate limiter instance. */
42
+ export interface RateLimitConfig {
43
+ /** Stable limiter identifier used as the `limiter` metric label. */
44
+ name: string;
45
+ windowMs: number;
46
+ maxAuthenticated: number;
47
+ maxUnauthenticated: number;
48
+ message: {
49
+ errors: Array<{
50
+ message: string;
51
+ }>;
52
+ };
53
+ standardHeaders?: boolean;
54
+ legacyHeaders?: boolean;
55
+ /** Cap on distinct bucket keys (defaults to {@link DEFAULT_MAX_TRACKED_KEYS}). */
56
+ maxTrackedKeys?: number;
57
+ }
58
+ /**
59
+ * Creates an in-memory rate limiter middleware with separate limits for
60
+ * verified (auth) and anonymous requests.
61
+ *
62
+ * Bucketing: verified callers are keyed per principal (`sub:<sub>`); anonymous
63
+ * callers are keyed by client IP, which resolves correctly behind the LB only
64
+ * with `trust proxy` configured in server.ts (audit B01-backend-legacy-02).
65
+ * The `auth` tier requires actual offline verification — a fabricated
66
+ * JWT-shaped header no longer earns the higher budget (B01-backend-legacy-09).
67
+ * CORS preflights (`OPTIONS`) are never counted (B01-backend-legacy-11).
68
+ *
69
+ * Response headers (enforce mode only, when standardHeaders is enabled):
70
+ * X-RateLimit-Limit - maximum requests allowed in the current window
71
+ * X-RateLimit-Remaining - requests remaining in the current window
72
+ * X-RateLimit-Reset - seconds until the current window resets
73
+ * Retry-After - seconds to wait before retrying (only on 429)
74
+ *
75
+ * @param config - Rate limit configuration.
76
+ * @returns Express middleware function.
77
+ */
78
+ export declare function createRateLimiter(config: RateLimitConfig): (req: Request, res: Response, next: NextFunction) => void;
79
+ /**
80
+ * Rate limiter for GraphQL endpoint.
81
+ *
82
+ * Verified requests: 1000 requests per 15 minutes (configurable via RATE_LIMIT_MAX)
83
+ * Anonymous requests: 200 requests per 15 minutes (configurable via RATE_LIMIT_MAX_UNAUTH)
84
+ */
85
+ export declare const graphqlRateLimiter: (req: Request, res: Response, next: NextFunction) => void;
86
+ /**
87
+ * Rate limiter for authentication endpoints.
88
+ *
89
+ * Verified requests: 50 requests per 15 minutes
90
+ * Anonymous requests: 20 requests per 15 minutes
91
+ */
92
+ export declare const authRateLimiter: (req: Request, res: Response, next: NextFunction) => void;
93
+ //# sourceMappingURL=rate-limiter.d.ts.map
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ /**
3
+ * Rate-limit tier resolution (audit B01-backend-legacy-09).
4
+ *
5
+ * The rate limiter previously granted the 5x-higher authenticated tier to any
6
+ * request carrying a 3-dot-segment `Bearer` header — a trivially fabricated
7
+ * shape (`Bearer a.b.c`). This module keys the tier off ACTUAL verification
8
+ * instead, using the two offline-verifiable credential classes:
9
+ *
10
+ * 1. `SERVER_AUTH_TOKEN` exact match (the engine / server-to-server path).
11
+ * 2. App-issued HS256 JWTs verified against the shared `jwtSecret`.
12
+ *
13
+ * Google ID tokens (RS256, JWKS-verified) cannot be verified synchronously
14
+ * without a network dependency in the request hot path; they are deliberately
15
+ * tiered as `anon`. This is a metrics-only inaccuracy while the limiter is in
16
+ * shadow mode — before any enforce graduation, either extend this resolver
17
+ * with an async JWKS-backed path or raise the anon ceiling to cover browser
18
+ * traffic (tracked in the B01-02 graduation checklist).
19
+ *
20
+ * Verified results are memoised in a bounded, TTL'd cache keyed by the token's
21
+ * SHA-256 (raw tokens are never retained) so the per-request cost is one hash.
22
+ */
23
+ var __importDefault = (this && this.__importDefault) || function (mod) {
24
+ return (mod && mod.__esModule) ? mod : { "default": mod };
25
+ };
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports._resetRateTierCacheForTests = _resetRateTierCacheForTests;
28
+ exports.resolveRateTier = resolveRateTier;
29
+ const crypto_1 = require("crypto");
30
+ const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
31
+ const jwtConfig_1 = require("../config/jwtConfig.cjs");
32
+ /** Bound on memoised token verdicts; oldest entries evicted first. */
33
+ const TIER_CACHE_MAX_ENTRIES = 2048;
34
+ /** Memoised verdicts expire after one rate-limit window (15 minutes). */
35
+ const TIER_CACHE_TTL_MS = 15 * 60 * 1000;
36
+ const ANON_RESOLUTION = { tier: 'anon', principalKey: null };
37
+ const tierCache = new Map();
38
+ /**
39
+ * Clears the memoised token-verdict cache. Test-only.
40
+ *
41
+ * @internal exported for testing
42
+ */
43
+ function _resetRateTierCacheForTests() {
44
+ tierCache.clear();
45
+ }
46
+ /**
47
+ * Verifies a bearer token offline and classifies its rate tier.
48
+ *
49
+ * @param token - Raw bearer token value (after the `Bearer ` prefix).
50
+ * @returns The resolved tier; `anon` for anything that fails verification.
51
+ */
52
+ function verifyTier(token) {
53
+ const serverAuthToken = process.env.SERVER_AUTH_TOKEN;
54
+ if (typeof serverAuthToken === 'string' &&
55
+ serverAuthToken.length > 0 &&
56
+ token === serverAuthToken) {
57
+ return { tier: 'auth', principalKey: 'sub:server' };
58
+ }
59
+ try {
60
+ // HS256 pinned for the same alg-confusion reasons as the token-verifier.
61
+ const payload = jsonwebtoken_1.default.verify(token, jwtConfig_1.jwtSecret, { algorithms: ['HS256'] });
62
+ if (typeof payload !== 'string' && typeof payload.sub === 'string') {
63
+ return { tier: 'auth', principalKey: `sub:${payload.sub}` };
64
+ }
65
+ return ANON_RESOLUTION;
66
+ }
67
+ catch (_a) {
68
+ // Unverifiable (bad signature, expired, RS256 Google ID token, garbage
69
+ // shape) — treated as anonymous for tier purposes. Never throws upward:
70
+ // the limiter must not be able to fail a request.
71
+ return ANON_RESOLUTION;
72
+ }
73
+ }
74
+ /**
75
+ * Resolves the rate-limit tier and principal bucket key for a request.
76
+ *
77
+ * Cheap on the hot path: one SHA-256 over the token plus a bounded map lookup;
78
+ * the HMAC verification runs at most once per token per TTL window.
79
+ *
80
+ * @param req - Incoming Express request.
81
+ * @returns The request's {@link RateTierResolution}; `anon` when no `Bearer`
82
+ * token is present or the token cannot be verified offline.
83
+ */
84
+ function resolveRateTier(req) {
85
+ var _a;
86
+ const authHeader = (_a = req.headers.authorization) !== null && _a !== void 0 ? _a : '';
87
+ if (!authHeader.startsWith('Bearer ')) {
88
+ return ANON_RESOLUTION;
89
+ }
90
+ const token = authHeader.slice('Bearer '.length).trim();
91
+ if (token.length === 0) {
92
+ return ANON_RESOLUTION;
93
+ }
94
+ const cacheKey = (0, crypto_1.createHash)('sha256').update(token).digest('hex');
95
+ const now = Date.now();
96
+ const cached = tierCache.get(cacheKey);
97
+ if (cached && cached.expiresAt > now) {
98
+ return cached.resolution;
99
+ }
100
+ const resolution = verifyTier(token);
101
+ if (tierCache.size >= TIER_CACHE_MAX_ENTRIES) {
102
+ // Map preserves insertion order — evict the oldest entry.
103
+ const oldestKey = tierCache.keys().next().value;
104
+ if (oldestKey !== undefined) {
105
+ tierCache.delete(oldestKey);
106
+ }
107
+ }
108
+ tierCache.set(cacheKey, { resolution, expiresAt: now + TIER_CACHE_TTL_MS });
109
+ return resolution;
110
+ }
111
+ //# sourceMappingURL=rate-tier.js.map