permdock 0.0.0 → 0.1.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 (290) hide show
  1. package/README.md +268 -1
  2. package/dist/a2a/index.d.ts +178 -0
  3. package/dist/a2a/index.js +271 -0
  4. package/dist/ai-sdk/index.d.ts +74 -0
  5. package/dist/ai-sdk/index.js +137 -0
  6. package/dist/approval-required-TzNB9oQA.js +6 -0
  7. package/dist/approvals/index.d.ts +3 -0
  8. package/dist/approvals/index.js +4 -0
  9. package/dist/approvals-DaxY-Bdg.js +218 -0
  10. package/dist/approvers-aH0PJkmf.js +20 -0
  11. package/dist/arazzo-CTeVuXr5.js +70 -0
  12. package/dist/arazzo-aoTkqYsJ.js +54 -0
  13. package/dist/authzen/index.d.ts +48 -0
  14. package/dist/authzen/index.js +336 -0
  15. package/dist/better-auth/index.d.ts +92 -0
  16. package/dist/better-auth/index.js +324 -0
  17. package/dist/budget-JqcRqyhK.d.ts +11 -0
  18. package/dist/budget-NbEtbJC_.js +11 -0
  19. package/dist/capability-B68OFnZx.js +171 -0
  20. package/dist/capability-BDG_nkxt.d.ts +99 -0
  21. package/dist/catalog/index.d.ts +12 -0
  22. package/dist/catalog/index.js +2 -0
  23. package/dist/catalog-B0E6bggc.js +48 -0
  24. package/dist/catalog-H-vFGwWK.js +55 -0
  25. package/dist/catalog-doc-BSo_Q_-6.js +298 -0
  26. package/dist/catalog-idsHc0vo.js +2 -0
  27. package/dist/catalog-path-CnI0XTFK.js +12 -0
  28. package/dist/claude-agent/index.d.ts +81 -0
  29. package/dist/claude-agent/index.js +83 -0
  30. package/dist/clerk/index.d.ts +56 -0
  31. package/dist/clerk/index.js +280 -0
  32. package/dist/cli/bin.d.ts +1 -0
  33. package/dist/cli/bin.js +20 -0
  34. package/dist/cli/index.d.ts +46 -0
  35. package/dist/cli/index.js +5 -0
  36. package/dist/cloud/index.d.ts +91 -0
  37. package/dist/cloud/index.js +390 -0
  38. package/dist/cloud-BNQTrmrr.js +50 -0
  39. package/dist/cloud-Cuxr6Czw.js +117 -0
  40. package/dist/collect-B7_TIfmg.js +49 -0
  41. package/dist/collect-O-tOtbnk.js +350 -0
  42. package/dist/collect-fRPAQIWb.js +2 -0
  43. package/dist/commands-BMh_Etm2.js +93 -0
  44. package/dist/compact-y6vfu2_f.js +19 -0
  45. package/dist/compare-pfyVnBjE.js +12 -0
  46. package/dist/compile-CQbvyIBr.d.ts +30 -0
  47. package/dist/compile-D22iwvuV.js +558 -0
  48. package/dist/config-BPYmjTOp.js +26 -0
  49. package/dist/connection-JvqwHODC.js +194 -0
  50. package/dist/context-CKEAabd7.js +73 -0
  51. package/dist/context-gtAwAILx.js +6 -0
  52. package/dist/convex/index.d.ts +40 -0
  53. package/dist/convex/index.js +55 -0
  54. package/dist/create-BKF3dgFk.d.ts +162 -0
  55. package/dist/create-CSkhDU9T.js +222 -0
  56. package/dist/credential-B_rkUNlY.js +326 -0
  57. package/dist/credentials-BgRX3WEg.js +268 -0
  58. package/dist/describe-Bt1YD5uS.js +99 -0
  59. package/dist/describe-DernyItf.d.ts +37 -0
  60. package/dist/diff-BUzf5Poi.js +48 -0
  61. package/dist/diff-x5Il8LVa.js +418 -0
  62. package/dist/digest-B3kc_PgQ.d.ts +19 -0
  63. package/dist/digest-BI-6aa6d.js +27 -0
  64. package/dist/doctor-BGle8Gqi.js +1314 -0
  65. package/dist/doctor-Bqo6FwUa.js +53 -0
  66. package/dist/drizzle/index.d.ts +72 -0
  67. package/dist/drizzle/index.js +160 -0
  68. package/dist/duration-xK2jGFVc.js +25 -0
  69. package/dist/elysia/index.d.ts +71 -0
  70. package/dist/elysia/index.js +103 -0
  71. package/dist/errors-DSMnAVNa.js +43 -0
  72. package/dist/errors-DbZ1YOnb.d.ts +138 -0
  73. package/dist/errors-Iy71s7Oj.js +177 -0
  74. package/dist/errors-m3u9TmDu.js +27 -0
  75. package/dist/evaluations-DsAU9ppl.js +479 -0
  76. package/dist/eve/index.d.ts +95 -0
  77. package/dist/eve/index.js +181 -0
  78. package/dist/express/index.d.ts +46 -0
  79. package/dist/express/index.js +108 -0
  80. package/dist/fastify/index.d.ts +56 -0
  81. package/dist/fastify/index.js +141 -0
  82. package/dist/files-B_wAGYmt.js +121 -0
  83. package/dist/fixtures-Cvaw0gDG.js +64 -0
  84. package/dist/freeze-y1_jQL4v.js +31 -0
  85. package/dist/from-snapshot-BMGnhmgv.js +552 -0
  86. package/dist/generate-CH7ThJ14.js +173 -0
  87. package/dist/grantee-Bv04_Vzf.js +521 -0
  88. package/dist/headers-B5RRv3Xm.js +6 -0
  89. package/dist/headers-C8SHQccD.d.ts +6 -0
  90. package/dist/helpers-DnSOrhB9.js +682 -0
  91. package/dist/hono/index.d.ts +70 -0
  92. package/dist/hono/index.js +131 -0
  93. package/dist/hosted-BwKQ1BTA.js +265 -0
  94. package/dist/http-DPuDaChb.d.ts +13 -0
  95. package/dist/http-GgVApX1k.js +111 -0
  96. package/dist/index-CltcQ4Bf.d.ts +138 -0
  97. package/dist/index-LF_hS-yn.d.ts +177 -0
  98. package/dist/index-fG6NSXlc.d.ts +9 -0
  99. package/dist/index-xIxJLwOQ.d.ts +415 -0
  100. package/dist/index.d.ts +11 -0
  101. package/dist/index.js +21 -0
  102. package/dist/jwt/index.d.ts +87 -0
  103. package/dist/jwt/index.js +571 -0
  104. package/dist/kernel-YOGCWNLf.js +211 -0
  105. package/dist/kysely/index.d.ts +77 -0
  106. package/dist/kysely/index.js +129 -0
  107. package/dist/load-BZ24CpZP.js +69 -0
  108. package/dist/load-QOOm1z70.js +2 -0
  109. package/dist/load-jose-BL6LH4bL.js +11 -0
  110. package/dist/lru-8q4WZjBV.js +28 -0
  111. package/dist/manifest-DDQbC6K0.d.ts +118 -0
  112. package/dist/map-DowSO96j.js +158 -0
  113. package/dist/map-claims-B_6I1Rn-.js +360 -0
  114. package/dist/map-error-RJ3ZsUyA.js +16 -0
  115. package/dist/markers-B0hYLvMD.js +60 -0
  116. package/dist/may-use-CnFEjVEp.js +37 -0
  117. package/dist/mcp/index.d.ts +127 -0
  118. package/dist/mcp/index.js +563 -0
  119. package/dist/nest/index.d.ts +80 -0
  120. package/dist/nest/index.js +270 -0
  121. package/dist/next/client.d.ts +24 -0
  122. package/dist/next/client.js +31 -0
  123. package/dist/next/index.d.ts +110 -0
  124. package/dist/next/index.js +195 -0
  125. package/dist/next/plugin.d.ts +14 -0
  126. package/dist/next/plugin.js +2 -0
  127. package/dist/node/index.d.ts +43 -0
  128. package/dist/node/index.js +66 -0
  129. package/dist/openai/index.d.ts +71 -0
  130. package/dist/openai/index.js +105 -0
  131. package/dist/openapi/index.d.ts +93 -0
  132. package/dist/openapi/index.js +3 -0
  133. package/dist/openapi-CwePaF7C.js +164 -0
  134. package/dist/openapi-DWD0Uc_4.js +250 -0
  135. package/dist/openapi-DcqM8nU7.js +306 -0
  136. package/dist/openapi-import-BWRUNNeW.js +5959 -0
  137. package/dist/openapi-schema-D8j_T9tO.js +6902 -0
  138. package/dist/orpc/index.d.ts +64 -0
  139. package/dist/orpc/index.js +188 -0
  140. package/dist/otel/index.d.ts +13 -0
  141. package/dist/otel/index.js +202 -0
  142. package/dist/package-root-zGkxO3oN.js +30 -0
  143. package/dist/parse-DPfIvFMU.js +135 -0
  144. package/dist/pdp/index.d.ts +22 -0
  145. package/dist/pdp/index.js +795 -0
  146. package/dist/peer-BOr_kJE1.js +31 -0
  147. package/dist/permdock-yoZ7EjxX.js +2956 -0
  148. package/dist/permissions-B4apnahQ.d.ts +185 -0
  149. package/dist/permissions-B8vCg_bI.d.ts +52 -0
  150. package/dist/permissions-CofRqesP.js +142 -0
  151. package/dist/permissions-DC7GROPA.js +600 -0
  152. package/dist/pg-4GJWDUxG.js +953 -0
  153. package/dist/pins-CqE1jZuF.js +12 -0
  154. package/dist/plugin-4gr7IxFJ.js +65 -0
  155. package/dist/policy-ANp36PnI.js +971 -0
  156. package/dist/policy-CInmNGkM.d.ts +1959 -0
  157. package/dist/policy-Cq2fB8Q5.d.ts +20 -0
  158. package/dist/prisma/index.d.ts +135 -0
  159. package/dist/prisma/index.js +430 -0
  160. package/dist/problem-Cgp9-KZA.js +226 -0
  161. package/dist/prompt-CXYhLfsS.js +32 -0
  162. package/dist/protected-B4K3BKoX.js +138 -0
  163. package/dist/protected-BuPAycJT.d.ts +26 -0
  164. package/dist/protected-wY7nXhY9.d.ts +23 -0
  165. package/dist/provider-_wx46HpB.js +48 -0
  166. package/dist/provider-wTAUda2v.d.ts +6 -0
  167. package/dist/react/index.d.ts +6 -0
  168. package/dist/react/index.js +6 -0
  169. package/dist/react/provider-client.d.ts +2 -0
  170. package/dist/react/provider-client.js +3 -0
  171. package/dist/react-native/index.d.ts +42 -0
  172. package/dist/react-native/index.js +174 -0
  173. package/dist/refs-ChLSxbST.js +90 -0
  174. package/dist/relations-r4soIFZB.js +426 -0
  175. package/dist/revocations-Cy06JNx2.d.ts +21 -0
  176. package/dist/rls-BOFU3chG.js +233 -0
  177. package/dist/rls-CJVja9Ww.js +2119 -0
  178. package/dist/rls-graph-DxQ39PJj.js +371 -0
  179. package/dist/rls-helpers-BxRuif0l.js +1346 -0
  180. package/dist/rls-import-CXV6LBlS.js +942 -0
  181. package/dist/rls-migrate-DrFPbf8p.js +366 -0
  182. package/dist/row-check-BajTgQZ-.d.ts +43 -0
  183. package/dist/run-CJ6UvS3a.js +155 -0
  184. package/dist/runtime-DP9ttFh1.js +27 -0
  185. package/dist/saas-BRrZzJkM.js +1193 -0
  186. package/dist/schema-P8yoma__.js +296 -0
  187. package/dist/scim/index.d.ts +2 -0
  188. package/dist/scim/index.js +2 -0
  189. package/dist/scim-9NFa0XVZ.js +1445 -0
  190. package/dist/scopes-cKVp_WTw.js +212 -0
  191. package/dist/server/index.d.ts +123 -0
  192. package/dist/server/index.js +8 -0
  193. package/dist/sha256-BO0swRXL.js +150 -0
  194. package/dist/sink-Bd9PSyfq.js +141 -0
  195. package/dist/sink-Cfr9-7YC.d.ts +104 -0
  196. package/dist/skills-C_lpV4Jx.js +50 -0
  197. package/dist/skills-Dx3QLnMY.js +110 -0
  198. package/dist/snapshot-DE8dE_hz.js +1051 -0
  199. package/dist/solid/index.d.ts +63 -0
  200. package/dist/solid/index.js +197 -0
  201. package/dist/source-DoBBYJi2.js +6 -0
  202. package/dist/sources-DOpW5Ila.d.ts +347 -0
  203. package/dist/sources-DVHM3Mwq.js +284 -0
  204. package/dist/sql-Bll1d7y0.js +22 -0
  205. package/dist/src-CTNT-PBW.js +430 -0
  206. package/dist/ssf/index.d.ts +3 -0
  207. package/dist/ssf/index.js +622 -0
  208. package/dist/store-Bq90395i.d.ts +27 -0
  209. package/dist/store-C6hFW6ta.js +508 -0
  210. package/dist/stores-CkG2HrSg.js +140 -0
  211. package/dist/stores-CvOnu_2T.d.ts +41 -0
  212. package/dist/stream-BhMfZOwr.d.ts +12 -0
  213. package/dist/stream-Q_xlB6Ko.js +52 -0
  214. package/dist/style-CTm1AXDT.js +22 -0
  215. package/dist/subject-C6dLxqHU.js +24 -0
  216. package/dist/subject-settings-xt7V845g.js +82 -0
  217. package/dist/supabase/index.d.ts +67 -0
  218. package/dist/supabase/index.js +4 -0
  219. package/dist/supabase/middleware.d.ts +77 -0
  220. package/dist/supabase/middleware.js +68 -0
  221. package/dist/supabase-D8UlBA7Z.js +83 -0
  222. package/dist/supabase-DTxGtYdi.js +796 -0
  223. package/dist/supabase-hook-DW-xP4hU.js +2 -0
  224. package/dist/supabase-hook-D_OqGb_V.js +1528 -0
  225. package/dist/svelte/Protected.svelte +34 -0
  226. package/dist/svelte/index.d.ts +10 -0
  227. package/dist/svelte/index.js +53 -0
  228. package/dist/svelte/runtime.d.ts +6 -0
  229. package/dist/svelte/runtime.js +3 -0
  230. package/dist/svelte/source.d.ts +10 -0
  231. package/dist/svelte/source.js +8 -0
  232. package/dist/terminal/index.d.ts +171 -0
  233. package/dist/terminal/index.js +821 -0
  234. package/dist/testing/index.d.ts +656 -0
  235. package/dist/testing/index.js +3208 -0
  236. package/dist/testing/saas/index.d.ts +194 -0
  237. package/dist/testing/saas/index.js +3 -0
  238. package/dist/testing/saas/permissions.d.ts +2 -0
  239. package/dist/testing/saas/permissions.js +2 -0
  240. package/dist/text-diff-BdkkYSbi.js +15 -0
  241. package/dist/thenable-okc2xDsj.js +10 -0
  242. package/dist/timeout-D51niuQP.js +8 -0
  243. package/dist/trpc/index.d.ts +80 -0
  244. package/dist/trpc/index.js +205 -0
  245. package/dist/types-B8w5PFtS.d.ts +141 -0
  246. package/dist/types-B9dmiiab.d.ts +66 -0
  247. package/dist/types-BBK-exvJ.d.ts +177 -0
  248. package/dist/types-BvBk1wgn.d.ts +118 -0
  249. package/dist/types-CxquUByI.d.ts +9 -0
  250. package/dist/types-D6Z6-rKJ.d.ts +312 -0
  251. package/dist/types-DbWdEfcm.d.ts +87 -0
  252. package/dist/types-bva3i4Gf.d.ts +98 -0
  253. package/dist/types-i4BAOvdb.d.ts +97 -0
  254. package/dist/unplugin/index.d.ts +7 -0
  255. package/dist/unplugin/index.js +30 -0
  256. package/dist/usage-1ozMubLY.js +42 -0
  257. package/dist/usage-CUnK6Ou9.js +530 -0
  258. package/dist/usage-PyEor6GA.js +2 -0
  259. package/dist/validity-D0uRmJKJ.js +224 -0
  260. package/dist/verifier-B90agnhl.js +461 -0
  261. package/dist/version-CnSh33Fj.js +16 -0
  262. package/dist/vocabulary-Dk0fs-Jk.d.ts +56 -0
  263. package/dist/vue/index.d.ts +57 -0
  264. package/dist/vue/index.js +203 -0
  265. package/dist/webmcp/index.d.ts +75 -0
  266. package/dist/webmcp/index.js +313 -0
  267. package/package.json +423 -4
  268. package/rulesets/permdock.yaml +29 -0
  269. package/schemas/catalog-v1.json +507 -0
  270. package/schemas/openapi/oas-3.1.json +1298 -0
  271. package/schemas/openapi/oas-3.2.json +1516 -0
  272. package/schemas/openapi/overlay-1.1.json +79 -0
  273. package/schemas/supabase-claims-v1.json +139 -0
  274. package/schemas/supabase-manifest-v1.json +217 -0
  275. package/skills/permdock/SKILL.md +66 -0
  276. package/skills/permdock-agents/SKILL.md +77 -0
  277. package/skills/permdock-agents/references/runtimes.md +211 -0
  278. package/skills/permdock-approvals/SKILL.md +80 -0
  279. package/skills/permdock-approvals/references/stores-and-resume.md +83 -0
  280. package/skills/permdock-audit/SKILL.md +67 -0
  281. package/skills/permdock-credentials/SKILL.md +55 -0
  282. package/skills/permdock-credentials/references/tokens-keys-links.md +127 -0
  283. package/skills/permdock-data/SKILL.md +57 -0
  284. package/skills/permdock-data/references/queries-and-rls.md +54 -0
  285. package/skills/permdock-data/references/relationships.md +65 -0
  286. package/skills/permdock-tenancy/SKILL.md +77 -0
  287. package/skills/permdock-tenancy/references/ownership-and-custom-roles.md +83 -0
  288. package/skills/permdock-wire/SKILL.md +116 -0
  289. package/skills/permdock-wire/references/adapters.md +480 -0
  290. package/skills/permdock-wire/references/policy-options.md +43 -0
