@xtandard/permissions 0.1.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 (164) hide show
  1. package/README.md +5 -3
  2. package/dist/{better-auth-NO40ZqSM.mjs → better-auth-BEmX8qyz.mjs} +28 -8
  3. package/dist/better-auth-BEmX8qyz.mjs.map +1 -0
  4. package/dist/{better-auth-Bp9YVyQa.d.cts → better-auth-DQET1sXa.d.mts} +24 -5
  5. package/dist/{better-auth-DHyW5-yt.cjs → better-auth-MR7dBtpo.cjs} +28 -8
  6. package/dist/better-auth-MR7dBtpo.cjs.map +1 -0
  7. package/dist/{better-auth-NSXgt6ZU.d.mts → better-auth-vgRYgjYK.d.cts} +24 -5
  8. package/dist/cli.cjs +12 -6
  9. package/dist/cli.cjs.map +1 -1
  10. package/dist/cli.mjs +12 -6
  11. package/dist/cli.mjs.map +1 -1
  12. package/dist/{contract-BMiOmg2f.d.cts → contract-BAisPHBw.d.cts} +30 -2
  13. package/dist/{contract-Yc5AZuvv.mjs → contract-BganM0fx.mjs} +34 -2
  14. package/dist/contract-BganM0fx.mjs.map +1 -0
  15. package/dist/{contract-CPmJVoRx.cjs → contract-Brnu9XXo.cjs} +45 -1
  16. package/dist/contract-Brnu9XXo.cjs.map +1 -0
  17. package/dist/{contract-Dk6d2ylD.d.cts → contract-CXPMGuHk.d.cts} +18 -2
  18. package/dist/{contract-D32H1t0u.d.mts → contract-D6j-yrBL.d.mts} +30 -2
  19. package/dist/{contract-DUzgB-He.d.mts → contract-DhS23Pcp.d.mts} +18 -2
  20. package/dist/{create-fetch-handler-ojjpk1Iw.mjs → create-fetch-handler-B0twltQL.mjs} +43 -6
  21. package/dist/create-fetch-handler-B0twltQL.mjs.map +1 -0
  22. package/dist/{create-fetch-handler-BHDU4chu.d.mts → create-fetch-handler-B711wb64.d.mts} +4 -4
  23. package/dist/{create-fetch-handler-C-WyaRCR.cjs → create-fetch-handler-BHT4vSZs.cjs} +43 -6
  24. package/dist/create-fetch-handler-BHT4vSZs.cjs.map +1 -0
  25. package/dist/{create-fetch-handler-BtX64_rS.d.cts → create-fetch-handler-DxhvXuBA.d.cts} +4 -4
  26. package/dist/{elysia-shared-BUTFTeal.cjs → elysia-shared-BFcWzfc9.cjs} +3 -3
  27. package/dist/{elysia-shared-BUTFTeal.cjs.map → elysia-shared-BFcWzfc9.cjs.map} +1 -1
  28. package/dist/{elysia-shared-BM6cPoCU.mjs → elysia-shared-BwUYg0Ln.mjs} +3 -3
  29. package/dist/{elysia-shared-BM6cPoCU.mjs.map → elysia-shared-BwUYg0Ln.mjs.map} +1 -1
  30. package/dist/{elysia-shared-DtKViycb.d.cts → elysia-shared-C2LnDOj3.d.cts} +5 -5
  31. package/dist/{elysia-shared-g8zsb_pU.d.mts → elysia-shared-WuDr0jco.d.mts} +5 -5
  32. package/dist/{engine-bMoz3iW-.cjs → engine--C7zo-4M.cjs} +93 -13
  33. package/dist/engine--C7zo-4M.cjs.map +1 -0
  34. package/dist/{engine-CGGVDCqi.d.cts → engine-BTgwbHeO.d.cts} +49 -9
  35. package/dist/{engine-DpFIcbgh.d.mts → engine-C3xHfi3q.d.mts} +49 -9
  36. package/dist/{engine-Bufv0TbD.mjs → engine-CR75K253.mjs} +93 -13
  37. package/dist/engine-CR75K253.mjs.map +1 -0
  38. package/dist/entry-auth-better-auth.cjs +6 -3
  39. package/dist/entry-auth-better-auth.d.cts +4 -4
  40. package/dist/entry-auth-better-auth.d.mts +4 -4
  41. package/dist/entry-auth-better-auth.mjs +4 -4
  42. package/dist/entry-auth-jwt.cjs +6 -2
  43. package/dist/entry-auth-jwt.cjs.map +1 -1
  44. package/dist/entry-auth-jwt.d.cts +9 -3
  45. package/dist/entry-auth-jwt.d.mts +9 -3
  46. package/dist/entry-auth-jwt.mjs +4 -3
  47. package/dist/entry-auth-jwt.mjs.map +1 -1
  48. package/dist/entry-auth-session.cjs +6 -2
  49. package/dist/entry-auth-session.cjs.map +1 -1
  50. package/dist/entry-auth-session.d.cts +8 -3
  51. package/dist/entry-auth-session.d.mts +8 -3
  52. package/dist/entry-auth-session.mjs +4 -3
  53. package/dist/entry-auth-session.mjs.map +1 -1
  54. package/dist/entry-authorization-permissions.cjs +1 -1
  55. package/dist/entry-authorization-permissions.d.cts +1 -1
  56. package/dist/entry-authorization-permissions.d.mts +1 -1
  57. package/dist/entry-authorization-permissions.mjs +1 -1
  58. package/dist/entry-better-auth-client.d.cts +2 -2
  59. package/dist/entry-better-auth-client.d.mts +2 -2
  60. package/dist/entry-better-auth.cjs +1 -1
  61. package/dist/entry-better-auth.d.cts +2 -2
  62. package/dist/entry-better-auth.d.mts +2 -2
  63. package/dist/entry-better-auth.mjs +1 -1
  64. package/dist/entry-bridges-audit.d.cts +1 -1
  65. package/dist/entry-bridges-audit.d.mts +1 -1
  66. package/dist/entry-bridges-webhooks.d.cts +1 -1
  67. package/dist/entry-bridges-webhooks.d.mts +1 -1
  68. package/dist/entry-bun.cjs +2 -2
  69. package/dist/entry-bun.d.cts +4 -4
  70. package/dist/entry-bun.d.mts +4 -4
  71. package/dist/entry-bun.mjs +2 -2
  72. package/dist/entry-elysia.cjs +1 -1
  73. package/dist/entry-elysia.d.cts +4 -4
  74. package/dist/entry-elysia.d.mts +4 -4
  75. package/dist/entry-elysia.mjs +1 -1
  76. package/dist/entry-elysia2.cjs +1 -1
  77. package/dist/entry-elysia2.d.cts +4 -4
  78. package/dist/entry-elysia2.d.mts +4 -4
  79. package/dist/entry-elysia2.mjs +1 -1
  80. package/dist/entry-express.cjs +2 -2
  81. package/dist/entry-express.d.cts +4 -4
  82. package/dist/entry-express.d.mts +4 -4
  83. package/dist/entry-express.mjs +2 -2
  84. package/dist/entry-hono.cjs +2 -2
  85. package/dist/entry-hono.d.cts +4 -4
  86. package/dist/entry-hono.d.mts +4 -4
  87. package/dist/entry-hono.mjs +2 -2
  88. package/dist/entry-hooks-log.d.cts +1 -1
  89. package/dist/entry-hooks-log.d.mts +1 -1
  90. package/dist/entry-next.cjs +2 -2
  91. package/dist/entry-next.d.cts +5 -5
  92. package/dist/entry-next.d.mts +5 -5
  93. package/dist/entry-next.mjs +2 -2
  94. package/dist/entry-react.d.cts +2 -2
  95. package/dist/entry-react.d.mts +2 -2
  96. package/dist/{errors-bL3XQLfE.mjs → errors-CG_OLEEv.mjs} +12 -2
  97. package/dist/errors-CG_OLEEv.mjs.map +1 -0
  98. package/dist/{errors-vVYic8gz.cjs → errors-CjpymzFj.cjs} +17 -1
  99. package/dist/errors-CjpymzFj.cjs.map +1 -0
  100. package/dist/{guard-BOx5cnMP.mjs → guard-Bj8zk23F.mjs} +2 -2
  101. package/dist/{guard-BOx5cnMP.mjs.map → guard-Bj8zk23F.mjs.map} +1 -1
  102. package/dist/{guard-nwdOYe90.cjs → guard-DvaoUgjk.cjs} +2 -2
  103. package/dist/{guard-nwdOYe90.cjs.map → guard-DvaoUgjk.cjs.map} +1 -1
  104. package/dist/{guard-C3o7V14m.d.cts → guard-VEK0W8ug.d.cts} +4 -4
  105. package/dist/{guard-DCbTnqPz.d.mts → guard-k7A71SWC.d.mts} +4 -4
  106. package/dist/index.cjs +9 -6
  107. package/dist/index.d.cts +28 -10
  108. package/dist/index.d.mts +28 -10
  109. package/dist/index.mjs +7 -7
  110. package/dist/{kit-DMVBLBI9.d.mts → kit-51JtMxsn.d.mts} +8 -3
  111. package/dist/{kit-fzXHYb1l.mjs → kit-BM3uosfV.mjs} +23 -8
  112. package/dist/kit-BM3uosfV.mjs.map +1 -0
  113. package/dist/{kit-C7tepDB2.cjs → kit-BrqnCcDw.cjs} +28 -7
  114. package/dist/kit-BrqnCcDw.cjs.map +1 -0
  115. package/dist/{kit-qAROuhOI.d.cts → kit-DLF7DZrp.d.cts} +8 -3
  116. package/dist/{permissions-C9PjftY6.mjs → permissions-CeV6M3v7.mjs} +6 -3
  117. package/dist/permissions-CeV6M3v7.mjs.map +1 -0
  118. package/dist/{permissions-Cxri_P_k.cjs → permissions-DDEkHNvN.cjs} +6 -3
  119. package/dist/permissions-DDEkHNvN.cjs.map +1 -0
  120. package/dist/react-embed.js +1880 -1855
  121. package/dist/relationships-BLYEJ9tc.cjs.map +1 -1
  122. package/dist/relationships-BfLonEMI.mjs.map +1 -1
  123. package/dist/{routes-irNuuZqo.cjs → routes-B2LrYpT0.cjs} +15 -9
  124. package/dist/routes-B2LrYpT0.cjs.map +1 -0
  125. package/dist/{routes-DtRb3EO0.mjs → routes-Cx-kl4PY.mjs} +15 -9
  126. package/dist/routes-Cx-kl4PY.mjs.map +1 -0
  127. package/dist/{server-CJ7AIJpO.d.mts → server-Bn643UOy.d.mts} +4 -4
  128. package/dist/{server-C2F4H6bR.d.cts → server-YdH25OEA.d.cts} +4 -4
  129. package/dist/testing.cjs +1 -1
  130. package/dist/testing.d.cts +2 -2
  131. package/dist/testing.d.mts +2 -2
  132. package/dist/testing.mjs +1 -1
  133. package/dist/types-elysia2/auth-provider/contract.d.ts +28 -0
  134. package/dist/types-elysia2/auth-provider/kit.d.ts +5 -0
  135. package/dist/types-elysia2/engine.d.ts +49 -8
  136. package/dist/types-elysia2/errors.d.ts +8 -0
  137. package/dist/types-elysia2/schema.d.ts +16 -0
  138. package/dist/types-elysia2/server/routes.d.ts +16 -5
  139. package/dist/types-react/engine.d.ts +49 -8
  140. package/dist/types-react/errors.d.ts +8 -0
  141. package/dist/types-react/schema.d.ts +16 -0
  142. package/dist/types-react/ui/App.d.ts +6 -1
  143. package/dist/types-react/ui/components/perm-bits.d.ts +5 -1
  144. package/dist/types-react/ui/types.d.ts +11 -2
  145. package/dist/ui/assets/index-DdvxpphI.js +104 -0
  146. package/dist/ui/index.html +1 -1
  147. package/package.json +1 -1
  148. package/dist/better-auth-DHyW5-yt.cjs.map +0 -1
  149. package/dist/better-auth-NO40ZqSM.mjs.map +0 -1
  150. package/dist/contract-CPmJVoRx.cjs.map +0 -1
  151. package/dist/contract-Yc5AZuvv.mjs.map +0 -1
  152. package/dist/create-fetch-handler-C-WyaRCR.cjs.map +0 -1
  153. package/dist/create-fetch-handler-ojjpk1Iw.mjs.map +0 -1
  154. package/dist/engine-Bufv0TbD.mjs.map +0 -1
  155. package/dist/engine-bMoz3iW-.cjs.map +0 -1
  156. package/dist/errors-bL3XQLfE.mjs.map +0 -1
  157. package/dist/errors-vVYic8gz.cjs.map +0 -1
  158. package/dist/kit-C7tepDB2.cjs.map +0 -1
  159. package/dist/kit-fzXHYb1l.mjs.map +0 -1
  160. package/dist/permissions-C9PjftY6.mjs.map +0 -1
  161. package/dist/permissions-Cxri_P_k.cjs.map +0 -1
  162. package/dist/routes-DtRb3EO0.mjs.map +0 -1
  163. package/dist/routes-irNuuZqo.cjs.map +0 -1
  164. package/dist/ui/assets/index-uXGOtyuj.js +0 -104
@@ -48,7 +48,17 @@ var ReadonlyError = class extends Error {
48
48
  this.name = "ReadonlyError";
49
49
  }
50
50
  };
51
+ /**
52
+ * `setRole()` on an engine whose `roleSource` is `"external"`: roles are managed by the auth
53
+ * provider, so a stored role would be ignored (ADR 0014). HTTP 409 `ROLES_EXTERNAL`.
54
+ */
55
+ var ExternalRolesError = class extends Error {
56
+ constructor(message = "Roles are managed by the auth provider (roleSource: \"external\"); change the role there.") {
57
+ super(message);
58
+ this.name = "ExternalRolesError";
59
+ }
60
+ };
51
61
  //#endregion
52
- export { UnknownPermissionError as a, ReadonlyError as i, NoSubjectError as n, UnknownRoleError as o, NotFoundError as r, ValidationError$1 as s, ForbiddenError as t };
62
+ export { ReadonlyError as a, ValidationError$1 as c, NotFoundError as i, ForbiddenError as n, UnknownPermissionError as o, NoSubjectError as r, UnknownRoleError as s, ExternalRolesError as t };
53
63
 
