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,3471 @@
1
+ import { n as isReadonlyArray, r as sole, t as compact } from "./compact-y6vfu2_f.js";
2
+ import { n as freezeDeep, t as freezeCopy } from "./freeze-CrU8nQeX.js";
3
+ import { E as ownGet, T as isForbiddenKey, _ as listPermissions, a as formerKeys, c as getResource, d as isEdgeRelation, f as isFieldRelation, i as findPermission, m as isPrincipalRelation, o as formerScopes, r as expandRelation } from "./permissions-DVoF6dMt.js";
4
+ import { a as hasConditionOp } from "./refs-KYb4ntaz.js";
5
+ import { d as normalizeApproval, f as normalizeAssurance, g as applyQuota, i as declaredRoleNames$1, l as levelCondition, m as role, n as assertApprovalRelations, s as grantList, u as levelNames, v as normalizeWhere } from "./policy-xyWg7QdR.js";
6
+ import { n as PermDockValidationError } from "./validation-error-CnjZ4t92.js";
7
+ import { a as wireDenials } from "./problem-details-_AMOYz-w.js";
8
+ import { a as deniedMessage, i as approvalMessage, n as PermDockDeniedError, t as PermDockApprovalRequiredError } from "./errors-Cz5zn0mW.js";
9
+ import { n as sameId } from "./ids-DC4V4CFu.js";
10
+ import { a as normalizeMemberships, c as rootScope, d as scopeList, f as subjectForPermission, i as keepsPermission, l as scopeChain, m as tenantOf, o as resolveScope, s as rootMembershipId, u as scopeIdOf } from "./scopes-CVdPrWN-.js";
11
+ import { a as whereFromGrants, c as rowIdOf, d as isArazzoSimulateInput, f as simulateArazzo, i as signSnapshot, l as rowValues, p as evaluateCondition, r as snapshotGrant, s as isRowPair, t as buildSnapshot } from "./snapshot-Enxd0n-s.js";
12
+ import { t as parseDuration } from "./duration-xK2jGFVc.js";
13
+ import { D as synthesiseRole, E as listRoles, S as findRole, _ as resourceRoleCondition, a as authenticated, d as matchGrantee, i as assurance, m as relationCondition, o as combineWhere, r as asGrantee, s as flattenGrantee, w as isRole } from "./grantee-Cv5Sogfv.js";
14
+ import { t as canonicalJson } from "./canonical-json-DemiK4Vp.js";
15
+ import { n as pickVisible, r as sanitizeContext, t as grantCoversField } from "./fields-BMl1RxoX.js";
16
+ import { a as isMembershipExpired, d as partitionsOf, f as relatesTo, g as tenantsOf, h as scopeField, i as inTeam, o as matchScopedMembership, p as resolveActiveTenant, r as heldRoleNamesIn, t as isActive, u as nowSeconds } from "./validity-uOp8UpYn.js";
17
+ import { t as requiresApproval } from "./approval-required-TzNB9oQA.js";
18
+ import { r as mergeHostedGrants, t as isPortableCondition } from "./hosted-DJQw46hn.js";
19
+ import { n as isThenable, t as ignoreRejection } from "./thenable-okc2xDsj.js";
20
+ import { t as byCodePoint } from "./compare-pfyVnBjE.js";
21
+ import { a as relationWalk, i as relationReader, n as pendingRelations, o as resolveRelated, r as relationId } from "./relations-cjOL01hZ.js";
22
+ import { i as requiresStandIn, n as coversRequirements, r as delegatedPermissions, t as coveredByDelegation } from "./delegation-D8pUEuce.js";
23
+ import { t as resourceIdOf } from "./resource-ref-CaS9yVPi.js";
24
+ import { n as payloadDigest, r as versionOf, t as decisionToken } from "./token-CIWxJOCh.js";
25
+ import { i as isSubject, r as isPrincipal, t as anonymousSubject } from "./subject-C6dLxqHU.js";
26
+ //#region src/core/approval-policies.ts
27
+ /** The denial detail when an `ApprovalPolicySource` fails: every call an allow would grant denies with reason `approval`. */
28
+ const APPROVAL_POLICY_UNAVAILABLE = "approval-policy-unavailable";
29
+ function memoryApprovalPolicies(policies) {
30
+ const entries = [...policies];
31
+ return Object.freeze({ approvalPoliciesFor(query) {
32
+ return entries.filter((entry) => entry.tenant === void 0 || query.tenants.includes(entry.tenant));
33
+ } });
34
+ }
35
+ function isRecord(value) {
36
+ return value !== null && typeof value === "object" && !Array.isArray(value);
37
+ }
38
+ function isStringList(value) {
39
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
40
+ }
41
+ function checkOne(policy, raw) {
42
+ if (!isRecord(raw) || typeof raw["permission"] !== "string") return { problem: "invalid" };
43
+ const permission = findPermission(policy.permissions, raw["permission"]);
44
+ if (permission === void 0) return { problem: "unknown-permission" };
45
+ const { tenant, actors, where, check, approval } = raw;
46
+ if (tenant !== void 0 && typeof tenant !== "string" || actors !== void 0 && !isStringList(actors) || where !== void 0 && !isPortableCondition(where) || check !== void 0 && !isPortableCondition(check) || approval !== "human" && !isRecord(approval)) return { problem: "invalid" };
47
+ if (where !== void 0 && permission.kind !== "instance") return { problem: "where-on-collection" };
48
+ let normalized;
49
+ try {
50
+ normalized = normalizeApproval(approval, permission.key);
51
+ if (normalized !== void 0) assertApprovalRelations([{
52
+ permission,
53
+ approval: normalized
54
+ }], policy.resources);
55
+ } catch {
56
+ return { problem: "invalid" };
57
+ }
58
+ if (normalized === void 0) return { problem: "invalid" };
59
+ if (normalized !== "human" && normalized.staleOn !== void 0 && (permission.kind !== "instance" || policy.resources.get(permission.resource)?.version === void 0)) return { problem: "stale-on-without-version" };
60
+ return { entry: compact({
61
+ permission: permission.key,
62
+ tenant,
63
+ actors: actors === void 0 ? void 0 : new Set(actors),
64
+ where: where === void 0 ? void 0 : normalizeWhere(where),
65
+ check: check === void 0 ? void 0 : normalizeWhere(check),
66
+ approval: normalized
67
+ }) };
68
+ }
69
+ /**
70
+ * Checks one entry against the policy the way `approvalPoliciesFor` loads
71
+ * it, for an application to refuse a bad entry when it is saved instead of
72
+ * finding every call denied. Never throws.
73
+ */
74
+ function validateApprovalPolicy(policy, entry) {
75
+ try {
76
+ const checked = checkOne(policy, entry);
77
+ return "problem" in checked ? {
78
+ ok: false,
79
+ problem: checked.problem
80
+ } : { ok: true };
81
+ } catch {
82
+ return {
83
+ ok: false,
84
+ problem: "invalid"
85
+ };
86
+ }
87
+ }
88
+ /**
89
+ * One raw entry checked against the policy: `null` when it names no
90
+ * permission the policy declares (it applies to nothing), `undefined` when
91
+ * it does not load.
92
+ */
93
+ function loadOne(policy, raw) {
94
+ const checked = checkOne(policy, raw);
95
+ if ("entry" in checked) return checked.entry;
96
+ return checked.problem === "unknown-permission" ? null : void 0;
97
+ }
98
+ function loadAll(policy, raw) {
99
+ if (!Array.isArray(raw)) return "failed";
100
+ const out = [];
101
+ for (const item of raw) {
102
+ const loaded = loadOne(policy, item);
103
+ if (loaded === void 0) return "failed";
104
+ if (loaded !== null) out.push(loaded);
105
+ }
106
+ return out;
107
+ }
108
+ /** Reads the source once for `tenants`; a throw or an invalid entry loads as `"failed"`. */
109
+ function approvalPoliciesFor(policy, source, tenants, auth) {
110
+ if (source === void 0) return;
111
+ const threw = () => {
112
+ auth.push({
113
+ reason: "source-threw",
114
+ source: "approvalPolicies"
115
+ });
116
+ return "failed";
117
+ };
118
+ let raw;
119
+ try {
120
+ raw = source.approvalPoliciesFor({ tenants });
121
+ } catch {
122
+ return threw();
123
+ }
124
+ if (isThenable(raw)) return Promise.resolve(raw).then((value) => loadAll(policy, value), threw);
125
+ return loadAll(policy, raw);
126
+ }
127
+ function matches(entry, tenant, subject, current, next, now, scopes) {
128
+ if (entry.tenant !== void 0 && entry.tenant !== tenant) return false;
129
+ if (entry.actors !== void 0 && (subject.actor === void 0 || !entry.actors.has(subject.actor.kind))) return false;
130
+ if (entry.where !== void 0 && !evaluateCondition(entry.where, current, subject, now, scopes)) return false;
131
+ return entry.check === void 0 || evaluateCondition(entry.check, next ?? current, subject, now, scopes);
132
+ }
133
+ function asStages(approval) {
134
+ if (approval === "human") return [{ by: authenticated() }];
135
+ if (approval.stages !== void 0) return approval.stages;
136
+ return [compact({
137
+ by: approval.by ?? authenticated(),
138
+ quorum: approval.quorum
139
+ })];
140
+ }
141
+ /** An entry's stages, each carrying the entry's escalation unless it has its own. */
142
+ function entryStages(approval) {
143
+ const stages = asStages(approval);
144
+ if (approval === "human" || approval.escalation === void 0) return stages;
145
+ const escalation = approval.escalation;
146
+ return stages.map((stage) => stage.escalation === void 0 ? compact({
147
+ by: stage.by,
148
+ quorum: stage.quorum,
149
+ escalation
150
+ }) : stage);
151
+ }
152
+ function shorter(a, b) {
153
+ if (a === void 0) return b;
154
+ if (b === void 0) return a;
155
+ return (parseDuration(b) ?? Infinity) < (parseDuration(a) ?? Infinity) ? b : a;
156
+ }
157
+ /**
158
+ * `code` with every matching entry added as further stages: the result
159
+ * needs all of them (`'sequential'` when any part is ordered), keeps the
160
+ * code's escalation, the shortest `ttl`, and `distinct` unless every part
161
+ * opts out. Without a matching entry, `code` unchanged.
162
+ */
163
+ function tightenApproval(code, entries, input) {
164
+ const extra = entries.filter((entry) => entry.permission === input.permission && matches(entry, input.tenant, input.subject, input.current, input.next, input.now, input.scopes));
165
+ if (extra.length === 0) return code;
166
+ const parts = [...code === void 0 ? [] : [code], ...extra.map((entry) => entry.approval)];
167
+ const stages = [];
168
+ const seen = /* @__PURE__ */ new Set();
169
+ let sequential = false;
170
+ let distinct = false;
171
+ let staleOn;
172
+ let ttl;
173
+ for (const [index, part] of parts.entries()) {
174
+ const fromCode = code !== void 0 && index === 0;
175
+ for (const stage of fromCode ? asStages(part) : entryStages(part)) {
176
+ const key = JSON.stringify(stage);
177
+ if (!seen.has(key)) {
178
+ seen.add(key);
179
+ stages.push(stage);
180
+ }
181
+ }
182
+ if (part === "human") {
183
+ distinct = true;
184
+ continue;
185
+ }
186
+ sequential ||= part.mode === "sequential";
187
+ distinct ||= part.distinct !== false;
188
+ staleOn ??= part.staleOn;
189
+ ttl = shorter(ttl, part.ttl);
190
+ }
191
+ return compact({
192
+ mode: sequential ? "sequential" : "all",
193
+ stages,
194
+ distinct: distinct ? void 0 : false,
195
+ staleOn,
196
+ ttl,
197
+ escalation: code === void 0 || code === "human" ? void 0 : code.escalation
198
+ });
199
+ }
200
+ /** The tenant a matched allow applies in: its membership's root scope, else the active tenant. */
201
+ function decisionTenant(subject, membership) {
202
+ return (membership === void 0 ? void 0 : rootMembershipId(membership)) ?? subject.principal?.tenant;
203
+ }
204
+ //#endregion
205
+ //#region src/core/memberships.ts
206
+ /** Two memberships are the same row when everything but `roles` matches. */
207
+ function identity(membership) {
208
+ const within = Object.entries(membership.within ?? {}).toSorted(([a], [b]) => byCodePoint(a, b));
209
+ return JSON.stringify([
210
+ membership.scope ?? null,
211
+ membership.id ?? null,
212
+ within,
213
+ membership.on ?? null,
214
+ membership.tenant ?? null,
215
+ membership.team ?? null,
216
+ membership.via ?? null,
217
+ membership.expiresAt ?? null,
218
+ membership.grantedBy ?? null,
219
+ membership.reason ?? null,
220
+ membership.member?.group ?? null,
221
+ [...membership.eligible ?? []].toSorted(),
222
+ membership.managedBy ?? null,
223
+ [...membership.entitlements ?? []].toSorted(),
224
+ membership.keep === void 0 ? null : [...membership.keep].toSorted()
225
+ ]);
226
+ }
227
+ /**
228
+ * Merges memberships from several sources: entries naming the same instance
229
+ * with the same `via`, expiry, owner and seats become one entry with the union
230
+ * of their roles. Entries that differ in any of those stay separate, so a
231
+ * staff role and a contact role in one instance keep their own `via`.
232
+ */
233
+ function mergeMemberships(lists) {
234
+ const merged = /* @__PURE__ */ new Map();
235
+ for (const list of lists) for (const membership of list) {
236
+ const key = identity(membership);
237
+ const found = merged.get(key);
238
+ merged.set(key, found === void 0 ? membership : {
239
+ ...found,
240
+ roles: [.../* @__PURE__ */ new Set([...found.roles, ...membership.roles])]
241
+ });
242
+ }
243
+ return [...merged.values()];
244
+ }
245
+ function all(values) {
246
+ return values.some((value) => isThenable(value)) ? Promise.all(values) : values;
247
+ }
248
+ function then(value, next) {
249
+ return isThenable(value) ? Promise.resolve(value).then(next) : next(value);
250
+ }
251
+ /**
252
+ * One `MembershipSource` over several: memberships are merged and
253
+ * de-duplicated, `list` concatenates the sources that can list, and `version`
254
+ * is the highest version any source reports. A source that throws makes the
255
+ * whole lookup throw, which the subject resolver turns into no memberships.
256
+ */
257
+ function composeMemberships(sources) {
258
+ const listing = sources.filter((source) => source.list !== void 0);
259
+ const versioned = sources.filter((source) => source.version !== void 0);
260
+ return {
261
+ membershipsFor(principal, options) {
262
+ return then(all(sources.map((source) => source.membershipsFor(principal, options))), (lists) => mergeMemberships(lists));
263
+ },
264
+ ...listing.length === 0 ? {} : { list(query) {
265
+ return then(all(listing.map((source) => source.list?.(query) ?? [])), (lists) => {
266
+ const seen = /* @__PURE__ */ new Map();
267
+ for (const entry of lists.flat()) {
268
+ const key = `${entry.principal.id}\u0000${identity(entry.membership)}`;
269
+ const found = seen.get(key);
270
+ seen.set(key, found === void 0 ? entry : {
271
+ principal: entry.principal,
272
+ membership: {
273
+ ...found.membership,
274
+ roles: [.../* @__PURE__ */ new Set([...found.membership.roles, ...entry.membership.roles])]
275
+ }
276
+ });
277
+ }
278
+ return [...seen.values()];
279
+ });
280
+ } },
281
+ ...versioned.length === 0 ? {} : { version(principal) {
282
+ return then(all(versioned.map((source) => source.version?.(principal))), (versions) => {
283
+ const known = versions.filter((value) => typeof value === "number" && Number.isFinite(value));
284
+ return known.length === 0 ? void 0 : Math.max(...known);
285
+ });
286
+ } }
287
+ };
288
+ }
289
+ /** A single source, or several composed. */
290
+ function asMembershipSource(input) {
291
+ return Array.isArray(input) ? composeMemberships(input) : input;
292
+ }
293
+ /**
294
+ * Trust the memberships the verified token carries, and read `source` only
295
+ * when the token marks them truncated. With `version`, a token minted before
296
+ * the latest membership change is stale for the policy's `fresh` permissions,
297
+ * or with `onStale: 'reread'` has its memberships read from `source` instead.
298
+ */
299
+ function claimsFirst(source, options = {}) {
300
+ const inner = asMembershipSource(source);
301
+ const version = options.version ?? (inner.version === void 0 ? void 0 : (principal) => inner.version?.(principal));
302
+ return {
303
+ membershipsFor: (principal, query) => inner.membershipsFor(principal, query),
304
+ ...inner.list === void 0 ? {} : { list: (query) => inner.list?.(query) ?? [] },
305
+ ...version === void 0 ? {} : { version },
306
+ ...options.onStale === "reread" ? { onStale: "reread" } : {},
307
+ claimsFirst: true
308
+ };
309
+ }
310
+ /** Whether the identity provider owns `membership`: the application must not add, change or remove it. */
311
+ function isExternallyManaged(membership) {
312
+ return membership.managedBy === "idp";
313
+ }
314
+ /**
315
+ * How many principals hold `role` in one scope instance now, from the
316
+ * source's member list (`MembershipSource.list`): live memberships of exactly
317
+ * that scope and instance, each principal counted once. The `holders` a
318
+ * `decideRoleChange` with `min`, `max` or `transferOnly` needs. `undefined`
319
+ * when the source cannot list or the read fails, which that check denies.
320
+ */
321
+ async function countHolders(source, query) {
322
+ const composed = asMembershipSource(source);
323
+ if (composed.list === void 0) return;
324
+ const role = typeof query.role === "string" ? query.role : query.role.key;
325
+ try {
326
+ const entries = await composed.list({
327
+ scope: query.scope,
328
+ id: query.id
329
+ });
330
+ const now = Math.floor(Date.now() / 1e3);
331
+ const holders = /* @__PURE__ */ new Set();
332
+ for (const entry of entries) {
333
+ const membership = entry.membership;
334
+ if (membership.scope === query.scope && membership.id === query.id && membership.roles.includes(role) && (membership.expiresAt === void 0 || membership.expiresAt > now)) holders.add(entry.principal.id);
335
+ }
336
+ return holders.size;
337
+ } catch {
338
+ return;
339
+ }
340
+ }
341
+ //#endregion
342
+ //#region src/core/custom-roles.ts
343
+ /** The current key for a stored key, current or former; `undefined` when neither. */
344
+ function currentKey(policy, raw) {
345
+ const leaf = findPermission(policy.permissions, raw);
346
+ if (leaf === void 0) return;
347
+ return leaf.key === raw || formerKeys(leaf).includes(raw) ? leaf.key : void 0;
348
+ }
349
+ const GRANT_KEYS = /* @__PURE__ */ new Set([
350
+ "permission",
351
+ "effect",
352
+ "level"
353
+ ]);
354
+ /** `where` narrowed by a level; the empty level (`{}`) leaves it as is. */
355
+ function andWhere(where, level) {
356
+ if (level.op === "and" && level.conditions.length === 0) return where;
357
+ return where === void 0 ? level : {
358
+ op: "and",
359
+ conditions: [where, level]
360
+ };
361
+ }
362
+ /** A ceiling grant narrowed by a level's condition and marked with the level. */
363
+ function leveled(grant, level, condition) {
364
+ const where = andWhere(grant.where, condition);
365
+ const check = grant.check === void 0 ? void 0 : andWhere(grant.check, condition);
366
+ return freezeDeep({
367
+ ...grant,
368
+ level,
369
+ ...where === void 0 ? {} : { where },
370
+ ...check === void 0 ? {} : { check }
371
+ });
372
+ }
373
+ /**
374
+ * The scope a custom role is held at: `scope` (a name or alias), the second
375
+ * scope for the `team` input shape, else the first scope. `undefined` when
376
+ * the policy does not declare it; such a role resolves to nothing.
377
+ */
378
+ function customRoleScope(role, scopes) {
379
+ if (role.scope === "global") return "global";
380
+ if (role.scope !== void 0) return resolveScope(scopes, role.scope);
381
+ return resolveScope(scopes, role.team === void 0 ? "tenant" : "team");
382
+ }
383
+ /** The instance of its scope a custom role is pinned to, if any. */
384
+ function customRoleId(role) {
385
+ return role.scope === void 0 ? role.team : role.id;
386
+ }
387
+ /** A platform custom role: held through `principal.roles`, capped by the assignable global roles. */
388
+ function isGlobalCustomRole(role) {
389
+ return role.scope === "global";
390
+ }
391
+ function isCeilingScope(scope) {
392
+ return typeof scope === "string";
393
+ }
394
+ function soleRole(grant) {
395
+ const roles = flattenGrantee(grant.to).filter((item) => item.kind === "role");
396
+ const first = roles[0];
397
+ return roles.length === 1 && first?.kind === "role" ? first.role : void 0;
398
+ }
399
+ /** Permission keys a declared role's allows reach, hosted grants included. */
400
+ function roleAllowKeys(policy, name) {
401
+ return new Set(grantList(policy).filter((grant) => grant.effect === "allow" && soleRole(grant) === name).map((grant) => grant.permission.key));
402
+ }
403
+ function isAssignableRole(policy, name) {
404
+ const binding = policy.rolesByName.get(name);
405
+ if (binding !== void 0) return binding.assignable;
406
+ return findRole(policy.vocabulary?.roles, name)?.assignable === true;
407
+ }
408
+ /**
409
+ * Every scope's ceiling, keyed by scope name (`global` for platform custom
410
+ * roles): the code allows of declared `assignable` roles in that scope,
411
+ * everything a custom role of the scope may ever reach. Hosted grants never
412
+ * widen it. `assignable` narrows it to those role names (`RoleSource.assignable`).
413
+ */
414
+ function ceilings(policy, assignable) {
415
+ const allowed = assignable === void 0 ? void 0 : new Set(assignable);
416
+ const byScope = /* @__PURE__ */ new Map();
417
+ for (const grant of grantList(policy)) {
418
+ const name = soleRole(grant);
419
+ if (grant.effect !== "allow" || grant.hosted !== void 0 || !isCeilingScope(grant.scope) || name === void 0 || !isAssignableRole(policy, name) || allowed !== void 0 && !allowed.has(name)) continue;
420
+ const list = byScope.get(grant.scope) ?? [];
421
+ list.push(grant);
422
+ byScope.set(grant.scope, list);
423
+ }
424
+ return byScope;
425
+ }
426
+ function ceilingGrants(policy, scope, assignable) {
427
+ return ceilings(policy, assignable).get(scope) ?? [];
428
+ }
429
+ function retarget(grant, role, scope) {
430
+ const grantee = {
431
+ kind: "role",
432
+ role: role.name,
433
+ scope
434
+ };
435
+ const others = flattenGrantee(grant.to).filter((item) => item.kind !== "role");
436
+ return freezeDeep({
437
+ ...grant,
438
+ to: others.length === 0 ? grantee : [grantee, ...others],
439
+ role: role.name,
440
+ scope
441
+ });
442
+ }
443
+ /**
444
+ * The one resolver behind evaluation, snapshots and `validateCustomRole`.
445
+ * Included roles' grants plus the role's own allows, minus its denies, all
446
+ * intersected with the ceiling. An allow inherits the condition, approval and
447
+ * limit of the declared grant it comes from: an included assignable role's
448
+ * grant when there is one, otherwise every ceiling grant of that permission,
449
+ * together with the denies of the roles those grants belong to.
450
+ */
451
+ function resolveCustomRole(policy, role) {
452
+ const scope = customRoleScope(role, scopeList(policy.scopes));
453
+ if (scope === void 0) return freezeDeep({
454
+ grants: [],
455
+ dropped: [],
456
+ renamed: []
457
+ });
458
+ const ceiling = ceilingGrants(policy, scope);
459
+ const ceilingSet = new Set(ceiling);
460
+ const ceilingKeys = new Set(ceiling.map((grant) => grant.permission.key));
461
+ const declared = declaredRoleNames$1(policy);
462
+ const all = grantList(policy).filter((grant) => grant.hosted === void 0);
463
+ const dropped = [];
464
+ const renamed = [];
465
+ const seen = /* @__PURE__ */ new Set();
466
+ const drop = (entry) => {
467
+ const id = "role" in entry ? `role:${entry.role}` : `${entry.reason}:${entry.permission}`;
468
+ if (!seen.has(id)) {
469
+ seen.add(id);
470
+ dropped.push(entry);
471
+ }
472
+ };
473
+ const included = [];
474
+ const includedKeys = /* @__PURE__ */ new Set();
475
+ const allowKeys = /* @__PURE__ */ new Map();
476
+ const denyKeys = /* @__PURE__ */ new Set();
477
+ const allowAll = (key) => {
478
+ allowKeys.set(key, "all");
479
+ };
480
+ for (const name of Array.isArray(role.includes) ? role.includes : []) {
481
+ if (typeof name !== "string" || !declared.has(name)) {
482
+ drop({
483
+ role: String(name),
484
+ reason: "unknown-role"
485
+ });
486
+ continue;
487
+ }
488
+ for (const grant of all) {
489
+ if (soleRole(grant) !== name) continue;
490
+ const key = grant.permission.key;
491
+ if (grant.effect === "deny") {
492
+ if (grant.scope === scope) included.push(grant);
493
+ } else if (ceilingSet.has(grant)) {
494
+ included.push(grant);
495
+ includedKeys.add(key);
496
+ } else if (ceilingKeys.has(key)) allowAll(key);
497
+ else drop({
498
+ permission: key,
499
+ reason: "outside-ceiling"
500
+ });
501
+ }
502
+ }
503
+ const entries = Array.isArray(role.grants) ? role.grants : [];
504
+ for (const item of entries) {
505
+ if (item === null || typeof item !== "object") {
506
+ drop({
507
+ permission: String(item),
508
+ reason: "unknown-permission"
509
+ });
510
+ continue;
511
+ }
512
+ const entry = item;
513
+ const raw = entry.permission;
514
+ const key = typeof raw === "string" ? currentKey(policy, raw) : void 0;
515
+ if (key === void 0) {
516
+ drop({
517
+ permission: String(raw),
518
+ reason: "unknown-permission"
519
+ });
520
+ continue;
521
+ }
522
+ if (key !== raw) renamed.push({
523
+ from: String(raw),
524
+ to: key
525
+ });
526
+ const effect = entry.effect ?? "allow";
527
+ const extra = Object.keys(entry).some((name) => !GRANT_KEYS.has(name));
528
+ const level = entry.level;
529
+ if (extra || effect !== "allow" && effect !== "deny" || effect === "deny" && level !== void 0) {
530
+ drop({
531
+ permission: key,
532
+ reason: "condition-not-allowed"
533
+ });
534
+ denyKeys.add(key);
535
+ continue;
536
+ }
537
+ if (effect === "deny") {
538
+ denyKeys.add(key);
539
+ continue;
540
+ }
541
+ let narrowing;
542
+ if (level !== void 0) {
543
+ const leaf = findPermission(policy.permissions, key);
544
+ const condition = typeof level === "string" && leaf?.kind === "instance" ? levelCondition(policy, leaf.resource, level) : void 0;
545
+ if (condition === void 0) {
546
+ drop({
547
+ permission: key,
548
+ reason: "unknown-level",
549
+ level: String(level)
550
+ });
551
+ denyKeys.add(key);
552
+ continue;
553
+ }
554
+ narrowing = [String(level), condition];
555
+ }
556
+ if (!ceilingKeys.has(key)) {
557
+ drop({
558
+ permission: key,
559
+ reason: "outside-ceiling"
560
+ });
561
+ continue;
562
+ }
563
+ const held = allowKeys.get(key);
564
+ if (narrowing === void 0) allowAll(key);
565
+ else if (held === void 0) allowKeys.set(key, new Map([narrowing]));
566
+ else if (held !== "all") held.set(...narrowing);
567
+ }
568
+ const out = [];
569
+ const push = (grant) => {
570
+ if (!out.includes(grant)) out.push(grant);
571
+ };
572
+ for (const grant of included) if (grant.effect === "deny" || !denyKeys.has(grant.permission.key)) push(grant);
573
+ for (const [key, levels] of allowKeys) {
574
+ if (denyKeys.has(key) || includedKeys.has(key)) continue;
575
+ const sources = /* @__PURE__ */ new Set();
576
+ for (const grant of ceiling) {
577
+ if (grant.permission.key !== key) continue;
578
+ sources.add(soleRole(grant) ?? "");
579
+ if (levels === "all") {
580
+ push(grant);
581
+ continue;
582
+ }
583
+ for (const [level, condition] of levels) push(leveled(grant, level, condition));
584
+ }
585
+ for (const grant of all) if (grant.effect === "deny" && grant.permission.key === key && sources.has(soleRole(grant) ?? "")) push(grant);
586
+ }
587
+ return freezeDeep({
588
+ grants: out.map((grant) => retarget(grant, role, scope)),
589
+ dropped,
590
+ renamed
591
+ });
592
+ }
593
+ function validateCustomRole(policy, role) {
594
+ const resolved = resolveCustomRole(policy, role);
595
+ const permissions = [...new Set(resolved.grants.filter((grant) => grant.effect === "allow").map((grant) => grant.permission.key))].toSorted();
596
+ return freezeDeep({
597
+ ok: resolved.dropped.length === 0,
598
+ permissions,
599
+ dropped: resolved.dropped,
600
+ renamed: resolved.renamed
601
+ });
602
+ }
603
+ function wellFormed(role) {
604
+ if (role === null || typeof role !== "object" || typeof role.name !== "string") return false;
605
+ if (role.scope === "global") return role.tenant === void 0 && role.team === void 0 && role.id === void 0;
606
+ return typeof role.tenant === "string" && (role.team === void 0 || typeof role.team === "string") && (role.scope === void 0 || typeof role.scope === "string") && (role.id === void 0 || typeof role.id === "string");
607
+ }
608
+ /** Every custom role's resolved grants, once per instance. Malformed roles resolve to nothing. */
609
+ function customGrantsFor(policy, roles) {
610
+ const declared = declaredRoleNames$1(policy);
611
+ const out = [];
612
+ for (const role of roles) {
613
+ if (!wellFormed(role) || declared.has(role.name)) continue;
614
+ for (const grant of resolveCustomRole(policy, role).grants) out.push({
615
+ grant,
616
+ role
617
+ });
618
+ }
619
+ return out;
620
+ }
621
+ /** The well-formed tenant (not platform) custom roles; a declared role name is never one. */
622
+ function tenantCustomRoles(policy, roles) {
623
+ const declared = declaredRoleNames$1(policy);
624
+ return roles.filter((role) => wellFormed(role) && !isGlobalCustomRole(role) && !declared.has(role.name));
625
+ }
626
+ /** A membership at the role's scope, inside its tenant (and instance, when pinned), naming it. */
627
+ function holdsCustomRole(membership, role, scopes) {
628
+ if (isGlobalCustomRole(role)) return false;
629
+ const scope = customRoleScope(role, scopes);
630
+ const id = customRoleId(role);
631
+ return scope !== void 0 && membership.scope === scope && sameId(tenantOf(membership, scopes), role.tenant) && (id === void 0 || sameId(membership.id, id)) && membership.roles.includes(role.name);
632
+ }
633
+ /** Whether `principal.roles` names the platform custom role. */
634
+ function holdsGlobalCustomRole(roles, role) {
635
+ return isGlobalCustomRole(role) && (roles ?? []).includes(role.name);
636
+ }
637
+ /** A tenant's custom role inside that tenant, or a platform custom role anywhere. */
638
+ function isCustomRoleName(name, roles, tenant) {
639
+ return roles.some((item) => wellFormed(item) && item.name === name && (isGlobalCustomRole(item) || tenant !== void 0 && sameId(item.tenant, tenant)));
640
+ }
641
+ /**
642
+ * The compact JWT form of custom roles for the `memberships[].grants` claim
643
+ * RLS reads in `jwt` mode: role name to entries, where `key` allows, `-key`
644
+ * denies and `@role` includes. Put a team custom role on its team membership.
645
+ * Pass `policy` to write keys stored under a former name as the current key.
646
+ */
647
+ function customRoleClaim(roles, policy) {
648
+ const keyOf = (raw) => policy === void 0 ? raw : currentKey(policy, raw) ?? raw;
649
+ const claim = {};
650
+ for (const role of roles) {
651
+ if (!wellFormed(role) || isForbiddenKey(role.name)) continue;
652
+ const entries = claim[role.name] ?? [];
653
+ const includes = Array.isArray(role.includes) ? role.includes : [];
654
+ const grants = Array.isArray(role.grants) ? role.grants : [];
655
+ for (const name of includes) entries.push(`@${name}`);
656
+ for (const grant of grants) {
657
+ if (grant.effect === "deny") {
658
+ entries.push(`-${keyOf(grant.permission)}`);
659
+ continue;
660
+ }
661
+ const level = grant.level;
662
+ entries.push(typeof level === "string" && level !== "" ? `${keyOf(grant.permission)}@${level}` : keyOf(grant.permission));
663
+ }
664
+ claim[role.name] = entries;
665
+ }
666
+ return freezeDeep(claim);
667
+ }
668
+ /**
669
+ * The `memberships` claim RLS reads in `jwt` mode: each membership canonical,
670
+ * with the custom roles it holds as the compact `grants` map.
671
+ */
672
+ function membershipsClaim(memberships, customRoles, scopes) {
673
+ const claim = [];
674
+ for (const membership of normalizeMemberships(memberships, scopes)) {
675
+ const held = customRoles.filter((role) => wellFormed(role) && holdsCustomRole(membership, role, scopes));
676
+ claim.push(held.length === 0 ? membership : Object.assign({}, membership, { grants: customRoleClaim(held) }));
677
+ }
678
+ return claim;
679
+ }
680
+ //#endregion
681
+ //#region src/core/elevated.ts
682
+ function flattenPermissions(input) {
683
+ if (input !== null && typeof input === "object" && "key" in input && "action" in input) return [input];
684
+ if (isReadonlyArray(input)) return input.flatMap((item) => flattenPermissions(item));
685
+ return [...listPermissions(input)];
686
+ }
687
+ /**
688
+ * The only deny override: a break-glass grant overrides deny grants whose
689
+ * `name` it lists, and nothing else. It is an allow that stays non-portable
690
+ * (RLS never compiles it) and grants only once its `requires` are met.
691
+ */
692
+ function breakGlass(permission, options = {}) {
693
+ const purpose = options.requires?.purpose === void 0 || options.requires.purpose.length === 0 ? void 0 : Object.freeze([...new Set(options.requires.purpose)]);
694
+ const spec = compact({
695
+ overrides: Object.freeze([...new Set(options.overrides ?? [])]),
696
+ purpose,
697
+ reason: options.requires?.reason === true,
698
+ assurance: normalizeAssurance(options.requires?.assurance),
699
+ maxDuration: options.maxDuration,
700
+ obligations: Object.freeze([...new Set(options.obligations ?? [])])
701
+ });
702
+ const grants = flattenPermissions(permission).map((leaf) => freezeDeep(compact({
703
+ permission: leaf,
704
+ effect: "allow",
705
+ to: authenticated(),
706
+ portable: false,
707
+ breakGlass: spec
708
+ })));
709
+ return sole(grants) ?? grants;
710
+ }
711
+ function supportAccess(options) {
712
+ const via = options.role;
713
+ const forbidden = (options.forbid ?? []).flatMap((item) => flattenPermissions(item));
714
+ const binding = role(options.role, [], {
715
+ on: options.on ?? "tenant",
716
+ for: [via]
717
+ });
718
+ const denies = forbidden.map((leaf) => freezeDeep(compact({
719
+ permission: leaf,
720
+ effect: "deny",
721
+ to: authenticated(),
722
+ role: options.role,
723
+ scope: "global",
724
+ viaOnly: via,
725
+ portable: false
726
+ })));
727
+ const support = freezeDeep(compact({
728
+ role: options.role,
729
+ actorRequired: options.actorRequired === true,
730
+ consent: {
731
+ by: asGrantee(options.consent.by),
732
+ durations: Object.freeze([...new Set(options.consent.durations)])
733
+ },
734
+ group: options.group ?? "vendor-support"
735
+ }));
736
+ return freezeDeep({
737
+ ...binding,
738
+ grants: [...binding.grants, ...denies],
739
+ support
740
+ });
741
+ }
742
+ /** Whether the subject's authentication is fresh enough for an elevated grant. */
743
+ function assuranceMet(requirement, subject, now) {
744
+ if (requirement === void 0) return true;
745
+ const held = subject.principal?.assurance;
746
+ if (requirement.acr !== void 0 && requirement.acr.length > 0) {
747
+ const acr = held?.acr;
748
+ if (acr === void 0 || !requirement.acr.includes(acr)) return false;
749
+ }
750
+ if (requirement.amr !== void 0 && requirement.amr.length > 0) {
751
+ const amr = held?.amr ?? [];
752
+ if (!requirement.amr.every((method) => amr.includes(method))) return false;
753
+ }
754
+ if (requirement.maxAge !== void 0) {
755
+ const authTime = held?.authTime;
756
+ if (authTime === void 0 || now - authTime > requirement.maxAge) return false;
757
+ }
758
+ return true;
759
+ }
760
+ /** `context.purpose` as a list of strings; fail-closed to empty. */
761
+ function purposesOf(subject) {
762
+ const value = subject.context["purpose"];
763
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : typeof value === "string" && value !== "" ? [value] : [];
764
+ }
765
+ /**
766
+ * Whether a break-glass grant fires for this subject. It engages when the
767
+ * caller asserts a purpose (`context.purpose`); once engaged, an unlisted
768
+ * purpose, a missing reason or stale authentication denies with the matching
769
+ * reason, and everything met grants with the declared obligations.
770
+ */
771
+ function evaluateBreakGlass(spec, subject, now) {
772
+ const purposes = purposesOf(subject);
773
+ if (purposes.length === 0) return { kind: "inactive" };
774
+ const required = spec.purpose;
775
+ if (required !== void 0 && !purposes.some((purpose) => required.includes(purpose))) return {
776
+ kind: "denied",
777
+ reason: "purpose"
778
+ };
779
+ const reason = subject.context["reason"];
780
+ if (spec.reason && (typeof reason !== "string" || reason === "")) return {
781
+ kind: "denied",
782
+ reason: "reason-required"
783
+ };
784
+ if (spec.assurance !== void 0 && !assuranceMet(spec.assurance, subject, now)) return {
785
+ kind: "denied",
786
+ reason: "insufficient-user-authentication",
787
+ to: assurance(spec.assurance)
788
+ };
789
+ return {
790
+ kind: "granted",
791
+ obligations: [...spec.obligations.map((kind) => ({ kind })), ...typeof reason === "string" && reason !== "" ? [{
792
+ kind: "justify",
793
+ reason
794
+ }] : []]
795
+ };
796
+ }
797
+ /** Support memberships (`via: 'support'`) the subject holds that demand an actor. */
798
+ function actorRequiredVias(supports) {
799
+ return new Set(supports.filter((spec) => spec.actorRequired).map((spec) => spec.role));
800
+ }
801
+ /** Whether a membership is a support membership of one of the given kinds. */
802
+ function isSupportMembership(membership, vias) {
803
+ return membership.via !== void 0 && vias.has(membership.via);
804
+ }
805
+ /**
806
+ * Whether the caller's `within` names the same ancestors as the eligible
807
+ * membership. Omitted means "whatever the membership holds"; any entry that
808
+ * disagrees, or names an ancestor the membership lacks, refuses.
809
+ */
810
+ function withinAgrees(scopes, held, requested) {
811
+ if (requested === void 0) return true;
812
+ return Object.entries(requested).every(([key, id]) => {
813
+ const name = resolveScope(scopes, key) ?? key;
814
+ return held !== void 0 && Object.hasOwn(held, name) && held[name] === id;
815
+ });
816
+ }
817
+ function activationDenied(reason, to) {
818
+ return freezeDeep({
819
+ outcome: "denied",
820
+ denials: [to === void 0 ? {
821
+ role: null,
822
+ reason
823
+ } : {
824
+ role: null,
825
+ reason,
826
+ to
827
+ }],
828
+ alternatives: []
829
+ });
830
+ }
831
+ /**
832
+ * Requests a just-in-time role activation. It never writes: a granted
833
+ * decision carries the elevated membership under `elevation` for the app to
834
+ * write. `approval-required` comes back first when the role's `activation`
835
+ * sets `approval`. Fail-closed: an unknown role, an ineligible subject, a
836
+ * missing justification or stale authentication all deny.
837
+ */
838
+ function activate(policy, subject, input, now = nowSeconds()) {
839
+ const roleName = isRole(input.role) ? input.role.key : input.role;
840
+ const binding = policy.rolesByName.get(roleName);
841
+ const activation = binding?.activation;
842
+ const principal = subject.principal;
843
+ if (principal === null) return activationDenied("anonymous");
844
+ if (binding === void 0 || activation === void 0) return activationDenied("unknown-role");
845
+ const scopes = scopeList(policy.scopes);
846
+ const scope = resolveScope(scopes, input.scope) ?? input.scope;
847
+ const eligible = (principal.memberships ?? []).find((membership) => membership.scope === scope && sameId(membership.id, input.id) && !isMembershipExpired(membership, now) && (membership.eligible ?? []).includes(roleName) && withinAgrees(scopes, membership.within, input.within));
848
+ if (eligible === void 0) return activationDenied("no-membership");
849
+ const within = eligible.within;
850
+ if (activation.justification === "required") {
851
+ const reason = input.reason;
852
+ if (typeof reason !== "string" || reason === "") return activationDenied("reason-required");
853
+ }
854
+ if (activation.assurance !== void 0 && !assuranceMet(activation.assurance, subject, now)) return activationDenied("insufficient-user-authentication", assurance(activation.assurance));
855
+ const requested = parseDuration(input.duration);
856
+ const cap = parseDuration(activation.maxDuration);
857
+ const seconds = cap === void 0 ? requested : Math.min(requested ?? cap, cap);
858
+ const membership = freezeDeep(compact({
859
+ scope,
860
+ id: input.id,
861
+ within,
862
+ roles: [roleName],
863
+ via: "elevated",
864
+ expiresAt: seconds === void 0 ? void 0 : Math.floor(now) + seconds,
865
+ grantedBy: principal.id,
866
+ reason: input.reason
867
+ }));
868
+ const token = decisionToken({
869
+ key: `activate:${roleName}`,
870
+ resourceId: within === void 0 ? `${scope}:${input.id}` : `${scope}:${input.id}@${canonicalJson(within)}`,
871
+ principal,
872
+ actor: subject.actor,
873
+ fingerprint: policy.fingerprint
874
+ });
875
+ if (activation.approval !== void 0) return freezeDeep({
876
+ outcome: "approval-required",
877
+ grant: {
878
+ role: roleName,
879
+ permission: `activate:${roleName}`
880
+ },
881
+ reason: "human",
882
+ token
883
+ });
884
+ return freezeDeep({
885
+ outcome: "granted",
886
+ subject,
887
+ matched: {
888
+ role: roleName,
889
+ permission: `activate:${roleName}`
890
+ },
891
+ token,
892
+ elevation: membership
893
+ });
894
+ }
895
+ //#endregion
896
+ //#region src/core/events.ts
897
+ function emitSafe(listeners, payload, errors) {
898
+ for (const listener of listeners) try {
899
+ listener(payload);
900
+ } catch (error) {
901
+ for (const handler of errors.error) try {
902
+ handler(error);
903
+ } catch {}
904
+ }
905
+ }
906
+ function emptyListeners() {
907
+ return {
908
+ decision: /* @__PURE__ */ new Set(),
909
+ denied: /* @__PURE__ */ new Set(),
910
+ approval: /* @__PURE__ */ new Set(),
911
+ auth: /* @__PURE__ */ new Set(),
912
+ error: /* @__PURE__ */ new Set()
913
+ };
914
+ }
915
+ function credentialRef(subject) {
916
+ const value = subject.principal?.["credential"];
917
+ if (value === null || typeof value !== "object") return;
918
+ const { id, kind } = value;
919
+ return typeof id === "string" && (kind === "user" || kind === "service") ? {
920
+ id,
921
+ kind
922
+ } : void 0;
923
+ }
924
+ function finish(policy, subject, permission, data, decision, options, env, trusted, membership, counts) {
925
+ const heard = env.sink !== void 0 || env.listeners.decision.size > 0 || decision.outcome === "denied" && env.listeners.denied.size > 0 || decision.outcome === "approval-required" && env.listeners.approval.size > 0;
926
+ if (!env.emit || !heard) return;
927
+ const resource = getResource(policy.permissions, permission.resource);
928
+ const resourceId = data !== null && typeof data === "object" ? data[resource?.id ?? "id"] : void 0;
929
+ const event = freezeDeep(compact({
930
+ type: "decision",
931
+ at: (/* @__PURE__ */ new Date()).toISOString(),
932
+ outcome: decision.outcome,
933
+ permission: permission.key,
934
+ scope: permission.scope,
935
+ resource: compact({
936
+ type: permission.resource,
937
+ id: resourceId === void 0 ? void 0 : String(resourceId)
938
+ }),
939
+ subject: compact({
940
+ principal: subject.principal === null ? null : compact({
941
+ id: subject.principal.id,
942
+ roles: subject.principal.roles ?? [],
943
+ tenant: subject.principal.tenant
944
+ }),
945
+ actor: subject.actor === void 0 ? void 0 : {
946
+ id: subject.actor.id,
947
+ kind: subject.actor.kind
948
+ },
949
+ delegation: subject.delegation === void 0 ? void 0 : compact({
950
+ scopes: subject.delegation.scopes,
951
+ authorizationDetails: subject.delegation.authorizationDetails
952
+ }),
953
+ credential: credentialRef(subject)
954
+ }),
955
+ tenant: subject.principal?.tenant,
956
+ membership,
957
+ via: membership?.via ?? null,
958
+ matched: decision.outcome === "granted" ? compact({
959
+ role: decision.matched.role,
960
+ permission: decision.matched.permission,
961
+ to: decision.matched.to,
962
+ hosted: decision.matched.hosted,
963
+ breakGlass: decision.matched.breakGlass
964
+ }) : decision.outcome === "approval-required" ? compact({
965
+ role: decision.grant.role,
966
+ permission: decision.grant.permission,
967
+ to: decision.grant.to,
968
+ hosted: decision.grant.hosted
969
+ }) : void 0,
970
+ purpose: Array.isArray(subject.context["purpose"]) && subject.context["purpose"].length > 0 ? subject.context["purpose"] : void 0,
971
+ reason: typeof subject.context["reason"] === "string" && subject.context["reason"] !== "" ? subject.context["reason"] : void 0,
972
+ denials: decision.outcome === "denied" ? wireDenials(decision.denials) : void 0,
973
+ alternatives: decision.outcome === "denied" ? decision.alternatives.map((leaf) => leaf.key) : void 0,
974
+ token: decision.outcome === "granted" || decision.outcome === "approval-required" ? decision.token : void 0,
975
+ trusted,
976
+ source: options.source ?? "decide",
977
+ adapter: options.adapter,
978
+ counts
979
+ }));
980
+ emitSafe(env.listeners.decision, event, env.listeners);
981
+ if (decision.outcome === "denied") emitSafe(env.listeners.denied, event, env.listeners);
982
+ if (decision.outcome === "approval-required") emitSafe(env.listeners.approval, event, env.listeners);
983
+ if (env.sink !== void 0) try {
984
+ const written = env.sink.write([event]);
985
+ if (isThenable(written)) written.catch((error) => {
986
+ emitSafe(env.listeners.error, error, env.listeners);
987
+ });
988
+ } catch (error) {
989
+ emitSafe(env.listeners.error, error, env.listeners);
990
+ }
991
+ }
992
+ //#endregion
993
+ //#region src/core/validation.ts
994
+ function validateBoundary(permission, resource, data, mode, trusted, boundary = "manual") {
995
+ if (!(mode === "always" || mode === "boundary" && !trusted)) return data;
996
+ if (resource?.schema === void 0) {
997
+ if (mode === "always") throw new PermDockValidationError({
998
+ code: "no-schema",
999
+ permission: permission.key,
1000
+ resource: permission.resource,
1001
+ boundary,
1002
+ message: `${permission.key}: no schema for resource ${permission.resource}.`
1003
+ });
1004
+ return data;
1005
+ }
1006
+ const result = resource.schema["~standard"].validate(data);
1007
+ if (isThenable(result)) {
1008
+ ignoreRejection(result);
1009
+ throw new PermDockValidationError({
1010
+ code: "async-schema",
1011
+ permission: permission.key,
1012
+ resource: permission.resource,
1013
+ boundary,
1014
+ message: `${permission.key}: schema for ${permission.resource} is async.`
1015
+ });
1016
+ }
1017
+ if ("issues" in result && result.issues !== void 0) throw new PermDockValidationError({
1018
+ code: "invalid-data",
1019
+ permission: permission.key,
1020
+ resource: permission.resource,
1021
+ issues: result.issues,
1022
+ boundary,
1023
+ message: validationMessage(permission, resource, result.issues)
1024
+ });
1025
+ return result.value;
1026
+ }
1027
+ function validationMessage(permission, resource, issues) {
1028
+ const parts = issues.map((issue) => {
1029
+ const path = issue.path?.map((item) => typeof item === "object" && "key" in item ? String(item.key) : String(item)).join(".") ?? "/";
1030
+ return `invalid ${resource.name} data at ${path}: ${issue.message}`;
1031
+ });
1032
+ return `${permission.key}: ${parts.join("; ")}.`;
1033
+ }
1034
+ //#endregion
1035
+ //#region src/core/evaluate.ts
1036
+ /**
1037
+ * A collection write proposes `next`; an update pair may move `next` out of
1038
+ * the scope `current` is in. Both must stay in scope.
1039
+ */
1040
+ function matchWriteScope(match, instance, current, next) {
1041
+ const first = match(instance ? current : next);
1042
+ if (!first.ok || !instance || next === current) return first;
1043
+ const moved = match(next);
1044
+ return moved.ok ? first : moved;
1045
+ }
1046
+ function isGlobalRole(value) {
1047
+ return value !== null && typeof value === "object" && Reflect.get(value, "scope") === "global";
1048
+ }
1049
+ function onlyGlobal(roles) {
1050
+ return Array.isArray(roles) ? roles.filter(isGlobalRole) : [];
1051
+ }
1052
+ /** The `customRoles` option as a source: a factory is called with the resolved subject, and a throw reads none. */
1053
+ function roleSourceFor(option, subject, auth) {
1054
+ if (typeof option !== "function") return option;
1055
+ try {
1056
+ return option(subject);
1057
+ } catch {
1058
+ auth.push({
1059
+ reason: "source-threw",
1060
+ source: "customRoles"
1061
+ });
1062
+ return;
1063
+ }
1064
+ }
1065
+ function customRolesFor(source, tenants, auth, globalHeld, heldIn) {
1066
+ if (source === void 0) return [];
1067
+ const loaded = [];
1068
+ for (const tenant of tenants) try {
1069
+ loaded.push(source.rolesFor(tenant, { held: heldIn(tenant) }));
1070
+ } catch {
1071
+ auth.push({
1072
+ reason: "source-threw",
1073
+ source: "customRoles"
1074
+ });
1075
+ loaded.push([]);
1076
+ }
1077
+ if (globalHeld !== void 0 && source.globalRoles !== void 0) try {
1078
+ const roles = source.globalRoles({ held: globalHeld });
1079
+ loaded.push(isThenable(roles) ? roles.then(onlyGlobal) : onlyGlobal(roles));
1080
+ } catch {
1081
+ auth.push({
1082
+ reason: "source-threw",
1083
+ source: "customRoles"
1084
+ });
1085
+ loaded.push([]);
1086
+ }
1087
+ if (loaded.some((item) => isThenable(item))) return Promise.all(loaded.map((item) => Promise.resolve(item).catch(() => {
1088
+ auth.push({
1089
+ reason: "source-threw",
1090
+ source: "customRoles"
1091
+ });
1092
+ return [];
1093
+ }))).then((lists) => lists.flat());
1094
+ return loaded.flat();
1095
+ }
1096
+ function stringList(value) {
1097
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
1098
+ }
1099
+ /**
1100
+ * `RoleSource.assignable` per tenant; `undefined` when the source has no
1101
+ * `assignable`. A tenant whose call throws or answers junk assigns nothing.
1102
+ */
1103
+ function assignableNamesFor(source, tenants, auth) {
1104
+ if (source?.assignable === void 0) return;
1105
+ const failed = () => {
1106
+ auth.push({
1107
+ reason: "source-threw",
1108
+ source: "customRoles"
1109
+ });
1110
+ return [];
1111
+ };
1112
+ const loaded = tenants.map((tenant) => {
1113
+ try {
1114
+ return source.assignable?.(tenant) ?? [];
1115
+ } catch {
1116
+ return failed();
1117
+ }
1118
+ });
1119
+ const toMap = (lists) => new Map(tenants.map((tenant, index) => [tenant, stringList(lists[index])]));
1120
+ if (loaded.some((item) => isThenable(item))) return Promise.all(loaded.map((item) => Promise.resolve(item).catch(failed))).then(toMap);
1121
+ return toMap(loaded);
1122
+ }
1123
+ /**
1124
+ * The declared role names among `names`. A custom role of `tenant` is known
1125
+ * but contributes no declared name: its grants are resolved separately
1126
+ * (`customGrantsFor`), bounded by the ceiling. A tenant's custom role is
1127
+ * unknown inside another tenant and for a membership without one.
1128
+ */
1129
+ function expandRoleNames(names, declared, custom, tenant) {
1130
+ const resolved = /* @__PURE__ */ new Set();
1131
+ const unknown = [];
1132
+ for (const name of names) if (declared.has(name)) resolved.add(name);
1133
+ else if (!isCustomRoleName(name, custom, tenant)) unknown.push(name);
1134
+ return {
1135
+ roles: [...resolved],
1136
+ unknown
1137
+ };
1138
+ }
1139
+ function declaredRoleNames(policy) {
1140
+ return policy.index.declaredRoles;
1141
+ }
1142
+ const NEVER = {
1143
+ op: "or",
1144
+ conditions: []
1145
+ };
1146
+ function isUnconditionedAllow(grant, now) {
1147
+ return grant.where === void 0 && grant.check === void 0 && grant.closure === void 0 && grant.portable && grant.purpose === void 0 && grant.viaOnly === void 0 && grant.requires === void 0 && isActive(grant.validity, now);
1148
+ }
1149
+ /**
1150
+ * The row condition a grant's `requires` adds: the row's instance of some
1151
+ * scope is one where the subject holds `key` through a role grant without a
1152
+ * row condition, minus the instances a deny of `key` reaches at that scope.
1153
+ * `undefined` when the subject holds `key` globally that way, so every row
1154
+ * passes. The in-process mirror of the SQL `permdock_has_permission` and
1155
+ * `permitted_<scope>_ids_by_permission`.
1156
+ */
1157
+ function requirementCondition(policy, subject, keys, resource, now, customRoles, customGrants) {
1158
+ let where;
1159
+ for (const key of keys) where = combineWhere(where, keyRequirement(policy, subject, key, resource, now, customRoles, customGrants));
1160
+ return where;
1161
+ }
1162
+ function keyRequirement(policy, subject, key, resource, now, customRoles, customGrants) {
1163
+ const principal = subject.principal;
1164
+ if (principal === null) return NEVER;
1165
+ const scopes = scopeList(policy.scopes);
1166
+ const declared = declaredRoleNames(policy);
1167
+ const global = new Set(expandRoleNames(principal.roles ?? [], declared, customRoles, principal.tenant).roles);
1168
+ const held = (principal.memberships ?? []).filter((membership) => !isMembershipExpired(membership, now) && keepsPermission(membership, key)).map((membership) => ({
1169
+ membership,
1170
+ roles: new Set(expandRoleNames(membership.roles, declared, customRoles, tenantOf(membership, scopes)).roles)
1171
+ }));
1172
+ const allowed = /* @__PURE__ */ new Map();
1173
+ const denied = /* @__PURE__ */ new Map();
1174
+ let globalAllow = false;
1175
+ let globalDeny = false;
1176
+ const note = (effect, membership) => {
1177
+ if (membership === void 0) {
1178
+ if (effect === "allow") globalAllow = true;
1179
+ else globalDeny = true;
1180
+ return;
1181
+ }
1182
+ if (membership.scope === void 0 || membership.id === void 0) return;
1183
+ const target = effect === "allow" ? allowed : denied;
1184
+ const ids = target.get(membership.scope) ?? /* @__PURE__ */ new Set();
1185
+ ids.add(membership.id);
1186
+ target.set(membership.scope, ids);
1187
+ };
1188
+ const applies = (grant) => grant.effect === "allow" ? isUnconditionedAllow(grant, now) : isActive(grant.validity, now);
1189
+ for (const grant of policy.index.grantsByKey.get(key) ?? []) {
1190
+ const items = flattenGrantee(grant.to);
1191
+ if (grant.breakGlass !== void 0 || !applies(grant) || items.length === 0 || !items.every((item) => item.kind === "role")) continue;
1192
+ const roles = items.flatMap((item) => item.kind === "role" ? [item] : []);
1193
+ if (!roles.every((item) => item.scope !== "global" || global.has(item.role))) continue;
1194
+ const scoped = roles.filter((item) => item.scope !== "global");
1195
+ if (scoped.length === 0) {
1196
+ note(grant.effect);
1197
+ continue;
1198
+ }
1199
+ for (const entry of held) if (scoped.every((item) => typeof item.scope === "string" && entry.membership.scope === item.scope && entry.roles.has(item.role))) note(grant.effect, entry.membership);
1200
+ }
1201
+ for (const { grant, role } of customGrants) {
1202
+ if (grant.permission.key !== key || !applies(grant)) continue;
1203
+ if (holdsGlobalCustomRole(principal.roles, role)) note(grant.effect);
1204
+ for (const entry of held) if (holdsCustomRole(entry.membership, role, scopes)) note(grant.effect, entry.membership);
1205
+ }
1206
+ if (globalAllow && !globalDeny) return;
1207
+ const parts = [];
1208
+ for (const name of resource === void 0 ? [] : partitionsOf(resource, scopes)) {
1209
+ const field = scopeField(resource, name, scopes);
1210
+ const deniedIds = denied.get(name);
1211
+ const ids = [...allowed.get(name) ?? []].filter((id) => deniedIds?.has(id) !== true).toSorted();
1212
+ if (field !== void 0 && ids.length > 0) parts.push({
1213
+ op: "in",
1214
+ field,
1215
+ value: ids
1216
+ });
1217
+ }
1218
+ return sole(parts) ?? {
1219
+ op: "or",
1220
+ conditions: parts
1221
+ };
1222
+ }
1223
+ function alternativesFor(policy, permission, subject, now, env) {
1224
+ return listPermissions(policy.permissions).filter((leaf) => leaf.resource === permission.resource && leaf.key !== permission.key).filter((leaf) => {
1225
+ return evaluate(policy, subject, leaf, void 0, {
1226
+ trusted: true,
1227
+ source: "simulate",
1228
+ now
1229
+ }, {
1230
+ ...env,
1231
+ emit: false,
1232
+ skipAlternatives: true,
1233
+ outcomeOnly: true
1234
+ }).outcome === "granted";
1235
+ });
1236
+ }
1237
+ function inheritedVerdict(policy, subject, resource, id, key, now, env) {
1238
+ const leaf = findPermission(policy.permissions, key);
1239
+ const loaded = env.relations?.row({
1240
+ resource,
1241
+ id
1242
+ });
1243
+ if (leaf === void 0 || loaded === void 0) return "relation-unavailable";
1244
+ if (loaded === "pending" || loaded === "failed") return "relation-unavailable";
1245
+ if (loaded.row === null) return false;
1246
+ const decision = evaluate(policy, subject, leaf, loaded.row, {
1247
+ trusted: true,
1248
+ source: "simulate",
1249
+ now
1250
+ }, {
1251
+ ...env,
1252
+ emit: false,
1253
+ skipAlternatives: true,
1254
+ outcomeOnly: true
1255
+ });
1256
+ if (decision.outcome === "granted") return true;
1257
+ const reasons = decision.outcome === "denied" ? decision.denials.map((denial) => denial.reason) : [];
1258
+ return reasons.includes("relation-unavailable") ? "relation-unavailable" : reasons.includes("relation-depth") ? "relation-depth" : false;
1259
+ }
1260
+ function evaluateGrantCondition(grant, permission, current, next, subject, now, scopes, relations, permitted) {
1261
+ let unknown;
1262
+ const onOpaque = () => {
1263
+ unknown ??= "opaque-condition";
1264
+ };
1265
+ const related = (condition, row) => {
1266
+ if (relations === void 0) {
1267
+ unknown ??= "relation-unavailable";
1268
+ return false;
1269
+ }
1270
+ const verdict = resolveRelated(condition, row, subject, now, relations, permitted);
1271
+ if (verdict === "relation-depth" || verdict === "relation-unavailable") {
1272
+ unknown ??= verdict;
1273
+ return false;
1274
+ }
1275
+ return verdict;
1276
+ };
1277
+ if (!grant.portable && grant.closure !== void 0) try {
1278
+ const result = grant.closure(next ?? current, {
1279
+ subject,
1280
+ actor: subject.actor,
1281
+ delegation: subject.delegation,
1282
+ context: subject.context
1283
+ });
1284
+ if (isThenable(result)) return {
1285
+ matched: false,
1286
+ reason: "closure-error",
1287
+ cause: result
1288
+ };
1289
+ return { matched: result === true };
1290
+ } catch (error) {
1291
+ return {
1292
+ matched: false,
1293
+ reason: "closure-error",
1294
+ cause: error
1295
+ };
1296
+ }
1297
+ if (grant.where !== void 0) {
1298
+ if (permission.kind === "collection") return {
1299
+ matched: false,
1300
+ reason: "condition"
1301
+ };
1302
+ if (current === void 0) return {
1303
+ matched: false,
1304
+ reason: "condition"
1305
+ };
1306
+ if (grant.where.op === "opaque" || grant.check?.op === "opaque") return {
1307
+ matched: false,
1308
+ reason: "opaque-condition"
1309
+ };
1310
+ const matched = evaluateCondition(grant.where, current, subject, now, scopes, related, onOpaque);
1311
+ if (unknown !== void 0) return {
1312
+ matched: false,
1313
+ reason: unknown
1314
+ };
1315
+ if (!matched) return {
1316
+ matched: false,
1317
+ reason: "condition"
1318
+ };
1319
+ }
1320
+ const checkCondition = grant.check ?? (permission.action === "update" ? grant.where : void 0);
1321
+ if (checkCondition !== void 0) {
1322
+ if (checkCondition.op === "opaque") return {
1323
+ matched: false,
1324
+ reason: "opaque-condition"
1325
+ };
1326
+ if (next === void 0) return {
1327
+ matched: false,
1328
+ reason: "condition"
1329
+ };
1330
+ const matched = evaluateCondition(checkCondition, next, subject, now, scopes, related, onOpaque);
1331
+ if (unknown !== void 0) return {
1332
+ matched: false,
1333
+ reason: unknown
1334
+ };
1335
+ if (!matched) return {
1336
+ matched: false,
1337
+ reason: "condition"
1338
+ };
1339
+ }
1340
+ return { matched: true };
1341
+ }
1342
+ /** A grant whose condition could not be answered; a deny with one denies. */
1343
+ function isUnevaluable(reason) {
1344
+ return reason === "relation-depth" || reason === "relation-unavailable" || reason === "closure-error" || reason === "opaque-condition";
1345
+ }
1346
+ function shouldConsumeQuota(source, simulated) {
1347
+ if (simulated) return false;
1348
+ switch (source) {
1349
+ case "can":
1350
+ case "filter":
1351
+ case "simulate":
1352
+ case "explain": return false;
1353
+ case "decide":
1354
+ case "assert":
1355
+ case "endpoint":
1356
+ case "adapter":
1357
+ case "approval":
1358
+ case void 0: return true;
1359
+ default: return source;
1360
+ }
1361
+ }
1362
+ function isDelegatedPermission(policy, permission) {
1363
+ const providers = policy.providers;
1364
+ if (providers === void 0 || providers.length === 0) return false;
1365
+ for (const provider of providers) if (provider.handles(permission)) return true;
1366
+ return false;
1367
+ }
1368
+ /** The `MatchedGrant` view of a grant, shared by `matched` and the trace. */
1369
+ function matchedOf(grant, permissionKey, breakGlass) {
1370
+ return compact({
1371
+ role: grant.role,
1372
+ permission: permissionKey,
1373
+ name: grant.name,
1374
+ to: grant.to,
1375
+ where: grant.where,
1376
+ check: grant.check,
1377
+ approval: grant.approval,
1378
+ hosted: grant.hosted,
1379
+ breakGlass
1380
+ });
1381
+ }
1382
+ function skip(tracer, grant, permissionKey, why) {
1383
+ tracer?.skipped.push({
1384
+ role: grant.role,
1385
+ permission: permissionKey,
1386
+ effect: grant.effect,
1387
+ why
1388
+ });
1389
+ }
1390
+ function traceOf(tracer) {
1391
+ return {
1392
+ evaluated: tracer.evaluated,
1393
+ allows: tracer.allows,
1394
+ denies: tracer.denies,
1395
+ skipped: tracer.skipped
1396
+ };
1397
+ }
1398
+ function evaluate(policy, given, permission, data, options, env) {
1399
+ const subject = subjectForPermission(given, permission.key);
1400
+ const now = options.now ?? nowSeconds();
1401
+ const trusted = options.trusted === true;
1402
+ const resource = getResource(policy.permissions, permission.resource);
1403
+ let { current, next } = rowValues(permission, data);
1404
+ const tracer = options.explain === true ? {
1405
+ evaluated: 0,
1406
+ allows: [],
1407
+ denies: [],
1408
+ skipped: []
1409
+ } : void 0;
1410
+ const complete = (decision, membership) => {
1411
+ const final = env.outcomeOnly === true ? decision : freezeDeep(tracer === void 0 ? decision : {
1412
+ ...decision,
1413
+ trace: traceOf(tracer)
1414
+ });
1415
+ finish(policy, given, permission, current, final, options, env, trusted, membership);
1416
+ return final;
1417
+ };
1418
+ try {
1419
+ if (data !== void 0 || permission.kind === "instance" && policy.validate === "always") {
1420
+ const validated = validateBoundary(permission, resource, permission.kind === "instance" && isRowPair(data) ? data.current : data, policy.validate, trusted, options.boundary ?? "manual");
1421
+ if (permission.kind === "instance" && isRowPair(data)) {
1422
+ current = validated;
1423
+ next = validateBoundary(permission, resource, data.next, policy.validate, trusted, options.boundary ?? "manual");
1424
+ } else if (permission.kind === "instance") {
1425
+ current = validated;
1426
+ next = validated;
1427
+ } else next = validated;
1428
+ }
1429
+ } catch (error) {
1430
+ if (error instanceof PermDockValidationError && error.code === "invalid-data") return complete({
1431
+ outcome: "denied",
1432
+ denials: [{
1433
+ role: null,
1434
+ reason: "validation",
1435
+ detail: error
1436
+ }],
1437
+ alternatives: []
1438
+ });
1439
+ throw error;
1440
+ }
1441
+ if (isDelegatedPermission(policy, permission)) return complete({
1442
+ outcome: "denied",
1443
+ denials: [{
1444
+ role: null,
1445
+ reason: "pdp-unavailable",
1446
+ detail: "use permdock/pdp createPermDock"
1447
+ }],
1448
+ alternatives: []
1449
+ });
1450
+ const scopes = scopeList(policy.scopes);
1451
+ const declared = declaredRoleNames(policy);
1452
+ const principalRoles = subject.principal?.roles ?? [];
1453
+ const globalNames = expandRoleNames(principalRoles, declared, env.customRoles, subject.principal?.tenant);
1454
+ if (subject.principal !== null && globalNames.unknown.length > 0) emitSafe(env.listeners.auth, {
1455
+ reason: "unknown-role",
1456
+ source: "roles"
1457
+ }, env.listeners);
1458
+ const denials = [];
1459
+ const allows = [];
1460
+ const matchingRoles = new Set(globalNames.roles);
1461
+ for (const membership of subject.principal?.memberships ?? []) {
1462
+ if (!inTeam(membership, scopes, env.team)) continue;
1463
+ const expanded = expandRoleNames(membership.roles, declared, env.customRoles, tenantOf(membership, scopes));
1464
+ for (const name of expanded.roles) matchingRoles.add(name);
1465
+ for (const name of expanded.unknown) denials.push({
1466
+ role: name,
1467
+ reason: "unknown-role"
1468
+ });
1469
+ }
1470
+ const actorVias = actorRequiredVias(policy.index.supports);
1471
+ if (actorVias.size > 0 && subject.actor === void 0 && (subject.principal?.memberships ?? []).some((membership) => isSupportMembership(membership, actorVias) && !isMembershipExpired(membership, now) && inTeam(membership, scopes, env.team))) return complete({
1472
+ outcome: "denied",
1473
+ denials: [{
1474
+ role: null,
1475
+ reason: "actor-required"
1476
+ }],
1477
+ alternatives: []
1478
+ });
1479
+ const purposes = purposesOf(subject);
1480
+ const forPermission = policy.index.grantsByKey.get(permission.key) ?? [];
1481
+ const candidates = forPermission.filter((grant) => grant.breakGlass === void 0).map((grant) => ({ grant }));
1482
+ for (const item of env.customGrants) if (item.grant.permission.key === permission.key) candidates.push({
1483
+ grant: item.grant,
1484
+ custom: item.role
1485
+ });
1486
+ let breakGlassGrant;
1487
+ let breakGlassObligations = [];
1488
+ const breakGlassOverrides = /* @__PURE__ */ new Set();
1489
+ let breakGlassDenial;
1490
+ for (const grant of forPermission) {
1491
+ if (grant.breakGlass === void 0) continue;
1492
+ if (tracer !== void 0) tracer.evaluated += 1;
1493
+ if (!matchGrantee(grant.to, subject, now, resource, scopes).matched) {
1494
+ skip(tracer, grant, permission.key, "grantee");
1495
+ continue;
1496
+ }
1497
+ const result = evaluateBreakGlass(grant.breakGlass, subject, now);
1498
+ if (result.kind === "inactive") {
1499
+ skip(tracer, grant, permission.key, "break-glass-inactive");
1500
+ continue;
1501
+ }
1502
+ for (const name of grant.breakGlass.overrides) breakGlassOverrides.add(name);
1503
+ if (result.kind === "granted") {
1504
+ breakGlassGrant = grant;
1505
+ breakGlassObligations = result.obligations;
1506
+ break;
1507
+ }
1508
+ breakGlassDenial ??= result.reason === "insufficient-user-authentication" ? {
1509
+ role: null,
1510
+ reason: result.reason,
1511
+ to: result.to
1512
+ } : {
1513
+ role: null,
1514
+ reason: result.reason
1515
+ };
1516
+ }
1517
+ const holdsCustom = (custom) => isGlobalCustomRole(custom) ? holdsGlobalCustomRole(principalRoles, custom) : (subject.principal?.memberships ?? []).some((membership) => inTeam(membership, scopes, env.team) && holdsCustomRole(membership, custom, scopes));
1518
+ const walkRole = env.relations?.available === true ? (membership, row) => {
1519
+ const on = membership.on;
1520
+ const condition = on === void 0 ? void 0 : resourceRoleCondition(resource, on.resource, [on.id], policy.resources);
1521
+ return condition === void 0 || env.relations === void 0 ? false : resolveRelated(condition, row, subject, now, env.relations);
1522
+ } : void 0;
1523
+ for (const { grant, custom } of candidates) {
1524
+ const displayRole = grant.role;
1525
+ if (tracer !== void 0) tracer.evaluated += 1;
1526
+ if (grant.viaOnly !== void 0 && !(subject.principal?.memberships ?? []).some((membership) => membership.via === grant.viaOnly && !isMembershipExpired(membership, now) && inTeam(membership, scopes, env.team))) {
1527
+ skip(tracer, grant, permission.key, "via-only");
1528
+ continue;
1529
+ }
1530
+ const required = grant.purpose;
1531
+ if (required !== void 0 && !purposes.some((purpose) => required.includes(purpose))) {
1532
+ skip(tracer, grant, permission.key, "purpose");
1533
+ continue;
1534
+ }
1535
+ const granteeMatch = matchGrantee(grant.to, subject, now, resource, scopes, policy.resources, grant.effect === "deny");
1536
+ if (!granteeMatch.matched) {
1537
+ const reason = granteeMatch.reason ?? "no-grant";
1538
+ if (reason === "not-entitled" && !flattenGrantee(grant.to).every((item) => item.kind !== "role" || (custom === void 0 ? item.scope === "global" ? globalNames.roles.includes(item.role) : matchingRoles.has(item.role) : holdsCustom(custom)))) {
1539
+ skip(tracer, grant, permission.key, "grantee");
1540
+ continue;
1541
+ }
1542
+ denials.push((reason === "insufficient-user-authentication" || reason === "not-entitled") && grant.to !== void 0 ? {
1543
+ role: displayRole,
1544
+ reason,
1545
+ to: grant.to
1546
+ } : {
1547
+ role: displayRole,
1548
+ reason
1549
+ });
1550
+ continue;
1551
+ }
1552
+ const roleItems = flattenGrantee(grant.to).filter((item) => item.kind === "role");
1553
+ let scopeMembership;
1554
+ let roleOk = roleItems.length === 0;
1555
+ if (roleItems.length > 0) {
1556
+ if (subject.principal === null) {
1557
+ denials.push({
1558
+ role: displayRole,
1559
+ reason: "anonymous"
1560
+ });
1561
+ continue;
1562
+ }
1563
+ let allHeld = true;
1564
+ for (const roleItem of roleItems) {
1565
+ if (!(custom === void 0 ? roleItem.scope === "global" ? globalNames.roles.includes(roleItem.role) : matchingRoles.has(roleItem.role) : holdsCustom(custom))) {
1566
+ skip(tracer, grant, permission.key, "role");
1567
+ allHeld = false;
1568
+ break;
1569
+ }
1570
+ const matchRow = (row) => matchScopedMembership(subject, roleItem.scope, roleItem.role, row, scopes, resource, policy.resources, now, (membership) => {
1571
+ if (custom === void 0) return expandRoleNames(membership.roles, declared, env.customRoles, tenantOf(membership, scopes)).roles;
1572
+ return holdsCustomRole(membership, custom, scopes) ? [custom.name] : [];
1573
+ }, env.team, walkRole, permission.kind === "instance", options.scope);
1574
+ const scopeMatch = matchWriteScope(matchRow, permission.kind === "instance", current, next);
1575
+ if (!scopeMatch.ok) {
1576
+ denials.push({
1577
+ role: roleItem.role,
1578
+ reason: scopeMatch.reason
1579
+ });
1580
+ allHeld = false;
1581
+ break;
1582
+ }
1583
+ scopeMembership = scopeMatch.membership ?? scopeMembership;
1584
+ }
1585
+ roleOk = allHeld;
1586
+ }
1587
+ if (!roleOk) continue;
1588
+ if (!isActive(grant.validity, now)) {
1589
+ if (grant.effect === "allow") denials.push({
1590
+ role: displayRole,
1591
+ reason: "inactive-grant",
1592
+ detail: grant.validity
1593
+ });
1594
+ else skip(tracer, grant, permission.key, "validity");
1595
+ continue;
1596
+ }
1597
+ const requirement = grant.requires === void 0 || grant.effect !== "allow" ? void 0 : requirementCondition(policy, subject, grant.requires, resource, now, env.customRoles, env.customGrants);
1598
+ const merged = freezeDeep(compact({
1599
+ ...grant,
1600
+ where: combineWhere(combineWhere(grant.where, granteeMatch.where), requirement)
1601
+ }));
1602
+ const condition = evaluateGrantCondition(merged, permission, current, next, subject, now, scopes, env.relations, (target, id, key) => inheritedVerdict(policy, given, target, id, key, now, env));
1603
+ if (!condition.matched && grant.effect === "deny" && isUnevaluable(condition.reason) && grantCoversField(grant.fields, options.field, grant.effect)) {
1604
+ if (condition.reason === "closure-error") emitSafe(env.listeners.error, condition.cause ?? /* @__PURE__ */ new Error("closure-error"), env.listeners);
1605
+ tracer?.denies.push(matchedOf(merged, permission.key));
1606
+ return complete({
1607
+ outcome: "denied",
1608
+ denials: [{
1609
+ role: displayRole,
1610
+ reason: condition.reason ?? "relation-unavailable"
1611
+ }],
1612
+ alternatives: []
1613
+ });
1614
+ }
1615
+ if (!condition.matched) {
1616
+ if (condition.reason === "closure-error") emitSafe(env.listeners.error, condition.cause ?? /* @__PURE__ */ new Error("closure-error"), env.listeners);
1617
+ denials.push({
1618
+ role: displayRole,
1619
+ reason: condition.reason ?? "condition",
1620
+ detail: condition.cause
1621
+ });
1622
+ continue;
1623
+ }
1624
+ if (!grantCoversField(grant.fields, options.field, grant.effect)) {
1625
+ skip(tracer, grant, permission.key, "field");
1626
+ continue;
1627
+ }
1628
+ if (grant.effect === "deny") {
1629
+ tracer?.denies.push(matchedOf(merged, permission.key));
1630
+ if (grant.name !== void 0 && breakGlassOverrides.has(grant.name)) {
1631
+ if (breakGlassGrant !== void 0) continue;
1632
+ if (breakGlassDenial !== void 0) return complete({
1633
+ outcome: "denied",
1634
+ denials: [breakGlassDenial],
1635
+ alternatives: env.skipAlternatives ? [] : alternativesFor(policy, permission, subject, now, env)
1636
+ });
1637
+ }
1638
+ return complete({
1639
+ outcome: "denied",
1640
+ denials: [grant.name === void 0 ? {
1641
+ role: displayRole,
1642
+ reason: "deny"
1643
+ } : {
1644
+ role: displayRole,
1645
+ reason: "deny",
1646
+ detail: { name: grant.name }
1647
+ }],
1648
+ alternatives: env.skipAlternatives ? [] : alternativesFor(policy, permission, subject, now, env)
1649
+ });
1650
+ }
1651
+ tracer?.allows.push(matchedOf(merged, permission.key));
1652
+ allows.push(scopeMembership === void 0 ? { grant: merged } : {
1653
+ grant: merged,
1654
+ membership: scopeMembership
1655
+ });
1656
+ }
1657
+ if (breakGlassGrant !== void 0) {
1658
+ tracer?.allows.push(matchedOf(breakGlassGrant, permission.key, true));
1659
+ allows.push({
1660
+ grant: breakGlassGrant,
1661
+ obligations: breakGlassObligations,
1662
+ breakGlass: true
1663
+ });
1664
+ } else if (breakGlassDenial !== void 0) denials.unshift(breakGlassDenial);
1665
+ if (allows.length === 0) {
1666
+ const reason = denials[0]?.reason ?? (subject.principal === null ? "anonymous" : globalNames.unknown.length > 0 && globalNames.roles.length === 0 ? "unknown-role" : "no-grant");
1667
+ return complete({
1668
+ outcome: "denied",
1669
+ denials: denials.length > 0 ? denials : [{
1670
+ role: null,
1671
+ reason
1672
+ }],
1673
+ alternatives: env.skipAlternatives ? [] : alternativesFor(policy, permission, subject, now, env)
1674
+ });
1675
+ }
1676
+ if (subject.stale === true && (policy.fresh ?? []).includes(permission.key)) return complete({
1677
+ outcome: "denied",
1678
+ denials: [{
1679
+ role: null,
1680
+ reason: "stale-credentials"
1681
+ }],
1682
+ alternatives: []
1683
+ });
1684
+ const ceiling = delegatedPermissions(policy.delegations, subject, matchingRoles, now);
1685
+ if (ceiling !== void 0 && !ceiling.has(permission.key)) return complete({
1686
+ outcome: "denied",
1687
+ denials: [{
1688
+ role: null,
1689
+ reason: "not-delegated"
1690
+ }],
1691
+ alternatives: env.skipAlternatives ? [] : alternativesFor(policy, permission, subject, now, env)
1692
+ });
1693
+ const unscoped = subject.actor !== void 0 && ceiling === void 0;
1694
+ let delegationMiss = coveredByDelegation(permission, subject.delegation, resourceIdOf(current), unscoped);
1695
+ const requirementsCovered = allows.filter((candidate) => coversRequirements(policy.permissions, candidate.grant.requires, subject.delegation, resourceIdOf(current), unscoped));
1696
+ let usable = delegationMiss === void 0 ? requirementsCovered : requirementsCovered.filter((candidate) => requiresStandIn(candidate.grant));
1697
+ if (delegationMiss === "not-delegated" && usable.length > 0) delegationMiss = void 0;
1698
+ if (delegationMiss === void 0 && usable.length === 0) delegationMiss = "not-delegated";
1699
+ if (delegationMiss !== void 0) return complete({
1700
+ outcome: "denied",
1701
+ denials: [{
1702
+ role: null,
1703
+ reason: delegationMiss
1704
+ }],
1705
+ alternatives: env.skipAlternatives ? [] : alternativesFor(policy, permission, subject, now, env)
1706
+ });
1707
+ const approvalPolicies = env.approvalPolicies;
1708
+ if (approvalPolicies === "failed" && usable.length > 0) return complete({
1709
+ outcome: "denied",
1710
+ denials: [{
1711
+ role: null,
1712
+ reason: "approval",
1713
+ detail: APPROVAL_POLICY_UNAVAILABLE
1714
+ }],
1715
+ alternatives: []
1716
+ });
1717
+ const approvalOf = (candidate) => approvalPolicies === void 0 || approvalPolicies === "failed" ? candidate.grant.approval : tightenApproval(candidate.grant.approval, approvalPolicies, {
1718
+ permission: permission.key,
1719
+ tenant: decisionTenant(subject, candidate.membership),
1720
+ subject,
1721
+ current,
1722
+ next,
1723
+ now,
1724
+ scopes: scopeList(policy.scopes)
1725
+ });
1726
+ const quotaDenials = [];
1727
+ let matchedAllow;
1728
+ let approval;
1729
+ let quotaState = {};
1730
+ for (const candidate of usable) {
1731
+ approval = approvalOf(candidate);
1732
+ const consume = !requiresApproval(approval) && shouldConsumeQuota(options.source, env.simulated);
1733
+ const quota = applyQuota({
1734
+ store: env.limits,
1735
+ cache: env.limitCache,
1736
+ grant: candidate.grant,
1737
+ permissionKey: permission.key,
1738
+ subjectId: subject.principal?.id ?? "",
1739
+ tenant: subject.principal?.tenant,
1740
+ now,
1741
+ consume
1742
+ });
1743
+ if (quota.ok) {
1744
+ matchedAllow = candidate;
1745
+ quotaState = compact({
1746
+ quota: quota.quota,
1747
+ obligations: quota.obligations
1748
+ });
1749
+ break;
1750
+ }
1751
+ quotaDenials.push(quota.reason === "limit" ? {
1752
+ role: candidate.grant.role,
1753
+ reason: "limit",
1754
+ detail: quota.detail
1755
+ } : {
1756
+ role: candidate.grant.role,
1757
+ reason: quota.reason
1758
+ });
1759
+ }
1760
+ if (matchedAllow === void 0) return complete({
1761
+ outcome: "denied",
1762
+ denials: quotaDenials.length > 0 ? quotaDenials : denials,
1763
+ alternatives: env.skipAlternatives ? [] : alternativesFor(policy, permission, subject, now, env)
1764
+ });
1765
+ const resourceId = permission.kind === "collection" ? "*" : rowIdOf(current, resource?.id);
1766
+ const version = approval !== void 0 && approval !== "human" && approval.staleOn === "resource-change" && resource?.version !== void 0 ? versionOf(current, resource.version) : void 0;
1767
+ const token = env.simulated ? "pd1.simulated" : env.outcomeOnly === true ? "pd1.outcome" : decisionToken({
1768
+ key: permission.key,
1769
+ resourceId,
1770
+ principal: subject.principal,
1771
+ actor: subject.actor,
1772
+ fingerprint: policy.fingerprint,
1773
+ version,
1774
+ payload: resourceId === "*" && (next ?? current) !== void 0 ? payloadDigest(next ?? current) : void 0
1775
+ });
1776
+ const matched = compact({
1777
+ ...matchedOf(matchedAllow.grant, permission.key, matchedAllow.breakGlass),
1778
+ approval
1779
+ });
1780
+ const obligations = [...quotaState.obligations ?? [], ...matchedAllow.obligations ?? []];
1781
+ return complete(requiresApproval(approval) ? {
1782
+ outcome: "approval-required",
1783
+ grant: matched,
1784
+ reason: "human",
1785
+ token
1786
+ } : {
1787
+ outcome: "granted",
1788
+ subject,
1789
+ matched,
1790
+ token,
1791
+ ...quotaState,
1792
+ ...obligations.length === 0 ? {} : { obligations }
1793
+ }, matchedAllow.membership);
1794
+ }
1795
+ //#endregion
1796
+ //#region src/core/ownership.ts
1797
+ function bindingOf(policy, name) {
1798
+ return policy.rolesByName.get(name);
1799
+ }
1800
+ function roleMeta(policy, name) {
1801
+ return bindingOf(policy, name)?.meta ?? findRole(policy.vocabulary?.roles, name)?.meta;
1802
+ }
1803
+ /** A role with `for` is held only through a membership of one of those kinds. */
1804
+ function mayHoldVia(policy, role, via) {
1805
+ const kinds = bindingOf(policy, role)?.for;
1806
+ return kinds === void 0 || via !== void 0 && kinds.includes(via);
1807
+ }
1808
+ function sameList(a, b) {
1809
+ return a.length === b.length && a.every((item, index) => item === b[index]);
1810
+ }
1811
+ /**
1812
+ * The identity provider may only hand out what the application could: a
1813
+ * declared role with `assignable: false` (an owner, a platform role) never
1814
+ * rides in on a `managedBy: 'idp'` membership. A name the policy does not
1815
+ * declare stays, because only a tenant's custom role can give it meaning.
1816
+ */
1817
+ function mayHoldManaged(policy, role, membership) {
1818
+ return !isExternallyManaged(membership) || bindingOf(policy, role)?.assignable !== false;
1819
+ }
1820
+ /**
1821
+ * Drops every role a membership's kind may not hold (fail-closed: a missing
1822
+ * `via` is no kind) and every non-assignable role on an identity-provider
1823
+ * membership. Global roles have no kind, so a role with `for` held globally
1824
+ * is dropped too.
1825
+ */
1826
+ function applyRoleKinds(policy, roles, memberships) {
1827
+ const kinds = policy.roles.some((binding) => binding.for !== void 0);
1828
+ if (!kinds && !memberships.some(isExternallyManaged)) return {
1829
+ roles,
1830
+ memberships
1831
+ };
1832
+ return {
1833
+ roles: kinds ? roles?.filter((name) => mayHoldVia(policy, name, void 0)) ?? roles : roles,
1834
+ memberships: memberships.map((membership) => {
1835
+ const allowed = membership.roles.filter((name) => mayHoldVia(policy, name, membership.via) && mayHoldManaged(policy, name, membership));
1836
+ return sameList(allowed, membership.roles) ? membership : freezeDeep({
1837
+ ...membership,
1838
+ roles: allowed
1839
+ });
1840
+ })
1841
+ };
1842
+ }
1843
+ function usesAssigns(policy) {
1844
+ return policy.roles.some((binding) => binding.assigns !== void 0);
1845
+ }
1846
+ /** Declared role names in declaration order: bindings first, then vocabulary-only leaves. */
1847
+ function declarationOrder(policy) {
1848
+ const names = policy.roles.map((binding) => binding.name);
1849
+ const seen = new Set(names);
1850
+ for (const leaf of listRoles(policy.vocabulary?.roles)) if (!seen.has(leaf.key)) {
1851
+ names.push(leaf.key);
1852
+ seen.add(leaf.key);
1853
+ }
1854
+ return names;
1855
+ }
1856
+ /**
1857
+ * Each role's depth in the `assigns` graph: a role nobody else assigns is 0,
1858
+ * a role another assigns sits one below its deepest assigner. Cycles stop
1859
+ * after one pass per role.
1860
+ */
1861
+ function assignDepths(policy) {
1862
+ const names = declarationOrder(policy);
1863
+ const depth = new Map(names.map((name) => [name, 0]));
1864
+ for (let pass = 0; pass < names.length; pass += 1) {
1865
+ let changed = false;
1866
+ for (const binding of policy.roles) {
1867
+ const from = depth.get(binding.name) ?? 0;
1868
+ for (const target of binding.assigns ?? []) if (target !== binding.name && (depth.get(target) ?? 0) < from + 1) {
1869
+ depth.set(target, from + 1);
1870
+ changed = true;
1871
+ }
1872
+ }
1873
+ if (!changed) break;
1874
+ }
1875
+ return depth;
1876
+ }
1877
+ /**
1878
+ * `names` ordered by rank: assigners before the roles they assign, then
1879
+ * declaration order. Without an `assigns` graph the order is kept.
1880
+ */
1881
+ function rankRoles(policy, names) {
1882
+ if (!usesAssigns(policy)) return names;
1883
+ const order = declarationOrder(policy);
1884
+ const depth = assignDepths(policy);
1885
+ const index = (name) => {
1886
+ const found = order.indexOf(name);
1887
+ return found === -1 ? order.length : found;
1888
+ };
1889
+ return [...names].toSorted((a, b) => (depth.get(a) ?? Number.MAX_SAFE_INTEGER) - (depth.get(b) ?? Number.MAX_SAFE_INTEGER) || index(a) - index(b));
1890
+ }
1891
+ /** The distinct `meta.audience` values of `names`, in rank order. */
1892
+ function audiencesOf(policy, names) {
1893
+ const out = [];
1894
+ for (const name of rankRoles(policy, names)) {
1895
+ const audience = roleMeta(policy, name)?.audience;
1896
+ if (typeof audience === "string" && !out.includes(audience)) out.push(audience);
1897
+ }
1898
+ return out;
1899
+ }
1900
+ /** Whether `membership` is the instance itself or one of its ancestors named in `within`. */
1901
+ function coversInstance(membership, scopes, scope, id, within) {
1902
+ if (membership.scope === void 0 || membership.id === void 0) return false;
1903
+ if (membership.scope === scope) return sameId(membership.id, id);
1904
+ if (!scopeChain(scopes, scope).slice(1).includes(membership.scope)) return false;
1905
+ const wanted = within === void 0 ? void 0 : Object.entries(within).find(([key]) => resolveScope(scopes, key) === membership.scope)?.[1] ?? void 0;
1906
+ return wanted !== void 0 && scopeIdOf(membership, membership.scope) === wanted;
1907
+ }
1908
+ /** Roles the principal holds at the instance, at an ancestor named in `within`, or globally. */
1909
+ function rolesAtInstance(policy, principal, scopes, scope, id, within, now) {
1910
+ const declared = declaredRoleNames$1(policy);
1911
+ const names = new Set((principal.roles ?? []).filter((name) => declared.has(name)));
1912
+ for (const membership of principal.memberships ?? []) if (!isMembershipExpired(membership, now) && coversInstance(membership, scopes, scope, id, within)) for (const name of membership.roles) names.add(name);
1913
+ return rankRoles(policy, [...names]);
1914
+ }
1915
+ /** Whether the principal holds `role` on a live membership of exactly this instance. */
1916
+ function holdsAt(principal, role, scope, id, now) {
1917
+ return (principal.memberships ?? []).some((membership) => membership.scope === scope && sameId(membership.id, id) && !isMembershipExpired(membership, now) && membership.roles.includes(role));
1918
+ }
1919
+ function includedRoles(role) {
1920
+ return isReadonlyArray(role.includes) ? role.includes.filter((name) => typeof name === "string") : [];
1921
+ }
1922
+ /**
1923
+ * The membership kinds a custom role may be held through: those every
1924
+ * included declared role with `for` allows. `undefined` when none restricts.
1925
+ */
1926
+ function customForKinds(policy, role) {
1927
+ let kinds;
1928
+ for (const name of includedRoles(role)) {
1929
+ const listed = bindingOf(policy, name)?.for;
1930
+ if (listed !== void 0) kinds = kinds === void 0 ? listed : kinds.filter((kind) => listed.includes(kind));
1931
+ }
1932
+ return kinds;
1933
+ }
1934
+ function conflictsWith(policy, role) {
1935
+ const out = new Set(bindingOf(policy, role)?.exclusiveWith ?? []);
1936
+ for (const binding of policy.roles) if (binding.exclusiveWith?.includes(role) === true) out.add(binding.name);
1937
+ return out;
1938
+ }
1939
+ /** What the change does to the instance's holder count. */
1940
+ function countRules(binding, role, holders, delta, deny) {
1941
+ if (binding === void 0 || delta === 0) return;
1942
+ const min = binding.min ?? 0;
1943
+ if (!(min > 0 || binding.max !== void 0 || binding.transferOnly === true)) return;
1944
+ if (!(holders !== void 0 && Number.isInteger(holders) && holders >= 0)) {
1945
+ deny(delta < 0 && min > 0 ? "last-holder" : delta > 0 && binding.max !== void 0 ? "max-holders" : "transfer-only", {
1946
+ role,
1947
+ holders: null
1948
+ });
1949
+ return;
1950
+ }
1951
+ const after = holders + delta;
1952
+ if (delta < 0 && min > 0 && after < min) deny("last-holder", {
1953
+ role,
1954
+ min,
1955
+ holders
1956
+ });
1957
+ if (delta > 0 && binding.max !== void 0 && after > binding.max) deny("max-holders", {
1958
+ role,
1959
+ max: binding.max,
1960
+ holders
1961
+ });
1962
+ if (binding.transferOnly === true && holders > 0 && after > 0) deny("transfer-only", {
1963
+ role,
1964
+ holders
1965
+ });
1966
+ }
1967
+ /**
1968
+ * A live membership of the principal on the instance or on an instance under
1969
+ * it: the one in-band fact that ties a nested instance to a tenant.
1970
+ */
1971
+ function heldAnchor(principal, scopes, scope, id, now) {
1972
+ return (principal.memberships ?? []).find((membership) => !isMembershipExpired(membership, now) && membership.scope !== void 0 && scopeChain(scopes, membership.scope).includes(scope) && scopeIdOf(membership, scope) === id && tenantOf(membership, scopes) !== void 0);
1973
+ }
1974
+ /**
1975
+ * The one rule check behind `permdock.decideRoleChange`. The actor is always
1976
+ * the instance's own principal; nothing in `change` can stand in for it.
1977
+ */
1978
+ function decideRoleChange(policy, principal, scopes, change, customRoles, authority, now, options = {}) {
1979
+ const name = typeof change?.role === "string" ? change.role : change?.role?.key;
1980
+ const denials = [];
1981
+ const deny = (reason, detail) => {
1982
+ denials.push(compact({
1983
+ role: name ?? null,
1984
+ reason,
1985
+ detail
1986
+ }));
1987
+ };
1988
+ const done = (role) => freezeDeep(denials.length === 0 ? {
1989
+ outcome: "granted",
1990
+ change,
1991
+ role
1992
+ } : {
1993
+ outcome: "denied",
1994
+ change,
1995
+ denials
1996
+ });
1997
+ if (principal === null) {
1998
+ deny("anonymous");
1999
+ return done(null);
2000
+ }
2001
+ const kind = change?.kind;
2002
+ const target = change?.target;
2003
+ if (typeof name !== "string" || kind !== "assign" && kind !== "revoke" && kind !== "transfer" || typeof change.id !== "string" || change.id === "" || target === null || typeof target !== "object" || typeof target.id !== "string" || target.id === "") {
2004
+ deny("validation");
2005
+ return done(null);
2006
+ }
2007
+ const binding = bindingOf(policy, name);
2008
+ const declared = declaredRoleNames$1(policy).has(name);
2009
+ const named = declared ? [] : tenantCustomRoles(policy, customRoles).filter((role) => role.name === name);
2010
+ if (!declared && named.length === 0) {
2011
+ deny("unknown-role");
2012
+ return done(null);
2013
+ }
2014
+ const scope = resolveScope(scopes, change.scope);
2015
+ const customAt = named.map((role) => customRoleScope(role, scopes));
2016
+ const on = declared ? binding?.on ?? findRole(policy.vocabulary?.roles, name)?.on : customAt.includes(scope) ? scope : customAt[0];
2017
+ const heldAt = typeof on === "string" ? resolveScope(scopes, on) : void 0;
2018
+ if (scope === void 0 || heldAt === void 0 || heldAt !== scope) {
2019
+ deny("scope", { expected: heldAt ?? null });
2020
+ return done(null);
2021
+ }
2022
+ const root = scopes[0]?.name;
2023
+ const supplied = change.within === void 0 ? void 0 : Object.entries(change.within).find(([key]) => resolveScope(scopes, key) === root)?.[1];
2024
+ let tenant;
2025
+ let within = change.within;
2026
+ if (scope === root) tenant = change.id;
2027
+ else {
2028
+ const anchor = heldAnchor(principal, scopes, scope, change.id, now);
2029
+ const held = anchor === void 0 ? void 0 : tenantOf(anchor, scopes);
2030
+ if (held !== void 0) {
2031
+ tenant = supplied === void 0 || supplied === held ? held : void 0;
2032
+ within = anchor?.within;
2033
+ } else if (options.trusted === true) tenant = supplied;
2034
+ }
2035
+ if (tenant === void 0) {
2036
+ deny("no-membership", {
2037
+ scope,
2038
+ id: change.id
2039
+ });
2040
+ return done(null);
2041
+ }
2042
+ const custom = named.find((role) => sameId(role.tenant, tenant) && customRoleScope(role, scopes) === scope && sameId(customRoleId(role) ?? change.id, change.id));
2043
+ if (!declared && custom === void 0) {
2044
+ deny("unknown-role");
2045
+ return done(null);
2046
+ }
2047
+ if (target.managedBy === "idp") {
2048
+ deny("externally-managed");
2049
+ return done(null);
2050
+ }
2051
+ const self = target.id === principal.id;
2052
+ const targetRoles = isReadonlyArray(target.roles) ? target.roles : [];
2053
+ const already = targetRoles.includes(name);
2054
+ let by = null;
2055
+ if (kind === "transfer") {
2056
+ if (self) deny("self-demotion");
2057
+ if (holdsAt(principal, name, scope, change.id, now)) by = name;
2058
+ else deny("not-assignable-by", { holds: false });
2059
+ } else {
2060
+ if (self) deny(kind === "revoke" ? "self-demotion" : "not-assignable-by", { self: true });
2061
+ const allowed = authority(tenant);
2062
+ const revocable = kind === "revoke" && custom !== void 0 && allowed.inert?.has(name);
2063
+ if (!allowed.assignable.has(name) && revocable !== true) deny("not-assignable-by");
2064
+ else if (custom === void 0 && usesAssigns(policy) && !allowed.manage) {
2065
+ const held = rolesAtInstance(policy, principal, scopes, scope, change.id, within, now);
2066
+ by = held.find((role) => bindingOf(policy, role)?.assigns?.includes(name) === true) ?? null;
2067
+ if (by === null) deny("not-assignable-by", { held });
2068
+ }
2069
+ }
2070
+ if (kind !== "revoke" && !already) {
2071
+ const kinds = custom === void 0 ? binding?.for : customForKinds(policy, custom);
2072
+ if (kinds !== void 0 && (target.via === void 0 || !kinds.includes(target.via))) deny("not-allowed-for-membership", {
2073
+ via: target.via ?? null,
2074
+ for: kinds
2075
+ });
2076
+ const conflicts = custom === void 0 ? conflictsWith(policy, name) : new Set(includedRoles(custom).flatMap((include) => Array.from(conflictsWith(policy, include))));
2077
+ const clash = targetRoles.filter((role) => conflicts.has(role));
2078
+ if (clash.length > 0) deny("conflicting-role", { with: clash });
2079
+ }
2080
+ const delta = kind === "assign" ? already ? 0 : 1 : kind === "revoke" ? targetRoles.length > 0 && !already ? 0 : -1 : already ? -1 : 0;
2081
+ countRules(binding, name, change.holders, delta, deny);
2082
+ return done(by);
2083
+ }
2084
+ //#endregion
2085
+ //#region src/core/who-can.ts
2086
+ const MAX_ROUNDS = 48;
2087
+ async function settle$1(cache) {
2088
+ for (let round = 0; round < MAX_ROUNDS; round += 1) {
2089
+ const pending = pendingRelations(cache);
2090
+ if (pending.length === 0) return;
2091
+ await Promise.all(pending);
2092
+ }
2093
+ }
2094
+ /** The holders on each instance a graph relation reads, or `undefined` when the graph cannot say. */
2095
+ async function walkHolders(condition, row, reader, cache) {
2096
+ let walk = relationWalk(condition, row, reader);
2097
+ if (walk === "relation-unavailable") {
2098
+ await settle$1(cache);
2099
+ walk = relationWalk(condition, row, reader);
2100
+ }
2101
+ if (walk === void 0) return [];
2102
+ if (walk === "relation-depth" || walk === "relation-unavailable") return;
2103
+ const { ids } = walk;
2104
+ const read = () => ids.map((id) => reader.holders({
2105
+ resource: condition.resource,
2106
+ id,
2107
+ relation: condition.relation
2108
+ }));
2109
+ let answers = read();
2110
+ if (answers.includes("pending")) {
2111
+ await settle$1(cache);
2112
+ answers = read();
2113
+ }
2114
+ const out = [];
2115
+ for (const [index, answer] of answers.entries()) {
2116
+ const id = ids[index];
2117
+ if (answer === "pending" || answer === "failed" || id === void 0) return;
2118
+ out.push({
2119
+ id,
2120
+ holders: answer
2121
+ });
2122
+ }
2123
+ return out;
2124
+ }
2125
+ async function discoverRole(item, allow, ctx) {
2126
+ if (typeof item.scope !== "string" || item.scope === "global") {
2127
+ ctx.incomplete();
2128
+ return;
2129
+ }
2130
+ const key = scopeField(ctx.resource, item.scope, ctx.scopes);
2131
+ const id = key === void 0 ? void 0 : relationId(ownGet(ctx.row, key));
2132
+ if (id === void 0) return;
2133
+ const members = await ctx.list(item.scope, id);
2134
+ if (members === null) {
2135
+ ctx.incomplete();
2136
+ return;
2137
+ }
2138
+ for (const member of members.filter((entry) => entry.membership.roles.includes(item.role))) ctx.add(member.id, allow ? {
2139
+ kind: "role",
2140
+ role: item.role,
2141
+ membership: member.membership
2142
+ } : void 0, member.membership);
2143
+ }
2144
+ function holderVia(holder, at, share, group) {
2145
+ if (!share) return {
2146
+ kind: "relation",
2147
+ ...at
2148
+ };
2149
+ return compact({
2150
+ kind: "share",
2151
+ ...at,
2152
+ expiresAt: holder.expiresAt,
2153
+ group
2154
+ });
2155
+ }
2156
+ /**
2157
+ * Principals holding `group`'s relation, through at most `budget` more groups
2158
+ * of its resource; `undefined` when a read failed. `memo` keeps each group's
2159
+ * members per budget across one discovery, so a group shared by many paths is
2160
+ * read once; a result cut short by a cycle is path-specific and not kept.
2161
+ */
2162
+ async function groupMembers(group, ctx, budget, seen, memo) {
2163
+ const key = JSON.stringify([
2164
+ group.resource,
2165
+ group.id,
2166
+ group.relation
2167
+ ]);
2168
+ const memoKey = `${budget}:${key}`;
2169
+ const known = memo.get(memoKey);
2170
+ if (known !== void 0) return {
2171
+ members: known,
2172
+ cut: false
2173
+ };
2174
+ let holders = ctx.reader.holders(group);
2175
+ if (holders === "pending") {
2176
+ await settle$1(ctx.cache);
2177
+ holders = ctx.reader.holders(group);
2178
+ }
2179
+ if (holders === "pending" || holders === "failed") return;
2180
+ const path = new Set(seen).add(key);
2181
+ const out = /* @__PURE__ */ new Set();
2182
+ let cut = false;
2183
+ for (const holder of holders) {
2184
+ if ("principal" in holder) {
2185
+ out.add(holder.principal.id);
2186
+ continue;
2187
+ }
2188
+ const nested = JSON.stringify([
2189
+ holder.group.resource,
2190
+ holder.group.id,
2191
+ holder.group.relation
2192
+ ]);
2193
+ const same = holder.group.resource === group.resource;
2194
+ if (path.has(nested)) {
2195
+ cut = true;
2196
+ continue;
2197
+ }
2198
+ if (same && budget <= 0) continue;
2199
+ const walk = await groupMembers(holder.group, ctx, same ? budget - 1 : 16, path, memo);
2200
+ if (walk === void 0) return;
2201
+ cut ||= walk.cut;
2202
+ for (const member of walk.members) out.add(member);
2203
+ }
2204
+ const members = [...out];
2205
+ if (!cut) memo.set(memoKey, members);
2206
+ return {
2207
+ members,
2208
+ cut
2209
+ };
2210
+ }
2211
+ async function discoverGraph(condition, allow, ctx) {
2212
+ const nodes = await walkHolders(condition, ctx.row, ctx.reader, ctx.cache);
2213
+ if (nodes === void 0) {
2214
+ ctx.incomplete();
2215
+ return;
2216
+ }
2217
+ const node = ctx.policy.resources.get(condition.resource);
2218
+ const memo = /* @__PURE__ */ new Map();
2219
+ for (const entry of nodes) for (const holder of entry.holders) {
2220
+ const at = {
2221
+ resource: condition.resource,
2222
+ relation: holder.relation,
2223
+ id: entry.id
2224
+ };
2225
+ const share = isEdgeRelation(node?.relations[holder.relation]);
2226
+ if ("principal" in holder) {
2227
+ ctx.add(holder.principal.id, allow ? holderVia(holder, at, share) : void 0);
2228
+ continue;
2229
+ }
2230
+ const walk = await groupMembers(holder.group, ctx, holder.group.resource === condition.resource ? 15 : 16, /* @__PURE__ */ new Set(), memo);
2231
+ if (walk === void 0) {
2232
+ ctx.incomplete();
2233
+ continue;
2234
+ }
2235
+ for (const member of walk.members) ctx.add(member, allow ? holderVia(holder, at, share, holder.group) : void 0);
2236
+ }
2237
+ }
2238
+ async function discoverRelation(item, allow, ctx, expanded = false) {
2239
+ const condition = relationCondition(item, ctx.resource, ctx.scopes, { resources: ctx.policy.resources });
2240
+ if (condition?.op === "related") {
2241
+ await discoverGraph(condition, allow, ctx);
2242
+ return;
2243
+ }
2244
+ const spec = ctx.resource?.relations[item.relation];
2245
+ if (spec?.includes !== void 0 && !expanded) {
2246
+ for (const name of expandRelation(ctx.resource, item.relation)) await discoverRelation({
2247
+ ...item,
2248
+ relation: name
2249
+ }, allow, ctx, true);
2250
+ return;
2251
+ }
2252
+ const via = allow ? {
2253
+ kind: "relation",
2254
+ resource: ctx.permission.resource,
2255
+ relation: item.relation,
2256
+ id: relationId(ownGet(ctx.row, ctx.resource?.id ?? "id")) ?? ""
2257
+ } : void 0;
2258
+ if (isFieldRelation(spec) && spec.memberOf !== void 0) {
2259
+ const scope = resolveScope(ctx.scopes, spec.memberOf);
2260
+ const id = relationId(ownGet(ctx.row, spec.field));
2261
+ const members = scope === void 0 || id === void 0 ? [] : await ctx.list(scope, id);
2262
+ if (members === null) {
2263
+ ctx.incomplete();
2264
+ return;
2265
+ }
2266
+ for (const member of members) ctx.add(member.id, via, member.membership);
2267
+ return;
2268
+ }
2269
+ const column = isFieldRelation(spec) ? spec.field : isPrincipalRelation(spec) ? spec.principal : void 0;
2270
+ const holder = column === void 0 ? void 0 : relationId(ownGet(ctx.row, column));
2271
+ if (holder !== void 0) ctx.add(holder, via);
2272
+ }
2273
+ function discover(grant, item, ctx) {
2274
+ const allow = grant.effect === "allow";
2275
+ switch (item.kind) {
2276
+ case "role": return discoverRole(item, allow, ctx);
2277
+ case "relation": return discoverRelation(item, allow, ctx);
2278
+ case "anyone":
2279
+ case "authenticated":
2280
+ case "plan":
2281
+ case "actor":
2282
+ case "assurance":
2283
+ case "inherit":
2284
+ ctx.incomplete();
2285
+ return Promise.resolve();
2286
+ default: return unknownKind(item, ctx);
2287
+ }
2288
+ }
2289
+ /** Holders of a grantee kind this build does not know cannot be listed. */
2290
+ function unknownKind(_item, ctx) {
2291
+ ctx.incomplete();
2292
+ return Promise.resolve();
2293
+ }
2294
+ function memberLister(source, scopes) {
2295
+ const listed = /* @__PURE__ */ new Map();
2296
+ const load = async (scope, id) => {
2297
+ if (source?.list === void 0) return null;
2298
+ try {
2299
+ return (await source.list({
2300
+ scope,
2301
+ id
2302
+ })).flatMap((entry) => typeof entry.principal?.id === "string" ? normalizeMemberships([entry.membership], scopes).map((membership) => ({
2303
+ id: entry.principal.id,
2304
+ membership
2305
+ })) : []);
2306
+ } catch {
2307
+ return null;
2308
+ }
2309
+ };
2310
+ return (scope, id) => {
2311
+ const key = JSON.stringify([scope, id]);
2312
+ const known = listed.get(key) ?? load(scope, id);
2313
+ listed.set(key, known);
2314
+ return known;
2315
+ };
2316
+ }
2317
+ async function whoCan(input) {
2318
+ const { policy, permission, row } = input;
2319
+ if (permission.kind !== "instance" || row === null || typeof row !== "object") return freezeDeep({
2320
+ permission: permission.key,
2321
+ holders: [],
2322
+ complete: false
2323
+ });
2324
+ const scopes = scopeList(policy.scopes);
2325
+ let complete = !input.customGrants.some((item) => item.grant.permission.key === permission.key);
2326
+ const found = /* @__PURE__ */ new Map();
2327
+ const ctx = {
2328
+ policy,
2329
+ scopes,
2330
+ resource: getResource(policy.permissions, permission.resource),
2331
+ permission,
2332
+ row,
2333
+ reader: input.reader,
2334
+ cache: input.cache,
2335
+ list: memberLister(input.memberships, scopes),
2336
+ add(id, via, membership) {
2337
+ const entry = found.get(id) ?? {
2338
+ memberships: [],
2339
+ via: []
2340
+ };
2341
+ found.set(id, entry);
2342
+ if (via !== void 0) entry.via.push(via);
2343
+ if (membership !== void 0) entry.memberships.push(membership);
2344
+ },
2345
+ incomplete() {
2346
+ complete = false;
2347
+ }
2348
+ };
2349
+ await Promise.all((policy.index.grantsByKey.get(permission.key) ?? []).flatMap((grant) => flattenGrantee(grant.to).map((item) => discover(grant, item, ctx))));
2350
+ const root = rootScope(scopes);
2351
+ const tenantKey = root === void 0 ? void 0 : scopeField(getResource(policy.permissions, permission.resource), root, scopes);
2352
+ const tenant = tenantKey === void 0 ? void 0 : relationId(ownGet(row, tenantKey));
2353
+ const env = {
2354
+ emit: false,
2355
+ simulated: true,
2356
+ skipAlternatives: true,
2357
+ customRoles: [],
2358
+ customGrants: [],
2359
+ listeners: emptyListeners(),
2360
+ sink: void 0,
2361
+ limits: void 0,
2362
+ limitCache: /* @__PURE__ */ new Map(),
2363
+ team: input.team,
2364
+ relations: input.reader
2365
+ };
2366
+ const now = nowSeconds();
2367
+ const ordered = [...found.entries()].toSorted(([a], [b]) => byCodePoint(a, b));
2368
+ const decideAll = () => ordered.map(([id, entry]) => {
2369
+ const subject = freezeDeep({
2370
+ principal: {
2371
+ id,
2372
+ roles: [],
2373
+ memberships: entry.memberships,
2374
+ ...tenant === void 0 ? {} : { tenant }
2375
+ },
2376
+ context: {}
2377
+ });
2378
+ return evaluate(policy, subject, permission, row, {
2379
+ source: "simulate",
2380
+ trusted: true,
2381
+ now
2382
+ }, env);
2383
+ });
2384
+ let decisions = decideAll();
2385
+ if (pendingRelations(input.cache).length > 0) {
2386
+ await settle$1(input.cache);
2387
+ decisions = decideAll();
2388
+ }
2389
+ const holders = [];
2390
+ for (const [index, [id, entry]] of ordered.entries()) {
2391
+ const decision = decisions[index];
2392
+ if (decision === void 0 || decision.outcome === "denied") {
2393
+ if (decision?.outcome === "denied" && decision.denials.some((denial) => denial.reason === "relation-unavailable" || denial.reason === "relation-depth")) complete = false;
2394
+ continue;
2395
+ }
2396
+ holders.push({
2397
+ principal: { id },
2398
+ via: entry.via
2399
+ });
2400
+ }
2401
+ return freezeDeep({
2402
+ permission: permission.key,
2403
+ holders,
2404
+ complete
2405
+ });
2406
+ }
2407
+ //#endregion
2408
+ //#region src/core/instance.ts
2409
+ /** Each round reads one more layer: link hops, then the chain, then nested groups. */
2410
+ const LOAD_ROUNDS = 48;
2411
+ /** A grant on a relation with a `period` is decided on the server, where the clock is. */
2412
+ function periodBound(policy, grant) {
2413
+ const relations = policy.resources.get(grant.permission.resource)?.relations;
2414
+ return flattenGrantee(grant.to).some((item) => {
2415
+ if (item.kind !== "relation") return false;
2416
+ const spec = relations?.[item.relation];
2417
+ return isPrincipalRelation(spec) && spec.period !== void 0;
2418
+ });
2419
+ }
2420
+ function includePrefixes(include) {
2421
+ if (include === void 0) return;
2422
+ return include.map((item) => {
2423
+ if ("key" in item && typeof item.key === "string") return item.key;
2424
+ const first = listPermissions(item)[0];
2425
+ if (first === void 0) return "";
2426
+ const parts = first.key.split(".");
2427
+ parts.pop();
2428
+ return parts.join(".");
2429
+ });
2430
+ }
2431
+ /**
2432
+ * Role names held in `tenant` on live memberships, global roles included, in
2433
+ * rank order. With `scope`, only the roles of that scope's memberships (and
2434
+ * instance `id`).
2435
+ */
2436
+ function heldRoleNames(policy, subject, tenant, only, now) {
2437
+ if (subject.principal === null) return [];
2438
+ const scopes = scopeList(policy.scopes);
2439
+ const scope = only?.scope === void 0 ? void 0 : resolveScope(scopes, only.scope);
2440
+ if (only?.scope !== void 0 && scope === void 0) return [];
2441
+ const names = new Set(scope === void 0 ? subject.principal.roles ?? [] : []);
2442
+ for (const membership of subject.principal.memberships ?? []) {
2443
+ if (isMembershipExpired(membership, now) || membership.keep !== void 0) continue;
2444
+ if (!(scope === void 0 ? tenantOf(membership, scopes) === tenant : membership.scope === scope && (only?.id === void 0 || sameId(membership.id, only.id)))) continue;
2445
+ for (const role of membership.roles) names.add(role);
2446
+ }
2447
+ return rankRoles(policy, [...names]);
2448
+ }
2449
+ function roleLeaf(policy, name) {
2450
+ const binding = policy.rolesByName.get(name);
2451
+ return findRole(policy.vocabulary?.roles, name) ?? synthesiseRole(name, compact({
2452
+ on: typeof binding?.on === "string" ? binding.on : void 0,
2453
+ assignable: binding?.assignable,
2454
+ meta: binding?.meta
2455
+ }));
2456
+ }
2457
+ /**
2458
+ * The grant with its grantee's row condition. A graph relation needs the
2459
+ * `RelationSource`, which snapshots and `where()` do not carry, so the grant
2460
+ * becomes server-only (`portable: false`) there.
2461
+ */
2462
+ function graphAware(grant, where) {
2463
+ const combined = combineWhere(grant.where, where);
2464
+ const graph = hasConditionOp(combined, "related");
2465
+ const inherits = flattenGrantee(grant.to).some((item) => item.kind === "inherit");
2466
+ return freezeDeep(compact({
2467
+ ...grant,
2468
+ where: combined,
2469
+ portable: graph ? false : grant.portable,
2470
+ graph: graph && grant.portable && !inherits ? true : void 0
2471
+ }));
2472
+ }
2473
+ /**
2474
+ * `where()` keeps a grant that is server-only because it reads the graph:
2475
+ * its `related` nodes compile to subqueries given relation mappings.
2476
+ */
2477
+ function whereGrant(grant) {
2478
+ return grant.graph === true ? freezeDeep({
2479
+ ...grant,
2480
+ portable: true
2481
+ }) : grant;
2482
+ }
2483
+ /**
2484
+ * Every grant the subject may reach, once per membership that holds all of
2485
+ * its scoped roles, so a client can check that membership's tenant, team or
2486
+ * resource. A scoped role held only globally reaches nothing.
2487
+ */
2488
+ function collectSnapshotGrants(policy, subject, customRoles, now = nowSeconds(), customGrants = customGrantsFor(policy, customRoles), mode = "held") {
2489
+ const skip = (grant, match) => mode === "held" ? !match.matched : match.matched || match.reason !== "not-entitled" || grant.effect !== "allow";
2490
+ const scopes = scopeList(policy.scopes);
2491
+ const declared = declaredRoleNames(policy);
2492
+ const global = expandRoleNames(subject.principal?.roles ?? [], declared, customRoles, subject.principal?.tenant);
2493
+ const held = (subject.principal?.memberships ?? []).map((membership) => ({
2494
+ membership,
2495
+ roles: new Set(expandRoleNames(membership.roles, declared, customRoles, tenantOf(membership, scopes)).roles)
2496
+ }));
2497
+ const holds = (entry, item) => entry.roles.has(item.role) && (typeof item.scope === "string" ? entry.membership.scope === item.scope : entry.membership.on !== void 0);
2498
+ const requirementOf = (grant, resource) => grant.requires === void 0 || grant.effect !== "allow" ? void 0 : requirementCondition(policy, subject, grant.requires, resource, now, customRoles, customGrants);
2499
+ const out = [];
2500
+ for (const grant of grantList(policy)) {
2501
+ if (mode === "held" && !coversRequirements(policy.permissions, grant.requires, subject.delegation)) continue;
2502
+ const resource = getResource(policy.permissions, grant.permission.resource);
2503
+ const match = matchGrantee(grant.to, subject, now, resource, scopes, policy.resources);
2504
+ if (skip(grant, match)) continue;
2505
+ const roleItems = flattenGrantee(grant.to).filter((item) => item.kind === "role");
2506
+ if (roleItems.length > 0 && subject.principal === null) continue;
2507
+ if (!roleItems.every((item) => item.scope !== "global" || global.roles.includes(item.role))) continue;
2508
+ const merged = graphAware(grant, combineWhere(match.where, requirementOf(grant, resource)));
2509
+ const scoped = roleItems.filter((item) => item.scope !== "global");
2510
+ if (scoped.length === 0) {
2511
+ out.push({ grant: merged });
2512
+ continue;
2513
+ }
2514
+ for (const entry of held) if (keepsPermission(entry.membership, grant.permission.key) && scoped.every((item) => item.kind === "role" && holds(entry, item))) out.push({
2515
+ grant: merged,
2516
+ membership: entry.membership
2517
+ });
2518
+ }
2519
+ for (const { grant, role } of customGrants) {
2520
+ const globalHeld = holdsGlobalCustomRole(subject.principal?.roles, role);
2521
+ const holders = held.filter((entry) => keepsPermission(entry.membership, grant.permission.key) && holdsCustomRole(entry.membership, role, scopes));
2522
+ if (holders.length === 0 && !globalHeld) continue;
2523
+ const resource = getResource(policy.permissions, grant.permission.resource);
2524
+ const match = matchGrantee(grant.to, subject, now, resource, scopes, policy.resources);
2525
+ if (skip(grant, match)) continue;
2526
+ const merged = graphAware(grant, combineWhere(match.where, requirementOf(grant, resource)));
2527
+ if (globalHeld) out.push({ grant: merged });
2528
+ for (const entry of holders) out.push({
2529
+ grant: merged,
2530
+ membership: entry.membership
2531
+ });
2532
+ }
2533
+ const fresh = policy.fresh ?? [];
2534
+ if (mode === "held" && subject.stale === true && fresh.length > 0) return out.filter(({ grant }) => grant.effect === "deny" || !fresh.includes(grant.permission.key));
2535
+ return out;
2536
+ }
2537
+ /**
2538
+ * Declared roles a tenant admin may hand out or compose, before any
2539
+ * intersection: `assignable` roles, plus every role some `assigns` lists.
2540
+ */
2541
+ function assignableCandidates(policy) {
2542
+ const listed = new Set(policy.roles.flatMap((binding) => binding.assigns ?? []));
2543
+ const names = [...listRoles(policy.vocabulary?.roles).filter((leaf) => leaf.assignable || listed.has(leaf.key)).map((leaf) => leaf.key), ...policy.roles.filter((binding) => binding.assignable || listed.has(binding.name)).map((binding) => binding.name)];
2544
+ return rankRoles(policy, [...new Set(names)]).map((name) => roleLeaf(policy, name));
2545
+ }
2546
+ /**
2547
+ * The levels a held allow of a permission covers: its own `level`, every
2548
+ * level when it has no row condition, or the levels whose condition equals
2549
+ * its condition.
2550
+ */
2551
+ function heldLevels(policy, grant, names) {
2552
+ if (grant.level !== void 0) return [grant.level];
2553
+ if (grant.where === void 0) return names;
2554
+ const held = canonicalJson(grant.where);
2555
+ return names.filter((name) => {
2556
+ const condition = levelCondition(policy, grant.permission.resource, name);
2557
+ return condition !== void 0 && canonicalJson(condition) === held;
2558
+ });
2559
+ }
2560
+ /**
2561
+ * What the subject may hand out in `tenant`: declared assignable roles and the
2562
+ * tenant custom-role ceiling, narrowed by `allowed` (`RoleSource.assignable`),
2563
+ * then intersected with the permissions the subject holds there. Holding a
2564
+ * role or a granted permission with `meta.manageRoles` lifts the intersection.
2565
+ */
2566
+ function assignableIn(policy, subject, customRoles, customGrants, tenant, allowed, now = nowSeconds(), global = false) {
2567
+ const principal = subject.principal;
2568
+ if (principal === null) return {
2569
+ roles: [],
2570
+ permissions: [],
2571
+ levels: {},
2572
+ manage: false,
2573
+ inert: []
2574
+ };
2575
+ const scopes = scopeList(policy.scopes);
2576
+ const scoped = tenant === void 0 ? subject : freezeDeep(compact({
2577
+ ...subject,
2578
+ principal: compact({
2579
+ ...principal,
2580
+ tenant: resolveActiveTenant(principal, tenant, scopes, now)
2581
+ })
2582
+ }));
2583
+ const heldGrants = collectSnapshotGrants(policy, scoped, customRoles, now, customGrants).filter((item) => item.grant.effect === "allow" && (item.membership === void 0 || !global && tenantOf(item.membership, scopes) === tenant && !isMembershipExpired(item.membership, now))).map((item) => item.grant);
2584
+ const heldKeys = new Set(heldGrants.map((grant) => grant.permission.key));
2585
+ const heldNames = heldRoleNames(policy, subject, tenant, void 0, now);
2586
+ const quiet = {
2587
+ emit: false,
2588
+ simulated: true,
2589
+ skipAlternatives: true,
2590
+ customRoles,
2591
+ customGrants,
2592
+ listeners: emptyListeners(),
2593
+ sink: void 0,
2594
+ limits: void 0,
2595
+ limitCache: /* @__PURE__ */ new Map(),
2596
+ team: void 0
2597
+ };
2598
+ const manage = heldNames.some((name) => roleMeta(policy, name)?.manageRoles === true) || listPermissions(policy.permissions).some((leaf) => leaf.meta.manageRoles === true && evaluate(policy, scoped, leaf, void 0, {
2599
+ source: "simulate",
2600
+ trusted: true,
2601
+ now
2602
+ }, quiet).outcome === "granted");
2603
+ const narrowed = allowed === void 0 ? void 0 : new Set(allowed);
2604
+ const candidates = assignableCandidates(policy).filter((leaf) => narrowed === void 0 || narrowed.has(leaf.key));
2605
+ const held = new Set(heldNames);
2606
+ const listed = usesAssigns(policy) ? new Set(heldNames.flatMap((name) => policy.rolesByName.get(name)?.assigns ?? [])) : void 0;
2607
+ const roles = manage ? candidates : candidates.filter((leaf) => {
2608
+ if (listed !== void 0) return listed.has(leaf.key);
2609
+ if (held.has(leaf.key)) return true;
2610
+ const keys = [...roleAllowKeys(policy, leaf.key)];
2611
+ return keys.length > 0 && keys.every((key) => heldKeys.has(key));
2612
+ });
2613
+ const root = global ? "global" : rootScope(scopes);
2614
+ const ceiling = new Set((root === void 0 ? [] : ceilingGrants(policy, root, allowed)).map((grant) => grant.permission.key));
2615
+ const permissions = listPermissions(policy.permissions).filter((leaf) => ceiling.has(leaf.key) && (manage || heldKeys.has(leaf.key)));
2616
+ const offeredLevels = (key, names) => {
2617
+ if (manage) return names;
2618
+ const reached = new Set(heldGrants.filter((grant) => grant.permission.key === key).flatMap((grant) => heldLevels(policy, grant, names)));
2619
+ return names.filter((name) => reached.has(name));
2620
+ };
2621
+ const levels = {};
2622
+ for (const leaf of permissions) {
2623
+ const names = leaf.kind === "instance" ? levelNames(policy, leaf.resource) : [];
2624
+ if (names.length > 0) levels[leaf.key] = offeredLevels(leaf.key, names);
2625
+ }
2626
+ const ceilingKeys = /* @__PURE__ */ new Map();
2627
+ const mayHandOut = (scope, grant) => {
2628
+ const key = grant.permission.key;
2629
+ let keys = ceilingKeys.get(scope);
2630
+ if (keys === void 0) {
2631
+ keys = new Set(ceilingGrants(policy, scope, allowed).map((item) => item.permission.key));
2632
+ ceilingKeys.set(scope, keys);
2633
+ }
2634
+ if (!keys.has(key) || !(manage || heldKeys.has(key))) return false;
2635
+ const names = grant.permission.kind === "instance" ? levelNames(policy, grant.permission.resource) : [];
2636
+ if (names.length === 0) return true;
2637
+ const offered = offeredLevels(key, names);
2638
+ return heldLevels(policy, grant, names).every((name) => offered.includes(name));
2639
+ };
2640
+ const custom = global || tenant === void 0 ? {
2641
+ roles: [],
2642
+ inert: []
2643
+ } : assignableCustomRoles(policy, customRoles, tenant, manage ? void 0 : roles, mayHandOut);
2644
+ return {
2645
+ roles: [...roles, ...custom.roles],
2646
+ permissions,
2647
+ levels,
2648
+ manage,
2649
+ inert: custom.inert
2650
+ };
2651
+ }
2652
+ /**
2653
+ * The tenant's custom roles the subject may hand out: held at a scope it may
2654
+ * assign declared roles at (any scope with `meta.manageRoles`), allowing at
2655
+ * least one permission after the ceiling, and only permissions and levels it
2656
+ * may hand out at that scope. A role that allows nothing is `inert`.
2657
+ */
2658
+ function assignableCustomRoles(policy, customRoles, tenant, declared, mayHandOut) {
2659
+ const scopes = scopeList(policy.scopes);
2660
+ const root = rootScope(scopes);
2661
+ const assignsAt = declared === void 0 ? void 0 : new Set(declared.map((leaf) => leaf.on === void 0 ? root : resolveScope(scopes, leaf.on)));
2662
+ const out = /* @__PURE__ */ new Map();
2663
+ const inert = /* @__PURE__ */ new Set();
2664
+ for (const role of tenantCustomRoles(policy, customRoles)) {
2665
+ if (role.tenant !== tenant || out.has(role.name)) continue;
2666
+ const at = customRoleScope(role, scopes);
2667
+ if (at === void 0 || assignsAt !== void 0 && !assignsAt.has(at)) continue;
2668
+ const { grants } = resolveCustomRole(policy, role);
2669
+ if (!grants.some((grant) => grant.effect === "allow")) {
2670
+ inert.add(role.name);
2671
+ continue;
2672
+ }
2673
+ if (grants.every((grant) => grant.effect === "deny" || mayHandOut(at, grant))) out.set(role.name, synthesiseRole(role.name, {
2674
+ on: at,
2675
+ assignable: true
2676
+ }));
2677
+ }
2678
+ return {
2679
+ roles: [...out.values()].toSorted((a, b) => a.key.localeCompare(b.key)),
2680
+ inert: [...inert].filter((name) => !out.has(name)).toSorted()
2681
+ };
2682
+ }
2683
+ /** The one path from a resolved subject to a `Snapshot`; pure apart from the default clock. */
2684
+ function snapshotOf(policy, subject, options) {
2685
+ const now = options.now ?? nowSeconds();
2686
+ const customGrants = options.customGrants ?? customGrantsFor(policy, options.customRoles);
2687
+ const roles = heldRoleNames(policy, subject, subject.principal?.tenant, void 0, now);
2688
+ const audiences = audiencesOf(policy, roles);
2689
+ return buildSnapshot(compact({
2690
+ subject,
2691
+ roles,
2692
+ audiences: audiences.length === 0 ? void 0 : audiences,
2693
+ notEntitled: collectSnapshotGrants(policy, subject, options.customRoles, now, customGrants, "not-entitled"),
2694
+ grants: collectSnapshotGrants(policy, subject, options.customRoles, now, customGrants).map((item) => periodBound(policy, item.grant) ? Object.assign({}, item, { grant: freezeDeep({
2695
+ ...item.grant,
2696
+ portable: false
2697
+ }) }) : item),
2698
+ include: includePrefixes(options.include),
2699
+ tenants: options.tenants,
2700
+ simulated: options.simulated,
2701
+ now: Math.floor(now),
2702
+ vocabulary: policy.vocabulary,
2703
+ scopes: snapshotScopes(policy),
2704
+ idOf: (name) => getResource(policy.permissions, name)?.id,
2705
+ delegated: delegatedPermissions(policy.delegations, subject, new Set(roles), now),
2706
+ assignable: (tenant) => {
2707
+ const found = assignableIn(policy, subject, options.customRoles, customGrants, tenant, options.assignable?.get(tenant), now);
2708
+ return compact({
2709
+ tenant,
2710
+ roles: found.roles.map((leaf) => leaf.key),
2711
+ permissions: found.permissions,
2712
+ levels: Object.keys(found.levels).length === 0 ? void 0 : found.levels
2713
+ });
2714
+ }
2715
+ }));
2716
+ }
2717
+ /** The policy's scopes as snapshots and `permdock cloud push` carry them, with the resources each partitions. */
2718
+ function snapshotScopes(policy) {
2719
+ if (policy.scopes.length === 0) return;
2720
+ const resources = [...policy.resources.values()];
2721
+ return policy.scopes.map((scope) => {
2722
+ const nodes = resources.filter((node) => partitionsOf(node, policy.scopes).includes(scope.name));
2723
+ const partitioned = nodes.map((node) => node.name);
2724
+ const fields = Object.fromEntries(nodes.flatMap((node) => {
2725
+ const field = scopeField(node, scope.name, policy.scopes);
2726
+ return field === void 0 || field === scope.key ? [] : [[node.name, field]];
2727
+ }));
2728
+ return compact({
2729
+ name: scope.name,
2730
+ key: scope.key ?? "",
2731
+ within: scope.within,
2732
+ resources: partitioned.length === 0 ? void 0 : partitioned,
2733
+ fields: Object.keys(fields).length === 0 ? void 0 : fields
2734
+ });
2735
+ });
2736
+ }
2737
+ function buildInstance(policy, subject, envBase, team) {
2738
+ const listeners = emptyListeners();
2739
+ const queuedAuth = [...envBase.queuedAuth];
2740
+ const queuedErrors = [...envBase.queuedErrors ?? []];
2741
+ const customGrants = customGrantsFor(policy, envBase.customRoles);
2742
+ const relationCache = envBase.relationCache ?? /* @__PURE__ */ new Map();
2743
+ const relations = relationReader(envBase.relations, relationCache, policy.resources);
2744
+ const assignableAt = (tenant) => assignableIn(policy, subject, envBase.customRoles, customGrants, tenant, tenant === void 0 ? void 0 : envBase.assignable?.get(tenant));
2745
+ const envFor = (emit, skipAlternatives = false) => ({
2746
+ emit,
2747
+ simulated: envBase.simulated,
2748
+ skipAlternatives,
2749
+ customRoles: envBase.customRoles,
2750
+ customGrants,
2751
+ listeners,
2752
+ sink: envBase.sink,
2753
+ limits: envBase.limits,
2754
+ limitCache: envBase.limitCache,
2755
+ team,
2756
+ relations,
2757
+ ...envBase.approvalPolicies === void 0 ? {} : { approvalPolicies: envBase.approvalPolicies }
2758
+ });
2759
+ /** The one `simulate` event for a batch: the worst decision, with the counts. */
2760
+ const simulateEvent = (evaluated) => {
2761
+ const counts = {
2762
+ granted: 0,
2763
+ denied: 0,
2764
+ approvalRequired: 0
2765
+ };
2766
+ for (const [, , decision] of evaluated) if (decision.outcome === "granted") counts.granted += 1;
2767
+ else if (decision.outcome === "approval-required") counts.approvalRequired += 1;
2768
+ else counts.denied += 1;
2769
+ const worst = evaluated.find(([, , decision]) => decision.outcome === "denied") ?? evaluated.find(([, , decision]) => decision.outcome === "approval-required") ?? evaluated[0];
2770
+ if (worst === void 0) return;
2771
+ const [permission, data, decision] = worst;
2772
+ finish(policy, subject, permission, data, decision, {
2773
+ source: "simulate",
2774
+ trusted: true
2775
+ }, {
2776
+ ...envFor(false),
2777
+ emit: true
2778
+ }, true, void 0, counts);
2779
+ };
2780
+ const decideImpl = (permission, data, options) => evaluate(policy, subject, permission, data, options ?? {}, envFor(options?.source !== "simulate", options?.source === "can"));
2781
+ const explainImpl = (permission, data, options) => {
2782
+ return decideImpl(permission, data, {
2783
+ ...options,
2784
+ source: options?.source ?? "explain",
2785
+ explain: true
2786
+ });
2787
+ };
2788
+ const canImpl = (permission, data, options) => {
2789
+ try {
2790
+ return decideImpl(permission, data, {
2791
+ ...options,
2792
+ source: options?.source ?? "can"
2793
+ }).outcome === "granted";
2794
+ } catch {
2795
+ return false;
2796
+ }
2797
+ };
2798
+ const assertImpl = (permission, data, options) => {
2799
+ const decision = decideImpl(permission, data, {
2800
+ ...options,
2801
+ source: options?.source ?? "assert"
2802
+ });
2803
+ if (decision.outcome === "granted") return decision;
2804
+ const onDenied = options?.onDenied ?? policy.onDenied;
2805
+ if (onDenied !== void 0) onDenied(decision);
2806
+ const resource = getResource(policy.permissions, permission.resource);
2807
+ const resourceId = data !== null && typeof data === "object" ? data[resource?.id ?? "id"] : void 0;
2808
+ const resourceRef = compact({
2809
+ type: permission.resource,
2810
+ id: resourceId === void 0 ? void 0 : String(resourceId)
2811
+ });
2812
+ if (decision.outcome === "approval-required") throw new PermDockApprovalRequiredError({
2813
+ decision,
2814
+ permission: permission.key,
2815
+ scope: permission.scope,
2816
+ resource: resourceRef,
2817
+ message: approvalMessage(permission.key, decision.reason, decision.token)
2818
+ });
2819
+ if (decision.denials.some((denial) => denial.reason === "validation")) {
2820
+ const detail = decision.denials[0]?.detail;
2821
+ if (detail instanceof PermDockValidationError) throw detail;
2822
+ }
2823
+ throw new PermDockDeniedError({
2824
+ decision,
2825
+ permission: permission.key,
2826
+ scope: permission.scope,
2827
+ resource: resourceRef,
2828
+ subject,
2829
+ message: deniedMessage(permission.key, subject.principal?.id, decision.denials, decision.alternatives.map((leaf) => leaf.key)),
2830
+ ...data === void 0 || resource === void 0 ? {} : { disclosure: resource.disclosure }
2831
+ });
2832
+ };
2833
+ const instance = {
2834
+ can: canImpl,
2835
+ decide: decideImpl,
2836
+ assert: assertImpl,
2837
+ explain: explainImpl,
2838
+ permissions: policy.permissions,
2839
+ roles: policy.vocabulary?.roles ?? {},
2840
+ plans: policy.vocabulary?.plans ?? {},
2841
+ filter(permission, rows, options) {
2842
+ const allowed = [];
2843
+ let granted = 0;
2844
+ let denied = 0;
2845
+ let approvalRequired = 0;
2846
+ const quiet = {
2847
+ ...envFor(false, true),
2848
+ outcomeOnly: true
2849
+ };
2850
+ const trusted = options?.trusted ?? true;
2851
+ const decideOptions = {
2852
+ ...options,
2853
+ source: "filter",
2854
+ trusted
2855
+ };
2856
+ for (const row of rows) {
2857
+ const decision = evaluate(policy, subject, permission, row, decideOptions, quiet);
2858
+ if (decision.outcome === "granted") {
2859
+ allowed.push(row);
2860
+ granted += 1;
2861
+ } else if (decision.outcome === "approval-required") approvalRequired += 1;
2862
+ else denied += 1;
2863
+ }
2864
+ const summary = granted > 0 ? freezeDeep({
2865
+ outcome: "granted",
2866
+ subject,
2867
+ matched: {
2868
+ role: "*",
2869
+ permission: permission.key
2870
+ },
2871
+ token: "pd1.filter"
2872
+ }) : freezeDeep({
2873
+ outcome: "denied",
2874
+ denials: [{
2875
+ role: null,
2876
+ reason: "no-grant"
2877
+ }],
2878
+ alternatives: []
2879
+ });
2880
+ finish(policy, subject, permission, rows[0], summary, decideOptions, {
2881
+ ...quiet,
2882
+ emit: true
2883
+ }, trusted, void 0, {
2884
+ granted,
2885
+ denied,
2886
+ approvalRequired
2887
+ });
2888
+ return allowed;
2889
+ },
2890
+ pick(permission, row, options) {
2891
+ if (row === null || typeof row !== "object") return {};
2892
+ if (canImpl(permission, row, options) !== true) return {};
2893
+ return pickVisible(row, (field) => {
2894
+ const next = compact({
2895
+ ...options,
2896
+ field
2897
+ });
2898
+ return canImpl(permission, row, next) === true;
2899
+ });
2900
+ },
2901
+ where(permission) {
2902
+ const grants = collectSnapshotGrants(policy, subject, envBase.customRoles, nowSeconds(), customGrants).filter((item) => item.grant.permission.key === permission.key).map((item) => snapshotGrant(whereGrant(item.grant), item.membership));
2903
+ return whereFromGrants(grants, compact({
2904
+ resource: permission.resource,
2905
+ resources: policy.resources,
2906
+ graph: envBase.relations !== void 0,
2907
+ scopes: scopeList(policy.scopes),
2908
+ partitioned: (name, key) => relatesTo(getResource(policy.permissions, permission.resource), key, name, scopeList(policy.scopes)),
2909
+ fieldOf: (name) => scopeField(getResource(policy.permissions, permission.resource), name, scopeList(policy.scopes)),
2910
+ tenant: subject.principal?.tenant,
2911
+ team,
2912
+ now: nowSeconds(),
2913
+ subject
2914
+ }));
2915
+ },
2916
+ actions(resource, data, options) {
2917
+ const fromTree = listPermissions(resource);
2918
+ return (fromTree.length > 0 ? fromTree : "resource" in resource && typeof resource.resource === "string" ? listPermissions(policy.permissions).filter((item) => item.resource === resource.resource) : []).filter((item) => canImpl(item, data, options) === true);
2919
+ },
2920
+ async loadRelations(permission, rows) {
2921
+ if (envBase.relations === void 0) return;
2922
+ const quiet = {
2923
+ ...envFor(false),
2924
+ simulated: true,
2925
+ skipAlternatives: true
2926
+ };
2927
+ for (let round = 0; round < LOAD_ROUNDS; round += 1) {
2928
+ for (const row of rows) evaluate(policy, subject, permission, row, {
2929
+ source: "simulate",
2930
+ trusted: true
2931
+ }, quiet);
2932
+ const pending = pendingRelations(relationCache);
2933
+ if (pending.length === 0) return;
2934
+ await Promise.all(pending);
2935
+ }
2936
+ },
2937
+ whoCan(permission, row) {
2938
+ return whoCan({
2939
+ policy,
2940
+ permission,
2941
+ row,
2942
+ memberships: envBase.memberships,
2943
+ reader: relations,
2944
+ cache: relationCache,
2945
+ customGrants,
2946
+ team
2947
+ });
2948
+ },
2949
+ simulate: ((input, options) => {
2950
+ const evaluated = [];
2951
+ const quietly = (permission, data) => {
2952
+ const decision = evaluate(policy, subject, permission, data, compact({
2953
+ source: "simulate",
2954
+ trusted: true,
2955
+ now: options?.now
2956
+ }), envFor(false));
2957
+ evaluated.push([
2958
+ permission,
2959
+ data,
2960
+ decision
2961
+ ]);
2962
+ return decision;
2963
+ };
2964
+ if (isReadonlyArray(input)) {
2965
+ const decisions = input.map(([permission, data]) => quietly(permission, data));
2966
+ simulateEvent(evaluated);
2967
+ return decisions;
2968
+ }
2969
+ if (isArazzoSimulateInput(input)) {
2970
+ const plan = simulateArazzo(input, input.permissions ?? policy.permissions, quietly);
2971
+ simulateEvent(evaluated);
2972
+ return plan;
2973
+ }
2974
+ const preview = input;
2975
+ const previewRoles = preview.roles?.map((item) => typeof item === "string" ? item : item.key);
2976
+ const kinds = subject.principal === null ? void 0 : applyRoleKinds(policy, previewRoles ?? subject.principal.roles, preview.memberships === void 0 ? subject.principal.memberships ?? [] : normalizeMemberships(preview.memberships, scopeList(policy.scopes)));
2977
+ const previewPrincipal = subject.principal === null || kinds === void 0 ? null : freezeDeep(compact({
2978
+ ...subject.principal,
2979
+ roles: kinds.roles,
2980
+ memberships: preview.memberships === void 0 && subject.principal.memberships === void 0 ? void 0 : kinds.memberships,
2981
+ tenant: preview.tenant ?? subject.principal.tenant
2982
+ }));
2983
+ return buildInstance(policy, freezeDeep({
2984
+ ...subject,
2985
+ principal: previewPrincipal
2986
+ }), {
2987
+ ...envBase,
2988
+ simulated: true,
2989
+ relationCache
2990
+ }, team);
2991
+ }),
2992
+ snapshot: ((options) => {
2993
+ const snapshot = snapshotOf(policy, subject, compact({
2994
+ customRoles: envBase.customRoles,
2995
+ customGrants,
2996
+ assignable: envBase.assignable,
2997
+ include: options?.include,
2998
+ tenants: options?.tenants,
2999
+ simulated: envBase.simulated
3000
+ }));
3001
+ if (options?.signer !== void 0) return signSnapshot(snapshot, options.signer, options.audience);
3002
+ return snapshot;
3003
+ }),
3004
+ on(event, handler) {
3005
+ const set = listeners[event];
3006
+ set.add(handler);
3007
+ if (event === "auth") for (const queued of queuedAuth) try {
3008
+ handler(queued);
3009
+ } catch (error) {
3010
+ emitSafe(listeners.error, error, listeners);
3011
+ }
3012
+ if (event === "error") for (const queued of queuedErrors) try {
3013
+ handler(queued);
3014
+ } catch {}
3015
+ return () => {
3016
+ set.delete(handler);
3017
+ };
3018
+ },
3019
+ tenant(id) {
3020
+ if (subject.principal === null) return buildInstance(policy, subject, {
3021
+ ...envBase,
3022
+ relationCache
3023
+ }, team);
3024
+ return buildInstance(policy, freezeDeep(compact({
3025
+ ...subject,
3026
+ principal: compact({
3027
+ ...subject.principal,
3028
+ tenant: resolveActiveTenant(subject.principal, id, scopeList(policy.scopes))
3029
+ })
3030
+ })), {
3031
+ ...envBase,
3032
+ relationCache
3033
+ }, team);
3034
+ },
3035
+ team(id) {
3036
+ return buildInstance(policy, subject, {
3037
+ ...envBase,
3038
+ relationCache
3039
+ }, id);
3040
+ },
3041
+ memberships() {
3042
+ return subject.principal?.memberships ?? [];
3043
+ },
3044
+ tenants() {
3045
+ return tenantsOf(subject.principal, scopeList(policy.scopes));
3046
+ },
3047
+ heldRoles(options) {
3048
+ return heldRoleNames(policy, subject, options?.tenant ?? subject.principal?.tenant, options?.scope === void 0 ? void 0 : compact({
3049
+ scope: options.scope,
3050
+ id: options.id
3051
+ })).map((name) => roleLeaf(policy, name));
3052
+ },
3053
+ audiences() {
3054
+ return audiencesOf(policy, heldRoleNames(policy, subject, subject.principal?.tenant));
3055
+ },
3056
+ assignableRoles(options) {
3057
+ return assignableAt(options?.tenant ?? subject.principal?.tenant).roles;
3058
+ },
3059
+ assignablePermissions(options) {
3060
+ if (options?.scope === "global") return assignableIn(policy, subject, envBase.customRoles, customGrants, void 0, void 0, nowSeconds(), true).permissions;
3061
+ const tenant = options?.tenant ?? subject.principal?.tenant;
3062
+ return tenant === void 0 ? [] : assignableAt(tenant).permissions;
3063
+ },
3064
+ assignableLevels(permission, options) {
3065
+ const of = (found) => (Object.hasOwn(found.levels, permission.key) ? found.levels[permission.key] : void 0) ?? [];
3066
+ if (options?.scope === "global") return of(assignableIn(policy, subject, envBase.customRoles, customGrants, void 0, void 0, nowSeconds(), true));
3067
+ const tenant = options?.tenant ?? subject.principal?.tenant;
3068
+ return tenant === void 0 ? [] : of(assignableAt(tenant));
3069
+ },
3070
+ decideRoleChange(change, options) {
3071
+ return decideRoleChange(policy, subject.principal, scopeList(policy.scopes), change, envBase.customRoles, (tenant) => {
3072
+ const found = assignableAt(tenant);
3073
+ return {
3074
+ assignable: new Set(found.roles.map((leaf) => leaf.key)),
3075
+ manage: found.manage,
3076
+ inert: new Set(found.inert)
3077
+ };
3078
+ }, nowSeconds(), options);
3079
+ },
3080
+ activate(input) {
3081
+ return activate(policy, subject, input, nowSeconds());
3082
+ },
3083
+ derive(options) {
3084
+ const scopes = scopeList(policy.scopes);
3085
+ const tenants = tenantsOf(subject.principal, scopes);
3086
+ const auth = [];
3087
+ const named = options.customRoles === void 0 ? void 0 : roleSourceFor(options.customRoles, subject, auth);
3088
+ const roleSource = options.customRoles === void 0 ? envBase.roleSource : named;
3089
+ const roles = options.customRoles === void 0 ? envBase.customRoles : customRolesFor(named, tenants, auth, subject.principal === null ? void 0 : subject.principal.roles ?? [], (tenant) => heldRoleNamesIn(subject.principal, scopes, tenant));
3090
+ const names = options.customRoles === void 0 ? envBase.assignable : assignableNamesFor(named, tenants, auth);
3091
+ const approvals = options.approvalPolicies === void 0 ? envBase.approvalPolicies : approvalPoliciesFor(policy, options.approvalPolicies, tenants, auth);
3092
+ const relationSource = options.relations ?? envBase.relations;
3093
+ const build = (loadedRoles, loadedNames, loadedApprovals) => buildInstance(policy, subject, compact({
3094
+ ...envBase,
3095
+ customRoles: loadedRoles,
3096
+ roleSource,
3097
+ assignable: loadedNames,
3098
+ approvalPolicies: loadedApprovals,
3099
+ relations: relationSource,
3100
+ relationCache: options.relations === void 0 ? relationCache : void 0,
3101
+ queuedAuth: auth,
3102
+ queuedErrors: []
3103
+ }), team);
3104
+ if (isThenable(roles) || isThenable(names) || isThenable(approvals)) return Promise.all([
3105
+ roles,
3106
+ names,
3107
+ approvals
3108
+ ]).then(([loadedRoles, loadedNames, loadedApprovals]) => build(loadedRoles, loadedNames, loadedApprovals));
3109
+ return build(roles, names, approvals);
3110
+ },
3111
+ subject
3112
+ };
3113
+ return Object.freeze(instance);
3114
+ }
3115
+ //#endregion
3116
+ //#region src/core/oauth-scopes.ts
3117
+ /**
3118
+ * `delegation` with every coarse OAuth scope the policy declares in
3119
+ * `oauthScopes` followed by the scopes of the permissions it covers, so the
3120
+ * delegation checks downstream match them. The token's scopes stay first and
3121
+ * unchanged; an undeclared scope expands to nothing.
3122
+ */
3123
+ function expandOAuthScopes(policy, delegation) {
3124
+ const declared = policy.oauthScopes;
3125
+ const scopes = delegation?.scopes;
3126
+ if (declared === void 0 || delegation === void 0 || scopes === void 0) return delegation;
3127
+ const out = new Set(scopes);
3128
+ for (const entry of declared) if (scopes.includes(entry.scope)) for (const scope of entry.scopes) out.add(scope);
3129
+ return out.size === scopes.length ? delegation : {
3130
+ ...delegation,
3131
+ scopes: [...out]
3132
+ };
3133
+ }
3134
+ /** The coarse scopes the policy declares that cover `permission`, in declaration order. */
3135
+ function coarseScopesFor(policy, permission) {
3136
+ return (policy.oauthScopes ?? []).filter((entry) => entry.permissions.includes(permission.key)).map((entry) => entry.scope);
3137
+ }
3138
+ /** Every token scope that reaches `permission`: its own, any it was renamed from, and the coarse scopes covering it. */
3139
+ function scopesReaching(policy, permission) {
3140
+ return [
3141
+ permission.scope,
3142
+ ...formerScopes(permission),
3143
+ ...coarseScopesFor(policy, permission)
3144
+ ];
3145
+ }
3146
+ /**
3147
+ * The scope an `insufficient_scope` challenge names for `permission`: the
3148
+ * first coarse scope that covers it, which the authorization server issues,
3149
+ * else the permission's own scope.
3150
+ */
3151
+ function challengeScope(policy, permission) {
3152
+ return coarseScopesFor(policy, permission)[0] ?? permission.scope;
3153
+ }
3154
+ //#endregion
3155
+ //#region src/core/resolve-subject.ts
3156
+ /**
3157
+ * The tenant a user API key holds its owner to (`Credential.tenant`): only
3158
+ * the memberships inside it count, and no global role.
3159
+ */
3160
+ function heldTenantOf(principal) {
3161
+ const credential = principal["credential"];
3162
+ if (credential === null || typeof credential !== "object" || !Object.hasOwn(credential, "tenant") || !Object.hasOwn(credential, "kind")) return;
3163
+ const record = credential;
3164
+ return record.kind === "user" && typeof record.tenant === "string" && record.tenant !== "" ? record.tenant : void 0;
3165
+ }
3166
+ function outsideHeld(held, options) {
3167
+ return held !== void 0 && options.tenant !== void 0 && options.tenant !== held;
3168
+ }
3169
+ function assemblePrincipal(policy, user, options, auth) {
3170
+ let principal;
3171
+ let context = {};
3172
+ let actor = options.actor;
3173
+ let delegation = options.delegation;
3174
+ let session = options.session;
3175
+ let expiresAt = options.expiresAt;
3176
+ let liveSession;
3177
+ try {
3178
+ if (user === null || user === void 0) principal = policy.subject(user);
3179
+ else if (isSubject(user)) {
3180
+ principal = user.principal;
3181
+ context = user.context;
3182
+ actor = user.actor ?? actor;
3183
+ delegation = user.delegation ?? delegation;
3184
+ session = user.session ?? session;
3185
+ expiresAt = user.expiresAt ?? expiresAt;
3186
+ liveSession = user.liveSession === true ? true : void 0;
3187
+ } else if (isPrincipal(user)) principal = user;
3188
+ else principal = policy.subject(user);
3189
+ } catch {
3190
+ principal = null;
3191
+ }
3192
+ const contextResult = resolveContext(policy, user, context, auth);
3193
+ let memberships = principal?.memberships ?? [];
3194
+ let live = false;
3195
+ const source = options.memberships === void 0 ? void 0 : asMembershipSource(options.memberships);
3196
+ const fromClaims = source?.claimsFirst === true && principal?.memberships !== void 0 && principal.membershipsTruncated !== true;
3197
+ const read = (from, of) => {
3198
+ try {
3199
+ return from.membershipsFor(compact({
3200
+ id: of.id,
3201
+ kind: of.kind
3202
+ }), compact({ tenant: options.tenant }));
3203
+ } catch {
3204
+ auth.push({
3205
+ reason: "source-threw",
3206
+ source: "memberships"
3207
+ });
3208
+ return [];
3209
+ }
3210
+ };
3211
+ let stale;
3212
+ if (principal !== null && source !== void 0 && !fromClaims) {
3213
+ live = true;
3214
+ memberships = read(source, principal);
3215
+ } else if (principal?.memberships !== void 0 && fromClaims && source.onStale === "reread" && source.version !== void 0) {
3216
+ const reread = rereadStale(source, principal, principal.memberships, () => read(source, principal), auth);
3217
+ memberships = reread.memberships;
3218
+ stale = reread.stale;
3219
+ }
3220
+ return compact({
3221
+ principal,
3222
+ context: contextResult,
3223
+ actor,
3224
+ delegation: expandOAuthScopes(policy, delegation),
3225
+ session,
3226
+ expiresAt,
3227
+ memberships,
3228
+ live,
3229
+ stale,
3230
+ liveSession: principal === null ? void 0 : liveSession
3231
+ });
3232
+ }
3233
+ function versionQuery(principal) {
3234
+ return compact({
3235
+ id: principal.id,
3236
+ roles: principal.roles,
3237
+ memberships: principal.memberships
3238
+ });
3239
+ }
3240
+ function rereadStale(source, principal, claims, read, auth) {
3241
+ const claimed = principal.authzVersion;
3242
+ const judge = (current) => typeof claimed === "number" && current !== void 0 && claimed >= current ? "fresh" : "reread";
3243
+ const unknown = () => {
3244
+ auth.push({
3245
+ reason: "source-threw",
3246
+ source: "memberships"
3247
+ });
3248
+ return "unknown";
3249
+ };
3250
+ let freshness;
3251
+ try {
3252
+ const current = source.version?.(versionQuery(principal));
3253
+ freshness = isThenable(current) ? Promise.resolve(current).then(judge, unknown) : judge(current);
3254
+ } catch {
3255
+ freshness = unknown();
3256
+ }
3257
+ if (isThenable(freshness)) return {
3258
+ memberships: freshness.then((found) => found === "reread" ? read() : claims),
3259
+ stale: freshness.then((found) => found === "unknown")
3260
+ };
3261
+ return {
3262
+ memberships: freshness === "reread" ? read() : claims,
3263
+ stale: freshness === "unknown"
3264
+ };
3265
+ }
3266
+ function finishSubject(policy, assembled, context, input, options, extra) {
3267
+ if (assembled.principal === null) return freezeCopy(compact({
3268
+ ...anonymousSubject(context),
3269
+ actor: assembled.actor,
3270
+ delegation: assembled.delegation,
3271
+ session: assembled.session,
3272
+ expiresAt: assembled.expiresAt
3273
+ }));
3274
+ const scopes = scopeList(policy.scopes);
3275
+ const held = heldTenantOf(assembled.principal);
3276
+ const kinds = applyRoleKinds(policy, assembled.principal.roles, normalizeMemberships(input, scopes));
3277
+ const roles = held === void 0 ? kinds.roles : [];
3278
+ const memberships = held === void 0 ? kinds.memberships : outsideHeld(held, options) ? [] : kinds.memberships.filter((membership) => tenantOf(membership, scopes) === held);
3279
+ const plans = [.../* @__PURE__ */ new Set([...assembled.principal.plans ?? [], ...extra.plans])];
3280
+ const withMemberships = freezeCopy(compact({
3281
+ ...assembled.principal,
3282
+ roles,
3283
+ memberships,
3284
+ plans: plans.length === 0 ? assembled.principal.plans : plans,
3285
+ tenant: activeTenantOf(policy, assembled, memberships, options)
3286
+ }));
3287
+ return freezeCopy(compact({
3288
+ principal: withMemberships,
3289
+ actor: assembled.actor,
3290
+ delegation: assembled.delegation,
3291
+ context: freezeCopy(context),
3292
+ session: assembled.session,
3293
+ expiresAt: assembled.expiresAt,
3294
+ stale: extra.stale ? true : void 0,
3295
+ liveSession: assembled.liveSession
3296
+ }));
3297
+ }
3298
+ function activeTenantOf(policy, assembled, memberships, options) {
3299
+ if (assembled.principal === null) return;
3300
+ const held = heldTenantOf(assembled.principal);
3301
+ if (held !== void 0) return outsideHeld(held, options) ? void 0 : held;
3302
+ return resolveActiveTenant({
3303
+ ...assembled.principal,
3304
+ memberships
3305
+ }, options.tenant ?? assembled.principal.tenant, scopeList(policy.scopes));
3306
+ }
3307
+ function settle(value, fallback, onError) {
3308
+ if (isThenable(value)) return Promise.resolve(value).catch(() => {
3309
+ onError();
3310
+ return fallback;
3311
+ });
3312
+ return value;
3313
+ }
3314
+ /**
3315
+ * Whether the token's memberships are behind the source for `fresh`
3316
+ * permissions. Live memberships are never stale; token memberships are stale
3317
+ * unless a source reports a version the token's `authzVersion` has reached.
3318
+ */
3319
+ function staleness(policy, assembled, options, auth) {
3320
+ const principal = assembled.principal;
3321
+ if ((policy.fresh ?? []).length === 0 || principal === null || assembled.live) return false;
3322
+ if (assembled.stale !== void 0) return assembled.stale;
3323
+ const source = options.memberships === void 0 ? void 0 : asMembershipSource(options.memberships);
3324
+ const claimed = principal.authzVersion;
3325
+ if (source?.version === void 0 || typeof claimed !== "number") return true;
3326
+ const compare = (current) => current === void 0 || claimed < current;
3327
+ try {
3328
+ const current = source.version(versionQuery(principal));
3329
+ return isThenable(current) ? settle(Promise.resolve(current).then(compare), true, () => {
3330
+ auth.push({
3331
+ reason: "source-threw",
3332
+ source: "memberships"
3333
+ });
3334
+ }) : compare(current);
3335
+ } catch {
3336
+ auth.push({
3337
+ reason: "source-threw",
3338
+ source: "memberships"
3339
+ });
3340
+ return true;
3341
+ }
3342
+ }
3343
+ function cleanNames(list) {
3344
+ return Array.isArray(list) ? list.filter((item) => typeof item === "string" && item !== "") : [];
3345
+ }
3346
+ function entitlementsOf(assembled, tenant, options, auth) {
3347
+ const source = options.entitlements;
3348
+ if (source === void 0 || assembled.principal === null || outsideHeld(heldTenantOf(assembled.principal), options)) return [];
3349
+ try {
3350
+ const found = source.entitlementsFor({ id: assembled.principal.id }, compact({ tenant }));
3351
+ return isThenable(found) ? settle(Promise.resolve(found).then(cleanNames), [], () => {
3352
+ auth.push({
3353
+ reason: "source-threw",
3354
+ source: "entitlements"
3355
+ });
3356
+ }) : cleanNames(found);
3357
+ } catch {
3358
+ auth.push({
3359
+ reason: "source-threw",
3360
+ source: "entitlements"
3361
+ });
3362
+ return [];
3363
+ }
3364
+ }
3365
+ function resolveContext(policy, user, fallback, auth) {
3366
+ if (policy.context === void 0) return sanitizeContext(fallback);
3367
+ try {
3368
+ const loaded = policy.context(user);
3369
+ if (isThenable(loaded)) return loaded.then((value) => sanitizeContext(value), () => {
3370
+ auth.push({
3371
+ reason: "source-threw",
3372
+ source: "context"
3373
+ });
3374
+ return {};
3375
+ });
3376
+ return sanitizeContext(loaded);
3377
+ } catch {
3378
+ auth.push({
3379
+ reason: "source-threw",
3380
+ source: "context"
3381
+ });
3382
+ return {};
3383
+ }
3384
+ }
3385
+ function resolveSubject(policy, user, options, auth) {
3386
+ const assembled = assemblePrincipal(policy, user, options, auth);
3387
+ const memberships = settle(assembled.memberships, [], () => {
3388
+ auth.push({
3389
+ reason: "source-threw",
3390
+ source: "memberships"
3391
+ });
3392
+ });
3393
+ const stale = staleness(policy, assembled, options, auth);
3394
+ const withPlans = (resolved) => entitlementsOf(assembled, activeTenantOf(policy, assembled, applyRoleKinds(policy, assembled.principal?.roles, normalizeMemberships(resolved, scopeList(policy.scopes))).memberships, options), options, auth);
3395
+ if (isThenable(assembled.context) || isThenable(memberships) || isThenable(stale)) return Promise.all([
3396
+ Promise.resolve(assembled.context),
3397
+ Promise.resolve(memberships),
3398
+ Promise.resolve(stale)
3399
+ ]).then(async ([context, resolved, isStale]) => finishSubject(policy, assembled, context, resolved, options, {
3400
+ stale: isStale,
3401
+ plans: await withPlans(resolved)
3402
+ }));
3403
+ const plans = withPlans(memberships);
3404
+ if (isThenable(plans)) return Promise.resolve(plans).then((resolved) => finishSubject(policy, assembled, assembled.context, memberships, options, {
3405
+ stale,
3406
+ plans: resolved
3407
+ }));
3408
+ return finishSubject(policy, assembled, assembled.context, memberships, options, {
3409
+ stale,
3410
+ plans
3411
+ });
3412
+ }
3413
+ //#endregion
3414
+ //#region src/core/permdock.ts
3415
+ function hostedPolicy(policy, source) {
3416
+ if (source === void 0 || policy.hostable.length === 0) return {
3417
+ policy,
3418
+ errors: []
3419
+ };
3420
+ let document;
3421
+ try {
3422
+ document = source.current();
3423
+ } catch (error) {
3424
+ return {
3425
+ policy,
3426
+ errors: [error]
3427
+ };
3428
+ }
3429
+ const merged = mergeHostedGrants(policy, document);
3430
+ return {
3431
+ policy: merged.policy,
3432
+ errors: merged.dropped
3433
+ };
3434
+ }
3435
+ function instantiate(codePolicy, subject, options, auth) {
3436
+ const { policy, errors } = hostedPolicy(codePolicy, options.policies);
3437
+ const scopes = scopeList(policy.scopes);
3438
+ const tenants = tenantsOf(subject.principal, scopes);
3439
+ const roleSource = roleSourceFor(options.customRoles, subject, auth);
3440
+ const customRoles = customRolesFor(roleSource, tenants, auth, subject.principal === null ? void 0 : subject.principal.roles ?? [], (tenant) => heldRoleNamesIn(subject.principal, scopes, tenant));
3441
+ const assignable = assignableNamesFor(roleSource, tenants, auth);
3442
+ const approvals = approvalPoliciesFor(policy, options.approvalPolicies, tenants, auth);
3443
+ const build = (roles, names, approvalPolicies) => buildInstance(policy, subject, compact({
3444
+ customRoles: roles,
3445
+ sink: options.sink,
3446
+ limits: options.limits,
3447
+ limitCache: /* @__PURE__ */ new Map(),
3448
+ simulated: false,
3449
+ roleSource,
3450
+ assignable: names,
3451
+ queuedAuth: auth,
3452
+ queuedErrors: errors,
3453
+ relations: options.relations,
3454
+ approvalPolicies,
3455
+ memberships: options.memberships === void 0 ? void 0 : asMembershipSource(options.memberships)
3456
+ }));
3457
+ if (isThenable(customRoles) || isThenable(assignable) || isThenable(approvals)) return Promise.all([
3458
+ customRoles,
3459
+ assignable,
3460
+ approvals
3461
+ ]).then(([roles, names, loaded]) => build(roles, names, loaded));
3462
+ return build(customRoles, assignable, approvals);
3463
+ }
3464
+ function createPermDock(policy, user, options = {}) {
3465
+ const auth = [];
3466
+ const subject = resolveSubject(policy, user, options, auth);
3467
+ if (isThenable(subject)) return subject.then((resolved) => instantiate(policy, resolved, options, auth));
3468
+ return instantiate(policy, subject, options, auth);
3469
+ }
3470
+ //#endregion
3471
+ export { countHolders as C, memoryApprovalPolicies as D, approvalPoliciesFor as E, validateApprovalPolicy as O, composeMemberships as S, APPROVAL_POLICY_UNAVAILABLE as T, leveled as _, collectSnapshotGrants as a, validateCustomRole as b, rankRoles as c, breakGlass as d, supportAccess as f, customRoleScope as g, customRoleClaim as h, scopesReaching as i, usesAssigns as l, ceilingGrants as m, resolveSubject as n, snapshotOf as o, andWhere as p, challengeScope as r, snapshotScopes as s, createPermDock as t, declaredRoleNames as u, membershipsClaim as v, isExternallyManaged as w, claimsFirst as x, resolveCustomRole as y };