permdock 0.25.1 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (969) hide show
  1. package/README.md +1 -1
  2. package/dist/2020-bJfT8aIA.js +6760 -0
  3. package/dist/a2a/index.d.ts +5 -9
  4. package/dist/a2a/index.js +13 -15
  5. package/dist/adapter-context-lHq_i_77.js +28 -0
  6. package/dist/adoption-scan-b0_Xpab8.js +106 -0
  7. package/dist/agent/index.d.ts +2 -2
  8. package/dist/agent/index.js +1 -1
  9. package/dist/ai-sdk/index.d.ts +4 -6
  10. package/dist/ai-sdk/index.js +6 -7
  11. package/dist/annotate-doc-BCOCOrq_.js +214 -0
  12. package/dist/annotate-routes-BvSuEht3.js +75 -0
  13. package/dist/annotate-uZVGIRym.js +25 -0
  14. package/dist/app/index.d.ts +2 -103
  15. package/dist/app/index.js +1 -114
  16. package/dist/app-data-DbSPSPIl.js +62 -0
  17. package/dist/approval-header-BvszJE3l.js +25 -0
  18. package/dist/approval-normalize-Cpp8R0rY.js +190 -0
  19. package/dist/approval-prompt-C-vjNZyd.d.ts +57 -0
  20. package/dist/approval-prompt-Covyx_DB.js +60 -0
  21. package/dist/approval-required-B-R4Yw3J.js +5 -0
  22. package/dist/approvals/index.d.ts +5 -5
  23. package/dist/approvals/index.js +8 -8
  24. package/dist/approvals-7jHYXocE.js +1039 -0
  25. package/dist/approvers-BkY_ZfWl.js +76 -0
  26. package/dist/arazzo-DMmcumRx.js +76 -0
  27. package/dist/arazzo-Hxerfx3_.js +35 -0
  28. package/dist/args-0EWFk-4S.js +311 -0
  29. package/dist/astro/index.d.ts +6 -8
  30. package/dist/astro/index.js +3 -4
  31. package/dist/audience-DauhRBNg.js +54 -0
  32. package/dist/auth-WHKYWtnS.js +187 -0
  33. package/dist/authz-topic-D8x24Jv-.js +14 -0
  34. package/dist/authzen/index.d.ts +37 -22
  35. package/dist/authzen/index.js +69 -27
  36. package/dist/automation-CUcWz8uu.d.ts +122 -0
  37. package/dist/automation-CpPdFX91.js +157 -0
  38. package/dist/base-url--yJPQlIK.js +8 -0
  39. package/dist/better-auth/index.d.ts +2 -8
  40. package/dist/better-auth/index.js +10 -13
  41. package/dist/better-supabase/index.d.ts +141 -95
  42. package/dist/better-supabase/index.js +239 -794
  43. package/dist/better-supabase-DSbs4MtQ.js +201 -0
  44. package/dist/bind-B3MHrzw4.d.ts +56 -0
  45. package/dist/bind-up3QptTt.js +124 -0
  46. package/dist/body-W1_8r6Tw.js +9 -0
  47. package/dist/body-text-B-m3p-qY.js +55 -0
  48. package/dist/boundary--5Swp7sN.js +18 -0
  49. package/dist/boundary-DJqHADKu.d.ts +22 -0
  50. package/dist/budget-5LJ8kfZk.d.ts +12 -0
  51. package/dist/budget-BH81q2cj.js +19 -0
  52. package/dist/build-instance-hLKYe3-E.js +30 -0
  53. package/dist/canonical-json-BibZkXtE.js +28 -0
  54. package/dist/capability-CVt3lpVK.d.ts +128 -0
  55. package/dist/capability-_ZsyfYxU.js +204 -0
  56. package/dist/casbin-CYwbggCS.js +29 -0
  57. package/dist/casbin-Co1KcLWU.js +241 -0
  58. package/dist/casl-CrltbDPa.js +23 -0
  59. package/dist/casl-D7n7yE-h.js +307 -0
  60. package/dist/catalog/index.d.ts +6 -20
  61. package/dist/catalog/index.js +13 -15
  62. package/dist/catalog-B3MJShnZ.js +51 -0
  63. package/dist/catalog-CgK_L4Qf.js +1 -0
  64. package/dist/catalog-DyC3LKc7.js +130 -0
  65. package/dist/catalog-doc-Bp5khmCG.js +352 -0
  66. package/dist/catalog-fingerprint-DAWZARy6.js +31 -0
  67. package/dist/catalog-operations-dxuOZr4J.js +59 -0
  68. package/dist/catalog-path-bG0XxHMu.js +11 -0
  69. package/dist/challenge-CjwmjcuX.js +518 -0
  70. package/dist/chat/index.d.ts +1 -1
  71. package/dist/chat/index.js +10 -13
  72. package/dist/chat-sdk/index.d.ts +3 -11
  73. package/dist/chat-sdk/index.js +7 -11
  74. package/dist/checks-DSm45qH7.js +71 -0
  75. package/dist/claims-map-BGbpbvGD.js +15 -0
  76. package/dist/claims-map-CLKQWxJG.d.ts +33 -0
  77. package/dist/claims-size-DcjhvUv5.js +58 -0
  78. package/dist/claude-agent/index.d.ts +3 -5
  79. package/dist/claude-agent/index.js +4 -5
  80. package/dist/clerk/index.d.ts +4 -8
  81. package/dist/clerk/index.js +7 -8
  82. package/dist/cli/bin.js +6 -7
  83. package/dist/cli/generate/watch-worker.d.ts +20 -0
  84. package/dist/cli/generate/watch-worker.js +69 -0
  85. package/dist/cli/index.d.ts +11 -20
  86. package/dist/cli/index.js +8 -8
  87. package/dist/cli/plugins/app.d.ts +18 -0
  88. package/dist/cli/plugins/app.js +26 -0
  89. package/dist/cli/plugins/better-supabase.d.ts +10 -0
  90. package/dist/cli/plugins/better-supabase.js +18 -0
  91. package/dist/cli/plugins/openapi.d.ts +19 -0
  92. package/dist/cli/plugins/openapi.js +40 -0
  93. package/dist/cli/plugins/powersync.d.ts +7 -0
  94. package/dist/cli/plugins/powersync.js +29 -0
  95. package/dist/cli/plugins/rls.d.ts +8 -0
  96. package/dist/cli/plugins/rls.js +27 -0
  97. package/dist/cli/plugins/schemas.d.ts +13 -0
  98. package/dist/cli/plugins/schemas.js +23 -0
  99. package/dist/cli/plugins/scim.d.ts +10 -0
  100. package/dist/cli/plugins/scim.js +32 -0
  101. package/dist/cli/plugins/supabase-hook.d.ts +13 -0
  102. package/dist/cli/plugins/supabase-hook.js +40 -0
  103. package/dist/cli/plugins/supabase.d.ts +27 -0
  104. package/dist/cli/plugins/supabase.js +69 -0
  105. package/dist/cli/plugins/ui.d.ts +11 -0
  106. package/dist/cli/plugins/ui.js +19 -0
  107. package/dist/client-V95IvZsF.d.ts +43 -0
  108. package/dist/client-subject-v89t811z.d.ts +25 -0
  109. package/dist/clients-Bb_33pRE.js +22 -0
  110. package/dist/clients-DGcyFDCc.d.ts +10 -0
  111. package/dist/cloud/index.d.ts +8 -26
  112. package/dist/cloud/index.js +22 -28
  113. package/dist/cloud-BfEI9TLS.js +85 -0
  114. package/dist/codemod-DwH0IZ2x.js +2159 -0
  115. package/dist/codemod-p67ePW25.js +35 -0
  116. package/dist/collect-BJZsuBW4.js +535 -0
  117. package/dist/collect-CPvCXMQ-.js +1 -0
  118. package/dist/collect-CpGnmGpL.js +54 -0
  119. package/dist/command-9GAzSI7E.js +5 -0
  120. package/dist/compact-C4LFuqbW.js +28 -0
  121. package/dist/compare-dfHDj8kT.js +11 -0
  122. package/dist/compile/index.d.ts +2 -2
  123. package/dist/compile/index.js +1 -1
  124. package/dist/compile-BUKXrueE.js +685 -0
  125. package/dist/compile-Blrr5WWw.js +724 -0
  126. package/dist/compile-D8c1nFGy.d.ts +118 -0
  127. package/dist/completion-CfrZOGcB.js +150 -0
  128. package/dist/conditions-CkHgXoZB.js +385 -0
  129. package/dist/config-D6gh_xvs.js +25 -0
  130. package/dist/config-iyy90IOU.js +143 -0
  131. package/dist/config-report-BaHEBpt-.js +55 -0
  132. package/dist/config-shape-B6tdyBju.js +149 -0
  133. package/dist/connection-BnoSqYU1.js +196 -0
  134. package/dist/connector-schema-BSRMyq4M.js +433 -0
  135. package/dist/constants-PCJiir_3.js +19 -0
  136. package/dist/context-DmH-Eyvx.js +95 -0
  137. package/dist/convex/index.d.ts +5 -9
  138. package/dist/convex/index.js +7 -8
  139. package/dist/core-CnC47rSf.d.ts +200 -0
  140. package/dist/core-DKqrD_xW.js +338 -0
  141. package/dist/coverage-DL7JCZmb.d.ts +133 -0
  142. package/dist/coverage-nFSMjFxH.js +42 -0
  143. package/dist/create-BAMPoEga.js +133 -0
  144. package/dist/create-BsRcXm_m.d.ts +125 -0
  145. package/dist/create-D3oXoXxM.js +373 -0
  146. package/dist/create-DeQ5t8mZ.d.ts +124 -0
  147. package/dist/create-sGl1ccTp.d.ts +185 -0
  148. package/dist/credential-ke0KMQeB.js +430 -0
  149. package/dist/credentials-6ZWbJ-Re.js +72 -0
  150. package/dist/credentials-BfzdL5kv.d.ts +123 -0
  151. package/dist/credentials-DOeqknte.js +309 -0
  152. package/dist/decide-set-CgNcE6pP.js +99 -0
  153. package/dist/deciding-columns-BnglEKqU.js +143 -0
  154. package/dist/decision-hHv4UZgy.js +20 -0
  155. package/dist/define-permdock-BLpQ0m95.d.ts +99 -0
  156. package/dist/define-permdock-CIxHBykk.js +148 -0
  157. package/dist/definition-options-9o8Hdww3.js +370 -0
  158. package/dist/delegation-BaUNCrE_.js +263 -0
  159. package/dist/delegation-input-7Y5Rlja7.js +18 -0
  160. package/dist/delivery/index.d.ts +4 -4
  161. package/dist/delivery/index.js +5 -5
  162. package/dist/delivery-Cb3VCij5.js +555 -0
  163. package/dist/delivery-event-D5b9yhaJ.js +39 -0
  164. package/dist/denied-text-D6JJTDr3.d.ts +20 -0
  165. package/dist/describe-B7EosIKA.js +100 -0
  166. package/dist/describe-lAafaRQQ.d.ts +43 -0
  167. package/dist/device-f3JEnqa0.js +195 -0
  168. package/dist/diff-BIqibFnm.js +464 -0
  169. package/dist/diff-n6LONVwL.js +36 -0
  170. package/dist/digest-BaP8bQzX.js +26 -0
  171. package/dist/digest-BcIZRYvp.d.ts +17 -0
  172. package/dist/doctor-Bg12v-8M.js +4847 -0
  173. package/dist/doctor-DCsyH7YR.js +53 -0
  174. package/dist/drizzle/index.d.ts +5 -9
  175. package/dist/drizzle/index.js +5 -6
  176. package/dist/elysia/index.d.ts +6 -8
  177. package/dist/elysia/index.js +6 -7
  178. package/dist/env-hbYumkRp.js +7 -0
  179. package/dist/errors-DOSkVeTC.js +127 -0
  180. package/dist/errors-DUJ7wLlE.d.ts +137 -0
  181. package/dist/errors-Da88YLm5.js +26 -0
  182. package/dist/errors-DgLOqc6j.js +148 -0
  183. package/dist/errors-KngVdJT9.d.ts +12 -0
  184. package/dist/evaluate-D8SdfP3h.js +1948 -0
  185. package/dist/evaluations-BQkpE7hC.js +609 -0
  186. package/dist/evaluations-K9qglDP7.d.ts +36 -0
  187. package/dist/evaluator-Dlhn2d7D.js +2 -0
  188. package/dist/evaluator-eager-UuJK6NX_.js +8 -0
  189. package/dist/eve/index.d.ts +11 -10
  190. package/dist/eve/index.js +7 -8
  191. package/dist/event-time-ChIrhzy5.js +26 -0
  192. package/dist/execute-SN8_dlch.js +166 -0
  193. package/dist/express/index.d.ts +6 -8
  194. package/dist/express/index.js +6 -7
  195. package/dist/fastify/index.d.ts +5 -11
  196. package/dist/fastify/index.js +6 -8
  197. package/dist/fetch-adapter-gmTCu4FR.d.ts +32 -0
  198. package/dist/fetch-adapter-ovZdSvlT.js +124 -0
  199. package/dist/fields-6d1j-q3c.js +502 -0
  200. package/dist/fields-C0L2FoZk.js +25 -0
  201. package/dist/files-DAR51W3J.js +157 -0
  202. package/dist/files-DuV7wRim.js +139 -0
  203. package/dist/fixtures-Bm0G0A7H.js +79 -0
  204. package/dist/flags-C0e-BzGW.js +112 -0
  205. package/dist/freeze-DGfJq_j2.js +86 -0
  206. package/dist/from-snapshot-CCDF_ihX.js +173 -0
  207. package/dist/gen-B4GUqsfM.js +1160 -0
  208. package/dist/gen-BC66z5Fd.js +1 -0
  209. package/dist/gen-kind-Bahz_i3U.js +67 -0
  210. package/dist/gen-kind-DFQnQwFN.d.ts +13 -0
  211. package/dist/generate-5_kz2309.js +305 -0
  212. package/dist/generate-B-msjuaO.js +2339 -0
  213. package/dist/generate-CbtjKcjn.js +67 -0
  214. package/dist/generate-DhP0jQDR.js +97 -0
  215. package/dist/generate-options-BDgadlwe.js +1104 -0
  216. package/dist/grantee-BPUG6f0r.js +109 -0
  217. package/dist/grantee-conditions-Dob6QQAc.js +270 -0
  218. package/dist/grantee-match-CFQ-LRcL.js +147 -0
  219. package/dist/grants-BzjbUCdR.js +139 -0
  220. package/dist/graph-sql-Ds3nbevr.d.ts +27 -0
  221. package/dist/h3/index.d.ts +4 -6
  222. package/dist/h3/index.js +4 -5
  223. package/dist/headers-D1oRr-js.d.ts +8 -0
  224. package/dist/helpers-DSmj6SHi.js +533 -0
  225. package/dist/hono/index.d.ts +6 -8
  226. package/dist/hono/index.js +7 -8
  227. package/dist/hook-sql-BIR4fL7i.js +3412 -0
  228. package/dist/hosted-DMJKJPoc.js +361 -0
  229. package/dist/hosted-DUbuh0Td.d.ts +100 -0
  230. package/dist/http-BUIYu1Kc.d.ts +10 -0
  231. package/dist/http-BbX_Ou3_.js +48 -0
  232. package/dist/http-C9jDw_bZ.js +82 -0
  233. package/dist/http-dNltTpC8.js +71 -0
  234. package/dist/ids-0QDIxtxL.js +53 -0
  235. package/dist/import-BZi1tZxq.js +318 -0
  236. package/dist/import-BqoDHpFt.js +1158 -0
  237. package/dist/index-BXz-XXC3.d.ts +1108 -0
  238. package/dist/index-CVuc3E1O.d.ts +196 -0
  239. package/dist/index-Cq9N5B92.d.ts +506 -0
  240. package/dist/index-D8A1d_Tt.d.ts +214 -0
  241. package/dist/index-DegTwZxD.d.ts +93 -0
  242. package/dist/index-O0qbI8Ha.d.ts +221 -0
  243. package/dist/index.d.ts +24 -25
  244. package/dist/index.js +47 -46
  245. package/dist/init-9cqnSJWG.js +95 -0
  246. package/dist/init-K3tKOwf4.js +94 -0
  247. package/dist/instance-options-B4MD2wgl.d.ts +9 -0
  248. package/dist/instance-options-CLErhA76.js +23 -0
  249. package/dist/instance-snapshot-DdGOpSfN.js +716 -0
  250. package/dist/instant-Ih5riY_A.js +18 -0
  251. package/dist/interactive-only-BZu9rLpa.js +1567 -0
  252. package/dist/internals-D58TnmDB.js +19 -0
  253. package/dist/json-schema-SDkWXxhu.d.ts +38 -0
  254. package/dist/json-schema-jtX26ydD.js +148 -0
  255. package/dist/jwt/index.d.ts +6 -24
  256. package/dist/jwt/index.js +18 -26
  257. package/dist/kernel-Dn6pKMAF.js +423 -0
  258. package/dist/kysely/index.d.ts +5 -9
  259. package/dist/kysely/index.js +5 -6
  260. package/dist/lazy-provider-CydlnKkS.d.ts +4 -0
  261. package/dist/lazy-provider-DG5rMeqL.js +28 -0
  262. package/dist/limits-DpTxX6N4.js +166 -0
  263. package/dist/live-options-CIUmc-YQ.js +70 -0
  264. package/dist/load-BPzIqlGB.js +1 -0
  265. package/dist/load-CZnlAyZ8.js +98 -0
  266. package/dist/load-jose-CjzIBSKI.js +7 -0
  267. package/dist/login-C1I5KIsK.js +67 -0
  268. package/dist/login-CP0UxnLw.js +255 -0
  269. package/dist/lru-Cp-AEvpR.js +27 -0
  270. package/dist/manifest-B-8d2lhG.js +45 -0
  271. package/dist/manifest-CRHphHxo.d.ts +362 -0
  272. package/dist/manifest-DvS2IoXo.js +399 -0
  273. package/dist/manifest-json-DMaBWmcG.js +8 -0
  274. package/dist/manifest-schema-DJY5Q_pR.js +507 -0
  275. package/dist/map-claims-BKdnPwep.js +386 -0
  276. package/dist/map-error-DTi_JZT8.js +22 -0
  277. package/dist/markers-C-kThnKN.js +79 -0
  278. package/dist/may-use-Died1tNU.js +233 -0
  279. package/dist/mcp/index.d.ts +11 -21
  280. package/dist/mcp/index.js +56 -43
  281. package/dist/membership-filter-CSKH48eD.js +66 -0
  282. package/dist/migrate-CmTMk7rd.js +536 -0
  283. package/dist/model-B4EKVHMK.js +188 -0
  284. package/dist/module-values-Ddx0GLaJ.js +106 -0
  285. package/dist/nest/index.d.ts +7 -13
  286. package/dist/nest/index.js +12 -15
  287. package/dist/next/client.d.ts +1 -3
  288. package/dist/next/client.js +2 -3
  289. package/dist/next/index.d.ts +36 -16
  290. package/dist/next/index.js +161 -31
  291. package/dist/next/plugin.d.ts +1 -3
  292. package/dist/next/plugin.js +3 -4
  293. package/dist/node/index.d.ts +6 -8
  294. package/dist/node/index.js +4 -5
  295. package/dist/oauth-security-C8fjzFRF.js +25 -0
  296. package/dist/ocsf-DKRQc6uv.js +135 -0
  297. package/dist/openai/index.d.ts +5 -7
  298. package/dist/openai/index.js +5 -6
  299. package/dist/openapi/index.d.ts +4 -16
  300. package/dist/openapi/index.js +4 -3
  301. package/dist/openapi-BHqqNSoG.js +95 -0
  302. package/dist/openapi-BT5XY7HY.js +260 -0
  303. package/dist/openapi-D2dmyWZK.js +411 -0
  304. package/dist/openapi-document-Ca5yAjc6.js +35 -0
  305. package/dist/operation-findings-D5Uo-dcm.js +35 -0
  306. package/dist/operation-risks-BD-j14dj.js +12 -0
  307. package/dist/operations-B0yO77Zz.js +290 -0
  308. package/dist/operations-BS8ExH5A.d.ts +58 -0
  309. package/dist/operations-De3F7tlf.js +88 -0
  310. package/dist/optional-CaQWp9HA.js +46 -0
  311. package/dist/orpc/index.d.ts +8 -12
  312. package/dist/orpc/index.js +10 -12
  313. package/dist/otel/index.d.ts +3 -5
  314. package/dist/otel/index.js +5 -7
  315. package/dist/output-djxu62oH.js +244 -0
  316. package/dist/output-files-C5LFnQa4.js +1 -0
  317. package/dist/output-files-DNid6TBl.js +197 -0
  318. package/dist/ownership-BO0sI5FB.js +558 -0
  319. package/dist/parse-local-manifest-BGLWVchi.d.ts +8 -0
  320. package/dist/parse-local-manifest-CfMjZAFi.js +67 -0
  321. package/dist/parse-nfHSt1Wy.js +149 -0
  322. package/dist/parse-request-IEEzVFM8.js +24 -0
  323. package/dist/parse-sink-events-B6nZx41L.js +125 -0
  324. package/dist/paths-CeS_gpHf.js +44 -0
  325. package/dist/pdp/index.d.ts +3 -9
  326. package/dist/pdp/index.js +22 -18
  327. package/dist/peer-BWTpSLs2.js +1 -0
  328. package/dist/peer-D77JpXe-.js +978 -0
  329. package/dist/perf-token-dFGVP14-.js +155 -0
  330. package/dist/permdock-BueSeg7X.js +1514 -0
  331. package/dist/permdock-Dz3yzWrp.d.ts +853 -0
  332. package/dist/permission-registry-DMYRZVcn.js +413 -0
  333. package/dist/permissions-CQW3cr2S.js +17 -0
  334. package/dist/permissions-DWULToSb.d.ts +52 -0
  335. package/dist/permissions-ijDw4sO1.js +144 -0
  336. package/dist/pg-CA651850.js +59 -0
  337. package/dist/pins-CXXkVEiD.js +14 -0
  338. package/dist/pipeline-CXuwijr2.js +307 -0
  339. package/dist/pkce-DdsRBK7n.js +20 -0
  340. package/dist/plugin-DGmbeXwA.d.ts +221 -0
  341. package/dist/plugin-MQVfUBUS.js +93 -0
  342. package/dist/plugin-outputs-BE2YCiMj.js +28 -0
  343. package/dist/policy-BhSUlHRr.js +37 -0
  344. package/dist/policy-C-Lzp3Zh.d.ts +18 -0
  345. package/dist/policy-DFD2J5o_.js +476 -0
  346. package/dist/policy-bundle-97xaDULc.js +82 -0
  347. package/dist/policy-from-catalog-YKaTeaco.js +452 -0
  348. package/dist/policy-module-Bp4HvsRg.js +107 -0
  349. package/dist/policy-types-93NwI8iI.d.ts +2855 -0
  350. package/dist/postgres-store-CYFvw98w.js +1023 -0
  351. package/dist/postgrest-DyrYo_XT.d.ts +138 -0
  352. package/dist/powersync-CN7IQIKk.js +40 -0
  353. package/dist/powersync-DdDLP02A.js +1630 -0
  354. package/dist/powersync-m9uYgCFF.js +1 -0
  355. package/dist/preset/index.d.ts +0 -12
  356. package/dist/preset/index.js +1 -1
  357. package/dist/preset-BcFDaeqd.js +1849 -0
  358. package/dist/principal-source-BIcukkB3.js +102 -0
  359. package/dist/prisma/index.d.ts +4 -12
  360. package/dist/prisma/index.js +10 -14
  361. package/dist/problem-BZB7zPC7.js +202 -0
  362. package/dist/problem-details-EJHcvYCz.js +154 -0
  363. package/dist/problem-types-81BEw0IN.js +7 -0
  364. package/dist/prompt-CSXHcJxy.js +931 -0
  365. package/dist/protected-action-BMb0ftEu.js +241 -0
  366. package/dist/protected-action-D6T3eJyW.d.ts +73 -0
  367. package/dist/protected-action-DiXulRVj.js +78 -0
  368. package/dist/provider-BnnFjtWI.js +893 -0
  369. package/dist/provider-ClD4rfgT.js +11 -0
  370. package/dist/provider-CydlnKkS.d.ts +4 -0
  371. package/dist/provider-store-atQUfsVO.js +51 -0
  372. package/dist/provider-with-CSw4mBDU.js +70 -0
  373. package/dist/public-api-DIMZmzWi.js +5579 -0
  374. package/dist/pull-9oQvY18T.js +252 -0
  375. package/dist/pull-jvJPMQhP.js +1 -0
  376. package/dist/push-Cb7PqXdO.js +158 -0
  377. package/dist/pushed-policy-pH-EFWyx.d.ts +61 -0
  378. package/dist/pushed-policy-rpB6k77P.js +240 -0
  379. package/dist/quote-BKrTBbcH.js +36 -0
  380. package/dist/rbac-B-49toAp.js +90 -0
  381. package/dist/react/index.d.ts +10 -9
  382. package/dist/react/index.js +8 -7
  383. package/dist/react/lazy.d.ts +10 -12
  384. package/dist/react/lazy.js +8 -35
  385. package/dist/react/provider-client-lazy.d.ts +2 -0
  386. package/dist/react/provider-client-lazy.js +2 -0
  387. package/dist/react/provider-client.d.ts +1 -1
  388. package/dist/react/provider-client.js +1 -1
  389. package/dist/react-native/index.d.ts +12 -30
  390. package/dist/react-native/index.js +31 -41
  391. package/dist/read-memberships-BkePIa1F.js +63 -0
  392. package/dist/refresh-on-C1zIMtJr.d.ts +47 -0
  393. package/dist/refresh-online-CYGZNo6V.js +19 -0
  394. package/dist/refresh-online-vtUfV6dk.d.ts +10 -0
  395. package/dist/refs-Cix9Zjis.js +103 -0
  396. package/dist/relation-walk-BlWy9gBK.js +188 -0
  397. package/dist/relations-CIgB5KPJ.js +162 -0
  398. package/dist/replay-ClGIMp5p.d.ts +3 -0
  399. package/dist/replay-X2m6moK1.js +28 -0
  400. package/dist/request-context-CVJodWx8.js +70 -0
  401. package/dist/request-context-E3-ps-H_.d.ts +3 -0
  402. package/dist/request-schema-DzEoR310.js +155 -0
  403. package/dist/resend/index.d.ts +4 -10
  404. package/dist/resend/index.js +14 -17
  405. package/dist/resolve-names-Cmg6SPAa.js +266 -0
  406. package/dist/resolver-kdZ4HrpC.js +404 -0
  407. package/dist/resource-ref-BiQtFK-I.js +19 -0
  408. package/dist/resource-relations-Ck5sjYQR.js +251 -0
  409. package/dist/retire-BNiXnbBR.js +248 -0
  410. package/dist/revocations-3jyzniOz.js +26 -0
  411. package/dist/revocations-ku_f2d2y.d.ts +24 -0
  412. package/dist/rls-BrsMogAP.js +321 -0
  413. package/dist/rls-Cv1V8YfI.js +946 -0
  414. package/dist/rls-files-Bj446vbj.js +114 -0
  415. package/dist/rls-options-Dpj_pEyU.d.ts +26 -0
  416. package/dist/role-builder-DhsGEVq-.js +501 -0
  417. package/dist/role-grants-Bk6ZsaS0.js +46 -0
  418. package/dist/roles-B29psCem.js +29 -0
  419. package/dist/rolldown-runtime-B8NLbhFH.js +3 -0
  420. package/dist/row-conditions-DwIJocfQ.js +27 -0
  421. package/dist/row-pair-CxEhErJU.js +33 -0
  422. package/dist/rpc-B-4IZOiU.js +111 -0
  423. package/dist/rpc-DjgxFbjK.d.ts +18 -0
  424. package/dist/run-DX4D6S6V.js +726 -0
  425. package/dist/run-decqEKNa.js +1 -0
  426. package/dist/run-ticket-D6T39Xdi.js +370 -0
  427. package/dist/run-ticket-DXwrko2J.d.ts +157 -0
  428. package/dist/runtime-Cl6xSbEq.js +13 -0
  429. package/dist/saas-DzjKUQr5.js +1218 -0
  430. package/dist/scan-Cj7PQLrS.js +28 -0
  431. package/dist/schema-BeY3croo.js +403 -0
  432. package/dist/schema-CJPvTfeN.js +133 -0
  433. package/dist/scim/index.d.ts +2 -2
  434. package/dist/scim/index.js +2 -2
  435. package/dist/scim-B9QyJ23q.js +1046 -0
  436. package/dist/scopes-B-KX9EI8.js +238 -0
  437. package/dist/seed-sql-CjF7u0aX.js +60 -0
  438. package/dist/seeds/index.d.ts +2 -0
  439. package/dist/seeds/index.js +1 -0
  440. package/dist/seeds-BDTG7xl-.js +53 -0
  441. package/dist/seeds-uG196Ev4.d.ts +73 -0
  442. package/dist/server/index.d.ts +13 -13
  443. package/dist/server/index.js +14 -14
  444. package/dist/server-Co9CYGqk.js +146 -0
  445. package/dist/server-types-BrHOGAYx.d.ts +318 -0
  446. package/dist/sha256-DFsnyVPo.js +157 -0
  447. package/dist/shared-BOsJIQf4.js +124 -0
  448. package/dist/shared-BdF5DJDQ.js +330 -0
  449. package/dist/signals-a1NxAP0X.js +31 -0
  450. package/dist/sink-BD34OS8T.d.ts +247 -0
  451. package/dist/sink-Bgvf9lIz.js +966 -0
  452. package/dist/size-DF7xQ-nH.js +95 -0
  453. package/dist/skills-B5bc6JIA.js +50 -0
  454. package/dist/skills-Cr1C0b9D.js +202 -0
  455. package/dist/snapshot-DckMnHk8.js +352 -0
  456. package/dist/snapshot-cache-DTTEfmxv.js +69 -0
  457. package/dist/snapshot-cache-DoP3avLl.d.ts +68 -0
  458. package/dist/snapshot-compact-CwAop_6C.js +119 -0
  459. package/dist/snapshot-empty-DZ6sZ83n.js +17 -0
  460. package/dist/snapshot-evaluate-9RGy7J3N.js +552 -0
  461. package/dist/snapshot-reads-D775amTL.js +65 -0
  462. package/dist/snapshot-size-D-pCR8x0.js +139 -0
  463. package/dist/snapshot-size-DU7CvpMt.js +1 -0
  464. package/dist/solid/index.d.ts +18 -20
  465. package/dist/solid/index.js +15 -19
  466. package/dist/solid-start/index.d.ts +6 -8
  467. package/dist/solid-start/index.js +4 -5
  468. package/dist/sources-BbSUNmFX.js +10 -0
  469. package/dist/sources-DnjJPGfb.js +657 -0
  470. package/dist/sources-NQio1yFq.d.ts +727 -0
  471. package/dist/sql-BYYNi1lu.d.ts +8 -0
  472. package/dist/sql-T4GaBh9X.js +93 -0
  473. package/dist/src-D6_T4zd7.js +1811 -0
  474. package/dist/ssf/index.d.ts +3 -3
  475. package/dist/ssf/index.js +20 -31
  476. package/dist/standard-webhooks-B3MQihcP.d.ts +86 -0
  477. package/dist/standard-webhooks-BtIkXclH.js +227 -0
  478. package/dist/storage-BhGDhsXm.js +131 -0
  479. package/dist/store-AH8bmaxW.js +377 -0
  480. package/dist/store-core-eqG8jijs.d.ts +306 -0
  481. package/dist/store-options-C8x39AHa.js +1034 -0
  482. package/dist/stores-4DOaL4ZP.d.ts +58 -0
  483. package/dist/stores-DoA7ACkz.js +127 -0
  484. package/dist/stream-DdF94h7T.js +73 -0
  485. package/dist/style-CQDaLJtP.js +24 -0
  486. package/dist/style-Crf-90o6.js +1 -0
  487. package/dist/subject-DkxY-AhF.js +23 -0
  488. package/dist/subject-cache-BZeSj4Xf.d.ts +156 -0
  489. package/dist/subject-settings-BO-frcYx.js +147 -0
  490. package/dist/subject-settings-C9F1sU1d.d.ts +48 -0
  491. package/dist/supabase/client.d.ts +1 -1
  492. package/dist/supabase/client.js +2 -3
  493. package/dist/supabase/index.d.ts +77 -24
  494. package/dist/supabase/index.js +9 -8
  495. package/dist/supabase/middleware.d.ts +27 -9
  496. package/dist/supabase/middleware.js +51 -21
  497. package/dist/supabase-BG1HPdQU.js +30 -0
  498. package/dist/supabase-BI5ZhzLl.js +792 -0
  499. package/dist/supabase-config-mXcggV5I.js +890 -0
  500. package/dist/supabase-hook-hd9abKy4.js +2 -0
  501. package/dist/supabase-hook-tdR45aXY.js +405 -0
  502. package/dist/supabase-outcome-CMLuLW-V.js +9 -0
  503. package/dist/supautils-DXzJ2E2Q.js +96 -0
  504. package/dist/support-session-B8xrW28B.js +157 -0
  505. package/dist/svelte/index.d.ts +8 -10
  506. package/dist/svelte/index.js +12 -15
  507. package/dist/svelte/runtime.d.ts +4 -6
  508. package/dist/svelte/runtime.js +4 -4
  509. package/dist/svelte/source.d.ts +8 -10
  510. package/dist/svelte/source.js +6 -7
  511. package/dist/sveltekit/index.d.ts +6 -8
  512. package/dist/sveltekit/index.js +3 -4
  513. package/dist/tables-CRTCBuFi.js +3240 -0
  514. package/dist/tanstack-start/index.d.ts +6 -8
  515. package/dist/tanstack-start/index.js +3 -4
  516. package/dist/target-BGpxgKsN.js +50 -0
  517. package/dist/tenancy-B5Xxt9Sc.js +223 -0
  518. package/dist/terminal/index.d.ts +6 -16
  519. package/dist/terminal/index.js +18 -23
  520. package/dist/testing/core.d.ts +1 -1
  521. package/dist/testing/core.js +1 -1
  522. package/dist/testing/fixtures/index.d.ts +12 -10
  523. package/dist/testing/fixtures/index.js +48 -25
  524. package/dist/testing/index.d.ts +85 -85
  525. package/dist/testing/index.js +226 -115
  526. package/dist/testing/saas/index.d.ts +5 -15
  527. package/dist/testing/saas/index.js +2 -2
  528. package/dist/testing/saas/permissions.d.ts +1 -1
  529. package/dist/testing/saas/permissions.js +1 -1
  530. package/dist/text-D704xHVl.js +7 -0
  531. package/dist/text-diff-CsglY49A.js +440 -0
  532. package/dist/thenable-BxMy2v8w.js +39 -0
  533. package/dist/time-r0CKBm57.js +94 -0
  534. package/dist/timeout-nOqLpU2I.js +7 -0
  535. package/dist/token-BgswTQzt.d.ts +9 -0
  536. package/dist/token-CSljQqzA.js +76 -0
  537. package/dist/tool-refusal-DzCSbjp8.js +43 -0
  538. package/dist/trpc/index.d.ts +7 -9
  539. package/dist/trpc/index.js +7 -8
  540. package/dist/type-helpers-DHCQEPj8.d.ts +47 -0
  541. package/dist/types-3pRMqcvw.d.ts +84 -0
  542. package/dist/types-BFtFaI1W.d.ts +66 -0
  543. package/dist/types-BdNdMix7.d.ts +263 -0
  544. package/dist/types-C7QtRn3n.d.ts +66 -0
  545. package/dist/types-CVCRFYY_.d.ts +102 -0
  546. package/dist/types-CWmBZtQN.d.ts +274 -0
  547. package/dist/types-Cakw89Wx.d.ts +372 -0
  548. package/dist/types-D3tjoLwT.d.ts +124 -0
  549. package/dist/types-D8VXQxKL.d.ts +1231 -0
  550. package/dist/types-DFZKovb3.js +77 -0
  551. package/dist/types-DONLJQjY.d.ts +134 -0
  552. package/dist/types-OzSal_K_.d.ts +178 -0
  553. package/dist/types-XSfi6ihL.d.ts +65 -0
  554. package/dist/unplugin/index.d.ts +1 -3
  555. package/dist/unplugin/index.js +3 -4
  556. package/dist/usage-B-E747wO.js +31 -0
  557. package/dist/usage-B7nx0_aa.js +761 -0
  558. package/dist/usage-rqQ9ViXv.js +1 -0
  559. package/dist/validation-error-BAO1W1yk.d.ts +27 -0
  560. package/dist/validation-error-CgDOA6VS.js +35 -0
  561. package/dist/validity-YNEEm2MZ.js +56 -0
  562. package/dist/verifier-BIYkGcJc.js +530 -0
  563. package/dist/verify-9HObfifg.js +1102 -0
  564. package/dist/version-CU6e2wxV.js +7 -0
  565. package/dist/version-D-jWyJb9.js +46 -0
  566. package/dist/version-DcZCjWXb.js +1 -0
  567. package/dist/version-cache-BXkl7-Fz.js +462 -0
  568. package/dist/views-Dpr1uB16.js +164 -0
  569. package/dist/vocabulary-CE2k7s1a.js +157 -0
  570. package/dist/vocabulary-FYgI_NoI.d.ts +400 -0
  571. package/dist/vue/index.d.ts +18 -20
  572. package/dist/vue/index.js +13 -18
  573. package/dist/waiter-DKdFHKVZ.js +66 -0
  574. package/dist/waiter-hYLJXA7r.d.ts +37 -0
  575. package/dist/watch-BecZtEdU.js +155 -0
  576. package/dist/watch-CiN6WU9k.js +221 -0
  577. package/dist/watch-NAUnUXph.js +1 -0
  578. package/dist/webmcp/index.d.ts +2 -6
  579. package/dist/webmcp/index.js +8 -9
  580. package/dist/who-can-rUSZfLvI.js +366 -0
  581. package/dist/wire-delegation-DC5Cyec4.js +35 -0
  582. package/dist/wire-denial-BcRQnA7p.js +26 -0
  583. package/dist/workflow/index.d.ts +3 -3
  584. package/dist/workflow/index.js +12 -14
  585. package/dist/workflow-sdk/index.d.ts +6 -8
  586. package/dist/workflow-sdk/index.js +2 -3
  587. package/dist/wrap-CsfsaJhd.js +32 -0
  588. package/dist/wrap-D-KvhzaC.d.ts +16 -0
  589. package/package.json +83 -39
  590. package/schemas/catalog-v2.json +665 -0
  591. package/schemas/cli-commands-v1.json +1 -1
  592. package/schemas/cli-result-v2.json +163 -0
  593. package/schemas/cloud-api-v1.json +1 -1
  594. package/schemas/snapshot-v1.json +26 -0
  595. package/schemas/supabase-claims-v1.json +5 -1
  596. package/schemas/supabase-manifest-v1.json +11 -2
  597. package/skills/permdock/SKILL.md +1 -1
  598. package/skills/permdock-data/references/queries-and-rls.md +2 -1
  599. package/skills/permdock-wire/references/adapters.md +5 -3
  600. package/dist/2020-CJbO8Bvz.js +0 -6773
  601. package/dist/active-tenant-DVee32-T.js +0 -39
  602. package/dist/adapter-context-OHikyRqV.js +0 -29
  603. package/dist/adoption-scan-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,3412 @@