54
- //# sourceMappingURL=errors-bL3XQLfE.mjs.map
64
+ //# sourceMappingURL=errors-CG_OLEEv.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-CG_OLEEv.mjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Typed errors. Every class sets a distinct `name`: the kit maps errors to HTTP\n * responses **by name** (`isNamed`), so a copy from another bundle still maps.\n *\n * | name | when |\n * | ------------------------ | --------------------------------------------------------------- |\n * | `NoSubjectError` | a write (or a check) without a subject id — never `\"\"` |\n * | `UnknownPermissionError` | a permission not in the catalog's `assignable` list |\n * | `UnknownRoleError` | a role not in the catalog's `roles` |\n * | `ForbiddenError` | the caller may not manage permissions |\n * | `NotFoundError` | a referenced record does not exist |\n * | `ReadonlyError` | a mutation on a `readonly` engine |\n * | `ExternalRolesError` | `setRole()` with `roleSource: \"external\"` (the provider owns roles) |\n * | `ValidationError` | malformed input (the kit's, with `errors` / `issues`) |\n * | `AsyncRuleError` | a rule returned a Promise (the lib's; the check denied) |\n *\n * @module\n */\n\nexport { ValidationError, type ValidationIssue } from \"@xtandard/kit/util\";\nexport { AsyncRuleError } from \"./policy.ts\";\n\n/** A write (or a check) needs a subject id and got none (no session, or an empty id). */\nexport class NoSubjectError extends Error {\n constructor(message = \"A subject id is required (no session, or an empty id).\") {\n super(message);\n this.name = \"NoSubjectError\";\n }\n}\n\n/** The permission is not in the catalog's `assignable` list. */\nexport class UnknownPermissionError extends Error {\n /** The rejected permission. */\n readonly permission: string;\n constructor(permission: unknown) {\n super(\n `Unknown permission ${JSON.stringify(String(permission))}: not in the catalog's assignable list.`,\n );\n this.name = \"UnknownPermissionError\";\n this.permission = String(permission);\n }\n}\n\n/** The role is not one of the catalog's `roles` (or may not be assigned). */\nexport class UnknownRoleError extends Error {\n /** The rejected role. */\n readonly role: string;\n constructor(role: unknown, message?: string) {\n super(message ?? `Unknown role ${JSON.stringify(String(role))}: not in the catalog's roles.`);\n this.name = \"UnknownRoleError\";\n this.role = String(role);\n }\n}\n\n/** The caller may not perform the operation (e.g. grant without a manager role). */\nexport class ForbiddenError extends Error {\n constructor(message = \"Forbidden\") {\n super(message);\n this.name = \"ForbiddenError\";\n }\n}\n\n/** A referenced record does not exist. */\nexport class NotFoundError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"NotFoundError\";\n }\n}\n\n/** Thrown by mutating operations when the engine is readonly. */\nexport class ReadonlyError extends Error {\n constructor(operation: string) {\n super(`Cannot ${operation}: @xtandard/permissions is in readonly mode.`);\n this.name = \"ReadonlyError\";\n }\n}\n\n/**\n * `setRole()` on an engine whose `roleSource` is `\"external\"`: roles are managed by the auth\n * provider, so a stored role would be ignored (ADR 0014). HTTP 409 `ROLES_EXTERNAL`.\n */\nexport class ExternalRolesError extends Error {\n constructor(\n message = 'Roles are managed by the auth provider (roleSource: \"external\"); change the role there.',\n ) {\n super(message);\n this.name = \"ExternalRolesError\";\n }\n}\n"],"mappings":";;;AAuBA,IAAa,iBAAb,cAAoC,MAAM;CACxC,YAAY,UAAU,0DAA0D;EAC9E,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,yBAAb,cAA4C,MAAM;;CAEhD;CACA,YAAY,YAAqB;EAC/B,MACE,sBAAsB,KAAK,UAAU,OAAO,UAAU,CAAC,EAAE,wCAC3D;EACA,KAAK,OAAO;EACZ,KAAK,aAAa,OAAO,UAAU;CACrC;AACF;;AAGA,IAAa,mBAAb,cAAsC,MAAM;;CAE1C;CACA,YAAY,MAAe,SAAkB;EAC3C,MAAM,WAAW,gBAAgB,KAAK,UAAU,OAAO,IAAI,CAAC,EAAE,8BAA8B;EAC5F,KAAK,OAAO;EACZ,KAAK,OAAO,OAAO,IAAI;CACzB;AACF;;AAGA,IAAa,iBAAb,cAAoC,MAAM;CACxC,YAAY,UAAU,aAAa;EACjC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,gBAAb,cAAmC,MAAM;CACvC,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,gBAAb,cAAmC,MAAM;CACvC,YAAY,WAAmB;EAC7B,MAAM,UAAU,UAAU,6CAA6C;EACvE,KAAK,OAAO;CACd;AACF;;;;;AAMA,IAAa,qBAAb,cAAwC,MAAM;CAC5C,YACE,UAAU,6FACV;EACA,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF"}
@@ -48,7 +48,23 @@ var ReadonlyError = class extends Error {
48
48
  this.name = "ReadonlyError";
49
49
  }
50
50
  };
51
+ /**
52
+ * `setRole()` on an engine whose `roleSource` is `"external"`: roles are managed by the auth
53
+ * provider, so a stored role would be ignored (ADR 0014). HTTP 409 `ROLES_EXTERNAL`.
54
+ */
55
+ var ExternalRolesError = class extends Error {
56
+ constructor(message = "Roles are managed by the auth provider (roleSource: \"external\"); change the role there.") {
57
+ super(message);
58
+ this.name = "ExternalRolesError";
59
+ }
60
+ };
51
61
  //#endregion
