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,4002 +0,0 @@
1
- import { c as listPermissions, h as formerKeys } from "./permission-registry-B8tYxPIt.js";
2
- import { a as expandRelation, c as isEdgeRelation, d as isSelfParented, l as isFieldRelation, o as groupEntries, p as restrictedFor, u as isPrincipalRelation } from "./resource-relations-8-pCScBO.js";
3
- import { o as flattenGrantee } from "./grantee-OG4klcNr.js";
4
- import { c as rootScope, d as scopeList, l as scopeChain, s as resolveScope } from "./scopes-gdH__vDZ.js";
5
- import { r as relationCondition, t as inheritCondition } from "./grantee-conditions-Dzprappv.js";
6
- import { l as partitionsOf, p as scopeField } from "./tenancy-BlxY5T0q.js";
7
- import { a as delegatedScopeMap } from "./permdock-B3zE16To.js";
8
- import { i as configError } from "./errors-BhRkoNS7.js";
9
- import { d as sqlTextArray, i as qualifySqlTable, t as SQL_IDENT } from "./sql-0WjxIp9g.js";
10
- import { a as scopeMembershipTable, d as restrictedRowsSql, i as scopeColumn, l as relationArmSql } from "./compile-Cvru58id.js";
11
- import { d as keptKeys, l as roleColumn, t as AUTHZ_VERSION_TABLE, u as roleManifest } from "./sources-C4vkzZJV.js";
12
- import { A as quoteQualified, D as qualified, E as helperSchema, L as scopeTypeOf, O as quoteIdent, _ as subjectClaimJsonSql, d as keyTenantSql, f as kindFilterSql, h as roleKindSql, i as allowEntry, j as quoteTable, k as quoteLiteral, m as memberVia, n as GLOBAL_ROLES, o as rootName, r as HELPERS, s as signedIn, t as CUSTOM_ROLES, u as globalKindFilterSql, v as subjectClaimSql, w as CLI, x as userIdHelperSql, y as subjectIdSql, z as tenantTypeOf } from "./shared-DfaIWvIJ.js";
13
- //#region src/cli/sql/active.ts
14
- function checkActiveRow(label, row) {
15
- quoteTable(row.table);
16
- quoteIdent(row.id);
17
- if (row.disabledAt !== void 0) quoteIdent(row.disabledAt);
18
- if (row.status !== void 0) {
19
- quoteIdent(row.status);
20
- if (row.active === void 0 || row.active.length === 0) throw configError(`PermDock CLI: ${label}.status needs the active values in ${label}.active`);
21
- }
22
- if (row.disabledAt === void 0 && row.status === void 0) throw configError(`PermDock CLI: ${label} needs disabledAt or status to tell an active row`);
23
- }
24
- /** Validates `rls.suspension` and keys its scopes by declared name. */
25
- function checkSuspension(suspension, scopes) {
26
- if (suspension === void 0) return;
27
- if (suspension.users !== void 0) checkActiveRow("rls.suspension.users", suspension.users);
28
- const byName = {};
29
- for (const [key, row] of Object.entries(suspension.scopes ?? {})) {
30
- const name = resolveScope(scopes, key);
31
- if (name === void 0) throw configError(`PermDock CLI: rls.suspension.scopes.${key} names a scope the policy does not declare`);
32
- checkActiveRow(`rls.suspension.scopes.${key}`, row);
33
- if (row.keep !== void 0 && !Array.isArray(row.keep)) throw configError(`PermDock CLI: rls.suspension.scopes.${key}.keep is a list of permissions or permission keys`);
34
- const keep = keptKeys(row);
35
- const { keep: _given, ...active } = row;
36
- byName[name] = keep.length === 0 ? active : {
37
- ...active,
38
- keep
39
- };
40
- }
41
- const memberships = suspension.memberships;
42
- if (memberships?.keep !== void 0 && !Array.isArray(memberships.keep)) throw configError("PermDock CLI: rls.suspension.memberships.keep is a list of permissions or permission keys");
43
- const keep = keptKeys(memberships);
44
- return {
45
- ...suspension.users === void 0 ? {} : { users: suspension.users },
46
- ...Object.keys(byName).length === 0 ? {} : { scopes: byName },
47
- ...keep.length === 0 ? {} : { memberships: { keep } }
48
- };
49
- }
50
- function disabledKeep(ctx) {
51
- return keptKeys(ctx.suspension?.memberships);
52
- }
53
- function activeMembershipSql(ctx, disabledAt, permission = ctx.permission === void 0 ? void 0 : { key: ctx.permission }) {
54
- if (disabledAt === void 0) return [];
55
- const keep = disabledKeep(ctx);
56
- if (permission !== void 0 && "key" in permission && keep.includes(permission.key)) return [];
57
- return permission !== void 0 && "sql" in permission && keep.length > 0 ? [`(${disabledAt} is null or ${permission.sql} = any(array[${keep.map(quoteLiteral).join(", ")}]::text[]))`] : [`${disabledAt} is null`];
58
- }
59
- function keptRowSql(keep, permission) {
60
- const kind = `coalesce(jsonb_typeof(${keep}), 'null')`;
61
- if (permission === void 0) return `${kind} = 'null'`;
62
- return `case ${kind} when 'null' then true when 'array' then ${keep} @> jsonb_build_array(${"key" in permission ? quoteLiteral(permission.key) : permission.sql}) else false end`;
63
- }
64
- /**
65
- * Whether `id` is among the active rows' ids: a missing row is suspended, so
66
- * the check fails closed, and so does a null `id`. `id` stays outside the
67
- * subquery so a column of the same name on `row.table` cannot capture it.
68
- */
69
- function activeRowSql(row, id) {
70
- const table = quoteTable(qualifySqlTable(row.table));
71
- const parts = [];
72
- if (row.disabledAt !== void 0) parts.push(`s.${quoteIdent(row.disabledAt)} is null`);
73
- if (row.status !== void 0) {
74
- const values = (row.active ?? []).map(quoteLiteral).join(", ");
75
- parts.push(`s.${quoteIdent(row.status)}::text = any(array[${values}]::text[])`);
76
- }
77
- const where = parts.length === 0 ? "" : ` where ${parts.join(" and ")}`;
78
- return `coalesce(${id} in (select s.${quoteIdent(row.id)} from ${table} s${where}), false)`;
79
- }
80
- function activeJoin(row, id, alias) {
81
- const table = quoteTable(qualifySqlTable(row.table));
82
- const parts = [`${alias}.${quoteIdent(row.id)} = ${id}`];
83
- if (row.disabledAt !== void 0) parts.push(`${alias}.${quoteIdent(row.disabledAt)} is null`);
84
- if (row.status !== void 0) {
85
- const values = (row.active ?? []).map(quoteLiteral).join(", ");
86
- parts.push(`${alias}.${quoteIdent(row.status)}::text = any(array[${values}]::text[])`);
87
- }
88
- return `join ${table} ${alias} on ${parts.join(" and ")}`;
89
- }
90
- function activeUserChecks(ctx, user, alias, indent) {
91
- const row = ctx.suspension?.users;
92
- return row === void 0 ? {
93
- joins: [],
94
- filters: []
95
- } : {
96
- joins: [`${indent}${activeJoin(row, user, alias)}`],
97
- filters: []
98
- };
99
- }
100
- function activeInstanceChecks(ctx, scope, idOf, aliasOf, indent, permission = ctx.permission === void 0 ? void 0 : { key: ctx.permission }) {
101
- const joins = [];
102
- const filters = [];
103
- for (const name of scopeChain(ctx.scopes, scope)) {
104
- const row = ctx.suspension?.scopes?.[name];
105
- if (row === void 0) continue;
106
- const id = idOf(name);
107
- if (id === void 0) throw configError(`PermDock CLI: rls.suspension.scopes.${name} needs the ${name} id on ${scope} memberships: add columns.${name} to the ${scope} memberships table`);
108
- const keep = keptKeys(row);
109
- if (permission !== void 0 && "key" in permission && keep.includes(permission.key)) continue;
110
- const cast = `(${id})::${scopeTypeOf(ctx, name)}`;
111
- if (keep.length === 0) {
112
- joins.push(`${indent}${activeJoin(row, cast, aliasOf(name))}`);
113
- continue;
114
- }
115
- const active = activeRowSql(row, cast);
116
- filters.push(permission !== void 0 && "sql" in permission ? `(${active} or ${permission.sql} = any(array[${keep.map(quoteLiteral).join(", ")}]::text[]))` : active);
117
- }
118
- return {
119
- joins,
120
- filters
121
- };
122
- }
123
- /** The active-user check for `user`; empty without `rls.suspension.users`. */
124
- function activeUserSql(ctx, user = subjectIdSql(ctx)) {
125
- const row = ctx.suspension?.users;
126
- return row === void 0 ? [] : [activeRowSql(row, user)];
127
- }
128
- /**
129
- * The permission of a grant key held in `grant`: `key#group` and `key@level`
130
- * name `key`.
131
- */
132
- function grantPermissionSql(grant) {
133
- return { sql: `split_part(split_part(${grant}, '#', 1), '@', 1)` };
134
- }
135
- /**
136
- * The active-instance check for every suspendable scope on `scope`'s chain: its
137
- * own and each ancestor's. `idOf` gives the SQL for the id the membership holds
138
- * for a scope on that chain. A scope's `keep` lets `permission` through a
139
- * suspended instance: a kept key known now drops its check, and one read at run
140
- * time is compared with the kept keys.
141
- */
142
- function activeInstancesSql(ctx, scope, idOf, permission = ctx.permission === void 0 ? void 0 : { key: ctx.permission }) {
143
- const parts = [];
144
- for (const name of scopeChain(ctx.scopes, scope)) {
145
- const row = ctx.suspension?.scopes?.[name];
146
- if (row === void 0) continue;
147
- const id = idOf(name);
148
- if (id === void 0) throw configError(`PermDock CLI: rls.suspension.scopes.${name} needs the ${name} id on ${scope} memberships: add columns.${name} to the ${scope} memberships table`);
149
- const keep = keptKeys(row);
150
- if (permission !== void 0 && "key" in permission && keep.includes(permission.key)) continue;
151
- const active = activeRowSql(row, `(${id})::${scopeTypeOf(ctx, name)}`);
152
- parts.push(permission !== void 0 && "sql" in permission && keep.length > 0 ? `(${active} or ${permission.sql} = any(array[${keep.map(quoteLiteral).join(", ")}]::text[]))` : active);
153
- }
154
- return parts;
155
- }
156
- //#endregion
157
- //#region src/cli/sql/names.ts
158
- /** The closure table graph grants read. Part of the SQL contract. */
159
- const CLOSURE = { table: "permdock_closure" };
160
- /**
161
- * The snake_case SQL name of a resource or link (`chatThread` becomes
162
- * `chat_thread`), or `undefined` when it is not made of ASCII letters, digits
163
- * and underscores starting with a letter.
164
- */
165
- function graphSqlName(name) {
166
- if (!/^[A-Za-z][A-Za-z0-9_]*$/u.test(name)) return;
167
- return name.replaceAll(/([a-z0-9])([A-Z])/gu, "$1_$2").replaceAll(/([A-Z]+)([A-Z][a-z])/gu, "$1_$2").toLowerCase();
168
- }
169
- function sqlNameOf(name, label) {
170
- const sql = graphSqlName(name);
171
- if (sql === void 0) throw configError(`PermDock CLI: ${label} is not a SQL name (letters, digits and underscores, starting with a letter), so rls generate cannot name its helper`);
172
- return sql;
173
- }
174
- /**
175
- * The helper returning the ids of `resource` the subject holds a relation on:
176
- * `permitted_<snake_case resource>_ids`.
177
- */
178
- function graphHelper(resource) {
179
- return permittedIdsHelper(sqlNameOf(resource, `resource '${resource}'`));
180
- }
181
- function inheritedRowsHelper(resource) {
182
- return `permitted_${sqlNameOf(resource, `resource '${resource}'`)}_rows`;
183
- }
184
- /**
185
- * The helper returning the ids of `resource` whose `link` points into the ids
186
- * it is given.
187
- */
188
- function linkHelper(resource, link) {
189
- return `permdock_link_${sqlNameOf(resource, `resource '${resource}'`)}_${sqlNameOf(link, `link '${link}' on ${resource}`)}`;
190
- }
191
- function restrictedHelper(resource) {
192
- return `permdock_restricted_${sqlNameOf(resource, `resource '${resource}'`)}`;
193
- }
194
- /**
195
- * Graph SQL parts as RLS text: values inline as literals, the subject from the
196
- * dialect's claim.
197
- */
198
- function graphSqlText(parts, ctx) {
199
- return parts.map((part) => {
200
- if ("text" in part) return part.text;
201
- if ("column" in part) return quoteIdent(part.column);
202
- if ("subject" in part) return subjectIdSql(ctx);
203
- return typeof part.value === "string" ? quoteLiteral(part.value) : String(part.value);
204
- }).join("");
205
- }
206
- /**
207
- * The role column of an `rls.memberships` table aliased `alias`; a `through`
208
- * column joins its roles table as `<alias>k`, after a newline and `indent`
209
- * (inline without one).
210
- */
211
- function memberRoleOf(table, alias = "m", indent) {
212
- return roleColumn(table.role, qualifySqlTable(table.table), alias, {
213
- label: `rls.memberships ${table.table} role`,
214
- prefix: CLI,
215
- ...indent === void 0 ? {} : { indent }
216
- });
217
- }
218
- /** The schema-qualified name of a table under `search_path = ''`. */
219
- /** The helper returning the ids of scope `name` a grant key reaches. */
220
- function permittedIdsHelper(name) {
221
- if (!/^[a-z][a-z0-9_]*$/u.test(name)) throw configError(`PermDock CLI: unsafe scope name '${name}'`);
222
- return `permitted_${name}_ids`;
223
- }
224
- /**
225
- * `permitted_<scope>_ids_for(p_user, p_grant)`: the same ids for a user the
226
- * caller names.
227
- */
228
- function permittedForHelper(name) {
229
- return `${permittedIdsHelper(name)}_for`;
230
- }
231
- /**
232
- * The helper returning the ids of scope `name` the subject holds any live
233
- * membership of.
234
- */
235
- function memberIdsHelper(name) {
236
- if (!/^[a-z][a-z0-9_]*$/u.test(name)) throw configError(`PermDock CLI: unsafe scope name '${name}'`);
237
- return `member_${name}_ids`;
238
- }
239
- /**
240
- * `member_<scope>_ids_for(p_user uuid)`: the same rows for a user the caller
241
- * names; the token hook's helper.
242
- */
243
- function memberForHelper(name) {
244
- return `${memberIdsHelper(name)}_for`;
245
- }
246
- /**
247
- * `member_<scope>_ids_of(p_user uuid)`: `member_<scope>_ids_for(p_user)` when
248
- * `p_user` is the caller and no rows otherwise, so `authenticated` may execute
249
- * it; better-supabase's `teamIdsOf` template calls it.
250
- */
251
- function memberOfHelper(name) {
252
- return `${memberIdsHelper(name)}_of`;
253
- }
254
- /** A scope better-supabase reads as its teams: `team` or `teams` (doctor BS417). */
255
- function isTeamScope(name) {
256
- return /^teams?$/u.test(name);
257
- }
258
- /**
259
- * Whether `member_<scope>_ids_of` is generated: a team scope with
260
- * `member_<scope>_ids_for`.
261
- */
262
- function hasMemberOf(input, name) {
263
- return isTeamScope(name) && hasMemberFor(input, name);
264
- }
265
- /**
266
- * Whether `member_<scope>_ids_for` is generated for `name`: Supabase only (its
267
- * one caller is `supabase_auth_admin`), and only where `memberships` maps a
268
- * table for the scope or a membership source can hold it.
269
- */
270
- function hasMemberFor(input, name) {
271
- if (input.dialect !== "supabase") return false;
272
- return memberForTable(input, name) !== void 0 || memberForSources(input, name).length > 0;
273
- }
274
- /**
275
- * Whether `permitted_<scope>_users` can list the members of one instance of
276
- * `name`: a mapped membership table, or sources that all read a table.
277
- */
278
- function hasPermittedUsers(input, name) {
279
- if (memberForTable(input, name) !== void 0) return true;
280
- const sources = memberForSources(input, name);
281
- return sources.length > 0 && sources.every((source) => source.sql.holders !== void 0);
282
- }
283
- /**
284
- * The table `member_<scope>_ids_for` reads for scope `name`, when `memberships`
285
- * maps one with its id column.
286
- */
287
- function memberForTable(input, name) {
288
- const table = scopeMembershipTable(input.memberships, input.scopes, name);
289
- return table !== void 0 && scopeColumn(table, input.scopes, name) !== void 0 ? table : void 0;
290
- }
291
- /**
292
- * The sources `member_<scope>_ids_for` reads: none when a table is mapped, as
293
- * in `database` mode.
294
- */
295
- function memberForSources(input, name) {
296
- if (memberForTable(input, name) !== void 0) return [];
297
- return (input.memberSources ?? []).filter((source) => source.sql.scope === void 0 || source.sql.scope === name);
298
- }
299
- /**
300
- * The membership sources that can hold scope `name` when `memberships` maps no
301
- * table for it: every `tableMembershipSource` source and the
302
- * `junctionMembershipSource` sources of that scope. Empty outside `database`
303
- * mode.
304
- */
305
- function scopeSources(ctx, name) {
306
- if (ctx.authorize !== "database" || scopeTable(ctx, name) !== void 0) return [];
307
- return (ctx.sources ?? []).filter((source) => source.sql.scope === void 0 || source.sql.scope === name);
308
- }
309
- /**
310
- * The membership table mapped for scope `name`, with the column of its id and
311
- * of the first scope's id.
312
- */
313
- function scopeTable(ctx, name) {
314
- const table = scopeMembershipTable(ctx.memberships, ctx.scopes, name);
315
- if (table === void 0) return;
316
- const column = scopeColumn(table, ctx.scopes, name);
317
- if (column === void 0) return;
318
- const root = rootScope(ctx.scopes);
319
- const tenantColumn = root !== void 0 && scopeChain(ctx.scopes, name).includes(root) ? scopeColumn(table, ctx.scopes, root) : void 0;
320
- return tenantColumn === void 0 ? {
321
- table,
322
- column
323
- } : {
324
- table,
325
- column,
326
- tenantColumn
327
- };
328
- }
329
- //#endregion
330
- //#region src/cli/rls/api-keys.ts
331
- const API_KEY_ALLOWS = "permdock_api_key_allows";
332
- const DEFAULTS = {
333
- claim: "api_key",
334
- scopes: "scopes",
335
- tenant: "tenant",
336
- roles: "roles"
337
- };
338
- function field(settings, name) {
339
- const value = settings[name] ?? DEFAULTS[name];
340
- if (typeof value !== "string" || !SQL_IDENT.test(value)) throw configError(`PermDock CLI: rls.apiKeys.${name} must be a claim field name matching ${SQL_IDENT.source}`);
341
- return value;
342
- }
343
- function apiKeyFields(setting) {
344
- const settings = setting === true ? {} : setting;
345
- return {
346
- claim: field(settings, "claim"),
347
- scopes: field(settings, "scopes"),
348
- tenant: field(settings, "tenant"),
349
- roles: field(settings, "roles"),
350
- serviceRoles: [...new Set(settings.serviceRoles ?? [])]
351
- };
352
- }
353
- function apiKeysPlan(setting, declared, renamed) {
354
- if (setting === void 0) return;
355
- const fields = apiKeyFields(setting);
356
- const unknown = fields.serviceRoles.filter((role) => !declared.has(role));
357
- if (unknown.length > 0) throw configError(`PermDock CLI: rls.apiKeys.serviceRoles names roles the policy does not declare: ${unknown.join(", ")}`);
358
- return {
359
- ...fields,
360
- ...Object.keys(renamed).length === 0 ? {} : { renamed }
361
- };
362
- }
363
- function keyOf(ctx, plan) {
364
- return `(select ${subjectClaimJsonSql(ctx, plan.claim)} as k) api_key`;
365
- }
366
- function permissionOf(plan, expr) {
367
- return plan.renamed === void 0 ? expr : `coalesce(${quoteLiteral(JSON.stringify(plan.renamed))}::jsonb ->> ${expr}, ${expr})`;
368
- }
369
- function apiKeyAllowsCall(ctx, grant) {
370
- return `${qualified(ctx, API_KEY_ALLOWS)}(${grant})`;
371
- }
372
- function apiKeyAllowsSql(ctx, plan, anonExecute) {
373
- const fn = qualified(ctx, API_KEY_ALLOWS);
374
- const scopes = `k -> ${quoteLiteral(plan.scopes)}`;
375
- const grants = anonExecute ? `revoke execute on function ${fn}(text) from public;
376
- grant execute on function ${fn}(text) to anon, authenticated;` : `revoke execute on function ${fn}(text) from public, anon;
377
- grant execute on function ${fn}(text) to authenticated;`;
378
- return `-- API keys: the ${plan.claim} claim's ${plan.scopes} list is a ceiling on every allow; denies always apply, and a request without the claim is not limited
379
- create or replace function ${fn}(p_grant text)
380
- returns boolean
381
- language sql
382
- stable
383
- security definer
384
- set search_path = ''
385
- as $$
386
- select case
387
- when k is null or k = 'null'::jsonb then true
388
- when exists (
389
- select 1 from ${qualified(ctx, "role_permissions")} rp
390
- where rp.grant_key = p_grant and rp.effect = 'deny'
391
- ) then true
392
- when jsonb_typeof(k) is distinct from 'object' or jsonb_typeof(${scopes}) is distinct from 'array' then false
393
- else exists (
394
- select 1
395
- from jsonb_array_elements_text(${scopes}) s(permission)
396
- where ${permissionOf(plan, "s.permission")} = split_part(split_part(p_grant, '#', 1), '@', 1)
397
- )
398
- end
399
- from ${keyOf(ctx, plan)}
400
- $$;
401
- ${grants}`;
402
- }
403
- function serviceRolesJson(plan) {
404
- return `${quoteLiteral(JSON.stringify(plan.serviceRoles))}::jsonb`;
405
- }
406
- function serviceKeyRows(ctx, plan) {
407
- const roles = `k -> ${quoteLiteral(plan.roles)}`;
408
- return ` from ${keyOf(ctx, plan)}
409
- cross join lateral jsonb_array_elements_text(
410
- case jsonb_typeof(${roles}) when 'array' then ${roles} else ${serviceRolesJson(plan)} end
411
- ) r(role)`;
412
- }
413
- function serviceKeyFilters(ctx, plan, root, permission) {
414
- const tenant = `k ->> ${quoteLiteral(plan.tenant)}`;
415
- return [
416
- `jsonb_typeof(k) = 'object'`,
417
- `coalesce(${subjectIdSql(ctx)}::text, '') = ''`,
418
- `coalesce(${tenant}, '') <> ''`,
419
- ...activeInstancesSql(ctx, root, (name) => name === root ? tenant : void 0, permission)
420
- ];
421
- }
422
- function serviceKeyIdsSql(ctx, plan, root, type) {
423
- const kind = kindFilterSql(ctx, "r.role", { value: "credential" });
424
- const set = ctx.grantSet === true;
425
- const filters = [
426
- ...serviceKeyFilters(ctx, plan, root, grantPermissionSql(set ? "rp.grant_key" : "p_grant")),
427
- ...set ? [] : ["rp.grant_key = p_grant"],
428
- `rp.scope = ${quoteLiteral(root)}`,
429
- ...kind === void 0 ? [] : [kind]
430
- ];
431
- return ` select (k ->> ${quoteLiteral(plan.tenant)})::${type}${set ? ", rp.grant_key" : ""}
432
- ${serviceKeyRows(ctx, plan)}
433
- join ${qualified(ctx, "role_permissions")} rp on rp.role = r.role
434
- where ${filters.join("\n and ")}`;
435
- }
436
- function serviceKeyMemberSql(ctx, plan, root, type) {
437
- return ` select distinct (k ->> ${quoteLiteral(plan.tenant)})::${type}
438
- ${serviceKeyRows(ctx, plan)}
439
- where ${serviceKeyFilters(ctx, plan, root).join("\n and ")}`;
440
- }
441
- function ceilingIdsSql(body, allows) {
442
- return ` select ids.id
443
- from (
444
- ${body}
445
- ) ids(id)
446
- where ${allows}`;
447
- }
448
- function ceilingHasSql(body, allows) {
449
- return ` select ${allows} and coalesce((
450
- ${body}
451
- ), false)`;
452
- }
453
- //#endregion
454
- //#region src/cli/shared/compare.ts
455
- /**
456
- * UTF-16 code-unit order, never `localeCompare`: generated SQL must match byte
457
- * for byte on every machine.
458
- */
459
- function byCodeUnit(a, b) {
460
- return a < b ? -1 : a > b ? 1 : 0;
461
- }
462
- function byKey([a], [b]) {
463
- return byCodeUnit(a, b);
464
- }
465
- //#endregion
466
- //#region src/cli/rls/custom-roles.ts
467
- /** The readers every helpers file ends with. Names are part of the SQL contract. */
468
- const READERS = {
469
- keys: "permdock_permission_keys",
470
- roles: "permdock_role_permissions",
471
- trusted: "permdock_trusted_role_permissions"
472
- };
473
- /**
474
- * The custom-role objects: the tables (`database` mode), the ceiling view over
475
- * the `assignable` declared roles, and `permdock_custom_keys`, which resolves
476
- * one custom role to the grant keys it holds in a scope. A row in the tables
477
- * can never reach a key outside the view.
478
- */
479
- function customRolesSql(ctx) {
480
- const custom = ctx.customRoles;
481
- if (custom === void 0) return "";
482
- const rp = qualified(ctx, "role_permissions");
483
- const ceiling = qualified(ctx, CUSTOM_ROLES.ceiling);
484
- const keys = qualified(ctx, CUSTOM_ROLES.keys);
485
- const chunks = [];
486
- if (ctx.authorize === "database") {
487
- const tenantType = tenantTypeOf(ctx);
488
- for (const [name, column, check] of [[
489
- CUSTOM_ROLES.permissions,
490
- "permission",
491
- `,
492
- effect text not null default 'allow' check (effect in ('allow', 'deny'))`
493
- ], [
494
- CUSTOM_ROLES.includes,
495
- "include_role",
496
- ""
497
- ]]) {
498
- const table = qualified(ctx, name);
499
- const leveled = custom.levels === true && name === CUSTOM_ROLES.permissions;
500
- const unique = `${column}${name === CUSTOM_ROLES.permissions ? ", effect" : ""}${leveled ? ", coalesce(level, '')" : ""}`;
501
- const index = leveled ? `drop index if exists ${qualified(ctx, quoteIdent(`${name}_key`))};
502
- alter table ${table} add column if not exists level text check (level ~ '^[a-z][a-z0-9_]*$');
503
- create unique index if not exists ${quoteIdent(`${name}_level_key`)}` : `create unique index if not exists ${quoteIdent(`${name}_key`)}`;
504
- chunks.push(`create table if not exists ${table} (
505
- tenant_id ${tenantType},
506
- scope text not null default ${quoteLiteral(rootName(ctx))},
507
- scope_id text,
508
- role text not null,
509
- ${column} text not null${check}
510
- );
511
- -- global: no tenant or instance; a tenant role: a tenant; a shared role: no tenant or instance
512
- alter table ${table} drop constraint if exists ${quoteIdent(`${name}_check`)};
513
- alter table ${table} drop constraint if exists ${quoteIdent(`${name}_shape`)};
514
- alter table ${table} add constraint ${quoteIdent(`${name}_shape`)} check (
515
- case when scope = 'global' then tenant_id is null and scope_id is null
516
- else tenant_id is not null or scope_id is null end
517
- );
518
- ${index}
519
- on ${table} (coalesce(tenant_id::text, ''), scope, coalesce(scope_id, ''), role, ${unique});
520
- -- a row identity for triggers the application adds, such as an audit trigger that reads the primary key
521
- alter table ${table} add column if not exists id bigint generated always as identity primary key;
522
- alter table ${table} enable row level security;
523
- revoke all on table ${table} from anon, authenticated, public;`);
524
- }
525
- }
526
- chunks.push(`-- the ceiling: keys of assignable declared roles, and the denies of those roles on the same permissions
527
- create or replace view ${ceiling} with (security_invoker = true) as
528
- select rp.scope, rp.role, rp.permission, rp.grant_key, rp.effect
529
- from ${rp} rp
530
- where rp.role = any(${sqlTextArray(custom.assignable)})
531
- and exists (
532
- select 1 from ${rp} a
533
- where a.role = rp.role
534
- and a.permission = rp.permission
535
- and a.scope = rp.scope
536
- and a.effect = 'allow'
537
- );
538
- revoke all on table ${ceiling} from anon, authenticated, public;`);
539
- const renames = Object.entries(custom.renamed ?? {}).toSorted(byKey);
540
- const shared = sharedRoleSql(ctx);
541
- if (custom.levels === true) {
542
- chunks.push(leveledKeysSql(ctx, renames));
543
- if (shared !== "") chunks.push(shared);
544
- return chunks.join("\n\n");
545
- }
546
- const rename = renamesSql(renames);
547
- chunks.push(`-- one custom role: included ceiling keys and same-scope denies, plus every ceiling key of an allowed permission, minus denied permissions
548
- create or replace function ${keys}(p_allow text[], p_deny text[], p_include text[], p_scope text)
549
- returns setof text
550
- language sql
551
- stable
552
- set search_path = ''
553
- as $$
554
- with ${rename.prelude}ceiling as (
555
- select c.role, ${rename.permission("c")}, c.grant_key, c.effect
556
- from ${ceiling} c${rename.join("c")}
557
- where c.scope = p_scope
558
- ),
559
- included as (
560
- select rp.role, ${rename.permission("rp")}, rp.grant_key, rp.scope, rp.effect
561
- from ${rp} rp${rename.join("rp")}
562
- where rp.role = any(coalesce(p_include, '{}'::text[]))
563
- ),
564
- kept as (
565
- select i.permission, i.grant_key
566
- from included i
567
- where i.effect = 'allow'
568
- and i.scope = p_scope
569
- and exists (
570
- select 1 from ceiling c
571
- where c.role = i.role and c.grant_key = i.grant_key and c.effect = 'allow'
572
- )
573
- ),
574
- wanted as (
575
- ${rename.allow}
576
- union
577
- select i.permission
578
- from included i
579
- where i.effect = 'allow'
580
- and not (i.scope = p_scope and exists (
581
- select 1 from ceiling c
582
- where c.role = i.role and c.grant_key = i.grant_key and c.effect = 'allow'
583
- ))
584
- ),
585
- allowed as (
586
- select w.permission
587
- from wanted w
588
- where not (${rename.denied("w")})
589
- and not exists (select 1 from kept k where k.permission = w.permission)
590
- )
591
- select k.grant_key from kept k
592
- where not (${rename.denied("k")})
593
- union
594
- select i.grant_key from included i
595
- where i.effect = 'deny' and i.scope = p_scope
596
- union
597
- select c.grant_key from ceiling c
598
- where c.permission in (select a.permission from allowed a)
599
- $$;
600
- revoke execute on function ${keys}(text[], text[], text[], text) from public, anon, authenticated;`);
601
- if (shared !== "") chunks.push(shared);
602
- return chunks.join("\n\n");
603
- }
604
- /**
605
- * `permdock_is_shared_role(p_scope, p_role)` (`database` mode): whether a
606
- * shared custom role of that name exists at the scope.
607
- */
608
- function sharedRoleSql(ctx) {
609
- if (ctx.authorize !== "database") return "";
610
- const perms = qualified(ctx, CUSTOM_ROLES.permissions);
611
- const includes = qualified(ctx, CUSTOM_ROLES.includes);
612
- const shared = qualified(ctx, CUSTOM_ROLES.shared);
613
- return `-- a shared custom role: rows with no tenant at a scope below global; its name wins over a tenant role's in every tenant
614
- create or replace function ${shared}(p_scope text, p_role text)
615
- returns boolean
616
- language sql
617
- stable
618
- security definer
619
- set search_path = ''
620
- as $$
621
- select p_scope <> 'global' and (
622
- exists (select 1 from ${perms} c where c.tenant_id is null and c.scope = p_scope and c.role = p_role)
623
- or exists (select 1 from ${includes} c where c.tenant_id is null and c.scope = p_scope and c.role = p_role)
624
- )
625
- $$;
626
- revoke execute on function ${shared}(text, text) from public, anon, authenticated;`;
627
- }
628
- /**
629
- * `permdock_custom_keys` when resources declare levels. An allow entry is `key`
630
- * or `key@level`. A level reaches only the ceiling's `<grant key>@<level>`
631
- * keys, plus the ceiling denies of that permission; a level no ceiling key
632
- * carries removes the permission, as `resolveCustomRole` drops it with
633
- * `unknown-level`.
634
- */
635
- function leveledKeysSql(ctx, renames) {
636
- const rp = qualified(ctx, "role_permissions");
637
- const ceiling = qualified(ctx, CUSTOM_ROLES.ceiling);
638
- const keys = qualified(ctx, CUSTOM_ROLES.keys);
639
- const renamed = renames.length > 0;
640
- const prelude = renamed ? `renamed (former, key) as (values ${renames.map(([former, current]) => `(${quoteLiteral(former)}, ${quoteLiteral(current)})`).join(", ")}),
641
- ` : "";
642
- const current = (raw, alias) => renamed ? `coalesce(r_${alias}.key, ${raw})` : raw;
643
- const join = (raw, alias) => renamed ? ` left join renamed r_${alias} on r_${alias}.former = ${raw}` : "";
644
- return `-- one custom role: as above, where an allow entry key@level reaches only the ceiling keys of that level
645
- create or replace function ${keys}(p_allow text[], p_deny text[], p_include text[], p_scope text)
646
- returns setof text
647
- language sql
648
- stable
649
- set search_path = ''
650
- as $$
651
- with ${prelude}entries as (
652
- select ${current("split_part(e.entry, '@', 1)", "e")} as permission, nullif(split_part(e.entry, '@', 2), '') as level
653
- from unnest(coalesce(p_allow, '{}'::text[])) as e(entry)${join("split_part(e.entry, '@', 1)", "e")}
654
- ),
655
- ceiling as (
656
- select c.role, ${current("c.permission", "c")} as permission, c.grant_key, c.effect
657
- from ${ceiling} c${join("c.permission", "c")}
658
- where c.scope = p_scope
659
- ),
660
- levels as (
661
- select distinct c.permission, split_part(c.grant_key, '@', 2) as level
662
- from ceiling c
663
- where c.effect = 'allow' and strpos(c.grant_key, '@') > 0
664
- ),
665
- denied as (
666
- select ${current("d.permission", "d")} as permission
667
- from unnest(coalesce(p_deny, '{}'::text[])) as d(permission)${join("d.permission", "d")}
668
- union
669
- select e.permission from entries e
670
- where e.level is not null
671
- and not exists (select 1 from levels l where l.permission = e.permission and l.level = e.level)
672
- ),
673
- included as (
674
- select rp.role, ${current("rp.permission", "rp")} as permission, rp.grant_key, rp.scope, rp.effect
675
- from ${rp} rp${join("rp.permission", "rp")}
676
- where rp.role = any(coalesce(p_include, '{}'::text[]))
677
- ),
678
- kept as (
679
- select i.permission, i.grant_key
680
- from included i
681
- where i.effect = 'allow'
682
- and i.scope = p_scope
683
- and exists (
684
- select 1 from ceiling c
685
- where c.role = i.role and c.grant_key = i.grant_key and c.effect = 'allow'
686
- )
687
- ),
688
- wanted as (
689
- select e.permission from entries e where e.level is null
690
- union
691
- select i.permission
692
- from included i
693
- where i.effect = 'allow'
694
- and not (i.scope = p_scope and exists (
695
- select 1 from ceiling c
696
- where c.role = i.role and c.grant_key = i.grant_key and c.effect = 'allow'
697
- ))
698
- ),
699
- allowed as (
700
- select w.permission
701
- from wanted w
702
- where w.permission not in (select d.permission from denied d)
703
- and not exists (select 1 from kept k where k.permission = w.permission)
704
- ),
705
- allowed_levels as (
706
- select e.permission, e.level
707
- from entries e
708
- where e.level is not null
709
- and e.permission not in (select d.permission from denied d)
710
- and e.permission not in (select a.permission from allowed a)
711
- and not exists (select 1 from kept k where k.permission = e.permission)
712
- )
713
- select k.grant_key from kept k
714
- where k.permission not in (select d.permission from denied d)
715
- union
716
- select i.grant_key from included i
717
- where i.effect = 'deny' and i.scope = p_scope
718
- union
719
- select c.grant_key from ceiling c
720
- where c.permission in (select a.permission from allowed a)
721
- union
722
- select c.grant_key from ceiling c
723
- join allowed_levels a on a.permission = c.permission
724
- where c.effect = 'deny' or split_part(c.grant_key, '@', 2) = a.level
725
- $$;
726
- revoke execute on function ${keys}(text[], text[], text[], text) from public, anon, authenticated;`;
727
- }
728
- function currentKeysSql(array) {
729
- return `select coalesce(r.key, e.permission) as permission
730
- from unnest(coalesce(${array}, '{}'::text[])) as e(permission)
731
- left join renamed r on r.former = e.permission`;
732
- }
733
- /**
734
- * SQL fragments that read a stored former key as its current key inside
735
- * `permdock_custom_keys`. Without renames they are the plain column and array
736
- * reads.
737
- */
738
- function renamesSql(renames) {
739
- if (renames.length === 0) return {
740
- prelude: "",
741
- permission: (alias) => `${alias}.permission`,
742
- join: () => "",
743
- allow: "select unnest(coalesce(p_allow, '{}'::text[])) as permission",
744
- denied: (alias) => `${alias}.permission = any(coalesce(p_deny, '{}'::text[]))`
745
- };
746
- return {
747
- prelude: `renamed (former, key) as (values ${renames.map(([former, current]) => `(${quoteLiteral(former)}, ${quoteLiteral(current)})`).join(", ")}),
748
- denied as (
749
- ${currentKeysSql("p_deny")}
750
- ),
751
- `,
752
- permission: (alias) => `coalesce(r_${alias}.key, ${alias}.permission) as permission`,
753
- join: (alias) => ` left join renamed r_${alias} on r_${alias}.former = ${alias}.permission`,
754
- allow: currentKeysSql("p_allow"),
755
- denied: (alias) => `${alias}.permission in (select d.permission from denied d)`
756
- };
757
- }
758
- /**
759
- * The catalog reader `permdock_permission_keys()` and the role reader
760
- * `permdock_role_permissions(p_role, p_scope, p_tenant, p_scope_id)`, both for
761
- * `authenticated`. A declared role answers from `role_permissions`, which is
762
- * the catalog. A custom role (`database` mode) answers from the tenant's own
763
- * rows through `permdock_custom_keys`, only to a member of the tenant or a
764
- * holder of a `meta.manageRoles` permission for a platform role; a shared role
765
- * (no tenant below global) to any signed-in caller. The effect is `deny` for a
766
- * deny the role carries after the ceiling, as `resolveCustomRole` returns it,
767
- * never for a deny that merely removes an allow.
768
- */
769
- function roleReadersSql(ctx, permissions, trustedReaders) {
770
- const rp = qualified(ctx, "role_permissions");
771
- const reader = qualified(ctx, READERS.roles);
772
- const tenantType = tenantTypeOf(ctx);
773
- const custom = ctx.customRoles;
774
- const root = ctx.scopes[0]?.name;
775
- const database = ctx.authorize === "database";
776
- const chunks = [];
777
- if (permissions !== void 0) {
778
- const catalog = qualified(ctx, READERS.keys);
779
- chunks.push(`-- every declared permission key
780
- create or replace function ${catalog}()
781
- returns setof text
782
- language sql
783
- stable
784
- set search_path = ''
785
- as $$
786
- select k.permission from unnest(${sqlTextArray(permissions.toSorted())}) k(permission) order by 1
787
- $$;
788
- revoke execute on function ${catalog}() from public, anon;
789
- grant execute on function ${catalog}() to authenticated;
790
-
791
- create or replace function ${catalog}(p_scope text)
792
- returns setof text
793
- language sql
794
- stable
795
- security definer
796
- set search_path = ''
797
- as $$
798
- select distinct rp.permission
799
- from ${rp} rp
800
- where rp.scope = p_scope
801
- and rp.effect = 'allow'
802
- and rp.permission = any(${sqlTextArray(permissions.toSorted())})
803
- order by 1
804
- $$;
805
- revoke execute on function ${catalog}(text) from public, anon;
806
- grant execute on function ${catalog}(text) to authenticated;`);
807
- }
808
- const declared = ` select distinct rp.permission, rp.effect
809
- from ${rp} rp
810
- where rp.role = p_role and rp.scope = p_scope
811
- order by 1, 2`;
812
- let body = `begin
813
- perform p_tenant, p_scope_id; -- only a custom role reads them
814
- return query
815
- ${declared};
816
- end;`;
817
- let trustedBody = body;
818
- if (custom !== void 0 && database && root !== void 0) {
819
- const tenant = qualified(ctx, CUSTOM_ROLES.permissions);
820
- const includes = qualified(ctx, CUSTOM_ROLES.includes);
821
- const keys = qualified(ctx, CUSTOM_ROLES.keys);
822
- const shape = qualified(ctx, CUSTOM_ROLES.shape);
823
- const ids = (helper) => `(select x::text from ${qualified(ctx, helper)}() x)`;
824
- const memberOf = `p_tenant::text in ${ids(memberIdsHelper(root))}
825
- or ${perScope(ctx, (scope) => scope === root ? "false" : `p_scope_id in ${ids(memberIdsHelper(scope))}`)}`;
826
- const manage = custom.manage ?? [];
827
- const platform = manage.length === 0 ? "false" : `exists (
828
- select 1 from ${rp} m
829
- where m.effect = 'allow'
830
- and m.permission = any(${sqlTextArray(manage)})
831
- and ${qualified(ctx, HELPERS.has)}(m.grant_key)
832
- )`;
833
- const match = `c.tenant_id is not distinct from p_tenant and c.scope = p_scope and c.scope_id is not distinct from p_scope_id and c.role = p_role`;
834
- const allowEntryOf = `c.${allowEntry(ctx)}`;
835
- const checked = (gate) => `begin
836
- if p_role = any(${sqlTextArray(custom.declared)}) then
837
- return query
838
- ${declared};
839
- return;
840
- end if;
841
- perform ${shape}(p_tenant, p_scope, p_scope_id, p_role);${gate}
842
- return query
843
- select distinct rp.permission, rp.effect
844
- from ${keys}(
845
- array(select ${allowEntryOf} from ${tenant} c where ${match} and c.effect = 'allow'),
846
- array(select c.permission from ${tenant} c where ${match} and c.effect = 'deny'),
847
- array(select c.include_role from ${includes} c where ${match}),
848
- p_scope
849
- ) k(grant_key)
850
- join ${rp} rp on rp.grant_key = k.grant_key and rp.scope = p_scope
851
- order by 1, 2;
852
- end;`;
853
- body = checked(`
854
- if not (${signedIn(ctx)} and (
855
- ${platform}
856
- or (p_scope <> 'global' and p_tenant is null and p_scope_id is null)
857
- or (p_scope <> 'global' and (${memberOf}))
858
- )) then
859
- ${raiseSql(" ", "42501", `'permdock: the caller is not a member of ' || coalesce(p_tenant::text, 'the platform')`, "not-member")}
860
- end if;`);
861
- trustedBody = checked("");
862
- }
863
- chunks.push(`-- the permission keys a role holds on a scope, with effect allow or deny; a custom role is read for its tenant and, below the first scope, its instance
864
- create or replace function ${reader}(p_role text, p_scope text, p_tenant ${tenantType} default null, p_scope_id text default null)
865
- returns table (permission text, effect text)
866
- language plpgsql
867
- stable
868
- security definer
869
- set search_path = ''
870
- as $$
871
- ${body}
872
- $$;
873
- revoke execute on function ${reader}(text, text, ${tenantType}, text) from public, anon;
874
- grant execute on function ${reader}(text, text, ${tenantType}, text) to authenticated;`);
875
- const trusted = qualified(ctx, READERS.trusted);
876
- const signature = `text, text, ${tenantType}, text`;
877
- const grants = trustedReaders === void 0 || trustedReaders.length === 0 ? "" : `\n${trustedReaderGrants(ctx, `${trusted}(${signature})`, trustedReaders)}`;
878
- chunks.push(`create or replace function ${trusted}(p_role text, p_scope text, p_tenant ${tenantType} default null, p_scope_id text default null)
879
- returns table (permission text, effect text)
880
- language plpgsql
881
- stable
882
- security definer
883
- set search_path = ''
884
- as $$
885
- ${trustedBody}
886
- $$;
887
- revoke execute on function ${trusted}(${signature}) from public, anon, authenticated;${grants}`);
888
- return chunks.join("\n\n");
889
- }
890
- /**
891
- * The stored definition of `p_role` at `p_scope` for `p_tenant`: the shared
892
- * rows when a shared role has the name.
893
- */
894
- function storedTenant(ctx) {
895
- return `case when ${qualified(ctx, CUSTOM_ROLES.shared)}(p_scope, p_role) then c.tenant_id is null else c.tenant_id is not distinct from p_tenant end`;
896
- }
897
- /**
898
- * The tenant half of a custom-role row match for a membership: the membership's
899
- * tenant, or no tenant when a shared role of that name exists at the scope, so
900
- * a shared role shadows a tenant role of the same name.
901
- */
902
- function customTenantMatch(ctx, tenant, scope, role) {
903
- return `case when ${qualified(ctx, CUSTOM_ROLES.shared)}(${quoteLiteral(scope)}, ${role}) then c.tenant_id is null else c.tenant_id::text = ${tenant} end`;
904
- }
905
- /**
906
- * The scope of a row of the application's roles table: its scope column (or the
907
- * first scope) with a tenant; with no tenant, the same scope when the `shared`
908
- * column is true, else `'global'`.
909
- */
910
- function rolesTableScope(table, tenant, root, column) {
911
- const own = table.scope === void 0 ? quoteLiteral(root) : `${column(table.scope)}::text`;
912
- return `case when ${tenant} is null then ${table.shared === void 0 ? "'global'" : `case when coalesce(${column(table.shared)}, false) then ${own} else 'global' end`} else ${own} end`;
913
- }
914
- /**
915
- * `expr` read as its current key: a former key maps to the key it was renamed
916
- * to.
917
- */
918
- function currentKeyExpr(renames, expr) {
919
- if (renames.length === 0) return expr;
920
- return `(case ${expr} ${renames.map(([former, current]) => `when ${quoteLiteral(former)} then ${quoteLiteral(current)}`).join(" ")} else ${expr} end)`;
921
- }
922
- /**
923
- * `case p_scope when '<scope>' then <sql for scope> ... else false end` over
924
- * the declared scopes.
925
- */
926
- function perScope(ctx, sql) {
927
- const arms = ctx.scopes.map((scope) => `when ${quoteLiteral(scope.name)} then ${sql(scope.name)}`).join(" ");
928
- return arms === "" ? "false" : `(case p_scope ${arms} else false end)`;
929
- }
930
- function raiseSql(indent, errcode, message, hint) {
931
- return `${indent}raise exception using
932
- ${indent} errcode = '${errcode}',
933
- ${indent} message = ${message},
934
- ${indent} hint = ${quoteLiteral(hint)};`;
935
- }
936
- function hasCustomRoleChecksFor(ctx) {
937
- return ctx.authorize === "database" && ctx.customRoles !== void 0 && ctx.scopes.length > 0 && ctx.scopes.every((scope) => hasMemberFor(ctx, scope.name));
938
- }
939
- /**
940
- * The grants a `rls.trustedReaders` role needs for one reader: usage on the
941
- * helper schema, which no client role reaches through these lines, and execute
942
- * on the function.
943
- */
944
- function trustedReaderGrants(ctx, fn, readers) {
945
- const to = readers.map(quoteIdent).join(", ");
946
- return `grant usage on schema ${quoteIdent(helperSchema(ctx))} to ${to};
947
- grant execute on function ${fn} to ${to};`;
948
- }
949
- //#endregion
950
- //#region src/cli/sql/global-roles.ts
951
- function qualify(name, schema) {
952
- return name.includes(".") ? name : `${schema}.${name}`;
953
- }
954
- function throughTenant(through, roles) {
955
- if (through === void 0 || roles?.tenant === void 0) return;
956
- return qualify(roles.table, "public") === through.table ? roles.tenant : void 0;
957
- }
958
- /**
959
- * Resolves `source` against `schema`, aliasing the table `alias` and the roles
960
- * table `<alias>k`.
961
- */
962
- function globalRoleSource(source, schema, alias, roles) {
963
- const table = qualify(source.table, schema);
964
- const user = source.user ?? "user_id";
965
- const role = roleColumn(source.role ?? "role", table, alias, {
966
- label: "roles.role",
967
- prefix: "PermDock CLI",
968
- indent: " "
969
- });
970
- const tenant = role.lateral ? void 0 : throughTenant(role.through, roles);
971
- const shared = tenant === void 0 ? void 0 : roles?.shared;
972
- const global = tenant === void 0 ? "" : ` and ${alias}k.${quoteIdent(tenant)} is null${shared === void 0 ? "" : ` and ${alias}k.${quoteIdent(shared)} is not true`}`;
973
- return {
974
- table,
975
- user,
976
- from: `${quoteTable(table)} ${alias}${role.join}${global}`,
977
- userSql: `${alias}.${quoteIdent(user)}`,
978
- roleSql: role.sql,
979
- nullable: role.nullable,
980
- role: roleManifest(role),
981
- ...role.through === void 0 ? {} : { through: role.through },
982
- ...tenant === void 0 ? {} : { tenant },
983
- ...shared === void 0 ? {} : { shared }
984
- };
985
- }
986
- //#endregion
987
- //#region src/cli/rls/helper-rows.ts
988
- function activeTenant(ctx) {
989
- return `nullif(${subjectClaimSql(ctx, ctx.tenantClaim)}, '')`;
990
- }
991
- function keyTenantLine(ctx, scope, tenant) {
992
- const keyed = keyTenantSql(ctx, underRoot(ctx, scope) ? tenant : void 0);
993
- return keyed === void 0 ? "" : `\n and ${keyed}`;
994
- }
995
- /**
996
- * Whether the helper for `scope` narrows to the tenant claim: unless
997
- * `rls.tenants` is `'all'`, when the first scope is on its chain.
998
- */
999
- function narrowsTo(ctx, scope) {
1000
- return ctx.tenants !== "all" && underRoot(ctx, scope);
1001
- }
1002
- /**
1003
- * Whether the active tenant narrows memberships of `scope`: the first scope is
1004
- * on its chain.
1005
- */
1006
- function underRoot(ctx, scope) {
1007
- const root = ctx.scopes[0]?.name;
1008
- let current = ctx.scopes.find((item) => item.name === scope);
1009
- const seen = /* @__PURE__ */ new Set();
1010
- while (current !== void 0 && !seen.has(current.name)) {
1011
- if (current.name === root) return true;
1012
- seen.add(current.name);
1013
- const parent = current.within;
1014
- current = parent === void 0 ? void 0 : ctx.scopes.find((item) => item.name === parent);
1015
- }
1016
- return false;
1017
- }
1018
- /**
1019
- * `and exists (...)` lines for an active user; empty without
1020
- * `rls.suspension.users`.
1021
- */
1022
- function userActive(ctx, indent, user) {
1023
- return activeUserSql(ctx, user).map((part) => `${indent}and ${part}`);
1024
- }
1025
- /**
1026
- * `and exists (...)` lines for every suspendable instance on the chain of
1027
- * `scope`'s membership.
1028
- */
1029
- function instancesActive(ctx, scope, idOf, indent, permission) {
1030
- return activeInstancesSql(ctx, scope, idOf, permission).map((part) => `${indent}and ${part}`);
1031
- }
1032
- function roleRows(ctx) {
1033
- const claim = ctx.roleClaim ?? "user_role";
1034
- switch (ctx.dialect) {
1035
- case "guc": return `unnest(string_to_array(nullif(current_setting(${quoteLiteral(`${ctx.gucPrefix}.${claim}`)}, true), ''), ',')) r(role)`;
1036
- case "supabase":
1037
- case "neon": {
1038
- const raw = subjectClaimJsonSql(ctx, claim);
1039
- const value = ctx.dialect === "supabase" ? `coalesce(nullif(${raw}, 'null'::jsonb), (select auth.jwt()) -> 'app_metadata' -> ${quoteLiteral(claim)})` : raw;
1040
- return `jsonb_array_elements_text(
1041
- case jsonb_typeof(${value})
1042
- when 'array' then ${value}
1043
- when 'string' then jsonb_build_array(${value})
1044
- else '[]'::jsonb
1045
- end
1046
- ) r(role)`;
1047
- }
1048
- default: return ctx.dialect;
1049
- }
1050
- }
1051
- function membershipRows(ctx) {
1052
- const raw = subjectClaimJsonSql(ctx, "memberships");
1053
- const value = ctx.dialect === "supabase" ? `coalesce(${raw}, (select auth.jwt()) -> 'app_metadata' -> 'memberships')` : raw;
1054
- return `jsonb_array_elements(
1055
- case jsonb_typeof(${value}) when 'array' then ${value} else '[]'::jsonb end
1056
- ) m
1057
- cross join lateral jsonb_array_elements_text(
1058
- case jsonb_typeof(m -> 'roles') when 'array' then m -> 'roles' else '[]'::jsonb end
1059
- ) r(role)`;
1060
- }
1061
- function andLine(indent, condition) {
1062
- return condition === void 0 ? "" : `\n${indent}and ${condition}`;
1063
- }
1064
- /** `rls.roles`, or the generated `user_roles (user_id, role)`, aliased `ur`. */
1065
- function globalRoleRows(ctx) {
1066
- return ctx.roles === void 0 ? {
1067
- from: `${qualified(ctx, "user_roles")} ur`,
1068
- userSql: "ur.user_id",
1069
- roleSql: "ur.role::text"
1070
- } : globalRoleSource(ctx.roles, "public", "ur", ctx.customRoles?.table);
1071
- }
1072
- function customKeysJoin(ctx, scope, allows, denies, includes) {
1073
- return ` cross join lateral ${qualified(ctx, CUSTOM_ROLES.keys)}(
1074
- ${allows},
1075
- ${denies},
1076
- ${includes},
1077
- ${quoteLiteral(scope)}
1078
- ) ck(grant_key)`;
1079
- }
1080
- //#endregion
1081
- //#region src/cli/rls/helper-bodies.ts
1082
- function hasSetBody(ctx) {
1083
- const rp = qualified(ctx, "role_permissions");
1084
- const active = userActive(ctx, " ").map((line) => `\n${line}`).join("");
1085
- const custom = ctx.customRoles;
1086
- if (ctx.authorize === "database") {
1087
- const ur = globalRoleRows(ctx);
1088
- const declared = ` select rp.grant_key
1089
- from ${ur.from}
1090
- join ${rp} rp on rp.role = ${ur.roleSql}
1091
- where ${ur.userSql} = ${subjectIdSql(ctx)}
1092
- and rp.scope = 'global'${andLine(" ", globalKindFilterSql(ctx, ur.roleSql))}${active}`;
1093
- if (custom === void 0) return declared;
1094
- const match = `c.tenant_id is null and c.scope = 'global' and c.scope_id is null and c.role = ${ur.roleSql}`;
1095
- const rows = (source, value, extra) => `array(select c.${value} from ${qualified(ctx, source)} c where ${match}${extra})`;
1096
- return `${declared}
1097
- union
1098
- select ck.grant_key
1099
- from ${ur.from}
1100
- ${customKeysJoin(ctx, "global", rows(CUSTOM_ROLES.permissions, allowEntry(ctx), " and c.effect = 'allow'"), rows(CUSTOM_ROLES.permissions, "permission", " and c.effect = 'deny'"), rows(CUSTOM_ROLES.includes, "include_role", ""))}
1101
- where ${ur.userSql} = ${subjectIdSql(ctx)}
1102
- and not (${ur.roleSql} = any(${sqlTextArray(custom.declared)}))${active}`;
1103
- }
1104
- const declared = ` select rp.grant_key
1105
- from ${roleRows(ctx)}
1106
- join ${rp} rp on rp.role = r.role
1107
- where ${signedIn(ctx)}
1108
- and rp.scope = 'global'${andLine(" ", globalKindFilterSql(ctx, "r.role"))}${active}`;
1109
- if (custom === void 0) return declared;
1110
- const claim = subjectClaimJsonSql(ctx, GLOBAL_GRANTS_CLAIM);
1111
- return `${declared}
1112
- union
1113
- select ck.grant_key
1114
- from ${roleRows(ctx)}
1115
- cross join lateral (select ${claim} -> r.role as g) cg
1116
- ${customKeysJoin(ctx, "global", claimEntries("left(e, 1) not in ('-', '@')", "e"), claimEntries("left(e, 1) = '-'", "substr(e, 2)"), claimEntries("left(e, 1) = '@'", "substr(e, 2)"))}
1117
- where ${signedIn(ctx)}
1118
- and jsonb_typeof(cg.g) = 'array'
1119
- and not (r.role = any(${sqlTextArray(custom.declared)}))${active}`;
1120
- }
1121
- function hasBody(ctx) {
1122
- if (ctx.grantSet === true) return hasSetBody(ctx);
1123
- const rp = qualified(ctx, "role_permissions");
1124
- const active = userActive(ctx, " ").map((line) => `\n${line}`).join("");
1125
- const custom = ctx.customRoles;
1126
- if (ctx.authorize === "database") {
1127
- const ur = globalRoleRows(ctx);
1128
- const declared = ` select exists (
1129
- select 1
1130
- from ${ur.from}
1131
- join ${rp} rp on rp.role = ${ur.roleSql}
1132
- where ${ur.userSql} = ${subjectIdSql(ctx)}
1133
- and rp.grant_key = p_grant
1134
- and rp.scope = 'global'${andLine(" ", globalKindFilterSql(ctx, ur.roleSql))}${active}
1135
- )`;
1136
- if (custom === void 0) return declared;
1137
- const match = `c.tenant_id is null and c.scope = 'global' and c.scope_id is null and c.role = ${ur.roleSql}`;
1138
- const rows = (source, value, extra) => `array(select c.${value} from ${qualified(ctx, source)} c where ${match}${extra})`;
1139
- return `${declared}
1140
- or exists (
1141
- select 1
1142
- from ${ur.from}
1143
- where ${ur.userSql} = ${subjectIdSql(ctx)}
1144
- and not (${ur.roleSql} = any(${sqlTextArray(custom.declared)}))${active}
1145
- ${customKeysSql(ctx, "global", rows(CUSTOM_ROLES.permissions, allowEntry(ctx), " and c.effect = 'allow'"), rows(CUSTOM_ROLES.permissions, "permission", " and c.effect = 'deny'"), rows(CUSTOM_ROLES.includes, "include_role", "")).trimStart()}
1146
- )`;
1147
- }
1148
- const declared = ` select ${signedIn(ctx)} and exists (
1149
- select 1
1150
- from ${roleRows(ctx)}
1151
- join ${rp} rp on rp.role = r.role
1152
- where rp.grant_key = p_grant
1153
- and rp.scope = 'global'${andLine(" ", globalKindFilterSql(ctx, "r.role"))}${active}
1154
- )`;
1155
- if (custom === void 0) return declared;
1156
- const claim = subjectClaimJsonSql(ctx, GLOBAL_GRANTS_CLAIM);
1157
- return `${declared}
1158
- or (${signedIn(ctx)} and exists (
1159
- select 1
1160
- from ${roleRows(ctx)}
1161
- cross join lateral (select ${claim} -> r.role as g) cg
1162
- where jsonb_typeof(cg.g) = 'array'
1163
- and not (r.role = any(${sqlTextArray(custom.declared)}))${active}
1164
- ${customKeysSql(ctx, "global", claimEntries("left(e, 1) not in ('-', '@')", "e"), claimEntries("left(e, 1) = '-'", "substr(e, 2)"), claimEntries("left(e, 1) = '@'", "substr(e, 2)")).trimStart()}
1165
- ))`;
1166
- }
1167
- /**
1168
- * The claim `jwt` mode reads platform custom roles from:
1169
- * `customRoleClaim(globalRoles)`.
1170
- */
1171
- const GLOBAL_GRANTS_CLAIM = "role_grants";
1172
- function memberColumn(name) {
1173
- return `m.${quoteIdent(name)}`;
1174
- }
1175
- function disabledColumn(table) {
1176
- return table.disabledAt === void 0 ? void 0 : memberColumn(table.disabledAt);
1177
- }
1178
- function claimKeptLines(ctx, indent, permission) {
1179
- return disabledKeep(ctx).length === 0 ? [] : [`${indent}and ${keptRowSql("m -> 'keep'", permission)}`];
1180
- }
1181
- /** Entries of a compact custom-role claim (`cg.g`) that match `where`. */
1182
- function claimEntries(where, value) {
1183
- return `array(select ${value} from jsonb_array_elements_text(cg.g) e where ${where})`;
1184
- }
1185
- /** `p_grant in (select permdock_custom_keys(allows, denies, includes, scope))`. */
1186
- function customKeysSql(ctx, scope, allows, denies, includes) {
1187
- return ` and p_grant in (select ${qualified(ctx, CUSTOM_ROLES.keys)}(
1188
- ${allows},
1189
- ${denies},
1190
- ${includes},
1191
- ${quoteLiteral(scope)}
1192
- ))`;
1193
- }
1194
- function tableFilters(ctx, scope, table, tenantColumn, grant) {
1195
- const filters = [];
1196
- if (table.expiresAt !== void 0) {
1197
- const expires = memberColumn(table.expiresAt);
1198
- filters.push(` and (${expires} is null or ${expires} > now())`);
1199
- }
1200
- filters.push(...activeMembershipSql(ctx, disabledColumn(table), grantPermissionSql(grant)).map((part) => ` and ${part}`));
1201
- if (tenantColumn !== void 0 && ctx.tenants !== "all") filters.push(` and (${activeTenant(ctx)} is null or ${memberColumn(tenantColumn)}::text = ${activeTenant(ctx)})`);
1202
- const keyed = keyTenantSql(ctx, tenantColumn === void 0 ? void 0 : memberColumn(tenantColumn));
1203
- if (keyed !== void 0) filters.push(` and ${keyed}`);
1204
- const user = activeUserChecks(ctx, memberColumn(table.user), "act_user", " ");
1205
- const instances = activeInstanceChecks(ctx, scope, (name) => {
1206
- const held = scopeColumn(table, ctx.scopes, name);
1207
- return held === void 0 ? void 0 : memberColumn(held);
1208
- }, (name) => `act_${name}`, " ", grantPermissionSql(grant));
1209
- filters.push(...instances.filters.map((part) => ` and ${part}`));
1210
- return {
1211
- owner: ` where ${memberColumn(table.user)} = ${subjectIdSql(ctx)}`,
1212
- joins: [...user.joins, ...instances.joins],
1213
- filters
1214
- };
1215
- }
1216
- function tableBranch(ctx, scope, type, table, column, tenantColumn, branch, set, declared, stale) {
1217
- const checks = tableFilters(ctx, scope, table, tenantColumn, branch === "custom" && set ? "ck.grant_key" : set ? "rp.grant_key" : "p_grant");
1218
- const role = memberRoleOf(table, "m", " ");
1219
- const kind = kindFilterSql(ctx, role.sql, memberVia(table));
1220
- const gate = stale === true ? [` and not (select ${qualified(ctx, HELPERS.tokenCurrent)}())`] : [];
1221
- const custom = ctx.customRoles;
1222
- return [
1223
- branch === "declared" ? ` select${role.lateral ? " distinct" : ""} ${memberColumn(column)}::${type}${set ? ", rp.grant_key" : ""}` : ` select ${memberColumn(column)}::${type}${set ? ", ck.grant_key" : ""}`,
1224
- ` from ${quoteQualified(table.table)} m${role.join}`,
1225
- ...checks.joins,
1226
- ...branch === "custom" && set && custom !== void 0 ? [customKeysJoin(ctx, scope, ...customEntries(ctx, scope, column, tenantColumn, role.sql))] : [],
1227
- ...branch === "declared" ? [` join ${qualified(ctx, "role_permissions")} rp on rp.role = ${role.sql}`] : [],
1228
- checks.owner,
1229
- ...gate,
1230
- ...branch === "declared" ? [
1231
- ...set ? [] : [" and rp.grant_key = p_grant"],
1232
- ` and rp.scope = ${quoteLiteral(scope)}`,
1233
- ...kind === void 0 ? [] : [` and ${kind}`]
1234
- ] : [` and not (${role.sql} = any(${sqlTextArray(declared)}))`],
1235
- ...checks.filters,
1236
- ...branch === "custom" && !set && custom !== void 0 ? [customKeysSql(ctx, scope, ...customEntries(ctx, scope, column, tenantColumn, role.sql))] : []
1237
- ].join("\n");
1238
- }
1239
- function customEntries(ctx, scope, column, tenantColumn, roleSql) {
1240
- const match = [
1241
- customTenantMatch(ctx, `${memberColumn(tenantColumn ?? column)}::text`, scope, roleSql),
1242
- `c.scope = ${quoteLiteral(scope)}`,
1243
- `(c.scope_id is null or c.scope_id = ${memberColumn(column)}::text)`,
1244
- `c.role = ${roleSql}`
1245
- ].join(" and ");
1246
- const rows = (source, value, extra) => `array(select c.${value} from ${qualified(ctx, source)} c where ${match}${extra})`;
1247
- return [
1248
- rows(CUSTOM_ROLES.permissions, allowEntry(ctx), " and c.effect = 'allow'"),
1249
- rows(CUSTOM_ROLES.permissions, "permission", " and c.effect = 'deny'"),
1250
- rows(CUSTOM_ROLES.includes, "include_role", "")
1251
- ];
1252
- }
1253
- function tableBody(ctx, scope, type) {
1254
- const mapped = scopeTable(ctx, scope);
1255
- if (mapped === void 0) return ` select null::${type} where false -- no ${scope} memberships table configured`;
1256
- const { table, column, tenantColumn } = mapped;
1257
- const set = ctx.grantSet === true;
1258
- const custom = ctx.customRoles;
1259
- const branches = [];
1260
- if (ctx.claimsFirst === true && !set) {
1261
- branches.push(claimDeclaredBody(ctx, scope, type));
1262
- branches.push(tableBranch(ctx, scope, type, table, column, tenantColumn, "declared", set, [], true));
1263
- } else branches.push(tableBranch(ctx, scope, type, table, column, tenantColumn, "declared", set, []));
1264
- if (custom !== void 0) branches.push(tableBranch(ctx, scope, type, table, column, tenantColumn, "custom", set, custom.declared));
1265
- return branches.join("\n union\n");
1266
- }
1267
- /** The membership's instance of the first scope, from the canonical claim. */
1268
- function claimTenant(ctx, scope) {
1269
- const root = rootName(ctx);
1270
- return scope === root ? `m ->> 'id'` : `m -> 'within' ->> ${quoteLiteral(root)}`;
1271
- }
1272
- function claimDeclaredBody(ctx, scope, type) {
1273
- const grant = "p_grant";
1274
- const narrow = narrowsTo(ctx, scope) ? `\n and (${activeTenant(ctx)} is null or ${claimTenant(ctx, scope)} = ${activeTenant(ctx)})` : "";
1275
- const user = activeUserChecks(ctx, subjectIdSql(ctx), "act_user", " ");
1276
- const instances = activeInstanceChecks(ctx, scope, (name) => name === scope ? `m ->> 'id'` : `m -> 'within' ->> ${quoteLiteral(name)}`, (name) => `act_${name}`, " ", grantPermissionSql(grant));
1277
- const filters = [
1278
- ` and (select ${qualified(ctx, HELPERS.tokenCurrent)}())`,
1279
- ` and m ->> 'scope' = ${quoteLiteral(scope)}`,
1280
- ` and m ->> 'id' is not null${narrow}${keyTenantLine(ctx, scope, claimTenant(ctx, scope))}`,
1281
- ` and case jsonb_typeof(m -> 'expires_at')
1282
- when 'number' then (m ->> 'expires_at')::numeric > extract(epoch from now())
1283
- else true
1284
- end`,
1285
- ...claimKeptLines(ctx, " ", grantPermissionSql(grant)),
1286
- ...instances.filters.map((part) => ` and ${part}`)
1287
- ];
1288
- const kind = kindFilterSql(ctx, "r.role", "m ->> 'via'");
1289
- return [
1290
- ` select (m ->> 'id')::${type}`,
1291
- ` from ${membershipRows(ctx)}`,
1292
- ...user.joins,
1293
- ...instances.joins,
1294
- ` join ${qualified(ctx, "role_permissions")} rp on rp.role = r.role`,
1295
- ` where ${signedIn(ctx)}`,
1296
- ` and rp.grant_key = p_grant`,
1297
- ` and rp.scope = ${quoteLiteral(scope)}`,
1298
- ...kind === void 0 ? [] : [` and ${kind}`],
1299
- ...filters
1300
- ].join("\n");
1301
- }
1302
- function claimBody(ctx, scope, type) {
1303
- const set = ctx.grantSet === true;
1304
- const narrow = narrowsTo(ctx, scope) ? `
1305
- and (${activeTenant(ctx)} is null or ${claimTenant(ctx, scope)} = ${activeTenant(ctx)})` : "";
1306
- const filtersFor = (grant) => ` and m ->> 'scope' = ${quoteLiteral(scope)}
1307
- and m ->> 'id' is not null${narrow}${keyTenantLine(ctx, scope, claimTenant(ctx, scope))}
1308
- and case jsonb_typeof(m -> 'expires_at')
1309
- when 'number' then (m ->> 'expires_at')::numeric > extract(epoch from now())
1310
- else true
1311
- end${[
1312
- ...claimKeptLines(ctx, " ", grantPermissionSql(grant)),
1313
- ...userActive(ctx, " "),
1314
- ...instancesActive(ctx, scope, (name) => name === scope ? `m ->> 'id'` : `m -> 'within' ->> ${quoteLiteral(name)}`, " ", grantPermissionSql(grant))
1315
- ].map((line) => `\n${line}`).join("")}`;
1316
- const filters = filtersFor(set ? "rp.grant_key" : "p_grant");
1317
- const declared = ` select (m ->> 'id')::${type}${set ? ", rp.grant_key" : ""}
1318
- from ${membershipRows(ctx)}
1319
- join ${qualified(ctx, "role_permissions")} rp on rp.role = r.role
1320
- where ${signedIn(ctx)}${set ? "" : "\n and rp.grant_key = p_grant"}
1321
- and rp.scope = ${quoteLiteral(scope)}${andLine(" ", kindFilterSql(ctx, "r.role", "m ->> 'via'"))}
1322
- ${filters}`;
1323
- const custom = ctx.customRoles;
1324
- if (custom === void 0) return declared;
1325
- if (set) return `${declared}
1326
- union
1327
- select (m ->> 'id')::${type}, ck.grant_key
1328
- from ${membershipRows(ctx)}
1329
- cross join lateral (select m -> 'grants' -> r.role as g) cg
1330
- ${customKeysJoin(ctx, scope, claimEntries("left(e, 1) not in ('-', '@')", "e"), claimEntries("left(e, 1) = '-'", "substr(e, 2)"), claimEntries("left(e, 1) = '@'", "substr(e, 2)"))}
1331
- where ${signedIn(ctx)}
1332
- and jsonb_typeof(cg.g) = 'array'
1333
- and not (r.role = any(${sqlTextArray(custom.declared)}))
1334
- ${filtersFor("ck.grant_key")}`;
1335
- return `${declared}
1336
- union
1337
- select (m ->> 'id')::${type}
1338
- from ${membershipRows(ctx)}
1339
- cross join lateral (select m -> 'grants' -> r.role as g) cg
1340
- where ${signedIn(ctx)}
1341
- and jsonb_typeof(cg.g) = 'array'
1342
- and not (r.role = any(${sqlTextArray(custom.declared)}))
1343
- ${filters}
1344
- ${customKeysSql(ctx, scope, claimEntries("left(e, 1) not in ('-', '@')", "e"), claimEntries("left(e, 1) = '-'", "substr(e, 2)"), claimEntries("left(e, 1) = '@'", "substr(e, 2)"))}`;
1345
- }
1346
- /**
1347
- * The rows the membership sources select for the subject, one per instance
1348
- * (`scope`, `id`, `within`, `roles`, `via`), with each source's own expiry and
1349
- * suspension filters: the statements the token hook runs.
1350
- */
1351
- function sourcesKeep(sources) {
1352
- return sources.some((source) => source.sql.keeps);
1353
- }
1354
- function sourceRows(sources) {
1355
- const keep = sourcesKeep(sources);
1356
- return sources.map((source, index) => source.sql.select(sourceUser(index), keep).replaceAll(/^/gmu, " ")).join("\n union all\n");
1357
- }
1358
- function sourceUser(index) {
1359
- return `v_user_${String(index)}`;
1360
- }
1361
- function memoizes(ctx) {
1362
- return ctx.authorize === "database" && ctx.dialect === "supabase" && ctx.grantSet !== true && ctx.subjectId === void 0;
1363
- }
1364
- function sqlBody(sql) {
1365
- return {
1366
- sql,
1367
- vars: []
1368
- };
1369
- }
1370
- function sourcesBodyOf(sql, sources, user) {
1371
- return {
1372
- sql,
1373
- vars: sources.map((source, index) => `${sourceUser(index)} ${source.sql.userType} := ${user};`)
1374
- };
1375
- }
1376
- /** SQL reading the memo at `key`: a text value, or null when unset. */
1377
- function memoReadSql(api, key) {
1378
- return api === "better-supabase" ? `better_supabase.memo_get(${key})` : `nullif(current_setting(${key}, true), '')`;
1379
- }
1380
- /** SQL writing `value` to the memo at `key`. */
1381
- function memoWriteSql(api, key, value) {
1382
- return api === "better-supabase" ? `better_supabase.memo_set(${key}, ${value})` : `set_config(${key}, ${value}, true)`;
1383
- }
1384
- function memoDiscriminatorSql(user, key) {
1385
- return `md5(concat_ws('|',
1386
- ${user},
1387
- ${key},
1388
- coalesce((select auth.jwt()) ->> 'authz_ver', ''),
1389
- coalesce(nullif(current_setting('permdock.m.gen', true), ''), '0'),
1390
- statement_timestamp()::text,
1391
- md5(coalesce((select auth.jwt())::text, ''))
1392
- ))`;
1393
- }
1394
- /**
1395
- * `language sql`, or `plpgsql` returning the query when the body declares
1396
- * variables.
1397
- */
1398
- function functionBody(body, parallelSafe = false) {
1399
- const planner = `cost 1000${parallelSafe ? "\nparallel safe" : ""}`;
1400
- if (body.memo !== void 0) {
1401
- const declare = [
1402
- ...body.vars,
1403
- `v_user text := ${body.memo.user}::text;`,
1404
- `v_key text := 'permdock.m.' || ${quoteLiteral(body.memo.scope)} || '.k' || (hashtext(p_grant) & 1023)::text;`,
1405
- `v_disc text := ${memoDiscriminatorSql("v_user", "p_grant")};`,
1406
- `v_memo text := ${memoReadSql(body.memo.api, "v_key")};`
1407
- ];
1408
- if (body.memo.type === "boolean") return `language plpgsql
1409
- volatile
1410
- security definer
1411
- cost 1000
1412
- set search_path = ''
1413
- as $$
1414
- declare
1415
- ${[...declare, "v_has boolean;"].map((line) => ` ${line}`).join("\n")}
1416
- begin
1417
- if v_memo is not null and (v_memo::jsonb ->> 'k') = v_disc then
1418
- return (v_memo::jsonb ->> 'v')::boolean;
1419
- end if;
1420
- v_has := (
1421
- ${body.sql}
1422
- );
1423
- perform ${memoWriteSql(body.memo.api, "v_key", "jsonb_build_object('k', v_disc, 'v', v_has)::text")};
1424
- return v_has;
1425
- end;
1426
- $$;`;
1427
- declare.push(`v_ids ${body.memo.type}[];`);
1428
- return `language plpgsql
1429
- volatile
1430
- security definer
1431
- cost 1000
1432
- set search_path = ''
1433
- as $$
1434
- declare
1435
- ${declare.map((line) => ` ${line}`).join("\n")}
1436
- begin
1437
- if v_memo is not null and (v_memo::jsonb ->> 'k') = v_disc then
1438
- v_ids := array(select jsonb_array_elements_text(v_memo::jsonb -> 'ids')::${body.memo.type});
1439
- else
1440
- v_ids := array(
1441
- ${body.sql}
1442
- );
1443
- perform ${memoWriteSql(body.memo.api, "v_key", "jsonb_build_object('k', v_disc, 'ids', to_jsonb(v_ids))::text")};
1444
- end if;
1445
- return query select unnest(v_ids);
1446
- end;
1447
- $$;`;
1448
- }
1449
- if (body.vars.length === 0) return `language sql
1450
- stable
1451
- security definer
1452
- ${planner}
1453
- set search_path = ''
1454
- as $$
1455
- ${body.sql}
1456
- $$;`;
1457
- return `language plpgsql
1458
- stable
1459
- security definer
1460
- ${planner}
1461
- set search_path = ''
1462
- as $$
1463
- declare
1464
- ${body.vars.map((line) => ` ${line}`).join("\n")}
1465
- begin
1466
- return query
1467
- ${body.sql};
1468
- end;
1469
- $$;`;
1470
- }
1471
- /**
1472
- * `ms.id` for the scope itself and `ms.within ->> name` for an ancestor. The
1473
- * alias is not `s`, which `activeRowSql` binds inside its `exists`.
1474
- */
1475
- function sourceIdOf(scope) {
1476
- return (name) => name === scope ? "ms.id" : `ms.within ->> ${quoteLiteral(name)}`;
1477
- }
1478
- function sourceFilters(ctx, scope, user = subjectIdSql(ctx), permission, keeps = false) {
1479
- return [
1480
- ...keeps ? [` and ${keptRowSql("ms.keep", permission)}`] : [],
1481
- ...userActive(ctx, " ", user),
1482
- ...instancesActive(ctx, scope, sourceIdOf(scope), " ", permission)
1483
- ].map((line) => `\n${line}`).join("");
1484
- }
1485
- function sourcesBody(ctx, scope, type) {
1486
- const root = rootName(ctx);
1487
- const tenant = sourceIdOf(scope)(root);
1488
- const narrow = narrowsTo(ctx, scope) ? `\n and (${activeTenant(ctx)} is null or ${tenant} = ${activeTenant(ctx)})${keyTenantLine(ctx, scope, tenant)}` : keyTenantLine(ctx, scope, tenant);
1489
- const sources = scopeSources(ctx, scope);
1490
- const set = ctx.grantSet === true;
1491
- const rows = ` from (
1492
- ${sourceRows(sources)}
1493
- ) ms
1494
- cross join lateral jsonb_array_elements_text(
1495
- case jsonb_typeof(ms.roles) when 'array' then ms.roles else '[]'::jsonb end
1496
- ) r(role)`;
1497
- const declared = ` select (ms.id)::${type}${set ? ", rp.grant_key" : ""}
1498
- ${rows}
1499
- join ${qualified(ctx, "role_permissions")} rp on rp.role = r.role
1500
- where ${signedIn(ctx)}
1501
- and ms.scope = ${quoteLiteral(scope)}${set ? "" : "\n and rp.grant_key = p_grant"}
1502
- and rp.scope = ${quoteLiteral(scope)}${andLine(" ", kindFilterSql(ctx, "r.role", "ms.via"))}${narrow}${sourceFilters(ctx, scope, subjectIdSql(ctx), grantPermissionSql(set ? "rp.grant_key" : "p_grant"), sourcesKeep(sources))}`;
1503
- const custom = ctx.customRoles;
1504
- if (custom === void 0) return sourcesBodyOf(declared, sources, subjectIdSql(ctx));
1505
- const match = [
1506
- customTenantMatch(ctx, `(${tenant})::text`, scope, "r.role"),
1507
- `c.scope = ${quoteLiteral(scope)}`,
1508
- "(c.scope_id is null or c.scope_id = (ms.id)::text)",
1509
- "c.role = r.role"
1510
- ].join(" and ");
1511
- const entries = (source, value, extra) => `array(select c.${value} from ${qualified(ctx, source)} c where ${match}${extra})`;
1512
- if (set) return sourcesBodyOf(`${declared}
1513
- union
1514
- select (ms.id)::${type}, ck.grant_key
1515
- ${rows}
1516
- ${customKeysJoin(ctx, scope, entries(CUSTOM_ROLES.permissions, allowEntry(ctx), " and c.effect = 'allow'"), entries(CUSTOM_ROLES.permissions, "permission", " and c.effect = 'deny'"), entries(CUSTOM_ROLES.includes, "include_role", ""))}
1517
- where ${signedIn(ctx)}
1518
- and ms.scope = ${quoteLiteral(scope)}
1519
- and not (r.role = any(${sqlTextArray(custom.declared)}))${narrow}${sourceFilters(ctx, scope, subjectIdSql(ctx), grantPermissionSql("ck.grant_key"), sourcesKeep(sources))}`, sources, subjectIdSql(ctx));
1520
- return sourcesBodyOf(`${declared}
1521
- union
1522
- select (ms.id)::${type}
1523
- ${rows}
1524
- where ${signedIn(ctx)}
1525
- and ms.scope = ${quoteLiteral(scope)}
1526
- and not (r.role = any(${sqlTextArray(custom.declared)}))${narrow}${sourceFilters(ctx, scope, subjectIdSql(ctx), grantPermissionSql("p_grant"), sourcesKeep(sources))}
1527
- ${customKeysSql(ctx, scope, entries(CUSTOM_ROLES.permissions, allowEntry(ctx), " and c.effect = 'allow'"), entries(CUSTOM_ROLES.permissions, "permission", " and c.effect = 'deny'"), entries(CUSTOM_ROLES.includes, "include_role", ""))}`, sources, subjectIdSql(ctx));
1528
- }
1529
- function scopedBody(ctx, scope, type) {
1530
- if (ctx.authorize !== "database") return sqlBody(claimBody(ctx, scope, type));
1531
- return scopeSources(ctx, scope).length > 0 ? sourcesBody(ctx, scope, type) : sqlBody(tableBody(ctx, scope, type));
1532
- }
1533
- //#endregion
1534
- //#region src/cli/rls/capabilities.ts
1535
- /**
1536
- * The helper `--capabilities` adds: ids of one resource a link capability claim
1537
- * reaches. Part of the SQL contract.
1538
- */
1539
- const CAPABILITIES = { ids: "permdock_capability_ids" };
1540
- /**
1541
- * The `anon` branch access for a resource-scoped grant reached through a link
1542
- * capability: the row's `field` holds an id the capability claim names for
1543
- * `resource`, `role` and `permission`. Uncorrelated, so it runs once per
1544
- * statement; the column is compared as text because the claim holds text.
1545
- */
1546
- function capabilityAccessSql(ctx, field, resource, role, permission) {
1547
- const args = [
1548
- resource,
1549
- role,
1550
- permission
1551
- ].map(quoteLiteral).join(", ");
1552
- return `${quoteIdent(field)}::text in (select ${qualified(ctx, CAPABILITIES.ids)}(${args}))`;
1553
- }
1554
- function capabilitiesSql(ctx) {
1555
- if (ctx.capabilities !== true) return "";
1556
- const fn = qualified(ctx, CAPABILITIES.ids);
1557
- return `-- link capabilities: the capability claim exchangeCapability mints (role anon, short-lived)
1558
- create or replace function ${fn}(p_resource text, p_role text, p_permission text)
1559
- returns setof text
1560
- language sql
1561
- stable
1562
- set search_path = ''
1563
- as $$
1564
- select c -> 'on' ->> 'id'
1565
- from (select ${subjectClaimJsonSql(ctx, "capability")} as c) capability
1566
- where jsonb_typeof(c) = 'object'
1567
- and c ->> 'v' = '1'
1568
- and c ->> 'holder' = 'link'
1569
- and c -> 'on' ->> 'resource' = p_resource
1570
- and jsonb_typeof(c -> 'roles') = 'array'
1571
- and c -> 'roles' @> jsonb_build_array(p_role)
1572
- and (c -> 'permissions' is null or c -> 'permissions' @> jsonb_build_array(p_permission))
1573
- and jsonb_typeof(c -> 'expires_at') = 'number'
1574
- and (c ->> 'expires_at')::numeric > extract(epoch from now())
1575
- $$;
1576
- revoke execute on function ${fn}(text, text, text) from public;
1577
- grant execute on function ${fn}(text, text, text) to anon, authenticated;`;
1578
- }
1579
- //#endregion
1580
- //#region src/cli/rls/custom-role-by-id.ts
1581
- const PREFIX = "PermDock CLI";
1582
- const col = (name) => `r.${quoteIdent(name)}`;
1583
- /**
1584
- * Custom-role functions keyed by the application's role row
1585
- * (`rls.customRoleWrites.roles.primaryKey`): the tenant, scope, instance and
1586
- * name come from the row, never from the caller. The writers delegate to
1587
- * `permdock_replace_custom_role_grants` (or its trusted variant), so every
1588
- * caller and definition check applies, and keep the stored denies and includes.
1589
- * The reader returns declared allow keys only and is executable by
1590
- * `rls.trustedReaders` alone.
1591
- */
1592
- function customRoleByIdSql(ctx, trustedReaders) {
1593
- const custom = ctx.customRoles;
1594
- const roles = custom?.table;
1595
- const root = ctx.scopes[0]?.name;
1596
- if (custom === void 0 || roles?.primaryKey === void 0 || ctx.authorize !== "database" || root === void 0) return "";
1597
- const pk = roles.primaryKey;
1598
- if (pk === "") throw configError(`${PREFIX}: rls.customRoleWrites.roles.primaryKey names no column`);
1599
- const leveled = custom.levels === true;
1600
- const tenantType = tenantTypeOf(ctx);
1601
- const table = quoteQualified(roles.table);
1602
- const idType = `${table}.${quoteIdent(pk)}%type`;
1603
- const perms = qualified(ctx, CUSTOM_ROLES.permissions);
1604
- const includes = qualified(ctx, CUSTOM_ROLES.includes);
1605
- const replace = qualified(ctx, CUSTOM_ROLES.replace);
1606
- const trustedReplace = qualified(ctx, CUSTOM_ROLES.trustedReplace);
1607
- const byId = qualified(ctx, CUSTOM_ROLES.replaceById);
1608
- const trustedById = qualified(ctx, CUSTOM_ROLES.trustedReplaceById);
1609
- const reader = qualified(ctx, CUSTOM_ROLES.trustedReadById);
1610
- const renames = Object.entries(custom.renamed ?? {}).toSorted(byKey);
1611
- const current = (expr) => currentKeyExpr(renames, expr);
1612
- const declaredKeys = sqlTextArray(custom.permissions ?? []);
1613
- const declaredRoles = sqlTextArray(custom.declared);
1614
- const tenant = roles.tenant === void 0 ? `null::${tenantType}` : `${col(roles.tenant)}::${tenantType}`;
1615
- const scope = rolesTableScope(roles, tenant, root, col);
1616
- const scopeId = roles.id === void 0 || roles.tenant === void 0 ? "null::text" : `case when ${tenant} is null then null else ${col(roles.id)}::text end`;
1617
- const skipped = roles.skip === void 0 || roles.tenant === void 0 ? "false" : `(${tenant} is not null and coalesce(${col(roles.skip)}, false))`;
1618
- const match = "c.tenant_id is not distinct from v_tenant and c.scope = v_scope and c.scope_id is not distinct from v_scope_id and c.role = v_key";
1619
- const audit = custom.audit;
1620
- const auditCall = audit === void 0 ? "" : `
1621
- perform ${quoteQualified(audit.function)}(${[
1622
- "event_type => 'permdock.custom_role.replaced'",
1623
- "target_type => 'role'",
1624
- "record_id => p_role_id::text",
1625
- "tenant => v_tenant",
1626
- "metadata => jsonb_build_object('operation', 'replace', 'role', v_key, 'permissions', p_permissions)",
1627
- ...Object.entries(audit.args ?? {}).toSorted(byKey).map(([name, value]) => `${quoteIdent(name)} => ${quoteLiteral(value)}`)
1628
- ].join(", ")});`;
1629
- const body = (write) => `declare
1630
- v_tenant ${tenantType};
1631
- v_scope text;
1632
- v_scope_id text;
1633
- v_key text;
1634
- v_skipped boolean;
1635
- v_deny text[];
1636
- v_include text[];
1637
- begin
1638
- select ${tenant}, ${scope}, ${scopeId}, ${col(roles.key)}::text, ${skipped}
1639
- into v_tenant, v_scope, v_scope_id, v_key, v_skipped
1640
- from ${table} r
1641
- where ${col(pk)} = p_role_id;
1642
- if not found then
1643
- ${raiseSql(" ", "P0002", "'permdock: no role row has id ' || coalesce(p_role_id::text, 'null')", "unknown-role")}
1644
- end if;
1645
- if v_skipped or v_key = any(${declaredRoles}) then
1646
- ${raiseSql(" ", "22023", "'permdock: ' || coalesce(v_key, 'null') || ' is a declared role, not a custom role'", "declared-role")}
1647
- end if;
1648
- select array_agg(c.permission) into v_deny
1649
- from ${perms} c
1650
- where ${match} and c.effect = 'deny';
1651
- select array_agg(c.include_role) into v_include
1652
- from ${includes} c
1653
- where ${match};
1654
- perform ${write}(v_tenant, v_scope, v_scope_id, v_key, p_permissions, v_deny, v_include);${auditCall}
1655
- end;`;
1656
- const writer = (comment, name, write, member) => `-- ${comment}
1657
- create or replace function ${name}(p_role_id ${idType}, p_permissions text[])
1658
- returns void
1659
- language plpgsql
1660
- volatile
1661
- security definer
1662
- set search_path = ''
1663
- as $$
1664
- ${body(write)}
1665
- $$;
1666
- ${member ? `revoke execute on function ${name}(${idType}, text[]) from public, anon;
1667
- grant execute on function ${name}(${idType}, text[]) to authenticated;` : `revoke execute on function ${name}(${idType}, text[]) from public, anon, authenticated;`}`;
1668
- const readerEntry = leveled ? `${current("c.permission")} || coalesce('@' || c.level, '')` : current("c.permission");
1669
- const readerGrant = trustedReaders === void 0 || trustedReaders.length === 0 ? "" : `\n${trustedReaderGrants(ctx, `${reader}(text[], ${tenantType})`, trustedReaders)}`;
1670
- return `${writer("save a custom role by its row id: the row supplies tenant, scope, instance and name; the caller checks of permdock_replace_custom_role_grants apply, and stored denies and includes stay", byId, replace, true)}
1671
-
1672
- ${writer("save a custom role by its row id for a trusted caller: the definition checks without the caller checks", trustedById, trustedReplace, false)}
1673
-
1674
- -- the declared allow keys of custom roles by their row ids as text, for a trusted reader; with p_tenant, an id of another tenant is refused
1675
- create or replace function ${reader}(p_role_ids text[], p_tenant ${tenantType} default null)
1676
- returns table (role_id text, permission text)
1677
- language plpgsql
1678
- stable
1679
- security definer
1680
- set search_path = ''
1681
- as $$
1682
- begin
1683
- if p_tenant is not null and exists (
1684
- select 1 from ${table} r
1685
- where ${col(pk)}::text = any(p_role_ids) and ${tenant} is distinct from p_tenant
1686
- ) then
1687
- ${raiseSql(" ", "42501", "'permdock: a role id belongs to another tenant than ' || p_tenant::text", "not-member")}
1688
- end if;
1689
- return query
1690
- select distinct v.role_id, ${readerEntry}
1691
- from (
1692
- select ${col(pk)}::text as role_id, ${tenant} as tenant_id, ${scope} as scope, ${scopeId} as scope_id, ${col(roles.key)}::text as role
1693
- from ${table} r
1694
- where ${col(pk)}::text = any(p_role_ids)
1695
- and not ${skipped}
1696
- and not (${col(roles.key)}::text = any(${declaredRoles}))
1697
- ) v
1698
- join ${perms} c
1699
- on c.tenant_id is not distinct from v.tenant_id
1700
- and c.scope = v.scope
1701
- and c.scope_id is not distinct from v.scope_id
1702
- and c.role = v.role
1703
- where c.effect = 'allow'
1704
- and ${current("c.permission")} = any(${declaredKeys})
1705
- order by 1, 2;
1706
- end;
1707
- $$;
1708
- revoke execute on function ${reader}(text[], ${tenantType}) from public, anon, authenticated;${readerGrant}`;
1709
- }
1710
- //#endregion
1711
- //#region src/cli/rls/custom-role-cascade.ts
1712
- /** `row.column`, for a trigger's `old` or `new`. */
1713
- function rowColumn(row, name) {
1714
- return `${row}.${quoteIdent(name)}`;
1715
- }
1716
- /** The custom-role rows of the role a trigger's `v_<prefix>_*` variables name. */
1717
- function cascadeMatch(prefix) {
1718
- return `c.tenant_id is not distinct from v_${prefix}_tenant and c.scope = v_${prefix}_scope and c.scope_id is not distinct from v_${prefix}_id and c.role = v_${prefix}_key`;
1719
- }
1720
- /**
1721
- * The trigger on the application's roles table (`rls.customRoleWrites.roles`):
1722
- * a rename, a move to another tenant, scope or instance, or a delete of a
1723
- * custom role's row carries its grants and includes along. A signed-in caller
1724
- * at trigger depth 1 passes the write functions' checks: authority over the
1725
- * stored definition where it was, and, after a move, membership and authority
1726
- * where it lands and entries inside that scope's ceiling. Other paths (a
1727
- * migration, a job, a nested trigger) move the rows as the function owner.
1728
- */
1729
- function customRoleCascadeSql(ctx) {
1730
- const custom = ctx.customRoles;
1731
- const table = custom?.table;
1732
- const root = ctx.scopes[0]?.name;
1733
- if (custom === void 0 || table === void 0 || root === void 0) return "";
1734
- const tenantType = tenantTypeOf(ctx);
1735
- const perms = qualified(ctx, CUSTOM_ROLES.permissions);
1736
- const includes = qualified(ctx, CUSTOM_ROLES.includes);
1737
- const fn = qualified(ctx, CUSTOM_ROLES.cascade);
1738
- const target = quoteTable(qualifySqlTable(table.table));
1739
- const tenant = (row) => table.tenant === void 0 ? `null::${tenantType}` : `${rowColumn(row, table.tenant)}::${tenantType}`;
1740
- const scope = (row) => rolesTableScope(table, tenant(row), root, (name) => rowColumn(row, name));
1741
- const id = (row) => table.id === void 0 || table.tenant === void 0 ? "null::text" : `case when ${tenant(row)} is null then null else ${rowColumn(row, table.id)}::text end`;
1742
- const skipped = (row) => table.skip === void 0 || table.tenant === void 0 ? "false" : `(${tenant(row)} is not null and coalesce(${rowColumn(row, table.skip)}, false))`;
1743
- const guard = qualified(ctx, CUSTOM_ROLES.guard);
1744
- const entries = qualified(ctx, CUSTOM_ROLES.entries);
1745
- const allowEntryOf = `c.${allowEntry(ctx)}`;
1746
- return `-- the application's roles table: renames, moves and deletes of a custom role carry its grants and includes
1747
- create or replace function ${fn}()
1748
- returns trigger
1749
- language plpgsql
1750
- volatile
1751
- security definer
1752
- set search_path = ''
1753
- as $$
1754
- declare
1755
- v_old_tenant ${tenantType} := ${tenant("old")};
1756
- v_old_scope text := ${scope("old")};
1757
- v_old_id text := ${id("old")};
1758
- v_old_key text := ${rowColumn("old", table.key)}::text;
1759
- v_new_tenant ${tenantType};
1760
- v_new_scope text;
1761
- v_new_id text;
1762
- v_new_key text;
1763
- v_checked boolean := ${signedIn(ctx)} and pg_trigger_depth() = 1;
1764
- v_allow text[];
1765
- v_deny text[];
1766
- v_include text[];
1767
- begin
1768
- if ${skipped("old")} then
1769
- return null;
1770
- end if;
1771
- if tg_op = 'UPDATE' and not ${skipped("new")} then
1772
- v_new_tenant := ${tenant("new")};
1773
- v_new_scope := ${scope("new")};
1774
- v_new_id := ${id("new")};
1775
- v_new_key := ${rowColumn("new", table.key)}::text;
1776
- if v_new_key = v_old_key
1777
- and v_new_tenant is not distinct from v_old_tenant
1778
- and v_new_scope = v_old_scope
1779
- and v_new_id is not distinct from v_old_id then
1780
- return null;
1781
- end if;
1782
- end if;
1783
- if not exists (select 1 from ${perms} c where ${cascadeMatch("old")})
1784
- and not exists (select 1 from ${includes} c where ${cascadeMatch("old")}) then
1785
- return null;
1786
- end if;
1787
- if v_checked then
1788
- perform ${guard}(v_old_tenant, v_old_scope, v_old_id, v_old_key);
1789
- end if;
1790
- if v_new_key is null then
1791
- delete from ${perms} c where ${cascadeMatch("old")};
1792
- delete from ${includes} c where ${cascadeMatch("old")};
1793
- return null;
1794
- end if;
1795
- if exists (select 1 from ${perms} c where ${cascadeMatch("new")})
1796
- or exists (select 1 from ${includes} c where ${cascadeMatch("new")}) then
1797
- ${raiseSql(" ", "22023", `'permdock: ' || v_new_key || ' already has grants'`, "role-exists")}
1798
- end if;
1799
- update ${perms} c set tenant_id = v_new_tenant, scope = v_new_scope, scope_id = v_new_id, role = v_new_key where ${cascadeMatch("old")};
1800
- update ${includes} c set tenant_id = v_new_tenant, scope = v_new_scope, scope_id = v_new_id, role = v_new_key where ${cascadeMatch("old")};
1801
- if v_checked then
1802
- perform ${guard}(v_new_tenant, v_new_scope, v_new_id, v_new_key);
1803
- select array_agg(${allowEntryOf}) filter (where c.effect = 'allow'),
1804
- array_agg(c.permission) filter (where c.effect = 'deny')
1805
- into v_allow, v_deny
1806
- from ${perms} c
1807
- where ${cascadeMatch("new")};
1808
- select array_agg(c.include_role) into v_include
1809
- from ${includes} c
1810
- where ${cascadeMatch("new")};
1811
- perform ${entries}(v_new_scope, v_allow, v_deny, v_include);
1812
- end if;
1813
- return null;
1814
- end;
1815
- $$;
1816
- revoke execute on function ${fn}() from public, anon, authenticated;
1817
- drop trigger if exists "permdock_custom_role_cascade" on ${target};
1818
- create trigger "permdock_custom_role_cascade"
1819
- after update or delete on ${target}
1820
- for each row execute function ${fn}();
1821
- `;
1822
- }
1823
- //#endregion
1824
- //#region src/cli/rls/custom-role-guard.ts
1825
- /** A column of the roles-table row a trigger sees as `new`. */
1826
- function column(name) {
1827
- return `new.${quoteIdent(name)}`;
1828
- }
1829
- /**
1830
- * The trigger on the application's roles table (`rls.customRoleWrites.roles`)
1831
- * that refuses a tenant row named like a declared role (`declared-role`) or
1832
- * like a shared custom role (`name-taken`). A row the `skip` column marks is a
1833
- * system role of the tenant and passes. Empty without a tenant column: then no
1834
- * row is a tenant row.
1835
- */
1836
- function customRoleNameGuardSql(ctx) {
1837
- const custom = ctx.customRoles;
1838
- const table = custom?.table;
1839
- const root = ctx.scopes[0]?.name;
1840
- if (custom === void 0 || table?.tenant === void 0 || root === void 0) return "";
1841
- const tenant = `${column(table.tenant)}::${tenantTypeOf(ctx)}`;
1842
- const skipped = table.skip === void 0 ? "false" : `coalesce(${column(table.skip)}, false)`;
1843
- const fn = qualified(ctx, CUSTOM_ROLES.nameGuard);
1844
- const target = quoteTable(qualifySqlTable(table.table));
1845
- const key = `${column(table.key)}::text`;
1846
- const scope = rolesTableScope(table, tenant, root, column);
1847
- return `-- the application's roles table: a tenant row cannot take the name of a declared or a shared role
1848
- create or replace function ${fn}()
1849
- returns trigger
1850
- language plpgsql
1851
- volatile
1852
- security definer
1853
- set search_path = ''
1854
- as $$
1855
- begin
1856
- if ${tenant} is null or ${skipped} then
1857
- return new;
1858
- end if;
1859
- if ${key} = any(${sqlTextArray(custom.declared)}) then
1860
- ${raiseSql(" ", "22023", `'permdock: ' || ${key} || ' is a declared role'`, "declared-role")}
1861
- end if;
1862
- if ${qualified(ctx, CUSTOM_ROLES.shared)}(${scope}, ${key}) then
1863
- ${raiseSql(" ", "22023", `'permdock: ' || ${key} || ' is a shared role'`, "name-taken")}
1864
- end if;
1865
- return new;
1866
- end;
1867
- $$;
1868
- revoke execute on function ${fn}() from public, anon, authenticated;
1869
- drop trigger if exists "permdock_custom_role_name_guard" on ${target};
1870
- create trigger "permdock_custom_role_name_guard"
1871
- before insert or update on ${target}
1872
- for each row execute function ${fn}();
1873
- `;
1874
- }
1875
- //#endregion
1876
- //#region src/cli/rls/custom-role-writes.ts
1877
- function callerFunctionsSql(ctx, custom, root, levelReach, forUser) {
1878
- const leveled = custom.levels === true;
1879
- const tenantType = tenantTypeOf(ctx);
1880
- const volatility = forUser || !memoizes(ctx) ? "stable" : "volatile";
1881
- const rp = qualified(ctx, "role_permissions");
1882
- const keys = qualified(ctx, CUSTOM_ROLES.keys);
1883
- const perms = qualified(ctx, CUSTOM_ROLES.permissions);
1884
- const includes = qualified(ctx, CUSTOM_ROLES.includes);
1885
- const shape = qualified(ctx, CUSTOM_ROLES.shape);
1886
- const beyond = qualified(ctx, forUser ? CUSTOM_ROLES.beyondFor : CUSTOM_ROLES.beyond);
1887
- const guard = qualified(ctx, forUser ? CUSTOM_ROLES.guardFor : CUSTOM_ROLES.guard);
1888
- const user = forUser ? "p_user" : subjectIdSql(ctx);
1889
- const userParam = forUser ? "p_user uuid, " : "";
1890
- const userArg = forUser ? "uuid, " : "";
1891
- const userCall = forUser ? "p_user, " : "";
1892
- const has = (key) => forUser ? `${qualified(ctx, HELPERS.hasFor)}(p_user, ${key})` : `${qualified(ctx, HELPERS.has)}(${key})`;
1893
- const ids = (helper, arg) => `(select x::text from ${qualified(ctx, helper)}(${arg}) x)`;
1894
- const permitted = (scope, key) => forUser ? ids(permittedForHelper(scope), `p_user, ${key}`) : ids(permittedIdsHelper(scope), key);
1895
- const members = (scope) => forUser ? ids(memberForHelper(scope), "p_user") : ids(memberIdsHelper(scope), "");
1896
- const heldKey = (key) => `(${has(key)}
1897
- or (p_scope <> 'global'
1898
- and (p_tenant::text in ${permitted(root, key)}
1899
- or ${perScope(ctx, (scope) => scope === root ? "false" : `p_scope_id in ${permitted(scope, key)}`)})))`;
1900
- const holdsAny = (permissions, held) => permissions.length === 0 ? "false" : `exists (
1901
- select 1 from ${rp} rp
1902
- where rp.effect = 'allow'
1903
- and rp.permission = any(${sqlTextArray(permissions)})
1904
- and ${held("rp.grant_key")}
1905
- )`;
1906
- const manageKeys = custom.manage ?? [];
1907
- const manage = holdsAny(manageKeys, heldKey);
1908
- const platform = holdsAny(manageKeys, has);
1909
- const requires = custom.requires === void 0 ? "" : `
1910
- if not ${holdsAny(custom.requires, heldKey)} then
1911
- ${raiseSql(" ", "42501", `'permdock: the caller may not manage roles in ' || coalesce(p_tenant::text, 'the platform')`, "manage-roles")}
1912
- end if;`;
1913
- const reachRows = levelReach.map(([grantKey, level]) => `(${quoteLiteral(grantKey)}, ${quoteLiteral(level)})`).join(", ");
1914
- const levelCheck = leveled && reachRows !== "" ? `
1915
- or exists (
1916
- select 1
1917
- from reach x
1918
- where x.grant_key = r.grant_key
1919
- and not exists (
1920
- select 1 from held h
1921
- join reach o on o.grant_key = h.grant_key
1922
- where h.permission = r.permission and o.level = x.level
1923
- )
1924
- )` : "";
1925
- const reachCte = leveled && reachRows !== "" ? `,
1926
- reach (grant_key, level) as (values ${reachRows})` : "";
1927
- const match = `${storedTenant(ctx)} and c.scope = p_scope and c.scope_id is not distinct from p_scope_id`;
1928
- const memberOf = `p_tenant::text in ${members(root)}
1929
- or ${perScope(ctx, (scope) => scope === root ? "false" : `p_scope_id in ${members(scope)}`)}`;
1930
- return {
1931
- beyond: `-- custom-role writes: the permission keys of a definition the caller may not hand out in the tenant, as assignablePermissions computes them
1932
- create or replace function ${beyond}(${userParam}p_tenant ${tenantType}, p_scope text, p_scope_id text, p_allow text[], p_deny text[], p_include text[])
1933
- returns setof text
1934
- language plpgsql
1935
- ${volatility}
1936
- security definer
1937
- set search_path = ''
1938
- as $$
1939
- begin
1940
- if ${manage} then
1941
- return;
1942
- end if;
1943
- return query
1944
- with resolved as (
1945
- select distinct rp.permission, k.key as grant_key
1946
- from ${keys}(p_allow, p_deny, p_include, p_scope) k(key)
1947
- join ${rp} rp on rp.grant_key = k.key and rp.effect = 'allow'
1948
- ),
1949
- held as (
1950
- select distinct rp.permission, rp.grant_key
1951
- from ${rp} rp
1952
- where rp.effect = 'allow'
1953
- and rp.permission in (select r.permission from resolved r)
1954
- and ${heldKey("rp.grant_key")}
1955
- )${reachCte}
1956
- select distinct r.permission
1957
- from resolved r
1958
- where not exists (select 1 from held h where h.permission = r.permission)${levelCheck};
1959
- end;
1960
- $$;
1961
- revoke execute on function ${beyond}(${userArg}${tenantType}, text, text, text[], text[], text[]) from public, anon, authenticated;`,
1962
- guard: `-- a custom role the caller may change: membership of the tenant or the instance (a platform role, or a caller holding a manageRoles permission through a global role, needs none), and authority over the stored definition
1963
- create or replace function ${guard}(${userParam}p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text)
1964
- returns void
1965
- language plpgsql
1966
- ${volatility}
1967
- security definer
1968
- set search_path = ''
1969
- as $$
1970
- declare
1971
- v_allow text[];
1972
- v_deny text[];
1973
- v_include text[];
1974
- v_beyond text;
1975
- begin
1976
- perform ${shape}(p_tenant, p_scope, p_scope_id, p_role);
1977
- if not (${signedIn(ctx, user)} and (
1978
- ${platform}
1979
- or (p_scope <> 'global' and coalesce(${memberOf}, false))
1980
- )) then
1981
- ${raiseSql(" ", "42501", `'permdock: the caller is not a member of ' || coalesce(p_tenant::text, 'the platform')`, "not-member")}
1982
- end if;${requires}
1983
- select array_agg(${allowEntry(ctx)}) filter (where c.effect = 'allow'),
1984
- array_agg(c.permission) filter (where c.effect = 'deny')
1985
- into v_allow, v_deny
1986
- from ${perms} c
1987
- where ${match} and c.role = p_role;
1988
- select array_agg(c.include_role) into v_include
1989
- from ${includes} c
1990
- where ${match} and c.role = p_role;
1991
- select string_agg(b, ', ' order by b) into v_beyond
1992
- from ${beyond}(${userCall}p_tenant, p_scope, p_scope_id, v_allow, v_deny, v_include) b;
1993
- if v_beyond is not null then
1994
- ${raiseSql(" ", "42501", `'permdock: ' || p_role || ' allows ' || v_beyond || ', which the caller may not hand out'`, "not-assignable-by")}
1995
- end if;
1996
- end;
1997
- $$;
1998
- revoke execute on function ${guard}(${userArg}${tenantType}, text, text, text) from public, anon, authenticated;`
1999
- };
2000
- }
2001
- /**
2002
- * The functions an application calls to save, rename and delete a custom role
2003
- * in \`database\` mode, with the rules of \`validateCustomRole\` and
2004
- * \`assignablePermissions\`: entries inside the ceiling of the role's scope,
2005
- * includes naming declared roles, and only permissions and levels the caller
2006
- * may hand out, for the new definition and the stored one alike. A platform
2007
- * custom role (\`p_scope = 'global'\`, no tenant) and a shared custom role (no
2008
- * tenant at a lower scope) are written by a caller who holds a
2009
- * \`meta.manageRoles\` permission through a global role. The
2010
- * \`permdock_trusted_*\` variants skip the caller checks and keep the
2011
- * definition checks; no client role may execute them.
2012
- */
2013
- function customRoleWritesSql(ctx, levelReach) {
2014
- const custom = ctx.customRoles;
2015
- const root = ctx.scopes[0]?.name;
2016
- if (custom === void 0 || ctx.authorize !== "database" || root === void 0) return "";
2017
- const leveled = custom.levels === true;
2018
- const tenantType = tenantTypeOf(ctx);
2019
- const rp = qualified(ctx, "role_permissions");
2020
- const ceiling = qualified(ctx, CUSTOM_ROLES.ceiling);
2021
- const perms = qualified(ctx, CUSTOM_ROLES.permissions);
2022
- const includes = qualified(ctx, CUSTOM_ROLES.includes);
2023
- const beyond = qualified(ctx, CUSTOM_ROLES.beyond);
2024
- const guard = qualified(ctx, CUSTOM_ROLES.guard);
2025
- const shape = qualified(ctx, CUSTOM_ROLES.shape);
2026
- const entries = qualified(ctx, CUSTOM_ROLES.entries);
2027
- const problem = qualified(ctx, CUSTOM_ROLES.entryProblem);
2028
- const renames = Object.entries(custom.renamed ?? {}).toSorted(byKey);
2029
- const current = (expr) => currentKeyExpr(renames, expr);
2030
- const known = sqlTextArray([...custom.permissions ?? [], ...renames.map(([former]) => former)]);
2031
- const caller = callerFunctionsSql(ctx, custom, root, levelReach, false);
2032
- const match = `c.tenant_id is not distinct from p_tenant and c.scope = p_scope and c.scope_id is not distinct from p_scope_id`;
2033
- const scopes = sqlTextArray(ctx.scopes.map((scope) => scope.name));
2034
- const roleName = (param) => `coalesce(${param}, '') = '' or ${param} = any(${sqlTextArray(custom.declared)})`;
2035
- const levelOf = leveled ? ", nullif(split_part(e, '@', 2), '')" : "";
2036
- const levelColumn = leveled ? ", level" : "";
2037
- const sharedRole = qualified(ctx, CUSTOM_ROLES.shared);
2038
- const taken = (param) => ` if p_tenant is not null and ${sharedRole}(p_scope, ${param}) then
2039
- ${raiseSql(" ", "22023", `'permdock: ' || ${param} || ' is the name of a shared custom role'`, "name-taken")}
2040
- end if;
2041
- `;
2042
- const write = `${taken("p_role")} delete from ${perms} c where ${match} and c.role = p_role;
2043
- delete from ${includes} c where ${match} and c.role = p_role;
2044
- insert into ${perms} (tenant_id, scope, scope_id, role, permission, effect${levelColumn})
2045
- select distinct p_tenant, p_scope, p_scope_id, p_role, ${current(leveled ? "split_part(e, '@', 1)" : "e")}, 'allow'${levelOf}
2046
- from unnest(coalesce(p_allow, '{}'::text[])) e
2047
- union
2048
- select distinct p_tenant, p_scope, p_scope_id, p_role, ${current("e")}, 'deny'${leveled ? ", null" : ""}
2049
- from unnest(coalesce(p_deny, '{}'::text[])) e;
2050
- insert into ${includes} (tenant_id, scope, scope_id, role, include_role)
2051
- select distinct p_tenant, p_scope, p_scope_id, p_role, e
2052
- from unnest(coalesce(p_include, '{}'::text[])) e;`;
2053
- const move = `${taken("p_to")} if ${roleName("p_to")} then
2054
- ${raiseSql(" ", "22023", `'permdock: ' || coalesce(p_to, 'null') || ' is not a custom role name'`, "declared-role")}
2055
- end if;
2056
- if exists (select 1 from ${perms} c where ${match} and c.role = p_to)
2057
- or exists (select 1 from ${includes} c where ${match} and c.role = p_to) then
2058
- ${raiseSql(" ", "22023", `'permdock: ' || p_to || ' already has grants'`, "role-exists")}
2059
- end if;
2060
- update ${perms} c set role = p_to where ${match} and c.role = p_from;
2061
- update ${includes} c set role = p_to where ${match} and c.role = p_from;`;
2062
- const remove = ` delete from ${perms} c where ${match} and c.role = p_role;
2063
- delete from ${includes} c where ${match} and c.role = p_role;`;
2064
- const writeArgs = `${tenantType}, text, text, text, text[], text[], text[]`;
2065
- const renameArgs = `${tenantType}, text, text, text, text`;
2066
- const removeArgs = `${tenantType}, text, text, text`;
2067
- const fn = (comment, name, params, args, body, member) => `-- ${comment}
2068
- create or replace function ${qualified(ctx, name)}(${params})
2069
- returns void
2070
- language plpgsql
2071
- volatile
2072
- security definer
2073
- set search_path = ''
2074
- as $$
2075
- ${body}
2076
- $$;
2077
- ${member ? `revoke execute on function ${qualified(ctx, name)}(${args}) from public, anon;
2078
- grant execute on function ${qualified(ctx, name)}(${args}) to authenticated;` : `revoke execute on function ${qualified(ctx, name)}(${args}) from public, anon, authenticated;`}`;
2079
- const writeParams = `p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text, p_allow text[], p_deny text[], p_include text[]`;
2080
- const renameParams = `p_tenant ${tenantType}, p_scope text, p_scope_id text, p_from text, p_to text`;
2081
- const removeParams = `p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text`;
2082
- return `${caller.beyond}
2083
-
2084
- -- where a custom role may live: a scope of a tenant, a scope of every tenant (shared: no tenant or instance), or the platform (scope global, no tenant or instance), under an undeclared name
2085
- create or replace function ${shape}(p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text)
2086
- returns void
2087
- language plpgsql
2088
- stable
2089
- set search_path = ''
2090
- as $$
2091
- begin
2092
- if p_scope = 'global' then
2093
- if p_tenant is not null or p_scope_id is not null then
2094
- ${raiseSql(" ", "22023", `'permdock: a platform custom role has no tenant or instance'`, "unknown-scope")}
2095
- end if;
2096
- elsif not (p_scope = any(${scopes})) then
2097
- ${raiseSql(" ", "22023", `'permdock: custom roles are held at a scope of a tenant or at global, not ' || coalesce(p_scope, 'null')`, "unknown-scope")}
2098
- elsif p_tenant is null and p_scope_id is not null then
2099
- ${raiseSql(" ", "22023", `'permdock: a shared custom role has no instance'`, "unknown-scope")}
2100
- end if;
2101
- if ${roleName("p_role")} then
2102
- ${raiseSql(" ", "22023", `'permdock: ' || coalesce(p_role, 'null') || ' is not a custom role name'`, "declared-role")}
2103
- end if;
2104
- end;
2105
- $$;
2106
- revoke execute on function ${shape}(${tenantType}, text, text, text) from public, anon, authenticated;
2107
-
2108
- ${caller.guard}
2109
- ${hasCustomRoleChecksFor(ctx) ? `
2110
- -- the same checks for a user the caller names: trusted SQL acting later for a stored user; no client role may execute them
2111
- ${callerFunctionsSql(ctx, custom, root, levelReach, true).beyond}
2112
-
2113
- ${callerFunctionsSql(ctx, custom, root, levelReach, true).guard}
2114
- ` : ""}
2115
- -- null when an allow entry is a declared permission inside the ceiling of the scope${leveled ? ", at a level the resource declares" : ""}; else unknown-permission, outside-ceiling${leveled ? " or unknown-level" : ""}
2116
- create or replace function ${problem}(p_scope text, p_entry text)
2117
- returns text
2118
- language plpgsql
2119
- stable
2120
- security definer
2121
- set search_path = ''
2122
- as $$
2123
- declare
2124
- v_key text := ${current(leveled ? "split_part(p_entry, '@', 1)" : "p_entry")};
2125
- begin
2126
- if p_entry is null or not (v_key = any(${known})) then
2127
- return 'unknown-permission';
2128
- end if;
2129
- if not exists (
2130
- select 1 from ${ceiling} c
2131
- where c.scope = p_scope and c.effect = 'allow' and ${current("c.permission")} = v_key
2132
- ) then
2133
- return 'outside-ceiling';
2134
- end if;${leveled ? `
2135
- if strpos(p_entry, '@') > 0 and not exists (
2136
- select 1 from ${ceiling} c
2137
- where c.scope = p_scope and c.effect = 'allow' and ${current("c.permission")} = v_key
2138
- and split_part(c.grant_key, '@', 2) = split_part(p_entry, '@', 2)
2139
- ) then
2140
- return 'unknown-level';
2141
- end if;` : ""}
2142
- return null;
2143
- end;
2144
- $$;
2145
- revoke execute on function ${problem}(text, text) from public, anon, authenticated;
2146
-
2147
- -- the entries of a definition: declared keys and levels inside the ceiling of the scope, and declared includes
2148
- create or replace function ${entries}(p_scope text, p_allow text[], p_deny text[], p_include text[])
2149
- returns void
2150
- language plpgsql
2151
- stable
2152
- security definer
2153
- set search_path = ''
2154
- as $$
2155
- declare
2156
- v_entry text;
2157
- v_key text;
2158
- v_problem text;
2159
- begin
2160
- foreach v_entry in array coalesce(p_allow, '{}'::text[]) loop
2161
- v_key := ${current(leveled ? "split_part(v_entry, '@', 1)" : "v_entry")};
2162
- v_problem := ${problem}(p_scope, v_entry);
2163
- if v_problem = 'unknown-permission' then
2164
- ${raiseSql(" ", "22023", `'permdock: ' || v_entry || ' is not a declared permission'`, "unknown-permission")}
2165
- end if;
2166
- if v_problem = 'outside-ceiling' then
2167
- ${raiseSql(" ", "22023", `'permdock: ' || v_key || ' is outside the ceiling of ' || p_scope`, "outside-ceiling")}
2168
- end if;${leveled ? `
2169
- if v_problem = 'unknown-level' then
2170
- ${raiseSql(" ", "22023", `'permdock: ' || v_entry || ' names a level the resource does not declare'`, "unknown-level")}
2171
- end if;` : ""}
2172
- end loop;
2173
- foreach v_entry in array coalesce(p_deny, '{}'::text[]) loop
2174
- if not (v_entry = any(${known})) then
2175
- ${raiseSql(" ", "22023", `'permdock: ' || v_entry || ' is not a declared permission'`, "unknown-permission")}
2176
- end if;
2177
- end loop;
2178
- foreach v_entry in array coalesce(p_include, '{}'::text[]) loop
2179
- if not (v_entry = any(${sqlTextArray(custom.declared)})) then
2180
- ${raiseSql(" ", "22023", `'permdock: ' || v_entry || ' is not a declared role'`, "unknown-role")}
2181
- end if;
2182
- end loop;
2183
- select string_agg(distinct ${current("rp.permission")}, ', ') into v_key
2184
- from ${rp} rp
2185
- where rp.role = any(coalesce(p_include, '{}'::text[]))
2186
- and rp.effect = 'allow'
2187
- and not exists (
2188
- select 1 from ${ceiling} c
2189
- where c.scope = p_scope and c.effect = 'allow' and ${current("c.permission")} = ${current("rp.permission")}
2190
- );
2191
- if v_key is not null then
2192
- ${raiseSql(" ", "22023", `'permdock: an included role allows ' || v_key || ', outside the ceiling of ' || p_scope`, "outside-ceiling")}
2193
- end if;
2194
- end;
2195
- $$;
2196
- revoke execute on function ${entries}(text, text[], text[], text[]) from public, anon, authenticated;
2197
-
2198
- ${fn("save a custom role: replace its grants and includes after checking each entry against the ceiling and the caller's own permissions", CUSTOM_ROLES.replace, writeParams, writeArgs, `declare
2199
- v_beyond text;
2200
- begin
2201
- perform ${guard}(p_tenant, p_scope, p_scope_id, p_role);
2202
- perform ${entries}(p_scope, p_allow, p_deny, p_include);
2203
- select string_agg(b, ', ' order by b) into v_beyond
2204
- from ${beyond}(p_tenant, p_scope, p_scope_id, p_allow, p_deny, p_include) b;
2205
- if v_beyond is not null then
2206
- ${raiseSql(" ", "42501", `'permdock: ' || p_role || ' would allow ' || v_beyond || ', which the caller may not hand out'`, "not-assignable-by")}
2207
- end if;
2208
- ${write}
2209
- end;`, true)}
2210
-
2211
- ${fn("rename a custom role: move its grants and includes to the new name", CUSTOM_ROLES.rename, renameParams, renameArgs, `begin
2212
- perform ${guard}(p_tenant, p_scope, p_scope_id, p_from);
2213
- ${move}
2214
- end;`, true)}
2215
-
2216
- ${fn("delete a custom role: remove its grants and includes", CUSTOM_ROLES.remove, removeParams, removeArgs, `begin
2217
- perform ${guard}(p_tenant, p_scope, p_scope_id, p_role);
2218
- ${remove}
2219
- end;`, true)}
2220
-
2221
- ${fn("save a custom role for a trusted caller (a migration, a job, a backend role granted execute): the definition checks without the caller checks", CUSTOM_ROLES.trustedReplace, writeParams, writeArgs, `begin
2222
- perform ${shape}(p_tenant, p_scope, p_scope_id, p_role);
2223
- perform ${entries}(p_scope, p_allow, p_deny, p_include);
2224
- ${write}
2225
- end;`, false)}
2226
-
2227
- ${fn("rename a custom role for a trusted caller", CUSTOM_ROLES.trustedRename, renameParams, renameArgs, `begin
2228
- perform ${shape}(p_tenant, p_scope, p_scope_id, p_from);
2229
- ${move}
2230
- end;`, false)}
2231
-
2232
- ${fn("delete a custom role for a trusted caller", CUSTOM_ROLES.trustedRemove, removeParams, removeArgs, `begin
2233
- perform ${shape}(p_tenant, p_scope, p_scope_id, p_role);
2234
- ${remove}
2235
- end;`, false)}`;
2236
- }
2237
- //#endregion
2238
- //#region src/cli/rls/global-roles.ts
2239
- /**
2240
- * `permdock_replace_global_roles(p_user, p_roles)`: sets the global roles of
2241
- * one user in `rls.roles` in one statement pair. It runs as the invoker, so the
2242
- * table's policies and the `rls.assignments` trigger judge every row it deletes
2243
- * or inserts.
2244
- */
2245
- function globalRolesSql(ctx) {
2246
- if (ctx.roles === void 0) return "";
2247
- const source = globalRoleSource(ctx.roles, "public", "t", ctx.customRoles?.table);
2248
- const table = quoteQualified(ctx.roles.table);
2249
- const user = quoteIdent(source.user);
2250
- const fn = qualified(ctx, GLOBAL_ROLES.replace);
2251
- const type = ctx.dialect === "supabase" ? "uuid" : "text";
2252
- const wanted = `select distinct r from unnest(coalesce(p_roles, '{}'::text[])) r where r is not null`;
2253
- const through = source.through;
2254
- let body;
2255
- if (through === void 0) {
2256
- const role = typeof ctx.roles.role === "string" ? ctx.roles.role : "role";
2257
- const column = quoteIdent(role);
2258
- body = ` delete from ${table} t
2259
- where t.${user} = p_user
2260
- and t.${column}::text <> all(coalesce(p_roles, '{}'::text[]));
2261
- insert into ${table} (${user}, ${column})
2262
- select p_user, w.r
2263
- from (${wanted}) w(r)
2264
- where not exists (
2265
- select 1 from ${table} t where t.${user} = p_user and t.${column}::text = w.r
2266
- );`;
2267
- } else {
2268
- const keys = quoteTable(through.table);
2269
- const id = quoteIdent(through.id);
2270
- const key = quoteIdent(through.key);
2271
- const ref = quoteIdent(through.ref);
2272
- const global = source.tenant === void 0 ? "" : ` and k.${quoteIdent(source.tenant)} is null${source.shared === void 0 ? "" : ` and k.${quoteIdent(source.shared)} is not true`}`;
2273
- body = ` select string_agg(w.r, ', ' order by w.r) into v_unknown
2274
- from (${wanted}) w(r)
2275
- where not exists (select 1 from ${keys} k where k.${key}::text = w.r${global});
2276
- if v_unknown is not null then
2277
- raise exception using
2278
- errcode = '22023',
2279
- message = 'permdock: ' || v_unknown || ' is not a role',
2280
- hint = 'unknown-role';
2281
- end if;
2282
- delete from ${table} t
2283
- where t.${user} = p_user
2284
- and not exists (
2285
- select 1 from ${keys} k
2286
- where k.${id} = t.${ref}
2287
- and k.${key}::text = any(coalesce(p_roles, '{}'::text[]))${global}
2288
- );
2289
- insert into ${table} (${user}, ${ref})
2290
- select p_user, k.${id}
2291
- from ${keys} k
2292
- where k.${key}::text in (${wanted})${global}
2293
- and not exists (
2294
- select 1 from ${table} t where t.${user} = p_user and t.${ref} = k.${id}
2295
- );`;
2296
- }
2297
- const declare = through === void 0 ? "" : "declare\n v_unknown text;\n";
2298
- const args = `${type}, text[]`;
2299
- return `-- set the global roles of a user: delete the others and insert the missing ones, as the caller, so the table's policies and the assignment trigger still apply
2300
- create or replace function ${fn}(p_user ${type}, p_roles text[])
2301
- returns void
2302
- language plpgsql
2303
- volatile
2304
- set search_path = ''
2305
- as $$
2306
- ${declare}begin
2307
- ${body}
2308
- end;
2309
- $$;
2310
- revoke execute on function ${fn}(${args}) from public, anon;
2311
- grant execute on function ${fn}(${args}) to authenticated;`;
2312
- }
2313
- //#endregion
2314
- //#region src/cli/rls/helper-members.ts
2315
- /**
2316
- * The body of `member_<scope>_ids()`: instances of `scope` the subject holds a
2317
- * live membership of, with any role. Not narrowed to the active tenant, and no
2318
- * cascade: a membership of a child scope is not one of its parent.
2319
- */
2320
- function memberBody(ctx, scope, type, roles) {
2321
- if (ctx.authorize !== "database") return sqlBody(` select distinct (m ->> 'id')::${type}
2322
- from jsonb_array_elements(
2323
- case jsonb_typeof(${membershipClaim(ctx)}) when 'array' then ${membershipClaim(ctx)} else '[]'::jsonb end
2324
- ) m
2325
- where ${signedIn(ctx)}
2326
- and m ->> 'scope' = ${quoteLiteral(scope)}
2327
- and m ->> 'id' is not null${keyTenantLine(ctx, scope, claimTenant(ctx, scope))}
2328
- and jsonb_typeof(m -> 'roles') = 'array'
2329
- and jsonb_array_length(m -> 'roles') > 0${roles === void 0 ? "" : `\n and (m -> 'roles') ?| ${roles}`}
2330
- and case jsonb_typeof(m -> 'expires_at')
2331
- when 'number' then (m ->> 'expires_at')::numeric > extract(epoch from now())
2332
- else true
2333
- end${[
2334
- ...claimKeptLines(ctx, " "),
2335
- ...userActive(ctx, " "),
2336
- ...instancesActive(ctx, scope, (name) => name === scope ? `m ->> 'id'` : `m -> 'within' ->> ${quoteLiteral(name)}`, " ")
2337
- ].map((line) => `\n${line}`).join("")}`);
2338
- return memberRowsBody(ctx, scope, type, subjectIdSql(ctx), scopeSources(ctx, scope), true, roles);
2339
- }
2340
- /**
2341
- * The membership rows of `user` for `scope`, from the sources or else the
2342
- * mapped table, with the same expiry and suspension filters either way.
2343
- */
2344
- function memberRowsBody(ctx, scope, type, user, sources, keyed = false, roles) {
2345
- if (sources.length > 0) {
2346
- const narrow = keyed ? keyTenantLine(ctx, scope, sourceIdOf(scope)(rootName(ctx))) : "";
2347
- return sourcesBodyOf(` select distinct (ms.id)::${type}
2348
- from (
2349
- ${sourceRows(sources)}
2350
- ) ms
2351
- where ${signedIn(ctx, user)}
2352
- and ms.scope = ${quoteLiteral(scope)}
2353
- and jsonb_typeof(ms.roles) = 'array'
2354
- and jsonb_array_length(ms.roles) > 0${roles === void 0 ? "" : `\n and ms.roles ?| ${roles}`}${narrow}${sourceFilters(ctx, scope, user, void 0, sourcesKeep(sources))}`, sources, user);
2355
- }
2356
- const mapped = scopeTable(ctx, scope);
2357
- if (mapped === void 0) return sqlBody(` select null::${type} where false -- no ${scope} memberships table configured`);
2358
- const { table, column, tenantColumn } = mapped;
2359
- const role = memberRoleOf(table, "m", " ");
2360
- const lines = [
2361
- ` select distinct ${memberColumn(column)}::${type}`,
2362
- ` from ${quoteQualified(table.table)} m${role.join}`,
2363
- ` where ${memberColumn(table.user)} = ${user}`,
2364
- ` and ${role.through === void 0 && !role.lateral ? memberColumn(role.column) : role.sql} is not null`
2365
- ];
2366
- if (roles !== void 0) lines.push(` and (${role.through === void 0 && !role.lateral ? memberColumn(role.column) : role.sql})::text = any(${roles})`);
2367
- const narrow = keyed ? keyTenantSql(ctx, tenantColumn === void 0 ? void 0 : memberColumn(tenantColumn)) : void 0;
2368
- if (narrow !== void 0) lines.push(` and ${narrow}`);
2369
- if (table.expiresAt !== void 0) {
2370
- const expires = memberColumn(table.expiresAt);
2371
- lines.push(` and (${expires} is null or ${expires} > now())`);
2372
- }
2373
- lines.push(...activeMembershipSql(ctx, disabledColumn(table), void 0).map((part) => ` and ${part}`), ...userActive(ctx, " ", user), ...instancesActive(ctx, scope, (name) => {
2374
- const held = scopeColumn(table, ctx.scopes, name);
2375
- return held === void 0 ? void 0 : memberColumn(held);
2376
- }, " "));
2377
- return sqlBody(lines.join("\n"));
2378
- }
2379
- function membershipClaim(ctx) {
2380
- const raw = subjectClaimJsonSql(ctx, "memberships");
2381
- return ctx.dialect === "supabase" ? `coalesce(${raw}, (select auth.jwt()) -> 'app_metadata' -> 'memberships')` : raw;
2382
- }
2383
- function memberFunction(ctx, scope, type, anonExecute) {
2384
- const fn = qualified(ctx, memberIdsHelper(scope));
2385
- const body = memberBody(ctx, scope, type);
2386
- const keys = ctx.apiKeys;
2387
- const keyed = keys === void 0 || scope !== rootName(ctx) ? body : {
2388
- sql: `${body.sql}\n union\n${serviceKeyMemberSql(ctx, keys, scope, type)}`,
2389
- vars: body.vars
2390
- };
2391
- const grants = anonExecute ? `revoke execute on function ${fn}() from public;
2392
- grant execute on function ${fn}() to anon, authenticated;` : `revoke execute on function ${fn}() from public, anon;
2393
- grant execute on function ${fn}() to authenticated;`;
2394
- return `create or replace function ${fn}()
2395
- returns setof ${type}
2396
- ${functionBody(keyed)}
2397
- ${grants}`;
2398
- }
2399
- /**
2400
- * `member_<scope>_ids(p_roles text[])`: `member_<scope>_ids()` narrowed to
2401
- * memberships holding one of `p_roles` by name, for `rls migrate`'s `role`
2402
- * helpers. Generated only for a scope such a helper names.
2403
- */
2404
- function memberRolesFunction(ctx, scope, type, anonExecute) {
2405
- const fn = qualified(ctx, memberIdsHelper(scope));
2406
- const body = memberBody(ctx, scope, type, "p_roles");
2407
- const grants = anonExecute ? `revoke execute on function ${fn}(text[]) from public;
2408
- grant execute on function ${fn}(text[]) to anon, authenticated;` : `revoke execute on function ${fn}(text[]) from public, anon;
2409
- grant execute on function ${fn}(text[]) to authenticated;`;
2410
- return `create or replace function ${fn}(p_roles text[])
2411
- returns setof ${type}
2412
- ${functionBody(body)}
2413
- ${grants}`;
2414
- }
2415
- /**
2416
- * `member_<scope>_ids_for(p_user uuid)`: `member_<scope>_ids()` for a user the
2417
- * caller names, read from the membership sources (or the mapped table) in
2418
- * either mode, so a token hook can call it before any claim exists. Naming the
2419
- * user is why no client role may execute it; the hook's grants give
2420
- * `supabase_auth_admin` execute.
2421
- */
2422
- function memberForFunction(ctx, scope, type) {
2423
- const fn = qualified(ctx, memberForHelper(scope));
2424
- return `create or replace function ${fn}(p_user uuid)
2425
- returns setof ${type}
2426
- ${functionBody(memberRowsBody(ctx, scope, type, "p_user", memberForSources(ctx, scope)))}
2427
- revoke execute on function ${fn}(uuid) from public, anon, authenticated;`;
2428
- }
2429
- /**
2430
- * `member_<scope>_ids_of(p_user uuid)`: `member_<scope>_ids_for(p_user)` for
2431
- * the caller only. Any other `p_user` returns no rows, so a client role may
2432
- * execute it without learning another user's memberships.
2433
- */
2434
- function memberOfFunction(ctx, scope, type) {
2435
- const fn = qualified(ctx, memberOfHelper(scope));
2436
- return `create or replace function ${fn}(p_user uuid)
2437
- returns setof ${type}
2438
- ${functionBody(sqlBody(` select m.id
2439
- from ${qualified(ctx, memberForHelper(scope))}(p_user) as m(id)
2440
- where p_user = ${subjectIdSql(ctx)}`))}
2441
- revoke execute on function ${fn}(uuid) from public, anon;
2442
- grant execute on function ${fn}(uuid) to authenticated;`;
2443
- }
2444
- //#endregion
2445
- //#region src/cli/rls/memo-generation.ts
2446
- const BUMP = "permdock_bump_memo_generation";
2447
- const TRIGGER = "permdock_memo_generation";
2448
- function add(targets, table, columns = []) {
2449
- const key = qualifySqlTable(table);
2450
- const existing = targets.get(key);
2451
- if (existing === void 0) {
2452
- targets.set(key, {
2453
- table,
2454
- columns: columns.length === 0 ? void 0 : new Set(columns)
2455
- });
2456
- return;
2457
- }
2458
- if (existing.columns === void 0 || columns.length === 0) {
2459
- targets.set(key, {
2460
- table: existing.table,
2461
- columns: void 0
2462
- });
2463
- return;
2464
- }
2465
- for (const column of columns) existing.columns.add(column);
2466
- }
2467
- function suspensionTargets(targets, row) {
2468
- if (row === void 0) return;
2469
- const columns = [...row.disabledAt === void 0 ? [] : [row.disabledAt], ...row.status === void 0 ? [] : [row.status]];
2470
- add(targets, row.table, columns);
2471
- }
2472
- const IDENT = String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)`;
2473
- const READ = new RegExp(String.raw`(?<!\bdistinct\s+)(?<!\bextract\s*\([^()]*)\b(?:from|join)\s+(${IDENT})\.(${IDENT})(?![\w$]|\s*[.(])`, "gu");
2474
- const SYSTEM = /* @__PURE__ */ new Set([
2475
- "auth",
2476
- "pg_catalog",
2477
- "information_schema"
2478
- ]);
2479
- function unquote(name) {
2480
- return name.startsWith("\"") ? name.slice(1, -1).replaceAll("\"\"", "\"") : name;
2481
- }
2482
- function readTables(sql) {
2483
- const out = /* @__PURE__ */ new Set();
2484
- for (const [, schema = "", table = ""] of sql.matchAll(READ)) {
2485
- const name = unquote(schema);
2486
- if (!SYSTEM.has(name)) out.add(`${name}.${unquote(table)}`);
2487
- }
2488
- return [...out];
2489
- }
2490
- function memoTargets(ctx, reads) {
2491
- const schema = helperSchema(ctx);
2492
- const targets = /* @__PURE__ */ new Map();
2493
- add(targets, `${schema}.role_permissions`);
2494
- if (ctx.customRoles !== void 0) {
2495
- add(targets, `${schema}.${CUSTOM_ROLES.permissions}`);
2496
- add(targets, `${schema}.${CUSTOM_ROLES.includes}`);
2497
- const roles = ctx.customRoles.table;
2498
- if (roles !== void 0) add(targets, roles.table, [
2499
- roles.key,
2500
- ...roles.tenant === void 0 ? [] : [roles.tenant],
2501
- ...roles.scope === void 0 ? [] : [roles.scope]
2502
- ]);
2503
- }
2504
- suspensionTargets(targets, ctx.suspension?.users);
2505
- for (const row of Object.values(ctx.suspension?.scopes ?? {})) suspensionTargets(targets, row);
2506
- for (const table of readTables(reads)) if (!targets.has(qualifySqlTable(table))) add(targets, table);
2507
- return targets;
2508
- }
2509
- function triggersSql(ctx, targets) {
2510
- const trigger = qualified(ctx, TRIGGER);
2511
- return [...targets].map(({ table, columns }) => {
2512
- const target = quoteTable(qualifySqlTable(table));
2513
- const update = columns === void 0 ? "update" : `update of ${[...columns].map((column) => quoteIdent(column)).join(", ")}`;
2514
- return `drop trigger if exists ${quoteIdent(TRIGGER)} on ${target};
2515
- create trigger ${quoteIdent(TRIGGER)}
2516
- after insert or ${update} or delete on ${target}
2517
- for each statement execute function ${trigger}();
2518
- drop trigger if exists ${quoteIdent(`${TRIGGER}_truncate`)} on ${target};
2519
- create trigger ${quoteIdent(`${TRIGGER}_truncate`)}
2520
- after truncate on ${target}
2521
- for each statement execute function ${trigger}();`;
2522
- }).join("\n");
2523
- }
2524
- /**
2525
- * The triggers that invalidate the memo when a write changes permitted ids
2526
- * inside the statement: the permission map, a custom role's grants, a suspended
2527
- * user or scope, and every table `reads` (the memoized helper bodies) selects
2528
- * from, such as the membership sources and the global roles. The hook's version
2529
- * triggers call the same bump.
2530
- */
2531
- function memoGenerationSql(ctx, reads = "") {
2532
- if (!memoizes(ctx)) return "";
2533
- const bump = qualified(ctx, BUMP);
2534
- const trigger = qualified(ctx, TRIGGER);
2535
- return `-- a permission, custom-role, suspension or membership write changes permitted ids inside the statement
2536
- create or replace function ${bump}()
2537
- returns void
2538
- language sql
2539
- volatile
2540
- security definer
2541
- set search_path = ''
2542
- as $$
2543
- select set_config(
2544
- 'permdock.m.gen',
2545
- (coalesce(nullif(current_setting('permdock.m.gen', true), ''), '0')::int + 1)::text,
2546
- true
2547
- )
2548
- $$;
2549
- revoke execute on function ${bump}() from public, anon, authenticated;
2550
-
2551
- create or replace function ${trigger}()
2552
- returns trigger
2553
- language plpgsql
2554
- volatile
2555
- security definer
2556
- set search_path = ''
2557
- as $$
2558
- begin
2559
- perform ${bump}();
2560
- return null;
2561
- end;
2562
- $$;
2563
- revoke execute on function ${trigger}() from public, anon, authenticated;
2564
- ${triggersSql(ctx, memoTargets(ctx, reads).values())}`;
2565
- }
2566
- function memoReadTriggersSql(ctx, reads, covered) {
2567
- const done = memoTargets(ctx, covered);
2568
- const targets = /* @__PURE__ */ new Map();
2569
- for (const table of readTables(reads)) if (!done.has(qualifySqlTable(table))) add(targets, table);
2570
- return targets.size === 0 ? "" : triggersSql(ctx, targets.values());
2571
- }
2572
- //#endregion
2573
- //#region src/cli/rls/token-scopes.ts
2574
- const TOKEN_SCOPE_ALLOWS = "permdock_token_scope_allows";
2575
- const TOKEN_SCOPE_MAP = "permdock_token_scope_map";
2576
- /**
2577
- * `rls.tokenScopes` as the SQL generator needs it, or `undefined` when it is
2578
- * off.
2579
- */
2580
- function tokenScopesPlan(setting, policy) {
2581
- if (setting !== true) return;
2582
- const permissions = listPermissions(policy.permissions).map((leaf) => ({
2583
- key: leaf.key,
2584
- scope: leaf.scope,
2585
- renamedFrom: formerKeys(leaf)
2586
- }));
2587
- return { scopes: delegatedScopeMap(permissions, policy.oauthScopes) };
2588
- }
2589
- function tokenScopeAllowsCall(ctx, grant) {
2590
- return `${qualified(ctx, TOKEN_SCOPE_ALLOWS)}(${grant})`;
2591
- }
2592
- /**
2593
- * The token's scopes as rows of `s(scope)`: a space-separated string or,
2594
- * outside `guc`, a JSON array.
2595
- */
2596
- function tokenScopeRows(ctx) {
2597
- if (ctx.dialect === "guc") return `regexp_split_to_table(btrim(coalesce(${subjectClaimSql(ctx, "scope")}, '')), '\\s+') s(scope)`;
2598
- const scope = subjectClaimJsonSql(ctx, "scope");
2599
- return `unnest(case jsonb_typeof(${scope})
2600
- when 'string' then regexp_split_to_array(btrim(${scope} #>> '{}'), '\\s+')
2601
- when 'array' then array(select jsonb_array_elements_text(${scope}))
2602
- else '{}'::text[]
2603
- end) s(scope)`;
2604
- }
2605
- /**
2606
- * `permdock_token_scope_allows(p_grant)`: a delegated token (a `client_id`, or
2607
- * an `act` that is not a support or impersonation session) reaches a grant key
2608
- * only when one of its scopes maps to the key's permission. better-supabase's
2609
- * `cap_allows` reads the same tokens the same way.
2610
- */
2611
- function tokenScopeAllowsSql(ctx, plan, anonExecute) {
2612
- const fn = qualified(ctx, TOKEN_SCOPE_ALLOWS);
2613
- const map = qualified(ctx, TOKEN_SCOPE_MAP);
2614
- const act = subjectClaimJsonSql(ctx, "act");
2615
- const grants = anonExecute ? `revoke execute on function ${fn}(text) from public;
2616
- grant execute on function ${fn}(text) to anon, authenticated;` : `revoke execute on function ${fn}(text) from public, anon;
2617
- grant execute on function ${fn}(text) to authenticated;`;
2618
- return `create or replace function ${map}()
2619
- returns jsonb
2620
- language sql
2621
- immutable
2622
- set search_path = ''
2623
- as $$
2624
- select ${quoteLiteral(JSON.stringify(plan.scopes))}::jsonb
2625
- $$;
2626
- revoke execute on function ${map}() from public, anon, authenticated;
2627
-
2628
- -- Token scopes: a delegated token holds only the permissions its scope claim maps to; denies always apply, and a token without client_id or an agent act is not limited
2629
- create or replace function ${fn}(p_grant text)
2630
- returns boolean
2631
- language sql
2632
- stable
2633
- security definer
2634
- set search_path = ''
2635
- as $$
2636
- select case
2637
- when coalesce(${subjectClaimSql(ctx, "client_id")}, '') = ''
2638
- and (${act} is null
2639
- or ${act} = 'null'::jsonb
2640
- or (jsonb_typeof(${act}) = 'object'
2641
- and ${act} ->> 'kind' in ('support', 'impersonation'))) then true
2642
- when exists (
2643
- select 1 from ${qualified(ctx, "role_permissions")} rp
2644
- where rp.grant_key = p_grant and rp.effect = 'deny'
2645
- ) then true
2646
- else exists (
2647
- select 1
2648
- from ${tokenScopeRows(ctx)}
2649
- where s.scope <> ''
2650
- and coalesce(${map}() -> s.scope, '[]'::jsonb)
2651
- ? split_part(split_part(p_grant, '#', 1), '@', 1)
2652
- )
2653
- end
2654
- $$;
2655
- ${grants}`;
2656
- }
2657
- //#endregion
2658
- //#region src/cli/rls/helpers.ts
2659
- /**
2660
- * The policy-side call for a grant key. Every form is uncorrelated, so Postgres
2661
- * runs the helper once per statement (an InitPlan, or a hashed SubPlan for
2662
- * `in`), never once per row.
2663
- */
2664
- function accessSql(ctx, scope, grantKey, column, helper) {
2665
- const key = quoteLiteral(grantKey);
2666
- if (scope === "global") return `(select ${qualified(ctx, HELPERS.has)}(${key}))`;
2667
- if (column === void 0) throw configError(`PermDock CLI: ${scope}-scoped grant needs definePolicy({ scopes.${scope} })`);
2668
- return `${quoteIdent(column)} in (select ${qualified(ctx, helper ?? permittedIdsHelper(scope))}(${key}))`;
2669
- }
2670
- /**
2671
- * `permitted_<parent>_ids(p_grant)` for each \`rls.tables\` \`via\`: the parent
2672
- * rows whose scope instance the grant reaches. \`security definer\`, so the
2673
- * caller needs no read on the parent, and called uncorrelated like
2674
- * \`permitted_<scope>_ids\`.
2675
- */
2676
- function viaHelpersSql(ctx, anonExecute) {
2677
- const done = /* @__PURE__ */ new Set();
2678
- const chunks = [];
2679
- for (const via of Object.values(ctx.vias ?? {})) {
2680
- if (done.has(via.helper)) continue;
2681
- done.add(via.helper);
2682
- chunks.push(`-- rows of ${via.table} whose ${via.column} is a ${via.scope} the grant reaches
2683
- ${helperFunction(ctx, via.helper, `setof ${via.type}`, sqlBody(` select p.${quoteIdent(via.id)}
2684
- from ${quoteQualified(via.table)} p
2685
- where p.${quoteIdent(via.column)} in (select ${qualified(ctx, permittedIdsHelper(via.scope))}(p_grant))`), anonExecute)}`);
2686
- }
2687
- return chunks;
2688
- }
2689
- function userIdSql(ctx, anonExecute) {
2690
- const fn = userIdHelperSql(ctx);
2691
- return `-- the caller's user id: the sub of request.jwt.claims, or null when it is empty or absent
2692
- create or replace function ${fn}()
2693
- returns uuid
2694
- language sql
2695
- stable
2696
- set search_path = ''
2697
- as $$
2698
- select nullif(
2699
- nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub',
2700
- ''
2701
- )::uuid
2702
- $$;
2703
- ${anonExecute ? `revoke execute on function ${fn}() from public;
2704
- grant execute on function ${fn}() to anon, authenticated;` : `revoke execute on function ${fn}() from public, anon;
2705
- grant execute on function ${fn}() to authenticated;`}`;
2706
- }
2707
- function tokenCurrentSql(ctx, anonExecute) {
2708
- const fn = qualified(ctx, HELPERS.tokenCurrent);
2709
- const version = qualified(ctx, AUTHZ_VERSION_TABLE);
2710
- const grants = anonExecute ? `revoke execute on function ${fn}() from public;
2711
- grant execute on function ${fn}() to anon, authenticated;` : `revoke execute on function ${fn}() from public, anon;
2712
- grant execute on function ${fn}() to authenticated;`;
2713
- return `create or replace function ${fn}()
2714
- returns boolean
2715
- language plpgsql
2716
- stable
2717
- security definer
2718
- set search_path = ''
2719
- as $$
2720
- begin
2721
- return coalesce((
2722
- select to_jsonb(v.version) = ((select auth.jwt()) -> 'authz_ver')
2723
- and coalesce((select auth.jwt()) -> 'memberships_truncated', 'false'::jsonb) <> 'true'::jsonb
2724
- and jsonb_typeof((select auth.jwt()) -> 'memberships') = 'array'
2725
- from ${version} v
2726
- where v.user_id = ${subjectIdSql(ctx)}
2727
- ), false);
2728
- end;
2729
- $$;
2730
- ${grants}`;
2731
- }
2732
- function helperFunction(ctx, name, returns, body, anonExecute) {
2733
- const fn = qualified(ctx, name);
2734
- const grants = anonExecute ? `revoke execute on function ${fn}(text) from public;
2735
- grant execute on function ${fn}(text) to anon, authenticated;` : `revoke execute on function ${fn}(text) from public, anon;
2736
- grant execute on function ${fn}(text) to authenticated;`;
2737
- return `create or replace function ${fn}(p_grant text)
2738
- returns ${returns}
2739
- ${functionBody(body, !memoizes(ctx))}
2740
- ${grants}`;
2741
- }
2742
- /**
2743
- * `permdock_has_for(p_user, p_grant)` and one
2744
- * `permitted_<scope>_ids_for(p_user, p_grant)` per scope in `database` mode:
2745
- * the bodies of `permdock_has` and `permitted_<scope>_ids` with `p_user` for
2746
- * the signed-in user and no tenant-claim narrowing, since a named user has no
2747
- * token. For trusted SQL that acts for a stored user (jobs, triggers, approvals
2748
- * resolved later). Naming the user is why no client role may execute them:
2749
- * `security definer` callers run them as their owner, and a backend role needs
2750
- * its own grant.
2751
- */
2752
- function forUserSql(ctx) {
2753
- if (ctx.authorize !== "database") return "";
2754
- const forUser = forUserContext(ctx);
2755
- const type = ctx.dialect === "supabase" ? "uuid" : "text";
2756
- const fn = (name, returns, body) => {
2757
- const qualifiedName = qualified(ctx, name);
2758
- return `create or replace function ${qualifiedName}(p_user ${type}, p_grant text)
2759
- returns ${returns}
2760
- ${functionBody(body, !memoizes(ctx))}
2761
- revoke execute on function ${qualifiedName}(${type}, text) from public, anon, authenticated;`;
2762
- };
2763
- return [`-- the helpers for a user the caller names: trusted SQL acting for a stored user; no client role may execute them
2764
- ${fn(HELPERS.hasFor, "boolean", sqlBody(hasBody(forUser)))}`, ...ctx.scopes.map((scope) => {
2765
- const scopeType = scopeTypeOf(ctx, scope.name);
2766
- return fn(permittedForHelper(scope.name), `setof ${scopeType}`, scopedBody(forUser, scope.name, scopeType));
2767
- })].join("\n\n");
2768
- }
2769
- function userIdType(ctx) {
2770
- return ctx.dialect === "supabase" ? "uuid not null references auth.users on delete cascade" : "text not null";
2771
- }
2772
- /**
2773
- * The `role_permissions` rows the policy compiles to: an upsert and a delete of
2774
- * every other row. Data, not schema, so `supabase db diff` drops it from a
2775
- * declarative schema; `--split ...,seeds` writes it as its own migration.
2776
- */
2777
- function seedSql(ctx, rows) {
2778
- const table = qualified(ctx, "role_permissions");
2779
- if (rows.length === 0) return `delete from ${table};`;
2780
- return `insert into ${table} (role, permission, grant_key, scope, effect) values
2781
- ${rows.map((row) => ` (${[
2782
- row.role,
2783
- row.permission,
2784
- row.grantKey,
2785
- row.scope,
2786
- row.effect
2787
- ].map(quoteLiteral).join(", ")})`).join(",\n")}
2788
- on conflict (role, grant_key, scope) do update
2789
- set permission = excluded.permission, effect = excluded.effect;
2790
- delete from ${table}
2791
- where (role, grant_key, scope) not in (values
2792
- ${rows.map((row) => ` (${[
2793
- row.role,
2794
- row.grantKey,
2795
- row.scope
2796
- ].map(quoteLiteral).join(", ")})`).join(",\n")}
2797
- );`;
2798
- }
2799
- /**
2800
- * `role_permissions` as a view over the compiled rows (`rls.seeds: 'view'`).
2801
- * `security_invoker` makes the view read as its caller, so it adds no
2802
- * privilege; the table's revoke applies to the view the same way.
2803
- */
2804
- function seedViewSql(ctx, rows) {
2805
- const view = qualified(ctx, "role_permissions");
2806
- const columns = "role, permission, grant_key, scope, effect";
2807
- return `-- rls.seeds: 'view': role_permissions is a view, so the rows travel with the schema
2808
- create or replace view ${view} (${columns}) with (security_invoker = true) as
2809
- ${rows.length === 0 ? `select null::text, null::text, null::text, null::text, null::text where false` : `select * from (values\n${rows.map((row) => ` (${[
2810
- row.role,
2811
- row.permission,
2812
- row.grantKey,
2813
- row.scope,
2814
- row.effect
2815
- ].map(quoteLiteral).join(", ")})`).join(",\n")}\n) as v(${columns})`};
2816
- revoke all on table ${view} from anon, authenticated, public;`;
2817
- }
2818
- /**
2819
- * `<schema>.seed()`: the same upsert and delete as `seedSql`, for a declarative
2820
- * schema that carries no rows.
2821
- */
2822
- function seedFunctionSql(ctx, rows) {
2823
- const fn = qualified(ctx, "seed");
2824
- return `-- rls.seeds: 'function': the role_permissions rows are data, so a declarative diff leaves them out; run select ${fn}(); after each deploy
2825
- create or replace function ${fn}()
2826
- returns void
2827
- language sql
2828
- volatile
2829
- security definer
2830
- set search_path = ''
2831
- as $permdock$
2832
- ${seedSql(ctx, rows)}
2833
- $permdock$;
2834
- revoke execute on function ${fn}() from public, anon, authenticated;`;
2835
- }
2836
- /**
2837
- * `role_permissions`, its seeds, and the three `security definer` helpers with
2838
- * `search_path = ''`. `execute` goes to `authenticated` only.
2839
- */
2840
- function helpersSql(ctx, rows, options) {
2841
- const schema = helperSchema(ctx);
2842
- const s = quoteIdent(schema);
2843
- const rp = qualified(ctx, "role_permissions");
2844
- const chunks = [`-- permdock helpers (${ctx.authorize === "database" ? "database: reads the membership and user_roles tables" : "jwt: reads the role and memberships claims"})
2845
- -- policies call them uncorrelated, so Postgres evaluates each once per statement`];
2846
- if (schema !== "public") {
2847
- const anonUsage = options.anonExecute === true || ctx.capabilities === true;
2848
- chunks.push(`create schema if not exists ${s};\nrevoke all on schema ${s} from public;\ngrant usage on schema ${s} to ${anonUsage ? "anon, authenticated" : "authenticated"};`);
2849
- }
2850
- if (ctx.dialect === "supabase") chunks.push(userIdSql(ctx, options.anonExecute === true));
2851
- if (ctx.claimsFirst === true) chunks.push(tokenCurrentSql(ctx, options.anonExecute === true));
2852
- if (ctx.seeds === "view") chunks.push(seedViewSql(ctx, rows));
2853
- else chunks.push(`create table if not exists ${rp} (
2854
- role text not null,
2855
- permission text not null,
2856
- grant_key text not null,
2857
- scope text not null check (scope ~ '^[a-z][a-z0-9_]*$'),
2858
- effect text not null default 'allow' check (effect in ('allow', 'deny')),
2859
- primary key (role, grant_key, scope)
2860
- );
2861
- alter table ${rp} enable row level security;
2862
- revoke all on table ${rp} from anon, authenticated, public;`);
2863
- if (ctx.seeds === "function") chunks.push(seedFunctionSql(ctx, rows));
2864
- else if (options.withoutSeeds !== true && ctx.seeds !== "view") chunks.push(seedSql(ctx, rows));
2865
- if (ctx.authorize === "database" && options.userRoles && ctx.roles === void 0) {
2866
- const ur = qualified(ctx, "user_roles");
2867
- chunks.push(`create table if not exists ${ur} (
2868
- user_id ${userIdType(ctx)},
2869
- role text not null,
2870
- primary key (user_id, role)
2871
- );
2872
- alter table ${ur} enable row level security;
2873
- revoke all on table ${ur} from anon, authenticated, public;`);
2874
- }
2875
- const custom = customRolesSql(ctx);
2876
- if (custom !== "") chunks.push(custom);
2877
- const memoGeneration = memoGenerationSql(ctx, memoReadsSql(ctx));
2878
- if (memoGeneration !== "") chunks.push(memoGeneration);
2879
- const anon = options.anonExecute === true;
2880
- const keys = ctx.apiKeys;
2881
- if (keys !== void 0) chunks.push(apiKeyAllowsSql(ctx, keys, anon));
2882
- if (ctx.tokenScopes !== void 0) chunks.push(tokenScopeAllowsSql(ctx, ctx.tokenScopes, anon));
2883
- const bodies = grantBodies(ctx);
2884
- chunks.push(helperFunction(ctx, HELPERS.has, "boolean", bodies.has, anon));
2885
- const capabilities = capabilitiesSql(ctx);
2886
- if (capabilities !== "") chunks.push(capabilities);
2887
- for (const scope of ctx.scopes) {
2888
- const type = scopeTypeOf(ctx, scope.name);
2889
- chunks.push(helperFunction(ctx, permittedIdsHelper(scope.name), `setof ${type}`, bodies.ids(scope.name), anon));
2890
- chunks.push(memberFunction(ctx, scope.name, type, anon));
2891
- if (ctx.roleMemberScopes?.includes(scope.name) === true) chunks.push(memberRolesFunction(ctx, scope.name, type, anon));
2892
- if (hasMemberFor(ctx, scope.name)) chunks.push(memberForFunction(ctx, scope.name, type));
2893
- if (hasMemberOf(ctx, scope.name)) chunks.push(memberOfFunction(ctx, scope.name, type));
2894
- }
2895
- chunks.push(...viaHelpersSql(ctx, anon));
2896
- const forUser = forUserSql(ctx);
2897
- if (forUser !== "") chunks.push(forUser);
2898
- const writes = customRoleWritesSql(ctx, options.levelReach ?? []);
2899
- if (writes !== "") {
2900
- chunks.push(writes);
2901
- const cascade = customRoleCascadeSql(ctx);
2902
- if (cascade !== "") chunks.push(cascade);
2903
- const sync = ctx.customRoles?.sync;
2904
- if (sync !== void 0) chunks.push(sync);
2905
- const byId = customRoleByIdSql(ctx, options.trustedReaders);
2906
- if (byId !== "") chunks.push(byId);
2907
- const nameGuard = customRoleNameGuardSql(ctx);
2908
- if (nameGuard !== "") chunks.push(nameGuard);
2909
- }
2910
- const globalRoles = globalRolesSql(ctx);
2911
- if (globalRoles !== "") chunks.push(globalRoles);
2912
- chunks.push(roleReadersSql(ctx, options.permissions, options.trustedReaders));
2913
- return `${chunks.join("\n\n")}\n`;
2914
- }
2915
- function memoBody(ctx, scope, type, body) {
2916
- if (!memoizes(ctx)) return body;
2917
- return {
2918
- ...body,
2919
- memo: {
2920
- type,
2921
- scope,
2922
- user: subjectIdSql(ctx),
2923
- ...ctx.memo === void 0 ? {} : { api: ctx.memo }
2924
- }
2925
- };
2926
- }
2927
- function memoReadsSql(ctx) {
2928
- const bodies = grantBodies(ctx);
2929
- return [bodies.has.sql, ...ctx.scopes.map((scope) => bodies.ids(scope.name).sql)].join("\n");
2930
- }
2931
- function grantBodies(ctx) {
2932
- const keys = ctx.apiKeys;
2933
- const scoped = ctx.tokenScopes !== void 0;
2934
- const set = ctx.grantSet === true;
2935
- const ceiling = (grant) => {
2936
- const calls = [...keys === void 0 ? [] : [apiKeyAllowsCall(ctx, grant)], ...scoped ? [tokenScopeAllowsCall(ctx, grant)] : []];
2937
- return calls.length === 0 ? void 0 : calls.join(" and ");
2938
- };
2939
- const allows = ceiling(set ? "ids.grant_key" : "p_grant");
2940
- const keyTenant = keys === void 0 ? "" : ` and ${keyTenantSql(ctx, void 0) ?? "true"}`;
2941
- const hasAllows = ceiling(set ? "g.grant_key" : "p_grant");
2942
- return {
2943
- has: memoBody(ctx, "global", "boolean", sqlBody(hasAllows === void 0 ? hasBody(ctx) : set ? ` select g.grant_key
2944
- from (
2945
- ${hasBody(ctx)}
2946
- ) g(grant_key)
2947
- where ${hasAllows}${keyTenant}` : ceilingHasSql(hasBody(ctx), `${hasAllows}${keyTenant}`))),
2948
- ids: (scope) => {
2949
- const type = scopeTypeOf(ctx, scope);
2950
- const body = scopedBody(ctx, scope, type);
2951
- const sql = allows === void 0 ? body.sql : keys !== void 0 && scope === rootName(ctx) ? `${body.sql}\n union\n${serviceKeyIdsSql(ctx, keys, scope, type)}` : body.sql;
2952
- return memoBody(ctx, scope, type, allows === void 0 ? {
2953
- sql,
2954
- vars: body.vars
2955
- } : {
2956
- sql: set ? ` select ids.id, ids.grant_key
2957
- from (
2958
- ${sql}
2959
- ) ids(id, grant_key)
2960
- where ${allows}` : ceilingIdsSql(sql, allows),
2961
- vars: body.vars
2962
- });
2963
- }
2964
- };
2965
- }
2966
- function forUserContext(ctx) {
2967
- const { apiKeys: _apiKeys, tokenScopes: _tokenScopes, claimsFirst: _claimsFirst, ...unkeyed } = ctx;
2968
- return {
2969
- ...unkeyed,
2970
- subjectId: "p_user",
2971
- tenants: "all"
2972
- };
2973
- }
2974
- //#endregion
2975
- //#region src/cli/rls/permission-keys.ts
2976
- /**
2977
- * The helpers that take a permission key instead of a grant key. Names are part
2978
- * of the SQL contract.
2979
- */
2980
- const PERMISSION_HELPERS = {
2981
- grantKeys: "grant_keys",
2982
- has: "permdock_has_permission",
2983
- hasFor: "permdock_has_permission_for"
2984
- };
2985
- /**
2986
- * `permitted_<scope>_permission_keys(p_id)`: every permission key the subject
2987
- * holds on one instance.
2988
- */
2989
- function permissionKeysHelper(scope) {
2990
- permittedIdsHelper(scope);
2991
- return `permitted_${scope}_permission_keys`;
2992
- }
2993
- /**
2994
- * `permitted_<scope>_permission_keys_for(p_user, p_id)`, written in `database`
2995
- * mode.
2996
- */
2997
- function permissionKeysForHelper(scope) {
2998
- return `${permissionKeysHelper(scope)}_for`;
2999
- }
3000
- /** `permitted_<scope>_ids_by_permission(p_permission)`. */
3001
- function permittedByPermissionHelper(scope) {
3002
- return `${permittedIdsHelper(scope)}_by_permission`;
3003
- }
3004
- /**
3005
- * A grant's `requires` as SQL: the subject holds `key` globally, or on the
3006
- * row's instance of a scope that partitions it, through the helpers by
3007
- * permission key, as `requirementCondition` does in process.
3008
- */
3009
- function requiresSql(ctx, key, resource) {
3010
- const literal = quoteLiteral(key);
3011
- return `(${[`(select ${qualified(ctx, PERMISSION_HELPERS.has)}(${literal}))`, ...(resource === void 0 ? [] : partitionsOf(resource, ctx.scopes)).map((scope) => {
3012
- const field = scopeField(resource, scope, ctx.scopes) ?? scope;
3013
- return `${quoteIdent(field)} in (select ${qualified(ctx, checkName(permittedByPermissionHelper(scope)))}(${literal}))`;
3014
- })].join(" or ")})`;
3015
- }
3016
- /**
3017
- * Postgres truncates an identifier past 63 bytes, which would merge two
3018
- * helpers.
3019
- */
3020
- function checkName(name) {
3021
- if (new TextEncoder().encode(name).length > 63) throw configError(`PermDock CLI: the helper name ${name} is longer than 63 bytes; use a shorter scope name`);
3022
- return name;
3023
- }
3024
- function grantsFunction(ctx, grants, renamed, anonExecute) {
3025
- const fn = qualified(ctx, PERMISSION_HELPERS.grantKeys);
3026
- const map = Object.fromEntries([...grants].toSorted(byKey));
3027
- const current = Object.keys(renamed).length === 0 ? "p_permission" : `coalesce(${quoteLiteral(JSON.stringify(renamed))}::jsonb ->> p_permission, p_permission)`;
3028
- return `-- the grant keys a permission key reaches on one scope: its unconditional allows, with p_effect 'deny' every deny, and with 'conditioned-allow' or 'conditioned-deny' the allows or denies that carry a row condition
3029
- create or replace function ${fn}(p_permission text, p_scope text, p_effect text default 'allow')
3030
- returns setof text
3031
- language sql
3032
- stable
3033
- set search_path = ''
3034
- as $$
3035
- select g.grant_key
3036
- from pg_catalog.jsonb_array_elements_text(coalesce(
3037
- ${quoteLiteral(JSON.stringify(map))}::jsonb -> p_scope -> ${current} -> p_effect,
3038
- '[]'::jsonb
3039
- )) g(grant_key)
3040
- $$;
3041
- ${grantsSql(fn, "text, text, text", anonExecute)}`;
3042
- }
3043
- function grantsSql(fn, args, anonExecute) {
3044
- return anonExecute ? `revoke execute on function ${fn}(${args}) from public;
3045
- grant execute on function ${fn}(${args}) to anon, authenticated;` : `revoke execute on function ${fn}(${args}) from public, anon;
3046
- grant execute on function ${fn}(${args}) to authenticated;`;
3047
- }
3048
- function definerSql(fn, params, returns, sql, parallelSafe) {
3049
- return `create or replace function ${fn}(${params})
3050
- returns ${returns}
3051
- language sql
3052
- stable
3053
- security definer
3054
- cost 1000${parallelSafe ? "\nparallel safe" : ""}
3055
- set search_path = ''
3056
- as $$
3057
- ${sql}
3058
- $$;`;
3059
- }
3060
- function heldSql(at, effect) {
3061
- return `select 1 from pdk_h where pdk_h.key = pdk_k.key and pdk_h.scope = ${quoteLiteral(at)} and pdk_h.effect = '${effect}'`;
3062
- }
3063
- function keysFunction(fn, params, body, access, parallelSafe) {
3064
- return `create or replace function ${fn}(${params})
3065
- returns setof text
3066
- ${functionBody(body, parallelSafe).replace("set search_path = ''", "set search_path = ''\nset jit = off")}
3067
- ${access}`;
3068
- }
3069
- /**
3070
- * The permission-key forms of the helpers: `grant_keys`, which maps a
3071
- * permission key to the grant keys of its unconditional allows on a scope (or
3072
- * every deny key, or the conditioned allow or deny keys),
3073
- * `permdock_has_permission(p_permission)` and one
3074
- * `permitted_<scope>_ids_by_permission(p_permission)` per scope, plus their
3075
- * `_for(p_user, ...)` forms in `database` mode. They answer with the
3076
- * unconditional allows minus any deny, so a permission whose allows all carry a
3077
- * row condition answers nothing. The
3078
- * `permitted_<scope>_ids_by_permission(p_permission, p_conditioned)` overload
3079
- * with `true` also lists the instances a conditioned allow reaches and
3080
- * subtracts only unconditional denies, leaving the row condition to the caller,
3081
- * as `permittedIds(..., { conditioned: true })` does in process.
3082
- */
3083
- function permissionHelpersSql(ctx, grants, renamed, anonExecute) {
3084
- const parallel = !memoizes(ctx);
3085
- const definer = (fn, params, returns, sql) => definerSql(fn, params, returns, sql, parallel);
3086
- const keys = qualified(ctx, PERMISSION_HELPERS.grantKeys);
3087
- const allowKeys = (scope) => `${keys}(p_permission, ${quoteLiteral(scope)}) g(grant_key)`;
3088
- const denyKeys = (scope) => `${keys}(p_permission, ${quoteLiteral(scope)}, 'deny') g(grant_key)`;
3089
- const has = (helper, user) => ` select exists (select 1 from ${allowKeys("global")} where ${helper}(${user}g.grant_key))
3090
- and not exists (select 1 from ${denyKeys("global")} where ${helper}(${user}g.grant_key))`;
3091
- const ids = (helper, scope, user) => ` select a.id
3092
- from ${allowKeys(scope)}
3093
- cross join lateral ${helper}(${user}g.grant_key) a(id)
3094
- except
3095
- select d.id
3096
- from ${denyKeys(scope)}
3097
- cross join lateral ${helper}(${user}g.grant_key) d(id)`;
3098
- const conditionedIds = (helper, scope, user) => ` select a.id
3099
- from (
3100
- select g.grant_key from ${allowKeys(scope)}
3101
- union all
3102
- select g.grant_key from ${keys}(p_permission, ${quoteLiteral(scope)}, 'conditioned-allow') g(grant_key)
3103
- where p_conditioned
3104
- ) g
3105
- cross join lateral ${helper}(${user}g.grant_key) a(id)
3106
- except
3107
- select d.id
3108
- from (
3109
- select g.grant_key from ${denyKeys(scope)}
3110
- except
3111
- select g.grant_key from ${keys}(p_permission, ${quoteLiteral(scope)}, 'conditioned-deny') g(grant_key)
3112
- where p_conditioned
3113
- ) g
3114
- cross join lateral ${helper}(${user}g.grant_key) d(id)`;
3115
- const keysBody = (scope, bodies, filtered) => {
3116
- const rows = ["global", scope].flatMap((at) => Object.entries(grants.get(at) ?? {}).toSorted(byKey).flatMap(([key, effects]) => ["allow", "deny"].flatMap((effect) => effects[effect].map((grant) => `(${[
3117
- key,
3118
- at,
3119
- effect,
3120
- grant
3121
- ].map(quoteLiteral).join(", ")})`))));
3122
- if (new Set(["global", scope].flatMap((at) => Object.entries(grants.get(at) ?? {}).flatMap(([key, effects]) => effects.allow.length > 0 ? [key] : []))).size === 0) return {
3123
- sql: " select null::text where false",
3124
- vars: []
3125
- };
3126
- const hasBody = bodies.has;
3127
- const idsBody = bodies.ids(scope);
3128
- return {
3129
- sql: ` with pdk_m(key, scope, effect, grant_key) as (
3130
- values
3131
- ${rows.join(",\n ")}
3132
- ),
3133
- pdk_w as (
3134
- select pdk_m.key, pdk_m.scope, pdk_m.effect, pdk_m.grant_key
3135
- from pdk_m${filtered ? `\n where pdk_m.key in (select ${Object.keys(renamed).length === 0 ? "k.key" : `coalesce(${quoteLiteral(JSON.stringify(renamed))}::jsonb ->> k.key, k.key)`} from pg_catalog.unnest(p_keys) k(key))` : ""}
3136
- ),
3137
- pdk_g as (
3138
- ${hasBody.sql}
3139
- ),
3140
- pdk_s as (
3141
- select pdk_i.grant_key
3142
- from (
3143
- ${idsBody.sql}
3144
- ) pdk_i(id, grant_key)
3145
- where pdk_i.id = p_id
3146
- ),
3147
- pdk_h as (
3148
- select pdk_w.key, pdk_w.scope, pdk_w.effect
3149
- from pdk_w
3150
- where (pdk_w.scope = 'global' and pdk_w.grant_key in (select pdk_g.grant_key from pdk_g))
3151
- or (pdk_w.scope = ${quoteLiteral(scope)} and pdk_w.grant_key in (select pdk_s.grant_key from pdk_s))
3152
- )
3153
- select pdk_k.key
3154
- from (select distinct pdk_w.key from pdk_w where pdk_w.effect = 'allow') pdk_k
3155
- where (exists (${heldSql("global", "allow")}) and not exists (${heldSql("global", "deny")}))
3156
- or (exists (${heldSql(scope, "allow")}) and not exists (${heldSql(scope, "deny")}))
3157
- order by 1`,
3158
- vars: [.../* @__PURE__ */ new Set([...hasBody.vars, ...idsBody.vars])]
3159
- };
3160
- };
3161
- const chunks = [grantsFunction(ctx, grants, renamed, anonExecute), `-- the helpers by permission key: unconditional allows minus any deny
3162
- ${definer(qualified(ctx, PERMISSION_HELPERS.has), "p_permission text", "boolean", has(qualified(ctx, HELPERS.has), ""))}
3163
- ${grantsSql(qualified(ctx, PERMISSION_HELPERS.has), "text", anonExecute)}`];
3164
- for (const scope of ctx.scopes) {
3165
- const fn = qualified(ctx, checkName(permittedByPermissionHelper(scope.name)));
3166
- chunks.push(`${definer(fn, "p_permission text", `setof ${scopeTypeOf(ctx, scope.name)}`, ids(qualified(ctx, permittedIdsHelper(scope.name)), scope.name, ""))}
3167
- ${grantsSql(fn, "text", anonExecute)}`);
3168
- const keysFn = qualified(ctx, checkName(permissionKeysHelper(scope.name)));
3169
- const type = scopeTypeOf(ctx, scope.name);
3170
- const caller = grantBodies({
3171
- ...ctx,
3172
- grantSet: true
3173
- });
3174
- chunks.push(`-- the permission keys the caller holds on one ${scope.name}: what permdock_has_permission or permitted_${scope.name}_ids_by_permission answers for each key, in one call
3175
- ${keysFunction(keysFn, `p_id ${type}`, keysBody(scope.name, caller, false), grantsSql(keysFn, type, anonExecute), parallel)}
3176
- ${keysFunction(keysFn, `p_id ${type}, p_keys text[]`, keysBody(scope.name, caller, true), grantsSql(keysFn, `${type}, text[]`, anonExecute), parallel)}`);
3177
- chunks.push(`-- with p_conditioned true, also the instances a conditioned allow reaches, minus only unconditional denies: the caller applies the row condition
3178
- ${definer(fn, "p_permission text, p_conditioned boolean", `setof ${scopeTypeOf(ctx, scope.name)}`, conditionedIds(qualified(ctx, permittedIdsHelper(scope.name)), scope.name, ""))}
3179
- ${grantsSql(fn, "text, boolean", anonExecute)}`);
3180
- }
3181
- if (ctx.authorize !== "database") return `${chunks.join("\n\n")}\n`;
3182
- const user = ctx.dialect === "supabase" ? "uuid" : "text";
3183
- const revoke = (fn) => `revoke execute on function ${fn}(${user}, text) from public, anon, authenticated;`;
3184
- const hasFor = qualified(ctx, PERMISSION_HELPERS.hasFor);
3185
- chunks.push(`-- the same for a user the caller names; no client role may execute them
3186
- ${definer(hasFor, `p_user ${user}, p_permission text`, "boolean", has(qualified(ctx, HELPERS.hasFor), "p_user, "))}
3187
- ${revoke(hasFor)}`);
3188
- for (const scope of ctx.scopes) {
3189
- const fn = qualified(ctx, checkName(`${permittedByPermissionHelper(scope.name)}_for`));
3190
- chunks.push(`${definer(fn, `p_user ${user}, p_permission text`, `setof ${scopeTypeOf(ctx, scope.name)}`, ids(qualified(ctx, permittedForHelper(scope.name)), scope.name, "p_user, "))}
3191
- ${revoke(fn)}`);
3192
- chunks.push(`${definer(fn, `p_user ${user}, p_permission text, p_conditioned boolean`, `setof ${scopeTypeOf(ctx, scope.name)}`, conditionedIds(qualified(ctx, permittedForHelper(scope.name)), scope.name, "p_user, "))}
3193
- revoke execute on function ${fn}(${user}, text, boolean) from public, anon, authenticated;`);
3194
- const keysFor = qualified(ctx, checkName(permissionKeysForHelper(scope.name)));
3195
- const type = scopeTypeOf(ctx, scope.name);
3196
- const named = grantBodies({
3197
- ...forUserContext(ctx),
3198
- grantSet: true
3199
- });
3200
- chunks.push(`${keysFunction(keysFor, `p_user ${user}, p_id ${type}`, keysBody(scope.name, named, false), `revoke execute on function ${keysFor}(${user}, ${type}) from public, anon, authenticated;`, parallel)}
3201
- ${keysFunction(keysFor, `p_user ${user}, p_id ${type}, p_keys text[]`, keysBody(scope.name, named, true), `revoke execute on function ${keysFor}(${user}, ${type}, text[]) from public, anon, authenticated;`, parallel)}`);
3202
- }
3203
- return `${chunks.join("\n\n")}\n`;
3204
- }
3205
- //#endregion
3206
- //#region src/cli/rls/ownership-names.ts
3207
- /**
3208
- * Objects the ownership rules add next to the helpers. Names are part of the
3209
- * SQL contract.
3210
- */
3211
- const OWNERSHIP = {
3212
- canAssign: "permdock_can_assign",
3213
- canAssignFor: "permdock_can_assign_for",
3214
- canAssignAny: "permdock_can_assign_any",
3215
- canAssignAnyFor: "permdock_can_assign_any_for",
3216
- holders: "permdock_holders",
3217
- transferOnly: "permdock_transfer_only"
3218
- };
3219
- /** Objects `rls.assignments` adds. Names are part of the SQL contract. */
3220
- const ASSIGNMENTS = {
3221
- custom: "permdock_can_assign_custom_role",
3222
- customFor: "permdock_can_assign_custom_role_for",
3223
- trigger: "permdock_assignment"
3224
- };
3225
- //#endregion
3226
- //#region src/cli/rls/ownership-triggers.ts
3227
- function objectName(prefix, scope) {
3228
- return quoteIdent(`${prefix}_${scope}`);
3229
- }
3230
- /**
3231
- * Live holders of `roleExpr` in instance `idExpr`, with the same kind and
3232
- * expiry rules as the helpers.
3233
- */
3234
- function holdersSql(ctx, table, column, idExpr, role, into) {
3235
- const roleExpr = typeof role === "string" ? quoteLiteral(role) : role.expr;
3236
- const held = memberRoleOf(table, "m", " ");
3237
- const filters = [`m.${quoteIdent(column)} = ${idExpr}`, `${held.sql} = ${roleExpr}`];
3238
- if (table.expiresAt !== void 0) {
3239
- const expires = memberColumn(table.expiresAt);
3240
- filters.push(`(${expires} is null or ${expires} > now())`);
3241
- }
3242
- const disabled = disabledColumn(table);
3243
- if (disabled !== void 0) filters.push(`${disabled} is null`);
3244
- const via = memberVia(table);
3245
- const kind = typeof role === "string" ? roleKindSql(ctx, role, via) : kindFilterSql(ctx, roleExpr, via);
3246
- if (kind !== void 0) filters.push(kind);
3247
- return `select count(distinct m.${quoteIdent(table.user)}) into ${into}
3248
- from ${quoteQualified(table.table)} m${held.join}
3249
- where ${filters.join("\n and ")}`;
3250
- }
3251
- /**
3252
- * `min` and `max` as a deferred constraint trigger: checked at commit, so a
3253
- * transfer (demote one holder, promote another) passes in one transaction. An
3254
- * instance with no memberships left is being torn down and skips `min`.
3255
- */
3256
- function holdersTriggerSql(ctx, scope, table, column, counted) {
3257
- const fn = qualified(ctx, `${OWNERSHIP.holders}_${scope}`);
3258
- const col = quoteIdent(column);
3259
- const checks = counted.map((rule) => {
3260
- const lines = [` select count(*) into v_total from ${quoteQualified(table.table)} m where m.${col} = v_key;`, ` ${holdersSql(ctx, table, column, "v_key", rule.role, "v_count")};`];
3261
- if (rule.min > 0) lines.push(` if v_total > 0 and v_count < ${String(rule.min)} then
3262
- raise exception using
3263
- errcode = '23514',
3264
- message = ${quoteLiteral(`permdock: ${scope} `)} || v_id || ${quoteLiteral(` keeps at least ${String(rule.min)} ${rule.role}`)},
3265
- hint = 'last-holder';
3266
- end if;`);
3267
- if (rule.max !== void 0) lines.push(` if v_count > ${String(rule.max)} then
3268
- raise exception using
3269
- errcode = '23514',
3270
- message = ${quoteLiteral(`permdock: ${scope} `)} || v_id || ${quoteLiteral(` has at most ${String(rule.max)} ${rule.role}`)},
3271
- hint = 'max-holders';
3272
- end if;`);
3273
- return lines.join("\n");
3274
- });
3275
- return `-- ${scope}: holder counts (min / max), checked at commit
3276
- create or replace function ${fn}()
3277
- returns trigger
3278
- language plpgsql
3279
- security definer
3280
- set search_path = ''
3281
- as $$
3282
- declare
3283
- v_ids text[] := '{}';
3284
- v_id text;
3285
- v_key ${quoteQualified(table.table)}.${col}%type;
3286
- v_total bigint;
3287
- v_count bigint;
3288
- begin
3289
- if tg_op in ('UPDATE', 'DELETE') then
3290
- v_ids := v_ids || old.${col}::text;
3291
- end if;
3292
- if tg_op in ('INSERT', 'UPDATE') then
3293
- v_ids := v_ids || new.${col}::text;
3294
- end if;
3295
- foreach v_id in array v_ids loop
3296
- continue when v_id is null;
3297
- v_key := v_id;
3298
- ${checks.join("\n")}
3299
- end loop;
3300
- return null;
3301
- end;
3302
- $$;
3303
- drop trigger if exists ${objectName(OWNERSHIP.holders, scope)} on ${quoteQualified(table.table)};
3304
- create constraint trigger ${objectName(OWNERSHIP.holders, scope)}
3305
- after insert or update or delete on ${quoteQualified(table.table)}
3306
- deferrable initially deferred
3307
- for each row execute function ${fn}();`;
3308
- }
3309
- /**
3310
- * `transferOnly` as statement triggers over transition tables: a statement that
3311
- * changes a role's holder count in an instance that had holders before and
3312
- * still has some after is refused. Creating the first holder and removing the
3313
- * last (which `min` guards) are not transfers.
3314
- */
3315
- function transferTriggerSql(ctx, scope, table, column, roles) {
3316
- const fn = qualified(ctx, `${OWNERSHIP.transferOnly}_${scope}`);
3317
- const col = quoteIdent(column);
3318
- const list = `array[${roles.map(quoteLiteral).join(", ")}]::text[]`;
3319
- const rows = (alias, source, delta) => {
3320
- const role = memberRoleOf(table, alias);
3321
- return `select ${alias}.${col} as id, ${role.sql} as role, ${delta} as delta from ${source} ${alias}${role.join} where ${role.sql} = any(${list})`;
3322
- };
3323
- const loop = (source) => ` for v_change in
3324
- select c.id, c.role, sum(c.delta) as delta
3325
- from (${source}) c
3326
- group by c.id, c.role
3327
- loop
3328
- continue when v_change.delta = 0 or v_change.id is null;
3329
- ${holdersSql(ctx, table, column, "v_change.id", { expr: "v_change.role" }, "v_after")};
3330
- if v_after > 0 and v_after - v_change.delta > 0 then
3331
- raise exception using
3332
- errcode = '23514',
3333
- message = 'permdock: ' || v_change.role || ${quoteLiteral(` in ${scope} `)} || v_change.id || ' moves only by transfer',
3334
- hint = 'transfer-only';
3335
- end if;
3336
- end loop;`;
3337
- const inserted = rows("n", "permdock_new", "1");
3338
- const deleted = rows("o", "permdock_old", "-1");
3339
- const target = quoteQualified(table.table);
3340
- const trigger = (op) => {
3341
- const name = quoteIdent(`${OWNERSHIP.transferOnly}_${scope}_${op}`);
3342
- return `drop trigger if exists ${name} on ${target};
3343
- create trigger ${name}
3344
- after ${op} on ${target}
3345
- referencing ${op === "insert" ? "new table as permdock_new" : op === "delete" ? "old table as permdock_old" : "old table as permdock_old new table as permdock_new"}
3346
- for each statement execute function ${fn}();`;
3347
- };
3348
- return `-- ${scope}: transfer-only roles (${roles.join(", ")}) keep their holder count per statement
3349
- create or replace function ${fn}()
3350
- returns trigger
3351
- language plpgsql
3352
- security definer
3353
- set search_path = ''
3354
- as $$
3355
- declare
3356
- v_change record;
3357
- v_after bigint;
3358
- begin
3359
- if tg_op = 'INSERT' then
3360
- ${loop(inserted)}
3361
- elsif tg_op = 'DELETE' then
3362
- ${loop(deleted)}
3363
- else
3364
- ${loop(`${inserted} union all ${deleted}`)}
3365
- end if;
3366
- return null;
3367
- end;
3368
- $$;
3369
- ${trigger("insert")}
3370
- ${trigger("update")}
3371
- ${trigger("delete")}`;
3372
- }
3373
- //#endregion
3374
- //#region src/cli/rls/ownership-sources.ts
3375
- /**
3376
- * The membership sources holding scope `name`: `undefined` when there are none,
3377
- * `'not-tables'` when one of them carries no table to put a trigger on.
3378
- */
3379
- function holderSources(ctx, name) {
3380
- const sources = memberForSources(ctx, name);
3381
- if (sources.length === 0) return;
3382
- const held = [];
3383
- for (const source of sources) {
3384
- if (source.sql.holders === void 0) return "not-tables";
3385
- held.push({
3386
- table: source.sql.table,
3387
- holders: source.sql.holders
3388
- });
3389
- }
3390
- return held;
3391
- }
3392
- function indent(sql, by) {
3393
- return sql.replaceAll(/^/gmu, by);
3394
- }
3395
- /**
3396
- * Every source's rows of one instance, each compared with its own typed
3397
- * `v_key_<n>`.
3398
- */
3399
- function sourceRowsOf(scope, sources) {
3400
- return sources.map((source, index) => indent(source.holders.rows(scope, { id: `v_key_${String(index)}` }), " ")).join("\n union all\n");
3401
- }
3402
- function sourceKeys(sources) {
3403
- return {
3404
- declare: sources.map((source, index) => ` v_key_${String(index)} ${source.holders.idType};`).join("\n"),
3405
- assign: (value, by) => sources.map((_, index) => `${by}v_key_${String(index)} := ${value};`).join("\n")
3406
- };
3407
- }
3408
- function regclassOf(table) {
3409
- return `${quoteLiteral(quoteQualified(table))}::regclass`;
3410
- }
3411
- function sourceTables(sources) {
3412
- return [...new Set(sources.map((source) => quoteQualified(source.table)))];
3413
- }
3414
- /**
3415
- * `min` and `max` over membership sources: the same commit-time check as on a
3416
- * mapped table, counted over every source of the scope.
3417
- */
3418
- function sourceHoldersTriggerSql(ctx, scope, sources, counted) {
3419
- const fn = qualified(ctx, `${OWNERSHIP.holders}_${scope}`);
3420
- const keys = sourceKeys(sources);
3421
- const rows = sourceRowsOf(scope, sources);
3422
- const collect = sources.map((source) => ` if tg_relid = ${regclassOf(source.table)} then
3423
- if tg_op in ('UPDATE', 'DELETE') then
3424
- v_ids := v_ids || ${source.holders.id(scope, "old")};
3425
- end if;
3426
- if tg_op in ('INSERT', 'UPDATE') then
3427
- v_ids := v_ids || ${source.holders.id(scope, "new")};
3428
- end if;
3429
- end if;`);
3430
- const checks = counted.map((rule) => {
3431
- const filters = ["h.live", `h.role = ${quoteLiteral(rule.role)}`];
3432
- const kind = roleKindSql(ctx, rule.role, "h.via");
3433
- if (kind !== void 0) filters.push(kind);
3434
- const lines = [` select count(distinct h.user_id) into v_count
3435
- from (
3436
- ${rows}
3437
- ) h
3438
- where ${filters.join("\n and ")};`];
3439
- if (rule.min > 0) lines.push(` if v_total > 0 and v_count < ${String(rule.min)} then
3440
- raise exception using
3441
- errcode = '23514',
3442
- message = ${quoteLiteral(`permdock: ${scope} `)} || v_id || ${quoteLiteral(` keeps at least ${String(rule.min)} ${rule.role}`)},
3443
- hint = 'last-holder';
3444
- end if;`);
3445
- if (rule.max !== void 0) lines.push(` if v_count > ${String(rule.max)} then
3446
- raise exception using
3447
- errcode = '23514',
3448
- message = ${quoteLiteral(`permdock: ${scope} `)} || v_id || ${quoteLiteral(` has at most ${String(rule.max)} ${rule.role}`)},
3449
- hint = 'max-holders';
3450
- end if;`);
3451
- return lines.join("\n");
3452
- });
3453
- const triggers = sourceTables(sources).map((table) => `drop trigger if exists ${objectName(OWNERSHIP.holders, scope)} on ${table};
3454
- create constraint trigger ${objectName(OWNERSHIP.holders, scope)}
3455
- after insert or update or delete on ${table}
3456
- deferrable initially deferred
3457
- for each row execute function ${fn}();`);
3458
- return `-- ${scope}: holder counts (min / max) over the membership sources, checked at commit
3459
- create or replace function ${fn}()
3460
- returns trigger
3461
- language plpgsql
3462
- security definer
3463
- set search_path = ''
3464
- as $$
3465
- declare
3466
- v_ids text[] := '{}';
3467
- v_id text;
3468
- ${keys.declare}
3469
- v_total bigint;
3470
- v_count bigint;
3471
- begin
3472
- ${collect.join("\n")}
3473
- foreach v_id in array v_ids loop
3474
- continue when v_id is null;
3475
- ${keys.assign("v_id", " ")}
3476
- select count(*) into v_total
3477
- from (
3478
- ${rows}
3479
- ) h;
3480
- ${checks.join("\n")}
3481
- end loop;
3482
- return null;
3483
- end;
3484
- $$;
3485
- ${triggers.join("\n")}`;
3486
- }
3487
- function collectChangesSql(changed) {
3488
- return ` v_changes := v_changes || coalesce((select jsonb_agg(to_jsonb(c)) from (${changed}) c), '[]'::jsonb);`;
3489
- }
3490
- /**
3491
- * `transferOnly` over membership sources: each source table's statement
3492
- * triggers diff its transition tables, and the count after reads every source.
3493
- */
3494
- function sourceTransferTriggerSql(ctx, scope, sources, roles) {
3495
- const fn = qualified(ctx, `${OWNERSHIP.transferOnly}_${scope}`);
3496
- const keys = sourceKeys(sources);
3497
- const list = `array[${roles.map(quoteLiteral).join(", ")}]::text[]`;
3498
- const kind = kindFilterSql(ctx, "h.role", "h.via");
3499
- const changes = (source, from, delta) => `select h.id, h.role, ${delta} as delta from (${source.holders.rows(scope, { from }).replaceAll("\n", " ")}) h where h.role = any(${list})`;
3500
- const branches = sources.map((source) => ` if tg_relid = ${regclassOf(source.table)} then
3501
- if tg_op in ('INSERT', 'UPDATE') then
3502
- ${collectChangesSql(changes(source, "permdock_new", "1"))}
3503
- end if;
3504
- if tg_op in ('UPDATE', 'DELETE') then
3505
- ${collectChangesSql(changes(source, "permdock_old", "-1"))}
3506
- end if;
3507
- end if;`);
3508
- const triggers = sourceTables(sources).flatMap((table) => [
3509
- "insert",
3510
- "update",
3511
- "delete"
3512
- ].map((op) => {
3513
- const name = quoteIdent(`${OWNERSHIP.transferOnly}_${scope}_${op}`);
3514
- return `drop trigger if exists ${name} on ${table};
3515
- create trigger ${name}
3516
- after ${op} on ${table}
3517
- referencing ${op === "insert" ? "new table as permdock_new" : op === "delete" ? "old table as permdock_old" : "old table as permdock_old new table as permdock_new"}
3518
- for each statement execute function ${fn}();`;
3519
- }));
3520
- return `-- ${scope}: transfer-only roles (${roles.join(", ")}) keep their holder count per statement, over the membership sources
3521
- create or replace function ${fn}()
3522
- returns trigger
3523
- language plpgsql
3524
- security definer
3525
- set search_path = ''
3526
- as $$
3527
- declare
3528
- v_changes jsonb := '[]'::jsonb;
3529
- v_change record;
3530
- v_after bigint;
3531
- ${keys.declare}
3532
- begin
3533
- ${branches.join("\n")}
3534
- for v_change in
3535
- select x.id, x.role, sum(x.delta) as delta
3536
- from jsonb_to_recordset(v_changes) x(id text, role text, delta bigint)
3537
- group by x.id, x.role
3538
- loop
3539
- continue when v_change.delta = 0 or v_change.id is null;
3540
- ${keys.assign("v_change.id", " ")}
3541
- select count(distinct h.user_id) into v_after
3542
- from (
3543
- ${sourceRowsOf(scope, sources)}
3544
- ) h
3545
- where h.live
3546
- and h.role = v_change.role${kind === void 0 ? "" : `\n and ${kind}`};
3547
- if v_after > 0 and v_after - v_change.delta > 0 then
3548
- raise exception using
3549
- errcode = '23514',
3550
- message = 'permdock: ' || v_change.role || ${quoteLiteral(` in ${scope} `)} || v_change.id || ' moves only by transfer',
3551
- hint = 'transfer-only';
3552
- end if;
3553
- end loop;
3554
- return null;
3555
- end;
3556
- $$;
3557
- ${triggers.join("\n")}`;
3558
- }
3559
- function pairsSql(pairs) {
3560
- return `values ${pairs.map((pair) => `(${quoteLiteral(pair.assigner)}, ${quoteLiteral(pair.role)})`).join(", ")}`;
3561
- }
3562
- /**
3563
- * Membership rows of the membership sources for scope `name`, each source's
3564
- * `select` comparing its user column with a variable `user` names.
3565
- */
3566
- function sourceRowsSql(sources, user) {
3567
- const keep = sources.some((source) => source.sql.keeps);
3568
- return sources.map((source) => source.sql.select(user(source), keep).replaceAll(/^/gmu, " ")).join("\n union all\n");
3569
- }
3570
- //#endregion
3571
- //#region src/cli/rls/graph.ts
3572
- function tableFor(resource, tables) {
3573
- return tables?.[resource] ?? resource;
3574
- }
3575
- /**
3576
- * Every `related` condition the policy's grants compile to, with the resource
3577
- * graph they need, groups included.
3578
- */
3579
- function graphPlan(policy) {
3580
- const scopes = scopeList(policy.scopes);
3581
- const plan = /* @__PURE__ */ new Map();
3582
- const entryFor = (node) => {
3583
- const entry = plan.get(node.name) ?? {
3584
- node,
3585
- relations: /* @__PURE__ */ new Set(),
3586
- links: /* @__PURE__ */ new Set()
3587
- };
3588
- plan.set(node.name, entry);
3589
- return entry;
3590
- };
3591
- const addRelation = (node, relation) => {
3592
- const entry = entryFor(node);
3593
- if (entry.relations.has(relation)) return;
3594
- entry.relations.add(relation);
3595
- for (const name of expandRelation(node, relation)) {
3596
- const spec = node.relations[name];
3597
- if (!isEdgeRelation(spec) || spec.groups === void 0) continue;
3598
- for (const { resource, relation: groupRelation } of groupEntries(spec)) {
3599
- const target = policy.resources.get(resource);
3600
- if (target !== void 0 && target.name !== node.name) addRelation(target, groupRelation);
3601
- }
3602
- }
3603
- };
3604
- const addLinks = (hops) => {
3605
- for (let index = 1; index < hops.length; index += 1) {
3606
- const from = policy.resources.get(hops[index - 1]?.resource ?? "");
3607
- const hop = hops[index];
3608
- if (from !== void 0 && hop !== void 0) entryFor(from).links.add(hop.link);
3609
- }
3610
- };
3611
- const addAbove = (above) => {
3612
- const node = above === void 0 ? void 0 : policy.resources.get(above.resource);
3613
- if (above === void 0 || node === void 0) return;
3614
- const entry = entryFor(node);
3615
- entry.closure = Math.max(entry.closure ?? 0, above.depth);
3616
- entry.restrictedAncestors = above;
3617
- };
3618
- for (const grant of policy.grants) {
3619
- const row = policy.resources.get(grant.permission.resource);
3620
- for (const item of flattenGrantee(grant.to)) {
3621
- if (item.kind === "inherit") {
3622
- const inherited = inheritCondition(item, row, policy.resources);
3623
- addLinks(inherited?.hops ?? []);
3624
- addAbove(inherited?.restrictedAncestors);
3625
- continue;
3626
- }
3627
- if (item.kind !== "relation") continue;
3628
- const condition = relationCondition(item, row, scopes, { resources: policy.resources });
3629
- if (condition?.op !== "related") continue;
3630
- const node = policy.resources.get(condition.resource);
3631
- if (node === void 0) continue;
3632
- addRelation(node, condition.relation);
3633
- const entry = entryFor(node);
3634
- if (condition.depth > 0 && isSelfParented(node)) entry.closure = Math.max(entry.closure ?? 0, condition.depth);
3635
- addLinks(condition.hops ?? []);
3636
- addAbove(condition.restrictedAncestors);
3637
- }
3638
- }
3639
- return plan;
3640
- }
3641
- /** The closure depth per walked resource, as `RlsSqlContext.graph` carries it. */
3642
- function closureDepths(plan) {
3643
- const out = {};
3644
- for (const [name, entry] of plan) if (entry.closure !== void 0) out[name] = entry.closure;
3645
- return out;
3646
- }
3647
- /**
3648
- * The `permitted_<resource>_ids(relation)` arm for one concrete relation: ids
3649
- * of `resource` the subject holds it on, directly or through a group. `asked`
3650
- * are the relation names that include it, so a call for any of them (or for
3651
- * all, with null) reads this arm.
3652
- */
3653
- function relationArm(ctx, plan, node, relation, asked, tables) {
3654
- const spec = node.relations[relation];
3655
- if (!isEdgeRelation(spec) && !isPrincipalRelation(spec) && (!isFieldRelation(spec) || spec.memberOf !== void 0)) throw configError(`PermDock CLI: relation '${relation}' on ${node.name} is not a graph relation RLS can compile`);
3656
- const guard = asked.length === 1 ? `(p_relation is null or p_relation = ${quoteLiteral(asked[0] ?? relation)})` : `(p_relation is null or p_relation in (${asked.map(quoteLiteral).join(", ")}))`;
3657
- return ` select a.id from (${graphSqlText(relationArmSql(node.name, relation, {
3658
- resources: new Map([...plan].map(([name, item]) => [name, item.node])),
3659
- ...tables === void 0 ? {} : { tables },
3660
- qualify: qualifySqlTable,
3661
- holders: (resource, groupRelation) => [{ text: `select ${qualified(ctx, graphHelper(resource))}(${quoteLiteral(groupRelation)})` }]
3662
- }), ctx)}) a\n where ${guard}${activeUserSql(ctx).map((part) => ` and ${part}`).join("")}`;
3663
- }
3664
- function permittedSql(ctx, plan, entry, tables) {
3665
- const fn = qualified(ctx, graphHelper(entry.node.name));
3666
- const asked = [...entry.relations].toSorted();
3667
- const arms = [...new Set(asked.flatMap((name) => expandRelation(entry.node, name)))].toSorted().map((relation) => relationArm(ctx, plan, entry.node, relation, asked.filter((name) => expandRelation(entry.node, name).includes(relation)), tables));
3668
- if (arms.length === 0) arms.push(" select null::text where false");
3669
- return `-- ${entry.node.name}: ids the subject holds a relation on (all relations when p_relation is null)
3670
- create or replace function ${fn}(p_relation text)
3671
- returns setof text
3672
- language sql
3673
- stable
3674
- security definer
3675
- cost 1000
3676
- set search_path = ''
3677
- as $$
3678
- ${arms.join("\n union\n")}
3679
- $$;
3680
- revoke execute on function ${fn}(text) from public, anon;
3681
- grant execute on function ${fn}(text) to authenticated;`;
3682
- }
3683
- /**
3684
- * `permdock_link_<resource>_<link>(ids)`: ids of `resource` whose link points
3685
- * into `ids`, read past the table's own policies.
3686
- */
3687
- function linkSql(ctx, node, link, tables) {
3688
- const spec = Object.hasOwn(node.links, link) ? node.links[link] : void 0;
3689
- if (spec === void 0) throw configError(`PermDock CLI: ${node.name} has no link '${link}'`);
3690
- const fn = qualified(ctx, linkHelper(node.name, link));
3691
- return `-- ${node.name}.${link}: rows whose ${spec.field} points at one of the given ${spec.resource} ids
3692
- create or replace function ${fn}(p_ids text[])
3693
- returns setof text
3694
- language sql
3695
- stable
3696
- security definer
3697
- cost 1000
3698
- set search_path = ''
3699
- as $$
3700
- select t.${quoteIdent(node.id)}::text from ${quoteQualified(tableFor(node.name, tables))} t
3701
- where t.${quoteIdent(spec.field)}::text = any(p_ids)
3702
- $$;
3703
- revoke execute on function ${fn}(text[]) from public, anon;
3704
- grant execute on function ${fn}(text[]) to authenticated;`;
3705
- }
3706
- function closureTableSql(ctx) {
3707
- const table = qualified(ctx, CLOSURE.table);
3708
- return `-- the object graph: one row per (ancestor, descendant) within each walked resource's depth,
3709
- -- never crossing a restricted row; kept current by statement triggers on each self-parented table
3710
- create table if not exists ${table} (
3711
- resource text not null,
3712
- ancestor text not null,
3713
- descendant text not null,
3714
- depth integer not null check (depth >= 0),
3715
- primary key (resource, descendant, ancestor)
3716
- );
3717
- create index if not exists ${quoteIdent(`${CLOSURE.table}_ancestor`)} on ${table} (resource, ancestor);
3718
- alter table ${table} enable row level security;
3719
- revoke all on table ${table} from anon, authenticated, public;
3720
- grant select on table ${table} to authenticated;`;
3721
- }
3722
- function closureObjectsSql(ctx, entry, depth, tables) {
3723
- const { node } = entry;
3724
- const parent = node.parent;
3725
- if (parent === void 0) return "";
3726
- const name = node.name;
3727
- const sqlName = graphSqlName(name) ?? name;
3728
- const closure = qualified(ctx, CLOSURE.table);
3729
- const table = quoteQualified(tableFor(name, tables));
3730
- const id = quoteIdent(node.id);
3731
- const up = quoteIdent(parent.field);
3732
- const restricted = restrictedFor(node, "parent");
3733
- const stop = restricted === void 0 ? "false" : `coalesce(t.${quoteIdent(restricted)}, false)`;
3734
- const stopParent = restricted === void 0 ? "false" : `coalesce(p.${quoteIdent(restricted)}, false)`;
3735
- const refresh = qualified(ctx, `${CLOSURE.table}_${sqlName}`);
3736
- const changed = qualified(ctx, `${CLOSURE.table}_${sqlName}_changed`);
3737
- const literal = quoteLiteral(name);
3738
- const restrictedChanged = restricted === void 0 ? "" : ` or n.${quoteIdent(restricted)} is distinct from o.${quoteIdent(restricted)}`;
3739
- const trigger = (suffix) => quoteIdent(`${CLOSURE.table}_${sqlName}_${suffix}`);
3740
- return `-- ${name}: ${restricted === void 0 ? `rows reach their ancestors up to depth ${String(depth)}` : `rows reach their ancestors up to depth ${String(depth)}, stopping at a restricted row`}
3741
- drop policy if exists ${quoteIdent(`${CLOSURE.table}_${sqlName}`)} on ${closure};
3742
- create policy ${quoteIdent(`${CLOSURE.table}_${sqlName}`)} on ${closure}
3743
- for select to authenticated
3744
- using (resource = ${literal} and ancestor in (select ${qualified(ctx, graphHelper(name))}(null)));
3745
- create or replace function ${refresh}(p_ids text[])
3746
- returns void
3747
- language plpgsql
3748
- security definer
3749
- set search_path = ''
3750
- as $$
3751
- declare
3752
- v_cycle text;
3753
- v_affected text[];
3754
- begin
3755
- with recursive walk(start, next, path) as (
3756
- select t.${id}, t.${up}, array[t.${id}::text]
3757
- from ${table} t
3758
- where t.${id}::text = any(p_ids)
3759
- union all
3760
- select walk.start, t.${up}, walk.path || t.${id}::text
3761
- from walk join ${table} t on t.${id} = walk.next
3762
- where not (walk.next::text = any(walk.path))
3763
- )
3764
- select walk.start::text into v_cycle
3765
- from walk
3766
- where walk.next::text = any(walk.path)
3767
- limit 1;
3768
- if v_cycle is not null then
3769
- raise exception 'permdock: % % is its own ancestor', ${literal}, v_cycle
3770
- using errcode = 'check_violation';
3771
- end if;
3772
- with recursive down(id, level) as (
3773
- select t.${id}, 0
3774
- from ${table} t
3775
- where t.${id}::text = any(p_ids) or t.${up}::text = any(p_ids)
3776
- union
3777
- select t.${id}, down.level + 1
3778
- from down join ${table} t on t.${up} = down.id
3779
- where down.level < ${String(depth)}
3780
- )
3781
- select coalesce(array_agg(distinct down.id::text), '{}') into v_affected from down;
3782
- delete from ${closure} c
3783
- where c.resource = ${literal}
3784
- and (c.descendant = any(p_ids) or c.descendant = any(v_affected));
3785
- insert into ${closure} (resource, ancestor, descendant, depth)
3786
- with recursive walk(descendant, ancestor, parent, depth, stop) as (
3787
- select t.${id}::text, t.${id}, t.${up}, 0, ${stop}
3788
- from ${table} t
3789
- where t.${id}::text = any(v_affected)
3790
- union all
3791
- select walk.descendant, p.${id}, p.${up}, walk.depth + 1, ${stopParent}
3792
- from walk join ${table} p on p.${id} = walk.parent
3793
- where not walk.stop and walk.depth < ${String(depth)}
3794
- )
3795
- select ${literal}, walk.ancestor::text, walk.descendant, walk.depth from walk
3796
- on conflict do nothing;
3797
- end
3798
- $$;
3799
- revoke execute on function ${refresh}(text[]) from public, anon, authenticated;
3800
- create or replace function ${changed}()
3801
- returns trigger
3802
- language plpgsql
3803
- security definer
3804
- set search_path = ''
3805
- as $$
3806
- begin
3807
- if tg_op = 'TRUNCATE' then
3808
- delete from ${closure} where resource = ${literal};
3809
- elsif tg_op = 'INSERT' then
3810
- perform ${refresh}(array(select n.${id}::text from new_rows n));
3811
- elsif tg_op = 'DELETE' then
3812
- perform ${refresh}(array(select o.${id}::text from old_rows o));
3813
- else
3814
- perform ${refresh}(array(
3815
- select n.${id}::text
3816
- from new_rows n left join old_rows o on o.${id} = n.${id}
3817
- where o.${id} is null or n.${up} is distinct from o.${up}${restrictedChanged}
3818
- union
3819
- select o.${id}::text
3820
- from old_rows o left join new_rows n on n.${id} = o.${id}
3821
- where n.${id} is null
3822
- ));
3823
- end if;
3824
- return null;
3825
- end
3826
- $$;
3827
- revoke execute on function ${changed}() from public, anon, authenticated;
3828
- drop trigger if exists ${trigger("insert")} on ${table};
3829
- create trigger ${trigger("insert")} after insert on ${table}
3830
- referencing new table as new_rows
3831
- for each statement execute function ${changed}();
3832
- drop trigger if exists ${trigger("update")} on ${table};
3833
- create trigger ${trigger("update")} after update on ${table}
3834
- referencing old table as old_rows new table as new_rows
3835
- for each statement execute function ${changed}();
3836
- drop trigger if exists ${trigger("delete")} on ${table};
3837
- create trigger ${trigger("delete")} after delete on ${table}
3838
- referencing old table as old_rows
3839
- for each statement execute function ${changed}();
3840
- drop trigger if exists ${trigger("truncate")} on ${table};
3841
- create trigger ${trigger("truncate")} after truncate on ${table}
3842
- for each statement execute function ${changed}();
3843
- select ${refresh}(array(select t.${id}::text from ${table} t));`;
3844
- }
3845
- function restrictedRowsHelperSql(ctx, plan, entry, tables) {
3846
- const above = entry.restrictedAncestors;
3847
- if (above === void 0) return "";
3848
- const fn = qualified(ctx, restrictedHelper(entry.node.name));
3849
- const body = graphSqlText(restrictedRowsSql(above, {
3850
- resources: new Map([...plan].map(([name, item]) => [name, item.node])),
3851
- ...tables === void 0 ? {} : { tables },
3852
- qualify: qualifySqlTable,
3853
- closure: `${helperSchema(ctx)}.${CLOSURE.table}`,
3854
- closureDepths: closureDepths(plan)
3855
- }), ctx);
3856
- return `-- ${entry.node.name}: rows a stopped link does not reach below: restricted, under a restricted row within ${String(above.depth - 1)} levels, or deeper
3857
- create or replace function ${fn}()
3858
- returns setof text
3859
- language sql
3860
- stable
3861
- security definer
3862
- cost 1000
3863
- set search_path = ''
3864
- as $$
3865
- ${body}
3866
- $$;
3867
- revoke execute on function ${fn}() from public, anon;
3868
- grant execute on function ${fn}() to authenticated;`;
3869
- }
3870
- /** Group resources a resource's asked relations name, other than itself. */
3871
- function groupTargets(entry) {
3872
- const out = /* @__PURE__ */ new Set();
3873
- for (const asked of entry.relations) for (const name of expandRelation(entry.node, asked)) {
3874
- const spec = entry.node.relations[name];
3875
- const resources = isEdgeRelation(spec) ? groupEntries(spec).map((group) => group.resource) : [];
3876
- for (const resource of resources) if (resource !== entry.node.name) out.add(resource);
3877
- }
3878
- return [...out].toSorted();
3879
- }
3880
- /**
3881
- * Plan entries by name, each after the group resources its helper calls (SQL
3882
- * function bodies are checked on create).
3883
- */
3884
- function dependencyOrder(plan) {
3885
- const out = [];
3886
- const done = /* @__PURE__ */ new Set();
3887
- const visit = (name) => {
3888
- const entry = plan.get(name);
3889
- if (entry === void 0 || done.has(name)) return;
3890
- done.add(name);
3891
- for (const target of groupTargets(entry)) visit(target);
3892
- out.push(entry);
3893
- };
3894
- for (const name of [...plan.keys()].toSorted()) visit(name);
3895
- return out;
3896
- }
3897
- function graphIdsSql(ctx, plan, tables) {
3898
- return dependencyOrder(plan).filter((entry) => entry.relations.size > 0 || entry.closure !== void 0).map((entry) => permittedSql(ctx, plan, entry, tables)).join("\n");
3899
- }
3900
- /**
3901
- * The graph preamble: `permitted_<resource>_ids` for every resource a graph
3902
- * grant reads, and the closure table with its triggers for every self-parented
3903
- * resource a grant walks. Empty when no grant is a graph grant.
3904
- */
3905
- function graphSql(ctx, plan, tables) {
3906
- if (plan.size === 0) return "";
3907
- const sqlNames = /* @__PURE__ */ new Map();
3908
- for (const name of plan.keys()) {
3909
- const helper = graphHelper(name);
3910
- const sql = graphSqlName(name) ?? name;
3911
- if (ctx.scopes.some((scope) => scope.name === sql)) throw configError(`PermDock CLI: resource '${name}' has graph relations and shares its SQL name with the ${sql} scope, so ${helper} would replace the scope helper; rename the resource (permdock doctor PD032)`);
3912
- const other = sqlNames.get(sql);
3913
- if (other !== void 0) throw configError(`PermDock CLI: resources '${other}' and '${name}' both name the SQL helper ${helper}; rename one (permdock doctor PD032)`);
3914
- sqlNames.set(sql, name);
3915
- }
3916
- const entries = dependencyOrder(plan);
3917
- const chunks = entries.flatMap((entry) => [...entry.relations.size === 0 && entry.closure === void 0 ? [] : [permittedSql(ctx, plan, entry, tables)], ...[...entry.links].toSorted().map((link) => linkSql(ctx, entry.node, link, tables))]);
3918
- const walked = entries.filter((entry) => entry.closure !== void 0);
3919
- if (walked.length > 0) {
3920
- chunks.push(closureTableSql(ctx));
3921
- for (const entry of walked) chunks.push(closureObjectsSql(ctx, entry, entry.closure ?? 0, tables));
3922
- for (const entry of walked) {
3923
- const helper = restrictedRowsHelperSql(ctx, plan, entry, tables);
3924
- if (helper !== "") chunks.push(helper);
3925
- }
3926
- }
3927
- return `${chunks.join("\n\n")}\n`;
3928
- }
3929
- //#endregion
3930
- //#region src/cli/sql/tables.ts
3931
- /**
3932
- * The `schema.table` an `rls.tables` entry names, or `resource` when it names
3933
- * none or is `false`.
3934
- */
3935
- function tableNameOf(entry, resource, tables) {
3936
- if (entry === void 0 || entry === false) return resource;
3937
- if (typeof entry === "string") return entry;
3938
- if ("tableOf" in entry) {
3939
- const owner = tables?.[entry.tableOf];
3940
- return typeof owner === "object" && "tableOf" in owner ? entry.tableOf : tableNameOf(owner, entry.tableOf);
3941
- }
3942
- return entry.table ?? resource;
3943
- }
3944
- /**
3945
- * `rls.tables` as resource to table name, the `via` objects reduced to their
3946
- * `table` and the `false` entries left out.
3947
- */
3948
- function tableNames(tables) {
3949
- return tables === void 0 ? void 0 : Object.fromEntries(Object.entries(tables).filter(([, entry]) => entry !== false).map(([resource, entry]) => [resource, tableNameOf(entry, resource, tables)]));
3950
- }
3951
- /**
3952
- * The resources `rls.tables` marks `false` or `{ tableOf }`: no policies of
3953
- * their own, their grants only seeded.
3954
- */
3955
- function tablelessResources(tables) {
3956
- return new Set(Object.entries(tables ?? {}).filter(([, entry]) => entry === false || typeof entry === "object" && "tableOf" in entry).map(([resource]) => resource));
3957
- }
3958
- /**
3959
- * Rejects a `{ tableOf }` entry that names its own resource, a `false` entry or
3960
- * another `{ tableOf }` entry: the owner must have a table of its own.
3961
- */
3962
- function checkSharedTables(tables) {
3963
- for (const [resource, entry] of Object.entries(tables ?? {})) {
3964
- if (typeof entry === "string" || entry === false || !("tableOf" in entry)) continue;
3965
- const owner = tables?.[entry.tableOf];
3966
- if (entry.tableOf === resource || owner === false || typeof owner === "object" && "tableOf" in owner) throw configError(`PermDock CLI: rls.tables.${resource}.tableOf names ${entry.tableOf}, which must be another resource with a table of its own`);
3967
- }
3968
- }
3969
- function singular(name) {
3970
- if (name.endsWith("ies")) return `${name.slice(0, -3)}y`;
3971
- if (name.endsWith("sses")) return name.slice(0, -2);
3972
- return name.endsWith("s") && !name.endsWith("ss") ? name.slice(0, -1) : name;
3973
- }
3974
- /** The `via` entries of `rls.tables`, by resource. */
3975
- function resolveVias(tables, scopes, dialect) {
3976
- const out = {};
3977
- for (const [resource, entry] of Object.entries(tables ?? {})) {
3978
- if (typeof entry === "string" || entry === false || "tableOf" in entry) continue;
3979
- const { via } = entry;
3980
- const scope = via.scope ?? scopes[0]?.name;
3981
- if (scope === void 0 || !scopes.some((item) => item.name === scope)) throw configError(`PermDock CLI: rls.tables.${resource}.via.scope '${scope ?? ""}' is not a scope of the policy (${scopes.map((item) => item.name).join(", ")})`);
3982
- const name = singular(via.table.slice(via.table.lastIndexOf(".") + 1));
3983
- out[resource] = {
3984
- helper: permittedIdsHelper(name),
3985
- key: via.key ?? `${name}_id`,
3986
- scope,
3987
- table: via.table.includes(".") ? via.table : `public.${via.table}`,
3988
- column: via.column,
3989
- id: via.id ?? "id",
3990
- type: via.type ?? (dialect === "supabase" ? "uuid" : "text")
3991
- };
3992
- }
3993
- const helpers = /* @__PURE__ */ new Map();
3994
- for (const [resource, via] of Object.entries(out)) {
3995
- const seen = helpers.get(via.helper);
3996
- if (seen !== void 0 && (seen.table !== via.table || seen.column !== via.column || seen.id !== via.id || seen.scope !== via.scope || seen.type !== via.type)) throw configError(`PermDock CLI: rls.tables.${resource}.via names ${via.helper}, which another resource defines over a different parent; give the parents different table names`);
3997
- helpers.set(via.helper, via);
3998
- }
3999
- return Object.keys(out).length === 0 ? void 0 : out;
4000
- }
4001
- //#endregion
4002
- export { byKey as $, tokenScopeAllowsCall as A, memoizes as B, permittedByPermissionHelper as C, scopeTable as Ct, memoReadsSql as D, activeUserSql as Dt, helpersSql as E, activeRowSql as Et, disabledColumn as F, roleRows as G, sourcesKeep as H, memberColumn as I, hasCustomRoleChecksFor as J, globalRoleSource as K, memoDiscriminatorSql as L, memoReadTriggersSql as M, capabilityAccessSql as N, seedSql as O, checkSuspension as Ot, claimKeptLines as P, byCodeUnit as Q, memoReadSql as R, permissionKeysForHelper as S, scopeSources as St, accessSql as T, activeMembershipSql as Tt, globalRoleRows as U, sourceFilters as V, membershipRows as W, rolesTableScope as X, raiseSql as Y, storedTenant as Z, ASSIGNMENTS as _, memberOfHelper as _t, tablelessResources as a, graphHelper as at, checkName as b, permittedIdsHelper as bt, graphPlan as c, hasMemberFor as ct, pairsSql as d, isTeamScope as dt, API_KEY_ALLOWS as et, sourceHoldersTriggerSql as f, linkHelper as ft, transferTriggerSql as g, memberIdsHelper as gt, holdersTriggerSql as h, memberForTable as ht, tableNames as i, CLOSURE as it, tokenScopesPlan as j, TOKEN_SCOPE_ALLOWS as k, graphSql as l, hasPermittedUsers as lt, sourceTransferTriggerSql as m, memberForSources as mt, resolveVias as n, apiKeyFields as nt, closureDepths as o, graphSqlName as ot, sourceRowsSql as p, memberForHelper as pt, currentKeyExpr as q, tableNameOf as r, apiKeysPlan as rt, graphIdsSql as s, graphSqlText as st, checkSharedTables as t, apiKeyAllowsCall as tt, holderSources as u, inheritedRowsHelper as ut, OWNERSHIP as v, memberRoleOf as vt, requiresSql as w, activeInstancesSql as wt, permissionHelpersSql as x, restrictedHelper as xt, PERMISSION_HELPERS as y, permittedForHelper as yt, memoWriteSql as z };