permdock 0.25.1 → 0.27.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-CMghLDUG.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-B8heXoYy.js +76 -0
  27. package/dist/arazzo-DdJBVrsy.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-BHYVxJDD.js +29 -0
  57. package/dist/casbin-D33ZeUf5.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 +24 -0
  88. package/dist/cli/plugins/app.js +36 -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-BmQrcTvx.js +85 -0
  114. package/dist/codemod-BpjMjxly.js +2159 -0
  115. package/dist/codemod-C_NKj01W.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-D8c1nFGy.d.ts +118 -0
  126. package/dist/compile-Dy3zMRxo.js +724 -0
  127. package/dist/completion-CSncf6cX.js +150 -0
  128. package/dist/conditions-CkHgXoZB.js +385 -0
  129. package/dist/config-iyy90IOU.js +143 -0
  130. package/dist/config-report-D607UDnv.js +55 -0
  131. package/dist/config-shape-B6tdyBju.js +149 -0
  132. package/dist/config-xiX3R65I.js +25 -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-BhoJiHi0.js +4847 -0
  173. package/dist/doctor-CoKSRLhf.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-CyQLisIB.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-CJE3Xud5.js +1168 -0
  208. package/dist/gen-WzJbAcMJ.js +1 -0
  209. package/dist/gen-kind-DFQnQwFN.d.ts +13 -0
  210. package/dist/gen-kind-DGQxmID0.js +69 -0
  211. package/dist/generate-5_kz2309.js +305 -0
  212. package/dist/generate-DF6Y8ncI.js +67 -0
  213. package/dist/generate-DIZNzMuk.js +2339 -0
  214. package/dist/generate-DhP0jQDR.js +97 -0
  215. package/dist/generate-options-CLPUvgVW.js +1185 -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-FSets5NB.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-BqoDHpFt.js +1158 -0
  236. package/dist/import-DemSCI1R.js +318 -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-BlYRZRnQ.js +94 -0
  246. package/dist/init-CgoOwXtk.js +95 -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-CNQJN8Fy.js +67 -0
  268. package/dist/login-TwrSjf6k.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-XIXxXYty.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-CH9Dh5UX.js +260 -0
  302. package/dist/openapi-CrCBEFEm.js +95 -0
  303. package/dist/openapi-D2dmyWZK.js +411 -0
  304. package/dist/openapi-document-CJO6cUS1.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-CU7OppLv.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-BBQe7GZp.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-1XW5OfAZ.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-C-Lzp3Zh.d.ts +18 -0
  344. package/dist/policy-DFD2J5o_.js +476 -0
  345. package/dist/policy-FrCL4wDQ.js +37 -0
  346. package/dist/policy-bundle-1Znzdxse.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-DVgkPQKM.js +1 -0
  353. package/dist/powersync-Y-_z8V5X.js +40 -0
  354. package/dist/powersync-pbvC5g6K.js +1630 -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-C3_fCkgX.js +1 -0
  375. package/dist/pull-CpLyeY2p.js +252 -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-Ca4ClMU2.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-CmyxiQsS.js +321 -0
  413. package/dist/rls-DY5ITGzf.js +946 -0
  414. package/dist/rls-files-BtaUXVp-.js +114 -0
  415. package/dist/rls-options-CEpg5nDP.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-BoVUFspr.js +726 -0
  425. package/dist/run-BriRChKE.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-C4x8UqS7.js +28 -0
  431. package/dist/schema-BeY3croo.js +403 -0
  432. package/dist/schema-Zfpbku8U.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-B0cLRZ7w.js +202 -0
  454. package/dist/skills-DiGdMvMw.js +50 -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-B7Q5bO-P.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-C7FNwQ1p.js +2 -0
  501. package/dist/supabase-hook-loL2iJVb.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-C8IwkTHq.js +3249 -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-DFZKovb3.js +77 -0
  550. package/dist/types-DONLJQjY.d.ts +134 -0
  551. package/dist/types-OzSal_K_.d.ts +178 -0
  552. package/dist/types-XSfi6ihL.d.ts +65 -0
  553. package/dist/types-nXo_oQYk.d.ts +1235 -0
  554. package/dist/unplugin/index.d.ts +1 -3
  555. package/dist/unplugin/index.js +3 -4
  556. package/dist/usage-BgNAgZfj.js +31 -0
  557. package/dist/usage-D6HUlfvP.js +1 -0
  558. package/dist/usage-llSQehNg.js +761 -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-nMTdEqBB.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-8F9VSQrK.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-BUVqRmaJ.js +0 -36
  615. package/dist/arazzo-CWmM8pWw.js +0 -77
  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-DIvUMac7.js +0 -242
  637. package/dist/casbin-qpG_ZphP.js +0 -30
  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-CXgE1qpa.js +0 -86
  655. package/dist/codemod-BJ0Kgv9b.js +0 -36
  656. package/dist/codemod-DjgVx3RQ.js +0 -2800
  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-DUHSRdoQ.js +0 -152
  666. package/dist/config-CgA_Z5Ts.js +0 -26
  667. package/dist/config-DC7aiuhP.js +0 -116
  668. package/dist/config-report-B31MnuKf.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-Dvt1_ROJ.js +0 -3560
  703. package/dist/doctor-JLouRSQt.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-D17P8vo0.js +0 -827
  727. package/dist/gen-YA3SK59O.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-B8zbuskR.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-BdgWNuc3.js +0 -96
  752. package/dist/init-DKRhYiGW.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-DEvccJwP.js +0 -68
  767. package/dist/login-IIUDSAYW.js +0 -257
  768. package/dist/lru-8q4WZjBV.js +0 -28
  769. package/dist/manifest-BoCYBbQL.js +0 -46
  770. package/dist/manifest-C6eFl3Vo.d.ts +0 -349
  771. package/dist/manifest-CZ-GmsOL.js +0 -401
  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-BFUnL8Yi.js +0 -137
  784. package/dist/openapi-Cc-aS9xC.js +0 -416
  785. package/dist/openapi-DcjyfR1g.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-LDciF_4t.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-DvK6INyx.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-B5YjtUGd.js +0 -1532
  819. package/dist/powersync-BgUsk2Nf.js +0 -1
  820. package/dist/powersync-Dx7odzyw.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-Pde1lapF.js +0 -257
  835. package/dist/pull-a4RpDxk8.js +0 -1
  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-D5_kABup.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-BI687j8q.js +0 -2700
  855. package/dist/rls-CKLHLcRl.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-B4heHtD1.js +0 -1
  863. package/dist/run-BG2kPruh.js +0 -694
  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-BvTBo9-D.js +0 -29
  869. package/dist/schema-BlnU_TzE.js +0 -414
  870. package/dist/schema-grK6TTBH.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-DzNdLezx.js +0 -51
  883. package/dist/skills-nPLVGtGH.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-dk1kB9bJ.js +0 -92
  916. package/dist/supabase-hook-Bu5gkzix.js +0 -1
  917. package/dist/supabase-hook-Cf9zKz8T.js +0 -4263
  918. package/dist/supautils-BREOPaHY.js +0 -1186
  919. package/dist/support-session-BGeEYDSq.js +0 -158
  920. package/dist/tables-DnNACfAr.js +0 -4003
  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-BkDU1dYf.js +0 -762
  946. package/dist/usage-DNj42KHA.js +0 -32
  947. package/dist/usage-DrB_tDNk.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-Boehaks6.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
