@adaptic/backend 0.0.1057 → 0.0.1058

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 (111) 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 +316 -0
  20. package/auth/service-token.d.ts +94 -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 +52 -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/generated/typegraphql-prisma/enhance.cjs +3 -3
  41. package/generated/typegraphql-prisma/index.cjs +6 -6
  42. package/generated/typegraphql-prisma/resolvers/crud/args.index.cjs +95 -95
  43. package/generated/typegraphql-prisma/resolvers/outputs/index.cjs +1 -1
  44. package/generated/typegraphql-prisma/resolvers/relations/args.index.cjs +32 -32
  45. package/middleware/audit-log-write-redaction.cjs +143 -0
  46. package/middleware/audit-log-write-redaction.d.ts +82 -0
  47. package/middleware/audit-logger.cjs +378 -0
  48. package/middleware/audit-logger.d.ts +158 -0
  49. package/middleware/audit-payload-guard.cjs +107 -0
  50. package/middleware/audit-payload-guard.d.ts +85 -0
  51. package/middleware/auth.cjs +66 -0
  52. package/middleware/auth.d.ts +41 -0
  53. package/middleware/credential-field-guard.cjs +514 -0
  54. package/middleware/credential-field-guard.d.ts +173 -0
  55. package/middleware/generated-type-names.cjs +77 -0
  56. package/middleware/generated-type-names.d.ts +44 -0
  57. package/middleware/graphql-validation-plugin.cjs +310 -0
  58. package/middleware/graphql-validation-plugin.d.ts +98 -0
  59. package/middleware/guard-log-throttle.cjs +89 -0
  60. package/middleware/guard-log-throttle.d.ts +80 -0
  61. package/middleware/index.cjs +57 -0
  62. package/middleware/index.d.ts +14 -0
  63. package/middleware/input-validator.cjs +220 -0
  64. package/middleware/input-validator.d.ts +63 -0
  65. package/middleware/mandate-version-validation.cjs +131 -0
  66. package/middleware/mandate-version-validation.d.ts +41 -0
  67. package/middleware/mutation-account-facts.cjs +223 -0
  68. package/middleware/mutation-account-facts.d.ts +143 -0
  69. package/middleware/mutation-auth-guard.cjs +536 -0
  70. package/middleware/mutation-auth-guard.d.ts +100 -0
  71. package/middleware/mutation-membership-facts.cjs +276 -0
  72. package/middleware/mutation-membership-facts.d.ts +133 -0
  73. package/middleware/mutation-tenant-facts.cjs +132 -0
  74. package/middleware/mutation-tenant-facts.d.ts +81 -0
  75. package/middleware/query-complexity.cjs +182 -0
  76. package/middleware/query-complexity.d.ts +56 -0
  77. package/middleware/rate-limiter.cjs +223 -0
  78. package/middleware/rate-limiter.d.ts +93 -0
  79. package/middleware/rate-tier.cjs +111 -0
  80. package/middleware/rate-tier.d.ts +56 -0
  81. package/middleware/soft-delete.cjs +175 -0
  82. package/middleware/soft-delete.d.ts +146 -0
  83. package/middleware/tenancy-scoping.cjs +229 -0
  84. package/middleware/tenancy-scoping.d.ts +67 -0
  85. package/middleware/trading-policy-audit.cjs +353 -0
  86. package/middleware/trading-policy-audit.d.ts +184 -0
  87. package/middleware/types.cjs +17 -0
  88. package/middleware/types.d.ts +87 -0
  89. package/middleware/validation-examples.cjs +398 -0
  90. package/middleware/validation-examples.d.ts +76 -0
  91. package/package.json +10 -2
  92. package/readers/index.cjs +15 -0
  93. package/readers/index.d.ts +10 -0
  94. package/readers/intraday-lane-prefs.cjs +76 -0
  95. package/readers/intraday-lane-prefs.d.ts +45 -0
  96. package/esm/config/__tests__/server-only-surface.harness.d.ts +0 -12
  97. package/esm/config/__tests__/server-only-surface.harness.mjs +0 -41
  98. package/esm/middleware/__tests__/audit-log-write-redaction.harness.d.ts +0 -144
  99. package/esm/middleware/__tests__/audit-log-write-redaction.harness.mjs +0 -920
  100. package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts +0 -55
  101. package/esm/middleware/__tests__/credential-field-coverage.harness.mjs +0 -440
  102. package/esm/middleware/__tests__/credential-field-guard.harness.d.ts +0 -34
  103. package/esm/middleware/__tests__/credential-field-guard.harness.mjs +0 -212
  104. package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +0 -56
  105. package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +0 -575
  106. package/esm/middleware/__tests__/rate-limit-test-utils.d.ts +0 -60
  107. package/esm/middleware/__tests__/rate-limit-test-utils.mjs +0 -85
  108. package/esm/middleware/__tests__/ts-node-harness.d.ts +0 -10
  109. package/esm/middleware/__tests__/ts-node-harness.mjs +0 -71
  110. package/health.cjs +0 -274
  111. package/server.cjs +0 -607