62
+ Object.defineProperty(exports, "ExternalRolesError", {
63
+ enumerable: true,
64
+ get: function() {
65
+ return ExternalRolesError;
66
+ }
67
+ });
52
68
  Object.defineProperty(exports, "ForbiddenError", {
53
69
  enumerable: true,
54
70
  get: function() {
@@ -86,4 +102,4 @@ Object.defineProperty(exports, "UnknownRoleError", {
86
102
  }
87
103
  });
88
104
 
89
- //# sourceMappingURL=errors-vVYic8gz.cjs.map
105
+ //# sourceMappingURL=errors-CjpymzFj.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-CjpymzFj.cjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Typed errors. Every class sets a distinct `name`: the kit maps errors to HTTP\n * responses **by name** (`isNamed`), so a copy from another bundle still maps.\n *\n * | name | when |\n * | ------------------------ | --------------------------------------------------------------- |\n * | `NoSubjectError` | a write (or a check) without a subject id — never `\"\"` |\n * | `UnknownPermissionError` | a permission not in the catalog's `assignable` list |\n * | `UnknownRoleError` | a role not in the catalog's `roles` |\n * | `ForbiddenError` | the caller may not manage permissions |\n * | `NotFoundError` | a referenced record does not exist |\n * | `ReadonlyError` | a mutation on a `readonly` engine |\n * | `ExternalRolesError` | `setRole()` with `roleSource: \"external\"` (the provider owns roles) |\n * | `ValidationError` | malformed input (the kit's, with `errors` / `issues`) |\n * | `AsyncRuleError` | a rule returned a Promise (the lib's; the check denied) |\n *\n * @module\n */\n\nexport { ValidationError, type ValidationIssue } from \"@xtandard/kit/util\";\nexport { AsyncRuleError } from \"./policy.ts\";\n\n/** A write (or a check) needs a subject id and got none (no session, or an empty id). */\nexport class NoSubjectError extends Error {\n constructor(message = \"A subject id is required (no session, or an empty id).\") {\n super(message);\n this.name = \"NoSubjectError\";\n }\n}\n\n/** The permission is not in the catalog's `assignable` list. */\nexport class UnknownPermissionError extends Error {\n /** The rejected permission. */\n readonly permission: string;\n constructor(permission: unknown) {\n super(\n `Unknown permission ${JSON.stringify(String(permission))}: not in the catalog's assignable list.`,\n );\n this.name = \"UnknownPermissionError\";\n this.permission = String(permission);\n }\n}\n\n/** The role is not one of the catalog's `roles` (or may not be assigned). */\nexport class UnknownRoleError extends Error {\n /** The rejected role. */\n readonly role: string;\n constructor(role: unknown, message?: string) {\n super(message ?? `Unknown role ${JSON.stringify(String(role))}: not in the catalog's roles.`);\n this.name = \"UnknownRoleError\";\n this.role = String(role);\n }\n}\n\n/** The caller may not perform the operation (e.g. grant without a manager role). */\nexport class ForbiddenError extends Error {\n constructor(message = \"Forbidden\") {\n super(message);\n this.name = \"ForbiddenError\";\n }\n}\n\n/** A referenced record does not exist. */\nexport class NotFoundError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"NotFoundError\";\n }\n}\n\n/** Thrown by mutating operations when the engine is readonly. */\nexport class ReadonlyError extends Error {\n constructor(operation: string) {\n super(`Cannot ${operation}: @xtandard/permissions is in readonly mode.`);\n this.name = \"ReadonlyError\";\n }\n}\n\n/**\n * `setRole()` on an engine whose `roleSource` is `\"external\"`: roles are managed by the auth\n * provider, so a stored role would be ignored (ADR 0014). HTTP 409 `ROLES_EXTERNAL`.\n */\nexport class ExternalRolesError extends Error {\n constructor(\n message = 'Roles are managed by the auth provider (roleSource: \"external\"); change the role there.',\n ) {\n super(message);\n this.name = \"ExternalRolesError\";\n }\n}\n"],"mappings":";;;AAuBA,IAAa,iBAAb,cAAoC,MAAM;CACxC,YAAY,UAAU,0DAA0D;EAC9E,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,yBAAb,cAA4C,MAAM;;CAEhD;CACA,YAAY,YAAqB;EAC/B,MACE,sBAAsB,KAAK,UAAU,OAAO,UAAU,CAAC,EAAE,wCAC3D;EACA,KAAK,OAAO;EACZ,KAAK,aAAa,OAAO,UAAU;CACrC;AACF;;AAGA,IAAa,mBAAb,cAAsC,MAAM;;CAE1C;CACA,YAAY,MAAe,SAAkB;EAC3C,MAAM,WAAW,gBAAgB,KAAK,UAAU,OAAO,IAAI,CAAC,EAAE,8BAA8B;EAC5F,KAAK,OAAO;EACZ,KAAK,OAAO,OAAO,IAAI;CACzB;AACF;;AAGA,IAAa,iBAAb,cAAoC,MAAM;CACxC,YAAY,UAAU,aAAa;EACjC,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,gBAAb,cAAmC,MAAM;CACvC,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,gBAAb,cAAmC,MAAM;CACvC,YAAY,WAAmB;EAC7B,MAAM,UAAU,UAAU,6CAA6C;EACvE,KAAK,OAAO;CACd;AACF;;;;;AAMA,IAAa,qBAAb,cAAwC,MAAM;CAC5C,YACE,UAAU,6FACV;EACA,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF"}
@@ -1,4 +1,4 @@
1
- import { c as serializeCheck } from "./routes-DtRb3EO0.mjs";
1
+ import { c as serializeCheck } from "./routes-Cx-kl4PY.mjs";
2
2
  //#region src/adapters/guard.ts
3
3
  /** An engine as the guard core sees it. */
4
4
  const guardEngine = (engine) => engine;
@@ -138,4 +138,4 @@ function guardFetchRelation(engine, relation, object, options, handler) {
138
138
  //#endregion
139
139
  export { guardFetchRelation as a, relationOutcomeResponse as c, guardFetch as i, evaluateRelationGuard as n, outcomeResponse as o, guardEngine as r, relationGuardEngine as s, evaluateGuard as t };
140
140
 
141
- //# sourceMappingURL=guard-BOx5cnMP.mjs.map
141
+ //# sourceMappingURL=guard-Bj8zk23F.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"guard-BOx5cnMP.mjs","names":[],"sources":["../src/adapters/guard.ts"],"sourcesContent":["/**\n * Framework-agnostic core of the `requirePermission` guards (ADR 0008): resolve the subject from\n * the framework's request context (your own resolver, or a `PermissionsAuthProvider`), decide the\n * path with the engine, and either hand the decision on or answer the denial as JSON:\n *\n * - allowed → the {@link CheckResult} is attached to the context;\n * - denied with no session → `401` `code: \"NO_SUBJECT\"` (a guest whose role allows passes);\n * - denied → `403` `code: \"FORBIDDEN\"` with the decision.\n *\n * Every adapter wraps this; it imports no framework.\n *\n * @module\n */\n\nimport type { PermissionsAuthProvider } from \"../auth-provider/contract.ts\";\nimport type { AnyPermissions, Permissions, SubjectInput } from \"../engine.ts\";\nimport type { RulesPaths } from \"../policy.ts\";\nimport type { CheckResult } from \"../schema.ts\";\nimport { serializeCheck } from \"../server/routes.ts\";\n\n/** What a guard needs from the engine (any `createPermissions` engine). */\nexport interface GuardEngine {\n ability(\n subject: SubjectInput,\n ...facts: [] | [{ ctx?: unknown }]\n ): Promise<{ checkAsync(path: string, data?: unknown): Promise<CheckResult> }>;\n}\n\n/** The typed permix paths of an engine's catalog (any string for an untyped engine). */\n// oxlint-disable-next-line typescript/no-explicit-any -- variance, see AnyPermissions.\nexport type PathOf<E> = E extends Permissions<infer D, any, any, any> ? RulesPaths<D> : string;\n\n/** An engine as the guard core sees it. */\nexport const guardEngine = (engine: AnyPermissions): GuardEngine => engine as GuardEngine;\n\n/** Options shared by every framework's `requirePermission` guard. */\nexport interface RequirePermissionOptions<Ctx> {\n /**\n * The subject of this request: an id, an identity (`{ id, role }`), or `null` / `undefined` for\n * no session (the guest role). Required unless `provider` is given.\n */\n subject?: (ctx: Ctx) => SubjectInput | Promise<SubjectInput>;\n /** Resolve the subject with an auth provider instead (better-auth, session, JWT…). */\n provider?: PermissionsAuthProvider;\n /** The data the rule at the path reads (e.g. the loaded resource). */\n data?: (ctx: Ctx) => unknown;\n /** The rules' `ctx`, for catalogs whose rules read app facts. */\n ctx?: (ctx: Ctx) => unknown;\n /** Build the denial response yourself (e.g. a redirect or an HTML page). */\n onDenied?: (denial: GuardDenial, ctx: Ctx) => Response | Promise<Response>;\n}\n\n/** A denied guard: the status, the JSON body and the decision. */\nexport interface GuardDenial {\n status: 401 | 403;\n body: Record<string, unknown>;\n result: CheckResult;\n}\n\n/** Outcome of {@link evaluateGuard}. */\nexport type GuardOutcome =\n | { allowed: true; result: CheckResult }\n | ({ allowed: false } & GuardDenial);\n\n/** The JSON status and body of a denied decision. */\nexport function denialOf(result: CheckResult): GuardDenial {\n const status = result.subject === null ? 401 : 403;\n return {\n status,\n result,\n body: {\n error:\n status === 401\n ? `Unauthorized: sign in to ${result.path}`\n : `Forbidden: ${result.path} (${result.reason})`,\n code: status === 401 ? \"NO_SUBJECT\" : \"FORBIDDEN\",\n ...serializeCheck(result),\n },\n };\n}\n\n/** A web `Response` for a denial. */\nexport const denialResponse = (denial: GuardDenial): Response =>\n Response.json(denial.body, { status: denial.status });\n\n/**\n * Run the guard for one request context. Never throws for a denial; errors from the resolvers,\n * the provider or the engine (an empty subject id: `NoSubjectError`) propagate.\n *\n * @param requestOf How to get a web `Request` from the context (for `provider`).\n */\nexport async function evaluateGuard<Ctx>(\n engine: GuardEngine,\n path: string,\n options: RequirePermissionOptions<Ctx>,\n ctx: Ctx,\n requestOf?: (ctx: Ctx) => Request,\n): Promise<GuardOutcome> {\n let subject: SubjectInput;\n if (options.subject) subject = await options.subject(ctx);\n else if (options.provider && requestOf)\n subject = await options.provider.getSubject(requestOf(ctx));\n else throw new TypeError(\"requirePermission: pass `subject` (or `provider`)\");\n const data = options.data?.(ctx);\n const facts: [] | [{ ctx: unknown }] = options.ctx ? [{ ctx: await options.ctx(ctx) }] : [];\n const ability = await engine.ability(subject, ...facts);\n const result = await ability.checkAsync(path, data);\n if (result.allowed) return { allowed: true, result };\n return { allowed: false, ...denialOf(result) };\n}\n\n/** The response for a denied outcome (honoring `onDenied`). */\nexport async function outcomeResponse<Ctx>(\n outcome: Extract<GuardOutcome, { allowed: false }>,\n options: RequirePermissionOptions<Ctx>,\n ctx: Ctx,\n): Promise<Response> {\n const { status, body, result } = outcome;\n if (options.onDenied) return options.onDenied({ status, body, result }, ctx);\n return Response.json(body, { status });\n}\n\n/**\n * Wrap a web-standard handler `(request, decision, ...extra) => Response` with a guard: the shape\n * `Bun.serve` routes and Next.js route handlers share.\n */\nexport function guardFetch<Extra extends unknown[] = []>(\n engine: GuardEngine,\n path: string,\n options: RequirePermissionOptions<Request>,\n handler: (\n request: Request,\n decision: CheckResult,\n ...extra: Extra\n ) => Response | Promise<Response>,\n): (request: Request, ...extra: Extra) => Promise<Response> {\n return async (request, ...extra) => {\n const outcome = await evaluateGuard(engine, path, options, request, (r) => r);\n if (!outcome.allowed) return outcomeResponse(outcome, options, request);\n return handler(request, outcome.result, ...extra);\n };\n}\n\n// ─── Relationship guards (ReBAC, ADR 0013) ──────────────────────────────────────────────────\n\n/** What a relationship guard needs from the engine. */\nexport interface RelationGuardEngine {\n checkRelation(query: {\n subject: string;\n relation: string;\n object: string;\n }): Promise<{ allowed: boolean; path: string[] }>;\n}\n\n/** An engine as the relationship guard sees it. */\nexport const relationGuardEngine = (engine: AnyPermissions): RelationGuardEngine =>\n engine as unknown as RelationGuardEngine;\n\n/** The decision of a relationship guard. */\nexport interface RelationDecision {\n allowed: boolean;\n /** The ReBAC subject (`user:ana`), `null` without a session. */\n subject: string | null;\n relation: string;\n object: string;\n /** When allowed, the chain of relations that granted it. */\n path: string[];\n}\n\n/** The object a relationship guard checks: fixed, or from the request (`doc:${params.id}`). */\nexport type RelationObjectInput<Ctx> = string | ((ctx: Ctx) => string | Promise<string>);\n\n/** Options shared by every framework's `requireRelation` guard. */\nexport interface RequireRelationOptions<Ctx> {\n /** The subject of this request (an id or identity; `null` / `undefined`: no session → 401). */\n subject?: (ctx: Ctx) => SubjectInput | Promise<SubjectInput>;\n /** Resolve the subject with an auth provider instead. */\n provider?: PermissionsAuthProvider;\n /** The subject id → its ReBAC reference. Default `user:{id}`. */\n subjectRef?: (id: string) => string;\n /** Build the denial response yourself. */\n onDenied?: (denial: RelationDenial, ctx: Ctx) => Response | Promise<Response>;\n}\n\n/** A denied relationship guard. */\nexport interface RelationDenial {\n status: 401 | 403;\n body: Record<string, unknown>;\n result: RelationDecision;\n}\n\n/** Outcome of {@link evaluateRelationGuard}. */\nexport type RelationGuardOutcome =\n | { allowed: true; result: RelationDecision }\n | ({ allowed: false } & RelationDenial);\n\n/** The JSON status and body of a denied relationship decision. */\nexport function relationDenialOf(result: RelationDecision): RelationDenial {\n const status = result.subject === null ? 401 : 403;\n const what = `${result.object}#${result.relation}`;\n return {\n status,\n result,\n body: {\n error: status === 401 ? `Unauthorized: sign in to reach ${what}` : `Forbidden: not ${what}`,\n code: status === 401 ? \"NO_SUBJECT\" : \"FORBIDDEN\",\n ...result,\n },\n };\n}\n\n/**\n * Run a relationship guard for one request context: resolve the subject, map it to a ReBAC\n * reference, resolve the object and `checkRelation`. Never throws for a denial.\n */\nexport async function evaluateRelationGuard<Ctx>(\n engine: RelationGuardEngine,\n relation: string,\n object: RelationObjectInput<Ctx>,\n options: RequireRelationOptions<Ctx>,\n ctx: Ctx,\n requestOf?: (ctx: Ctx) => Request,\n): Promise<RelationGuardOutcome> {\n let subject: SubjectInput;\n if (options.subject) subject = await options.subject(ctx);\n else if (options.provider && requestOf)\n subject = await options.provider.getSubject(requestOf(ctx));\n else throw new TypeError(\"requireRelation: pass `subject` (or `provider`)\");\n const target = typeof object === \"function\" ? await object(ctx) : object;\n const id =\n subject === null || subject === undefined\n ? null\n : typeof subject === \"string\"\n ? subject\n : subject.id;\n if (!id) {\n return {\n allowed: false,\n ...relationDenialOf({ allowed: false, subject: null, relation, object: target, path: [] }),\n };\n }\n const ref = options.subjectRef ? options.subjectRef(id) : `user:${id}`;\n const { allowed, path } = await engine.checkRelation({ subject: ref, relation, object: target });\n const result: RelationDecision = { allowed, subject: ref, relation, object: target, path };\n return allowed ? { allowed: true, result } : { allowed: false, ...relationDenialOf(result) };\n}\n\n/** The response for a denied relationship outcome (honoring `onDenied`). */\nexport async function relationOutcomeResponse<Ctx>(\n outcome: Extract<RelationGuardOutcome, { allowed: false }>,\n options: RequireRelationOptions<Ctx>,\n ctx: Ctx,\n): Promise<Response> {\n const { status, body, result } = outcome;\n if (options.onDenied) return options.onDenied({ status, body, result }, ctx);\n return Response.json(body, { status });\n}\n\n/** Wrap a web-standard handler `(request, decision, ...extra)` with a relationship guard. */\nexport function guardFetchRelation<Extra extends unknown[] = []>(\n engine: RelationGuardEngine,\n relation: string,\n object: RelationObjectInput<Request>,\n options: RequireRelationOptions<Request>,\n handler: (\n request: Request,\n decision: RelationDecision,\n ...extra: Extra\n ) => Response | Promise<Response>,\n): (request: Request, ...extra: Extra) => Promise<Response> {\n return async (request, ...extra) => {\n const outcome = await evaluateRelationGuard(\n engine,\n relation,\n object,\n options,\n request,\n (r) => r,\n );\n if (!outcome.allowed) return relationOutcomeResponse(outcome, options, request);\n return handler(request, outcome.result, ...extra);\n };\n}\n"],"mappings":";;;AAiCA,MAAa,eAAe,WAAwC;;AAgCpE,SAAgB,SAAS,QAAkC;CACzD,MAAM,SAAS,OAAO,YAAY,OAAO,MAAM;CAC/C,OAAO;EACL;EACA;EACA,MAAM;GACJ,OACE,WAAW,MACP,4BAA4B,OAAO,SACnC,cAAc,OAAO,KAAK,IAAI,OAAO,OAAO;GAClD,MAAM,WAAW,MAAM,eAAe;GACtC,GAAG,eAAe,MAAM;EAC1B;CACF;AACF;;;;;;;AAYA,eAAsB,cACpB,QACA,MACA,SACA,KACA,WACuB;CACvB,IAAI;CACJ,IAAI,QAAQ,SAAS,UAAU,MAAM,QAAQ,QAAQ,GAAG;MACnD,IAAI,QAAQ,YAAY,WAC3B,UAAU,MAAM,QAAQ,SAAS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O,QAAQ,SAAS,QAAQ,QAAQ,GAAG,KAAK;CAClD;AACF"}
1
+ {"version":3,"file":"guard-Bj8zk23F.mjs","names":[],"sources":["../src/adapters/guard.ts"],"sourcesContent":["/**\n * Framework-agnostic core of the `requirePermission` guards (ADR 0008): resolve the subject from\n * the framework's request context (your own resolver, or a `PermissionsAuthProvider`), decide the\n * path with the engine, and either hand the decision on or answer the denial as JSON:\n *\n * - allowed → the {@link CheckResult} is attached to the context;\n * - denied with no session → `401` `code: \"NO_SUBJECT\"` (a guest whose role allows passes);\n * - denied → `403` `code: \"FORBIDDEN\"` with the decision.\n *\n * Every adapter wraps this; it imports no framework.\n *\n * @module\n */\n\nimport type { PermissionsAuthProvider } from \"../auth-provider/contract.ts\";\nimport type { AnyPermissions, Permissions, SubjectInput } from \"../engine.ts\";\nimport type { RulesPaths } from \"../policy.ts\";\nimport type { CheckResult } from \"../schema.ts\";\nimport { serializeCheck } from \"../server/routes.ts\";\n\n/** What a guard needs from the engine (any `createPermissions` engine). */\nexport interface GuardEngine {\n ability(\n subject: SubjectInput,\n ...facts: [] | [{ ctx?: unknown }]\n ): Promise<{ checkAsync(path: string, data?: unknown): Promise<CheckResult> }>;\n}\n\n/** The typed permix paths of an engine's catalog (any string for an untyped engine). */\n// oxlint-disable-next-line typescript/no-explicit-any -- variance, see AnyPermissions.\nexport type PathOf<E> = E extends Permissions<infer D, any, any, any> ? RulesPaths<D> : string;\n\n/** An engine as the guard core sees it. */\nexport const guardEngine = (engine: AnyPermissions): GuardEngine => engine as GuardEngine;\n\n/** Options shared by every framework's `requirePermission` guard. */\nexport interface RequirePermissionOptions<Ctx> {\n /**\n * The subject of this request: an id, an identity (`{ id, role }`), or `null` / `undefined` for\n * no session (the guest role). Required unless `provider` is given.\n */\n subject?: (ctx: Ctx) => SubjectInput | Promise<SubjectInput>;\n /** Resolve the subject with an auth provider instead (better-auth, session, JWT…). */\n provider?: PermissionsAuthProvider;\n /** The data the rule at the path reads (e.g. the loaded resource). */\n data?: (ctx: Ctx) => unknown;\n /** The rules' `ctx`, for catalogs whose rules read app facts. */\n ctx?: (ctx: Ctx) => unknown;\n /** Build the denial response yourself (e.g. a redirect or an HTML page). */\n onDenied?: (denial: GuardDenial, ctx: Ctx) => Response | Promise<Response>;\n}\n\n/** A denied guard: the status, the JSON body and the decision. */\nexport interface GuardDenial {\n status: 401 | 403;\n body: Record<string, unknown>;\n result: CheckResult;\n}\n\n/** Outcome of {@link evaluateGuard}. */\nexport type GuardOutcome =\n | { allowed: true; result: CheckResult }\n | ({ allowed: false } & GuardDenial);\n\n/** The JSON status and body of a denied decision. */\nexport function denialOf(result: CheckResult): GuardDenial {\n const status = result.subject === null ? 401 : 403;\n return {\n status,\n result,\n body: {\n error:\n status === 401\n ? `Unauthorized: sign in to ${result.path}`\n : `Forbidden: ${result.path} (${result.reason})`,\n code: status === 401 ? \"NO_SUBJECT\" : \"FORBIDDEN\",\n ...serializeCheck(result),\n },\n };\n}\n\n/** A web `Response` for a denial. */\nexport const denialResponse = (denial: GuardDenial): Response =>\n Response.json(denial.body, { status: denial.status });\n\n/**\n * Run the guard for one request context. Never throws for a denial; errors from the resolvers,\n * the provider or the engine (an empty subject id: `NoSubjectError`) propagate.\n *\n * @param requestOf How to get a web `Request` from the context (for `provider`).\n */\nexport async function evaluateGuard<Ctx>(\n engine: GuardEngine,\n path: string,\n options: RequirePermissionOptions<Ctx>,\n ctx: Ctx,\n requestOf?: (ctx: Ctx) => Request,\n): Promise<GuardOutcome> {\n let subject: SubjectInput;\n if (options.subject) subject = await options.subject(ctx);\n else if (options.provider && requestOf)\n subject = await options.provider.getSubject(requestOf(ctx));\n else throw new TypeError(\"requirePermission: pass `subject` (or `provider`)\");\n const data = options.data?.(ctx);\n const facts: [] | [{ ctx: unknown }] = options.ctx ? [{ ctx: await options.ctx(ctx) }] : [];\n const ability = await engine.ability(subject, ...facts);\n const result = await ability.checkAsync(path, data);\n if (result.allowed) return { allowed: true, result };\n return { allowed: false, ...denialOf(result) };\n}\n\n/** The response for a denied outcome (honoring `onDenied`). */\nexport async function outcomeResponse<Ctx>(\n outcome: Extract<GuardOutcome, { allowed: false }>,\n options: RequirePermissionOptions<Ctx>,\n ctx: Ctx,\n): Promise<Response> {\n const { status, body, result } = outcome;\n if (options.onDenied) return options.onDenied({ status, body, result }, ctx);\n return Response.json(body, { status });\n}\n\n/**\n * Wrap a web-standard handler `(request, decision, ...extra) => Response` with a guard: the shape\n * `Bun.serve` routes and Next.js route handlers share.\n */\nexport function guardFetch<Extra extends unknown[] = []>(\n engine: GuardEngine,\n path: string,\n options: RequirePermissionOptions<Request>,\n handler: (\n request: Request,\n decision: CheckResult,\n ...extra: Extra\n ) => Response | Promise<Response>,\n): (request: Request, ...extra: Extra) => Promise<Response> {\n return async (request, ...extra) => {\n const outcome = await evaluateGuard(engine, path, options, request, (r) => r);\n if (!outcome.allowed) return outcomeResponse(outcome, options, request);\n return handler(request, outcome.result, ...extra);\n };\n}\n\n// ─── Relationship guards (ReBAC, ADR 0013) ──────────────────────────────────────────────────\n\n/** What a relationship guard needs from the engine. */\nexport interface RelationGuardEngine {\n checkRelation(query: {\n subject: string;\n relation: string;\n object: string;\n }): Promise<{ allowed: boolean; path: string[] }>;\n}\n\n/** An engine as the relationship guard sees it. */\nexport const relationGuardEngine = (engine: AnyPermissions): RelationGuardEngine =>\n engine as unknown as RelationGuardEngine;\n\n/** The decision of a relationship guard. */\nexport interface RelationDecision {\n allowed: boolean;\n /** The ReBAC subject (`user:ana`), `null` without a session. */\n subject: string | null;\n relation: string;\n object: string;\n /** When allowed, the chain of relations that granted it. */\n path: string[];\n}\n\n/** The object a relationship guard checks: fixed, or from the request (`doc:${params.id}`). */\nexport type RelationObjectInput<Ctx> = string | ((ctx: Ctx) => string | Promise<string>);\n\n/** Options shared by every framework's `requireRelation` guard. */\nexport interface RequireRelationOptions<Ctx> {\n /** The subject of this request (an id or identity; `null` / `undefined`: no session → 401). */\n subject?: (ctx: Ctx) => SubjectInput | Promise<SubjectInput>;\n /** Resolve the subject with an auth provider instead. */\n provider?: PermissionsAuthProvider;\n /** The subject id → its ReBAC reference. Default `user:{id}`. */\n subjectRef?: (id: string) => string;\n /** Build the denial response yourself. */\n onDenied?: (denial: RelationDenial, ctx: Ctx) => Response | Promise<Response>;\n}\n\n/** A denied relationship guard. */\nexport interface RelationDenial {\n status: 401 | 403;\n body: Record<string, unknown>;\n result: RelationDecision;\n}\n\n/** Outcome of {@link evaluateRelationGuard}. */\nexport type RelationGuardOutcome =\n | { allowed: true; result: RelationDecision }\n | ({ allowed: false } & RelationDenial);\n\n/** The JSON status and body of a denied relationship decision. */\nexport function relationDenialOf(result: RelationDecision): RelationDenial {\n const status = result.subject === null ? 401 : 403;\n const what = `${result.object}#${result.relation}`;\n return {\n status,\n result,\n body: {\n error: status === 401 ? `Unauthorized: sign in to reach ${what}` : `Forbidden: not ${what}`,\n code: status === 401 ? \"NO_SUBJECT\" : \"FORBIDDEN\",\n ...result,\n },\n };\n}\n\n/**\n * Run a relationship guard for one request context: resolve the subject, map it to a ReBAC\n * reference, resolve the object and `checkRelation`. Never throws for a denial.\n */\nexport async function evaluateRelationGuard<Ctx>(\n engine: RelationGuardEngine,\n relation: string,\n object: RelationObjectInput<Ctx>,\n options: RequireRelationOptions<Ctx>,\n ctx: Ctx,\n requestOf?: (ctx: Ctx) => Request,\n): Promise<RelationGuardOutcome> {\n let subject: SubjectInput;\n if (options.subject) subject = await options.subject(ctx);\n else if (options.provider && requestOf)\n subject = await options.provider.getSubject(requestOf(ctx));\n else throw new TypeError(\"requireRelation: pass `subject` (or `provider`)\");\n const target = typeof object === \"function\" ? await object(ctx) : object;\n const id =\n subject === null || subject === undefined\n ? null\n : typeof subject === \"string\"\n ? subject\n : subject.id;\n if (!id) {\n return {\n allowed: false,\n ...relationDenialOf({ allowed: false, subject: null, relation, object: target, path: [] }),\n };\n }\n const ref = options.subjectRef ? options.subjectRef(id) : `user:${id}`;\n const { allowed, path } = await engine.checkRelation({ subject: ref, relation, object: target });\n const result: RelationDecision = { allowed, subject: ref, relation, object: target, path };\n return allowed ? { allowed: true, result } : { allowed: false, ...relationDenialOf(result) };\n}\n\n/** The response for a denied relationship outcome (honoring `onDenied`). */\nexport async function relationOutcomeResponse<Ctx>(\n outcome: Extract<RelationGuardOutcome, { allowed: false }>,\n options: RequireRelationOptions<Ctx>,\n ctx: Ctx,\n): Promise<Response> {\n const { status, body, result } = outcome;\n if (options.onDenied) return options.onDenied({ status, body, result }, ctx);\n return Response.json(body, { status });\n}\n\n/** Wrap a web-standard handler `(request, decision, ...extra)` with a relationship guard. */\nexport function guardFetchRelation<Extra extends unknown[] = []>(\n engine: RelationGuardEngine,\n relation: string,\n object: RelationObjectInput<Request>,\n options: RequireRelationOptions<Request>,\n handler: (\n request: Request,\n decision: RelationDecision,\n ...extra: Extra\n ) => Response | Promise<Response>,\n): (request: Request, ...extra: Extra) => Promise<Response> {\n return async (request, ...extra) => {\n const outcome = await evaluateRelationGuard(\n engine,\n relation,\n object,\n options,\n request,\n (r) => r,\n );\n if (!outcome.allowed) return relationOutcomeResponse(outcome, options, request);\n return handler(request, outcome.result, ...extra);\n };\n}\n"],"mappings":";;;AAiCA,MAAa,eAAe,WAAwC;;AAgCpE,SAAgB,SAAS,QAAkC;CACzD,MAAM,SAAS,OAAO,YAAY,OAAO,MAAM;CAC/C,OAAO;EACL;EACA;EACA,MAAM;GACJ,OACE,WAAW,MACP,4BAA4B,OAAO,SACnC,cAAc,OAAO,KAAK,IAAI,OAAO,OAAO;GAClD,MAAM,WAAW,MAAM,eAAe;GACtC,GAAG,eAAe,MAAM;EAC1B;CACF;AACF;;;;;;;AAYA,eAAsB,cACpB,QACA,MACA,SACA,KACA,WACuB;CACvB,IAAI;CACJ,IAAI,QAAQ,SAAS,UAAU,MAAM,QAAQ,QAAQ,GAAG;MACnD,IAAI,QAAQ,YAAY,WAC3B,UAAU,MAAM,QAAQ,SAAS,WAAW,UAAU,GAAG,CAAC;MACvD,MAAM,IAAI,U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ClD;AACF"}
@@ -1,4 +1,4 @@
1
- const require_routes = require("./routes-irNuuZqo.cjs");
1
+ const require_routes = require("./routes-B2LrYpT0.cjs");
2
2
  //#region src/adapters/guard.ts
3
3
  /** An engine as the guard core sees it. */
4
4
  const guardEngine = (engine) => engine;
@@ -185,4 +185,4 @@ Object.defineProperty(exports, "relationOutcomeResponse", {
185
185
  }
186
186
  });
187
187
 
188
- //# sourceMappingURL=guard-nwdOYe90.cjs.map
188
+ //# sourceMappingURL=guard-DvaoUgjk.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"guard-nwdOYe90.cjs","names":["serializeCheck"],"sources":["../src/adapters/guard.ts"],"sourcesContent":["/**\n * Framework-agnostic core of the `requirePermission` guards (ADR 0008): resolve the subject from\n * the framework's request context (your own resolver, or a `PermissionsAuthProvider`), decide the\n * path with the engine, and either hand the decision on or answer the denial as JSON:\n *\n * - allowed → the {@link CheckResult} is attached to the context;\n * - denied with no session → `401` `code: \"NO_SUBJECT\"` (a guest whose role allows passes);\n * - denied → `403` `code: \"FORBIDDEN\"` with the decision.\n *\n * Every adapter wraps this; it imports no framework.\n *\n * @module\n */\n\nimport type { PermissionsAuthProvider } from \"../auth-provider/contract.ts\";\nimport type { AnyPermissions, Permissions, SubjectInput } from \"../engine.ts\";\nimport type { RulesPaths } from \"../policy.ts\";\nimport type { CheckResult } from \"../schema.ts\";\nimport { serializeCheck } from \"../server/routes.ts\";\n\n/** What a guard needs from the engine (any `createPermissions` engine). */\nexport interface GuardEngine {\n ability(\n subject: SubjectInput,\n ...facts: [] | [{ ctx?: unknown }]\n ): Promise<{ checkAsync(path: string, data?: unknown): Promise<CheckResult> }>;\n}\n\n/** The typed permix paths of an engine's catalog (any string for an untyped engine). */\n// oxlint-disable-next-line typescript/no-explicit-any -- variance, see AnyPermissions.\nexport type PathOf<E> = E extends Permissions<infer D, any, any, any> ? RulesPaths<D> : string;\n\n/** An engine as the guard core sees it. */\nexport const guardEngine = (engine: AnyPermissions): GuardEngine => engine as GuardEngine;\n\n/** Options shared by every framework's `requirePermission` guard. */\nexport interface RequirePermissionOptions<Ctx> {\n /**\n * The subject of this request: an id, an identity (`{ id, role }`), or `null` / `undefined` for\n * no session (the guest role). Required unless `provider` is given.\n */\n subject?: (ctx: Ctx) => SubjectInput | Promise<SubjectInput>;\n /** Resolve the subject with an auth provider instead (better-auth, session, JWT…). */\n provider?: PermissionsAuthProvider;\n /** The data the rule at the path reads (e.g. the loaded resource). */\n data?: (ctx: Ctx) => unknown;\n /** The rules' `ctx`, for catalogs whose rules read app facts. */\n ctx?: (ctx: Ctx) => unknown;\n /** Build the denial response yourself (e.g. a redirect or an HTML page). */\n onDenied?: (denial: GuardDenial, ctx: Ctx) => Response | Promise<Response>;\n}\n\n/** A denied guard: the status, the JSON body and the decision. */\nexport interface GuardDenial {\n status: 401 | 403;\n body: Record<string, unknown>;\n result: CheckResult;\n}\n\n/** Outcome of {@link evaluateGuard}. */\nexport type GuardOutcome =\n | { allowed: true; result: CheckResult }\n | ({ allowed: false } & GuardDenial);\n\n/** The JSON status and body of a denied decision. */\nexport function denialOf(result: CheckResult): GuardDenial {\n const status = result.subject === null ? 401 : 403;\n return {\n status,\n result,\n body: {\n error:\n status === 401\n ? `Unauthorized: sign in to ${result.path}`\n : `Forbidden: ${result.path} (${result.reason})`,\n code: status === 401 ? \"NO_SUBJECT\" : \"FORBIDDEN\",\n ...serializeCheck(result),\n },\n };\n}\n\n/** A web `Response` for a denial. */\nexport const denialResponse = (denial: GuardDenial): Response =>\n Response.json(denial.body, { status: denial.status });\n\n/**\n * Run the guard for one request context. Never throws for a denial; errors from the resolvers,\n * the provider or the engine (an empty subject id: `NoSubjectError`) propagate.\n *\n * @param requestOf How to get a web `Request` from the context (for `provider`).\n */\nexport async function evaluateGuard<Ctx>(\n engine: GuardEngine,\n path: string,\n options: RequirePermissionOptions<Ctx>,\n ctx: Ctx,\n requestOf?: (ctx: Ctx) => Request,\n): Promise<GuardOutcome> {\n let subject: SubjectInput;\n if (options.subject) subject = await options.subject(ctx);\n else if (options.provider && requestOf)\n subject = await options.provider.getSubject(requestOf(ctx));\n else throw new TypeError(\"requirePermission: pass `subject` (or `provider`)\");\n const data = options.data?.(ctx);\n const facts: [] | [{ ctx: unknown }] = options.ctx ? [{ ctx: await options.ctx(ctx) }] : [];\n const ability = await engine.ability(subject, ...facts);\n const result = await ability.checkAsync(path, data);\n if (result.allowed) return { allowed: true, result };\n return { allowed: false, ...denialOf(result) };\n}\n\n/** The response for a denied outcome (honoring `onDenied`). */\nexport async function outcomeResponse<Ctx>(\n outcome: Extract<GuardOutcome, { allowed: false }>,\n options: RequirePermissionOptions<Ctx>,\n ctx: Ctx,\n): Promise<Response> {\n const { status, body, result } = outcome;\n if (options.onDenied) return options.onDenied({ status, body, result }, ctx);\n return Response.json(body, { status });\n}\n\n/**\n * Wrap a web-standard handler `(request, decision, ...extra) => Response` with a guard: the shape\n * `Bun.serve` routes and Next.js route handlers share.\n */\nexport function guardFetch<Extra extends unknown[] = []>(\n engine: GuardEngine,\n path: string,\n options: RequirePermissionOptions<Request>,\n handler: (\n request: Request,\n decision: CheckResult,\n ...extra: Extra\n ) => Response | Promise<Response>,\n): (request: Request, ...extra: Extra) => Promise<Response> {\n return async (request, ...extra) => {\n const outcome = await evaluateGuard(engine, path, options, request, (r) => r);\n if (!outcome.allowed) return outcomeResponse(outcome, options, request);\n return handler(request, outcome.result, ...extra);\n };\n}\n\n// ─── Relationship guards (ReBAC, ADR 0013) ──────────────────────────────────────────────────\n\n/** What a relationship guard needs from the engine. */\nexport interface RelationGuardEngine {\n checkRelation(query: {\n subject: string;\n relation: string;\n object: string;\n }): Promise<{ allowed: boolean; path: string[] }>;\n}\n\n/** An engine as the relationship guard sees it. */\nexport const relationGuardEngine = (engine: AnyPermissions): RelationGuardEngine =>\n engine as unknown as RelationGuardEngine;\n\n/** The decision of a relationship guard. */\nexport interface RelationDecision {\n allowed: boolean;\n /** The ReBAC subject (`user:ana`), `null` without a session. */\n subject: string | null;\n relation: string;\n object: string;\n /** When allowed, the chain of relations that granted it. */\n path: string[];\n}\n\n/** The object a relationship guard checks: fixed, or from the request (`doc:${params.id}`). */\nexport type RelationObjectInput<Ctx> = string | ((ctx: Ctx) => string | Promise<string>);\n\n/** Options shared by every framework's `requireRelation` guard. */\nexport interface RequireRelationOptions<Ctx> {\n /** The subject of this request (an id or identity; `null` / `undefined`: no session → 401). */\n subject?: (ctx: Ctx) => SubjectInput | Promise<SubjectInput>;\n /** Resolve the subject with an auth provider instead. */\n provider?: PermissionsAuthProvider;\n /** The subject id → its ReBAC reference. Default `user:{id}`. */\n subjectRef?: (id: string) => string;\n /** Build the denial response yourself. */\n onDenied?: (denial: RelationDenial, ctx: Ctx) => Response | Promise<Response>;\n}\n\n/** A denied relationship guard. */\nexport interface RelationDenial {\n status: 401 | 403;\n body: Record<string, unknown>;\n result: RelationDecision;\n}\n\n/** Outcome of {@link evaluateRelationGuard}. */\nexport type RelationGuardOutcome =\n | { allowed: true; result: RelationDecision }\n | ({ allowed: false } & RelationDenial);\n\n/** The JSON status and body of a denied relationship decision. */\nexport function relationDenialOf(result: RelationDecision): RelationDenial {\n const status = result.subject === null ? 401 : 403;\n const what = `${result.object}#${result.relation}`;\n return {\n status,\n result,\n body: {\n error: status === 401 ? `Unauthorized: sign in to reach ${what}` : `Forbidden: not ${what}`,\n code: status === 401 ? \"NO_SUBJECT\" : \"FORBIDDEN\",\n ...result,\n },\n };\n}\n\n/**\n * Run a relationship guard for one request context: resolve the subject, map it to a ReBAC\n * reference, resolve the object and `checkRelation`. Never throws for a denial.\n */\nexport async function evaluateRelationGuard<Ctx>(\n engine: RelationGuardEngine,\n relation: string,\n object: RelationObjectInput<Ctx>,\n options: RequireRelationOptions<Ctx>,\n ctx: Ctx,\n requestOf?: (ctx: Ctx) => Request,\n): Promise<RelationGuardOutcome> {\n let subject: SubjectInput;\n if (options.subject) subject = await options.subject(ctx);\n else if (options.provider && requestOf)\n subject = await options.provider.getSubject(requestOf(ctx));\n else throw new TypeError(\"requireRelation: pass `subject` (or `provider`)\");\n const target = typeof object === \"function\" ? await object(ctx) : object;\n const id =\n subject === null || subject === undefined\n ? null\n : typeof subject === \"string\"\n ? subject\n : subject.id;\n if (!id) {\n return {\n allowed: false,\n ...relationDenialOf({ allowed: false, subject: null, relation, object: target, path: [] }),\n };\n }\n const ref = options.subjectRef ? options.subjectRef(id) : `user:${id}`;\n const { allowed, path } = await engine.checkRelation({ subject: ref, relation, object: target });\n const result: RelationDecision = { allowed, subject: ref, relation, object: target, path };\n return allowed ? { allowed: true, result } : { allowed: false, ...relationDenialOf(result) };\n}\n\n/** The response for a denied relationship outcome (honoring `onDenied`). */\nexport async function relationOutcomeResponse<Ctx>(\n outcome: Extract<RelationGuardOutcome, { allowed: false }>,\n options: RequireRelationOptions<Ctx>,\n ctx: Ctx,\n): Promise<Response> {\n const { status, body, result } = outcome;\n if (options.onDenied) return options.onDenied({ status, body, result }, ctx);\n return Response.json(body, { status });\n}\n\n/** Wrap a web-standard handler `(request, decision, ...extra)` with a relationship guard. */\nexport function guardFetchRelation<Extra extends unknown[] = []>(\n engine: RelationGuardEngine,\n relation: string,\n object: RelationObjectInput<Request>,\n options: RequireRelationOptions<Request>,\n handler: (\n request: Request,\n decision: RelationDecision,\n ...extra: Extra\n ) => Response | Promise<Response>,\n): (request: Request, ...extra: Extra) => Promise<Response> {\n return async (request, ...extra) => {\n const outcome = await evaluateRelationGuard(\n engine,\n relation,\n object,\n options,\n request,\n (r) => r,\n );\n if (!outcome.allowed) return relationOutcomeResponse(outcome, options, request);\n return handler(request, outcome.result, ...extra);\n };\n}\n"],"mappings":";;;AAiCA,MAAa,eAAe,WAAwC;;AAgCpE,SAAgB,SAAS,QAAkC;CACzD,MAAM,SAAS,OAAO,YAAY,OAAO,MAAM;CAC/C,OAAO;EACL;EACA;EACA,MAAM;GACJ,OACE,WAAW,MACP,4BAA4B,OAAO,SACnC,cAAc,OAAO,KAAK,IAAI,OAAO,OAAO;GA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,MAAM,EAAE,OAAO,CAAC;AACvC;;AAGA,SAAgB,mBACd,QACA,UACA,QACA,SACA,SAK0D;CAC1D,OAAO,OAAO,SAAS,GAAG,UAAU;EAClC,MAAM,UAAU,MAAM,sBACpB,QACA,UACA,QACA,SACA,UACC,MAAM,CACT;EACA,IAAI,CAAC,QAAQ,SAAS,OAAO,wBAAwB,SAAS,SAAS,OAAO;EAC9E,OAAO,QAAQ,SAAS,QAAQ,QAAQ,GAAG,KAAK;CAClD;AACF"}
1
+ {"version":3,"file":"guard-DvaoUgjk.cjs","names":["serializeCheck"],"sources":["../src/adapters/guard.ts"],"sourcesContent":["/**\n * Framework-agnostic core of the `requirePermission` guards (ADR 0008): resolve the subject from\n * the framework's request context (your own resolver, or a `PermissionsAuthProvider`), decide the\n * path with the engine, and either hand the decision on or answer the denial as JSON:\n *\n * - allowed → the {@link CheckResult} is attached to the context;\n * - denied with no session → `401` `code: \"NO_SUBJECT\"` (a guest whose role allows passes);\n * - denied → `403` `code: \"FORBIDDEN\"` with the decision.\n *\n * Every adapter wraps this; it imports no framework.\n *\n * @module\n */\n\nimport type { PermissionsAuthProvider } from \"../auth-provider/contract.ts\";\nimport type { AnyPermissions, Permissions, SubjectInput } from \"../engine.ts\";\nimport type { RulesPaths } from \"../policy.ts\";\nimport type { CheckResult } from \"../schema.ts\";\nimport { serializeCheck } from \"../server/routes.ts\";\n\n/** What a guard needs from the engine (any `createPermissions` engine). */\nexport interface GuardEngine {\n ability(\n subject: SubjectInput,\n ...facts: [] | [{ ctx?: unknown }]\n ): Promise<{ checkAsync(path: string, data?: unknown): Promise<CheckResult> }>;\n}\n\n/** The typed permix paths of an engine's catalog (any string for an untyped engine). */\n// oxlint-disable-next-line typescript/no-explicit-any -- variance, see AnyPermissions.\nexport type PathOf<E> = E extends Permissions<infer D, any, any, any> ? RulesPaths<D> : string;\n\n/** An engine as the guard core sees it. */\nexport const guardEngine = (engine: AnyPermissions): GuardEngine => engine as GuardEngine;\n\n/** Options shared by every framework's `requirePermission` guard. */\nexport interface RequirePermissionOptions<Ctx> {\n /**\n * The subject of this request: an id, an identity (`{ id, role }`), or `null` / `undefined` for\n * no session (the guest role). Required unless `provider` is given.\n */\n subject?: (ctx: Ctx) => SubjectInput | Promise<SubjectInput>;\n /** Resolve the subject with an auth provider instead (better-auth, session, JWT…). */\n provider?: PermissionsAuthProvider;\n /** The data the rule at the path reads (e.g. the loaded resource). */\n data?: (ctx: Ctx) => unknown;\n /** The rules' `ctx`, for catalogs whose rules read app facts. */\n ctx?: (ctx: Ctx) => unknown;\n /** Build the denial response yourself (e.g. a redirect or an HTML page). */\n onDenied?: (denial: GuardDenial, ctx: Ctx) => Response | Promise<Response>;\n}\n\n/** A denied guard: the status, the JSON body and the decision. */\nexport interface GuardDenial {\n status: 401 | 403;\n body: Record<string, unknown>;\n result: CheckResult;\n}\n\n/** Outcome of {@link evaluateGuard}. */\nexport type GuardOutcome =\n | { allowed: true; result: CheckResult }\n | ({ allowed: false } & GuardDenial);\n\n/** The JSON status and body of a denied decision. */\nexport function denialOf(result: CheckResult): GuardDenial {\n const status = result.subject === null ? 401 : 403;\n return {\n status,\n result,\n body: {\n error:\n status === 401\n ? `Unauthorized: sign in to ${result.path}`\n : `Forbidden: ${result.path} (${result.reason})`,\n code: status === 401 ? \"NO_SUBJECT\" : \"FORBIDDEN\",\n ...serializeCheck(result),\n },\n };\n}\n\n/** A web `Response` for a denial. */\nexport const denialResponse = (denial: GuardDenial): Response =>\n Response.json(denial.body, { status: denial.status });\n\n/**\n * Run the guard for one request context. Never throws for a denial; errors from the resolvers,\n * the provider or the engine (an empty subject id: `NoSubjectError`) propagate.\n *\n * @param requestOf How to get a web `Request` from the context (for `provider`).\n */\nexport async function evaluateGuard<Ctx>(\n engine: GuardEngine,\n path: string,\n options: RequirePermissionOptions<Ctx>,\n ctx: Ctx,\n requestOf?: (ctx: Ctx) => Request,\n): Promise<GuardOutcome> {\n let subject: SubjectInput;\n if (options.subject) subject = await options.subject(ctx);\n else if (options.provider && requestOf)\n subject = await options.provider.getSubject(requestOf(ctx));\n else throw new TypeError(\"requirePermission: pass `subject` (or `provider`)\");\n const data = options.data?.(ctx);\n const facts: [] | [{ ctx: unknown }] = options.ctx ? [{ ctx: await options.ctx(ctx) }] : [];\n const ability = await engine.ability(subject, ...facts);\n const result = await ability.checkAsync(path, data);\n if (result.allowed) return { allowed: true, result };\n return { allowed: false, ...denialOf(result) };\n}\n\n/** The response for a denied outcome (honoring `onDenied`). */\nexport async function outcomeResponse<Ctx>(\n outcome: Extract<GuardOutcome, { allowed: false }>,\n options: RequirePermissionOptions<Ctx>,\n ctx: Ctx,\n): Promise<Response> {\n const { status, body, result } = outcome;\n if (options.onDenied) return options.onDenied({ status, body, result }, ctx);\n return Response.json(body, { status });\n}\n\n/**\n * Wrap a web-standard handler `(request, decision, ...extra) => Response` with a guard: the shape\n * `Bun.serve` routes and Next.js route handlers share.\n */\nexport function guardFetch<Extra extends unknown[] = []>(\n engine: GuardEngine,\n path: string,\n options: RequirePermissionOptions<Request>,\n handler: (\n request: Request,\n decision: CheckResult,\n ...extra: Extra\n ) => Response | Promise<Response>,\n): (request: Request, ...extra: Extra) => Promise<Response> {\n return async (request, ...extra) => {\n const outcome = await evaluateGuard(engine, path, options, request, (r) => r);\n if (!outcome.allowed) return outcomeResponse(outcome, options, request);\n return handler(request, outcome.result, ...extra);\n };\n}\n\n// ─── Relationship guards (ReBAC, ADR 0013) ──────────────────────────────────────────────────\n\n/** What a relationship guard needs from the engine. */\nexport interface RelationGuardEngine {\n checkRelation(query: {\n subject: string;\n relation: string;\n object: string;\n }): Promise<{ allowed: boolean; path: string[] }>;\n}\n\n/** An engine as the relationship guard sees it. */\nexport const relationGuardEngine = (engine: AnyPermissions): RelationGuardEngine =>\n engine as unknown as RelationGuardEngine;\n\n/** The decision of a relationship guard. */\nexport interface RelationDecision {\n allowed: boolean;\n /** The ReBAC subject (`user:ana`), `null` without a session. */\n subject: string | null;\n relation: string;\n object: string;\n /** When allowed, the chain of relations that granted it. */\n path: string[];\n}\n\n/** The object a relationship guard checks: fixed, or from the request (`doc:${params.id}`). */\nexport type RelationObjectInput<Ctx> = string | ((ctx: Ctx) => string | Promise<string>);\n\n/** Options shared by every framework's `requireRelation` guard. */\nexport interface RequireRelationOptions<Ctx> {\n /** The subject of this request (an id or identity; `null` / `undefined`: no session → 401). */\n subject?: (ctx: Ctx) => SubjectInput | Promise<SubjectInput>;\n /** Resolve the subject with an auth provider instead. */\n provider?: PermissionsAuthProvider;\n /** The subject id → its ReBAC reference. Default `user:{id}`. */\n subjectRef?: (id: string) => string;\n /** Build the denial response yourself. */\n onDenied?: (denial: RelationDenial, ctx: Ctx) => Response | Promise<Response>;\n}\n\n/** A denied relationship guard. */\nexport interface RelationDenial {\n status: 401 | 403;\n body: Record<string, unknown>;\n result: RelationDecision;\n}\n\n/** Outcome of {@link evaluateRelationGuard}. */\nexport type RelationGuardOutcome =\n | { allowed: true; result: RelationDecision }\n | ({ allowed: false } & RelationDenial);\n\n/** The JSON status and body of a denied relationship decision. */\nexport function relationDenialOf(result: RelationDecision): RelationDenial {\n const status = result.subject === null ? 401 : 403;\n const what = `${result.object}#${result.relation}`;\n return {\n status,\n result,\n body: {\n error: status === 401 ? `Unauthorized: sign in to reach ${what}` : `Forbidden: not ${what}`,\n code: status === 401 ? \"NO_SUBJECT\" : \"FORBIDDEN\",\n ...result,\n },\n };\n}\n\n/**\n * Run a relationship guard for one request context: resolve the subject, map it to a ReBAC\n * reference, resolve the object and `checkRelation`. Never throws for a denial.\n */\nexport async function evaluateRelationGuard<Ctx>(\n engine: RelationGuardEngine,\n relation: string,\n object: RelationObjectInput<Ctx>,\n options: RequireRelationOptions<Ctx>,\n ctx: Ctx,\n requestOf?: (ctx: Ctx) => Request,\n): Promise<RelationGuardOutcome> {\n let subject: SubjectInput;\n if (options.subject) subject = await options.subject(ctx);\n else if (options.provider && requestOf)\n subject = await options.provider.getSubject(requestOf(ctx));\n else throw new TypeError(\"requireRelation: pass `subject` (or `provider`)\");\n const target = typeof object === \"function\" ? await object(ctx) : object;\n const id =\n subject === null || subject === undefined\n ? null\n : typeof subject === \"string\"\n ? subject\n : subject.id;\n if (!id) {\n return {\n allowed: false,\n ...relationDenialOf({ allowed: false, subject: null, relation, object: target, path: [] }),\n };\n }\n const ref = options.subjectRef ? options.subjectRef(id) : `user:${id}`;\n const { allowed, path } = await engine.checkRelation({ subject: ref, relation, object: target });\n const result: RelationDecision = { allowed, subject: ref, relation, object: target, path };\n return allowed ? { allowed: true, result } : { allowed: false, ...relationDenialOf(result) };\n}\n\n/** The response for a denied relationship outcome (honoring `onDenied`). */\nexport async function relationOutcomeResponse<Ctx>(\n outcome: Extract<RelationGuardOutcome, { allowed: false }>,\n options: RequireRelationOptions<Ctx>,\n ctx: Ctx,\n): Promise<Response> {\n const { status, body, result } = outcome;\n if (options.onDenied) return options.onDenied({ status, body, result }, ctx);\n return Response.json(body, { status });\n}\n\n/** Wrap a web-standard handler `(request, decision, ...extra)` with a relationship guard. */\nexport function guardFetchRelation<Extra extends unknown[] = []>(\n engine: RelationGuardEngine,\n relation: string,\n object: RelationObjectInput<Request>,\n options: RequireRelationOptions<Request>,\n handler: (\n request: Request,\n decision: RelationDecision,\n ...extra: Extra\n ) => Response | Promise<Response>,\n): (request: Request, ...extra: Extra) => Promise<Response> {\n return async (request, ...extra) => {\n const outcome = await evaluateRelationGuard(\n engine,\n relation,\n object,\n options,\n request,\n (r) => r,\n );\n if (!outcome.allowed) return relationOutcomeResponse(outcome, options, request);\n return handler(request, outcome.result, ...extra);\n };\n}\n"],"mappings":";;;AAiCA,MAAa,eAAe,WAAwC;;AAgCpE,SAAgB,SAAS,QAAkC;CACzD,MAAM,SAAS,OAAO,YAAY,OAAO,MAAM;CAC/C,OAAO;EACL;EACA;EACA,MAAM;GACJ,OACE,WAAW,MACP,4BAA4B,OAAO,SACnC,cAAc,OAAO,KAAK,IAAI,OAAO,OAAO;GAClD,MAAM,WAAW,MAAM,eAAe;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vC;;AAGA,SAAgB,mBACd,QACA,UACA,QACA,SACA,SAK0D;CAC1D,OAAO,OAAO,SAAS,GAAG,UAAU;EAClC,MAAM,UAAU,MAAM,sBACpB,QACA,UACA,QACA,SACA,UACC,MAAM,CACT;EACA,IAAI,CAAC,QAAQ,SAAS,OAAO,wBAAwB,SAAS,SAAS,OAAO;EAC9E,OAAO,QAAQ,SAAS,QAAQ,QAAQ,GAAG,KAAK;CAClD;AACF"}
@@ -1,7 +1,7 @@
1
1
  import { y as RulesPaths } from "./policy-DFq_SYR3.cjs";
2
- import { t as PermissionsAuthProvider } from "./contract-BMiOmg2f.cjs";
3
- import { h as CheckResult } from "./contract-Dk6d2ylD.cjs";
4
- import { i as Permissions, l as SubjectInput } from "./engine-CGGVDCqi.cjs";
2
+ import { t as PermissionsAuthProvider } from "./contract-BAisPHBw.cjs";
3
+ import { h as CheckResult } from "./contract-CXPMGuHk.cjs";
4
+ import { i as Permissions, l as SubjectInput } from "./engine-BTgwbHeO.cjs";
5
5
 
6
6
  //#region src/adapters/guard.d.ts
7
7
  /** The typed permix paths of an engine's catalog (any string for an untyped engine). */
@@ -59,4 +59,4 @@ interface RelationDenial {
59
59
  }
60
60
  //#endregion
61
61
  export { RequireRelationOptions as a, RequirePermissionOptions as i, RelationDecision as n, RelationObjectInput as r, PathOf as t };
62
- //# sourceMappingURL=guard-C3o7V14m.d.cts.map
62
+ //# sourceMappingURL=guard-VEK0W8ug.d.cts.map
@@ -1,7 +1,7 @@
1
1
  import { y as RulesPaths } from "./policy-CGA6QD0a.mjs";
2
- import { t as PermissionsAuthProvider } from "./contract-D32H1t0u.mjs";
3
- import { h as CheckResult } from "./contract-DUzgB-He.mjs";
4
- import { i as Permissions, l as SubjectInput } from "./engine-DpFIcbgh.mjs";
2
+ import { t as PermissionsAuthProvider } from "./contract-D6j-yrBL.mjs";
3
+ import { h as CheckResult } from "./contract-DhS23Pcp.mjs";
4
+ import { i as Permissions, l as SubjectInput } from "./engine-C3xHfi3q.mjs";
5
5
 
6
6
  //#region src/adapters/guard.d.ts
7
7
  /** The typed permix paths of an engine's catalog (any string for an untyped engine). */
@@ -59,4 +59,4 @@ interface RelationDenial {
59
59
  }
60
60
  //#endregion
61
61
  export { RequireRelationOptions as a, RequirePermissionOptions as i, RelationDecision as n, RelationObjectInput as r, PathOf as t };
62
- //# sourceMappingURL=guard-DCbTnqPz.d.mts.map
62
+ //# sourceMappingURL=guard-k7A71SWC.d.mts.map
package/dist/index.cjs CHANGED
@@ -1,13 +1,13 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_catalog = require("./catalog.cjs");
3
3
  const require_relationships = require("./relationships-BLYEJ9tc.cjs");
4
- const require_errors = require("./errors-vVYic8gz.cjs");
5
- const require_engine = require("./engine-bMoz3iW-.cjs");
6
- const require_contract = require("./contract-CPmJVoRx.cjs");
7
- const require_kit = require("./kit-C7tepDB2.cjs");
4
+ const require_errors = require("./errors-CjpymzFj.cjs");
5
+ const require_engine = require("./engine--C7zo-4M.cjs");
6
+ const require_contract = require("./contract-Brnu9XXo.cjs");
7
+ const require_kit = require("./kit-BrqnCcDw.cjs");
8
8
  const require_contract$1 = require("./contract-Bpy8yPrS.cjs");
9
- const require_routes = require("./routes-irNuuZqo.cjs");
10
- const require_create_fetch_handler = require("./create-fetch-handler-C-WyaRCR.cjs");
9
+ const require_routes = require("./routes-B2LrYpT0.cjs");
10
+ const require_create_fetch_handler = require("./create-fetch-handler-BHT4vSZs.cjs");
11
11
  let _xtandard_kit_storage = require("@xtandard/kit/storage");
12
12
  let _xtandard_lib_policy_permix = require("@xtandard/lib/policy/permix");
13
13
  let _xtandard_kit_hooks = require("@xtandard/kit/hooks");
@@ -68,6 +68,7 @@ Object.defineProperty(exports, "AsyncRuleError", {
68
68
  }
69
69
  });
70
70
  exports.CONFIG_PATHS = require_routes.CONFIG_PATHS;
71
+ exports.ExternalRolesError = require_errors.ExternalRolesError;
71
72
  exports.ForbiddenError = require_errors.ForbiddenError;
72
73
  Object.defineProperty(exports, "HookDeniedError", {
73
74
  enumerable: true,
@@ -138,6 +139,7 @@ Object.defineProperty(exports, "exclusion", {
138
139
  return _xtandard_lib_policy_rebac.exclusion;
139
140
  }
140
141
  });
142
+ exports.externalRoles = require_contract.externalRoles;
141
143
  Object.defineProperty(exports, "from", {
142
144
  enumerable: true,
143
145
  get: function() {
@@ -159,6 +161,7 @@ Object.defineProperty(exports, "hasPermission", {
159
161
  }
160
162
  });
161
163
  exports.historyQuerySchema = require_relationships.historyQuerySchema;
164
+ exports.identityOf = require_kit.identityOf;
162
165
  Object.defineProperty(exports, "intersection", {
163
166
  enumerable: true,
164
167
  get: function() {
package/dist/index.d.cts CHANGED
@@ -1,12 +1,12 @@
1
1
  import { A as intersection, C as computed, D as from, E as exclusion, M as union, O as hasAssignedPermission, S as checkRulesAtPath, T as direct, _ as RuleHelpers, a as CheckExplanation, b as SubjectRef, c as ObjectRef, d as RelationExplanation, f as RelationExpr, g as RuleContext, h as RelationTuple, j as toPermissionSet, k as hasPermission, l as PermissionPath, m as RelationSchemaError, n as AsyncRuleError, p as RelationSchema, s as Definition, t as Ability, u as RelationDepthError, v as Rules, w as defineRelations, y as RulesPaths } from "./policy-DFq_SYR3.cjs";
2
2
  import { _ as fromAuthorization, a as Label, c as PermissionOf, d as PermissionsConfig, f as PermissionsSubject, g as definePermissions, h as SubjectIdentity, i as DefinitionOf, l as PermissionUnion, m as RoleOf, n as CatalogMeta, o as LabelInput, p as RelationsOf, r as CtxOf, s as NoRelations, t as AnyPermissionsCatalog, u as PermissionsCatalog } from "./catalog-DA_d1SdC.cjs";
3
3
  import { a as WatchablePermissionsStorage, c as isWatchable, i as TransactionalPermissionsStorage, n as PermissionsStorage, o as isCompareAndSwap, r as StorageChangeEvent, s as isTransactional, t as CompareAndSwapPermissionsStorage } from "./contract-RMkmERhT.cjs";
4
- import { a as normalizeRoles, n as ProviderRoleOptions, o as splitRoles, r as RoleMapper, t as PermissionsAuthProvider } from "./contract-BMiOmg2f.cjs";
5
- import { a as toKitAuth, i as subjectOf, n as KitAuthEngine, r as ToKitAuthOptions, t as KitAuth } from "./kit-qAROuhOI.cjs";
4
+ import { a as externalRoles, c as normalizeRoles, i as SubjectLookupFn, l as splitRoles, n as ProviderRoleOptions, r as RoleMapper, t as PermissionsAuthProvider } from "./contract-BAisPHBw.cjs";
5
+ import { a as subjectOf, i as identityOf, n as KitAuthEngine, o as toKitAuth, r as ToKitAuthOptions, t as KitAuth } from "./kit-DLF7DZrp.cjs";
6
6
  import { a as PermissionsAction, i as MUTATING_ACTIONS, n as AuthorizationProvider, o as PermissionsResource, r as AuthorizeInput, s as isMutatingAction, t as ALL_ACTIONS } from "./contract-CNgMXr2u.cjs";
7
- import { A as SetRoleInput, B as relationshipInputSchema, C as ListQuery, D as RelationshipPage, E as RelationshipInput, F as historyQuerySchema, H as revokeInputSchema, I as listObjectsQuerySchema, L as listQuerySchema, M as UpsertSubjectInput, N as actorSchema, O as RelationshipQuery, P as grantInputSchema, R as listRelationSubjectsQuerySchema, S as InstantInput, T as Relationship, U as setRoleInputSchema, V as relationshipQuerySchema, W as upsertSubjectInputSchema, _ as GrantInput, a as HookDeniedError, b as HistoryQuery, c as PermissionsHooksInput, d as runAfter, f as runBefore, g as Grant, h as CheckResult, i as BeforeEventType, j as SubjectRecord, k as RevokeInput, l as defaultHookErrorReporter, m as CheckReason, n as AfterEventType, o as HookErrorReporter, p as Actor, r as BeforeEvent, s as PermissionsHooks, t as AfterEvent, u as normalizeHooks, v as HistoryEntry, w as PermissionsSnapshot, x as HistoryType, y as HistoryPage, z as relationCheckSchema } from "./contract-Dk6d2ylD.cjs";
8
- import { C as RepairReport, S as RelationshipsApi, _ as RelationCheckQuery, a as PermissionsAbility, b as RelationTypeView, c as SetRoleResult, d as SubjectView, f as createPermissions, g as LoadRelationsOptions, h as ListRelationSubjectsQuery, i as Permissions, l as SubjectInput, m as ListObjectsQuery, n as FactsArgs, o as PermissionsOptions, p as DeleteRelationshipResult, r as PathData, s as RevokeResult, t as AnyPermissions, u as SubjectSummary, v as RelationCheckResult, w as WriteRelationshipResult, x as RelationsOptions, y as RelationFacts } from "./engine-CGGVDCqi.cjs";
9
- import { a as AuthProvider, i as PermissionsCorsOptions, n as PermissionsPanelOptions, o as Principal, r as createFetchHandler, t as CreateFetchHandlerResult } from "./create-fetch-handler-BtX64_rS.cjs";
7
+ import { A as RoleSource, B as listRelationSubjectsQuerySchema, C as ListQuery, D as RelationshipPage, E as RelationshipInput, F as actorSchema, G as setRoleInputSchema, H as relationshipInputSchema, I as grantInputSchema, K as upsertSubjectInputSchema, L as historyQuerySchema, M as SetRoleInput, N as SubjectRecord, O as RelationshipQuery, P as UpsertSubjectInput, R as listObjectsQuerySchema, S as InstantInput, T as Relationship, U as relationshipQuerySchema, V as relationCheckSchema, W as revokeInputSchema, _ as GrantInput, a as HookDeniedError, b as HistoryQuery, c as PermissionsHooksInput, d as runAfter, f as runBefore, g as Grant, h as CheckResult, i as BeforeEventType, j as RoleSourceMode, k as RevokeInput, l as defaultHookErrorReporter, m as CheckReason, n as AfterEventType, o as HookErrorReporter, p as Actor, r as BeforeEvent, s as PermissionsHooks, t as AfterEvent, u as normalizeHooks, v as HistoryEntry, w as PermissionsSnapshot, x as HistoryType, y as HistoryPage, z as listQuerySchema } from "./contract-CXPMGuHk.cjs";
8
+ import { C as RelationshipsApi, S as RelationsOptions, T as WriteRelationshipResult, _ as LoadRelationsOptions, a as PermissionsAbility, b as RelationFacts, c as SetRoleResult, d as SubjectSummary, f as SubjectView, g as ListRelationSubjectsQuery, h as ListObjectsQuery, i as Permissions, l as SubjectInput, m as DeleteRelationshipResult, n as FactsArgs, o as PermissionsOptions, p as createPermissions, r as PathData, s as RevokeResult, t as AnyPermissions, u as SubjectLookup, v as RelationCheckQuery, w as RepairReport, x as RelationTypeView, y as RelationCheckResult } from "./engine-BTgwbHeO.cjs";
9
+ import { a as AuthProvider, i as PermissionsCorsOptions, n as PermissionsPanelOptions, o as Principal, r as createFetchHandler, t as CreateFetchHandlerResult } from "./create-fetch-handler-DxhvXuBA.cjs";
10
10
  import { PgNotificationClient, PgNotificationClient as PgNotificationClient$1, WatchSubscribe, WatchSubscribe as WatchSubscribe$1, withWatch } from "@xtandard/kit/storage";
11
11
  import { ValidationError, ValidationIssue } from "@xtandard/kit/util";
12
12
  import { RouteSpec as RouteSpec$1 } from "@xtandard/kit/server/router";
@@ -40,6 +40,13 @@ declare class NotFoundError extends Error {
40
40
  declare class ReadonlyError extends Error {
41
41
  constructor(operation: string);
42
42
  }
43
+ /**
44
+ * `setRole()` on an engine whose `roleSource` is `"external"`: roles are managed by the auth
45
+ * provider, so a stored role would be ignored (ADR 0014). HTTP 409 `ROLES_EXTERNAL`.
46
+ */
47
+ declare class ExternalRolesError extends Error {
48
+ constructor(message?: string);
49
+ }
43
50
  //#endregion
44
51
  //#region src/keys.d.ts
45
52
  /**
@@ -93,11 +100,17 @@ interface PanelConfig {
93
100
  logoUrl?: string;
94
101
  basePath: string;
95
102
  readonly: boolean;
103
+ /** Who owns roles (ADR 0014): `"external"` hides role changes (the auth provider owns them). */
104
+ roleSource: RoleSourceMode;
96
105
  authenticated: boolean;
97
- /** The caller, with its effective catalog role; `null` when not authenticated. */
106
+ /**
107
+ * The caller, with its effective catalog role and the source that decided it; `null` when not
108
+ * authenticated.
109
+ */
98
110
  principal: {
99
111
  id: string;
100
112
  role: string;
113
+ roleSource?: RoleSource;
101
114
  name?: string;
102
115
  email?: string;
103
116
  } | null;
@@ -122,6 +135,8 @@ interface CatalogView {
122
135
  defaultRole: string;
123
136
  managerRoles: string[];
124
137
  directGrants: boolean;
138
+ /** Who owns roles: `"stored"` (role changes allowed) or `"external"` (the auth provider's). */
139
+ roleSource: RoleSourceMode;
125
140
  /** Every leaf permix path of every role's rules tree, sorted (for the playground). */
126
141
  paths: string[];
127
142
  /** The relation schema (ReBAC), `null` when the catalog declares none. */
@@ -133,7 +148,10 @@ interface SubjectList {
133
148
  }
134
149
  /** `GET /api/subjects/:id`: the stored view plus the effective role and active permissions. */
135
150
  interface SubjectDetail extends SubjectView {
136
- /** The stored role if any, else the catalog's `defaultRole` (the panel has no provider role). */
151
+ /**
152
+ * The role checks use: the stored role (`roleSource: "stored"` mode only), else the auth
153
+ * provider's (`lookupSubject`), else the catalog's `defaultRole`; `roleSource` says which.
154
+ */
137
155
  effectiveRole: string;
138
156
  /** The non-expired, assignable granted permissions. */
139
157
  permissions: string[];
@@ -149,8 +167,8 @@ type RouteSpec = RouteSpec$1<PermissionsAction, RouteTag> & {
149
167
  * placeholder subject and no grants; a role whose rules can't be built that way is skipped.
150
168
  */
151
169
  declare function catalogPaths(catalog: AnyPermissionsCatalog): string[];
152
- /** The catalog view served at `/api/catalog`. */
153
- declare function catalogView(catalog: AnyPermissionsCatalog): CatalogView;
170
+ /** The catalog view served at `/api/catalog` (`roleSource`: the engine's, default `"stored"`). */
171
+ declare function catalogView(catalog: AnyPermissionsCatalog, roleSource?: RoleSourceMode): CatalogView;
154
172
  /** A check result as JSON: `explanation.error` (a thrown value) becomes its message. */
155
173
  declare function serializeCheck(result: CheckResult): CheckResult;
156
174
  /** The documented route table (every API route, in match order). */
@@ -191,5 +209,5 @@ interface OpenApiOptions {
191
209
  */
192
210
  declare function buildOpenApiDocument(options?: OpenApiOptions): Record<string, unknown>;
193
211
  //#endregion
194
- export { ALL_ACTIONS, API_ROUTES, type Ability, type Actor, type AfterEvent, type AfterEventType, type AnyPermissions, type AnyPermissionsCatalog, AsyncRuleError, type AuthProvider, type AuthorizationProvider, type AuthorizeInput, type BeforeEvent, type BeforeEventType, CONFIG_PATHS, type CatalogMeta, type CatalogView, type CheckExplanation, type CheckReason, type CheckResult, type CompareAndSwapPermissionsStorage, type CreateFetchHandlerResult, type CtxOf, type Definition, type DefinitionOf, type DeleteRelationshipResult, type FactsArgs, ForbiddenError, type Grant, type GrantInput, type HistoryEntry, type HistoryPage, type HistoryQuery, type HistoryType, HookDeniedError, type HookErrorReporter, type InstantInput, ROOT as KEY_ROOT, type KitAuth, type KitAuthEngine, type Label, type LabelInput, type LabeledKey, type ListObjectsQuery, type ListQuery, type ListRelationSubjectsQuery, type LoadRelationsOptions, MUTATING_ACTIONS, type NoRelations, NoSubjectError, NotFoundError, type ObjectRef, type OpenApiOptions, type PanelConfig, type PathData, type PermissionOf, type PermissionPath, type PermissionUnion, type Permissions, type PermissionsAbility, type PermissionsAction, type PermissionsAuthProvider, type PermissionsCatalog, type PermissionsConfig, type PermissionsCorsOptions, type PermissionsHooks, type PermissionsHooksInput, type PermissionsOptions, type PermissionsPanelOptions, type PermissionsResource, type PermissionsSnapshot, type PermissionsStorage, type PermissionsSubject, type PgNotificationClient, type Principal, type ProviderRoleOptions, ReadonlyError, type RelationCheckQuery, type RelationCheckResult, RelationDepthError, type RelationExplanation, type RelationExpr, type RelationFacts, type RelationSchema, RelationSchemaError, type RelationTuple, type RelationsOf, type RelationsOptions, type Relationship, type RelationshipInput, type RelationshipPage, type RelationshipQuery, type RelationshipsApi, type RepairReport, type RevokeInput, type RevokeResult, type RoleMapper, type RoleOf, type RouteSpec, type RouteTag, type RuleContext, type RuleHelpers, type Rules, type RulesPaths, type SetRoleInput, type SetRoleResult, type StorageChangeEvent, type SubjectDetail, type SubjectIdentity, type SubjectInput, type SubjectList, type SubjectRecord, type SubjectRef, type SubjectSummary, type SubjectView, type ToKitAuthOptions, type TransactionalPermissionsStorage, UnknownPermissionError, UnknownRoleError, type UpsertSubjectInput, ValidationError, type ValidationIssue, type WatchSubscribe, type WatchablePermissionsStorage, type WriteRelationshipResult, actorSchema, buildOpenApiDocument, catalogPaths, catalogView, checkRulesAtPath, computed, createFetchHandler, createPermissions, defaultHookErrorReporter, definePermissions, defineRelations, direct, exclusion, from, fromAuthorization, grantInputSchema, hasAssignedPermission, hasPermission, historyQuerySchema, intersection, isCompareAndSwap, isMutatingAction, isTransactional, isWatchable, listObjectsQuerySchema, listQuerySchema, listRelationSubjectsQuerySchema, mapError, normalizeHooks, normalizeRoles, pgListenNotify, relationCheckSchema, relationshipInputSchema, relationshipQuerySchema, revokeInputSchema, runAfter, runBefore, serializeCheck, setRoleInputSchema, splitRoles, subjectOf, toKitAuth, toPermissionSet, union, upsertSubjectInputSchema, withWatch };
212
+ export { ALL_ACTIONS, API_ROUTES, type Ability, type Actor, type AfterEvent, type AfterEventType, type AnyPermissions, type AnyPermissionsCatalog, AsyncRuleError, type AuthProvider, type AuthorizationProvider, type AuthorizeInput, type BeforeEvent, type BeforeEventType, CONFIG_PATHS, type CatalogMeta, type CatalogView, type CheckExplanation, type CheckReason, type CheckResult, type CompareAndSwapPermissionsStorage, type CreateFetchHandlerResult, type CtxOf, type Definition, type DefinitionOf, type DeleteRelationshipResult, ExternalRolesError, type FactsArgs, ForbiddenError, type Grant, type GrantInput, type HistoryEntry, type HistoryPage, type HistoryQuery, type HistoryType, HookDeniedError, type HookErrorReporter, type InstantInput, ROOT as KEY_ROOT, type KitAuth, type KitAuthEngine, type Label, type LabelInput, type LabeledKey, type ListObjectsQuery, type ListQuery, type ListRelationSubjectsQuery, type LoadRelationsOptions, MUTATING_ACTIONS, type NoRelations, NoSubjectError, NotFoundError, type ObjectRef, type OpenApiOptions, type PanelConfig, type PathData, type PermissionOf, type PermissionPath, type PermissionUnion, type Permissions, type PermissionsAbility, type PermissionsAction, type PermissionsAuthProvider, type PermissionsCatalog, type PermissionsConfig, type PermissionsCorsOptions, type PermissionsHooks, type PermissionsHooksInput, type PermissionsOptions, type PermissionsPanelOptions, type PermissionsResource, type PermissionsSnapshot, type PermissionsStorage, type PermissionsSubject, type PgNotificationClient, type Principal, type ProviderRoleOptions, ReadonlyError, type RelationCheckQuery, type RelationCheckResult, RelationDepthError, type RelationExplanation, type RelationExpr, type RelationFacts, type RelationSchema, RelationSchemaError, type RelationTuple, type RelationsOf, type RelationsOptions, type Relationship, type RelationshipInput, type RelationshipPage, type RelationshipQuery, type RelationshipsApi, type RepairReport, type RevokeInput, type RevokeResult, type RoleMapper, type RoleOf, type RoleSource, type RoleSourceMode, type RouteSpec, type RouteTag, type RuleContext, type RuleHelpers, type Rules, type RulesPaths, type SetRoleInput, type SetRoleResult, type StorageChangeEvent, type SubjectDetail, type SubjectIdentity, type SubjectInput, type SubjectList, type SubjectLookup, type SubjectLookupFn, type SubjectRecord, type SubjectRef, type SubjectSummary, type SubjectView, type ToKitAuthOptions, type TransactionalPermissionsStorage, UnknownPermissionError, UnknownRoleError, type UpsertSubjectInput, ValidationError, type ValidationIssue, type WatchSubscribe, type WatchablePermissionsStorage, type WriteRelationshipResult, actorSchema, buildOpenApiDocument, catalogPaths, catalogView, checkRulesAtPath, computed, createFetchHandler, createPermissions, defaultHookErrorReporter, definePermissions, defineRelations, direct, exclusion, externalRoles, from, fromAuthorization, grantInputSchema, hasAssignedPermission, hasPermission, historyQuerySchema, identityOf, intersection, isCompareAndSwap, isMutatingAction, isTransactional, isWatchable, listObjectsQuerySchema, listQuerySchema, listRelationSubjectsQuerySchema, mapError, normalizeHooks, normalizeRoles, pgListenNotify, relationCheckSchema, relationshipInputSchema, relationshipQuerySchema, revokeInputSchema, runAfter, runBefore, serializeCheck, setRoleInputSchema, splitRoles, subjectOf, toKitAuth, toPermissionSet, union, upsertSubjectInputSchema, withWatch };
195
213
  //# sourceMappingURL=index.d.cts.map
package/dist/index.d.mts CHANGED
@@ -1,12 +1,12 @@
1
1
  import { A as intersection, C as computed, D as from, E as exclusion, M as union, O as hasAssignedPermission, S as checkRulesAtPath, T as direct, _ as RuleHelpers, a as CheckExplanation, b as SubjectRef, c as ObjectRef, d as RelationExplanation, f as RelationExpr, g as RuleContext, h as RelationTuple, j as toPermissionSet, k as hasPermission, l as PermissionPath, m as RelationSchemaError, n as AsyncRuleError, p as RelationSchema, s as Definition, t as Ability, u as RelationDepthError, v as Rules, w as defineRelations, y as RulesPaths } from "./policy-CGA6QD0a.mjs";
2
2
  import { _ as fromAuthorization, a as Label, c as PermissionOf, d as PermissionsConfig, f as PermissionsSubject, g as definePermissions, h as SubjectIdentity, i as DefinitionOf, l as PermissionUnion, m as RoleOf, n as CatalogMeta, o as LabelInput, p as RelationsOf, r as CtxOf, s as NoRelations, t as AnyPermissionsCatalog, u as PermissionsCatalog } from "./catalog-DJcJ3ycq.mjs";
3
3
  import { a as WatchablePermissionsStorage, c as isWatchable, i as TransactionalPermissionsStorage, n as PermissionsStorage, o as isCompareAndSwap, r as StorageChangeEvent, s as isTransactional, t as CompareAndSwapPermissionsStorage } from "./contract-RMkmERhT.mjs";
4
- import { a as normalizeRoles, n as ProviderRoleOptions, o as splitRoles, r as RoleMapper, t as PermissionsAuthProvider } from "./contract-D32H1t0u.mjs";
5
- import { a as toKitAuth, i as subjectOf, n as KitAuthEngine, r as ToKitAuthOptions, t as KitAuth } from "./kit-DMVBLBI9.mjs";
4
+ import { a as externalRoles, c as normalizeRoles, i as SubjectLookupFn, l as splitRoles, n as ProviderRoleOptions, r as RoleMapper, t as PermissionsAuthProvider } from "./contract-D6j-yrBL.mjs";
5
+ import { a as subjectOf, i as identityOf, n as KitAuthEngine, o as toKitAuth, r as ToKitAuthOptions, t as KitAuth } from "./kit-51JtMxsn.mjs";
6
6
  import { a as PermissionsAction, i as MUTATING_ACTIONS, n as AuthorizationProvider, o as PermissionsResource, r as AuthorizeInput, s as isMutatingAction, t as ALL_ACTIONS } from "./contract-CNgMXr2u.mjs";
7
- import { A as SetRoleInput, B as relationshipInputSchema, C as ListQuery, D as RelationshipPage, E as RelationshipInput, F as historyQuerySchema, H as revokeInputSchema, I as listObjectsQuerySchema, L as listQuerySchema, M as UpsertSubjectInput, N as actorSchema, O as RelationshipQuery, P as grantInputSchema, R as listRelationSubjectsQuerySchema, S as InstantInput, T as Relationship, U as setRoleInputSchema, V as relationshipQuerySchema, W as upsertSubjectInputSchema, _ as GrantInput, a as HookDeniedError, b as HistoryQuery, c as PermissionsHooksInput, d as runAfter, f as runBefore, g as Grant, h as CheckResult, i as BeforeEventType, j as SubjectRecord, k as RevokeInput, l as defaultHookErrorReporter, m as CheckReason, n as AfterEventType, o as HookErrorReporter, p as Actor, r as BeforeEvent, s as PermissionsHooks, t as AfterEvent, u as normalizeHooks, v as HistoryEntry, w as PermissionsSnapshot, x as HistoryType, y as HistoryPage, z as relationCheckSchema } from "./contract-DUzgB-He.mjs";
8
- import { C as RepairReport, S as RelationshipsApi, _ as RelationCheckQuery, a as PermissionsAbility, b as RelationTypeView, c as SetRoleResult, d as SubjectView, f as createPermissions, g as LoadRelationsOptions, h as ListRelationSubjectsQuery, i as Permissions, l as SubjectInput, m as ListObjectsQuery, n as FactsArgs, o as PermissionsOptions, p as DeleteRelationshipResult, r as PathData, s as RevokeResult, t as AnyPermissions, u as SubjectSummary, v as RelationCheckResult, w as WriteRelationshipResult, x as RelationsOptions, y as RelationFacts } from "./engine-DpFIcbgh.mjs";
9
- import { a as AuthProvider, i as PermissionsCorsOptions, n as PermissionsPanelOptions, o as Principal, r as createFetchHandler, t as CreateFetchHandlerResult } from "./create-fetch-handler-BHDU4chu.mjs";
7
+ import { A as RoleSource, B as listRelationSubjectsQuerySchema, C as ListQuery, D as RelationshipPage, E as RelationshipInput, F as actorSchema, G as setRoleInputSchema, H as relationshipInputSchema, I as grantInputSchema, K as upsertSubjectInputSchema, L as historyQuerySchema, M as SetRoleInput, N as SubjectRecord, O as RelationshipQuery, P as UpsertSubjectInput, R as listObjectsQuerySchema, S as InstantInput, T as Relationship, U as relationshipQuerySchema, V as relationCheckSchema, W as revokeInputSchema, _ as GrantInput, a as HookDeniedError, b as HistoryQuery, c as PermissionsHooksInput, d as runAfter, f as runBefore, g as Grant, h as CheckResult, i as BeforeEventType, j as RoleSourceMode, k as RevokeInput, l as defaultHookErrorReporter, m as CheckReason, n as AfterEventType, o as HookErrorReporter, p as Actor, r as BeforeEvent, s as PermissionsHooks, t as AfterEvent, u as normalizeHooks, v as HistoryEntry, w as PermissionsSnapshot, x as HistoryType, y as HistoryPage, z as listQuerySchema } from "./contract-DhS23Pcp.mjs";
8
+ import { C as RelationshipsApi, S as RelationsOptions, T as WriteRelationshipResult, _ as LoadRelationsOptions, a as PermissionsAbility, b as RelationFacts, c as SetRoleResult, d as SubjectSummary, f as SubjectView, g as ListRelationSubjectsQuery, h as ListObjectsQuery, i as Permissions, l as SubjectInput, m as DeleteRelationshipResult, n as FactsArgs, o as PermissionsOptions, p as createPermissions, r as PathData, s as RevokeResult, t as AnyPermissions, u as SubjectLookup, v as RelationCheckQuery, w as RepairReport, x as RelationTypeView, y as RelationCheckResult } from "./engine-C3xHfi3q.mjs";
9
+ import { a as AuthProvider, i as PermissionsCorsOptions, n as PermissionsPanelOptions, o as Principal, r as createFetchHandler, t as CreateFetchHandlerResult } from "./create-fetch-handler-B711wb64.mjs";
10
10
  import { ValidationError, ValidationIssue } from "@xtandard/kit/util";
11
11
  import { PgNotificationClient, PgNotificationClient as PgNotificationClient$1, WatchSubscribe, WatchSubscribe as WatchSubscribe$1, withWatch } from "@xtandard/kit/storage";
12
12
  import { RouteSpec as RouteSpec$1 } from "@xtandard/kit/server/router";
@@ -40,6 +40,13 @@ declare class NotFoundError extends Error {
40
40
  declare class ReadonlyError extends Error {
41
41
  constructor(operation: string);
42
42
  }
43
+ /**
44
+ * `setRole()` on an engine whose `roleSource` is `"external"`: roles are managed by the auth
45
+ * provider, so a stored role would be ignored (ADR 0014). HTTP 409 `ROLES_EXTERNAL`.
46
+ */
47
+ declare class ExternalRolesError extends Error {
48
+ constructor(message?: string);
49
+ }
43
50
  //#endregion
44
51
  //#region src/keys.d.ts
45
52
  /**
@@ -93,11 +100,17 @@ interface PanelConfig {
93
100
  logoUrl?: string;
94
101
  basePath: string;
95
102
  readonly: boolean;
103
+ /** Who owns roles (ADR 0014): `"external"` hides role changes (the auth provider owns them). */
104
+ roleSource: RoleSourceMode;
96
105
  authenticated: boolean;
97
- /** The caller, with its effective catalog role; `null` when not authenticated. */
106
+ /**
107
+ * The caller, with its effective catalog role and the source that decided it; `null` when not
108
+ * authenticated.
109
+ */
98
110
  principal: {
99
111
  id: string;
100
112
  role: string;
113
+ roleSource?: RoleSource;
101
114
  name?: string;
102
115
  email?: string;
103
116
  } | null;
@@ -122,6 +135,8 @@ interface CatalogView {
122
135
  defaultRole: string;
123
136
  managerRoles: string[];
124
137
  directGrants: boolean;
138
+ /** Who owns roles: `"stored"` (role changes allowed) or `"external"` (the auth provider's). */
139
+ roleSource: RoleSourceMode;
125
140
  /** Every leaf permix path of every role's rules tree, sorted (for the playground). */
126
141
  paths: string[];
127
142
  /** The relation schema (ReBAC), `null` when the catalog declares none. */
@@ -133,7 +148,10 @@ interface SubjectList {
133
148
  }
134
149
  /** `GET /api/subjects/:id`: the stored view plus the effective role and active permissions. */
135
150
  interface SubjectDetail extends SubjectView {
136
- /** The stored role if any, else the catalog's `defaultRole` (the panel has no provider role). */
151
+ /**
152
+ * The role checks use: the stored role (`roleSource: "stored"` mode only), else the auth
153
+ * provider's (`lookupSubject`), else the catalog's `defaultRole`; `roleSource` says which.
154
+ */
137
155
  effectiveRole: string;
138
156
  /** The non-expired, assignable granted permissions. */
139
157
  permissions: string[];
@@ -149,8 +167,8 @@ type RouteSpec = RouteSpec$1<PermissionsAction, RouteTag> & {
149
167
  * placeholder subject and no grants; a role whose rules can't be built that way is skipped.
150
168
  */
151
169
  declare function catalogPaths(catalog: AnyPermissionsCatalog): string[];
152
- /** The catalog view served at `/api/catalog`. */
153
- declare function catalogView(catalog: AnyPermissionsCatalog): CatalogView;
170
+ /** The catalog view served at `/api/catalog` (`roleSource`: the engine's, default `"stored"`). */
171
+ declare function catalogView(catalog: AnyPermissionsCatalog, roleSource?: RoleSourceMode): CatalogView;
154
172
  /** A check result as JSON: `explanation.error` (a thrown value) becomes its message. */
155
173
  declare function serializeCheck(result: CheckResult): CheckResult;
156
174
  /** The documented route table (every API route, in match order). */
@@ -191,5 +209,5 @@ interface OpenApiOptions {
191
209
  */
192
210
  declare function buildOpenApiDocument(options?: OpenApiOptions): Record<string, unknown>;
193
211
  //#endregion
194
- export { ALL_ACTIONS, API_ROUTES, type Ability, type Actor, type AfterEvent, type AfterEventType, type AnyPermissions, type AnyPermissionsCatalog, AsyncRuleError, type AuthProvider, type AuthorizationProvider, type AuthorizeInput, type BeforeEvent, type BeforeEventType, CONFIG_PATHS, type CatalogMeta, type CatalogView, type CheckExplanation, type CheckReason, type CheckResult, type CompareAndSwapPermissionsStorage, type CreateFetchHandlerResult, type CtxOf, type Definition, type DefinitionOf, type DeleteRelationshipResult, type FactsArgs, ForbiddenError, type Grant, type GrantInput, type HistoryEntry, type HistoryPage, type HistoryQuery, type HistoryType, HookDeniedError, type HookErrorReporter, type InstantInput, ROOT as KEY_ROOT, type KitAuth, type KitAuthEngine, type Label, type LabelInput, type LabeledKey, type ListObjectsQuery, type ListQuery, type ListRelationSubjectsQuery, type LoadRelationsOptions, MUTATING_ACTIONS, type NoRelations, NoSubjectError, NotFoundError, type ObjectRef, type OpenApiOptions, type PanelConfig, type PathData, type PermissionOf, type PermissionPath, type PermissionUnion, type Permissions, type PermissionsAbility, type PermissionsAction, type PermissionsAuthProvider, type PermissionsCatalog, type PermissionsConfig, type PermissionsCorsOptions, type PermissionsHooks, type PermissionsHooksInput, type PermissionsOptions, type PermissionsPanelOptions, type PermissionsResource, type PermissionsSnapshot, type PermissionsStorage, type PermissionsSubject, type PgNotificationClient, type Principal, type ProviderRoleOptions, ReadonlyError, type RelationCheckQuery, type RelationCheckResult, RelationDepthError, type RelationExplanation, type RelationExpr, type RelationFacts, type RelationSchema, RelationSchemaError, type RelationTuple, type RelationsOf, type RelationsOptions, type Relationship, type RelationshipInput, type RelationshipPage, type RelationshipQuery, type RelationshipsApi, type RepairReport, type RevokeInput, type RevokeResult, type RoleMapper, type RoleOf, type RouteSpec, type RouteTag, type RuleContext, type RuleHelpers, type Rules, type RulesPaths, type SetRoleInput, type SetRoleResult, type StorageChangeEvent, type SubjectDetail, type SubjectIdentity, type SubjectInput, type SubjectList, type SubjectRecord, type SubjectRef, type SubjectSummary, type SubjectView, type ToKitAuthOptions, type TransactionalPermissionsStorage, UnknownPermissionError, UnknownRoleError, type UpsertSubjectInput, ValidationError, type ValidationIssue, type WatchSubscribe, type WatchablePermissionsStorage, type WriteRelationshipResult, actorSchema, buildOpenApiDocument, catalogPaths, catalogView, checkRulesAtPath, computed, createFetchHandler, createPermissions, defaultHookErrorReporter, definePermissions, defineRelations, direct, exclusion, from, fromAuthorization, grantInputSchema, hasAssignedPermission, hasPermission, historyQuerySchema, intersection, isCompareAndSwap, isMutatingAction, isTransactional, isWatchable, listObjectsQuerySchema, listQuerySchema, listRelationSubjectsQuerySchema, mapError, normalizeHooks, normalizeRoles, pgListenNotify, relationCheckSchema, relationshipInputSchema, relationshipQuerySchema, revokeInputSchema, runAfter, runBefore, serializeCheck, setRoleInputSchema, splitRoles, subjectOf, toKitAuth, toPermissionSet, union, upsertSubjectInputSchema, withWatch };
212
+ export { ALL_ACTIONS, API_ROUTES, type Ability, type Actor, type AfterEvent, type AfterEventType, type AnyPermissions, type AnyPermissionsCatalog, AsyncRuleError, type AuthProvider, type AuthorizationProvider, type AuthorizeInput, type BeforeEvent, type BeforeEventType, CONFIG_PATHS, type CatalogMeta, type CatalogView, type CheckExplanation, type CheckReason, type CheckResult, type CompareAndSwapPermissionsStorage, type CreateFetchHandlerResult, type CtxOf, type Definition, type DefinitionOf, type DeleteRelationshipResult, ExternalRolesError, type FactsArgs, ForbiddenError, type Grant, type GrantInput, type HistoryEntry, type HistoryPage, type HistoryQuery, type HistoryType, HookDeniedError, type HookErrorReporter, type InstantInput, ROOT as KEY_ROOT, type KitAuth, type KitAuthEngine, type Label, type LabelInput, type LabeledKey, type ListObjectsQuery, type ListQuery, type ListRelationSubjectsQuery, type LoadRelationsOptions, MUTATING_ACTIONS, type NoRelations, NoSubjectError, NotFoundError, type ObjectRef, type OpenApiOptions, type PanelConfig, type PathData, type PermissionOf, type PermissionPath, type PermissionUnion, type Permissions, type PermissionsAbility, type PermissionsAction, type PermissionsAuthProvider, type PermissionsCatalog, type PermissionsConfig, type PermissionsCorsOptions, type PermissionsHooks, type PermissionsHooksInput, type PermissionsOptions, type PermissionsPanelOptions, type PermissionsResource, type PermissionsSnapshot, type PermissionsStorage, type PermissionsSubject, type PgNotificationClient, type Principal, type ProviderRoleOptions, ReadonlyError, type RelationCheckQuery, type RelationCheckResult, RelationDepthError, type RelationExplanation, type RelationExpr, type RelationFacts, type RelationSchema, RelationSchemaError, type RelationTuple, type RelationsOf, type RelationsOptions, type Relationship, type RelationshipInput, type RelationshipPage, type RelationshipQuery, type RelationshipsApi, type RepairReport, type RevokeInput, type RevokeResult, type RoleMapper, type RoleOf, type RoleSource, type RoleSourceMode, type RouteSpec, type RouteTag, type RuleContext, type RuleHelpers, type Rules, type RulesPaths, type SetRoleInput, type SetRoleResult, type StorageChangeEvent, type SubjectDetail, type SubjectIdentity, type SubjectInput, type SubjectList, type SubjectLookup, type SubjectLookupFn, type SubjectRecord, type SubjectRef, type SubjectSummary, type SubjectView, type ToKitAuthOptions, type TransactionalPermissionsStorage, UnknownPermissionError, UnknownRoleError, type UpsertSubjectInput, ValidationError, type ValidationIssue, type WatchSubscribe, type WatchablePermissionsStorage, type WriteRelationshipResult, actorSchema, buildOpenApiDocument, catalogPaths, catalogView, checkRulesAtPath, computed, createFetchHandler, createPermissions, defaultHookErrorReporter, definePermissions, defineRelations, direct, exclusion, externalRoles, from, fromAuthorization, grantInputSchema, hasAssignedPermission, hasPermission, historyQuerySchema, identityOf, intersection, isCompareAndSwap, isMutatingAction, isTransactional, isWatchable, listObjectsQuerySchema, listQuerySchema, listRelationSubjectsQuerySchema, mapError, normalizeHooks, normalizeRoles, pgListenNotify, relationCheckSchema, relationshipInputSchema, relationshipQuerySchema, revokeInputSchema, runAfter, runBefore, serializeCheck, setRoleInputSchema, splitRoles, subjectOf, toKitAuth, toPermissionSet, union, upsertSubjectInputSchema, withWatch };
195
213
  //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs CHANGED
@@ -1,13 +1,13 @@
1
1
  import { a as computed, b as union, d as exclusion, f as from, g as intersection, i as checkRulesAtPath, l as defineRelations, m as hasPermission, n as RelationDepthError, p as hasAssignedPermission, r as RelationSchemaError, t as AsyncRuleError, u as direct, y as toPermissionSet } from "./policy-BQmlo2lu.mjs";
2
2
  import { definePermissions, fromAuthorization } from "./catalog.mjs";
3
3
  import { A as revokeInputSchema, C as historyQuerySchema, D as relationCheckSchema, E as listRelationSubjectsQuerySchema, M as upsertSubjectInputSchema, O as relationshipInputSchema, S as grantInputSchema, T as listQuerySchema, _ as defaultHookErrorReporter, a as isWatchable, b as runBefore, g as HookDeniedError, i as isTransactional, j as setRoleInputSchema, k as relationshipQuerySchema, o as ROOT, r as isCompareAndSwap, v as normalizeHooks, w as listObjectsQuerySchema, x as actorSchema, y as runAfter } from "./relationships-BfLonEMI.mjs";
4
- import { a as UnknownPermissionError, i as ReadonlyError, n as NoSubjectError, o as UnknownRoleError, r as NotFoundError, s as ValidationError, t as ForbiddenError } from "./errors-bL3XQLfE.mjs";
5
- import { t as createPermissions } from "./engine-Bufv0TbD.mjs";
6
- import { n as normalizeRoles, r as splitRoles } from "./contract-Yc5AZuvv.mjs";
7
- import { n as toKitAuth, t as subjectOf } from "./kit-fzXHYb1l.mjs";
4
+ import { a as ReadonlyError, c as ValidationError, i as NotFoundError, n as ForbiddenError, o as UnknownPermissionError, r as NoSubjectError, s as UnknownRoleError, t as ExternalRolesError } from "./errors-CG_OLEEv.mjs";
5
+ import { t as createPermissions } from "./engine-CR75K253.mjs";
6
+ import { a as splitRoles, i as normalizeRoles, t as externalRoles } from "./contract-BganM0fx.mjs";
7
+ import { n as subjectOf, r as toKitAuth, t as identityOf } from "./kit-BM3uosfV.mjs";
8
8
  import { i as isMutatingAction, n as MUTATING_ACTIONS, t as ALL_ACTIONS } from "./contract-DTdTXZtJ.mjs";
9
- import { c as serializeCheck, i as catalogView, n as CONFIG_PATHS, o as mapError, r as catalogPaths, t as API_ROUTES } from "./routes-DtRb3EO0.mjs";
10
- import { r as buildOpenApiDocument, t as createFetchHandler } from "./create-fetch-handler-ojjpk1Iw.mjs";
9
+ import { c as serializeCheck, i as catalogView, n as CONFIG_PATHS, o as mapError, r as catalogPaths, t as API_ROUTES } from "./routes-Cx-kl4PY.mjs";
10
+ import { r as buildOpenApiDocument, t as createFetchHandler } from "./create-fetch-handler-B0twltQL.mjs";
11
11
  import { pgListenNotify as pgListenNotify$1, withWatch } from "@xtandard/kit/storage";
12
12
  //#region src/storage/watch.ts
13
13
  /**
@@ -55,6 +55,6 @@ function pgListenNotify(client, channel = "xtandard_permissions") {
55
55
  return pgListenNotify$1(client, channel);
56
56
  }
57
57
  //#endregion
58
- export { ALL_ACTIONS, API_ROUTES, AsyncRuleError, CONFIG_PATHS, ForbiddenError, HookDeniedError, ROOT as KEY_ROOT, MUTATING_ACTIONS, NoSubjectError, NotFoundError, ReadonlyError, RelationDepthError, RelationSchemaError, UnknownPermissionError, UnknownRoleError, ValidationError, actorSchema, buildOpenApiDocument, catalogPaths, catalogView, checkRulesAtPath, computed, createFetchHandler, createPermissions, defaultHookErrorReporter, definePermissions, defineRelations, direct, exclusion, from, fromAuthorization, grantInputSchema, hasAssignedPermission, hasPermission, historyQuerySchema, intersection, isCompareAndSwap, isMutatingAction, isTransactional, isWatchable, listObjectsQuerySchema, listQuerySchema, listRelationSubjectsQuerySchema, mapError, normalizeHooks, normalizeRoles, pgListenNotify, relationCheckSchema, relationshipInputSchema, relationshipQuerySchema, revokeInputSchema, runAfter, runBefore, serializeCheck, setRoleInputSchema, splitRoles, subjectOf, toKitAuth, toPermissionSet, union, upsertSubjectInputSchema, withWatch };
58
+ export { ALL_ACTIONS, API_ROUTES, AsyncRuleError, CONFIG_PATHS, ExternalRolesError, ForbiddenError, HookDeniedError, ROOT as KEY_ROOT, MUTATING_ACTIONS, NoSubjectError, NotFoundError, ReadonlyError, RelationDepthError, RelationSchemaError, UnknownPermissionError, UnknownRoleError, ValidationError, actorSchema, buildOpenApiDocument, catalogPaths, catalogView, checkRulesAtPath, computed, createFetchHandler, createPermissions, defaultHookErrorReporter, definePermissions, defineRelations, direct, exclusion, externalRoles, from, fromAuthorization, grantInputSchema, hasAssignedPermission, hasPermission, historyQuerySchema, identityOf, intersection, isCompareAndSwap, isMutatingAction, isTransactional, isWatchable, listObjectsQuerySchema, listQuerySchema, listRelationSubjectsQuerySchema, mapError, normalizeHooks, normalizeRoles, pgListenNotify, relationCheckSchema, relationshipInputSchema, relationshipQuerySchema, revokeInputSchema, runAfter, runBefore, serializeCheck, setRoleInputSchema, splitRoles, subjectOf, toKitAuth, toPermissionSet, union, upsertSubjectInputSchema, withWatch };
59
59
 
60
60
  //# sourceMappingURL=index.mjs.map