@opensaas/stack-core 0.42.3 → 0.44.0-alpha.1

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 (641) hide show
  1. package/CHANGELOG.md +2745 -0
  2. package/README.md +182 -115
  3. package/dist/.build-hash +1 -0
  4. package/dist/access/declared-dependencies.d.ts +102 -88
  5. package/dist/access/declared-dependencies.d.ts.map +1 -1
  6. package/dist/access/declared-dependencies.js +83 -71
  7. package/dist/access/declared-dependencies.js.map +1 -1
  8. package/dist/access/depth-limits.d.ts +4 -0
  9. package/dist/access/depth-limits.d.ts.map +1 -1
  10. package/dist/access/depth-limits.js +4 -0
  11. package/dist/access/depth-limits.js.map +1 -1
  12. package/dist/access/engine.d.ts +68 -20
  13. package/dist/access/engine.d.ts.map +1 -1
  14. package/dist/access/engine.js +151 -37
  15. package/dist/access/engine.js.map +1 -1
  16. package/dist/access/errors.d.ts +33 -48
  17. package/dist/access/errors.d.ts.map +1 -1
  18. package/dist/access/errors.js +73 -63
  19. package/dist/access/errors.js.map +1 -1
  20. package/dist/access/field-access.d.ts +76 -5
  21. package/dist/access/field-access.d.ts.map +1 -1
  22. package/dist/access/field-access.js +235 -61
  23. package/dist/access/field-access.js.map +1 -1
  24. package/dist/access/field-visibility.d.ts +50 -4
  25. package/dist/access/field-visibility.d.ts.map +1 -1
  26. package/dist/access/field-visibility.js +143 -160
  27. package/dist/access/field-visibility.js.map +1 -1
  28. package/dist/access/index.d.ts +5 -12
  29. package/dist/access/index.d.ts.map +1 -1
  30. package/dist/access/index.js +6 -19
  31. package/dist/access/index.js.map +1 -1
  32. package/dist/access/orm-client.d.ts +19 -0
  33. package/dist/access/orm-client.d.ts.map +1 -0
  34. package/dist/access/orm-client.js +37 -0
  35. package/dist/access/orm-client.js.map +1 -0
  36. package/dist/access/query-validation.d.ts +7 -129
  37. package/dist/access/query-validation.d.ts.map +1 -1
  38. package/dist/access/query-validation.js +12 -314
  39. package/dist/access/query-validation.js.map +1 -1
  40. package/dist/access/system-fields.d.ts +2 -0
  41. package/dist/access/system-fields.d.ts.map +1 -0
  42. package/dist/access/system-fields.js +7 -0
  43. package/dist/access/system-fields.js.map +1 -0
  44. package/dist/access/transaction-registry.d.ts +25 -2
  45. package/dist/access/transaction-registry.d.ts.map +1 -1
  46. package/dist/access/transaction-registry.js +34 -17
  47. package/dist/access/transaction-registry.js.map +1 -1
  48. package/dist/access/types.d.ts +217 -131
  49. package/dist/access/types.d.ts.map +1 -1
  50. package/dist/config/field-kind.d.ts +66 -0
  51. package/dist/config/field-kind.d.ts.map +1 -0
  52. package/dist/config/field-kind.js +63 -0
  53. package/dist/config/field-kind.js.map +1 -0
  54. package/dist/config/hook-only-fields.d.ts +3 -0
  55. package/dist/config/hook-only-fields.d.ts.map +1 -0
  56. package/dist/config/hook-only-fields.js +17 -0
  57. package/dist/config/hook-only-fields.js.map +1 -0
  58. package/dist/config/index.d.ts +3 -1
  59. package/dist/config/index.d.ts.map +1 -1
  60. package/dist/config/index.js +6 -3
  61. package/dist/config/index.js.map +1 -1
  62. package/dist/config/mcp-tool-names.d.ts +3 -0
  63. package/dist/config/mcp-tool-names.d.ts.map +1 -0
  64. package/dist/config/mcp-tool-names.js +25 -0
  65. package/dist/config/mcp-tool-names.js.map +1 -0
  66. package/dist/config/nav-count.d.ts.map +1 -1
  67. package/dist/config/nav-count.js +4 -4
  68. package/dist/config/nav-count.js.map +1 -1
  69. package/dist/config/plugin-engine.d.ts +8 -2
  70. package/dist/config/plugin-engine.d.ts.map +1 -1
  71. package/dist/config/plugin-engine.js +102 -38
  72. package/dist/config/plugin-engine.js.map +1 -1
  73. package/dist/config/types.d.ts +966 -614
  74. package/dist/config/types.d.ts.map +1 -1
  75. package/dist/context/apply-defaults.d.ts +18 -1
  76. package/dist/context/apply-defaults.d.ts.map +1 -1
  77. package/dist/context/apply-defaults.js +30 -4
  78. package/dist/context/apply-defaults.js.map +1 -1
  79. package/dist/context/engine-context.d.ts +73 -0
  80. package/dist/context/engine-context.d.ts.map +1 -0
  81. package/dist/context/engine-context.js +67 -0
  82. package/dist/context/engine-context.js.map +1 -0
  83. package/dist/context/hook-pipeline.d.ts +9 -2
  84. package/dist/context/hook-pipeline.d.ts.map +1 -1
  85. package/dist/context/hook-pipeline.js +5 -4
  86. package/dist/context/hook-pipeline.js.map +1 -1
  87. package/dist/context/index.d.ts +98 -89
  88. package/dist/context/index.d.ts.map +1 -1
  89. package/dist/context/index.js +917 -722
  90. package/dist/context/index.js.map +1 -1
  91. package/dist/context/junction.d.ts +59 -0
  92. package/dist/context/junction.d.ts.map +1 -0
  93. package/dist/context/junction.js +126 -0
  94. package/dist/context/junction.js.map +1 -0
  95. package/dist/context/plugin-field-read.d.ts +33 -0
  96. package/dist/context/plugin-field-read.d.ts.map +1 -0
  97. package/dist/context/plugin-field-read.js +41 -0
  98. package/dist/context/plugin-field-read.js.map +1 -0
  99. package/dist/context/plugin-field-write.d.ts +104 -0
  100. package/dist/context/plugin-field-write.d.ts.map +1 -0
  101. package/dist/context/plugin-field-write.js +184 -0
  102. package/dist/context/plugin-field-write.js.map +1 -0
  103. package/dist/context/relationship-input.d.ts +146 -0
  104. package/dist/context/relationship-input.d.ts.map +1 -0
  105. package/dist/context/relationship-input.js +453 -0
  106. package/dist/context/relationship-input.js.map +1 -0
  107. package/dist/context/transaction-boundary.d.ts +54 -28
  108. package/dist/context/transaction-boundary.d.ts.map +1 -1
  109. package/dist/context/transaction-boundary.js +87 -169
  110. package/dist/context/transaction-boundary.js.map +1 -1
  111. package/dist/context/write-pipeline.d.ts +33 -51
  112. package/dist/context/write-pipeline.d.ts.map +1 -1
  113. package/dist/context/write-pipeline.js +372 -185
  114. package/dist/context/write-pipeline.js.map +1 -1
  115. package/dist/contract/dependencies.d.ts +88 -0
  116. package/dist/contract/dependencies.d.ts.map +1 -0
  117. package/dist/contract/dependencies.js +237 -0
  118. package/dist/contract/dependencies.js.map +1 -0
  119. package/dist/contract/derive.d.ts +49 -0
  120. package/dist/contract/derive.d.ts.map +1 -0
  121. package/dist/contract/derive.js +540 -0
  122. package/dist/contract/derive.js.map +1 -0
  123. package/dist/contract/fixtures/contract-configs.d.ts +64 -0
  124. package/dist/contract/fixtures/contract-configs.d.ts.map +1 -0
  125. package/dist/contract/fixtures/contract-configs.js +345 -0
  126. package/dist/contract/fixtures/contract-configs.js.map +1 -0
  127. package/dist/contract/id-boundary.d.ts +53 -0
  128. package/dist/contract/id-boundary.d.ts.map +1 -0
  129. package/dist/contract/id-boundary.js +76 -0
  130. package/dist/contract/id-boundary.js.map +1 -0
  131. package/dist/contract/index.d.ts +8 -0
  132. package/dist/contract/index.d.ts.map +1 -0
  133. package/dist/contract/index.js +11 -0
  134. package/dist/contract/index.js.map +1 -0
  135. package/dist/contract/prisma.d.ts +58 -0
  136. package/dist/contract/prisma.d.ts.map +1 -0
  137. package/dist/contract/prisma.js +282 -0
  138. package/dist/contract/prisma.js.map +1 -0
  139. package/dist/contract/relation-graph.d.ts +70 -0
  140. package/dist/contract/relation-graph.d.ts.map +1 -0
  141. package/dist/contract/relation-graph.js +113 -0
  142. package/dist/contract/relation-graph.js.map +1 -0
  143. package/dist/contract/types.d.ts +135 -0
  144. package/dist/contract/types.d.ts.map +1 -0
  145. package/dist/contract/types.js +2 -0
  146. package/dist/contract/types.js.map +1 -0
  147. package/dist/db/client.d.ts +55 -0
  148. package/dist/db/client.d.ts.map +1 -0
  149. package/dist/db/client.js +73 -0
  150. package/dist/db/client.js.map +1 -0
  151. package/dist/db/dev-database.d.ts +124 -0
  152. package/dist/db/dev-database.d.ts.map +1 -0
  153. package/dist/db/dev-database.js +291 -0
  154. package/dist/db/dev-database.js.map +1 -0
  155. package/dist/db/password-front.d.ts +10 -0
  156. package/dist/db/password-front.d.ts.map +1 -0
  157. package/dist/db/password-front.js +147 -0
  158. package/dist/db/password-front.js.map +1 -0
  159. package/dist/db/process-identity.d.ts +36 -0
  160. package/dist/db/process-identity.d.ts.map +1 -0
  161. package/dist/db/process-identity.js +114 -0
  162. package/dist/db/process-identity.js.map +1 -0
  163. package/dist/db/state-file.d.ts +54 -0
  164. package/dist/db/state-file.d.ts.map +1 -0
  165. package/dist/db/state-file.js +91 -0
  166. package/dist/db/state-file.js.map +1 -0
  167. package/dist/db/url.d.ts +89 -0
  168. package/dist/db/url.d.ts.map +1 -0
  169. package/dist/db/url.js +118 -0
  170. package/dist/db/url.js.map +1 -0
  171. package/dist/extend.d.ts +13 -2
  172. package/dist/extend.d.ts.map +1 -1
  173. package/dist/extend.js +24 -1
  174. package/dist/extend.js.map +1 -1
  175. package/dist/fields/index.d.ts +87 -42
  176. package/dist/fields/index.d.ts.map +1 -1
  177. package/dist/fields/index.js +457 -677
  178. package/dist/fields/index.js.map +1 -1
  179. package/dist/filter/collect.d.ts +3 -4
  180. package/dist/filter/collect.d.ts.map +1 -1
  181. package/dist/filter/collect.js +2 -2
  182. package/dist/filter/collect.js.map +1 -1
  183. package/dist/filter/index.d.ts +1 -2
  184. package/dist/filter/index.d.ts.map +1 -1
  185. package/dist/filter/index.js +0 -1
  186. package/dist/filter/index.js.map +1 -1
  187. package/dist/filter/map.d.ts +12 -5
  188. package/dist/filter/map.d.ts.map +1 -1
  189. package/dist/filter/map.js +47 -19
  190. package/dist/filter/map.js.map +1 -1
  191. package/dist/filter/types.d.ts +10 -24
  192. package/dist/filter/types.d.ts.map +1 -1
  193. package/dist/filter/types.js +2 -11
  194. package/dist/filter/types.js.map +1 -1
  195. package/dist/hooks/index.d.ts +22 -31
  196. package/dist/hooks/index.d.ts.map +1 -1
  197. package/dist/hooks/index.js +33 -37
  198. package/dist/hooks/index.js.map +1 -1
  199. package/dist/hooks/transition-guard.d.ts +61 -0
  200. package/dist/hooks/transition-guard.d.ts.map +1 -0
  201. package/dist/hooks/transition-guard.js +93 -0
  202. package/dist/hooks/transition-guard.js.map +1 -0
  203. package/dist/index.d.ts +52 -15
  204. package/dist/index.d.ts.map +1 -1
  205. package/dist/index.js +105 -44
  206. package/dist/index.js.map +1 -1
  207. package/dist/internal.d.ts +4 -2
  208. package/dist/internal.d.ts.map +1 -1
  209. package/dist/internal.js +16 -0
  210. package/dist/internal.js.map +1 -1
  211. package/dist/lib/case-utils.d.ts +0 -1
  212. package/dist/lib/case-utils.d.ts.map +1 -1
  213. package/dist/lib/case-utils.js +0 -3
  214. package/dist/lib/case-utils.js.map +1 -1
  215. package/dist/lib/client-safe-error.d.ts +9 -0
  216. package/dist/lib/client-safe-error.d.ts.map +1 -0
  217. package/dist/lib/client-safe-error.js +23 -0
  218. package/dist/lib/client-safe-error.js.map +1 -0
  219. package/dist/lib/database-errors.d.ts +78 -0
  220. package/dist/lib/database-errors.d.ts.map +1 -0
  221. package/dist/lib/database-errors.js +148 -0
  222. package/dist/lib/database-errors.js.map +1 -0
  223. package/dist/lib/null-prototype-registry.d.ts +9 -0
  224. package/dist/lib/null-prototype-registry.d.ts.map +1 -0
  225. package/dist/lib/null-prototype-registry.js +11 -0
  226. package/dist/lib/null-prototype-registry.js.map +1 -0
  227. package/dist/lib/prisma-errors.d.ts +30 -32
  228. package/dist/lib/prisma-errors.d.ts.map +1 -1
  229. package/dist/lib/prisma-errors.js +86 -46
  230. package/dist/lib/prisma-errors.js.map +1 -1
  231. package/dist/lib/process-global.d.ts +23 -0
  232. package/dist/lib/process-global.d.ts.map +1 -0
  233. package/dist/lib/process-global.js +33 -0
  234. package/dist/lib/process-global.js.map +1 -0
  235. package/dist/lib/warn-once.d.ts +7 -0
  236. package/dist/lib/warn-once.d.ts.map +1 -0
  237. package/dist/lib/warn-once.js +13 -0
  238. package/dist/lib/warn-once.js.map +1 -0
  239. package/dist/mcp/advertise.d.ts +16 -0
  240. package/dist/mcp/advertise.d.ts.map +1 -0
  241. package/dist/mcp/advertise.js +25 -0
  242. package/dist/mcp/advertise.js.map +1 -0
  243. package/dist/mcp/arguments.d.ts +10 -0
  244. package/dist/mcp/arguments.d.ts.map +1 -0
  245. package/dist/mcp/arguments.js +143 -0
  246. package/dist/mcp/arguments.js.map +1 -0
  247. package/dist/mcp/field-schema.d.ts +50 -5
  248. package/dist/mcp/field-schema.d.ts.map +1 -1
  249. package/dist/mcp/field-schema.js +137 -14
  250. package/dist/mcp/field-schema.js.map +1 -1
  251. package/dist/mcp/handler.d.ts +16 -5
  252. package/dist/mcp/handler.d.ts.map +1 -1
  253. package/dist/mcp/handler.js +404 -126
  254. package/dist/mcp/handler.js.map +1 -1
  255. package/dist/mcp/index.d.ts +1 -0
  256. package/dist/mcp/index.d.ts.map +1 -1
  257. package/dist/mcp/index.js +1 -0
  258. package/dist/mcp/index.js.map +1 -1
  259. package/dist/mcp/projection.d.ts +42 -34
  260. package/dist/mcp/projection.d.ts.map +1 -1
  261. package/dist/mcp/projection.js +246 -200
  262. package/dist/mcp/projection.js.map +1 -1
  263. package/dist/mcp/tool-error.d.ts +8 -0
  264. package/dist/mcp/tool-error.d.ts.map +1 -0
  265. package/dist/mcp/tool-error.js +11 -0
  266. package/dist/mcp/tool-error.js.map +1 -0
  267. package/dist/mcp/types.d.ts +3 -2
  268. package/dist/mcp/types.d.ts.map +1 -1
  269. package/dist/mcp/where-id-boundary.d.ts +28 -0
  270. package/dist/mcp/where-id-boundary.d.ts.map +1 -0
  271. package/dist/mcp/where-id-boundary.js +187 -0
  272. package/dist/mcp/where-id-boundary.js.map +1 -0
  273. package/dist/origin.d.ts +147 -0
  274. package/dist/origin.d.ts.map +1 -0
  275. package/dist/origin.js +191 -0
  276. package/dist/origin.js.map +1 -0
  277. package/dist/query/relationship-options.d.ts +35 -6
  278. package/dist/query/relationship-options.d.ts.map +1 -1
  279. package/dist/query/relationship-options.js +33 -23
  280. package/dist/query/relationship-options.js.map +1 -1
  281. package/dist/secured/aggregate.d.ts +32 -0
  282. package/dist/secured/aggregate.d.ts.map +1 -0
  283. package/dist/secured/aggregate.js +31 -0
  284. package/dist/secured/aggregate.js.map +1 -0
  285. package/dist/secured/include.d.ts +320 -0
  286. package/dist/secured/include.d.ts.map +1 -0
  287. package/dist/secured/include.js +650 -0
  288. package/dist/secured/include.js.map +1 -0
  289. package/dist/secured/lock.d.ts +127 -0
  290. package/dist/secured/lock.d.ts.map +1 -0
  291. package/dist/secured/lock.js +275 -0
  292. package/dist/secured/lock.js.map +1 -0
  293. package/dist/secured/lower.d.ts +82 -0
  294. package/dist/secured/lower.d.ts.map +1 -0
  295. package/dist/secured/lower.js +162 -0
  296. package/dist/secured/lower.js.map +1 -0
  297. package/dist/secured/operators.d.ts +7 -0
  298. package/dist/secured/operators.d.ts.map +1 -0
  299. package/dist/secured/operators.js +18 -0
  300. package/dist/secured/operators.js.map +1 -0
  301. package/dist/secured/read.d.ts +208 -0
  302. package/dist/secured/read.d.ts.map +1 -0
  303. package/dist/secured/read.js +1245 -0
  304. package/dist/secured/read.js.map +1 -0
  305. package/dist/secured/select.d.ts +87 -0
  306. package/dist/secured/select.d.ts.map +1 -0
  307. package/dist/secured/select.js +250 -0
  308. package/dist/secured/select.js.map +1 -0
  309. package/dist/secured/vector.d.ts +58 -0
  310. package/dist/secured/vector.d.ts.map +1 -0
  311. package/dist/secured/vector.js +113 -0
  312. package/dist/secured/vector.js.map +1 -0
  313. package/dist/secured/vocabulary.d.ts +227 -0
  314. package/dist/secured/vocabulary.d.ts.map +1 -0
  315. package/dist/secured/vocabulary.js +578 -0
  316. package/dist/secured/vocabulary.js.map +1 -0
  317. package/dist/secured/write.d.ts +58 -0
  318. package/dist/secured/write.d.ts.map +1 -0
  319. package/dist/secured/write.js +87 -0
  320. package/dist/secured/write.js.map +1 -0
  321. package/dist/testing/context.d.ts +236 -0
  322. package/dist/testing/context.d.ts.map +1 -0
  323. package/dist/testing/context.js +457 -0
  324. package/dist/testing/context.js.map +1 -0
  325. package/dist/testing/escape.d.ts +83 -0
  326. package/dist/testing/escape.d.ts.map +1 -0
  327. package/dist/testing/escape.js +148 -0
  328. package/dist/testing/escape.js.map +1 -0
  329. package/dist/testing/extensions.d.ts +48 -0
  330. package/dist/testing/extensions.d.ts.map +1 -0
  331. package/dist/testing/extensions.js +107 -0
  332. package/dist/testing/extensions.js.map +1 -0
  333. package/dist/testing/index.d.ts +5 -0
  334. package/dist/testing/index.d.ts.map +1 -0
  335. package/dist/testing/index.js +11 -0
  336. package/dist/testing/index.js.map +1 -0
  337. package/dist/testing/plans.d.ts +64 -0
  338. package/dist/testing/plans.d.ts.map +1 -0
  339. package/dist/testing/plans.js +47 -0
  340. package/dist/testing/plans.js.map +1 -0
  341. package/dist/types/context.d.ts +110 -0
  342. package/dist/types/context.d.ts.map +1 -0
  343. package/dist/types/context.js +2 -0
  344. package/dist/types/context.js.map +1 -0
  345. package/dist/types/contract.d.ts +198 -0
  346. package/dist/types/contract.d.ts.map +1 -0
  347. package/dist/types/contract.js +2 -0
  348. package/dist/types/contract.js.map +1 -0
  349. package/dist/types/index.d.ts +6 -0
  350. package/dist/types/index.d.ts.map +1 -0
  351. package/dist/types/index.js +11 -0
  352. package/dist/types/index.js.map +1 -0
  353. package/dist/types/inputs.d.ts +83 -0
  354. package/dist/types/inputs.d.ts.map +1 -0
  355. package/dist/types/inputs.js +2 -0
  356. package/dist/types/inputs.js.map +1 -0
  357. package/dist/types/rows.d.ts +76 -0
  358. package/dist/types/rows.d.ts.map +1 -0
  359. package/dist/types/rows.js +2 -0
  360. package/dist/types/rows.js.map +1 -0
  361. package/dist/types/secured-list.d.ts +396 -0
  362. package/dist/types/secured-list.d.ts.map +1 -0
  363. package/dist/types/secured-list.js +2 -0
  364. package/dist/types/secured-list.js.map +1 -0
  365. package/dist/unsafe.d.ts +162 -0
  366. package/dist/unsafe.d.ts.map +1 -0
  367. package/dist/unsafe.js +177 -0
  368. package/dist/unsafe.js.map +1 -0
  369. package/dist/validation/config-refusal.d.ts +16 -0
  370. package/dist/validation/config-refusal.d.ts.map +1 -0
  371. package/dist/validation/config-refusal.js +2 -0
  372. package/dist/validation/config-refusal.js.map +1 -0
  373. package/dist/validation/database-config.d.ts +19 -0
  374. package/dist/validation/database-config.d.ts.map +1 -0
  375. package/dist/validation/database-config.js +221 -0
  376. package/dist/validation/database-config.js.map +1 -0
  377. package/dist/validation/default-value.d.ts +21 -0
  378. package/dist/validation/default-value.d.ts.map +1 -0
  379. package/dist/validation/default-value.js +72 -0
  380. package/dist/validation/default-value.js.map +1 -0
  381. package/dist/validation/extension-packs.d.ts +11 -0
  382. package/dist/validation/extension-packs.d.ts.map +1 -0
  383. package/dist/validation/extension-packs.js +53 -0
  384. package/dist/validation/extension-packs.js.map +1 -0
  385. package/dist/validation/field-config.d.ts +35 -21
  386. package/dist/validation/field-config.d.ts.map +1 -1
  387. package/dist/validation/field-config.js +51 -41
  388. package/dist/validation/field-config.js.map +1 -1
  389. package/dist/validation/field-names.d.ts +15 -0
  390. package/dist/validation/field-names.d.ts.map +1 -0
  391. package/dist/validation/field-names.js +155 -0
  392. package/dist/validation/field-names.js.map +1 -0
  393. package/dist/validation/identifier-names.d.ts +4 -0
  394. package/dist/validation/identifier-names.d.ts.map +1 -0
  395. package/dist/validation/identifier-names.js +39 -0
  396. package/dist/validation/identifier-names.js.map +1 -0
  397. package/dist/validation/needs-closure.d.ts +20 -30
  398. package/dist/validation/needs-closure.d.ts.map +1 -1
  399. package/dist/validation/needs-closure.js +29 -105
  400. package/dist/validation/needs-closure.js.map +1 -1
  401. package/dist/validation/relations.d.ts +17 -0
  402. package/dist/validation/relations.d.ts.map +1 -0
  403. package/dist/validation/relations.js +268 -0
  404. package/dist/validation/relations.js.map +1 -0
  405. package/dist/validation/schema.d.ts.map +1 -1
  406. package/dist/validation/schema.js +1 -3
  407. package/dist/validation/schema.js.map +1 -1
  408. package/dist/where/like.d.ts +32 -0
  409. package/dist/where/like.d.ts.map +1 -0
  410. package/dist/where/like.js +42 -0
  411. package/dist/where/like.js.map +1 -0
  412. package/package.json +70 -8
  413. package/.turbo/turbo-build.log +0 -4
  414. package/CLAUDE.md +0 -609
  415. package/dist/access/access-filter.d.ts +0 -241
  416. package/dist/access/access-filter.d.ts.map +0 -1
  417. package/dist/access/access-filter.js +0 -692
  418. package/dist/access/access-filter.js.map +0 -1
  419. package/dist/access/access-filter.test.d.ts +0 -2
  420. package/dist/access/access-filter.test.d.ts.map +0 -1
  421. package/dist/access/access-filter.test.js +0 -1256
  422. package/dist/access/access-filter.test.js.map +0 -1
  423. package/dist/access/declared-dependencies.test.d.ts +0 -2
  424. package/dist/access/declared-dependencies.test.d.ts.map +0 -1
  425. package/dist/access/declared-dependencies.test.js +0 -226
  426. package/dist/access/declared-dependencies.test.js.map +0 -1
  427. package/dist/access/denied-relation-visibility.test.d.ts +0 -2
  428. package/dist/access/denied-relation-visibility.test.d.ts.map +0 -1
  429. package/dist/access/denied-relation-visibility.test.js +0 -114
  430. package/dist/access/denied-relation-visibility.test.js.map +0 -1
  431. package/dist/access/engine.test.d.ts +0 -2
  432. package/dist/access/engine.test.d.ts.map +0 -1
  433. package/dist/access/engine.test.js +0 -56
  434. package/dist/access/engine.test.js.map +0 -1
  435. package/dist/access/field-access.test.d.ts +0 -2
  436. package/dist/access/field-access.test.d.ts.map +0 -1
  437. package/dist/access/field-access.test.js +0 -635
  438. package/dist/access/field-access.test.js.map +0 -1
  439. package/dist/access/multi-column-read-write.test.d.ts +0 -2
  440. package/dist/access/multi-column-read-write.test.d.ts.map +0 -1
  441. package/dist/access/multi-column-read-write.test.js +0 -183
  442. package/dist/access/multi-column-read-write.test.js.map +0 -1
  443. package/dist/access/relationship-count.d.ts +0 -98
  444. package/dist/access/relationship-count.d.ts.map +0 -1
  445. package/dist/access/relationship-count.js +0 -262
  446. package/dist/access/relationship-count.js.map +0 -1
  447. package/dist/access/relationship-count.test.d.ts +0 -2
  448. package/dist/access/relationship-count.test.d.ts.map +0 -1
  449. package/dist/access/relationship-count.test.js +0 -247
  450. package/dist/access/relationship-count.test.js.map +0 -1
  451. package/dist/access/relationship-label-filter.d.ts +0 -45
  452. package/dist/access/relationship-label-filter.d.ts.map +0 -1
  453. package/dist/access/relationship-label-filter.js +0 -22
  454. package/dist/access/relationship-label-filter.js.map +0 -1
  455. package/dist/access/relationship-label-filter.test.d.ts +0 -2
  456. package/dist/access/relationship-label-filter.test.d.ts.map +0 -1
  457. package/dist/access/relationship-label-filter.test.js +0 -89
  458. package/dist/access/relationship-label-filter.test.js.map +0 -1
  459. package/dist/access/synthetic-include-read.test.d.ts +0 -2
  460. package/dist/access/synthetic-include-read.test.d.ts.map +0 -1
  461. package/dist/access/synthetic-include-read.test.js +0 -121
  462. package/dist/access/synthetic-include-read.test.js.map +0 -1
  463. package/dist/context/nested-operations.d.ts +0 -47
  464. package/dist/context/nested-operations.d.ts.map +0 -1
  465. package/dist/context/nested-operations.js +0 -731
  466. package/dist/context/nested-operations.js.map +0 -1
  467. package/dist/fields/calendar-day.test.d.ts +0 -2
  468. package/dist/fields/calendar-day.test.d.ts.map +0 -1
  469. package/dist/fields/calendar-day.test.js +0 -246
  470. package/dist/fields/calendar-day.test.js.map +0 -1
  471. package/dist/fields/format-prisma-default.d.ts +0 -35
  472. package/dist/fields/format-prisma-default.d.ts.map +0 -1
  473. package/dist/fields/format-prisma-default.js +0 -49
  474. package/dist/fields/format-prisma-default.js.map +0 -1
  475. package/dist/fields/format-prisma-default.test.d.ts +0 -2
  476. package/dist/fields/format-prisma-default.test.d.ts.map +0 -1
  477. package/dist/fields/format-prisma-default.test.js +0 -54
  478. package/dist/fields/format-prisma-default.test.js.map +0 -1
  479. package/dist/fields/relationship-foreign-key.test.d.ts +0 -2
  480. package/dist/fields/relationship-foreign-key.test.d.ts.map +0 -1
  481. package/dist/fields/relationship-foreign-key.test.js +0 -18
  482. package/dist/fields/relationship-foreign-key.test.js.map +0 -1
  483. package/dist/fields/select.test.d.ts +0 -2
  484. package/dist/fields/select.test.d.ts.map +0 -1
  485. package/dist/fields/select.test.js +0 -279
  486. package/dist/fields/select.test.js.map +0 -1
  487. package/dist/fields/text-keystone-compat.test.d.ts +0 -2
  488. package/dist/fields/text-keystone-compat.test.d.ts.map +0 -1
  489. package/dist/fields/text-keystone-compat.test.js +0 -93
  490. package/dist/fields/text-keystone-compat.test.js.map +0 -1
  491. package/dist/filter/filter.test.d.ts +0 -2
  492. package/dist/filter/filter.test.d.ts.map +0 -1
  493. package/dist/filter/filter.test.js +0 -431
  494. package/dist/filter/filter.test.js.map +0 -1
  495. package/dist/filter/serialize.test.d.ts +0 -2
  496. package/dist/filter/serialize.test.d.ts.map +0 -1
  497. package/dist/filter/serialize.test.js +0 -83
  498. package/dist/filter/serialize.test.js.map +0 -1
  499. package/dist/index.test.d.ts +0 -2
  500. package/dist/index.test.d.ts.map +0 -1
  501. package/dist/index.test.js +0 -33
  502. package/dist/index.test.js.map +0 -1
  503. package/dist/lib/case-utils.test.d.ts +0 -2
  504. package/dist/lib/case-utils.test.d.ts.map +0 -1
  505. package/dist/lib/case-utils.test.js +0 -123
  506. package/dist/lib/case-utils.test.js.map +0 -1
  507. package/dist/query/index.d.ts +0 -127
  508. package/dist/query/index.d.ts.map +0 -1
  509. package/dist/query/index.js +0 -179
  510. package/dist/query/index.js.map +0 -1
  511. package/dist/query/index.test.d.ts +0 -2
  512. package/dist/query/index.test.d.ts.map +0 -1
  513. package/dist/query/index.test.js +0 -632
  514. package/dist/query/index.test.js.map +0 -1
  515. package/dist/query/relationship-options.test.d.ts +0 -2
  516. package/dist/query/relationship-options.test.d.ts.map +0 -1
  517. package/dist/query/relationship-options.test.js +0 -150
  518. package/dist/query/relationship-options.test.js.map +0 -1
  519. package/dist/validation/field-config.test.d.ts +0 -2
  520. package/dist/validation/field-config.test.d.ts.map +0 -1
  521. package/dist/validation/field-config.test.js +0 -159
  522. package/dist/validation/field-config.test.js.map +0 -1
  523. package/dist/validation/schema.test.d.ts +0 -2
  524. package/dist/validation/schema.test.d.ts.map +0 -1
  525. package/dist/validation/schema.test.js +0 -409
  526. package/dist/validation/schema.test.js.map +0 -1
  527. package/docs/type-distribution-fix.md +0 -136
  528. package/src/access/access-filter.test.ts +0 -1919
  529. package/src/access/access-filter.ts +0 -1041
  530. package/src/access/declared-dependencies.test.ts +0 -277
  531. package/src/access/declared-dependencies.ts +0 -220
  532. package/src/access/denied-relation-visibility.test.ts +0 -173
  533. package/src/access/depth-limits.ts +0 -27
  534. package/src/access/engine.test.ts +0 -67
  535. package/src/access/engine.ts +0 -193
  536. package/src/access/errors.ts +0 -242
  537. package/src/access/field-access.test.ts +0 -792
  538. package/src/access/field-access.ts +0 -353
  539. package/src/access/field-transforms.ts +0 -68
  540. package/src/access/field-visibility.ts +0 -569
  541. package/src/access/index.ts +0 -82
  542. package/src/access/multi-column-read-write.test.ts +0 -305
  543. package/src/access/query-validation.ts +0 -486
  544. package/src/access/relationship-count.test.ts +0 -344
  545. package/src/access/relationship-count.ts +0 -346
  546. package/src/access/relationship-label-filter.test.ts +0 -128
  547. package/src/access/relationship-label-filter.ts +0 -63
  548. package/src/access/synthetic-include-read.test.ts +0 -179
  549. package/src/access/transaction-registry.ts +0 -58
  550. package/src/access/types.ts +0 -391
  551. package/src/config/index.ts +0 -177
  552. package/src/config/label.ts +0 -51
  553. package/src/config/nav-count.ts +0 -77
  554. package/src/config/plugin-engine.ts +0 -261
  555. package/src/config/types.ts +0 -3270
  556. package/src/context/apply-defaults.ts +0 -47
  557. package/src/context/hook-pipeline.ts +0 -137
  558. package/src/context/index.ts +0 -1737
  559. package/src/context/nested-operations.ts +0 -1325
  560. package/src/context/transaction-boundary.ts +0 -485
  561. package/src/context/write-pipeline.ts +0 -732
  562. package/src/extend.ts +0 -28
  563. package/src/fields/calendar-day.test.ts +0 -291
  564. package/src/fields/format-prisma-default.test.ts +0 -64
  565. package/src/fields/format-prisma-default.ts +0 -64
  566. package/src/fields/index.ts +0 -1901
  567. package/src/fields/relationship-foreign-key.test.ts +0 -29
  568. package/src/fields/select.test.ts +0 -336
  569. package/src/fields/text-keystone-compat.test.ts +0 -126
  570. package/src/filter/collect.ts +0 -108
  571. package/src/filter/filter.test.ts +0 -538
  572. package/src/filter/index.ts +0 -26
  573. package/src/filter/map.ts +0 -63
  574. package/src/filter/parse.ts +0 -99
  575. package/src/filter/serialize.test.ts +0 -115
  576. package/src/filter/serialize.ts +0 -73
  577. package/src/filter/types.ts +0 -120
  578. package/src/hooks/index.ts +0 -752
  579. package/src/index.test.ts +0 -50
  580. package/src/index.ts +0 -184
  581. package/src/internal.ts +0 -61
  582. package/src/lib/case-utils.test.ts +0 -159
  583. package/src/lib/case-utils.ts +0 -68
  584. package/src/lib/prisma-errors.ts +0 -86
  585. package/src/mcp/constants.ts +0 -24
  586. package/src/mcp/field-schema.ts +0 -84
  587. package/src/mcp/handler.ts +0 -633
  588. package/src/mcp/index.ts +0 -7
  589. package/src/mcp/projection.ts +0 -497
  590. package/src/mcp/types.ts +0 -18
  591. package/src/query/index.test.ts +0 -830
  592. package/src/query/index.ts +0 -352
  593. package/src/query/relationship-options.test.ts +0 -194
  594. package/src/query/relationship-options.ts +0 -78
  595. package/src/utils/password.ts +0 -80
  596. package/src/validation/field-config.test.ts +0 -199
  597. package/src/validation/field-config.ts +0 -139
  598. package/src/validation/needs-closure.ts +0 -188
  599. package/src/validation/schema.test.ts +0 -487
  600. package/src/validation/schema.ts +0 -51
  601. package/tests/access-relationships.test.ts +0 -646
  602. package/tests/access.test.ts +0 -590
  603. package/tests/apply-defaults.test.ts +0 -119
  604. package/tests/bare-read-scalars.test.ts +0 -147
  605. package/tests/computed-field-selective-evaluation.test.ts +0 -418
  606. package/tests/config.test.ts +0 -242
  607. package/tests/context.test.ts +0 -3141
  608. package/tests/default-value-create.test.ts +0 -299
  609. package/tests/field-hooks.test.ts +0 -410
  610. package/tests/field-types.test.ts +0 -1291
  611. package/tests/hook-context-secured.test.ts +0 -424
  612. package/tests/hook-pipeline.test.ts +0 -233
  613. package/tests/hooks.test.ts +0 -481
  614. package/tests/interactive-transaction.test.ts +0 -444
  615. package/tests/label.test.ts +0 -135
  616. package/tests/mcp-fields-projection-access.test.ts +0 -250
  617. package/tests/mcp-handler.test.ts +0 -1411
  618. package/tests/multi-column-validation-ordering.test.ts +0 -305
  619. package/tests/nav-count.test.ts +0 -189
  620. package/tests/needs-declared-dependencies.test.ts +0 -503
  621. package/tests/nested-access-and-hooks.test.ts +0 -2566
  622. package/tests/nested-operation-registry.test.ts +0 -231
  623. package/tests/nested-write-hooks.test.ts +0 -864
  624. package/tests/nested-write-synthetic-relation.test.ts +0 -437
  625. package/tests/password-type-distribution.test.ts +0 -154
  626. package/tests/password-types.test.ts +0 -174
  627. package/tests/password.test.ts +0 -263
  628. package/tests/plugin-engine.test.ts +0 -1155
  629. package/tests/prisma-errors.test.ts +0 -141
  630. package/tests/resolve-chain.test.ts +0 -411
  631. package/tests/singleton.test.ts +0 -421
  632. package/tests/sudo.test.ts +0 -676
  633. package/tests/to-one-include-access-filter.test.ts +0 -172
  634. package/tests/transaction-boundary-hooks.test.ts +0 -710
  635. package/tests/transaction-boundary-outermost.test.ts +0 -530
  636. package/tests/virtual-fields.test.ts +0 -421
  637. package/tests/with-session.test.ts +0 -243
  638. package/tests/write-pipeline.test.ts +0 -617
  639. package/tsconfig.json +0 -12
  640. package/tsconfig.tsbuildinfo +0 -1
  641. package/vitest.config.ts +0 -69