@@ -0,0 +1,3249 @@
1
+ import { c as listPermissions, h as formerKeys } from "./permission-registry-DMYRZVcn.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-Ck5sjYQR.js";
3
+ import { o as flattenGrantee } from "./grantee-BPUG6f0r.js";
4
+ import { c as rootScope, d as scopeList } from "./scopes-B-KX9EI8.js";
5
+ import { t as canonicalJson } from "./canonical-json-BibZkXtE.js";
6
+ import { r as relationCondition, t as inheritCondition } from "./grantee-conditions-Dob6QQAc.js";
7
+ import { l as partitionsOf, p as scopeField } from "./tenancy-B5Xxt9Sc.js";
8
+ import { a as delegatedScopeMap } from "./permdock-BueSeg7X.js";
9
+ import { i as configError } from "./errors-DgLOqc6j.js";
10
+ import { d as sqlTextArray, i as qualifySqlTable, t as SQL_IDENT } from "./sql-T4GaBh9X.js";
11
+ import { d as restrictedRowsSql, i as scopeColumn, l as relationArmSql } from "./compile-BUKXrueE.js";
12
+ import { t as AUTHZ_VERSION_TABLE } from "./sources-DnjJPGfb.js";
13
+ import { a as quoteIdent, c as quoteTable, i as qualified, o as quoteLiteral, r as helperSchema, s as quoteQualified } from "./quote-BKrTBbcH.js";
14
+ import { A as tenantTypeOf, D as idTypeOf, O as scopeTypeOf, _ as subjectClaimJsonSql, d as keyTenantSql, f as kindFilterSql, h as roleKindSql, i as allowEntry, m as memberVia, n as GLOBAL_ROLES, o as rootName, r as HELPERS, s as signedIn, t as CUSTOM_ROLES, v as subjectClaimSql, x as userIdHelperSql, y as subjectIdSql } from "./shared-BdF5DJDQ.js";
15
+ import { $ as linkHelper, A as userActive, B as trustedReaderGrants, C as sourcesKeep, D as keyTenantLine, E as instancesActive, F as perScope, G as graphHelper, H as byKey, I as raiseSql, J as hasMemberFor, K as graphSqlName, L as roleReadersSql, M as currentKeyExpr, N as customRolesSql, P as hasCustomRoleChecksFor, Q as isTeamScope, R as rolesTableScope, S as sourcesBodyOf, V as byCodeUnit, W as CLOSURE, Y as hasMemberOf, _ as memoizes, at as memberRoleOf, b as sourceIdOf, c as claimTenant, ct as restrictedHelper, d as hasBody, dt as activeInstancesSql, et as memberForHelper, ft as activeMembershipSql, g as memoizedSetofSql, gt as grantPermissionSql, h as memoWriteSql, it as memberOfHelper, j as globalRoleSource, l as disabledColumn, lt as scopeSources, m as memoHitList, mt as activeUserSql, n as interactiveAllowsCall, o as memoUserSql, ot as permittedForHelper, p as memberColumn, pt as activeRowSql, q as graphSqlText, r as interactiveAllowsSql, rt as memberIdsHelper, s as claimKeptLines, st as permittedIdsHelper, tt as memberForSources, u as functionBody, ut as scopeTable, v as scopedBody, w as sqlBody, x as sourceRows, y as sourceFilters, z as storedTenant } from "./interactive-only-BZu9rLpa.js";
16
+ import { createHash } from "node:crypto";
17
+ // src/cli/rls/graph.ts
18
+ function tableFor(resource, tables) {
19
+ return tables?.[resource] ?? resource;
20
+ }
21
+ /**
22
+ * Every `related` condition the policy's grants compile to, with the resource
23
+ * graph they need, groups included.
24
+ */
25
+ function graphPlan(policy) {
26
+ const scopes = scopeList(policy.scopes);
27
+ const plan = /* @__PURE__ */ new Map();
28
+ const entryFor = (node) => {
29
+ const entry = plan.get(node.name) ?? {
30
+ node,
31
+ relations: /* @__PURE__ */ new Set(),
32
+ links: /* @__PURE__ */ new Set()
33
+ };
34
+ plan.set(node.name, entry);
35
+ return entry;
36
+ };
37
+ const addRelation = (node, relation) => {
38
+ const entry = entryFor(node);
39
+ if (entry.relations.has(relation)) return;
40
+ entry.relations.add(relation);
41
+ for (const name of expandRelation(node, relation)) {
42
+ const spec = node.relations[name];
43
+ if (!isEdgeRelation(spec) || spec.groups === void 0) continue;
44
+ for (const { resource, relation: groupRelation } of groupEntries(spec)) {
45
+ const target = policy.resources.get(resource);
46
+ if (target !== void 0 && target.name !== node.name) addRelation(target, groupRelation);
47
+ }
48
+ }
49
+ };
50
+ const addLinks = (hops) => {
51
+ for (let index = 1; index < hops.length; index += 1) {
52
+ const from = policy.resources.get(hops[index - 1]?.resource ?? "");
53
+ const hop = hops[index];
54
+ if (from !== void 0 && hop !== void 0) entryFor(from).links.add(hop.link);
55
+ }
56
+ };
57
+ const addAbove = (above) => {
58
+ const node = above === void 0 ? void 0 : policy.resources.get(above.resource);
59
+ if (above === void 0 || node === void 0) return;
60
+ const entry = entryFor(node);
61
+ entry.closure = Math.max(entry.closure ?? 0, above.depth);
62
+ entry.restrictedAncestors = above;
63
+ };
64
+ for (const grant of policy.grants) {
65
+ const row = policy.resources.get(grant.permission.resource);
66
+ for (const item of flattenGrantee(grant.to)) {
67
+ if (item.kind === "inherit") {
68
+ const inherited = inheritCondition(item, row, policy.resources);
69
+ addLinks(inherited?.hops ?? []);
70
+ addAbove(inherited?.restrictedAncestors);
71
+ continue;
72
+ }
73
+ if (item.kind !== "relation") continue;
74
+ const condition = relationCondition(item, row, scopes, { resources: policy.resources });
75
+ if (condition?.op !== "related") continue;
76
+ const node = policy.resources.get(condition.resource);
77
+ if (node === void 0) continue;
78
+ addRelation(node, condition.relation);
79
+ const entry = entryFor(node);
80
+ if (condition.depth > 0 && isSelfParented(node)) entry.closure = Math.max(entry.closure ?? 0, condition.depth);
81
+ addLinks(condition.hops ?? []);
82
+ addAbove(condition.restrictedAncestors);
83
+ }
84
+ }
85
+ return plan;
86
+ }
87
+ /** The closure depth per walked resource, as `RlsSqlContext.graph` carries it. */
88
+ function closureDepths(plan) {
89
+ const out = {};
90
+ for (const [name, entry] of plan) if (entry.closure !== void 0) out[name] = entry.closure;
91
+ return out;
92
+ }
93
+ /**
94
+ * The `permitted_<resource>_ids(relation)` arm for one concrete relation: ids
95
+ * of `resource` the subject holds it on, directly or through a group. `asked`
96
+ * are the relation names that include it, so a call for any of them (or for
97
+ * all, with null) reads this arm.
98
+ */
99
+ function relationArm(ctx, plan, node, relation, asked, tables) {
100
+ const spec = node.relations[relation];
101
+ 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`);
102
+ 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(", ")}))`;
103
+ return ` select a.id from (${graphSqlText(relationArmSql(node.name, relation, {
104
+ resources: new Map([...plan].map(([name, item]) => [name, item.node])),
105
+ ...tables === void 0 ? {} : { tables },
106
+ qualify: qualifySqlTable,
107
+ idType: (resource) => idTypeOf(ctx, resource),
108
+ holders: (resource, groupRelation) => [{ text: `select ${qualified(ctx, graphHelper(resource))}(${quoteLiteral(groupRelation)})` }]
109
+ }), ctx)}) a\n where ${guard}${activeUserSql(ctx).map((part) => ` and ${part}`).join("")}`;
110
+ }
111
+ function permittedSql(ctx, plan, entry, tables) {
112
+ const fn = qualified(ctx, graphHelper(entry.node.name));
113
+ const asked = [...entry.relations].toSorted();
114
+ 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));
115
+ const idType = idTypeOf(ctx, entry.node.name);
116
+ if (arms.length === 0) arms.push(` select null::${idType} where false`);
117
+ const query = arms.join("\n union\n");
118
+ const comment = `-- ${entry.node.name}: ids the subject holds a relation on (all relations when p_relation is null)`;
119
+ const grants = `revoke execute on function ${fn}(text) from public, anon;
120
+ grant execute on function ${fn}(text) to authenticated;`;
121
+ if (memoizes(ctx)) return `${comment}
122
+ ${memoizedSetofSql({
123
+ fn,
124
+ param: "p_relation text",
125
+ returns: `setof ${idType}`,
126
+ idType,
127
+ scope: `rel.${entry.node.name}`,
128
+ keySql: "coalesce(p_relation, '')",
129
+ userSql: memoUserSql(ctx, subjectIdSql(ctx)),
130
+ query,
131
+ ...ctx.memo === void 0 ? {} : { api: ctx.memo },
132
+ grants
133
+ })}`;
134
+ return `${comment}
135
+ create or replace function ${fn}(p_relation text)
136
+ returns setof ${idType}
137
+ language sql
138
+ stable
139
+ security definer
140
+ cost 1000
141
+ set search_path = ''
142
+ as $$
143
+ ${query}
144
+ $$;
145
+ ${grants}`;
146
+ }
147
+ /**
148
+ * `permdock_link_<resource>_<link>(ids)`: ids of `resource` whose link points
149
+ * into `ids`, read past the table's own policies.
150
+ */
151
+ function linkSql(ctx, node, link, tables) {
152
+ const spec = Object.hasOwn(node.links, link) ? node.links[link] : void 0;
153
+ if (spec === void 0) throw configError(`PermDock CLI: ${node.name} has no link '${link}'`);
154
+ const fn = qualified(ctx, linkHelper(node.name, link));
155
+ const sourceType = idTypeOf(ctx, node.name);
156
+ const targetType = idTypeOf(ctx, spec.resource);
157
+ return `-- ${node.name}.${link}: rows whose ${spec.field} points at one of the given ${spec.resource} ids
158
+ create or replace function ${fn}(p_ids ${targetType}[])
159
+ returns setof ${sourceType}
160
+ language sql
161
+ stable
162
+ security definer
163
+ cost 1000
164
+ set search_path = ''
165
+ as $$
166
+ select t.${quoteIdent(node.id)} from ${quoteQualified(tableFor(node.name, tables))} t
167
+ where t.${quoteIdent(spec.field)} = any(p_ids)
168
+ $$;
169
+ revoke execute on function ${fn}(${targetType}[]) from public, anon;
170
+ grant execute on function ${fn}(${targetType}[]) to authenticated;`;
171
+ }
172
+ function closureTableSql(ctx) {
173
+ const table = qualified(ctx, CLOSURE.table);
174
+ return `-- the object graph: one row per (ancestor, descendant) within each walked resource's depth,
175
+ -- never crossing a restricted row; kept current by statement triggers on each self-parented table
176
+ create table if not exists ${table} (
177
+ resource text not null,
178
+ ancestor text not null,
179
+ descendant text not null,
180
+ depth integer not null check (depth >= 0),
181
+ primary key (resource, descendant, ancestor)
182
+ );
183
+ create index if not exists ${quoteIdent(`${CLOSURE.table}_ancestor`)} on ${table} (resource, ancestor);
184
+ alter table ${table} enable row level security;
185
+ revoke all on table ${table} from anon, authenticated, public;
186
+ grant select on table ${table} to authenticated;`;
187
+ }
188
+ function closureObjectsSql(ctx, entry, depth, tables) {
189
+ const { node } = entry;
190
+ const parent = node.parent;
191
+ if (parent === void 0) return "";
192
+ const name = node.name;
193
+ const sqlName = graphSqlName(name) ?? name;
194
+ const closure = qualified(ctx, CLOSURE.table);
195
+ const table = quoteQualified(tableFor(name, tables));
196
+ const id = quoteIdent(node.id);
197
+ const up = quoteIdent(parent.field);
198
+ const restricted = restrictedFor(node, "parent");
199
+ const stop = restricted === void 0 ? "false" : `coalesce(t.${quoteIdent(restricted)}, false)`;
200
+ const stopParent = restricted === void 0 ? "false" : `coalesce(p.${quoteIdent(restricted)}, false)`;
201
+ const refresh = qualified(ctx, `${CLOSURE.table}_${sqlName}`);
202
+ const changed = qualified(ctx, `${CLOSURE.table}_${sqlName}_changed`);
203
+ const literal = quoteLiteral(name);
204
+ const idType = idTypeOf(ctx, name);
205
+ const ancestor = idType === "text" ? "ancestor" : `ancestor::${idType}`;
206
+ const typed = (array) => idType === "text" ? array : `${array}::${idType}[]`;
207
+ const restrictedChanged = restricted === void 0 ? "" : ` or n.${quoteIdent(restricted)} is distinct from o.${quoteIdent(restricted)}`;
208
+ const trigger = (suffix) => quoteIdent(`${CLOSURE.table}_${sqlName}_${suffix}`);
209
+ 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`}
210
+ drop policy if exists ${quoteIdent(`${CLOSURE.table}_${sqlName}`)} on ${closure};
211
+ create policy ${quoteIdent(`${CLOSURE.table}_${sqlName}`)} on ${closure}
212
+ for select to authenticated
213
+ using (resource = ${literal} and ${ancestor} in (select ${qualified(ctx, graphHelper(name))}(null)));
214
+ create or replace function ${refresh}(p_ids text[])
215
+ returns void
216
+ language plpgsql
217
+ security definer
218
+ set search_path = ''
219
+ as $$
220
+ declare
221
+ v_cycle text;
222
+ v_affected text[];
223
+ begin
224
+ with recursive walk(start, next, path) as (
225
+ select t.${id}, t.${up}, array[t.${id}::text]
226
+ from ${table} t
227
+ where t.${id} = any(${typed("p_ids")})
228
+ union all
229
+ select walk.start, t.${up}, walk.path || t.${id}::text
230
+ from walk join ${table} t on t.${id} = walk.next
231
+ where not (walk.next::text = any(walk.path))
232
+ )
233
+ select walk.start::text into v_cycle
234
+ from walk
235
+ where walk.next::text = any(walk.path)
236
+ limit 1;
237
+ if v_cycle is not null then
238
+ raise exception 'permdock: % % is its own ancestor', ${literal}, v_cycle
239
+ using errcode = 'check_violation';
240
+ end if;
241
+ with recursive down(id, level) as (
242
+ select t.${id}, 0
243
+ from ${table} t
244
+ where t.${id} = any(${typed("p_ids")}) or t.${up} = any(${typed("p_ids")})
245
+ union
246
+ select t.${id}, down.level + 1
247
+ from down join ${table} t on t.${up} = down.id
248
+ where down.level < ${String(depth)}
249
+ )
250
+ select coalesce(array_agg(distinct down.id::text), '{}') into v_affected from down;
251
+ delete from ${closure} c
252
+ where c.resource = ${literal}
253
+ and (c.descendant = any(p_ids) or c.descendant = any(v_affected));
254
+ insert into ${closure} (resource, ancestor, descendant, depth)
255
+ with recursive walk(descendant, ancestor, parent, depth, stop) as (
256
+ select t.${id}::text, t.${id}, t.${up}, 0, ${stop}
257
+ from ${table} t
258
+ where t.${id} = any(${typed("v_affected")})
259
+ union all
260
+ select walk.descendant, p.${id}, p.${up}, walk.depth + 1, ${stopParent}
261
+ from walk join ${table} p on p.${id} = walk.parent
262
+ where not walk.stop and walk.depth < ${String(depth)}
263
+ )
264
+ select ${literal}, walk.ancestor::text, walk.descendant, walk.depth from walk
265
+ on conflict do nothing;
266
+ end
267
+ $$;
268
+ revoke execute on function ${refresh}(text[]) from public, anon, authenticated;
269
+ create or replace function ${changed}()
270
+ returns trigger
271
+ language plpgsql
272
+ security definer
273
+ set search_path = ''
274
+ as $$
275
+ begin
276
+ if tg_op = 'TRUNCATE' then
277
+ delete from ${closure} where resource = ${literal};
278
+ elsif tg_op = 'INSERT' then
279
+ perform ${refresh}(array(select n.${id}::text from new_rows n));
280
+ elsif tg_op = 'DELETE' then
281
+ perform ${refresh}(array(select o.${id}::text from old_rows o));
282
+ else
283
+ perform ${refresh}(array(
284
+ select n.${id}::text
285
+ from new_rows n left join old_rows o on o.${id} = n.${id}
286
+ where o.${id} is null or n.${up} is distinct from o.${up}${restrictedChanged}
287
+ union
288
+ select o.${id}::text
289
+ from old_rows o left join new_rows n on n.${id} = o.${id}
290
+ where n.${id} is null
291
+ ));
292
+ end if;
293
+ return null;
294
+ end
295
+ $$;
296
+ revoke execute on function ${changed}() from public, anon, authenticated;
297
+ drop trigger if exists ${trigger("insert")} on ${table};
298
+ create trigger ${trigger("insert")} after insert on ${table}
299
+ referencing new table as new_rows
300
+ for each statement execute function ${changed}();
301
+ drop trigger if exists ${trigger("update")} on ${table};
302
+ create trigger ${trigger("update")} after update on ${table}
303
+ referencing old table as old_rows new table as new_rows
304
+ for each statement execute function ${changed}();
305
+ drop trigger if exists ${trigger("delete")} on ${table};
306
+ create trigger ${trigger("delete")} after delete on ${table}
307
+ referencing old table as old_rows
308
+ for each statement execute function ${changed}();
309
+ drop trigger if exists ${trigger("truncate")} on ${table};
310
+ create trigger ${trigger("truncate")} after truncate on ${table}
311
+ for each statement execute function ${changed}();`;
312
+ }
313
+ /**
314
+ * One statement per walked table that fills the closure from the rows already
315
+ * stored. It is data, so it belongs in the seeds migration. `rls.seeds: 'view'`
316
+ * has no data migration, and the triggers fill the closure from later writes.
317
+ */
318
+ function closureBackfillSql(ctx, plan, tables) {
319
+ if (ctx.seeds === "view") return "";
320
+ const lines = dependencyOrder(plan).flatMap((entry) => {
321
+ const { node } = entry;
322
+ if (entry.closure === void 0 || node.parent === void 0) return [];
323
+ const sqlName = graphSqlName(node.name) ?? node.name;
324
+ const refresh = qualified(ctx, `${CLOSURE.table}_${sqlName}`);
325
+ const table = quoteQualified(tableFor(node.name, tables));
326
+ return [`select ${refresh}(array(select t.${quoteIdent(node.id)}::text from ${table} t));`];
327
+ });
328
+ return lines.length === 0 ? "" : `-- closure backfill: one pass over each walked table after its triggers exist\n${lines.join("\n")}\n`;
329
+ }
330
+ function restrictedRowsHelperSql(ctx, plan, entry, tables) {
331
+ const above = entry.restrictedAncestors;
332
+ if (above === void 0) return "";
333
+ const fn = qualified(ctx, restrictedHelper(entry.node.name));
334
+ const body = graphSqlText(restrictedRowsSql(above, {
335
+ resources: new Map([...plan].map(([name, item]) => [name, item.node])),
336
+ ...tables === void 0 ? {} : { tables },
337
+ qualify: qualifySqlTable,
338
+ idType: (resource) => idTypeOf(ctx, resource),
339
+ closure: `${helperSchema(ctx)}.${CLOSURE.table}`,
340
+ closureDepths: closureDepths(plan)
341
+ }), ctx);
342
+ 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
343
+ create or replace function ${fn}()
344
+ returns setof ${idTypeOf(ctx, entry.node.name)}
345
+ language sql
346
+ stable
347
+ security definer
348
+ cost 1000
349
+ set search_path = ''
350
+ as $$
351
+ ${body}
352
+ $$;
353
+ revoke execute on function ${fn}() from public, anon;
354
+ grant execute on function ${fn}() to authenticated;`;
355
+ }
356
+ /** Group resources a resource's asked relations name, other than itself. */
357
+ function groupTargets(entry) {
358
+ const out = /* @__PURE__ */ new Set();
359
+ for (const asked of entry.relations) for (const name of expandRelation(entry.node, asked)) {
360
+ const spec = entry.node.relations[name];
361
+ const resources = isEdgeRelation(spec) ? groupEntries(spec).map((group) => group.resource) : [];
362
+ for (const resource of resources) if (resource !== entry.node.name) out.add(resource);
363
+ }
364
+ return [...out].toSorted();
365
+ }
366
+ /**
367
+ * Plan entries by name, each after the group resources its helper calls (SQL
368
+ * function bodies are checked on create).
369
+ */
370
+ function dependencyOrder(plan) {
371
+ const out = [];
372
+ const done = /* @__PURE__ */ new Set();
373
+ const visit = (name) => {
374
+ const entry = plan.get(name);
375
+ if (entry === void 0 || done.has(name)) return;
376
+ done.add(name);
377
+ for (const target of groupTargets(entry)) visit(target);
378
+ out.push(entry);
379
+ };
380
+ for (const name of [...plan.keys()].toSorted()) visit(name);
381
+ return out;
382
+ }
383
+ function graphIdsSql(ctx, plan, tables) {
384
+ return dependencyOrder(plan).filter((entry) => entry.relations.size > 0 || entry.closure !== void 0).map((entry) => permittedSql(ctx, plan, entry, tables)).join("\n");
385
+ }
386
+ /**
387
+ * The graph preamble: `permitted_<resource>_ids` for every resource a graph
388
+ * grant reads, and the closure table with its triggers for every self-parented
389
+ * resource a grant walks. Empty when no grant is a graph grant.
390
+ */
391
+ function graphSql(ctx, plan, tables) {
392
+ if (plan.size === 0) return "";
393
+ const sqlNames = /* @__PURE__ */ new Map();
394
+ for (const name of plan.keys()) {
395
+ const helper = graphHelper(name);
396
+ const sql = graphSqlName(name) ?? name;
397
+ 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)`);
398
+ const other = sqlNames.get(sql);
399
+ if (other !== void 0) throw configError(`PermDock CLI: resources '${other}' and '${name}' both name the SQL helper ${helper}; rename one (permdock doctor PD032)`);
400
+ sqlNames.set(sql, name);
401
+ }
402
+ const entries = dependencyOrder(plan);
403
+ 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))]);
404
+ const walked = entries.filter((entry) => entry.closure !== void 0);
405
+ if (walked.length > 0) {
406
+ chunks.push(closureTableSql(ctx));
407
+ for (const entry of walked) chunks.push(closureObjectsSql(ctx, entry, entry.closure ?? 0, tables));
408
+ for (const entry of walked) {
409
+ const helper = restrictedRowsHelperSql(ctx, plan, entry, tables);
410
+ if (helper !== "") chunks.push(helper);
411
+ }
412
+ }
413
+ return `${chunks.join("\n\n")}\n`;
414
+ }
415
+ // src/cli/sql/policy-bundle.ts
416
+ /** The `format` member of a policy bundle. */
417
+ const POLICY_BUNDLE_FORMAT = "policy-bundle";
418
+ /** The table a bundle is loaded into, in the helpers schema. */
419
+ const POLICY_BUNDLE_TABLE = "permdock_policy_bundle";
420
+ /**
421
+ * The grant keys each role holds per scope, as the `permdock_role_keys` lookup
422
+ * reads them: sorted, without duplicates.
423
+ */
424
+ function roleKeyMap(rows) {
425
+ const map = {};
426
+ for (const row of rows) {
427
+ const byRole = map[row.scope] ??= {};
428
+ const keys = byRole[row.role] ??= [];
429
+ if (!keys.includes(row.grantKey)) keys.push(row.grantKey);
430
+ }
431
+ return Object.fromEntries(Object.entries(map).toSorted(([a], [b]) => byCodeUnit(a, b)).map(([scope, byRole]) => [scope, Object.fromEntries(Object.entries(byRole).toSorted(([a], [b]) => byCodeUnit(a, b)).map(([role, keys]) => [role, keys.toSorted(byCodeUnit)]))]));
432
+ }
433
+ /** `sha-256:<base64url>` of a string's UTF-8 bytes. */
434
+ function bundleDigest(text) {
435
+ return `sha-256:${createHash("sha256").update(text, "utf8").digest("base64url")}`;
436
+ }
437
+ /**
438
+ * The bundle of a policy's static grants: `policy-bundle` v1, with the rows
439
+ * sorted and deduplicated and each key in the order RFC 8785 gives it, so the
440
+ * same policy always produces the same bytes and the same hash. `rows` are the
441
+ * `role_permissions` rows; `roleKeys` is the lookup the helpers read.
442
+ */
443
+ function policyBundle(rows) {
444
+ const unique = /* @__PURE__ */ new Map();
445
+ for (const row of rows) unique.set(canonicalJson([
446
+ row.scope,
447
+ row.role,
448
+ row.grantKey,
449
+ row.permission
450
+ ]), row);
451
+ const sorted = [...unique.entries()].toSorted(([a], [b]) => byCodeUnit(a, b)).map(([, row]) => row);
452
+ const text = canonicalJson({
453
+ format: POLICY_BUNDLE_FORMAT,
454
+ v: 1,
455
+ rows: sorted.map((row) => ({
456
+ effect: row.effect,
457
+ grant_key: row.grantKey,
458
+ permission: row.permission,
459
+ role: row.role,
460
+ scope: row.scope
461
+ })),
462
+ roleKeys: roleKeyMap(sorted)
463
+ });
464
+ return {
465
+ text,
466
+ hash: bundleDigest(text)
467
+ };
468
+ }
469
+ /** The SQL expression that recomputes `bundleDigest` over a `body` column. */
470
+ const DIGEST_SQL = "'sha-256:' || translate(rtrim(encode(sha256(convert_to(body, 'UTF8')), 'base64'), '='), '+/', '-_')";
471
+ /**
472
+ * The table a bundle is loaded into. The check recomputes the digest, so a body
473
+ * stored under a hash it does not have is refused; `doc` is the parsed body the
474
+ * helpers read.
475
+ */
476
+ function bundleTableSql(ctx) {
477
+ const table = qualified(ctx, POLICY_BUNDLE_TABLE);
478
+ return `create table if not exists ${table} (
479
+ hash text primary key,
480
+ body text not null,
481
+ doc jsonb generated always as (body::jsonb) stored,
482
+ constraint permdock_policy_bundle_digest check (hash = ${DIGEST_SQL})
483
+ );
484
+ alter table ${table} enable row level security;
485
+ revoke all on table ${table} from anon, authenticated, public;`;
486
+ }
487
+ /**
488
+ * Loads a bundle: an insert keyed by its hash. A bundle that is already there
489
+ * stays as it is, so the statement is safe to run twice.
490
+ */
491
+ function bundleLoaderSql(ctx, bundle) {
492
+ return `insert into ${qualified(ctx, POLICY_BUNDLE_TABLE)} (hash, body) values
493
+ (${quoteLiteral(bundle.hash)}, ${quoteLiteral(bundle.text)})
494
+ on conflict (hash) do nothing;`;
495
+ }
496
+ // src/cli/sql/digest.ts
497
+ /**
498
+ * Adds the `sha-256:` digest of everything after the first line to that line,
499
+ * so a reader can tell a generated helpers file from an edited or older one.
500
+ * The digest covers the text a database executes, not the version of the CLI,
501
+ * so a release that writes the same helpers writes the same bytes.
502
+ */
503
+ function stampHelpers(text) {
504
+ const newline = text.indexOf("\n");
505
+ if (newline < 0) return text;
506
+ const first = text.slice(0, newline);
507
+ const rest = text.slice(newline + 1);
508
+ return `${first} ${bundleDigest(rest)}\n${rest}`;
509
+ }
510
+ // src/cli/supabase-hook/teams.ts
511
+ /** The reader `supabase.hook.teams` writes when no team scope does. */
512
+ const HOOK_TEAM_READER = "member_team_ids_for";
513
+ /**
514
+ * The `member_team_ids_of` helper the hook file writes from
515
+ * `supabase.hook.teams`, or `undefined` when there is no teams table or `rls
516
+ * generate` already writes one for a `team` or `teams` scope.
517
+ */
518
+ function hookTeamsHelper(parts) {
519
+ if (parts.hook.teams === void 0) return;
520
+ return parts.helpers.memberFor.some((scope) => isTeamScope(scope)) ? void 0 : memberOfHelper("team");
521
+ }
522
+ /**
523
+ * The `(p_user uuid, p_active text default null)` reader the hook's `team_ids`
524
+ * claim and `subject_for` call, unqualified: `member_<scope>_ids_for` of a
525
+ * `team` or `teams` scope, else the one `supabase.hook.teams` writes.
526
+ */
527
+ function hookTeamReader(parts) {
528
+ const scope = parts.helpers.memberFor.find((name) => isTeamScope(name));
529
+ return scope === void 0 ? HOOK_TEAM_READER : memberForHelper(scope);
530
+ }
531
+ /**
532
+ * `member_team_ids_for` and `member_team_ids_of` for the helpers file.
533
+ * `member_team_ids_for` takes the user and never compares it with `auth.uid()`;
534
+ * it skips disabled rows, a suspended user and a suspended tenant. The wrapper
535
+ * answers the caller only. Empty when a team scope already writes the same
536
+ * names.
537
+ */
538
+ function hookTeamReadersSql(ctx) {
539
+ const teams = ctx.hookTeams;
540
+ if (teams === void 0 || ctx.scopes.some((scope) => hasMemberOf(ctx, scope.name))) return "";
541
+ const definer = ctx.hookSecurity === "definer";
542
+ const schema = quoteIdent(helperSchema(ctx));
543
+ const reader = `${schema}.${quoteIdent(HOOK_TEAM_READER)}`;
544
+ const wrapper = `${schema}.${quoteIdent(memberOfHelper("team"))}`;
545
+ const root = ctx.scopes[0]?.name;
546
+ const tenantRow = root === void 0 ? void 0 : ctx.suspension?.scopes?.[root];
547
+ const filters = [
548
+ ...teams.disabledAt === void 0 ? [] : [` and t.${quoteIdent(teams.disabledAt)} is null`],
549
+ ...activeUserSql(ctx, "p_user").map((part) => ` and ${part}`),
550
+ ...tenantRow === void 0 || teams.tenant === void 0 ? [] : [` and ${activeRowSql(tenantRow, `t.${quoteIdent(teams.tenant)}`)}`]
551
+ ];
552
+ const order = teams.tenant === void 0 ? `t.${quoteIdent(teams.team)}` : `(p_active is not null and t.${quoteIdent(teams.tenant)}::text is not distinct from p_active) desc, t.${quoteIdent(teams.team)}`;
553
+ return `-- teams of p_user from supabase.hook.teams; ${definer ? "only the hook's owner executes it" : "execute is supabase_auth_admin only"}
554
+ create or replace function ${reader}(p_user uuid, p_active text default null)
555
+ returns setof uuid
556
+ language sql
557
+ stable
558
+ security definer
559
+ set search_path = ''
560
+ as $$
561
+ select t.${quoteIdent(teams.team)}
562
+ from ${quoteQualified(teams.table)} t
563
+ where t.${quoteIdent(teams.user)} = p_user
564
+ ${filters.join("\n")}
565
+ order by ${order}
566
+ $$;
567
+ revoke execute on function ${reader}(uuid, text) from public, anon, authenticated;${definer ? "" : `\ngrant execute on function ${reader}(uuid, text) to supabase_auth_admin;`}
568
+
569
+ -- the caller's teams only, for better-supabase's teamIdsOf
570
+ create or replace function ${wrapper}(p_user uuid)
571
+ returns setof uuid
572
+ language sql
573
+ stable
574
+ security definer
575
+ set search_path = ''
576
+ as $$
577
+ select m.id
578
+ from ${reader}(p_user, null) as m(id)
579
+ where p_user = (select ${schema}.permdock_user_id())
580
+ $$;
581
+ revoke execute on function ${wrapper}(uuid) from public, anon;
582
+ grant execute on function ${wrapper}(uuid) to authenticated;`;
583
+ }
584
+ // src/cli/rls/api-keys.ts
585
+ const API_KEY_ALLOWS = "permdock_api_key_allows";
586
+ const DEFAULTS = {
587
+ claim: "api_key",
588
+ scopes: "scopes",
589
+ tenant: "tenant",
590
+ roles: "roles"
591
+ };
592
+ function field(settings, name) {
593
+ const value = settings[name] ?? DEFAULTS[name];
594
+ 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}`);
595
+ return value;
596
+ }
597
+ function apiKeyFields(setting) {
598
+ const settings = setting === true ? {} : setting;
599
+ return {
600
+ claim: field(settings, "claim"),
601
+ scopes: field(settings, "scopes"),
602
+ tenant: field(settings, "tenant"),
603
+ roles: field(settings, "roles"),
604
+ serviceRoles: [...new Set(settings.serviceRoles ?? [])]
605
+ };
606
+ }
607
+ function apiKeysPlan(setting, declared, renamed) {
608
+ if (setting === void 0) return;
609
+ const fields = apiKeyFields(setting);
610
+ const unknown = fields.serviceRoles.filter((role) => !declared.has(role));
611
+ if (unknown.length > 0) throw configError(`PermDock CLI: rls.apiKeys.serviceRoles names roles the policy does not declare: ${unknown.join(", ")}`);
612
+ return {
613
+ ...fields,
614
+ ...Object.keys(renamed).length === 0 ? {} : { renamed }
615
+ };
616
+ }
617
+ function keyOf(ctx, plan) {
618
+ return `(select ${subjectClaimJsonSql(ctx, plan.claim)} as k) api_key`;
619
+ }
620
+ function permissionOf(plan, expr) {
621
+ return plan.renamed === void 0 ? expr : `coalesce(${quoteLiteral(JSON.stringify(plan.renamed))}::jsonb ->> ${expr}, ${expr})`;
622
+ }
623
+ function apiKeyAllowsCall(ctx, grant) {
624
+ return `${qualified(ctx, API_KEY_ALLOWS)}(${grant})`;
625
+ }
626
+ function apiKeyUnlimitedSql(key) {
627
+ return `${key} is null or ${key} = 'null'::jsonb`;
628
+ }
629
+ function apiKeyClaimSql(ctx, plan) {
630
+ return subjectClaimJsonSql(ctx, plan.claim);
631
+ }
632
+ function apiKeyAllowsSql(ctx, plan, anonExecute) {
633
+ const fn = qualified(ctx, API_KEY_ALLOWS);
634
+ const scopes = `k -> ${quoteLiteral(plan.scopes)}`;
635
+ const grants = anonExecute ? `revoke execute on function ${fn}(text) from public;
636
+ grant execute on function ${fn}(text) to anon, authenticated;` : `revoke execute on function ${fn}(text) from public, anon;
637
+ grant execute on function ${fn}(text) to authenticated;`;
638
+ 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
639
+ create or replace function ${fn}(p_grant text)
640
+ returns boolean
641
+ language sql
642
+ stable
643
+ security definer
644
+ set search_path = ''
645
+ as $$
646
+ select case
647
+ when ${apiKeyUnlimitedSql("k")} then true
648
+ when exists (
649
+ select 1 from ${qualified(ctx, "role_permissions")} rp
650
+ where rp.grant_key = p_grant and rp.effect = 'deny'
651
+ ) then true
652
+ when jsonb_typeof(k) is distinct from 'object' or jsonb_typeof(${scopes}) is distinct from 'array' then false
653
+ else exists (
654
+ select 1
655
+ from jsonb_array_elements_text(${scopes}) s(permission)
656
+ where ${permissionOf(plan, "s.permission")} = split_part(split_part(p_grant, '#', 1), '@', 1)
657
+ )
658
+ end
659
+ from ${keyOf(ctx, plan)}
660
+ $$;
661
+ ${grants}`;
662
+ }
663
+ function serviceRolesJson(plan) {
664
+ return `${quoteLiteral(JSON.stringify(plan.serviceRoles))}::jsonb`;
665
+ }
666
+ function serviceKeyRows(ctx, plan) {
667
+ const roles = `k -> ${quoteLiteral(plan.roles)}`;
668
+ return ` from ${keyOf(ctx, plan)}
669
+ cross join lateral jsonb_array_elements_text(
670
+ case jsonb_typeof(${roles}) when 'array' then ${roles} else ${serviceRolesJson(plan)} end
671
+ ) r(role)`;
672
+ }
673
+ function serviceKeyFilters(ctx, plan, root, permission) {
674
+ const tenant = `k ->> ${quoteLiteral(plan.tenant)}`;
675
+ return [
676
+ `jsonb_typeof(k) = 'object'`,
677
+ `coalesce(${subjectIdSql(ctx)}::text, '') = ''`,
678
+ `coalesce(${tenant}, '') <> ''`,
679
+ ...activeInstancesSql(ctx, root, (name) => name === root ? tenant : void 0, permission)
680
+ ];
681
+ }
682
+ function serviceKeyIdsSql(ctx, plan, root, type) {
683
+ const kind = kindFilterSql(ctx, "r.role", { value: "credential" });
684
+ const set = ctx.grantSet === true;
685
+ const filters = [
686
+ ...serviceKeyFilters(ctx, plan, root, grantPermissionSql(set ? "rp.grant_key" : "p_grant")),
687
+ ...set ? [] : ["rp.grant_key = p_grant"],
688
+ `rp.scope = ${quoteLiteral(root)}`,
689
+ ...kind === void 0 ? [] : [kind]
690
+ ];
691
+ return ` select (k ->> ${quoteLiteral(plan.tenant)})::${type}${set ? ", rp.grant_key" : ""}
692
+ ${serviceKeyRows(ctx, plan)}
693
+ join ${qualified(ctx, "role_permissions")} rp on rp.role = r.role
694
+ where ${filters.join("\n and ")}`;
695
+ }
696
+ function serviceKeyMemberSql(ctx, plan, root, type) {
697
+ return ` select distinct (k ->> ${quoteLiteral(plan.tenant)})::${type}
698
+ ${serviceKeyRows(ctx, plan)}
699
+ where ${serviceKeyFilters(ctx, plan, root).join("\n and ")}`;
700
+ }
701
+ function ceilingIdsSql(body, allows) {
702
+ return ` select ids.id
703
+ from (
704
+ ${body}
705
+ ) ids(id)
706
+ where ${allows}`;
707
+ }
708
+ function ceilingHasSql(body, allows) {
709
+ return ` select ${allows} and coalesce((
710
+ ${body}
711
+ ), false)`;
712
+ }
713
+ // src/cli/rls/capabilities.ts
714
+ /**
715
+ * The helper `--capabilities` adds: ids of one resource a link capability claim
716
+ * reaches. Part of the SQL contract.
717
+ */
718
+ const CAPABILITIES = { ids: "permdock_capability_ids" };
719
+ /**
720
+ * The `anon` branch access for a resource-scoped grant reached through a link
721
+ * capability: the row's `field` holds an id the capability claim names for
722
+ * `resource`, `role` and `permission`. Uncorrelated, so it runs once per
723
+ * statement; the column is compared as text because the claim holds text.
724
+ */
725
+ function capabilityAccessSql(ctx, field, resource, role, permission) {
726
+ const args = [
727
+ resource,
728
+ role,
729
+ permission
730
+ ].map(quoteLiteral).join(", ");
731
+ return `${quoteIdent(field)}::text in (select ${qualified(ctx, CAPABILITIES.ids)}(${args}))`;
732
+ }
733
+ function capabilitiesSql(ctx) {
734
+ if (ctx.capabilities !== true) return "";
735
+ const fn = qualified(ctx, CAPABILITIES.ids);
736
+ return `-- link capabilities: the capability claim exchangeCapability mints (role anon, short-lived)
737
+ create or replace function ${fn}(p_resource text, p_role text, p_permission text)
738
+ returns setof text
739
+ language sql
740
+ stable
741
+ set search_path = ''
742
+ as $$
743
+ select c -> 'on' ->> 'id'
744
+ from (select ${subjectClaimJsonSql(ctx, "capability")} as c) capability
745
+ where jsonb_typeof(c) = 'object'
746
+ and c ->> 'v' = '1'
747
+ and c ->> 'holder' = 'link'
748
+ and c -> 'on' ->> 'resource' = p_resource
749
+ and jsonb_typeof(c -> 'roles') = 'array'
750
+ and c -> 'roles' @> jsonb_build_array(p_role)
751
+ and (c -> 'permissions' is null or c -> 'permissions' @> jsonb_build_array(p_permission))
752
+ and jsonb_typeof(c -> 'expires_at') = 'number'
753
+ and (c ->> 'expires_at')::numeric > extract(epoch from now())
754
+ $$;
755
+ revoke execute on function ${fn}(text, text, text) from public;
756
+ grant execute on function ${fn}(text, text, text) to anon, authenticated;`;
757
+ }
758
+ // src/cli/rls/custom-role-by-id.ts
759
+ const PREFIX = "PermDock CLI";
760
+ const col = (name) => `r.${quoteIdent(name)}`;
761
+ /**
762
+ * Custom-role functions keyed by the application's role row
763
+ * (`rls.customRoleWrites.roles.primaryKey`): the tenant, scope, instance and
764
+ * name come from the row, never from the caller. The writers delegate to
765
+ * `permdock_replace_custom_role_grants` (or its trusted variant), so every
766
+ * caller and definition check applies, and keep the stored denies and includes.
767
+ * The reader returns declared allow keys only and is executable by
768
+ * `rls.trustedReaders` alone.
769
+ */
770
+ function customRoleByIdSql(ctx, trustedReaders) {
771
+ const custom = ctx.customRoles;
772
+ const roles = custom?.table;
773
+ const root = ctx.scopes[0]?.name;
774
+ if (custom === void 0 || roles?.primaryKey === void 0 || ctx.authorize !== "database" || root === void 0) return "";
775
+ const pk = roles.primaryKey;
776
+ if (pk === "") throw configError(`${PREFIX}: rls.customRoleWrites.roles.primaryKey names no column`);
777
+ const leveled = custom.levels === true;
778
+ const tenantType = tenantTypeOf(ctx);
779
+ const table = quoteQualified(roles.table);
780
+ const idType = `${table}.${quoteIdent(pk)}%type`;
781
+ const perms = qualified(ctx, CUSTOM_ROLES.permissions);
782
+ const includes = qualified(ctx, CUSTOM_ROLES.includes);
783
+ const replace = qualified(ctx, CUSTOM_ROLES.replace);
784
+ const trustedReplace = qualified(ctx, CUSTOM_ROLES.trustedReplace);
785
+ const byId = qualified(ctx, CUSTOM_ROLES.replaceById);
786
+ const trustedById = qualified(ctx, CUSTOM_ROLES.trustedReplaceById);
787
+ const reader = qualified(ctx, CUSTOM_ROLES.trustedReadById);
788
+ const renames = Object.entries(custom.renamed ?? {}).toSorted(byKey);
789
+ const current = (expr) => currentKeyExpr(renames, expr);
790
+ const declaredKeys = sqlTextArray(custom.permissions ?? []);
791
+ const declaredRoles = sqlTextArray(custom.declared);
792
+ const tenant = roles.tenant === void 0 ? `null::${tenantType}` : `${col(roles.tenant)}::${tenantType}`;
793
+ const scope = rolesTableScope(roles, tenant, root, col);
794
+ 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`;
795
+ const skipped = roles.skip === void 0 || roles.tenant === void 0 ? "false" : `(${tenant} is not null and coalesce(${col(roles.skip)}, false))`;
796
+ const match = "(v_tenant is null and c.tenant_id is null or c.tenant_id = v_tenant) and c.scope = v_scope and (v_scope_id is null and c.scope_id is null or c.scope_id = v_scope_id) and c.role = v_key";
797
+ const audit = custom.audit;
798
+ const auditCall = audit === void 0 ? "" : `
799
+ perform ${quoteQualified(audit.function)}(${[
800
+ "event_type => 'permdock.custom_role.replaced'",
801
+ "target_type => 'role'",
802
+ "record_id => p_role_id::text",
803
+ "tenant => v_tenant",
804
+ "metadata => jsonb_build_object('operation', 'replace', 'role', v_key, 'permissions', p_permissions)",
805
+ ...Object.entries(audit.args ?? {}).toSorted(byKey).map(([name, value]) => `${quoteIdent(name)} => ${quoteLiteral(value)}`)
806
+ ].join(", ")});`;
807
+ const body = (write) => `declare
808
+ v_tenant ${tenantType};
809
+ v_scope text;
810
+ v_scope_id text;
811
+ v_key text;
812
+ v_skipped boolean;
813
+ v_deny text[];
814
+ v_include text[];
815
+ begin
816
+ select ${tenant}, ${scope}, ${scopeId}, ${col(roles.key)}::text, ${skipped}
817
+ into v_tenant, v_scope, v_scope_id, v_key, v_skipped
818
+ from ${table} r
819
+ where ${col(pk)} = p_role_id;
820
+ if not found then
821
+ ${raiseSql(" ", "P0002", "'permdock: no role row has id ' || coalesce(p_role_id::text, 'null')", "unknown-role")}
822
+ end if;
823
+ if v_skipped or v_key = any(${declaredRoles}) then
824
+ ${raiseSql(" ", "22023", "'permdock: ' || coalesce(v_key, 'null') || ' is a declared role, not a custom role'", "declared-role")}
825
+ end if;
826
+ select array_agg(c.permission) into v_deny
827
+ from ${perms} c
828
+ where ${match} and c.effect = 'deny';
829
+ select array_agg(c.include_role) into v_include
830
+ from ${includes} c
831
+ where ${match};
832
+ perform ${write}(v_tenant, v_scope, v_scope_id, v_key, p_permissions, v_deny, v_include);${auditCall}
833
+ end;`;
834
+ const writer = (comment, name, write, member) => `-- ${comment}
835
+ create or replace function ${name}(p_role_id ${idType}, p_permissions text[])
836
+ returns void
837
+ language plpgsql
838
+ volatile
839
+ security definer
840
+ set search_path = ''
841
+ as $$
842
+ ${body(write)}
843
+ $$;
844
+ ${member ? `revoke execute on function ${name}(${idType}, text[]) from public, anon;
845
+ grant execute on function ${name}(${idType}, text[]) to authenticated;` : `revoke execute on function ${name}(${idType}, text[]) from public, anon, authenticated;`}`;
846
+ const readerEntry = leveled ? `${current("c.permission")} || coalesce('@' || c.level, '')` : current("c.permission");
847
+ const readerGrant = trustedReaders === void 0 || trustedReaders.length === 0 ? "" : `\n${trustedReaderGrants(ctx, `${reader}(text[], ${tenantType})`, trustedReaders)}`;
848
+ 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)}
849
+
850
+ ${writer("save a custom role by its row id for a trusted caller: the definition checks without the caller checks", trustedById, trustedReplace, false)}
851
+
852
+ -- 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
853
+ create or replace function ${reader}(p_role_ids text[], p_tenant ${tenantType} default null)
854
+ returns table (role_id text, permission text)
855
+ language plpgsql
856
+ stable
857
+ security definer
858
+ set search_path = ''
859
+ as $$
860
+ begin
861
+ if p_tenant is not null and exists (
862
+ select 1 from ${table} r
863
+ where ${col(pk)}::text = any(p_role_ids) and ${tenant} is distinct from p_tenant
864
+ ) then
865
+ ${raiseSql(" ", "42501", "'permdock: a role id belongs to another tenant than ' || p_tenant::text", "not-member")}
866
+ end if;
867
+ return query
868
+ select distinct v.role_id, ${readerEntry}
869
+ from (
870
+ select ${col(pk)}::text as role_id, ${tenant} as tenant_id, ${scope} as scope, ${scopeId} as scope_id, ${col(roles.key)}::text as role
871
+ from ${table} r
872
+ where ${col(pk)}::text = any(p_role_ids)
873
+ and not ${skipped}
874
+ and not (${col(roles.key)}::text = any(${declaredRoles}))
875
+ ) v
876
+ join ${perms} c
877
+ on (v.tenant_id is null and c.tenant_id is null or c.tenant_id = v.tenant_id)
878
+ and c.scope = v.scope
879
+ and (v.scope_id is null and c.scope_id is null or c.scope_id = v.scope_id)
880
+ and c.role = v.role
881
+ where c.effect = 'allow'
882
+ and ${current("c.permission")} = any(${declaredKeys})
883
+ order by 1, 2;
884
+ end;
885
+ $$;
886
+ revoke execute on function ${reader}(text[], ${tenantType}) from public, anon, authenticated;${readerGrant}`;
887
+ }
888
+ // src/cli/rls/custom-role-cascade.ts
889
+ /** `row.column`, for a trigger's `old` or `new`. */
890
+ function rowColumn(row, name) {
891
+ return `${row}.${quoteIdent(name)}`;
892
+ }
893
+ /** The custom-role rows of the role a trigger's `v_<prefix>_*` variables name. */
894
+ function cascadeMatch(prefix) {
895
+ return `(v_${prefix}_tenant is null and c.tenant_id is null or c.tenant_id = v_${prefix}_tenant) and c.scope = v_${prefix}_scope and (v_${prefix}_id is null and c.scope_id is null or c.scope_id = v_${prefix}_id) and c.role = v_${prefix}_key`;
896
+ }
897
+ /**
898
+ * The trigger on the application's roles table (`rls.customRoleWrites.roles`):
899
+ * a rename, a move to another tenant, scope or instance, or a delete of a
900
+ * custom role's row carries its grants and includes along. A signed-in caller
901
+ * passes the write functions' checks unless the transaction set
902
+ * `permdock.sync`: authority over the stored definition where it was, and,
903
+ * after a move, membership and authority where it lands and entries inside that
904
+ * scope's ceiling. Other paths (a migration, a job, a nested trigger) move the
905
+ * rows as the function owner.
906
+ */
907
+ function customRoleCascadeSql(ctx) {
908
+ const custom = ctx.customRoles;
909
+ const table = custom?.table;
910
+ const root = ctx.scopes[0]?.name;
911
+ if (custom === void 0 || table === void 0 || root === void 0) return "";
912
+ const tenantType = tenantTypeOf(ctx);
913
+ const perms = qualified(ctx, CUSTOM_ROLES.permissions);
914
+ const includes = qualified(ctx, CUSTOM_ROLES.includes);
915
+ const fn = qualified(ctx, CUSTOM_ROLES.cascade);
916
+ const target = quoteTable(qualifySqlTable(table.table));
917
+ const tenant = (row) => table.tenant === void 0 ? `null::${tenantType}` : `${rowColumn(row, table.tenant)}::${tenantType}`;
918
+ const scope = (row) => rolesTableScope(table, tenant(row), root, (name) => rowColumn(row, name));
919
+ 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`;
920
+ const skipped = (row) => table.skip === void 0 || table.tenant === void 0 ? "false" : `(${tenant(row)} is not null and coalesce(${rowColumn(row, table.skip)}, false))`;
921
+ const guard = qualified(ctx, CUSTOM_ROLES.guard);
922
+ const entries = qualified(ctx, CUSTOM_ROLES.entries);
923
+ const allowEntryOf = `c.${allowEntry(ctx)}`;
924
+ return `-- the application's roles table: renames, moves and deletes of a custom role carry its grants and includes
925
+ create or replace function ${fn}()
926
+ returns trigger
927
+ language plpgsql
928
+ volatile
929
+ security definer
930
+ set search_path = ''
931
+ as $$
932
+ declare
933
+ v_old_tenant ${tenantType} := ${tenant("old")};
934
+ v_old_scope text := ${scope("old")};
935
+ v_old_id text := ${id("old")};
936
+ v_old_key text := ${rowColumn("old", table.key)}::text;
937
+ v_new_tenant ${tenantType};
938
+ v_new_scope text;
939
+ v_new_id text;
940
+ v_new_key text;
941
+ v_checked boolean := ${signedIn(ctx)} and current_setting('permdock.sync', true) is distinct from 'on';
942
+ v_allow text[];
943
+ v_deny text[];
944
+ v_include text[];
945
+ begin
946
+ if ${skipped("old")} then
947
+ return null;
948
+ end if;
949
+ if tg_op = 'UPDATE' and not ${skipped("new")} then
950
+ v_new_tenant := ${tenant("new")};
951
+ v_new_scope := ${scope("new")};
952
+ v_new_id := ${id("new")};
953
+ v_new_key := ${rowColumn("new", table.key)}::text;
954
+ if v_new_key = v_old_key
955
+ and v_new_tenant is not distinct from v_old_tenant
956
+ and v_new_scope = v_old_scope
957
+ and v_new_id is not distinct from v_old_id then
958
+ return null;
959
+ end if;
960
+ end if;
961
+ if not exists (select 1 from ${perms} c where ${cascadeMatch("old")})
962
+ and not exists (select 1 from ${includes} c where ${cascadeMatch("old")}) then
963
+ return null;
964
+ end if;
965
+ if v_checked then
966
+ perform ${guard}(v_old_tenant, v_old_scope, v_old_id, v_old_key);
967
+ end if;
968
+ if v_new_key is null then
969
+ perform set_config('permdock.sync', 'on', true);
970
+ perform ${qualified(ctx, CUSTOM_ROLES.trustedRemove)}(v_old_tenant, v_old_scope, v_old_id, v_old_key);
971
+ delete from ${includes} c
972
+ where c.include_role = v_old_key
973
+ and not (v_old_key = any(${sqlTextArray(custom.declared)}));
974
+ perform set_config('permdock.sync', '', true);
975
+ return null;
976
+ end if;
977
+ if exists (select 1 from ${perms} c where ${cascadeMatch("new")})
978
+ or exists (select 1 from ${includes} c where ${cascadeMatch("new")}) then
979
+ ${raiseSql(" ", "22023", `'permdock: ' || v_new_key || ' already has grants'`, "role-exists")}
980
+ end if;
981
+ 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")};
982
+ 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")};
983
+ if v_checked then
984
+ perform ${guard}(v_new_tenant, v_new_scope, v_new_id, v_new_key);
985
+ select array_agg(${allowEntryOf}) filter (where c.effect = 'allow'),
986
+ array_agg(c.permission) filter (where c.effect = 'deny')
987
+ into v_allow, v_deny
988
+ from ${perms} c
989
+ where ${cascadeMatch("new")};
990
+ select array_agg(c.include_role) into v_include
991
+ from ${includes} c
992
+ where ${cascadeMatch("new")};
993
+ perform ${entries}(v_new_scope, v_allow, v_deny, v_include);
994
+ end if;
995
+ return null;
996
+ end;
997
+ $$;
998
+ revoke execute on function ${fn}() from public, anon, authenticated;
999
+ create or replace trigger "permdock_custom_role_cascade"
1000
+ after update or delete on ${target}
1001
+ for each row execute function ${fn}();
1002
+ `;
1003
+ }
1004
+ // src/cli/rls/custom-role-compiled.ts
1005
+ /** The event name of a tenant's custom-role version message. */
1006
+ const CUSTOM_ROLES_EVENT = "custom_roles";
1007
+ /** `authz-tenant:<tenant>`, the topic one message per edited tenant goes to. */
1008
+ const CUSTOM_ROLES_TENANT_TOPIC = "authz-tenant:";
1009
+ function tenantMatch(alias) {
1010
+ return `(p_tenant is null and ${alias}.tenant_id is null or ${alias}.tenant_id = p_tenant)`;
1011
+ }
1012
+ function roleMatch(alias) {
1013
+ return `${tenantMatch(alias)} and ${alias}.scope = p_scope and ${alias}.role = p_role`;
1014
+ }
1015
+ function trigger(table, suffix, event, fn) {
1016
+ const name = `permdock_custom_roles_compile_${suffix}_${event}`;
1017
+ return `drop trigger if exists "${name}" on ${table};
1018
+ create trigger "${name}"
1019
+ after ${event} on ${table}
1020
+ ${event === "insert" ? "referencing new table as permdock_new" : event === "delete" ? "referencing old table as permdock_old" : "referencing old table as permdock_old new table as permdock_new"}
1021
+ for each statement execute function ${fn}();`;
1022
+ }
1023
+ function touched(source) {
1024
+ return `select array_agg(t.tenant_id), array_agg(t.scope), array_agg(t.role) from (select distinct tenant_id, scope, role from ${source}) t`;
1025
+ }
1026
+ /**
1027
+ * `database` mode: the tables a custom-role edit maintains from statement
1028
+ * triggers, so no policy or read resolves a role at query time.
1029
+ *
1030
+ * - `custom_role_version (tenant_id, version)`: one counter per tenant, and one
1031
+ * row with a null tenant for the shared and platform roles. One edit
1032
+ * statement bumps each tenant it touched once.
1033
+ * - `custom_role_compiled`: one row per stored role (and per instance it is
1034
+ * pinned to), holding the grant keys `permdock_custom_keys` resolves, the
1035
+ * grants in `CustomRole` form and the includes.
1036
+ *
1037
+ * A pinned row merges the rows with no instance, so a probe reads the pinned
1038
+ * row when there is one and the unpinned row otherwise.
1039
+ */
1040
+ function customRoleCompiledSql(ctx) {
1041
+ const custom = ctx.customRoles;
1042
+ if (custom === void 0 || ctx.authorize !== "database") return "";
1043
+ const tenantType = tenantTypeOf(ctx);
1044
+ const perms = qualified(ctx, CUSTOM_ROLES.permissions);
1045
+ const includes = qualified(ctx, CUSTOM_ROLES.includes);
1046
+ const compiled = qualified(ctx, CUSTOM_ROLES.compiled);
1047
+ const versions = qualified(ctx, CUSTOM_ROLES.versions);
1048
+ const keys = qualified(ctx, CUSTOM_ROLES.keys);
1049
+ const compile = qualified(ctx, CUSTOM_ROLES.compile);
1050
+ const compileFor = qualified(ctx, CUSTOM_ROLES.compileFor);
1051
+ const recompile = qualified(ctx, CUSTOM_ROLES.recompile);
1052
+ const entry = `c.${allowEntry(ctx)}`;
1053
+ const broadcast = custom.broadcast;
1054
+ const send = broadcast === void 0 ? "" : `
1055
+ if to_regprocedure('realtime.send(jsonb, text, text, boolean)') is not null then
1056
+ for r in
1057
+ select v.tenant_id, v.version from ${versions} v
1058
+ where v.tenant_id in (select u from unnest(p_owners) u)
1059
+ or (v.tenant_id is null and exists (select 1 from unnest(p_owners) u where u is null))
1060
+ loop
1061
+ execute pg_catalog.format('select %s($1, $2, $3, true)', pg_catalog.to_regprocedure('realtime.send(jsonb, text, text, boolean)')::oid::regproc) using
1062
+ jsonb_build_object('tenant', r.tenant_id, 'version', r.version),
1063
+ ${quoteLiteral(CUSTOM_ROLES_EVENT)}::text,
1064
+ (case when r.tenant_id is null then ${quoteLiteral(broadcast.topic)} else ${quoteLiteral(CUSTOM_ROLES_TENANT_TOPIC)} || r.tenant_id::text end)::text;
1065
+ end loop;
1066
+ end if;`;
1067
+ const handler = (event) => {
1068
+ const fn = qualified(ctx, `${CUSTOM_ROLES.compileStatement}_${event}`);
1069
+ const body = event === "insert" ? touched("permdock_new") : event === "delete" ? touched("permdock_old") : `select array_agg(t.tenant_id), array_agg(t.scope), array_agg(t.role)
1070
+ from (select tenant_id, scope, role from permdock_old union select tenant_id, scope, role from permdock_new) t`;
1071
+ return `create or replace function ${fn}()
1072
+ returns trigger
1073
+ language plpgsql
1074
+ volatile
1075
+ security definer
1076
+ set search_path = ''
1077
+ as $$
1078
+ declare
1079
+ v_owners ${tenantType}[];
1080
+ v_scopes text[];
1081
+ v_roles text[];
1082
+ begin
1083
+ ${body}
1084
+ into v_owners, v_scopes, v_roles;
1085
+ perform ${compileFor}(v_owners, v_scopes, v_roles);
1086
+ return null;
1087
+ end;
1088
+ $$;
1089
+ revoke execute on function ${fn}() from public, anon, authenticated;`;
1090
+ };
1091
+ return `-- the compiled custom roles: the keys of each stored role, written when it is saved and read by the policies and by subject_for
1092
+ create table if not exists ${versions} (
1093
+ tenant_id ${tenantType},
1094
+ version bigint not null default 0
1095
+ );
1096
+ -- the row with no tenant counts the shared and platform roles
1097
+ create unique index if not exists ${CUSTOM_ROLES.versions}_key on ${versions} (tenant_id) nulls not distinct;
1098
+ alter table ${versions} enable row level security;
1099
+ revoke all on table ${versions} from anon, authenticated, public;
1100
+
1101
+ create table if not exists ${compiled} (
1102
+ tenant_id ${tenantType},
1103
+ scope text not null,
1104
+ scope_id text,
1105
+ role text not null,
1106
+ grant_keys text[] not null default '{}',
1107
+ grants jsonb not null default '[]'::jsonb,
1108
+ includes text[] not null default '{}',
1109
+ version bigint not null default 0
1110
+ );
1111
+ create unique index if not exists ${CUSTOM_ROLES.compiled}_role_key on ${compiled} (tenant_id, scope, role, scope_id) nulls not distinct;
1112
+ alter table ${compiled} enable row level security;
1113
+ revoke all on table ${compiled} from anon, authenticated, public;
1114
+
1115
+ -- one stored role, compiled: a row per instance it is pinned to, each merged with the rows that name no instance
1116
+ create or replace function ${compile}(p_tenant ${tenantType}, p_scope text, p_role text, p_version bigint)
1117
+ returns void
1118
+ language plpgsql
1119
+ volatile
1120
+ security definer
1121
+ set search_path = ''
1122
+ as $$
1123
+ begin
1124
+ delete from ${compiled} c
1125
+ where (p_tenant is null and c.tenant_id is null or c.tenant_id = p_tenant) and c.scope = p_scope and c.role = p_role;
1126
+ insert into ${compiled} (tenant_id, scope, scope_id, role, grant_keys, grants, includes, version)
1127
+ select p_tenant, p_scope, pin.scope_id, p_role,
1128
+ array(select k from ${keys}(e.allow, e.deny, e.incl, p_scope) k order by 1),
1129
+ own.grants, own.incl, p_version
1130
+ from (
1131
+ select c.scope_id from ${perms} c where ${roleMatch("c")}
1132
+ union
1133
+ select c.scope_id from ${includes} c where ${roleMatch("c")}
1134
+ ) pin
1135
+ cross join lateral (
1136
+ select
1137
+ coalesce(array_agg(${entry} order by ${entry}) filter (where c.effect = 'allow'), '{}'::text[]) as allow,
1138
+ coalesce(array_agg(c.permission order by c.permission) filter (where c.effect = 'deny'), '{}'::text[]) as deny,
1139
+ array(
1140
+ select i.include_role from ${includes} i
1141
+ where ${roleMatch("i")} and (i.scope_id is null or i.scope_id = pin.scope_id)
1142
+ order by 1
1143
+ ) as incl
1144
+ from ${perms} c
1145
+ where ${roleMatch("c")} and (c.scope_id is null or c.scope_id = pin.scope_id)
1146
+ ) e
1147
+ cross join lateral (
1148
+ select
1149
+ coalesce(jsonb_agg(jsonb_strip_nulls(jsonb_build_object(
1150
+ 'permission', c.permission, 'effect', c.effect, 'level', to_jsonb(c) ->> 'level'
1151
+ )) order by c.permission, c.effect), '[]'::jsonb) as grants,
1152
+ array(
1153
+ select i.include_role from ${includes} i
1154
+ where ${roleMatch("i")} and i.scope_id is not distinct from pin.scope_id
1155
+ order by 1
1156
+ ) as incl
1157
+ from ${perms} c
1158
+ where ${roleMatch("c")} and c.scope_id is not distinct from pin.scope_id
1159
+ ) own;
1160
+ end;
1161
+ $$;
1162
+ revoke execute on function ${compile}(${tenantType}, text, text, bigint) from public, anon, authenticated;
1163
+
1164
+ -- the roles a statement touched: one version bump per tenant, then each role compiled at the new version
1165
+ create or replace function ${compileFor}(p_owners ${tenantType}[], p_scopes text[], p_roles text[])
1166
+ returns void
1167
+ language plpgsql
1168
+ volatile
1169
+ security definer
1170
+ set search_path = ''
1171
+ as $$
1172
+ declare
1173
+ r record;
1174
+ begin
1175
+ insert into ${versions} as v (tenant_id, version)
1176
+ select distinct u, 1 from unnest(p_owners) u
1177
+ on conflict (tenant_id) do update set version = v.version + 1;
1178
+ for r in
1179
+ select distinct u.own_id, u.scope, u.role, (
1180
+ select v.version from ${versions} v where v.tenant_id is not distinct from u.own_id
1181
+ ) as version
1182
+ from unnest(p_owners, p_scopes, p_roles) u(own_id, scope, role)
1183
+ loop
1184
+ perform ${compile}(r.own_id, r.scope, r.role, r.version);
1185
+ end loop;${send}
1186
+ end;
1187
+ $$;
1188
+ revoke execute on function ${compileFor}(${tenantType}[], text[], text[]) from public, anon, authenticated;
1189
+
1190
+ ${handler("insert")}
1191
+
1192
+ ${handler("update")}
1193
+
1194
+ ${handler("delete")}
1195
+
1196
+ ${[perms, includes].map((table, index) => [
1197
+ "insert",
1198
+ "update",
1199
+ "delete"
1200
+ ].map((event) => trigger(table, index === 0 ? "permissions" : "includes", event, qualified(ctx, `${CUSTOM_ROLES.compileStatement}_${event}`))).join("\n")).join("\n")}
1201
+
1202
+ -- compiles every stored role again, for the first run after an upgrade or a change to the declared roles
1203
+ create or replace function ${recompile}()
1204
+ returns void
1205
+ language plpgsql
1206
+ volatile
1207
+ security definer
1208
+ set search_path = ''
1209
+ as $$
1210
+ begin
1211
+ delete from ${compiled};
1212
+ perform ${compileFor}(
1213
+ array(select t.tenant_id from (select distinct tenant_id, scope, role from ${perms} union select tenant_id, scope, role from ${includes}) t order by t.tenant_id, t.scope, t.role),
1214
+ array(select t.scope from (select distinct tenant_id, scope, role from ${perms} union select tenant_id, scope, role from ${includes}) t order by t.tenant_id, t.scope, t.role),
1215
+ array(select t.role from (select distinct tenant_id, scope, role from ${perms} union select tenant_id, scope, role from ${includes}) t order by t.tenant_id, t.scope, t.role)
1216
+ );
1217
+ end;
1218
+ $$;
1219
+ revoke execute on function ${recompile}() from public, anon, authenticated;`;
1220
+ }
1221
+ // src/cli/rls/custom-role-guard.ts
1222
+ /** A column of the roles-table row a trigger sees as `new`. */
1223
+ function column(name) {
1224
+ return `new.${quoteIdent(name)}`;
1225
+ }
1226
+ /**
1227
+ * The trigger on the application's roles table (`rls.customRoleWrites.roles`)
1228
+ * that refuses a tenant row named like a declared role (`declared-role`) or
1229
+ * like a shared custom role (`name-taken`). A row the `skip` column marks is a
1230
+ * system role of the tenant and passes. Empty without a tenant column: then no
1231
+ * row is a tenant row.
1232
+ */
1233
+ function customRoleNameGuardSql(ctx) {
1234
+ const custom = ctx.customRoles;
1235
+ const table = custom?.table;
1236
+ const root = ctx.scopes[0]?.name;
1237
+ if (custom === void 0 || table?.tenant === void 0 || root === void 0) return "";
1238
+ const tenant = `${column(table.tenant)}::${tenantTypeOf(ctx)}`;
1239
+ const skipped = table.skip === void 0 ? "false" : `coalesce(${column(table.skip)}, false)`;
1240
+ const fn = qualified(ctx, CUSTOM_ROLES.nameGuard);
1241
+ const target = quoteTable(qualifySqlTable(table.table));
1242
+ const key = `${column(table.key)}::text`;
1243
+ const scope = rolesTableScope(table, tenant, root, column);
1244
+ return `-- the application's roles table: a tenant row cannot take the name of a declared or a shared role
1245
+ create or replace function ${fn}()
1246
+ returns trigger
1247
+ language plpgsql
1248
+ volatile
1249
+ security definer
1250
+ set search_path = ''
1251
+ as $$
1252
+ begin
1253
+ if ${tenant} is null or ${skipped} then
1254
+ return new;
1255
+ end if;
1256
+ if ${key} = any(${sqlTextArray(custom.declared)}) then
1257
+ ${raiseSql(" ", "22023", `'permdock: ' || ${key} || ' is a declared role'`, "declared-role")}
1258
+ end if;
1259
+ if ${qualified(ctx, CUSTOM_ROLES.shared)}(${scope}, ${key}) then
1260
+ ${raiseSql(" ", "22023", `'permdock: ' || ${key} || ' is a shared role'`, "name-taken")}
1261
+ end if;
1262
+ return new;
1263
+ end;
1264
+ $$;
1265
+ revoke execute on function ${fn}() from public, anon, authenticated;
1266
+ drop trigger if exists "permdock_custom_role_name_guard" on ${target};
1267
+ create trigger "permdock_custom_role_name_guard"
1268
+ before insert or update on ${target}
1269
+ for each row execute function ${fn}();
1270
+ `;
1271
+ }
1272
+ // src/cli/rls/custom-role-writes.ts
1273
+ function callerFunctionsSql(ctx, custom, root, levelReach, forUser) {
1274
+ const leveled = custom.levels === true;
1275
+ const tenantType = tenantTypeOf(ctx);
1276
+ const volatility = "volatile";
1277
+ const rp = qualified(ctx, "role_permissions");
1278
+ const keys = qualified(ctx, CUSTOM_ROLES.keys);
1279
+ const perms = qualified(ctx, CUSTOM_ROLES.permissions);
1280
+ const includes = qualified(ctx, CUSTOM_ROLES.includes);
1281
+ const shape = qualified(ctx, CUSTOM_ROLES.shape);
1282
+ const beyond = qualified(ctx, forUser ? CUSTOM_ROLES.beyondFor : CUSTOM_ROLES.beyond);
1283
+ const guard = qualified(ctx, forUser ? CUSTOM_ROLES.guardFor : CUSTOM_ROLES.guard);
1284
+ const user = forUser ? "p_user" : subjectIdSql(ctx);
1285
+ const userParam = forUser ? "p_user uuid, " : "";
1286
+ const userArg = forUser ? "uuid, " : "";
1287
+ const userCall = forUser ? "p_user, " : "";
1288
+ const has = (key) => forUser ? `${qualified(ctx, HELPERS.hasFor)}(p_user, ${key})` : `${qualified(ctx, HELPERS.has)}(${key})`;
1289
+ const ids = (helper, arg) => `(select x::text from ${qualified(ctx, helper)}(${arg}) x)`;
1290
+ const permitted = (scope, key) => forUser ? ids(permittedForHelper(scope), `p_user, ${key}`) : ids(permittedIdsHelper(scope), key);
1291
+ const members = (scope) => forUser ? ids(memberForHelper(scope), "p_user") : ids(memberIdsHelper(scope), "");
1292
+ const heldKey = (key) => `(${has(key)}
1293
+ or (p_scope <> 'global'
1294
+ and (p_tenant::text in ${permitted(root, key)}
1295
+ or ${perScope(ctx, (scope) => scope === root ? "false" : `p_scope_id in ${permitted(scope, key)}`)})))`;
1296
+ const holdsAny = (permissions, held) => permissions.length === 0 ? "false" : `exists (
1297
+ select 1 from ${rp} rp
1298
+ where rp.effect = 'allow'
1299
+ and rp.permission = any(${sqlTextArray(permissions)})
1300
+ and ${held("rp.grant_key")}
1301
+ )`;
1302
+ const manageKeys = custom.manage ?? [];
1303
+ const manage = holdsAny(manageKeys, heldKey);
1304
+ const platform = holdsAny(manageKeys, has);
1305
+ const requires = custom.requires === void 0 ? "" : `
1306
+ if not ${holdsAny(custom.requires, heldKey)} then
1307
+ ${raiseSql(" ", "42501", `'permdock: the caller may not manage roles in ' || coalesce(p_tenant::text, 'the platform')`, "manage-roles")}
1308
+ end if;`;
1309
+ const reachRows = levelReach.map(([grantKey, level]) => `(${quoteLiteral(grantKey)}, ${quoteLiteral(level)})`).join(", ");
1310
+ const levelCheck = leveled && reachRows !== "" ? `
1311
+ or exists (
1312
+ select 1
1313
+ from reach x
1314
+ where x.grant_key = r.grant_key
1315
+ and not exists (
1316
+ select 1 from held h
1317
+ join reach o on o.grant_key = h.grant_key
1318
+ where h.permission = r.permission and o.level = x.level
1319
+ )
1320
+ )` : "";
1321
+ const reachCte = leveled && reachRows !== "" ? `,
1322
+ reach (grant_key, level) as (values ${reachRows})` : "";
1323
+ const match = `${storedTenant(ctx)} and c.scope = p_scope and (p_scope_id is null and c.scope_id is null or c.scope_id = p_scope_id)`;
1324
+ const memberOf = `p_tenant::text in ${members(root)}
1325
+ or ${perScope(ctx, (scope) => scope === root ? "false" : `p_scope_id in ${members(scope)}`)}`;
1326
+ return {
1327
+ beyond: `-- custom-role writes: the permission keys of a definition the caller may not hand out in the tenant, as assignablePermissions computes them
1328
+ 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[])
1329
+ returns setof text
1330
+ language plpgsql
1331
+ ${volatility}
1332
+ security definer
1333
+ set search_path = ''
1334
+ as $$
1335
+ begin
1336
+ if ${manage} then
1337
+ return;
1338
+ end if;
1339
+ return query
1340
+ with resolved as (
1341
+ select distinct rp.permission, k.key as grant_key
1342
+ from ${keys}(p_allow, p_deny, p_include, p_scope) k(key)
1343
+ join ${rp} rp on rp.grant_key = k.key and rp.effect = 'allow'
1344
+ ),
1345
+ held as (
1346
+ select distinct rp.permission, rp.grant_key
1347
+ from ${rp} rp
1348
+ where rp.effect = 'allow'
1349
+ and rp.permission in (select r.permission from resolved r)
1350
+ and ${heldKey("rp.grant_key")}
1351
+ )${reachCte}
1352
+ select distinct r.permission
1353
+ from resolved r
1354
+ where not exists (select 1 from held h where h.permission = r.permission)${levelCheck};
1355
+ end;
1356
+ $$;
1357
+ revoke execute on function ${beyond}(${userArg}${tenantType}, text, text, text[], text[], text[]) from public, anon, authenticated;`,
1358
+ 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
1359
+ create or replace function ${guard}(${userParam}p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text)
1360
+ returns void
1361
+ language plpgsql
1362
+ ${volatility}
1363
+ security definer
1364
+ set search_path = ''
1365
+ as $$
1366
+ declare
1367
+ v_allow text[];
1368
+ v_deny text[];
1369
+ v_include text[];
1370
+ v_beyond text;
1371
+ begin
1372
+ perform ${shape}(p_tenant, p_scope, p_scope_id, p_role);
1373
+ if not (${signedIn(ctx, user)} and (
1374
+ ${platform}
1375
+ or (p_scope <> 'global' and coalesce(${memberOf}, false))
1376
+ )) then
1377
+ ${raiseSql(" ", "42501", `'permdock: the caller is not a member of ' || coalesce(p_tenant::text, 'the platform')`, "not-member")}
1378
+ end if;${requires}
1379
+ select array_agg(${allowEntry(ctx)}) filter (where c.effect = 'allow'),
1380
+ array_agg(c.permission) filter (where c.effect = 'deny')
1381
+ into v_allow, v_deny
1382
+ from ${perms} c
1383
+ where ${match} and c.role = p_role;
1384
+ select array_agg(c.include_role) into v_include
1385
+ from ${includes} c
1386
+ where ${match} and c.role = p_role;
1387
+ select string_agg(b, ', ' order by b) into v_beyond
1388
+ from ${beyond}(${userCall}p_tenant, p_scope, p_scope_id, v_allow, v_deny, v_include) b;
1389
+ if v_beyond is not null then
1390
+ ${raiseSql(" ", "42501", `'permdock: ' || p_role || ' allows ' || v_beyond || ', which the caller may not hand out'`, "not-assignable-by")}
1391
+ end if;
1392
+ end;
1393
+ $$;
1394
+ revoke execute on function ${guard}(${userArg}${tenantType}, text, text, text) from public, anon, authenticated;`
1395
+ };
1396
+ }
1397
+ /**
1398
+ * The functions an application calls to save, rename and delete a custom role
1399
+ * in \`database\` mode, with the rules of \`validateCustomRole\` and
1400
+ * \`assignablePermissions\`: entries inside the ceiling of the role's scope,
1401
+ * includes naming declared roles, and only permissions and levels the caller
1402
+ * may hand out, for the new definition and the stored one alike. A platform
1403
+ * custom role (\`p_scope = 'global'\`, no tenant) and a shared custom role (no
1404
+ * tenant at a lower scope) are written by a caller who holds a
1405
+ * \`meta.manageRoles\` permission through a global role. The
1406
+ * \`permdock_trusted_*\` variants skip the caller checks and keep the
1407
+ * definition checks; no client role may execute them.
1408
+ */
1409
+ function customRoleWritesSql(ctx, levelReach) {
1410
+ const custom = ctx.customRoles;
1411
+ const root = ctx.scopes[0]?.name;
1412
+ if (custom === void 0 || ctx.authorize !== "database" || root === void 0) return "";
1413
+ const leveled = custom.levels === true;
1414
+ const tenantType = tenantTypeOf(ctx);
1415
+ const rp = qualified(ctx, "role_permissions");
1416
+ const ceiling = qualified(ctx, CUSTOM_ROLES.ceiling);
1417
+ const perms = qualified(ctx, CUSTOM_ROLES.permissions);
1418
+ const includes = qualified(ctx, CUSTOM_ROLES.includes);
1419
+ const beyond = qualified(ctx, CUSTOM_ROLES.beyond);
1420
+ const guard = qualified(ctx, CUSTOM_ROLES.guard);
1421
+ const shape = qualified(ctx, CUSTOM_ROLES.shape);
1422
+ const entries = qualified(ctx, CUSTOM_ROLES.entries);
1423
+ const problem = qualified(ctx, CUSTOM_ROLES.entryProblem);
1424
+ const renames = Object.entries(custom.renamed ?? {}).toSorted(byKey);
1425
+ const current = (expr) => currentKeyExpr(renames, expr);
1426
+ const known = sqlTextArray([...custom.permissions ?? [], ...renames.map(([former]) => former)]);
1427
+ const caller = callerFunctionsSql(ctx, custom, root, levelReach, false);
1428
+ const match = `(p_tenant is null and c.tenant_id is null or c.tenant_id = p_tenant) and c.scope = p_scope and (p_scope_id is null and c.scope_id is null or c.scope_id = p_scope_id)`;
1429
+ const scopes = sqlTextArray(ctx.scopes.map((scope) => scope.name));
1430
+ const roleName = (param) => `coalesce(${param}, '') = '' or ${param} = any(${sqlTextArray(custom.declared)})`;
1431
+ const levelOf = leveled ? ", nullif(split_part(e, '@', 2), '')" : "";
1432
+ const levelColumn = leveled ? ", level" : "";
1433
+ const sharedRole = qualified(ctx, CUSTOM_ROLES.shared);
1434
+ const taken = (param) => ` if p_tenant is not null and ${sharedRole}(p_scope, ${param}) then
1435
+ ${raiseSql(" ", "22023", `'permdock: ' || ${param} || ' is the name of a shared custom role'`, "name-taken")}
1436
+ end if;
1437
+ `;
1438
+ const write = `${taken("p_role")} delete from ${perms} c where ${match} and c.role = p_role;
1439
+ delete from ${includes} c where ${match} and c.role = p_role;
1440
+ insert into ${perms} (tenant_id, scope, scope_id, role, permission, effect${levelColumn})
1441
+ select distinct p_tenant, p_scope, p_scope_id, p_role, ${current(leveled ? "split_part(e, '@', 1)" : "e")}, 'allow'${levelOf}
1442
+ from unnest(coalesce(p_allow, '{}'::text[])) e
1443
+ union
1444
+ select distinct p_tenant, p_scope, p_scope_id, p_role, ${current("e")}, 'deny'${leveled ? ", null" : ""}
1445
+ from unnest(coalesce(p_deny, '{}'::text[])) e;
1446
+ insert into ${includes} (tenant_id, scope, scope_id, role, include_role)
1447
+ select distinct p_tenant, p_scope, p_scope_id, p_role, e
1448
+ from unnest(coalesce(p_include, '{}'::text[])) e;`;
1449
+ const move = `${taken("p_to")} if ${roleName("p_to")} then
1450
+ ${raiseSql(" ", "22023", `'permdock: ' || coalesce(p_to, 'null') || ' is not a custom role name'`, "declared-role")}
1451
+ end if;
1452
+ if exists (select 1 from ${perms} c where ${match} and c.role = p_to)
1453
+ or exists (select 1 from ${includes} c where ${match} and c.role = p_to) then
1454
+ ${raiseSql(" ", "22023", `'permdock: ' || p_to || ' already has grants'`, "role-exists")}
1455
+ end if;
1456
+ update ${perms} c set role = p_to where ${match} and c.role = p_from;
1457
+ update ${includes} c set role = p_to where ${match} and c.role = p_from;`;
1458
+ const remove = ` delete from ${perms} c where ${match} and c.role = p_role;
1459
+ delete from ${includes} c where ${match} and c.role = p_role;`;
1460
+ const writeArgs = `${tenantType}, text, text, text, text[], text[], text[]`;
1461
+ const renameArgs = `${tenantType}, text, text, text, text`;
1462
+ const removeArgs = `${tenantType}, text, text, text`;
1463
+ const fn = (comment, name, params, args, body, member) => `-- ${comment}
1464
+ create or replace function ${qualified(ctx, name)}(${params})
1465
+ returns void
1466
+ language plpgsql
1467
+ volatile
1468
+ security definer
1469
+ set search_path = ''
1470
+ as $$
1471
+ ${body}
1472
+ $$;
1473
+ ${member ? `revoke execute on function ${qualified(ctx, name)}(${args}) from public, anon;
1474
+ grant execute on function ${qualified(ctx, name)}(${args}) to authenticated;` : `revoke execute on function ${qualified(ctx, name)}(${args}) from public, anon, authenticated;`}`;
1475
+ const writeParams = `p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text, p_allow text[], p_deny text[], p_include text[]`;
1476
+ const renameParams = `p_tenant ${tenantType}, p_scope text, p_scope_id text, p_from text, p_to text`;
1477
+ const removeParams = `p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text`;
1478
+ return `${caller.beyond}
1479
+
1480
+ -- 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
1481
+ create or replace function ${shape}(p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text)
1482
+ returns void
1483
+ language plpgsql
1484
+ stable
1485
+ set search_path = ''
1486
+ as $$
1487
+ begin
1488
+ if p_scope = 'global' then
1489
+ if p_tenant is not null or p_scope_id is not null then
1490
+ ${raiseSql(" ", "22023", `'permdock: a platform custom role has no tenant or instance'`, "unknown-scope")}
1491
+ end if;
1492
+ elsif not (p_scope = any(${scopes})) then
1493
+ ${raiseSql(" ", "22023", `'permdock: custom roles are held at a scope of a tenant or at global, not ' || coalesce(p_scope, 'null')`, "unknown-scope")}
1494
+ elsif p_tenant is null and p_scope_id is not null then
1495
+ ${raiseSql(" ", "22023", `'permdock: a shared custom role has no instance'`, "unknown-scope")}
1496
+ end if;
1497
+ if ${roleName("p_role")} then
1498
+ ${raiseSql(" ", "22023", `'permdock: ' || coalesce(p_role, 'null') || ' is not a custom role name'`, "declared-role")}
1499
+ end if;
1500
+ end;
1501
+ $$;
1502
+ revoke execute on function ${shape}(${tenantType}, text, text, text) from public, anon, authenticated;
1503
+
1504
+ ${caller.guard}
1505
+ ${hasCustomRoleChecksFor(ctx) ? `
1506
+ -- the same checks for a user the caller names: trusted SQL acting later for a stored user; no client role may execute them
1507
+ ${callerFunctionsSql(ctx, custom, root, levelReach, true).beyond}
1508
+
1509
+ ${callerFunctionsSql(ctx, custom, root, levelReach, true).guard}
1510
+ ` : ""}
1511
+ -- 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" : ""}
1512
+ create or replace function ${problem}(p_scope text, p_entry text)
1513
+ returns text
1514
+ language plpgsql
1515
+ stable
1516
+ security definer
1517
+ set search_path = ''
1518
+ as $$
1519
+ declare
1520
+ v_key text := ${current(leveled ? "split_part(p_entry, '@', 1)" : "p_entry")};
1521
+ begin
1522
+ if p_entry is null or not (v_key = any(${known})) then
1523
+ return 'unknown-permission';
1524
+ end if;
1525
+ if not exists (
1526
+ select 1 from ${ceiling} c
1527
+ where c.scope = p_scope and c.effect = 'allow' and ${current("c.permission")} = v_key
1528
+ ) then
1529
+ return 'outside-ceiling';
1530
+ end if;${leveled ? `
1531
+ if strpos(p_entry, '@') > 0 and not exists (
1532
+ select 1 from ${ceiling} c
1533
+ where c.scope = p_scope and c.effect = 'allow' and ${current("c.permission")} = v_key
1534
+ and split_part(c.grant_key, '@', 2) = split_part(p_entry, '@', 2)
1535
+ ) then
1536
+ return 'unknown-level';
1537
+ end if;` : ""}
1538
+ return null;
1539
+ end;
1540
+ $$;
1541
+ revoke execute on function ${problem}(text, text) from public, anon, authenticated;
1542
+
1543
+ -- the entries of a definition: declared keys and levels inside the ceiling of the scope, and declared includes
1544
+ create or replace function ${entries}(p_scope text, p_allow text[], p_deny text[], p_include text[])
1545
+ returns void
1546
+ language plpgsql
1547
+ stable
1548
+ security definer
1549
+ set search_path = ''
1550
+ as $$
1551
+ declare
1552
+ v_entry text;
1553
+ v_key text;
1554
+ v_problem text;
1555
+ begin
1556
+ foreach v_entry in array coalesce(p_allow, '{}'::text[]) loop
1557
+ v_key := ${current(leveled ? "split_part(v_entry, '@', 1)" : "v_entry")};
1558
+ v_problem := ${problem}(p_scope, v_entry);
1559
+ if v_problem = 'unknown-permission' then
1560
+ ${raiseSql(" ", "22023", `'permdock: ' || v_entry || ' is not a declared permission'`, "unknown-permission")}
1561
+ end if;
1562
+ if v_problem = 'outside-ceiling' then
1563
+ ${raiseSql(" ", "22023", `'permdock: ' || v_key || ' is outside the ceiling of ' || p_scope`, "outside-ceiling")}
1564
+ end if;${leveled ? `
1565
+ if v_problem = 'unknown-level' then
1566
+ ${raiseSql(" ", "22023", `'permdock: ' || v_entry || ' names a level the resource does not declare'`, "unknown-level")}
1567
+ end if;` : ""}
1568
+ end loop;
1569
+ foreach v_entry in array coalesce(p_deny, '{}'::text[]) loop
1570
+ if not (v_entry = any(${known})) then
1571
+ ${raiseSql(" ", "22023", `'permdock: ' || v_entry || ' is not a declared permission'`, "unknown-permission")}
1572
+ end if;
1573
+ end loop;
1574
+ foreach v_entry in array coalesce(p_include, '{}'::text[]) loop
1575
+ if not (v_entry = any(${sqlTextArray(custom.declared)})) then
1576
+ ${raiseSql(" ", "22023", `'permdock: ' || v_entry || ' is not a declared role'`, "unknown-role")}
1577
+ end if;
1578
+ end loop;
1579
+ select string_agg(distinct ${current("rp.permission")}, ', ') into v_key
1580
+ from ${rp} rp
1581
+ where rp.role = any(coalesce(p_include, '{}'::text[]))
1582
+ and rp.effect = 'allow'
1583
+ and not exists (
1584
+ select 1 from ${ceiling} c
1585
+ where c.scope = p_scope and c.effect = 'allow' and ${current("c.permission")} = ${current("rp.permission")}
1586
+ );
1587
+ if v_key is not null then
1588
+ ${raiseSql(" ", "22023", `'permdock: an included role allows ' || v_key || ', outside the ceiling of ' || p_scope`, "outside-ceiling")}
1589
+ end if;
1590
+ end;
1591
+ $$;
1592
+ revoke execute on function ${entries}(text, text[], text[], text[]) from public, anon, authenticated;
1593
+
1594
+ ${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
1595
+ v_beyond text;
1596
+ begin
1597
+ perform ${guard}(p_tenant, p_scope, p_scope_id, p_role);
1598
+ perform ${entries}(p_scope, p_allow, p_deny, p_include);
1599
+ select string_agg(b, ', ' order by b) into v_beyond
1600
+ from ${beyond}(p_tenant, p_scope, p_scope_id, p_allow, p_deny, p_include) b;
1601
+ if v_beyond is not null then
1602
+ ${raiseSql(" ", "42501", `'permdock: ' || p_role || ' would allow ' || v_beyond || ', which the caller may not hand out'`, "not-assignable-by")}
1603
+ end if;
1604
+ ${write}
1605
+ end;`, true)}
1606
+
1607
+ ${fn("rename a custom role: move its grants and includes to the new name", CUSTOM_ROLES.rename, renameParams, renameArgs, `begin
1608
+ perform ${guard}(p_tenant, p_scope, p_scope_id, p_from);
1609
+ ${move}
1610
+ end;`, true)}
1611
+
1612
+ ${fn("delete a custom role: remove its grants and includes", CUSTOM_ROLES.remove, removeParams, removeArgs, `begin
1613
+ perform ${guard}(p_tenant, p_scope, p_scope_id, p_role);
1614
+ ${remove}
1615
+ end;`, true)}
1616
+
1617
+ ${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
1618
+ perform ${shape}(p_tenant, p_scope, p_scope_id, p_role);
1619
+ perform ${entries}(p_scope, p_allow, p_deny, p_include);
1620
+ ${write}
1621
+ end;`, false)}
1622
+
1623
+ ${fn("rename a custom role for a trusted caller", CUSTOM_ROLES.trustedRename, renameParams, renameArgs, `begin
1624
+ perform ${shape}(p_tenant, p_scope, p_scope_id, p_from);
1625
+ ${move}
1626
+ end;`, false)}
1627
+
1628
+ ${fn("delete a custom role for a trusted caller", CUSTOM_ROLES.trustedRemove, removeParams, removeArgs, `begin
1629
+ perform ${shape}(p_tenant, p_scope, p_scope_id, p_role);
1630
+ ${remove}
1631
+ end;`, false)}`;
1632
+ }
1633
+ // src/cli/rls/global-roles.ts
1634
+ /**
1635
+ * `permdock_replace_global_roles(p_user, p_roles)`: sets the global roles of
1636
+ * one user in `rls.roles` in one statement pair. It runs as the invoker, so the
1637
+ * table's policies and the `rls.assignments` trigger judge every row it deletes
1638
+ * or inserts.
1639
+ */
1640
+ function globalRolesSql(ctx) {
1641
+ if (ctx.roles === void 0) return "";
1642
+ const source = globalRoleSource(ctx.roles, "public", "t", ctx.customRoles?.table);
1643
+ const table = quoteQualified(ctx.roles.table);
1644
+ const user = quoteIdent(source.user);
1645
+ const fn = qualified(ctx, GLOBAL_ROLES.replace);
1646
+ const type = ctx.dialect === "supabase" ? "uuid" : "text";
1647
+ const wanted = `select distinct r from unnest(coalesce(p_roles, '{}'::text[])) r where r is not null`;
1648
+ const through = source.through;
1649
+ let body;
1650
+ if (through === void 0) {
1651
+ const role = typeof ctx.roles.role === "string" ? ctx.roles.role : "role";
1652
+ const column = quoteIdent(role);
1653
+ body = ` delete from ${table} t
1654
+ where t.${user} = p_user
1655
+ and t.${column}::text <> all(coalesce(p_roles, '{}'::text[]));
1656
+ insert into ${table} (${user}, ${column})
1657
+ select p_user, w.r
1658
+ from (${wanted}) w(r)
1659
+ where not exists (
1660
+ select 1 from ${table} t where t.${user} = p_user and t.${column}::text = w.r
1661
+ );`;
1662
+ } else {
1663
+ const keys = quoteTable(through.table);
1664
+ const id = quoteIdent(through.id);
1665
+ const key = quoteIdent(through.key);
1666
+ const ref = quoteIdent(through.ref);
1667
+ 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`}`;
1668
+ body = ` select string_agg(w.r, ', ' order by w.r) into v_unknown
1669
+ from (${wanted}) w(r)
1670
+ where not exists (select 1 from ${keys} k where k.${key}::text = w.r${global});
1671
+ if v_unknown is not null then
1672
+ raise exception using
1673
+ errcode = '22023',
1674
+ hint = 'unknown-role',
1675
+ message = 'permdock: ' || v_unknown || ' is not a role';
1676
+ end if;
1677
+ delete from ${table} t
1678
+ where t.${user} = p_user
1679
+ and not exists (
1680
+ select 1 from ${keys} k
1681
+ where k.${id} = t.${ref}
1682
+ and k.${key}::text = any(coalesce(p_roles, '{}'::text[]))${global}
1683
+ );
1684
+ insert into ${table} (${user}, ${ref})
1685
+ select p_user, k.${id}
1686
+ from ${keys} k
1687
+ where k.${key}::text in (${wanted})${global}
1688
+ and not exists (
1689
+ select 1 from ${table} t where t.${user} = p_user and t.${ref} = k.${id}
1690
+ );`;
1691
+ }
1692
+ const declare = through === void 0 ? "" : "declare\n v_unknown text;\n";
1693
+ const args = `${type}, text[]`;
1694
+ 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
1695
+ create or replace function ${fn}(p_user ${type}, p_roles text[])
1696
+ returns void
1697
+ language plpgsql
1698
+ volatile
1699
+ set search_path = ''
1700
+ as $$
1701
+ ${declare}begin
1702
+ ${body}
1703
+ end;
1704
+ $$;
1705
+ revoke execute on function ${fn}(${args}) from public, anon;
1706
+ grant execute on function ${fn}(${args}) to authenticated;`;
1707
+ }
1708
+ // src/cli/rls/helper-members.ts
1709
+ /**
1710
+ * The body of `member_<scope>_ids()`: instances of `scope` the subject holds a
1711
+ * live membership of, with any role. Not narrowed to the active tenant, and no
1712
+ * cascade: a membership of a child scope is not one of its parent.
1713
+ */
1714
+ function memberBody(ctx, scope, type, roles) {
1715
+ if (ctx.authorize !== "database") return sqlBody(` select distinct (m ->> 'id')::${type}
1716
+ from (select ${membershipClaim(ctx)} as v) pdk_c
1717
+ cross join lateral jsonb_array_elements(
1718
+ case jsonb_typeof(pdk_c.v) when 'array' then pdk_c.v else '[]'::jsonb end
1719
+ ) m
1720
+ where ${signedIn(ctx)}
1721
+ and m ->> 'scope' = ${quoteLiteral(scope)}
1722
+ and m ->> 'id' is not null${keyTenantLine(ctx, scope, claimTenant(ctx, scope))}
1723
+ and jsonb_typeof(m -> 'roles') = 'array'
1724
+ and jsonb_array_length(m -> 'roles') > 0${roles === void 0 ? "" : `\n and (m -> 'roles') ?| ${roles}`}
1725
+ and case jsonb_typeof(m -> 'expires_at')
1726
+ when 'number' then (m ->> 'expires_at')::numeric > extract(epoch from now())
1727
+ else true
1728
+ end${[
1729
+ ...claimKeptLines(ctx, " "),
1730
+ ...userActive(ctx, " "),
1731
+ ...instancesActive(ctx, scope, (name) => name === scope ? `m ->> 'id'` : `m -> 'within' ->> ${quoteLiteral(name)}`, " ")
1732
+ ].map((line) => `\n${line}`).join("")}`);
1733
+ return memberRowsBody(ctx, scope, type, subjectIdSql(ctx), scopeSources(ctx, scope), true, roles);
1734
+ }
1735
+ /**
1736
+ * The membership rows of `user` for `scope`, from the sources or else the
1737
+ * mapped table, with the same expiry and suspension filters either way.
1738
+ */
1739
+ function memberRowsBody(ctx, scope, type, user, sources, keyed = false, roles) {
1740
+ if (sources.length > 0) {
1741
+ const narrow = keyed ? keyTenantLine(ctx, scope, sourceIdOf(scope)(rootName(ctx))) : "";
1742
+ return sourcesBodyOf(` select distinct (ms.id)::${type}
1743
+ from (
1744
+ ${sourceRows(sources)}
1745
+ ) ms
1746
+ where ${signedIn(ctx, user)}
1747
+ and ms.scope = ${quoteLiteral(scope)}
1748
+ and jsonb_typeof(ms.roles) = 'array'
1749
+ 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);
1750
+ }
1751
+ const mapped = scopeTable(ctx, scope);
1752
+ if (mapped === void 0) return sqlBody(` select null::${type} where false -- no ${scope} memberships table configured`);
1753
+ const { table, column, tenantColumn } = mapped;
1754
+ const role = memberRoleOf(table, "m", " ");
1755
+ const lines = [
1756
+ ` select distinct ${memberColumn(column)}::${type}`,
1757
+ ` from ${quoteQualified(table.table)} m${role.join}`,
1758
+ ` where ${memberColumn(table.user)} = ${user}`,
1759
+ ` and ${role.through === void 0 && !role.lateral ? memberColumn(role.column) : role.sql} is not null`
1760
+ ];
1761
+ if (roles !== void 0) lines.push(` and (${role.through === void 0 && !role.lateral ? memberColumn(role.column) : role.sql})::text = any(${roles})`);
1762
+ const narrow = keyed ? keyTenantSql(ctx, tenantColumn === void 0 ? void 0 : memberColumn(tenantColumn)) : void 0;
1763
+ if (narrow !== void 0) lines.push(` and ${narrow}`);
1764
+ if (table.expiresAt !== void 0) {
1765
+ const expires = memberColumn(table.expiresAt);
1766
+ lines.push(` and (${expires} is null or ${expires} > now())`);
1767
+ }
1768
+ lines.push(...activeMembershipSql(ctx, disabledColumn(table), void 0).map((part) => ` and ${part}`), ...userActive(ctx, " ", user), ...instancesActive(ctx, scope, (name) => {
1769
+ const held = scopeColumn(table, ctx.scopes, name);
1770
+ return held === void 0 ? void 0 : memberColumn(held);
1771
+ }, " "));
1772
+ return sqlBody(lines.join("\n"));
1773
+ }
1774
+ function membershipClaim(ctx) {
1775
+ const raw = subjectClaimJsonSql(ctx, "memberships");
1776
+ return ctx.dialect === "supabase" ? `coalesce(${raw}, (select auth.jwt()) -> 'app_metadata' -> 'memberships')` : raw;
1777
+ }
1778
+ function memberFunction(ctx, scope, type, anonExecute) {
1779
+ const fn = qualified(ctx, memberIdsHelper(scope));
1780
+ const body = memberBody(ctx, scope, type);
1781
+ const keys = ctx.apiKeys;
1782
+ const keyed = keys === void 0 || scope !== rootName(ctx) ? body : {
1783
+ sql: `${body.sql}\n union\n${serviceKeyMemberSql(ctx, keys, scope, type)}`,
1784
+ vars: body.vars
1785
+ };
1786
+ const grants = anonExecute ? `revoke execute on function ${fn}() from public;
1787
+ grant execute on function ${fn}() to anon, authenticated;` : `revoke execute on function ${fn}() from public, anon;
1788
+ grant execute on function ${fn}() to authenticated;`;
1789
+ return `create or replace function ${fn}()
1790
+ returns setof ${type}
1791
+ ${functionBody(keyed, true, true)}
1792
+ ${grants}`;
1793
+ }
1794
+ /**
1795
+ * `member_<scope>_ids(p_roles text[])`: `member_<scope>_ids()` narrowed to
1796
+ * memberships holding one of `p_roles` by name, for `rls migrate`'s `role`
1797
+ * helpers. Generated only for a scope such a helper names.
1798
+ */
1799
+ function memberRolesFunction(ctx, scope, type, anonExecute) {
1800
+ const fn = qualified(ctx, memberIdsHelper(scope));
1801
+ const body = memberBody(ctx, scope, type, "p_roles");
1802
+ const grants = anonExecute ? `revoke execute on function ${fn}(text[]) from public;
1803
+ grant execute on function ${fn}(text[]) to anon, authenticated;` : `revoke execute on function ${fn}(text[]) from public, anon;
1804
+ grant execute on function ${fn}(text[]) to authenticated;`;
1805
+ return `create or replace function ${fn}(p_roles text[])
1806
+ returns setof ${type}
1807
+ ${functionBody(body, true, true)}
1808
+ ${grants}`;
1809
+ }
1810
+ /**
1811
+ * `member_<scope>_ids_for(p_user uuid)`: `member_<scope>_ids()` for a user the
1812
+ * caller names, read from the membership sources (or the mapped table) in
1813
+ * either mode, so a token hook can call it before any claim exists. Naming the
1814
+ * user is why no client role may execute it. `supabase_auth_admin` may: the
1815
+ * hook's claims functions and better-supabase's `memberIdsFor` call it as that
1816
+ * role. The grant sits next to the function, so no migration order matters, and
1817
+ * runs only where the role exists, so plain Postgres loads the file too. A
1818
+ * `team` or `teams` scope takes `p_active text default null` too, the one
1819
+ * signature the hook's `team_ids` claim calls with the active tenant; its
1820
+ * one-argument form is dropped so a call with the user alone stays
1821
+ * unambiguous.
1822
+ */
1823
+ function memberForFunction(ctx, scope, type) {
1824
+ const fn = qualified(ctx, memberForHelper(scope));
1825
+ const body = memberRowsBody(ctx, scope, type, "p_user", memberForSources(ctx, scope));
1826
+ const team = ctx.dialect === "supabase" && isTeamScope(scope);
1827
+ const types = team ? "uuid, text" : "uuid";
1828
+ return `${team ? `drop function if exists ${fn}(uuid);\n` : ""}create or replace function ${fn}(p_user uuid${team ? ", p_active text default null" : ""})
1829
+ returns setof ${type}
1830
+ ${functionBody(body)}
1831
+ revoke execute on function ${fn}(${types}) from public, anon, authenticated;
1832
+ ${authAdminGrants([`grant usage on schema ${quoteIdent(helperSchema(ctx))} to supabase_auth_admin;`, `grant execute on function ${fn}(${types}) to supabase_auth_admin;`])}`;
1833
+ }
1834
+ const AUTH_ADMIN_GUARD = `do $permdock$ begin
1835
+ if exists (select 1 from pg_catalog.pg_roles where rolname = 'supabase_auth_admin') then
1836
+ `;
1837
+ const AUTH_ADMIN_END = ` end if;
1838
+ end
1839
+ $permdock$;`;
1840
+ /** Grants to `supabase_auth_admin` that run only on a database with the role. */
1841
+ function authAdminGrants(grants) {
1842
+ return `${AUTH_ADMIN_GUARD}${grants.map((grant) => ` ${grant}\n`).join("")}${AUTH_ADMIN_END}`;
1843
+ }
1844
+ /**
1845
+ * The `authAdminGrants` blocks of `sql` as plain grants, for a split helpers
1846
+ * file: a declarative schema keeps no `do` block, and Supabase always has the
1847
+ * role.
1848
+ */
1849
+ function unguardAuthAdminGrants(sql) {
1850
+ let out = "";
1851
+ let from = 0;
1852
+ for (;;) {
1853
+ const start = sql.indexOf(AUTH_ADMIN_GUARD, from);
1854
+ if (start === -1) return out + sql.slice(from);
1855
+ const end = sql.indexOf(AUTH_ADMIN_END, start);
1856
+ const body = sql.slice(start + AUTH_ADMIN_GUARD.length, end);
1857
+ out += sql.slice(from, start);
1858
+ out += body.replaceAll(/^ {4}/gmu, "").trimEnd();
1859
+ from = end + AUTH_ADMIN_END.length;
1860
+ }
1861
+ }
1862
+ const AUTH_ADMIN_GRANT = /^grant [^;]+ to supabase_auth_admin;$/u;
1863
+ /**
1864
+ * `sql` with its plain grants to `supabase_auth_admin` moved into one
1865
+ * `authAdminGrants` block at the end, for a `--grants-out` file: a migration
1866
+ * may keep a `do` block, and plain Postgres has no such role.
1867
+ */
1868
+ function guardAuthAdminGrants(sql) {
1869
+ const lines = sql.split("\n");
1870
+ const grants = lines.filter((line) => AUTH_ADMIN_GRANT.test(line));
1871
+ if (grants.length === 0) return sql;
1872
+ const rest = lines.filter((line) => !AUTH_ADMIN_GRANT.test(line)).join("\n");
1873
+ const trailing = /\s*$/u.exec(rest)?.[0] ?? "";
1874
+ return `${rest.trimEnd()}\n${authAdminGrants(grants)}${trailing}`;
1875
+ }
1876
+ /**
1877
+ * `member_<scope>_ids_of(p_user uuid)`: `member_<scope>_ids_for(p_user)` for
1878
+ * the caller only. Any other `p_user` returns no rows, so a client role may
1879
+ * execute it without learning another user's memberships.
1880
+ */
1881
+ function memberOfFunction(ctx, scope, type) {
1882
+ const fn = qualified(ctx, memberOfHelper(scope));
1883
+ return `create or replace function ${fn}(p_user uuid)
1884
+ returns setof ${type}
1885
+ ${functionBody(sqlBody(` select m.id
1886
+ from ${qualified(ctx, memberForHelper(scope))}(p_user) as m(id)
1887
+ where p_user = ${subjectIdSql(ctx)}`))}
1888
+ revoke execute on function ${fn}(uuid) from public, anon;
1889
+ grant execute on function ${fn}(uuid) to authenticated;`;
1890
+ }
1891
+ // src/cli/rls/memo-generation.ts
1892
+ const BUMP = "permdock_bump_memo_generation";
1893
+ const TRIGGER = "permdock_memo_generation";
1894
+ function add(targets, table, columns = []) {
1895
+ const key = qualifySqlTable(table);
1896
+ const existing = targets.get(key);
1897
+ if (existing === void 0) {
1898
+ targets.set(key, {
1899
+ table,
1900
+ columns: columns.length === 0 ? void 0 : new Set(columns)
1901
+ });
1902
+ return;
1903
+ }
1904
+ if (existing.columns === void 0 || columns.length === 0) {
1905
+ targets.set(key, {
1906
+ table: existing.table,
1907
+ columns: void 0
1908
+ });
1909
+ return;
1910
+ }
1911
+ for (const column of columns) existing.columns.add(column);
1912
+ }
1913
+ function suspensionTargets(targets, row) {
1914
+ if (row === void 0) return;
1915
+ const columns = [...row.disabledAt === void 0 ? [] : [row.disabledAt], ...row.status === void 0 ? [] : [row.status]];
1916
+ add(targets, row.table, columns);
1917
+ }
1918
+ const IDENT = String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)`;
1919
+ const READ = new RegExp(String.raw`(?<!\bdistinct\s+)(?<!\bextract\s*\([^()]*)\b(?:from|join)\s+(${IDENT})\.(${IDENT})(?![\w$]|\s*[.(])`, "gu");
1920
+ const SYSTEM = /* @__PURE__ */ new Set([
1921
+ "auth",
1922
+ "pg_catalog",
1923
+ "information_schema"
1924
+ ]);
1925
+ function unquote(name) {
1926
+ return name.startsWith("\"") ? name.slice(1, -1).replaceAll("\"\"", "\"") : name;
1927
+ }
1928
+ function readTables(sql) {
1929
+ const out = /* @__PURE__ */ new Set();
1930
+ for (const [, schema = "", table = ""] of sql.matchAll(READ)) {
1931
+ const name = unquote(schema);
1932
+ if (!SYSTEM.has(name)) out.add(`${name}.${unquote(table)}`);
1933
+ }
1934
+ return [...out];
1935
+ }
1936
+ /** A `role_permissions` view cannot carry a trigger. */
1937
+ function memoTable(ctx, table) {
1938
+ return !(ctx.seeds === "view" && qualifySqlTable(table) === `${helperSchema(ctx)}.role_permissions`);
1939
+ }
1940
+ function memoTargets(ctx, reads) {
1941
+ const schema = helperSchema(ctx);
1942
+ const targets = /* @__PURE__ */ new Map();
1943
+ if (memoTable(ctx, `${schema}.role_permissions`)) add(targets, `${schema}.role_permissions`);
1944
+ if (ctx.customRoles !== void 0) {
1945
+ add(targets, `${schema}.${CUSTOM_ROLES.permissions}`);
1946
+ add(targets, `${schema}.${CUSTOM_ROLES.includes}`);
1947
+ const roles = ctx.customRoles.table;
1948
+ if (roles !== void 0) add(targets, roles.table, [
1949
+ roles.key,
1950
+ ...roles.tenant === void 0 ? [] : [roles.tenant],
1951
+ ...roles.scope === void 0 ? [] : [roles.scope]
1952
+ ]);
1953
+ }
1954
+ suspensionTargets(targets, ctx.suspension?.users);
1955
+ for (const row of Object.values(ctx.suspension?.scopes ?? {})) suspensionTargets(targets, row);
1956
+ for (const table of readTables(reads)) if (memoTable(ctx, table) && !targets.has(qualifySqlTable(table))) add(targets, table);
1957
+ if (ctx.seeds === "view") targets.delete(qualifySqlTable(`${schema}.role_permissions`));
1958
+ return targets;
1959
+ }
1960
+ function triggersSql(ctx, targets) {
1961
+ const trigger = qualified(ctx, TRIGGER);
1962
+ return [...targets].map(({ table, columns }) => {
1963
+ const target = quoteTable(qualifySqlTable(table));
1964
+ const update = columns === void 0 ? "update" : `update of ${[...columns].map((column) => quoteIdent(column)).join(", ")}`;
1965
+ return `drop trigger if exists ${quoteIdent(TRIGGER)} on ${target};
1966
+ create trigger ${quoteIdent(TRIGGER)}
1967
+ after insert or ${update} or delete on ${target}
1968
+ for each statement execute function ${trigger}();
1969
+ drop trigger if exists ${quoteIdent(`${TRIGGER}_truncate`)} on ${target};
1970
+ create trigger ${quoteIdent(`${TRIGGER}_truncate`)}
1971
+ after truncate on ${target}
1972
+ for each statement execute function ${trigger}();`;
1973
+ }).join("\n");
1974
+ }
1975
+ /**
1976
+ * The triggers that invalidate the memo when a write changes permitted ids
1977
+ * inside the statement: the permission map, a custom role's grants, a suspended
1978
+ * user or scope, and every table `reads` (the memoized helper bodies) selects
1979
+ * from, such as the membership sources and the global roles. The hook's version
1980
+ * triggers call the same bump.
1981
+ */
1982
+ function memoGenerationSql(ctx, reads = "") {
1983
+ if (!memoizes(ctx)) return "";
1984
+ const bump = qualified(ctx, BUMP);
1985
+ const trigger = qualified(ctx, TRIGGER);
1986
+ const put = qualified(ctx, "permdock_memo_put");
1987
+ return `-- a permission, custom-role, suspension or membership write changes permitted ids inside the statement
1988
+ create or replace function ${put}(p_key text, p_value text)
1989
+ returns void
1990
+ language sql
1991
+ volatile
1992
+ security definer
1993
+ set search_path = ''
1994
+ as $$
1995
+ select ${memoWriteSql(ctx.memo, "p_key", "p_value")}
1996
+ $$;
1997
+ revoke execute on function ${put}(text, text) from public, anon, authenticated;
1998
+
1999
+ create or replace function ${bump}()
2000
+ returns void
2001
+ language sql
2002
+ volatile
2003
+ security definer
2004
+ set search_path = ''
2005
+ as $$
2006
+ select set_config(
2007
+ 'permdock.m.gen',
2008
+ (coalesce(nullif(current_setting('permdock.m.gen', true), ''), '0')::int + 1)::text,
2009
+ true
2010
+ )
2011
+ $$;
2012
+ revoke execute on function ${bump}() from public, anon, authenticated;
2013
+
2014
+ create or replace function ${trigger}()
2015
+ returns trigger
2016
+ language plpgsql
2017
+ volatile
2018
+ security definer
2019
+ set search_path = ''
2020
+ as $$
2021
+ begin
2022
+ perform ${bump}();
2023
+ return null;
2024
+ end;
2025
+ $$;
2026
+ revoke execute on function ${trigger}() from public, anon, authenticated;
2027
+ ${triggersSql(ctx, memoTargets(ctx, reads).values())}`;
2028
+ }
2029
+ function memoReadTriggersSql(ctx, reads, covered) {
2030
+ const done = memoTargets(ctx, covered);
2031
+ const targets = /* @__PURE__ */ new Map();
2032
+ for (const table of readTables(reads)) if (memoTable(ctx, table) && !done.has(qualifySqlTable(table))) add(targets, table);
2033
+ return targets.size === 0 ? "" : triggersSql(ctx, targets.values());
2034
+ }
2035
+ // src/cli/rls/set-helpers.ts
2036
+ /**
2037
+ * `permitted_<scope>_id_array(p_grant)`: the ids of a scope a grant key
2038
+ * reaches, as one array.
2039
+ */
2040
+ function idArrayHelper(scope) {
2041
+ return permittedIdsHelper(scope).replace(/_ids$/u, "_id_array");
2042
+ }
2043
+ /**
2044
+ * `permdock_<root scope>_has(p_grant, p_tenant)`, named after the root scope
2045
+ * (`permdock_tenant_has` for a scope called `tenant`).
2046
+ */
2047
+ function scopeHasHelper(scope) {
2048
+ return permittedIdsHelper(scope).replace(/^permitted_/u, "permdock_").replace(/_ids$/u, "_has");
2049
+ }
2050
+ /**
2051
+ * `permitted_<scope>_id_array(p_grant)` for one scope: a policy writes
2052
+ * `<column> = any(<array>)`, which an index on the column serves. The root
2053
+ * scope also gets `permdock_<scope>_has(p_grant, p_tenant)`, one membership
2054
+ * test for one tenant that reads the same array.
2055
+ */
2056
+ function setHelpersSql(ctx, scope, anonExecute) {
2057
+ const type = scopeTypeOf(ctx, scope);
2058
+ const parallel = memoizes(ctx) ? "" : "\nparallel safe";
2059
+ const array = qualified(ctx, idArrayHelper(scope));
2060
+ const grants = (fn, args) => anonExecute ? `revoke execute on function ${fn}(${args}) from public;\ngrant execute on function ${fn}(${args}) to anon, authenticated;` : `revoke execute on function ${fn}(${args}) from public, anon;\ngrant execute on function ${fn}(${args}) to authenticated;`;
2061
+ const chunks = [`-- ${scope} ids a grant key reaches, as one array, for \`<column> = any(...)\`
2062
+ create or replace function ${array}(p_grant text)
2063
+ returns ${type}[]
2064
+ language sql
2065
+ stable
2066
+ security definer
2067
+ cost 1000${parallel}
2068
+ set search_path = ''
2069
+ as $$
2070
+ select coalesce(array_agg(i), '{}'::${type}[]) from ${qualified(ctx, permittedIdsHelper(scope))}(p_grant) i
2071
+ $$;
2072
+ ${grants(array, "text")}`];
2073
+ if (rootScope(ctx.scopes) === scope) {
2074
+ const fn = qualified(ctx, scopeHasHelper(scope));
2075
+ chunks.push(`-- whether a grant key reaches one ${scope}
2076
+ create or replace function ${fn}(p_grant text, p_tenant ${type})
2077
+ returns boolean
2078
+ language sql
2079
+ stable
2080
+ security definer
2081
+ cost 1000${parallel}
2082
+ set search_path = ''
2083
+ as $$
2084
+ select p_tenant = any(${array}(p_grant))
2085
+ $$;
2086
+ ${grants(fn, `text, ${type}`)}`);
2087
+ }
2088
+ return chunks.join("\n");
2089
+ }
2090
+ // src/cli/rls/token-scopes.ts
2091
+ const TOKEN_SCOPE_ALLOWS = "permdock_token_scope_allows";
2092
+ const TOKEN_SCOPE_MAP = "permdock_token_scope_map";
2093
+ /**
2094
+ * `rls.tokenScopes` as the SQL generator needs it, or `undefined` when it is
2095
+ * off.
2096
+ */
2097
+ function tokenScopesPlan(setting, policy) {
2098
+ if (setting !== true) return;
2099
+ const permissions = listPermissions(policy.permissions).map((leaf) => ({
2100
+ key: leaf.key,
2101
+ scope: leaf.scope,
2102
+ renamedFrom: formerKeys(leaf),
2103
+ meta: leaf.meta
2104
+ }));
2105
+ return { scopes: delegatedScopeMap(permissions, policy.oauthScopes) };
2106
+ }
2107
+ function tokenScopeUnlimitedSql(ctx) {
2108
+ const act = subjectClaimJsonSql(ctx, "act");
2109
+ return `coalesce(${subjectClaimSql(ctx, "client_id")}, '') = ''
2110
+ and (${act} is null
2111
+ or ${act} = 'null'::jsonb
2112
+ or (jsonb_typeof(${act}) = 'object'
2113
+ and ${act} ->> 'kind' in ('support', 'impersonation')))`;
2114
+ }
2115
+ function tokenScopeAllowsCall(ctx, grant) {
2116
+ return `${qualified(ctx, TOKEN_SCOPE_ALLOWS)}(${grant})`;
2117
+ }
2118
+ /**
2119
+ * The token's scopes as rows of `s(scope)`: a space-separated string or,
2120
+ * outside `guc`, a JSON array.
2121
+ */
2122
+ function tokenScopeRows(ctx) {
2123
+ if (ctx.dialect === "guc") return `regexp_split_to_table(btrim(coalesce(${subjectClaimSql(ctx, "scope")}, '')), '\\s+') s(scope)`;
2124
+ const scope = subjectClaimJsonSql(ctx, "scope");
2125
+ return `unnest(case jsonb_typeof(${scope})
2126
+ when 'string' then regexp_split_to_array(btrim(${scope} #>> '{}'), '\\s+')
2127
+ when 'array' then array(select jsonb_array_elements_text(${scope}))
2128
+ else '{}'::text[]
2129
+ end) s(scope)`;
2130
+ }
2131
+ /**
2132
+ * `permdock_token_scope_allows(p_grant)`: a delegated token (a `client_id`, or
2133
+ * an `act` that is not a support or impersonation session) reaches a grant key
2134
+ * only when one of its scopes maps to the key's permission. better-supabase's
2135
+ * `cap_allows` reads the same tokens the same way.
2136
+ */
2137
+ function tokenScopeAllowsSql(ctx, plan, anonExecute) {
2138
+ const fn = qualified(ctx, TOKEN_SCOPE_ALLOWS);
2139
+ const map = qualified(ctx, TOKEN_SCOPE_MAP);
2140
+ const grants = anonExecute ? `revoke execute on function ${fn}(text) from public;
2141
+ grant execute on function ${fn}(text) to anon, authenticated;` : `revoke execute on function ${fn}(text) from public, anon;
2142
+ grant execute on function ${fn}(text) to authenticated;`;
2143
+ return `create or replace function ${map}()
2144
+ returns jsonb
2145
+ language sql
2146
+ immutable
2147
+ set search_path = ''
2148
+ as $$
2149
+ select ${quoteLiteral(JSON.stringify(plan.scopes))}::jsonb
2150
+ $$;
2151
+ revoke execute on function ${map}() from public, anon, authenticated;
2152
+
2153
+ -- 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
2154
+ create or replace function ${fn}(p_grant text)
2155
+ returns boolean
2156
+ language sql
2157
+ stable
2158
+ security definer
2159
+ set search_path = ''
2160
+ as $$
2161
+ select case
2162
+ when ${tokenScopeUnlimitedSql(ctx)} then true
2163
+ when exists (
2164
+ select 1 from ${qualified(ctx, "role_permissions")} rp
2165
+ where rp.grant_key = p_grant and rp.effect = 'deny'
2166
+ ) then true
2167
+ else exists (
2168
+ select 1
2169
+ from ${tokenScopeRows(ctx)}
2170
+ where s.scope <> ''
2171
+ and coalesce(${map}() -> s.scope, '[]'::jsonb)
2172
+ ? split_part(split_part(p_grant, '#', 1), '@', 1)
2173
+ )
2174
+ end
2175
+ $$;
2176
+ ${grants}`;
2177
+ }
2178
+ // src/cli/rls/helpers.ts
2179
+ /**
2180
+ * The policy-side call for a grant key. Every form is uncorrelated, so Postgres
2181
+ * runs the helper once per statement (an InitPlan, or a hashed SubPlan for
2182
+ * `in`), never once per row.
2183
+ */
2184
+ function accessSql(ctx, scope, grantKey, column, helper) {
2185
+ const key = quoteLiteral(grantKey);
2186
+ if (scope === "global") return `(select ${qualified(ctx, HELPERS.has)}(${key}))`;
2187
+ if (column === void 0) throw configError(`PermDock CLI: ${scope}-scoped grant needs definePolicy({ scopes.${scope} })`);
2188
+ const fn = qualified(ctx, helper ?? permittedIdsHelper(scope));
2189
+ if (ctx.reuseMemo === true && memoizes(ctx)) return `${quoteIdent(column)} in (${memoHitList(scope, key, `${fn}(${key})`, `${memoUserSql(ctx, subjectIdSql(ctx))}::text`, ctx.memo, scopeTypeOf(ctx, scope))})`;
2190
+ return `${quoteIdent(column)} = any(array(select ${fn}(${key})))`;
2191
+ }
2192
+ /**
2193
+ * `permitted_<parent>_ids(p_grant)` for each \`rls.tables\` \`via\`: the parent
2194
+ * rows whose scope instance the grant reaches. \`security definer\`, so the
2195
+ * caller needs no read on the parent, and called uncorrelated like
2196
+ * \`permitted_<scope>_ids\`.
2197
+ */
2198
+ function viaHelpersSql(ctx, anonExecute) {
2199
+ const done = /* @__PURE__ */ new Set();
2200
+ const chunks = [];
2201
+ for (const via of Object.values(ctx.vias ?? {})) {
2202
+ if (done.has(via.helper)) continue;
2203
+ done.add(via.helper);
2204
+ chunks.push(`-- rows of ${via.table} whose ${via.column} is a ${via.scope} the grant reaches
2205
+ ${helperFunction(ctx, via.helper, `setof ${via.type}`, sqlBody(` select p.${quoteIdent(via.id)}
2206
+ from ${quoteQualified(via.table)} p
2207
+ where p.${quoteIdent(via.column)} = any(array(select ${qualified(ctx, permittedIdsHelper(via.scope))}(p_grant)))`), anonExecute)}`);
2208
+ }
2209
+ return chunks;
2210
+ }
2211
+ function userIdSql(ctx, anonExecute) {
2212
+ const fn = userIdHelperSql(ctx);
2213
+ return `-- the caller's user id: the sub of request.jwt.claims, or null when it is empty or absent
2214
+ create or replace function ${fn}()
2215
+ returns uuid
2216
+ language sql
2217
+ stable
2218
+ parallel safe
2219
+ set search_path = ''
2220
+ as $$
2221
+ select nullif(
2222
+ nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub',
2223
+ ''
2224
+ )::uuid
2225
+ $$;
2226
+ ${anonExecute ? `revoke execute on function ${fn}() from public;
2227
+ grant execute on function ${fn}() to anon, authenticated;` : `revoke execute on function ${fn}() from public, anon;
2228
+ grant execute on function ${fn}() to authenticated;`}`;
2229
+ }
2230
+ function tokenCurrentSql(ctx, anonExecute) {
2231
+ const fn = qualified(ctx, HELPERS.tokenCurrent);
2232
+ const version = qualified(ctx, AUTHZ_VERSION_TABLE);
2233
+ const grants = anonExecute ? `revoke execute on function ${fn}() from public;
2234
+ grant execute on function ${fn}() to anon, authenticated;` : `revoke execute on function ${fn}() from public, anon;
2235
+ grant execute on function ${fn}() to authenticated;`;
2236
+ return `create or replace function ${fn}()
2237
+ returns boolean
2238
+ language plpgsql
2239
+ stable
2240
+ security definer
2241
+ set search_path = ''
2242
+ as $$
2243
+ begin
2244
+ return coalesce((
2245
+ select to_jsonb(v.version) = (c.j -> 'authz_ver')
2246
+ and coalesce(c.j -> 'memberships_truncated', 'false'::jsonb) <> 'true'::jsonb
2247
+ and jsonb_typeof(c.j -> 'memberships') = 'array'
2248
+ from ${version} v
2249
+ cross join (select auth.jwt() as j) c
2250
+ where v.user_id = ${subjectIdSql(ctx)}
2251
+ ), false);
2252
+ end;
2253
+ $$;
2254
+ ${grants}`;
2255
+ }
2256
+ function helperFunction(ctx, name, returns, body, anonExecute) {
2257
+ const fn = qualified(ctx, name);
2258
+ const grants = anonExecute ? `revoke execute on function ${fn}(text) from public;
2259
+ grant execute on function ${fn}(text) to anon, authenticated;` : `revoke execute on function ${fn}(text) from public, anon;
2260
+ grant execute on function ${fn}(text) to authenticated;`;
2261
+ return `create or replace function ${fn}(p_grant text)
2262
+ returns ${returns}
2263
+ ${functionBody(body, !memoizes(ctx), returns.startsWith("setof"))}
2264
+ ${grants}`;
2265
+ }
2266
+ /**
2267
+ * `permdock_has_for(p_user, p_grant)` and one
2268
+ * `permitted_<scope>_ids_for(p_user, p_grant)` per scope in `database` mode:
2269
+ * the bodies of `permdock_has` and `permitted_<scope>_ids` with `p_user` for
2270
+ * the signed-in user and no tenant-claim narrowing, since a named user has no
2271
+ * token. For trusted SQL that acts for a stored user (jobs, triggers, approvals
2272
+ * resolved later). Naming the user is why no client role may execute them:
2273
+ * `security definer` callers run them as their owner, and a backend role needs
2274
+ * its own grant.
2275
+ */
2276
+ function forUserSql(ctx) {
2277
+ if (ctx.authorize !== "database") return "";
2278
+ const forUser = forUserContext(ctx);
2279
+ const type = ctx.dialect === "supabase" ? "uuid" : "text";
2280
+ const fn = (name, returns, body) => {
2281
+ const qualifiedName = qualified(ctx, name);
2282
+ return `create or replace function ${qualifiedName}(p_user ${type}, p_grant text)
2283
+ returns ${returns}
2284
+ ${functionBody(body, !memoizes(ctx), returns.startsWith("setof"))}
2285
+ revoke execute on function ${qualifiedName}(${type}, text) from public, anon, authenticated;`;
2286
+ };
2287
+ return [`-- the helpers for a user the caller names: trusted SQL acting for a stored user; no client role may execute them
2288
+ ${fn(HELPERS.hasFor, "boolean", sqlBody(hasBody(forUser)))}`, ...ctx.scopes.map((scope) => {
2289
+ const scopeType = scopeTypeOf(ctx, scope.name);
2290
+ return fn(permittedForHelper(scope.name), `setof ${scopeType}`, scopedBody(forUser, scope.name, scopeType));
2291
+ })].join("\n\n");
2292
+ }
2293
+ function userIdType(ctx) {
2294
+ return ctx.dialect === "supabase" ? "uuid not null references auth.users on delete cascade" : "text not null";
2295
+ }
2296
+ /**
2297
+ * The `role_permissions` rows the policy compiles to: an upsert and a delete of
2298
+ * every other row. Data, not schema, so `supabase db diff` drops it from a
2299
+ * declarative schema; `--split ...,seeds` writes it as its own migration.
2300
+ */
2301
+ function seedSql(ctx, rows) {
2302
+ const table = qualified(ctx, "role_permissions");
2303
+ if (rows.length === 0) return `delete from ${table};`;
2304
+ return `insert into ${table} (role, permission, grant_key, scope, effect) values
2305
+ ${rows.map((row) => ` (${[
2306
+ row.role,
2307
+ row.permission,
2308
+ row.grantKey,
2309
+ row.scope,
2310
+ row.effect
2311
+ ].map(quoteLiteral).join(", ")})`).join(",\n")}
2312
+ on conflict (role, grant_key, scope) do update
2313
+ set permission = excluded.permission, effect = excluded.effect;
2314
+ delete from ${table}
2315
+ where (role, grant_key, scope) not in (values
2316
+ ${rows.map((row) => ` (${[
2317
+ row.role,
2318
+ row.grantKey,
2319
+ row.scope
2320
+ ].map(quoteLiteral).join(", ")})`).join(",\n")}
2321
+ );`;
2322
+ }
2323
+ /**
2324
+ * `role_permissions` as a view over the compiled rows (`rls.seeds: 'view'`).
2325
+ * `security_invoker` makes the view read as its caller, so it adds no
2326
+ * privilege; the table's revoke applies to the view the same way.
2327
+ */
2328
+ function seedViewSql(ctx, rows) {
2329
+ const view = qualified(ctx, "role_permissions");
2330
+ const columns = "role, permission, grant_key, scope, effect";
2331
+ if (ctx.staticGrants === "ref") return seedRefSql(ctx, rows);
2332
+ const body = rows.length === 0 ? `select null::text, null::text, null::text, null::text, null::text where false` : `select * from (values\n${rows.map((row) => ` (${[
2333
+ row.role,
2334
+ row.permission,
2335
+ row.grantKey,
2336
+ row.scope,
2337
+ row.effect
2338
+ ].map(quoteLiteral).join(", ")})`).join(",\n")}\n) as v(${columns})`;
2339
+ const sorted = roleKeyMap(rows);
2340
+ const keys = qualified(ctx, "permdock_role_keys");
2341
+ return `-- rls.seeds: 'view': role_permissions is a view, so the rows travel with the schema
2342
+ create or replace view ${view} (${columns}) with (security_invoker = true) as
2343
+ ${body};
2344
+ revoke all on table ${view} from anon, authenticated, public;
2345
+ -- the grant keys of each declared role per scope, as a hash lookup where the view's values list is scanned
2346
+ create or replace function ${keys}(p_scope text, p_role text)
2347
+ returns jsonb
2348
+ language sql
2349
+ immutable
2350
+ parallel safe
2351
+ set search_path = ''
2352
+ as $$
2353
+ select ${quoteLiteral(JSON.stringify(sorted))}::jsonb -> p_scope -> p_role
2354
+ $$;
2355
+ revoke execute on function ${keys}(text, text) from public, anon, authenticated;`;
2356
+ }
2357
+ /**
2358
+ * `rls.staticGrants: 'ref'`: `role_permissions` is a view over the policy
2359
+ * bundle whose hash the SQL pins, and `permdock_role_keys` reads the bundle's
2360
+ * lookup. The rows are not in the SQL; \`permdock policy bundle --kind sql\`
2361
+ * loads them. A bundle that is not loaded, or is loaded under another hash,
2362
+ * leaves the view empty and the lookup null, so every static grant denies.
2363
+ */
2364
+ function seedRefSql(ctx, rows) {
2365
+ const { hash } = policyBundle(rows);
2366
+ const view = qualified(ctx, "role_permissions");
2367
+ const table = qualified(ctx, POLICY_BUNDLE_TABLE);
2368
+ const keys = qualified(ctx, "permdock_role_keys");
2369
+ return `-- rls.staticGrants: 'ref': the static grants are the policy bundle ${hash}, loaded by permdock policy bundle
2370
+ ${bundleTableSql(ctx)}
2371
+ create or replace view ${view} (role, permission, grant_key, scope, effect) with (security_invoker = true) as
2372
+ select r.role, r.permission, r.grant_key, r.scope, r.effect
2373
+ from ${table} b
2374
+ cross join lateral jsonb_to_recordset(b.doc -> 'rows') as r(role text, permission text, grant_key text, scope text, effect text)
2375
+ where b.hash = ${quoteLiteral(hash)};
2376
+ revoke all on table ${view} from anon, authenticated, public;
2377
+ create or replace function ${keys}(p_scope text, p_role text)
2378
+ returns jsonb
2379
+ language sql
2380
+ stable
2381
+ parallel safe
2382
+ set search_path = ''
2383
+ as $$
2384
+ select b.doc -> 'roleKeys' -> p_scope -> p_role from ${table} b where b.hash = ${quoteLiteral(hash)}
2385
+ $$;
2386
+ revoke execute on function ${keys}(text, text) from public, anon, authenticated;`;
2387
+ }
2388
+ /**
2389
+ * `<schema>.seed()`: the same upsert and delete as `seedSql`, for a declarative
2390
+ * schema that carries no rows.
2391
+ */
2392
+ function seedFunctionSql(ctx, rows) {
2393
+ const fn = qualified(ctx, "seed");
2394
+ return `-- rls.seeds: 'function': the role_permissions rows are data, so a declarative diff leaves them out; run select ${fn}(); after each deploy
2395
+ create or replace function ${fn}()
2396
+ returns void
2397
+ language sql
2398
+ volatile
2399
+ security definer
2400
+ set search_path = ''
2401
+ as $permdock$
2402
+ ${seedSql(ctx, rows)}
2403
+ $permdock$;
2404
+ revoke execute on function ${fn}() from public, anon, authenticated;`;
2405
+ }
2406
+ /**
2407
+ * The one lookup from a role to its grant keys on a scope, which every helper
2408
+ * body reads through `cross join lateral`. It reads `role_permissions` as its
2409
+ * caller, as the join it replaces did, and pins `search_path` like every
2410
+ * helper. The pin keeps Postgres from inlining it, so each call is a primary
2411
+ * key range read of `role_permissions`.
2412
+ */
2413
+ function roleGrantKeysSql(ctx) {
2414
+ const fn = qualified(ctx, HELPERS.roleGrantKeys);
2415
+ return `create or replace function ${fn}(p_scope text, p_role text)
2416
+ returns setof text
2417
+ language sql
2418
+ stable
2419
+ parallel safe
2420
+ rows 10
2421
+ set search_path = ''
2422
+ as $$
2423
+ select rp.grant_key from ${qualified(ctx, "role_permissions")} rp where rp.role = p_role and rp.scope = p_scope
2424
+ $$;
2425
+ revoke execute on function ${fn}(text, text) from public, anon, authenticated;`;
2426
+ }
2427
+ /**
2428
+ * `role_permissions`, its seeds, and the three `security definer` helpers with
2429
+ * `search_path = ''`. `execute` goes to `authenticated` only.
2430
+ */
2431
+ function helpersSql(ctx, rows, options) {
2432
+ const schema = helperSchema(ctx);
2433
+ const s = quoteIdent(schema);
2434
+ const rp = qualified(ctx, "role_permissions");
2435
+ const chunks = [`-- permdock helpers (${ctx.authorize === "database" ? "database: reads the membership and user_roles tables" : "jwt: reads the role and memberships claims"})
2436
+ -- policies call them uncorrelated, so Postgres evaluates each once per statement`];
2437
+ if (schema !== "public") {
2438
+ const anonUsage = options.anonExecute === true || ctx.capabilities === true;
2439
+ 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"};`);
2440
+ }
2441
+ if (ctx.dialect === "supabase") chunks.push(userIdSql(ctx, options.anonExecute === true));
2442
+ if (ctx.claimsFirst === true) chunks.push(tokenCurrentSql(ctx, options.anonExecute === true));
2443
+ if (ctx.seeds === "view") chunks.push(seedViewSql(ctx, rows));
2444
+ else chunks.push(`create table if not exists ${rp} (
2445
+ role text not null,
2446
+ permission text not null,
2447
+ grant_key text not null,
2448
+ scope text not null check (scope ~ '^[a-z][a-z0-9_]*$'),
2449
+ effect text not null default 'allow' check (effect in ('allow', 'deny')),
2450
+ primary key (role, grant_key, scope)
2451
+ );
2452
+ alter table ${rp} enable row level security;
2453
+ revoke all on table ${rp} from anon, authenticated, public;
2454
+ ${roleGrantKeysSql(ctx)}`);
2455
+ if (ctx.seeds === "function") chunks.push(seedFunctionSql(ctx, rows));
2456
+ else if (options.withoutSeeds !== true && ctx.seeds !== "view") chunks.push(seedSql(ctx, rows));
2457
+ if (ctx.authorize === "database" && options.userRoles && ctx.roles === void 0) {
2458
+ const ur = qualified(ctx, "user_roles");
2459
+ chunks.push(`create table if not exists ${ur} (
2460
+ user_id ${userIdType(ctx)},
2461
+ role text not null,
2462
+ primary key (user_id, role)
2463
+ );
2464
+ alter table ${ur} enable row level security;
2465
+ revoke all on table ${ur} from anon, authenticated, public;`);
2466
+ }
2467
+ const custom = customRolesSql(ctx);
2468
+ if (custom !== "") chunks.push(custom);
2469
+ const compiled = customRoleCompiledSql(ctx);
2470
+ if (compiled !== "") chunks.push(compiled);
2471
+ const memoGeneration = memoGenerationSql(ctx, memoReadsSql(ctx));
2472
+ if (memoGeneration !== "") chunks.push(memoGeneration);
2473
+ const anon = options.anonExecute === true;
2474
+ const keys = ctx.apiKeys;
2475
+ if (keys !== void 0) chunks.push(apiKeyAllowsSql(ctx, keys, anon));
2476
+ if (ctx.tokenScopes !== void 0) chunks.push(tokenScopeAllowsSql(ctx, ctx.tokenScopes, anon));
2477
+ if (ctx.interactiveOnly !== void 0) chunks.push(interactiveAllowsSql(ctx, ctx.interactiveOnly, anon));
2478
+ const bodies = grantBodies(ctx);
2479
+ chunks.push(helperFunction(ctx, HELPERS.has, "boolean", bodies.has, anon));
2480
+ const capabilities = capabilitiesSql(ctx);
2481
+ if (capabilities !== "") chunks.push(capabilities);
2482
+ for (const scope of ctx.scopes) {
2483
+ const type = scopeTypeOf(ctx, scope.name);
2484
+ chunks.push(helperFunction(ctx, permittedIdsHelper(scope.name), `setof ${type}`, bodies.ids(scope.name), anon));
2485
+ chunks.push(setHelpersSql(ctx, scope.name, anon));
2486
+ chunks.push(memberFunction(ctx, scope.name, type, anon));
2487
+ if (ctx.roleMemberScopes?.includes(scope.name) === true) chunks.push(memberRolesFunction(ctx, scope.name, type, anon));
2488
+ if (hasMemberFor(ctx, scope.name)) chunks.push(memberForFunction(ctx, scope.name, type));
2489
+ if (hasMemberOf(ctx, scope.name)) chunks.push(memberOfFunction(ctx, scope.name, type));
2490
+ }
2491
+ const teamReaders = hookTeamReadersSql(ctx);
2492
+ if (teamReaders !== "") chunks.push(teamReaders);
2493
+ chunks.push(...viaHelpersSql(ctx, anon));
2494
+ const forUser = forUserSql(ctx);
2495
+ if (forUser !== "") chunks.push(forUser);
2496
+ const writes = customRoleWritesSql(ctx, options.levelReach ?? []);
2497
+ if (writes !== "") {
2498
+ chunks.push(writes);
2499
+ const cascade = customRoleCascadeSql(ctx);
2500
+ if (cascade !== "") chunks.push(cascade);
2501
+ const sync = ctx.customRoles?.sync;
2502
+ if (sync !== void 0) chunks.push(sync);
2503
+ const byId = customRoleByIdSql(ctx, options.trustedReaders);
2504
+ if (byId !== "") chunks.push(byId);
2505
+ const nameGuard = customRoleNameGuardSql(ctx);
2506
+ if (nameGuard !== "") chunks.push(nameGuard);
2507
+ }
2508
+ const globalRoles = globalRolesSql(ctx);
2509
+ if (globalRoles !== "") chunks.push(globalRoles);
2510
+ chunks.push(roleReadersSql(ctx, options.permissions, options.trustedReaders));
2511
+ return stampHelpers(`${chunks.join("\n\n")}\n`);
2512
+ }
2513
+ function memoBody(ctx, scope, type, body) {
2514
+ if (!memoizes(ctx)) return body;
2515
+ return {
2516
+ ...body,
2517
+ memo: {
2518
+ type,
2519
+ scope,
2520
+ user: memoUserSql(ctx, subjectIdSql(ctx)),
2521
+ ...ctx.memo === void 0 ? {} : { api: ctx.memo }
2522
+ }
2523
+ };
2524
+ }
2525
+ function memoReadsSql(ctx) {
2526
+ const bodies = grantBodies(ctx);
2527
+ return [bodies.has.sql, ...ctx.scopes.map((scope) => bodies.ids(scope.name).sql)].join("\n");
2528
+ }
2529
+ function grantBodies(ctx) {
2530
+ const keys = ctx.apiKeys;
2531
+ const scoped = ctx.tokenScopes !== void 0;
2532
+ const interactive = ctx.interactiveOnly !== void 0;
2533
+ const set = ctx.grantSet === true;
2534
+ const ceiling = (grant) => {
2535
+ const calls = [
2536
+ ...keys === void 0 ? [] : [apiKeyAllowsCall(ctx, grant)],
2537
+ ...scoped ? [tokenScopeAllowsCall(ctx, grant)] : [],
2538
+ ...interactive ? [interactiveAllowsCall(ctx, grant)] : []
2539
+ ];
2540
+ return calls.length === 0 ? void 0 : calls.join(" and ");
2541
+ };
2542
+ const allows = ceiling(set ? "ids.grant_key" : "p_grant");
2543
+ const keyTenant = keys === void 0 ? "" : ` and ${keyTenantSql(ctx, void 0) ?? "true"}`;
2544
+ const hasAllows = ceiling(set ? "g.grant_key" : "p_grant");
2545
+ return {
2546
+ has: memoBody(ctx, "global", "boolean", sqlBody(hasAllows === void 0 ? hasBody(ctx) : set ? ` select g.grant_key
2547
+ from (
2548
+ ${hasBody(ctx)}
2549
+ ) g(grant_key)
2550
+ where ${hasAllows}${keyTenant}` : ceilingHasSql(hasBody(ctx), `${hasAllows}${keyTenant}`))),
2551
+ ids: (scope) => {
2552
+ const type = scopeTypeOf(ctx, scope);
2553
+ const body = scopedBody(ctx, scope, type);
2554
+ 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;
2555
+ return memoBody(ctx, scope, type, allows === void 0 ? {
2556
+ sql,
2557
+ vars: body.vars
2558
+ } : {
2559
+ sql: set ? ` select ids.id, ids.grant_key
2560
+ from (
2561
+ ${sql}
2562
+ ) ids(id, grant_key)
2563
+ where ${allows}` : ceilingIdsSql(sql, allows),
2564
+ vars: body.vars
2565
+ });
2566
+ }
2567
+ };
2568
+ }
2569
+ function forUserContext(ctx) {
2570
+ const { apiKeys: _apiKeys, tokenScopes: _tokenScopes, interactiveOnly: _interactiveOnly, claimsFirst: _claimsFirst, ...unkeyed } = ctx;
2571
+ return {
2572
+ ...unkeyed,
2573
+ subjectId: "p_user",
2574
+ tenants: "all"
2575
+ };
2576
+ }
2577
+ // src/cli/rls/ownership-names.ts
2578
+ /**
2579
+ * Objects the ownership rules add next to the helpers. Names are part of the
2580
+ * SQL contract.
2581
+ */
2582
+ const OWNERSHIP = {
2583
+ canAssign: "permdock_can_assign",
2584
+ canAssignFor: "permdock_can_assign_for",
2585
+ canAssignAny: "permdock_can_assign_any",
2586
+ canAssignAnyFor: "permdock_can_assign_any_for",
2587
+ holders: "permdock_holders",
2588
+ transferOnly: "permdock_transfer_only"
2589
+ };
2590
+ /** Objects `rls.assignments` adds. Names are part of the SQL contract. */
2591
+ const ASSIGNMENTS = {
2592
+ custom: "permdock_can_assign_custom_role",
2593
+ customFor: "permdock_can_assign_custom_role_for",
2594
+ trigger: "permdock_assignment"
2595
+ };
2596
+ // src/cli/rls/ownership-triggers.ts
2597
+ function objectName(prefix, scope) {
2598
+ return quoteIdent(`${prefix}_${scope}`);
2599
+ }
2600
+ /**
2601
+ * Live holders of `roleExpr` in instance `idExpr`, with the same kind and
2602
+ * expiry rules as the helpers.
2603
+ */
2604
+ function holdersSql(ctx, table, column, idExpr, role, into) {
2605
+ const roleExpr = typeof role === "string" ? quoteLiteral(role) : role.expr;
2606
+ const held = memberRoleOf(table, "m", " ");
2607
+ const filters = [`m.${quoteIdent(column)} = ${idExpr}`, `${held.sql} = ${roleExpr}`];
2608
+ if (table.expiresAt !== void 0) {
2609
+ const expires = memberColumn(table.expiresAt);
2610
+ filters.push(`(${expires} is null or ${expires} > now())`);
2611
+ }
2612
+ const disabled = disabledColumn(table);
2613
+ if (disabled !== void 0) filters.push(`${disabled} is null`);
2614
+ const via = memberVia(table);
2615
+ const kind = typeof role === "string" ? roleKindSql(ctx, role, via) : kindFilterSql(ctx, roleExpr, via);
2616
+ if (kind !== void 0) filters.push(kind);
2617
+ return `select count(distinct m.${quoteIdent(table.user)}) into ${into}
2618
+ from ${quoteQualified(table.table)} m${held.join}
2619
+ where ${filters.join("\n and ")}`;
2620
+ }
2621
+ /**
2622
+ * `min` and `max` as a deferred constraint trigger: checked at commit, so a
2623
+ * transfer (demote one holder, promote another) passes in one transaction. An
2624
+ * instance with no memberships left is being torn down and skips `min`.
2625
+ */
2626
+ function holdersTriggerSql(ctx, scope, table, column, counted) {
2627
+ const fn = qualified(ctx, `${OWNERSHIP.holders}_${scope}`);
2628
+ const col = quoteIdent(column);
2629
+ const checks = counted.map((rule) => {
2630
+ 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")};`];
2631
+ if (rule.min > 0) lines.push(` if v_total > 0 and v_count < ${String(rule.min)} then
2632
+ raise exception using
2633
+ errcode = '23514',
2634
+ hint = 'last-holder',
2635
+ message = ${quoteLiteral(`permdock: ${scope} `)} || v_id || ${quoteLiteral(` keeps at least ${String(rule.min)} ${rule.role}`)};
2636
+ end if;`);
2637
+ if (rule.max !== void 0) lines.push(` if v_count > ${String(rule.max)} then
2638
+ raise exception using
2639
+ errcode = '23514',
2640
+ hint = 'max-holders',
2641
+ message = ${quoteLiteral(`permdock: ${scope} `)} || v_id || ${quoteLiteral(` has at most ${String(rule.max)} ${rule.role}`)};
2642
+ end if;`);
2643
+ return lines.join("\n");
2644
+ });
2645
+ return `-- ${scope}: holder counts (min / max), checked at commit
2646
+ create or replace function ${fn}()
2647
+ returns trigger
2648
+ language plpgsql
2649
+ security definer
2650
+ set search_path = ''
2651
+ as $$
2652
+ declare
2653
+ v_ids text[] := '{}';
2654
+ v_id text;
2655
+ v_key ${quoteQualified(table.table)}.${col}%type;
2656
+ v_total bigint;
2657
+ v_count bigint;
2658
+ begin
2659
+ if tg_op in ('UPDATE', 'DELETE') then
2660
+ v_ids := v_ids || old.${col}::text;
2661
+ end if;
2662
+ if tg_op in ('INSERT', 'UPDATE') then
2663
+ v_ids := v_ids || new.${col}::text;
2664
+ end if;
2665
+ foreach v_id in array v_ids loop
2666
+ continue when v_id is null;
2667
+ v_key := v_id;
2668
+ ${checks.join("\n")}
2669
+ end loop;
2670
+ return null;
2671
+ end;
2672
+ $$;
2673
+ drop trigger if exists ${objectName(OWNERSHIP.holders, scope)} on ${quoteQualified(table.table)};
2674
+ create constraint trigger ${objectName(OWNERSHIP.holders, scope)}
2675
+ after insert or update or delete on ${quoteQualified(table.table)}
2676
+ deferrable initially deferred
2677
+ for each row execute function ${fn}();`;
2678
+ }
2679
+ /**
2680
+ * `transferOnly` as statement triggers over transition tables: a statement that
2681
+ * changes a role's holder count in an instance that had holders before and
2682
+ * still has some after is refused. Creating the first holder and removing the
2683
+ * last (which `min` guards) are not transfers.
2684
+ */
2685
+ function transferTriggerSql(ctx, scope, table, column, roles) {
2686
+ const fn = qualified(ctx, `${OWNERSHIP.transferOnly}_${scope}`);
2687
+ const col = quoteIdent(column);
2688
+ const list = `array[${roles.map(quoteLiteral).join(", ")}]::text[]`;
2689
+ const rows = (alias, source, delta) => {
2690
+ const role = memberRoleOf(table, alias);
2691
+ return `select ${alias}.${col} as id, ${role.sql} as role, ${delta} as delta from ${source} ${alias}${role.join} where ${role.sql} = any(${list})`;
2692
+ };
2693
+ const loop = (source) => ` for v_change in
2694
+ select c.id, c.role, sum(c.delta) as delta
2695
+ from (${source}) c
2696
+ group by c.id, c.role
2697
+ loop
2698
+ continue when v_change.delta = 0 or v_change.id is null;
2699
+ ${holdersSql(ctx, table, column, "v_change.id", { expr: "v_change.role" }, "v_after")};
2700
+ if v_after > 0 and v_after - v_change.delta > 0 then
2701
+ raise exception using
2702
+ errcode = '23514',
2703
+ hint = 'transfer-only',
2704
+ message = 'permdock: ' || v_change.role || ${quoteLiteral(` in ${scope} `)} || v_change.id || ' moves only by transfer';
2705
+ end if;
2706
+ end loop;`;
2707
+ const inserted = rows("n", "permdock_new", "1");
2708
+ const deleted = rows("o", "permdock_old", "-1");
2709
+ const target = quoteQualified(table.table);
2710
+ const trigger = (op) => {
2711
+ const name = quoteIdent(`${OWNERSHIP.transferOnly}_${scope}_${op}`);
2712
+ return `drop trigger if exists ${name} on ${target};
2713
+ create trigger ${name}
2714
+ after ${op} on ${target}
2715
+ 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"}
2716
+ for each statement execute function ${fn}();`;
2717
+ };
2718
+ return `-- ${scope}: transfer-only roles (${roles.join(", ")}) keep their holder count per statement
2719
+ create or replace function ${fn}()
2720
+ returns trigger
2721
+ language plpgsql
2722
+ security definer
2723
+ set search_path = ''
2724
+ as $$
2725
+ declare
2726
+ v_change record;
2727
+ v_after bigint;
2728
+ begin
2729
+ if tg_op = 'INSERT' then
2730
+ ${loop(inserted)}
2731
+ elsif tg_op = 'DELETE' then
2732
+ ${loop(deleted)}
2733
+ else
2734
+ ${loop(`${inserted} union all ${deleted}`)}
2735
+ end if;
2736
+ return null;
2737
+ end;
2738
+ $$;
2739
+ ${trigger("insert")}
2740
+ ${trigger("update")}
2741
+ ${trigger("delete")}`;
2742
+ }
2743
+ // src/cli/rls/ownership-sources.ts
2744
+ /**
2745
+ * The membership sources holding scope `name`: `undefined` when there are none,
2746
+ * `'not-tables'` when one of them carries no table to put a trigger on.
2747
+ */
2748
+ function holderSources(ctx, name) {
2749
+ const sources = memberForSources(ctx, name);
2750
+ if (sources.length === 0) return;
2751
+ const held = [];
2752
+ for (const source of sources) {
2753
+ if (source.sql.holders === void 0) return "not-tables";
2754
+ held.push({
2755
+ table: source.sql.table,
2756
+ holders: source.sql.holders
2757
+ });
2758
+ }
2759
+ return held;
2760
+ }
2761
+ function indent(sql, by) {
2762
+ return sql.replaceAll(/^/gmu, by);
2763
+ }
2764
+ /**
2765
+ * Every source's rows of one instance, each compared with its own typed
2766
+ * `v_key_<n>`.
2767
+ */
2768
+ function sourceRowsOf(scope, sources) {
2769
+ return sources.map((source, index) => indent(source.holders.rows(scope, { id: `v_key_${String(index)}` }), " ")).join("\n union all\n");
2770
+ }
2771
+ function sourceKeys(sources) {
2772
+ return {
2773
+ declare: sources.map((source, index) => ` v_key_${String(index)} ${source.holders.idType};`).join("\n"),
2774
+ assign: (value, by) => sources.map((_, index) => `${by}v_key_${String(index)} := ${value};`).join("\n")
2775
+ };
2776
+ }
2777
+ function regclassOf(table) {
2778
+ return `${quoteLiteral(quoteQualified(table))}::regclass`;
2779
+ }
2780
+ function sourceTables(sources) {
2781
+ return [...new Set(sources.map((source) => quoteQualified(source.table)))];
2782
+ }
2783
+ /**
2784
+ * `min` and `max` over membership sources: the same commit-time check as on a
2785
+ * mapped table, counted over every source of the scope.
2786
+ */
2787
+ function sourceHoldersTriggerSql(ctx, scope, sources, counted) {
2788
+ const fn = qualified(ctx, `${OWNERSHIP.holders}_${scope}`);
2789
+ const keys = sourceKeys(sources);
2790
+ const rows = sourceRowsOf(scope, sources);
2791
+ const collect = sources.map((source) => ` if tg_relid = ${regclassOf(source.table)} then
2792
+ if tg_op in ('UPDATE', 'DELETE') then
2793
+ v_ids := v_ids || ${source.holders.id(scope, "old")};
2794
+ end if;
2795
+ if tg_op in ('INSERT', 'UPDATE') then
2796
+ v_ids := v_ids || ${source.holders.id(scope, "new")};
2797
+ end if;
2798
+ end if;`);
2799
+ const checks = counted.map((rule) => {
2800
+ const filters = ["h.live", `h.role = ${quoteLiteral(rule.role)}`];
2801
+ const kind = roleKindSql(ctx, rule.role, "h.via");
2802
+ if (kind !== void 0) filters.push(kind);
2803
+ const lines = [` select count(distinct h.user_id) into v_count
2804
+ from (
2805
+ ${rows}
2806
+ ) h
2807
+ where ${filters.join("\n and ")};`];
2808
+ if (rule.min > 0) lines.push(` if v_total > 0 and v_count < ${String(rule.min)} then
2809
+ raise exception using
2810
+ errcode = '23514',
2811
+ hint = 'last-holder',
2812
+ message = ${quoteLiteral(`permdock: ${scope} `)} || v_id || ${quoteLiteral(` keeps at least ${String(rule.min)} ${rule.role}`)};
2813
+ end if;`);
2814
+ if (rule.max !== void 0) lines.push(` if v_count > ${String(rule.max)} then
2815
+ raise exception using
2816
+ errcode = '23514',
2817
+ hint = 'max-holders',
2818
+ message = ${quoteLiteral(`permdock: ${scope} `)} || v_id || ${quoteLiteral(` has at most ${String(rule.max)} ${rule.role}`)};
2819
+ end if;`);
2820
+ return lines.join("\n");
2821
+ });
2822
+ const triggers = sourceTables(sources).map((table) => `drop trigger if exists ${objectName(OWNERSHIP.holders, scope)} on ${table};
2823
+ create constraint trigger ${objectName(OWNERSHIP.holders, scope)}
2824
+ after insert or update or delete on ${table}
2825
+ deferrable initially deferred
2826
+ for each row execute function ${fn}();`);
2827
+ return `-- ${scope}: holder counts (min / max) over the membership sources, checked at commit
2828
+ create or replace function ${fn}()
2829
+ returns trigger
2830
+ language plpgsql
2831
+ security definer
2832
+ set search_path = ''
2833
+ as $$
2834
+ declare
2835
+ v_ids text[] := '{}';
2836
+ v_id text;
2837
+ ${keys.declare}
2838
+ v_total bigint;
2839
+ v_count bigint;
2840
+ begin
2841
+ ${collect.join("\n")}
2842
+ foreach v_id in array v_ids loop
2843
+ continue when v_id is null;
2844
+ ${keys.assign("v_id", " ")}
2845
+ select count(*) into v_total
2846
+ from (
2847
+ ${rows}
2848
+ ) h;
2849
+ ${checks.join("\n")}
2850
+ end loop;
2851
+ return null;
2852
+ end;
2853
+ $$;
2854
+ ${triggers.join("\n")}`;
2855
+ }
2856
+ function collectChangesSql(changed) {
2857
+ return ` v_changes := v_changes || coalesce((select jsonb_agg(to_jsonb(c)) from (${changed}) c), '[]'::jsonb);`;
2858
+ }
2859
+ /**
2860
+ * `transferOnly` over membership sources: each source table's statement
2861
+ * triggers diff its transition tables, and the count after reads every source.
2862
+ */
2863
+ function sourceTransferTriggerSql(ctx, scope, sources, roles) {
2864
+ const fn = qualified(ctx, `${OWNERSHIP.transferOnly}_${scope}`);
2865
+ const keys = sourceKeys(sources);
2866
+ const list = `array[${roles.map(quoteLiteral).join(", ")}]::text[]`;
2867
+ const kind = kindFilterSql(ctx, "h.role", "h.via");
2868
+ 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})`;
2869
+ const branches = sources.map((source) => ` if tg_relid = ${regclassOf(source.table)} then
2870
+ if tg_op in ('INSERT', 'UPDATE') then
2871
+ ${collectChangesSql(changes(source, "permdock_new", "1"))}
2872
+ end if;
2873
+ if tg_op in ('UPDATE', 'DELETE') then
2874
+ ${collectChangesSql(changes(source, "permdock_old", "-1"))}
2875
+ end if;
2876
+ end if;`);
2877
+ const triggers = sourceTables(sources).flatMap((table) => [
2878
+ "insert",
2879
+ "update",
2880
+ "delete"
2881
+ ].map((op) => {
2882
+ const name = quoteIdent(`${OWNERSHIP.transferOnly}_${scope}_${op}`);
2883
+ return `drop trigger if exists ${name} on ${table};
2884
+ create trigger ${name}
2885
+ after ${op} on ${table}
2886
+ 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"}
2887
+ for each statement execute function ${fn}();`;
2888
+ }));
2889
+ return `-- ${scope}: transfer-only roles (${roles.join(", ")}) keep their holder count per statement, over the membership sources
2890
+ create or replace function ${fn}()
2891
+ returns trigger
2892
+ language plpgsql
2893
+ security definer
2894
+ set search_path = ''
2895
+ as $$
2896
+ declare
2897
+ v_changes jsonb := '[]'::jsonb;
2898
+ v_change record;
2899
+ v_after bigint;
2900
+ ${keys.declare}
2901
+ begin
2902
+ ${branches.join("\n")}
2903
+ for v_change in
2904
+ select x.id, x.role, sum(x.delta) as delta
2905
+ from jsonb_to_recordset(v_changes) x(id text, role text, delta bigint)
2906
+ group by x.id, x.role
2907
+ loop
2908
+ continue when v_change.delta = 0 or v_change.id is null;
2909
+ ${keys.assign("v_change.id", " ")}
2910
+ select count(distinct h.user_id) into v_after
2911
+ from (
2912
+ ${sourceRowsOf(scope, sources)}
2913
+ ) h
2914
+ where h.live
2915
+ and h.role = v_change.role${kind === void 0 ? "" : `\n and ${kind}`};
2916
+ if v_after > 0 and v_after - v_change.delta > 0 then
2917
+ raise exception using
2918
+ errcode = '23514',
2919
+ hint = 'transfer-only',
2920
+ message = 'permdock: ' || v_change.role || ${quoteLiteral(` in ${scope} `)} || v_change.id || ' moves only by transfer';
2921
+ end if;
2922
+ end loop;
2923
+ return null;
2924
+ end;
2925
+ $$;
2926
+ ${triggers.join("\n")}`;
2927
+ }
2928
+ function pairsSql(pairs) {
2929
+ return `values ${pairs.map((pair) => `(${quoteLiteral(pair.assigner)}, ${quoteLiteral(pair.role)})`).join(", ")}`;
2930
+ }
2931
+ /**
2932
+ * Membership rows of the membership sources for scope `name`, each source's
2933
+ * `select` comparing its user column with a variable `user` names.
2934
+ */
2935
+ function sourceRowsSql(sources, user) {
2936
+ const keep = sources.some((source) => source.sql.keeps);
2937
+ return sources.map((source) => source.sql.select(user(source), keep).replaceAll(/^/gmu, " ")).join("\n union all\n");
2938
+ }
2939
+ // src/cli/rls/permission-keys.ts
2940
+ /**
2941
+ * The helpers that take a permission key instead of a grant key. Names are part
2942
+ * of the SQL contract.
2943
+ */
2944
+ const PERMISSION_HELPERS = {
2945
+ grantKeys: "grant_keys",
2946
+ has: "permdock_has_permission",
2947
+ hasFor: "permdock_has_permission_for"
2948
+ };
2949
+ /**
2950
+ * `permitted_<scope>_permission_keys(p_id)`: every permission key the subject
2951
+ * holds on one instance.
2952
+ */
2953
+ function permissionKeysHelper(scope) {
2954
+ permittedIdsHelper(scope);
2955
+ return `permitted_${scope}_permission_keys`;
2956
+ }
2957
+ /**
2958
+ * `permitted_<scope>_permission_keys_for(p_user, p_id)`, written in `database`
2959
+ * mode.
2960
+ */
2961
+ function permissionKeysForHelper(scope) {
2962
+ return `${permissionKeysHelper(scope)}_for`;
2963
+ }
2964
+ /** `permitted_<scope>_ids_by_permission(p_permission)`. */
2965
+ function permittedByPermissionHelper(scope) {
2966
+ return `${permittedIdsHelper(scope)}_by_permission`;
2967
+ }
2968
+ /**
2969
+ * A grant's `requires` as SQL: the subject holds `key` globally, or on the
2970
+ * row's instance of a scope that partitions it, through the helpers by
2971
+ * permission key, as `requirementCondition` does in process.
2972
+ */
2973
+ function requiresSql(ctx, key, resource) {
2974
+ const literal = quoteLiteral(key);
2975
+ return `(${[`(select ${qualified(ctx, PERMISSION_HELPERS.has)}(${literal}))`, ...(resource === void 0 ? [] : partitionsOf(resource, ctx.scopes)).map((scope) => {
2976
+ const field = scopeField(resource, scope, ctx.scopes) ?? scope;
2977
+ return `${quoteIdent(field)} = any(array(select ${qualified(ctx, checkName(permittedByPermissionHelper(scope)))}(${literal})))`;
2978
+ })].join(" or ")})`;
2979
+ }
2980
+ /**
2981
+ * Postgres truncates an identifier past 63 bytes, which would merge two
2982
+ * helpers.
2983
+ */
2984
+ function checkName(name) {
2985
+ 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`);
2986
+ return name;
2987
+ }
2988
+ function grantsFunction(ctx, grants, renamed, anonExecute) {
2989
+ const fn = qualified(ctx, PERMISSION_HELPERS.grantKeys);
2990
+ const map = Object.fromEntries([...grants].toSorted(byKey));
2991
+ const current = Object.keys(renamed).length === 0 ? "p_permission" : `coalesce(${quoteLiteral(JSON.stringify(renamed))}::jsonb ->> p_permission, p_permission)`;
2992
+ 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
2993
+ create or replace function ${fn}(p_permission text, p_scope text, p_effect text default 'allow')
2994
+ returns setof text
2995
+ language sql
2996
+ stable
2997
+ set search_path = ''
2998
+ as $$
2999
+ select g.grant_key
3000
+ from pg_catalog.jsonb_array_elements_text(coalesce(
3001
+ ${quoteLiteral(JSON.stringify(map))}::jsonb -> p_scope -> ${current} -> p_effect,
3002
+ '[]'::jsonb
3003
+ )) g(grant_key)
3004
+ $$;
3005
+ ${grantsSql(fn, "text, text, text", anonExecute)}`;
3006
+ }
3007
+ function grantsSql(fn, args, anonExecute) {
3008
+ return anonExecute ? `revoke execute on function ${fn}(${args}) from public;
3009
+ grant execute on function ${fn}(${args}) to anon, authenticated;` : `revoke execute on function ${fn}(${args}) from public, anon;
3010
+ grant execute on function ${fn}(${args}) to authenticated;`;
3011
+ }
3012
+ function definerSql(fn, params, returns, sql, parallelSafe) {
3013
+ return `create or replace function ${fn}(${params})
3014
+ returns ${returns}
3015
+ language sql
3016
+ stable
3017
+ security definer
3018
+ cost 1000${returns.startsWith("setof") ? "\nrows 10" : ""}${parallelSafe ? "\nparallel safe" : ""}
3019
+ set search_path = ''
3020
+ as $$
3021
+ ${sql}
3022
+ $$;`;
3023
+ }
3024
+ function heldSql(at, effect) {
3025
+ return `select 1 from pdk_h where pdk_h.key = pdk_k.key and pdk_h.scope = ${quoteLiteral(at)} and pdk_h.effect = '${effect}'`;
3026
+ }
3027
+ function keysFunction(fn, params, body, access, parallelSafe) {
3028
+ return `create or replace function ${fn}(${params})
3029
+ returns setof text
3030
+ ${functionBody(body, parallelSafe).replace("set search_path = ''", "set search_path = ''\nset jit = off")}
3031
+ ${access}`;
3032
+ }
3033
+ /**
3034
+ * The permission-key forms of the helpers: `grant_keys`, which maps a
3035
+ * permission key to the grant keys of its unconditional allows on a scope (or
3036
+ * every deny key, or the conditioned allow or deny keys),
3037
+ * `permdock_has_permission(p_permission)` and one
3038
+ * `permitted_<scope>_ids_by_permission(p_permission)` per scope, plus their
3039
+ * `_for(p_user, ...)` forms in `database` mode. They answer with the
3040
+ * unconditional allows minus any deny, so a permission whose allows all carry a
3041
+ * row condition answers nothing. The
3042
+ * `permitted_<scope>_ids_by_permission(p_permission, p_conditioned)` overload
3043
+ * with `true` also lists the instances a conditioned allow reaches and
3044
+ * subtracts only unconditional denies, leaving the row condition to the caller,
3045
+ * as `permittedIds(..., { conditioned: true })` does in process.
3046
+ */
3047
+ function permissionHelpersSql(ctx, grants, renamed, anonExecute) {
3048
+ const parallel = !memoizes(ctx);
3049
+ const definer = (fn, params, returns, sql) => definerSql(fn, params, returns, sql, parallel);
3050
+ const keys = qualified(ctx, PERMISSION_HELPERS.grantKeys);
3051
+ const allowKeys = (scope) => `${keys}(p_permission, ${quoteLiteral(scope)}) g(grant_key)`;
3052
+ const denyKeys = (scope) => `${keys}(p_permission, ${quoteLiteral(scope)}, 'deny') g(grant_key)`;
3053
+ const has = (helper, user) => ` select exists (select 1 from ${allowKeys("global")} where ${helper}(${user}g.grant_key))
3054
+ and not exists (select 1 from ${denyKeys("global")} where ${helper}(${user}g.grant_key))`;
3055
+ const ids = (helper, scope, user) => ` select a.id
3056
+ from ${allowKeys(scope)}
3057
+ cross join lateral ${helper}(${user}g.grant_key) a(id)
3058
+ except
3059
+ select d.id
3060
+ from ${denyKeys(scope)}
3061
+ cross join lateral ${helper}(${user}g.grant_key) d(id)`;
3062
+ const conditionedIds = (helper, scope, user) => ` select a.id
3063
+ from (
3064
+ select g.grant_key from ${allowKeys(scope)}
3065
+ union all
3066
+ select g.grant_key from ${keys}(p_permission, ${quoteLiteral(scope)}, 'conditioned-allow') g(grant_key)
3067
+ where p_conditioned
3068
+ ) g
3069
+ cross join lateral ${helper}(${user}g.grant_key) a(id)
3070
+ except
3071
+ select d.id
3072
+ from (
3073
+ select g.grant_key from ${denyKeys(scope)}
3074
+ except
3075
+ select g.grant_key from ${keys}(p_permission, ${quoteLiteral(scope)}, 'conditioned-deny') g(grant_key)
3076
+ where p_conditioned
3077
+ ) g
3078
+ cross join lateral ${helper}(${user}g.grant_key) d(id)`;
3079
+ const keysBody = (scope, bodies, filtered) => {
3080
+ const rows = ["global", scope].flatMap((at) => Object.entries(grants.get(at) ?? {}).toSorted(byKey).flatMap(([key, effects]) => ["allow", "deny"].flatMap((effect) => effects[effect].map((grant) => `(${[
3081
+ key,
3082
+ at,
3083
+ effect,
3084
+ grant
3085
+ ].map(quoteLiteral).join(", ")})`))));
3086
+ if (new Set(["global", scope].flatMap((at) => Object.entries(grants.get(at) ?? {}).flatMap(([key, effects]) => effects.allow.length > 0 ? [key] : []))).size === 0) return {
3087
+ sql: " select null::text where false",
3088
+ vars: []
3089
+ };
3090
+ const hasBody = bodies.has;
3091
+ const idsBody = bodies.ids(scope);
3092
+ return {
3093
+ sql: ` with pdk_m(key, scope, effect, grant_key) as (
3094
+ values
3095
+ ${rows.join(",\n ")}
3096
+ ),
3097
+ pdk_w as (
3098
+ select pdk_m.key, pdk_m.scope, pdk_m.effect, pdk_m.grant_key
3099
+ 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))` : ""}
3100
+ ),
3101
+ pdk_g as (
3102
+ ${hasBody.sql}
3103
+ ),
3104
+ pdk_s as (
3105
+ select pdk_i.grant_key
3106
+ from (
3107
+ ${idsBody.sql}
3108
+ ) pdk_i(id, grant_key)
3109
+ where pdk_i.id = p_id
3110
+ ),
3111
+ pdk_h as (
3112
+ select pdk_w.key, pdk_w.scope, pdk_w.effect
3113
+ from pdk_w
3114
+ where (pdk_w.scope = 'global' and pdk_w.grant_key in (select pdk_g.grant_key from pdk_g))
3115
+ or (pdk_w.scope = ${quoteLiteral(scope)} and pdk_w.grant_key in (select pdk_s.grant_key from pdk_s))
3116
+ )
3117
+ select pdk_k.key
3118
+ from (select distinct pdk_w.key from pdk_w where pdk_w.effect = 'allow') pdk_k
3119
+ where (exists (${heldSql("global", "allow")}) and not exists (${heldSql("global", "deny")}))
3120
+ or (exists (${heldSql(scope, "allow")}) and not exists (${heldSql(scope, "deny")}))
3121
+ order by 1`,
3122
+ vars: [.../* @__PURE__ */ new Set([...hasBody.vars, ...idsBody.vars])]
3123
+ };
3124
+ };
3125
+ const chunks = [grantsFunction(ctx, grants, renamed, anonExecute), `-- the helpers by permission key: unconditional allows minus any deny
3126
+ ${definer(qualified(ctx, PERMISSION_HELPERS.has), "p_permission text", "boolean", has(qualified(ctx, HELPERS.has), ""))}
3127
+ ${grantsSql(qualified(ctx, PERMISSION_HELPERS.has), "text", anonExecute)}`];
3128
+ for (const scope of ctx.scopes) {
3129
+ const fn = qualified(ctx, checkName(permittedByPermissionHelper(scope.name)));
3130
+ chunks.push(`${definer(fn, "p_permission text", `setof ${scopeTypeOf(ctx, scope.name)}`, ids(qualified(ctx, permittedIdsHelper(scope.name)), scope.name, ""))}
3131
+ ${grantsSql(fn, "text", anonExecute)}`);
3132
+ const keysFn = qualified(ctx, checkName(permissionKeysHelper(scope.name)));
3133
+ const type = scopeTypeOf(ctx, scope.name);
3134
+ const caller = grantBodies({
3135
+ ...ctx,
3136
+ grantSet: true
3137
+ });
3138
+ 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
3139
+ ${keysFunction(keysFn, `p_id ${type}`, keysBody(scope.name, caller, false), grantsSql(keysFn, type, anonExecute), parallel)}
3140
+ ${keysFunction(keysFn, `p_id ${type}, p_keys text[]`, keysBody(scope.name, caller, true), grantsSql(keysFn, `${type}, text[]`, anonExecute), parallel)}`);
3141
+ chunks.push(`-- with p_conditioned true, also the instances a conditioned allow reaches, minus only unconditional denies: the caller applies the row condition
3142
+ ${definer(fn, "p_permission text, p_conditioned boolean", `setof ${scopeTypeOf(ctx, scope.name)}`, conditionedIds(qualified(ctx, permittedIdsHelper(scope.name)), scope.name, ""))}
3143
+ ${grantsSql(fn, "text, boolean", anonExecute)}`);
3144
+ }
3145
+ if (ctx.authorize !== "database") return `${chunks.join("\n\n")}\n`;
3146
+ const user = ctx.dialect === "supabase" ? "uuid" : "text";
3147
+ const revoke = (fn) => `revoke execute on function ${fn}(${user}, text) from public, anon, authenticated;`;
3148
+ const hasFor = qualified(ctx, PERMISSION_HELPERS.hasFor);
3149
+ chunks.push(`-- the same for a user the caller names; no client role may execute them
3150
+ ${definer(hasFor, `p_user ${user}, p_permission text`, "boolean", has(qualified(ctx, HELPERS.hasFor), "p_user, "))}
3151
+ ${revoke(hasFor)}`);
3152
+ for (const scope of ctx.scopes) {
3153
+ const fn = qualified(ctx, checkName(`${permittedByPermissionHelper(scope.name)}_for`));
3154
+ 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, "))}
3155
+ ${revoke(fn)}`);
3156
+ 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, "))}
3157
+ revoke execute on function ${fn}(${user}, text, boolean) from public, anon, authenticated;`);
3158
+ const keysFor = qualified(ctx, checkName(permissionKeysForHelper(scope.name)));
3159
+ const type = scopeTypeOf(ctx, scope.name);
3160
+ const named = grantBodies({
3161
+ ...forUserContext(ctx),
3162
+ grantSet: true
3163
+ });
3164
+ 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)}
3165
+ ${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)}`);
3166
+ }
3167
+ return `${chunks.join("\n\n")}\n`;
3168
+ }
3169
+ // src/cli/sql/tables.ts
3170
+ /**
3171
+ * The `schema.table` an `rls.tables` entry names, or `resource` when it names
3172
+ * none or is `false`.
3173
+ */
3174
+ function tableNameOf(entry, resource, tables) {
3175
+ if (entry === void 0 || entry === false) return resource;
3176
+ if (typeof entry === "string") return entry;
3177
+ if ("tableOf" in entry) {
3178
+ const owner = tables?.[entry.tableOf];
3179
+ return typeof owner === "object" && "tableOf" in owner ? entry.tableOf : tableNameOf(owner, entry.tableOf);
3180
+ }
3181
+ return entry.table ?? resource;
3182
+ }
3183
+ /**
3184
+ * `rls.tables` as resource to table name, the `via` objects reduced to their
3185
+ * `table` and the `false` entries left out.
3186
+ */
3187
+ function tableNames(tables) {
3188
+ return tables === void 0 ? void 0 : Object.fromEntries(Object.entries(tables).filter(([, entry]) => entry !== false).map(([resource, entry]) => [resource, tableNameOf(entry, resource, tables)]));
3189
+ }
3190
+ function isOwner(entry) {
3191
+ return typeof entry === "object" && !("tableOf" in entry);
3192
+ }
3193
+ /**
3194
+ * The resources `rls.tables` marks `false` or `{ tableOf }`, plus every
3195
+ * resource an owner's `also` names: no policies of their own, their grants only
3196
+ * seeded.
3197
+ */
3198
+ function tablelessResources(tables) {
3199
+ const out = /* @__PURE__ */ new Set();
3200
+ for (const [resource, entry] of Object.entries(tables ?? {})) {
3201
+ if (entry === false || typeof entry === "object" && "tableOf" in entry) out.add(resource);
3202
+ if (isOwner(entry)) for (const name of entry.also ?? []) out.add(name);
3203
+ }
3204
+ return out;
3205
+ }
3206
+ /**
3207
+ * Rejects a `{ tableOf }` entry that names its own resource, a `false` entry or
3208
+ * another `{ tableOf }` entry: the owner must have a table of its own.
3209
+ */
3210
+ function checkSharedTables(tables) {
3211
+ for (const [resource, entry] of Object.entries(tables ?? {})) {
3212
+ if (typeof entry === "string" || entry === false || !("tableOf" in entry)) continue;
3213
+ const owner = tables?.[entry.tableOf];
3214
+ 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`);
3215
+ }
3216
+ }
3217
+ function singular(name) {
3218
+ if (name.endsWith("ies")) return `${name.slice(0, -3)}y`;
3219
+ if (name.endsWith("sses")) return name.slice(0, -2);
3220
+ return name.endsWith("s") && !name.endsWith("ss") ? name.slice(0, -1) : name;
3221
+ }
3222
+ /** The `via` entries of `rls.tables`, by resource. */
3223
+ function resolveVias(tables, scopes, dialect) {
3224
+ const out = {};
3225
+ for (const [resource, entry] of Object.entries(tables ?? {})) {
3226
+ if (!isOwner(entry) || entry.via === void 0) continue;
3227
+ const { via } = entry;
3228
+ const scope = via.scope ?? scopes[0]?.name;
3229
+ 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(", ")})`);
3230
+ const name = singular(via.table.slice(via.table.lastIndexOf(".") + 1));
3231
+ out[resource] = {
3232
+ helper: permittedIdsHelper(name),
3233
+ key: via.key ?? `${name}_id`,
3234
+ scope,
3235
+ table: via.table.includes(".") ? via.table : `public.${via.table}`,
3236
+ column: via.column,
3237
+ id: via.id ?? "id",
3238
+ type: via.type ?? (dialect === "supabase" ? "uuid" : "text")
3239
+ };
3240
+ }
3241
+ const helpers = /* @__PURE__ */ new Map();
3242
+ for (const [resource, via] of Object.entries(out)) {
3243
+ const seen = helpers.get(via.helper);
3244
+ 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`);
3245
+ helpers.set(via.helper, via);
3246
+ }
3247
+ return Object.keys(out).length === 0 ? void 0 : out;
3248
+ }
3249
+ export { tokenScopeUnlimitedSql as A, apiKeyUnlimitedSql as B, forUserContext as C, seedSql as D, memoReadsSql as E, capabilityAccessSql as F, POLICY_BUNDLE_FORMAT as G, HOOK_TEAM_READER as H, API_KEY_ALLOWS as I, closureBackfillSql as J, bundleLoaderSql as K, apiKeyAllowsCall as L, memoReadTriggersSql as M, guardAuthAdminGrants as N, TOKEN_SCOPE_ALLOWS as O, unguardAuthAdminGrants as P, graphSql as Q, apiKeyClaimSql as R, accessSql as S, helpersSql as T, hookTeamReader as U, apiKeysPlan as V, hookTeamsHelper as W, graphIdsSql as X, closureDepths as Y, graphPlan as Z, sourceTransferTriggerSql as _, tablelessResources as a, ASSIGNMENTS as b, permissionHelpersSql as c, permittedByPermissionHelper as d, requiresSql as f, sourceRowsSql as g, sourceHoldersTriggerSql as h, tableNames as i, tokenScopesPlan as j, tokenScopeAllowsCall as k, permissionKeysForHelper as l, pairsSql as m, resolveVias as n, PERMISSION_HELPERS as o, holderSources as p, policyBundle as q, tableNameOf as r, checkName as s, checkSharedTables as t, permissionKeysHelper as u, holdersTriggerSql as v, grantBodies as w, OWNERSHIP as x, transferTriggerSql as y, apiKeyFields as z };