permdock 0.25.1 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (969) hide show
  1. package/README.md +1 -1
  2. package/dist/2020-bJfT8aIA.js +6760 -0
  3. package/dist/a2a/index.d.ts +5 -9
  4. package/dist/a2a/index.js +13 -15
  5. package/dist/adapter-context-lHq_i_77.js +28 -0
  6. package/dist/adoption-scan-CMghLDUG.js +106 -0
  7. package/dist/agent/index.d.ts +2 -2
  8. package/dist/agent/index.js +1 -1
  9. package/dist/ai-sdk/index.d.ts +4 -6
  10. package/dist/ai-sdk/index.js +6 -7
  11. package/dist/annotate-doc-BCOCOrq_.js +214 -0
  12. package/dist/annotate-routes-BvSuEht3.js +75 -0
  13. package/dist/annotate-uZVGIRym.js +25 -0
  14. package/dist/app/index.d.ts +2 -103
  15. package/dist/app/index.js +1 -114
  16. package/dist/app-data-DbSPSPIl.js +62 -0
  17. package/dist/approval-header-BvszJE3l.js +25 -0
  18. package/dist/approval-normalize-Cpp8R0rY.js +190 -0
  19. package/dist/approval-prompt-C-vjNZyd.d.ts +57 -0
  20. package/dist/approval-prompt-Covyx_DB.js +60 -0
  21. package/dist/approval-required-B-R4Yw3J.js +5 -0
  22. package/dist/approvals/index.d.ts +5 -5
  23. package/dist/approvals/index.js +8 -8
  24. package/dist/approvals-7jHYXocE.js +1039 -0
  25. package/dist/approvers-BkY_ZfWl.js +76 -0
  26. package/dist/arazzo-B8heXoYy.js +76 -0
  27. package/dist/arazzo-DdJBVrsy.js +35 -0
  28. package/dist/args-0EWFk-4S.js +311 -0
  29. package/dist/astro/index.d.ts +6 -8
  30. package/dist/astro/index.js +3 -4
  31. package/dist/audience-DauhRBNg.js +54 -0
  32. package/dist/auth-WHKYWtnS.js +187 -0
  33. package/dist/authz-topic-D8x24Jv-.js +14 -0
  34. package/dist/authzen/index.d.ts +37 -22
  35. package/dist/authzen/index.js +69 -27
  36. package/dist/automation-CUcWz8uu.d.ts +122 -0
  37. package/dist/automation-CpPdFX91.js +157 -0
  38. package/dist/base-url--yJPQlIK.js +8 -0
  39. package/dist/better-auth/index.d.ts +2 -8
  40. package/dist/better-auth/index.js +10 -13
  41. package/dist/better-supabase/index.d.ts +141 -95
  42. package/dist/better-supabase/index.js +239 -794
  43. package/dist/better-supabase-DSbs4MtQ.js +201 -0
  44. package/dist/bind-B3MHrzw4.d.ts +56 -0
  45. package/dist/bind-up3QptTt.js +124 -0
  46. package/dist/body-W1_8r6Tw.js +9 -0
  47. package/dist/body-text-B-m3p-qY.js +55 -0
  48. package/dist/boundary--5Swp7sN.js +18 -0
  49. package/dist/boundary-DJqHADKu.d.ts +22 -0
  50. package/dist/budget-5LJ8kfZk.d.ts +12 -0
  51. package/dist/budget-BH81q2cj.js +19 -0
  52. package/dist/build-instance-hLKYe3-E.js +30 -0
  53. package/dist/canonical-json-BibZkXtE.js +28 -0
  54. package/dist/capability-CVt3lpVK.d.ts +128 -0
  55. package/dist/capability-_ZsyfYxU.js +204 -0
  56. package/dist/casbin-BHYVxJDD.js +29 -0
  57. package/dist/casbin-D33ZeUf5.js +241 -0
  58. package/dist/casl-CrltbDPa.js +23 -0
  59. package/dist/casl-D7n7yE-h.js +307 -0
  60. package/dist/catalog/index.d.ts +6 -20
  61. package/dist/catalog/index.js +13 -15
  62. package/dist/catalog-B3MJShnZ.js +51 -0
  63. package/dist/catalog-CgK_L4Qf.js +1 -0
  64. package/dist/catalog-DyC3LKc7.js +130 -0
  65. package/dist/catalog-doc-Bp5khmCG.js +352 -0
  66. package/dist/catalog-fingerprint-DAWZARy6.js +31 -0
  67. package/dist/catalog-operations-dxuOZr4J.js +59 -0
  68. package/dist/catalog-path-bG0XxHMu.js +11 -0
  69. package/dist/challenge-CjwmjcuX.js +518 -0
  70. package/dist/chat/index.d.ts +1 -1
  71. package/dist/chat/index.js +10 -13
  72. package/dist/chat-sdk/index.d.ts +3 -11
  73. package/dist/chat-sdk/index.js +7 -11
  74. package/dist/checks-DSm45qH7.js +71 -0
  75. package/dist/claims-map-BGbpbvGD.js +15 -0
  76. package/dist/claims-map-CLKQWxJG.d.ts +33 -0
  77. package/dist/claims-size-DcjhvUv5.js +58 -0
  78. package/dist/claude-agent/index.d.ts +3 -5
  79. package/dist/claude-agent/index.js +4 -5
  80. package/dist/clerk/index.d.ts +4 -8
  81. package/dist/clerk/index.js +7 -8
  82. package/dist/cli/bin.js +6 -7
  83. package/dist/cli/generate/watch-worker.d.ts +20 -0
  84. package/dist/cli/generate/watch-worker.js +69 -0
  85. package/dist/cli/index.d.ts +11 -20
  86. package/dist/cli/index.js +8 -8
  87. package/dist/cli/plugins/app.d.ts +24 -0
  88. package/dist/cli/plugins/app.js +36 -0
  89. package/dist/cli/plugins/better-supabase.d.ts +10 -0
  90. package/dist/cli/plugins/better-supabase.js +18 -0
  91. package/dist/cli/plugins/openapi.d.ts +19 -0
  92. package/dist/cli/plugins/openapi.js +40 -0
  93. package/dist/cli/plugins/powersync.d.ts +7 -0
  94. package/dist/cli/plugins/powersync.js +29 -0
  95. package/dist/cli/plugins/rls.d.ts +8 -0
  96. package/dist/cli/plugins/rls.js +27 -0
  97. package/dist/cli/plugins/schemas.d.ts +13 -0
  98. package/dist/cli/plugins/schemas.js +23 -0
  99. package/dist/cli/plugins/scim.d.ts +10 -0
  100. package/dist/cli/plugins/scim.js +32 -0
  101. package/dist/cli/plugins/supabase-hook.d.ts +13 -0
  102. package/dist/cli/plugins/supabase-hook.js +40 -0
  103. package/dist/cli/plugins/supabase.d.ts +27 -0
  104. package/dist/cli/plugins/supabase.js +69 -0
  105. package/dist/cli/plugins/ui.d.ts +11 -0
  106. package/dist/cli/plugins/ui.js +19 -0
  107. package/dist/client-V95IvZsF.d.ts +43 -0
  108. package/dist/client-subject-v89t811z.d.ts +25 -0
  109. package/dist/clients-Bb_33pRE.js +22 -0
  110. package/dist/clients-DGcyFDCc.d.ts +10 -0
  111. package/dist/cloud/index.d.ts +8 -26
  112. package/dist/cloud/index.js +22 -28
  113. package/dist/cloud-BmQrcTvx.js +85 -0
  114. package/dist/codemod-BpjMjxly.js +2159 -0
  115. package/dist/codemod-C_NKj01W.js +35 -0
  116. package/dist/collect-BJZsuBW4.js +535 -0
  117. package/dist/collect-CPvCXMQ-.js +1 -0
  118. package/dist/collect-CpGnmGpL.js +54 -0
  119. package/dist/command-9GAzSI7E.js +5 -0
  120. package/dist/compact-C4LFuqbW.js +28 -0
  121. package/dist/compare-dfHDj8kT.js +11 -0
  122. package/dist/compile/index.d.ts +2 -2
  123. package/dist/compile/index.js +1 -1
  124. package/dist/compile-BUKXrueE.js +685 -0
  125. package/dist/compile-D8c1nFGy.d.ts +118 -0
  126. package/dist/compile-Dy3zMRxo.js +724 -0
  127. package/dist/completion-CSncf6cX.js +150 -0
  128. package/dist/conditions-CkHgXoZB.js +385 -0
  129. package/dist/config-iyy90IOU.js +143 -0
  130. package/dist/config-report-D607UDnv.js +55 -0
  131. package/dist/config-shape-B6tdyBju.js +149 -0
  132. package/dist/config-xiX3R65I.js +25 -0
  133. package/dist/connection-BnoSqYU1.js +196 -0
  134. package/dist/connector-schema-BSRMyq4M.js +433 -0
  135. package/dist/constants-PCJiir_3.js +19 -0
  136. package/dist/context-DmH-Eyvx.js +95 -0
  137. package/dist/convex/index.d.ts +5 -9
  138. package/dist/convex/index.js +7 -8
  139. package/dist/core-CnC47rSf.d.ts +200 -0
  140. package/dist/core-DKqrD_xW.js +338 -0
  141. package/dist/coverage-DL7JCZmb.d.ts +133 -0
  142. package/dist/coverage-nFSMjFxH.js +42 -0
  143. package/dist/create-BAMPoEga.js +133 -0
  144. package/dist/create-BsRcXm_m.d.ts +125 -0
  145. package/dist/create-D3oXoXxM.js +373 -0
  146. package/dist/create-DeQ5t8mZ.d.ts +124 -0
  147. package/dist/create-sGl1ccTp.d.ts +185 -0
  148. package/dist/credential-ke0KMQeB.js +430 -0
  149. package/dist/credentials-6ZWbJ-Re.js +72 -0
  150. package/dist/credentials-BfzdL5kv.d.ts +123 -0
  151. package/dist/credentials-DOeqknte.js +309 -0
  152. package/dist/decide-set-CgNcE6pP.js +99 -0
  153. package/dist/deciding-columns-BnglEKqU.js +143 -0
  154. package/dist/decision-hHv4UZgy.js +20 -0
  155. package/dist/define-permdock-BLpQ0m95.d.ts +99 -0
  156. package/dist/define-permdock-CIxHBykk.js +148 -0
  157. package/dist/definition-options-9o8Hdww3.js +370 -0
  158. package/dist/delegation-BaUNCrE_.js +263 -0
  159. package/dist/delegation-input-7Y5Rlja7.js +18 -0
  160. package/dist/delivery/index.d.ts +4 -4
  161. package/dist/delivery/index.js +5 -5
  162. package/dist/delivery-Cb3VCij5.js +555 -0
  163. package/dist/delivery-event-D5b9yhaJ.js +39 -0
  164. package/dist/denied-text-D6JJTDr3.d.ts +20 -0
  165. package/dist/describe-B7EosIKA.js +100 -0
  166. package/dist/describe-lAafaRQQ.d.ts +43 -0
  167. package/dist/device-f3JEnqa0.js +195 -0
  168. package/dist/diff-BIqibFnm.js +464 -0
  169. package/dist/diff-n6LONVwL.js +36 -0
  170. package/dist/digest-BaP8bQzX.js +26 -0
  171. package/dist/digest-BcIZRYvp.d.ts +17 -0
  172. package/dist/doctor-BhoJiHi0.js +4847 -0
  173. package/dist/doctor-CoKSRLhf.js +53 -0
  174. package/dist/drizzle/index.d.ts +5 -9
  175. package/dist/drizzle/index.js +5 -6
  176. package/dist/elysia/index.d.ts +6 -8
  177. package/dist/elysia/index.js +6 -7
  178. package/dist/env-hbYumkRp.js +7 -0
  179. package/dist/errors-DOSkVeTC.js +127 -0
  180. package/dist/errors-DUJ7wLlE.d.ts +137 -0
  181. package/dist/errors-Da88YLm5.js +26 -0
  182. package/dist/errors-DgLOqc6j.js +148 -0
  183. package/dist/errors-KngVdJT9.d.ts +12 -0
  184. package/dist/evaluate-D8SdfP3h.js +1948 -0
  185. package/dist/evaluations-BQkpE7hC.js +609 -0
  186. package/dist/evaluations-K9qglDP7.d.ts +36 -0
  187. package/dist/evaluator-Dlhn2d7D.js +2 -0
  188. package/dist/evaluator-eager-UuJK6NX_.js +8 -0
  189. package/dist/eve/index.d.ts +11 -10
  190. package/dist/eve/index.js +7 -8
  191. package/dist/event-time-ChIrhzy5.js +26 -0
  192. package/dist/execute-CyQLisIB.js +166 -0
  193. package/dist/express/index.d.ts +6 -8
  194. package/dist/express/index.js +6 -7
  195. package/dist/fastify/index.d.ts +5 -11
  196. package/dist/fastify/index.js +6 -8
  197. package/dist/fetch-adapter-gmTCu4FR.d.ts +32 -0
  198. package/dist/fetch-adapter-ovZdSvlT.js +124 -0
  199. package/dist/fields-6d1j-q3c.js +502 -0
  200. package/dist/fields-C0L2FoZk.js +25 -0
  201. package/dist/files-DAR51W3J.js +157 -0
  202. package/dist/files-DuV7wRim.js +139 -0
  203. package/dist/fixtures-Bm0G0A7H.js +79 -0
  204. package/dist/flags-C0e-BzGW.js +112 -0
  205. package/dist/freeze-DGfJq_j2.js +86 -0
  206. package/dist/from-snapshot-CCDF_ihX.js +173 -0
  207. package/dist/gen-CJE3Xud5.js +1168 -0
  208. package/dist/gen-WzJbAcMJ.js +1 -0
  209. package/dist/gen-kind-DFQnQwFN.d.ts +13 -0
  210. package/dist/gen-kind-DGQxmID0.js +69 -0
  211. package/dist/generate-5_kz2309.js +305 -0
  212. package/dist/generate-DF6Y8ncI.js +67 -0
  213. package/dist/generate-DIZNzMuk.js +2339 -0
  214. package/dist/generate-DhP0jQDR.js +97 -0
  215. package/dist/generate-options-CLPUvgVW.js +1185 -0
  216. package/dist/grantee-BPUG6f0r.js +109 -0
  217. package/dist/grantee-conditions-Dob6QQAc.js +270 -0
  218. package/dist/grantee-match-CFQ-LRcL.js +147 -0
  219. package/dist/grants-BzjbUCdR.js +139 -0
  220. package/dist/graph-sql-Ds3nbevr.d.ts +27 -0
  221. package/dist/h3/index.d.ts +4 -6
  222. package/dist/h3/index.js +4 -5
  223. package/dist/headers-D1oRr-js.d.ts +8 -0
  224. package/dist/helpers-DSmj6SHi.js +533 -0
  225. package/dist/hono/index.d.ts +6 -8
  226. package/dist/hono/index.js +7 -8
  227. package/dist/hook-sql-FSets5NB.js +3412 -0
  228. package/dist/hosted-DMJKJPoc.js +361 -0
  229. package/dist/hosted-DUbuh0Td.d.ts +100 -0
  230. package/dist/http-BUIYu1Kc.d.ts +10 -0
  231. package/dist/http-BbX_Ou3_.js +48 -0
  232. package/dist/http-C9jDw_bZ.js +82 -0
  233. package/dist/http-dNltTpC8.js +71 -0
  234. package/dist/ids-0QDIxtxL.js +53 -0
  235. package/dist/import-BqoDHpFt.js +1158 -0
  236. package/dist/import-DemSCI1R.js +318 -0
  237. package/dist/index-BXz-XXC3.d.ts +1108 -0
  238. package/dist/index-CVuc3E1O.d.ts +196 -0
  239. package/dist/index-Cq9N5B92.d.ts +506 -0
  240. package/dist/index-D8A1d_Tt.d.ts +214 -0
  241. package/dist/index-DegTwZxD.d.ts +93 -0
  242. package/dist/index-O0qbI8Ha.d.ts +221 -0
  243. package/dist/index.d.ts +24 -25
  244. package/dist/index.js +47 -46
  245. package/dist/init-BlYRZRnQ.js +94 -0
  246. package/dist/init-CgoOwXtk.js +95 -0
  247. package/dist/instance-options-B4MD2wgl.d.ts +9 -0
  248. package/dist/instance-options-CLErhA76.js +23 -0
  249. package/dist/instance-snapshot-DdGOpSfN.js +716 -0
  250. package/dist/instant-Ih5riY_A.js +18 -0
  251. package/dist/interactive-only-BZu9rLpa.js +1567 -0
  252. package/dist/internals-D58TnmDB.js +19 -0
  253. package/dist/json-schema-SDkWXxhu.d.ts +38 -0
  254. package/dist/json-schema-jtX26ydD.js +148 -0
  255. package/dist/jwt/index.d.ts +6 -24
  256. package/dist/jwt/index.js +18 -26
  257. package/dist/kernel-Dn6pKMAF.js +423 -0
  258. package/dist/kysely/index.d.ts +5 -9
  259. package/dist/kysely/index.js +5 -6
  260. package/dist/lazy-provider-CydlnKkS.d.ts +4 -0
  261. package/dist/lazy-provider-DG5rMeqL.js +28 -0
  262. package/dist/limits-DpTxX6N4.js +166 -0
  263. package/dist/live-options-CIUmc-YQ.js +70 -0
  264. package/dist/load-BPzIqlGB.js +1 -0
  265. package/dist/load-CZnlAyZ8.js +98 -0
  266. package/dist/load-jose-CjzIBSKI.js +7 -0
  267. package/dist/login-CNQJN8Fy.js +67 -0
  268. package/dist/login-TwrSjf6k.js +255 -0
  269. package/dist/lru-Cp-AEvpR.js +27 -0
  270. package/dist/manifest-B-8d2lhG.js +45 -0
  271. package/dist/manifest-CRHphHxo.d.ts +362 -0
  272. package/dist/manifest-XIXxXYty.js +399 -0
  273. package/dist/manifest-json-DMaBWmcG.js +8 -0
  274. package/dist/manifest-schema-DJY5Q_pR.js +507 -0
  275. package/dist/map-claims-BKdnPwep.js +386 -0
  276. package/dist/map-error-DTi_JZT8.js +22 -0
  277. package/dist/markers-C-kThnKN.js +79 -0
  278. package/dist/may-use-Died1tNU.js +233 -0
  279. package/dist/mcp/index.d.ts +11 -21
  280. package/dist/mcp/index.js +56 -43
  281. package/dist/membership-filter-CSKH48eD.js +66 -0
  282. package/dist/migrate-CmTMk7rd.js +536 -0
  283. package/dist/model-B4EKVHMK.js +188 -0
  284. package/dist/module-values-Ddx0GLaJ.js +106 -0
  285. package/dist/nest/index.d.ts +7 -13
  286. package/dist/nest/index.js +12 -15
  287. package/dist/next/client.d.ts +1 -3
  288. package/dist/next/client.js +2 -3
  289. package/dist/next/index.d.ts +36 -16
  290. package/dist/next/index.js +161 -31
  291. package/dist/next/plugin.d.ts +1 -3
  292. package/dist/next/plugin.js +3 -4
  293. package/dist/node/index.d.ts +6 -8
  294. package/dist/node/index.js +4 -5
  295. package/dist/oauth-security-C8fjzFRF.js +25 -0
  296. package/dist/ocsf-DKRQc6uv.js +135 -0
  297. package/dist/openai/index.d.ts +5 -7
  298. package/dist/openai/index.js +5 -6
  299. package/dist/openapi/index.d.ts +4 -16
  300. package/dist/openapi/index.js +4 -3
  301. package/dist/openapi-CH9Dh5UX.js +260 -0
  302. package/dist/openapi-CrCBEFEm.js +95 -0
  303. package/dist/openapi-D2dmyWZK.js +411 -0
  304. package/dist/openapi-document-CJO6cUS1.js +35 -0
  305. package/dist/operation-findings-D5Uo-dcm.js +35 -0
  306. package/dist/operation-risks-BD-j14dj.js +12 -0
  307. package/dist/operations-B0yO77Zz.js +290 -0
  308. package/dist/operations-BS8ExH5A.d.ts +58 -0
  309. package/dist/operations-De3F7tlf.js +88 -0
  310. package/dist/optional-CaQWp9HA.js +46 -0
  311. package/dist/orpc/index.d.ts +8 -12
  312. package/dist/orpc/index.js +10 -12
  313. package/dist/otel/index.d.ts +3 -5
  314. package/dist/otel/index.js +5 -7
  315. package/dist/output-CU7OppLv.js +244 -0
  316. package/dist/output-files-C5LFnQa4.js +1 -0
  317. package/dist/output-files-DNid6TBl.js +197 -0
  318. package/dist/ownership-BBQe7GZp.js +558 -0
  319. package/dist/parse-local-manifest-BGLWVchi.d.ts +8 -0
  320. package/dist/parse-local-manifest-CfMjZAFi.js +67 -0
  321. package/dist/parse-nfHSt1Wy.js +149 -0
  322. package/dist/parse-request-IEEzVFM8.js +24 -0
  323. package/dist/parse-sink-events-B6nZx41L.js +125 -0
  324. package/dist/paths-CeS_gpHf.js +44 -0
  325. package/dist/pdp/index.d.ts +3 -9
  326. package/dist/pdp/index.js +22 -18
  327. package/dist/peer-BWTpSLs2.js +1 -0
  328. package/dist/peer-D77JpXe-.js +978 -0
  329. package/dist/perf-token-dFGVP14-.js +155 -0
  330. package/dist/permdock-BueSeg7X.js +1514 -0
  331. package/dist/permdock-Dz3yzWrp.d.ts +853 -0
  332. package/dist/permission-registry-DMYRZVcn.js +413 -0
  333. package/dist/permissions-CQW3cr2S.js +17 -0
  334. package/dist/permissions-DWULToSb.d.ts +52 -0
  335. package/dist/permissions-ijDw4sO1.js +144 -0
  336. package/dist/pg-CA651850.js +59 -0
  337. package/dist/pins-CXXkVEiD.js +14 -0
  338. package/dist/pipeline-CXuwijr2.js +307 -0
  339. package/dist/pkce-DdsRBK7n.js +20 -0
  340. package/dist/plugin-1XW5OfAZ.d.ts +221 -0
  341. package/dist/plugin-MQVfUBUS.js +93 -0
  342. package/dist/plugin-outputs-BE2YCiMj.js +28 -0
  343. package/dist/policy-C-Lzp3Zh.d.ts +18 -0
  344. package/dist/policy-DFD2J5o_.js +476 -0
  345. package/dist/policy-FrCL4wDQ.js +37 -0
  346. package/dist/policy-bundle-1Znzdxse.js +82 -0
  347. package/dist/policy-from-catalog-YKaTeaco.js +452 -0
  348. package/dist/policy-module-Bp4HvsRg.js +107 -0
  349. package/dist/policy-types-93NwI8iI.d.ts +2855 -0
  350. package/dist/postgres-store-CYFvw98w.js +1023 -0
  351. package/dist/postgrest-DyrYo_XT.d.ts +138 -0
  352. package/dist/powersync-DVgkPQKM.js +1 -0
  353. package/dist/powersync-Y-_z8V5X.js +40 -0
  354. package/dist/powersync-pbvC5g6K.js +1630 -0
  355. package/dist/preset/index.d.ts +0 -12
  356. package/dist/preset/index.js +1 -1
  357. package/dist/preset-BcFDaeqd.js +1849 -0
  358. package/dist/principal-source-BIcukkB3.js +102 -0
  359. package/dist/prisma/index.d.ts +4 -12
  360. package/dist/prisma/index.js +10 -14
  361. package/dist/problem-BZB7zPC7.js +202 -0
  362. package/dist/problem-details-EJHcvYCz.js +154 -0
  363. package/dist/problem-types-81BEw0IN.js +7 -0
  364. package/dist/prompt-CSXHcJxy.js +931 -0
  365. package/dist/protected-action-BMb0ftEu.js +241 -0
  366. package/dist/protected-action-D6T3eJyW.d.ts +73 -0
  367. package/dist/protected-action-DiXulRVj.js +78 -0
  368. package/dist/provider-BnnFjtWI.js +893 -0
  369. package/dist/provider-ClD4rfgT.js +11 -0
  370. package/dist/provider-CydlnKkS.d.ts +4 -0
  371. package/dist/provider-store-atQUfsVO.js +51 -0
  372. package/dist/provider-with-CSw4mBDU.js +70 -0
  373. package/dist/public-api-DIMZmzWi.js +5579 -0
  374. package/dist/pull-C3_fCkgX.js +1 -0
  375. package/dist/pull-CpLyeY2p.js +252 -0
  376. package/dist/push-Cb7PqXdO.js +158 -0
  377. package/dist/pushed-policy-pH-EFWyx.d.ts +61 -0
  378. package/dist/pushed-policy-rpB6k77P.js +240 -0
  379. package/dist/quote-BKrTBbcH.js +36 -0
  380. package/dist/rbac-B-49toAp.js +90 -0
  381. package/dist/react/index.d.ts +10 -9
  382. package/dist/react/index.js +8 -7
  383. package/dist/react/lazy.d.ts +10 -12
  384. package/dist/react/lazy.js +8 -35
  385. package/dist/react/provider-client-lazy.d.ts +2 -0
  386. package/dist/react/provider-client-lazy.js +2 -0
  387. package/dist/react/provider-client.d.ts +1 -1
  388. package/dist/react/provider-client.js +1 -1
  389. package/dist/react-native/index.d.ts +12 -30
  390. package/dist/react-native/index.js +31 -41
  391. package/dist/read-memberships-BkePIa1F.js +63 -0
  392. package/dist/refresh-on-C1zIMtJr.d.ts +47 -0
  393. package/dist/refresh-online-CYGZNo6V.js +19 -0
  394. package/dist/refresh-online-vtUfV6dk.d.ts +10 -0
  395. package/dist/refs-Cix9Zjis.js +103 -0
  396. package/dist/relation-walk-BlWy9gBK.js +188 -0
  397. package/dist/relations-CIgB5KPJ.js +162 -0
  398. package/dist/replay-ClGIMp5p.d.ts +3 -0
  399. package/dist/replay-X2m6moK1.js +28 -0
  400. package/dist/request-context-CVJodWx8.js +70 -0
  401. package/dist/request-context-E3-ps-H_.d.ts +3 -0
  402. package/dist/request-schema-DzEoR310.js +155 -0
  403. package/dist/resend/index.d.ts +4 -10
  404. package/dist/resend/index.js +14 -17
  405. package/dist/resolve-names-Ca4ClMU2.js +266 -0
  406. package/dist/resolver-kdZ4HrpC.js +404 -0
  407. package/dist/resource-ref-BiQtFK-I.js +19 -0
  408. package/dist/resource-relations-Ck5sjYQR.js +251 -0
  409. package/dist/retire-BNiXnbBR.js +248 -0
  410. package/dist/revocations-3jyzniOz.js +26 -0
  411. package/dist/revocations-ku_f2d2y.d.ts +24 -0
  412. package/dist/rls-CmyxiQsS.js +321 -0
  413. package/dist/rls-DY5ITGzf.js +946 -0
  414. package/dist/rls-files-BtaUXVp-.js +114 -0
  415. package/dist/rls-options-CEpg5nDP.d.ts +26 -0
  416. package/dist/role-builder-DhsGEVq-.js +501 -0
  417. package/dist/role-grants-Bk6ZsaS0.js +46 -0
  418. package/dist/roles-B29psCem.js +29 -0
  419. package/dist/rolldown-runtime-B8NLbhFH.js +3 -0
  420. package/dist/row-conditions-DwIJocfQ.js +27 -0
  421. package/dist/row-pair-CxEhErJU.js +33 -0
  422. package/dist/rpc-B-4IZOiU.js +111 -0
  423. package/dist/rpc-DjgxFbjK.d.ts +18 -0
  424. package/dist/run-BoVUFspr.js +726 -0
  425. package/dist/run-BriRChKE.js +1 -0
  426. package/dist/run-ticket-D6T39Xdi.js +370 -0
  427. package/dist/run-ticket-DXwrko2J.d.ts +157 -0
  428. package/dist/runtime-Cl6xSbEq.js +13 -0
  429. package/dist/saas-DzjKUQr5.js +1218 -0
  430. package/dist/scan-C4x8UqS7.js +28 -0
  431. package/dist/schema-BeY3croo.js +403 -0
  432. package/dist/schema-Zfpbku8U.js +133 -0
  433. package/dist/scim/index.d.ts +2 -2
  434. package/dist/scim/index.js +2 -2
  435. package/dist/scim-B9QyJ23q.js +1046 -0
  436. package/dist/scopes-B-KX9EI8.js +238 -0
  437. package/dist/seed-sql-CjF7u0aX.js +60 -0
  438. package/dist/seeds/index.d.ts +2 -0
  439. package/dist/seeds/index.js +1 -0
  440. package/dist/seeds-BDTG7xl-.js +53 -0
  441. package/dist/seeds-uG196Ev4.d.ts +73 -0
  442. package/dist/server/index.d.ts +13 -13
  443. package/dist/server/index.js +14 -14
  444. package/dist/server-Co9CYGqk.js +146 -0
  445. package/dist/server-types-BrHOGAYx.d.ts +318 -0
  446. package/dist/sha256-DFsnyVPo.js +157 -0
  447. package/dist/shared-BOsJIQf4.js +124 -0
  448. package/dist/shared-BdF5DJDQ.js +330 -0
  449. package/dist/signals-a1NxAP0X.js +31 -0
  450. package/dist/sink-BD34OS8T.d.ts +247 -0
  451. package/dist/sink-Bgvf9lIz.js +966 -0
  452. package/dist/size-DF7xQ-nH.js +95 -0
  453. package/dist/skills-B0cLRZ7w.js +202 -0
  454. package/dist/skills-DiGdMvMw.js +50 -0
  455. package/dist/snapshot-DckMnHk8.js +352 -0
  456. package/dist/snapshot-cache-DTTEfmxv.js +69 -0
  457. package/dist/snapshot-cache-DoP3avLl.d.ts +68 -0
  458. package/dist/snapshot-compact-CwAop_6C.js +119 -0
  459. package/dist/snapshot-empty-DZ6sZ83n.js +17 -0
  460. package/dist/snapshot-evaluate-9RGy7J3N.js +552 -0
  461. package/dist/snapshot-reads-D775amTL.js +65 -0
  462. package/dist/snapshot-size-D-pCR8x0.js +139 -0
  463. package/dist/snapshot-size-DU7CvpMt.js +1 -0
  464. package/dist/solid/index.d.ts +18 -20
  465. package/dist/solid/index.js +15 -19
  466. package/dist/solid-start/index.d.ts +6 -8
  467. package/dist/solid-start/index.js +4 -5
  468. package/dist/sources-BbSUNmFX.js +10 -0
  469. package/dist/sources-DnjJPGfb.js +657 -0
  470. package/dist/sources-NQio1yFq.d.ts +727 -0
  471. package/dist/sql-BYYNi1lu.d.ts +8 -0
  472. package/dist/sql-T4GaBh9X.js +93 -0
  473. package/dist/src-D6_T4zd7.js +1811 -0
  474. package/dist/ssf/index.d.ts +3 -3
  475. package/dist/ssf/index.js +20 -31
  476. package/dist/standard-webhooks-B3MQihcP.d.ts +86 -0
  477. package/dist/standard-webhooks-BtIkXclH.js +227 -0
  478. package/dist/storage-BhGDhsXm.js +131 -0
  479. package/dist/store-AH8bmaxW.js +377 -0
  480. package/dist/store-core-eqG8jijs.d.ts +306 -0
  481. package/dist/store-options-C8x39AHa.js +1034 -0
  482. package/dist/stores-4DOaL4ZP.d.ts +58 -0
  483. package/dist/stores-DoA7ACkz.js +127 -0
  484. package/dist/stream-DdF94h7T.js +73 -0
  485. package/dist/style-CQDaLJtP.js +24 -0
  486. package/dist/style-Crf-90o6.js +1 -0
  487. package/dist/subject-DkxY-AhF.js +23 -0
  488. package/dist/subject-cache-BZeSj4Xf.d.ts +156 -0
  489. package/dist/subject-settings-BO-frcYx.js +147 -0
  490. package/dist/subject-settings-C9F1sU1d.d.ts +48 -0
  491. package/dist/supabase/client.d.ts +1 -1
  492. package/dist/supabase/client.js +2 -3
  493. package/dist/supabase/index.d.ts +77 -24
  494. package/dist/supabase/index.js +9 -8
  495. package/dist/supabase/middleware.d.ts +27 -9
  496. package/dist/supabase/middleware.js +51 -21
  497. package/dist/supabase-B7Q5bO-P.js +30 -0
  498. package/dist/supabase-BI5ZhzLl.js +792 -0
  499. package/dist/supabase-config-mXcggV5I.js +890 -0
  500. package/dist/supabase-hook-C7FNwQ1p.js +2 -0
  501. package/dist/supabase-hook-loL2iJVb.js +405 -0
  502. package/dist/supabase-outcome-CMLuLW-V.js +9 -0
  503. package/dist/supautils-DXzJ2E2Q.js +96 -0
  504. package/dist/support-session-B8xrW28B.js +157 -0
  505. package/dist/svelte/index.d.ts +8 -10
  506. package/dist/svelte/index.js +12 -15
  507. package/dist/svelte/runtime.d.ts +4 -6
  508. package/dist/svelte/runtime.js +4 -4
  509. package/dist/svelte/source.d.ts +8 -10
  510. package/dist/svelte/source.js +6 -7
  511. package/dist/sveltekit/index.d.ts +6 -8
  512. package/dist/sveltekit/index.js +3 -4
  513. package/dist/tables-C8IwkTHq.js +3249 -0
  514. package/dist/tanstack-start/index.d.ts +6 -8
  515. package/dist/tanstack-start/index.js +3 -4
  516. package/dist/target-BGpxgKsN.js +50 -0
  517. package/dist/tenancy-B5Xxt9Sc.js +223 -0
  518. package/dist/terminal/index.d.ts +6 -16
  519. package/dist/terminal/index.js +18 -23
  520. package/dist/testing/core.d.ts +1 -1
  521. package/dist/testing/core.js +1 -1
  522. package/dist/testing/fixtures/index.d.ts +12 -10
  523. package/dist/testing/fixtures/index.js +48 -25
  524. package/dist/testing/index.d.ts +85 -85
  525. package/dist/testing/index.js +226 -115
  526. package/dist/testing/saas/index.d.ts +5 -15
  527. package/dist/testing/saas/index.js +2 -2
  528. package/dist/testing/saas/permissions.d.ts +1 -1
  529. package/dist/testing/saas/permissions.js +1 -1
  530. package/dist/text-D704xHVl.js +7 -0
  531. package/dist/text-diff-CsglY49A.js +440 -0
  532. package/dist/thenable-BxMy2v8w.js +39 -0
  533. package/dist/time-r0CKBm57.js +94 -0
  534. package/dist/timeout-nOqLpU2I.js +7 -0
  535. package/dist/token-BgswTQzt.d.ts +9 -0
  536. package/dist/token-CSljQqzA.js +76 -0
  537. package/dist/tool-refusal-DzCSbjp8.js +43 -0
  538. package/dist/trpc/index.d.ts +7 -9
  539. package/dist/trpc/index.js +7 -8
  540. package/dist/type-helpers-DHCQEPj8.d.ts +47 -0
  541. package/dist/types-3pRMqcvw.d.ts +84 -0
  542. package/dist/types-BFtFaI1W.d.ts +66 -0
  543. package/dist/types-BdNdMix7.d.ts +263 -0
  544. package/dist/types-C7QtRn3n.d.ts +66 -0
  545. package/dist/types-CVCRFYY_.d.ts +102 -0
  546. package/dist/types-CWmBZtQN.d.ts +274 -0
  547. package/dist/types-Cakw89Wx.d.ts +372 -0
  548. package/dist/types-D3tjoLwT.d.ts +124 -0
  549. package/dist/types-DFZKovb3.js +77 -0
  550. package/dist/types-DONLJQjY.d.ts +134 -0
  551. package/dist/types-OzSal_K_.d.ts +178 -0
  552. package/dist/types-XSfi6ihL.d.ts +65 -0
  553. package/dist/types-nXo_oQYk.d.ts +1235 -0
  554. package/dist/unplugin/index.d.ts +1 -3
  555. package/dist/unplugin/index.js +3 -4
  556. package/dist/usage-BgNAgZfj.js +31 -0
  557. package/dist/usage-D6HUlfvP.js +1 -0
  558. package/dist/usage-llSQehNg.js +761 -0
  559. package/dist/validation-error-BAO1W1yk.d.ts +27 -0
  560. package/dist/validation-error-CgDOA6VS.js +35 -0
  561. package/dist/validity-YNEEm2MZ.js +56 -0
  562. package/dist/verifier-BIYkGcJc.js +530 -0
  563. package/dist/verify-nMTdEqBB.js +1102 -0
  564. package/dist/version-CU6e2wxV.js +7 -0
  565. package/dist/version-D-jWyJb9.js +46 -0
  566. package/dist/version-DcZCjWXb.js +1 -0
  567. package/dist/version-cache-BXkl7-Fz.js +462 -0
  568. package/dist/views-Dpr1uB16.js +164 -0
  569. package/dist/vocabulary-CE2k7s1a.js +157 -0
  570. package/dist/vocabulary-FYgI_NoI.d.ts +400 -0
  571. package/dist/vue/index.d.ts +18 -20
  572. package/dist/vue/index.js +13 -18
  573. package/dist/waiter-DKdFHKVZ.js +66 -0
  574. package/dist/waiter-hYLJXA7r.d.ts +37 -0
  575. package/dist/watch-BecZtEdU.js +155 -0
  576. package/dist/watch-CiN6WU9k.js +221 -0
  577. package/dist/watch-NAUnUXph.js +1 -0
  578. package/dist/webmcp/index.d.ts +2 -6
  579. package/dist/webmcp/index.js +8 -9
  580. package/dist/who-can-rUSZfLvI.js +366 -0
  581. package/dist/wire-delegation-DC5Cyec4.js +35 -0
  582. package/dist/wire-denial-BcRQnA7p.js +26 -0
  583. package/dist/workflow/index.d.ts +3 -3
  584. package/dist/workflow/index.js +12 -14
  585. package/dist/workflow-sdk/index.d.ts +6 -8
  586. package/dist/workflow-sdk/index.js +2 -3
  587. package/dist/wrap-CsfsaJhd.js +32 -0
  588. package/dist/wrap-D-KvhzaC.d.ts +16 -0
  589. package/package.json +83 -39
  590. package/schemas/catalog-v2.json +665 -0
  591. package/schemas/cli-commands-v1.json +1 -1
  592. package/schemas/cli-result-v2.json +163 -0
  593. package/schemas/cloud-api-v1.json +1 -1
  594. package/schemas/snapshot-v1.json +26 -0
  595. package/schemas/supabase-claims-v1.json +5 -1
  596. package/schemas/supabase-manifest-v1.json +11 -2
  597. package/skills/permdock/SKILL.md +1 -1
  598. package/skills/permdock-data/references/queries-and-rls.md +2 -1
  599. package/skills/permdock-wire/references/adapters.md +5 -3
  600. package/dist/2020-CJbO8Bvz.js +0 -6773
  601. package/dist/active-tenant-DVee32-T.js +0 -39
  602. package/dist/adapter-context-OHikyRqV.js +0 -29
  603. package/dist/adoption-scan-8F9VSQrK.js +0 -107
  604. package/dist/app-J9PE1LNm.js +0 -24
  605. package/dist/app-data-UNNm07jV.js +0 -63
  606. package/dist/approval-header-8QV6MU4H.js +0 -26
  607. package/dist/approval-normalize-KfhzpD93.js +0 -196
  608. package/dist/approval-policies-BiXMlYBu.d.ts +0 -138
  609. package/dist/approval-prompt-B8hQY69x.js +0 -61
  610. package/dist/approval-prompt-j5PTItiy.d.ts +0 -59
  611. package/dist/approval-required-TzNB9oQA.js +0 -6
  612. package/dist/approvals-BfzI8Foe.js +0 -1048
  613. package/dist/approvers-BaNwKYgd.js +0 -77
  614. package/dist/arazzo-BUVqRmaJ.js +0 -36
  615. package/dist/arazzo-CWmM8pWw.js +0 -77
  616. package/dist/args-iafbHiXn.js +0 -311
  617. package/dist/audience-DLoopY4q.js +0 -55
  618. package/dist/auth-BxXHxWRy.js +0 -189
  619. package/dist/authz-topic-Dbc-HDOS.js +0 -15
  620. package/dist/automation-BueW05db.js +0 -158
  621. package/dist/automation-_iGeP54L.d.ts +0 -124
  622. package/dist/base-url-BQbddZO5.js +0 -9
  623. package/dist/better-supabase-DF8f8oly.js +0 -194
  624. package/dist/bind-CTj4dHc1.d.ts +0 -58
  625. package/dist/bind-LQ6zbARV.js +0 -125
  626. package/dist/body-Cy9S8zhw.js +0 -10
  627. package/dist/body-text-DQhcmqdY.js +0 -56
  628. package/dist/boundary-BV3O1eud.js +0 -19
  629. package/dist/boundary-C9ck-3uK.d.ts +0 -24
  630. package/dist/budget-BBCPDOGP.js +0 -14
  631. package/dist/budget-CNLsV2SL.d.ts +0 -14
  632. package/dist/build-instance-Bq8wkJ4i.js +0 -31
  633. package/dist/canonical-json-DwilZ1iB.js +0 -29
  634. package/dist/capability-CenWwTMR.js +0 -205
  635. package/dist/capability-DqCyFGip.d.ts +0 -130
  636. package/dist/casbin-DIvUMac7.js +0 -242
  637. package/dist/casbin-qpG_ZphP.js +0 -30
  638. package/dist/casl-CjBVJj8R.js +0 -24
  639. package/dist/casl-CkBssiB1.js +0 -308
  640. package/dist/catalog-B1MAmRQI.js +0 -131
  641. package/dist/catalog-BCVIH7kq.js +0 -1
  642. package/dist/catalog-CaZoXBD8.js +0 -52
  643. package/dist/catalog-doc-DnQDviXY.js +0 -353
  644. package/dist/catalog-fingerprint-e6aCWosn.js +0 -157
  645. package/dist/catalog-operations-Do1eD-Rt.js +0 -60
  646. package/dist/catalog-path-CnI0XTFK.js +0 -12
  647. package/dist/challenge-DKJpP-5P.js +0 -521
  648. package/dist/checks-fyDOhcz0.js +0 -72
  649. package/dist/claims-map-CKkoAAYF.js +0 -16
  650. package/dist/claims-map-D1Pb5oRq.d.ts +0 -35
  651. package/dist/client-JK504UCq.d.ts +0 -45
  652. package/dist/clients-C_NOET3z.d.ts +0 -12
  653. package/dist/clients-DYr3U86j.js +0 -23
  654. package/dist/cloud-CXgE1qpa.js +0 -86
  655. package/dist/codemod-BJ0Kgv9b.js +0 -36
  656. package/dist/codemod-DjgVx3RQ.js +0 -2800
  657. package/dist/collect-BG-SXFQv.js +0 -537
  658. package/dist/collect-CxPJRjoc.js +0 -55
  659. package/dist/collect-ZLgHgujd.js +0 -1
  660. package/dist/command-L8EstFNm.js +0 -6
  661. package/dist/compact-CAf557ZB.js +0 -29
  662. package/dist/compare-DTfyUunF.js +0 -12
  663. package/dist/compile-Cvru58id.js +0 -661
  664. package/dist/compile-Dh9pW_Co.d.ts +0 -120
  665. package/dist/completion-DUHSRdoQ.js +0 -152
  666. package/dist/config-CgA_Z5Ts.js +0 -26
  667. package/dist/config-DC7aiuhP.js +0 -116
  668. package/dist/config-report-B31MnuKf.js +0 -56
  669. package/dist/config-shape-ChhsuGSV.js +0 -147
  670. package/dist/connection-zoAgwdsD.js +0 -197
  671. package/dist/connector-schema-CYLQNMYq.js +0 -434
  672. package/dist/constants-DcJABbLW.js +0 -20
  673. package/dist/context-BXM0MDB0.js +0 -95
  674. package/dist/core-BTJlqWsv.js +0 -341
  675. package/dist/core-BhZEo5Le.d.ts +0 -206
  676. package/dist/coverage-BuGlwUms.d.ts +0 -135
  677. package/dist/coverage-CGu_Kovx.js +0 -261
  678. package/dist/create--q7-j0hX.d.ts +0 -127
  679. package/dist/create-C5IQw_-i.d.ts +0 -191
  680. package/dist/create-CYj0cjTu.d.ts +0 -128
  681. package/dist/create-D7D94oNh.js +0 -376
  682. package/dist/create-DaddhCIg.js +0 -134
  683. package/dist/credential-BMsbcaeP.js +0 -431
  684. package/dist/credentials-BZU7Twpt.js +0 -310
  685. package/dist/credentials-Bq-Xa7Vq.d.ts +0 -125
  686. package/dist/credentials-dkycUsY3.js +0 -74
  687. package/dist/decide-set-DXEPepY1.js +0 -100
  688. package/dist/deciding-columns-NB4wcyBf.js +0 -134
  689. package/dist/decision-CaG5_eNJ.js +0 -21
  690. package/dist/delegation-CrdqnesZ.js +0 -262
  691. package/dist/delegation-input-DcXhiMkf.js +0 -19
  692. package/dist/delivery-BupfvJIV.js +0 -560
  693. package/dist/delivery-event-JioK5YbS.js +0 -40
  694. package/dist/denied-text-B6s29jcf.d.ts +0 -22
  695. package/dist/describe-BZAlPHxT.js +0 -101
  696. package/dist/describe-DwcoWMLB.d.ts +0 -45
  697. package/dist/device-BkSynWdg.js +0 -196
  698. package/dist/diff-BnYHpRSI.js +0 -466
  699. package/dist/diff-H75YU6Q-.js +0 -37
  700. package/dist/digest-8Yx2CchM.d.ts +0 -19
  701. package/dist/digest-BI-6aa6d.js +0 -27
  702. package/dist/doctor-Dvt1_ROJ.js +0 -3560
  703. package/dist/doctor-JLouRSQt.js +0 -54
  704. package/dist/env-DJZrPjRi.js +0 -8
  705. package/dist/errors-BDUwg2qC.js +0 -27
  706. package/dist/errors-BhRkoNS7.js +0 -145
  707. package/dist/errors-CHwoRRpB.d.ts +0 -14
  708. package/dist/errors-D_SnqcRn.d.ts +0 -141
  709. package/dist/errors-ynga1EQy.js +0 -128
  710. package/dist/evaluate-BQ2nWOki.js +0 -1905
  711. package/dist/evaluations-BVtY66lF.d.ts +0 -38
  712. package/dist/evaluations-Bj5xw0EM.js +0 -612
  713. package/dist/evaluator-CDl2YUd_.js +0 -2
  714. package/dist/evaluator-eager-CULtQ8t6.js +0 -9
  715. package/dist/event-time-BGy48400.js +0 -27
  716. package/dist/fetch-adapter-BJ76IZZg.d.ts +0 -34
  717. package/dist/fetch-adapter-CXeBg4CH.js +0 -124
  718. package/dist/fields-D9PIYlJy.js +0 -504
  719. package/dist/fields-DlKwZYiy.js +0 -26
  720. package/dist/files-BSjrtIHw.js +0 -141
  721. package/dist/files-CfiRtQ-m.js +0 -140
  722. package/dist/fixtures-BVZc7OCF.js +0 -80
  723. package/dist/flags-BlmpmXoY.js +0 -86
  724. package/dist/freeze-jjan0lCv.js +0 -63
  725. package/dist/from-snapshot-FdVXG_QZ.js +0 -159
  726. package/dist/gen-D17P8vo0.js +0 -827
  727. package/dist/gen-YA3SK59O.js +0 -58
  728. package/dist/generate-BqkZq8Dr.js +0 -165
  729. package/dist/generate-CezbCaTI.js +0 -275
  730. package/dist/grantee-OG4klcNr.js +0 -110
  731. package/dist/grantee-conditions-Dzprappv.js +0 -271
  732. package/dist/grantee-match-CPQ9zV-H.js +0 -148
  733. package/dist/graph-sql-BwFC4Qjs.d.ts +0 -29
  734. package/dist/headers-B9jQxjtW.d.ts +0 -10
  735. package/dist/helpers-CO2hDpBU.js +0 -537
  736. package/dist/hosted-CQW_YNx7.js +0 -362
  737. package/dist/hosted-D5StFpKa.d.ts +0 -102
  738. package/dist/http-B_LphE5Y.d.ts +0 -12
  739. package/dist/http-DH94eh6f.js +0 -72
  740. package/dist/http-DKLXrFGk.js +0 -83
  741. package/dist/http-dptLQzPP.js +0 -49
  742. package/dist/ids-DzhJaCUj.js +0 -55
  743. package/dist/import-B8zbuskR.js +0 -5950
  744. package/dist/import-BYYXmHvP.js +0 -1143
  745. package/dist/index-B1-tE0Kx.d.ts +0 -1159
  746. package/dist/index-BwSEp_O5.d.ts +0 -210
  747. package/dist/index-CB_eM-qx.d.ts +0 -101
  748. package/dist/index-CvcE9mYP.d.ts +0 -234
  749. package/dist/index-D7sMtTf6.d.ts +0 -542
  750. package/dist/index-d7f0hNss.d.ts +0 -233
  751. package/dist/init-BdgWNuc3.js +0 -96
  752. package/dist/init-DKRhYiGW.js +0 -95
  753. package/dist/instance-options-DhQVCuhT.d.ts +0 -11
  754. package/dist/instance-options-URVwqpMW.js +0 -24
  755. package/dist/instance-snapshot-DyG_5ASl.js +0 -693
  756. package/dist/instant-DK3Iz83e.js +0 -19
  757. package/dist/internals-B3IgHrvo.js +0 -20
  758. package/dist/json-schema-BPGa-RjQ.js +0 -149
  759. package/dist/json-schema-BfXgnRNT.d.ts +0 -40
  760. package/dist/kernel-D9AxUqmz.js +0 -427
  761. package/dist/limits-CAhpRrhk.js +0 -167
  762. package/dist/live-options-BBIT68le.js +0 -73
  763. package/dist/load-C4p4VgwR.js +0 -99
  764. package/dist/load-DiBUJx77.js +0 -1
  765. package/dist/load-jose-DZ4dnjri.js +0 -8
  766. package/dist/login-DEvccJwP.js +0 -68
  767. package/dist/login-IIUDSAYW.js +0 -257
  768. package/dist/lru-8q4WZjBV.js +0 -28
  769. package/dist/manifest-BoCYBbQL.js +0 -46
  770. package/dist/manifest-C6eFl3Vo.d.ts +0 -349
  771. package/dist/manifest-CZ-GmsOL.js +0 -401
  772. package/dist/manifest-json-CAGzls-C.js +0 -9
  773. package/dist/manifest-schema-svAkgqMc.js +0 -501
  774. package/dist/map-claims-CAa_bQt9.js +0 -387
  775. package/dist/map-error-BCdb2Nrp.js +0 -23
  776. package/dist/markers-BeHZ4x9Q.js +0 -80
  777. package/dist/may-use-WDhFPqGG.js +0 -125
  778. package/dist/membership-filter-BWnfRQzo.js +0 -68
  779. package/dist/migrate-DVsxeE0y.js +0 -537
  780. package/dist/module-values-CdaVwrab.js +0 -107
  781. package/dist/oauth-security-X7Em8DbH.js +0 -26
  782. package/dist/ocsf-TcjRBgIs.js +0 -136
  783. package/dist/openapi-BFUnL8Yi.js +0 -137
  784. package/dist/openapi-Cc-aS9xC.js +0 -416
  785. package/dist/openapi-DcjyfR1g.js +0 -256
  786. package/dist/operation-findings-CVwJHEu_.js +0 -36
  787. package/dist/operation-risks-BKOcTv8J.js +0 -13
  788. package/dist/operations-BMPx7HyO.d.ts +0 -62
  789. package/dist/operations-Bm9HFecz.js +0 -89
  790. package/dist/optional-8TKc-0j4.js +0 -47
  791. package/dist/output-LDciF_4t.js +0 -96
  792. package/dist/output-files-BYscrQl-.js +0 -1
  793. package/dist/output-files-CM0BnH05.js +0 -150
  794. package/dist/ownership-DvK6INyx.js +0 -1062
  795. package/dist/parse-CORUNcCo.js +0 -151
  796. package/dist/parse-local-manifest-Ce2N-Opr.js +0 -69
  797. package/dist/parse-local-manifest-w_ksIkB9.d.ts +0 -10
  798. package/dist/parse-request-DOBVaeiQ.js +0 -25
  799. package/dist/paths-CUvURzHp.js +0 -45
  800. package/dist/peer-BuK9F53f.js +0 -982
  801. package/dist/peer-n-swIV4H.js +0 -1
  802. package/dist/permdock-B3zE16To.js +0 -1203
  803. package/dist/permdock-DV3opaI3.d.ts +0 -674
  804. package/dist/permission-registry-B8tYxPIt.js +0 -398
  805. package/dist/permissions-BaoLxy66.js +0 -18
  806. package/dist/permissions-D-M48hW-.js +0 -146
  807. package/dist/permissions-DriWkV7q.d.ts +0 -54
  808. package/dist/pg-Ddxsd5ZB.js +0 -60
  809. package/dist/pins-nqarl3oE.js +0 -15
  810. package/dist/pkce-CnmmYqUZ.js +0 -21
  811. package/dist/policy-DIHfTqm6.d.ts +0 -20
  812. package/dist/policy-DnNOTENd.js +0 -430
  813. package/dist/policy-from-catalog-Z0hvSffr.js +0 -454
  814. package/dist/policy-module-xym9fnSq.js +0 -95
  815. package/dist/policy-types-DU389Elz.d.ts +0 -2809
  816. package/dist/postgres-store-DcyrPS-r.js +0 -1028
  817. package/dist/postgrest-3dE9SGx9.d.ts +0 -124
  818. package/dist/powersync-B5YjtUGd.js +0 -1532
  819. package/dist/powersync-BgUsk2Nf.js +0 -1
  820. package/dist/powersync-Dx7odzyw.js +0 -62
  821. package/dist/preset-Bn5Z54cH.js +0 -1858
  822. package/dist/principal-source-C6N60GtM.js +0 -103
  823. package/dist/problem-CPB8kqk7.js +0 -203
  824. package/dist/problem-details-CLDgX1KV.js +0 -156
  825. package/dist/problem-types-DSsRfONQ.js +0 -8
  826. package/dist/prompt-D1Gj1W4Y.js +0 -938
  827. package/dist/protected-action-CjSUoPGx.d.ts +0 -76
  828. package/dist/protected-action-D41o5LvP.js +0 -244
  829. package/dist/protected-action-OpOxtTsN.js +0 -80
  830. package/dist/provider-Bzzux0TR.js +0 -12
  831. package/dist/provider-D1jsNJ85.d.ts +0 -6
  832. package/dist/provider-store-tIAwP4aW.js +0 -52
  833. package/dist/provider-with-Do28DhxP.js +0 -69
  834. package/dist/pull-Pde1lapF.js +0 -257
  835. package/dist/pull-a4RpDxk8.js +0 -1
  836. package/dist/push-sJ5dy46a.js +0 -162
  837. package/dist/pushed-policy-Db651nih.d.ts +0 -63
  838. package/dist/pushed-policy-UZyQinrL.js +0 -241
  839. package/dist/refresh-on-L9UOwATg.d.ts +0 -49
  840. package/dist/refs-C8BKxc_e.js +0 -105
  841. package/dist/relation-walk-BDTaTKTM.js +0 -189
  842. package/dist/relations-CMsJ1ARY.js +0 -163
  843. package/dist/replay-BU09ad4L.js +0 -29
  844. package/dist/replay-BpmpY2ev.d.ts +0 -5
  845. package/dist/request-context-C2_1lchh.d.ts +0 -5
  846. package/dist/request-context-dyCY4V1t.js +0 -71
  847. package/dist/request-schema-CMP8Cmxd.js +0 -156
  848. package/dist/resolve-names-D5_kABup.js +0 -206
  849. package/dist/resource-ref-CaS9yVPi.js +0 -20
  850. package/dist/resource-relations-8-pCScBO.js +0 -252
  851. package/dist/retire-B2xffQgY.js +0 -249
  852. package/dist/revocations-BaUXHM1N.d.ts +0 -26
  853. package/dist/revocations-Bhr0aMIC.js +0 -27
  854. package/dist/rls-BI687j8q.js +0 -2700
  855. package/dist/rls-CKLHLcRl.js +0 -367
  856. package/dist/role-builder-BXdhhQcB.js +0 -507
  857. package/dist/rolldown-runtime-C3I60J0A.js +0 -4
  858. package/dist/row-conditions-BAGHOmVq.js +0 -28
  859. package/dist/row-pair-DglMdRFh.js +0 -34
  860. package/dist/rpc-BdFGYcWm.js +0 -112
  861. package/dist/rpc-DKRQobOX.d.ts +0 -22
  862. package/dist/run-B4heHtD1.js +0 -1
  863. package/dist/run-BG2kPruh.js +0 -694
  864. package/dist/run-ticket-Ddxt9OuU.js +0 -371
  865. package/dist/run-ticket-o4RxoaEN.d.ts +0 -159
  866. package/dist/runtime-rf0ZuyF3.js +0 -14
  867. package/dist/saas-D9maBt0q.js +0 -1223
  868. package/dist/scan-BvTBo9-D.js +0 -29
  869. package/dist/schema-BlnU_TzE.js +0 -414
  870. package/dist/schema-grK6TTBH.js +0 -134
  871. package/dist/scim-BG6uPUeW.js +0 -1056
  872. package/dist/scim-CovliQUg.js +0 -44
  873. package/dist/scopes-gdH__vDZ.js +0 -239
  874. package/dist/server-CKjFooaJ.js +0 -147
  875. package/dist/server-types-C4q8_8MM.d.ts +0 -325
  876. package/dist/sha256-C-4WXKIu.js +0 -158
  877. package/dist/shared-BRmCJxDK.js +0 -125
  878. package/dist/shared-DfaIWvIJ.js +0 -354
  879. package/dist/signals-B1vHR3fN.js +0 -32
  880. package/dist/sink-C3KDccl9.d.ts +0 -249
  881. package/dist/sink-D9_vh372.js +0 -968
  882. package/dist/skills-DzNdLezx.js +0 -51
  883. package/dist/skills-nPLVGtGH.js +0 -204
  884. package/dist/snapshot-D0VOanxQ.js +0 -334
  885. package/dist/snapshot-cache-B66h7FBK.js +0 -70
  886. package/dist/snapshot-cache-C1mN0pXe.d.ts +0 -70
  887. package/dist/snapshot-compact-CUtXsx6i.js +0 -75
  888. package/dist/snapshot-empty-F7d5BRlc.js +0 -18
  889. package/dist/snapshot-evaluate-C3ZA35O_.js +0 -501
  890. package/dist/snapshot-reads-CNNmp1cK.js +0 -66
  891. package/dist/sources-2virTxHt.d.ts +0 -721
  892. package/dist/sources-C4vkzZJV.js +0 -660
  893. package/dist/sources-qoIJQrJv.js +0 -11
  894. package/dist/sql-0WjxIp9g.js +0 -80
  895. package/dist/sql-B80DFdpG.d.ts +0 -10
  896. package/dist/src-ieIv22BA.js +0 -2080
  897. package/dist/standard-webhooks-B2g_yWK8.d.ts +0 -88
  898. package/dist/standard-webhooks-D67a3nzk.js +0 -228
  899. package/dist/storage-C2bWdvJH.js +0 -132
  900. package/dist/store-DXO0aVgf.js +0 -380
  901. package/dist/store-core-BI-9ZU-5.d.ts +0 -311
  902. package/dist/store-options-BYKNX_JG.js +0 -993
  903. package/dist/stores-DtM8pt8o.js +0 -128
  904. package/dist/stores-DwGfIcmq.d.ts +0 -57
  905. package/dist/stream-DQ3rbO3J.js +0 -74
  906. package/dist/style-DblOtSga.js +0 -1
  907. package/dist/style-Ds11Hmk4.js +0 -25
  908. package/dist/subject-C7RddW0G.js +0 -24
  909. package/dist/subject-cache-BT1fGuea.js +0 -193
  910. package/dist/subject-cache-TY2tw-k9.d.ts +0 -144
  911. package/dist/subject-jG6o8eKo.js +0 -556
  912. package/dist/subject-settings-8sH5HlII.js +0 -150
  913. package/dist/subject-settings-vNW8qmUH.d.ts +0 -52
  914. package/dist/supabase-BlAqmxD8.js +0 -723
  915. package/dist/supabase-dk1kB9bJ.js +0 -92
  916. package/dist/supabase-hook-Bu5gkzix.js +0 -1
  917. package/dist/supabase-hook-Cf9zKz8T.js +0 -4263
  918. package/dist/supautils-BREOPaHY.js +0 -1186
  919. package/dist/support-session-BGeEYDSq.js +0 -158
  920. package/dist/tables-DnNACfAr.js +0 -4003
  921. package/dist/target-qdEAnnhU.js +0 -51
  922. package/dist/tenancy-BlxY5T0q.js +0 -224
  923. package/dist/text-BMFRfBqc.js +0 -8
  924. package/dist/text-diff-BtfSmdUo.js +0 -444
  925. package/dist/thenable-BNSM1U2R.js +0 -40
  926. package/dist/time-nR1JesoH.js +0 -95
  927. package/dist/timeout-D51niuQP.js +0 -8
  928. package/dist/token-D6pWn8Uj.d.ts +0 -11
  929. package/dist/token-DaMnIU9O.js +0 -77
  930. package/dist/tool-refusal-D4spOJ7I.js +0 -44
  931. package/dist/type-helpers-tDoGEIsd.d.ts +0 -49
  932. package/dist/types-61f3KMtI.d.ts +0 -1136
  933. package/dist/types-BDgMzK1i.d.ts +0 -368
  934. package/dist/types-BIvkpVoc.d.ts +0 -180
  935. package/dist/types-BWjNPQkS.d.ts +0 -67
  936. package/dist/types-Bq4AU68k.d.ts +0 -105
  937. package/dist/types-BsqLNNvG.d.ts +0 -68
  938. package/dist/types-CH67RMvL.d.ts +0 -136
  939. package/dist/types-CcUXciSj.js +0 -79
  940. package/dist/types-DAyp592k.d.ts +0 -276
  941. package/dist/types-DEDocm4c.d.ts +0 -81
  942. package/dist/types-DQQkzF97.d.ts +0 -126
  943. package/dist/types-DdeivUBP.d.ts +0 -68
  944. package/dist/types-X40XNxRP.d.ts +0 -265
  945. package/dist/usage-BkDU1dYf.js +0 -762
  946. package/dist/usage-DNj42KHA.js +0 -32
  947. package/dist/usage-DrB_tDNk.js +0 -1
  948. package/dist/validation-error-CV0nV6_L.d.ts +0 -29
  949. package/dist/validation-error-CYg2kJEw.js +0 -36
  950. package/dist/validity-IcjQSR7I.js +0 -57
  951. package/dist/verifier-DUV6pLqZ.js +0 -519
  952. package/dist/verify-Boehaks6.js +0 -1736
  953. package/dist/version-DMQ0dnN5.js +0 -48
  954. package/dist/version-DizhmD72.js +0 -1
  955. package/dist/version-sources-BRb9ZteH.js +0 -34
  956. package/dist/views-MWmJ6Y4P.js +0 -147
  957. package/dist/vocabulary-BuYFWeCU.js +0 -158
  958. package/dist/vocabulary-DeZvUaTw.d.ts +0 -401
  959. package/dist/waiter-BophA4BT.d.ts +0 -39
  960. package/dist/waiter-aBLM63_f.js +0 -67
  961. package/dist/watch-CJKYQYNb.js +0 -167
  962. package/dist/watch-Cv-xvI6e.js +0 -1
  963. package/dist/who-can-Yh9WdiwK.js +0 -367
  964. package/dist/wire-delegation-Cv3W2eaM.js +0 -36
  965. package/dist/wire-denial-C7PaVYEM.js +0 -27
  966. package/dist/wrap-Bq9fHwuT.d.ts +0 -18
  967. package/dist/wrap-C5PWzgkq.js +0 -33
  968. package/schemas/catalog-v1.json +0 -679
  969. package/schemas/cli-result-v1.json +0 -95
