@adaptic/backend-legacy 0.0.1057 → 0.0.1059

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,306 @@
1
+ "use strict";
2
+ /**
3
+ * CORTEX-P0-001 phase 2 — `@Authorized()` coverage for generated CRUD resolvers
4
+ * (audit B01-backend-legacy-03).
5
+ *
6
+ * The `cortexAuthChecker` registered in `buildSchema` is only invoked by
7
+ * TypeGraphQL for fields carrying an `@Authorized()` decorator; the
8
+ * auto-generated typegraphql-prisma resolvers carry none, so the checker was
9
+ * registered-but-inert. This module applies decorators via
10
+ * `applyResolversEnhanceMap`, making the checker actually execute:
11
+ *
12
+ * - FULL coverage (`_all`) for the five investor-relations models —
13
+ * regulated PII (tax documents, KYC status, LP capital ledger) that must
14
+ * never sit on an unauthenticated CRUD surface.
15
+ * - DELETE mutations (`deleteOne*` / `deleteMany*`) for every other model —
16
+ * the most destructive operations on the trading system-of-record.
17
+ *
18
+ * CRITICAL SAFETY CONTRACT — the checker itself remains SHADOW-FIRST: while
19
+ * `CORTEX_AUTHCHECKER_ENFORCE` is OFF (default) a would-deny operation is
20
+ * logged + counted and then ALLOWED, so engine service traffic cannot break.
21
+ * This module only determines WHERE the checker runs, not what it does.
22
+ * Graduation rule (audit B01-backend-legacy-07): enforce only after
23
+ * `cortex_authchecker_evaluations_total` > 0 and the would-deny series has
24
+ * been observed over a full trading week.
25
+ *
26
+ * Must be applied BEFORE `buildSchema` — decorators land in TypeGraphQL's
27
+ * global metadata storage, which `buildSchema` reads.
28
+ */
29
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
30
+ if (k2 === undefined) k2 = k;
31
+ var desc = Object.getOwnPropertyDescriptor(m, k);
32
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
33
+ desc = { enumerable: true, get: function() { return m[k]; } };
34
+ }
35
+ Object.defineProperty(o, k2, desc);
36
+ }) : (function(o, m, k, k2) {
37
+ if (k2 === undefined) k2 = k;
38
+ o[k2] = m[k];
39
+ }));
40
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
41
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
42
+ }) : function(o, v) {
43
+ o["default"] = v;
44
+ });
45
+ var __importStar = (this && this.__importStar) || (function () {
46
+ var ownKeys = function(o) {
47
+ ownKeys = Object.getOwnPropertyNames || function (o) {
48
+ var ar = [];
49
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
50
+ return ar;
51
+ };
52
+ return ownKeys(o);
53
+ };
54
+ return function (mod) {
55
+ if (mod && mod.__esModule) return mod;
56
+ var result = {};
57
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
58
+ __setModuleDefault(result, mod);
59
+ return result;
60
+ };
61
+ })();
62
+ Object.defineProperty(exports, "__esModule", { value: true });
63
+ exports.TENANT_SCOPED_READ_MODELS = exports.DESK_READ_MODELS = exports.IR_MODELS = void 0;
64
+ exports.buildCortexAuthorizationMap = buildCortexAuthorizationMap;
65
+ exports.applyCortexAuthorizationMap = applyCortexAuthorizationMap;
66
+ const type_graphql_1 = require("type-graphql");
67
+ const client_1 = require("@prisma/client");
68
+ const typegraphql_prisma_1 = require("../generated/typegraphql-prisma/index.cjs");
69
+ const generatedIndex = __importStar(require("../generated/typegraphql-prisma/index.cjs"));
70
+ const logger_1 = require("../utils/logger.cjs");
71
+ /**
72
+ * The five investor-relations models receiving FULL (`_all`) coverage:
73
+ * every generated query and mutation on these models invokes the authChecker.
74
+ */
75
+ exports.IR_MODELS = [
76
+ 'Investor',
77
+ 'Holding',
78
+ 'InvestorTransaction',
79
+ 'InvestorDocument',
80
+ 'TaxDocument',
81
+ ];
82
+ /**
83
+ * The trading-desk models, admitted to {@link TENANT_SCOPED_READ_MODELS} at
84
+ * birth. The measurement criterion below exists to find surfaces that were
85
+ * already answering to anyone; these never did. Their row scope is the
86
+ * tenancy predicate in `src/auth/tenancy-scope.ts` (`DESK_MODELS`: a user's
87
+ * own rows for Follow, PushSubscription, UserTotp and an unshared
88
+ * AdaConversation; the fund tenant for DeskDecision, AutoFollowRule and a
89
+ * shared AdaConversation; the user or organization for FeatureFlagOverride),
90
+ * enforced in every mode, with an unauthenticated read refused outright by
91
+ * the tenancy middleware. Decorating them here puts the same reads on the
92
+ * checker's evaluation and would-deny series as the models below.
93
+ */
94
+ exports.DESK_READ_MODELS = [
95
+ 'AdaConversation',
96
+ 'AdaMessage',
97
+ 'DeskDecision',
98
+ 'PushSubscription',
99
+ 'UserTotp',
100
+ 'Follow',
101
+ 'AutoFollowRule',
102
+ 'FeatureFlagOverride',
103
+ ];
104
+ /**
105
+ * Models whose READ actions are decorated as well as their deletes.
106
+ *
107
+ * These four answer to anyone today. A read-only probe of the deployed API
108
+ * with no Authorization header returns a real organisation name, a real user's
109
+ * email address, and a real membership row, so the standing escalation is not
110
+ * theoretical. They were outside the checker entirely: `_all` covers the five
111
+ * investor-relations models, everything else got delete coverage only, and a
112
+ * query the checker never runs for is a query it cannot even count.
113
+ *
114
+ * `AuditLog` joined them on 2026-09-26, on the same admission criterion and by
115
+ * measurement rather than by inspection. It is the largest of the four by some
116
+ * distance and the only one carrying correlatable personal data: a census of
117
+ * the anonymously readable rows found, across roughly 70,000 rows, at most five
118
+ * distinct email identities, 33 distinct IP addresses, at most four person
119
+ * names and two user agents. Report that as a small number of data subjects
120
+ * with a great many records about each, NOT as a large exposure — the row count
121
+ * is a true number answering a question nobody asked. Note also that 27,964
122
+ * `accountName` rows, first classified as an account label, were hash-matched
123
+ * in-database against the users table to three real email addresses, so
124
+ * per-subject completeness is higher than a field-name reading suggests.
125
+ *
126
+ * Decorating them changes NO behaviour while the checker is in shadow — a
127
+ * would-deny is logged and counted and then allowed. What it changes is that
128
+ * the exposure becomes measurable.
129
+ *
130
+ * `Fund` joined them on 2026-09-27, and it is the one admission that corrects a
131
+ * belief rather than adding a surface. The exposure is an unauthenticated
132
+ * request receiving HTTP 200 with every fund's P&L — measured on the deployed
133
+ * API by Sophie Nguyen at 02:42Z and independently by James Kirkland at
134
+ * 09:46:56Z, not inferred from the schema. `Fund` carries `aum`,
135
+ * `navPerShare` and `highWaterMarkNav`.
136
+ *
137
+ * The belief it corrects: this gap was being treated as something the
138
+ * `CORTEX_AUTHCHECKER_ENFORCE` flip would close. **It would not have.** `Fund`
139
+ * was in neither list, so its reads were never decorated, so the checker never
140
+ * ran for them — and per the paragraph above, a query the checker never runs
141
+ * for is a query it cannot even count. Waiting for the enforcement flip would
142
+ * have closed the four models here and left every fund's P&L answering to
143
+ * anyone, with nothing in the would-deny ratio to show it. Coverage and
144
+ * enforcement are separate axes and only one of them was being tracked.
145
+ *
146
+ * `FundAssignment` is a candidate and is deliberately NOT admitted here. It
147
+ * reveals which accounts belong to which fund, which is structural rather than
148
+ * P&L, and no anonymous probe of it has been run. Admitting it on inspection
149
+ * would break the criterion this list is built on — by measurement, not by
150
+ * reading the schema. Measure it, then admit it. Enforcement cannot be argued from a
151
+ * would-deny ratio that reflects only surfaces nobody ever authenticated to,
152
+ * and the measurement has to exist before the decision does.
153
+ */
154
+ exports.TENANT_SCOPED_READ_MODELS = [
155
+ 'Organization',
156
+ 'OrgMembership',
157
+ 'User',
158
+ 'AuditLog',
159
+ 'Fund',
160
+ ...exports.DESK_READ_MODELS,
161
+ ];
162
+ /**
163
+ * Action-name prefixes that MUTATE. Everything else on a generated CRUD
164
+ * resolver reads.
165
+ *
166
+ * Read actions are derived by exclusion rather than listed, because the
167
+ * generator names them inconsistently — `organizations`, `organization`,
168
+ * `getOrganization`, `findFirstOrganization`, `aggregateOrganization`,
169
+ * `groupByOrganization` are all reads of one model. Enumerating them by hand is
170
+ * how a read gets missed silently; excluding the four mutation shapes cannot.
171
+ */
172
+ const MUTATION_PREFIXES = [
173
+ 'create',
174
+ 'update',
175
+ 'delete',
176
+ 'upsert',
177
+ ];
178
+ /**
179
+ * The read actions a model's generated CRUD resolver actually exposes.
180
+ *
181
+ * Derived from the real prototype, so a generator rename shows up as a smaller
182
+ * set rather than as silently absent coverage.
183
+ */
184
+ function readActionsOf(model) {
185
+ const prototype = crudResolverPrototype(model);
186
+ if (!prototype)
187
+ return [];
188
+ return Object.getOwnPropertyNames(prototype).filter((name) => {
189
+ if (name === 'constructor')
190
+ return false;
191
+ if (typeof prototype[name] !== 'function')
192
+ return false;
193
+ return !MUTATION_PREFIXES.some((prefix) => name.startsWith(prefix));
194
+ });
195
+ }
196
+ /**
197
+ * Looks up the generated `<Model>CrudResolver` class for a model, so delete
198
+ * action names can be validated against the real resolver surface instead of
199
+ * being assumed by convention.
200
+ */
201
+ function crudResolverPrototype(model) {
202
+ const resolverClass = generatedIndex[`${model}CrudResolver`];
203
+ if (typeof resolverClass !== 'function') {
204
+ return undefined;
205
+ }
206
+ return resolverClass.prototype;
207
+ }
208
+ /**
209
+ * Builds the CORTEX authorization enhance-map. Pure (no metadata mutation) so
210
+ * tests can pin its contents without touching TypeGraphQL global state.
211
+ *
212
+ * @returns The enhance map and a summary of the coverage it encodes.
213
+ */
214
+ function buildCortexAuthorizationMap() {
215
+ var _a;
216
+ const map = {};
217
+ const skippedActions = [];
218
+ let decoratedActions = 0;
219
+ let deleteCoverageModels = 0;
220
+ for (const model of exports.IR_MODELS) {
221
+ map[model] = { _all: [(0, type_graphql_1.Authorized)()] };
222
+ decoratedActions += 1;
223
+ }
224
+ // Read coverage for the tenant-scoped models, applied BEFORE the delete pass
225
+ // so the two merge into one action config rather than overwriting it.
226
+ const readActionsByModel = new Map();
227
+ let readCoverageModels = 0;
228
+ for (const model of exports.TENANT_SCOPED_READ_MODELS) {
229
+ const actions = readActionsOf(model);
230
+ if (actions.length === 0) {
231
+ skippedActions.push(`${model}:reads`);
232
+ continue;
233
+ }
234
+ const config = {};
235
+ for (const action of actions) {
236
+ config[action] = [(0, type_graphql_1.Authorized)()];
237
+ }
238
+ readActionsByModel.set(model, config);
239
+ decoratedActions += actions.length;
240
+ readCoverageModels += 1;
241
+ }
242
+ const irModelSet = new Set(exports.IR_MODELS);
243
+ for (const model of Object.values(client_1.Prisma.ModelName)) {
244
+ // IR models already have full coverage; decorating deletes again would
245
+ // register duplicate Authorized metadata on the same fields.
246
+ if (irModelSet.has(model)) {
247
+ continue;
248
+ }
249
+ const prototype = crudResolverPrototype(model);
250
+ const actionsConfig = {
251
+ ...((_a = readActionsByModel.get(model)) !== null && _a !== void 0 ? _a : {}),
252
+ };
253
+ let coveredForModel = 0;
254
+ for (const action of [`deleteOne${model}`, `deleteMany${model}`]) {
255
+ if (prototype && typeof prototype[action] === 'function') {
256
+ actionsConfig[action] = [(0, type_graphql_1.Authorized)()];
257
+ coveredForModel += 1;
258
+ }
259
+ else {
260
+ skippedActions.push(action);
261
+ }
262
+ }
263
+ if (coveredForModel > 0 || Object.keys(actionsConfig).length > 0) {
264
+ map[model] =
265
+ actionsConfig;
266
+ decoratedActions += coveredForModel;
267
+ deleteCoverageModels += 1;
268
+ }
269
+ }
270
+ return {
271
+ map,
272
+ summary: {
273
+ fullCoverageModels: exports.IR_MODELS.length,
274
+ deleteCoverageModels,
275
+ readCoverageModels,
276
+ decoratedActions,
277
+ skippedActions,
278
+ },
279
+ };
280
+ }
281
+ let appliedSummary;
282
+ /**
283
+ * Applies the CORTEX authorization map to the generated resolvers. Idempotent:
284
+ * decorators land in TypeGraphQL's global metadata storage, so applying twice
285
+ * would duplicate `Authorized` metadata — subsequent calls return the cached
286
+ * summary without re-applying.
287
+ *
288
+ * Call BEFORE `buildSchema`. The registered `cortexAuthChecker` stays
289
+ * SHADOW-FIRST (log + count + allow) until `CORTEX_AUTHCHECKER_ENFORCE` is
290
+ * explicitly flipped on.
291
+ *
292
+ * @returns The {@link AuthorizationMapSummary} for the boot log.
293
+ */
294
+ function applyCortexAuthorizationMap() {
295
+ if (appliedSummary) {
296
+ return appliedSummary;
297
+ }
298
+ const { map, summary } = buildCortexAuthorizationMap();
299
+ (0, typegraphql_prisma_1.applyResolversEnhanceMap)(map);
300
+ if (summary.skippedActions.length > 0) {
301
+ logger_1.logger.warn('[cortex-authz] delete actions missing from generated resolvers — authorization map drifted from codegen', { skippedActions: summary.skippedActions });
302
+ }
303
+ appliedSummary = summary;
304
+ return summary;
305
+ }
306
+ //# sourceMappingURL=authorization-map.js.map
@@ -0,0 +1,143 @@
1
+ /**
2
+ * CORTEX-P0-001 phase 2 — `@Authorized()` coverage for generated CRUD resolvers
3
+ * (audit B01-backend-legacy-03).
4
+ *
5
+ * The `cortexAuthChecker` registered in `buildSchema` is only invoked by
6
+ * TypeGraphQL for fields carrying an `@Authorized()` decorator; the
7
+ * auto-generated typegraphql-prisma resolvers carry none, so the checker was
8
+ * registered-but-inert. This module applies decorators via
9
+ * `applyResolversEnhanceMap`, making the checker actually execute:
10
+ *
11
+ * - FULL coverage (`_all`) for the five investor-relations models —
12
+ * regulated PII (tax documents, KYC status, LP capital ledger) that must
13
+ * never sit on an unauthenticated CRUD surface.
14
+ * - DELETE mutations (`deleteOne*` / `deleteMany*`) for every other model —
15
+ * the most destructive operations on the trading system-of-record.
16
+ *
17
+ * CRITICAL SAFETY CONTRACT — the checker itself remains SHADOW-FIRST: while
18
+ * `CORTEX_AUTHCHECKER_ENFORCE` is OFF (default) a would-deny operation is
19
+ * logged + counted and then ALLOWED, so engine service traffic cannot break.
20
+ * This module only determines WHERE the checker runs, not what it does.
21
+ * Graduation rule (audit B01-backend-legacy-07): enforce only after
22
+ * `cortex_authchecker_evaluations_total` > 0 and the would-deny series has
23
+ * been observed over a full trading week.
24
+ *
25
+ * Must be applied BEFORE `buildSchema` — decorators land in TypeGraphQL's
26
+ * global metadata storage, which `buildSchema` reads.
27
+ */
28
+ import { type ResolversEnhanceMap } from '../generated/typegraphql-prisma';
29
+ /** Model names accepted by the generated {@link ResolversEnhanceMap}. */
30
+ type EnhanceModelName = keyof ResolversEnhanceMap;
31
+ /**
32
+ * The five investor-relations models receiving FULL (`_all`) coverage:
33
+ * every generated query and mutation on these models invokes the authChecker.
34
+ */
35
+ export declare const IR_MODELS: readonly EnhanceModelName[];
36
+ /**
37
+ * The trading-desk models, admitted to {@link TENANT_SCOPED_READ_MODELS} at
38
+ * birth. The measurement criterion below exists to find surfaces that were
39
+ * already answering to anyone; these never did. Their row scope is the
40
+ * tenancy predicate in `src/auth/tenancy-scope.ts` (`DESK_MODELS`: a user's
41
+ * own rows for Follow, PushSubscription, UserTotp and an unshared
42
+ * AdaConversation; the fund tenant for DeskDecision, AutoFollowRule and a
43
+ * shared AdaConversation; the user or organization for FeatureFlagOverride),
44
+ * enforced in every mode, with an unauthenticated read refused outright by
45
+ * the tenancy middleware. Decorating them here puts the same reads on the
46
+ * checker's evaluation and would-deny series as the models below.
47
+ */
48
+ export declare const DESK_READ_MODELS: readonly EnhanceModelName[];
49
+ /**
50
+ * Models whose READ actions are decorated as well as their deletes.
51
+ *
52
+ * These four answer to anyone today. A read-only probe of the deployed API
53
+ * with no Authorization header returns a real organisation name, a real user's
54
+ * email address, and a real membership row, so the standing escalation is not
55
+ * theoretical. They were outside the checker entirely: `_all` covers the five
56
+ * investor-relations models, everything else got delete coverage only, and a
57
+ * query the checker never runs for is a query it cannot even count.
58
+ *
59
+ * `AuditLog` joined them on 2026-09-26, on the same admission criterion and by
60
+ * measurement rather than by inspection. It is the largest of the four by some
61
+ * distance and the only one carrying correlatable personal data: a census of
62
+ * the anonymously readable rows found, across roughly 70,000 rows, at most five
63
+ * distinct email identities, 33 distinct IP addresses, at most four person
64
+ * names and two user agents. Report that as a small number of data subjects
65
+ * with a great many records about each, NOT as a large exposure — the row count
66
+ * is a true number answering a question nobody asked. Note also that 27,964
67
+ * `accountName` rows, first classified as an account label, were hash-matched
68
+ * in-database against the users table to three real email addresses, so
69
+ * per-subject completeness is higher than a field-name reading suggests.
70
+ *
71
+ * Decorating them changes NO behaviour while the checker is in shadow — a
72
+ * would-deny is logged and counted and then allowed. What it changes is that
73
+ * the exposure becomes measurable.
74
+ *
75
+ * `Fund` joined them on 2026-09-27, and it is the one admission that corrects a
76
+ * belief rather than adding a surface. The exposure is an unauthenticated
77
+ * request receiving HTTP 200 with every fund's P&L — measured on the deployed
78
+ * API by Sophie Nguyen at 02:42Z and independently by James Kirkland at
79
+ * 09:46:56Z, not inferred from the schema. `Fund` carries `aum`,
80
+ * `navPerShare` and `highWaterMarkNav`.
81
+ *
82
+ * The belief it corrects: this gap was being treated as something the
83
+ * `CORTEX_AUTHCHECKER_ENFORCE` flip would close. **It would not have.** `Fund`
84
+ * was in neither list, so its reads were never decorated, so the checker never
85
+ * ran for them — and per the paragraph above, a query the checker never runs
86
+ * for is a query it cannot even count. Waiting for the enforcement flip would
87
+ * have closed the four models here and left every fund's P&L answering to
88
+ * anyone, with nothing in the would-deny ratio to show it. Coverage and
89
+ * enforcement are separate axes and only one of them was being tracked.
90
+ *
91
+ * `FundAssignment` is a candidate and is deliberately NOT admitted here. It
92
+ * reveals which accounts belong to which fund, which is structural rather than
93
+ * P&L, and no anonymous probe of it has been run. Admitting it on inspection
94
+ * would break the criterion this list is built on — by measurement, not by
95
+ * reading the schema. Measure it, then admit it. Enforcement cannot be argued from a
96
+ * would-deny ratio that reflects only surfaces nobody ever authenticated to,
97
+ * and the measurement has to exist before the decision does.
98
+ */
99
+ export declare const TENANT_SCOPED_READ_MODELS: readonly EnhanceModelName[];
100
+ /** Summary of the coverage applied, for the boot log and tests. */
101
+ export interface AuthorizationMapSummary {
102
+ /** Models decorated with `_all` (full CRUD coverage). */
103
+ readonly fullCoverageModels: number;
104
+ /** Models whose delete mutations were decorated. */
105
+ readonly deleteCoverageModels: number;
106
+ /** Models whose READ actions were decorated as well ({@link TENANT_SCOPED_READ_MODELS}). */
107
+ readonly readCoverageModels: number;
108
+ /** Total decorated resolver actions (delete actions + `_all` markers). */
109
+ readonly decoratedActions: number;
110
+ /**
111
+ * Delete-action names skipped because the generated CRUD resolver does not
112
+ * expose them — non-empty output means the naming convention drifted and the
113
+ * map must be updated. Never silently ignored: logged at warn on apply.
114
+ */
115
+ readonly skippedActions: readonly string[];
116
+ }
117
+ /** Internal build output: the map plus its audit summary. */
118
+ interface BuiltAuthorizationMap {
119
+ readonly map: ResolversEnhanceMap;
120
+ readonly summary: AuthorizationMapSummary;
121
+ }
122
+ /**
123
+ * Builds the CORTEX authorization enhance-map. Pure (no metadata mutation) so
124
+ * tests can pin its contents without touching TypeGraphQL global state.
125
+ *
126
+ * @returns The enhance map and a summary of the coverage it encodes.
127
+ */
128
+ export declare function buildCortexAuthorizationMap(): BuiltAuthorizationMap;
129
+ /**
130
+ * Applies the CORTEX authorization map to the generated resolvers. Idempotent:
131
+ * decorators land in TypeGraphQL's global metadata storage, so applying twice
132
+ * would duplicate `Authorized` metadata — subsequent calls return the cached
133
+ * summary without re-applying.
134
+ *
135
+ * Call BEFORE `buildSchema`. The registered `cortexAuthChecker` stays
136
+ * SHADOW-FIRST (log + count + allow) until `CORTEX_AUTHCHECKER_ENFORCE` is
137
+ * explicitly flipped on.
138
+ *
139
+ * @returns The {@link AuthorizationMapSummary} for the boot log.
140
+ */
141
+ export declare function applyCortexAuthorizationMap(): AuthorizationMapSummary;
142
+ export {};
143
+ //# sourceMappingURL=authorization-map.d.ts.map
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+ /**
3
+ * CORTEX-P0-001 — resolver-level authorization AuthChecker (SHADOW-FIRST).
4
+ *
5
+ * A TypeGraphQL {@link AuthChecker} that evaluates whether an operation WOULD be
6
+ * allowed under resolver-level authorization, closing the residual vector called
7
+ * out in the tenancy-scoping middleware docs: a governed model reached
8
+ * transitively through a non-governed root, and — more broadly — any
9
+ * `@Authorized()`-decorated field executed without a verified principal.
10
+ *
11
+ * CRITICAL SAFETY CONTRACT — this change is additive and default-OFF. When
12
+ * enforcement is OFF (the default), the checker NEVER denies: it returns `true`
13
+ * for every operation, emitting a structured warn log and incrementing a
14
+ * Prometheus counter for any operation that enforcement WOULD deny. Live
15
+ * behaviour is byte-identical to before this change until
16
+ * `CORTEX_AUTHCHECKER_ENFORCE` is flipped on. Additionally, TypeGraphQL only
17
+ * invokes an AuthChecker for fields decorated with `@Authorized()`; the
18
+ * auto-generated typegraphql-prisma resolvers carry no such decorator, so
19
+ * registering this checker via `buildSchema({ authChecker })` is inert at
20
+ * runtime until decorators are added in the separate enforcement phase.
21
+ *
22
+ * Decision model (mirrors the token-verifier principal kinds):
23
+ *
24
+ * - `server` — trusted server-to-server caller. ALWAYS allowed; the
25
+ * engine + utils call the CRUD resolvers with a server principal and must
26
+ * retain full access, bypassing any role gate.
27
+ * - `admin` / `user` — verified end-user. Allowed when the field requires no
28
+ * specific role, or when the principal carries one of the required roles;
29
+ * otherwise a would-deny with reason `insufficient_role`.
30
+ * - `null` (no verified principal) — a genuinely unauthenticated caller on a
31
+ * non-public (i.e. `@Authorized()`) operation. A would-deny with reason
32
+ * `unauthenticated`.
33
+ *
34
+ * @see src/auth/tenancy-scope.ts for the row-level (data-scope) counterpart.
35
+ * @see src/auth/token-verifier.ts for `BackendPrincipal`.
36
+ */
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ exports.cortexAuthChecker = exports.cortexAuthCheckerWouldDenyTotal = exports.cortexAuthCheckerEvaluationsTotal = exports.CORTEX_AUTHCHECKER_ENFORCE_ENV = void 0;
39
+ exports.isAuthCheckerEnforced = isAuthCheckerEnforced;
40
+ exports.evaluateWouldAllow = evaluateWouldAllow;
41
+ const prom_client_1 = require("prom-client");
42
+ const metrics_1 = require("../config/metrics.cjs");
43
+ const logger_1 = require("../utils/logger.cjs");
44
+ // -----------------------------------------------------------------------------
45
+ // Enforcement flag
46
+ // -----------------------------------------------------------------------------
47
+ /**
48
+ * Environment variable gating enforcement. When set to `true`/`1`, the checker
49
+ * fails closed (returns `false`) for any would-deny operation. Unset or any
50
+ * other value keeps the checker in SHADOW mode (observe + count + allow).
51
+ */
52
+ exports.CORTEX_AUTHCHECKER_ENFORCE_ENV = 'CORTEX_AUTHCHECKER_ENFORCE';
53
+ /** The `admin` role string used to satisfy admin-gated `@Authorized()` fields. */
54
+ const ADMIN_ROLE = 'admin';
55
+ /**
56
+ * Whether resolver-level authorization enforcement is ON. Read fresh on each
57
+ * call (a cheap env read) so the shadow→enforce graduation can be flipped
58
+ * operationally without a process restart — the same pattern the tenancy-scoping
59
+ * middleware uses. Defaults to OFF (shadow) for any unset/unrecognised value.
60
+ *
61
+ * @param env - Environment source (defaults to `process.env`); injectable for tests.
62
+ * @returns `true` only when the flag is explicitly `true`/`1`.
63
+ */
64
+ function isAuthCheckerEnforced(env = process.env) {
65
+ var _a;
66
+ const raw = ((_a = env[exports.CORTEX_AUTHCHECKER_ENFORCE_ENV]) !== null && _a !== void 0 ? _a : '').trim().toLowerCase();
67
+ return raw === 'true' || raw === '1';
68
+ }
69
+ /**
70
+ * Counts EVERY AuthChecker invocation, regardless of outcome (audit
71
+ * B01-backend-legacy-07). A flat-zero {@link cortexAuthCheckerWouldDenyTotal}
72
+ * is ambiguous on its own: it can mean "no traffic would be denied" OR "the
73
+ * checker never ran" (no `@Authorized()` field was ever executed) — exactly the
74
+ * false-confidence pattern that preceded the beta-net-cap fail-open. Graduation
75
+ * rule: enforce only when this counter is > 0 and the would-deny series has
76
+ * been observed over a full trading week.
77
+ */
78
+ exports.cortexAuthCheckerEvaluationsTotal = new prom_client_1.Counter({
79
+ name: 'cortex_authchecker_evaluations_total',
80
+ help: 'Total AuthChecker invocations, any outcome (zero means no @Authorized field was executed — distinct from "no would-denies")',
81
+ registers: [metrics_1.metricsRegistry],
82
+ });
83
+ /**
84
+ * Counts operations that resolver-level authorization WOULD deny. In shadow mode
85
+ * this is the primary signal proving whether flipping `CORTEX_AUTHCHECKER_ENFORCE`
86
+ * to `enforce` would reject any legitimate platform or engine traffic. Labelled
87
+ * by the discriminated {@link WouldDenyReason}.
88
+ */
89
+ exports.cortexAuthCheckerWouldDenyTotal = new prom_client_1.Counter({
90
+ name: 'cortex_authchecker_would_deny_total',
91
+ help: 'Operations resolver-level authorization would deny, by reason (counted in shadow mode without denying)',
92
+ labelNames: ['reason'],
93
+ registers: [metrics_1.metricsRegistry],
94
+ });
95
+ /**
96
+ * Pure evaluation of whether a principal would satisfy the required roles for an
97
+ * operation. Performs no I/O and no logging.
98
+ *
99
+ * @param principal - The verified principal, or `null` for an unauthenticated caller.
100
+ * @param requiredRoles - Roles declared on the field's `@Authorized(...)` decorator
101
+ * (empty when the field only requires authentication).
102
+ * @returns The {@link AuthEvaluation}.
103
+ */
104
+ function evaluateWouldAllow(principal, requiredRoles) {
105
+ if (!principal) {
106
+ return { wouldAllow: false, reason: 'unauthenticated' };
107
+ }
108
+ // Server-to-server callers are unconditionally allowed and bypass role gates.
109
+ if (principal.kind === 'server') {
110
+ return { wouldAllow: true };
111
+ }
112
+ // Authenticated user/admin with no specific role requirement -> allowed.
113
+ if (requiredRoles.length === 0) {
114
+ return { wouldAllow: true };
115
+ }
116
+ const principalRoles = principal.kind === 'admin'
117
+ ? [...principal.roles, ADMIN_ROLE]
118
+ : principal.roles;
119
+ const roleSet = new Set(principalRoles);
120
+ const hasRequiredRole = requiredRoles.some((role) => roleSet.has(role));
121
+ return hasRequiredRole
122
+ ? { wouldAllow: true }
123
+ : { wouldAllow: false, reason: 'insufficient_role' };
124
+ }
125
+ /** Describe an operation for structured logs, without leaking arguments. */
126
+ function describeOperation(resolverData) {
127
+ var _a, _b;
128
+ const { info } = resolverData;
129
+ return {
130
+ operationType: info.operation.operation,
131
+ operationName: (_b = (_a = info.operation.name) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : info.fieldName,
132
+ field: info.fieldName,
133
+ };
134
+ }
135
+ /**
136
+ * The CORTEX-P0-001 AuthChecker. Register via
137
+ * `buildSchema({ authChecker: cortexAuthChecker })`.
138
+ *
139
+ * SHADOW (default): a would-deny operation increments
140
+ * {@link cortexAuthCheckerWouldDenyTotal}, emits a warn log, and RETURNS TRUE —
141
+ * no behaviour change. ENFORCE (`CORTEX_AUTHCHECKER_ENFORCE=true`): a would-deny
142
+ * operation is logged, the counter is incremented, and the checker RETURNS FALSE
143
+ * (fail closed). Operations that would be allowed always return `true` with no
144
+ * metric or log emission.
145
+ */
146
+ const cortexAuthChecker = (resolverData, roles) => {
147
+ var _a, _b, _c;
148
+ // Unconditional: proves the checker is actually reachable (see
149
+ // cortexAuthCheckerEvaluationsTotal TSDoc / audit B01-backend-legacy-07).
150
+ exports.cortexAuthCheckerEvaluationsTotal.inc();
151
+ const principal = (_a = resolverData.context.principal) !== null && _a !== void 0 ? _a : null;
152
+ const evaluation = evaluateWouldAllow(principal, roles);
153
+ if (evaluation.wouldAllow) {
154
+ return true;
155
+ }
156
+ const reason = (_b = evaluation.reason) !== null && _b !== void 0 ? _b : 'unauthenticated';
157
+ const enforced = isAuthCheckerEnforced();
158
+ const operation = describeOperation(resolverData);
159
+ exports.cortexAuthCheckerWouldDenyTotal.inc({ reason });
160
+ logger_1.logger.warn(enforced
161
+ ? '[cortex-authchecker] denying operation (enforce)'
162
+ : '[cortex-authchecker] shadow would-deny (allowing)', {
163
+ ...operation,
164
+ reason,
165
+ enforced,
166
+ principalKind: (_c = principal === null || principal === void 0 ? void 0 : principal.kind) !== null && _c !== void 0 ? _c : 'none',
167
+ requiredRoles: [...roles],
168
+ });
169
+ return !enforced;
170
+ };
171
+ exports.cortexAuthChecker = cortexAuthChecker;
172
+ //# sourceMappingURL=cortex-auth-checker.js.map