@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
@@ -0,0 +1,736 @@
1
+ "use strict";
2
+ /**
3
+ * Row-level tenancy scoping — pure domain logic (SP2-G7 / SOC2 hardening).
4
+ *
5
+ * The auto-generated typegraphql-prisma CRUD resolvers expose the org → fund →
6
+ * brokerageAccount tenancy graph (and the notification pipeline) to ANY
7
+ * authenticated principal with a caller-supplied `where` clause. App-side
8
+ * authorization (platform `fund-authorization.ts`) does not protect direct
9
+ * GraphQL calls, so a user-scoped JWT can read/mutate another org's rows.
10
+ *
11
+ * This module contains the transport-agnostic decision logic used by the
12
+ * TypeGraphQL global middleware in `src/middleware/tenancy-scoping.ts`:
13
+ *
14
+ * - {@link resolveEntitlement} — turns a `userId` into the set of org and
15
+ * fund ids the caller is entitled to, by reading their OrgMembership and
16
+ * FundAssignment rows.
17
+ * - {@link classifyGovernedField} — maps a generated resolver field name
18
+ * (e.g. `funds`, `updateOneBrokerageAccount`) to the governed model and
19
+ * operation kind, or `null` for anything not tenancy-governed.
20
+ * - {@link buildScopeWhere} — the Prisma `where` fragment restricting a read
21
+ * to entitled rows.
22
+ * - {@link injectScopeWhere} — AND-composes the scope fragment onto a
23
+ * caller-supplied `where`, preserving any top-level unique selector so
24
+ * `findUnique`/`update`/`delete` keep working (Prisma extendedWhereUnique).
25
+ * - {@link dataInScope} — whether a create/upsert payload lands in an
26
+ * entitled tenant.
27
+ * - {@link evaluateAccess} — the shadow/enforce decision for one operation.
28
+ *
29
+ * By design this module imports nothing from `graphql`, `type-graphql`, or
30
+ * `@apollo/server`; it is a pure function library the middleware wires into the
31
+ * request lifecycle. Service (`SERVER_AUTH_TOKEN`) and admin principals are
32
+ * NEVER passed here — the middleware bypasses them before this code runs — so
33
+ * the engine's server-to-server `adaptic.*` traffic is never scoped.
34
+ */
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.ALWAYS_ENFORCED_MODELS = exports.GOVERNED_MODELS = exports.READ_SCOPED_MODELS = exports.DESK_MODELS = exports.DEFAULT_TENANCY_SCOPING_MODE = void 0;
37
+ exports.getTenancyScopingMode = getTenancyScopingMode;
38
+ exports.isAlwaysEnforced = isAlwaysEnforced;
39
+ exports.classifyGovernedField = classifyGovernedField;
40
+ exports.resolveEntitlement = resolveEntitlement;
41
+ exports.buildScopeWhere = buildScopeWhere;
42
+ exports.buildWriteScopeWhere = buildWriteScopeWhere;
43
+ exports.anonymousScopeWhere = anonymousScopeWhere;
44
+ exports.injectScopeWhere = injectScopeWhere;
45
+ exports.hasCreateParent = hasCreateParent;
46
+ exports.parentScopedCreateInScope = parentScopedCreateInScope;
47
+ exports.dataInScope = dataInScope;
48
+ exports.evaluateAccess = evaluateAccess;
49
+ /** Default mode when `TENANCY_SCOPING_MODE` is unset or unrecognised. */
50
+ exports.DEFAULT_TENANCY_SCOPING_MODE = 'shadow';
51
+ /**
52
+ * Resolve the current scoping mode from `TENANCY_SCOPING_MODE`. Read fresh on
53
+ * each call (cheap env read) so the mode can be flipped operationally without a
54
+ * process restart — the same pattern the engine uses to graduate a shadowed
55
+ * guard to enforcement. Unknown values fall back to the safe default (shadow),
56
+ * which never changes query behaviour.
57
+ *
58
+ * @param env - Environment source (defaults to `process.env`); injectable for tests.
59
+ * @returns The resolved {@link TenancyScopingMode}.
60
+ */
61
+ function getTenancyScopingMode(env = process.env) {
62
+ var _a;
63
+ const raw = ((_a = env.TENANCY_SCOPING_MODE) !== null && _a !== void 0 ? _a : '').trim().toLowerCase();
64
+ if (raw === 'off' || raw === 'shadow' || raw === 'enforce') {
65
+ return raw;
66
+ }
67
+ return exports.DEFAULT_TENANCY_SCOPING_MODE;
68
+ }
69
+ // -----------------------------------------------------------------------------
70
+ // Governed models + field classification
71
+ // -----------------------------------------------------------------------------
72
+ /**
73
+ * The trading-desk models. They are tenancy-governed like the models above
74
+ * them, and additionally ALWAYS enforced (see {@link ALWAYS_ENFORCED_MODELS}).
75
+ *
76
+ * Ownership: Follow, PushSubscription and UserTotp belong to a user
77
+ * (`userId`); AdaConversation belongs to its author and is readable by the
78
+ * fund's members only when `sharedWithOrg`; AdaMessage inherits its
79
+ * conversation's scope; DeskDecision and AutoFollowRule belong to a fund;
80
+ * FeatureFlagOverride belongs to a user or an organization.
81
+ */
82
+ exports.DESK_MODELS = [
83
+ 'Follow',
84
+ 'AutoFollowRule',
85
+ 'PushSubscription',
86
+ 'AdaConversation',
87
+ 'AdaMessage',
88
+ 'UserTotp',
89
+ 'DeskDecision',
90
+ 'FeatureFlagOverride',
91
+ ];
92
+ /**
93
+ * Models scoped on READ only: the middleware classifies their read fields and
94
+ * none of their writes.
95
+ *
96
+ * `Strategy` holds two kinds of row. A SYSTEM strategy (`kind` NULL) is the
97
+ * platform's catalog and stays readable as it always was. An authored
98
+ * strategy (`kind` set, written by the strategy builder) belongs to one fund
99
+ * (`fundId`) and is readable only by that fund's members, so a draft never
100
+ * reaches a person outside the fund it was written in.
101
+ *
102
+ * Writes are decided elsewhere, and more narrowly: every generated `Strategy`
103
+ * mutation is `service_only` for a user in the mutation guard, and the draft
104
+ * mutations hold the author and the fund themselves
105
+ * (`src/resolvers/custom/strategy-draft-service.ts`, through
106
+ * {@link buildWriteScopeWhere}). The model is kept out of
107
+ * {@link GOVERNED_MODELS} on purpose: that list also gives each model a
108
+ * user-write rule (`tenant_scoped`, or `membership_authority` for the
109
+ * entitlement rows; `src/auth/mutation-authorization.ts`),
110
+ * which would make the generated `Strategy` writes user-writable.
111
+ *
112
+ * Scoped in every mode ({@link ALWAYS_ENFORCED_MODELS}): the predicate leaves
113
+ * every SYSTEM row exactly as readable as before, so a staged rollout has no
114
+ * existing reader to protect, and holding it in shadow would serve every
115
+ * fund's drafts to any signed-in user.
116
+ */
117
+ exports.READ_SCOPED_MODELS = ['Strategy'];
118
+ /**
119
+ * The tenancy, notification and desk models subject to row-level scoping.
120
+ * Everything else (AlpacaAccount, Trade, User, …) is intentionally out of
121
+ * scope for this change — see the SP2-G7 gap and the follow-ups in the
122
+ * middleware docs.
123
+ */
124
+ exports.GOVERNED_MODELS = [
125
+ 'Organization',
126
+ 'OrgMembership',
127
+ 'Fund',
128
+ 'FundAssignment',
129
+ 'BrokerageAccount',
130
+ 'NotificationEvent',
131
+ 'NotificationDelivery',
132
+ 'NotificationPreference',
133
+ ...exports.DESK_MODELS,
134
+ ];
135
+ /**
136
+ * Governed models whose scoping is enforced in every mode, `off` included,
137
+ * and which refuse an unauthenticated caller outright.
138
+ *
139
+ * `TENANCY_SCOPING_MODE` stages the rollout for models that had live traffic
140
+ * before scoping existed: shadow proves no legitimate caller is caught before
141
+ * enforcement can break one, and `off` rolls back to the unscoped behaviour.
142
+ * The desk models were born after the guard and have never been served
143
+ * unscoped, so there is no caller for shadow to protect and no unscoped
144
+ * behaviour for `off` to restore. Holding them in shadow would only serve a
145
+ * user's conversations, push endpoints and second-factor state to whoever
146
+ * asks while the shadow series accumulated.
147
+ */
148
+ exports.ALWAYS_ENFORCED_MODELS = new Set([
149
+ ...exports.DESK_MODELS,
150
+ ...exports.READ_SCOPED_MODELS,
151
+ ]);
152
+ /** Whether a governed model is scoped in every mode (see {@link ALWAYS_ENFORCED_MODELS}). */
153
+ function isAlwaysEnforced(model) {
154
+ return exports.ALWAYS_ENFORCED_MODELS.has(model);
155
+ }
156
+ /**
157
+ * The plural (findMany) GraphQL field name typegraphql-prisma generates per
158
+ * model. Hardcoded (rather than reconstructed via a pluralization library) for
159
+ * the 8 governed models so classification is exact and drift-proof; the
160
+ * singular (findUnique) field name is the lower-camel model name.
161
+ */
162
+ const PLURAL_FIELD = {
163
+ Organization: 'organizations',
164
+ OrgMembership: 'orgMemberships',
165
+ Fund: 'funds',
166
+ FundAssignment: 'fundAssignments',
167
+ BrokerageAccount: 'brokerageAccounts',
168
+ NotificationEvent: 'notificationEvents',
169
+ NotificationDelivery: 'notificationDeliveries',
170
+ NotificationPreference: 'notificationPreferences',
171
+ Follow: 'follows',
172
+ AutoFollowRule: 'autoFollowRules',
173
+ PushSubscription: 'pushSubscriptions',
174
+ AdaConversation: 'adaConversations',
175
+ AdaMessage: 'adaMessages',
176
+ UserTotp: 'userTotps',
177
+ DeskDecision: 'deskDecisions',
178
+ FeatureFlagOverride: 'featureFlagOverrides',
179
+ Strategy: 'strategies',
180
+ };
181
+ /** The read fields typegraphql-prisma generates for a model. */
182
+ function readFieldsOf(model) {
183
+ return [
184
+ PLURAL_FIELD[model], // findMany
185
+ lowerFirst(model), // findUnique
186
+ `get${model}`, // findUniqueOrThrow
187
+ `findFirst${model}`,
188
+ `findFirst${model}OrThrow`,
189
+ `aggregate${model}`,
190
+ `groupBy${model}`,
191
+ ];
192
+ }
193
+ /** Lower-camel the first character of a model name (e.g. `Fund` → `fund`). */
194
+ function lowerFirst(value) {
195
+ return value.length === 0 ? value : value[0].toLowerCase() + value.slice(1);
196
+ }
197
+ /**
198
+ * Static map of every generated resolver field name → its governed model +
199
+ * operation kind. Built once at module load from the model list and the
200
+ * deterministic typegraphql-prisma naming templates.
201
+ */
202
+ const GOVERNED_FIELD_MAP = (() => {
203
+ const map = new Map();
204
+ for (const model of exports.READ_SCOPED_MODELS) {
205
+ for (const field of readFieldsOf(model)) {
206
+ map.set(field, { model, opKind: 'whereScope' });
207
+ }
208
+ }
209
+ for (const model of exports.GOVERNED_MODELS) {
210
+ const whereScopeFields = [
211
+ ...readFieldsOf(model),
212
+ `updateOne${model}`,
213
+ `updateMany${model}`,
214
+ `deleteOne${model}`,
215
+ `deleteMany${model}`,
216
+ ];
217
+ for (const field of whereScopeFields) {
218
+ map.set(field, { model, opKind: 'whereScope' });
219
+ }
220
+ for (const field of [
221
+ `createOne${model}`,
222
+ `createMany${model}`,
223
+ `createManyAndReturn${model}`,
224
+ ]) {
225
+ map.set(field, { model, opKind: 'createScope' });
226
+ }
227
+ map.set(`upsertOne${model}`, { model, opKind: 'upsertScope' });
228
+ }
229
+ return map;
230
+ })();
231
+ /**
232
+ * Classify a root Query/Mutation field name as a governed tenancy operation.
233
+ *
234
+ * @param fieldName - The GraphQL field name (`info.fieldName`).
235
+ * @returns The {@link GovernedField}, or `null` when the field is not governed.
236
+ */
237
+ function classifyGovernedField(fieldName) {
238
+ var _a;
239
+ return (_a = GOVERNED_FIELD_MAP.get(fieldName)) !== null && _a !== void 0 ? _a : null;
240
+ }
241
+ /** De-duplicate a string array, preserving first-seen order. */
242
+ function unique(values) {
243
+ return Array.from(new Set(values));
244
+ }
245
+ /**
246
+ * Resolve the {@link Entitlement} for a user id by reading their org
247
+ * memberships, the funds owned by those orgs, and any directly-assigned funds.
248
+ *
249
+ * A user with no memberships resolves to empty id sets, which makes every
250
+ * governed read return nothing under enforcement — the correct fail-closed
251
+ * posture for a caller entitled to no tenants.
252
+ *
253
+ * @param prisma - Prisma client (or a structural subset).
254
+ * @param userId - The caller's user id (JWT `sub`).
255
+ * @returns The resolved entitlement.
256
+ */
257
+ async function resolveEntitlement(prisma, userId) {
258
+ const memberships = await prisma.orgMembership.findMany({
259
+ where: { userId },
260
+ select: { organizationId: true },
261
+ });
262
+ const orgIds = unique(memberships.map((m) => m.organizationId));
263
+ const [orgFunds, assignments] = await Promise.all([
264
+ orgIds.length > 0
265
+ ? prisma.fund.findMany({
266
+ where: { organizationId: { in: orgIds } },
267
+ select: { id: true },
268
+ })
269
+ : Promise.resolve([]),
270
+ prisma.fundAssignment.findMany({
271
+ where: { userId },
272
+ select: { fundId: true },
273
+ }),
274
+ ]);
275
+ const fundIds = unique([
276
+ ...orgFunds.map((f) => f.id),
277
+ ...assignments.map((a) => a.fundId),
278
+ ]);
279
+ return { userId, orgIds, fundIds };
280
+ }
281
+ /**
282
+ * The Strategy rows a user may READ: every SYSTEM strategy (no authoring
283
+ * kind), and an authored strategy only in a fund they belong to. An authored
284
+ * row with no fund belongs to no fund, so no user reads it.
285
+ */
286
+ function strategyReadScope(fundIds) {
287
+ return { OR: [{ kind: { equals: null } }, { fundId: { in: fundIds } }] };
288
+ }
289
+ /** The AdaConversation rows a user may READ: their own, and shared ones in an entitled fund. */
290
+ function adaConversationReadScope(ent, fundIds) {
291
+ return {
292
+ OR: [{ userId: { equals: ent.userId } }, { sharedWithOrg: { equals: true }, fundId: { in: fundIds } }],
293
+ };
294
+ }
295
+ /**
296
+ * Equality on a scalar column, in the filter-object form.
297
+ *
298
+ * The fragment is injected into the GraphQL `where` argument BEFORE
299
+ * TypeGraphQL converts the arguments into the generated input classes, and
300
+ * the column's input type there is a filter class (`UuidFilter`,
301
+ * `StringFilter`). A bare value (`{ userId: 'u' }`) is valid Prisma but is not
302
+ * a filter object, so the conversion turns it into an empty filter, which
303
+ * matches every row: the scope would silently stop scoping. `{ equals }` is
304
+ * the form both the conversion and Prisma read the same way.
305
+ */
306
+ function eq(value) {
307
+ return { equals: value };
308
+ }
309
+ /**
310
+ * Build the Prisma `where` fragment that restricts reads/writes of a governed
311
+ * model to the caller's entitled rows:
312
+ *
313
+ * - Organization → `id ∈ orgIds`
314
+ * - OrgMembership → `organizationId ∈ orgIds`
315
+ * - Fund → `organizationId ∈ orgIds` OR `id ∈ fundIds` (covers assigned funds
316
+ * in an org the user is not a member of)
317
+ * - FundAssignment / BrokerageAccount → `fundId ∈ fundIds`
318
+ * - NotificationEvent → `orgId ∈ orgIds` OR `fundId ∈ fundIds` OR
319
+ * `actorUserId == userId`
320
+ * - NotificationDelivery → `recipientUserId == userId`
321
+ * - NotificationPreference → `userId == userId`
322
+ *
323
+ * @param model - The governed model.
324
+ * @param ent - The caller's entitlement.
325
+ * @returns A Prisma `where` fragment.
326
+ */
327
+ function buildScopeWhere(model, ent) {
328
+ const orgIds = [...ent.orgIds];
329
+ const fundIds = [...ent.fundIds];
330
+ switch (model) {
331
+ case 'Organization':
332
+ return { id: { in: orgIds } };
333
+ case 'OrgMembership':
334
+ return { organizationId: { in: orgIds } };
335
+ case 'Fund':
336
+ return {
337
+ OR: [{ organizationId: { in: orgIds } }, { id: { in: fundIds } }],
338
+ };
339
+ case 'FundAssignment':
340
+ return { fundId: { in: fundIds } };
341
+ case 'BrokerageAccount':
342
+ return { fundId: { in: fundIds } };
343
+ case 'NotificationEvent':
344
+ return {
345
+ OR: [
346
+ { orgId: { in: orgIds } },
347
+ { fundId: { in: fundIds } },
348
+ { actorUserId: eq(ent.userId) },
349
+ ],
350
+ };
351
+ case 'NotificationDelivery':
352
+ return { recipientUserId: eq(ent.userId) };
353
+ case 'NotificationPreference':
354
+ case 'Follow':
355
+ case 'PushSubscription':
356
+ case 'UserTotp':
357
+ return { userId: eq(ent.userId) };
358
+ case 'AutoFollowRule':
359
+ case 'DeskDecision':
360
+ return { fundId: { in: fundIds } };
361
+ case 'AdaConversation':
362
+ return adaConversationReadScope(ent, fundIds);
363
+ case 'AdaMessage':
364
+ return { conversation: { is: adaConversationReadScope(ent, fundIds) } };
365
+ case 'FeatureFlagOverride':
366
+ return { OR: [{ userId: eq(ent.userId) }, { organizationId: { in: orgIds } }] };
367
+ case 'Strategy':
368
+ return strategyReadScope(fundIds);
369
+ }
370
+ }
371
+ /**
372
+ * The scope a WRITE (update, upsert, delete) must stay inside. Identical to
373
+ * {@link buildScopeWhere} except for Ada conversations: a conversation shared
374
+ * with the organization is readable by its members but writable only by its
375
+ * author, and the same holds for its messages. A Strategy is written by a
376
+ * user only as their own authored draft, in a fund they belong to; a SYSTEM
377
+ * strategy is never in a user's write scope.
378
+ *
379
+ * @param model - The governed model.
380
+ * @param ent - The caller's entitlement.
381
+ * @returns A Prisma `where` fragment.
382
+ */
383
+ function buildWriteScopeWhere(model, ent) {
384
+ if (model === 'Strategy') {
385
+ return {
386
+ kind: { not: null },
387
+ ownerUserId: eq(ent.userId),
388
+ fundId: { in: [...ent.fundIds] },
389
+ };
390
+ }
391
+ if (model === 'AdaConversation')
392
+ return { userId: eq(ent.userId) };
393
+ if (model === 'AdaMessage')
394
+ return { conversation: { is: { userId: eq(ent.userId) } } };
395
+ return buildScopeWhere(model, ent);
396
+ }
397
+ /**
398
+ * The scope an UNAUTHENTICATED read of a model is held to, or `null` when the
399
+ * model has none (it is then passed or refused by the middleware's mode
400
+ * rules). A caller with no identity belongs to no fund, so it reads only the
401
+ * SYSTEM strategies and never an authored one.
402
+ *
403
+ * @param model - The scoped model.
404
+ * @returns A Prisma `where` fragment, or `null`.
405
+ */
406
+ function anonymousScopeWhere(model) {
407
+ return model === 'Strategy' ? { kind: { equals: null } } : null;
408
+ }
409
+ /**
410
+ * AND-compose a scope fragment onto a caller-supplied `where`, preserving any
411
+ * top-level fields (including a unique selector such as `id`/`slug`) so
412
+ * `findUnique`/`update`/`delete` remain valid under Prisma extendedWhereUnique.
413
+ * The scope is appended to the `AND` array rather than overwriting caller keys.
414
+ *
415
+ * @param where - The caller-supplied `where` (may be `undefined`).
416
+ * @param scope - The scope fragment from {@link buildScopeWhere}.
417
+ * @returns A new `where` object with the scope ANDed in.
418
+ */
419
+ function injectScopeWhere(where, scope) {
420
+ const base = where ? { ...where } : {};
421
+ const existing = base.AND;
422
+ const existingAnd = Array.isArray(existing)
423
+ ? existing
424
+ : existing !== undefined
425
+ ? [existing]
426
+ : [];
427
+ base.AND = [...existingAnd, scope];
428
+ return base;
429
+ }
430
+ // -----------------------------------------------------------------------------
431
+ // Create-payload scope checks
432
+ // -----------------------------------------------------------------------------
433
+ /**
434
+ * Read a foreign-key id from a create payload, supporting both the scalar form
435
+ * (`{ organizationId: 'x' }`) and the typegraphql-prisma nested relation form
436
+ * (`{ organization: { connect: { id: 'x' } } }`).
437
+ */
438
+ function readConnectId(data, scalarField, relationField) {
439
+ const scalar = data[scalarField];
440
+ if (typeof scalar === 'string')
441
+ return scalar;
442
+ const relation = data[relationField];
443
+ if (relation && typeof relation === 'object') {
444
+ const connect = relation.connect;
445
+ if (connect && typeof connect === 'object') {
446
+ const id = connect.id;
447
+ if (typeof id === 'string')
448
+ return id;
449
+ }
450
+ }
451
+ return undefined;
452
+ }
453
+ /** Whether a single create payload lands in a tenant the caller is entitled to. */
454
+ function singleDataInScope(model, data, ent) {
455
+ const orgIds = new Set(ent.orgIds);
456
+ const fundIds = new Set(ent.fundIds);
457
+ switch (model) {
458
+ case 'Organization':
459
+ // Self-service org creation (onboarding): the caller becomes the owner.
460
+ // This creates a brand-new tenant, not a cross-tenant access, so it is
461
+ // permitted. Membership creation into an EXISTING org is scoped below.
462
+ return true;
463
+ case 'OrgMembership': {
464
+ const orgId = readConnectId(data, 'organizationId', 'organization');
465
+ return orgId !== undefined && orgIds.has(orgId);
466
+ }
467
+ case 'Fund': {
468
+ const orgId = readConnectId(data, 'organizationId', 'organization');
469
+ return orgId !== undefined && orgIds.has(orgId);
470
+ }
471
+ case 'FundAssignment': {
472
+ const fundId = readConnectId(data, 'fundId', 'fund');
473
+ return fundId !== undefined && fundIds.has(fundId);
474
+ }
475
+ case 'BrokerageAccount': {
476
+ const fundId = readConnectId(data, 'fundId', 'fund');
477
+ return fundId !== undefined && fundIds.has(fundId);
478
+ }
479
+ case 'NotificationEvent': {
480
+ const orgId = readConnectId(data, 'orgId', 'organization');
481
+ const fundId = readConnectId(data, 'fundId', 'fund');
482
+ return ((orgId !== undefined && orgIds.has(orgId)) ||
483
+ (fundId !== undefined && fundIds.has(fundId)) ||
484
+ data.actorUserId === ent.userId);
485
+ }
486
+ case 'NotificationDelivery': {
487
+ const recipientId = readConnectId(data, 'recipientUserId', 'recipient');
488
+ return recipientId === ent.userId;
489
+ }
490
+ case 'NotificationPreference':
491
+ case 'PushSubscription':
492
+ case 'UserTotp': {
493
+ const userId = readConnectId(data, 'userId', 'user');
494
+ return userId === ent.userId;
495
+ }
496
+ case 'Follow':
497
+ case 'AdaConversation': {
498
+ const userId = readConnectId(data, 'userId', 'user');
499
+ const fundId = readConnectId(data, 'fundId', 'fund');
500
+ return userId === ent.userId && fundId !== undefined && fundIds.has(fundId);
501
+ }
502
+ case 'AutoFollowRule': {
503
+ const ownerId = readConnectId(data, 'ownerId', 'owner');
504
+ const fundId = readConnectId(data, 'fundId', 'fund');
505
+ return ownerId === ent.userId && fundId !== undefined && fundIds.has(fundId);
506
+ }
507
+ case 'DeskDecision': {
508
+ const fundId = readConnectId(data, 'fundId', 'fund');
509
+ return fundId !== undefined && fundIds.has(fundId);
510
+ }
511
+ case 'FeatureFlagOverride': {
512
+ const userId = readConnectId(data, 'userId', 'user');
513
+ const orgId = readConnectId(data, 'organizationId', 'organization');
514
+ if (userId !== undefined && orgId !== undefined)
515
+ return false;
516
+ return userId === ent.userId || (orgId !== undefined && orgIds.has(orgId));
517
+ }
518
+ case 'AdaMessage':
519
+ // A message's tenant is its conversation's, which the payload names only
520
+ // by id: it cannot be proven from the payload alone. The callers that can
521
+ // read the database resolve it with {@link parentScopedCreateInScope}.
522
+ return false;
523
+ case 'Strategy':
524
+ // No create is classified for Strategy: a user creates one only through
525
+ // createStrategyDraft, which checks the fund itself.
526
+ return false;
527
+ }
528
+ }
529
+ const CREATE_PARENTS = {
530
+ AdaMessage: { model: 'AdaConversation', scalarField: 'conversationId', relationField: 'conversation' },
531
+ };
532
+ /** Whether a model's create is scoped by a parent row (see {@link parentScopedCreateInScope}). */
533
+ function hasCreateParent(model) {
534
+ return CREATE_PARENTS[model] !== undefined;
535
+ }
536
+ /**
537
+ * Whether a create payload (or every element of a createMany payload) names a
538
+ * parent row the caller may WRITE. Used for models whose tenant is their
539
+ * parent's, which {@link dataInScope} cannot decide from the payload alone.
540
+ *
541
+ * @param prisma - A client exposing the parent delegates.
542
+ * @param model - The governed model being created.
543
+ * @param data - The create payload (object or array).
544
+ * @param ent - The caller's entitlement.
545
+ * @returns `false` for a model with no parent rule, a payload naming no
546
+ * parent, or a parent outside the caller's write scope.
547
+ */
548
+ async function parentScopedCreateInScope(prisma, model, data, ent) {
549
+ const parent = CREATE_PARENTS[model];
550
+ if (!parent)
551
+ return false;
552
+ const items = Array.isArray(data) ? data : [data];
553
+ if (items.length === 0)
554
+ return false;
555
+ const ids = [];
556
+ for (const item of items) {
557
+ if (item === null || typeof item !== 'object')
558
+ return false;
559
+ const id = readConnectId(item, parent.scalarField, parent.relationField);
560
+ if (id === undefined)
561
+ return false;
562
+ ids.push(id);
563
+ }
564
+ const reader = prisma.adaConversation;
565
+ for (const id of unique(ids)) {
566
+ const row = await reader.findFirst({
567
+ where: injectScopeWhere({ id }, buildWriteScopeWhere(parent.model, ent)),
568
+ select: { id: true },
569
+ });
570
+ if (!row)
571
+ return false;
572
+ }
573
+ return true;
574
+ }
575
+ /**
576
+ * Whether a create/createMany/upsert payload is entirely within the caller's
577
+ * entitlement. Accepts a single object or an array (createMany), requiring
578
+ * every element to be in scope.
579
+ *
580
+ * @param model - The governed model.
581
+ * @param data - The create payload (object or array).
582
+ * @param ent - The caller's entitlement.
583
+ * @returns `true` when every element lands in an entitled tenant.
584
+ */
585
+ function dataInScope(model, data, ent) {
586
+ if (Array.isArray(data)) {
587
+ return data.every((item) => item !== null &&
588
+ typeof item === 'object' &&
589
+ singleDataInScope(model, item, ent));
590
+ }
591
+ if (data === null || typeof data !== 'object') {
592
+ // Absent/malformed payload cannot be proven in-scope → treat as out of scope.
593
+ return false;
594
+ }
595
+ return singleDataInScope(model, data, ent);
596
+ }
597
+ /**
598
+ * Extract the concrete string values a caller constrained a `where` field to,
599
+ * supporting the scalar (`'x'`), `{ equals: 'x' }`, and `{ in: [...] }` forms.
600
+ * Returns `undefined` when the field is unconstrained or uses a form we cannot
601
+ * statically prove (in which case the caller is not treated as pre-scoped).
602
+ */
603
+ function extractConstraint(where, field) {
604
+ if (!where)
605
+ return undefined;
606
+ const value = where[field];
607
+ if (value === undefined || value === null)
608
+ return undefined;
609
+ if (typeof value === 'string')
610
+ return [value];
611
+ if (typeof value === 'object') {
612
+ const obj = value;
613
+ if (typeof obj.equals === 'string')
614
+ return [obj.equals];
615
+ if (Array.isArray(obj.in)) {
616
+ const strings = obj.in.filter((x) => typeof x === 'string');
617
+ return strings.length === obj.in.length ? strings : undefined;
618
+ }
619
+ }
620
+ return undefined;
621
+ }
622
+ /** Whether every value in `values` is a member of `allowed`. */
623
+ function isSubset(values, allowed) {
624
+ if (values.length === 0)
625
+ return false;
626
+ const set = new Set(allowed);
627
+ return values.every((v) => set.has(v));
628
+ }
629
+ /**
630
+ * Whether the caller-supplied `where` already constrains a read to rows within
631
+ * their entitlement. Used only to decide whether shadow mode should log — it is
632
+ * a conservative heuristic over top-level fields: when it cannot prove the
633
+ * query is pre-scoped it returns `false`, so enforce (which always injects the
634
+ * scope) may narrow a query shadow flagged as `restrict`. It never produces a
635
+ * false "already scoped" (which would hide a real cross-tenant access).
636
+ */
637
+ function readAlreadyScoped(model, where, ent) {
638
+ const inOrg = (field) => {
639
+ const c = extractConstraint(where, field);
640
+ return c !== undefined && isSubset(c, ent.orgIds);
641
+ };
642
+ const inFund = (field) => {
643
+ const c = extractConstraint(where, field);
644
+ return c !== undefined && isSubset(c, ent.fundIds);
645
+ };
646
+ const isSelf = (field) => {
647
+ const c = extractConstraint(where, field);
648
+ return c !== undefined && c.length === 1 && c[0] === ent.userId;
649
+ };
650
+ switch (model) {
651
+ case 'Organization':
652
+ return inOrg('id');
653
+ case 'OrgMembership':
654
+ return inOrg('organizationId') || isSelf('userId');
655
+ case 'Fund':
656
+ return inFund('id') || inOrg('organizationId');
657
+ case 'FundAssignment':
658
+ return inFund('fundId') || isSelf('userId');
659
+ case 'BrokerageAccount':
660
+ return inFund('fundId');
661
+ case 'NotificationEvent':
662
+ return inOrg('orgId') || inFund('fundId') || isSelf('actorUserId');
663
+ case 'NotificationDelivery':
664
+ return isSelf('recipientUserId');
665
+ case 'NotificationPreference':
666
+ case 'PushSubscription':
667
+ case 'UserTotp':
668
+ return isSelf('userId');
669
+ case 'Follow':
670
+ return isSelf('userId') || compoundIsSelf(where, 'userId_fundId_targetKind_targetId', ent.userId);
671
+ case 'AdaConversation':
672
+ return isSelf('userId');
673
+ case 'AutoFollowRule':
674
+ case 'DeskDecision':
675
+ return inFund('fundId');
676
+ case 'FeatureFlagOverride':
677
+ return isSelf('userId') || inOrg('organizationId');
678
+ case 'AdaMessage':
679
+ return false;
680
+ case 'Strategy':
681
+ return inFund('fundId');
682
+ }
683
+ }
684
+ /** Whether a compound unique selector in `where` names the caller as its `userId`. */
685
+ function compoundIsSelf(where, compound, userId) {
686
+ const key = where === null || where === void 0 ? void 0 : where[compound];
687
+ if (key === null || typeof key !== 'object')
688
+ return false;
689
+ return key.userId === userId;
690
+ }
691
+ /**
692
+ * Evaluate the scoping decision for one governed operation. Pure: it inspects
693
+ * the args but does not mutate them and performs no I/O.
694
+ *
695
+ * @param field - The classified governed field.
696
+ * @param args - The resolver args (`where` and/or `data`).
697
+ * @param ent - The caller's entitlement.
698
+ * @returns The {@link AccessAssessment}.
699
+ */
700
+ function evaluateAccess(field, args, ent) {
701
+ const where = args.where && typeof args.where === 'object'
702
+ ? args.where
703
+ : undefined;
704
+ if (field.opKind === 'whereScope') {
705
+ return readAlreadyScoped(field.model, where, ent)
706
+ ? { decision: 'allow', reason: 'where_within_entitlement' }
707
+ : { decision: 'restrict', reason: 'where_not_proven_in_scope' };
708
+ }
709
+ if (field.opKind === 'createScope') {
710
+ return dataInScope(field.model, args.data, ent)
711
+ ? { decision: 'allow', reason: 'create_data_in_scope' }
712
+ : { decision: 'deny', reason: 'create_data_out_of_scope' };
713
+ }
714
+ // upsertScope: verify the create payload AND require the where be pre-scoped
715
+ // (the update path is additionally hardened by where-injection at enforce).
716
+ // An always-enforced model is never run unscoped, so its where-injection is
717
+ // guaranteed and carries the update side on its own: a `where` naming a row
718
+ // outside the caller's scope matches nothing and the upsert falls through to
719
+ // the create, which must be in scope. That lets a user upsert by a natural
720
+ // key the scope fragment does not name (a push subscription's `endpoint`).
721
+ const createInScope = dataInScope(field.model, args.create, ent);
722
+ if (isAlwaysEnforced(field.model)) {
723
+ return createInScope
724
+ ? { decision: 'allow', reason: 'upsert_create_in_scope_where_injected' }
725
+ : { decision: 'deny', reason: 'upsert_create_out_of_scope' };
726
+ }
727
+ const whereScoped = readAlreadyScoped(field.model, where, ent);
728
+ if (createInScope && whereScoped) {
729
+ return { decision: 'allow', reason: 'upsert_in_scope' };
730
+ }
731
+ return {
732
+ decision: 'deny',
733
+ reason: createInScope ? 'upsert_where_not_in_scope' : 'upsert_create_out_of_scope',
734
+ };
735
+ }
736
+ //# sourceMappingURL=tenancy-scope.js.map