package/server.cjs DELETED
@@ -1,607 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- require("reflect-metadata");
40
- const dotenv_1 = __importDefault(require("dotenv"));
41
- dotenv_1.default.config();
42
- // IMPORTANT: tracing initialization must happen before any other instrumented
43
- // import is loaded. `initTracing()` is a no-op unless `OTEL_TRACING_ENABLED=true`
44
- // (or NODE_ENV ∈ {production, staging}), so this remains safe in development.
45
- // See: src/config/tracing.ts and docs/ENVIRONMENT_SETUP.md.
46
- const tracing_1 = require("./config/tracing.cjs");
47
- (0, tracing_1.initTracing)();
48
- const express_1 = __importDefault(require("express"));
49
- const server_1 = require("@apollo/server");
50
- const express4_1 = require("@as-integrations/express4");
51
- const drainHttpServer_1 = require("@apollo/server/plugin/drainHttpServer");
52
- const type_graphql_1 = require("type-graphql");
53
- const graphql_1 = require("graphql");
54
- const typegraphql_prisma_1 = require("./generated/typegraphql-prisma.cjs");
55
- const server_only_models_1 = require("./config/server-only-models.cjs");
56
- const custom_1 = require("./resolvers/custom.cjs");
57
- const http_1 = require("http");
58
- const cors_1 = __importDefault(require("cors"));
59
- const body_parser_1 = __importDefault(require("body-parser"));
60
- const ws_1 = require("ws");
61
- const ws_2 = require("graphql-ws/lib/use/ws");
62
- const auth_1 = require("./middleware/auth.cjs");
63
- const rate_limiter_1 = require("./middleware/rate-limiter.cjs");
64
- const audit_logger_1 = require("./middleware/audit-logger.cjs");
65
- const tenancy_scoping_1 = require("./middleware/tenancy-scoping.cjs");
66
- const credential_field_guard_1 = require("./middleware/credential-field-guard.cjs");
67
- const mutation_auth_guard_1 = require("./middleware/mutation-auth-guard.cjs");
68
- const mandate_version_validation_1 = require("./middleware/mandate-version-validation.cjs");
69
- const trading_policy_audit_1 = require("./middleware/trading-policy-audit.cjs");
70
- const cortex_auth_checker_1 = require("./auth/cortex-auth-checker.cjs");
71
- const authorization_map_1 = require("./auth/authorization-map.cjs");
72
- const http_status_mapper_1 = require("./plugins/http-status-mapper.cjs");
73
- const graphql_validation_plugin_1 = require("./middleware/graphql-validation-plugin.cjs");
74
- const query_complexity_1 = require("./middleware/query-complexity.cjs");
75
- const metrics_1 = require("./config/metrics.cjs");
76
- const persisted_queries_1 = require("./config/persisted-queries.cjs");
77
- const prismaClient_1 = __importStar(require("./prismaClient.cjs"));
78
- const health_1 = require("./health.cjs");
79
- const logger_1 = require("./utils/logger.cjs");
80
- const token_verifier_1 = require("./auth/token-verifier.cjs");
81
- const ws_auth_context_1 = require("./auth/ws-auth-context.cjs");
82
- const graphql_auth_shadow_1 = require("./auth/graphql-auth-shadow.cjs");
83
- /**
84
- * Adapt a verified `BackendPrincipal` to the legacy `user` context shape used
85
- * by downstream resolvers and audit plugins (`{ sub, role, roles? }`).
86
- *
87
- * The server-kind principal is materialised as `{ sub: 'server', role: 'server' }`
88
- * for compatibility with the historical `audit-logger` middleware that checks
89
- * `context.user?.role === 'server'`.
90
- */
91
- function principalToUser(principal) {
92
- var _a, _b;
93
- switch (principal.kind) {
94
- case 'server':
95
- return { sub: 'server', name: 'Server Auth', role: 'server' };
96
- case 'admin':
97
- return {
98
- sub: principal.sub,
99
- role: 'admin',
100
- // Preserve the email if Google or our JWT provided one.
101
- ...(principal.email ? { name: principal.email } : {}),
102
- };
103
- case 'user':
104
- // Surface the highest-privilege role string for legacy consumers that
105
- // expect `role` to be a single value (default to "user").
106
- return {
107
- sub: principal.sub,
108
- role: (_b = (_a = principal.roles.find((r) => r !== 'user')) !== null && _a !== void 0 ? _a : principal.roles[0]) !== null && _b !== void 0 ? _b : 'user',
109
- ...(principal.email ? { name: principal.email } : {}),
110
- };
111
- }
112
- }
113
- /**
114
- * Default number of proxy hops trusted for X-Forwarded-For resolution when
115
- * `TRUST_PROXY` is unset. One hop matches a single fronting LB/ingress proxy;
116
- * operators must set `TRUST_PROXY` to the exact hop count of their deployment
117
- * (audit B01-backend-legacy-02 / -12).
118
- */
119
- const DEFAULT_TRUST_PROXY_HOPS = 1;
120
- const startServer = async () => {
121
- var _a;
122
- // Boot-time invariant: in production, `GOOGLE_OAUTH_CLIENT_IDS` must be set.
123
- // Without it, no Google ID token can be safely verified — and the verifier
124
- // would surface a per-request `misconfigured` error indefinitely. Refuse to
125
- // boot with broken identity configuration.
126
- (0, token_verifier_1.assertGoogleAudienceConfiguredForProd)();
127
- // Prometheus metrics initialization. No-op unless `PROMETHEUS_METRICS_ENABLED`
128
- // is on (defaults on in production/staging). Registers default Node.js metrics
129
- // and starts the uptime gauge ticker. See: src/config/metrics.ts.
130
- (0, metrics_1.initMetrics)();
131
- // CORTEX-P0-001 phase 2 (audit B01-backend-legacy-03): decorate generated
132
- // CRUD resolvers with @Authorized() — full coverage on the 5 investor-relations
133
- // models, delete mutations elsewhere — so the authChecker below actually
134
- // executes. Must run BEFORE buildSchema (decorators land in TypeGraphQL's
135
- // metadata storage). The checker stays SHADOW-FIRST: would-denies are logged
136
- // + counted but ALLOWED until CORTEX_AUTHCHECKER_ENFORCE is flipped on.
137
- // The boot log satisfies audit B01-backend-legacy-07: a zero decorated-action
138
- // count means the checker is unreachable and its metrics are meaningless.
139
- const authzSummary = (0, authorization_map_1.applyCortexAuthorizationMap)();
140
- logger_1.logger.info('[cortex-authz] applied @Authorized coverage (authChecker in shadow unless CORTEX_AUTHCHECKER_ENFORCE)', {
141
- fullCoverageModels: authzSummary.fullCoverageModels,
142
- deleteCoverageModels: authzSummary.deleteCoverageModels,
143
- decoratedActions: authzSummary.decoratedActions,
144
- skippedActions: authzSummary.skippedActions.length,
145
- });
146
- // Server-only models (the trade restatement ledger) get no GraphQL surface:
147
- // their resolvers are dropped here and any residual field or input that
148
- // references them is stripped from the built schema.
149
- const schema = (0, server_only_models_1.withoutServerOnlySchemaSurface)(await (0, type_graphql_1.buildSchema)({
150
- resolvers: [
151
- ...(0, server_only_models_1.withoutServerOnlyResolvers)(typegraphql_prisma_1.resolvers),
152
- custom_1.OptionsGreeksHistoryCustomResolver,
153
- custom_1.TradingSettingsResolver,
154
- custom_1.BrokerageAccountCredentialStatusResolver,
155
- custom_1.AccountEquityCurveResolver,
156
- custom_1.UserTotpResolver,
157
- custom_1.StrategyDraftResolver,
158
- ],
159
- validate: false,
160
- // Row-level tenancy scoping (SP2-G7 / SOC2). Applies ONLY to user-scoped
161
- // principals on the tenancy + notification models; service/admin principals
162
- // and unauthenticated callers are bypassed in every mode. Gated by
163
- // `TENANCY_SCOPING_MODE` (default `shadow`).
164
- //
165
- // Credential-field guard: stored credentials (broker API keys, OAuth,
166
- // session and invite tokens) resolve — and can be filtered, sorted or
167
- // grouped on — only for a verified service principal. It runs FIRST so a
168
- // credential predicate is refused before any other middleware or resolver
169
- // touches the database. Gated by `CREDENTIAL_FIELD_GUARD_MODE` (default
170
- // `enforce`); see src/middleware/credential-field-guard.ts.
171
- globalMiddlewares: [
172
- (0, credential_field_guard_1.createCredentialFieldGuardMiddleware)(),
173
- (0, tenancy_scoping_1.createTenancyScopingMiddleware)(),
174
- ],
175
- // Resolver-level authorization (CORTEX-P0-001). Invoked for the
176
- // `@Authorized()`-decorated fields applied by applyCortexAuthorizationMap
177
- // above. SHADOW-FIRST: while `CORTEX_AUTHCHECKER_ENFORCE` is OFF (default),
178
- // it observes + counts would-deny operations but always allows —
179
- // byte-identical live behaviour until enforcement is flipped on.
180
- authChecker: cortex_auth_checker_1.cortexAuthChecker,
181
- }));
182
- // Mutation authorization: every mutation is admitted only for a principal
183
- // authorised to write that model — the engine's service principal and admins
184
- // everywhere, a user only on an account, row or tenant it owns — and every
185
- // TradingPolicy write leaves an attributed audit row. Installed on the built
186
- // schema's Mutation fields (not as a global middleware, which would tax every
187
- // read field), so it covers generated and custom mutations alike on both the
188
- // HTTP and WebSocket transports. Gated by `MUTATION_AUTH_MODE` (unset =
189
- // `shadow`) and the per-model escalation `MUTATION_AUTH_ENFORCE_MODELS`; see
190
- // src/middleware/mutation-auth-guard.ts and
191
- // docs/security/2026-09-24-mutation-authorization-runbook.md.
192
- // MandateVersion JSON shapes (autonomy, triggers, instruments) are checked on
193
- // every mutation that can write a version, nested writes included. Installed
194
- // BEFORE the guard so the guard wraps it and authorises first.
195
- const mandateValidatedMutations = (0, mandate_version_validation_1.installMandateVersionValidation)(schema);
196
- logger_1.logger.info('[mandate-version] JSON shape validation installed', { mandateValidatedMutations });
197
- const guardedMutations = (0, mutation_auth_guard_1.installMutationAuthGuard)(schema);
198
- logger_1.logger.info('[mutation-auth] guard installed on every root Mutation field', {
199
- guardedMutations,
200
- });
201
- const app = (0, express_1.default)();
202
- const httpServer = (0, http_1.createServer)(app);
203
- // Trust the load-balancer proxy chain so `req.ip` resolves the CLIENT address
204
- // from X-Forwarded-For instead of the proxy hop (audit B01-backend-legacy-02).
205
- // Without this, every external caller shares one rate-limit bucket per tier,
206
- // invalidating the shadow signal and making any future enforce flip an outage
207
- // switch for the whole /graphql surface. `TRUST_PROXY` accepts a hop count
208
- // (recommended: the EXACT number of proxy hops, so a spoofed X-Forwarded-For
209
- // cannot mint arbitrary identifiers — audit B01-backend-legacy-12) or an
210
- // Express trust-proxy string (CIDR / preset). Defaults to 1 hop.
211
- const rawTrustProxy = ((_a = process.env.TRUST_PROXY) !== null && _a !== void 0 ? _a : '').trim();
212
- const trustProxy = rawTrustProxy === ''
213
- ? DEFAULT_TRUST_PROXY_HOPS
214
- : /^\d+$/.test(rawTrustProxy)
215
- ? parseInt(rawTrustProxy, 10)
216
- : rawTrustProxy;
217
- app.set('trust proxy', trustProxy);
218
- // HTTP request metrics — must be mounted early to capture every request.
219
- // The middleware is a no-op when metrics are disabled.
220
- app.use(metrics_1.metricsMiddleware);
221
- // Rate limiting (CORTEX-P0-001). SHADOW-FIRST: while `CORTEX_RATE_LIMIT_ENFORCE`
222
- // is OFF (default), the limiters observe + count requests that WOULD be blocked
223
- // but never touch the response, so live behaviour is byte-identical. The
224
- // GraphQL limiter is mounted INSIDE the /graphql chain after cors() (see below)
225
- // so an enforce-mode 429 carries CORS headers and browser clients can read the
226
- // Retry-After instead of seeing an opaque CORS failure
227
- // (audit B01-backend-legacy-11). Mounted before `/api` auth so limiting
228
- // precedes the (more expensive) auth work.
229
- app.use('/api', rate_limiter_1.authRateLimiter);
230
- app.use('/api', (req, res, next) => (0, auth_1.authMiddleware)(req, res, next));
231
- // APQ cache: in-memory LRU, gated by `APQ_ENABLED` (default on). The
232
- // Apollo Server option only accepts a value when a cache is provided;
233
- // omit the option when APQ is disabled rather than passing `false` so
234
- // Apollo's default in-memory cache can take over if needed.
235
- const apqCache = (0, persisted_queries_1.createAPQCache)();
236
- const server = new server_1.ApolloServer({
237
- schema,
238
- introspection: process.env.NODE_ENV !== 'production',
239
- plugins: [
240
- (0, drainHttpServer_1.ApolloServerPluginDrainHttpServer)({ httpServer }),
241
- (0, audit_logger_1.createAuditLogPlugin)(),
242
- (0, http_status_mapper_1.createHttpStatusMapperPlugin)(),
243
- // Validation plugin — runs on `didResolveOperation` and rejects
244
- // mutations whose input variables fail pattern-based validation
245
- // (percentages, positive numbers, non-empty strings).
246
- (0, graphql_validation_plugin_1.createValidationPlugin)(),
247
- // Query complexity + depth guard. No-op unless
248
- // `GRAPHQL_COMPLEXITY_ENABLED` is on (defaults on in production /
249
- // staging). Tunable via `GRAPHQL_MAX_DEPTH`,
250
- // `GRAPHQL_MAX_COMPLEXITY_AUTH`, `GRAPHQL_MAX_COMPLEXITY_UNAUTH`.
251
- (0, query_complexity_1.createQueryComplexityPlugin)(schema),
252
- // GraphQL operation metrics (count, duration, error counts).
253
- // No-op when metrics are disabled.
254
- (0, metrics_1.createMetricsPlugin)(),
255
- ],
256
- ...(apqCache && (0, persisted_queries_1.isAPQEnabled)()
257
- ? { persistedQueries: { cache: apqCache } }
258
- : {}),
259
- formatError: (err) => {
260
- var _a, _b;
261
- const message = err.message || '';
262
- // Demote known caller-handled / caller-side error patterns to lower
263
- // log levels so they don't pollute ERROR logs and trigger spurious
264
- // alerts. The Prisma client error categorizer in prismaClient.ts also
265
- // demotes these on the raw client side; this mirror keeps the
266
- // GraphQL-formatted error consistent.
267
- const isExpectedDeleteRace = message.includes('No record was found for a delete') ||
268
- message.includes('No record was found for an update');
269
- const isInvalidUuidInput = message.includes('Error creating UUID') ||
270
- message.includes('Inconsistent column data: Error creating UUID');
271
- if (isExpectedDeleteRace) {
272
- logger_1.logger.info('GraphQL expected race (record already removed)', {
273
- graphqlError: err,
274
- });
275
- }
276
- else if (isInvalidUuidInput) {
277
- logger_1.logger.warn('GraphQL rejected invalid UUID input', {
278
- graphqlError: err,
279
- });
280
- }
281
- else {
282
- logger_1.logger.error('GraphQL Error', { graphqlError: err });
283
- }
284
- if (message.includes("Can't reach database server")) {
285
- logger_1.logger.warn('Database unreachable', { graphqlError: err });
286
- }
287
- // Surface the verifier's `reason` enum on UNAUTHENTICATED responses so
288
- // operators (and the web app's network tab) can diagnose auth failures
289
- // without grepping Railway logs. The reason is one of a finite set —
290
- // `malformed | expired | bad_signature | bad_audience |
291
- // opaque_access_token_rejected | misconfigured` — and carries no
292
- // sensitive data (no token bytes, no claim values). Whitelisted to
293
- // UNAUTHENTICATED so we do not accidentally leak a `reason` field
294
- // attached to any other error class. See CORTEX-2026-05-12 auth-debug
295
- // change log.
296
- const code = ((_a = err.extensions) === null || _a === void 0 ? void 0 : _a.code) || 'INTERNAL_SERVER_ERROR';
297
- const reasonValue = (_b = err.extensions) === null || _b === void 0 ? void 0 : _b.reason;
298
- const includeReason = code === 'UNAUTHENTICATED' && typeof reasonValue === 'string';
299
- return {
300
- message: err.message,
301
- locations: err.locations,
302
- path: err.path,
303
- extensions: {
304
- code,
305
- ...(includeReason ? { reason: reasonValue } : {}),
306
- },
307
- };
308
- },
309
- });
310
- await server.start();
311
- // Health check endpoint - mounted before Apollo middleware so it's not behind GraphQL or auth
312
- app.use((0, health_1.createHealthRouter)());
313
- // Prometheus metrics endpoint — GET /metrics returns metrics in the
314
- // Prometheus text exposition format. Mounted outside of Apollo and auth
315
- // so a scraper can pull metrics without a Bearer token. In production
316
- // this endpoint should be protected via firewall / Cloud Run ingress
317
- // rules rather than at the application layer. No-op response if
318
- // `PROMETHEUS_METRICS_ENABLED` is off (the registry is simply empty).
319
- app.use((0, metrics_1.createMetricsRouter)());
320
- // Configure CORS with allowed origins
321
- const defaultOrigins = [
322
- 'http://localhost:3000',
323
- 'http://localhost:3001',
324
- 'http://localhost:4000',
325
- 'https://adaptic.ai',
326
- 'https://os.adaptic.ai',
327
- 'https://stable.adaptic.ai',
328
- ];
329
- const envOrigins = process.env.ALLOWED_ORIGINS
330
- ? process.env.ALLOWED_ORIGINS.split(',').map((o) => o.trim())
331
- : [];
332
- const allowedOrigins = [...new Set([...defaultOrigins, ...envOrigins])];
333
- const corsOptions = {
334
- origin: (origin, callback) => {
335
- // Allow requests with no origin (mobile apps, server-to-server, curl)
336
- if (!origin)
337
- return callback(null, true);
338
- if (allowedOrigins.includes(origin)) {
339
- callback(null, true);
340
- }
341
- else {
342
- callback(new Error(`Origin ${origin} not allowed by CORS`));
343
- }
344
- },
345
- credentials: true,
346
- methods: ['GET', 'POST', 'OPTIONS'],
347
- // X-Adaptic-Change-Reason is the stated reason recorded on every
348
- // TradingPolicy audit row (src/middleware/trading-policy-audit.ts); a
349
- // browser caller can only send it if preflight allows it.
350
- allowedHeaders: ['Content-Type', 'Authorization', 'X-Request-ID', 'X-Adaptic-Change-Reason'],
351
- maxAge: 86400, // 24h preflight cache
352
- };
353
- app.use('/graphql', (0, cors_1.default)(corsOptions),
354
- // After cors() so enforce-mode 429s carry CORS headers; before body parsing
355
- // so limiting stays cheap. OPTIONS preflights are skipped inside the
356
- // limiter (audit B01-backend-legacy-11).
357
- rate_limiter_1.graphqlRateLimiter, body_parser_1.default.json(), (0, express4_1.expressMiddleware)(server, {
358
- context: async ({ req }) => {
359
- // Ensure we're using the global prisma instance and never disconnecting it between requests
360
- if (!global.prisma) {
361
- logger_1.logger.warn('Prisma client not found in global scope, reinitializing');
362
- global.prisma = prismaClient_1.default;
363
- }
364
- // Extract token from Authorization header
365
- const authHeader = req.headers.authorization || '';
366
- const token = authHeader.startsWith('Bearer ')
367
- ? authHeader.slice('Bearer '.length).trim()
368
- : '';
369
- // When NO token is presented, fall through with `user: null`. The
370
- // `AuthChecker` introduced in CORTEX-P0-001 will reject any operation
371
- // that requires a principal; this contract preserves the current
372
- // unauthenticated-public-query path until P0-001 lands.
373
- if (!token) {
374
- // Shadow-observe the would-deny WITHOUT blocking: this null-principal
375
- // request is exactly what a principal-required enforcement flip would
376
- // reject. Counting + (throttled) logging it here is how we measure the
377
- // enforcement blast radius in production before ever flipping it.
378
- // See src/auth/graphql-auth-shadow.ts and
379
- // docs/security/2026-08-23-graphql-auth-enforcement-runbook.md.
380
- const rawBody = req.body;
381
- (0, graphql_auth_shadow_1.recordShadowAuthMiss)({
382
- transport: 'http',
383
- operationName: (0, graphql_auth_shadow_1.extractOperationName)(rawBody),
384
- origin: (0, graphql_auth_shadow_1.headerToString)(req.headers.origin),
385
- ip: req.ip,
386
- userAgent: (0, graphql_auth_shadow_1.headerToString)(req.headers['user-agent']),
387
- authHeaderPresent: authHeader.length > 0,
388
- });
389
- return { prisma: global.prisma, req, user: null, principal: null };
390
- }
391
- // Verify the bearer token through the SINGLE typed entry point. There
392
- // is no prefix shortcut (ya29.…), no parallel path, and no silent
393
- // downgrade to an unverified principal on failure.
394
- try {
395
- const principal = await (0, token_verifier_1.verifyBackendToken)(token);
396
- (0, graphql_auth_shadow_1.recordAuthContextOutcome)('http', 'authenticated');
397
- return {
398
- prisma: global.prisma,
399
- req,
400
- user: principalToUser(principal),
401
- // The typed principal is consumed by the tenancy-scoping middleware
402
- // to distinguish user-scoped callers (scoped) from server/admin
403
- // callers (never scoped).
404
- principal,
405
- };
406
- }
407
- catch (e) {
408
- const reason = e instanceof token_verifier_1.AuthError ? e.reason : 'bad_signature';
409
- // Already rejected today (HTTP 401). Counted only to complete the
410
- // shadow denominator alongside authenticated / no_principal outcomes.
411
- (0, graphql_auth_shadow_1.recordAuthContextOutcome)('http', 'invalid_token');
412
- logger_1.logger.warn('GraphQL HTTP auth rejected', { reason });
413
- // Throw `UNAUTHENTICATED` so Apollo's HTTP transport returns a
414
- // GraphQL-shaped error response. The `formatError` hook above
415
- // preserves the `code` extension.
416
- //
417
- // `extensions.http.status: 401` is essential and easy to miss:
418
- // when `context()` throws, Apollo Server takes the
419
- // `errorResponse` path (ApolloServer.js#executeHTTPGraphQLRequest
420
- // catch block) which BYPASSES the request pipeline entirely —
421
- // willSendResponse plugins do not fire. The only mechanism left
422
- // for setting the HTTP status is `extensions.http.status` on the
423
- // thrown error itself, which `normalizeAndFormatErrors` lifts
424
- // into the response head and then strips from the body so it does
425
- // not leak. Without this, every auth failure ships as HTTP 500,
426
- // and Apollo Client's observable pipeline crashes on the 5xx +
427
- // GraphQL-body combination (`Cannot read properties of undefined
428
- // (reading 'write')`), leaving consumer `await client.query(...)`
429
- // promises that neither resolve nor reject — which is precisely
430
- // how /configure/trading-policy ended up locked in a permanent
431
- // loading state.
432
- throw new graphql_1.GraphQLError('Unauthenticated', {
433
- extensions: {
434
- code: 'UNAUTHENTICATED',
435
- reason,
436
- http: { status: 401 },
437
- },
438
- });
439
- }
440
- },
441
- }));
442
- // Custom error handling middleware for express
443
- app.use((err, req, res, _next) => {
444
- logger_1.logger.error('Express error', { error: err.message, stack: err.stack });
445
- res.status(500).json({ error: 'An internal server error occurred' });
446
- });
447
- app.use((req, res, next) => {
448
- logger_1.logger.debug('Incoming request', { method: req.method, url: req.url });
449
- next();
450
- });
451
- const wsServer = new ws_1.WebSocketServer({
452
- server: httpServer,
453
- path: '/subscriptions',
454
- });
455
- (0, ws_2.useServer)({
456
- schema,
457
- context: async (ctx, _msg, args) => {
458
- var _a;
459
- // Ensure we're using the global prisma instance for WebSocket connections too
460
- if (!global.prisma) {
461
- logger_1.logger.warn('Prisma client not found in global scope for WebSocket context, reinitializing');
462
- global.prisma = prismaClient_1.default;
463
- }
464
- const authHeader = ((_a = ctx.connectionParams) === null || _a === void 0 ? void 0 : _a.authorization) ||
465
- '';
466
- // The classification itself lives in src/auth/ws-auth-context.ts so the
467
- // security predicate is reachable by tests without booting the server.
468
- // The effects it drives — shadow metrics, logging, Prisma attachment —
469
- // stay here at the transport boundary.
470
- const decision = await (0, ws_auth_context_1.decideWsAuth)(authHeader);
471
- switch (decision.kind) {
472
- case 'anonymous': {
473
- // No token presented -> deliver a null-user context. The AuthChecker
474
- // landing in CORTEX-P0-001 will reject any subscription that requires
475
- // a principal. Until then, public subscriptions continue to work.
476
- //
477
- // Shadow-observe the would-deny WITHOUT blocking — the WebSocket
478
- // parallel of the HTTP path. Operation name is best-effort from
479
- // ExecutionArgs; origin / user-agent / IP come from the upgrade
480
- // request carried on ctx.extra.
481
- const wsIdentity = (0, graphql_auth_shadow_1.extractHeaderIdentityFromWsExtra)(ctx.extra);
482
- (0, graphql_auth_shadow_1.recordShadowAuthMiss)({
483
- transport: 'ws',
484
- operationName: (0, graphql_auth_shadow_1.extractOperationNameFromArgs)(args),
485
- origin: wsIdentity.origin,
486
- ip: wsIdentity.ip,
487
- userAgent: wsIdentity.userAgent,
488
- authHeaderPresent: authHeader.length > 0,
489
- });
490
- return {
491
- prisma: global.prisma,
492
- req: (0, trading_policy_audit_1.wsActorRequest)(ctx.extra, ctx.connectionParams),
493
- user: null,
494
- principal: null,
495
- };
496
- }
497
- case 'authenticated': {
498
- (0, graphql_auth_shadow_1.recordAuthContextOutcome)('ws', 'authenticated');
499
- return {
500
- prisma: global.prisma,
501
- req: (0, trading_policy_audit_1.wsActorRequest)(ctx.extra, ctx.connectionParams),
502
- user: principalToUser(decision.principal),
503
- principal: decision.principal,
504
- };
505
- }
506
- case 'rejected': {
507
- // Already rejected today (connection closed). Counted only to complete
508
- // the shadow denominator alongside authenticated / no_principal.
509
- (0, graphql_auth_shadow_1.recordAuthContextOutcome)('ws', 'invalid_token');
510
- logger_1.logger.warn('WebSocket auth rejected — closing connection', {
511
- reason: decision.reason,
512
- });
513
- // Throwing IS the close mechanism: graphql-ws propagates the throw
514
- // out of its message handler and terminates the socket (close code
515
- // 4500, close reason "Unauthenticated"). There is deliberately no
516
- // fall-through to a degraded `authError` context that would keep
517
- // delivering messages to an unauthenticated socket.
518
- throw (0, ws_auth_context_1.unauthenticatedWsError)(decision.reason);
519
- }
520
- }
521
- },
522
- }, wsServer);
523
- // Start the periodic database connection health monitor
524
- (0, prismaClient_1.startConnectionHealthMonitor)();
525
- const PORT = process.env.PORT || 4000;
526
- httpServer.listen(PORT, () => {
527
- logger_1.logger.info('Server ready', {
528
- graphql: `http://localhost:${PORT}/graphql`,
529
- health: `http://localhost:${PORT}/health`,
530
- });
531
- logger_1.logger.info('Subscriptions ready', {
532
- endpoint: `ws://localhost:${PORT}/subscriptions`,
533
- });
534
- });
535
- // --- Graceful shutdown ---
536
- // Sequence: stop accepting connections → drain in-flight requests →
537
- // close WebSocket → disconnect DB → flush traces → exit
538
- let isShuttingDown = false;
539
- const SHUTDOWN_TIMEOUT_MS = 15000;
540
- async function gracefulShutdown(signal) {
541
- if (isShuttingDown)
542
- return;
543
- isShuttingDown = true;
544
- logger_1.logger.info(`Received ${signal}, starting graceful shutdown`);
545
- // Force exit if shutdown takes too long
546
- const forceExitTimer = setTimeout(() => {
547
- logger_1.logger.error('Graceful shutdown timed out, forcing exit');
548
- process.exit(1);
549
- }, SHUTDOWN_TIMEOUT_MS);
550
- forceExitTimer.unref();
551
- try {
552
- // 1. Stop accepting new HTTP connections
553
- await new Promise((resolve) => {
554
- httpServer.close(() => {
555
- logger_1.logger.info('HTTP server closed');
556
- resolve();
557
- });
558
- });
559
- // 2. Close WebSocket server (rejects new WS connections)
560
- await new Promise((resolve) => {
561
- wsServer.close(() => {
562
- logger_1.logger.info('WebSocket server closed');
563
- resolve();
564
- });
565
- });
566
- // 3. Apollo Server drain is handled by ApolloServerPluginDrainHttpServer
567
- // 4. Stop health monitor and disconnect DB with timeout
568
- await (0, prismaClient_1.disconnectWithTimeout)(5000);
569
- // 5. Flush OpenTelemetry traces
570
- await (0, tracing_1.shutdownTracing)();
571
- logger_1.logger.info('Graceful shutdown complete');
572
- }
573
- catch (error) {
574
- logger_1.logger.error('Error during graceful shutdown', {
575
- error: error instanceof Error ? error.message : String(error),
576
- });
577
- }
578
- finally {
579
- clearTimeout(forceExitTimer);
580
- process.exit(0);
581
- }
582
- }
583
- process.on('SIGINT', () => {
584
- void gracefulShutdown('SIGINT');
585
- });
586
- process.on('SIGTERM', () => {
587
- void gracefulShutdown('SIGTERM');
588
- });
589
- };
590
- startServer().catch((error) => {
591
- logger_1.logger.error('Error starting the server', {
592
- error: error instanceof Error ? error.message : String(error),
593
- });
594
- process.exit(1);
595
- });
596
- process.on('unhandledRejection', (reason, _promise) => {
597
- logger_1.logger.error('Unhandled Rejection', {
598
- reason: reason instanceof Error ? reason.message : String(reason),
599
- });
600
- });
601
- process.on('uncaughtException', (error) => {
602
- logger_1.logger.error('Uncaught Exception', {
603
- error: error.message,
604
- stack: error.stack,
605
- });
606
- });
607
- //# sourceMappingURL=server.js.map