permdock 0.25.0 → 0.26.0

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 (969) hide show
  1. package/README.md +1 -1
  2. package/dist/2020-bJfT8aIA.js +6760 -0
  3. package/dist/a2a/index.d.ts +5 -9
  4. package/dist/a2a/index.js +13 -15
  5. package/dist/adapter-context-lHq_i_77.js +28 -0
  6. package/dist/adoption-scan-b0_Xpab8.js +106 -0
  7. package/dist/agent/index.d.ts +2 -2
  8. package/dist/agent/index.js +1 -1
  9. package/dist/ai-sdk/index.d.ts +4 -6
  10. package/dist/ai-sdk/index.js +6 -7
  11. package/dist/annotate-doc-BCOCOrq_.js +214 -0
  12. package/dist/annotate-routes-BvSuEht3.js +75 -0
  13. package/dist/annotate-uZVGIRym.js +25 -0
  14. package/dist/app/index.d.ts +2 -103
  15. package/dist/app/index.js +1 -114
  16. package/dist/app-data-DbSPSPIl.js +62 -0
  17. package/dist/approval-header-BvszJE3l.js +25 -0
  18. package/dist/approval-normalize-Cpp8R0rY.js +190 -0
  19. package/dist/approval-prompt-C-vjNZyd.d.ts +57 -0
  20. package/dist/approval-prompt-Covyx_DB.js +60 -0
  21. package/dist/approval-required-B-R4Yw3J.js +5 -0
  22. package/dist/approvals/index.d.ts +5 -5
  23. package/dist/approvals/index.js +8 -8
  24. package/dist/approvals-7jHYXocE.js +1039 -0
  25. package/dist/approvers-BkY_ZfWl.js +76 -0
  26. package/dist/arazzo-DMmcumRx.js +76 -0
  27. package/dist/arazzo-Hxerfx3_.js +35 -0
  28. package/dist/args-0EWFk-4S.js +311 -0
  29. package/dist/astro/index.d.ts +6 -8
  30. package/dist/astro/index.js +3 -4
  31. package/dist/audience-DauhRBNg.js +54 -0
  32. package/dist/auth-WHKYWtnS.js +187 -0
  33. package/dist/authz-topic-D8x24Jv-.js +14 -0
  34. package/dist/authzen/index.d.ts +37 -22
  35. package/dist/authzen/index.js +69 -27
  36. package/dist/automation-CUcWz8uu.d.ts +122 -0
  37. package/dist/automation-CpPdFX91.js +157 -0
  38. package/dist/base-url--yJPQlIK.js +8 -0
  39. package/dist/better-auth/index.d.ts +2 -8
  40. package/dist/better-auth/index.js +10 -13
  41. package/dist/better-supabase/index.d.ts +141 -95
  42. package/dist/better-supabase/index.js +239 -794
  43. package/dist/better-supabase-DSbs4MtQ.js +201 -0
  44. package/dist/bind-B3MHrzw4.d.ts +56 -0
  45. package/dist/bind-up3QptTt.js +124 -0
  46. package/dist/body-W1_8r6Tw.js +9 -0
  47. package/dist/body-text-B-m3p-qY.js +55 -0
  48. package/dist/boundary--5Swp7sN.js +18 -0
  49. package/dist/boundary-DJqHADKu.d.ts +22 -0
  50. package/dist/budget-5LJ8kfZk.d.ts +12 -0
  51. package/dist/budget-BH81q2cj.js +19 -0
  52. package/dist/build-instance-hLKYe3-E.js +30 -0
  53. package/dist/canonical-json-BibZkXtE.js +28 -0
  54. package/dist/capability-CVt3lpVK.d.ts +128 -0
  55. package/dist/capability-_ZsyfYxU.js +204 -0
  56. package/dist/casbin-CYwbggCS.js +29 -0
  57. package/dist/casbin-Co1KcLWU.js +241 -0
  58. package/dist/casl-CrltbDPa.js +23 -0
  59. package/dist/casl-D7n7yE-h.js +307 -0
  60. package/dist/catalog/index.d.ts +6 -20
  61. package/dist/catalog/index.js +13 -15
  62. package/dist/catalog-B3MJShnZ.js +51 -0
  63. package/dist/catalog-CgK_L4Qf.js +1 -0
  64. package/dist/catalog-DyC3LKc7.js +130 -0
  65. package/dist/catalog-doc-Bp5khmCG.js +352 -0
  66. package/dist/catalog-fingerprint-DAWZARy6.js +31 -0
  67. package/dist/catalog-operations-dxuOZr4J.js +59 -0
  68. package/dist/catalog-path-bG0XxHMu.js +11 -0
  69. package/dist/challenge-CjwmjcuX.js +518 -0
  70. package/dist/chat/index.d.ts +1 -1
  71. package/dist/chat/index.js +10 -13
  72. package/dist/chat-sdk/index.d.ts +3 -11
  73. package/dist/chat-sdk/index.js +7 -11
  74. package/dist/checks-DSm45qH7.js +71 -0
  75. package/dist/claims-map-BGbpbvGD.js +15 -0
  76. package/dist/claims-map-CLKQWxJG.d.ts +33 -0
  77. package/dist/claims-size-DcjhvUv5.js +58 -0
  78. package/dist/claude-agent/index.d.ts +3 -5
  79. package/dist/claude-agent/index.js +4 -5
  80. package/dist/clerk/index.d.ts +4 -8
  81. package/dist/clerk/index.js +7 -8
  82. package/dist/cli/bin.js +6 -7
  83. package/dist/cli/generate/watch-worker.d.ts +20 -0
  84. package/dist/cli/generate/watch-worker.js +69 -0
  85. package/dist/cli/index.d.ts +11 -20
  86. package/dist/cli/index.js +8 -8
  87. package/dist/cli/plugins/app.d.ts +18 -0
  88. package/dist/cli/plugins/app.js +26 -0
  89. package/dist/cli/plugins/better-supabase.d.ts +10 -0
  90. package/dist/cli/plugins/better-supabase.js +18 -0
  91. package/dist/cli/plugins/openapi.d.ts +19 -0
  92. package/dist/cli/plugins/openapi.js +40 -0
  93. package/dist/cli/plugins/powersync.d.ts +7 -0
  94. package/dist/cli/plugins/powersync.js +29 -0
  95. package/dist/cli/plugins/rls.d.ts +8 -0
  96. package/dist/cli/plugins/rls.js +27 -0
  97. package/dist/cli/plugins/schemas.d.ts +13 -0
  98. package/dist/cli/plugins/schemas.js +23 -0
  99. package/dist/cli/plugins/scim.d.ts +10 -0
  100. package/dist/cli/plugins/scim.js +32 -0
  101. package/dist/cli/plugins/supabase-hook.d.ts +13 -0
  102. package/dist/cli/plugins/supabase-hook.js +40 -0
  103. package/dist/cli/plugins/supabase.d.ts +27 -0
  104. package/dist/cli/plugins/supabase.js +69 -0
  105. package/dist/cli/plugins/ui.d.ts +11 -0
  106. package/dist/cli/plugins/ui.js +19 -0
  107. package/dist/client-V95IvZsF.d.ts +43 -0
  108. package/dist/client-subject-v89t811z.d.ts +25 -0
  109. package/dist/clients-Bb_33pRE.js +22 -0
  110. package/dist/clients-DGcyFDCc.d.ts +10 -0
  111. package/dist/cloud/index.d.ts +8 -26
  112. package/dist/cloud/index.js +22 -28
  113. package/dist/cloud-BfEI9TLS.js +85 -0
  114. package/dist/codemod-DwH0IZ2x.js +2159 -0
  115. package/dist/codemod-p67ePW25.js +35 -0
  116. package/dist/collect-BJZsuBW4.js +535 -0
  117. package/dist/collect-CPvCXMQ-.js +1 -0
  118. package/dist/collect-CpGnmGpL.js +54 -0
  119. package/dist/command-9GAzSI7E.js +5 -0
  120. package/dist/compact-C4LFuqbW.js +28 -0
  121. package/dist/compare-dfHDj8kT.js +11 -0
  122. package/dist/compile/index.d.ts +2 -2
  123. package/dist/compile/index.js +1 -1
  124. package/dist/compile-BUKXrueE.js +685 -0
  125. package/dist/compile-Blrr5WWw.js +724 -0
  126. package/dist/compile-D8c1nFGy.d.ts +118 -0
  127. package/dist/completion-CfrZOGcB.js +150 -0
  128. package/dist/conditions-CkHgXoZB.js +385 -0
  129. package/dist/config-D6gh_xvs.js +25 -0
  130. package/dist/config-iyy90IOU.js +143 -0
  131. package/dist/config-report-BaHEBpt-.js +55 -0
  132. package/dist/config-shape-B6tdyBju.js +149 -0
  133. package/dist/connection-BnoSqYU1.js +196 -0
  134. package/dist/connector-schema-BSRMyq4M.js +433 -0
  135. package/dist/constants-PCJiir_3.js +19 -0
  136. package/dist/context-DmH-Eyvx.js +95 -0
  137. package/dist/convex/index.d.ts +5 -9
  138. package/dist/convex/index.js +7 -8
  139. package/dist/core-CnC47rSf.d.ts +200 -0
  140. package/dist/core-DKqrD_xW.js +338 -0
  141. package/dist/coverage-DL7JCZmb.d.ts +133 -0
  142. package/dist/coverage-nFSMjFxH.js +42 -0
  143. package/dist/create-BAMPoEga.js +133 -0
  144. package/dist/create-BsRcXm_m.d.ts +125 -0
  145. package/dist/create-D3oXoXxM.js +373 -0
  146. package/dist/create-DeQ5t8mZ.d.ts +124 -0
  147. package/dist/create-sGl1ccTp.d.ts +185 -0
  148. package/dist/credential-ke0KMQeB.js +430 -0
  149. package/dist/credentials-6ZWbJ-Re.js +72 -0
  150. package/dist/credentials-BfzdL5kv.d.ts +123 -0
  151. package/dist/credentials-DOeqknte.js +309 -0
  152. package/dist/decide-set-CgNcE6pP.js +99 -0
  153. package/dist/deciding-columns-BnglEKqU.js +143 -0
  154. package/dist/decision-hHv4UZgy.js +20 -0
  155. package/dist/define-permdock-BLpQ0m95.d.ts +99 -0
  156. package/dist/define-permdock-CIxHBykk.js +148 -0
  157. package/dist/definition-options-9o8Hdww3.js +370 -0
  158. package/dist/delegation-BaUNCrE_.js +263 -0
  159. package/dist/delegation-input-7Y5Rlja7.js +18 -0
  160. package/dist/delivery/index.d.ts +4 -4
  161. package/dist/delivery/index.js +5 -5
  162. package/dist/delivery-Cb3VCij5.js +555 -0
  163. package/dist/delivery-event-D5b9yhaJ.js +39 -0
  164. package/dist/denied-text-D6JJTDr3.d.ts +20 -0
  165. package/dist/describe-B7EosIKA.js +100 -0
  166. package/dist/describe-lAafaRQQ.d.ts +43 -0
  167. package/dist/device-f3JEnqa0.js +195 -0
  168. package/dist/diff-BIqibFnm.js +464 -0
  169. package/dist/diff-n6LONVwL.js +36 -0
  170. package/dist/digest-BaP8bQzX.js +26 -0
  171. package/dist/digest-BcIZRYvp.d.ts +17 -0
  172. package/dist/doctor-Bg12v-8M.js +4847 -0
  173. package/dist/doctor-DCsyH7YR.js +53 -0
  174. package/dist/drizzle/index.d.ts +5 -9
  175. package/dist/drizzle/index.js +5 -6
  176. package/dist/elysia/index.d.ts +6 -8
  177. package/dist/elysia/index.js +6 -7
  178. package/dist/env-hbYumkRp.js +7 -0
  179. package/dist/errors-DOSkVeTC.js +127 -0
  180. package/dist/errors-DUJ7wLlE.d.ts +137 -0
  181. package/dist/errors-Da88YLm5.js +26 -0
  182. package/dist/errors-DgLOqc6j.js +148 -0
  183. package/dist/errors-KngVdJT9.d.ts +12 -0
  184. package/dist/evaluate-D8SdfP3h.js +1948 -0
  185. package/dist/evaluations-BQkpE7hC.js +609 -0
  186. package/dist/evaluations-K9qglDP7.d.ts +36 -0
  187. package/dist/evaluator-Dlhn2d7D.js +2 -0
  188. package/dist/evaluator-eager-UuJK6NX_.js +8 -0
  189. package/dist/eve/index.d.ts +11 -10
  190. package/dist/eve/index.js +7 -8
  191. package/dist/event-time-ChIrhzy5.js +26 -0
  192. package/dist/execute-SN8_dlch.js +166 -0
  193. package/dist/express/index.d.ts +6 -8
  194. package/dist/express/index.js +6 -7
  195. package/dist/fastify/index.d.ts +5 -11
  196. package/dist/fastify/index.js +6 -8
  197. package/dist/fetch-adapter-gmTCu4FR.d.ts +32 -0
  198. package/dist/fetch-adapter-ovZdSvlT.js +124 -0
  199. package/dist/fields-6d1j-q3c.js +502 -0
  200. package/dist/fields-C0L2FoZk.js +25 -0
  201. package/dist/files-DAR51W3J.js +157 -0
  202. package/dist/files-DuV7wRim.js +139 -0
  203. package/dist/fixtures-Bm0G0A7H.js +79 -0
  204. package/dist/flags-C0e-BzGW.js +112 -0
  205. package/dist/freeze-DGfJq_j2.js +86 -0
  206. package/dist/from-snapshot-CCDF_ihX.js +173 -0
  207. package/dist/gen-B4GUqsfM.js +1160 -0
  208. package/dist/gen-BC66z5Fd.js +1 -0
  209. package/dist/gen-kind-Bahz_i3U.js +67 -0
  210. package/dist/gen-kind-DFQnQwFN.d.ts +13 -0
  211. package/dist/generate-5_kz2309.js +305 -0
  212. package/dist/generate-B-msjuaO.js +2339 -0
  213. package/dist/generate-CbtjKcjn.js +67 -0
  214. package/dist/generate-DhP0jQDR.js +97 -0
  215. package/dist/generate-options-BDgadlwe.js +1104 -0
  216. package/dist/grantee-BPUG6f0r.js +109 -0
  217. package/dist/grantee-conditions-Dob6QQAc.js +270 -0
  218. package/dist/grantee-match-CFQ-LRcL.js +147 -0
  219. package/dist/grants-BzjbUCdR.js +139 -0
  220. package/dist/graph-sql-Ds3nbevr.d.ts +27 -0
  221. package/dist/h3/index.d.ts +4 -6
  222. package/dist/h3/index.js +4 -5
  223. package/dist/headers-D1oRr-js.d.ts +8 -0
  224. package/dist/helpers-DSmj6SHi.js +533 -0
  225. package/dist/hono/index.d.ts +6 -8
  226. package/dist/hono/index.js +7 -8
  227. package/dist/hook-sql-BIR4fL7i.js +3412 -0
  228. package/dist/hosted-DMJKJPoc.js +361 -0
  229. package/dist/hosted-DUbuh0Td.d.ts +100 -0
  230. package/dist/http-BUIYu1Kc.d.ts +10 -0
  231. package/dist/http-BbX_Ou3_.js +48 -0
  232. package/dist/http-C9jDw_bZ.js +82 -0
  233. package/dist/http-dNltTpC8.js +71 -0
  234. package/dist/ids-0QDIxtxL.js +53 -0
  235. package/dist/import-BZi1tZxq.js +318 -0
  236. package/dist/import-BqoDHpFt.js +1158 -0
  237. package/dist/index-BXz-XXC3.d.ts +1108 -0
  238. package/dist/index-CVuc3E1O.d.ts +196 -0
  239. package/dist/index-Cq9N5B92.d.ts +506 -0
  240. package/dist/index-D8A1d_Tt.d.ts +214 -0
  241. package/dist/index-DegTwZxD.d.ts +93 -0
  242. package/dist/index-O0qbI8Ha.d.ts +221 -0
  243. package/dist/index.d.ts +24 -25
  244. package/dist/index.js +47 -46
  245. package/dist/init-9cqnSJWG.js +95 -0
  246. package/dist/init-K3tKOwf4.js +94 -0
  247. package/dist/instance-options-B4MD2wgl.d.ts +9 -0
  248. package/dist/instance-options-CLErhA76.js +23 -0
  249. package/dist/instance-snapshot-DdGOpSfN.js +716 -0
  250. package/dist/instant-Ih5riY_A.js +18 -0
  251. package/dist/interactive-only-BZu9rLpa.js +1567 -0
  252. package/dist/internals-D58TnmDB.js +19 -0
  253. package/dist/json-schema-SDkWXxhu.d.ts +38 -0
  254. package/dist/json-schema-jtX26ydD.js +148 -0
  255. package/dist/jwt/index.d.ts +6 -24
  256. package/dist/jwt/index.js +18 -26
  257. package/dist/kernel-Dn6pKMAF.js +423 -0
  258. package/dist/kysely/index.d.ts +5 -9
  259. package/dist/kysely/index.js +5 -6
  260. package/dist/lazy-provider-CydlnKkS.d.ts +4 -0
  261. package/dist/lazy-provider-DG5rMeqL.js +28 -0
  262. package/dist/limits-DpTxX6N4.js +166 -0
  263. package/dist/live-options-CIUmc-YQ.js +70 -0
  264. package/dist/load-BPzIqlGB.js +1 -0
  265. package/dist/load-CZnlAyZ8.js +98 -0
  266. package/dist/load-jose-CjzIBSKI.js +7 -0
  267. package/dist/login-C1I5KIsK.js +67 -0
  268. package/dist/login-CP0UxnLw.js +255 -0
  269. package/dist/lru-Cp-AEvpR.js +27 -0
  270. package/dist/manifest-B-8d2lhG.js +45 -0
  271. package/dist/manifest-CRHphHxo.d.ts +362 -0
  272. package/dist/manifest-DvS2IoXo.js +399 -0
  273. package/dist/manifest-json-DMaBWmcG.js +8 -0
  274. package/dist/manifest-schema-DJY5Q_pR.js +507 -0
  275. package/dist/map-claims-BKdnPwep.js +386 -0
  276. package/dist/map-error-DTi_JZT8.js +22 -0
  277. package/dist/markers-C-kThnKN.js +79 -0
  278. package/dist/may-use-Died1tNU.js +233 -0
  279. package/dist/mcp/index.d.ts +11 -21
  280. package/dist/mcp/index.js +56 -43
  281. package/dist/membership-filter-CSKH48eD.js +66 -0
  282. package/dist/migrate-CmTMk7rd.js +536 -0
  283. package/dist/model-B4EKVHMK.js +188 -0
  284. package/dist/module-values-Ddx0GLaJ.js +106 -0
  285. package/dist/nest/index.d.ts +7 -13
  286. package/dist/nest/index.js +12 -15
  287. package/dist/next/client.d.ts +1 -3
  288. package/dist/next/client.js +2 -3
  289. package/dist/next/index.d.ts +36 -16
  290. package/dist/next/index.js +161 -31
  291. package/dist/next/plugin.d.ts +1 -3
  292. package/dist/next/plugin.js +3 -4
  293. package/dist/node/index.d.ts +6 -8
  294. package/dist/node/index.js +4 -5
  295. package/dist/oauth-security-C8fjzFRF.js +25 -0
  296. package/dist/ocsf-DKRQc6uv.js +135 -0
  297. package/dist/openai/index.d.ts +5 -7
  298. package/dist/openai/index.js +5 -6
  299. package/dist/openapi/index.d.ts +4 -16
  300. package/dist/openapi/index.js +4 -3
  301. package/dist/openapi-BHqqNSoG.js +95 -0
  302. package/dist/openapi-BT5XY7HY.js +260 -0
  303. package/dist/openapi-D2dmyWZK.js +411 -0
  304. package/dist/openapi-document-Ca5yAjc6.js +35 -0
  305. package/dist/operation-findings-D5Uo-dcm.js +35 -0
  306. package/dist/operation-risks-BD-j14dj.js +12 -0
  307. package/dist/operations-B0yO77Zz.js +290 -0
  308. package/dist/operations-BS8ExH5A.d.ts +58 -0
  309. package/dist/operations-De3F7tlf.js +88 -0
  310. package/dist/optional-CaQWp9HA.js +46 -0
  311. package/dist/orpc/index.d.ts +8 -12
  312. package/dist/orpc/index.js +10 -12
  313. package/dist/otel/index.d.ts +3 -5
  314. package/dist/otel/index.js +5 -7
  315. package/dist/output-djxu62oH.js +244 -0
  316. package/dist/output-files-C5LFnQa4.js +1 -0
  317. package/dist/output-files-DNid6TBl.js +197 -0
  318. package/dist/ownership-BO0sI5FB.js +558 -0
  319. package/dist/parse-local-manifest-BGLWVchi.d.ts +8 -0
  320. package/dist/parse-local-manifest-CfMjZAFi.js +67 -0
  321. package/dist/parse-nfHSt1Wy.js +149 -0
  322. package/dist/parse-request-IEEzVFM8.js +24 -0
  323. package/dist/parse-sink-events-B6nZx41L.js +125 -0
  324. package/dist/paths-CeS_gpHf.js +44 -0
  325. package/dist/pdp/index.d.ts +3 -9
  326. package/dist/pdp/index.js +22 -18
  327. package/dist/peer-BWTpSLs2.js +1 -0
  328. package/dist/peer-D77JpXe-.js +978 -0
  329. package/dist/perf-token-dFGVP14-.js +155 -0
  330. package/dist/permdock-BueSeg7X.js +1514 -0
  331. package/dist/permdock-Dz3yzWrp.d.ts +853 -0
  332. package/dist/permission-registry-DMYRZVcn.js +413 -0
  333. package/dist/permissions-CQW3cr2S.js +17 -0
  334. package/dist/permissions-DWULToSb.d.ts +52 -0
  335. package/dist/permissions-ijDw4sO1.js +144 -0
  336. package/dist/pg-CA651850.js +59 -0
  337. package/dist/pins-CXXkVEiD.js +14 -0
  338. package/dist/pipeline-CXuwijr2.js +307 -0
  339. package/dist/pkce-DdsRBK7n.js +20 -0
  340. package/dist/plugin-DGmbeXwA.d.ts +221 -0
  341. package/dist/plugin-MQVfUBUS.js +93 -0
  342. package/dist/plugin-outputs-BE2YCiMj.js +28 -0
  343. package/dist/policy-BhSUlHRr.js +37 -0
  344. package/dist/policy-C-Lzp3Zh.d.ts +18 -0
  345. package/dist/policy-DFD2J5o_.js +476 -0
  346. package/dist/policy-bundle-97xaDULc.js +82 -0
  347. package/dist/policy-from-catalog-YKaTeaco.js +452 -0
  348. package/dist/policy-module-Bp4HvsRg.js +107 -0
  349. package/dist/policy-types-93NwI8iI.d.ts +2855 -0
  350. package/dist/postgres-store-CYFvw98w.js +1023 -0
  351. package/dist/postgrest-DyrYo_XT.d.ts +138 -0
  352. package/dist/powersync-CN7IQIKk.js +40 -0
  353. package/dist/powersync-DdDLP02A.js +1630 -0
  354. package/dist/powersync-m9uYgCFF.js +1 -0
  355. package/dist/preset/index.d.ts +0 -12
  356. package/dist/preset/index.js +1 -1
  357. package/dist/preset-BcFDaeqd.js +1849 -0
  358. package/dist/principal-source-BIcukkB3.js +102 -0
  359. package/dist/prisma/index.d.ts +4 -12
  360. package/dist/prisma/index.js +10 -14
  361. package/dist/problem-BZB7zPC7.js +202 -0
  362. package/dist/problem-details-EJHcvYCz.js +154 -0
  363. package/dist/problem-types-81BEw0IN.js +7 -0
  364. package/dist/prompt-CSXHcJxy.js +931 -0
  365. package/dist/protected-action-BMb0ftEu.js +241 -0
  366. package/dist/protected-action-D6T3eJyW.d.ts +73 -0
  367. package/dist/protected-action-DiXulRVj.js +78 -0
  368. package/dist/provider-BnnFjtWI.js +893 -0
  369. package/dist/provider-ClD4rfgT.js +11 -0
  370. package/dist/provider-CydlnKkS.d.ts +4 -0
  371. package/dist/provider-store-atQUfsVO.js +51 -0
  372. package/dist/provider-with-CSw4mBDU.js +70 -0
  373. package/dist/public-api-DIMZmzWi.js +5579 -0
  374. package/dist/pull-9oQvY18T.js +252 -0
  375. package/dist/pull-jvJPMQhP.js +1 -0
  376. package/dist/push-Cb7PqXdO.js +158 -0
  377. package/dist/pushed-policy-pH-EFWyx.d.ts +61 -0
  378. package/dist/pushed-policy-rpB6k77P.js +240 -0
  379. package/dist/quote-BKrTBbcH.js +36 -0
  380. package/dist/rbac-B-49toAp.js +90 -0
  381. package/dist/react/index.d.ts +10 -9
  382. package/dist/react/index.js +8 -7
  383. package/dist/react/lazy.d.ts +10 -12
  384. package/dist/react/lazy.js +8 -35
  385. package/dist/react/provider-client-lazy.d.ts +2 -0
  386. package/dist/react/provider-client-lazy.js +2 -0
  387. package/dist/react/provider-client.d.ts +1 -1
  388. package/dist/react/provider-client.js +1 -1
  389. package/dist/react-native/index.d.ts +12 -30
  390. package/dist/react-native/index.js +31 -41
  391. package/dist/read-memberships-BkePIa1F.js +63 -0
  392. package/dist/refresh-on-C1zIMtJr.d.ts +47 -0
  393. package/dist/refresh-online-CYGZNo6V.js +19 -0
  394. package/dist/refresh-online-vtUfV6dk.d.ts +10 -0
  395. package/dist/refs-Cix9Zjis.js +103 -0
  396. package/dist/relation-walk-BlWy9gBK.js +188 -0
  397. package/dist/relations-CIgB5KPJ.js +162 -0
  398. package/dist/replay-ClGIMp5p.d.ts +3 -0
  399. package/dist/replay-X2m6moK1.js +28 -0
  400. package/dist/request-context-CVJodWx8.js +70 -0
  401. package/dist/request-context-E3-ps-H_.d.ts +3 -0
  402. package/dist/request-schema-DzEoR310.js +155 -0
  403. package/dist/resend/index.d.ts +4 -10
  404. package/dist/resend/index.js +14 -17
  405. package/dist/resolve-names-Cmg6SPAa.js +266 -0
  406. package/dist/resolver-kdZ4HrpC.js +404 -0
  407. package/dist/resource-ref-BiQtFK-I.js +19 -0
  408. package/dist/resource-relations-Ck5sjYQR.js +251 -0
  409. package/dist/retire-BNiXnbBR.js +248 -0
  410. package/dist/revocations-3jyzniOz.js +26 -0
  411. package/dist/revocations-ku_f2d2y.d.ts +24 -0
  412. package/dist/rls-BrsMogAP.js +321 -0
  413. package/dist/rls-Cv1V8YfI.js +946 -0
  414. package/dist/rls-files-Bj446vbj.js +114 -0
  415. package/dist/rls-options-Dpj_pEyU.d.ts +26 -0
  416. package/dist/role-builder-DhsGEVq-.js +501 -0
  417. package/dist/role-grants-Bk6ZsaS0.js +46 -0
  418. package/dist/roles-B29psCem.js +29 -0
  419. package/dist/rolldown-runtime-B8NLbhFH.js +3 -0
  420. package/dist/row-conditions-DwIJocfQ.js +27 -0
  421. package/dist/row-pair-CxEhErJU.js +33 -0
  422. package/dist/rpc-B-4IZOiU.js +111 -0
  423. package/dist/rpc-DjgxFbjK.d.ts +18 -0
  424. package/dist/run-DX4D6S6V.js +726 -0
  425. package/dist/run-decqEKNa.js +1 -0
  426. package/dist/run-ticket-D6T39Xdi.js +370 -0
  427. package/dist/run-ticket-DXwrko2J.d.ts +157 -0
  428. package/dist/runtime-Cl6xSbEq.js +13 -0
  429. package/dist/saas-DzjKUQr5.js +1218 -0
  430. package/dist/scan-Cj7PQLrS.js +28 -0
  431. package/dist/schema-BeY3croo.js +403 -0
  432. package/dist/schema-CJPvTfeN.js +133 -0
  433. package/dist/scim/index.d.ts +2 -2
  434. package/dist/scim/index.js +2 -2
  435. package/dist/scim-B9QyJ23q.js +1046 -0
  436. package/dist/scopes-B-KX9EI8.js +238 -0
  437. package/dist/seed-sql-CjF7u0aX.js +60 -0
  438. package/dist/seeds/index.d.ts +2 -0
  439. package/dist/seeds/index.js +1 -0
  440. package/dist/seeds-BDTG7xl-.js +53 -0
  441. package/dist/seeds-uG196Ev4.d.ts +73 -0
  442. package/dist/server/index.d.ts +13 -13
  443. package/dist/server/index.js +14 -14
  444. package/dist/server-Co9CYGqk.js +146 -0
  445. package/dist/server-types-BrHOGAYx.d.ts +318 -0
  446. package/dist/sha256-DFsnyVPo.js +157 -0
  447. package/dist/shared-BOsJIQf4.js +124 -0
  448. package/dist/shared-BdF5DJDQ.js +330 -0
  449. package/dist/signals-a1NxAP0X.js +31 -0
  450. package/dist/sink-BD34OS8T.d.ts +247 -0
  451. package/dist/sink-Bgvf9lIz.js +966 -0
  452. package/dist/size-DF7xQ-nH.js +95 -0
  453. package/dist/skills-B5bc6JIA.js +50 -0
  454. package/dist/skills-Cr1C0b9D.js +202 -0
  455. package/dist/snapshot-DckMnHk8.js +352 -0
  456. package/dist/snapshot-cache-DTTEfmxv.js +69 -0
  457. package/dist/snapshot-cache-DoP3avLl.d.ts +68 -0
  458. package/dist/snapshot-compact-CwAop_6C.js +119 -0
  459. package/dist/snapshot-empty-DZ6sZ83n.js +17 -0
  460. package/dist/snapshot-evaluate-9RGy7J3N.js +552 -0
  461. package/dist/snapshot-reads-D775amTL.js +65 -0
  462. package/dist/snapshot-size-D-pCR8x0.js +139 -0
  463. package/dist/snapshot-size-DU7CvpMt.js +1 -0
  464. package/dist/solid/index.d.ts +18 -20
  465. package/dist/solid/index.js +15 -19
  466. package/dist/solid-start/index.d.ts +6 -8
  467. package/dist/solid-start/index.js +4 -5
  468. package/dist/sources-BbSUNmFX.js +10 -0
  469. package/dist/sources-DnjJPGfb.js +657 -0
  470. package/dist/sources-NQio1yFq.d.ts +727 -0
  471. package/dist/sql-BYYNi1lu.d.ts +8 -0
  472. package/dist/sql-T4GaBh9X.js +93 -0
  473. package/dist/src-D6_T4zd7.js +1811 -0
  474. package/dist/ssf/index.d.ts +3 -3
  475. package/dist/ssf/index.js +20 -31
  476. package/dist/standard-webhooks-B3MQihcP.d.ts +86 -0
  477. package/dist/standard-webhooks-BtIkXclH.js +227 -0
  478. package/dist/storage-BhGDhsXm.js +131 -0
  479. package/dist/store-AH8bmaxW.js +377 -0
  480. package/dist/store-core-eqG8jijs.d.ts +306 -0
  481. package/dist/store-options-C8x39AHa.js +1034 -0
  482. package/dist/stores-4DOaL4ZP.d.ts +58 -0
  483. package/dist/stores-DoA7ACkz.js +127 -0
  484. package/dist/stream-DdF94h7T.js +73 -0
  485. package/dist/style-CQDaLJtP.js +24 -0
  486. package/dist/style-Crf-90o6.js +1 -0
  487. package/dist/subject-DkxY-AhF.js +23 -0
  488. package/dist/subject-cache-BZeSj4Xf.d.ts +156 -0
  489. package/dist/subject-settings-BO-frcYx.js +147 -0
  490. package/dist/subject-settings-C9F1sU1d.d.ts +48 -0
  491. package/dist/supabase/client.d.ts +1 -1
  492. package/dist/supabase/client.js +2 -3
  493. package/dist/supabase/index.d.ts +77 -24
  494. package/dist/supabase/index.js +9 -8
  495. package/dist/supabase/middleware.d.ts +27 -9
  496. package/dist/supabase/middleware.js +51 -21
  497. package/dist/supabase-BG1HPdQU.js +30 -0
  498. package/dist/supabase-BI5ZhzLl.js +792 -0
  499. package/dist/supabase-config-mXcggV5I.js +890 -0
  500. package/dist/supabase-hook-hd9abKy4.js +2 -0
  501. package/dist/supabase-hook-tdR45aXY.js +405 -0
  502. package/dist/supabase-outcome-CMLuLW-V.js +9 -0
  503. package/dist/supautils-DXzJ2E2Q.js +96 -0
  504. package/dist/support-session-B8xrW28B.js +157 -0
  505. package/dist/svelte/index.d.ts +8 -10
  506. package/dist/svelte/index.js +12 -15
  507. package/dist/svelte/runtime.d.ts +4 -6
  508. package/dist/svelte/runtime.js +4 -4
  509. package/dist/svelte/source.d.ts +8 -10
  510. package/dist/svelte/source.js +6 -7
  511. package/dist/sveltekit/index.d.ts +6 -8
  512. package/dist/sveltekit/index.js +3 -4
  513. package/dist/tables-CRTCBuFi.js +3240 -0
  514. package/dist/tanstack-start/index.d.ts +6 -8
  515. package/dist/tanstack-start/index.js +3 -4
  516. package/dist/target-BGpxgKsN.js +50 -0
  517. package/dist/tenancy-B5Xxt9Sc.js +223 -0
  518. package/dist/terminal/index.d.ts +6 -16
  519. package/dist/terminal/index.js +18 -23
  520. package/dist/testing/core.d.ts +1 -1
  521. package/dist/testing/core.js +1 -1
  522. package/dist/testing/fixtures/index.d.ts +12 -10
  523. package/dist/testing/fixtures/index.js +48 -25
  524. package/dist/testing/index.d.ts +85 -85
  525. package/dist/testing/index.js +226 -115
  526. package/dist/testing/saas/index.d.ts +5 -15
  527. package/dist/testing/saas/index.js +2 -2
  528. package/dist/testing/saas/permissions.d.ts +1 -1
  529. package/dist/testing/saas/permissions.js +1 -1
  530. package/dist/text-D704xHVl.js +7 -0
  531. package/dist/text-diff-CsglY49A.js +440 -0
  532. package/dist/thenable-BxMy2v8w.js +39 -0
  533. package/dist/time-r0CKBm57.js +94 -0
  534. package/dist/timeout-nOqLpU2I.js +7 -0
  535. package/dist/token-BgswTQzt.d.ts +9 -0
  536. package/dist/token-CSljQqzA.js +76 -0
  537. package/dist/tool-refusal-DzCSbjp8.js +43 -0
  538. package/dist/trpc/index.d.ts +7 -9
  539. package/dist/trpc/index.js +7 -8
  540. package/dist/type-helpers-DHCQEPj8.d.ts +47 -0
  541. package/dist/types-3pRMqcvw.d.ts +84 -0
  542. package/dist/types-BFtFaI1W.d.ts +66 -0
  543. package/dist/types-BdNdMix7.d.ts +263 -0
  544. package/dist/types-C7QtRn3n.d.ts +66 -0
  545. package/dist/types-CVCRFYY_.d.ts +102 -0
  546. package/dist/types-CWmBZtQN.d.ts +274 -0
  547. package/dist/types-Cakw89Wx.d.ts +372 -0
  548. package/dist/types-D3tjoLwT.d.ts +124 -0
  549. package/dist/types-D8VXQxKL.d.ts +1231 -0
  550. package/dist/types-DFZKovb3.js +77 -0
  551. package/dist/types-DONLJQjY.d.ts +134 -0
  552. package/dist/types-OzSal_K_.d.ts +178 -0
  553. package/dist/types-XSfi6ihL.d.ts +65 -0
  554. package/dist/unplugin/index.d.ts +1 -3
  555. package/dist/unplugin/index.js +3 -4
  556. package/dist/usage-B-E747wO.js +31 -0
  557. package/dist/usage-B7nx0_aa.js +761 -0
  558. package/dist/usage-rqQ9ViXv.js +1 -0
  559. package/dist/validation-error-BAO1W1yk.d.ts +27 -0
  560. package/dist/validation-error-CgDOA6VS.js +35 -0
  561. package/dist/validity-YNEEm2MZ.js +56 -0
  562. package/dist/verifier-BIYkGcJc.js +530 -0
  563. package/dist/verify-9HObfifg.js +1102 -0
  564. package/dist/version-CU6e2wxV.js +7 -0
  565. package/dist/version-D-jWyJb9.js +46 -0
  566. package/dist/version-DcZCjWXb.js +1 -0
  567. package/dist/version-cache-BXkl7-Fz.js +462 -0
  568. package/dist/views-Dpr1uB16.js +164 -0
  569. package/dist/vocabulary-CE2k7s1a.js +157 -0
  570. package/dist/vocabulary-FYgI_NoI.d.ts +400 -0
  571. package/dist/vue/index.d.ts +18 -20
  572. package/dist/vue/index.js +13 -18
  573. package/dist/waiter-DKdFHKVZ.js +66 -0
  574. package/dist/waiter-hYLJXA7r.d.ts +37 -0
  575. package/dist/watch-BecZtEdU.js +155 -0
  576. package/dist/watch-CiN6WU9k.js +221 -0
  577. package/dist/watch-NAUnUXph.js +1 -0
  578. package/dist/webmcp/index.d.ts +2 -6
  579. package/dist/webmcp/index.js +8 -9
  580. package/dist/who-can-rUSZfLvI.js +366 -0
  581. package/dist/wire-delegation-DC5Cyec4.js +35 -0
  582. package/dist/wire-denial-BcRQnA7p.js +26 -0
  583. package/dist/workflow/index.d.ts +3 -3
  584. package/dist/workflow/index.js +12 -14
  585. package/dist/workflow-sdk/index.d.ts +6 -8
  586. package/dist/workflow-sdk/index.js +2 -3
  587. package/dist/wrap-CsfsaJhd.js +32 -0
  588. package/dist/wrap-D-KvhzaC.d.ts +16 -0
  589. package/package.json +83 -39
  590. package/schemas/catalog-v2.json +665 -0
  591. package/schemas/cli-commands-v1.json +1 -1
  592. package/schemas/cli-result-v2.json +163 -0
  593. package/schemas/cloud-api-v1.json +1 -1
  594. package/schemas/snapshot-v1.json +26 -0
  595. package/schemas/supabase-claims-v1.json +5 -1
  596. package/schemas/supabase-manifest-v1.json +11 -2
  597. package/skills/permdock/SKILL.md +1 -1
  598. package/skills/permdock-data/references/queries-and-rls.md +2 -1
  599. package/skills/permdock-wire/references/adapters.md +5 -3
  600. package/dist/2020-CJbO8Bvz.js +0 -6773
  601. package/dist/active-tenant-DVee32-T.js +0 -39
  602. package/dist/adapter-context-OHikyRqV.js +0 -29
  603. package/dist/adoption-scan-DhZejKH8.js +0 -107
  604. package/dist/app-J9PE1LNm.js +0 -24
  605. package/dist/app-data-UNNm07jV.js +0 -63
  606. package/dist/approval-header-8QV6MU4H.js +0 -26
  607. package/dist/approval-normalize-KfhzpD93.js +0 -196
  608. package/dist/approval-policies-BiXMlYBu.d.ts +0 -138
  609. package/dist/approval-prompt-B8hQY69x.js +0 -61
  610. package/dist/approval-prompt-j5PTItiy.d.ts +0 -59
  611. package/dist/approval-required-TzNB9oQA.js +0 -6
  612. package/dist/approvals-BfzI8Foe.js +0 -1048
  613. package/dist/approvers-BaNwKYgd.js +0 -77
  614. package/dist/arazzo-2_9pOddr.js +0 -77
  615. package/dist/arazzo-BDDzHgwW.js +0 -36
  616. package/dist/args-iafbHiXn.js +0 -311
  617. package/dist/audience-DLoopY4q.js +0 -55
  618. package/dist/auth-BxXHxWRy.js +0 -189
  619. package/dist/authz-topic-Dbc-HDOS.js +0 -15
  620. package/dist/automation-BueW05db.js +0 -158
  621. package/dist/automation-_iGeP54L.d.ts +0 -124
  622. package/dist/base-url-BQbddZO5.js +0 -9
  623. package/dist/better-supabase-DF8f8oly.js +0 -194
  624. package/dist/bind-CTj4dHc1.d.ts +0 -58
  625. package/dist/bind-LQ6zbARV.js +0 -125
  626. package/dist/body-Cy9S8zhw.js +0 -10
  627. package/dist/body-text-DQhcmqdY.js +0 -56
  628. package/dist/boundary-BV3O1eud.js +0 -19
  629. package/dist/boundary-C9ck-3uK.d.ts +0 -24
  630. package/dist/budget-BBCPDOGP.js +0 -14
  631. package/dist/budget-CNLsV2SL.d.ts +0 -14
  632. package/dist/build-instance-Bq8wkJ4i.js +0 -31
  633. package/dist/canonical-json-DwilZ1iB.js +0 -29
  634. package/dist/capability-CenWwTMR.js +0 -205
  635. package/dist/capability-DqCyFGip.d.ts +0 -130
  636. package/dist/casbin-BspH3-6_.js +0 -30
  637. package/dist/casbin-XFqehd6I.js +0 -242
  638. package/dist/casl-CjBVJj8R.js +0 -24
  639. package/dist/casl-CkBssiB1.js +0 -308
  640. package/dist/catalog-B1MAmRQI.js +0 -131
  641. package/dist/catalog-BCVIH7kq.js +0 -1
  642. package/dist/catalog-CaZoXBD8.js +0 -52
  643. package/dist/catalog-doc-DnQDviXY.js +0 -353
  644. package/dist/catalog-fingerprint-e6aCWosn.js +0 -157
  645. package/dist/catalog-operations-Do1eD-Rt.js +0 -60
  646. package/dist/catalog-path-CnI0XTFK.js +0 -12
  647. package/dist/challenge-DKJpP-5P.js +0 -521
  648. package/dist/checks-fyDOhcz0.js +0 -72
  649. package/dist/claims-map-CKkoAAYF.js +0 -16
  650. package/dist/claims-map-D1Pb5oRq.d.ts +0 -35
  651. package/dist/client-JK504UCq.d.ts +0 -45
  652. package/dist/clients-C_NOET3z.d.ts +0 -12
  653. package/dist/clients-DYr3U86j.js +0 -23
  654. package/dist/cloud-CUvR7okV.js +0 -86
  655. package/dist/codemod-iwXnO0fg.js +0 -2800
  656. package/dist/codemod-uZsk1b6T.js +0 -36
  657. package/dist/collect-BG-SXFQv.js +0 -537
  658. package/dist/collect-CxPJRjoc.js +0 -55
  659. package/dist/collect-ZLgHgujd.js +0 -1
  660. package/dist/command-L8EstFNm.js +0 -6
  661. package/dist/compact-CAf557ZB.js +0 -29
  662. package/dist/compare-DTfyUunF.js +0 -12
  663. package/dist/compile-Cvru58id.js +0 -661
  664. package/dist/compile-Dh9pW_Co.d.ts +0 -120
  665. package/dist/completion-DenWMczI.js +0 -152
  666. package/dist/config-CoUYTCCu.js +0 -26
  667. package/dist/config-DC7aiuhP.js +0 -116
  668. package/dist/config-report-C5D1rPiF.js +0 -56
  669. package/dist/config-shape-ChhsuGSV.js +0 -147
  670. package/dist/connection-zoAgwdsD.js +0 -197
  671. package/dist/connector-schema-CYLQNMYq.js +0 -434
  672. package/dist/constants-DcJABbLW.js +0 -20
  673. package/dist/context-BXM0MDB0.js +0 -95
  674. package/dist/core-BTJlqWsv.js +0 -341
  675. package/dist/core-BhZEo5Le.d.ts +0 -206
  676. package/dist/coverage-BuGlwUms.d.ts +0 -135
  677. package/dist/coverage-CGu_Kovx.js +0 -261
  678. package/dist/create--q7-j0hX.d.ts +0 -127
  679. package/dist/create-C5IQw_-i.d.ts +0 -191
  680. package/dist/create-CYj0cjTu.d.ts +0 -128
  681. package/dist/create-D7D94oNh.js +0 -376
  682. package/dist/create-DaddhCIg.js +0 -134
  683. package/dist/credential-BMsbcaeP.js +0 -431
  684. package/dist/credentials-BZU7Twpt.js +0 -310
  685. package/dist/credentials-Bq-Xa7Vq.d.ts +0 -125
  686. package/dist/credentials-dkycUsY3.js +0 -74
  687. package/dist/decide-set-DXEPepY1.js +0 -100
  688. package/dist/deciding-columns-NB4wcyBf.js +0 -134
  689. package/dist/decision-CaG5_eNJ.js +0 -21
  690. package/dist/delegation-CrdqnesZ.js +0 -262
  691. package/dist/delegation-input-DcXhiMkf.js +0 -19
  692. package/dist/delivery-BupfvJIV.js +0 -560
  693. package/dist/delivery-event-JioK5YbS.js +0 -40
  694. package/dist/denied-text-B6s29jcf.d.ts +0 -22
  695. package/dist/describe-BZAlPHxT.js +0 -101
  696. package/dist/describe-DwcoWMLB.d.ts +0 -45
  697. package/dist/device-BkSynWdg.js +0 -196
  698. package/dist/diff-BnYHpRSI.js +0 -466
  699. package/dist/diff-H75YU6Q-.js +0 -37
  700. package/dist/digest-8Yx2CchM.d.ts +0 -19
  701. package/dist/digest-BI-6aa6d.js +0 -27
  702. package/dist/doctor-CF9TXVkX.js +0 -3560
  703. package/dist/doctor-DreyO1At.js +0 -54
  704. package/dist/env-DJZrPjRi.js +0 -8
  705. package/dist/errors-BDUwg2qC.js +0 -27
  706. package/dist/errors-BhRkoNS7.js +0 -145
  707. package/dist/errors-CHwoRRpB.d.ts +0 -14
  708. package/dist/errors-D_SnqcRn.d.ts +0 -141
  709. package/dist/errors-ynga1EQy.js +0 -128
  710. package/dist/evaluate-BQ2nWOki.js +0 -1905
  711. package/dist/evaluations-BVtY66lF.d.ts +0 -38
  712. package/dist/evaluations-Bj5xw0EM.js +0 -612
  713. package/dist/evaluator-CDl2YUd_.js +0 -2
  714. package/dist/evaluator-eager-CULtQ8t6.js +0 -9
  715. package/dist/event-time-BGy48400.js +0 -27
  716. package/dist/fetch-adapter-BJ76IZZg.d.ts +0 -34
  717. package/dist/fetch-adapter-CXeBg4CH.js +0 -124
  718. package/dist/fields-D9PIYlJy.js +0 -504
  719. package/dist/fields-DlKwZYiy.js +0 -26
  720. package/dist/files-BSjrtIHw.js +0 -141
  721. package/dist/files-CfiRtQ-m.js +0 -140
  722. package/dist/fixtures-BVZc7OCF.js +0 -80
  723. package/dist/flags-BlmpmXoY.js +0 -86
  724. package/dist/freeze-jjan0lCv.js +0 -63
  725. package/dist/from-snapshot-FdVXG_QZ.js +0 -159
  726. package/dist/gen-BU5glz2Q.js +0 -827
  727. package/dist/gen-C75KIBdA.js +0 -58
  728. package/dist/generate-BqkZq8Dr.js +0 -165
  729. package/dist/generate-CezbCaTI.js +0 -275
  730. package/dist/grantee-OG4klcNr.js +0 -110
  731. package/dist/grantee-conditions-Dzprappv.js +0 -271
  732. package/dist/grantee-match-CPQ9zV-H.js +0 -148
  733. package/dist/graph-sql-BwFC4Qjs.d.ts +0 -29
  734. package/dist/headers-B9jQxjtW.d.ts +0 -10
  735. package/dist/helpers-CO2hDpBU.js +0 -537
  736. package/dist/hosted-CQW_YNx7.js +0 -362
  737. package/dist/hosted-D5StFpKa.d.ts +0 -102
  738. package/dist/http-B_LphE5Y.d.ts +0 -12
  739. package/dist/http-DH94eh6f.js +0 -72
  740. package/dist/http-DKLXrFGk.js +0 -83
  741. package/dist/http-dptLQzPP.js +0 -49
  742. package/dist/ids-DzhJaCUj.js +0 -55
  743. package/dist/import-B34PyXgL.js +0 -5950
  744. package/dist/import-BYYXmHvP.js +0 -1143
  745. package/dist/index-B1-tE0Kx.d.ts +0 -1159
  746. package/dist/index-BwSEp_O5.d.ts +0 -210
  747. package/dist/index-CB_eM-qx.d.ts +0 -101
  748. package/dist/index-CvcE9mYP.d.ts +0 -234
  749. package/dist/index-D7sMtTf6.d.ts +0 -542
  750. package/dist/index-d7f0hNss.d.ts +0 -233
  751. package/dist/init-C-nzibt_.js +0 -96
  752. package/dist/init-C1Bj0BFA.js +0 -95
  753. package/dist/instance-options-DhQVCuhT.d.ts +0 -11
  754. package/dist/instance-options-URVwqpMW.js +0 -24
  755. package/dist/instance-snapshot-DyG_5ASl.js +0 -693
  756. package/dist/instant-DK3Iz83e.js +0 -19
  757. package/dist/internals-B3IgHrvo.js +0 -20
  758. package/dist/json-schema-BPGa-RjQ.js +0 -149
  759. package/dist/json-schema-BfXgnRNT.d.ts +0 -40
  760. package/dist/kernel-D9AxUqmz.js +0 -427
  761. package/dist/limits-CAhpRrhk.js +0 -167
  762. package/dist/live-options-BBIT68le.js +0 -73
  763. package/dist/load-C4p4VgwR.js +0 -99
  764. package/dist/load-DiBUJx77.js +0 -1
  765. package/dist/load-jose-DZ4dnjri.js +0 -8
  766. package/dist/login-Cm_ebe5M.js +0 -68
  767. package/dist/login-DjuUQqqK.js +0 -257
  768. package/dist/lru-8q4WZjBV.js +0 -28
  769. package/dist/manifest-9KSrH_1h.js +0 -401
  770. package/dist/manifest-BoCYBbQL.js +0 -46
  771. package/dist/manifest-C6eFl3Vo.d.ts +0 -349
  772. package/dist/manifest-json-CAGzls-C.js +0 -9
  773. package/dist/manifest-schema-svAkgqMc.js +0 -501
  774. package/dist/map-claims-CAa_bQt9.js +0 -387
  775. package/dist/map-error-BCdb2Nrp.js +0 -23
  776. package/dist/markers-BeHZ4x9Q.js +0 -80
  777. package/dist/may-use-WDhFPqGG.js +0 -125
  778. package/dist/membership-filter-BWnfRQzo.js +0 -68
  779. package/dist/migrate-DVsxeE0y.js +0 -537
  780. package/dist/module-values-CdaVwrab.js +0 -107
  781. package/dist/oauth-security-X7Em8DbH.js +0 -26
  782. package/dist/ocsf-TcjRBgIs.js +0 -136
  783. package/dist/openapi-C2WGtmFa.js +0 -137
  784. package/dist/openapi-Cc-aS9xC.js +0 -416
  785. package/dist/openapi-DvTtFkwY.js +0 -256
  786. package/dist/operation-findings-CVwJHEu_.js +0 -36
  787. package/dist/operation-risks-BKOcTv8J.js +0 -13
  788. package/dist/operations-BMPx7HyO.d.ts +0 -62
  789. package/dist/operations-Bm9HFecz.js +0 -89
  790. package/dist/optional-8TKc-0j4.js +0 -47
  791. package/dist/output-CuJfGWo6.js +0 -96
  792. package/dist/output-files-BYscrQl-.js +0 -1
  793. package/dist/output-files-CM0BnH05.js +0 -150
  794. package/dist/ownership-C_5eZ6N2.js +0 -1062
  795. package/dist/parse-CORUNcCo.js +0 -151
  796. package/dist/parse-local-manifest-Ce2N-Opr.js +0 -69
  797. package/dist/parse-local-manifest-w_ksIkB9.d.ts +0 -10
  798. package/dist/parse-request-DOBVaeiQ.js +0 -25
  799. package/dist/paths-CUvURzHp.js +0 -45
  800. package/dist/peer-BuK9F53f.js +0 -982
  801. package/dist/peer-n-swIV4H.js +0 -1
  802. package/dist/permdock-B3zE16To.js +0 -1203
  803. package/dist/permdock-DV3opaI3.d.ts +0 -674
  804. package/dist/permission-registry-B8tYxPIt.js +0 -398
  805. package/dist/permissions-BaoLxy66.js +0 -18
  806. package/dist/permissions-D-M48hW-.js +0 -146
  807. package/dist/permissions-DriWkV7q.d.ts +0 -54
  808. package/dist/pg-Ddxsd5ZB.js +0 -60
  809. package/dist/pins-nqarl3oE.js +0 -15
  810. package/dist/pkce-CnmmYqUZ.js +0 -21
  811. package/dist/policy-DIHfTqm6.d.ts +0 -20
  812. package/dist/policy-DnNOTENd.js +0 -430
  813. package/dist/policy-from-catalog-Z0hvSffr.js +0 -454
  814. package/dist/policy-module-xym9fnSq.js +0 -95
  815. package/dist/policy-types-DU389Elz.d.ts +0 -2809
  816. package/dist/postgres-store-DcyrPS-r.js +0 -1028
  817. package/dist/postgrest-3dE9SGx9.d.ts +0 -124
  818. package/dist/powersync-BO1ty3Mf.js +0 -1
  819. package/dist/powersync-Bqy5Un2J.js +0 -1532
  820. package/dist/powersync-CCQAqiOo.js +0 -62
  821. package/dist/preset-Bn5Z54cH.js +0 -1858
  822. package/dist/principal-source-C6N60GtM.js +0 -103
  823. package/dist/problem-CPB8kqk7.js +0 -203
  824. package/dist/problem-details-CLDgX1KV.js +0 -156
  825. package/dist/problem-types-DSsRfONQ.js +0 -8
  826. package/dist/prompt-D1Gj1W4Y.js +0 -938
  827. package/dist/protected-action-CjSUoPGx.d.ts +0 -76
  828. package/dist/protected-action-D41o5LvP.js +0 -244
  829. package/dist/protected-action-OpOxtTsN.js +0 -80
  830. package/dist/provider-Bzzux0TR.js +0 -12
  831. package/dist/provider-D1jsNJ85.d.ts +0 -6
  832. package/dist/provider-store-tIAwP4aW.js +0 -52
  833. package/dist/provider-with-Do28DhxP.js +0 -69
  834. package/dist/pull-CYdd5HzX.js +0 -1
  835. package/dist/pull-DLkaZBwH.js +0 -257
  836. package/dist/push-sJ5dy46a.js +0 -162
  837. package/dist/pushed-policy-Db651nih.d.ts +0 -63
  838. package/dist/pushed-policy-UZyQinrL.js +0 -241
  839. package/dist/refresh-on-L9UOwATg.d.ts +0 -49
  840. package/dist/refs-C8BKxc_e.js +0 -105
  841. package/dist/relation-walk-BDTaTKTM.js +0 -189
  842. package/dist/relations-CMsJ1ARY.js +0 -163
  843. package/dist/replay-BU09ad4L.js +0 -29
  844. package/dist/replay-BpmpY2ev.d.ts +0 -5
  845. package/dist/request-context-C2_1lchh.d.ts +0 -5
  846. package/dist/request-context-dyCY4V1t.js +0 -71
  847. package/dist/request-schema-CMP8Cmxd.js +0 -156
  848. package/dist/resolve-names-DHDedxk0.js +0 -206
  849. package/dist/resource-ref-CaS9yVPi.js +0 -20
  850. package/dist/resource-relations-8-pCScBO.js +0 -252
  851. package/dist/retire-B2xffQgY.js +0 -249
  852. package/dist/revocations-BaUXHM1N.d.ts +0 -26
  853. package/dist/revocations-Bhr0aMIC.js +0 -27
  854. package/dist/rls-B3-tGA4r.js +0 -2700
  855. package/dist/rls-BW2u4lQW.js +0 -367
  856. package/dist/role-builder-BXdhhQcB.js +0 -507
  857. package/dist/rolldown-runtime-C3I60J0A.js +0 -4
  858. package/dist/row-conditions-BAGHOmVq.js +0 -28
  859. package/dist/row-pair-DglMdRFh.js +0 -34
  860. package/dist/rpc-BdFGYcWm.js +0 -112
  861. package/dist/rpc-DKRQobOX.d.ts +0 -22
  862. package/dist/run-2GwcSago.js +0 -694
  863. package/dist/run-CdGNonHf.js +0 -1
  864. package/dist/run-ticket-Ddxt9OuU.js +0 -371
  865. package/dist/run-ticket-o4RxoaEN.d.ts +0 -159
  866. package/dist/runtime-rf0ZuyF3.js +0 -14
  867. package/dist/saas-D9maBt0q.js +0 -1223
  868. package/dist/scan-CB46GDQ0.js +0 -29
  869. package/dist/schema-BlnU_TzE.js +0 -414
  870. package/dist/schema-CyEB_zeO.js +0 -134
  871. package/dist/scim-BG6uPUeW.js +0 -1056
  872. package/dist/scim-CovliQUg.js +0 -44
  873. package/dist/scopes-gdH__vDZ.js +0 -239
  874. package/dist/server-CKjFooaJ.js +0 -147
  875. package/dist/server-types-C4q8_8MM.d.ts +0 -325
  876. package/dist/sha256-C-4WXKIu.js +0 -158
  877. package/dist/shared-BRmCJxDK.js +0 -125
  878. package/dist/shared-DfaIWvIJ.js +0 -354
  879. package/dist/signals-B1vHR3fN.js +0 -32
  880. package/dist/sink-C3KDccl9.d.ts +0 -249
  881. package/dist/sink-D9_vh372.js +0 -968
  882. package/dist/skills-BYHCObpD.js +0 -51
  883. package/dist/skills-C-9wjNaE.js +0 -204
  884. package/dist/snapshot-D0VOanxQ.js +0 -334
  885. package/dist/snapshot-cache-B66h7FBK.js +0 -70
  886. package/dist/snapshot-cache-C1mN0pXe.d.ts +0 -70
  887. package/dist/snapshot-compact-CUtXsx6i.js +0 -75
  888. package/dist/snapshot-empty-F7d5BRlc.js +0 -18
  889. package/dist/snapshot-evaluate-C3ZA35O_.js +0 -501
  890. package/dist/snapshot-reads-CNNmp1cK.js +0 -66
  891. package/dist/sources-2virTxHt.d.ts +0 -721
  892. package/dist/sources-C4vkzZJV.js +0 -660
  893. package/dist/sources-qoIJQrJv.js +0 -11
  894. package/dist/sql-0WjxIp9g.js +0 -80
  895. package/dist/sql-B80DFdpG.d.ts +0 -10
  896. package/dist/src-ieIv22BA.js +0 -2080
  897. package/dist/standard-webhooks-B2g_yWK8.d.ts +0 -88
  898. package/dist/standard-webhooks-D67a3nzk.js +0 -228
  899. package/dist/storage-C2bWdvJH.js +0 -132
  900. package/dist/store-DXO0aVgf.js +0 -380
  901. package/dist/store-core-BI-9ZU-5.d.ts +0 -311
  902. package/dist/store-options-BYKNX_JG.js +0 -993
  903. package/dist/stores-DtM8pt8o.js +0 -128
  904. package/dist/stores-DwGfIcmq.d.ts +0 -57
  905. package/dist/stream-DQ3rbO3J.js +0 -74
  906. package/dist/style-DblOtSga.js +0 -1
  907. package/dist/style-Ds11Hmk4.js +0 -25
  908. package/dist/subject-C7RddW0G.js +0 -24
  909. package/dist/subject-cache-BT1fGuea.js +0 -193
  910. package/dist/subject-cache-TY2tw-k9.d.ts +0 -144
  911. package/dist/subject-jG6o8eKo.js +0 -556
  912. package/dist/subject-settings-8sH5HlII.js +0 -150
  913. package/dist/subject-settings-vNW8qmUH.d.ts +0 -52
  914. package/dist/supabase-BlAqmxD8.js +0 -723
  915. package/dist/supabase-C1hExXsZ.js +0 -92
  916. package/dist/supabase-hook-DCemge7i.js +0 -1
  917. package/dist/supabase-hook-DJA8AJYz.js +0 -4263
  918. package/dist/supautils-DuwkBqKm.js +0 -1186
  919. package/dist/support-session-BGeEYDSq.js +0 -158
  920. package/dist/tables-B3w3EtUF.js +0 -4002
  921. package/dist/target-qdEAnnhU.js +0 -51
  922. package/dist/tenancy-BlxY5T0q.js +0 -224
  923. package/dist/text-BMFRfBqc.js +0 -8
  924. package/dist/text-diff-BtfSmdUo.js +0 -444
  925. package/dist/thenable-BNSM1U2R.js +0 -40
  926. package/dist/time-nR1JesoH.js +0 -95
  927. package/dist/timeout-D51niuQP.js +0 -8
  928. package/dist/token-D6pWn8Uj.d.ts +0 -11
  929. package/dist/token-DaMnIU9O.js +0 -77
  930. package/dist/tool-refusal-D4spOJ7I.js +0 -44
  931. package/dist/type-helpers-tDoGEIsd.d.ts +0 -49
  932. package/dist/types-61f3KMtI.d.ts +0 -1136
  933. package/dist/types-BDgMzK1i.d.ts +0 -368
  934. package/dist/types-BIvkpVoc.d.ts +0 -180
  935. package/dist/types-BWjNPQkS.d.ts +0 -67
  936. package/dist/types-Bq4AU68k.d.ts +0 -105
  937. package/dist/types-BsqLNNvG.d.ts +0 -68
  938. package/dist/types-CH67RMvL.d.ts +0 -136
  939. package/dist/types-CcUXciSj.js +0 -79
  940. package/dist/types-DAyp592k.d.ts +0 -276
  941. package/dist/types-DEDocm4c.d.ts +0 -81
  942. package/dist/types-DQQkzF97.d.ts +0 -126
  943. package/dist/types-DdeivUBP.d.ts +0 -68
  944. package/dist/types-X40XNxRP.d.ts +0 -265
  945. package/dist/usage-BBEm7GVn.js +0 -762
  946. package/dist/usage-CkKbvpmL.js +0 -32
  947. package/dist/usage-GQxn7qkA.js +0 -1
  948. package/dist/validation-error-CV0nV6_L.d.ts +0 -29
  949. package/dist/validation-error-CYg2kJEw.js +0 -36
  950. package/dist/validity-IcjQSR7I.js +0 -57
  951. package/dist/verifier-DUV6pLqZ.js +0 -519
  952. package/dist/verify-lgYu1Twv.js +0 -1736
  953. package/dist/version-DMQ0dnN5.js +0 -48
  954. package/dist/version-DizhmD72.js +0 -1
  955. package/dist/version-sources-BRb9ZteH.js +0 -34
  956. package/dist/views-MWmJ6Y4P.js +0 -147
  957. package/dist/vocabulary-BuYFWeCU.js +0 -158
  958. package/dist/vocabulary-DeZvUaTw.d.ts +0 -401
  959. package/dist/waiter-BophA4BT.d.ts +0 -39
  960. package/dist/waiter-aBLM63_f.js +0 -67
  961. package/dist/watch-CJKYQYNb.js +0 -167
  962. package/dist/watch-Cv-xvI6e.js +0 -1
  963. package/dist/who-can-Yh9WdiwK.js +0 -367
  964. package/dist/wire-delegation-Cv3W2eaM.js +0 -36
  965. package/dist/wire-denial-C7PaVYEM.js +0 -27
  966. package/dist/wrap-Bq9fHwuT.d.ts +0 -18
  967. package/dist/wrap-C5PWzgkq.js +0 -33
  968. package/schemas/catalog-v1.json +0 -679
  969. package/schemas/cli-result-v1.json +0 -95