@@ -1,3141 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
2
- import { getContext } from '../src/context/index.js'
3
- import { defineFragment } from '../src/query/index.js'
4
- import { virtual } from '../src/fields/index.js'
5
- import {
6
- AccessScopeDepthExceededError,
7
- InvalidFieldAccessResultError,
8
- } from '../src/access/index.js'
9
- import { READ_INCLUDE_MAX_DEPTH } from '../src/access/depth-limits.js'
10
- import type { OpenSaasConfig } from '../src/config/types.js'
11
-
12
- describe('getContext', () => {
13
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
14
- let mockPrisma: any
15
- let config: OpenSaasConfig
16
-
17
- beforeEach(() => {
18
- // Mock Prisma client with all methods needed by context
19
- mockPrisma = {
20
- user: {
21
- findFirst: vi.fn(),
22
- findUnique: vi.fn(),
23
- findMany: vi.fn(),
24
- create: vi.fn(),
25
- update: vi.fn(),
26
- delete: vi.fn(),
27
- count: vi.fn(),
28
- },
29
- post: {
30
- findFirst: vi.fn(),
31
- findUnique: vi.fn(),
32
- findMany: vi.fn(),
33
- create: vi.fn(),
34
- update: vi.fn(),
35
- delete: vi.fn(),
36
- count: vi.fn(),
37
- },
38
- }
39
-
40
- // Sample config with open access (no access control to simplify tests)
41
- config = {
42
- db: {
43
- provider: 'postgresql',
44
- url: 'postgresql://localhost:5432/test',
45
- },
46
- lists: {
47
- User: {
48
- fields: {
49
- name: { type: 'text' },
50
- email: { type: 'text', isIndexed: 'unique' },
51
- posts: { type: 'relationship', ref: 'Post.author', many: true },
52
- },
53
- access: {
54
- operation: {
55
- query: () => true,
56
- create: () => true,
57
- update: () => true,
58
- delete: () => true,
59
- },
60
- },
61
- },
62
- Post: {
63
- fields: {
64
- title: { type: 'text' },
65
- content: { type: 'text' },
66
- author: { type: 'relationship', ref: 'User.posts' },
67
- },
68
- access: {
69
- operation: {
70
- query: () => true,
71
- create: () => true,
72
- update: () => true,
73
- delete: () => true,
74
- },
75
- },
76
- },
77
- },
78
- }
79
- })
80
-
81
- it('should create context with lowercase db keys', async () => {
82
- const context = await getContext(config, mockPrisma, null)
83
-
84
- expect(context.db).toBeDefined()
85
- expect(context.db.user).toBeDefined()
86
- expect(context.db.post).toBeDefined()
87
- expect(context.session).toBeNull()
88
- expect(context.prisma).toBe(mockPrisma)
89
- })
90
-
91
- it('should include session when provided', async () => {
92
- const session = { userId: '123', role: 'admin' }
93
- const context = await getContext(config, mockPrisma, session)
94
-
95
- expect(context.session).toEqual(session)
96
- })
97
-
98
- describe('serverAction', () => {
99
- it('should create an item', async () => {
100
- const mockCreatedUser = { id: '1', name: 'John', email: 'john@example.com' }
101
- mockPrisma.user.create.mockResolvedValue(mockCreatedUser)
102
-
103
- const context = await getContext(config, mockPrisma, null)
104
- const result = await context.serverAction({
105
- listKey: 'User',
106
- action: 'create',
107
- data: { name: 'John', email: 'john@example.com' },
108
- })
109
-
110
- expect(mockPrisma.user.create).toHaveBeenCalledWith({
111
- data: { name: 'John', email: 'john@example.com' },
112
- })
113
- expect(result).toEqual({ success: true, data: mockCreatedUser })
114
- })
115
-
116
- it('should update an item', async () => {
117
- const existingUser = { id: '1', name: 'John', email: 'john@example.com' }
118
- const mockUpdatedUser = { id: '1', name: 'John Updated', email: 'john@example.com' }
119
- // Update operation first fetches the existing item
120
- mockPrisma.user.findUnique.mockResolvedValue(existingUser)
121
- mockPrisma.user.update.mockResolvedValue(mockUpdatedUser)
122
-
123
- const context = await getContext(config, mockPrisma, null)
124
- const result = await context.serverAction({
125
- listKey: 'User',
126
- action: 'update',
127
- id: '1',
128
- data: { name: 'John Updated' },
129
- })
130
-
131
- expect(mockPrisma.user.findUnique).toHaveBeenCalled()
132
- expect(mockPrisma.user.update).toHaveBeenCalled()
133
- expect(result).toEqual({ success: true, data: mockUpdatedUser })
134
- })
135
-
136
- it('should delete an item', async () => {
137
- const mockDeletedUser = { id: '1', name: 'John', email: 'john@example.com' }
138
- // Delete operation first fetches the existing item
139
- mockPrisma.user.findUnique.mockResolvedValue(mockDeletedUser)
140
- mockPrisma.user.delete.mockResolvedValue(mockDeletedUser)
141
-
142
- const context = await getContext(config, mockPrisma, null)
143
- const result = await context.serverAction({
144
- listKey: 'User',
145
- action: 'delete',
146
- id: '1',
147
- })
148
-
149
- expect(mockPrisma.user.findUnique).toHaveBeenCalled()
150
- expect(mockPrisma.user.delete).toHaveBeenCalled()
151
- expect(result).toEqual({ success: true, data: mockDeletedUser })
152
- })
153
-
154
- it('should convert listKey to lowercase for db operations', async () => {
155
- const mockCreatedPost = { id: '1', title: 'Test Post' }
156
- mockPrisma.post.create.mockResolvedValue(mockCreatedPost)
157
-
158
- const context = await getContext(config, mockPrisma, null)
159
- const result = await context.serverAction({
160
- listKey: 'Post',
161
- action: 'create',
162
- data: { title: 'Test Post' },
163
- })
164
-
165
- expect(mockPrisma.post.create).toHaveBeenCalled()
166
- expect(result).toEqual({ success: true, data: mockCreatedPost })
167
- })
168
-
169
- it('should return error for unknown action', async () => {
170
- const context = await getContext(config, mockPrisma, null)
171
- const result = await context.serverAction({
172
- listKey: 'User',
173
- action: 'unknown' as unknown as 'create',
174
- data: {},
175
- })
176
-
177
- expect(result).toEqual({ success: false, error: 'Access denied or operation failed' })
178
- })
179
-
180
- it('should return error for unknown list', async () => {
181
- const context = await getContext(config, mockPrisma, null)
182
- const result = await context.serverAction({
183
- listKey: 'UnknownList',
184
- action: 'create',
185
- data: {},
186
- })
187
-
188
- expect(result).toEqual({
189
- success: false,
190
- error: 'List "UnknownList" not found in configuration',
191
- })
192
- })
193
-
194
- it('should handle database errors', async () => {
195
- const dbError = new Error('Database connection failed')
196
- mockPrisma.user.create.mockRejectedValue(dbError)
197
-
198
- const context = await getContext(config, mockPrisma, null)
199
- const result = await context.serverAction({
200
- listKey: 'User',
201
- action: 'create',
202
- data: { name: 'John', email: 'john@example.com' },
203
- })
204
-
205
- expect(result).toMatchObject({
206
- success: false,
207
- error: 'Database connection failed',
208
- })
209
- })
210
-
211
- describe('removeRelated (relationship-table row removal)', () => {
212
- it('unlinks a to-one back-reference via an update on the related list', async () => {
213
- const existing = { id: 'p1', title: 'T', content: 'c', authorId: 'u1' }
214
- mockPrisma.post.findUnique.mockResolvedValue(existing)
215
- mockPrisma.post.update.mockResolvedValue({ id: 'p1', title: 'T', authorId: null })
216
-
217
- const context = await getContext(config, mockPrisma, { userId: 'u1' })
218
- const result = await context.serverAction({
219
- listKey: 'Post',
220
- action: 'removeRelated',
221
- mode: 'disconnect',
222
- id: 'p1',
223
- field: 'author',
224
- parentId: 'u1',
225
- })
226
-
227
- // Disconnect is an UPDATE on the related list nulling the back-reference
228
- // (a to-one back-ref disconnects with `true`), never a delete. The
229
- // distinct `{ removed }` shape avoids a redirect-on-success wrapper.
230
- expect(mockPrisma.post.update).toHaveBeenCalled()
231
- const updateArg = mockPrisma.post.update.mock.calls[0][0]
232
- expect(updateArg.where).toEqual({ id: 'p1' })
233
- expect(updateArg.data.author).toEqual({ disconnect: true })
234
- expect(mockPrisma.post.delete).not.toHaveBeenCalled()
235
- expect(result).toEqual({ removed: true })
236
- })
237
-
238
- it('deletes the related row when mode is delete', async () => {
239
- mockPrisma.post.findUnique.mockResolvedValue({ id: 'p1', title: 'T', authorId: 'u1' })
240
- mockPrisma.post.delete.mockResolvedValue({ id: 'p1', title: 'T' })
241
-
242
- const context = await getContext(config, mockPrisma, { userId: 'u1' })
243
- const result = await context.serverAction({
244
- listKey: 'Post',
245
- action: 'removeRelated',
246
- mode: 'delete',
247
- id: 'p1',
248
- })
249
-
250
- expect(mockPrisma.post.delete).toHaveBeenCalled()
251
- expect(mockPrisma.post.update).not.toHaveBeenCalled()
252
- expect(result).toEqual({ removed: true })
253
- })
254
-
255
- it('disconnects a to-many back-reference by parent id (many-to-many)', async () => {
256
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
257
- const m2mPrisma: any = {
258
- lesson: {
259
- findUnique: vi.fn().mockResolvedValue({ id: 'l1', title: 'L' }),
260
- update: vi.fn().mockResolvedValue({ id: 'l1', title: 'L' }),
261
- delete: vi.fn(),
262
- },
263
- }
264
- const m2mConfig: OpenSaasConfig = {
265
- db: { provider: 'postgresql', url: 'postgresql://localhost:5432/test' },
266
- lists: {
267
- Lesson: {
268
- fields: {
269
- title: { type: 'text' },
270
- teachers: { type: 'relationship', ref: 'Teacher.lessons', many: true },
271
- },
272
- access: {
273
- operation: {
274
- query: () => true,
275
- create: () => true,
276
- update: () => true,
277
- delete: () => true,
278
- },
279
- },
280
- },
281
- Teacher: {
282
- fields: {
283
- name: { type: 'text' },
284
- lessons: { type: 'relationship', ref: 'Lesson.teachers', many: true },
285
- },
286
- access: {
287
- operation: {
288
- query: () => true,
289
- create: () => true,
290
- update: () => true,
291
- delete: () => true,
292
- },
293
- },
294
- },
295
- },
296
- }
297
-
298
- const context = await getContext(m2mConfig, m2mPrisma, { userId: 'u1' })
299
- await context.serverAction({
300
- listKey: 'Lesson',
301
- action: 'removeRelated',
302
- mode: 'disconnect',
303
- id: 'l1',
304
- field: 'teachers',
305
- parentId: 't1',
306
- })
307
-
308
- const updateArg = m2mPrisma.lesson.update.mock.calls[0][0]
309
- // A to-many back-reference disconnects the specific parent by id.
310
- expect(updateArg.data.teachers).toEqual({ disconnect: { id: 't1' } })
311
- })
312
-
313
- it('returns a generic error (Silent failure) when the update is access-denied', async () => {
314
- const deniedConfig: OpenSaasConfig = {
315
- ...config,
316
- lists: {
317
- ...config.lists,
318
- Post: {
319
- ...config.lists.Post,
320
- access: {
321
- operation: {
322
- query: () => true,
323
- create: () => true,
324
- update: () => false, // no update access → disconnect denied
325
- delete: () => true,
326
- },
327
- },
328
- },
329
- },
330
- }
331
-
332
- const context = await getContext(deniedConfig, mockPrisma, { userId: 'u1' })
333
- const result = await context.serverAction({
334
- listKey: 'Post',
335
- action: 'removeRelated',
336
- mode: 'disconnect',
337
- id: 'p1',
338
- field: 'author',
339
- parentId: 'u1',
340
- })
341
-
342
- // Denied: reported as not removed with a generic reason (no leak).
343
- expect(result).toEqual({ removed: false, error: 'Access denied or operation failed' })
344
- })
345
- })
346
-
347
- describe('bulkAction (custom list bulk actions, #736)', () => {
348
- // A config whose Post list declares a custom bulk action that runs each
349
- // selected id through the SECURED context (`context.db.post.update`), so
350
- // access control + hooks apply per id.
351
- function configWithPublishAction(
352
- overrides?: Partial<import('../src/config/types.js').BulkAction>,
353
- ): OpenSaasConfig {
354
- return {
355
- ...config,
356
- lists: {
357
- ...config.lists,
358
- Post: {
359
- ...config.lists.Post,
360
- fields: {
361
- ...config.lists.Post.fields,
362
- status: { type: 'text' },
363
- },
364
- ui: {
365
- listView: {
366
- bulkActions: [
367
- {
368
- key: 'publish',
369
- label: 'Publish',
370
- handler: async ({ ids, context }) => {
371
- let n = 0
372
- for (const id of ids) {
373
- const r = await context.db.post.update({
374
- where: { id },
375
- data: { status: 'published' },
376
- })
377
- if (r) n++
378
- }
379
- return { message: `Published ${n} of ${ids.length}` }
380
- },
381
- ...overrides,
382
- },
383
- ],
384
- },
385
- },
386
- },
387
- },
388
- }
389
- }
390
-
391
- it('runs the handler over the selected ids through the secured context', async () => {
392
- mockPrisma.post.findUnique.mockImplementation(({ where }: { where: { id: string } }) =>
393
- Promise.resolve({ id: where.id, title: 'T', content: 'c' }),
394
- )
395
- mockPrisma.post.update.mockImplementation(({ where }: { where: { id: string } }) =>
396
- Promise.resolve({ id: where.id, status: 'published' }),
397
- )
398
-
399
- const context = await getContext(configWithPublishAction(), mockPrisma, { userId: 'u1' })
400
- const result = await context.serverAction({
401
- listKey: 'Post',
402
- action: 'bulkAction',
403
- key: 'publish',
404
- ids: ['p1', 'p2'],
405
- })
406
-
407
- // Each id went through the secured update delegate, not a raw call.
408
- expect(mockPrisma.post.update).toHaveBeenCalledTimes(2)
409
- expect(result).toEqual({ bulkAction: true, message: 'Published 2 of 2' })
410
- })
411
-
412
- it('absorbs a per-id Silent failure into the handler count (no leak)', async () => {
413
- // Update access scopes writes to id p1 only → p2 is denied and returns
414
- // null through the secured delegate. The handler simply does not count
415
- // it; the outcome never reveals which id was denied.
416
- const scopedConfig = configWithPublishAction()
417
- scopedConfig.lists.Post.access = {
418
- operation: {
419
- query: () => true,
420
- create: () => true,
421
- update: () => ({ id: { equals: 'p1' } }),
422
- delete: () => true,
423
- },
424
- }
425
- // The access filter merges into the existence pre-check: only p1 is
426
- // visible, so p2's update is denied (Silent failure → null) before it
427
- // ever reaches the update delegate.
428
- mockPrisma.post.findUnique.mockImplementation(({ where }: { where: { id: string } }) =>
429
- where.id === 'p1'
430
- ? Promise.resolve({ id: 'p1', title: 'T', content: 'c' })
431
- : Promise.resolve(null),
432
- )
433
- // The filter-match re-check (mergeFilters) only ever runs for the row
434
- // that passed the existence pre-check (p1), so returning it is enough.
435
- mockPrisma.post.findFirst.mockResolvedValue({ id: 'p1', title: 'T', content: 'c' })
436
- mockPrisma.post.update.mockResolvedValue({ id: 'p1', status: 'published' })
437
-
438
- const context = await getContext(scopedConfig, mockPrisma, { userId: 'u1' })
439
- const result = await context.serverAction({
440
- listKey: 'Post',
441
- action: 'bulkAction',
442
- key: 'publish',
443
- ids: ['p1', 'p2'],
444
- })
445
-
446
- expect(result).toEqual({ bulkAction: true, message: 'Published 1 of 2' })
447
- })
448
-
449
- it('returns an error for an unknown action key', async () => {
450
- const context = await getContext(configWithPublishAction(), mockPrisma, { userId: 'u1' })
451
- const result = await context.serverAction({
452
- listKey: 'Post',
453
- action: 'bulkAction',
454
- key: 'nope',
455
- ids: ['p1'],
456
- })
457
-
458
- expect(result).toMatchObject({ bulkAction: false })
459
- })
460
-
461
- it('re-checks hasAccess server-side so a hidden action cannot be invoked', async () => {
462
- const context = await getContext(
463
- configWithPublishAction({ hasAccess: () => false }),
464
- mockPrisma,
465
- { userId: 'u1' },
466
- )
467
- const result = await context.serverAction({
468
- listKey: 'Post',
469
- action: 'bulkAction',
470
- key: 'publish',
471
- ids: ['p1', 'p2'],
472
- })
473
-
474
- expect(result).toEqual({ bulkAction: false, error: 'Access denied' })
475
- // The handler never ran.
476
- expect(mockPrisma.post.update).not.toHaveBeenCalled()
477
- })
478
-
479
- it('returns a generic message (not the internal text) and logs when the handler throws a plain Error', async () => {
480
- // An unexpected, non-Prisma, non-known-error bug inside the handler must
481
- // not surface its internal message to the client (#761).
482
- const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
483
- try {
484
- const context = await getContext(
485
- configWithPublishAction({
486
- handler: async () => {
487
- throw new Error('secret internal detail: connection string leaked')
488
- },
489
- }),
490
- mockPrisma,
491
- { userId: 'u1' },
492
- )
493
- const result = await context.serverAction({
494
- listKey: 'Post',
495
- action: 'bulkAction',
496
- key: 'publish',
497
- ids: ['p1', 'p2'],
498
- })
499
-
500
- // Client sees the generic fallback — never the internal message.
501
- expect(result).toEqual({ bulkAction: false, error: 'Action failed' })
502
- if ('error' in result) {
503
- expect(result.error).not.toContain('secret internal detail')
504
- }
505
- // The real error is logged server-side for the operator.
506
- expect(consoleError).toHaveBeenCalled()
507
- const loggedArgs = consoleError.mock.calls[0]
508
- expect(loggedArgs.some((arg) => arg instanceof Error)).toBe(true)
509
- } finally {
510
- consoleError.mockRestore()
511
- }
512
- })
513
- })
514
-
515
- describe('updateRelated (relationship-table inline cell edit)', () => {
516
- it('updates a single field on the related row through the secured context', async () => {
517
- mockPrisma.post.findUnique.mockResolvedValue({
518
- id: 'p1',
519
- title: 'Old',
520
- content: 'c',
521
- authorId: 'u1',
522
- })
523
- mockPrisma.post.update.mockResolvedValue({
524
- id: 'p1',
525
- title: 'New',
526
- content: 'c',
527
- authorId: 'u1',
528
- })
529
-
530
- const context = await getContext(config, mockPrisma, { userId: 'u1' })
531
- const result = await context.serverAction({
532
- listKey: 'Post',
533
- action: 'updateRelated',
534
- id: 'p1',
535
- field: 'title',
536
- value: 'New',
537
- })
538
-
539
- // The edit is an UPDATE on the RELATED list, one field only. The distinct
540
- // `{ updated }` shape avoids a redirect-on-success wrapper.
541
- expect(mockPrisma.post.update).toHaveBeenCalled()
542
- const updateArg = mockPrisma.post.update.mock.calls[0][0]
543
- expect(updateArg.where).toEqual({ id: 'p1' })
544
- expect(updateArg.data.title).toBe('New')
545
- expect(mockPrisma.post.delete).not.toHaveBeenCalled()
546
- expect(result).toEqual({ updated: true })
547
- })
548
-
549
- it('returns a generic error (Silent failure) when the update is access-denied', async () => {
550
- const deniedConfig: OpenSaasConfig = {
551
- ...config,
552
- lists: {
553
- ...config.lists,
554
- Post: {
555
- ...config.lists.Post,
556
- access: {
557
- operation: {
558
- query: () => true,
559
- create: () => true,
560
- update: () => false, // no update access → inline edit denied
561
- delete: () => true,
562
- },
563
- },
564
- },
565
- },
566
- }
567
-
568
- const context = await getContext(deniedConfig, mockPrisma, { userId: 'u1' })
569
- const result = await context.serverAction({
570
- listKey: 'Post',
571
- action: 'updateRelated',
572
- id: 'p1',
573
- field: 'title',
574
- value: 'New',
575
- })
576
-
577
- // Denied: reported as not updated with a generic reason (no denied-vs-absent leak).
578
- expect(result).toEqual({ updated: false, error: 'Access denied or operation failed' })
579
- })
580
-
581
- it('surfaces a validation error so the cell can revert with a reason', async () => {
582
- const validationConfig: OpenSaasConfig = {
583
- ...config,
584
- lists: {
585
- ...config.lists,
586
- Post: {
587
- ...config.lists.Post,
588
- hooks: {
589
- validateInput: async (args) => {
590
- if (args.operation === 'delete') return
591
- const { resolvedData, addValidationError } = args
592
- if (resolvedData.title === 'spam') {
593
- addValidationError('Title cannot contain the word "spam"')
594
- }
595
- },
596
- },
597
- },
598
- },
599
- }
600
- mockPrisma.post.findUnique.mockResolvedValue({
601
- id: 'p1',
602
- title: 'Old',
603
- content: 'c',
604
- authorId: 'u1',
605
- })
606
-
607
- const context = await getContext(validationConfig, mockPrisma, { userId: 'u1' })
608
- const result = await context.serverAction({
609
- listKey: 'Post',
610
- action: 'updateRelated',
611
- id: 'p1',
612
- field: 'title',
613
- value: 'spam',
614
- })
615
-
616
- // A validation error becomes { updated: false } with the reason; the write
617
- // never reaches the database.
618
- expect(mockPrisma.post.update).not.toHaveBeenCalled()
619
- expect(result).toMatchObject({ updated: false })
620
- const failure = result as { updated: boolean; error?: string }
621
- expect(failure.error).toContain('spam')
622
- })
623
- })
624
-
625
- describe('createRelated (relationship-table pre-linked create)', () => {
626
- it('creates a row on the related list with the to-one back-reference preset to the parent', async () => {
627
- const created = { id: 'p1', title: 'New', content: 'c', authorId: 'u1' }
628
- mockPrisma.post.create.mockResolvedValue(created)
629
- // The connect target must be reachable (the related list's read access).
630
- mockPrisma.user.findUnique.mockResolvedValue({ id: 'u1' })
631
-
632
- const context = await getContext(config, mockPrisma, { userId: 'u1' })
633
- const result = await context.serverAction({
634
- listKey: 'Post',
635
- action: 'createRelated',
636
- data: { title: 'New', content: 'c' },
637
- field: 'author',
638
- parentId: 'u1',
639
- })
640
-
641
- // The back-reference is set on the SERVER (a to-one back-ref connects a
642
- // single parent), so the new row links to exactly the parent being edited.
643
- expect(mockPrisma.post.create).toHaveBeenCalled()
644
- const createArg = mockPrisma.post.create.mock.calls[0][0]
645
- expect(createArg.data.title).toBe('New')
646
- expect(createArg.data.author).toEqual({ connect: { id: 'u1' } })
647
- // Distinct `{ created }` shape (never a single-op `success`).
648
- expect(result).toEqual({ created: true, id: 'p1' })
649
- })
650
-
651
- it('connects a to-many back-reference by parent id (many-to-many)', async () => {
652
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
653
- const m2mPrisma: any = {
654
- lesson: {
655
- findUnique: vi.fn(),
656
- update: vi.fn(),
657
- delete: vi.fn(),
658
- create: vi.fn().mockResolvedValue({ id: 'l1', title: 'L' }),
659
- },
660
- teacher: {
661
- findUnique: vi.fn().mockResolvedValue({ id: 't1' }),
662
- update: vi.fn(),
663
- delete: vi.fn(),
664
- create: vi.fn(),
665
- },
666
- }
667
- const m2mConfig: OpenSaasConfig = {
668
- db: { provider: 'postgresql', url: 'postgresql://localhost:5432/test' },
669
- lists: {
670
- Lesson: {
671
- fields: {
672
- title: { type: 'text' },
673
- teachers: { type: 'relationship', ref: 'Teacher.lessons', many: true },
674
- },
675
- access: {
676
- operation: {
677
- query: () => true,
678
- create: () => true,
679
- update: () => true,
680
- delete: () => true,
681
- },
682
- },
683
- },
684
- Teacher: {
685
- fields: {
686
- name: { type: 'text' },
687
- lessons: { type: 'relationship', ref: 'Lesson.teachers', many: true },
688
- },
689
- access: {
690
- operation: {
691
- query: () => true,
692
- create: () => true,
693
- update: () => true,
694
- delete: () => true,
695
- },
696
- },
697
- },
698
- },
699
- }
700
-
701
- const context = await getContext(m2mConfig, m2mPrisma, { userId: 'u1' })
702
- await context.serverAction({
703
- listKey: 'Lesson',
704
- action: 'createRelated',
705
- data: { title: 'L' },
706
- field: 'teachers',
707
- parentId: 't1',
708
- })
709
-
710
- const createArg = m2mPrisma.lesson.create.mock.calls[0][0]
711
- // A to-many back-reference connects the parent by id.
712
- expect(createArg.data.teachers).toEqual({ connect: [{ id: 't1' }] })
713
- })
714
-
715
- // Security-critical invariant (#758): the server sets the back-reference by
716
- // spreading client `data` and THEN overwriting `data[field]` from the
717
- // trusted `parentId`, so a HOSTILE client-supplied `data[field]` can never
718
- // re-target the link to a different parent. These lock that overwrite for
719
- // both the to-one and the to-many back-reference shapes.
720
- it('overwrites a hostile client-supplied to-one back-reference with the trusted parentId', async () => {
721
- const created = { id: 'p1', title: 'New', authorId: 'u1' }
722
- mockPrisma.post.create.mockResolvedValue(created)
723
- // The connect target must be reachable (the related list's read access).
724
- mockPrisma.user.findUnique.mockResolvedValue({ id: 'u1' })
725
-
726
- const context = await getContext(config, mockPrisma, { userId: 'u1' })
727
- await context.serverAction({
728
- listKey: 'Post',
729
- action: 'createRelated',
730
- // Hostile: the client tries to re-target the link to a different parent
731
- // by supplying the back-reference field itself.
732
- data: { title: 'New', author: 'evil-id' },
733
- field: 'author',
734
- parentId: 'u1',
735
- })
736
-
737
- // The server OVERWRITES the spread-in hostile value with a connect to the
738
- // trusted parentId — the evil id never reaches the secured create.
739
- const createArg = mockPrisma.post.create.mock.calls[0][0]
740
- expect(createArg.data.author).toEqual({ connect: { id: 'u1' } })
741
- expect(createArg.data.author).not.toBe('evil-id')
742
- })
743
-
744
- it('overwrites a hostile client-supplied to-many back-reference with the trusted parentId', async () => {
745
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
746
- const m2mPrisma: any = {
747
- lesson: {
748
- findUnique: vi.fn(),
749
- update: vi.fn(),
750
- delete: vi.fn(),
751
- create: vi.fn().mockResolvedValue({ id: 'l1', title: 'L' }),
752
- },
753
- teacher: {
754
- findUnique: vi.fn().mockResolvedValue({ id: 't1' }),
755
- update: vi.fn(),
756
- delete: vi.fn(),
757
- create: vi.fn(),
758
- },
759
- }
760
- const m2mConfig: OpenSaasConfig = {
761
- db: { provider: 'postgresql', url: 'postgresql://localhost:5432/test' },
762
- lists: {
763
- Lesson: {
764
- fields: {
765
- title: { type: 'text' },
766
- teachers: { type: 'relationship', ref: 'Teacher.lessons', many: true },
767
- },
768
- access: {
769
- operation: {
770
- query: () => true,
771
- create: () => true,
772
- update: () => true,
773
- delete: () => true,
774
- },
775
- },
776
- },
777
- Teacher: {
778
- fields: {
779
- name: { type: 'text' },
780
- lessons: { type: 'relationship', ref: 'Lesson.teachers', many: true },
781
- },
782
- access: {
783
- operation: {
784
- query: () => true,
785
- create: () => true,
786
- update: () => true,
787
- delete: () => true,
788
- },
789
- },
790
- },
791
- },
792
- }
793
-
794
- const context = await getContext(m2mConfig, m2mPrisma, { userId: 'u1' })
795
- await context.serverAction({
796
- listKey: 'Lesson',
797
- action: 'createRelated',
798
- // Hostile: the client tries to connect a different teacher.
799
- data: { title: 'L', teachers: { connect: [{ id: 'evil-id' }] } },
800
- field: 'teachers',
801
- parentId: 't1',
802
- })
803
-
804
- // The to-many back-reference is overwritten to connect exactly the trusted
805
- // parent by id — the hostile connect is discarded.
806
- const createArg = m2mPrisma.lesson.create.mock.calls[0][0]
807
- expect(createArg.data.teachers).toEqual({ connect: [{ id: 't1' }] })
808
- })
809
-
810
- // Defensive guard (#758): malformed direct calls (unreachable from the
811
- // drawer, which always sends a valid relationship back-reference plus both
812
- // field and parentId) are rejected rather than degrading to an unguarded
813
- // create.
814
- it('rejects a malformed call supplying only one of field/parentId (defensive guard)', async () => {
815
- const context = await getContext(config, mockPrisma, { userId: 'u1' })
816
- const result = await context.serverAction({
817
- listKey: 'Post',
818
- action: 'createRelated',
819
- data: { title: 'New', author: 'evil-id' },
820
- field: 'author',
821
- // parentId omitted — a lone back-reference field is malformed.
822
- })
823
-
824
- expect(result).toEqual({
825
- created: false,
826
- error: 'createRelated requires both field and parentId, or neither',
827
- })
828
- // The unguarded create is never attempted.
829
- expect(mockPrisma.post.create).not.toHaveBeenCalled()
830
- })
831
-
832
- it('rejects a back-reference that does not name a relationship field (defensive guard)', async () => {
833
- const context = await getContext(config, mockPrisma, { userId: 'u1' })
834
- const result = await context.serverAction({
835
- listKey: 'Post',
836
- action: 'createRelated',
837
- data: { title: 'New' },
838
- field: 'title', // a scalar field, not a relationship
839
- parentId: 'u1',
840
- })
841
-
842
- expect(result).toMatchObject({ created: false })
843
- expect(mockPrisma.post.create).not.toHaveBeenCalled()
844
- })
845
-
846
- it('returns a generic error (Silent failure) when the create is access-denied', async () => {
847
- const deniedConfig: OpenSaasConfig = {
848
- ...config,
849
- lists: {
850
- ...config.lists,
851
- Post: {
852
- ...config.lists.Post,
853
- access: {
854
- operation: {
855
- query: () => true,
856
- create: () => false, // no create access → create denied
857
- update: () => true,
858
- delete: () => true,
859
- },
860
- },
861
- },
862
- },
863
- }
864
-
865
- const context = await getContext(deniedConfig, mockPrisma, { userId: 'u1' })
866
- const result = await context.serverAction({
867
- listKey: 'Post',
868
- action: 'createRelated',
869
- data: { title: 'New' },
870
- field: 'author',
871
- parentId: 'u1',
872
- })
873
-
874
- // Denied: reported as not created with a generic reason (no leak). The
875
- // create is never attempted at the Prisma layer.
876
- expect(result).toEqual({ created: false, error: 'Access denied or operation failed' })
877
- expect(mockPrisma.post.create).not.toHaveBeenCalled()
878
- })
879
-
880
- it('surfaces field errors from the create (e.g. a unique constraint) in the drawer shape', async () => {
881
- mockPrisma.post.create.mockRejectedValue({ code: 'P2002', meta: { target: ['title'] } })
882
- mockPrisma.user.findUnique.mockResolvedValue({ id: 'u1' })
883
-
884
- const context = await getContext(config, mockPrisma, { userId: 'u1' })
885
- const result = await context.serverAction({
886
- listKey: 'Post',
887
- action: 'createRelated',
888
- data: { title: 'Dup' },
889
- field: 'author',
890
- parentId: 'u1',
891
- })
892
-
893
- // Parsed to a distinct { created: false } with per-field errors the drawer
894
- // renders — never a single-op `success` envelope.
895
- expect(result).toMatchObject({ created: false })
896
- const created = result as { created: boolean; fieldErrors?: Record<string, string> }
897
- expect(created.fieldErrors?.title).toBeDefined()
898
- })
899
-
900
- // Prisma 7 driver adapters (verified against @prisma/adapter-pg and PGlite,
901
- // issue #979) leave `meta.target` undefined and put the equivalent data at
902
- // `meta.driverAdapterError.cause` instead, as free-text-adjacent structured
903
- // data rather than the documented shape.
904
- describe('P2002 under Prisma 7 driver adapters (issue #979)', () => {
905
- it('produces per-field errors for a composite unique violation', async () => {
906
- mockPrisma.post.create.mockRejectedValue({
907
- code: 'P2002',
908
- meta: {
909
- modelName: 'Post',
910
- driverAdapterError: {
911
- name: 'DriverAdapterError',
912
- cause: {
913
- originalCode: '23505',
914
- originalMessage:
915
- 'duplicate key value violates unique constraint "post_title_content_key"',
916
- kind: 'UniqueConstraintViolation',
917
- constraint: { fields: ['title', 'content'] },
918
- },
919
- },
920
- },
921
- })
922
- mockPrisma.user.findUnique.mockResolvedValue({ id: 'u1' })
923
-
924
- const context = await getContext(config, mockPrisma, { userId: 'u1' })
925
- const result = await context.serverAction({
926
- listKey: 'Post',
927
- action: 'createRelated',
928
- data: { title: 'Dup', content: 'Dup' },
929
- field: 'author',
930
- parentId: 'u1',
931
- })
932
-
933
- expect(result).toMatchObject({ created: false })
934
- const created = result as { created: boolean; fieldErrors?: Record<string, string> }
935
- expect(created.fieldErrors?.title).toBeDefined()
936
- expect(created.fieldErrors?.content).toBeDefined()
937
- })
938
-
939
- it('produces a field error for a single-column unique violation', async () => {
940
- mockPrisma.post.create.mockRejectedValue({
941
- code: 'P2002',
942
- meta: {
943
- modelName: 'Post',
944
- driverAdapterError: {
945
- cause: {
946
- originalMessage:
947
- 'duplicate key value violates unique constraint "post_title_key"',
948
- constraint: { fields: ['title'] },
949
- },
950
- },
951
- },
952
- })
953
- mockPrisma.user.findUnique.mockResolvedValue({ id: 'u1' })
954
-
955
- const context = await getContext(config, mockPrisma, { userId: 'u1' })
956
- const result = await context.serverAction({
957
- listKey: 'Post',
958
- action: 'createRelated',
959
- data: { title: 'Dup' },
960
- field: 'author',
961
- parentId: 'u1',
962
- })
963
-
964
- const created = result as { created: boolean; fieldErrors?: Record<string, string> }
965
- expect(created.fieldErrors?.title).toBeDefined()
966
- })
967
-
968
- it('strips quotes so a camelCase column is keyed correctly (not left quoted)', async () => {
969
- // Postgres quotes an identifier in `constraint.fields` only when it
970
- // needed quoting — a camelCase column arrives as `"authorId"`. A naive
971
- // fix that skips stripping would key fieldErrors by the literal string
972
- // `"authorId"` (quotes included), missing the real field name.
973
- mockPrisma.post.create.mockRejectedValue({
974
- code: 'P2002',
975
- meta: {
976
- driverAdapterError: {
977
- cause: {
978
- originalMessage:
979
- 'duplicate key value violates unique constraint "post_authorId_key"',
980
- constraint: { fields: ['"authorId"'] },
981
- },
982
- },
983
- },
984
- })
985
- mockPrisma.user.findUnique.mockResolvedValue({ id: 'u1' })
986
-
987
- const context = await getContext(config, mockPrisma, { userId: 'u1' })
988
- const result = await context.serverAction({
989
- listKey: 'Post',
990
- action: 'createRelated',
991
- data: { title: 'Dup' },
992
- field: 'author',
993
- parentId: 'u1',
994
- })
995
-
996
- const created = result as { created: boolean; fieldErrors?: Record<string, string> }
997
- expect(created.fieldErrors).toEqual({ authorId: 'This value is already in use' })
998
- })
999
-
1000
- it('humanizes a camelCase field name in the message instead of running words together', async () => {
1001
- // Before this fix, `target` was always empty under a driver adapter, so
1002
- // this label-formatting path never ran for a camelCase column. Recovering
1003
- // real column names makes it reachable — verify it reads as words, not
1004
- // "tenantid".
1005
- const camelCaseConfig: OpenSaasConfig = {
1006
- ...config,
1007
- lists: {
1008
- ...config.lists,
1009
- Post: {
1010
- ...config.lists.Post,
1011
- fields: { ...config.lists.Post.fields, tenantSlug: { type: 'text' } },
1012
- },
1013
- },
1014
- }
1015
- mockPrisma.post.create.mockRejectedValue({
1016
- code: 'P2002',
1017
- meta: {
1018
- driverAdapterError: {
1019
- cause: {
1020
- originalMessage:
1021
- 'duplicate key value violates unique constraint "post_tenantSlug_key"',
1022
- constraint: { fields: ['"tenantSlug"'] },
1023
- },
1024
- },
1025
- },
1026
- })
1027
- mockPrisma.user.findUnique.mockResolvedValue({ id: 'u1' })
1028
-
1029
- const context = await getContext(camelCaseConfig, mockPrisma, { userId: 'u1' })
1030
- const result = await context.serverAction({
1031
- listKey: 'Post',
1032
- action: 'createRelated',
1033
- data: { title: 'Dup' },
1034
- field: 'author',
1035
- parentId: 'u1',
1036
- })
1037
-
1038
- const created = result as { created: boolean; fieldErrors?: Record<string, string> }
1039
- expect(created.fieldErrors).toEqual({
1040
- tenantSlug: 'This tenant slug is already in use',
1041
- })
1042
- })
1043
-
1044
- it('leaves an already-populated meta.target unaffected (existing path still wins)', async () => {
1045
- mockPrisma.post.create.mockRejectedValue({
1046
- code: 'P2002',
1047
- meta: {
1048
- target: ['title'],
1049
- // Present but must be ignored — meta.target already answers the question.
1050
- driverAdapterError: {
1051
- cause: {
1052
- originalMessage: 'duplicate key value violates unique constraint "other_key"',
1053
- constraint: { fields: ['content'] },
1054
- },
1055
- },
1056
- },
1057
- })
1058
- mockPrisma.user.findUnique.mockResolvedValue({ id: 'u1' })
1059
-
1060
- const context = await getContext(config, mockPrisma, { userId: 'u1' })
1061
- const result = await context.serverAction({
1062
- listKey: 'Post',
1063
- action: 'createRelated',
1064
- data: { title: 'Dup' },
1065
- field: 'author',
1066
- parentId: 'u1',
1067
- })
1068
-
1069
- const created = result as { created: boolean; fieldErrors?: Record<string, string> }
1070
- expect(created.fieldErrors).toEqual({ title: 'This title is already in use' })
1071
- })
1072
-
1073
- it('falls back to the generic message (not a throw) when nothing is recoverable', async () => {
1074
- mockPrisma.post.create.mockRejectedValue({ code: 'P2002', meta: {} })
1075
- mockPrisma.user.findUnique.mockResolvedValue({ id: 'u1' })
1076
-
1077
- const context = await getContext(config, mockPrisma, { userId: 'u1' })
1078
- const result = await context.serverAction({
1079
- listKey: 'Post',
1080
- action: 'createRelated',
1081
- data: { title: 'Dup' },
1082
- field: 'author',
1083
- parentId: 'u1',
1084
- })
1085
-
1086
- expect(result).toEqual({
1087
- created: false,
1088
- error: 'A record with this value already exists',
1089
- fieldErrors: {},
1090
- })
1091
- })
1092
-
1093
- it('leaves a non-P2002 Prisma error unaffected', async () => {
1094
- mockPrisma.post.create.mockRejectedValue({
1095
- code: 'P2025',
1096
- meta: { driverAdapterError: { cause: { constraint: { fields: ['title'] } } } },
1097
- message: 'Record to update not found',
1098
- })
1099
- mockPrisma.user.findUnique.mockResolvedValue({ id: 'u1' })
1100
-
1101
- const context = await getContext(config, mockPrisma, { userId: 'u1' })
1102
- const result = await context.serverAction({
1103
- listKey: 'Post',
1104
- action: 'createRelated',
1105
- data: { title: 'Dup' },
1106
- field: 'author',
1107
- parentId: 'u1',
1108
- })
1109
-
1110
- expect(result).toEqual({
1111
- created: false,
1112
- error: 'Record to update not found',
1113
- fieldErrors: {},
1114
- })
1115
- })
1116
- })
1117
- })
1118
-
1119
- describe('relationshipOptions', () => {
1120
- it('returns { id, label }[] for the related list, unfiltered/unincluded', async () => {
1121
- mockPrisma.user.findMany.mockResolvedValue([
1122
- { id: 'u1', name: 'Ada' },
1123
- { id: 'u2', name: 'Alan' },
1124
- ])
1125
-
1126
- const context = await getContext(config, mockPrisma, null)
1127
- const result = await context.serverAction({
1128
- listKey: 'Post',
1129
- action: 'relationshipOptions',
1130
- field: 'author',
1131
- })
1132
-
1133
- expect(result).toEqual({
1134
- success: true,
1135
- data: [
1136
- { id: 'u1', label: 'Ada' },
1137
- { id: 'u2', label: 'Alan' },
1138
- ],
1139
- })
1140
- const call = mockPrisma.user.findMany.mock.calls[0][0]
1141
- expect(call.include).toBeUndefined()
1142
- })
1143
-
1144
- it('bounds the query by take', async () => {
1145
- mockPrisma.user.findMany.mockResolvedValue([{ id: 'u1', name: 'Ada' }])
1146
-
1147
- const context = await getContext(config, mockPrisma, null)
1148
- await context.serverAction({
1149
- listKey: 'Post',
1150
- action: 'relationshipOptions',
1151
- field: 'author',
1152
- take: 1,
1153
- })
1154
-
1155
- expect(mockPrisma.user.findMany).toHaveBeenCalledWith(expect.objectContaining({ take: 1 }))
1156
- })
1157
-
1158
- it('unions selectedIds beyond the take/search window', async () => {
1159
- mockPrisma.user.findMany.mockResolvedValueOnce([{ id: 'u1', name: 'Ada' }])
1160
- mockPrisma.user.findMany.mockResolvedValueOnce([{ id: 'u9', name: 'Zed' }])
1161
-
1162
- const context = await getContext(config, mockPrisma, null)
1163
- const result = await context.serverAction({
1164
- listKey: 'Post',
1165
- action: 'relationshipOptions',
1166
- field: 'author',
1167
- take: 1,
1168
- selectedIds: ['u9'],
1169
- })
1170
-
1171
- expect(result).toEqual({
1172
- success: true,
1173
- data: [
1174
- { id: 'u1', label: 'Ada' },
1175
- { id: 'u9', label: 'Zed' },
1176
- ],
1177
- })
1178
- })
1179
-
1180
- it('returns [] data when the related list query access is denied', async () => {
1181
- const deniedConfig: OpenSaasConfig = {
1182
- ...config,
1183
- lists: {
1184
- ...config.lists,
1185
- User: {
1186
- ...config.lists.User,
1187
- access: { operation: { query: () => false } },
1188
- },
1189
- },
1190
- }
1191
- mockPrisma.user.findMany.mockResolvedValue([{ id: 'u1', name: 'Ada' }])
1192
-
1193
- const context = await getContext(deniedConfig, mockPrisma, null)
1194
- const result = await context.serverAction({
1195
- listKey: 'Post',
1196
- action: 'relationshipOptions',
1197
- field: 'author',
1198
- })
1199
-
1200
- expect(result).toEqual({ success: true, data: [] })
1201
- })
1202
-
1203
- it('returns an error when the field is not a relationship field', async () => {
1204
- const context = await getContext(config, mockPrisma, null)
1205
- const result = await context.serverAction({
1206
- listKey: 'Post',
1207
- action: 'relationshipOptions',
1208
- field: 'title',
1209
- })
1210
-
1211
- expect(result).toEqual({
1212
- success: false,
1213
- error: 'Field "title" on list "Post" is not a relationship field',
1214
- })
1215
- })
1216
-
1217
- it('returns an error when the field does not exist', async () => {
1218
- const context = await getContext(config, mockPrisma, null)
1219
- const result = await context.serverAction({
1220
- listKey: 'Post',
1221
- action: 'relationshipOptions',
1222
- field: 'nonexistent',
1223
- })
1224
-
1225
- expect(result).toEqual({
1226
- success: false,
1227
- error: 'Field "nonexistent" on list "Post" is not a relationship field',
1228
- })
1229
- })
1230
- })
1231
- })
1232
-
1233
- describe('db operations', () => {
1234
- it('should delegate findUnique to prisma with access control', async () => {
1235
- const mockUser = { id: '1', name: 'John', email: 'john@example.com' }
1236
- mockPrisma.user.findFirst.mockResolvedValue(mockUser)
1237
-
1238
- const context = await getContext(config, mockPrisma, null)
1239
- const result = await context.db.user.findUnique({ where: { id: '1' } })
1240
-
1241
- expect(mockPrisma.user.findFirst).toHaveBeenCalled()
1242
- expect(result).toEqual(mockUser)
1243
- })
1244
-
1245
- describe('findUnique unique-where enforcement (#567)', () => {
1246
- it('accepts a valid unique where (id) and keeps access + include intact', async () => {
1247
- const mockUser = { id: '1', name: 'John', email: 'john@example.com' }
1248
- mockPrisma.user.findFirst.mockResolvedValue(mockUser)
1249
-
1250
- const context = await getContext(config, mockPrisma, null)
1251
- const result = await context.db.user.findUnique({
1252
- where: { id: '1' },
1253
- include: { posts: true },
1254
- })
1255
-
1256
- // Access control still runs and the underlying delegate is invoked with
1257
- // the merged where + include (proving access + include path is intact).
1258
- expect(mockPrisma.user.findFirst).toHaveBeenCalledWith(
1259
- expect.objectContaining({
1260
- where: expect.objectContaining({ id: '1' }),
1261
- include: { posts: true },
1262
- }),
1263
- )
1264
- expect(result).toEqual(mockUser)
1265
- })
1266
-
1267
- it('accepts a configured-unique field (email) as the unique where', async () => {
1268
- const mockUser = { id: '1', name: 'John', email: 'john@example.com' }
1269
- mockPrisma.user.findFirst.mockResolvedValue(mockUser)
1270
-
1271
- const context = await getContext(config, mockPrisma, null)
1272
- const result = await context.db.user.findUnique({
1273
- where: { email: 'john@example.com' },
1274
- })
1275
-
1276
- expect(mockPrisma.user.findFirst).toHaveBeenCalled()
1277
- expect(result).toEqual(mockUser)
1278
- })
1279
-
1280
- it('narrows the result through a query fragment with a unique where', async () => {
1281
- const mockUser = { id: '1', name: 'John', email: 'john@example.com' }
1282
- mockPrisma.user.findFirst.mockResolvedValue(mockUser)
1283
-
1284
- const fragment = defineFragment<{ id: string; name: string; email: string }>()({
1285
- id: true,
1286
- name: true,
1287
- } as const)
1288
-
1289
- const context = await getContext(config, mockPrisma, null)
1290
- const result = await context.db.user.findUnique({ where: { id: '1' }, query: fragment })
1291
-
1292
- // Fragment narrows the result to only the requested fields (email omitted)
1293
- expect(result).toEqual({ id: '1', name: 'John' })
1294
- })
1295
-
1296
- it('THROWS on a non-unique where (caller-shape error, not a silent null)', async () => {
1297
- mockPrisma.user.findFirst.mockResolvedValue({ id: '1', name: 'John' })
1298
-
1299
- const context = await getContext(config, mockPrisma, null)
1300
-
1301
- // `name` is not a unique key — this is misuse and must throw, not return null.
1302
- await expect(context.db.user.findUnique({ where: { name: 'John' } })).rejects.toThrow(
1303
- /requires a unique `where`/,
1304
- )
1305
- // The error guides the caller toward findFirst (the non-unique escape hatch).
1306
- await expect(context.db.user.findUnique({ where: { name: 'John' } })).rejects.toThrow(
1307
- /findFirst/,
1308
- )
1309
- // Guard runs before any DB access.
1310
- expect(mockPrisma.user.findFirst).not.toHaveBeenCalled()
1311
- })
1312
-
1313
- it('THROWS when a unique key is mixed with extra non-unique keys', async () => {
1314
- const context = await getContext(config, mockPrisma, null)
1315
-
1316
- await expect(
1317
- context.db.user.findUnique({ where: { id: '1', name: 'John' } }),
1318
- ).rejects.toThrow(/requires a unique `where`/)
1319
- expect(mockPrisma.user.findFirst).not.toHaveBeenCalled()
1320
- })
1321
-
1322
- it('THROWS on an empty where', async () => {
1323
- const context = await getContext(config, mockPrisma, null)
1324
-
1325
- await expect(context.db.user.findUnique({ where: {} })).rejects.toThrow(
1326
- /requires a unique `where`/,
1327
- )
1328
- expect(mockPrisma.user.findFirst).not.toHaveBeenCalled()
1329
- })
1330
-
1331
- it('returns null on access denial (silent-failure contract preserved)', async () => {
1332
- const deniedConfig: OpenSaasConfig = {
1333
- ...config,
1334
- lists: {
1335
- ...config.lists,
1336
- User: {
1337
- ...config.lists.User,
1338
- access: {
1339
- operation: {
1340
- query: () => false,
1341
- create: () => true,
1342
- update: () => true,
1343
- delete: () => true,
1344
- },
1345
- },
1346
- },
1347
- },
1348
- }
1349
- mockPrisma.user.findFirst.mockResolvedValue({ id: '1', name: 'John' })
1350
-
1351
- const context = await getContext(deniedConfig, mockPrisma, null)
1352
- const result = await context.db.user.findUnique({ where: { id: '1' } })
1353
-
1354
- // Access denied -> null (not a throw), and the DB is never queried.
1355
- expect(result).toBeNull()
1356
- expect(mockPrisma.user.findFirst).not.toHaveBeenCalled()
1357
- })
1358
-
1359
- it('returns null when no record matches a valid unique where', async () => {
1360
- mockPrisma.user.findFirst.mockResolvedValue(null)
1361
-
1362
- const context = await getContext(config, mockPrisma, null)
1363
- const result = await context.db.user.findUnique({ where: { id: 'missing' } })
1364
-
1365
- expect(result).toBeNull()
1366
- expect(mockPrisma.user.findFirst).toHaveBeenCalled()
1367
- })
1368
- })
1369
-
1370
- it('should delegate findMany to prisma with access control', async () => {
1371
- const mockUsers = [
1372
- { id: '1', name: 'John' },
1373
- { id: '2', name: 'Jane' },
1374
- ]
1375
- mockPrisma.user.findMany.mockResolvedValue(mockUsers)
1376
-
1377
- const context = await getContext(config, mockPrisma, null)
1378
- const result = await context.db.user.findMany()
1379
-
1380
- expect(mockPrisma.user.findMany).toHaveBeenCalled()
1381
- expect(result).toEqual(mockUsers)
1382
- })
1383
-
1384
- describe('findFirst', () => {
1385
- it('should return the first matching row', async () => {
1386
- const mockUsers = [
1387
- { id: '1', name: 'John', email: 'john@example.com' },
1388
- { id: '2', name: 'Jane', email: 'jane@example.com' },
1389
- ]
1390
- mockPrisma.user.findMany.mockResolvedValue(mockUsers)
1391
-
1392
- const context = await getContext(config, mockPrisma, null)
1393
- const result = await context.db.user.findFirst()
1394
-
1395
- // Delegates to the access-controlled findMany with take: 1
1396
- expect(mockPrisma.user.findMany).toHaveBeenCalledWith(expect.objectContaining({ take: 1 }))
1397
- expect(result).toEqual(mockUsers[0])
1398
- })
1399
-
1400
- it('should return null (not undefined, not throw) when nothing matches', async () => {
1401
- mockPrisma.user.findMany.mockResolvedValue([])
1402
-
1403
- const context = await getContext(config, mockPrisma, null)
1404
- const result = await context.db.user.findFirst({ where: { name: 'Nobody' } })
1405
-
1406
- expect(result).toBeNull()
1407
- expect(result).not.toBeUndefined()
1408
- })
1409
-
1410
- it('should respect where and orderBy', async () => {
1411
- const mockUser = { id: '2', name: 'Jane', email: 'jane@example.com' }
1412
- mockPrisma.user.findMany.mockResolvedValue([mockUser])
1413
-
1414
- const context = await getContext(config, mockPrisma, null)
1415
- const result = await context.db.user.findFirst({
1416
- where: { name: 'Jane' },
1417
- orderBy: { name: 'asc' },
1418
- })
1419
-
1420
- expect(mockPrisma.user.findMany).toHaveBeenCalledWith(
1421
- expect.objectContaining({
1422
- where: expect.objectContaining({ name: 'Jane' }),
1423
- orderBy: { name: 'asc' },
1424
- take: 1,
1425
- }),
1426
- )
1427
- expect(result).toEqual(mockUser)
1428
- })
1429
-
1430
- it('should honour query-access denial the same as findMany (denied -> null)', async () => {
1431
- const deniedConfig: OpenSaasConfig = {
1432
- ...config,
1433
- lists: {
1434
- ...config.lists,
1435
- User: {
1436
- ...config.lists.User,
1437
- access: {
1438
- operation: {
1439
- query: () => false,
1440
- create: () => true,
1441
- update: () => true,
1442
- delete: () => true,
1443
- },
1444
- },
1445
- },
1446
- },
1447
- }
1448
- mockPrisma.user.findMany.mockResolvedValue([
1449
- { id: '1', name: 'John', email: 'john@example.com' },
1450
- ])
1451
-
1452
- const context = await getContext(deniedConfig, mockPrisma, null)
1453
- const result = await context.db.user.findFirst()
1454
-
1455
- // Denied query short-circuits before hitting prisma — exactly like findMany
1456
- expect(result).toBeNull()
1457
- expect(mockPrisma.user.findMany).not.toHaveBeenCalled()
1458
- })
1459
-
1460
- it('should respect a query fragment, narrowing the returned single result', async () => {
1461
- const mockUsers = [
1462
- { id: '1', name: 'John', email: 'john@example.com' },
1463
- { id: '2', name: 'Jane', email: 'jane@example.com' },
1464
- ]
1465
- mockPrisma.user.findMany.mockResolvedValue(mockUsers)
1466
-
1467
- const fragment = defineFragment<{ id: string; name: string; email: string }>()({
1468
- id: true,
1469
- name: true,
1470
- } as const)
1471
-
1472
- const context = await getContext(config, mockPrisma, null)
1473
- const result = await context.db.user.findFirst({ query: fragment })
1474
-
1475
- // Fragment narrows the result to only the requested fields (email omitted)
1476
- expect(result).toEqual({ id: '1', name: 'John' })
1477
- })
1478
- })
1479
-
1480
- describe('read-path key validation (#912)', () => {
1481
- it('throws on an undeclared `where` key on findMany, naming the list and the key', async () => {
1482
- const context = await getContext(config, mockPrisma, null)
1483
-
1484
- await expect(context.db.post.findMany({ where: { bogusKey: 'x' } })).rejects.toThrow(/Post/)
1485
- await expect(context.db.post.findMany({ where: { bogusKey: 'x' } })).rejects.toThrow(
1486
- /bogusKey/,
1487
- )
1488
- expect(mockPrisma.post.findMany).not.toHaveBeenCalled()
1489
- })
1490
-
1491
- it('throws on an undeclared `where` key on count', async () => {
1492
- const context = await getContext(config, mockPrisma, null)
1493
-
1494
- await expect(context.db.user.count({ where: { bogusKey: 'x' } })).rejects.toThrow(
1495
- /bogusKey/,
1496
- )
1497
- expect(mockPrisma.user.count).not.toHaveBeenCalled()
1498
- })
1499
-
1500
- it('throws on an undeclared `orderBy` key on findMany', async () => {
1501
- const context = await getContext(config, mockPrisma, null)
1502
-
1503
- await expect(context.db.post.findMany({ orderBy: { bogusKey: 'asc' } })).rejects.toThrow(
1504
- /bogusKey/,
1505
- )
1506
- expect(mockPrisma.post.findMany).not.toHaveBeenCalled()
1507
- })
1508
-
1509
- it('throws on an undeclared key nested inside a logical operator (AND/OR/NOT)', async () => {
1510
- const context = await getContext(config, mockPrisma, null)
1511
-
1512
- await expect(
1513
- context.db.post.findMany({
1514
- where: { OR: [{ title: { contains: 'a' } }, { bogusKey: 'x' }] },
1515
- }),
1516
- ).rejects.toThrow(/bogusKey/)
1517
-
1518
- await expect(
1519
- context.db.post.findMany({
1520
- where: { AND: [{ NOT: { bogusKey: 'x' } }] },
1521
- }),
1522
- ).rejects.toThrow(/bogusKey/)
1523
- })
1524
-
1525
- it('throws on an undeclared key nested inside a relation filter, naming the RELATED list', async () => {
1526
- const context = await getContext(config, mockPrisma, null)
1527
-
1528
- await expect(
1529
- context.db.post.findMany({ where: { author: { is: { bogusKey: 'x' } } } }),
1530
- ).rejects.toThrow(/User/)
1531
- await expect(
1532
- context.db.post.findMany({ where: { author: { is: { bogusKey: 'x' } } } }),
1533
- ).rejects.toThrow(/bogusKey/)
1534
- })
1535
-
1536
- it("throws on an undeclared key reached via Prisma's direct-nesting to-one filter (no `is` wrapper)", async () => {
1537
- // Prisma's documented default for filtering a to-one relation nests the
1538
- // related list's fields directly, with no `is`/`isNot` wrapper at all —
1539
- // e.g. `{ author: { email: { contains: '...' } } }`. An undeclared key
1540
- // reached this way (one hop through a to-one relation, rather than at
1541
- // the root) must be rejected exactly like the wrapped `is` form.
1542
- const context = await getContext(config, mockPrisma, null)
1543
-
1544
- await expect(
1545
- context.db.post.findMany({ where: { author: { bogusKey: 'x' } } }),
1546
- ).rejects.toThrow(/User/)
1547
- await expect(
1548
- context.db.post.findMany({ where: { author: { bogusKey: 'x' } } }),
1549
- ).rejects.toThrow(/bogusKey/)
1550
- expect(mockPrisma.post.findMany).not.toHaveBeenCalled()
1551
- })
1552
-
1553
- it('accepts a declared field on the direct-nesting to-one filter form', async () => {
1554
- mockPrisma.post.findMany.mockResolvedValue([])
1555
-
1556
- const context = await getContext(config, mockPrisma, null)
1557
- const where = { author: { name: { equals: 'John' } } }
1558
- await context.db.post.findMany({ where })
1559
-
1560
- expect(mockPrisma.post.findMany).toHaveBeenCalledWith(expect.objectContaining({ where }))
1561
- })
1562
-
1563
- it('rejects a Prisma-generated back-relation the list config never declares (the regression that matters most)', async () => {
1564
- // Organisation declares no relationship back to Document — mirrors a
1565
- // list whose Prisma model gets a `from_Document_organisation`
1566
- // back-relation purely because Document holds an FK pointing at it.
1567
- const backRelationPrisma = {
1568
- organisation: { findMany: vi.fn(), count: vi.fn() },
1569
- }
1570
- const backRelationConfig: OpenSaasConfig = {
1571
- db: { provider: 'postgresql', url: 'postgresql://localhost:5432/test' },
1572
- lists: {
1573
- Organisation: {
1574
- fields: { name: { type: 'text' } },
1575
- access: { operation: { query: () => true } },
1576
- },
1577
- },
1578
- }
1579
-
1580
- const context = await getContext(backRelationConfig, backRelationPrisma, null)
1581
-
1582
- await expect(
1583
- context.db.organisation.findMany({
1584
- where: { from_Document_organisation: { some: {} } },
1585
- }),
1586
- ).rejects.toThrow(/from_Document_organisation/)
1587
- await expect(
1588
- context.db.organisation.count({
1589
- where: { from_Document_organisation: { some: {} } },
1590
- }),
1591
- ).rejects.toThrow(/from_Document_organisation/)
1592
-
1593
- expect(backRelationPrisma.organisation.findMany).not.toHaveBeenCalled()
1594
- expect(backRelationPrisma.organisation.count).not.toHaveBeenCalled()
1595
- })
1596
-
1597
- it('never mistakes a Prisma filter operator (equals/contains/startsWith/in/is/isNot) for a field name', async () => {
1598
- mockPrisma.post.findMany.mockResolvedValue([
1599
- { id: '1', title: 'Test Post', content: 'x', authorId: 'u1' },
1600
- ])
1601
-
1602
- const context = await getContext(config, mockPrisma, null)
1603
- const where = {
1604
- title: { equals: 'Test Post', contains: 'Test', startsWith: 'T', in: ['Test Post'] },
1605
- author: { is: { name: 'John' }, isNot: null },
1606
- }
1607
-
1608
- await context.db.post.findMany({ where })
1609
-
1610
- expect(mockPrisma.post.findMany).toHaveBeenCalledWith(expect.objectContaining({ where }))
1611
- })
1612
-
1613
- it('passes all of the above through under sudo (the single trusted bypass)', async () => {
1614
- mockPrisma.post.findMany.mockResolvedValue([])
1615
-
1616
- const context = (await getContext(config, mockPrisma, null)).sudo()
1617
- await context.db.post.findMany({
1618
- where: { bogusKey: 'x', OR: [{ alsoBogus: 'y' }] },
1619
- orderBy: { alsoOrderByBogus: 'asc' },
1620
- })
1621
-
1622
- expect(mockPrisma.post.findMany).toHaveBeenCalledWith(
1623
- expect.objectContaining({
1624
- where: { bogusKey: 'x', OR: [{ alsoBogus: 'y' }] },
1625
- orderBy: { alsoOrderByBogus: 'asc' },
1626
- }),
1627
- )
1628
- })
1629
-
1630
- it('keeps an implied foreign-key scalar filterable (authorId for author: relationship(...))', async () => {
1631
- mockPrisma.post.findMany.mockResolvedValue([])
1632
-
1633
- const context = await getContext(config, mockPrisma, null)
1634
- await context.db.post.findMany({ where: { authorId: 'user-1' } })
1635
-
1636
- expect(mockPrisma.post.findMany).toHaveBeenCalledWith(
1637
- expect.objectContaining({ where: { authorId: 'user-1' } }),
1638
- )
1639
- })
1640
-
1641
- it('findFirst inherits the check through findMany, with no second copy', async () => {
1642
- const context = await getContext(config, mockPrisma, null)
1643
-
1644
- await expect(context.db.post.findFirst({ where: { bogusKey: 'x' } })).rejects.toThrow(
1645
- /bogusKey/,
1646
- )
1647
- expect(mockPrisma.post.findMany).not.toHaveBeenCalled()
1648
- })
1649
-
1650
- it('updateMany inherits the check through findMany, with no second copy', async () => {
1651
- const context = await getContext(config, mockPrisma, null)
1652
-
1653
- await expect(
1654
- context.db.user.updateMany({ where: { bogusKey: 'x' }, data: { name: 'y' } }),
1655
- ).rejects.toThrow(/bogusKey/)
1656
- expect(mockPrisma.user.findMany).not.toHaveBeenCalled()
1657
- expect(mockPrisma.user.update).not.toHaveBeenCalled()
1658
- })
1659
-
1660
- it('an ordinary read using only declared keys is unaffected', async () => {
1661
- const mockUsers = [{ id: '1', name: 'John', email: 'john@example.com' }]
1662
- mockPrisma.user.findMany.mockResolvedValue(mockUsers)
1663
-
1664
- const context = await getContext(config, mockPrisma, null)
1665
- const result = await context.db.user.findMany({
1666
- where: { name: 'John' },
1667
- orderBy: { name: 'asc' },
1668
- })
1669
-
1670
- expect(result).toEqual(mockUsers)
1671
- })
1672
- })
1673
-
1674
- describe('predicate-time field-read access (#915)', () => {
1675
- // The exact shape from the issue: a public `query` gate with one
1676
- // field-level `read` gate. Without this fix, `billingAddress`'s withheld
1677
- // value can be recovered one character at a time via `count()`, and its
1678
- // relative order leaked via `orderBy`, despite no session ever being
1679
- // allowed to READ it.
1680
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1681
- let orgPrisma: any
1682
- let orgConfig: OpenSaasConfig
1683
-
1684
- beforeEach(() => {
1685
- orgPrisma = {
1686
- organisation: { findMany: vi.fn(), count: vi.fn() },
1687
- }
1688
- orgConfig = {
1689
- db: { provider: 'postgresql', url: 'postgresql://localhost:5432/test' },
1690
- lists: {
1691
- Organisation: {
1692
- fields: {
1693
- name: { type: 'text' },
1694
- billingAddress: {
1695
- type: 'text',
1696
- access: { read: () => false },
1697
- },
1698
- },
1699
- access: { operation: { query: () => true } },
1700
- },
1701
- },
1702
- }
1703
- })
1704
-
1705
- it('denies a `where` filter naming a read-denied field, on both findMany and count', async () => {
1706
- const context = await getContext(orgConfig, orgPrisma, null)
1707
-
1708
- await expect(
1709
- context.db.organisation.findMany({
1710
- where: { billingAddress: { startsWith: '12 ' } },
1711
- }),
1712
- ).rejects.toThrow(/billingAddress/)
1713
- await expect(
1714
- context.db.organisation.count({
1715
- where: { billingAddress: { startsWith: '12 ' } },
1716
- }),
1717
- ).rejects.toThrow(/billingAddress/)
1718
-
1719
- expect(orgPrisma.organisation.findMany).not.toHaveBeenCalled()
1720
- expect(orgPrisma.organisation.count).not.toHaveBeenCalled()
1721
- })
1722
-
1723
- it('a count probe answers identically for a matching and a non-matching prefix (no oracle)', async () => {
1724
- // Before the fix, these two counts would differ (1 vs 0), letting the
1725
- // withheld value be recovered one character at a time. After the fix,
1726
- // both throw the SAME denial — there is no distinguishing signal left.
1727
- const context = await getContext(orgConfig, orgPrisma, null)
1728
-
1729
- const matching = context.db.organisation
1730
- .count({ where: { billingAddress: { startsWith: '12 ' } } })
1731
- .catch((err: Error) => err.message)
1732
- const nonMatching = context.db.organisation
1733
- .count({ where: { billingAddress: { startsWith: '99 ' } } })
1734
- .catch((err: Error) => err.message)
1735
-
1736
- expect(await matching).toEqual(await nonMatching)
1737
- expect(orgPrisma.organisation.count).not.toHaveBeenCalled()
1738
- })
1739
-
1740
- it('denies ordering by a read-denied field', async () => {
1741
- const context = await getContext(orgConfig, orgPrisma, null)
1742
-
1743
- await expect(
1744
- context.db.organisation.findMany({ orderBy: { billingAddress: 'asc' } }),
1745
- ).rejects.toThrow(/billingAddress/)
1746
- expect(orgPrisma.organisation.findMany).not.toHaveBeenCalled()
1747
- })
1748
-
1749
- it('checks keys nested inside logical operators (AND/OR/NOT)', async () => {
1750
- const context = await getContext(orgConfig, orgPrisma, null)
1751
-
1752
- await expect(
1753
- context.db.organisation.findMany({
1754
- where: { OR: [{ name: { contains: 'a' } }, { billingAddress: { contains: 'x' } }] },
1755
- }),
1756
- ).rejects.toThrow(/billingAddress/)
1757
- await expect(
1758
- context.db.organisation.findMany({
1759
- where: { AND: [{ NOT: { billingAddress: { contains: 'x' } } }] },
1760
- }),
1761
- ).rejects.toThrow(/billingAddress/)
1762
- })
1763
-
1764
- it('a row-dependent read rule resolves to a denial, not a skipped check', async () => {
1765
- // `item` cannot be evaluated before the query runs — there is no row
1766
- // yet — so a rule that depends on it (the shape `FieldAccess['read']`
1767
- // documents as the norm) must deny here even though, post-query, the
1768
- // very same rule might have allowed this session to read the field.
1769
- const rowDependentConfig: OpenSaasConfig = {
1770
- ...orgConfig,
1771
- lists: {
1772
- Organisation: {
1773
- ...orgConfig.lists.Organisation,
1774
- fields: {
1775
- ...orgConfig.lists.Organisation.fields,
1776
- billingAddress: {
1777
- type: 'text',
1778
- access: {
1779
- read: ({ item, session }: { item: { ownerId: string }; session: unknown }) =>
1780
- item.ownerId === (session as { userId?: string } | null)?.userId,
1781
- },
1782
- },
1783
- },
1784
- },
1785
- },
1786
- }
1787
-
1788
- const context = await getContext(rowDependentConfig, orgPrisma, { userId: 'user-1' })
1789
-
1790
- await expect(
1791
- context.db.organisation.findMany({
1792
- where: { billingAddress: { contains: 'x' } },
1793
- }),
1794
- ).rejects.toThrow(/billingAddress/)
1795
- expect(orgPrisma.organisation.findMany).not.toHaveBeenCalled()
1796
- })
1797
-
1798
- it('propagates InvalidFieldAccessResultError (#913), never folding it into a plain denial', async () => {
1799
- const filterReturningConfig: OpenSaasConfig = {
1800
- ...orgConfig,
1801
- lists: {
1802
- Organisation: {
1803
- ...orgConfig.lists.Organisation,
1804
- fields: {
1805
- ...orgConfig.lists.Organisation.fields,
1806
- billingAddress: {
1807
- type: 'text',
1808
- // Bypasses the FieldAccessControl boolean-only type on purpose —
1809
- // this is the exact misconfiguration #913 closed.
1810
- access: { read: (() => ({ ownerId: 'x' })) as unknown as () => boolean },
1811
- },
1812
- },
1813
- },
1814
- },
1815
- }
1816
-
1817
- const context = await getContext(filterReturningConfig, orgPrisma, null)
1818
-
1819
- await expect(
1820
- context.db.organisation.findMany({
1821
- where: { billingAddress: { contains: 'x' } },
1822
- }),
1823
- ).rejects.toThrow(InvalidFieldAccessResultError)
1824
- })
1825
-
1826
- it('leaves a readable field filterable and sortable (no regression)', async () => {
1827
- orgPrisma.organisation.findMany.mockResolvedValue([])
1828
-
1829
- const context = await getContext(orgConfig, orgPrisma, null)
1830
- await context.db.organisation.findMany({
1831
- where: { name: { contains: 'Acme' } },
1832
- orderBy: { name: 'asc' },
1833
- })
1834
-
1835
- expect(orgPrisma.organisation.findMany).toHaveBeenCalledWith(
1836
- expect.objectContaining({
1837
- where: { name: { contains: 'Acme' } },
1838
- orderBy: { name: 'asc' },
1839
- }),
1840
- )
1841
- })
1842
-
1843
- it('sudo bypasses the check entirely, matching #912', async () => {
1844
- orgPrisma.organisation.findMany.mockResolvedValue([])
1845
- orgPrisma.organisation.count.mockResolvedValue(3)
1846
-
1847
- const context = (await getContext(orgConfig, orgPrisma, null)).sudo()
1848
- await context.db.organisation.findMany({
1849
- where: { billingAddress: { startsWith: '12 ' } },
1850
- orderBy: { billingAddress: 'asc' },
1851
- })
1852
- await context.db.organisation.count({
1853
- where: { billingAddress: { startsWith: '12 ' } },
1854
- })
1855
-
1856
- expect(orgPrisma.organisation.findMany).toHaveBeenCalledWith(
1857
- expect.objectContaining({
1858
- where: { billingAddress: { startsWith: '12 ' } },
1859
- orderBy: { billingAddress: 'asc' },
1860
- }),
1861
- )
1862
- expect(orgPrisma.organisation.count).toHaveBeenCalledWith(
1863
- expect.objectContaining({ where: { billingAddress: { startsWith: '12 ' } } }),
1864
- )
1865
- })
1866
-
1867
- it('a caller with zero list access gets the ordinary silent denial, not a validation error naming the field (found in review of #925)', async () => {
1868
- // Operation-level `query` access is fully denied for this session.
1869
- // The #912/#915 where/orderBy validation must never run in that case
1870
- // — the thrown ValidationError names the offending key, which would
1871
- // let a caller with NO access to the list at all learn a field's
1872
- // name and its read-gating status purely from the error message.
1873
- // That is itself the kind of oracle #915 exists to close, just
1874
- // pointed at "does this field exist and is it read-gated" instead of
1875
- // "what is this field's value" — so a fully denied caller must see
1876
- // the SAME silent []/0 whether or not the where/orderBy names an
1877
- // undeclared or read-denied key.
1878
- const deniedConfig: OpenSaasConfig = {
1879
- ...orgConfig,
1880
- lists: {
1881
- Organisation: {
1882
- ...orgConfig.lists.Organisation,
1883
- access: { operation: { query: () => false } },
1884
- },
1885
- },
1886
- }
1887
- const context = await getContext(deniedConfig, orgPrisma, null)
1888
-
1889
- await expect(
1890
- context.db.organisation.findMany({
1891
- where: { billingAddress: { startsWith: '12 ' } },
1892
- }),
1893
- ).resolves.toEqual([])
1894
- await expect(
1895
- context.db.organisation.findMany({ where: { bogusKey: 'x' } }),
1896
- ).resolves.toEqual([])
1897
- await expect(
1898
- context.db.organisation.count({
1899
- where: { billingAddress: { startsWith: '12 ' } },
1900
- }),
1901
- ).resolves.toBe(0)
1902
- await expect(context.db.organisation.count({ where: { bogusKey: 'x' } })).resolves.toBe(0)
1903
-
1904
- expect(orgPrisma.organisation.findMany).not.toHaveBeenCalled()
1905
- expect(orgPrisma.organisation.count).not.toHaveBeenCalled()
1906
- })
1907
-
1908
- it('#915 itself does not recurse into a related list nested inside a relation filter, but #916 now does', async () => {
1909
- // #915 (`validateQueryFieldReadAccess`) checks whether THIS list's
1910
- // relationship field may be named at all — it does not by itself
1911
- // reject a field on the RELATED list reached through it. Once #916
1912
- // landed, that gap is closed by a SEPARATE pass
1913
- // (`buildAccessScopedWhere`) that scopes relation filters and applies
1914
- // the related list's own field-read access to keys nested inside
1915
- // them — so the read-denied `User.secret` field is still rejected
1916
- // overall, just not by #915's own top-level-only check.
1917
- const relPrisma = {
1918
- post: { findMany: vi.fn(), count: vi.fn() },
1919
- }
1920
- const relConfig: OpenSaasConfig = {
1921
- db: { provider: 'postgresql', url: 'postgresql://localhost:5432/test' },
1922
- lists: {
1923
- User: {
1924
- fields: {
1925
- name: { type: 'text' },
1926
- secret: { type: 'text', access: { read: () => false } },
1927
- },
1928
- access: { operation: { query: () => true } },
1929
- },
1930
- Post: {
1931
- fields: {
1932
- title: { type: 'text' },
1933
- author: { type: 'relationship', ref: 'User.posts' },
1934
- },
1935
- access: { operation: { query: () => true } },
1936
- },
1937
- },
1938
- }
1939
- relPrisma.post.findMany.mockResolvedValue([])
1940
-
1941
- const context = await getContext(relConfig, relPrisma, null)
1942
- // Names a field on the RELATED list (User.secret) nested inside the
1943
- // relation filter — not a key of Post itself, so #915's own check
1944
- // (which only inspects Post's own fields) does not deny it, but
1945
- // #916's relation-filter scoping (which checks the RELATED list's
1946
- // field-read access) now does.
1947
- await expect(
1948
- context.db.post.findMany({ where: { author: { is: { secret: { contains: 'x' } } } } }),
1949
- ).rejects.toThrow(/secret/)
1950
-
1951
- expect(relPrisma.post.findMany).not.toHaveBeenCalled()
1952
- })
1953
- })
1954
-
1955
- describe('relation filter access scoping (#916)', () => {
1956
- // The exact shape from the issue: a publicly-queryable Organisation,
1957
- // reachable Document/Membership/User lists each gated differently, and
1958
- // a two-hop chain (Organisation -> members -> user -> email) that lets
1959
- // an anonymous caller binary-search a field it could never read
1960
- // directly, unless the relation filter itself is scoped.
1961
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1962
- let orgPrisma: any
1963
- let orgConfig: OpenSaasConfig
1964
-
1965
- beforeEach(() => {
1966
- orgPrisma = {
1967
- organisation: { findMany: vi.fn(), count: vi.fn() },
1968
- }
1969
- orgConfig = {
1970
- db: { provider: 'postgresql', url: 'postgresql://localhost:5432/test' },
1971
- lists: {
1972
- Organisation: {
1973
- fields: {
1974
- name: { type: 'text' },
1975
- documents: { type: 'relationship', ref: 'Document.organisation', many: true },
1976
- members: { type: 'relationship', ref: 'Membership.organisation', many: true },
1977
- },
1978
- access: { operation: { query: () => true } },
1979
- },
1980
- // Membership-scoped: `query` denies everything for an anonymous
1981
- // session (no session means no membership filter can match).
1982
- Document: {
1983
- fields: {
1984
- organisation: { type: 'relationship', ref: 'Organisation.documents' },
1985
- billingAddress: { type: 'text' },
1986
- },
1987
- access: { operation: { query: () => false } },
1988
- },
1989
- Membership: {
1990
- fields: {
1991
- organisation: { type: 'relationship', ref: 'Organisation.members' },
1992
- user: { type: 'relationship', ref: 'User.memberships' },
1993
- },
1994
- // Readable by anyone — the hop itself isn't the leak, the
1995
- // identity list at the end of the chain is.
1996
- access: { operation: { query: () => true } },
1997
- },
1998
- User: {
1999
- fields: {
2000
- memberships: { type: 'relationship', ref: 'Membership.user', many: true },
2001
- email: { type: 'text' },
2002
- },
2003
- // Not queryable at all by an anonymous session.
2004
- access: { operation: { query: () => false } },
2005
- },
2006
- },
2007
- }
2008
- })
2009
-
2010
- it('denies a single-hop relation filter through a fully denied related list, on both findMany and count', async () => {
2011
- const context = await getContext(orgConfig, orgPrisma, null)
2012
-
2013
- await expect(
2014
- context.db.organisation.findMany({
2015
- where: { documents: { some: { billingAddress: { startsWith: '12 ' } } } },
2016
- }),
2017
- ).rejects.toThrow(/Document/)
2018
- await expect(
2019
- context.db.organisation.count({
2020
- where: { documents: { some: { billingAddress: { startsWith: '12 ' } } } },
2021
- }),
2022
- ).rejects.toThrow(/Document/)
2023
-
2024
- expect(orgPrisma.organisation.findMany).not.toHaveBeenCalled()
2025
- expect(orgPrisma.organisation.count).not.toHaveBeenCalled()
2026
- })
2027
-
2028
- it('a count probe through a denied relation answers identically for a matching and non-matching value (no oracle)', async () => {
2029
- // Before the fix these counts could differ (1 vs 0), letting a caller
2030
- // recover `billingAddress` one character at a time. After the fix
2031
- // both throw the SAME denial.
2032
- const context = await getContext(orgConfig, orgPrisma, null)
2033
-
2034
- const matching = context.db.organisation
2035
- .count({ where: { documents: { some: { billingAddress: { startsWith: '12 ' } } } } })
2036
- .catch((err: Error) => err.message)
2037
- const nonMatching = context.db.organisation
2038
- .count({ where: { documents: { some: { billingAddress: { startsWith: '99 ' } } } } })
2039
- .catch((err: Error) => err.message)
2040
-
2041
- expect(await matching).toEqual(await nonMatching)
2042
- expect(orgPrisma.organisation.count).not.toHaveBeenCalled()
2043
- })
2044
-
2045
- it('denies a two-hop chain reaching a denied identity list, the exact probe from the issue', async () => {
2046
- const context = await getContext(orgConfig, orgPrisma, null)
2047
-
2048
- await expect(
2049
- context.db.organisation.count({
2050
- where: {
2051
- members: { some: { user: { is: { email: { equals: 'ada@example.com' } } } } },
2052
- },
2053
- }),
2054
- ).rejects.toThrow(/User/)
2055
-
2056
- expect(orgPrisma.organisation.count).not.toHaveBeenCalled()
2057
- })
2058
-
2059
- it('a two-hop count probe answers identically for a real and a fabricated email (no identity-confirmation oracle)', async () => {
2060
- const context = await getContext(orgConfig, orgPrisma, null)
2061
-
2062
- const real = context.db.organisation
2063
- .count({
2064
- where: {
2065
- members: { some: { user: { is: { email: { equals: 'real@example.com' } } } } },
2066
- },
2067
- })
2068
- .catch((err: Error) => err.message)
2069
- const fabricated = context.db.organisation
2070
- .count({
2071
- where: {
2072
- members: { some: { user: { is: { email: { equals: 'nobody@example.com' } } } } },
2073
- },
2074
- })
2075
- .catch((err: Error) => err.message)
2076
-
2077
- expect(await real).toEqual(await fabricated)
2078
- expect(orgPrisma.organisation.count).not.toHaveBeenCalled()
2079
- })
2080
-
2081
- it("folds the related list's access filter into a relation filter rather than denying or passing it through unscoped", async () => {
2082
- orgPrisma.organisation.findMany.mockResolvedValue([])
2083
- const scopedConfig: OpenSaasConfig = {
2084
- ...orgConfig,
2085
- lists: {
2086
- ...orgConfig.lists,
2087
- Document: {
2088
- ...orgConfig.lists.Document,
2089
- // A filter, not a boolean: only this org's own published docs.
2090
- access: { operation: { query: () => ({ published: { equals: true } }) } },
2091
- },
2092
- },
2093
- }
2094
-
2095
- const context = await getContext(scopedConfig, orgPrisma, null)
2096
- await context.db.organisation.findMany({
2097
- where: { documents: { some: { billingAddress: { startsWith: '12 ' } } } },
2098
- })
2099
-
2100
- expect(orgPrisma.organisation.findMany).toHaveBeenCalledWith(
2101
- expect.objectContaining({
2102
- where: {
2103
- documents: {
2104
- some: {
2105
- AND: [{ published: { equals: true } }, { billingAddress: { startsWith: '12 ' } }],
2106
- },
2107
- },
2108
- },
2109
- }),
2110
- )
2111
- })
2112
-
2113
- it('leaves a relation filter through a fully readable related list unwrapped (no perturbation)', async () => {
2114
- orgPrisma.organisation.findMany.mockResolvedValue([])
2115
- const openConfig: OpenSaasConfig = {
2116
- ...orgConfig,
2117
- lists: {
2118
- ...orgConfig.lists,
2119
- Membership: {
2120
- ...orgConfig.lists.Membership,
2121
- access: { operation: { query: () => true } },
2122
- },
2123
- },
2124
- }
2125
- const context = await getContext(openConfig, orgPrisma, null)
2126
- const where = { members: { some: { organisation: { is: { name: { equals: 'Acme' } } } } } }
2127
-
2128
- await context.db.organisation.findMany({ where })
2129
-
2130
- expect(orgPrisma.organisation.findMany).toHaveBeenCalledWith(
2131
- expect.objectContaining({ where }),
2132
- )
2133
- })
2134
-
2135
- it('sudo bypasses relation-filter scoping entirely (#916 unaffected)', async () => {
2136
- orgPrisma.organisation.findMany.mockResolvedValue([])
2137
-
2138
- const context = (await getContext(orgConfig, orgPrisma, null)).sudo()
2139
- const where = { documents: { some: { billingAddress: { startsWith: '12 ' } } } }
2140
- await context.db.organisation.findMany({ where })
2141
-
2142
- expect(orgPrisma.organisation.findMany).toHaveBeenCalledWith(
2143
- expect.objectContaining({ where }),
2144
- )
2145
- })
2146
-
2147
- it('a caller with zero list access gets the ordinary silent denial, never the relation-filter error', async () => {
2148
- const deniedConfig: OpenSaasConfig = {
2149
- ...orgConfig,
2150
- lists: {
2151
- ...orgConfig.lists,
2152
- Organisation: {
2153
- ...orgConfig.lists.Organisation,
2154
- access: { operation: { query: () => false } },
2155
- },
2156
- },
2157
- }
2158
- const context = await getContext(deniedConfig, orgPrisma, null)
2159
-
2160
- await expect(
2161
- context.db.organisation.findMany({
2162
- where: { documents: { some: { billingAddress: { startsWith: '12 ' } } } },
2163
- }),
2164
- ).resolves.toEqual([])
2165
- await expect(
2166
- context.db.organisation.count({
2167
- where: { documents: { some: { billingAddress: { startsWith: '12 ' } } } },
2168
- }),
2169
- ).resolves.toBe(0)
2170
-
2171
- expect(orgPrisma.organisation.findMany).not.toHaveBeenCalled()
2172
- expect(orgPrisma.organisation.count).not.toHaveBeenCalled()
2173
- })
2174
- })
2175
-
2176
- describe('explicit include merges with access control (#566)', () => {
2177
- // Author has many Posts; Post.query access scopes to published posts only.
2178
- // A caller-supplied `include` must NOT bypass that per-relation filter.
2179
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2180
- let relPrisma: any
2181
- let relConfig: OpenSaasConfig
2182
-
2183
- beforeEach(() => {
2184
- relPrisma = {
2185
- author: {
2186
- findFirst: vi.fn(),
2187
- findUnique: vi.fn(),
2188
- findMany: vi.fn(),
2189
- },
2190
- post: {
2191
- findFirst: vi.fn(),
2192
- findUnique: vi.fn(),
2193
- findMany: vi.fn(),
2194
- },
2195
- comment: {
2196
- findFirst: vi.fn(),
2197
- findMany: vi.fn(),
2198
- },
2199
- }
2200
-
2201
- relConfig = {
2202
- db: { provider: 'postgresql', url: 'postgresql://localhost:5432/test' },
2203
- lists: {
2204
- Author: {
2205
- fields: {
2206
- name: { type: 'text' },
2207
- posts: { type: 'relationship', ref: 'Post.author', many: true },
2208
- },
2209
- access: { operation: { query: () => true } },
2210
- },
2211
- Post: {
2212
- fields: {
2213
- title: { type: 'text' },
2214
- author: { type: 'relationship', ref: 'Author.posts' },
2215
- comments: { type: 'relationship', ref: 'Comment.post', many: true },
2216
- },
2217
- access: {
2218
- // Row filter: only published posts are visible.
2219
- operation: { query: () => ({ status: { equals: 'published' } }) },
2220
- },
2221
- },
2222
- Comment: {
2223
- fields: {
2224
- body: { type: 'text' },
2225
- post: { type: 'relationship', ref: 'Post.comments' },
2226
- },
2227
- access: {
2228
- operation: { query: () => ({ approved: { equals: true } }) },
2229
- },
2230
- },
2231
- Secret: {
2232
- fields: {
2233
- value: { type: 'text' },
2234
- },
2235
- // Fully denied list.
2236
- access: { operation: { query: () => false } },
2237
- },
2238
- },
2239
- }
2240
- // Add a denied relation onto Author for the "drop denied relation" test.
2241
- relConfig.lists.Author.fields.secrets = {
2242
- type: 'relationship',
2243
- ref: 'Secret',
2244
- many: true,
2245
- }
2246
- })
2247
-
2248
- it('findMany: caller include {posts:true} applies the relation access where (not bare true)', async () => {
2249
- relPrisma.author.findMany.mockResolvedValue([{ id: 'a1', name: 'Jo', posts: [] }])
2250
-
2251
- const context = await getContext(relConfig, relPrisma, null)
2252
- await context.db.author.findMany({ include: { posts: true } })
2253
-
2254
- // The relation is fetched WITH the Post query-access where (NOT bare true),
2255
- // proving the row-level bypass is closed.
2256
- const call = relPrisma.author.findMany.mock.calls[0][0]
2257
- expect(call.include.posts).not.toBe(true)
2258
- expect(call.include.posts.where).toEqual({ status: { equals: 'published' } })
2259
- })
2260
-
2261
- it('findUnique: caller include {posts:true} applies the relation access where', async () => {
2262
- relPrisma.author.findFirst.mockResolvedValue({ id: 'a1', name: 'Jo', posts: [] })
2263
-
2264
- const context = await getContext(relConfig, relPrisma, null)
2265
- await context.db.author.findUnique({ where: { id: 'a1' }, include: { posts: true } })
2266
-
2267
- const call = relPrisma.author.findFirst.mock.calls[0][0]
2268
- expect(call.where).toEqual(expect.objectContaining({ id: 'a1' }))
2269
- expect(call.include.posts).not.toBe(true)
2270
- expect(call.include.posts.where).toEqual({ status: { equals: 'published' } })
2271
- })
2272
-
2273
- it('drops a relation whose query access is false when named in the caller include', async () => {
2274
- relPrisma.author.findMany.mockResolvedValue([{ id: 'a1', name: 'Jo' }])
2275
-
2276
- const context = await getContext(relConfig, relPrisma, null)
2277
- await context.db.author.findMany({ include: { secrets: true, posts: true } })
2278
-
2279
- const call = relPrisma.author.findMany.mock.calls[0][0]
2280
- // Denied `secrets` relation is dropped; allowed `posts` keeps its filter.
2281
- expect(call.include.secrets).toBeUndefined()
2282
- expect(call.include.posts.where).toEqual({ status: { equals: 'published' } })
2283
- })
2284
-
2285
- it('caller `_count` folds the relation access where into the select (#1087)', async () => {
2286
- relPrisma.author.findMany.mockResolvedValue([
2287
- { id: 'a1', name: 'Jo', _count: { posts: 3 } },
2288
- ])
2289
-
2290
- const context = await getContext(relConfig, relPrisma, null)
2291
- const result = await context.db.author.findMany({
2292
- include: { _count: { select: { posts: true } } },
2293
- })
2294
-
2295
- const call = relPrisma.author.findMany.mock.calls[0][0]
2296
- expect(call.include._count).toEqual({
2297
- select: { posts: { where: { status: { equals: 'published' } } } },
2298
- })
2299
- expect(result[0]._count).toEqual({ posts: 3 })
2300
- })
2301
-
2302
- it('caller `_count` on a fully-denied relation is omitted from the select and returns 0 (#1087)', async () => {
2303
- relPrisma.author.findMany.mockResolvedValue([{ id: 'a1', name: 'Jo' }])
2304
-
2305
- const context = await getContext(relConfig, relPrisma, null)
2306
- const result = await context.db.author.findMany({
2307
- include: { _count: { select: { posts: true, secrets: true } } },
2308
- })
2309
-
2310
- const call = relPrisma.author.findMany.mock.calls[0][0]
2311
- // The denied `Secret` list is never asked to be counted...
2312
- expect(call.include._count).toEqual({
2313
- select: { posts: { where: { status: { equals: 'published' } } } },
2314
- })
2315
- // ...but the caller still sees an explicit `0`, never an absent key —
2316
- // a count is session-relative, and `0` is what "no visible rows" means.
2317
- expect(result[0]._count).toEqual({ secrets: 0 })
2318
- })
2319
-
2320
- it('sudo `_count` is used as-is, unscoped (behaviour preserved)', async () => {
2321
- relPrisma.author.findMany.mockResolvedValue([
2322
- { id: 'a1', name: 'Jo', _count: { posts: 3, secrets: 7 } },
2323
- ])
2324
-
2325
- const context = await getContext(relConfig, relPrisma, null).sudo()
2326
- const result = await context.db.author.findMany({
2327
- include: { _count: { select: { posts: true, secrets: true } } },
2328
- })
2329
-
2330
- expect(relPrisma.author.findMany).toHaveBeenCalledWith(
2331
- expect.objectContaining({
2332
- include: { _count: { select: { posts: true, secrets: true } } },
2333
- }),
2334
- )
2335
- expect(result[0]._count).toEqual({ posts: 3, secrets: 7 })
2336
- })
2337
-
2338
- it('AND-combines a caller nested where with the relation access where', async () => {
2339
- relPrisma.author.findMany.mockResolvedValue([{ id: 'a1', name: 'Jo', posts: [] }])
2340
-
2341
- const context = await getContext(relConfig, relPrisma, null)
2342
- await context.db.author.findMany({
2343
- include: { posts: { where: { title: { contains: 'hello' } } } },
2344
- })
2345
-
2346
- const call = relPrisma.author.findMany.mock.calls[0][0]
2347
- // Both the access where and the caller where are applied via AND.
2348
- expect(call.include.posts.where).toEqual({
2349
- AND: [{ status: { equals: 'published' } }, { title: { contains: 'hello' } }],
2350
- })
2351
- })
2352
-
2353
- it('access-filters nested (2-level) caller includes at every level', async () => {
2354
- relPrisma.author.findMany.mockResolvedValue([{ id: 'a1', name: 'Jo', posts: [] }])
2355
-
2356
- const context = await getContext(relConfig, relPrisma, null)
2357
- await context.db.author.findMany({
2358
- include: { posts: { include: { comments: true } } },
2359
- })
2360
-
2361
- const call = relPrisma.author.findMany.mock.calls[0][0]
2362
- // Level 1 (posts) and level 2 (comments) both carry their access where.
2363
- expect(call.include.posts.where).toEqual({ status: { equals: 'published' } })
2364
- expect(call.include.posts.include.comments.where).toEqual({ approved: { equals: true } })
2365
- })
2366
-
2367
- it('sudo with explicit include returns the include unfiltered (behaviour preserved)', async () => {
2368
- relPrisma.author.findMany.mockResolvedValue([{ id: 'a1', name: 'Jo' }])
2369
-
2370
- const context = await getContext(relConfig, relPrisma, null).sudo()
2371
- await context.db.author.findMany({ include: { posts: true, secrets: true } })
2372
-
2373
- // Under sudo the caller include is used as-is: no filter, nothing dropped.
2374
- expect(relPrisma.author.findMany).toHaveBeenCalledWith(
2375
- expect.objectContaining({ include: { posts: true, secrets: true } }),
2376
- )
2377
- })
2378
-
2379
- it('query fragment path carries the access filter, same as the include: path (#1088)', async () => {
2380
- relPrisma.author.findMany.mockResolvedValue([{ id: 'a1', name: 'Jo', posts: [] }])
2381
-
2382
- const postsFragment = defineFragment<{ id: string; title: string }>()({
2383
- title: true,
2384
- } as const)
2385
- const fragment = defineFragment<{ id: string; name: string; posts: unknown }>()({
2386
- id: true,
2387
- name: true,
2388
- posts: postsFragment,
2389
- } as const)
2390
-
2391
- const context = await getContext(relConfig, relPrisma, null)
2392
- await context.db.author.findMany({ query: fragment })
2393
-
2394
- const call = relPrisma.author.findMany.mock.calls[0][0]
2395
- // The fragment-built include now runs through the same scoping walk as
2396
- // an explicit caller `include`, so `posts` carries Post's access where
2397
- // (matching the `include: { posts: true }` test above) instead of a
2398
- // bare, unfiltered `true`.
2399
- expect(call.include).toEqual({ posts: { where: { status: { equals: 'published' } } } })
2400
- })
2401
-
2402
- it('drops a relation whose query access is false when named in a query fragment', async () => {
2403
- relPrisma.author.findMany.mockResolvedValue([{ id: 'a1', name: 'Jo' }])
2404
-
2405
- const secretsFragment = defineFragment<{ id: string; value: string }>()({
2406
- value: true,
2407
- } as const)
2408
- const fragment = defineFragment<{ id: string; name: string; secrets: unknown }>()({
2409
- id: true,
2410
- name: true,
2411
- secrets: secretsFragment,
2412
- } as const)
2413
-
2414
- const context = await getContext(relConfig, relPrisma, null)
2415
- await context.db.author.findMany({ query: fragment })
2416
-
2417
- const call = relPrisma.author.findMany.mock.calls[0][0]
2418
- // `Secret`'s query access is `() => false` — the denied relation is
2419
- // dropped from the include entirely, same as the `include:` path.
2420
- expect(call.include.secrets).toBeUndefined()
2421
- })
2422
-
2423
- it('a fragment nesting past the depth cap raises the same depth error a caller include does', async () => {
2424
- const chainLength = READ_INCLUDE_MAX_DEPTH + 2
2425
- const chainConfig: OpenSaasConfig = {
2426
- db: { provider: 'postgresql', url: 'postgresql://localhost:5432/test' },
2427
- lists: {},
2428
- }
2429
- for (let i = 0; i < chainLength; i++) {
2430
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal config for unit test
2431
- const fields: Record<string, any> = { name: { type: 'text' } }
2432
- if (i < chainLength - 1) fields.next = { type: 'relationship', ref: `D${i + 1}.prev` }
2433
- if (i > 0) fields.prev = { type: 'relationship', ref: `D${i - 1}.next` }
2434
- chainConfig.lists[`D${i}`] = { fields, access: { operation: { query: () => true } } }
2435
- }
2436
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2437
- const chainPrisma: any = {}
2438
- for (let i = 0; i < chainLength; i++) {
2439
- chainPrisma[`d${i}`] = { findMany: vi.fn(), findFirst: vi.fn(), findUnique: vi.fn() }
2440
- }
2441
-
2442
- // A fragment selecting `next` recursively, `hops` levels deep.
2443
- function nestedFragmentFields(hops: number): Record<string, unknown> {
2444
- if (hops <= 0) return { name: true }
2445
- return {
2446
- name: true,
2447
- next: defineFragment<Record<string, unknown>>()(nestedFragmentFields(hops - 1)),
2448
- }
2449
- }
2450
- const deepFragment = defineFragment<Record<string, unknown>>()(
2451
- nestedFragmentFields(READ_INCLUDE_MAX_DEPTH + 1),
2452
- )
2453
-
2454
- const context = await getContext(chainConfig, chainPrisma, null)
2455
-
2456
- await expect(context.db.d0.findMany({ query: deepFragment })).rejects.toThrow(
2457
- AccessScopeDepthExceededError,
2458
- )
2459
- expect(chainPrisma.d0.findMany).not.toHaveBeenCalled()
2460
- })
2461
-
2462
- it('sudo query fragment reads stay unscoped (behaviour preserved)', async () => {
2463
- relPrisma.author.findMany.mockResolvedValue([{ id: 'a1', name: 'Jo' }])
2464
-
2465
- const secretsFragment = defineFragment<{ id: string; value: string }>()({
2466
- value: true,
2467
- } as const)
2468
- const fragment = defineFragment<{ id: string; name: string; secrets: unknown }>()({
2469
- id: true,
2470
- name: true,
2471
- secrets: secretsFragment,
2472
- } as const)
2473
-
2474
- const context = await getContext(relConfig, relPrisma, null).sudo()
2475
- await context.db.author.findMany({ query: fragment })
2476
-
2477
- // Under sudo, the fragment-built include is used as-is: the denied
2478
- // `Secret` relation is fetched unfiltered, matching sudo's existing
2479
- // include: behaviour.
2480
- expect(relPrisma.author.findMany).toHaveBeenCalledWith(
2481
- expect.objectContaining({ include: { secrets: true } }),
2482
- )
2483
- })
2484
-
2485
- it('a fragment read on a to-one relation nulls out a row its related list denies, matching include: (#974)', async () => {
2486
- // `Comment.post` is a to-one relation onto `Post`, whose query access
2487
- // is a row filter (`status: published`) rather than a plain boolean —
2488
- // Prisma can't carry that as a `where` on a to-one include, so it's
2489
- // resolved via the post-query existence check instead.
2490
- const postFragment = defineFragment<{ id: string; title: string }>()({
2491
- title: true,
2492
- } as const)
2493
- const fragment = defineFragment<{ id: string; body: string; post: unknown }>()({
2494
- id: true,
2495
- body: true,
2496
- post: postFragment,
2497
- } as const)
2498
-
2499
- relPrisma.comment.findMany.mockResolvedValue([
2500
- { id: 'c1', body: 'hi', post: { id: 'p1', title: 'Draft' } },
2501
- ])
2502
- // The batched existence check queries the raw Post model directly;
2503
- // an empty result means `p1` does not satisfy Post's access filter.
2504
- relPrisma.post.findMany.mockResolvedValue([])
2505
-
2506
- const context = await getContext(relConfig, relPrisma, null)
2507
- const result = await context.db.comment.findMany({ query: fragment })
2508
-
2509
- expect(result[0].post).toBeNull()
2510
- })
2511
-
2512
- it('a fragment read and an equivalent include: read produce the same access-scoped include', async () => {
2513
- relPrisma.author.findMany.mockResolvedValue([{ id: 'a1', name: 'Jo', posts: [] }])
2514
-
2515
- const postsFragment = defineFragment<{ id: string; title: string }>()({
2516
- title: true,
2517
- } as const)
2518
- const fragment = defineFragment<{ id: string; name: string; posts: unknown }>()({
2519
- id: true,
2520
- name: true,
2521
- posts: postsFragment,
2522
- } as const)
2523
-
2524
- const context = await getContext(relConfig, relPrisma, null)
2525
- await context.db.author.findMany({ query: fragment })
2526
- const fragmentInclude = relPrisma.author.findMany.mock.calls[0][0].include
2527
-
2528
- relPrisma.author.findMany.mockClear()
2529
- await context.db.author.findMany({ include: { posts: true } })
2530
- const callerInclude = relPrisma.author.findMany.mock.calls[0][0].include
2531
-
2532
- expect(fragmentInclude).toEqual(callerInclude)
2533
- })
2534
-
2535
- // Core new guarantee introduced by #852 / ADR-0026: naming one relation
2536
- // no longer walks (and access-checks) every other relationship of the
2537
- // list. Before this fix, `include: { posts: true }` would ALSO evaluate
2538
- // `Secret`'s query access (and, one hop further, `Comment`'s) even
2539
- // though the caller never named `secrets` — wasted access calls the
2540
- // caller never asked to pay for. Asserted directly on the access
2541
- // function, not just on the resulting include shape.
2542
- it('does not invoke query access on a relation the caller did not name (#852)', async () => {
2543
- const postQuerySpy = vi.fn(() => ({ status: { equals: 'published' } }))
2544
- const secretQuerySpy = vi.fn(() => false)
2545
- const spiedConfig: OpenSaasConfig = {
2546
- ...relConfig,
2547
- lists: {
2548
- ...relConfig.lists,
2549
- Post: { ...relConfig.lists.Post, access: { operation: { query: postQuerySpy } } },
2550
- Secret: { ...relConfig.lists.Secret, access: { operation: { query: secretQuerySpy } } },
2551
- },
2552
- }
2553
- relPrisma.author.findMany.mockResolvedValue([{ id: 'a1', name: 'Jo', posts: [] }])
2554
-
2555
- const context = await getContext(spiedConfig, relPrisma, null)
2556
- await context.db.author.findMany({ include: { posts: true } })
2557
-
2558
- expect(postQuerySpy).toHaveBeenCalledTimes(1)
2559
- expect(secretQuerySpy).not.toHaveBeenCalled()
2560
- })
2561
-
2562
- // Regression for issue #830: a read issued from inside a `resolveOutput`
2563
- // hook used to lose relation row scoping ENTIRELY — `buildIncludeWithAccessControl`
2564
- // returned a whole-object `undefined` for the inner read (any
2565
- // `_resolveOutputChain.length > 0`), which `mergeIncludeWithAccessControl`
2566
- // treated as "nothing to merge against" and passed the caller's include
2567
- // through completely unscoped. The fix scopes each immediate relation with
2568
- // its own access `where` while still not auto-EXPANDING into that
2569
- // relation's own nested relations (preserving the original loop-prevention
2570
- // — see the self-referential coverage in `access-filter.test.ts`).
2571
- describe('scopes (without expanding) a caller include used inside a resolveOutput hook (#830)', () => {
2572
- // Build an Author config with a virtual field whose resolveOutput issues a
2573
- // read WITH an explicit include. While that hook runs,
2574
- // _resolveOutputChain.length > 0.
2575
- function configWithResolveOutputProbe(
2576
- callerInclude: Record<string, unknown>,
2577
- capture: (include: unknown) => void,
2578
- ): OpenSaasConfig {
2579
- return {
2580
- ...relConfig,
2581
- lists: {
2582
- ...relConfig.lists,
2583
- Author: {
2584
- ...relConfig.lists.Author,
2585
- fields: {
2586
- ...relConfig.lists.Author.fields,
2587
- commentSummary: virtual({
2588
- type: 'string',
2589
- hooks: {
2590
- resolveOutput: async ({ context }) => {
2591
- await context.db.comment.findMany({ include: callerInclude })
2592
- capture(relPrisma.comment.findMany.mock.calls[0][0].include)
2593
- return 'summary'
2594
- },
2595
- },
2596
- }),
2597
- },
2598
- },
2599
- },
2600
- }
2601
- }
2602
-
2603
- it('findUnique inside a resolveOutput hook still fetches the relation, unscoped at the Prisma level (#974)', async () => {
2604
- let innerIncludeSeen: unknown
2605
- const hookConfig = configWithResolveOutputProbe({ post: true }, (include) => {
2606
- innerIncludeSeen = include
2607
- })
2608
-
2609
- relPrisma.author.findFirst.mockResolvedValue({ id: 'a1', name: 'Jo' })
2610
- relPrisma.comment.findMany.mockResolvedValue([{ id: 'c1', body: 'hi', post: null }])
2611
-
2612
- const context = await getContext(hookConfig, relPrisma, null)
2613
- await context.db.author.findUnique({ where: { id: 'a1' } })
2614
-
2615
- // `post` is still fetched (not dropped). It carries no `where` — Post
2616
- // is a to-one relation here, and Prisma rejects a `where` on a to-one
2617
- // include (#974); Post's own access filter is enforced afterward via
2618
- // a batched existence check instead (see access-filter.test.ts).
2619
- expect(innerIncludeSeen).toEqual({ post: true })
2620
- })
2621
-
2622
- it('findMany inside a resolveOutput hook scopes the relation but does not auto-expand its nested include', async () => {
2623
- let innerIncludeSeen: unknown
2624
- const hookConfig = configWithResolveOutputProbe(
2625
- { post: { include: { author: true } } },
2626
- (include) => {
2627
- innerIncludeSeen = include
2628
- },
2629
- )
2630
-
2631
- relPrisma.author.findMany.mockResolvedValue([{ id: 'a1', name: 'Jo' }])
2632
- relPrisma.comment.findMany.mockResolvedValue([{ id: 'c1', body: 'hi', post: null }])
2633
-
2634
- const context = await getContext(hookConfig, relPrisma, null)
2635
- await context.db.author.findMany()
2636
-
2637
- // The caller's own nested selection (`post.include.author`) is honoured
2638
- // as-is (access control does not auto-descend further here). `post`
2639
- // itself carries no `where` — see the findUnique test above (#974).
2640
- expect(innerIncludeSeen).toEqual({
2641
- post: { include: { author: true } },
2642
- })
2643
- })
2644
- })
2645
-
2646
- // Regression for issue #830: a caller `include` nested deeper than the
2647
- // Access Filter can scope used to be returned unscoped rather than
2648
- // denied. This exercises the fix end-to-end through `context.db`,
2649
- // matching the reproduction in the issue: a chain of lists deep enough
2650
- // to cross `READ_INCLUDE_MAX_DEPTH`, read as a non-privileged session.
2651
- describe('fail-closed at the read-include depth cap through context.db (#830)', () => {
2652
- function chainListConfig(count: number): OpenSaasConfig['lists'] {
2653
- const lists: OpenSaasConfig['lists'] = {}
2654
- for (let i = 0; i < count; i++) {
2655
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- minimal config for unit test
2656
- const fields: Record<string, any> = { name: { type: 'text' } }
2657
- if (i < count - 1) fields.next = { type: 'relationship', ref: `C${i + 1}.prev` }
2658
- if (i > 0) fields.prev = { type: 'relationship', ref: `C${i - 1}.next` }
2659
- lists[`C${i}`] = {
2660
- fields,
2661
- access: {
2662
- operation: { query: () => (i === 0 ? true : { ownerId: { equals: `C${i}` } }) },
2663
- },
2664
- }
2665
- }
2666
- return lists
2667
- }
2668
-
2669
- // A caller include selecting `next` `hops` more times, ending bare.
2670
- function nestedCallerInclude(hops: number): Record<string, unknown> {
2671
- if (hops <= 0) return true as unknown as Record<string, unknown>
2672
- return { include: { next: nestedCallerInclude(hops - 1) } }
2673
- }
2674
-
2675
- it('throws AccessScopeDepthExceededError for a caller include one hop past the cap', async () => {
2676
- const chainLength = READ_INCLUDE_MAX_DEPTH + 2
2677
- const chainConfig: OpenSaasConfig = {
2678
- db: { provider: 'postgresql', url: 'postgresql://localhost:5432/test' },
2679
- lists: chainListConfig(chainLength),
2680
- }
2681
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2682
- const chainPrisma: any = {}
2683
- for (let i = 0; i < chainLength; i++) {
2684
- chainPrisma[`c${i}`] = { findMany: vi.fn(), findFirst: vi.fn(), findUnique: vi.fn() }
2685
- }
2686
-
2687
- const context = await getContext(chainConfig, chainPrisma, null)
2688
-
2689
- await expect(
2690
- context.db.c0.findMany({
2691
- include: { next: nestedCallerInclude(READ_INCLUDE_MAX_DEPTH) },
2692
- }),
2693
- ).rejects.toThrow(AccessScopeDepthExceededError)
2694
-
2695
- // The database is never even queried — the denial happens before the
2696
- // Prisma call, not as a post-hoc filter on returned data.
2697
- expect(chainPrisma.c0.findMany).not.toHaveBeenCalled()
2698
- })
2699
-
2700
- it('still applies row-scoping at the deepest hop for the same include one hop shallower', async () => {
2701
- const chainLength = READ_INCLUDE_MAX_DEPTH + 1
2702
- const chainConfig: OpenSaasConfig = {
2703
- db: { provider: 'postgresql', url: 'postgresql://localhost:5432/test' },
2704
- lists: chainListConfig(chainLength),
2705
- }
2706
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2707
- const chainPrisma: any = {}
2708
- for (let i = 0; i < chainLength; i++) {
2709
- chainPrisma[`c${i}`] = { findMany: vi.fn(), findFirst: vi.fn(), findUnique: vi.fn() }
2710
- }
2711
-
2712
- // Every hop here is to-one (no `many: true`), so none of them can
2713
- // carry a `where` on the Prisma include (#974) — the chain comes
2714
- // back unscoped at the Prisma level, one nested object per hop, and
2715
- // row-scoping is enforced afterward via a batched existence check
2716
- // per hop instead.
2717
- let deepestItem: Record<string, unknown> = { id: `id${chainLength - 1}`, name: 'leaf' }
2718
- for (let i = chainLength - 2; i >= 0; i--) {
2719
- deepestItem = { id: `id${i}`, name: 'x', next: deepestItem }
2720
- }
2721
- chainPrisma.c0.findMany.mockResolvedValue([deepestItem])
2722
- for (let i = 1; i < chainLength; i++) {
2723
- chainPrisma[`c${i}`].findMany.mockResolvedValue([{ id: `id${i}` }])
2724
- }
2725
-
2726
- const context = await getContext(chainConfig, chainPrisma, null)
2727
-
2728
- await context.db.c0.findMany({
2729
- include: { next: nestedCallerInclude(READ_INCLUDE_MAX_DEPTH - 1) },
2730
- })
2731
-
2732
- // Walk the built include down to the last list — no hop carries a
2733
- // `where` (they are all to-one).
2734
- let entry = chainPrisma.c0.findMany.mock.calls[0][0].include.next
2735
- for (let i = 1; i < READ_INCLUDE_MAX_DEPTH; i++) {
2736
- expect(entry.where).toBeUndefined()
2737
- entry = entry.include.next
2738
- }
2739
- expect(entry.where).toBeUndefined()
2740
-
2741
- // The deepest hop's own existence check still carries that list's
2742
- // access filter — row scoping reaches all the way down, just not
2743
- // through the Prisma `include` itself.
2744
- expect(chainPrisma[`c${READ_INCLUDE_MAX_DEPTH}`].findMany).toHaveBeenCalledWith({
2745
- where: {
2746
- AND: [
2747
- { ownerId: { equals: `C${READ_INCLUDE_MAX_DEPTH}` } },
2748
- { id: { in: [`id${READ_INCLUDE_MAX_DEPTH}`] } },
2749
- ],
2750
- },
2751
- select: { id: true },
2752
- })
2753
- })
2754
- })
2755
-
2756
- // Regression for #628: a virtual field named in `include` used to be
2757
- // forwarded straight through to Prisma, which throws "Unknown field"
2758
- // because virtual fields have no database column. The runtime must
2759
- // strip virtual keys from the include payload while still computing
2760
- // the virtual value (via resolveOutput) and leaving real relationship
2761
- // includes — access-controlled or not — untouched.
2762
- describe('virtual fields named in include no longer reach Prisma (#628)', () => {
2763
- function configWithVirtualDisplayName(): OpenSaasConfig {
2764
- return {
2765
- ...relConfig,
2766
- lists: {
2767
- ...relConfig.lists,
2768
- Author: {
2769
- ...relConfig.lists.Author,
2770
- fields: {
2771
- ...relConfig.lists.Author.fields,
2772
- displayName: virtual({
2773
- type: 'string',
2774
- hooks: {
2775
- resolveOutput: ({ item }) => `Author: ${item.name}`,
2776
- },
2777
- }),
2778
- },
2779
- },
2780
- },
2781
- }
2782
- }
2783
-
2784
- it('findMany: strips the virtual key from the Prisma include but keeps the real relationship include, and computes the virtual value', async () => {
2785
- const vConfig = configWithVirtualDisplayName()
2786
- relPrisma.author.findMany.mockResolvedValue([{ id: 'a1', name: 'Jo', posts: [] }])
2787
-
2788
- const context = await getContext(vConfig, relPrisma, null)
2789
- const result = await context.db.author.findMany({
2790
- include: { displayName: true, posts: true },
2791
- })
2792
-
2793
- const call = relPrisma.author.findMany.mock.calls[0][0]
2794
- expect(call.include).not.toHaveProperty('displayName')
2795
- expect(call.include.posts).toBeDefined()
2796
- expect(result[0].displayName).toBe('Author: Jo')
2797
- })
2798
-
2799
- it('findUnique: strips the virtual key from the Prisma include but keeps the real relationship include, and computes the virtual value', async () => {
2800
- const vConfig = configWithVirtualDisplayName()
2801
- relPrisma.author.findFirst.mockResolvedValue({ id: 'a1', name: 'Jo', posts: [] })
2802
-
2803
- const context = await getContext(vConfig, relPrisma, null)
2804
- const result = await context.db.author.findUnique({
2805
- where: { id: 'a1' },
2806
- include: { displayName: true, posts: true },
2807
- })
2808
-
2809
- const call = relPrisma.author.findFirst.mock.calls[0][0]
2810
- expect(call.include).not.toHaveProperty('displayName')
2811
- expect(call.include.posts).toBeDefined()
2812
- expect(result.displayName).toBe('Author: Jo')
2813
- })
2814
-
2815
- it('the virtual value is populated even when omitted from include', async () => {
2816
- const vConfig = configWithVirtualDisplayName()
2817
- relPrisma.author.findFirst.mockResolvedValue({ id: 'a1', name: 'Jo' })
2818
-
2819
- const context = await getContext(vConfig, relPrisma, null)
2820
- const result = await context.db.author.findUnique({ where: { id: 'a1' } })
2821
-
2822
- expect(result.displayName).toBe('Author: Jo')
2823
- })
2824
-
2825
- it('sudo: the virtual key is stripped from the Prisma include even though it bypasses access control', async () => {
2826
- const vConfig = configWithVirtualDisplayName()
2827
- relPrisma.author.findMany.mockResolvedValue([{ id: 'a1', name: 'Jo' }])
2828
-
2829
- const context = await getContext(vConfig, relPrisma, null).sudo()
2830
- const result = await context.db.author.findMany({
2831
- include: { displayName: true, posts: true },
2832
- })
2833
-
2834
- const call = relPrisma.author.findMany.mock.calls[0][0]
2835
- expect(call.include).not.toHaveProperty('displayName')
2836
- // The real relationship is unaffected — sudo still passes it through as-is.
2837
- expect(call.include.posts).toBe(true)
2838
- expect(result[0].displayName).toBe('Author: Jo')
2839
- })
2840
-
2841
- it('read access control on the virtual field is still enforced (denied field is omitted)', async () => {
2842
- const vConfig = configWithVirtualDisplayName()
2843
- vConfig.lists.Author.fields.displayName = virtual({
2844
- type: 'string',
2845
- access: { read: () => false },
2846
- hooks: {
2847
- resolveOutput: ({ item }) => `Author: ${item.name}`,
2848
- },
2849
- })
2850
- relPrisma.author.findFirst.mockResolvedValue({ id: 'a1', name: 'Jo' })
2851
-
2852
- const context = await getContext(vConfig, relPrisma, null)
2853
- const result = await context.db.author.findUnique({
2854
- where: { id: 'a1' },
2855
- include: { displayName: true },
2856
- })
2857
-
2858
- expect(result).not.toHaveProperty('displayName')
2859
- })
2860
- })
2861
- })
2862
-
2863
- it('should delegate create to prisma with access control and hooks', async () => {
2864
- const mockUser = { id: '1', name: 'John', email: 'john@example.com' }
2865
- mockPrisma.user.create.mockResolvedValue(mockUser)
2866
-
2867
- const context = await getContext(config, mockPrisma, null)
2868
- const result = await context.db.user.create({
2869
- data: { name: 'John', email: 'john@example.com' },
2870
- })
2871
-
2872
- expect(mockPrisma.user.create).toHaveBeenCalled()
2873
- expect(result).toEqual(mockUser)
2874
- })
2875
-
2876
- it('should delegate update to prisma with access control and hooks', async () => {
2877
- const existingUser = { id: '1', name: 'John', email: 'john@example.com' }
2878
- const updatedUser = { id: '1', name: 'John Updated', email: 'john@example.com' }
2879
- mockPrisma.user.findUnique.mockResolvedValue(existingUser)
2880
- mockPrisma.user.update.mockResolvedValue(updatedUser)
2881
-
2882
- const context = await getContext(config, mockPrisma, null)
2883
- const result = await context.db.user.update({
2884
- where: { id: '1' },
2885
- data: { name: 'John Updated' },
2886
- })
2887
-
2888
- expect(mockPrisma.user.update).toHaveBeenCalled()
2889
- expect(result).toEqual(updatedUser)
2890
- })
2891
-
2892
- it('should delegate delete to prisma with access control and hooks', async () => {
2893
- const mockUser = { id: '1', name: 'John', email: 'john@example.com' }
2894
- mockPrisma.user.findUnique.mockResolvedValue(mockUser)
2895
- mockPrisma.user.delete.mockResolvedValue(mockUser)
2896
-
2897
- const context = await getContext(config, mockPrisma, null)
2898
- const result = await context.db.user.delete({ where: { id: '1' } })
2899
-
2900
- expect(mockPrisma.user.delete).toHaveBeenCalled()
2901
- expect(result).toEqual(mockUser)
2902
- })
2903
-
2904
- it('should delegate count to prisma with access control', async () => {
2905
- mockPrisma.user.count.mockResolvedValue(5)
2906
-
2907
- const context = await getContext(config, mockPrisma, null)
2908
- const result = await context.db.user.count()
2909
-
2910
- expect(mockPrisma.user.count).toHaveBeenCalled()
2911
- expect(result).toBe(5)
2912
- })
2913
-
2914
- it('should batch create items via createMany', async () => {
2915
- const mockUsers = [
2916
- { id: '1', name: 'John', email: 'john@example.com' },
2917
- { id: '2', name: 'Jane', email: 'jane@example.com' },
2918
- { id: '3', name: 'Bob', email: 'bob@example.com' },
2919
- ]
2920
-
2921
- // Mock create to return each user in sequence
2922
- mockPrisma.user.create
2923
- .mockResolvedValueOnce(mockUsers[0])
2924
- .mockResolvedValueOnce(mockUsers[1])
2925
- .mockResolvedValueOnce(mockUsers[2])
2926
-
2927
- const context = await getContext(config, mockPrisma, null)
2928
- const result = await context.db.user.createMany({
2929
- data: [
2930
- { name: 'John', email: 'john@example.com' },
2931
- { name: 'Jane', email: 'jane@example.com' },
2932
- { name: 'Bob', email: 'bob@example.com' },
2933
- ],
2934
- })
2935
-
2936
- // Should call create 3 times (once for each item)
2937
- expect(mockPrisma.user.create).toHaveBeenCalledTimes(3)
2938
- expect(result).toEqual(mockUsers)
2939
- })
2940
-
2941
- it('should batch update items via updateMany', async () => {
2942
- const mockUsers = [
2943
- { id: '1', name: 'John', email: 'john@example.com' },
2944
- { id: '2', name: 'Jane', email: 'jane@example.com' },
2945
- ]
2946
-
2947
- const updatedUsers = [
2948
- { id: '1', name: 'John Updated', email: 'john@example.com' },
2949
- { id: '2', name: 'Jane Updated', email: 'jane@example.com' },
2950
- ]
2951
-
2952
- // Mock findMany to return the users
2953
- mockPrisma.user.findMany.mockResolvedValue(mockUsers)
2954
-
2955
- // Mock findUnique for each update's access check
2956
- mockPrisma.user.findUnique
2957
- .mockResolvedValueOnce(mockUsers[0])
2958
- .mockResolvedValueOnce(mockUsers[1])
2959
-
2960
- // Mock update to return updated users
2961
- mockPrisma.user.update
2962
- .mockResolvedValueOnce(updatedUsers[0])
2963
- .mockResolvedValueOnce(updatedUsers[1])
2964
-
2965
- const context = await getContext(config, mockPrisma, null)
2966
- const result = await context.db.user.updateMany({
2967
- where: { id: { in: ['1', '2'] } },
2968
- data: { name: 'Updated' },
2969
- })
2970
-
2971
- // Should call findMany once to get records
2972
- expect(mockPrisma.user.findMany).toHaveBeenCalledWith({
2973
- where: { id: { in: ['1', '2'] } },
2974
- take: undefined,
2975
- skip: undefined,
2976
- include: undefined,
2977
- })
2978
-
2979
- // Should call update twice (once for each item)
2980
- expect(mockPrisma.user.update).toHaveBeenCalledTimes(2)
2981
- expect(result).toEqual(updatedUsers)
2982
- })
2983
-
2984
- it('should run hooks and access control for each item in createMany', async () => {
2985
- // Test that hooks are called for each item
2986
- const mockUsers = [
2987
- { id: '1', name: 'John', email: 'john@example.com' },
2988
- { id: '2', name: 'Jane', email: 'jane@example.com' },
2989
- ]
2990
-
2991
- mockPrisma.user.create.mockResolvedValueOnce(mockUsers[0]).mockResolvedValueOnce(mockUsers[1])
2992
-
2993
- // Config with hook
2994
- const configWithHook: OpenSaasConfig = {
2995
- ...config,
2996
- lists: {
2997
- ...config.lists,
2998
- User: {
2999
- ...config.lists.User,
3000
- hooks: {
3001
- resolveInput: vi.fn(async ({ resolvedData }) => resolvedData),
3002
- },
3003
- },
3004
- },
3005
- }
3006
-
3007
- const context = await getContext(configWithHook, mockPrisma, null)
3008
- await context.db.user.createMany({
3009
- data: [
3010
- { name: 'John', email: 'john@example.com' },
3011
- { name: 'Jane', email: 'jane@example.com' },
3012
- ],
3013
- })
3014
-
3015
- // Hook should be called twice (once for each item)
3016
- expect(configWithHook.lists.User.hooks?.resolveInput).toHaveBeenCalledTimes(2)
3017
- })
3018
-
3019
- it('should run hooks and access control for each item in updateMany', async () => {
3020
- const mockUsers = [
3021
- { id: '1', name: 'John', email: 'john@example.com' },
3022
- { id: '2', name: 'Jane', email: 'jane@example.com' },
3023
- ]
3024
-
3025
- const updatedUsers = [
3026
- { id: '1', name: 'John Updated', email: 'john@example.com' },
3027
- { id: '2', name: 'Jane Updated', email: 'jane@example.com' },
3028
- ]
3029
-
3030
- mockPrisma.user.findMany.mockResolvedValue(mockUsers)
3031
- mockPrisma.user.findUnique
3032
- .mockResolvedValueOnce(mockUsers[0])
3033
- .mockResolvedValueOnce(mockUsers[1])
3034
- mockPrisma.user.update
3035
- .mockResolvedValueOnce(updatedUsers[0])
3036
- .mockResolvedValueOnce(updatedUsers[1])
3037
-
3038
- // Config with hook
3039
- const configWithHook: OpenSaasConfig = {
3040
- ...config,
3041
- lists: {
3042
- ...config.lists,
3043
- User: {
3044
- ...config.lists.User,
3045
- hooks: {
3046
- resolveInput: vi.fn(async ({ resolvedData }) => resolvedData),
3047
- },
3048
- },
3049
- },
3050
- }
3051
-
3052
- const context = await getContext(configWithHook, mockPrisma, null)
3053
- await context.db.user.updateMany({
3054
- where: { id: { in: ['1', '2'] } },
3055
- data: { name: 'Updated' },
3056
- })
3057
-
3058
- // Hook should be called twice (once for each item)
3059
- expect(configWithHook.lists.User.hooks?.resolveInput).toHaveBeenCalledTimes(2)
3060
- })
3061
- })
3062
-
3063
- // `select` is not honoured by context.db reads — it is a visible no-op: the
3064
- // op warns (once per list+operation) and still returns the full, access-
3065
- // filtered result. Each test re-imports getContext via vi.resetModules() so
3066
- // the module-level warn-once cache starts empty.
3067
- describe('select no-op warning', () => {
3068
- let warnSpy: ReturnType<typeof vi.spyOn>
3069
- let freshGetContext: typeof getContext
3070
-
3071
- beforeEach(async () => {
3072
- vi.resetModules()
3073
- warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
3074
- const mod = await import('../src/context/index.js')
3075
- freshGetContext = mod.getContext
3076
- })
3077
-
3078
- afterEach(() => {
3079
- warnSpy.mockRestore()
3080
- })
3081
-
3082
- it('warns AND still returns the row when findUnique is passed a select', async () => {
3083
- const mockUser = { id: '1', name: 'John', email: 'john@example.com' }
3084
- mockPrisma.user.findFirst.mockResolvedValue(mockUser)
3085
-
3086
- const context = await freshGetContext(config, mockPrisma, null)
3087
- const result = await context.db.user.findUnique({
3088
- where: { id: '1' },
3089
- select: { name: true },
3090
- })
3091
-
3092
- expect(warnSpy).toHaveBeenCalledTimes(1)
3093
- expect(warnSpy.mock.calls[0][0]).toContain('`select` is ignored')
3094
- expect(warnSpy.mock.calls[0][0]).toContain('findUnique')
3095
- // Behaviour unchanged: the op still runs and returns the full row.
3096
- expect(mockPrisma.user.findFirst).toHaveBeenCalled()
3097
- expect(result).toEqual(mockUser)
3098
- })
3099
-
3100
- it('warns AND still returns the rows when findMany is passed a select', async () => {
3101
- const mockUsers = [
3102
- { id: '1', name: 'John' },
3103
- { id: '2', name: 'Jane' },
3104
- ]
3105
- mockPrisma.user.findMany.mockResolvedValue(mockUsers)
3106
-
3107
- const context = await freshGetContext(config, mockPrisma, null)
3108
- const result = await context.db.user.findMany({ select: { name: true } })
3109
-
3110
- expect(warnSpy).toHaveBeenCalledTimes(1)
3111
- expect(warnSpy.mock.calls[0][0]).toContain('`select` is ignored')
3112
- expect(warnSpy.mock.calls[0][0]).toContain('findMany')
3113
- expect(mockPrisma.user.findMany).toHaveBeenCalled()
3114
- expect(result).toEqual(mockUsers)
3115
- })
3116
-
3117
- it('warns only once per list+operation across repeated calls', async () => {
3118
- mockPrisma.user.findMany.mockResolvedValue([])
3119
-
3120
- const context = await freshGetContext(config, mockPrisma, null)
3121
- await context.db.user.findMany({ select: { name: true } })
3122
- await context.db.user.findMany({ select: { name: true } })
3123
- await context.db.user.findMany({ select: { email: true } })
3124
-
3125
- expect(warnSpy).toHaveBeenCalledTimes(1)
3126
- })
3127
-
3128
- it('does NOT warn for findUnique/findMany using only include or query', async () => {
3129
- const mockUser = { id: '1', name: 'John' }
3130
- mockPrisma.user.findFirst.mockResolvedValue(mockUser)
3131
- mockPrisma.user.findMany.mockResolvedValue([mockUser])
3132
-
3133
- const context = await freshGetContext(config, mockPrisma, null)
3134
- await context.db.user.findUnique({ where: { id: '1' }, include: { posts: true } })
3135
- await context.db.user.findMany({ include: { posts: true } })
3136
- await context.db.user.findMany()
3137
-
3138
- expect(warnSpy).not.toHaveBeenCalled()
3139
- })
3140
- })
3141
- })