@adaptic/backend-legacy 0.0.1056 → 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 (292) hide show
  1. package/Account.cjs +14 -0
  2. package/AccountLinkingRequest.cjs +14 -0
  3. package/AccountRiskMetrics.cjs +11 -0
  4. package/AdaConversation.cjs +14 -0
  5. package/Alert.cjs +11 -0
  6. package/Allocation.cjs +11 -0
  7. package/AlpacaAccount.cjs +36 -0
  8. package/Authenticator.cjs +14 -0
  9. package/AutoFollowRule.cjs +14 -0
  10. package/BrokerageAccount.cjs +11 -0
  11. package/Customer.cjs +14 -0
  12. package/DeskDecision.cjs +11 -0
  13. package/FeatureFlagOverride.cjs +14 -0
  14. package/Follow.cjs +14 -0
  15. package/Fund.cjs +56 -0
  16. package/FundAssignment.cjs +14 -0
  17. package/Investor.cjs +14 -0
  18. package/LinkedProvider.cjs +14 -0
  19. package/LlmConfiguration.cjs +14 -0
  20. package/Mandate.cjs +14 -0
  21. package/MandateApproval.cjs +14 -0
  22. package/MandateVersion.cjs +14 -0
  23. package/NotificationDelivery.cjs +14 -0
  24. package/NotificationPreference.cjs +14 -0
  25. package/OrgMembership.cjs +14 -0
  26. package/PolicyOverlay.cjs +64 -0
  27. package/PushSubscription.cjs +14 -0
  28. package/RiskEscalationEvent.cjs +33 -0
  29. package/Session.cjs +14 -0
  30. package/Strategy.cjs +28 -0
  31. package/StrategyHealthSnapshot.cjs +11 -0
  32. package/StrategySubscription.cjs +11 -0
  33. package/TradingPolicy.cjs +6 -0
  34. package/User.cjs +11 -0
  35. package/UserTotp.cjs +14 -0
  36. package/WaitlistEntry.cjs +14 -0
  37. package/auth/authorization-map.cjs +306 -0
  38. package/auth/authorization-map.d.ts +143 -0
  39. package/auth/cortex-auth-checker.cjs +172 -0
  40. package/auth/cortex-auth-checker.d.ts +114 -0
  41. package/auth/credential-fields.cjs +51 -0
  42. package/auth/credential-fields.d.ts +19 -0
  43. package/auth/credential-redaction.cjs +134 -0
  44. package/auth/credential-redaction.d.ts +60 -0
  45. package/auth/graphql-auth-shadow.cjs +317 -0
  46. package/auth/graphql-auth-shadow.d.ts +194 -0
  47. package/auth/membership-write-authority.cjs +131 -0
  48. package/auth/membership-write-authority.d.ts +110 -0
  49. package/auth/mutation-authorization.cjs +376 -0
  50. package/auth/mutation-authorization.d.ts +261 -0
  51. package/auth/nested-write-inspector.cjs +189 -0
  52. package/auth/nested-write-inspector.d.ts +94 -0
  53. package/auth/nested-write-policy.cjs +189 -0
  54. package/auth/nested-write-policy.d.ts +99 -0
  55. package/auth/service-token.cjs +316 -0
  56. package/auth/service-token.d.ts +94 -0
  57. package/auth/tenancy-scope.cjs +736 -0
  58. package/auth/tenancy-scope.d.ts +347 -0
  59. package/auth/token-verifier.cjs +451 -0
  60. package/auth/token-verifier.d.ts +153 -0
  61. package/auth/totp.cjs +265 -0
  62. package/auth/totp.d.ts +111 -0
  63. package/auth/user-write-content.cjs +116 -0
  64. package/auth/user-write-content.d.ts +47 -0
  65. package/auth/ws-auth-context.cjs +75 -0
  66. package/auth/ws-auth-context.d.ts +69 -0
  67. package/config/jwtConfig.cjs +52 -0
  68. package/config/jwtConfig.d.ts +16 -0
  69. package/config/metrics.cjs +356 -0
  70. package/config/metrics.d.ts +128 -0
  71. package/config/persisted-queries.cjs +122 -0
  72. package/config/persisted-queries.d.ts +40 -0
  73. package/config/server-only-models.cjs +166 -0
  74. package/config/server-only-models.d.ts +89 -0
  75. package/config/tracing.d.ts +24 -0
  76. package/esm/Account.mjs +14 -0
  77. package/esm/AccountLinkingRequest.mjs +14 -0
  78. package/esm/AccountRiskMetrics.mjs +11 -0
  79. package/esm/AdaConversation.mjs +14 -0
  80. package/esm/Alert.mjs +11 -0
  81. package/esm/Allocation.mjs +11 -0
  82. package/esm/AlpacaAccount.mjs +36 -0
  83. package/esm/Authenticator.mjs +14 -0
  84. package/esm/AutoFollowRule.mjs +14 -0
  85. package/esm/BrokerageAccount.mjs +11 -0
  86. package/esm/Customer.mjs +14 -0
  87. package/esm/DeskDecision.mjs +11 -0
  88. package/esm/FeatureFlagOverride.mjs +14 -0
  89. package/esm/Follow.mjs +14 -0
  90. package/esm/Fund.mjs +56 -0
  91. package/esm/FundAssignment.mjs +14 -0
  92. package/esm/Investor.mjs +14 -0
  93. package/esm/LinkedProvider.mjs +14 -0
  94. package/esm/LlmConfiguration.mjs +14 -0
  95. package/esm/Mandate.mjs +14 -0
  96. package/esm/MandateApproval.mjs +14 -0
  97. package/esm/MandateVersion.mjs +14 -0
  98. package/esm/NotificationDelivery.mjs +14 -0
  99. package/esm/NotificationPreference.mjs +14 -0
  100. package/esm/OrgMembership.mjs +14 -0
  101. package/esm/PolicyOverlay.mjs +64 -0
  102. package/esm/PushSubscription.mjs +14 -0
  103. package/esm/RiskEscalationEvent.mjs +33 -0
  104. package/esm/Session.mjs +14 -0
  105. package/esm/Strategy.mjs +28 -0
  106. package/esm/StrategyHealthSnapshot.mjs +11 -0
  107. package/esm/StrategySubscription.mjs +11 -0
  108. package/esm/TradingPolicy.mjs +6 -0
  109. package/esm/User.mjs +11 -0
  110. package/esm/UserTotp.mjs +14 -0
  111. package/esm/WaitlistEntry.mjs +14 -0
  112. package/esm/generated/typeStrings/PolicyOverlay.d.ts +1 -1
  113. package/esm/generated/typeStrings/PolicyOverlay.mjs +18 -0
  114. package/esm/generated/typeStrings/TradingPolicy.d.ts +1 -1
  115. package/esm/generated/typeStrings/TradingPolicy.mjs +18 -0
  116. package/esm/generated/typeStrings/index.d.ts +2 -2
  117. package/esm/generated/typegraphql-prisma/enhance.mjs +18 -18
  118. package/esm/generated/typegraphql-prisma/enums/TradingPolicyScalarFieldEnum.d.ts +1 -0
  119. package/esm/generated/typegraphql-prisma/enums/TradingPolicyScalarFieldEnum.mjs +1 -0
  120. package/esm/generated/typegraphql-prisma/models/TradingPolicy.d.ts +20 -0
  121. package/esm/generated/typegraphql-prisma/models/TradingPolicy.mjs +27 -0
  122. package/esm/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindFirstTradingPolicyArgs.d.ts +1 -1
  123. package/esm/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindFirstTradingPolicyOrThrowArgs.d.ts +1 -1
  124. package/esm/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindManyTradingPolicyArgs.d.ts +1 -1
  125. package/esm/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/GroupByTradingPolicyArgs.d.ts +1 -1
  126. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCountOrderByAggregateInput.d.ts +1 -0
  127. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCountOrderByAggregateInput.mjs +7 -0
  128. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateInput.d.ts +1 -0
  129. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateInput.mjs +7 -0
  130. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateManyInput.d.ts +1 -0
  131. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateManyInput.mjs +7 -0
  132. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutAlpacaAccountInput.d.ts +1 -0
  133. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutAlpacaAccountInput.mjs +7 -0
  134. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutOverlaysInput.d.ts +1 -0
  135. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutOverlaysInput.mjs +7 -0
  136. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithAggregationInput.d.ts +1 -0
  137. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithAggregationInput.mjs +7 -0
  138. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithRelationInput.d.ts +1 -0
  139. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithRelationInput.mjs +7 -0
  140. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyScalarWhereWithAggregatesInput.d.ts +1 -0
  141. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyScalarWhereWithAggregatesInput.mjs +7 -0
  142. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateInput.d.ts +1 -0
  143. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateInput.mjs +7 -0
  144. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateManyMutationInput.d.ts +1 -0
  145. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateManyMutationInput.mjs +7 -0
  146. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutAlpacaAccountInput.d.ts +1 -0
  147. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutAlpacaAccountInput.mjs +7 -0
  148. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutOverlaysInput.d.ts +1 -0
  149. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutOverlaysInput.mjs +7 -0
  150. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereInput.d.ts +1 -0
  151. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereInput.mjs +7 -0
  152. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereUniqueInput.d.ts +1 -0
  153. package/esm/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereUniqueInput.mjs +7 -0
  154. package/esm/generated/typegraphql-prisma/resolvers/outputs/CreateManyAndReturnTradingPolicy.d.ts +1 -0
  155. package/esm/generated/typegraphql-prisma/resolvers/outputs/CreateManyAndReturnTradingPolicy.mjs +7 -0
  156. package/esm/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyCountAggregate.d.ts +1 -0
  157. package/esm/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyCountAggregate.mjs +7 -0
  158. package/esm/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyGroupBy.d.ts +1 -0
  159. package/esm/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyGroupBy.mjs +7 -0
  160. package/esm/index.d.ts +1 -0
  161. package/esm/index.mjs +2 -0
  162. package/esm/middleware/mutation-account-facts.d.ts +3 -0
  163. package/esm/middleware/mutation-account-facts.mjs +2 -0
  164. package/esm/middleware/trading-policy-audit.d.ts +16 -4
  165. package/esm/middleware/trading-policy-audit.mjs +40 -11
  166. package/esm/readers/index.d.ts +10 -0
  167. package/esm/readers/index.mjs +10 -0
  168. package/esm/readers/intraday-lane-prefs.d.ts +45 -0
  169. package/esm/readers/intraday-lane-prefs.mjs +71 -0
  170. package/esm/tests/trading-policy-lane-fields-roundtrip.harness.d.ts +14 -0
  171. package/esm/tests/trading-policy-lane-fields-roundtrip.harness.mjs +107 -0
  172. package/generated/typeStrings/PolicyOverlay.cjs +18 -0
  173. package/generated/typeStrings/PolicyOverlay.d.ts +1 -1
  174. package/generated/typeStrings/TradingPolicy.cjs +18 -0
  175. package/generated/typeStrings/TradingPolicy.d.ts +1 -1
  176. package/generated/typeStrings/index.d.ts +2 -2
  177. package/generated/typegraphql-prisma/enhance.cjs +21 -21
  178. package/generated/typegraphql-prisma/enums/TradingPolicyScalarFieldEnum.cjs +1 -0
  179. package/generated/typegraphql-prisma/enums/TradingPolicyScalarFieldEnum.d.ts +1 -0
  180. package/generated/typegraphql-prisma/index.cjs +6 -6
  181. package/generated/typegraphql-prisma/models/TradingPolicy.cjs +7 -0
  182. package/generated/typegraphql-prisma/models/TradingPolicy.d.ts +20 -0
  183. package/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindFirstTradingPolicyArgs.d.ts +1 -1
  184. package/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindFirstTradingPolicyOrThrowArgs.d.ts +1 -1
  185. package/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/FindManyTradingPolicyArgs.d.ts +1 -1
  186. package/generated/typegraphql-prisma/resolvers/crud/TradingPolicy/args/GroupByTradingPolicyArgs.d.ts +1 -1
  187. package/generated/typegraphql-prisma/resolvers/crud/args.index.cjs +95 -95
  188. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCountOrderByAggregateInput.cjs +6 -0
  189. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCountOrderByAggregateInput.d.ts +1 -0
  190. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateInput.cjs +6 -0
  191. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateInput.d.ts +1 -0
  192. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateManyInput.cjs +6 -0
  193. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateManyInput.d.ts +1 -0
  194. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutAlpacaAccountInput.cjs +6 -0
  195. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutAlpacaAccountInput.d.ts +1 -0
  196. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutOverlaysInput.cjs +6 -0
  197. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyCreateWithoutOverlaysInput.d.ts +1 -0
  198. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithAggregationInput.cjs +6 -0
  199. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithAggregationInput.d.ts +1 -0
  200. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithRelationInput.cjs +6 -0
  201. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyOrderByWithRelationInput.d.ts +1 -0
  202. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyScalarWhereWithAggregatesInput.cjs +6 -0
  203. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyScalarWhereWithAggregatesInput.d.ts +1 -0
  204. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateInput.cjs +6 -0
  205. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateInput.d.ts +1 -0
  206. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateManyMutationInput.cjs +6 -0
  207. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateManyMutationInput.d.ts +1 -0
  208. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutAlpacaAccountInput.cjs +6 -0
  209. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutAlpacaAccountInput.d.ts +1 -0
  210. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutOverlaysInput.cjs +6 -0
  211. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyUpdateWithoutOverlaysInput.d.ts +1 -0
  212. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereInput.cjs +6 -0
  213. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereInput.d.ts +1 -0
  214. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereUniqueInput.cjs +6 -0
  215. package/generated/typegraphql-prisma/resolvers/inputs/TradingPolicyWhereUniqueInput.d.ts +1 -0
  216. package/generated/typegraphql-prisma/resolvers/outputs/CreateManyAndReturnTradingPolicy.cjs +6 -0
  217. package/generated/typegraphql-prisma/resolvers/outputs/CreateManyAndReturnTradingPolicy.d.ts +1 -0
  218. package/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyCountAggregate.cjs +6 -0
  219. package/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyCountAggregate.d.ts +1 -0
  220. package/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyGroupBy.cjs +6 -0
  221. package/generated/typegraphql-prisma/resolvers/outputs/TradingPolicyGroupBy.d.ts +1 -0
  222. package/generated/typegraphql-prisma/resolvers/outputs/index.cjs +1 -1
  223. package/generated/typegraphql-prisma/resolvers/relations/args.index.cjs +32 -32
  224. package/index.cjs +2 -0
  225. package/index.d.ts +1 -0
  226. package/middleware/audit-log-write-redaction.cjs +143 -0
  227. package/middleware/audit-log-write-redaction.d.ts +82 -0
  228. package/middleware/audit-logger.cjs +378 -0
  229. package/middleware/audit-logger.d.ts +158 -0
  230. package/middleware/audit-payload-guard.cjs +107 -0
  231. package/middleware/audit-payload-guard.d.ts +85 -0
  232. package/middleware/auth.cjs +66 -0
  233. package/middleware/auth.d.ts +41 -0
  234. package/middleware/credential-field-guard.cjs +514 -0
  235. package/middleware/credential-field-guard.d.ts +173 -0
  236. package/middleware/generated-type-names.cjs +77 -0
  237. package/middleware/generated-type-names.d.ts +44 -0
  238. package/middleware/graphql-validation-plugin.cjs +310 -0
  239. package/middleware/graphql-validation-plugin.d.ts +98 -0
  240. package/middleware/guard-log-throttle.cjs +89 -0
  241. package/middleware/guard-log-throttle.d.ts +80 -0
  242. package/middleware/index.cjs +57 -0
  243. package/middleware/index.d.ts +14 -0
  244. package/middleware/input-validator.cjs +220 -0
  245. package/middleware/input-validator.d.ts +63 -0
  246. package/middleware/mandate-version-validation.cjs +131 -0
  247. package/middleware/mandate-version-validation.d.ts +41 -0
  248. package/middleware/mutation-account-facts.cjs +223 -0
  249. package/middleware/mutation-account-facts.d.ts +143 -0
  250. package/middleware/mutation-auth-guard.cjs +536 -0
  251. package/middleware/mutation-auth-guard.d.ts +100 -0
  252. package/middleware/mutation-membership-facts.cjs +276 -0
  253. package/middleware/mutation-membership-facts.d.ts +133 -0
  254. package/middleware/mutation-tenant-facts.cjs +132 -0
  255. package/middleware/mutation-tenant-facts.d.ts +81 -0
  256. package/middleware/query-complexity.cjs +182 -0
  257. package/middleware/query-complexity.d.ts +56 -0
  258. package/middleware/rate-limiter.cjs +223 -0
  259. package/middleware/rate-limiter.d.ts +93 -0
  260. package/middleware/rate-tier.cjs +111 -0
  261. package/middleware/rate-tier.d.ts +56 -0
  262. package/middleware/soft-delete.cjs +175 -0
  263. package/middleware/soft-delete.d.ts +146 -0
  264. package/middleware/tenancy-scoping.cjs +229 -0
  265. package/middleware/tenancy-scoping.d.ts +67 -0
  266. package/middleware/trading-policy-audit.cjs +353 -0
  267. package/middleware/trading-policy-audit.d.ts +184 -0
  268. package/middleware/types.cjs +17 -0
  269. package/middleware/types.d.ts +87 -0
  270. package/middleware/validation-examples.cjs +398 -0
  271. package/middleware/validation-examples.d.ts +76 -0
  272. package/package.json +10 -2
  273. package/readers/index.cjs +15 -0
  274. package/readers/index.d.ts +10 -0
  275. package/readers/intraday-lane-prefs.cjs +76 -0
  276. package/readers/intraday-lane-prefs.d.ts +45 -0
  277. package/esm/config/__tests__/server-only-surface.harness.d.ts +0 -12
  278. package/esm/config/__tests__/server-only-surface.harness.mjs +0 -41
  279. package/esm/middleware/__tests__/audit-log-write-redaction.harness.d.ts +0 -144
  280. package/esm/middleware/__tests__/audit-log-write-redaction.harness.mjs +0 -920
  281. package/esm/middleware/__tests__/credential-field-coverage.harness.d.ts +0 -55
  282. package/esm/middleware/__tests__/credential-field-coverage.harness.mjs +0 -440
  283. package/esm/middleware/__tests__/credential-field-guard.harness.d.ts +0 -34
  284. package/esm/middleware/__tests__/credential-field-guard.harness.mjs +0 -212
  285. package/esm/middleware/__tests__/mutation-auth-guard.harness.d.ts +0 -56
  286. package/esm/middleware/__tests__/mutation-auth-guard.harness.mjs +0 -570
  287. package/esm/middleware/__tests__/rate-limit-test-utils.d.ts +0 -60
  288. package/esm/middleware/__tests__/rate-limit-test-utils.mjs +0 -85
  289. package/esm/middleware/__tests__/ts-node-harness.d.ts +0 -10
  290. package/esm/middleware/__tests__/ts-node-harness.mjs +0 -71
  291. package/health.cjs +0 -274
  292. package/server.cjs +0 -607