1
+ import { r as isRecord } from "./compact-C4LFuqbW.js";
2
+ import { o as hasConditionOp } from "./refs-Cix9Zjis.js";
3
+ import { c as rootScope, l as scopeChain, s as resolveScope } from "./scopes-B-KX9EI8.js";
4
+ import { t as APPROVAL_REQUEST_SCHEMA } from "./request-schema-DzEoR310.js";
5
+ import { t as AUTHZ_EVENT } from "./authz-topic-D8x24Jv-.js";
6
+ import { i as configError } from "./errors-DgLOqc6j.js";
7
+ import { a as SUPABASE_MANIFEST_SCHEMA } from "./version-D-jWyJb9.js";
8
+ import { t as CUSTOM_ROLES_VERSION_CLAIM } from "./budget-BH81q2cj.js";
9
+ import { i as qualifySqlTable } from "./sql-T4GaBh9X.js";
10
+ import { i as scopeColumn } from "./compile-BUKXrueE.js";
11
+ import { a as hookApiNames, d as keptKeys, o as junctionMembershipSource, t as AUTHZ_VERSION_TABLE, u as roleManifest } from "./sources-DnjJPGfb.js";
12
+ import { r as REGISTERED_CLAIMS } from "./definition-options-9o8Hdww3.js";
13
+ import { t as beforeFirst } from "./text-D704xHVl.js";
14
+ import { n as GRANTS_MARKER, r as HOOK_MARKER } from "./markers-C-kThnKN.js";
15
+ import { c as ACTOR_MAY_WRITE, p as readOnlyActorKinds } from "./fields-6d1j-q3c.js";
16
+ import { a as quoteIdent, c as quoteTable, i as qualified$1, o as quoteLiteral, s as quoteQualified } from "./quote-BKrTBbcH.js";
17
+ import { A as tenantTypeOf, E as firstScopeType, O as scopeTypeOf, a as customRolesOn, j as userTypeOf, k as sqlType, l as USER_ID_HELPER, r as HELPERS, y as subjectIdSql } from "./shared-BdF5DJDQ.js";
18
+ import { J as hasMemberFor, Q as isTeamScope, U as BOOTSTRAP_PERMISSIONS, X as hasPermittedUsers, at as memberRoleOf, et as memberForHelper, ht as checkSuspension, i as interactiveOnlyKeys, it as memberOfHelper, j as globalRoleSource, nt as memberForTable, ot as permittedForHelper, pt as activeRowSql, rt as memberIdsHelper, st as permittedIdsHelper, t as INTERACTIVE_ALLOWS, tt as memberForSources } from "./interactive-only-BZu9rLpa.js";
19
+ import { B as hookTeamReader, F as API_KEY_ALLOWS, L as apiKeyFields, O as TOKEN_SCOPE_ALLOWS, V as hookTeamsHelper, b as ASSIGNMENTS, d as permittedByPermissionHelper, l as permissionKeysForHelper, o as PERMISSION_HELPERS, s as checkName, x as OWNERSHIP, z as HOOK_TEAM_READER } from "./tables-CRTCBuFi.js";
20
+ import { r as permittedUsersHelper, t as resolveNames } from "./resolve-names-Cmg6SPAa.js";
21
+ import { a as supabaseConfig, t as declarativeSchemaDir } from "./supabase-config-mXcggV5I.js";
22
+ import { a as resolveAuthorize, n as hookUri, t as authAdminRead } from "./rbac-B-49toAp.js";
23
+ import { a as splitUndiffed, r as tableKey, t as decidingColumns } from "./deciding-columns-BnglEKqU.js";
24
+ import { a as guardedTables, t as ownershipRules } from "./ownership-BO0sI5FB.js";
25
+ import { t as membershipSourcesOf } from "./sources-BbSUNmFX.js";
26
+ // src/cli/claims-schema.ts
27
+ /**
28
+ * The PermDock claims of `schemas/supabase-claims-v1.json` (its
29
+ * `permdockClaims` and `membership` definitions), self-contained so
30
+ * `supabase.hook.validate` can inline it into the hook for pg_jsonschema.
31
+ */
32
+ const PERMDOCK_CLAIMS_SCHEMA = {
33
+ $schema: "https://json-schema.org/draft/2020-12/schema",
34
+ $ref: "#/$defs/permdockClaims",
35
+ $defs: {
36
+ permdockClaims: {
37
+ type: "object",
38
+ properties: {
39
+ user_role: {
40
+ description: "Global roles: one name, a list, or null for none.",
41
+ anyOf: [
42
+ { type: "string" },
43
+ {
44
+ type: "array",
45
+ items: { type: "string" }
46
+ },
47
+ { type: "null" }
48
+ ]
49
+ },
50
+ roles: {
51
+ type: "array",
52
+ items: { type: "string" }
53
+ },
54
+ memberships: {
55
+ type: "array",
56
+ items: { $ref: "#/$defs/membership" }
57
+ },
58
+ memberships_truncated: {
59
+ description: "true when the size budget cut memberships or attrs.",
60
+ type: "boolean"
61
+ },
62
+ team_ids: {
63
+ description: "The uuid of every team the user belongs to (supabase.hook.teams). Omitted when the team budget is exceeded.",
64
+ type: "array",
65
+ items: { type: "string" }
66
+ },
67
+ team_ids_truncated: {
68
+ description: "true when team_ids was omitted because it did not fit the shared budget. memberships_truncated is not set by team rows.",
69
+ type: "boolean"
70
+ },
71
+ tenant_id: {
72
+ description: "The active tenant (the default rls.tenantClaim): the canonical text of one instance of the first scope.",
73
+ type: "string"
74
+ },
75
+ attrs: {
76
+ description: "Allow-listed server-owned attributes, read as principal.claims.attrs.<key>.",
77
+ type: "object"
78
+ },
79
+ authz_ver: {
80
+ description: "The principal's authorization version.",
81
+ type: "integer"
82
+ }
83
+ }
84
+ },
85
+ membership: {
86
+ type: "object",
87
+ required: ["roles"],
88
+ properties: {
89
+ scope: { type: "string" },
90
+ id: {
91
+ description: "Canonical text of the scope instance id (uuid::text for a uuid column); compared exactly, never lower-cased.",
92
+ type: "string"
93
+ },
94
+ within: {
95
+ description: "The id of every ancestor scope instance, by scope name.",
96
+ type: "object",
97
+ additionalProperties: { type: "string" }
98
+ },
99
+ on: {
100
+ type: "object",
101
+ required: ["resource", "id"],
102
+ properties: {
103
+ resource: { type: "string" },
104
+ id: { type: "string" }
105
+ }
106
+ },
107
+ tenant: { type: "string" },
108
+ team: { type: "string" },
109
+ roles: {
110
+ type: "array",
111
+ minItems: 1,
112
+ items: { type: "string" }
113
+ },
114
+ via: { type: "string" },
115
+ expires_at: {
116
+ description: "NumericDate (RFC 7519): seconds since the epoch.",
117
+ type: "number"
118
+ },
119
+ granted_by: { type: "string" },
120
+ reason: { type: "string" },
121
+ member: {
122
+ description: "The subgroup a membership source's group fills.",
123
+ type: "object",
124
+ required: ["group"],
125
+ properties: { group: {
126
+ type: "string",
127
+ minLength: 1
128
+ } }
129
+ },
130
+ managed_by: { const: "idp" },
131
+ entitlements: {
132
+ type: "array",
133
+ items: { type: "string" }
134
+ },
135
+ keep: {
136
+ description: "Set when the instance or an ancestor is suspended: the permission keys the membership still grants.",
137
+ type: "array",
138
+ items: {
139
+ type: "string",
140
+ minLength: 1
141
+ }
142
+ },
143
+ grants: {
144
+ description: "Custom roles in compact form, read by the helpers in jwt mode.",
145
+ type: "object"
146
+ }
147
+ },
148
+ anyOf: [
149
+ { required: ["scope", "id"] },
150
+ { required: ["tenant"] },
151
+ { required: ["team"] },
152
+ { required: ["on"] }
153
+ ]
154
+ }
155
+ }
156
+ };
157
+ // src/cli/supabase-hook/claims.ts
158
+ const CLAIM_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/u;
159
+ const PROTOTYPE_KEYS = /* @__PURE__ */ new Set([
160
+ "__proto__",
161
+ "constructor",
162
+ "prototype"
163
+ ]);
164
+ const USER_EDITABLE = /^(raw_)?user_meta(_)?data$/iu;
165
+ /**
166
+ * Splits `supabase.hook.attrs` into table columns and `app_metadata` keys and
167
+ * lists what cannot be compiled: `user_metadata` (the user can edit it), a
168
+ * direct `auth.users` column, an unsafe or prototype key, a duplicate key, or a
169
+ * table column without a table.
170
+ */
171
+ function attrsPlan(attrs) {
172
+ const errors = [];
173
+ const columns = [];
174
+ const meta = [];
175
+ const seen = /* @__PURE__ */ new Set();
176
+ if (attrs.table?.replaceAll("\"", "").toLowerCase() === "auth.users") errors.push("supabase.hook.attrs.table cannot be auth.users: list app_metadata.<key> entries instead");
177
+ for (const entry of attrs.columns) {
178
+ const [head = "", ...rest] = entry.split(".");
179
+ const isMeta = head === "app_metadata" || head === "raw_app_meta_data";
180
+ const key = isMeta ? rest.join(".") : entry;
181
+ if (USER_EDITABLE.test(head) || USER_EDITABLE.test(key) || /user_?meta/iu.test(entry)) {
182
+ errors.push(`supabase.hook.attrs lists ${entry}: user_metadata is user-editable and never becomes a claim`);
183
+ continue;
184
+ }
185
+ if (!CLAIM_KEY.test(key) || PROTOTYPE_KEYS.has(key)) {
186
+ errors.push(`supabase.hook.attrs lists ${entry}: a key must match ${CLAIM_KEY.source} and not be a prototype key`);
187
+ continue;
188
+ }
189
+ if (seen.has(key)) {
190
+ errors.push(`supabase.hook.attrs names the key ${key} twice`);
191
+ continue;
192
+ }
193
+ seen.add(key);
194
+ if (isMeta) meta.push(key);
195
+ else columns.push(key);
196
+ }
197
+ if (columns.length > 0 && attrs.table === void 0) errors.push(`supabase.hook.attrs lists ${columns.join(", ")} without a table`);
198
+ return {
199
+ ...attrs.table === void 0 ? {} : { table: attrs.table },
200
+ id: attrs.id ?? "id",
201
+ columns,
202
+ meta,
203
+ errors
204
+ };
205
+ }
206
+ /**
207
+ * Claim names `supabase.hook.claims` cannot write: the ones this hook owns
208
+ * (plus the tenant claim) and the ones Supabase Auth issues.
209
+ */
210
+ const RESERVED_CLAIMS = /* @__PURE__ */ new Set([
211
+ "roles",
212
+ "user_role",
213
+ "memberships",
214
+ "memberships_truncated",
215
+ "team_ids",
216
+ "team_ids_truncated",
217
+ "attrs",
218
+ "authz_ver",
219
+ "custom_roles_ver",
220
+ ...REGISTERED_CLAIMS
221
+ ]);
222
+ const CLAIM_FUNCTION = /^[A-Za-z_][A-Za-z0-9_]*\.[A-Za-z_][A-Za-z0-9_]*$/u;
223
+ /**
224
+ * Checks `supabase.hook.claims`: each name is a safe claim key outside
225
+ * {@link RESERVED_CLAIMS} and the tenant claim, each function is
226
+ * schema-qualified (the hook runs with an empty `search_path`).
227
+ */
228
+ function extraClaimsPlan(claims, tenantClaim) {
229
+ const errors = [];
230
+ const planned = [];
231
+ for (const [claim, fn] of Object.entries(claims ?? {})) {
232
+ if (!CLAIM_KEY.test(claim) || PROTOTYPE_KEYS.has(claim)) {
233
+ errors.push(`supabase.hook.claims names ${claim}: a claim must match ${CLAIM_KEY.source} and not be a prototype key`);
234
+ continue;
235
+ }
236
+ if (RESERVED_CLAIMS.has(claim) || claim === tenantClaim) {
237
+ errors.push(`supabase.hook.claims names ${claim}, which PermDock or Supabase Auth writes`);
238
+ continue;
239
+ }
240
+ if (typeof fn !== "string" || !CLAIM_FUNCTION.test(fn)) {
241
+ errors.push(`supabase.hook.claims.${claim} must be a schema-qualified function name such as public.feature_claims`);
242
+ continue;
243
+ }
244
+ planned.push({
245
+ claim,
246
+ fn
247
+ });
248
+ }
249
+ return {
250
+ claims: planned,
251
+ errors
252
+ };
253
+ }
254
+ function beforePlan(before) {
255
+ const list = before === void 0 ? [] : typeof before === "string" ? [before] : before;
256
+ const bad = list.filter((fn) => typeof fn !== "string" || !CLAIM_FUNCTION.test(fn));
257
+ if (bad.length > 0) throw configError(`PermDock CLI: supabase.hook.before must name schema-qualified functions such as auth_checks.before_token (got ${bad.map(String).join(", ")})`);
258
+ return [...new Set(list)];
259
+ }
260
+ function beforeSql(before) {
261
+ return before.map((fn) => `
262
+ checked := ${quoteTable(fn)}(event);
263
+ if checked is null or jsonb_typeof(checked) is distinct from 'object' then
264
+ return jsonb_build_object('error', jsonb_build_object('http_code', 500, 'message', ${quoteLiteral(`${fn} returned no event`)}));
265
+ end if;
266
+ if checked ? 'error' then
267
+ return checked;
268
+ end if;
269
+ event := checked;`).join("").concat(before.length === 0 ? "" : "\n claims := event -> 'claims';");
270
+ }
271
+ /**
272
+ * `hook.validate`: the claims the hook writes, dropped together when they do
273
+ * not match `supabase-claims-v1.json`, so a bad claim denies instead of failing
274
+ * sign-in. `hook.claims` entries belong to other packages and stay.
275
+ */
276
+ function validateSql(parts) {
277
+ if (parts.hook.validate !== true) return "";
278
+ const keys = /* @__PURE__ */ new Set([
279
+ "user_role",
280
+ "roles",
281
+ "memberships",
282
+ "memberships_truncated",
283
+ ...parts.hook.teams === void 0 ? [] : ["team_ids", "team_ids_truncated"],
284
+ "attrs",
285
+ "authz_ver",
286
+ parts.tenantClaim
287
+ ]);
288
+ return `
289
+ if not extensions.jsonb_matches_schema(${quoteLiteral(JSON.stringify(PERMDOCK_CLAIMS_SCHEMA))}::json, claims) then
290
+ claims := claims${[...keys].map((key) => ` - ${quoteLiteral(key)}`).join("")};
291
+ end if;`;
292
+ }
293
+ function validateGrantsSql(parts) {
294
+ return parts.hook.validate === true ? `
295
+ create extension if not exists pg_jsonschema with schema extensions;
296
+ grant usage on schema extensions to supabase_auth_admin;
297
+ grant execute on function extensions.jsonb_matches_schema(json, jsonb) to supabase_auth_admin;` : "";
298
+ }
299
+ /**
300
+ * Fails the migration when a client role can write an `attrs` column: a claim
301
+ * the user can set is not a server-owned attribute.
302
+ */
303
+ function attrsGuardSql(plan, schema = "permdock") {
304
+ if (plan?.table === void 0 || plan.columns.length === 0) return "";
305
+ const target = quoteLiteral(quoteQualified(plan.table));
306
+ const columns = plan.columns.map((column) => `(${quoteLiteral(column)})`).join(", ");
307
+ const fn = `${quoteIdent(schema)}.permdock_attrs_are_server_owned`;
308
+ return `-- attrs must be server-owned: refuse columns anon or authenticated can insert or update
309
+ create or replace function ${fn}()
310
+ returns void
311
+ language plpgsql
312
+ volatile
313
+ set search_path = ''
314
+ as $$
315
+ begin
316
+ if exists (
317
+ select 1
318
+ from (values ${columns}) c(name)
319
+ cross join (values ('anon'), ('authenticated')) r(role)
320
+ where has_column_privilege(r.role, ${target}, c.name, 'INSERT')
321
+ or has_column_privilege(r.role, ${target}, c.name, 'UPDATE')
322
+ ) then
323
+ raise exception 'PermDock: an attrs column of % is writable by anon or authenticated; revoke insert and update on it before it becomes a claim', ${target}
324
+ using errcode = '42501';
325
+ end if;
326
+ end
327
+ $$;
328
+ revoke execute on function ${fn}() from public, anon, authenticated;
329
+ select ${fn}();`;
330
+ }
331
+ function permdockClaim(name, budget = false) {
332
+ return {
333
+ name,
334
+ source: "permdock",
335
+ budget
336
+ };
337
+ }
338
+ function hookClaims(parts) {
339
+ return [
340
+ permdockClaim("user_role"),
341
+ permdockClaim("roles", true),
342
+ permdockClaim("memberships", true),
343
+ permdockClaim("memberships_truncated"),
344
+ permdockClaim(parts.tenantClaim),
345
+ ...parts.hook.teams === void 0 ? [] : [permdockClaim("team_ids", true), permdockClaim("team_ids_truncated")],
346
+ ...parts.attrs === void 0 ? [] : [permdockClaim("attrs", true)],
347
+ ...parts.version ? [permdockClaim("authz_ver", true)] : [],
348
+ ...parts.extra.map((entry) => ({
349
+ name: entry.claim,
350
+ source: entry.fn,
351
+ budget: false
352
+ }))
353
+ ];
354
+ }
355
+ // src/cli/sql/declarative.ts
356
+ /**
357
+ * A migration's SQL as a declarative schema file: pg-delta diffs the file
358
+ * against the database itself, so a `drop trigger if exists`, `drop policy if
359
+ * exists` or `drop function if exists` (a replaced overload) before its
360
+ * `create` is an error, and a trigger is `create or replace trigger`. A
361
+ * constraint trigger stays `create constraint trigger`, because pg-delta has no
362
+ * `create or replace constraint trigger`. A policy keeps its plain `create
363
+ * policy`. A schema keeps `if not exists`: the helpers and the hook are
364
+ * separate files, and the shadow load applies both.
365
+ */
366
+ function declarativeSql(sql) {
367
+ return sql.replaceAll(/^drop (?:trigger|policy|function) if exists [^;\n]+;\n/gmu, "").replaceAll(/^create trigger /gmu, "create or replace trigger ").replaceAll(/^(create (?:unique index|index|table|type|extension)) if not exists /gmu, "$1 ");
368
+ }
369
+ // src/cli/supabase-schemas.ts
370
+ const MODES = [
371
+ "pg-delta",
372
+ "migra",
373
+ "migrations"
374
+ ];
375
+ function isSupabaseSchemas(value) {
376
+ return MODES.some((mode) => mode === value);
377
+ }
378
+ /** The `--schemas` refusal, or `undefined` when the value is one of the modes. */
379
+ function schemasRefusal(command, value) {
380
+ return value === void 0 || isSupabaseSchemas(value) ? void 0 : `${command} --schemas must be ${MODES.join(", ")} (got ${value})`;
381
+ }
382
+ /**
383
+ * `--schemas`, else `supabase.schemas`, else `migra` when `config.toml` sets
384
+ * `[experimental.pgdelta] enabled = false`, else `pg-delta`: the default of new
385
+ * Supabase projects and of the next Supabase CLI major.
386
+ */
387
+ function resolveSchemas(cwd, config, flag) {
388
+ const toml = supabaseConfig(cwd).pgDelta;
389
+ const mode = flag ?? config.supabase?.schemas ?? (toml?.enabled === false ? "migra" : "pg-delta");
390
+ switch (mode) {
391
+ case "pg-delta": return {
392
+ mode,
393
+ schemaDir: toml?.schemaDir ?? declarativeSchemaDir()
394
+ };
395
+ case "migra":
396
+ case "migrations": return { mode };
397
+ default: return mode;
398
+ }
399
+ }
400
+ // src/cli/supabase-hook/memberships.ts
401
+ function memberForPlan(input) {
402
+ const memberFor = input.scopes.map((scope) => scope.name).filter((name) => hasMemberFor({
403
+ dialect: "supabase",
404
+ ...input
405
+ }, name));
406
+ const holders = memberFor.filter((name) => hasPermittedUsers(input, name));
407
+ const entries = /* @__PURE__ */ new Map();
408
+ for (const name of memberFor) {
409
+ const mapped = memberForTable(input, name);
410
+ const found = mapped === void 0 ? memberForSources(input, name).map((source) => source.sql.manifest) : [mappedMembership(mapped, input.scopes, name)];
411
+ for (const entry of found) entries.set(JSON.stringify(entry), entry);
412
+ }
413
+ return {
414
+ memberFor,
415
+ holders,
416
+ memberships: [...entries.values()]
417
+ };
418
+ }
419
+ /**
420
+ * An `rls.memberships` table in the manifest's `tableMembershipSource` /
421
+ * `junctionMembershipSource` shape, for scope `name`.
422
+ */
423
+ function mappedMembership(mapped, scopes, name) {
424
+ const id = scopeColumn(mapped, scopes, name) ?? "";
425
+ const within = {};
426
+ for (const ancestor of scopeChain(scopes, name).slice(1)) {
427
+ const column = scopeColumn(mapped, scopes, ancestor);
428
+ if (column !== void 0) within[ancestor] = column;
429
+ }
430
+ const role = memberRoleOf(mapped);
431
+ const columns = [
432
+ mapped.user,
433
+ id,
434
+ ...role.columns,
435
+ ...Object.values(within),
436
+ ...typeof mapped.via === "string" ? [mapped.via] : [],
437
+ ...mapped.expiresAt === void 0 ? [] : [mapped.expiresAt],
438
+ ...mapped.disabledAt === void 0 ? [] : [mapped.disabledAt]
439
+ ];
440
+ return {
441
+ table: qualifySqlTable(mapped.table),
442
+ user: { column: mapped.user },
443
+ scope: { value: name },
444
+ id: { column: id },
445
+ role: roleManifest(role),
446
+ ...Object.keys(within).length === 0 ? {} : { within: { columns: within } },
447
+ ...mapped.via === void 0 ? {} : { via: typeof mapped.via === "string" ? { column: mapped.via } : { value: mapped.via.value } },
448
+ ...mapped.expiresAt === void 0 ? {} : { expiresAt: { column: mapped.expiresAt } },
449
+ ...mapped.disabledAt === void 0 ? {} : { disabledAt: { column: mapped.disabledAt } },
450
+ columns: [...new Set(columns)]
451
+ };
452
+ }
453
+ function positiveInteger(value, label) {
454
+ const number = typeof value === "string" ? Number(value) : value;
455
+ if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) throw configError(`PermDock CLI: ${label} must be a positive integer`);
456
+ return number;
457
+ }
458
+ /**
459
+ * Where the hook reads the active first-scope id: `supabase.hook.activeFrom`,
460
+ * or `app_metadata.active_<root>` by default.
461
+ */
462
+ function activeSource(input, root) {
463
+ const spec = input ?? `app_metadata.active_${root}`;
464
+ if (typeof spec === "string" && spec.startsWith("app_metadata.")) {
465
+ const key = spec.slice(13);
466
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(key)) throw configError(`PermDock CLI: unsafe app_metadata key '${key}'`);
467
+ return { appMetadata: key };
468
+ }
469
+ if (typeof spec !== "string") return {
470
+ table: spec.table,
471
+ column: spec.column,
472
+ id: spec.id ?? "id"
473
+ };
474
+ const dot = spec.lastIndexOf(".");
475
+ if (dot <= 0) throw configError(`PermDock CLI: --active-from must be app_metadata.<key> or <table>.<column>, got '${spec}'`);
476
+ return {
477
+ table: spec.slice(0, dot),
478
+ column: spec.slice(dot + 1),
479
+ id: "id"
480
+ };
481
+ }
482
+ /**
483
+ * SQL for the active first-scope id, as text, for user `uid`; a table source
484
+ * compares its id column with `v_active_user`, declared as `userType`.
485
+ */
486
+ function activeFromSql(input, root) {
487
+ const from = activeSource(input, root);
488
+ if ("appMetadata" in from) return { sql: `claims -> 'app_metadata' ->> ${quoteLiteral(from.appMetadata)}` };
489
+ return {
490
+ sql: `(select a.${quoteIdent(from.column)}::text from ${quoteQualified(from.table)} a where a.${quoteIdent(from.id)} = v_active_user)`,
491
+ userType: `${quoteQualified(from.table)}.${quoteIdent(from.id)}%type`
492
+ };
493
+ }
494
+ /**
495
+ * One variable per user-keyed table `memberships_for` reads, holding the user
496
+ * (a uuid, as Supabase Auth issues) as that column's type, so each lookup
497
+ * compares the column uncast and its index applies.
498
+ */
499
+ function typedSourceUsers(parts) {
500
+ return parts.sources.map((source, index) => `\n v_user_${String(index)} ${source.sql.userType} := p_user;`).join("");
501
+ }
502
+ /**
503
+ * The remaining user-keyed variables of the hook: the attribute row and the
504
+ * active-tenant row, each as its column's type.
505
+ */
506
+ function typedUsers(parts) {
507
+ return [...parts.attrs?.table === void 0 || parts.attrs.columns.length === 0 ? [] : [`v_attrs_user ${quoteQualified(parts.attrs.table)}.${quoteIdent(parts.attrs.id)}%type := uid;`], ...parts.active.userType === void 0 ? [] : [`v_active_user ${parts.active.userType} := uid;`]].map((line) => `\n ${line}`).join("");
508
+ }
509
+ function isRoleList(role) {
510
+ return Array.isArray(role);
511
+ }
512
+ function junctionRoles(role) {
513
+ if (isRoleList(role)) return { sources: role };
514
+ return role;
515
+ }
516
+ /**
517
+ * `supabase.hook.memberships`, or one junction source per `rls.memberships`
518
+ * scope table when the hook leaves memberships unset. The junction sources read
519
+ * `suspension`, so a suspended instance's rows carry the keys it keeps.
520
+ */
521
+ function hookMemberships(memberships, tables, scopes, suspension) {
522
+ if (memberships !== void 0) return memberships;
523
+ return Object.entries(tables?.scopes ?? {}).map(([key, table]) => {
524
+ const scope = resolveScope(scopes, key) ?? key;
525
+ const id = scopeColumn(table, scopes, scope) ?? table.id;
526
+ const within = {};
527
+ for (const ancestor of scopeChain(scopes, scope).slice(1)) {
528
+ const column = scopeColumn(table, scopes, ancestor);
529
+ if (column !== void 0) within[ancestor] = column;
530
+ }
531
+ return junctionMembershipSource({
532
+ table: table.table,
533
+ scope,
534
+ ...id === void 0 ? {} : { id },
535
+ user: table.user,
536
+ roles: junctionRoles(table.role),
537
+ ...Object.keys(within).length === 0 ? {} : { within },
538
+ ...table.expiresAt === void 0 ? {} : { expiresAt: table.expiresAt },
539
+ ...table.disabledAt === void 0 ? {} : { disabledAt: table.disabledAt },
540
+ ...typeof table.via === "object" ? { via: table.via.value } : {},
541
+ ...suspension === void 0 ? {} : { suspension }
542
+ });
543
+ });
544
+ }
545
+ function checkSources(parts) {
546
+ if (parts.sources.length === 0) throw configError("PermDock CLI: supabase.hook.memberships needs at least one tableMembershipSource, junctionMembershipSource or blockMembershipSource source, or rls.memberships");
547
+ for (const source of parts.sources) {
548
+ if (source.sql === void 0 || typeof source.sql.select !== "function") throw configError("PermDock CLI: supabase.hook.memberships takes tableMembershipSource, junctionMembershipSource or blockMembershipSource sources from permdock/supabase");
549
+ const scope = source.sql.scope;
550
+ if (scope === void 0) continue;
551
+ if (resolveScope(parts.scopes, scope) !== scope) throw configError(`PermDock CLI: the ${source.sql.table} source names scope '${scope}', which the policy does not declare by that name`);
552
+ const chain = scopeChain(parts.scopes, scope);
553
+ const holds = new Set(source.sql.holds ?? [scope]);
554
+ const missing = chain.filter((ancestor) => !holds.has(ancestor));
555
+ if (missing.length > 0) throw configError(`PermDock CLI: the ${source.sql.table} source needs within columns for ${missing.join(", ")}: a ${scope} membership without every ancestor grants nothing`);
556
+ }
557
+ }
558
+ function entriesSql(parts) {
559
+ const tenant = `case when s.scope = ${quoteLiteral(parts.root)} then s.id else s.within ->> ${quoteLiteral(parts.root)} end`;
560
+ return parts.sources.map((source, index) => `select ${String(index)} as ord,
561
+ (${tenant}) as tenant,
562
+ jsonb_strip_nulls(jsonb_build_object(
563
+ 'scope', s.scope, 'id', s.id, 'within', s.within, 'roles', s.roles, 'via', s.via,
564
+ 'expires_at', s.expires_at, 'granted_by', s.granted_by, 'reason', s.reason,
565
+ 'member', case when s.member_group is not null then jsonb_build_object('group', s.member_group) end,
566
+ 'managed_by', s.managed_by, 'entitlements', s.seats${source.sql.keeps ? ", 'keep', s.keep" : ""}
567
+ )) as entry
568
+ from (
569
+ ${source.sql.select(`v_user_${String(index)}`).replaceAll(/^/gmu, " ")}
570
+ ) s`).join("\nunion all\n");
571
+ }
572
+ // src/cli/supabase-hook/entries.ts
573
+ const MEMBERSHIPS_FOR = "memberships_for";
574
+ const GLOBAL_ROLES_FOR = "global_roles_for";
575
+ function qualified(parts, name) {
576
+ return `${quoteIdent(parts.schema)}.${name}`;
577
+ }
578
+ /**
579
+ * `memberships_for(p_user uuid) returns table(ord int, entry jsonb)`: every
580
+ * membership entry the hook and `subject_for` read, one row per entry in the
581
+ * shape of a token's `memberships` claim. Both callers order and budget the
582
+ * rows themselves; the function never truncates. A suspended user has no
583
+ * entries, and an entry in a suspended tenant (`rls.suspension.scopes.<root>`)
584
+ * is dropped unless it carries the keys the tenant keeps, whatever the source
585
+ * filters itself. `security definer`, and it never compares `p_user` with
586
+ * `auth.uid()`. Execute belongs to `supabase_auth_admin` only.
587
+ */
588
+ function membershipEntriesSql(parts) {
589
+ return `${entriesFunction(parts, false)}\n\n${entriesFunction(parts, true)}`;
590
+ }
591
+ /**
592
+ * `memberships_for(p_user uuid, p_tenant text)`: the entries of `p_tenant`
593
+ * alone, filtered inside each source's read so a user in many tenants costs one
594
+ * tenant's rows. A null or unknown tenant answers no rows. `p_tenant` is text
595
+ * because an entry's tenant is the text of its id; `subject_for(p_user,
596
+ * p_tenant)` passes its tenant cast to text. Execute belongs to no client
597
+ * role.
598
+ */
599
+ function entriesFunction(parts, tenant) {
600
+ const fn = qualified(parts, MEMBERSHIPS_FOR);
601
+ const params = tenant ? "p_user uuid, p_tenant text" : "p_user uuid";
602
+ const types = tenant ? "uuid, text" : "uuid";
603
+ const suspended = parts.users === void 0 ? "" : `
604
+ if not ${activeRowSql(parts.users, "p_user")} then
605
+ return;
606
+ end if;`;
607
+ const filters = [...tenant ? ["x.tenant = p_tenant"] : [], ...parts.tenants === void 0 ? [] : [`(x.tenant is null or x.entry ? 'keep' or ${activeTenantSql(parts.tenants, "x.tenant")})`]];
608
+ return `-- the membership entries ${tenant ? "of one tenant that subject_for(p_user, p_tenant) reads" : "the hook and subject_for read for p_user"}; no client role may execute it
609
+ create or replace function ${fn}(${params})
610
+ returns table (ord integer, entry jsonb)
611
+ language plpgsql
612
+ stable
613
+ security definer
614
+ set search_path = ''
615
+ as $$
616
+ #variable_conflict use_column
617
+ declare${typedSourceUsers(parts)}
618
+ begin${suspended}
619
+ return query
620
+ select x.ord, x.entry
621
+ from (
622
+ ${entriesSql(parts).replaceAll(/^/gmu, " ")}
623
+ ) x${filters.length === 0 ? "" : `\n where ${filters.join("\n and ")}`};
624
+ end;
625
+ $$;
626
+ revoke execute on function ${fn}(${types}) from public, anon, authenticated;`;
627
+ }
628
+ /**
629
+ * Whether the tenant whose id is the text `id` has an active row. Compared as
630
+ * text, like the per-source filters: the tenants table's id column need not
631
+ * have the root scope's type, and a failed cast would fail the token hook.
632
+ */
633
+ function activeTenantSql(row, id) {
634
+ const where = [`s.${quoteIdent(row.id)}::text = ${id}`];
635
+ if (row.disabledAt !== void 0) where.push(`s.${quoteIdent(row.disabledAt)} is null`);
636
+ if (row.status !== void 0) {
637
+ const values = (row.active ?? []).map(quoteLiteral).join(", ");
638
+ where.push(`s.${quoteIdent(row.status)}::text = any(array[${values}]::text[])`);
639
+ }
640
+ return `exists (select 1 from ${quoteTable(qualifySqlTable(row.table))} s where ${where.join(" and ")})`;
641
+ }
642
+ /**
643
+ * `global_roles_for(p_user uuid) returns jsonb`: the sorted, distinct global
644
+ * roles of `p_user` as a json array, for the hook's `roles` and `user_role`
645
+ * claims and for `subject_for`. Empty without a roles source. `security
646
+ * definer`, like `memberships_for`, so the hook needs no grant on the roles
647
+ * tables.
648
+ */
649
+ function globalRolesSql(parts) {
650
+ const rows = parts.roles;
651
+ if (rows === void 0) return "";
652
+ const fn = qualified(parts, GLOBAL_ROLES_FOR);
653
+ return `-- the global roles of p_user as a json array; no client role may execute it
654
+ create or replace function ${fn}(p_user uuid)
655
+ returns jsonb
656
+ language plpgsql
657
+ stable
658
+ security definer
659
+ set search_path = ''
660
+ as $$
661
+ declare
662
+ v_roles_user ${quoteQualified(rows.table)}.${quoteIdent(rows.user)}%type := p_user;
663
+ held jsonb;
664
+ begin
665
+ select coalesce(jsonb_agg(distinct ${rows.roleSql} order by ${rows.roleSql}) filter (where ${rows.roleSql} is not null), '[]'::jsonb)
666
+ into held
667
+ from ${rows.from}
668
+ where ${rows.userSql} = v_roles_user;
669
+ return held;
670
+ end;
671
+ $$;
672
+ revoke execute on function ${fn}(uuid) from public, anon, authenticated;`;
673
+ }
674
+ /**
675
+ * Execute on both readers for the invoker hook, which runs as
676
+ * `supabase_auth_admin`.
677
+ */
678
+ function entriesGrantsSql(parts) {
679
+ return [MEMBERSHIPS_FOR, ...parts.roles === void 0 ? [] : [GLOBAL_ROLES_FOR]].map((name) => `\ngrant execute on function ${qualified(parts, name)}(uuid) to supabase_auth_admin;`).join("");
680
+ }
681
+ /** The `held` assignment, from `global_roles_for` or an empty array. */
682
+ function heldSql(parts, user) {
683
+ return parts.roles === void 0 ? ` held := '[]'::jsonb;` : ` held := ${qualified(parts, GLOBAL_ROLES_FOR)}(${user});`;
684
+ }
685
+ /** The tenant id of an entry, as the hook orders by it. */
686
+ function entryTenantSql(parts, alias) {
687
+ const root = quoteLiteral(parts.root);
688
+ return `case when ${alias}.entry ->> 'scope' = ${root} then ${alias}.entry ->> 'id' else ${alias}.entry -> 'within' ->> ${root} end`;
689
+ }
690
+ // src/cli/supabase-hook/api.ts
691
+ const SUBJECT_FOR = "subject_for";
692
+ const PERMDOCK_SUBJECT = "permdock_subject";
693
+ /**
694
+ * `subject_for(p_user uuid) returns jsonb`: what the hook would put in a token
695
+ * for `p_user`, from the same membership, role, suspension and version reads,
696
+ * plus the custom roles the user holds when `database` mode keeps them in
697
+ * tables. A backend that only has PostgREST (`postgrestSources`) builds a
698
+ * subject for an acting user or a job from it. Naming the user is why no client
699
+ * role may execute it.
700
+ */
701
+ function subjectForSql(parts, config) {
702
+ return subjectSql(parts, config, false);
703
+ }
704
+ /**
705
+ * `subject_for(p_user, p_tenant) returns jsonb`: `subject_for(p_user)` for one
706
+ * tenant. The memberships are the entries `memberships_for(p_user, p_tenant)`
707
+ * reads for that tenant alone, so the custom roles and their versions follow
708
+ * the one tenant, and `team_ids` keeps the teams of that tenant (none without a
709
+ * membership there, and none when `supabase.hook.teams` has no `tenant` column
710
+ * to tell them apart). The global roles, the authorization version and the
711
+ * `claims` of `supabase.hook.claims` are the user's, not the tenant's. An
712
+ * unknown tenant, a tenant the user holds no membership in and a null
713
+ * `p_tenant` answer with no memberships: the function never reads another
714
+ * tenant. Same security posture as the one-argument form: `security definer`,
715
+ * empty `search_path`, no client role may execute it.
716
+ */
717
+ function subjectForTenantSql(parts, config) {
718
+ return subjectSql(parts, config, true);
719
+ }
720
+ function subjectSql(parts, config, tenant) {
721
+ const schema = quoteIdent(parts.schema);
722
+ const fn = `${schema}.${SUBJECT_FOR}`;
723
+ const tenantType = tenant ? tenantTypeFor(parts, config) : "";
724
+ const params = tenant ? `p_user uuid, p_tenant ${tenantType}` : "p_user uuid";
725
+ const types = tenant ? `uuid, ${tenantType}` : "uuid";
726
+ const entries = tenant ? `${schema}.${MEMBERSHIPS_FOR}(uid, p_tenant::text)` : `${schema}.${MEMBERSHIPS_FOR}(uid)`;
727
+ const roles = heldSql(parts, "uid");
728
+ const suspended = parts.users === void 0 ? "" : `
729
+ if not ${activeRowSql(parts.users, "uid")} then
730
+ return jsonb_build_object('id', uid::text, 'active', false);
731
+ end if;`;
732
+ const version = parts.version ? `
733
+ select v.version into ver from ${schema}.${quoteIdent(AUTHZ_VERSION_TABLE)} v where v.user_id = uid;
734
+ ver := coalesce(ver, 0);` : "";
735
+ const teamsConfig = parts.hook.teams;
736
+ const teamTenant = teamsConfig !== void 0 && tenant && teamsConfig.tenant !== void 0 ? `
737
+ where team_id in (
738
+ select t.${quoteIdent(teamsConfig.team)} from ${quoteQualified(teamsConfig.table)} t
739
+ where t.${quoteIdent(teamsConfig.tenant)}::text = p_tenant::text
740
+ )` : "";
741
+ const teams = teamsConfig === void 0 || tenant && teamsConfig.tenant === void 0 ? "" : `
742
+ select ${tenant ? "case when memberships = '[]'::jsonb then '[]'::jsonb else " : ""}coalesce((
743
+ select jsonb_agg(to_jsonb(u.id::text) order by u.n)
744
+ from unnest(array(
745
+ select team_id from ${quoteIdent(parts.helpers.schema)}.${quoteIdent(hookTeamReader(parts))}(uid, ${tenant ? "p_tenant::text" : "null"}) as team(team_id)${teamTenant}
746
+ )) with ordinality as u(id, n)
747
+ ), '[]'::jsonb)${tenant ? " end" : ""}
748
+ into team_ids;
749
+ if team_ids <> '[]'::jsonb then
750
+ claims := jsonb_set(claims, '{team_ids}', team_ids);
751
+ end if;`;
752
+ const extra = parts.extra.map((entry) => `
753
+ extra := ${quoteTable(entry.fn)}(uid);
754
+ if extra is not null then
755
+ claims := jsonb_set(claims, ${quoteLiteral(`{${entry.claim}}`)}, extra);
756
+ end if;`).join("");
757
+ const custom = customRolesOn(config.rls) && resolveAuthorize(config) === "database" ? customRolesOfSql(parts, sqlType(firstScopeType(config.rls?.scopeTypes, parts.scopes))) : "";
758
+ return `-- the subject the hook would mint for p_user${tenant ? ", with the memberships of p_tenant only" : ""}, for a backend acting for a stored user; no client role may execute it
759
+ create or replace function ${fn}(${params})
760
+ returns jsonb
761
+ language plpgsql
762
+ stable
763
+ security definer
764
+ set search_path = ''
765
+ as $$
766
+ declare
767
+ uid uuid := p_user;
768
+ held jsonb;
769
+ memberships jsonb;
770
+ custom jsonb := '[]'::jsonb;${custom === "" ? "" : "\n custom_versions jsonb := '{}'::jsonb;"}
771
+ ver bigint;
772
+ claims jsonb := '{}'::jsonb;${teamsConfig === void 0 ? "" : "\n team_ids jsonb := '[]'::jsonb;"}${parts.extra.length === 0 ? "" : "\n extra jsonb;"}${typedUsers(parts)}
773
+ begin
774
+ if uid is null or not exists (select 1 from auth.users u where u.id = uid) then
775
+ return null;
776
+ end if;${suspended}
777
+ ${roles}
778
+ select coalesce(jsonb_agg(x.entry order by x.ord, x.entry ->> 'scope', x.entry ->> 'id', x.entry::text), '[]'::jsonb)
779
+ into memberships
780
+ from ${entries} x;${custom}${version}${teams}${extra}
781
+ return jsonb_strip_nulls(jsonb_build_object(
782
+ 'claims', case when claims = '{}'::jsonb then null else claims end,
783
+ 'id', uid::text,
784
+ 'active', true,
785
+ 'roles', held,
786
+ 'memberships', memberships,
787
+ 'customRoles', custom,${custom === "" ? "" : "\n 'customRolesVersions', case when custom_versions = '{}'::jsonb then null else custom_versions end,"}
788
+ 'authzVersion', ver
789
+ ));
790
+ end;
791
+ $$;
792
+ revoke execute on function ${fn}(${types}) from public, anon, authenticated;`;
793
+ }
794
+ /**
795
+ * `<helpers schema>.permdock_subject() returns jsonb`: `subject_for` for the
796
+ * signed-in user, `null` for an anonymous or suspended one. A client role may
797
+ * execute it because it names no user: `bootstrap` calls it so one round trip
798
+ * returns the subject the authorizer would otherwise read again.
799
+ */
800
+ function permdockSubjectSql(parts) {
801
+ const helpers = quoteIdent(parts.helpers.schema);
802
+ const fn = `${helpers}.${PERMDOCK_SUBJECT}`;
803
+ return `-- the signed-in user's subject_for record, for a bootstrap that seeds the authorizer; null when anonymous or suspended
804
+ create or replace function ${fn}()
805
+ returns jsonb
806
+ language plpgsql
807
+ stable
808
+ security definer
809
+ set search_path = ''
810
+ as $$
811
+ declare
812
+ subject jsonb := ${quoteIdent(parts.schema)}.${SUBJECT_FOR}((select ${helpers}.${USER_ID_HELPER}()));
813
+ begin
814
+ if subject is null or (subject ->> 'active') is distinct from 'true' then
815
+ return null;
816
+ end if;
817
+ return subject;
818
+ end;
819
+ $$;
820
+ revoke execute on function ${fn}() from public, anon, authenticated;
821
+ grant execute on function ${fn}() to authenticated;
822
+
823
+ ${permdockSubjectForTenantSql(parts)}`;
824
+ }
825
+ /**
826
+ * `<helpers schema>.permdock_subject(p_tenant text) returns jsonb`:
827
+ * `subject_for(p_user, p_tenant)` for the signed-in user, better-supabase's
828
+ * `subjectForTenant`. `null` for an anonymous or suspended caller, a null
829
+ * tenant, a tenant id that is not of the root scope's type, and a tenant the
830
+ * caller holds no membership in, so a page never sees another tenant's
831
+ * memberships. The record carries `tenant`, so a subject cache keeps it apart
832
+ * from the all-tenants record at the same version.
833
+ */
834
+ function permdockSubjectForTenantSql(parts) {
835
+ const helpers = quoteIdent(parts.helpers.schema);
836
+ const fn = `${helpers}.${PERMDOCK_SUBJECT}`;
837
+ return `-- the signed-in user's subject_for record for one tenant, better-supabase's subjectForTenant; null for a null, malformed or unknown tenant and for a tenant the caller is no member of
838
+ create or replace function ${fn}(p_tenant text)
839
+ returns jsonb
840
+ language plpgsql
841
+ stable
842
+ security definer
843
+ set search_path = ''
844
+ as $$
845
+ declare
846
+ v_tenant ${parts.tenantType};
847
+ subject jsonb;
848
+ begin
849
+ if p_tenant is null then
850
+ return null;
851
+ end if;
852
+ begin
853
+ v_tenant := p_tenant::${parts.tenantType};
854
+ exception when invalid_text_representation then
855
+ return null;
856
+ end;
857
+ subject := ${quoteIdent(parts.schema)}.${SUBJECT_FOR}((select ${helpers}.${USER_ID_HELPER}()), v_tenant);
858
+ if subject is null
859
+ or (subject ->> 'active') is distinct from 'true'
860
+ or coalesce(jsonb_array_length(subject -> 'memberships'), 0) = 0 then
861
+ return null;
862
+ end if;
863
+ return subject || jsonb_build_object('tenant', v_tenant::text);
864
+ end;
865
+ $$;
866
+ revoke execute on function ${fn}(text) from public, anon, authenticated;
867
+ grant execute on function ${fn}(text) to authenticated;`;
868
+ }
869
+ /**
870
+ * The PostgREST wrappers `supabase.hook.api` asks for: one `security invoker`
871
+ * function per reader, in the API schema, executable by `service_role` only.
872
+ * The `security definer` readers stay in the hook schema, which the Data API
873
+ * does not expose; `service_role` gets `usage` on it and `execute` on each
874
+ * reader, so no definer function sits in an exposed schema.
875
+ */
876
+ function apiWrappersSql(parts, config) {
877
+ const api = parts.hook.api;
878
+ if (api === void 0) return "";
879
+ const target = api.schema ?? "public";
880
+ const names = hookApiNames(api.prefix);
881
+ const source = quoteIdent(parts.schema);
882
+ const wrapper = (name, inner, params, args, types, returns) => {
883
+ const fn = `${quoteIdent(target)}.${quoteIdent(name)}`;
884
+ if (target === parts.schema && name === inner) throw configError(`PermDock CLI: supabase.hook.api would replace ${source}.${inner}: set api.schema or api.prefix`);
885
+ return `create or replace function ${fn}(${params})
886
+ returns ${returns}
887
+ language sql
888
+ stable
889
+ security invoker
890
+ set search_path = ''
891
+ as $$ select ${source}.${inner}(${args}) $$;
892
+ revoke execute on function ${fn}(${types}) from public, anon, authenticated;
893
+ grant execute on function ${fn}(${types}) to service_role;
894
+ grant execute on function ${source}.${inner}(${types}) to service_role;`;
895
+ };
896
+ return `-- supabase.hook.api: security invoker wrappers in ${quoteIdent(target)} for a backend that reaches the hook schema through the Data API; only service_role may execute them, and the security definer readers stay in ${source}
897
+ grant usage on schema ${source} to service_role;
898
+
899
+ ${wrapper(names.subjectFor, SUBJECT_FOR, "p_user uuid", "p_user", "uuid", "jsonb")}
900
+
901
+ ${wrapper(names.subjectFor, SUBJECT_FOR, `p_user uuid, p_tenant ${tenantTypeFor(parts, config)}`, "p_user, p_tenant", `uuid, ${tenantTypeFor(parts, config)}`, "jsonb")}
902
+
903
+ ${wrapper(names.membersOf, MEMBERS_OF, "p_scope text, p_id text", "p_scope, p_id", "text, text", "jsonb")}
904
+
905
+ ${wrapper(names.authzVersionFor, AUTHZ_VERSION_FOR, "p_user uuid", "p_user", "uuid", "bigint")}${storesCustomRoles(config) ? `\n\n${wrapper(names.rolesVersionFor, CUSTOM_ROLES_VERSION_FOR, `p_tenant ${tenantTypeFor(parts, config)}`, "p_tenant", tenantTypeFor(parts, config), "bigint")}` : ""}`;
906
+ }
907
+ /**
908
+ * Whether the custom roles live in the `permdock` tables, which keep a version
909
+ * per tenant.
910
+ */
911
+ function storesCustomRoles(config) {
912
+ return customRolesOn(config.rls) && resolveAuthorize(config) === "database";
913
+ }
914
+ function tenantTypeFor(parts, config) {
915
+ return sqlType(firstScopeType(config.rls?.scopeTypes, parts.scopes));
916
+ }
917
+ const CUSTOM_ROLES_VERSION_FOR = "custom_roles_version_for";
918
+ /**
919
+ * `custom_roles_version_for(p_tenant) returns bigint`: the custom-role version
920
+ * of one tenant, which every edit of a role in the tenant (or of a shared or
921
+ * platform role) raises. A backend that holds a subject read at one version
922
+ * reads this to know whether the tenant's custom roles moved since. No client
923
+ * role may execute it.
924
+ */
925
+ function customRolesVersionForSql(parts, config) {
926
+ if (!storesCustomRoles(config)) return "";
927
+ const fn = `${quoteIdent(parts.schema)}.${CUSTOM_ROLES_VERSION_FOR}`;
928
+ const type = tenantTypeFor(parts, config);
929
+ return `-- the custom-role version of p_tenant: its own counter plus the counter of the shared and platform roles; no client role may execute it
930
+ create or replace function ${fn}(p_tenant ${type})
931
+ returns bigint
932
+ language sql
933
+ stable
934
+ security definer
935
+ set search_path = ''
936
+ as $$
937
+ select coalesce(sum(v.version), 0)::bigint from ${`${quoteIdent(parts.helpers.schema)}.custom_role_version`} v
938
+ where v.tenant_id = p_tenant or v.tenant_id is null
939
+ $$;
940
+ revoke execute on function ${fn}(${type}) from public, anon, authenticated;`;
941
+ }
942
+ const AUTHZ_VERSION_FOR = "authz_version_for";
943
+ /**
944
+ * `authz_version_for(p_user uuid) returns bigint`: the authorization version
945
+ * `subject_for` reports, without reading roles or memberships, so a
946
+ * `claimsFirst` reread can check a token's freshness on every request and read
947
+ * the full subject only when it is behind. `null` for an unknown or suspended
948
+ * user, and when the version is off.
949
+ */
950
+ function authzVersionForSql(parts) {
951
+ const schema = quoteIdent(parts.schema);
952
+ const fn = `${schema}.${AUTHZ_VERSION_FOR}`;
953
+ return `-- the authorization version subject_for reports for p_user, for a cheap freshness check; no client role may execute it
954
+ create or replace function ${fn}(p_user uuid)
955
+ returns bigint
956
+ language plpgsql
957
+ stable
958
+ security definer
959
+ set search_path = ''
960
+ as $$
961
+ declare
962
+ uid uuid := p_user;
963
+ ver bigint;
964
+ begin
965
+ if uid is null or not exists (select 1 from auth.users u where u.id = uid) then
966
+ return null;
967
+ end if;${parts.users === void 0 ? "" : `
968
+ if not ${activeRowSql(parts.users, "uid")} then
969
+ return null;
970
+ end if;`}${parts.version ? `
971
+ select v.version into ver from ${schema}.${quoteIdent(AUTHZ_VERSION_TABLE)} v where v.user_id = uid;
972
+ ver := coalesce(ver, 0);` : ""}
973
+ return ver;
974
+ end;
975
+ $$;
976
+ revoke execute on function ${fn}(uuid) from public, anon, authenticated;`;
977
+ }
978
+ const MEMBERS_OF = "members_of";
979
+ function membersOfSql(parts) {
980
+ const fn = `${quoteIdent(parts.schema)}.${MEMBERS_OF}`;
981
+ const keep = parts.sources.some((source) => source.sql.keeps);
982
+ const rows = parts.sources.map((source) => source.sql.list(keep).replaceAll(/^/gmu, " ")).join("\n union all\n");
983
+ return `-- the live memberships of one scope instance, for a backend that lists members over PostgREST; no client role may execute it
984
+ create or replace function ${fn}(p_scope text, p_id text)
985
+ returns jsonb
986
+ language sql
987
+ stable
988
+ security definer
989
+ set search_path = ''
990
+ as $$
991
+ select coalesce(jsonb_agg(jsonb_build_object(
992
+ 'principal', jsonb_build_object('id', s.user_id),
993
+ 'membership', jsonb_strip_nulls(jsonb_build_object(
994
+ 'scope', s.scope, 'id', s.id, 'within', s.within, 'roles', s.roles, 'via', s.via,
995
+ 'expires_at', s.expires_at, 'granted_by', s.granted_by, 'reason', s.reason,
996
+ 'member', case when s.member_group is not null then jsonb_build_object('group', s.member_group) end,
997
+ 'managed_by', s.managed_by, 'entitlements', s.seats${keep ? ", 'keep', s.keep" : ""}
998
+ ))
999
+ ) order by s.user_id, s.roles::text), '[]'::jsonb)
1000
+ from (
1001
+ ${rows}
1002
+ ) s
1003
+ $$;
1004
+ revoke execute on function ${fn}(text, text) from public, anon, authenticated;`;
1005
+ }
1006
+ /**
1007
+ * The custom roles `p_user` holds: tenant and shared roles named on a
1008
+ * membership of the scope (and instance) they live at, and platform roles among
1009
+ * the global roles, each with its grants and includes in `CustomRole` form. One
1010
+ * indexed read of `custom_role_compiled` per held role. A shadowed tenant role
1011
+ * comes along; `resolveCustomRole`'s callers drop it.
1012
+ */
1013
+ function customRolesOfSql(parts, tenantType) {
1014
+ const compiled = `${quoteIdent(parts.helpers.schema)}.custom_role_compiled`;
1015
+ const root = quoteLiteral(parts.root);
1016
+ return `
1017
+ select coalesce(jsonb_agg(jsonb_strip_nulls(jsonb_build_object(
1018
+ 'name', c.role,
1019
+ 'shared', case when c.tenant_id is null and c.scope <> 'global' then true end,
1020
+ 'tenant', c.tenant_id::text,
1021
+ 'scope', c.scope,
1022
+ 'id', c.scope_id,
1023
+ 'grants', c.grants,
1024
+ 'includes', case when cardinality(c.includes) > 0 then to_jsonb(c.includes) end
1025
+ )) order by c.tenant_id::text, c.scope, c.scope_id, c.role), '[]'::jsonb)
1026
+ into custom
1027
+ from (
1028
+ select distinct c.tenant_id, c.scope, c.scope_id, c.role, c.grants, c.includes
1029
+ from (
1030
+ select m ->> 'scope' as scope, m ->> 'id' as id,
1031
+ case when m ->> 'scope' = ${root} then m ->> 'id' else m -> 'within' ->> ${root} end as tenant,
1032
+ r.role
1033
+ from jsonb_array_elements(memberships) m
1034
+ cross join lateral jsonb_array_elements_text(case when jsonb_typeof(m -> 'roles') = 'array' then m -> 'roles' else '[]'::jsonb end) r(role)
1035
+ ) h
1036
+ cross join lateral (
1037
+ select t.tenant_id, t.scope, t.scope_id, t.role, t.grants, t.includes from ${compiled} t
1038
+ where t.scope = h.scope and t.role = h.role
1039
+ and (t.tenant_id is null and t.scope_id is null or t.tenant_id = h.tenant::${tenantType})
1040
+ and (t.scope_id is null or t.scope_id = h.id)
1041
+ ) c
1042
+ union
1043
+ select t.tenant_id, t.scope, t.scope_id, t.role, t.grants, t.includes from ${compiled} t
1044
+ where t.scope = 'global' and t.tenant_id is null and t.role in (select jsonb_array_elements_text(held))
1045
+ ) c;
1046
+ -- the custom-role version of each tenant where a held role is a custom one, so a cached record is served only at the version it was read at
1047
+ select coalesce(jsonb_object_agg(v.tenant, ${quoteIdent(parts.schema)}.${CUSTOM_ROLES_VERSION_FOR}(v.tenant::${tenantType})), '{}'::jsonb)
1048
+ into custom_versions
1049
+ from (
1050
+ select distinct case when m ->> 'scope' = ${root} then m ->> 'id' else m -> 'within' ->> ${root} end as tenant
1051
+ from jsonb_array_elements(memberships) m
1052
+ where exists (
1053
+ select 1 from jsonb_array_elements_text(case when jsonb_typeof(m -> 'roles') = 'array' then m -> 'roles' else '[]'::jsonb end) r(role)
1054
+ where r.role in (select k ->> 'name' from jsonb_array_elements(custom) k)
1055
+ )
1056
+ ) v
1057
+ where v.tenant is not null;`;
1058
+ }
1059
+ // src/cli/rls/approval-managers.ts
1060
+ /** Whether the signed-in user manages a requester; better-supabase reads it. */
1061
+ const MANAGES = "permdock_manages";
1062
+ /**
1063
+ * The approver check with `manager` leaves; only `permdock_is_approver` calls
1064
+ * it.
1065
+ */
1066
+ const APPROVES = "permdock_approves";
1067
+ const MANAGES_FOR = "permdock_manages_for";
1068
+ function named$1(value) {
1069
+ return typeof value === "string" && value !== "";
1070
+ }
1071
+ function checked$1(managers, ctx) {
1072
+ if (typeof managers !== "object" || managers === null || !("table" in managers && named$1(managers.table)) || !("user" in managers && named$1(managers.user)) || !("manager" in managers && named$1(managers.manager))) throw configError("PermDock CLI: rls.approvals.managers needs { table, user, manager }: the table that names each user's manager, its user column and its manager column");
1073
+ const tenant = "tenant" in managers ? managers.tenant : void 0;
1074
+ if (tenant !== void 0 && !named$1(tenant)) throw configError("PermDock CLI: rls.approvals.managers.tenant must be a column name");
1075
+ if (tenant === void 0 && ctx.scopes.length > 0) throw configError("PermDock CLI: rls.approvals.managers needs `tenant`, the column of the manager table or view that holds each edge's tenant; without it an edge in one tenant would count in every tenant");
1076
+ return {
1077
+ table: managers.table,
1078
+ user: managers.user,
1079
+ manager: managers.manager,
1080
+ ...tenant === void 0 ? {} : { tenant }
1081
+ };
1082
+ }
1083
+ /**
1084
+ * `rls.approvals.managers`: `permdock_manages(p_requester, p_levels)` walks the
1085
+ * app's manager table, keeping the edges of `p_tenant`, up to `levels` steps
1086
+ * (at most `MAX_MANAGER_LEVELS`) with a cycle guard, and `permdock_approves`
1087
+ * decides `manager` leaves with it and every other leaf through `base`, the
1088
+ * two-argument check. The requester never manages themselves into an approval.
1089
+ * `permdock_is_approver(p_approvers, p_tenant, p_requester)` routes through
1090
+ * `permdock_approves`, so the call with a requester decides `manager` leaves;
1091
+ * without one they match nobody. Without `delegations`, the four-argument
1092
+ * `permdock_is_approver` is written here; with them, `approvalDelegationsSql`
1093
+ * writes it and calls `permdock_approves` first.
1094
+ */
1095
+ function approvalManagersSql(ctx, given, isApprover, base, delegations) {
1096
+ const managers = checked$1(given, ctx);
1097
+ const table = quoteQualified(managers.table);
1098
+ const user = quoteIdent(managers.user);
1099
+ const boss = quoteIdent(managers.manager);
1100
+ const manages = qualified$1(ctx, MANAGES);
1101
+ const managesFor = qualified$1(ctx, MANAGES_FOR);
1102
+ const approves = qualified$1(ctx, APPROVES);
1103
+ const me = `${subjectIdSql(ctx)}::text`;
1104
+ const tenant = managers.tenant === void 0 ? void 0 : quoteIdent(managers.tenant);
1105
+ const edgeTenant = (alias) => tenant === void 0 ? "" : `\n and ${alias}.${tenant} = p_tenant::${tenantTypeOf(ctx)}`;
1106
+ const userType = ctx.dialect === "supabase" ? "uuid" : "text";
1107
+ const entry = delegations ? "" : `
1108
+ -- approvers with managers: permdock_approves for the signed-in user
1109
+ create or replace function ${isApprover}(p_approvers jsonb, p_tenant text, p_requester text, p_resource text)
1110
+ returns boolean
1111
+ language sql
1112
+ stable
1113
+ security definer
1114
+ set search_path = ''
1115
+ as $$
1116
+ select ${approves}(p_approvers, p_tenant, p_requester)
1117
+ $$;
1118
+ revoke execute on function ${isApprover}(jsonb, text, text, text) from public, anon;
1119
+ grant execute on function ${isApprover}(jsonb, text, text, text) to authenticated;
1120
+ `;
1121
+ const twoArguments = `
1122
+ -- approvers with managers: the two-argument call decides manager leaves when it passes the requester
1123
+ create or replace function ${isApprover}(p_approvers jsonb, p_tenant text default null, p_requester text default null)
1124
+ returns boolean
1125
+ language sql
1126
+ stable
1127
+ security definer
1128
+ set search_path = ''
1129
+ as $$
1130
+ select coalesce(${approves}(p_approvers, p_tenant, p_requester), false)
1131
+ $$;
1132
+ revoke execute on function ${isApprover}(jsonb, text, text) from public, anon;
1133
+ grant execute on function ${isApprover}(jsonb, text, text) to authenticated;
1134
+ `;
1135
+ return `
1136
+ -- approval managers: whether p_user manages p_requester within p_levels steps of ${managers.table}
1137
+ create or replace function ${managesFor}(p_user text, p_requester text, p_levels integer, p_tenant text default null)
1138
+ returns boolean
1139
+ language sql
1140
+ stable
1141
+ security definer
1142
+ set search_path = ''
1143
+ as $$
1144
+ with recursive chain (id, depth, path) as (
1145
+ select m.${boss}::text, 1, array[p_requester, m.${boss}::text]
1146
+ from ${table} m
1147
+ where m.${user} = p_requester::${userType}
1148
+ and m.${boss} is not null${edgeTenant("m")}
1149
+ union all
1150
+ select m.${boss}::text, c.depth + 1, c.path || m.${boss}::text
1151
+ from chain c
1152
+ join ${table} m on m.${user} = c.id::${userType}
1153
+ where c.depth < least(p_levels, ${String(8)})
1154
+ and m.${boss} is not null
1155
+ and not (m.${boss}::text = any (c.path))${edgeTenant("m")}
1156
+ )
1157
+ select coalesce(
1158
+ p_requester <> ''
1159
+ and p_user <> ''
1160
+ and p_levels between 1 and ${String(8)}
1161
+ and p_user <> p_requester
1162
+ and exists (select 1 from chain c where c.id = p_user),
1163
+ false
1164
+ )
1165
+ $$;
1166
+ revoke execute on function ${managesFor}(text, text, integer, text) from public, anon, authenticated;
1167
+
1168
+ -- approval managers: whether the signed-in user manages p_requester within p_levels steps of ${managers.table}
1169
+ create or replace function ${manages}(p_requester text, p_levels integer, p_tenant text default null)
1170
+ returns boolean
1171
+ language sql
1172
+ stable
1173
+ security definer
1174
+ set search_path = ''
1175
+ as $$
1176
+ select ${managesFor}(${me}, p_requester, p_levels, p_tenant)
1177
+ $$;
1178
+ revoke execute on function ${manages}(text, integer, text) from public, anon, authenticated;
1179
+
1180
+ -- approval managers: approvers.by with manager leaves; only permdock_is_approver calls it
1181
+ create or replace function ${approves}(p_approvers jsonb, p_tenant text, p_requester text)
1182
+ returns boolean
1183
+ language plpgsql
1184
+ stable
1185
+ security definer
1186
+ set search_path = ''
1187
+ as $$
1188
+ declare
1189
+ v_item jsonb;
1190
+ v_levels jsonb;
1191
+ begin
1192
+ if p_approvers is null then
1193
+ return false;
1194
+ end if;
1195
+ if jsonb_typeof(p_approvers) = 'array' then
1196
+ if jsonb_array_length(p_approvers) = 0 then
1197
+ return false;
1198
+ end if;
1199
+ for v_item in select value from jsonb_array_elements(p_approvers) loop
1200
+ if not ${approves}(v_item, p_tenant, p_requester) then
1201
+ return false;
1202
+ end if;
1203
+ end loop;
1204
+ return true;
1205
+ end if;
1206
+ if jsonb_typeof(p_approvers) <> 'object' then
1207
+ return false;
1208
+ end if;
1209
+ case p_approvers ->> 'kind'
1210
+ when 'manager' then
1211
+ v_levels := coalesce(p_approvers -> 'levels', '1'::jsonb);
1212
+ if jsonb_typeof(v_levels) <> 'number' or v_levels::text !~ '^[0-9]{1,2}$' then
1213
+ return false;
1214
+ end if;
1215
+ return coalesce(${manages}(p_requester, v_levels::text::integer, p_tenant), false);
1216
+ when 'any-of' then
1217
+ if jsonb_typeof(p_approvers -> 'of') <> 'array' then
1218
+ return false;
1219
+ end if;
1220
+ for v_item in select value from jsonb_array_elements(p_approvers -> 'of') loop
1221
+ if ${approves}(v_item, p_tenant, p_requester) then
1222
+ return true;
1223
+ end if;
1224
+ end loop;
1225
+ return false;
1226
+ else
1227
+ return ${base}(p_approvers, p_tenant);
1228
+ end case;
1229
+ end;
1230
+ $$;
1231
+ revoke execute on function ${approves}(jsonb, text, text) from public, anon, authenticated;
1232
+ ${twoArguments}${entry}`;
1233
+ }
1234
+ // src/cli/rls/approval-sets.ts
1235
+ /** The caller plus active delegators, one hop. */
1236
+ const APPROVER_FOR_IDS = "permdock_approver_for_ids";
1237
+ /** Users the caller manages, walking down `rls.approvals.managers`. */
1238
+ const MANAGED_USER_IDS = "permdock_managed_user_ids";
1239
+ /**
1240
+ * Sets a policy uses to decide an approval in SQL. `permdock_approver_for_ids`
1241
+ * is the caller and, with delegations, each active delegator, one hop and no
1242
+ * further. `permdock_managed_user_ids` walks down the manager table from the
1243
+ * caller. Neither set contains the caller as someone they manage, and a
1244
+ * decision still refuses the requester: compare the set with `id <>
1245
+ * <requester>`.
1246
+ */
1247
+ function approvalSetsSql(ctx, options) {
1248
+ const me = subjectIdSql(ctx);
1249
+ const user = userTypeOf(ctx);
1250
+ const approvers = qualified$1(ctx, APPROVER_FOR_IDS);
1251
+ return `
1252
+ -- approvers: the caller, plus each active delegator, one hop
1253
+ create or replace function ${approvers}()
1254
+ returns setof ${user}
1255
+ language sql
1256
+ stable
1257
+ security definer
1258
+ cost 100
1259
+ rows 5
1260
+ parallel safe
1261
+ set search_path = ''
1262
+ as $$
1263
+ select ${me}
1264
+ where ${me} is not null${options.delegations ? `
1265
+ union
1266
+ select d.delegator
1267
+ from ${qualified$1(ctx, "approval_delegations")} d
1268
+ where d.delegate = ${me}
1269
+ and d."from" <= now()
1270
+ and d."until" > now()
1271
+ and d.delegator <> ${me}` : ""}
1272
+ $$;
1273
+ revoke execute on function ${approvers}() from public, anon;
1274
+ grant execute on function ${approvers}() to authenticated;
1275
+ ${options.managers === void 0 ? "" : managedSql$1(ctx, options.managers, me)}`;
1276
+ }
1277
+ function managedSql$1(ctx, managers, me) {
1278
+ const fn = qualified$1(ctx, MANAGED_USER_IDS);
1279
+ const table = quoteQualified(managers.table);
1280
+ const user = quoteIdent(managers.user);
1281
+ const boss = quoteIdent(managers.manager);
1282
+ const type = userTypeOf(ctx);
1283
+ const tenant = managers.tenant === void 0 ? void 0 : quoteIdent(managers.tenant);
1284
+ const argType = tenant === void 0 ? "" : tenantTypeOf(ctx);
1285
+ const argument = tenant === void 0 ? "" : `p_tenant ${argType}`;
1286
+ const seedTenant = tenant === void 0 ? "" : `\n and m.${tenant} = p_tenant`;
1287
+ const stepTenant = tenant === void 0 ? "" : `\n and m.${tenant} = p_tenant`;
1288
+ return `
1289
+ -- approval managers: users below the caller within p_tenant; the caller is not in the set, so a self-decision stays refused
1290
+ create or replace function ${fn}(${argument})
1291
+ returns setof ${type}
1292
+ language sql
1293
+ stable
1294
+ security definer
1295
+ cost 1000
1296
+ rows 50
1297
+ parallel safe
1298
+ set search_path = ''
1299
+ as $$
1300
+ with recursive down (id, depth, path) as (
1301
+ select m.${user}, 1, array[${me}, m.${user}]
1302
+ from ${table} m
1303
+ where m.${boss} = ${me}
1304
+ and m.${user} is not null
1305
+ and m.${user} <> ${me}${seedTenant}
1306
+ union all
1307
+ select m.${user}, d.depth + 1, d.path || m.${user}
1308
+ from down d
1309
+ join ${table} m on m.${boss} = d.id
1310
+ where d.depth < ${String(8)}
1311
+ and m.${user} is not null
1312
+ and m.${user} <> ${me}
1313
+ and not (m.${user} = any (d.path))${stepTenant}
1314
+ )
1315
+ select id from down
1316
+ $$;
1317
+ revoke execute on function ${fn}(${argType}) from public, anon;
1318
+ grant execute on function ${fn}(${argType}) to authenticated;
1319
+ `;
1320
+ }
1321
+ // src/cli/rls/approval-policies.ts
1322
+ /**
1323
+ * The objects `rls.approvals.tenantPolicies` adds; `tableApprovalPolicySource`
1324
+ * calls the function.
1325
+ */
1326
+ const APPROVAL_POLICIES = {
1327
+ table: "approval_policies",
1328
+ read: "permdock_approval_policies_for"
1329
+ };
1330
+ const COLUMN_DEFAULTS = {
1331
+ id: "id",
1332
+ tenant: "tenant",
1333
+ name: "name",
1334
+ body: "body",
1335
+ enabled: "enabled",
1336
+ createdAt: "created_at"
1337
+ };
1338
+ const KEY = /^[A-Za-z][\w-]*(?:\.[A-Za-z][\w-]*)+$/u;
1339
+ /**
1340
+ * `rls.approvals.tenantPolicies`: one table of `ApprovalPolicy` bodies, a
1341
+ * tenant row per requirement a tenant adds and platform floors with `tenant`
1342
+ * null. Members read their tenants' rows and the floors; a holder of `manage`
1343
+ * in a tenant writes that tenant's rows; nobody but the owner writes a floor.
1344
+ * `permdock_approval_policies_for(p_tenants)` answers the enabled bodies with
1345
+ * the row's tenant set, floors first, and only the owner may execute it, since
1346
+ * it reads every tenant.
1347
+ */
1348
+ function named(value) {
1349
+ return typeof value === "string" && value !== "";
1350
+ }
1351
+ /** `options` with its optional parts checked; `manage` is the only required one. */
1352
+ function checked(options) {
1353
+ if (options === null || typeof options !== "object" || !("manage" in options) || typeof options.manage !== "string" || !KEY.test(options.manage)) throw configError("PermDock CLI: rls.approvals.tenantPolicies needs { manage: '<permission key>' }, the permission whose holders in a tenant edit its approval policies");
1354
+ const given = { ...options };
1355
+ for (const key of ["table", "function"]) if (given[key] !== void 0 && !named(given[key])) throw configError(`PermDock CLI: rls.approvals.tenantPolicies.${key} must be a non-empty string`);
1356
+ const columns = given["columns"];
1357
+ if (columns !== void 0) {
1358
+ if (typeof columns !== "object" || columns === null) throw configError("PermDock CLI: rls.approvals.tenantPolicies.columns must be an object of column names");
1359
+ for (const [key, value] of Object.entries(columns)) if (!Object.hasOwn(COLUMN_DEFAULTS, key) || !named(value)) throw configError(`PermDock CLI: rls.approvals.tenantPolicies.columns.${key} must be a column name; the keys are ${Object.keys(COLUMN_DEFAULTS).join(", ")}`);
1360
+ }
1361
+ const path = given["path"];
1362
+ if (path !== void 0 && !(Array.isArray(path) && path.every(named))) throw configError("PermDock CLI: rls.approvals.tenantPolicies.path must be a list of keys");
1363
+ return given;
1364
+ }
1365
+ function approvalPoliciesSql(ctx, given, actorMayWrite = false) {
1366
+ const options = checked(given);
1367
+ const root = ctx.scopes[0]?.name;
1368
+ if (root === void 0) throw configError("PermDock CLI: rls.approvals.tenantPolicies needs a tenant scope; declare one in the policy's scopes");
1369
+ const column = (key) => quoteIdent(options.columns?.[key] ?? COLUMN_DEFAULTS[key]);
1370
+ const id = column("id");
1371
+ const tenantColumn = column("tenant");
1372
+ const name = column("name");
1373
+ const bodyColumn = column("body");
1374
+ const enabled = column("enabled");
1375
+ const createdAt = column("createdAt");
1376
+ const path = options.path ?? [];
1377
+ const keys = `{${path.map((key) => `"${key.replaceAll("\"", String.raw`\"`)}"`).join(",")}}`;
1378
+ const policyIn = (alias) => path.length === 0 ? `${alias}${bodyColumn}` : `(${alias}${bodyColumn} #> ${quoteLiteral(keys)})`;
1379
+ const tableName = options.table === void 0 ? APPROVAL_POLICIES.table : options.table.split(".").at(-1) ?? APPROVAL_POLICIES.table;
1380
+ const table = options.table === void 0 ? qualified$1(ctx, APPROVAL_POLICIES.table) : quoteQualified(options.table);
1381
+ const fn = qualified$1(ctx, options.function ?? APPROVAL_POLICIES.read);
1382
+ const member = `${tenantColumn} in (select m.id::text from ${qualified$1(ctx, memberIdsHelper(root))}() m(id))`;
1383
+ const manages = `exists (
1384
+ select 1
1385
+ from ${qualified$1(ctx, checkName(permittedByPermissionHelper(root)))}(${quoteLiteral(options.manage)}) i(id)
1386
+ where i.id::text = ${tenantColumn}
1387
+ )`;
1388
+ const writable = actorMayWrite ? ` and (select ${qualified$1(ctx, ACTOR_MAY_WRITE)}())` : "";
1389
+ const own = `${tenantColumn} is not null and ${subjectIdSql(ctx)} is not null and ${manages}${writable}`;
1390
+ const policy = (suffix) => quoteIdent(`${tableName}_${suffix}`);
1391
+ return `
1392
+ -- approval policies: requirements a tenant keeps as data, plus platform floors (tenant null); tableApprovalPolicySource reads them
1393
+ create table if not exists ${table} (
1394
+ ${id} text primary key default gen_random_uuid()::text,
1395
+ ${tenantColumn} text,
1396
+ ${name} text not null,
1397
+ ${bodyColumn} jsonb not null,
1398
+ ${enabled} boolean not null default true,
1399
+ ${createdAt} timestamptz not null default now(),
1400
+ updated_at timestamptz not null default now(),
1401
+ constraint ${quoteIdent(`${tableName}_body`)} check (jsonb_typeof(${policyIn("")}) = 'object' and ${policyIn("")} ? 'approval')
1402
+ );
1403
+ create index if not exists ${quoteIdent(`${tableName}_tenant`)} on ${table} (${tenantColumn});
1404
+ alter table ${table} enable row level security;
1405
+ revoke all on table ${table} from anon, public;
1406
+ grant select, insert, update, delete on table ${table} to authenticated;
1407
+ drop policy if exists ${policy("read")} on ${table};
1408
+ create policy ${policy("read")} on ${table}
1409
+ for select to authenticated
1410
+ using (${tenantColumn} is null or ${member});
1411
+ drop policy if exists ${policy("insert")} on ${table};
1412
+ create policy ${policy("insert")} on ${table}
1413
+ for insert to authenticated
1414
+ with check (${own});
1415
+ drop policy if exists ${policy("update")} on ${table};
1416
+ create policy ${policy("update")} on ${table}
1417
+ for update to authenticated
1418
+ using (${own})
1419
+ with check (${own});
1420
+ drop policy if exists ${policy("delete")} on ${table};
1421
+ create policy ${policy("delete")} on ${table}
1422
+ for delete to authenticated
1423
+ using (${own});
1424
+
1425
+ -- approval policies: the enabled bodies for p_tenants and every floor, with the row's tenant; only the owner executes it
1426
+ create or replace function ${fn}(p_tenants text[])
1427
+ returns setof jsonb
1428
+ language sql
1429
+ stable
1430
+ set search_path = ''
1431
+ as $$
1432
+ select case
1433
+ when p.${tenantColumn} is null then ${policyIn("p.")} - 'tenant'
1434
+ else ${policyIn("p.")} || jsonb_build_object('tenant', p.${tenantColumn})
1435
+ end
1436
+ from ${table} p
1437
+ where p.${enabled}
1438
+ and (p.${tenantColumn} is null or p.${tenantColumn} = any(coalesce(p_tenants, '{}')))
1439
+ order by p.${tenantColumn} nulls first, p.${createdAt}, p.${id};
1440
+ $$;
1441
+ revoke execute on function ${fn}(text[]) from public, anon, authenticated;
1442
+ `;
1443
+ }
1444
+ // src/cli/rls/approvals.ts
1445
+ /**
1446
+ * `rls.approvals`' approver check; better-supabase's `isApprover` template
1447
+ * calls it.
1448
+ */
1449
+ const IS_APPROVER = "permdock_is_approver";
1450
+ /**
1451
+ * The objects `rls.approvals` adds. Names are part of the SQL contract
1452
+ * `supabaseApprovalStore` calls.
1453
+ */
1454
+ const APPROVAL_STORE = {
1455
+ table: "approval_requests",
1456
+ open: "permdock_approval_open",
1457
+ get: "permdock_approval_get",
1458
+ resolve: "permdock_approval_resolve",
1459
+ consume: "permdock_approval_consume",
1460
+ list: "permdock_approval_list",
1461
+ expire: "permdock_approval_expire",
1462
+ cancel: "permdock_approval_cancel",
1463
+ isApprover: IS_APPROVER,
1464
+ /**
1465
+ * The two-argument check `permdock_approves` falls back to for non-manager
1466
+ * leaves.
1467
+ */
1468
+ isApproverBase: "permdock_is_approver_base"
1469
+ };
1470
+ /** `body` as the row's filter columns hold it. */
1471
+ const COLUMNS = `p_request ->> 'token',
1472
+ p_request,
1473
+ p_request ->> 'status',
1474
+ p_request #>> '{subject,principal,tenant}',
1475
+ p_request #>> '{subject,principal,id}',
1476
+ p_request #>> '{subject,actor,id}',
1477
+ p_request #>> '{subject,session}',
1478
+ coalesce(jsonb_array_length(p_request -> 'approvals'), 0),
1479
+ p_request ->> 'createdAt',
1480
+ (p_request ->> 'expiresAt')::timestamptz,
1481
+ (p_request ->> 'consumedAt')::timestamptz`;
1482
+ /** The `ApprovalListFilter` in `p_filter`, over the row aliased `a`. */
1483
+ const FILTER = `(p_filter ->> 'status' is null or a.status = p_filter ->> 'status')
1484
+ and (p_filter ->> 'tenant' is null or a.tenant = p_filter ->> 'tenant')
1485
+ and (p_filter ->> 'principalId' is null or a.principal_id = p_filter ->> 'principalId')
1486
+ and (p_filter ->> 'actorId' is null or a.actor_id = p_filter ->> 'actorId')
1487
+ and (p_filter ->> 'session' is null or a.session = p_filter ->> 'session')`;
1488
+ function serverOnly(fn, args) {
1489
+ return `revoke execute on function ${fn}(${args}) from public, anon, authenticated;`;
1490
+ }
1491
+ const BODY_CHECK = `${APPROVAL_STORE.table}_body_schema`;
1492
+ /**
1493
+ * `rls.jsonSchema: true`: a pg_jsonschema check that `body` matches
1494
+ * `approval-request-v1.json`, added `not valid` and then validated.
1495
+ */
1496
+ function bodySchemaSql(table, body = "body", check = BODY_CHECK) {
1497
+ return `\n-- approval store: body matches schemas/approval-request-v1.json through pg_jsonschema\n${[
1498
+ "create schema if not exists extensions;",
1499
+ "create extension if not exists pg_jsonschema with schema extensions;",
1500
+ `alter table ${table} drop constraint if exists "${check}";`,
1501
+ `alter table ${table} add constraint "${check}" check (extensions.jsonb_matches_schema(${quoteLiteral(JSON.stringify(APPROVAL_REQUEST_SCHEMA))}::json, ${body})) not valid;`,
1502
+ `alter table ${table} validate constraint "${check}";`
1503
+ ].join("\n")}\n`;
1504
+ }
1505
+ /**
1506
+ * The approval store (`rls.approvals`): one table of `ApprovalRequest` bodies
1507
+ * with the columns a list filters on, and one `security definer` function per
1508
+ * `ApprovalStore` method, each one atomic statement. No client role may read
1509
+ * the table or execute the functions: approvals are opened and resolved by the
1510
+ * server, which grants its own role.
1511
+ */
1512
+ function approvalStoreSql(ctx, jsonSchema = false) {
1513
+ const table = qualified$1(ctx, APPROVAL_STORE.table);
1514
+ const fn = (name) => qualified$1(ctx, name);
1515
+ const index = (name) => `"${APPROVAL_STORE.table}_${name}"`;
1516
+ return `-- approval store: ApprovalRequest bodies, opened, resolved and consumed through the functions below; supabaseApprovalStore calls them
1517
+ create table if not exists ${table} (
1518
+ token text primary key,
1519
+ body jsonb not null,
1520
+ status text not null check (status in ('pending', 'approved', 'rejected', 'expired')),
1521
+ tenant text,
1522
+ principal_id text,
1523
+ actor_id text,
1524
+ session text,
1525
+ approvals integer not null default 0,
1526
+ created_at text not null,
1527
+ expires_at timestamptz not null,
1528
+ consumed_at timestamptz
1529
+ );
1530
+ create index if not exists ${index("page")} on ${table} (created_at collate "C", token collate "C");
1531
+ -- only open requests expire, so the index holds them alone
1532
+ create index if not exists ${index("pending_expires")} on ${table} (expires_at) where status = 'pending';
1533
+ alter table ${table} enable row level security;
1534
+ revoke all on table ${table} from anon, authenticated, public;
1535
+ ${jsonSchema ? bodySchemaSql(table) : ""}
1536
+ -- open a request; a repeated ask keeps the open record and replaces only an expired one
1537
+ create or replace function ${fn(APPROVAL_STORE.open)}(p_request jsonb)
1538
+ returns void
1539
+ language sql
1540
+ volatile
1541
+ security definer
1542
+ set search_path = ''
1543
+ as $$
1544
+ insert into ${table} as a (token, body, status, tenant, principal_id, actor_id, session, approvals, created_at, expires_at, consumed_at)
1545
+ values (
1546
+ ${COLUMNS}
1547
+ )
1548
+ on conflict (token) do update
1549
+ set body = excluded.body, status = excluded.status, tenant = excluded.tenant,
1550
+ principal_id = excluded.principal_id, actor_id = excluded.actor_id, session = excluded.session,
1551
+ approvals = excluded.approvals, created_at = excluded.created_at,
1552
+ expires_at = excluded.expires_at, consumed_at = excluded.consumed_at
1553
+ where a.status = 'expired' or a.expires_at <= now()
1554
+ $$;
1555
+ ${serverOnly(fn(APPROVAL_STORE.open), "jsonb")}
1556
+
1557
+ create or replace function ${fn(APPROVAL_STORE.get)}(p_token text)
1558
+ returns jsonb
1559
+ language sql
1560
+ stable
1561
+ security definer
1562
+ set search_path = ''
1563
+ as $$
1564
+ select a.body from ${table} a where a.token = p_token
1565
+ $$;
1566
+ ${serverOnly(fn(APPROVAL_STORE.get), "text")}
1567
+
1568
+ -- write a verdict over the record it was computed from: still pending, unexpired, with p_seen approvals
1569
+ create or replace function ${fn(APPROVAL_STORE.resolve)}(p_token text, p_next jsonb, p_seen integer)
1570
+ returns jsonb
1571
+ language sql
1572
+ volatile
1573
+ security definer
1574
+ set search_path = ''
1575
+ as $$
1576
+ update ${table} a
1577
+ set body = p_next,
1578
+ status = p_next ->> 'status',
1579
+ approvals = coalesce(jsonb_array_length(p_next -> 'approvals'), 0)
1580
+ where a.token = p_token
1581
+ and a.status = 'pending'
1582
+ and a.expires_at > now()
1583
+ and a.approvals = p_seen
1584
+ returning a.body
1585
+ $$;
1586
+ ${serverOnly(fn(APPROVAL_STORE.resolve), "text, jsonb, integer")}
1587
+
1588
+ -- consume an approved, unexpired, unconsumed request once
1589
+ create or replace function ${fn(APPROVAL_STORE.consume)}(p_token text, p_now text)
1590
+ returns jsonb
1591
+ language sql
1592
+ volatile
1593
+ security definer
1594
+ set search_path = ''
1595
+ as $$
1596
+ update ${table} a
1597
+ set consumed_at = p_now::timestamptz,
1598
+ body = a.body || jsonb_build_object('consumedAt', p_now)
1599
+ where a.token = p_token
1600
+ and a.status = 'approved'
1601
+ and a.consumed_at is null
1602
+ and a.expires_at > p_now::timestamptz
1603
+ returning a.body
1604
+ $$;
1605
+ ${serverOnly(fn(APPROVAL_STORE.consume), "text, text")}
1606
+
1607
+ -- one page in (createdAt, token) order after the cursor position
1608
+ create or replace function ${fn(APPROVAL_STORE.list)}(p_filter jsonb, p_after_created text, p_after_token text, p_limit integer)
1609
+ returns setof jsonb
1610
+ language sql
1611
+ stable
1612
+ security definer
1613
+ set search_path = ''
1614
+ as $$
1615
+ select a.body
1616
+ from ${table} a
1617
+ where ${FILTER}
1618
+ and (p_after_created is null
1619
+ or (a.created_at collate "C", a.token collate "C") > (p_after_created collate "C", p_after_token collate "C"))
1620
+ order by a.created_at collate "C", a.token collate "C"
1621
+ limit p_limit
1622
+ $$;
1623
+ ${serverOnly(fn(APPROVAL_STORE.list), "jsonb, text, text, integer")}
1624
+
1625
+ create or replace function ${fn(APPROVAL_STORE.expire)}(p_now text)
1626
+ returns integer
1627
+ language sql
1628
+ volatile
1629
+ security definer
1630
+ set search_path = ''
1631
+ as $$
1632
+ with expired as (
1633
+ update ${table} a
1634
+ set status = 'expired', body = a.body || '{"status":"expired"}'::jsonb
1635
+ where a.status = 'pending' and a.expires_at <= p_now::timestamptz
1636
+ returning 1
1637
+ )
1638
+ select count(*)::integer from expired
1639
+ $$;
1640
+ ${serverOnly(fn(APPROVAL_STORE.expire), "text")}
1641
+
1642
+ -- reject every pending request the filter matches, as system:<by>
1643
+ create or replace function ${fn(APPROVAL_STORE.cancel)}(p_filter jsonb, p_by text, p_note text, p_now text)
1644
+ returns integer
1645
+ language sql
1646
+ volatile
1647
+ security definer
1648
+ set search_path = ''
1649
+ as $$
1650
+ with cancelled as (
1651
+ update ${table} a
1652
+ set status = 'rejected',
1653
+ body = (a.body - 'note') || jsonb_strip_nulls(jsonb_build_object(
1654
+ 'status', 'rejected', 'resolvedAt', p_now, 'resolvedBy', 'system:' || p_by, 'note', p_note
1655
+ ))
1656
+ where a.status = 'pending'
1657
+ and ${FILTER.replaceAll("\n ", "\n ")}
1658
+ returning 1
1659
+ )
1660
+ select count(*)::integer from cancelled
1661
+ $$;
1662
+ ${serverOnly(fn(APPROVAL_STORE.cancel), "jsonb, text, text, text")}
1663
+ `;
1664
+ }
1665
+ /**
1666
+ * `permdock_is_approver(p_approvers jsonb, p_tenant text default null)`, or
1667
+ * with `rls.approvals.managers` its base `permdock_is_approver_base`: true when
1668
+ * the signed-in user matches the serialised approvers of a request
1669
+ * (`approvers.by`), for policies on the app's own approval views. A list needs
1670
+ * every item and `any-of` one of them; `user` compares the user id and
1671
+ * `holder(permission)` reads `permitted_<root>_ids_by_permission` in
1672
+ * `p_tenant`, or `permdock_has_permission` without one. Role, relation and
1673
+ * other grantee approvers need facts the database does not hold for every
1674
+ * membership source, so they match nobody.
1675
+ */
1676
+ function isApproverSql(ctx, managers = false) {
1677
+ const fn = qualified$1(ctx, managers ? APPROVAL_STORE.isApproverBase : APPROVAL_STORE.isApprover);
1678
+ const exposure = managers ? `revoke execute on function ${fn}(jsonb, text) from public, anon, authenticated;` : `revoke execute on function ${fn}(jsonb, text) from public, anon;
1679
+ grant execute on function ${fn}(jsonb, text) to authenticated;`;
1680
+ const root = ctx.scopes[0]?.name;
1681
+ const inTenant = root === void 0 ? "false" : `exists (
1682
+ select 1
1683
+ from ${qualified$1(ctx, checkName(permittedByPermissionHelper(root)))}(p_approvers ->> 'permission') i(id)
1684
+ where i.id::text = p_tenant
1685
+ )`;
1686
+ return `
1687
+ -- approvers: whether the signed-in user matches a request's approvers.by; policies on approval views call it
1688
+ create or replace function ${fn}(p_approvers jsonb, p_tenant text default null)
1689
+ returns boolean
1690
+ language plpgsql
1691
+ stable
1692
+ security definer
1693
+ set search_path = ''
1694
+ as $$
1695
+ declare
1696
+ v_item jsonb;
1697
+ v_user text := ${subjectIdSql(ctx)}::text;
1698
+ begin
1699
+ if coalesce(v_user, '') = '' or p_approvers is null then
1700
+ return false;
1701
+ end if;
1702
+ if jsonb_typeof(p_approvers) = 'array' then
1703
+ if jsonb_array_length(p_approvers) = 0 then
1704
+ return false;
1705
+ end if;
1706
+ for v_item in select value from jsonb_array_elements(p_approvers) loop
1707
+ if not ${fn}(v_item, p_tenant) then
1708
+ return false;
1709
+ end if;
1710
+ end loop;
1711
+ return true;
1712
+ end if;
1713
+ if jsonb_typeof(p_approvers) <> 'object' then
1714
+ return false;
1715
+ end if;
1716
+ case p_approvers ->> 'kind'
1717
+ when 'user' then
1718
+ return coalesce(p_approvers ->> 'id' = v_user, false);
1719
+ when 'permission' then
1720
+ if p_tenant is null then
1721
+ return coalesce(${qualified$1(ctx, PERMISSION_HELPERS.has)}(p_approvers ->> 'permission'), false);
1722
+ end if;
1723
+ return ${inTenant};
1724
+ when 'any-of' then
1725
+ if jsonb_typeof(p_approvers -> 'of') <> 'array' then
1726
+ return false;
1727
+ end if;
1728
+ for v_item in select value from jsonb_array_elements(p_approvers -> 'of') loop
1729
+ if ${fn}(v_item, p_tenant) then
1730
+ return true;
1731
+ end if;
1732
+ end loop;
1733
+ return false;
1734
+ else
1735
+ return false;
1736
+ end case;
1737
+ end;
1738
+ $$;
1739
+ ${exposure}
1740
+ `;
1741
+ }
1742
+ /**
1743
+ * Everything `rls.approvals` writes: the generated or adopted store, the
1744
+ * approver check, with `managers` the manager walk, with `delegations: true`
1745
+ * the covers, and with `tenantPolicies` the tenant approval policies. With
1746
+ * `actorMayWrite`, the covers' write policies call
1747
+ * `permdock_actor_may_write()`.
1748
+ */
1749
+ function approvalsSql(ctx, approvals, jsonSchema, actorMayWrite = false) {
1750
+ if (approvals === void 0 || approvals === false) return;
1751
+ if (approvals === true) return approvalStoreSql(ctx, jsonSchema) + isApproverSql(ctx) + approvalSetsSql(ctx, { delegations: false });
1752
+ const { table, delegations, tenantPolicies, managers } = approvals;
1753
+ if (delegations !== void 0 && typeof delegations !== "boolean") throw new TypeError("PermDock CLI: rls.approvals.delegations must be a boolean");
1754
+ if (approvals.store !== void 0 && typeof approvals.store !== "boolean") throw new TypeError("PermDock CLI: rls.approvals.store must be a boolean");
1755
+ let store;
1756
+ if (approvals.store === false) {
1757
+ const adopted = [
1758
+ "table",
1759
+ "token",
1760
+ "body",
1761
+ "open",
1762
+ "schema",
1763
+ "mirror"
1764
+ ].find((key) => approvals[key] !== void 0);
1765
+ if (adopted !== void 0) throw configError(`PermDock CLI: rls.approvals.${adopted} configures the approval store, which rls.approvals.store: false leaves out`);
1766
+ store = "";
1767
+ } else if (table === void 0) {
1768
+ const adoptOnly = [
1769
+ "token",
1770
+ "body",
1771
+ "open",
1772
+ "schema",
1773
+ "mirror"
1774
+ ].find((key) => approvals[key] !== void 0);
1775
+ if (adoptOnly !== void 0) throw configError(`PermDock CLI: rls.approvals.${adoptOnly} adopts a table; set rls.approvals.table too`);
1776
+ store = approvalStoreSql(ctx, jsonSchema);
1777
+ } else store = adoptedApprovalStoreSql(ctx, {
1778
+ ...approvals,
1779
+ table
1780
+ }, jsonSchema);
1781
+ return store + isApproverSql(ctx, managers !== void 0) + (managers === void 0 ? "" : approvalManagersSql(ctx, managers, qualified$1(ctx, APPROVAL_STORE.isApprover), qualified$1(ctx, APPROVAL_STORE.isApproverBase), delegations === true)) + (delegations === true ? approvalDelegationsSql(ctx, actorMayWrite, managers !== void 0) : "") + (delegations === true || managers !== void 0 ? requestApproversSql(ctx) : "") + (tenantPolicies === void 0 ? "" : approvalPoliciesSql(ctx, tenantPolicies, actorMayWrite)) + approvalSetsSql(ctx, {
1782
+ delegations: delegations === true,
1783
+ ...managers === void 0 ? {} : { managers }
1784
+ });
1785
+ }
1786
+ /**
1787
+ * The objects `rls.approvals.delegations` adds; `tableApprovalDelegationSource`
1788
+ * reads the table.
1789
+ */
1790
+ const DELEGATIONS = {
1791
+ table: "approval_delegations",
1792
+ covers: "permdock_cover_approves"
1793
+ };
1794
+ /**
1795
+ * `rls.approvals.delegations`: one table of out-of-office covers that a user
1796
+ * writes for themselves, and a four-argument `permdock_is_approver` that also
1797
+ * answers for a delegate inside an active cover. With `managers`, the signed-in
1798
+ * user's own check is `permdock_approves`, and a cover passes on a `manager`
1799
+ * leaf when the delegator manages the requester. One hop: a cover is checked
1800
+ * against the delegator's own approver rights, never the delegator's covers. A
1801
+ * delegator who is the requester never counts. A `holder()` approver through a
1802
+ * cover needs `rls.mode: "database"`, where the `_for` helpers exist; in `jwt`
1803
+ * mode only `user()` approvers pass.
1804
+ */
1805
+ function approvalDelegationsSql(ctx, actorMayWrite = false, managers = false) {
1806
+ const table = qualified$1(ctx, DELEGATIONS.table);
1807
+ const fn = qualified$1(ctx, APPROVAL_STORE.isApprover);
1808
+ const covers = qualified$1(ctx, DELEGATIONS.covers);
1809
+ const user = ctx.dialect === "supabase" ? "uuid" : "text";
1810
+ const me = `${subjectIdSql(ctx)}::text`;
1811
+ const defaultMe = subjectIdSql(ctx).replace(/^\(select (.+)\)$/su, "$1");
1812
+ const root = ctx.scopes[0]?.name;
1813
+ const member = (tenant) => root === void 0 ? "false" : `${tenant} in (select m.id::text from ${qualified$1(ctx, memberIdsHelper(root))}() m(id))`;
1814
+ const database = ctx.authorize === "database";
1815
+ const holderGlobal = database ? `coalesce(${qualified$1(ctx, PERMISSION_HELPERS.hasFor)}(p_delegator, p_approvers ->> 'permission'), false)` : "false";
1816
+ const holderTenant = database && root !== void 0 ? `exists (
1817
+ select 1
1818
+ from ${qualified$1(ctx, checkName(`${permittedByPermissionHelper(root)}_for`))}(p_delegator, p_approvers ->> 'permission') i(id)
1819
+ where i.id::text = p_tenant
1820
+ )` : "false";
1821
+ const policy = (name) => quoteIdent(`${DELEGATIONS.table}_${name}`);
1822
+ const writable = actorMayWrite ? ` and (select ${qualified$1(ctx, ACTOR_MAY_WRITE)}())` : "";
1823
+ const managerCase = managers ? `
1824
+ when 'manager' then
1825
+ v_levels := coalesce(p_approvers -> 'levels', '1'::jsonb);
1826
+ if jsonb_typeof(v_levels) <> 'number' or v_levels::text !~ '^[0-9]{1,2}$' then
1827
+ return false;
1828
+ end if;
1829
+ return coalesce(${qualified$1(ctx, MANAGES_FOR)}(p_delegator::text, p_requester, v_levels::text::integer, p_tenant), false);` : "";
1830
+ const meTyped = `${subjectIdSql(ctx)}::${user}`;
1831
+ const mine = `delegator = ${meTyped}${writable}`;
1832
+ const own = `${mine} and (tenant is null or ${member("tenant")})`;
1833
+ return `
1834
+ -- approval delegations: out-of-office covers a user writes for themselves; tableApprovalDelegationSource and permdock_is_approver read them
1835
+ create table if not exists ${table} (
1836
+ id text primary key default gen_random_uuid()::text,
1837
+ delegator ${user} not null default (${defaultMe})::${user},
1838
+ delegate ${user} not null,
1839
+ tenant text,
1840
+ permissions text[],
1841
+ resources text[],
1842
+ "from" timestamptz not null default now(),
1843
+ "until" timestamptz not null,
1844
+ created_at timestamptz not null default now(),
1845
+ constraint ${quoteIdent(`${DELEGATIONS.table}_window`)} check ("from" < "until"),
1846
+ constraint ${quoteIdent(`${DELEGATIONS.table}_distinct`)} check (delegator <> delegate)
1847
+ );
1848
+ create index if not exists ${quoteIdent(`${DELEGATIONS.table}_delegate`)} on ${table} (delegate, "until");
1849
+ create index if not exists ${quoteIdent(`${DELEGATIONS.table}_delegator`)} on ${table} (delegator, "until");
1850
+ alter table ${table} enable row level security;
1851
+ revoke all on table ${table} from anon, public;
1852
+ grant select, insert, update, delete on table ${table} to authenticated;
1853
+ drop policy if exists ${policy("read")} on ${table};
1854
+ create policy ${policy("read")} on ${table}
1855
+ for select to authenticated
1856
+ using (delegator = ${meTyped} or delegate = ${meTyped});
1857
+ drop policy if exists ${policy("insert")} on ${table};
1858
+ create policy ${policy("insert")} on ${table}
1859
+ for insert to authenticated
1860
+ with check (${own});
1861
+ drop policy if exists ${policy("update")} on ${table};
1862
+ create policy ${policy("update")} on ${table}
1863
+ for update to authenticated
1864
+ using (${mine})
1865
+ with check (${own});
1866
+ drop policy if exists ${policy("delete")} on ${table};
1867
+ create policy ${policy("delete")} on ${table}
1868
+ for delete to authenticated
1869
+ using (${mine});
1870
+
1871
+ -- approval delegations: whether a delegator's own rights match approvers.by; only permdock_is_approver calls it
1872
+ create or replace function ${covers}(p_delegator ${user}, p_approvers jsonb, p_tenant text, p_requester text)
1873
+ returns boolean
1874
+ language plpgsql
1875
+ stable
1876
+ security definer
1877
+ set search_path = ''
1878
+ as $$
1879
+ declare
1880
+ v_item jsonb;${managers ? "\n v_levels jsonb;" : ""}
1881
+ begin
1882
+ if p_delegator is null or p_approvers is null then
1883
+ return false;
1884
+ end if;
1885
+ if jsonb_typeof(p_approvers) = 'array' then
1886
+ if jsonb_array_length(p_approvers) = 0 then
1887
+ return false;
1888
+ end if;
1889
+ for v_item in select value from jsonb_array_elements(p_approvers) loop
1890
+ if not ${covers}(p_delegator, v_item, p_tenant, p_requester) then
1891
+ return false;
1892
+ end if;
1893
+ end loop;
1894
+ return true;
1895
+ end if;
1896
+ if jsonb_typeof(p_approvers) <> 'object' then
1897
+ return false;
1898
+ end if;
1899
+ case p_approvers ->> 'kind'
1900
+ when 'user' then
1901
+ return coalesce(p_approvers ->> 'id' = p_delegator::text, false);
1902
+ when 'permission' then
1903
+ if p_tenant is null then
1904
+ return ${holderGlobal};
1905
+ end if;
1906
+ return ${holderTenant};${managerCase}
1907
+ when 'any-of' then
1908
+ if jsonb_typeof(p_approvers -> 'of') <> 'array' then
1909
+ return false;
1910
+ end if;
1911
+ for v_item in select value from jsonb_array_elements(p_approvers -> 'of') loop
1912
+ if ${covers}(p_delegator, v_item, p_tenant, p_requester) then
1913
+ return true;
1914
+ end if;
1915
+ end loop;
1916
+ return false;
1917
+ else
1918
+ return false;
1919
+ end case;
1920
+ end;
1921
+ $$;
1922
+ revoke execute on function ${covers}(${user}, jsonb, text, text) from public, anon, authenticated;
1923
+
1924
+ -- approvers with covers: the signed-in user, or a delegate inside an active cover of a delegator who is not the requester
1925
+ create or replace function ${fn}(p_approvers jsonb, p_tenant text, p_requester text, p_resource text)
1926
+ returns boolean
1927
+ language plpgsql
1928
+ stable
1929
+ security definer
1930
+ set search_path = ''
1931
+ as $$
1932
+ declare
1933
+ v_delegator ${user};
1934
+ v_user text := ${me};
1935
+ begin
1936
+ if ${managers ? `${qualified$1(ctx, APPROVES)}(p_approvers, p_tenant, p_requester)` : `${fn}(p_approvers, p_tenant)`} then
1937
+ return true;
1938
+ end if;
1939
+ if coalesce(v_user, '') = '' or coalesce(p_requester, '') = '' then
1940
+ return false;
1941
+ end if;
1942
+ if p_tenant is not null and not (${member("p_tenant")}) then
1943
+ return false;
1944
+ end if;
1945
+ for v_delegator in
1946
+ select d.delegator
1947
+ from ${table} d
1948
+ where d.delegate = v_user::${user}
1949
+ and d.delegator::text <> v_user
1950
+ and d.delegator::text <> p_requester
1951
+ and d."from" <= now()
1952
+ and now() < d."until"
1953
+ and (d.tenant is null or d.tenant = p_tenant)
1954
+ and d.permissions is null
1955
+ and (d.resources is null or p_resource = any (d.resources))
1956
+ loop
1957
+ if ${covers}(v_delegator, p_approvers, p_tenant, p_requester) then
1958
+ return true;
1959
+ end if;
1960
+ end loop;
1961
+ return false;
1962
+ end;
1963
+ $$;
1964
+ revoke execute on function ${fn}(jsonb, text, text, text) from public, anon;
1965
+ grant execute on function ${fn}(jsonb, text, text, text) to authenticated;
1966
+ `;
1967
+ }
1968
+ function requestApproversSql(ctx) {
1969
+ const fn = qualified$1(ctx, APPROVAL_STORE.isApprover);
1970
+ return `
1971
+ -- approvers with the current step: the four-argument check over p_approvers and the step's users, manager and permission
1972
+ create or replace function ${fn}(p_approvers jsonb, p_tenant text, p_requester text, p_resource text, p_request_approvers jsonb)
1973
+ returns boolean
1974
+ language sql
1975
+ stable
1976
+ security definer
1977
+ set search_path = ''
1978
+ as $$
1979
+ select ${fn}(
1980
+ jsonb_build_object(
1981
+ 'kind', 'any-of',
1982
+ 'of',
1983
+ case when p_approvers is null then '[]'::jsonb else jsonb_build_array(p_approvers) end
1984
+ || case
1985
+ when jsonb_typeof(p_request_approvers -> 'users') = 'array' then coalesce(
1986
+ (select jsonb_agg(jsonb_build_object('kind', 'user', 'id', u.id)) from jsonb_array_elements_text(p_request_approvers -> 'users') u(id)),
1987
+ '[]'::jsonb
1988
+ )
1989
+ else '[]'::jsonb
1990
+ end
1991
+ || case when p_request_approvers -> 'manager' = 'true'::jsonb then '[{"kind": "manager"}]'::jsonb else '[]'::jsonb end
1992
+ || case
1993
+ when jsonb_typeof(p_request_approvers -> 'permission') = 'string'
1994
+ then jsonb_build_array(jsonb_build_object('kind', 'permission', 'permission', p_request_approvers ->> 'permission'))
1995
+ else '[]'::jsonb
1996
+ end
1997
+ ),
1998
+ p_tenant,
1999
+ p_requester,
2000
+ p_resource
2001
+ )
2002
+ $$;
2003
+ revoke execute on function ${fn}(jsonb, text, text, text, jsonb) from public, anon;
2004
+ grant execute on function ${fn}(jsonb, text, text, text, jsonb) to authenticated;
2005
+ `;
2006
+ }
2007
+ /**
2008
+ * The request fields an adopted table may mirror into its own columns, as SQL
2009
+ * over a body.
2010
+ */
2011
+ const MIRRORS = {
2012
+ status: (body) => `${body} ->> 'status'`,
2013
+ permission: (body) => `${body} ->> 'permission'`,
2014
+ tenant: (body) => `${body} #>> '{subject,principal,tenant}'`,
2015
+ principalId: (body) => `${body} #>> '{subject,principal,id}'`,
2016
+ actorId: (body) => `${body} #>> '{subject,actor,id}'`,
2017
+ session: (body) => `${body} #>> '{subject,session}'`,
2018
+ approvals: (body) => `coalesce(jsonb_array_length(${body} -> 'approvals'), 0)`,
2019
+ createdAt: (body) => `${body} ->> 'createdAt'`,
2020
+ expiresAt: (body) => `${body} ->> 'expiresAt'`,
2021
+ resolvedAt: (body) => `${body} ->> 'resolvedAt'`,
2022
+ resolvedBy: (body) => `${body} ->> 'resolvedBy'`,
2023
+ consumedAt: (body) => `${body} ->> 'consumedAt'`
2024
+ };
2025
+ function mirrorsOf(adopt) {
2026
+ const out = [];
2027
+ for (const [field, column] of Object.entries(adopt.mirror ?? {})) {
2028
+ if (!Object.hasOwn(MIRRORS, field)) throw configError(`PermDock CLI: rls.approvals.mirror.${field} is not a request field; use ${Object.keys(MIRRORS).join(", ")}`);
2029
+ if (typeof column !== "string") throw new TypeError(`PermDock CLI: rls.approvals.mirror.${field} must be a column name`);
2030
+ out.push([column, field]);
2031
+ }
2032
+ return out;
2033
+ }
2034
+ /**
2035
+ * One row of `table` from `values` (column, SQL), each converted to the
2036
+ * column's own type.
2037
+ */
2038
+ function populate(table, values) {
2039
+ return `pg_catalog.jsonb_populate_record(null::${table}, pg_catalog.jsonb_build_object(${values.map(([column, sql]) => `${quoteLiteral(column)}, ${sql}`).join(", ")}))`;
2040
+ }
2041
+ /** The mirrored columns' values for the request `body`. */
2042
+ function mirrorRow(table, mirror, body) {
2043
+ return populate(table, mirror.map(([column, field]) => [column, MIRRORS[field](body)]));
2044
+ }
2045
+ /**
2046
+ * `, (<mirrored columns>) = (select …)` for an update that writes `body`; empty
2047
+ * without mirrors.
2048
+ */
2049
+ function mirrorSet(table, mirror, body) {
2050
+ if (mirror.length === 0) return "";
2051
+ const columns = mirror.map(([column]) => quoteIdent(column));
2052
+ const picked = columns.map((column) => `r.${column}`).join(", ");
2053
+ return `,\n ${columns.length === 1 ? columns[0] ?? "" : `(${columns.join(", ")})`} = (select ${picked} from ${mirrorRow(table, mirror, body)} r)`;
2054
+ }
2055
+ /**
2056
+ * The approval store over a table the app already has (`rls.approvals: { table,
2057
+ * token?, body?, mirror? }`): the same `permdock_approval_*` functions, reading
2058
+ * every field from the request body in `body`, keyed by the text column
2059
+ * `token`, and copying the fields `mirror` names into the app's own columns,
2060
+ * converted to their types, on every write. The table's grants and policies
2061
+ * stay the app's.
2062
+ */
2063
+ function adoptedApprovalStoreSql(ctx, adopt, jsonSchema = false) {
2064
+ const table = quoteQualified(adopt.table);
2065
+ const base = adopt.table.split(".").at(-1) ?? adopt.table;
2066
+ const token = quoteIdent(adopt.token ?? "token");
2067
+ const body = quoteIdent(adopt.body ?? "body");
2068
+ const mirror = mirrorsOf(adopt);
2069
+ for (const [column] of mirror) if (column === (adopt.token ?? "token") || column === (adopt.body ?? "body")) throw configError(`PermDock CLI: rls.approvals.mirror names the ${column} column, which already holds the token or the body`);
2070
+ const open = adopt.open ?? "insert";
2071
+ if (open !== "insert" && open !== "attach") throw configError(`PermDock CLI: rls.approvals.open must be 'insert' or 'attach', got '${String(open)}'`);
2072
+ const schema = adopt.schema;
2073
+ if (schema !== void 0 && (typeof schema !== "string" || schema === "")) throw configError("PermDock CLI: rls.approvals.schema must be a schema name");
2074
+ const fn = (name) => schema === void 0 ? qualified$1(ctx, name) : `${quoteIdent(schema)}.${name}`;
2075
+ const index = (name) => quoteIdent(`${base}_permdock_${name}`);
2076
+ const status = `a.${body} ->> 'status'`;
2077
+ const expires = `(a.${body} ->> 'expiresAt')::timestamptz`;
2078
+ const created = `(a.${body} ->> 'createdAt')`;
2079
+ const filter = `(p_filter ->> 'status' is null or ${status} = p_filter ->> 'status')
2080
+ and (p_filter ->> 'tenant' is null or a.${body} #>> '{subject,principal,tenant}' = p_filter ->> 'tenant')
2081
+ and (p_filter ->> 'principalId' is null or a.${body} #>> '{subject,principal,id}' = p_filter ->> 'principalId')
2082
+ and (p_filter ->> 'actorId' is null or a.${body} #>> '{subject,actor,id}' = p_filter ->> 'actorId')
2083
+ and (p_filter ->> 'session' is null or a.${body} #>> '{subject,session}' = p_filter ->> 'session')`;
2084
+ const columns = [
2085
+ token,
2086
+ body,
2087
+ ...mirror.map(([column]) => quoteIdent(column))
2088
+ ];
2089
+ const inserted = populate(table, [
2090
+ [adopt.token ?? "token", "p_request ->> 'token'"],
2091
+ [adopt.body ?? "body", "p_request"],
2092
+ ...mirror.map(([column, field]) => [column, MIRRORS[field]("p_request")])
2093
+ ]);
2094
+ const insertSql = `-- open a request; a repeated ask keeps the open record and replaces only an expired one
2095
+ create or replace function ${fn(APPROVAL_STORE.open)}(p_request jsonb)
2096
+ returns void
2097
+ language sql
2098
+ volatile
2099
+ security definer
2100
+ set search_path = ''
2101
+ as $$
2102
+ insert into ${table} as a (${columns.join(", ")})
2103
+ select ${columns.map((column) => `r.${column}`).join(", ")}
2104
+ from ${inserted} r
2105
+ on conflict (${token}) do update
2106
+ set ${columns.filter((column) => column !== token).map((column) => `${column} = excluded.${column}`).join(", ")}
2107
+ where ${status} = 'expired' or ${expires} <= now()
2108
+ $$;`;
2109
+ const attachSql = `create or replace function ${fn(APPROVAL_STORE.open)}(p_request jsonb)
2110
+ returns void
2111
+ language plpgsql
2112
+ volatile
2113
+ security definer
2114
+ set search_path = ''
2115
+ as $$
2116
+ begin
2117
+ update ${table} a
2118
+ set ${body} = p_request${mirrorSet(table, mirror, "p_request")}
2119
+ where a.${token} = p_request ->> 'token'
2120
+ and (a.${body} is null or ${status} = 'expired' or ${expires} <= now());
2121
+ if not found and not exists (select 1 from ${table} a where a.${token} = p_request ->> 'token') then
2122
+ raise exception using
2123
+ errcode = 'P0002',
2124
+ hint = 'insert the application row with this token before opening the request',
2125
+ message = 'permdock: no row of ${adopt.table.replaceAll("'", "''")} holds approval token ' || (p_request ->> 'token');
2126
+ end if;
2127
+ end;
2128
+ $$;`;
2129
+ return `-- approval store adopted onto ${adopt.table}: ApprovalRequest bodies in ${adopt.body ?? "body"}, keyed by ${adopt.token ?? "token"}; supabaseApprovalStore calls the functions below
2130
+ alter table ${table} add column if not exists ${token} text;
2131
+ comment on column ${table}.${token} is '@bsb identifier: the approval token is a SHA-256 digest of the decision inputs, which the approval is bound to, not a secret';
2132
+ alter table ${table} add column if not exists ${body} jsonb;
2133
+ create unique index if not exists ${index("token")} on ${table} (${token});
2134
+ create index if not exists ${index("page")} on ${table} ((${body} ->> 'createdAt') collate "C", ${token} collate "C");
2135
+ create index if not exists ${index("status")} on ${table} ((${body} ->> 'status'));
2136
+ ${jsonSchema ? bodySchemaSql(table, body, `${base}_permdock_body_schema`) : ""}
2137
+ ${open === "attach" ? attachSql : insertSql}
2138
+ ${serverOnly(fn(APPROVAL_STORE.open), "jsonb")}
2139
+
2140
+ create or replace function ${fn(APPROVAL_STORE.get)}(p_token text)
2141
+ returns jsonb
2142
+ language sql
2143
+ stable
2144
+ security definer
2145
+ set search_path = ''
2146
+ as $$
2147
+ select a.${body} from ${table} a where a.${token} = p_token
2148
+ $$;
2149
+ ${serverOnly(fn(APPROVAL_STORE.get), "text")}
2150
+
2151
+ -- write a verdict over the record it was computed from: still pending, unexpired, with p_seen approvals
2152
+ create or replace function ${fn(APPROVAL_STORE.resolve)}(p_token text, p_next jsonb, p_seen integer)
2153
+ returns jsonb
2154
+ language sql
2155
+ volatile
2156
+ security definer
2157
+ set search_path = ''
2158
+ as $$
2159
+ update ${table} a
2160
+ set ${body} = p_next${mirrorSet(table, mirror, "p_next")}
2161
+ where a.${token} = p_token
2162
+ and ${status} = 'pending'
2163
+ and ${expires} > now()
2164
+ and coalesce(jsonb_array_length(a.${body} -> 'approvals'), 0) = p_seen
2165
+ returning a.${body}
2166
+ $$;
2167
+ ${serverOnly(fn(APPROVAL_STORE.resolve), "text, jsonb, integer")}
2168
+
2169
+ -- consume an approved, unexpired, unconsumed request once
2170
+ create or replace function ${fn(APPROVAL_STORE.consume)}(p_token text, p_now text)
2171
+ returns jsonb
2172
+ language sql
2173
+ volatile
2174
+ security definer
2175
+ set search_path = ''
2176
+ as $$
2177
+ update ${table} a
2178
+ set ${body} = a.${body} || jsonb_build_object('consumedAt', p_now)${mirrorSet(table, mirror, `(a.${body} || jsonb_build_object('consumedAt', p_now))`)}
2179
+ where a.${token} = p_token
2180
+ and ${status} = 'approved'
2181
+ and a.${body} ->> 'consumedAt' is null
2182
+ and ${expires} > p_now::timestamptz
2183
+ returning a.${body}
2184
+ $$;
2185
+ ${serverOnly(fn(APPROVAL_STORE.consume), "text, text")}
2186
+
2187
+ -- one page in (createdAt, token) order after the cursor position
2188
+ create or replace function ${fn(APPROVAL_STORE.list)}(p_filter jsonb, p_after_created text, p_after_token text, p_limit integer)
2189
+ returns setof jsonb
2190
+ language sql
2191
+ stable
2192
+ security definer
2193
+ set search_path = ''
2194
+ as $$
2195
+ select a.${body}
2196
+ from ${table} a
2197
+ where a.${body} is not null
2198
+ and ${filter}
2199
+ and (p_after_created is null
2200
+ or (${created} collate "C", a.${token} collate "C") > (p_after_created collate "C", p_after_token collate "C"))
2201
+ order by ${created} collate "C", a.${token} collate "C"
2202
+ limit p_limit
2203
+ $$;
2204
+ ${serverOnly(fn(APPROVAL_STORE.list), "jsonb, text, text, integer")}
2205
+
2206
+ create or replace function ${fn(APPROVAL_STORE.expire)}(p_now text)
2207
+ returns integer
2208
+ language sql
2209
+ volatile
2210
+ security definer
2211
+ set search_path = ''
2212
+ as $$
2213
+ with expired as (
2214
+ update ${table} a
2215
+ set ${body} = a.${body} || '{"status":"expired"}'::jsonb${mirrorSet(table, mirror, `(a.${body} || '{"status":"expired"}'::jsonb)`)}
2216
+ where ${status} = 'pending' and ${expires} <= p_now::timestamptz
2217
+ returning 1
2218
+ )
2219
+ select count(*)::integer from expired
2220
+ $$;
2221
+ ${serverOnly(fn(APPROVAL_STORE.expire), "text")}
2222
+
2223
+ -- reject every pending request the filter matches, as system:<by>
2224
+ create or replace function ${fn(APPROVAL_STORE.cancel)}(p_filter jsonb, p_by text, p_note text, p_now text)
2225
+ returns integer
2226
+ language sql
2227
+ volatile
2228
+ security definer
2229
+ set search_path = ''
2230
+ as $$
2231
+ with cancelled as (
2232
+ update ${table} a
2233
+ set ${body} = (a.${body} - 'note') || jsonb_strip_nulls(jsonb_build_object(
2234
+ 'status', 'rejected', 'resolvedAt', p_now, 'resolvedBy', 'system:' || p_by, 'note', p_note
2235
+ ))${mirrorSet(table, mirror, `((a.${body} - 'note') || jsonb_strip_nulls(jsonb_build_object('status', 'rejected', 'resolvedAt', p_now, 'resolvedBy', 'system:' || p_by, 'note', p_note)))`)}
2236
+ where ${status} = 'pending'
2237
+ and ${filter.replaceAll("\n ", "\n ")}
2238
+ returning 1
2239
+ )
2240
+ select count(*)::integer from cancelled
2241
+ $$;
2242
+ ${serverOnly(fn(APPROVAL_STORE.cancel), "jsonb, text, text, text")}
2243
+ `;
2244
+ }
2245
+ // src/cli/supabase-hook/refresh.ts
2246
+ /**
2247
+ * Why the refresh fast path cannot run for these sources, or `undefined` when
2248
+ * every change to what the memberships claim reads bumps `authz_ver`.
2249
+ *
2250
+ * A membership table, a roles table, the teams table and the tables a role or a
2251
+ * user id is read through all carry a version trigger. Two things change a
2252
+ * claim without a write to those tables: a row expiring (`expiresAt`) and a
2253
+ * suspended scope read from another table (`reads`). The fast path never runs
2254
+ * for a source with either, nor with a suspended-tenant table, which
2255
+ * `memberships_for` reads for every source. The suspended-user table is the one
2256
+ * read the hook checks itself, before it looks at the token.
2257
+ */
2258
+ function refreshBlocker(sources, version, usersTable, tenantsTable) {
2259
+ if (!version) return "supabase.hook.version is false, so the token carries no authz_ver to compare";
2260
+ if (tenantsTable !== void 0) return `the tenants are suspended through ${tenantsTable} (rls.suspension.scopes): a change there does not bump authz_ver`;
2261
+ for (const source of sources) {
2262
+ if (source.sql.manifest.expiresAt !== void 0) return `the ${source.sql.table} source has expiresAt: a row expires without a write, so authz_ver does not move`;
2263
+ const reads = source.sql.reads.filter((table) => table !== usersTable);
2264
+ if (reads.length > 0) return `the ${source.sql.table} source reads ${reads.join(", ")} (scope suspension): a change there does not bump authz_ver`;
2265
+ }
2266
+ }
2267
+ function refreshMode(hook) {
2268
+ const mode = hook.refresh ?? "reuse";
2269
+ if (mode !== "reuse" && mode !== "full") throw configError(`PermDock CLI: supabase.hook.refresh must be 'reuse' or 'full' (got ${String(mode)})`);
2270
+ return mode;
2271
+ }
2272
+ /**
2273
+ * `supabase.hook.membershipsClaim`. `false` needs `database` mode, where the
2274
+ * helpers read memberships from the tables, and rules out an explicit `refresh:
2275
+ * 'reuse'`: a refresh has no entries to reuse.
2276
+ */
2277
+ function membershipsClaim(hook, authorize) {
2278
+ const value = hook.membershipsClaim ?? true;
2279
+ if (typeof value !== "boolean") throw configError(`PermDock CLI: supabase.hook.membershipsClaim must be a boolean (got ${String(value)})`);
2280
+ if (!value && authorize !== "database") throw configError("PermDock CLI: supabase.hook.membershipsClaim: false needs rls.authorize: 'database'; in 'jwt' mode the RLS helpers read memberships from the claim");
2281
+ if (!value && hook.refresh === "reuse") throw configError("PermDock CLI: supabase.hook.refresh 'reuse' cannot run: supabase.hook.membershipsClaim is false, so a refresh has no memberships to reuse");
2282
+ return value;
2283
+ }
2284
+ function oauthMode(hook) {
2285
+ const mode = hook.oauth ?? "full";
2286
+ if (mode !== "full" && mode !== "slim") throw configError(`PermDock CLI: supabase.hook.oauth must be 'full' or 'slim' (got ${String(mode)})`);
2287
+ return mode;
2288
+ }
2289
+ /**
2290
+ * Whether the hook compiles the fast path. An explicit `refresh: 'reuse'` that
2291
+ * cannot hold fails the command; the default falls back to the full path.
2292
+ */
2293
+ function refreshReuse(hook, sources, version, usersTable, tenantsTable) {
2294
+ if (refreshMode(hook) === "full") return false;
2295
+ const blocker = refreshBlocker(sources, version, usersTable, tenantsTable);
2296
+ if (blocker !== void 0 && hook.refresh === "reuse") throw configError(`PermDock CLI: supabase.hook.refresh 'reuse' cannot run: ${blocker}`);
2297
+ return blocker === void 0;
2298
+ }
2299
+ // src/cli/supabase-hook/sql.ts
2300
+ const MANAGED_TRIGGER = "permdock_protect_managed";
2301
+ function schemaSql(parts) {
2302
+ if (parts.schema === "public") return "";
2303
+ const schema = quoteIdent(parts.schema);
2304
+ return `create schema if not exists ${schema};\nrevoke all on schema ${schema} from public;`;
2305
+ }
2306
+ function hookSql(parts) {
2307
+ const schema = quoteIdent(parts.schema);
2308
+ const fn = `${schema}.custom_access_token_hook`;
2309
+ const plan = parts.attrs;
2310
+ const tableMembershipSource = plan === void 0 || plan.columns.length === 0 || plan.table === void 0 ? "" : `
2311
+ select jsonb_strip_nulls(jsonb_build_object(${plan.columns.map((column) => `${quoteLiteral(column)}, to_jsonb(p.${quoteIdent(column)})`).join(", ")}))
2312
+ into attrs
2313
+ from ${quoteQualified(plan.table)} p
2314
+ where p.${quoteIdent(plan.id)} = v_attrs_user;`;
2315
+ const fromMeta = plan === void 0 || plan.meta.length === 0 ? "" : `
2316
+ attrs := coalesce(attrs, '{}'::jsonb) || jsonb_strip_nulls(jsonb_build_object(${plan.meta.map((key) => `${quoteLiteral(key)}, claims -> 'app_metadata' -> ${quoteLiteral(key)}`).join(", ")}));`;
2317
+ const attrs = plan === void 0 ? "" : `${tableMembershipSource}${fromMeta}
2318
+ if attrs is not null and attrs <> '{}'::jsonb then
2319
+ used := octet_length(attrs::text);
2320
+ if used > budget then
2321
+ truncated := true;
2322
+ used := 0;
2323
+ else
2324
+ claims := jsonb_set(claims, '{attrs}', attrs);
2325
+ end if;
2326
+ end if;`;
2327
+ const versionTable = `${schema}.${quoteIdent(AUTHZ_VERSION_TABLE)}`;
2328
+ const version = parts.version ? `
2329
+ select v.version into ver from ${versionTable} v where v.user_id = uid;
2330
+ claims := jsonb_set(claims, '{authz_ver}', to_jsonb(coalesce(ver, 0)));` : "";
2331
+ const versionClaim = parts.version ? `
2332
+ claims := jsonb_set(claims, '{authz_ver}', to_jsonb(ver));` : "";
2333
+ const customVersion = parts.customRoles === void 0 ? "" : `
2334
+ claims := jsonb_set(claims, ${quoteLiteral(`{${CUSTOM_ROLES_VERSION_CLAIM}}`)}, to_jsonb(${schema}.custom_roles_version_for(active::${parts.customRoles.tenantType})));`;
2335
+ const dropCustom = parts.customRoles === void 0 ? "" : ` - ${quoteLiteral(CUSTOM_ROLES_VERSION_CLAIM)}`;
2336
+ const dropExtra = parts.extra.map((entry) => ` - ${quoteLiteral(entry.claim)}`).join("");
2337
+ const extra = parts.extra.map((entry) => `
2338
+ extra := ${quoteTable(entry.fn)}(uid);
2339
+ if extra is not null then
2340
+ claims := jsonb_set(claims, ${quoteLiteral(`{${entry.claim}}`)}, extra);
2341
+ end if;`).join("");
2342
+ const dropTeams = parts.hook.teams === void 0 ? "" : " - 'team_ids' - 'team_ids_truncated'";
2343
+ const suspended = parts.users === void 0 ? "" : `
2344
+ if not ${activeRowSql(parts.users, "uid")} then
2345
+ claims := claims - 'memberships_truncated' - 'attrs'${dropTeams} - ${quoteLiteral(parts.tenantClaim)}${dropCustom}${dropExtra};
2346
+ claims := claims || jsonb_build_object('user_role', '[]'::jsonb, 'roles', '[]'::jsonb, 'memberships', '[]'::jsonb);${version}
2347
+ return jsonb_set(event, '{claims}', claims);
2348
+ end if;`;
2349
+ const teamsConfig = parts.hook.teams;
2350
+ const teams = teamsConfig === void 0 ? "" : `
2351
+ -- the teams share the budget with the roles, the attrs, the version and the memberships already kept
2352
+ if used + octet_length(kept::text) + octet_length(team_ids::text) > budget then
2353
+ team_truncated := true;
2354
+ end if;
2355
+ if team_truncated then
2356
+ claims := jsonb_set(claims, '{team_ids_truncated}', 'true'::jsonb);
2357
+ else
2358
+ claims := claims - 'team_ids_truncated';
2359
+ if team_ids <> '[]'::jsonb then
2360
+ claims := jsonb_set(claims, '{team_ids}', team_ids);
2361
+ end if;
2362
+ end if;`;
2363
+ const schemaName = quoteIdent(parts.schema);
2364
+ const rolesCte = parts.roles === void 0 ? "select '[]'::jsonb as held" : `select ${schemaName}.global_roles_for(uid) as held`;
2365
+ const versionCte = parts.version ? `,
2366
+ pdk_version as (
2367
+ select coalesce((select v.version from ${versionTable} v where v.user_id = uid), 0) as ver
2368
+ )` : "";
2369
+ const teamsCte = teamsConfig === void 0 ? "" : `,
2370
+ pdk_teams as (
2371
+ select coalesce(jsonb_agg(to_jsonb(u.id::text) order by u.n), '[]'::jsonb) as team_ids
2372
+ from unnest(array(
2373
+ select team_id from ${quoteIdent(parts.helpers.schema)}.${quoteIdent(hookTeamReader(parts))}(uid, active) as team(team_id)
2374
+ )) with ordinality as u(id, n)
2375
+ )`;
2376
+ const fixed = `used + octet_length(pdk_roles.held::text) + octet_length(case jsonb_array_length(pdk_roles.held) when 0 then '' when 1 then (pdk_roles.held -> 0)::text else pdk_roles.held::text end) + coalesce(octet_length(to_jsonb(active)::text), 0)${parts.customRoles === void 0 ? "" : " + 20"}${parts.version ? " + octet_length(pdk_version.ver::text)" : ""}`;
2377
+ const fixedFrom = `pdk_roles${parts.version ? ", pdk_version" : ""}`;
2378
+ const ranked = parts.membershipsClaim ? `,
2379
+ pdk_ranked as (
2380
+ select x.entry, x.root_id is not distinct from active as current,
2381
+ row_number() over w as n,
2382
+ sum(octet_length(x.entry::text)) over w as bytes
2383
+ from pdk_entries x
2384
+ window w as (
2385
+ order by (x.root_id is not distinct from active) desc, x.ord, x.entry ->> 'scope', x.entry ->> 'id', x.entry::text
2386
+ rows between unbounded preceding and current row
2387
+ )
2388
+ ),
2389
+ pdk_kept as (
2390
+ select r.* from pdk_ranked r, pdk_fixed f where f.bytes + 2 + r.bytes + 2 * (r.n - 1) <= budget
2391
+ )` : "";
2392
+ const keptSelect = parts.membershipsClaim ? `coalesce((select jsonb_agg(k.entry order by k.n) from pdk_kept k), '[]'::jsonb),
2393
+ truncated or (select count(*) from pdk_ranked) > (select count(*) from pdk_kept),
2394
+ active is not null and coalesce((select bool_or(k.current) from pdk_ranked k), false),` : `'[]'::jsonb,
2395
+ truncated or exists (select 1 from pdk_entries),
2396
+ active is not null and coalesce((select bool_or(x.root_id is not distinct from active) from pdk_entries x), false),`;
2397
+ const readQuery = ` -- one statement reads the roles, the memberships${teamsConfig === void 0 ? "" : ", the teams"}${parts.version ? " and the authorization version" : ""}; the budget counts every slice${parts.membershipsClaim ? "" : "\n -- supabase.hook.membershipsClaim is false: the claim keeps no entry, and memberships_truncated sends a reader to the database"}
2398
+ with pdk_roles as (
2399
+ ${rolesCte}
2400
+ )${versionCte}${teamsCte},
2401
+ pdk_entries as (
2402
+ select e.ord, e.entry, ${entryTenantSql(parts, "e")} as root_id
2403
+ from ${schemaName}.${MEMBERSHIPS_FOR}(uid) e
2404
+ ),
2405
+ pdk_fixed as (
2406
+ select ${fixed} as bytes from ${fixedFrom}
2407
+ )${ranked}
2408
+ select
2409
+ (select pdk_roles.held from pdk_roles),
2410
+ ${keptSelect}
2411
+ (select bytes from pdk_fixed)${teamsConfig === void 0 ? "" : ",\n (select pdk_teams.team_ids from pdk_teams)"}${parts.version ? ",\n (select pdk_version.ver from pdk_version)" : ""}
2412
+ into held, kept, truncated, in_active, used${teamsConfig === void 0 ? "" : ", team_ids"}${parts.version ? ", ver" : ""};`;
2413
+ const applyHeld = ` claims := jsonb_set(claims, '{roles}', held);
2414
+ if jsonb_array_length(held) = 1 then
2415
+ claims := jsonb_set(claims, '{user_role}', held -> 0);
2416
+ elsif jsonb_array_length(held) > 1 then
2417
+ claims := jsonb_set(claims, '{user_role}', held);
2418
+ end if;
2419
+ claims := jsonb_set(claims, '{memberships}', kept);`;
2420
+ const incoming = "event -> 'claims'";
2421
+ const fastBlock = parts.refreshReuse ? `
2422
+ -- a refresh whose token carries the current authz_ver keeps the roles, memberships and teams it holds; any doubt reads them again
2423
+ if event ->> 'authentication_method' = 'token_refresh'
2424
+ and not truncated
2425
+ and jsonb_typeof(${incoming} -> 'authz_ver') = 'number'
2426
+ and jsonb_typeof(${incoming} -> 'roles') = 'array'
2427
+ and jsonb_typeof(${incoming} -> 'memberships') = 'array'
2428
+ and not (${incoming} ? 'memberships_truncated')${teamsConfig === void 0 ? "" : `\n and not (${incoming} ? 'team_ids_truncated')`} then
2429
+ select coalesce((select v.version from ${versionTable} v where v.user_id = uid), 0) into ver;
2430
+ if (${incoming} ->> 'authz_ver')::numeric = ver then
2431
+ held := ${incoming} -> 'roles';
2432
+ kept := ${incoming} -> 'memberships';${teamsConfig === void 0 ? "" : `\n team_ids := case when jsonb_typeof(${incoming} -> 'team_ids') = 'array' then ${incoming} -> 'team_ids' else '[]'::jsonb end;`}
2433
+ if used + 2 * octet_length(held::text) + octet_length(kept::text)${teamsConfig === void 0 ? "" : " + octet_length(team_ids::text)"} + coalesce(octet_length(to_jsonb(active)::text), 0) + octet_length(ver::text) + ${parts.customRoles === void 0 ? "0" : "20"} + 2 <= budget then
2434
+ fast := true;
2435
+ end if;
2436
+ end if;
2437
+ end if;` : "";
2438
+ const oneQuery = parts.refreshReuse ? `${fastBlock}
2439
+ if fast then
2440
+ in_active := active is not null and exists (
2441
+ select 1 from jsonb_array_elements(kept) as e(entry) where ${entryTenantSql(parts, "e")} = active
2442
+ );
2443
+ else
2444
+ ${readQuery.replaceAll(/^/gmu, " ")}
2445
+ end if;
2446
+ ${applyHeld}` : `${readQuery}\n${applyHeld}`;
2447
+ const slim = parts.oauth === "slim" ? `
2448
+ -- a token for an OAuth client (client_id) gets no memberships, roles or attrs: the client acts for a scope the user granted, not as the user
2449
+ if coalesce(claims ->> 'client_id', '') <> '' then
2450
+ claims := claims - 'memberships_truncated' - 'attrs' - 'user_role' - 'authz_ver'${dropTeams} - ${quoteLiteral(parts.tenantClaim)}${dropCustom}${dropExtra};
2451
+ claims := claims || jsonb_build_object('roles', '[]'::jsonb, 'memberships', '[]'::jsonb);
2452
+ return jsonb_set(event, '{claims}', claims);
2453
+ end if;` : "";
2454
+ const dropIssued = parts.refreshReuse ? ` - 'user_role' - ${quoteLiteral(parts.tenantClaim)}` : "";
2455
+ return `create or replace function ${fn}(event jsonb)
2456
+ returns jsonb
2457
+ language plpgsql
2458
+ stable${parts.hook.security === "definer" ? "\nsecurity definer" : ""}
2459
+ set search_path = ''
2460
+ as $$
2461
+ declare
2462
+ claims jsonb := event -> 'claims';
2463
+ uid uuid := (event ->> 'user_id')::uuid;
2464
+ active text;
2465
+ held jsonb;
2466
+ kept jsonb := '[]'::jsonb;
2467
+ truncated boolean := false;
2468
+ in_active boolean := false;
2469
+ budget integer := ${String(parts.budget)};
2470
+ used integer := 0;${teamsConfig === void 0 ? "" : "\n team_ids jsonb := '[]'::jsonb;\n team_truncated boolean := false;"}${typedUsers(parts)}${plan === void 0 ? "" : "\n attrs jsonb;"}${parts.extra.length === 0 ? "" : "\n extra jsonb;"}${parts.version ? "\n ver bigint;" : ""}${parts.refreshReuse ? "\n fast boolean := false;" : ""}${parts.before.length === 0 ? "" : "\n checked jsonb;"}
2471
+ begin${beforeSql(parts.before)}${suspended}${slim}
2472
+ claims := claims - 'attrs'${dropTeams}${dropCustom}${dropExtra}${dropIssued};
2473
+ active := ${parts.active.sql};${attrs}
2474
+ ${oneQuery}${teams}
2475
+ if truncated then
2476
+ claims := jsonb_set(claims, '{memberships_truncated}', 'true'::jsonb);
2477
+ else
2478
+ claims := claims - 'memberships_truncated';
2479
+ end if;
2480
+ if in_active then
2481
+ claims := jsonb_set(claims, ${quoteLiteral(`{${parts.tenantClaim}}`)}, to_jsonb(active));${customVersion}
2482
+ end if;${extra}${versionClaim}${validateSql(parts)}
2483
+ return jsonb_set(event, '{claims}', claims);
2484
+ end;
2485
+ $$;`;
2486
+ }
2487
+ /** Everything the hook grants `supabase_auth_admin`, and the execute revoke. */
2488
+ function grantsSql(parts) {
2489
+ const schema = quoteIdent(parts.schema);
2490
+ const fn = `${schema}.custom_access_token_hook`;
2491
+ if (parts.hook.security === "definer") return `-- supabase_auth_admin: execute only; the hook reads with its owner's rights
2492
+ revoke execute on function ${fn}(jsonb) from authenticated, anon, public;
2493
+ grant usage on schema ${schema} to supabase_auth_admin;
2494
+ grant execute on function ${fn}(jsonb) to supabase_auth_admin;${extraRevokesSql(parts.extra, parts.before)}`;
2495
+ return [
2496
+ `-- supabase_auth_admin: the grants and read policies the hook needs
2497
+ grant usage on schema ${schema} to supabase_auth_admin;
2498
+ grant execute on function ${fn}(jsonb) to supabase_auth_admin;
2499
+ revoke execute on function ${fn}(jsonb) from authenticated, anon, public;${extraGrantsSql(parts.extra)}${beforeGrantsSql(parts.before, parts.extra)}${customRolesGrantsSql(parts)}${entriesGrantsSql(parts)}${memberForGrantsSql(parts)}${validateGrantsSql(parts)}`,
2500
+ readsSql(parts),
2501
+ parts.version ? authAdminRead(`${parts.schema}.${AUTHZ_VERSION_TABLE}`, "version") : ""
2502
+ ].filter((chunk) => chunk !== "").join("\n");
2503
+ }
2504
+ /**
2505
+ * The hook reads the active tenant's custom-role version through the definer
2506
+ * function.
2507
+ */
2508
+ function customRolesGrantsSql(parts) {
2509
+ return parts.customRoles === void 0 ? "" : `\ngrant execute on function ${quoteIdent(parts.schema)}.custom_roles_version_for(${parts.customRoles.tenantType}) to supabase_auth_admin;`;
2510
+ }
2511
+ /**
2512
+ * A definer hook calls `hook.claims` and `hook.before` functions as its owner,
2513
+ * so they need no grant; they are still revoked from the client roles.
2514
+ */
2515
+ function extraRevokesSql(extra, before) {
2516
+ return [...extra.map((entry) => `\nrevoke all on function ${quoteTable(entry.fn)}(uuid) from public, anon, authenticated;`), ...before.map((fn) => `\nrevoke all on function ${quoteTable(fn)}(jsonb) from public, anon, authenticated;`)].join("");
2517
+ }
2518
+ function extraGrantsSql(extra) {
2519
+ return [...[...new Set(extra.map((entry) => entry.fn.split(".")[0]))].map((name) => `\ngrant usage on schema ${quoteIdent(name ?? "")} to supabase_auth_admin;`), ...extra.map((entry) => `\nrevoke all on function ${quoteTable(entry.fn)}(uuid) from public, anon, authenticated;\ngrant execute on function ${quoteTable(entry.fn)}(uuid) to supabase_auth_admin;`)].join("");
2520
+ }
2521
+ function beforeGrantsSql(before, extra) {
2522
+ const granted = new Set(extra.map((entry) => entry.fn.split(".")[0]));
2523
+ return [...[...new Set(before.map((fn) => beforeFirst(fn, ".")))].filter((name) => !granted.has(name)).map((name) => `\ngrant usage on schema ${quoteIdent(name)} to supabase_auth_admin;`), ...before.map((fn) => `\nrevoke all on function ${quoteTable(fn)}(jsonb) from public, anon, authenticated;\ngrant execute on function ${quoteTable(fn)}(jsonb) to supabase_auth_admin;`)].join("");
2524
+ }
2525
+ /**
2526
+ * Execute on each `member_<scope>_ids_for` for the `hook.claims` functions,
2527
+ * which run as `supabase_auth_admin` and may call them, and on a team scope's
2528
+ * one when `hook.teams` reads it for `team_ids`. Only then: the grant needs the
2529
+ * helpers migration applied first, and a hook that calls none does not. The
2530
+ * helpers file grants the same on a database that has the role.
2531
+ */
2532
+ function memberForGrantsSql(parts) {
2533
+ const { schema, memberFor } = parts.helpers;
2534
+ const granted = parts.extra.length > 0 ? memberFor : memberFor.filter((scope) => parts.hook.teams !== void 0 && isTeamScope(scope));
2535
+ if (granted.length === 0) return "";
2536
+ return [...schema === parts.schema ? [] : [`\ngrant usage on schema ${quoteIdent(schema)} to supabase_auth_admin;`], ...granted.map((scope) => `\ngrant execute on function ${quoteIdent(schema)}.${memberForHelper(scope)}(${isTeamScope(scope) ? "uuid, text" : "uuid"}) to supabase_auth_admin;`)].join("");
2537
+ }
2538
+ /**
2539
+ * The tables the invoker hook reads in its own body: the `attrs` table and the
2540
+ * suspended-user table. Memberships and global roles come through the `security
2541
+ * definer` readers, so their tables get no grant.
2542
+ */
2543
+ function readsSql(parts) {
2544
+ const reads = /* @__PURE__ */ new Map();
2545
+ if (parts.attrs?.table !== void 0 && parts.attrs.columns.length > 0) reads.set(parts.attrs.table, reads.get(parts.attrs.table) ?? "attrs");
2546
+ if (parts.users !== void 0) reads.set(parts.users.table, reads.get(parts.users.table) ?? "status_users");
2547
+ return [...[...new Set([...reads.keys()].map((name) => name.includes(".") ? name.split(".")[0] : "public").filter((schema) => schema !== void 0 && schema !== parts.schema && schema !== "auth"))].map((schema) => `grant usage on schema ${quoteIdent(schema)} to supabase_auth_admin;`), ...[...reads].map(([name, label]) => authAdminRead(name, label))].join("\n");
2548
+ }
2549
+ function managedSql(parts) {
2550
+ const managed = parts.sources.filter((source) => source.sql.managed !== void 0);
2551
+ if (managed.length === 0) return "";
2552
+ const guard = `${quoteIdent(parts.schema)}.permdock_protect_managed`;
2553
+ return `-- memberships the identity provider owns: clients (anon, authenticated) cannot write them
2554
+ create or replace function ${guard}()
2555
+ returns trigger
2556
+ language plpgsql
2557
+ set search_path = ''
2558
+ as $$
2559
+ declare
2560
+ column_name text := tg_argv[0];
2561
+ begin
2562
+ if current_user in ('anon', 'authenticated') and (
2563
+ column_name = ''
2564
+ or (tg_op <> 'INSERT' and to_jsonb(old) ->> column_name = 'idp')
2565
+ or (tg_op <> 'DELETE' and to_jsonb(new) ->> column_name = 'idp')
2566
+ ) then
2567
+ raise exception 'PermDock: % rows managed by the identity provider cannot be changed here', tg_table_name
2568
+ using errcode = '42501';
2569
+ end if;
2570
+ return coalesce(new, old);
2571
+ end;
2572
+ $$;
2573
+ ${managed.map((source) => `drop trigger if exists ${quoteIdent(MANAGED_TRIGGER)} on ${quoteQualified(source.sql.table)};
2574
+ create trigger ${quoteIdent(MANAGED_TRIGGER)}
2575
+ before insert or update or delete on ${quoteQualified(source.sql.table)}
2576
+ for each row execute function ${guard}(${quoteLiteral(source.sql.managed ?? "")});`).join("\n")}`;
2577
+ }
2578
+ /** The `config.toml` block that enables the hook and bounds token staleness. */
2579
+ function configToml(schema, jwtExpiry) {
2580
+ return `[auth]
2581
+ jwt_expiry = ${String(jwtExpiry)}
2582
+
2583
+ [auth.hook.custom_access_token]
2584
+ enabled = true
2585
+ uri = "${hookUri(schema)}"`;
2586
+ }
2587
+ const BUDGET_MEASURE = "octet_length(roles::text) + octet_length(user_role::text) + octet_length(memberships::text) + octet_length(team_ids::text) + octet_length(attrs::text) + octet_length(active_tenant::text) + 20 + octet_length(authz_ver::text)";
2588
+ function hookParts(scopes, config, overrides) {
2589
+ const hook = config.supabase?.hook;
2590
+ if (hook === void 0) throw configError("PermDock CLI: supabase hook generate needs supabase.hook in permdock.config.ts");
2591
+ const root = rootScope(scopes) ?? "tenant";
2592
+ const suspension = checkSuspension(hook.suspension ?? config.rls?.suspension, scopes);
2593
+ const schema = overrides.schema ?? hook.schema ?? config.rls?.schema ?? "permdock";
2594
+ quoteIdent(schema);
2595
+ const tenantClaim = config.rls?.tenantClaim ?? "tenant_id";
2596
+ const extraPlan = extraClaimsPlan(hook.claims, tenantClaim);
2597
+ const sources = hookMemberships(hook.memberships, config.rls?.memberships, scopes, suspension);
2598
+ checkSources({
2599
+ sources,
2600
+ scopes
2601
+ });
2602
+ const tenants = suspension?.scopes?.[root];
2603
+ const claimed = membershipsClaim(hook, resolveAuthorize(config));
2604
+ const parts = {
2605
+ schema,
2606
+ scopes,
2607
+ root,
2608
+ sources,
2609
+ budget: positiveInteger(overrides.budget ?? hook.budget ?? 1024, "budget"),
2610
+ membershipsClaim: claimed,
2611
+ version: hook.version !== false,
2612
+ refreshReuse: refreshReuse(hook, sources, hook.version !== false, suspension?.users?.table, tenants?.table) && claimed,
2613
+ oauth: oauthMode(hook),
2614
+ broadcast: hook.version === false || hook.broadcast === false ? void 0 : {
2615
+ topic: hook.broadcast?.topic ?? "permdock:authz",
2616
+ receivePolicy: hook.broadcast?.receivePolicy ?? true
2617
+ },
2618
+ jwtExpiry: positiveInteger(hook.jwtExpiry ?? 900, "jwtExpiry"),
2619
+ tenantClaim,
2620
+ customRoles: customRolesOn(config.rls) && resolveAuthorize(config) === "database" ? { tenantType: sqlType(firstScopeType(config.rls?.scopeTypes, scopes)) } : void 0,
2621
+ users: suspension?.users,
2622
+ tenants,
2623
+ tenantType: sqlType(firstScopeType(config.rls?.scopeTypes, scopes)),
2624
+ hook,
2625
+ roles: hook.roles === false ? void 0 : globalRoleSource(hook.roles ?? config.rls?.roles ?? { table: `${schema}.user_roles` }, "public", "r", config.rls?.customRoleWrites?.roles),
2626
+ active: activeFromSql(overrides.activeFrom ?? hook.activeFrom, root),
2627
+ activeFrom: activeSource(overrides.activeFrom ?? hook.activeFrom, root),
2628
+ attrs: hook.attrs === void 0 ? void 0 : attrsPlan(hook.attrs),
2629
+ extra: extraPlan.claims,
2630
+ before: beforePlan(hook.before),
2631
+ helpers: {
2632
+ schema: config.rls?.schema ?? "permdock",
2633
+ ...memberForPlan({
2634
+ scopes,
2635
+ ...config.rls?.memberships === void 0 ? {} : { memberships: config.rls.memberships },
2636
+ memberSources: membershipSourcesOf(config)
2637
+ })
2638
+ }
2639
+ };
2640
+ if (parts.attrs !== void 0 && parts.attrs.errors.length > 0) throw configError(`PermDock CLI: ${parts.attrs.errors.join("; ")}`);
2641
+ if (extraPlan.errors.length > 0) throw configError(`PermDock CLI: ${extraPlan.errors.join("; ")}`);
2642
+ quoteIdent(parts.tenantClaim);
2643
+ return parts;
2644
+ }
2645
+ // src/cli/supabase-hook/version.ts
2646
+ const VERSION_TRIGGER = "permdock_authz_version";
2647
+ /**
2648
+ * Insert, update and delete statement triggers with transition tables, running
2649
+ * `call`.
2650
+ */
2651
+ function statementTriggers(target, call) {
2652
+ return `drop trigger if exists ${quoteIdent(STATEMENT_TRIGGERS.insert)} on ${target};
2653
+ create trigger ${quoteIdent(STATEMENT_TRIGGERS.insert)}
2654
+ after insert on ${target}
2655
+ referencing new table as permdock_new
2656
+ for each statement execute function ${call};
2657
+ drop trigger if exists ${quoteIdent(STATEMENT_TRIGGERS.update)} on ${target};
2658
+ create trigger ${quoteIdent(STATEMENT_TRIGGERS.update)}
2659
+ after update on ${target}
2660
+ referencing old table as permdock_old new table as permdock_new
2661
+ for each statement execute function ${call};
2662
+ drop trigger if exists ${quoteIdent(STATEMENT_TRIGGERS.delete)} on ${target};
2663
+ create trigger ${quoteIdent(STATEMENT_TRIGGERS.delete)}
2664
+ after delete on ${target}
2665
+ referencing old table as permdock_old
2666
+ for each statement execute function ${call};`;
2667
+ }
2668
+ /** The statement triggers on a direct membership table, one per event. */
2669
+ const STATEMENT_TRIGGERS = {
2670
+ insert: "permdock_authz_version_insert",
2671
+ update: "permdock_authz_version_update",
2672
+ delete: "permdock_authz_version_delete"
2673
+ };
2674
+ const AUTHZ_VERSION_BUMP = "permdock_bump_authz_version_for";
2675
+ function versionSql(parts) {
2676
+ if (!parts.version) return "";
2677
+ const schema = quoteIdent(parts.schema);
2678
+ const versionTable = `${schema}.${quoteIdent(AUTHZ_VERSION_TABLE)}`;
2679
+ const bump = `${schema}.permdock_bump_authz_version`;
2680
+ const bumpFor = `${schema}.${AUTHZ_VERSION_BUMP}`;
2681
+ const tables = [...new Map(parts.sources.filter((source) => source.sql.userThrough === void 0).map((source) => [source.sql.table, source.sql.user]))];
2682
+ if (parts.roles !== void 0) tables.push([parts.roles.table, parts.roles.user]);
2683
+ if (parts.hook.teams !== void 0) tables.push([parts.hook.teams.table, parts.hook.teams.user]);
2684
+ return `-- the authorization version: bumped on every membership change, written to authz_ver
2685
+ create table if not exists ${versionTable} (
2686
+ user_id uuid primary key references auth.users on delete cascade,
2687
+ version bigint not null default 0
2688
+ );
2689
+ alter table ${versionTable} enable row level security;
2690
+ revoke all on table ${versionTable} from anon, authenticated, public;
2691
+
2692
+ -- bumps each listed user once, skipping users already deleted from auth.users; no client role may call it
2693
+ create or replace function ${bumpFor}(p_users uuid[])
2694
+ returns void
2695
+ language sql
2696
+ security definer
2697
+ set search_path = ''
2698
+ as $$
2699
+ insert into ${versionTable} as v (user_id, version)
2700
+ select distinct u, 1 from unnest(p_users) u
2701
+ where u is not null and exists (select 1 from auth.users au where au.id = u)
2702
+ on conflict (user_id) do update set version = v.version + 1;
2703
+ select set_config(
2704
+ 'permdock.m.gen',
2705
+ (coalesce(nullif(current_setting('permdock.m.gen', true), ''), '0')::int + 1)::text,
2706
+ true
2707
+ )
2708
+ $$;
2709
+ revoke execute on function ${bumpFor}(uuid[]) from public, anon, authenticated;
2710
+
2711
+ -- one bump per statement: the users in the transition tables, old and new, each once
2712
+ create or replace function ${bump}()
2713
+ returns trigger
2714
+ language plpgsql
2715
+ security definer
2716
+ set search_path = ''
2717
+ as $$
2718
+ declare
2719
+ column_name text := tg_argv[0];
2720
+ users uuid[] := '{}';
2721
+ holder uuid[];
2722
+ begin
2723
+ if tg_op <> 'INSERT' then
2724
+ execute format('select coalesce(array_agg(distinct %1$I::text::uuid), ''{}'') from permdock_old where %1$I is not null', column_name)
2725
+ into holder;
2726
+ users := users || holder;
2727
+ end if;
2728
+ if tg_op <> 'DELETE' then
2729
+ execute format('select coalesce(array_agg(distinct %1$I::text::uuid), ''{}'') from permdock_new where %1$I is not null', column_name)
2730
+ into holder;
2731
+ users := users || holder;
2732
+ end if;
2733
+ perform ${bumpFor}(users);
2734
+ return null;
2735
+ end;
2736
+ $$;
2737
+ revoke execute on function ${bump}() from public, anon, authenticated;
2738
+ ${tables.map(([name, user]) => {
2739
+ const target = quoteQualified(name);
2740
+ const argument = quoteLiteral(user);
2741
+ return `drop trigger if exists ${quoteIdent(VERSION_TRIGGER)} on ${target};
2742
+ drop trigger if exists ${quoteIdent(STATEMENT_TRIGGERS.insert)} on ${target};
2743
+ create trigger ${quoteIdent(STATEMENT_TRIGGERS.insert)}
2744
+ after insert on ${target}
2745
+ referencing new table as permdock_new
2746
+ for each statement execute function ${bump}(${argument});
2747
+ drop trigger if exists ${quoteIdent(STATEMENT_TRIGGERS.update)} on ${target};
2748
+ create trigger ${quoteIdent(STATEMENT_TRIGGERS.update)}
2749
+ after update on ${target}
2750
+ referencing old table as permdock_old new table as permdock_new
2751
+ for each statement execute function ${bump}(${argument});
2752
+ drop trigger if exists ${quoteIdent(STATEMENT_TRIGGERS.delete)} on ${target};
2753
+ create trigger ${quoteIdent(STATEMENT_TRIGGERS.delete)}
2754
+ after delete on ${target}
2755
+ referencing old table as permdock_old
2756
+ for each statement execute function ${bump}(${argument});`;
2757
+ }).join("\n")}${broadcastSql(parts, versionTable)}${memberUsersVersionSql(parts, bumpFor)}${roleKeysVersionSql(parts, versionTable)}`;
2758
+ }
2759
+ const AUTHZ_RECEIVE_POLICY = `create policy permdock_authz_version_receive on realtime.messages
2760
+ for select to authenticated
2761
+ using (
2762
+ realtime.messages.extension = 'broadcast'
2763
+ and (select realtime.topic()) = 'authz:' || (select auth.uid())::text
2764
+ );`;
2765
+ /** The receive policy as a `do` block, for a migration that may lack the table. */
2766
+ function authzReceiveEmbed() {
2767
+ return `
2768
+
2769
+ -- each user receives their own authz:<uid> topic, and no user may join the server topic
2770
+ do $$
2771
+ begin
2772
+ if to_regclass('realtime.messages') is not null and not exists (
2773
+ select 1 from pg_policies
2774
+ where schemaname = 'realtime' and tablename = 'messages'
2775
+ and policyname = 'permdock_authz_version_receive'
2776
+ ) then
2777
+ ${AUTHZ_RECEIVE_POLICY}
2778
+ end if;
2779
+ end;
2780
+ $$;`;
2781
+ }
2782
+ const AUTHZ_RECEIVE_FILE = `-- Each user receives their own authz:<uid> topic, and no user may join the server topic.
2783
+ -- This policy sits outside the scoped declarative sync: pg-delta's shadow database has no realtime.messages.
2784
+ -- Apply this file with an unscoped sync only where the Realtime service has created the table.
2785
+ create policy permdock_authz_version_receive on realtime.messages
2786
+ for select to authenticated
2787
+ using (
2788
+ realtime.messages.extension = 'broadcast'
2789
+ and (select realtime.topic()) = 'authz:' || (select auth.uid())::text
2790
+ );
2791
+ `;
2792
+ /**
2793
+ * Moves the receive policy out of a schema file. A migration keeps the guarded
2794
+ * block.
2795
+ */
2796
+ function asideAuthzReceive(sql) {
2797
+ const embed = authzReceiveEmbed();
2798
+ if (!sql.includes(embed)) return {
2799
+ sql,
2800
+ receive: void 0
2801
+ };
2802
+ return {
2803
+ sql: sql.replace(embed, ""),
2804
+ receive: AUTHZ_RECEIVE_FILE
2805
+ };
2806
+ }
2807
+ /**
2808
+ * Every version row written is sent as `{ user_id, version }` on the server
2809
+ * topic and on the user's `authz:<uid>`, in the shape better-supabase's
2810
+ * `subscribeAuthzVersions` and `SessionProvider` read.
2811
+ */
2812
+ function broadcastSql(parts, versionTable) {
2813
+ const broadcast = parts.broadcast;
2814
+ if (broadcast === void 0) return "";
2815
+ const send = `${quoteIdent(parts.schema)}.permdock_broadcast_authz_version`;
2816
+ const payload = "jsonb_build_object('user_id', r.user_id, 'version', r.version)";
2817
+ const event = quoteLiteral(AUTHZ_EVENT);
2818
+ const receive = broadcast.receivePolicy ? authzReceiveEmbed() : "";
2819
+ return `
2820
+
2821
+ -- sends every version bump on the server topic and on the user's authz:<uid>
2822
+ create or replace function ${send}()
2823
+ returns trigger
2824
+ language plpgsql
2825
+ security definer
2826
+ set search_path = ''
2827
+ as $$
2828
+ declare
2829
+ r record;
2830
+ begin
2831
+ if to_regprocedure('realtime.send(jsonb, text, text, boolean)') is not null then
2832
+ for r in select * from permdock_new loop
2833
+ perform realtime.send(${payload}, ${event}, ${quoteLiteral(broadcast.topic)}, true);
2834
+ perform realtime.send(${payload}, ${event}, 'authz:' || r.user_id::text, true);
2835
+ end loop;
2836
+ end if;
2837
+ return null;
2838
+ end;
2839
+ $$;
2840
+ revoke execute on function ${send}() from public, anon, authenticated;
2841
+ drop trigger if exists permdock_authz_version_broadcast on ${versionTable};
2842
+ drop trigger if exists permdock_authz_version_broadcast_insert on ${versionTable};
2843
+ create trigger permdock_authz_version_broadcast_insert
2844
+ after insert on ${versionTable}
2845
+ referencing new table as permdock_new
2846
+ for each statement execute function ${send}();
2847
+ drop trigger if exists permdock_authz_version_broadcast_update on ${versionTable};
2848
+ create trigger permdock_authz_version_broadcast_update
2849
+ after update on ${versionTable}
2850
+ referencing new table as permdock_new
2851
+ for each statement execute function ${send}();${receive}`;
2852
+ }
2853
+ function signedUp(user) {
2854
+ return `exists (select 1 from auth.users a where a.id = ${user})`;
2855
+ }
2856
+ /**
2857
+ * Every membership source whose user id lives in another table: a row of the
2858
+ * source bumps the users its old and new references hold, and a change of that
2859
+ * table's user id (a contact re-linked to another login) bumps the old and the
2860
+ * new user.
2861
+ */
2862
+ function memberUsersVersionSql(parts, bumpFor) {
2863
+ const holders = /* @__PURE__ */ new Map();
2864
+ for (const source of parts.sources) {
2865
+ const users = source.sql.userThrough;
2866
+ if (users !== void 0) holders.set(JSON.stringify([
2867
+ tableKey(source.sql.table),
2868
+ tableKey(users.table),
2869
+ users.id,
2870
+ users.key,
2871
+ users.ref
2872
+ ]), {
2873
+ table: source.sql.table,
2874
+ users
2875
+ });
2876
+ }
2877
+ if (holders.size === 0) return "";
2878
+ const byTable = /* @__PURE__ */ new Map();
2879
+ for (const holder of holders.values()) {
2880
+ const key = tableKey(holder.table);
2881
+ const group = byTable.get(key);
2882
+ if (group === void 0) byTable.set(key, {
2883
+ table: holder.table,
2884
+ users: [holder.users]
2885
+ });
2886
+ else group.users.push(holder.users);
2887
+ }
2888
+ const memberBump = `${quoteIdent(parts.schema)}.permdock_bump_authz_version_member_users`;
2889
+ const linkedBump = `${quoteIdent(parts.schema)}.permdock_bump_authz_version_linked_users`;
2890
+ const groups = [...byTable];
2891
+ const lookup = (users, indent) => {
2892
+ const bumpFrom = (side) => `${indent} perform ${bumpFor}(array(
2893
+ ${indent} select u.${quoteIdent(users.key)}::uuid from ${quoteQualified(users.table)} u
2894
+ ${indent} where u.${quoteIdent(users.id)} in (select t.${quoteIdent(users.ref)} from permdock_${side} t)
2895
+ ${indent} and ${signedUp(`u.${quoteIdent(users.key)}::uuid`)}
2896
+ ${indent} ));`;
2897
+ return `${indent}if tg_op <> 'INSERT' then
2898
+ ${bumpFrom("old")}
2899
+ ${indent}end if;
2900
+ ${indent}if tg_op <> 'DELETE' then
2901
+ ${bumpFrom("new")}
2902
+ ${indent}end if;`;
2903
+ };
2904
+ const body = groups.map(([key, group]) => {
2905
+ if (groups.length === 1) return group.users.map((users) => lookup(users, " ")).join("\n");
2906
+ const dot = key.indexOf(".");
2907
+ return ` if tg_table_schema = ${quoteLiteral(key.slice(0, dot))} and tg_table_name = ${quoteLiteral(key.slice(dot + 1))} then
2908
+ ${group.users.map((users) => lookup(users, " ")).join("\n")}
2909
+ end if;`;
2910
+ }).join("\n");
2911
+ const memberTriggers = groups.map(([, group]) => {
2912
+ const target = quoteQualified(group.table);
2913
+ return `drop trigger if exists ${quoteIdent(VERSION_TRIGGER)} on ${target};
2914
+ ${statementTriggers(target, `${memberBump}()`)}`;
2915
+ }).join("\n");
2916
+ const userTables = /* @__PURE__ */ new Map();
2917
+ for (const { users } of holders.values()) {
2918
+ const key = JSON.stringify([tableKey(users.table), users.key]);
2919
+ const entry = userTables.get(key) ?? {
2920
+ table: users.table,
2921
+ key: users.key,
2922
+ ids: /* @__PURE__ */ new Set()
2923
+ };
2924
+ entry.ids.add(users.id);
2925
+ userTables.set(key, entry);
2926
+ }
2927
+ const userTriggers = [...userTables.values()].map((entry) => {
2928
+ const target = quoteQualified(entry.table);
2929
+ const name = quoteIdent(`${VERSION_TRIGGER}_${entry.key}`);
2930
+ return `drop trigger if exists ${name} on ${target};
2931
+ create trigger ${name}
2932
+ after update of ${[entry.key, ...entry.ids].map(quoteIdent).join(", ")} or delete on ${target}
2933
+ for each row execute function ${linkedBump}(${quoteLiteral(entry.key)});`;
2934
+ }).join("\n");
2935
+ return `
2936
+
2937
+ -- a membership whose user id lives in another table bumps the users its old and new rows reference
2938
+ create or replace function ${memberBump}()
2939
+ returns trigger
2940
+ language plpgsql
2941
+ security definer
2942
+ set search_path = ''
2943
+ as $$
2944
+ begin
2945
+ ${body}
2946
+ return null;
2947
+ end;
2948
+ $$;
2949
+ revoke execute on function ${memberBump}() from public, anon, authenticated;
2950
+ ${memberTriggers}
2951
+
2952
+ -- re-linking that table's user id moves every membership that references the row: bump the old and the new user,
2953
+ -- skipping a login being deleted (its version row goes with it)
2954
+ create or replace function ${linkedBump}()
2955
+ returns trigger
2956
+ language plpgsql
2957
+ security definer
2958
+ set search_path = ''
2959
+ as $$
2960
+ declare
2961
+ column_name text := tg_argv[0];
2962
+ begin
2963
+ perform ${bumpFor}(array(
2964
+ select u
2965
+ from unnest(array[
2966
+ case when tg_op <> 'INSERT' then to_jsonb(old) ->> column_name end,
2967
+ case when tg_op <> 'DELETE' then to_jsonb(new) ->> column_name end
2968
+ ]::uuid[]) u
2969
+ where ${signedUp("u")}
2970
+ ));
2971
+ return null;
2972
+ end;
2973
+ $$;
2974
+ revoke execute on function ${linkedBump}() from public, anon, authenticated;
2975
+ ${userTriggers}`;
2976
+ }
2977
+ /**
2978
+ * Every table whose role column references a roles table: the global roles and
2979
+ * the membership sources.
2980
+ */
2981
+ function roleKeyHolders(parts) {
2982
+ const holders = [];
2983
+ if (parts.roles?.through !== void 0) holders.push({
2984
+ table: parts.roles.table,
2985
+ user: parts.roles.user,
2986
+ through: parts.roles.through
2987
+ });
2988
+ for (const source of parts.sources) for (const through of source.sql.throughs) holders.push({
2989
+ table: source.sql.table,
2990
+ user: source.sql.user,
2991
+ ...source.sql.userThrough === void 0 ? {} : { userThrough: source.sql.userThrough },
2992
+ through
2993
+ });
2994
+ const seen = /* @__PURE__ */ new Set();
2995
+ return holders.filter((holder) => {
2996
+ const key = JSON.stringify([
2997
+ tableKey(holder.table),
2998
+ holder.user,
2999
+ holder.userThrough === void 0 ? null : [
3000
+ tableKey(holder.userThrough.table),
3001
+ holder.userThrough.id,
3002
+ holder.userThrough.key
3003
+ ],
3004
+ tableKey(holder.through.table),
3005
+ holder.through.key,
3006
+ holder.through.match
3007
+ ]);
3008
+ if (seen.has(key)) return false;
3009
+ seen.add(key);
3010
+ return true;
3011
+ });
3012
+ }
3013
+ /**
3014
+ * The holders of the roles rows in `source`, a relation of the roles table's
3015
+ * columns (`permdock_old`, `permdock_new` or a difference of the two).
3016
+ */
3017
+ function holderSelect(holder, source) {
3018
+ const held = holder.through.match.map(([ref, id]) => `h.${quoteIdent(ref)} = r.${quoteIdent(id)}`).join(" and ");
3019
+ return holder.userThrough === void 0 ? `select h.${quoteIdent(holder.user)}::uuid as user_id from ${quoteQualified(holder.table)} h join ${source} r on ${held}` : `select u.${quoteIdent(holder.userThrough.key)}::uuid as user_id from ${quoteQualified(holder.table)} h join ${quoteQualified(holder.userThrough.table)} u on u.${quoteIdent(holder.userThrough.id)} = h.${quoteIdent(holder.user)} join ${source} r on ${held}`;
3020
+ }
3021
+ function bumpHolders(selects, versionTable, indent) {
3022
+ return `${indent}insert into ${versionTable} as v (user_id, version)
3023
+ ${indent}select distinct h.user_id, 1
3024
+ ${indent}from (
3025
+ ${indent} ${selects.join(`\n${indent} union\n${indent} `)}
3026
+ ${indent}) h
3027
+ ${indent}where h.user_id is not null
3028
+ ${indent} and exists (select 1 from auth.users au where au.id = h.user_id)
3029
+ ${indent}on conflict (user_id) do update set version = v.version + 1;`;
3030
+ }
3031
+ /**
3032
+ * An insert bumps the new holders, a delete the old ones, and an update the
3033
+ * holders of every row whose key or ids differ between `permdock_old` and
3034
+ * `permdock_new`: a row that kept them is in both and bumps no one, so an edit
3035
+ * to another column writes nothing.
3036
+ */
3037
+ function roleKeysBumpSql(holders, versionTable, indent) {
3038
+ const columns = [...new Set(holders.flatMap((holder) => [holder.through.key, ...holder.through.match.map(([, id]) => id)]))].map(quoteIdent).join(", ");
3039
+ const changed = (from, other) => `(select ${columns} from ${from} except select ${columns} from ${other})`;
3040
+ const rows = (source) => holders.map((holder) => holderSelect(holder, source));
3041
+ return `${indent}if tg_op = 'INSERT' then
3042
+ ${bumpHolders(rows("permdock_new"), versionTable, `${indent} `)}
3043
+ ${indent}elsif tg_op = 'DELETE' then
3044
+ ${bumpHolders(rows("permdock_old"), versionTable, `${indent} `)}
3045
+ ${indent}else
3046
+ ${bumpHolders([...rows(changed("permdock_old", "permdock_new")), ...rows(changed("permdock_new", "permdock_old"))], versionTable, `${indent} `)}
3047
+ ${indent}end if;`;
3048
+ }
3049
+ /**
3050
+ * A new membership role, a removed one, or a renamed role key changes the
3051
+ * `roles` claim, so an insert, update or delete on the roles table bumps each
3052
+ * holder. A moved row bumps the old holder and the new one.
3053
+ */
3054
+ function roleKeysVersionSql(parts, versionTable) {
3055
+ const holders = roleKeyHolders(parts);
3056
+ if (holders.length === 0) return "";
3057
+ const byTable = /* @__PURE__ */ new Map();
3058
+ for (const holder of holders) {
3059
+ const key = tableKey(holder.through.table);
3060
+ const group = byTable.get(key);
3061
+ if (group === void 0) byTable.set(key, {
3062
+ table: holder.through.table,
3063
+ holders: [holder]
3064
+ });
3065
+ else group.holders.push(holder);
3066
+ }
3067
+ const bump = `${quoteIdent(parts.schema)}.permdock_bump_authz_version_role_keys`;
3068
+ const groups = [...byTable];
3069
+ return `
3070
+
3071
+ -- a renamed role key changes the roles of everyone who holds it, globally or through a membership
3072
+ create or replace function ${bump}()
3073
+ returns trigger
3074
+ language plpgsql
3075
+ security definer
3076
+ set search_path = ''
3077
+ as $$
3078
+ begin
3079
+ ${groups.map(([key, group]) => {
3080
+ if (groups.length === 1) return roleKeysBumpSql(group.holders, versionTable, " ");
3081
+ const dot = key.indexOf(".");
3082
+ return ` if tg_table_schema = ${quoteLiteral(key.slice(0, dot))} and tg_table_name = ${quoteLiteral(key.slice(dot + 1))} then
3083
+ ${roleKeysBumpSql(group.holders, versionTable, " ")}
3084
+ end if;`;
3085
+ }).join("\n")}
3086
+ return null;
3087
+ end;
3088
+ $$;
3089
+ revoke execute on function ${bump}() from public, anon, authenticated;
3090
+ ${groups.map(([, group]) => {
3091
+ const target = quoteQualified(group.table);
3092
+ return `drop trigger if exists ${quoteIdent(VERSION_TRIGGER)} on ${target};
3093
+ ${statementTriggers(target, `${bump}()`)}`;
3094
+ }).join("\n")}`;
3095
+ }
3096
+ // src/cli/supabase-hook/manifest.ts
3097
+ function helperList(parts, types) {
3098
+ const client = ["authenticated"];
3099
+ const teams = hookTeamsHelper(parts);
3100
+ return [
3101
+ helperEntry(HELPERS.has, "p_grant text", "boolean", client),
3102
+ ...parts.scopes.flatMap((scope) => {
3103
+ const returns = `setof ${types.get(scope.name) ?? "uuid"}`;
3104
+ return [
3105
+ helperEntry(permittedIdsHelper(scope.name), "p_grant text", returns, client),
3106
+ helperEntry(memberIdsHelper(scope.name), "", returns, client),
3107
+ ...parts.helpers.memberFor.includes(scope.name) ? [helperEntry(memberForHelper(scope.name), isTeamScope(scope.name) ? "p_user uuid, p_active text" : "p_user uuid", returns, ["supabase_auth_admin"])] : [],
3108
+ ...parts.helpers.memberFor.includes(scope.name) && isTeamScope(scope.name) ? [helperEntry(memberOfHelper(scope.name), "p_user uuid", returns, client)] : []
3109
+ ];
3110
+ }),
3111
+ ...teams === void 0 ? [] : [helperEntry(HOOK_TEAM_READER, "p_user uuid, p_active text", "setof uuid", parts.hook.security === "definer" ? [] : ["supabase_auth_admin"]), helperEntry(teams, "p_user uuid", "setof uuid", client)]
3112
+ ];
3113
+ }
3114
+ function helperEntry(name, args, returns, execute) {
3115
+ return {
3116
+ name,
3117
+ args,
3118
+ returns,
3119
+ execute
3120
+ };
3121
+ }
3122
+ /**
3123
+ * The helpers `rls generate` writes beyond the ones the hook's claims feed: the
3124
+ * `_for` forms in `database` mode, and the assignment checks when a role
3125
+ * declares `assigns` (known only with the policy).
3126
+ */
3127
+ function trustedHelpers(parts, config, types, tenantType, policy) {
3128
+ const database = resolveAuthorize(config) === "database";
3129
+ const custom = database && customRolesOn(config.rls);
3130
+ const everyFor = parts.scopes.every((scope) => parts.helpers.memberFor.includes(scope.name));
3131
+ const client = ["authenticated"];
3132
+ const scopeTypes = parts.scopes.map((scope) => [scope.name, types.get(scope.name) ?? "uuid"]);
3133
+ const forUser = database ? [
3134
+ helperEntry(HELPERS.hasFor, "p_user uuid, p_grant text", "boolean", []),
3135
+ ...scopeTypes.map(([scope, type]) => helperEntry(permittedForHelper(scope), "p_user uuid, p_grant text", `setof ${type}`, [])),
3136
+ ...scopeTypes.map(([scope, type]) => helperEntry(permissionKeysForHelper(scope), `p_user uuid, p_id ${type}`, "setof text", [])),
3137
+ ...scopeTypes.filter(([scope]) => parts.helpers.holders.includes(scope)).map(([scope, type]) => helperEntry(permittedUsersHelper(scope), `p_permission text, p_id ${type}`, "setof uuid", []))
3138
+ ] : [];
3139
+ const keyed = [
3140
+ helperEntry(USER_ID_HELPER, "", "uuid", client),
3141
+ helperEntry(PERMDOCK_SUBJECT, "", "jsonb", client),
3142
+ helperEntry(PERMDOCK_SUBJECT, "p_tenant text", "jsonb", client),
3143
+ helperEntry(BOOTSTRAP_PERMISSIONS, "p_tenant text", "jsonb", client),
3144
+ ...config.rls?.apiKeys === void 0 ? [] : [helperEntry(API_KEY_ALLOWS, "p_grant text", "boolean", client)],
3145
+ ...config.rls?.tokenScopes === true ? [helperEntry(TOKEN_SCOPE_ALLOWS, "p_grant text", "boolean", client)] : [],
3146
+ ...policy === void 0 || interactiveOnlyKeys(policy) === void 0 ? [] : [helperEntry(INTERACTIVE_ALLOWS, "p_grant text", "boolean", client)],
3147
+ ...readOnlyActorKinds(config.rls?.readOnlyActors) === void 0 ? [] : [helperEntry(ACTOR_MAY_WRITE, "", "boolean", client)],
3148
+ ...config.rls?.approvals === true || typeof config.rls?.approvals === "object" ? [helperEntry(IS_APPROVER, typeof config.rls.approvals === "object" && (config.rls.approvals.delegations === true || config.rls.approvals.managers !== void 0) ? "p_approvers jsonb, p_tenant text, p_requester text, p_resource text" : "p_approvers jsonb, p_tenant text", "boolean", client), helperEntry(APPROVER_FOR_IDS, "", "setof uuid", client)] : [],
3149
+ ...typeof config.rls?.approvals === "object" && config.rls.approvals.managers !== void 0 ? [helperEntry(MANAGES, "p_requester text, p_levels integer", "boolean", []), helperEntry(MANAGED_USER_IDS, config.rls.approvals.managers.tenant === void 0 ? "" : `p_tenant ${tenantType}`, "setof uuid", client)] : [],
3150
+ ...forUser
3151
+ ];
3152
+ if (!(policy !== void 0 && (ownershipRules(policy, parts.scopes)?.assigns.length ?? 0) > 0)) return keyed;
3153
+ const customArgs = `p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text`;
3154
+ const anyArgs = `p_role text, p_tenant ${tenantType}, p_scope text, p_scope_id text`;
3155
+ return [
3156
+ ...keyed,
3157
+ helperEntry(OWNERSHIP.canAssign, "p_role text, p_scope_id text", "boolean", client),
3158
+ ...database ? [helperEntry(OWNERSHIP.canAssignFor, "p_user uuid, p_role text, p_scope_id text", "boolean", [])] : [],
3159
+ ...custom ? [helperEntry(ASSIGNMENTS.custom, customArgs, "boolean", client)] : [],
3160
+ ...custom && everyFor ? [helperEntry(ASSIGNMENTS.customFor, `p_user uuid, ${customArgs}`, "boolean", [])] : [],
3161
+ helperEntry(OWNERSHIP.canAssignAny, anyArgs, "boolean", client),
3162
+ ...database && (!custom || everyFor) ? [helperEntry(OWNERSHIP.canAssignAnyFor, `p_user uuid, ${anyArgs}`, "boolean", [])] : []
3163
+ ];
3164
+ }
3165
+ function activeRowManifest(row) {
3166
+ const keep = "keep" in row ? keptKeys(row) : [];
3167
+ return {
3168
+ table: qualifySqlTable(row.table),
3169
+ id: row.id,
3170
+ ...row.disabledAt === void 0 ? {} : { disabledAt: row.disabledAt },
3171
+ ...row.status === void 0 ? {} : { status: row.status },
3172
+ ...row.active === void 0 ? {} : { active: row.active },
3173
+ ...keep.length === 0 ? {} : { keep }
3174
+ };
3175
+ }
3176
+ /**
3177
+ * The `rls` settings a package writing SQL next to the helpers reads: custom
3178
+ * roles, global roles, suspension and assignment triggers.
3179
+ */
3180
+ function rlsSettings(parts, config) {
3181
+ const rls = config.rls;
3182
+ const suspension = checkSuspension(rls?.suspension, parts.scopes);
3183
+ const scopes = Object.entries(suspension?.scopes ?? {});
3184
+ const assigned = rls?.assignments === void 0 ? void 0 : guardedTables(config, parts.scopes);
3185
+ return {
3186
+ customRoles: resolveAuthorize(config) === "database" && customRolesOn(rls),
3187
+ ...rls?.customRoleWrites?.roles?.tenant === void 0 ? {} : { customRoleTenant: rls.customRoleWrites.roles.tenant },
3188
+ ...parts.roles === void 0 ? {} : { roles: {
3189
+ table: qualifySqlTable(parts.roles.table),
3190
+ user: { column: parts.roles.user },
3191
+ role: parts.roles.role
3192
+ } },
3193
+ ...suspension === void 0 ? {} : { suspension: {
3194
+ ...suspension.users === void 0 ? {} : { users: activeRowManifest(suspension.users) },
3195
+ ...scopes.length === 0 ? {} : { scopes: Object.fromEntries(scopes.map(([name, row]) => [name, activeRowManifest(row)])) },
3196
+ ...suspension.memberships === void 0 ? {} : { memberships: { keep: keptKeys(suspension.memberships) } }
3197
+ } },
3198
+ ...assigned === void 0 ? {} : { assignments: { tables: assigned } },
3199
+ ...rls?.apiKeys === void 0 ? {} : { apiKeys: apiKeyFields(rls.apiKeys) },
3200
+ ...rls?.tokenScopes === true ? { tokenScopes: true } : {}
3201
+ };
3202
+ }
3203
+ /** The `supabase/sdk` release `requires.capabilities` names features of. */
3204
+ const CAPABILITY_MATRIX = "capability-matrix-v1.12.0";
3205
+ function usesLiveSession(policy) {
3206
+ return [...policy?.grants ?? [], ...policy?.roles.flatMap((binding) => binding.grants) ?? []].some((grant) => hasConditionOp(grant.where, "liveSession") || hasConditionOp(grant.check, "liveSession"));
3207
+ }
3208
+ function requiredCapabilities(config, policy) {
3209
+ const ids = /* @__PURE__ */ new Set(["auth.session.get_claims"]);
3210
+ if (usesLiveSession(policy)) ids.add("auth.session.get_user");
3211
+ if (config.rls?.realtime !== void 0) ids.add("realtime.subscriptions.private_channel");
3212
+ for (const bucket of Object.values(config.rls?.storage?.buckets ?? {})) {
3213
+ if (bucket.read !== void 0) {
3214
+ ids.add("storage.file_buckets.download");
3215
+ ids.add("storage.file_buckets.list_files");
3216
+ }
3217
+ if (bucket.write !== void 0) {
3218
+ ids.add("storage.file_buckets.upload");
3219
+ ids.add("storage.file_buckets.update_file");
3220
+ ids.add("storage.file_buckets.move");
3221
+ }
3222
+ if (bucket.delete !== void 0) ids.add("storage.file_buckets.remove");
3223
+ }
3224
+ return {
3225
+ matrix: CAPABILITY_MATRIX,
3226
+ capabilities: [...ids].toSorted()
3227
+ };
3228
+ }
3229
+ /**
3230
+ * The declared roles the `defineSeeds` fixtures give a member, or without
3231
+ * fixture memberships every role at the root scope and every global role,
3232
+ * sorted.
3233
+ */
3234
+ function fixtureRolesOf(policy, config, root) {
3235
+ const declared = new Set(policy.roles.map((binding) => binding.name));
3236
+ const fixtures = config.seeds === void 0 ? void 0 : Reflect.get(config.seeds, "fixtures");
3237
+ const entries = isRecord(fixtures) ? fixtures["memberships"] : void 0;
3238
+ const seeded = (Array.isArray(entries) ? entries : []).flatMap((entry) => {
3239
+ const held = isRecord(entry) ? entry["roles"] : void 0;
3240
+ return Array.isArray(held) ? held.filter((role) => typeof role === "string") : [];
3241
+ });
3242
+ const roles = seeded.length > 0 ? seeded.filter((role) => declared.has(role)) : policy.roles.filter((binding) => binding.on === void 0 || binding.on === root).map((binding) => binding.name);
3243
+ return [...new Set(roles)].toSorted();
3244
+ }
3245
+ function manifestOf(parts, out, config, policy) {
3246
+ const rls = config.rls;
3247
+ const ctx = {
3248
+ dialect: "supabase",
3249
+ scopes: parts.scopes,
3250
+ tenantClaim: parts.tenantClaim,
3251
+ gucPrefix: rls?.gucPrefix ?? "app",
3252
+ tenantType: firstScopeType(rls?.scopeTypes, parts.scopes),
3253
+ ...rls?.scopeTypes === void 0 ? {} : { scopeTypes: rls.scopeTypes }
3254
+ };
3255
+ const types = new Map(parts.scopes.map((scope) => [scope.name, scopeTypeOf(ctx, scope.name)]));
3256
+ const helpers = helperList(parts, types);
3257
+ return {
3258
+ $schema: SUPABASE_MANIFEST_SCHEMA,
3259
+ version: 1,
3260
+ hook: {
3261
+ schema: parts.schema,
3262
+ function: "custom_access_token_hook",
3263
+ out,
3264
+ ...parts.before.length === 0 ? {} : { before: parts.before },
3265
+ activeFrom: parts.activeFrom
3266
+ },
3267
+ helpers: {
3268
+ schema: parts.helpers.schema,
3269
+ functions: helpers.map((entry) => entry.name)
3270
+ },
3271
+ tenantClaim: parts.tenantClaim,
3272
+ budget: {
3273
+ bytes: parts.budget,
3274
+ measure: BUDGET_MEASURE
3275
+ },
3276
+ claims: hookClaims(parts),
3277
+ authzVersion: parts.version,
3278
+ ...parts.version ? { authzVersionBump: {
3279
+ schema: parts.schema,
3280
+ function: AUTHZ_VERSION_BUMP,
3281
+ args: "p_users uuid[]"
3282
+ } } : {},
3283
+ memberships: parts.sources.map((source) => source.sql.manifest),
3284
+ rls: {
3285
+ schema: parts.helpers.schema,
3286
+ mode: resolveAuthorize(config),
3287
+ tenantClaim: parts.tenantClaim,
3288
+ scopes: parts.scopes.map((scope) => ({
3289
+ name: scope.name,
3290
+ type: types.get(scope.name) ?? "uuid",
3291
+ ...scope.within === void 0 ? {} : { within: scope.within }
3292
+ })),
3293
+ helpers: [...helpers, ...trustedHelpers(parts, config, types, tenantTypeOf(ctx), policy)],
3294
+ memberships: parts.helpers.memberships,
3295
+ ...rlsSettings(parts, config)
3296
+ },
3297
+ decidingColumns: decidingColumns(config, parts.attrs === void 0 ? void 0 : {
3298
+ ...parts.attrs.table === void 0 ? {} : { table: parts.attrs.table },
3299
+ columns: parts.attrs.columns
3300
+ }, parts.hook.teams),
3301
+ markers: {
3302
+ hook: "v1",
3303
+ grants: "v1"
3304
+ },
3305
+ requires: requiredCapabilities(config, policy),
3306
+ ...policy === void 0 ? {} : {
3307
+ names: resolveNames(policy, config, {
3308
+ schema: parts.helpers.schema,
3309
+ tenantClaim: parts.tenantClaim
3310
+ }),
3311
+ fixtureRoles: fixtureRolesOf(policy, config, parts.root)
3312
+ }
3313
+ };
3314
+ }
3315
+ /**
3316
+ * The manifest without the token hook: what a project with no `supabase.hook`
3317
+ * records.
3318
+ */
3319
+ function databaseManifestOf(parts, out, config, policy) {
3320
+ const { hook: _hook, budget: _budget, claims: _claims, authzVersion: _authzVersion, authzVersionBump: _authzVersionBump, memberships: _memberships, ...rest } = manifestOf(parts, out, config, policy);
3321
+ return rest;
3322
+ }
3323
+ /**
3324
+ * The first line of the generated hook: fields `--check` compares before the
3325
+ * full text.
3326
+ */
3327
+ function hookMarker(manifest) {
3328
+ return `${HOOK_MARKER} schema=${manifest.hook.schema} tenant=${manifest.tenantClaim} budget=${String(manifest.budget.bytes)} claims=${manifest.claims.map((claim) => claim.name).join(",")}`;
3329
+ }
3330
+ function defaultOut(config) {
3331
+ return config.supabase?.hook?.out ?? "supabase/permdock-hook.sql";
3332
+ }
3333
+ // src/cli/supabase-hook/emit/hook-sql.ts
3334
+ /** Whether the project is in the one case that has a manifest without a hook. */
3335
+ function hooklessDatabase(config) {
3336
+ return config.supabase?.hook === void 0 && resolveAuthorize(config) === "database";
3337
+ }
3338
+ /**
3339
+ * The manifest `supabase inspect` prints. With `policy`, `rls.helpers` also
3340
+ * lists the assignment checks `rls generate` writes for roles that declare
3341
+ * `assigns`.
3342
+ */
3343
+ function supabaseHookManifest(scopes, config, overrides = {}, policy) {
3344
+ const manifest = manifestOf(hookParts(scopes, config, overrides), overrides.out ?? defaultOut(config), config, policy);
3345
+ return overrides.schemas === void 0 ? manifest : {
3346
+ ...manifest,
3347
+ hook: {
3348
+ ...manifest.hook,
3349
+ schemas: overrides.schemas
3350
+ }
3351
+ };
3352
+ }
3353
+ /**
3354
+ * The manifest of a project in `rls.authorize: 'database'` mode with no
3355
+ * `supabase.hook`: the helpers, scopes, membership sources and grants, and no
3356
+ * token hook.
3357
+ */
3358
+ function supabaseDatabaseManifest(scopes, config, overrides = {}, policy) {
3359
+ return databaseManifestOf(hookParts(scopes, {
3360
+ ...config,
3361
+ supabase: {
3362
+ ...config.supabase,
3363
+ hook: config.rls?.membershipSources === void 0 ? {} : { memberships: config.rls.membershipSources }
3364
+ }
3365
+ }, overrides), overrides.out ?? defaultOut(config), config, policy);
3366
+ }
3367
+ /**
3368
+ * The hook migration. With `grantsOut`, the statements `supabase db diff` drops
3369
+ * are left out of `sql` and returned in `grants` for that file.
3370
+ */
3371
+ function supabaseHookSql(scopes, config, overrides = {}, grantsOut) {
3372
+ const parts = hookParts(scopes, config, overrides);
3373
+ const manifest = manifestOf(parts, defaultOut(config), config);
3374
+ const toml = configToml(parts.schema, parts.jwtExpiry).split("\n").map((line) => line === "" ? "--" : `-- ${line}`).join("\n");
3375
+ const sql = [
3376
+ `${hookMarker(manifest)}
3377
+ -- custom_access_token_hook(jsonb): memberships go active ${parts.root} first and stop at the budget
3378
+ -- supabase/config.toml:
3379
+ ${toml}${grantsOut === void 0 ? "" : `\n-- what supabase db diff drops from this part is in ${grantsOut}`}`,
3380
+ schemaSql(parts),
3381
+ attrsGuardSql(parts.attrs, parts.schema),
3382
+ globalRolesSql(parts),
3383
+ membershipEntriesSql(parts),
3384
+ hookSql(parts),
3385
+ versionSql(parts),
3386
+ subjectForSql(parts, config),
3387
+ subjectForTenantSql(parts, config),
3388
+ permdockSubjectSql(parts),
3389
+ authzVersionForSql(parts),
3390
+ customRolesVersionForSql(parts, config),
3391
+ membersOfSql(parts),
3392
+ apiWrappersSql(parts, config),
3393
+ grantsSql(parts),
3394
+ managedSql(parts)
3395
+ ].filter((chunk) => chunk !== "").join("\n\n");
3396
+ const { kept, moved } = splitUndiffed(`${sql}\n`);
3397
+ const grants = `${GRANTS_MARKER} schema=${parts.schema}
3398
+ -- the privileges and view options supabase db diff drops from the hook part
3399
+ ${moved.join("\n")}
3400
+ `;
3401
+ return {
3402
+ sql: grantsOut === void 0 ? `${sql}\n` : kept,
3403
+ grants,
3404
+ manifest
3405
+ };
3406
+ }
3407
+ /** What the hook file's header says about where its grants went. */
3408
+ function grantsLabel(grantsOut) {
3409
+ if (grantsOut === void 0) return;
3410
+ return grantsOut === "-" ? "a separate migration" : grantsOut;
3411
+ }
3412
+ export { supabaseHookSql as a, asideAuthzReceive as c, activeSource as d, isSupabaseSchemas as f, attrsPlan as g, declarativeSql as h, supabaseHookManifest as i, configToml as l, schemasRefusal as m, hooklessDatabase as n, defaultOut as o, resolveSchemas as p, supabaseDatabaseManifest as r, hookMarker as s, grantsLabel as t, approvalsSql as u };