permdock 0.0.0 → 0.2.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 (344) hide show
  1. package/README.md +327 -1
  2. package/dist/a2a/index.d.ts +169 -0
  3. package/dist/a2a/index.js +232 -0
  4. package/dist/adapter-context-mlWsVGGg.js +23 -0
  5. package/dist/ai-sdk/index.d.ts +95 -0
  6. package/dist/ai-sdk/index.js +154 -0
  7. package/dist/approval-required-TzNB9oQA.js +6 -0
  8. package/dist/approvals/index.d.ts +3 -0
  9. package/dist/approvals/index.js +5 -0
  10. package/dist/approvals-DbYAuNkG.js +224 -0
  11. package/dist/approvers-DT4AVyIg.js +52 -0
  12. package/dist/arazzo-BAgw9ap6.js +70 -0
  13. package/dist/arazzo-cmvX2jDe.js +54 -0
  14. package/dist/authzen/index.d.ts +39 -0
  15. package/dist/authzen/index.js +302 -0
  16. package/dist/better-auth/index.d.ts +109 -0
  17. package/dist/better-auth/index.js +344 -0
  18. package/dist/better-supabase/index.d.ts +206 -0
  19. package/dist/better-supabase/index.js +620 -0
  20. package/dist/bind-CVy3Espv.d.ts +25 -0
  21. package/dist/bind-VnYn2HKq.js +97 -0
  22. package/dist/boundary-BM8a_P6E.js +13 -0
  23. package/dist/boundary-BmHxVH1J.d.ts +15 -0
  24. package/dist/budget-JqcRqyhK.d.ts +11 -0
  25. package/dist/budget-NbEtbJC_.js +11 -0
  26. package/dist/canonical-json-DemiK4Vp.js +26 -0
  27. package/dist/capability-4qPdO9gk.js +173 -0
  28. package/dist/capability-Dq43tT1u.d.ts +99 -0
  29. package/dist/catalog/index.d.ts +12 -0
  30. package/dist/catalog/index.js +2 -0
  31. package/dist/catalog-BjZSovXQ.js +2 -0
  32. package/dist/catalog-doc-Dsc9y7sd.js +309 -0
  33. package/dist/catalog-h2tlKFkq.js +48 -0
  34. package/dist/catalog-path-CnI0XTFK.js +12 -0
  35. package/dist/catalog-z8q6bi_r.js +55 -0
  36. package/dist/claude-agent/index.d.ts +72 -0
  37. package/dist/claude-agent/index.js +77 -0
  38. package/dist/clerk/index.d.ts +65 -0
  39. package/dist/clerk/index.js +301 -0
  40. package/dist/cli/bin.d.ts +1 -0
  41. package/dist/cli/bin.js +20 -0
  42. package/dist/cli/index.d.ts +46 -0
  43. package/dist/cli/index.js +5 -0
  44. package/dist/clients-C7zLFuWT.d.ts +12 -0
  45. package/dist/clients-DjU5ABMy.js +23 -0
  46. package/dist/cloud/index.d.ts +90 -0
  47. package/dist/cloud/index.js +404 -0
  48. package/dist/cloud-BGhHS-lY.js +50 -0
  49. package/dist/cloud-Bo3e9Ak3.js +118 -0
  50. package/dist/collect-DDDv_ESs.js +502 -0
  51. package/dist/collect-DLlujdHC.js +83 -0
  52. package/dist/collect-rG2IQ3t0.js +2 -0
  53. package/dist/commands-DWOrSQic.js +97 -0
  54. package/dist/compact-y6vfu2_f.js +19 -0
  55. package/dist/compare-pfyVnBjE.js +12 -0
  56. package/dist/compile/index.d.ts +3 -0
  57. package/dist/compile/index.js +2 -0
  58. package/dist/compile-Ba4blROR.js +613 -0
  59. package/dist/compile-CNnl6uIt.d.ts +94 -0
  60. package/dist/config-BJiM-xAm.js +157 -0
  61. package/dist/config-Bn00Z3ks.js +36 -0
  62. package/dist/config-report-Dw_JcUqT.js +44 -0
  63. package/dist/connection-CU8MQxRi.js +194 -0
  64. package/dist/context-Ttp0ekMT.js +82 -0
  65. package/dist/convex/index.d.ts +45 -0
  66. package/dist/convex/index.js +65 -0
  67. package/dist/create-BWyx3jua.d.ts +245 -0
  68. package/dist/create-CPhDL6qx.js +253 -0
  69. package/dist/credential-8P81ff4u.js +306 -0
  70. package/dist/delegation-D8pUEuce.js +103 -0
  71. package/dist/describe-B_gVZEVi.js +94 -0
  72. package/dist/describe-PdoqESvg.d.ts +36 -0
  73. package/dist/diff-B8Tunc3o.js +451 -0
  74. package/dist/diff-CzqLxZ77.js +48 -0
  75. package/dist/digest-B3kc_PgQ.d.ts +19 -0
  76. package/dist/digest-BI-6aa6d.js +27 -0
  77. package/dist/doctor-WpvG6p4k.js +1194 -0
  78. package/dist/doctor-collect-ByfYlNv1.js +664 -0
  79. package/dist/doctor-rOr-4ZfS.js +53 -0
  80. package/dist/drizzle/index.d.ts +73 -0
  81. package/dist/drizzle/index.js +160 -0
  82. package/dist/duration-xK2jGFVc.js +25 -0
  83. package/dist/elysia/index.d.ts +49 -0
  84. package/dist/elysia/index.js +59 -0
  85. package/dist/errors-CWfoNg9N.js +47 -0
  86. package/dist/errors-Cz5zn0mW.js +123 -0
  87. package/dist/errors-DAqevpNk.d.ts +125 -0
  88. package/dist/errors-DRnGZHzF.js +30 -0
  89. package/dist/evaluation-items-CfCCejQd.js +40 -0
  90. package/dist/evaluations-tz6D9A2G.js +461 -0
  91. package/dist/eve/index.d.ts +86 -0
  92. package/dist/eve/index.js +176 -0
  93. package/dist/expiry-BoBJ8Tvc.js +7 -0
  94. package/dist/express/index.d.ts +23 -0
  95. package/dist/express/index.js +78 -0
  96. package/dist/fastify/index.d.ts +33 -0
  97. package/dist/fastify/index.js +92 -0
  98. package/dist/fields-BMl1RxoX.js +26 -0
  99. package/dist/files-DWUN9PzI.js +125 -0
  100. package/dist/fixtures-ht28Cplr.js +67 -0
  101. package/dist/freeze-CrU8nQeX.js +60 -0
  102. package/dist/from-snapshot-C3sHpZNS.js +569 -0
  103. package/dist/generate-CH7ThJ14.js +173 -0
  104. package/dist/grantee-Cv5Sogfv.js +602 -0
  105. package/dist/graph-sql-B-dsAT6j.d.ts +29 -0
  106. package/dist/headers-BZSDieNT.js +6 -0
  107. package/dist/headers-Cf-zWvsO.d.ts +6 -0
  108. package/dist/helpers-H_KARDVC.js +421 -0
  109. package/dist/hono/index.d.ts +48 -0
  110. package/dist/hono/index.js +99 -0
  111. package/dist/hosted-DJQw46hn.js +266 -0
  112. package/dist/http-BIhmLfCc.js +95 -0
  113. package/dist/http-DPuDaChb.d.ts +13 -0
  114. package/dist/http-SO7qGttf.js +44 -0
  115. package/dist/ids-DC4V4CFu.js +18 -0
  116. package/dist/index-A0YNL8jZ.d.ts +177 -0
  117. package/dist/index-CtE07CBF.d.ts +6 -0
  118. package/dist/index-D3vbkoSI.d.ts +483 -0
  119. package/dist/index-D6_cSa1z.d.ts +201 -0
  120. package/dist/index.d.ts +16 -0
  121. package/dist/index.js +26 -0
  122. package/dist/instance-options-BK_rNOSC.d.ts +11 -0
  123. package/dist/instance-options-Dhhcnm3y.js +22 -0
  124. package/dist/json-schema-BsAflUGW.js +106 -0
  125. package/dist/jwt/index.d.ts +91 -0
  126. package/dist/jwt/index.js +590 -0
  127. package/dist/kernel-GSQnMz3O.js +208 -0
  128. package/dist/kysely/index.d.ts +78 -0
  129. package/dist/kysely/index.js +129 -0
  130. package/dist/live-options-H2eG8dfJ.js +60 -0
  131. package/dist/load-DhWEB9P1.js +75 -0
  132. package/dist/load-DwJUafYN.js +2 -0
  133. package/dist/load-jose-BL6LH4bL.js +11 -0
  134. package/dist/lru-8q4WZjBV.js +28 -0
  135. package/dist/manifest-iaoBXHKc.js +783 -0
  136. package/dist/manifest-uDS9y5de.d.ts +206 -0
  137. package/dist/map-AcxK9o_D.js +147 -0
  138. package/dist/map-claims-Z4QZOiFF.js +369 -0
  139. package/dist/map-error-pgUWNNtG.js +23 -0
  140. package/dist/markers-B0hYLvMD.js +60 -0
  141. package/dist/may-use-DndQ5tQ-.js +77 -0
  142. package/dist/mcp/index.d.ts +159 -0
  143. package/dist/mcp/index.js +603 -0
  144. package/dist/nest/index.d.ts +75 -0
  145. package/dist/nest/index.js +261 -0
  146. package/dist/next/client.d.ts +23 -0
  147. package/dist/next/client.js +33 -0
  148. package/dist/next/index.d.ts +93 -0
  149. package/dist/next/index.js +180 -0
  150. package/dist/next/plugin.d.ts +14 -0
  151. package/dist/next/plugin.js +33 -0
  152. package/dist/node/index.d.ts +24 -0
  153. package/dist/node/index.js +34 -0
  154. package/dist/openai/index.d.ts +62 -0
  155. package/dist/openai/index.js +92 -0
  156. package/dist/openapi/index.d.ts +176 -0
  157. package/dist/openapi/index.js +3 -0
  158. package/dist/openapi-Bbg4wGVL.js +164 -0
  159. package/dist/openapi-BqRBvAng.js +538 -0
  160. package/dist/openapi-CqqEbHsL.js +250 -0
  161. package/dist/openapi-import-cmwetbzw.js +5959 -0
  162. package/dist/openapi-schema--ARjyfQr.js +6902 -0
  163. package/dist/orpc/index.d.ts +51 -0
  164. package/dist/orpc/index.js +145 -0
  165. package/dist/otel/index.d.ts +13 -0
  166. package/dist/otel/index.js +202 -0
  167. package/dist/package-root-zGkxO3oN.js +30 -0
  168. package/dist/parse-BuyjxhZV.js +53 -0
  169. package/dist/parse-local-manifest-BkGQNzAh.d.ts +10 -0
  170. package/dist/parse-local-manifest-BrMozJCo.js +36 -0
  171. package/dist/pdp/index.d.ts +22 -0
  172. package/dist/pdp/index.js +682 -0
  173. package/dist/peer-BOr_kJE1.js +31 -0
  174. package/dist/permdock-CzqXjCpU.js +3471 -0
  175. package/dist/permissions-CDgvKG5L.d.ts +52 -0
  176. package/dist/permissions-CpZrivYv.js +142 -0
  177. package/dist/permissions-DVoF6dMt.js +662 -0
  178. package/dist/permissions-DttnqqxC.d.ts +214 -0
  179. package/dist/pins-8ILTftC9.js +12 -0
  180. package/dist/policy-CFZAr_Al.d.ts +2252 -0
  181. package/dist/policy-D8UFyERw.d.ts +20 -0
  182. package/dist/policy-xyWg7QdR.js +1122 -0
  183. package/dist/powersync-A8x_Yyvh.js +2 -0
  184. package/dist/powersync-C7kLglqX.js +540 -0
  185. package/dist/powersync-yW1UUFzp.js +62 -0
  186. package/dist/prisma/index.d.ts +136 -0
  187. package/dist/prisma/index.js +455 -0
  188. package/dist/problem-B43ztKIm.js +191 -0
  189. package/dist/problem-details-CkL50EEf.d.ts +7 -0
  190. package/dist/problem-details-_AMOYz-w.js +144 -0
  191. package/dist/prompt-CXYhLfsS.js +32 -0
  192. package/dist/protected-CNsMzrVd.d.ts +27 -0
  193. package/dist/protected-Cs6kTaHo.js +100 -0
  194. package/dist/protected-bZs6rbT1.d.ts +40 -0
  195. package/dist/provider-Cjr62YMV.d.ts +6 -0
  196. package/dist/provider-DLzpb2Xz.js +52 -0
  197. package/dist/provider-store-DNyC1y48.js +43 -0
  198. package/dist/react/index.d.ts +8 -0
  199. package/dist/react/index.js +7 -0
  200. package/dist/react/provider-client.d.ts +2 -0
  201. package/dist/react/provider-client.js +3 -0
  202. package/dist/react-native/index.d.ts +198 -0
  203. package/dist/react-native/index.js +696 -0
  204. package/dist/refs-KYb4ntaz.js +91 -0
  205. package/dist/relations-cjOL01hZ.js +505 -0
  206. package/dist/replay-BsOyTrdV.js +28 -0
  207. package/dist/replay-sqBGMnNs.d.ts +5 -0
  208. package/dist/resource-ref-CaS9yVPi.js +20 -0
  209. package/dist/revocations-Bhr0aMIC.js +27 -0
  210. package/dist/revocations-Cy06JNx2.d.ts +21 -0
  211. package/dist/rls-BMNydpHk.js +2521 -0
  212. package/dist/rls-CEvs64Kj.js +238 -0
  213. package/dist/rls-fields-BMasREhR.js +3502 -0
  214. package/dist/rls-graph-pc9fuXYm.js +435 -0
  215. package/dist/rls-import-D8F7j35Q.js +943 -0
  216. package/dist/rls-migrate-7wikfrVI.js +367 -0
  217. package/dist/rls-ownership-B5Lkq62W.js +843 -0
  218. package/dist/rls-shared-aOQ4hGTO.js +493 -0
  219. package/dist/rls-verify-D8B7dOTh.js +745 -0
  220. package/dist/row-check-Dt35czLy.d.ts +40 -0
  221. package/dist/rpc-DOK54_CS.js +89 -0
  222. package/dist/run-YXCJDNYk.js +174 -0
  223. package/dist/runtime-CB8gQFvS.js +11 -0
  224. package/dist/saas-Bj_FFkjN.js +1203 -0
  225. package/dist/schema-D3MnDMxa.js +300 -0
  226. package/dist/scim/index.d.ts +2 -0
  227. package/dist/scim/index.js +2 -0
  228. package/dist/scim-BFGBBAqR.js +1445 -0
  229. package/dist/scopes-CVdPrWN-.js +239 -0
  230. package/dist/server/index.d.ts +134 -0
  231. package/dist/server/index.js +11 -0
  232. package/dist/server-DlZ28Oz5.js +268 -0
  233. package/dist/sha256-BO0swRXL.js +150 -0
  234. package/dist/shared-DRu8VFVM.js +123 -0
  235. package/dist/sink-Bd9PSyfq.js +141 -0
  236. package/dist/sink-Gs6TTVa-.d.ts +104 -0
  237. package/dist/skills-Biq5uup3.js +192 -0
  238. package/dist/skills-JaymNCdK.js +56 -0
  239. package/dist/snapshot-Enxd0n-s.js +975 -0
  240. package/dist/snapshot-cache-D6jLelln.js +44 -0
  241. package/dist/snapshot-cache-DwQH8ufx.d.ts +45 -0
  242. package/dist/solid/index.d.ts +93 -0
  243. package/dist/solid/index.js +188 -0
  244. package/dist/sources-B0UvrJ21.js +534 -0
  245. package/dist/sources-BcJgw0lt.d.ts +192 -0
  246. package/dist/sql-xdg5f4Fi.js +27 -0
  247. package/dist/src-CSbUiozF.js +568 -0
  248. package/dist/ssf/index.d.ts +4 -0
  249. package/dist/ssf/index.js +596 -0
  250. package/dist/store-DMAWwAJV.js +371 -0
  251. package/dist/store-D_pjn91-.d.ts +36 -0
  252. package/dist/store-options-yO0V6gRn.js +716 -0
  253. package/dist/stores-4_sqiOA1.js +87 -0
  254. package/dist/stores-DVR5NHLE.d.ts +52 -0
  255. package/dist/stream-DDpvynSB.js +66 -0
  256. package/dist/stream-DlvG2hs-.d.ts +12 -0
  257. package/dist/style-CTm1AXDT.js +22 -0
  258. package/dist/subject-C6dLxqHU.js +24 -0
  259. package/dist/subject-settings-BwBmCdTR.js +128 -0
  260. package/dist/supabase/index.d.ts +183 -0
  261. package/dist/supabase/index.js +5 -0
  262. package/dist/supabase/middleware.d.ts +82 -0
  263. package/dist/supabase/middleware.js +102 -0
  264. package/dist/supabase-CwafwxxF.js +83 -0
  265. package/dist/supabase-DTBaC20O.js +774 -0
  266. package/dist/supabase-config-Bs44dare.js +472 -0
  267. package/dist/supabase-hook-BuxLQLpU.js +1814 -0
  268. package/dist/supabase-hook-D5qVd_D8.js +2 -0
  269. package/dist/supautils-DYZnzRWV.js +91 -0
  270. package/dist/svelte/PermissionBoundary.svelte +37 -0
  271. package/dist/svelte/Protected.svelte +40 -0
  272. package/dist/svelte/index.d.ts +13 -0
  273. package/dist/svelte/index.js +107 -0
  274. package/dist/svelte/runtime.d.ts +7 -0
  275. package/dist/svelte/runtime.js +4 -0
  276. package/dist/svelte/source.d.ts +13 -0
  277. package/dist/svelte/source.js +11 -0
  278. package/dist/terminal/index.d.ts +163 -0
  279. package/dist/terminal/index.js +833 -0
  280. package/dist/testing/index.d.ts +745 -0
  281. package/dist/testing/index.js +3672 -0
  282. package/dist/testing/saas/index.d.ts +194 -0
  283. package/dist/testing/saas/index.js +3 -0
  284. package/dist/testing/saas/permissions.d.ts +2 -0
  285. package/dist/testing/saas/permissions.js +2 -0
  286. package/dist/text-diff-BdkkYSbi.js +15 -0
  287. package/dist/thenable-okc2xDsj.js +10 -0
  288. package/dist/timeout-D51niuQP.js +8 -0
  289. package/dist/token-CIWxJOCh.js +50 -0
  290. package/dist/trpc/index.d.ts +61 -0
  291. package/dist/trpc/index.js +122 -0
  292. package/dist/types-9AWO9EGt.d.ts +197 -0
  293. package/dist/types-BPxgszlT.d.ts +550 -0
  294. package/dist/types-BVyImy5I.d.ts +120 -0
  295. package/dist/types-Bvc4oWT6.d.ts +9 -0
  296. package/dist/types-C3s9xVJG.d.ts +48 -0
  297. package/dist/types-Dnemwd77.d.ts +183 -0
  298. package/dist/types-kxznc7cn.d.ts +52 -0
  299. package/dist/types-vKyAMtcX.d.ts +157 -0
  300. package/dist/types-vNSDF7Dq.d.ts +66 -0
  301. package/dist/types-yF5LmQVD.d.ts +306 -0
  302. package/dist/unplugin/index.d.ts +7 -0
  303. package/dist/unplugin/index.js +31 -0
  304. package/dist/usage-D07N9QJ3.js +42 -0
  305. package/dist/usage-D82l1CwK.js +2 -0
  306. package/dist/usage-DG1oeCca.js +693 -0
  307. package/dist/validation-error-CnjZ4t92.js +33 -0
  308. package/dist/validation-error-CtF23SrC.d.ts +26 -0
  309. package/dist/validity-uOp8UpYn.js +245 -0
  310. package/dist/verifier-BxBo6I44.js +466 -0
  311. package/dist/version-BvacVTZR.js +17 -0
  312. package/dist/views-Soe7bGSC.js +95 -0
  313. package/dist/vocabulary-DA8a8zif.d.ts +56 -0
  314. package/dist/vue/index.d.ts +79 -0
  315. package/dist/vue/index.js +196 -0
  316. package/dist/watch-Etoa_Mvr.js +2 -0
  317. package/dist/watch-UihESpsJ.js +128 -0
  318. package/dist/webmcp/index.d.ts +75 -0
  319. package/dist/webmcp/index.js +307 -0
  320. package/package.json +450 -5
  321. package/rulesets/permdock.yaml +29 -0
  322. package/schemas/approval-request-v1.json +175 -0
  323. package/schemas/catalog-v1.json +535 -0
  324. package/schemas/openapi/oas-3.1.json +1298 -0
  325. package/schemas/openapi/oas-3.2.json +1516 -0
  326. package/schemas/openapi/overlay-1.1.json +79 -0
  327. package/schemas/supabase-claims-v1.json +144 -0
  328. package/schemas/supabase-manifest-v1.json +361 -0
  329. package/skills/permdock/SKILL.md +66 -0
  330. package/skills/permdock-agents/SKILL.md +77 -0
  331. package/skills/permdock-agents/references/runtimes.md +213 -0
  332. package/skills/permdock-approvals/SKILL.md +80 -0
  333. package/skills/permdock-approvals/references/stores-and-resume.md +94 -0
  334. package/skills/permdock-audit/SKILL.md +67 -0
  335. package/skills/permdock-credentials/SKILL.md +55 -0
  336. package/skills/permdock-credentials/references/tokens-keys-links.md +132 -0
  337. package/skills/permdock-data/SKILL.md +57 -0
  338. package/skills/permdock-data/references/queries-and-rls.md +62 -0
  339. package/skills/permdock-data/references/relationships.md +67 -0
  340. package/skills/permdock-tenancy/SKILL.md +80 -0
  341. package/skills/permdock-tenancy/references/ownership-and-custom-roles.md +89 -0
  342. package/skills/permdock-wire/SKILL.md +116 -0
  343. package/skills/permdock-wire/references/adapters.md +492 -0
  344. package/skills/permdock-wire/references/policy-options.md +45 -0
