@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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes-B2LrYpT0.cjs","names":["v","grantInputSchema","revokeInputSchema","relationshipInputSchema","relationCheckSchema","relationSchemaView","principalIdentity","ALL_ACTIONS","isMutatingAction","UnknownRoleError"],"sources":["../src/server/validation.ts","../src/server/routes.ts"],"sourcesContent":["/**\n * Valibot schemas of the HTTP request bodies (docs: the OpenAPI component schemas of the same\n * names). Unknown keys are dropped: the actor of every write is the authenticated principal, never\n * a body field. The engine validates the domain (assignable permission, known role, future expiry).\n *\n * @module\n */\n\nimport * as v from \"valibot\";\nimport {\n grantInputSchema,\n relationCheckSchema,\n relationshipInputSchema,\n revokeInputSchema,\n} from \"../schema.ts\";\n\nconst nonEmpty = v.pipe(v.string(), v.minLength(1, \"must not be empty\"));\nconst reason = v.pipe(v.string(), v.maxLength(1000, \"must be at most 1000 characters\"));\nconst display = v.nullable(v.pipe(v.string(), v.maxLength(500, \"must be at most 500 characters\")));\n\n/** `POST /api/grants`: `{ subject, permission, reason?, expiresAt? }`. */\nexport const grantBodySchema = v.omit(grantInputSchema, [\"actor\"]);\n\n/** `DELETE /api/grants/:subject/:permission`: optional `{ reason }`. */\nexport const revokeBodySchema = v.pick(revokeInputSchema, [\"reason\"]);\n\n/**\n * `PUT /api/subjects/:id`: any of `role` (`null` clears the stored assignment), `name`, `email`\n * (`null` clears), plus the `reason` recorded with a role change.\n */\nexport const subjectUpdateBodySchema = v.object({\n role: v.optional(v.nullable(nonEmpty)),\n name: v.optional(display),\n email: v.optional(display),\n reason: v.optional(reason),\n});\n\n/**\n * `POST /api/check` (playground): a stored subject, a bare role (no subject, no grants), both (the\n * role is the provider's, a stored role still wins) or neither (a guest).\n */\nexport const checkBodySchema = v.object({\n subject: v.optional(v.nullable(nonEmpty)),\n role: v.optional(nonEmpty),\n path: nonEmpty,\n data: v.optional(v.unknown()),\n ctx: v.optional(v.unknown()),\n});\n\n/** `POST /api/me/check`: the caller's own check. */\nexport const meCheckBodySchema = v.object({\n path: nonEmpty,\n data: v.optional(v.unknown()),\n});\n\n/** `POST /api/relationships` and `DELETE /api/relationships`: `{ object, relation, subject, reason? }`. */\nexport const relationshipBodySchema = v.omit(relationshipInputSchema, [\"actor\"]);\n\n/** `POST /api/relationships/check`: `{ subject, relation, object }`. */\nexport const relationCheckBodySchema = relationCheckSchema;\n\n/** `POST /api/me/relation`: the caller's own relationship check. */\nexport const meRelationBodySchema = v.object({\n relation: nonEmpty,\n object: v.pipe(v.string(), v.regex(/^[^:#]+:[^#]+$/, 'must be \"type:id\"')),\n});\n\nexport type GrantBody = v.InferOutput<typeof grantBodySchema>;\nexport type SubjectUpdateBody = v.InferOutput<typeof subjectUpdateBodySchema>;\nexport type CheckBody = v.InferOutput<typeof checkBodySchema>;\n","/**\n * The panel's JSON API (ADR 0008): the route table on the kit's declarative router\n * (`@xtandard/kit/server/router`), wired to authentication, authorization, the readonly switch\n * (423) and valibot body validation. Returns `null` for non-API paths so the panel falls through\n * to static assets / the SPA.\n *\n * Every route is one entry of {@link API_ROUTES}: method, path, action, resource and handler. The\n * OpenAPI document is generated from the same table, so the two cannot drift.\n *\n * Two kinds of routes:\n *\n * - **admin** routes carry an action (`catalog:read`, `subjects:read`, `grants:read`,\n * `history:read`, `check:run`, `relationships:read`, and the mutating `grants:write`,\n * `roles:write`, `relationships:write`) and go through the authorization provider;\n * - **runtime** routes (`GET /api/me`, `POST /api/me/check`, `POST /api/me/relation`) answer for\n * the caller and need only an authenticated principal (401 otherwise): the provider is not\n * consulted.\n *\n * The actor of every write is the authenticated principal.\n *\n * @module\n */\n\nimport { parseInput, type Actor } from \"@xtandard/kit/util\";\nimport { intParam, json, mapError as kitMapError, type ErrorMap } from \"@xtandard/kit/server\";\nimport {\n createRouter,\n type Call as KitCall,\n type Route,\n type RouteMethod as KitRouteMethod,\n type RouteQueryParam as KitRouteQueryParam,\n type RouteSpec as KitRouteSpec,\n type Router,\n} from \"@xtandard/kit/server/router\";\nimport type { AuthProvider, Principal } from \"../auth/contract.ts\";\nimport {\n ALL_ACTIONS,\n isMutatingAction,\n type AuthorizationProvider,\n type PermissionsAction,\n type PermissionsResource,\n} from \"../authorization/contract.ts\";\nimport { principalIdentity } from \"../authorization/permissions.ts\";\nimport type { AnyPermissionsCatalog, SubjectIdentity } from \"../catalog.ts\";\nimport type { AnyPermissions, SubjectSummary, SubjectView } from \"../engine.ts\";\nimport { UnknownRoleError } from \"../errors.ts\";\nimport { relationSchemaView, type RelationTypeView } from \"../relationships.ts\";\nimport type { CheckResult, RoleSource, RoleSourceMode } from \"../schema.ts\";\nimport {\n checkBodySchema,\n grantBodySchema,\n meCheckBodySchema,\n meRelationBodySchema,\n relationCheckBodySchema,\n relationshipBodySchema,\n revokeBodySchema,\n subjectUpdateBodySchema,\n} from \"./validation.ts\";\n\n/** Everything the API router needs. */\nexport interface ApiContext {\n engine: AnyPermissions;\n auth: AuthProvider;\n authorization: AuthorizationProvider;\n title: string;\n readonly: boolean;\n basePath: string;\n logoUrl?: string;\n /** The document served at `/api/openapi.json`. */\n openapi?: () => Record<string, unknown>;\n /**\n * The rules' `ctx` for the caller's runtime checks (`/api/me/check`), for catalogs whose rules\n * read app facts. The caller can't supply `ctx` on that route.\n */\n checkContext?: (request: Request, subject: SubjectIdentity) => unknown;\n /**\n * The ReBAC subject of the caller for `POST /api/me/relation`. Default `user:{principal id}`.\n */\n relationSubject?: (principal: Principal) => string;\n}\n\n/** `GET /config` (and `/api/config`): the SPA bootstrap. */\nexport interface PanelConfig {\n title: string;\n logoUrl?: string;\n basePath: string;\n readonly: boolean;\n /** Who owns roles (ADR 0014): `\"external\"` hides role changes (the auth provider owns them). */\n roleSource: RoleSourceMode;\n authenticated: boolean;\n /**\n * The caller, with its effective catalog role and the source that decided it; `null` when not\n * authenticated.\n */\n principal: {\n id: string;\n role: string;\n roleSource?: RoleSource;\n name?: string;\n email?: string;\n } | null;\n /**\n * The ADR 0008 actions the caller may perform. Mutating actions are left out of a readonly\n * panel, so the SPA can hide write UI from this list alone.\n */\n allowed: PermissionsAction[];\n}\n\n/** A role or permission with its label. */\nexport interface LabeledKey {\n key: string;\n label: string;\n description?: string;\n}\n\n/** `GET /api/catalog`. */\nexport interface CatalogView {\n /** Least → most privileged. */\n roles: LabeledKey[];\n assignable: LabeledKey[];\n guestRole: string;\n defaultRole: string;\n managerRoles: string[];\n directGrants: boolean;\n /** Who owns roles: `\"stored\"` (role changes allowed) or `\"external\"` (the auth provider's). */\n roleSource: RoleSourceMode;\n /** Every leaf permix path of every role's rules tree, sorted (for the playground). */\n paths: string[];\n /** The relation schema (ReBAC), `null` when the catalog declares none. */\n relations: RelationTypeView[] | null;\n}\n\n/** `GET /api/subjects`. */\nexport interface SubjectList {\n subjects: SubjectSummary[];\n}\n\n/** `GET /api/subjects/:id`: the stored view plus the effective role and active permissions. */\nexport interface SubjectDetail extends SubjectView {\n /**\n * The role checks use: the stored role (`roleSource: \"stored\"` mode only), else the auth\n * provider's (`lookupSubject`), else the catalog's `defaultRole`; `roleSource` says which.\n */\n effectiveRole: string;\n /** The non-expired, assignable granted permissions. */\n permissions: string[];\n}\n\n/** Route tags (OpenAPI grouping). */\nexport type RouteTag =\n | \"panel\"\n | \"catalog\"\n | \"subjects\"\n | \"grants\"\n | \"history\"\n | \"check\"\n | \"relationships\"\n | \"runtime\";\n\n/** HTTP methods the router serves. */\nexport type RouteMethod = KitRouteMethod;\n\n/** A query parameter a route documents. */\nexport type RouteQueryParam = KitRouteQueryParam;\n\n/** The documented shape of one route (consumed by the OpenAPI builder). */\nexport type RouteSpec = KitRouteSpec<PermissionsAction, RouteTag> & {\n /** Runtime route: needs an authenticated principal, no action. */\n runtime?: boolean;\n};\n\ntype Call = KitCall<ApiContext>;\ntype ApiRoute = Route<PermissionsAction, PermissionsResource, ApiContext, never, RouteTag> & {\n runtime?: boolean;\n};\n\n// ─── Helpers ────────────────────────────────────────────────────────────────────────────────\n\n/** The actor of a write: the authenticated principal. */\nfunction actorOf(c: Call): Actor | null {\n const p = c.principal;\n if (!p) return null;\n return {\n id: p.id,\n type: \"user\",\n ...(p.name !== undefined ? { name: p.name } : {}),\n ...(p.email !== undefined ? { email: p.email } : {}),\n };\n}\n\nconst labeled = (key: string, label: { label: string; description?: string }): LabeledKey => ({\n key,\n label: label.label,\n ...(label.description !== undefined ? { description: label.description } : {}),\n});\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst pathsCache = new WeakMap<object, string[]>();\n\n/**\n * Every leaf path of every role's rules tree. The trees are built (never evaluated) with a\n * placeholder subject and no grants; a role whose rules can't be built that way is skipped.\n */\nexport function catalogPaths(catalog: AnyPermissionsCatalog): string[] {\n const cached = pathsCache.get(catalog);\n if (cached) return cached;\n const paths = new Set<string>();\n const walk = (node: unknown, prefix: string) => {\n if (!isRecord(node)) {\n if (prefix && (typeof node === \"boolean\" || typeof node === \"function\")) paths.add(prefix);\n return;\n }\n for (const key of Object.keys(node)) walk(node[key], prefix ? `${prefix}.${key}` : key);\n };\n const createRules = catalog.authorization.createRules as (\n user: unknown,\n facts: { permissions: string[] },\n ) => unknown;\n for (const role of catalog.roles as readonly string[]) {\n const user = role === catalog.guestRole ? undefined : { id: \"\", role };\n try {\n walk(createRules(user, { permissions: [] }), \"\");\n } catch {\n // The role's rules need a real subject or ctx: its paths are not listed.\n }\n }\n const out = [...paths].sort();\n pathsCache.set(catalog, out);\n return out;\n}\n\n/** The catalog view served at `/api/catalog` (`roleSource`: the engine's, default `\"stored\"`). */\nexport function catalogView(\n catalog: AnyPermissionsCatalog,\n roleSource: RoleSourceMode = \"stored\",\n): CatalogView {\n const roles = catalog.roles as readonly string[];\n const assignable = catalog.assignable as readonly string[];\n const labels = catalog.labels as {\n roles: Record<string, { label: string; description?: string }>;\n permissions: Record<string, { label: string; description?: string }>;\n };\n return {\n roles: roles.map((role) => labeled(role, labels.roles[role] ?? { label: role })),\n assignable: assignable.map((p) => labeled(p, labels.permissions[p] ?? { label: p })),\n guestRole: catalog.guestRole,\n defaultRole: catalog.defaultRole,\n managerRoles: [...(catalog.managerRoles as readonly string[])],\n directGrants: catalog.directGrants,\n roleSource,\n paths: catalogPaths(catalog),\n relations: catalog.relations ? relationSchemaView(catalog.relations) : null,\n };\n}\n\n/** A check result as JSON: `explanation.error` (a thrown value) becomes its message. */\nexport function serializeCheck(result: CheckResult): CheckResult {\n const error = result.explanation.error;\n if (error === undefined) return result;\n const message =\n error instanceof Error ? error.message || error.name : typeof error === \"string\" ? error : \"\";\n return {\n ...result,\n explanation: { ...result.explanation, error: message || String(error) },\n };\n}\n\n/** The subject detail served at `/api/subjects/:id`. */\nasync function subjectDetail(engine: AnyPermissions, id: string): Promise<SubjectDetail> {\n const [view, snapshot] = await Promise.all([engine.getSubject(id), engine.snapshot(id)]);\n return { ...(view as SubjectView), permissions: snapshot.permissions };\n}\n\n/** The resource every action is evaluated on for the bootstrap's `allowed` list. */\nconst COLLECTION: Record<PermissionsAction, PermissionsResource> = {\n \"catalog:read\": { type: \"catalog\" },\n \"subjects:read\": { type: \"subject\" },\n \"grants:read\": { type: \"grant\" },\n \"history:read\": { type: \"history\" },\n \"check:run\": { type: \"check\" },\n \"relationships:read\": { type: \"relationship\" },\n \"grants:write\": { type: \"grant\" },\n \"roles:write\": { type: \"subject\" },\n \"relationships:write\": { type: \"relationship\" },\n};\n\nasync function panelConfig(c: Call): Promise<PanelConfig> {\n const { ctx, principal, request } = c;\n let who: PanelConfig[\"principal\"] = null;\n const allowed: PermissionsAction[] = [];\n if (principal) {\n const identity = principalIdentity(principal);\n const snapshot = await ctx.engine.snapshot(identity);\n who = {\n id: principal.id,\n role: snapshot.subject.role,\n ...(snapshot.subject.roleSource !== undefined\n ? { roleSource: snapshot.subject.roleSource }\n : {}),\n ...(identity.name !== undefined ? { name: identity.name } : {}),\n ...(identity.email !== undefined ? { email: identity.email } : {}),\n };\n const decisions = await Promise.all(\n ALL_ACTIONS.map((action) =>\n ctx.readonly && isMutatingAction(action)\n ? false\n : ctx.authorization.authorize({\n principal,\n action,\n resource: COLLECTION[action],\n request,\n }),\n ),\n );\n ALL_ACTIONS.forEach((action, i) => decisions[i] && allowed.push(action));\n }\n return {\n title: ctx.title,\n ...(ctx.logoUrl !== undefined ? { logoUrl: ctx.logoUrl } : {}),\n basePath: ctx.basePath,\n readonly: ctx.readonly,\n roleSource: ctx.engine.roleSource,\n authenticated: principal !== null,\n principal: who,\n allowed,\n };\n}\n\nconst NO_PRINCIPAL = () =>\n json({ error: \"Unauthorized: no authenticated subject\", code: \"NO_SUBJECT\" }, 401);\n\n/** The caller as a subject (runtime routes). */\nfunction callerOf(principal: Principal): SubjectIdentity {\n return principalIdentity(principal);\n}\n\nconst subjectRes = (c: Call): PermissionsResource => ({ type: \"subject\", subject: c.params.id! });\n\nconst truthy = (value: string | null): boolean => value === \"true\" || value === \"1\";\n\n/** The caller's ReBAC subject (`POST /api/me/relation`). */\nconst relationSubjectOf = (c: Call, principal: Principal): string =>\n c.ctx.relationSubject?.(principal) ?? `user:${principal.id}`;\n\n/** `?name=` or `undefined` when absent / empty. */\nconst queryOf = (c: Call, name: string): string | undefined => c.query.get(name) || undefined;\n\n/** The relationship a request names: the JSON body, or `?object=&relation=&subject=` (DELETE). */\nasync function relationshipOf(c: Call) {\n if (queryOf(c, \"object\") === undefined) return c.body(relationshipBodySchema);\n const fromQuery: Record<string, string> = {};\n for (const name of [\"object\", \"relation\", \"subject\", \"reason\"]) {\n const value = queryOf(c, name);\n if (value !== undefined) fromQuery[name] = value;\n }\n return parseInput(relationshipBodySchema, fromQuery);\n}\n\n/** A role-only playground check runs as this placeholder (no record, no grants). */\nconst ROLE_PREVIEW_ID = \"\\u0000role-preview\";\n\n// ─── Routes ─────────────────────────────────────────────────────────────────────────────────\n\nconst ROUTES: ApiRoute[] = [\n // --- Public ---------------------------------------------------------------------------------\n {\n method: \"GET\",\n path: \"/healthcheck\",\n operationId: \"healthcheck\",\n summary: \"Liveness probe\",\n tag: \"panel\",\n response: { status: 200, schema: \"Health\", description: \"Alive\" },\n handle: () => json({ ok: true }),\n },\n {\n method: \"GET\",\n path: \"/api/openapi.json\",\n operationId: \"getOpenApi\",\n summary: \"This OpenAPI 3.1 document\",\n tag: \"panel\",\n response: { status: 200, schema: { type: \"object\" }, description: \"OpenAPI 3.1\" },\n handle: (c) => json(c.ctx.openapi?.() ?? {}),\n },\n\n // --- Admin: catalog -------------------------------------------------------------------------\n {\n method: \"GET\",\n path: \"/api/catalog\",\n operationId: \"getCatalog\",\n summary: \"The catalog: roles, assignable permissions, labels and every rule path\",\n tag: \"catalog\",\n action: \"catalog:read\",\n resource: () => ({ type: \"catalog\" }),\n response: { status: 200, schema: \"CatalogView\", description: \"Catalog\" },\n handle: (c) => json(catalogView(c.ctx.engine.catalog, c.ctx.engine.roleSource)),\n },\n\n // --- Admin: subjects ------------------------------------------------------------------------\n {\n method: \"GET\",\n path: \"/api/subjects\",\n operationId: \"listSubjects\",\n summary: \"Every subject with a record or a grant, sorted by id\",\n tag: \"subjects\",\n action: \"subjects:read\",\n query: [{ name: \"search\", type: \"string\", description: \"Substring of id, name or email.\" }],\n resource: () => ({ type: \"subject\" }),\n response: { status: 200, schema: \"SubjectList\", description: \"Subjects\" },\n async handle(c) {\n const search = c.query.get(\"search\")?.trim().toLowerCase() || undefined;\n let subjects = await c.ctx.engine.listSubjects();\n if (search !== undefined) {\n subjects = subjects.filter((s) =>\n [s.id, s.name, s.email].some((f) => f?.toLowerCase().includes(search)),\n );\n }\n return json({ subjects } satisfies SubjectList);\n },\n },\n {\n method: \"GET\",\n path: \"/api/subjects/:id\",\n operationId: \"getSubject\",\n summary: \"A subject's record, grants, effective role and active permissions\",\n tag: \"subjects\",\n action: \"subjects:read\",\n query: [\n {\n name: \"includeExpired\",\n type: \"string\",\n description: \"`true` to include expired grants.\",\n },\n ],\n resource: subjectRes,\n response: { status: 200, schema: \"SubjectDetail\", description: \"Subject\" },\n async handle(c) {\n const id = c.params.id!;\n const detail = await subjectDetail(c.ctx.engine, id);\n if (truthy(c.query.get(\"includeExpired\"))) {\n detail.grants = (await c.ctx.engine.getSubject(id, { includeExpired: true })).grants;\n }\n return json(detail);\n },\n },\n {\n method: \"PUT\",\n path: \"/api/subjects/:id\",\n operationId: \"updateSubject\",\n summary: \"Assign or clear a stored role; set or clear the display name / email\",\n description:\n '`role: null` clears the stored assignment (the auth provider\\'s role, or `defaultRole`, applies again). A field left out is kept. The role change is recorded in the history with the principal as actor. With `roleSource: \"external\"` a `role` is refused (409 `ROLES_EXTERNAL`); name / email updates still work.',\n tag: \"subjects\",\n action: \"roles:write\",\n resource: subjectRes,\n body: \"SubjectUpdate\",\n response: { status: 200, schema: \"SubjectDetail\", description: \"The updated subject\" },\n async handle(c) {\n const id = c.params.id!;\n const body = await c.body(subjectUpdateBodySchema);\n const { engine } = c.ctx;\n if (body.role !== undefined) {\n if (body.role !== null && !engine.catalog.isRole(body.role)) {\n throw new UnknownRoleError(body.role);\n }\n await engine.setRole({\n subject: id,\n role: body.role,\n actor: actorOf(c),\n ...(body.reason !== undefined ? { reason: body.reason } : {}),\n });\n }\n if (body.name !== undefined || body.email !== undefined) {\n await engine.upsertSubject({\n id,\n ...(body.name !== undefined ? { name: body.name } : {}),\n ...(body.email !== undefined ? { email: body.email } : {}),\n });\n }\n return json(await subjectDetail(engine, id));\n },\n },\n\n // --- Admin: grants --------------------------------------------------------------------------\n {\n method: \"GET\",\n path: \"/api/grants\",\n operationId: \"listGrants\",\n summary: \"Grants by subject, by permission, both, or all (sorted by subject, permission)\",\n tag: \"grants\",\n action: \"grants:read\",\n query: [\n { name: \"subject\", type: \"string\", description: \"One subject's grants.\" },\n { name: \"permission\", type: \"string\", description: \"One permission's grants.\" },\n { name: \"includeExpired\", type: \"string\", description: \"`true` to include expired.\" },\n ],\n resource: (c) => ({\n type: \"grant\",\n ...(c.query.get(\"subject\") ? { subject: c.query.get(\"subject\")! } : {}),\n ...(c.query.get(\"permission\") ? { permission: c.query.get(\"permission\")! } : {}),\n }),\n response: { status: 200, schema: \"GrantList\", description: \"Grants\" },\n async handle(c) {\n const subject = c.query.get(\"subject\") || undefined;\n const permission = c.query.get(\"permission\") || undefined;\n const grants = await c.ctx.engine.list({\n ...(subject !== undefined ? { subject } : {}),\n ...(permission !== undefined ? { permission } : {}),\n ...(truthy(c.query.get(\"includeExpired\")) ? { includeExpired: true } : {}),\n });\n return json({ grants });\n },\n },\n {\n method: \"POST\",\n path: \"/api/grants\",\n operationId: \"grant\",\n summary: \"Grant a permission (idempotent: 201 when created, 200 when it already existed)\",\n tag: \"grants\",\n action: \"grants:write\",\n async resource(c) {\n const { subject, permission } = await c.body(grantBodySchema);\n return { type: \"grant\", subject, permission };\n },\n body: \"GrantInput\",\n response: { status: 201, schema: \"GrantResult\", description: \"Granted\" },\n async handle(c) {\n const body = await c.body(grantBodySchema);\n const result = await c.ctx.engine.grant({ ...body, actor: actorOf(c) });\n return json(result, result.created ? 201 : 200);\n },\n },\n {\n method: \"DELETE\",\n path: \"/api/grants/:subject/:permission\",\n operationId: \"revoke\",\n summary: \"Revoke a permission (idempotent: `removed: false` when absent)\",\n description: \"The reason is read from the JSON body `{ reason }` or the `?reason=` query.\",\n tag: \"grants\",\n action: \"grants:write\",\n query: [{ name: \"reason\", type: \"string\", description: \"Why (when there is no body).\" }],\n resource: (c) => ({\n type: \"grant\",\n subject: c.params.subject!,\n permission: c.params.permission!,\n }),\n body: \"RevokeInput\",\n bodyRequired: false,\n response: { status: 200, schema: \"RevokeResult\", description: \"Revoked (or nothing to do)\" },\n async handle(c) {\n const body = await c.body(revokeBodySchema);\n const reason = body.reason ?? (c.query.get(\"reason\") || undefined);\n return json(\n await c.ctx.engine.revoke({\n subject: c.params.subject!,\n permission: c.params.permission!,\n actor: actorOf(c),\n ...(reason !== undefined ? { reason } : {}),\n }),\n );\n },\n },\n\n // --- Admin: history -------------------------------------------------------------------------\n {\n method: \"GET\",\n path: \"/api/history\",\n operationId: \"history\",\n summary: \"Grant / revoke / role history, newest first (cursor pagination)\",\n tag: \"history\",\n action: \"history:read\",\n query: [\n { name: \"subject\", type: \"string\", description: \"One subject's history.\" },\n { name: \"limit\", type: \"integer\", description: \"Page size, 1–1000 (default 50).\" },\n { name: \"cursor\", type: \"string\", description: \"The previous page's `nextCursor`.\" },\n ],\n resource: (c) => ({\n type: \"history\",\n ...(c.query.get(\"subject\") ? { subject: c.query.get(\"subject\")! } : {}),\n }),\n response: { status: 200, schema: \"HistoryPage\", description: \"A page of history\" },\n async handle(c) {\n const subject = c.query.get(\"subject\") || undefined;\n const cursor = c.query.get(\"cursor\") || undefined;\n const limit = intParam(c.query.get(\"limit\"), { name: \"limit\" });\n return json(\n await c.ctx.engine.history({\n ...(subject !== undefined ? { subject } : {}),\n ...(limit !== undefined ? { limit } : {}),\n ...(cursor !== undefined ? { cursor } : {}),\n }),\n );\n },\n },\n\n // --- Admin: check playground ----------------------------------------------------------------\n {\n method: \"POST\",\n path: \"/api/check\",\n operationId: \"check\",\n summary: \"Check playground: decide a path for a subject, a role, or a guest, with reasons\",\n description:\n \"`subject` checks a subject (its grants, and its stored role or the provider's from `lookupSubject`). `role` alone checks the role with no subject and no grants (`subject: null` in the result). Both: `role` is the provider's role (a stored role still wins unless `roleSource` is `external`). Neither: a guest. A denial is `200` with `allowed: false`.\",\n tag: \"check\",\n action: \"check:run\",\n async resource(c) {\n const body = await c.body(checkBodySchema);\n return {\n type: \"check\",\n subject: body.subject ?? null,\n ...(body.role !== undefined ? { role: body.role } : {}),\n path: body.path,\n };\n },\n body: \"CheckInput\",\n response: { status: 200, schema: \"CheckResult\", description: \"The decision\" },\n async handle(c) {\n const body = await c.body(checkBodySchema);\n const { engine } = c.ctx;\n const catalog = engine.catalog;\n if (body.role !== undefined && !catalog.isRole(body.role)) {\n throw new UnknownRoleError(body.role);\n }\n let subject: SubjectIdentity | null = null;\n let preview = false;\n if (body.subject) {\n subject = { id: body.subject, ...(body.role !== undefined ? { role: body.role } : {}) };\n } else if (body.role !== undefined && body.role !== catalog.guestRole) {\n subject = { id: ROLE_PREVIEW_ID, role: body.role };\n preview = true;\n }\n const facts = body.ctx !== undefined ? [{ ctx: body.ctx }] : [];\n const ability = await engine.ability(subject, ...(facts as []));\n const result = (await ability.checkAsync(body.path, body.data)) as CheckResult;\n return json(serializeCheck(preview ? { ...result, subject: null } : result));\n },\n },\n\n // --- Admin: relationships (ReBAC, ADR 0013) -------------------------------------------------\n {\n method: \"GET\",\n path: \"/api/relationships\",\n operationId: \"readRelationships\",\n summary: \"Stored relationships by object (or type), relation and/or subject (paginated)\",\n tag: \"relationships\",\n action: \"relationships:read\",\n query: [\n { name: \"object\", type: \"string\", description: \"`type:id`, or a bare `type`.\" },\n { name: \"relation\", type: \"string\", description: \"One relation.\" },\n { name: \"subject\", type: \"string\", description: \"Exactly this subject reference.\" },\n { name: \"limit\", type: \"integer\", description: \"Page size, 1–1000 (default 100).\" },\n { name: \"cursor\", type: \"string\", description: \"The previous page's `nextCursor`.\" },\n ],\n resource: (c) => ({\n type: \"relationship\",\n ...(queryOf(c, \"object\") ? { object: queryOf(c, \"object\")! } : {}),\n ...(queryOf(c, \"relation\") ? { relation: queryOf(c, \"relation\")! } : {}),\n ...(queryOf(c, \"subject\") ? { subject: queryOf(c, \"subject\")! } : {}),\n }),\n response: { status: 200, schema: \"RelationshipPage\", description: \"A page of relationships\" },\n async handle(c) {\n const limit = intParam(c.query.get(\"limit\"), { name: \"limit\" });\n const query: Record<string, unknown> = {};\n for (const name of [\"object\", \"relation\", \"subject\", \"cursor\"]) {\n const value = queryOf(c, name);\n if (value !== undefined) query[name] = value;\n }\n if (limit !== undefined) query.limit = limit;\n return json(await c.ctx.engine.readRelationships(query));\n },\n },\n {\n method: \"POST\",\n path: \"/api/relationships\",\n operationId: \"writeRelationship\",\n summary: \"Write a relationship (idempotent: 201 when created, 200 when it already existed)\",\n description:\n \"Validated against the catalog's relation schema (400 `INVALID_RELATION` when the schema doesn't allow the subject on that relation).\",\n tag: \"relationships\",\n action: \"relationships:write\",\n async resource(c) {\n const { object, relation, subject } = await c.body(relationshipBodySchema);\n return { type: \"relationship\", object, relation, subject };\n },\n body: \"RelationshipInput\",\n response: { status: 201, schema: \"WriteRelationshipResult\", description: \"Written\" },\n async handle(c) {\n const body = await c.body(relationshipBodySchema);\n const result = await c.ctx.engine.writeRelationship({ ...body, actor: actorOf(c) });\n return json(result, result.created ? 201 : 200);\n },\n },\n {\n method: \"DELETE\",\n path: \"/api/relationships\",\n operationId: \"deleteRelationship\",\n summary: \"Delete a relationship (idempotent: `removed: false` when absent)\",\n description:\n \"The tuple comes from the JSON body `{ object, relation, subject, reason? }` or the `?object=&relation=&subject=&reason=` query.\",\n tag: \"relationships\",\n action: \"relationships:write\",\n query: [\n { name: \"object\", type: \"string\", description: \"When there is no body.\" },\n { name: \"relation\", type: \"string\", description: \"When there is no body.\" },\n { name: \"subject\", type: \"string\", description: \"When there is no body.\" },\n { name: \"reason\", type: \"string\", description: \"When there is no body.\" },\n ],\n async resource(c) {\n const { object, relation, subject } = await relationshipOf(c);\n return { type: \"relationship\", object, relation, subject };\n },\n body: \"RelationshipInput\",\n bodyRequired: false,\n response: {\n status: 200,\n schema: \"DeleteRelationshipResult\",\n description: \"Deleted (or nothing to do)\",\n },\n async handle(c) {\n const tuple = await relationshipOf(c);\n return json(await c.ctx.engine.deleteRelationship({ ...tuple, actor: actorOf(c) }));\n },\n },\n {\n method: \"POST\",\n path: \"/api/relationships/check\",\n operationId: \"checkRelation\",\n summary:\n \"Does a subject have a relation on an object? With the path of relations that decided it\",\n description: \"A denial is `200` with `allowed: false` and an empty `path`.\",\n tag: \"relationships\",\n action: \"relationships:read\",\n async resource(c) {\n const { object, relation, subject } = await c.body(relationCheckBodySchema);\n return { type: \"relationship\", object, relation, subject };\n },\n body: \"RelationCheckInput\",\n response: { status: 200, schema: \"RelationCheckResult\", description: \"The decision\" },\n async handle(c) {\n return json(\n await c.ctx.engine.checkRelation((await c.body(relationCheckBodySchema)) as never),\n );\n },\n },\n {\n method: \"GET\",\n path: \"/api/relationships/objects\",\n operationId: \"listObjects\",\n summary: \"The objects of a type on which a subject has a relation\",\n description:\n \"A walk backwards over the reverse index, bounded by `maxDepth`; fine for app-scale data (see docs/REBAC.md).\",\n tag: \"relationships\",\n action: \"relationships:read\",\n query: [\n {\n name: \"subject\",\n type: \"string\",\n description: \"`user:ana`, `group:eng#member`.\",\n required: true,\n },\n { name: \"relation\", type: \"string\", description: \"A relation of `type`.\", required: true },\n { name: \"type\", type: \"string\", description: \"The object type.\", required: true },\n ],\n resource: (c) => ({\n type: \"relationship\",\n ...(queryOf(c, \"subject\") ? { subject: queryOf(c, \"subject\")! } : {}),\n ...(queryOf(c, \"relation\") ? { relation: queryOf(c, \"relation\")! } : {}),\n }),\n response: { status: 200, schema: \"ObjectList\", description: \"Objects, sorted\" },\n async handle(c) {\n const objects = await c.ctx.engine.listObjects({\n subject: c.query.get(\"subject\") ?? \"\",\n relation: c.query.get(\"relation\") ?? \"\",\n type: c.query.get(\"type\") ?? \"\",\n } as never);\n return json({ objects });\n },\n },\n {\n method: \"GET\",\n path: \"/api/relationships/subjects\",\n operationId: \"listRelationSubjects\",\n summary: \"The subjects that have a relation on an object (usersets expanded)\",\n tag: \"relationships\",\n action: \"relationships:read\",\n query: [\n { name: \"object\", type: \"string\", description: \"`type:id`.\", required: true },\n {\n name: \"relation\",\n type: \"string\",\n description: \"A relation of the object's type.\",\n required: true,\n },\n { name: \"type\", type: \"string\", description: \"Only subjects of this type.\" },\n ],\n resource: (c) => ({\n type: \"relationship\",\n ...(queryOf(c, \"object\") ? { object: queryOf(c, \"object\")! } : {}),\n ...(queryOf(c, \"relation\") ? { relation: queryOf(c, \"relation\")! } : {}),\n }),\n response: { status: 200, schema: \"SubjectRefList\", description: \"Subjects, sorted\" },\n async handle(c) {\n const type = queryOf(c, \"type\");\n const subjects = await c.ctx.engine.listRelationSubjects({\n object: c.query.get(\"object\") ?? \"\",\n relation: c.query.get(\"relation\") ?? \"\",\n ...(type !== undefined ? { type } : {}),\n } as never);\n return json({ subjects });\n },\n },\n\n // --- Runtime: the caller --------------------------------------------------------------------\n {\n method: \"GET\",\n path: \"/api/me\",\n operationId: \"me\",\n summary: \"The caller's snapshot: id, effective role and active permissions (ADR 0009)\",\n tag: \"runtime\",\n authenticate: true,\n runtime: true,\n response: { status: 200, schema: \"PermissionsSnapshot\", description: \"Snapshot\" },\n async handle(c) {\n if (!c.principal) return NO_PRINCIPAL();\n return json(await c.ctx.engine.snapshot(callerOf(c.principal)));\n },\n },\n {\n method: \"POST\",\n path: \"/api/me/check\",\n operationId: \"meCheck\",\n summary: \"Decide a path for the caller, with reasons\",\n description:\n \"Advisory (for UI gating): `data` comes from the caller. Enforce on the server with the engine. The rules' `ctx` comes from the server's `checkContext` option, never from the body.\",\n tag: \"runtime\",\n authenticate: true,\n runtime: true,\n body: \"MeCheckInput\",\n response: { status: 200, schema: \"CheckResult\", description: \"The decision\" },\n async handle(c) {\n if (!c.principal) return NO_PRINCIPAL();\n const body = await c.body(meCheckBodySchema);\n const subject = callerOf(c.principal);\n const facts = c.ctx.checkContext\n ? [{ ctx: await c.ctx.checkContext(c.request, subject) }]\n : [];\n const ability = await c.ctx.engine.ability(subject, ...(facts as []));\n return json(serializeCheck((await ability.checkAsync(body.path, body.data)) as CheckResult));\n },\n },\n {\n method: \"POST\",\n path: \"/api/me/relation\",\n operationId: \"meRelation\",\n summary: \"Does the caller have a relation on an object? (ReBAC, with the path)\",\n description:\n \"The caller is the subject `user:{id}` unless the server's `relationSubject` option maps it. Advisory for UI gating; enforce on the server.\",\n tag: \"runtime\",\n authenticate: true,\n runtime: true,\n body: \"MeRelationInput\",\n response: { status: 200, schema: \"RelationCheckResult\", description: \"The decision\" },\n async handle(c) {\n if (!c.principal) return NO_PRINCIPAL();\n const body = await c.body(meRelationBodySchema);\n return json(\n await c.ctx.engine.checkRelation({\n subject: relationSubjectOf(c, c.principal),\n relation: body.relation,\n object: body.object,\n } as never),\n );\n },\n },\n];\n\n/** The documented route table (every API route, in match order). */\nexport const API_ROUTES: readonly RouteSpec[] = ROUTES;\n\n/** The paths served as the bootstrap config (not in {@link API_ROUTES}). */\nexport const CONFIG_PATHS: readonly string[] = [\"/config\", \"/api/config\"];\n\nconst CONFIG_ROUTES: ApiRoute[] = CONFIG_PATHS.map((path) => ({\n method: \"GET\",\n path,\n operationId: path === \"/config\" ? \"getConfig\" : \"getApiConfig\",\n summary: \"SPA bootstrap config: title, readonly, the caller and the actions it may perform\",\n tag: \"panel\",\n authenticate: true,\n hidden: true,\n response: { status: 200, schema: \"PanelConfig\", description: \"Panel config\" },\n handle: async (c) => json(await panelConfig(c)),\n}));\n\n/** Domain errors by name (ADR 0008); see `@xtandard/kit/server` `mapError`. */\nexport const ERRORS: ErrorMap = {\n NoSubjectError: { status: 401, code: \"NO_SUBJECT\" },\n ForbiddenError: { status: 403, code: \"FORBIDDEN\" },\n UnknownPermissionError: { status: 400, code: \"UNKNOWN_PERMISSION\" },\n UnknownRoleError: { status: 400, code: \"UNKNOWN_ROLE\" },\n NotFoundError: { status: 404, code: \"NOT_FOUND\" },\n ReadonlyError: { status: 423, code: \"READONLY\" },\n ExternalRolesError: { status: 409, code: \"ROLES_EXTERNAL\" },\n AsyncRuleError: { status: 500, code: \"ASYNC_RULE\" },\n RelationSchemaError: { status: 400, code: \"INVALID_RELATION\" },\n RelationDepthError: { status: 422, code: \"RELATION_DEPTH\" },\n};\n\n/** Build the API router for one panel. */\nexport function createApiRouter(\n ctx: ApiContext,\n): Router<PermissionsAction, PermissionsResource, ApiContext, never, RouteTag> {\n return createRouter<PermissionsAction, PermissionsResource, ApiContext, never, RouteTag>({\n routes: [...CONFIG_ROUTES, ...ROUTES],\n context: ctx,\n readonly: ctx.readonly,\n isMutatingAction,\n readonlyStatus: 423,\n readonlyMessage: (route) =>\n `Cannot ${route.operationId}: @xtandard/permissions is in readonly mode.`,\n auth: ctx.auth,\n authorization: ctx.authorization,\n errors: ERRORS,\n });\n}\n\n/** Map domain errors to HTTP responses (ADR 0008), by name across bundles. */\nexport function mapError(err: unknown): Response {\n return kitMapError(err, ERRORS);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAgBA,MAAM,WAAWA,QAAE,KAAKA,QAAE,OAAO,GAAGA,QAAE,UAAU,GAAG,mBAAmB,CAAC;AACvE,MAAM,SAASA,QAAE,KAAKA,QAAE,OAAO,GAAGA,QAAE,UAAU,KAAM,iCAAiC,CAAC;AACtF,MAAM,UAAUA,QAAE,SAASA,QAAE,KAAKA,QAAE,OAAO,GAAGA,QAAE,UAAU,KAAK,gCAAgC,CAAC,CAAC;;AAGjG,MAAa,kBAAkBA,QAAE,KAAKC,sBAAAA,kBAAkB,CAAC,OAAO,CAAC;;AAGjE,MAAa,mBAAmBD,QAAE,KAAKE,sBAAAA,mBAAmB,CAAC,QAAQ,CAAC;;;;;AAMpE,MAAa,0BAA0BF,QAAE,OAAO;CAC9C,MAAMA,QAAE,SAASA,QAAE,SAAS,QAAQ,CAAC;CACrC,MAAMA,QAAE,SAAS,OAAO;CACxB,OAAOA,QAAE,SAAS,OAAO;CACzB,QAAQA,QAAE,SAAS,MAAM;AAC3B,CAAC;;;;;AAMD,MAAa,kBAAkBA,QAAE,OAAO;CACt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AI;EACd,kBAAA,iBAAA;EACA,gBAAgB;EAChB,kBAAkB,UAChB,UAAU,MAAM,YAAY;EAC9B,MAAM,IAAI;EACV,eAAe,IAAI;EACnB,QAAQ;CACV,CAAC;AACH;;AAGA,SAAgB,SAAS,KAAwB;CAC/C,QAAA,GAAA,qBAAA,UAAmB,KAAK,MAAM;AAChC"}
@@ -1,8 +1,8 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
2
  import { A as revokeInputSchema, D as relationCheckSchema, O as relationshipInputSchema, S as grantInputSchema, n as relationSchemaView } from "./relationships-BfLonEMI.mjs";
