@adaptic/backend 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
@@ -1,60 +0,0 @@
1
- import { vi } from 'vitest';
2
- import type { Counter } from 'prom-client';
3
- import type { Request, Response } from 'express';
4
- import type { RateLimitConfig } from '../rate-limiter';
5
- /**
6
- * Shared fixtures for the rate-limiter test files (audit
7
- * B01-backend-legacy-08). Pure helpers only — each test file remains
8
- * responsible for setting `process.env.JWT_SECRET` via `vi.hoisted` BEFORE its
9
- * first import pulls in `config/jwtConfig` (which reads the env at load time).
10
- */
11
- /** Window used by every test config. */
12
- export declare const WINDOW_MS = 60000;
13
- /**
14
- * Builds a small test limiter config.
15
- *
16
- * @param overrides - Field overrides applied over the defaults.
17
- * @returns A complete {@link RateLimitConfig}.
18
- */
19
- export declare function makeConfig(overrides?: Partial<RateLimitConfig>): RateLimitConfig;
20
- /** A mock Express response with observable spies. */
21
- export interface MockResponse {
22
- res: Response;
23
- setHeader: ReturnType<typeof vi.fn>;
24
- status: ReturnType<typeof vi.fn>;
25
- json: ReturnType<typeof vi.fn>;
26
- }
27
- /**
28
- * Creates a mock response whose header/status/json calls are observable —
29
- * the shadow contract is proven by these spies staying untouched.
30
- *
31
- * @returns The {@link MockResponse}.
32
- */
33
- export declare function makeRes(): MockResponse;
34
- /**
35
- * Creates a mock request. Defaults to an anonymous POST from a fixed IP.
36
- *
37
- * @param overrides - Request field overrides (headers, ip, method, …).
38
- * @returns A Request usable by the limiter middleware.
39
- */
40
- export declare function makeReq(overrides?: Record<string, unknown>): Request;
41
- /**
42
- * Reads the current value of a limiter counter for a label pair.
43
- *
44
- * @param counter - The prom-client counter to read.
45
- * @param labels - The limiter/tier label pair identifying the series.
46
- * @returns The current value (0 when the series does not exist yet).
47
- */
48
- export declare function counterValue(counter: Counter<'limiter' | 'tier'>, labels: {
49
- limiter: string;
50
- tier: string;
51
- }): Promise<number>;
52
- /**
53
- * Signs a real HS256 user JWT with the ambient `JWT_SECRET` (the same secret
54
- * `config/jwtConfig` resolved at load), so the tier resolver verifies it.
55
- *
56
- * @param sub - Subject claim for the token.
57
- * @returns A signed JWT string.
58
- */
59
- export declare function signUserToken(sub: string): string;
60
- //# sourceMappingURL=rate-limit-test-utils.d.ts.map
@@ -1,85 +0,0 @@
1
- import { vi } from 'vitest';
2
- import jwt from 'jsonwebtoken';
3
- /**
4
- * Shared fixtures for the rate-limiter test files (audit
5
- * B01-backend-legacy-08). Pure helpers only — each test file remains
6
- * responsible for setting `process.env.JWT_SECRET` via `vi.hoisted` BEFORE its
7
- * first import pulls in `config/jwtConfig` (which reads the env at load time).
8
- */
9
- /** Window used by every test config. */
10
- export const WINDOW_MS = 60_000;
11
- /**
12
- * Builds a small test limiter config.
13
- *
14
- * @param overrides - Field overrides applied over the defaults.
15
- * @returns A complete {@link RateLimitConfig}.
16
- */
17
- export function makeConfig(overrides = {}) {
18
- return {
19
- name: 'graphql',
20
- windowMs: WINDOW_MS,
21
- maxAuthenticated: 100,
22
- maxUnauthenticated: 2,
23
- standardHeaders: true,
24
- message: { errors: [{ message: 'Too many requests' }] },
25
- ...overrides,
26
- };
27
- }
28
- /**
29
- * Creates a mock response whose header/status/json calls are observable —
30
- * the shadow contract is proven by these spies staying untouched.
31
- *
32
- * @returns The {@link MockResponse}.
33
- */
34
- export function makeRes() {
35
- const setHeader = vi.fn();
36
- const json = vi.fn();
37
- const status = vi.fn(() => ({ json }));
38
- const res = { setHeader, status, json };
39
- return { res, setHeader, status, json };
40
- }
41
- /**
42
- * Creates a mock request. Defaults to an anonymous POST from a fixed IP.
43
- *
44
- * @param overrides - Request field overrides (headers, ip, method, …).
45
- * @returns A Request usable by the limiter middleware.
46
- */
47
- export function makeReq(overrides = {}) {
48
- return {
49
- method: 'POST',
50
- headers: {},
51
- ip: '203.0.113.10',
52
- socket: { remoteAddress: '203.0.113.10' },
53
- ...overrides,
54
- };
55
- }
56
- /**
57
- * Reads the current value of a limiter counter for a label pair.
58
- *
59
- * @param counter - The prom-client counter to read.
60
- * @param labels - The limiter/tier label pair identifying the series.
61
- * @returns The current value (0 when the series does not exist yet).
62
- */
63
- export async function counterValue(counter, labels) {
64
- const metric = await counter.get();
65
- const sample = metric.values.find((v) => v.labels.limiter === labels.limiter && v.labels.tier === labels.tier);
66
- return sample?.value ?? 0;
67
- }
68
- /**
69
- * Signs a real HS256 user JWT with the ambient `JWT_SECRET` (the same secret
70
- * `config/jwtConfig` resolved at load), so the tier resolver verifies it.
71
- *
72
- * @param sub - Subject claim for the token.
73
- * @returns A signed JWT string.
74
- */
75
- export function signUserToken(sub) {
76
- const secret = process.env.JWT_SECRET;
77
- if (!secret) {
78
- throw new Error('JWT_SECRET must be set by the test file before signing');
79
- }
80
- return jwt.sign({ sub, roles: ['user'] }, secret, {
81
- algorithm: 'HS256',
82
- expiresIn: '1h',
83
- });
84
- }
85
- //# sourceMappingURL=rate-limit-test-utils.js.map
@@ -1,10 +0,0 @@
1
- /**
2
- * Run `harnessPath` (relative to the repository root) under ts-node and parse
3
- * its results.
4
- *
5
- * @param harnessPath - Harness file, relative to the repository root.
6
- * @param timeoutMs - Wall-clock budget; the child is killed when it runs out.
7
- * @returns The parsed results object.
8
- */
9
- export declare function runTsNodeHarness<T>(harnessPath: string, timeoutMs: number): Promise<T>;
10
- //# sourceMappingURL=ts-node-harness.d.ts.map
@@ -1,71 +0,0 @@
1
- /**
2
- * Run an out-of-process ts-node harness and return the JSON it prints between
3
- * `<<<RESULTS>>>` and `<<<END>>>`.
4
- *
5
- * The guard harnesses build schemas from the generated resolvers, which need
6
- * `emitDecoratorMetadata`, so they cannot run inside vitest's esbuild
7
- * transform. A run costs tens of seconds of CPU, and far longer on a loaded
8
- * machine, so the child is awaited, never spawned synchronously: a synchronous
9
- * spawn blocks the vitest worker's event loop for the whole run, the worker
10
- * cannot answer the runner's RPC in that time, and once the block outlasts
11
- * vitest's 60 s RPC timeout the run records an unhandled
12
- * `Timeout calling "onTaskUpdate"` error and exits 1 even though every
13
- * assertion passed.
14
- *
15
- * The child is killed at `timeoutMs` and the failure says so. Set the calling
16
- * hook's timeout above it, so a hung harness fails its suite with this reason
17
- * rather than with a bare hook timeout that leaves the child running.
18
- */
19
- import { execFile } from 'node:child_process';
20
- import path from 'node:path';
21
- import { promisify } from 'node:util';
22
- const execFileAsync = promisify(execFile);
23
- /** Repository root, resolved from `src/middleware/__tests__`. */
24
- const REPO_ROOT = path.resolve(__dirname, '../../..');
25
- /** Largest harness stdout accepted, in bytes. */
26
- const MAX_OUTPUT_BYTES = 64 * 1024 * 1024;
27
- /** Characters of harness output quoted in a failure message. */
28
- const FAILURE_TAIL_CHARS = 2000;
29
- const RESULTS = /<<<RESULTS>>>(.*)<<<END>>>/s;
30
- function describeFailure(failure, timeoutMs) {
31
- if (failure.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') {
32
- return `printed more than ${MAX_OUTPUT_BYTES} bytes`;
33
- }
34
- if (failure.killed)
35
- return `was killed after ${timeoutMs} ms`;
36
- if (failure.signal)
37
- return `was terminated by ${failure.signal}`;
38
- return `exited with code ${String(failure.code)}`;
39
- }
40
- /**
41
- * Run `harnessPath` (relative to the repository root) under ts-node and parse
42
- * its results.
43
- *
44
- * @param harnessPath - Harness file, relative to the repository root.
45
- * @param timeoutMs - Wall-clock budget; the child is killed when it runs out.
46
- * @returns The parsed results object.
47
- */
48
- export async function runTsNodeHarness(harnessPath, timeoutMs) {
49
- let stdout;
50
- try {
51
- ({ stdout } = await execFileAsync(path.join(REPO_ROOT, 'node_modules/.bin/ts-node'), ['--transpile-only', harnessPath], {
52
- cwd: REPO_ROOT,
53
- encoding: 'utf8',
54
- env: { ...process.env, LOG_LEVEL: 'error' },
55
- maxBuffer: MAX_OUTPUT_BYTES,
56
- timeout: timeoutMs,
57
- killSignal: 'SIGKILL',
58
- }));
59
- }
60
- catch (error) {
61
- const failure = error;
62
- throw new Error(`harness ${harnessPath} ${describeFailure(failure, timeoutMs)}:\n` +
63
- (failure.stderr ?? '').slice(-FAILURE_TAIL_CHARS));
64
- }
65
- const match = RESULTS.exec(stdout);
66
- if (!match) {
67
- throw new Error(`harness ${harnessPath} printed no results:\n${stdout.slice(-FAILURE_TAIL_CHARS)}`);
68
- }
69
- return JSON.parse(match[1]);
70
- }
71
- //# sourceMappingURL=ts-node-harness.js.map
package/health.cjs DELETED
@@ -1,274 +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
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.HEALTH_PROBE_TIMEOUT_MS = exports.DB_SUCCESS_FRESHNESS_MS = void 0;
37
- exports.warnIfStatementTimeoutDefeatsFreshness = warnIfStatementTimeoutDefeatsFreshness;
38
- exports.checkDatabaseReadiness = checkDatabaseReadiness;
39
- exports.createHealthRouter = createHealthRouter;
40
- const express_1 = require("express");
41
- const prismaClient_1 = __importStar(require("./prismaClient.cjs"));
42
- const logger_1 = require("./utils/logger.cjs");
43
- const SERVICE_NAME = 'backend-legacy';
44
- /**
45
- * Reads the package version from package.json at startup.
46
- * Falls back to 'unknown' if the version cannot be determined.
47
- */
48
- function getPackageVersion() {
49
- try {
50
- const pkg = require('../package.json');
51
- return pkg.version || 'unknown';
52
- }
53
- catch (_a) {
54
- return 'unknown';
55
- }
56
- }
57
- const PACKAGE_VERSION = getPackageVersion();
58
- /** Tracks the process start time for uptime calculation */
59
- const startedAt = Date.now();
60
- /**
61
- * How recently a query must have completed for `/health` to accept it as
62
- * proof the database is answering, without issuing a query of its own.
63
- *
64
- * Derived from the heartbeat rather than set by hand: it tolerates every
65
- * heartbeat but the last before reconnection being missed, plus half an
66
- * interval of slack — `(MAX_HEARTBEAT_FAILURES - 0.5) * HEARTBEAT_INTERVAL_MS`,
67
- * 75s at the current 3 x 30s. That keeps it longer than one heartbeat interval,
68
- * so an idle process that the heartbeat keeps refreshing never goes stale, and
69
- * shorter than the reconnect point, so a database that has stopped answering
70
- * reads as disconnected before the heartbeat gives up on the client.
71
- *
72
- * A saturated pool still completes queries, each bounded by the statement
73
- * timeout, so saturation alone does not let it go stale — provided that
74
- * timeout is shorter than this window (see
75
- * {@link warnIfStatementTimeoutDefeatsFreshness}).
76
- */
77
- exports.DB_SUCCESS_FRESHNESS_MS = (prismaClient_1.MAX_HEARTBEAT_FAILURES - 0.5) * prismaClient_1.HEARTBEAT_INTERVAL_MS;
78
- /**
79
- * Warn when the configured statement timeout is not shorter than the
80
- * freshness window.
81
- *
82
- * The case for trusting a recent success under saturation is that every query
83
- * on a busy pool finishes or fails within the statement timeout, so completed
84
- * queries keep arriving inside {@link DB_SUCCESS_FRESHNESS_MS}. A timeout at or
85
- * above the window breaks that: a pool full of long-running statements can go
86
- * a whole window without a completion and `/health` would fall back to a probe
87
- * that cannot get a connection. A value that is not a positive integer (unset
88
- * timeouts parse from the default; `0` disables the timeout in Postgres) is
89
- * treated the same way, since it bounds nothing.
90
- *
91
- * @param statementTimeoutMs - The resolved statement timeout (injectable for tests).
92
- * @returns True if a warning was logged.
93
- */
94
- function warnIfStatementTimeoutDefeatsFreshness(statementTimeoutMs = (0, prismaClient_1.resolveStatementTimeoutMs)()) {
95
- if (Number.isFinite(statementTimeoutMs) &&
96
- statementTimeoutMs > 0 &&
97
- statementTimeoutMs < exports.DB_SUCCESS_FRESHNESS_MS) {
98
- return false;
99
- }
100
- logger_1.logger.warn('DATABASE_STATEMENT_TIMEOUT_MS is not shorter than the /health freshness window — a saturated pool can read as disconnected', {
101
- statementTimeoutMs,
102
- freshnessWindowMs: exports.DB_SUCCESS_FRESHNESS_MS,
103
- });
104
- return true;
105
- }
106
- /**
107
- * Budget for the fallback probe when no recent success exists. Well under the
108
- * 10s pool wait so a saturated pool yields an answer inside the platform's
109
- * probe timeout rather than hanging the request.
110
- */
111
- exports.HEALTH_PROBE_TIMEOUT_MS = 2000;
112
- /** The one probe query this module may have outstanding on the pool. */
113
- let outstandingProbe;
114
- /**
115
- * Probe the live client with `SELECT 1`, giving up after `timeoutMs`.
116
- *
117
- * Reads `global.prisma` rather than the module-level import, because the
118
- * heartbeat's reconnect path replaces `global.prisma` and the import stays
119
- * pinned to the original (by then disconnected) client.
120
- *
121
- * At most one probe query is ever outstanding: a caller that arrives while a
122
- * previous probe is still queued on the pool waits on that same query instead
123
- * of adding another waiter, so frequent health checks cannot themselves deepen
124
- * a saturated pool's queue.
125
- *
126
- * @param timeoutMs - How long to wait for the probe before calling it failed.
127
- * @returns True if the probe completed within the budget.
128
- */
129
- async function probeLiveClient(timeoutMs) {
130
- var _a;
131
- if (!outstandingProbe) {
132
- const client = (_a = global.prisma) !== null && _a !== void 0 ? _a : prismaClient_1.default;
133
- outstandingProbe = Promise.resolve(client.$queryRaw `SELECT 1`).finally(() => {
134
- outstandingProbe = undefined;
135
- });
136
- }
137
- const probe = outstandingProbe;
138
- let timer;
139
- const timedOut = new Promise((resolve) => {
140
- timer = setTimeout(() => resolve(false), timeoutMs);
141
- });
142
- try {
143
- return await Promise.race([
144
- probe.then(() => true, (dbError) => {
145
- logger_1.logger.warn('Health check: database probe failed', {
146
- error: dbError instanceof Error ? dbError.message : String(dbError),
147
- });
148
- return false;
149
- }),
150
- timedOut,
151
- ]);
152
- }
153
- finally {
154
- clearTimeout(timer);
155
- }
156
- }
157
- /**
158
- * Decide whether the database is answering this process, without depending
159
- * on a free pool connection when there is already evidence that it is.
160
- *
161
- * A query that completed within {@link DB_SUCCESS_FRESHNESS_MS} is taken as
162
- * that evidence and no query is issued. Only when there is none (startup, or a
163
- * database that has stopped answering) does it fall back to a bounded probe.
164
- *
165
- * @param now - Current epoch ms (injectable for tests).
166
- * @returns The database status, how it was decided, and the success age.
167
- */
168
- async function checkDatabaseReadiness(now = Date.now()) {
169
- const lastSuccess = (0, prismaClient_1.getLastQuerySucceededAt)();
170
- const ageMs = lastSuccess === undefined ? undefined : now - lastSuccess;
171
- if (ageMs !== undefined && ageMs <= exports.DB_SUCCESS_FRESHNESS_MS) {
172
- return {
173
- database: 'connected',
174
- databaseCheck: 'recent-query',
175
- lastQuerySucceededSecondsAgo: Math.max(0, Math.floor(ageMs / 1000)),
176
- };
177
- }
178
- const answered = await probeLiveClient(exports.HEALTH_PROBE_TIMEOUT_MS);
179
- // A successful probe goes through the same client extension and refreshes
180
- // the stamp; report the age as it stands after the probe.
181
- const after = (0, prismaClient_1.getLastQuerySucceededAt)();
182
- return {
183
- database: answered ? 'connected' : 'disconnected',
184
- databaseCheck: 'probe',
185
- lastQuerySucceededSecondsAgo: after === undefined
186
- ? null
187
- : Math.max(0, Math.floor((Date.now() - after) / 1000)),
188
- };
189
- }
190
- /**
191
- * Checks database connectivity by issuing a lightweight query.
192
- * Returns 'connected' or 'disconnected'. Never throws.
193
- */
194
- async function checkDatabase() {
195
- try {
196
- await prismaClient_1.default.$queryRaw `SELECT 1`;
197
- return 'connected';
198
- }
199
- catch (dbError) {
200
- logger_1.logger.warn('Health check: database connectivity test failed', {
201
- error: dbError instanceof Error ? dbError.message : String(dbError),
202
- });
203
- return 'disconnected';
204
- }
205
- }
206
- /**
207
- * Creates an Express router with health-probe endpoints.
208
- *
209
- * - `GET /livez` — Process-only liveness check. Always returns HTTP 200 with
210
- * `{ status, service, version, uptime }`. Safe for Cloud Run / Kubernetes
211
- * liveness probes since it never touches the database.
212
- * - `GET /readyz` — Readiness check. Returns HTTP 200 only when the database
213
- * is reachable (`SELECT 1`), HTTP 503 otherwise. Suitable for Cloud Run
214
- * startup probes and load-balancer readiness.
215
- * - `GET /health` — Full health snapshot including memory usage and database
216
- * status. Returns 503 only when the database has stopped answering this
217
- * process: a query that completed within the freshness window counts as
218
- * proof without taking a pool connection, so a saturated-but-working pool
219
- * reads as healthy. With no recent success it falls back to a bounded
220
- * probe (see {@link checkDatabaseReadiness}). Kept for backward
221
- * compatibility with existing Railway/uptime checks.
222
- *
223
- * All endpoints should be mounted before auth middleware so they remain
224
- * accessible without authentication.
225
- */
226
- function createHealthRouter() {
227
- warnIfStatementTimeoutDefeatsFreshness();
228
- const router = (0, express_1.Router)();
229
- router.get('/livez', (_req, res) => {
230
- res.status(200).json({
231
- status: 'ok',
232
- service: SERVICE_NAME,
233
- version: PACKAGE_VERSION,
234
- timestamp: new Date().toISOString(),
235
- uptime: Math.floor((Date.now() - startedAt) / 1000),
236
- });
237
- });
238
- router.get('/readyz', async (_req, res) => {
239
- const databaseStatus = await checkDatabase();
240
- const isReady = databaseStatus === 'connected';
241
- res.status(isReady ? 200 : 503).json({
242
- status: isReady ? 'ready' : 'not-ready',
243
- service: SERVICE_NAME,
244
- version: PACKAGE_VERSION,
245
- database: databaseStatus,
246
- timestamp: new Date().toISOString(),
247
- });
248
- });
249
- router.get('/health', async (_req, res) => {
250
- const readiness = await checkDatabaseReadiness();
251
- const databaseStatus = readiness.database;
252
- const isHealthy = databaseStatus === 'connected';
253
- const statusCode = isHealthy ? 200 : 503;
254
- const memoryUsage = process.memoryUsage();
255
- const body = {
256
- status: isHealthy ? 'ok' : 'degraded',
257
- service: SERVICE_NAME,
258
- version: PACKAGE_VERSION,
259
- timestamp: new Date().toISOString(),
260
- uptime: Math.floor((Date.now() - startedAt) / 1000),
261
- memory: {
262
- rss: Math.round(memoryUsage.rss / 1024 / 1024),
263
- heapUsed: Math.round(memoryUsage.heapUsed / 1024 / 1024),
264
- heapTotal: Math.round(memoryUsage.heapTotal / 1024 / 1024),
265
- },
266
- database: databaseStatus,
267
- databaseCheck: readiness.databaseCheck,
268
- lastQuerySucceededSecondsAgo: readiness.lastQuerySucceededSecondsAgo,
269
- };
270
- res.status(statusCode).json(body);
271
- });
272
- return router;
273
- }
274
- //# sourceMappingURL=health.js.map