@@ -0,0 +1,3502 @@
1
+ import { n as isReadonlyArray, r as sole } from "./compact-y6vfu2_f.js";
2
+ import { T as isForbiddenKey, _ as listPermissions, a as formerKeys } from "./permissions-DVoF6dMt.js";
3
+ import { a as hasConditionOp, c as isConditionRef, l as isSqlFunctionField } from "./refs-KYb4ntaz.js";
4
+ import { p as policyLevels } from "./policy-xyWg7QdR.js";
5
+ import { c as rootScope, d as scopeList, o as resolveScope } from "./scopes-CVdPrWN-.js";
6
+ import { E as listRoles, l as inheritCondition, m as relationCondition } from "./grantee-Cv5Sogfv.js";
7
+ import { t as canonicalJson } from "./canonical-json-DemiK4Vp.js";
8
+ import { d as partitionsOf, h as scopeField } from "./validity-uOp8UpYn.js";
9
+ import { t as requiresApproval } from "./approval-required-TzNB9oQA.js";
10
+ import { _ as leveled, p as andWhere } from "./permdock-CzqXjCpU.js";
11
+ import { i as requiresStandIn } from "./delegation-D8pUEuce.js";
12
+ import { t as CliError } from "./errors-CWfoNg9N.js";
13
+ import { o as jsonSchemaOf } from "./catalog-doc-Dsc9y7sd.js";
14
+ import { i as scopeMembershipTable, o as relatedSql, r as scopeColumn } from "./compile-Ba4blROR.js";
15
+ import { t as SQL_IDENT } from "./sql-xdg5f4Fi.js";
16
+ import { c as roleManifest, s as roleColumn } from "./sources-B0UvrJ21.js";
17
+ import { n as requirePeer } from "./peer-BOr_kJE1.js";
18
+ import { $ as sqlType, A as keyTenantSql, C as graphHelper, D as inheritedRowsHelper, E as hasMemberFor, F as memberForSources, G as quoteLiteral, H as permittedIdsHelper, J as roleKindSql, K as quoteTable, L as memberIdsHelper, M as linkHelper, N as liveSessionSql, O as isRecord, P as memberForHelper, R as memberRoleOf, S as grantPermissionSql, T as graphSqlText, U as qualifiedTable, V as permittedForHelper, W as quoteIdent, X as scopeTable, Y as scopeSources, Z as scopeTypeOf, _ as arrayColumnsOf, a as qualified$1, at as userIdHelperSql, b as disabledKeep, c as textArray, et as subjectClaimJsonSql, g as activeUserSql, i as helperSchema, it as tenantTypeOf, j as kindFilterSql, k as keptRowSql, l as CLAIM, m as activeMembershipSql, n as HELPERS, nt as subjectIdSql, o as rootName, p as activeInstancesSql, q as restrictedHelper, r as allowEntry, rt as tenantClaimSql, s as signedIn, t as CUSTOM_ROLES, tt as subjectClaimSql, u as CLOSURE, x as globalKindFilterSql, y as columnTypesOf, z as memberVia } from "./rls-shared-aOQ4hGTO.js";
19
+ import { createHash } from "node:crypto";
20
+ //#region src/cli/rls-api-keys.ts
21
+ const API_KEY_ALLOWS = "permdock_api_key_allows";
22
+ const DEFAULTS = {
23
+ claim: "api_key",
24
+ scopes: "scopes",
25
+ tenant: "tenant",
26
+ roles: "roles"
27
+ };
28
+ function field(settings, name) {
29
+ const value = settings[name] ?? DEFAULTS[name];
30
+ if (typeof value !== "string" || !SQL_IDENT.test(value)) throw new Error(`PermDock CLI: rls.apiKeys.${name} must be a claim field name matching ${SQL_IDENT.source}`);
31
+ return value;
32
+ }
33
+ function apiKeyFields(setting) {
34
+ const settings = setting === true ? {} : setting;
35
+ return {
36
+ claim: field(settings, "claim"),
37
+ scopes: field(settings, "scopes"),
38
+ tenant: field(settings, "tenant"),
39
+ roles: field(settings, "roles"),
40
+ serviceRoles: [...new Set(settings.serviceRoles ?? [])]
41
+ };
42
+ }
43
+ function apiKeysPlan(setting, declared, renamed) {
44
+ if (setting === void 0) return;
45
+ const fields = apiKeyFields(setting);
46
+ const unknown = fields.serviceRoles.filter((role) => !declared.has(role));
47
+ if (unknown.length > 0) throw new Error(`PermDock CLI: rls.apiKeys.serviceRoles names roles the policy does not declare: ${unknown.join(", ")}`);
48
+ return {
49
+ ...fields,
50
+ ...Object.keys(renamed).length === 0 ? {} : { renamed }
51
+ };
52
+ }
53
+ function qualified(ctx, name) {
54
+ return `${quoteIdent(ctx.schema ?? "permdock")}.${name}`;
55
+ }
56
+ function keyOf(ctx, plan) {
57
+ return `(select ${subjectClaimJsonSql(ctx, plan.claim)} as k) api_key`;
58
+ }
59
+ function permissionOf(plan, expr) {
60
+ return plan.renamed === void 0 ? expr : `coalesce(${quoteLiteral(JSON.stringify(plan.renamed))}::jsonb ->> ${expr}, ${expr})`;
61
+ }
62
+ function apiKeyAllowsCall(ctx, grant) {
63
+ return `${qualified(ctx, API_KEY_ALLOWS)}(${grant})`;
64
+ }
65
+ function apiKeyAllowsSql(ctx, plan, anonExecute) {
66
+ const fn = qualified(ctx, API_KEY_ALLOWS);
67
+ const scopes = `k -> ${quoteLiteral(plan.scopes)}`;
68
+ const grants = anonExecute ? `revoke execute on function ${fn}(text) from public;
69
+ grant execute on function ${fn}(text) to anon, authenticated;` : `revoke execute on function ${fn}(text) from public, anon;
70
+ grant execute on function ${fn}(text) to authenticated;`;
71
+ return `-- API keys: the ${plan.claim} claim's ${plan.scopes} list is a ceiling on every allow; denies always apply, and a request without the claim is not limited
72
+ create or replace function ${fn}(p_grant text)
73
+ returns boolean
74
+ language sql
75
+ stable
76
+ security definer
77
+ set search_path = ''
78
+ as $$
79
+ select case
80
+ when k is null or k = 'null'::jsonb then true
81
+ when exists (
82
+ select 1 from ${qualified(ctx, "role_permissions")} rp
83
+ where rp.grant_key = p_grant and rp.effect = 'deny'
84
+ ) then true
85
+ when jsonb_typeof(k) is distinct from 'object' or jsonb_typeof(${scopes}) is distinct from 'array' then false
86
+ else exists (
87
+ select 1
88
+ from jsonb_array_elements_text(${scopes}) s(permission)
89
+ where ${permissionOf(plan, "s.permission")} = split_part(split_part(p_grant, '#', 1), '@', 1)
90
+ )
91
+ end
92
+ from ${keyOf(ctx, plan)}
93
+ $$;
94
+ ${grants}`;
95
+ }
96
+ function serviceRolesJson(plan) {
97
+ return `${quoteLiteral(JSON.stringify(plan.serviceRoles))}::jsonb`;
98
+ }
99
+ function serviceKeyRows(ctx, plan) {
100
+ const roles = `k -> ${quoteLiteral(plan.roles)}`;
101
+ return ` from ${keyOf(ctx, plan)}
102
+ cross join lateral jsonb_array_elements_text(
103
+ case jsonb_typeof(${roles}) when 'array' then ${roles} else ${serviceRolesJson(plan)} end
104
+ ) r(role)`;
105
+ }
106
+ function serviceKeyFilters(ctx, plan, root, permission) {
107
+ const tenant = `k ->> ${quoteLiteral(plan.tenant)}`;
108
+ return [
109
+ `jsonb_typeof(k) = 'object'`,
110
+ `coalesce(${subjectIdSql(ctx)}::text, '') = ''`,
111
+ `coalesce(${tenant}, '') <> ''`,
112
+ ...activeInstancesSql(ctx, root, (name) => name === root ? tenant : void 0, permission)
113
+ ];
114
+ }
115
+ function serviceKeyIdsSql(ctx, plan, root, type) {
116
+ const kind = kindFilterSql(ctx, "r.role", { value: "credential" });
117
+ const set = ctx.grantSet === true;
118
+ const filters = [
119
+ ...serviceKeyFilters(ctx, plan, root, grantPermissionSql(set ? "rp.grant_key" : "p_grant")),
120
+ ...set ? [] : ["rp.grant_key = p_grant"],
121
+ `rp.scope = ${quoteLiteral(root)}`,
122
+ ...kind === void 0 ? [] : [kind]
123
+ ];
124
+ return ` select (k ->> ${quoteLiteral(plan.tenant)})::${type}${set ? ", rp.grant_key" : ""}
125
+ ${serviceKeyRows(ctx, plan)}
126
+ join ${qualified(ctx, "role_permissions")} rp on rp.role = r.role
127
+ where ${filters.join("\n and ")}`;
128
+ }
129
+ function serviceKeyMemberSql(ctx, plan, root, type) {
130
+ return ` select distinct (k ->> ${quoteLiteral(plan.tenant)})::${type}
131
+ ${serviceKeyRows(ctx, plan)}
132
+ where ${serviceKeyFilters(ctx, plan, root).join("\n and ")}`;
133
+ }
134
+ function ceilingIdsSql(body, allows) {
135
+ return ` select ids.id
136
+ from (
137
+ ${body}
138
+ ) ids(id)
139
+ where ${allows}`;
140
+ }
141
+ function ceilingHasSql(body, allows) {
142
+ return ` select ${allows} and coalesce((
143
+ ${body}
144
+ ), false)`;
145
+ }
146
+ //#endregion
147
+ //#region src/cli/rls-conditions.ts
148
+ const MAX_CLAIM_DEPTH = 8;
149
+ /**
150
+ * The claim path of a `principal.claim.*` / `principal.claims.*` ref, one
151
+ * segment per JSON key; `undefined` for any other ref.
152
+ */
153
+ function claimPath(ref) {
154
+ const prefix = ["principal.claim.", "principal.claims."].find((item) => ref.startsWith(item));
155
+ if (prefix === void 0) return;
156
+ const segments = ref.slice(prefix.length).split(".");
157
+ if (segments.length > MAX_CLAIM_DEPTH) throw new Error(`PermDock CLI: claim path '${ref}' is deeper than ${MAX_CLAIM_DEPTH}`);
158
+ for (const segment of segments) if (!CLAIM.test(segment) || isForbiddenKey(segment)) throw new Error(`PermDock CLI: unsafe claim name '${segment}'`);
159
+ return segments;
160
+ }
161
+ function jsonPath(base, keys, last) {
162
+ let sql = base;
163
+ for (const [index, key] of keys.entries()) sql += ` ${index === keys.length - 1 ? last : "->"} ${quoteLiteral(key)}`;
164
+ return sql;
165
+ }
166
+ /**
167
+ * The JSON document a claim path starts from and the keys to walk in it. The
168
+ * `guc` dialect keeps each top-level claim in its own setting as JSON text.
169
+ */
170
+ function claimRoot(ctx, path) {
171
+ const [head, ...rest] = path;
172
+ if (head === void 0) throw new Error("PermDock CLI: empty claim path");
173
+ switch (ctx.dialect) {
174
+ case "supabase": return {
175
+ root: "(select auth.jwt())",
176
+ keys: path
177
+ };
178
+ case "neon": return {
179
+ root: "(select auth.session())",
180
+ keys: path
181
+ };
182
+ case "guc": return {
183
+ root: subjectClaimJsonSql(ctx, head),
184
+ keys: rest
185
+ };
186
+ default: return ctx.dialect;
187
+ }
188
+ }
189
+ /** The claim at `path` as `jsonb`. */
190
+ function claimJsonSql(ctx, path) {
191
+ const { root, keys } = claimRoot(ctx, path);
192
+ return keys.length === 0 ? root : `(${jsonPath(root, keys, "->")})`;
193
+ }
194
+ /** The claim at `path` as text: `->>` on the last key, or the plain setting for a one-segment `guc` claim. */
195
+ function claimTextSql(ctx, path) {
196
+ const [head] = path;
197
+ if (path.length === 1 && head !== void 0) return subjectClaimSql(ctx, head);
198
+ const { root, keys } = claimRoot(ctx, path);
199
+ return `(${jsonPath(root, keys, "->>")})`;
200
+ }
201
+ /** The JSON kind a claim must have to compare with a column of `type`. */
202
+ function jsonKindOf(type) {
203
+ if (type === "numeric") return "number";
204
+ return type === "boolean" ? "boolean" : "string";
205
+ }
206
+ /**
207
+ * A claim compared with a column of `type`. Numbers and booleans must be JSON
208
+ * of that kind (anything else is `null`, so the comparison is false, as in
209
+ * memory); other types cast the text form. A one-segment `guc` claim is text
210
+ * and is cast as is.
211
+ */
212
+ function typedClaimSql(ctx, path, type) {
213
+ const text = claimTextSql(ctx, path);
214
+ if (type === void 0 || type === "text") return text;
215
+ const cast = `${text}::${sqlType(type)}`;
216
+ const kind = jsonKindOf(type);
217
+ if (kind === "string" || ctx.dialect === "guc" && path.length === 1) return `(${cast})`;
218
+ return `(case when jsonb_typeof(${claimJsonSql(ctx, path)}) = '${kind}' then ${cast} end)`;
219
+ }
220
+ /**
221
+ * The elements of an array claim as a Postgres array of the column's type,
222
+ * built once per statement (an uncorrelated `array(select ...)` is an InitPlan).
223
+ * A missing or non-array claim is the empty array; elements of another JSON
224
+ * kind are left out.
225
+ */
226
+ function claimArraySql(ctx, path, type) {
227
+ const json = claimJsonSql(ctx, path);
228
+ return `array(select ${type === void 0 || type === "text" ? `(e #>> '{}')` : `(e #>> '{}')::${sqlType(type)}`} from jsonb_array_elements(case when jsonb_typeof(${json}) = 'array' then ${json} else '[]'::jsonb end) e where jsonb_typeof(e) = '${jsonKindOf(type)}')`;
229
+ }
230
+ function sqlValue(value, ctx, field) {
231
+ if (value !== null && typeof value === "object" && "ref" in value) return compileRef(value.ref, ctx, field);
232
+ if (value !== null && typeof value === "object" && "date" in value) return quoteLiteral(value.date);
233
+ if (isReadonlyArray(value)) return `array[${value.map((item) => sqlValue(item, ctx)).join(", ")}]`;
234
+ if (value === null) return "null";
235
+ if (typeof value === "boolean") return value ? "true" : "false";
236
+ if (typeof value === "number") return Number.isFinite(value) ? String(value) : "null";
237
+ if (typeof value === "string") return quoteLiteral(value);
238
+ throw new Error("PermDock CLI: non-portable condition value");
239
+ }
240
+ function compileRef(ref, ctx, field) {
241
+ if (ref === "principal.id") return subjectIdSql(ctx);
242
+ if (ref === "now") return "now()";
243
+ const path = claimPath(ref);
244
+ if (ref === "principal.tenant" || path?.length === 1 && path[0] === ctx.tenantClaim) return tenantClaimSql(ctx);
245
+ if (path !== void 0) return typedClaimSql(ctx, path, field === void 0 ? void 0 : ctx.columnTypes?.[field]);
246
+ if (ref === "context" || ref.startsWith("context.")) throw new Error(`PermDock CLI: '${ref}' is request context, which is not in the token; RLS cannot read it (permdock doctor PD027)`);
247
+ throw new Error(`PermDock CLI: non-portable subject ref '${ref}'`);
248
+ }
249
+ /** `value` with `\`, `%` and `_` escaped for `like ... escape '\'`, as `escapeLike` does in process. */
250
+ function likeLiteralSql(value) {
251
+ return `replace(replace(replace(${value}, '\\', '\\\\'), '%', '\\%'), '_', '\\_')`;
252
+ }
253
+ function compareSql(op, field, value) {
254
+ const left = quoteIdent(field);
255
+ switch (op) {
256
+ case "eq": return `${left} = ${value}`;
257
+ case "ne": return `${left} <> ${value}`;
258
+ case "gt": return `${left} > ${value}`;
259
+ case "gte": return `${left} >= ${value}`;
260
+ case "lt": return `${left} < ${value}`;
261
+ case "lte": return `${left} <= ${value}`;
262
+ case "contains": return `${left}::text like '%' || ${likeLiteralSql(`${value}::text`)} || '%' escape '\\'`;
263
+ default: return op;
264
+ }
265
+ }
266
+ function existsSql(table, rowColumn, rowField, roles, ctx, tenantColumn, scope) {
267
+ const parts = [`m.${quoteIdent(rowColumn)} = ${quoteIdent(rowField)}`, `m.${quoteIdent(table.user)} = ${subjectIdSql(ctx)}`];
268
+ const role = memberRoleOf(table);
269
+ if (roles.length > 0) {
270
+ const roleList = roles.map((name) => name.replaceAll("'", "''")).join(",");
271
+ const held = role.through === void 0 && !role.lateral ? `m.${quoteIdent(role.column)}` : role.lookup;
272
+ parts.push(`${held} = any('{${roleList}}')`);
273
+ const via = memberVia(table);
274
+ const single = sole(roles);
275
+ const kind = single === void 0 ? kindFilterSql(ctx, role.lookup, via) : roleKindSql(ctx, single, via);
276
+ if (kind !== void 0) parts.push(kind);
277
+ }
278
+ if (table.expiresAt !== void 0) parts.push(`(m.${quoteIdent(table.expiresAt)} is null or m.${quoteIdent(table.expiresAt)} > now())`);
279
+ parts.push(...activeMembershipSql(ctx, table.disabledAt === void 0 ? void 0 : `m.${quoteIdent(table.disabledAt)}`));
280
+ if (tenantColumn !== void 0 && ctx.tenants !== "all") parts.push(`m.${quoteIdent(tenantColumn)} = ${tenantClaimSql(ctx)}`);
281
+ parts.push(...activeUserSql(ctx));
282
+ if (scope !== void 0) {
283
+ const tenantOf = scope === rootScope(ctx.scopes) ? rowColumn : tenantColumn;
284
+ const keyed = keyTenantSql(ctx, tenantOf === void 0 ? void 0 : `m.${quoteIdent(tenantOf)}`);
285
+ if (keyed !== void 0) parts.push(keyed);
286
+ parts.push(...activeInstancesSql(ctx, scope, (name) => {
287
+ const held = scopeColumn(table, ctx.scopes, name);
288
+ return held === void 0 ? void 0 : `m.${quoteIdent(held)}`;
289
+ }));
290
+ }
291
+ const expand = roles.length > 0 && role.lateral ? role.join : "";
292
+ return `exists (select 1 from ${quoteTable(table.table)} m${expand} where ${parts.join(" and ")})`;
293
+ }
294
+ function compileMemberOf(condition, ctx) {
295
+ const scope = condition.scope === "resource" ? void 0 : resolveScope(ctx.scopes, condition.scope);
296
+ if (condition.scope !== "resource" && scope === void 0) throw new Error(`PermDock CLI: memberOf ${condition.scope} names a scope the policy does not declare`);
297
+ const mapping = scope === void 0 ? condition.resource === void 0 ? void 0 : ctx.memberships?.resource?.[condition.resource] : scopeMembershipTable(ctx.memberships, ctx.scopes, scope);
298
+ if (mapping !== void 0) {
299
+ const named = scope === void 0 ? void 0 : scopeTable(ctx, scope);
300
+ const rowColumn = scope === void 0 ? mapping.id : named?.column;
301
+ if (rowColumn === void 0) throw new Error(`PermDock CLI: memberships mapping for ${condition.scope} is missing the row column`);
302
+ const tenantColumn = scope === void 0 || scope === rootScope(ctx.scopes) ? void 0 : named?.tenantColumn;
303
+ const primary = existsSql(mapping, rowColumn, condition.field, condition.roles, ctx, tenantColumn, scope);
304
+ if (condition.scope !== "resource" || condition.parents === void 0) return primary;
305
+ return `(${[primary, ...condition.parents.flatMap((parent) => {
306
+ if (typeof parent === "string") return [existsSql(mapping, rowColumn, parent, condition.roles, ctx, tenantColumn)];
307
+ const hopTable = ctx.memberships?.resource?.[parent.resource];
308
+ return hopTable?.id === void 0 ? [] : [existsSql(hopTable, hopTable.id, parent.field, condition.roles, ctx)];
309
+ })].join(" or ")})`;
310
+ }
311
+ if (scope !== void 0 && condition.roles.length === 0 && scopeSources(ctx, scope).length > 0) return `${quoteIdent(condition.field)} in (select ${quoteIdent(ctx.schema ?? "permdock")}.${memberIdsHelper(scope)}())`;
312
+ if (scope !== void 0 && scope === rootScope(ctx.scopes)) {
313
+ const parts = [
314
+ ctx.tenants === "all" ? `${quoteIdent(condition.field)} in (select ${quoteIdent(ctx.schema ?? "permdock")}.${memberIdsHelper(scope)}())` : `${quoteIdent(condition.field)} = ${tenantClaimSql(ctx)}`,
315
+ ...ctx.tenants === "all" ? [] : [keyTenantSql(ctx, quoteIdent(condition.field))].filter((part) => part !== void 0),
316
+ ...activeUserSql(ctx),
317
+ ...activeInstancesSql(ctx, scope, () => quoteIdent(condition.field))
318
+ ];
319
+ return parts.length === 1 ? parts.join("") : `(${parts.join(" and ")})`;
320
+ }
321
+ throw new Error(`PermDock CLI: memberOf ${condition.scope} needs a memberships table mapping`);
322
+ }
323
+ function compileConditionSql(condition, ctx) {
324
+ switch (condition.op) {
325
+ case "eq":
326
+ case "ne":
327
+ case "gt":
328
+ case "gte":
329
+ case "lt":
330
+ case "lte": return compareSql(condition.op, condition.field, sqlValue(condition.value, ctx, condition.field));
331
+ case "contains": {
332
+ const element = ctx.arrayColumns?.[condition.field];
333
+ if (element !== void 0) return `${sqlValue(condition.value, {
334
+ ...ctx,
335
+ columnTypes: {
336
+ ...ctx.columnTypes,
337
+ [condition.field]: element
338
+ }
339
+ }, condition.field)} = any(${quoteIdent(condition.field)})`;
340
+ return compareSql(condition.op, condition.field, sqlValue(condition.value, ctx, condition.field));
341
+ }
342
+ case "in":
343
+ case "notIn": {
344
+ const keyword = condition.op === "in" ? "in" : "not in";
345
+ if (!Array.isArray(condition.value) && typeof condition.value === "object" && "ref" in condition.value) {
346
+ const path = claimPath(condition.value.ref);
347
+ if (path === void 0) {
348
+ compileRef(condition.value.ref, ctx);
349
+ throw new Error(`PermDock CLI: non-portable ${condition.op} against '${condition.value.ref}'`);
350
+ }
351
+ const column = quoteIdent(condition.field);
352
+ const list = claimArraySql(ctx, path, ctx.columnTypes?.[condition.field]);
353
+ return condition.op === "in" ? `${column} = any (${list})` : `(${column} is not null and not (${column} = any (${list})))`;
354
+ }
355
+ const values = condition.value.map((item) => sqlValue(item, ctx));
356
+ return `${quoteIdent(condition.field)} ${keyword} (${values.join(", ")})`;
357
+ }
358
+ case "isNull": return `${quoteIdent(condition.field)} is ${condition.value ? "" : "not "}null`;
359
+ case "and": return `(${condition.conditions.map((item) => compileConditionSql(item, ctx)).join(" and ")})`;
360
+ case "or":
361
+ if (condition.conditions.length === 0) return "false";
362
+ return `(${condition.conditions.map((item) => compileConditionSql(item, ctx)).join(" or ")})`;
363
+ case "not": return `(${compileConditionSql(condition.condition, ctx)}) is not true`;
364
+ case "memberOf": return compileMemberOf(condition, ctx);
365
+ case "related": return compileRelatedSql(condition, ctx);
366
+ case "sqlFunction":
367
+ if (ctx.inlineFunctions === true) return compileConditionSql(condition.twin, ctx);
368
+ return `${quoteTable(condition.name)}(${condition.args.map((arg) => isSqlFunctionField(arg) ? quoteIdent(arg.field) : sqlValue(arg, ctx)).join(", ")})`;
369
+ case "opaque": return condition.sql;
370
+ case "liveSession": return liveSessionSql(ctx);
371
+ default: return condition;
372
+ }
373
+ }
374
+ function andConditions(left, right) {
375
+ if (left === void 0) return right;
376
+ if (right === void 0) return left;
377
+ return {
378
+ op: "and",
379
+ conditions: [left, right]
380
+ };
381
+ }
382
+ function valueContextRefs(value) {
383
+ if (Array.isArray(value)) return value.flatMap(valueContextRefs);
384
+ if (isRecord(value) && typeof value["ref"] === "string" && (value["ref"] === "context" || value["ref"].startsWith("context."))) return [value["ref"]];
385
+ return [];
386
+ }
387
+ /**
388
+ * The `context.*` refs a condition reads. The request context is not in the
389
+ * token, so RLS cannot evaluate them.
390
+ */
391
+ function contextRefs(condition) {
392
+ if (condition === void 0) return [];
393
+ switch (condition.op) {
394
+ case "eq":
395
+ case "ne":
396
+ case "gt":
397
+ case "gte":
398
+ case "lt":
399
+ case "lte":
400
+ case "contains":
401
+ case "in":
402
+ case "notIn": return valueContextRefs(condition.value);
403
+ case "and":
404
+ case "or": return condition.conditions.flatMap((child) => contextRefs(child));
405
+ case "not": return contextRefs(condition.condition);
406
+ case "sqlFunction": return [...condition.args.flatMap(valueContextRefs), ...contextRefs(condition.twin)];
407
+ case "isNull":
408
+ case "memberOf":
409
+ case "related":
410
+ case "opaque":
411
+ case "liveSession": return [];
412
+ default: return condition;
413
+ }
414
+ }
415
+ function sqlFunctionNames(condition) {
416
+ if (condition === void 0) return [];
417
+ switch (condition.op) {
418
+ case "sqlFunction": return [condition.name, ...sqlFunctionNames(condition.twin)];
419
+ case "and":
420
+ case "or": return condition.conditions.flatMap((child) => sqlFunctionNames(child));
421
+ case "not": return sqlFunctionNames(condition.condition);
422
+ case "eq":
423
+ case "ne":
424
+ case "gt":
425
+ case "gte":
426
+ case "lt":
427
+ case "lte":
428
+ case "contains":
429
+ case "in":
430
+ case "notIn":
431
+ case "isNull":
432
+ case "memberOf":
433
+ case "related":
434
+ case "opaque":
435
+ case "liveSession": return [];
436
+ default: return condition;
437
+ }
438
+ }
439
+ /**
440
+ * A `related` condition as uncorrelated subqueries, so Postgres runs the
441
+ * helper once per statement: the row's field in the closure's descendants of
442
+ * the ids the subject holds the relation on (or those ids alone at depth 0).
443
+ * The helper sits in `array(...)` so it stays an InitPlan; a plain `in` gets
444
+ * pulled into a join that can rescan it per closure row.
445
+ */
446
+ function compileRelatedSql(condition, ctx) {
447
+ if (condition.hops !== void 0 && condition.hops.length > 0) return compileHoppedSql(condition, ctx);
448
+ const type = ctx.columnTypes?.[condition.field];
449
+ const cast = type === void 0 || type === "text" ? "" : `::${type}`;
450
+ const column = type === void 0 ? `${quoteIdent(condition.field)}::text` : quoteIdent(condition.field);
451
+ const helper = condition.permission === void 0 ? `${`${quoteIdent(ctx.schema ?? "permdock")}.${graphHelper(condition.resource)}`}(${quoteLiteral(condition.relation)})` : `${quoteIdent(ctx.schema ?? "permdock")}.${inheritedRowsHelper(condition.resource)}(${quoteLiteral(condition.permission)})`;
452
+ const cap = ctx.graph?.closures[condition.resource];
453
+ let inner;
454
+ if (condition.depth > 0 && cap !== void 0) {
455
+ const depth = condition.depth < cap ? ` and depth <= ${String(condition.depth)}` : "";
456
+ inner = `select descendant${cast} from ${`${quoteIdent(ctx.schema ?? "permdock")}.${CLOSURE.table}`} where resource = ${quoteLiteral(condition.resource)}${depth} and ancestor = any (array(select ${helper}))`;
457
+ } else inner = cast === "" ? `select ${helper}` : `select p.id${cast} from ${helper} as p(id)`;
458
+ const reach = `${column} in (${inner})`;
459
+ if (condition.parent === true && condition.restricted !== void 0) return `(${reach} and ${quoteIdent(condition.restricted)} is not true)`;
460
+ return reach;
461
+ }
462
+ /**
463
+ * A `related` condition that crosses link hops: the reached instances of the
464
+ * last resource, carried back over each link by its security definer helper,
465
+ * so the hop reads a table the subject may not see.
466
+ */
467
+ function compileHoppedSql(condition, ctx) {
468
+ const resources = ctx.graph?.resources;
469
+ if (resources === void 0) throw new Error("PermDock CLI: a related condition with link hops needs the policy resources in the RLS context");
470
+ const schema = quoteIdent(ctx.schema ?? "permdock");
471
+ return graphSqlText(relatedSql(condition, {
472
+ resources,
473
+ ...ctx.graph?.tables === void 0 ? {} : { tables: ctx.graph.tables },
474
+ closure: `${ctx.schema ?? "permdock"}.${CLOSURE.table}`,
475
+ closureDepths: ctx.graph?.closures ?? {},
476
+ qualify: qualifiedTable,
477
+ holders: (resource, relation) => [{ text: `select ${schema}.${graphHelper(resource)}(${quoteLiteral(relation)})` }],
478
+ permitted: (resource, permission) => [{ text: `select ${schema}.${inheritedRowsHelper(resource)}(${quoteLiteral(permission)})` }],
479
+ restrictedRows: (resource) => [{ text: `select ${schema}.${restrictedHelper(resource)}()` }],
480
+ linked: (resource, link, targets) => [
481
+ { text: `select ${schema}.${linkHelper(resource, link)}(array(` },
482
+ ...targets,
483
+ { text: "))" }
484
+ ]
485
+ }), ctx);
486
+ }
487
+ //#endregion
488
+ //#region src/cli/rls-grants.ts
489
+ /**
490
+ * The `role_permissions` grant key of a break-glass grant. It differs from
491
+ * the permission key, so `authorize()` and the table policies never count it;
492
+ * only the break-glass read asks for it.
493
+ */
494
+ function breakGlassKey(permission) {
495
+ return `${permission}#break-glass`;
496
+ }
497
+ /**
498
+ * The role and scope holding a break-glass grant. `breakGlass()` sets
499
+ * `to: authenticated`, so inside `role()` the role is on the grant itself.
500
+ */
501
+ function breakGlassHolder(item) {
502
+ if (item.access.kind === "role") return {
503
+ role: item.access.role,
504
+ scope: item.access.scope
505
+ };
506
+ const { role, scope } = item.grant;
507
+ return role === null || typeof scope !== "string" ? void 0 : {
508
+ role,
509
+ scope
510
+ };
511
+ }
512
+ function granteeItems(to) {
513
+ return Array.isArray(to) ? to : [to];
514
+ }
515
+ function relationWhere(policy, grant, grantee) {
516
+ const node = policy.resources.get(grant.permission.resource);
517
+ const where = relationCondition(grantee, node, scopeList(policy.scopes), {
518
+ resources: policy.resources,
519
+ now: { ref: "now" }
520
+ });
521
+ if (where === void 0) throw new Error(`PermDock CLI: grant ${grant.permission.key} names relation '${grantee.relation}', which ${grant.permission.resource} does not declare`);
522
+ return where;
523
+ }
524
+ function inheritWhere(policy, grant, grantee) {
525
+ const where = inheritCondition(grantee, policy.resources.get(grant.permission.resource), policy.resources);
526
+ if (where === void 0) throw new Error(`PermDock CLI: grant ${grant.permission.key} inherits ${grantee.permission}, which ${grant.permission.resource} cannot reach`);
527
+ return where;
528
+ }
529
+ /** Only a deny for `oauth-client` actors compiles: Postgres sees `client_id` and `act`, not other actor kinds. */
530
+ function actorAccess(grant, grantee, others) {
531
+ if (grant.effect !== "deny" || grantee.actor !== "oauth-client" || others > 0) throw new Error(`PermDock CLI: grant ${grant.permission.key} is limited to an actor grantee; RLS compiles only deny(…, { to: actor('oauth-client') }) on its own, so enforce it in the application`);
532
+ return {
533
+ kind: "actor",
534
+ actor: "oauth-client"
535
+ };
536
+ }
537
+ function accessOf(grant, roles, anyone) {
538
+ const [held, ...more] = roles;
539
+ if (more.length > 0) throw new Error(`PermDock CLI: grant ${grant.permission.key} requires several roles at once (${roles.map((item) => item.role).join(", ")}); RLS compiles one role per grant`);
540
+ if (held === void 0) return anyone ? { kind: "anyone" } : { kind: "authenticated" };
541
+ if (typeof held.scope === "object") return {
542
+ kind: "resource",
543
+ role: held.role,
544
+ resource: held.scope.resource
545
+ };
546
+ return {
547
+ kind: "role",
548
+ role: held.role,
549
+ scope: held.scope
550
+ };
551
+ }
552
+ /**
553
+ * Every grant RLS must enforce: role grants and top-level
554
+ * `definePolicy({ grants })` alike (`policy.grants` holds both). A grantee
555
+ * Postgres cannot see (plan, actor, assurance) fails with the permission named.
556
+ */
557
+ function collectGrants(policy) {
558
+ return policy.grants.map((grant) => {
559
+ const items = granteeItems(grant.to);
560
+ const roles = [];
561
+ let anyone = true;
562
+ let where = grant.where;
563
+ let delegated;
564
+ for (const item of items) switch (item.kind) {
565
+ case "role":
566
+ roles.push(item);
567
+ break;
568
+ case "anyone": break;
569
+ case "authenticated":
570
+ anyone = false;
571
+ break;
572
+ case "relation":
573
+ anyone = false;
574
+ where = andConditions(where, relationWhere(policy, grant, item));
575
+ break;
576
+ case "inherit":
577
+ anyone = false;
578
+ where = andConditions(where, inheritWhere(policy, grant, item));
579
+ break;
580
+ case "actor":
581
+ delegated = actorAccess(grant, item, items.length - 1);
582
+ break;
583
+ case "plan":
584
+ case "assurance": throw new Error(`PermDock CLI: grant ${grant.permission.key} is limited to a ${item.kind} grantee, which RLS cannot compile; enforce it in the application`);
585
+ default: return item;
586
+ }
587
+ const access = delegated ?? accessOf(grant, roles, anyone);
588
+ const label = access.kind === "role" || access.kind === "resource" ? access.role : access.kind;
589
+ return where === void 0 ? {
590
+ grant,
591
+ label,
592
+ access
593
+ } : {
594
+ grant,
595
+ label,
596
+ access,
597
+ where
598
+ };
599
+ });
600
+ }
601
+ /** Declared role names (bindings and `defineRoles` leaves) plus any role a top-level grant names. */
602
+ function roleNames(policy) {
603
+ const names = new Set(policy.roles.map((item) => item.name));
604
+ for (const leaf of listRoles(policy.vocabulary.roles)) names.add(leaf.key);
605
+ for (const item of collectGrants(policy)) if (item.access.kind === "role" || item.access.kind === "resource") names.add(item.access.role);
606
+ return [...names];
607
+ }
608
+ //#endregion
609
+ //#region src/cli/global-roles.ts
610
+ function qualify(name, schema) {
611
+ return name.includes(".") ? name : `${schema}.${name}`;
612
+ }
613
+ /** Resolves `source` against `schema`, aliasing the table `alias` and the roles table `<alias>k`. */
614
+ function globalRoleSource(source, schema, alias) {
615
+ const table = qualify(source.table, schema);
616
+ const user = source.user ?? "user_id";
617
+ const role = roleColumn(source.role ?? "role", table, alias, {
618
+ label: "roles.role",
619
+ prefix: "PermDock CLI",
620
+ indent: " "
621
+ });
622
+ return {
623
+ table,
624
+ user,
625
+ from: `${quoteTable(table)} ${alias}${role.join}`,
626
+ userSql: `${alias}.${quoteIdent(user)}`,
627
+ roleSql: role.sql,
628
+ role: roleManifest(role),
629
+ ...role.through === void 0 ? {} : { through: role.through }
630
+ };
631
+ }
632
+ //#endregion
633
+ //#region src/cli/rls-custom-roles.ts
634
+ /** The readers every helpers file ends with. Names are part of the SQL contract. */
635
+ const READERS = {
636
+ keys: "permdock_permission_keys",
637
+ roles: "permdock_role_permissions",
638
+ trusted: "permdock_trusted_role_permissions"
639
+ };
640
+ /**
641
+ * The custom-role objects: the tables (`database` mode), the ceiling view
642
+ * over the `assignable` declared roles, and `permdock_custom_keys`, which
643
+ * resolves one custom role to the grant keys it holds in a scope. A row in
644
+ * the tables can never reach a key outside the view.
645
+ */
646
+ function customRolesSql(ctx) {
647
+ const custom = ctx.customRoles;
648
+ if (custom === void 0) return "";
649
+ const rp = qualified$1(ctx, "role_permissions");
650
+ const ceiling = qualified$1(ctx, CUSTOM_ROLES.ceiling);
651
+ const keys = qualified$1(ctx, CUSTOM_ROLES.keys);
652
+ const chunks = [];
653
+ if (ctx.authorize === "database") {
654
+ const tenantType = tenantTypeOf(ctx);
655
+ for (const [name, column, check] of [[
656
+ CUSTOM_ROLES.permissions,
657
+ "permission",
658
+ `,
659
+ effect text not null default 'allow' check (effect in ('allow', 'deny'))`
660
+ ], [
661
+ CUSTOM_ROLES.includes,
662
+ "include_role",
663
+ ""
664
+ ]]) {
665
+ const table = qualified$1(ctx, name);
666
+ const leveled = custom.levels === true && name === CUSTOM_ROLES.permissions;
667
+ const unique = `${column}${name === CUSTOM_ROLES.permissions ? ", effect" : ""}${leveled ? ", coalesce(level, '')" : ""}`;
668
+ const index = leveled ? `drop index if exists ${qualified$1(ctx, quoteIdent(`${name}_key`))};
669
+ alter table ${table} add column if not exists level text check (level ~ '^[a-z][a-z0-9_]*$');
670
+ create unique index if not exists ${quoteIdent(`${name}_level_key`)}` : `create unique index if not exists ${quoteIdent(`${name}_key`)}`;
671
+ chunks.push(`create table if not exists ${table} (
672
+ tenant_id ${tenantType},
673
+ scope text not null default ${quoteLiteral(rootName(ctx))},
674
+ scope_id text,
675
+ role text not null,
676
+ ${column} text not null${check},
677
+ check ((scope = 'global') = (tenant_id is null)),
678
+ check (scope <> 'global' or scope_id is null)
679
+ );
680
+ ${index}
681
+ on ${table} (coalesce(tenant_id::text, ''), scope, coalesce(scope_id, ''), role, ${unique});
682
+ alter table ${table} enable row level security;
683
+ revoke all on table ${table} from anon, authenticated, public;`);
684
+ }
685
+ }
686
+ chunks.push(`-- the ceiling: keys of assignable declared roles, and the denies of those roles on the same permissions
687
+ create or replace view ${ceiling} with (security_invoker = true) as
688
+ select rp.scope, rp.role, rp.permission, rp.grant_key, rp.effect
689
+ from ${rp} rp
690
+ where rp.role = any(${textArray(custom.assignable)})
691
+ and exists (
692
+ select 1 from ${rp} a
693
+ where a.role = rp.role
694
+ and a.permission = rp.permission
695
+ and a.scope = rp.scope
696
+ and a.effect = 'allow'
697
+ );
698
+ revoke all on table ${ceiling} from anon, authenticated, public;`);
699
+ const renames = Object.entries(custom.renamed ?? {}).toSorted(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
700
+ if (custom.levels === true) {
701
+ chunks.push(leveledKeysSql(ctx, renames));
702
+ return chunks.join("\n\n");
703
+ }
704
+ const rename = renamesSql(renames);
705
+ chunks.push(`-- one custom role: included ceiling keys and same-scope denies, plus every ceiling key of an allowed permission, minus denied permissions
706
+ create or replace function ${keys}(p_allow text[], p_deny text[], p_include text[], p_scope text)
707
+ returns setof text
708
+ language sql
709
+ stable
710
+ set search_path = ''
711
+ as $$
712
+ with ${rename.prelude}ceiling as (
713
+ select c.role, ${rename.permission("c")}, c.grant_key, c.effect
714
+ from ${ceiling} c${rename.join("c")}
715
+ where c.scope = p_scope
716
+ ),
717
+ included as (
718
+ select rp.role, ${rename.permission("rp")}, rp.grant_key, rp.scope, rp.effect
719
+ from ${rp} rp${rename.join("rp")}
720
+ where rp.role = any(coalesce(p_include, '{}'::text[]))
721
+ ),
722
+ kept as (
723
+ select i.permission, i.grant_key
724
+ from included i
725
+ where i.effect = 'allow'
726
+ and i.scope = p_scope
727
+ and exists (
728
+ select 1 from ceiling c
729
+ where c.role = i.role and c.grant_key = i.grant_key and c.effect = 'allow'
730
+ )
731
+ ),
732
+ wanted as (
733
+ ${rename.allow}
734
+ union
735
+ select i.permission
736
+ from included i
737
+ where i.effect = 'allow'
738
+ and not (i.scope = p_scope and exists (
739
+ select 1 from ceiling c
740
+ where c.role = i.role and c.grant_key = i.grant_key and c.effect = 'allow'
741
+ ))
742
+ ),
743
+ allowed as (
744
+ select w.permission
745
+ from wanted w
746
+ where not (${rename.denied("w")})
747
+ and not exists (select 1 from kept k where k.permission = w.permission)
748
+ )
749
+ select k.grant_key from kept k
750
+ where not (${rename.denied("k")})
751
+ union
752
+ select i.grant_key from included i
753
+ where i.effect = 'deny' and i.scope = p_scope
754
+ union
755
+ select c.grant_key from ceiling c
756
+ where c.permission in (select a.permission from allowed a)
757
+ $$;
758
+ revoke execute on function ${keys}(text[], text[], text[], text) from public, anon, authenticated;`);
759
+ return chunks.join("\n\n");
760
+ }
761
+ /**
762
+ * `permdock_custom_keys` when resources declare levels. An allow entry is
763
+ * `key` or `key@level`. A level reaches only the ceiling's `<grant key>@<level>`
764
+ * keys, plus the ceiling denies of that permission; a level no ceiling key
765
+ * carries removes the permission, as `resolveCustomRole` drops it with
766
+ * `unknown-level`.
767
+ */
768
+ function leveledKeysSql(ctx, renames) {
769
+ const rp = qualified$1(ctx, "role_permissions");
770
+ const ceiling = qualified$1(ctx, CUSTOM_ROLES.ceiling);
771
+ const keys = qualified$1(ctx, CUSTOM_ROLES.keys);
772
+ const renamed = renames.length > 0;
773
+ const prelude = renamed ? `renamed (former, key) as (values ${renames.map(([former, current]) => `(${quoteLiteral(former)}, ${quoteLiteral(current)})`).join(", ")}),
774
+ ` : "";
775
+ const current = (raw, alias) => renamed ? `coalesce(r_${alias}.key, ${raw})` : raw;
776
+ const join = (raw, alias) => renamed ? ` left join renamed r_${alias} on r_${alias}.former = ${raw}` : "";
777
+ return `-- one custom role: as above, where an allow entry key@level reaches only the ceiling keys of that level
778
+ create or replace function ${keys}(p_allow text[], p_deny text[], p_include text[], p_scope text)
779
+ returns setof text
780
+ language sql
781
+ stable
782
+ set search_path = ''
783
+ as $$
784
+ with ${prelude}entries as (
785
+ select ${current("split_part(e.entry, '@', 1)", "e")} as permission, nullif(split_part(e.entry, '@', 2), '') as level
786
+ from unnest(coalesce(p_allow, '{}'::text[])) as e(entry)${join("split_part(e.entry, '@', 1)", "e")}
787
+ ),
788
+ ceiling as (
789
+ select c.role, ${current("c.permission", "c")} as permission, c.grant_key, c.effect
790
+ from ${ceiling} c${join("c.permission", "c")}
791
+ where c.scope = p_scope
792
+ ),
793
+ levels as (
794
+ select distinct c.permission, split_part(c.grant_key, '@', 2) as level
795
+ from ceiling c
796
+ where c.effect = 'allow' and strpos(c.grant_key, '@') > 0
797
+ ),
798
+ denied as (
799
+ select ${current("d.permission", "d")} as permission
800
+ from unnest(coalesce(p_deny, '{}'::text[])) as d(permission)${join("d.permission", "d")}
801
+ union
802
+ select e.permission from entries e
803
+ where e.level is not null
804
+ and not exists (select 1 from levels l where l.permission = e.permission and l.level = e.level)
805
+ ),
806
+ included as (
807
+ select rp.role, ${current("rp.permission", "rp")} as permission, rp.grant_key, rp.scope, rp.effect
808
+ from ${rp} rp${join("rp.permission", "rp")}
809
+ where rp.role = any(coalesce(p_include, '{}'::text[]))
810
+ ),
811
+ kept as (
812
+ select i.permission, i.grant_key
813
+ from included i
814
+ where i.effect = 'allow'
815
+ and i.scope = p_scope
816
+ and exists (
817
+ select 1 from ceiling c
818
+ where c.role = i.role and c.grant_key = i.grant_key and c.effect = 'allow'
819
+ )
820
+ ),
821
+ wanted as (
822
+ select e.permission from entries e where e.level is null
823
+ union
824
+ select i.permission
825
+ from included i
826
+ where i.effect = 'allow'
827
+ and not (i.scope = p_scope and exists (
828
+ select 1 from ceiling c
829
+ where c.role = i.role and c.grant_key = i.grant_key and c.effect = 'allow'
830
+ ))
831
+ ),
832
+ allowed as (
833
+ select w.permission
834
+ from wanted w
835
+ where w.permission not in (select d.permission from denied d)
836
+ and not exists (select 1 from kept k where k.permission = w.permission)
837
+ ),
838
+ allowed_levels as (
839
+ select e.permission, e.level
840
+ from entries e
841
+ where e.level is not null
842
+ and e.permission not in (select d.permission from denied d)
843
+ and e.permission not in (select a.permission from allowed a)
844
+ and not exists (select 1 from kept k where k.permission = e.permission)
845
+ )
846
+ select k.grant_key from kept k
847
+ where k.permission not in (select d.permission from denied d)
848
+ union
849
+ select i.grant_key from included i
850
+ where i.effect = 'deny' and i.scope = p_scope
851
+ union
852
+ select c.grant_key from ceiling c
853
+ where c.permission in (select a.permission from allowed a)
854
+ union
855
+ select c.grant_key from ceiling c
856
+ join allowed_levels a on a.permission = c.permission
857
+ where c.effect = 'deny' or split_part(c.grant_key, '@', 2) = a.level
858
+ $$;
859
+ revoke execute on function ${keys}(text[], text[], text[], text) from public, anon, authenticated;`;
860
+ }
861
+ function currentKeysSql(array) {
862
+ return `select coalesce(r.key, e.permission) as permission
863
+ from unnest(coalesce(${array}, '{}'::text[])) as e(permission)
864
+ left join renamed r on r.former = e.permission`;
865
+ }
866
+ /**
867
+ * SQL fragments that read a stored former key as its current key inside
868
+ * `permdock_custom_keys`. Without renames they are the plain column and
869
+ * array reads.
870
+ */
871
+ function renamesSql(renames) {
872
+ if (renames.length === 0) return {
873
+ prelude: "",
874
+ permission: (alias) => `${alias}.permission`,
875
+ join: () => "",
876
+ allow: "select unnest(coalesce(p_allow, '{}'::text[])) as permission",
877
+ denied: (alias) => `${alias}.permission = any(coalesce(p_deny, '{}'::text[]))`
878
+ };
879
+ return {
880
+ prelude: `renamed (former, key) as (values ${renames.map(([former, current]) => `(${quoteLiteral(former)}, ${quoteLiteral(current)})`).join(", ")}),
881
+ denied as (
882
+ ${currentKeysSql("p_deny")}
883
+ ),
884
+ `,
885
+ permission: (alias) => `coalesce(r_${alias}.key, ${alias}.permission) as permission`,
886
+ join: (alias) => ` left join renamed r_${alias} on r_${alias}.former = ${alias}.permission`,
887
+ allow: currentKeysSql("p_allow"),
888
+ denied: (alias) => `${alias}.permission in (select d.permission from denied d)`
889
+ };
890
+ }
891
+ /**
892
+ * The catalog reader `permdock_permission_keys()` and the role reader
893
+ * `permdock_role_permissions(p_role, p_scope, p_tenant, p_scope_id)`, both
894
+ * for `authenticated`. A declared role answers from `role_permissions`, which
895
+ * is the catalog. A custom role (`database` mode) answers from the tenant's
896
+ * own rows through `permdock_custom_keys`, only to a member of the tenant or
897
+ * a holder of a `meta.manageRoles` permission for a platform role. The
898
+ * effect is `deny` for a deny the role carries after the ceiling, as
899
+ * `resolveCustomRole` returns it, never for a deny that merely removes an allow.
900
+ */
901
+ function roleReadersSql(ctx, permissions, trustedReaders) {
902
+ const rp = qualified$1(ctx, "role_permissions");
903
+ const reader = qualified$1(ctx, READERS.roles);
904
+ const tenantType = tenantTypeOf(ctx);
905
+ const custom = ctx.customRoles;
906
+ const root = ctx.scopes[0]?.name;
907
+ const database = ctx.authorize === "database";
908
+ const chunks = [];
909
+ if (permissions !== void 0) {
910
+ const catalog = qualified$1(ctx, READERS.keys);
911
+ chunks.push(`-- every declared permission key
912
+ create or replace function ${catalog}()
913
+ returns setof text
914
+ language sql
915
+ stable
916
+ set search_path = ''
917
+ as $$
918
+ select k.permission from unnest(${textArray(permissions.toSorted())}) k(permission) order by 1
919
+ $$;
920
+ revoke execute on function ${catalog}() from public, anon;
921
+ grant execute on function ${catalog}() to authenticated;
922
+
923
+ create or replace function ${catalog}(p_scope text)
924
+ returns setof text
925
+ language sql
926
+ stable
927
+ security definer
928
+ set search_path = ''
929
+ as $$
930
+ select distinct rp.permission
931
+ from ${rp} rp
932
+ where rp.scope = p_scope
933
+ and rp.effect = 'allow'
934
+ and rp.permission = any(${textArray(permissions.toSorted())})
935
+ order by 1
936
+ $$;
937
+ revoke execute on function ${catalog}(text) from public, anon;
938
+ grant execute on function ${catalog}(text) to authenticated;`);
939
+ }
940
+ const declared = ` select distinct rp.permission, rp.effect
941
+ from ${rp} rp
942
+ where rp.role = p_role and rp.scope = p_scope
943
+ order by 1, 2`;
944
+ let body = `begin
945
+ perform p_tenant, p_scope_id; -- only a custom role reads them
946
+ return query
947
+ ${declared};
948
+ end;`;
949
+ let trustedBody = body;
950
+ if (custom !== void 0 && database && root !== void 0) {
951
+ const tenant = qualified$1(ctx, CUSTOM_ROLES.permissions);
952
+ const includes = qualified$1(ctx, CUSTOM_ROLES.includes);
953
+ const keys = qualified$1(ctx, CUSTOM_ROLES.keys);
954
+ const shape = qualified$1(ctx, CUSTOM_ROLES.shape);
955
+ const ids = (helper) => `(select x::text from ${qualified$1(ctx, helper)}() x)`;
956
+ const memberOf = `p_tenant::text in ${ids(memberIdsHelper(root))}
957
+ or ${perScope(ctx, (scope) => scope === root ? "false" : `p_scope_id in ${ids(memberIdsHelper(scope))}`)}`;
958
+ const manage = custom.manage ?? [];
959
+ const platform = manage.length === 0 ? "false" : `exists (
960
+ select 1 from ${rp} m
961
+ where m.effect = 'allow'
962
+ and m.permission = any(${textArray(manage)})
963
+ and ${qualified$1(ctx, HELPERS.has)}(m.grant_key)
964
+ )`;
965
+ const match = `c.tenant_id is not distinct from p_tenant and c.scope = p_scope and c.scope_id is not distinct from p_scope_id and c.role = p_role`;
966
+ const allowEntryOf = custom.levels === true ? "c.permission || coalesce('@' || c.level, '')" : "c.permission";
967
+ const checked = (gate) => `begin
968
+ if p_role = any(${textArray(custom.declared)}) then
969
+ return query
970
+ ${declared};
971
+ return;
972
+ end if;
973
+ perform ${shape}(p_tenant, p_scope, p_scope_id, p_role);${gate}
974
+ return query
975
+ select distinct rp.permission, rp.effect
976
+ from ${keys}(
977
+ array(select ${allowEntryOf} from ${tenant} c where ${match} and c.effect = 'allow'),
978
+ array(select c.permission from ${tenant} c where ${match} and c.effect = 'deny'),
979
+ array(select c.include_role from ${includes} c where ${match}),
980
+ p_scope
981
+ ) k(grant_key)
982
+ join ${rp} rp on rp.grant_key = k.grant_key and rp.scope = p_scope
983
+ order by 1, 2;
984
+ end;`;
985
+ body = checked(`
986
+ if not (${signedIn(ctx)} and (
987
+ ${platform}
988
+ or (p_scope <> 'global' and (${memberOf}))
989
+ )) then
990
+ ${raiseSql(" ", "42501", `'permdock: the caller is not a member of ' || coalesce(p_tenant::text, 'the platform')`, "not-member")}
991
+ end if;`);
992
+ trustedBody = checked("");
993
+ }
994
+ chunks.push(`-- the permission keys a role holds on a scope, with effect allow or deny; a custom role is read for its tenant and, below the first scope, its instance
995
+ create or replace function ${reader}(p_role text, p_scope text, p_tenant ${tenantType} default null, p_scope_id text default null)
996
+ returns table (permission text, effect text)
997
+ language plpgsql
998
+ stable
999
+ security definer
1000
+ set search_path = ''
1001
+ as $$
1002
+ ${body}
1003
+ $$;
1004
+ revoke execute on function ${reader}(text, text, ${tenantType}, text) from public, anon;
1005
+ grant execute on function ${reader}(text, text, ${tenantType}, text) to authenticated;`);
1006
+ const trusted = qualified$1(ctx, READERS.trusted);
1007
+ const signature = `text, text, ${tenantType}, text`;
1008
+ const grants = trustedReaders === void 0 || trustedReaders.length === 0 ? "" : `\ngrant execute on function ${trusted}(${signature}) to ${trustedReaders.map(quoteIdent).join(", ")};`;
1009
+ chunks.push(`create or replace function ${trusted}(p_role text, p_scope text, p_tenant ${tenantType} default null, p_scope_id text default null)
1010
+ returns table (permission text, effect text)
1011
+ language plpgsql
1012
+ stable
1013
+ security definer
1014
+ set search_path = ''
1015
+ as $$
1016
+ ${trustedBody}
1017
+ $$;
1018
+ revoke execute on function ${trusted}(${signature}) from public, anon, authenticated;${grants}`);
1019
+ return chunks.join("\n\n");
1020
+ }
1021
+ /** `expr` read as its current key: a former key maps to the key it was renamed to. */
1022
+ function currentKeyExpr(renames, expr) {
1023
+ if (renames.length === 0) return expr;
1024
+ return `(case ${expr} ${renames.map(([former, current]) => `when ${quoteLiteral(former)} then ${quoteLiteral(current)}`).join(" ")} else ${expr} end)`;
1025
+ }
1026
+ /** `case p_scope when '<scope>' then <sql for scope> ... else false end` over the declared scopes. */
1027
+ function perScope(ctx, sql) {
1028
+ const arms = ctx.scopes.map((scope) => `when ${quoteLiteral(scope.name)} then ${sql(scope.name)}`).join(" ");
1029
+ return arms === "" ? "false" : `(case p_scope ${arms} else false end)`;
1030
+ }
1031
+ function raiseSql(indent, errcode, message, hint) {
1032
+ return `${indent}raise exception using
1033
+ ${indent} errcode = '${errcode}',
1034
+ ${indent} message = ${message},
1035
+ ${indent} hint = ${quoteLiteral(hint)};`;
1036
+ }
1037
+ function hasCustomRoleChecksFor(ctx) {
1038
+ return ctx.authorize === "database" && ctx.customRoles !== void 0 && ctx.scopes.length > 0 && ctx.scopes.every((scope) => hasMemberFor(ctx, scope.name));
1039
+ }
1040
+ function callerFunctionsSql(ctx, custom, root, levelReach, forUser) {
1041
+ const leveled = custom.levels === true;
1042
+ const tenantType = tenantTypeOf(ctx);
1043
+ const rp = qualified$1(ctx, "role_permissions");
1044
+ const keys = qualified$1(ctx, CUSTOM_ROLES.keys);
1045
+ const perms = qualified$1(ctx, CUSTOM_ROLES.permissions);
1046
+ const includes = qualified$1(ctx, CUSTOM_ROLES.includes);
1047
+ const shape = qualified$1(ctx, CUSTOM_ROLES.shape);
1048
+ const beyond = qualified$1(ctx, forUser ? CUSTOM_ROLES.beyondFor : CUSTOM_ROLES.beyond);
1049
+ const guard = qualified$1(ctx, forUser ? CUSTOM_ROLES.guardFor : CUSTOM_ROLES.guard);
1050
+ const user = forUser ? "p_user" : subjectIdSql(ctx);
1051
+ const userParam = forUser ? "p_user uuid, " : "";
1052
+ const userArg = forUser ? "uuid, " : "";
1053
+ const userCall = forUser ? "p_user, " : "";
1054
+ const has = (key) => forUser ? `${qualified$1(ctx, HELPERS.hasFor)}(p_user, ${key})` : `${qualified$1(ctx, HELPERS.has)}(${key})`;
1055
+ const ids = (helper, arg) => `(select x::text from ${qualified$1(ctx, helper)}(${arg}) x)`;
1056
+ const permitted = (scope, key) => forUser ? ids(permittedForHelper(scope), `p_user, ${key}`) : ids(permittedIdsHelper(scope), key);
1057
+ const members = (scope) => forUser ? ids(memberForHelper(scope), "p_user") : ids(memberIdsHelper(scope), "");
1058
+ const heldKey = (key) => `(${has(key)}
1059
+ or (p_scope <> 'global'
1060
+ and (p_tenant::text in ${permitted(root, key)}
1061
+ or ${perScope(ctx, (scope) => scope === root ? "false" : `p_scope_id in ${permitted(scope, key)}`)})))`;
1062
+ const holdsAny = (permissions, held) => permissions.length === 0 ? "false" : `exists (
1063
+ select 1 from ${rp} rp
1064
+ where rp.effect = 'allow'
1065
+ and rp.permission = any(${textArray(permissions)})
1066
+ and ${held("rp.grant_key")}
1067
+ )`;
1068
+ const manageKeys = custom.manage ?? [];
1069
+ const manage = holdsAny(manageKeys, heldKey);
1070
+ const platform = holdsAny(manageKeys, has);
1071
+ const requires = custom.requires === void 0 ? "" : `
1072
+ if not ${holdsAny(custom.requires, heldKey)} then
1073
+ ${raiseSql(" ", "42501", `'permdock: the caller may not manage roles in ' || coalesce(p_tenant::text, 'the platform')`, "manage-roles")}
1074
+ end if;`;
1075
+ const reachRows = levelReach.map(([grantKey, level]) => `(${quoteLiteral(grantKey)}, ${quoteLiteral(level)})`).join(", ");
1076
+ const levelCheck = leveled && reachRows !== "" ? `
1077
+ or exists (
1078
+ select 1
1079
+ from reach x
1080
+ where x.grant_key = r.grant_key
1081
+ and not exists (
1082
+ select 1 from held h
1083
+ join reach o on o.grant_key = h.grant_key
1084
+ where h.permission = r.permission and o.level = x.level
1085
+ )
1086
+ )` : "";
1087
+ const reachCte = leveled && reachRows !== "" ? `,
1088
+ reach (grant_key, level) as (values ${reachRows})` : "";
1089
+ const match = `c.tenant_id is not distinct from p_tenant and c.scope = p_scope and c.scope_id is not distinct from p_scope_id`;
1090
+ const memberOf = `p_tenant::text in ${members(root)}
1091
+ or ${perScope(ctx, (scope) => scope === root ? "false" : `p_scope_id in ${members(scope)}`)}`;
1092
+ return {
1093
+ beyond: `-- custom-role writes: the permission keys of a definition the caller may not hand out in the tenant, as assignablePermissions computes them
1094
+ create or replace function ${beyond}(${userParam}p_tenant ${tenantType}, p_scope text, p_scope_id text, p_allow text[], p_deny text[], p_include text[])
1095
+ returns setof text
1096
+ language plpgsql
1097
+ stable
1098
+ security definer
1099
+ set search_path = ''
1100
+ as $$
1101
+ begin
1102
+ if ${manage} then
1103
+ return;
1104
+ end if;
1105
+ return query
1106
+ with resolved as (
1107
+ select distinct rp.permission, k.key as grant_key
1108
+ from ${keys}(p_allow, p_deny, p_include, p_scope) k(key)
1109
+ join ${rp} rp on rp.grant_key = k.key and rp.effect = 'allow'
1110
+ ),
1111
+ held as (
1112
+ select distinct rp.permission, rp.grant_key
1113
+ from ${rp} rp
1114
+ where rp.effect = 'allow'
1115
+ and rp.permission in (select r.permission from resolved r)
1116
+ and ${heldKey("rp.grant_key")}
1117
+ )${reachCte}
1118
+ select distinct r.permission
1119
+ from resolved r
1120
+ where not exists (select 1 from held h where h.permission = r.permission)${levelCheck};
1121
+ end;
1122
+ $$;
1123
+ revoke execute on function ${beyond}(${userArg}${tenantType}, text, text, text[], text[], text[]) from public, anon, authenticated;`,
1124
+ guard: `-- a custom role the caller may change: membership of the tenant or the instance (a platform role, or a caller holding a manageRoles permission through a global role, needs none), and authority over the stored definition
1125
+ create or replace function ${guard}(${userParam}p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text)
1126
+ returns void
1127
+ language plpgsql
1128
+ stable
1129
+ security definer
1130
+ set search_path = ''
1131
+ as $$
1132
+ declare
1133
+ v_allow text[];
1134
+ v_deny text[];
1135
+ v_include text[];
1136
+ v_beyond text;
1137
+ begin
1138
+ perform ${shape}(p_tenant, p_scope, p_scope_id, p_role);
1139
+ if not (${signedIn(ctx, user)} and (
1140
+ ${platform}
1141
+ or (p_scope <> 'global' and (${memberOf}))
1142
+ )) then
1143
+ ${raiseSql(" ", "42501", `'permdock: the caller is not a member of ' || coalesce(p_tenant::text, 'the platform')`, "not-member")}
1144
+ end if;${requires}
1145
+ select array_agg(${allowEntry(ctx)}) filter (where c.effect = 'allow'),
1146
+ array_agg(c.permission) filter (where c.effect = 'deny')
1147
+ into v_allow, v_deny
1148
+ from ${perms} c
1149
+ where ${match} and c.role = p_role;
1150
+ select array_agg(c.include_role) into v_include
1151
+ from ${includes} c
1152
+ where ${match} and c.role = p_role;
1153
+ select string_agg(b, ', ' order by b) into v_beyond
1154
+ from ${beyond}(${userCall}p_tenant, p_scope, p_scope_id, v_allow, v_deny, v_include) b;
1155
+ if v_beyond is not null then
1156
+ ${raiseSql(" ", "42501", `'permdock: ' || p_role || ' allows ' || v_beyond || ', which the caller may not hand out'`, "not-assignable-by")}
1157
+ end if;
1158
+ end;
1159
+ $$;
1160
+ revoke execute on function ${guard}(${userArg}${tenantType}, text, text, text) from public, anon, authenticated;`
1161
+ };
1162
+ }
1163
+ /**
1164
+ * The functions an application calls to save, rename and delete a custom
1165
+ * role in \`database\` mode, with the rules of \`validateCustomRole\` and
1166
+ * \`assignablePermissions\`: entries inside the ceiling of the role's scope,
1167
+ * includes naming declared roles, and only permissions and levels the caller
1168
+ * may hand out, for the new definition and the stored one alike. A platform
1169
+ * custom role (\`p_scope = 'global'\`, no tenant) is written by a caller who
1170
+ * holds a \`meta.manageRoles\` permission through a global role. The
1171
+ * \`permdock_trusted_*\` variants skip the caller checks and keep the
1172
+ * definition checks; no client role may execute them.
1173
+ */
1174
+ function customRoleWritesSql(ctx, levelReach) {
1175
+ const custom = ctx.customRoles;
1176
+ const root = ctx.scopes[0]?.name;
1177
+ if (custom === void 0 || ctx.authorize !== "database" || root === void 0) return "";
1178
+ const leveled = custom.levels === true;
1179
+ const tenantType = tenantTypeOf(ctx);
1180
+ const rp = qualified$1(ctx, "role_permissions");
1181
+ const ceiling = qualified$1(ctx, CUSTOM_ROLES.ceiling);
1182
+ const perms = qualified$1(ctx, CUSTOM_ROLES.permissions);
1183
+ const includes = qualified$1(ctx, CUSTOM_ROLES.includes);
1184
+ const beyond = qualified$1(ctx, CUSTOM_ROLES.beyond);
1185
+ const guard = qualified$1(ctx, CUSTOM_ROLES.guard);
1186
+ const shape = qualified$1(ctx, CUSTOM_ROLES.shape);
1187
+ const entries = qualified$1(ctx, CUSTOM_ROLES.entries);
1188
+ const renames = Object.entries(custom.renamed ?? {}).toSorted(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
1189
+ const current = (expr) => currentKeyExpr(renames, expr);
1190
+ const known = textArray([...custom.permissions ?? [], ...renames.map(([former]) => former)]);
1191
+ const caller = callerFunctionsSql(ctx, custom, root, levelReach, false);
1192
+ const match = `c.tenant_id is not distinct from p_tenant and c.scope = p_scope and c.scope_id is not distinct from p_scope_id`;
1193
+ const scopes = textArray(ctx.scopes.map((scope) => scope.name));
1194
+ const roleName = (param) => `coalesce(${param}, '') = '' or ${param} = any(${textArray(custom.declared)})`;
1195
+ const levelOf = leveled ? ", nullif(split_part(e, '@', 2), '')" : "";
1196
+ const write = ` delete from ${perms} c where ${match} and c.role = p_role;
1197
+ delete from ${includes} c where ${match} and c.role = p_role;
1198
+ insert into ${perms} (tenant_id, scope, scope_id, role, permission, effect${leveled ? ", level" : ""})
1199
+ select distinct p_tenant, p_scope, p_scope_id, p_role, ${current(leveled ? "split_part(e, '@', 1)" : "e")}, 'allow'${levelOf}
1200
+ from unnest(coalesce(p_allow, '{}'::text[])) e
1201
+ union
1202
+ select distinct p_tenant, p_scope, p_scope_id, p_role, ${current("e")}, 'deny'${leveled ? ", null" : ""}
1203
+ from unnest(coalesce(p_deny, '{}'::text[])) e;
1204
+ insert into ${includes} (tenant_id, scope, scope_id, role, include_role)
1205
+ select distinct p_tenant, p_scope, p_scope_id, p_role, e
1206
+ from unnest(coalesce(p_include, '{}'::text[])) e;`;
1207
+ const move = ` if ${roleName("p_to")} then
1208
+ ${raiseSql(" ", "22023", `'permdock: ' || coalesce(p_to, 'null') || ' is not a custom role name'`, "declared-role")}
1209
+ end if;
1210
+ if exists (select 1 from ${perms} c where ${match} and c.role = p_to)
1211
+ or exists (select 1 from ${includes} c where ${match} and c.role = p_to) then
1212
+ ${raiseSql(" ", "22023", `'permdock: ' || p_to || ' already has grants'`, "role-exists")}
1213
+ end if;
1214
+ update ${perms} c set role = p_to where ${match} and c.role = p_from;
1215
+ update ${includes} c set role = p_to where ${match} and c.role = p_from;`;
1216
+ const remove = ` delete from ${perms} c where ${match} and c.role = p_role;
1217
+ delete from ${includes} c where ${match} and c.role = p_role;`;
1218
+ const writeArgs = `${tenantType}, text, text, text, text[], text[], text[]`;
1219
+ const renameArgs = `${tenantType}, text, text, text, text`;
1220
+ const removeArgs = `${tenantType}, text, text, text`;
1221
+ const fn = (comment, name, params, args, body, member) => `-- ${comment}
1222
+ create or replace function ${qualified$1(ctx, name)}(${params})
1223
+ returns void
1224
+ language plpgsql
1225
+ volatile
1226
+ security definer
1227
+ set search_path = ''
1228
+ as $$
1229
+ ${body}
1230
+ $$;
1231
+ ${member ? `revoke execute on function ${qualified$1(ctx, name)}(${args}) from public, anon;
1232
+ grant execute on function ${qualified$1(ctx, name)}(${args}) to authenticated;` : `revoke execute on function ${qualified$1(ctx, name)}(${args}) from public, anon, authenticated;`}`;
1233
+ const writeParams = `p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text, p_allow text[], p_deny text[], p_include text[]`;
1234
+ const renameParams = `p_tenant ${tenantType}, p_scope text, p_scope_id text, p_from text, p_to text`;
1235
+ const removeParams = `p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text`;
1236
+ return `${caller.beyond}
1237
+
1238
+ -- where a custom role may live: a scope of a tenant, or the platform (scope global, no tenant or instance), under an undeclared name
1239
+ create or replace function ${shape}(p_tenant ${tenantType}, p_scope text, p_scope_id text, p_role text)
1240
+ returns void
1241
+ language plpgsql
1242
+ stable
1243
+ set search_path = ''
1244
+ as $$
1245
+ begin
1246
+ if p_scope = 'global' then
1247
+ if p_tenant is not null or p_scope_id is not null then
1248
+ ${raiseSql(" ", "22023", `'permdock: a platform custom role has no tenant or instance'`, "unknown-scope")}
1249
+ end if;
1250
+ elsif p_tenant is null or not (p_scope = any(${scopes})) then
1251
+ ${raiseSql(" ", "22023", `'permdock: custom roles are held at a scope of a tenant or at global, not ' || coalesce(p_scope, 'null')`, "unknown-scope")}
1252
+ end if;
1253
+ if ${roleName("p_role")} then
1254
+ ${raiseSql(" ", "22023", `'permdock: ' || coalesce(p_role, 'null') || ' is not a custom role name'`, "declared-role")}
1255
+ end if;
1256
+ end;
1257
+ $$;
1258
+ revoke execute on function ${shape}(${tenantType}, text, text, text) from public, anon, authenticated;
1259
+
1260
+ ${caller.guard}
1261
+ ${hasCustomRoleChecksFor(ctx) ? `
1262
+ -- the same checks for a user the caller names: trusted SQL acting later for a stored user; no client role may execute them
1263
+ ${callerFunctionsSql(ctx, custom, root, levelReach, true).beyond}
1264
+
1265
+ ${callerFunctionsSql(ctx, custom, root, levelReach, true).guard}
1266
+ ` : ""}
1267
+ -- the entries of a definition: declared keys and levels inside the ceiling of the scope, and declared includes
1268
+ create or replace function ${entries}(p_scope text, p_allow text[], p_deny text[], p_include text[])
1269
+ returns void
1270
+ language plpgsql
1271
+ stable
1272
+ security definer
1273
+ set search_path = ''
1274
+ as $$
1275
+ declare
1276
+ v_entry text;
1277
+ v_key text;
1278
+ begin
1279
+ foreach v_entry in array coalesce(p_allow, '{}'::text[]) loop
1280
+ v_key := ${current(leveled ? "split_part(v_entry, '@', 1)" : "v_entry")};
1281
+ if not (v_key = any(${known})) then
1282
+ ${raiseSql(" ", "22023", `'permdock: ' || v_entry || ' is not a declared permission'`, "unknown-permission")}
1283
+ end if;
1284
+ if not exists (
1285
+ select 1 from ${ceiling} c
1286
+ where c.scope = p_scope and c.effect = 'allow' and ${current("c.permission")} = v_key
1287
+ ) then
1288
+ ${raiseSql(" ", "22023", `'permdock: ' || v_key || ' is outside the ceiling of ' || p_scope`, "outside-ceiling")}
1289
+ end if;${leveled ? `
1290
+ if strpos(v_entry, '@') > 0 and not exists (
1291
+ select 1 from ${ceiling} c
1292
+ where c.scope = p_scope and c.effect = 'allow' and ${current("c.permission")} = v_key
1293
+ and split_part(c.grant_key, '@', 2) = split_part(v_entry, '@', 2)
1294
+ ) then
1295
+ ${raiseSql(" ", "22023", `'permdock: ' || v_entry || ' names a level the resource does not declare'`, "unknown-level")}
1296
+ end if;` : ""}
1297
+ end loop;
1298
+ foreach v_entry in array coalesce(p_deny, '{}'::text[]) loop
1299
+ if not (v_entry = any(${known})) then
1300
+ ${raiseSql(" ", "22023", `'permdock: ' || v_entry || ' is not a declared permission'`, "unknown-permission")}
1301
+ end if;
1302
+ end loop;
1303
+ foreach v_entry in array coalesce(p_include, '{}'::text[]) loop
1304
+ if not (v_entry = any(${textArray(custom.declared)})) then
1305
+ ${raiseSql(" ", "22023", `'permdock: ' || v_entry || ' is not a declared role'`, "unknown-role")}
1306
+ end if;
1307
+ end loop;
1308
+ select string_agg(distinct ${current("rp.permission")}, ', ') into v_key
1309
+ from ${rp} rp
1310
+ where rp.role = any(coalesce(p_include, '{}'::text[]))
1311
+ and rp.effect = 'allow'
1312
+ and not exists (
1313
+ select 1 from ${ceiling} c
1314
+ where c.scope = p_scope and c.effect = 'allow' and ${current("c.permission")} = ${current("rp.permission")}
1315
+ );
1316
+ if v_key is not null then
1317
+ ${raiseSql(" ", "22023", `'permdock: an included role allows ' || v_key || ', outside the ceiling of ' || p_scope`, "outside-ceiling")}
1318
+ end if;
1319
+ end;
1320
+ $$;
1321
+ revoke execute on function ${entries}(text, text[], text[], text[]) from public, anon, authenticated;
1322
+
1323
+ ${fn("save a custom role: replace its grants and includes after checking each entry against the ceiling and the caller's own permissions", CUSTOM_ROLES.replace, writeParams, writeArgs, `declare
1324
+ v_beyond text;
1325
+ begin
1326
+ perform ${guard}(p_tenant, p_scope, p_scope_id, p_role);
1327
+ perform ${entries}(p_scope, p_allow, p_deny, p_include);
1328
+ select string_agg(b, ', ' order by b) into v_beyond
1329
+ from ${beyond}(p_tenant, p_scope, p_scope_id, p_allow, p_deny, p_include) b;
1330
+ if v_beyond is not null then
1331
+ ${raiseSql(" ", "42501", `'permdock: ' || p_role || ' would allow ' || v_beyond || ', which the caller may not hand out'`, "not-assignable-by")}
1332
+ end if;
1333
+ ${write}
1334
+ end;`, true)}
1335
+
1336
+ ${fn("rename a custom role: move its grants and includes to the new name", CUSTOM_ROLES.rename, renameParams, renameArgs, `begin
1337
+ perform ${guard}(p_tenant, p_scope, p_scope_id, p_from);
1338
+ ${move}
1339
+ end;`, true)}
1340
+
1341
+ ${fn("delete a custom role: remove its grants and includes", CUSTOM_ROLES.remove, removeParams, removeArgs, `begin
1342
+ perform ${guard}(p_tenant, p_scope, p_scope_id, p_role);
1343
+ ${remove}
1344
+ end;`, true)}
1345
+
1346
+ ${fn("save a custom role for a trusted caller (a migration, a job, a backend role granted execute): the definition checks without the caller checks", CUSTOM_ROLES.trustedReplace, writeParams, writeArgs, `begin
1347
+ perform ${shape}(p_tenant, p_scope, p_scope_id, p_role);
1348
+ perform ${entries}(p_scope, p_allow, p_deny, p_include);
1349
+ ${write}
1350
+ end;`, false)}
1351
+
1352
+ ${fn("rename a custom role for a trusted caller", CUSTOM_ROLES.trustedRename, renameParams, renameArgs, `begin
1353
+ perform ${shape}(p_tenant, p_scope, p_scope_id, p_from);
1354
+ ${move}
1355
+ end;`, false)}
1356
+
1357
+ ${fn("delete a custom role for a trusted caller", CUSTOM_ROLES.trustedRemove, removeParams, removeArgs, `begin
1358
+ perform ${shape}(p_tenant, p_scope, p_scope_id, p_role);
1359
+ ${remove}
1360
+ end;`, false)}`;
1361
+ }
1362
+ /** `row.column`, for a trigger's `old` or `new`. */
1363
+ function rowColumn(row, name) {
1364
+ return `${row}.${quoteIdent(name)}`;
1365
+ }
1366
+ /** The custom-role rows of the role a trigger's `v_<prefix>_*` variables name. */
1367
+ function cascadeMatch(prefix) {
1368
+ return `c.tenant_id is not distinct from v_${prefix}_tenant and c.scope = v_${prefix}_scope and c.scope_id is not distinct from v_${prefix}_id and c.role = v_${prefix}_key`;
1369
+ }
1370
+ /**
1371
+ * The trigger on the application's roles table (`rls.customRoleWrites.roles`):
1372
+ * a rename, a move to another tenant, scope or instance, or a delete of a
1373
+ * custom role's row carries its grants and includes along. A signed-in
1374
+ * caller at trigger depth 1 passes the write functions' checks: authority
1375
+ * over the stored definition where it was, and, after a move, membership
1376
+ * and authority where it lands and entries inside that scope's ceiling.
1377
+ * Other paths (a migration, a job, a nested trigger) move the rows as the
1378
+ * function owner.
1379
+ */
1380
+ function customRoleCascadeSql(ctx) {
1381
+ const custom = ctx.customRoles;
1382
+ const table = custom?.table;
1383
+ const root = ctx.scopes[0]?.name;
1384
+ if (custom === void 0 || table === void 0 || root === void 0) return "";
1385
+ const tenantType = tenantTypeOf(ctx);
1386
+ const perms = qualified$1(ctx, CUSTOM_ROLES.permissions);
1387
+ const includes = qualified$1(ctx, CUSTOM_ROLES.includes);
1388
+ const fn = qualified$1(ctx, CUSTOM_ROLES.cascade);
1389
+ const target = quoteTable(table.table.includes(".") ? table.table : `public.${table.table}`);
1390
+ const tenant = (row) => table.tenant === void 0 ? `null::${tenantType}` : `${rowColumn(row, table.tenant)}::${tenantType}`;
1391
+ const scope = (row) => table.scope === void 0 ? `case when ${tenant(row)} is null then 'global' else ${quoteLiteral(root)} end` : `case when ${tenant(row)} is null then 'global' else ${rowColumn(row, table.scope)}::text end`;
1392
+ const id = (row) => table.id === void 0 ? "null::text" : `${rowColumn(row, table.id)}::text`;
1393
+ const skipped = (row) => table.skip === void 0 ? "false" : `coalesce(${rowColumn(row, table.skip)}, false)`;
1394
+ const guard = qualified$1(ctx, CUSTOM_ROLES.guard);
1395
+ const entries = qualified$1(ctx, CUSTOM_ROLES.entries);
1396
+ const allowEntryOf = custom.levels === true ? "c.permission || coalesce('@' || c.level, '')" : "c.permission";
1397
+ return `-- the application's roles table: renames, moves and deletes of a custom role carry its grants and includes
1398
+ create or replace function ${fn}()
1399
+ returns trigger
1400
+ language plpgsql
1401
+ volatile
1402
+ security definer
1403
+ set search_path = ''
1404
+ as $$
1405
+ declare
1406
+ v_old_tenant ${tenantType} := ${tenant("old")};
1407
+ v_old_scope text := ${scope("old")};
1408
+ v_old_id text := ${id("old")};
1409
+ v_old_key text := ${rowColumn("old", table.key)}::text;
1410
+ v_new_tenant ${tenantType};
1411
+ v_new_scope text;
1412
+ v_new_id text;
1413
+ v_new_key text;
1414
+ v_checked boolean := ${signedIn(ctx)} and pg_trigger_depth() = 1;
1415
+ v_allow text[];
1416
+ v_deny text[];
1417
+ v_include text[];
1418
+ begin
1419
+ if ${skipped("old")} then
1420
+ return null;
1421
+ end if;
1422
+ if tg_op = 'UPDATE' and not ${skipped("new")} then
1423
+ v_new_tenant := ${tenant("new")};
1424
+ v_new_scope := ${scope("new")};
1425
+ v_new_id := ${id("new")};
1426
+ v_new_key := ${rowColumn("new", table.key)}::text;
1427
+ if v_new_key = v_old_key
1428
+ and v_new_tenant is not distinct from v_old_tenant
1429
+ and v_new_scope = v_old_scope
1430
+ and v_new_id is not distinct from v_old_id then
1431
+ return null;
1432
+ end if;
1433
+ end if;
1434
+ if not exists (select 1 from ${perms} c where ${cascadeMatch("old")})
1435
+ and not exists (select 1 from ${includes} c where ${cascadeMatch("old")}) then
1436
+ return null;
1437
+ end if;
1438
+ if v_checked then
1439
+ perform ${guard}(v_old_tenant, v_old_scope, v_old_id, v_old_key);
1440
+ end if;
1441
+ if v_new_key is null then
1442
+ delete from ${perms} c where ${cascadeMatch("old")};
1443
+ delete from ${includes} c where ${cascadeMatch("old")};
1444
+ return null;
1445
+ end if;
1446
+ if exists (select 1 from ${perms} c where ${cascadeMatch("new")})
1447
+ or exists (select 1 from ${includes} c where ${cascadeMatch("new")}) then
1448
+ ${raiseSql(" ", "22023", `'permdock: ' || v_new_key || ' already has grants'`, "role-exists")}
1449
+ end if;
1450
+ update ${perms} c set tenant_id = v_new_tenant, scope = v_new_scope, scope_id = v_new_id, role = v_new_key where ${cascadeMatch("old")};
1451
+ update ${includes} c set tenant_id = v_new_tenant, scope = v_new_scope, scope_id = v_new_id, role = v_new_key where ${cascadeMatch("old")};
1452
+ if v_checked then
1453
+ perform ${guard}(v_new_tenant, v_new_scope, v_new_id, v_new_key);
1454
+ select array_agg(${allowEntryOf}) filter (where c.effect = 'allow'),
1455
+ array_agg(c.permission) filter (where c.effect = 'deny')
1456
+ into v_allow, v_deny
1457
+ from ${perms} c
1458
+ where ${cascadeMatch("new")};
1459
+ select array_agg(c.include_role) into v_include
1460
+ from ${includes} c
1461
+ where ${cascadeMatch("new")};
1462
+ perform ${entries}(v_new_scope, v_allow, v_deny, v_include);
1463
+ end if;
1464
+ return null;
1465
+ end;
1466
+ $$;
1467
+ revoke execute on function ${fn}() from public, anon, authenticated;
1468
+ drop trigger if exists "permdock_custom_role_cascade" on ${target};
1469
+ create trigger "permdock_custom_role_cascade"
1470
+ after update or delete on ${target}
1471
+ for each row execute function ${fn}();
1472
+ `;
1473
+ }
1474
+ //#endregion
1475
+ //#region src/cli/rls-helpers.ts
1476
+ /** The helper `--capabilities` adds: ids of one resource a link capability claim reaches. Part of the SQL contract. */
1477
+ const CAPABILITIES = { ids: "permdock_capability_ids" };
1478
+ /**
1479
+ * The policy-side call for a grant key. Every form is uncorrelated, so
1480
+ * Postgres runs the helper once per statement (an InitPlan, or a hashed
1481
+ * SubPlan for `in`), never once per row.
1482
+ */
1483
+ function accessSql(ctx, scope, grantKey, column) {
1484
+ const key = quoteLiteral(grantKey);
1485
+ if (scope === "global") return `(select ${qualified$1(ctx, HELPERS.has)}(${key}))`;
1486
+ if (column === void 0) throw new Error(`PermDock CLI: ${scope}-scoped grant needs definePolicy({ scopes.${scope} })`);
1487
+ return `${quoteIdent(column)} in (select ${qualified$1(ctx, permittedIdsHelper(scope))}(${key}))`;
1488
+ }
1489
+ /**
1490
+ * The `anon` branch access for a resource-scoped grant reached through a link
1491
+ * capability: the row's `field` holds an id the capability claim names for
1492
+ * `resource`, `role` and `permission`. Uncorrelated, so it runs once per
1493
+ * statement; the column is compared as text because the claim holds text.
1494
+ */
1495
+ function capabilityAccessSql(ctx, field, resource, role, permission) {
1496
+ const args = [
1497
+ resource,
1498
+ role,
1499
+ permission
1500
+ ].map(quoteLiteral).join(", ");
1501
+ return `${quoteIdent(field)}::text in (select ${qualified$1(ctx, CAPABILITIES.ids)}(${args}))`;
1502
+ }
1503
+ function capabilitiesSql(ctx) {
1504
+ if (ctx.capabilities !== true) return "";
1505
+ const fn = qualified$1(ctx, CAPABILITIES.ids);
1506
+ return `-- link capabilities: the capability claim exchangeCapability mints (role anon, short-lived)
1507
+ create or replace function ${fn}(p_resource text, p_role text, p_permission text)
1508
+ returns setof text
1509
+ language sql
1510
+ stable
1511
+ set search_path = ''
1512
+ as $$
1513
+ select c -> 'on' ->> 'id'
1514
+ from (select ${subjectClaimJsonSql(ctx, "capability")} as c) capability
1515
+ where jsonb_typeof(c) = 'object'
1516
+ and c ->> 'v' = '1'
1517
+ and c ->> 'holder' = 'link'
1518
+ and c -> 'on' ->> 'resource' = p_resource
1519
+ and jsonb_typeof(c -> 'roles') = 'array'
1520
+ and c -> 'roles' @> jsonb_build_array(p_role)
1521
+ and (c -> 'permissions' is null or c -> 'permissions' @> jsonb_build_array(p_permission))
1522
+ and jsonb_typeof(c -> 'expiresAt') = 'number'
1523
+ and (c ->> 'expiresAt')::numeric > extract(epoch from now())
1524
+ $$;
1525
+ revoke execute on function ${fn}(text, text, text) from public;
1526
+ grant execute on function ${fn}(text, text, text) to anon, authenticated;`;
1527
+ }
1528
+ function userIdSql(ctx, anonExecute) {
1529
+ const fn = userIdHelperSql(ctx);
1530
+ return `-- the caller's user id: the sub of request.jwt.claims, or null when it is empty or absent
1531
+ create or replace function ${fn}()
1532
+ returns uuid
1533
+ language sql
1534
+ stable
1535
+ set search_path = ''
1536
+ as $$
1537
+ select nullif(
1538
+ nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub',
1539
+ ''
1540
+ )::uuid
1541
+ $$;
1542
+ ${anonExecute ? `revoke execute on function ${fn}() from public;
1543
+ grant execute on function ${fn}() to anon, authenticated;` : `revoke execute on function ${fn}() from public, anon;
1544
+ grant execute on function ${fn}() to authenticated;`}`;
1545
+ }
1546
+ function membershipTable(name) {
1547
+ return quoteTable(name.includes(".") ? name : `public.${name}`);
1548
+ }
1549
+ function activeTenant(ctx) {
1550
+ return `nullif(${subjectClaimSql(ctx, ctx.tenantClaim)}, '')`;
1551
+ }
1552
+ function keyTenantLine(ctx, scope, tenant) {
1553
+ const keyed = keyTenantSql(ctx, underRoot(ctx, scope) ? tenant : void 0);
1554
+ return keyed === void 0 ? "" : `\n and ${keyed}`;
1555
+ }
1556
+ /** Whether the helper for `scope` narrows to the tenant claim: unless `rls.tenants` is `'all'`, when the first scope is on its chain. */
1557
+ function narrowsTo(ctx, scope) {
1558
+ return ctx.tenants !== "all" && underRoot(ctx, scope);
1559
+ }
1560
+ /** Whether the active tenant narrows memberships of `scope`: the first scope is on its chain. */
1561
+ function underRoot(ctx, scope) {
1562
+ const root = ctx.scopes[0]?.name;
1563
+ let current = ctx.scopes.find((item) => item.name === scope);
1564
+ const seen = /* @__PURE__ */ new Set();
1565
+ while (current !== void 0 && !seen.has(current.name)) {
1566
+ if (current.name === root) return true;
1567
+ seen.add(current.name);
1568
+ const parent = current.within;
1569
+ current = parent === void 0 ? void 0 : ctx.scopes.find((item) => item.name === parent);
1570
+ }
1571
+ return false;
1572
+ }
1573
+ /** `and exists (...)` lines for an active user; empty without `rls.suspension.users`. */
1574
+ function userActive(ctx, indent, user) {
1575
+ return activeUserSql(ctx, user).map((part) => `${indent}and ${part}`);
1576
+ }
1577
+ /** `and exists (...)` lines for every suspendable instance on the chain of `scope`'s membership. */
1578
+ function instancesActive(ctx, scope, idOf, indent, permission) {
1579
+ return activeInstancesSql(ctx, scope, idOf, permission).map((part) => `${indent}and ${part}`);
1580
+ }
1581
+ function roleRows(ctx) {
1582
+ const claim = ctx.roleClaim ?? "user_role";
1583
+ switch (ctx.dialect) {
1584
+ case "guc": return `unnest(string_to_array(nullif(current_setting(${quoteLiteral(`${ctx.gucPrefix}.${claim}`)}, true), ''), ',')) r(role)`;
1585
+ case "supabase":
1586
+ case "neon": {
1587
+ const raw = subjectClaimJsonSql(ctx, claim);
1588
+ const value = ctx.dialect === "supabase" ? `coalesce(nullif(${raw}, 'null'::jsonb), (select auth.jwt()) -> 'app_metadata' -> ${quoteLiteral(claim)})` : raw;
1589
+ return `jsonb_array_elements_text(
1590
+ case jsonb_typeof(${value})
1591
+ when 'array' then ${value}
1592
+ when 'string' then jsonb_build_array(${value})
1593
+ else '[]'::jsonb
1594
+ end
1595
+ ) r(role)`;
1596
+ }
1597
+ default: return ctx.dialect;
1598
+ }
1599
+ }
1600
+ function membershipRows(ctx) {
1601
+ const raw = subjectClaimJsonSql(ctx, "memberships");
1602
+ const value = ctx.dialect === "supabase" ? `coalesce(${raw}, (select auth.jwt()) -> 'app_metadata' -> 'memberships')` : raw;
1603
+ return `jsonb_array_elements(
1604
+ case jsonb_typeof(${value}) when 'array' then ${value} else '[]'::jsonb end
1605
+ ) m
1606
+ cross join lateral jsonb_array_elements_text(
1607
+ case jsonb_typeof(m -> 'roles') when 'array' then m -> 'roles' else '[]'::jsonb end
1608
+ ) r(role)`;
1609
+ }
1610
+ function andLine(indent, condition) {
1611
+ return condition === void 0 ? "" : `\n${indent}and ${condition}`;
1612
+ }
1613
+ /** `rls.roles`, or the generated `user_roles (user_id, role)`, aliased `ur`. */
1614
+ function globalRoleRows(ctx) {
1615
+ return ctx.roles === void 0 ? {
1616
+ from: `${qualified$1(ctx, "user_roles")} ur`,
1617
+ userSql: "ur.user_id",
1618
+ roleSql: "ur.role::text"
1619
+ } : globalRoleSource(ctx.roles, "public", "ur");
1620
+ }
1621
+ function customKeysJoin(ctx, scope, allows, denies, includes) {
1622
+ return ` cross join lateral ${qualified$1(ctx, CUSTOM_ROLES.keys)}(
1623
+ ${allows},
1624
+ ${denies},
1625
+ ${includes},
1626
+ ${quoteLiteral(scope)}
1627
+ ) ck(grant_key)`;
1628
+ }
1629
+ function hasSetBody(ctx) {
1630
+ const rp = qualified$1(ctx, "role_permissions");
1631
+ const active = userActive(ctx, " ").map((line) => `\n${line}`).join("");
1632
+ const custom = ctx.customRoles;
1633
+ if (ctx.authorize === "database") {
1634
+ const ur = globalRoleRows(ctx);
1635
+ const declared = ` select rp.grant_key
1636
+ from ${ur.from}
1637
+ join ${rp} rp on rp.role = ${ur.roleSql}
1638
+ where ${ur.userSql} = ${subjectIdSql(ctx)}
1639
+ and rp.scope = 'global'${andLine(" ", globalKindFilterSql(ctx, ur.roleSql))}${active}`;
1640
+ if (custom === void 0) return declared;
1641
+ const match = `c.tenant_id is null and c.scope = 'global' and c.scope_id is null and c.role = ${ur.roleSql}`;
1642
+ const rows = (source, value, extra) => `array(select c.${value} from ${qualified$1(ctx, source)} c where ${match}${extra})`;
1643
+ return `${declared}
1644
+ union
1645
+ select ck.grant_key
1646
+ from ${ur.from}
1647
+ ${customKeysJoin(ctx, "global", rows(CUSTOM_ROLES.permissions, allowEntry(ctx), " and c.effect = 'allow'"), rows(CUSTOM_ROLES.permissions, "permission", " and c.effect = 'deny'"), rows(CUSTOM_ROLES.includes, "include_role", ""))}
1648
+ where ${ur.userSql} = ${subjectIdSql(ctx)}
1649
+ and not (${ur.roleSql} = any(${textArray(custom.declared)}))${active}`;
1650
+ }
1651
+ const declared = ` select rp.grant_key
1652
+ from ${roleRows(ctx)}
1653
+ join ${rp} rp on rp.role = r.role
1654
+ where ${signedIn(ctx)}
1655
+ and rp.scope = 'global'${andLine(" ", globalKindFilterSql(ctx, "r.role"))}${active}`;
1656
+ if (custom === void 0) return declared;
1657
+ const claim = subjectClaimJsonSql(ctx, GLOBAL_GRANTS_CLAIM);
1658
+ return `${declared}
1659
+ union
1660
+ select ck.grant_key
1661
+ from ${roleRows(ctx)}
1662
+ cross join lateral (select ${claim} -> r.role as g) cg
1663
+ ${customKeysJoin(ctx, "global", claimEntries("left(e, 1) not in ('-', '@')", "e"), claimEntries("left(e, 1) = '-'", "substr(e, 2)"), claimEntries("left(e, 1) = '@'", "substr(e, 2)"))}
1664
+ where ${signedIn(ctx)}
1665
+ and jsonb_typeof(cg.g) = 'array'
1666
+ and not (r.role = any(${textArray(custom.declared)}))${active}`;
1667
+ }
1668
+ function hasBody(ctx) {
1669
+ if (ctx.grantSet === true) return hasSetBody(ctx);
1670
+ const rp = qualified$1(ctx, "role_permissions");
1671
+ const active = userActive(ctx, " ").map((line) => `\n${line}`).join("");
1672
+ const custom = ctx.customRoles;
1673
+ if (ctx.authorize === "database") {
1674
+ const ur = globalRoleRows(ctx);
1675
+ const declared = ` select exists (
1676
+ select 1
1677
+ from ${ur.from}
1678
+ join ${rp} rp on rp.role = ${ur.roleSql}
1679
+ where ${ur.userSql} = ${subjectIdSql(ctx)}
1680
+ and rp.grant_key = p_grant
1681
+ and rp.scope = 'global'${andLine(" ", globalKindFilterSql(ctx, ur.roleSql))}${active}
1682
+ )`;
1683
+ if (custom === void 0) return declared;
1684
+ const match = `c.tenant_id is null and c.scope = 'global' and c.scope_id is null and c.role = ${ur.roleSql}`;
1685
+ const rows = (source, value, extra) => `array(select c.${value} from ${qualified$1(ctx, source)} c where ${match}${extra})`;
1686
+ return `${declared}
1687
+ or exists (
1688
+ select 1
1689
+ from ${ur.from}
1690
+ where ${ur.userSql} = ${subjectIdSql(ctx)}
1691
+ and not (${ur.roleSql} = any(${textArray(custom.declared)}))${active}
1692
+ ${customKeysSql(ctx, "global", rows(CUSTOM_ROLES.permissions, allowEntry(ctx), " and c.effect = 'allow'"), rows(CUSTOM_ROLES.permissions, "permission", " and c.effect = 'deny'"), rows(CUSTOM_ROLES.includes, "include_role", "")).trimStart()}
1693
+ )`;
1694
+ }
1695
+ const declared = ` select ${signedIn(ctx)} and exists (
1696
+ select 1
1697
+ from ${roleRows(ctx)}
1698
+ join ${rp} rp on rp.role = r.role
1699
+ where rp.grant_key = p_grant
1700
+ and rp.scope = 'global'${andLine(" ", globalKindFilterSql(ctx, "r.role"))}${active}
1701
+ )`;
1702
+ if (custom === void 0) return declared;
1703
+ const claim = subjectClaimJsonSql(ctx, GLOBAL_GRANTS_CLAIM);
1704
+ return `${declared}
1705
+ or (${signedIn(ctx)} and exists (
1706
+ select 1
1707
+ from ${roleRows(ctx)}
1708
+ cross join lateral (select ${claim} -> r.role as g) cg
1709
+ where jsonb_typeof(cg.g) = 'array'
1710
+ and not (r.role = any(${textArray(custom.declared)}))${active}
1711
+ ${customKeysSql(ctx, "global", claimEntries("left(e, 1) not in ('-', '@')", "e"), claimEntries("left(e, 1) = '-'", "substr(e, 2)"), claimEntries("left(e, 1) = '@'", "substr(e, 2)")).trimStart()}
1712
+ ))`;
1713
+ }
1714
+ /** The claim `jwt` mode reads platform custom roles from: `customRoleClaim(globalRoles)`. */
1715
+ const GLOBAL_GRANTS_CLAIM = "role_grants";
1716
+ function memberColumn(name) {
1717
+ return `m.${quoteIdent(name)}`;
1718
+ }
1719
+ function disabledColumn(table) {
1720
+ return table.disabledAt === void 0 ? void 0 : memberColumn(table.disabledAt);
1721
+ }
1722
+ function claimKeptLines(ctx, indent, permission) {
1723
+ return disabledKeep(ctx).length === 0 ? [] : [`${indent}and ${keptRowSql("m -> 'keep'", permission)}`];
1724
+ }
1725
+ /** Entries of a compact custom-role claim (`cg.g`) that match `where`. */
1726
+ function claimEntries(where, value) {
1727
+ return `array(select ${value} from jsonb_array_elements_text(cg.g) e where ${where})`;
1728
+ }
1729
+ /** `p_grant in (select permdock_custom_keys(allows, denies, includes, scope))`. */
1730
+ function customKeysSql(ctx, scope, allows, denies, includes) {
1731
+ return ` and p_grant in (select ${qualified$1(ctx, CUSTOM_ROLES.keys)}(
1732
+ ${allows},
1733
+ ${denies},
1734
+ ${includes},
1735
+ ${quoteLiteral(scope)}
1736
+ ))`;
1737
+ }
1738
+ function tableBody(ctx, scope, type) {
1739
+ const mapped = scopeTable(ctx, scope);
1740
+ if (mapped === void 0) return ` select null::${type} where false -- no ${scope} memberships table configured`;
1741
+ const { table, column, tenantColumn } = mapped;
1742
+ const set = ctx.grantSet === true;
1743
+ const filtersFor = (grant) => {
1744
+ const filters = [` where ${memberColumn(table.user)} = ${subjectIdSql(ctx)}`];
1745
+ if (table.expiresAt !== void 0) {
1746
+ const expires = memberColumn(table.expiresAt);
1747
+ filters.push(` and (${expires} is null or ${expires} > now())`);
1748
+ }
1749
+ filters.push(...activeMembershipSql(ctx, disabledColumn(table), grantPermissionSql(grant)).map((part) => ` and ${part}`));
1750
+ if (tenantColumn !== void 0 && ctx.tenants !== "all") filters.push(` and (${activeTenant(ctx)} is null or ${memberColumn(tenantColumn)}::text = ${activeTenant(ctx)})`);
1751
+ const keyed = keyTenantSql(ctx, tenantColumn === void 0 ? void 0 : memberColumn(tenantColumn));
1752
+ if (keyed !== void 0) filters.push(` and ${keyed}`);
1753
+ filters.push(...userActive(ctx, " "), ...instancesActive(ctx, scope, (name) => {
1754
+ const held = scopeColumn(table, ctx.scopes, name);
1755
+ return held === void 0 ? void 0 : memberColumn(held);
1756
+ }, " ", grantPermissionSql(grant)));
1757
+ return filters;
1758
+ };
1759
+ const filters = filtersFor(set ? "rp.grant_key" : "p_grant");
1760
+ const [owner, ...rest] = filters;
1761
+ const role = memberRoleOf(table, "m", " ");
1762
+ const kind = kindFilterSql(ctx, role.sql, memberVia(table));
1763
+ const lines = [
1764
+ ` select${role.lateral ? " distinct" : ""} ${memberColumn(column)}::${type}${set ? ", rp.grant_key" : ""}`,
1765
+ ` from ${membershipTable(table.table)} m${role.join}`,
1766
+ ` join ${qualified$1(ctx, "role_permissions")} rp on rp.role = ${role.sql}`,
1767
+ owner ?? "",
1768
+ ...set ? [] : [" and rp.grant_key = p_grant"],
1769
+ ` and rp.scope = ${quoteLiteral(scope)}`,
1770
+ ...kind === void 0 ? [] : [` and ${kind}`],
1771
+ ...rest
1772
+ ];
1773
+ const custom = ctx.customRoles;
1774
+ if (custom === void 0) return lines.join("\n");
1775
+ const match = [
1776
+ `c.tenant_id::text = ${memberColumn(tenantColumn ?? column)}::text`,
1777
+ `c.scope = ${quoteLiteral(scope)}`,
1778
+ `(c.scope_id is null or c.scope_id = ${memberColumn(column)}::text)`,
1779
+ `c.role = ${role.sql}`
1780
+ ].join(" and ");
1781
+ const rows = (source, value, extra) => `array(select c.${value} from ${qualified$1(ctx, source)} c where ${match}${extra})`;
1782
+ const entries = [
1783
+ rows(CUSTOM_ROLES.permissions, allowEntry(ctx), " and c.effect = 'allow'"),
1784
+ rows(CUSTOM_ROLES.permissions, "permission", " and c.effect = 'deny'"),
1785
+ rows(CUSTOM_ROLES.includes, "include_role", "")
1786
+ ];
1787
+ if (set) return [
1788
+ ...lines,
1789
+ " union",
1790
+ ` select ${memberColumn(column)}::${type}, ck.grant_key`,
1791
+ ` from ${membershipTable(table.table)} m${role.join}`,
1792
+ customKeysJoin(ctx, scope, ...entries),
1793
+ ...filtersFor("ck.grant_key"),
1794
+ ` and not (${role.sql} = any(${textArray(custom.declared)}))`
1795
+ ].join("\n");
1796
+ return [
1797
+ ...lines,
1798
+ " union",
1799
+ ` select ${memberColumn(column)}::${type}`,
1800
+ ` from ${membershipTable(table.table)} m${role.join}`,
1801
+ ...filters,
1802
+ ` and not (${role.sql} = any(${textArray(custom.declared)}))`,
1803
+ customKeysSql(ctx, scope, ...entries)
1804
+ ].join("\n");
1805
+ }
1806
+ /** The membership's instance of the first scope, from the canonical claim. */
1807
+ function claimTenant(ctx, scope) {
1808
+ const root = rootName(ctx);
1809
+ return scope === root ? `m ->> 'id'` : `m -> 'within' ->> ${quoteLiteral(root)}`;
1810
+ }
1811
+ function claimBody(ctx, scope, type) {
1812
+ const set = ctx.grantSet === true;
1813
+ const narrow = narrowsTo(ctx, scope) ? `
1814
+ and (${activeTenant(ctx)} is null or ${claimTenant(ctx, scope)} = ${activeTenant(ctx)})` : "";
1815
+ const filtersFor = (grant) => ` and m ->> 'scope' = ${quoteLiteral(scope)}
1816
+ and m ->> 'id' is not null${narrow}${keyTenantLine(ctx, scope, claimTenant(ctx, scope))}
1817
+ and case jsonb_typeof(m -> 'expiresAt')
1818
+ when 'number' then (m ->> 'expiresAt')::numeric > extract(epoch from now())
1819
+ else true
1820
+ end${[
1821
+ ...claimKeptLines(ctx, " ", grantPermissionSql(grant)),
1822
+ ...userActive(ctx, " "),
1823
+ ...instancesActive(ctx, scope, (name) => name === scope ? `m ->> 'id'` : `m -> 'within' ->> ${quoteLiteral(name)}`, " ", grantPermissionSql(grant))
1824
+ ].map((line) => `\n${line}`).join("")}`;
1825
+ const filters = filtersFor(set ? "rp.grant_key" : "p_grant");
1826
+ const declared = ` select (m ->> 'id')::${type}${set ? ", rp.grant_key" : ""}
1827
+ from ${membershipRows(ctx)}
1828
+ join ${qualified$1(ctx, "role_permissions")} rp on rp.role = r.role
1829
+ where ${signedIn(ctx)}${set ? "" : "\n and rp.grant_key = p_grant"}
1830
+ and rp.scope = ${quoteLiteral(scope)}${andLine(" ", kindFilterSql(ctx, "r.role", "m ->> 'via'"))}
1831
+ ${filters}`;
1832
+ const custom = ctx.customRoles;
1833
+ if (custom === void 0) return declared;
1834
+ if (set) return `${declared}
1835
+ union
1836
+ select (m ->> 'id')::${type}, ck.grant_key
1837
+ from ${membershipRows(ctx)}
1838
+ cross join lateral (select m -> 'grants' -> r.role as g) cg
1839
+ ${customKeysJoin(ctx, scope, claimEntries("left(e, 1) not in ('-', '@')", "e"), claimEntries("left(e, 1) = '-'", "substr(e, 2)"), claimEntries("left(e, 1) = '@'", "substr(e, 2)"))}
1840
+ where ${signedIn(ctx)}
1841
+ and jsonb_typeof(cg.g) = 'array'
1842
+ and not (r.role = any(${textArray(custom.declared)}))
1843
+ ${filtersFor("ck.grant_key")}`;
1844
+ return `${declared}
1845
+ union
1846
+ select (m ->> 'id')::${type}
1847
+ from ${membershipRows(ctx)}
1848
+ cross join lateral (select m -> 'grants' -> r.role as g) cg
1849
+ where ${signedIn(ctx)}
1850
+ and jsonb_typeof(cg.g) = 'array'
1851
+ and not (r.role = any(${textArray(custom.declared)}))
1852
+ ${filters}
1853
+ ${customKeysSql(ctx, scope, claimEntries("left(e, 1) not in ('-', '@')", "e"), claimEntries("left(e, 1) = '-'", "substr(e, 2)"), claimEntries("left(e, 1) = '@'", "substr(e, 2)"))}`;
1854
+ }
1855
+ /**
1856
+ * The rows the membership sources select for the subject, one per instance
1857
+ * (`scope`, `id`, `within`, `roles`, `via`), with each source's own expiry
1858
+ * and suspension filters: the statements the token hook runs.
1859
+ */
1860
+ function sourcesKeep(sources) {
1861
+ return sources.some((source) => source.sql.keeps);
1862
+ }
1863
+ function sourceRows(sources) {
1864
+ const keep = sourcesKeep(sources);
1865
+ return sources.map((source, index) => source.sql.select(sourceUser(index), keep).replaceAll(/^/gmu, " ")).join("\n union all\n");
1866
+ }
1867
+ function sourceUser(index) {
1868
+ return `v_user_${String(index)}`;
1869
+ }
1870
+ function sqlBody(sql) {
1871
+ return {
1872
+ sql,
1873
+ vars: []
1874
+ };
1875
+ }
1876
+ function sourcesBodyOf(sql, sources, user) {
1877
+ return {
1878
+ sql,
1879
+ vars: sources.map((source, index) => `${sourceUser(index)} ${source.sql.userType} := ${user};`)
1880
+ };
1881
+ }
1882
+ /** `language sql`, or `plpgsql` returning the query when the body declares variables. */
1883
+ function functionBody(body) {
1884
+ if (body.vars.length === 0) return `language sql
1885
+ stable
1886
+ security definer
1887
+ set search_path = ''
1888
+ as $$
1889
+ ${body.sql}
1890
+ $$;`;
1891
+ return `language plpgsql
1892
+ stable
1893
+ security definer
1894
+ set search_path = ''
1895
+ as $$
1896
+ declare
1897
+ ${body.vars.map((line) => ` ${line}`).join("\n")}
1898
+ begin
1899
+ return query
1900
+ ${body.sql};
1901
+ end;
1902
+ $$;`;
1903
+ }
1904
+ /**
1905
+ * `ms.id` for the scope itself and `ms.within ->> name` for an ancestor. The
1906
+ * alias is not `s`, which `activeRowSql` binds inside its `exists`.
1907
+ */
1908
+ function sourceIdOf(scope) {
1909
+ return (name) => name === scope ? "ms.id" : `ms.within ->> ${quoteLiteral(name)}`;
1910
+ }
1911
+ function sourceFilters(ctx, scope, user = subjectIdSql(ctx), permission, keeps = false) {
1912
+ return [
1913
+ ...keeps ? [` and ${keptRowSql("ms.keep", permission)}`] : [],
1914
+ ...userActive(ctx, " ", user),
1915
+ ...instancesActive(ctx, scope, sourceIdOf(scope), " ", permission)
1916
+ ].map((line) => `\n${line}`).join("");
1917
+ }
1918
+ function sourcesBody(ctx, scope, type) {
1919
+ const root = rootName(ctx);
1920
+ const tenant = sourceIdOf(scope)(root);
1921
+ const narrow = narrowsTo(ctx, scope) ? `\n and (${activeTenant(ctx)} is null or ${tenant} = ${activeTenant(ctx)})${keyTenantLine(ctx, scope, tenant)}` : keyTenantLine(ctx, scope, tenant);
1922
+ const sources = scopeSources(ctx, scope);
1923
+ const set = ctx.grantSet === true;
1924
+ const rows = ` from (
1925
+ ${sourceRows(sources)}
1926
+ ) ms
1927
+ cross join lateral jsonb_array_elements_text(
1928
+ case jsonb_typeof(ms.roles) when 'array' then ms.roles else '[]'::jsonb end
1929
+ ) r(role)`;
1930
+ const declared = ` select (ms.id)::${type}${set ? ", rp.grant_key" : ""}
1931
+ ${rows}
1932
+ join ${qualified$1(ctx, "role_permissions")} rp on rp.role = r.role
1933
+ where ${signedIn(ctx)}
1934
+ and ms.scope = ${quoteLiteral(scope)}${set ? "" : "\n and rp.grant_key = p_grant"}
1935
+ and rp.scope = ${quoteLiteral(scope)}${andLine(" ", kindFilterSql(ctx, "r.role", "ms.via"))}${narrow}${sourceFilters(ctx, scope, subjectIdSql(ctx), grantPermissionSql(set ? "rp.grant_key" : "p_grant"), sourcesKeep(sources))}`;
1936
+ const custom = ctx.customRoles;
1937
+ if (custom === void 0) return sourcesBodyOf(declared, sources, subjectIdSql(ctx));
1938
+ const match = [
1939
+ `c.tenant_id::text = (${tenant})::text`,
1940
+ `c.scope = ${quoteLiteral(scope)}`,
1941
+ "(c.scope_id is null or c.scope_id = (ms.id)::text)",
1942
+ "c.role = r.role"
1943
+ ].join(" and ");
1944
+ const entries = (source, value, extra) => `array(select c.${value} from ${qualified$1(ctx, source)} c where ${match}${extra})`;
1945
+ if (set) return sourcesBodyOf(`${declared}
1946
+ union
1947
+ select (ms.id)::${type}, ck.grant_key
1948
+ ${rows}
1949
+ ${customKeysJoin(ctx, scope, entries(CUSTOM_ROLES.permissions, "permission", " and c.effect = 'allow'"), entries(CUSTOM_ROLES.permissions, "permission", " and c.effect = 'deny'"), entries(CUSTOM_ROLES.includes, "include_role", ""))}
1950
+ where ${signedIn(ctx)}
1951
+ and ms.scope = ${quoteLiteral(scope)}
1952
+ and not (r.role = any(${textArray(custom.declared)}))${narrow}${sourceFilters(ctx, scope, subjectIdSql(ctx), grantPermissionSql("ck.grant_key"), sourcesKeep(sources))}`, sources, subjectIdSql(ctx));
1953
+ return sourcesBodyOf(`${declared}
1954
+ union
1955
+ select (ms.id)::${type}
1956
+ ${rows}
1957
+ where ${signedIn(ctx)}
1958
+ and ms.scope = ${quoteLiteral(scope)}
1959
+ and not (r.role = any(${textArray(custom.declared)}))${narrow}${sourceFilters(ctx, scope, subjectIdSql(ctx), grantPermissionSql("p_grant"), sourcesKeep(sources))}
1960
+ ${customKeysSql(ctx, scope, entries(CUSTOM_ROLES.permissions, "permission", " and c.effect = 'allow'"), entries(CUSTOM_ROLES.permissions, "permission", " and c.effect = 'deny'"), entries(CUSTOM_ROLES.includes, "include_role", ""))}`, sources, subjectIdSql(ctx));
1961
+ }
1962
+ function scopedBody(ctx, scope, type) {
1963
+ if (ctx.authorize !== "database") return sqlBody(claimBody(ctx, scope, type));
1964
+ return scopeSources(ctx, scope).length > 0 ? sourcesBody(ctx, scope, type) : sqlBody(tableBody(ctx, scope, type));
1965
+ }
1966
+ /**
1967
+ * The body of `member_<scope>_ids()`: instances of `scope` the subject holds
1968
+ * a live membership of, with any role. Not narrowed to the active tenant, and
1969
+ * no cascade: a membership of a child scope is not one of its parent.
1970
+ */
1971
+ function memberBody(ctx, scope, type) {
1972
+ if (ctx.authorize !== "database") return sqlBody(` select distinct (m ->> 'id')::${type}
1973
+ from jsonb_array_elements(
1974
+ case jsonb_typeof(${membershipClaim(ctx)}) when 'array' then ${membershipClaim(ctx)} else '[]'::jsonb end
1975
+ ) m
1976
+ where ${signedIn(ctx)}
1977
+ and m ->> 'scope' = ${quoteLiteral(scope)}
1978
+ and m ->> 'id' is not null${keyTenantLine(ctx, scope, claimTenant(ctx, scope))}
1979
+ and jsonb_typeof(m -> 'roles') = 'array'
1980
+ and jsonb_array_length(m -> 'roles') > 0
1981
+ and case jsonb_typeof(m -> 'expiresAt')
1982
+ when 'number' then (m ->> 'expiresAt')::numeric > extract(epoch from now())
1983
+ else true
1984
+ end${[
1985
+ ...claimKeptLines(ctx, " "),
1986
+ ...userActive(ctx, " "),
1987
+ ...instancesActive(ctx, scope, (name) => name === scope ? `m ->> 'id'` : `m -> 'within' ->> ${quoteLiteral(name)}`, " ")
1988
+ ].map((line) => `\n${line}`).join("")}`);
1989
+ return memberRowsBody(ctx, scope, type, subjectIdSql(ctx), scopeSources(ctx, scope), true);
1990
+ }
1991
+ /**
1992
+ * The membership rows of `user` for `scope`, from the sources or else the
1993
+ * mapped table, with the same expiry and suspension filters either way.
1994
+ */
1995
+ function memberRowsBody(ctx, scope, type, user, sources, keyed = false) {
1996
+ if (sources.length > 0) {
1997
+ const narrow = keyed ? keyTenantLine(ctx, scope, sourceIdOf(scope)(rootName(ctx))) : "";
1998
+ return sourcesBodyOf(` select distinct (ms.id)::${type}
1999
+ from (
2000
+ ${sourceRows(sources)}
2001
+ ) ms
2002
+ where ${signedIn(ctx, user)}
2003
+ and ms.scope = ${quoteLiteral(scope)}
2004
+ and jsonb_typeof(ms.roles) = 'array'
2005
+ and jsonb_array_length(ms.roles) > 0${narrow}${sourceFilters(ctx, scope, user, void 0, sourcesKeep(sources))}`, sources, user);
2006
+ }
2007
+ const mapped = scopeTable(ctx, scope);
2008
+ if (mapped === void 0) return sqlBody(` select null::${type} where false -- no ${scope} memberships table configured`);
2009
+ const { table, column, tenantColumn } = mapped;
2010
+ const role = memberRoleOf(table, "m", " ");
2011
+ const lines = [
2012
+ ` select distinct ${memberColumn(column)}::${type}`,
2013
+ ` from ${membershipTable(table.table)} m${role.join}`,
2014
+ ` where ${memberColumn(table.user)} = ${user}`,
2015
+ ` and ${role.through === void 0 && !role.lateral ? memberColumn(role.column) : role.sql} is not null`
2016
+ ];
2017
+ const narrow = keyed ? keyTenantSql(ctx, tenantColumn === void 0 ? void 0 : memberColumn(tenantColumn)) : void 0;
2018
+ if (narrow !== void 0) lines.push(` and ${narrow}`);
2019
+ if (table.expiresAt !== void 0) {
2020
+ const expires = memberColumn(table.expiresAt);
2021
+ lines.push(` and (${expires} is null or ${expires} > now())`);
2022
+ }
2023
+ lines.push(...activeMembershipSql(ctx, disabledColumn(table), void 0).map((part) => ` and ${part}`), ...userActive(ctx, " ", user), ...instancesActive(ctx, scope, (name) => {
2024
+ const held = scopeColumn(table, ctx.scopes, name);
2025
+ return held === void 0 ? void 0 : memberColumn(held);
2026
+ }, " "));
2027
+ return sqlBody(lines.join("\n"));
2028
+ }
2029
+ function membershipClaim(ctx) {
2030
+ const raw = subjectClaimJsonSql(ctx, "memberships");
2031
+ return ctx.dialect === "supabase" ? `coalesce(${raw}, (select auth.jwt()) -> 'app_metadata' -> 'memberships')` : raw;
2032
+ }
2033
+ function memberFunction(ctx, scope, type, anonExecute) {
2034
+ const fn = qualified$1(ctx, memberIdsHelper(scope));
2035
+ const body = memberBody(ctx, scope, type);
2036
+ const keys = ctx.apiKeys;
2037
+ const keyed = keys === void 0 || scope !== rootName(ctx) ? body : {
2038
+ sql: `${body.sql}\n union\n${serviceKeyMemberSql(ctx, keys, scope, type)}`,
2039
+ vars: body.vars
2040
+ };
2041
+ const grants = anonExecute ? `revoke execute on function ${fn}() from public;
2042
+ grant execute on function ${fn}() to anon, authenticated;` : `revoke execute on function ${fn}() from public, anon;
2043
+ grant execute on function ${fn}() to authenticated;`;
2044
+ return `create or replace function ${fn}()
2045
+ returns setof ${type}
2046
+ ${functionBody(keyed)}
2047
+ ${grants}`;
2048
+ }
2049
+ /**
2050
+ * `member_<scope>_ids_for(p_user uuid)`: `member_<scope>_ids()` for a user the
2051
+ * caller names, read from the membership sources (or the mapped table) in
2052
+ * either mode, so a token hook can call it before any claim exists. Naming
2053
+ * the user is why no client role may execute it; the hook's grants give
2054
+ * `supabase_auth_admin` execute.
2055
+ */
2056
+ function memberForFunction(ctx, scope, type) {
2057
+ const fn = qualified$1(ctx, memberForHelper(scope));
2058
+ return `create or replace function ${fn}(p_user uuid)
2059
+ returns setof ${type}
2060
+ ${functionBody(memberRowsBody(ctx, scope, type, "p_user", memberForSources(ctx, scope)))}
2061
+ revoke execute on function ${fn}(uuid) from public, anon, authenticated;`;
2062
+ }
2063
+ function helperFunction(ctx, name, returns, body, anonExecute) {
2064
+ const fn = qualified$1(ctx, name);
2065
+ const grants = anonExecute ? `revoke execute on function ${fn}(text) from public;
2066
+ grant execute on function ${fn}(text) to anon, authenticated;` : `revoke execute on function ${fn}(text) from public, anon;
2067
+ grant execute on function ${fn}(text) to authenticated;`;
2068
+ return `create or replace function ${fn}(p_grant text)
2069
+ returns ${returns}
2070
+ ${functionBody(body)}
2071
+ ${grants}`;
2072
+ }
2073
+ /**
2074
+ * `permdock_has_for(p_user, p_grant)` and one
2075
+ * `permitted_<scope>_ids_for(p_user, p_grant)` per scope in `database` mode:
2076
+ * the bodies of `permdock_has` and `permitted_<scope>_ids` with `p_user` for
2077
+ * the signed-in user and no tenant-claim narrowing, since a named user has
2078
+ * no token. For trusted SQL that acts for a stored user (jobs, triggers,
2079
+ * approvals resolved later). Naming the user is why no client role may
2080
+ * execute them: `security definer` callers run them as their owner, and a
2081
+ * backend role needs its own grant.
2082
+ */
2083
+ function forUserSql(ctx) {
2084
+ if (ctx.authorize !== "database") return "";
2085
+ const forUser = forUserContext(ctx);
2086
+ const type = ctx.dialect === "supabase" ? "uuid" : "text";
2087
+ const fn = (name, returns, body) => {
2088
+ const qualifiedName = qualified$1(ctx, name);
2089
+ return `create or replace function ${qualifiedName}(p_user ${type}, p_grant text)
2090
+ returns ${returns}
2091
+ ${functionBody(body)}
2092
+ revoke execute on function ${qualifiedName}(${type}, text) from public, anon, authenticated;`;
2093
+ };
2094
+ return [`-- the helpers for a user the caller names: trusted SQL acting for a stored user; no client role may execute them
2095
+ ${fn(HELPERS.hasFor, "boolean", sqlBody(hasBody(forUser)))}`, ...ctx.scopes.map((scope) => {
2096
+ const scopeType = scopeTypeOf(ctx, scope.name);
2097
+ return fn(permittedForHelper(scope.name), `setof ${scopeType}`, scopedBody(forUser, scope.name, scopeType));
2098
+ })].join("\n\n");
2099
+ }
2100
+ function userIdType(ctx) {
2101
+ return ctx.dialect === "supabase" ? "uuid not null references auth.users on delete cascade" : "text not null";
2102
+ }
2103
+ /**
2104
+ * The `role_permissions` rows the policy compiles to: an upsert and a delete
2105
+ * of every other row. Data, not schema, so `supabase db diff` drops it from a
2106
+ * declarative schema; `--split ...,seeds` writes it as its own migration.
2107
+ */
2108
+ function seedSql(ctx, rows) {
2109
+ const table = qualified$1(ctx, "role_permissions");
2110
+ if (rows.length === 0) return `delete from ${table};`;
2111
+ return `insert into ${table} (role, permission, grant_key, scope, effect) values
2112
+ ${rows.map((row) => ` (${[
2113
+ row.role,
2114
+ row.permission,
2115
+ row.grantKey,
2116
+ row.scope,
2117
+ row.effect
2118
+ ].map(quoteLiteral).join(", ")})`).join(",\n")}
2119
+ on conflict (role, grant_key, scope) do update
2120
+ set permission = excluded.permission, effect = excluded.effect;
2121
+ delete from ${table}
2122
+ where (role, grant_key, scope) not in (values
2123
+ ${rows.map((row) => ` (${[
2124
+ row.role,
2125
+ row.grantKey,
2126
+ row.scope
2127
+ ].map(quoteLiteral).join(", ")})`).join(",\n")}
2128
+ );`;
2129
+ }
2130
+ /**
2131
+ * `role_permissions`, its seeds, and the three `security definer` helpers
2132
+ * with `search_path = ''`. `execute` goes to `authenticated` only.
2133
+ */
2134
+ function helpersSql(ctx, rows, options) {
2135
+ const schema = helperSchema(ctx);
2136
+ const s = quoteIdent(schema);
2137
+ const rp = qualified$1(ctx, "role_permissions");
2138
+ const chunks = [`-- permdock helpers (${ctx.authorize === "database" ? "database: reads the membership and user_roles tables" : "jwt: reads the role and memberships claims"})
2139
+ -- policies call them uncorrelated, so Postgres evaluates each once per statement`];
2140
+ if (schema !== "public") chunks.push(`create schema if not exists ${s};\nrevoke all on schema ${s} from public;\ngrant usage on schema ${s} to ${options.anonExecute === true ? "anon, authenticated" : "authenticated"};`);
2141
+ if (ctx.dialect === "supabase") chunks.push(userIdSql(ctx, options.anonExecute === true));
2142
+ chunks.push(`create table if not exists ${rp} (
2143
+ role text not null,
2144
+ permission text not null,
2145
+ grant_key text not null,
2146
+ scope text not null check (scope ~ '^[a-z][a-z0-9_]*$'),
2147
+ effect text not null default 'allow' check (effect in ('allow', 'deny')),
2148
+ primary key (role, grant_key, scope)
2149
+ );
2150
+ alter table ${rp} enable row level security;
2151
+ revoke all on table ${rp} from anon, authenticated, public;`);
2152
+ if (options.withoutSeeds !== true) chunks.push(seedSql(ctx, rows));
2153
+ if (ctx.authorize === "database" && options.userRoles && ctx.roles === void 0) {
2154
+ const ur = qualified$1(ctx, "user_roles");
2155
+ chunks.push(`create table if not exists ${ur} (
2156
+ user_id ${userIdType(ctx)},
2157
+ role text not null,
2158
+ primary key (user_id, role)
2159
+ );
2160
+ alter table ${ur} enable row level security;
2161
+ revoke all on table ${ur} from anon, authenticated, public;`);
2162
+ }
2163
+ const custom = customRolesSql(ctx);
2164
+ if (custom !== "") chunks.push(custom);
2165
+ const anon = options.anonExecute === true;
2166
+ const keys = ctx.apiKeys;
2167
+ if (keys !== void 0) chunks.push(apiKeyAllowsSql(ctx, keys, anon));
2168
+ const bodies = grantBodies(ctx);
2169
+ chunks.push(helperFunction(ctx, HELPERS.has, "boolean", bodies.has, anon));
2170
+ const capabilities = capabilitiesSql(ctx);
2171
+ if (capabilities !== "") chunks.push(capabilities);
2172
+ for (const scope of ctx.scopes) {
2173
+ const type = scopeTypeOf(ctx, scope.name);
2174
+ chunks.push(helperFunction(ctx, permittedIdsHelper(scope.name), `setof ${type}`, bodies.ids(scope.name), anon));
2175
+ chunks.push(memberFunction(ctx, scope.name, type, anon));
2176
+ if (hasMemberFor(ctx, scope.name)) chunks.push(memberForFunction(ctx, scope.name, type));
2177
+ }
2178
+ const forUser = forUserSql(ctx);
2179
+ if (forUser !== "") chunks.push(forUser);
2180
+ const writes = customRoleWritesSql(ctx, options.levelReach ?? []);
2181
+ if (writes !== "") {
2182
+ chunks.push(writes);
2183
+ const cascade = customRoleCascadeSql(ctx);
2184
+ if (cascade !== "") chunks.push(cascade);
2185
+ }
2186
+ const readers = roleReadersSql(ctx, options.permissions, options.trustedReaders);
2187
+ if (readers !== "") chunks.push(readers);
2188
+ return `${chunks.join("\n\n")}\n`;
2189
+ }
2190
+ function grantBodies(ctx) {
2191
+ const keys = ctx.apiKeys;
2192
+ const set = ctx.grantSet === true;
2193
+ const allows = apiKeyAllowsCall(ctx, set ? "ids.grant_key" : "p_grant");
2194
+ const keyTenant = keyTenantSql(ctx, void 0) ?? "true";
2195
+ return {
2196
+ has: sqlBody(keys === void 0 ? hasBody(ctx) : set ? ` select g.grant_key
2197
+ from (
2198
+ ${hasBody(ctx)}
2199
+ ) g(grant_key)
2200
+ where ${apiKeyAllowsCall(ctx, "g.grant_key")} and ${keyTenant}` : ceilingHasSql(hasBody(ctx), `${allows} and ${keyTenant}`)),
2201
+ ids: (scope) => {
2202
+ const type = scopeTypeOf(ctx, scope);
2203
+ const body = scopedBody(ctx, scope, type);
2204
+ if (keys === void 0) return body;
2205
+ const sql = scope === rootName(ctx) ? `${body.sql}\n union\n${serviceKeyIdsSql(ctx, keys, scope, type)}` : body.sql;
2206
+ return {
2207
+ sql: set ? ` select ids.id, ids.grant_key
2208
+ from (
2209
+ ${sql}
2210
+ ) ids(id, grant_key)
2211
+ where ${allows}` : ceilingIdsSql(sql, allows),
2212
+ vars: body.vars
2213
+ };
2214
+ }
2215
+ };
2216
+ }
2217
+ function forUserContext(ctx) {
2218
+ const { apiKeys: _apiKeys, ...unkeyed } = ctx;
2219
+ return {
2220
+ ...unkeyed,
2221
+ subjectId: "p_user",
2222
+ tenants: "all"
2223
+ };
2224
+ }
2225
+ //#endregion
2226
+ //#region src/cli/pg.ts
2227
+ const CONNECT_TIMEOUT_MS = 1e4;
2228
+ const STATEMENT_TIMEOUT_MS = 6e4;
2229
+ function loadPg(command) {
2230
+ return requirePeer(() => import("pg"), "pg", command);
2231
+ }
2232
+ function options(db) {
2233
+ return {
2234
+ connectionString: db,
2235
+ connectionTimeoutMillis: CONNECT_TIMEOUT_MS,
2236
+ statement_timeout: STATEMENT_TIMEOUT_MS
2237
+ };
2238
+ }
2239
+ /** Ctrl-C ends the connection, so a query that hangs cannot keep the process alive. */
2240
+ function endOnInterrupt(end) {
2241
+ const interrupt = () => {
2242
+ end().catch(() => void 0);
2243
+ process.exitCode = 130;
2244
+ };
2245
+ process.once("SIGINT", interrupt);
2246
+ return async () => {
2247
+ process.off("SIGINT", interrupt);
2248
+ await end();
2249
+ };
2250
+ }
2251
+ function unreachable(command, cause) {
2252
+ return new CliError("unavailable", `PermDock CLI: ${command.replace(/^permdock /u, "")} could not connect`, { cause });
2253
+ }
2254
+ /** One connection, for commands that run a transaction. */
2255
+ async function connectPg(db, command) {
2256
+ const client = new (await (loadPg(command))).Client(options(db));
2257
+ try {
2258
+ await client.connect();
2259
+ } catch (cause) {
2260
+ throw unreachable(command, cause);
2261
+ }
2262
+ return {
2263
+ query: (sql, values) => client.query(sql, values),
2264
+ end: endOnInterrupt(() => client.end())
2265
+ };
2266
+ }
2267
+ /** A small pool, for independent catalog reads that can run in parallel. */
2268
+ async function connectPgPool(db, command) {
2269
+ const pool = new (await (loadPg(command))).Pool({
2270
+ ...options(db),
2271
+ max: 4
2272
+ });
2273
+ try {
2274
+ (await pool.connect()).release();
2275
+ } catch (cause) {
2276
+ await pool.end();
2277
+ throw unreachable(command, cause);
2278
+ }
2279
+ return {
2280
+ query: (sql, values) => pool.query(sql, values),
2281
+ end: endOnInterrupt(() => pool.end())
2282
+ };
2283
+ }
2284
+ //#endregion
2285
+ //#region src/cli/rls-indexes.ts
2286
+ /** Postgres truncates identifiers longer than this, in bytes. */
2287
+ const MAX_IDENT = 63;
2288
+ /**
2289
+ * The row fields `condition` compares with the subject, a claim or a
2290
+ * membership (`ownerId: principal.id`, `memberOf`), through `and` and `or`:
2291
+ * the selective comparisons an index serves. A comparison with a constant
2292
+ * (`status: 'sent'`) narrows rows the scope key already found, a negation
2293
+ * scans anyway, and a dotted field is a JSON path a plain index does not serve.
2294
+ */
2295
+ function indexedFields(condition) {
2296
+ if (condition === void 0) return [];
2297
+ switch (condition.op) {
2298
+ case "and":
2299
+ case "or": return condition.conditions.flatMap(indexedFields);
2300
+ case "memberOf": return plainField(condition.field);
2301
+ case "eq":
2302
+ case "in": return isConditionRef(condition.value) ? plainField(condition.field) : [];
2303
+ case "not":
2304
+ case "sqlFunction":
2305
+ case "opaque":
2306
+ case "related":
2307
+ case "ne":
2308
+ case "gt":
2309
+ case "gte":
2310
+ case "lt":
2311
+ case "lte":
2312
+ case "contains":
2313
+ case "notIn":
2314
+ case "isNull":
2315
+ case "liveSession": return [];
2316
+ default: return condition;
2317
+ }
2318
+ }
2319
+ function plainField(field) {
2320
+ return field.includes(".") ? [] : [field];
2321
+ }
2322
+ /**
2323
+ * Every index the generated SQL reads through: the row columns policies
2324
+ * filter on (scope keys and selective condition fields), and the membership
2325
+ * tables' user column, followed by the scope column the helpers select.
2326
+ */
2327
+ function indexTargets(ctx, rowColumns) {
2328
+ const targets = /* @__PURE__ */ new Map();
2329
+ const add = (table, columns) => {
2330
+ const target = {
2331
+ table: qualifiedTable(table),
2332
+ columns
2333
+ };
2334
+ targets.set(`${target.table}\u0000${columns[0] ?? ""}`, target);
2335
+ };
2336
+ for (const { table, column } of rowColumns) add(table, [column]);
2337
+ for (const scope of ctx.scopes) {
2338
+ const mapped = scopeTable(ctx, scope.name);
2339
+ if (mapped !== void 0) add(mapped.table.table, [mapped.table.user, mapped.column]);
2340
+ }
2341
+ for (const source of [...ctx.sources ?? [], ...ctx.memberSources ?? []]) {
2342
+ add(source.sql.table, [source.sql.user]);
2343
+ const users = source.sql.userThrough;
2344
+ if (users !== void 0) add(users.table, [users.key]);
2345
+ }
2346
+ return [...targets.values()].toSorted((a, b) => `${a.table}.${a.columns.join(",")}` < `${b.table}.${b.columns.join(",")}` ? -1 : 1);
2347
+ }
2348
+ /** A stable index name under Postgres' identifier limit. */
2349
+ function indexName(target) {
2350
+ const name = `permdock_${target.table.slice(target.table.lastIndexOf(".") + 1)}_${target.columns.join("_")}_idx`;
2351
+ if (Buffer.byteLength(name) <= MAX_IDENT) return name;
2352
+ return `permdock_${createHash("sha256").update(name).digest("hex").slice(0, 8)}_idx`;
2353
+ }
2354
+ /** `create index if not exists` for every target, one per line. */
2355
+ function indexesSql(targets) {
2356
+ return targets.map((target) => `create index if not exists ${quoteIdent(indexName(target))} on ${quoteTable(target.table)} (${target.columns.map(quoteIdent).join(", ")});`).join("\n");
2357
+ }
2358
+ /** Every live column of the tables in `$1` (`schema.table`), as `target` and `name`. */
2359
+ const COLUMNS_SQL = `select n.nspname || '.' || c.relname as target, a.attname as name
2360
+ from pg_attribute a
2361
+ join pg_class c on c.oid = a.attrelid
2362
+ join pg_namespace n on n.oid = c.relnamespace
2363
+ where a.attnum > 0 and not a.attisdropped
2364
+ and n.nspname || '.' || c.relname = any($1::text[])`;
2365
+ const INDEX_COLUMNS_SQL = `select n.nspname || '.' || c.relname as target,
2366
+ array(
2367
+ select a.attname::text
2368
+ from unnest(i.indkey) with ordinality k(attnum, ord)
2369
+ left join pg_attribute a on a.attrelid = i.indrelid and a.attnum = k.attnum and k.attnum > 0
2370
+ where k.ord <= i.indnkeyatts
2371
+ order by k.ord
2372
+ ) as columns
2373
+ from pg_index i
2374
+ join pg_class c on c.oid = i.indrelid
2375
+ join pg_namespace n on n.oid = c.relnamespace
2376
+ where i.indpred is null and n.nspname || '.' || c.relname = any($1::text[])`;
2377
+ function strings(value) {
2378
+ return Array.isArray(value) ? value.map((item) => typeof item === "string" ? item : null) : [];
2379
+ }
2380
+ /** Reads the columns and index key columns of `tables` (`schema.table`). */
2381
+ async function readTableIndexFacts(db, tables, connect = (url) => connectPgPool(url, "permdock rls generate --db")) {
2382
+ const client = await connect(db);
2383
+ try {
2384
+ const [columns, indexes] = await Promise.all([client.query(COLUMNS_SQL, [[...tables]]), client.query(INDEX_COLUMNS_SQL, [[...tables]])]);
2385
+ const byTable = {};
2386
+ for (const row of columns.rows) (byTable[String(row["target"])] ??= []).push(String(row["name"]));
2387
+ const keys = {};
2388
+ for (const row of indexes.rows) {
2389
+ const list = strings(row["columns"]);
2390
+ const end = list.indexOf(null);
2391
+ const lead = end === -1 ? list : list.slice(0, end);
2392
+ if (lead.length > 0) (keys[String(row["target"])] ??= []).push(lead);
2393
+ }
2394
+ return {
2395
+ columns: byTable,
2396
+ indexes: keys
2397
+ };
2398
+ } finally {
2399
+ await client.end();
2400
+ }
2401
+ }
2402
+ /**
2403
+ * Drops the targets a database already serves or cannot hold: a target on a
2404
+ * table or column the database lacks (with a warning), and one an existing
2405
+ * index leads with (its key columns start with the target's).
2406
+ */
2407
+ function pruneIndexTargets(targets, facts) {
2408
+ const warnings = [];
2409
+ return {
2410
+ targets: targets.filter((target) => {
2411
+ const columns = facts.columns[target.table];
2412
+ if (columns === void 0) {
2413
+ warnings.push(`no index suggested on ${target.table}: the database has no such table`);
2414
+ return false;
2415
+ }
2416
+ const absent = target.columns.filter((column) => !columns.includes(column));
2417
+ if (absent.length > 0) {
2418
+ warnings.push(`no index suggested on ${target.table} (${target.columns.join(", ")}): the table has no column ${absent.join(", ")}`);
2419
+ return false;
2420
+ }
2421
+ return !(facts.indexes[target.table] ?? []).some((index) => target.columns.every((column, at) => index[at] === column));
2422
+ }),
2423
+ warnings
2424
+ };
2425
+ }
2426
+ //#endregion
2427
+ //#region src/cli/rls-permission-keys.ts
2428
+ /** The helpers that take a permission key instead of a grant key. Names are part of the SQL contract. */
2429
+ const PERMISSION_HELPERS = {
2430
+ grantKeys: "grant_keys",
2431
+ has: "permdock_has_permission",
2432
+ hasFor: "permdock_has_permission_for"
2433
+ };
2434
+ /** `permitted_<scope>_permission_keys(p_id)`: every permission key the subject holds on one instance. */
2435
+ function permissionKeysHelper(scope) {
2436
+ permittedIdsHelper(scope);
2437
+ return `permitted_${scope}_permission_keys`;
2438
+ }
2439
+ /** `permitted_<scope>_permission_keys_for(p_user, p_id)`, written in `database` mode. */
2440
+ function permissionKeysForHelper(scope) {
2441
+ return `${permissionKeysHelper(scope)}_for`;
2442
+ }
2443
+ /** `permitted_<scope>_ids_by_permission(p_permission)`. */
2444
+ function permittedByPermissionHelper(scope) {
2445
+ return `${permittedIdsHelper(scope)}_by_permission`;
2446
+ }
2447
+ /**
2448
+ * A grant's `requires` as SQL: the subject holds `key` globally, or on the
2449
+ * row's instance of a scope that partitions it, through the helpers by
2450
+ * permission key, as `requirementCondition` does in process.
2451
+ */
2452
+ function requiresSql(ctx, key, resource) {
2453
+ const literal = quoteLiteral(key);
2454
+ return `(${[`(select ${qualified$1(ctx, PERMISSION_HELPERS.has)}(${literal}))`, ...(resource === void 0 ? [] : partitionsOf(resource, ctx.scopes)).map((scope) => {
2455
+ const field = scopeField(resource, scope, ctx.scopes) ?? scope;
2456
+ return `${quoteIdent(field)} in (select ${qualified$1(ctx, checkName(permittedByPermissionHelper(scope)))}(${literal}))`;
2457
+ })].join(" or ")})`;
2458
+ }
2459
+ /** Postgres truncates an identifier past 63 bytes, which would merge two helpers. */
2460
+ function checkName(name) {
2461
+ if (new TextEncoder().encode(name).length > 63) throw new Error(`PermDock CLI: the helper name ${name} is longer than 63 bytes; use a shorter scope name`);
2462
+ return name;
2463
+ }
2464
+ function grantsFunction(ctx, grants, renamed, anonExecute) {
2465
+ const fn = qualified$1(ctx, PERMISSION_HELPERS.grantKeys);
2466
+ const map = Object.fromEntries([...grants].toSorted(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
2467
+ const current = Object.keys(renamed).length === 0 ? "p_permission" : `coalesce(${quoteLiteral(JSON.stringify(renamed))}::jsonb ->> p_permission, p_permission)`;
2468
+ return `-- the grant keys a permission key reaches on one scope: its unconditional allows, with p_effect 'deny' every deny, and with 'conditioned-allow' or 'conditioned-deny' the allows or denies that carry a row condition
2469
+ create or replace function ${fn}(p_permission text, p_scope text, p_effect text default 'allow')
2470
+ returns setof text
2471
+ language sql
2472
+ stable
2473
+ set search_path = ''
2474
+ as $$
2475
+ select g.grant_key
2476
+ from pg_catalog.jsonb_array_elements_text(coalesce(
2477
+ ${quoteLiteral(JSON.stringify(map))}::jsonb -> p_scope -> ${current} -> p_effect,
2478
+ '[]'::jsonb
2479
+ )) g(grant_key)
2480
+ $$;
2481
+ ${grantsSql(fn, "text, text, text", anonExecute)}`;
2482
+ }
2483
+ function grantsSql(fn, args, anonExecute) {
2484
+ return anonExecute ? `revoke execute on function ${fn}(${args}) from public;
2485
+ grant execute on function ${fn}(${args}) to anon, authenticated;` : `revoke execute on function ${fn}(${args}) from public, anon;
2486
+ grant execute on function ${fn}(${args}) to authenticated;`;
2487
+ }
2488
+ function definer(fn, params, returns, sql) {
2489
+ return `create or replace function ${fn}(${params})
2490
+ returns ${returns}
2491
+ language sql
2492
+ stable
2493
+ security definer
2494
+ set search_path = ''
2495
+ as $$
2496
+ ${sql}
2497
+ $$;`;
2498
+ }
2499
+ function heldSql(at, effect) {
2500
+ return `select 1 from pdk_h where pdk_h.key = pdk_k.key and pdk_h.scope = ${quoteLiteral(at)} and pdk_h.effect = '${effect}'`;
2501
+ }
2502
+ function keysFunction(fn, params, body, access) {
2503
+ return `create or replace function ${fn}(${params})
2504
+ returns setof text
2505
+ ${functionBody(body).replace("set search_path = ''", "set search_path = ''\nset jit = off")}
2506
+ ${access}`;
2507
+ }
2508
+ /**
2509
+ * The permission-key forms of the helpers: `grant_keys`, which maps a
2510
+ * permission key to the grant keys of its unconditional allows on a scope
2511
+ * (or every deny key, or the conditioned allow or deny keys),
2512
+ * `permdock_has_permission(p_permission)` and one
2513
+ * `permitted_<scope>_ids_by_permission(p_permission)` per scope, plus their
2514
+ * `_for(p_user, ...)` forms in `database` mode. They answer with the
2515
+ * unconditional allows minus any deny, so a permission whose allows all carry
2516
+ * a row condition answers nothing. The
2517
+ * `permitted_<scope>_ids_by_permission(p_permission, p_conditioned)` overload
2518
+ * with `true` also lists the instances a conditioned allow reaches and
2519
+ * subtracts only unconditional denies, leaving the row condition to the
2520
+ * caller, as `permittedIds(..., { conditioned: true })` does in process.
2521
+ */
2522
+ function permissionHelpersSql(ctx, grants, renamed, anonExecute) {
2523
+ const keys = qualified$1(ctx, PERMISSION_HELPERS.grantKeys);
2524
+ const allowKeys = (scope) => `${keys}(p_permission, ${quoteLiteral(scope)}) g(grant_key)`;
2525
+ const denyKeys = (scope) => `${keys}(p_permission, ${quoteLiteral(scope)}, 'deny') g(grant_key)`;
2526
+ const has = (helper, user) => ` select exists (select 1 from ${allowKeys("global")} where ${helper}(${user}g.grant_key))
2527
+ and not exists (select 1 from ${denyKeys("global")} where ${helper}(${user}g.grant_key))`;
2528
+ const ids = (helper, scope, user) => ` select a.id
2529
+ from ${allowKeys(scope)}
2530
+ cross join lateral ${helper}(${user}g.grant_key) a(id)
2531
+ except
2532
+ select d.id
2533
+ from ${denyKeys(scope)}
2534
+ cross join lateral ${helper}(${user}g.grant_key) d(id)`;
2535
+ const conditionedIds = (helper, scope, user) => ` select a.id
2536
+ from (
2537
+ select g.grant_key from ${allowKeys(scope)}
2538
+ union all
2539
+ select g.grant_key from ${keys}(p_permission, ${quoteLiteral(scope)}, 'conditioned-allow') g(grant_key)
2540
+ where p_conditioned
2541
+ ) g
2542
+ cross join lateral ${helper}(${user}g.grant_key) a(id)
2543
+ except
2544
+ select d.id
2545
+ from (
2546
+ select g.grant_key from ${denyKeys(scope)}
2547
+ except
2548
+ select g.grant_key from ${keys}(p_permission, ${quoteLiteral(scope)}, 'conditioned-deny') g(grant_key)
2549
+ where p_conditioned
2550
+ ) g
2551
+ cross join lateral ${helper}(${user}g.grant_key) d(id)`;
2552
+ const keysBody = (scope, bodies, filtered) => {
2553
+ const rows = ["global", scope].flatMap((at) => Object.entries(grants.get(at) ?? {}).toSorted(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).flatMap(([key, effects]) => ["allow", "deny"].flatMap((effect) => effects[effect].map((grant) => `(${[
2554
+ key,
2555
+ at,
2556
+ effect,
2557
+ grant
2558
+ ].map(quoteLiteral).join(", ")})`))));
2559
+ if (new Set(["global", scope].flatMap((at) => Object.entries(grants.get(at) ?? {}).flatMap(([key, effects]) => effects.allow.length > 0 ? [key] : []))).size === 0) return {
2560
+ sql: " select null::text where false",
2561
+ vars: []
2562
+ };
2563
+ const hasBody = bodies.has;
2564
+ const idsBody = bodies.ids(scope);
2565
+ return {
2566
+ sql: ` with pdk_m(key, scope, effect, grant_key) as (
2567
+ values
2568
+ ${rows.join(",\n ")}
2569
+ ),
2570
+ pdk_w as (
2571
+ select pdk_m.key, pdk_m.scope, pdk_m.effect, pdk_m.grant_key
2572
+ from pdk_m${filtered ? `\n where pdk_m.key in (select ${Object.keys(renamed).length === 0 ? "k.key" : `coalesce(${quoteLiteral(JSON.stringify(renamed))}::jsonb ->> k.key, k.key)`} from pg_catalog.unnest(p_keys) k(key))` : ""}
2573
+ ),
2574
+ pdk_g as (
2575
+ ${hasBody.sql}
2576
+ ),
2577
+ pdk_s as (
2578
+ select pdk_i.grant_key
2579
+ from (
2580
+ ${idsBody.sql}
2581
+ ) pdk_i(id, grant_key)
2582
+ where pdk_i.id = p_id
2583
+ ),
2584
+ pdk_h as (
2585
+ select pdk_w.key, pdk_w.scope, pdk_w.effect
2586
+ from pdk_w
2587
+ where (pdk_w.scope = 'global' and pdk_w.grant_key in (select pdk_g.grant_key from pdk_g))
2588
+ or (pdk_w.scope = ${quoteLiteral(scope)} and pdk_w.grant_key in (select pdk_s.grant_key from pdk_s))
2589
+ )
2590
+ select pdk_k.key
2591
+ from (select distinct pdk_w.key from pdk_w where pdk_w.effect = 'allow') pdk_k
2592
+ where (exists (${heldSql("global", "allow")}) and not exists (${heldSql("global", "deny")}))
2593
+ or (exists (${heldSql(scope, "allow")}) and not exists (${heldSql(scope, "deny")}))
2594
+ order by 1`,
2595
+ vars: [.../* @__PURE__ */ new Set([...hasBody.vars, ...idsBody.vars])]
2596
+ };
2597
+ };
2598
+ const chunks = [grantsFunction(ctx, grants, renamed, anonExecute), `-- the helpers by permission key: unconditional allows minus any deny
2599
+ ${definer(qualified$1(ctx, PERMISSION_HELPERS.has), "p_permission text", "boolean", has(qualified$1(ctx, HELPERS.has), ""))}
2600
+ ${grantsSql(qualified$1(ctx, PERMISSION_HELPERS.has), "text", anonExecute)}`];
2601
+ for (const scope of ctx.scopes) {
2602
+ const fn = qualified$1(ctx, checkName(permittedByPermissionHelper(scope.name)));
2603
+ chunks.push(`${definer(fn, "p_permission text", `setof ${scopeTypeOf(ctx, scope.name)}`, ids(qualified$1(ctx, permittedIdsHelper(scope.name)), scope.name, ""))}
2604
+ ${grantsSql(fn, "text", anonExecute)}`);
2605
+ const keysFn = qualified$1(ctx, checkName(permissionKeysHelper(scope.name)));
2606
+ const type = scopeTypeOf(ctx, scope.name);
2607
+ const caller = grantBodies({
2608
+ ...ctx,
2609
+ grantSet: true
2610
+ });
2611
+ chunks.push(`-- the permission keys the caller holds on one ${scope.name}: what permdock_has_permission or permitted_${scope.name}_ids_by_permission answers for each key, in one call
2612
+ ${keysFunction(keysFn, `p_id ${type}`, keysBody(scope.name, caller, false), grantsSql(keysFn, type, anonExecute))}
2613
+ ${keysFunction(keysFn, `p_id ${type}, p_keys text[]`, keysBody(scope.name, caller, true), grantsSql(keysFn, `${type}, text[]`, anonExecute))}`);
2614
+ chunks.push(`-- with p_conditioned true, also the instances a conditioned allow reaches, minus only unconditional denies: the caller applies the row condition
2615
+ ${definer(fn, "p_permission text, p_conditioned boolean", `setof ${scopeTypeOf(ctx, scope.name)}`, conditionedIds(qualified$1(ctx, permittedIdsHelper(scope.name)), scope.name, ""))}
2616
+ ${grantsSql(fn, "text, boolean", anonExecute)}`);
2617
+ }
2618
+ if (ctx.authorize !== "database") return `${chunks.join("\n\n")}\n`;
2619
+ const user = ctx.dialect === "supabase" ? "uuid" : "text";
2620
+ const revoke = (fn) => `revoke execute on function ${fn}(${user}, text) from public, anon, authenticated;`;
2621
+ const hasFor = qualified$1(ctx, PERMISSION_HELPERS.hasFor);
2622
+ chunks.push(`-- the same for a user the caller names; no client role may execute them
2623
+ ${definer(hasFor, `p_user ${user}, p_permission text`, "boolean", has(qualified$1(ctx, HELPERS.hasFor), "p_user, "))}
2624
+ ${revoke(hasFor)}`);
2625
+ for (const scope of ctx.scopes) {
2626
+ const fn = qualified$1(ctx, checkName(`${permittedByPermissionHelper(scope.name)}_for`));
2627
+ chunks.push(`${definer(fn, `p_user ${user}, p_permission text`, `setof ${scopeTypeOf(ctx, scope.name)}`, ids(qualified$1(ctx, permittedForHelper(scope.name)), scope.name, "p_user, "))}
2628
+ ${revoke(fn)}`);
2629
+ chunks.push(`${definer(fn, `p_user ${user}, p_permission text, p_conditioned boolean`, `setof ${scopeTypeOf(ctx, scope.name)}`, conditionedIds(qualified$1(ctx, permittedForHelper(scope.name)), scope.name, "p_user, "))}
2630
+ revoke execute on function ${fn}(${user}, text, boolean) from public, anon, authenticated;`);
2631
+ const keysFor = qualified$1(ctx, checkName(permissionKeysForHelper(scope.name)));
2632
+ const type = scopeTypeOf(ctx, scope.name);
2633
+ const named = grantBodies({
2634
+ ...forUserContext(ctx),
2635
+ grantSet: true
2636
+ });
2637
+ chunks.push(`${keysFunction(keysFor, `p_user ${user}, p_id ${type}`, keysBody(scope.name, named, false), `revoke execute on function ${keysFor}(${user}, ${type}) from public, anon, authenticated;`)}
2638
+ ${keysFunction(keysFor, `p_user ${user}, p_id ${type}, p_keys text[]`, keysBody(scope.name, named, true), `revoke execute on function ${keysFor}(${user}, ${type}, text[]) from public, anon, authenticated;`)}`);
2639
+ }
2640
+ return `${chunks.join("\n\n")}\n`;
2641
+ }
2642
+ //#endregion
2643
+ //#region src/cli/rls-compile.ts
2644
+ /**
2645
+ * The levels an allow reaches: every level without a row condition, else the
2646
+ * levels whose condition equals its condition.
2647
+ */
2648
+ function reachedLevels(where, levels) {
2649
+ if (where === void 0) return levels.map(([name]) => name);
2650
+ const held = canonicalJson(where);
2651
+ return levels.filter(([, condition]) => canonicalJson(condition) === held).map(([name]) => name);
2652
+ }
2653
+ function levelReachOf(policy, keys) {
2654
+ const reach = /* @__PURE__ */ new Map();
2655
+ for (const [entry, grantKey] of keys) {
2656
+ const { item } = entry;
2657
+ const { grant } = item;
2658
+ if (item.access.kind !== "role" || grant.effect !== "allow" || grant.permission.kind !== "instance" || grant.level !== void 0) continue;
2659
+ const levels = policyLevels(policy, grant.permission.resource);
2660
+ if (levels.length > 0) {
2661
+ const set = reach.get(grantKey) ?? /* @__PURE__ */ new Set();
2662
+ for (const name of reachedLevels(grant.where, levels)) set.add(name);
2663
+ reach.set(grantKey, set);
2664
+ }
2665
+ }
2666
+ const out = [];
2667
+ for (const grantKey of new Set(keys.values())) {
2668
+ const at = grantKey.lastIndexOf("@");
2669
+ const base = at === -1 ? grantKey : grantKey.slice(0, at);
2670
+ const level = at === -1 ? void 0 : grantKey.slice(at + 1);
2671
+ for (const name of reach.get(base) ?? []) if (level === void 0 || level === name) out.push([grantKey, name]);
2672
+ }
2673
+ return out.toSorted(([a, x], [b, y]) => a === b ? x < y ? -1 : 1 : a < b ? -1 : 1);
2674
+ }
2675
+ /** The SQL command `action` compiles to: `rls.actions` first, then the six default verbs. */
2676
+ function commandFor(action, actions) {
2677
+ if (actions !== void 0 && Object.hasOwn(actions, action)) {
2678
+ const configured = actions[action];
2679
+ return configured === "none" ? void 0 : configured;
2680
+ }
2681
+ switch (action) {
2682
+ case "read":
2683
+ case "list":
2684
+ case "get": return "select";
2685
+ case "create": return "insert";
2686
+ case "update": return "update";
2687
+ case "delete": return "delete";
2688
+ default: return;
2689
+ }
2690
+ }
2691
+ function tableFor(resource, tables) {
2692
+ return tables?.[resource] ?? resource;
2693
+ }
2694
+ function ancestorsOf(policy, name) {
2695
+ const names = [];
2696
+ let current = policy.resources.get(name);
2697
+ while (current?.parent !== void 0 && !names.includes(current.parent.resource)) {
2698
+ names.push(current.parent.resource);
2699
+ current = policy.resources.get(current.parent.resource);
2700
+ }
2701
+ return names;
2702
+ }
2703
+ function membershipField(policy, resource, holder) {
2704
+ if (resource === void 0) return;
2705
+ if (resource.name === holder) return resource.id ?? "id";
2706
+ let current = resource;
2707
+ const seen = /* @__PURE__ */ new Set();
2708
+ while (current?.parent !== void 0 && !seen.has(current.name)) {
2709
+ seen.add(current.name);
2710
+ if (current.parent.resource === holder) return current.parent.field;
2711
+ current = policy.resources.get(current.parent.resource);
2712
+ }
2713
+ }
2714
+ function resourceCondition(item, policy, ctx) {
2715
+ if (item.access.kind !== "resource") throw new Error("PermDock CLI: resourceCondition needs a resource role");
2716
+ const { role, resource: roleResource } = item.access;
2717
+ const target = policy.resources.get(item.grant.permission.resource);
2718
+ const holders = [roleResource, ...ancestorsOf(policy, roleResource)];
2719
+ const hops = [];
2720
+ for (const [index, holder] of holders.entries()) {
2721
+ const field = membershipField(policy, target, holder);
2722
+ if (field === void 0) continue;
2723
+ if (index > 0 && ctx.memberships?.resource?.[holder] === void 0) continue;
2724
+ hops.push({
2725
+ op: "memberOf",
2726
+ scope: "resource",
2727
+ field,
2728
+ roles: [role],
2729
+ resource: holder
2730
+ });
2731
+ }
2732
+ return sole(hops) ?? {
2733
+ op: "or",
2734
+ conditions: hops
2735
+ };
2736
+ }
2737
+ /**
2738
+ * The access a link capability has to a resource-scoped grant, over the same
2739
+ * holders as `resourceCondition`. It reads the claim, so ancestor hops need
2740
+ * no memberships table. `undefined` when no holder is on the row's chain.
2741
+ */
2742
+ function capabilityAccess(item, policy, ctx) {
2743
+ if (item.access.kind !== "resource") return;
2744
+ const { role, resource: roleResource } = item.access;
2745
+ const kinds = ctx.ownership?.kinds[role];
2746
+ if (kinds !== void 0 && !kinds.includes("link")) return;
2747
+ const target = policy.resources.get(item.grant.permission.resource);
2748
+ const hops = [];
2749
+ for (const holder of [roleResource, ...ancestorsOf(policy, roleResource)]) {
2750
+ const field = membershipField(policy, target, holder);
2751
+ if (field !== void 0) hops.push(capabilityAccessSql(ctx, field, holder, role, item.grant.permission.key));
2752
+ }
2753
+ if (hops.length === 0) return;
2754
+ return hops.length === 1 ? hops[0] : hops.map(wrapSql).join(" or ");
2755
+ }
2756
+ function prepare(item, tables, warnings, skipClosures, actions, rowActions = false) {
2757
+ const { grant, label } = item;
2758
+ if (grant.breakGlass !== void 0) {
2759
+ warnings.push(`break-glass grant ${label}/${grant.permission.key} reads through permdock_break_glass_${grant.permission.resource}, not a policy`);
2760
+ return;
2761
+ }
2762
+ if (grant.closure !== void 0 || grant.portable === false) {
2763
+ if (skipClosures) {
2764
+ warnings.push(`skipped non-portable grant ${label}/${grant.permission.key}`);
2765
+ return;
2766
+ }
2767
+ throw new Error(`PermDock CLI: closure grant ${label}/${grant.permission.key} is not portable; rewrite it or pass --skip-closures`);
2768
+ }
2769
+ const context = [.../* @__PURE__ */ new Set([...contextRefs(item.where), ...contextRefs(grant.check)])];
2770
+ if (context.length > 0) {
2771
+ if (skipClosures) {
2772
+ warnings.push(`skipped grant ${label}/${grant.permission.key}: it reads ${context.join(", ")}, which is not in the token`);
2773
+ return;
2774
+ }
2775
+ throw new Error(`PermDock CLI: grant ${label}/${grant.permission.key} reads ${context.join(", ")}; request context is not in the token, so RLS cannot compile it. Move the value to a server-set claim (principal.claims.*) or pass --skip-closures (permdock doctor PD027)`);
2776
+ }
2777
+ if (requiresApproval(grant.approval)) {
2778
+ warnings.push(`skipped approval grant ${label}/${grant.permission.key}`);
2779
+ return;
2780
+ }
2781
+ const command = commandFor(grant.permission.action, actions);
2782
+ const table = tableFor(grant.permission.resource, tables);
2783
+ if (command === void 0) {
2784
+ if (item.access.kind !== "role" && rowActions) {
2785
+ warnings.push(`no policy for ${label}/${grant.permission.key}: action '${grant.permission.action}' has no SQL command (rls.actions); only permitted_<resource>_rows answers it`);
2786
+ return {
2787
+ item,
2788
+ command: "none",
2789
+ table,
2790
+ ...item.where === void 0 ? {} : { using: item.where }
2791
+ };
2792
+ }
2793
+ if (item.access.kind !== "role") {
2794
+ warnings.push(`skipped ${label}/${grant.permission.key}: action '${grant.permission.action}' has no SQL command (rls.actions) and only role grants are seeded`);
2795
+ return;
2796
+ }
2797
+ if (grant.validity !== void 0 && grant.effect === "allow") {
2798
+ warnings.push(`skipped ${label}/${grant.permission.key}: a role_permissions row cannot carry validFrom / validUntil, so a time-bounded grant on an action with no SQL command is not seeded`);
2799
+ return;
2800
+ }
2801
+ warnings.push(`no policy for ${label}/${grant.permission.key}: action '${grant.permission.action}' has no SQL command (rls.actions); seeded for permdock_has and permitted_<scope>_ids`);
2802
+ return {
2803
+ item,
2804
+ command: "none",
2805
+ table,
2806
+ ...item.where === void 0 ? {} : { using: item.where },
2807
+ ...grant.check === void 0 ? {} : { check: grant.check }
2808
+ };
2809
+ }
2810
+ const using = command === "insert" ? void 0 : item.where;
2811
+ const check = command === "insert" ? grant.check ?? item.where : command === "update" ? grant.check ?? item.where : void 0;
2812
+ return {
2813
+ item,
2814
+ command,
2815
+ table,
2816
+ ...using === void 0 ? {} : { using },
2817
+ ...check === void 0 ? {} : { check }
2818
+ };
2819
+ }
2820
+ function signature(entry, byFields) {
2821
+ const base = [
2822
+ entry.item.grant.effect,
2823
+ entry.using ?? null,
2824
+ entry.check ?? null
2825
+ ];
2826
+ return JSON.stringify(byFields ? [...base, entry.item.grant.fields ?? null] : base);
2827
+ }
2828
+ /**
2829
+ * Grant keys per permission: the key is the permission, split into
2830
+ * `permission#n` when role grants carry different portable conditions (or
2831
+ * effects), one key per condition group; a group whose grants set `group`
2832
+ * is `permission#<group>` instead. With field views, grants that differ
2833
+ * only in `fields` get their own keys too, so a view can tell them apart.
2834
+ */
2835
+ function assignKeys(entries, byFields) {
2836
+ const groups = /* @__PURE__ */ new Map();
2837
+ for (const entry of entries) {
2838
+ if (entry.item.access.kind !== "role") continue;
2839
+ const key = entry.item.grant.permission.key;
2840
+ const byCondition = groups.get(key) ?? /* @__PURE__ */ new Map();
2841
+ const sig = signature(entry, byFields);
2842
+ byCondition.set(sig, [...byCondition.get(sig) ?? [], entry]);
2843
+ groups.set(key, byCondition);
2844
+ }
2845
+ const keys = /* @__PURE__ */ new Map();
2846
+ for (const [permission, byCondition] of groups) {
2847
+ const lists = [...byCondition.values()];
2848
+ const named = /* @__PURE__ */ new Set();
2849
+ for (const [index, list] of lists.entries()) {
2850
+ const group = groupOf(permission, list);
2851
+ if (group !== void 0 && named.has(group)) throw new Error(`PermDock CLI: grants of ${permission} with different conditions share group '${group}'; a group names one condition`);
2852
+ if (group !== void 0) named.add(group);
2853
+ const grantKey = group !== void 0 ? `${permission}#${group}` : lists.length === 1 ? permission : `${permission}#${index + 1}`;
2854
+ for (const entry of list) keys.set(entry, grantKey);
2855
+ }
2856
+ }
2857
+ return keys;
2858
+ }
2859
+ function groupOf(permission, list) {
2860
+ const names = [...new Set(list.flatMap((entry) => entry.item.grant.group === void 0 ? [] : [entry.item.grant.group]))].toSorted();
2861
+ if (names.length > 1) throw new Error(`PermDock CLI: grants of ${permission} with one condition name the groups ${names.join(", ")}; give them one group`);
2862
+ return names[0];
2863
+ }
2864
+ /**
2865
+ * One entry per level for every allow of an assignable role on a resource
2866
+ * with levels, keyed `<grant key>@<level>`. Only `permdock_custom_keys`
2867
+ * hands these keys out, to a custom role whose stored allow names the level.
2868
+ */
2869
+ function levelEntries(policy, ctx, keys, tables, warnings, skipClosures) {
2870
+ const custom = ctx.customRoles;
2871
+ if (custom?.levels !== true) return [];
2872
+ const assignable = new Set(custom.assignable);
2873
+ const out = [];
2874
+ for (const [entry, grantKey] of Array.from(keys)) {
2875
+ const { item } = entry;
2876
+ const { grant } = item;
2877
+ if (item.access.kind !== "role" || grant.effect !== "allow" || grant.permission.kind !== "instance" || !assignable.has(item.access.role)) continue;
2878
+ if (grant.permission.key.includes("@")) throw new Error(`PermDock CLI: permission key '${grant.permission.key}' holds '@', which separates a level in custom-role grant keys`);
2879
+ for (const [level, condition] of policyLevels(policy, grant.permission.resource)) {
2880
+ const where = andWhere(item.where, condition);
2881
+ const prepared = prepare({
2882
+ ...item,
2883
+ grant: leveled(grant, level, condition),
2884
+ ...where === void 0 ? {} : { where }
2885
+ }, tables, warnings, skipClosures, ctx.actions);
2886
+ if (prepared !== void 0) {
2887
+ keys.set(prepared, `${grantKey}@${level}`);
2888
+ out.push(prepared);
2889
+ }
2890
+ }
2891
+ }
2892
+ return out;
2893
+ }
2894
+ function compileOptional(condition, ctx) {
2895
+ return condition === void 0 ? void 0 : compileConditionSql(condition, ctx);
2896
+ }
2897
+ function noteConditions(entry, warnings) {
2898
+ const { label, grant } = entry.item;
2899
+ const names = [...sqlFunctionNames(entry.using), ...sqlFunctionNames(entry.check)];
2900
+ if (names.length > 0) warnings.push(`sqlFunction ${[...new Set(names)].join(", ")} on ${label}/${grant.permission.key} is portable via twin`);
2901
+ if (hasConditionOp(entry.using, "opaque") || hasConditionOp(entry.check, "opaque")) warnings.push(`opaque SQL on ${label}/${grant.permission.key} is untestable app-side`);
2902
+ }
2903
+ /**
2904
+ * Compiles every grant (role and top-level) to branches whose role check is
2905
+ * a helper call keyed by grant key. Nothing in a branch is per-row except the
2906
+ * portable row condition and resource-membership joins.
2907
+ */
2908
+ /** A Supabase token from a permanent user: anonymous sign-ins carry `is_anonymous: true`. */
2909
+ const PERMANENT_USER = `((select auth.jwt()) ->> 'is_anonymous') is distinct from 'true'`;
2910
+ function compileGrants(policy, ctx, tables, warnings, skipClosures, rowActions = false) {
2911
+ const items = collectGrants(policy);
2912
+ const entries = items.flatMap((item) => {
2913
+ const entry = prepare(item, tables, warnings, skipClosures, ctx.actions, rowActions);
2914
+ return entry === void 0 ? [] : [entry];
2915
+ });
2916
+ const keys = assignKeys(entries, ctx.fields === "views");
2917
+ entries.push(...levelEntries(policy, ctx, keys, tables, warnings, skipClosures));
2918
+ const conditionedKeys = /* @__PURE__ */ new Set();
2919
+ for (const [entry, grantKey] of keys) if (entry.using !== void 0 || entry.check !== void 0 || entry.item.grant.validity !== void 0 || entry.item.grant.requires !== void 0) conditionedKeys.add(grantKey);
2920
+ const rows = /* @__PURE__ */ new Map();
2921
+ for (const item of items) {
2922
+ const holder = item.grant.breakGlass === void 0 ? void 0 : breakGlassHolder(item);
2923
+ if (holder !== void 0) {
2924
+ const row = {
2925
+ role: holder.role,
2926
+ permission: item.grant.permission.key,
2927
+ grantKey: breakGlassKey(item.grant.permission.key),
2928
+ scope: holder.scope,
2929
+ effect: item.grant.effect
2930
+ };
2931
+ rows.set(`${row.role}\u0000${row.grantKey}\u0000${row.scope}`, row);
2932
+ }
2933
+ }
2934
+ const branches = [];
2935
+ const actionBranches = [];
2936
+ const rowColumns = /* @__PURE__ */ new Map();
2937
+ const filters = (resource, table, column) => {
2938
+ rowColumns.set(`${table}\u0000${column}`, {
2939
+ resource,
2940
+ table,
2941
+ column
2942
+ });
2943
+ };
2944
+ const typed = /* @__PURE__ */ new Map();
2945
+ const contextFor = (name) => {
2946
+ const known = typed.get(name);
2947
+ if (known !== void 0) return known;
2948
+ const node = policy.resources.get(name);
2949
+ const schema = node === void 0 ? void 0 : jsonSchemaOf(node);
2950
+ const next = {
2951
+ ...ctx,
2952
+ columnTypes: columnTypesOf(schema),
2953
+ arrayColumns: arrayColumnsOf(schema)
2954
+ };
2955
+ typed.set(name, next);
2956
+ return next;
2957
+ };
2958
+ for (const entry of entries) {
2959
+ const { item, table } = entry;
2960
+ const { grant, access, label } = item;
2961
+ if (entry.command === "none") {
2962
+ const grantKey = keys.get(entry);
2963
+ if (access.kind === "role" && grantKey !== void 0) {
2964
+ const row = {
2965
+ role: access.role,
2966
+ permission: grant.permission.key,
2967
+ grantKey,
2968
+ scope: access.scope,
2969
+ effect: grant.effect
2970
+ };
2971
+ rows.set(`${row.role}\u0000${row.grantKey}\u0000${row.scope}`, row);
2972
+ }
2973
+ if (!rowActions) continue;
2974
+ }
2975
+ const actionOnly = entry.command === "none";
2976
+ const command = actionOnly ? "select" : entry.command;
2977
+ const target = actionOnly ? actionBranches : branches;
2978
+ const rowCtx = {
2979
+ ...contextFor(item.grant.permission.resource),
2980
+ permission: grant.permission.key
2981
+ };
2982
+ noteConditions(entry, warnings);
2983
+ for (const field of [...indexedFields(entry.using), ...indexedFields(entry.check)]) filters(grant.permission.resource, table, field);
2984
+ const grantKey = keys.get(entry);
2985
+ let accessExpr;
2986
+ if (access.kind === "role" && grantKey !== void 0) {
2987
+ const column = access.scope === "global" ? void 0 : scopeField(policy.resources.get(grant.permission.resource), access.scope, policy.scopes);
2988
+ accessExpr = accessSql(ctx, access.scope, grantKey, column);
2989
+ if (column !== void 0) filters(grant.permission.resource, table, column);
2990
+ const row = {
2991
+ role: access.role,
2992
+ permission: grant.permission.key,
2993
+ grantKey,
2994
+ scope: access.scope,
2995
+ effect: grant.effect
2996
+ };
2997
+ rows.set(`${row.role}\u0000${row.grantKey}\u0000${row.scope}`, row);
2998
+ }
2999
+ const linkOnly = access.kind === "resource" && ctx.capabilities === true && ctx.memberships?.resource?.[access.resource] === void 0;
3000
+ if (access.kind === "actor") accessExpr = `${subjectClaimSql(ctx, "client_id")} is not null or ${subjectClaimJsonSql(ctx, "act")} is not null`;
3001
+ if (access.kind === "resource" && !linkOnly) accessExpr = compileConditionSql(resourceCondition(item, policy, ctx), {
3002
+ ...ctx,
3003
+ permission: grant.permission.key
3004
+ });
3005
+ if (linkOnly) warnings.push(`no ${access.resource} memberships table: only link capabilities reach ${label}/${grant.permission.key}`);
3006
+ const validity = validitySql(grant.validity);
3007
+ accessExpr = andSql(accessExpr, validity);
3008
+ for (const key of grant.requires ?? []) accessExpr = andSql(accessExpr, requiresSql(ctx, key, policy.resources.get(grant.permission.resource)));
3009
+ if (ctx.anonymousSignIns === "deny" && access.kind !== "anyone") accessExpr = andSql(accessExpr, PERMANENT_USER);
3010
+ if (ctx.apiKeys !== void 0 && grant.effect === "allow" && access.kind !== "anyone" && access.kind !== "role") {
3011
+ const calls = (requiresStandIn(grant) ? grant.requires ?? [] : [grant.permission.key, ...grant.requires ?? []]).map((key) => `(select ${apiKeyAllowsCall(ctx, quoteLiteral(key))})`);
3012
+ accessExpr = andSql(accessExpr, calls.length === 1 ? calls[0] ?? "" : `(${calls.join(" and ")})`);
3013
+ }
3014
+ const using = compileOptional(entry.using, rowCtx);
3015
+ const check = compileOptional(entry.check, rowCtx);
3016
+ const fields = grant.fields === void 0 ? {} : { fields: grant.fields };
3017
+ if (!linkOnly) target.push({
3018
+ table,
3019
+ command,
3020
+ effect: grant.effect,
3021
+ roles: access.kind === "anyone" ? ["anon", "authenticated"] : ["authenticated"],
3022
+ label,
3023
+ resource: grant.permission.resource,
3024
+ permissionKey: grant.permission.key,
3025
+ ...fields,
3026
+ ...grantKey === void 0 ? {} : { grantKey },
3027
+ ...accessExpr === void 0 ? {} : { access: accessExpr },
3028
+ ...using === void 0 ? {} : { using },
3029
+ ...check === void 0 ? {} : { check }
3030
+ });
3031
+ const linked = ctx.capabilities === true ? capabilityAccess(item, policy, ctx) : void 0;
3032
+ if (linked !== void 0) target.push({
3033
+ table,
3034
+ command,
3035
+ effect: grant.effect,
3036
+ roles: ["anon"],
3037
+ label,
3038
+ resource: grant.permission.resource,
3039
+ permissionKey: grant.permission.key,
3040
+ ...fields,
3041
+ access: andSql(linked, validity) ?? linked,
3042
+ ...using === void 0 ? {} : { using },
3043
+ ...check === void 0 ? {} : { check }
3044
+ });
3045
+ }
3046
+ return {
3047
+ branches: ensureSelectCoverage(branches, warnings),
3048
+ actionBranches,
3049
+ rolePermissions: withAliasRows(policy, [...rows.values()]),
3050
+ conditionedKeys,
3051
+ rowColumns: [...rowColumns.values()],
3052
+ levelReach: ctx.customRoles?.levels === true ? levelReachOf(policy, keys) : []
3053
+ };
3054
+ }
3055
+ /**
3056
+ * Each row again under every key its permission was renamed from, so SQL that
3057
+ * still calls `permdock_has('<old key>')` keeps the access the current key
3058
+ * has. A split grant key (`key#n`) keeps its suffix; break-glass rows are not
3059
+ * copied.
3060
+ */
3061
+ function withAliasRows(policy, rows) {
3062
+ const former = new Map(listPermissions(policy.permissions).map((leaf) => [leaf.key, formerKeys(leaf)]));
3063
+ const out = [...rows];
3064
+ for (const row of rows) {
3065
+ const suffix = row.grantKey.slice(row.permission.length);
3066
+ if (!row.grantKey.startsWith(row.permission) || suffix !== "" && (!/^#[a-z0-9][a-z0-9_-]*$/u.test(suffix) || suffix === "#break-glass")) continue;
3067
+ for (const old of former.get(row.permission) ?? []) out.push({
3068
+ ...row,
3069
+ permission: old,
3070
+ grantKey: `${old}${suffix}`
3071
+ });
3072
+ }
3073
+ return out;
3074
+ }
3075
+ /**
3076
+ * Postgres needs SELECT access to find rows for UPDATE / DELETE and for
3077
+ * RETURNING, so a table with only update or delete grants gets matching
3078
+ * SELECT branches.
3079
+ */
3080
+ function ensureSelectCoverage(branches, warnings) {
3081
+ const extra = [];
3082
+ const readable = new Set(branches.filter((item) => item.command === "select" && item.effect === "allow").map((item) => item.table));
3083
+ const covered = /* @__PURE__ */ new Set();
3084
+ for (const item of branches) {
3085
+ if (item.effect !== "allow" || item.command !== "update" && item.command !== "delete" || readable.has(item.table)) continue;
3086
+ const { check: _check, ...rest } = item;
3087
+ extra.push({
3088
+ ...rest,
3089
+ command: "select",
3090
+ coverage: true
3091
+ });
3092
+ if (!covered.has(item.table)) {
3093
+ covered.add(item.table);
3094
+ warnings.push(`added SELECT coverage for ${item.table} (${item.permissionKey})`);
3095
+ }
3096
+ }
3097
+ return [...branches, ...extra];
3098
+ }
3099
+ /** True when `sql` is one parenthesised expression, so AND / OR need not wrap it again. */
3100
+ function isWrapped(sql) {
3101
+ if (!sql.startsWith("(") || !sql.endsWith(")")) return false;
3102
+ let depth = 0;
3103
+ let quoted = false;
3104
+ for (let index = 0; index < sql.length; index += 1) {
3105
+ const ch = sql[index];
3106
+ if (ch === "'") quoted = !quoted;
3107
+ else if (!quoted && ch === "(") depth += 1;
3108
+ else if (!quoted && ch === ")") {
3109
+ depth -= 1;
3110
+ if (depth === 0 && index < sql.length - 1) return false;
3111
+ }
3112
+ }
3113
+ return depth === 0;
3114
+ }
3115
+ function wrapSql(sql) {
3116
+ return isWrapped(sql) ? sql : `(${sql})`;
3117
+ }
3118
+ /**
3119
+ * The grant's `validFrom` / `validUntil` as a clock check: `from` inclusive,
3120
+ * `until` exclusive, matching the in-process evaluator.
3121
+ */
3122
+ function validitySql(validity) {
3123
+ if (validity === void 0) return;
3124
+ return andSql(validity.from === void 0 ? void 0 : `now() >= to_timestamp(${validity.from})`, validity.until === void 0 ? void 0 : `now() < to_timestamp(${validity.until})`);
3125
+ }
3126
+ function andSql(...parts) {
3127
+ const present = parts.filter((part) => part !== void 0 && part !== "true");
3128
+ if (present.length === 0) return;
3129
+ return present.length === 1 ? present[0] : present.map(wrapSql).join(" and ");
3130
+ }
3131
+ /** `USING` and `WITH CHECK` for a branch: its access check ANDed with its row conditions. */
3132
+ function branchClauses(branch) {
3133
+ const using = branch.command === "insert" ? void 0 : andSql(branch.access, branch.using) ?? "true";
3134
+ const check = branch.command === "insert" || branch.command === "update" ? andSql(branch.access, branch.check) ?? "true" : void 0;
3135
+ return {
3136
+ ...using === void 0 ? {} : { using },
3137
+ ...check === void 0 ? {} : { check }
3138
+ };
3139
+ }
3140
+ //#endregion
3141
+ //#region src/cli/rls-policies.ts
3142
+ /** Each database role gets its own policy, so no role sees two permissive policies for one command. */
3143
+ const AUDIENCES = ["authenticated", "anon"];
3144
+ const DEFAULT_POLICY_NAME = "{table}_{op}";
3145
+ const DEFAULT_PER_ROLE_NAME = "{role}_{permission}";
3146
+ const PLACEHOLDER = /\{(table|op|role|permission)\}/gu;
3147
+ function sanitize(name) {
3148
+ return name.replaceAll(/[^A-Za-z0-9_]/g, "_");
3149
+ }
3150
+ function render(template, values) {
3151
+ return sanitize(template.replaceAll(PLACEHOLDER, (_match, key) => values[key]));
3152
+ }
3153
+ /** Rejects a template that cannot name every policy of the chosen shape uniquely. */
3154
+ function assertPolicyName(template, perRole) {
3155
+ if (!perRole && /\{(role|permission)\}/u.test(template)) throw new Error("PermDock CLI: --policy-name {role} and {permission} need --policy-per-role; a collapsed policy covers several roles");
3156
+ if (!perRole && !(template.includes("{table}") && template.includes("{op}"))) throw new Error("PermDock CLI: --policy-name needs {table} and {op} so each table and command gets its own policy");
3157
+ }
3158
+ function orSql(parts) {
3159
+ const distinct = [...new Set(parts)];
3160
+ if (distinct.includes("true")) return "true";
3161
+ return sole(distinct) ?? distinct.map(wrapSql).join(" or ");
3162
+ }
3163
+ function negate(sql) {
3164
+ return sql === void 0 ? void 0 : `(${sql}) is not true`;
3165
+ }
3166
+ function policyOf(name, branch, using, check) {
3167
+ const deny = branch.effect === "deny";
3168
+ const policy = {
3169
+ name,
3170
+ table: branch.table,
3171
+ command: branch.command,
3172
+ effect: branch.effect,
3173
+ roles: branch.roles
3174
+ };
3175
+ const finalUsing = deny ? negate(using) : using;
3176
+ const finalCheck = deny ? negate(check) : check;
3177
+ if (finalUsing !== void 0) policy.using = finalUsing;
3178
+ if (finalCheck !== void 0) policy.check = finalCheck;
3179
+ return policy;
3180
+ }
3181
+ function uniqueName(names, name) {
3182
+ const seen = names.get(name) ?? 0;
3183
+ names.set(name, seen + 1);
3184
+ return seen === 0 ? name : `${name}_${seen + 1}`;
3185
+ }
3186
+ function perRolePolicies(branches, template) {
3187
+ const names = /* @__PURE__ */ new Map();
3188
+ return branches.map((branch) => {
3189
+ const clauses = branchClauses(branch);
3190
+ const deny = branch.effect === "deny";
3191
+ const base = render(template, {
3192
+ table: branch.table,
3193
+ op: branch.command,
3194
+ role: branch.label,
3195
+ permission: branch.permissionKey
3196
+ });
3197
+ const name = `${deny ? "deny_" : ""}${base}${branch.coverage === true ? "_select_coverage" : ""}`;
3198
+ return policyOf(uniqueName(names, name), branch, clauses.using, clauses.check);
3199
+ });
3200
+ }
3201
+ /**
3202
+ * Branches of one grant-key group share their row condition, so the group
3203
+ * becomes one OR branch whose access ORs the helper calls of each scope.
3204
+ */
3205
+ function mergeGroups(branches) {
3206
+ const merged = [];
3207
+ const byKey = /* @__PURE__ */ new Map();
3208
+ for (const branch of branches) {
3209
+ const id = branch.grantKey === void 0 ? void 0 : `${branch.table}\u0000${branch.command}\u0000${branch.grantKey}\u0000${branch.coverage === true}`;
3210
+ const entry = id === void 0 ? void 0 : byKey.get(id);
3211
+ if (entry === void 0) {
3212
+ const created = {
3213
+ branch,
3214
+ accesses: branch.access === void 0 ? [] : [branch.access]
3215
+ };
3216
+ if (id !== void 0) byKey.set(id, created);
3217
+ merged.push(created);
3218
+ continue;
3219
+ }
3220
+ if (branch.access !== void 0 && !entry.accesses.includes(branch.access)) entry.accesses.push(branch.access);
3221
+ }
3222
+ return merged.map(({ branch, accesses }) => accesses.length <= 1 ? branch : withAccess(branch, orSql(accesses)));
3223
+ }
3224
+ function withAccess(branch, access) {
3225
+ return {
3226
+ ...branch,
3227
+ access
3228
+ };
3229
+ }
3230
+ function collapsedPolicies(branches, template) {
3231
+ const groups = /* @__PURE__ */ new Map();
3232
+ for (const branch of mergeGroups(branches)) {
3233
+ const id = `${branch.table}\u0000${branch.command}\u0000${branch.effect}`;
3234
+ groups.set(id, [...groups.get(id) ?? [], branch]);
3235
+ }
3236
+ const names = /* @__PURE__ */ new Map();
3237
+ return [...groups.values()].flatMap((group) => AUDIENCES.flatMap((audience) => {
3238
+ const members = group.filter((branch) => branch.roles.includes(audience));
3239
+ const [first] = members;
3240
+ if (first === void 0) return [];
3241
+ const deny = first.effect === "deny";
3242
+ const clauses = members.map(branchClauses);
3243
+ const usings = clauses.flatMap((item) => item.using === void 0 ? [] : [item.using]);
3244
+ const checks = clauses.flatMap((item) => item.check === void 0 ? [] : [item.check]);
3245
+ const base = render(template, {
3246
+ table: first.table,
3247
+ op: first.command,
3248
+ role: first.label,
3249
+ permission: first.permissionKey
3250
+ });
3251
+ return [policyOf(uniqueName(names, `${deny ? "deny_" : ""}${base}${audience === "anon" ? "_anon" : ""}`), {
3252
+ ...first,
3253
+ roles: [audience]
3254
+ }, usings.length === 0 ? void 0 : orSql(usings), checks.length === 0 ? void 0 : orSql(checks))];
3255
+ }));
3256
+ }
3257
+ /**
3258
+ * Assembles policies. The default is one PERMISSIVE policy per table,
3259
+ * command and database role (Splinter `multiple_permissive_policies` stays
3260
+ * quiet), with denies in one RESTRICTIVE policy per table, command and role.
3261
+ */
3262
+ function assemblePolicies(branches, shape) {
3263
+ const template = shape.name ?? (shape.perRole ? DEFAULT_PER_ROLE_NAME : DEFAULT_POLICY_NAME);
3264
+ assertPolicyName(template, shape.perRole);
3265
+ return shape.perRole ? perRolePolicies(branches, template) : collapsedPolicies(branches, template);
3266
+ }
3267
+ const DEFAULT_READ_ONLY_ACTORS = ["support", "impersonation"];
3268
+ const ACTOR_KIND = /^[a-z][a-z0-9_-]*$/u;
3269
+ /** The actor kinds `rls.readOnlyActors` names, or `undefined` when it is off. */
3270
+ function readOnlyActorKinds(setting) {
3271
+ if (setting === void 0 || setting === false) return;
3272
+ const kinds = setting === true ? DEFAULT_READ_ONLY_ACTORS : setting;
3273
+ if (kinds.length === 0 || kinds.some((kind) => !ACTOR_KIND.test(kind))) throw new Error("PermDock CLI: rls.readOnlyActors must be true or a non-empty list of actor kinds such as 'support'");
3274
+ return [...new Set(kinds)];
3275
+ }
3276
+ /**
3277
+ * One restrictive policy per table and write command the allow policies
3278
+ * grant to `authenticated`: the write passes unless the token's `act` claim
3279
+ * (`act`, as SQL `jsonb`) is a session of one of `kinds` that is not
3280
+ * `read_only: false`. Reads are never touched.
3281
+ */
3282
+ function readOnlyActorPolicies(policies, act, kinds) {
3283
+ const list = `array[${kinds.map((kind) => `'${kind}'`).join(", ")}]::text[]`;
3284
+ const passes = `not coalesce(${kinds.includes("support") ? `(${act} ->> 'kind') = any(${list}) or ((${act} ->> 'kind') is null and ${act} ? 'session_id')` : `(${act} ->> 'kind') = any(${list})`}, false) or coalesce((${act} ->> 'read_only') = 'false', false)`;
3285
+ const seen = /* @__PURE__ */ new Set();
3286
+ const out = [];
3287
+ for (const policy of policies) {
3288
+ const key = `${policy.table}\u0000${policy.command}`;
3289
+ if (policy.effect !== "allow" || policy.command === "select" || !policy.roles.includes("authenticated") || seen.has(key)) continue;
3290
+ seen.add(key);
3291
+ out.push({
3292
+ name: sanitize(`${policy.table}_${policy.command}_read_only_actors`),
3293
+ table: policy.table,
3294
+ command: policy.command,
3295
+ effect: "deny",
3296
+ roles: ["authenticated"],
3297
+ ...policy.command === "insert" ? {} : { using: passes },
3298
+ ...policy.command === "delete" ? {} : { check: passes }
3299
+ });
3300
+ }
3301
+ return out;
3302
+ }
3303
+ //#endregion
3304
+ //#region src/cli/rls-fields.ts
3305
+ /** Names of the field-view objects. Part of the SQL contract. */
3306
+ const FIELD_VIEWS = {
3307
+ /** `<table>_visible`: the `security_invoker` view clients read. */
3308
+ view: "_visible",
3309
+ /** `<table>_visible_fields`: the owner-rights companion `--revoke-columns` adds. */
3310
+ companion: "_visible_fields",
3311
+ /** The companion's row-key column, joined to the base table's key. */
3312
+ key: "permdock_key",
3313
+ /** Marks the companion so doctor PD022 knows it reads as its owner on purpose. */
3314
+ comment: "permdock:field-companion"
3315
+ };
3316
+ function covers(branch, column) {
3317
+ return branch.fields === void 0 || branch.fields.includes(column);
3318
+ }
3319
+ /**
3320
+ * A read grant that only shapes columns: a field-limited deny (it never
3321
+ * denies the row) or an allow with an empty list (it grants nothing). With
3322
+ * field views it leaves the row policy and lives in the view's masks.
3323
+ */
3324
+ function fieldOnly(branch) {
3325
+ if (branch.command !== "select" || branch.fields === void 0) return false;
3326
+ return branch.effect === "deny" || branch.fields.length === 0;
3327
+ }
3328
+ /** Branches the row policies keep when field views compile. */
3329
+ function rowBranches(branches) {
3330
+ return branches.filter((branch) => !fieldOnly(branch));
3331
+ }
3332
+ /**
3333
+ * Whether the reader is signed in, for branches with no helper call: a grant
3334
+ * to any signed-in user relies on `to authenticated` in its policy, which a
3335
+ * view does not have.
3336
+ */
3337
+ function audience(ctx, branch) {
3338
+ if (branch.access !== void 0 || branch.roles.length !== 1) return;
3339
+ if (branch.roles[0] === "authenticated") return signedIn(ctx);
3340
+ return branch.roles[0] === "anon" ? `not (${signedIn(ctx)})` : void 0;
3341
+ }
3342
+ function clause(ctx, branch) {
3343
+ return andSql(audience(ctx, branch), branchClauses(branch).using) ?? "true";
3344
+ }
3345
+ /**
3346
+ * `can(permission, row, { field })` in SQL: an allow that covers the column
3347
+ * holds for the row and no covering deny does. Every access term is the
3348
+ * uncorrelated helper call the row policy uses, so it runs once per statement.
3349
+ */
3350
+ function maskSql(ctx, allows, denies, column) {
3351
+ const allowed = allows.filter((branch) => covers(branch, column)).map((branch) => clause(ctx, branch));
3352
+ if (allowed.length === 0) return "false";
3353
+ const denied = denies.filter((branch) => covers(branch, column)).map((branch) => clause(ctx, branch));
3354
+ const allow = orSql(allowed);
3355
+ if (denied.length === 0) return allow;
3356
+ const deny = orSql(denied);
3357
+ return allow === "true" ? `not ${wrapSql(deny)}` : `${wrapSql(allow)} and not ${wrapSql(deny)}`;
3358
+ }
3359
+ function schemaColumns(policy, resource) {
3360
+ const node = policy.resources.get(resource);
3361
+ const schema = node === void 0 ? null : jsonSchemaOf(node);
3362
+ const properties = schema !== null && typeof schema === "object" ? schema.properties : void 0;
3363
+ return properties !== null && typeof properties === "object" ? Object.keys(properties) : void 0;
3364
+ }
3365
+ function viewName(table, suffix) {
3366
+ return `${table}${suffix}`;
3367
+ }
3368
+ /**
3369
+ * `<helper schema>.<table>_visible_fields`: outside the Data API's schemas,
3370
+ * so its owner rights reach clients only through the `_visible` join.
3371
+ */
3372
+ function companionName(ctx, table) {
3373
+ const base = table.startsWith("public.") ? table.slice(7) : table.replaceAll(".", "_");
3374
+ return `${helperSchema(ctx)}.${viewName(base, FIELD_VIEWS.companion)}`;
3375
+ }
3376
+ /**
3377
+ * One view per table whose read grants limit fields. A column is restricted
3378
+ * when some read allow lists fields without it or some read deny lists it;
3379
+ * every other column, and the row key, passes through unchanged.
3380
+ */
3381
+ function fieldViews(policy, ctx, branches, options, warnings) {
3382
+ const byTable = /* @__PURE__ */ new Map();
3383
+ for (const branch of branches) {
3384
+ if (branch.command !== "select" || branch.coverage === true) continue;
3385
+ byTable.set(branch.table, [...byTable.get(branch.table) ?? [], branch]);
3386
+ }
3387
+ const views = [];
3388
+ for (const [table, reads] of byTable) {
3389
+ const allows = reads.filter((branch) => branch.effect === "allow" && branch.fields?.length !== 0);
3390
+ const denies = reads.filter((branch) => branch.effect === "deny");
3391
+ const limited = reads.some((branch) => branch.fields !== void 0);
3392
+ const resource = reads.find((branch) => branch.resource !== void 0)?.resource;
3393
+ if (!limited || allows.length === 0 || resource === void 0) continue;
3394
+ const names = schemaColumns(policy, resource);
3395
+ if (names === void 0) throw new Error(`PermDock CLI: --fields views needs the ${resource} schema's JSON Schema (Standard JSON Schema) to list the columns of ${table}`);
3396
+ const key = policy.resources.get(resource)?.id ?? "id";
3397
+ const restricted = (column) => column !== key && (allows.some((branch) => branch.fields !== void 0 && !branch.fields.includes(column)) || denies.some((branch) => branch.fields?.includes(column) === true));
3398
+ const columns = names.map((name) => {
3399
+ quoteIdent(name);
3400
+ return restricted(name) ? {
3401
+ name,
3402
+ mask: maskSql(ctx, allows, denies, name)
3403
+ } : { name };
3404
+ });
3405
+ if (columns.every((column) => column.mask === void 0)) continue;
3406
+ const view = viewName(table, FIELD_VIEWS.view);
3407
+ if (allows.some((branch) => branch.fields !== void 0 && !branch.fields.includes(key))) warnings.push(`field view ${view}: the key ${key} passes through, although a read grant on ${resource} omits it`);
3408
+ const hidden = columns.filter((column) => column.mask !== void 0).map((column) => column.name);
3409
+ if (options.helpersOnly === true) warnings.push(`field view ${view}: ${table} still returns ${hidden.join(", ")} to direct reads; revoke select on those columns from client roles in your own grants, or read them through a function`);
3410
+ else if (!options.revokeColumns) warnings.push(`field view ${view}: ${table} still returns ${hidden.join(", ")} to direct reads; add --revoke-columns so clients read through the view`);
3411
+ views.push({
3412
+ resource,
3413
+ table,
3414
+ view,
3415
+ key,
3416
+ columns,
3417
+ roles: reads.some((branch) => branch.roles.includes("anon")) ? ["anon", "authenticated"] : ["authenticated"],
3418
+ ...options.revokeColumns ? { companion: companionName(ctx, table) } : {}
3419
+ });
3420
+ }
3421
+ return views;
3422
+ }
3423
+ /** Columns of `view`'s table that `anon` and `authenticated` keep on the base table with `--revoke-columns`. */
3424
+ function readableColumns(view) {
3425
+ return view.columns.filter((column) => column.mask === void 0).map((column) => column.name);
3426
+ }
3427
+ function restrictedColumns(view) {
3428
+ return view.columns.filter((column) => column.mask !== void 0).map((column) => column.name);
3429
+ }
3430
+ function columnList(names) {
3431
+ return names.map(quoteIdent).join(", ");
3432
+ }
3433
+ function selectList(lines) {
3434
+ return lines.map((line) => ` ${line}`).join(",\n");
3435
+ }
3436
+ function grantView(name, roles) {
3437
+ return [`revoke all on table ${quoteTable(qualifiedTable(name))} from anon, authenticated, public;`, `grant select on table ${quoteTable(qualifiedTable(name))} to ${roles.join(", ")};`].join("\n");
3438
+ }
3439
+ function inlineViewSql(view) {
3440
+ const targets = view.columns.map((column) => column.mask === void 0 ? quoteIdent(column.name) : `case when ${column.mask} then ${quoteIdent(column.name)} end as ${quoteIdent(column.name)}`);
3441
+ return `create or replace view ${quoteTable(qualifiedTable(view.view))} with (security_invoker = true) as
3442
+ select
3443
+ ${selectList(targets)}
3444
+ from ${quoteTable(qualifiedTable(view.table))};`;
3445
+ }
3446
+ function companionSql(view, companion) {
3447
+ const restricted = view.columns.filter((column) => column.mask !== void 0);
3448
+ const targets = [`${quoteIdent(view.key)} as ${quoteIdent(FIELD_VIEWS.key)}`, ...restricted.map((column) => `case when ${column.mask} then ${quoteIdent(column.name)} end as ${quoteIdent(column.name)}`)];
3449
+ const any = orSql(restricted.map((column) => column.mask ?? "false"));
3450
+ const name = companion.slice(0, companion.indexOf("."));
3451
+ const schema = quoteIdent(name);
3452
+ return `${name === "public" ? "" : `create schema if not exists ${schema};
3453
+ revoke all on schema ${schema} from public;
3454
+ grant usage on schema ${schema} to ${view.roles.join(", ")};
3455
+ `}create or replace view ${quoteTable(qualifiedTable(companion))} with (security_barrier = true) as
3456
+ select
3457
+ ${selectList(targets)}
3458
+ from ${quoteTable(qualifiedTable(view.table))}
3459
+ where ${any};
3460
+ comment on view ${quoteTable(qualifiedTable(companion))} is ${quoteLiteral(`${FIELD_VIEWS.comment} ${view.view}`)};`;
3461
+ }
3462
+ function joinedViewSql(view, companion) {
3463
+ const targets = view.columns.map((column) => column.mask === void 0 ? `t.${quoteIdent(column.name)}` : `f.${quoteIdent(column.name)}`);
3464
+ return `create or replace view ${quoteTable(qualifiedTable(view.view))} with (security_invoker = true) as
3465
+ select
3466
+ ${selectList(targets)}
3467
+ from ${quoteTable(qualifiedTable(view.table))} t
3468
+ left join ${quoteTable(qualifiedTable(companion))} f on f.${quoteIdent(FIELD_VIEWS.key)} = t.${quoteIdent(view.key)};`;
3469
+ }
3470
+ /** `select` on only the unrestricted columns (and the key) of the base table, for `--revoke-columns`. */
3471
+ function columnGrantSql(view, role) {
3472
+ return `grant select (${columnList(readableColumns(view))}) on table ${quoteTable(qualifiedTable(view.table))} to ${role};`;
3473
+ }
3474
+ function columnRevokeSql(view) {
3475
+ return `revoke select (${columnList(restrictedColumns(view))}) on table ${quoteTable(qualifiedTable(view.table))} from anon, authenticated;`;
3476
+ }
3477
+ /**
3478
+ * The view SQL: the `security_invoker` view, and with `--revoke-columns` the
3479
+ * owner-rights companion it joins for the restricted columns. The companion
3480
+ * masks every column with the full field decision and keeps only rows where
3481
+ * one is readable, so reading it directly shows nothing `pick` would not.
3482
+ */
3483
+ function fieldViewsSql(views) {
3484
+ return views.map((view) => {
3485
+ const head = `-- field view over ${view.table}: ${restrictedColumns(view).join(", ")} read as null unless a read grant covers the column for the row`;
3486
+ if (view.companion === void 0) return [
3487
+ head,
3488
+ inlineViewSql(view),
3489
+ grantView(view.view, view.roles)
3490
+ ].join("\n");
3491
+ return [
3492
+ head,
3493
+ `-- ${view.companion} reads ${view.table} as its owner; ${view.view} reads the rows as the caller and joins it`,
3494
+ companionSql(view, view.companion),
3495
+ grantView(view.companion, view.roles),
3496
+ joinedViewSql(view, view.companion),
3497
+ grantView(view.view, view.roles)
3498
+ ].join("\n");
3499
+ }).join("\n\n");
3500
+ }
3501
+ //#endregion
3502
+ export { helpersSql as A, breakGlassHolder as B, readTableIndexFacts as C, claimKeptLines as D, accessSql as E, seedSql as F, API_KEY_ALLOWS as G, collectGrants as H, sourceFilters as I, apiKeyFields as K, sourcesKeep as L, membershipRows as M, membershipTable as N, disabledColumn as O, roleRows as P, hasCustomRoleChecksFor as R, pruneIndexTargets as S, connectPgPool as T, roleNames as U, breakGlassKey as V, contextRefs as W, permissionKeysForHelper as _, fieldViewsSql as a, indexTargets as b, assemblePolicies as c, readOnlyActorPolicies as d, branchClauses as f, permissionHelpersSql as g, tableFor as h, fieldViews as i, memberColumn as j, globalRoleRows as k, orSql as l, compileGrants as m, columnGrantSql as n, rowBranches as o, commandFor as p, apiKeysPlan as q, columnRevokeSql as r, viewName as s, FIELD_VIEWS as t, readOnlyActorKinds as u, permittedByPermissionHelper as v, connectPg as w, indexesSql as x, COLUMNS_SQL as y, globalRoleSource as z };