@@ -1,2700 +0,0 @@
1
- import { t as compact } from "./compact-CAf557ZB.js";
2
- import { c as listPermissions, u as renamedKeys } from "./permission-registry-B8tYxPIt.js";
3
- import { i as dateAt } from "./time-nR1JesoH.js";
4
- import { p as scopeField } from "./tenancy-BlxY5T0q.js";
5
- import { a as describeError, i as configError, o as exitCodeOfError, u as usageResult } from "./errors-BhRkoNS7.js";
6
- import { t as policyRowConditionKeys } from "./row-conditions-BAGHOmVq.js";
7
- import { o as sqlFiles } from "./files-BSjrtIHw.js";
8
- import { i as requirePeer, n as packageManagerOf, t as addLine } from "./peer-BuK9F53f.js";
9
- import { c as requirePolicy } from "./load-C4p4VgwR.js";
10
- import { i as qualifySqlTable, r as escapeSqlIdent } from "./sql-0WjxIp9g.js";
11
- import "./sources-C4vkzZJV.js";
12
- import { t as policyFromCatalog } from "./policy-from-catalog-Z0hvSffr.js";
13
- import { t as beforeFirst } from "./text-BMFRfBqc.js";
14
- import { i as INDEXES_MARKER, n as GRANTS_MARKER, o as SEEDS_MARKER, t as BACKFILL_MARKER } from "./markers-BeHZ4x9Q.js";
15
- import { a as nonEmptyOr } from "./output-CuJfGWo6.js";
16
- import { t as POLICY_NOT_PUBLISHED } from "./problem-types-DSsRfONQ.js";
17
- import { t as fetchProjectPolicy } from "./pull-DLkaZBwH.js";
18
- import { n as MIGRATION_DIRS } from "./constants-DcJABbLW.js";
19
- import { a as isSeedsDirectory, c as parseSplit, d as seedsMigration, f as writeOutputFiles, l as partPath, n as dataMigrationFile, r as driftOf, u as pgDeltaPath } from "./output-files-CM0BnH05.js";
20
- import { t as connectPgPool } from "./pg-Ddxsd5ZB.js";
21
- import { b as rbacScaffold, d as resolveSchemas, f as schemasRefusal, o as supabaseHookSql, p as declarativeSql, s as approvalsSql, t as grantsLabel, u as isSupabaseSchemas, y as parseRbacAuthorize } from "./supabase-hook-DJA8AJYz.js";
22
- import { A as quoteQualified, D as qualified$1, L as scopeTypeOf, O as quoteIdent$1, _ as subjectClaimJsonSql, c as SESSION_LIVE_HELPER, g as sessionLiveHelperSql, j as quoteTable, k as quoteLiteral, r as HELPERS, t as CUSTOM_ROLES, y as subjectIdSql } from "./shared-DfaIWvIJ.js";
23
- import { $ as byKey, C as permittedByPermissionHelper, Ct as scopeTable, E as helpersSql, O as seedSql, St as scopeSources, T as accessSql, at as graphHelper, bt as permittedIdsHelper, gt as memberIdsHelper, i as tableNames, l as graphSql, x as permissionHelpersSql } from "./tables-B3w3EtUF.js";
24
- import { c as breakGlassKey, i as assignmentSql, l as collectGrants, n as ownershipSql, s as breakGlassHolder } from "./ownership-C_5eZ6N2.js";
25
- import { a as splitUndiffed } from "./deciding-columns-NB4wcyBf.js";
26
- import { a as fieldViewsSql, c as ACTOR_MAY_WRITE, d as assemblePolicies, i as fieldViews, l as actorMayWriteCall, m as readOnlyActorPolicies, n as columnGrantSql, o as rowBranches, p as readOnlyActorKinds, r as columnRevokeSql, u as actorMayWriteSql } from "./fields-D9PIYlJy.js";
27
- import { n as permissionHoldersSql } from "./resolve-names-DHDedxk0.js";
28
- import { _ as INDEX_COLUMNS_SQL, a as verifyResult, b as pruneIndexTargets, c as callsHelper, g as COLUMNS_SQL, h as tableFor, i as verifyIgnores, l as helperCallKeys, m as inferredCommand, n as runRlsVerify, o as HELPER_TABLES, p as compileGrants, r as rlsFinding, v as indexTargets, x as readTableIndexFacts, y as indexesSql } from "./verify-lgYu1Twv.js";
29
- import { a as buildContext, c as levelKeys, d as rebuildPlan, i as splitsPart, l as rowHelpersSql, n as generateOptions, o as CANDIDATES, r as isRefusal, s as inheritTargets, t as supautilsRejections, u as DROPPED_LIST } from "./supautils-DuwkBqKm.js";
30
- import { readFileSync } from "node:fs";
31
- import { basename, delimiter, join } from "node:path";
32
- import { spawn } from "node:child_process";
33
- //#region src/cli/rls/advisors.ts
34
- /** The PermDock doctor check that reports the same problem in migrations. */
35
- const ADVISOR_CODES = {
36
- function_search_path_mutable: "PD048",
37
- auth_rls_initplan: "PD051",
38
- rls_disabled_in_public: "PD050",
39
- security_definer_view: "PD022",
40
- anon_security_definer_function_executable: "PD049",
41
- authenticated_security_definer_function_executable: "PD046"
42
- };
43
- const defaultExec = (command, args, options) => new Promise((resolve) => {
44
- const child = spawn(command, [...args], {
45
- cwd: options.cwd,
46
- env: options.env,
47
- stdio: [
48
- "ignore",
49
- "pipe",
50
- "pipe"
51
- ],
52
- ...options.signal === void 0 ? {} : { signal: options.signal }
53
- });
54
- let stdout = "";
55
- let stderr = "";
56
- child.stdout.setEncoding("utf8").on("data", (chunk) => {
57
- stdout += chunk;
58
- });
59
- child.stderr.setEncoding("utf8").on("data", (chunk) => {
60
- stderr += chunk;
61
- });
62
- child.once("error", (error) => {
63
- resolve({
64
- status: null,
65
- stdout,
66
- stderr,
67
- error
68
- });
69
- });
70
- child.once("close", (status) => {
71
- resolve({
72
- status,
73
- stdout,
74
- stderr
75
- });
76
- });
77
- });
78
- function text(value, key) {
79
- const field = typeof value === "object" && value !== null ? Reflect.get(value, key) : void 0;
80
- return typeof field === "string" ? field : "";
81
- }
82
- function findingsOf(value) {
83
- const results = typeof value === "object" && value !== null ? Reflect.get(value, "results") : void 0;
84
- if (!Array.isArray(results)) return;
85
- return results.map((row) => {
86
- const name = text(row, "name");
87
- const finding = {
88
- name,
89
- level: text(row, "level"),
90
- detail: text(row, "detail"),
91
- remediation: text(row, "remediation"),
92
- cacheKey: text(row, "cacheKey")
93
- };
94
- const code = ADVISOR_CODES[name];
95
- return code === void 0 ? finding : Object.assign(finding, { code });
96
- });
97
- }
98
- function installHint(agent) {
99
- return `rls verify --advisors runs the Supabase CLI: install it with ${addLine(agent, ["supabase"], { dev: true })} (or brew install supabase/tap/supabase)`;
100
- }
101
- /**
102
- * `supabase db advisors --type security` against `--db-url` or the local stack,
103
- * from the project's `node_modules/.bin` first, then `PATH`. Exit 1 on a WARN
104
- * or ERROR row, 2 when the CLI is missing or fails.
105
- */
106
- async function runRlsAdvisors(input) {
107
- const exec = input.exec ?? defaultExec;
108
- const bin = join(input.cwd, "node_modules", ".bin");
109
- const path = input.env["PATH"];
110
- const result = await exec("supabase", [
111
- "db",
112
- "advisors",
113
- ...input.db === void 0 ? ["--local"] : ["--db-url", input.db],
114
- "--type",
115
- "security",
116
- "--output-format",
117
- "json"
118
- ], {
119
- cwd: input.cwd,
120
- env: {
121
- ...input.env,
122
- PATH: path === void 0 ? bin : `${bin}${delimiter}${path}`
123
- },
124
- ...input.signal === void 0 ? {} : { signal: input.signal }
125
- });
126
- if (result.error !== void 0) return {
127
- code: 2,
128
- output: installHint(await packageManagerOf(input.cwd))
129
- };
130
- let parsed;
131
- try {
132
- parsed = JSON.parse(result.stdout);
133
- } catch {
134
- parsed = void 0;
135
- }
136
- const findings = findingsOf(parsed);
137
- if (findings === void 0) {
138
- const error = typeof parsed === "object" && parsed !== null ? Reflect.get(parsed, "error") : void 0;
139
- const message = [text(error, "message"), text(error, "suggestion")].filter((part) => part !== "").join(" ");
140
- return {
141
- code: 2,
142
- output: `supabase db advisors failed: ${message === "" ? nonEmptyOr(result.stderr.trim(), `exit ${String(result.status)}`) : message}`
143
- };
144
- }
145
- const failing = findings.filter((finding) => finding.level === "WARN" || finding.level === "ERROR");
146
- const code = failing.length > 0 ? 1 : 0;
147
- if (input.json) return {
148
- code,
149
- output: JSON.stringify({
150
- findings,
151
- errors: findings.filter((finding) => finding.level === "ERROR").length,
152
- warnings: findings.filter((finding) => finding.level === "WARN").length
153
- }, null, 2)
154
- };
155
- if (findings.length === 0) return {
156
- code,
157
- output: "supabase db advisors: no security findings"
158
- };
159
- return {
160
- code,
161
- output: `${findings.map((finding) => `${finding.level} ${finding.name}${finding.code === void 0 ? "" : ` (${finding.code})`}: ${finding.detail}\n ${finding.remediation}`).join("\n")}\n\n${String(failing.length)} finding(s) at WARN or above`
162
- };
163
- }
164
- //#endregion
165
- //#region src/cli/rls/bindings.ts
166
- /**
167
- * The table each resource with row policies binds to. With `helpersOnly`, a
168
- * resource `rls.tables` does not name has no table and no binding.
169
- */
170
- function tableBindings(resources, tables, helpersOnly) {
171
- const out = [];
172
- for (const resource of [...new Set(resources)].toSorted()) {
173
- const named = tables !== void 0 && Object.hasOwn(tables, resource);
174
- if (helpersOnly && !named) continue;
175
- out.push({
176
- resource,
177
- table: qualifySqlTable(tableFor(resource, tables)),
178
- inferred: !named
179
- });
180
- }
181
- return out;
182
- }
183
- /**
184
- * The generate notes for `bindings`: the inferred ones, and where to see them
185
- * all.
186
- */
187
- function bindingNotes(bindings, withDatabase) {
188
- const inferred = bindings.filter((binding) => binding.inferred);
189
- if (inferred.length === 0) return [];
190
- return [`table bindings (no rls.tables entry, so the table is named after the resource): ${inferred.map((binding) => `${binding.resource} -> ${binding.table}`).join(", ")}${withDatabase ? "" : "; run permdock rls explain, or generate with --db-url-stdin, to check each table exists"}`];
191
- }
192
- /**
193
- * The generate notes for the bindings whose table no project SQL file creates.
194
- * A project with no `create table` in those files gets none: its schema lives
195
- * elsewhere (an ORM, another repository).
196
- */
197
- function unknownTableNotes(bindings, created) {
198
- if (created.size === 0) return [];
199
- return bindings.filter((binding) => !created.has(binding.table) && !created.has(binding.table.toLowerCase())).map((binding) => `resource ${binding.resource} is bound to ${binding.table}, which no SQL file in the migration or schema folders creates; name its table in rls.tables, or set rls.tables.${binding.resource}: false when it has none`);
200
- }
201
- /** The inferred bindings whose table `facts` shows missing. */
202
- function missingBindings(bindings, columns) {
203
- return bindings.filter((binding) => binding.inferred && columns[binding.table] === void 0);
204
- }
205
- //#endregion
206
- //#region src/cli/rls/trigger-notes.ts
207
- const CREATE = /^create trigger\s+("[^"]+"|[\w$]+)[^;]*?\bon\s+("[^"]+"(?:\."[^"]+")?|[\w$.]+)/gmu;
208
- function unquote(name) {
209
- return name.replaceAll("\"", "");
210
- }
211
- function reasonOf(name) {
212
- if (name === "permdock_custom_role_name_guard") return "customRoleWrites.roles: a tenant role cannot take a declared or shared role's name";
213
- if (name === "permdock_custom_role_cascade") return "customRoleWrites.roles: a rename or delete of a role carries its grants";
214
- if (name.startsWith("permdock_sync_custom_role_guard")) return "customRoles.from.sync: a signed-in caller writes only entries they may hand out";
215
- if (name.startsWith("permdock_sync_custom_role")) return "customRoles.from.sync: each write to the legacy table rebuilds the role's grants";
216
- if (name.startsWith("permdock_holders") || name.startsWith("permdock_transfer_only")) return "ownershipTriggers; set rls.ownershipTriggers.<scope>: false to skip";
217
- if (name === "permdock_assignment") return "assignments: a role assignment is checked against the caller's own roles";
218
- if (name.startsWith("permdock_closure")) return "the relationship closure table follows its source table";
219
- return "generated by rls generate";
220
- }
221
- /** The triggers `sql` creates, in order, each with the option behind it. */
222
- function generatedTriggers(sql) {
223
- const found = [];
224
- for (const match of sql.matchAll(CREATE)) {
225
- const name = unquote(match.slice(1, 2).join(""));
226
- const table = unquote(match.slice(2, 3).join(""));
227
- found.push({
228
- name,
229
- table,
230
- reason: reasonOf(name)
231
- });
232
- }
233
- return found;
234
- }
235
- /** One generate note per trigger. */
236
- function triggerNotes(sql) {
237
- return generatedTriggers(sql).map((trigger) => `generated trigger ${trigger.name} on ${trigger.table} (${trigger.reason})`);
238
- }
239
- //#endregion
240
- //#region src/cli/rls/explain.ts
241
- function holds(table) {
242
- if (table.tenant === void 0) return ["global"];
243
- return [
244
- "tenant",
245
- ...table.shared === void 0 ? [] : ["shared"],
246
- "global"
247
- ];
248
- }
249
- function explainRls(input) {
250
- const { config, ctx, generated } = input;
251
- const rls = config.rls;
252
- const bindings = tableBindings(generated.compiled.rowColumns.map((item) => item.resource), tableNames(rls?.tables), generated.helpersOnly);
253
- const sources = ctx.memberSources ?? ctx.sources ?? [];
254
- const roles = rls?.customRoleWrites?.roles;
255
- const wanted = rls?.rowHelpers;
256
- const resources = wanted === void 0 ? [] : wanted === true ? [...new Set(generated.compiled.branches.flatMap((branch) => branch.resource === void 0 ? [] : [branch.resource]))].toSorted() : [...new Set(wanted)];
257
- return {
258
- schema: input.schema,
259
- authorize: input.authorize,
260
- scopes: ctx.scopes.map((scope) => scope.within === void 0 ? {
261
- name: scope.name,
262
- key: scope.key ?? scope.name
263
- } : {
264
- name: scope.name,
265
- key: scope.key ?? scope.name,
266
- within: scope.within
267
- }),
268
- bindings: bindings.map((binding) => {
269
- const via = ctx.vias?.[binding.resource];
270
- return via === void 0 ? binding : Object.assign({}, binding, { via: `${via.helper} over ${via.table}.${via.column} (${binding.table}.${via.key})` });
271
- }),
272
- membershipSources: sources.map((source) => ({
273
- table: source.sql.table,
274
- select: source.sql.select("$1")
275
- })),
276
- ...roles === void 0 ? {} : { customRoles: {
277
- table: roles.table,
278
- key: roles.key,
279
- ...roles.tenant === void 0 ? {} : { tenant: roles.tenant },
280
- ...roles.shared === void 0 ? {} : { shared: roles.shared },
281
- ...roles.skip === void 0 ? {} : { skip: roles.skip },
282
- holds: holds(roles)
283
- } },
284
- rowHelpers: resources.map((resource) => ({
285
- resource,
286
- permissions: [...new Set(generated.compiled.branches.flatMap((branch) => branch.resource === resource && branch.coverage !== true ? [branch.permissionKey] : []))].toSorted()
287
- })),
288
- inferredActions: inferredActions(generated, rls?.actions),
289
- triggers: generatedTriggers(input.text)
290
- };
291
- }
292
- function inferredActions(generated, actions) {
293
- const found = /* @__PURE__ */ new Map();
294
- for (const branch of generated.compiled.branches) {
295
- if (branch.resource === void 0) continue;
296
- const base = branch.permissionKey.split("@")[0] ?? branch.permissionKey;
297
- const action = base.slice(branch.resource.length + 1);
298
- const command = inferredCommand(action, actions);
299
- if (command !== void 0) {
300
- const entry = found.get(action) ?? {
301
- command,
302
- keys: /* @__PURE__ */ new Set()
303
- };
304
- entry.keys.add(base);
305
- found.set(action, entry);
306
- }
307
- }
308
- return [...found.entries()].toSorted(([a], [b]) => a < b ? -1 : 1).map(([action, { command, keys }]) => ({
309
- action,
310
- command,
311
- permissions: [...keys].toSorted()
312
- }));
313
- }
314
- /** The text report of `explain`. */
315
- function describeExplain(explain) {
316
- const lines = [
317
- `schema ${explain.schema}, authorize ${explain.authorize}`,
318
- `scopes: ${explain.scopes.map((scope) => `${scope.name} (${scope.key}${scope.within === void 0 ? "" : `, within ${scope.within}`})`).join(", ")}`,
319
- "",
320
- "table bindings:",
321
- ...explain.bindings.map((binding) => ` ${binding.resource} -> ${binding.table}${binding.inferred ? " (named after the resource; set rls.tables to change)" : ""}${binding.via === void 0 ? "" : ` via ${binding.via}`}${binding.exists === false ? " MISSING" : ""}`)
322
- ];
323
- if (explain.membershipSources.length > 0) {
324
- lines.push("", "membership sources:");
325
- for (const source of explain.membershipSources) lines.push(` ${source.table}`, ` ${source.select.replaceAll("\n", "\n ")}`);
326
- }
327
- if (explain.customRoles !== void 0) {
328
- const roles = explain.customRoles;
329
- const columns = [
330
- `key ${roles.key}`,
331
- ...roles.tenant === void 0 ? [] : [`tenant ${roles.tenant}`],
332
- ...roles.shared === void 0 ? [] : [`shared ${roles.shared}`],
333
- ...roles.skip === void 0 ? [] : [`skip ${roles.skip}`]
334
- ];
335
- lines.push("", `custom roles: ${roles.table} (${columns.join(", ")}); holds ${roles.holds.join(", ")} roles`);
336
- }
337
- if (explain.rowHelpers.length > 0) {
338
- lines.push("", "row helpers:");
339
- for (const helper of explain.rowHelpers) lines.push(` ${helper.resource}: ${helper.permissions.join(", ")}`);
340
- }
341
- if (explain.inferredActions.length > 0) {
342
- lines.push("", "inferred actions (set rls.actions to change):");
343
- for (const item of explain.inferredActions) lines.push(` ${item.action} -> ${item.command}: ${item.permissions.join(", ")}`);
344
- }
345
- if (explain.triggers.length > 0) {
346
- lines.push("", "generated triggers:");
347
- for (const trigger of explain.triggers) lines.push(` ${trigger.name} on ${trigger.table} (${trigger.reason})`);
348
- }
349
- return lines.join("\n");
350
- }
351
- //#endregion
352
- //#region src/cli/rls/generate-output.ts
353
- function moveUndiffed(sql, label, part) {
354
- const { kept, moved } = splitUndiffed(sql);
355
- const [first = "", ...rest] = kept.split("\n");
356
- return {
357
- sql: [
358
- first,
359
- `-- what supabase db diff drops from this part is in ${label}`,
360
- ...rest
361
- ].join("\n"),
362
- grants: `-- the privileges and view options supabase db diff drops from the ${part} part\n${moved.join("\n")}`
363
- };
364
- }
365
- /** Why `--split` cannot be written for `mode`, or `undefined`. */
366
- function splitRefusal(mode, plan) {
367
- const seedsWithoutOut = plan.split.includes("seeds") && plan.seedsOut === void 0 && !plan.noSeeds && !plan.seedView;
368
- const helpersWithoutSeeds = plan.split.includes("helpers") && !plan.noSeeds && !plan.split.includes("seeds") && !plan.seedFunction && !plan.seedView;
369
- switch (mode) {
370
- case "pg-delta":
371
- if (plan.explicitOut && !plan.placeholder) return `rls generate --split needs {part} in --out, or no --out for pg-delta's per-schema layout (got ${plan.outRel})`;
372
- if (plan.grantsOut !== void 0) return "rls generate --grants-out is for --schemas migra: pg-delta keeps the grants in each part, so drop --grants-out";
373
- if (helpersWithoutSeeds) return "rls generate --split helpers under pg-delta needs the seeds part with --seeds-out: pg-delta rejects the role_permissions rows in a declarative file";
374
- if (seedsWithoutOut) return "rls generate --split seeds under pg-delta needs --seeds-out: pg-delta does not diff the role_permissions rows, so they go in a migration";
375
- return;
376
- case "migra":
377
- if (!plan.placeholder) return `rls generate --split under migra needs {part} in --out, for example supabase/schemas/identity/056_permdock_{part}.sql (got ${plan.outRel})`;
378
- if (helpersWithoutSeeds) return "rls generate --split helpers under migra needs the seeds part with --seeds-out: supabase db diff does not carry the role_permissions rows from a schema file";
379
- if (seedsWithoutOut) return "rls generate --split seeds under migra needs --seeds-out: supabase db diff does not carry the role_permissions rows, so they go in a migration";
380
- return;
381
- case "migrations":
382
- if (!plan.placeholder) return `rls generate --split needs {part} in --out, for example supabase/migrations/20260101000000_permdock_{part}.sql (got ${plan.outRel})`;
383
- if (plan.grantsOut !== void 0) return "rls generate --grants-out is for --schemas migra: a hand-written migration keeps its grants, so drop --grants-out";
384
- return;
385
- default: return mode;
386
- }
387
- }
388
- /**
389
- * The files `generate` writes: one, or one per `--split` part, plus the hook's
390
- * grants under migra.
391
- */
392
- function outputFiles(plan) {
393
- const { input } = plan;
394
- const split = parseSplit(input.split);
395
- if (typeof split === "string") return split;
396
- if (split?.includes("policies") === true && plan.helpersOnly) return "rls generate --helpers-only writes no policies part; drop it from --split";
397
- if (split === void 0) {
398
- if (input.grantsOut !== void 0) return "rls generate --grants-out needs --split with the helpers or hook part";
399
- if (input.seedsOut !== void 0) return "rls generate --seeds-out needs --split with the seeds part";
400
- if (input.noSeeds === true) return "rls generate --no-seeds needs --split: without it the seeds are part of the one file";
401
- return [{
402
- part: "rls",
403
- rel: plan.outRel,
404
- text: plan.text
405
- }];
406
- }
407
- if (input.target !== "sql") return "rls generate --split needs --target sql";
408
- const schemas = resolveSchemas(input.cwd, input.config, input.schemas);
409
- const pgDelta = schemas.mode === "pg-delta" ? schemas : void 0;
410
- const placeholder = plan.outRel.includes("{part}");
411
- const refused = splitRefusal(schemas.mode, {
412
- split,
413
- placeholder,
414
- explicitOut: input.out !== void 0,
415
- outRel: plan.outRel,
416
- grantsOut: input.grantsOut,
417
- seedsOut: input.seedsOut,
418
- noSeeds: input.noSeeds === true,
419
- seedFunction: input.config.rls?.seeds === "function",
420
- seedView: input.config.rls?.seeds === "view"
421
- });
422
- if (refused !== void 0) return refused;
423
- const at = (part, schema = plan.schema) => pgDelta === void 0 || placeholder ? partPath(plan.outRel, part) : pgDeltaPath(pgDelta.schemaDir, part, schema);
424
- if (input.grantsOut !== void 0 && !split.includes("hook") && !split.includes("helpers")) return "rls generate --grants-out needs the helpers or hook part in --split";
425
- if (input.noSeeds === true && input.seedsOut !== void 0) return "rls generate --no-seeds and --seeds-out exclude each other: drop one";
426
- if (input.seedsOut !== void 0 && !split.includes("seeds")) return "rls generate --seeds-out needs the seeds part in --split";
427
- if (split.includes("hook") && input.config.supabase?.hook === void 0) return "rls generate --split hook needs supabase.hook in permdock.config.ts";
428
- const sql = plan.sql();
429
- const relocated = pgDelta === void 0 ? void 0 : sql.servicePolicies;
430
- if (relocated !== void 0 && split.includes("policies") && !split.includes("seeds")) return "rls generate --split policies under pg-delta with rls.realtime or rls.storage needs the seeds part with --seeds-out: the declarative sync shadow database has no realtime.messages or storage.objects, so their policies go in that migration";
431
- const seeds = relocated === void 0 || !split.includes("policies") ? sql.seeds : `${sql.seeds}\n${relocated}`;
432
- const files = [];
433
- const label = grantsLabel(input.grantsOut);
434
- let grantsMarker = `${GRANTS_MARKER} schema=${plan.schema}`;
435
- const grants = [];
436
- for (const part of split) switch (part) {
437
- case "helpers": {
438
- if (label === void 0) {
439
- files.push({
440
- part,
441
- rel: at(part),
442
- text: sql.helpers
443
- });
444
- break;
445
- }
446
- const moved = moveUndiffed(sql.helpers, label, part);
447
- files.push({
448
- part,
449
- rel: at(part),
450
- text: moved.sql
451
- });
452
- grants.push(moved.grants);
453
- break;
454
- }
455
- case "seeds": {
456
- if (input.noSeeds === true) {
457
- if (relocated !== void 0 && split.includes("policies")) return "rls generate --no-seeds cannot drop the seeds part under pg-delta with rls.realtime or rls.storage: their policies live in it";
458
- break;
459
- }
460
- const out = input.seedsOut;
461
- if (out !== void 0 && isSeedsDirectory(input.cwd, out)) {
462
- const planned = seedsMigration(input.cwd, out, SEEDS_MARKER, seeds, input.io.now?.() ?? dateAt());
463
- if (!planned.current || input.check) files.push({
464
- part,
465
- rel: planned.rel,
466
- text: seeds
467
- });
468
- break;
469
- }
470
- files.push({
471
- part,
472
- rel: out ?? at(part),
473
- text: seeds
474
- });
475
- break;
476
- }
477
- case "indexes":
478
- files.push({
479
- part,
480
- rel: at(part),
481
- text: sql.indexes
482
- });
483
- break;
484
- case "policies":
485
- files.push({
486
- part,
487
- rel: at(part),
488
- text: pgDelta === void 0 ? sql.policies : sql.declarativePolicies
489
- });
490
- break;
491
- case "hook": {
492
- const hook = supabaseHookSql(plan.scopes, input.config, {}, label);
493
- files.push({
494
- part,
495
- rel: at(part, hook.manifest.hook.schema),
496
- text: hook.sql
497
- });
498
- const [marker = grantsMarker, ...rest] = hook.grants.split("\n");
499
- grantsMarker = marker;
500
- grants.push(rest.join("\n").trimEnd());
501
- break;
502
- }
503
- default: return part;
504
- }
505
- if (pgDelta !== void 0 && !placeholder) {
506
- for (const [index, file] of files.entries()) if (file.part !== "seeds" || input.seedsOut === void 0) files[index] = {
507
- ...file,
508
- text: declarativeSql(file.text)
509
- };
510
- }
511
- if (input.grantsOut !== void 0) files.push({
512
- part: "grants",
513
- rel: input.grantsOut,
514
- text: `${[grantsMarker, ...grants].join("\n")}\n`
515
- });
516
- return files;
517
- }
518
- //#endregion
519
- //#region src/cli/rls/backfill.ts
520
- /**
521
- * The `--backfill-out` migration: every custom role in the application's roles
522
- * table that has no rows in `custom_role_permissions` or `custom_role_includes`
523
- * yet is saved through `permdock_trusted_replace_custom_role_grants`, with the
524
- * entries PermDock cannot hold left out and listed in one warning. Running it
525
- * again copies nothing, so a role edited after the copy keeps its edits.
526
- */
527
- function backfillSql(ctx, from, migrate) {
528
- const plan = rebuildPlan(ctx, from, migrate);
529
- const { rolesTable, perms, includes, replace, scopes } = plan;
530
- return `${BACKFILL_MARKER} schema=${ctx.schema ?? "permdock"}
531
- -- custom roles copied from ${qualifySqlTable(plan.roles.table)} (rls.customRoles.from) through ${replace}
532
- -- a role that already has rows is left as it is; entries PermDock cannot hold are dropped and listed in one warning
533
- do $permdock$
534
- declare
535
- v record;
536
- v_allow text[];
537
- v_deny text[];
538
- v_include text[];
539
- v_lost text[];
540
- v_dropped text[] := '{}'::text[];
541
- v_copied integer := 0;
542
- v_present integer := 0;
543
- begin
544
- for v in
545
- ${plan.identity}
546
- from ${rolesTable} r
547
- where ${plan.eligible}
548
- order by 4, 2, 1, 3
549
- loop
550
- if v.role is null or not (v.scope = 'global' or v.scope = any(${scopes})) then
551
- v_dropped := v_dropped || (coalesce(v.role, 'null') || ': scope ' || coalesce(v.scope, 'null') || ' is not declared');
552
- continue;
553
- end if;
554
- if exists (
555
- select 1 from ${perms} c
556
- where c.tenant_id is not distinct from v.tenant_id and c.scope = v.scope and c.scope_id is not distinct from v.scope_id and c.role = v.role
557
- ) or exists (
558
- select 1 from ${includes} c
559
- where c.tenant_id is not distinct from v.tenant_id and c.scope = v.scope and c.scope_id is not distinct from v.scope_id and c.role = v.role
560
- ) then
561
- v_present := v_present + 1;
562
- continue;
563
- end if;
564
- ${plan.collect}
565
- if v_allow is null and v_deny is null and v_include is null then
566
- continue;
567
- end if;
568
- perform ${replace}(v.tenant_id, v.scope, v.scope_id, v.role, v_allow, v_deny, v_include);
569
- v_copied := v_copied + 1;
570
- end loop;
571
- raise notice 'permdock backfill: copied % custom role(s), % already present', v_copied, v_present;
572
- if cardinality(v_dropped) > 0 then
573
- raise warning 'permdock backfill: dropped % entr(ies) PermDock cannot hold: %', cardinality(v_dropped), ${DROPPED_LIST};
574
- end if;
575
- end
576
- $permdock$;
577
- `;
578
- }
579
- //#endregion
580
- //#region src/cli/rls/break-glass.ts
581
- /**
582
- * The audit table every generated break-glass read writes to. Part of the SQL
583
- * contract.
584
- */
585
- const BREAK_GLASS_AUDIT = "permdock_break_glass_audit";
586
- const IDENT$2 = /^[a-z][a-z0-9_]*$/u;
587
- /**
588
- * The resources a `breakGlass` grant targets, with the table each reads. A
589
- * break-glass grant is non-portable, so `compileGrants` never turns it into a
590
- * policy; the server reads restricted rows through the generated function
591
- * instead, which is why plain RLS keeps denying them.
592
- */
593
- function breakGlassEntries(policy, tables) {
594
- const byResource = /* @__PURE__ */ new Map();
595
- for (const item of collectGrants(policy)) {
596
- const { grant } = item;
597
- if (grant.breakGlass === void 0) continue;
598
- const holder = breakGlassHolder(item);
599
- const resource = grant.permission.resource;
600
- const grants = byResource.get(resource) ?? [];
601
- byResource.set(resource, grants);
602
- if (holder === void 0) {
603
- const root = policy.scopes[0];
604
- grants.push({
605
- permission: grant.permission.key,
606
- scope: "anyone",
607
- column: root === void 0 ? void 0 : scopeField(policy.resources.get(resource), root.name, policy.scopes),
608
- ...root === void 0 ? {} : { root: root.name }
609
- });
610
- continue;
611
- }
612
- grants.push({
613
- permission: grant.permission.key,
614
- scope: holder.scope,
615
- column: holder.scope === "global" ? void 0 : scopeField(policy.resources.get(resource), holder.scope, policy.scopes)
616
- });
617
- }
618
- return [...byResource].map(([resource, grants]) => ({
619
- resource,
620
- table: tableFor(resource, tables),
621
- grants
622
- }));
623
- }
624
- /**
625
- * Rows the subject's roles reach for `p_permission`: a break-glass grant lifts
626
- * denies, never the tenant boundary. A grant to no role reads the rows of the
627
- * root scopes the subject is a member of, or every row when the policy declares
628
- * no scopes.
629
- */
630
- function rowsFilter(ctx, entry) {
631
- const arms = entry.grants.flatMap((grant) => {
632
- const asked = `p_permission = ${quoteLiteral(grant.permission)}`;
633
- if (grant.scope === "anyone") {
634
- if (grant.root === void 0) return [`(${asked})`];
635
- return grant.column === void 0 ? [] : [`(${asked} and ${quoteIdent$1(grant.column)} in (select ${qualified$1(ctx, memberIdsHelper(grant.root))}()))`];
636
- }
637
- if (grant.scope !== "global" && grant.column === void 0) return [];
638
- return [`(${asked} and ${accessSql(ctx, grant.scope, breakGlassKey(grant.permission), grant.column)})`];
639
- });
640
- return arms.length === 0 ? "false" : [...new Set(arms)].join("\n or ");
641
- }
642
- function functionName$1(resource) {
643
- if (!IDENT$2.test(resource)) throw configError(`PermDock CLI: unsafe break-glass resource '${resource}'`);
644
- return `permdock_break_glass_${resource}`;
645
- }
646
- function auditSql$1(ctx) {
647
- const audit = qualified$1(ctx, quoteIdent$1(BREAK_GLASS_AUDIT));
648
- return `-- break-glass audit: one row per session that read restricted data
649
- -- RLS never compiles a break-glass override, so restricted rows stay denied to a direct read
650
- create table if not exists ${audit} (
651
- id bigint generated always as identity primary key,
652
- at timestamptz not null default now(),
653
- subject text,
654
- permission text not null,
655
- purpose text,
656
- reason text not null
657
- );
658
- alter table ${audit} enable row level security;
659
- revoke all on table ${audit} from anon, authenticated, public;`;
660
- }
661
- function readFunctionSql(ctx, entry) {
662
- const fn = qualified$1(ctx, functionName$1(entry.resource));
663
- const audit = qualified$1(ctx, quoteIdent$1(BREAK_GLASS_AUDIT));
664
- const table = quoteQualified(entry.table);
665
- const session = subjectClaimJsonSql(ctx, "break_glass");
666
- const subject = subjectIdSql(ctx);
667
- return `-- ${entry.resource}: reads restricted rows through a checked, audited break-glass session
668
- create or replace function ${fn}(p_permission text)
669
- returns setof ${table}
670
- language plpgsql
671
- security definer
672
- set search_path = ''
673
- as $$
674
- declare
675
- session jsonb := ${session};
676
- begin
677
- if session is null
678
- or jsonb_typeof(session) <> 'object'
679
- or session ->> 'v' <> '1'
680
- or session ->> 'permission' <> p_permission
681
- or coalesce(session ->> 'reason', '') = ''
682
- or jsonb_typeof(session -> 'expires_at') <> 'number'
683
- or (session ->> 'expires_at')::numeric <= extract(epoch from now())
684
- then
685
- raise exception 'PermDock: no valid break-glass session for %', p_permission
686
- using errcode = '42501';
687
- end if;
688
- insert into ${audit} (subject, permission, purpose, reason)
689
- values (
690
- nullif((${subject})::text, ''),
691
- p_permission,
692
- session ->> 'purpose',
693
- session ->> 'reason'
694
- );
695
- return query select * from ${table}
696
- where ${rowsFilter(ctx, entry)};
697
- end;
698
- $$;
699
- revoke execute on function ${fn}(text) from public, anon;
700
- grant execute on function ${fn}(text) to authenticated;`;
701
- }
702
- /**
703
- * The `security definer` read path for every `breakGlass` grant: an audit table
704
- * and one `permdock_break_glass_<resource>(permission)` per resource that
705
- * checks a signed break-glass session, writes an audit row and returns the rows
706
- * in the scope instances where the subject holds a role with the break-glass
707
- * grant (bypassing the table's policies as the definer). Empty when the policy
708
- * has no break-glass grant.
709
- */
710
- function breakGlassSql(ctx, entries) {
711
- if (entries.length === 0) return "";
712
- return [auditSql$1(ctx), ...entries.map((entry) => readFunctionSql(ctx, entry))].join("\n\n");
713
- }
714
- //#endregion
715
- //#region src/cli/rls/emit.ts
716
- const HEADER = "-- generated by permdock rls generate\n-- fail-closed: never target a bypass role\n";
717
- const TRUSTED_READER_GRANT = /^grant usage on schema "[^"\n]+" to [^\n;]+;\ngrant execute on function [^\n]+\.permdock_trusted_role_permissions(?:_by_id)?\([^)\n]*\) to [^\n;]+;$/gmu;
718
- function assertNoServiceRole(text) {
719
- if (/\bservice_role\b/iu.test(text.replaceAll(TRUSTED_READER_GRANT, ""))) throw new Error("PermDock CLI: generated RLS must never emit service_role");
720
- }
721
- function assertSupautilsSafe(text) {
722
- const [first] = supautilsRejections(text);
723
- if (first !== void 0) throw new Error(`PermDock CLI: generated SQL line ${String(first.line)} ${first.reason}, which supautils rejects on Supabase`);
724
- }
725
- /**
726
- * Neon's Data API and `pg_session_jwt` name the anonymous role `anonymous`;
727
- * Supabase, PostgREST and the GUC pattern use `anon`. Role lists end a line or
728
- * a statement after `to` or `from`, so only those are renamed.
729
- */
730
- function dialectRoles(text, dialect) {
731
- if (dialect !== "neon") return text;
732
- return text.replaceAll(/\b(to|from) ((?:[a-z_]+, )*[a-z_]+)(?=;|\n)/gu, (_match, keyword, list) => `${keyword} ${list.split(", ").map((role) => role === "anon" ? "anonymous" : role).join(", ")}`);
733
- }
734
- function tablesOf(policies) {
735
- return [...new Set(policies.map((item) => item.table))];
736
- }
737
- /**
738
- * Enable (and force) row level security, then the table grants for the commands
739
- * a policy allows.
740
- */
741
- function tableSql(table, policies, force, views) {
742
- const closed = views.find((view) => view.table === table && view.companion !== void 0);
743
- const target = quoteQualified(table);
744
- const lines = [`alter table ${target} enable row level security;`];
745
- if (force) lines.push(`alter table ${target} force row level security;`);
746
- lines.push(`revoke all on table ${target} from anon, authenticated;`);
747
- for (const role of ["anon", "authenticated"]) {
748
- const cmds = new Set(policies.filter((item) => item.table === table && item.effect === "allow" && item.roles.includes(role)).map((item) => item.command));
749
- const grants = [
750
- "select",
751
- "insert",
752
- "update",
753
- "delete"
754
- ].filter((cmd) => cmds.has(cmd) && (closed === void 0 || cmd !== "select"));
755
- if (grants.length > 0) lines.push(`grant ${grants.join(", ")} on table ${target} to ${role};`);
756
- if (closed !== void 0 && cmds.has("select")) lines.push(columnGrantSql(closed, role));
757
- }
758
- if (closed !== void 0) lines.push(columnRevokeSql(closed));
759
- return lines.join("\n");
760
- }
761
- /**
762
- * `drop policy if exists` and `create policy` for one policy, without the
763
- * table's grants.
764
- */
765
- function policySql(item) {
766
- const target = quoteQualified(item.table);
767
- const lines = [
768
- `drop policy if exists ${quoteIdent$1(item.name)} on ${target};`,
769
- `create policy ${quoteIdent$1(item.name)}`,
770
- ` on ${target}`,
771
- ` as ${item.effect === "deny" ? "restrictive" : "permissive"}`,
772
- ` for ${item.command}`,
773
- ` to ${item.roles.join(", ")}`
774
- ];
775
- if (item.using !== void 0) lines.push(` using (${item.using})`);
776
- if (item.check !== void 0) lines.push(` with check (${item.check})`);
777
- return `${lines.join("\n")};\n`;
778
- }
779
- function emitSql(policies, preamble, force = false, views = []) {
780
- const chunks = [HEADER];
781
- if (preamble !== "") chunks.push(preamble);
782
- for (const table of tablesOf(policies)) chunks.push(tableSql(table, policies, force, views), "");
783
- for (const item of policies) chunks.push(policySql(item));
784
- if (views.length > 0) chunks.push(fieldViewsSql(views));
785
- const text = `${chunks.join("\n").trim()}\n`;
786
- assertNoServiceRole(text);
787
- assertSupautilsSafe(text);
788
- return text;
789
- }
790
- /**
791
- * The SQL a Drizzle or Prisma schema cannot declare: helpers, grants, `force`
792
- * and field views. `rls generate` writes it next to `out` for a custom
793
- * migration.
794
- */
795
- function migrationSql(policies, preamble, force, views) {
796
- const parts = [
797
- preamble.trim(),
798
- ...tablesOf(policies).map((table) => tableSql(table, policies, force, views)),
799
- fieldViewsSql(views)
800
- ].filter((part) => part !== "");
801
- if (parts.length === 0) return "";
802
- const text = `${HEADER}\n${parts.join("\n\n")}\n`;
803
- assertNoServiceRole(text);
804
- assertSupautilsSafe(text);
805
- return text;
806
- }
807
- function helpersNote(helpers, how) {
808
- return helpers === void 0 ? [] : [`// run ${helpers} ${how}`];
809
- }
810
- function camelCase(name) {
811
- return name.replaceAll(/[_-]+([a-z0-9])/giu, (_, char) => char.toUpperCase());
812
- }
813
- function tableName(table) {
814
- return table.slice(table.lastIndexOf(".") + 1);
815
- }
816
- function pascalCase(name) {
817
- const camel = camelCase(name);
818
- return camel.charAt(0).toUpperCase() + camel.slice(1);
819
- }
820
- const IDENTIFIER = /^[A-Za-z_$][\w$]*$/u;
821
- function identifier(name, what) {
822
- if (!IDENTIFIER.test(name)) throw configError(`PermDock CLI: ${what} ${JSON.stringify(name)} is not an identifier`);
823
- return name;
824
- }
825
- function quoted(text) {
826
- return `'${text.replaceAll(/[\\']/gu, (match) => `\\${match}`)}'`;
827
- }
828
- function templateText(text) {
829
- return text.replaceAll(/[\\`]|\$\{/gu, (match) => `\\${match}`);
830
- }
831
- const AUTH_UID = "(select auth.uid())";
832
- function drizzleRoles(list) {
833
- return list.includes("anon") ? "[anonRole, authenticatedRole]" : "authenticatedRole";
834
- }
835
- function emitDrizzle(policies, options) {
836
- const supabase = options.dialect === "supabase";
837
- const anon = policies.some((item) => item.roles.includes("anon"));
838
- const sqlOf = (text) => {
839
- const parts = text.split(AUTH_UID).map(templateText);
840
- return `sql\`${supabase ? parts.join("${authUid}") : parts.join(AUTH_UID)}\``;
841
- };
842
- const usesUid = supabase && policies.some((item) => item.using?.includes(AUTH_UID) === true || item.check?.includes(AUTH_UID) === true);
843
- const lines = [
844
- "// generated by permdock rls generate",
845
- "// fail-closed: never target a bypass role",
846
- ...helpersNote(options.helpers, "in a custom migration (drizzle-kit generate --custom)"),
847
- "import { sql } from 'drizzle-orm'"
848
- ];
849
- if (supabase) {
850
- const named = [
851
- anon ? "anonRole" : "",
852
- "authenticatedRole",
853
- usesUid ? "authUid" : ""
854
- ].filter((name) => name !== "").join(", ");
855
- lines.push("import { pgPolicy } from 'drizzle-orm/pg-core'", `import { ${named} } from 'drizzle-orm/supabase'`);
856
- } else lines.push("import { pgPolicy, pgRole } from 'drizzle-orm/pg-core'");
857
- lines.push(`import * as schema from ${quoted(options.schema ?? "./schema")}`, "");
858
- if (!supabase) {
859
- if (anon) lines.push(`export const anonRole = pgRole('${options.dialect === "neon" ? "anonymous" : "anon"}').existing()`);
860
- lines.push("export const authenticatedRole = pgRole('authenticated').existing()", "");
861
- }
862
- for (const item of policies) {
863
- const as = item.effect === "deny" ? "restrictive" : "permissive";
864
- const table = identifier(options.exports?.[item.table] ?? camelCase(tableName(item.table)), "table export");
865
- const name = identifier(camelCase(item.name), "policy export");
866
- const using = item.using === void 0 ? "" : `\n using: ${sqlOf(item.using)},`;
867
- const check = item.check === void 0 ? "" : `\n withCheck: ${sqlOf(item.check)},`;
868
- lines.push(`export const ${name} = pgPolicy(${quoted(item.name)}, {`, ` as: '${as}',`, ` for: '${item.command}',`, ` to: ${drizzleRoles(item.roles)},${using}${check}`, `}).link(schema.${table})`, "");
869
- }
870
- const text = `${lines.join("\n").trimEnd()}\n`;
871
- assertNoServiceRole(text);
872
- return text;
873
- }
874
- /**
875
- * Prisma 8 `policy_<command>` blocks; each target model declares `@@rls`
876
- * itself.
877
- */
878
- function emitPrisma(policies, options = {}) {
879
- const modelOf = (table) => identifier(options.models?.[table] ?? pascalCase(tableName(table)), "model");
880
- const models = [...new Set(policies.map((item) => modelOf(item.table)))];
881
- const lines = [
882
- "// generated by permdock rls generate (Prisma 8 policy blocks)",
883
- "// fail-closed: never target a bypass role",
884
- `// add @@rls to ${models.length === 1 ? "model" : "models"} ${models.join(", ")}; keep these blocks in their namespace`,
885
- ...helpersNote(options.helpers, "in a migration before these policies"),
886
- ""
887
- ];
888
- for (const item of policies) {
889
- if (item.effect === "deny") throw configError(`PermDock CLI: Prisma policy blocks are permissive only, so ${item.name} (a deny) needs --target sql`);
890
- lines.push(`policy_${item.command} ${identifier(item.name, "policy name")} {`, ` target = ${modelOf(item.table)}`, ` roles = [${item.roles.join(", ")}]`);
891
- if (item.using !== void 0) lines.push(` using = ${JSON.stringify(item.using)}`);
892
- if (item.check !== void 0) lines.push(` withCheck = ${JSON.stringify(item.check)}`);
893
- lines.push("}", "");
894
- }
895
- const text = `${lines.join("\n").trimEnd()}\n`;
896
- assertNoServiceRole(text);
897
- return text;
898
- }
899
- /** The migration file written next to `out`. */
900
- function migrationOut(out) {
901
- const dot = out.lastIndexOf(".");
902
- return `${dot > Math.max(out.lastIndexOf("/"), out.lastIndexOf("\\")) ? out.slice(0, dot) : out}.migration.sql`;
903
- }
904
- function defaultOut(target) {
905
- switch (target) {
906
- case "sql": return "rls.sql";
907
- case "drizzle": return "src/db/policies.ts";
908
- case "prisma": return "prisma/policies.prisma";
909
- default: return target;
910
- }
911
- }
912
- //#endregion
913
- //#region src/cli/rls/realtime-storage.ts
914
- const SCOPE_SEGMENT = /^\{([a-z][a-z0-9_]*)\}$/u;
915
- const LITERAL_SEGMENT = /^[^{}:\s]+$/u;
916
- const TOPIC = "(select realtime.topic())";
917
- function policyName(prefix, name, command) {
918
- const full = `permdock_${prefix}_${name.replaceAll(/[^A-Za-z0-9]+/gu, "_").replaceAll(/^_|_$/gu, "")}_${command}`;
919
- if (new TextEncoder().encode(full).length > 63) throw configError(`PermDock CLI: the ${prefix} policy name ${full} is longer than Postgres's 63 bytes; shorten '${name}'`);
920
- return full;
921
- }
922
- function grantKey(facts, ref, where, warnings) {
923
- if (ref === void 0) return;
924
- const key = typeof ref === "object" && ref !== null ? Reflect.get(ref, "key") : ref;
925
- if (typeof key !== "string" || !facts.keys.has(key)) throw configError(`PermDock CLI: ${where} must be a permission reference from the definitions (got ${JSON.stringify(key)})`);
926
- if (facts.rowConditions.has(key)) warnings.push(`${where} is ${key}, whose grants carry row conditions (a relation, a where or another condition): the policy admits only the instances its role allows without a condition reach, through permitted_<scope>_ids_by_permission`);
927
- return key;
928
- }
929
- function declaredScope(facts, scope, where) {
930
- if (!facts.scopes.has(scope)) throw configError(`PermDock CLI: ${where} names the scope '${scope}', which definePolicy({ scopes }) does not declare`);
931
- return scope;
932
- }
933
- /**
934
- * The ids of `scope` where the subject holds `key` through an allow without a
935
- * row condition, minus a deny of it, as text: `<value> in (…)`. A relationship
936
- * or a `where` on the same permission never widens it.
937
- */
938
- function permitted(ctx, value, scope, key) {
939
- return `${value} in (select x::text from ${qualified$1(ctx, permittedByPermissionHelper(scope))}(${quoteLiteral(key)}) x)`;
940
- }
941
- function escapeRegex(text) {
942
- return text.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`);
943
- }
944
- function realtimePolicies(ctx, facts, realtime, warnings) {
945
- return Object.entries(realtime.topics).flatMap(([pattern, topic]) => {
946
- const where = `rls.realtime.topics['${pattern}']`;
947
- const segments = pattern.split(":");
948
- const placeholders = segments.flatMap((segment, index) => {
949
- const match = SCOPE_SEGMENT.exec(segment);
950
- return match === null ? [] : [{
951
- index,
952
- scope: match[1] ?? ""
953
- }];
954
- });
955
- const [placeholder] = placeholders;
956
- if (placeholder === void 0 || placeholders.length > 1 || segments.some((segment, index) => index !== placeholder.index && !LITERAL_SEGMENT.test(segment))) throw configError(`PermDock CLI: ${where} must be ':'-separated segments with exactly one '{<scope>}' segment, such as 'org:{organization}:chat'`);
957
- const scope = declaredScope(facts, placeholder.scope, where);
958
- const regex = `^${segments.map((segment, index) => index === placeholder.index ? "[^:]+" : escapeRegex(segment)).join(":")}$`;
959
- const id = `split_part(${TOPIC}, ':', ${String(placeholder.index + 1)})`;
960
- const condition = (key) => `extension in ('broadcast', 'presence')
961
- and ${TOPIC} ~ ${quoteLiteral(regex)}
962
- and ${permitted(ctx, id, scope, key)}`;
963
- const read = grantKey(facts, topic.read, `${where}.read`, warnings);
964
- const write = grantKey(facts, topic.write, `${where}.write`, warnings);
965
- if (read === void 0) throw configError(`PermDock CLI: ${where}.read is required`);
966
- const policies = [{
967
- name: policyName("realtime", pattern, "select"),
968
- table: "realtime.messages",
969
- command: "select",
970
- effect: "allow",
971
- roles: ["authenticated"],
972
- using: condition(read)
973
- }];
974
- if (write !== void 0) policies.push({
975
- name: policyName("realtime", pattern, "insert"),
976
- table: "realtime.messages",
977
- command: "insert",
978
- effect: "allow",
979
- roles: ["authenticated"],
980
- check: condition(write)
981
- });
982
- return policies;
983
- });
984
- }
985
- function folderOf(bucket, where) {
986
- const folder = bucket.folder ?? 1;
987
- if (!Number.isInteger(folder) || folder < 1) throw configError(`PermDock CLI: ${where}.folder must be a positive integer (got ${String(folder)})`);
988
- return folder;
989
- }
990
- function storagePolicies(ctx, facts, storage, warnings) {
991
- return Object.entries(storage.buckets).flatMap(([id, bucket]) => {
992
- const where = `rls.storage.buckets['${id}']`;
993
- const scope = declaredScope(facts, bucket.scope, `${where}.scope`);
994
- const folder = folderOf(bucket, where);
995
- const condition = (key) => `bucket_id = ${quoteLiteral(id)}
996
- and ${permitted(ctx, `(storage.foldername(name))[${String(folder)}]`, scope, key)}`;
997
- const policies = [
998
- [
999
- "select",
1000
- bucket.read,
1001
- "read"
1002
- ],
1003
- [
1004
- "insert",
1005
- bucket.write,
1006
- "write"
1007
- ],
1008
- [
1009
- "update",
1010
- bucket.write,
1011
- "write"
1012
- ],
1013
- [
1014
- "delete",
1015
- bucket.delete,
1016
- "delete"
1017
- ]
1018
- ].flatMap(([command, ref, field]) => {
1019
- const key = grantKey(facts, ref, `${where}.${field}`, warnings);
1020
- if (key === void 0) return [];
1021
- const expression = condition(key);
1022
- return [{
1023
- name: policyName("storage", id, command),
1024
- table: "storage.objects",
1025
- command,
1026
- effect: "allow",
1027
- roles: ["authenticated"],
1028
- ...command === "insert" ? {} : { using: expression },
1029
- ...command === "select" || command === "delete" ? {} : { check: expression }
1030
- }];
1031
- });
1032
- if (policies.length === 0) throw configError(`PermDock CLI: ${where} needs read, write or delete`);
1033
- return policies;
1034
- });
1035
- }
1036
- /**
1037
- * The `realtime.messages` and `storage.objects` policies `rls.realtime` and
1038
- * `rls.storage` describe. Each one admits a row only where the subject holds
1039
- * the permission in the scope instance its topic segment or folder names,
1040
- * through an allow without a row condition, so the helpers' API-key ceiling and
1041
- * suspension rules apply and a relationship grant on the same permission never
1042
- * reaches a topic or a folder.
1043
- */
1044
- function realtimeStoragePolicies(ctx, facts, config, warnings = []) {
1045
- if (config.realtime === void 0 && config.storage === void 0) return [];
1046
- if (ctx.dialect !== "supabase") throw configError(`PermDock CLI: rls.realtime and rls.storage need --dialect supabase (got ${ctx.dialect})`);
1047
- const policies = [...config.realtime === void 0 ? [] : realtimePolicies(ctx, facts, config.realtime, warnings), ...config.storage === void 0 ? [] : storagePolicies(ctx, facts, config.storage, warnings)];
1048
- const seen = /* @__PURE__ */ new Set();
1049
- for (const { name } of policies) {
1050
- if (seen.has(name)) throw configError(`PermDock CLI: two rls.realtime or rls.storage entries both name the policy ${name}; rename one`);
1051
- seen.add(name);
1052
- }
1053
- return policies;
1054
- }
1055
- //#endregion
1056
- //#region src/cli/rls/generate-policies.ts
1057
- const ACTOR_GUARDS_HEADER = "-- rls.readOnlyActors with --helpers-only: restrictive policies on the write commands, which narrow the hand-written policies and grant nothing. Apply this after the migrations that create the tables.";
1058
- const SERVICE_TABLES_HEADER = "-- Supabase Realtime and Storage: rls.realtime and rls.storage. RLS on both tables is Supabase's.";
1059
- /**
1060
- * A policy that applies only where its table exists. The Realtime and Storage
1061
- * services create `realtime.messages` and `storage.objects`, so a local stack
1062
- * with the service off, and pg-delta's shadow database, have none; under
1063
- * `--helpers-only` the app's own migrations create its tables.
1064
- */
1065
- function guardedPolicySql(item) {
1066
- const body = policySql(item).trimEnd().split("\n").map((line) => ` ${line}`).join("\n");
1067
- return `do $permdock$
1068
- begin
1069
- if to_regclass(${quoteLiteral(qualifySqlTable(item.table))}) is not null then
1070
- ${body}
1071
- end if;
1072
- end
1073
- $permdock$;
1074
- `;
1075
- }
1076
- /**
1077
- * Appends the `realtime.messages` and `storage.objects` policies, which never
1078
- * get `tableSql`.
1079
- */
1080
- function withHelperTables(sql, helperTables) {
1081
- if (helperTables === void 0) return sql;
1082
- const tables = `${helperTables.trimEnd()}\n`;
1083
- return sql.trim() === "" ? tables : `${sql.trimEnd()}\n\n${tables}`;
1084
- }
1085
- /**
1086
- * The read-only actor policies `--helpers-only` writes: those on a table
1087
- * `rls.tables` names. A resource it does not name has no known table, so its
1088
- * write commands get a warning instead.
1089
- */
1090
- function helpersOnlyActorGuards(guards, tables, actorMayWrite, warnings) {
1091
- const named = new Set(Object.values(tableNames(tables) ?? {}).map((table) => qualifySqlTable(table)));
1092
- const kept = guards.filter((guard) => named.has(qualifySqlTable(guard.table)));
1093
- const unmapped = [...new Set(guards.filter((guard) => !named.has(qualifySqlTable(guard.table))).map((guard) => qualifySqlTable(guard.table)))].toSorted();
1094
- if (unmapped.length > 0) warnings.push(`rls.readOnlyActors with --helpers-only writes read-only actor policies only on tables rls.tables names; for ${unmapped.join(", ")}, name the table in rls.tables, or add \`and (select ${actorMayWrite}())\` to each hand-written insert, update and delete policy`);
1095
- return kept;
1096
- }
1097
- function databaseModeWarnings(policy, { ctx }, warnings) {
1098
- if (ctx.authorize !== "database") return;
1099
- for (const { name } of ctx.scopes) if (policy.grants.some((grant) => grant.scope === name) && scopeTable(ctx, name) === void 0 && scopeSources(ctx, name).length === 0) warnings.push(`${name}-scoped grants read the ${name} memberships table in database mode: set rls.memberships.scopes.${name}, rls.membershipSources or supabase.hook.memberships (or --memberships for the first scope), otherwise they deny`);
1100
- }
1101
- /**
1102
- * The grants compiled into table policies, and the Realtime and Storage
1103
- * policies beside them.
1104
- */
1105
- function generatePolicies(input, policy, options, built, warnings) {
1106
- const rls = input.config.rls;
1107
- const { ctx } = built;
1108
- const { fieldsMode, revokeColumns } = options;
1109
- databaseModeWarnings(policy, built, warnings);
1110
- const compiled = compileGrants(policy, ctx, tableNames(rls?.tables), warnings, input.skipClosures, rls?.rowHelpers !== void 0 || inheritTargets(policy).length > 0);
1111
- const helpersOnly = input.helpersOnly === true || rls?.helpersOnly === true;
1112
- if (helpersOnly && (input.target !== "sql" || revokeColumns)) return { refusal: "rls generate --helpers-only needs --target sql and no --revoke-columns: the table grants are hand-written, so revoke the restricted columns there" };
1113
- const views = fieldsMode === void 0 ? [] : fieldViews(policy, ctx, compiled.branches, {
1114
- revokeColumns,
1115
- helpersOnly,
1116
- mask: fieldsMode === "mask"
1117
- }, warnings);
1118
- const force = input.force === true || rls?.force === true;
1119
- if (force && views.some((view) => view.companion !== void 0)) warnings.push("--force with --revoke-columns: each <table>_visible_fields companion reads as its owner, so its owner needs BYPASSRLS or the restricted columns read as null");
1120
- const policyName = input.policyName ?? rls?.policyName;
1121
- const assembled = assemblePolicies(fieldsMode === void 0 ? compiled.branches : rowBranches(compiled.branches), {
1122
- perRole: input.policyPerRole === true || rls?.policyPerRole === true,
1123
- ...policyName === void 0 ? {} : { name: policyName }
1124
- });
1125
- const actorKinds = readOnlyActorKinds(rls?.readOnlyActors);
1126
- const actorGuards = actorKinds === void 0 || !helpersOnly ? [] : helpersOnlyActorGuards(readOnlyActorPolicies(assembled, actorMayWriteCall(ctx)), rls?.tables, qualified$1(ctx, ACTOR_MAY_WRITE), warnings);
1127
- const withActors = (items) => actorKinds === void 0 ? items : [...items, ...readOnlyActorPolicies(items, actorMayWriteCall(ctx))];
1128
- let tablePolicies;
1129
- try {
1130
- tablePolicies = realtimeStoragePolicies(ctx, {
1131
- scopes: new Set(ctx.scopes.map((scope) => scope.name)),
1132
- keys: new Set(listPermissions(policy.vocabulary.permissions).map((leaf) => leaf.key)),
1133
- rowConditions: new Set(policyRowConditionKeys(policy))
1134
- }, compact({
1135
- realtime: rls?.realtime,
1136
- storage: rls?.storage
1137
- }), warnings);
1138
- } catch (cause) {
1139
- return { refusal: describeError(cause) };
1140
- }
1141
- if (tablePolicies.length > 0 && helpersOnly) warnings.push("rls.realtime and rls.storage add policies, and --helpers-only writes none: no realtime.messages or storage.objects policy is written");
1142
- const servicePolicies = tablePolicies.length === 0 || helpersOnly ? [] : withActors(tablePolicies);
1143
- const generated = {
1144
- compiled,
1145
- helpersOnly,
1146
- force,
1147
- views,
1148
- policies: helpersOnly ? [] : withActors(assembled),
1149
- ...actorGuards.length === 0 ? {} : { actorGuards: [ACTOR_GUARDS_HEADER, ...actorGuards.map((item) => policySql(item))].join("\n") }
1150
- };
1151
- if (servicePolicies.length === 0) return generated;
1152
- return {
1153
- ...generated,
1154
- helperTables: [SERVICE_TABLES_HEADER, ...servicePolicies.map(policySql)].join("\n"),
1155
- guardedTables: [`${SERVICE_TABLES_HEADER} A stack without the service has no table, so each policy is skipped there.`, ...servicePolicies.map(guardedPolicySql)].join("\n")
1156
- };
1157
- }
1158
- //#endregion
1159
- //#region src/cli/rls/shims.ts
1160
- const NAME$1 = /^[a-z_][a-z0-9_]*$/u;
1161
- /**
1162
- * The key a legacy caller passes, mapped the way `rls migrate` maps it: `keys`
1163
- * and `renamed` exactly, then the longest `prefixes` entry.
1164
- */
1165
- function mappedKey(config, renamed) {
1166
- const exact = {
1167
- ...renamed,
1168
- ...config.keys
1169
- };
1170
- const prefixes = Object.entries(config.prefixes ?? {}).toSorted(([a], [b]) => b.length - a.length);
1171
- const fallback = prefixes.length === 0 ? "p_key" : `case ${prefixes.map(([from, to]) => `when pg_catalog.starts_with(p_key, ${quoteLiteral(from)}) then ${quoteLiteral(to)} || pg_catalog.substr(p_key, ${String(from.length + 1)})`).join(" ")} else p_key end`;
1172
- if (Object.keys(exact).length === 0) return fallback;
1173
- return `coalesce(${quoteLiteral(JSON.stringify(exact))}::jsonb ->> p_key, ${fallback})`;
1174
- }
1175
- function scopeOf(ctx, scope) {
1176
- if (!ctx.scopes.some((item) => item.name === scope)) throw configError(`PermDock CLI: rls.migrate helper scope '${scope}' is not a declared scope`);
1177
- return scope;
1178
- }
1179
- function addKey(list, key) {
1180
- if (!list.includes(key)) list.push(key);
1181
- }
1182
- /**
1183
- * The grant keys behind each permission, per scope: the keys of its
1184
- * unconditional allows, and every deny key. A shim cannot apply a row condition
1185
- * or a validity window, so a conditional allow answers nothing and a
1186
- * conditional deny always subtracts; the conditioned keys are listed apart. A
1187
- * break-glass key answers only the break-glass read, so it is left out too.
1188
- * Rows seeded under a former key are left out; the shim maps a former key to
1189
- * the current one first.
1190
- */
1191
- function shimGrants(rows, conditioned, renamed) {
1192
- const byScope = /* @__PURE__ */ new Map();
1193
- for (const row of rows.toSorted((a, b) => a.grantKey < b.grantKey ? -1 : a.grantKey > b.grantKey ? 1 : 0)) {
1194
- if (Object.hasOwn(renamed, row.permission) || row.effect === "allow" && row.grantKey === breakGlassKey(row.permission)) continue;
1195
- const scope = byScope.get(row.scope) ?? {};
1196
- byScope.set(row.scope, scope);
1197
- const keys = (Object.hasOwn(scope, row.permission) ? scope[row.permission] : void 0) ?? {
1198
- allow: [],
1199
- deny: []
1200
- };
1201
- scope[row.permission] = keys;
1202
- const isConditioned = conditioned.has(row.grantKey);
1203
- if (row.effect === "allow") {
1204
- if (isConditioned) {
1205
- keys["conditioned-allow"] ??= [];
1206
- addKey(keys["conditioned-allow"], row.grantKey);
1207
- } else addKey(keys.allow, row.grantKey);
1208
- continue;
1209
- }
1210
- addKey(keys.deny, row.grantKey);
1211
- if (isConditioned) {
1212
- keys["conditioned-deny"] ??= [];
1213
- addKey(keys["conditioned-deny"], row.grantKey);
1214
- }
1215
- }
1216
- return byScope;
1217
- }
1218
- function shimMap(grants, scope) {
1219
- const entries = Object.entries(grants.get(scope) ?? {}).flatMap(([permission, keys]) => keys.allow.length === 0 && keys.deny.length === 0 ? [] : [[permission, {
1220
- allow: keys.allow,
1221
- deny: keys.deny
1222
- }]]);
1223
- return JSON.stringify(Object.fromEntries(entries));
1224
- }
1225
- function shimFunction(name, args, argTypes, returns, sql) {
1226
- return `create or replace function ${name}(${args})
1227
- returns ${returns}
1228
- language sql
1229
- stable
1230
- security definer
1231
- set search_path = ''
1232
- as $$
1233
- ${sql}
1234
- $$;
1235
- revoke execute on function ${name}(${argTypes}) from public, anon;
1236
- grant execute on function ${name}(${argTypes}) to authenticated;`;
1237
- }
1238
- function grantKeys(keys, scope, effect) {
1239
- return `pg_catalog.jsonb_array_elements_text(coalesce(${keys.map(scope)} -> (${keys.key}) -> ${quoteLiteral(effect)}, '[]'::jsonb)) g(grant_key)`;
1240
- }
1241
- /**
1242
- * The instances of `scope` the caller holds an unconditional allow of the key
1243
- * in, minus those it holds a deny in.
1244
- */
1245
- function idsSql(ctx, keys, scope) {
1246
- const helper = qualified$1(ctx, permittedIdsHelper(scope));
1247
- return ` select a.id
1248
- from ${grantKeys(keys, scope, "allow")}
1249
- cross join lateral ${helper}(g.grant_key) a(id)
1250
- except
1251
- select d.id
1252
- from ${grantKeys(keys, scope, "deny")}
1253
- cross join lateral ${helper}(g.grant_key) d(id)`;
1254
- }
1255
- function hasSql(ctx, keys) {
1256
- const has = qualified$1(ctx, HELPERS.has);
1257
- return `exists (select 1 from ${grantKeys(keys, "global", "allow")} where ${has}(g.grant_key))
1258
- and not exists (select 1 from ${grantKeys(keys, "global", "deny")} where ${has}(g.grant_key))`;
1259
- }
1260
- function shim(ctx, config, keys, fn, helper) {
1261
- switch (helper.form) {
1262
- case "ids": {
1263
- const scope = scopeOf(ctx, helper.scope);
1264
- return shimFunction(fn, "p_key text", "text", `setof ${scopeTypeOf(ctx, scope)}`, idsSql(ctx, keys, scope));
1265
- }
1266
- case "row": {
1267
- const scope = scopeOf(ctx, helper.scope);
1268
- const type = scopeTypeOf(ctx, scope);
1269
- return shimFunction(fn, `p_id ${type}, p_key text`, `${type}, text`, "boolean", ` select coalesce(p_id in (\n${idsSql(ctx, keys, scope)}\n ), false)`);
1270
- }
1271
- case "membership": {
1272
- const scope = scopeOf(ctx, helper.scope);
1273
- const type = scopeTypeOf(ctx, scope);
1274
- return shimFunction(fn, `p_id ${type}`, type, "boolean", ` select coalesce(p_id in (select ${qualified$1(ctx, memberIdsHelper(scope))}()), false)`);
1275
- }
1276
- case "role": {
1277
- const scope = scopeOf(ctx, helper.scope);
1278
- const type = scopeTypeOf(ctx, scope);
1279
- const values = Object.entries(ctx.roleValues ?? {});
1280
- const role = values.length === 0 ? "p_role" : `case p_role ${values.map(([from, to]) => `when ${quoteLiteral(from)} then ${quoteLiteral(to)}`).join(" ")} else p_role end`;
1281
- return shimFunction(fn, `p_id ${type}, p_role text`, `${type}, text`, "boolean", ` select coalesce(p_id in (select ${qualified$1(ctx, memberIdsHelper(scope))}(array[${role}])), false)`);
1282
- }
1283
- case "global": return shimFunction(fn, "p_key text", "text", "boolean", ` select ${hasSql(ctx, keys)}`);
1284
- case "scoped": {
1285
- const literals = /* @__PURE__ */ new Map();
1286
- for (const scope of ctx.scopes) literals.set(scope.name, scope.name);
1287
- for (const [literal, scope] of Object.entries(config.scopes ?? {})) literals.set(literal, scopeOf(ctx, scope));
1288
- const global = config.globalScopes ?? [];
1289
- return shimFunction(fn, "p_scope text, p_id text, p_key text", "text, text, text", "boolean", ` select case\n${[...global.length === 0 ? [] : [` when p_scope in (${global.map(quoteLiteral).join(", ")}) then ${hasSql(ctx, keys)}`], ...[...literals].filter(([literal]) => !global.includes(literal)).map(([literal, scope]) => ` when p_scope = ${quoteLiteral(literal)} then coalesce(p_id in (select s.id::text from (\n${idsSql(ctx, keys, scope)}\n ) s(id)), false)`)].join("\n")}\n else false\n end`);
1290
- }
1291
- default: return helper;
1292
- }
1293
- }
1294
- /**
1295
- * One wrapper per `rls.migrate.helpers` entry under its legacy name, so SQL
1296
- * that `rls migrate` has not rewritten yet (function bodies, views, triggers)
1297
- * answers from the PermDock helpers. A wrapper maps the legacy key to the
1298
- * permission key, then to the grant keys `grants` lists for the helper's scope,
1299
- * so a permission whose grants are split by condition still answers. Each is
1300
- * `security definer` with an empty `search_path`, so a caller needs `execute`
1301
- * on the wrapper only, not usage on the helper schema.
1302
- */
1303
- function shimsSql(ctx, config, shims, renamed, grants) {
1304
- const schema = shims.schema ?? "public";
1305
- const keys = {
1306
- key: mappedKey(config, renamed),
1307
- map: (scope) => `${quoteLiteral(shimMap(grants, scope))}::jsonb`
1308
- };
1309
- const chunks = [`-- permdock shims: legacy helper names over the permdock helpers; drop each once doctor reports no caller (PD056)`];
1310
- for (const [name, helper] of Object.entries(config.helpers).toSorted(byKey)) {
1311
- if (!NAME$1.test(name)) throw configError(`PermDock CLI: unsafe rls.migrate helper name '${name}'`);
1312
- chunks.push(shim(ctx, config, keys, `${quoteIdent$1(schema)}.${name}`, helper));
1313
- }
1314
- return `${chunks.join("\n\n")}\n`;
1315
- }
1316
- //#endregion
1317
- //#region src/cli/rls/triggers.ts
1318
- const PREFIX = "PermDock CLI";
1319
- const EVENTS = /* @__PURE__ */ new Set([
1320
- "insert",
1321
- "update",
1322
- "delete",
1323
- "truncate"
1324
- ]);
1325
- const AUDITED = [
1326
- CUSTOM_ROLES.permissions,
1327
- CUSTOM_ROLES.includes,
1328
- "user_roles"
1329
- ];
1330
- const IDENT$1 = /^[a-z_][a-z0-9_$]*$/u;
1331
- /** The tables `sql` creates in `schema`, by name without the schema. */
1332
- function generatedTables(sql, schema) {
1333
- const prefix = `create table if not exists ${quoteIdent$1(schema)}.`;
1334
- const found = /* @__PURE__ */ new Set();
1335
- for (const line of sql.split("\n")) {
1336
- if (!line.startsWith(prefix)) continue;
1337
- const name = /^"?([A-Za-z_][\w$]*)"?/u.exec(line.slice(prefix.length))?.[1];
1338
- if (name !== void 0) found.add(name);
1339
- }
1340
- return [...found].toSorted();
1341
- }
1342
- function functionName(name, label) {
1343
- if (typeof name !== "string" || name.split(".").length !== 2) throw configError(`${PREFIX}: ${label} must be a schema-qualified function such as audit.log_change, got ${JSON.stringify(name)}`);
1344
- return quoteTable(name);
1345
- }
1346
- function knownTable(table, tables, label) {
1347
- if (!tables.includes(table)) throw configError(`${PREFIX}: ${label} names ${table}, which rls generate does not create with this config; it creates ${tables.join(", ")}`);
1348
- }
1349
- function triggerSql(table, trigger, label) {
1350
- if (typeof trigger.name !== "string" || trigger.name === "" || trigger.name.toLowerCase().startsWith("permdock_")) throw configError(`${PREFIX}: ${label}.name must be a name outside permdock_, which generated triggers use, got ${JSON.stringify(trigger.name)}`);
1351
- if (trigger.when !== "before" && trigger.when !== "after") throw configError(`${PREFIX}: ${label}.when must be before or after`);
1352
- const events = trigger.events;
1353
- if (events.length === 0 || !events.every((event) => EVENTS.has(event))) throw configError(`${PREFIX}: ${label}.events must list insert, update, delete or truncate`);
1354
- const level = trigger.level ?? "row";
1355
- if (level !== "row" && level !== "statement") throw configError(`${PREFIX}: ${label}.level must be row or statement`);
1356
- if (level === "row" && events.includes("truncate")) throw configError(`${PREFIX}: ${label} fires on truncate, which Postgres allows only with level: 'statement'`);
1357
- const fn = functionName(trigger.function, `${label}.function`);
1358
- const args = (trigger.args ?? []).map((arg) => quoteLiteral(arg));
1359
- const name = quoteIdent$1(trigger.name);
1360
- return `drop trigger if exists ${name} on ${table};
1361
- create trigger ${name}
1362
- ${trigger.when} ${[...new Set(events)].join(" or ")} on ${table}
1363
- for each ${level} execute function ${fn}(${args.join(", ")});`;
1364
- }
1365
- /**
1366
- * `rls.triggers`: the application's triggers on generated tables, after the
1367
- * tables. A table this run does not create is an error, so a trigger never
1368
- * silently goes missing.
1369
- */
1370
- function triggersSql(triggers, schema, tables) {
1371
- if (triggers === void 0) return "";
1372
- const chunks = [];
1373
- for (const [table, list] of Object.entries(triggers).toSorted(byKey)) {
1374
- knownTable(table, tables, `rls.triggers.${table}`);
1375
- const target = `${quoteIdent$1(schema)}.${quoteIdent$1(table)}`;
1376
- for (const [index, trigger] of list.entries()) chunks.push(triggerSql(target, trigger, `rls.triggers.${table}[${String(index)}]`));
1377
- }
1378
- return chunks.length === 0 ? "" : `-- rls.triggers: triggers the application owns on generated tables\n${chunks.join("\n")}\n`;
1379
- }
1380
- /**
1381
- * `rls.audit`: one call of the audit function per generated table, which
1382
- * registers the table with the application's audit module. Statements that run
1383
- * code, so they travel with the seeds.
1384
- */
1385
- function auditSql(audit, schema, tables) {
1386
- if (audit === void 0) return "";
1387
- const fn = functionName(audit.function, "rls.audit.function");
1388
- const listed = audit.tables;
1389
- if (listed !== void 0) for (const table of listed) knownTable(table, tables, "rls.audit.tables");
1390
- const targets = listed ?? AUDITED.filter((table) => tables.includes(table));
1391
- const args = Object.entries(audit.args ?? {}).map(([name, value]) => {
1392
- if (!IDENT$1.test(name)) throw configError(`${PREFIX}: rls.audit.args names ${JSON.stringify(name)}, which is not a lower-case parameter name`);
1393
- return `, ${quoteIdent$1(name)} => ${quoteLiteral(value)}`;
1394
- });
1395
- if (targets.length === 0) return "";
1396
- return `-- rls.audit: generated tables registered with ${audit.function}
1397
- ${targets.map((table) => `select ${fn}(${quoteLiteral(`${quoteIdent$1(schema)}.${quoteIdent$1(table)}`)}::regclass${args.join("")});`).join("\n")}
1398
- `;
1399
- }
1400
- //#endregion
1401
- //#region src/cli/rls/generate-sql.ts
1402
- /**
1403
- * The checks that need the SQL context: `--backfill-out`,
1404
- * `rls.anonymousSignIns`, `rls.jsonSchema`.
1405
- */
1406
- function preflight(input, { ctx }) {
1407
- const rls = input.config.rls;
1408
- const from = typeof rls?.customRoles === "object" ? rls.customRoles.from : void 0;
1409
- if (input.backfillOut !== void 0 && from === void 0) return { refusal: "rls generate --backfill-out needs rls.customRoles.from in permdock.config.ts" };
1410
- let backfill;
1411
- if (from !== void 0) try {
1412
- backfill = backfillSql(ctx, from, rls?.migrate);
1413
- } catch (cause) {
1414
- return { refusal: describeError(cause) };
1415
- }
1416
- if (ctx.anonymousSignIns === "deny" && ctx.dialect !== "supabase") return { refusal: `rls.anonymousSignIns needs --dialect supabase (got ${ctx.dialect})` };
1417
- const jsonSchema = rls?.jsonSchema;
1418
- if (jsonSchema !== void 0 && jsonSchema !== "auto" && typeof jsonSchema !== "boolean") return { refusal: `rls.jsonSchema must be 'auto', true or false (got ${JSON.stringify(jsonSchema)})` };
1419
- return {
1420
- backfill,
1421
- jsonSchema
1422
- };
1423
- }
1424
- function rbacPart(input, policy, { ctx, schema, authorize }, warnings) {
1425
- const rootMapped = ctx.scopes[0] === void 0 ? void 0 : scopeTable(ctx, ctx.scopes[0].name);
1426
- const rootTable = rootMapped === void 0 ? void 0 : {
1427
- ...rootMapped.table,
1428
- tenant: rootMapped.column
1429
- };
1430
- const rbac = input.rbac ? rbacScaffold(policy, {
1431
- schema,
1432
- authorize,
1433
- ...rootTable === void 0 ? {} : { memberships: rootTable },
1434
- ...ctx.scopes[0] === void 0 ? {} : { scope: ctx.scopes[0].name },
1435
- ...ctx.customRoles === void 0 ? {} : { customRoles: {
1436
- declared: ctx.customRoles.declared,
1437
- ...ctx.customRoles.levels === true ? { levels: true } : {}
1438
- } },
1439
- context: ctx
1440
- }) : void 0;
1441
- if (rbac !== void 0) warnings.push(...rbac.warnings);
1442
- if (input.rbac) warnings.push("the token hook that writes user_role and memberships comes from permdock supabase hook generate");
1443
- return rbac;
1444
- }
1445
- /** The ownership, approval store, graph, row-helper and break-glass sections. */
1446
- function sectionsSql(input, policy, options, built, generated, jsonSchema, warnings) {
1447
- const rls = input.config.rls;
1448
- const { ctx, graph, ownership } = built;
1449
- const { compiled } = generated;
1450
- const owned = [ownershipSql(ctx), assignmentSql(ctx)].filter((part) => part !== "").join("\n");
1451
- if (ctx.assignments !== void 0 && (ownership === void 0 || ownership.assigns.length === 0)) warnings.push("rls.assignments needs a role that declares assigns: no assignment trigger is written");
1452
- let approvals;
1453
- try {
1454
- approvals = approvalsSql(ctx, rls?.approvals, jsonSchema ?? false, readOnlyActorKinds(rls?.readOnlyActors) !== void 0);
1455
- } catch (cause) {
1456
- return { refusal: describeError(cause) };
1457
- }
1458
- if (typeof rls?.approvals === "object" && rls.approvals.delegations === true && ctx.authorize !== "database") warnings.push("rls.approvals.delegations with --authorize jwt: permdock_is_approver cannot read a delegator's permissions from the caller's token, so in SQL a cover never satisfies a holder() approver; approvalsHandler still does");
1459
- const graphed = graphSql(ctx, graph, tableNames(rls?.tables));
1460
- let rowHelpers = "";
1461
- if (rls?.rowHelpers !== void 0 || inheritTargets(policy).length > 0) {
1462
- const readable = (grants) => [...options.fieldsMode === void 0 ? grants.branches : rowBranches(grants.branches), ...grants.actionBranches];
1463
- try {
1464
- const narrowed = compileGrants(policy, {
1465
- ...ctx,
1466
- candidates: CANDIDATES
1467
- }, tableNames(rls?.tables), [], input.skipClosures, true);
1468
- rowHelpers = rowHelpersSql(ctx, policy, readable(compiled), rls?.rowHelpers ?? [], tableNames(rls?.tables), warnings, readable(narrowed));
1469
- } catch (cause) {
1470
- return { refusal: describeError(cause) };
1471
- }
1472
- }
1473
- const breakGlass = breakGlassSql(ctx, breakGlassEntries(policy, tableNames(rls?.tables)));
1474
- return [
1475
- approvals,
1476
- owned === "" ? void 0 : owned,
1477
- graphed === "" ? void 0 : graphed,
1478
- breakGlass === "" ? void 0 : breakGlass,
1479
- rowHelpers === "" ? void 0 : rowHelpers
1480
- ];
1481
- }
1482
- /**
1483
- * Whether `anon` calls a helper: `rls.anonExecute`, an anon field view or an
1484
- * anon branch reading the user id.
1485
- */
1486
- function anonExecutes(input, { compiled, views }) {
1487
- return input.config.rls?.anonExecute === true || views.some((view) => view.roles.includes("anon")) || compiled.branches.some((branch) => branch.roles.includes("anon") && [
1488
- branch.access,
1489
- branch.using,
1490
- branch.check
1491
- ].some((sql) => sql?.includes("permdock_user_id") === true));
1492
- }
1493
- /**
1494
- * Everything before the table policies: helpers, sections, shims, scaffold and
1495
- * triggers.
1496
- */
1497
- function preambleSql(input, policy, options, built, generated, jsonSchema, warnings) {
1498
- const rls = input.config.rls;
1499
- const { ctx } = built;
1500
- const { compiled } = generated;
1501
- const rbac = rbacPart(input, policy, built, warnings);
1502
- const sections = sectionsSql(input, policy, options, built, generated, jsonSchema, warnings);
1503
- if (isRefusal(sections)) return sections;
1504
- const configured = rls?.shims;
1505
- const shimsConfig = typeof configured === "object" ? configured : configured === true || input.shims === true ? {} : void 0;
1506
- if (shimsConfig !== void 0 && rls?.migrate === void 0) return { refusal: "PermDock CLI: rls generate --shims needs rls.migrate.helpers in permdock.config.ts" };
1507
- const renamed = Object.fromEntries(renamedKeys(policy.vocabulary.permissions));
1508
- const grants = shimGrants(compiled.rolePermissions, compiled.conditionedKeys, renamed);
1509
- const anonExecute = anonExecutes(input, generated);
1510
- const actorKinds = readOnlyActorKinds(rls?.readOnlyActors);
1511
- const usesLiveSession = compiled.branches.some((branch) => [
1512
- branch.access,
1513
- branch.using,
1514
- branch.check
1515
- ].some((sql) => sql?.includes(SESSION_LIVE_HELPER) === true));
1516
- const shims = shimsConfig === void 0 || rls?.migrate === void 0 ? void 0 : shimsSql(ctx, rls.migrate, shimsConfig, renamed, grants);
1517
- const core = [
1518
- rbac?.head,
1519
- helpersSql(ctx, compiled.rolePermissions, {
1520
- levelReach: compiled.levelReach,
1521
- permissions: listPermissions(policy.permissions).map((leaf) => leaf.key).toSorted(),
1522
- userRoles: !input.rbac,
1523
- anonExecute,
1524
- withoutSeeds: splitsPart(input.split, "seeds"),
1525
- ...rls?.trustedReaders === void 0 ? {} : { trustedReaders: rls.trustedReaders }
1526
- }),
1527
- permissionHelpersSql(ctx, grants, renamed, anonExecute),
1528
- nonEmptyOr(permissionHoldersSql(ctx), void 0),
1529
- actorKinds === void 0 ? void 0 : actorMayWriteSql(ctx, actorKinds),
1530
- usesLiveSession ? sessionLiveHelperSql(ctx) : void 0,
1531
- ...sections,
1532
- shims,
1533
- rbac?.tail
1534
- ].filter((part) => part !== void 0).join("\n");
1535
- const created = generatedTables(core, built.schema);
1536
- let ownTriggers;
1537
- let audit;
1538
- try {
1539
- ownTriggers = triggersSql(rls?.triggers, built.schema, created);
1540
- audit = auditSql(rls?.audit, built.schema, created);
1541
- } catch (cause) {
1542
- return { refusal: describeError(cause) };
1543
- }
1544
- const seedsSplit = splitsPart(input.split, "seeds");
1545
- return {
1546
- preamble: [
1547
- core,
1548
- ownTriggers,
1549
- seedsSplit ? "" : audit
1550
- ].filter((part) => part !== "").join("\n"),
1551
- audit
1552
- };
1553
- }
1554
- function seedsBody(ctx, schema, rows) {
1555
- switch (ctx.seeds) {
1556
- case "function": return `select ${quoteQualified(`${schema}.seed`)}();`;
1557
- case "view": return "-- rls.seeds: 'view': the role_permissions rows are in the helpers part";
1558
- case void 0: return seedSql(ctx, rows);
1559
- default: return ctx.seeds;
1560
- }
1561
- }
1562
- function forceWarnings({ graph }, warnings) {
1563
- for (const entry of graph.values()) {
1564
- const own = [...entry.relations].filter((name) => !("edge" in (entry.node.relations[name] ?? {})));
1565
- if (own.length > 0) warnings.push(`--force: ${entry.node.name} relations ${own.join(", ")} are read from the ${entry.node.name} table itself, so ${graphHelper(entry.node.name)} would recurse through its own policy; keep ${entry.node.name} unforced or move them to edge tables`);
1566
- }
1567
- }
1568
- /**
1569
- * The row columns that belong to a table. With `rls.tables` set, a resource it
1570
- * does not name is a table only when generated policies are written for it;
1571
- * with `--helpers-only` it has none, so it gets no index.
1572
- */
1573
- function tableColumns(rowColumns, tables, helpersOnly, warnings) {
1574
- if (tables === void 0) return rowColumns;
1575
- const unmapped = [...new Set(rowColumns.map((item) => item.resource).filter((resource) => !Object.hasOwn(tables, resource)))].toSorted();
1576
- if (unmapped.length === 0) return rowColumns;
1577
- if (helpersOnly) {
1578
- warnings.push(`no index is suggested for resources without an rls.tables entry: ${unmapped.join(", ")}; map each one that is a table`);
1579
- return rowColumns.filter((item) => Object.hasOwn(tables, item.resource));
1580
- }
1581
- warnings.push(`policies for resources without an rls.tables entry target a table named after the resource: ${unmapped.map((resource) => qualifySqlTable(resource)).join(", ")}; map each one to its table`);
1582
- return rowColumns;
1583
- }
1584
- /** The `--target` file, and for Drizzle and Prisma the SQL migration beside it. */
1585
- function emitTarget(input, built, generated, preamble) {
1586
- const rls = input.config.rls;
1587
- const { ctx } = built;
1588
- const { policies, force, views, helperTables, actorGuards } = generated;
1589
- const outRel = input.out ?? rls?.out ?? defaultOut(input.target);
1590
- const migration = input.target === "sql" ? "" : dialectRoles(migrationSql(policies, withHelperTables(preamble, helperTables), force, views), ctx.dialect);
1591
- const migrationRel = migration === "" ? void 0 : migrationOut(outRel);
1592
- const helpers = migrationRel === void 0 ? void 0 : basename(migrationRel);
1593
- let text;
1594
- switch (input.target) {
1595
- case "sql":
1596
- text = dialectRoles(withHelperTables(withHelperTables(emitSql(policies, preamble, force, views), helperTables), actorGuards), ctx.dialect);
1597
- break;
1598
- case "drizzle":
1599
- text = emitDrizzle(policies, compact({
1600
- dialect: ctx.dialect,
1601
- schema: rls?.drizzle?.schema,
1602
- exports: rls?.drizzle?.exports,
1603
- helpers
1604
- }));
1605
- break;
1606
- case "prisma":
1607
- text = emitPrisma(policies, compact({
1608
- models: rls?.prisma?.models,
1609
- helpers
1610
- }));
1611
- break;
1612
- default: return input.target;
1613
- }
1614
- return {
1615
- text,
1616
- migration,
1617
- migrationRel,
1618
- outRel
1619
- };
1620
- }
1621
- /**
1622
- * The generated SQL for one run, before `--db-url-stdin` prunes the index
1623
- * targets.
1624
- */
1625
- function generateSql(input, policy, options, built, warnings) {
1626
- const rls = input.config.rls;
1627
- const { ctx } = built;
1628
- const checked = preflight(input, built);
1629
- if (isRefusal(checked)) return checked;
1630
- const { jsonSchema } = checked;
1631
- if (jsonSchema !== void 0 && jsonSchema !== false && (rls?.approvals === void 0 || rls.approvals === false || typeof rls.approvals === "object" && rls.approvals.store === false)) warnings.push("rls.jsonSchema constrains the approval store's body, which needs rls.approvals: true; nothing else is jsonb");
1632
- const generated = generatePolicies(input, policy, options, built, warnings);
1633
- if (isRefusal(generated)) return generated;
1634
- const assembled = preambleSql(input, policy, options, built, generated, jsonSchema, warnings);
1635
- if (isRefusal(assembled)) return assembled;
1636
- const { preamble, audit } = assembled;
1637
- if (generated.force) forceWarnings(built, warnings);
1638
- const emitted = emitTarget(input, built, generated, preamble);
1639
- const { policies, force, views, helperTables, guardedTables, helpersOnly, actorGuards } = generated;
1640
- const seedsSplit = splitsPart(input.split, "seeds");
1641
- return {
1642
- ...generated,
1643
- ...emitted,
1644
- backfill: checked.backfill,
1645
- indexes: indexTargets(ctx, tableColumns(generated.compiled.rowColumns, tableNames(rls?.tables), helpersOnly, warnings)),
1646
- parts: (indexes) => ({
1647
- policies: dialectRoles(withHelperTables(emitSql(policies, "", force, views), helperTables), ctx.dialect),
1648
- declarativePolicies: dialectRoles(emitSql(policies, "", force, views), ctx.dialect),
1649
- ...guardedTables === void 0 ? {} : { servicePolicies: dialectRoles(guardedTables, ctx.dialect) },
1650
- helpers: dialectRoles(withHelperTables(emitSql([], preamble, false, helpersOnly ? views : []), actorGuards), ctx.dialect),
1651
- seeds: `${SEEDS_MARKER} schema=${built.schema}\n${seedsBody(ctx, built.schema, generated.compiled.rolePermissions)}\n${seedsSplit ? audit : ""}`,
1652
- indexes: `${INDEXES_MARKER}\n${indexesSql(indexes)}\n`
1653
- })
1654
- };
1655
- }
1656
- //#endregion
1657
- //#region src/cli/rls/index-scan.ts
1658
- /**
1659
- * An index PermDock generated (`permdock_<table>_<columns>_idx`), in the
1660
- * indexes part or in a migration derived from it: it never counts as serving
1661
- * its own target.
1662
- */
1663
- const GENERATED_INDEX = /\bcreate\s+index\s+(?:if\s+not\s+exists\s+)?"?permdock_\w*_idx"?[^;]*;/giu;
1664
- const IDENT = String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][\w$]*)`;
1665
- const NAME = String.raw`${IDENT}(?:\s*\.\s*${IDENT})?`;
1666
- const CREATE_INDEX = new RegExp(String.raw`\bcreate\s+(?:unique\s+)?index\s+(?:concurrently\s+)?(?:if\s+not\s+exists\s+)?(?:${IDENT}\s+)?on\s+(?:only\s+)?(${NAME})\s*(?:using\s+\w+\s*)?\(`, "giu");
1667
- const ADD_KEY = new RegExp(String.raw`\balter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?(${NAME})\s+add\s+(?:constraint\s+${IDENT}\s+)?(?:unique|primary\s+key)\s*(?:nulls\s+not\s+distinct\s*)?\(`, "giu");
1668
- const CREATE_TABLE = new RegExp(String.raw`\bcreate\s+(?:unlogged\s+|temp(?:orary)?\s+)?table\s+(?:if\s+not\s+exists\s+)?(${NAME})\s*\(`, "giu");
1669
- const TABLE_NAME = new RegExp(String.raw`\bcreate\s+(?:unlogged\s+)?table\s+(?:if\s+not\s+exists\s+)?(${NAME})`, "giu");
1670
- const TABLE_KEY = new RegExp(String.raw`^(?:constraint\s+${IDENT}\s+)?(?:unique|primary\s+key)\s*(?:nulls\s+not\s+distinct\s*)?\(`, "iu");
1671
- const COLUMN_KEY = new RegExp(String.raw`^(${IDENT})\s+[^,]*?\b(?:primary\s+key|unique)\b`, "iu");
1672
- const NOT_A_COLUMN = /^(?:constraint|check|foreign|exclude|like)\b/iu;
1673
- function bare(part) {
1674
- const trimmed = part.trim();
1675
- return trimmed.startsWith("\"") ? trimmed.slice(1, -1).replaceAll("\"\"", "\"") : trimmed.toLowerCase();
1676
- }
1677
- /** `schema.table`, with `public` for an unqualified name. */
1678
- function qualified(raw) {
1679
- const parts = raw.split(".").map(bare);
1680
- return parts.length === 1 ? `public.${parts.join("")}` : parts.join(".");
1681
- }
1682
- function stripComments(sql) {
1683
- return sql.replaceAll(/\/\*[\s\S]*?\*\//gu, " ").replaceAll(/--[^\n]*/gu, " ");
1684
- }
1685
- /**
1686
- * The text between the `(` that ends `match` and its closing `)`, and the index
1687
- * after it.
1688
- */
1689
- function group(text, open) {
1690
- let depth = 1;
1691
- for (let index = open; index < text.length; index += 1) {
1692
- const char = text[index];
1693
- if (char === "'" || char === "\"") {
1694
- const close = text.indexOf(char, index + 1);
1695
- if (close === -1) return;
1696
- index = close;
1697
- } else if (char === "(") depth += 1;
1698
- else if (char === ")") {
1699
- depth -= 1;
1700
- if (depth === 0) return {
1701
- body: text.slice(open, index),
1702
- end: index + 1
1703
- };
1704
- }
1705
- }
1706
- }
1707
- function splitTop(body) {
1708
- const items = [];
1709
- let depth = 0;
1710
- let from = 0;
1711
- for (let index = 0; index < body.length; index += 1) {
1712
- const char = body[index];
1713
- if (char === "'" || char === "\"") index = Math.max(body.indexOf(char, index + 1), index);
1714
- else if (char === "(") depth += 1;
1715
- else if (char === ")") depth -= 1;
1716
- else if (char === "," && depth === 0) {
1717
- items.push(body.slice(from, index));
1718
- from = index + 1;
1719
- }
1720
- }
1721
- items.push(body.slice(from));
1722
- return items.map((item) => item.trim());
1723
- }
1724
- /** The first capture group of a match; every pattern here captures it. */
1725
- function captured(match) {
1726
- return match.slice(1, 2).join("");
1727
- }
1728
- /** The index just past a match. */
1729
- function endOf(match) {
1730
- return match.index + match[0].length;
1731
- }
1732
- /** The plain key columns of an index column list, cut at the first expression. */
1733
- function keyColumns(body) {
1734
- const columns = [];
1735
- for (const item of splitTop(body)) {
1736
- const match = new RegExp(`^(${IDENT})(?:\\s|$)`, "u").exec(item);
1737
- if (match === null || item.startsWith("(")) break;
1738
- columns.push(bare(captured(match)));
1739
- }
1740
- return columns;
1741
- }
1742
- /**
1743
- * Key columns of each index, unique constraint and primary key the SQL creates,
1744
- * per `schema.table`.
1745
- */
1746
- function indexKeysFromSql(sql) {
1747
- const text = stripComments(sql);
1748
- const keys = {};
1749
- const add = (table, columns) => {
1750
- if (columns.length > 0) (keys[qualified(table)] ??= []).push(columns);
1751
- };
1752
- for (const pattern of [CREATE_INDEX, ADD_KEY]) for (const match of text.matchAll(pattern)) {
1753
- const found = group(text, endOf(match));
1754
- if (found !== void 0) add(captured(match), keyColumns(found.body));
1755
- }
1756
- for (const match of text.matchAll(CREATE_TABLE)) {
1757
- const found = group(text, endOf(match));
1758
- if (found === void 0) continue;
1759
- for (const item of splitTop(found.body)) if (TABLE_KEY.test(item)) {
1760
- const inner = group(item, item.indexOf("(") + 1);
1761
- if (inner !== void 0) add(captured(match), keyColumns(inner.body));
1762
- } else if (!NOT_A_COLUMN.test(item)) {
1763
- const column = COLUMN_KEY.exec(item)?.[1];
1764
- if (column !== void 0) add(captured(match), [bare(column)]);
1765
- }
1766
- }
1767
- return keys;
1768
- }
1769
- /**
1770
- * The index keys of the SQL files under the migration and schema folders of
1771
- * `cwd`.
1772
- */
1773
- function indexKeysFromProject(cwd) {
1774
- const all = {};
1775
- for (const file of sqlFiles(cwd, [...MIGRATION_DIRS])) {
1776
- const keys = indexKeysFromSql(readFileSync(file, "utf8").replaceAll(GENERATED_INDEX, ""));
1777
- for (const [table, list] of Object.entries(keys)) (all[table] ??= []).push(...list);
1778
- }
1779
- return all;
1780
- }
1781
- /** Every `schema.table` the SQL creates, temporary tables left out. */
1782
- function tablesFromSql(sql) {
1783
- return new Set([...stripComments(sql).matchAll(TABLE_NAME)].map((match) => qualified(captured(match))));
1784
- }
1785
- /**
1786
- * Every `schema.table` the SQL files under the migration and schema folders of
1787
- * `cwd` create.
1788
- */
1789
- function tablesFromProject(cwd) {
1790
- const all = /* @__PURE__ */ new Set();
1791
- for (const file of sqlFiles(cwd, [...MIGRATION_DIRS])) for (const table of tablesFromSql(readFileSync(file, "utf8"))) all.add(table);
1792
- return all;
1793
- }
1794
- /**
1795
- * The targets no index in `keys` leads with: its key columns start with the
1796
- * target's, as `pruneIndexTargets` reads a database.
1797
- */
1798
- function withoutServedTargets(targets, keys) {
1799
- return targets.filter((target) => !(keys[target.table] ?? []).some((key) => target.columns.every((column, at) => key[at] === column)));
1800
- }
1801
- //#endregion
1802
- //#region src/cli/rls/generate.ts
1803
- function loadPolicy(cwd, config, from) {
1804
- const policyPath = from === "drizzle" ? config.policy : from ?? config.policy;
1805
- return requirePolicy(cwd, policyPath, "rls generate needs policy in permdock.config.ts or --policy");
1806
- }
1807
- const PROJECT_COMMAND = "permdock rls generate";
1808
- /**
1809
- * The policy `policyFromCatalog` rebuilds from the project's pushed catalog and
1810
- * policy; a project with no pushed policy fails with `policy-not-published`.
1811
- */
1812
- async function projectPolicyOf(input, project) {
1813
- const fetched = await fetchProjectPolicy({
1814
- command: PROJECT_COMMAND,
1815
- url: input.url,
1816
- project,
1817
- json: input.json === true,
1818
- env: input.io.env ?? process.env,
1819
- io: input.io
1820
- });
1821
- if (!fetched.ok) return {
1822
- ...fetched.result,
1823
- text: ""
1824
- };
1825
- const { catalog, policy } = fetched.value;
1826
- if (policy === void 0) {
1827
- const detail = `project ${project} has a pushed catalog but no policy; push from a project whose permdock.config.ts names one`;
1828
- return {
1829
- code: 1,
1830
- output: input.json === true ? JSON.stringify({
1831
- type: POLICY_NOT_PUBLISHED,
1832
- title: "Policy not published",
1833
- detail,
1834
- command: PROJECT_COMMAND,
1835
- exitCode: 1
1836
- }, null, 2) : `${PROJECT_COMMAND}: ${detail}`,
1837
- text: ""
1838
- };
1839
- }
1840
- try {
1841
- return policyFromCatalog(catalog, policy);
1842
- } catch (cause) {
1843
- return {
1844
- code: 1,
1845
- output: `${PROJECT_COMMAND}: the pushed policy does not rebuild: ${describeError(cause)}`,
1846
- text: ""
1847
- };
1848
- }
1849
- }
1850
- function isOutcome(value) {
1851
- return "text" in value && "code" in value;
1852
- }
1853
- function refused(output) {
1854
- return {
1855
- code: 2,
1856
- output,
1857
- text: ""
1858
- };
1859
- }
1860
- async function runRlsGenerate(input) {
1861
- const options = generateOptions(input);
1862
- if (isRefusal(options)) return refused(options.refusal);
1863
- if (input.project !== void 0 && input.from !== void 0 && input.from !== "drizzle") return refused("rls generate takes the policy from --project or from a --policy module, not both");
1864
- let policy;
1865
- if (input.project === void 0) policy = await loadPolicy(input.cwd, input.config, input.from);
1866
- else {
1867
- const loaded = await projectPolicyOf(input, input.project);
1868
- if (isOutcome(loaded)) return loaded;
1869
- policy = loaded;
1870
- }
1871
- const built = buildContext(input, policy, options);
1872
- if (isRefusal(built)) return refused(built.refusal);
1873
- const warnings = [];
1874
- const generated = generateSql(input, policy, options, built, warnings);
1875
- if (isRefusal(generated)) return refused(generated.refusal);
1876
- const { ctx } = built;
1877
- const { text, migration, migrationRel, helpersOnly } = generated;
1878
- let indexes = generated.indexes;
1879
- const bindings = tableBindings(generated.compiled.rowColumns.map((item) => item.resource), tableNames(input.config.rls?.tables), helpersOnly);
1880
- if (input.config.rls?.tables === void 0) warnings.push(...bindingNotes(bindings, input.db !== void 0));
1881
- warnings.push(...triggerNotes(text));
1882
- if (ctx.seeds === "function") warnings.push(`run select ${built.schema}.seed(); after each deploy`);
1883
- if (input.db === void 0) {
1884
- indexes = withoutServedTargets(indexes, indexKeysFromProject(input.cwd));
1885
- warnings.push(...unknownTableNotes(bindings, tablesFromProject(input.cwd)));
1886
- }
1887
- if (input.db !== void 0) try {
1888
- const facts = await readTableIndexFacts(input.db, [.../* @__PURE__ */ new Set([...indexes.map((target) => target.table), ...bindings.map((binding) => binding.table)])], input.connect);
1889
- const missing = missingBindings(bindings, facts.columns);
1890
- if (missing.length > 0) return refused(`rls generate: ${missing.map((binding) => `resource ${binding.resource} is bound to ${binding.table}, which the database does not have`).join("; ")}; name the table in rls.tables, or set rls.tables.<resource>: false for a resource with no table`);
1891
- const pruned = pruneIndexTargets(indexes, facts);
1892
- indexes = pruned.targets;
1893
- warnings.push(...pruned.warnings);
1894
- } catch (cause) {
1895
- return {
1896
- code: exitCodeOfError(cause),
1897
- output: describeError(cause),
1898
- text: ""
1899
- };
1900
- }
1901
- if (!splitsPart(input.split, "indexes")) for (const target of indexes) warnings.push(`index suggestion: create index on ${target.table} (${target.columns.join(", ")}), or add indexes to --split`);
1902
- const extras = migration === "" ? {} : { migration };
1903
- if (input.write === false) return {
1904
- code: 0,
1905
- output: warnings.join("\n"),
1906
- text,
1907
- policies: generated.policies,
1908
- seeds: generated.compiled.rolePermissions,
1909
- indexes,
1910
- keys: {
1911
- permissions: listPermissions(policy.vocabulary.permissions).map((leaf) => leaf.key),
1912
- rowConditions: [...policyRowConditionKeys(policy)],
1913
- levels: levelKeys(policy),
1914
- renamed: Object.fromEntries(renamedKeys(policy.vocabulary.permissions))
1915
- },
1916
- schema: built.schema,
1917
- helpersOnly,
1918
- explain: explainRls({
1919
- config: input.config,
1920
- ctx,
1921
- schema: built.schema,
1922
- authorize: built.authorize,
1923
- generated,
1924
- text
1925
- }),
1926
- ...extras
1927
- };
1928
- const planned = outputFiles({
1929
- input,
1930
- outRel: generated.outRel,
1931
- text,
1932
- helpersOnly,
1933
- sql: () => generated.parts(indexes),
1934
- scopes: ctx.scopes,
1935
- schema: built.schema
1936
- });
1937
- if (typeof planned === "string") return {
1938
- code: 2,
1939
- output: planned,
1940
- text,
1941
- ...extras
1942
- };
1943
- const files = [...planned];
1944
- if (migrationRel !== void 0) files.push({
1945
- part: "migration",
1946
- rel: migrationRel,
1947
- text: migration
1948
- });
1949
- if (input.backfillOut !== void 0 && generated.backfill !== void 0) {
1950
- const file = dataMigrationFile({
1951
- cwd: input.cwd,
1952
- out: input.backfillOut,
1953
- part: "backfill",
1954
- marker: BACKFILL_MARKER,
1955
- text: generated.backfill,
1956
- now: input.io.now?.() ?? dateAt(),
1957
- check: input.check,
1958
- reserved: files.map((other) => other.rel)
1959
- });
1960
- if (file !== void 0) files.push(file);
1961
- }
1962
- if (input.check) {
1963
- const drift = driftOf(input.cwd, files);
1964
- return drift.length === 0 ? {
1965
- code: 0,
1966
- output: "rls generate up to date",
1967
- text,
1968
- ...extras
1969
- } : {
1970
- code: 1,
1971
- output: drift.map((line) => `rls generate drift: ${line}`).join("\n"),
1972
- text,
1973
- ...extras
1974
- };
1975
- }
1976
- const written = writeOutputFiles(input.cwd, files);
1977
- const notes = [...written.wrote.length === 0 ? [] : [`wrote ${written.wrote.join(", ")}`], ...warnings];
1978
- if (written.printed !== "") for (const note of notes) input.io.stderr(note);
1979
- return {
1980
- code: 0,
1981
- output: written.printed === "" ? notes.join("\n") : written.printed,
1982
- text,
1983
- ...extras
1984
- };
1985
- }
1986
- //#endregion
1987
- //#region src/cli/rls/introspect.ts
1988
- const ROLES = ["anon", "authenticated"];
1989
- /**
1990
- * Neon's `anonymous` is the role `rls generate` writes as `anon` for the other
1991
- * dialects.
1992
- */
1993
- function liveRole(role) {
1994
- return role === "anonymous" ? "anon" : role;
1995
- }
1996
- const PRIVILEGES = [
1997
- "select",
1998
- "insert",
1999
- "update",
2000
- "delete"
2001
- ];
2002
- /** `posts` and `"app"."posts"` as `public.posts` and `app.posts`. */
2003
- function normalizeTableName(table) {
2004
- const parts = table.split(".").map((part) => part.replaceAll("\"", ""));
2005
- return parts.length === 1 ? `public.${parts[0] ?? ""}` : parts.join(".");
2006
- }
2007
- const FUNCTION_HEADER = /create or replace function ("?)([A-Za-z_][\w$]*)\1\.("?)([A-Za-z_][\w$]*)\3\s*\(([\s\S]*?)\nas \$/gu;
2008
- const TYPE_ALIASES = {
2009
- int: "integer",
2010
- int4: "integer",
2011
- int2: "smallint",
2012
- int8: "bigint",
2013
- bool: "boolean",
2014
- varchar: "character varying",
2015
- char: "character",
2016
- float4: "real",
2017
- float8: "double precision",
2018
- timestamp: "timestamp without time zone",
2019
- timestamptz: "timestamp with time zone",
2020
- time: "time without time zone",
2021
- timetz: "time with time zone"
2022
- };
2023
- /**
2024
- * A parameter type as `oidvectortypes` prints it: lower case, no quotes, no
2025
- * schema, no type modifier, aliases spelled out. A `%type` reference is `*`,
2026
- * which matches any type.
2027
- */
2028
- function normalizeParameterType(type) {
2029
- const text = type.trim().toLowerCase().replaceAll("\"", "");
2030
- if (text.endsWith("%type")) return "*";
2031
- const array = /(?:\[\d*\])+$/u.exec(text)?.[0] ?? "";
2032
- const base = text.slice(0, text.length - array.length).replaceAll(/\([^)]*\)/gu, "").replaceAll(/\s+/gu, " ").trim();
2033
- const unqualified = /^[\w$]+(?:\.[\w$]+)+$/u.test(base) ? base.split(".").at(-1) ?? base : base;
2034
- return `${TYPE_ALIASES[unqualified] ?? unqualified}${"[]".repeat(array.split("[").length - 1)}`;
2035
- }
2036
- function splitTopLevel(text) {
2037
- const parts = [];
2038
- let depth = 0;
2039
- let quoted = false;
2040
- let start = 0;
2041
- for (let index = 0; index < text.length; index += 1) {
2042
- const char = text[index];
2043
- if (char === "'") quoted = !quoted;
2044
- else if (!quoted && char === "(") depth += 1;
2045
- else if (!quoted && char === ")") depth -= 1;
2046
- else if (!quoted && depth === 0 && char === ",") {
2047
- parts.push(text.slice(start, index));
2048
- start = index + 1;
2049
- }
2050
- }
2051
- parts.push(text.slice(start));
2052
- return parts.map((part) => part.trim()).filter((part) => part !== "");
2053
- }
2054
- /**
2055
- * The input parameter types of a function header that starts after its opening
2056
- * parenthesis. Every generated parameter is named, so the first word of a
2057
- * parameter with more than one is its name.
2058
- */
2059
- function parameterTypes(header) {
2060
- let depth = 0;
2061
- let end = header.length;
2062
- for (let index = 0; index < header.length; index += 1) {
2063
- const char = header[index];
2064
- if (char === "(") depth += 1;
2065
- else if (char === ")") {
2066
- if (depth === 0) {
2067
- end = index;
2068
- break;
2069
- }
2070
- depth -= 1;
2071
- }
2072
- }
2073
- return splitTopLevel(header.slice(0, end)).flatMap((parameter) => {
2074
- const words = parameter.replace(/\s+(?:default\b|=)[\s\S]*$/iu, "").split(/\s+/u);
2075
- const mode = words[0]?.toLowerCase();
2076
- if (mode === "out") return [];
2077
- const rest = mode === "in" || mode === "inout" || mode === "variadic" ? words.slice(1) : words;
2078
- return [normalizeParameterType((rest.length > 1 ? rest.slice(1) : rest).join(" "))];
2079
- });
2080
- }
2081
- /** `schema.name(type, type)`, the key a helper is checked by. */
2082
- function signatureOf(name, types) {
2083
- return `${name}(${types.join(", ")})`;
2084
- }
2085
- function helpersOf(sql) {
2086
- const found = /* @__PURE__ */ new Set();
2087
- for (const match of sql.matchAll(FUNCTION_HEADER)) {
2088
- const [header = "", , schema = "", , name = "", rest = ""] = match;
2089
- if (/\bsecurity definer\b/u.test(header)) found.add(signatureOf(`${schema}.${name}`, parameterTypes(rest)));
2090
- }
2091
- return [...found];
2092
- }
2093
- function nameOfSignature(signature) {
2094
- return signature.slice(0, signature.indexOf("("));
2095
- }
2096
- function typesOfSignature(signature) {
2097
- return splitTopLevel(signature.slice(signature.indexOf("(") + 1, signature.lastIndexOf(")"))).map(normalizeParameterType);
2098
- }
2099
- /** The actual overload `expected` names; `*` matches any parameter type. */
2100
- function matchHelper(expected, actual) {
2101
- if (Object.hasOwn(actual, expected)) return actual[expected];
2102
- const name = nameOfSignature(expected);
2103
- const want = typesOfSignature(expected);
2104
- for (const [signature, helper] of Object.entries(actual)) {
2105
- const have = typesOfSignature(signature);
2106
- if (nameOfSignature(signature) === name && have.length === want.length && want.every((type, index) => type === "*" || type === have[index])) return helper;
2107
- }
2108
- }
2109
- function expectedRls(policies, sql, indexes = []) {
2110
- const tables = [...new Set(policies.map((item) => normalizeTableName(item.table)))];
2111
- const grants = {};
2112
- for (const table of tables) {
2113
- const byRole = {};
2114
- for (const role of ROLES) {
2115
- const commands = new Set(policies.filter((item) => normalizeTableName(item.table) === table && item.effect === "allow" && item.roles.includes(role)).map((item) => item.command));
2116
- byRole[role] = PRIVILEGES.filter((privilege) => commands.has(privilege));
2117
- }
2118
- grants[table] = byRole;
2119
- }
2120
- return {
2121
- policies: policies.map((item) => ({
2122
- table: normalizeTableName(item.table),
2123
- name: item.name,
2124
- command: item.command,
2125
- permissive: item.effect === "allow",
2126
- roles: item.roles.toSorted()
2127
- })),
2128
- tables,
2129
- grants,
2130
- helpers: helpersOf(sql),
2131
- indexes: indexes.map((target) => ({
2132
- ...target,
2133
- table: normalizeTableName(target.table)
2134
- }))
2135
- };
2136
- }
2137
- /**
2138
- * One warning per index target no index starts with. A missing index slows the
2139
- * policy down but grants nothing, so these do not fail `verify`.
2140
- */
2141
- function missingIndexes(expected, actual) {
2142
- return expected.indexes.flatMap((target) => {
2143
- const column = target.columns[0];
2144
- const columns = actual.columns?.[target.table];
2145
- return column === void 0 || columns !== void 0 && !columns.includes(column) || actual.leadingColumns[target.table]?.includes(column) === true ? [] : [rlsFinding("index-missing", target.table, column, `${target.table}: no index starts with ${column}, which the policies or helpers filter on; add it, or write it with rls generate --split ...,indexes`, "warning")];
2146
- });
2147
- }
2148
- function sameList(left, right) {
2149
- const a = left.toSorted();
2150
- const b = right.toSorted();
2151
- return a.length === b.length && a.every((item, index) => item === b[index]);
2152
- }
2153
- /**
2154
- * One finding per difference; policy expressions are not compared, since
2155
- * Postgres rewrites their text.
2156
- */
2157
- function diffRls(expected, actual, options = {}) {
2158
- const out = [];
2159
- const found = new Map(actual.policies.map((item) => [`${item.table}\u0000${item.name}`, item]));
2160
- for (const want of expected.policies) {
2161
- const have = found.get(`${want.table}\u0000${want.name}`);
2162
- if (have === void 0) {
2163
- out.push(rlsFinding("policy-missing", want.table, want.name, `${want.table}: policy ${want.name} is missing`));
2164
- continue;
2165
- }
2166
- if (have.command !== want.command) out.push(rlsFinding("policy-command", want.table, want.name, `${want.table}: policy ${want.name} is for ${have.command}, expected ${want.command}`));
2167
- if (have.permissive !== want.permissive) out.push(rlsFinding("policy-mode", want.table, want.name, `${want.table}: policy ${want.name} is ${have.permissive ? "permissive" : "restrictive"}, expected ${want.permissive ? "permissive" : "restrictive"}`));
2168
- if (!sameList(have.roles, want.roles)) out.push(rlsFinding("policy-roles", want.table, want.name, `${want.table}: policy ${want.name} applies to ${have.roles.join(", ")}, expected ${want.roles.join(", ")}`));
2169
- }
2170
- const wanted = new Set(expected.policies.map((item) => `${item.table}\u0000${item.name}`));
2171
- for (const have of actual.policies) if (expected.tables.includes(have.table) && !wanted.has(`${have.table}\u0000${have.name}`)) out.push(rlsFinding("policy-extra", have.table, have.name, `${have.table}: policy ${have.name} is not generated (${have.permissive ? "permissive" : "restrictive"} ${have.command}); a permissive one widens access`));
2172
- for (const table of expected.tables) {
2173
- if (actual.rlsEnabled[table] !== true) {
2174
- out.push(actual.rlsEnabled[table] === void 0 ? rlsFinding("table-missing", table, "table", `${table}: table is missing`) : rlsFinding("rls-disabled", table, "table", `${table}: row level security is disabled`));
2175
- continue;
2176
- }
2177
- for (const role of ROLES) {
2178
- const want = expected.grants[table]?.[role] ?? [];
2179
- const have = actual.grants[table]?.[role] ?? [];
2180
- for (const privilege of want) if (!have.includes(privilege) && !(privilege === "select" && options.columnGrants === true)) out.push(rlsFinding("grant-missing", table, `${role}.${privilege}`, `${table}: ${role} lacks ${privilege}, so the policy answers 42501 instead of filtering`));
2181
- for (const privilege of have) if (!want.includes(privilege)) out.push(rlsFinding("grant-extra", table, `${role}.${privilege}`, `${table}: ${role} holds ${privilege}, which no generated policy allows`));
2182
- }
2183
- }
2184
- for (const helper of expected.helpers) {
2185
- const have = matchHelper(helper, actual.helpers);
2186
- if (have === void 0) {
2187
- out.push(rlsFinding("helper-missing", helper, "helper", `${helper}: helper is missing`));
2188
- continue;
2189
- }
2190
- if (!have.securityDefiner) out.push(rlsFinding("helper-definer", helper, "helper", `${helper}: helper is not security definer`));
2191
- if (!have.emptySearchPath) out.push(rlsFinding("helper-search-path", helper, "helper", `${helper}: helper does not set search_path = ''`));
2192
- }
2193
- return out;
2194
- }
2195
- const POLICIES_SQL = `select schemaname || '.' || tablename as target, policyname, cmd, permissive, roles::text[] as roles
2196
- from pg_policies
2197
- where schemaname || '.' || tablename = any($1::text[])`;
2198
- const TABLES_SQL = `select n.nspname || '.' || c.relname as target, c.relrowsecurity as enabled
2199
- from pg_class c
2200
- join pg_namespace n on n.oid = c.relnamespace
2201
- where c.relkind in ('r', 'p') and n.nspname || '.' || c.relname = any($1::text[])`;
2202
- const GRANTS_SQL = `select table_schema || '.' || table_name as target, grantee, lower(privilege_type) as privilege
2203
- from information_schema.role_table_grants
2204
- where grantee in ('anon', 'anonymous', 'authenticated')
2205
- and lower(privilege_type) in ('select', 'insert', 'update', 'delete')
2206
- and table_schema || '.' || table_name = any($1::text[])`;
2207
- const HELPERS_SQL = `select n.nspname || '.' || p.proname || '(' || oidvectortypes(p.proargtypes) || ')' as target, p.prosecdef as definer,
2208
- coalesce(array_to_string(p.proconfig, ','), '') as config
2209
- from pg_proc p
2210
- join pg_namespace n on n.oid = p.pronamespace
2211
- where n.nspname || '.' || p.proname = any($1::text[])`;
2212
- function commandOf(cmd) {
2213
- const text = typeof cmd === "string" ? cmd.toLowerCase() : "";
2214
- return text === "*" ? "all" : text;
2215
- }
2216
- function connectIntrospect(db) {
2217
- return connectPgPool(db, "permdock rls verify --introspect");
2218
- }
2219
- /**
2220
- * Reads the catalogs for the tables and helpers `expected` names
2221
- * (postgres-meta's queries, trimmed).
2222
- */
2223
- async function introspectRls(db, expected, connect = connectIntrospect) {
2224
- const client = await connect(db);
2225
- try {
2226
- const tables = [...expected.tables];
2227
- const indexed = [...new Set(expected.indexes.map((target) => target.table))];
2228
- const [policies, enabled, grants, helpers, indexes, columns] = await Promise.all([
2229
- client.query(POLICIES_SQL, [tables]),
2230
- client.query(TABLES_SQL, [tables]),
2231
- client.query(GRANTS_SQL, [tables]),
2232
- client.query(HELPERS_SQL, [[...new Set(expected.helpers.map(nameOfSignature))]]),
2233
- client.query(INDEX_COLUMNS_SQL, [indexed]),
2234
- client.query(COLUMNS_SQL, [indexed])
2235
- ]);
2236
- const columnsOf = {};
2237
- for (const row of columns.rows) (columnsOf[String(row["target"])] ??= []).push(String(row["name"]));
2238
- const leadingColumns = {};
2239
- for (const row of indexes.rows) {
2240
- const lead = (Array.isArray(row["columns"]) ? row["columns"] : []).at(0);
2241
- if (typeof lead === "string") (leadingColumns[String(row["target"])] ??= []).push(lead);
2242
- }
2243
- const byTable = {};
2244
- for (const row of grants.rows) {
2245
- const table = String(row["target"]);
2246
- const role = liveRole(String(row["grantee"]));
2247
- const entry = byTable[table] ??= {};
2248
- (entry[role] ??= []).push(String(row["privilege"]));
2249
- }
2250
- return {
2251
- policies: policies.rows.map((row) => ({
2252
- table: String(row["target"]),
2253
- name: String(row["policyname"]),
2254
- command: commandOf(row["cmd"]),
2255
- permissive: String(row["permissive"]).toUpperCase() === "PERMISSIVE",
2256
- roles: Array.isArray(row["roles"]) ? row["roles"].map((role) => liveRole(String(role))) : []
2257
- })),
2258
- rlsEnabled: Object.fromEntries(enabled.rows.map((row) => [String(row["target"]), row["enabled"] === true])),
2259
- grants: byTable,
2260
- helpers: Object.fromEntries(helpers.rows.map((row) => [signatureOf(nameOfSignature(String(row["target"])), typesOfSignature(String(row["target"]))), {
2261
- securityDefiner: row["definer"] === true,
2262
- emptySearchPath: String(row["config"]).split(",").some((item) => item === "search_path=\"\"" || item === "search_path=''")
2263
- }])),
2264
- leadingColumns,
2265
- columns: columnsOf
2266
- };
2267
- } finally {
2268
- await client.end();
2269
- }
2270
- }
2271
- const WRITES = [
2272
- "insert",
2273
- "update",
2274
- "delete"
2275
- ];
2276
- /**
2277
- * `rls generate` inlines the check in its `<table>_<command>_read_only_actors`
2278
- * policies.
2279
- */
2280
- function inlinesActorCheck(expression) {
2281
- return expression.includes("'act'") && expression.includes("'read_only'");
2282
- }
2283
- /**
2284
- * Each table and write command whose permissive policies reach `authenticated`
2285
- * (or `public`) without the read-only actor check: no restrictive policy for
2286
- * the command calls `permdock_actor_may_write()`, and some permissive one does
2287
- * not.
2288
- */
2289
- function unguardedWrites(policies, fn) {
2290
- const out = [];
2291
- const tables = [...new Set(policies.map((policy) => policy.table))];
2292
- for (const table of tables) for (const command of WRITES) {
2293
- const applying = policies.filter((policy) => policy.table === table && (policy.command === command || policy.command === "all"));
2294
- const permissive = applying.filter((policy) => policy.restrictive !== true && (policy.roles ?? []).some((role) => role === "authenticated" || role === "public"));
2295
- if (permissive.length === 0) continue;
2296
- const calls = (expression) => expression.includes(fn);
2297
- if (!(applying.some((policy) => policy.restrictive === true && (calls(policy.expression) || inlinesActorCheck(policy.expression))) || permissive.every((policy) => calls(policy.expression)))) out.push(rlsFinding("write-unguarded", table, command, `${table}: ${command} policies for authenticated do not call ${fn}(), so a read-only support or impersonation session can write (rls.readOnlyActors)`));
2298
- }
2299
- return out;
2300
- }
2301
- const SYSTEM_SCHEMAS = [
2302
- "pg_catalog",
2303
- "information_schema",
2304
- "pg_toast",
2305
- "auth",
2306
- "storage",
2307
- "realtime",
2308
- "extensions",
2309
- "graphql",
2310
- "graphql_public",
2311
- "vault",
2312
- "pgsodium",
2313
- "pgsodium_masks",
2314
- "net",
2315
- "cron",
2316
- "supabase_functions",
2317
- "supabase_migrations"
2318
- ];
2319
- function inScope(table) {
2320
- const schema = beforeFirst(table, ".");
2321
- return HELPER_TABLES.some((item) => item === table) || !(SYSTEM_SCHEMAS.some((item) => item === schema) || schema.startsWith("pg_"));
2322
- }
2323
- function seedLine(row) {
2324
- return `${row.role} ${row.effect} ${row.grantKey} on ${row.scope}`;
2325
- }
2326
- function seedKey(line) {
2327
- return line.replace(" on ", " ").replaceAll(" ", "/");
2328
- }
2329
- /**
2330
- * Drift is an error; `info` names RLS tables whose policies call no PermDock
2331
- * helper.
2332
- */
2333
- function diffMixed(expected, actual) {
2334
- const drift = [];
2335
- const seeds = `${expected.schema}.role_permissions`;
2336
- const want = new Set(expected.seeds.map(seedLine));
2337
- const have = new Set(actual.seeds.map(seedLine));
2338
- for (const line of want) if (!have.has(line)) drift.push(rlsFinding("seed-missing", seeds, seedKey(line), `${seeds}: missing ${line}`));
2339
- for (const line of have) if (!want.has(line)) drift.push(rlsFinding("seed-extra", seeds, seedKey(line), `${seeds}: unexpected ${line}`));
2340
- const permissions = new Set(expected.permissions);
2341
- const conditioned = new Set(expected.rowConditions);
2342
- const levels = new Map((expected.levels ?? []).map((level) => [level.key, level]));
2343
- const notes = [];
2344
- const covered = /* @__PURE__ */ new Set();
2345
- for (const policy of actual.policies) {
2346
- if (callsHelper(policy.expression)) covered.add(policy.table);
2347
- const blind = new Set(helperCallKeys(policy.expression, true));
2348
- for (const key of helperCallKeys(policy.expression)) {
2349
- const level = levels.get(key);
2350
- if (level !== void 0) {
2351
- if (level.conditioned) notes.push(rlsFinding("level-unconditioned", policy.table, `${policy.name}/${key}`, `${policy.table}: policy ${policy.name} passes ${key}, which skips the level's row condition, so holders of it are denied there; use ${level.rowHelper}(${policy.table.slice(policy.table.lastIndexOf(".") + 1)}, '${level.permission}')`, "info"));
2352
- } else if (!permissions.has(key)) drift.push(rlsFinding("undeclared-key", policy.table, `${policy.name}/${key}`, `${policy.table}: policy ${policy.name} passes ${key}, which the policy does not declare, so it always denies`));
2353
- else if (conditioned.has(key) && blind.has(key)) drift.push(rlsFinding("condition-blind", policy.table, `${policy.name}/${key}`, `${policy.table}: policy ${policy.name} passes ${key}, whose grants carry row conditions the helpers do not check: the policy grants more than the application does`));
2354
- }
2355
- }
2356
- if (expected.readOnlyActors === true) drift.push(...unguardedWrites(actual.policies, ACTOR_MAY_WRITE));
2357
- return {
2358
- drift,
2359
- info: [...notes, ...actual.rlsTables.filter((table) => !covered.has(table)).map((table) => rlsFinding("helper-uncalled", table, "table", `${table}: no policy calls a PermDock helper`, "info"))]
2360
- };
2361
- }
2362
- const ALL_POLICIES_SQL = `select schemaname || '.' || tablename as target, policyname,
2363
- coalesce(qual, '') || ' ' || coalesce(with_check, '') as expression,
2364
- lower(cmd) as command, permissive = 'RESTRICTIVE' as restrictive,
2365
- array_to_string(roles, ',') as roles
2366
- from pg_policies`;
2367
- const RLS_TABLES_SQL = `select n.nspname || '.' || c.relname as target
2368
- from pg_class c
2369
- join pg_namespace n on n.oid = c.relnamespace
2370
- where c.relkind in ('r', 'p') and c.relrowsecurity`;
2371
- const quoteIdent = escapeSqlIdent;
2372
- /**
2373
- * Reads `role_permissions`, `pg_policies` and the RLS-enabled tables for
2374
- * {@link diffMixed}.
2375
- */
2376
- async function introspectMixed(db, schema, connect = connectIntrospect) {
2377
- const client = await connect(db);
2378
- try {
2379
- const [seeds, policies, tables] = await Promise.all([
2380
- client.query(`select role, permission, grant_key, scope, effect from ${quoteIdent(schema)}.role_permissions`, []),
2381
- client.query(ALL_POLICIES_SQL, []),
2382
- client.query(RLS_TABLES_SQL, [])
2383
- ]);
2384
- return {
2385
- seeds: seeds.rows.map((row) => ({
2386
- role: String(row["role"]),
2387
- permission: String(row["permission"]),
2388
- grantKey: String(row["grant_key"]),
2389
- scope: String(row["scope"]),
2390
- effect: String(row["effect"]) === "deny" ? "deny" : "allow"
2391
- })),
2392
- policies: policies.rows.map((row) => ({
2393
- table: String(row["target"]),
2394
- name: String(row["policyname"]),
2395
- expression: String(row["expression"]),
2396
- command: String(row["command"]),
2397
- restrictive: row["restrictive"] === true,
2398
- roles: (typeof row["roles"] === "string" ? row["roles"] : "").split(",").filter((role) => role !== "")
2399
- })).filter((row) => inScope(row.table)),
2400
- rlsTables: tables.rows.map((row) => String(row["target"])).filter(inScope).toSorted()
2401
- };
2402
- } finally {
2403
- await client.end();
2404
- }
2405
- }
2406
- //#endregion
2407
- //#region src/cli/rls/rls.ts
2408
- /** `rls migrate` and `rls import` read the pgsql-parser 18 AST. */
2409
- const PGSQL_PARSER_MAJOR = 18;
2410
- const RLS_HELP = `permdock rls generate | import | verify | migrate | explain
2411
-
2412
- generate Compile the policy into RLS policies and helpers
2413
- import Turn existing policies (--sql or --db-url-stdin) into a permissions module
2414
- verify Run the fixtures, or compare a live database with --introspect
2415
- migrate Rewrite the rls.migrate helpers' calls onto the generated helpers
2416
- explain Show the tables, membership sources, custom roles and triggers the SQL binds to
2417
-
2418
- Run permdock rls <command> --help for its flags.
2419
- Never emits service_role, except in the execute grant rls.trustedReaders asks for. memberOf compiles through the dialect memberships mapping.
2420
- `;
2421
- function asTarget(value) {
2422
- if (value === void 0 || value === "sql" || value === "drizzle" || value === "prisma") return value ?? "sql";
2423
- }
2424
- function asDialect(value) {
2425
- if (value === void 0 || value === "supabase" || value === "neon" || value === "guc") return value ?? "supabase";
2426
- }
2427
- /** `--split`, else `rls.split` for the SQL target. */
2428
- function splitOf(input, target) {
2429
- if (input.split !== void 0) return { split: input.split };
2430
- const configured = input.config.rls?.split;
2431
- return configured === void 0 || target !== "sql" ? {} : { split: configured.join(",") };
2432
- }
2433
- function generateInput(input, target, dialect) {
2434
- return {
2435
- cwd: input.cwd,
2436
- config: input.config,
2437
- target,
2438
- dialect,
2439
- rbac: input.rbac,
2440
- ...input.rbacSchema === void 0 ? {} : { rbacSchema: input.rbacSchema },
2441
- ...input.authorize === void 0 ? {} : { authorize: parseRbacAuthorize(input.authorize) ?? "database" },
2442
- check: input.check,
2443
- skipClosures: input.skipClosures,
2444
- inlineFunctions: input.inlineFunctions,
2445
- force: input.force,
2446
- io: input.io,
2447
- ...input.out === void 0 ? {} : { out: input.out },
2448
- ...input.from === void 0 ? {} : { from: input.from },
2449
- ...input.project === void 0 ? {} : { project: input.project },
2450
- ...input.url === void 0 ? {} : { url: input.url },
2451
- json: input.json,
2452
- ...input.memberships === void 0 ? {} : { memberships: input.memberships },
2453
- ...input.gucPrefix === void 0 ? {} : { gucPrefix: input.gucPrefix },
2454
- policyPerRole: input.policyPerRole,
2455
- ...input.policyName === void 0 ? {} : { policyName: input.policyName },
2456
- ...input.tenantType === void 0 ? {} : { tenantType: input.tenantType },
2457
- customRoles: input.customRoles,
2458
- capabilities: input.capabilities,
2459
- ...input.fields === void 0 ? {} : { fields: input.fields },
2460
- revokeColumns: input.revokeColumns,
2461
- ...splitOf(input, target),
2462
- ...isSupabaseSchemas(input.schemas) ? { schemas: input.schemas } : {},
2463
- ...input.grantsOut === void 0 ? {} : { grantsOut: input.grantsOut },
2464
- ...input.seedsOut === void 0 ? {} : { seedsOut: input.seedsOut },
2465
- ...input.noSeeds === true ? { noSeeds: true } : {},
2466
- ...input.backfillOut === void 0 ? {} : { backfillOut: input.backfillOut },
2467
- helpersOnly: input.helpersOnly,
2468
- shims: input.shims === true
2469
- };
2470
- }
2471
- async function explain(input) {
2472
- const dialect = asDialect(input.dialect ?? input.config.rls?.dialect);
2473
- if (dialect === void 0) return {
2474
- code: 2,
2475
- output: "rls explain --dialect (or rls.dialect) must be supabase, neon or guc"
2476
- };
2477
- const generated = await runRlsGenerate({
2478
- ...generateInput(input, "sql", dialect),
2479
- check: false,
2480
- write: false
2481
- });
2482
- if (generated.explain === void 0) return {
2483
- code: generated.code,
2484
- output: generated.output
2485
- };
2486
- let report = generated.explain;
2487
- if (input.db !== void 0) try {
2488
- const facts = await readTableIndexFacts(input.db, report.bindings.map((binding) => binding.table), input.connect);
2489
- report = {
2490
- ...report,
2491
- bindings: report.bindings.map((binding) => ({
2492
- ...binding,
2493
- exists: facts.columns[binding.table] !== void 0
2494
- }))
2495
- };
2496
- } catch (cause) {
2497
- return {
2498
- code: exitCodeOfError(cause),
2499
- output: describeError(cause)
2500
- };
2501
- }
2502
- return {
2503
- code: 0,
2504
- output: input.json ? JSON.stringify(report, null, 2) : describeExplain(report)
2505
- };
2506
- }
2507
- async function migrate(input) {
2508
- const config = input.config.rls?.migrate;
2509
- if (config === void 0) return {
2510
- code: 2,
2511
- output: "rls migrate needs rls.migrate.helpers in permdock.config.ts"
2512
- };
2513
- if (input.sql === void 0) return {
2514
- code: 2,
2515
- output: "rls migrate needs --sql <dir>"
2516
- };
2517
- const dialect = asDialect(input.dialect ?? input.config.rls?.dialect);
2518
- if (dialect === void 0) return {
2519
- code: 2,
2520
- output: "rls migrate --dialect (or rls.dialect) must be supabase, neon or guc"
2521
- };
2522
- const generated = await runRlsGenerate({
2523
- ...generateInput(input, "sql", dialect),
2524
- check: false,
2525
- write: false
2526
- });
2527
- if (generated.code !== 0) return {
2528
- code: 2,
2529
- output: generated.output
2530
- };
2531
- await requirePeer(() => import("pgsql-parser"), "pgsql-parser", "permdock rls migrate", input.cwd, PGSQL_PARSER_MAJOR);
2532
- const { migrateTarget, runRlsMigrate } = await import("./migrate-DVsxeE0y.js");
2533
- return runRlsMigrate({
2534
- cwd: input.cwd,
2535
- sql: input.sql,
2536
- config,
2537
- target: {
2538
- ...migrateTarget(generated),
2539
- ...input.config.rls?.roleValues === void 0 ? {} : { roleValues: input.config.rls.roleValues }
2540
- },
2541
- write: input.write,
2542
- force: input.forceRewrite === true,
2543
- json: input.json,
2544
- retireOut: input.retireOut,
2545
- ...input.io.now === void 0 ? {} : { now: input.io.now() }
2546
- });
2547
- }
2548
- /**
2549
- * `verify --introspect` with `--helpers-only`: helpers and seeds exactly,
2550
- * hand-written policies by their keys.
2551
- */
2552
- async function introspectHelpersOnly(db, expected, generated, connect, readOnlyActors, ignore) {
2553
- const schema = generated.schema ?? "permdock";
2554
- try {
2555
- const actual = await introspectRls(db, expected, connect);
2556
- const helpers = diffRls(expected, actual);
2557
- const warnings = missingIndexes(expected, actual);
2558
- const mixed = diffMixed({
2559
- schema,
2560
- seeds: generated.seeds ?? [],
2561
- permissions: generated.keys?.permissions ?? [],
2562
- rowConditions: generated.keys?.rowConditions ?? [],
2563
- levels: generated.keys?.levels ?? [],
2564
- readOnlyActors
2565
- }, await introspectMixed(db, schema, connect));
2566
- return verifyResult({
2567
- findings: [
2568
- ...helpers,
2569
- ...mixed.drift,
2570
- ...warnings,
2571
- ...mixed.info
2572
- ],
2573
- ignore,
2574
- summary: `introspected ${String(expected.helpers.length)} helper(s) and ${String(generated.seeds?.length ?? 0)} seeded row(s), helpers only: no drift`
2575
- });
2576
- } catch (cause) {
2577
- return usageResult(cause);
2578
- }
2579
- }
2580
- /**
2581
- * `verify --introspect`: the catalogs against what `generate` would write with
2582
- * the same flags.
2583
- */
2584
- async function introspect(input, ignore) {
2585
- if (input.db === void 0) return {
2586
- code: 2,
2587
- output: "PermDock CLI: rls verify --introspect needs a database: --db-url-stdin, DATABASE_URL or SUPABASE_DB_URL"
2588
- };
2589
- const dialect = asDialect(input.dialect ?? input.config.rls?.dialect);
2590
- if (dialect === void 0) return {
2591
- code: 2,
2592
- output: "rls verify --dialect (or rls.dialect) must be supabase, neon or guc"
2593
- };
2594
- const generated = await runRlsGenerate({
2595
- ...generateInput(input, "sql", dialect),
2596
- check: false,
2597
- write: false
2598
- });
2599
- if (generated.code !== 0 || generated.policies === void 0) return {
2600
- code: 2,
2601
- output: generated.output
2602
- };
2603
- const expected = expectedRls(generated.policies, generated.text, generated.indexes);
2604
- if (generated.helpersOnly === true) return introspectHelpersOnly(input.db, expected, generated, input.connect, readOnlyActorKinds(input.config.rls?.readOnlyActors) !== void 0, ignore);
2605
- try {
2606
- const actual = await introspectRls(input.db, expected, input.connect);
2607
- const drift = diffRls(expected, actual, { columnGrants: (input.fields ?? input.config.rls?.fields) !== void 0 });
2608
- return verifyResult({
2609
- findings: [...drift, ...missingIndexes(expected, actual)],
2610
- ignore,
2611
- summary: `introspected ${String(expected.policies.length)} policies on ${String(expected.tables.length)} table(s) and ${String(expected.helpers.length)} helper(s): no drift`
2612
- });
2613
- } catch (cause) {
2614
- return usageResult(cause);
2615
- }
2616
- }
2617
- async function runRls(input) {
2618
- const action = input.rest[0];
2619
- if (action === void 0 || action === "help") return {
2620
- code: 2,
2621
- output: RLS_HELP
2622
- };
2623
- const badSchemas = schemasRefusal(`rls ${action}`, input.schemas);
2624
- if (badSchemas !== void 0) return {
2625
- code: 2,
2626
- output: badSchemas
2627
- };
2628
- switch (action) {
2629
- case "generate": {
2630
- const target = asTarget(input.target);
2631
- const dialect = asDialect(input.dialect ?? input.config.rls?.dialect);
2632
- if (target === void 0) return {
2633
- code: 2,
2634
- output: "rls generate --target must be drizzle, sql or prisma"
2635
- };
2636
- if (dialect === void 0) return {
2637
- code: 2,
2638
- output: "rls generate --dialect (or rls.dialect) must be supabase, neon or guc"
2639
- };
2640
- return runRlsGenerate({
2641
- ...generateInput(input, target, dialect),
2642
- ...input.db === void 0 ? {} : { db: input.db },
2643
- ...input.connect === void 0 ? {} : { connect: input.connect }
2644
- });
2645
- }
2646
- case "import": {
2647
- await requirePeer(() => import("pgsql-parser"), "pgsql-parser", "permdock rls import", input.cwd, PGSQL_PARSER_MAJOR);
2648
- const { runRlsImport } = await import("./import-BYYXmHvP.js");
2649
- return runRlsImport({
2650
- cwd: input.cwd,
2651
- config: input.config,
2652
- schema: input.schema ?? "zod",
2653
- io: input.io,
2654
- ...input.sql === void 0 ? {} : { sql: input.sql },
2655
- ...input.db === void 0 ? {} : { db: input.db },
2656
- ...input.out === void 0 ? {} : { out: input.out },
2657
- ...input.memberships === void 0 ? {} : { memberships: input.memberships },
2658
- ...input.connect === void 0 ? {} : { connect: input.connect }
2659
- });
2660
- }
2661
- case "verify": {
2662
- if (input.advisors === true) return runRlsAdvisors({
2663
- cwd: input.cwd,
2664
- json: input.json,
2665
- env: input.io.env ?? process.env,
2666
- ...input.io.signal === void 0 ? {} : { signal: input.io.signal },
2667
- ...input.db === void 0 ? {} : { db: input.db },
2668
- ...input.exec === void 0 ? {} : { exec: input.exec }
2669
- });
2670
- const ignore = verifyIgnores(input.config, input.ignore);
2671
- if (input.introspect) return introspect(input, ignore);
2672
- const format = input.format ?? "node";
2673
- if (format !== "node" && format !== "pgtap") return {
2674
- code: 2,
2675
- output: "rls verify --format must be pgtap or node"
2676
- };
2677
- return await runRlsVerify({
2678
- cwd: input.cwd,
2679
- config: input.config,
2680
- format,
2681
- tree: input.tree,
2682
- io: input.io,
2683
- ...input.out === void 0 ? {} : { out: input.out },
2684
- ...input.fixtures === void 0 ? {} : { fixtures: input.fixtures },
2685
- ...input.db === void 0 ? {} : { db: input.db },
2686
- ...input.from === void 0 ? {} : { from: input.from },
2687
- ...input.connect === void 0 ? {} : { connect: input.connect },
2688
- ignore
2689
- });
2690
- }
2691
- case "migrate": return migrate(input);
2692
- case "explain": return explain(input);
2693
- default: return {
2694
- code: 2,
2695
- output: RLS_HELP
2696
- };
2697
- }
2698
- }
2699
- //#endregion
2700
- export { runRls };