@@ -1,4263 +0,0 @@
1
- import { r as isRecord } from "./compact-CAf557ZB.js";
2
- import { o as hasConditionOp } from "./refs-C8BKxc_e.js";
3
- import { c as rootScope, d as scopeList, l as scopeChain, s as resolveScope } from "./scopes-gdH__vDZ.js";
4
- import { r as readMemberships } from "./subject-cache-BT1fGuea.js";
5
- import { t as APPROVAL_REQUEST_SCHEMA } from "./request-schema-CMP8Cmxd.js";
6
- import { t as AUTHZ_EVENT } from "./authz-topic-Dbc-HDOS.js";
7
- import { a as describeError, i as configError } from "./errors-BhRkoNS7.js";
8
- import { i as readJsonFile, o as sqlFiles, s as writeFileEnsuringDir } from "./files-BSjrtIHw.js";
9
- import { a as SUPABASE_MANIFEST_SCHEMA } from "./version-DMQ0dnN5.js";
10
- import { c as requirePolicy } from "./load-C4p4VgwR.js";
11
- import "./budget-BBCPDOGP.js";
12
- import { i as qualifySqlTable } from "./sql-0WjxIp9g.js";
13
- import { i as scopeColumn } from "./compile-Cvru58id.js";
14
- import { t as authorizeSql } from "./supabase-BlAqmxD8.js";
15
- import { a as hookApiNames, d as keptKeys, t as AUTHZ_VERSION_TABLE, u as roleManifest } from "./sources-C4vkzZJV.js";
16
- import { t as beforeFirst } from "./text-BMFRfBqc.js";
17
- import { n as GRANTS_MARKER, r as HOOK_MARKER, s as hookMarkerFields } from "./markers-BeHZ4x9Q.js";
18
- import { n as formatManifestJson, t as MANIFEST_FILE } from "./manifest-json-CAGzls-C.js";
19
- import { n as MIGRATION_DIRS } from "./constants-DcJABbLW.js";
20
- import { f as writeOutputFiles, l as partPath, r as driftOf, u as pgDeltaPath } from "./output-files-CM0BnH05.js";
21
- import { n as pgConnector } from "./pg-Ddxsd5ZB.js";
22
- import { A as quoteQualified, D as qualified$1, F as firstScopeType, L as scopeTypeOf, O as quoteIdent, a as customRolesOn, j as quoteTable, k as quoteLiteral, l as USER_ID_HELPER, r as HELPERS, y as subjectIdSql, z as tenantTypeOf } from "./shared-DfaIWvIJ.js";
23
- import { C as permittedByPermissionHelper, Et as activeRowSql, K as globalRoleSource, Ot as checkSuspension, S as permissionKeysForHelper, _ as ASSIGNMENTS, _t as memberOfHelper, b as checkName, bt as permittedIdsHelper, ct as hasMemberFor, dt as isTeamScope, et as API_KEY_ALLOWS, gt as memberIdsHelper, ht as memberForTable, k as TOKEN_SCOPE_ALLOWS, lt as hasPermittedUsers, mt as memberForSources, nt as apiKeyFields, pt as memberForHelper, v as OWNERSHIP, vt as memberRoleOf, y as PERMISSION_HELPERS, yt as permittedForHelper } from "./tables-DnNACfAr.js";
24
- import { a as guardedTables, t as ownershipRules, u as roleNames } from "./ownership-DvK6INyx.js";
25
- import { t as membershipSourcesOf } from "./sources-qoIJQrJv.js";
26
- import { a as splitUndiffed, r as tableKey, t as decidingColumns } from "./deciding-columns-NB4wcyBf.js";
27
- import { c as ACTOR_MAY_WRITE, p as readOnlyActorKinds } from "./fields-D9PIYlJy.js";
28
- import { r as permittedUsersHelper, t as resolveNames } from "./resolve-names-D5_kABup.js";
29
- import { existsSync, readFileSync, readdirSync } from "node:fs";
30
- import { dirname, join, posix, resolve } from "node:path";
31
- //#region ../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/error.js
32
- /*!
33
- * Copyright (c) Squirrel Chat et al., All rights reserved.
34
- * SPDX-License-Identifier: BSD-3-Clause
35
- *
36
- * Redistribution and use in source and binary forms, with or without
37
- * modification, are permitted provided that the following conditions are met:
38
- *
39
- * 1. Redistributions of source code must retain the above copyright notice, this
40
- * list of conditions and the following disclaimer.
41
- * 2. Redistributions in binary form must reproduce the above copyright notice,
42
- * this list of conditions and the following disclaimer in the
43
- * documentation and/or other materials provided with the distribution.
44
- * 3. Neither the name of the copyright holder nor the names of its contributors
45
- * may be used to endorse or promote products derived from this software without
46
- * specific prior written permission.
47
- *
48
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
49
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
50
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
51
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
52
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
54
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
55
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
56
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
57
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
58
- */
59
- function getLineColFromPtr(string, ptr) {
60
- let lines = string.slice(0, ptr).split(/\r?\n/);
61
- return [lines.length, lines.pop().length + 1];
62
- }
63
- function makeCodeBlock(string, line, column) {
64
- let lines = string.split(/\r?\n/);
65
- let codeblock = "";
66
- let numberLen = (Math.log10(line + 1) | 0) + 1;
67
- for (let i = line - 1; i <= line + 1; i++) {
68
- let l = lines[i - 1];
69
- if (!l) continue;
70
- codeblock += i.toString().padEnd(numberLen, " ");
71
- codeblock += ": ";
72
- codeblock += l;
73
- codeblock += "\n";
74
- if (i === line) {
75
- codeblock += " ".repeat(numberLen + column + 2);
76
- codeblock += "^\n";
77
- }
78
- }
79
- return codeblock;
80
- }
81
- var TomlError = class TomlError extends Error {
82
- line;
83
- column;
84
- codeblock;
85
- constructor(message, options) {
86
- const [line, column] = getLineColFromPtr(options.toml, options.ptr);
87
- const codeblock = makeCodeBlock(options.toml, line, column);
88
- super(`Invalid TOML document: ${message}\n\n${codeblock}`, options);
89
- this.line = line;
90
- this.column = column;
91
- this.codeblock = codeblock;
92
- }
93
- /** @internal */
94
- static x(message, ctx, ptr) {
95
- throw new TomlError(message, {
96
- toml: ctx.s,
97
- ptr: ptr ?? ctx.p
98
- });
99
- }
100
- };
101
- //#endregion
102
- //#region ../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/primitive.js
103
- /*!
104
- * Copyright (c) Squirrel Chat et al., All rights reserved.
105
- * SPDX-License-Identifier: BSD-3-Clause
106
- *
107
- * Redistribution and use in source and binary forms, with or without
108
- * modification, are permitted provided that the following conditions are met:
109
- *
110
- * 1. Redistributions of source code must retain the above copyright notice, this
111
- * list of conditions and the following disclaimer.
112
- * 2. Redistributions in binary form must reproduce the above copyright notice,
113
- * this list of conditions and the following disclaimer in the
114
- * documentation and/or other materials provided with the distribution.
115
- * 3. Neither the name of the copyright holder nor the names of its contributors
116
- * may be used to endorse or promote products derived from this software without
117
- * specific prior written permission.
118
- *
119
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
120
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
121
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
122
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
123
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
124
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
125
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
126
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
127
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
128
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
129
- */
130
- /** @internal */
131
- function parseString(ctx) {
132
- let startPtr = ctx.p;
133
- let c = ctx.s.charCodeAt(ctx.p++);
134
- let first = c;
135
- let isLiteral = c === 39;
136
- let isMultiline = c === ctx.s.charCodeAt(ctx.p) && c === ctx.s.charCodeAt(ctx.p + 1);
137
- if (isMultiline) {
138
- if ((c = ctx.s.charCodeAt(ctx.p += 2)) === 10) ctx.p++;
139
- else if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10) ctx.p += 2;
140
- }
141
- let parsed = "";
142
- let sliceStart = ctx.p;
143
- let state = 0;
144
- for (; ctx.p < ctx.s.length; ctx.p++) {
145
- c = ctx.s.charCodeAt(ctx.p);
146
- if (isMultiline && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)) state = state && 3;
147
- else if (c < 32 && c !== 9 || c === 127) TomlError.x("control characters are not allowed in strings", ctx);
148
- else if ((!state || state === 3) && c === first && (!isMultiline || ctx.s.charCodeAt(ctx.p + 1) === first && ctx.s.charCodeAt(ctx.p + 2) === first)) {
149
- if (isMultiline) {
150
- if (ctx.s.charCodeAt(ctx.p + 3) === first) ctx.p++;
151
- if (ctx.s.charCodeAt(ctx.p + 3) === first) ctx.p++;
152
- }
153
- if (!state) {
154
- let s = ctx.s.slice(sliceStart, ctx.p);
155
- parsed = parsed ? parsed + s : s;
156
- }
157
- ctx.p += isMultiline ? 3 : 1;
158
- return parsed;
159
- } else if (!state) {
160
- if (!isLiteral && c === 92) {
161
- parsed += ctx.s.slice(sliceStart, sliceStart = ctx.p);
162
- state = 1;
163
- }
164
- } else if (state === 1) {
165
- if (c === 120 || c === 117 || c === 85) {
166
- let errPtr = ctx.p++ - 1;
167
- let value = 0;
168
- let len = c === 120 ? 2 : c === 117 ? 4 : 8;
169
- for (let j = 0; j < len; j++, ctx.p++) {
170
- let hex = ctx.s.charCodeAt(ctx.p);
171
- let digit = hex >= 48 && hex <= 57 ? hex - 48 : hex >= 65 && hex <= 70 ? hex - 65 + 10 : hex >= 97 && hex <= 102 ? hex - 97 + 10 : -1;
172
- if (digit < 0) TomlError.x("invalid non-hex character in unicode escape", ctx);
173
- value = value << 4 | digit;
174
- }
175
- if (value < 0 || value > 1114111 || value >= 55296 && value <= 57343) TomlError.x("invalid unicode escape", ctx, errPtr);
176
- parsed += String.fromCodePoint(value);
177
- sliceStart = ctx.p--;
178
- state = 0;
179
- } else if (isMultiline && (c === 32 || c === 9)) state = 2;
180
- else {
181
- if (c === 98) parsed += "\b";
182
- else if (c === 116) parsed += " ";
183
- else if (c === 110) parsed += "\n";
184
- else if (c === 102) parsed += "\f";
185
- else if (c === 114) parsed += "\r";
186
- else if (c === 101) parsed += "\x1B";
187
- else if (c === 34) parsed += "\"";
188
- else if (c === 92) parsed += "\\";
189
- else TomlError.x("unrecognised escape sequence", ctx);
190
- sliceStart = ctx.p + 1;
191
- state = 0;
192
- }
193
- } else if (c !== 32 && c !== 9) {
194
- if (state === 2) TomlError.x("invalid escape: only line-ending whitespace may be escaped", ctx, sliceStart);
195
- state = !isLiteral && c === 92 ? 1 : 0;
196
- sliceStart = ctx.p;
197
- }
198
- }
199
- TomlError.x("unfinished string", ctx, startPtr);
200
- }
201
- //#endregion
202
- //#region ../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/date.js
203
- /*!
204
- * Copyright (c) Squirrel Chat et al., All rights reserved.
205
- * SPDX-License-Identifier: BSD-3-Clause
206
- *
207
- * Redistribution and use in source and binary forms, with or without
208
- * modification, are permitted provided that the following conditions are met:
209
- *
210
- * 1. Redistributions of source code must retain the above copyright notice, this
211
- * list of conditions and the following disclaimer.
212
- * 2. Redistributions in binary form must reproduce the above copyright notice,
213
- * this list of conditions and the following disclaimer in the
214
- * documentation and/or other materials provided with the distribution.
215
- * 3. Neither the name of the copyright holder nor the names of its contributors
216
- * may be used to endorse or promote products derived from this software without
217
- * specific prior written permission.
218
- *
219
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
220
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
221
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
222
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
223
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
224
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
225
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
226
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
227
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
228
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
229
- */
230
- let DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;
231
- var TomlDate = class TomlDate extends Date {
232
- #hasDate = false;
233
- #hasTime = false;
234
- #offset = null;
235
- constructor(date, fasttype, unsafeDelim) {
236
- let hasDate = true;
237
- let hasTime = true;
238
- let offset = "Z";
239
- let c;
240
- if (typeof date === "string") {
241
- if (fasttype) prep: {
242
- if (fasttype < 3) {
243
- if (+date.slice(11, 13) > 23) {
244
- date = "";
245
- break prep;
246
- }
247
- if (fasttype === 2) {
248
- offset = null;
249
- date += "Z";
250
- } else if ((c = date.charCodeAt(date.length - 1)) !== 90 && c !== 122) offset = date.slice(date.length - 6);
251
- if (unsafeDelim) date = date.slice(0, 10) + "T" + date.slice(11);
252
- } else if (fasttype === 4) date = +date.slice(0, 2) > 23 ? "" : `0000-01-01T${date}Z`;
253
- hasDate = fasttype !== 4;
254
- hasTime = fasttype !== 3;
255
- }
256
- else {
257
- let match = date.match(DATE_TIME_RE);
258
- if (match) {
259
- if (!match[1]) {
260
- hasDate = false;
261
- date = `0000-01-01T${date}`;
262
- }
263
- hasTime = !!match[2];
264
- hasTime && date[10] === " " && (date = date.replace(" ", "T"));
265
- if (match[2] && +match[2] > 23) date = "";
266
- else {
267
- offset = match[3] || null;
268
- if (!offset && hasTime) date += "Z";
269
- }
270
- } else date = "";
271
- }
272
- }
273
- super(date);
274
- if (!isNaN(this.getTime())) {
275
- this.#hasDate = hasDate;
276
- this.#hasTime = hasTime;
277
- this.#offset = offset;
278
- }
279
- }
280
- isDateTime() {
281
- return this.#hasDate && this.#hasTime;
282
- }
283
- isLocal() {
284
- return !this.#hasDate || !this.#hasTime || !this.#offset;
285
- }
286
- isDate() {
287
- return this.#hasDate && !this.#hasTime;
288
- }
289
- isTime() {
290
- return this.#hasTime && !this.#hasDate;
291
- }
292
- isValid() {
293
- return this.#hasDate || this.#hasTime;
294
- }
295
- toISOString() {
296
- let iso = super.toISOString();
297
- if (this.isDate()) return iso.slice(0, 10);
298
- if (this.isTime()) return iso.slice(11, 23);
299
- if (this.#offset === null) return iso.slice(0, -1);
300
- if (this.#offset === "Z" || this.#offset === "z") return iso;
301
- let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
302
- offset = this.#offset[0] === "-" ? offset : -offset;
303
- return (/* @__PURE__ */ new Date(this.getTime() - offset * 6e4)).toISOString().slice(0, -1) + this.#offset;
304
- }
305
- static wrapAsOffsetDateTime(jsDate, offset = "Z") {
306
- let date = new TomlDate(jsDate);
307
- date.#offset = offset;
308
- return date;
309
- }
310
- static wrapAsLocalDateTime(jsDate) {
311
- let date = new TomlDate(jsDate);
312
- date.#offset = null;
313
- return date;
314
- }
315
- static wrapAsLocalDate(jsDate) {
316
- let date = new TomlDate(jsDate);
317
- date.#hasTime = false;
318
- date.#offset = null;
319
- return date;
320
- }
321
- static wrapAsLocalTime(jsDate) {
322
- let date = new TomlDate(jsDate);
323
- date.#hasDate = false;
324
- date.#offset = null;
325
- return date;
326
- }
327
- };
328
- //#endregion
329
- //#region ../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/extract.js
330
- /*!
331
- * Copyright (c) Squirrel Chat et al., All rights reserved.
332
- * SPDX-License-Identifier: BSD-3-Clause
333
- *
334
- * Redistribution and use in source and binary forms, with or without
335
- * modification, are permitted provided that the following conditions are met:
336
- *
337
- * 1. Redistributions of source code must retain the above copyright notice, this
338
- * list of conditions and the following disclaimer.
339
- * 2. Redistributions in binary form must reproduce the above copyright notice,
340
- * this list of conditions and the following disclaimer in the
341
- * documentation and/or other materials provided with the distribution.
342
- * 3. Neither the name of the copyright holder nor the names of its contributors
343
- * may be used to endorse or promote products derived from this software without
344
- * specific prior written permission.
345
- *
346
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
347
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
348
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
349
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
350
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
351
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
352
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
353
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
354
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
355
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
356
- */
357
- function isDigit(char, base = 10) {
358
- return base === 16 ? char > 47 && char < 58 || char > 64 && char < 71 || char > 96 && char < 103 : char > 47 && char < 48 + base;
359
- }
360
- function isEndOfValue(char, delim) {
361
- return char === 32 || char === 9 || char === 10 || char === 13 || delim && (char === delim || char === 44) || char === 35;
362
- }
363
- /** @internal */
364
- function extractValue(ctx, end) {
365
- let errPtr = ctx.p;
366
- let c = ctx.s.charCodeAt(ctx.p);
367
- if (c === 91 || c === 123) {
368
- ctx.d-- || TomlError.x("document contains excessively nested structures. aborting.", ctx);
369
- let value = c === 91 ? parseArray(ctx) : parseInlineTable(ctx);
370
- ctx.d++;
371
- return value;
372
- }
373
- if (c === 34 || c === 39) return parseString(ctx);
374
- if (c === 116) {
375
- if (ctx.s.charCodeAt(++ctx.p) !== 114 || ctx.s.charCodeAt(++ctx.p) !== 117 || ctx.s.charCodeAt(++ctx.p) !== 101) TomlError.x("invalid value", ctx, errPtr);
376
- return ctx.p++, true;
377
- }
378
- if (c === 102) {
379
- if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 108 || ctx.s.charCodeAt(++ctx.p) !== 115 || ctx.s.charCodeAt(++ctx.p) !== 101) TomlError.x("invalid value", ctx, errPtr);
380
- return ctx.p++, false;
381
- }
382
- if (c === 43 || c === 45) return parseNumber(ctx, ctx.p, ctx.s.charCodeAt(++ctx.p), 44 - c, end);
383
- if (ctx.s.charCodeAt(ctx.p + 4) === 45 && ctx.s.charCodeAt(ctx.p + 7) === 45) return parseDate(ctx, c, end);
384
- if (ctx.s.charCodeAt(ctx.p + 2) === 58) return parseTime(ctx, c, end);
385
- return parseNumber(ctx, ctx.p, c, 0, end);
386
- }
387
- function parseNumber(ctx, startPtr, startChr, sign, endChr) {
388
- let c = startChr;
389
- let state = 0;
390
- let hasUnderscores = false;
391
- if (c === 105) {
392
- if (ctx.s.charCodeAt(++ctx.p) !== 110 || ctx.s.charCodeAt(++ctx.p) !== 102) TomlError.x("invalid value", ctx, startPtr);
393
- return ctx.p++, (sign || 1) / 0;
394
- }
395
- if (c === 110) {
396
- if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 110) TomlError.x("invalid value", ctx, startPtr);
397
- return ctx.p++, NaN;
398
- }
399
- if (c === 48) {
400
- if (++ctx.p >= ctx.s.length || isEndOfValue(c = ctx.s.charCodeAt(ctx.p), endChr)) return ctx.bi === true ? 0n : 0;
401
- if (!sign) {
402
- if (c === 120) return parseIntegerBaseN(ctx, startPtr, 16, endChr);
403
- else if (c === 98) return parseIntegerBaseN(ctx, startPtr, 2, endChr);
404
- else if (c === 111) return parseIntegerBaseN(ctx, startPtr, 8, endChr);
405
- }
406
- if (c === 46) state = 2;
407
- else if (c === 101 || c === 69) state = 4;
408
- else TomlError.x("illegal leading zero", ctx, startPtr);
409
- } else if (!isDigit(c)) TomlError.x("invalid value", ctx, startPtr);
410
- while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
411
- if (!state) state = 1;
412
- if (c === 95) {
413
- if (!(state & 1)) TomlError.x("illegal underscore", ctx);
414
- state += 11;
415
- hasUnderscores = true;
416
- } else if (state === 1 && c === 46) state = 2;
417
- else if ((state === 1 || state === 3) && (c === 101 || c === 69)) state = 4;
418
- else if (state === 4 && (c === 43 || c === 45)) state = 6;
419
- else if (!isDigit(c)) TomlError.x(`illegal character in numeric literal`, ctx);
420
- else if (state > 9) state -= 11;
421
- else if (!(state & 1)) state++;
422
- }
423
- if (!state) {
424
- let val = (startChr - 48) * (sign || 1);
425
- return ctx.bi === true ? BigInt(val) : val;
426
- }
427
- if (!(state & 1)) TomlError.x("unfinished numeric value", ctx, startPtr);
428
- let str = ctx.s.slice(startPtr, ctx.p);
429
- if (hasUnderscores) str = str.replaceAll("_", "");
430
- return state > 1 ? parseFloat(str) : parseInteger(ctx, str, 10, startPtr);
431
- }
432
- function parseIntegerBaseN(ctx, startPtr, base, endChr) {
433
- let c, underscore = 1;
434
- while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) if (c === 95) {
435
- if (underscore & 1) TomlError.x("illegal underscore", ctx);
436
- underscore = 3;
437
- } else if (!isDigit(c, base)) TomlError.x(`illegal character in numeric literal`, ctx);
438
- else if (underscore & 1) underscore--;
439
- if (underscore & 1) TomlError.x("unfinished numeric value", ctx);
440
- let str = ctx.s.slice(startPtr + 2, ctx.p);
441
- if (underscore) str = str.replaceAll("_", "");
442
- return parseInteger(ctx, str, base, startPtr);
443
- }
444
- function parseInteger(ctx, str, base, startPtr) {
445
- if (ctx.bi !== true) int: {
446
- let val = parseInt(str, base);
447
- if (!Number.isSafeInteger(val)) {
448
- if (ctx.bi) break int;
449
- TomlError.x("integer value cannot be represented losslessly", ctx, startPtr);
450
- }
451
- return val;
452
- }
453
- return base === 10 ? BigInt(str) : BigInt((base === 2 ? "0b" : base === 8 ? "0o" : "0x") + str);
454
- }
455
- function parseDate(ctx, c, endChr) {
456
- let startPtr = ctx.p++, unsafeSeparator;
457
- if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++))) return parseNumber(ctx, ctx.p = startPtr, c, 0, endChr);
458
- ctx.p += 5;
459
- if (!isDigit(ctx.s.charCodeAt(ctx.p++))) TomlError.x("invalid date-time: date part is malformed", ctx, startPtr);
460
- if (ctx.p >= ctx.s.length || ((c = ctx.s.charCodeAt(ctx.p)) !== 32 || (unsafeSeparator = true, !isDigit(ctx.s.charCodeAt(ctx.p + 1)))) && c !== 84 && c !== 116) return readDate(ctx, ctx.s.slice(startPtr, ctx.p), 3, false, startPtr);
461
- if (ctx.s.charCodeAt(ctx.p += 3) !== 58) TomlError.x("invalid date-time: time part is malformed", ctx, startPtr);
462
- if (ctx.s.charCodeAt(ctx.p += 3) === 58) ctx.p += 3;
463
- if (ctx.s.charCodeAt(ctx.p) === 46) while (isDigit(ctx.s.charCodeAt(++ctx.p)));
464
- if (c = ctx.s.charCodeAt(ctx.p)) {
465
- if (c === 90 || c === 122) return readDate(ctx, ctx.s.slice(startPtr, ++ctx.p), 1, unsafeSeparator, startPtr, "[+00:00]");
466
- if (c === 43 || c === 45) return readDate(ctx, ctx.s.slice(startPtr, ctx.p += 6), 1, unsafeSeparator, startPtr, !ctx.ld && "[" + ctx.s.slice(ctx.p - 6, ctx.p) + "]");
467
- }
468
- return readDate(ctx, ctx.s.slice(startPtr, ctx.p), 2, unsafeSeparator, startPtr);
469
- }
470
- function parseTime(ctx, c, endChr) {
471
- let start = ctx.p;
472
- if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(++ctx.p))) return parseNumber(ctx, --ctx.p, c, 0, endChr);
473
- if (ctx.s.charCodeAt(ctx.p += 4) === 58) ctx.p += 3;
474
- if (ctx.s.charCodeAt(ctx.p) === 46) while (isDigit(ctx.s.charCodeAt(++ctx.p)));
475
- return readDate(ctx, ctx.s.slice(start, ctx.p), 4, false, start);
476
- }
477
- function readDate(ctx, str, type, unsafeDelim, errPtr, temporalSuffix) {
478
- if (ctx.ld) {
479
- let date = new TomlDate(str, type, unsafeDelim);
480
- if (!date.isValid()) TomlError.x("invalid date", ctx, errPtr);
481
- return date;
482
- }
483
- try {
484
- if (temporalSuffix) str += temporalSuffix;
485
- switch (type) {
486
- case 1: return Temporal.ZonedDateTime.from(str);
487
- case 2: return Temporal.PlainDateTime.from(str);
488
- case 3: return Temporal.PlainDate.from(str);
489
- case 4: return Temporal.PlainTime.from(str);
490
- }
491
- } catch (e) {
492
- TomlError.x(e instanceof Error ? e.message : "" + e, ctx, errPtr);
493
- }
494
- }
495
- //#endregion
496
- //#region ../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/util.js
497
- /*!
498
- * Copyright (c) Squirrel Chat et al., All rights reserved.
499
- * SPDX-License-Identifier: BSD-3-Clause
500
- *
501
- * Redistribution and use in source and binary forms, with or without
502
- * modification, are permitted provided that the following conditions are met:
503
- *
504
- * 1. Redistributions of source code must retain the above copyright notice, this
505
- * list of conditions and the following disclaimer.
506
- * 2. Redistributions in binary form must reproduce the above copyright notice,
507
- * this list of conditions and the following disclaimer in the
508
- * documentation and/or other materials provided with the distribution.
509
- * 3. Neither the name of the copyright holder nor the names of its contributors
510
- * may be used to endorse or promote products derived from this software without
511
- * specific prior written permission.
512
- *
513
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
514
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
515
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
516
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
517
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
518
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
519
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
520
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
521
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
522
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
523
- */
524
- /** @internal */
525
- function skipComment(ctx) {
526
- for (; ctx.p < ctx.s.length; ctx.p++) {
527
- let c = ctx.s.charCodeAt(ctx.p);
528
- if (c === 10) break;
529
- if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10) {
530
- ctx.p++;
531
- break;
532
- }
533
- if (c < 32 && c !== 9 || c === 127) TomlError.x("control characters are not allowed in comments", ctx);
534
- }
535
- }
536
- /** @internal */
537
- function skipVoid(ctx, banNewLines, banComments) {
538
- let c;
539
- while (ctx.p < ctx.s.length) {
540
- while (ctx.p < ctx.s.length && ((c = ctx.s.charCodeAt(ctx.p)) === 32 || c === 9 || !banNewLines && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10))) ctx.p++;
541
- if (banComments || c !== 35) break;
542
- skipComment(ctx);
543
- }
544
- }
545
- //#endregion
546
- //#region ../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/struct.js
547
- /*!
548
- * Copyright (c) Squirrel Chat et al., All rights reserved.
549
- * SPDX-License-Identifier: BSD-3-Clause
550
- *
551
- * Redistribution and use in source and binary forms, with or without
552
- * modification, are permitted provided that the following conditions are met:
553
- *
554
- * 1. Redistributions of source code must retain the above copyright notice, this
555
- * list of conditions and the following disclaimer.
556
- * 2. Redistributions in binary form must reproduce the above copyright notice,
557
- * this list of conditions and the following disclaimer in the
558
- * documentation and/or other materials provided with the distribution.
559
- * 3. Neither the name of the copyright holder nor the names of its contributors
560
- * may be used to endorse or promote products derived from this software without
561
- * specific prior written permission.
562
- *
563
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
564
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
565
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
566
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
567
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
568
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
569
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
570
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
571
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
572
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
573
- */
574
- /** @internal */
575
- function parseKey(ctx, end = 61) {
576
- let startPtr;
577
- let state = 0;
578
- let parsed = [];
579
- let sliceStart;
580
- let c = ctx.s.charCodeAt(startPtr = ctx.p);
581
- do
582
- if (c === end) {
583
- if (!state) TomlError.x("unexpected end of key", ctx);
584
- if (state === 1) parsed.push(ctx.s.slice(sliceStart, ctx.p));
585
- return ctx.p++, parsed;
586
- } else if (c === 46) {
587
- if (!state) TomlError.x("illegal empty bare key", ctx);
588
- if (state === 1) parsed.push(ctx.s.slice(sliceStart, ctx.p));
589
- state = 0;
590
- } else if (!state && (c === 34 || c === 39)) {
591
- if (c === ctx.s.charCodeAt(ctx.p + 1) && c === ctx.s.charCodeAt(ctx.p + 2)) TomlError.x("illegal quoted key: multiline strings are not allowed", ctx);
592
- parsed.push(parseString(ctx));
593
- state = 2;
594
- ctx.p--;
595
- } else if (c === 32 || c === 9) {
596
- if (state === 1) {
597
- parsed.push(ctx.s.slice(sliceStart, ctx.p));
598
- state = 2;
599
- }
600
- } else if (state === 2 || c < 48 && c !== 45 || c > 57 && c < 65 || c > 90 && c < 97 && c !== 95 || c > 122) TomlError.x("illegal character in key", ctx);
601
- else if (!state) {
602
- state = 1;
603
- sliceStart = ctx.p;
604
- }
605
- while (c = ctx.s.charCodeAt(++ctx.p));
606
- TomlError.x("incomplete key-value: cannot find end of key", ctx, startPtr);
607
- }
608
- /** @internal */
609
- function parseInlineTable(ctx) {
610
- let startPtr = ctx.p++;
611
- let res = Object.create(null);
612
- let seen = /* @__PURE__ */ new Set();
613
- let c;
614
- while (ctx.p < ctx.s.length) {
615
- skipVoid(ctx);
616
- if ((c = ctx.s.charCodeAt(ctx.p)) === 125) {
617
- ctx.p++;
618
- return res;
619
- }
620
- let k;
621
- let t = res;
622
- let hasOwn = false;
623
- let errPtr = ctx.p;
624
- let key = parseKey(ctx);
625
- for (let i = 0; i < key.length; i++) {
626
- if (i) t = hasOwn ? t[k] : t[k] = Object.create(null);
627
- k = key[i];
628
- if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) TomlError.x("trying to redefine an already defined value", ctx, errPtr);
629
- let unsafe = k === "__proto__";
630
- if (ctx.uk && (unsafe || k === "constructor")) {
631
- t = ctx.uk !== 1 && TomlError.x("document contains an unsafe property", ctx, errPtr);
632
- break;
633
- }
634
- if (!hasOwn && unsafe) Object.defineProperty(t, k, {
635
- enumerable: true,
636
- configurable: true,
637
- writable: true
638
- });
639
- }
640
- if (hasOwn) TomlError.x("trying to redefine an already defined value", ctx, errPtr);
641
- skipVoid(ctx, true, true);
642
- let value = extractValue(ctx, 125);
643
- if (t && typeof (t[k] = value) === "object") seen.add(value);
644
- skipVoid(ctx);
645
- if ((c = ctx.s.charCodeAt(ctx.p++)) === 125) return res;
646
- if (c !== 44) TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
647
- }
648
- TomlError.x("unfinished table", ctx, startPtr);
649
- }
650
- /** @internal */
651
- function parseArray(ctx) {
652
- let startPtr = ctx.p++;
653
- let res = [];
654
- let c;
655
- while (ctx.p < ctx.s.length) {
656
- skipVoid(ctx);
657
- if ((c = ctx.s.charCodeAt(ctx.p)) === 93) {
658
- ctx.p++;
659
- return res;
660
- }
661
- res.push(extractValue(ctx, 93));
662
- skipVoid(ctx);
663
- if ((c = ctx.s.charCodeAt(ctx.p++)) === 93) return res;
664
- if (c !== 44) TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
665
- }
666
- TomlError.x("unfinished array", ctx, startPtr);
667
- }
668
- //#endregion
669
- //#region ../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/parse.js
670
- /*!
671
- * Copyright (c) Squirrel Chat et al., All rights reserved.
672
- * SPDX-License-Identifier: BSD-3-Clause
673
- *
674
- * Redistribution and use in source and binary forms, with or without
675
- * modification, are permitted provided that the following conditions are met:
676
- *
677
- * 1. Redistributions of source code must retain the above copyright notice, this
678
- * list of conditions and the following disclaimer.
679
- * 2. Redistributions in binary form must reproduce the above copyright notice,
680
- * this list of conditions and the following disclaimer in the
681
- * documentation and/or other materials provided with the distribution.
682
- * 3. Neither the name of the copyright holder nor the names of its contributors
683
- * may be used to endorse or promote products derived from this software without
684
- * specific prior written permission.
685
- *
686
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
687
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
688
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
689
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
690
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
691
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
692
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
693
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
694
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
695
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
696
- */
697
- function peekTable(ctx, key, table, meta, type) {
698
- let t = table;
699
- let m = meta;
700
- let k;
701
- let hasOwn = false;
702
- let state;
703
- for (let i = 0; i < key.length; i++) {
704
- if (i) {
705
- t = hasOwn ? t[k] : t[k] = Object.create(null);
706
- m = (state = m[k]).c;
707
- if (type === 0 && (state.t === 1 || state.t === 2)) return null;
708
- if (state.t === 2) {
709
- let l = t.length - 1;
710
- t = t[l];
711
- m = m[l].c;
712
- }
713
- }
714
- k = key[i];
715
- if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) return null;
716
- if (!hasOwn) {
717
- let unsafe = k === "__proto__";
718
- if (ctx.uk && (unsafe || k === "constructor")) return false;
719
- if (unsafe) {
720
- Object.defineProperty(t, k, {
721
- enumerable: true,
722
- configurable: true,
723
- writable: true
724
- });
725
- Object.defineProperty(m, k, {
726
- enumerable: true,
727
- configurable: true,
728
- writable: true
729
- });
730
- }
731
- m[k] = {
732
- t: i < key.length - 1 && type === 2 ? 3 : type,
733
- d: false,
734
- i: 0,
735
- c: Object.create(null)
736
- };
737
- }
738
- }
739
- state = m[k];
740
- if (state.t !== type && !(type === 1 && state.t === 3)) return null;
741
- if (type === 2) {
742
- if (!state.d) {
743
- state.d = true;
744
- t[k] = [];
745
- }
746
- t[k].push(t = Object.create(null));
747
- state.c[state.i++] = state = {
748
- t: 1,
749
- d: false,
750
- i: 0,
751
- c: Object.create(null)
752
- };
753
- }
754
- if (state.d) return null;
755
- state.d = true;
756
- if (type === 1) t = hasOwn ? t[k] : t[k] = Object.create(null);
757
- else if (type === 0 && hasOwn) return null;
758
- return [
759
- k,
760
- t,
761
- state.c
762
- ];
763
- }
764
- function validateTablePeek(ctx, peek, ptr) {
765
- if (peek === null || ctx.uk === 2) TomlError.x(peek === null ? "trying to redefine an already defined table or value" : "document contains an unsafe property", ctx, ptr);
766
- }
767
- function parse(toml, options = {}) {
768
- let ctx = {
769
- s: toml,
770
- p: 0,
771
- d: options.maxDepth ?? 1e3,
772
- bi: options.integersAsBigInt ?? false,
773
- ld: options.useLegacyDate ?? true,
774
- uk: options.unsafeKeyBehaviour === "throw" ? 2 : options.unsafeKeyBehaviour === "drop" ? 1 : 0
775
- };
776
- let res = Object.create(null);
777
- let meta = Object.create(null);
778
- let tmp;
779
- let skipping = false;
780
- let tbl = res;
781
- let m = meta;
782
- if (toml.charCodeAt(0) === 65279) ctx.p++;
783
- skipVoid(ctx);
784
- while (ctx.p < toml.length) {
785
- if (toml.charCodeAt(ctx.p) === 91) {
786
- let isTableArray = toml.charCodeAt(++ctx.p) === 91;
787
- tmp = ctx.p += +isTableArray;
788
- skipping = false;
789
- let k = parseKey(ctx, 93);
790
- if (isTableArray) {
791
- if (toml.charCodeAt(ctx.p) !== 93) TomlError.x("expected end of table array declaration", ctx);
792
- ctx.p++;
793
- }
794
- let p = peekTable(ctx, k, res, meta, isTableArray ? 2 : 1);
795
- if (!p) {
796
- validateTablePeek(ctx, p, tmp);
797
- skipping = true;
798
- } else {
799
- m = p[2];
800
- tbl = p[1];
801
- }
802
- } else {
803
- tmp = ctx.p;
804
- let p = peekTable(ctx, parseKey(ctx), tbl, m, 0);
805
- if (!p && !skipping) validateTablePeek(ctx, p, tmp);
806
- skipVoid(ctx, true, true);
807
- let v = extractValue(ctx, void 0);
808
- if (p && !skipping) p[1][p[0]] = v;
809
- }
810
- skipVoid(ctx, true);
811
- if (ctx.p < toml.length && (tmp = toml.charCodeAt(ctx.p)) !== 10 && (tmp !== 13 || toml.charCodeAt(ctx.p + 1) !== 10)) TomlError.x("each key-value declaration must be followed by an end-of-line", ctx);
812
- skipVoid(ctx);
813
- }
814
- return res;
815
- }
816
- //#endregion
817
- //#region src/cli/rls/rbac.ts
818
- /**
819
- * Where the helpers read roles and memberships: the flag, `rls.authorize`,
820
- * `rls.rbac.authorize`, then `database` with `rls.membershipSources`, with
821
- * `--rbac` or with a mapped memberships table, else `jwt`.
822
- */
823
- function resolveAuthorize(config, flags = {}) {
824
- const rls = config.rls;
825
- const explicit = flags.authorize ?? rls?.authorize ?? rls?.rbac?.authorize;
826
- if (explicit !== void 0) return explicit;
827
- if (rls?.membershipSources !== void 0 || flags.rbac === true) return "database";
828
- const memberships = flags.memberships ?? rls?.memberships;
829
- return Object.keys(memberships?.scopes ?? {}).length > 0 ? "database" : "jwt";
830
- }
831
- function parseRbacAuthorize(raw) {
832
- if (raw === void 0) return;
833
- if (raw === "database" || raw === "jwt") return raw;
834
- throw configError(`PermDock CLI: --authorize must be database or jwt, got '${raw}'`);
835
- }
836
- function hookUri(schema) {
837
- return `pg-functions://postgres/${schema}/custom_access_token_hook`;
838
- }
839
- function createEnum(schema, name, values) {
840
- const list = values.map((value) => quoteLiteral(value)).join(", ");
841
- return `do $$ begin
842
- create type ${quoteTable(`${schema}.${name}`)} as enum (${list});
843
- exception when duplicate_object then null;
844
- end $$;`;
845
- }
846
- /**
847
- * A read policy and `select` grant for `supabase_auth_admin` on a table the
848
- * hook reads.
849
- */
850
- function authAdminRead(table, label) {
851
- const t = quoteQualified(table);
852
- const policy = quoteIdent(`permdock_auth_admin_read_${label}`);
853
- return `grant select on table ${t} to supabase_auth_admin;
854
- drop policy if exists ${policy} on ${t};
855
- create policy ${policy} on ${t}
856
- as permissive for select
857
- to supabase_auth_admin
858
- using (true);`;
859
- }
860
- /**
861
- * Supabase's Custom Claims and RBAC scaffold on top of the PermDock helpers:
862
- * enums, `user_roles` and `authorize()` over the shared `role_permissions`. The
863
- * token hook comes only from `permdock supabase hook generate`, so one function
864
- * writes the claims. Policies never call `authorize()` per row; they call the
865
- * helpers. Never grants anything to `service_role`.
866
- */
867
- function rbacScaffold(policy, options) {
868
- const schema = options.schema;
869
- const q = (name) => quoteTable(`${schema}.${name}`);
870
- const s = quoteIdent(schema);
871
- const permissions = [...new Set(policy.grants.map((grant) => grant.permission.key))];
872
- const authorizeFn = authorizeSql({
873
- schema,
874
- authorize: options.authorize,
875
- ...options.scope === void 0 ? {} : { scope: options.scope },
876
- ...options.memberships === void 0 ? {} : { tenant: options.memberships },
877
- ...options.customRoles === void 0 ? {} : { customRoles: options.customRoles },
878
- ...options.context?.suspension === void 0 ? {} : { suspension: options.context.suspension }
879
- });
880
- return {
881
- head: `-- rbac scaffold (Supabase Custom Claims and RBAC)
882
- -- authorize: ${options.authorize}${options.authorize === "jwt" ? " (reads the hook claims; stale until the token refreshes)" : " (reads user_roles on every statement)"}
883
- -- the custom access token hook that writes user_role${options.authorize === "jwt" ? " and memberships" : ""}: permdock supabase hook generate
884
- ${schema === "public" ? "" : `create schema if not exists ${s};\n`}${createEnum(schema, "app_role", roleNames(policy))}
885
- ${createEnum(schema, "app_permission", permissions)}
886
-
887
- create table if not exists ${q("user_roles")} (
888
- user_id uuid not null references auth.users on delete cascade,
889
- role ${options.customRoles === void 0 ? q("app_role") : "text"} not null,
890
- primary key (user_id, role)
891
- );
892
-
893
- alter table ${q("user_roles")} enable row level security;
894
- revoke all on table ${q("user_roles")} from authenticated, anon, public;
895
- `,
896
- tail: authorizeFn,
897
- warnings: []
898
- };
899
- }
900
- //#endregion
901
- //#region src/cli/supabase-config.ts
902
- const SUPABASE_CONFIG = "supabase/config.toml";
903
- function table(value) {
904
- if (value === null || typeof value !== "object" || Array.isArray(value)) return;
905
- return value;
906
- }
907
- function strings(value) {
908
- return Array.isArray(value) ? value.filter((item) => typeof item === "string") : void 0;
909
- }
910
- /** `supabase/config.toml`, parsed; `undefined` when the project has none. */
911
- function readSupabaseConfig(cwd) {
912
- const file = join(cwd, SUPABASE_CONFIG);
913
- if (!existsSync(file)) return;
914
- let root;
915
- try {
916
- root = parse(readFileSync(file, "utf8"));
917
- } catch (error) {
918
- return {
919
- ok: false,
920
- error: describeError(error)
921
- };
922
- }
923
- const expiry = table(root["auth"])?.["jwt_expiry"];
924
- const paths = table(table(root["db"])?.["migrations"])?.["schema_paths"];
925
- const schemaPaths = strings(paths);
926
- const apiSchemas = strings(table(root["api"])?.["schemas"]);
927
- const hookTable = table(table(table(root["auth"])?.["hook"])?.["custom_access_token"]);
928
- const hookEnabled = hookTable?.["enabled"];
929
- const hookUriValue = hookTable?.["uri"];
930
- const pgDelta = table(table(root["experimental"])?.["pgdelta"]);
931
- const schemaPath = pgDelta?.["declarative_schema_path"];
932
- const enabled = pgDelta?.["enabled"];
933
- return {
934
- ok: true,
935
- config: {
936
- ...typeof expiry === "number" ? { jwtExpiry: expiry } : {},
937
- ...schemaPaths === void 0 ? {} : { schemaPaths },
938
- ...apiSchemas === void 0 ? {} : { apiSchemas },
939
- ...hookTable === void 0 ? {} : { customAccessTokenHook: {
940
- ...typeof hookEnabled === "boolean" ? { enabled: hookEnabled } : {},
941
- ...typeof hookUriValue === "string" ? { uri: hookUriValue } : {}
942
- } },
943
- ...pgDelta === void 0 ? {} : { pgDelta: {
944
- ...typeof enabled === "boolean" ? { enabled } : {},
945
- schemaDir: declarativeSchemaDir(schemaPath)
946
- } }
947
- }
948
- };
949
- }
950
- /**
951
- * `supabase/` joined with `declarative_schema_path`, which defaults to
952
- * `schemas`.
953
- */
954
- function declarativeSchemaDir(schemaPath) {
955
- return posix.join("supabase", typeof schemaPath === "string" ? schemaPath : "schemas").replace(/\/$/u, "");
956
- }
957
- /**
958
- * The parsed config, or `{}` when it is missing or does not parse (PD045
959
- * reports that).
960
- */
961
- function supabaseConfig(cwd) {
962
- const read = readSupabaseConfig(cwd);
963
- return read?.ok === true ? read.config : {};
964
- }
965
- /**
966
- * PD045: a `supabase/config.toml` the CLI cannot parse, so every check that
967
- * reads it falls back to defaults.
968
- */
969
- function pd045(cwd) {
970
- const read = readSupabaseConfig(cwd);
971
- if (read === void 0 || read.ok) return [];
972
- return [{
973
- code: "PD045",
974
- severity: "warning",
975
- message: `${SUPABASE_CONFIG} does not parse: ${read.error.replace(/\n[\s\S]*/u, "")}`,
976
- fix: `fix the TOML syntax in ${SUPABASE_CONFIG}; until then PermDock assumes Supabase's defaults for jwt_expiry, schema_paths and [experimental.pgdelta], and generates for pg-delta`
977
- }];
978
- }
979
- /**
980
- * PD074: `supabase.hook` is configured but `[auth.hook.custom_access_token]` in
981
- * `supabase/config.toml` does not enable the generated function, so a local
982
- * stack and every branch push issue tokens without memberships.
983
- */
984
- function pd074(cwd, config) {
985
- const hook = config.supabase?.hook;
986
- const read = readSupabaseConfig(cwd);
987
- if (hook === void 0 || read === void 0 || !read.ok) return [];
988
- const expected = hookUri(hook.schema ?? config.rls?.schema ?? "permdock");
989
- const found = read.config.customAccessTokenHook;
990
- const fix = `add to ${SUPABASE_CONFIG}:\n[auth.hook.custom_access_token]\nenabled = true\nuri = "${expected}"`;
991
- if (found?.enabled !== true) return [{
992
- code: "PD074",
993
- severity: "warning",
994
- message: `supabase.hook is configured but ${SUPABASE_CONFIG} does not set [auth.hook.custom_access_token] enabled = true, so Auth never calls the hook`,
995
- fix
996
- }];
997
- if (found.uri !== expected) return [{
998
- code: "PD074",
999
- severity: "warning",
1000
- message: `[auth.hook.custom_access_token] uri is ${found.uri ?? "missing"}, but the generated hook is ${expected}`,
1001
- fix: `set uri = "${expected}" in ${SUPABASE_CONFIG}`
1002
- }];
1003
- return [];
1004
- }
1005
- //#endregion
1006
- //#region src/cli/claims-schema.ts
1007
- /**
1008
- * The PermDock claims of `schemas/supabase-claims-v1.json` (its
1009
- * `permdockClaims` and `membership` definitions), self-contained so
1010
- * `supabase.hook.validate` can inline it into the hook for pg_jsonschema.
1011
- */
1012
- const PERMDOCK_CLAIMS_SCHEMA = {
1013
- $schema: "https://json-schema.org/draft/2020-12/schema",
1014
- $ref: "#/$defs/permdockClaims",
1015
- $defs: {
1016
- permdockClaims: {
1017
- type: "object",
1018
- properties: {
1019
- user_role: {
1020
- description: "Global roles: one name, a list, or null for none.",
1021
- anyOf: [
1022
- { type: "string" },
1023
- {
1024
- type: "array",
1025
- items: { type: "string" }
1026
- },
1027
- { type: "null" }
1028
- ]
1029
- },
1030
- roles: {
1031
- type: "array",
1032
- items: { type: "string" }
1033
- },
1034
- memberships: {
1035
- type: "array",
1036
- items: { $ref: "#/$defs/membership" }
1037
- },
1038
- memberships_truncated: {
1039
- description: "true when the size budget cut memberships or attrs.",
1040
- type: "boolean"
1041
- },
1042
- team_ids: {
1043
- description: "The uuid of every team the user belongs to (supabase.hook.teams), cut by the memberships budget.",
1044
- type: "array",
1045
- items: { type: "string" }
1046
- },
1047
- tenant_id: {
1048
- description: "The active tenant (the default rls.tenantClaim): the canonical text of one instance of the first scope.",
1049
- type: "string"
1050
- },
1051
- attrs: {
1052
- description: "Allow-listed server-owned attributes, read as principal.claims.attrs.<key>.",
1053
- type: "object"
1054
- },
1055
- authz_ver: {
1056
- description: "The principal's authorization version.",
1057
- type: "integer"
1058
- }
1059
- }
1060
- },
1061
- membership: {
1062
- type: "object",
1063
- required: ["roles"],
1064
- properties: {
1065
- scope: { type: "string" },
1066
- id: {
1067
- description: "Canonical text of the scope instance id (uuid::text for a uuid column); compared exactly, never lower-cased.",
1068
- type: "string"
1069
- },
1070
- within: {
1071
- description: "The id of every ancestor scope instance, by scope name.",
1072
- type: "object",
1073
- additionalProperties: { type: "string" }
1074
- },
1075
- on: {
1076
- type: "object",
1077
- required: ["resource", "id"],
1078
- properties: {
1079
- resource: { type: "string" },
1080
- id: { type: "string" }
1081
- }
1082
- },
1083
- tenant: { type: "string" },
1084
- team: { type: "string" },
1085
- roles: {
1086
- type: "array",
1087
- minItems: 1,
1088
- items: { type: "string" }
1089
- },
1090
- via: { type: "string" },
1091
- expires_at: {
1092
- description: "NumericDate (RFC 7519): seconds since the epoch.",
1093
- type: "number"
1094
- },
1095
- granted_by: { type: "string" },
1096
- reason: { type: "string" },
1097
- member: {
1098
- description: "The subgroup a membership source's group fills.",
1099
- type: "object",
1100
- required: ["group"],
1101
- properties: { group: {
1102
- type: "string",
1103
- minLength: 1
1104
- } }
1105
- },
1106
- managed_by: { const: "idp" },
1107
- entitlements: {
1108
- type: "array",
1109
- items: { type: "string" }
1110
- },
1111
- keep: {
1112
- description: "Set when the instance or an ancestor is suspended: the permission keys the membership still grants.",
1113
- type: "array",
1114
- items: {
1115
- type: "string",
1116
- minLength: 1
1117
- }
1118
- },
1119
- grants: {
1120
- description: "Custom roles in compact form, read by the helpers in jwt mode.",
1121
- type: "object"
1122
- }
1123
- },
1124
- anyOf: [
1125
- { required: ["scope", "id"] },
1126
- { required: ["tenant"] },
1127
- { required: ["team"] },
1128
- { required: ["on"] }
1129
- ]
1130
- }
1131
- }
1132
- };
1133
- //#endregion
1134
- //#region src/cli/supabase-hook/claims.ts
1135
- const CLAIM_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/u;
1136
- const PROTOTYPE_KEYS = /* @__PURE__ */ new Set([
1137
- "__proto__",
1138
- "constructor",
1139
- "prototype"
1140
- ]);
1141
- const USER_EDITABLE = /^(raw_)?user_meta(_)?data$/iu;
1142
- /**
1143
- * Splits `supabase.hook.attrs` into table columns and `app_metadata` keys and
1144
- * lists what cannot be compiled: `user_metadata` (the user can edit it), a
1145
- * direct `auth.users` column, an unsafe or prototype key, a duplicate key, or a
1146
- * table column without a table.
1147
- */
1148
- function attrsPlan(attrs) {
1149
- const errors = [];
1150
- const columns = [];
1151
- const meta = [];
1152
- const seen = /* @__PURE__ */ new Set();
1153
- if (attrs.table?.replaceAll("\"", "").toLowerCase() === "auth.users") errors.push("supabase.hook.attrs.table cannot be auth.users: list app_metadata.<key> entries instead");
1154
- for (const entry of attrs.columns) {
1155
- const [head = "", ...rest] = entry.split(".");
1156
- const isMeta = head === "app_metadata" || head === "raw_app_meta_data";
1157
- const key = isMeta ? rest.join(".") : entry;
1158
- if (USER_EDITABLE.test(head) || USER_EDITABLE.test(key) || /user_?meta/iu.test(entry)) {
1159
- errors.push(`supabase.hook.attrs lists ${entry}: user_metadata is user-editable and never becomes a claim`);
1160
- continue;
1161
- }
1162
- if (!CLAIM_KEY.test(key) || PROTOTYPE_KEYS.has(key)) {
1163
- errors.push(`supabase.hook.attrs lists ${entry}: a key must match ${CLAIM_KEY.source} and not be a prototype key`);
1164
- continue;
1165
- }
1166
- if (seen.has(key)) {
1167
- errors.push(`supabase.hook.attrs names the key ${key} twice`);
1168
- continue;
1169
- }
1170
- seen.add(key);
1171
- if (isMeta) meta.push(key);
1172
- else columns.push(key);
1173
- }
1174
- if (columns.length > 0 && attrs.table === void 0) errors.push(`supabase.hook.attrs lists ${columns.join(", ")} without a table`);
1175
- return {
1176
- ...attrs.table === void 0 ? {} : { table: attrs.table },
1177
- id: attrs.id ?? "id",
1178
- columns,
1179
- meta,
1180
- errors
1181
- };
1182
- }
1183
- /**
1184
- * Claim names `supabase.hook.claims` cannot write: the ones this hook owns
1185
- * (plus the tenant claim) and the ones Supabase Auth issues.
1186
- */
1187
- const RESERVED_CLAIMS = /* @__PURE__ */ new Set([
1188
- "roles",
1189
- "user_role",
1190
- "memberships",
1191
- "memberships_truncated",
1192
- "team_ids",
1193
- "attrs",
1194
- "authz_ver",
1195
- "sub",
1196
- "aud",
1197
- "role",
1198
- "exp",
1199
- "iat",
1200
- "iss",
1201
- "aal",
1202
- "amr",
1203
- "session_id",
1204
- "is_anonymous",
1205
- "email",
1206
- "phone",
1207
- "app_metadata",
1208
- "user_metadata"
1209
- ]);
1210
- const CLAIM_FUNCTION = /^[A-Za-z_][A-Za-z0-9_]*\.[A-Za-z_][A-Za-z0-9_]*$/u;
1211
- /**
1212
- * Checks `supabase.hook.claims`: each name is a safe claim key outside
1213
- * {@link RESERVED_CLAIMS} and the tenant claim, each function is
1214
- * schema-qualified (the hook runs with an empty `search_path`).
1215
- */
1216
- function extraClaimsPlan(claims, tenantClaim) {
1217
- const errors = [];
1218
- const planned = [];
1219
- for (const [claim, fn] of Object.entries(claims ?? {})) {
1220
- if (!CLAIM_KEY.test(claim) || PROTOTYPE_KEYS.has(claim)) {
1221
- errors.push(`supabase.hook.claims names ${claim}: a claim must match ${CLAIM_KEY.source} and not be a prototype key`);
1222
- continue;
1223
- }
1224
- if (RESERVED_CLAIMS.has(claim) || claim === tenantClaim) {
1225
- errors.push(`supabase.hook.claims names ${claim}, which PermDock or Supabase Auth writes`);
1226
- continue;
1227
- }
1228
- if (typeof fn !== "string" || !CLAIM_FUNCTION.test(fn)) {
1229
- errors.push(`supabase.hook.claims.${claim} must be a schema-qualified function name such as public.feature_claims`);
1230
- continue;
1231
- }
1232
- planned.push({
1233
- claim,
1234
- fn
1235
- });
1236
- }
1237
- return {
1238
- claims: planned,
1239
- errors
1240
- };
1241
- }
1242
- function beforePlan(before) {
1243
- const list = before === void 0 ? [] : typeof before === "string" ? [before] : before;
1244
- const bad = list.filter((fn) => typeof fn !== "string" || !CLAIM_FUNCTION.test(fn));
1245
- 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(", ")})`);
1246
- return [...new Set(list)];
1247
- }
1248
- function beforeSql(before) {
1249
- return before.map((fn) => `
1250
- checked := ${quoteTable(fn)}(event);
1251
- if checked is null or jsonb_typeof(checked) is distinct from 'object' then
1252
- return jsonb_build_object('error', jsonb_build_object('http_code', 500, 'message', ${quoteLiteral(`${fn} returned no event`)}));
1253
- end if;
1254
- if checked ? 'error' then
1255
- return checked;
1256
- end if;
1257
- event := checked;`).join("").concat(before.length === 0 ? "" : "\n claims := event -> 'claims';");
1258
- }
1259
- /**
1260
- * `hook.validate`: the claims the hook writes, dropped together when they do
1261
- * not match `supabase-claims-v1.json`, so a bad claim denies instead of failing
1262
- * sign-in. `hook.claims` entries belong to other packages and stay.
1263
- */
1264
- function validateSql(parts) {
1265
- if (parts.hook.validate !== true) return "";
1266
- const keys = /* @__PURE__ */ new Set([
1267
- "user_role",
1268
- "roles",
1269
- "memberships",
1270
- "memberships_truncated",
1271
- ...parts.hook.teams === void 0 ? [] : ["team_ids"],
1272
- "attrs",
1273
- "authz_ver",
1274
- parts.tenantClaim
1275
- ]);
1276
- return `
1277
- if not extensions.jsonb_matches_schema(${quoteLiteral(JSON.stringify(PERMDOCK_CLAIMS_SCHEMA))}::json, claims) then
1278
- claims := claims${[...keys].map((key) => ` - ${quoteLiteral(key)}`).join("")};
1279
- end if;`;
1280
- }
1281
- function validateGrantsSql(parts) {
1282
- return parts.hook.validate === true ? `
1283
- create extension if not exists pg_jsonschema with schema extensions;
1284
- grant usage on schema extensions to supabase_auth_admin;
1285
- grant execute on function extensions.jsonb_matches_schema(json, jsonb) to supabase_auth_admin;` : "";
1286
- }
1287
- /**
1288
- * Fails the migration when a client role can write an `attrs` column: a claim
1289
- * the user can set is not a server-owned attribute.
1290
- */
1291
- function attrsGuardSql(plan) {
1292
- if (plan?.table === void 0 || plan.columns.length === 0) return "";
1293
- const target = quoteLiteral(quoteQualified(plan.table));
1294
- return `-- attrs must be server-owned: refuse columns anon or authenticated can insert or update
1295
- do $$
1296
- begin
1297
- if exists (
1298
- select 1
1299
- from (values ${plan.columns.map((column) => `(${quoteLiteral(column)})`).join(", ")}) c(name)
1300
- cross join (values ('anon'), ('authenticated')) r(role)
1301
- where has_column_privilege(r.role, ${target}, c.name, 'INSERT')
1302
- or has_column_privilege(r.role, ${target}, c.name, 'UPDATE')
1303
- ) then
1304
- 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}
1305
- using errcode = '42501';
1306
- end if;
1307
- end
1308
- $$;`;
1309
- }
1310
- function permdockClaim(name, budget = false) {
1311
- return {
1312
- name,
1313
- source: "permdock",
1314
- budget
1315
- };
1316
- }
1317
- function hookClaims(parts) {
1318
- return [
1319
- permdockClaim("user_role"),
1320
- permdockClaim("roles"),
1321
- permdockClaim("memberships", true),
1322
- permdockClaim("memberships_truncated"),
1323
- permdockClaim(parts.tenantClaim),
1324
- ...parts.hook.teams === void 0 ? [] : [permdockClaim("team_ids", true)],
1325
- ...parts.attrs === void 0 ? [] : [permdockClaim("attrs", true)],
1326
- ...parts.version ? [permdockClaim("authz_ver")] : [],
1327
- ...parts.extra.map((entry) => ({
1328
- name: entry.claim,
1329
- source: entry.fn,
1330
- budget: false
1331
- }))
1332
- ];
1333
- }
1334
- //#endregion
1335
- //#region src/cli/sql/declarative.ts
1336
- /**
1337
- * A migration's SQL as a declarative schema file: pg-delta diffs the file
1338
- * against the database itself, so a `drop trigger if exists` or `drop policy if
1339
- * exists` before its `create` is an error, and a trigger is `create or replace
1340
- * trigger`. A constraint trigger stays `create constraint trigger`, because
1341
- * pg-delta has no `create or replace constraint trigger`. A policy keeps its
1342
- * plain `create policy`.
1343
- */
1344
- function declarativeSql(sql) {
1345
- return sql.replaceAll(/^drop (?:trigger|policy) if exists [^;\n]+;\n/gmu, "").replaceAll(/^create trigger /gmu, "create or replace trigger ");
1346
- }
1347
- //#endregion
1348
- //#region src/cli/supabase-schemas.ts
1349
- const MODES = [
1350
- "pg-delta",
1351
- "migra",
1352
- "migrations"
1353
- ];
1354
- function isSupabaseSchemas(value) {
1355
- return MODES.some((mode) => mode === value);
1356
- }
1357
- /** The `--schemas` refusal, or `undefined` when the value is one of the modes. */
1358
- function schemasRefusal(command, value) {
1359
- return value === void 0 || isSupabaseSchemas(value) ? void 0 : `${command} --schemas must be ${MODES.join(", ")} (got ${value})`;
1360
- }
1361
- /**
1362
- * `--schemas`, else `supabase.schemas`, else `migra` when `config.toml` sets
1363
- * `[experimental.pgdelta] enabled = false`, else `pg-delta`: the default of new
1364
- * Supabase projects and of the next Supabase CLI major.
1365
- */
1366
- function resolveSchemas(cwd, config, flag) {
1367
- const toml = supabaseConfig(cwd).pgDelta;
1368
- const mode = flag ?? config.supabase?.schemas ?? (toml?.enabled === false ? "migra" : "pg-delta");
1369
- switch (mode) {
1370
- case "pg-delta": return {
1371
- mode,
1372
- schemaDir: toml?.schemaDir ?? declarativeSchemaDir()
1373
- };
1374
- case "migra":
1375
- case "migrations": return { mode };
1376
- default: return mode;
1377
- }
1378
- }
1379
- //#endregion
1380
- //#region src/cli/supabase-setup.ts
1381
- const HELPER_NAME = /^(?:permdock_has|permitted_[a-z][a-z0-9_]*_ids|member_[a-z][a-z0-9_]*_ids(?:_for)?)$/u;
1382
- function escape(text) {
1383
- return text.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`);
1384
- }
1385
- /**
1386
- * The helper functions `sql` creates in `schema`; unqualified names count for
1387
- * `public`.
1388
- */
1389
- function helpersDefined(sql, schema) {
1390
- const qualifier = schema === "public" ? String.raw`(?:(?:"public"|public)\.)?` : String.raw`(?:"${escape(schema)}"|${escape(schema)})\.`;
1391
- const create = new RegExp(String.raw`\bcreate\s+(?:or\s+replace\s+)?function\s+${qualifier}"?([a-z_][a-z0-9_]*)"?\s*\(`, "giu");
1392
- const names = /* @__PURE__ */ new Set();
1393
- for (const match of sql.matchAll(create)) {
1394
- const name = (match[1] ?? "").toLowerCase();
1395
- if (HELPER_NAME.test(name)) names.add(name);
1396
- }
1397
- return names;
1398
- }
1399
- /**
1400
- * SQL files that may hold the generated helpers: `rls.out` (else `rls.sql`; its
1401
- * `helpers` part when it has `{part}`), pg-delta's helpers part, the SQL files
1402
- * next to the hook, and the migration folders, not the hook itself.
1403
- */
1404
- function helperSources(cwd, config, hookOut, helpersSchema) {
1405
- const hook = resolve(cwd, hookOut);
1406
- const files = new Set(sqlFiles(cwd, config.doctor?.migrations ?? MIGRATION_DIRS));
1407
- const out = config.rls?.out ?? "rls.sql";
1408
- const schemas = resolveSchemas(cwd, config);
1409
- const candidates = [partPath(out, "helpers")];
1410
- if (schemas.mode === "pg-delta" && !out.includes("{part}")) candidates.push(pgDeltaPath(schemas.schemaDir, "helpers", helpersSchema));
1411
- for (const candidate of candidates) {
1412
- const path = resolve(cwd, candidate);
1413
- if (path.endsWith(".sql") && existsSync(path)) files.add(path);
1414
- }
1415
- const beside = dirname(hook);
1416
- if (existsSync(beside)) {
1417
- for (const entry of readdirSync(beside, { withFileTypes: true })) if (entry.isFile() && entry.name.endsWith(".sql")) files.add(join(beside, entry.name));
1418
- }
1419
- files.delete(hook);
1420
- return [...files];
1421
- }
1422
- function missingHelpersInFiles(cwd, config, manifest) {
1423
- const found = /* @__PURE__ */ new Set();
1424
- for (const file of helperSources(cwd, config, manifest.hook.out, manifest.helpers.schema)) for (const name of helpersDefined(readFileSync(file, "utf8"), manifest.helpers.schema)) found.add(name);
1425
- return manifest.helpers.functions.filter((name) => !found.has(name));
1426
- }
1427
- async function missingHelpersInDb(db, manifest, connect = pgConnector("permdock supabase hook generate --db-url-stdin")) {
1428
- const client = await connect(db);
1429
- try {
1430
- const result = await client.query(`select p.proname from pg_proc p join pg_namespace n on n.oid = p.pronamespace
1431
- where n.nspname = $1 and p.proname = any($2::text[])`, [manifest.helpers.schema, [...manifest.helpers.functions]]);
1432
- const found = new Set(result.rows.map((row) => row["proname"]));
1433
- return manifest.helpers.functions.filter((name) => !found.has(name));
1434
- } finally {
1435
- await client.end();
1436
- }
1437
- }
1438
- function missingHelpersMessage(manifest, missing) {
1439
- return `PD039 schema ${manifest.helpers.schema} has no ${missing.join(", ")}: the hook's claims are read by these helpers; run permdock rls generate and apply its migration`;
1440
- }
1441
- /**
1442
- * Bytes of JSON of each extra claim in the largest sample, for claims that pass
1443
- * the budget.
1444
- */
1445
- function oversizedClaims(samples, manifest) {
1446
- const encoder = new TextEncoder();
1447
- const oversized = [];
1448
- for (const claim of manifest.claims) {
1449
- if (claim.source === "permdock") continue;
1450
- let bytes = 0;
1451
- for (const sample of samples) {
1452
- if (sample === null || typeof sample !== "object") continue;
1453
- const value = Object.hasOwn(sample, claim.name) ? sample[claim.name] : void 0;
1454
- if (value !== void 0) bytes = Math.max(bytes, encoder.encode(JSON.stringify(value)).byteLength);
1455
- }
1456
- if (bytes > manifest.budget.bytes) oversized.push({
1457
- name: claim.name,
1458
- bytes
1459
- });
1460
- }
1461
- return oversized;
1462
- }
1463
- /** `memberships[i]` entries `subjectFromSupabase` drops, per sample index. */
1464
- function droppedMemberships(samples) {
1465
- const out = [];
1466
- for (const [index, sample] of samples.entries()) {
1467
- if (sample === null || typeof sample !== "object") continue;
1468
- const claim = Object.hasOwn(sample, "memberships") ? sample["memberships"] : void 0;
1469
- const { dropped } = readMemberships(claim);
1470
- if (dropped.length > 0) out.push({
1471
- sample: index,
1472
- entries: dropped
1473
- });
1474
- }
1475
- return out;
1476
- }
1477
- function pd039(input) {
1478
- const findings = [];
1479
- const missing = missingHelpersInFiles(input.cwd, input.config, input.manifest);
1480
- if (missing.length > 0) findings.push({
1481
- code: "PD039",
1482
- severity: "warning",
1483
- message: missingHelpersMessage(input.manifest, missing).slice(6),
1484
- fix: "run permdock rls generate, or set rls.out to the file that holds the helpers (with {part} for --split output) or write them next to the hook"
1485
- });
1486
- const fixture = input.config.doctor?.claims;
1487
- if (fixture !== void 0) {
1488
- const parsed = readClaimsFixture(resolve(input.cwd, fixture));
1489
- if (!parsed.ok) {
1490
- findings.push({
1491
- code: "PD039",
1492
- severity: "warning",
1493
- message: `doctor.claims ${fixture} is not a JSON file doctor can read (${parsed.message}), so the claim budget went unchecked`,
1494
- fix: "point doctor.claims at a JSON array of sample claims"
1495
- });
1496
- return findings;
1497
- }
1498
- const samples = Array.isArray(parsed.value) ? parsed.value : [];
1499
- for (const claim of oversizedClaims(samples, input.manifest)) findings.push({
1500
- code: "PD039",
1501
- severity: "warning",
1502
- message: `claim ${claim.name} is ${String(claim.bytes)} bytes of JSON in ${fixture}, more than the ${String(input.manifest.budget.bytes)}-byte memberships budget`,
1503
- fix: "return less from the claim function, or read the data per request instead of from the token"
1504
- });
1505
- for (const { sample, entries } of droppedMemberships(samples)) findings.push({
1506
- code: "PD039",
1507
- severity: "warning",
1508
- message: `sample ${String(sample)} in ${fixture} has memberships ${entries.map((entry) => `[${String(entry)}]`).join(", ")} that subjectFromSupabase drops (membership-dropped)`,
1509
- fix: "emit { scope, id, roles } (or tenant, team or on) with a non-empty roles array for each entry"
1510
- });
1511
- }
1512
- return findings;
1513
- }
1514
- function readClaimsFixture(path) {
1515
- try {
1516
- return {
1517
- ok: true,
1518
- value: JSON.parse(readFileSync(path, "utf8"))
1519
- };
1520
- } catch (error) {
1521
- return {
1522
- ok: false,
1523
- message: error instanceof Error ? error.message : String(error)
1524
- };
1525
- }
1526
- }
1527
- //#endregion
1528
- //#region src/cli/supabase-hook/memberships.ts
1529
- function memberForPlan(input) {
1530
- const memberFor = input.scopes.map((scope) => scope.name).filter((name) => hasMemberFor({
1531
- dialect: "supabase",
1532
- ...input
1533
- }, name));
1534
- const holders = memberFor.filter((name) => hasPermittedUsers(input, name));
1535
- const entries = /* @__PURE__ */ new Map();
1536
- for (const name of memberFor) {
1537
- const mapped = memberForTable(input, name);
1538
- const found = mapped === void 0 ? memberForSources(input, name).map((source) => source.sql.manifest) : [mappedMembership(mapped, input.scopes, name)];
1539
- for (const entry of found) entries.set(JSON.stringify(entry), entry);
1540
- }
1541
- return {
1542
- memberFor,
1543
- holders,
1544
- memberships: [...entries.values()]
1545
- };
1546
- }
1547
- /**
1548
- * An `rls.memberships` table in the manifest's `tableMembershipSource` /
1549
- * `junctionMembershipSource` shape, for scope `name`.
1550
- */
1551
- function mappedMembership(mapped, scopes, name) {
1552
- const id = scopeColumn(mapped, scopes, name) ?? "";
1553
- const within = {};
1554
- for (const ancestor of scopeChain(scopes, name).slice(1)) {
1555
- const column = scopeColumn(mapped, scopes, ancestor);
1556
- if (column !== void 0) within[ancestor] = column;
1557
- }
1558
- const role = memberRoleOf(mapped);
1559
- const columns = [
1560
- mapped.user,
1561
- id,
1562
- ...role.columns,
1563
- ...Object.values(within),
1564
- ...typeof mapped.via === "string" ? [mapped.via] : [],
1565
- ...mapped.expiresAt === void 0 ? [] : [mapped.expiresAt],
1566
- ...mapped.disabledAt === void 0 ? [] : [mapped.disabledAt]
1567
- ];
1568
- return {
1569
- table: qualifySqlTable(mapped.table),
1570
- user: { column: mapped.user },
1571
- scope: { value: name },
1572
- id: { column: id },
1573
- role: roleManifest(role),
1574
- ...Object.keys(within).length === 0 ? {} : { within: { columns: within } },
1575
- ...mapped.via === void 0 ? {} : { via: typeof mapped.via === "string" ? { column: mapped.via } : { value: mapped.via.value } },
1576
- ...mapped.expiresAt === void 0 ? {} : { expiresAt: { column: mapped.expiresAt } },
1577
- ...mapped.disabledAt === void 0 ? {} : { disabledAt: { column: mapped.disabledAt } },
1578
- columns: [...new Set(columns)]
1579
- };
1580
- }
1581
- function positiveInteger(value, label) {
1582
- const number = typeof value === "string" ? Number(value) : value;
1583
- if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) throw configError(`PermDock CLI: ${label} must be a positive integer`);
1584
- return number;
1585
- }
1586
- /**
1587
- * Where the hook reads the active first-scope id: `supabase.hook.activeFrom`,
1588
- * or `app_metadata.active_<root>` by default.
1589
- */
1590
- function activeSource(input, root) {
1591
- const spec = input ?? `app_metadata.active_${root}`;
1592
- if (typeof spec === "string" && spec.startsWith("app_metadata.")) {
1593
- const key = spec.slice(13);
1594
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(key)) throw configError(`PermDock CLI: unsafe app_metadata key '${key}'`);
1595
- return { appMetadata: key };
1596
- }
1597
- if (typeof spec !== "string") return {
1598
- table: spec.table,
1599
- column: spec.column,
1600
- id: spec.id ?? "id"
1601
- };
1602
- const dot = spec.lastIndexOf(".");
1603
- if (dot <= 0) throw configError(`PermDock CLI: --active-from must be app_metadata.<key> or <table>.<column>, got '${spec}'`);
1604
- return {
1605
- table: spec.slice(0, dot),
1606
- column: spec.slice(dot + 1),
1607
- id: "id"
1608
- };
1609
- }
1610
- /**
1611
- * SQL for the active first-scope id, as text, for user `uid`; a table source
1612
- * compares its id column with `v_active_user`, declared as `userType`.
1613
- */
1614
- function activeFromSql(input, root) {
1615
- const from = activeSource(input, root);
1616
- if ("appMetadata" in from) return { sql: `claims -> 'app_metadata' ->> ${quoteLiteral(from.appMetadata)}` };
1617
- return {
1618
- sql: `(select a.${quoteIdent(from.column)}::text from ${quoteQualified(from.table)} a where a.${quoteIdent(from.id)} = v_active_user)`,
1619
- userType: `${quoteQualified(from.table)}.${quoteIdent(from.id)}%type`
1620
- };
1621
- }
1622
- /**
1623
- * One variable per user-keyed table `membership_entries_for` reads, holding the
1624
- * user (a uuid, as Supabase Auth issues) as that column's type, so each lookup
1625
- * compares the column uncast and its index applies.
1626
- */
1627
- function typedSourceUsers(parts) {
1628
- return parts.sources.map((source, index) => `\n v_user_${String(index)} ${source.sql.userType} := p_user;`).join("");
1629
- }
1630
- /**
1631
- * The remaining user-keyed variables of the hook: the attribute row and the
1632
- * active-tenant row, each as its column's type.
1633
- */
1634
- function typedUsers(parts) {
1635
- 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("");
1636
- }
1637
- function checkSources(parts) {
1638
- if (parts.sources.length === 0) throw configError("PermDock CLI: supabase.hook.memberships needs at least one tableMembershipSource, junctionMembershipSource or blockMembershipSource source");
1639
- for (const source of parts.sources) {
1640
- 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");
1641
- const scope = source.sql.scope;
1642
- if (scope === void 0) continue;
1643
- 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`);
1644
- const chain = scopeChain(parts.scopes, scope);
1645
- const holds = new Set(source.sql.holds ?? [scope]);
1646
- const missing = chain.filter((ancestor) => !holds.has(ancestor));
1647
- 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`);
1648
- }
1649
- }
1650
- function entriesSql(parts) {
1651
- const tenant = `case when s.scope = ${quoteLiteral(parts.root)} then s.id else s.within ->> ${quoteLiteral(parts.root)} end`;
1652
- return parts.sources.map((source, index) => `select ${String(index)} as ord,
1653
- (${tenant}) as tenant,
1654
- jsonb_strip_nulls(jsonb_build_object(
1655
- 'scope', s.scope, 'id', s.id, 'within', s.within, 'roles', s.roles, 'via', s.via,
1656
- 'expires_at', s.expires_at, 'granted_by', s.granted_by, 'reason', s.reason,
1657
- 'member', case when s.member_group is not null then jsonb_build_object('group', s.member_group) end,
1658
- 'managed_by', s.managed_by, 'entitlements', s.seats${source.sql.keeps ? ", 'keep', s.keep" : ""}
1659
- )) as entry
1660
- from (
1661
- ${source.sql.select(`v_user_${String(index)}`).replaceAll(/^/gmu, " ")}
1662
- ) s`).join("\nunion all\n");
1663
- }
1664
- //#endregion
1665
- //#region src/cli/supabase-hook/entries.ts
1666
- const MEMBERSHIP_ENTRIES_FOR = "membership_entries_for";
1667
- const GLOBAL_ROLES_FOR = "global_roles_for";
1668
- function qualified(parts, name) {
1669
- return `${quoteIdent(parts.schema)}.${name}`;
1670
- }
1671
- /**
1672
- * `membership_entries_for(p_user uuid) returns table(ord int, entry jsonb)`:
1673
- * every membership entry the hook and `subject_for` read, one row per entry in
1674
- * the shape of a token's `memberships` claim. Both callers order and budget the
1675
- * rows themselves; the function never truncates. `security invoker`, so the
1676
- * caller's table reads apply.
1677
- */
1678
- function membershipEntriesSql(parts) {
1679
- const fn = qualified(parts, MEMBERSHIP_ENTRIES_FOR);
1680
- return `-- the membership entries the hook and subject_for read for p_user; no client role may execute it
1681
- create or replace function ${fn}(p_user uuid)
1682
- returns table (ord integer, entry jsonb)
1683
- language plpgsql
1684
- stable
1685
- set search_path = ''
1686
- as $$
1687
- #variable_conflict use_column
1688
- declare${typedSourceUsers(parts)}
1689
- begin
1690
- return query
1691
- select x.ord, x.entry
1692
- from (
1693
- ${entriesSql(parts).replaceAll(/^/gmu, " ")}
1694
- ) x;
1695
- end;
1696
- $$;
1697
- revoke execute on function ${fn}(uuid) from public, anon, authenticated;`;
1698
- }
1699
- /**
1700
- * `global_roles_for(p_user uuid) returns jsonb`: the sorted, distinct global
1701
- * roles of `p_user` as a json array, for the hook's `roles` and `user_role`
1702
- * claims and for `subject_for`. Empty without a roles source.
1703
- */
1704
- function globalRolesSql(parts) {
1705
- const rows = parts.roles;
1706
- if (rows === void 0) return "";
1707
- const fn = qualified(parts, GLOBAL_ROLES_FOR);
1708
- return `-- the global roles of p_user as a json array; no client role may execute it
1709
- create or replace function ${fn}(p_user uuid)
1710
- returns jsonb
1711
- language plpgsql
1712
- stable
1713
- set search_path = ''
1714
- as $$
1715
- declare
1716
- v_roles_user ${quoteQualified(rows.table)}.${quoteIdent(rows.user)}%type := p_user;
1717
- held jsonb;
1718
- begin
1719
- select coalesce(jsonb_agg(distinct ${rows.roleSql} order by ${rows.roleSql}) filter (where ${rows.roleSql} is not null), '[]'::jsonb)
1720
- into held
1721
- from ${rows.from}
1722
- where ${rows.userSql} = v_roles_user;
1723
- return held;
1724
- end;
1725
- $$;
1726
- revoke execute on function ${fn}(uuid) from public, anon, authenticated;`;
1727
- }
1728
- /**
1729
- * Execute on both readers for the invoker hook, which runs as
1730
- * `supabase_auth_admin`.
1731
- */
1732
- function entriesGrantsSql(parts) {
1733
- return [MEMBERSHIP_ENTRIES_FOR, ...parts.roles === void 0 ? [] : [GLOBAL_ROLES_FOR]].map((name) => `\ngrant execute on function ${qualified(parts, name)}(uuid) to supabase_auth_admin;`).join("");
1734
- }
1735
- /** The `held` assignment, from `global_roles_for` or an empty array. */
1736
- function heldSql(parts, user) {
1737
- return parts.roles === void 0 ? ` held := '[]'::jsonb;` : ` held := ${qualified(parts, GLOBAL_ROLES_FOR)}(${user});`;
1738
- }
1739
- /** The tenant id of an entry, as the hook orders by it. */
1740
- function entryTenantSql(parts, alias) {
1741
- const root = quoteLiteral(parts.root);
1742
- return `case when ${alias}.entry ->> 'scope' = ${root} then ${alias}.entry ->> 'id' else ${alias}.entry -> 'within' ->> ${root} end`;
1743
- }
1744
- //#endregion
1745
- //#region src/cli/supabase-hook/api.ts
1746
- const SUBJECT_FOR = "subject_for";
1747
- const PERMDOCK_SUBJECT = "permdock_subject";
1748
- /**
1749
- * `subject_for(p_user uuid) returns jsonb`: what the hook would put in a token
1750
- * for `p_user`, from the same membership, role, suspension and version reads,
1751
- * plus the custom roles the user holds when `database` mode keeps them in
1752
- * tables. A backend that only has PostgREST (`postgrestSources`) builds a
1753
- * subject for an acting user or a job from it. Naming the user is why no client
1754
- * role may execute it.
1755
- */
1756
- function subjectForSql(parts, config) {
1757
- const schema = quoteIdent(parts.schema);
1758
- const fn = `${schema}.${SUBJECT_FOR}`;
1759
- const roles = heldSql(parts, "uid");
1760
- const suspended = parts.users === void 0 ? "" : `
1761
- if not ${activeRowSql(parts.users, "uid")} then
1762
- return jsonb_build_object('id', uid::text, 'active', false);
1763
- end if;`;
1764
- const version = parts.version ? `
1765
- select v.version into ver from ${schema}.${quoteIdent(AUTHZ_VERSION_TABLE)} v where v.user_id = uid;
1766
- ver := coalesce(ver, 0);` : "";
1767
- const teamsConfig = parts.hook.teams;
1768
- const teams = teamsConfig === void 0 ? "" : `
1769
- select coalesce(jsonb_agg(to_jsonb(t.${quoteIdent(teamsConfig.team)}::text) order by t.${quoteIdent(teamsConfig.team)}), '[]'::jsonb)
1770
- into team_ids
1771
- from ${quoteQualified(teamsConfig.table)} t
1772
- where t.${quoteIdent(teamsConfig.user)} = uid;
1773
- if team_ids <> '[]'::jsonb then
1774
- claims := jsonb_set(claims, '{team_ids}', team_ids);
1775
- end if;`;
1776
- const extra = parts.extra.map((entry) => `
1777
- extra := ${quoteTable(entry.fn)}(uid);
1778
- if extra is not null then
1779
- claims := jsonb_set(claims, ${quoteLiteral(`{${entry.claim}}`)}, extra);
1780
- end if;`).join("");
1781
- const custom = customRolesOn(config.rls) && resolveAuthorize(config) === "database" ? customRolesOfSql(parts) : "";
1782
- return `-- the subject the hook would mint for p_user, for a backend acting for a stored user; no client role may execute it
1783
- create or replace function ${fn}(p_user uuid)
1784
- returns jsonb
1785
- language plpgsql
1786
- stable
1787
- security definer
1788
- set search_path = ''
1789
- as $$
1790
- declare
1791
- uid uuid := p_user;
1792
- held jsonb;
1793
- memberships jsonb;
1794
- custom jsonb := '[]'::jsonb;
1795
- ver bigint;
1796
- claims jsonb := '{}'::jsonb;${teamsConfig === void 0 ? "" : "\n team_ids jsonb := '[]'::jsonb;"}${parts.extra.length === 0 ? "" : "\n extra jsonb;"}${typedUsers(parts)}
1797
- begin
1798
- if uid is null or not exists (select 1 from auth.users u where u.id = uid) then
1799
- return null;
1800
- end if;${suspended}
1801
- ${roles}
1802
- select coalesce(jsonb_agg(x.entry order by x.ord, x.entry ->> 'scope', x.entry ->> 'id', x.entry::text), '[]'::jsonb)
1803
- into memberships
1804
- from ${schema}.${MEMBERSHIP_ENTRIES_FOR}(uid) x;${custom}${version}${teams}${extra}
1805
- return jsonb_strip_nulls(jsonb_build_object(
1806
- 'claims', case when claims = '{}'::jsonb then null else claims end,
1807
- 'id', uid::text,
1808
- 'active', true,
1809
- 'roles', held,
1810
- 'memberships', memberships,
1811
- 'customRoles', custom,
1812
- 'authzVersion', ver
1813
- ));
1814
- end;
1815
- $$;
1816
- revoke execute on function ${fn}(uuid) from public, anon, authenticated;`;
1817
- }
1818
- /**
1819
- * `<helpers schema>.permdock_subject() returns jsonb`: `subject_for` for the
1820
- * signed-in user, `null` for an anonymous or suspended one. A client role may
1821
- * execute it because it names no user: `bootstrap` calls it so one round trip
1822
- * returns the subject the authorizer would otherwise read again.
1823
- */
1824
- function permdockSubjectSql(parts) {
1825
- const helpers = quoteIdent(parts.helpers.schema);
1826
- const fn = `${helpers}.${PERMDOCK_SUBJECT}`;
1827
- return `-- the signed-in user's subject_for record, for a bootstrap that seeds the authorizer; null when anonymous or suspended
1828
- create or replace function ${fn}()
1829
- returns jsonb
1830
- language plpgsql
1831
- stable
1832
- security definer
1833
- set search_path = ''
1834
- as $$
1835
- declare
1836
- subject jsonb := ${quoteIdent(parts.schema)}.${SUBJECT_FOR}((select ${helpers}.${USER_ID_HELPER}()));
1837
- begin
1838
- if subject is null or (subject ->> 'active') is distinct from 'true' then
1839
- return null;
1840
- end if;
1841
- return subject;
1842
- end;
1843
- $$;
1844
- revoke execute on function ${fn}() from public, anon, authenticated;
1845
- grant execute on function ${fn}() to authenticated;`;
1846
- }
1847
- /**
1848
- * The PostgREST wrappers `supabase.hook.api` asks for: one `security invoker`
1849
- * function per reader, in the API schema, executable by `service_role` only.
1850
- * The `security definer` readers stay in the hook schema, which the Data API
1851
- * does not expose; `service_role` gets `usage` on it and `execute` on each
1852
- * reader, so no definer function sits in an exposed schema.
1853
- */
1854
- function apiWrappersSql(parts) {
1855
- const api = parts.hook.api;
1856
- if (api === void 0) return "";
1857
- const target = api.schema ?? "public";
1858
- const names = hookApiNames(api.prefix);
1859
- const source = quoteIdent(parts.schema);
1860
- const wrapper = (name, inner, params, args, types, returns) => {
1861
- const fn = `${quoteIdent(target)}.${quoteIdent(name)}`;
1862
- if (target === parts.schema && name === inner) throw configError(`PermDock CLI: supabase.hook.api would replace ${source}.${inner}: set api.schema or api.prefix`);
1863
- return `create or replace function ${fn}(${params})
1864
- returns ${returns}
1865
- language sql
1866
- stable
1867
- security invoker
1868
- set search_path = ''
1869
- as $$ select ${source}.${inner}(${args}) $$;
1870
- revoke execute on function ${fn}(${types}) from public, anon, authenticated;
1871
- grant execute on function ${fn}(${types}) to service_role;
1872
- grant execute on function ${source}.${inner}(${types}) to service_role;`;
1873
- };
1874
- 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}
1875
- grant usage on schema ${source} to service_role;
1876
-
1877
- ${wrapper(names.subjectFor, SUBJECT_FOR, "p_user uuid", "p_user", "uuid", "jsonb")}
1878
-
1879
- ${wrapper(names.membersOf, MEMBERS_OF, "p_scope text, p_id text", "p_scope, p_id", "text, text", "jsonb")}
1880
-
1881
- ${wrapper(names.authzVersionFor, AUTHZ_VERSION_FOR, "p_user uuid", "p_user", "uuid", "bigint")}`;
1882
- }
1883
- const AUTHZ_VERSION_FOR = "authz_version_for";
1884
- /**
1885
- * `authz_version_for(p_user uuid) returns bigint`: the authorization version
1886
- * `subject_for` reports, without reading roles or memberships, so a
1887
- * `claimsFirst` reread can check a token's freshness on every request and read
1888
- * the full subject only when it is behind. `null` for an unknown or suspended
1889
- * user, and when the version is off.
1890
- */
1891
- function authzVersionForSql(parts) {
1892
- const schema = quoteIdent(parts.schema);
1893
- const fn = `${schema}.${AUTHZ_VERSION_FOR}`;
1894
- return `-- the authorization version subject_for reports for p_user, for a cheap freshness check; no client role may execute it
1895
- create or replace function ${fn}(p_user uuid)
1896
- returns bigint
1897
- language plpgsql
1898
- stable
1899
- security definer
1900
- set search_path = ''
1901
- as $$
1902
- declare
1903
- uid uuid := p_user;
1904
- ver bigint;
1905
- begin
1906
- if uid is null or not exists (select 1 from auth.users u where u.id = uid) then
1907
- return null;
1908
- end if;${parts.users === void 0 ? "" : `
1909
- if not ${activeRowSql(parts.users, "uid")} then
1910
- return null;
1911
- end if;`}${parts.version ? `
1912
- select v.version into ver from ${schema}.${quoteIdent(AUTHZ_VERSION_TABLE)} v where v.user_id = uid;
1913
- ver := coalesce(ver, 0);` : ""}
1914
- return ver;
1915
- end;
1916
- $$;
1917
- revoke execute on function ${fn}(uuid) from public, anon, authenticated;`;
1918
- }
1919
- const MEMBERS_OF = "members_of";
1920
- function membersOfSql(parts) {
1921
- const fn = `${quoteIdent(parts.schema)}.${MEMBERS_OF}`;
1922
- const keep = parts.sources.some((source) => source.sql.keeps);
1923
- const rows = parts.sources.map((source) => source.sql.list(keep).replaceAll(/^/gmu, " ")).join("\n union all\n");
1924
- return `-- the live memberships of one scope instance, for a backend that lists members over PostgREST; no client role may execute it
1925
- create or replace function ${fn}(p_scope text, p_id text)
1926
- returns jsonb
1927
- language sql
1928
- stable
1929
- security definer
1930
- set search_path = ''
1931
- as $$
1932
- select coalesce(jsonb_agg(jsonb_build_object(
1933
- 'principal', jsonb_build_object('id', s.user_id),
1934
- 'membership', jsonb_strip_nulls(jsonb_build_object(
1935
- 'scope', s.scope, 'id', s.id, 'within', s.within, 'roles', s.roles, 'via', s.via,
1936
- 'expires_at', s.expires_at, 'granted_by', s.granted_by, 'reason', s.reason,
1937
- 'member', case when s.member_group is not null then jsonb_build_object('group', s.member_group) end,
1938
- 'managed_by', s.managed_by, 'entitlements', s.seats${keep ? ", 'keep', s.keep" : ""}
1939
- ))
1940
- ) order by s.user_id, s.roles::text), '[]'::jsonb)
1941
- from (
1942
- ${rows}
1943
- ) s
1944
- $$;
1945
- revoke execute on function ${fn}(text, text) from public, anon, authenticated;`;
1946
- }
1947
- /**
1948
- * The custom roles `p_user` holds: tenant and shared roles named on a
1949
- * membership of the scope (and instance) they live at, and platform roles among
1950
- * the global roles, each with its grants and includes in `CustomRole` form. A
1951
- * shadowed tenant role comes along; `resolveCustomRole`'s callers drop it.
1952
- */
1953
- function customRolesOfSql(parts) {
1954
- const helpers = quoteIdent(parts.helpers.schema);
1955
- const perms = `${helpers}.custom_role_permissions`;
1956
- const includes = `${helpers}.custom_role_includes`;
1957
- const root = quoteLiteral(parts.root);
1958
- const match = `p.tenant_id is not distinct from c.tenant_id and p.scope = c.scope and p.scope_id is not distinct from c.scope_id and p.role = c.role`;
1959
- return `
1960
- select coalesce(jsonb_agg(jsonb_strip_nulls(jsonb_build_object(
1961
- 'name', c.role,
1962
- 'shared', case when c.tenant_id is null and c.scope <> 'global' then true end,
1963
- 'tenant', c.tenant_id::text,
1964
- 'scope', c.scope,
1965
- 'id', c.scope_id,
1966
- 'grants', (
1967
- select coalesce(jsonb_agg(jsonb_strip_nulls(jsonb_build_object(
1968
- 'permission', p.permission,
1969
- 'effect', p.effect,
1970
- 'level', to_jsonb(p) ->> 'level'
1971
- )) order by p.permission, p.effect), '[]'::jsonb)
1972
- from ${perms} p
1973
- where ${match}
1974
- ),
1975
- 'includes', (
1976
- select jsonb_agg(p.include_role order by p.include_role)
1977
- from ${includes} p
1978
- where ${match}
1979
- )
1980
- )) order by c.tenant_id::text, c.scope, c.scope_id, c.role), '[]'::jsonb)
1981
- into custom
1982
- from (
1983
- select tenant_id, scope, scope_id, role from ${perms}
1984
- union
1985
- select tenant_id, scope, scope_id, role from ${includes}
1986
- ) c
1987
- where (c.scope = 'global' and c.tenant_id is null and held ? c.role)
1988
- or exists (
1989
- select 1
1990
- from jsonb_array_elements(memberships) m
1991
- where m -> 'roles' ? c.role
1992
- and m ->> 'scope' = c.scope
1993
- and (
1994
- (c.tenant_id is null and c.scope_id is null)
1995
- or c.tenant_id::text = case when m ->> 'scope' = ${root} then m ->> 'id' else m -> 'within' ->> ${root} end
1996
- )
1997
- and (c.scope_id is null or c.scope_id = m ->> 'id')
1998
- );`;
1999
- }
2000
- //#endregion
2001
- //#region src/cli/rls/approval-managers.ts
2002
- /** Whether the signed-in user manages a requester; better-supabase reads it. */
2003
- const MANAGES = "permdock_manages";
2004
- /**
2005
- * The approver check with `manager` leaves; only `permdock_is_approver` calls
2006
- * it.
2007
- */
2008
- const APPROVES = "permdock_approves";
2009
- const MANAGES_FOR = "permdock_manages_for";
2010
- function named$1(value) {
2011
- return typeof value === "string" && value !== "";
2012
- }
2013
- function checked$1(managers) {
2014
- 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");
2015
- return {
2016
- table: managers.table,
2017
- user: managers.user,
2018
- manager: managers.manager
2019
- };
2020
- }
2021
- /**
2022
- * `rls.approvals.managers`: `permdock_manages(p_requester, p_levels)` walks the
2023
- * app's manager table up to `levels` steps (at most `MAX_MANAGER_LEVELS`) with
2024
- * a cycle guard, and `permdock_approves` decides `manager` leaves with it and
2025
- * every other leaf through `base`, the two-argument check. The requester never
2026
- * manages themselves into an approval. `permdock_is_approver(p_approvers,
2027
- * p_tenant, p_requester)` routes through `permdock_approves`, so the call with
2028
- * a requester decides `manager` leaves; without one they match nobody. Without
2029
- * `delegations`, the four-argument `permdock_is_approver` is written here; with
2030
- * them, `approvalDelegationsSql` writes it and calls `permdock_approves`
2031
- * first.
2032
- */
2033
- function approvalManagersSql(ctx, given, isApprover, base, delegations) {
2034
- const managers = checked$1(given);
2035
- const table = quoteQualified(managers.table);
2036
- const user = quoteIdent(managers.user);
2037
- const boss = quoteIdent(managers.manager);
2038
- const manages = qualified$1(ctx, MANAGES);
2039
- const managesFor = qualified$1(ctx, MANAGES_FOR);
2040
- const approves = qualified$1(ctx, APPROVES);
2041
- const me = `${subjectIdSql(ctx)}::text`;
2042
- const entry = delegations ? "" : `
2043
- -- approvers with managers: permdock_approves for the signed-in user
2044
- create or replace function ${isApprover}(p_approvers jsonb, p_tenant text, p_requester text, p_resource text)
2045
- returns boolean
2046
- language sql
2047
- stable
2048
- security definer
2049
- set search_path = ''
2050
- as $$
2051
- select ${approves}(p_approvers, p_tenant, p_requester)
2052
- $$;
2053
- revoke execute on function ${isApprover}(jsonb, text, text, text) from public, anon;
2054
- grant execute on function ${isApprover}(jsonb, text, text, text) to authenticated;
2055
- `;
2056
- const twoArguments = `
2057
- -- approvers with managers: the two-argument call decides manager leaves when it passes the requester
2058
- drop function if exists ${isApprover}(jsonb, text);
2059
- create or replace function ${isApprover}(p_approvers jsonb, p_tenant text default null, p_requester text default null)
2060
- returns boolean
2061
- language sql
2062
- stable
2063
- security definer
2064
- set search_path = ''
2065
- as $$
2066
- select coalesce(${approves}(p_approvers, p_tenant, p_requester), false)
2067
- $$;
2068
- revoke execute on function ${isApprover}(jsonb, text, text) from public, anon;
2069
- grant execute on function ${isApprover}(jsonb, text, text) to authenticated;
2070
- `;
2071
- return `
2072
- -- approval managers: whether p_user manages p_requester within p_levels steps of ${managers.table}
2073
- create or replace function ${managesFor}(p_user text, p_requester text, p_levels integer)
2074
- returns boolean
2075
- language sql
2076
- stable
2077
- security definer
2078
- set search_path = ''
2079
- as $$
2080
- with recursive chain (id, depth, path) as (
2081
- select m.${boss}::text, 1, array[p_requester, m.${boss}::text]
2082
- from ${table} m
2083
- where m.${user}::text = p_requester
2084
- and m.${boss} is not null
2085
- union all
2086
- select m.${boss}::text, c.depth + 1, c.path || m.${boss}::text
2087
- from chain c
2088
- join ${table} m on m.${user}::text = c.id
2089
- where c.depth < least(p_levels, ${String(8)})
2090
- and m.${boss} is not null
2091
- and not (m.${boss}::text = any (c.path))
2092
- )
2093
- select coalesce(
2094
- p_requester <> ''
2095
- and p_user <> ''
2096
- and p_levels between 1 and ${String(8)}
2097
- and p_user <> p_requester
2098
- and exists (select 1 from chain c where c.id = p_user),
2099
- false
2100
- )
2101
- $$;
2102
- revoke execute on function ${managesFor}(text, text, integer) from public, anon, authenticated;
2103
-
2104
- -- approval managers: whether the signed-in user manages p_requester within p_levels steps of ${managers.table}
2105
- create or replace function ${manages}(p_requester text, p_levels integer)
2106
- returns boolean
2107
- language sql
2108
- stable
2109
- security definer
2110
- set search_path = ''
2111
- as $$
2112
- select ${managesFor}(${me}, p_requester, p_levels)
2113
- $$;
2114
- revoke execute on function ${manages}(text, integer) from public, anon, authenticated;
2115
-
2116
- -- approval managers: approvers.by with manager leaves; only permdock_is_approver calls it
2117
- create or replace function ${approves}(p_approvers jsonb, p_tenant text, p_requester text)
2118
- returns boolean
2119
- language plpgsql
2120
- stable
2121
- security definer
2122
- set search_path = ''
2123
- as $$
2124
- declare
2125
- v_item jsonb;
2126
- v_levels jsonb;
2127
- begin
2128
- if p_approvers is null then
2129
- return false;
2130
- end if;
2131
- if jsonb_typeof(p_approvers) = 'array' then
2132
- if jsonb_array_length(p_approvers) = 0 then
2133
- return false;
2134
- end if;
2135
- for v_item in select value from jsonb_array_elements(p_approvers) loop
2136
- if not ${approves}(v_item, p_tenant, p_requester) then
2137
- return false;
2138
- end if;
2139
- end loop;
2140
- return true;
2141
- end if;
2142
- if jsonb_typeof(p_approvers) <> 'object' then
2143
- return false;
2144
- end if;
2145
- case p_approvers ->> 'kind'
2146
- when 'manager' then
2147
- v_levels := coalesce(p_approvers -> 'levels', '1'::jsonb);
2148
- if jsonb_typeof(v_levels) <> 'number' or v_levels::text !~ '^[0-9]{1,2}$' then
2149
- return false;
2150
- end if;
2151
- return coalesce(${manages}(p_requester, v_levels::text::integer), false);
2152
- when 'any-of' then
2153
- if jsonb_typeof(p_approvers -> 'of') <> 'array' then
2154
- return false;
2155
- end if;
2156
- for v_item in select value from jsonb_array_elements(p_approvers -> 'of') loop
2157
- if ${approves}(v_item, p_tenant, p_requester) then
2158
- return true;
2159
- end if;
2160
- end loop;
2161
- return false;
2162
- else
2163
- return ${base}(p_approvers, p_tenant);
2164
- end case;
2165
- end;
2166
- $$;
2167
- revoke execute on function ${approves}(jsonb, text, text) from public, anon, authenticated;
2168
- ${twoArguments}${entry}`;
2169
- }
2170
- //#endregion
2171
- //#region src/cli/rls/approval-policies.ts
2172
- /**
2173
- * The objects `rls.approvals.tenantPolicies` adds; `tableApprovalPolicySource`
2174
- * calls the function.
2175
- */
2176
- const APPROVAL_POLICIES = {
2177
- table: "approval_policies",
2178
- read: "permdock_approval_policies_for"
2179
- };
2180
- const COLUMN_DEFAULTS = {
2181
- id: "id",
2182
- tenant: "tenant",
2183
- name: "name",
2184
- body: "body",
2185
- enabled: "enabled",
2186
- createdAt: "created_at"
2187
- };
2188
- const KEY = /^[A-Za-z][\w-]*(?:\.[A-Za-z][\w-]*)+$/u;
2189
- /**
2190
- * `rls.approvals.tenantPolicies`: one table of `ApprovalPolicy` bodies, a
2191
- * tenant row per requirement a tenant adds and platform floors with `tenant`
2192
- * null. Members read their tenants' rows and the floors; a holder of `manage`
2193
- * in a tenant writes that tenant's rows; nobody but the owner writes a floor.
2194
- * `permdock_approval_policies_for(p_tenants)` answers the enabled bodies with
2195
- * the row's tenant set, floors first, and only the owner may execute it, since
2196
- * it reads every tenant.
2197
- */
2198
- function named(value) {
2199
- return typeof value === "string" && value !== "";
2200
- }
2201
- /** `options` with its optional parts checked; `manage` is the only required one. */
2202
- function checked(options) {
2203
- 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");
2204
- const given = { ...options };
2205
- 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`);
2206
- const columns = given["columns"];
2207
- if (columns !== void 0) {
2208
- if (typeof columns !== "object" || columns === null) throw configError("PermDock CLI: rls.approvals.tenantPolicies.columns must be an object of column names");
2209
- 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(", ")}`);
2210
- }
2211
- const path = given["path"];
2212
- if (path !== void 0 && !(Array.isArray(path) && path.every(named))) throw configError("PermDock CLI: rls.approvals.tenantPolicies.path must be a list of keys");
2213
- return given;
2214
- }
2215
- function approvalPoliciesSql(ctx, given, actorMayWrite = false) {
2216
- const options = checked(given);
2217
- const root = ctx.scopes[0]?.name;
2218
- if (root === void 0) throw configError("PermDock CLI: rls.approvals.tenantPolicies needs a tenant scope; declare one in the policy's scopes");
2219
- const column = (key) => quoteIdent(options.columns?.[key] ?? COLUMN_DEFAULTS[key]);
2220
- const id = column("id");
2221
- const tenantColumn = column("tenant");
2222
- const name = column("name");
2223
- const bodyColumn = column("body");
2224
- const enabled = column("enabled");
2225
- const createdAt = column("createdAt");
2226
- const path = options.path ?? [];
2227
- const keys = `{${path.map((key) => `"${key.replaceAll("\"", String.raw`\"`)}"`).join(",")}}`;
2228
- const policyIn = (alias) => path.length === 0 ? `${alias}${bodyColumn}` : `(${alias}${bodyColumn} #> ${quoteLiteral(keys)})`;
2229
- const tableName = options.table === void 0 ? APPROVAL_POLICIES.table : options.table.split(".").at(-1) ?? APPROVAL_POLICIES.table;
2230
- const table = options.table === void 0 ? qualified$1(ctx, APPROVAL_POLICIES.table) : quoteQualified(options.table);
2231
- const fn = qualified$1(ctx, options.function ?? APPROVAL_POLICIES.read);
2232
- const member = `${tenantColumn} in (select m.id::text from ${qualified$1(ctx, memberIdsHelper(root))}() m(id))`;
2233
- const manages = `exists (
2234
- select 1
2235
- from ${qualified$1(ctx, checkName(permittedByPermissionHelper(root)))}(${quoteLiteral(options.manage)}) i(id)
2236
- where i.id::text = ${tenantColumn}
2237
- )`;
2238
- const writable = actorMayWrite ? ` and (select ${qualified$1(ctx, ACTOR_MAY_WRITE)}())` : "";
2239
- const own = `${tenantColumn} is not null and ${subjectIdSql(ctx)} is not null and ${manages}${writable}`;
2240
- const policy = (suffix) => quoteIdent(`${tableName}_${suffix}`);
2241
- return `
2242
- -- approval policies: requirements a tenant keeps as data, plus platform floors (tenant null); tableApprovalPolicySource reads them
2243
- create table if not exists ${table} (
2244
- ${id} text primary key default gen_random_uuid()::text,
2245
- ${tenantColumn} text,
2246
- ${name} text not null,
2247
- ${bodyColumn} jsonb not null,
2248
- ${enabled} boolean not null default true,
2249
- ${createdAt} timestamptz not null default now(),
2250
- updated_at timestamptz not null default now(),
2251
- constraint ${quoteIdent(`${tableName}_body`)} check (jsonb_typeof(${policyIn("")}) = 'object' and ${policyIn("")} ? 'approval')
2252
- );
2253
- create index if not exists ${quoteIdent(`${tableName}_tenant`)} on ${table} (${tenantColumn});
2254
- alter table ${table} enable row level security;
2255
- revoke all on table ${table} from anon, public;
2256
- grant select, insert, update, delete on table ${table} to authenticated;
2257
- drop policy if exists ${policy("read")} on ${table};
2258
- create policy ${policy("read")} on ${table}
2259
- for select to authenticated
2260
- using (${tenantColumn} is null or ${member});
2261
- drop policy if exists ${policy("insert")} on ${table};
2262
- create policy ${policy("insert")} on ${table}
2263
- for insert to authenticated
2264
- with check (${own});
2265
- drop policy if exists ${policy("update")} on ${table};
2266
- create policy ${policy("update")} on ${table}
2267
- for update to authenticated
2268
- using (${own})
2269
- with check (${own});
2270
- drop policy if exists ${policy("delete")} on ${table};
2271
- create policy ${policy("delete")} on ${table}
2272
- for delete to authenticated
2273
- using (${own});
2274
-
2275
- -- approval policies: the enabled bodies for p_tenants and every floor, with the row's tenant; only the owner executes it
2276
- create or replace function ${fn}(p_tenants text[])
2277
- returns setof jsonb
2278
- language sql
2279
- stable
2280
- set search_path = ''
2281
- as $$
2282
- select case
2283
- when p.${tenantColumn} is null then ${policyIn("p.")} - 'tenant'
2284
- else ${policyIn("p.")} || jsonb_build_object('tenant', p.${tenantColumn})
2285
- end
2286
- from ${table} p
2287
- where p.${enabled}
2288
- and (p.${tenantColumn} is null or p.${tenantColumn} = any(coalesce(p_tenants, '{}')))
2289
- order by p.${tenantColumn} nulls first, p.${createdAt}, p.${id};
2290
- $$;
2291
- revoke execute on function ${fn}(text[]) from public, anon, authenticated;
2292
- `;
2293
- }
2294
- //#endregion
2295
- //#region src/cli/rls/approvals.ts
2296
- /**
2297
- * `rls.approvals`' approver check; better-supabase's `isApprover` template
2298
- * calls it.
2299
- */
2300
- const IS_APPROVER = "permdock_is_approver";
2301
- /**
2302
- * The objects `rls.approvals` adds. Names are part of the SQL contract
2303
- * `supabaseApprovalStore` calls.
2304
- */
2305
- const APPROVAL_STORE = {
2306
- table: "approval_requests",
2307
- open: "permdock_approval_open",
2308
- get: "permdock_approval_get",
2309
- resolve: "permdock_approval_resolve",
2310
- consume: "permdock_approval_consume",
2311
- list: "permdock_approval_list",
2312
- expire: "permdock_approval_expire",
2313
- cancel: "permdock_approval_cancel",
2314
- isApprover: IS_APPROVER,
2315
- /**
2316
- * The two-argument check `permdock_approves` falls back to for non-manager
2317
- * leaves.
2318
- */
2319
- isApproverBase: "permdock_is_approver_base"
2320
- };
2321
- /** `body` as the row's filter columns hold it. */
2322
- const COLUMNS = `p_request ->> 'token',
2323
- p_request,
2324
- p_request ->> 'status',
2325
- p_request #>> '{subject,principal,tenant}',
2326
- p_request #>> '{subject,principal,id}',
2327
- p_request #>> '{subject,actor,id}',
2328
- p_request #>> '{subject,session}',
2329
- coalesce(jsonb_array_length(p_request -> 'approvals'), 0),
2330
- p_request ->> 'createdAt',
2331
- (p_request ->> 'expiresAt')::timestamptz,
2332
- (p_request ->> 'consumedAt')::timestamptz`;
2333
- /** The `ApprovalListFilter` in `p_filter`, over the row aliased `a`. */
2334
- const FILTER = `(p_filter ->> 'status' is null or a.status = p_filter ->> 'status')
2335
- and (p_filter ->> 'tenant' is null or a.tenant = p_filter ->> 'tenant')
2336
- and (p_filter ->> 'principalId' is null or a.principal_id = p_filter ->> 'principalId')
2337
- and (p_filter ->> 'actorId' is null or a.actor_id = p_filter ->> 'actorId')
2338
- and (p_filter ->> 'session' is null or a.session = p_filter ->> 'session')`;
2339
- function serverOnly(fn, args) {
2340
- return `revoke execute on function ${fn}(${args}) from public, anon, authenticated;`;
2341
- }
2342
- const BODY_CHECK = `${APPROVAL_STORE.table}_body_schema`;
2343
- /**
2344
- * `rls.jsonSchema`: a pg_jsonschema check that `body` matches
2345
- * `approval-request-v1.json`, added `not valid` and then validated. `auto` adds
2346
- * it only where the extension is available.
2347
- */
2348
- function bodySchemaSql(table, mode, body = "body", check = BODY_CHECK) {
2349
- const statements = [
2350
- "create schema if not exists extensions;",
2351
- "create extension if not exists pg_jsonschema with schema extensions;",
2352
- `alter table ${table} drop constraint if exists "${check}";`,
2353
- `alter table ${table} add constraint "${check}" check (extensions.jsonb_matches_schema(${quoteLiteral(JSON.stringify(APPROVAL_REQUEST_SCHEMA))}::json, ${body})) not valid;`,
2354
- `alter table ${table} validate constraint "${check}";`
2355
- ];
2356
- const comment = "-- approval store: body matches schemas/approval-request-v1.json through pg_jsonschema";
2357
- if (mode === true) return `\n${comment}\n${statements.join("\n")}\n`;
2358
- return `\n${comment}, where the extension is available
2359
- do $permdock$
2360
- begin
2361
- if exists (select 1 from pg_available_extensions where name = 'pg_jsonschema') then
2362
- ${statements.map((statement) => ` ${statement}`).join("\n")}
2363
- end if;
2364
- end
2365
- $permdock$;\n`;
2366
- }
2367
- /**
2368
- * The approval store (`rls.approvals`): one table of `ApprovalRequest` bodies
2369
- * with the columns a list filters on, and one `security definer` function per
2370
- * `ApprovalStore` method, each one atomic statement. No client role may read
2371
- * the table or execute the functions: approvals are opened and resolved by the
2372
- * server, which grants its own role.
2373
- */
2374
- function approvalStoreSql(ctx, jsonSchema = false) {
2375
- const table = qualified$1(ctx, APPROVAL_STORE.table);
2376
- const fn = (name) => qualified$1(ctx, name);
2377
- const index = (name) => `"${APPROVAL_STORE.table}_${name}"`;
2378
- return `-- approval store: ApprovalRequest bodies, opened, resolved and consumed through the functions below; supabaseApprovalStore calls them
2379
- create table if not exists ${table} (
2380
- token text primary key,
2381
- body jsonb not null,
2382
- status text not null check (status in ('pending', 'approved', 'rejected', 'expired')),
2383
- tenant text,
2384
- principal_id text,
2385
- actor_id text,
2386
- session text,
2387
- approvals integer not null default 0,
2388
- created_at text not null,
2389
- expires_at timestamptz not null,
2390
- consumed_at timestamptz
2391
- );
2392
- create index if not exists ${index("page")} on ${table} (created_at collate "C", token collate "C");
2393
- create index if not exists ${index("pending")} on ${table} (status, expires_at);
2394
- alter table ${table} enable row level security;
2395
- revoke all on table ${table} from anon, authenticated, public;
2396
- ${jsonSchema === false ? "" : bodySchemaSql(table, jsonSchema)}
2397
- -- open a request; a repeated ask keeps the open record and replaces only an expired one
2398
- create or replace function ${fn(APPROVAL_STORE.open)}(p_request jsonb)
2399
- returns void
2400
- language sql
2401
- volatile
2402
- security definer
2403
- set search_path = ''
2404
- as $$
2405
- insert into ${table} as a (token, body, status, tenant, principal_id, actor_id, session, approvals, created_at, expires_at, consumed_at)
2406
- values (
2407
- ${COLUMNS}
2408
- )
2409
- on conflict (token) do update
2410
- set body = excluded.body, status = excluded.status, tenant = excluded.tenant,
2411
- principal_id = excluded.principal_id, actor_id = excluded.actor_id, session = excluded.session,
2412
- approvals = excluded.approvals, created_at = excluded.created_at,
2413
- expires_at = excluded.expires_at, consumed_at = excluded.consumed_at
2414
- where a.status = 'expired' or a.expires_at <= now()
2415
- $$;
2416
- ${serverOnly(fn(APPROVAL_STORE.open), "jsonb")}
2417
-
2418
- create or replace function ${fn(APPROVAL_STORE.get)}(p_token text)
2419
- returns jsonb
2420
- language sql
2421
- stable
2422
- security definer
2423
- set search_path = ''
2424
- as $$
2425
- select a.body from ${table} a where a.token = p_token
2426
- $$;
2427
- ${serverOnly(fn(APPROVAL_STORE.get), "text")}
2428
-
2429
- -- write a verdict over the record it was computed from: still pending, unexpired, with p_seen approvals
2430
- create or replace function ${fn(APPROVAL_STORE.resolve)}(p_token text, p_next jsonb, p_seen integer)
2431
- returns jsonb
2432
- language sql
2433
- volatile
2434
- security definer
2435
- set search_path = ''
2436
- as $$
2437
- update ${table} a
2438
- set body = p_next,
2439
- status = p_next ->> 'status',
2440
- approvals = coalesce(jsonb_array_length(p_next -> 'approvals'), 0)
2441
- where a.token = p_token
2442
- and a.status = 'pending'
2443
- and a.expires_at > now()
2444
- and a.approvals = p_seen
2445
- returning a.body
2446
- $$;
2447
- ${serverOnly(fn(APPROVAL_STORE.resolve), "text, jsonb, integer")}
2448
-
2449
- -- consume an approved, unexpired, unconsumed request once
2450
- create or replace function ${fn(APPROVAL_STORE.consume)}(p_token text, p_now text)
2451
- returns jsonb
2452
- language sql
2453
- volatile
2454
- security definer
2455
- set search_path = ''
2456
- as $$
2457
- update ${table} a
2458
- set consumed_at = p_now::timestamptz,
2459
- body = a.body || jsonb_build_object('consumedAt', p_now)
2460
- where a.token = p_token
2461
- and a.status = 'approved'
2462
- and a.consumed_at is null
2463
- and a.expires_at > p_now::timestamptz
2464
- returning a.body
2465
- $$;
2466
- ${serverOnly(fn(APPROVAL_STORE.consume), "text, text")}
2467
-
2468
- -- one page in (createdAt, token) order after the cursor position
2469
- create or replace function ${fn(APPROVAL_STORE.list)}(p_filter jsonb, p_after_created text, p_after_token text, p_limit integer)
2470
- returns setof jsonb
2471
- language sql
2472
- stable
2473
- security definer
2474
- set search_path = ''
2475
- as $$
2476
- select a.body
2477
- from ${table} a
2478
- where ${FILTER}
2479
- and (p_after_created is null
2480
- or (a.created_at collate "C", a.token collate "C") > (p_after_created collate "C", p_after_token collate "C"))
2481
- order by a.created_at collate "C", a.token collate "C"
2482
- limit p_limit
2483
- $$;
2484
- ${serverOnly(fn(APPROVAL_STORE.list), "jsonb, text, text, integer")}
2485
-
2486
- create or replace function ${fn(APPROVAL_STORE.expire)}(p_now text)
2487
- returns integer
2488
- language sql
2489
- volatile
2490
- security definer
2491
- set search_path = ''
2492
- as $$
2493
- with expired as (
2494
- update ${table} a
2495
- set status = 'expired', body = a.body || '{"status":"expired"}'::jsonb
2496
- where a.status = 'pending' and a.expires_at <= p_now::timestamptz
2497
- returning 1
2498
- )
2499
- select count(*)::integer from expired
2500
- $$;
2501
- ${serverOnly(fn(APPROVAL_STORE.expire), "text")}
2502
-
2503
- -- reject every pending request the filter matches, as system:<by>
2504
- create or replace function ${fn(APPROVAL_STORE.cancel)}(p_filter jsonb, p_by text, p_note text, p_now text)
2505
- returns integer
2506
- language sql
2507
- volatile
2508
- security definer
2509
- set search_path = ''
2510
- as $$
2511
- with cancelled as (
2512
- update ${table} a
2513
- set status = 'rejected',
2514
- body = (a.body - 'note') || jsonb_strip_nulls(jsonb_build_object(
2515
- 'status', 'rejected', 'resolvedAt', p_now, 'resolvedBy', 'system:' || p_by, 'note', p_note
2516
- ))
2517
- where a.status = 'pending'
2518
- and ${FILTER.replaceAll("\n ", "\n ")}
2519
- returning 1
2520
- )
2521
- select count(*)::integer from cancelled
2522
- $$;
2523
- ${serverOnly(fn(APPROVAL_STORE.cancel), "jsonb, text, text, text")}
2524
- `;
2525
- }
2526
- /**
2527
- * `permdock_is_approver(p_approvers jsonb, p_tenant text default null)`, or
2528
- * with `rls.approvals.managers` its base `permdock_is_approver_base`: true when
2529
- * the signed-in user matches the serialised approvers of a request
2530
- * (`approvers.by`), for policies on the app's own approval views. A list needs
2531
- * every item and `any-of` one of them; `user` compares the user id and
2532
- * `holder(permission)` reads `permitted_<root>_ids_by_permission` in
2533
- * `p_tenant`, or `permdock_has_permission` without one. Role, relation and
2534
- * other grantee approvers need facts the database does not hold for every
2535
- * membership source, so they match nobody.
2536
- */
2537
- function isApproverSql(ctx, managers = false) {
2538
- const fn = qualified$1(ctx, managers ? APPROVAL_STORE.isApproverBase : APPROVAL_STORE.isApprover);
2539
- const exposure = managers ? `revoke execute on function ${fn}(jsonb, text) from public, anon, authenticated;` : `revoke execute on function ${fn}(jsonb, text) from public, anon;
2540
- grant execute on function ${fn}(jsonb, text) to authenticated;`;
2541
- const root = ctx.scopes[0]?.name;
2542
- const inTenant = root === void 0 ? "false" : `exists (
2543
- select 1
2544
- from ${qualified$1(ctx, checkName(permittedByPermissionHelper(root)))}(p_approvers ->> 'permission') i(id)
2545
- where i.id::text = p_tenant
2546
- )`;
2547
- return `
2548
- -- approvers: whether the signed-in user matches a request's approvers.by; policies on approval views call it
2549
- create or replace function ${fn}(p_approvers jsonb, p_tenant text default null)
2550
- returns boolean
2551
- language plpgsql
2552
- stable
2553
- security definer
2554
- set search_path = ''
2555
- as $$
2556
- declare
2557
- v_item jsonb;
2558
- v_user text := ${subjectIdSql(ctx)}::text;
2559
- begin
2560
- if coalesce(v_user, '') = '' or p_approvers is null then
2561
- return false;
2562
- end if;
2563
- if jsonb_typeof(p_approvers) = 'array' then
2564
- if jsonb_array_length(p_approvers) = 0 then
2565
- return false;
2566
- end if;
2567
- for v_item in select value from jsonb_array_elements(p_approvers) loop
2568
- if not ${fn}(v_item, p_tenant) then
2569
- return false;
2570
- end if;
2571
- end loop;
2572
- return true;
2573
- end if;
2574
- if jsonb_typeof(p_approvers) <> 'object' then
2575
- return false;
2576
- end if;
2577
- case p_approvers ->> 'kind'
2578
- when 'user' then
2579
- return coalesce(p_approvers ->> 'id' = v_user, false);
2580
- when 'permission' then
2581
- if p_tenant is null then
2582
- return coalesce(${qualified$1(ctx, PERMISSION_HELPERS.has)}(p_approvers ->> 'permission'), false);
2583
- end if;
2584
- return ${inTenant};
2585
- when 'any-of' then
2586
- if jsonb_typeof(p_approvers -> 'of') <> 'array' then
2587
- return false;
2588
- end if;
2589
- for v_item in select value from jsonb_array_elements(p_approvers -> 'of') loop
2590
- if ${fn}(v_item, p_tenant) then
2591
- return true;
2592
- end if;
2593
- end loop;
2594
- return false;
2595
- else
2596
- return false;
2597
- end case;
2598
- end;
2599
- $$;
2600
- ${exposure}
2601
- `;
2602
- }
2603
- /**
2604
- * Everything `rls.approvals` writes: the generated or adopted store, the
2605
- * approver check, with `managers` the manager walk, with `delegations: true`
2606
- * the covers, and with `tenantPolicies` the tenant approval policies. With
2607
- * `actorMayWrite`, the covers' write policies call
2608
- * `permdock_actor_may_write()`.
2609
- */
2610
- function approvalsSql(ctx, approvals, jsonSchema, actorMayWrite = false) {
2611
- if (approvals === void 0 || approvals === false) return;
2612
- if (approvals === true) return approvalStoreSql(ctx, jsonSchema) + isApproverSql(ctx);
2613
- const { table, delegations, tenantPolicies, managers } = approvals;
2614
- if (delegations !== void 0 && typeof delegations !== "boolean") throw new TypeError("PermDock CLI: rls.approvals.delegations must be a boolean");
2615
- if (approvals.store !== void 0 && typeof approvals.store !== "boolean") throw new TypeError("PermDock CLI: rls.approvals.store must be a boolean");
2616
- let store;
2617
- if (approvals.store === false) {
2618
- const adopted = [
2619
- "table",
2620
- "token",
2621
- "body",
2622
- "open",
2623
- "schema",
2624
- "mirror"
2625
- ].find((key) => approvals[key] !== void 0);
2626
- if (adopted !== void 0) throw configError(`PermDock CLI: rls.approvals.${adopted} configures the approval store, which rls.approvals.store: false leaves out`);
2627
- store = "";
2628
- } else if (table === void 0) {
2629
- const adoptOnly = [
2630
- "token",
2631
- "body",
2632
- "open",
2633
- "schema",
2634
- "mirror"
2635
- ].find((key) => approvals[key] !== void 0);
2636
- if (adoptOnly !== void 0) throw configError(`PermDock CLI: rls.approvals.${adoptOnly} adopts a table; set rls.approvals.table too`);
2637
- store = approvalStoreSql(ctx, jsonSchema);
2638
- } else store = adoptedApprovalStoreSql(ctx, {
2639
- ...approvals,
2640
- table
2641
- }, jsonSchema);
2642
- 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));
2643
- }
2644
- /**
2645
- * The objects `rls.approvals.delegations` adds; `tableApprovalDelegationSource`
2646
- * reads the table.
2647
- */
2648
- const DELEGATIONS = {
2649
- table: "approval_delegations",
2650
- covers: "permdock_cover_approves"
2651
- };
2652
- /**
2653
- * `rls.approvals.delegations`: one table of out-of-office covers that a user
2654
- * writes for themselves, and a four-argument `permdock_is_approver` that also
2655
- * answers for a delegate inside an active cover. With `managers`, the signed-in
2656
- * user's own check is `permdock_approves`, and a cover passes on a `manager`
2657
- * leaf when the delegator manages the requester. One hop: a cover is checked
2658
- * against the delegator's own approver rights, never the delegator's covers. A
2659
- * delegator who is the requester never counts. A `holder()` approver through a
2660
- * cover needs `rls.mode: "database"`, where the `_for` helpers exist; in `jwt`
2661
- * mode only `user()` approvers pass.
2662
- */
2663
- function approvalDelegationsSql(ctx, actorMayWrite = false, managers = false) {
2664
- const table = qualified$1(ctx, DELEGATIONS.table);
2665
- const fn = qualified$1(ctx, APPROVAL_STORE.isApprover);
2666
- const covers = qualified$1(ctx, DELEGATIONS.covers);
2667
- const user = ctx.dialect === "supabase" ? "uuid" : "text";
2668
- const me = `${subjectIdSql(ctx)}::text`;
2669
- const defaultMe = subjectIdSql(ctx).replace(/^\(select (.+)\)$/su, "$1");
2670
- const root = ctx.scopes[0]?.name;
2671
- const member = (tenant) => root === void 0 ? "false" : `${tenant} in (select m.id::text from ${qualified$1(ctx, memberIdsHelper(root))}() m(id))`;
2672
- const database = ctx.authorize === "database";
2673
- const holderGlobal = database ? `coalesce(${qualified$1(ctx, PERMISSION_HELPERS.hasFor)}(p_delegator, p_approvers ->> 'permission'), false)` : "false";
2674
- const holderTenant = database && root !== void 0 ? `exists (
2675
- select 1
2676
- from ${qualified$1(ctx, checkName(`${permittedByPermissionHelper(root)}_for`))}(p_delegator, p_approvers ->> 'permission') i(id)
2677
- where i.id::text = p_tenant
2678
- )` : "false";
2679
- const policy = (name) => quoteIdent(`${DELEGATIONS.table}_${name}`);
2680
- const writable = actorMayWrite ? ` and (select ${qualified$1(ctx, ACTOR_MAY_WRITE)}())` : "";
2681
- const managerCase = managers ? `
2682
- when 'manager' then
2683
- v_levels := coalesce(p_approvers -> 'levels', '1'::jsonb);
2684
- if jsonb_typeof(v_levels) <> 'number' or v_levels::text !~ '^[0-9]{1,2}$' then
2685
- return false;
2686
- end if;
2687
- return coalesce(${qualified$1(ctx, MANAGES_FOR)}(p_delegator::text, p_requester, v_levels::text::integer), false);` : "";
2688
- const mine = `delegator::text = ${me}${writable}`;
2689
- const own = `${mine} and (tenant is null or ${member("tenant")})`;
2690
- return `
2691
- -- approval delegations: out-of-office covers a user writes for themselves; tableApprovalDelegationSource and permdock_is_approver read them
2692
- create table if not exists ${table} (
2693
- id text primary key default gen_random_uuid()::text,
2694
- delegator ${user} not null default (${defaultMe})::${user},
2695
- delegate ${user} not null,
2696
- tenant text,
2697
- permissions text[],
2698
- resources text[],
2699
- "from" timestamptz not null default now(),
2700
- "until" timestamptz not null,
2701
- created_at timestamptz not null default now(),
2702
- constraint ${quoteIdent(`${DELEGATIONS.table}_window`)} check ("from" < "until"),
2703
- constraint ${quoteIdent(`${DELEGATIONS.table}_distinct`)} check (delegator <> delegate)
2704
- );
2705
- create index if not exists ${quoteIdent(`${DELEGATIONS.table}_delegate`)} on ${table} (delegate, "until");
2706
- alter table ${table} enable row level security;
2707
- revoke all on table ${table} from anon, public;
2708
- grant select, insert, update, delete on table ${table} to authenticated;
2709
- drop policy if exists ${policy("read")} on ${table};
2710
- create policy ${policy("read")} on ${table}
2711
- for select to authenticated
2712
- using (delegator::text = ${me} or delegate::text = ${me});
2713
- drop policy if exists ${policy("insert")} on ${table};
2714
- create policy ${policy("insert")} on ${table}
2715
- for insert to authenticated
2716
- with check (${own});
2717
- drop policy if exists ${policy("update")} on ${table};
2718
- create policy ${policy("update")} on ${table}
2719
- for update to authenticated
2720
- using (${mine})
2721
- with check (${own});
2722
- drop policy if exists ${policy("delete")} on ${table};
2723
- create policy ${policy("delete")} on ${table}
2724
- for delete to authenticated
2725
- using (${mine});
2726
-
2727
- -- approval delegations: whether a delegator's own rights match approvers.by; only permdock_is_approver calls it
2728
- create or replace function ${covers}(p_delegator ${user}, p_approvers jsonb, p_tenant text, p_requester text)
2729
- returns boolean
2730
- language plpgsql
2731
- stable
2732
- security definer
2733
- set search_path = ''
2734
- as $$
2735
- declare
2736
- v_item jsonb;${managers ? "\n v_levels jsonb;" : ""}
2737
- begin
2738
- if p_delegator is null or p_approvers is null then
2739
- return false;
2740
- end if;
2741
- if jsonb_typeof(p_approvers) = 'array' then
2742
- if jsonb_array_length(p_approvers) = 0 then
2743
- return false;
2744
- end if;
2745
- for v_item in select value from jsonb_array_elements(p_approvers) loop
2746
- if not ${covers}(p_delegator, v_item, p_tenant, p_requester) then
2747
- return false;
2748
- end if;
2749
- end loop;
2750
- return true;
2751
- end if;
2752
- if jsonb_typeof(p_approvers) <> 'object' then
2753
- return false;
2754
- end if;
2755
- case p_approvers ->> 'kind'
2756
- when 'user' then
2757
- return coalesce(p_approvers ->> 'id' = p_delegator::text, false);
2758
- when 'permission' then
2759
- if p_tenant is null then
2760
- return ${holderGlobal};
2761
- end if;
2762
- return ${holderTenant};${managerCase}
2763
- when 'any-of' then
2764
- if jsonb_typeof(p_approvers -> 'of') <> 'array' then
2765
- return false;
2766
- end if;
2767
- for v_item in select value from jsonb_array_elements(p_approvers -> 'of') loop
2768
- if ${covers}(p_delegator, v_item, p_tenant, p_requester) then
2769
- return true;
2770
- end if;
2771
- end loop;
2772
- return false;
2773
- else
2774
- return false;
2775
- end case;
2776
- end;
2777
- $$;
2778
- revoke execute on function ${covers}(${user}, jsonb, text, text) from public, anon, authenticated;
2779
-
2780
- -- approvers with covers: the signed-in user, or a delegate inside an active cover of a delegator who is not the requester
2781
- create or replace function ${fn}(p_approvers jsonb, p_tenant text, p_requester text, p_resource text)
2782
- returns boolean
2783
- language plpgsql
2784
- stable
2785
- security definer
2786
- set search_path = ''
2787
- as $$
2788
- declare
2789
- v_delegator ${user};
2790
- v_user text := ${me};
2791
- begin
2792
- if ${managers ? `${qualified$1(ctx, APPROVES)}(p_approvers, p_tenant, p_requester)` : `${fn}(p_approvers, p_tenant)`} then
2793
- return true;
2794
- end if;
2795
- if coalesce(v_user, '') = '' or coalesce(p_requester, '') = '' then
2796
- return false;
2797
- end if;
2798
- if p_tenant is not null and not (${member("p_tenant")}) then
2799
- return false;
2800
- end if;
2801
- for v_delegator in
2802
- select d.delegator
2803
- from ${table} d
2804
- where d.delegate::text = v_user
2805
- and d.delegator::text <> v_user
2806
- and d.delegator::text <> p_requester
2807
- and d."from" <= now()
2808
- and now() < d."until"
2809
- and (d.tenant is null or d.tenant = p_tenant)
2810
- and d.permissions is null
2811
- and (d.resources is null or p_resource = any (d.resources))
2812
- loop
2813
- if ${covers}(v_delegator, p_approvers, p_tenant, p_requester) then
2814
- return true;
2815
- end if;
2816
- end loop;
2817
- return false;
2818
- end;
2819
- $$;
2820
- revoke execute on function ${fn}(jsonb, text, text, text) from public, anon;
2821
- grant execute on function ${fn}(jsonb, text, text, text) to authenticated;
2822
- `;
2823
- }
2824
- function requestApproversSql(ctx) {
2825
- const fn = qualified$1(ctx, APPROVAL_STORE.isApprover);
2826
- return `
2827
- -- approvers with the current step: the four-argument check over p_approvers and the step's users, manager and permission
2828
- create or replace function ${fn}(p_approvers jsonb, p_tenant text, p_requester text, p_resource text, p_request_approvers jsonb)
2829
- returns boolean
2830
- language sql
2831
- stable
2832
- security definer
2833
- set search_path = ''
2834
- as $$
2835
- select ${fn}(
2836
- jsonb_build_object(
2837
- 'kind', 'any-of',
2838
- 'of',
2839
- case when p_approvers is null then '[]'::jsonb else jsonb_build_array(p_approvers) end
2840
- || case
2841
- when jsonb_typeof(p_request_approvers -> 'users') = 'array' then coalesce(
2842
- (select jsonb_agg(jsonb_build_object('kind', 'user', 'id', u.id)) from jsonb_array_elements_text(p_request_approvers -> 'users') u(id)),
2843
- '[]'::jsonb
2844
- )
2845
- else '[]'::jsonb
2846
- end
2847
- || case when p_request_approvers -> 'manager' = 'true'::jsonb then '[{"kind": "manager"}]'::jsonb else '[]'::jsonb end
2848
- || case
2849
- when jsonb_typeof(p_request_approvers -> 'permission') = 'string'
2850
- then jsonb_build_array(jsonb_build_object('kind', 'permission', 'permission', p_request_approvers ->> 'permission'))
2851
- else '[]'::jsonb
2852
- end
2853
- ),
2854
- p_tenant,
2855
- p_requester,
2856
- p_resource
2857
- )
2858
- $$;
2859
- revoke execute on function ${fn}(jsonb, text, text, text, jsonb) from public, anon;
2860
- grant execute on function ${fn}(jsonb, text, text, text, jsonb) to authenticated;
2861
- `;
2862
- }
2863
- /**
2864
- * The request fields an adopted table may mirror into its own columns, as SQL
2865
- * over a body.
2866
- */
2867
- const MIRRORS = {
2868
- status: (body) => `${body} ->> 'status'`,
2869
- permission: (body) => `${body} ->> 'permission'`,
2870
- tenant: (body) => `${body} #>> '{subject,principal,tenant}'`,
2871
- principalId: (body) => `${body} #>> '{subject,principal,id}'`,
2872
- actorId: (body) => `${body} #>> '{subject,actor,id}'`,
2873
- session: (body) => `${body} #>> '{subject,session}'`,
2874
- approvals: (body) => `coalesce(jsonb_array_length(${body} -> 'approvals'), 0)`,
2875
- createdAt: (body) => `${body} ->> 'createdAt'`,
2876
- expiresAt: (body) => `${body} ->> 'expiresAt'`,
2877
- resolvedAt: (body) => `${body} ->> 'resolvedAt'`,
2878
- resolvedBy: (body) => `${body} ->> 'resolvedBy'`,
2879
- consumedAt: (body) => `${body} ->> 'consumedAt'`
2880
- };
2881
- function mirrorsOf(adopt) {
2882
- const out = [];
2883
- for (const [field, column] of Object.entries(adopt.mirror ?? {})) {
2884
- if (!Object.hasOwn(MIRRORS, field)) throw configError(`PermDock CLI: rls.approvals.mirror.${field} is not a request field; use ${Object.keys(MIRRORS).join(", ")}`);
2885
- if (typeof column !== "string") throw new TypeError(`PermDock CLI: rls.approvals.mirror.${field} must be a column name`);
2886
- out.push([column, field]);
2887
- }
2888
- return out;
2889
- }
2890
- /**
2891
- * One row of `table` from `values` (column, SQL), each converted to the
2892
- * column's own type.
2893
- */
2894
- function populate(table, values) {
2895
- return `pg_catalog.jsonb_populate_record(null::${table}, pg_catalog.jsonb_build_object(${values.map(([column, sql]) => `${quoteLiteral(column)}, ${sql}`).join(", ")}))`;
2896
- }
2897
- /** The mirrored columns' values for the request `body`. */
2898
- function mirrorRow(table, mirror, body) {
2899
- return populate(table, mirror.map(([column, field]) => [column, MIRRORS[field](body)]));
2900
- }
2901
- /**
2902
- * `, (<mirrored columns>) = (select …)` for an update that writes `body`; empty
2903
- * without mirrors.
2904
- */
2905
- function mirrorSet(table, mirror, body) {
2906
- if (mirror.length === 0) return "";
2907
- const columns = mirror.map(([column]) => quoteIdent(column));
2908
- const picked = columns.map((column) => `r.${column}`).join(", ");
2909
- return `,\n ${columns.length === 1 ? columns[0] ?? "" : `(${columns.join(", ")})`} = (select ${picked} from ${mirrorRow(table, mirror, body)} r)`;
2910
- }
2911
- /**
2912
- * The approval store over a table the app already has (`rls.approvals: { table,
2913
- * token?, body?, mirror? }`): the same `permdock_approval_*` functions, reading
2914
- * every field from the request body in `body`, keyed by the text column
2915
- * `token`, and copying the fields `mirror` names into the app's own columns,
2916
- * converted to their types, on every write. The table's grants and policies
2917
- * stay the app's.
2918
- */
2919
- function adoptedApprovalStoreSql(ctx, adopt, jsonSchema = false) {
2920
- const table = quoteQualified(adopt.table);
2921
- const base = adopt.table.split(".").at(-1) ?? adopt.table;
2922
- const token = quoteIdent(adopt.token ?? "token");
2923
- const body = quoteIdent(adopt.body ?? "body");
2924
- const mirror = mirrorsOf(adopt);
2925
- 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`);
2926
- const open = adopt.open ?? "insert";
2927
- if (open !== "insert" && open !== "attach") throw configError(`PermDock CLI: rls.approvals.open must be 'insert' or 'attach', got '${String(open)}'`);
2928
- const schema = adopt.schema;
2929
- if (schema !== void 0 && (typeof schema !== "string" || schema === "")) throw configError("PermDock CLI: rls.approvals.schema must be a schema name");
2930
- const fn = (name) => schema === void 0 ? qualified$1(ctx, name) : `${quoteIdent(schema)}.${name}`;
2931
- const index = (name) => quoteIdent(`${base}_permdock_${name}`);
2932
- const status = `a.${body} ->> 'status'`;
2933
- const expires = `(a.${body} ->> 'expiresAt')::timestamptz`;
2934
- const created = `(a.${body} ->> 'createdAt')`;
2935
- const filter = `(p_filter ->> 'status' is null or ${status} = p_filter ->> 'status')
2936
- and (p_filter ->> 'tenant' is null or a.${body} #>> '{subject,principal,tenant}' = p_filter ->> 'tenant')
2937
- and (p_filter ->> 'principalId' is null or a.${body} #>> '{subject,principal,id}' = p_filter ->> 'principalId')
2938
- and (p_filter ->> 'actorId' is null or a.${body} #>> '{subject,actor,id}' = p_filter ->> 'actorId')
2939
- and (p_filter ->> 'session' is null or a.${body} #>> '{subject,session}' = p_filter ->> 'session')`;
2940
- const columns = [
2941
- token,
2942
- body,
2943
- ...mirror.map(([column]) => quoteIdent(column))
2944
- ];
2945
- const inserted = populate(table, [
2946
- [adopt.token ?? "token", "p_request ->> 'token'"],
2947
- [adopt.body ?? "body", "p_request"],
2948
- ...mirror.map(([column, field]) => [column, MIRRORS[field]("p_request")])
2949
- ]);
2950
- const insertSql = `-- open a request; a repeated ask keeps the open record and replaces only an expired one
2951
- create or replace function ${fn(APPROVAL_STORE.open)}(p_request jsonb)
2952
- returns void
2953
- language sql
2954
- volatile
2955
- security definer
2956
- set search_path = ''
2957
- as $$
2958
- insert into ${table} as a (${columns.join(", ")})
2959
- select ${columns.map((column) => `r.${column}`).join(", ")}
2960
- from ${inserted} r
2961
- on conflict (${token}) do update
2962
- set ${columns.filter((column) => column !== token).map((column) => `${column} = excluded.${column}`).join(", ")}
2963
- where ${status} = 'expired' or ${expires} <= now()
2964
- $$;`;
2965
- const attachSql = `create or replace function ${fn(APPROVAL_STORE.open)}(p_request jsonb)
2966
- returns void
2967
- language plpgsql
2968
- volatile
2969
- security definer
2970
- set search_path = ''
2971
- as $$
2972
- begin
2973
- update ${table} a
2974
- set ${body} = p_request${mirrorSet(table, mirror, "p_request")}
2975
- where a.${token} = p_request ->> 'token'
2976
- and (a.${body} is null or ${status} = 'expired' or ${expires} <= now());
2977
- if not found and not exists (select 1 from ${table} a where a.${token} = p_request ->> 'token') then
2978
- raise exception using
2979
- errcode = 'P0002',
2980
- message = 'permdock: no row of ${adopt.table.replaceAll("'", "''")} holds approval token ' || (p_request ->> 'token'),
2981
- hint = 'insert the application row with this token before opening the request';
2982
- end if;
2983
- end;
2984
- $$;`;
2985
- return `-- approval store adopted onto ${adopt.table}: ApprovalRequest bodies in ${adopt.body ?? "body"}, keyed by ${adopt.token ?? "token"}; supabaseApprovalStore calls the functions below
2986
- alter table ${table} add column if not exists ${token} text;
2987
- 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';
2988
- alter table ${table} add column if not exists ${body} jsonb;
2989
- create unique index if not exists ${index("token")} on ${table} (${token});
2990
- create index if not exists ${index("page")} on ${table} ((${body} ->> 'createdAt') collate "C", ${token} collate "C");
2991
- create index if not exists ${index("status")} on ${table} ((${body} ->> 'status'));
2992
- ${jsonSchema === false ? "" : bodySchemaSql(table, jsonSchema, body, `${base}_permdock_body_schema`)}
2993
- ${open === "attach" ? attachSql : insertSql}
2994
- ${serverOnly(fn(APPROVAL_STORE.open), "jsonb")}
2995
-
2996
- create or replace function ${fn(APPROVAL_STORE.get)}(p_token text)
2997
- returns jsonb
2998
- language sql
2999
- stable
3000
- security definer
3001
- set search_path = ''
3002
- as $$
3003
- select a.${body} from ${table} a where a.${token} = p_token
3004
- $$;
3005
- ${serverOnly(fn(APPROVAL_STORE.get), "text")}
3006
-
3007
- -- write a verdict over the record it was computed from: still pending, unexpired, with p_seen approvals
3008
- create or replace function ${fn(APPROVAL_STORE.resolve)}(p_token text, p_next jsonb, p_seen integer)
3009
- returns jsonb
3010
- language sql
3011
- volatile
3012
- security definer
3013
- set search_path = ''
3014
- as $$
3015
- update ${table} a
3016
- set ${body} = p_next${mirrorSet(table, mirror, "p_next")}
3017
- where a.${token} = p_token
3018
- and ${status} = 'pending'
3019
- and ${expires} > now()
3020
- and coalesce(jsonb_array_length(a.${body} -> 'approvals'), 0) = p_seen
3021
- returning a.${body}
3022
- $$;
3023
- ${serverOnly(fn(APPROVAL_STORE.resolve), "text, jsonb, integer")}
3024
-
3025
- -- consume an approved, unexpired, unconsumed request once
3026
- create or replace function ${fn(APPROVAL_STORE.consume)}(p_token text, p_now text)
3027
- returns jsonb
3028
- language sql
3029
- volatile
3030
- security definer
3031
- set search_path = ''
3032
- as $$
3033
- update ${table} a
3034
- set ${body} = a.${body} || jsonb_build_object('consumedAt', p_now)${mirrorSet(table, mirror, `(a.${body} || jsonb_build_object('consumedAt', p_now))`)}
3035
- where a.${token} = p_token
3036
- and ${status} = 'approved'
3037
- and a.${body} ->> 'consumedAt' is null
3038
- and ${expires} > p_now::timestamptz
3039
- returning a.${body}
3040
- $$;
3041
- ${serverOnly(fn(APPROVAL_STORE.consume), "text, text")}
3042
-
3043
- -- one page in (createdAt, token) order after the cursor position
3044
- create or replace function ${fn(APPROVAL_STORE.list)}(p_filter jsonb, p_after_created text, p_after_token text, p_limit integer)
3045
- returns setof jsonb
3046
- language sql
3047
- stable
3048
- security definer
3049
- set search_path = ''
3050
- as $$
3051
- select a.${body}
3052
- from ${table} a
3053
- where a.${body} is not null
3054
- and ${filter}
3055
- and (p_after_created is null
3056
- or (${created} collate "C", a.${token} collate "C") > (p_after_created collate "C", p_after_token collate "C"))
3057
- order by ${created} collate "C", a.${token} collate "C"
3058
- limit p_limit
3059
- $$;
3060
- ${serverOnly(fn(APPROVAL_STORE.list), "jsonb, text, text, integer")}
3061
-
3062
- create or replace function ${fn(APPROVAL_STORE.expire)}(p_now text)
3063
- returns integer
3064
- language sql
3065
- volatile
3066
- security definer
3067
- set search_path = ''
3068
- as $$
3069
- with expired as (
3070
- update ${table} a
3071
- set ${body} = a.${body} || '{"status":"expired"}'::jsonb${mirrorSet(table, mirror, `(a.${body} || '{"status":"expired"}'::jsonb)`)}
3072
- where ${status} = 'pending' and ${expires} <= p_now::timestamptz
3073
- returning 1
3074
- )
3075
- select count(*)::integer from expired
3076
- $$;
3077
- ${serverOnly(fn(APPROVAL_STORE.expire), "text")}
3078
-
3079
- -- reject every pending request the filter matches, as system:<by>
3080
- create or replace function ${fn(APPROVAL_STORE.cancel)}(p_filter jsonb, p_by text, p_note text, p_now text)
3081
- returns integer
3082
- language sql
3083
- volatile
3084
- security definer
3085
- set search_path = ''
3086
- as $$
3087
- with cancelled as (
3088
- update ${table} a
3089
- set ${body} = (a.${body} - 'note') || jsonb_strip_nulls(jsonb_build_object(
3090
- 'status', 'rejected', 'resolvedAt', p_now, 'resolvedBy', 'system:' || p_by, 'note', p_note
3091
- ))${mirrorSet(table, mirror, `((a.${body} - 'note') || jsonb_strip_nulls(jsonb_build_object('status', 'rejected', 'resolvedAt', p_now, 'resolvedBy', 'system:' || p_by, 'note', p_note)))`)}
3092
- where ${status} = 'pending'
3093
- and ${filter.replaceAll("\n ", "\n ")}
3094
- returning 1
3095
- )
3096
- select count(*)::integer from cancelled
3097
- $$;
3098
- ${serverOnly(fn(APPROVAL_STORE.cancel), "jsonb, text, text, text")}
3099
- `;
3100
- }
3101
- //#endregion
3102
- //#region src/cli/supabase-hook/sql.ts
3103
- const MANAGED_TRIGGER = "permdock_protect_managed";
3104
- function schemaSql(parts) {
3105
- if (parts.schema === "public") return "";
3106
- const schema = quoteIdent(parts.schema);
3107
- return `create schema if not exists ${schema};\nrevoke all on schema ${schema} from public;`;
3108
- }
3109
- function hookSql(parts) {
3110
- const schema = quoteIdent(parts.schema);
3111
- const fn = `${schema}.custom_access_token_hook`;
3112
- const roles = heldSql(parts, "uid");
3113
- const plan = parts.attrs;
3114
- const tableMembershipSource = plan === void 0 || plan.columns.length === 0 || plan.table === void 0 ? "" : `
3115
- select jsonb_strip_nulls(jsonb_build_object(${plan.columns.map((column) => `${quoteLiteral(column)}, to_jsonb(p.${quoteIdent(column)})`).join(", ")}))
3116
- into attrs
3117
- from ${quoteQualified(plan.table)} p
3118
- where p.${quoteIdent(plan.id)} = v_attrs_user;`;
3119
- const fromMeta = plan === void 0 || plan.meta.length === 0 ? "" : `
3120
- attrs := coalesce(attrs, '{}'::jsonb) || jsonb_strip_nulls(jsonb_build_object(${plan.meta.map((key) => `${quoteLiteral(key)}, claims -> 'app_metadata' -> ${quoteLiteral(key)}`).join(", ")}));`;
3121
- const attrs = plan === void 0 ? "" : `${tableMembershipSource}${fromMeta}
3122
- if attrs is not null and attrs <> '{}'::jsonb then
3123
- used := octet_length(attrs::text);
3124
- if used > budget then
3125
- truncated := true;
3126
- used := 0;
3127
- else
3128
- claims := jsonb_set(claims, '{attrs}', attrs);
3129
- end if;
3130
- end if;`;
3131
- const versionTable = `${schema}.${quoteIdent(AUTHZ_VERSION_TABLE)}`;
3132
- const version = parts.version ? `
3133
- select v.version into ver from ${versionTable} v where v.user_id = uid;
3134
- claims := jsonb_set(claims, '{authz_ver}', to_jsonb(coalesce(ver, 0)));` : "";
3135
- const dropExtra = parts.extra.map((entry) => ` - ${quoteLiteral(entry.claim)}`).join("");
3136
- const extra = parts.extra.map((entry) => `
3137
- extra := ${quoteTable(entry.fn)}(uid);
3138
- if extra is not null then
3139
- claims := jsonb_set(claims, ${quoteLiteral(`{${entry.claim}}`)}, extra);
3140
- end if;`).join("");
3141
- const dropTeams = parts.hook.teams === void 0 ? "" : " - 'team_ids'";
3142
- const suspended = parts.users === void 0 ? "" : `
3143
- if not ${activeRowSql(parts.users, "uid")} then
3144
- claims := claims - 'memberships_truncated' - 'attrs'${dropTeams} - ${quoteLiteral(parts.tenantClaim)}${dropExtra};
3145
- claims := claims || jsonb_build_object('user_role', '[]'::jsonb, 'roles', '[]'::jsonb, 'memberships', '[]'::jsonb);${version}
3146
- return jsonb_set(event, '{claims}', claims);
3147
- end if;`;
3148
- const teamsConfig = parts.hook.teams;
3149
- const teams = teamsConfig === void 0 ? "" : `
3150
- for team in
3151
- select t.${quoteIdent(teamsConfig.team)}::text as id
3152
- from ${quoteQualified(teamsConfig.table)} t
3153
- where t.${quoteIdent(teamsConfig.user)} = uid
3154
- order by ${teamsConfig.tenant === void 0 ? "" : `(t.${quoteIdent(teamsConfig.tenant)}::text is not distinct from active) desc, `}t.${quoteIdent(teamsConfig.team)}
3155
- loop
3156
- if octet_length(kept::text) + used + octet_length((team_ids || to_jsonb(team.id))::text) > budget then
3157
- truncated := true;
3158
- exit;
3159
- end if;
3160
- team_ids := team_ids || jsonb_build_array(team.id);
3161
- end loop;
3162
- if team_ids <> '[]'::jsonb then
3163
- claims := jsonb_set(claims, '{team_ids}', team_ids);
3164
- end if;`;
3165
- return `create or replace function ${fn}(event jsonb)
3166
- returns jsonb
3167
- language plpgsql
3168
- stable${parts.hook.security === "definer" ? "\nsecurity definer" : ""}
3169
- set search_path = ''
3170
- as $$
3171
- declare
3172
- claims jsonb := event -> 'claims';
3173
- uid uuid := (event ->> 'user_id')::uuid;
3174
- active text;
3175
- held jsonb;
3176
- kept jsonb := '[]'::jsonb;
3177
- truncated boolean := false;
3178
- in_active boolean := false;
3179
- budget integer := ${String(parts.budget)};
3180
- used integer := 0;
3181
- item record;${teamsConfig === void 0 ? "" : "\n team record;\n team_ids jsonb := '[]'::jsonb;"}${typedUsers(parts)}${plan === void 0 ? "" : "\n attrs jsonb;"}${parts.extra.length === 0 ? "" : "\n extra jsonb;"}${parts.version ? "\n ver bigint;" : ""}${parts.before.length === 0 ? "" : "\n checked jsonb;"}
3182
- begin${beforeSql(parts.before)}${suspended}
3183
- claims := claims - 'attrs'${dropTeams}${dropExtra};
3184
- ${roles}
3185
- claims := jsonb_set(claims, '{roles}', held);
3186
- if jsonb_array_length(held) = 1 then
3187
- claims := jsonb_set(claims, '{user_role}', held -> 0);
3188
- elsif jsonb_array_length(held) > 1 then
3189
- claims := jsonb_set(claims, '{user_role}', held);
3190
- end if;
3191
- active := ${parts.active.sql};${attrs}
3192
- for item in
3193
- select x.entry, x.root_id is not distinct from active as current
3194
- from (
3195
- select e.ord, e.entry, ${entryTenantSql(parts, "e")} as root_id
3196
- from ${quoteIdent(parts.schema)}.${MEMBERSHIP_ENTRIES_FOR}(uid) e
3197
- ) x
3198
- order by (x.root_id is not distinct from active) desc, x.ord, x.entry ->> 'scope', x.entry ->> 'id', x.entry::text
3199
- loop
3200
- if octet_length((kept || jsonb_build_array(item.entry))::text) + used > budget then
3201
- truncated := true;
3202
- exit;
3203
- end if;
3204
- kept := kept || jsonb_build_array(item.entry);
3205
- in_active := in_active or (active is not null and item.current);
3206
- end loop;
3207
- claims := jsonb_set(claims, '{memberships}', kept);${teams}
3208
- if truncated then
3209
- claims := jsonb_set(claims, '{memberships_truncated}', 'true'::jsonb);
3210
- else
3211
- claims := claims - 'memberships_truncated';
3212
- end if;
3213
- if in_active then
3214
- claims := jsonb_set(claims, ${quoteLiteral(`{${parts.tenantClaim}}`)}, to_jsonb(active));
3215
- end if;${extra}${version}${validateSql(parts)}
3216
- return jsonb_set(event, '{claims}', claims);
3217
- end;
3218
- $$;`;
3219
- }
3220
- /** Everything the hook grants `supabase_auth_admin`, and the execute revoke. */
3221
- function grantsSql(parts) {
3222
- const schema = quoteIdent(parts.schema);
3223
- const fn = `${schema}.custom_access_token_hook`;
3224
- if (parts.hook.security === "definer") return `-- supabase_auth_admin: execute only; the hook reads with its owner's rights
3225
- revoke execute on function ${fn}(jsonb) from authenticated, anon, public;
3226
- grant usage on schema ${schema} to supabase_auth_admin;
3227
- grant execute on function ${fn}(jsonb) to supabase_auth_admin;${extraRevokesSql(parts.extra, parts.before)}`;
3228
- return [
3229
- `-- supabase_auth_admin: the grants and read policies the hook needs
3230
- grant usage on schema ${schema} to supabase_auth_admin;
3231
- grant execute on function ${fn}(jsonb) to supabase_auth_admin;
3232
- revoke execute on function ${fn}(jsonb) from authenticated, anon, public;${extraGrantsSql(parts.extra)}${beforeGrantsSql(parts.before, parts.extra)}${entriesGrantsSql(parts)}${memberForGrantsSql(parts)}${validateGrantsSql(parts)}`,
3233
- readsSql(parts),
3234
- parts.version ? authAdminRead(`${parts.schema}.${AUTHZ_VERSION_TABLE}`, "version") : ""
3235
- ].filter((chunk) => chunk !== "").join("\n");
3236
- }
3237
- /**
3238
- * A definer hook calls `hook.claims` and `hook.before` functions as its owner,
3239
- * so they need no grant; they are still revoked from the client roles.
3240
- */
3241
- function extraRevokesSql(extra, before) {
3242
- 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("");
3243
- }
3244
- function extraGrantsSql(extra) {
3245
- 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("");
3246
- }
3247
- function beforeGrantsSql(before, extra) {
3248
- const granted = new Set(extra.map((entry) => entry.fn.split(".")[0]));
3249
- 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("");
3250
- }
3251
- /**
3252
- * Execute on each `member_<scope>_ids_for(uuid)` for the `hook.claims`
3253
- * functions, which run as `supabase_auth_admin` and may call them. Only with
3254
- * `hook.claims`: the grant needs the helpers migration applied first, and a
3255
- * hook without extra claims does not.
3256
- */
3257
- function memberForGrantsSql(parts) {
3258
- const { schema, memberFor } = parts.helpers;
3259
- if (memberFor.length === 0 || parts.extra.length === 0) return "";
3260
- return [...schema === parts.schema ? [] : [`\ngrant usage on schema ${quoteIdent(schema)} to supabase_auth_admin;`], ...memberFor.map((scope) => `\ngrant execute on function ${quoteIdent(schema)}.${memberForHelper(scope)}(uuid) to supabase_auth_admin;`)].join("");
3261
- }
3262
- function readsSql(parts) {
3263
- const reads = /* @__PURE__ */ new Map();
3264
- for (const source of parts.sources) reads.set(source.sql.table, "memberships");
3265
- for (const source of parts.sources) {
3266
- for (const name of source.sql.reads) reads.set(name, reads.get(name) ?? "status");
3267
- for (const through of source.sql.throughs) reads.set(through.table, reads.get(through.table) ?? "role_keys");
3268
- const users = source.sql.userThrough;
3269
- if (users !== void 0) reads.set(users.table, reads.get(users.table) ?? "member_users");
3270
- }
3271
- if (parts.roles !== void 0) {
3272
- const { table: rolesTable, through } = parts.roles;
3273
- reads.set(rolesTable, reads.get(rolesTable) ?? "roles");
3274
- if (through !== void 0) reads.set(through.table, reads.get(through.table) ?? "role_keys");
3275
- }
3276
- if (parts.hook.teams !== void 0) reads.set(parts.hook.teams.table, reads.get(parts.hook.teams.table) ?? "teams");
3277
- if (parts.attrs?.table !== void 0 && parts.attrs.columns.length > 0) reads.set(parts.attrs.table, reads.get(parts.attrs.table) ?? "attrs");
3278
- if (parts.users !== void 0) reads.set(parts.users.table, reads.get(parts.users.table) ?? "status_users");
3279
- 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");
3280
- }
3281
- function managedSql(parts) {
3282
- const managed = parts.sources.filter((source) => source.sql.managed !== void 0);
3283
- if (managed.length === 0) return "";
3284
- const guard = `${quoteIdent(parts.schema)}.permdock_protect_managed`;
3285
- return `-- memberships the identity provider owns: clients (anon, authenticated) cannot write them
3286
- create or replace function ${guard}()
3287
- returns trigger
3288
- language plpgsql
3289
- set search_path = ''
3290
- as $$
3291
- declare
3292
- column_name text := tg_argv[0];
3293
- begin
3294
- if current_user in ('anon', 'authenticated') and (
3295
- column_name = ''
3296
- or (tg_op <> 'INSERT' and to_jsonb(old) ->> column_name = 'idp')
3297
- or (tg_op <> 'DELETE' and to_jsonb(new) ->> column_name = 'idp')
3298
- ) then
3299
- raise exception 'PermDock: % rows managed by the identity provider cannot be changed here', tg_table_name
3300
- using errcode = '42501';
3301
- end if;
3302
- return coalesce(new, old);
3303
- end;
3304
- $$;
3305
- ${managed.map((source) => `drop trigger if exists ${quoteIdent(MANAGED_TRIGGER)} on ${quoteQualified(source.sql.table)};
3306
- create trigger ${quoteIdent(MANAGED_TRIGGER)}
3307
- before insert or update or delete on ${quoteQualified(source.sql.table)}
3308
- for each row execute function ${guard}(${quoteLiteral(source.sql.managed ?? "")});`).join("\n")}`;
3309
- }
3310
- /** The `config.toml` block that enables the hook and bounds token staleness. */
3311
- function configToml(schema, jwtExpiry) {
3312
- return `[auth]
3313
- jwt_expiry = ${String(jwtExpiry)}
3314
-
3315
- [auth.hook.custom_access_token]
3316
- enabled = true
3317
- uri = "${hookUri(schema)}"`;
3318
- }
3319
- const BUDGET_MEASURE = "octet_length(memberships::text) + octet_length(attrs::text)";
3320
- function hookParts(scopes, config, overrides) {
3321
- const hook = config.supabase?.hook;
3322
- if (hook === void 0) throw configError("PermDock CLI: supabase hook generate needs supabase.hook in permdock.config.ts");
3323
- const root = rootScope(scopes) ?? "tenant";
3324
- const suspension = checkSuspension(hook.suspension ?? config.rls?.suspension, scopes);
3325
- const schema = overrides.schema ?? hook.schema ?? config.rls?.schema ?? "permdock";
3326
- quoteIdent(schema);
3327
- const tenantClaim = config.rls?.tenantClaim ?? "tenant_id";
3328
- const extraPlan = extraClaimsPlan(hook.claims, tenantClaim);
3329
- checkSources({
3330
- sources: hook.memberships,
3331
- scopes
3332
- });
3333
- const parts = {
3334
- schema,
3335
- scopes,
3336
- root,
3337
- sources: hook.memberships,
3338
- budget: positiveInteger(overrides.budget ?? hook.budget ?? 1024, "budget"),
3339
- version: hook.version !== false,
3340
- broadcast: hook.version === false || hook.broadcast === false ? void 0 : {
3341
- topic: hook.broadcast?.topic ?? "permdock:authz",
3342
- receivePolicy: hook.broadcast?.receivePolicy ?? true
3343
- },
3344
- jwtExpiry: positiveInteger(hook.jwtExpiry ?? 900, "jwtExpiry"),
3345
- tenantClaim,
3346
- users: suspension?.users,
3347
- hook,
3348
- roles: hook.roles === false ? void 0 : globalRoleSource(hook.roles ?? config.rls?.roles ?? { table: `${schema}.user_roles` }, "public", "r", config.rls?.customRoleWrites?.roles),
3349
- active: activeFromSql(overrides.activeFrom ?? hook.activeFrom, root),
3350
- activeFrom: activeSource(overrides.activeFrom ?? hook.activeFrom, root),
3351
- attrs: hook.attrs === void 0 ? void 0 : attrsPlan(hook.attrs),
3352
- extra: extraPlan.claims,
3353
- before: beforePlan(hook.before),
3354
- helpers: {
3355
- schema: config.rls?.schema ?? "permdock",
3356
- ...memberForPlan({
3357
- scopes,
3358
- ...config.rls?.memberships === void 0 ? {} : { memberships: config.rls.memberships },
3359
- memberSources: membershipSourcesOf(config)
3360
- })
3361
- }
3362
- };
3363
- if (parts.attrs !== void 0 && parts.attrs.errors.length > 0) throw configError(`PermDock CLI: ${parts.attrs.errors.join("; ")}`);
3364
- if (extraPlan.errors.length > 0) throw configError(`PermDock CLI: ${extraPlan.errors.join("; ")}`);
3365
- quoteIdent(parts.tenantClaim);
3366
- return parts;
3367
- }
3368
- //#endregion
3369
- //#region src/cli/supabase-hook/teams.ts
3370
- /**
3371
- * The `member_team_ids_of` helper the hook file writes from
3372
- * `supabase.hook.teams`, or `undefined` when there is no teams table or `rls
3373
- * generate` already writes one for a `team` or `teams` scope.
3374
- */
3375
- function hookTeamsHelper(parts) {
3376
- if (parts.hook.teams === void 0) return;
3377
- return parts.helpers.memberFor.some((scope) => isTeamScope(scope)) ? void 0 : memberOfHelper("team");
3378
- }
3379
- /**
3380
- * `member_team_ids_of(p_user uuid)`: the teams `supabase.hook.teams` lists for
3381
- * the caller, the rows the hook writes to `team_ids`. Any other `p_user`, and a
3382
- * suspended user, gets no rows, so `authenticated` may execute it. The team
3383
- * column is a uuid, as the `team_ids` claim is.
3384
- */
3385
- function teamIdsOfSql(parts) {
3386
- const name = hookTeamsHelper(parts);
3387
- const teams = parts.hook.teams;
3388
- if (name === void 0 || teams === void 0) return "";
3389
- const fn = `${quoteIdent(parts.helpers.schema)}.${quoteIdent(name)}`;
3390
- const active = parts.users === void 0 ? "" : `\n and ${activeRowSql(parts.users, "p_user")}`;
3391
- return `-- the caller's teams from supabase.hook.teams, for better-supabase's teamIdsOf
3392
- create or replace function ${fn}(p_user uuid)
3393
- returns setof uuid
3394
- language sql
3395
- stable
3396
- security definer
3397
- set search_path = ''
3398
- as $$
3399
- select t.${quoteIdent(teams.team)}
3400
- from ${quoteQualified(teams.table)} t
3401
- where t.${quoteIdent(teams.user)} = p_user
3402
- and p_user = (select auth.uid())${active}
3403
- $$;
3404
- revoke execute on function ${fn}(uuid) from public, anon;
3405
- grant execute on function ${fn}(uuid) to authenticated;`;
3406
- }
3407
- //#endregion
3408
- //#region src/cli/supabase-hook/version.ts
3409
- const VERSION_TRIGGER = "permdock_authz_version";
3410
- const AUTHZ_VERSION_BUMP = "permdock_bump_authz_version_for";
3411
- function versionSql(parts) {
3412
- if (!parts.version) return "";
3413
- const schema = quoteIdent(parts.schema);
3414
- const versionTable = `${schema}.${quoteIdent(AUTHZ_VERSION_TABLE)}`;
3415
- const bump = `${schema}.permdock_bump_authz_version`;
3416
- const bumpFor = `${schema}.${AUTHZ_VERSION_BUMP}`;
3417
- const tables = [...new Map(parts.sources.filter((source) => source.sql.userThrough === void 0).map((source) => [source.sql.table, source.sql.user]))];
3418
- if (parts.roles !== void 0) tables.push([parts.roles.table, parts.roles.user]);
3419
- return `-- the authorization version: bumped on every membership change, written to authz_ver
3420
- create table if not exists ${versionTable} (
3421
- user_id uuid primary key references auth.users on delete cascade,
3422
- version bigint not null default 0
3423
- );
3424
- alter table ${versionTable} enable row level security;
3425
- revoke all on table ${versionTable} from anon, authenticated, public;
3426
-
3427
- -- bumps each listed user once, skipping users already deleted from auth.users; no client role may call it
3428
- create or replace function ${bumpFor}(p_users uuid[])
3429
- returns void
3430
- language sql
3431
- security definer
3432
- set search_path = ''
3433
- as $$
3434
- insert into ${versionTable} as v (user_id, version)
3435
- select distinct u, 1 from unnest(p_users) u
3436
- where u is not null and exists (select 1 from auth.users au where au.id = u)
3437
- on conflict (user_id) do update set version = v.version + 1;
3438
- select set_config(
3439
- 'permdock.m.gen',
3440
- (coalesce(nullif(current_setting('permdock.m.gen', true), ''), '0')::int + 1)::text,
3441
- true
3442
- )
3443
- $$;
3444
- revoke execute on function ${bumpFor}(uuid[]) from public, anon, authenticated;
3445
-
3446
- create or replace function ${bump}()
3447
- returns trigger
3448
- language plpgsql
3449
- security definer
3450
- set search_path = ''
3451
- as $$
3452
- declare
3453
- column_name text := tg_argv[0];
3454
- begin
3455
- perform ${bumpFor}(array[
3456
- case when tg_op <> 'INSERT' then to_jsonb(old) ->> column_name end,
3457
- case when tg_op <> 'DELETE' then to_jsonb(new) ->> column_name end
3458
- ]::uuid[]);
3459
- return null;
3460
- end;
3461
- $$;
3462
- revoke execute on function ${bump}() from public, anon, authenticated;
3463
- ${tables.map(([name, user]) => `drop trigger if exists ${quoteIdent(VERSION_TRIGGER)} on ${quoteQualified(name)};
3464
- create trigger ${quoteIdent(VERSION_TRIGGER)}
3465
- after insert or update or delete on ${quoteQualified(name)}
3466
- for each row execute function ${bump}(${quoteLiteral(user)});`).join("\n")}${broadcastSql(parts, versionTable)}${memberUsersVersionSql(parts, bumpFor)}${roleKeysVersionSql(parts, versionTable)}`;
3467
- }
3468
- /**
3469
- * Every version row written is sent as `{ user_id, version }` on the server
3470
- * topic and on the user's `authz:<uid>`, in the shape better-supabase's
3471
- * `subscribeAuthzVersions` and `SessionProvider` read.
3472
- */
3473
- function broadcastSql(parts, versionTable) {
3474
- const broadcast = parts.broadcast;
3475
- if (broadcast === void 0) return "";
3476
- const send = `${quoteIdent(parts.schema)}.permdock_broadcast_authz_version`;
3477
- const payload = "jsonb_build_object('user_id', new.user_id, 'version', new.version)";
3478
- const event = quoteLiteral(AUTHZ_EVENT);
3479
- const receive = broadcast.receivePolicy ? `
3480
-
3481
- -- each user receives their own authz:<uid> topic, and no user may join the server topic
3482
- do $$
3483
- begin
3484
- if to_regclass('realtime.messages') is not null and not exists (
3485
- select 1 from pg_policies
3486
- where schemaname = 'realtime' and tablename = 'messages'
3487
- and policyname = 'permdock_authz_version_receive'
3488
- ) then
3489
- create policy permdock_authz_version_receive on realtime.messages
3490
- for select to authenticated
3491
- using (
3492
- realtime.messages.extension = 'broadcast'
3493
- and (select realtime.topic()) = 'authz:' || (select auth.uid())::text
3494
- );
3495
- end if;
3496
- end;
3497
- $$;` : "";
3498
- return `
3499
-
3500
- -- sends every version bump on the server topic and on the user's authz:<uid>
3501
- create or replace function ${send}()
3502
- returns trigger
3503
- language plpgsql
3504
- security definer
3505
- set search_path = ''
3506
- as $$
3507
- begin
3508
- if to_regprocedure('realtime.send(jsonb, text, text, boolean)') is not null then
3509
- perform realtime.send(${payload}, ${event}, ${quoteLiteral(broadcast.topic)}, true);
3510
- perform realtime.send(${payload}, ${event}, 'authz:' || new.user_id::text, true);
3511
- end if;
3512
- return null;
3513
- end;
3514
- $$;
3515
- revoke execute on function ${send}() from public, anon, authenticated;
3516
- drop trigger if exists permdock_authz_version_broadcast on ${versionTable};
3517
- create trigger permdock_authz_version_broadcast
3518
- after insert or update on ${versionTable}
3519
- for each row execute function ${send}();${receive}`;
3520
- }
3521
- function signedUp(user) {
3522
- return `exists (select 1 from auth.users a where a.id = ${user})`;
3523
- }
3524
- /**
3525
- * Every membership source whose user id lives in another table: a row of the
3526
- * source bumps the users its old and new references hold, and a change of that
3527
- * table's user id (a contact re-linked to another login) bumps the old and the
3528
- * new user.
3529
- */
3530
- function memberUsersVersionSql(parts, bumpFor) {
3531
- const holders = /* @__PURE__ */ new Map();
3532
- for (const source of parts.sources) {
3533
- const users = source.sql.userThrough;
3534
- if (users !== void 0) holders.set(JSON.stringify([
3535
- tableKey(source.sql.table),
3536
- tableKey(users.table),
3537
- users.id,
3538
- users.key,
3539
- users.ref
3540
- ]), {
3541
- table: source.sql.table,
3542
- users
3543
- });
3544
- }
3545
- if (holders.size === 0) return "";
3546
- const byTable = /* @__PURE__ */ new Map();
3547
- for (const holder of holders.values()) {
3548
- const key = tableKey(holder.table);
3549
- const group = byTable.get(key);
3550
- if (group === void 0) byTable.set(key, {
3551
- table: holder.table,
3552
- users: [holder.users]
3553
- });
3554
- else group.users.push(holder.users);
3555
- }
3556
- const memberBump = `${quoteIdent(parts.schema)}.permdock_bump_authz_version_member_users`;
3557
- const linkedBump = `${quoteIdent(parts.schema)}.permdock_bump_authz_version_linked_users`;
3558
- const groups = [...byTable];
3559
- const lookup = (users, indent) => `${indent}perform ${bumpFor}(array(
3560
- ${indent} select u.${quoteIdent(users.key)}::uuid from ${quoteQualified(users.table)} u
3561
- ${indent} where ((tg_op <> 'INSERT' and u.${quoteIdent(users.id)} = old.${quoteIdent(users.ref)})
3562
- ${indent} or (tg_op <> 'DELETE' and u.${quoteIdent(users.id)} = new.${quoteIdent(users.ref)}))
3563
- ${indent} and ${signedUp(`u.${quoteIdent(users.key)}::uuid`)}
3564
- ${indent}));`;
3565
- const body = groups.map(([key, group]) => {
3566
- if (groups.length === 1) return group.users.map((users) => lookup(users, " ")).join("\n");
3567
- const dot = key.indexOf(".");
3568
- return ` if tg_table_schema = ${quoteLiteral(key.slice(0, dot))} and tg_table_name = ${quoteLiteral(key.slice(dot + 1))} then
3569
- ${group.users.map((users) => lookup(users, " ")).join("\n")}
3570
- end if;`;
3571
- }).join("\n");
3572
- const memberTriggers = groups.map(([, group]) => {
3573
- const target = quoteQualified(group.table);
3574
- return `drop trigger if exists ${quoteIdent(VERSION_TRIGGER)} on ${target};
3575
- create trigger ${quoteIdent(VERSION_TRIGGER)}
3576
- after insert or update or delete on ${target}
3577
- for each row execute function ${memberBump}();`;
3578
- }).join("\n");
3579
- const userTables = /* @__PURE__ */ new Map();
3580
- for (const { users } of holders.values()) {
3581
- const key = JSON.stringify([tableKey(users.table), users.key]);
3582
- const entry = userTables.get(key) ?? {
3583
- table: users.table,
3584
- key: users.key,
3585
- ids: /* @__PURE__ */ new Set()
3586
- };
3587
- entry.ids.add(users.id);
3588
- userTables.set(key, entry);
3589
- }
3590
- const userTriggers = [...userTables.values()].map((entry) => {
3591
- const target = quoteQualified(entry.table);
3592
- const name = quoteIdent(`${VERSION_TRIGGER}_${entry.key}`);
3593
- return `drop trigger if exists ${name} on ${target};
3594
- create trigger ${name}
3595
- after update of ${[entry.key, ...entry.ids].map(quoteIdent).join(", ")} or delete on ${target}
3596
- for each row execute function ${linkedBump}(${quoteLiteral(entry.key)});`;
3597
- }).join("\n");
3598
- return `
3599
-
3600
- -- a membership whose user id lives in another table bumps the users its old and new rows reference
3601
- create or replace function ${memberBump}()
3602
- returns trigger
3603
- language plpgsql
3604
- security definer
3605
- set search_path = ''
3606
- as $$
3607
- begin
3608
- ${body}
3609
- return null;
3610
- end;
3611
- $$;
3612
- revoke execute on function ${memberBump}() from public, anon, authenticated;
3613
- ${memberTriggers}
3614
-
3615
- -- re-linking that table's user id moves every membership that references the row: bump the old and the new user,
3616
- -- skipping a login being deleted (its version row goes with it)
3617
- create or replace function ${linkedBump}()
3618
- returns trigger
3619
- language plpgsql
3620
- security definer
3621
- set search_path = ''
3622
- as $$
3623
- declare
3624
- column_name text := tg_argv[0];
3625
- begin
3626
- perform ${bumpFor}(array(
3627
- select u
3628
- from unnest(array[
3629
- case when tg_op <> 'INSERT' then to_jsonb(old) ->> column_name end,
3630
- case when tg_op <> 'DELETE' then to_jsonb(new) ->> column_name end
3631
- ]::uuid[]) u
3632
- where ${signedUp("u")}
3633
- ));
3634
- return null;
3635
- end;
3636
- $$;
3637
- revoke execute on function ${linkedBump}() from public, anon, authenticated;
3638
- ${userTriggers}`;
3639
- }
3640
- /**
3641
- * Every table whose role column references a roles table: the global roles and
3642
- * the membership sources.
3643
- */
3644
- function roleKeyHolders(parts) {
3645
- const holders = [];
3646
- if (parts.roles?.through !== void 0) holders.push({
3647
- table: parts.roles.table,
3648
- user: parts.roles.user,
3649
- through: parts.roles.through
3650
- });
3651
- for (const source of parts.sources) for (const through of source.sql.throughs) holders.push({
3652
- table: source.sql.table,
3653
- user: source.sql.user,
3654
- ...source.sql.userThrough === void 0 ? {} : { userThrough: source.sql.userThrough },
3655
- through
3656
- });
3657
- const seen = /* @__PURE__ */ new Set();
3658
- return holders.filter((holder) => {
3659
- const key = JSON.stringify([
3660
- tableKey(holder.table),
3661
- holder.user,
3662
- holder.userThrough === void 0 ? null : [
3663
- tableKey(holder.userThrough.table),
3664
- holder.userThrough.id,
3665
- holder.userThrough.key
3666
- ],
3667
- tableKey(holder.through.table),
3668
- holder.through.key,
3669
- holder.through.match
3670
- ]);
3671
- if (seen.has(key)) return false;
3672
- seen.add(key);
3673
- return true;
3674
- });
3675
- }
3676
- /**
3677
- * The bump for one roles table: unchanged keys and ids return early, else every
3678
- * holder of `old` is bumped.
3679
- */
3680
- function roleKeysBumpSql(holders, versionTable, indent) {
3681
- return `${indent}if tg_op = 'UPDATE'
3682
- ${indent} and ${[...new Set(holders.flatMap((holder) => [holder.through.key, ...holder.through.match.map(([, id]) => id)]))].map((column) => `new.${quoteIdent(column)} is not distinct from old.${quoteIdent(column)}`).join(`\n${indent} and `)} then
3683
- ${indent} return null;
3684
- ${indent}end if;
3685
- ${indent}insert into ${versionTable} as v (user_id, version)
3686
- ${indent}select distinct h.user_id, 1
3687
- ${indent}from (
3688
- ${indent} ${holders.map((holder) => {
3689
- const held = holder.through.match.map(([ref, id]) => `h.${quoteIdent(ref)} = old.${quoteIdent(id)}`).join(" and ");
3690
- return holder.userThrough === void 0 ? `select h.${quoteIdent(holder.user)}::uuid as user_id from ${quoteQualified(holder.table)} h where ${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)} where ${held}`;
3691
- }).join(`\n${indent} union\n${indent} `)}
3692
- ${indent}) h
3693
- ${indent}where h.user_id is not null
3694
- ${indent} and exists (select 1 from auth.users au where au.id = h.user_id)
3695
- ${indent}on conflict (user_id) do update set version = v.version + 1;`;
3696
- }
3697
- /**
3698
- * A renamed role key changes the `roles` claim of everyone who holds it and the
3699
- * `roles` of every membership that references it, so updates to a roles table
3700
- * bump each holder.
3701
- */
3702
- function roleKeysVersionSql(parts, versionTable) {
3703
- const holders = roleKeyHolders(parts);
3704
- if (holders.length === 0) return "";
3705
- const byTable = /* @__PURE__ */ new Map();
3706
- for (const holder of holders) {
3707
- const key = tableKey(holder.through.table);
3708
- const group = byTable.get(key);
3709
- if (group === void 0) byTable.set(key, {
3710
- table: holder.through.table,
3711
- holders: [holder]
3712
- });
3713
- else group.holders.push(holder);
3714
- }
3715
- const bump = `${quoteIdent(parts.schema)}.permdock_bump_authz_version_role_keys`;
3716
- const groups = [...byTable];
3717
- return `
3718
-
3719
- -- a renamed role key changes the roles of everyone who holds it, globally or through a membership
3720
- create or replace function ${bump}()
3721
- returns trigger
3722
- language plpgsql
3723
- security definer
3724
- set search_path = ''
3725
- as $$
3726
- begin
3727
- ${groups.map(([key, group]) => {
3728
- if (groups.length === 1) return roleKeysBumpSql(group.holders, versionTable, " ");
3729
- const dot = key.indexOf(".");
3730
- return ` if tg_table_schema = ${quoteLiteral(key.slice(0, dot))} and tg_table_name = ${quoteLiteral(key.slice(dot + 1))} then
3731
- ${roleKeysBumpSql(group.holders, versionTable, " ")}
3732
- end if;`;
3733
- }).join("\n")}
3734
- return null;
3735
- end;
3736
- $$;
3737
- revoke execute on function ${bump}() from public, anon, authenticated;
3738
- ${groups.map(([, group]) => {
3739
- const target = quoteQualified(group.table);
3740
- return `drop trigger if exists ${quoteIdent(VERSION_TRIGGER)} on ${target};
3741
- create trigger ${quoteIdent(VERSION_TRIGGER)}
3742
- after update or delete on ${target}
3743
- for each row execute function ${bump}();`;
3744
- }).join("\n")}`;
3745
- }
3746
- //#endregion
3747
- //#region src/cli/supabase-hook/manifest.ts
3748
- function helperList(parts, types) {
3749
- const client = ["authenticated"];
3750
- const teams = hookTeamsHelper(parts);
3751
- return [
3752
- helperEntry(HELPERS.has, "p_grant text", "boolean", client),
3753
- ...parts.scopes.flatMap((scope) => {
3754
- const returns = `setof ${types.get(scope.name) ?? "uuid"}`;
3755
- return [
3756
- helperEntry(permittedIdsHelper(scope.name), "p_grant text", returns, client),
3757
- helperEntry(memberIdsHelper(scope.name), "", returns, client),
3758
- ...parts.helpers.memberFor.includes(scope.name) ? [helperEntry(memberForHelper(scope.name), "p_user uuid", returns, parts.extra.length === 0 ? [] : ["supabase_auth_admin"])] : [],
3759
- ...parts.helpers.memberFor.includes(scope.name) && isTeamScope(scope.name) ? [helperEntry(memberOfHelper(scope.name), "p_user uuid", returns, client)] : []
3760
- ];
3761
- }),
3762
- ...teams === void 0 ? [] : [helperEntry(teams, "p_user uuid", "setof uuid", client)]
3763
- ];
3764
- }
3765
- function helperEntry(name, args, returns, execute) {
3766
- return {
3767
- name,
3768
- args,
3769
- returns,
3770
- execute
3771
- };
3772
- }
3773
- /**
3774
- * The helpers `rls generate` writes beyond the ones the hook's claims feed: the
3775
- * `_for` forms in `database` mode, and the assignment checks when a role
3776
- * declares `assigns` (known only with the policy).
3777
- */
3778
- function trustedHelpers(parts, config, types, tenantType, policy) {
3779
- const database = resolveAuthorize(config) === "database";
3780
- const custom = database && customRolesOn(config.rls);
3781
- const everyFor = parts.scopes.every((scope) => parts.helpers.memberFor.includes(scope.name));
3782
- const client = ["authenticated"];
3783
- const scopeTypes = parts.scopes.map((scope) => [scope.name, types.get(scope.name) ?? "uuid"]);
3784
- const forUser = database ? [
3785
- helperEntry(HELPERS.hasFor, "p_user uuid, p_grant text", "boolean", []),
3786
- ...scopeTypes.map(([scope, type]) => helperEntry(permittedForHelper(scope), "p_user uuid, p_grant text", `setof ${type}`, [])),
3787
- ...scopeTypes.map(([scope, type]) => helperEntry(permissionKeysForHelper(scope), `p_user uuid, p_id ${type}`, "setof text", [])),
3788
- ...scopeTypes.filter(([scope]) => parts.helpers.holders.includes(scope)).map(([scope, type]) => helperEntry(permittedUsersHelper(scope), `p_permission text, p_id ${type}`, "setof uuid", []))
3789
- ] : [];
3790
- const keyed = [
3791
- helperEntry(USER_ID_HELPER, "", "uuid", client),
3792
- helperEntry(PERMDOCK_SUBJECT, "", "jsonb", client),
3793
- ...config.rls?.apiKeys === void 0 ? [] : [helperEntry(API_KEY_ALLOWS, "p_grant text", "boolean", client)],
3794
- ...config.rls?.tokenScopes === true ? [helperEntry(TOKEN_SCOPE_ALLOWS, "p_grant text", "boolean", client)] : [],
3795
- ...readOnlyActorKinds(config.rls?.readOnlyActors) === void 0 ? [] : [helperEntry(ACTOR_MAY_WRITE, "", "boolean", client)],
3796
- ...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)] : [],
3797
- ...typeof config.rls?.approvals === "object" && config.rls.approvals.managers !== void 0 ? [helperEntry(MANAGES, "p_requester text, p_levels integer", "boolean", [])] : [],
3798
- ...forUser
3799
- ];
3800
- if (!(policy !== void 0 && (ownershipRules(policy, parts.scopes)?.assigns.length ?? 0) > 0)) return keyed;
3801
- const customArgs = `p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text`;
3802
- const anyArgs = `p_role text, p_tenant ${tenantType}, p_scope text, p_scope_id text`;
3803
- return [
3804
- ...keyed,
3805
- helperEntry(OWNERSHIP.canAssign, "p_role text, p_scope_id text", "boolean", client),
3806
- ...database ? [helperEntry(OWNERSHIP.canAssignFor, "p_user uuid, p_role text, p_scope_id text", "boolean", [])] : [],
3807
- ...custom ? [helperEntry(ASSIGNMENTS.custom, customArgs, "boolean", client)] : [],
3808
- ...custom && everyFor ? [helperEntry(ASSIGNMENTS.customFor, `p_user uuid, ${customArgs}`, "boolean", [])] : [],
3809
- helperEntry(OWNERSHIP.canAssignAny, anyArgs, "boolean", client),
3810
- ...database && (!custom || everyFor) ? [helperEntry(OWNERSHIP.canAssignAnyFor, `p_user uuid, ${anyArgs}`, "boolean", [])] : []
3811
- ];
3812
- }
3813
- function activeRowManifest(row) {
3814
- const keep = "keep" in row ? keptKeys(row) : [];
3815
- return {
3816
- table: qualifySqlTable(row.table),
3817
- id: row.id,
3818
- ...row.disabledAt === void 0 ? {} : { disabledAt: row.disabledAt },
3819
- ...row.status === void 0 ? {} : { status: row.status },
3820
- ...row.active === void 0 ? {} : { active: row.active },
3821
- ...keep.length === 0 ? {} : { keep }
3822
- };
3823
- }
3824
- /**
3825
- * The `rls` settings a package writing SQL next to the helpers reads: custom
3826
- * roles, global roles, suspension and assignment triggers.
3827
- */
3828
- function rlsSettings(parts, config) {
3829
- const rls = config.rls;
3830
- const suspension = checkSuspension(rls?.suspension, parts.scopes);
3831
- const scopes = Object.entries(suspension?.scopes ?? {});
3832
- const assigned = rls?.assignments === void 0 ? void 0 : guardedTables(config, parts.scopes);
3833
- return {
3834
- customRoles: resolveAuthorize(config) === "database" && customRolesOn(rls),
3835
- ...parts.roles === void 0 ? {} : { roles: {
3836
- table: qualifySqlTable(parts.roles.table),
3837
- user: { column: parts.roles.user },
3838
- role: parts.roles.role
3839
- } },
3840
- ...suspension === void 0 ? {} : { suspension: {
3841
- ...suspension.users === void 0 ? {} : { users: activeRowManifest(suspension.users) },
3842
- ...scopes.length === 0 ? {} : { scopes: Object.fromEntries(scopes.map(([name, row]) => [name, activeRowManifest(row)])) },
3843
- ...suspension.memberships === void 0 ? {} : { memberships: { keep: keptKeys(suspension.memberships) } }
3844
- } },
3845
- ...assigned === void 0 ? {} : { assignments: { tables: assigned } },
3846
- ...rls?.apiKeys === void 0 ? {} : { apiKeys: apiKeyFields(rls.apiKeys) },
3847
- ...rls?.tokenScopes === true ? { tokenScopes: true } : {}
3848
- };
3849
- }
3850
- /** The `supabase/sdk` release `requires.capabilities` names features of. */
3851
- const CAPABILITY_MATRIX = "capability-matrix-v1.12.0";
3852
- function usesLiveSession(policy) {
3853
- return [...policy?.grants ?? [], ...policy?.roles.flatMap((binding) => binding.grants) ?? []].some((grant) => hasConditionOp(grant.where, "liveSession") || hasConditionOp(grant.check, "liveSession"));
3854
- }
3855
- function requiredCapabilities(config, policy) {
3856
- const ids = /* @__PURE__ */ new Set(["auth.session.get_claims"]);
3857
- if (usesLiveSession(policy)) ids.add("auth.session.get_user");
3858
- if (config.rls?.realtime !== void 0) ids.add("realtime.subscriptions.private_channel");
3859
- for (const bucket of Object.values(config.rls?.storage?.buckets ?? {})) {
3860
- if (bucket.read !== void 0) {
3861
- ids.add("storage.file_buckets.download");
3862
- ids.add("storage.file_buckets.list_files");
3863
- }
3864
- if (bucket.write !== void 0) {
3865
- ids.add("storage.file_buckets.upload");
3866
- ids.add("storage.file_buckets.update_file");
3867
- ids.add("storage.file_buckets.move");
3868
- }
3869
- if (bucket.delete !== void 0) ids.add("storage.file_buckets.remove");
3870
- }
3871
- return {
3872
- matrix: CAPABILITY_MATRIX,
3873
- capabilities: [...ids].toSorted()
3874
- };
3875
- }
3876
- function manifestOf(parts, out, config, policy) {
3877
- const rls = config.rls;
3878
- const ctx = {
3879
- dialect: "supabase",
3880
- scopes: parts.scopes,
3881
- tenantClaim: parts.tenantClaim,
3882
- gucPrefix: rls?.gucPrefix ?? "app",
3883
- tenantType: firstScopeType(rls?.scopeTypes, parts.scopes),
3884
- ...rls?.scopeTypes === void 0 ? {} : { scopeTypes: rls.scopeTypes }
3885
- };
3886
- const types = new Map(parts.scopes.map((scope) => [scope.name, scopeTypeOf(ctx, scope.name)]));
3887
- const helpers = helperList(parts, types);
3888
- return {
3889
- $schema: SUPABASE_MANIFEST_SCHEMA,
3890
- version: 1,
3891
- hook: {
3892
- schema: parts.schema,
3893
- function: "custom_access_token_hook",
3894
- out,
3895
- ...parts.before.length === 0 ? {} : { before: parts.before },
3896
- activeFrom: parts.activeFrom
3897
- },
3898
- helpers: {
3899
- schema: parts.helpers.schema,
3900
- functions: helpers.map((entry) => entry.name)
3901
- },
3902
- tenantClaim: parts.tenantClaim,
3903
- budget: {
3904
- bytes: parts.budget,
3905
- measure: BUDGET_MEASURE
3906
- },
3907
- claims: hookClaims(parts),
3908
- authzVersion: parts.version,
3909
- ...parts.version ? { authzVersionBump: {
3910
- schema: parts.schema,
3911
- function: AUTHZ_VERSION_BUMP,
3912
- args: "p_users uuid[]"
3913
- } } : {},
3914
- memberships: parts.sources.map((source) => source.sql.manifest),
3915
- rls: {
3916
- schema: parts.helpers.schema,
3917
- mode: resolveAuthorize(config),
3918
- tenantClaim: parts.tenantClaim,
3919
- scopes: parts.scopes.map((scope) => ({
3920
- name: scope.name,
3921
- type: types.get(scope.name) ?? "uuid",
3922
- ...scope.within === void 0 ? {} : { within: scope.within }
3923
- })),
3924
- helpers: [...helpers, ...trustedHelpers(parts, config, types, tenantTypeOf(ctx), policy)],
3925
- memberships: parts.helpers.memberships,
3926
- ...rlsSettings(parts, config)
3927
- },
3928
- decidingColumns: decidingColumns(config, parts.attrs === void 0 ? void 0 : {
3929
- ...parts.attrs.table === void 0 ? {} : { table: parts.attrs.table },
3930
- columns: parts.attrs.columns
3931
- }, parts.hook.teams),
3932
- markers: {
3933
- hook: "v1",
3934
- grants: "v1"
3935
- },
3936
- requires: requiredCapabilities(config, policy),
3937
- ...policy === void 0 ? {} : { names: resolveNames(policy, config, {
3938
- schema: parts.helpers.schema,
3939
- tenantClaim: parts.tenantClaim
3940
- }) }
3941
- };
3942
- }
3943
- /**
3944
- * The manifest without the token hook: what a project with no `supabase.hook`
3945
- * records.
3946
- */
3947
- function databaseManifestOf(parts, out, config, policy) {
3948
- const { hook: _hook, budget: _budget, claims: _claims, authzVersion: _authzVersion, authzVersionBump: _authzVersionBump, memberships: _memberships, ...rest } = manifestOf(parts, out, config, policy);
3949
- return rest;
3950
- }
3951
- /**
3952
- * The first line of the generated hook: fields `--check` compares before the
3953
- * full text.
3954
- */
3955
- function hookMarker(manifest) {
3956
- return `${HOOK_MARKER} schema=${manifest.hook.schema} tenant=${manifest.tenantClaim} budget=${String(manifest.budget.bytes)} claims=${manifest.claims.map((claim) => claim.name).join(",")}`;
3957
- }
3958
- function defaultOut(config) {
3959
- return config.supabase?.hook?.out ?? "supabase/permdock-hook.sql";
3960
- }
3961
- //#endregion
3962
- //#region src/cli/supabase-hook/supabase-hook.ts
3963
- const SUPABASE_HELP = `permdock supabase hook generate | inspect
3964
-
3965
- hook generate [--out <file>] [--check] [--db-url-stdin] [--schemas pg-delta|migra|migrations]
3966
- [--active-from app_metadata.active_<scope>|<table>.<column>]
3967
- [--budget 1024] [--schema public] [--grants-out <file>|-]
3968
- inspect [--json] [--out [permdock.manifest.json]] [--check]
3969
-
3970
- Reads supabase.hook from permdock.config.ts: the tableMembershipSource / junctionMembershipSource sources the app
3971
- passes as memberships. hook generate emits custom_access_token_hook(jsonb), the grants it
3972
- needs, the permdock_authz_version table and its triggers. Under pg-delta (the default) --out defaults to
3973
- supabase/schemas/<schema>/functions/custom_access_token_hook.sql and the grants stay in it; under
3974
- --schemas migra, --grants-out takes the privileges supabase db diff drops. Never grants anything to
3975
- service_role unless supabase.hook.api is set, which grants its wrappers to it. inspect prints the manifest: helper schema, names and signatures, tenant claim,
3976
- budget, the claims the hook writes, the membership sources and the columns that decide them.
3977
- --out writes it as JSON, to permdock.manifest.json without a path; --check exits 1 when that
3978
- file differs.
3979
- `;
3980
- /**
3981
- * The hook part of `rls generate --split`: `rls.out` with `{part}` replaced by
3982
- * `hook`, when `rls.split` lists `hook`, or, without `rls.split`, when that
3983
- * file carries the hook marker.
3984
- */
3985
- function splitHookOut(cwd, config) {
3986
- const out = config.rls?.out;
3987
- if (out?.includes("{part}") !== true) return;
3988
- const rel = partPath(out, "hook");
3989
- const split = config.rls?.split;
3990
- if (split !== void 0) return split.includes("hook") ? rel : void 0;
3991
- const path = resolve(cwd, rel);
3992
- return existsSync(path) && readFileSync(path, "utf8").includes("-- permdock:hook v1") ? rel : void 0;
3993
- }
3994
- /**
3995
- * `supabase.hook.out`, else the hook part of `rls generate --split`, else
3996
- * pg-delta's per-schema path under pg-delta, else
3997
- * `supabase/permdock-hook.sql`.
3998
- */
3999
- function hookOut(cwd, config, schema, flag) {
4000
- const split = config.supabase?.hook?.out === void 0 ? splitHookOut(cwd, config) : void 0;
4001
- if (split !== void 0) return split;
4002
- const schemas = resolveSchemas(cwd, config, flag);
4003
- return config.supabase?.hook?.out !== void 0 || schemas.mode !== "pg-delta" ? defaultOut(config) : pgDeltaPath(schemas.schemaDir, "hook", schema ?? config.supabase?.hook?.schema ?? config.rls?.schema ?? "permdock");
4004
- }
4005
- /**
4006
- * The manifest `supabase inspect` prints. With `policy`, `rls.helpers` also
4007
- * lists the assignment checks `rls generate` writes for roles that declare
4008
- * `assigns`.
4009
- */
4010
- function supabaseHookManifest(scopes, config, overrides = {}, policy) {
4011
- const manifest = manifestOf(hookParts(scopes, config, overrides), overrides.out ?? defaultOut(config), config, policy);
4012
- return overrides.schemas === void 0 ? manifest : {
4013
- ...manifest,
4014
- hook: {
4015
- ...manifest.hook,
4016
- schemas: overrides.schemas
4017
- }
4018
- };
4019
- }
4020
- /**
4021
- * The manifest of a project in `rls.authorize: 'database'` mode with no
4022
- * `supabase.hook`: the helpers, scopes, membership sources and grants, and no
4023
- * token hook.
4024
- */
4025
- function supabaseDatabaseManifest(scopes, config, overrides = {}, policy) {
4026
- return databaseManifestOf(hookParts(scopes, {
4027
- ...config,
4028
- supabase: {
4029
- ...config.supabase,
4030
- hook: { memberships: membershipSourcesOf(config) }
4031
- }
4032
- }, overrides), overrides.out ?? defaultOut(config), config, policy);
4033
- }
4034
- /** Whether the project is in the one case that has a manifest without a hook. */
4035
- function hooklessDatabase(config) {
4036
- return config.supabase?.hook === void 0 && resolveAuthorize(config) === "database";
4037
- }
4038
- /**
4039
- * The hook migration. With `grantsOut`, the statements `supabase db diff` drops
4040
- * are left out of `sql` and returned in `grants` for that file.
4041
- */
4042
- function supabaseHookSql(scopes, config, overrides = {}, grantsOut) {
4043
- const parts = hookParts(scopes, config, overrides);
4044
- const manifest = manifestOf(parts, defaultOut(config), config);
4045
- const toml = configToml(parts.schema, parts.jwtExpiry).split("\n").map((line) => line === "" ? "--" : `-- ${line}`).join("\n");
4046
- const sql = [
4047
- `${hookMarker(manifest)}
4048
- -- custom_access_token_hook(jsonb): memberships go active ${parts.root} first and stop at the budget
4049
- -- supabase/config.toml:
4050
- ${toml}${grantsOut === void 0 ? "" : `\n-- what supabase db diff drops from this part is in ${grantsOut}`}`,
4051
- schemaSql(parts),
4052
- attrsGuardSql(parts.attrs),
4053
- globalRolesSql(parts),
4054
- membershipEntriesSql(parts),
4055
- hookSql(parts),
4056
- versionSql(parts),
4057
- subjectForSql(parts, config),
4058
- permdockSubjectSql(parts),
4059
- authzVersionForSql(parts),
4060
- membersOfSql(parts),
4061
- teamIdsOfSql(parts),
4062
- apiWrappersSql(parts),
4063
- grantsSql(parts),
4064
- managedSql(parts)
4065
- ].filter((chunk) => chunk !== "").join("\n\n");
4066
- const { kept, moved } = splitUndiffed(`${sql}\n`);
4067
- const grants = `${GRANTS_MARKER} schema=${parts.schema}
4068
- -- the privileges and view options supabase db diff drops from the hook part
4069
- ${moved.join("\n")}
4070
- `;
4071
- return {
4072
- sql: grantsOut === void 0 ? `${sql}\n` : kept,
4073
- grants,
4074
- manifest
4075
- };
4076
- }
4077
- /** What the hook file's header says about where its grants went. */
4078
- function grantsLabel(grantsOut) {
4079
- if (grantsOut === void 0) return;
4080
- return grantsOut === "-" ? "a separate migration" : grantsOut;
4081
- }
4082
- function markerDrift(onDisk, expected, outRel) {
4083
- const found = hookMarkerFields(onDisk);
4084
- if (found === void 0) return `supabase hook drift: ${outRel} has no ${HOOK_MARKER} line`;
4085
- const want = hookMarkerFields(hookMarker(expected)) ?? {};
4086
- const changed = Object.keys(want).filter((key) => found[key] !== want[key]).map((key) => `${key} ${found[key] ?? "(none)"} -> ${want[key] ?? ""}`);
4087
- return changed.length === 0 ? "supabase hook drift" : `supabase hook drift: ${changed.join("; ")}`;
4088
- }
4089
- /** Supabase's default access token lifetime when `[auth] jwt_expiry` is unset. */
4090
- const DEFAULT_JWT_EXPIRY = 3600;
4091
- function managementApi(cwd, manifest) {
4092
- return {
4093
- hook_custom_access_token_enabled: true,
4094
- hook_custom_access_token_uri: hookUri(manifest.hook.schema),
4095
- jwt_exp: supabaseConfig(cwd).jwtExpiry ?? DEFAULT_JWT_EXPIRY
4096
- };
4097
- }
4098
- function inspectText(manifest, api) {
4099
- return [
4100
- `hook ${manifest.hook.schema}.${manifest.hook.function} (${manifest.hook.out})`,
4101
- `helpers ${manifest.helpers.functions.map((fn) => `${manifest.helpers.schema}.${fn}`).join(", ")}`,
4102
- `tenant claim ${manifest.tenantClaim}`,
4103
- `budget ${String(manifest.budget.bytes)} bytes of ${manifest.budget.measure}`,
4104
- `claims ${manifest.claims.map((claim) => `${claim.name}${claim.source === "permdock" ? "" : ` (${claim.source})`}${claim.budget ? " [budget]" : ""}`).join(", ")}`,
4105
- `authz_ver ${manifest.authzVersion ? "on" : "off"}`,
4106
- `hook_custom_access_token_enabled ${String(api.hook_custom_access_token_enabled)}`,
4107
- `hook_custom_access_token_uri ${api.hook_custom_access_token_uri}`,
4108
- `jwt_exp ${String(api.jwt_exp)}`
4109
- ].join("\n");
4110
- }
4111
- function databaseInspectText(manifest) {
4112
- return [
4113
- "no token hook (rls.authorize: database, no supabase.hook)",
4114
- `helpers ${manifest.helpers.functions.map((fn) => `${manifest.helpers.schema}.${fn}`).join(", ")}`,
4115
- `tenant claim ${manifest.tenantClaim}`
4116
- ].join("\n");
4117
- }
4118
- /**
4119
- * Writes the manifest to `rel`, or with `check` compares it as JSON, so a
4120
- * formatter that reflows the file is not drift.
4121
- */
4122
- function manifestFile(cwd, rel, manifest, check) {
4123
- const path = resolve(cwd, rel);
4124
- if (!check) {
4125
- writeFileEnsuringDir(path, formatManifestJson(manifest));
4126
- return {
4127
- code: 0,
4128
- output: `wrote ${rel}`
4129
- };
4130
- }
4131
- if (!existsSync(path)) return {
4132
- code: 1,
4133
- output: `supabase manifest drift: missing ${rel}`
4134
- };
4135
- let onDisk;
4136
- try {
4137
- onDisk = readJsonFile(path);
4138
- } catch {
4139
- return {
4140
- code: 1,
4141
- output: `supabase manifest drift: ${rel} is not JSON`
4142
- };
4143
- }
4144
- const found = isRecord(onDisk) ? Object.fromEntries(Object.entries(onDisk)) : {};
4145
- const changed = [.../* @__PURE__ */ new Set([...Object.keys(manifest), ...Object.keys(found)])].filter((key) => JSON.stringify(Reflect.get(manifest, key)) !== JSON.stringify(found[key]));
4146
- return changed.length === 0 ? {
4147
- code: 0,
4148
- output: "supabase manifest up to date"
4149
- } : {
4150
- code: 1,
4151
- output: `supabase manifest drift: ${rel} differs in ${changed.join(", ")}; run permdock supabase inspect --out ${rel}`
4152
- };
4153
- }
4154
- async function loadScopes(cwd, config) {
4155
- return scopeList((await loadHookPolicy(cwd, config)).scopes);
4156
- }
4157
- function loadHookPolicy(cwd, config) {
4158
- return requirePolicy(cwd, config.policy, "supabase hook generate needs policy in permdock.config.ts");
4159
- }
4160
- async function runSupabase(input) {
4161
- const [area, action] = input.rest;
4162
- const badSchemas = schemasRefusal("supabase", input.schemas);
4163
- if (badSchemas !== void 0) return {
4164
- code: 2,
4165
- output: badSchemas
4166
- };
4167
- const flag = isSupabaseSchemas(input.schemas) ? input.schemas : void 0;
4168
- const schemas = resolveSchemas(input.cwd, input.config, flag);
4169
- const overrides = Object.fromEntries(Object.entries({
4170
- activeFrom: input.activeFrom,
4171
- budget: input.budget,
4172
- schema: input.schema
4173
- }).filter(([, value]) => value !== void 0));
4174
- if (area === "inspect" && action === void 0) {
4175
- const policy = await loadHookPolicy(input.cwd, input.config);
4176
- if (hooklessDatabase(input.config)) {
4177
- const bare = supabaseDatabaseManifest(scopeList(policy.scopes), input.config, overrides, policy);
4178
- if (input.out !== void 0 || input.check) return manifestFile(input.cwd, typeof input.out === "string" ? input.out : MANIFEST_FILE, bare, input.check);
4179
- return {
4180
- code: 0,
4181
- output: input.json === true ? JSON.stringify(bare, null, 2) : databaseInspectText(bare)
4182
- };
4183
- }
4184
- const manifest = supabaseHookManifest(scopeList(policy.scopes), input.config, {
4185
- ...overrides,
4186
- out: hookOut(input.cwd, input.config, input.schema, flag),
4187
- schemas: schemas.mode
4188
- }, policy);
4189
- const api = managementApi(input.cwd, manifest);
4190
- if (input.out !== void 0 || input.check) return manifestFile(input.cwd, typeof input.out === "string" ? input.out : MANIFEST_FILE, {
4191
- ...manifest,
4192
- managementApi: api
4193
- }, input.check);
4194
- return {
4195
- code: 0,
4196
- output: input.json === true ? JSON.stringify({
4197
- ...manifest,
4198
- managementApi: managementApi(input.cwd, manifest)
4199
- }, null, 2) : inspectText(manifest, api)
4200
- };
4201
- }
4202
- if (area !== "hook" || action !== "generate") return {
4203
- code: 2,
4204
- output: SUPABASE_HELP
4205
- };
4206
- if (input.grantsOut !== void 0 && schemas.mode !== "migra") return {
4207
- code: 2,
4208
- output: `supabase hook generate --grants-out is for --schemas migra: ${schemas.mode === "pg-delta" ? "pg-delta keeps the grants in the hook file" : "a hand-written migration keeps its grants"}, so drop --grants-out`
4209
- };
4210
- const generated = supabaseHookSql(await loadScopes(input.cwd, input.config), input.config, overrides, grantsLabel(input.grantsOut));
4211
- const { grants, manifest } = generated;
4212
- const outRel = typeof input.out === "string" ? input.out : hookOut(input.cwd, input.config, input.schema, flag);
4213
- const sql = schemas.mode === "pg-delta" && typeof input.out !== "string" && input.config.supabase?.hook?.out === void 0 && splitHookOut(input.cwd, input.config) === void 0 ? declarativeSql(generated.sql) : generated.sql;
4214
- const outPath = resolve(input.cwd, outRel);
4215
- const hook = input.config.supabase?.hook;
4216
- const grantsFile = input.grantsOut === void 0 ? [] : [{
4217
- part: "grants",
4218
- rel: input.grantsOut,
4219
- text: grants
4220
- }];
4221
- const toml = configToml(input.schema ?? hook?.schema ?? input.config.rls?.schema ?? "permdock", hook?.jwtExpiry ?? 900);
4222
- if (input.check) {
4223
- if (!existsSync(outPath)) return {
4224
- code: 1,
4225
- output: `supabase hook drift: missing ${outRel}`
4226
- };
4227
- const onDisk = readFileSync(outPath, "utf8");
4228
- if (onDisk !== sql) return {
4229
- code: 1,
4230
- output: markerDrift(onDisk, manifest, outRel)
4231
- };
4232
- const drift = driftOf(input.cwd, grantsFile);
4233
- return drift.length === 0 ? {
4234
- code: 0,
4235
- output: "supabase hook up to date"
4236
- } : {
4237
- code: 1,
4238
- output: `supabase hook drift: ${drift.join("; ")}`
4239
- };
4240
- }
4241
- writeFileEnsuringDir(outPath, sql);
4242
- const grantsWritten = writeOutputFiles(input.cwd, grantsFile);
4243
- const placed = {
4244
- ...manifest,
4245
- hook: {
4246
- ...manifest.hook,
4247
- out: outRel
4248
- }
4249
- };
4250
- const missing = input.db === void 0 ? missingHelpersInFiles(input.cwd, input.config, placed) : await missingHelpersInDb(input.db, placed);
4251
- return {
4252
- code: 0,
4253
- output: [
4254
- `wrote ${[outRel, ...grantsWritten.wrote].join(", ")}`,
4255
- ...grantsWritten.printed === "" ? [] : [grantsWritten.printed],
4256
- "add to supabase/config.toml:",
4257
- toml,
4258
- ...missing.length === 0 ? [] : [missingHelpersMessage(placed, missing)]
4259
- ].join("\n")
4260
- };
4261
- }
4262
- //#endregion
4263
- export { readSupabaseConfig as _, supabaseHookManifest as a, rbacScaffold as b, activeSource as c, resolveSchemas as d, schemasRefusal as f, pd074 as g, pd045 as h, runSupabase as i, pd039 as l, attrsPlan as m, hookOut as n, supabaseHookSql as o, declarativeSql as p, loadScopes as r, approvalsSql as s, grantsLabel as t, isSupabaseSchemas as u, supabaseConfig as v, resolveAuthorize as x, parseRbacAuthorize as y };