@@ -0,0 +1,953 @@
1
+ import { r as sole } from "./compact-y6vfu2_f.js";
2
+ import { a as formerKeys, g as listPermissions } from "./permissions-DC7GROPA.js";
3
+ import { a as hasConditionOp } from "./refs-ChLSxbST.js";
4
+ import { u as scopeList } from "./scopes-cKVp_WTw.js";
5
+ import { f as relationCondition, w as listRoles } from "./grantee-Bv04_Vzf.js";
6
+ import { t as requiresApproval } from "./approval-required-TzNB9oQA.js";
7
+ import { o as jsonSchemaOf } from "./catalog-doc-BSo_Q_-6.js";
8
+ import { t as CliError } from "./errors-DSMnAVNa.js";
9
+ import { n as requirePeer } from "./peer-BOr_kJE1.js";
10
+ import { F as qualifiedTable, G as subjectClaimSql, I as quoteIdent, L as quoteLiteral, R as quoteTable, S as contextRefs, U as sqlFunctionNames, V as scopeTable, W as subjectClaimJsonSql, _ as andConditions, b as columnTypesOf, f as signedIn, n as accessSql, r as capabilityAccessSql, v as arrayColumnsOf, x as compileConditionSql } from "./rls-helpers-BxRuif0l.js";
11
+ import { createHash } from "node:crypto";
12
+ //#region src/cli/rls-grants.ts
13
+ /**
14
+ * The `role_permissions` grant key of a break-glass grant. It differs from
15
+ * the permission key, so `authorize()` and the table policies never count it;
16
+ * only the break-glass read asks for it.
17
+ */
18
+ function breakGlassKey(permission) {
19
+ return `${permission}#break-glass`;
20
+ }
21
+ /**
22
+ * The role and scope holding a break-glass grant. `breakGlass()` sets
23
+ * `to: authenticated`, so inside `role()` the role is on the grant itself.
24
+ */
25
+ function breakGlassHolder(item) {
26
+ if (item.access.kind === "role") return {
27
+ role: item.access.role,
28
+ scope: item.access.scope
29
+ };
30
+ const { role, scope } = item.grant;
31
+ return role === null || typeof scope !== "string" ? void 0 : {
32
+ role,
33
+ scope
34
+ };
35
+ }
36
+ function granteeItems(to) {
37
+ return Array.isArray(to) ? to : [to];
38
+ }
39
+ function relationWhere(policy, grant, grantee) {
40
+ const node = policy.resources.get(grant.permission.resource);
41
+ const where = relationCondition(grantee, node, scopeList(policy.scopes), {
42
+ resources: policy.resources,
43
+ now: { ref: "now" }
44
+ });
45
+ if (where === void 0) throw new Error(`PermDock CLI: grant ${grant.permission.key} names relation '${grantee.relation}', which ${grant.permission.resource} does not declare`);
46
+ return where;
47
+ }
48
+ /** Only a deny for `oauth-client` actors compiles: Postgres sees `client_id` and `act`, not other actor kinds. */
49
+ function actorAccess(grant, grantee, others) {
50
+ 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`);
51
+ return {
52
+ kind: "actor",
53
+ actor: "oauth-client"
54
+ };
55
+ }
56
+ function accessOf(grant, roles, anyone) {
57
+ const [held, ...more] = roles;
58
+ 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`);
59
+ if (held === void 0) return anyone ? { kind: "anyone" } : { kind: "authenticated" };
60
+ if (typeof held.scope === "object") return {
61
+ kind: "resource",
62
+ role: held.role,
63
+ resource: held.scope.resource
64
+ };
65
+ return {
66
+ kind: "role",
67
+ role: held.role,
68
+ scope: held.scope
69
+ };
70
+ }
71
+ /**
72
+ * Every grant RLS must enforce: role grants and top-level
73
+ * `definePolicy({ grants })` alike (`policy.grants` holds both). A grantee
74
+ * Postgres cannot see (plan, actor, assurance) fails with the permission named.
75
+ */
76
+ function collectGrants(policy) {
77
+ return policy.grants.map((grant) => {
78
+ const items = granteeItems(grant.to);
79
+ const roles = [];
80
+ let anyone = true;
81
+ let where = grant.where;
82
+ let delegated;
83
+ for (const item of items) switch (item.kind) {
84
+ case "role":
85
+ roles.push(item);
86
+ break;
87
+ case "anyone": break;
88
+ case "authenticated":
89
+ anyone = false;
90
+ break;
91
+ case "relation":
92
+ anyone = false;
93
+ where = andConditions(where, relationWhere(policy, grant, item));
94
+ break;
95
+ case "actor":
96
+ delegated = actorAccess(grant, item, items.length - 1);
97
+ break;
98
+ case "plan":
99
+ 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`);
100
+ default: return item;
101
+ }
102
+ const access = delegated ?? accessOf(grant, roles, anyone);
103
+ const label = access.kind === "role" || access.kind === "resource" ? access.role : access.kind;
104
+ return where === void 0 ? {
105
+ grant,
106
+ label,
107
+ access
108
+ } : {
109
+ grant,
110
+ label,
111
+ access,
112
+ where
113
+ };
114
+ });
115
+ }
116
+ /** Declared role names (bindings and `defineRoles` leaves) plus any role a top-level grant names. */
117
+ function roleNames(policy) {
118
+ const names = new Set(policy.roles.map((item) => item.name));
119
+ for (const leaf of listRoles(policy.vocabulary.roles)) names.add(leaf.key);
120
+ for (const item of collectGrants(policy)) if (item.access.kind === "role" || item.access.kind === "resource") names.add(item.access.role);
121
+ return [...names];
122
+ }
123
+ //#endregion
124
+ //#region src/cli/rls-indexes.ts
125
+ /** Postgres truncates identifiers longer than this, in bytes. */
126
+ const MAX_IDENT = 63;
127
+ /**
128
+ * The row fields `condition` compares, through `and`, `or` and `not`. A
129
+ * dotted field is a JSON path, which a plain index does not serve.
130
+ */
131
+ function conditionFields(condition) {
132
+ if (condition === void 0) return [];
133
+ switch (condition.op) {
134
+ case "and":
135
+ case "or": return condition.conditions.flatMap(conditionFields);
136
+ case "not": return conditionFields(condition.condition);
137
+ case "sqlFunction": return conditionFields(condition.twin);
138
+ case "opaque":
139
+ case "related": return [];
140
+ case "eq":
141
+ case "ne":
142
+ case "gt":
143
+ case "gte":
144
+ case "lt":
145
+ case "lte":
146
+ case "contains":
147
+ case "in":
148
+ case "notIn":
149
+ case "isNull":
150
+ case "memberOf": return condition.field.includes(".") ? [] : [condition.field];
151
+ default: return condition;
152
+ }
153
+ }
154
+ /**
155
+ * Every index the generated SQL reads through: the row columns policies
156
+ * filter on (scope keys and condition fields), and the membership tables'
157
+ * user column, followed by the scope column the helpers select.
158
+ */
159
+ function indexTargets(ctx, rowColumns) {
160
+ const targets = /* @__PURE__ */ new Map();
161
+ const add = (table, columns) => {
162
+ const target = {
163
+ table: qualifiedTable(table),
164
+ columns
165
+ };
166
+ targets.set(`${target.table}\u0000${columns[0] ?? ""}`, target);
167
+ };
168
+ for (const { table, column } of rowColumns) add(table, [column]);
169
+ for (const scope of ctx.scopes) {
170
+ const mapped = scopeTable(ctx, scope.name);
171
+ if (mapped !== void 0) add(mapped.table.table, [mapped.table.user, mapped.column]);
172
+ }
173
+ for (const source of [...ctx.sources ?? [], ...ctx.memberSources ?? []]) add(source.sql.table, [source.sql.user]);
174
+ return [...targets.values()].toSorted((a, b) => `${a.table}.${a.columns.join(",")}` < `${b.table}.${b.columns.join(",")}` ? -1 : 1);
175
+ }
176
+ /** A stable index name under Postgres' identifier limit. */
177
+ function indexName(target) {
178
+ const name = `permdock_${target.table.slice(target.table.lastIndexOf(".") + 1)}_${target.columns.join("_")}_idx`;
179
+ if (Buffer.byteLength(name) <= MAX_IDENT) return name;
180
+ return `permdock_${createHash("sha256").update(name).digest("hex").slice(0, 8)}_idx`;
181
+ }
182
+ /** `create index if not exists` for every target, one per line. */
183
+ function indexesSql(targets) {
184
+ return targets.map((target) => `create index if not exists ${quoteIdent(indexName(target))} on ${quoteTable(target.table)} (${target.columns.map(quoteIdent).join(", ")});`).join("\n");
185
+ }
186
+ //#endregion
187
+ //#region src/cli/rls-compile.ts
188
+ /** The SQL command `action` compiles to: `rls.actions` first, then the six default verbs. */
189
+ function commandFor(action, actions) {
190
+ if (actions !== void 0 && Object.hasOwn(actions, action)) {
191
+ const configured = actions[action];
192
+ return configured === "none" ? void 0 : configured;
193
+ }
194
+ switch (action) {
195
+ case "read":
196
+ case "list":
197
+ case "get": return "select";
198
+ case "create": return "insert";
199
+ case "update": return "update";
200
+ case "delete": return "delete";
201
+ default: return;
202
+ }
203
+ }
204
+ function tableFor(resource, tables) {
205
+ return tables?.[resource] ?? resource;
206
+ }
207
+ function ancestorsOf(policy, name) {
208
+ const names = [];
209
+ let current = policy.resources.get(name);
210
+ while (current?.parent !== void 0 && !names.includes(current.parent.resource)) {
211
+ names.push(current.parent.resource);
212
+ current = policy.resources.get(current.parent.resource);
213
+ }
214
+ return names;
215
+ }
216
+ function membershipField(policy, resource, holder) {
217
+ if (resource === void 0) return;
218
+ if (resource.name === holder) return resource.id ?? "id";
219
+ let current = resource;
220
+ const seen = /* @__PURE__ */ new Set();
221
+ while (current?.parent !== void 0 && !seen.has(current.name)) {
222
+ seen.add(current.name);
223
+ if (current.parent.resource === holder) return current.parent.field;
224
+ current = policy.resources.get(current.parent.resource);
225
+ }
226
+ }
227
+ function resourceCondition(item, policy, ctx) {
228
+ if (item.access.kind !== "resource") throw new Error("PermDock CLI: resourceCondition needs a resource role");
229
+ const { role, resource: roleResource } = item.access;
230
+ const target = policy.resources.get(item.grant.permission.resource);
231
+ const holders = [roleResource, ...ancestorsOf(policy, roleResource)];
232
+ const hops = [];
233
+ for (const [index, holder] of holders.entries()) {
234
+ const field = membershipField(policy, target, holder);
235
+ if (field === void 0) continue;
236
+ if (index > 0 && ctx.memberships?.resource?.[holder] === void 0) continue;
237
+ hops.push({
238
+ op: "memberOf",
239
+ scope: "resource",
240
+ field,
241
+ roles: [role],
242
+ resource: holder
243
+ });
244
+ }
245
+ return sole(hops) ?? {
246
+ op: "or",
247
+ conditions: hops
248
+ };
249
+ }
250
+ /**
251
+ * The access a link capability has to a resource-scoped grant, over the same
252
+ * holders as `resourceCondition`. It reads the claim, so ancestor hops need
253
+ * no memberships table. `undefined` when no holder is on the row's chain.
254
+ */
255
+ function capabilityAccess(item, policy, ctx) {
256
+ if (item.access.kind !== "resource") return;
257
+ const { role, resource: roleResource } = item.access;
258
+ const kinds = ctx.ownership?.kinds[role];
259
+ if (kinds !== void 0 && !kinds.includes("link")) return;
260
+ const target = policy.resources.get(item.grant.permission.resource);
261
+ const hops = [];
262
+ for (const holder of [roleResource, ...ancestorsOf(policy, roleResource)]) {
263
+ const field = membershipField(policy, target, holder);
264
+ if (field !== void 0) hops.push(capabilityAccessSql(ctx, field, holder, role, item.grant.permission.key));
265
+ }
266
+ if (hops.length === 0) return;
267
+ return hops.length === 1 ? hops[0] : hops.map(wrapSql).join(" or ");
268
+ }
269
+ function prepare(item, tables, warnings, skipClosures, actions) {
270
+ const { grant, label } = item;
271
+ if (grant.breakGlass !== void 0) {
272
+ warnings.push(`break-glass grant ${label}/${grant.permission.key} reads through permdock_break_glass_${grant.permission.resource}, not a policy`);
273
+ return;
274
+ }
275
+ if (grant.closure !== void 0 || grant.portable === false) {
276
+ if (skipClosures) {
277
+ warnings.push(`skipped non-portable grant ${label}/${grant.permission.key}`);
278
+ return;
279
+ }
280
+ throw new Error(`PermDock CLI: closure grant ${label}/${grant.permission.key} is not portable; rewrite it or pass --skip-closures`);
281
+ }
282
+ const context = [.../* @__PURE__ */ new Set([...contextRefs(item.where), ...contextRefs(grant.check)])];
283
+ if (context.length > 0) {
284
+ if (skipClosures) {
285
+ warnings.push(`skipped grant ${label}/${grant.permission.key}: it reads ${context.join(", ")}, which is not in the token`);
286
+ return;
287
+ }
288
+ 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)`);
289
+ }
290
+ if (requiresApproval(grant.approval)) {
291
+ warnings.push(`skipped approval grant ${label}/${grant.permission.key}`);
292
+ return;
293
+ }
294
+ const command = commandFor(grant.permission.action, actions);
295
+ const table = tableFor(grant.permission.resource, tables);
296
+ if (command === void 0) {
297
+ if (item.access.kind !== "role") {
298
+ warnings.push(`skipped ${label}/${grant.permission.key}: action '${grant.permission.action}' has no SQL command (rls.actions) and only role grants are seeded`);
299
+ return;
300
+ }
301
+ if (grant.validity !== void 0 && grant.effect === "allow") {
302
+ 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`);
303
+ return;
304
+ }
305
+ 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`);
306
+ return {
307
+ item,
308
+ command: "none",
309
+ table,
310
+ ...item.where === void 0 ? {} : { using: item.where },
311
+ ...grant.check === void 0 ? {} : { check: grant.check }
312
+ };
313
+ }
314
+ const using = command === "insert" ? void 0 : item.where;
315
+ const check = command === "insert" ? grant.check ?? item.where : command === "update" ? grant.check ?? item.where : void 0;
316
+ return {
317
+ item,
318
+ command,
319
+ table,
320
+ ...using === void 0 ? {} : { using },
321
+ ...check === void 0 ? {} : { check }
322
+ };
323
+ }
324
+ function signature(entry, byFields) {
325
+ const base = [
326
+ entry.item.grant.effect,
327
+ entry.using ?? null,
328
+ entry.check ?? null
329
+ ];
330
+ return JSON.stringify(byFields ? [...base, entry.item.grant.fields ?? null] : base);
331
+ }
332
+ /**
333
+ * Grant keys per permission: the key is the permission, split into
334
+ * `permission#n` when role grants carry different portable conditions (or
335
+ * effects), one key per condition group. With field views, grants that differ
336
+ * only in `fields` get their own keys too, so a view can tell them apart.
337
+ */
338
+ function assignKeys(entries, byFields) {
339
+ const groups = /* @__PURE__ */ new Map();
340
+ for (const entry of entries) {
341
+ if (entry.item.access.kind !== "role") continue;
342
+ const key = entry.item.grant.permission.key;
343
+ const byCondition = groups.get(key) ?? /* @__PURE__ */ new Map();
344
+ const sig = signature(entry, byFields);
345
+ byCondition.set(sig, [...byCondition.get(sig) ?? [], entry]);
346
+ groups.set(key, byCondition);
347
+ }
348
+ const keys = /* @__PURE__ */ new Map();
349
+ for (const [permission, byCondition] of groups) {
350
+ const lists = [...byCondition.values()];
351
+ for (const [index, list] of lists.entries()) {
352
+ const grantKey = lists.length === 1 ? permission : `${permission}#${index + 1}`;
353
+ for (const entry of list) keys.set(entry, grantKey);
354
+ }
355
+ }
356
+ return keys;
357
+ }
358
+ function compileOptional(condition, ctx) {
359
+ return condition === void 0 ? void 0 : compileConditionSql(condition, ctx);
360
+ }
361
+ function noteConditions(entry, warnings) {
362
+ const { label, grant } = entry.item;
363
+ const names = [...sqlFunctionNames(entry.using), ...sqlFunctionNames(entry.check)];
364
+ if (names.length > 0) warnings.push(`sqlFunction ${[...new Set(names)].join(", ")} on ${label}/${grant.permission.key} is portable via twin`);
365
+ if (hasConditionOp(entry.using, "opaque") || hasConditionOp(entry.check, "opaque")) warnings.push(`opaque SQL on ${label}/${grant.permission.key} is untestable app-side`);
366
+ }
367
+ /**
368
+ * Compiles every grant (role and top-level) to branches whose role check is
369
+ * a helper call keyed by grant key. Nothing in a branch is per-row except the
370
+ * portable row condition and resource-membership joins.
371
+ */
372
+ /** A Supabase token from a permanent user: anonymous sign-ins carry `is_anonymous: true`. */
373
+ const PERMANENT_USER = `((select auth.jwt()) ->> 'is_anonymous') is distinct from 'true'`;
374
+ function compileGrants(policy, ctx, tables, warnings, skipClosures) {
375
+ const items = collectGrants(policy);
376
+ const entries = items.flatMap((item) => {
377
+ const entry = prepare(item, tables, warnings, skipClosures, ctx.actions);
378
+ return entry === void 0 ? [] : [entry];
379
+ });
380
+ const keys = assignKeys(entries, ctx.fields === "views");
381
+ const rows = /* @__PURE__ */ new Map();
382
+ for (const item of items) {
383
+ const holder = item.grant.breakGlass === void 0 ? void 0 : breakGlassHolder(item);
384
+ if (holder !== void 0) {
385
+ const row = {
386
+ role: holder.role,
387
+ permission: item.grant.permission.key,
388
+ grantKey: breakGlassKey(item.grant.permission.key),
389
+ scope: holder.scope,
390
+ effect: item.grant.effect
391
+ };
392
+ rows.set(`${row.role}\u0000${row.grantKey}\u0000${row.scope}`, row);
393
+ }
394
+ }
395
+ const branches = [];
396
+ const rowColumns = /* @__PURE__ */ new Map();
397
+ const filters = (table, column) => {
398
+ rowColumns.set(`${table}\u0000${column}`, {
399
+ table,
400
+ column
401
+ });
402
+ };
403
+ const typed = /* @__PURE__ */ new Map();
404
+ const contextFor = (name) => {
405
+ const known = typed.get(name);
406
+ if (known !== void 0) return known;
407
+ const node = policy.resources.get(name);
408
+ const schema = node === void 0 ? void 0 : jsonSchemaOf(node);
409
+ const next = {
410
+ ...ctx,
411
+ columnTypes: columnTypesOf(schema),
412
+ arrayColumns: arrayColumnsOf(schema)
413
+ };
414
+ typed.set(name, next);
415
+ return next;
416
+ };
417
+ for (const entry of entries) {
418
+ const { item, command, table } = entry;
419
+ const { grant, access, label } = item;
420
+ if (command === "none") {
421
+ const grantKey = keys.get(entry);
422
+ if (access.kind === "role" && grantKey !== void 0) {
423
+ const row = {
424
+ role: access.role,
425
+ permission: grant.permission.key,
426
+ grantKey,
427
+ scope: access.scope,
428
+ effect: grant.effect
429
+ };
430
+ rows.set(`${row.role}\u0000${row.grantKey}\u0000${row.scope}`, row);
431
+ }
432
+ continue;
433
+ }
434
+ const rowCtx = contextFor(item.grant.permission.resource);
435
+ noteConditions(entry, warnings);
436
+ for (const field of [...conditionFields(entry.using), ...conditionFields(entry.check)]) filters(table, field);
437
+ const grantKey = keys.get(entry);
438
+ let accessExpr;
439
+ if (access.kind === "role" && grantKey !== void 0) {
440
+ const column = access.scope === "global" ? void 0 : policy.scopes.find((scope) => scope.name === access.scope)?.key;
441
+ accessExpr = accessSql(ctx, access.scope, grantKey, column);
442
+ if (column !== void 0) filters(table, column);
443
+ const row = {
444
+ role: access.role,
445
+ permission: grant.permission.key,
446
+ grantKey,
447
+ scope: access.scope,
448
+ effect: grant.effect
449
+ };
450
+ rows.set(`${row.role}\u0000${row.grantKey}\u0000${row.scope}`, row);
451
+ }
452
+ const linkOnly = access.kind === "resource" && ctx.capabilities === true && ctx.memberships?.resource?.[access.resource] === void 0;
453
+ if (access.kind === "actor") accessExpr = `${subjectClaimSql(ctx, "client_id")} is not null or ${subjectClaimJsonSql(ctx, "act")} is not null`;
454
+ if (access.kind === "resource" && !linkOnly) accessExpr = compileConditionSql(resourceCondition(item, policy, ctx), ctx);
455
+ if (linkOnly) warnings.push(`no ${access.resource} memberships table: only link capabilities reach ${label}/${grant.permission.key}`);
456
+ const validity = validitySql(grant.validity);
457
+ accessExpr = andSql(accessExpr, validity);
458
+ if (ctx.anonymousSignIns === "deny" && access.kind !== "anyone") accessExpr = andSql(accessExpr, PERMANENT_USER);
459
+ const using = compileOptional(entry.using, rowCtx);
460
+ const check = compileOptional(entry.check, rowCtx);
461
+ const fields = grant.fields === void 0 ? {} : { fields: grant.fields };
462
+ if (!linkOnly) branches.push({
463
+ table,
464
+ command,
465
+ effect: grant.effect,
466
+ roles: access.kind === "anyone" ? ["anon", "authenticated"] : ["authenticated"],
467
+ label,
468
+ resource: grant.permission.resource,
469
+ permissionKey: grant.permission.key,
470
+ ...fields,
471
+ ...grantKey === void 0 ? {} : { grantKey },
472
+ ...accessExpr === void 0 ? {} : { access: accessExpr },
473
+ ...using === void 0 ? {} : { using },
474
+ ...check === void 0 ? {} : { check }
475
+ });
476
+ const linked = ctx.capabilities === true ? capabilityAccess(item, policy, ctx) : void 0;
477
+ if (linked !== void 0) branches.push({
478
+ table,
479
+ command,
480
+ effect: grant.effect,
481
+ roles: ["anon"],
482
+ label,
483
+ resource: grant.permission.resource,
484
+ permissionKey: grant.permission.key,
485
+ ...fields,
486
+ access: andSql(linked, validity) ?? linked,
487
+ ...using === void 0 ? {} : { using },
488
+ ...check === void 0 ? {} : { check }
489
+ });
490
+ }
491
+ return {
492
+ branches: ensureSelectCoverage(branches, warnings),
493
+ rolePermissions: withAliasRows(policy, [...rows.values()]),
494
+ rowColumns: [...rowColumns.values()]
495
+ };
496
+ }
497
+ /**
498
+ * Each row again under every key its permission was renamed from, so SQL that
499
+ * still calls `permdock_has('<old key>')` keeps the access the current key
500
+ * has. A split grant key (`key#n`) keeps its suffix; break-glass rows are not
501
+ * copied.
502
+ */
503
+ function withAliasRows(policy, rows) {
504
+ const former = new Map(listPermissions(policy.permissions).map((leaf) => [leaf.key, formerKeys(leaf)]));
505
+ const out = [...rows];
506
+ for (const row of rows) {
507
+ const suffix = row.grantKey.slice(row.permission.length);
508
+ if (!row.grantKey.startsWith(row.permission) || suffix !== "" && !/^#\d+$/u.test(suffix)) continue;
509
+ for (const old of former.get(row.permission) ?? []) out.push({
510
+ ...row,
511
+ permission: old,
512
+ grantKey: `${old}${suffix}`
513
+ });
514
+ }
515
+ return out;
516
+ }
517
+ /**
518
+ * Postgres needs SELECT access to find rows for UPDATE / DELETE and for
519
+ * RETURNING, so a table with only update or delete grants gets matching
520
+ * SELECT branches.
521
+ */
522
+ function ensureSelectCoverage(branches, warnings) {
523
+ const extra = [];
524
+ const readable = new Set(branches.filter((item) => item.command === "select" && item.effect === "allow").map((item) => item.table));
525
+ const covered = /* @__PURE__ */ new Set();
526
+ for (const item of branches) {
527
+ if (item.effect !== "allow" || item.command !== "update" && item.command !== "delete" || readable.has(item.table)) continue;
528
+ const { check: _check, ...rest } = item;
529
+ extra.push({
530
+ ...rest,
531
+ command: "select",
532
+ coverage: true
533
+ });
534
+ if (!covered.has(item.table)) {
535
+ covered.add(item.table);
536
+ warnings.push(`added SELECT coverage for ${item.table} (${item.permissionKey})`);
537
+ }
538
+ }
539
+ return [...branches, ...extra];
540
+ }
541
+ /** True when `sql` is one parenthesised expression, so AND / OR need not wrap it again. */
542
+ function isWrapped(sql) {
543
+ if (!sql.startsWith("(") || !sql.endsWith(")")) return false;
544
+ let depth = 0;
545
+ let quoted = false;
546
+ for (let index = 0; index < sql.length; index += 1) {
547
+ const ch = sql[index];
548
+ if (ch === "'") quoted = !quoted;
549
+ else if (!quoted && ch === "(") depth += 1;
550
+ else if (!quoted && ch === ")") {
551
+ depth -= 1;
552
+ if (depth === 0 && index < sql.length - 1) return false;
553
+ }
554
+ }
555
+ return depth === 0;
556
+ }
557
+ function wrapSql(sql) {
558
+ return isWrapped(sql) ? sql : `(${sql})`;
559
+ }
560
+ /**
561
+ * The grant's `validFrom` / `validUntil` as a clock check: `from` inclusive,
562
+ * `until` exclusive, matching the in-process evaluator.
563
+ */
564
+ function validitySql(validity) {
565
+ if (validity === void 0) return;
566
+ return andSql(validity.from === void 0 ? void 0 : `now() >= to_timestamp(${validity.from})`, validity.until === void 0 ? void 0 : `now() < to_timestamp(${validity.until})`);
567
+ }
568
+ function andSql(...parts) {
569
+ const present = parts.filter((part) => part !== void 0 && part !== "true");
570
+ if (present.length === 0) return;
571
+ return present.length === 1 ? present[0] : present.map(wrapSql).join(" and ");
572
+ }
573
+ /** `USING` and `WITH CHECK` for a branch: its access check ANDed with its row conditions. */
574
+ function branchClauses(branch) {
575
+ const using = branch.command === "insert" ? void 0 : andSql(branch.access, branch.using) ?? "true";
576
+ const check = branch.command === "insert" || branch.command === "update" ? andSql(branch.access, branch.check) ?? "true" : void 0;
577
+ return {
578
+ ...using === void 0 ? {} : { using },
579
+ ...check === void 0 ? {} : { check }
580
+ };
581
+ }
582
+ //#endregion
583
+ //#region src/cli/rls-policies.ts
584
+ /** Each database role gets its own policy, so no role sees two permissive policies for one command. */
585
+ const AUDIENCES = ["authenticated", "anon"];
586
+ const DEFAULT_POLICY_NAME = "{table}_{op}";
587
+ const DEFAULT_PER_ROLE_NAME = "{role}_{permission}";
588
+ const PLACEHOLDER = /\{(table|op|role|permission)\}/gu;
589
+ function sanitize(name) {
590
+ return name.replaceAll(/[^A-Za-z0-9_]/g, "_");
591
+ }
592
+ function render(template, values) {
593
+ return sanitize(template.replaceAll(PLACEHOLDER, (_match, key) => values[key]));
594
+ }
595
+ /** Rejects a template that cannot name every policy of the chosen shape uniquely. */
596
+ function assertPolicyName(template, perRole) {
597
+ 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");
598
+ 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");
599
+ }
600
+ function orSql(parts) {
601
+ const distinct = [...new Set(parts)];
602
+ if (distinct.includes("true")) return "true";
603
+ return sole(distinct) ?? distinct.map(wrapSql).join(" or ");
604
+ }
605
+ function negate(sql) {
606
+ return sql === void 0 ? void 0 : `not (${sql})`;
607
+ }
608
+ function policyOf(name, branch, using, check) {
609
+ const deny = branch.effect === "deny";
610
+ const policy = {
611
+ name,
612
+ table: branch.table,
613
+ command: branch.command,
614
+ effect: branch.effect,
615
+ roles: branch.roles
616
+ };
617
+ const finalUsing = deny ? negate(using) : using;
618
+ const finalCheck = deny ? negate(check) : check;
619
+ if (finalUsing !== void 0) policy.using = finalUsing;
620
+ if (finalCheck !== void 0) policy.check = finalCheck;
621
+ return policy;
622
+ }
623
+ function uniqueName(names, name) {
624
+ const seen = names.get(name) ?? 0;
625
+ names.set(name, seen + 1);
626
+ return seen === 0 ? name : `${name}_${seen + 1}`;
627
+ }
628
+ function perRolePolicies(branches, template) {
629
+ const names = /* @__PURE__ */ new Map();
630
+ return branches.map((branch) => {
631
+ const clauses = branchClauses(branch);
632
+ const deny = branch.effect === "deny";
633
+ const base = render(template, {
634
+ table: branch.table,
635
+ op: branch.command,
636
+ role: branch.label,
637
+ permission: branch.permissionKey
638
+ });
639
+ const name = `${deny ? "deny_" : ""}${base}${branch.coverage === true ? "_select_coverage" : ""}`;
640
+ return policyOf(uniqueName(names, name), branch, clauses.using, clauses.check);
641
+ });
642
+ }
643
+ /**
644
+ * Branches of one grant-key group share their row condition, so the group
645
+ * becomes one OR branch whose access ORs the helper calls of each scope.
646
+ */
647
+ function mergeGroups(branches) {
648
+ const merged = [];
649
+ const byKey = /* @__PURE__ */ new Map();
650
+ for (const branch of branches) {
651
+ const id = branch.grantKey === void 0 ? void 0 : `${branch.table}\u0000${branch.command}\u0000${branch.grantKey}\u0000${branch.coverage === true}`;
652
+ const entry = id === void 0 ? void 0 : byKey.get(id);
653
+ if (entry === void 0) {
654
+ const created = {
655
+ branch,
656
+ accesses: branch.access === void 0 ? [] : [branch.access]
657
+ };
658
+ if (id !== void 0) byKey.set(id, created);
659
+ merged.push(created);
660
+ continue;
661
+ }
662
+ if (branch.access !== void 0 && !entry.accesses.includes(branch.access)) entry.accesses.push(branch.access);
663
+ }
664
+ return merged.map(({ branch, accesses }) => accesses.length <= 1 ? branch : withAccess(branch, orSql(accesses)));
665
+ }
666
+ function withAccess(branch, access) {
667
+ return {
668
+ ...branch,
669
+ access
670
+ };
671
+ }
672
+ function collapsedPolicies(branches, template) {
673
+ const groups = /* @__PURE__ */ new Map();
674
+ for (const branch of mergeGroups(branches)) {
675
+ const id = `${branch.table}\u0000${branch.command}\u0000${branch.effect}`;
676
+ groups.set(id, [...groups.get(id) ?? [], branch]);
677
+ }
678
+ const names = /* @__PURE__ */ new Map();
679
+ return [...groups.values()].flatMap((group) => AUDIENCES.flatMap((audience) => {
680
+ const members = group.filter((branch) => branch.roles.includes(audience));
681
+ const [first] = members;
682
+ if (first === void 0) return [];
683
+ const deny = first.effect === "deny";
684
+ const clauses = members.map(branchClauses);
685
+ const usings = clauses.flatMap((item) => item.using === void 0 ? [] : [item.using]);
686
+ const checks = clauses.flatMap((item) => item.check === void 0 ? [] : [item.check]);
687
+ const base = render(template, {
688
+ table: first.table,
689
+ op: first.command,
690
+ role: first.label,
691
+ permission: first.permissionKey
692
+ });
693
+ return [policyOf(uniqueName(names, `${deny ? "deny_" : ""}${base}${audience === "anon" ? "_anon" : ""}`), {
694
+ ...first,
695
+ roles: [audience]
696
+ }, usings.length === 0 ? void 0 : orSql(usings), checks.length === 0 ? void 0 : orSql(checks))];
697
+ }));
698
+ }
699
+ /**
700
+ * Assembles policies. The default is one PERMISSIVE policy per table,
701
+ * command and database role (Splinter `multiple_permissive_policies` stays
702
+ * quiet), with denies in one RESTRICTIVE policy per table, command and role.
703
+ */
704
+ function assemblePolicies(branches, shape) {
705
+ const template = shape.name ?? (shape.perRole ? DEFAULT_PER_ROLE_NAME : DEFAULT_POLICY_NAME);
706
+ assertPolicyName(template, shape.perRole);
707
+ return shape.perRole ? perRolePolicies(branches, template) : collapsedPolicies(branches, template);
708
+ }
709
+ //#endregion
710
+ //#region src/cli/rls-fields.ts
711
+ /** Names of the field-view objects. Part of the SQL contract. */
712
+ const FIELD_VIEWS = {
713
+ /** `<table>_visible`: the `security_invoker` view clients read. */
714
+ view: "_visible",
715
+ /** `<table>_visible_fields`: the owner-rights companion `--revoke-columns` adds. */
716
+ companion: "_visible_fields",
717
+ /** The companion's row-key column, joined to the base table's key. */
718
+ key: "permdock_key",
719
+ /** Marks the companion so doctor PD022 knows it reads as its owner on purpose. */
720
+ comment: "permdock:field-companion"
721
+ };
722
+ function covers(branch, column) {
723
+ return branch.fields === void 0 || branch.fields.includes(column);
724
+ }
725
+ /**
726
+ * A read grant that only shapes columns: a field-limited deny (it never
727
+ * denies the row) or an allow with an empty list (it grants nothing). With
728
+ * field views it leaves the row policy and lives in the view's masks.
729
+ */
730
+ function fieldOnly(branch) {
731
+ if (branch.command !== "select" || branch.fields === void 0) return false;
732
+ return branch.effect === "deny" || branch.fields.length === 0;
733
+ }
734
+ /** Branches the row policies keep when field views compile. */
735
+ function rowBranches(branches) {
736
+ return branches.filter((branch) => !fieldOnly(branch));
737
+ }
738
+ /**
739
+ * Whether the reader is signed in, for branches with no helper call: a grant
740
+ * to any signed-in user relies on `to authenticated` in its policy, which a
741
+ * view does not have.
742
+ */
743
+ function audience(ctx, branch) {
744
+ if (branch.access !== void 0 || branch.roles.length !== 1) return;
745
+ if (branch.roles[0] === "authenticated") return signedIn(ctx);
746
+ return branch.roles[0] === "anon" ? `not (${signedIn(ctx)})` : void 0;
747
+ }
748
+ function clause(ctx, branch) {
749
+ return andSql(audience(ctx, branch), branchClauses(branch).using) ?? "true";
750
+ }
751
+ /**
752
+ * `can(permission, row, { field })` in SQL: an allow that covers the column
753
+ * holds for the row and no covering deny does. Every access term is the
754
+ * uncorrelated helper call the row policy uses, so it runs once per statement.
755
+ */
756
+ function maskSql(ctx, allows, denies, column) {
757
+ const allowed = allows.filter((branch) => covers(branch, column)).map((branch) => clause(ctx, branch));
758
+ if (allowed.length === 0) return "false";
759
+ const denied = denies.filter((branch) => covers(branch, column)).map((branch) => clause(ctx, branch));
760
+ const allow = orSql(allowed);
761
+ if (denied.length === 0) return allow;
762
+ const deny = orSql(denied);
763
+ return allow === "true" ? `not ${wrapSql(deny)}` : `${wrapSql(allow)} and not ${wrapSql(deny)}`;
764
+ }
765
+ function schemaColumns(policy, resource) {
766
+ const node = policy.resources.get(resource);
767
+ const schema = node === void 0 ? null : jsonSchemaOf(node);
768
+ const properties = schema !== null && typeof schema === "object" ? schema.properties : void 0;
769
+ return properties !== null && typeof properties === "object" ? Object.keys(properties) : void 0;
770
+ }
771
+ function viewName(table, suffix) {
772
+ return `${table}${suffix}`;
773
+ }
774
+ /**
775
+ * One view per table whose read grants limit fields. A column is restricted
776
+ * when some read allow lists fields without it or some read deny lists it;
777
+ * every other column, and the row key, passes through unchanged.
778
+ */
779
+ function fieldViews(policy, ctx, branches, options, warnings) {
780
+ const byTable = /* @__PURE__ */ new Map();
781
+ for (const branch of branches) {
782
+ if (branch.command !== "select" || branch.coverage === true) continue;
783
+ byTable.set(branch.table, [...byTable.get(branch.table) ?? [], branch]);
784
+ }
785
+ const views = [];
786
+ for (const [table, reads] of byTable) {
787
+ const allows = reads.filter((branch) => branch.effect === "allow" && branch.fields?.length !== 0);
788
+ const denies = reads.filter((branch) => branch.effect === "deny");
789
+ const limited = reads.some((branch) => branch.fields !== void 0);
790
+ const resource = reads.find((branch) => branch.resource !== void 0)?.resource;
791
+ if (!limited || allows.length === 0 || resource === void 0) continue;
792
+ const names = schemaColumns(policy, resource);
793
+ 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}`);
794
+ const key = policy.resources.get(resource)?.id ?? "id";
795
+ const restricted = (column) => column !== key && (allows.some((branch) => branch.fields !== void 0 && !branch.fields.includes(column)) || denies.some((branch) => branch.fields?.includes(column) === true));
796
+ const columns = names.map((name) => {
797
+ quoteIdent(name);
798
+ return restricted(name) ? {
799
+ name,
800
+ mask: maskSql(ctx, allows, denies, name)
801
+ } : { name };
802
+ });
803
+ if (columns.every((column) => column.mask === void 0)) continue;
804
+ const view = viewName(table, FIELD_VIEWS.view);
805
+ 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`);
806
+ const hidden = columns.filter((column) => column.mask !== void 0).map((column) => column.name);
807
+ 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`);
808
+ views.push({
809
+ resource,
810
+ table,
811
+ view,
812
+ key,
813
+ columns,
814
+ roles: reads.some((branch) => branch.roles.includes("anon")) ? ["anon", "authenticated"] : ["authenticated"],
815
+ ...options.revokeColumns ? { companion: viewName(table, FIELD_VIEWS.companion) } : {}
816
+ });
817
+ }
818
+ return views;
819
+ }
820
+ /** Columns of `view`'s table that `anon` and `authenticated` keep on the base table with `--revoke-columns`. */
821
+ function readableColumns(view) {
822
+ return view.columns.filter((column) => column.mask === void 0).map((column) => column.name);
823
+ }
824
+ function restrictedColumns(view) {
825
+ return view.columns.filter((column) => column.mask !== void 0).map((column) => column.name);
826
+ }
827
+ function columnList(names) {
828
+ return names.map(quoteIdent).join(", ");
829
+ }
830
+ function selectList(lines) {
831
+ return lines.map((line) => ` ${line}`).join(",\n");
832
+ }
833
+ function grantView(name, roles) {
834
+ return [`revoke all on table ${quoteTable(qualifiedTable(name))} from anon, authenticated, public;`, `grant select on table ${quoteTable(qualifiedTable(name))} to ${roles.join(", ")};`].join("\n");
835
+ }
836
+ function inlineViewSql(view) {
837
+ 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)}`);
838
+ return `create or replace view ${quoteTable(qualifiedTable(view.view))} with (security_invoker = true) as
839
+ select
840
+ ${selectList(targets)}
841
+ from ${quoteTable(qualifiedTable(view.table))};`;
842
+ }
843
+ function companionSql(view, companion) {
844
+ const restricted = view.columns.filter((column) => column.mask !== void 0);
845
+ 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)}`)];
846
+ const any = orSql(restricted.map((column) => column.mask ?? "false"));
847
+ return `create or replace view ${quoteTable(qualifiedTable(companion))} with (security_barrier = true) as
848
+ select
849
+ ${selectList(targets)}
850
+ from ${quoteTable(qualifiedTable(view.table))}
851
+ where ${any};
852
+ comment on view ${quoteTable(qualifiedTable(companion))} is ${quoteLiteral(`${FIELD_VIEWS.comment} ${view.view}`)};`;
853
+ }
854
+ function joinedViewSql(view, companion) {
855
+ const targets = view.columns.map((column) => column.mask === void 0 ? `t.${quoteIdent(column.name)}` : `f.${quoteIdent(column.name)}`);
856
+ return `create or replace view ${quoteTable(qualifiedTable(view.view))} with (security_invoker = true) as
857
+ select
858
+ ${selectList(targets)}
859
+ from ${quoteTable(qualifiedTable(view.table))} t
860
+ left join ${quoteTable(qualifiedTable(companion))} f on f.${quoteIdent(FIELD_VIEWS.key)} = t.${quoteIdent(view.key)};`;
861
+ }
862
+ /** `select` on only the unrestricted columns (and the key) of the base table, for `--revoke-columns`. */
863
+ function columnGrantSql(view, role) {
864
+ return `grant select (${columnList(readableColumns(view))}) on table ${quoteTable(qualifiedTable(view.table))} to ${role};`;
865
+ }
866
+ function columnRevokeSql(view) {
867
+ return `revoke select (${columnList(restrictedColumns(view))}) on table ${quoteTable(qualifiedTable(view.table))} from anon, authenticated;`;
868
+ }
869
+ /**
870
+ * The view SQL: the `security_invoker` view, and with `--revoke-columns` the
871
+ * owner-rights companion it joins for the restricted columns. The companion
872
+ * masks every column with the full field decision and keeps only rows where
873
+ * one is readable, so reading it directly shows nothing `pick` would not.
874
+ */
875
+ function fieldViewsSql(views) {
876
+ return views.map((view) => {
877
+ const head = `-- field view over ${view.table}: ${restrictedColumns(view).join(", ")} read as null unless a read grant covers the column for the row`;
878
+ if (view.companion === void 0) return [
879
+ head,
880
+ inlineViewSql(view),
881
+ grantView(view.view, view.roles)
882
+ ].join("\n");
883
+ return [
884
+ head,
885
+ `-- ${view.companion} reads ${view.table} as its owner; ${view.view} reads the rows as the caller and joins it`,
886
+ companionSql(view, view.companion),
887
+ grantView(view.companion, view.roles),
888
+ joinedViewSql(view, view.companion),
889
+ grantView(view.view, view.roles)
890
+ ].join("\n");
891
+ }).join("\n\n");
892
+ }
893
+ //#endregion
894
+ //#region src/cli/pg.ts
895
+ const CONNECT_TIMEOUT_MS = 1e4;
896
+ const STATEMENT_TIMEOUT_MS = 6e4;
897
+ function loadPg(command) {
898
+ return requirePeer(() => import("pg"), "pg", command);
899
+ }
900
+ function options(db) {
901
+ return {
902
+ connectionString: db,
903
+ connectionTimeoutMillis: CONNECT_TIMEOUT_MS,
904
+ statement_timeout: STATEMENT_TIMEOUT_MS
905
+ };
906
+ }
907
+ /** Ctrl-C ends the connection, so a query that hangs cannot keep the process alive. */
908
+ function endOnInterrupt(end) {
909
+ const interrupt = () => {
910
+ end().catch(() => void 0);
911
+ process.exitCode = 130;
912
+ };
913
+ process.once("SIGINT", interrupt);
914
+ return async () => {
915
+ process.off("SIGINT", interrupt);
916
+ await end();
917
+ };
918
+ }
919
+ function unreachable(command, cause) {
920
+ return new CliError("unavailable", `PermDock CLI: ${command.replace(/^permdock /u, "")} could not connect`, { cause });
921
+ }
922
+ /** One connection, for commands that run a transaction. */
923
+ async function connectPg(db, command) {
924
+ const client = new (await (loadPg(command))).Client(options(db));
925
+ try {
926
+ await client.connect();
927
+ } catch (cause) {
928
+ throw unreachable(command, cause);
929
+ }
930
+ return {
931
+ query: (sql, values) => client.query(sql, values),
932
+ end: endOnInterrupt(() => client.end())
933
+ };
934
+ }
935
+ /** A small pool, for independent catalog reads that can run in parallel. */
936
+ async function connectPgPool(db, command) {
937
+ const pool = new (await (loadPg(command))).Pool({
938
+ ...options(db),
939
+ max: 4
940
+ });
941
+ try {
942
+ (await pool.connect()).release();
943
+ } catch (cause) {
944
+ await pool.end();
945
+ throw unreachable(command, cause);
946
+ }
947
+ return {
948
+ query: (sql, values) => pool.query(sql, values),
949
+ end: endOnInterrupt(() => pool.end())
950
+ };
951
+ }
952
+ //#endregion
953
+ export { breakGlassKey as _, columnRevokeSql as a, rowBranches as c, commandFor as d, compileGrants as f, breakGlassHolder as g, indexesSql as h, columnGrantSql as i, viewName as l, indexTargets as m, connectPgPool as n, fieldViews as o, tableFor as p, FIELD_VIEWS as r, fieldViewsSql as s, connectPg as t, assemblePolicies as u, collectGrants as v, roleNames as y };