@@ -0,0 +1,69 @@
1
+ /**
2
+ * WebSocket connection-auth decision for the `/subscriptions` transport.
3
+ *
4
+ * graphql-ws invokes the `context` callback lazily, on Subscribe. Whatever that
5
+ * callback throws terminates the socket: graphql-ws catches it in its message
6
+ * handler and closes with `CloseCode.InternalServerError` (4500), carrying the
7
+ * error message as the close reason. There is deliberately no path that keeps
8
+ * an unverified socket open with a degraded context — a subscription that
9
+ * streams data to a caller whose token did not verify is an authentication
10
+ * bypass, not a degraded mode.
11
+ *
12
+ * The decision is separated from its effects (metrics, logging, Prisma
13
+ * attachment) so the security-relevant predicate is a pure function that can be
14
+ * exercised, and mutation-proven, without booting the server.
15
+ */
16
+ import { GraphQLError } from 'graphql';
17
+ import { type AuthErrorReason, type BackendPrincipal } from './token-verifier';
18
+ /**
19
+ * Outcome of evaluating a WebSocket connection's `authorization` parameter.
20
+ *
21
+ * - `anonymous`: no bearer token presented. The socket opens with a null
22
+ * principal; the AuthChecker rejects any operation that requires one.
23
+ * - `authenticated`: the token verified to a `BackendPrincipal`.
24
+ * - `rejected`: a token was presented and failed verification. The caller MUST
25
+ * throw so graphql-ws closes the socket.
26
+ */
27
+ export type WsAuthDecision = {
28
+ kind: 'anonymous';
29
+ } | {
30
+ kind: 'authenticated';
31
+ principal: BackendPrincipal;
32
+ } | {
33
+ kind: 'rejected';
34
+ reason: AuthErrorReason;
35
+ };
36
+ /**
37
+ * Token verification entry point. Injectable so callers can exercise the
38
+ * decision without provisioning real signing keys.
39
+ */
40
+ export type TokenVerifier = (token: string) => Promise<BackendPrincipal>;
41
+ /**
42
+ * Extract the raw token from an `Authorization` value. Returns the empty string
43
+ * for anything that is not a well-formed `Bearer <token>` header, which the
44
+ * caller treats as "no token presented" rather than as a malformed token.
45
+ */
46
+ export declare function parseBearerToken(authHeader: string | undefined): string;
47
+ /**
48
+ * Classify a WebSocket connection's credentials.
49
+ *
50
+ * A presented-but-unverifiable token always yields `rejected`, never
51
+ * `anonymous`. Downgrading a failed verification to an anonymous session would
52
+ * convert an authentication failure into a weaker session that still serves
53
+ * data — the bypass this function exists to make unrepresentable.
54
+ *
55
+ * Verification failures that are not `AuthError` are classified
56
+ * `bad_signature` rather than escaping, so an unexpected verifier fault still
57
+ * fails closed (socket closed) instead of surfacing as an unhandled rejection.
58
+ */
59
+ export declare function decideWsAuth(authHeader: string | undefined, verify?: TokenVerifier): Promise<WsAuthDecision>;
60
+ /**
61
+ * The error a rejected WebSocket connection throws from its `context` callback.
62
+ *
63
+ * `extensions.http.status` is carried for symmetry with the HTTP context: the
64
+ * WebSocket transport closes rather than producing an HTTP response, but any
65
+ * future code that funnels a WS rejection into an HTTP reply gets the correct
66
+ * status without a second definition of it.
67
+ */
68
+ export declare function unauthenticatedWsError(reason: AuthErrorReason): GraphQLError;
69
+ //# sourceMappingURL=ws-auth-context.d.ts.map
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ /**
3
+ * Centralized JWT_SECRET configuration with environment-aware validation.
4
+ *
5
+ * - In production (NODE_ENV=production): throws a startup error if JWT_SECRET
6
+ * is missing or shorter than 32 characters.
7
+ * - In development: logs a warning and falls back to a local-only default.
8
+ *
9
+ * This module is designed to be imported once at startup so that any
10
+ * misconfiguration is caught immediately rather than at the first request.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.jwtSecret = void 0;
14
+ const logger_1 = require("../utils/logger.cjs");
15
+ const MINIMUM_SECRET_LENGTH = 32;
16
+ const DEV_FALLBACK_SECRET = 'development_secret_key_for_local_testing_only_do_not_use_in_production';
17
+ const isProduction = process.env.NODE_ENV === 'production';
18
+ function resolveJwtSecret() {
19
+ // Try JWT_SECRET first, then fall back to NEXTAUTH_SECRET for compatibility
20
+ const secret = process.env.JWT_SECRET || process.env.NEXTAUTH_SECRET;
21
+ if (!secret) {
22
+ if (isProduction) {
23
+ logger_1.logger.error('[SECURITY] FATAL: JWT_SECRET environment variable is not set. ' +
24
+ 'The server cannot start in production without a valid JWT_SECRET. ' +
25
+ 'Set JWT_SECRET to a cryptographically random string of at least ' +
26
+ `${MINIMUM_SECRET_LENGTH} characters.`);
27
+ throw new Error('JWT_SECRET is required in production. Set the JWT_SECRET environment variable.');
28
+ }
29
+ logger_1.logger.warn('[SECURITY] WARNING: JWT_SECRET is not set. Using an insecure development ' +
30
+ 'fallback. This is acceptable for local development only. ' +
31
+ 'Do NOT deploy to production without setting JWT_SECRET.');
32
+ return DEV_FALLBACK_SECRET;
33
+ }
34
+ if (secret.length < MINIMUM_SECRET_LENGTH) {
35
+ if (isProduction) {
36
+ logger_1.logger.error(`[SECURITY] FATAL: JWT_SECRET is too short (${secret.length} characters). ` +
37
+ `A minimum of ${MINIMUM_SECRET_LENGTH} characters is required in production.`);
38
+ throw new Error(`JWT_SECRET must be at least ${MINIMUM_SECRET_LENGTH} characters in production. ` +
39
+ `Current length: ${secret.length}.`);
40
+ }
41
+ logger_1.logger.warn(`[SECURITY] WARNING: JWT_SECRET is only ${secret.length} characters. ` +
42
+ `A minimum of ${MINIMUM_SECRET_LENGTH} characters is recommended. ` +
43
+ 'This warning will become a fatal error in production.');
44
+ }
45
+ return secret;
46
+ }
47
+ /**
48
+ * The validated JWT secret for this environment.
49
+ * Resolved once at import time; will throw in production if invalid.
50
+ */
51
+ exports.jwtSecret = resolveJwtSecret();
52
+ //# sourceMappingURL=jwtConfig.js.map
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Centralized JWT_SECRET configuration with environment-aware validation.
3
+ *
4
+ * - In production (NODE_ENV=production): throws a startup error if JWT_SECRET
5
+ * is missing or shorter than 32 characters.
6
+ * - In development: logs a warning and falls back to a local-only default.
7
+ *
8
+ * This module is designed to be imported once at startup so that any
9
+ * misconfiguration is caught immediately rather than at the first request.
10
+ */
11
+ /**
12
+ * The validated JWT secret for this environment.
13
+ * Resolved once at import time; will throw in production if invalid.
14
+ */
15
+ export declare const jwtSecret: string;
16
+ //# sourceMappingURL=jwtConfig.d.ts.map
@@ -0,0 +1,356 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UNMATCHED_ROUTE_LABEL = exports.tenancyScopingDecisionsTotal = exports.activeWebSocketConnections = exports.activeSubscriptions = exports.dbConnectionsActive = exports.dbQueryDuration = exports.graphqlErrorsTotal = exports.graphqlOperationDuration = exports.graphqlOperationsTotal = exports.httpRequestDuration = exports.httpRequestsTotal = exports.metricsRegistry = void 0;
4
+ exports.initMetrics = initMetrics;
5
+ exports.routeLabel = routeLabel;
6
+ exports.metricsMiddleware = metricsMiddleware;
7
+ exports.createMetricsPlugin = createMetricsPlugin;
8
+ exports.scrapeAuthorized = scrapeAuthorized;
9
+ exports.createMetricsRouter = createMetricsRouter;
10
+ const node_crypto_1 = require("node:crypto");
11
+ const express_1 = require("express");
12
+ const prom_client_1 = require("prom-client");
13
+ const logger_1 = require("../utils/logger.cjs");
14
+ const SERVICE_NAME = 'backend-legacy';
15
+ /**
16
+ * Dedicated Prometheus registry for backend-legacy metrics.
17
+ * Using a dedicated registry avoids conflicts with default Node.js metrics
18
+ * that might be registered by other libraries.
19
+ */
20
+ exports.metricsRegistry = new prom_client_1.Registry();
21
+ exports.metricsRegistry.setDefaultLabels({ service: SERVICE_NAME });
22
+ // ---------------------------------------------------------------------------
23
+ // HTTP / GraphQL request metrics
24
+ // ---------------------------------------------------------------------------
25
+ /** Counts total HTTP requests by method, route, and status code */
26
+ exports.httpRequestsTotal = new prom_client_1.Counter({
27
+ name: 'http_requests_total',
28
+ help: 'Total number of HTTP requests',
29
+ labelNames: ['method', 'route', 'status_code'],
30
+ registers: [exports.metricsRegistry],
31
+ });
32
+ /** Histogram of HTTP request durations in seconds */
33
+ exports.httpRequestDuration = new prom_client_1.Histogram({
34
+ name: 'http_request_duration_seconds',
35
+ help: 'Duration of HTTP requests in seconds',
36
+ labelNames: ['method', 'route', 'status_code'],
37
+ buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10],
38
+ registers: [exports.metricsRegistry],
39
+ });
40
+ /** Counts total GraphQL operations by type and name */
41
+ exports.graphqlOperationsTotal = new prom_client_1.Counter({
42
+ name: 'graphql_operations_total',
43
+ help: 'Total number of GraphQL operations',
44
+ labelNames: ['operation_type', 'operation_name', 'status'],
45
+ registers: [exports.metricsRegistry],
46
+ });
47
+ /** Histogram of GraphQL operation durations in seconds */
48
+ exports.graphqlOperationDuration = new prom_client_1.Histogram({
49
+ name: 'graphql_operation_duration_seconds',
50
+ help: 'Duration of GraphQL operations in seconds',
51
+ labelNames: ['operation_type', 'operation_name'],
52
+ buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30],
53
+ registers: [exports.metricsRegistry],
54
+ });
55
+ /** Counts GraphQL errors by operation and error code */
56
+ exports.graphqlErrorsTotal = new prom_client_1.Counter({
57
+ name: 'graphql_errors_total',
58
+ help: 'Total number of GraphQL errors',
59
+ labelNames: ['operation_type', 'operation_name', 'error_code'],
60
+ registers: [exports.metricsRegistry],
61
+ });
62
+ // ---------------------------------------------------------------------------
63
+ // Database metrics
64
+ // ---------------------------------------------------------------------------
65
+ /** Histogram of Prisma query durations in seconds */
66
+ exports.dbQueryDuration = new prom_client_1.Histogram({
67
+ name: 'db_query_duration_seconds',
68
+ help: 'Duration of database queries in seconds',
69
+ labelNames: ['operation', 'model'],
70
+ buckets: [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 5],
71
+ registers: [exports.metricsRegistry],
72
+ });
73
+ /** Gauge for active database connections */
74
+ exports.dbConnectionsActive = new prom_client_1.Gauge({
75
+ name: 'db_connections_active',
76
+ help: 'Number of active database connections (approximate)',
77
+ registers: [exports.metricsRegistry],
78
+ });
79
+ // ---------------------------------------------------------------------------
80
+ // WebSocket / Subscriptions metrics
81
+ // ---------------------------------------------------------------------------
82
+ /** Gauge for active GraphQL subscriptions */
83
+ exports.activeSubscriptions = new prom_client_1.Gauge({
84
+ name: 'graphql_active_subscriptions',
85
+ help: 'Number of active GraphQL subscriptions',
86
+ registers: [exports.metricsRegistry],
87
+ });
88
+ /** Gauge for active WebSocket connections */
89
+ exports.activeWebSocketConnections = new prom_client_1.Gauge({
90
+ name: 'websocket_active_connections',
91
+ help: 'Number of active WebSocket connections',
92
+ registers: [exports.metricsRegistry],
93
+ });
94
+ /**
95
+ * Counts row-level tenancy-scoping decisions for user-scoped principals.
96
+ * Labelled by `mode` (off/shadow/enforce), the governed `model`, the resolver
97
+ * `operation` field, and the `decision` (allow/restrict/deny). In `shadow` mode
98
+ * a non-`allow` decision is the signal proving whether flipping to `enforce`
99
+ * would catch any legitimate platform or engine query.
100
+ */
101
+ exports.tenancyScopingDecisionsTotal = new prom_client_1.Counter({
102
+ name: 'tenancy_scoping_decisions_total',
103
+ help: 'Row-level tenancy-scoping decisions by mode, model, operation, and decision',
104
+ labelNames: ['mode', 'model', 'operation', 'decision'],
105
+ registers: [exports.metricsRegistry],
106
+ });
107
+ // ---------------------------------------------------------------------------
108
+ // Application metrics
109
+ // ---------------------------------------------------------------------------
110
+ /** Gauge for application uptime in seconds */
111
+ const uptimeGauge = new prom_client_1.Gauge({
112
+ name: 'app_uptime_seconds',
113
+ help: 'Application uptime in seconds',
114
+ registers: [exports.metricsRegistry],
115
+ });
116
+ const startedAt = Date.now();
117
+ // ---------------------------------------------------------------------------
118
+ // Initialization
119
+ // ---------------------------------------------------------------------------
120
+ /**
121
+ * Determines if metrics collection is enabled.
122
+ * Enabled by default in production/staging; can be explicitly controlled
123
+ * via PROMETHEUS_METRICS_ENABLED env var.
124
+ */
125
+ function isMetricsEnabled() {
126
+ const explicitSetting = process.env.PROMETHEUS_METRICS_ENABLED;
127
+ if (explicitSetting !== undefined) {
128
+ return explicitSetting === 'true' || explicitSetting === '1';
129
+ }
130
+ const env = process.env.NODE_ENV || 'development';
131
+ return env === 'production' || env === 'staging';
132
+ }
133
+ /**
134
+ * Initializes Prometheus metrics collection.
135
+ *
136
+ * Registers default Node.js metrics (CPU, memory, event loop, GC) and
137
+ * application-specific metrics for HTTP, GraphQL, and database operations.
138
+ *
139
+ * Environment variables:
140
+ * - PROMETHEUS_METRICS_ENABLED: Explicit on/off ('true'/'false'). Defaults to on in production/staging.
141
+ *
142
+ * @returns true if metrics were initialized, false if disabled
143
+ */
144
+ function initMetrics() {
145
+ if (!isMetricsEnabled()) {
146
+ logger_1.logger.info('Prometheus metrics collection is disabled', {
147
+ reason: 'PROMETHEUS_METRICS_ENABLED not set or environment is development',
148
+ });
149
+ return false;
150
+ }
151
+ // Register default Node.js metrics (memory, CPU, event loop lag, etc.)
152
+ (0, prom_client_1.collectDefaultMetrics)({ register: exports.metricsRegistry });
153
+ // Update uptime gauge periodically
154
+ const UPTIME_UPDATE_INTERVAL_MS = 15000;
155
+ setInterval(() => {
156
+ uptimeGauge.set((Date.now() - startedAt) / 1000);
157
+ }, UPTIME_UPDATE_INTERVAL_MS);
158
+ logger_1.logger.info('Prometheus metrics initialized');
159
+ return true;
160
+ }
161
+ // ---------------------------------------------------------------------------
162
+ // Express middleware
163
+ // ---------------------------------------------------------------------------
164
+ /**
165
+ * The label used for a request that matched no route.
166
+ *
167
+ * One bucket, not the path that was asked for.
168
+ */
169
+ exports.UNMATCHED_ROUTE_LABEL = 'unmatched';
170
+ /**
171
+ * The bounded route label for a request.
172
+ *
173
+ * `req.route.path` is the Express route PATTERN, so its value set is bounded by
174
+ * this application's own routing table. `req.path` is not bounded by anything —
175
+ * it is whatever the client asked for. Falling back from the first to the second
176
+ * turns a metric label into an attack surface: every unmatched path a scanner
177
+ * probes becomes a new permanent time series, and the registry grows without
178
+ * limit at the caller's discretion. Production carried 679 distinct values, 130
179
+ * of them probes such as `/wp-config.php` and
180
+ * `/@fs/proc/self/cwd/.config/gcloud/application_default_credentials.json`.
181
+ *
182
+ * A request that matched no route is therefore recorded as a single bucket. The
183
+ * request is still counted, with its method and status; what is discarded is the
184
+ * attacker's choice of string.
185
+ *
186
+ * @param req - The request being recorded.
187
+ * @returns The matched route pattern, or {@link UNMATCHED_ROUTE_LABEL}.
188
+ */
189
+ function routeLabel(req) {
190
+ var _a;
191
+ const matched = (_a = req.route) === null || _a === void 0 ? void 0 : _a.path;
192
+ return typeof matched === 'string' && matched.length > 0
193
+ ? matched
194
+ : exports.UNMATCHED_ROUTE_LABEL;
195
+ }
196
+ /**
197
+ * Express middleware that records HTTP request metrics.
198
+ * Tracks request count and duration for each method/route/status combination.
199
+ *
200
+ * Should be mounted early in the middleware chain to capture all requests.
201
+ */
202
+ function metricsMiddleware(req, res, next) {
203
+ if (!isMetricsEnabled()) {
204
+ next();
205
+ return;
206
+ }
207
+ const start = process.hrtime.bigint();
208
+ res.on('finish', () => {
209
+ const durationNs = Number(process.hrtime.bigint() - start);
210
+ const durationSeconds = durationNs / 1e9;
211
+ const route = routeLabel(req);
212
+ const method = req.method;
213
+ const statusCode = String(res.statusCode);
214
+ exports.httpRequestsTotal.inc({ method, route, status_code: statusCode });
215
+ exports.httpRequestDuration.observe({ method, route, status_code: statusCode }, durationSeconds);
216
+ });
217
+ next();
218
+ }
219
+ // ---------------------------------------------------------------------------
220
+ // Apollo Server plugin
221
+ // ---------------------------------------------------------------------------
222
+ /**
223
+ * Creates an Apollo Server plugin that records GraphQL operation metrics.
224
+ *
225
+ * Tracks:
226
+ * - Operation count by type (query/mutation/subscription) and name
227
+ * - Operation duration
228
+ * - Error count by operation and error code
229
+ *
230
+ * @returns Apollo Server plugin configuration
231
+ */
232
+ function createMetricsPlugin() {
233
+ return {
234
+ async requestDidStart() {
235
+ const start = process.hrtime.bigint();
236
+ return {
237
+ async willSendResponse(requestContext) {
238
+ var _a, _b, _c, _d;
239
+ const durationNs = Number(process.hrtime.bigint() - start);
240
+ const durationSeconds = durationNs / 1e9;
241
+ const operationName = requestContext.operationName || 'anonymous';
242
+ const operationType = ((_a = requestContext.operation) === null || _a === void 0 ? void 0 : _a.operation) || 'unknown';
243
+ exports.graphqlOperationDuration.observe({ operation_type: operationType, operation_name: operationName }, durationSeconds);
244
+ const responseBody = requestContext.response.body;
245
+ const hasErrors = responseBody.kind === 'single' &&
246
+ ((_b = responseBody.singleResult) === null || _b === void 0 ? void 0 : _b.errors) &&
247
+ responseBody.singleResult.errors.length > 0;
248
+ if (hasErrors &&
249
+ responseBody.kind === 'single' &&
250
+ ((_c = responseBody.singleResult) === null || _c === void 0 ? void 0 : _c.errors)) {
251
+ for (const error of responseBody.singleResult.errors) {
252
+ const errorCode = ((_d = error.extensions) === null || _d === void 0 ? void 0 : _d.code) || 'INTERNAL_SERVER_ERROR';
253
+ exports.graphqlErrorsTotal.inc({
254
+ operation_type: operationType,
255
+ operation_name: operationName,
256
+ error_code: String(errorCode),
257
+ });
258
+ }
259
+ exports.graphqlOperationsTotal.inc({
260
+ operation_type: operationType,
261
+ operation_name: operationName,
262
+ status: 'error',
263
+ });
264
+ }
265
+ else {
266
+ exports.graphqlOperationsTotal.inc({
267
+ operation_type: operationType,
268
+ operation_name: operationName,
269
+ status: 'success',
270
+ });
271
+ }
272
+ },
273
+ };
274
+ },
275
+ };
276
+ }
277
+ // ---------------------------------------------------------------------------
278
+ // Metrics endpoint
279
+ // ---------------------------------------------------------------------------
280
+ /**
281
+ * Creates an Express router that exposes Prometheus metrics at GET /metrics.
282
+ *
283
+ * The endpoint returns metrics in Prometheus text exposition format.
284
+ * This should be scraped by a Prometheus server at regular intervals.
285
+ *
286
+ * Note: This endpoint should be protected in production (e.g., by firewall rules
287
+ * or by requiring a bearer token). It is excluded from rate limiting by default.
288
+ */
289
+ /**
290
+ * Whether the scrape endpoint requires a bearer token, and which one.
291
+ *
292
+ * Read per request rather than captured at boot so the switch can be turned on
293
+ * without a restart.
294
+ */
295
+ function metricsScrapeToken() {
296
+ const token = process.env.METRICS_SCRAPE_TOKEN;
297
+ return typeof token === 'string' && token.length > 0 ? token : null;
298
+ }
299
+ /**
300
+ * Whether an `Authorization` header may read the scrape.
301
+ *
302
+ * Returns true when no token is configured, which is the state every existing
303
+ * deployment is in: the gate is inert until an operator sets one, so shipping it
304
+ * breaks no scraper and closing the endpoint stays an operator decision.
305
+ *
306
+ * The comparison is constant-time so a wrong token cannot be discovered a byte
307
+ * at a time from response timing. A length mismatch short-circuits, which is
308
+ * correct — the length is not the secret, the bytes are.
309
+ *
310
+ * @param authorization - The request's `Authorization` header, if any.
311
+ * @param expected - The configured token, or `null` when none is configured.
312
+ */
313
+ function scrapeAuthorized(authorization, expected) {
314
+ if (expected === null)
315
+ return true;
316
+ const header = authorization !== null && authorization !== void 0 ? authorization : '';
317
+ if (!header.startsWith('Bearer '))
318
+ return false;
319
+ const presented = Buffer.from(header.slice(7), 'utf8');
320
+ const wanted = Buffer.from(expected, 'utf8');
321
+ return presented.length === wanted.length && (0, node_crypto_1.timingSafeEqual)(presented, wanted);
322
+ }
323
+ function createMetricsRouter() {
324
+ const router = (0, express_1.Router)();
325
+ router.get('/metrics', async (req, res) => {
326
+ // Optional bearer gate. Inert until METRICS_SCRAPE_TOKEN is set, so
327
+ // enabling it is an operator decision and no existing scraper breaks by
328
+ // deploying this. When set, the endpoint stops being world-readable.
329
+ //
330
+ // This is defence in depth, not the fix. The endpoint is mounted outside
331
+ // Apollo and outside auth on purpose, and restricting it at the ingress
332
+ // remains the right control; it simply is not in place, and until it is
333
+ // this scrape exposes the service's whole operational posture — request
334
+ // volumes, error rates, and the authorization counters that reveal the
335
+ // checker is running in shadow — to anyone who asks.
336
+ if (!scrapeAuthorized(req.get('authorization'), metricsScrapeToken())) {
337
+ res.status(401).set('WWW-Authenticate', 'Bearer').send('Unauthorized');
338
+ return;
339
+ }
340
+ try {
341
+ const metrics = await exports.metricsRegistry.metrics();
342
+ res.set('Content-Type', exports.metricsRegistry.contentType);
343
+ res.status(200).send(metrics);
344
+ }
345
+ catch (metricsError) {
346
+ logger_1.logger.error('Failed to generate metrics', {
347
+ error: metricsError instanceof Error
348
+ ? metricsError.message
349
+ : String(metricsError),
350
+ });
351
+ res.status(500).send('Failed to generate metrics');
352
+ }
353
+ });
354
+ return router;
355
+ }
356
+ //# sourceMappingURL=metrics.js.map
@@ -0,0 +1,128 @@
1
+ import { Request, Response, Router } from 'express';
2
+ import { Registry, Counter, Histogram, Gauge } from 'prom-client';
3
+ /**
4
+ * Dedicated Prometheus registry for backend-legacy metrics.
5
+ * Using a dedicated registry avoids conflicts with default Node.js metrics
6
+ * that might be registered by other libraries.
7
+ */
8
+ export declare const metricsRegistry: Registry<"text/plain; version=0.0.4; charset=utf-8">;
9
+ /** Counts total HTTP requests by method, route, and status code */
10
+ export declare const httpRequestsTotal: Counter<"route" | "method" | "status_code">;
11
+ /** Histogram of HTTP request durations in seconds */
12
+ export declare const httpRequestDuration: Histogram<"route" | "method" | "status_code">;
13
+ /** Counts total GraphQL operations by type and name */
14
+ export declare const graphqlOperationsTotal: Counter<"status" | "operation_type" | "operation_name">;
15
+ /** Histogram of GraphQL operation durations in seconds */
16
+ export declare const graphqlOperationDuration: Histogram<"operation_type" | "operation_name">;
17
+ /** Counts GraphQL errors by operation and error code */
18
+ export declare const graphqlErrorsTotal: Counter<"operation_type" | "operation_name" | "error_code">;
19
+ /** Histogram of Prisma query durations in seconds */
20
+ export declare const dbQueryDuration: Histogram<"operation" | "model">;
21
+ /** Gauge for active database connections */
22
+ export declare const dbConnectionsActive: Gauge<string>;
23
+ /** Gauge for active GraphQL subscriptions */
24
+ export declare const activeSubscriptions: Gauge<string>;
25
+ /** Gauge for active WebSocket connections */
26
+ export declare const activeWebSocketConnections: Gauge<string>;
27
+ /**
28
+ * Counts row-level tenancy-scoping decisions for user-scoped principals.
29
+ * Labelled by `mode` (off/shadow/enforce), the governed `model`, the resolver
30
+ * `operation` field, and the `decision` (allow/restrict/deny). In `shadow` mode
31
+ * a non-`allow` decision is the signal proving whether flipping to `enforce`
32
+ * would catch any legitimate platform or engine query.
33
+ */
34
+ export declare const tenancyScopingDecisionsTotal: Counter<"mode" | "operation" | "model" | "decision">;
35
+ /**
36
+ * Initializes Prometheus metrics collection.
37
+ *
38
+ * Registers default Node.js metrics (CPU, memory, event loop, GC) and
39
+ * application-specific metrics for HTTP, GraphQL, and database operations.
40
+ *
41
+ * Environment variables:
42
+ * - PROMETHEUS_METRICS_ENABLED: Explicit on/off ('true'/'false'). Defaults to on in production/staging.
43
+ *
44
+ * @returns true if metrics were initialized, false if disabled
45
+ */
46
+ export declare function initMetrics(): boolean;
47
+ /**
48
+ * The label used for a request that matched no route.
49
+ *
50
+ * One bucket, not the path that was asked for.
51
+ */
52
+ export declare const UNMATCHED_ROUTE_LABEL = "unmatched";
53
+ /**
54
+ * The bounded route label for a request.
55
+ *
56
+ * `req.route.path` is the Express route PATTERN, so its value set is bounded by
57
+ * this application's own routing table. `req.path` is not bounded by anything —
58
+ * it is whatever the client asked for. Falling back from the first to the second
59
+ * turns a metric label into an attack surface: every unmatched path a scanner
60
+ * probes becomes a new permanent time series, and the registry grows without
61
+ * limit at the caller's discretion. Production carried 679 distinct values, 130
62
+ * of them probes such as `/wp-config.php` and
63
+ * `/@fs/proc/self/cwd/.config/gcloud/application_default_credentials.json`.
64
+ *
65
+ * A request that matched no route is therefore recorded as a single bucket. The
66
+ * request is still counted, with its method and status; what is discarded is the
67
+ * attacker's choice of string.
68
+ *
69
+ * @param req - The request being recorded.
70
+ * @returns The matched route pattern, or {@link UNMATCHED_ROUTE_LABEL}.
71
+ */
72
+ export declare function routeLabel(req: Pick<Request, 'route'>): string;
73
+ /**
74
+ * Express middleware that records HTTP request metrics.
75
+ * Tracks request count and duration for each method/route/status combination.
76
+ *
77
+ * Should be mounted early in the middleware chain to capture all requests.
78
+ */
79
+ export declare function metricsMiddleware(req: Request, res: Response, next: () => void): void;
80
+ /**
81
+ * Creates an Apollo Server plugin that records GraphQL operation metrics.
82
+ *
83
+ * Tracks:
84
+ * - Operation count by type (query/mutation/subscription) and name
85
+ * - Operation duration
86
+ * - Error count by operation and error code
87
+ *
88
+ * @returns Apollo Server plugin configuration
89
+ */
90
+ export declare function createMetricsPlugin(): {
91
+ requestDidStart: () => Promise<{
92
+ willSendResponse: (requestContext: {
93
+ operationName?: string | null;
94
+ operation?: {
95
+ operation: string;
96
+ } | null;
97
+ response: {
98
+ body: {
99
+ kind: string;
100
+ singleResult?: {
101
+ errors?: ReadonlyArray<{
102
+ extensions?: {
103
+ code?: string;
104
+ };
105
+ }>;
106
+ };
107
+ };
108
+ };
109
+ }) => Promise<void>;
110
+ }>;
111
+ };
112
+ /**
113
+ * Whether an `Authorization` header may read the scrape.
114
+ *
115
+ * Returns true when no token is configured, which is the state every existing
116
+ * deployment is in: the gate is inert until an operator sets one, so shipping it
117
+ * breaks no scraper and closing the endpoint stays an operator decision.
118
+ *
119
+ * The comparison is constant-time so a wrong token cannot be discovered a byte
120
+ * at a time from response timing. A length mismatch short-circuits, which is
121
+ * correct — the length is not the secret, the bytes are.
122
+ *
123
+ * @param authorization - The request's `Authorization` header, if any.
124
+ * @param expected - The configured token, or `null` when none is configured.
125
+ */
126
+ export declare function scrapeAuthorized(authorization: string | undefined, expected: string | null): boolean;
127
+ export declare function createMetricsRouter(): Router;
128
+ //# sourceMappingURL=metrics.d.ts.map