3
- import { o as UnknownRoleError } from "./errors-bL3XQLfE.mjs";
3
+ import { s as UnknownRoleError } from "./errors-CG_OLEEv.mjs";
4
4
  import { i as isMutatingAction, t as ALL_ACTIONS } from "./contract-DTdTXZtJ.mjs";
5
- import { n as principalIdentity } from "./permissions-C9PjftY6.mjs";
5
+ import { n as principalIdentity } from "./permissions-CeV6M3v7.mjs";
6
6
  import * as v from "valibot";
7
7
  import { parseInput } from "@xtandard/kit/util";
8
8
  import { intParam, json, mapError } from "@xtandard/kit/server";
@@ -138,8 +138,8 @@ function catalogPaths(catalog) {
138
138
  pathsCache.set(catalog, out);
139
139
  return out;
140
140
  }
141
- /** The catalog view served at `/api/catalog`. */
142
- function catalogView(catalog) {
141
+ /** The catalog view served at `/api/catalog` (`roleSource`: the engine's, default `"stored"`). */
142
+ function catalogView(catalog, roleSource = "stored") {
143
143
  const roles = catalog.roles;
144
144
  const assignable = catalog.assignable;
145
145
  const labels = catalog.labels;
@@ -150,6 +150,7 @@ function catalogView(catalog) {
150
150
  defaultRole: catalog.defaultRole,
151
151
  managerRoles: [...catalog.managerRoles],
152
152
  directGrants: catalog.directGrants,
153
+ roleSource,
153
154
  paths: catalogPaths(catalog),
154
155
  relations: catalog.relations ? relationSchemaView(catalog.relations) : null
155
156
  };
@@ -172,7 +173,6 @@ async function subjectDetail(engine, id) {
172
173
  const [view, snapshot] = await Promise.all([engine.getSubject(id), engine.snapshot(id)]);
173
174
  return {
174
175
  ...view,
175
- effectiveRole: snapshot.subject.role,
176
176
  permissions: snapshot.permissions
177
177
  };
178
178
  }
@@ -198,6 +198,7 @@ async function panelConfig(c) {
198
198
  who = {
199
199
  id: principal.id,
200
200
  role: snapshot.subject.role,
201
+ ...snapshot.subject.roleSource !== void 0 ? { roleSource: snapshot.subject.roleSource } : {},
201
202
  ...identity.name !== void 0 ? { name: identity.name } : {},
202
203
  ...identity.email !== void 0 ? { email: identity.email } : {}
203
204
  };
@@ -214,6 +215,7 @@ async function panelConfig(c) {
214
215
  ...ctx.logoUrl !== void 0 ? { logoUrl: ctx.logoUrl } : {},
215
216
  basePath: ctx.basePath,
216
217
  readonly: ctx.readonly,
218
+ roleSource: ctx.engine.roleSource,
217
219
  authenticated: principal !== null,
218
220
  principal: who,
219
221
  allowed
@@ -293,7 +295,7 @@ const ROUTES = [
293
295
  schema: "CatalogView",
294
296
  description: "Catalog"
295
297
  },
296
- handle: (c) => json(catalogView(c.ctx.engine.catalog))
298
+ handle: (c) => json(catalogView(c.ctx.engine.catalog, c.ctx.engine.roleSource))
297
299
  },
298
300
  {
299
301
  method: "GET",
@@ -354,7 +356,7 @@ const ROUTES = [
354
356
  path: "/api/subjects/:id",
355
357
  operationId: "updateSubject",
356
358
  summary: "Assign or clear a stored role; set or clear the display name / email",
357
- description: "`role: null` clears the stored assignment (the auth provider's role, or `defaultRole`, applies again). A field left out is kept. The role change is recorded in the history with the principal as actor.",
359
+ description: "`role: null` clears the stored assignment (the auth provider's role, or `defaultRole`, applies again). A field left out is kept. The role change is recorded in the history with the principal as actor. With `roleSource: \"external\"` a `role` is refused (409 `ROLES_EXTERNAL`); name / email updates still work.",
358
360
  tag: "subjects",
359
361
  action: "roles:write",
360
362
  resource: subjectRes,
@@ -543,7 +545,7 @@ const ROUTES = [
543
545
  path: "/api/check",
544
546
  operationId: "check",
545
547
  summary: "Check playground: decide a path for a subject, a role, or a guest, with reasons",
546
- description: "`subject` checks a stored subject (its stored role and grants). `role` alone checks the role with no subject and no grants (`subject: null` in the result). Both: `role` is the provider's role (a stored role still wins). Neither: a guest. A denial is `200` with `allowed: false`.",
548
+ description: "`subject` checks a subject (its grants, and its stored role or the provider's from `lookupSubject`). `role` alone checks the role with no subject and no grants (`subject: null` in the result). Both: `role` is the provider's role (a stored role still wins unless `roleSource` is `external`). Neither: a guest. A denial is `200` with `allowed: false`.",
547
549
  tag: "check",
548
550
  action: "check:run",
549
551
  async resource(c) {
@@ -964,6 +966,10 @@ const ERRORS = {
964
966
  status: 423,
965
967
  code: "READONLY"
966
968
  },
969
+ ExternalRolesError: {
970
+ status: 409,
971
+ code: "ROLES_EXTERNAL"
972
+ },
967
973
  AsyncRuleError: {
968
974
  status: 500,
969
975
  code: "ASYNC_RULE"
@@ -998,4 +1004,4 @@ function mapError$1(err) {
998
1004
  //#endregion
999
1005
  export { createApiRouter as a, serializeCheck as c, catalogView as i, CONFIG_PATHS as n, mapError$1 as o, catalogPaths as r, routes_exports as s, API_ROUTES as t };
1000
1006
 
1001
- //# sourceMappingURL=routes-DtRb3EO0.mjs.map
1007
+ //# sourceMappingURL=routes-Cx-kl4PY.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes-Cx-kl4PY.mjs","names":["mapError","kitMapError"],"sources":["../src/server/validation.ts","../src/server/routes.ts"],"sourcesContent":["/**\n * Valibot schemas of the HTTP request bodies (docs: the OpenAPI component schemas of the same\n * names). Unknown keys are dropped: the actor of every write is the authenticated principal, never\n * a body field. The engine validates the domain (assignable permission, known role, future expiry).\n *\n * @module\n */\n\nimport * as v from \"valibot\";\nimport {\n grantInputSchema,\n relationCheckSchema,\n relationshipInputSchema,\n revokeInputSchema,\n} from \"../schema.ts\";\n\nconst nonEmpty = v.pipe(v.string(), v.minLength(1, \"must not be empty\"));\nconst reason = v.pipe(v.string(), v.maxLength(1000, \"must be at most 1000 characters\"));\nconst display = v.nullable(v.pipe(v.string(), v.maxLength(500, \"must be at most 500 characters\")));\n\n/** `POST /api/grants`: `{ subject, permission, reason?, expiresAt? }`. */\nexport const grantBodySchema = v.omit(grantInputSchema, [\"actor\"]);\n\n/** `DELETE /api/grants/:subject/:permission`: optional `{ reason }`. */\nexport const revokeBodySchema = v.pick(revokeInputSchema, [\"reason\"]);\n\n/**\n * `PUT /api/subjects/:id`: any of `role` (`null` clears the stored assignment), `name`, `email`\n * (`null` clears), plus the `reason` recorded with a role change.\n */\nexport const subjectUpdateBodySchema = v.object({\n role: v.optional(v.nullable(nonEmpty)),\n name: v.optional(display),\n email: v.optional(display),\n reason: v.optional(reason),\n});\n\n/**\n * `POST /api/check` (playground): a stored subject, a bare role (no subject, no grants), both (the\n * role is the provider's, a stored role still wins) or neither (a guest).\n */\nexport const checkBodySchema = v.object({\n subject: v.optional(v.nullable(nonEmpty)),\n role: v.optional(nonEmpty),\n path: nonEmpty,\n data: v.optional(v.unknown()),\n ctx: v.optional(v.unknown()),\n});\n\n/** `POST /api/me/check`: the caller's own check. */\nexport const meCheckBodySchema = v.object({\n path: nonEmpty,\n data: v.optional(v.unknown()),\n});\n\n/** `POST /api/relationships` and `DELETE /api/relationships`: `{ object, relation, subject, reason? }`. */\nexport const relationshipBodySchema = v.omit(relationshipInputSchema, [\"actor\"]);\n\n/** `POST /api/relationships/check`: `{ subject, relation, object }`. */\nexport const relationCheckBodySchema = relationCheckSchema;\n\n/** `POST /api/me/relation`: the caller's own relationship check. */\nexport const meRelationBodySchema = v.object({\n relation: nonEmpty,\n object: v.pipe(v.string(), v.regex(/^[^:#]+:[^#]+$/, 'must be \"type:id\"')),\n});\n\nexport type GrantBody = v.InferOutput<typeof grantBodySchema>;\nexport type SubjectUpdateBody = v.InferOutput<typeof subjectUpdateBodySchema>;\nexport type CheckBody = v.InferOutput<typeof checkBodySchema>;\n","/**\n * The panel's JSON API (ADR 0008): the route table on the kit's declarative router\n * (`@xtandard/kit/server/router`), wired to authentication, authorization, the readonly switch\n * (423) and valibot body validation. Returns `null` for non-API paths so the panel falls through\n * to static assets / the SPA.\n *\n * Every route is one entry of {@link API_ROUTES}: method, path, action, resource and handler. The\n * OpenAPI document is generated from the same table, so the two cannot drift.\n *\n * Two kinds of routes:\n *\n * - **admin** routes carry an action (`catalog:read`, `subjects:read`, `grants:read`,\n * `history:read`, `check:run`, `relationships:read`, and the mutating `grants:write`,\n * `roles:write`, `relationships:write`) and go through the authorization provider;\n * - **runtime** routes (`GET /api/me`, `POST /api/me/check`, `POST /api/me/relation`) answer for\n * the caller and need only an authenticated principal (401 otherwise): the provider is not\n * consulted.\n *\n * The actor of every write is the authenticated principal.\n *\n * @module\n */\n\nimport { parseInput, type Actor } from \"@xtandard/kit/util\";\nimport { intParam, json, mapError as kitMapError, type ErrorMap } from \"@xtandard/kit/server\";\nimport {\n createRouter,\n type Call as KitCall,\n type Route,\n type RouteMethod as KitRouteMethod,\n type RouteQueryParam as KitRouteQueryParam,\n type RouteSpec as KitRouteSpec,\n type Router,\n} from \"@xtandard/kit/server/router\";\nimport type { AuthProvider, Principal } from \"../auth/contract.ts\";\nimport {\n ALL_ACTIONS,\n isMutatingAction,\n type AuthorizationProvider,\n type PermissionsAction,\n type PermissionsResource,\n} from \"../authorization/contract.ts\";\nimport { principalIdentity } from \"../authorization/permissions.ts\";\nimport type { AnyPermissionsCatalog, SubjectIdentity } from \"../catalog.ts\";\nimport type { AnyPermissions, SubjectSummary, SubjectView } from \"../engine.ts\";\nimport { UnknownRoleError } from \"../errors.ts\";\nimport { relationSchemaView, type RelationTypeView } from \"../relationships.ts\";\nimport type { CheckResult, RoleSource, RoleSourceMode } from \"../schema.ts\";\nimport {\n checkBodySchema,\n grantBodySchema,\n meCheckBodySchema,\n meRelationBodySchema,\n relationCheckBodySchema,\n relationshipBodySchema,\n revokeBodySchema,\n subjectUpdateBodySchema,\n} from \"./validation.ts\";\n\n/** Everything the API router needs. */\nexport interface ApiContext {\n engine: AnyPermissions;\n auth: AuthProvider;\n authorization: AuthorizationProvider;\n title: string;\n readonly: boolean;\n basePath: string;\n logoUrl?: string;\n /** The document served at `/api/openapi.json`. */\n openapi?: () => Record<string, unknown>;\n /**\n * The rules' `ctx` for the caller's runtime checks (`/api/me/check`), for catalogs whose rules\n * read app facts. The caller can't supply `ctx` on that route.\n */\n checkContext?: (request: Request, subject: SubjectIdentity) => unknown;\n /**\n * The ReBAC subject of the caller for `POST /api/me/relation`. Default `user:{principal id}`.\n */\n relationSubject?: (principal: Principal) => string;\n}\n\n/** `GET /config` (and `/api/config`): the SPA bootstrap. */\nexport interface PanelConfig {\n title: string;\n logoUrl?: string;\n basePath: string;\n readonly: boolean;\n /** Who owns roles (ADR 0014): `\"external\"` hides role changes (the auth provider owns them). */\n roleSource: RoleSourceMode;\n authenticated: boolean;\n /**\n * The caller, with its effective catalog role and the source that decided it; `null` when not\n * authenticated.\n */\n principal: {\n id: string;\n role: string;\n roleSource?: RoleSource;\n name?: string;\n email?: string;\n } | null;\n /**\n * The ADR 0008 actions the caller may perform. Mutating actions are left out of a readonly\n * panel, so the SPA can hide write UI from this list alone.\n */\n allowed: PermissionsAction[];\n}\n\n/** A role or permission with its label. */\nexport interface LabeledKey {\n key: string;\n label: string;\n description?: string;\n}\n\n/** `GET /api/catalog`. */\nexport interface CatalogView {\n /** Least → most privileged. */\n roles: LabeledKey[];\n assignable: LabeledKey[];\n guestRole: string;\n defaultRole: string;\n managerRoles: string[];\n directGrants: boolean;\n /** Who owns roles: `\"stored\"` (role changes allowed) or `\"external\"` (the auth provider's). */\n roleSource: RoleSourceMode;\n /** Every leaf permix path of every role's rules tree, sorted (for the playground). */\n paths: string[];\n /** The relation schema (ReBAC), `null` when the catalog declares none. */\n relations: RelationTypeView[] | null;\n}\n\n/** `GET /api/subjects`. */\nexport interface SubjectList {\n subjects: SubjectSummary[];\n}\n\n/** `GET /api/subjects/:id`: the stored view plus the effective role and active permissions. */\nexport interface SubjectDetail extends SubjectView {\n /**\n * The role checks use: the stored role (`roleSource: \"stored\"` mode only), else the auth\n * provider's (`lookupSubject`), else the catalog's `defaultRole`; `roleSource` says which.\n */\n effectiveRole: string;\n /** The non-expired, assignable granted permissions. */\n permissions: string[];\n}\n\n/** Route tags (OpenAPI grouping). */\nexport type RouteTag =\n | \"panel\"\n | \"catalog\"\n | \"subjects\"\n | \"grants\"\n | \"history\"\n | \"check\"\n | \"relationships\"\n | \"runtime\";\n\n/** HTTP methods the router serves. */\nexport type RouteMethod = KitRouteMethod;\n\n/** A query parameter a route documents. */\nexport type RouteQueryParam = KitRouteQueryParam;\n\n/** The documented shape of one route (consumed by the OpenAPI builder). */\nexport type RouteSpec = KitRouteSpec<PermissionsAction, RouteTag> & {\n /** Runtime route: needs an authenticated principal, no action. */\n runtime?: boolean;\n};\n\ntype Call = KitCall<ApiContext>;\ntype ApiRoute = Route<PermissionsAction, PermissionsResource, ApiContext, never, RouteTag> & {\n runtime?: boolean;\n};\n\n// ─── Helpers ────────────────────────────────────────────────────────────────────────────────\n\n/** The actor of a write: the authenticated principal. */\nfunction actorOf(c: Call): Actor | null {\n const p = c.principal;\n if (!p) return null;\n return {\n id: p.id,\n type: \"user\",\n ...(p.name !== undefined ? { name: p.name } : {}),\n ...(p.email !== undefined ? { email: p.email } : {}),\n };\n}\n\nconst labeled = (key: string, label: { label: string; description?: string }): LabeledKey => ({\n key,\n label: label.label,\n ...(label.description !== undefined ? { description: label.description } : {}),\n});\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst pathsCache = new WeakMap<object, string[]>();\n\n/**\n * Every leaf path of every role's rules tree. The trees are built (never evaluated) with a\n * placeholder subject and no grants; a role whose rules can't be built that way is skipped.\n */\nexport function catalogPaths(catalog: AnyPermissionsCatalog): string[] {\n const cached = pathsCache.get(catalog);\n if (cached) return cached;\n const paths = new Set<string>();\n const walk = (node: unknown, prefix: string) => {\n if (!isRecord(node)) {\n if (prefix && (typeof node === \"boolean\" || typeof node === \"function\")) paths.add(prefix);\n return;\n }\n for (const key of Object.keys(node)) walk(node[key], prefix ? `${prefix}.${key}` : key);\n };\n const createRules = catalog.authorization.createRules as (\n user: unknown,\n facts: { permissions: string[] },\n ) => unknown;\n for (const role of catalog.roles as readonly string[]) {\n const user = role === catalog.guestRole ? undefined : { id: \"\", role };\n try {\n walk(createRules(user, { permissions: [] }), \"\");\n } catch {\n // The role's rules need a real subject or ctx: its paths are not listed.\n }\n }\n const out = [...paths].sort();\n pathsCache.set(catalog, out);\n return out;\n}\n\n/** The catalog view served at `/api/catalog` (`roleSource`: the engine's, default `\"stored\"`). */\nexport function catalogView(\n catalog: AnyPermissionsCatalog,\n roleSource: RoleSourceMode = \"stored\",\n): CatalogView {\n const roles = catalog.roles as readonly string[];\n const assignable = catalog.assignable as readonly string[];\n const labels = catalog.labels as {\n roles: Record<string, { label: string; description?: string }>;\n permissions: Record<string, { label: string; description?: string }>;\n };\n return {\n roles: roles.map((role) => labeled(role, labels.roles[role] ?? { label: role })),\n assignable: assignable.map((p) => labeled(p, labels.permissions[p] ?? { label: p })),\n guestRole: catalog.guestRole,\n defaultRole: catalog.defaultRole,\n managerRoles: [...(catalog.managerRoles as readonly string[])],\n directGrants: catalog.directGrants,\n roleSource,\n paths: catalogPaths(catalog),\n relations: catalog.relations ? relationSchemaView(catalog.relations) : null,\n };\n}\n\n/** A check result as JSON: `explanation.error` (a thrown value) becomes its message. */\nexport function serializeCheck(result: CheckResult): CheckResult {\n const error = result.explanation.error;\n if (error === undefined) return result;\n const message =\n error instanceof Error ? error.message || error.name : typeof error === \"string\" ? error : \"\";\n return {\n ...result,\n explanation: { ...result.explanation, error: message || String(error) },\n };\n}\n\n/** The subject detail served at `/api/subjects/:id`. */\nasync function subjectDetail(engine: AnyPermissions, id: string): Promise<SubjectDetail> {\n const [view, snapshot] = await Promise.all([engine.getSubject(id), engine.snapshot(id)]);\n return { ...(view as SubjectView), permissions: snapshot.permissions };\n}\n\n/** The resource every action is evaluated on for the bootstrap's `allowed` list. */\nconst COLLECTION: Record<PermissionsAction, PermissionsResource> = {\n \"catalog:read\": { type: \"catalog\" },\n \"subjects:read\": { type: \"subject\" },\n \"grants:read\": { type: \"grant\" },\n \"history:read\": { type: \"history\" },\n \"check:run\": { type: \"check\" },\n \"relationships:read\": { type: \"relationship\" },\n \"grants:write\": { type: \"grant\" },\n \"roles:write\": { type: \"subject\" },\n \"relationships:write\": { type: \"relationship\" },\n};\n\nasync function panelConfig(c: Call): Promise<PanelConfig> {\n const { ctx, principal, request } = c;\n let who: PanelConfig[\"principal\"] = null;\n const allowed: PermissionsAction[] = [];\n if (principal) {\n const identity = principalIdentity(principal);\n const snapshot = await ctx.engine.snapshot(identity);\n who = {\n id: principal.id,\n role: snapshot.subject.role,\n ...(snapshot.subject.roleSource !== undefined\n ? { roleSource: snapshot.subject.roleSource }\n : {}),\n ...(identity.name !== undefined ? { name: identity.name } : {}),\n ...(identity.email !== undefined ? { email: identity.email } : {}),\n };\n const decisions = await Promise.all(\n ALL_ACTIONS.map((action) =>\n ctx.readonly && isMutatingAction(action)\n ? false\n : ctx.authorization.authorize({\n principal,\n action,\n resource: COLLECTION[action],\n request,\n }),\n ),\n );\n ALL_ACTIONS.forEach((action, i) => decisions[i] && allowed.push(action));\n }\n return {\n title: ctx.title,\n ...(ctx.logoUrl !== undefined ? { logoUrl: ctx.logoUrl } : {}),\n basePath: ctx.basePath,\n readonly: ctx.readonly,\n roleSource: ctx.engine.roleSource,\n authenticated: principal !== null,\n principal: who,\n allowed,\n };\n}\n\nconst NO_PRINCIPAL = () =>\n json({ error: \"Unauthorized: no authenticated subject\", code: \"NO_SUBJECT\" }, 401);\n\n/** The caller as a subject (runtime routes). */\nfunction callerOf(principal: Principal): SubjectIdentity {\n return principalIdentity(principal);\n}\n\nconst subjectRes = (c: Call): PermissionsResource => ({ type: \"subject\", subject: c.params.id! });\n\nconst truthy = (value: string | null): boolean => value === \"true\" || value === \"1\";\n\n/** The caller's ReBAC subject (`POST /api/me/relation`). */\nconst relationSubjectOf = (c: Call, principal: Principal): string =>\n c.ctx.relationSubject?.(principal) ?? `user:${principal.id}`;\n\n/** `?name=` or `undefined` when absent / empty. */\nconst queryOf = (c: Call, name: string): string | undefined => c.query.get(name) || undefined;\n\n/** The relationship a request names: the JSON body, or `?object=&relation=&subject=` (DELETE). */\nasync function relationshipOf(c: Call) {\n if (queryOf(c, \"object\") === undefined) return c.body(relationshipBodySchema);\n const fromQuery: Record<string, string> = {};\n for (const name of [\"object\", \"relation\", \"subject\", \"reason\"]) {\n const value = queryOf(c, name);\n if (value !== undefined) fromQuery[name] = value;\n }\n return parseInput(relationshipBodySchema, fromQuery);\n}\n\n/** A role-only playground check runs as this placeholder (no record, no grants). */\nconst ROLE_PREVIEW_ID = \"\\u0000role-preview\";\n\n// ─── Routes ─────────────────────────────────────────────────────────────────────────────────\n\nconst ROUTES: ApiRoute[] = [\n // --- Public ---------------------------------------------------------------------------------\n {\n method: \"GET\",\n path: \"/healthcheck\",\n operationId: \"healthcheck\",\n summary: \"Liveness probe\",\n tag: \"panel\",\n response: { status: 200, schema: \"Health\", description: \"Alive\" },\n handle: () => json({ ok: true }),\n },\n {\n method: \"GET\",\n path: \"/api/openapi.json\",\n operationId: \"getOpenApi\",\n summary: \"This OpenAPI 3.1 document\",\n tag: \"panel\",\n response: { status: 200, schema: { type: \"object\" }, description: \"OpenAPI 3.1\" },\n handle: (c) => json(c.ctx.openapi?.() ?? {}),\n },\n\n // --- Admin: catalog -------------------------------------------------------------------------\n {\n method: \"GET\",\n path: \"/api/catalog\",\n operationId: \"getCatalog\",\n summary: \"The catalog: roles, assignable permissions, labels and every rule path\",\n tag: \"catalog\",\n action: \"catalog:read\",\n resource: () => ({ type: \"catalog\" }),\n response: { status: 200, schema: \"CatalogView\", description: \"Catalog\" },\n handle: (c) => json(catalogView(c.ctx.engine.catalog, c.ctx.engine.roleSource)),\n },\n\n // --- Admin: subjects ------------------------------------------------------------------------\n {\n method: \"GET\",\n path: \"/api/subjects\",\n operationId: \"listSubjects\",\n summary: \"Every subject with a record or a grant, sorted by id\",\n tag: \"subjects\",\n action: \"subjects:read\",\n query: [{ name: \"search\", type: \"string\", description: \"Substring of id, name or email.\" }],\n resource: () => ({ type: \"subject\" }),\n response: { status: 200, schema: \"SubjectList\", description: \"Subjects\" },\n async handle(c) {\n const search = c.query.get(\"search\")?.trim().toLowerCase() || undefined;\n let subjects = await c.ctx.engine.listSubjects();\n if (search !== undefined) {\n subjects = subjects.filter((s) =>\n [s.id, s.name, s.email].some((f) => f?.toLowerCase().includes(search)),\n );\n }\n return json({ subjects } satisfies SubjectList);\n },\n },\n {\n method: \"GET\",\n path: \"/api/subjects/:id\",\n operationId: \"getSubject\",\n summary: \"A subject's record, grants, effective role and active permissions\",\n tag: \"subjects\",\n action: \"subjects:read\",\n query: [\n {\n name: \"includeExpired\",\n type: \"string\",\n description: \"`true` to include expired grants.\",\n },\n ],\n resource: subjectRes,\n response: { status: 200, schema: \"SubjectDetail\", description: \"Subject\" },\n async handle(c) {\n const id = c.params.id!;\n const detail = await subjectDetail(c.ctx.engine, id);\n if (truthy(c.query.get(\"includeExpired\"))) {\n detail.grants = (await c.ctx.engine.getSubject(id, { includeExpired: true })).grants;\n }\n return json(detail);\n },\n },\n {\n method: \"PUT\",\n path: \"/api/subjects/:id\",\n operationId: \"updateSubject\",\n summary: \"Assign or clear a stored role; set or clear the display name / email\",\n description:\n '`role: null` clears the stored assignment (the auth provider\\'s role, or `defaultRole`, applies again). A field left out is kept. The role change is recorded in the history with the principal as actor. With `roleSource: \"external\"` a `role` is refused (409 `ROLES_EXTERNAL`); name / email updates still work.',\n tag: \"subjects\",\n action: \"roles:write\",\n resource: subjectRes,\n body: \"SubjectUpdate\",\n response: { status: 200, schema: \"SubjectDetail\", description: \"The updated subject\" },\n async handle(c) {\n const id = c.params.id!;\n const body = await c.body(subjectUpdateBodySchema);\n const { engine } = c.ctx;\n if (body.role !== undefined) {\n if (body.role !== null && !engine.catalog.isRole(body.role)) {\n throw new UnknownRoleError(body.role);\n }\n await engine.setRole({\n subject: id,\n role: body.role,\n actor: actorOf(c),\n ...(body.reason !== undefined ? { reason: body.reason } : {}),\n });\n }\n if (body.name !== undefined || body.email !== undefined) {\n await engine.upsertSubject({\n id,\n ...(body.name !== undefined ? { name: body.name } : {}),\n ...(body.email !== undefined ? { email: body.email } : {}),\n });\n }\n return json(await subjectDetail(engine, id));\n },\n },\n\n // --- Admin: grants --------------------------------------------------------------------------\n {\n method: \"GET\",\n path: \"/api/grants\",\n operationId: \"listGrants\",\n summary: \"Grants by subject, by permission, both, or all (sorted by subject, permission)\",\n tag: \"grants\",\n action: \"grants:read\",\n query: [\n { name: \"subject\", type: \"string\", description: \"One subject's grants.\" },\n { name: \"permission\", type: \"string\", description: \"One permission's grants.\" },\n { name: \"includeExpired\", type: \"string\", description: \"`true` to include expired.\" },\n ],\n resource: (c) => ({\n type: \"grant\",\n ...(c.query.get(\"subject\") ? { subject: c.query.get(\"subject\")! } : {}),\n ...(c.query.get(\"permission\") ? { permission: c.query.get(\"permission\")! } : {}),\n }),\n response: { status: 200, schema: \"GrantList\", description: \"Grants\" },\n async handle(c) {\n const subject = c.query.get(\"subject\") || undefined;\n const permission = c.query.get(\"permission\") || undefined;\n const grants = await c.ctx.engine.list({\n ...(subject !== undefined ? { subject } : {}),\n ...(permission !== undefined ? { permission } : {}),\n ...(truthy(c.query.get(\"includeExpired\")) ? { includeExpired: true } : {}),\n });\n return json({ grants });\n },\n },\n {\n method: \"POST\",\n path: \"/api/grants\",\n operationId: \"grant\",\n summary: \"Grant a permission (idempotent: 201 when created, 200 when it already existed)\",\n tag: \"grants\",\n action: \"grants:write\",\n async resource(c) {\n const { subject, permission } = await c.body(grantBodySchema);\n return { type: \"grant\", subject, permission };\n },\n body: \"GrantInput\",\n response: { status: 201, schema: \"GrantResult\", description: \"Granted\" },\n async handle(c) {\n const body = await c.body(grantBodySchema);\n const result = await c.ctx.engine.grant({ ...body, actor: actorOf(c) });\n return json(result, result.created ? 201 : 200);\n },\n },\n {\n method: \"DELETE\",\n path: \"/api/grants/:subject/:permission\",\n operationId: \"revoke\",\n summary: \"Revoke a permission (idempotent: `removed: false` when absent)\",\n description: \"The reason is read from the JSON body `{ reason }` or the `?reason=` query.\",\n tag: \"grants\",\n action: \"grants:write\",\n query: [{ name: \"reason\", type: \"string\", description: \"Why (when there is no body).\" }],\n resource: (c) => ({\n type: \"grant\",\n subject: c.params.subject!,\n permission: c.params.permission!,\n }),\n body: \"RevokeInput\",\n bodyRequired: false,\n response: { status: 200, schema: \"RevokeResult\", description: \"Revoked (or nothing to do)\" },\n async handle(c) {\n const body = await c.body(revokeBodySchema);\n const reason = body.reason ?? (c.query.get(\"reason\") || undefined);\n return json(\n await c.ctx.engine.revoke({\n subject: c.params.subject!,\n permission: c.params.permission!,\n actor: actorOf(c),\n ...(reason !== undefined ? { reason } : {}),\n }),\n );\n },\n },\n\n // --- Admin: history -------------------------------------------------------------------------\n {\n method: \"GET\",\n path: \"/api/history\",\n operationId: \"history\",\n summary: \"Grant / revoke / role history, newest first (cursor pagination)\",\n tag: \"history\",\n action: \"history:read\",\n query: [\n { name: \"subject\", type: \"string\", description: \"One subject's history.\" },\n { name: \"limit\", type: \"integer\", description: \"Page size, 1–1000 (default 50).\" },\n { name: \"cursor\", type: \"string\", description: \"The previous page's `nextCursor`.\" },\n ],\n resource: (c) => ({\n type: \"history\",\n ...(c.query.get(\"subject\") ? { subject: c.query.get(\"subject\")! } : {}),\n }),\n response: { status: 200, schema: \"HistoryPage\", description: \"A page of history\" },\n async handle(c) {\n const subject = c.query.get(\"subject\") || undefined;\n const cursor = c.query.get(\"cursor\") || undefined;\n const limit = intParam(c.query.get(\"limit\"), { name: \"limit\" });\n return json(\n await c.ctx.engine.history({\n ...(subject !== undefined ? { subject } : {}),\n ...(limit !== undefined ? { limit } : {}),\n ...(cursor !== undefined ? { cursor } : {}),\n }),\n );\n },\n },\n\n // --- Admin: check playground ----------------------------------------------------------------\n {\n method: \"POST\",\n path: \"/api/check\",\n operationId: \"check\",\n summary: \"Check playground: decide a path for a subject, a role, or a guest, with reasons\",\n description:\n \"`subject` checks a subject (its grants, and its stored role or the provider's from `lookupSubject`). `role` alone checks the role with no subject and no grants (`subject: null` in the result). Both: `role` is the provider's role (a stored role still wins unless `roleSource` is `external`). Neither: a guest. A denial is `200` with `allowed: false`.\",\n tag: \"check\",\n action: \"check:run\",\n async resource(c) {\n const body = await c.body(checkBodySchema);\n return {\n type: \"check\",\n subject: body.subject ?? null,\n ...(body.role !== undefined ? { role: body.role } : {}),\n path: body.path,\n };\n },\n body: \"CheckInput\",\n response: { status: 200, schema: \"CheckResult\", description: \"The decision\" },\n async handle(c) {\n const body = await c.body(checkBodySchema);\n const { engine } = c.ctx;\n const catalog = engine.catalog;\n if (body.role !== undefined && !catalog.isRole(body.role)) {\n throw new UnknownRoleError(body.role);\n }\n let subject: SubjectIdentity | null = null;\n let preview = false;\n if (body.subject) {\n subject = { id: body.subject, ...(body.role !== undefined ? { role: body.role } : {}) };\n } else if (body.role !== undefined && body.role !== catalog.guestRole) {\n subject = { id: ROLE_PREVIEW_ID, role: body.role };\n preview = true;\n }\n const facts = body.ctx !== undefined ? [{ ctx: body.ctx }] : [];\n const ability = await engine.ability(subject, ...(facts as []));\n const result = (await ability.checkAsync(body.path, body.data)) as CheckResult;\n return json(serializeCheck(preview ? { ...result, subject: null } : result));\n },\n },\n\n // --- Admin: relationships (ReBAC, ADR 0013) -------------------------------------------------\n {\n method: \"GET\",\n path: \"/api/relationships\",\n operationId: \"readRelationships\",\n summary: \"Stored relationships by object (or type), relation and/or subject (paginated)\",\n tag: \"relationships\",\n action: \"relationships:read\",\n query: [\n { name: \"object\", type: \"string\", description: \"`type:id`, or a bare `type`.\" },\n { name: \"relation\", type: \"string\", description: \"One relation.\" },\n { name: \"subject\", type: \"string\", description: \"Exactly this subject reference.\" },\n { name: \"limit\", type: \"integer\", description: \"Page size, 1–1000 (default 100).\" },\n { name: \"cursor\", type: \"string\", description: \"The previous page's `nextCursor`.\" },\n ],\n resource: (c) => ({\n type: \"relationship\",\n ...(queryOf(c, \"object\") ? { object: queryOf(c, \"object\")! } : {}),\n ...(queryOf(c, \"relation\") ? { relation: queryOf(c, \"relation\")! } : {}),\n ...(queryOf(c, \"subject\") ? { subject: queryOf(c, \"subject\")! } : {}),\n }),\n response: { status: 200, schema: \"RelationshipPage\", description: \"A page of relationships\" },\n async handle(c) {\n const limit = intParam(c.query.get(\"limit\"), { name: \"limit\" });\n const query: Record<string, unknown> = {};\n for (const name of [\"object\", \"relation\", \"subject\", \"cursor\"]) {\n const value = queryOf(c, name);\n if (value !== undefined) query[name] = value;\n }\n if (limit !== undefined) query.limit = limit;\n return json(await c.ctx.engine.readRelationships(query));\n },\n },\n {\n method: \"POST\",\n path: \"/api/relationships\",\n operationId: \"writeRelationship\",\n summary: \"Write a relationship (idempotent: 201 when created, 200 when it already existed)\",\n description:\n \"Validated against the catalog's relation schema (400 `INVALID_RELATION` when the schema doesn't allow the subject on that relation).\",\n tag: \"relationships\",\n action: \"relationships:write\",\n async resource(c) {\n const { object, relation, subject } = await c.body(relationshipBodySchema);\n return { type: \"relationship\", object, relation, subject };\n },\n body: \"RelationshipInput\",\n response: { status: 201, schema: \"WriteRelationshipResult\", description: \"Written\" },\n async handle(c) {\n const body = await c.body(relationshipBodySchema);\n const result = await c.ctx.engine.writeRelationship({ ...body, actor: actorOf(c) });\n return json(result, result.created ? 201 : 200);\n },\n },\n {\n method: \"DELETE\",\n path: \"/api/relationships\",\n operationId: \"deleteRelationship\",\n summary: \"Delete a relationship (idempotent: `removed: false` when absent)\",\n description:\n \"The tuple comes from the JSON body `{ object, relation, subject, reason? }` or the `?object=&relation=&subject=&reason=` query.\",\n tag: \"relationships\",\n action: \"relationships:write\",\n query: [\n { name: \"object\", type: \"string\", description: \"When there is no body.\" },\n { name: \"relation\", type: \"string\", description: \"When there is no body.\" },\n { name: \"subject\", type: \"string\", description: \"When there is no body.\" },\n { name: \"reason\", type: \"string\", description: \"When there is no body.\" },\n ],\n async resource(c) {\n const { object, relation, subject } = await relationshipOf(c);\n return { type: \"relationship\", object, relation, subject };\n },\n body: \"RelationshipInput\",\n bodyRequired: false,\n response: {\n status: 200,\n schema: \"DeleteRelationshipResult\",\n description: \"Deleted (or nothing to do)\",\n },\n async handle(c) {\n const tuple = await relationshipOf(c);\n return json(await c.ctx.engine.deleteRelationship({ ...tuple, actor: actorOf(c) }));\n },\n },\n {\n method: \"POST\",\n path: \"/api/relationships/check\",\n operationId: \"checkRelation\",\n summary:\n \"Does a subject have a relation on an object? With the path of relations that decided it\",\n description: \"A denial is `200` with `allowed: false` and an empty `path`.\",\n tag: \"relationships\",\n action: \"relationships:read\",\n async resource(c) {\n const { object, relation, subject } = await c.body(relationCheckBodySchema);\n return { type: \"relationship\", object, relation, subject };\n },\n body: \"RelationCheckInput\",\n response: { status: 200, schema: \"RelationCheckResult\", description: \"The decision\" },\n async handle(c) {\n return json(\n await c.ctx.engine.checkRelation((await c.body(relationCheckBodySchema)) as never),\n );\n },\n },\n {\n method: \"GET\",\n path: \"/api/relationships/objects\",\n operationId: \"listObjects\",\n summary: \"The objects of a type on which a subject has a relation\",\n description:\n \"A walk backwards over the reverse index, bounded by `maxDepth`; fine for app-scale data (see docs/REBAC.md).\",\n tag: \"relationships\",\n action: \"relationships:read\",\n query: [\n {\n name: \"subject\",\n type: \"string\",\n description: \"`user:ana`, `group:eng#member`.\",\n required: true,\n },\n { name: \"relation\", type: \"string\", description: \"A relation of `type`.\", required: true },\n { name: \"type\", type: \"string\", description: \"The object type.\", required: true },\n ],\n resource: (c) => ({\n type: \"relationship\",\n ...(queryOf(c, \"subject\") ? { subject: queryOf(c, \"subject\")! } : {}),\n ...(queryOf(c, \"relation\") ? { relation: queryOf(c, \"relation\")! } : {}),\n }),\n response: { status: 200, schema: \"ObjectList\", description: \"Objects, sorted\" },\n async handle(c) {\n const objects = await c.ctx.engine.listObjects({\n subject: c.query.get(\"subject\") ?? \"\",\n relation: c.query.get(\"relation\") ?? \"\",\n type: c.query.get(\"type\") ?? \"\",\n } as never);\n return json({ objects });\n },\n },\n {\n method: \"GET\",\n path: \"/api/relationships/subjects\",\n operationId: \"listRelationSubjects\",\n summary: \"The subjects that have a relation on an object (usersets expanded)\",\n tag: \"relationships\",\n action: \"relationships:read\",\n query: [\n { name: \"object\", type: \"string\", description: \"`type:id`.\", required: true },\n {\n name: \"relation\",\n type: \"string\",\n description: \"A relation of the object's type.\",\n required: true,\n },\n { name: \"type\", type: \"string\", description: \"Only subjects of this type.\" },\n ],\n resource: (c) => ({\n type: \"relationship\",\n ...(queryOf(c, \"object\") ? { object: queryOf(c, \"object\")! } : {}),\n ...(queryOf(c, \"relation\") ? { relation: queryOf(c, \"relation\")! } : {}),\n }),\n response: { status: 200, schema: \"SubjectRefList\", description: \"Subjects, sorted\" },\n async handle(c) {\n const type = queryOf(c, \"type\");\n const subjects = await c.ctx.engine.listRelationSubjects({\n object: c.query.get(\"object\") ?? \"\",\n relation: c.query.get(\"relation\") ?? \"\",\n ...(type !== undefined ? { type } : {}),\n } as never);\n return json({ subjects });\n },\n },\n\n // --- Runtime: the caller --------------------------------------------------------------------\n {\n method: \"GET\",\n path: \"/api/me\",\n operationId: \"me\",\n summary: \"The caller's snapshot: id, effective role and active permissions (ADR 0009)\",\n tag: \"runtime\",\n authenticate: true,\n runtime: true,\n response: { status: 200, schema: \"PermissionsSnapshot\", description: \"Snapshot\" },\n async handle(c) {\n if (!c.principal) return NO_PRINCIPAL();\n return json(await c.ctx.engine.snapshot(callerOf(c.principal)));\n },\n },\n {\n method: \"POST\",\n path: \"/api/me/check\",\n operationId: \"meCheck\",\n summary: \"Decide a path for the caller, with reasons\",\n description:\n \"Advisory (for UI gating): `data` comes from the caller. Enforce on the server with the engine. The rules' `ctx` comes from the server's `checkContext` option, never from the body.\",\n tag: \"runtime\",\n authenticate: true,\n runtime: true,\n body: \"MeCheckInput\",\n response: { status: 200, schema: \"CheckResult\", description: \"The decision\" },\n async handle(c) {\n if (!c.principal) return NO_PRINCIPAL();\n const body = await c.body(meCheckBodySchema);\n const subject = callerOf(c.principal);\n const facts = c.ctx.checkContext\n ? [{ ctx: await c.ctx.checkContext(c.request, subject) }]\n : [];\n const ability = await c.ctx.engine.ability(subject, ...(facts as []));\n return json(serializeCheck((await ability.checkAsync(body.path, body.data)) as CheckResult));\n },\n },\n {\n method: \"POST\",\n path: \"/api/me/relation\",\n operationId: \"meRelation\",\n summary: \"Does the caller have a relation on an object? (ReBAC, with the path)\",\n description:\n \"The caller is the subject `user:{id}` unless the server's `relationSubject` option maps it. Advisory for UI gating; enforce on the server.\",\n tag: \"runtime\",\n authenticate: true,\n runtime: true,\n body: \"MeRelationInput\",\n response: { status: 200, schema: \"RelationCheckResult\", description: \"The decision\" },\n async handle(c) {\n if (!c.principal) return NO_PRINCIPAL();\n const body = await c.body(meRelationBodySchema);\n return json(\n await c.ctx.engine.checkRelation({\n subject: relationSubjectOf(c, c.principal),\n relation: body.relation,\n object: body.object,\n } as never),\n );\n },\n },\n];\n\n/** The documented route table (every API route, in match order). */\nexport const API_ROUTES: readonly RouteSpec[] = ROUTES;\n\n/** The paths served as the bootstrap config (not in {@link API_ROUTES}). */\nexport const CONFIG_PATHS: readonly string[] = [\"/config\", \"/api/config\"];\n\nconst CONFIG_ROUTES: ApiRoute[] = CONFIG_PATHS.map((path) => ({\n method: \"GET\",\n path,\n operationId: path === \"/config\" ? \"getConfig\" : \"getApiConfig\",\n summary: \"SPA bootstrap config: title, readonly, the caller and the actions it may perform\",\n tag: \"panel\",\n authenticate: true,\n hidden: true,\n response: { status: 200, schema: \"PanelConfig\", description: \"Panel config\" },\n handle: async (c) => json(await panelConfig(c)),\n}));\n\n/** Domain errors by name (ADR 0008); see `@xtandard/kit/server` `mapError`. */\nexport const ERRORS: ErrorMap = {\n NoSubjectError: { status: 401, code: \"NO_SUBJECT\" },\n ForbiddenError: { status: 403, code: \"FORBIDDEN\" },\n UnknownPermissionError: { status: 400, code: \"UNKNOWN_PERMISSION\" },\n UnknownRoleError: { status: 400, code: \"UNKNOWN_ROLE\" },\n NotFoundError: { status: 404, code: \"NOT_FOUND\" },\n ReadonlyError: { status: 423, code: \"READONLY\" },\n ExternalRolesError: { status: 409, code: \"ROLES_EXTERNAL\" },\n AsyncRuleError: { status: 500, code: \"ASYNC_RULE\" },\n RelationSchemaError: { status: 400, code: \"INVALID_RELATION\" },\n RelationDepthError: { status: 422, code: \"RELATION_DEPTH\" },\n};\n\n/** Build the API router for one panel. */\nexport function createApiRouter(\n ctx: ApiContext,\n): Router<PermissionsAction, PermissionsResource, ApiContext, never, RouteTag> {\n return createRouter<PermissionsAction, PermissionsResource, ApiContext, never, RouteTag>({\n routes: [...CONFIG_ROUTES, ...ROUTES],\n context: ctx,\n readonly: ctx.readonly,\n isMutatingAction,\n readonlyStatus: 423,\n readonlyMessage: (route) =>\n `Cannot ${route.operationId}: @xtandard/permissions is in readonly mode.`,\n auth: ctx.auth,\n authorization: ctx.authorization,\n errors: ERRORS,\n });\n}\n\n/** Map domain errors to HTTP responses (ADR 0008), by name across bundles. */\nexport function mapError(err: unknown): Response {\n return kitMapError(err, ERRORS);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgBA,MAAM,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,UAAU,GAAG,mBAAmB,CAAC;AACvE,MAAM,SAAS,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,UAAU,KAAM,iCAAiC,CAAC;AACtF,MAAM,UAAU,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,UAAU,KAAK,gCAAgC,CAAC,CAAC;;AAGjG,MAAa,kBAAkB,EAAE,KAAK,kBAAkB,CAAC,OAAO,CAAC;;AAGjE,MAAa,mBAAmB,EAAE,KAAK,mBAAmB,CAAC,QAAQ,CAAC;;;;;AAMpE,MAAa,0BAA0B,EAAE,OAAO;CAC9C,MAAM,EAAE,SAAS,EAAE,S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oleMapper } from "./contract-D32H1t0u.mjs";
3
- import { r as BetterAuthSessionLike } from "./better-auth-NSXgt6ZU.mjs";
4
- import { t as AnyPermissions } from "./engine-DpFIcbgh.mjs";
2
+ import { r as RoleMapper } from "./contract-D6j-yrBL.mjs";
3
+ import { i as BetterAuthSessionLike } from "./better-auth-DQET1sXa.mjs";
4
+ import { t as AnyPermissions } from "./engine-C3xHfi3q.mjs";
5
5
  import * as v from "valibot";
6
6
 
7
7
  //#region node_modules/better-call/dist/standard-schema.d.mts
@@ -883,4 +883,4 @@ declare const permissions: <P extends AnyPermissions>(options: PermissionsPlugin
883
883
  type PermissionsPlugin<P extends AnyPermissions = AnyPermissions> = ReturnType<typeof permissions<P>>;
884
884
  //#endregion
885
885
  export { PERMISSIONS_ERROR_CODES as i, PermissionsPluginOptions as n, permissions as r, PermissionsPlugin as t };
886
- //# sourceMappingURL=server-CJ7AIJpO.d.mts.map
886
+ //# sourceMappingURL=server-Bn643UOy.d.mts.map
@@ -1,7 +1,7 @@
1
1
  import { f as PermissionsSubject, h as SubjectIdentity } from "./catalog-DA_d1SdC.cjs";
2
- import { r as RoleMapper } from "./contract-BMiOmg2f.cjs";
3
- import { r as BetterAuthSessionLike } from "./better-auth-Bp9YVyQa.cjs";
4
- import { t as AnyPermissions } from "./engine-CGGVDCqi.cjs";
2
+ import { r as RoleMapper } from "./contract-BAisPHBw.cjs";
3
+ import { i as BetterAuthSessionLike } from "./better-auth-vgRYgjYK.cjs";
4
+ import { t as AnyPermissions } from "./engine-BTgwbHeO.cjs";
5
5
  import * as v from "valibot";
6
6
 
7
7
  //#region node_modules/better-call/dist/standard-schema.d.mts
@@ -883,4 +883,4 @@ declare const permissions: <P extends AnyPermissions>(options: PermissionsPlugin
883
883
  type PermissionsPlugin<P extends AnyPermissions = AnyPermissions> = ReturnType<typeof permissions<P>>;
884
884
  //#endregion
885
885
  export { PERMISSIONS_ERROR_CODES as i, PermissionsPluginOptions as n, permissions as r, PermissionsPlugin as t };
886
- //# sourceMappingURL=server-C2F4H6bR.d.cts.map
886
+ //# sourceMappingURL=server-YdH25OEA.d.cts.map
package/dist/testing.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_engine = require("./engine-bMoz3iW-.cjs");
2
+ const require_engine = require("./engine--C7zo-4M.cjs");
3
3
  const require_memory = require("./memory-knijqKw_.cjs");
4
4
  //#region src/testing.ts
5
5
  /**
@@ -1,6 +1,6 @@
1
1
  import { s as Definition } from "./policy-DFq_SYR3.cjs";
2
- import { t as AfterEvent } from "./contract-Dk6d2ylD.cjs";
3
- import { i as Permissions, o as PermissionsOptions } from "./engine-CGGVDCqi.cjs";
2
+ import { t as AfterEvent } from "./contract-CXPMGuHk.cjs";
3
+ import { i as Permissions, o as PermissionsOptions } from "./engine-BTgwbHeO.cjs";
4
4
 
5
5
  //#region src/testing.d.ts
6
6
  /** A controllable clock. */
@@ -1,6 +1,6 @@
1
1
  import { s as Definition } from "./policy-CGA6QD0a.mjs";
2
- import { t as AfterEvent } from "./contract-DUzgB-He.mjs";
3
- import { i as Permissions, o as PermissionsOptions } from "./engine-DpFIcbgh.mjs";
2
+ import { t as AfterEvent } from "./contract-DhS23Pcp.mjs";
3
+ import { i as Permissions, o as PermissionsOptions } from "./engine-C3xHfi3q.mjs";
4
4
 
5
5
  //#region src/testing.d.ts
6
6
  /** A controllable clock. */
package/dist/testing.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { t as createPermissions } from "./engine-Bufv0TbD.mjs";
1
+ import { t as createPermissions } from "./engine-CR75K253.mjs";
2
2
  import { t as createMemoryStorage } from "./memory-BbBbbY8-.mjs";
3
3
  //#region src/testing.ts
4
4
  /**
@@ -23,7 +23,35 @@ export interface PermissionsAuthProvider {
23
23
  * the role is one of the catalog's `managerRoles`.
24
24
  */
25
25
  canManage?(subject: PermissionsSubject, request: Request): boolean | Promise<boolean>;
26
+ /**
27
+ * Look a subject up by id, without a request (ADR 0014): the provider's identity, with the role
28
+ * as `getSubject` would report it, or `null` for an unknown id. Pass it to the engine's
29
+ * `lookupSubject` so checks by id and the panel see the provider's role of any subject.
30
+ */
31
+ lookupSubject?(id: string): Promise<SubjectIdentity | null> | SubjectIdentity | null;
26
32
  }
33
+ /** A by-id lookup a provider can't do on its own (`sessionProvider` / `jwtProvider` `lookup`). */
34
+ export type SubjectLookupFn = (id: string) => SubjectIdentity | null | undefined | Promise<SubjectIdentity | null | undefined>;
35
+ /**
36
+ * The engine options that hand role ownership to an auth provider (ADR 0014):
37
+ * `{ roleSource: "external", lookupSubject }`.
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * const provider = betterAuthProvider(auth);
42
+ * const perms = createPermissions({ catalog, storage, ...externalRoles(provider) });
43
+ * ```
44
+ */
45
+ export declare function externalRoles(provider: Pick<PermissionsAuthProvider, "lookupSubject">): {
46
+ roleSource: "external";
47
+ lookupSubject: ((id: string) => Promise<SubjectIdentity | null>) | undefined;
48
+ };
49
+ /**
50
+ * Wrap a user-supplied lookup like `getSubject`'s result: roles split and mapped, empty fields
51
+ * dropped. `null` for an unknown id.
52
+ * @internal
53
+ */
54
+ export declare function mappedLookup(lookup: SubjectLookupFn, mapRole: RoleMapper | undefined): (id: string) => Promise<SubjectIdentity | null>;
27
55
  /**
28
56
  * Renames raw roles from the auth library before the catalog parses them: a map
29
57
  * (`{ user: "member", "org:admin": "admin" }`, unmapped roles pass through) or a function
@@ -41,6 +41,11 @@ export interface KitAuth {
41
41
  }
42
42
  /** The `PermissionsSubject` a kit principal built by {@link toKitAuth} carries, if any. */
43
43
  export declare function subjectOf(principal: Principal | null | undefined): PermissionsSubject | null;
44
+ /**
45
+ * The identity the auth provider reported for a kit principal built by {@link toKitAuth} (its raw
46
+ * role, before the engine resolved it), if any.
47
+ */
48
+ export declare function identityOf(principal: Principal | null | undefined): SubjectIdentity | null;
44
49
  /**
45
50
  * Build the kit `auth` + `authorization` pair from a provider and the engine.
46
51
  *