# Add resource sharing (/docs/adding-sharing) > An end-to-end guide to sharing one resource type with owners, members, and invitations. This guide makes one resource type, `project`, shareable on PostgreSQL with Better Auth as the identity provider. Each step links to the reference for the details. For SQLite, swap step 2 and 3 for the [SQLite adapter](/docs/sharing-sqlite); for Clerk or WorkOS, swap step 4. > **Not on npm yet.** These packages are not on npm yet: `rolebook`, `@rolebook/sharing`, `@rolebook/sharing-postgres` and `@rolebook/sharing-better-auth`. The npm package named `rolebook` is an unrelated project, so do not install it. ## 1. Roles for the resource [#1-roles-for-the-resource] Add an owner role, member roles, and three management actions at the project's own scope. See [the policy shape](/docs/sharing/setup#the-policy). ```ts title="policy.ts" group=share import { definePolicy } from "rolebook"; export const policy = definePolicy({ resources: { workspace: { actions: ["read"] }, project: { parent: "workspace", actions: ["read", "update", "manage_members", "manage_invitations", "transfer_ownership"], }, }, roles: { project_owner: { scope: "project", rules: [{ effect: "allow", permission: "project:*" }] }, project_editor: { scope: "project", rules: [ { effect: "allow", permission: "project:read" }, { effect: "allow", permission: "project:update" }, ], }, project_viewer: { scope: "project", rules: [{ effect: "allow", permission: "project:read" }] }, }, }); ``` ## 2. Tables [#2-tables] Describe the application table and run the generated migrations on every deploy. See [PostgreSQL migrations](/docs/sharing-postgres/migrations). ```ts title="projects.ts" group=share import { trustedResource } from "rolebook"; import { applyPostgresMigrations, createResourceSharingMigrations, type ParameterizedSqlExecutor, type PostgresResourceDescriptor, } from "@rolebook/sharing-postgres"; // createPgExecutor(pool): see "An executor" in the PostgreSQL guide. Listing needs this checked executor. declare const executor: ParameterizedSqlExecutor; export const projectTable = { resourceType: "project", table: ["app", "project"], tenantColumn: "workspace_id", idColumn: "id", resourceVersionColumn: "version", sharingTablePrefix: "project", resourceFromRow: (row) => trustedResource({ type: "project", id: String(row.id) }, [{ type: "workspace", id: String(row.workspace_id) }]), } as const satisfies PostgresResourceDescriptor; await applyPostgresMigrations(executor, createResourceSharingMigrations(projectTable)); ``` ## 3. The storage adapter [#3-the-storage-adapter] Fence eligibility against Better Auth's member table, and email recipients against its member and user tables. See [fences](/docs/sharing-postgres/fences). ```ts title="adapter.ts" group=share import { createPostgresEmailInvitationRecipientFence, createPostgresMembershipEligibilityFence, createPostgresSharingAdapter, } from "@rolebook/sharing-postgres"; export const projectAdapter = createPostgresSharingAdapter({ executor, resource: projectTable, lockEligibleSubjects: createPostgresMembershipEligibilityFence({ table: ["auth", "member"], tenantColumn: "organizationId", subjectIdColumn: "userId", }), lockInvitationRecipient: createPostgresEmailInvitationRecipientFence({ membershipTable: ["auth", "member"], membershipTenantColumn: "organizationId", membershipSubjectIdColumn: "userId", userTable: ["auth", "user"], userIdColumn: "id", userEmailColumn: "email", userEmailVerifiedColumn: "emailVerified", }), }); ``` ## 4. Identity [#4-identity] See [Better Auth](/docs/sharing-better-auth) for a directory reader over its tables. ```ts title="identity.ts" group=share import { createBetterAuthIdentityAdapter, type BetterAuthDirectoryReader } from "@rolebook/sharing-better-auth"; declare const directory: BetterAuthDirectoryReader; export const identity = createBetterAuthIdentityAdapter({ directory }); ``` ## 5. The sharing instance [#5-the-sharing-instance] Generate the two keys once with `generateInvitationTokenKey()` and `generateListingCursorKey()` and store them as secrets. See [secret keys](/docs/sharing/setup#secret-keys). ```ts title="sharing.ts" group=share import { createHmacInvitationTokens, createSharing, defineSharing } from "@rolebook/sharing"; export const sharing = createSharing({ definition: defineSharing({ policy, resources: { project: { memberRoles: { editor: "project_editor", viewer: "project_viewer" }, ownershipRole: "project_owner", actions: { read: "project:read", update: "project:update" }, management: { members: "project:manage_members", invitations: "project:manage_invitations", ownership: "project:transfer_ownership", }, adapter: projectAdapter, }, }, }), identity, invitationTokens: createHmacInvitationTokens(process.env.SHARING_INVITATION_KEY!), listingCursorKey: process.env.SHARING_LISTING_CURSOR_KEY!, }); ``` ## 6. Create projects with an owner [#6-create-projects-with-an-owner] Insert the application row and initialize its owner in the same `SERIALIZABLE` transaction. See [lifecycle](/docs/sharing-postgres/lifecycle). ```ts title="create-project.ts" group=share import { withSerializableTransaction } from "@rolebook/sharing-postgres"; export async function createProject(workspaceId: string, userId: string, projectId: string, title: string) { const user = { type: "user", id: userId }; return withSerializableTransaction(executor, async (transaction) => { await transaction.query( "INSERT INTO app.project (workspace_id, id, title, version) VALUES ($1, $2, $3, 1)", [workspaceId, projectId, title], ); return projectAdapter.initializeResourceInTransaction(transaction, { tenantId: workspaceId, resourceId: projectId, owner: user, actor: user, occurredAt: new Date(), }); }); } ``` ## 7. Share and check [#7-share-and-check] ```ts title="use.ts" group=share const tenant = sharing.forTenant({ tenantId: "ws_456", actor: { type: "user", id: "user_123" } }); await tenant.execute({ kind: "grantRole", resource: { type: "project", id: "project_1" }, subject: { type: "user", id: "user_789" }, role: "viewer", idempotencyKey: "share-project_1-user_789", }); const viewer = sharing.forTenant({ tenantId: "ws_456", actor: { type: "user", id: "user_789" } }); const canRead = await viewer.authorize({ resource: { type: "project", id: "project_1" }, action: "read" }); ``` Commands return result codes rather than throwing; see [commands](/docs/sharing/commands). Expose the same operations to a browser with the [HTTP API](/docs/http-api). ## 8. List what a user can open [#8-list-what-a-user-can-open] `listAccessible()` pages through the projects a user may perform one action on, and `listAccess()` through the projects they may do anything on, with every action's decision. Each page is read at [one coherent point](/docs/sharing/listing#what-one-page-guarantees), which asks more of the configuration than `authorize()` does: - **Storage.** The adapter from step 3 qualifies when `executor` comes from `createPgExecutor(pool)` and the `workspace_id` and `id` columns are `text`. - **Eligibility.** `createPostgresMembershipEligibilityFence` supplies the evidence a page needs. A fence you write yourself needs a matching `readEligibleSubjects`. - **Identity.** The identity adapter from step 4 must supply evidence that its answer belongs to the page. Either it implements `resolvePagePrincipal`, which requires a source with a non-repeating revision, or you keep the identity facts in a projection table in the same database and name it in the adapter's `pageIdentity` option. [Identity for listing](/docs/sharing/listing#identity) shows the projection setup. The Better Auth adapter from step 4 does neither, and neither do the Clerk and WorkOS adapters: wired exactly as shown, both listings reject with `identity_evidence_missing`. To list, replace it with an identity adapter that answers exclusively from a projection table complete for every fact it returns (kept in sync from the provider), and name that identity object and projection in `pageIdentity`. `pageIdentity` is your attestation, and it is valid only when that identity resolves exclusively from the complete projection. Rolebook checks that the object is the same, not where its data comes from, so naming the provider-backed adapter beside a copy would make listings run without being sound. ```ts title="list.ts" group=share import { AccessListingUnavailableError } from "@rolebook/sharing"; try { const page = await viewer.listAccessible({ type: "project", action: "read", limit: 20 }); const everything = await viewer.listAccess({ type: "project", limit: 20 }); console.log(page.resources.length, everything.resources.length, page.nextCursor); } catch (error) { if (!(error instanceof AccessListingUnavailableError)) throw error; // No page was returned. `reason` says why: "identity_evidence_missing" means the step above is not done. console.warn(`listing unavailable: ${error.reason}`); } ``` A listing that cannot read a consistent page rejects with `AccessListingUnavailableError`; it never returns a partial list, and the error does not mean the user has no access. Continue with `nextCursor` until `exhausted`: a page can be empty and not exhausted. See [listing](/docs/sharing/listing). ## 9. Operate it [#9-operate-it] - Run the [adapter contract](/docs/sharing-testkit) in your test suite. - Schedule one [pruning job](/docs/sharing/retention). - Size the connection pool for listing: each page attempt holds one connection under a 2-second deadline, a call makes up to three attempts, and at most 32 attempts are open at once per adapter; see [bounds](/docs/sharing/listing#bounds). Alert on `ACCESS_LISTING_UNAVAILABLE` with the reasons `capability_missing`, `identity_evidence_missing`, or `policy_evidence_missing`, which indicate configuration, not load. - Drain the audit table if you deliver audit events elsewhere. - Roll out per resource type, comparing with your existing checks first: see [migrating to sharing](/docs/migrations#adopting-sharing). # Docs for agents and LLMs (/docs/agents) > Give a coding agent or an LLM tool these docs as Markdown, and teach it Rolebook with the skills bundle. These docs are published as plain Markdown as well as HTML, so a coding agent or an LLM tool can read them without scraping the page. The Rolebook skills bundle goes one step further: it teaches an agent the steps to add Rolebook to an app. ## The docs as Markdown [#the-docs-as-markdown] | URL | What it holds | | --- | --- | | [`/llms.txt`](/llms.txt) | An index of every docs page: its title, URL and description, grouped like the sidebar. | | [`/llms-full.txt`](/llms-full.txt) | The full text of every docs page as Markdown, in one file. | | `.md` | One page as Markdown. This page is [`/docs/agents.md`](/docs/agents.md); the introduction is [`/docs.md`](/docs.md). | Each Markdown copy starts with the page title and URL, then the description, then the page body. Code blocks keep their language. On every page, **Copy Markdown** copies that page's Markdown to the clipboard, and the menu next to it opens the Markdown, or opens a chat in an AI tool such as ChatGPT, Claude or Cursor that is asked to read the page. Point an agent at `/llms.txt` when it should pick the pages it needs, or at `/llms-full.txt` when it should read everything up front. ## The skills bundle [#the-skills-bundle] The [Rolebook skills](/docs/agents/skills) are instructions an agent loads when you ask it for a Rolebook task, such as setting up authorization, adding sharing, writing roles, or finding out why a check said no. Each skill names the package versions it supports and uses only the APIs these docs show. [Skills](/docs/agents/skills) has the install commands and one page per skill. # MCP server (/docs/agents/mcp) > rolebook mcp: a Model Context Protocol server that runs next to your own Rolebook server, so an agent can look up and explain access and propose changes you confirm. `rolebook mcp` is a [Model Context Protocol](https://modelcontextprotocol.io) server that runs on your machine, next to the Rolebook server you mount with `@rolebook/server`. Your agent's MCP client starts it as a local process and talks to it on stdin and stdout. It calls your server's [Sharing HTTP API](/docs/http-api), as one identity you configure, and nothing else. It comes with [`@rolebook/cli`](/docs/cli). There is no hosted endpoint in this package. ## Add it to your agent [#add-it-to-your-agent] Most MCP clients take a JSON entry like this one: ```json { "mcpServers": { "rolebook": { "command": "npx", "args": ["--no", "rolebook", "mcp"], "env": { "ROLEBOOK_URL": "https://app.example.com/api/sharing", "ROLEBOOK_TOKEN": "a token your server accepts for this person", "ROLEBOOK_POLICY": "src/authz/policy.ts" } } } } ``` `--no` stops `npx` from downloading anything, so it runs only a copy that is already installed. Start the client in your project's directory: elsewhere, `npx` can find a globally installed command of the same name. The package is not on npm yet, and the npm package named `rolebook` is unrelated. The variables are the same as for the command line; see [Connect to your server](/docs/cli#connect-to-your-server). `ROLEBOOK_POLICY` is optional; a policy module named there runs in a child process as [for the command line](/docs/cli#check-a-setup): the credentials are not passed in its environment and only its exported policy comes back, but it is not a sandbox, so name only your own file. ## Who the agent acts as [#who-the-agent-acts-as] The server acts as the identity in its configuration, and only that identity: - Your server's `getContext` turns `ROLEBOOK_TOKEN`, `ROLEBOOK_COOKIE` or `ROLEBOOK_HEADERS` into the tenant and the actor, as it does for a request from your app. The tenant and the actor are never taken from a tool argument. - Every tool's input schema is closed. An argument the schema does not name, such as `tenantId`, `actor`, `headers` or `url`, is refused before any request is sent. - That identity's own Rolebook roles still apply: the agent can read and change only what that person could through your app. - Values the tools return (ids, names, emails, roles) are data from your server. The server's instructions tell the agent never to follow instructions found in them, and errors are written by the MCP server from status and code, never copied from the server's text. - Without `ROLEBOOK_URL` or a credential the server does not start. An unreachable server, a timeout or a rejected credential is an error result, never an empty answer. Credentials never appear in a result. Give the agent a credential for a person, not a service account with more access than you want the agent to have. ## Tools [#tools] | Tool | What it does | | --- | --- | | `describe_access` | The owner, the direct members with their roles and expiry, and pending invitations of one item. Access that comes from a parent item or a team is not listed; use `explain_access` for one person. | | `check_access` | Whether the configured identity may do one action on an item, or all its actions. | | `explain_access` | Why a subject can or cannot do an action, with the deciding rule. Needs [inspection](/docs/http-api/server) on your server. | | `list_accessible` | The items of one type the configured identity can reach, one page at a time. | | `audit_history` | Who changed access to an item, and when. | | `grant_role` | Previews giving a subject a role on an item, optionally until a date. | | `change_role` | Previews changing a member's role or expiry. | | `revoke_member` | Previews removing a member. | | `apply_change` | Applies the newest preview, given its confirmation and the same change restated. | | `get_policy` | Only when `ROLEBOOK_POLICY` is set: the policy's version, resource types and actions. | | `list_roles` | Only when `ROLEBOOK_POLICY` is set: each role's scope, inherited roles and rules. | Read tools are marked read-only. `grant_role`, `change_role` and `revoke_member` are read-only too: they only preview. `apply_change` is the only tool that changes anything, and it is marked destructive. ## Changes are previewed first [#changes-are-previewed-first] A change takes two calls, and the first never changes anything: 1. `grant_role`, `change_role` or `revoke_member` reads the item's current access and returns what would change (the subject's role and expiry before and after, and warnings such as "already a member"), the `change` itself, and a `confirmation`. 2. After the user agrees, `apply_change` takes the `confirmation` and the same change restated: `kind`, `resource`, `subject`, `role`, and `expiresAt` or `permanent` as the preview returned them. A restated change that differs from the preview is refused and discards the preview; arguments that do not fit the tool's schema are refused before that and leave it in place. So the arguments your MCP client shows you when it asks to run `apply_change` are the change itself, not an opaque id. Only the newest preview can be applied, once, within 10 minutes: a second preview replaces the first, so an agent cannot show you one change and apply another. `apply_change` sends one `sharing.executeIfUnchanged` command carrying the previewed sharing revision, with an idempotency key fixed at preview time, and your server decides whether the identity may make it. The server checks the revision in the same commit as the change, so when anything moved it since the preview, even a moment before the write, nothing is applied and the result is `STALE_PREVIEW`. A server that predates `sharing.executeIfUnchanged`, or a newer one whose sharing runtime does not declare `conditionalExecution`, answers 404 and the result is `PRECONDITION_UNSUPPORTED`; the change is never sent without its revision. If no valid result or 4xx refusal in the Sharing API's error format came back (no answer, a 5xx, a 2xx or 3xx carrying an error, or a body that is not the API's), the result is `OUTCOME_UNKNOWN` and the preview is kept: calling `apply_change` again with the same arguments retries with the same key and revision, so a change that did apply is reported as already applied, not applied twice, and one that did not applies only if nothing else changed the item meanwhile. Set your MCP client to ask before every `apply_change` call: that prompt is where you confirm, and these guarantees hold only if it is shown to you. A membership reaching its expiry does not move the revision. And if your server chooses the tenant from session state that can change, such as an "active team" cookie, keep it fixed while the agent changes access. Invitations and ownership transfers are not available as tools in this version. ## Protocol [#protocol] The server speaks JSON-RPC 2.0, one message per line of at most 1 MiB, and does not accept batches. It answers the `initialize` handshake of the 2025-11-25, 2025-06-18 and 2024-11-05 revisions, and `server/discover` with per-request versions for the 2026-07-28 revision. It offers tools only: no resources, prompts or sampling. ## Not in this version [#not-in-this-version] - A hosted MCP endpoint. A hosted server would belong to Rolebook Console, which is not available yet. - `issue_invitation`: the Sharing API returns the invitation token to the caller, and the MCP server returns no secrets to an agent. - `diff_policy` and `sdk_snippet`. Use [`rolebook policy diff`](/docs/cli#compare-policies) and the [skills](/docs/agents/skills) instead. # Skills (/docs/agents/skills) > Skills that teach your coding agent to add Rolebook authorization and sharing to an app the right way. {/* Generated by website/scripts/generate-skill-pages.ts from skills/. Do not edit. */} The Rolebook skills bundle (`rolebook` 0.1.0) teaches a coding agent to add Rolebook authorization and sharing to an app the right way. It is published to [Amakinto-Labs/rolebook-skills](https://github.com/Amakinto-Labs/rolebook-skills). ## Install [#install] Into every detected agent tool, one tool, or as a dry run, with the `plugins` CLI; or the skills only, with the `skills` CLI (Node 22.20 or later): ```sh # Every detected agent tool. plugins@1.3.6 npx plugins@1.3.6 add Amakinto-Labs/rolebook-skills npx plugins@1.3.6 add Amakinto-Labs/rolebook-skills --target claude-code # one tool: claude-code, cursor, codex, grok, kimi, github-copilot, vscode npx plugins@1.3.6 discover Amakinto-Labs/rolebook-skills # dry run # Skills only, into the current project (add -g for every project). skills@1.7.4, Node 22.20+ npx skills@1.7.4 add Amakinto-Labs/rolebook-skills npx skills@1.7.4 add Amakinto-Labs/rolebook-skills --skill rolebook-setup -a claude-code ``` In Claude Code without either CLI: ```text /plugin marketplace add Amakinto-Labs/rolebook-skills /plugin install rolebook@rolebook ``` ## The skills [#the-skills] | Skill | Name | Does | | --- | --- | --- | | [Set up Rolebook](/docs/agents/skills/rolebook-setup) | `rolebook-setup` | Adds Rolebook authorization to a Next.js or Hono app in TypeScript: a policy file, a session-to-binding loader, trusted resource loaders, and server-side permission checks on routes | | [Add sharing](/docs/agents/skills/rolebook-add-sharing) | `rolebook-add-sharing` | Makes one resource type shareable with Rolebook Sharing: owners, members with roles, invitations to existing users, access that ends on a date, listing what a user can access, and the database tables and server routes it needs | | [Add the screens](/docs/agents/skills/rolebook-add-screens) | `rolebook-add-screens` | Adds sharing screens and permission-aware buttons to an app that already uses Rolebook Sharing: a share dialog with owner, members and invitations, an access history panel, and buttons hidden or disabled when the user cannot use them | | [Write roles](/docs/agents/skills/rolebook-write-roles) | `rolebook-write-roles` | Writes and tests Rolebook roles and rules in the app's policy file, including deny rules, conditions, and field restrictions, with table-driven tests that prove who can and cannot do each action | | [Debug a no](/docs/agents/skills/rolebook-debug-denial) | `rolebook-debug-denial` | Finds out why Rolebook said no to someone and how to fix it, by reproducing the exact check through the app's own loaders and reading its decision code and trace | | [Review before launch](/docs/agents/skills/rolebook-launch-review) | `rolebook-launch-review` | Reviews an app that uses Rolebook for common access-control mistakes before launch and reports each finding with file, line, risk, and fix, changing nothing unless asked | | [Mount the API](/docs/agents/skills/rolebook-mount-api) | `rolebook-mount-api` | Mounts the Rolebook Sharing HTTP API in a Hono or Next.js app with @rolebook/server, taking the tenant and actor from the session, checking origins, and keeping invitation tokens on the server, then calls it from the browser with a typed fetch client | | [Add custom roles](/docs/agents/skills/rolebook-custom-roles) | `rolebook-custom-roles` | Moves an app that uses Rolebook Sharing to versioned policies stored in its own database, so operators can save, preview, and publish policy changes and define custom member roles per tenant within a fixed template | | [Run sharing in production](/docs/agents/skills/rolebook-operate-sharing) | `rolebook-operate-sharing` | Runs Rolebook Sharing safely in production: the storage migrations on every deploy, one scheduled pruning job with alerts, shared secrets across instances, what Rolebook never deletes, and when a rollback is allowed | | [Write a storage adapter](/docs/agents/skills/rolebook-write-adapter) | `rolebook-write-adapter` | Writes a Rolebook Sharing storage adapter for a database the first-party adapters do not cover, and proves it with the @rolebook/sharing-testkit contract suite before any route uses it | Each skill states the package versions it supports, uses only the APIs these docs and its references show, and follows the bundle's shared security rules. # Add the screens (/docs/agents/skills/rolebook-add-screens) > The rolebook-add-screens agent skill. {/* Generated by website/scripts/generate-skill-pages.ts from skills/. Do not edit. */} Adds sharing screens and permission-aware buttons to an app that already uses Rolebook Sharing: a share dialog with owner, members and invitations, an access history panel, and buttons hidden or disabled when the user cannot use them. Use when the user asks for a share button or dialog, a members list, an activity or audit panel, or to hide actions a user is not allowed to take. Skill name: `rolebook-add-screens`. Ask your agent for the task in your own words, or invoke the skill by name where your tool supports it. ## Packages it needs [#packages-it-needs] | Requirement | Package and supported versions | | --- | --- | | Always | `rolebook` `>=4.0.0 <5.0.0` | | Always | `@rolebook/sharing` `>=0.1.0 <0.2.0` | | One of | `@rolebook/sharing-postgres` `>=0.1.0 <0.2.0`, `@rolebook/sharing-sqlite` `>=0.1.0 <0.2.0` | | One of | `@rolebook/sharing-better-auth` `>=0.1.0 <0.2.0`, `@rolebook/sharing-clerk` `>=0.1.0 <0.2.0`, `@rolebook/sharing-workos` `>=0.1.0 <0.2.0` | The skill checks the installed versions against these ranges before it uses each part, and stops rather than up- or downgrading without your consent. ## What it does [#what-it-does] 1. Before you start 2. Check the starting point 3. Hide what people cannot use 4. Build the share dialog 5. Show the history 6. Check your work ## Reference files [#reference-files] The skill loads these files from its `references/` folder when a step needs them: - `buttons.md` - `history.md` - `security-rules.md` - `share-dialog.md` - `sharing-module.md` # Add sharing (/docs/agents/skills/rolebook-add-sharing) > The rolebook-add-sharing agent skill. {/* Generated by website/scripts/generate-skill-pages.ts from skills/. Do not edit. */} Makes one resource type shareable with Rolebook Sharing: owners, members with roles, invitations to existing users, access that ends on a date, listing what a user can access, and the database tables and server routes it needs. Use when the user wants people to share a project, folder, document, or other record with colleagues, invite a user, transfer ownership, give access until a date, or list the records a user can access. Skill name: `rolebook-add-sharing`. Ask your agent for the task in your own words, or invoke the skill by name where your tool supports it. ## Packages it needs [#packages-it-needs] | Requirement | Package and supported versions | | --- | --- | | Always | `rolebook` `>=4.0.0 <5.0.0` | | Always | `@rolebook/sharing` `>=0.1.0 <0.2.0` | | One of | `@rolebook/sharing-postgres` `>=0.1.0 <0.2.0`, `@rolebook/sharing-sqlite` `>=0.1.0 <0.2.0` | | One of | `@rolebook/sharing-better-auth` `>=0.1.0 <0.2.0`, `@rolebook/sharing-clerk` `>=0.1.0 <0.2.0`, `@rolebook/sharing-workos` `>=0.1.0 <0.2.0` | The skill checks the installed versions against these ranges before it uses each part, and stops rather than up- or downgrading without your consent. ## What it does [#what-it-does] 1. Before you start 2. Check the starting point 3. Pick the storage 4. Pick the identity source 5. Extend the policy 6. Prepare the table 7. Wire the module 8. Run the migrations 9. Give every new record an owner 10. Schedule pruning 11. Authorize the existing routes with Sharing 12. Add the sharing routes 13. Test it 14. Check your work ## Reference files [#reference-files] The skill loads these files from its `references/` folder when a step needs them: - `identity.md` - `keys.md` - `module.md` - `policy.md` - `postgres.md` - `routes.md` - `security-rules.md` - `sharing-module.md` - `sqlite.md` - `teams-better-auth.md` - `teams-sql.md` # Add custom roles (/docs/agents/skills/rolebook-custom-roles) > The rolebook-custom-roles agent skill. {/* Generated by website/scripts/generate-skill-pages.ts from skills/. Do not edit. */} Moves an app that uses Rolebook Sharing to versioned policies stored in its own database, so operators can save, preview, and publish policy changes and define custom member roles per tenant within a fixed template. Use when the user wants roles that differ per customer or workspace, a custom role such as an editor who may only edit drafts, policy changes without a redeploy, a preview of who gains or loses access before publishing, or a record of policy versions. Skill name: `rolebook-custom-roles`. Ask your agent for the task in your own words, or invoke the skill by name where your tool supports it. ## Packages it needs [#packages-it-needs] | Requirement | Package and supported versions | | --- | --- | | Always | `rolebook` `>=4.0.0 <5.0.0` | | Always | `@rolebook/sharing` `>=0.1.0 <0.2.0` | | One of | `@rolebook/sharing-postgres` `>=0.1.0 <0.2.0`, `@rolebook/sharing-sqlite` `>=0.1.0 <0.2.0` | | One of | `@rolebook/sharing-better-auth` `>=0.1.0 <0.2.0`, `@rolebook/sharing-clerk` `>=0.1.0 <0.2.0`, `@rolebook/sharing-workos` `>=0.1.0 <0.2.0` | The skill checks the installed versions against these ranges before it uses each part, and stops rather than up- or downgrading without your consent. ## What it does [#what-it-does] 1. Before you start 2. Check the starting point 3. Agree the model with the user 4. Fence the storage 5. Switch the module 6. Add the operator routes 7. Accept custom labels in the sharing routes 8. Test it 9. Check your work ## Reference files [#reference-files] The skill loads these files from its `references/` folder when a step needs them: - `module.md` - `operator.md` - `postgres.md` - `security-rules.md` - `sqlite.md` - `testing.md` # Debug a no (/docs/agents/skills/rolebook-debug-denial) > The rolebook-debug-denial agent skill. {/* Generated by website/scripts/generate-skill-pages.ts from skills/. Do not edit. */} Finds out why Rolebook said no to someone and how to fix it, by reproducing the exact check through the app's own loaders and reading its decision code and trace. Use when a user cannot open, edit, or see something they expect to, or when a check returns NOT_GRANTED, EXPLICIT_DENY, UNKNOWN_ROLE, INVALID_ASSIGNMENT, RESOURCE_MISMATCH, INVALID_REQUEST, or INVALID_SUBJECT. Skill name: `rolebook-debug-denial`. Ask your agent for the task in your own words, or invoke the skill by name where your tool supports it. ## Packages it needs [#packages-it-needs] | Requirement | Package and supported versions | | --- | --- | | Always | `rolebook` `>=4.0.0 <5.0.0` | The skill checks the installed versions against these ranges before it uses each part, and stops rather than up- or downgrading without your consent. ## What it does [#what-it-does] 1. Before you start 2. Pin down the question 3. Reproduce with the app's own loaders 4. Read the answer 5. Missing from a list 6. Propose the fix 7. Check your work ## Reference files [#reference-files] The skill loads these files from its `references/` folder when a step needs them: - `decision-codes.md` - `listing.md` - `reproduce.md` - `security-rules.md` - `sharing-codes.md` # Review before launch (/docs/agents/skills/rolebook-launch-review) > The rolebook-launch-review agent skill. {/* Generated by website/scripts/generate-skill-pages.ts from skills/. Do not edit. */} Reviews an app that uses Rolebook for common access-control mistakes before launch and reports each finding with file, line, risk, and fix, changing nothing unless asked. Use when the user asks for a security or access review, a pre-launch or production-readiness check, or an audit of how roles, tenants, and permission checks are wired. Skill name: `rolebook-launch-review`. Ask your agent for the task in your own words, or invoke the skill by name where your tool supports it. ## Packages it needs [#packages-it-needs] | Requirement | Package and supported versions | | --- | --- | | Always | `rolebook` `>=4.0.0 <5.0.0` | The skill checks the installed versions against these ranges before it uses each part, and stops rather than up- or downgrading without your consent. ## What it does [#what-it-does] 1. Before you start 2. Map the app 3. Run the checklist 4. Report 5. Check your work ## Reference files [#reference-files] The skill loads these files from its `references/` folder when a step needs them: - `checklist.md` - `security-rules.md` # Mount the API (/docs/agents/skills/rolebook-mount-api) > The rolebook-mount-api agent skill. {/* Generated by website/scripts/generate-skill-pages.ts from skills/. Do not edit. */} Mounts the Rolebook Sharing HTTP API in a Hono or Next.js app with @rolebook/server, taking the tenant and actor from the session, checking origins, and keeping invitation tokens on the server, then calls it from the browser with a typed fetch client. Use when the user wants sharing over HTTP, a sharing API for a single-page or mobile frontend, CSRF or CORS settings for that API, or a typed client for share, list, access, and history calls. Skill name: `rolebook-mount-api`. Ask your agent for the task in your own words, or invoke the skill by name where your tool supports it. ## Packages it needs [#packages-it-needs] | Requirement | Package and supported versions | | --- | --- | | Always | `rolebook` `>=4.0.0 <5.0.0` | | Always | `@rolebook/sharing` `>=0.1.0 <0.2.0` | | Always | `@rolebook/server` `>=0.1.0 <0.2.0` | | One of | `@rolebook/sharing-postgres` `>=0.1.0 <0.2.0`, `@rolebook/sharing-sqlite` `>=0.1.0 <0.2.0` | | One of | `@rolebook/sharing-better-auth` `>=0.1.0 <0.2.0`, `@rolebook/sharing-clerk` `>=0.1.0 <0.2.0`, `@rolebook/sharing-workos` `>=0.1.0 <0.2.0` | The skill checks the installed versions against these ranges before it uses each part, and stops rather than up- or downgrading without your consent. ## What it does [#what-it-does] 1. Before you start 2. Check the starting point 3. Agree the model with the user 4. Write the context and the API's sharing 5. Mount it 6. Call it from the browser 7. Other languages 8. Test it 9. Check your work ## Reference files [#reference-files] The skill loads these files from its `references/` folder when a step needs them: - `client.md` - `handler.md` - `hono.md` - `nextjs.md` - `security-rules.md` - `sharing-module.md` # Run sharing in production (/docs/agents/skills/rolebook-operate-sharing) > The rolebook-operate-sharing agent skill. {/* Generated by website/scripts/generate-skill-pages.ts from skills/. Do not edit. */} Runs Rolebook Sharing safely in production: the storage migrations on every deploy, one scheduled pruning job with alerts, shared secrets across instances, what Rolebook never deletes, and when a rollback is allowed. Use when the user asks how to deploy, migrate, or upgrade sharing, schedule or fix pruning, set retention for sharing records or audit history, rotate sharing keys, run several instances, or roll sharing back. Skill name: `rolebook-operate-sharing`. Ask your agent for the task in your own words, or invoke the skill by name where your tool supports it. ## Packages it needs [#packages-it-needs] | Requirement | Package and supported versions | | --- | --- | | Always | `rolebook` `>=4.0.0 <5.0.0` | | Always | `@rolebook/sharing` `>=0.1.0 <0.2.0` | | One of | `@rolebook/sharing-postgres` `>=0.1.0 <0.2.0`, `@rolebook/sharing-sqlite` `>=0.1.0 <0.2.0` | The skill checks the installed versions against these ranges before it uses each part, and stops rather than up- or downgrading without your consent. ## What it does [#what-it-does] 1. Before you start 2. Check the starting point 3. Agree the plan with the user 4. Run the migrations on every deploy 5. Keep the secrets the same everywhere 6. Schedule pruning 7. Know what is never deleted 8. Roll back only when asked 9. Check your work ## Reference files [#reference-files] The skill loads these files from its `references/` folder when a step needs them: - `postgres.md` - `prune-job.md` - `security-rules.md` - `sqlite.md` # Set up Rolebook (/docs/agents/skills/rolebook-setup) > The rolebook-setup agent skill. {/* Generated by website/scripts/generate-skill-pages.ts from skills/. Do not edit. */} Adds Rolebook authorization to a Next.js or Hono app in TypeScript: a policy file, a session-to-binding loader, trusted resource loaders, and server-side permission checks on routes. Use when the user asks to add Rolebook, add roles or permissions, protect routes or server actions, or check who may read or change a record. Skill name: `rolebook-setup`. Ask your agent for the task in your own words, or invoke the skill by name where your tool supports it. ## Packages it needs [#packages-it-needs] | Requirement | Package and supported versions | | --- | --- | | Always | `rolebook` `>=4.0.0 <5.0.0` | The skill checks the installed versions against these ranges before it uses each part, and stops rather than up- or downgrading without your consent. ## What it does [#what-it-does] 1. Before you start 2. Find the framework 3. Agree the model with the user 4. Write the policy 5. Load assignments 6. Load trusted resources 7. Protect the routes 8. Test it 9. Check your work ## Reference files [#reference-files] The skill loads these files from its `references/` folder when a step needs them: - `assignments.md` - `hono.md` - `nextjs.md` - `resources.md` - `security-rules.md` # Write a storage adapter (/docs/agents/skills/rolebook-write-adapter) > The rolebook-write-adapter agent skill. {/* Generated by website/scripts/generate-skill-pages.ts from skills/. Do not edit. */} Writes a Rolebook Sharing storage adapter for a database the first-party adapters do not cover, and proves it with the @rolebook/sharing-testkit contract suite before any route uses it. Use when the user wants Rolebook Sharing on another database or storage layer, asks to implement SharingAdapter, or wants to check that an existing adapter meets the sharing security contract. Skill name: `rolebook-write-adapter`. Ask your agent for the task in your own words, or invoke the skill by name where your tool supports it. ## Packages it needs [#packages-it-needs] | Requirement | Package and supported versions | | --- | --- | | Always | `rolebook` `>=4.0.0 <5.0.0` | | Always | `@rolebook/sharing` `>=0.1.0 <0.2.0` | | Always | `@rolebook/sharing-testkit` `>=0.1.0 <0.2.0` | The skill checks the installed versions against these ranges before it uses each part, and stops rather than up- or downgrading without your consent. ## What it does [#what-it-does] 1. Before you start 2. Check the starting point 3. Agree the model with the user 4. Read the interface 5. Keep these guarantees 6. Run the contract 7. Use it 8. Check your work ## Reference files [#reference-files] The skill loads these files from its `references/` folder when a step needs them: - `contract.md` - `security-rules.md` # Write roles (/docs/agents/skills/rolebook-write-roles) > The rolebook-write-roles agent skill. {/* Generated by website/scripts/generate-skill-pages.ts from skills/. Do not edit. */} Writes and tests Rolebook roles and rules in the app's policy file, including deny rules, conditions, and field restrictions, with table-driven tests that prove who can and cannot do each action. Use when the user asks to add or change a role, a permission, an action, a deny, a condition such as only the owner or only while not archived, a field that some roles cannot see, or tests for roles. Skill name: `rolebook-write-roles`. Ask your agent for the task in your own words, or invoke the skill by name where your tool supports it. ## Packages it needs [#packages-it-needs] | Requirement | Package and supported versions | | --- | --- | | Always | `rolebook` `>=4.0.0 <5.0.0` | The skill checks the installed versions against these ranges before it uses each part, and stops rather than up- or downgrading without your consent. ## What it does [#what-it-does] 1. Before you start 2. Read the current policy 3. Write the change 4. Prove it with tests 5. Show the user 6. Check your work ## Reference files [#reference-files] The skill loads these files from its `references/` folder when a step needs them: - `policy.md` - `security-rules.md` - `testing.md` # rolebook/authoring (/docs/api/authoring) > The exports of the optional authoring entry point - fact schemas, policy diagnostics, and fact validation. `import { ... } from "rolebook/authoring"`. An optional entry point with no peers: `rolebook` never imports it, so an application that does not use it does not load it. For usage, see [Fact schemas](/docs/fact-schemas). Nothing on this page changes what `check`, `enforce`, or `explain` decide, and nothing here is a grant. Validation checks the shape of facts. It cannot prove they are fresh or where they came from. ## Schemas [#schemas] ### `defineFactSchema` [#definefactschema] ```ts api="rolebook/authoring" function defineFactSchema(input: unknown): FactSchema; ``` Validates, copies, normalizes, and deeply freezes a fact schema, and returns the schema handle. Throws a [`FactSchemaError`](#factschemaerror) for malformed input. The input is snapshotted first, without running getters. A non-plain object, an accessor, a symbol key, a cycle, `undefined`, or a non-finite number fails the snapshot, as does going over a bound: 4096 nodes, 32 levels, 64 KiB of serialized UTF-8, 64 keys in an object (256 in `facts`), 128 array elements, or 512 characters in a string. A failed snapshot, or a header that is not exactly `format`, `version`, `id`, and `facts`, is one `INVALID_SCHEMA` diagnostic at the empty pointer. `version` must be `1`; there is no interpretation of later versions. After that, each declaration is checked, in sorted path order, and each bad one is one `INVALID_SCHEMA` diagnostic at `/facts/`. A path is bad when it is not a [fact path](/docs/conditions-and-fields#facts), when it redeclares `subject.type`, `subject.id`, `resource.type`, or `resource.id`, when its declaration is malformed, or when an ancestor of it is a reserved identity or is declared without `object` or `json`. The returned handle's facts are in sorted path order, with `required` always present. The other functions accept only handles that this copy of the module returned. A structurally identical object, including a handle that went through `JSON.stringify`, is not accepted: pass it through `defineFactSchema` again. ### `FactSchema` [#factschema] ```ts api="rolebook/authoring" interface FactSchema { readonly format: "rolebook-fact-schema"; readonly version: 1; readonly id: string; readonly facts: Readonly< Record< FactPath, { readonly types: readonly FactType[]; readonly required: boolean; } > >; } ``` The normalized, frozen schema. `id` is 1 to 64 ASCII characters: a letter, then letters, digits, `_`, or `-`. `facts` holds 0 to 256 declarations. The handle carries no brand property; its origin is tracked privately. ### `FactDeclaration` [#factdeclaration] ```ts api="rolebook/authoring" interface FactDeclaration { readonly types: readonly FactType[]; readonly required?: boolean; } ``` One declaration as written. `types` is a non-empty list of at most 6 distinct types. `required` defaults to `false` and concerns presence, not non-null: a required fact whose value is `null` passes when `"null"` is one of its types. A declaration accepts only these two keys. ### `FactType` [#facttype] ```ts api="rolebook/authoring" type FactType = | "string" | "number" | "boolean" | "null" | "object" | "json" | { readonly array: "string" | "number" | "boolean" | "null" | "json"; }; ``` | Type | A value matches when it is | | --- | --- | | `"string"`, `"number"`, `"boolean"` | That JavaScript type. Numbers are finite. | | `"null"` | `null`. | | `"object"` | A plain object. Not an array, and not `null`. | | `{ array: T }` | An array whose every element matches `T`. `{ array: "json" }` is any array. | | `"json"` | Any value. It must be the declaration's only type. | A declaration has at most one array type. `object` and `json` do not declare their children: a path below them is known only when it is declared itself. ### `FactSchemaError` [#factschemaerror] ```ts api="rolebook/authoring" class FactSchemaError extends Error { readonly code: "INVALID_SCHEMA"; readonly diagnostics: readonly Diagnostic[]; readonly truncated: boolean; constructor(diagnostics: readonly Diagnostic[], truncated: boolean); } ``` Thrown only by `defineFactSchema`. The message is always `Invalid Rolebook fact schema`; the frozen `diagnostics` say where. `name` is `"FactSchemaError"`. ## Policy checks [#policy-checks] ### `analyzePolicy` [#analyzepolicy] ```ts api="rolebook/authoring" function analyzePolicy(policy: unknown, schema: FactSchema): PolicyAnalysis; ``` Calls `definePolicy` once on `policy` and analyses only that frozen result, so changing the input afterwards cannot hide a diagnostic. Never throws. A schema that is not a handle from `defineFactSchema` is one `INVALID_SCHEMA` diagnostic, and a policy `definePolicy` rejects is one `INVALID_POLICY` diagnostic, both at the empty pointer and without the error's text. Otherwise it visits roles in sorted name order and each role's direct rules in order. Inherited rules are analysed once, in the role that defines them. For each rule it reports `DUPLICATE_RULE` when the rule's canonical JSON equals an earlier rule of the same role, then walks the rule's `where`, every node in order, whatever a runtime short circuit would skip. For each comparison it reports an undeclared left fact, then an undeclared fact-reference operand, as `UNKNOWN_FACT`, and, when both are known, an operand type problem as `INCOMPATIBLE_OPERANDS` or `POSSIBLY_UNSUPPORTED_OPERANDS`. The reserved identities are known strings without being declared. ### `compilePolicy` [#compilepolicy] ```ts api="rolebook/authoring" function compilePolicy(policy: unknown, schema: FactSchema): CompilePolicyResult; ``` `analyzePolicy`, plus the compiled policy when there is no error. Warnings do not prevent it. The policy is the object `definePolicy` returned for the same input, so its `canonicalPolicyJson` is the same as defining it without a schema. ### `PolicyAnalysis` [#policyanalysis] ```ts api="rolebook/authoring" interface PolicyAnalysis { readonly ok: boolean; readonly diagnostics: readonly Diagnostic[]; readonly truncated: boolean; } ``` `ok` is `false` when there is any error, including one omitted after the 128-diagnostic cap. `truncated` is `true` when a diagnostic was omitted. The whole result is frozen. ### `CompilePolicyResult` [#compilepolicyresult] ```ts api="rolebook/authoring" type CompilePolicyResult = | { readonly ok: true; readonly policy: RolebookPolicy; readonly diagnostics: readonly Diagnostic[]; readonly truncated: boolean; } | { readonly ok: false; readonly diagnostics: readonly Diagnostic[]; readonly truncated: boolean; }; ``` A failed result has no `policy` property. ## Fact validation [#fact-validation] ### `validateFacts` [#validatefacts] ```ts api="rolebook/authoring" function validateFacts( schema: FactSchema, facts: { readonly subject: Subject; readonly resource: TrustedResource; readonly context?: Readonly>; }, ): ValidateFactsResult; ``` Checks a copy of the facts an application is about to bind against the schema. It performs no authorization, and a passing result is never a grant. Never throws. It first captures `subject`, `resource`, and `context` once and validates them with Core's own snapshot and shape rules, the same ones `bind` and `check` apply. Any structural fault, including an object with other keys, a malformed subject or trusted resource, an `undefined` value anywhere inside, or a value over Core's [limits](/docs/limits), is one `INVALID_FACTS` diagnostic at the empty pointer. An omitted or `undefined` `context` is treated as absent. Then, for each declared path in sorted order, it reads the fact the way Core does, through own properties of plain objects only. The reserved `type` and `id` come from the subject and the resource reference, never from the attribute bags. A required fact that does not resolve is `MISSING_REQUIRED_FACT`; a fact that resolves to a value no declared type matches is `FACT_TYPE_MISMATCH`. An optional fact that does not resolve passes. Undeclared properties pass and are not removed. Pointers are logical, such as `/resource/ownerId` for `resource.ownerId`, and not locations in the input. ### `ValidateFactsResult` [#validatefactsresult] ```ts api="rolebook/authoring" interface ValidateFactsResult { readonly ok: boolean; readonly diagnostics: readonly Diagnostic[]; readonly truncated: boolean; } ``` The same shape and cap as [`PolicyAnalysis`](#policyanalysis). ## Diagnostics [#diagnostics] ### `Diagnostic` [#diagnostic] ```ts api="rolebook/authoring" interface Diagnostic { readonly severity: "error" | "warning"; readonly code: DiagnosticCode; readonly pointer: string; readonly message: string; } ``` `pointer` is an RFC 6901 JSON Pointer relative to the operation's input, not a line or column. `message` is a fixed sentence per code and never contains a path, literal, or value. Its wording may change between versions: key on `code`, `severity`, and `pointer`. ### `DiagnosticCode` [#diagnosticcode] ```ts api="rolebook/authoring" type DiagnosticCode = | "INVALID_SCHEMA" | "INVALID_POLICY" | "UNKNOWN_FACT" | "INCOMPATIBLE_OPERANDS" | "POSSIBLY_UNSUPPORTED_OPERANDS" | "DUPLICATE_RULE" | "INVALID_FACTS" | "MISSING_REQUIRED_FACT" | "FACT_TYPE_MISMATCH"; ``` Each code has one severity. `POSSIBLY_UNSUPPORTED_OPERANDS` and `DUPLICATE_RULE` are warnings; every other code is an error. See the [code table](/docs/fact-schemas#diagnostics). ### `toEditorDiagnostics` [#toeditordiagnostics] ```ts api="rolebook/authoring" function toEditorDiagnostics(diagnostics: readonly Diagnostic[]): readonly EditorDiagnostic[]; ``` Returns a fresh frozen copy of each diagnostic, in order, for an editor integration. It reads no source file and writes nothing. It checks its input without running getters: at most 128 entries, each with exactly the four diagnostic keys, a known code with that code's severity, a valid JSON Pointer of at most 2048 characters, and a non-empty message of at most 160 characters. Anything else throws `TypeError("Invalid diagnostics")`. ### `EditorDiagnostic` [#editordiagnostic] ```ts api="rolebook/authoring" interface EditorDiagnostic { readonly pointer: string; readonly severity: "error" | "warning"; readonly code: DiagnosticCode; readonly message: string; } ``` The pointer is still a JSON Pointer into the policy, schema, or facts, not a source position. Mapping it to a line is the editor's job. # rolebook/middleware/express (/docs/api/express) > The exports of the optional Express middleware entry point. `import { ... } from "rolebook/middleware/express"`. Requires `express` `>=5.1.0 <6`; TypeScript applications also install `@types/express`. Express is an optional peer: the entry point imports only Express types, so `rolebook` alone never loads Express. ```ts prelude=express import express from "express"; import { createRolebookMiddleware } from "rolebook/middleware/express"; const app = express(); const middleware = createRolebookMiddleware({ policy, getBinding: (request) => loadAuthorizationContext(request), }); app.get( "/projects/:id", middleware.requirePermission(async (request) => { const { id } = request.params; return { permission: "project:read", resource: await loadTrustedProject(typeof id === "string" ? id : undefined), }; }), (_request, response) => { response.json({ ok: true }); }, ); // After the routes: Express recognizes an error handler by its four parameters. app.use(middleware.onError); ``` Authenticate before `requirePermission` runs. The adapter does not authenticate sessions or read a binding from headers, `request.user` or `response.locals`. ### `createRolebookMiddleware` [#createrolebookmiddleware] ```ts api="rolebook/middleware/express" function createRolebookMiddleware< TRole extends string, TPermission extends string, TResources extends ResourceDefinitions = ResourceDefinitions, >( options: RolebookMiddlewareOptions, ): RolebookMiddleware>; ``` Creates one authorizer for `options.policy` (with `onEvaluationFault` as its fault reporter) and returns a frozen [`RolebookMiddleware`](#rolebookmiddleware). ### `RolebookMiddleware` [#rolebookmiddleware] ```ts api="rolebook/middleware/express" interface RolebookMiddleware { readonly onError: ErrorRequestHandler; readonly requirePermission: ( check: | CheckRequest | ((request: Request) => CheckRequest | Promise>), ) => RequestHandler; } ``` - **`requirePermission(check)`**: an Express 5 request handler. For each request it gets the authorization (calling `getBinding` and binding, or reusing the request's binding when `reuseBindingPerRequest` is on) and answers `onUnauthorized` when there is none. Otherwise it sets `response.locals.authorization`, resolves `check` (calling it with the request when it is a function), checks it, and answers `onForbidden` on a denial or calls `next()` on an allow. Errors from `getBinding` or the check function reject, and Express 5 passes them to its error pipeline. - **`onError`**: an error handler to mount after the routes. When headers have already been sent it calls `next(error)`. An `AuthorizationError` (from `enforce()` in a handler) becomes `onForbidden`. Any other error goes to `next(error)`, so install the application's own error handler after this one. ### `RolebookMiddlewareOptions` [#rolebookmiddlewareoptions] ```ts api="rolebook/middleware/express" interface RolebookMiddlewareOptions< TRole extends string = string, TPermission extends string = string, TResources extends ResourceDefinitions = ResourceDefinitions, > { readonly policy: RolebookPolicy; readonly getBinding: ( request: Request, ) => BindInput | undefined | Promise | undefined>; readonly onUnauthorized?: (request: Request, response: Response) => unknown | Promise; readonly onForbidden?: (request: Request, response: Response) => unknown | Promise; readonly onEvaluationFault?: InternalErrorReporter; readonly reuseBindingPerRequest?: boolean; } ``` | Option | Behaviour | | --- | --- | | `policy` | The policy every check uses. | | `getBinding` | Loads the binding for the request. `undefined` becomes `onUnauthorized` and is never remembered. | | `onUnauthorized` | Default: `response.status(401).json({ error: "Unauthorized" })`. A replacement must finish the response. | | `onForbidden` | Default: `response.status(403).json({ error: "Forbidden" })`. Used for denied checks and downstream `AuthorizationError`s. A replacement must finish the response. | | `onEvaluationFault` | Passed to `createAuthorizer` as `onInternalError`. A fault still fails closed, so the check still answers 403. | | `reuseBindingPerRequest` | Default `false`. When `true`, bind once per request per middleware instance. Enable only when identity and assignments cannot change during the request. | ### `RolebookLocals` [#rolebooklocals] ```ts api="rolebook/middleware/express" interface RolebookLocals { authorization: BoundAuthorizer< RequestPermission, TPolicy["resources"]> >; } ``` The type of `response.locals` after `requirePermission` allows a request. Use `Response>` in a handler to keep the policy's concrete permission union for further `check()` and `enforce()` calls. It is output for the application: the adapter never reads it back as authority. `PolicyPermission` is an internal helper type: the union of the permissions the policy's rules name. # rolebook/middleware/fastify (/docs/api/fastify) > The exports of the optional Fastify middleware entry point. `import { ... } from "rolebook/middleware/fastify"`. Requires `fastify` `>=5.0.0 <6`, which ships its own TypeScript declarations. Fastify is an optional peer: the entry point imports only Fastify types, so `rolebook` alone never loads Fastify. ```ts prelude=fastify import Fastify from "fastify"; import { createRolebookMiddleware, type RolebookRequest } from "rolebook/middleware/fastify"; const app = Fastify(); app.register(async (routes) => { const middleware = createRolebookMiddleware({ policy, getBinding: (request) => loadAuthorizationContext(request), }); // setErrorHandler, in the same plugin scope as the protected routes. routes.setErrorHandler(middleware.onError); routes.get( "/projects/:id", { preHandler: middleware.requirePermission(async (request) => ({ permission: "project:read", resource: await loadTrustedProject((request.params as { id: string }).id), })), }, async (request) => { const authorization = (request as RolebookRequest).authorization; return { ok: authorization !== undefined }; }, ); }); ``` Authenticate in an earlier hook. The adapter does not authenticate sessions or read a binding from headers or decorated request fields. ### `createRolebookMiddleware` [#createrolebookmiddleware] ```ts api="rolebook/middleware/fastify" function createRolebookMiddleware< TRole extends string, TPermission extends string, TResources extends ResourceDefinitions = ResourceDefinitions, >( options: RolebookMiddlewareOptions, ): RolebookMiddleware>; ``` Creates one authorizer for `options.policy` (with `onEvaluationFault` as its fault reporter) and returns a frozen [`RolebookMiddleware`](#rolebookmiddleware). ### `RolebookMiddleware` [#rolebookmiddleware] ```ts api="rolebook/middleware/fastify" interface RolebookMiddleware { readonly onError: (error: unknown, request: FastifyRequest, reply: FastifyReply) => Promise; readonly requirePermission: ( check: | CheckRequest | (( request: FastifyRequest, ) => CheckRequest | Promise>), ) => (request: FastifyRequest, reply: FastifyReply) => Promise; } ``` - **`requirePermission(check)`**: an async `preHandler`, not an `onRequest` hook. It does nothing when the reply is already sent. Otherwise it gets the authorization (calling `getBinding` and binding, or reusing the request's binding when `reuseBindingPerRequest` is on) and answers `onUnauthorized` when there is none. It then sets `request.authorization`, resolves `check` (calling it with the request when it is a function), checks it, and answers `onForbidden` on a denial. On an allow it returns and the route runs. Errors from `getBinding` or the check function go to Fastify's error pipeline. - **`onError`**: install with `setErrorHandler`, not the `onError` hook, in the plugin scope of the protected routes. It leaves an already-sent reply alone, answers `onForbidden` for an `AuthorizationError`, and rethrows anything else to the parent or default error handler. A responder (`onUnauthorized`, `onForbidden`, or a default) must finish the reply before it settles. When it does not, the adapter throws, so the protected route never runs. ### `RolebookMiddlewareOptions` [#rolebookmiddlewareoptions] ```ts api="rolebook/middleware/fastify" interface RolebookMiddlewareOptions< TRole extends string = string, TPermission extends string = string, TResources extends ResourceDefinitions = ResourceDefinitions, > { readonly policy: RolebookPolicy; readonly getBinding: ( request: FastifyRequest, ) => BindInput | undefined | Promise | undefined>; readonly onUnauthorized?: ( request: FastifyRequest, reply: FastifyReply, ) => unknown | Promise; readonly onForbidden?: ( request: FastifyRequest, reply: FastifyReply, ) => unknown | Promise; readonly onEvaluationFault?: InternalErrorReporter; readonly reuseBindingPerRequest?: boolean; } ``` | Option | Behaviour | | --- | --- | | `policy` | The policy every check uses. | | `getBinding` | Loads the binding for the request. `undefined` becomes `onUnauthorized` and is never remembered. | | `onUnauthorized` | Default: `reply.code(401).send({ error: "Unauthorized" })`. A replacement must finish the reply. | | `onForbidden` | Default: `reply.code(403).send({ error: "Forbidden" })`. Used for denied checks and downstream `AuthorizationError`s. A replacement must finish the reply. | | `onEvaluationFault` | Passed to `createAuthorizer` as `onInternalError`. A fault still fails closed, so the check still answers 403. | | `reuseBindingPerRequest` | Default `false`. When `true`, bind once per request per middleware instance. Enable only when identity and assignments cannot change during the request. | ### `RolebookRequest` [#rolebookrequest] ```ts api="rolebook/middleware/fastify" interface RolebookRequest extends FastifyRequest { authorization?: BoundAuthorizer< RequestPermission, TPolicy["resources"]> >; } ``` The request type after `requirePermission` allows it. `authorization` is optional because a request exists before the `preHandler` runs. Use `RolebookRequest` in a handler to keep the policy's concrete permission union without augmenting every Fastify request. It is output for the application: the adapter never reads it back as authority. `PolicyPermission` is an internal helper type: the union of the permissions the policy's rules name. # rolebook/middleware/hono (/docs/api/hono) > The exports of the optional Hono middleware entry point. `import { ... } from "rolebook/middleware/hono"`. Requires `hono` `>=4.12.34 <5`. For usage, see the [Hono middleware guide](/docs/hono). ### `createRolebookMiddleware` [#createrolebookmiddleware] ```ts api="rolebook/middleware/hono" function createRolebookMiddleware< TRole extends string, TPermission extends string, TResources extends ResourceDefinitions = ResourceDefinitions, >( options: RolebookMiddlewareOptions, ): Readonly<{ onError: (error: unknown, context: Context) => Promise; requirePermission( request: | CheckRequest> | (( context: Context, ) => | CheckRequest> | Promise>>), ): (context: Context, next: Next) => Promise; }>; ``` Creates one authorizer for `options.policy` (with `onEvaluationFault` as its fault reporter) and returns a frozen object with: - **`requirePermission(request)`**: a Hono middleware. For each request it gets the authorization (calling `getBinding` and binding, or reusing the request's binding when `reuseBindingPerRequest` is on), answers `onUnauthorized` when there is none, sets the `authorization` context variable, resolves `request` (calling it with the context when it is a function), checks it, and answers `onForbidden` on a denial or calls `next()` on an allow. Errors thrown by `getBinding` or the request function propagate to Hono's error handler. - **`onError(error, context)`**: an error handler for `app.onError`. An `AuthorizationError` becomes `onForbidden(context)`. An error with a `getResponse()` method returning a `Response` (Hono's `HTTPException`) keeps that response. Anything else is reported to `onInternalError` and answered with `context.text("Internal Server Error", 500)`. When classifying the error or building the response throws, both errors are reported and the answer is the same 500. It always returns a promise. ### `RolebookMiddlewareOptions` [#rolebookmiddlewareoptions] ```ts api="rolebook/middleware/hono" interface RolebookMiddlewareOptions< TRole extends string = string, TPermission extends string = string, TResources extends ResourceDefinitions = ResourceDefinitions, > { readonly policy: RolebookPolicy; readonly getBinding: ( context: Context, ) => BindInput | undefined | Promise | undefined>; readonly onUnauthorized?: (context: Context) => Response | Promise; readonly onForbidden?: (context: Context) => Response | Promise; readonly onInternalError?: (error: unknown, context: Context) => void; readonly onEvaluationFault?: InternalErrorReporter; readonly reuseBindingPerRequest?: boolean; } ``` | Option | Behaviour | | --- | --- | | `policy` | The policy every check uses. | | `getBinding` | Loads the binding for the request. `undefined` becomes `onUnauthorized` and is never remembered. | | `onUnauthorized` | Default: `context.json({ error: "Unauthorized" }, 401)`. | | `onForbidden` | Default: `context.json({ error: "Forbidden" }, 403)`. Used for denied checks and downstream `AuthorizationError`s. | | `onInternalError` | Default: `console.error(error)`. Diagnostics only: a throwing or rejecting reporter is ignored. | | `onEvaluationFault` | Passed to `createAuthorizer` as `onInternalError`. A fault still fails closed, so the check still answers 403. | | `reuseBindingPerRequest` | Default `false`. When `true`, bind once per request per middleware instance; see [reuse](/docs/hono#reusing-the-binding-per-request). | ### `RolebookEnv` [#rolebookenv] ```ts api="rolebook/middleware/hono" interface RolebookEnv extends Env { Variables: { authorization: BoundAuthorizer< RequestPermission, TPolicy["resources"]> >; }; } ``` The Hono environment that types the `authorization` context variable set by `requirePermission`. Use `new Hono>()`. `PolicyPermission` is an internal helper type: the union of the permissions the policy's rules name. # rolebook (/docs/api) > Every export of the rolebook package, with its signature and behaviour. `import { ... } from "rolebook"`. The [Hono middleware](/docs/api/hono) is a separate entry point, `rolebook/middleware/hono`. The optional [authoring checks](/docs/api/authoring) are another, `rolebook/authoring`. Signatures on this page are checked against the package's built declarations. ## Policies [#policies] ### `definePolicy` [#definepolicy] ```ts api="rolebook" function definePolicy< const R extends ResourceDefinitions, const Roles extends Record< string, RoleDefinition, ResourceNames> >, >(policy: { readonly version?: string; readonly resources: R & CheckedResources; readonly roles: Roles & CheckedRoles, ResourceNames>; }): Readonly, PolicyPermissionFromResources, R>>; ``` Validates, canonicalizes, compiles, and deeply freezes a policy, and returns the frozen canonical policy. The type parameters infer the literal resource, action, and role names, so rule permissions, role scopes, `parent` names, and inherited role names are checked at compile time. Throws a `PolicyError` for a malformed or inconsistent policy, or one over a [limit](/docs/limits). The error extends `Error`, its message starts with `Invalid Rolebook policy:`, and it carries a stable `code` and a `location` (`resource`, `role`, `rule`, `condition`) naming where the problem is. The returned object's compiled form and shared authorizer are cached by identity: define a policy once and reuse it. See [Policies](/docs/policies). ### `diffPolicies` [#diffpolicies] ```ts api="rolebook" function diffPolicies(from: RolebookPolicy, to: RolebookPolicy): PolicyDiff; ``` Returns the structural difference between two policies as a frozen [`PolicyDiff`](#policydiff). Both inputs are compiled first, so an invalid policy throws the same `PolicyError` as `definePolicy()`. Names in `added` and `removed` lists are sorted. Rule changes compare direct rules as a multiset of canonical rule JSON, and effective (inherited plus direct) rules separately. ### `canonicalPolicyJson` [#canonicalpolicyjson] ```ts api="rolebook" function canonicalPolicyJson(policy: RolebookPolicy): string; ``` The deterministic serialization of a policy's meaning: the compiled policy without its `version` label, every object's keys sorted by UTF-16 code unit, arrays in their order, no whitespace. Two policies with equal canonical JSON evaluate identically. Throws the same `Error` as `definePolicy()` for an invalid policy. `@rolebook/sharing` digests this string to identify policy versions. ### `canonicalValueJson` [#canonicalvaluejson] ```ts api="rolebook" function canonicalValueJson(value: unknown): string; ``` The same writer applied to an already validated JSON-like value: `null`, a boolean, a finite number, a string, a dense array, or a plain object. Object keys are sorted. Throws a `TypeError` for anything else, including `undefined`, a non-finite number, a function, an accessor property, a cycle, or a non-plain object. It never calls `toJSON`. ## Authorizers [#authorizers] ### `createAuthorizer` [#createauthorizer] ```ts api="rolebook" function createAuthorizer< TRole extends string, TPermission extends string, TResources extends ResourceDefinitions = ResourceDefinitions, >( policy: RolebookPolicy, options?: AuthorizerOptions, ): Authorizer>; ``` Compiles the policy (or reuses its cached compilation) and returns a frozen [`Authorizer`](#authorizer). Without `options.onInternalError`, the authorizer is shared per policy object: calling `createAuthorizer(policy)` again returns the same instance. With a reporter, each call returns a new authorizer, still on the cached compilation. Throws like `definePolicy()` for an invalid policy. ### `check` [#check] ```ts api="rolebook" function check< TRole extends string, TPermission extends string, TResources extends ResourceDefinitions = ResourceDefinitions, >( policy: RolebookPolicy, request: AuthorizationRequest>, ): AuthorizationDecision; ``` One-shot form of `createAuthorizer(policy).bind(binding).check(request)`, taking the binding and the check fields in one object. Never throws for malformed runtime input. A request with any key other than the binding keys and `permission`, `resource`, `field` is `INVALID_REQUEST`. ### `enforce` [#enforce] ```ts api="rolebook" function enforce< TRole extends string, TPermission extends string, TResources extends ResourceDefinitions = ResourceDefinitions, >( policy: RolebookPolicy, request: AuthorizationRequest>, ): AuthorizationDecision; ``` One-shot `enforce`: returns the allowed decision, or throws [`AuthorizationError`](#authorizationerror) carrying the denial. ### `explain` [#explain] ```ts api="rolebook" function explain< TRole extends string, TPermission extends string, TResources extends ResourceDefinitions = ResourceDefinitions, >( policy: RolebookPolicy, request: AuthorizationRequest>, options?: ExplainOptions, ): DecisionExplanation; ``` One-shot `explain`: the decision plus a bounded trace of evaluated rules. `options` is inspected only after the request snapshot is fixed. See [Decisions](/docs/decisions#explain). ### `prepareAssignments` [#prepareassignments] ```ts api="rolebook" function prepareAssignments( value: readonly RoleAssignment[], ): readonly RoleAssignment[] | undefined; function prepareAssignments(value: unknown): readonly RoleAssignment[] | undefined; ``` Validates and deep-freezes an assignment collection once, so repeated bindings over the same principal reuse the copy instead of making a new one per `bind()`. Passing the result to `bind()` is equivalent to passing the original: every entry is still validated, and the assignment count and node budgets still apply across reused and fresh entries together. Returns `undefined` for a collection that would not bind; keep your original value then and let `bind()` return its usual closed decision. See [reusing a validated collection](/docs/subjects-and-assignments#reusing-a-validated-collection). ### `trustedResource` [#trustedresource] ```ts api="rolebook" function trustedResource( ref: ResourceRef, ancestors?: readonly ResourceRef[], attributes?: Readonly>, ): TrustedResource; ``` Creates a deeply frozen, caller-attested resource snapshot. `ancestors` defaults to `[]` and `attributes` to `{}`. Throws an `Error` when the reference, ancestry, or attributes are malformed or over the snapshot limits. It records no provenance: load every input authoritatively. See [trusted resources](/docs/trusted-resources). ## Errors [#errors] ### `AuthorizationError` [#authorizationerror] ```ts api="rolebook" class AuthorizationError extends Error { readonly decision: AuthorizationDecision; constructor(decisionResult: AuthorizationDecision); } ``` Thrown by every `enforce()` on a denial. `name` is `"AuthorizationError"`, `message` is the decision's `reason`, and `decision` is the full denial. Test for it with `instanceof`. ### `PolicyError` [#policyerror] ```ts api="rolebook" class PolicyError extends Error { readonly code: PolicyErrorCode; readonly location: PolicyErrorLocation; constructor(message: string, code: PolicyErrorCode, location?: PolicyErrorLocation); } ``` Thrown by `definePolicy()`, `createAuthorizer()`, and every other entry point that compiles a policy. `name` is `"PolicyError"`. The message starts with `Invalid Rolebook policy:` and ends with the location when one applies, such as `(role "member", rule 1)`. Branch on `code`, not on the message text. ### `PolicyErrorCode` [#policyerrorcode] ```ts api="rolebook" type PolicyErrorCode = | "MALFORMED_POLICY" | "MALFORMED_RESOURCE" | "MALFORMED_ROLE" | "MALFORMED_RULE" | "MALFORMED_CONDITION" | "TOO_MANY_ROLES" | "TOO_MANY_RULES" | "COMPILED_LIMIT_EXCEEDED"; ``` The stable classification of a policy error. The `MALFORMED_*` codes name the part of the policy that is invalid. The other three report a [limit](/docs/limits). ### `PolicyErrorLocation` [#policyerrorlocation] ```ts api="rolebook" interface PolicyErrorLocation { readonly resource?: string; readonly role?: string; readonly rule?: number; readonly condition?: string; } ``` Where in the policy the error was raised. Each field is present only when it applies. `rule` is the zero-based index of the rule in its role, and `condition` is a JSON Pointer from `/where`. ## Constants [#constants] ### `MAX_PRINCIPALS` [#max_principals] ```ts api="rolebook" const MAX_PRINCIPALS: 64; ``` The most group principals one binding may carry beside its subject. ## Authorizer types [#authorizer-types] ### `Authorizer` [#authorizer] ```ts api="rolebook" interface Authorizer { bind(input: BindInput): BoundAuthorizer; check(request: AuthorizationRequest): AuthorizationDecision; enforce(request: AuthorizationRequest): AuthorizationDecision; explain( request: AuthorizationRequest, options?: ExplainOptions, ): DecisionExplanation; } ``` `bind()` snapshots and validates a binding once and returns a [`BoundAuthorizer`](#boundauthorizer). A binding that fails validation still returns a bound authorizer, whose every check returns the binding's denial. `check`, `enforce`, and `explain` are the one-shot forms. ### `BoundAuthorizer` [#boundauthorizer] ```ts api="rolebook" interface BoundAuthorizer { check(request: CheckRequest): AuthorizationDecision; enforce(request: CheckRequest): AuthorizationDecision; explain(request: CheckRequest, options?: ExplainOptions): DecisionExplanation; } ``` Checks against one binding. `check` never throws for malformed input; `enforce` throws `AuthorizationError` on denial; `explain` adds a trace. See [Decisions](/docs/decisions). ### `AuthorizerOptions` [#authorizeroptions] ```ts api="rolebook" interface AuthorizerOptions { readonly onInternalError?: InternalErrorReporter; } ``` ### `InternalErrorReporter` [#internalerrorreporter] ```ts api="rolebook" type InternalErrorReporter = ( error: unknown, context: { readonly permission: string; }, ) => void; ``` Called when evaluation itself throws. The decision is still a closed `INVALID_REQUEST`. The reporter runs synchronously and cannot influence the decision; a throw or a rejected promise from it is ignored, and returned promises are not awaited. It is not called for ordinary malformed input. ### `BindInput` [#bindinput] ```ts api="rolebook" interface BindInput { readonly subject: Subject; readonly principals?: readonly ResourceRef[]; readonly assignments: readonly RoleAssignment[]; readonly context?: Readonly>; } ``` The binding: see [subjects, principals, and assignments](/docs/subjects-and-assignments). Only these keys are accepted. `principals` and `context` may be omitted or `undefined`. ### `CheckRequest` [#checkrequest] ```ts api="rolebook" interface CheckRequest { readonly permission: TPermission; readonly resource: TrustedResource; readonly field?: string; } ``` One check: a concrete permission, a trusted resource of that permission's type, and an optional field path. An omitted and an `undefined` field both mean a resource-wide check. ### `AuthorizationRequest` [#authorizationrequest] ```ts api="rolebook" interface AuthorizationRequest extends BindInput, CheckRequest {} ``` A binding and a check in one object, for the one-shot functions. ## Decision types [#decision-types] ### `AuthorizationDecision` [#authorizationdecision] ```ts api="rolebook" interface AuthorizationDecision { readonly allowed: boolean; readonly code: DecisionCode; readonly reason: string; readonly permission: string; readonly policyVersion?: string; readonly matched?: MatchedRule; } ``` The frozen result of every check. `permission` is empty when the requested permission was not a string of at most 257 characters. `policyVersion` is present when the policy has a `version`. `matched` is present on `ALLOWED` and `EXPLICIT_DENY`. ### `DecisionCode` [#decisioncode] ```ts api="rolebook" type DecisionCode = | "ALLOWED" | "INVALID_REQUEST" | "INVALID_SUBJECT" | "INVALID_ASSIGNMENT" | "UNKNOWN_ROLE" | "RESOURCE_MISMATCH" | "EXPLICIT_DENY" | "NOT_GRANTED"; ``` See [decision codes](/docs/decisions#decision-codes) and [evaluation order](/docs/evaluation). ### `MatchedRule` [#matchedrule] ```ts api="rolebook" interface MatchedRule { readonly effect: "allow" | "deny"; readonly role: string; readonly permission: string; readonly via?: ResourceRef; } ``` The rule that decided. `role` is the role that defines the rule (for an inherited rule, the inherited role). `permission` is the rule's permission, which may be a wildcard. `via` names the group principal whose assignment contributed the rule; it is absent when the subject holds the rule directly. ### `ExplainOptions` [#explainoptions] ```ts api="rolebook" interface ExplainOptions { readonly detail?: "conditions"; } ``` Only a runtime object whose single own enumerable data property is `detail: "conditions"` selects condition detail. Every other value keeps the rule-only explanation. ### `ConditionTraceResult` [#conditiontraceresult] ```ts api="rolebook" type ConditionTraceResult = true | false | "unknown"; ``` ### `ConditionTraceReasonCode` [#conditiontracereasoncode] ```ts api="rolebook" type ConditionTraceReasonCode = | "SATISFIED" | "UNSATISFIED" | "MISSING_FACT" | "MISSING_OPERAND_FACT" | "UNSUPPORTED_OPERANDS"; ``` ### `RuleTraceReasonCode` [#ruletracereasoncode] ```ts api="rolebook" type RuleTraceReasonCode = | "PERMISSION_MISMATCH" | "FIELD_MISMATCH" | "CONDITION_FALSE" | "CONDITION_UNKNOWN_ALLOW" | "CONDITION_UNKNOWN_DENY" | "MATCHED"; ``` ### `ConditionTraceLeaf` [#conditiontraceleaf] ```ts api="rolebook" interface ConditionTraceLeaf { readonly kind: "leaf"; readonly path: string; readonly operator: ValueOperator | "exists"; readonly fact: FactPath; readonly operandFact?: FactPath; readonly operandEvaluated?: boolean; readonly result: ConditionTraceResult; readonly reasonCode: ConditionTraceReasonCode; } ``` ### `ConditionTraceLogical` [#conditiontracelogical] ```ts api="rolebook" interface ConditionTraceLogical { readonly kind: "logical"; readonly path: string; readonly operator: "all" | "any" | "none" | "not"; readonly result: ConditionTraceResult; readonly children: readonly ConditionTraceNode[]; readonly skippedChildren: number; readonly childrenTruncated: boolean; } ``` ### `ConditionTraceNode` [#conditiontracenode] ```ts api="rolebook" type ConditionTraceNode = ConditionTraceLeaf | ConditionTraceLogical; ``` ### `RuleConditionTrace` [#ruleconditiontrace] ```ts api="rolebook" type RuleConditionTrace = | { readonly status: "absent" } | { readonly status: "not_evaluated"; readonly reasonCode: "PERMISSION_MISMATCH" | "FIELD_MISMATCH"; } | { readonly status: "evaluated"; readonly result: ConditionTraceResult; readonly tree?: ConditionTraceNode; readonly truncated: boolean; }; ``` ### `DecisionTraceDetails` [#decisiontracedetails] ```ts api="rolebook" interface DecisionTraceDetails { readonly ruleId: string; readonly reasonCode: RuleTraceReasonCode; readonly condition: RuleConditionTrace; } ``` `ruleId` is the defining role and rule index in the compiled policy snapshot, such as `reader:0`. It is not stable across rule reordering and it is not an assignment id. ### `DecisionExplanation` [#decisionexplanation] ```ts api="rolebook" interface DecisionExplanation extends AuthorizationDecision { readonly trace: readonly DecisionTraceEntry[]; readonly traceTruncated: boolean; readonly conditionTraceTruncated?: boolean; readonly optionsRejected?: true; } ``` `conditionTraceTruncated` is present only when condition detail was accepted. `optionsRejected` is present, and `true`, only when `explain()` received an options value it does not accept; the explanation is then rule-only and the decision is unaffected. ### `DecisionTraceEntry` [#decisiontraceentry] ```ts api="rolebook" interface DecisionTraceEntry { readonly outcome: "matched" | "not_matched"; readonly effect: "allow" | "deny"; readonly role: string; readonly permission: string; readonly reason: string; readonly via?: ResourceRef; readonly details?: DecisionTraceDetails; } ``` One evaluated rule. The trace lists denies before allows and stops at the first match; it holds at most 64 entries. `details` is present on every retained rule when condition detail was accepted, and absent otherwise. ## Policy types [#policy-types] ### `RolebookPolicy` [#rolebookpolicy] ```ts api="rolebook" interface RolebookPolicy< TRole extends string = string, TPermission extends string = string, TResources extends ResourceDefinitions = ResourceDefinitions, > { readonly version?: string; readonly resources: TResources; readonly roles: Record>; } ``` ### `ResourceDefinition` [#resourcedefinition] ```ts api="rolebook" interface ResourceDefinition { readonly actions: readonly TAction[]; readonly parent?: TParent; readonly recursive?: true; } ``` `recursive: true` lets resources of the type nest under resources of the same type. It is the only accepted value; omit the key otherwise. See [Recursive resource types](/docs/policies#recursive-resource-types). ### `ResourceDefinitions` [#resourcedefinitions] ```ts api="rolebook" type ResourceDefinitions = Record; ``` ### `RoleDefinition` [#roledefinition] ```ts api="rolebook" interface RoleDefinition< TRole extends string = string, TPermission extends string = string, TScope extends string = string, > { readonly scope: TScope; readonly inherits?: readonly TRole[]; readonly rules: readonly PolicyRule[]; } ``` ### `PolicyRule` [#policyrule] ```ts api="rolebook" interface PolicyRule { readonly effect: "allow" | "deny"; readonly permission: TPermission; readonly where?: PolicyCondition; readonly fields?: readonly string[]; } ``` ### `PolicyCondition` [#policycondition] ```ts api="rolebook" type PolicyCondition = | { readonly fact: FactPath; readonly operator: ValueOperator; readonly value: ConditionValue; } | { readonly fact: FactPath; readonly operator: "exists"; readonly value?: boolean; } | { readonly all: readonly PolicyCondition[]; } | { readonly any: readonly PolicyCondition[]; } | { readonly none: readonly PolicyCondition[]; } | { readonly not: PolicyCondition; }; ``` See [conditions](/docs/conditions-and-fields#conditions). ### `ValueOperator` [#valueoperator] ```ts api="rolebook" type ValueOperator = | "equals" | "notEquals" | "oneOf" | "noneOf" | "contains" | "containsAll" | "sizeEquals" | "startsWith" | "endsWith" | "lessThan" | "lessThanOrEqual" | "greaterThan" | "greaterThanOrEqual"; ``` ### `ConditionValue` [#conditionvalue] ```ts api="rolebook" type ConditionValue = PolicyLiteral | FactReference; ``` ### `PolicyLiteral` [#policyliteral] ```ts api="rolebook" type PolicyLiteral = | null | boolean | number | string | readonly PolicyLiteral[] | ({ readonly [key: string]: PolicyLiteral; } & { readonly fact?: never; }); ``` A literal object cannot have a `fact` key. That key is reserved for a [`FactReference`](#factreference), and the compiler rejects it in a literal at any depth. ### `FactPath` [#factpath] ```ts api="rolebook" type FactPath = `subject.${string}` | `resource.${string}` | `context.${string}`; ``` ### `FactReference` [#factreference] ```ts api="rolebook" interface FactReference { readonly fact: FactPath; } ``` A condition operand that reads another fact, such as `{ fact: "subject.id" }`. It must be an object with exactly the `fact` key. ### `PermissionFromResources` [#permissionfromresources] ```ts api="rolebook" type PermissionFromResources = { [K in keyof R & string]: `${K}:${R[K]["actions"][number] & string}`; }[keyof R & string]; ``` Every concrete `resource:action` a resource map declares. ### `PolicyPermissionFromResources` [#policypermissionfromresources] ```ts api="rolebook" type PolicyPermissionFromResources = | PermissionFromResources | { [K in keyof R & string]: `${K}:*`; }[keyof R & string]; ``` Every permission a rule may name: the concrete permissions plus one `resource:*` wildcard per type. ### `ConcretePermission` [#concretepermission] ```ts api="rolebook" type ConcretePermission = TPermission extends `${string}:*` ? never : TPermission; ``` Removes wildcards from a permission union. ### `RequestPermission` [#requestpermission] ```ts api="rolebook" type RequestPermission< TPermission extends string, TResources extends ResourceDefinitions = ResourceDefinitions, > = string extends keyof TResources ? ConcretePermission : PermissionFromResources | ConcretePermission; ``` The permissions a request may name: every declared concrete permission, never a wildcard. ### `PolicyDiff` [#policydiff] ```ts api="rolebook" interface PolicyDiff { readonly identical: boolean; readonly version?: { readonly from?: string; readonly to?: string; }; readonly resources: { readonly added: readonly string[]; readonly removed: readonly string[]; readonly changed: readonly ResourceDefinitionChange[]; }; readonly roles: { readonly added: readonly string[]; readonly removed: readonly string[]; readonly changed: readonly RoleDefinitionChange[]; }; } ``` `identical` is true when the canonical policy JSON of both sides is equal. `version` is present only when the labels differ; an absent side means no label. ### `ResourceDefinitionChange` [#resourcedefinitionchange] ```ts api="rolebook" interface ResourceDefinitionChange { readonly resourceType: string; readonly actionsAdded: readonly string[]; readonly actionsRemoved: readonly string[]; readonly parent?: { readonly from?: string; readonly to?: string; }; readonly recursive?: { readonly from?: true; readonly to?: true; }; } ``` `parent` is present only when the parent changed; an absent side means no parent. `recursive` is present only when the `recursive` flag changed; an absent side means the type is not recursive. Turning the flag on changes which resources an assignment can reach, so a diff that only toggles it is still not `identical`. ### `RoleDefinitionChange` [#roledefinitionchange] ```ts api="rolebook" interface RoleDefinitionChange { readonly role: string; readonly scope?: { readonly from: string; readonly to: string; }; readonly inheritsAdded: readonly string[]; readonly inheritsRemoved: readonly string[]; readonly rulesAdded: readonly PolicyRule[]; readonly rulesRemoved: readonly PolicyRule[]; readonly rulesReordered: boolean; readonly effectiveRulesAdded: readonly PolicyRule[]; readonly effectiveRulesRemoved: readonly PolicyRule[]; } ``` `scope` is present only when the scope changed. `rulesReordered` is true when the direct rules are the same multiset in a different order. The `effectiveRules*` lists compare inherited plus direct rules. ## Subjects and resources [#subjects-and-resources] ### `Subject` [#subject] ```ts api="rolebook" interface Subject { readonly type: string; readonly id: string; readonly attributes?: Readonly>; } ``` ### `ResourceRef` [#resourceref] ```ts api="rolebook" interface ResourceRef { readonly type: string; readonly id: string; } ``` A `{ type, id }` reference with exactly those keys. `type` is a policy name; `id` is an opaque string of 1 to 128 characters. ### `RoleAssignment` [#roleassignment] ```ts api="rolebook" interface RoleAssignment { readonly subject: ResourceRef; readonly role: TRole; readonly scope: { readonly resource: ResourceRef; readonly appliesTo: "self" | "descendants"; }; } ``` ### `TrustedResource` [#trustedresource-1] ```ts api="rolebook" interface TrustedResource { readonly ref: ResourceRef; readonly ancestors: readonly ResourceRef[]; readonly attributes: Readonly>; } ``` Build it with [`trustedResource()`](#trustedresource). The type proves shape only, not provenance. # Better Auth plugin (/docs/better-auth) > @rolebook/better-auth: Rolebook Sharing as a Better Auth 1.7.14 plugin, with a client plugin and React bindings. `@rolebook/better-auth` serves the Sharing operations from the Better Auth session. The actor is the signed-in user and the tenant is the session's active organization, read from Better Auth's authoritative session; nothing in a request body, a client-side scope or a `customSession` projection selects them. Decoding, decisions, fences and error mapping are the existing ones of `@rolebook/sharing`, its SQL adapters and `@rolebook/server/core`. | Entry | Use | | --- | --- | | `@rolebook/better-auth` | Server: `createBetterAuthSharing`, `rolebook`, `getRolebook`, `getRolebookMigrations` | | `@rolebook/better-auth/postgres` | Server only: `createPostgresBetterAuthSharing`, the PostgreSQL-bound kit factory with `PostgresSharingAdapter` adapters | | `@rolebook/better-auth/sqlite` | Server only: `createSqliteBetterAuthSharing`, the SQLite-bound kit factory with `SqliteSharingAdapter` adapters | | `@rolebook/better-auth/client` | Browser: `rolebookClient`, `createScopeController` | | `@rolebook/better-auth/react` | Browser: `RolebookSharingProvider`, `useRolebookScope`, `useCan` | > **Not on npm yet.** The `@rolebook/*` packages are not on npm yet. The npm package named `rolebook` is an unrelated project, so do not install it. It needs `better-auth` `>=1.7.14 <1.8` with the organization plugin and server-side sessions, and the application installs the mandatory `@rolebook/sharing` peer, the SQL adapter it uses, and for the browser entries `@rolebook/client`, `nanostores` and (React) `@rolebook/react` with `react` `>=18.3 <20`. ## Set up on PostgreSQL [#set-up-on-postgresql] Build the kit before `betterAuth()`: nothing in it needs the `auth` object. Better Auth and Rolebook use the very same `pg` pool. `storage.executor` must be the very object `createPgExecutor(pool)` returns. Strict listing (`sharing.listAccessible`) opens its read-only page only on that checked executor. With a proxy or wrapper in its place, every page answers `503 ACCESS_LISTING_UNAVAILABLE` (`capability_missing`). ```ts import { createBetterAuthSharing, getRolebookMigrations, rolebook } from "@rolebook/better-auth"; import { createHmacInvitationTokens } from "@rolebook/sharing"; import { createPgExecutor } from "@rolebook/sharing-postgres"; import { betterAuth } from "better-auth"; import { organization } from "better-auth/plugins"; import pg from "pg"; import { definePolicy, trustedResource } from "rolebook"; const policy = definePolicy({ version: "1", resources: { workspace: { actions: ["read"] }, project: { parent: "workspace", actions: ["read", "update", "share"] }, }, roles: { project_owner: { scope: "project", rules: [{ effect: "allow", permission: "project:*" }] }, project_editor: { scope: "project", rules: [ { effect: "allow", permission: "project:read" }, { effect: "allow", permission: "project:update" }, ], }, }, }); const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); export const kit = await createBetterAuthSharing({ storage: { dialect: "postgres", pool, executor: createPgExecutor(pool) }, definition: { policy, resources: { project: { memberRoles: { editor: "project_editor" }, ownershipRole: "project_owner", actions: { read: "project:read", update: "project:update", share: "project:share" }, management: { members: "project:share", invitations: "project:share", ownership: "project:share" }, }, }, }, descriptors: { project: { resourceType: "project", table: ["app", "project"], tenantColumn: "workspace_id", idColumn: "id", resourceVersionColumn: "version", sharingTablePrefix: "project", resourceFromRow: (row) => trustedResource({ type: "project", id: String(row.id) }, [ { type: "workspace", id: String(row.workspace_id) }, ]), }, }, invitationTokens: createHmacInvitationTokens(process.env.ROLEBOOK_INVITATION_KEY ?? ""), listingCursorKey: process.env.ROLEBOOK_LISTING_CURSOR_KEY ?? "", }); export const auth = betterAuth({ database: pool, // the same pool object emailAndPassword: { enabled: true }, plugins: [organization(), rolebook(kit)], }); // Better Auth's own migration, then the application's tables, then Rolebook's explicit plan. await (await auth.$context).runMigrations(); await pool.query( "CREATE TABLE IF NOT EXISTS app.project (workspace_id text NOT NULL, id text NOT NULL, version text NOT NULL, PRIMARY KEY (workspace_id, id))", ); await getRolebookMigrations(auth).apply(); ``` The keys come from your secret store (`generateListingCursorKey()` and the invitation-token key generator of `@rolebook/sharing`); the factory refuses an empty listing key. The kit's identity reads Better Auth's `member` and `user` rows (and, with teams, `team` and `teamMember`) through the Rolebook executor. Strict `sharing.listAccessible` pages resolve the actor with the same function inside the page's own read-only transaction, so a page always reflects Better Auth's rows as of that page. A malformed Better Auth directory fails the page closed (`503 ACCESS_LISTING_UNAVAILABLE`). ### Versioned policy [#versioned-policy] With `storage.policyStore`, the kit is registered before it is initialized: building it, registering `rolebook(kit)` and serving requests read, seed and migrate nothing. Keep the same order: Better Auth's migration, the application's tables, then `getRolebookMigrations(auth).apply()`. `apply()` does the following: 1. It runs the idempotent policy-store and sharing steps. 2. It builds the versioned Sharing instance, which seeds and activates the policy on an empty store. 3. It publishes Sharing, the core and the `":"` label together. Concurrent calls share one attempt. A failed call can be repeated, and a later call never seeds again. Until then, and after `kit.close()`: - operations, and `GET /rolebook/scope` for a session with an active organization, answer `503 SHARING_SCHEMA_UNAVAILABLE`; - `kit.sharing`, `kit.core`, `kit.policyLabel()` and `getRolebook(auth).forRequest()` throw `RolebookConfigurationError` with the code `MIGRATIONS_PENDING`, or `KIT_CLOSED` after close. A missing session is still `401`, and no active organization is still `no_active_organization`. `rolebook(kit)` accepts only a kit `createBetterAuthSharing()` built. Its `init` runs no SQL and refuses, with a `RolebookConfigurationError` code: an adapter-backed database or a Better Auth without its built-in Kysely database (`ADAPTER_UNSUPPORTED`), stateless sessions (`STATELESS_SESSIONS_UNSUPPORTED`), a database object other than the kit's (`DATABASE_MISMATCH`), a missing organization plugin (`ORGANIZATION_PLUGIN_REQUIRED`), and a Better Auth model named like a Rolebook table (`MODEL_NAME_COLLISION`). `better-auth/minimal` given a database object fails in Better Auth itself ("Direct database connection requires Kysely") before any plugin initializes; with an adapter it is `ADAPTER_UNSUPPORTED`. ## Set up on SQLite [#set-up-on-sqlite] Better Auth keeps its own raw `bun:sqlite` connection; the kit opens and owns separate Rolebook worker connections (`@rolebook/sharing-sqlite/bun-query`) to the same database file, so the two never share a transaction. Open the file by its absolute canonical path and configure Better Auth's connection yourself; the kit checks these settings and never changes them. ```ts import { Database } from "bun:sqlite"; import { createBetterAuthSharing, getRolebookMigrations, rolebook } from "@rolebook/better-auth"; import type { CreateBetterAuthSharingOptions } from "@rolebook/better-auth"; import { betterAuth } from "better-auth"; import { organization } from "better-auth/plugins"; declare const sharing: Omit; // definition, descriptors, keys const database = new Database("/srv/app/data/app.db"); // absolute, canonical, existing file database.exec("PRAGMA journal_mode = WAL"); database.exec("PRAGMA foreign_keys = ON"); database.exec("PRAGMA synchronous = FULL"); database.exec("PRAGMA busy_timeout = 0"); const kit = await createBetterAuthSharing({ ...sharing, storage: { dialect: "sqlite", database } }); export const auth = betterAuth({ database, plugins: [organization(), rolebook(kit)] }); await (await auth.$context).runMigrations(); database.exec( "CREATE TABLE IF NOT EXISTS project (workspace_id TEXT NOT NULL, id TEXT NOT NULL, version TEXT NOT NULL, PRIMARY KEY (workspace_id, id))", ); await getRolebookMigrations(auth).apply(); // Shutdown: close the kit's Rolebook connections first, then the application's database. await kit.close(); database.close(); ``` - The filename must be absolute and equal to its `realpath`, and the connection's `main` database must be that file; in-memory, temporary and `file:` URI databases, relative paths, `.`/`..` segments and symlink aliases are refused (`SQLITE_FILE_IDENTITY`). - WAL, `foreign_keys = ON`, `synchronous = FULL` and `busy_timeout = 0` on Better Auth's connection are checked when the kit is built and again by `apply()` (`SQLITE_CONNECTION_POLICY`). - With `busy_timeout = 0`, a write that meets the other connection's open write transaction fails instead of waiting on the lock. Better Auth reports its own write error. A conflicting Rolebook core-storage operation fails closed as `503` after the adapter's bounded retries, with no partial Rolebook state. The public plugin endpoint first obtains an authoritative Better Auth session, and that admission may wait while a Better Auth transaction is open, so endpoint requests have no promise of an immediate HTTP `503`, cancellation or latency bound. Nothing retries a failed request for the caller. - `kit.close()` closes only the kit's worker connections (idempotent). After that, every Rolebook operation request is refused at admission with `503 SHARING_SCHEMA_UNAVAILABLE`, before the core runs, including on a server that has already answered requests. Teams are PostgreSQL only. ## Lifecycle on your database [#lifecycle-on-your-database] `kit.adapters.` is a `RolebookResourceAdapter` from the root entry: the Sharing storage adapter and `initializeResource`. The root entry's types name neither SQL adapter package, so an application with one of them installed type-checks strictly. For transaction-bound lifecycle work (`withLifecycleTransaction`, `initializeResourceInTransaction`, deletion and moves), build the kit with `createPostgresBetterAuthSharing()` from `@rolebook/better-auth/postgres` or `createSqliteBetterAuthSharing()` from `@rolebook/better-auth/sqlite`. Each accepts only its own `storage.dialect` and returns the same kit, typed with that backend's own adapter. Both entries are server only. ## Endpoints [#endpoints] The plugin adds `POST /rolebook/v1/sharing.` for the seven Sharing operations and `sharing.executeIfUnchanged`, the conditional form of `sharing.execute`, with the existing wire format, and `GET /rolebook/scope`. They are not Better Auth actions, so they add nothing to `auth.api` or to path-inferred client methods. For each operation: Rolebook CSRF (same-origin, or an exact `trustedOrigins` origin, whatever Better Auth's own origin settings), `application/json`, an authoritative session with an active organization (`401 UNAUTHENTICATED` otherwise), the optional `x-rolebook-actor` / `x-rolebook-tenant` headers (a mismatch is `401 UNAUTHENTICATED`, after Better Auth's own session read and before any Rolebook core or storage call), readiness (`503 SHARING_SCHEMA_UNAVAILABLE` until `apply()` has run, and after `kit.close()`), then `@rolebook/server/core`. `GET /rolebook/scope` answers `{ status: "ready", scope: { actor, tenant, policy } }`, `{ status: "no_active_organization" }` or `401`, and ignores the expected-scope headers. For a static kit, scope does not depend on the Rolebook tables. For a versioned kit, scope with an active organization checks readiness first. It answers `503 SHARING_SCHEMA_UNAVAILABLE` before `apply()`, after `kit.close()`, or when the readiness probe fails or rejects. A request whose readiness probe is in flight when the kit closes answers the same 503, for operations and for versioned scope. ## Client and React [#client-and-react] ```ts import { createScopeController, rolebookClient } from "@rolebook/better-auth/client"; import { createAuthClient } from "better-auth/client"; import { organizationClient } from "better-auth/client/plugins"; export const authClient = createAuthClient({ plugins: [organizationClient(), rolebookClient()], }); const scope = createScopeController({ rolebook: authClient.rolebook }); scope.subscribe(() => console.log(scope.getSnapshot().status)); scope.start(); // focus, page visible, same-origin channel, this client's session changes, any 401 ``` `authClient.rolebook.fetchScope()` reads the scope through Better Auth's configured fetch and base URL; `sharingClientFor()` builds the existing `@rolebook/client` POST client for it, with cookies and only the actor/tenant refusal headers. ```tsx import { RolebookSharingProvider, useCan } from "@rolebook/better-auth/react"; import { MembersList } from "@rolebook/react"; } signedOut={} noActiveOrganization={} unavailable={(code, retry) => } > ; ``` Any change of the server scope or `scopeContext` remounts the kit view. While the scope is re-read the previous view stays mounted but hidden and `aria-busy`, and a capture-phase fence cancels clicks, submits and activation keys inside it, so none of its controls starts an operation; an operation already in flight is not cancelled. A closed view's reads reject before any request and its invitation tokens are not handed over. `useCan(resource, action)` is a hint, `no_hint` until the server answers. On the server the provider renders `fallback` and reads nothing. ## API [#api] Signatures are checked against the built declarations. ## Exports of `@rolebook/better-auth` [#exports-of-rolebookbetter-auth] ### `RolebookConfigurationError` [#rolebookconfigurationerror] ```ts api="@rolebook/better-auth" class RolebookConfigurationError extends Error { readonly code: RolebookConfigurationCode; constructor(code: RolebookConfigurationCode, message: string); } ``` ### `RolebookConfigurationCode` [#rolebookconfigurationcode] ```ts api="@rolebook/better-auth" type RolebookConfigurationCode = "FOREIGN_KIT" | "DATABASE_MISMATCH" | "ADAPTER_UNSUPPORTED" | "STATELESS_SESSIONS_UNSUPPORTED" | "ORGANIZATION_PLUGIN_REQUIRED" | "MODEL_NAME_COLLISION" | "TEAMS_REQUIRE_POSTGRES" | "SQLITE_FILE_IDENTITY" | "SQLITE_CONNECTION_POLICY" | "INVALID_OPTIONS" | "MIGRATIONS_PENDING" | "KIT_CLOSED"; ``` ### `RolebookUnauthenticatedError` [#rolebookunauthenticatederror] ```ts api="@rolebook/better-auth" class RolebookUnauthenticatedError extends Error { readonly code: "UNAUTHENTICATED"; constructor(message?: string); } ``` ### `BetterAuthSharingKit` [#betterauthsharingkit] ```ts api="@rolebook/better-auth" interface BetterAuthSharingKit> = Readonly>> { readonly dialect: "postgres" | "sqlite"; readonly sharing: ResourceSharing | VersionedResourceSharing; readonly database: object; readonly core: SharingCore; readonly migrations: RolebookMigrationPlan; readonly schema: Readonly>; readonly policyLabel: () => string; readonly adapters: { readonly [K in keyof TResources]: RolebookResourceAdapter; }; readonly ready: () => Promise; readonly close: () => Promise; readonly onInternalError: (error: unknown, request: Request) => void; } ``` ### `BetterAuthSharingResource` [#betterauthsharingresource] ```ts api="@rolebook/better-auth" type BetterAuthSharingResource = Omit; ``` ### `BetterAuthSharingStorage` [#betterauthsharingstorage] ```ts api="@rolebook/better-auth" type BetterAuthSharingStorage = PostgresStorage | SqliteStorage; ``` ### `CreateBetterAuthSharingOptions` [#createbetterauthsharingoptions] ```ts api="@rolebook/better-auth" interface CreateBetterAuthSharingOptions> = Readonly>> { readonly storage: BetterAuthSharingStorage; readonly betterAuthTables?: BetterAuthTables; readonly definition: { readonly policy: RolebookPolicy; readonly resources: TResources; }; readonly descriptors: { readonly [K in keyof TResources]: PostgresTableDescriptor | SqliteTableDescriptor; }; readonly invitationTokens: InvitationTokenProtector; readonly listingCursorKey: string | Uint8Array | readonly (string | Uint8Array)[]; readonly teams?: { readonly enabled: true; }; readonly mapWorkspaceAssignments?: BetterAuthIdentityAdapterOptions["mapWorkspaceAssignments"]; readonly inspection?: CreateSharingOptions["inspection"]; readonly maxBodyBytes?: number; readonly onInternalError?: (error: unknown, request: Request) => void; readonly sharingOptions?: Pick; } ``` ### `createBetterAuthSharing` [#createbetterauthsharing] ```ts api="@rolebook/better-auth" function createBetterAuthSharing>>(options: CreateBetterAuthSharingOptions): Promise>; ``` ### `DisabledModel` [#disabledmodel] ```ts api="@rolebook/better-auth" interface DisabledModel { readonly modelName: string; readonly fields: Record; readonly disableMigration: true; } ``` ### `PostgresStorage` [#postgresstorage] ```ts api="@rolebook/better-auth" interface PostgresStorage { readonly dialect: "postgres"; readonly pool: object; readonly executor: PostgresSqlExecutor; readonly policyStore?: { readonly tablePrefix?: string; readonly schema?: string; readonly seed?: "activate-if-empty" | "require-active"; readonly refreshIntervalMs?: number; readonly maxStalenessMs?: number; }; } ``` ### `RolebookMigrationPlan` [#rolebookmigrationplan] ```ts api="@rolebook/better-auth" interface RolebookMigrationPlan { readonly dialect: "postgres" | "sqlite"; readonly steps: readonly RolebookMigrationStep[]; compile(): string; apply(): Promise; rollback(options?: { readonly dropAudit?: boolean; }): readonly RolebookRollbackStep[]; } ``` ### `RolebookMigrationStep` [#rolebookmigrationstep] ```ts api="@rolebook/better-auth" interface RolebookMigrationStep { readonly name: string; readonly sql: string; } ``` ### `RolebookRollbackStep` [#rolebookrollbackstep] ```ts api="@rolebook/better-auth" interface RolebookRollbackStep extends RolebookMigrationStep { readonly dataLoss?: string; } ``` ### `SqliteStorage` [#sqlitestorage] ```ts api="@rolebook/better-auth" interface SqliteStorage { readonly dialect: "sqlite"; readonly database: BunSqliteRawDatabase; readonly maxConnections?: number; } ``` ### `getRolebook` [#getrolebook] ```ts api="@rolebook/better-auth" function getRolebook(auth: RolebookAuthLike): { forRequest(headers: Headers): Promise; }; ``` ### `getRolebookMigrations` [#getrolebookmigrations] ```ts api="@rolebook/better-auth" function getRolebookMigrations(auth: RolebookAuthLike): RolebookMigrationPlan; ``` ### `RolebookAuthLike` [#rolebookauthlike] ```ts api="@rolebook/better-auth" interface RolebookAuthLike { readonly options: { readonly plugins?: readonly unknown[]; }; readonly api: object; } ``` ### `RolebookRequestScope` [#rolebookrequestscope] ```ts api="@rolebook/better-auth" interface RolebookRequestScope { readonly actor: string; readonly tenant: string; can(resource: ResourceKey, action: string): Promise; forTenant(): TenantSharing; } ``` ### `RolebookPlugin` [#rolebookplugin] ```ts api="@rolebook/better-auth" type RolebookPlugin = ReturnType; ``` ### `rolebook` [#rolebook] ```ts api="@rolebook/better-auth" function rolebook(kit: BetterAuthSharingKit): { id: "rolebook"; schema: Readonly>; endpoints: RolebookEndpoints; options: { kit: BetterAuthSharingKit>>; }; rateLimit: { window: number; max: number; pathMatcher: (path: string) => boolean; }[]; init(ctx: import("better-auth").AuthContext): void; }; ``` ### `RolebookInitializeResourceInput` [#rolebookinitializeresourceinput] ```ts api="@rolebook/better-auth" interface RolebookInitializeResourceInput { readonly tenantId: string; readonly resourceId: string; readonly owner: OwnerRef; readonly actor: ResourceRef; readonly occurredAt: Date; } ``` ### `RolebookInitializeResourceResult` [#rolebookinitializeresourceresult] ```ts api="@rolebook/better-auth" type RolebookInitializeResourceResult = "applied" | "already_initialized" | "identity_ineligible" | "owner_mismatch" | "group_owner" | "not_found"; ``` ### `RolebookResourceAdapter` [#rolebookresourceadapter] ```ts api="@rolebook/better-auth" interface RolebookResourceAdapter extends SharingAdapter { initializeResource(input: RolebookInitializeResourceInput): Promise; } ``` ### `BetterAuthTables` [#betterauthtables] ```ts api="@rolebook/better-auth" interface BetterAuthTables { readonly schema?: string; readonly user?: string; readonly member?: string; readonly team?: string; readonly teamMember?: string; readonly fields?: { readonly memberId?: string; readonly memberOrganizationId?: string; readonly memberUserId?: string; readonly memberRole?: string; readonly userId?: string; readonly userEmail?: string; readonly userEmailVerified?: string; readonly userName?: string; }; } ``` ## Exports of `@rolebook/better-auth/postgres` [#exports-of-rolebookbetter-authpostgres] ### `createPostgresBetterAuthSharing` [#createpostgresbetterauthsharing] ```ts api="@rolebook/better-auth/postgres" function createPostgresBetterAuthSharing>>(options: CreatePostgresBetterAuthSharingOptions): Promise>; ``` ### `CreatePostgresBetterAuthSharingOptions` [#createpostgresbetterauthsharingoptions] ```ts api="@rolebook/better-auth/postgres" type CreatePostgresBetterAuthSharingOptions> = Readonly>> = Omit, "storage" | "descriptors"> & { readonly storage: PostgresStorage; readonly descriptors: { readonly [K in keyof TResources]: PostgresResourceDescriptor; }; }; ``` ### `PostgresBetterAuthSharingKit` [#postgresbetterauthsharingkit] ```ts api="@rolebook/better-auth/postgres" type PostgresBetterAuthSharingKit> = Readonly>> = Omit, "dialect" | "adapters"> & { readonly dialect: "postgres"; readonly adapters: { readonly [K in keyof TResources]: PostgresSharingAdapter; }; }; ``` ## Exports of `@rolebook/better-auth/sqlite` [#exports-of-rolebookbetter-authsqlite] ### `createSqliteBetterAuthSharing` [#createsqlitebetterauthsharing] ```ts api="@rolebook/better-auth/sqlite" function createSqliteBetterAuthSharing>>(options: CreateSqliteBetterAuthSharingOptions): Promise>; ``` ### `CreateSqliteBetterAuthSharingOptions` [#createsqlitebetterauthsharingoptions] ```ts api="@rolebook/better-auth/sqlite" type CreateSqliteBetterAuthSharingOptions> = Readonly>> = Omit, "storage" | "descriptors" | "teams"> & { readonly storage: SqliteStorage; readonly descriptors: { readonly [K in keyof TResources]: SqliteResourceDescriptor; }; }; ``` ### `SqliteBetterAuthSharingKit` [#sqlitebetterauthsharingkit] ```ts api="@rolebook/better-auth/sqlite" type SqliteBetterAuthSharingKit> = Readonly>> = Omit, "dialect" | "adapters"> & { readonly dialect: "sqlite"; readonly adapters: { readonly [K in keyof TResources]: SqliteSharingAdapter; }; }; ``` ## Exports of `@rolebook/better-auth/client` [#exports-of-rolebookbetter-authclient] ### `createScopeController` [#createscopecontroller] ```ts api="@rolebook/better-auth/client" function createScopeController(options: ScopeControllerOptions): ScopeController; ``` ### `ScopeState` [#scopestate] ```ts api="@rolebook/better-auth/client" type ScopeState = { readonly status: "inert"; } | { readonly status: "verifying"; readonly previous?: ReadyScope; readonly epoch: number; } | ReadyScope | { readonly status: "signed_out"; } | { readonly status: "no_active_organization"; } | { readonly status: "unavailable"; readonly code: string; }; ``` ### `rolebookClient` [#rolebookclient] ```ts api="@rolebook/better-auth/client" function rolebookClient(): { id: "rolebook"; $InferServerPlugin: RolebookPlugin; getAtoms: () => { $rolebookScopeSignal: import("nanostores").PreinitializedWritableAtom & object; }; atomListeners: { signal: "$rolebookScopeSignal"; matcher: typeof changesScope; callback: () => void; }[]; getActions: ($fetch: unknown, _store: unknown, options: unknown) => { rolebook: RolebookActions; }; }; ``` ### `RolebookActions` [#rolebookactions] ```ts api="@rolebook/better-auth/client" interface RolebookActions { fetchScope(signal?: AbortSignal): Promise; sharingClientFor(server: ServerScope, sharingBase: string, onUnauthenticated: () => void): RolebookSharingClient; register(controller: { localChange(): void; }): () => void; } ``` ### `ScopeRead` [#scoperead] ```ts api="@rolebook/better-auth/client" type ScopeRead = { readonly kind: "ready"; readonly scope: ServerScope; readonly sharingBase: string; } | { readonly kind: "no_active_organization"; } | { readonly kind: "signed_out"; } | { readonly kind: "unavailable"; readonly code: string; }; ``` ## Exports of `@rolebook/better-auth/react` [#exports-of-rolebookbetter-authreact] ### `RolebookSharingProvider` [#rolebooksharingprovider] ```ts api="@rolebook/better-auth/react" function RolebookSharingProvider(props: RolebookSharingProviderProps): ReactNode; ``` ### `RolebookSharingProviderProps` [#rolebooksharingproviderprops] ```ts api="@rolebook/better-auth/react" type RolebookSharingProviderProps = Omit & { readonly authClient: { readonly rolebook: RolebookActions; }; readonly scopeContext?: SharingScope["context"]; readonly fallback?: ReactNode; readonly signedOut?: ReactNode; readonly noActiveOrganization?: ReactNode; readonly unavailable?: (code: string, retry: () => void) => ReactNode; }; ``` ### `useRolebookScope` [#userolebookscope] ```ts api="@rolebook/better-auth/react" function useRolebookScope(): ScopeState; ``` ### `useCan` [#usecan] ```ts api="@rolebook/better-auth/react" function useCan(resource: SharingResource, action: string, options?: UseCanOptions): UseCanResult; ``` # Choose how decisions run (/docs/choosing) > The embedded engine, the Sharing module and its HTTP API, the decision service, and signed offline snapshots, and when to use each. Rolebook has one evaluator: the engine in the `rolebook` package. Everything else is a way to bring a question to it. This page explains the five ways, what each one needs from your application, and how they fit together. They are not alternatives to pick once; most products combine two or three. ## At a glance [#at-a-glance] | You have | Use | Where the engine runs | Who supplies the facts | | --- | --- | --- | --- | | TypeScript or JavaScript on your server, with roles your application already loads | The [embedded engine](#the-embedded-engine) (`rolebook`) | In your process | Your code, per request | | A product where users share items with people and teams | The [Sharing module](#the-sharing-module) (`@rolebook/sharing`) | In your process | Sharing's storage and identity adapters | | Browser code, or Python, Go, or Rust code, that works with shared items | The [Sharing HTTP API](#the-sharing-http-api) (`@rolebook/server`) | On your server | The Sharing module behind the handler | | Other services that need a plain check on a subject, an action, and a resource | The [decision service](#the-decision-service) (`@rolebook/decision-service`) | On your server | An authority provider you write | | A device or edge process that must decide without a connection | [Signed offline snapshots](#signed-offline-snapshots) (`@rolebook/offline`) | On the device | An issuer you run, which signs them | Every row ends in the same call: a policy, a binding, and a trusted resource go to `createAuthorizer(policy).bind(binding).check(request)`. No package contains a second evaluator, a compiled-to-SQL policy, or an engine in another language. ## The embedded engine [#the-embedded-engine] `rolebook` evaluates a [policy](/docs/policies) against the subject, assignments, and [trusted resource](/docs/trusted-resources) your code passes to it. It has no database, network, authentication-provider, framework, or UI dependency, and nothing in its request path leaves the process. Use it when the code that asks runs on your server in TypeScript or JavaScript. It is the shortest path: a check adds no network hop and does not depend on another service being available. Route checks for [Hono](/docs/hono), [Express 5](/docs/api/express), and [Fastify 5](/docs/api/fastify) are thin middleware over it. Your application owns the inputs: the authenticated subject, assignments from an authoritative store, and a resource loaded through a tenant-scoped query with its complete ancestry. Start with the [quick start](/docs/getting-started) and the [multi-tenant guide](/docs/multi-tenant). ## The Sharing module [#the-sharing-module] [`@rolebook/sharing`](/docs/sharing) adds the state most collaborative products need: per-resource ownership, memberships, invitations, expiry, revocation, and audit events, stored in your own PostgreSQL or SQLite database. It loads that state through its adapters, projects it into assignments, and asks the embedded engine for every decision. Use it when access to an item depends on who it was shared with. It also answers the questions screens ask: every action a person may take on one item, who the item is shared with, [the items a person can reach](/docs/sharing/listing), and [your own tables filtered to what a person may open](/docs/sharing/authorized-queries). On PostgreSQL and SQLite, you can also turn on [inherited folder access](/docs/sharing/inheritance), run [protected writes](/docs/sharing-postgres/protected-updates) that decide an application update inside the transaction that performs it, and deliver signed [access-change webhooks](/docs/sharing/webhooks) when memberships change. If your app already uses Better Auth, [`@rolebook/better-auth`](/docs/better-auth) wires up the Sharing server endpoints, client, and React bindings as a single plugin. The module is a library in your server process. It is the only path with transactional guarantees: a sharing change commits with its audit event, and a protected write commits with its decision. ## The Sharing HTTP API [#the-sharing-http-api] [`@rolebook/http`, `@rolebook/server`, and `@rolebook/client`](/docs/http-api) expose one Sharing instance over HTTP as seven operations, `sharing.authorize` through `sharing.explain`, plus `sharing.executeIfUnchanged`, the conditional form of `sharing.execute`. The handler is a web-standard `(request) => Promise` function that you mount in your own server. Use it for browser code (either directly with `@rolebook/client` or with the accessible components in [`@rolebook/react`](/docs/react)), and for Python, Go, and Rust services that work with shared items through the [SDKs](/docs/http-api). The tenant and the actor always come from `getContext`, which reads your trusted session; they are never in the request body. A caller therefore asks about itself, in the tenant its session belongs to. The one exception is `sharing.explain`, the opt-in privileged inspection: an actor who holds a resource's inspect permission names another subject and reads why that subject can or cannot act. The HTTP API is the Sharing module's surface, not a general check endpoint: its operations are about shared resources, and results are deliberately smaller than in-process ones. Named authorized queries and protected writes are not served over it. ## The decision service [#the-decision-service] [`@rolebook/decision-service`](/docs/decision-service) answers Core checks for other services. A caller sends a subject, a resource, and a concrete action, optionally with one field, to one of two routes: ```text POST /v1/scopes/{scopeId}/decisions:check POST /v1/scopes/{scopeId}/decisions:checkBatch ``` ```json { "contract": "rolebook/decision-service/v1", "semanticProfile": "rolebook/core-v4", "scalarProfile": "rolebook/scalars-p1/v1", "model": { "kind": "current" }, "freshness": { "kind": "captured_inputs" }, "check": { "subject": { "type": "user", "id": "alice" }, "resource": { "type": "project", "id": "p1" }, "action": "read", "field": "title" } } ``` A request carries no assignments, facts, context, principals, or policy. The service authenticates the caller through a credential verifier you supply, matches a grant that names the scope, the operations, and the subjects that caller may ask about, and then loads the binding and the resource through the **authority provider** registered for that scope. The provider is your code over your own source of truth. The engine evaluates what it returns. Use it when services that do not embed the engine need the same answers, including services in other languages and callers that ask about subjects other than themselves. It differs from the Sharing HTTP API in three ways: | | Sharing HTTP API | Decision service | | --- | --- | --- | | Caller | An end user's session | An authenticated service credential with a grant | | Subject of the check | The session's actor; `sharing.explain`, when enabled, takes a named subject | Any subject the grant allows: one bound subject, or any in the scope | | Facts come from | The Sharing module's adapters | Your authority provider, for any Core policy | | Operations | Authorize, permissions, describe, list, audit, execute, explain | Check and batch check only | | A failure to load facts | A domain code or an error response, as the Sharing module reports it | A typed **no-decision**, distinct from every denial | The package is a `fetch` handler with no listener. Before you expose it, your deployment supplies and qualifies a credential verifier, an authority provider for each scope, and an HTTP host that terminates TLS, rejects duplicate headers, and limits request rates. See the [deployment responsibilities](/docs/decision-service#deployment-responsibilities). ## Signed offline snapshots [#signed-offline-snapshots] [`@rolebook/offline`](/docs/offline) carries one exact check to a place that cannot call your server. An issuer signs a bundle that contains the policy, the binding, the resource, the permission, and the optional field. A verifier authenticates the bundle under a trust lease signed by your root key, checks its audience, validity window, and fact age, applies its stored anti-rollback state, and evaluates the carried input with the engine. Use it for a device, a kiosk, or an edge process that must keep answering during a disconnection. Know what a snapshot is not: - It is not a general offline policy engine. One bundle answers one check; the verifier accepts no local policy and no caller-supplied facts. - It is not a write authorization or a one-time token. A decision is reusable while the bundle is valid. - It is not instantly revocable. A revoked signer stays usable until the device installs a newer root-signed lease that no longer authorizes its key. Until then, the bound is the key horizon (at most 7 days), the bundle expiry (at most 24 hours), and fact freshness. A verifier constructed as `ui_only` returns results labelled `ui_hint`, suitable for showing or hiding a control. Enforcement requires `enforcement_qualified` construction with a host qualification record, and host adapters you have reviewed: a clock that cannot be set back, a state store that cannot be rolled back, strict Ed25519 verification, and out-of-band root provisioning. The package ships none of these. A hint is not a lower bar for integrity. Both modes run the same signature, trust, schema, time, and stored-rollback checks, and both return a no-decision when the clock cannot vouch for the time or the trust state is missing or lost; the difference is that only enforcement records the accepted bundle in the state store. The verifier stops accepting a signer when a newer root-signed lease that no longer authorizes its key is installed, and otherwise when the bundle or the key expires. The package runs on Node.js 24 or later and on Bun. ## Decisions and no-decisions [#decisions-and-no-decisions] The embedded engine always decides: malformed input becomes a denial with its own [code](/docs/decisions#decision-codes), because the caller supplied the facts and a bad fact is the caller's fault. The decision service and the offline verifier load or receive facts on the caller's behalf, so they separate two results: | Result | Codes | Meaning | | --- | --- | --- | | Decision | `ALLOWED`, `EXPLICIT_DENY`, `NOT_GRANTED` | The inputs passed every configured admission and verification check, and the engine evaluated them. | | No-decision | `error` from the service, `reason` from the verifier | The inputs could not be loaded, verified, or admitted in time. | A decision does not certify its inputs beyond those checks. Completeness stays the obligation of the trusted source: the service checks that an authority document is well formed, pinned to the right policy, and within the fact age you configured, and the verifier checks signatures, validity, and the declared manifest, but neither can tell that a provider or an issuer left an assignment out. Freshness follows the contract the request selects: with `captured_inputs`, the service reports when the facts were observed and when they were evaluated, not that they are still current. A no-decision is never an allow, and it is not a denial either: it says the question was not answered. Treat it as a refusal to proceed, and report it as an availability problem, not as an access denial. Neither component falls back to cached facts, an empty assignment set, or an earlier answer. ## One reader for bytes that cross a boundary [#one-reader-for-bytes-that-cross-a-boundary] The decision service and offline snapshots parse every JSON boundary with [`@rolebook/scalars-p1`](/docs/scalars-p1), the `rolebook/scalars-p1/v1` profile: strict UTF-8 JSON with duplicate member names rejected at every depth, and explicit budgets for bytes, depth, values, members, entries, and string size. A number is admitted when the exact value of its token is at most 253 − 1 in magnitude, and is then rounded to the nearest binary64 value, ties to even. That is a range check, not exact-decimal arithmetic: `4503599627370496.5` is admitted and becomes `4503599627370496`. Send identifiers and values that must stay exact as strings. Authority providers and issuers produce raw P1 bytes; stringifying an already parsed JavaScript value cannot show that the original input met the profile. The Sharing HTTP API keeps its own JSON contract and does not use P1. ## What stays the same everywhere [#what-stays-the-same-everywhere] - **The semantics.** Deny before allow across every applicable assignment, unknown conditions that never grant, field rules, flat group principals, and the [hard limits](/docs/limits). - **The trust model.** A decision says the policy matched the supplied facts. Whoever supplies the facts (your request handler, a Sharing adapter, an authority provider, or an issuer) is trusted to supply complete and authoritative ones. No component can detect a deny assignment that its source left out. - **Point-in-time answers.** A decision describes the facts when it was made. Only Sharing commands and [protected writes](/docs/sharing-postgres/protected-updates) bind a decision to a write in one transaction. A response from the decision service or a verified snapshot does not fence a later write. - **The model's shape.** Roles are scoped to a declared resource hierarchy, each resource has one ancestry chain, and core group principals are flat. Sharing and Teams offer opt-in, bounded folder inheritance and nested team lineage on PostgreSQL and SQLite, but none of these packages traverses an open-ended relationship graph. ## Combining them [#combining-them] A typical product embeds the engine in its API server for route checks, uses the Sharing module for per-item access, serves the Sharing HTTP API to its own front end, and mounts the decision service for internal services written in other languages. One policy definition feeds all of them: the decision service takes the policy as P1 bytes for each scope, and an offline issuer signs the policy into each bundle and pins its digest in the trust lease. Define a policy, bind a subject, and check a permission in-process. Memberships, invitations, ownership, audit, and listing in your own database. Authenticated single and batch checks for other services. Signed exact-check bundles, trust leases, and host qualification. What each component guarantees, and what your application must establish. # The rolebook command (/docs/cli) > @rolebook/cli: set up Rolebook, check a setup, explain decisions, read and change access on your own server, and compare policies. `@rolebook/cli` installs the `rolebook` command. It works on your project and on the Rolebook server you run yourself: it never calls anything else, and it sends no telemetry. > **Not on npm yet.** `@rolebook/cli` is not on npm yet. The npm package named `rolebook` is an unrelated project, so do not install it. The commands on this page use `npx --no`, which runs only a copy already installed in your project and never downloads one. ```sh npx --no rolebook --help ``` It needs Node 24 or later, or Bun. `rolebook` and `@rolebook/sharing` are its peers. | Command | What it does | | --- | --- | | `rolebook init` | Writes a starting policy and its wiring. | | `rolebook doctor` | Checks a setup and reports what is wrong. | | `rolebook explain` | Asks your server why someone can or cannot do something. | | `rolebook access` | Reads access, and changes it after a preview. | | `rolebook policy diff` | Compares two policies. | | `rolebook mcp` | Runs the [MCP server](/docs/agents/mcp) for your agent. | Every command takes `--help`, and every command that prints a result takes `--json`. The exit status is `0` when the answer is the good one, `1` when the command ran and the answer is a no (a denial from `access check`, a difference, a failed check, a change that was not applied), and `2` when the command could not run. `explain` exits `0` whenever it got an explanation, whatever the decision. Text output shows control and direction characters from the server or from arguments as visible `\u{…}` escapes, so a crafted id cannot rewrite a line in your terminal. `--json` keeps every value exact. Error messages are written by the command from the HTTP status and the error code; text the server sent is never repeated. ## Set up a project [#set-up-a-project] ```sh npx --no rolebook init ``` `init` reads `package.json`, detects Next.js, Hono, Express or Fastify (or plain Node), and writes into `src/authz/`, or `lib/authz/` when there is no `src/` directory: - `policy.ts`, a `definePolicy()` starting point to rename to your own resources and roles; - `middleware.ts` for Hono, Express and Fastify, built on `rolebook/middleware/`; - `authorizer.ts` for Next.js and plain Node, with `createAuthorizer(policy)`. Each wiring file has a `getBinding` hook that returns `undefined` until you read the signed-in user from your session, so every check is denied until you fill it in. `init` never overwrites a file: one that exists is reported and left as it is. It does not edit `package.json` or install anything; it says so when `rolebook` is missing. `--framework` chooses the framework, `--dir` the project, and `--dry-run` writes nothing. `init` writes only into real directories of the project: a symbolic link on the way, or a file where a directory belongs, is refused. Each file is written to a temporary name, flushed, and then linked to its final name, so a failed write leaves nothing behind; on a file system without hard links it is created exclusively instead. The checks work by path, so they do not defend against another process that swaps a directory for a link while `init` runs. ## Check a setup [#check-a-setup] ```sh npx --no rolebook doctor ``` `doctor` checks the Node version, that every `rolebook` and `@rolebook/*` dependency is installed and that its Rolebook peers are installed at a matching version (a range other than `^x.y.z` is reported as unchecked), that the policy passes `definePolicy`, and, when `ROLEBOOK_URL` is set, that your server answers and accepts the configured credentials. It changes nothing in the project. It does not inspect database tables; the storage adapters' own migrations and tests cover those. On its own, `doctor` reads only a data policy: `rolebook.policy.json`, `src/authz/policy.json` or `lib/authz/policy.json`. A policy module such as the `src/authz/policy.ts` that `init` writes is code, so `doctor` points at it and runs it only when you pass it explicitly: ```sh npx --no rolebook doctor --policy src/authz/policy.ts ``` A module runs in a child process. The command passes that process only `PATH` as its environment, so the credentials are not passed on; it starts in a new empty working directory, and under Bun with `.env` loading and auto-install turned off. Inside that process, `definePolicy` builds the policy from the module's original export, and only that result comes back; the module's own output and error text are discarded, and a policy error is reported by its code alone. The policy checked is the one the module exports under those conditions: a module that depends on an environment variable or on the working directory may select a different policy there than in your application, or fail to load, in which case the check fails. To check what a particular deployment loads, write that deployment's policy to a JSON file and compare or check that file. The process and its process group are ended after 10 seconds, or when the command is interrupted (on Windows, only the process itself). This is not a sandbox: the module runs with your own file-system and network access, and on some systems a process can read its parent's environment from the process table. Run only your own files. ## Connect to your server [#connect-to-your-server] `explain`, `access` and `mcp` call the [Sharing HTTP API](/docs/http-api) that you mount with `@rolebook/server`. The credentials come from the environment, never from a flag that would land in your shell history; only the URL can also be given with `--url`: | Variable | Meaning | | --- | --- | | `ROLEBOOK_URL` | The mounted API, for example `https://app.example.com/api/sharing`. `--url` overrides it. | | `ROLEBOOK_TOKEN` | Sent as `Authorization: Bearer `. | | `ROLEBOOK_COOKIE` | Sent as the `Cookie` header. | | `ROLEBOOK_HEADERS` | A JSON object of further headers, for example a team header your `getContext` reads. | | `ROLEBOOK_TIMEOUT_MS` | Milliseconds per request, 1 to 120000. Default 10000. | Your server's `getContext` turns these credentials into the tenant and the actor, exactly as for a request from your app. The command sends no tenant and no actor of its own, and no flag can name one. It fails closed: - without `ROLEBOOK_URL`, or without any of the three credential variables, it stops before sending anything; - the URL must be `https`, except `http` for `localhost`, `127.0.0.1` and `[::1]`, and may not carry a user name, a password, a query or a fragment; - a credential with a line break or another character a header cannot hold is refused, and `ROLEBOOK_HEADERS` may not set `host`, `origin`, `content-type` or the other headers the request owns; - an unreachable server, a timeout, a 401 or a response that is not the Sharing API is an error (exit `2`), never an empty answer. No message repeats a credential. ## Ask why [#ask-why] ```sh npx --no rolebook explain --resource project:q3-report --action delete --subject user:ada ``` `explain` calls `sharing.explain` and prints the decision, the rule that decided it, and the rules that were considered. `--subject` defaults to the configured identity, and `--field` explains one field. Your server must enable [inspection](/docs/http-api/server), and the configured identity must be allowed to inspect the item; otherwise the answer is `NOT_FOUND_OR_DENIED` and the exit status is `1`. ## Read access [#read-access] ```sh npx --no rolebook access check --resource project:q3-report --action delete npx --no rolebook access permissions --resource project:q3-report npx --no rolebook access describe --resource project:q3-report npx --no rolebook access list --type project --action read --limit 20 npx --no rolebook access history --resource project:q3-report ``` `check` and `permissions` answer for the configured identity. `describe` lists the owner, the members with their roles and expiry, and pending invitations. `list` and `history` page with `--cursor`, which they print when there is more. ## Change access [#change-access] ```sh npx --no rolebook access grant --resource project:brand-assets --subject team:design --role editor --until 2027-03-31 npx --no rolebook access change --resource project:brand-assets --subject team:design --role viewer --permanent npx --no rolebook access revoke --resource project:brand-assets --subject team:design ``` A change takes two runs. The first only reads the item's current access and prints what would change, and a confirmation; nothing that changes anything is sent. To apply exactly what you read, run the same command again with `--confirm` and the confirmation that preview printed, in place of ``: ```sh npx --no rolebook access revoke --resource project:brand-assets --subject team:design --confirm ``` The confirmation is a digest of the change (kind, item, subject, role and expiry) followed by the item's sharing revision. The second run refuses a confirmation made for any other change, and stops without changing anything when the revision is no longer the one you confirmed. The confirmation is not tied to the tenant or to `--url`, and it is an integrity check, not proof that a preview was shown: anyone who knows the change and the item's revision can compute it. A server revision with anything but letters, digits and `. _ ~ : -` is refused rather than printed, so the line you are asked to run can never carry shell syntax from the server. Otherwise it sends one `sharing.executeIfUnchanged` command carrying the confirmed revision, and the server decides whether the configured identity may make the change. `--until` takes a date (meaning 00:00 UTC on that day) or an RFC 3339 time with real calendar values; without it a grant is permanent, and a role change keeps the current expiry unless you pass `--until` or `--permanent`. What the revision check does and does not guarantee: - It catches any change that moves the item's sharing revision between your preview and the write. The server checks the confirmed revision in the same commit as the change, so a change that lands at any moment before it, however close, is refused as `STALE_PREVIEW` and nothing is applied. A membership reaching its expiry does not move the revision. - A server that predates `sharing.executeIfUnchanged`, or a newer one whose sharing runtime does not declare `conditionalExecution`, answers 404, and the command stops with `PRECONDITION_UNSUPPORTED` without changing anything; it never falls back to an unconditional `sharing.execute`. - The revision belongs to the item in the tenant your credentials select. If your server picks the tenant from session state that can change (an "active team" cookie, for example), keep it fixed while you change access. - A valid `sharing.executeIfUnchanged` result is definitive: applied, already applied, or refused with a reason. A 4xx refusal in the Sharing API's error format is definitive too. Any other exchange (no answer, a 5xx, a 2xx or 3xx carrying an error, or a body that is not the API's) leaves the outcome unknown: the command says so and exits `2`. Read the access with `access describe` before trying again. Invitations and ownership transfers are not in this version. ## Compare policies [#compare-policies] ```sh npx --no rolebook policy diff policies/staging.json policies/production.json ``` `policy diff` loads two policies, checks each with `definePolicy`, and lists the differences that `diffPolicies` finds: resource types and actions, parents, roles, scopes, inheritance, and direct and effective rules. It exits `0` when the two grant the same access and `1` when they differ. Each side is a `.json` file, or a module (`.js`, `.mjs`, and `.ts` or `.mts` where your runtime strips types) whose `policy` or default export is the policy; `--export` names another export. A module runs in a child process as for `doctor`: the credentials are not passed to it, but it is not a sandbox, so compare only your own files. JSON is read strictly, so a policy that repeats a key is refused rather than read as its last value. ## Not in this version [#not-in-this-version] - `rolebook login` and `rolebook keys` belong to Rolebook Console, which is not available yet. - `rolebook migrate`: apply your storage adapter's migrations with your own migration tool; see [Migrations](/docs/migrations). - `doctor` does not inspect database tables, columns or fences. - A way for the server to report the tenant a preview was read in. ## API reference [#api-reference] The package's entry point runs the same command in-process, for a script or a test. ### `runCli` [#runcli] ```ts api="@rolebook/cli" function runCli(argv: readonly string[], io: CliIo, streams?: McpStreams): Promise; ``` Runs one invocation and resolves to its exit status. It never calls `process.exit`. `streams` is needed only for `mcp`. While a policy module runs (`doctor --policy`, `policy diff`, the MCP policy tools), SIGINT, SIGTERM and SIGHUP end that module's process. Inside your own program, `runCli` leaves the signal itself to you: it never ends your process, whatever handlers you have, so handle those signals yourself. The `rolebook` command, which owns its process, ends after ending the module. ### `CliIo` [#cliio] ```ts api="@rolebook/cli" interface CliIo { readonly stdout: (text: string) => void; readonly stderr: (text: string) => void; readonly env: Readonly>; readonly cwd: string; readonly fetch?: (input: string, init: RequestInit) => Promise; } ``` `fetch` defaults to the global `fetch`; it is only ever called with the configured server's URL. ### `McpStreams` [#mcpstreams] ```ts api="@rolebook/cli" interface McpStreams { readonly input: AsyncIterable; readonly write: (line: string) => void; } ``` ### `EXIT` [#exit] ```ts api="@rolebook/cli" const EXIT: Readonly<{ ok: 0; negative: 1; error: 2; }>; ``` ### `VERSION` [#version] ```ts api="@rolebook/cli" const VERSION: string; ``` The version in the package's own `package.json`. # Conditions, facts, and fields (/docs/conditions-and-fields) > Constrain a rule by facts about the subject, resource, and request, and by field paths. A rule may carry a `where` condition and a `fields` list. Every constraint a rule carries must match for the rule to match. ## Facts [#facts] Conditions read **facts**: dot-separated paths under one of three roots. | Root | Reads | Reserved | | --- | --- | --- | | `subject` | The bound subject's `attributes`, plus `type` and `id` | `subject.type`, `subject.id` | | `resource` | The trusted resource's `attributes`, plus `type` and `id` | `resource.type`, `resource.id` | | `context` | The binding's `context` | none | A path has 1 to 16 segments after the root, each a [policy name](/docs/policies#names): `subject.department`, `resource.metadata.visibility`, `context.ipCountry`. Lookups read own properties of plain objects only. A path that does not resolve is a **missing** fact. `definePolicy()` accepts any well-formed path, so a mistyped one such as `resource.stauts` is not an error: the fact is simply always missing. To catch that before deployment, declare your facts in a [fact schema](/docs/fact-schemas) and check the policy with the optional `rolebook/authoring` entry point. It also reports operators applied to facts of the wrong type. It never changes a decision. ## Conditions [#conditions] ```ts import type { PolicyCondition } from "rolebook"; const ownerOfDraft: PolicyCondition = { all: [ { fact: "resource.ownerId", operator: "equals", value: { fact: "subject.id" } }, { fact: "resource.status", operator: "oneOf", value: ["draft", "review"] }, { not: { fact: "subject.suspended", operator: "equals", value: true } }, ], }; ``` A condition is one of: - a comparison `{ fact, operator, value }`, where `value` is a JSON literal or a fact reference. A fact reference is exactly `{ fact: "subject." }`, `{ fact: "resource." }`, or `{ fact: "context." }`. Any other value that contains an object with a `fact` key, at any depth, fails compilation, so a mistyped reference such as `{ fact: "subjct.id" }` is a policy error and is never compared as a literal; - `{ fact, operator: "exists", value? }`, where `value` is an optional boolean, `true` by default; - `{ all: [...] }`, `{ any: [...] }`, or `{ none: [...] }` with a non-empty list of conditions; - `{ not: condition }`. A whole condition has at most 256 nodes and is at most 16 levels deep. Malformed conditions fail `definePolicy()`. ### Operators [#operators] | Operator | Matches when | Operand rules | | --- | --- | --- | | `equals` | The fact deeply equals the value. Arrays compare in order, objects by keys. | Any JSON value. | | `notEquals` | The fact does not deeply equal the value. | Any JSON value. | | `oneOf` | The fact equals one of the listed values. | A non-empty array. | | `noneOf` | The fact equals none of the listed values. | A non-empty array. | | `contains` | An array fact has an element equal to the value, or a string fact contains the string value. | For strings, a non-empty needle. | | `containsAll` | An array fact contains every listed value. | A non-empty array. | | `sizeEquals` | An array or string fact has exactly this length. | A non-negative integer. | | `startsWith`, `endsWith` | A string fact starts or ends with the value. | A non-empty string. | | `lessThan`, `lessThanOrEqual`, `greaterThan`, `greaterThanOrEqual` | Both sides are finite numbers, or both are strings, and the comparison holds. | A number or a string. | | `exists` | The fact is present (`value: true`, the default) or absent (`value: false`). | An optional boolean. | Literal operands are checked when the policy is defined. A fact-reference operand is checked when it resolves: a dynamic `oneOf`, `noneOf`, or `containsAll` operand that is not a non-empty array, or a comparison between a number and a string, makes the comparison unknown rather than false. Strings compare by UTF-16 code units, as JavaScript's `<` does. ### Missing facts and unknown results [#missing-facts-and-unknown-results] Conditions are three-valued: true, false, or **unknown**. A comparison is unknown when its fact or its fact-reference operand is missing, or when the values have the wrong shape for the operator. `all`, `any`, `none`, and `not` combine results the way SQL's three-valued logic does: `all` is false if any child is false, otherwise unknown if any child is unknown; `not` of unknown is unknown. The rule's effect decides what unknown means: - An **allow** matches only when its condition is true. A missing fact never grants access. - A **deny** matches when its condition is true **or unknown**. A conditional deny fires when Rolebook cannot tell, so a missing `subject.suspended` blocks a `suspended`-conditioned deny. `exists` is the one operator that tests presence itself, so it is never unknown: `exists: false` is a known match when the fact is absent. ```ts prelude=core import { createAuthorizer, definePolicy } from "rolebook"; const guarded = definePolicy({ resources: policy.resources, roles: { editor: { scope: "workspace", rules: [ { effect: "allow", permission: "project:update" }, { effect: "deny", permission: "project:update", where: { fact: "subject.suspended", operator: "equals", value: true }, }, ], }, }, }); const check = (attributes: Record) => createAuthorizer(guarded) .bind({ subject: { type: "user", id: "user_123", attributes }, assignments: [ { subject: { type: "user", id: "user_123" }, role: "editor", scope: { resource: { type: "workspace", id: "ws_456" }, appliesTo: "descendants" }, }, ], }) .check({ permission: "project:update", resource: project }).code; check({ suspended: false }); // "ALLOWED" check({ suspended: true }); // "EXPLICIT_DENY" check({}); // "EXPLICIT_DENY": the fact is missing, so the deny's condition is unknown ``` `explain(request, { detail: "conditions" })` records the same result as a tree of operators and fact paths. It does not include the values that were compared. See [Decisions](/docs/decisions#explain). ## Fields [#fields] A rule may be limited to field paths of the resource with `fields`, a list of 1 to 64 patterns: ```ts import type { PolicyRule } from "rolebook"; const titleAndMetadata: PolicyRule = { effect: "allow", permission: "project:update", fields: ["title", "metadata.*"], }; ``` A request names the field it touches with `field`: ```ts prelude=core authorization.check({ permission: "project:update", resource: project, field: "metadata.visibility" }); ``` A requested field is a dot-separated path of 1 to 16 policy-name segments. A pattern segment is a policy name, `*` (exactly one segment), or `**` (zero or more segments). A request without `field`, or with `field: undefined`, is a resource-wide request. Allows and denies apply field patterns differently, so that neither can widen access: - A field-restricted **allow** grants only a requested field that one of its patterns matches exactly. It never grants a resource-wide request. `metadata.*` grants `metadata.visibility`, but not `metadata` and not `metadata.visibility.level`. - A field-restricted **deny** matches every request that could expose a path one of its patterns matches: a resource-wide request, and a requested field that equals, is an ancestor of, or is a descendant of such a path. A deny on `metadata.secret` matches `metadata`, `metadata.secret`, and `metadata.secret.value`, but not `title` or `metadata.public`. A deny on `*.secret` matches every single-segment field, since each may hold a `secret` child, and a deny pattern that starts with `**` matches every field. | Rule | Request | Result | | --- | --- | --- | | allow `title`, `metadata.*` | no field | not granted | | allow `title`, `metadata.*` | `title` | allowed | | allow `title`, `metadata.*` | `metadata` | not granted | | allow `title`, `metadata.*` | `metadata.visibility` | allowed | | allow `project:read`, deny `metadata.secret` | no field | denied | | allow `project:read`, deny `metadata.secret` | `metadata` | denied | | allow `project:read`, deny `metadata.secret` | `metadata.secret.value` | denied | | allow `project:read`, deny `metadata.secret` | `metadata.public` | allowed | A rule without `fields` applies to every request for its permission, with or without a field. # Connect to Rolebook Console (/docs/connect-to-rolebook-console) > The connector that lets Rolebook Console, the hosted console, change sharing in your app, through your own Sharing instance and database. `@rolebook/connector` connects your application to Rolebook Console, the hosted console. The console sends signed commands (grant a role, change a role, revoke a member, transfer ownership, issue or revoke an invitation, explain a decision); the connector checks each one and runs it through your application's own Sharing instance, in your database. Your database stays the only place where memberships live. ## What the connector does [#what-the-connector-does] - **It dials out.** The connector opens one outbound WebSocket connection to the console. Your application opens no inbound port. `wss://` is required; `ws://` is accepted only for a loopback host, for local development. - **It checks every command before running it.** In this order: the Ed25519 signature against the signing keys you configured, by key ID; the environment the command was signed for; the command's validity window (expired, issued too far in the future, or a window longer than the console issues for that command: 15 seconds for reads, 60 seconds for changes and previews, 120 seconds for `policy.activate`, `guardrails.activate` and `tenantRoles.set`); a repeated envelope ID (different bytes answer `DUPLICATE_MISMATCH`; the same bytes answer a change's cached result, and are evaluated again for reads and desired-state commands); the capability; whether the console is enabled for the command's tenant. A clock that returns an invalid date refuses every command. - **It runs changes through the public Sharing API.** A change runs as `sharing.forTenant({ tenantId, actor: consolePrincipal }).execute(...)`. Its idempotency key is derived from the environment ID and the console's command ID, so two environments never share one. Fences, the delegation ceiling and idempotency are Sharing's own: the connector grants the console principal nothing. Your identity adapter decides what that principal may do in each tenant. - **It calls Sharing at most once per change.** Before anything runs, the connector records an admission in your database: the command ID (bound once per environment), the tenant, the sequence, the resource, the signed expiry and the SHA-256 of the command name and parameters. A command that reuses the ID with different parameters, in any tenant, is refused `DUPLICATE_MISMATCH`. One executor moves the admission from `pending` to `started` in a conditional write that only one can win. It then asks the tenant check again, reads the clock again and calls Sharing in that same continuation, only if both deadlines still hold: the admission's own signed expiry and the signed expiry of the delivery it is handling. If the admission's expiry has passed, it records the admission `expired`. If only the delivery's expiry has passed, or the clock is invalid, or the tenant check no longer allows the tenant, it hands the admission back to `pending` without calling Sharing, so a later valid delivery can start it. That write is tried once and never repeated: a store call that failed may still commit, and a repeat could hand back an admission another executor has started since. If the hand-back cannot be recorded, the admission stays `started` until the sweep records it `unknown`, although Sharing was never called. A store that fails before anything ran (reading the admission, the sweep, the check for earlier admissions) answers `BUSY`; a stored admission that does not decode answers `INTERNAL`. Nothing calls Sharing twice for one admission. - **When it cannot prove an outcome, it says so and stops.** Each admission ends in one recorded state: - `committed`: Sharing committed it. The exact envelope that delivered it gets its original `APPLIED` result again only if that result was cached: from the same process, within the 10-minute dedup window. Any other delivery (another envelope, another instance, after a restart, later, or after a first delivery that timed out and whose commit was recorded late), before or after its expiry, gets `ALREADY_APPLIED`. - `refused`: Sharing refused the one call; every later delivery gets the same refusal. A refusal code the wire cannot carry is answered `INTERNAL` with that code as its message and is final too. Some of those are transient in Sharing (`POLICY_GENERATION_CHANGED`, `TENANT_ROLES_CHANGED`, `POLICY_UNAVAILABLE`, `HIERARCHY_UNAVAILABLE`, `DELEGATION_UNAVAILABLE`): to try again, the console issues a new command ID. - `expired`: its expiry passed before Sharing was called; it never ran (`COMMAND_EXPIRED`). - `unknown`: the start was recorded and no result was: Sharing failed or was given up on after `commandTimeoutMs`, or the process stopped after the start write, before or during the call (`INTERNAL`, message `Outcome unknown`). The connector never re-runs a change to find out. It reads Sharing's own record of the call instead: Sharing writes an idempotency record in the change's transaction, under a key derived from the environment and the command ID, bound to the tenant, the console principal and the change, and `lookupExecution` reads it without executing anything. A call that failed (rather than one given up on while it still runs) is looked up at once, and an `unknown` admission is looked up again on every delivery of the same change. When the record proves the commit, the admission is recorded `committed` and the delivery answers `ALREADY_APPLIED` with the commit's revision. Any other answer leaves it `unknown`: a record not found is not proof that nothing committed, and a record of another command under the key is not proof either. Every such answer comes from a conditional write or a fresh read of the admission, never from an earlier read. While another executor owns a started call, or before the change may start, a delivery answers `BUSY`. A commit reported after the connector gave up on the call is still recorded and replaces `unknown`. - **It keeps changes in sequence order.** Sequences start at 1. A change that was never admitted is refused `STALE` when another admission of the environment, refused or expired ones included, has an equal or higher sequence, and `INVALID_PARAMS` (details `code: "SEQUENCE_JUMP"`) when its sequence is more than 2^32 above every admission. A change starts only when every admission with a lower sequence has a final state; until then it answers `BUSY` (retryable). This holds across processes that share the database. An admission nobody will finish gets its final state on its own: once a console has accepted this instance's `hello` (and with it its clock), a sweep runs then, every 10 seconds and before each change. It marks `pending` admissions past their expiry `expired`, and `started` ones `unknown` only 60 seconds (the clock difference the console allows between instances) after the latest moment their owner could still be waiting for Sharing, which the owner recorded when it started. Until a console has accepted this instance's `hello`, it does not sweep at all. Terminal admissions are kept: each one binds its command ID and holds its sequence for good, so the table grows by one small row per change. The sweeps and the predecessor check read only an index of unresolved admissions. - **It does not send invitation tokens unless you allow it.** An invitation token is a bearer secret. By default `issueInvitation` is refused `UNSUPPORTED_COMMAND` (details `reason: "INVITATION_TOKENS_NOT_EXPORTED"`) before anything is admitted. An invitation admitted by an instance with the option on is never started by one with it off; that instance answers `BUSY` with the same reason, and the admission is started elsewhere or expires. With `exportInvitationTokens: true` the first result carries the token with `delivery: "not_configured"` so the console can hand it to the recipient. A token is sent only while the clock is valid and the command's signed window is open; otherwise the result goes without it. If no open connection accepted that result, the connector keeps it in memory until that deadline. A redelivery receives it after `isTenantEnabled` is asked again and the deadline checked again: a refusal drops the token, a failing check keeps it for a later try. `stop()` drops every kept token, and so does a restart. A redelivery of a committed change after its tenant was disabled answers `TENANT_NOT_ENABLED`, by design. - **It answers explain only when you enable inspection.** `access.explain` is advertised only when you pass `inspection: true` and your Sharing instance was created with an `inspection` configuration. It runs `TenantSharing.explain` as the console principal, so it needs the resource's configured inspect permission, is rate limited by your limiter, and is recorded by your inspection audit sink before any detail is returned. - **It copies audit events from your outbox.** With the `audit` option, the connector becomes the delivery worker of your protected-write outbox and sends committed events to the console. See [Audit copies](#audit-copies). - **It reports codes and counts, not data.** The `events` surface carries command names, outcome codes and counts. It never carries a tenant, subject, resource or command identifier, a key, the service key or a signature. ## The four settings [#the-four-settings] | Variable | Value | | --- | --- | | `ROLEBOOK_CONSOLE_URL` | The console's connector endpoint, `wss://…`. | | `ROLEBOOK_ENVIRONMENT_ID` | The environment this deployment belongs to. Commands signed for another environment are refused. | | `ROLEBOOK_SERVICE_KEY` | The environment's service key. It is sent only inside the authenticated `hello` frame. | | `ROLEBOOK_SIGNING_KEYS` | A comma-separated list of 1 to 8 base64url Ed25519 public keys, each optionally prefixed by its key ID and a colon (`sk_…:key`). A stated key ID must match the key. | Set all four, or none. With none set, nothing is started. With some set, or any of them malformed, `startConsoleConnector` throws at startup, naming the variables but never printing their values. ```ts import { createSqlConnectorStateStore, connectorStateMigrations, startConsoleConnector, } from "@rolebook/connector"; import type { ConsoleSharing } from "@rolebook/connector"; import type { AppSchema } from "@rolebook/connector-protocol"; declare const sharing: ConsoleSharing; // your createVersionedSharing() instance declare const schema: AppSchema; // the resource types, roles and actions the console may show declare const executor: { query(sql: string, values?: readonly (string | number | null)[]): Promise<{ rows: readonly Record[] }>; }; declare function consoleEnabledFor(tenantId: string): Promise; for (const sql of connectorStateMigrations({ dialect: "postgres" })) await executor.query(sql); const connector = startConsoleConnector({ sharing, schema, consolePrincipal: { type: "service", id: "rolebook-console" }, isTenantEnabled: consoleEnabledFor, // Built only when all four settings are present, for the configured environment. state: (environmentId) => createSqlConnectorStateStore({ executor, dialect: "postgres", environmentId }), }); connector?.events.on("halted", (event) => console.error("Rolebook Console refused the connection", event.code)); ``` `startConsoleConnector` builds the state store only when the connector is enabled, so the example runs unchanged with none of the four settings. To configure the connector from somewhere other than the environment, call `createConsoleConnector({ url, environmentId, serviceKey, signingKeys, ... })` and then `start()`. ## Trust model [#trust-model] - **Your database is authoritative.** Memberships, ownership, invitations and their audit rows are written by Sharing in your database, in the same transaction as the change. The console does not store memberships; it learns of them from command outcomes and from the audit events you map. - **The connector stores only bookkeeping.** `connectorStateMigrations()` creates three tables in your database: command admissions (command ID, tenant, sequence, resource, signed expiry, command hash, state and outcome), a per-environment sequence row that PostgreSQL uses to serialize admissions, and a small key-value table for the active console policy, each prepared policy publish and the custom-role revisions the console set. The state store you pass must belong to the connector's environment; another environment's store is refused at construction. On PostgreSQL the statements expect READ COMMITTED, the default; a serialization failure or deadlock answers `BUSY`. - **Commands are signed by the console and checked locally.** A command with an unknown key ID, a bad signature, another environment, an unknown command name, an unknown frame type or another protocol version is refused. An unknown frame, command name or version closes the connection. Rotating keys means changing `ROLEBOOK_SIGNING_KEYS`; a key you remove is refused from the next start. - **The console acts as one principal.** Every change and explanation runs as `consolePrincipal`, bounded by what your identity adapter grants it in that tenant and by `isTenantEnabled`. Nothing is attributed to a person the console names. - **Policy, guardrails and custom roles need your authorization.** Sharing records the actor of a policy publish or a custom-role change but does not authorize it, and nothing else authorizes a guardrail set. So `policy.console`, `guardrails` and `tenantRoles` are advertised only when you pass `authorizeAdministration` (`tenantRoles` only when Sharing offers `customRoles.set`, `guardrails` only with the `guardrails` option), and each `policy.activate`, `guardrails.activate` and `tenantRoles.set` asks it first, with the operation, the console principal and, for roles, the tenant. Anything other than `true` refuses the command (`UNSUPPORTED_COMMAND`, details `reason: "NOT_AUTHORIZED"`); a check that times out or loses a database race answers `BUSY`, and one that throws otherwise `INTERNAL`, retryable. The check is asked again right before each effect, and a refusal stops only what comes after it. Before a policy's draft, no draft is written; the number stays reserved for that document. Before its publish, the saved draft and its audit row stay and nothing is published. Before a role set's one Sharing call, nothing of the set is written; the refusal answers `UNSUPPORTED_COMMAND`. - **Policy.** When your app schema says `policySource: "console"` and Sharing is a versioned instance, `policy.activate` checks that the document matches its signed hash, saves it as a policy version and publishes it through the policy store (`policies.saveDraft` and `policies.publish`), as the console principal. Each policy number is reserved once, with its hash, before anything is prepared: the generation it is published against and the policy it is built on. Another hash under a reserved number answers `STALE` (details `code: "NUMBER_RESERVED"`). A number lower than one already reserved is not reserved, drafted or published, on a retry too (`STALE`, details `code: "NEWER_POLICY"`), unless it is already the active number with the same hash and still in place: that is confirmed before the newer reservation is checked. A number below the recorded active one, or the active number with another hash, answers `STALE` without details. Across processes that check and the publish are separate steps, so what holds is this: a publish is always against its own reserved generation, so it never overwrites a policy published after that reservation; if another publish won, the command fails `STALE` (details `code: "GENERATION_CONFLICT"`). The recorded active policy only moves through a compare-and-set from the value read. If the publish succeeded but cannot be recorded, the command answers `INTERNAL`, message `Policy published, not recorded`, retryable: a retry of the same command finds the policy active and records it. A repeat of the active number and hash is confirmed only while that policy is still the active one; after a local publish it answers `STALE` (details `code: "POLICY_CHANGED"`). With `policySource: "code"` it is refused `POLICY_SOURCE_CODE`. - **Custom roles.** `tenantRoles.set` refuses a set whose roles do not match its signed hash or that lists a role twice (`POLICY_INVALID`). What is already done is read from Sharing's live roles, never from the connector's notes: a role is in place when it is live, usable (status `available`) and has exactly these contents, or absent when the set removes it. The set is applied by one [`customRoles.set`](/docs/sharing/api#customroleadministration) call, so Sharing writes all of it or none of it: the complete result is every live role the console does not list, unchanged, and every role it lists as available; a role it lists as unavailable is left out, and Sharing removes it. Sharing validates that whole result: every role gets the checks a single `define` makes, and the per-tenant limits are counted on the result, so a set that removes one role and adds another at the limit applies. A role the console does not list is validated too: one that the active policy no longer admits refuses the set until the console lists it (available with a valid definition, or unavailable, so it is removed) or it is fixed locally. A stored role row that does not decode refuses every set (`CUSTOM_ROLE_UNREADABLE`, naming it), listed or not, until the row is repaired in the database: Sharing cannot tell whether it is live or retired. A refusal answers `POLICY_INVALID` with Sharing's code (and, for one role, `role`). The call carries the revision and the policy generation the roles were listed under, so a local role change or policy publish that commits between the connector's read of the roles and its call answers `BUSY`, with nothing written. `tenantRoles` is advertised only when Sharing offers `customRoles.set`, which needs a policy store that implements `writeTenantRoleSet` (the first-party stores do). Before its call the connector reserves the set revision in its own record, by a compare-and-set from the record it read before listing the roles. A set revision below a recorded, reserved or (from the previous connector version) claimed one answers `STALE`, and so does the same revision under another hash. A set revision another executor reserves after this one read the record makes the reservation fail (`BUSY`), and the retry `STALE`. A call that fails or is given up on answers `INTERNAL`, message `Role set outcome unknown`, retryable: Sharing applied all of it or none of it. A commit that cannot be recorded answers `INTERNAL`, message `Role set applied, not recorded`, retryable. The reservation keeps the Sharing revision the first call of that set revision was made against. From then on, a retry continues only from that revision; if Sharing has moved since, the set is recorded only when it is exactly in place, and otherwise answers `STALE` (details `code: "ROLES_CHANGED"`), not retryable, so a local change made after a lost commit is never overwritten; the console issues a new set revision. A later attempt never clears that baseline, whatever happens to its own call. Only the attempt that set it clears it (best effort), when its own call was not made (a host or clock check refused it) or Sharing refused it, and only while the record is still its own reservation: each reservation carries an attempt ID, so one executor's refusal never clears another executor's reservation of the same set revision. A repeat of a completed set is confirmed only while every role is still in place; otherwise it answers `STALE` (details `code: "ROLES_CHANGED"`). A claim the previous connector version left under `roles/` is read, never written: its set revision still orders sets, and the per-role revisions it recorded are still the console's. A claim of the same set revision that was not released before a write, whether or not it was marked done, may have written: the set is applied by one atomic set only while Sharing is still at the revision the claim last recorded, or recorded when it is exactly in place, and otherwise answers `STALE` with `ROLES_CHANGED`. A leftover claim that recorded no Sharing revision is accepted only when the set is exactly in place, and a reservation written for it keeps that rule after the claim is released. Stop every process of the previous connector version before starting this one on the same state store. The two must not run at the same time: the previous version neither reads the reservation nor keeps the per-role revisions this one records. - **Results are re-checked before release.** Reads, `access.explain` and the desired-state commands run again on every delivery, so a duplicate passes the tenant gate, Sharing's inspect check, limiter and audit again. A duplicate read that arrives while the first is still running answers `BUSY`; the first keeps its own connection. A duplicate change, `policy.activate`, `guardrails.activate` or `tenantRoles.set` waits in the change queue and runs after the first: a change is then answered from this process's cache of its result, or else from its admission, after the tenant check, and the others run again against current state. A read's result is released only if `isTenantEnabled` still allows its tenant when it finishes. Every result of a change or a role set, and every error answer that carries tenant data in its details (a role-set conflict with its stored revisions, say), is released only after `isTenantEnabled` is asked again, on its first delivery and on every repeat; error answers with a fixed code only are not. The commit itself stays recorded. If that check fails without refusing, a change's successful result is kept for a redelivery; an error answer, or a `policy.activate` or `tenantRoles.set` result, is not, and a redelivery runs the command again. Approval is per tenant, not one snapshot: a multi-tenant answer (`hello`, `directory.listCustomers`, the two tenants of a move's audit event) asks each tenant again just before release and drops one no longer allowed. `directory.listCustomers` lists only tenants `isTenantEnabled` allows. Its `nextCursor`, and that of `directory.listResources`, is bound to the command and tenant it was issued for and is the host's continuation sealed with a key that never leaves the connector; a cursor from another instance, from before a restart, or altered, answers `INVALID_PARAMS`. `directory.getCustomer` returns only the customer the request named. ## Failure behaviour [#failure-behaviour] For the same situations as a table of what happens and what to do, see [What happens when](/docs/what-happens-when#the-console-sends-a-change-through-the-connector). - **Console unreachable or disconnected.** Local sharing keeps working: your application's own reads and writes do not go through the connector. The connector reconnects after a random delay of up to 1 second, a bound that doubles with each failed attempt to at most 60 seconds, and resets it after a connection that stayed up for a minute. A connection on which the console sends nothing for 60 seconds is closed and reopened. While disconnected, no command reaches the connector, so nothing is applied. A command that arrives after its expiry is refused `COMMAND_EXPIRED`, except that a delivery of a change can still read that change's recorded outcome. - **Refused connection.** After an authentication, environment, replacement or protocol-version refusal (close codes 4401, 4403, 4409, 4426) the connector stops reconnecting and emits `halted`. - **Crash or disconnect after a commit.** If the process stops after the start write, a redelivery does not call Sharing again: it answers `BUSY` while the call's owner may still be waiting. After that the admission is `unknown`, and the redelivery reads Sharing's idempotency record: when it proves the commit, the delivery answers `ALREADY_APPLIED` and the admission is recorded `committed`; otherwise `Outcome unknown`. - **Command lookup.** `command.lookup` answers `found: true` from a committed receipt for the same resource. Anything else answers `found: false, definitive: false`: the connector cannot terminate a local transaction, so it never claims a command did not commit. It reads only the connector's receipts, not Sharing's record, because the record is bound to the change, which the lookup does not carry; a redelivery of the change reads it. - **Overload.** At most 16 read commands run at once; more answer `BUSY` (retryable). Per connection, at most 64 commands and `maxPendingBytes` (8 MiB by default) of them wait for an answer, verification included; across connections at most 96 are queued. A connection that sends more is closed with code 4429 and the event `frame_rejected` with reason `overloaded`. Commands queued from a closed connection that have not started are dropped, and the console redelivers them. One already running finishes on its own connection; if that connection is gone, a later delivery of the change is answered from its admission. - **Bounded calls.** Every call to Sharing, the state store, `isTenantEnabled`, `authorizeAdministration` and the directory is waited for at most `commandTimeoutMs`; outbox calls are waited for at most the audit lease. A store or host call given up on before any effect answers `BUSY`. The Sharing call of a change or a policy publish given up on answers `Outcome unknown`, and a role set's call `INTERNAL` with `Role set outcome unknown`, retryable. A database that reports a serialization failure, a deadlock, or SQLite busy or locked (as a code or a numeric result code) answers `BUSY`, and so does a tenant check, administration check or policy refresh that times out or loses such a race. A tenant check that throws otherwise answers `INTERNAL`, retryable. - **Duplicate envelopes.** Envelope IDs are remembered for 10 minutes, reads and changes apart. Reads are capped at 4096 entries, oldest first; changes are never forgotten inside that window, and a change that would exceed 4096 entries answers `BUSY`. `hello` reports custom-role revisions only for tenants `isTenantEnabled` allows. ## Limits [#limits] What the connector cannot rule out, and what it does instead. None of these ever re-runs a change. - **The admission, the Sharing change and the receipt are three transactions.** If the process stops between them, or the call fails, the admission is recorded `unknown`. Sharing's idempotency record, written in the change's own transaction, then resolves it when it can: a failed call is looked up at once, and every later delivery of the same change looks up an `unknown` admission again. It stays `unknown` when the record cannot prove the commit: the call is still running (a call given up on is not looked up until a redelivery), the record was pruned by retention (`pruneSettledRecords`, no sooner than one day after the commit), the resource was deleted or moved to another tenant since (both delete the record at the source key), the key holds another command's record, the console principal no longer resolves as a member of the tenant or was changed (the lookup is bound to the current one), the tenant's hierarchy enrollment has started (Sharing does not read an enrolled tenant's records for a lookup), the lookup fails or is given up on, or the Sharing tenant has no `lookupExecution` (an adapter without `lookupMutationIdempotency`). - **A call given up on can still commit.** A timer stops the connector waiting, not Sharing. A call that is given up on, or whose executor stopped, can commit after it was recorded `unknown`, and after a change with a higher sequence ran. A late commit that reaches the connector is recorded, and so is one a later delivery finds in Sharing's record. - **What the console does with `Outcome unknown`.** The change may or may not have taken effect. Redeliver the same change with the same command ID: it never runs again, and answers `ALREADY_APPLIED` once Sharing's record proves the commit. `command.lookup` reads only the connector's receipts. If the outcome stays unknown, check the membership, and issue a new command with a new ID if it is still needed. - **A role set that changes nothing writes nothing.** Sharing answers it without a write, so it does not fence on Sharing's revision: an older executor's role set already in flight against the same revision can still commit after this one is recorded. The reservation stops an older set revision from starting once a newer one is reserved, not one whose call already started. - **Two refused calls can strand a set revision.** When two executors run the same set revision and both calls are refused cleanly (a local change moved Sharing first), the second inherited the first's baseline and the first's release lost its compare-and-set, so the baseline stays. Every later retry of that set revision then answers `STALE` (`ROLES_CHANGED`) unless the set happens to be exactly in place, although nothing of it committed. It fails closed: the console issues a new set revision. - **One connector version at a time.** The previous connector version wrote role sets one role at a time under a claim it does not share with this version's reservation. Running both against one state store can apply an older set after a newer one; stop the previous version's processes first. - **A retried role set does not overwrite a local change.** When a set's commit may have been lost and Sharing has moved since, the retry cannot tell its own commit followed by a local change from a local change alone, so it answers `STALE` (`ROLES_CHANGED`) unless the set is exactly in place, and the console issues a new set revision. - **Two host answers, two calls.** Before the role set's one Sharing call the connector asks `isTenantEnabled` first and `authorizeAdministration` last, right before the clock check and the call. They are separate calls, so the last one asked is the freshest; a tenant disabled between the two answers is not caught for that call. - **Several processes.** Admissions, single ownership of each call and sequence order are enforced through the shared database, which must run the store's statements at READ COMMITTED on PostgreSQL. A change another process owns makes later changes answer `BUSY` until it has a final state. - **A role list can be a cached view.** Sharing serves `customRoles.list` from a per-process snapshot refreshed on its `refreshIntervalMs`. A repeat of a completed set is confirmed from that view, so a local change made through another process may take up to that interval to be seen. Writes are not affected: the set is a compare-and-set on Sharing's revision. A set decided from a stale view conflicts and answers `BUSY`; the conflict drops that process's cached view, so the retry reads the stored roles. - **Audit quarantine is permanent.** An audit event that names a tenant `isTenantEnabled` refused when it was checked, at collection or again at send, is quarantined and is not sent if the tenant is enabled later. ## Audit copies [#audit-copies] The connector reuses your existing protected-write outbox (`createPostgresProtectedWriteOutbox` or `createSqliteProtectedWriteOutbox`) through Sharing's run-once delivery worker. You map each committed outbox event to the console's audit shape: ```ts import type { ConsoleAuditOptions } from "@rolebook/connector"; import type { OutboxDeliveryPort } from "@rolebook/sharing"; declare const outbox: OutboxDeliveryPort; const audit: ConsoleAuditOptions = { outbox, toEvent(event) { if (event.kind !== "app.member.granted") return undefined; const payload = event.payload as { tenantId: string; resource: { type: string; id: string }; actor: { type: string; id: string }; at: string; }; return { id: event.eventId, tenantId: payload.tenantId, resourceType: payload.resource.type, resourceId: payload.resource.id, actor: payload.actor, action: "member.granted", occurredAt: payload.at, }; }, }; ``` - Only the primary connection sends audit batches, one at a time. Rows are acknowledged in the outbox only after the console's `audit.ack`. A nack retries them; a disconnect or timeout leaves them for replay after the lease expires. - Delivery is at least once. The event ID is the outbox event ID, so a redelivered event has the same ID and the console deduplicates on it. - An event your mapping returns `undefined` for is quarantined with the reason `Not a console audit event`, visible in `inspectDeadLetters`, and never sent. - The outbox must be created with the connector's environment ID. An event from another environment is left pending: neither mapped, sent nor quarantined. - The lease is measured from before the claim. A batch is not sent once less than a quarter of the lease (at most one second) remains, nor on a connection other than the one it was collected for; an event whose lease expires while its batch is collected is dropped from it. Each batch sent carries the events of one tenant (or one move's pair of tenants), checked right before it is sent; a pair is checked twice. The tenant groups of one claim are sent one after another, in claim order, each after the console answered the previous one, while the lease margin holds; what is left goes back to the outbox. - An event that names a tenant `isTenantEnabled` does not allow, on either side of a move, is quarantined with the reason `Tenant not enabled for the console` and never sent. A gate that throws leaves the event for a later attempt. - The connector becomes that outbox's consumer: do not run a second delivery worker on it. - Sharing's own membership changes write their audit rows to the sharing audit table, not to the outbox, so a console grant is not copied by this path unless your application also records it in the outbox. ## Guardrails [#guardrails] Rolebook Console can publish one set of [guardrails](/docs/guardrails) for the whole environment. The connector records the set in its state store, and `createConsoleGuardrails()` gives each of your processes the compiled set to run: ```ts import { createConsoleConnector, createConsoleGuardrails } from "@rolebook/connector"; import type { ConsoleConnectorOptions } from "@rolebook/connector"; import { createGuardedAuthorizer, createGuardrails } from "@rolebook/guardrails"; import type { Authorizer } from "rolebook"; declare const authorizer: Authorizer; // your createAuthorizer(policy) declare const options: ConsoleConnectorOptions; // as above, with authorizeAdministration const guardrails = createConsoleGuardrails({ compile: createGuardrails, state: options.state }); await guardrails.load(); // stop here if the recorded set cannot be read guardrails.start(); // then read it again refreshMs after each read ends // Every check runs the recorded set. const guarded = createGuardedAuthorizer(authorizer, guardrails.current); const connector = createConsoleConnector({ ...options, guardrails }); await connector.start(); ``` - **Offered when** you pass `guardrails` and `authorizeAdministration`. Your administration check is asked with `operation: "guardrails.activate"` when the command starts and again right before the set is recorded. If your check has a fall-through branch, give this operation its own. - **One store.** Pass `createConsoleGuardrails()` the same `state` object you pass the connector. The connector refuses an instance that reads another one, even of the same environment. - **What a command does.** The connector checks that the document is the one its signed hash names, compiles a copy of it with your `compile`, and replaces the one record in the state store with a compare-and-set. Nothing is recorded that `compile` refused, and `compile` must answer synchronously. The process that took the command runs the new set at once, dated from just before the write, or before the read that found it already recorded when the command is a repeat. A write the store took longer than `maxStaleMs` to answer leaves the set stale until a read confirms it. If the process loaded a newer set while the command ran, it keeps that one and the command answers `STALE`, with `RUNNING_NEWER` in its details when the write had already happened. - **Other processes** run the set from their next successful read. A started instance reads again `refreshMs` (5 seconds unless you set it) after each read ends, so that is usually within `refreshMs` plus the time of one read. A process that only decides checks needs `createConsoleGuardrails()` over the same store and no connector. - **When the record cannot be confirmed.** `guardrails.current()` throws until a read succeeded, and again when the store last agreed with the running set more than `maxStaleMs` ago (60 seconds, or three times `refreshMs` when that is larger, unless you set it; never less than three times `refreshMs`: one read, the wait and the next read. Time your `compile` takes, and a busy event loop, come on top of that, so leave room if either is slow). A check that your roles allow then answers `GUARDRAIL_ERROR`, which is a denial; a check your roles deny keeps its own code. A process that cannot confirm its set stops allowing instead of running one that may have been replaced. While reads fail, a process keeps the previous set for up to `maxStaleMs`. `onError` receives each failed read. A store call that never answers is not joined by another until `maxStaleMs` has passed. - **Before any set is published**, and after the console publishes an empty one, the set has no policies and every check keeps its role decision. - **A store that went back.** A process never runs an older set than the one it runs, and the connector answers `STALE` to a number below it. If the store's record goes back (a restored database), each such process keeps allowing under its set until `maxStaleMs` has passed and denies from then on, until the console publishes that set again or a newer one, or the process restarts and reads the store. A record that is absent after such a restore is reported as no set. - **A record the connector cannot run.** The connector says hello only after it has checked that the stored record is the document its hash names and that `compile` accepts it. A record it cannot read or run keeps it from connecting. Processes that already run a set keep it until `maxStaleMs` has passed and then deny; a process that starts denies at once. A connector that is still connected repairs a record whose document was damaged when the console sends that set again, or a newer one, provided the record still parses and has its number, its hash and a document. A record without those, and any record once no connector can connect, has to be repaired in the store. `startConsoleConnector()` takes the same `guardrails` option. Build the store for `ROLEBOOK_ENVIRONMENT_ID` once, give it to `createConsoleGuardrails()`, and return that same object from the `state` function. ## API [#api] `@rolebook/connector` ### `createConsoleConnector` [#createconsoleconnector] ```ts api="@rolebook/connector" function createConsoleConnector(input: ConsoleConnectorOptions): ConsoleConnector; ``` ### `ConsoleConnector` [#consoleconnector] `maxConcurrentMutations` is a diagnostic: the highest number of state-changing commands that ran at once, which is always at most 1. ```ts api="@rolebook/connector" interface ConsoleConnector { start(): Promise; stop(): Promise; readonly events: ConsoleConnectorEvents; readonly maxConcurrentMutations: number; } ``` ### `startConsoleConnector` [#startconsoleconnector] Starts the connector from `ROLEBOOK_CONSOLE_URL`, `ROLEBOOK_ENVIRONMENT_ID`, `ROLEBOOK_SERVICE_KEY` and `ROLEBOOK_SIGNING_KEYS`. With none set it returns `undefined` and builds nothing; with some set, or any malformed, it throws naming the variables, never their values. An unreachable console does not fail startup. ```ts api="@rolebook/connector" function startConsoleConnector(options: StartConsoleConnectorOptions): ConsoleConnector | undefined; ``` ### `StartConsoleConnectorOptions` [#startconsoleconnectoroptions] ```ts api="@rolebook/connector" type StartConsoleConnectorOptions = Omit & { readonly env?: Readonly>; readonly state: (environmentId: string) => ConsoleConnectorOptions["state"]; }; ``` ### `ConsoleConnectorOptions` [#consoleconnectoroptions] ```ts api="@rolebook/connector" interface ConsoleConnectorOptions { readonly url: string; readonly environmentId: string; readonly serviceKey: string; readonly signingKeys: readonly SigningPublicKey[]; readonly sharing: ConsoleSharing; readonly consolePrincipal: ResourceRef; readonly isTenantEnabled: (tenantId: string) => boolean | Promise; readonly schema: AppSchema; readonly state: ConnectorStateStore; readonly directory?: ConsoleDirectory; readonly inspection?: boolean; readonly audit?: ConsoleAuditOptions; readonly guardrails?: ConsoleGuardrails; readonly authorizeAdministration?: (request: ConsoleAdministrationRequest) => boolean | Promise; readonly exportInvitationTokens?: boolean; readonly connector?: { readonly name: string; readonly version: string; }; readonly instanceId?: string; readonly clock?: () => Date; readonly random?: () => number; readonly WebSocket?: typeof WebSocket; readonly idleTimeoutMs?: number; readonly commandTimeoutMs?: number; readonly maxPendingBytes?: number; } ``` ### `ConsoleAdministrationRequest` [#consoleadministrationrequest] ```ts api="@rolebook/connector" type ConsoleAdministrationRequest = { readonly operation: "policy.activate"; readonly principal: ResourceRef; } | { readonly operation: "guardrails.activate"; readonly principal: ResourceRef; } | { readonly operation: "tenantRoles.set"; readonly principal: ResourceRef; readonly tenantId: string; }; ``` ### `createConsoleGuardrails` [#createconsoleguardrails] The guardrail set a process runs, read from the connector's state store. See [Guardrails](#guardrails). ```ts api="@rolebook/connector" function createConsoleGuardrails(options: ConsoleGuardrailsOptions): ConsoleGuardrails; ``` ### `ConsoleGuardrailsOptions` [#consoleguardrailsoptions] `compile` must answer synchronously and is given its own copy of the document. `state` is the object the connector is given. `refreshMs` is an integer from 100 to 300,000 and defaults to 5,000. `maxStaleMs` is an integer from three times `refreshMs` to 86,400,000 and defaults to 60,000, or to three times `refreshMs` when that is larger. `onError` is called once with each failed read. `now` is a monotonic clock in milliseconds and defaults to `performance.now`. ```ts api="@rolebook/connector" interface ConsoleGuardrailsOptions { readonly compile: (document: unknown) => TGuardrails; readonly state: Pick; readonly refreshMs?: number; readonly maxStaleMs?: number; readonly onError?: (error: unknown) => void; readonly now?: () => number; } ``` ### `ConsoleGuardrails` [#consoleguardrails] `active` is the number and hash of the set this process last loaded: `null` when no set was ever activated, `undefined` before the first one. It stays the same while `current()` throws because the set went stale. `load()` rejects when the read fails, when the record cannot be run, and when the record is older than the set this process runs. `start()` reads now and again `refreshMs` after each read ends. ```ts api="@rolebook/connector" interface ConsoleGuardrails { readonly current: () => TGuardrails; readonly active: { readonly number: number; readonly hash: string; } | null | undefined; load(): Promise; start(): void; stop(): void; } ``` ### `ConsoleGuardrailsUnavailable` [#consoleguardrailsunavailable] Thrown by `current()` before the first successful read (`not_loaded`) and when the store last agreed with the running set more than `maxStaleMs` ago (`stale`). ```ts api="@rolebook/connector" class ConsoleGuardrailsUnavailable extends Error { readonly reason: "not_loaded" | "stale"; constructor(reason: "not_loaded" | "stale"); } ``` ### `ConsoleSharing` [#consolesharing] ```ts api="@rolebook/connector" type ConsoleSharing = ResourceSharing & { readonly policies?: PolicyAdministration; readonly customRoles?: CustomRoleAdministration; current?(): { readonly generation: string; readonly digest: string; }; refresh?(): Promise<{ readonly generation: string; readonly digest: string; }>; }; ``` The application's Sharing instance. A change's lost outcome is resolved through its tenants' `lookupExecution`; a tenant without it leaves such an outcome `unknown`. `tenantRoles` needs `customRoles.set`. ### `ConsoleDirectory` [#consoledirectory] Optional. With it, the connector advertises `directory` and answers the console's customer, people and item lookups from your handlers; every answer is validated against the protocol schema. ```ts api="@rolebook/connector" interface ConsoleDirectory { listCustomers(params: CommandParams<"directory.listCustomers">): Promise>; getCustomer(params: CommandParams<"directory.getCustomer">): Promise | undefined>; searchPeople(params: CommandParams<"directory.searchPeople">): Promise>; getPeople(params: CommandParams<"directory.getPeople">): Promise>; listResources(params: CommandParams<"directory.listResources">): Promise>; } ``` ### `ConsoleAuditOptions` [#consoleauditoptions] ```ts api="@rolebook/connector" interface ConsoleAuditOptions { readonly outbox: OutboxDeliveryPort; readonly toEvent: (event: OutboxDeliveryEvent) => OutboxEvent | undefined; readonly batchSize?: number; readonly leaseMs?: number; readonly pollMs?: number; } ``` ### `UNMAPPED_AUDIT_REASON` [#unmapped_audit_reason] ```ts api="@rolebook/connector" const UNMAPPED_AUDIT_REASON = "Not a console audit event"; ``` ### `DISABLED_TENANT_AUDIT_REASON` [#disabled_tenant_audit_reason] ```ts api="@rolebook/connector" const DISABLED_TENANT_AUDIT_REASON = "Tenant not enabled for the console"; ``` ### `MAX_PENDING_COMMANDS` [#max_pending_commands] ```ts api="@rolebook/connector" const MAX_PENDING_COMMANDS = 64; ``` ### `MAX_PENDING_BYTES` [#max_pending_bytes] ```ts api="@rolebook/connector" const MAX_PENDING_BYTES: number; ``` ### `MAX_QUEUED_COMMANDS` [#max_queued_commands] ```ts api="@rolebook/connector" const MAX_QUEUED_COMMANDS: number; ``` ### `MAX_DEDUP_ENTRIES` [#max_dedup_entries] ```ts api="@rolebook/connector" const MAX_DEDUP_ENTRIES = 4096; ``` ### `ConsoleConnectorEvent` [#consoleconnectorevent] ```ts api="@rolebook/connector" type ConsoleConnectorEvent = { readonly type: "connected"; readonly primary: boolean; } | { readonly type: "disconnected"; readonly code: number; readonly retryInMs?: number; } | { readonly type: "halted"; readonly code: number; } | { readonly type: "command"; readonly name: string; readonly outcome: "applied" | "already_applied" | "answered" | "refused" | "failed"; readonly code?: string; } | { readonly type: "audit"; readonly sent: number; readonly acknowledged: boolean; } | { readonly type: "frame_rejected"; readonly reason: "malformed" | "oversized" | "overloaded"; }; ``` ### `ConsoleConnectorEvents` [#consoleconnectorevents] ```ts api="@rolebook/connector" interface ConsoleConnectorEvents { on(type: T, listener: (event: Extract) => void): () => void; } ``` ### `ConsoleConnectorEventType` [#consoleconnectoreventtype] ```ts api="@rolebook/connector" type ConsoleConnectorEventType = ConsoleConnectorEvent["type"]; ``` ### `validConsoleUrl` [#validconsoleurl] ```ts api="@rolebook/connector" function validConsoleUrl(value: unknown): value is string; ``` ### `validSigningKey` [#validsigningkey] ```ts api="@rolebook/connector" function validSigningKey(key: unknown): key is SigningPublicKey; ``` ### `CONNECTOR_ENVIRONMENT_VARIABLES` [#connector_environment_variables] ```ts api="@rolebook/connector" const CONNECTOR_ENVIRONMENT_VARIABLES: readonly [ "ROLEBOOK_CONSOLE_URL", "ROLEBOOK_ENVIRONMENT_ID", "ROLEBOOK_SERVICE_KEY", "ROLEBOOK_SIGNING_KEYS" ]; ``` ### `ConnectorConfigurationResult` [#connectorconfigurationresult] ```ts api="@rolebook/connector" type ConnectorConfigurationResult = { readonly enabled: false; } | { readonly enabled: true; readonly url: string; readonly environmentId: string; readonly serviceKey: string; readonly signingKeys: readonly SigningPublicKey[]; }; ``` ### `parseConnectorEnvironment` [#parseconnectorenvironment] ```ts api="@rolebook/connector" function parseConnectorEnvironment(env: Readonly>): ConnectorConfigurationResult; ``` ### `parseSigningKeys` [#parsesigningkeys] ```ts api="@rolebook/connector" function parseSigningKeys(value: string): readonly SigningPublicKey[]; ``` ### `ConnectorAdmission` [#connectoradmission] ```ts api="@rolebook/connector" interface ConnectorAdmission { readonly tenantId: string; readonly commandId: string; readonly seq: number; readonly payloadHash: string; readonly resourceType: string; readonly resourceId: string; readonly expiresAt: number; } ``` ### `ConnectorAdmissionResult` [#connectoradmissionresult] ```ts api="@rolebook/connector" type ConnectorAdmissionResult = "admitted" | "exists" | "stale" | "jump"; ``` ### `ConnectorReceiptState` [#connectorreceiptstate] ```ts api="@rolebook/connector" type ConnectorReceiptState = "pending" | "started" | "committed" | "refused" | "expired" | "unknown"; ``` ### `ConnectorReceipt` [#connectorreceipt] ```ts api="@rolebook/connector" interface ConnectorReceipt { readonly tenantId: string; readonly seq: number; readonly payloadHash: string; readonly resourceType: string; readonly resourceId: string; readonly expiresAt: number; readonly state: ConnectorReceiptState; readonly outcome: string | undefined; } ``` ### `ConnectorTransition` [#connectortransition] ```ts api="@rolebook/connector" interface ConnectorTransition { readonly commandId: string; readonly payloadHash: string; readonly from: readonly ConnectorReceiptState[]; readonly to: ConnectorReceiptState; readonly outcome?: string; readonly notAfterExpiry?: number; readonly waitUntil?: number; } ``` ### `ConnectorCompletion` [#connectorcompletion] ```ts api="@rolebook/connector" interface ConnectorCompletion { readonly commandId: string; readonly payloadHash: string; readonly sharingRevision: string; } ``` ### `MAX_SEQUENCE_STEP` [#max_sequence_step] ```ts api="@rolebook/connector" const MAX_SEQUENCE_STEP: number; ``` ### `ConnectorSqlDialect` [#connectorsqldialect] ```ts api="@rolebook/connector" type ConnectorSqlDialect = "sqlite" | "postgres"; ``` ### `ConnectorSqlExecutor` [#connectorsqlexecutor] ```ts api="@rolebook/connector" interface ConnectorSqlExecutor { query(sql: string, values?: readonly (string | number | null)[]): Promise<{ readonly rows: readonly Readonly>[]; }>; } ``` ### `ConnectorStateStore` [#connectorstatestore] ```ts api="@rolebook/connector" interface ConnectorStateStore { readonly environmentId: string; highestCommittedSeq(): Promise; readReceipt(commandId: string): Promise; admitCommand(admission: ConnectorAdmission): Promise; transition(change: ConnectorTransition): Promise; completeReceipt(input: ConnectorCompletion): Promise; hasUnresolvedBefore(seq: number): Promise; sweep(now: number, skewMs: number): Promise; read(key: string): Promise; write(key: string, value: string): Promise; writeOnce(key: string, value: string): Promise; compareAndSet(key: string, expected: string | undefined, value: string): Promise; list(prefix: string): Promise; } ``` ### `connectorStateMigrations` [#connectorstatemigrations] ```ts api="@rolebook/connector" function connectorStateMigrations(options: { readonly dialect: ConnectorSqlDialect; readonly tablePrefix?: string; }): readonly string[]; ``` ### `createMemoryConnectorStateStore` [#creatememoryconnectorstatestore] ```ts api="@rolebook/connector" function createMemoryConnectorStateStore(options: { readonly environmentId: string; }): ConnectorStateStore; ``` ### `createSqlConnectorStateStore` [#createsqlconnectorstatestore] ```ts api="@rolebook/connector" function createSqlConnectorStateStore(options: { readonly executor: ConnectorSqlExecutor; readonly dialect: ConnectorSqlDialect; readonly environmentId: string; readonly tablePrefix?: string; }): ConnectorStateStore; ``` # Decision service (/docs/decision-service) > @rolebook/decision-service: authenticated single and batch Core checks through a Fetch handler. `@rolebook/decision-service` answers Rolebook Core checks for other services over HTTP. A caller names a subject, a resource and a concrete action; the service authenticates the caller, loads the authoritative facts through a provider your deployment registers, evaluates them with the [engine](/docs/api), and returns either a completed decision or a typed no-decision. Use it when a service that does not embed the engine needs the same answers, including services in other languages. To serve the Sharing operations to a browser or an SDK, use the [Sharing HTTP API](/docs/http-api) instead. [Choose how decisions run](/docs/choosing) compares the two, and the [security model](/docs/security-model#the-decision-service) states what the service guarantees and what your deployment establishes. > **Not on npm yet.** `rolebook` and `@rolebook/decision-service` are not on npm yet. The npm package named `rolebook` is an unrelated project, so do not install it. ## Create the service [#create-the-service] `createDecisionService(config)` returns `{ fetch, replaceRegistry, close }`. The package has no listener, credential verifier, authority source or default clock: each one is an explicit dependency that your deployment supplies. ```ts title="decisions.ts" group=service import { createDecisionService, type AuthorityProvider, type Clock, type CredentialVerifier, } from "@rolebook/decision-service"; // Supplied and qualified by your deployment. The package ships no implementation of any of them. declare const clock: Clock; // wall and monotonic time declare const randomBytes: (length: number) => Uint8Array; // a cryptographically secure source declare const credentialVerifier: CredentialVerifier; // your issuer, audience, expiry and revocation declare const directoryProvider: AuthorityProvider; // loads assignments and resources from your source declare const policyBytes: Uint8Array; // the raw JSON bytes of the Rolebook policy, at most 1 MiB export const service = createDecisionService({ clock, randomBytes, credentialVerifier, initialRegistry: { grants: [ { credentialId: "cred-billing", actorId: "svc-billing", scopeId: "acme", operations: ["check", "check_batch"], subjectSelector: { kind: "any_in_scope" }, }, ], scopes: [ { scopeId: "acme", generation: "acme-2026-11-12", modelId: "main", policyGeneration: "policy-41", policyP1: policyBytes, authorityProfileId: "acme-directory/v3", provider: directoryProvider, maxFactAgeMs: 5000, }, ], }, }); // Mount `service.fetch` in your trusted HTTP host. ``` The configuration is copied, validated and frozen; an invalid one throws `TypeError`. `fetch` never rejects. `replaceRegistry(next)` validates and compiles the whole next registry and then publishes it in one step; a failure throws and keeps the current one. `close()` refuses new calls, aborts active work and resolves once every started verifier and provider call has settled. ## Routes and requests [#routes-and-requests] | Route | Body | | --- | --- | | `POST /v1/scopes/{scopeId}/decisions:check` | `CheckEnvelope`: one `check` | | `POST /v1/scopes/{scopeId}/decisions:checkBatch` | `BatchEnvelope`: 1 to 100 `checks`, each with a unique `id` | The request and response media type is `application/vnd.rolebook.decision-service.v1+json`, and the caller sends `Authorization: Bearer `. A request identifies the subject, the resource, the action and optionally one field. It cannot carry policies, assignments, memberships, context or resource facts, and an object with an unknown member is refused. ```ts title="caller.ts" group=caller import type { CheckEnvelope, Decision, NoDecision } from "@rolebook/decision-service"; declare const serviceUrl: string; // where your host mounts the service declare const token: string; // the calling service's credential // Written by your application; the package exports no client parser. It must throw unless the // response has the expected media type, a closed body of the documented shape, an `allowed` that // agrees with `code`, and an `error` that belongs to the HTTP status it arrived with. declare const decodeCheckResponse: (response: Response) => Promise; const body: CheckEnvelope = { contract: "rolebook/decision-service/v1", semanticProfile: "rolebook/core-v4", scalarProfile: "rolebook/scalars-p1/v1", model: { kind: "current" }, freshness: { kind: "captured_inputs" }, check: { subject: { type: "user", id: "alice" }, resource: { type: "project", id: "p1" }, action: "read", }, }; const response = await fetch(`${serviceUrl}/v1/scopes/acme/decisions:check`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/vnd.rolebook.decision-service.v1+json", }, body: JSON.stringify(body), }); // Validate before trusting anything in the body. A thrown error here is a failed call, not a denial. const result = await decodeCheckResponse(response); if (result.kind === "decision") { if (!result.allowed) throw new Error(`denied: ${result.code}`); } else { // Not an answer about access. Do not proceed, and report it as an availability problem. throw new Error(`no decision: ${result.error}`); } ``` Never cast the response body to a result type and branch on it. Your decoder is the only thing between the wire and an access decision, so it validates all of the following and throws on any mismatch: the HTTP status, the response media type, a closed body with no unknown members, `allowed` being `true` exactly when `code` is `ALLOWED`, and each `error` arriving with its own status from the table below. A network failure or a decoder error is a failed call, never a denial and never an allow. Every response also carries `requestId` in the body and in `X-Request-Id`, with one exception: a 500 `internal_fault` sent when no request ID could be generated has none, so a decoder must accept that body without it. ## Authentication and grants [#authentication-and-grants] Authentication identifies the calling actor and runs before the body is read. The verifier returns a `CredentialIdentity`, or `null` for a credential that is not valid; there is no anonymous fallback. Grants then decide what that actor may ask: each one maps a credential and actor to one scope and its operations. A `bound` grant may check only its own subject, and `any_in_scope` may check any subject in the scope. An unknown scope, another scope, another actor and an ungranted operation all answer the same `forbidden`. Every item of a batch passes preflight before any authority provider runs. ## Authority providers [#authority-providers] For each check the service calls `provider.load(input)` with the scope, actor, subject, resource, permission, optional field and the pinned policy identity. The provider returns one of three results: | Result | Meaning | Outcome | | --- | --- | --- | | `{ kind: "complete", bytes }` | The raw bytes of one `AuthorityDocument`, at most 1 MiB | Evaluated when the document is valid and fresh | | `{ kind: "not_found" }` | The subject or resource is confirmed absent | 403 `subject_or_resource_unavailable` | | `{ kind: "unavailable" }`, or a throw | The source could not be read | 503 `authority_unavailable` | The statuses in this table are for a single check. In a batch that passed preflight, a failed provider outcome is a `no_decision` item inside the HTTP 200 response, and valid authority still produces a decision for its item; only a failure of the whole request changes the batch's status. A document must name the requested subject and resource, the scope, the pinned policy generation and digest, and an `observedAtMs` no older than the scope's `maxFactAgeMs`; otherwise the result is a no-decision. Its `binding` and `resource` go to the engine unchanged. Produce the bytes from your source under the [P1 profile](/docs/scalars-p1); `sourceRevision` is opaque evidence and not an ordering token or a write fence. ## Decisions and no-decisions [#decisions-and-no-decisions] Only `ALLOWED`, `EXPLICIT_DENY` and `NOT_GRANTED` are completed decisions, returned with HTTP 200 together with the policy generation and digest that were used and the times the facts were observed and evaluated. An unavailable provider, an invalid authority document, a timeout or a registry replacement during the request is a no-decision. It never becomes a denial or an allow, and nothing falls back to cached facts, caller facts or empty authority. A batch answers each item in input order and keeps a failed item apart from a failed whole request. Responses carry no reasons, policies, facts, assignments or matched roles. | Status | `error` | | --- | --- | | 400 | `malformed_input`, `unsupported_profile`, `unsupported_model`, `unsupported_freshness` | | 401 | `unauthenticated` | | 403 | `forbidden`, `subject_or_resource_unavailable` | | 404, 405 | `route_not_found`, `method_not_allowed` | | 413, 415 | `request_too_large`, `unsupported_media` | | 429 | `scope_busy` | | 500 | `internal_fault` | | 503 | `service_busy`, `authentication_unavailable`, `authority_unavailable`, `authority_invalid`, `configuration_changed`, `clock_unavailable` | | 504 | `deadline_exceeded` | Core's validation codes map to `authority_invalid`, because the caller's request already passed preflight; see [how engine codes map](/docs/decisions#decisions-from-the-decision-service-and-offline-snapshots). A decision is an observation at the decision point, not a transaction fence for a later write. ## Limits [#limits] | Budget | Value | | --- | --- | | Request body, single and batch | 64 KiB and 256 KiB | | Policy and authority document | 1 MiB each | | Overall deadline, single and batch | 2 seconds and 5 seconds | | Authentication, and each provider call | 500 ms and 1 second | | Concurrent requests per service instance | 32, then `service_busy` | | Concurrent requests per scope, within that instance | 8, then `scope_busy` | | Concurrent provider calls per scope, within that instance | 8, then `scope_busy` | | Provider calls of one batch at once | 4, started in input order | | `maxFactAgeMs` | 0 to 60,000 | These are fixed admission budgets, not performance figures. The concurrency limits belong to one service instance: each `createDecisionService()` result has its own 32 and its own per-scope limits, and they carry over when you replace its registry. A timed-out callback keeps the capacity it occupies in that instance until it actually settles, so abandoned work cannot grow without bound; JavaScript cannot forcibly stop a promise or synchronous code, so verifiers and providers must be nonblocking. ## Deployment responsibilities [#deployment-responsibilities] Before you expose the service, supply and qualify each of the following against its real source. Tests that use stand-ins do not establish these properties. - **A credential verifier**, checked against its real issuer, audience, expiry, revocation and key custody. - **An authority provider for each scope.** The service cannot tell whether a document marked `complete: true` is complete: a provider that omits a deny assignment produces an allow the service cannot detect. Qualify scope isolation, complete assignments including denies and flat memberships, complete ordered ancestry, resource existence, and confirmed absence versus unavailable data. - **A trusted HTTP host** that terminates TLS, rejects duplicate headers, normalizes the raw request target before it constructs the `Request`, and owns rate limiting and connection teardown. - **Clocks.** Freshness compares the provider's `observedAtMs` with the service's wall clock, so the accuracy between the two is yours to maintain. The service answers checks against the current policy of a scope from facts its provider loads. Listing, explanations, sharing changes and protected writes belong to the [Sharing packages](/docs/sharing). ## API reference [#api-reference] ### `createDecisionService` [#createdecisionservice] ```ts api="@rolebook/decision-service" function createDecisionService(config: DecisionServiceConfig): DecisionService; ``` ### `AuthorityDocument` [#authoritydocument] ```ts api="@rolebook/decision-service" interface AuthorityDocument { readonly authorityProfileId: string; readonly scopeId: string; readonly modelId: string; readonly policyGeneration: string; readonly policyDigest: string; readonly observedAtMs: number; readonly sourceRevision: string; readonly complete: true; readonly binding: CoreBindInput; readonly resource: CoreTrustedResource; } ``` ### `AuthorityLoadInput` [#authorityloadinput] ```ts api="@rolebook/decision-service" interface AuthorityLoadInput { readonly scopeId: string; readonly actorId: string; readonly subject: Ref; readonly resource: Ref; readonly permission: string; readonly field?: string; readonly modelId: string; readonly policyGeneration: string; readonly policyDigest: string; readonly requestId: string; readonly itemId?: string; readonly signal: AbortSignal; readonly deadlineMonotonicMs: number; } ``` ### `AuthorityLoadResult` [#authorityloadresult] ```ts api="@rolebook/decision-service" type AuthorityLoadResult = { readonly kind: "complete"; readonly bytes: Uint8Array; } | { readonly kind: "not_found"; } | { readonly kind: "unavailable"; }; ``` ### `AuthorityProvider` [#authorityprovider] ```ts api="@rolebook/decision-service" interface AuthorityProvider { load(input: AuthorityLoadInput): Promise; } ``` ### `BatchEnvelope` [#batchenvelope] ```ts api="@rolebook/decision-service" interface BatchEnvelope extends EnvelopeHeader { readonly checks: readonly { readonly id: string; readonly check: CheckItem; }[]; } ``` ### `BatchResponse` [#batchresponse] ```ts api="@rolebook/decision-service" type BatchResponse = { readonly kind: "batch"; readonly requestId: string; readonly results: readonly { readonly id: string; readonly result: Decision | NoDecision; }[]; } | (NoDecision & { readonly requestId: string; }); ``` ### `CheckEnvelope` [#checkenvelope] ```ts api="@rolebook/decision-service" interface CheckEnvelope extends EnvelopeHeader { readonly check: CheckItem; } ``` ### `CheckItem` [#checkitem] ```ts api="@rolebook/decision-service" interface CheckItem { readonly subject: Ref; readonly resource: Ref; readonly action: string; readonly field?: string; } ``` ### `Clock` [#clock] ```ts api="@rolebook/decision-service" interface Clock { wallNowMs(): number; monotonicNowMs(): number; } ``` ### `CoreBindInput` [#corebindinput] ```ts api="@rolebook/decision-service" type CoreBindInput = BindInput; ``` ### `CoreTrustedResource` [#coretrustedresource] ```ts api="@rolebook/decision-service" type CoreTrustedResource = TrustedResource; ``` ### `CredentialGrant` [#credentialgrant] ```ts api="@rolebook/decision-service" interface CredentialGrant { readonly credentialId: string; readonly actorId: string; readonly scopeId: string; readonly operations: readonly GrantOperation[]; readonly subjectSelector: SubjectSelector; } ``` ### `CredentialIdentity` [#credentialidentity] ```ts api="@rolebook/decision-service" interface CredentialIdentity { readonly credentialId: string; readonly actorId: string; } ``` ### `CredentialVerifier` [#credentialverifier] ```ts api="@rolebook/decision-service" interface CredentialVerifier { verify(input: { readonly authorization: string | undefined; readonly signal: AbortSignal; readonly deadlineMonotonicMs: number; }): Promise; } ``` ### `Decision` [#decision] ```ts api="@rolebook/decision-service" interface Decision { readonly kind: "decision"; readonly allowed: boolean; readonly code: DecisionCode; readonly policy: { readonly modelId: string; readonly policyGeneration: string; readonly digest: string; }; readonly consistency: { readonly kind: "captured_inputs"; readonly observedAtMs: number; readonly evaluatedAtMs: number; }; } ``` ### `DecisionCode` [#decisioncode] ```ts api="@rolebook/decision-service" type DecisionCode = "ALLOWED" | "EXPLICIT_DENY" | "NOT_GRANTED"; ``` ### `DecisionService` [#decisionservice] ```ts api="@rolebook/decision-service" interface DecisionService { fetch(request: Request): Promise; replaceRegistry(next: Registry): void; close(): Promise; } ``` ### `DecisionServiceConfig` [#decisionserviceconfig] ```ts api="@rolebook/decision-service" interface DecisionServiceConfig { readonly clock: Clock; readonly randomBytes: (length: number) => Uint8Array; readonly credentialVerifier: CredentialVerifier; readonly initialRegistry: Registry; readonly onDiagnostic?: (event: DiagnosticEvent) => void; } ``` ### `DiagnosticEvent` [#diagnosticevent] ```ts api="@rolebook/decision-service" interface DiagnosticEvent { readonly requestId: string; readonly error: ErrorCode; readonly category: string; readonly profileId?: string; } ``` ### `ErrorCode` [#errorcode] ```ts api="@rolebook/decision-service" type ErrorCode = "route_not_found" | "method_not_allowed" | "unauthenticated" | "forbidden" | "subject_or_resource_unavailable" | "request_too_large" | "unsupported_media" | "malformed_input" | "unsupported_profile" | "unsupported_model" | "unsupported_freshness" | "scope_busy" | "service_busy" | "authentication_unavailable" | "authority_unavailable" | "authority_invalid" | "configuration_changed" | "clock_unavailable" | "deadline_exceeded" | "internal_fault"; ``` ### `GrantOperation` [#grantoperation] ```ts api="@rolebook/decision-service" type GrantOperation = "check" | "check_batch"; ``` ### `NoDecision` [#nodecision] ```ts api="@rolebook/decision-service" interface NoDecision { readonly kind: "no_decision"; readonly error: ErrorCode; } ``` ### `Ref` [#ref] ```ts api="@rolebook/decision-service" interface Ref { readonly type: string; readonly id: string; } ``` ### `Registry` [#registry] ```ts api="@rolebook/decision-service" interface Registry { readonly grants: readonly CredentialGrant[]; readonly scopes: readonly ScopeDeployment[]; } ``` ### `ScopeDeployment` [#scopedeployment] ```ts api="@rolebook/decision-service" interface ScopeDeployment { readonly scopeId: string; readonly generation: string; readonly modelId: string; readonly policyGeneration: string; readonly policyP1: Uint8Array; readonly authorityProfileId: string; readonly provider: AuthorityProvider; readonly maxFactAgeMs: number; } ``` ### `SingleResponse` [#singleresponse] ```ts api="@rolebook/decision-service" type SingleResponse = (Decision | NoDecision) & { readonly requestId: string; }; ``` ### `SubjectSelector` [#subjectselector] ```ts api="@rolebook/decision-service" type SubjectSelector = { readonly kind: "bound"; readonly subject: Ref; } | { readonly kind: "any_in_scope"; }; ``` # Decisions, enforce, and explain (/docs/decisions) > Decision codes, check versus enforce, explanation traces, and fault reporting. Every check returns a frozen decision object, never a bare boolean: ```ts api="rolebook" interface AuthorizationDecision { readonly allowed: boolean; readonly code: DecisionCode; readonly reason: string; readonly permission: string; readonly policyVersion?: string; readonly matched?: MatchedRule; } ``` - `reason` is a short, stable English sentence for logs, such as `"A deny rule matched."`. - `permission` is the requested permission, or an empty string when the request's permission was not a string of at most 257 characters, so a decision never reflects unbounded caller input. - `policyVersion` is the policy's `version` label, when it has one. - `matched` is present on `ALLOWED` and `EXPLICIT_DENY`: the effect, the role that defines the matched rule, the rule's permission (which may be a wildcard such as `project:*`), and `via` when a group principal contributed it. ## Decision codes [#decision-codes] | Code | `allowed` | Meaning | | --- | --- | --- | | `ALLOWED` | `true` | An allow rule matched and no deny did. | | `EXPLICIT_DENY` | `false` | A deny rule matched (or its condition was unknown). | | `NOT_GRANTED` | `false` | No applicable allow rule matched. | | `UNKNOWN_ROLE` | `false` | An assignment names a role the policy does not define. | | `INVALID_ASSIGNMENT` | `false` | The assignments are malformed, or one's scope type does not match its role. | | `INVALID_SUBJECT` | `false` | The subject or the principals are malformed. | | `RESOURCE_MISMATCH` | `false` | The resource is malformed, the wrong type for the permission, or its ancestry does not follow the policy. | | `INVALID_REQUEST` | `false` | The binding or request is malformed, the permission is not declared, or evaluation itself faulted. | The order in which these are decided is described in [evaluation order](/docs/evaluation). ## `check` [#check] `check(request)` returns a decision and never throws for malformed runtime input. Use it when the caller decides what a denial means, for example to hide a button or filter a list. ## `enforce` [#enforce] `enforce(request)` returns the decision when it allows, and throws `AuthorizationError` on any denial. The error's `message` is the decision's `reason`, and `error.decision` is the full decision. ```ts prelude=core import { AuthorizationError } from "rolebook"; try { authorization.enforce({ permission: "project:delete", resource: project }); } catch (error) { if (error instanceof AuthorizationError) { console.log(error.decision.code); // "NOT_GRANTED" } else { throw error; } } ``` Map `AuthorizationError` deliberately at your framework boundary (the [Hono middleware](/docs/hono) maps it to 403). Do not use exceptions, reasons, or traces as an audit log. ## `explain` [#explain] `explain(request)` runs the same evaluation and returns the decision plus a trace of the rules it evaluated, in evaluation order: every applicable deny first, then allows, stopping at the first match. ```ts prelude=core const explanation = authorization.explain({ permission: "project:update", resource: project }); for (const entry of explanation.trace) { // entry.outcome: "matched" | "not_matched" // entry.effect, entry.role, entry.permission, entry.reason, and entry.via for group rules console.log(entry.outcome, entry.effect, entry.role, entry.permission); } if (explanation.traceTruncated) console.log("More rules were evaluated than the trace holds"); ``` The trace holds at most 64 entries; `traceTruncated` is `true` when evaluated rules were left out. Explanation never changes the decision. A request denied before rules are evaluated (a malformed binding, an unknown role) has an empty trace. ```ts prelude=core const detailed = authorization.explain( { permission: "project:update", resource: project }, { detail: "conditions" }, ); if (detailed.conditionTraceTruncated) console.log("A condition tree was shortened"); ``` `{ detail: "conditions" }` is the only options value that adds detail. Each retained rule then includes `details`: the compiled `ruleId` (the defining role and rule index in this policy snapshot), a `reasonCode`, and the condition outcome. A rule with no `where` has `condition.status` `"absent"`. A `where` that was not reached because the permission or field did not match is `"not_evaluated"`. An evaluated condition has its result (`true`, `false`, or `"unknown"`) and, while the budget allows, a tree of nodes addressed by JSON Pointer from `/where`. The tree omits runtime values and policy literals. The rule that decided the request always keeps its whole tree. The other retained rules share a budget of 256 condition nodes in evaluation order, so one explanation holds at most 512; `conditionTraceTruncated` is `true` only when a retained rule actually dropped an evaluated node. Rules past the 64-entry cap are described only by `traceTruncated`. `{}` and `{ detail: undefined }` give the rule-only trace. Any other options value, including one that cannot be inspected, also gives the rule-only trace and sets `optionsRejected: true` on the explanation; it does not report an internal fault. Keep detailed explanations on the server: fact names and rule ids are diagnostic metadata. ## One-shot forms [#one-shot-forms] `check(policy, request)`, `enforce(policy, request)`, and `explain(policy, request)` take the binding and the check fields together, for a single decision: ```ts prelude=core import { check } from "rolebook"; const decision = check(policy, { subject: { type: "user", id: "user_123" }, assignments: [ { subject: { type: "user", id: "user_123" }, role: "workspace_editor", scope: { resource: { type: "workspace", id: "ws_456" }, appliesTo: "descendants" }, }, ], permission: "project:read", resource: project, }); ``` They use the policy's shared authorizer, so they are as cheap as `createAuthorizer(policy).bind(...)`. A one-shot request accepts exactly the binding keys plus `permission`, `resource`, and `field`. ## Faults fail closed, and can be reported [#faults-fail-closed-and-can-be-reported] If evaluation itself throws, Rolebook returns `INVALID_REQUEST`: a fault must not tell a caller more than a malformed request does. That also makes an evaluator regression look like client error, so pass a reporter to tell them apart: ```ts prelude=core import { createAuthorizer } from "rolebook"; declare const logger: { error(fields: Record): void }; const observed = createAuthorizer(policy, { onInternalError: (error, { permission }) => logger.error({ err: error, permission }), }); ``` The reporter is diagnostics only. It never changes the decision, is never called for ordinary malformed input, runs synchronously on the decision path (hand the error off rather than doing work inline), and is ignored if it throws or returns a rejected promise. An authorizer created with a reporter is not the shared per-policy authorizer, though compilation is still reused. ## Decisions from the decision service and offline snapshots [#decisions-from-the-decision-service-and-offline-snapshots] The [decision service](/docs/decision-service) and the [offline verifier](/docs/offline) run this same decision path, on facts they load or receive on the caller's behalf. They report a narrower set of results: | Engine result | Decision service | Offline verifier | | --- | --- | --- | | `ALLOWED`, `EXPLICIT_DENY`, `NOT_GRANTED` | A decision with that code, HTTP 200 | A decision with that code | | `UNKNOWN_ROLE`, `INVALID_ASSIGNMENT`, `INVALID_SUBJECT`, `RESOURCE_MISMATCH`, `INVALID_REQUEST` | No-decision `authority_invalid` | No-decision `incomplete_snapshot` | | An `onInternalError` notification | No-decision `internal_fault` | No-decision `internal_fault` | In-process, a validation code is a denial because the caller supplied the malformed input. Behind the service or in a signed snapshot, the caller supplied only the question; malformed authority is a fault of the provider or the issuer, so it is reported as a no-decision and not as a denial of the subject. A decision from either component carries `allowed` and `code`, without the engine's human-readable `reason`, the `matched` rule, or a trace. A no-decision names its cause in a closed set: the service returns it as `error`, and the offline verifier as `reason`. See [decisions and no-decisions](/docs/choosing#decisions-and-no-decisions). # Evaluation order and deny precedence (/docs/evaluation) > Exactly how Rolebook turns a binding and a request into a decision. Every check runs the same steps, and stops at the first one that decides. The first failing validation step determines the denial code. ## Binding validation [#binding-validation] When you call `bind()` (or a one-shot function), the binding is snapshotted once: 1. **Envelope.** The binding must be a plain object with only `subject`, `principals`, `assignments`, and `context`. Otherwise every check is `INVALID_REQUEST`. 2. **Subject.** A malformed subject is `INVALID_SUBJECT`. 3. **Assignments.** The collection must be a dense array of at most 256 well-formed assignments within the snapshot budget. Otherwise `INVALID_ASSIGNMENT`. 4. **Principals.** At most 64 distinct references, none equal to the subject. Otherwise `INVALID_SUBJECT`. 5. **Context.** A plain object of JSON-like values, or omitted. Otherwise `INVALID_REQUEST`. A binding that fails here returns that same denial for every check made on it. ## Per-check steps [#per-check-steps] 6. **Request.** The request must be a plain object with only `permission`, `resource`, and `field`; the permission must be a concrete `resource:action` string; a `field`, when present, must be a valid path. Otherwise `INVALID_REQUEST`. 7. **Declared permission.** The policy must declare the action on the resource type. Otherwise `INVALID_REQUEST`. 8. **Resource.** The resource must be a well-formed snapshot of the permission's resource type, with an ancestry that follows the declared parents to the root. Otherwise `RESOURCE_MISMATCH`. 9. **Roles.** Every assignment must name a known role (`UNKNOWN_ROLE`) whose scope matches the assignment's scope resource type (`INVALID_ASSIGNMENT`). This is checked for the whole collection, not only for applicable assignments. 10. **Applicable rules.** Rolebook collects the effective rules (own and inherited) of every assignment whose subject is the bound subject or one of its principals and whose scope covers the resource: the scope resource is the checked resource itself, or, for `descendants`, appears in its ancestry. Assignments to the subject are collected before group assignments, and a rule held both ways is counted once, attributed to the subject. 11. **Denies.** Every applicable deny rule for the permission is evaluated. The first that matches decides `EXPLICIT_DENY`. 12. **Allows.** Then every applicable allow rule. The first that matches decides `ALLOWED`. 13. Otherwise `NOT_GRANTED`. An unexpected exception anywhere in these steps becomes `INVALID_REQUEST` and is passed to the authorizer's [`onInternalError`](/docs/decisions#faults-fail-closed-and-can-be-reported) reporter. ## When a rule matches [#when-a-rule-matches] A rule matches a request when all of these hold: - Its resource type is the requested type, and its action is the requested action or `*`. - Its field constraint matches (see [fields](/docs/conditions-and-fields#fields)): an allow needs a requested field that a pattern matches exactly; a deny matches any request that could expose a denied path, including a resource-wide request. - Its condition is true, or, for a deny only, unknown. ## Deny precedence [#deny-precedence] Denies are evaluated before allows across **every** applicable assignment, whichever role, scope, or principal contributed them. Consequences: - A deny in one role cannot be cancelled by an allow in another, even a more specific one. There is no rule ordering, priority, or specificity. - A deny reached through a group principal blocks the subject too. - A deny inherited from a base role stays a deny in every role that inherits it. - A conditional deny whose fact is missing still denies. Use deny rules for invariants, and keep allows additive. When you need "allow everything except", write the allow and a deny for the exception: ```ts import { definePolicy } from "rolebook"; const policy = definePolicy({ resources: { workspace: { actions: ["read"] }, project: { parent: "workspace", actions: ["read", "update", "delete"] }, }, roles: { contributor: { scope: "workspace", rules: [ { effect: "allow", permission: "project:*" }, { effect: "deny", permission: "project:delete" }, ], }, }, }); ``` The [sharing package](/docs/sharing/delegation) relies on this property when it decides who may hand out a role: a manager can only grant what it holds, and its denies travel with the grant. # Fact schemas (/docs/fact-schemas) > Declare the facts your policy reads, catch mistyped fact paths and operand types before deployment, and check request facts before binding. A policy reads facts by path, and Core accepts any well-formed path. A typo such as `resource.stauts` is a valid policy: no request has that fact, so the comparison is unknown and an allow that needs it never matches. A **fact schema** declares which facts exist and what JSON types they hold. The optional `rolebook/authoring` entry point checks a policy, or the facts of one request, against that schema. `rolebook` never imports this entry point. If you do not use it, nothing changes. ## What these checks prove, and what they do not [#what-these-checks-prove-and-what-they-do-not] - Validation checks **shape only**: that a fact is present and has a declared type. It cannot prove that a fact is fresh or where it came from. Load facts from your own authoritative, tenant-scoped records, exactly as before. - A passing result is **never a grant**. Nothing in `rolebook/authoring` makes a request more permitted. - Core's decision does not change. `check`, `enforce`, and `explain` decide exactly as they would without a schema. A policy that `definePolicy()` accepts stays accepted by Core, even when the authoring checks reject it. Use the checks to stop a bad policy at deployment and to notice a broken fact loader. Do not use them to decide who may do what. ## Declare a fact schema [#declare-a-fact-schema] ```ts group=facts import { defineFactSchema } from "rolebook/authoring"; const projectFacts = defineFactSchema({ format: "rolebook-fact-schema", version: 1, id: "projects", facts: { "subject.department": { types: ["string"], required: true }, "subject.suspended": { types: ["boolean"] }, "resource.ownerId": { types: ["string"], required: true }, "resource.status": { types: ["string"] }, "resource.tags": { types: [{ array: "string" }] }, "resource.priority": { types: ["number", "null"] }, "context.ipCountry": { types: ["string", "null"] }, }, }); ``` The schema is plain data, so it can live in a JSON file next to the policy. Each key is a [fact path](/docs/conditions-and-fields#facts), and each declaration has: - `types`: one to six of `"string"`, `"number"`, `"boolean"`, `"null"`, `"object"`, one array type such as `{ array: "string" }`, or `"json"` on its own for any value; - `required`: optional, `false` by default. It means the fact must be present. A required fact may still be `null` when `"null"` is one of its types. `subject.type`, `subject.id`, `resource.type`, and `resource.id` are always known, required strings. Do not declare them. A path with dots means nested properties: `resource.metadata.visibility` is the `visibility` property of `resource.metadata`. When you declare both, the parent must allow `"object"` or `"json"`, because nothing else can be traversed. Arrays are never traversed, even when their elements are objects. A parent may be optional while a child is required: when the parent is missing, the child is reported missing. `defineFactSchema()` copies, checks, and freezes the schema, and throws a `FactSchemaError` when it is malformed. Its `diagnostics` point at each bad declaration, for example `/facts/subject.id` for a redeclared identity. The other functions accept only a schema that `defineFactSchema()` returned. A schema that went through `JSON.stringify` must be defined again. ## Check a policy before you deploy it [#check-a-policy-before-you-deploy-it] `compilePolicy()` defines the policy with `definePolicy()` and checks every condition against the schema. This draft has a mistyped path, and it applies `startsWith`, a string operator, to an array: ```ts group=facts import { compilePolicy } from "rolebook/authoring"; const draft = compilePolicy( { resources: { project: { actions: ["read", "update"] } }, roles: { editor: { scope: "project", rules: [ { effect: "allow", permission: "project:update", where: { all: [ { fact: "resource.ownerId", operator: "equals", value: { fact: "subject.id" } }, { fact: "resource.stauts", operator: "equals", value: "draft" }, { fact: "resource.tags", operator: "startsWith", value: "eng-" }, ], }, }, ], }, }, }, projectFacts, ); // draft.ok === false, and there is no draft.policy. // draft.diagnostics, without their messages: // { severity: "error", code: "UNKNOWN_FACT", pointer: "/roles/editor/rules/0/where/all/1/fact" } // { severity: "error", code: "INCOMPATIBLE_OPERANDS", pointer: "/roles/editor/rules/0/where/all/2/operator" } ``` `definePolicy()` accepts this draft. Only the authoring check rejects it. With the path fixed and `contains` in place of `startsWith`, the policy compiles. A warning does not stop it: ```ts group=facts import { createAuthorizer } from "rolebook"; const compiled = compilePolicy( { resources: { project: { actions: ["read", "update"] } }, roles: { editor: { scope: "project", rules: [ { effect: "allow", permission: "project:update", where: { all: [ { fact: "resource.ownerId", operator: "equals", value: { fact: "subject.id" } }, { fact: "resource.status", operator: "equals", value: "draft" }, { fact: "resource.tags", operator: "contains", value: "eng" }, ], }, }, { effect: "allow", permission: "project:read", where: { fact: "resource.priority", operator: "greaterThan", value: 2 }, }, ], }, }, }, projectFacts, ); // compiled.ok === true // compiled.diagnostics, without their messages: // { severity: "warning", code: "POSSIBLY_UNSUPPORTED_OPERANDS", pointer: "/roles/editor/rules/1/where/operator" } if (!compiled.ok) throw new Error("The policy failed its authoring checks"); const authorizer = createAuthorizer(compiled.policy); ``` `resource.priority` may be `null`, and `greaterThan` compares only numbers or strings, so some declared values cannot satisfy the comparison. That is a warning, not an error: at runtime such a comparison is unknown, and an allow does not match. `compiled.policy` is the object `definePolicy()` returns for the same input, with the same `canonicalPolicyJson()`. `analyzePolicy()` returns the same `ok`, `diagnostics`, and `truncated` without the policy. The analysis checks: - **Fact paths.** The left fact of every comparison and every fact-reference operand must be declared or be a reserved identity. Every node is visited, including branches that a runtime short circuit would skip. - **Operand types.** For each operator, it compares every declared type of the fact with every type of the operand. When no pair can work, it reports `INCOMPATIBLE_OPERANDS`. When some pairs cannot work, or a pair needs a value the schema cannot describe (a non-empty string, a non-empty array, a non-negative integer), it warns with `POSSIBLY_UNSUPPORTED_OPERANDS`. `equals`, `notEquals`, and `exists` accept any declared type. A literal operand is already checked by `definePolicy()`. - **Duplicate rules.** A direct rule whose canonical JSON equals an earlier rule of the same role is a `DUPLICATE_RULE` warning. The duplicate stays in the compiled policy. This is compatibility analysis. It does not prove that a condition can be true, and it does not look for contradictions, shadowed rules, or unused rules. ## Validate facts before you bind [#validate-facts-before-you-bind] `validateFacts()` checks the subject, the trusted resource, and the context you are about to bind. It performs no authorization. Decide in your own code what a failure means, and decide it before binding: ```ts group=facts import type { Subject, TrustedResource } from "rolebook"; import { type Diagnostic, validateFacts } from "rolebook/authoring"; type Outcome = "allowed" | "denied" | "unavailable"; function updateProject( subject: Subject, project: TrustedResource, context: { readonly ipCountry: string | null }, report: (diagnostics: readonly Diagnostic[]) => void, ): Outcome { const facts = validateFacts(projectFacts, { subject, resource: project, context }); if (!facts.ok) { // This application treats malformed facts like a database outage. Answering "denied" is // the other safe choice. Either way, the request is not bound or checked. report(facts.diagnostics); return "unavailable"; } const decision = authorizer .bind({ subject, assignments: [ { subject: { type: subject.type, id: subject.id }, role: "editor", scope: { resource: project.ref, appliesTo: "self" }, }, ], context, }) .check({ permission: "project:update", resource: project }); return decision.allowed ? "allowed" : "denied"; } ``` The assignment here is inline to keep the example short. Load assignments as you always do. Suppose a loader returns the priority as a string and drops the owner column: ```ts group=facts import { trustedResource } from "rolebook"; const alice: Subject = { type: "user", id: "alice", attributes: { department: "eng" } }; const broken = trustedResource({ type: "project", id: "p2" }, [], { status: "draft", priority: "high", }); const outcome = updateProject(alice, broken, { ipCountry: "DE" }, (diagnostics) => { for (const { severity, code, pointer } of diagnostics) console.log(severity, code, pointer); }); // error MISSING_REQUIRED_FACT /resource/ownerId // error FACT_TYPE_MISMATCH /resource/priority // outcome === "unavailable" ``` Without the validation, Core would still fail closed: the owner comparison is unknown, so the allow does not match and the answer is `"denied"`. Validation does not make that answer safer. It tells you that the loader is broken, and lets you choose an answer that says so. Pointers here are logical: `/resource/ownerId` names the fact `resource.ownerId`, which Core reads from the resource's `attributes`. They are not locations in your input. A structural problem, such as an `undefined` value anywhere in the facts, a malformed subject, or a value over Core's [limits](/docs/limits), is one `INVALID_FACTS` error at the empty pointer instead of per-fact diagnostics. ## What the checks deliberately do not do [#what-the-checks-deliberately-do-not-do] - **An `object` or `json` fact does not declare its children.** Declaring `resource.metadata` as `"object"` does not make `resource.metadata.visibility` known. Each path a policy references must be declared itself. - **Undeclared properties are allowed at runtime.** `validateFacts()` checks declared paths and ignores the rest, within Core's structural limits. It removes nothing. - **Missing optional facts are not warned about.** A policy may reference an optional fact, and a request may omit it. Core already fails closed on a missing fact: an allow does not match, and a conditional deny does. - **No rule is rewritten or removed.** Duplicates are reported and kept. Branches are never simplified by type. - **A policy Core accepts stays accepted by Core.** The checks run only where you call them. - **No duplicate-key detection.** The functions take parsed objects. If your schema or policy comes from JSON text, duplicate keys are your parser's concern. ## Diagnostics [#diagnostics] Every result has the same shape: `ok`, a frozen list of `diagnostics`, and `truncated`. | Code | Severity | Reported by | Meaning | | --- | --- | --- | --- | | `INVALID_SCHEMA` | error | `defineFactSchema` (thrown), the others | A malformed schema or declaration, or a schema that did not come from `defineFactSchema`. | | `INVALID_POLICY` | error | `analyzePolicy`, `compilePolicy` | `definePolicy()` rejects the policy. The error's text is not included. | | `UNKNOWN_FACT` | error | `analyzePolicy`, `compilePolicy` | A fact path, or a fact-reference operand, is not declared. | | `INCOMPATIBLE_OPERANDS` | error | `analyzePolicy`, `compilePolicy` | No declared type pair can satisfy the operator. | | `POSSIBLY_UNSUPPORTED_OPERANDS` | warning | `analyzePolicy`, `compilePolicy` | Some declared type pairs may not satisfy the operator. | | `DUPLICATE_RULE` | warning | `analyzePolicy`, `compilePolicy` | A direct rule repeats an earlier rule of the same role. | | `INVALID_FACTS` | error | `validateFacts` | The facts are structurally invalid. | | `MISSING_REQUIRED_FACT` | error | `validateFacts` | A required fact does not resolve. | | `FACT_TYPE_MISMATCH` | error | `validateFacts` | A fact's value matches none of its declared types. | - `ok` is `false` when there is any error. Warnings never make it `false`. - An operation records at most 128 diagnostics. `truncated` is `true` when it had more to report. Errors past the cap still count, so a truncated result with only warnings showing can still have `ok: false`. - `pointer` is an RFC 6901 JSON Pointer, not a line and column. In a policy it follows the policy's structure, such as `/roles/editor/rules/0/where/all/1/fact`. A comparison's type problem points at its `/operator`, and a duplicate rule at the rule. A schema declaration error points at `/facts/`, with the whole path as one segment. A structural failure uses the empty pointer. - The order is deterministic: schema paths and role names sorted by UTF-16 code unit, rules and conditions in declaration order. - `message` is a fixed sentence for each code. It never contains a path, a literal, or a value, so a diagnostic does not leak a fact. The wording is not a contract and may change: key your handling on `code`, `severity`, and `pointer`. Diagnostics name fact paths and role names. Treat them as authoring metadata, and decide yourself whether to show them to end users. ## Editor diagnostics [#editor-diagnostics] `toEditorDiagnostics(diagnostics)` returns a fresh frozen `{ pointer, severity, code, message }` for each diagnostic, in order, ready to hand to an editor integration. It reads no file and throws `TypeError("Invalid diagnostics")` for anything that is not a list of at most 128 well-formed diagnostics. The pointer is still a JSON Pointer: mapping it to a line in your source file is the editor's job. See the [`rolebook/authoring` API reference](/docs/api/authoring) for every signature. A runnable version of this page is `examples/authoring.ts` in the repository: `bun examples/authoring.ts`. # Quick start (/docs/getting-started) > Define a policy, bind a subject, check a permission. This page walks through one complete permission check in four short steps: - Define a **policy** with three resource types (organization, workspace, project) and an editor role. - **Bind** the signed-in user and the roles your app loaded for them. - Pass the target project as a **trusted resource** (with its parent workspace and organization) and call `check()`. - Throw on denial with `enforce()`, or inspect which rules ran with `explain()`. ## 1. Define a policy [#1-define-a-policy] Resources declare their concrete actions and at most one parent type. Roles live at a scope and hold allow and deny rules. Define the policy once, at module level, and reuse the returned object: `definePolicy()` validates it, freezes it, and caches its compiled form by object identity. ```ts title="policy.ts" group=quickstart import { definePolicy } from "rolebook"; export const policy = definePolicy({ version: "4.0.0", resources: { organization: { actions: ["read"] }, workspace: { parent: "organization", actions: ["read", "update"] }, project: { parent: "workspace", actions: ["read", "update", "delete"] }, }, roles: { workspace_editor: { scope: "workspace", rules: [ { effect: "allow", permission: "project:read" }, { effect: "allow", permission: "project:update" }, ], }, }, }); ``` `definePolicy()` throws an `Error` for a malformed policy, so a bad policy fails at startup rather than on a request. Permission strings are typed: `"project:archive"` would not compile, because `project` does not declare `archive`. ## 2. Bind the request [#2-bind-the-request] Load the subject's scoped assignments for this request from your own authoritative store, and bind them together with the authenticated subject. The subject itself never carries roles. ```ts group=quickstart import { createAuthorizer } from "rolebook"; const authorization = createAuthorizer(policy).bind({ subject: { type: "user", id: "user_123", attributes: { mfa: true } }, assignments: [ { subject: { type: "user", id: "user_123" }, role: "workspace_editor", scope: { resource: { type: "workspace", id: "ws_456" }, appliesTo: "descendants", }, }, ], context: { requestId: "req_789" }, }); ``` `appliesTo: "descendants"` makes the assignment cover the workspace itself and everything below it. ## 3. Check against a trusted resource [#3-check-against-a-trusted-resource] Load the resource through your authoritative, tenant-scoped data path, then snapshot it with its complete ancestry, from the immediate parent to the root. ```ts group=quickstart import { trustedResource } from "rolebook"; const project = trustedResource( { type: "project", id: "project_1" }, [ { type: "workspace", id: "ws_456" }, { type: "organization", id: "org_1" }, ], { ownerId: "user_123", status: "draft" }, ); const decision = authorization.check({ permission: "project:update", resource: project }); // decision.allowed === true // decision.code === "ALLOWED" // decision.matched -> { effect: "allow", role: "workspace_editor", permission: "project:update" } ``` The assignment applies because `ws_456` is in the project's ancestry. Checking `project:delete` returns `{ allowed: false, code: "NOT_GRANTED" }`: no applicable rule allows it. ## 4. Enforce or explain [#4-enforce-or-explain] `check()` never throws for malformed input; it returns a closed decision with a stable code. `enforce()` throws `AuthorizationError` on any denial, which suits handlers that should stop. `explain()` runs the same evaluation and adds a bounded trace of the rules it evaluated. ```ts group=quickstart import { AuthorizationError } from "rolebook"; try { authorization.enforce({ permission: "project:delete", resource: project }); } catch (error) { if (error instanceof AuthorizationError) console.log(error.decision.code); // "NOT_GRANTED" } const explanation = authorization.explain({ permission: "project:update", resource: project }); for (const entry of explanation.trace) { console.log(entry.outcome, entry.effect, entry.role, entry.permission); } ``` ## Next [#next] Resources, actions, rules, wildcards, and the policy lifecycle. Where a role lives, what it may target, and inheritance. Loading assignments and resources per tenant, safely. Guard Hono, Express 5, and Fastify 5 routes with a binding and resource per request. Policy tests as a table or as JSON, and the adapter contracts. Sharing, the HTTP API, the decision service, and offline snapshots around this engine. # Access guardrails (/docs/guardrails) > @rolebook/guardrails: organization-wide policies that block, hold for approval, or notify on top of role decisions. `@rolebook/guardrails` runs organization-wide policies after a Core decision. A policy can **block** an allowed request, **hold it for human approval**, or **allow it and notify**. Each policy is **enforced**, runs in **monitor** mode (evaluated and reported, never changing a decision), or stays a **draft** you only simulate. Recorded checks let you preview a policy's impact on real traffic before you enforce it. Guardrails only ever tighten. A request Core denies stays denied with its original code; an allowed request can become `BLOCKED` or `APPROVAL_REQUIRED`. No guardrail grants access a role does not give. The package has no database, network or framework dependency. It ships in-memory stores for the approval queue and the decision log; a production deployment implements the two small store interfaces against its own database. > **Not on npm yet.** `rolebook` and `@rolebook/guardrails` are not on npm yet. The npm package named `rolebook` is an unrelated project, so do not install it. ## Define policies [#define-policies] ```ts title="guardrails.ts" group=guard import { createGuardrails, type GuardrailPolicy } from "@rolebook/guardrails"; const prodDeploys: GuardrailPolicy = { id: "prod-deploys", name: "Production deploys need approval", status: "enforced", when: [ { field: "principal", operator: "isAnyOf", values: ["team:platform"] }, { field: "permission", operator: "matches", values: ["service:deploy", "environment:*"] }, { field: "scope.environment", operator: "isAnyOf", values: ["production"] }, ], effect: { type: "requireApproval", approvers: [{ type: "team", id: "security-oncall" }], requestTtlSeconds: 900, // a request waits 15 minutes for an answer grantTtlSeconds: 900, // an approval lets the subject repeat the check for 15 minutes }, except: [ { id: "sev1", label: "During a SEV1 incident", enabled: true, when: [{ field: "context.incident", operator: "isAnyOf", values: ["sev1"] }], notify: "#incidents", }, ], }; export const guardrails = createGuardrails({ format: "rolebook.guardrails/1", policies: [prodDeploys], }); ``` `createGuardrails()` validates the document and compiles it; `defineGuardrails()` validates without compiling. Both throw `GuardrailsError` with code `INVALID_GUARDRAILS` and the path of the first problem. A condition reads one field: | Field | Reads | | --- | --- | | `permission`, `action` | The requested permission (`service:deploy`) and the part after the colon (`deploy`). | | `resource.type`, `resource.id`, `resource.attributes.` | The checked resource. | | `scope.` | The ID of the resource itself or of its ancestor of that type. `scope.environment` matches a check on the environment or anything inside it. A resource with no ancestor of that type is outside every such scope. | | `subject.type`, `subject.id`, `subject.attributes.` | The caller. | | `principal` | The caller's group principals (teams), as `type:id`. | | `context.` | The bound request context. | `isAnyOf` and `isNoneOf` compare exact values. `matches` and `notMatches` compare strings with `*` as a wildcard, in linear time. `lessThan` and `greaterThan` compare one number. `exists` and `notExists` test presence. A multi-valued field (`principal`, an array attribute) matches `isAnyOf` and `matches` when any value does, and `isNoneOf` and `notMatches` when none does. ### Unknown facts fail closed [#unknown-facts-fail-closed] All of a policy's `when` conditions must hold. A condition whose answer is **unknown** counts as **holding**, so a gap in your request facts applies the guardrail rather than skipping it; the match is reported with `uncertain: true`. Exceptions loosen, so they apply only when every one of their conditions is known to hold. A comparison is unknown when the key is absent, when the value is not comparable (an object, `null`, or an array holding one), when its type matches none of the listed values (`isAnyOf [1]` against `"1"`), and when the whole bag is unavailable: `decide()` without `principals` or `context`, or a replayed record that dropped it. `exists` and `notExists` answer presence instead, which is known for every key of a supplied bag. So `rows exists AND rows > 500` skips a request without `rows`, where `rows > 500` alone applies. `scope.` is always known: core requires ancestry to the root, so an organization-level check is not inside any environment and `scope.environment isAnyOf ["production"]` is simply false there. A `principal` condition narrows a policy to those teams. ### Precedence [#precedence] When several enforced policies apply, `block` wins over `requireApproval`, which wins over `notify`. An applied exception turns that one policy into an allow. Every applied policy is listed in `decision.enforced`, and monitor-mode policies in `decision.monitored`. ## Check requests [#check-requests] Wrap a Core authorizer. The wrapper captures the binding and each request once, as frozen copies with exactly the shape you passed, and gives that same copy to Core, to the guardrails and to `onDecision`. Input it cannot copy faithfully (an unknown key, an accessor, a malformed array) goes to Core unchanged, and if Core still allows it the check is denied with `GUARDRAIL_ERROR`, so wrapping never allows what Core alone would refuse. A binding without `principals` or `context` leaves them unknown to the guardrails, as in `decide()`; bind `[]` or `{}` when the caller truly has none. A Core denial keeps its own code; a Core call that throws, failing guardrails or a failing clock deny an allowed check with `GUARDRAIL_ERROR`. The wrapper keeps the authorizer's role and permission types. Passing a function instead of a `Guardrails` value lets a running process swap the active set without rebuilding the authorizer. ```ts title="check.ts" group=guard import { createApprovals, createGuardedAuthorizer, createMemoryApprovalStore, createMemoryDecisionLog, recordFrom, } from "@rolebook/guardrails"; import { createAuthorizer, type RoleAssignment, type RolebookPolicy, type Subject, type TrustedResource, } from "rolebook"; declare const policy: RolebookPolicy; declare const subject: Subject; declare const assignments: readonly RoleAssignment[]; declare const resource: TrustedResource; const approvals = createApprovals({ store: createMemoryApprovalStore(), guardrails, tenant: "acme", // required, from your trusted session }); const decisionLog = createMemoryDecisionLog(); const guarded = createGuardedAuthorizer(createAuthorizer(policy), () => guardrails, { onDecision: (event) => decisionLog.append(recordFrom(event, { id: crypto.randomUUID() })), }); const decision = guarded .bind({ subject, principals: [{ type: "team", id: "platform" }], assignments, context: { incident: "none" }, }) .check( { permission: "service:deploy", resource }, { grants: await approvals.grantsFor(subject) }, ); if (decision.code === "APPROVAL_REQUIRED") { // Answer "pending"; nothing runs until someone approves and the caller checks again. await approvals.request({ decision, reason: "ship the fix" }); } // Proceed only when decision.allowed (ALLOWED or APPROVED); decision.notify lists who to tell. export const allowed = decision.allowed; ``` You can also call `guardrails.decide()` with a Core decision you already have. The checked permission is the decision's own; pass the `principals`, `field` and `context` the Core check was bound with. `decide()` never throws: a fault, an unreadable input, an unknown input key, an invalid `now` or a decision whose `allowed` and `code` disagree returns `GUARDRAIL_ERROR`, which is a denial. A failing or rejected `onDecision` callback never changes a decision. ## Approvals [#approvals] - `request({ decision })` takes the subject, permission, field, resource and ancestry from the guarded decision, and the approvers and TTLs from the active policy. Every missing approval is checked before anything is written; a decision made under other terms fails with `APPROVAL_STALE`. Pass the decision straight from your server-side check. - One live pending request exists per tenant, operation and terms; concurrent retries share it. - `approve()` and `reject()` need the active policy to still have the request's terms (`APPROVAL_STALE`) and an actor among that policy's current approvers who is not the requester (`SELF_APPROVAL`). A removed approver can neither grant nor reject. The actor is copied once, so the identity authorized is the identity recorded. - Every read and change uses the store's clock (`store.now()`), read under its lock for changes. A pending request whose `expiresAt` is not after it (or is unreadable) is `expired`. A policy edited while its request is being opened makes that open fail with `APPROVAL_STALE`, whether it would create a request or reuse one. - An approval is a **grant** for that exact operation, ancestry included. It lasts the active policy's `grantTtlSeconds`, may be repeated until then and is not consumed. `grantsFor()` returns the ones live at the store's time, at most 500, each stamped with that instant as `readAt` and noted, in this process, with a monotonic clock reading. `check()` estimates the store's current time as `readAt` plus the monotonic time since and counts a grant only while `expiresAt` is after both that estimate and its own clock, so a host behind the store never extends a grant. A grant without the note (copied, serialized or from another process) never counts. The reading is taken before the store's time is sampled, and two copies of the package in one process share the notes. An edit to the policy does not revoke grants already given. - Grants are server-side authority: load them with `grantsFor()`, never from a client. A malformed grant record is ignored on its own, without hiding valid ones. `tenant` is required and comes from your trusted session: one tenant's requests, answers and grants never reach another's, even in a shared store with repeated resource IDs. Ancestry alone does not separate queues. Load an actor's `principals` from that same tenant. An `ApprovalStore` makes each method atomic and supplies the time: `now()` for reads, and the time read after its lock for changes. `open(key, create, isLive)` gets or creates the pending request for `key`, calling `create(now)` under the lock. `update(id, change)` calls `change(row, now)` under a lock on the row and writes its result. `list()` keeps `query.tenant`, judges status at `query.at` and filters live grants before applying `limit`. `createMemoryApprovalStore({ clock })` is for tests, demos and single-process deployments. ## Impact previews [#impact-previews] Record checks with `recordFrom()` into any `DecisionLog` (`createMemoryDecisionLog()` is a bounded ring buffer), then replay a draft against a window: ```ts title="preview.ts" group=guard import { simulateGuardrail } from "@rolebook/guardrails"; const since = new Date(Date.now() - 7 * 86_400_000); const until = new Date(); const records = await decisionLog.read({ since, until, limit: 50_000 }); export const impact = simulateGuardrail({ ...prodDeploys, status: "draft" }, records, { since, until, truncated: records.length === 50_000, history: await approvals.list({ policyId: prodDeploys.id }), }); // impact.matched, impact.byEffect.requireApproval, impact.samples, impact.matchesPerDay ``` The simulation treats the policy as enforced whatever its status, counts only checks Core allowed (the only ones a guardrail can change), and writes nothing. Decision records hold subject, resource and context attributes so conditions can be replayed. Pass `keep: { subjectAttributes: false }` (or `resourceAttributes`, `context`) to `recordFrom()` to drop what you must not keep, and apply your own retention. The record lists what it dropped, so a condition on a dropped bag, even `exists`, replays as unknown and the match as `uncertain`. `matchesPerDay` divides by the window's actual length. ## Limits [#limits] At most 256 policies, 16 conditions per policy or exception, 64 values per condition, 8 exceptions and 32 approvers per policy. TTLs are whole seconds from 60 to 30 days. See `GUARDRAIL_LIMITS`. `guardrailsDigest()` returns a `sha256:` content address over the canonical JSON of a validated set, so two processes can confirm they run the same version. Key order does not matter and an empty `except` list equals none; the order of array entries does. Validation reads each property once from its descriptor and refuses accessors and sparse arrays. The package imports `node:crypto`, so it is not offered for a browser bundle. Its own tests run on Bun; no packed Node fixture exercises it yet. ## API reference [#api-reference] ### `ApprovalActor` [#approvalactor] ```ts api="@rolebook/guardrails" interface ApprovalActor { readonly subject: ResourceRef; readonly principals?: readonly ResourceRef[]; } ``` ### `ApprovalQuery` [#approvalquery] ```ts api="@rolebook/guardrails" interface ApprovalQuery { readonly status?: ApprovalStatus; readonly subject?: ResourceRef; readonly policyId?: string; readonly limit?: number; } ``` ### `ApprovalRequest` [#approvalrequest] ```ts api="@rolebook/guardrails" interface ApprovalRequest extends GuardedOperation { readonly id: string; readonly tenant: string; readonly key: string; readonly policyId: string; readonly revision?: number; readonly terms: string; readonly status: ApprovalStatus; readonly approvers: readonly ResourceRef[]; readonly reason?: string; readonly createdAt: string; readonly expiresAt: string; readonly grantTtlSeconds: number; readonly resolution?: { readonly by: ResourceRef; readonly at: string; readonly comment?: string; readonly grantExpiresAt?: string; }; } ``` ### `ApprovalStatus` [#approvalstatus] ```ts api="@rolebook/guardrails" type ApprovalStatus = "pending" | "approved" | "rejected" | "cancelled" | "expired"; ``` ### `ApprovalStore` [#approvalstore] ```ts api="@rolebook/guardrails" interface ApprovalStore { now(): Promise; open(key: string, create: (now: Date) => ApprovalRequest, isLive: (row: ApprovalRequest, now: Date) => boolean): Promise; get(id: string): Promise; list(query: ApprovalStoreQuery): Promise; update(id: string, change: (current: ApprovalRequest, now: Date) => ApprovalRequest): Promise; } ``` ### `Approvals` [#approvals-1] ```ts api="@rolebook/guardrails" interface Approvals { request(input: { readonly decision: GuardedDecision; readonly reason?: string; }): Promise; approve(input: { readonly requestId: string; readonly actor: ApprovalActor; readonly comment?: string; }): Promise; reject(input: { readonly requestId: string; readonly actor: ApprovalActor; readonly comment?: string; }): Promise; cancel(input: { readonly requestId: string; readonly actor: ApprovalActor; }): Promise; get(requestId: string): Promise; list(query?: ApprovalQuery): Promise; grantsFor(subject: ResourceRef): Promise; canApprove(request: ApprovalRequest, actor: ApprovalActor): boolean; } ``` ### `ApprovalsOptions` [#approvalsoptions] ```ts api="@rolebook/guardrails" interface ApprovalsOptions { readonly store: ApprovalStore; readonly guardrails: Guardrails | (() => Guardrails); readonly tenant: string; readonly ids?: () => string; } ``` ### `createApprovals` [#createapprovals] ```ts api="@rolebook/guardrails" function createApprovals(options: ApprovalsOptions): Approvals; ``` ### `createMemoryApprovalStore` [#creatememoryapprovalstore] ```ts api="@rolebook/guardrails" function createMemoryApprovalStore(options?: { readonly clock?: () => Date; }): ApprovalStore & { readonly size: number; }; ``` ### `medianApprovalWaitSeconds` [#medianapprovalwaitseconds] ```ts api="@rolebook/guardrails" function medianApprovalWaitSeconds(requests: readonly ApprovalRequest[]): number | undefined; ``` ### `DecisionLog` [#decisionlog] ```ts api="@rolebook/guardrails" interface DecisionLog { append(record: DecisionRecord): void | Promise; read(query: { readonly since: Date; readonly until: Date; readonly limit: number; }): Promise; } ``` ### `DecisionRecord` [#decisionrecord] ```ts api="@rolebook/guardrails" interface DecisionRecord { readonly id: string; readonly at: string; readonly subject: Subject; readonly principals: readonly ResourceRef[]; readonly permission: string; readonly field?: string; readonly resource: TrustedResource; readonly context: Readonly>; readonly dropped?: readonly DroppedFacts[]; readonly coreAllowed: boolean; readonly code: GuardedDecisionCode; readonly enforced: readonly string[]; readonly monitored: readonly string[]; } ``` ### `RecordOptions` [#recordoptions] ```ts api="@rolebook/guardrails" interface RecordOptions { readonly id: string; readonly keep?: { readonly subjectAttributes?: boolean; readonly resourceAttributes?: boolean; readonly context?: boolean; }; } ``` ### `createMemoryDecisionLog` [#creatememorydecisionlog] ```ts api="@rolebook/guardrails" function createMemoryDecisionLog(capacity?: number): DecisionLog & { readonly size: number; }; ``` ### `recordFrom` [#recordfrom] ```ts api="@rolebook/guardrails" function recordFrom(event: GuardedCheckEvent, options: RecordOptions): DecisionRecord; ``` ### `GuardrailsErrorCode` [#guardrailserrorcode] ```ts api="@rolebook/guardrails" type GuardrailsErrorCode = "INVALID_GUARDRAILS" | "APPROVAL_NOT_FOUND" | "APPROVAL_NOT_PENDING" | "APPROVAL_EXPIRED" | "NOT_AN_APPROVER" | "SELF_APPROVAL" | "NOT_THE_REQUESTER" | "NOTHING_TO_APPROVE" | "APPROVAL_STALE"; ``` ### `defineGuardrailPolicy` [#defineguardrailpolicy] ```ts api="@rolebook/guardrails" function defineGuardrailPolicy(value: unknown): GuardrailPolicy; ``` ### `defineGuardrails` [#defineguardrails] ```ts api="@rolebook/guardrails" function defineGuardrails(value: unknown): GuardrailSet; ``` ### `GUARDRAIL_LIMITS` [#guardrail_limits] ```ts api="@rolebook/guardrails" const GUARDRAIL_LIMITS: Readonly<{ policies: 256; conditions: 16; values: 64; exceptions: 8; approvers: 32; text: 256; description: 1024; refId: 128; minTtlSeconds: 60; maxTtlSeconds: number; }>; ``` ### `GUARDRAILS_FORMAT` [#guardrails_format] ```ts api="@rolebook/guardrails" const GUARDRAILS_FORMAT = "rolebook.guardrails/1"; ``` ### `GuardrailsError` [#guardrailserror] ```ts api="@rolebook/guardrails" class GuardrailsError extends Error { readonly code: GuardrailsErrorCode; constructor(code: GuardrailsErrorCode, message: string); } ``` ### `guardrailsDigest` [#guardrailsdigest] ```ts api="@rolebook/guardrails" function guardrailsDigest(set: GuardrailSet): string; ``` ### `isGuardrailField` [#isguardrailfield] ```ts api="@rolebook/guardrails" function isGuardrailField(value: unknown): boolean; ``` ### `GuardedAuthorizerOptions` [#guardedauthorizeroptions] ```ts api="@rolebook/guardrails" interface GuardedAuthorizerOptions { readonly onDecision?: (event: GuardedCheckEvent) => unknown; readonly clock?: () => Date; } ``` ### `GuardedBoundAuthorizer` [#guardedboundauthorizer] ```ts api="@rolebook/guardrails" interface GuardedBoundAuthorizer { check(request: CheckRequest, options?: { readonly grants?: readonly ApprovalGrant[]; }): GuardedDecision; } ``` ### `GuardedCheckEvent` [#guardedcheckevent] ```ts api="@rolebook/guardrails" interface GuardedCheckEvent { readonly at: string; readonly subject: Subject; readonly principals?: readonly ResourceRef[]; readonly permission: string; readonly field?: string; readonly resource: TrustedResource; readonly context?: Readonly>; readonly decision: GuardedDecision; } ``` ### `Guardrails` [#guardrails] ```ts api="@rolebook/guardrails" interface Guardrails { readonly set: GuardrailSet; decide(input: GuardrailInput): GuardedDecision; } ``` ### `createGuardedAuthorizer` [#createguardedauthorizer] ```ts api="@rolebook/guardrails" function createGuardedAuthorizer(authorizer: Authorizer, guardrails: Guardrails | (() => Guardrails), options?: GuardedAuthorizerOptions): { bind(input: BindInput): GuardedBoundAuthorizer; }; ``` ### `createGuardrails` [#createguardrails] ```ts api="@rolebook/guardrails" function createGuardrails(value: GuardrailSet | unknown): Guardrails; ``` ### `GuardrailImpact` [#guardrailimpact] ```ts api="@rolebook/guardrails" interface GuardrailImpact { readonly policyId: string; readonly scanned: number; readonly considered: number; readonly matched: number; readonly byEffect: Readonly>; readonly uncertain: number; readonly distinctSubjects: number; readonly matchesPerDay: number; readonly medianApprovalWaitSeconds?: number; readonly samples: readonly ImpactSample[]; readonly truncated: boolean; } ``` ### `ImpactSample` [#impactsample] ```ts api="@rolebook/guardrails" interface ImpactSample { readonly recordId: string; readonly at: string; readonly subject: ResourceRef; readonly permission: string; readonly resource: ResourceRef; readonly effect: GuardrailMatchEffect; readonly uncertain: boolean; } ``` ### `SimulateOptions` [#simulateoptions] ```ts api="@rolebook/guardrails" interface SimulateOptions { readonly since: Date; readonly until: Date; readonly sampleLimit?: number; readonly truncated?: boolean; readonly history?: readonly ApprovalRequest[]; } ``` ### `simulateGuardrail` [#simulateguardrail] ```ts api="@rolebook/guardrails" function simulateGuardrail(value: GuardrailPolicy | unknown, records: readonly DecisionRecord[], options: SimulateOptions): GuardrailImpact; ``` ### `DroppedFacts` [#droppedfacts] ```ts api="@rolebook/guardrails" type DroppedFacts = "subjectAttributes" | "resourceAttributes" | "context" | "principals"; ``` ### `ApprovalStoreQuery` [#approvalstorequery] ```ts api="@rolebook/guardrails" interface ApprovalStoreQuery extends ApprovalQuery { readonly tenant: string; readonly at: string; readonly grantLiveAt?: string; } ``` ### `GuardrailStatus` [#guardrailstatus] ```ts api="@rolebook/guardrails" type GuardrailStatus = "enforced" | "monitor" | "draft"; ``` ### `GuardrailField` [#guardrailfield] ```ts api="@rolebook/guardrails" type GuardrailField = "permission" | "action" | "resource.type" | "resource.id" | `resource.attributes.${string}` | `scope.${string}` | "subject.type" | "subject.id" | `subject.attributes.${string}` | "principal" | `context.${string}`; ``` ### `GuardrailOperator` [#guardrailoperator] ```ts api="@rolebook/guardrails" type GuardrailOperator = "isAnyOf" | "isNoneOf" | "matches" | "notMatches" | "exists" | "notExists" | "lessThan" | "greaterThan"; ``` ### `GuardrailScalar` [#guardrailscalar] ```ts api="@rolebook/guardrails" type GuardrailScalar = string | number | boolean; ``` ### `GuardrailCondition` [#guardrailcondition] ```ts api="@rolebook/guardrails" type GuardrailCondition = { readonly field: GuardrailField; readonly operator: "isAnyOf" | "isNoneOf"; readonly values: readonly GuardrailScalar[]; } | { readonly field: GuardrailField; readonly operator: "matches" | "notMatches"; readonly values: readonly string[]; } | { readonly field: GuardrailField; readonly operator: "exists" | "notExists"; } | { readonly field: GuardrailField; readonly operator: "lessThan" | "greaterThan"; readonly values: readonly [ number ]; }; ``` ### `GuardrailEffect` [#guardraileffect] ```ts api="@rolebook/guardrails" type GuardrailEffect = { readonly type: "block"; readonly message?: string; } | { readonly type: "requireApproval"; readonly approvers: readonly ResourceRef[]; readonly requestTtlSeconds: number; readonly grantTtlSeconds: number; } | { readonly type: "notify"; readonly target: string; }; ``` ### `GuardrailException` [#guardrailexception] ```ts api="@rolebook/guardrails" interface GuardrailException { readonly id: string; readonly label?: string; readonly enabled: boolean; readonly when: readonly GuardrailCondition[]; readonly notify?: string; } ``` ### `GuardrailPolicy` [#guardrailpolicy] ```ts api="@rolebook/guardrails" interface GuardrailPolicy { readonly id: string; readonly name: string; readonly description?: string; readonly status: GuardrailStatus; readonly revision?: number; readonly when: readonly GuardrailCondition[]; readonly effect: GuardrailEffect; readonly except?: readonly GuardrailException[]; } ``` ### `GuardrailSet` [#guardrailset] ```ts api="@rolebook/guardrails" interface GuardrailSet { readonly format: "rolebook.guardrails/1"; readonly policies: readonly GuardrailPolicy[]; } ``` ### `GuardedOperation` [#guardedoperation] ```ts api="@rolebook/guardrails" interface GuardedOperation { readonly subject: ResourceRef; readonly permission: string; readonly field?: string; readonly resource: ResourceRef; readonly ancestors: readonly ResourceRef[]; } ``` ### `ApprovalGrant` [#approvalgrant] ```ts api="@rolebook/guardrails" interface ApprovalGrant extends GuardedOperation { readonly requestId: string; readonly policyId: string; readonly approvedBy: ResourceRef; readonly expiresAt: string; readonly readAt: string; } ``` ### `GuardrailInput` [#guardrailinput] ```ts api="@rolebook/guardrails" interface GuardrailInput { readonly decision: AuthorizationDecision; readonly subject: Subject; readonly principals?: readonly ResourceRef[]; readonly field?: string; readonly resource: TrustedResource; readonly context?: Readonly>; readonly grants?: readonly ApprovalGrant[]; readonly now?: Date; } ``` ### `GuardrailMatchEffect` [#guardrailmatcheffect] ```ts api="@rolebook/guardrails" type GuardrailMatchEffect = "block" | "requireApproval" | "notify" | "exception"; ``` ### `GuardrailMatch` [#guardrailmatch] ```ts api="@rolebook/guardrails" interface GuardrailMatch { readonly policyId: string; readonly revision?: number; readonly effect: GuardrailMatchEffect; readonly uncertain: boolean; readonly exceptionId?: string; readonly approvedBy?: { readonly requestId: string; readonly approver: ResourceRef; }; } ``` ### `PendingApproval` [#pendingapproval] ```ts api="@rolebook/guardrails" interface PendingApproval { readonly policyId: string; readonly revision?: number; readonly approvers: readonly ResourceRef[]; readonly requestTtlSeconds: number; readonly grantTtlSeconds: number; } ``` ### `GuardedDecisionCode` [#guardeddecisioncode] ```ts api="@rolebook/guardrails" type GuardedDecisionCode = Exclude | "ALLOWED" | "APPROVED" | "BLOCKED" | "APPROVAL_REQUIRED" | "GUARDRAIL_ERROR"; ``` ### `GuardedDecision` [#guardeddecision] ```ts api="@rolebook/guardrails" interface GuardedDecision { readonly allowed: boolean; readonly code: GuardedDecisionCode; readonly reason: string; readonly permission: string; readonly decision: AuthorizationDecision; readonly enforced: readonly GuardrailMatch[]; readonly monitored: readonly GuardrailMatch[]; readonly approvals?: readonly PendingApproval[]; readonly operation?: GuardedOperation; readonly notify: readonly string[]; readonly message?: string; } ``` # Hono middleware (/docs/hono) > Guard Hono routes with a binding and a trusted resource per request. The optional adapter at `rolebook/middleware/hono` resolves a bound authorization for each request and a concrete check for each route, and maps denials to HTTP responses. It contains no policy logic: every decision is an ordinary Rolebook check. It needs `hono` `>=4.12.34 <5`. Using Express or Fastify instead? Rolebook ships matching middleware with the same binding contract at [`rolebook/middleware/express`](/docs/api/express) (Express 5) and [`rolebook/middleware/fastify`](/docs/api/fastify) (Fastify 5). ```ts prelude=hono import { Hono } from "hono"; import { createRolebookMiddleware, type RolebookEnv } from "rolebook/middleware/hono"; const app = new Hono>(); const middleware = createRolebookMiddleware({ policy, getBinding: (context) => loadAuthorizationContext(context), }); app.onError(middleware.onError); app.get( "/projects/:id", middleware.requirePermission(async (context) => ({ permission: "project:read", resource: await loadTrustedProject(context.req.param("id")), })), (context) => context.json({ ok: true }), ); ``` Parameterize `RolebookEnv` with the policy type so `context.get("authorization")` keeps the policy's concrete permission union. ## What each piece does [#what-each-piece-does] - **`getBinding(context)`** returns the [binding](/docs/subjects-and-assignments) for the request: the authenticated subject, its assignments, and optional principals and context. It may be async. Returning `undefined` means the request is unauthenticated: the middleware answers 401 and never remembers that result. - **`requirePermission(request)`** takes a check request, or a function of the Hono context that returns one (sync or async). The middleware binds, stores the bound authorizer on the context as `authorization`, resolves the request, and checks it. A denial answers 403; an allow calls the next handler. - **`app.onError(middleware.onError)`** maps errors thrown downstream. It answers 403 for an `AuthorizationError` (from `enforce()` in a handler), preserves the response of a Hono `HTTPException`, and reports any other error before answering a plain-text 500. Without it, Hono answers an `AuthorizationError` with its default 500. Inside a handler, use the stored authorization for further checks on the same binding: ```ts prelude=hono import { Hono } from "hono"; import { createRolebookMiddleware, type RolebookEnv } from "rolebook/middleware/hono"; const app = new Hono>(); const middleware = createRolebookMiddleware({ policy, getBinding: loadAuthorizationContext }); app.onError(middleware.onError); app.delete( "/projects/:id", middleware.requirePermission(async (context) => ({ permission: "project:update", resource: await loadTrustedProject(context.req.param("id")), })), async (context) => { const project = await loadTrustedProject(context.req.param("id")); // Throws AuthorizationError on denial; onError turns it into a 403. context.get("authorization").enforce({ permission: "project:delete", resource: project }); return context.body(null, 204); }, ); ``` ## Options [#options] | Option | Default | Purpose | | --- | --- | --- | | `policy` | required | The policy. The middleware creates one authorizer for it. | | `getBinding` | required | Loads the request's binding, or `undefined` for 401. | | `onUnauthorized(context)` | `context.json({ error: "Unauthorized" }, 401)` | The response when `getBinding` returns `undefined`. | | `onForbidden(context)` | `context.json({ error: "Forbidden" }, 403)` | The response for a denied check and for a downstream `AuthorizationError`. | | `onInternalError(error, context)` | `console.error(error)` | Reports an unexpected downstream error before the generic 500. Supply a logger, or a no-op to silence it. | | `onEvaluationFault` | none | Reports evaluator faults; passed to `createAuthorizer` as [`onInternalError`](/docs/decisions#faults-fail-closed-and-can-be-reported). | | `reuseBindingPerRequest` | `false` | Bind once per request and reuse it for later checks from this middleware instance. | `onInternalError` is diagnostics only. A reporter that throws or rejects is ignored, and the response is unchanged. If classifying the error or producing its response also fails (a throwing `onForbidden`, a hostile error object), both the original error and the secondary failure are reported and the answer is a plain-text 500. `onError` always returns a `Promise`; code that calls it directly rather than through `app.onError` must await it. ## Reusing the binding per request [#reusing-the-binding-per-request] By default every `requirePermission` calls `getBinding` and binds afresh, so a route that stacks several checks loads the binding once per check. With `reuseBindingPerRequest: true`, the first check on a request binds and later checks from the **same middleware instance** on the **same request** reuse that authorization. Overlapping checks share one pending `getBinding` call. The next request loads again, and a load that returned `undefined` or failed is forgotten, so a later check on the same request tries again. The reuse is private to the middleware instance and keyed by Hono's per-request `Context`. The middleware never reads a binding or authorization back from a context variable, so a value other code puts there cannot stand in for one. With reuse on, a later check keeps the first binding even when its own answer would differ. An app-level check on `/api/*` cannot see a route parameter such as `:tenant` that a route-level check can, and middleware between two checks may swap or step down the identity. Turn it on only when `getBinding` depends solely on data that cannot change within a request, such as the authenticated session. See the [API reference](/docs/api/hono) for the exact types. The [HTTP authorization recipe](/docs/recipes/http-authorization) puts the same middleware on two document routes and uses `onForbidden` so a denial is indistinguishable from a missing document. # @rolebook/client (/docs/http-api/client) > A typed fetch client for the sharing HTTP API. `@rolebook/client` calls a server mounted with [`@rolebook/server`](/docs/http-api/server). Its methods mirror `TenantSharing`, typed by your resource catalog when you pass it, and return the [wire shapes](/docs/http-api#the-wire-contract). ```ts import { createIdempotencyKey, createSharingClient, SharingHttpError } from "@rolebook/client"; const sharing = createSharingClient({ baseUrl: "/api/sharing", credentials: "include", headers: async () => ({ "x-request-id": crypto.randomUUID() }), }); try { const page = await sharing.listAccessible({ type: "project", action: "read", limit: 50 }); const history = await sharing.auditHistory({ resource: { type: "project", id: "project_1" }, limit: 20 }); if (history.ok) history.page.events[0]?.occurredAt.getTime(); // revived to a Date await sharing.execute({ kind: "revokeMember", resource: { type: "project", id: "project_1" }, subject: { type: "user", id: "user_789" }, idempotencyKey: createIdempotencyKey(), }); } catch (error) { if (error instanceof SharingHttpError) console.error(error.status, error.code); else throw error; } ``` - `baseUrl` is a path or an absolute URL; one trailing slash is removed. `fetch` defaults to the platform `fetch`, and `credentials` to `"same-origin"`. `headers` may be a function, called per request. - Results are the wire shapes: `authorize` has no `decision`, `permissions` decisions are `{ allowed }`, listed resources have no `snapshot`. `describeAccess` and `auditHistory` revive their timestamps to `Date`. - Four failures throw the client's own typed classes: `InvalidCursorError`, `AccessibleListingError`, and `AuditHistoryError` for cursor, listing, and audit requests the server refuses with 400, and `AccessListingUnavailableError` when `listAccessible` gets a 503 because the server could not read a consistent page. Every other HTTP error throws `SharingHttpError` (code `UNEXPECTED_RESPONSE` for a body that is not a wire error). None of these is `instanceof` a class from `@rolebook/sharing`: check `name` or `code`. - An unavailable listing returned no page; it is not an empty result. See [handling an unavailable listing](#handling-an-unavailable-listing). - Call `createIdempotencyKey()` once per user intent and send that key again when retrying the intent. A replay answers `ALREADY_APPLIED` without an invitation token. ## Handling an unavailable listing [#handling-an-unavailable-listing] ```ts import { AccessListingUnavailableError, createSharingClient } from "@rolebook/client"; const sharing = createSharingClient({ baseUrl: "/api/sharing" }); try { const page = await sharing.listAccessible({ type: "project", action: "read", limit: 50 }); console.log(page.resources.length, page.exhausted); } catch (error) { if (!(error instanceof AccessListingUnavailableError)) throw error; // The server returned no page. Offer a retry; do not render an empty list. console.warn(`listing unavailable: ${error.reason}`); } ``` The error has `code: "ACCESS_LISTING_UNAVAILABLE"` and a `reason`, one of the eight values of [`WireAccessListingUnavailableReason`](/docs/http-api/http#wireaccesslistingunavailablereason). The reasons `expiry_crossed`, `session_expired`, `snapshot_unavailable`, and `changed` may succeed on a later call, although `snapshot_unavailable` can also mean corrupt stored data that needs repair; the others indicate the server's configuration or identity data and need attention there. See the [reason table](/docs/sharing/listing#when-no-consistent-page-can-be-read). `import { ... } from "@rolebook/client"`. Signatures are checked against the built declarations. ## Client [#client] ### `createSharingClient` [#createsharingclient] ```ts api="@rolebook/client" function createSharingClient< TResources extends SharingResourceConfigurations = SharingResourceConfigurations, >(options: SharingClientOptions): SharingClient; ``` Creates a client. Pass your resource catalog type for typed resource types, actions, and roles. ### `SharingClient` [#sharingclient] ```ts api="@rolebook/client" interface SharingClient { authorize>(input: { readonly resource: ResourceKey; readonly action: ActionFor; }): Promise; permissions>(input: { readonly resource: ResourceKey; }): Promise, TType>>; describeAccess>(input: { readonly resource: ResourceKey; }): Promise, TType>>; listAccessible>(input: { readonly type: TType; readonly action: ActionFor; readonly limit: number; readonly cursor?: string; }): Promise>; auditHistory>(input: { readonly resource: ResourceKey; readonly limit: number; readonly cursor?: string; }): Promise>; execute>( command: SharingCommand, ): Promise; explain>(input: { readonly resource: ResourceKey; readonly action: ActionFor; readonly subject?: WireRef; readonly field?: string; }): Promise; } ``` The operations over HTTP. `explain` is described under [Inspection](#inspection). `execute` sends a command with `expectedSharingRevision` as `sharing.executeIfUnchanged`: it applies only while the resource's sharing revision is still that value, and resolves to `{ ok: false, code: "SHARING_REVISION_CHANGED" }` otherwise. A server that predates the operation, or a newer server whose sharing runtime does not declare [`conditionalExecution`](/docs/sharing/api#tenantsharing), rejects with `SharingHttpError` 404 `UNKNOWN_OPERATION` and applies nothing; the client never falls back to an unconditional `sharing.execute`. A key set to `undefined` still counts: the server refuses it with `SharingHttpError` 400. A command without the key is sent as before. ```ts import { createIdempotencyKey, createSharingClient } from "@rolebook/client"; const sharing = createSharingClient({ baseUrl: "/api/sharing" }); const described = await sharing.describeAccess({ resource: { type: "project", id: "p1" } }); if (described.ok) { const result = await sharing.execute({ kind: "revokeMember", resource: { type: "project", id: "p1" }, subject: { type: "user", id: "u2" }, idempotencyKey: createIdempotencyKey(), expectedSharingRevision: described.access.sharingRevision, }); if (!result.ok && result.code === "SHARING_REVISION_CHANGED") { // Someone changed access since it was read: read it again and ask the user. } } ``` ### `SharingClientOptions` [#sharingclientoptions] ```ts api="@rolebook/client" interface SharingClientOptions { readonly baseUrl: string; readonly fetch?: (input: string, init: RequestInit) => Promise; readonly headers?: SharingHeadersInit | (() => SharingHeadersInit | Promise); readonly credentials?: SharingCredentials; readonly timeoutMs?: number; readonly maxResponseBytes?: number; } ``` `timeoutMs` bounds each call, from sending the request to reading the whole response; it defaults to [`DEFAULT_TIMEOUT_MS`](#default_timeout_ms). `maxResponseBytes` caps how much of a response body is read; it defaults to [`DEFAULT_MAX_RESPONSE_BYTES`](#default_max_response_bytes). The client sends every request with `redirect: "error"` and never follows a redirect. ### `SharingCredentials` [#sharingcredentials] ```ts api="@rolebook/client" type SharingCredentials = "omit" | "same-origin" | "include"; ``` ### `SharingHeadersInit` [#sharingheadersinit] ```ts api="@rolebook/client" type SharingHeadersInit = | Headers | readonly (readonly [string, string])[] | Readonly>; ``` ### `createIdempotencyKey` [#createidempotencykey] ```ts api="@rolebook/client" function createIdempotencyKey(): string; ``` A new random idempotency key for one user intent. ### `DEFAULT_TIMEOUT_MS` [#default_timeout_ms] ```ts api="@rolebook/client" const DEFAULT_TIMEOUT_MS = 10000; ``` The default `timeoutMs`: 10 seconds, the default of the Python, Go and Rust SDKs. ### `DEFAULT_MAX_RESPONSE_BYTES` [#default_max_response_bytes] ```ts api="@rolebook/client" const DEFAULT_MAX_RESPONSE_BYTES = 4194304; ``` The default `maxResponseBytes`: 4 MiB, the default of the Python, Go and Rust SDKs. ## Inspection [#inspection] `explain` calls [`sharing.explain`](/docs/http-api/http#inspection), the privileged current-state inspection of [`TenantSharing.explain`](/docs/sharing/inspection), when the server enables it. `subject` defaults to the authenticated actor. ```ts import { createSharingClient } from "@rolebook/client"; const sharing = createSharingClient({ baseUrl: "/api/sharing" }); const result = await sharing.explain({ resource: { type: "project", id: "project_1" }, action: "read", subject: { type: "user", id: "user_789" }, }); if (result.ok) console.log(result.explanation.decision.code); else console.log(result.code); // INVALID_REQUEST, NOT_FOUND_OR_DENIED, RATE_LIMITED, INSPECTION_UNAVAILABLE ``` It resolves to [`HttpInspectionResult`](/docs/http-api/http#httpinspectionresult) only for a 200 that matches the `ExplainResult` schema, or for exactly the fixed body of a 400, 404, 429, or 503. Every other response rejects as usual: a 404 or 200 body that is not exactly the contract is `SharingHttpError` with `UNEXPECTED_RESPONSE`, and a 401, a 413 for a body over 8 KiB, a timeout, or a network failure keep their usual errors. A disabled server, a hidden resource, a denied inspector, and an unavailable target are all `NOT_FOUND_OR_DENIED`, and nothing in the response tells them apart. The result is never a permission; do not retry `INSPECTION_UNAVAILABLE` automatically. ## Errors [#errors] ### `SharingHttpError` [#sharinghttperror] ```ts api="@rolebook/client" class SharingHttpError extends Error { readonly status: number; readonly code: WireErrorCode | SharingClientErrorCode; readonly issues?: readonly WireIssue[]; constructor( status: number, code: WireErrorCode | SharingClientErrorCode, message: string, issues?: readonly WireIssue[], ); } ``` Any non-200 response other than the cursor, listing, and audit errors and the typed [`AccessListingUnavailableError`](#accesslistingunavailableerror): `status`, `code`, and `issues`. ### `SharingClientErrorCode` [#sharingclienterrorcode] ```ts api="@rolebook/client" type SharingClientErrorCode = "UNEXPECTED_RESPONSE" | "TIMEOUT"; ``` The codes the client produces itself. `UNEXPECTED_RESPONSE` means a response did not match the wire contract at any status, including an HTTP 200 body that is not the operation's result, a redirect, or a body over `maxResponseBytes`. `TIMEOUT` means the call did not finish within `timeoutMs`; its `status` is `0`. A timed-out mutation may still have been applied, so retry it with the same idempotency key. ### `InvalidCursorError` [#invalidcursorerror] ```ts api="@rolebook/client" class InvalidCursorError extends RangeError { readonly code: "INVALID_CURSOR"; constructor(message: string); } ``` The client's own class for a 400 `INVALID_CURSOR`. ### `AccessibleListingError` [#accessiblelistingerror] ```ts api="@rolebook/client" class AccessibleListingError extends RangeError { readonly code: AccessibleListingErrorCode; constructor(code: AccessibleListingErrorCode, message: string); } ``` The client's own class for a listing 400. ### `AccessListingUnavailableError` [#accesslistingunavailableerror] ```ts api="@rolebook/client" class AccessListingUnavailableError extends Error { readonly code: "ACCESS_LISTING_UNAVAILABLE"; readonly reason: WireAccessListingUnavailableReason; constructor(reason: WireAccessListingUnavailableReason, message: string); } ``` Thrown by `listAccessible` when the server answers HTTP 503 with a body that is exactly the listing refusal of [`WireError`](/docs/http-api/http#wireerror): the code `ACCESS_LISTING_UNAVAILABLE`, a message, and an allowlisted `reason`. Only that status on that operation produces this class; the same code on any other response is an ordinary `SharingHttpError`. The server returned no page, partial page, or weaker page. The class has `code` and `reason` and no `status`. It extends `Error`, not `RangeError`, and is the client's own class: it is not `instanceof` the `AccessListingUnavailableError` of `@rolebook/sharing`, and not a `SharingHttpError`. The body is validated against the closed error schema before any error is constructed. A body with a missing or unknown `reason`, a `reason` beside another code, `issues` beside this code, or any extra member does not match and throws `SharingHttpError` with `UNEXPECTED_RESPONSE`, like every other response that is not the wire contract. ### `HierarchyUnavailableError` [#hierarchyunavailableerror] ```ts api="@rolebook/client" class HierarchyUnavailableError extends Error { readonly code: "HIERARCHY_UNAVAILABLE"; readonly reason: WireHierarchyUnavailableReason; constructor(reason: WireHierarchyUnavailableReason, message: string); } ``` Thrown by any client operation when the server answers HTTP 503 with the closed `HIERARCHY_UNAVAILABLE` body of [`WireError`](/docs/http-api/http#wireerror): the tenant's hierarchy state could not be used and nothing was decided, listed or applied. `reason` is the server's allowlisted cause. Like `AccessListingUnavailableError`, it is the client's own class, not `instanceof` the `@rolebook/sharing` class and not a `SharingHttpError`; a body that does not match the closed schema throws `SharingHttpError` with `UNEXPECTED_RESPONSE`. ### `AuditHistoryError` [#audithistoryerror] ```ts api="@rolebook/client" class AuditHistoryError extends RangeError { readonly code: AuditHistoryErrorCode; constructor(code: AuditHistoryErrorCode, message: string); } ``` The client's own class for an audit 400. ## Revived results [#revived-results] ### `ClientAccessDescriptionResult` [#clientaccessdescriptionresult] ```ts api="@rolebook/client" type ClientAccessDescriptionResult = | { readonly ok: true; readonly code: "DESCRIBED"; readonly access: ClientAccessDescription; } | { readonly ok: false; readonly code: "NOT_FOUND_OR_DENIED"; }; ``` `describeAccess()` with timestamps revived to `Date`. ### `ClientAccessDescription` [#clientaccessdescription] ```ts api="@rolebook/client" interface ClientAccessDescription { readonly resource: ResourceKey; readonly sharingRevision: string; readonly owner: ClientOwnership; readonly members: readonly ClientAccessMember[]; readonly invitations?: readonly ClientPendingInvitation[]; } ``` ### `ClientAccessMember` [#clientaccessmember] ```ts api="@rolebook/client" type ClientAccessMember = Omit< WireAccessMember, "createdAt" | "expiresAt" > & { readonly createdAt: Date; readonly expiresAt?: Date; }; ``` ### `ClientOwnership` [#clientownership] ```ts api="@rolebook/client" type ClientOwnership = Omit & { readonly createdAt: Date; }; ``` ### `ClientPendingInvitation` [#clientpendinginvitation] ```ts api="@rolebook/client" type ClientPendingInvitation = Omit< WirePendingInvitation, "expiresAt" | "membershipExpiresAt" | "createdAt" > & { readonly expiresAt: Date; readonly membershipExpiresAt?: Date; readonly createdAt: Date; }; ``` ### `ClientAuditHistoryResult` [#clientaudithistoryresult] ```ts api="@rolebook/client" type ClientAuditHistoryResult = | { readonly ok: true; readonly code: "LISTED"; readonly page: ClientAuditHistoryPage; } | { readonly ok: false; readonly code: "NOT_FOUND_OR_DENIED"; }; ``` `auditHistory()` with timestamps revived to `Date`. ### `ClientAuditHistoryPage` [#clientaudithistorypage] ```ts api="@rolebook/client" interface ClientAuditHistoryPage { readonly resource: ResourceKey; readonly events: readonly ClientAuditEvent[]; readonly nextCursor?: string; readonly exhausted: boolean; } ``` ### `ClientAuditEvent` [#clientauditevent] ```ts api="@rolebook/client" type ClientAuditEvent = Omit & { readonly occurredAt: Date; }; ``` ## Wire types [#wire-types] Re-exported from `@rolebook/http`; their declarations are on the [`@rolebook/http` page](/docs/http-api/http#wire-types). ### `WireHierarchyUnavailableReason` [#wirehierarchyunavailablereason] See [`WireHierarchyUnavailableReason`](/docs/http-api/http#wirehierarchyunavailablereason). ### `WireSharingDecision` [#wiresharingdecision] See [`WireSharingDecision`](/docs/http-api/http#wiresharingdecision). ### `WireResourcePermissionsResult` [#wireresourcepermissionsresult] See [`WireResourcePermissionsResult`](/docs/http-api/http#wireresourcepermissionsresult). ### `WireResourcePermissions` [#wireresourcepermissions] See [`WireResourcePermissions`](/docs/http-api/http#wireresourcepermissions). ### `WireDecision` [#wiredecision] See [`WireDecision`](/docs/http-api/http#wiredecision). ### `WireAccessDescriptionResult` [#wireaccessdescriptionresult] See [`WireAccessDescriptionResult`](/docs/http-api/http#wireaccessdescriptionresult). ### `WireAccessDescription` [#wireaccessdescription] See [`WireAccessDescription`](/docs/http-api/http#wireaccessdescription). ### `WireAccessMember` [#wireaccessmember] See [`WireAccessMember`](/docs/http-api/http#wireaccessmember). ### `WireOwnership` [#wireownership] See [`WireOwnership`](/docs/http-api/http#wireownership). ### `WirePendingInvitation` [#wirependinginvitation] See [`WirePendingInvitation`](/docs/http-api/http#wirependinginvitation). ### `WireAccessiblePage` [#wireaccessiblepage] See [`WireAccessiblePage`](/docs/http-api/http#wireaccessiblepage). ### `WireAccessibleResource` [#wireaccessibleresource] See [`WireAccessibleResource`](/docs/http-api/http#wireaccessibleresource). ### `WireAuditHistoryResult` [#wireaudithistoryresult] See [`WireAuditHistoryResult`](/docs/http-api/http#wireaudithistoryresult). ### `WireAuditHistoryPage` [#wireaudithistorypage] See [`WireAuditHistoryPage`](/docs/http-api/http#wireaudithistorypage). ### `WireAuditEvent` [#wireauditevent] See [`WireAuditEvent`](/docs/http-api/http#wireauditevent). ### `WireMutationResult` [#wiremutationresult] See [`WireMutationResult`](/docs/http-api/http#wiremutationresult). ### `WireMutationFailureCode` [#wiremutationfailurecode] See [`WireMutationFailureCode`](/docs/http-api/http#wiremutationfailurecode). ### `WireRef` [#wireref] See [`WireRef`](/docs/http-api/http#wireref). ### `WireDateTime` [#wiredatetime] See [`WireDateTime`](/docs/http-api/http#wiredatetime). ### `WireError` [#wireerror] See [`WireError`](/docs/http-api/http#wireerror). ### `WireErrorCode` [#wireerrorcode] See [`WireErrorCode`](/docs/http-api/http#wireerrorcode). ### `WireIssue` [#wireissue] See [`WireIssue`](/docs/http-api/http#wireissue). ### `HttpInspectionResult` [#httpinspectionresult] See [`HttpInspectionResult`](/docs/http-api/http#httpinspectionresult). # @rolebook/http (/docs/http-api/http) > The wire contract of the sharing HTTP API: operations, codecs, schemas, and OpenAPI. `@rolebook/http` defines the [HTTP API](/docs/http-api)'s contract once, for the server and the client: the operation names, which body keys each copies, the request decoder, the result serializers, the client's encode and revive helpers, the JSON schemas, and an OpenAPI 3.1 document. You rarely import it directly; use [`@rolebook/server`](/docs/http-api/server) and [`@rolebook/client`](/docs/http-api/client). The OpenAPI document ships as `@rolebook/http/openapi.json` (title "Rolebook Sharing API", paths `/v1/sharing.authorize` through `/v1/sharing.explain`) and is also produced by `openApiDocument()`. `import { ... } from "@rolebook/http"`. Signatures are checked against the built declarations. ## Operations [#operations] ### `SHARING_OPERATIONS` [#sharing_operations] ```ts api="@rolebook/http" const SHARING_OPERATIONS: readonly [ "sharing.authorize", "sharing.permissions", "sharing.describeAccess", "sharing.listAccessible", "sharing.auditHistory", "sharing.execute", "sharing.explain", "sharing.executeIfUnchanged", ]; ``` The eight operation names, in order. `sharing.explain` is the privileged inspection; see [Inspection](#inspection). `sharing.executeIfUnchanged` was appended later, so every earlier operation keeps its position; see [Conditional commands](#conditional-commands). ### `SharingOperation` [#sharingoperation] ```ts api="@rolebook/http" type SharingOperation = (typeof SHARING_OPERATIONS)[number]; ``` ### `isSharingOperation` [#issharingoperation] ```ts api="@rolebook/http" function isSharingOperation(value: string): value is SharingOperation; ``` Whether a string names an operation. ### `SharingCommandOperation` [#sharingcommandoperation] ```ts api="@rolebook/http" type SharingCommandOperation = Extract< SharingOperation, "sharing.execute" | "sharing.executeIfUnchanged" >; ``` ### `isCommandOperation` [#iscommandoperation] ```ts api="@rolebook/http" function isCommandOperation(operation: SharingOperation): operation is SharingCommandOperation; ``` Whether an operation applies a command: `sharing.execute` or `sharing.executeIfUnchanged`. ### Conditional commands [#conditional-commands] `sharing.executeIfUnchanged` takes `{ command, expectedSharingRevision }`. The command applies only while the resource's sharing revision is still `expectedSharingRevision`, checked in the same commit as the write; otherwise the 200 result is `SHARING_REVISION_CHANGED` and nothing changes. A retry whose idempotency key already committed answers `ALREADY_APPLIED` even though its own write moved the revision. Authorization and tenancy are decided first and answer exactly as for the unconditional command, so a refused caller learns nothing about the revision. It is a separate operation, not a command field, because an older server ignores unknown command fields and would apply the command unconditionally. A server without the operation answers 404 `UNKNOWN_OPERATION` and applies nothing. A newer server refuses the same way when its sharing runtime cannot honour the precondition: `@rolebook/server` and the Better Auth plugin run the operation only on a tenant that declares [`conditionalExecution`](/docs/sharing/api#tenantsharing), and for any other tenant (a hand-built or wrapped tenant without the flag, or one from an older `@rolebook/sharing`) answer 404 `UNKNOWN_OPERATION`, with the same body as an unknown operation, without calling it. That check comes after authentication and the body checks below. A client cannot tell the two 404s apart, and needs not to: in both, nothing was applied. For the same reason, `sharing.execute` refuses `expectedSharingRevision` inside its command or beside it with 400 `INVALID_REQUEST`, and `sharing.executeIfUnchanged` refuses a body without one, or with one inside the command. ### `OPERATION_KEYS` [#operation_keys] ```ts api="@rolebook/http" const OPERATION_KEYS: Readonly>; ``` The body keys copied for each operation; others are dropped. For `sharing.explain` the server refuses any other key with the fixed 400 instead of dropping it. ### `DEFAULT_MAX_BODY_BYTES` [#default_max_body_bytes] ```ts api="@rolebook/http" const DEFAULT_MAX_BODY_BYTES = 65536; ``` The default request body limit: 64 KiB. ## Server codecs [#server-codecs] ### `decodeRequestBody` [#decoderequestbody] ```ts api="@rolebook/http" function decodeRequestBody(operation: SharingOperation, body: unknown): DecodeResult; ``` Decodes a parsed JSON body for an operation: refuses a non-object with an issue, copies only the operation's keys, and for `sharing.execute` and `sharing.executeIfUnchanged` revives the command's dates. Frozen. ### `DecodeResult` [#decoderesult] ```ts api="@rolebook/http" type DecodeResult = | { readonly ok: true; readonly input: Readonly>; } | { readonly ok: false; readonly issues: readonly WireIssue[]; }; ``` ### `reviveCommandDates` [#revivecommanddates] ```ts api="@rolebook/http" function reviveCommandDates(command: unknown): unknown; ``` Revives `expiresAt` and `membershipExpiresAt` when they are RFC 3339 strings; every other value is kept as it arrived. ### `serializeResult` [#serializeresult] ```ts api="@rolebook/http" function serializeResult( operation: SharingOperation, result: unknown, input: Readonly>, ): unknown; ``` Serializes an in-process result to its wire shape for an operation. For `sharing.explain` it copies the result exactly as plain JSON data (strings, finite numbers, booleans, null, dense arrays, and plain objects of own enumerable data properties) and throws a `TypeError` for anything else; it never drops or renames a key, so the `ExplainResult` schema decides what may be sent. ## Client codecs [#client-codecs] ### `encodeRequestBody` [#encoderequestbody] ```ts api="@rolebook/http" function encodeRequestBody(operation: SharingOperation, input: unknown): string; ``` The JSON text of a request body: `{ command }` for `sharing.execute`; for `sharing.executeIfUnchanged` the input is the command with its `expectedSharingRevision`, sent as `{ command, expectedSharingRevision }`; the input itself otherwise, with dates as ISO strings. ### `toWireJson` [#towirejson] ```ts api="@rolebook/http" function toWireJson(value: unknown): unknown; ``` A deep copy for JSON: `Date` to `toISOString()` (an invalid date to `"Invalid Date"`), arrays and plain objects recursed. ### `reviveResult` [#reviveresult] ```ts api="@rolebook/http" function reviveResult(operation: SharingOperation, json: unknown): unknown; ``` Revives the timestamps of a wire result into `Date`s for the operations that carry them. Throws `TypeError` for an invalid date. ### `parseRfc3339` [#parserfc3339] ```ts api="@rolebook/http" function parseRfc3339(value: string): Date | undefined; ``` A `Date` when the string is RFC 3339 (`Z` or an offset, up to millisecond precision) and parses, otherwise `undefined`. ## Schemas and OpenAPI [#schemas-and-openapi] ### `openApiDocument` [#openapidocument] ```ts api="@rolebook/http" function openApiDocument(): Record; ``` Builds the OpenAPI 3.1 document: one path per operation, with the 200 result and every error response. Every path except `sharing.explain` documents the 503 `HIERARCHY_UNAVAILABLE` response, with its allowlisted `reason`; the `sharing.listAccessible` path also documents its 503 `ACCESS_LISTING_UNAVAILABLE` response. `sharing.explain` keeps its own [inspection](#inspection) responses. ### `SCHEMAS` [#schemas] ```ts api="@rolebook/http" summary const SCHEMAS: { readonly [name: string]: object }; ``` The JSON schemas the OpenAPI document references, as one constant object whose literal type is too large to print here. Its keys: `Ref`, `DateTime`, `IdempotencyKey`, `InvitationRecipient`, one schema per command (`GrantRoleCommand` through `RevokeInvitationCommand`) and `Command`, the request schemas (`AuthorizeRequest`, `ResourceRequest`, `ListAccessibleRequest`, `AuditHistoryRequest`, `ExecuteRequest`), and the result schemas (`Denied`, `AuthorizeResult`, `PermissionsResult`, `Ownership`, `AccessMember`, `PendingInvitation`, `DescribeAccessResult`, `ListAccessibleResult`, `AuditEvent`, `AuditHistoryResult`, `ExecuteResult`, `Error`), and the [inspection](#inspection) schemas (`ExplainRequest`, `ExplainResult`, `InspectionEnvelope`, `InspectionDecision`, `InspectionTraceEntry`, `InspectionRuleCondition`, `InspectionConditionResult`, `InspectionConditionNode`, and the fixed failure bodies `ExplainInvalidRequest`, `ExplainNotFoundOrDenied`, `ExplainRateLimited`, `ExplainUnavailable`). ### `SharingSchemaName` [#sharingschemaname] ```ts api="@rolebook/http" type SharingSchemaName = keyof typeof SCHEMAS; ``` The name of one schema in [`SCHEMAS`](#schemas). ### `REQUEST_SCHEMA_NAMES` [#request_schema_names] ```ts api="@rolebook/http" const REQUEST_SCHEMA_NAMES: Readonly<{ readonly "sharing.authorize": "AuthorizeRequest"; readonly "sharing.permissions": "ResourceRequest"; readonly "sharing.describeAccess": "ResourceRequest"; readonly "sharing.listAccessible": "ListAccessibleRequest"; readonly "sharing.auditHistory": "AuditHistoryRequest"; readonly "sharing.execute": "ExecuteRequest"; readonly "sharing.executeIfUnchanged": "ExecuteIfUnchangedRequest"; readonly "sharing.explain": "ExplainRequest"; }>; ``` The request schema of each operation, as named in the OpenAPI document. ### `RESULT_SCHEMA_NAMES` [#result_schema_names] ```ts api="@rolebook/http" const RESULT_SCHEMA_NAMES: Readonly<{ readonly "sharing.authorize": "AuthorizeResult"; readonly "sharing.permissions": "PermissionsResult"; readonly "sharing.describeAccess": "DescribeAccessResult"; readonly "sharing.listAccessible": "ListAccessibleResult"; readonly "sharing.auditHistory": "AuditHistoryResult"; readonly "sharing.execute": "ExecuteResult"; readonly "sharing.executeIfUnchanged": "ExecuteResult"; readonly "sharing.explain": "ExplainResult"; }>; ``` The HTTP 200 result schema of each operation, as named in the OpenAPI document. ### `matchesSchema` [#matchesschema] ```ts api="@rolebook/http" function matchesSchema(name: SharingSchemaName, value: unknown): boolean; ``` True when `value`, already parsed from JSON, matches the named schema of the wire contract. It is strict in the same way as the Python, Go and Rust SDKs: a wrong type, a missing required field, a value out of range, an impossible date, an unpaired surrogate, or a key the schema does not declare all fail. String lengths are counted in UTF-16 code units, as on the server. ### `isValidResult` [#isvalidresult] ```ts api="@rolebook/http" function isValidResult(operation: SharingOperation, value: unknown): boolean; ``` True when `value` is a valid HTTP 200 result for `operation`. `@rolebook/client` calls this before it returns any result. ### `parseStrictJson` [#parsestrictjson] ```ts api="@rolebook/http" function parseStrictJson(text: string): | { readonly ok: true; readonly value: unknown } | { readonly ok: false }; ``` Parses a response body as JSON with the native SDKs' rules: valid JSON, no duplicate object keys, and nesting of at most 64 levels. Returns `{ ok: false }` and does not throw. ## Inspection [#inspection] `POST {basePath}/v1/sharing.explain` carries [`TenantSharing.explain`](/docs/sharing/inspection), the privileged current-state inspection. It is off unless the server's sharing instance has an `inspection` configuration. The body is exactly the library input, `{ resource, action, subject?, field? }`; tenant and actor come only from the server session. The ordinary checks come first and are unchanged (401, 403, 405, 415). The body may be at most 8 KiB: a longer one is the ordinary 413 `PAYLOAD_TOO_LARGE`, and one that is not UTF-8 or JSON is the ordinary 400. Every other outcome is a fixed response: | Status | Body | | --- | --- | | 200 | `{ "ok": true, "code": "EXPLAINED", "explanation": { ... } }`, the library's success exactly | | 400 | `{ "error": { "code": "INVALID_REQUEST", "message": "Invalid request" } }` | | 404 | `{ "error": { "code": "NOT_FOUND_OR_DENIED", "message": "Not found or denied" } }` | | 429 | `{ "error": { "code": "RATE_LIMITED", "message": "Rate limited" } }` | | 503 | `{ "error": { "code": "INSPECTION_UNAVAILABLE", "message": "Inspection unavailable" } }` | The 400 covers an unknown body key (such as `tenantId`, `actor`, or `context`), a body that is not an object, and the library's `INVALID_REQUEST`. A disabled server, a missing or hidden resource, a denied inspector, and an unavailable target are one byte-identical 404, headers included. Every response of the operation has `Cache-Control: no-store` and a JSON content type. ### `HttpInspectionResult` [#httpinspectionresult] ```ts api="@rolebook/http" type HttpInspectionResult = | { readonly ok: true; readonly code: "EXPLAINED"; readonly explanation: InspectionEnvelope; } | { readonly ok: false; readonly code: "INVALID_REQUEST" | "NOT_FOUND_OR_DENIED" | "RATE_LIMITED" | "INSPECTION_UNAVAILABLE"; }; ``` What `sharing.explain` answers over HTTP, narrowed from the library's [`InspectionResult`](/docs/sharing/api#inspectionresult): the explanation, or `{ ok: false, code }` for one of the four fixed failures. The library's `INSPECTION_DISABLED` and `TARGET_UNAVAILABLE` never cross the wire. [`@rolebook/client`](/docs/http-api/client#inspection) and the Python SDK's `explain` return it. ## Wire types [#wire-types] ### `WireSharingDecision` [#wiresharingdecision] ```ts api="@rolebook/http" type WireSharingDecision = | { readonly allowed: true; readonly code: "ALLOWED"; } | { readonly allowed: false; readonly code: "NOT_FOUND_OR_DENIED" | "FORBIDDEN"; }; ``` `sharing.authorize`'s result: `{ allowed, code }`, without the Rolebook decision. ### `WireResourcePermissionsResult` [#wireresourcepermissionsresult] ```ts api="@rolebook/http" type WireResourcePermissionsResult = | { readonly ok: true; readonly code: "EVALUATED"; readonly permissions: WireResourcePermissions; } | { readonly ok: false; readonly code: "NOT_FOUND_OR_DENIED"; }; ``` `sharing.permissions`' result. ### `WireResourcePermissions` [#wireresourcepermissions] ```ts api="@rolebook/http" interface WireResourcePermissions { readonly resource: ResourceKey; readonly sharingRevision: string; readonly allowed: Readonly>; readonly decisions: Readonly>; } ``` Every action decided: `allowed` booleans and `decisions` reduced to `{ allowed }`. ### `WireDecision` [#wiredecision] ```ts api="@rolebook/http" interface WireDecision { readonly allowed: boolean; } ``` A decision reduced to `{ allowed }`. ### `WireAccessDescriptionResult` [#wireaccessdescriptionresult] ```ts api="@rolebook/http" type WireAccessDescriptionResult = | { readonly ok: true; readonly code: "DESCRIBED"; readonly access: WireAccessDescription; } | { readonly ok: false; readonly code: "NOT_FOUND_OR_DENIED"; }; ``` `sharing.describeAccess`' result. ### `WireAccessDescription` [#wireaccessdescription] ```ts api="@rolebook/http" interface WireAccessDescription { readonly resource: ResourceKey; readonly sharingRevision: string; readonly owner: WireOwnership; readonly members: readonly WireAccessMember[]; readonly invitations?: readonly WirePendingInvitation[]; } ``` ### `WireAccessMember` [#wireaccessmember] ```ts api="@rolebook/http" interface WireAccessMember { readonly subject: WireRef; readonly role: TRole; readonly createdAt: WireDateTime; readonly createdBy: WireRef; readonly expiresAt?: WireDateTime; } ``` ### `WireOwnership` [#wireownership] ```ts api="@rolebook/http" interface WireOwnership { readonly subject: WireRef; readonly createdAt: WireDateTime; readonly createdBy: WireRef; } ``` ### `WirePendingInvitation` [#wirependinginvitation] ```ts api="@rolebook/http" interface WirePendingInvitation { readonly id: string; readonly recipient: InvitationRecipient; readonly role: TRole; readonly expiresAt: WireDateTime; readonly membershipExpiresAt?: WireDateTime; readonly createdAt: WireDateTime; readonly createdBy: WireRef; } ``` ### `WireAccessiblePage` [#wireaccessiblepage] ```ts api="@rolebook/http" interface WireAccessiblePage { readonly resources: readonly WireAccessibleResource[]; readonly nextCursor?: string; readonly exhausted: boolean; } ``` `sharing.listAccessible`'s result. ### `WireAccessibleResource` [#wireaccessibleresource] ```ts api="@rolebook/http" interface WireAccessibleResource { readonly resource: ResourceKey; } ``` A listed resource: `{ resource }` only, no snapshot. ### `WireAuditHistoryResult` [#wireaudithistoryresult] ```ts api="@rolebook/http" type WireAuditHistoryResult = | { readonly ok: true; readonly code: "LISTED"; readonly page: WireAuditHistoryPage; } | { readonly ok: false; readonly code: "NOT_FOUND_OR_DENIED"; }; ``` `sharing.auditHistory`'s result. ### `WireAuditHistoryPage` [#wireaudithistorypage] ```ts api="@rolebook/http" interface WireAuditHistoryPage { readonly resource: ResourceKey; readonly events: readonly WireAuditEvent[]; readonly nextCursor?: string; readonly exhausted: boolean; } ``` ### `WireAuditEvent` [#wireauditevent] ```ts api="@rolebook/http" interface WireAuditEvent { readonly id: string; readonly tenantId: string; readonly resourceType: string; readonly resourceId: string; readonly actor: WireRef; readonly action: SharingAuditEvent["action"]; readonly subject?: WireRef; readonly invitationId?: string; readonly fromTenantId?: string; readonly toTenantId?: string; readonly occurredAt: WireDateTime; } ``` An audit event with its timestamp as an RFC 3339 string. ### `WireMutationResult` [#wiremutationresult] ```ts api="@rolebook/http" type WireMutationResult = | { readonly ok: true; readonly code: "APPLIED"; readonly sharingRevision: string; readonly invitation?: { readonly id: string; readonly token: string; }; } | { readonly ok: true; readonly code: "ALREADY_APPLIED"; readonly sharingRevision: string; } | { readonly ok: false; readonly code: WireMutationFailureCode; }; ``` The result of `sharing.execute` and `sharing.executeIfUnchanged`. The invitation token appears only on `APPLIED`. ### `WireMutationFailureCode` [#wiremutationfailurecode] ```ts api="@rolebook/http" type WireMutationFailureCode = Extract< SharingMutationResult, { readonly ok: false; } >["code"]; ``` The failure codes of `SharingMutationResult`, each an HTTP 200 result. That includes a versioned instance's `POLICY_GENERATION_CHANGED`, `TENANT_ROLES_CHANGED` and `POLICY_UNAVAILABLE`, and `SHARING_REVISION_CHANGED`, which only `sharing.executeIfUnchanged` answers. ### `WIRE_MUTATION_FAILURE_CODES` [#wire_mutation_failure_codes] ```ts api="@rolebook/http" const WIRE_MUTATION_FAILURE_CODES: readonly WireMutationFailureCode[]; ``` Every `WireMutationFailureCode`, in the order of the `ExecuteResult` schema, which is built from it. The list is checked against the library's type at compile time in both directions, so a code added to `@rolebook/sharing` cannot be missing from the wire contract. ### `WireRef` [#wireref] ```ts api="@rolebook/http" interface WireRef { readonly type: string; readonly id: string; } ``` A `{ type, id }` reference. ### `WireDateTime` [#wiredatetime] ```ts api="@rolebook/http" type WireDateTime = string; ``` An RFC 3339 string from `toISOString()`. ### `WireError` [#wireerror] ```ts api="@rolebook/http" interface WireError { readonly error: { readonly code: Exclude; readonly message: string; readonly issues?: readonly WireIssue[]; } | { readonly code: "ACCESS_LISTING_UNAVAILABLE"; readonly message: string; readonly reason: WireAccessListingUnavailableReason; } | { readonly code: "HIERARCHY_UNAVAILABLE"; readonly message: string; readonly reason: WireHierarchyUnavailableReason; }; } ``` The body of every non-200 response, apart from the fixed bodies of [`sharing.explain`](#inspection). It has exactly one of three shapes, and the `Error` schema in [`SCHEMAS`](#schemas) and in the OpenAPI document is closed on all three: - An ordinary error: any code except `ACCESS_LISTING_UNAVAILABLE` and `HIERARCHY_UNAVAILABLE`, a `message`, and optional `issues`. It never has a `reason`. - A listing refusal: `ACCESS_LISTING_UNAVAILABLE`, a `message`, and a required `reason`. It never has `issues`. - A hierarchy refusal: `HIERARCHY_UNAVAILABLE`, a `message`, and a required `reason` from [`WIRE_HIERARCHY_UNAVAILABLE_REASONS`](#wire_hierarchy_unavailable_reasons). It never has `issues`. Every sharing operation except `sharing.explain` may answer it with HTTP 503, when the tenant's hierarchy state cannot be used; nothing was decided, listed or applied. The server sends the listing refusal only for `sharing.listAccessible`, with HTTP 503, when no [consistent page](/docs/sharing/listing#when-no-consistent-page-can-be-read) could be read: ```json { "error": { "code": "ACCESS_LISTING_UNAVAILABLE", "message": "Access listing unavailable", "reason": "session_expired" } } ``` It means the server returned no page and no partial page. It is not an empty result: an empty page is an HTTP 200 answer, and one that is not `exhausted` continues with `nextCursor`; see [listing](/docs/sharing/listing#pages-can-be-empty-and-not-exhausted). The OpenAPI document lists this 503 response on the `sharing.listAccessible` path only (beside the hierarchy 503 every non-explain path documents). `listAccess()` has no HTTP operation. ### `WireAccessListingUnavailableReason` [#wireaccesslistingunavailablereason] ```ts api="@rolebook/http" type WireAccessListingUnavailableReason = | "capability_missing" | "identity_evidence_missing" | "policy_evidence_missing" | "unrepresentable_identity" | "expiry_crossed" | "session_expired" | "snapshot_unavailable" | "changed"; ``` Why a listing was refused: exactly the reasons of `AccessListingUnavailableError` in `@rolebook/sharing`. A reason names a cause only, never a tenant, subject, resource, or value. `capability_missing`, `identity_evidence_missing`, `policy_evidence_missing`, and `unrepresentable_identity` point at the server's configuration or its identity data and need attention there; `expiry_crossed`, `session_expired`, `snapshot_unavailable`, and `changed` may succeed on a later request, although `snapshot_unavailable` can also mean corrupt stored data that needs repair. See the [reason table](/docs/sharing/listing#when-no-consistent-page-can-be-read). ### `WIRE_ACCESS_LISTING_UNAVAILABLE_REASONS` [#wire_access_listing_unavailable_reasons] ```ts api="@rolebook/http" const WIRE_ACCESS_LISTING_UNAVAILABLE_REASONS: readonly WireAccessListingUnavailableReason[]; ``` Every `WireAccessListingUnavailableReason`. The server sends a reason only when it is in this list. ### `WireHierarchyUnavailableReason` [#wirehierarchyunavailablereason] ```ts api="@rolebook/http" type WireHierarchyUnavailableReason = HierarchyUnavailableReason; ``` The `reason` of a `HIERARCHY_UNAVAILABLE` error: the tenant-level cause of `HierarchyUnavailableError` in `@rolebook/sharing`. ### `WIRE_HIERARCHY_UNAVAILABLE_REASONS` [#wire_hierarchy_unavailable_reasons] ```ts api="@rolebook/http" const WIRE_HIERARCHY_UNAVAILABLE_REASONS: readonly WireHierarchyUnavailableReason[]; ``` Every `WireHierarchyUnavailableReason` the server may send. Any sharing operation except `sharing.explain` (including `execute`) that hits a tenant-level `HierarchyUnavailableError` answers HTTP 503 `HIERARCHY_UNAVAILABLE` with a fixed message and a reason from this list; a reason outside it is a reported 500. An ordinary domain rejection, including an adapter-returned `HIERARCHY_UNAVAILABLE` result, stays a 200 result. ### `WireErrorCode` [#wireerrorcode] ```ts api="@rolebook/http" type WireErrorCode = "INVALID_REQUEST" | "INVALID_CURSOR" | "INVALID_LIMIT" | "UNKNOWN_RESOURCE_TYPE" | "UNKNOWN_ACTION" | "TOO_MANY_ASSIGNMENTS" | "UNAUTHENTICATED" | "CSRF" | "UNKNOWN_OPERATION" | "METHOD_NOT_ALLOWED" | "PAYLOAD_TOO_LARGE" | "UNSUPPORTED_MEDIA_TYPE" | "ACCESS_LISTING_UNAVAILABLE" | "HIERARCHY_UNAVAILABLE" | "INTERNAL"; ``` `ACCESS_LISTING_UNAVAILABLE` and `HIERARCHY_UNAVAILABLE` are the only codes that carry a `reason`, and each always carries one; see [`WireError`](#wireerror). ### `WireIssue` [#wireissue] ```ts api="@rolebook/http" interface WireIssue { readonly path: string; readonly message: string; } ``` ### `WIRE_ERROR_CODES` [#wire_error_codes] ```ts api="@rolebook/http" const WIRE_ERROR_CODES: readonly WireErrorCode[]; ``` Every `WireErrorCode`. # HTTP API (/docs/http-api) > Serve the sharing operations over HTTP with @rolebook/server, and call them from a browser with @rolebook/client. Three packages expose a [sharing](/docs/sharing) instance over HTTP: | Package | Role | | --- | --- | | [`@rolebook/http`](/docs/http-api/http) | The wire contract: operation names, JSON shapes, request decoding, result serialization, client codecs, and an OpenAPI 3.1 document. | | [`@rolebook/server`](/docs/http-api/server) | A web-standard `(request: Request) => Promise` handler, with Hono and Next.js adapters. | | [`@rolebook/client`](/docs/http-api/client) | A typed `fetch` client for browsers and other services. | This API serves the Sharing module: a signed-in actor asks about, lists, and changes access to shared resources in its own tenant. For a plain check on any subject, action, and resource of a Core policy, asked by another service with its own credential, mount the [decision service](/docs/decision-service) instead. The two are independent handlers with separate routes, media types, and authentication, and you can run both. [Choose how decisions run](/docs/choosing) compares them. ## Serve it [#serve-it] ```ts title="server.ts" group=http import { createSharingHandler } from "@rolebook/server"; import type { ResourceSharing, SharingResourceConfigurations, TenantContext } from "@rolebook/sharing"; declare const sharing: ResourceSharing; declare function sessionFor(request: Request): Promise<{ workspaceId: string; userId: string } | undefined>; export const sharingHandler = createSharingHandler({ basePath: "/api/sharing", sharing, async getContext(request): Promise { const session = await sessionFor(request); if (!session) return undefined; // 401 return { tenantId: session.workspaceId, actor: { type: "user", id: session.userId } }; }, }); ``` `getContext` derives the tenant and the actor from the trusted session. Never read them from the request body or from headers the browser controls, and do not read the body yourself: the handler reads it after `getContext` returns. ## Call it [#call-it] ```ts title="client.ts" group=http import { createIdempotencyKey, createSharingClient } from "@rolebook/client"; const client = createSharingClient({ baseUrl: "/api/sharing", credentials: "same-origin" }); const decision = await client.authorize({ resource: { type: "project", id: "project_1" }, action: "update" }); if (decision.allowed) { await client.execute({ kind: "grantRole", resource: { type: "project", id: "project_1" }, subject: { type: "user", id: "user_789" }, role: "editor", idempotencyKey: createIdempotencyKey(), }); } ``` ## The wire contract [#the-wire-contract] Every operation is `POST {basePath}/v1/{operation}` with a JSON object body. Tenant and actor are never in the body. Dates are RFC 3339 strings from `Date.prototype.toISOString()`. | Operation | Body keys copied | Result | | --- | --- | --- | | `sharing.authorize` | `resource`, `action` | `{ allowed, code }` | | `sharing.permissions` | `resource` | permissions, or `{ ok: false, code }` | | `sharing.describeAccess` | `resource` | access description, or `{ ok: false, code }` | | `sharing.listAccessible` | `type`, `action`, `limit`, `cursor` | `{ resources, nextCursor?, exhausted }` | | `sharing.auditHistory` | `resource`, `limit`, `cursor` | audit page, or `{ ok: false, code }` | | `sharing.execute` | `command` | mutation result | | `sharing.explain` | `resource`, `action`, `subject`, `field` | `{ ok: true, code: "EXPLAINED", explanation }` | | `sharing.executeIfUnchanged` | `command`, `expectedSharingRevision` | mutation result | Other body keys are dropped, except by `sharing.explain`, which refuses them (see [Inspection](/docs/http-api/http#inspection)). `sharing.execute` and `sharing.executeIfUnchanged` revive RFC 3339 `expiresAt` and `membershipExpiresAt` values back into `Date`s and forward every other command value unchanged. `sharing.executeIfUnchanged` applies the command only while the resource's sharing revision is still `expectedSharingRevision`, checked in the same commit, and answers `SHARING_REVISION_CHANGED` otherwise. A server without it, and a newer server whose sharing runtime does not declare `conditionalExecution`, answer 404 and apply nothing (see [Conditional commands](/docs/http-api/http#conditional-commands)). The OpenAPI schemas describe valid input, but the server does not enforce them: it forwards values to the sharing module, which answers most malformed values with a domain code. Results are deliberately smaller than in-process ones: `authorize` returns `{ allowed, code }` without the Rolebook decision, `permissions` decisions are `{ allowed }` only, listed resources are `{ resource }` without a snapshot, and a mutation result carries no `policyVersion`. An `issueInvitation` result carries the invitation token only on `APPLIED`. ## Status codes [#status-codes] A domain outcome, allowed or not, is HTTP 200: the status never reveals whether a resource exists. Every other response body is `{ "error": { "code", "message", "issues"? } }`, with one variant: a listing refusal is `{ "error": { "code", "message", "reason" } }`, with a required `reason` and no `issues`. No other error carries a `reason`. `sharing.explain`, the privileged inspection, has a separate contract: it answers its failures with fixed bodies at 400, 404, 429, and 503, listed under [Inspection](/docs/http-api/http#inspection). | Status | Code | When | | --- | --- | --- | | 400 | `INVALID_REQUEST` | The body is not UTF-8, not JSON, or not a JSON object; or a command's `expectedSharingRevision` is misplaced (on `sharing.execute`, or inside the command) or missing (on `sharing.executeIfUnchanged`). | | 400 | `INVALID_CURSOR` | A listing or audit cursor does not open. | | 400 | `INVALID_LIMIT`, `UNKNOWN_RESOURCE_TYPE`, `UNKNOWN_ACTION`, `TOO_MANY_ASSIGNMENTS` | A listing request cannot be answered. | | 400 | `INVALID_LIMIT`, `UNKNOWN_RESOURCE_TYPE` | An audit request cannot be answered. | | 401 | `UNAUTHENTICATED` | `getContext` returned `undefined`. | | 403 | `CSRF` | The origin check failed. | | 404 | `UNKNOWN_OPERATION` | The path is not a known operation, or it is `sharing.executeIfUnchanged` and the sharing runtime does not declare `conditionalExecution` (checked after authentication and the body; nothing is called). | | 405 | `METHOD_NOT_ALLOWED` | The method is not `POST`. (A CORS preflight `OPTIONS` from a configured origin is answered instead.) | | 413 | `PAYLOAD_TOO_LARGE` | The body is longer than `maxBodyBytes`. | | 415 | `UNSUPPORTED_MEDIA_TYPE` | The content type is not JSON. | | 503 | `ACCESS_LISTING_UNAVAILABLE` | `sharing.listAccessible` only: no consistent page could be read. The body carries a `reason`. | | 500 | `INTERNAL` | Any other failure; reported to `onInternalError`. | The messages of `InvalidCursorError`, `AccessibleListingError`, and `AuditHistoryError` are forwarded verbatim, so keep the messages of any adapter subclasses free of tenant data. ### When a listing cannot be read [#when-a-listing-cannot-be-read] `sharing.listAccessible` reads each page at [one coherent point](/docs/sharing/listing#what-one-page-guarantees). When the server cannot establish one, it answers HTTP 503 with a fixed message and one of eight reasons: ```json { "error": { "code": "ACCESS_LISTING_UNAVAILABLE", "message": "Access listing unavailable", "reason": "session_expired" } } ``` This is an expected outcome, not a server fault, and it is not reported to `onInternalError`. The server returned no page and no partial page, so do not show it as an empty list. An empty list is an HTTP 200 answer: a page with no resources is valid, and it can be [empty without being exhausted](/docs/sharing/listing#pages-can-be-empty-and-not-exhausted), so continue with `nextCursor` until `exhausted` is `true`. The reasons `capability_missing`, `identity_evidence_missing`, `policy_evidence_missing`, and `unrepresentable_identity` point at the server's configuration or its identity data and need attention there; `expiry_crossed`, `session_expired`, `snapshot_unavailable`, and `changed` may succeed on a later request, although `snapshot_unavailable` can also mean corrupt stored data that needs repair. See the [reason table](/docs/sharing/listing#when-no-consistent-page-can-be-read). The reason never contains a tenant, subject, or resource value. [`@rolebook/client`](/docs/http-api/client#accesslistingunavailableerror) and the Python, Go, and Rust clients surface it as a typed error with the reason. `listAccess()` is a library call and has no HTTP operation. ## CSRF and CORS [#csrf-and-cors] A request with an `Origin` header is allowed when that origin is the request's own origin or is listed in `allowedOrigins` or `cors.origins`; `Origin: null` is refused. A request without `Origin` but with `Sec-Fetch-Site` is allowed only for `same-origin`. A request with neither header is allowed, so non-browser SDKs keep working; to accept browsers only, require `Sec-Fetch-Site` in `getContext` and return `undefined` without it. Behind a proxy that rewrites the host, list the public origin in `allowedOrigins`. CORS headers are added only when `cors` is set and the request's origin is in `cors.origins`. ## Idempotency and instances [#idempotency-and-instances] Clients choose idempotency keys: one per user intent, sent again when retrying that intent. The server never generates or rewrites a key. A replay answers `ALREADY_APPLIED` without an invitation token. Listing and audit cursors are sealed with the sharing instance's `listingCursorKey`. Configure one shared key wherever more than one process, instance, or restart may page the same cursor; see [secret keys](/docs/sharing/setup#secret-keys). ## Body limit [#body-limit] `maxBodyBytes` defaults to 65,536 (`DEFAULT_MAX_BODY_BYTES`) and must be an integer from 1 to 1,048,576. A larger `Content-Length` is refused before the body is read, and a streamed body is cancelled as soon as it passes the limit. `sharing.explain` reads at most 8,192 bytes, or `maxBodyBytes` when that is smaller. # @rolebook/server (/docs/http-api/server) > A mountable fetch handler for the sharing HTTP API, with Hono and Next.js adapters. `@rolebook/server` turns a sharing instance into a web-standard handler. See the [HTTP API guide](/docs/http-api) for the contract, status codes, and CSRF rules. ```ts import { createSharingHandler } from "@rolebook/server"; import type { ResourceSharing, SharingResourceConfigurations, TenantContext } from "@rolebook/sharing"; declare const sharing: ResourceSharing; declare function getContext(request: Request): Promise; const handler = createSharingHandler({ basePath: "/api/sharing", sharing, getContext, allowedOrigins: ["https://app.example.com"], cors: { origins: ["https://admin.example.com"], credentials: true }, onInternalError: (error) => console.error("sharing api", error), }); const response = await handler(new Request("https://app.example.com/api/sharing/v1/sharing.authorize")); ``` With Hono, mount it on a wildcard route; `getContext` receives the Hono context: ```ts import { type Context, Hono } from "hono"; import { createSharingHonoHandler } from "@rolebook/server/hono"; import type { ResourceSharing, SharingResourceConfigurations, TenantContext } from "@rolebook/sharing"; declare const sharing: ResourceSharing; type AppEnv = { Variables: { tenantContext: TenantContext | undefined } }; const app = new Hono(); app.all( "/api/sharing/*", createSharingHonoHandler({ basePath: "/api/sharing", sharing, getContext: (context: Context) => context.get("tenantContext"), }), ); ``` With Next.js, in `app/api/sharing/[...rolebook]/route.ts`: ```ts import { createSharingRouteHandlers } from "@rolebook/server/next"; import type { ResourceSharing, SharingResourceConfigurations, TenantContext } from "@rolebook/sharing"; declare const sharing: ResourceSharing; declare function getContext(request: Request): Promise; export const { POST, OPTIONS } = createSharingRouteHandlers({ basePath: "/api/sharing", sharing, getContext }); ``` ## Request handling [#request-handling] For each request the handler checks, in order: the path names a known operation (404), a CORS preflight from a configured origin is answered, the method is `POST` (405), the origin check passes (403), the content type is JSON (415), `getContext` returns a context (401), the body fits `maxBodyBytes` (413), and it is UTF-8 JSON of an object (400). It then runs the operation on `sharing.forTenant(context)`, maps listing, cursor, and audit request errors to 400, maps a listing that could not read a consistent page to 503, and serializes the result with 200. Other unexpected failures are reported to `onInternalError` (default `console.error`; its own failures are swallowed) and answered with 500. A `TOO_MANY_ASSIGNMENTS` listing error is reported too. The 503 is an expected outcome and not a fault. When `listAccessible()` rejects with the sharing module's `AccessListingUnavailableError` and one of its eight known reasons, the response body is an error object with the code `ACCESS_LISTING_UNAVAILABLE`, the fixed message `Access listing unavailable`, and that reason. The message is fixed and the reason comes from an allowlist, so nothing else the error carries reaches the response, and `onInternalError` is not called. Monitor these responses by reason if you need to: the reasons `capability_missing`, `identity_evidence_missing`, and `policy_evidence_missing` mean listing needs a configuration change before it can work. See [when a listing cannot be read](/docs/http-api#when-a-listing-cannot-be-read) for the body. `sharing.explain` follows the same order up to `getContext`, then differs. The handler reads the root's `inspectionEnabled` once, when it is created: unless it was exactly `true`, the operation answers the fixed private 404 without reading the body and without calling the limiter, the audit sink, or `explain`, and nothing the root does later enables it. When enabled, the body fits 8 KiB (or `maxBodyBytes`, if smaller) or is the ordinary 413; a body that is not UTF-8 JSON is the ordinary 400; a body with any key other than `resource`, `action`, `subject`, and `field` is the fixed 400 and is never forwarded. The result is sent as the 200 only when it matches the `ExplainResult` schema; each library failure has its fixed body, and a throw, a rejection, or any other shape is the fixed 503. Nothing on this path reaches `onInternalError`. The bodies are listed under [Inspection](/docs/http-api/http#inspection). The constructor throws a `TypeError` for a missing `sharing` or `getContext`, a `basePath` that is not `""` or a path starting with `/` and not ending with one, a `maxBodyBytes` outside 1 to 1,048,576, or an invalid origin. `import { ... } from "@rolebook/server"`, `"@rolebook/server/hono"` (needs `hono` `>=4.12.34 <5`), and `"@rolebook/server/next"`. Signatures are checked against the built declarations. ## @rolebook/server [#rolebookserver] ### `createSharingHandler` [#createsharinghandler] ```ts api="@rolebook/server" function createSharingHandler( options: SharingHandlerOptions, ): (request: Request) => Promise; ``` A `(request: Request) => Promise` serving every operation under `{basePath}/v1/`. ### `SharingHandlerOptions` [#sharinghandleroptions] ```ts api="@rolebook/server" interface SharingHandlerOptions< TResources extends SharingResourceConfigurations = SharingResourceConfigurations, > { readonly sharing: ResourceSharing; readonly getContext: ( request: Request, ) => TenantContext | undefined | Promise; readonly basePath?: string; readonly allowedOrigins?: readonly string[]; readonly cors?: SharingCorsOptions; readonly maxBodyBytes?: number; readonly onInternalError?: (error: unknown, request: Request) => void; } ``` `sharing` and `getContext` (required); `basePath` (default `""`), `allowedOrigins` (default none), `cors`, `maxBodyBytes` (default 65,536), and `onInternalError` (default `console.error`). ### `SharingCorsOptions` [#sharingcorsoptions] ```ts api="@rolebook/server" interface SharingCorsOptions { readonly origins: readonly string[]; readonly allowHeaders?: readonly string[]; readonly credentials?: boolean; readonly maxAgeSeconds?: number; } ``` `origins`, `allowHeaders` (default `["content-type"]`), `credentials` (default `false`), `maxAgeSeconds` (default 600, 0 to 86,400). ## @rolebook/server/hono [#rolebookserverhono] ### `createSharingHonoHandler` [#createsharinghonohandler] ```ts api="@rolebook/server/hono" function createSharingHonoHandler< TResources extends SharingResourceConfigurations, E extends Env = Env, >(options: SharingHonoOptions): (context: Context) => Promise; ``` The handler as a Hono handler: `getContext` and `onInternalError` receive the Hono context. ### `SharingHonoOptions` [#sharinghonooptions] ```ts api="@rolebook/server/hono" interface SharingHonoOptions< TResources extends SharingResourceConfigurations = SharingResourceConfigurations, E extends Env = Env, > extends Omit, "getContext" | "onInternalError"> { readonly getContext: ( context: Context, ) => TenantContext | undefined | Promise; readonly onInternalError?: (error: unknown, context: Context) => void; } ``` ## @rolebook/server/next [#rolebookservernext] ### `createSharingRouteHandlers` [#createsharingroutehandlers] ```ts api="@rolebook/server/next" function createSharingRouteHandlers( options: SharingHandlerOptions, ): { readonly POST: (request: Request) => Promise; readonly OPTIONS: (request: Request) => Promise; }; ``` Frozen `{ POST, OPTIONS }` route handlers for a Next.js App Router catch-all route. ## @rolebook/server/core [#rolebookservercore] The response core of the handler, for a host that owns its own HTTP admission. The host authenticates the request, derives the `TenantContext` from its own session, recognizes the operation, and applies its own routing, CORS, CSRF, and media-type checks. `run` then answers that one operation exactly as `createSharingHandler` does after the same checks: body limits and decoding, the operation, error mapping, and serialization. The core never reads a session, a header-supplied tenant, or CORS configuration, and `run` never rejects. ```ts import { createResponseHeaders, createSharingCore, csrfAllowed, errorResponse, isJsonContentType, } from "@rolebook/server/core"; import { isSharingOperation } from "@rolebook/http"; import type { ResourceSharing, SharingResourceConfigurations, TenantContext } from "@rolebook/sharing"; declare const sharing: ResourceSharing; declare function sessionContext(request: Request): Promise; const core = createSharingCore({ sharing }); const allowed = new Set(["https://app.example.com"]); async function serve(request: Request, name: string): Promise { const headers = createResponseHeaders(); if (!isSharingOperation(name)) return errorResponse(404, "UNKNOWN_OPERATION", "Unknown operation", headers); if (!csrfAllowed(request, allowed)) return errorResponse(403, "CSRF", "Cross-site request refused", headers); if (!isJsonContentType(request.headers.get("content-type"))) return errorResponse(415, "UNSUPPORTED_MEDIA_TYPE", "Content-Type must be application/json", headers); const context = await sessionContext(request); if (context === undefined) return errorResponse(401, "UNAUTHENTICATED", "No authenticated tenant context", headers); return core.run({ operation: name, request, context, headers }); } ``` ### `createSharingCore` [#createsharingcore] ```ts api="@rolebook/server/core" function createSharingCore(o: SharingCoreOptions): SharingCore; ``` Validates its options with the handler's own checks and messages, and reads the root's `inspectionEnabled` once: only a literal `true` enables `sharing.explain`. ### `SharingCoreOptions` [#sharingcoreoptions] ```ts api="@rolebook/server/core" interface SharingCoreOptions { sharing: ResourceSharing; maxBodyBytes?: number; onInternalError?: (error: unknown, request: Request) => void; } ``` `sharing` (required), `maxBodyBytes` (default 65,536, 1 to 1,048,576), and `onInternalError` (default `console.error`; its own throw or rejected promise is ignored). ### `SharingCore` [#sharingcore] ```ts api="@rolebook/server/core" interface SharingCore { readonly inspectionEnabled: boolean; readonly maxBodyBytes: number; run(input: SharingOperationInput): Promise; } ``` ### `SharingOperationInput` [#sharingoperationinput] ```ts api="@rolebook/server/core" interface SharingOperationInput { operation: SharingOperation; request: Request; context: TenantContext; headers: Headers; } ``` `context` is an already authenticated tenant context. `headers` is a fresh object for this response: `run` adds only `content-type: application/json; charset=utf-8`, so headers the host set (CORS) are kept. ### `createResponseHeaders` [#createresponseheaders] ```ts api="@rolebook/server/core" function createResponseHeaders(): Headers; ``` The fixed non-CORS headers: `cache-control: no-store` and `x-content-type-options: nosniff`. ### `csrfAllowed` [#csrfallowed] ```ts api="@rolebook/server/core" function csrfAllowed(request: Request, allowed: ReadonlySet): boolean; ``` True for a same-origin request, an `Origin` in `allowed`, or a request with no browser signal. ### `isJsonContentType` [#isjsoncontenttype] ```ts api="@rolebook/server/core" function isJsonContentType(value: string | null): boolean; ``` True for `application/json` with no `charset` other than `utf-8`. ### `errorResponse` [#errorresponse] ```ts api="@rolebook/server/core" function errorResponse(status: number, code: string, message: string, headers: Headers, issues?: readonly WireIssue[], reason?: string): Response; ``` The wire error envelope `{ error: { code, message, issues?, reason? } }` as a JSON response. ### `EXPLAIN_MAX_BODY_BYTES` [#explain_max_body_bytes] ```ts api="@rolebook/server/core" const EXPLAIN_MAX_BODY_BYTES = 8192; ``` The `sharing.explain` body limit in bytes, unless `maxBodyBytes` is smaller. # Introduction (/docs) > Permissions and resource sharing for TypeScript: roles, conditions, field rules, teams, invitations, webhooks, and audit logs. Rolebook decides who can do what in your app, and tells you why. At its core, `rolebook` is a small TypeScript library that runs inside your own server process. You define your resources and roles once, pass in who is asking and what they are trying to touch, and Rolebook returns `allowed` or a coded denial, with the matching rule whenever one decided it. The core engine has no database, network, authentication, framework, or UI dependency. When you need more than role checks, first-party packages build on the same engine: - **Resource sharing** (`@rolebook/sharing`): per-item owners, members, expiring access, invitations, folder inheritance, filtered lists, and audit logs stored in your own PostgreSQL or SQLite database. - **Identity & teams**: read users and organizations from Better Auth (including a drop-in Better Auth plugin), Clerk, or WorkOS, and share with flat or optionally nested teams. - **HTTP, React UI, webhooks & SDKs**: serve sharing from your own server (`@rolebook/server`), call it from browsers (`@rolebook/client`, `@rolebook/react`) or Python, Go, and Rust clients, and send signed access-change webhooks. - **Route middleware, CLI & remote/offline checks**: guard Hono, Express 5, and Fastify 5 routes, inspect and manage access with `@rolebook/cli` (and its local MCP server), answer checks for other services with `@rolebook/decision-service`, or verify signed checks offline with `@rolebook/offline`. [Choose how decisions run](/docs/choosing) compares each option so you can pick only what you need. ## The model in one paragraph [#the-model-in-one-paragraph] A **policy** lists the things in your app (organizations, workspaces, projects), what actions each supports, and the roles that allow or block those actions at a **scope**. A **subject** (such as a user) never carries roles on itself. On each request, your app loads that person's scoped **assignments** and passes the target item as a **trusted resource** along with its parent chain. Rolebook validates every input, checks deny rules before allow rules across all roles and teams, and returns a **decision** with a stable code, a reason, the deciding rule, and optionally a trace of every rule it checked. ## Where it sits [#where-it-sits] | Layer | Answers | | --- | --- | | Identity provider | Who is signed in, and which workspaces do they belong to? | | Your application | Which role assignments and which item does this request involve? | | The Rolebook engine (`rolebook`) | Is this action allowed, and why? | | Rolebook Sharing (optional) | Who has access to this specific item, and who may change it? | | Decision service (optional) | The same permission check, asked over HTTP by another service you authenticate. | | Offline snapshots (optional) | The same check for one prepared action, verified on a device with no connection. | ## Packages [#packages] | Package | What it does | | --- | --- | | [`rolebook`](/docs/api) | The core engine (`definePolicy`, `check`, `enforce`, `explain`), optional `rolebook/authoring` fact-schema checks, and [Hono](/docs/hono), [Express 5](/docs/api/express), and [Fastify 5](/docs/api/fastify) middleware. | | [`@rolebook/sharing`](/docs/sharing) | Per-resource ownership, memberships, invitations, expiring access, folder inheritance, audit logs, and accessible-resource listing. | | [`@rolebook/sharing-postgres`](/docs/sharing-postgres) | PostgreSQL storage adapter, migrations, transactional fences, authorized queries, and protected writes. | | [`@rolebook/sharing-sqlite`](/docs/sharing-sqlite) | SQLite storage adapter for local-first, edge, and desktop apps (Bun, Node, better-sqlite3, local libSQL). | | [`@rolebook/teams`](/docs/teams) | Team principals for sharing: flat teams by default, with optional bounded nested team lineage on PostgreSQL and SQLite. | | [`@rolebook/better-auth`](/docs/better-auth) | Drop-in Better Auth plugin for Sharing: session-bound endpoints, PostgreSQL/SQLite kits, client plugin, and React bindings. | | [`@rolebook/sharing-better-auth`](/docs/sharing-better-auth) | Better Auth identity adapter (users and workspace membership). | | [`@rolebook/sharing-clerk`](/docs/sharing-clerk) | Clerk identity adapter (users and organization membership). | | [`@rolebook/sharing-workos`](/docs/sharing-workos) | WorkOS User Management identity adapter (users, memberships, Directory Sync groups). | | [`@rolebook/sharing-testkit`](/docs/sharing-testkit) | Reusable security contract tests that every sharing storage adapter must pass. | | [`@rolebook/http`, `@rolebook/server`, `@rolebook/client`](/docs/http-api) | The Sharing HTTP API (wire contract, OpenAPI, mountable fetch/Hono/Next.js handler, typed client) plus signed [access-change webhooks](/docs/sharing/webhooks). | | [`@rolebook/react`](/docs/react) | Accessible React sharing components (`MembersList`, `InviteMember`, `OwnershipTransfer`, `AuditLog`) and headless state (`@rolebook/react/core`). | | [`@rolebook/cli`](/docs/cli) | The `rolebook` CLI for setup, checks, explanations, access changes, policy diffs, and the local [MCP server](/docs/agents/mcp). | | [`@rolebook/connector`](/docs/connect-to-rolebook-console) | Connects your application to Rolebook Console: signed commands, applied through your own Sharing instance. | | [`@rolebook/decision-service`](/docs/decision-service) | A `fetch` handler for authenticated single and batch permission checks over HTTP, using an authority provider you supply. | | [`@rolebook/offline`](/docs/offline) | Signed bundles for one exact check, verified under a root-signed trust lease and evaluated offline by the engine. | | [`@rolebook/scalars-p1`](/docs/scalars-p1) | The strict, bounded JSON parser shared by the decision service and offline snapshots. | | [`@rolebook/migrate`](/docs/migrate) | Casbin-subset and role-table import planning, plan diffs, and read-only shadow comparison. | ## Where to go next [#where-to-go-next] Embedded engine, Sharing, the HTTP API, the decision service, or offline snapshots. Packages, runtimes, and peer dependencies. Define a policy, bind a subject, check a permission. Policies, roles, assignments, resources, conditions, and decisions. What Rolebook guarantees, and what your application must establish. # Installation (/docs/installation) > Packages, entry points, runtimes, and peer dependencies. The Rolebook engine is one package, `rolebook`, with no runtime dependencies. > **Not on npm yet.** The Rolebook packages are not on npm yet. The npm package named `rolebook` is an unrelated project, so do not install it. Add the sharing packages only when you need [resource sharing](/docs/sharing): the module itself, one storage adapter, and the identity adapter for your provider. For example, sharing on PostgreSQL with Better Auth uses `rolebook`, `@rolebook/sharing`, `@rolebook/sharing-postgres` and `@rolebook/sharing-better-auth`. To answer checks for other services, or on a device without a connection, add the [decision service](/docs/decision-service) or [offline snapshots](/docs/offline). Both evaluate with `rolebook`, which they declare as a peer, and both bring in `@rolebook/scalars-p1` as their own dependency, so you add it yourself only to call the parser directly. Not sure which packages you need? [Choose how decisions run](/docs/choosing) compares them. ## Packages and entry points [#packages-and-entry-points] Every package is ECMAScript modules only (`"type": "module"`, `import` exports) and ships its own TypeScript declarations. There is no CommonJS build. | Package | Version | Entry points | Peer dependencies | | --- | --- | --- | --- | | `rolebook` | 4.0.0 | `rolebook`, `/authoring`, `/middleware/hono`, `/middleware/express`, `/middleware/fastify` | All optional, each only for its own middleware: `hono` `>=4.12.34 <5`, `express` `>=5.1.0 <6`, `fastify` `>=5.0.0 <6` | | `@rolebook/sharing` | 0.1.0 | `@rolebook/sharing`, `/checkpoints` | `rolebook` `^4.0.0` | | `@rolebook/sharing-postgres` | 0.1.0 | `@rolebook/sharing-postgres` | `@rolebook/sharing` `^0.1.0`, `rolebook` `^4.0.0` | | `@rolebook/sharing-sqlite` | 0.1.0 | `@rolebook/sharing-sqlite`, `/bun`, `/bun-query` (Bun only), `/libsql` | `@rolebook/sharing` `^0.1.0`, `rolebook` `^4.0.0`; `@libsql/client` `>=0.17.0 <1`, optional (only for `/libsql`) | | `@rolebook/teams` | 0.1.0 | `@rolebook/teams`, `/sql`, `/better-auth`, `/sqlite` | `@rolebook/sharing` `^0.1.0`, `rolebook` `^4.0.0`; `@rolebook/sharing-postgres` `^0.1.0` and `@rolebook/sharing-sqlite` `^0.1.0`, each optional | | `@rolebook/sharing-better-auth` | 0.1.0 | `@rolebook/sharing-better-auth` | `@rolebook/sharing` `^0.1.0`, `rolebook` `^4.0.0`, `better-auth` `>=1.7.7 <2` | | `@rolebook/better-auth` | 0.1.0 | `@rolebook/better-auth`, `/postgres`, `/sqlite`, `/client`, `/react` | `@rolebook/sharing` `^0.1.0`, `rolebook` `^4.0.0`, `better-auth` `>=1.7.14 <1.8`; optional peers per entry: `@rolebook/sharing-postgres`, `@rolebook/sharing-sqlite`, `@rolebook/teams`, `@rolebook/client`, `@rolebook/react`, `nanostores`, `react` | | `@rolebook/sharing-clerk` | 0.1.0 | `@rolebook/sharing-clerk` | `@rolebook/sharing` `^0.1.0`, `rolebook` `^4.0.0`, `@clerk/backend` `>=3.17.0 <4` | | `@rolebook/sharing-workos` | 0.1.0 | `@rolebook/sharing-workos` | `@rolebook/sharing` `^0.1.0`, `rolebook` `^4.0.0`, `@workos-inc/node` `>=11.0.0 <12` | | `@rolebook/sharing-testkit` | 0.1.0 | `@rolebook/sharing-testkit` | `@rolebook/sharing` `^0.1.0` | | `@rolebook/http` | 0.1.0 | `@rolebook/http`, `/webhooks`, `@rolebook/http/openapi.json` | `@rolebook/sharing` `^0.1.0` | | `@rolebook/server` | 0.1.0 | `@rolebook/server`, `/webhooks`, `/hono`, `/next`, `/core` | `@rolebook/sharing` `^0.1.0`; `hono` `>=4.12.34 <5`, optional (only for `/hono`) | | `@rolebook/client` | 0.1.0 | `@rolebook/client` | `@rolebook/sharing` `^0.1.0` | | `@rolebook/react` | 0.1.0 | `@rolebook/react`, `/core` | `@rolebook/client` `^0.1.0`, `@rolebook/sharing` `^0.1.0`, `react` `>=18.3.0 <20` | | `@rolebook/cli` | 0.1.0 | `@rolebook/cli` (`rolebook` binary) | `rolebook` `^4.0.0`, `@rolebook/sharing` `^0.1.0` | | `@rolebook/decision-service` | 0.1.0 | `@rolebook/decision-service` | `rolebook` `^4.0.0` | | `@rolebook/offline` | 0.1.0 | `@rolebook/offline` | `rolebook` `^4.0.0` | | `@rolebook/scalars-p1` | 0.1.0 | `@rolebook/scalars-p1`, `@rolebook/scalars-p1/fixtures/p1-v1.json` | None | | `@rolebook/migrate` | 0.1.0 | `@rolebook/migrate` | `rolebook` `^4.0.0` | `@rolebook/server` and `@rolebook/client` depend on `@rolebook/http`, and `@rolebook/decision-service` and `@rolebook/offline` depend on `@rolebook/scalars-p1`; your package manager installs those for you. The decision service and offline packages are independent of Sharing. They ship no adapters, so each needs code from you before it can answer: | Package | You supply | | --- | --- | | `@rolebook/decision-service` | A credential verifier, an authority provider for each scope, a clock, a random source, and the HTTP host that mounts the handler. | | `@rolebook/offline` | Root keys, a qualified clock, a trusted state store, and Ed25519 functions; an issuer also needs a durable sequence allocator. | | `@rolebook/scalars-p1` | Explicit limits on every call. It has no defaults. | The storage adapters do not depend on a database driver. They take a small parameterized executor that you build over the driver you already use (`pg`, `postgres.js`, `bun:sqlite`, `better-sqlite3`, `node:sqlite`, libSQL). The SQLite package ships executors for `bun:sqlite` and `@libsql/client`. ## Runtime [#runtime] `rolebook` declares Node.js 24 or later in its `engines` field. The core imports no Node.js built-in module, so it also runs on other runtimes that load ES modules. The sharing packages import `node:crypto` (invitation tokens, sealed cursors, policy digests), so they need Node.js, Bun, or a runtime with Node.js compatibility. `@rolebook/migrate` hashes with `node:crypto` too, so it needs Node.js or Bun. The SQLite `/bun` executor also uses `node:async_hooks` and expects a `bun:sqlite` database. `@rolebook/offline` imports `node:crypto` for SHA-256 and runs on Node.js 24 or later or on Bun; a browser is not a supported runtime for it. Ed25519 signing and verification come from the adapter you inject. `@rolebook/decision-service` is a web-standard `fetch` handler: mount it in a host that provides `Request` and `Response`, such as `Bun.serve`, a Node.js adapter, or a framework route. The declarations use `const` type parameters and template literal types, so permissions are checked at compile time. Use a current TypeScript release with `strict` enabled. The packages are built and tested with `exactOptionalPropertyTypes` and `noUncheckedIndexedAccess` on, and the code samples in these docs are type-checked with the same settings. ## Development of Rolebook itself [#development-of-rolebook-itself] The repository pins Bun 1.4.3. From a checkout: ```sh bun ci bun run verify ``` `bun run build` builds the core into `dist/`, and `bun run build:packages` builds every package in dependency order. See the repository README for the coverage gates and the PostgreSQL test database. # Limits (/docs/limits) > The hard bounds that keep policy compilation and evaluation finite. Rolebook bounds every input, so policy compilation and every check finish in bounded time and memory. Inputs beyond these limits deny at binding or check time. Invalid policy data, including a policy over a limit, fails `definePolicy()` with an `Error` instead. ## Policy [#policy] | Input | Limit | | --- | ---: | | Resource types | 1 to 128 | | Roles | 1 to 128 | | Actions per resource type | 1 to 128 | | Parent chain above a resource type | 16 | | Direct rules per role | 256 | | Direct rules in the policy | 4,096 | | Effective rules per role (own and inherited) | 4,096 | | Effective rules summed over all roles | 16,384 | | Field patterns per rule | 1 to 64 | | Condition nodes per rule / condition depth | 256 / 16 | | Policy names (types, actions, roles, fact and field segments) | 1 to 128 characters | | `version` label | 1 to 512 characters | | Policy snapshot: values / array entries / object keys / depth | 32,768 / 4,096 / 129 / 54 | ## Bindings and requests [#bindings-and-requests] | Input | Limit | | --- | ---: | | Assignments in one binding | 256 | | Group principals in one binding (`MAX_PRINCIPALS`) | 64 | | Assignment snapshot: values / array entries / object keys / depth | 4,096 / 256 / 64 / 16 | | Subject, context, resource, and literal snapshots: values / array entries / object keys / depth | 1,024 / 128 / 64 / 16 | | String values | 512 characters | | Subject and resource IDs | 1 to 128 characters | | Request permission | 257 characters | | Requested field: length / segments | 512 characters / 16 | | Fact path segments after the root | 16 | | Resource ancestry entries | 16 | | Explanation trace entries | 64; `traceTruncated` reports the rest | | Condition-tree nodes in a `{ detail: "conditions" }` explanation | 256 shared by the rules that do not decide the request, plus the deciding rule's whole tree (512 at most); `conditionTraceTruncated` reports a tree it shortened | A request permission that is not a string, or is longer than 257 characters, is reported as an empty `permission` on the denial, so decisions never echo unbounded caller input into logs or responses. ## Keys and values inside snapshots [#keys-and-values-inside-snapshots] Every object key in subject attributes, resource attributes, context, and nested literal values follows the [policy-name grammar](/docs/policies#names): it starts with an ASCII letter and continues with letters, digits, `.`, `_`, or `-`, up to 128 characters. Any other key denies the whole binding or request (`INVALID_SUBJECT`, `INVALID_REQUEST`, or `RESOURCE_MISMATCH`), and `trustedResource()` throws on one. Values must be JSON-like: strings, finite numbers, booleans, `null`, plain objects, and dense arrays. That means a database row passed through as attributes can deny for reasons that look like authorization bugs: a key such as `_id`, `$ref`, `first name`, or a non-ASCII name; a `Date` object (pass a number or an ISO string); a string over 512 characters, such as a description; more than 64 keys; or an `undefined` from a nullable column. Map the row to the few facts the policy reads instead. ## Sharing packages [#sharing-packages] The sharing packages add their own bounds, listed with each API: for example 200 resources per `readAccessBatch()`, 256 candidate hints, 100 items per listing or audit page, 64 groups per subject, 32 custom roles per tenant, and a 1 MiB policy document. See the [`@rolebook/sharing` API](/docs/sharing/api#limits). Boundary and adversarial tests for the core limits live in `tests/v4-limits-and-closure.test.ts` in the repository. # Migrating from Casbin and role tables (/docs/migrate) > @rolebook/migrate: a strict Casbin-subset checker, import planners, plan diffs, and a read-only shadow comparison. `@rolebook/migrate` plans a move to Rolebook without changing what your application enforces. It checks a Casbin source against one exact, versioned subset, plans a Rolebook policy and assignments from it (or from an application role table), diffs plans so an import can be applied idempotently and rolled back, and compares Rolebook's decisions with your legacy system's in shadow. Every export is pure: nothing reads files, opens a connection, writes to a store, evaluates model text, or switches enforcement. Unsupported input is refused with a precise reason, never approximated. The importer and its development/test dependency graph contain no Casbin engine; its only package dependency is the Rolebook peer. Applying a plan is your application's code, because only it owns the store and its transactions. The [tested SQLite recipe](https://github.com/Amakinto-Labs/rolebook/tree/qa/packages/migrate/examples) in the package's examples shows one way: it applies a plan atomically and rolls assignments back, and it refuses stale revisions, receipt drift, and a policy replacement that would invalidate unrelated assignments. A typical migration has four steps, and enforcement changes only in the last one: 1. **Check.** Run the planner on your Casbin model and policy, or on your role table. Fix or scope out every issue it reports; nothing is approximated. 2. **Plan and review.** Read the planned Rolebook policy and assignments, and diff the plan against the previous one to see exactly what an import would add or remove. 3. **Shadow.** Keep enforcing with your legacy system, evaluate the same requests with Rolebook, and compare the two decisions. Investigate every disagreement. 4. **Apply and switch.** Apply the plan in your own transaction, then move enforcement to Rolebook in your application. ```ts import { planCasbinImport } from "@rolebook/migrate"; import { createAuthorizer, trustedResource } from "rolebook"; declare const model: string; // the Casbin model text declare const policy: string; // the Casbin policy lines const result = planCasbinImport({ model, policy, roles: ["editor"], // declared, never inferred importId: "casbin-2026-11", subjectType: "user", objects: { "doc-1": { type: "document", id: "1" }, "doc-2": { type: "document", id: "2" }, }, }); if (!result.ok) throw new Error(result.issues.map((issue) => issue.code).join(", ")); const decision = createAuthorizer(result.plan.policy).check({ subject: { type: "user", id: "alice" }, assignments: result.plan.assignments.map((record) => record.assignment), permission: "document:read", resource: trustedResource({ type: "document", id: "1" }), }); ``` ## The accepted Casbin subset [#the-accepted-casbin-subset] Version `rolebook/casbin-rbac-equality/v1` accepts exactly one model, five sections in any order, each once: ```ini [request_definition] r = sub, obj, act [policy_definition] p = sub, obj, act [role_definition] g = _, _ [policy_effect] e = some(where (p.eft == allow)) [matchers] m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act ``` The definitions are read with a fixed, token-preserving grammar and never evaluated. Spaces and tabs are allowed around headers, keys and values and between tokens, but never inside one: `s ub`, `r . sub`, `& &` and a split section name are refused, and the effect must be exactly `some(where (p.eft == allow))`, as Casbin itself requires. Accepted formatting fixtures are checked against committed observations from Casbin 5.43.0 and evaluated through the real Rolebook Core. The tests retain 200 differential worlds (105,600 requests) and a separate 300-world reference suite without installing or executing Casbin. The observations bind exact inputs to recorded decisions; a new input requires separately captured and reviewed evidence. This verifies the recorded cases against that fixed version, not compatibility with every Casbin release. Domains, deny or priority effects, custom matchers, matcher functions, extra definitions such as `p2` or `g2`, and unknown, duplicate, or missing sections are each refused with their own code and section. Policy lines are exactly `p, role, object, action` and `g, user, role`, compared exactly. A wrong field count, an empty field, a `*`, a quote, a control or format character, unbalanced parentheses, or a field over 256 characters is refused with its line number. Repeated roles and lines are sets and change nothing. Roles are declared by you: a `p` line naming an individual user, a `g` line to an undeclared role, a `g` line whose user is itself a role, and a declared role nothing uses are all refused. Issues never carry source text. Users and roles share one namespace, as in Casbin: a request is allowed when some role holds the permission on the object and the subject is either a member of that role through a `g` line or is the role's own name. Casbin links every name to itself, so the planner gives each role that holds anything a subject with its own name. ## How a Casbin import is planned [#how-a-casbin-import-is-planned] A Rolebook role's rules apply to a resource type, and its assignment decides where. A Casbin role can hold `read` on one document and `write` on another, so one Rolebook role per Casbin role would widen access. The planner generates one role per Casbin role, resource type, and exact action set held on one object, and assigns it only at that object with `appliesTo: "self"`. Generated names are the Casbin role, the type, and a SHA-256 of both with the action set, and must fit Rolebook's role-name grammar; otherwise the import is refused, never renamed. Capacity is checked from an exact count before anything is built: at most 256 assignments per subject, at most `MAX_PLANNED_ASSIGNMENTS` (100,000) in a plan, and Rolebook's own policy limits (128 roles, 128 resource types, 128 actions per type, 4,096 rules). Each limit has its own code, distinct from the subset codes. The 100,000 limit is a protective starting limit, not a performance guarantee; raising it requires memory and timing measurements. The plan is all or nothing and deterministic, with a `sourceDigest`, a content-derived `policyDigest`, and a `recordId` per assignment. ## Role tables [#role-tables] `planRoleTableImport` turns your existing `{ subject, role, resource }` rows into direct memberships on exactly those resources, under a policy you already have. Each row is validated with the engine's own assignment validation and against the policy. A role whose rules, inherited ones included, reach another resource type is refused rather than imported in part. Any rejected row refuses the whole import with its row number. ## Applying, rolling back, and cutting over [#applying-rolling-back-and-cutting-over] The package writes nothing. Apply the plan's policy and assignments together, in one transaction of your own store. `diffImportPlans(applied, next)` returns the records to create and remove and whether the policy changed, with both policy digests, so a widened role with unchanged assignments is never reported as unchanged. `rollbackOfImportPlan(applied)` lists every record the import owns; it does not restore an earlier policy. `createShadowComparison` takes a run id and evaluates each request with the real engine. Each comparison carries an envelope: either your attestation that both systems decided over the same facts at the same logical time, named by opaque snapshot identities, or a reason the request is not comparable. Requests without a valid attestation, or with mismatched identities, are counted by reason and excluded from the comparison. Only `ALLOWED`, `NOT_GRANTED` and `EXPLICIT_DENY` are compared; any other engine code is an error, split by the legacy outcome. Only redacted references and permissions of mismatches are kept. `assessCutover` checks that every false allow is acknowledged by run, policy digest and sample, that false denies (with errors where the legacy system allowed) are within your budget, and that every mismatch bucket has a disposition. Every counter and every sum of counters must be an exact safe integer, or the evidence is malformed; a comparison stops counting at `Number.MAX_SAFE_INTEGER` calls and its report is then marked `saturated` and never ready. It is a report: cutover stays your decision. The package hashes with `node:crypto`, so it runs on Node 24 or later and Bun. ## API [#api] ### `CASBIN_SUBSET_VERSION` [#casbin_subset_version] ```ts api="@rolebook/migrate" const CASBIN_SUBSET_VERSION: "rolebook/casbin-rbac-equality/v1"; ``` ### `CasbinSubsetReport` [#casbinsubsetreport] ```ts api="@rolebook/migrate" type CasbinSubsetReport = { readonly supported: true; readonly version: typeof CASBIN_SUBSET_VERSION; readonly rules: readonly { readonly role: string; readonly object: string; readonly action: string; }[]; readonly memberships: readonly { readonly user: string; readonly role: string; }[]; } | { readonly supported: false; readonly issues: readonly ImportIssue[]; readonly truncated: boolean; }; ``` ### `checkCasbinSubset` [#checkcasbinsubset] ```ts api="@rolebook/migrate" function checkCasbinSubset(input: { readonly model: string; readonly policy: string; readonly roles: readonly string[]; }): CasbinSubsetReport; ``` ### `ImportIssue` [#importissue] ```ts api="@rolebook/migrate" interface ImportIssue { readonly code: ImportIssueCode; readonly line?: number; readonly section?: string; } ``` ### `ImportIssueCode` [#importissuecode] ```ts api="@rolebook/migrate" type ImportIssueCode = "UNSUPPORTED_MODEL" | "DOMAINS" | "DENY_EFFECT" | "PRIORITY" | "CUSTOM_MATCHER" | "MATCHER_FUNCTION" | "EXTRA_DEFINITION" | "UNKNOWN_SECTION" | "DUPLICATE_SECTION" | "MISSING_SECTION" | "UNKNOWN_LINE_TYPE" | "FIELD_COUNT" | "EMPTY_FIELD" | "WILDCARD" | "QUOTED_FIELD" | "INVALID_FIELD" | "USER_POLICY" | "UNDECLARED_ROLE" | "ROLE_NESTING" | "UNUSED_ROLE" | "TOO_LARGE" | "INVALID_NAME" | "UNMAPPED_OBJECT" | "UNUSED_OBJECT_MAPPING" | "DUPLICATE_OBJECT_MAPPING" | "POLICY_REJECTED" | "ASSIGNMENT_LIMIT" | "TOTAL_ASSIGNMENT_LIMIT" | "GENERATED_ROLE_LIMIT" | "RESOURCE_TYPE_LIMIT" | "ACTION_LIMIT" | "RULE_LIMIT" | "NAME_COLLISION" | "ROW_REJECTED" | "ROW_NOT_SELF_ONLY"; ``` ### `diffImportPlans` [#diffimportplans] ```ts api="@rolebook/migrate" function diffImportPlans(applied: ImportPlan | undefined, next: ImportPlan): { readonly create: readonly PlannedAssignment[]; readonly remove: readonly PlannedAssignment[]; readonly unchanged: number; readonly policyChanged: boolean; readonly fromPolicyDigest?: string; readonly toPolicyDigest: string; }; ``` ### `ImportPlan` [#importplan] ```ts api="@rolebook/migrate" interface ImportPlan { readonly version: 1; readonly importId: string; readonly sourceDigest: string; readonly policyDigest: string; readonly policy: RolebookPolicy; readonly assignments: readonly PlannedAssignment[]; } ``` ### `ImportPlanResult` [#importplanresult] ```ts api="@rolebook/migrate" type ImportPlanResult = { readonly ok: true; readonly plan: ImportPlan; } | { readonly ok: false; readonly issues: readonly ImportIssue[]; readonly truncated: boolean; }; ``` ### `MAX_PLANNED_ASSIGNMENTS` [#max_planned_assignments] ```ts api="@rolebook/migrate" const MAX_PLANNED_ASSIGNMENTS = 100000; ``` ### `PlannedAssignment` [#plannedassignment] ```ts api="@rolebook/migrate" interface PlannedAssignment { readonly recordId: string; readonly assignment: RoleAssignment; } ``` ### `planCasbinImport` [#plancasbinimport] ```ts api="@rolebook/migrate" function planCasbinImport(input: { readonly model: string; readonly policy: string; readonly roles: readonly string[]; readonly importId: string; readonly subjectType: string; readonly objects: Readonly>; }): ImportPlanResult; ``` ### `planRoleTableImport` [#planroletableimport] ```ts api="@rolebook/migrate" function planRoleTableImport(input: { readonly policy: RolebookPolicy; readonly importId: string; readonly rows: readonly { readonly subject: ResourceRef; readonly role: string; readonly resource: ResourceRef; }[]; }): ImportPlanResult; ``` ### `rollbackOfImportPlan` [#rollbackofimportplan] ```ts api="@rolebook/migrate" function rollbackOfImportPlan(applied: ImportPlan): { readonly remove: readonly PlannedAssignment[]; }; ``` ### `assessCutover` [#assesscutover] ```ts api="@rolebook/migrate" function assessCutover(input: { readonly report: ShadowReport; readonly explainedFalseAllows: readonly FalseAllowAcknowledgment[]; readonly falseDenyBudget: number; readonly dispositions: Partial>; }): { readonly ready: boolean; readonly blockers: readonly string[]; }; ``` ### `createShadowComparison` [#createshadowcomparison] ```ts api="@rolebook/migrate" function createShadowComparison(options: { readonly policy: RolebookPolicy; readonly maxSamples: number; readonly runId: string; }): ShadowComparison; ``` ### `FalseAllowAcknowledgment` [#falseallowacknowledgment] ```ts api="@rolebook/migrate" interface FalseAllowAcknowledgment { readonly runId: string; readonly policyDigest: string; readonly sampleId: number; } ``` ### `ShadowBucket` [#shadowbucket] ```ts api="@rolebook/migrate" type ShadowBucket = "match_allow" | "match_deny" | "false_allow" | "false_deny" | "rolebook_error_legacy_allow" | "rolebook_error_legacy_deny" | "noncomparable"; ``` ### `ShadowComparability` [#shadowcomparability] ```ts api="@rolebook/migrate" type ShadowComparability = { readonly kind: "attested"; readonly rolebookSnapshot: string; readonly legacySnapshot: string; readonly rolebookTime: string; readonly legacyTime: string; } | { readonly kind: "noncomparable"; readonly reason: ShadowDeclaredReason; }; ``` ### `ShadowComparison` [#shadowcomparison] ```ts api="@rolebook/migrate" interface ShadowComparison { compare(input: { readonly request: AuthorizationRequest; readonly legacy: "allow" | "deny" | "unknown"; readonly comparability: ShadowComparability; }): void; report(): ShadowReport; } ``` ### `ShadowDeclaredReason` [#shadowdeclaredreason] ```ts api="@rolebook/migrate" type ShadowDeclaredReason = "missing_input" | "stale_snapshot" | "unsupported_semantics" | "nonreplayable_facts" | "unknown_legacy_result"; ``` ### `ShadowNoncomparableReason` [#shadownoncomparablereason] ```ts api="@rolebook/migrate" type ShadowNoncomparableReason = ShadowDeclaredReason | "snapshot_mismatch" | "time_mismatch" | "invalid_provenance" | "invalid_legacy_result"; ``` ### `ShadowReport` [#shadowreport] ```ts api="@rolebook/migrate" interface ShadowReport { readonly runId: string; readonly policyDigest: string; readonly counts: Readonly>; readonly noncomparable: Readonly>; readonly compared: number; readonly dropped: Readonly>; readonly samples: readonly ShadowSample[]; readonly saturated: boolean; } ``` ### `ShadowSample` [#shadowsample] ```ts api="@rolebook/migrate" interface ShadowSample { readonly sampleId: number; readonly bucket: ShadowBucket; readonly subject: ResourceRef | null; readonly permission: string | null; readonly resource: ResourceRef | null; } ``` # Migrations and upgrades (/docs/migrations) > Moving to Rolebook 4, adopting sharing one resource type at a time, and upgrading the sharing packages. ## Moving to Rolebook 4 [#moving-to-rolebook-4] Rolebook 4 is a breaking rewrite of the core. These docs describe version 4 only; earlier APIs are not documented here. The model changes you must account for: - **Subjects no longer carry roles.** A `Subject` is `{ type, id, attributes? }`. Load the subject's scoped [assignments](/docs/subjects-and-assignments#assignments) from your own store and pass them to `bind()`. - **Roles live at a scope.** Every role declares a `scope` resource type, and every assignment names a concrete scope resource and whether it covers `self` or `descendants`. - **Resources carry their ancestry.** Build each check's target with [`trustedResource()`](/docs/trusted-resources), including the complete chain from immediate parent to root. - **Input is validated as complete envelopes.** An extra key on a binding, request, assignment, or resource denies instead of being ignored, and `undefined` values inside snapshots deny. Map rows to exactly the documented fields. - **Policies are compiled and frozen.** Define a policy once with `definePolicy()` and reuse the object. ## Adopting sharing [#adopting-sharing] [Sharing](/docs/sharing) is additive: existing Rolebook 4 policies and checks keep working. Adopt it one resource type at a time: 1. Add owner and member roles, and the three management actions, at the resource's scope. 2. Create the sharing tables with the adapter's migrations. Configure the eligibility fence against your authoritative, database-local organization-member table and its real columns; it must lock member rows in the mutation transaction. With a remote provider (Clerk, WorkOS), coordinate a local projection with membership removal first. If you map workspace roles to assignments, configure the workspace-role fact fence too. 3. Backfill exactly one ownership row per resource. Reject the rollout for a resource without an unambiguous owner; do not guess from the highest existing role. 4. Backfill ordinary memberships without mapping any legacy owner-equivalent label to a member role. 5. Run the [adapter contract](/docs/sharing-testkit) against the migrated schema, including duplicate resource IDs across tenants and concurrent ownership and invitation cases. 6. In shadow mode, compare existing decisions and listings with sharing's. Investigate every additional allow before enforcing. 7. Route mutations through `execute()`, then reads and listings. Remove legacy membership writes only after stale-access monitoring is clean. **Invitations.** Do not import legacy raw invitation tokens. Reissue pending invitations in the new keyed digest format with bounded expiry and an explicit recipient. Consumed, revoked, or expired legacy invitations stay closed. **Moves and deletions.** Wrap application deletes and moves in the adapter's lifecycle transaction (see [PostgreSQL lifecycle](/docs/sharing-postgres/lifecycle)). Never call a standalone lifecycle convenience after the application change committed. **Rollback.** Keep the old read path during shadowing, but do not dual-write ownership after cutover. Roll back deliberately: freeze sharing mutations, export owner, member, invitation, audit, lifecycle, and idempotency state, restore the previous store, verify authorization and listing parity, then run the adapter's rollback migrations. Rollback cannot restore deleted or moved application rows or raw invitation secrets. ## The sharing packages at 0.1.0 [#the-sharing-packages-at-010] The sharing packages have not had a public release before 0.1.0, so there is no upgrade path to follow yet. The behaviours below are part of the 0.1.0 baseline. They are listed because each one differs from what an application that grew its own sharing layer may expect, and each names what to do when adopting the packages or when a future release changes the behaviour: | Change | What to do | | --- | --- | | Secret keys are `rbk1_` generated keys when given as strings | Pass an existing random key as bytes with `new TextEncoder().encode(key)`; replace a passphrase with a generated key. See [secret keys](/docs/sharing/setup#secret-keys). | | The delegation ceiling | A manager that hands out a role stronger than their own gets `FORBIDDEN`. Give managers covering roles, or leave those changes to owners. See [delegation](/docs/sharing/delegation). | | Denials hide existence | Callers without a relationship to a resource get `NOT_FOUND_OR_DENIED`, not `FORBIDDEN`. Handle both alike. | | Sealed listing cursors | Cursors are sealed and bound to the caller; a cursor from another key or another caller rejects with `INVALID_CURSOR`, and the client restarts from the first page. Configure a shared `listingCursorKey` across instances. | | Time-limited memberships | Do not issue expiring grants until every instance runs a build with expiry. | | Audit incarnations | History is scoped to a resource's current incarnation; a deleted and recreated ID starts a new history. | | Restricting keys (PostgreSQL) and the key guard (SQLite) | Route tenant or ID changes of initialized resources through the move seam, never through a plain `UPDATE`. | | Idempotency `created_at` and pruning | Schedule one [pruning job](/docs/sharing/retention) with a retention longer than every client's retry window. | | Better Auth subject attributes | `principal.subject` is `{ type, id }` only; `email`, `emailVerified`, and `workspaceRole` live in `principal.attributes`. Conditions read `subject.email` and similar from there, including deny rules and `exists` checks. | | Teams team-set facts | Every team-wrapped principal carries a `TEAM_SET_AUTHORIZATION_FACT`; custom team fences must handle it and return `"conflict"` when the set changed. See [teams](/docs/teams#fences-are-required). | | Versioned sharing | Fence every writing process's adapters before the first `publish`. | Re-run the adapter migrations on every deploy: they validate the existing schema and upgrade it in place, so a future release that changes a table ships as a migration step rather than a manual procedure. # Multi-tenant setup (/docs/multi-tenant) > Model tenants, load bindings and resources per tenant, and keep every input authoritative. Rolebook has no notion of a tenant of its own: a tenant is simply the root of your resource hierarchy, and tenant isolation comes from how you load bindings and resources. This guide shows the shape that keeps it safe. ## Model the tenant as the root resource [#model-the-tenant-as-the-root-resource] Make the tenant (an organization or a workspace) the root resource type, and give every tenant-owned type a parent chain that ends there: ```ts title="policy.ts" group=tenant import { definePolicy } from "rolebook"; export const policy = definePolicy({ version: "2026-11-01", resources: { workspace: { actions: ["read", "manage"] }, project: { parent: "workspace", actions: ["read", "update", "delete"] }, document: { parent: "project", actions: ["read", "update", "delete"] }, }, roles: { workspace_admin: { scope: "workspace", rules: [ { effect: "allow", permission: "workspace:*" }, { effect: "allow", permission: "project:*" }, { effect: "allow", permission: "document:*" }, ], }, workspace_member: { scope: "workspace", rules: [{ effect: "allow", permission: "workspace:read" }], }, project_editor: { scope: "project", rules: [ { effect: "allow", permission: "project:read" }, { effect: "allow", permission: "project:update" }, { effect: "allow", permission: "document:read" }, { effect: "allow", permission: "document:update" }, ], }, }, }); ``` Because every resource's ancestry ends at its workspace, an assignment on one workspace can never apply to a resource of another: the scope resource would not be in its ancestry. ## Load the binding from the tenant [#load-the-binding-from-the-tenant] On every request, resolve the tenant from your routing or session, verify the user is a member of exactly that tenant, and load only that tenant's assignments: ```ts title="authorization.ts" group=tenant import { createAuthorizer, type BindInput, type RoleAssignment } from "rolebook"; interface AssignmentRow { readonly role: "workspace_admin" | "workspace_member" | "project_editor"; readonly scopeType: "workspace" | "project"; readonly scopeId: string; } declare const db: { isMember(tenantId: string, userId: string): Promise; assignments(tenantId: string, userId: string): Promise; }; const authorizer = createAuthorizer(policy); export async function bindingFor( tenantId: string, userId: string, ): Promise | undefined> { if (!(await db.isMember(tenantId, userId))) return undefined; const subject = { type: "user", id: userId }; const assignments: RoleAssignment[] = (await db.assignments(tenantId, userId)).map( (row) => ({ subject, role: row.role, scope: { resource: { type: row.scopeType, id: row.scopeId }, appliesTo: "descendants" }, }), ); return { subject, assignments, context: { tenantId } }; } export async function authorizationFor(tenantId: string, userId: string) { const binding = await bindingFor(tenantId, userId); return binding && authorizer.bind(binding); } ``` - **The tenant comes from the request path or the session, never from the body.** Use the same tenant ID for the membership check, the assignment query, and every resource query. - **Map rows to exactly the documented fields.** An extra key on an assignment denies the binding, and a `null` or `undefined` column is not a valid value. - **Bind once per request, not once per process.** A binding is a snapshot. Positive decisions should not be cached across requests, because membership and assignments change. ## Load resources by tenant and ID [#load-resources-by-tenant-and-id] Load every resource with a query that names both the tenant and the ID, and build the ancestry from stored parent links: ```ts title="resources.ts" group=tenant import { trustedResource, type TrustedResource } from "rolebook"; declare const documents: { find(tenantId: string, id: string): Promise< { readonly id: string; readonly projectId: string; readonly ownerId: string; readonly archived: boolean } | undefined >; }; export async function loadDocument(tenantId: string, id: string): Promise { const row = await documents.find(tenantId, id); // WHERE workspace_id = $1 AND id = $2 if (!row) return undefined; return trustedResource( { type: "document", id: row.id }, [ { type: "project", id: row.projectId }, { type: "workspace", id: tenantId }, ], { ownerId: row.ownerId, archived: row.archived }, ); } export async function canUpdateDocument(tenantId: string, userId: string, documentId: string) { const [authorization, document] = await Promise.all([ authorizationFor(tenantId, userId), loadDocument(tenantId, documentId), ]); if (!authorization || !document) return false; // treat "missing" and "not allowed" alike return authorization.check({ permission: "document:update", resource: document }).allowed; } ``` A resource that exists in another tenant is simply not found by the tenant-scoped query, so a client cannot reach it by guessing IDs. Treat "not found" and "not allowed" the same in responses when existence itself is sensitive. ## Many resources for one user [#many-resources-for-one-user] When you check one user against many resources (filtering a list), bind once and run every check on that one authorization: ```ts group=tenant export async function visibleDocuments(tenantId: string, userId: string, candidates: readonly TrustedResource[]) { const authorization = await authorizationFor(tenantId, userId); if (!authorization) return []; return candidates.filter( (resource) => authorization.check({ permission: "document:read", resource }).allowed, ); } ``` Each candidate must itself come from a tenant-scoped loader such as `loadDocument` above. For listings that must page through large tables, private resources shared per user, and invitations, use the [sharing packages](/docs/sharing): they own the storage, candidate queries, and transactional fences. ## Teams and other groups [#teams-and-other-groups] If users act through groups, load the user's groups in the same tenant and pass them as [principals](/docs/subjects-and-assignments#group-principals). Load assignments for the user and for each of its groups, from the same tenant-scoped source. Never trust group membership from a token or the client. ## Checklist [#checklist] - The tenant ID used for a request comes from routing or the session, and is the same for membership, assignments, groups, and resources. - Every resource query filters by tenant and ID. - Ancestry is built from stored parent links and ends at the tenant. - Context values a client can influence are not used as authority. - The policy is defined once and reused; bindings are per request. - Policy changes are reviewed with [`diffPolicies()`](/docs/api#diffpolicies) before they ship. # Offline check snapshots (/docs/offline) > @rolebook/offline: signed exact-check snapshots with explicit trust, freshness and rollback boundaries. `@rolebook/offline` issues and verifies `rolebook/offline-snapshot/v1` bundles. Each bundle carries the complete Core policy and inputs for one exact check. Verification authenticates the bytes, validates the current root-authorized trust lease and evaluates the carried inputs through Core. Callers cannot replace or supplement signed facts. Use it for a device, a kiosk or an edge process that must answer a prepared check without reaching your server. [Choose how decisions run](/docs/choosing) places it beside the embedded engine and the decision service, and the [security model](/docs/security-model#offline-snapshots) lists what verification guarantees and what your host establishes. > **Not on npm yet.** `rolebook` and `@rolebook/offline` are not on npm yet. The npm package named `rolebook` is an unrelated project, so do not install it. A snapshot is not a precomputed grant, delegated capability or one-time authorization. It is reusable subject to its freshness and rollback checks. Protecting a side effect requires a separate write/idempotency protocol. ## Verify a snapshot [#verify-a-snapshot] `createOfflineVerifier(config)` returns `{ verifySnapshot, installTrustLease }`. The root record, the clock, the state store and Ed25519 verification are host adapters that you supply; the package contains none of them. ```ts title="verify.ts" group=verify import { createOfflineVerifier, type OfflineRoot, type OfflineVerifyCrypto, type QualifiedClock, type TrustedStateStore, } from "@rolebook/offline"; // Host adapters supplied by your deployment. The package ships no implementation of any of them. declare const root: OfflineRoot; // provisioned out of band: root id, key and its one namespace declare const clock: QualifiedClock; // returns undefined when it cannot vouch for the time declare const state: TrustedStateStore; // durable trust lease and anti-rollback state declare const ed25519: OfflineVerifyCrypto; // strict Ed25519 verification declare const bundleBytes: Uint8Array; // the compact JWS exactly as received const verifier = createOfflineVerifier({ roots: [root], clock, state, crypto: ed25519, qualification: "ui_only", }); const result = await verifier.verifySnapshot(bundleBytes, { mode: "ui_hint", rootId: root.rootId, expectedIssuer: root.issuer, expectedAudience: root.audience, expectedScope: root.authorityScope, }); // A hint for the interface. A no-decision is never a deny and never an allow. export const showEditControl = result.kind === "decision" && result.allowed; if (result.kind === "no_decision") console.warn(`offline check unavailable: ${result.reason}`); ``` The verifier needs an installed trust lease in the state store before it can accept a bundle. The store is provisioned out of band; after that, pass each newer root-signed lease to `installTrustLease(bytes)`, which answers `installed`, `unchanged` or a no-decision. To enforce with a result, construct the verifier with `qualification: "enforcement_qualified"` and the `hostQualificationId` of your reviewed host record, and ask for `mode: "enforcement"`. See [UI hints and enforcement](#ui-hints-and-enforcement). `createOfflineIssuer(config)` returns `{ issue }`. An issuer signs the P1 bytes of one `OfflineCoreSnapshotV1` with a key the installed lease authorizes, after it reserves a sequence from the durable allocator you supply and evaluates the snapshot with Core. ## Bundles, leases and rollback state [#bundles-leases-and-rollback-state] Bundles and trust leases use compact JWS with Ed25519. Signatures cover the exact received bytes; parsing and reserializing a payload does not reproduce its signed message. All JSON boundaries use the shared `rolebook/scalars-p1/v1` profile. Policy and provider-manifest digests additionally bind the interpreted contents to the installed lease. Root-authorized leases bind the issuer, scope, audience, signing keys, authority epoch and permitted policy identities. Installing a newer lease atomically retains its exact bytes and rollback floor. The verifier refuses an older lease that could restore a retired key. Bundle rollback state is separate for each exact check, so a newer check for one resource does not invalidate an unrelated check. The issuer's durable allocator also orders authority observations. An older fact observation cannot acquire a newer sequence after a more recent observation has been reserved. Equal observation times with different snapshot contents are refused. ## UI hints and enforcement [#ui-hints-and-enforcement] A `ui_only` verifier can return only an explicitly labelled UI hint. Asking it for enforcement returns `host_not_qualified`. UI hints still require signature, time, freshness and available-state checks; invalid or missing trust does not become a hint that allows access. Enforcement requires a constructor-bound qualification record and reviewed host adapters for trustworthy time, rollback-resistant state, root-key operations and complete authority inputs. There is no default qualified clock, state store or issuer allocator. Ordinary browser storage, a restorable file or an independently mutable wall clock does not establish those guarantees. Disconnected revocation is bounded, not immediate. A verifier stops accepting a signer when it installs a newer root-signed lease that no longer authorizes that signer's key. Until then the bound is the key and lease validity (at most 7 days), the bundle expiry (at most 24 hours) and the fact age the lease allows. Lost trust state fails closed until authenticated recovery; it cannot be reset from an unsigned bundle. ## Limits and runtime [#limits-and-runtime] | Limit | Value | | --- | --- | | Compact bundle, and its decoded payload | 1,400,000 bytes and 1,048,576 bytes | | Compact lease, and its decoded payload | 96,000 bytes and 65,536 bytes | | Bundle lifetime | At most 24 hours | | Lease and signing-key lifetime | At most 7 days | | Clock uncertainty | At most 120,000 ms | | Signing keys and allowed policies in one lease | 32 and 256 | The package imports `node:crypto` for SHA-256 and runs on Node.js 24 or later and on Bun. A browser is not a supported runtime. Ed25519 comes from the adapter you inject. Distribution of bundles and leases to devices, and the qualification of each host, are your deployment's work. ## API reference [#api-reference] ### `createOfflineIssuer` [#createofflineissuer] ```ts api="@rolebook/offline" function createOfflineIssuer(config: IssuerConfig): OfflineIssuer; ``` ### `AntiRollbackStateV1` [#antirollbackstatev1] ```ts api="@rolebook/offline" interface AntiRollbackStateV1 { readonly highestEpoch: number; readonly highestSequence: number; readonly bundleId: string; readonly payloadSha256: string; readonly leaseId: string; readonly leaseRevision: number; readonly updatedAtMs: number; } ``` ### `ClockReading` [#clockreading] ```ts api="@rolebook/offline" type ClockReading = Readonly<{ nowMs: number; uncertaintyMs: number; }>; ``` ### `InstallResult` [#installresult] ```ts api="@rolebook/offline" type InstallResult = { readonly kind: "installed" | "unchanged"; } | { readonly kind: "no_decision"; readonly reason: OfflineFailure; }; ``` ### `IssueResult` [#issueresult] ```ts api="@rolebook/offline" type IssueResult = { readonly kind: "issued"; readonly bytes: Uint8Array; } | { readonly kind: "no_decision"; readonly reason: OfflineFailure; }; ``` ### `IssuerConfig` [#issuerconfig] ```ts api="@rolebook/offline" interface IssuerConfig { readonly root: OfflineRoot; readonly clock: QualifiedClock; readonly state: Pick; readonly crypto: OfflineIssuerCrypto; readonly randomBytes: (length: number) => Uint8Array; readonly signingKid: string; readonly modelId: string; readonly policyGeneration: string; readonly sequenceAllocator: SequenceAllocator; } ``` ### `IssuerMetadata` [#issuermetadata] ```ts api="@rolebook/offline" type IssuerMetadata = Readonly<{ issuer: string; authorityScope: string; audience: string; issuedAtMs: number; notBeforeMs: number; expiresAtMs: number; observedAtMs: number; maxFactAgeMs: number; }>; ``` ### `LeaseFloor` [#leasefloor] ```ts api="@rolebook/offline" type LeaseFloor = Readonly<{ leaseRevision: number; leasePayloadSha256: string; leaseId: string; authorityEpoch: number; }>; ``` ### `LeaseSlot` [#leaseslot] ```ts api="@rolebook/offline" type LeaseSlot = Omit; ``` ### `OfflineCoreSnapshotV1` [#offlinecoresnapshotv1] ```ts api="@rolebook/offline" type OfflineCoreSnapshotV1 = Readonly<{ policy: RolebookPolicy; binding: Pick; resource: AuthorizationRequest["resource"]; request: Pick; }>; ``` ### `OfflineFailure` [#offlinefailure] ```ts api="@rolebook/offline" type OfflineFailure = "malformed_bundle" | "unsupported_profile" | "trust_unavailable" | "signature_invalid" | "audience_mismatch" | "scope_mismatch" | "not_yet_valid" | "expired" | "clock_unqualified" | "rollback_detected" | "issuer_equivocation" | "state_unavailable" | "trust_changed" | "host_not_qualified" | "incomplete_snapshot" | "policy_rejected" | "policy_digest_mismatch" | "internal_fault"; ``` ### `OfflineIssuer` [#offlineissuer] ```ts api="@rolebook/offline" interface OfflineIssuer { issue(snapshotP1Json: Uint8Array, metadata: IssuerMetadata): Promise; } ``` ### `OfflineIssuerCrypto` [#offlineissuercrypto] ```ts api="@rolebook/offline" interface OfflineIssuerCrypto extends OfflineVerifyCrypto { sign(message: Uint8Array): Promise; } ``` ### `OfflineResult` [#offlineresult] ```ts api="@rolebook/offline" type OfflineResult = { readonly kind: "decision"; readonly mode: VerifyMode; readonly allowed: boolean; readonly code: "ALLOWED" | "EXPLICIT_DENY" | "NOT_GRANTED"; readonly policyDigest: string; readonly bundleId: string; } | { readonly kind: "no_decision"; readonly mode: VerifyMode; readonly reason: OfflineFailure; readonly bundleId?: string; }; ``` ### `OfflineRoot` [#offlineroot] ```ts api="@rolebook/offline" type OfflineRoot = Readonly<{ rootId: string; kid: string; publicKey: Uint8Array; issuer: string; authorityScope: string; audience: string; }>; ``` ### `OfflineSnapshotV1` [#offlinesnapshotv1] ```ts api="@rolebook/offline" interface OfflineSnapshotV1 { readonly kind: "rolebook/offline-snapshot/v1"; readonly bundleId: string; readonly issuer: string; readonly authorityScope: string; readonly audience: string; readonly issuedAtMs: number; readonly notBeforeMs: number; readonly expiresAtMs: number; readonly authorityEpoch: number; readonly snapshotKey: string; readonly sequence: number; readonly semanticProfile: "rolebook/core-v4"; readonly scalarProfile: "rolebook/scalars-p1/v1"; readonly modelId: string; readonly policyGeneration: string; readonly policyDigest: string; readonly observedAtMs: number; readonly maxFactAgeMs: number; readonly providerManifestId: string; readonly providerManifestDigest: string; readonly snapshot: OfflineCoreSnapshotV1; } ``` ### `OfflineTrustLeaseV1` [#offlinetrustleasev1] ```ts api="@rolebook/offline" interface OfflineTrustLeaseV1 { readonly kind: "rolebook/offline-trust-lease/v1"; readonly leaseId: string; readonly issuer: string; readonly authorityScope: string; readonly audience: string; readonly issuedAtMs: number; readonly notBeforeMs: number; readonly expiresAtMs: number; readonly leaseRevision: number; readonly authorityEpoch: number; readonly providerManifest: ProviderManifestV1; readonly allowedPolicies: readonly { readonly modelId: string; readonly policyGeneration: string; readonly policyDigest: string; }[]; readonly keys: readonly { readonly kid: string; readonly publicKey: string; readonly notBeforeMs: number; readonly expiresAtMs: number; }[]; } ``` ### `OfflineVerifier` [#offlineverifier] ```ts api="@rolebook/offline" interface OfflineVerifier { verifySnapshot(compactJws: Uint8Array, options: VerifyOptions): Promise; installTrustLease(compactJws: Uint8Array): Promise; } ``` ### `OfflineVerifyCrypto` [#offlineverifycrypto] ```ts api="@rolebook/offline" interface OfflineVerifyCrypto { verify(key32: Uint8Array, message: Uint8Array, signature64: Uint8Array): Promise; } ``` ### `ProviderManifestClass` [#providermanifestclass] ```ts api="@rolebook/offline" type ProviderManifestClass = "subject" | "principals" | "assignments" | "resource" | "ancestors" | "resource_attributes" | "context"; ``` ### `ProviderManifestV1` [#providermanifestv1] ```ts api="@rolebook/offline" interface ProviderManifestV1 { readonly id: string; readonly maxFactAgeMs: number; readonly required: readonly { readonly class: ProviderManifestClass; readonly paths: readonly string[]; }[]; readonly optional: readonly { readonly class: ProviderManifestClass; readonly paths: readonly string[]; }[]; } ``` ### `QualifiedClock` [#qualifiedclock] ```ts api="@rolebook/offline" interface QualifiedClock { now(): ClockReading | undefined; } ``` ### `SequenceAllocator` [#sequenceallocator] ```ts api="@rolebook/offline" interface SequenceAllocator { reserve(slot: Slot, expectedLease: LeaseFloor, observedAtMs: number, snapshotContentSha256: string): Promise; } ``` ### `SequenceReservation` [#sequencereservation] ```ts api="@rolebook/offline" type SequenceReservation = { readonly kind: "reserved"; readonly authorityEpoch: number; readonly sequence: number; } | { readonly kind: "no_decision"; readonly reason: "trust_changed" | "state_unavailable" | "incomplete_snapshot"; }; ``` ### `Slot` [#slot] ```ts api="@rolebook/offline" type Slot = Readonly<{ issuer: string; authorityScope: string; audience: string; snapshotKey: string; }>; ``` ### `TrustedState` [#trustedstate] ```ts api="@rolebook/offline" type TrustedState = Readonly<{ leaseJws: Uint8Array; leaseDigest: string; floor: LeaseFloor; slot: AntiRollbackStateV1 | undefined; }>; ``` ### `TrustedStateStore` [#trustedstatestore] ```ts api="@rolebook/offline" interface TrustedStateStore { read(slot: LeaseSlot, snapshotKey?: string): Promise; finalize(slot: Slot, expectedLease: LeaseFloor, expectedSlot: AntiRollbackStateV1 | undefined, nextSlot: AntiRollbackStateV1): Promise<"applied" | "changed" | "conflict" | "capacity_exhausted" | "state_lost">; installLease(slot: LeaseSlot, next: LeaseFloor, compactRootJws: Uint8Array): Promise<"installed" | "unchanged" | "rollback_detected" | "issuer_equivocation" | "state_lost">; } ``` ### `VerifyConfig` [#verifyconfig] ```ts api="@rolebook/offline" type VerifyConfig = (VerifyConfigBase & { readonly qualification: "ui_only"; }) | (VerifyConfigBase & { readonly qualification: "enforcement_qualified"; readonly hostQualificationId: string; }); ``` ### `VerifyMode` [#verifymode] ```ts api="@rolebook/offline" type VerifyMode = "ui_hint" | "enforcement"; ``` ### `VerifyOptions` [#verifyoptions] ```ts api="@rolebook/offline" interface VerifyOptions { readonly mode: VerifyMode; readonly rootId: string; readonly expectedIssuer: string; readonly expectedAudience: string; readonly expectedScope: string; } ``` ### `createOfflineVerifier` [#createofflineverifier] ```ts api="@rolebook/offline" function createOfflineVerifier(config: VerifyConfig): OfflineVerifier; ``` # Policies (/docs/policies) > Resources and actions, rules, wildcards, versions, and the policy lifecycle. A policy is plain data: the resource types your product has, the actions each one supports, and the roles that grant or deny those actions. `definePolicy()` validates it, canonicalizes it, compiles it, and deeply freezes it. ```ts import { definePolicy } from "rolebook"; export const policy = definePolicy({ version: "2026-11-01", resources: { organization: { actions: ["read", "manage_billing"] }, workspace: { parent: "organization", actions: ["read", "update"] }, project: { parent: "workspace", actions: ["read", "update", "delete", "share"] }, }, roles: { workspace_viewer: { scope: "workspace", rules: [ { effect: "allow", permission: "workspace:read" }, { effect: "allow", permission: "project:read" }, ], }, workspace_editor: { scope: "workspace", inherits: ["workspace_viewer"], rules: [{ effect: "allow", permission: "project:update" }], }, project_admin: { scope: "project", rules: [{ effect: "allow", permission: "project:*" }], }, }, }); ``` A policy has exactly three top-level keys: an optional `version`, `resources`, and `roles`. Any other key is an error. ## Resources and actions [#resources-and-actions] Each entry in `resources` is a resource type. It declares its concrete `actions` and at most one `parent` type. Parents form the ancestry that [scopes](/docs/roles-and-scopes) and [trusted resources](/docs/trusted-resources) are checked against. - `actions` is a non-empty list of distinct action names, at most 128. - `parent` must name another declared resource type. Parent chains may not loop, and a chain may be at most 16 types above any resource. - `recursive` is optional and, when present, must be exactly `true` (see below). - A resource definition accepts only `actions`, `parent`, and `recursive`. ### Recursive resource types [#recursive-resource-types] `recursive: true` lets resources of a type nest under resources of the same type, for example a `folder` inside a `folder`. `parent` keeps its meaning and never names the type itself: with `folder: { parent: "workspace", actions: ["read"], recursive: true }`, a document's ancestry may be `[folder, folder, workspace, organization]`. A run of folders must still continue to the root type; when the recursive type declares no parent, the chain may end at any folder. Every ancestor of every type counts against the 16-ancestor limit, and an ancestor that repeats the resource or an earlier ancestor is refused (`RESOURCE_MISMATCH`, "ancestor `i` repeats a resource"). A policy without the flag is unchanged: same accepted chains, same refusals, same canonical JSON and digest. Inside a run of same-type ancestors, Rolebook cannot tell that a folder was left out of the chain, and that folder may carry a deny. Supplying the complete chain, read to the root from authoritative data, is the caller's obligation. For that reason `@rolebook/sharing` refuses a Sharing resource type that is recursive or sits below a recursive type until it can read chains from a managed hierarchy, and managed move refuses recursive parent and child types. An engine older than this flag refuses a policy that uses it, so upgrade every process that compiles the policy before any stored policy carries the key. A **permission** is `resource:action`, for example `project:update`. Requests always name one concrete, declared permission. ### Names [#names] Resource types, actions, role names, condition fact segments, field segments, and every key inside subject attributes, resource attributes, and context are policy names. A policy name starts with a letter, continues with letters, digits, `.`, `_`, or `-`, and is at most 128 characters. `__proto__`, `prototype`, and `constructor` are refused. Subject and resource IDs are not policy names: they are opaque, non-empty strings of up to 128 characters, so numeric and UUID-style IDs work as they are. ## Rules [#rules] A rule is an allow or a deny for one permission, with optional constraints: ```ts import type { PolicyRule } from "rolebook"; const rules: PolicyRule[] = [ { effect: "allow", permission: "project:read" }, { effect: "deny", permission: "project:delete" }, { effect: "allow", permission: "project:update", where: { fact: "resource.status", operator: "equals", value: "draft" }, fields: ["title", "metadata.*"], }, ]; ``` | Key | Meaning | | --- | --- | | `effect` | `"allow"` or `"deny"`. | | `permission` | A declared `resource:action`, or `resource:*` for every action of that type. | | `where` | Optional [condition](/docs/conditions-and-fields#conditions) over subject, resource, and context facts. | | `fields` | Optional list of 1 to 64 [field patterns](/docs/conditions-and-fields#fields). | Every supplied constraint must match for a rule to match. A rule accepts only these four keys. ### Wildcards [#wildcards] A rule may use an action wildcard, `project:*`, which matches every action `project` declares. A request never may: every check names one concrete action, and a wildcard in a request is denied with `INVALID_REQUEST`. The typed authorizer rejects it at compile time too: ```ts prelude=core authorization.check({ permission: "project:update", resource: project }); // @ts-expect-error: requests name one concrete action authorization.check({ permission: "project:*", resource: project }); // @ts-expect-error: project does not declare archive authorization.check({ permission: "project:archive", resource: project }); ``` There is no wildcard for resource types and no implication between actions: `update` does not imply `read`. Grant each action explicitly. ## Version labels [#version-labels] `version` is an optional, non-empty label of up to 512 characters that you control. Every decision echoes it as `policyVersion`, so an audit record can say which policy produced a result. It does not change evaluation, and it is excluded from [`canonicalPolicyJson()`](/docs/api#canonicalpolicyjson), so two policies that differ only in their label have the same canonical form. ## Policy lifecycle [#policy-lifecycle] - **Define once.** Call `definePolicy()` at module level and reuse the returned object. It is frozen, and its compiled form and its shared authorizer are cached by object identity, so `createAuthorizer(policy)` on the same object is cheap and returns the same authorizer. - **Raw objects are revalidated.** A plain policy object that did not come from `definePolicy()` is snapshotted and validated again every time it is passed in, because it is mutable. - **Failures are deployment failures.** `definePolicy()` and `createAuthorizer()` throw a `PolicyError` when the policy is malformed, inconsistent, or over a [limit](/docs/limits). Its message starts with `Invalid Rolebook policy:` and names where the problem is, for example `(role "member", rule 1)`. Its `code` is a stable classification such as `MALFORMED_RULE` or `TOO_MANY_RULES`, and its `location` holds the `resource`, `role`, `rule` index, and `condition` pointer that apply. Treat that as a failed configuration rollout, not a request error. - **Typed facts are optional checks.** `definePolicy()` does not know which facts your application supplies, so a mistyped fact path deploys, and every comparison on it is unknown. To fail the rollout on it as well, check the policy against a [fact schema](/docs/fact-schemas) with `compilePolicy()` from `rolebook/authoring`. Core still accepts a policy those checks reject. ### Comparing policies [#comparing-policies] `diffPolicies(from, to)` describes what changed between two policies: added, removed, and changed resource types and roles, including the rules a role gains or loses through inheritance. `canonicalPolicyJson(policy)` is the deterministic serialization of a policy's meaning, useful for digests and change detection. ```ts prelude=core import { canonicalPolicyJson, definePolicy, diffPolicies } from "rolebook"; const next = definePolicy({ version: "4.1.0", resources: { organization: { actions: ["read"] }, workspace: { parent: "organization", actions: ["read", "update"] }, project: { parent: "workspace", actions: ["read", "update", "delete", "archive"] }, }, roles: { workspace_editor: { scope: "workspace", rules: [ { effect: "allow", permission: "project:read" }, { effect: "allow", permission: "project:update" }, ], }, }, }); const diff = diffPolicies(policy, next); // diff.identical === false // diff.version -> { from: "4.0.0", to: "4.1.0" } // diff.resources.changed -> [{ resourceType: "project", actionsAdded: ["archive"], actionsRemoved: [] }] const same = canonicalPolicyJson(policy) === canonicalPolicyJson(next); // false ``` The [sharing package](/docs/sharing/versioned) builds published policy versions on these two functions. ## No bypass role [#no-bypass-role] There is no built-in super administrator and no action-level implication. Elevated access is an ordinary scoped assignment of a role with explicit rules. Every grant stays visible in the policy, and every decision stays explainable. # React components (/docs/react) > @rolebook/react: accessible sharing screens and headless state for the Rolebook Sharing HTTP API. `@rolebook/react` gives you ready-to-use React components and headless state for building sharing screens over the [Rolebook Sharing HTTP API](/docs/http-api) and [`@rolebook/client`](/docs/http-api/client). - `@rolebook/react` provides `SharingProvider`, hooks (`useSharingAccess`, `useSharingMutations`, `useAuditLog`, `useOffered`), and accessible components: `MembersList`, `InviteMember`, `OwnershipTransfer`, `AuditLog`, `IntentPanel`, and `ConfirmDialog`. - `@rolebook/react/core` provides the framework-neutral state stores, idempotent mutation runner, and message catalog, with no React import. Your server still authorizes every read and write. Permission hints in the browser only decide which controls to offer. ## Install [#install] > **Not on npm yet.** `@rolebook/react`, `@rolebook/client` and `@rolebook/sharing` are not on npm yet. The npm package named `rolebook` is an unrelated project, so do not install it. `react` (18.3 or 19), `@rolebook/client`, and `@rolebook/sharing` are peer dependencies. The package has no runtime dependencies of its own. If you use Better Auth, [`@rolebook/better-auth/react`](/docs/better-auth#client-and-react) wraps `SharingProvider` with `RolebookSharingProvider`, keeps `scope` in sync with the Better Auth session, and adds `useCan(resource, action)`. ## Use the components [#use-the-components] Wrap your sharing UI in `SharingProvider`, passing your `@rolebook/client` instance, the current signed-in `scope`, and the action names from your Sharing definition: ```tsx import { createSharingClient } from "@rolebook/client"; import { AuditLog, type DirectorySearch, InviteMember, MembersList, OwnershipTransfer, SharingProvider, type SubjectRef, } from "@rolebook/react"; const client = createSharingClient({ baseUrl: "/api/sharing" }); const roles = [ { value: "viewer", label: "Viewer" }, { value: "editor", label: "Editor" }, ]; export function ProjectSharing({ session, projectId, searchWorkspaceMembers, directoryName, }: { session: { userId: string; tenantId: string; policyVersion: string; mfa?: boolean }; projectId: string; searchWorkspaceMembers: DirectorySearch; directoryName: (subject: SubjectRef) => string; }) { const resource = { type: "project", id: projectId }; return ( ({ copyLink: () => navigator.clipboard.writeText(`${location.origin}/join/${invitationId}#${token}`), })} searchDirectory={searchWorkspaceMembers} describeSubject={directoryName} > ); } ``` Keep `scope` aligned with the active session that `client` sends: `scope` keys browser caches and in-flight intents and is never sent to the server. Update `scope` whenever the user, tenant, policy version, or MFA state changes. Only pass `retryWindow={{ serverRetentionMs }}` once you know your deployment's guaranteed idempotency retention (`pruneSettledRecords` retention minus safety margin). Leaving `retryWindow` unset keeps retries disabled (`RETRY_WINDOW_UNDECLARED`). Never hardcode a window longer than your server retains idempotency records: retrying after the server has pruned a record could replay a grant that was later revoked. ## What the package handles for you [#what-the-package-handles-for-you] - **Hints stay hints.** `permissions()` maps to `"allowed"`, `"not_allowed"`, or `"no_hint"`. While access is being re-read, controls stay mounted with `aria-disabled="true"` so users keep focus and drafts, and the server still enforces delegation limits on every write. - **No accidental duplicate writes.** Mutations are admitted atomically under an idempotency key scoped to tenant, actor, and command across clicks and browser tabs (`localStorage` + Web Locks by default, or a custom `intentStore`). - **Safe handling of unknown outcomes.** If a network drop leaves a write's outcome unknown, nothing retries automatically. Users explicitly choose `retry()` (reusing the original idempotency key within `retryWindow`) or release the blocked intent. - **Minimal browser storage.** The browser stores only digests, keys, statuses, and timestamps, never payloads, emails, roles, or invitation tokens. Invitation tokens go once to `onInvitationIssued`. - **Accessibility.** Labelled controls and tables, live status and alert regions, focus-trapped confirmation dialogs, and customizable `messages` / `formatMessage` for localization. ## Headless usage (`@rolebook/react/core`) [#headless-usage-rolebookreactcore] Use `@rolebook/react/core` when you want the same access cache, hints, and safe mutation runner without React: ```ts import { createSharingClient } from "@rolebook/client"; import { createIntentRegistry, createSharingAccessStore, createSharingMutationRunner, type SharingScope, } from "@rolebook/react/core"; const client = createSharingClient({ baseUrl: "/api/sharing" }); const scope: SharingScope = { actor: "user_1", tenant: "org_1", policy: "1" }; const access = createSharingAccessStore({ client, actions: { members: "manage_members" }, }); const runner = createSharingMutationRunner({ client, registry: createIntentRegistry(), onChanged: (changedScope, resource) => void access.invalidate(changedScope, resource), }); const outcome = await runner.submit(scope, { kind: "grantRole", resource: { type: "project", id: "p1" }, subject: { type: "user", id: "u2" }, role: "viewer", }); outcome.status; ``` ## API [#api] Signatures are checked against the built declarations. ## Exports of `@rolebook/react` [#exports-of-rolebookreact] ### `ConfirmDialog` [#confirmdialog] ```ts api="@rolebook/react" function ConfirmDialog(props: ConfirmDialogProps): ReactNode; ``` ### `ConfirmDialogProps` [#confirmdialogprops] ```ts api="@rolebook/react" interface ConfirmDialogProps { readonly title: string; readonly children?: ReactNode; readonly confirmLabel: string; readonly onConfirm: () => void; readonly onCancel: () => void; } ``` ### `useAnnouncer` [#useannouncer] ```ts api="@rolebook/react" function useAnnouncer(): { readonly announce: (tone: "status" | "alert", text: string) => void; readonly announceOutcome: (outcome: SharingMutationOutcome) => void; readonly announceKey: (tone: "status" | "alert", key: SharingMessageKey) => void; readonly clear: () => void; readonly regions: ReactNode; }; ``` ### `AuditLog` [#auditlog] ```ts api="@rolebook/react" function AuditLog(props: AuditLogProps): ReactNode; ``` ### `AuditLogProps` [#auditlogprops] ```ts api="@rolebook/react" interface AuditLogProps { readonly resource: SharingResource; readonly pageSize?: number; } ``` ### `DirectoryEntry` [#directoryentry] ```ts api="@rolebook/react" interface DirectoryEntry { readonly subject: SubjectRef; readonly label: string; readonly detail?: string; } ``` ### `DirectorySearch` [#directorysearch] ```ts api="@rolebook/react" type DirectorySearch = (query: string, context: { readonly resource: SharingResource; readonly purpose: "invite" | "transfer"; readonly signal: AbortSignal; }) => Promise; ``` ### `SharingContextValue` [#sharingcontextvalue] ```ts api="@rolebook/react" interface SharingContextValue { readonly scope: SharingScope; readonly access: SharingAccessStore; readonly runner: SharingMutationRunner; readonly client: SharingKitClient; readonly offerWithoutHint: boolean; readonly searchDirectory: DirectorySearch | undefined; readonly describeSubject: (subject: SubjectRef) => string; readonly t: (key: SharingMessageKey, params?: SharingMessageParams) => string; readonly now: () => number; } ``` ### `SharingProvider` [#sharingprovider] ```ts api="@rolebook/react" function SharingProvider(props: SharingProviderProps): ReactNode; ``` ### `SharingProviderProps` [#sharingproviderprops] ```ts api="@rolebook/react" interface SharingProviderProps { readonly client: SharingKitClient; readonly scope: SharingScope; readonly actions?: SharingActionMap; readonly offerWithoutHint?: boolean; readonly intentStore?: IntentStore; readonly retryWindow?: RetryWindow; readonly retryCommands?: RetryCommandStore; readonly resolveOutcome?: OutcomeResolver; readonly acknowledgeDuplicateRisk?: DuplicateRiskAcknowledger; readonly onInvitationIssued?: InvitationIssuedCallback; readonly searchDirectory?: DirectorySearch; readonly describeSubject?: (subject: SubjectRef) => string; readonly messages?: Partial; readonly formatMessage?: SharingMessageFormatter; readonly freshForMs?: number; readonly now?: () => number; readonly newKey?: () => string; readonly children?: ReactNode; } ``` ### `useSharingContext` [#usesharingcontext] ```ts api="@rolebook/react" function useSharingContext(): SharingContextValue; ``` ### `SharingMutations` [#sharingmutations] ```ts api="@rolebook/react" interface SharingMutations { readonly busy: boolean; readonly outcome: SharingMutationOutcome | undefined; readonly unresolved: readonly UnresolvedIntent[]; readonly unresolvedError: SharingKitUnavailableCode | undefined; readonly capabilities: { readonly retry: boolean; readonly resolve: boolean; readonly release: boolean; }; submit(command: SharingKitCommand): Promise; retry(intentId: string, command?: SharingKitCommand): Promise; reconcile(intentId: string): Promise; abandon(intentId: string): Promise; release(intentId: string): Promise; refresh(): void; clearOutcome(): void; } ``` ### `useAuditLog` [#useauditlog] ```ts api="@rolebook/react" function useAuditLog(resourceInput: SharingResource, pageSize?: number): { readonly state: SharingAuditState; readonly loadMore: () => void; readonly reload: () => void; }; ``` ### `useOffered` [#useoffered] ```ts api="@rolebook/react" function useOffered(hint: SharingHint): boolean; ``` ### `useSharingAccess` [#usesharingaccess] ```ts api="@rolebook/react" function useSharingAccess(resourceInput: SharingResource): { readonly state: SharingAccessState; readonly reload: () => void; }; ``` ### `useSharingMessages` [#usesharingmessages] ```ts api="@rolebook/react" function useSharingMessages(): (key: import("../core.js").SharingMessageKey, params?: import("../core.js").SharingMessageParams) => string; ``` ### `useSharingMutations` [#usesharingmutations] ```ts api="@rolebook/react" function useSharingMutations(resourceInput: SharingResource): SharingMutations; ``` ### `IntentPanel` [#intentpanel] ```ts api="@rolebook/react" function IntentPanel({ mutations, onOutcome }: IntentPanelProps): ReactNode; ``` ### `IntentPanelProps` [#intentpanelprops] ```ts api="@rolebook/react" interface IntentPanelProps { readonly mutations: SharingMutations; readonly onOutcome: (outcome: SharingMutationOutcome) => void; } ``` ### `InviteMember` [#invitemember] ```ts api="@rolebook/react" function InviteMember(props: InviteMemberProps): ReactNode; ``` ### `InviteMemberProps` [#invitememberprops] ```ts api="@rolebook/react" interface InviteMemberProps { readonly resource: SharingResource; readonly roles: readonly RoleOption[]; readonly allowEmail?: boolean; readonly defaultExpiresInMs?: number; } ``` ### `MembersList` [#memberslist] ```ts api="@rolebook/react" function MembersList(props: MembersListProps): ReactNode; ``` ### `MembersListProps` [#memberslistprops] ```ts api="@rolebook/react" interface MembersListProps { readonly resource: SharingResource; readonly roles?: readonly RoleOption[]; readonly resourceLabel?: string; readonly allowExpiry?: boolean; } ``` ### `RoleOption` [#roleoption] ```ts api="@rolebook/react" interface RoleOption { readonly value: string; readonly label: string; } ``` ### `OwnershipTransfer` [#ownershiptransfer] ```ts api="@rolebook/react" function OwnershipTransfer(props: OwnershipTransferProps): ReactNode; ``` ### `OwnershipTransferProps` [#ownershiptransferprops] ```ts api="@rolebook/react" interface OwnershipTransferProps { readonly resource: SharingResource; readonly formerOwnerRoles?: readonly RoleOption[]; readonly subjectType?: string; } ``` ## Exports of `@rolebook/react/core` [#exports-of-rolebookreactcore] ### `ACCESS_LOADING` [#access_loading] ```ts api="@rolebook/react/core" const ACCESS_LOADING: SharingAccessState; ``` ### `createSharingAccessStore` [#createsharingaccessstore] ```ts api="@rolebook/react/core" function createSharingAccessStore(options: SharingAccessStoreOptions): SharingAccessStore; ``` ### `hintsFrom` [#hintsfrom] ```ts api="@rolebook/react/core" function hintsFrom(result: WireResourcePermissionsResult, actions: SharingActionMap, resource: SharingResource, sharingRevision: string): SharingActionHints; ``` ### `NO_HINTS` [#no_hints] ```ts api="@rolebook/react/core" const NO_HINTS: SharingActionHints; ``` ### `SharingAccessState` [#sharingaccessstate] ```ts api="@rolebook/react/core" type SharingAccessState = { readonly status: "loading"; } | { readonly status: "fresh"; readonly access: ClientAccessDescription; readonly hints: SharingActionHints; readonly readAt: number; } | { readonly status: "stale"; readonly access: ClientAccessDescription; readonly hints: SharingActionHints; readonly lastHints: SharingActionHints; readonly readAt: number; } | { readonly status: "denied"; } | { readonly status: "unavailable"; readonly code: string; }; ``` ### `SharingAccessStore` [#sharingaccessstore] ```ts api="@rolebook/react/core" interface SharingAccessStore { get(key: string): SharingAccessState; subscribe(key: string, listener: () => void): () => void; load(scope: SharingScope, resource: SharingResource, options?: { readonly force?: boolean; }): Promise; invalidate(scope: SharingScope, resource: SharingResource): Promise; retain(scope: SharingScope): void; clear(): void; } ``` ### `SharingAccessStoreOptions` [#sharingaccessstoreoptions] ```ts api="@rolebook/react/core" interface SharingAccessStoreOptions { readonly client: SharingKitClient; readonly actions: SharingActionMap; readonly freshForMs?: number; readonly now?: () => number; } ``` ### `SharingActionHints` [#sharingactionhints] ```ts api="@rolebook/react/core" interface SharingActionHints { readonly members: SharingHint; readonly invitations: SharingHint; readonly ownership: SharingHint; readonly audit: SharingHint; } ``` ### `SharingActionMap` [#sharingactionmap] ```ts api="@rolebook/react/core" interface SharingActionMap { readonly members?: string; readonly invitations?: string; readonly ownership?: string; readonly audit?: string; } ``` ### `SharingHint` [#sharinghint] ```ts api="@rolebook/react/core" type SharingHint = "allowed" | "not_allowed" | "no_hint"; ``` ### `AUDIT_LOADING` [#audit_loading] ```ts api="@rolebook/react/core" const AUDIT_LOADING: SharingAuditState; ``` ### `readAuditPage` [#readauditpage] ```ts api="@rolebook/react/core" function readAuditPage(client: SharingKitClient, resource: SharingResource, limit: number, previous: readonly ClientAuditEvent[], cursor?: string): Promise; ``` ### `SharingAuditState` [#sharingauditstate] ```ts api="@rolebook/react/core" type SharingAuditState = { readonly status: "loading"; } | { readonly status: "ready"; readonly events: readonly ClientAuditEvent[]; readonly nextCursor?: string; readonly loadingMore: boolean; } | { readonly status: "denied"; } | { readonly status: "unavailable"; readonly code: string; readonly events: readonly ClientAuditEvent[]; }; ``` ### `canonicalJson` [#canonicaljson] ```ts api="@rolebook/react/core" function canonicalJson(value: unknown): string; ``` ### `sha256Hex` [#sha256hex] ```ts api="@rolebook/react/core" function sha256Hex(text: string): Promise; ``` ### `errorCode` [#errorcode] ```ts api="@rolebook/react/core" function errorCode(error: unknown): string; ``` ### `provesNotApplied` [#provesnotapplied] ```ts api="@rolebook/react/core" function provesNotApplied(error: unknown): boolean; ``` ### `SharingKitClient` [#sharingkitclient] ```ts api="@rolebook/react/core" interface SharingKitClient { describeAccess(input: { readonly resource: SharingResource; }): Promise; permissions(input: { readonly resource: SharingResource; }): Promise; auditHistory(input: { readonly resource: SharingResource; readonly limit: number; readonly cursor?: string; }): Promise; execute(command: SharingCommand): Promise; } ``` ### `describeOutcome` [#describeoutcome] ```ts api="@rolebook/react/core" function describeOutcome(outcome: SharingMutationOutcome): OutcomeAnnouncement; ``` ### `OutcomeAnnouncement` [#outcomeannouncement] ```ts api="@rolebook/react/core" interface OutcomeAnnouncement { readonly tone: "status" | "alert"; readonly key: SharingMessageKey; } ``` ### `SharingCommandError` [#sharingcommanderror] ```ts api="@rolebook/react/core" class SharingCommandError extends TypeError { readonly code: "COMMAND_INVALID"; constructor(message: string); } ``` ### `SharingKitUnavailableCode` [#sharingkitunavailablecode] ```ts api="@rolebook/react/core" type SharingKitUnavailableCode = "CRYPTO_UNAVAILABLE" | "STORAGE_UNAVAILABLE" | "ATOMICITY_UNAVAILABLE" | "INVITATION_CALLBACK_MISSING" | "IDEMPOTENCY_KEY_INVALID"; ``` ### `SharingKitUnavailableError` [#sharingkitunavailableerror] ```ts api="@rolebook/react/core" class SharingKitUnavailableError extends Error { readonly code: SharingKitUnavailableCode; constructor(code: SharingKitUnavailableCode, message: string); } ``` ### `createBrowserIntentStore` [#createbrowserintentstore] ```ts api="@rolebook/react/core" function createBrowserIntentStore(prefix?: string): IntentStore; ``` ### `createMemoryIntentStore` [#creatememoryintentstore] ```ts api="@rolebook/react/core" function createMemoryIntentStore(): IntentStore; ``` ### `createWebStorageIntentStore` [#createwebstorageintentstore] ```ts api="@rolebook/react/core" function createWebStorageIntentStore(options: { readonly storage: IntentWebStorage | undefined; readonly locks: IntentLockManager | undefined; readonly prefix?: string; }): IntentStore; ``` ### `IntentLockManager` [#intentlockmanager] ```ts api="@rolebook/react/core" interface IntentLockManager { request(name: string, options: { readonly mode: "exclusive"; }, callback: () => Promise | T): Promise; } ``` ### `IntentStore` [#intentstore] ```ts api="@rolebook/react/core" interface IntentStore { readonly durability: "durable" | "memory"; update(id: string, change: (current: string | null) => string | null | undefined): Promise; read(id: string): Promise; entries(): Promise; } ``` ### `IntentWebStorage` [#intentwebstorage] ```ts api="@rolebook/react/core" interface IntentWebStorage { readonly length: number; key(index: number): string | null; getItem(key: string): string | null; setItem(key: string, value: string): void; removeItem(key: string): void; } ``` ### `BeginResult` [#beginresult] ```ts api="@rolebook/react/core" type BeginResult = { readonly admitted: true; readonly projected: ProjectedCommand; readonly record: IntentRecord; } | { readonly admitted: false; readonly projected: ProjectedCommand; readonly record: IntentRecord; }; ``` ### `createIntentRegistry` [#createintentregistry] ```ts api="@rolebook/react/core" function createIntentRegistry(options?: IntentRegistryOptions): IntentRegistry; ``` ### `IDEMPOTENCY_KEY_PATTERN` [#idempotency_key_pattern] ```ts api="@rolebook/react/core" const IDEMPOTENCY_KEY_PATTERN: RegExp; ``` ### `IntentRecord` [#intentrecord] ```ts api="@rolebook/react/core" interface IntentRecord { readonly intentId: string; readonly resourceDigest: string; readonly kind: SharingKitCommandKind; readonly idempotencyKey: string; readonly status: IntentStatus; readonly createdAt: number; readonly sentAt: number; readonly updatedAt: number; readonly retentionMs: number | null; readonly attempts: number; } ``` ### `IntentRegistry` [#intentregistry] ```ts api="@rolebook/react/core" interface IntentRegistry { readonly retryWindow: RetryWindow | undefined; begin(input: { readonly scope: SharingScope; readonly command: unknown; } | { readonly scope: SharingScope; readonly projected: ProjectedCommand; }): Promise; get(intentId: string): Promise; transition(intentId: string, idempotencyKey: string, change: (record: IntentRecord) => IntentRecord | null | undefined): Promise<{ readonly changed: boolean; readonly record: IntentRecord | undefined; }>; list(scope: SharingScope, resource: SharingResource): Promise; preserve(record: IntentRecord, at: number): Promise; } ``` ### `IntentRegistryOptions` [#intentregistryoptions] ```ts api="@rolebook/react/core" interface IntentRegistryOptions { readonly store?: IntentStore; readonly newKey?: () => string; readonly now?: () => number; readonly retryWindow?: RetryWindow; } ``` ### `IntentStatus` [#intentstatus] ```ts api="@rolebook/react/core" type IntentStatus = "pending" | "unknown" | "abandoned"; ``` ### `parseIntentRecord` [#parseintentrecord] ```ts api="@rolebook/react/core" function parseIntentRecord(intentId: string, text: string): IntentRecord | undefined; ``` ### `RetryBlockReason` [#retryblockreason] ```ts api="@rolebook/react/core" type RetryBlockReason = "RETRY_WINDOW_UNDECLARED" | "RETRY_WINDOW_EXPIRED" | "CLOCK_ROLLBACK"; ``` ### `retryBlock` [#retryblock] ```ts api="@rolebook/react/core" function retryBlock(record: IntentRecord, now: number, window: RetryWindow | undefined): RetryBlockReason | undefined; ``` ### `RetryWindow` [#retrywindow] ```ts api="@rolebook/react/core" interface RetryWindow { readonly serverRetentionMs: number; } ``` ### `createMessageFormatter` [#createmessageformatter] ```ts api="@rolebook/react/core" function createMessageFormatter(overrides?: Partial, format?: SharingMessageFormatter): SharingMessageFormatter; ``` ### `DEFAULT_MESSAGES` [#default_messages] ```ts api="@rolebook/react/core" const DEFAULT_MESSAGES: Readonly<{ "access.loading": "Loading access…"; "access.stale": "Showing the last known access while it is refreshed."; "access.denied": "This resource was not found, or you cannot view who has access."; "access.unavailable": "Access could not be loaded. Try again."; "access.retry": "Reload access"; "members.title": "People with access"; "members.caption": "Owner and members of {resource}"; "members.column.member": "Member"; "members.column.role": "Role"; "members.column.expires": "Access ends"; "members.column.actions": "Actions"; "members.owner": "Owner"; "members.never": "Never"; "members.empty": "No members besides the owner."; "members.roleFor": "Role for {member}"; "members.expiryFor": "Access end for {member}"; "members.clearExpiryFor": "Remove access end for {member}"; "members.save": "Save changes for {member}"; "members.revoke": "Remove {member}"; "members.revokeTitle": "Remove {member}?"; "members.revokeBody": "{member} loses access granted by this membership."; "members.invitations": "Pending invitations"; "members.invitationTo": "Invitation to {recipient} as {role}, expires {expires}"; "members.revokeInvitation": "Revoke invitation to {recipient}"; "members.noHint": "Permission could not be confirmed; the server will decide."; "invite.title": "Invite someone"; "invite.search": "Search people"; "invite.searchButton": "Search"; "invite.results": "Search results"; "invite.noResults": "No people found."; "invite.resultCount": "{count} people found."; "invite.recipientConflict": "Choose either a person or an email address, not both."; "invite.email": "Email address"; "invite.role": "Role"; "invite.expires": "Invitation expires"; "invite.membershipExpires": "Access ends (optional)"; "invite.submit": "Send invitation"; "invite.recipientRequired": "Choose a person or enter an email address."; "invite.expiryRequired": "Enter a valid invitation expiry."; "invite.membershipExpiryInvalid": "Enter a valid access end, or leave it empty."; "invite.sent": "Invitation created."; "invite.copyLink": "Copy invitation link"; "invite.copied": "Invitation link copied. It cannot be shown again."; "invite.copyFailed": "The link could not be copied. Revoke this invitation and send a new one."; "invite.deliveryFailed": "The invitation was created, but its link could not be delivered. Revoke it and send a new one."; "invite.tokenLost": "The invitation exists, but its link was only available to the first response and cannot be shown. Revoke it from pending invitations and send a new one."; "transfer.title": "Transfer ownership"; "transfer.search": "Search for the new owner"; "transfer.subjectId": "New owner's user ID"; "transfer.formerRole": "Your role after the transfer"; "transfer.formerRoleNone": "No role (lose access)"; "transfer.submit": "Transfer ownership"; "transfer.confirmTitle": "Transfer ownership to {member}?"; "transfer.confirmBody": "Only the new owner can transfer it back."; "transfer.recipientRequired": "Choose the new owner."; "transfer.done": "Ownership transferred."; "audit.title": "Activity"; "audit.empty": "No activity yet."; "audit.loadMore": "Load older activity"; "audit.loading": "Loading activity…"; "audit.denied": "You cannot view this resource's activity."; "audit.unavailable": "Activity could not be loaded."; "audit.event": "{actor} {action}{subject}"; "audit.subject": " {subject}"; "audit.action.member.granted": "granted access to"; "audit.action.member.role_changed": "changed the role of"; "audit.action.member.revoked": "removed"; "audit.action.ownership.transferred": "transferred ownership to"; "audit.action.invitation.issued": "invited"; "audit.action.invitation.consumed": "accepted an invitation"; "audit.action.invitation.revoked": "revoked an invitation"; "audit.action.resource.initialized": "created the resource"; "audit.action.resource.deleted": "deleted the resource"; "audit.action.resource.moved": "moved the resource"; "audit.action.unknown": "made a change"; "dialog.confirm": "Confirm"; "dialog.cancel": "Cancel"; "outcome.applied": "Done."; "outcome.alreadyApplied": "This change had already been applied."; "outcome.resolvedApplied": "Confirmed: the change was applied."; "outcome.notApplied": "The change was not applied."; "outcome.unknown": "We could not confirm whether the change was applied. It will not be sent again automatically."; "outcome.retryRefused": "The retry was refused. That does not show whether the original change was applied."; "outcome.pending": "Sending…"; "outcome.recordRetained": "The change was applied, but this browser could not record that. Check its status before repeating it."; "outcome.abandoned": "Stopped waiting. The same change stays blocked until it is resolved."; "outcome.released": "Released. The same change can be sent again."; "intent.title": "Changes waiting for confirmation"; "intent.item": "{kind} — {status}, first sent {sentAt}"; "intent.status.pending": "sending or unconfirmed"; "intent.status.unknown": "outcome unknown"; "intent.status.abandoned": "stopped waiting, unresolved"; "intent.retry": "Retry {kind}"; "intent.reconcile": "Check status of {kind}"; "intent.abandon": "Stop waiting for {kind}"; "intent.release": "Allow sending {kind} again"; "intent.abandonTitle": "Stop waiting for this change?"; "intent.abandonBody": "It may already have been applied. It stays recorded and blocks the identical change until its status is checked or you allow it explicitly."; "intent.kind.grantRole": "Grant access"; "intent.kind.changeRole": "Change role"; "intent.kind.revokeMember": "Remove member"; "intent.kind.transferOwnership": "Transfer ownership"; "intent.kind.issueInvitation": "Invitation"; "intent.kind.revokeInvitation": "Revoke invitation"; "blocked.UNRESOLVED_INTENT": "An identical change is still unconfirmed. Retry it or check its status below instead of sending it again."; "blocked.IN_FLIGHT": "This change is already being sent."; "blocked.STORAGE_FAULT": "This browser's storage could not record an earlier change's status, so nothing more is sent from this page until it can, or that change's status is checked."; "outcome.storageFault": "The outcome of this change is unknown, and this browser's storage could not record that. Nothing more is sent from this page until it can; check the change's status before repeating it."; "intent.storageFault": "not recorded in this browser's storage"; "blocked.ABANDONED_NEEDS_RESOLUTION": "An identical change was abandoned without confirmation. Check its status before sending it again."; "blocked.RETRY_WINDOW_UNDECLARED": "Retrying is not enabled for this application."; "blocked.RETRY_WINDOW_EXPIRED": "This change is too old to retry safely. Check its status instead."; "blocked.CLOCK_ROLLBACK": "The device clock moved backwards. Retrying is blocked."; "blocked.RETRY_COMMAND_UNAVAILABLE": "The original change is not available to retry. Submit the identical change again to retry it."; "blocked.COMMAND_MISMATCH": "That is not the same change."; "blocked.RESOURCE_UNAVAILABLE": "The resource can no longer be reached, so the change is not retried."; "blocked.NOT_FOUND": "That change is no longer recorded."; "blocked.RESOLVER_MISSING": "Status checks are not available in this application."; "blocked.ACKNOWLEDGEMENT_REQUIRED": "Sending this change again was not acknowledged."; "unavailable.CRYPTO_UNAVAILABLE": "This browser cannot make changes safely (no Web Crypto)."; "unavailable.STORAGE_UNAVAILABLE": "Changes are unavailable: this browser's storage cannot be used."; "unavailable.ATOMICITY_UNAVAILABLE": "Changes are unavailable: this browser cannot coordinate them between tabs."; "unavailable.INVITATION_CALLBACK_MISSING": "Invitations are not set up in this application."; "unavailable.IDEMPOTENCY_KEY_INVALID": "Changes are unavailable: invalid request key."; "invalid.COMMAND_INVALID": "Some values are not valid."; "error.generic": "Something went wrong."; "error.NOT_FOUND_OR_DENIED": "The resource was not found, or you are not allowed to do that."; "error.FORBIDDEN": "You are not allowed to do that."; "error.NOT_TENANT_MEMBER": "That person is not a member of this workspace."; "error.ROLE_NOT_ALLOWED": "That role cannot be given here."; "error.SELF_PROMOTION": "You cannot change your own access."; "error.OWNER_TRANSFER_REQUIRED": "The owner's access can only change through an ownership transfer."; "error.GROUP_CANNOT_OWN": "A group cannot own a resource."; "error.MEMBER_ALREADY_EXISTS": "That person already has access."; "error.INVITATION_EXPIRED": "The invitation expiry must be in the future."; "error.INVITATION_RECIPIENT_INVALID": "That recipient is not valid."; "error.INVITATION_UNAVAILABLE": "That invitation is no longer available."; "error.INVITATION_RECIPIENT_MISMATCH": "That invitation is for someone else."; "error.MEMBERSHIP_EXPIRY_INVALID": "The access end date is not valid."; "error.CONFLICT": "Something changed at the same time. Reload and try again."; "error.POLICY_GENERATION_CHANGED": "Access rules changed. Reload and try again."; "error.TENANT_ROLES_CHANGED": "Roles changed. Reload and try again."; "error.POLICY_UNAVAILABLE": "Access rules are temporarily unavailable."; "error.UNAUTHENTICATED": "Your session has ended. Sign in again."; "error.CSRF": "The request was rejected. Reload the page."; "error.INVALID_REQUEST": "The request was not valid."; "error.TIMEOUT": "The server did not answer in time."; "error.NETWORK": "The server could not be reached."; "error.UNEXPECTED_RESPONSE": "The server sent an unexpected answer."; "error.INTERNAL": "The server had a problem."; }>; ``` ### `failureMessageKey` [#failuremessagekey] ```ts api="@rolebook/react/core" function failureMessageKey(code: string): SharingMessageKey; ``` ### `interpolate` [#interpolate] ```ts api="@rolebook/react/core" function interpolate(template: string, params: SharingMessageParams): string; ``` ### `SharingMessageFormatter` [#sharingmessageformatter] ```ts api="@rolebook/react/core" type SharingMessageFormatter = (key: SharingMessageKey, params: SharingMessageParams) => string; ``` ### `SharingMessageKey` [#sharingmessagekey] ```ts api="@rolebook/react/core" type SharingMessageKey = keyof typeof DEFAULT_MESSAGES; ``` ### `SharingMessageParams` [#sharingmessageparams] ```ts api="@rolebook/react/core" type SharingMessageParams = Readonly>; ``` ### `SharingMessages` [#sharingmessages] ```ts api="@rolebook/react/core" type SharingMessages = { readonly [K in SharingMessageKey]: string; }; ``` ### `createSharingMutationRunner` [#createsharingmutationrunner] ```ts api="@rolebook/react/core" function createSharingMutationRunner(options: SharingMutationRunnerOptions): SharingMutationRunner; ``` ### `DuplicateRiskAcknowledger` [#duplicateriskacknowledger] ```ts api="@rolebook/react/core" type DuplicateRiskAcknowledger = (intent: { readonly intentId: string; readonly kind: SharingKitCommandKind; readonly createdAt: number; readonly sentAt: number; }) => boolean | Promise; ``` ### `InvitationHandoff` [#invitationhandoff] ```ts api="@rolebook/react/core" interface InvitationHandoff { readonly copyLink?: () => void | Promise; } ``` ### `InvitationIssuedCallback` [#invitationissuedcallback] ```ts api="@rolebook/react/core" type InvitationIssuedCallback = (invitation: IssuedInvitation) => InvitationHandoff | undefined | Promise; ``` ### `InvitationOutcome` [#invitationoutcome] ```ts api="@rolebook/react/core" type InvitationOutcome = { readonly delivery: "delivered"; readonly invitationId: string; } | { readonly delivery: "copy_available"; readonly invitationId: string; readonly copyLink: () => Promise; } | { readonly delivery: "failed"; readonly invitationId: string; } | { readonly delivery: "token_lost"; }; ``` ### `IssuedInvitation` [#issuedinvitation] ```ts api="@rolebook/react/core" interface IssuedInvitation { readonly resource: SharingResource; readonly invitationId: string; readonly token: string; } ``` ### `MutationBlockReason` [#mutationblockreason] ```ts api="@rolebook/react/core" type MutationBlockReason = RetryBlockReason | "UNRESOLVED_INTENT" | "IN_FLIGHT" | "ABANDONED_NEEDS_RESOLUTION" | "RETRY_COMMAND_UNAVAILABLE" | "COMMAND_MISMATCH" | "RESOURCE_UNAVAILABLE" | "NOT_FOUND" | "RESOLVER_MISSING" | "STORAGE_FAULT" | "ACKNOWLEDGEMENT_REQUIRED"; ``` ### `OutcomeResolution` [#outcomeresolution] ```ts api="@rolebook/react/core" type OutcomeResolution = "applied" | "not_applied" | "unknown"; ``` ### `OutcomeResolver` [#outcomeresolver] ```ts api="@rolebook/react/core" type OutcomeResolver = (query: { readonly intentId: string; readonly idempotencyKey: string; readonly kind: SharingKitCommandKind; readonly createdAt: number; readonly sentAt: number; }) => OutcomeResolution | Promise; ``` ### `RetryCommandStore` [#retrycommandstore] ```ts api="@rolebook/react/core" interface RetryCommandStore { save(intentId: string, command: ProjectedCommand): void | Promise; load(intentId: string): unknown; delete(intentId: string): void | Promise; } ``` ### `SharingMutationOutcome` [#sharingmutationoutcome] ```ts api="@rolebook/react/core" type SharingMutationOutcome = { readonly status: "applied"; readonly kind: SharingKitCommandKind; readonly intentId: string; readonly code: "APPLIED" | "ALREADY_APPLIED" | "RESOLVED_APPLIED"; readonly sharingRevision?: string; readonly invitation?: InvitationOutcome; readonly recordRetained?: true; } | { readonly status: "not_applied"; readonly kind: SharingKitCommandKind; readonly intentId: string; readonly code: string; } | { readonly status: "unknown"; readonly kind: SharingKitCommandKind; readonly intentId: string; readonly code: string; readonly retryRefusedCode?: string; readonly concurrentAttempt?: true; readonly settlementFailed?: true; } | { readonly status: "blocked"; readonly reason: MutationBlockReason; readonly kind?: SharingKitCommandKind; readonly intentId?: string; readonly intentStatus?: IntentStatus; } | { readonly status: "storage_fault"; readonly kind: SharingKitCommandKind; readonly intentId: string; readonly code: string; } | { readonly status: "abandoned"; readonly kind: SharingKitCommandKind; readonly intentId: string; } | { readonly status: "released"; readonly kind: SharingKitCommandKind; readonly intentId: string; } | { readonly status: "unavailable"; readonly code: SharingKitUnavailableCode; readonly kind?: SharingKitCommandKind; } | { readonly status: "invalid"; readonly code: "COMMAND_INVALID"; }; ``` ### `SharingMutationRunner` [#sharingmutationrunner] ```ts api="@rolebook/react/core" interface SharingMutationRunner { submit(scope: SharingScope, command: unknown): Promise; retry(scope: SharingScope, resource: SharingResource, intentId: string, options?: { readonly command?: unknown; }): Promise; reconcile(scope: SharingScope, resource: SharingResource, intentId: string): Promise; abandon(scope: SharingScope, resource: SharingResource, intentId: string): Promise; release(scope: SharingScope, resource: SharingResource, intentId: string): Promise; unresolved(scope: SharingScope, resource: SharingResource): Promise; readonly capabilities: { readonly retry: boolean; readonly resolve: boolean; readonly release: boolean; }; } ``` ### `SharingMutationRunnerOptions` [#sharingmutationrunneroptions] ```ts api="@rolebook/react/core" interface SharingMutationRunnerOptions { readonly client: SharingKitClient; readonly registry: IntentRegistry; readonly onInvitationIssued?: InvitationIssuedCallback; readonly resolveOutcome?: OutcomeResolver; readonly retryCommands?: RetryCommandStore; readonly acknowledgeDuplicateRisk?: DuplicateRiskAcknowledger; readonly onChanged?: (scope: SharingScope, resource: SharingResource) => void; readonly now?: () => number; } ``` ### `UnresolvedIntent` [#unresolvedintent] ```ts api="@rolebook/react/core" interface UnresolvedIntent { readonly intentId: string; readonly kind: SharingKitCommandKind; readonly status: IntentStatus; readonly createdAt: number; readonly sentAt: number; readonly attempts: number; readonly inFlight: boolean; readonly storageFault?: true; readonly retryBlocked?: RetryBlockReason | "IN_FLIGHT" | "ABANDONED_NEEDS_RESOLUTION"; } ``` ### `commandFromProjection` [#commandfromprojection] ```ts api="@rolebook/react/core" function commandFromProjection(projected: ProjectedCommand, idempotencyKey: string): AnyCommand; ``` ### `IntentIdentity` [#intentidentity] ```ts api="@rolebook/react/core" interface IntentIdentity { readonly intentId: string; readonly resourceDigest: string; } ``` ### `intentIdentity` [#intentidentity-1] ```ts api="@rolebook/react/core" function intentIdentity(scope: SharingScope, projected: ProjectedCommand): Promise; ``` ### `MAX_INVITATION_EMAIL_LENGTH` [#max_invitation_email_length] ```ts api="@rolebook/react/core" const MAX_INVITATION_EMAIL_LENGTH = 320; ``` ### `MAX_OPAQUE_ID_LENGTH` [#max_opaque_id_length] ```ts api="@rolebook/react/core" const MAX_OPAQUE_ID_LENGTH = 128; ``` ### `ProjectedCommand` [#projectedcommand] ```ts api="@rolebook/react/core" type ProjectedCommand = { readonly kind: "grantRole"; readonly resource: SharingResource; readonly subject: SubjectRef; readonly role: string; readonly expiresAt?: number; } | { readonly kind: "changeRole"; readonly resource: SharingResource; readonly subject: SubjectRef; readonly role: string; readonly expiresAt?: number | null; } | { readonly kind: "revokeMember"; readonly resource: SharingResource; readonly subject: SubjectRef; } | { readonly kind: "transferOwnership"; readonly resource: SharingResource; readonly to: SubjectRef; readonly formerOwnerRole: string | null; } | { readonly kind: "issueInvitation"; readonly resource: SharingResource; readonly recipient: { readonly type: "subject"; readonly subject: SubjectRef; } | { readonly type: "email"; readonly email: string; }; readonly role: string; readonly expiresAt: number; readonly membershipExpiresAt?: number; } | { readonly kind: "revokeInvitation"; readonly resource: SharingResource; readonly invitationId: string; }; ``` ### `projectCommand` [#projectcommand] ```ts api="@rolebook/react/core" function projectCommand(command: unknown): ProjectedCommand; ``` ### `SharingKitCommand` [#sharingkitcommand] ```ts api="@rolebook/react/core" type SharingKitCommand = WithoutKey>; ``` ### `SharingKitCommandKind` [#sharingkitcommandkind] ```ts api="@rolebook/react/core" type SharingKitCommandKind = SharingKitCommand["kind"]; ``` ### `baseScopeKey` [#basescopekey] ```ts api="@rolebook/react/core" function baseScopeKey(scope: SharingScope): string; ``` ### `normalizeScope` [#normalizescope] ```ts api="@rolebook/react/core" function normalizeScope(scope: SharingScope): SharingScope; ``` ### `scopeKey` [#scopekey] ```ts api="@rolebook/react/core" function scopeKey(scope: SharingScope, resource: SharingResource): string; ``` ### `SharingResource` [#sharingresource] ```ts api="@rolebook/react/core" interface SharingResource { readonly type: string; readonly id: string; } ``` ### `SharingScope` [#sharingscope] ```ts api="@rolebook/react/core" interface SharingScope { readonly actor: string; readonly tenant: string; readonly policy: string; readonly context?: string; } ``` ### `SubjectRef` [#subjectref] ```ts api="@rolebook/react/core" interface SubjectRef { readonly type: string; readonly id: string; } ``` # ACL recipe (/docs/recipes/acl) > Scoped roles, explicit deny, revocation, and resource membership commands. An access-control list in Rolebook is a scoped role assignment. This recipe uses one tenant, its projects, and its documents. Alice administers tenant A. Bob can read one document. Carol is a tenant member with no assignment. A second assignment can deny Bob, and removing Bob's own assignment does not revoke a grant he still holds through a team. The runnable program is `examples/acl.ts` in a checkout of this repository: ```sh bun examples/acl.ts ``` Examples are not part of the npm package. Load assignments and ancestry from server-owned records. The objects below are an in-memory stand-in for that store, so the example can run without a database. ## One policy [#one-policy] Roles are defined once. `tenant_admin` names `document:read` and `document:update`. It is an ordinary role: there is no bypass role, and a wildcard such as `tenant:*` grants only `tenant` actions. It does not grant operations on projects or documents. ```ts import { createAuthorizer, definePolicy, trustedResource } from "rolebook"; const policy = definePolicy({ version: "acl-recipe", resources: { tenant: { actions: ["read"] }, project: { parent: "tenant", actions: ["read"] }, document: { parent: "project", actions: ["read", "update"] }, }, roles: { tenant_admin: { scope: "tenant", rules: [ { effect: "allow", permission: "document:read" }, { effect: "allow", permission: "document:update" }, ], }, document_reader: { scope: "document", rules: [{ effect: "allow", permission: "document:read" }], }, document_read_denied: { scope: "document", rules: [{ effect: "deny", permission: "document:read" }], }, }, }); const authorizer = createAuthorizer(policy); const documentA1 = trustedResource({ type: "document", id: "doc_a1" }, [ { type: "project", id: "project_a" }, { type: "tenant", id: "tenant_a" }, ]); const documentB1 = trustedResource({ type: "document", id: "doc_b1" }, [ { type: "project", id: "project_b" }, { type: "tenant", id: "tenant_b" }, ]); const alice = authorizer.bind({ subject: { type: "user", id: "alice" }, assignments: [ { subject: { type: "user", id: "alice" }, role: "tenant_admin", scope: { resource: { type: "tenant", id: "tenant_a" }, appliesTo: "descendants" }, }, ], }); alice.check({ permission: "document:read", resource: documentA1 }).allowed; // true alice.check({ permission: "document:read", resource: documentB1 }).allowed; // false ``` Build `trustedResource` from the row your server loaded for `(tenantId, documentId)`. The ancestor list is the complete chain from the immediate parent to the root. An id in the URL selects which row to load. It does not prove that the caller owns that row, and it does not prove the parent ids. | Principal | Assignment | Result | | --- | --- | --- | | Alice | `tenant_admin` on tenant A, `descendants` | Document read and update in A. No rights in B. | | Bob | `document_reader` on document A1, `self` | Read A1. Cannot update A1, read A2, or read B1. | | Carol | Tenant member, `assignments: []` | No document access. Membership is not a role. | | Bob, plus a deny | `document_read_denied` on A1 for `document:read` | The deny wins. | `appliesTo: "descendants"` includes the scope resource itself and everything below it in the ancestry you supplied. `appliesTo: "self"` is only that resource. ## Revocation is a new binding [#revocation-is-a-new-binding] `bind` keeps its own snapshot of the assignments. Changing or deleting the caller's array does not change an authorizer you already hold. The next request builds a new binding from the store after the deletion. A team assignment is a second source. Removing Bob's direct row leaves the team's `document_reader` grant in place, so Bob can still read A1 while he remains a member of that team. Revoking one grant is not a promise that every grant is gone. ## Sharing commands [#sharing-commands] For a real membership store, `@rolebook/sharing` keeps one live membership per subject and resource. `grantRole` sets that membership's role. Granting again does not add a second permission; `changeRole` replaces the role, and `revokeMember` removes the membership. The membership label, such as `reader`, is not the policy role it maps to, such as `document_reader`. The role applies to that resource itself. Only an eligible tenant member can be granted, and only an actor who may manage members can grant. A manager who is not the owner can hand out only access they hold. See [setup](/docs/sharing/setup), [commands](/docs/sharing/commands), and [delegation](/docs/sharing/delegation). This recipe does not start a second sharing application. ```ts import { definePolicy } from "rolebook"; import { createHmacInvitationTokens, createSharing, defineSharing, generateInvitationTokenKey, type SharingAdapter, type TenantIdentityAdapter, } from "@rolebook/sharing"; const sharingPolicy = definePolicy({ resources: { document: { actions: ["read", "update", "manage_members", "manage_invitations", "transfer_ownership"], }, }, roles: { document_owner: { scope: "document", rules: [{ effect: "allow", permission: "document:*" }], }, document_reader: { scope: "document", rules: [{ effect: "allow", permission: "document:read" }], }, document_manager: { scope: "document", rules: [ { effect: "allow", permission: "document:manage_members" }, { effect: "allow", permission: "document:manage_invitations" }, { effect: "allow", permission: "document:read" }, ], }, }, }); declare const documents: SharingAdapter; declare const identity: TenantIdentityAdapter; const sharing = createSharing({ definition: defineSharing({ policy: sharingPolicy, resources: { document: { memberRoles: { reader: "document_reader", manager: "document_manager" }, ownershipRole: "document_owner", actions: { read: "document:read", update: "document:update" }, management: { members: "document:manage_members", invitations: "document:manage_invitations", ownership: "document:transfer_ownership", }, adapter: documents, }, }, }), identity, invitationTokens: createHmacInvitationTokens(generateInvitationTokenKey()), }); const tenant = sharing.forTenant({ tenantId: "tenant_a", actor: { type: "user", id: "alice" }, }); await tenant.execute({ kind: "grantRole", resource: { type: "document", id: "doc_a1" }, subject: { type: "user", id: "bob" }, role: "reader", idempotencyKey: "grant-bob-doc_a1", }); await tenant.execute({ kind: "changeRole", resource: { type: "document", id: "doc_a1" }, subject: { type: "user", id: "bob" }, role: "manager", idempotencyKey: "change-bob-doc_a1", }); await tenant.execute({ kind: "revokeMember", resource: { type: "document", id: "doc_a1" }, subject: { type: "user", id: "bob" }, idempotencyKey: "revoke-bob-doc_a1", }); ``` ## Read next [#read-next] Bindings, principals, and why the whole assignment list is validated. The same documents, behind two Hono routes. # HTTP authorization (/docs/recipes/http-authorization) > Protect application routes with the Hono adapter without revealing whether a document exists. This recipe guards your application's own document routes. It is not the [Sharing HTTP API](/docs/http-api). The adapter is the one documented on the [Hono](/docs/hono) page. The runnable program is `examples/http-hono.ts`: ```sh bun examples/http-hono.ts ``` It reuses the [ACL recipe](/docs/recipes/acl) names: tenant A, documents, `tenant_admin`, and `document_reader`. Examples are not published in the npm package. | Route | Permission | | --- | --- | | `GET /api/tenants/:tenantId/documents/:id` | `document:read` | | `PATCH /api/tenants/:tenantId/documents/:id` | `document:update` | Those are ordinary Hono routes. Nothing new dispatches on the permission. ## Request order [#request-order] 1. Read the authenticated subject from the server session. No session returns 401 and does not load a document. `getBinding` returns `undefined` only for that case. 2. In `getBinding`, decide whether that subject is a member of the tenant in the path, and load that tenant's assignments. A member with no assignments still gets a binding, with `assignments: []`. A member of a different tenant throws the same 404 used for a missing document, before the document lookup. An unexpected eligibility failure is left to the server error handler. 3. Load the document by `(tenantId, documentId)`. Ancestry and facts come from that row. The path selects the lookup. It does not attest ownership. 4. Keep that row for both the check and the handler. A write still has to re-check its version inside the application's transaction. The snapshot is not a lock. 5. Install `app.onError(middleware.onError)`. Leave `reuseBindingPerRequest` off: the binding depends on the tenant in the path. The adapter's default denial is 403. This recipe sets `onForbidden` so a denial, a missing document, a document in another tenant, and an ineligible tenant all return the same plain-text 404. That hides existence in the status and body. It does not make response timing identical. Keep authorization traces on the server. Do not add a header or cookie that varies by which of those cases it was. ```ts import { Hono } from "hono"; import { HTTPException } from "hono/http-exception"; import { definePolicy, trustedResource, type RoleAssignment } from "rolebook"; import { createRolebookMiddleware, type RolebookEnv } from "rolebook/middleware/hono"; const policy = definePolicy({ resources: { tenant: { actions: ["read"] }, project: { parent: "tenant", actions: ["read"] }, document: { parent: "project", actions: ["read", "update"] }, }, roles: { tenant_admin: { scope: "tenant", rules: [ { effect: "allow", permission: "document:read" }, { effect: "allow", permission: "document:update" }, ], }, document_reader: { scope: "document", rules: [{ effect: "allow", permission: "document:read" }], }, }, }); const records = [ { tenantId: "tenant_a", projectId: "project_a", id: "doc_a1", title: "Plan A1" }, ] as const; function unavailableResponse(): Response { return new Response("Not Found", { status: 404, headers: { "content-type": "text/plain; charset=UTF-8" }, }); } function unavailable(): HTTPException { return new HTTPException(404, { res: unavailableResponse() }); } function subjectFor(session: string) { if (session === "alice") return { type: "user" as const, id: "alice" }; if (session === "bob") return { type: "user" as const, id: "bob" }; if (session === "carol") return { type: "user" as const, id: "carol" }; return undefined; } const members = new Map>([["tenant_a", new Set(["alice", "bob", "carol"])]]); function assignmentsFor( subjectId: string, tenantId: string, ): readonly RoleAssignment<"tenant_admin" | "document_reader">[] { // Only the assignments stored for this tenant. Another tenant's grants never reach the binding. if (tenantId !== "tenant_a") return []; if (subjectId === "alice") { return [ { subject: { type: "user", id: "alice" }, role: "tenant_admin", scope: { resource: { type: "tenant", id: "tenant_a" }, appliesTo: "descendants" }, }, ]; } if (subjectId === "bob") { return [ { subject: { type: "user", id: "bob" }, role: "document_reader", scope: { resource: { type: "document", id: "doc_a1" }, appliesTo: "self" }, }, ]; } return []; } function loadDocument(tenantId: string, documentId: string) { return records.find((record) => record.tenantId === tenantId && record.id === documentId); } type AppEnv = { Variables: RolebookEnv["Variables"] & { document: (typeof records)[number] }; }; const app = new Hono(); const middleware = createRolebookMiddleware({ policy, onForbidden: () => unavailableResponse(), getBinding: (context) => { const session = context.req.raw.headers.get("session"); if (session === null) return undefined; const subject = subjectFor(session); if (subject === undefined) return undefined; const tenantId = context.req.param("tenantId"); if (tenantId === undefined || !members.get(tenantId)?.has(subject.id)) throw unavailable(); return { subject, assignments: assignmentsFor(subject.id, tenantId) }; }, }); app.onError(middleware.onError); app.get("/health", (context) => context.text("ok")); function openDocument(tenantId: string | undefined, documentId: string | undefined) { if (tenantId === undefined || documentId === undefined) throw unavailable(); const record = loadDocument(tenantId, documentId); if (record === undefined) throw unavailable(); return record; } function trustedDocument(record: (typeof records)[number]) { return trustedResource({ type: "document", id: record.id }, [ { type: "project", id: record.projectId }, { type: "tenant", id: record.tenantId }, ]); } app.get( "/api/tenants/:tenantId/documents/:id", middleware.requirePermission((context) => { const record = openDocument(context.req.param("tenantId"), context.req.param("id")); context.set("document", record); return { permission: "document:read", resource: trustedDocument(record) }; }), (context) => context.json({ id: context.get("document").id, title: context.get("document").title }), ); app.patch( "/api/tenants/:tenantId/documents/:id", middleware.requirePermission((context) => { const record = openDocument(context.req.param("tenantId"), context.req.param("id")); context.set("document", record); return { permission: "document:update", resource: trustedDocument(record) }; }), (context) => context.json({ id: context.get("document").id, updated: true }), ); ``` Hono 4 serves `HEAD` with the `GET` route and strips the body. The request method stays `HEAD`. Prefer mapping the permission on the route. This sample has no CORS middleware and no `OPTIONS` handler, so a preflight or an unsupported method is the framework's ordinary 404. Configuring CORS does not authorize the request that follows. `GET /health` is public because it does not use the middleware. ## Path and method conditions [#path-and-method-conditions] The application above has no pathname or method conditions. A separate policy can require them on every `document:read` and `document:update` allow. Read `context.path` from `c.req.path` and `context.method` from `c.req.method`. Do not parse another copy of the URL, and do not copy either fact from a client header or body. A query string is not part of `c.req.path`. Each read allow requires `context.path` to start with `/api/tenants/` and `context.method` to be `GET` or `HEAD`. Each update allow requires the same prefix and `context.method` equal to `PATCH`. Use those explicit permissions so a wildcard cannot skip the condition. The strings do not match path parameters and do not establish the tenant. A binding that omits either fact cannot match the allow. The main application is unchanged. ## Read next [#read-next] Binding reuse, errors, and the default 403. The roles these routes check. # Roles and scopes (/docs/roles-and-scopes) > Where a role lives, what its rules may target, and how inheritance works. A role is a named set of rules that lives at one **scope**: a resource type such as `organization`, `workspace`, or `project`. A role only ever takes effect through an [assignment](/docs/subjects-and-assignments) of that role on a concrete resource of its scope type. ```ts import { definePolicy } from "rolebook"; const policy = definePolicy({ resources: { organization: { actions: ["read"] }, workspace: { parent: "organization", actions: ["read", "update"] }, project: { parent: "workspace", actions: ["read", "update", "delete"] }, }, roles: { workspace_editor: { scope: "workspace", rules: [ { effect: "allow", permission: "workspace:read" }, { effect: "allow", permission: "project:read" }, { effect: "allow", permission: "project:update" }, ], }, workspace_admin: { scope: "workspace", inherits: ["workspace_editor"], rules: [ { effect: "allow", permission: "workspace:update" }, { effect: "allow", permission: "project:delete" }, ], }, }, }); ``` A role definition accepts exactly `scope`, `rules`, and an optional `inherits`. `scope` must name a declared resource type. A role may have up to 256 direct rules, and the whole policy up to 4,096. ## What a role's rules may target [#what-a-roles-rules-may-target] A role's rules may target its scope type or any type below it in the declared parent chain. They may not target an ancestor or an unrelated type, because such a rule could never apply: an assignment on a workspace never covers its organization. - A `workspace` role can grant `workspace:update` and `project:delete`. - A `workspace` role cannot grant `organization:read`. `definePolicy()` throws `Invalid Rolebook policy: rule permission is outside the role scope`. ## Inheritance [#inheritance] `inherits` lists other roles at the **same scope**. A role inherits their complete rules, allows and denies alike, transitively. In the example, `workspace_admin` can read, update, and delete projects and update the workspace. Inheritance rules: - Every inherited role must exist and must have the same `scope`. - `inherits` may not repeat a role, and inheritance may not form a cycle. - A role's effective rule set (its own plus every inherited rule) is at most 4,096 rules, and the sum over all roles at most 16,384. Decisions attribute a matched rule to the role that **defines** it. When `workspace_admin` is allowed `project:update`, `decision.matched.role` is `"workspace_editor"`, because that rule comes from the inherited role. The assignment itself still names `workspace_admin`. ## Assignment scope: `self` or `descendants` [#assignment-scope-self-or-descendants] An assignment places a role on one resource and says how far it reaches: | `appliesTo` | Covers | | --- | --- | | `"self"` | Only the named scope resource. | | `"descendants"` | The named resource itself **and** every resource below it in the checked resource's ancestry. | Scope is inclusive: a `descendants` assignment on `ws_456` applies to the workspace `ws_456` and to every project whose trusted ancestry contains `ws_456`. A `self` assignment on `ws_456` never applies to its projects. The assignment's scope resource type must equal the role's `scope`. Assigning `workspace_editor` on a project denies the whole binding with `INVALID_ASSIGNMENT`. ## No bypass, no implication [#no-bypass-no-implication] There is no role that bypasses evaluation, and no action implies another. An organization owner who should be able to read every project needs an organization-scoped role with an explicit `project:read` rule and a `descendants` assignment. Deny rules still apply to such a role: see [deny precedence](/docs/evaluation#deny-precedence). ## Designing roles [#designing-roles] - Put a role at the narrowest scope that matches how it is granted. A role granted per project belongs at `project`; a role granted per workspace belongs at `workspace` and reaches projects through `descendants`. - Prefer composition with `inherits` over copying rules, so that a change to a base role reaches every role built on it. - Use deny rules for invariants that must hold whatever else a subject holds, such as "suspended users cannot write", and keep them conditional on authoritative facts. - For tenant-defined roles, see [custom roles](/docs/sharing/versioned#custom-roles) in the sharing package: tenant labels bounded by a static template role. # The P1 input profile (/docs/scalars-p1) > @rolebook/scalars-p1: bounded raw JSON admission shared by the decision service and offline snapshots. `@rolebook/scalars-p1` reads JSON bytes under the versioned `rolebook/scalars-p1/v1` profile. The decision service and offline snapshot package use the same parser and conformance fixtures. The parser returns an admitted value or a typed boundary error; it makes no permission decision. You rarely call it yourself: the [decision service](/docs/decision-service) and [offline snapshots](/docs/offline) depend on it and apply it to every request body, policy, authority document, bundle and lease. Read this page when you write an authority provider or an issuer that produces P1 bytes, or when you implement the same boundary elsewhere. [Choose how decisions run](/docs/choosing) shows where the profile sits. ## Parse bytes [#parse-bytes] > **Not on npm yet.** `@rolebook/scalars-p1` is not on npm yet. The npm package named `rolebook` is an unrelated project, so do not install it. ```ts title="admit.ts" group=parse import { parseP1, type P1Limits } from "@rolebook/scalars-p1"; declare const bytes: Uint8Array; // the JSON exactly as received, never re-serialized // Every budget is required. There are no defaults. const limits: P1Limits = { maxBytes: 65536, maxDepth: 32, maxValues: 16384, maxObjectMembers: 4096, maxArrayEntries: 4096, maxStringBytes: 16384, }; const result = parseP1(bytes, limits); if (!result.ok) throw new Error(`not admitted: ${result.error.code}`); export const value = result.value; ``` `parseP1` never throws for malformed bytes or limits; the first failure, in a fixed order, is the reported code. The result shares nothing with the input buffer. Objects have a null prototype, so a member named `__proto__` or `constructor` is ordinary data. ## What P1 admits [#what-p1-admits] P1 rejects invalid UTF-8, a byte-order mark, duplicate decoded object keys, lone surrogates, trailing data and input exceeding the caller's explicit structural budgets. It preserves string contents without Unicode normalization. Core still applies its own limits and UTF-16 text semantics after admission. Number admission checks the original decimal token before conversion. Exact magnitude must not exceed `9007199254740991`; admitted values are rounded to binary64 using nearest, ties to even. Nonzero values that round to zero are rejected. Signed zero and subnormal numbers are preserved. P1 is not exact-decimal arithmetic, a full-range binary64 profile or an int64/uint64 profile. Pass the original bytes to `parseP1`. Serializing an already parsed JavaScript number cannot recover the original token or establish that it satisfied this boundary. The decision service and offline snapshots use P1 to admit JSON input. P1 decides only whether the bytes are admitted. Permission decisions for admitted values use Core's decision semantics. The `@rolebook/scalars-p1/fixtures/p1-v1.json` export contains the shared byte fixtures. They include expected admission and binary64 results for boundary cases. Passing them demonstrates agreement on those cases; it does not qualify a new language runtime or prove complete semantic coverage. ## API reference [#api-reference] ### `parseP1` [#parsep1] ```ts api="@rolebook/scalars-p1" function parseP1(bytes: Uint8Array, limits: P1Limits): P1Result; ``` ### `P1_ERROR_CODES` [#p1_error_codes] ```ts api="@rolebook/scalars-p1" const P1_ERROR_CODES: readonly [ "input_type", "invalid_limits", "byte_limit", "invalid_utf8", "invalid_json", "duplicate_key", "invalid_unicode", "number_limit", "number_range", "number_underflow", "depth_limit", "value_limit", "member_limit", "array_limit", "string_limit" ]; ``` ### `P1_MAX_EXPONENT_DIGITS` [#p1_max_exponent_digits] ```ts api="@rolebook/scalars-p1" const P1_MAX_EXPONENT_DIGITS = 6; ``` ### `P1_MAX_MAGNITUDE` [#p1_max_magnitude] ```ts api="@rolebook/scalars-p1" const P1_MAX_MAGNITUDE = 9007199254740991; ``` ### `P1_MAX_NUMBER_TOKEN_BYTES` [#p1_max_number_token_bytes] ```ts api="@rolebook/scalars-p1" const P1_MAX_NUMBER_TOKEN_BYTES = 256; ``` ### `P1_SCALAR_PROFILE` [#p1_scalar_profile] ```ts api="@rolebook/scalars-p1" const P1_SCALAR_PROFILE = "rolebook/scalars-p1/v1"; ``` ### `P1Error` [#p1error] ```ts api="@rolebook/scalars-p1" interface P1Error { readonly code: P1ErrorCode; } ``` ### `P1ErrorCode` [#p1errorcode] ```ts api="@rolebook/scalars-p1" type P1ErrorCode = (typeof P1_ERROR_CODES)[number]; ``` ### `P1Limits` [#p1limits] ```ts api="@rolebook/scalars-p1" interface P1Limits { readonly maxBytes: number; readonly maxDepth: number; readonly maxValues: number; readonly maxObjectMembers: number; readonly maxArrayEntries: number; readonly maxStringBytes: number; } ``` ### `P1Result` [#p1result] ```ts api="@rolebook/scalars-p1" type P1Result = { readonly ok: true; readonly value: P1Value; } | { readonly ok: false; readonly error: P1Error; }; ``` ### `P1Value` [#p1value] ```ts api="@rolebook/scalars-p1" type P1Value = null | boolean | number | string | P1Value[] | { [key: string]: P1Value; }; ``` # Security model (/docs/security-model) > What Rolebook guarantees, and what your application must establish. Rolebook is an embedded authorization decision library. An application binds a subject, scoped role assignments, and trusted request context to a policy, then checks a concrete action against a concrete resource. Rolebook evaluates those supplied facts locally and returns an allow or a coded denial. Rolebook is not an identity system, a resource database, or evidence that the supplied facts are true. This page defines the boundary your application must preserve. It is not an external security audit or certification. The engine is the only evaluator. The [sharing packages](#the-sharing-layer), the [decision service](#the-decision-service), and [offline snapshots](#offline-snapshots) each bring facts to it from a different place, and each adds its own boundary, described below. [Choose how decisions run](/docs/choosing) compares them. ## Your application establishes [#your-application-establishes] Before binding or checking: - The subject's canonical `type` and `id`, from an authenticated identity. - Role assignments, including their subject, scoped resource, and descendant applicability, from an authoritative store. - The requested resource and its ordered ancestry, loaded through an authoritative, tenant-scoped path. - Context facts, including their freshness and whether a client may influence them. - The policy version selected for the request. With the sharing package's versioned constructor, the sharing layer selects it from the policy store and reports it on the decision. A decision says only that the supplied policy and facts matched. It does not prove identity, tenancy, membership, ownership, resource existence, or the freshness of a policy or context value. ### Resource provenance [#resource-provenance] `trustedResource(ref, ancestors, attributes)` makes an immutable, caller-attested snapshot. Its type and structural validation do not represent a database row, an external signature, or tenant proof, and a type-correct ancestor ID is only caller-supplied data. Load a resource through a query scoped to the authenticated tenant, build the snapshot from that result, and pass immediate-parent-to-root ancestry in the policy's declared type order. Never treat a client-provided resource ID, attribute, active-workspace selection, or claimed role as authorization proof. A structurally valid resource from another tenant is still the wrong input. ### Who may change policy [#who-may-change-policy] With [versioned sharing](/docs/sharing/versioned), whoever can call `policies.*` or `customRoles.*` can change every tenant's access. Rolebook records the `actor` in the policy audit but does not authorize it: authenticate and authorize operators before calling these APIs, and never let tenant users reach them. The policy store is authority data with the same standing as membership rows, in your database: write access to its tables is write access to policy. Before the first `publish`, every process that writes sharing state must run policy-fenced adapters. ## Core invariants [#core-invariants] For a policy that compiles, Rolebook enforces: 1. A check names a concrete `resource:action`; wildcards are accepted only in policy rules. 2. An assignment applies only when its subject is the bound subject or one of the binding's flat group principals, and its scope is the checked resource or an allowed ancestor. `appliesTo: "descendants"` covers the scope resource itself and its descendants; `"self"` covers only the scope resource. 3. Resource ancestry is bounded, ordered, and consistent with the policy's declared parent types. A `recursive: true` type may repeat as a contiguous run of distinct same-type ancestors, still within the 16-ancestor limit and continuing to the root. Repeated references are refused. Core cannot detect an omitted ancestor within a same-type run; the caller must supply the complete authoritative chain, just as it must supply authentic resource IDs. 4. A role's rules target its scope type or declared descendants; rules for an ancestor or unrelated type fail compilation because they could never apply. 5. A rule matches only when its permission, condition, and field constraint all match. A known false condition matches neither effect; an unknown condition never matches an allow and conservatively matches a deny. A field-restricted allow matches only a requested field one of its patterns matches exactly, so it never authorizes a request without a field; a field-restricted deny matches a request without a field and any field that equals, contains, or lies inside a denied path. 6. Matching denies are evaluated before matching allows. Inherited rules keep their effects; there is no implicit bypass role or action implication. 7. Subject and resource identity come from reserved canonical fields; attribute bags cannot replace `type` or `id`. 8. Dynamic map access uses own properties. Unsafe prototype keys and accessor properties are rejected. 9. Policy, binding, request, resource, context, and condition values are copied into immutable, JSON-like snapshots with finite numbers. Cycles, sparse arrays, accessors, and unsupported object shapes are rejected or denied. An explicit `undefined` inside a snapshot is rejected; only the optional top-level `context`, `principals`, and `field` slots treat `undefined` as omitted. 10. `check()`, `enforce()`, and `explain()` run one decision path; explaining only observes it, is bounded, and does not change the decision. `check()` and `enforce()` build no trace. `{ detail: "conditions" }` adds condition trees, read only after the request snapshot is fixed. They record fact paths and rule identifiers, not runtime values or policy literals. The rules that do not decide the request share a budget of 256 condition-tree nodes in evaluation order; the deciding rule's tree, itself at most 256 nodes, is always retained whole beside them, so one explanation holds at most 512 nodes. A deciding rule beyond the 64-entry trace cap is still omitted, as `traceTruncated` reports. Options are inspected without invoking accessors. Only a plain object whose single own enumerable data property is `detail: "conditions"` selects condition detail; `{}` and `{ detail: undefined }` select the rule-only trace. Every other value, including one with an extra key, a non-plain prototype, an accessor, or one whose inspection throws, also yields the rule-only trace and sets `optionsRejected: true` on the explanation, and is never treated as an evaluator fault. Do not return a detailed explanation to an unauthorized caller. 11. The complete assignment collection is validated before entries are filtered. A malformed assignment, unknown role, or role/scope mismatch denies the binding even if that entry would not otherwise apply. 12. Group principals are flat and bounded: at most 64 distinct principals, none equal to the subject. They are never expanded, so nesting and membership graphs cannot be expressed. Deny precedence spans every principal; decisions and traces name the contributing group in `via`. 13. A binding may reuse a copy Rolebook itself produced with `prepareAssignments()`. Reuse skips only the copy: every reused entry is validated on every bind, and budgets apply across reused and fresh entries together. A caller cannot register a value. ## Errors and outcomes [#errors-and-outcomes] Policy compilation is a deployment-time operation: `definePolicy()` and `createAuthorizer()` throw for a malformed policy. Treat that as a failed rollout. Binding and checking are fail-closed: invalid input returns a denial with a stable [code](/docs/decisions#decision-codes), and runtime inputs are validated as complete envelopes, so an unknown key denies rather than being ignored. Storage adapters treat a fence or fact revalidation as passing only when it returns literally `true`. `enforce()` throws `AuthorizationError` with the denial; map it deliberately at your framework boundary. Do not use exceptions, reasons, or traces as an audit log. An unexpected evaluator fault returns `INVALID_REQUEST`, indistinguishable from a malformed call by design; pass `onInternalError` to `createAuthorizer()` to observe it. Policy names use a strict safe grammar; subject and resource IDs are opaque, bounded strings never interpreted as names. Missing or malformed facts never grant access, except that `exists: false` is a known match when its fact is absent. ## The sharing layer [#the-sharing-layer] The [sharing packages](/docs/sharing) do not change this boundary. A sharing adapter must establish tenant-scoped resource provenance, current identity eligibility, membership, ownership, and ancestry before it creates a Rolebook binding, and sharing decisions are no stronger than those inputs. Beyond that: - Workspace membership is eligibility, not access to private resources. - Mutations hold the actor's eligibility (and any authorization facts) in the storage transaction: `SERIALIZABLE` with `FOR SHARE` locks on PostgreSQL, the `BEGIN IMMEDIATE` write lock on SQLite. The in-memory adapter only re-checks, and only when configured; it is not a production adapter. - A manager other than the owner can hand out only access it holds itself (the [delegation ceiling](/docs/sharing/delegation)), denies on groups belong to the owner, and the owner can always remove a deny that reaches them through a group. - A denial does not confirm that a resource exists. - Teams never act or own resources. Flat teams (`withTeams()`) are the default: leaving a team ends its access on the next request, and joining one mid-mutation restarts the mutation. Optional bounded nested team lineage (`withTeamLineage()`) is available on PostgreSQL and SQLite. - Versioned reads may use the previous policy generation for at most the refresh interval, or `maxStalenessMs` while the store is unreachable; writes fence the generation and the tenant's custom-role revision in the transaction. - An idempotency key replays its committed answer only while its record is kept; after pruning, a retry runs as a new command against current state. - Each page of [`listAccessible()` and `listAccess()`](/docs/sharing/listing) is consistent within the page: its candidates, including their absence, the principal, each examined resource, the policy runtime, and one logical instant for every expiry comparison are read at one coherent point. This requires a storage adapter that holds one snapshot for the page, and identity evidence for the same point. The in-memory adapter holds its own snapshot; a SQL adapter needs a supported executor, which on SQLite is the worker-backed executor and not the queued one. A page that cannot be established that way rejects with `AccessListingUnavailableError` and a non-sensitive `reason`; it is never a partial page or a weaker read. The guarantee covers one page. Each page takes a fresh snapshot, so a cursor does not freeze a traversal across pages, and a returned page is not kept fresh until your code acts on it. - `describeAccess()` reports the ownership, memberships, and invitations stored on one resource. It is not an enumeration of every subject the policy would allow. ## The decision service [#the-decision-service] [`@rolebook/decision-service`](/docs/decision-service) evaluates Core checks for authenticated callers. It adds these guarantees: - A request names a subject, a resource, a concrete action, and optionally a field. It cannot carry assignments, principals, context, facts, or a policy; an object with an unknown member is refused. - Authentication runs before the body is read. There is no anonymous fallback and no allow-all default. - A grant maps one credential and actor to one scope and its operations. An unknown scope, another scope, another actor, and an ungranted operation all answer the same `forbidden`. A `bound` grant may check only its own subject. - Every item of a batch passes preflight before any authority is loaded. - Only `ALLOWED`, `EXPLICIT_DENY`, and `NOT_GRANTED` are decisions. An unavailable provider, an invalid or stale authority document, a timeout, or a registry replacement during the request is a **no-decision**. It never becomes a denial, an allow, cached facts, or empty authority. - Responses carry no reasons, stacks, policies, facts, assignments, or matched roles. - Body size, structure, time, and concurrency are bounded, and exceeding a bound fails closed. Your deployment establishes the rest: - **The credential verifier.** Qualify it against its real issuer, audience, expiry, revocation, and key custody. The package ships none. - **Each authority provider.** The service checks that a document names the requested subject and resource, the pinned policy, and a fresh observation time. It cannot check that a document marked `complete: true` is complete: a provider that omits a deny assignment produces an allow the service cannot detect. Qualify each provider against its real source for scope isolation, complete assignments including denies and flat memberships, complete ordered ancestry, resource existence, the origin of every attribute, and confirmed absence versus unavailability. - **The HTTP host.** It terminates TLS, rejects duplicate headers, normalizes the raw request target before it constructs the `Request`, and owns rate limiting and connection teardown. - **Clocks.** Freshness compares the provider's `observedAtMs` with the service's wall clock, so the accuracy between the two is a deployment requirement. A decision is an observation at the decision point. It identifies the policy generation and digest it used, but it is not a transaction fence for a later write and makes no causal-consistency promise. ## Offline snapshots [#offline-snapshots] [`@rolebook/offline`](/docs/offline) verifies a signed bundle that carries one exact check and evaluates it with the engine. It adds these guarantees: - The signature covers the exact received bytes. The bundle's signer cannot supply its own trust lease: the lease is verified under the configured root on every read. - A verifier takes no local policy and no caller facts. The carried policy is compiled and its canonical digest compared with the bundle's and with the lease's allowed policies. - Audience, scope, validity window, fact age, and the stored anti-rollback state are checked before the engine runs. A bundle behind the stored rollback floor for its check, or a lease older than the installed one, is refused. - Every failure is a typed no-decision. Missing or lost trust state is never reset and accepted. - A `ui_only` verifier refuses enforcement before parsing, and its results are labelled `ui_hint`. It deliberately does not provide: - **Immediate disconnected revocation.** A revoked or compromised signer stays usable until a newer root-signed lease that no longer authorizes its key is durably installed, bounded by the key horizon (at most 7 days), the bundle expiry (at most 24 hours), and fact freshness. - **Proof of fact completeness.** The provider manifest makes a snapshot carry the declared members and fact paths. It cannot prove that the issuer included every assignment, principal, ancestor, or deny. A compromised issuer can falsify facts and timestamps within its trust horizon. - **Write authorization or one-time use.** A decision is reusable while the bundle is valid. A protected side effect needs its own idempotency or use-record protocol. - **A qualified host.** The clock, the state store, the sequence allocator, key custody, and the host qualification record are yours. A wall clock that can be set back, ordinary browser storage, or a restorable file does not meet the adapter contracts, and a TypeScript interface is not a qualification. ## Non-goals [#non-goals] The Rolebook engine does not authenticate users, issue sessions, store subjects or memberships, manage invitations, load resources, provide transactional workspace lifecycle, persist audit events, distribute policies, open network connections, or execute accessible-resource queries. The companion packages add some of these as explicit, separately configured layers; none of them hosts a service for you, and each HTTP surface is a handler you mount behind your own authentication. No Rolebook package supports arbitrary relationship graphs or unbounded cross-resource traversal. The core engine uses flat group principals and a single declared ancestry chain per resource (with optional `recursive: true` resource types up to 16 ancestors). `@rolebook/sharing` and `@rolebook/teams` add opt-in, bounded folder inheritance and nested team lineage on PostgreSQL and SQLite, with strict depth and principal caps. If your access model is dominated by arbitrary relationship graphs and cross-service traversal, use a relationship-based authorization system instead. Delegated authority is not supported. No Rolebook package lets an actor such as a workload, background job or AI agent act on behalf of another subject, and a caller-supplied `onBehalfOf` value, grant id or token is never evidence of authority. A workload is checked as an ordinary subject with its own role assignments. The design is a proposal only, recorded in the [delegated authority decision record](https://github.com/Amakinto-Labs/rolebook/blob/qa/docs/decisions/delegated-authority-2026-11.md). See [limits](/docs/limits) for the hard bounds. Adversarial tests for them live in `tests/v4-limits-and-closure.test.ts` in the repository. ## Reporting a vulnerability [#reporting-a-vulnerability] Report a suspected vulnerability privately: through the [contact page](/contact), saying it is a security report, or through GitHub's private vulnerability-reporting flow where the repository offers it. Never put vulnerability details, proof-of-concept code, credentials, or affected customer data in a public issue, discussion, or pull request. A useful report names the affected package version or commit, gives a minimal reproduction with the observed and expected authorization result, states the impact and prerequisites, and says whether the issue can cause an unintended allow, a denial, or an availability problem. The maintainers acknowledge a report, assess reproducibility and impact, and coordinate a fix through the private report. No specific response or remediation window is promised, and this page does not represent any version as externally audited or certified. # Better Auth (/docs/sharing-better-auth) > @rolebook/sharing-better-auth: Better Auth organizations as the source of users and workspace membership. `@rolebook/sharing-better-auth` resolves sharing principals from Better Auth's organization plugin: users, organizations, organization members, and member roles. It needs `better-auth` `>=1.7.7 <2`. ```ts import { createBetterAuthIdentityAdapter, type BetterAuthDirectoryReader } from "@rolebook/sharing-better-auth"; import type { ParameterizedSqlExecutor } from "@rolebook/sharing-postgres"; declare const executor: ParameterizedSqlExecutor; // the same database Better Auth uses // Read Better Auth's tables directly; adjust table and column names to your Better Auth schema. const directory: BetterAuthDirectoryReader = { async getOrganizationMember({ organizationId, userId }) { const { rows } = await executor.query<{ id: string; organizationId: string; userId: string; role: string }>( 'SELECT id, "organizationId", "userId", role FROM auth.member WHERE "organizationId" = $1 AND "userId" = $2', [organizationId, userId], ); return rows.length === 1 ? rows[0] : undefined; }, async getUser({ userId }) { const { rows } = await executor.query<{ id: string; email: string; emailVerified: boolean }>( 'SELECT id, email, "emailVerified" FROM auth."user" WHERE id = $1', [userId], ); return rows[0]; }, }; export const identity = createBetterAuthIdentityAdapter({ directory }); ``` The reader must query membership with **both** the organization and user IDs, from an authoritative path: your Better Auth database or its server API. ## Behaviour [#behaviour] - Resolution always loads the user (the factory's `requireUser`): a principal is ineligible unless the user exists with the requested ID. The user's `email`, `emailVerified`, and the member's `workspaceRole` are exposed on `principal.attributes` for your application, never to Rolebook conditions, because the member-role fence does not protect profile changes. - Membership IDs and roles must be non-empty strings of at most 128 characters; malformed records fail closed. - Better Auth stores several roles as one comma-separated string (`"admin,member"`). The mapper, the authorization fact, and `attributes.workspaceRole` receive that string unchanged: match on `role.split(",")`, not on equality or a substring (`includes("admin")` also matches `superadmin`). - Email-bound invitations match only a current member whose Better Auth email is verified. ## Mapping workspace roles [#mapping-workspace-roles] ```ts import { createBetterAuthIdentityAdapter, type BetterAuthDirectoryReader } from "@rolebook/sharing-better-auth"; declare const directory: BetterAuthDirectoryReader; export const identity = createBetterAuthIdentityAdapter({ directory, mapWorkspaceAssignments: ({ tenantId, subject, member }) => member.role.split(",").includes("admin") ? [ { subject, role: "workspace_admin", scope: { resource: { type: "workspace", id: tenantId }, appliesTo: "descendants" }, }, ] : [], }); ``` With a mapper, each principal carries a `BETTER_AUTH_WORKSPACE_MEMBER_AUTHORIZATION_FACT` with the member ID and role. Configure the storage adapter's [workspace-role fact fence](/docs/sharing-postgres/fences#mapped-workspace-roles) with that `factType` and Better Auth's real `id` and `role` columns; without it, mapped management mutations fail closed. ## Fences [#fences] Better Auth can share your application database, so its member and user rows can be locked by the sharing transaction: configure `createPostgresMembershipEligibilityFence()` (or the SQLite equivalent) against Better Auth's `member` table, and `createPostgresEmailInvitationRecipientFence()` against `member` and `user` for email invitations. A Better Auth deployment reached only through a remote API cannot be fenced: issue subject-bound invitations there. For teams, see [`@rolebook/teams/better-auth`](/docs/teams#wiring-it-up-with-better-auth). ## Listing accessible resources [#listing-accessible-resources] This adapter answers `authorize()`, `permissions()`, and commands. It does not implement `resolvePagePrincipal`, so on its own it supplies no identity evidence for [`listAccessible()` and `listAccess()`](/docs/sharing/listing#identity): those calls reject with `AccessListingUnavailableError` and the reason `identity_evidence_missing`. That holds even when Better Auth shares your database, because the adapter reads through your directory reader and not inside the page's snapshot. The membership eligibility fence above does carry the eligibility evidence a page needs; identity evidence is a separate requirement. To list, the sharing instance needs an identity adapter that resolves principals from a complete local identity projection in the same database as the sharing tables: eligibility, assignments, groups, and attributes. Name that adapter object and the projection in the storage adapter's `pageIdentity` option. The option is an attestation that the adapter passed to `createSharing()` answers from exactly that projection, so it must be an adapter that really reads the projection. Do not name this Better Auth adapter as the source of a projection it does not read. Keep the projection synchronized from Better Auth as authoritative data, and advance the row's revision on every change. A sharing instance has one identity adapter, so its checks and commands then use the projection as well. The alternative is an identity adapter of your own that implements `resolvePagePrincipal` over a source with a revision that never repeats and changes on every relevant change. See [identity for listing](/docs/sharing/listing#identity). ## What every identity adapter guarantees [#what-every-identity-adapter-guarantees] All three provider adapters are configurations of [`createWorkspaceIdentityAdapter()`](/docs/sharing/adapters#createworkspaceidentityadapter), so they enforce the same rules: - Every membership lookup receives the explicit organization (tenant) ID and user ID. There is no session or active-organization input. - Organization membership is eligibility only. No Rolebook assignment is emitted unless you supply `mapWorkspaceAssignments`, and then each mapped assignment must target the canonical subject, a role of at most 128 characters, the configured workspace resource type with the explicit tenant ID, and `appliesTo` `"self"` or `"descendants"`; anything else throws. - Records are copied (each field read once) before they are validated, so a cache-backed record cannot answer two checks differently. - The Rolebook subject is the canonical `{ type, id }` only (default type `"user"`, workspace resource type `"workspace"`). Profile data never reaches conditions. - Invitation matching requires an eligible principal in canonical form and rechecks current membership. - Provider organization invitations are never created or replaced: resource invitations are separate. - The member-removed handler validates and freezes the event for cleanup code. It is not an authorization fence: every sharing operation checks current membership. ## API [#api] `import { ... } from "@rolebook/sharing-better-auth"`. Signatures are checked against the built declarations. ## Exports [#exports] ### `createBetterAuthIdentityAdapter` [#createbetterauthidentityadapter] ```ts api="@rolebook/sharing-better-auth" function createBetterAuthIdentityAdapter( options: BetterAuthIdentityAdapterOptions, ): TenantIdentityAdapter; ``` Builds the `TenantIdentityAdapter`. Always loads the user while resolving. ### `BetterAuthIdentityAdapterOptions` [#betterauthidentityadapteroptions] ```ts api="@rolebook/sharing-better-auth" interface BetterAuthIdentityAdapterOptions { readonly directory: BetterAuthDirectoryReader; readonly subjectType?: string; readonly workspaceResourceType?: string; readonly mapWorkspaceAssignments?: (input: { readonly tenantId: string; readonly subject: ResourceRef; readonly member: BetterAuthMemberRecord; }) => readonly RoleAssignment[]; readonly normalizeEmail?: (email: string) => string; } ``` `directory` (required), `subjectType`, `workspaceResourceType`, `mapWorkspaceAssignments`, `normalizeEmail`. ### `BetterAuthDirectoryReader` [#betterauthdirectoryreader] ```ts api="@rolebook/sharing-better-auth" interface BetterAuthDirectoryReader { getOrganizationMember(input: { readonly organizationId: string; readonly userId: string; }): Promise; getUser(input: { readonly userId: string }): Promise; } ``` Exact membership and user lookups you implement. ### `BetterAuthMemberRecord` [#betterauthmemberrecord] ```ts api="@rolebook/sharing-better-auth" type BetterAuthMemberRecord = Pick< BetterAuthOrganizationMember, "id" | "organizationId" | "userId" | "role" >; ``` The authority-bearing fields of a Better Auth organization member. ### `BetterAuthUserRecord` [#betterauthuserrecord] ```ts api="@rolebook/sharing-better-auth" type BetterAuthUserRecord = Pick & Partial>; ``` The user fields the adapter reads. ### `BETTER_AUTH_WORKSPACE_MEMBER_AUTHORIZATION_FACT` [#better_auth_workspace_member_authorization_fact] ```ts api="@rolebook/sharing-better-auth" const BETTER_AUTH_WORKSPACE_MEMBER_AUTHORIZATION_FACT = "rolebook.better-auth.workspace-member.v1"; ``` The fact type for the workspace-role fact fence. ### `createBetterAuthMemberRemovedHandler` [#createbetterauthmemberremovedhandler] ```ts api="@rolebook/sharing-better-auth" function createBetterAuthMemberRemovedHandler(input: { readonly onMemberRemoved: (event: { readonly organizationId: string; readonly userId: string; }) => void | Promise; }): (event: { readonly organization: { readonly id: string; }; readonly member: { readonly userId: string; }; }) => Promise; ``` Adapts Better Auth's member-removed hook event (`{ organization, member }`) to a validated, frozen `{ organizationId, userId }` for cleanup. # Clerk (/docs/sharing-clerk) > @rolebook/sharing-clerk: Clerk organizations as the source of users and organization membership. `@rolebook/sharing-clerk` resolves sharing principals from Clerk organization memberships and users. It needs `@clerk/backend` `>=3.17.0 <4`. ```ts import { createClerkClient } from "@clerk/backend"; import { createClerkBackendDirectoryReader, createClerkIdentityAdapter } from "@rolebook/sharing-clerk"; const clerkClient = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY! }); export const identity = createClerkIdentityAdapter({ directory: createClerkBackendDirectoryReader(clerkClient), }); ``` `createClerkBackendDirectoryReader()` requests `getOrganizationMembershipList({ organizationId, userId: [userId], limit: 2 })` and returns a membership only when the response holds exactly one record whose organization ID and user ID both match; missing, mismatched, nullable-user, or duplicate results fail closed. For users it projects only the primary email address ID and the addresses' verification status. ## Behaviour [#behaviour] - Resolving a principal makes one call, the exact membership lookup. `getUser` is called only to match an email-bound invitation. Set `requireUser: true` when your reader is not authoritative for memberships (a cache or a webhook-fed projection that can briefly keep a deleted user's membership): each resolution then also fetches the user and is ineligible unless it still exists. - The Rolebook subject carries no Clerk role, email, or metadata. The role reaches only your mapper and its authorization fact. - Email-bound invitations match only the user's **primary** email address, and only when that address's verification status is `verified`. A verified secondary address never matches. - Clerk Organizations have no teams; keep team tables of your own and use [`@rolebook/teams/sql`](/docs/teams#application-owned-tables). ## Remote identity and fences [#remote-identity-and-fences] Clerk is a remote system: a Clerk API check or a webhook-fed projection is not by itself an atomic fence for a sharing mutation. For database-backed sharing, keep a database-local projection of Clerk memberships whose lifecycle you coordinate with removals (for example from verified `organizationMembership.deleted` webhooks through `createClerkMemberRemovedHandler()`), and point the eligibility fence, and with a role mapper the workspace-role fact fence (`CLERK_ORGANIZATION_MEMBER_AUTHORIZATION_FACT`), at it. If you cannot establish that, keep Clerk roles out of sharing-management policy. Email-bound acceptance needs a database-local recipient fence over the membership, the primary address ID, the address, and its verification; without one, issue subject-bound invitations, which compare Clerk's immutable user ID. Mapped roles used by a decision are snapshots at the current Clerk lookup: a decision concurrent with a Clerk role change can linearize at that lookup, and one invoked after the change completes performs a new lookup. This is not a cross-system transaction. ## Listing accessible resources [#listing-accessible-resources] This adapter answers `authorize()`, `permissions()`, and commands. It does not implement `resolvePagePrincipal`, so on its own it supplies no identity evidence for [`listAccessible()` and `listAccess()`](/docs/sharing/listing#identity): those calls reject with `AccessListingUnavailableError` and the reason `identity_evidence_missing`. A Clerk lookup cannot be read at the same point as a database page. To list, the sharing instance needs an identity adapter that resolves principals from a complete local identity projection in the same database as the sharing tables: eligibility, assignments, groups, and attributes. Name that adapter object and the projection in the storage adapter's `pageIdentity` option. The option is an attestation that the adapter passed to `createSharing()` answers from exactly that projection, so it must be an adapter that really reads the projection. Do not name this Clerk adapter as the source of a projection it does not read. Keep the projection synchronized from Clerk as authoritative data, and advance the row's revision on every change. A sharing instance has one identity adapter, so its checks and commands then use the projection as well. The alternative is an identity adapter of your own that implements `resolvePagePrincipal` over a source with a revision that never repeats and changes on every relevant change. See [identity for listing](/docs/sharing/listing#identity). ## What every identity adapter guarantees [#what-every-identity-adapter-guarantees] All three provider adapters are configurations of [`createWorkspaceIdentityAdapter()`](/docs/sharing/adapters#createworkspaceidentityadapter), so they enforce the same rules: - Every membership lookup receives the explicit organization (tenant) ID and user ID. There is no session or active-organization input. - Organization membership is eligibility only. No Rolebook assignment is emitted unless you supply `mapWorkspaceAssignments`, and then each mapped assignment must target the canonical subject, a role of at most 128 characters, the configured workspace resource type with the explicit tenant ID, and `appliesTo` `"self"` or `"descendants"`; anything else throws. - Records are copied (each field read once) before they are validated, so a cache-backed record cannot answer two checks differently. - The Rolebook subject is the canonical `{ type, id }` only (default type `"user"`, workspace resource type `"workspace"`). Profile data never reaches conditions. - Invitation matching requires an eligible principal in canonical form and rechecks current membership. - Provider organization invitations are never created or replaced: resource invitations are separate. - The member-removed handler validates and freezes the event for cleanup code. It is not an authorization fence: every sharing operation checks current membership. ## API [#api] `import { ... } from "@rolebook/sharing-clerk"`. Signatures are checked against the built declarations. ## Exports [#exports] ### `createClerkIdentityAdapter` [#createclerkidentityadapter] ```ts api="@rolebook/sharing-clerk" function createClerkIdentityAdapter( options: ClerkIdentityAdapterOptions, ): TenantIdentityAdapter; ``` Builds the `TenantIdentityAdapter`. ### `ClerkIdentityAdapterOptions` [#clerkidentityadapteroptions] ```ts api="@rolebook/sharing-clerk" interface ClerkIdentityAdapterOptions { readonly directory: ClerkDirectoryReader; readonly subjectType?: string; readonly workspaceResourceType?: string; readonly mapWorkspaceAssignments?: (input: { readonly tenantId: string; readonly subject: ResourceRef; readonly member: ClerkOrganizationMembershipRecord; }) => readonly RoleAssignment[]; readonly normalizeEmail?: (email: string) => string; readonly requireUser?: boolean; } ``` `directory` (required), `subjectType`, `workspaceResourceType`, `mapWorkspaceAssignments`, `normalizeEmail`, `requireUser`. ### `createClerkBackendDirectoryReader` [#createclerkbackenddirectoryreader] ```ts api="@rolebook/sharing-clerk" function createClerkBackendDirectoryReader( client: ClerkBackendDirectoryClient, ): ClerkDirectoryReader; ``` A reader over a `@clerk/backend` v3 client that validates both identifiers on every returned record. ### `ClerkBackendDirectoryClient` [#clerkbackenddirectoryclient] ```ts api="@rolebook/sharing-clerk" type ClerkBackendDirectoryClient = Pick; ``` The client subset the reader uses. ### `ClerkDirectoryReader` [#clerkdirectoryreader] ```ts api="@rolebook/sharing-clerk" interface ClerkDirectoryReader { getOrganizationMembership(input: { readonly organizationId: string; readonly userId: string; }): Promise; getUser(input: { readonly userId: string }): Promise; } ``` Exact membership and user lookups. ### `ClerkOrganizationMembershipRecord` [#clerkorganizationmembershiprecord] ```ts api="@rolebook/sharing-clerk" interface ClerkOrganizationMembershipRecord { readonly id: string; readonly organizationId: string; readonly userId: string; readonly role: string; } ``` The authority-bearing fields of a Clerk organization membership. ### `ClerkUserRecord` [#clerkuserrecord] ```ts api="@rolebook/sharing-clerk" interface ClerkUserRecord { readonly id: string; readonly primaryEmailAddressId: string | null; readonly emailAddresses: readonly ClerkEmailAddressRecord[]; } ``` The user fields the adapter reads: the primary address ID and the addresses. ### `ClerkEmailAddressRecord` [#clerkemailaddressrecord] ```ts api="@rolebook/sharing-clerk" interface ClerkEmailAddressRecord { readonly id: string; readonly emailAddress: string; readonly verification: { readonly status: string; } | null; } ``` ### `CLERK_ORGANIZATION_MEMBER_AUTHORIZATION_FACT` [#clerk_organization_member_authorization_fact] ```ts api="@rolebook/sharing-clerk" const CLERK_ORGANIZATION_MEMBER_AUTHORIZATION_FACT = "rolebook.clerk.organization-member.v1"; ``` The fact type for the workspace-role fact fence. ### `createClerkMemberRemovedHandler` [#createclerkmemberremovedhandler] ```ts api="@rolebook/sharing-clerk" function createClerkMemberRemovedHandler(input: { readonly onMemberRemoved: (event: ClerkMemberRemovedEvent) => void | Promise; }): (event: ClerkMemberRemovedEvent) => Promise; ``` Validates and freezes a translated `organizationMembership.deleted` event for cleanup. ### `ClerkMemberRemovedEvent` [#clerkmemberremovedevent] ```ts api="@rolebook/sharing-clerk" interface ClerkMemberRemovedEvent { readonly organizationId: string; readonly userId: string; } ``` # @rolebook/sharing-postgres API (/docs/sharing-postgres/api) > Every export of @rolebook/sharing-postgres, with its signature and behaviour. `import { ... } from "@rolebook/sharing-postgres"`. Signatures are checked against the package's built declarations. Start with the [PostgreSQL adapter guide](/docs/sharing-postgres). ## Adapter [#adapter] ### `createPostgresSharingAdapter` [#createpostgressharingadapter] ```ts api="@rolebook/sharing-postgres" function createPostgresSharingAdapter( options: CreatePostgresSharingAdapterOptions, ): PostgresSharingAdapter; ``` Creates the adapter for one concrete resource table. Validates the descriptor and options before any SQL runs. See [setup](/docs/sharing-postgres#3-fences-and-the-adapter). ### `CreatePostgresSharingAdapterOptions` [#createpostgressharingadapteroptions] ```ts api="@rolebook/sharing-postgres" interface CreatePostgresSharingAdapterOptions { readonly executor: ParameterizedSqlExecutor; readonly resource: PostgresResourceDescriptor; readonly clock?: SharingClock; readonly lockEligibleSubjects: PostgresEligibilityFence; readonly readEligibleSubjects?: PostgresEligibilityReader; readonly lockInvitationRecipient?: PostgresInvitationRecipientFence; readonly revalidateAuthorizationFacts?: PostgresAuthorizationFactFence; readonly groupSubjectTypes?: readonly string[]; readonly fencePolicy?: PostgresPolicyFence; readonly governanceGate?: GovernanceDirectGate; readonly governanceBinding?: GovernanceBinding; readonly serializableRetry?: SerializableRetryOptions; readonly pageIdentity?: PostgresPageIdentity; readonly groupGraph?: import("./group-graph-fence.js").PostgresGroupGraphOption; } ``` `executor`, `resource`, and the required `lockEligibleSubjects`; optional `lockInvitationRecipient` (email invitations), `revalidateAuthorizationFacts` (mapped roles, teams), `groupSubjectTypes` (default `["team"]`), `fencePolicy`, `clock`, and `serializableRetry`. Two options matter only to [`listAccessible()` and `listAccess()`](/docs/sharing/listing#what-a-consistent-page-requires), which read each page in one `SERIALIZABLE READ ONLY` transaction: - `readEligibleSubjects` is the read-only form of `lockEligibleSubjects`; see [`PostgresEligibilityReader`](#postgreseligibilityreader). The first-party fences carry their own, so set it only beside a fence you wrote yourself. A custom fence without it makes every listing answer `identity_evidence_missing`. - `pageIdentity` names the identity adapter of the sharing instance and the local projection it answers from; see [`PostgresPageIdentity`](#postgrespageidentity). Without it, the identity adapter must implement `resolvePagePrincipal`, or listings answer `identity_evidence_missing`. A malformed value throws a `TypeError` when the adapter is created. Listing also requires `executor` to be the executor [`createPgExecutor(pool)`](#createpgexecutor) returned, recognized by provenance and not by shape, and `text` tenant and resource ID columns. Any other executor or column type answers `capability_missing`. The page reads its clocks as `timestamptz` values, which the pool must decode as finite `Date` objects (the node-postgres default); a custom `timestamptz` type parser that returns anything else makes every page `snapshot_unavailable`. An adapter `clock` does not apply to listing pages: they judge expiry by the database clock. With [versioned sharing](/docs/sharing/versioned), the policy store must be the one [`createPostgresPolicyStore()`](#createpostgrespolicystore) returned, created with this same executor object, so the page can read policy state in its own transaction; a wrapped store or one on another executor answers `policy_evidence_missing`. `groupGraph` binds one nested-team profile. Set `teamType`, an explicit `identityStability` (`registry_incarnation` or `ids_never_reused`), and a `directory` whose `readDirectTeams` and `readEndpoint` run in the adapter's transaction. `teamIdsGloballyUnique` does not select `ids_never_reused`. When a graph row exists and `groupGraph` is omitted, direct-only reads and writes refuse. Optional `integrity` is that deployment's bootstrap provider. When it is set, a read or mutation that finds structural corruption confirms the finding after the detecting transaction settles, with no user actor. A failed confirmation makes no quarantine claim. Build the commands with [`createPostgresGroupGraphControl()`](#createpostgresgroupgraphcontrol). ### `PostgresSharingAdapter` [#postgressharingadapter] ```ts api="@rolebook/sharing-postgres" interface PostgresSharingAdapter extends SharingAdapter, SettledRecordPruner { withLifecycleTransaction( operation: (transaction: SerializablePostgresTransaction) => Promise, ): Promise; resourceDeletedInTransaction( transaction: SerializablePostgresTransaction, input: DeletePostgresResourceInTransactionInput, ): Promise; resourceMovedInTransaction( transaction: SerializablePostgresTransaction, input: MovePostgresResourceInTransactionInput, ): Promise; initializeResource( input: InitializePostgresSharingResourceInput, ): Promise; initializeResourceInTransaction( executor: SerializablePostgresTransaction, input: InitializePostgresSharingResourceInput, ): Promise; } ``` A `SharingAdapter` and `SettledRecordPruner`, plus `withLifecycleTransaction`, the two `...InTransaction` lifecycle methods, and `initializeResource` / `initializeResourceInTransaction`. See [lifecycle](/docs/sharing-postgres/lifecycle). ### `PostgresResourceDescriptor` [#postgresresourcedescriptor] ```ts api="@rolebook/sharing-postgres" interface PostgresResourceDescriptor { readonly resourceType: string; readonly table: QualifiedIdentifier; readonly tenantColumn: string; readonly idColumn: string; readonly tenantSqlType?: PostgresResourceSqlType; readonly resourceSqlType?: PostgresResourceSqlType; readonly resourceVersionColumn: string; readonly sharingRevisionColumn?: string; readonly resourceFromRow: (row: Readonly>) => TrustedResource; readonly resourceVersion?: (row: Readonly>) => string; readonly resourceColumns?: readonly string[]; readonly sharingTablePrefix: string; readonly hierarchyControl?: { readonly schema: string; readonly prefix?: string; }; readonly governance?: { readonly tablePrefix: string; }; } ``` The application table and how to snapshot its row. See [the descriptor](/docs/sharing-postgres#2-a-resource-descriptor). `hierarchyControl` names the schema (and table prefix, default `rolebook_control`) of the schema-qualified hierarchy control tables this descriptor is permanently bound to. It is required when `table` is unqualified and defaults to the table's schema otherwise; `search_path` is never consulted. See [hierarchy control tables](/docs/sharing-postgres/migrations#hierarchy-control-tables). ### `PostgresResourceSqlType` [#postgresresourcesqltype] ```ts api="@rolebook/sharing-postgres" type PostgresResourceSqlType = "text" | "uuid"; ``` The accepted tenant and resource ID column types. ### `NormalizedPostgresResourceSqlTypes` [#normalizedpostgresresourcesqltypes] ```ts api="@rolebook/sharing-postgres" interface NormalizedPostgresResourceSqlTypes { readonly tenantSqlType: PostgresResourceSqlType; readonly resourceSqlType: PostgresResourceSqlType; } ``` Both SQL types with their `text` defaults applied. ### `normalizePostgresResourceSqlTypes` [#normalizepostgresresourcesqltypes] ```ts api="@rolebook/sharing-postgres" function normalizePostgresResourceSqlTypes( descriptor: Pick, ): NormalizedPostgresResourceSqlTypes; ``` Applies the `text` defaults and rejects any value other than `text` or `uuid`. ## Nested team commands [#nested-team-commands] `groupGraph` on the adapter recomputes lineage inside a sharing mutation. Graph commands change the graph itself. [`createPostgresGroupGraphControl()`](#createpostgresgroupgraphcontrol) builds the facade from the deployment policy, six action permissions, two distinct binding ids, and the bootstrap row descriptor. The branded bootstrap provider and the compiled command object stay inside that call. Each facade method runs in one `SERIALIZABLE` transaction: the hierarchy barrier and admission, the graph row, the policy loaded by the versioned sharing instance, then the planner. The facade has no `confirm` method. Structural confirmation is the adapter's later transaction when `groupGraph.integrity` is the `integrity` object this call returns. [`hierarchyControlTables()`](#hierarchycontroltables) names the control tables for a schema and prefix. Resource migrations install that same profile when the descriptor sets `hierarchyControl`. [`createHierarchyControlMigrations()`](#createhierarchycontrolmigrations) installs the profile on its own, and [`createPolicyCatalogRegistrationMigrations()`](#createpolicycatalogregistrationmigrations) appends the profile to the policy catalog. Activation stores `control_configuration` as `sha256:` plus 64 hexadecimal characters. That digest is the canonical identity of the profile, team type, identity stability, bootstrap type, both binding ids, the six permissions, the graph-independent providers, and the first-party local projection. Provider order, and the order of each provider's fact paths and fact types, do not change it. A later command whose action map differs throws `HierarchyUnavailableError` with reason `profile_mismatch` and does not write the edge. ### `createPostgresGroupGraphControl` [#createpostgresgroupgraphcontrol] ```ts api="@rolebook/sharing-postgres" function createPostgresGroupGraphControl(options: PostgresGroupGraphControlOptions): Readonly<{ tables: HierarchyControlTableNames; integrity: PostgresBootstrapIntegrity; facade: Readonly<{ activate(tenantId: string): Promise; link(tenantId: string, child: ResourceRef, parent: ResourceRef): Promise; unlink(tenantId: string, child: ResourceRef, parent: ResourceRef): Promise; repairUnlink(tenantId: string, child: ResourceRef, parent: ResourceRef): Promise; repairBatch(tenantId: string, start: boolean, limit: number): Promise; release(tenantId: string): Promise; }>; }>; ``` `activate` inserts the graph admission. `link` and `unlink` change one direct edge. `repairUnlink`, `repairBatch`, and `release` run only while the graph is quarantined. `repairBatch` reads at most `limit` rows; `limit` has to be an integer of at least 1, and a smaller or fractional limit is `refused` with `invalid_batch`. A Core denial comes back as `status: "denied"` and `decision`. A structural refusal comes back as `status: "refused"`. An unavailable graph throws `HierarchyUnavailableError`. ```ts import { HierarchyUnavailableError, type PolicyStore } from "@rolebook/sharing"; import { createPostgresGroupGraphControl, createPostgresLocalIdentityProjection, type ParameterizedSqlExecutor, } from "@rolebook/sharing-postgres"; import type { RolebookPolicy } from "rolebook"; declare const executor: ParameterizedSqlExecutor; declare const policy: RolebookPolicy; declare const policyStore: PolicyStore; declare const sharing: object; declare const identity: ReturnType; const graph = createPostgresGroupGraphControl({ executor, profile: { schema: "public", prefix: "rolebook_control" }, teamType: "team", identityStability: "registry_incarnation", actor: { type: "user", id: "ada" }, policy, bootstrapType: "tenant_admin", actions: { activate: "tenant_admin:graph_activate", link: "tenant_admin:graph_link", unlink: "tenant_admin:graph_unlink", repairUnlink: "tenant_admin:graph_repair_unlink", heightRepair: "tenant_admin:graph_height_repair", release: "tenant_admin:graph_release", }, controlBindingId: "control-binding", normalBindingId: "graph-binding", providers: [ { id: "local", graphIndependent: true, factPaths: ["subject.attribute"], factTypes: ["attribute"], }, ], policyStore, sharing, identity, bootstrap: { policyStore: { schema: "public", tablePrefix: "rolebook" }, descriptor: { resourceType: "tenant_admin", schema: "public", table: "tenant_admin", tenantColumn: "workspace_id", idColumn: "id", versionColumn: "version", incarnationColumn: "incarnation", }, }, registry(tx, tenantId) { return { async readEndpoint(group) { const result = await tx.query<{ incarnation: string }>( "SELECT incarnation FROM public.team WHERE tenant_id = $1 AND id = $2", [tenantId, group.id], ); const row = result.rows[0]; return row ? { present: true as const, incarnation: row.incarnation } : { present: false as const }; }, }; }, }); const child = { type: "team", id: "design" }; const parent = { type: "team", id: "product" }; try { const outcome = await graph.facade.link("ws_456", child, parent); if (outcome.status === "denied") outcome.decision.allowed; if (outcome.status === "refused") outcome.refusal; if (outcome.status === "applied") outcome.effect; } catch (error) { if (error instanceof HierarchyUnavailableError) error.reason; } graph.tables.names.groupGraph; graph.integrity.descriptorDigest; ``` `executor`, `policy`, `policyStore`, `sharing`, and `identity` are the objects the rest of the deployment already constructed: the same executor as the policy store, the active policy, the store [`createVersionedSharing()`](/docs/sharing/versioned) reads, that sharing instance, and the object [`createPostgresLocalIdentityProjection()`](#createpostgreslocalidentityprojection) returns. `registry` reads one group endpoint inside the command transaction. The two binding ids are distinct opaque ids. Omit `providers` when the deployment declares no graph-independent fact paths. ### `PostgresGroupGraphControlOptions` [#postgresgroupgraphcontroloptions] ```ts api="@rolebook/sharing-postgres" interface PostgresGroupGraphControlOptions { readonly executor: ParameterizedSqlExecutor; readonly tenantSqlType?: PostgresTenantCodec; readonly teamType: string; readonly identityStability: "registry_incarnation" | "ids_never_reused"; readonly actor: ResourceRef; readonly policy: RolebookPolicy; readonly bootstrapType: string; readonly actions: { readonly activate: string; readonly link: string; readonly unlink: string; readonly repairUnlink: string; readonly heightRepair: string; readonly release: string; }; readonly controlBindingId: string; readonly normalBindingId: string; readonly providers?: readonly { readonly id: string; readonly graphIndependent: true; readonly factPaths: readonly string[]; readonly factTypes: readonly string[]; }[]; readonly profile: HierarchyControlProfile; readonly policyStore: PolicyStore; readonly sharing: object; readonly identity: ReturnType; readonly bootstrap: { readonly policyStore: { readonly schema: string; readonly tablePrefix: string; }; readonly descriptor: PostgresBootstrapRowDescriptor; }; registry(tx: ParameterizedSqlExecutor, tenantId: string): GroupRegistryReader; } ``` `tenantSqlType` selects the tenant key codec (`text` or `uuid`) for the control tables. It has to agree with the codec the profile already bound. `identityStability` is the same explicit declaration the lineage directory was built with. `actor` is the control subject. A control actor whose groups include `teamType`, or a lineage fact, is `identity_unavailable`. ### `hierarchyControlTables` [#hierarchycontroltables] ```ts api="@rolebook/sharing-postgres" function hierarchyControlTables(profile: HierarchyControlProfile): HierarchyControlTableNames; ``` ### `HierarchyControlProfile` [#hierarchycontrolprofile] ```ts api="@rolebook/sharing-postgres" interface HierarchyControlProfile { readonly schema: string; readonly prefix: string; } ``` `prefix` defaults to `rolebook_control` on a resource descriptor. Pass the same schema and prefix here. ### `HierarchyControlTableNames` [#hierarchycontroltablenames] ```ts api="@rolebook/sharing-postgres" interface HierarchyControlTableNames { readonly profile: HierarchyControlProfile; readonly profileId: string; readonly barrier: string; readonly admission: string; readonly hierarchyTenant: string; readonly link: string; readonly inventory: string; readonly principalGeneration: string; readonly descriptorProfile: string; readonly policyIssuer: string; readonly tenantKeyCodec: string; readonly controlReceipt: string; readonly verifierProgress: string; readonly groupGraph: string; readonly groupNode: string; readonly groupEdge: string; readonly groupRepair: string; readonly names: { readonly barrier: string; readonly admission: string; readonly hierarchyTenant: string; readonly link: string; readonly inventory: string; readonly principalGeneration: string; readonly descriptorProfile: string; readonly policyIssuer: string; readonly tenantKeyCodec: string; readonly controlReceipt: string; readonly verifierProgress: string; readonly groupGraph: string; readonly groupNode: string; readonly groupEdge: string; readonly groupRepair: string; }; } ``` The table fields are schema-qualified dotted names. `names` holds the same identifiers without the schema. `profileId` is the canonical JSON of `[schema, prefix]`. ### `createHierarchyControlMigrations` [#createhierarchycontrolmigrations] ```ts api="@rolebook/sharing-postgres" function createHierarchyControlMigrations(profile: HierarchyControlProfile): readonly ResourceSharingMigration[]; ``` These statements create the control tables, including the group-graph tables. Resource migrations install this same profile for a descriptor that sets `hierarchyControl`. ### `createPolicyCatalogRegistrationMigrations` [#createpolicycatalogregistrationmigrations] ```ts api="@rolebook/sharing-postgres" function createPolicyCatalogRegistrationMigrations(input: { readonly policyStore: QualifiedPolicyStoreConfig; readonly profiles: readonly HierarchyControlProfile[]; }): readonly ResourceSharingMigration[]; ``` ### `QualifiedPolicyStoreConfig` [#qualifiedpolicystoreconfig] ```ts api="@rolebook/sharing-postgres" interface QualifiedPolicyStoreConfig { readonly schema: string; readonly tablePrefix: string; } ``` `schema` and `tablePrefix` name the policy store whose catalog receives the control profiles. ### `PostgresBootstrapIntegrity` [#postgresbootstrapintegrity] ```ts api="@rolebook/sharing-postgres" interface PostgresBootstrapIntegrity { readonly resourceType: string; readonly descriptorDigest: string; readonly profileId: string; readonly policyStoreId: string; } ``` `descriptorDigest` is the `sha256:` identity of the bootstrap row. Pass this object as `groupGraph.integrity` when the adapter confirms structural corruption after the detecting transaction. ### `createPostgresGroupGraphFacade` [#createpostgresgroupgraphfacade] ```ts api="@rolebook/sharing-postgres" function createPostgresGroupGraphFacade(options: PostgresGroupGraphFacadeOptions): Readonly<{ activate(tenantId: string): Promise; link(tenantId: string, child: ResourceRef, parent: ResourceRef): Promise; unlink(tenantId: string, child: ResourceRef, parent: ResourceRef): Promise; repairUnlink(tenantId: string, child: ResourceRef, parent: ResourceRef): Promise; repairBatch(tenantId: string, start: boolean, limit: number): Promise; release(tenantId: string): Promise; }>; ``` `activate` inserts the graph admission. `link` and `unlink` change one direct edge. `repairUnlink`, `repairBatch`, and `release` run only while the graph is quarantined, and each one is authorized for `authority.actor`. `repairBatch` reads at most `limit` rows; `limit` has to be an integer of at least 1, and a smaller or fractional limit is `refused` with `invalid_batch`. A Core denial comes back as `status: "denied"` and `decision`. The facade does not turn that decision into an allow. A structural refusal comes back as `status: "refused"`. An unavailable graph throws `HierarchyUnavailableError` (the outcome type also names `status: "unavailable"`, and the facade throws that reason before returning it). Build a new graph with [`createPostgresGroupGraphControl()`](#createpostgresgroupgraphcontrol). This function is the lower facade for a caller that already holds `tables` and an authority object. ### `PostgresGroupGraphFacadeOptions` [#postgresgroupgraphfacadeoptions] ```ts api="@rolebook/sharing-postgres" interface PostgresGroupGraphFacadeOptions { readonly executor: ParameterizedSqlExecutor; readonly tables: HierarchyControlTableNames; readonly tenantSqlType?: PostgresTenantCodec; readonly teamType: string; readonly identityStability: "registry_incarnation" | "ids_never_reused"; readonly authority: PostgresGroupGraphAuthority; readonly serializableRetry?: SerializableRetryOptions; } ``` `tenantSqlType` selects the tenant key codec (`text` or `uuid`) for the control tables. It has to agree with the codec the profile already bound. `identityStability` is the same explicit declaration the lineage directory was built with. The bootstrap descriptor is `authority.integrity`'s digest. `serializableRetry` bounds how many times a serialization failure starts that transaction again. ### `PostgresGroupGraphAuthority` [#postgresgroupgraphauthority] ```ts api="@rolebook/sharing-postgres" interface PostgresGroupGraphAuthority { readonly actor: ResourceRef; readonly commands: GroupGraphCommands; readonly integrity: PostgresBootstrapIntegrity; readonly policyStore: PolicyStore; readonly sharing: object; readonly identity: ReturnType; registry(tx: ParameterizedSqlExecutor, tenantId: string): GroupRegistryReader; } ``` `actor` is the control subject. `commands` is the compiled control object for this bootstrap resource. `integrity` is the first-party bootstrap provider, and its profile id matches `tables`. `policyStore` is the store [`createVersionedSharing()`](/docs/sharing/versioned) reads, and `sharing` is that instance. `identity` is the object [`createPostgresLocalIdentityProjection()`](#createpostgreslocalidentityprojection) returns; the command reads it inside the transaction and revalidates its facts. A control actor whose groups include `teamType`, or a lineage fact, is `identity_unavailable`. `registry` reads group endpoints in that same transaction. [`createPostgresGroupGraphControl()`](#createpostgresgroupgraphcontrol) compiles that provider and those commands from the policy, the six permissions, the binding ids, and the bootstrap descriptor. ### `PostgresGroupGraphOutcome` [#postgresgroupgraphoutcome] ```ts api="@rolebook/sharing-postgres" type PostgresGroupGraphOutcome = (GroupGraphApplyResult & { readonly progress?: GroupGraphRepairProgress; }) | { readonly status: "denied"; readonly decision: AuthorizationDecision; }; ``` `progress` is present on a repair batch. `denied` carries the Core decision unchanged. ## Inherited access [#inherited-access] The supported way to switch on [inherited access](/docs/sharing/inheritance) (`sharing.inheritance/1`). ### `enablePostgresInheritedReads` [#enablepostgresinheritedreads] ```ts api="@rolebook/sharing-postgres" function enablePostgresInheritedReads(options: EnablePostgresInheritedReadsOptions): void; ``` Enables inherited reads on every type of `definition` that sets `inheritance: "ancestors"`, replacing the internal readiness gate. Call it once, after `defineSharing` and before `createVersionedSharing`. Every option is read once and every adapter is validated before any is changed. It throws when an inheriting type is not on a first-party PostgreSQL adapter or its adapter has no `pageIdentity`, when the inheriting types do not share one control profile (the bootstrap provider's), when the definition also holds a first-party type that does not inherit, when `identity` is not a first-party local identity projection, when the command map's types differ from the opted-in types, or when `configurationGeneration` does not bind this definition and command map. Once a Sharing instance is built from a definition that opts a type in, that type's storage refuses every tenant that is not enrolled (`not_enrolled`) on every read, listing, command, protected write and governed call (lifecycle writers that initialize, delete or move a resource are not refused); enroll a tenant before it uses the type. See [inherited access](/docs/sharing/inheritance). ### `EnablePostgresInheritedReadsOptions` [#enablepostgresinheritedreadsoptions] ```ts api="@rolebook/sharing-postgres" interface EnablePostgresInheritedReadsOptions { readonly definition: SharingDefinition; readonly commands: HierarchyCommandsInput; readonly configurationGeneration: string; readonly authorityEpoch: string; readonly identity: ReturnType; readonly bootstrap: PostgresBootstrapIntegrity; } ``` `configurationGeneration` comes from `hierarchyConfigurationGeneration`. `identity` is the complete local identity projection; an enrolled tenant's reads resolve the actor from it in the read transaction and never consult the generic identity adapter. `bootstrap` is the profile's one bootstrap provider; pass the same object to the control facade. ### `createPostgresHierarchyControl` [#createpostgreshierarchycontrol] ```ts api="@rolebook/sharing-postgres" function createPostgresHierarchyControl(options: CreatePostgresHierarchyControlOptions): PostgresInheritanceControl; ``` The actor-authorized hierarchy control facade. `forTenant({ tenantId, actor })` returns `enroll`, `activate`, `releaseQuarantine` and `repairHeights` (each needs the matching bootstrap action) and `structure` with `create`, `move` and `delete` (each needs the configured command permissions on the resources involved). Every action is one transaction decided by Rolebook; a non-applied outcome rolls back. It throws when the Sharing definition's opted-in types and the command map differ. ### `CreatePostgresHierarchyControlOptions` [#createpostgreshierarchycontroloptions] ```ts api="@rolebook/sharing-postgres" interface CreatePostgresHierarchyControlOptions { readonly sharing: VersionedResourceSharing; readonly policy: RolebookPolicy; readonly commands: HierarchyCommandsInput; readonly bootstrap: PostgresBootstrapIntegrity; readonly authorityEpoch: string; readonly configurationGeneration: string; readonly serializableRetry?: SerializableRetryOptions; } ``` Use the same `bootstrap`, `authorityEpoch` and `configurationGeneration` as the inherited read configuration. ### `PostgresInheritanceControl` [#postgresinheritancecontrol] ```ts api="@rolebook/sharing-postgres" interface PostgresInheritanceControl { forTenant(scope: { readonly tenantId: string; readonly actor: ResourceRef; }): { enroll(input: { readonly idempotencyKey: string; }): Promise; activate(input: { readonly idempotencyKey: string; }): Promise; releaseQuarantine(input: { readonly idempotencyKey: string; }): Promise; repairHeights(): Promise; readonly structure: ReturnType["structure"]; }; } ``` The facade `createPostgresHierarchyControl` returns. After the actor is authorized, `enroll` and `activate` answer `unlinked_resources`, on the same control transaction and before changing tenant state, while the tenant has a row of an inheriting type that the managed hierarchy does not place: existing resources are not adopted. ### `PostgresHierarchyControlResult` [#postgreshierarchycontrolresult] ```ts api="@rolebook/sharing-postgres" type PostgresHierarchyControlResult = HierarchyControlResult; ``` An actor control action's answer. Through this facade `enroll` and `activate` may also answer `unlinked_resources` with the first unplaced type, after the actor is authorized. ### `runPostgresHierarchyInventory` [#runpostgreshierarchyinventory] ```ts api="@rolebook/sharing-postgres" function runPostgresHierarchyInventory(control: PostgresInheritanceControl, tenantId: string, batchSize?: number): Promise; ``` One bounded, resumable batch of the activation inventory for a tenant in `building`: call it until it answers `complete`, then `activate`. An operator job, not an actor command; it changes no authority. Activation refuses while any stored membership on a would-be inheriting scope carries an allow that would reach further. ### `createPostgresBootstrapIntegrity` [#createpostgresbootstrapintegrity] ```ts api="@rolebook/sharing-postgres" function createPostgresBootstrapIntegrity(options: { readonly profile: HierarchyControlProfile; readonly policyStore: QualifiedPolicyStoreConfig; readonly descriptor: PostgresBootstrapRowDescriptor; }): PostgresBootstrapIntegrity; ``` The profile's bootstrap integrity provider over the application table that holds each tenant's bootstrap row (the resource the bootstrap actions are checked on). Inherited reads prove the row in their own snapshot; commands lock it. ### `PostgresBootstrapRowDescriptor` [#postgresbootstraprowdescriptor] ```ts api="@rolebook/sharing-postgres" interface PostgresBootstrapRowDescriptor { readonly resourceType: string; readonly schema: string; readonly table: string; readonly tenantColumn: string; readonly idColumn: string; readonly versionColumn: string; readonly incarnationColumn: string; readonly fields?: readonly { readonly field: string; readonly column: string; readonly codec: "text" | "boolean" | "safe-integer"; readonly nullable?: boolean; }[]; } ``` Where the bootstrap row lives: its table and the tenant, id, version and incarnation columns, plus optional fields the bootstrap resource exposes to policy conditions. ### `HierarchyControlResult` [#hierarchycontrolresult] An actor control action's answer (`enrolled`, `already_enrolled`, `activated`, `inventory_incomplete`, `released`, `verifying`, `repairing`, `repaired`, `not_enrolled`, `denied`, `conflict`, `unlinked_resources`). `denied` and `conflict` are ordinary outcomes; tenant-level unavailability throws `HierarchyUnavailableError`. Declared by the control runtime this package bundles; it has no signature block here. ### `HierarchyControlJobResult` [#hierarchycontroljobresult] An operator job's answer. The inventory answers `progress` until it is `complete`. Declared by the control runtime this package bundles; it has no signature block here. ## Lifecycle [#lifecycle] ### `InitializePostgresSharingResourceInput` [#initializepostgressharingresourceinput] ```ts api="@rolebook/sharing-postgres" interface InitializePostgresSharingResourceInput { readonly tenantId: string; readonly resourceId: string; readonly owner: OwnerRef; readonly actor: ResourceRef; readonly occurredAt: Date; } ``` Tenant, resource, intended owner, actor, and time of an initialization. ### `InitializePostgresSharingResourceResult` [#initializepostgressharingresourceresult] ```ts api="@rolebook/sharing-postgres" type InitializePostgresSharingResourceResult = | "applied" | "already_initialized" | "identity_ineligible" | "owner_mismatch" | "group_owner" | "not_found"; ``` ### `DeletePostgresResourceInTransactionInput` [#deletepostgresresourceintransactioninput] ```ts api="@rolebook/sharing-postgres" interface DeletePostgresResourceInTransactionInput extends PostgresLifecycleInput { readonly tenantId: string; readonly resourceId: string; readonly deleteResource: ( transaction: SerializablePostgresTransaction, ) => Promise; } ``` A deletion: the key, the actor and subjects to fence, idempotency key and fingerprint, the expected resource version and sharing revision, and your `deleteResource` callback. ### `MovePostgresResourceInTransactionInput` [#movepostgresresourceintransactioninput] ```ts api="@rolebook/sharing-postgres" interface MovePostgresResourceInTransactionInput extends PostgresLifecycleInput { readonly fromTenantId: string; readonly toTenantId: string; readonly resourceId: string; readonly resultingResourceVersion: string; readonly moveResource: ( transaction: SerializablePostgresTransaction, ) => Promise; } ``` A move: source and destination tenant, the resulting resource version, the same fencing and idempotency fields, and your `moveResource` callback. ### `PostgresLifecycleApplicationResult` [#postgreslifecycleapplicationresult] ```ts api="@rolebook/sharing-postgres" type PostgresLifecycleApplicationResult = "applied" | "not_found" | "conflict"; ``` What your lifecycle callback returns. ### `PostgresLifecycleResult` [#postgreslifecycleresult] ```ts api="@rolebook/sharing-postgres" type PostgresLifecycleResult = | "applied" | "already_applied" | "not_found" | "conflict" | "identity_ineligible"; ``` What a lifecycle method returns. ## Fences [#fences] ### `PostgresEligibilityFence` [#postgreseligibilityfence] ```ts api="@rolebook/sharing-postgres" type PostgresEligibilityFence = (input: { readonly executor: ParameterizedSqlExecutor; readonly tenantId: string; readonly subjects: readonly ResourceRef[]; readonly ownerCandidates?: readonly ResourceRef[]; }) => Promise; ``` Locks and verifies tenant eligibility of `subjects` inside the mutation transaction, and may refuse `ownerCandidates`. Only `true` counts as eligible. ### `PostgresEligibilityReader` [#postgreseligibilityreader] ```ts api="@rolebook/sharing-postgres" type PostgresEligibilityReader = (input: { readonly executor: ParameterizedSqlExecutor; readonly tenantId: string; readonly subjects: readonly ResourceRef[]; readonly evaluatedAt: string; }) => Promise; ``` The read-only form of a `PostgresEligibilityFence`, used by listing pages. It gives the same answer from the same authoritative rows, read through `executor`, which is the page's `SERIALIZABLE READ ONLY` transaction. It must not lock or write: `FOR SHARE` cannot run there, and a reader that tries makes the page `snapshot_unavailable`. Judge every time-dependent fact at `evaluatedAt`, the page's instant, and never read another clock. `createPostgresMembershipEligibilityFence()` and `createPostgresLocalIdentityProjection().lockEligibleSubjects` carry their own reader, recognized by provenance. If you wrap one of them in a function of your own, the wrapper is a custom fence: pass a reader wrapped the same way as `readEligibleSubjects`. ### `PostgresEligibilityEvidence` [#postgreseligibilityevidence] ```ts api="@rolebook/sharing-postgres" interface PostgresEligibilityEvidence { readonly eligible: boolean; readonly expiryDependencies: readonly string[]; } ``` What a reader returns. `eligible` must be a boolean, and only `true` makes the subjects eligible; an actor it refuses receives an empty exhausted page. `expiryDependencies` lists every instant at which a time-sensitive fact behind the answer changes it: a membership or projection expiry, and equally the end of a refusing condition. Each is an ISO 8601 UTC instant with three or six fractional digits, compared in SQL at microsecond precision. Leave it empty only when the answer depends on no time. The page seals all of them, and one that passes before the seal refuses the page with `expiry_crossed`. A boolean, a missing field, or a malformed instant is `identity_evidence_missing`, never a page. ### `createPostgresMembershipEligibilityFence` [#createpostgresmembershipeligibilityfence] ```ts api="@rolebook/sharing-postgres" function createPostgresMembershipEligibilityFence( descriptor: PostgresMembershipEligibilityDescriptor, ): PostgresEligibilityFence; ``` A fence over an organization-member table: locks each member row `FOR SHARE` and requires the exact tenant and subject. It carries its own listing reader, which reads the same rows unlocked and declares no expiry, because row existence depends on no time. ### `PostgresMembershipEligibilityDescriptor` [#postgresmembershipeligibilitydescriptor] ```ts api="@rolebook/sharing-postgres" interface PostgresMembershipEligibilityDescriptor { readonly table: QualifiedIdentifier; readonly tenantColumn: string; readonly subjectIdColumn: string; readonly subjectType?: string; } ``` The member table, its tenant and subject ID columns, and the subject type. ### `PostgresInvitationRecipientFence` [#postgresinvitationrecipientfence] ```ts api="@rolebook/sharing-postgres" type PostgresInvitationRecipientFence = (input: { readonly executor: ParameterizedSqlExecutor; readonly verification: InvitationRecipientFenceInput; }) => Promise; ``` Checks an email invitation's recipient while it is consumed. ### `createPostgresEmailInvitationRecipientFence` [#createpostgresemailinvitationrecipientfence] ```ts api="@rolebook/sharing-postgres" function createPostgresEmailInvitationRecipientFence( descriptor: PostgresEmailInvitationRecipientFenceDescriptor, ): PostgresInvitationRecipientFence; ``` Locks the membership and user rows `FOR SHARE` and requires a verified email equal to the invitation's, under `lower_trim` (default) or `exact` normalization. ### `PostgresEmailInvitationRecipientFenceDescriptor` [#postgresemailinvitationrecipientfencedescriptor] ```ts api="@rolebook/sharing-postgres" interface PostgresEmailInvitationRecipientFenceDescriptor { readonly membershipTable: QualifiedIdentifier; readonly membershipTenantColumn: string; readonly membershipSubjectIdColumn: string; readonly userTable: QualifiedIdentifier; readonly userIdColumn: string; readonly userEmailColumn: string; readonly userEmailVerifiedColumn: string; readonly subjectType?: string; readonly emailNormalization?: "lower_trim" | "exact"; } ``` Membership and user tables and their columns, subject type, email normalization. ### `PostgresAuthorizationFactFence` [#postgresauthorizationfactfence] ```ts api="@rolebook/sharing-postgres" type PostgresAuthorizationFactFence = (input: { readonly executor: ParameterizedSqlExecutor; readonly tenantId: string; readonly facts: readonly TransactionalAuthorizationFact[]; }) => Promise; ``` Revalidates a mutation's authorization facts in its transaction: `true` proceeds, `"conflict"` re-authorizes, anything else is `identity_ineligible`. ### `PostgresAuthorizationFactFenceResult` [#postgresauthorizationfactfenceresult] ```ts api="@rolebook/sharing-postgres" type PostgresAuthorizationFactFenceResult = boolean | "conflict"; ``` ### `createPostgresWorkspaceRoleAuthorizationFactFence` [#createpostgresworkspaceroleauthorizationfactfence] ```ts api="@rolebook/sharing-postgres" function createPostgresWorkspaceRoleAuthorizationFactFence( descriptor: PostgresWorkspaceRoleAuthorizationFactDescriptor, ): PostgresAuthorizationFactFence; ``` Locks member rows and compares the exact tenant, subject, membership ID, and role behind mapped workspace assignments. ### `PostgresWorkspaceRoleAuthorizationFactDescriptor` [#postgresworkspaceroleauthorizationfactdescriptor] ```ts api="@rolebook/sharing-postgres" interface PostgresWorkspaceRoleAuthorizationFactDescriptor extends PostgresMembershipEligibilityDescriptor { readonly factType: string; readonly memberIdColumn: string; readonly roleColumn: string; } ``` The member-table descriptor plus the fact type, member ID column, and role column. ## Migrations [#migrations] ### `createResourceSharingMigrations` [#createresourcesharingmigrations] ```ts api="@rolebook/sharing-postgres" function createResourceSharingMigrations( descriptor: PostgresResourceDescriptor, ): readonly ResourceSharingMigration[]; ``` The ordered, idempotent migration steps for one descriptor. See [migrations](/docs/sharing-postgres/migrations). ### `createResourceSharingRollbackMigrations` [#createresourcesharingrollbackmigrations] ```ts api="@rolebook/sharing-postgres" function createResourceSharingRollbackMigrations( descriptor: PostgresResourceDescriptor, options?: ResourceSharingRollbackOptions, ): readonly ResourceSharingRollbackMigration[]; ``` Ordered `DROP` steps for sharing-owned state. Keeps audit history unless `dropAudit` is true; never drops the application's revision column or unique index. ### `ResourceSharingMigration` [#resourcesharingmigration] ```ts api="@rolebook/sharing-postgres" interface ResourceSharingMigration { readonly name: string; readonly sql: string; readonly apply?: (executor: Pick) => Promise; } ``` One named migration step. ### `ResourceSharingRollbackMigration` [#resourcesharingrollbackmigration] ```ts api="@rolebook/sharing-postgres" interface ResourceSharingRollbackMigration { readonly name: string; readonly sql: string; readonly dataLoss?: string; } ``` One named rollback step, with a `dataLoss` note when it destroys data. ### `ResourceSharingRollbackOptions` [#resourcesharingrollbackoptions] ```ts api="@rolebook/sharing-postgres" interface ResourceSharingRollbackOptions { readonly dropAudit?: boolean; } ``` `dropAudit: true` also drops the audit table. ### `applyPostgresMigrations` [#applypostgresmigrations] ```ts api="@rolebook/sharing-postgres" function applyPostgresMigrations(executor: MigrationExecutor, steps: readonly PostgresMigrationStep[], options?: ApplyPostgresMigrationsOptions): Promise; ``` Applies steps one transaction each, with `SET LOCAL lock_timeout`, retrying lock timeouts, deadlocks, and serialization failures with backoff. Throws `PostgresMigrationError`. ### `ApplyPostgresMigrationsOptions` [#applypostgresmigrationsoptions] ```ts api="@rolebook/sharing-postgres" interface ApplyPostgresMigrationsOptions { readonly lockTimeoutMs?: number; readonly attempts?: number; readonly backoffMs?: (retry: number) => number; readonly wait?: (milliseconds: number) => Promise; } ``` `lockTimeoutMs` (default 5,000), `attempts` (default 5), `backoffMs`, `wait`. ### `PostgresMigrationStep` [#postgresmigrationstep] ```ts api="@rolebook/sharing-postgres" interface PostgresMigrationStep { readonly name: string; readonly sql: string; readonly apply?: (executor: Pick) => Promise; } ``` A named SQL step `applyPostgresMigrations` accepts. ### `PostgresMigrationError` [#postgresmigrationerror] ```ts api="@rolebook/sharing-postgres" class PostgresMigrationError extends Error { readonly code: "POSTGRES_MIGRATION_FAILED"; readonly step: string; readonly attempts: number; readonly sqlState: string | undefined; constructor(step: string, attempts: number, cause: unknown); } ``` The step that failed, after how many attempts, its SQLSTATE, and the driver error as `cause`. ### `sharingTables` [#sharingtables] ```ts api="@rolebook/sharing-postgres" function sharingTables(descriptor: PostgresResourceDescriptor): SharingTableNames; ``` The sharing table names for a descriptor's `sharingTablePrefix`. ### `SharingTableNames` [#sharingtablenames] ```ts api="@rolebook/sharing-postgres" interface SharingTableNames { readonly binding: string; readonly owner: string; readonly member: string; readonly invitation: string; readonly audit: string; readonly idempotency: string; readonly lifecycle: string; readonly revisionFloor: string; } ``` ### `quoteIdentifier` [#quoteidentifier] ```ts api="@rolebook/sharing-postgres" function quoteIdentifier(identifier: QualifiedIdentifier): string; ``` Validates and double-quotes an identifier or a qualified `[schema, name]`. ### `QualifiedIdentifier` [#qualifiedidentifier] ```ts api="@rolebook/sharing-postgres" type QualifiedIdentifier = string | readonly string[]; ``` ### `assertPostgresSharingSearchPath` [#assertpostgressharingsearchpath] ```ts api="@rolebook/sharing-postgres" function assertPostgresSharingSearchPath( executor: ParameterizedSqlExecutor, options: PostgresSearchPathCheckOptions, ): Promise; ``` Checks that the adapter-owned tables resolve to `expectedSchema` for the connection's `search_path`. The adapter names its sharing, policy store, and journal tables without a schema, so a migration role and an application role with different `search_path` settings could otherwise create and read different tables. Resolves with one entry per table checked, and throws [`PostgresSearchPathError`](#postgressearchpatherror) when a table is missing, resolves to another schema, or is shadowed by an earlier schema or a temporary table. Run it at startup with the application's own connection settings. ### `PostgresSearchPathCheckOptions` [#postgressearchpathcheckoptions] ```ts api="@rolebook/sharing-postgres" interface PostgresSearchPathCheckOptions { readonly expectedSchema: string; readonly resources?: readonly Pick[]; readonly policyStoreTablePrefix?: string; readonly journalPrefix?: string; } ``` Names the schema the tables must resolve to and which table sets to check: the sharing tables of each resource, the policy store tables, and the protected-write journal tables. ### `PostgresSearchPathResolution` [#postgressearchpathresolution] ```ts api="@rolebook/sharing-postgres" interface PostgresSearchPathResolution { readonly table: string; readonly resolvedSchema: string | null; } ``` The schema one table name resolves to, or `null` when the name does not resolve. ### `PostgresSearchPathError` [#postgressearchpatherror] ```ts api="@rolebook/sharing-postgres" class PostgresSearchPathError extends Error { readonly expectedSchema: string; readonly mismatches: readonly PostgresSearchPathResolution[]; readonly code: "SEARCH_PATH_MISMATCH"; constructor(expectedSchema: string, mismatches: readonly PostgresSearchPathResolution[]); } ``` Thrown by [`assertPostgresSharingSearchPath`](#assertpostgressharingsearchpath). `mismatches` lists every table that did not resolve to `expectedSchema`. ## Policy store [#policy-store] ### `createPostgresPolicyStore` [#createpostgrespolicystore] ```ts api="@rolebook/sharing-postgres" function createPostgresPolicyStore(options: CreatePostgresPolicyStoreOptions): PolicyStore; ``` A `PolicyStore` over the policy-store tables, with serializable retries. ### `CreatePostgresPolicyStoreOptions` [#createpostgrespolicystoreoptions] ```ts api="@rolebook/sharing-postgres" interface CreatePostgresPolicyStoreOptions { readonly executor: ParameterizedSqlExecutor; readonly tablePrefix?: string; readonly schema?: string; readonly serializableRetry?: SerializableRetryOptions; } ``` `executor`, `tablePrefix` (default `rolebook`), `schema`, `serializableRetry`. With `schema` every statement is qualified by it and the store has a known issuer `[schema, tablePrefix]`; protected writes and authorized queries require it. Without it the tables resolve through the search path. ### `createPostgresPolicyFence` [#createpostgrespolicyfence] ```ts api="@rolebook/sharing-postgres" function createPostgresPolicyFence(options?: { readonly tablePrefix?: string; readonly schema?: string; }): PostgresPolicyFence; ``` The policy fence for `fencePolicy`. Use the store's `tablePrefix` and `schema`. Protected writes and authorized queries accept the adapter only when its fence and the policy store were both constructed with the same explicit `schema` and `tablePrefix`; a fence without `schema` never matches. ### `PostgresPolicyFence` [#postgrespolicyfence] ```ts api="@rolebook/sharing-postgres" type PostgresPolicyFence = (input: { readonly executor: ParameterizedSqlExecutor; readonly tenantId: string; readonly expectedPolicy: ExpectedPolicy; }) => Promise; ``` Reads the active generation and tenant-role revision through the mutation's own executor. ### `createPolicyStoreMigrations` [#createpolicystoremigrations] ```ts api="@rolebook/sharing-postgres" function createPolicyStoreMigrations(options?: { readonly tablePrefix?: string; }): readonly ResourceSharingMigration[]; ``` Migration steps for the policy-store tables. ### `createPolicyStoreRollbackMigrations` [#createpolicystorerollbackmigrations] ```ts api="@rolebook/sharing-postgres" function createPolicyStoreRollbackMigrations(options?: { readonly tablePrefix?: string; }): readonly ResourceSharingRollbackMigration[]; ``` Rollback for the policy-store tables: one step whose first statement refuses while the hierarchy policy catalog is not empty, then drops the header, catalog and policy tables in one transaction. ### `policyStoreTables` [#policystoretables] ```ts api="@rolebook/sharing-postgres" function policyStoreTables(tablePrefix?: string): PolicyStoreTableNames; ``` The policy-store table names for a prefix. ### `PolicyStoreTableNames` [#policystoretablenames] ```ts api="@rolebook/sharing-postgres" interface PolicyStoreTableNames { readonly version: string; readonly active: string; readonly activation: string; readonly tenantRole: string; readonly tenantRoleRevision: string; readonly audit: string; } ``` ## Executor and transactions [#executor-and-transactions] ### `ParameterizedSqlExecutor` [#parameterizedsqlexecutor] ```ts api="@rolebook/sharing-postgres" interface ParameterizedSqlExecutor { query( sql: string, values?: readonly SqlValue[], ): Promise>; transaction( options: PostgresTransactionOptions, operation: (transaction: SerializablePostgresTransaction) => Promise, ): Promise; } ``` The executor seam: parameterized queries and `SERIALIZABLE` transactions. ### `PostgresTransactionOptions` [#postgrestransactionoptions] ```ts api="@rolebook/sharing-postgres" interface PostgresTransactionOptions { readonly isolationLevel: "serializable"; } ``` ### `SerializablePostgresTransaction` [#serializablepostgrestransaction] ```ts api="@rolebook/sharing-postgres" type SerializablePostgresTransaction = ParameterizedSqlExecutor & { readonly [serializableTransaction]: true; }; ``` An executor branded as a `SERIALIZABLE` transaction. ### `SqlResult` [#sqlresult] ```ts api="@rolebook/sharing-postgres" interface SqlResult { readonly rows: readonly TRow[]; readonly rowCount: number; } ``` ### `SqlRow` [#sqlrow] ```ts api="@rolebook/sharing-postgres" type SqlRow = Readonly>; ``` ### `SqlValue` [#sqlvalue] ```ts api="@rolebook/sharing-postgres" type SqlValue = string | number | boolean | Date | null | readonly string[]; ``` The values the adapter binds. ### `asSerializablePostgresTransaction` [#asserializablepostgrestransaction] ```ts api="@rolebook/sharing-postgres" function asSerializablePostgresTransaction( transaction: ParameterizedSqlExecutor, ): SerializablePostgresTransaction; ``` Compile-time assertion that an ORM transaction you opened is `SERIALIZABLE`. It inspects nothing; lifecycle methods still require `withLifecycleTransaction()`'s transaction. ### `withSerializableRetry` [#withserializableretry] ```ts api="@rolebook/sharing-postgres" function withSerializableRetry( executor: ParameterizedSqlExecutor, operation: (transaction: SerializablePostgresTransaction) => Promise, options?: SerializableRetryOptions, ): Promise; ``` Runs an idempotent unit of work in a retried `SERIALIZABLE` transaction. ### `withSerializableTransaction` [#withserializabletransaction] ```ts api="@rolebook/sharing-postgres" function withSerializableTransaction( executor: ParameterizedSqlExecutor, operation: (transaction: SerializablePostgresTransaction) => Promise, options?: SerializableRetryOptions, ): Promise; ``` Runs caller-owned application and sharing work in one retried `SERIALIZABLE` transaction. ### `SerializableRetryOptions` [#serializableretryoptions] ```ts api="@rolebook/sharing-postgres" interface SerializableRetryOptions { readonly attempts?: number; readonly wait?: (milliseconds: number) => Promise; readonly backoffMs?: (retry: number) => number; } ``` `attempts` (default 3, including the first), `backoffMs` (0 to 1,000 ms), `wait`. ### `isRetryableSerializationError` [#isretryableserializationerror] ```ts api="@rolebook/sharing-postgres" function isRetryableSerializationError(error: unknown): boolean; ``` True for SQLSTATE `40001` or `40P01`, also when wrapped in an error's `cause` chain. ## Errors [#errors] ### `InvalidPostgresCursorError` [#invalidpostgrescursorerror] ```ts api="@rolebook/sharing-postgres" class InvalidPostgresCursorError extends InvalidCursorError { constructor(resourceSqlType: "text" | "uuid"); } ``` A listing cursor the ID column cannot hold. An `InvalidCursorError`. ### `InvalidPostgresAuditCursorError` [#invalidpostgresauditcursorerror] ```ts api="@rolebook/sharing-postgres" class InvalidPostgresAuditCursorError extends InvalidCursorError { constructor(message?: string); } ``` An audit cursor that is malformed or names no event of this incarnation. An `InvalidCursorError`. ### `PostgresSharingRowError` [#postgressharingrowerror] ```ts api="@rolebook/sharing-postgres" class PostgresSharingRowError extends Error { readonly code: "POSTGRES_SHARING_ROW_INVALID"; readonly table: string; readonly reason: string; constructor(table: string, reason: string); } ``` An invitation or audit row that does not decode, or an audit page whose cursor cannot be issued. ### `PostgresLifecycleConflictError` [#postgreslifecycleconflicterror] ```ts api="@rolebook/sharing-postgres" class PostgresLifecycleConflictError extends Error { readonly code: "POSTGRES_LIFECYCLE_CONFLICT"; constructor(message: string); } ``` A lifecycle postcondition failed. The transaction is rollback-only. ### `PolicyStoreRowError` [#policystorerowerror] ```ts api="@rolebook/sharing-postgres" class PolicyStoreRowError extends Error { readonly table: string; readonly reason: string; constructor(table: string, reason: string); } ``` A policy-store row that does not decode. `isPolicyStoreRowError` recognizes it. ## Transaction and clock foundations [#transaction-and-clock-foundations] These supporting exports are used by the PostgreSQL [protected application update API](/docs/sharing-postgres/protected-updates). Metadata and fixtures alone do not authorize an application write. The supported wrapper is resource/action scoped; field-mediated post-state enforcement and application operational integration are separate contracts. ### `PostgresAuthorizationClock` [#postgresauthorizationclock] ```ts api="@rolebook/sharing-postgres" interface PostgresAuthorizationClock { readonly snapshotId: string; /** Observation time, not a claim of an exact MVCC snapshot creation timestamp. */ readonly snapshotObservedAt: string; readonly evaluatedAt: string; } ``` Descriptive timing and bounded snapshot evidence from a serializable PostgreSQL transaction. `snapshotObservedAt` is observation time, not the exact creation time of the MVCC snapshot. ### `readPostgresAuthorizationClock` [#readpostgresauthorizationclock] ```ts api="@rolebook/sharing-postgres" function readPostgresAuthorizationClock(transaction: SerializablePostgresTransaction): Promise; ``` Read immediately after isolation verification on the same transaction connection that will load authority. Verifies serializable isolation and hashes the raw PostgreSQL snapshot into a bounded opaque identifier. Throws `ConsistencyUnavailableError` when isolation or clock evidence is unavailable. It does not attest the provenance of facts loaded later. ### `readPostgresSealTime` [#readpostgressealtime] ```ts api="@rolebook/sharing-postgres" function readPostgresSealTime(transaction: SerializablePostgresTransaction): Promise; ``` Reads the advancing database `clock_timestamp()` on the supplied transaction and returns its ISO timestamp. This is descriptive evidence: driver `Date` values lose PostgreSQL microseconds, so a production expiry fence must compare in SQL against the advancing database clock. This helper alone does not seal a protected write. ### `PgPoolConnection` [#pgpoolconnection] ```ts api="@rolebook/sharing-postgres" interface PgPoolConnection { query(sql: string, values?: unknown[]): Promise<{ rows: Record[]; rowCount: number | null; command?: string; }>; release(error?: Error | boolean): void; on?(event: "error", listener: (error: Error) => void): unknown; removeListener?(event: "error", listener: (error: Error) => void): unknown; } ``` The structural connection boundary accepted by the executor, compatible with a checked-out `pg` client. The executor uses parameterized queries and releases the connection when the transaction completes. For event-emitting drivers, wrappers must forward **both** `on` and `removeListener` from the same checked-out client, preserving the receiver. They are optional only for connections that do not emit errors. A wrapper that hides both methods also hides transport/session errors from the executor; exposing only one method is rejected before a query is issued. ```ts import type { PgPoolConnection } from "@rolebook/sharing-postgres"; function wrapEventEmittingClient(client: Required): PgPoolConnection { return { query: client.query.bind(client), release: client.release.bind(client), on: client.on.bind(client), removeListener: client.removeListener.bind(client), }; } ``` The executor observes checked-out client errors for both standalone queries (including receipt lookup and outbox operations) and transactions. A client error observed before query/transaction completion prevents a successful result and discards the connection. Its listener remains attached through release and is then removed; a driver error during COMMIT remains an uncertain outcome requiring receipt reconciliation. Applications still own pool-level idle-error handling and pool shutdown. No automatic replay of queries, callbacks or external delivery is introduced. ### `PgPoolSource` [#pgpoolsource] ```ts api="@rolebook/sharing-postgres" interface PgPoolSource { connect(): Promise; } ``` A pool-like source of checked-out connections. The application retains ownership of pool creation and shutdown. ### `DetachedPostgresTransactionError` [#detachedpostgrestransactionerror] ```ts api="@rolebook/sharing-postgres" class DetachedPostgresTransactionError extends Error { readonly code: "GUARD_DETACHED"; constructor(); } ``` Rejects use of a transaction handle outside its active callback lifetime with `GUARD_DETACHED`. ### `PostgresTransactionRolledBackError` [#postgrestransactionrolledbackerror] ```ts api="@rolebook/sharing-postgres" class PostgresTransactionRolledBackError extends Error { readonly code: "TRANSACTION_ROLLED_BACK"; constructor(); } ``` Reports a `ROLLBACK` completion tag where commit success was expected. The executor does not treat that outcome as a successful transaction. ### `PostgresCommitOutcomeUnknownError` [#postgrescommitoutcomeunknownerror] ```ts api="@rolebook/sharing-postgres" class PostgresCommitOutcomeUnknownError extends Error { readonly code: "COMMIT_OUTCOME_UNKNOWN"; constructor(cause: unknown); } ``` Reports an unacknowledged commit outcome. The connection is discarded without another statement; do not interpret this as proof of rollback or blindly replay the callback. Use the protected adapter's scoped `lookupReceipt()` with the exact original intent to reconcile a durable receipt before deciding whether to retry. Absence alone does not prove an in-flight commit cannot succeed. ### `createPgExecutor` [#createpgexecutor] ```ts api="@rolebook/sharing-postgres" function createPgExecutor(pool: PgPoolSource): ParameterizedSqlExecutor; ``` Adapts a pool to the parameterized SQL executor. Each transaction uses one checked-out client; nested and detached transaction use is rejected. Accepted queries are drained before rollback and release, and there is no automatic callback replay. This is an executor, not an authorization guard: application SQL is trusted and must not issue `COMMIT`, `ROLLBACK` or isolation changes itself. ## Protected application updates [#protected-application-updates] The public PostgreSQL wrapper supports one resource/action SQL update with complete local authority. It is not a field-mediated API or a transaction spanning HTTP calls. See [the guide](/docs/sharing-postgres/protected-updates) for the retained-authority postcondition, explicit migration ownership, receipt reconciliation and separate-worker delivery. ### `TransactionalTenantIdentityResolver` [#transactionaltenantidentityresolver] ```ts api="@rolebook/sharing-postgres" interface TransactionalTenantIdentityResolver { resolvePrincipalInTransaction(input: { readonly executor: ParameterizedSqlExecutor; readonly tenantId: string; readonly subject: ResourceRef; }): Promise<{ readonly principal: TenantPrincipal; /** Attests complete eligibility, assignments, groups and policy-visible attributes, including absence. */ readonly authority: "complete-local-projection"; /** Exact PostgreSQL timestamp text for every identity/group/projection expiry; empty only when none exist. */ readonly expiryDependencies: readonly string[]; /** Counters actually read locally, including a subject projection covering absent assignments/groups. */ readonly revisions: readonly AuthorityRevision[]; }>; } ``` Trusted transaction-local identity boundary. Reads through the supplied executor and attests the complete local eligibility, assignments, groups and policy-visible attributes, including absence. Every contributing source must participate in the fence protocol. Exact expiry dependencies are PostgreSQL timestamp strings; an empty array is valid only when none exist. Prefer `createPostgresLocalIdentityProjection()` for its complete-row contract; this interface does not attest remote-provider freshness. ### `ProtectedUpdateIntent` [#protectedupdateintent] ```ts api="@rolebook/sharing-postgres" interface ProtectedUpdateIntent { readonly resource: ResourceRef; readonly action: string; readonly incarnationId: string; readonly idempotencyKey: string; /** Complete application intent; captured and hashed before SQL. */ readonly payload: unknown; /** The callback must advance to this version without changing incarnation, ancestry, owner or sharing. */ readonly postVersion: string; } ``` Captured resource/action intent bound to the incarnation, idempotency key, complete application payload and resulting resource version. The callback must reach `postVersion` while retaining incarnation, ancestry, owner and sharing state. Hashing `payload` establishes replay identity; it does not map fields to columns or enforce field-level post-state policy. ### `ProtectedUpdateGuard` [#protectedupdateguard] ```ts api="@rolebook/sharing-postgres" interface ProtectedUpdateGuard { /** Cooperative cancellation; SQL containment is also enforced independently. */ readonly signal: AbortSignal; readonly executor: ParameterizedSqlExecutor; readonly resource: TrustedResource; readonly resourceVersion: string; readonly incarnationId: string; readonly metadata: AuthorizationDecisionMetadata | HierarchyAuthorizationDecisionMetadata; readonly payload: unknown; } ``` The callback-scoped executor, trusted resource snapshot, pre-version, incarnation, captured payload and decision metadata. All queries must finish before the callback returns. The executor detaches before sealing and cannot be reused later. Observe `signal` for cooperative cancellation; arbitrary JavaScript CPU cannot be preempted. ### `ProtectedWriteDeniedError` [#protectedwritedeniederror] ```ts api="@rolebook/sharing-postgres" class ProtectedWriteDeniedError extends Error { readonly code = "PROTECTED_WRITE_DENIED"; constructor(); } ``` Resource/action authorization refused before the callback. Field-only permission cannot admit this raw SQL path. Reports `PROTECTED_WRITE_DENIED`. ### `ProtectedWriteTimeoutError` [#protectedwritetimeouterror] ```ts api="@rolebook/sharing-postgres" class ProtectedWriteTimeoutError extends Error { readonly code = "PROTECTED_WRITE_TIMEOUT"; constructor(options?: { readonly cause?: unknown; }); } ``` A lock wait that PostgreSQL ends during the managed delete or move lock phase also reports this error, with the driver error as `cause`. The protected scope exceeded its configured execution lifetime. Reports `PROTECTED_WRITE_TIMEOUT`; later guarded SQL rejects and database work is drained before rollback/release. Pool acquisition and driver setup precede this deadline, and COMMIT follows it; applications also need connection/request bounds. ### `ProtectedWritePostconditionError` [#protectedwritepostconditionerror] ```ts api="@rolebook/sharing-postgres" class ProtectedWritePostconditionError extends Error { readonly code = "PROTECTED_WRITE_POSTCONDITION_FAILED"; constructor(); } ``` The update violated its declared postcondition or retained authority. The application write and journal roll back. Reports `PROTECTED_WRITE_POSTCONDITION_FAILED`. ### `ProtectedWriteRefusedError` [#protectedwriterefusederror] ```ts api="@rolebook/sharing-postgres" class ProtectedWriteRefusedError extends Error { readonly code = "PROTECTED_WRITE_REFUSED"; readonly refusal: "hierarchy_not_leaf" | "hierarchy_cycle" | "ancestry_cap" | "hierarchy_edge_refused" | "hierarchy_exists"; constructor(refusal: ProtectedWriteRefusedError["refusal"]); } ``` An enrolled managed delete or move that every authorization check (the protected action on the target included) allowed, refused by the stored hierarchy: `hierarchy_not_leaf` (the resource has children), `hierarchy_cycle` (the destination is the resource or below it), `ancestry_cap` (the moved subtree would end below 16 ancestors), `hierarchy_edge_refused` (the policy does not allow that parent type) or `hierarchy_exists` (the destination is the current parent). Nothing was changed and no receipt was written. ### `CreatePostgresProtectedWriteAdapterOptions` [#createpostgresprotectedwriteadapteroptions] ```ts api="@rolebook/sharing-postgres" interface CreatePostgresProtectedWriteAdapterOptions { readonly adapter: PostgresSharingAdapter; readonly sharing: VersionedResourceSharing; readonly identity: TransactionalTenantIdentityResolver; readonly environmentId: string; readonly authorityEpoch: string; readonly journalPrefix: string; readonly maxLifetimeMs?: number; readonly managed?: PostgresManagedWriteDescriptor; readonly managedMove?: PostgresManagedMoveDescriptor; readonly hierarchy?: { readonly control: PostgresInheritanceControl; readonly parentIdColumn?: string; }; } ``` `hierarchy` enables managed delete and managed move on hierarchy-enrolled tenants. `control` is the deployment's hierarchy control facade (`createPostgresHierarchyControl`), built from the same versioned Sharing instance passed as `sharing` (not another instance over the same adapters and store) and the same authority epoch and configuration generation as the adapters' inherited reads; anything else throws at construction. This adapter's `maxLifetimeMs` bounds the whole write; the control's own lifetime does not apply. When `managedMove` is also configured, a move is captured under each route's own mapping, so adding either option keeps every existing receipt key, and the flat descriptor applies only on a flat tenant. `parentIdColumn`, when the application keeps its own parent column, is rewritten by an enrolled move; it must be projected by `managed` and not be a patchable field. Without `hierarchy`, an enrolled delete or move refuses `HIERARCHY_UNAVAILABLE` / `enrolled`. See [managed deletion](/docs/sharing-postgres/managed-deletion) and [managed moves](/docs/sharing-postgres/managed-moves). The original resource adapter and its versioned Sharing instance must share the checked `createPgExecutor()` and matching PostgreSQL policy fence. Configure complete local identity and authorization-fact fences. `environmentId`, namespace, actor and idempotency key scope durable outcomes; `authorityEpoch` scopes revision evidence. `journalPrefix` must match the separately applied migrations. `maxLifetimeMs` is an integer from 1 through 60,000, defaults to 5,000, and bounds execution, not pool acquisition, driver setup or COMMIT. ### `createPostgresProtectedWriteAdapter` [#createpostgresprotectedwriteadapter] ```ts api="@rolebook/sharing-postgres" function createPostgresProtectedWriteAdapter(options: CreatePostgresProtectedWriteAdapterOptions): Readonly<{ receiptRoute(): object; forScope(value: TenantContext): Readonly<{ withManagedMove(value: ManagedMoveIntent): Promise<{ readonly status: "committed" | "replayed"; readonly receipt: MutationReceipt; }>; lookupManagedMoveReceipt(value: ManagedMoveIntent): Promise; withManagedDelete(value: ManagedDeleteIntent): Promise<{ readonly status: "committed" | "replayed"; readonly receipt: MutationReceipt; }>; lookupManagedDeleteReceipt(value: ManagedDeleteIntent): Promise; withManagedUpdates(value: ManagedUpdateBatchIntent): Promise | Readonly<{ status: "committed"; receipt: Readonly<{ receiptId: `${string}-${string}-${string}-${string}-${string}`; result: { updates: { resource: Readonly<{ type: string; id: string; }>; version: string; }[]; }; metadata: HierarchyAuthorizationDecisionMetadata | import("@rolebook/sharing").HierarchyBatchAuthorizationDecisionMetadata; sealedAt: string; }>; }> | Readonly<{ status: "committed"; receipt: Readonly<{ receiptId: `${string}-${string}-${string}-${string}-${string}`; result: { updates: { resource: ResourceRef; version: string; }[]; }; metadata: AuthorizationDecisionMetadata; sealedAt: string; }>; }>>; lookupManagedUpdatesReceipt(value: ManagedUpdateBatchIntent): Promise; withManagedUpdate(value: ManagedUpdateIntent): Promise<{ readonly status: "committed" | "replayed"; readonly receipt: MutationReceipt; }>; lookupManagedReceipt(value: ManagedUpdateIntent): Promise; lookupReceipt(value: ProtectedUpdateIntent): Promise; withAuthorizedTransaction(value: ProtectedUpdateIntent, operation: (guard: ProtectedUpdateGuard) => Promise): Promise<{ readonly status: "committed" | "replayed"; readonly receipt: MutationReceipt; }>; }>; }>; ``` Creates the embedded PostgreSQL resource/action facade. `forScope()` captures namespace and actor. `withAuthorizedTransaction()` owns a SERIALIZABLE transaction, admits only a resource-wide allow, invokes the callback once without automatic replay, seals authority and commits the application result, receipt and outbox event together. Returns `committed` or an exact durable `replayed` receipt. `lookupReceipt()` is trusted server recovery for the exact original intent; absence does not prove an in-flight commit cannot succeed. HTTP SDK calls do not extend this SQL transaction. See [Protected application updates](/docs/sharing-postgres/protected-updates) for setup, supported postconditions and operational boundaries. ### `ManagedScalarCodec` [#managedscalarcodec] ```ts api="@rolebook/sharing-postgres" type ManagedScalarCodec = "text" | "boolean" | "safe-integer"; ``` ### `PostgresManagedField` [#postgresmanagedfield] ```ts api="@rolebook/sharing-postgres" interface PostgresManagedField { readonly field: string; readonly column: string; readonly codec: ManagedScalarCodec; readonly nullable?: boolean; } ``` ### `PostgresManagedWriteDescriptor` [#postgresmanagedwritedescriptor] ```ts api="@rolebook/sharing-postgres" interface PostgresManagedWriteDescriptor { readonly target: { readonly schema: string; readonly table: string; readonly userColumns: readonly string[]; }; readonly fields: readonly PostgresManagedField[]; } ``` ### `ManagedUpdateIntent` [#managedupdateintent] ```ts api="@rolebook/sharing-postgres" interface ManagedUpdateIntent extends Omit { readonly expectedVersion: string; readonly patch: Readonly>; } ``` ### `createPostgresLocalIdentityProjection` [#createpostgreslocalidentityprojection] ```ts api="@rolebook/sharing-postgres" function createPostgresLocalIdentityProjection(options: { readonly table: QualifiedIdentifier; readonly groupSubjectTypes?: readonly string[]; }): { readonly identity: TransactionalTenantIdentityResolver & QueryIdentityResolver; readonly lockEligibleSubjects: PostgresEligibilityFence; readonly readEligibleSubjects: PostgresEligibilityReader; readonly revalidateAuthorizationFacts: PostgresAuthorizationFactFence; }; ``` Builds a resolver plus eligibility and authorization-fact fences for a complete application-owned local identity row. The table contract is described in [Complete local identity authority](/docs/sharing-postgres/protected-updates#complete-local-identity-authority). Writers must advance the row revision for every relevant change, including absent-to-present assignments/groups. External identity freshness and facts in additional unfenced tables are outside the contract. `identity` also has `resolveQueryPrincipalInTransaction` (see [`QueryIdentityResolver`](#queryidentityresolver)) for [named authorized queries](/docs/sharing/authorized-queries): the same complete local projection, with every expiry judged against the page's captured database time. For [listing](/docs/sharing/listing#identity), `identity` is the `resolver` of [`PostgresPageIdentity`](#postgrespageidentity). `lockEligibleSubjects` already carries its listing reader. `readEligibleSubjects` is that reader on its own, for an adapter whose `lockEligibleSubjects` wraps this projection's fence: pass it, wrapped the same way, as the adapter's `readEligibleSubjects`. It reads the rows unlocked, judges expiry at the page's instant, and reports each eligible row's expiry. ### `PostgresPageIdentity` [#postgrespageidentity] ```ts api="@rolebook/sharing-postgres" interface PostgresPageIdentity { readonly source: TenantIdentityAdapter; readonly resolver: QueryIdentityResolver; } ``` Identity evidence for listing pages, passed as the adapter's `pageIdentity`. `source` is the exact identity adapter object the sharing instance is created with. `resolver` reads that identity's complete local projection through the page's transaction; use `createPostgresLocalIdentityProjection().identity`. Supplying both is your attestation that `source` answers from exactly that projection. Rolebook checks only that the sharing instance's identity is this same object; it does not check what a remote provider behind it would answer. A sharing instance created with a different object, including a copy or a wrapper of `source`, does not match, and its listings need bracketed evidence from the identity adapter or answer `identity_evidence_missing`. An eligible principal must come from a projection row with a revision; a row the resolver cannot decode is `identity_evidence_missing`, and an absent row is an ordinary ineligible principal. The projection row and the adapter's eligibility authority are separate checks. A projection that says the actor is eligible does not override an eligibility fence that refuses the actor: the page is empty. ### `ProtectedWriteOutboxClaim` [#protectedwriteoutboxclaim] ```ts api="@rolebook/sharing-postgres" type ProtectedWriteOutboxClaim = OutboxClaim; ``` A committed event with stable `eventId`, `kind` and `payload`, plus a `deliveryToken` containing `environmentId`, `eventId` and claim `generation`. Preserve the exact token for acknowledgement. The underlying alias is an implementation type; applications use this exported claim type. ### `createPostgresProtectedWriteOutbox` [#createpostgresprotectedwriteoutbox] ```ts api="@rolebook/sharing-postgres" function createPostgresProtectedWriteOutbox(options: { readonly executor: ParameterizedSqlExecutor; readonly tablePrefix: string; readonly environmentId: string; readonly operator?: ProtectedWriteOperator; }): Readonly<{ claim(input: { readonly limit: number; readonly leaseMs: number; }): Promise; inspectPending(input: { readonly limit: number; }): Promise[]>; retry(token: ProtectedWriteOutboxClaim["deliveryToken"], input: { readonly delayMs: number; }): Promise; claimForInspection(input: { readonly eventId: string; readonly leaseMs: number; }): Promise<{ readonly environmentId: string; readonly eventId: string; readonly generation: string; } | undefined>; quarantine(token: ProtectedWriteOutboxClaim["deliveryToken"], input: { readonly reason: string; }): Promise<{ readonly environmentId: string; readonly eventId: string; readonly generation: string; } | undefined>; inspectOperatorActions(input: { readonly eventId: string; readonly limit: number; readonly afterGeneration?: string; }): Promise; inspectDeadLetters(input: { readonly limit: number; }): Promise; requeue(token: ProtectedWriteOutboxClaim["deliveryToken"]): Promise; acknowledge(token: ProtectedWriteOutboxClaim["deliveryToken"]): Promise; }>; ``` Trusted separate-worker API. Claim committed events with a bounded limit and lease, deliver outside the protected transaction, deduplicate by `eventId` at the sink and acknowledge only after delivery. Tokens are environment-bound; expired or superseded leases cannot acknowledge a later claim. Delivery is at least once. This does not register a worker, external sink, Sharing `listAudit()` integration or console audit route. `inspectPending({ limit })` returns 1–1000 oldest pending rows, including leased rows, with `eventId`, `kind`, `generation` and `state`. It omits payload decoding and is a bounded snapshot, not pagination or a delivery watermark. A future retry delay also appears as `leased`. `retry(deliveryToken, { delayMs })` accepts 0–300000ms and only a current unexpired lease. It advances the fencing generation immediately, so the old ACK fails even during the delay. Stale, expired, delivered or foreign-environment claims return false; invalid bounds throw. Normal claim recovers expired leases after worker crashes. The generation is fencing metadata, not an authentication secret or exact attempt count; restrict inspection to trusted operators. Deduplicate destination effects by `(environmentId, eventId)`. Receipts and outbox rows are retained indefinitely. Explicit quarantine/requeue is available after the additive migration described below. No pruning, scheduler, HTTP route or console integration is provided. `claimForInspection({ eventId, leaseMs })` acquires one exact event's lease without decoding its payload. It cannot steal a live lease or claim a quarantined/delivered event; lease bounds are 1–300000ms. `quarantine(currentToken, { reason })` requires that current unexpired lease and a nonblank reason of 1–1024 characters without NUL. It returns a new quarantine token or `undefined` for an ineligible/stale/foreign claim. Quarantine advances the generation and suppresses delivery; it does not mark the event delivered or change its payload. `inspectDeadLetters({ limit })` returns 1–1000 oldest active quarantines without decoding payloads. `requeue(quarantineToken)` requires the exact active quarantine generation, advances it again and makes the event available for normal claim. It returns false for stale/foreign/already-requeued state. Invalid input throws. Quarantine requires generation below 9223372036854775805 to leave headroom for requeue and a subsequent claim; no operation wraps or resets the counter. These are trusted environment-wide operator methods, not authenticated tenant-user endpoints. They preserve at-least-once delivery and stable event IDs through recovery. Requeue leaves corrupt payloads corrupt; resolve the producer/decoder/destination problem before redelivery. **Migration required:** stop/drain old workers, explicitly run the protected-write migrations to add `_dead_v1`, then start only upgraded workers. Old binaries ignore quarantine and must not run concurrently. New worker paths fail closed if the table is absent. The original receipt and outbox schemas are unchanged. See [operator recovery](/docs/sharing-postgres/protected-updates#quarantine-and-explicit-operator-recovery). `operator` is optional application-attested attribution copied at factory construction, not a credential or authorization bypass. Omitted identity records null. Each successful quarantine or requeue appends history atomically; append failure rolls back the transition. Failed/stale/foreign operations append nothing. Apply the explicit `_actions_v1` migration before using upgraded operator workers, and stop/drain old binaries. Existing factory calls remain compatible after migration. History starts at upgraded-worker rollout: prior transitions are not fabricated, and mixed-version operator execution cannot claim complete history. `inspectOperatorActions({ eventId, limit, afterGeneration? })` reads immutable successful actions for one exact event in the bound environment. Limit is an integer 1–1000. The exclusive cursor is `"0"` (default) or a canonical positive signed-64-bit decimal generation. Use the last returned generation for the next page. Numeric generation order is independent of timestamps; gaps are normal because claims/retries also advance fencing generations. This is live per-event pagination, not a frozen or cross-event feed. Corrupt returned records fail closed. Retention is indefinite; append-only is an API guarantee under trusted DB ownership, not tamper evidence against database administrators. See [operator history](/docs/sharing-postgres/protected-updates#retained-operator-action-history). ### `createProtectedWriteMigrations` [#createprotectedwritemigrations] ```ts api="@rolebook/sharing-postgres" function createProtectedWriteMigrations(options: { readonly tablePrefix: string; }): readonly ResourceSharingMigration[]; ``` Returns repeatable, schema-validating receipt/outbox migration steps for `applyPostgresMigrations()`. The application migration owner must run them explicitly; adapter construction does not. Existing incompatible schemas fail closed. Resource/projection/policy setup, retention and operator recovery remain application responsibilities. ### `MutationReceipt` [#mutationreceipt] ```ts api="@rolebook/sharing-postgres" interface MutationReceipt { readonly receiptId: string; readonly result: unknown; readonly metadata: AuthorizationDecisionMetadata | HierarchyAuthorizationDecisionMetadata | HierarchyBatchAuthorizationDecisionMetadata; /** Seal time recorded inside the transaction, not an exact COMMIT timestamp. */ readonly sealedAt: string; } ``` Durable committed callback result and captured decision metadata. `metadata.schemaVersion` is the stored metadata version, not a journal-table schema: 1 for a flat write, 2 for one enrolled target or a legacy multi-target batch, and 3 for an enrolled batch of 2–32 targets. A version-3 `hierarchy` block is evidence for its own target, not a capability. `sealedAt` is the time recorded at the common seal, not the exact COMMIT timestamp. A matching receipt can reconcile an uncertain commit; keep it for the full retry/reconciliation horizon. ### `IdempotencyConflictError` [#idempotencyconflicterror] ```ts api="@rolebook/sharing-postgres" class IdempotencyConflictError extends Error { readonly code: "IDEMPOTENCY_CONFLICT"; constructor(); } ``` The durable key was already used with a different complete intent. Reports `IDEMPOTENCY_CONFLICT`; do not reinterpret the existing outcome as the new request. ### `MutationJournalRowError` [#mutationjournalrowerror] ```ts api="@rolebook/sharing-postgres" class MutationJournalRowError extends Error { readonly code: "MUTATION_JOURNAL_CORRUPT"; constructor(cause: unknown); } ``` Stored journal evidence is malformed or violates the decoding contract. Reports `MUTATION_JOURNAL_CORRUPT`. Recovery fails closed instead of trusting corrupted receipt or delivery data. ### `ManagedUpdateBatchIntent` [#managedupdatebatchintent] ```ts api="@rolebook/sharing-postgres" interface ManagedUpdateBatchIntent { readonly idempotencyKey: string; readonly updates: readonly Omit[]; } ``` An atomic batch of 1–32 distinct existing resources through one configured adapter in one tenant. Each update has the single-update fields except its idempotency key; the outer key binds the whole batch. Use `withManagedUpdates(intent)` and `lookupManagedUpdatesReceipt(intent)`. Input order is canonicalized by resource ID; reordered identical intent replays the same receipt. Create/delete/move and cross-adapter transactions are outside this contract. ### `createPostgresProtectedWriteReceipts` [#createpostgresprotectedwritereceipts] ```ts api="@rolebook/sharing-postgres" function createPostgresProtectedWriteReceipts(options: { readonly receiptRoute: object; }): Readonly<{ forScope(scope: ReceiptLookupScope): Readonly<{ lookup(input: { readonly idempotencyKey: string; }): Promise; }>; }>; ``` Trusted server lookup of a committed outcome by key. `receiptRoute` is the opaque object from `createPostgresProtectedWriteAdapter(...).receiptRoute()`. It captures that adapter's resource type, journal prefix and environment. A missing, cloned or foreign route throws before any journal read. Bind tenant and actor from authenticated server context and enforce application access policy before calling `lookup`. Every query includes environment, tenant, actor type, actor ID and key. It returns an immutable receipt or `undefined`; absence does not prove rollback. This does not validate a proposed retry payload: use the protected adapter’s exact-intent receipt lookup for that. Receipt access can expose sensitive historical business results. ### `ProtectedWriteDeadLetter` [#protectedwritedeadletter] ```ts api="@rolebook/sharing-postgres" type ProtectedWriteDeadLetter = OutboxDeadLetter; ``` An immutable diagnostic record with `eventId`, `kind`, `reason`, ISO `quarantinedAt`, and `quarantineToken` (environment/event/generation). It contains no payload or receipt result. The underlying alias is an implementation type; applications use this exported type. Inspection returns only active quarantines and fails closed on inconsistent generation/identity evidence. The retained side row stores the latest quarantine/requeue state. The separate operator-action history retains successful transitions after the history upgrade. ### `ManagedDeleteIntent` [#manageddeleteintent] ```ts api="@rolebook/sharing-postgres" interface ManagedDeleteIntent extends Omit { readonly expectedVersion: string; } ``` One callback-free deletion of an exact existing resource incarnation and version, using the configured managed descriptor. `withManagedDelete(intent)` authorizes the resource/action and atomically removes the business row and live sharing state while retaining lifecycle evidence, a receipt and one outbox event. `lookupManagedDeleteReceipt(intent)` recovers the original outcome; it does not authorize a replacement incarnation. See [Managed deletion](/docs/sharing-postgres/managed-deletion). ### `ProtectedWriteOperator` [#protectedwriteoperator] ```ts api="@rolebook/sharing-postgres" type ProtectedWriteOperator = OutboxOperator; ``` An optional application-attested `{ type, id }` identity copied and frozen at worker construction. Both fields are nonblank strings of at most 1024 characters without NUL. The library does not authenticate or authorize this identity. Omitted identity is recorded as null. ### `ProtectedWriteOperatorAction` [#protectedwriteoperatoraction] ```ts api="@rolebook/sharing-postgres" type ProtectedWriteOperatorAction = OutboxOperatorAction; ``` An immutable retained successful-action record with `environmentId`, `eventId`, stable `actionId`, resulting decimal `generation`, `action` (`quarantine` or `requeue`), nullable `operator`, nullable `reason`, and ISO `recordedAt`. Requeue reasons are null. The timestamp describes the transition inside its transaction, not exact COMMIT time. The action ID is a digest identifier, not a signature. No receipt or event payload is included. ### `ManagedMoveIntent` [#managedmoveintent] ```ts api="@rolebook/sharing-postgres" interface ManagedMoveIntent extends Omit { readonly expectedVersion: string; readonly sourceParent: ManagedParentExpectation; readonly destinationParent: ManagedParentExpectation; } ``` ### `ManagedParentExpectation` [#managedparentexpectation] ```ts api="@rolebook/sharing-postgres" interface ManagedParentExpectation { readonly type?: string; readonly id: string; readonly incarnationId: string; readonly version: string; } ``` ### `ManagedParentField` [#managedparentfield] ```ts api="@rolebook/sharing-postgres" interface ManagedParentField { readonly field: string; readonly column: string; readonly codec: "text" | "boolean" | "safe-integer"; readonly nullable?: boolean; } ``` ### `PostgresManagedMoveDescriptor` [#postgresmanagedmovedescriptor] ```ts api="@rolebook/sharing-postgres" interface PostgresManagedMoveDescriptor { readonly parentIdColumn: string; readonly parent: { readonly resourceType: string; readonly schema: string; readonly table: string; readonly tenantColumn: string; readonly idColumn: string; readonly versionColumn: string; readonly incarnationColumn: string; readonly expiresAtColumn?: string; readonly userColumns: readonly string[]; readonly fields: readonly ManagedParentField[]; }; readonly sourceAction: string; readonly destinationAction: string; } ``` ### `createPostgresProtectedWriteDeliveryWorker` [#createpostgresprotectedwritedeliveryworker] ```ts api="@rolebook/sharing-postgres" function createPostgresProtectedWriteDeliveryWorker(options: OutboxDeliveryOptions & { readonly executor: ParameterizedSqlExecutor; readonly tablePrefix: string; readonly environmentId: string; readonly operator?: ProtectedWriteOperator; }): OutboxDeliveryWorkerWithDiagnostics; ``` Creates the shared bounded delivery worker over this adapter's existing protected-write outbox. Apply explicit journal/operator-history migrations first. Operator identity is copied at construction as application-attested attribution; omitted identity remains null. No authentication, daemon, scheduler, actual sink service or payload/receipt mutation is added. One pass claims batchSize1–32 events, starts at most that many concurrent sinks after releasing the claim connection, and serializes exact-token settlements. Lease bounds are1–300000ms and callback timeout is1–leaseMs. Only explicit delivered results permit ACK. Caller-selected retry/quarantine, unknown outcomes, stale leases and ambiguous ACKs follow the [shared delivery contract](/docs/sharing/outbox-delivery). Cancellation prevents future queued settlements but cannot undo submitted DB work or external sink effects. A worker stays busy while abandoned sink work remains. No automatic retry occurs. The optional `diagnostics` option is forwarded to the shared worker unchanged and validated at construction; `diagnostics()` returns the worker-local, redacted snapshot described in [worker diagnostics](/docs/sharing/outbox-delivery#worker-diagnostics). ## Named authorized queries [#named-authorized-queries] A small, fixed set of named queries over the adapter's own resource table that return only the resource keys the actor is allowed. The contract, bounds and guarantees are in the [named authorized queries guide](/docs/sharing/authorized-queries). ### `createPostgresAuthorizedQueries` [#createpostgresauthorizedqueries] ```ts api="@rolebook/sharing-postgres" function createPostgresAuthorizedQueries(options: CreatePostgresAuthorizedQueriesOptions): AuthorizedQueries; ``` Checks every capability without database I/O and throws `QueryConfigurationError` before serving a request: the original adapter on an original `createPgExecutor` executor, with an enforced `fencePolicy` for the policy store of `sharing`, which must use that same executor; a resolver with `resolveQueryPrincipalInTransaction`; `text` tenant and resource SQL types (an adapter with `resourceSqlType: "uuid"` is refused); and a registry whose unqualified table, tenant and ID columns equal the adapter's descriptor. One page is one `SERIALIZABLE READ ONLY` transaction on one pool connection, which also checks that those columns are non-null `text` or `varchar`. ### `CreatePostgresAuthorizedQueriesOptions` [#createpostgresauthorizedqueriesoptions] ```ts api="@rolebook/sharing-postgres" interface CreatePostgresAuthorizedQueriesOptions { readonly adapter: PostgresSharingAdapter; readonly sharing: VersionedResourceSharing; readonly identity: QueryIdentityResolver; readonly queries: readonly QueryDefinition[]; readonly listingCursorKey: string | Uint8Array | readonly (string | Uint8Array)[]; readonly environmentId: string; } ``` `queries` holds 1 to 64 definitions. `listingCursorKey` is one key or 1 to 8 keys: the first seals and every key opens, and there is no random default. `environmentId` matches `[A-Za-z][A-Za-z0-9_-]{0,63}` and is bound into every cursor. `identity` is usually `createPostgresLocalIdentityProjection().identity`. The shapes below are declared once in `@rolebook/sharing` and re-exported from this package and from `@rolebook/sharing-sqlite`. Import them from the driver package: `@rolebook/sharing` does not export them from its root. ### `AuthorizedQueries` [#authorizedqueries] ```ts api="@rolebook/sharing/internal/transaction-runtime" interface AuthorizedQueries { forTenant(binding: QueryTenantBinding): TenantAuthorizedQueries; close(): Promise; } ``` The factory. `forTenant(binding)` captures the trusted binding synchronously and throws `QueryConfigurationError` when it is invalid. `close()` rejects new requests, ends the pages in flight and resolves once they have settled; when that takes longer than 1,000 ms it rejects with `QueryCloseError`, and a later call waits on the same cleanup again. ### `TenantAuthorizedQueries` [#tenantauthorizedqueries] ```ts api="@rolebook/sharing/internal/transaction-runtime" interface TenantAuthorizedQueries { query(request: QueryRequest): Promise; } ``` `query()` never throws for an operational failure: every failure is a coded `QueryResult`. ### `QueryTenantBinding` [#querytenantbinding] ```ts api="@rolebook/sharing/internal/transaction-runtime" interface QueryTenantBinding { readonly tenantId: string; readonly actor: ResourceRef; readonly context?: Readonly>; readonly sessionBinding: string; } ``` Trusted server facts, never client input. `context` is plain JSON within Core's context bounds (default `{}`) and may not contain `tenantId` or `sharingRevision`. `sessionBinding` is your session or authority incarnation, 1 to 128 UTF-16 units; it is bound into every cursor and never returned. ### `QueryRequest` [#queryrequest] ```ts api="@rolebook/sharing/internal/transaction-runtime" interface QueryRequest { readonly name: string; readonly filters?: readonly QueryPredicate[]; readonly limit?: number; readonly cursor?: string; } ``` `name` selects a registered query. `filters` is a conjunction (default none), `limit` an integer from 1 to 100 (default 25, not bound to the cursor), and `cursor` the previous page's `nextCursor`. ### `QueryPredicate` [#querypredicate] ```ts api="@rolebook/sharing/internal/transaction-runtime" type QueryPredicate = { readonly field: string; readonly op: "eq" | "gt" | "gte" | "lt" | "lte"; readonly value: QueryScalar; } | { readonly field: string; readonly op: "in"; readonly value: readonly QueryScalar[]; } | { readonly field: string; readonly op: "isNull"; readonly value: boolean; }; type QueryScalar = string | number | boolean; ``` `field` is a registered filter name and `op` one of its registered operators. `in` takes 1 to 32 distinct values of one type, ranges take integers or strings, and `isNull` is the only way to test for null. `QueryScalar` is not exported by name. ### `QueryResult` [#queryresult] ```ts api="@rolebook/sharing/internal/transaction-runtime" type QueryResult = { readonly ok: true; readonly page: { readonly items: readonly ResourceKey[]; readonly nextCursor?: string; readonly exhausted: boolean; readonly completion: "complete" | "budget_limited"; readonly evaluatedAt: number; readonly queryVersion: string; readonly schemaVersion: string; readonly consistency: "local-snapshot"; readonly traversal: "live"; }; } | { readonly ok: false; readonly code: QueryErrorCode; }; type QueryErrorCode = "INVALID_REQUEST" | "INVALID_CURSOR" | "CURSOR_STALE_RESTART" | "QUERY_UNAVAILABLE"; ``` `items` are resource keys only. `exhausted: true` comes with no `nextCursor`; otherwise `nextCursor` is present, even when `items` is empty. `evaluatedAt` is the page's database time in epoch milliseconds. `QueryErrorCode` is not exported by name. The codes are described in the [guide](/docs/sharing/authorized-queries#errors). ### `QueryDefinition` [#querydefinition] ```ts api="@rolebook/sharing/internal/transaction-runtime" interface QueryDefinition { readonly name: string; readonly version: string; readonly resourceType: string; readonly action: string; readonly schemaVersion: string; readonly table: string; readonly tenantColumn: string; readonly idColumn: string; readonly filters: Readonly>; readonly sort: QuerySort; } ``` One trusted, server-registered query. `table`, `tenantColumn` and `idColumn` must equal the adapter's resource descriptor. Names, versions and filter names match `[A-Za-z][A-Za-z0-9_-]{0,63}`; SQL identifiers are unqualified `[A-Za-z_][A-Za-z0-9_]{0,62}`. ### `FilterColumn` [#filtercolumn] ```ts api="@rolebook/sharing/internal/transaction-runtime" interface FilterColumn { readonly column: string; readonly type: ColumnType; readonly operators: readonly QueryFilterOperator[]; readonly disclosable: true; } type QueryFilterOperator = "eq" | "in" | "gt" | "gte" | "lt" | "lte" | "isNull"; ``` `operators` is non-empty and unique; range operators are invalid for `boolean`. `disclosable: true` attests that every subject who may run the query and receive this action's resources may learn the column's values by inference. `QueryFilterOperator` is not exported by name. ### `QuerySort` [#querysort] ```ts api="@rolebook/sharing/internal/transaction-runtime" interface QuerySort { readonly column: string; readonly type: ColumnType; readonly direction: "asc" | "desc"; readonly nulls: "first" | "last"; readonly disclosable: true; } ``` The one sort. Resource IDs always break ties, ascending in binary order, whatever `direction` is. ### `ColumnType` [#columntype] ```ts api="@rolebook/sharing/internal/transaction-runtime" type ColumnType = "integer" | "string" | "boolean"; ``` `integer` is a safe integer, `string` compares in binary UTF-8 order, and `boolean` sorts `false` before `true`. Every registered column may be nullable except the tenant and ID columns. ### `QueryIdentityResolver` [#queryidentityresolver] ```ts api="@rolebook/sharing/internal/transaction-runtime" interface QueryIdentityResolver { resolveQueryPrincipalInTransaction(input: { readonly executor: TExecutor; readonly tenantId: string; readonly subject: ResourceRef; readonly evaluatedAt: string; }): Promise; } interface QueryPrincipalResolution { readonly principal: TenantPrincipal; readonly authority: "complete-local-projection"; readonly expiryDependencies: readonly string[]; readonly revisions: readonly AuthorityRevision[]; } ``` Resolves the actor inside the page transaction. `evaluatedAt` is the page's captured database time (ISO 8601 UTC, milliseconds), and the resolver must judge every expiry against it. The local identity projection's `identity` implements it. `QueryPrincipalResolution` is not exported by name. ### `QueryConfigurationError` [#queryconfigurationerror] ```ts api="@rolebook/sharing/internal/transaction-runtime" class QueryConfigurationError extends Error { readonly code: "QUERY_CONFIGURATION_INVALID"; constructor(); } ``` Thrown by the factory and by `forTenant()` for an invalid or unsupported configuration or binding. Its message is fixed and it carries no cause. `instanceof` across separately bundled copies of `@rolebook/sharing` is not promised, so branch on `code`. ### `QueryCloseError` [#querycloseerror] ```ts api="@rolebook/sharing/internal/transaction-runtime" class QueryCloseError extends Error { readonly code: "QUERY_CLOSE_FAILED"; constructor(); } ``` `close()` could not confirm within 1,000 ms that every owned page had been cleaned up. Its message is fixed and it carries no cause. ## Governance attachment [#governance-attachment] Create a PostgreSQL governance attachment once for a sharing resource configuration. Give its `adapterOptions` to the PostgreSQL sharing adapter and its `attachment` to the sharing configuration. The governing-rule resolver receives both tenant and resource identifiers, preserving tenant isolation when resource IDs overlap. ### `createPostgresGovernanceAttachment` [#createpostgresgovernanceattachment] ```ts api="@rolebook/sharing-postgres" function createPostgresGovernanceAttachment(options: PostgresGovernanceAttachmentOptions): PostgresGovernanceAttachmentBundle; ``` ### `PostgresGovernanceAdapterOptions` [#postgresgovernanceadapteroptions] ```ts api="@rolebook/sharing-postgres" interface PostgresGovernanceAdapterOptions { readonly governanceGate: GovernanceDirectGate; readonly governanceBinding: GovernanceBinding; readonly lockEligibleSubjects: PostgresEligibilityFence; readonly fencePolicy?: PostgresPolicyFence; } ``` ### `PostgresGovernanceAttachmentBundle` [#postgresgovernanceattachmentbundle] ```ts api="@rolebook/sharing-postgres" interface PostgresGovernanceAttachmentBundle { readonly attachment: GovernanceAttachment; readonly adapterOptions: PostgresGovernanceAdapterOptions; } ``` ### `PostgresGovernanceAttachmentOptions` [#postgresgovernanceattachmentoptions] Bind the identity assignment table and group graph that this tenant uses. For a source the application does not use, declare `evidenceSources.identity` or `evidenceSources.groups` as `"none"`. If a required source is missing, governed decisions return `UNAVAILABLE`. With `groups: "none"`, governance cannot see anyone's teams: wherever a group holds any role on the resource (or on a parent the resource inherits from, or anywhere in the tenant when the resource passes access down), approvals and rejections cannot be confirmed and answer `UNKNOWN_REQUEST`, so such a request cannot complete. Bind a group graph to govern resources that teams hold roles on. Without a group graph, a request whose target is a group also cannot complete, because nobody's membership of that group can be seen: an approval or rejection from someone who would otherwise count answers `UNAVAILABLE`, and from anyone else `UNKNOWN_REQUEST`, as for a request that does not exist. ```ts api="@rolebook/sharing-postgres" interface PostgresGovernanceAttachmentOptions { readonly executor: ParameterizedSqlExecutor; readonly schema: string; readonly tablePrefix: string; readonly requestTtlMs: number; readonly restoreEpoch: string | (() => string | "pending" | "unavailable" | Promise); readonly governingRule: (tenantId: string, resourceId: string, command: GovernanceFoundationCommandKind, scope: PostgresGovernanceRuleScope) => GovernanceRuleSnapshot | "clear" | "unavailable" | Promise; readonly binding: GovernanceBinding; readonly eligibility: PostgresEligibilityFence; readonly policyFence?: PostgresPolicyFence; readonly policyStore?: PolicyStore; readonly policy: RolebookPolicy; readonly sharing: PostgresGovernanceSharingConfig; readonly groupGraph?: PostgresGovernanceGroupSource; readonly identityAssignmentTable?: string; readonly evidenceSources?: { readonly identity?: "none"; readonly groups?: "none"; }; readonly outbox?: { readonly tablePrefix: string; readonly environmentId: string; }; } ``` ### `PostgresGovernanceSharingConfig` [#postgresgovernancesharingconfig] ```ts api="@rolebook/sharing-postgres" interface PostgresGovernanceSharingConfig { readonly resourceType: string; readonly memberRoles: Readonly>; readonly ownershipRole: string; readonly management: { readonly members: string; readonly ownership: string; }; readonly parents?: readonly GovernanceFoundationRef[]; readonly attributes?: Readonly>; readonly inheritingTypes?: readonly string[]; } ``` ## Access-change delivery [#access-change-delivery] The delivery cursor and queue behind [access-change webhooks](/docs/sharing/webhooks). ### `AccessChangeDeliveryError` [#accesschangedeliveryerror] ```ts api="@rolebook/sharing-postgres" class AccessChangeDeliveryError extends Error { readonly code: AccessChangeDeliveryErrorCode; constructor(code: AccessChangeDeliveryErrorCode, message: string); } ``` Thrown when delivery storage returns a row that does not decode, or when a subscription is bound to another tenant. Each resource type is drained in its own transaction: a drain that fails on one resource type keeps what earlier ones queued, and a failed page queues nothing and leaves its cursor where it was. On PostgreSQL it is also thrown when a cursor or audit row holds a transaction ID at or beyond the cluster's next one, as after a logical restore. ### `createAccessChangeDeliveryMigrations` [#createaccesschangedeliverymigrations] ```ts api="@rolebook/sharing-postgres" function createAccessChangeDeliveryMigrations(options: { readonly tablePrefix: string; }): readonly ResourceSharingMigration[]; ``` Idempotent steps that create the delivery subscription, cursor and queue tables, for `applyPostgresMigrations`. Never run automatically. The audit tables' commit-order column and its index come from `createResourceSharingMigrations` (steps `:audit-delivery-position` and `:audit-delivery-index`). ### `createPostgresAccessChangeDeliveryStore` [#createpostgresaccesschangedeliverystore] ```ts api="@rolebook/sharing-postgres" function createPostgresAccessChangeDeliveryStore(options: { readonly executor: ParameterizedSqlExecutor; readonly tablePrefix: string; readonly environmentId: string; readonly resources: readonly PostgresResourceDescriptor[]; }): PostgresAccessChangeDeliveryStore; ``` The PostgreSQL delivery store over the audit tables of `resources` (the descriptors passed to `createResourceSharingMigrations`). It drains rows in `(delivery_xid, resource_id, event_id)` order, and only those whose writing transaction is older than every running transaction, so a row that commits later never falls behind the cursor. It reads the audit table outside any transaction and queues in one short transaction. Bound to one `environmentId`. ### `PostgresAccessChangeDeliveryStore` [#postgresaccesschangedeliverystore] ```ts api="@rolebook/sharing-postgres" interface PostgresAccessChangeDeliveryStore extends AccessChangeDeliveryStore { adoptCluster(): Promise<{ readonly adopted: boolean; }>; rebaseline(input?: { readonly force?: boolean; }): Promise; } ``` The PostgreSQL store, with the operator actions for a cluster whose identity changed. The sharing migration records, per audit table, the cluster its positions belong to; on another cluster a drain throws with code `foreign-cluster`. After `pg_upgrade` or a physical copy call `adoptCluster`, which keeps every cursor; it refuses when a position is ahead of the counter or a subscription is halted, and success does not prove the counter was continuous. After a logical restore, before the application writes anything, call `rebaseline`. It queues the outstanding restored changes of the subscriptions that exist at that moment, in order, clears every position, and advances the epoch, so other cursors start again from changes committed afterwards. It records this cluster and reports what it did. Restored changes reach only the subscriptions that existed when it ran, and only for resources whose audit table the subscription already had a cursor for; a subscription that never drained a resource gets none of its restored changes. A change committed on the new cluster before it is not delivered, or is delivered out of order, and a subscription created afterwards starts from later changes. It refuses a missing origin row unless forced, because that is usually a missing grant, fixed by running the migration again. Both need the schema owner's executor. See [access-change webhooks](/docs/sharing/webhooks). ### `RebaselineResult` [#rebaselineresult] ```ts api="@rolebook/sharing-postgres" interface RebaselineResult { readonly rebaselined: boolean; readonly subscriptions: number; readonly entries: number; readonly positionsCleared: number; readonly rowsSkipped: number; } ``` What `rebaseline` did: the subscriptions of the environment that had at least one restored change queued, the entries it queued, the audit rows (of every tenant) whose position it cleared, and the restored access changes it set aside because they did not decode. # PostgreSQL fences and transactions (/docs/sharing-postgres/fences) > Eligibility, email-recipient, workspace-role, team, and policy fences, and SERIALIZABLE retries. The identity adapter's answer is a preflight. Fences make it hold until the mutation commits: each runs inside the mutation's `SERIALIZABLE` transaction, takes `FOR SHARE` locks on the authoritative rows, and rechecks them, so a concurrent removal either commits first (and the mutation fails) or waits for the already-authorized mutation. A fence result counts only when it is literally `true`. The authoritative identity rows must live in the **same database** as the sharing tables. A remote provider (Clerk, WorkOS) cannot be locked by this transaction: maintain a database-local projection of its memberships whose lifecycle you coordinate with removals, and point the fences at that projection. ## Membership eligibility [#membership-eligibility] ```ts import { createPostgresMembershipEligibilityFence } from "@rolebook/sharing-postgres"; const lockEligibleSubjects = createPostgresMembershipEligibilityFence({ table: ["auth", "member"], tenantColumn: "organization_id", subjectIdColumn: "user_id", subjectType: "user", // optional }); ``` Required on every adapter. It locks each required subject's member row in the tenant and checks that the row names exactly the requested tenant and subject. It also receives `ownerCandidates` (the owner on initialization, a transfer's recipient, a move's retained owner); the team-aware fence refuses a team there. ## Email invitation recipients [#email-invitation-recipients] ```ts import { createPostgresEmailInvitationRecipientFence } from "@rolebook/sharing-postgres"; const lockInvitationRecipient = createPostgresEmailInvitationRecipientFence({ membershipTable: ["auth", "member"], membershipTenantColumn: "organization_id", membershipSubjectIdColumn: "user_id", userTable: ["auth", "user"], userIdColumn: "id", userEmailColumn: "email", userEmailVerifiedColumn: "email_verified", emailNormalization: "lower_trim", // default; "exact" only for a pre-normalized column }); ``` Email-bound acceptance locks the membership row and the user's email and verification row in the consuming transaction and requires a verified address equal to the invitation's. Without this fence, email invitations fail closed. A remote identity API cannot be made atomic with the transaction, so with a remote provider issue subject-bound invitations instead. ## Mapped workspace roles [#mapped-workspace-roles] When your identity adapter maps provider workspace roles to Rolebook assignments, each mutation carries an authorization fact with the member ID and role. Configure a fence that locks and compares it: ```ts import { BETTER_AUTH_WORKSPACE_MEMBER_AUTHORIZATION_FACT } from "@rolebook/sharing-better-auth"; import { createPostgresWorkspaceRoleAuthorizationFactFence } from "@rolebook/sharing-postgres"; const revalidateAuthorizationFacts = createPostgresWorkspaceRoleAuthorizationFactFence({ table: ["auth", "member"], tenantColumn: "organization_id", subjectIdColumn: "user_id", factType: BETTER_AUTH_WORKSPACE_MEMBER_AUTHORIZATION_FACT, // the identity adapter's fact type memberIdColumn: "id", roleColumn: "role", }); ``` Member-row existence alone does not make a mapped allow current: the fence compares the exact tenant, subject, membership ID, and role. A mutation that carries facts while no `revalidateAuthorizationFacts` is configured fails closed (`identity_ineligible`, reported as `NOT_TENANT_MEMBER`), and the adapter logs once which fact types were unfenced. `revalidateAuthorizationFacts` runs after the eligibility fence and decides the mutation: `true` proceeds; `"conflict"` means facts changed in a way that needs a fresh authorization (the adapter rolls back, returns `conflict`, and the module re-resolves and retries); anything else is `identity_ineligible`. Lifecycle methods do not call it. ### Exact text comparison [#exact-text-comparison] Every shipped fence matches identity rows in SQL and then compares the matched columns, read back as text, with the requested values in JavaScript, exactly. SQL `=` follows the column's type and collation: a `citext` column, a case-insensitive collation, or a `uuid` or `integer` column would also match another spelling, so a membership reassigned from `bob` to a distinct `BOB` could otherwise satisfy a fence for `bob`. A row with another spelling, a second matching row, a `NULL`, or a non-string value fails closed, so identity columns must hold the canonical spelling your identity adapter reports. ## Teams [#teams] With [teams](/docs/teams), use `createPostgresTeamFences()` from `@rolebook/teams/sql` for both `lockEligibleSubjects` and `revalidateAuthorizationFacts`. It wraps your membership fences, locks team and team-member rows, refuses a team as an owner candidate, and returns `"conflict"` when the actor's team set changed since preflight. Keep `groupSubjectTypes` equal to the `teamType` you give `withTeams()`. ## Policy fence [#policy-fence] For [versioned sharing](/docs/sharing/versioned), store policy versions in the same database and fence every adapter: ```ts import { createPostgresPolicyFence, createPostgresPolicyStore, createPostgresSharingAdapter, type ParameterizedSqlExecutor, type PostgresEligibilityFence, type PostgresResourceDescriptor, } from "@rolebook/sharing-postgres"; declare const executor: ParameterizedSqlExecutor; declare const projectTable: PostgresResourceDescriptor; declare const lockEligibleSubjects: PostgresEligibilityFence; const policyStore = createPostgresPolicyStore({ executor, schema: "app", tablePrefix: "rolebook" }); const projectAdapter = createPostgresSharingAdapter({ executor, resource: projectTable, lockEligibleSubjects, fencePolicy: createPostgresPolicyFence({ schema: "app", tablePrefix: "rolebook" }), }); // projectAdapter.policyFence === "enforced" ``` The fence runs inside the mutation transaction, after the resource-revision compare and before the sharing write, through that transaction's executor only. The store and every fence must use the same `schema` and `tablePrefix`; protected writes and authorized queries refuse a fence without an explicit `schema`. A fenced adapter rejects an `applyMutation` without `expectedPolicy`. `PolicyStoreRowError` reports a store row that does not decode; `isPolicyStoreRowError` from `@rolebook/sharing` recognizes it. ## SERIALIZABLE retries [#serializable-retries] Serialization failures and deadlocks (`40001`, `40P01`, also when wrapped as an error's `cause`) retry only the idempotent unit of work. `serializableRetry` on the adapter (and the same options on the helpers below) sets `attempts` (default 3, including the first) and pauses with the same capped, fully jittered backoff the sharing module uses: 0 to `min(50, 5 x 2^(retry - 1))` ms before each retry. `backoffMs(retry)` must return 0 to 1,000 ms; `wait(ms)` replaces the timer. | Helper | Use | | --- | --- | | `withSerializableRetry(executor, operation, options?)` | Run an idempotent unit of work in a retried `SERIALIZABLE` transaction. | | `withSerializableTransaction(executor, operation, options?)` | Run caller-owned application and sharing work in one retried `SERIALIZABLE` transaction. | | `isRetryableSerializationError(error)` | Whether an error (or its `cause` chain) is a retryable serialization or deadlock failure. | | `asSerializablePostgresTransaction(transaction)` | Compile-time assertion that an ORM transaction you opened is `SERIALIZABLE`. | Retries replay the whole unit of work, so callbacks must not perform non-transactional side effects. # PostgreSQL adapter (/docs/sharing-postgres) > @rolebook/sharing-postgres: an ORM-neutral PostgreSQL storage adapter for sharing. `@rolebook/sharing-postgres` stores sharing state in your PostgreSQL database, next to the resources it protects. It does not import a driver or an ORM: it takes a small parameterized executor that you build over `pg`, Postgres.js, Kysely, Drizzle, or your own database boundary. - One adapter per concrete resource table. Sharing rows are separate tables (owner, member, invitation, audit, idempotency, lifecycle, revision floor) with composite foreign keys to the application row's `(tenant, id)` key, never a polymorphic `(resource_type, resource_id)` pair. - Sharing mutations run at `SERIALIZABLE` isolation, locks the application row and the required workspace member rows (`FOR SHARE`), compares exact resource versions and sharing revisions, and writes the idempotency record and audit event before committing. Serialization failures and deadlocks retry. - Migrations are generated per resource, idempotent, and validate the existing schema before changing it. - PostgreSQL 13 or later is required (`gen_random_uuid()`). - [Named authorized queries](/docs/sharing/authorized-queries) serve registered, filtered and sorted queries over a resource table on the checked `createPgExecutor(pool)` executor. ## 1. An executor [#1-an-executor] The executor runs parameterized SQL and opens `SERIALIZABLE` transactions. The custom executor below is a Sharing adapter example. For [protected application updates](/docs/sharing-postgres/protected-updates), use the checked `createPgExecutor(pool)` factory for both the resource adapter and policy store; a structural custom executor is not accepted by that wrapper. With node-postgres: ```ts title="executor.ts" group=pg import pg from "pg"; import { asSerializablePostgresTransaction, type ParameterizedSqlExecutor, type SqlResult, type SqlRow, type SqlValue, } from "@rolebook/sharing-postgres"; const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL }); async function run( client: pg.Pool | pg.PoolClient, sql: string, values: readonly SqlValue[], ): Promise> { const result = await client.query(sql, [...values]); return { rows: result.rows as TRow[], rowCount: result.rowCount ?? 0 }; } export const executor: ParameterizedSqlExecutor = { query: (sql, values = []) => run(pool, sql, values), async transaction(options, operation) { if (options.isolationLevel !== "serializable") throw new Error("SERIALIZABLE only"); const client = await pool.connect(); try { await client.query("BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE"); const transaction = asSerializablePostgresTransaction({ query: (sql, values = []) => run(client, sql, values), transaction: async () => { throw new Error("Nested transactions are not supported"); }, }); const result = await operation(transaction); await client.query("COMMIT"); return result; } catch (error) { await client.query("ROLLBACK").catch(() => undefined); throw error; } finally { client.release(); } }, }; ``` Two requirements: a call with no values must be sent as a simple query, because migration steps are multi-statement SQL (node-postgres does this; with Postgres.js use `unsafe()`), and the transaction must really be `SERIALIZABLE`. `asSerializablePostgresTransaction()` is an explicit assertion that it is: the adapter cannot inspect a driver's isolation level at runtime. ## 2. A resource descriptor [#2-a-resource-descriptor] The descriptor names the application table and how to build a trusted snapshot from its row: ```ts title="projects.ts" group=pg import { trustedResource } from "rolebook"; import type { PostgresResourceDescriptor } from "@rolebook/sharing-postgres"; export const projectTable = { resourceType: "project", table: ["app", "project"], tenantColumn: "workspace_id", idColumn: "id", tenantSqlType: "uuid", resourceSqlType: "uuid", resourceVersionColumn: "version", // Globally unique per concrete application table. sharingTablePrefix: "project", resourceColumns: ["visibility", "archived_at"], resourceFromRow: (row) => trustedResource( { type: "project", id: String(row.id) }, [{ type: "workspace", id: String(row.workspace_id) }], { visibility: String(row.visibility), archived: row.archived_at !== null }, ), } as const satisfies PostgresResourceDescriptor; ``` | Field | Meaning | | --- | --- | | `resourceType` | The sharing resource type this table holds. | | `table` | The application table, `"name"` or `["schema", "name"]`. | | `tenantColumn`, `idColumn` | The columns of its `(tenant, id)` key. | | `tenantSqlType`, `resourceSqlType` | `"text"` (default) or `"uuid"`; must match the real columns exactly. | | `resourceVersionColumn` | A version that changes whenever a field authorization reads changes. | | `sharingRevisionColumn` | Optional name of the generated sharing revision column (default `rolebook_sharing_revision`). | | `resourceFromRow(row)` | Builds the `TrustedResource` from the locked row, ancestry included. | | `resourceVersion(row)` | Optional: derive the version string from the row. | | `resourceColumns` | Optional: the extra columns your callbacks read, instead of `SELECT *`. Unquoted, case-sensitive names. | | `sharingTablePrefix` | Required, globally unique prefix for this table's sharing tables. | With `resourceColumns`, application-table reads select only the key, version, and revision columns plus the listed ones; an unlisted column arrives as `undefined`. A `uuid` column accepts PostgreSQL's input forms (case variants, braces, missing hyphens) on the adapter's direct methods and returns the canonical lowercase hyphenated form. The sharing module compares resource IDs exactly as given, so always pass it the canonical form. ## 3. Fences and the adapter [#3-fences-and-the-adapter] ```ts title="sharing.ts" group=pg import { createPostgresEmailInvitationRecipientFence, createPostgresMembershipEligibilityFence, createPostgresSharingAdapter, } from "@rolebook/sharing-postgres"; const lockEligibleSubjects = createPostgresMembershipEligibilityFence({ table: ["auth", "member"], // your real organization-member table, for example Better Auth's tenantColumn: "organization_id", subjectIdColumn: "user_id", }); const lockInvitationRecipient = createPostgresEmailInvitationRecipientFence({ membershipTable: ["auth", "member"], membershipTenantColumn: "organization_id", membershipSubjectIdColumn: "user_id", userTable: ["auth", "user"], userIdColumn: "id", userEmailColumn: "email", userEmailVerifiedColumn: "email_verified", }); export const projectAdapter = createPostgresSharingAdapter({ executor, resource: projectTable, lockEligibleSubjects, lockInvitationRecipient, }); ``` Then pass `projectAdapter` as the `adapter` of the `project` type in [`defineSharing()`](/docs/sharing/setup). See [fences](/docs/sharing-postgres/fences) for what each fence locks, mapped workspace roles, teams, and the policy fence. | Option | Meaning | | --- | --- | | `executor` | The executor above. | | `resource` | The resource descriptor. | | `lockEligibleSubjects` | Required. Locks and checks tenant eligibility in the mutation transaction. | | `lockInvitationRecipient` | Required for email invitations; without it they fail closed. | | `revalidateAuthorizationFacts` | Required when mapped workspace roles or teams authorize mutations. | | `groupSubjectTypes` | Group subject types that may never own (default `["team"]`). | | `fencePolicy` | The policy fence, for [versioned sharing](/docs/sharing/versioned). | | `clock` | Inject a clock for deterministic tests (otherwise the database clock decides expiry). | | `serializableRetry` | `attempts` (default 3, including the first), `backoffMs`, `wait`. | ## 4. Migrations and resources [#4-migrations-and-resources] Generate the migration steps for the descriptor and apply them on every deploy: ```ts group=pg import { applyPostgresMigrations, createResourceSharingMigrations } from "@rolebook/sharing-postgres"; await applyPostgresMigrations(executor, createResourceSharingMigrations(projectTable)); ``` When the application creates a project, create its owner in the same transaction with `initializeResourceInTransaction()`. See [migrations](/docs/sharing-postgres/migrations) and [lifecycle](/docs/sharing-postgres/lifecycle). ## Clocks [#clocks] Without a `clock`, every expiry comparison uses the database's `clock_timestamp()` at the statement that compares, so time spent waiting for locks cannot extend an invitation or a membership. In deterministic tests pass the same `clock` to the adapter and to `createSharing()`. ## Protected application updates [#protected-application-updates] For an application-owned resource/action SQL update, the [protected update wrapper](/docs/sharing-postgres/protected-updates) authorizes, seals authority and commits the callback result, durable receipt and outbox event together. Unlike ordinary Sharing mutations, it never automatically retries the transaction or callback. This embedded PostgreSQL API requires complete local authority and preserves incarnation, ancestry, owner and sharing state while advancing the declared resource version. It is not a field-mediated or HTTP transaction API. # PostgreSQL resource lifecycle (/docs/sharing-postgres/lifecycle) > Initializing owners, and deleting or moving resources atomically with their sharing state. Sharing state belongs to an application row. Creating, deleting, or moving that row must change the sharing state in the **same** `SERIALIZABLE` transaction, or a private resource can outlive its grants or carry them somewhere they were never given. ## Initializing a resource [#initializing-a-resource] A resource has exactly one owner, created when the resource is created: ```ts import type { PostgresSharingAdapter, ParameterizedSqlExecutor } from "@rolebook/sharing-postgres"; import { withSerializableTransaction } from "@rolebook/sharing-postgres"; declare const executor: ParameterizedSqlExecutor; declare const projectAdapter: PostgresSharingAdapter; const workspaceId = "8c3a3b8e-2f0e-4c1b-9d55-1f0f1b5b8a10"; const projectId = "5d2a7c9e-6b1f-4f57-8e3a-0b9c1d2e3f40"; const user = { type: "user", id: "user_123" }; const result = await withSerializableTransaction(executor, async (transaction) => { await transaction.query( "INSERT INTO app.project (workspace_id, id, title, version) VALUES ($1, $2, $3, 1)", [workspaceId, projectId, "Q3 launch"], ); return projectAdapter.initializeResourceInTransaction(transaction, { tenantId: workspaceId, resourceId: projectId, owner: user, actor: user, occurredAt: new Date(), }); }); // "applied" | "already_initialized" | "identity_ineligible" | "owner_mismatch" | "group_owner" | "not_found" ``` - Initialization locks and verifies both the actor and the intended owner through the eligibility fence before creating or inspecting ownership; an ineligible one is `identity_ineligible`. - Retrying with the same owner is `already_initialized`; a different owner is `owner_mismatch`, and ownership is unchanged. A group owner is `group_owner`. - It records a `resource.initialized` audit event and mints the resource's incarnation identifier. - `initializeResourceInTransaction()` accepts only a `SerializablePostgresTransaction`. `initializeResource(input)` opens its own transaction, for resources that already exist. - A resource without an owner row stays fail-closed: `readAccess()` returns nothing for it. - A key whose revision floor reached the largest `bigint` cannot start a new generation: initialization throws `PostgresLifecycleConflictError` and writes nothing. ## Deleting and moving [#deleting-and-moving] `resourceDeleted()` and `resourceMoved()` return `"unsupported"`: the adapter never mutates an application row through a standalone call. Use `withLifecycleTransaction()` and the matching `...InTransaction()` method instead. Your callback performs the conditional application change on the supplied transaction, using the supplied pre-version in its `WHERE` clause: ```ts import type { PostgresSharingAdapter } from "@rolebook/sharing-postgres"; declare const projectAdapter: PostgresSharingAdapter; declare const project: { readonly version: string; readonly sharingRevision: string }; declare const idempotencyFingerprint: string; const actor = { type: "user", id: "user_123" }; const [workspaceA, workspaceB, projectId] = ["ws_a", "ws_b", "project_1"]; const nextVersion = String(Number(project.version) + 1); const moved = await projectAdapter.withLifecycleTransaction((transaction) => projectAdapter.resourceMovedInTransaction(transaction, { fromTenantId: workspaceA, toTenantId: workspaceB, resourceId: projectId, expectedResourceVersion: project.version, expectedSharingRevision: project.sharingRevision, resultingResourceVersion: nextVersion, actor, requiredEligibleSubjects: [actor], idempotencyKey: "move-project_1-to-ws_b", idempotencyFingerprint, occurredAt: new Date(), moveResource: async (tx) => { const changed = await tx.query( `UPDATE app.project SET workspace_id = $3, version = $4 WHERE workspace_id = $1 AND id = $2 AND version = $5`, [workspaceA, projectId, workspaceB, nextVersion, project.version], ); return changed.rowCount === 1 ? "applied" : "conflict"; }, }), ); // "applied" | "already_applied" | "not_found" | "conflict" | "identity_ineligible" ``` `resourceDeletedInTransaction(transaction, { tenantId, resourceId, deleteResource, ... })` works the same way with a `deleteResource` callback. What the adapter guarantees: - It adds and deduplicates the `actor` in `requiredEligibleSubjects`, locks every source-tenant identity before the callback, and returns `identity_ineligible` without calling it if any is stale. - **Moves.** Before the callback it locks and verifies the retained owner in the destination tenant and removes the source key's live sharing rows (memberships, invitations, mutation idempotency), so the application's `UPDATE` passes the restricting foreign keys. After the callback it re-attaches **only the owner** at the destination, with its original creation metadata. Members and invitees from the old tenant never gain access in the new one, and any grant the callback writes at the destination fails the move. A move must write its declared `resultingResourceVersion`. A move between two spellings of the same `uuid` tenant is a same-tenant move and keeps its grants. - **Deletions.** The adapter verifies that none of the resource's sharing rows survive under any tenant. A deletion authorized against an earlier generation of a re-created, not yet initialized key returns `conflict` instead of deleting the replacement. - It increments the sharing revision and records the lifecycle idempotency record and audit event before commit. A lifecycle record is bound to the command's fingerprint and to the sharing revision it was authorized against, so a retry replays as `already_applied` while a same-key command authorized against a re-created resource conflicts. - After the callback starts, a non-`applied` result or a failed postcondition throws `PostgresLifecycleConflictError`, and the transaction is marked rollback-only even if the error is caught. The same holds for errors the callback throws, including non-`Error` values. Use only the transaction you are given. Write the conditional `UPDATE` or `DELETE` with the pre-version. Let a `PostgresLifecycleConflictError` escape so the transaction rolls back. Perform no external side effects: retries replay the whole unit of work. Never call a standalone lifecycle convenience after the application change committed: it cannot repair a split transaction. Cross-tenant moves are unsupported by default and work only through this complete contract, including the restricting keys from [the migrations](/docs/sharing-postgres/migrations#upgrades-handled-by-reruns): with them, an `UPDATE` of an initialized resource's `(tenant, id)` outside the move path fails with `23001`. Same-tenant hierarchy moves use the same contract and must update the resource version, so conditions and ancestry are evaluated again. # Managed deletion (/docs/sharing-postgres/managed-deletion) > Delete one authorized resource and its live sharing state in one local transaction. `withManagedDelete()` performs one generated, conditional business-row deletion. The same transaction authorizes the resource/action, removes its live sharing state, retains lifecycle evidence, seals the original authority dependencies and records one receipt and one outbox event. It uses the existing managed descriptor and complete local identity and policy fences from [protected updates](/docs/sharing-postgres/protected-updates). ## Delete an exact incarnation [#delete-an-exact-incarnation] Configure a destructive action in the Sharing resource definition, such as `delete` mapped to `document:delete`, and grant that permission through your policy. The trusted server chooses this action for its deletion command; never accept an arbitrary action name from an untrusted request. Resource-wide authorization is required. A field-only grant cannot authorize deletion. ```ts import { createPostgresProtectedWriteAdapter, type ManagedDeleteIntent } from "@rolebook/sharing-postgres"; // The configured instance includes a managed descriptor and complete local authority fences. declare const protectedAdapter: ReturnType; declare const incarnationId: string; declare const currentVersion: string; const scoped = protectedAdapter.forScope({ tenantId: "application_namespace", actor: { type: "user", id: "user_123" }, }); const intent = { resource: { type: "document", id: "document_1" }, action: "delete", incarnationId, idempotencyKey: "delete-document_1-once", expectedVersion: currentVersion, } satisfies ManagedDeleteIntent; const outcome = await scoped.withManagedDelete(intent); // On an uncertain COMMIT, use this exact intent in trusted server recovery. const recovered = await scoped.lookupManagedDeleteReceipt(intent); ``` The operation has no SQL callback, patch or post-version. Its result contains `deleted: true`, the resource reference, deleted incarnation and deleted resource version. The receipt metadata describes the authority used before deletion. Authorization happens before the expected-version comparison. Missing resources, wrong incarnations and denied actions fail closed. ## Atomic cleanup and retained evidence [#atomic-cleanup-and-retained-evidence] The adapter deletes only the matching namespace, resource ID, incarnation and version. It proves that the business row and all live owner, membership, invitation and sharing-idempotency rows are absent. The existing lifecycle code retains the revision floor, lifecycle outcome and audit for the deleted incarnation. The protected receipt and outbox event are retained independently of the deleted resource; there is exactly one protected event for this operation. The final seal follows all deletion and lifecycle DML. It revalidates policy, identity eligibility, complete group/assignment/absence facts and the **original** identity and membership expiry dependencies, including dependencies whose granting rows have just been removed. A failed seal rolls the deletion and its evidence back together. Validity is established at the final seal; this is not a promise about the exact physical commit timestamp. Resource ancestry must come from the locked, authoritative resource projection. Scoped assignments and group facts remain covered by the complete local identity fences after deletion. This API does not discover or fence arbitrary external ancestor tables or graph traversal dependencies. All participating writers must obey the existing revision/fence contract. ## Replay and recreation [#replay-and-recreation] The `managed.delete.v1` receipt binds the namespace, actor, key, resource, action, expected version, incarnation, authority epoch and configured descriptor digest. Reusing its key with changed intent conflicts. Exact replay returns the original receipt before current schema or authorization checks, without another delete or outbox event. This remains true after recreation or schema drift. Reinitializing a resource under the same ID creates a fresh incarnation and advances the retained sharing revision floor. A fresh request for the old incarnation cannot delete that replacement. A recovered receipt is historical outcome evidence, never permission to act on a replacement. A missing receipt does not prove that an in-flight or ambiguous commit cannot succeed. ## On a hierarchy-enrolled tenant [#on-a-hierarchy-enrolled-tenant] On a tenant whose hierarchy is enrolled (see [inherited access](/docs/sharing/inheritance)), the same `withManagedDelete()` runs through the hierarchy command engine, inside its own protected transaction, when the adapter is given the deployment's hierarchy control facade: ```ts import { createPostgresProtectedWriteAdapter, type PostgresInheritanceControl, } from "@rolebook/sharing-postgres"; declare const options: Parameters[0]; declare const control: PostgresInheritanceControl; // from createPostgresHierarchyControl const protectedAdapter = createPostgresProtectedWriteAdapter({ ...options, hierarchy: { control } }); ``` Without `hierarchy`, an enrolled delete refuses `HIERARCHY_UNAVAILABLE` / `enrolled` after the current gate and before any journal lookup or effect. - **Leaves only.** A resource with any child refuses `PROTECTED_WRITE_REFUSED` / `hierarchy_not_leaf` and nothing changes. Delete a subtree bottom-up, one leaf per call; descendants are never orphaned. - **Authorization.** The protected action on the resource's inherited snapshot, plus the hierarchy command map: the type's `delete` and `management.members` on the resource, and the parent's `removeChild` and `management.members` (for a root, the bootstrap `rootPlacement`). Any denial, and a missing resource, is `PROTECTED_WRITE_DENIED`; a structural refusal is reported only after every check, the protected action included, allowed. - **Effects.** The business row, every live Sharing row, the revision floor, lifecycle record and audit, as on a flat tenant, then the resource's link; the parent path's subtree heights are repaired in the same transaction. - **Receipt.** Metadata version 2: the protected fields with the resource's pre-delete inherited evidence (its stored chain). The result and the `protected.delete.committed` event are unchanged. - **One final seal** covers the local identity, the inherited memberships the decisions relied on, and every decision read's `validUntil`; an expiry at or before it rolls everything back. - **Retry.** The journal lookup follows the hierarchy gate and precedes the first resource lock; a stored receipt returns verbatim. A serialization failure or deadlock reruns the whole attempt under the hierarchy control's retry policy, recapturing the clock, identity, evidence and seal. Exhaustion is `HIERARCHY_UNAVAILABLE` / `serialization_conflict`. ## Supported schema and transaction boundary [#supported-schema-and-transaction-boundary] The adapter owns one `SERIALIZABLE` transaction. On a flat tenant it does not automatically retry. Before taking its snapshot it takes deterministic schema-stability locks on the business target, live sharing, retained lifecycle and journal tables. The business target also takes the stronger deletion-specific lock, so concurrent inheritance attachment waits until this transaction releases it. These locks prevent concurrent trigger, rule and foreign-key changes through commit. Deletions sharing those tables serialize at the schema locks; ordinary DML remains compatible with those table locks, with normal row/fence contention still applying. Lock waits are bounded by the configured lifetime. Every live sharing, retained lifecycle and journal relation must also be an ordinary permanent table. PostgreSQL rejects inheritance, partitioning and row-level security (including forced RLS) on all these relations; SQLite rejects views, virtual/shadow tables and temporary name shadows. The existing managed-target checks still apply. Deletion additionally rejects user triggers or rules on live sharing, retained lifecycle and journal tables, and rejects foreign keys into the target or its live sharing tables except the exact first-party tenant/resource cascade edges. SQLite retains its exact first-party resource-key guard. General application cascade graphs, including otherwise harmless extra referring tables, are deliberately unsupported in this slice. Application DDL and migrations are trusted. Run the adapter migrations and preserve their schema, constraints, defaults and collations. These checks restrict supported side effects; they are not a sandbox against a malicious database owner, privileged DDL, custom SQL functions or a false identity resolver. One local adapter/resource is supported. General creation, movement, batch deletion, cross-adapter transactions and public consistency tokens remain outside this API. # Managed same-tenant moves (/docs/sharing-postgres/managed-moves) > Reparent one leaf resource using SQL-authoritative parent permissions in one transaction. `withManagedMove()` moves one existing leaf between two distinct root parents in the same namespace. The adapter reads both parents from one configured SQL table, checks the source remove and destination accept permissions, changes the child parent column and version, and advances its sharing revision. Owner, incarnation, direct memberships, invitations and previous sharing-idempotency records remain intact. This API requires the complete local identity and policy fences described in [protected updates](/docs/sharing-postgres/protected-updates), plus the existing `managed` descriptor. The parent column belongs in the full child projection but must not be writable through ordinary managed patches. The application resource projection must return exactly the SQL parent as the child's immediate ancestor; the adapter checks this agreement before and after the move. ## Configure authoritative parents [#configure-authoritative-parents] ```ts import type { PostgresManagedMoveDescriptor } from "@rolebook/sharing-postgres"; const managedMove = { parentIdColumn: "folder_id", parent: { resourceType: "folder", schema: "public", table: "folder", tenantColumn: "tenant_id", idColumn: "id", versionColumn: "version", incarnationColumn: "incarnation", userColumns: ["tenant_id", "id", "version", "incarnation", "enabled"], fields: [{ field: "enabled", column: "enabled", codec: "boolean" }], }, sourceAction: "remove", destinationAction: "accept", } satisfies PostgresManagedMoveDescriptor; ``` Pass `managedMove` to the protected adapter factory beside `managed`. Parent IDs, versions and incarnations use text columns. Map policy attributes explicitly with `text`, `boolean` or `safe-integer` codecs; nullable attributes require `nullable: true`. Enumerate every physical column in order in `userColumns`. Optional `expiresAtColumn` uses `timestamptz`, retained at microsecond precision. The policy must declare `folder` as a root and the child as its immediate leaf. Parent permissions come from the complete fenced local identity assignments and groups. A parent type with its own Sharing membership configuration is unsupported and rejected. The adapter constructs parent resources directly from SQL, without a caller-provided parent projection. It checks whole-resource `folder:remove` and `folder:accept`; field-only allows do not suffice. Parent condition context contains the tenant ID, without an invented parent sharing revision. ## Move an exact incarnation [#move-an-exact-incarnation] ```ts import { createPostgresProtectedWriteAdapter, type ManagedMoveIntent } from "@rolebook/sharing-postgres"; declare const adapter: ReturnType; const scoped = adapter.forScope({ tenantId: "namespace_1", actor: { type: "user", id: "alice" } }); const intent = { resource: { type: "document", id: "doc_1" }, action: "move", incarnationId: "document-incarnation", expectedVersion: "1", postVersion: "2", idempotencyKey: "move-doc_1-once", sourceParent: { id: "folder_a", incarnationId: "folder-a-incarnation", version: "1" }, destinationParent: { id: "folder_b", incarnationId: "folder-b-incarnation", version: "3" }, } satisfies ManagedMoveIntent; const outcome = await scoped.withManagedMove(intent); const recovered = await scoped.lookupManagedMoveReceipt(intent); ``` The trusted application chooses the child action mapped to its move command. Caller versions and incarnations are expectations checked against locked authoritative rows, not permission evidence. The child must be allowed both before and after movement. Both parent permissions, unchanged parent snapshots, policy and complete identity/group/absence facts are revalidated. Original parent, identity and membership expiry dependencies survive until the advancing final seal. Validity is established at that seal, not at the physical COMMIT timestamp. The generated conditional update and existing lifecycle bookkeeping run in the same owned transaction. Failed authorization, stale expectations, schema drift or a failed final seal rolls back the move, lifecycle audit, protected receipt and outbox event together. The result records the child version/incarnation/sharing revision and both parent version/incarnation tuples. ## On a hierarchy-enrolled tenant [#on-a-hierarchy-enrolled-tenant] On a tenant whose hierarchy is enrolled (see [inherited access](/docs/sharing/inheritance)), the stored hierarchy, not the application's parent column, is the ancestry Rolebook decides with. Give the protected adapter the deployment's hierarchy control facade and, if the application keeps one, its parent column: ```ts import { createPostgresProtectedWriteAdapter, type ManagedMoveIntent, type PostgresInheritanceControl, } from "@rolebook/sharing-postgres"; declare const options: Parameters[0]; declare const control: PostgresInheritanceControl; // from createPostgresHierarchyControl const adapter = createPostgresProtectedWriteAdapter({ ...options, hierarchy: { control, parentIdColumn: "folder_id" }, }); const intent = { resource: { type: "folder", id: "folder_7" }, action: "move", incarnationId: "folder-7-incarnation", expectedVersion: "4", postVersion: "5", idempotencyKey: "move-folder_7-once", // A recursive type names its parent type; otherwise it defaults to the declared parent type. sourceParent: { type: "folder", id: "folder_a", incarnationId: "a-incarnation", version: "2" }, destinationParent: { type: "folder", id: "folder_b", incarnationId: "b-incarnation", version: "9" }, } satisfies ManagedMoveIntent; await adapter.forScope({ tenantId: "namespace_1", actor: { type: "user", id: "alice" } }).withManagedMove(intent); ``` The move runs through the hierarchy command engine inside the protected transaction. Without `hierarchy` it refuses `HIERARCHY_UNAVAILABLE` / `enrolled` after the current gate. The flat `managedMove` descriptor is not used on an enrolled tenant. - **Parents** are placed resources of the hierarchy. Each expectation's `version` is the parent's resource version and `incarnationId` its Sharing incarnation, compared on the stored bytes; the source must be the stored parent. A wrong source is rejected before the adapter looks up any parent by the source id the request names, so an existing and an absent id answer the same. A stale target, a stale parent or a wrong source is `PROTECTED_WRITE_POSTCONDITION_FAILED`. An omitted `type` is the moved type's declared parent type. - **Subtrees.** The resource moves with everything below it: its link is re-parented, heights are repaired on the old path and then the new one, and descendants follow the moved link. Stored memberships stay where they are; what changes is the ancestry the subtree inherits from. Members of the destination's ancestors gain inherited access to the moved subtree; the move proof constrains only the actor. - **Refusals** (only after every authorization check, the protected action included, allowed; with no effect): `PROTECTED_WRITE_REFUSED` with `hierarchy_cycle` (the destination is the resource or below it), `ancestry_cap` (the subtree would end below 16 ancestors), `hierarchy_edge_refused` (the policy does not allow that parent type) or `hierarchy_exists` (the destination is the current parent). A parent `type` outside the hierarchy command map is refused `hierarchy_edge_refused` before authorization: that answer depends only on the request and the configuration. - **Authorization.** The protected action on the resource before the move and again on its new chain; the type's `move` and `management.members` on the resource; `removeChild` on the source and `addChild` on the destination, each with that parent's `management.members`; and the move proof: for every permission of every type at or below the moved type, the actor must already hold an unrestricted allow at a common ancestor of both positions (with no common ancestor, also the bootstrap `rootPlacement`), and no actor role may carry a deny for those permissions. A move can never extend the actor's authority over the subtree. Any denial is `PROTECTED_WRITE_DENIED`. - **Effects and receipt.** The business row's version advances to `postVersion` (and `parentIdColumn` to the destination); key, incarnation, sharing revision, owner and members are unchanged. The receipt records metadata version 2 with the pre-move inherited evidence; the result and the `protected.move.committed` event name both parents and the unchanged sharing revision. Moves never cross tenants and never move to or from the root position (use `structure.move` of the control facade for that). - **One final seal** covers the local identity, the inherited memberships every decision relied on, and the pre- and post-move evidence. A serialization failure or deadlock reruns the whole attempt with fresh capture; exhaustion is `HIERARCHY_UNAVAILABLE` / `serialization_conflict`. ## Recovery and boundaries [#recovery-and-boundaries] The `managed.move.v1` receipt binds the complete intent, configured mappings and authority epoch. A changed intent with the same key conflicts. Exact replay recovers the historical receipt before current authorization or schema validation and never executes a second move. After an uncertain COMMIT use the exact-intent lookup; no receipt is not proof that an in-flight commit aborted. Historical receipt recovery never grants access to a replacement incarnation. Only one child, one namespace, one mapped root-parent table and one adapter-owned local transaction are supported. IDs are opaque within their resource types: equal child and parent IDs do not form a hierarchy cycle because these are distinct types. Same source/destination parent IDs are rejected. There is no create, subtree or multi-level move, batch move, cross-tenant/cross-adapter operation, remote authority, parent Sharing membership source or public consistency token in this API. Ordinary permanent tables and exact projections are required. Existing managed safeguards reject unsupported triggers, rules, generated columns, RLS, inheritance, partitioning, temporary shadows and cascade graphs where applicable. All participating writers must honor the identity/revision contract. SQL mapping is trusted server configuration; it is not accepted from the request. # Managed field updates (/docs/sharing-postgres/managed-updates) > Apply a declared patch with field authorization before and after a PostgreSQL update. `withManagedUpdate()` applies a declared patch using SQL generated by Rolebook. Every declared field must be allowed by the canonical policy evaluator against both the authoritative before state and the resulting state. A field-only grant can authorize this method. A deny covering any declared field rejects the complete update. The [raw protected callback](/docs/sharing-postgres/protected-updates) keeps its resource/action contract. Configuring managed updates does not make arbitrary callback SQL field-safe. ## Configure the managed mapping [#configure-the-managed-mapping] Add `managed` when binding the existing sharing adapter and VersionedSharing instance with `createPostgresProtectedWriteAdapter()`. Keep the same checked executor, local identity projection and fences described in [protected updates](/docs/sharing-postgres/protected-updates). ```ts group=postgres-managed import type { SharingResourceConfigurations, VersionedResourceSharing } from "@rolebook/sharing"; import { createPostgresLocalIdentityProjection, createPostgresProtectedWriteAdapter, type PostgresSharingAdapter } from "@rolebook/sharing-postgres"; const projection = createPostgresLocalIdentityProjection({table:["app", "authz_identity_projection"]}); declare const sharingAdapter: PostgresSharingAdapter; declare const versionedSharing: VersionedResourceSharing; const protectedAdapter = createPostgresProtectedWriteAdapter({ adapter: sharingAdapter, sharing: versionedSharing, identity: projection.identity, environmentId: "production", authorityEpoch: "installation-epoch-1", journalPrefix: "app_authorization", managed: { target: { schema: "app", table: "document", // All user columns, in their actual catalog order, including migration-added columns. userColumns: ["tenant_id", "id", "title", "visibility", "version", "rolebook_sharing_revision"], }, fields: [ { field: "title", column: "title", codec: "text" }, { field: "visibility", column: "visibility", codec: "text" }, ], }, }); ``` The target must match the original resource adapter. The trusted projection receives native driver values; normalize policy attributes explicitly, such as PostgreSQL bigint text into a safe integer where appropriate. Its trusted `resourceFromRow` projection must include every policy-visible attribute, including attributes that cannot be written through the patch. The adapter validates the live schema inside the owned transaction. Field names are flat; nested paths and duplicate mappings are unsupported. Identity, version and sharing columns cannot be mapped as writable fields. Supported patch codecs are text, boolean and safe integer, with explicit `nullable: true` to permit SQL NULL. Missing fields mean unchanged; NULL means set NULL. JSON, floating-point values, binary data and timestamps are outside this managed scalar contract. The exact database column type must match its configured codec. Unknown fields and unsupported values fail closed. ## Apply a patch [#apply-a-patch] ```ts group=postgres-managed const scoped = protectedAdapter.forScope({ tenantId: "workspace_1", actor: { type: "user", id: "user_123" }, }); declare const incarnationId: string; declare const currentVersion: string; declare const nextVersion: string; const intent = { resource: { type: "document", id: "document_1" }, action: "update", incarnationId, expectedVersion: currentVersion, postVersion: nextVersion, idempotencyKey: "rename-document_1-once", patch: { title: "New title" }, }; const outcome = await scoped.withManagedUpdate(intent); ``` Versions are opaque application tokens. `expectedVersion` must match the locked resource and `postVersion` must be nonempty and different. Rolebook does not derive a numeric version from the lifecycle incarnation or claim global version ordering. Applications remain responsible for avoiding version reuse when their concurrency model requires that. All before-state field checks complete before the generated update. Rolebook then reloads the resulting row with a separate SELECT, checks the actual stored values and complete target-row change set, and evaluates the same action and fields against the resulting authoritative state. A failed field decision, unexpected mutation, stale version or seal rolls back the application update, receipt and outbox together. An empty patch is invalid. An allowed patch whose values are already present still requires all field checks, advances the version and records one receipt/event. Denies on undeclared fields do not prevent a patch to unrelated fields. ## Recovery and boundaries [#recovery-and-boundaries] Use `scoped.lookupManagedReceipt(intent)` to reconcile an uncertain commit. Exact replay returns the original receipt without re-evaluating today's policy or requiring today's resource version. The receipt binds the computed mapping, target, actor, namespace, patch and expected/post versions. Reusing a key with another mapping or intent conflicts. Raw and managed operations are distinct. No business operation is automatically replayed after a database failure. The supported target is an ordinary permanent table with a complete verified column projection. User triggers, rewrite rules, inheritance, generated columns and automatic derived-column updates are unsupported in this PostgreSQL slice. Only version is exempt from the unchanged-column rule, and its stored value must equal `postVersion` exactly. The physical-row check proves nothing about other rows, tables or deferred triggers, including foreign-key `ON UPDATE CASCADE` effects on referencing rows. Trusted schema and participating source-writer contracts still apply. This is an embedded transaction API; it does not extend a SQL transaction over HTTP. ## Atomic managed batches [#atomic-managed-batches] `withManagedUpdates()` applies 1–32 updates to distinct existing resources through the same configured adapter and tenant scope. Each item uses the same field, incarnation and version checks as a single managed update. The batch shares one transaction and lifetime; final persisted-state and authority checks run after the last update. Any failure rolls back every update, the single receipt and its single outbox event. There is no per-item partial success. ```ts group=postgres-managed import type { ManagedUpdateBatchIntent } from "@rolebook/sharing-postgres"; declare const secondIncarnationId: string; declare const secondCurrentVersion: string; declare const secondNextVersion: string; const batchIntent: ManagedUpdateBatchIntent = { idempotencyKey: "rename-two-documents-once", updates: [ { resource: { type: "document", id: "document_1" }, action: "update", incarnationId, expectedVersion: currentVersion, postVersion: nextVersion, patch: { title: "First title" }, }, { resource: { type: "document", id: "document_2" }, action: "update", incarnationId: secondIncarnationId, expectedVersion: secondCurrentVersion, postVersion: secondNextVersion, patch: { title: "Second title" }, }, ], }; const batchOutcome = await scoped.withManagedUpdates(batchIntent); // After an uncertain commit, reconcile using the original complete batch intent: const recoveredBatch = await scoped.lookupManagedUpdatesReceipt(batchIntent); ``` Choose either the single-update or batch example for a given set of expected versions; do not apply the preceding single update first and then reuse its stale expected version in this batch. The receipt result contains `updates` entries with `resource` and resulting `version`, ordered by resource ID. One environment/tenant/actor-bound key covers the entire batch. Input order is canonicalized; reordered identical items replay the original receipt. A changed item, mapping or complete intent under that key conflicts. Missing receipt evidence does not prove rollback. PostgreSQL acquires resource locks in deterministic resource-ID order; SQLite retains its single-writer transaction behavior. No automatic retry, cross-adapter transaction, create, delete or move operation is added. The existing local-authority and supported-driver limits still apply. # PostgreSQL migrations (/docs/sharing-postgres/migrations) > Generating, applying, upgrading, and rolling back the sharing and policy-store schema on PostgreSQL. `createResourceSharingMigrations(descriptor)` returns the ordered steps for one resource table: the sharing tables, their indexes and foreign keys, the generated `rolebook_sharing_revision` column, and a unique `(tenant, id)` index on the application table (PostgreSQL requires the referenced composite key to be unique; review that index before applying it to a large table). ```ts import { applyPostgresMigrations, createPolicyStoreMigrations, createResourceSharingMigrations, type ParameterizedSqlExecutor, type PostgresResourceDescriptor, } from "@rolebook/sharing-postgres"; declare const executor: ParameterizedSqlExecutor; declare const projectTable: PostgresResourceDescriptor; declare const folderTable: PostgresResourceDescriptor; // On every deploy, the complete lists: await applyPostgresMigrations(executor, createResourceSharingMigrations(projectTable)); await applyPostgresMigrations(executor, createResourceSharingMigrations(folderTable)); await applyPostgresMigrations(executor, createPolicyStoreMigrations()); // only for versioned sharing ``` ## How the runner applies steps [#how-the-runner-applies-steps] `applyPostgresMigrations(executor, steps, options?)` runs **each step as its own transaction**, so a step that has to lock a table holds the lock only until that step commits: - Each step starts with `SET LOCAL lock_timeout` (`lockTimeoutMs`, 5 seconds by default). A step that cannot get its lock in time, deadlocks, or hits a serialization failure rolls back whole and is retried after a backoff (`attempts`, 5 by default; `backoffMs`, `wait`). - Any other error, or the last failed attempt, throws `PostgresMigrationError` with the `step` name, `attempts`, `sqlState`, and the driver error as `cause`. The steps before it stay committed. - Every step validates the existing schema before it changes anything and is idempotent, so the next run resumes where the last stopped. - Each step is one parameterless `executor.query()` call, run by PostgreSQL as one implicit `READ COMMITTED` transaction. A driver that prepares every call refuses the first step before anything changes. Run one migration process at a time. If you apply the steps with your own migration tool, do the same: one transaction per step, each starting with `SET LOCAL lock_timeout`, at `READ COMMITTED`, retried on a lock timeout. Do not apply the whole list in one transaction. Step names are stable across releases while their SQL changes: tightened validation, new columns, and foreign-key upgrades arrive as new SQL under existing names. A runner that records step names and skips the ones it has applied misses those changes. Re-run the complete list each time, or key recorded names by package version. Re-running is cheap on an up-to-date schema: every step that adds a column, sets a default, or creates an index first checks the catalog (no table lock) and runs DDL only when something is missing. ## What a rerun validates [#what-a-rerun-validates] Existing sharing tables are validated before reuse: column types and nullability, primary keys, the invitation recipient constraint, and index shapes (columns, uniqueness, operator classes, collation, sort order). Missing lookup indexes are recreated; incompatible ones are rejected. The sharing revision column must be `bigint NOT NULL` with a constant zero default. Repair incompatible drift explicitly before retrying. The tenant and resource SQL types must match the application columns exactly. `text` and `uuid` are the only accepted values, and both default to `text`. ## Upgrades handled by reruns [#upgrades-handled-by-reruns] Each of these arrives as new SQL in existing steps, applied by an ordinary rerun: - **Restricting keys.** Live foreign keys become `ON DELETE CASCADE ON UPDATE RESTRICT`. Re-adding a key validates every row under a `SHARE ROW EXCLUSIVE` lock, so schedule it like any foreign-key addition. Afterwards, application code that changes an initialized resource's tenant or ID directly fails with `23001`: move it through [`resourceMovedInTransaction()`](/docs/sharing-postgres/lifecycle). Deploy the adapter before running this migration. - **Revision floors.** `_rolebook_revision_floor` keeps the highest sharing revision each key has held, outliving deletions and moves, so a resource re-created under a reused ID never repeats a revision a stale authorization expects. It is backfilled once. Never prune it, and grant the adapter's role the same privileges as on the other sharing tables. - **Membership expiry.** Nullable `timestamptz` columns `expires_at` (member) and `membership_expires_at` (invitation). Existing rows stay permanent. - **Audit incarnations.** An `incarnation_id` on the owner row (default `gen_random_uuid()::text`) and on audit rows, plus an index. The run that adds the audit column attributes existing history by the lifecycle events of the time; it rewrites the owner and audit tables under `ACCESS EXCLUSIVE` locks, measured at about 10 seconds for 20,000 owners and 400,000 audit rows on PGlite. Plan a window for it. - **Idempotency `created_at`.** `created_at timestamptz NOT NULL DEFAULT now()` and two indexes, needed by [pruning](/docs/sharing/retention). On a large table you can build the indexes concurrently first; see the package README for the exact statements. - **Policy version on idempotency rows.** A nullable `policy_version` column, for versioned replays. During a rolling upgrade, an instance on an older release keeps working against the upgraded schema, with the effects the package README describes (for example audit rows it writes carry no incarnation and are not listed). ## Rollback [#rollback] `createResourceSharingRollbackMigrations(descriptor, { dropAudit? })` produces ordered `DROP TABLE` statements for sharing-owned state. Its first step verifies the retained descriptor registry: a mismatched descriptor, or a missing registry while sharing tables remain, aborts before any drop. It keeps audit history by default and never drops the application's revision column or `(tenant, id)` unique index. Each step may carry a `dataLoss` note. `{ dropAudit: true }` destroys audit history. Rollback is a deliberate operation: freeze sharing writes, export owner, member, invitation, audit, lifecycle, idempotency, and revision-floor data, restore the previous store, verify access-list parity, then execute the steps. It cannot restore application rows deleted or moved since, nor raw invitation secrets (never stored). A default rollback followed by a migration for the same descriptor preserves the audit history. ## Hierarchy control tables [#hierarchy-control-tables] `createResourceSharingMigrations()` also installs the descriptor's hierarchy control profile: the tenant writer barrier, hierarchy admission, hierarchy tenant, link, inventory and principal-generation tables, the profile's descriptor registry, and a tenant-key codec header. Unlike the sharing tables, these are always **schema-qualified** by the profile and never resolved through `search_path`. The profile is the descriptor's `hierarchyControl: { schema, prefix? }` (prefix default `rolebook_control`), or the schema of a schema-qualified `table`. An unqualified `table` without `hierarchyControl` is unbound: its migration throws. [`hierarchyControlTables()`](/docs/sharing-postgres/api#hierarchycontroltables) returns those qualified names. [`createHierarchyControlMigrations()`](/docs/sharing-postgres/api#createhierarchycontrolmigrations) installs the profile, including the group-graph tables. [`createPolicyCatalogRegistrationMigrations()`](/docs/sharing-postgres/api#createpolicycatalogregistrationmigrations) appends the profile to the policy catalog. A graph command built with [`createPostgresGroupGraphControl()`](/docs/sharing-postgres/api#createpostgresgroupgraphcontrol) uses that same profile and stores its configuration as `sha256:` plus 64 hexadecimal characters. The control tables, registry rows and bindings are **permanent**: no rollback removes them, and per-resource rollback leaves them in place. The first successful migration binds the family to its profile for good; a later migration naming another profile refuses ("already bound to another hierarchy control profile"). **Upgrading.** Rerun the resource migrations for every sharing family before deploying the new adapter. Until then every writer and read answers `HIERARCHY_UNAVAILABLE` (`profile_unbound`), and a refused write inside a registered caller-owned transaction marks that transaction rollback-only. **Tenant-key codec header.** One permanent row (`_tenant_key_codec`) records how the profile's control tables key tenants. It is `unbound` until the first tenant enrollment binds it to `text` or `uuid` from the registered descriptors' tenant column type. If the codec step installs the header on a profile that already has admitted tenants (enrolled by a binary that predates the header), it records `repair_required` instead. In that state every reader and writer bound to the profile, for flat and enrolled tenants alike, answers `HIERARCHY_UNAVAILABLE` (`profile_mismatch`) until an offline, trusted first-party repair runs. This release has no public repair API. The codec step and descriptor adoption run at `READ COMMITTED` whatever the session default (their first statement sets it), so an enrollment committed while they wait on the profile registry lock is seen, never missed. ## Policy-store tables [#policy-store-tables] `createPolicyStoreMigrations({ tablePrefix? })` and `createPolicyStoreRollbackMigrations({ tablePrefix? })` create and drop the policy-version, activation, active-pointer, tenant-role, tenant-role revision, and policy-audit tables; `policyStoreTables(prefix)` names them. The default prefix is `rolebook`. Apply them with `applyPostgresMigrations()` on every deploy, in the same database as the sharing tables. See [policy fence](/docs/sharing-postgres/fences#policy-fence). The migrations also create a permanent policy header (`_policy_header`: protocol version, the store's qualified identity `[schema, prefix]` and a catalog generation) and an append-only hierarchy catalog (`_policy_catalog`) beside those tables. Every store operation and the policy fence check the header first; a store migrated before this release answers `HIERARCHY_UNAVAILABLE` (`policy_profile_mismatch`) until its policy migrations are rerun. An empty catalog is the normal flat state. The rollback is one step that refuses while the catalog holds any registered hierarchy descriptor. # Protected application updates (/docs/sharing-postgres/protected-updates) > Authorize and commit one PostgreSQL resource/action update with a durable receipt. `createPostgresProtectedWriteAdapter()` runs a resource/action authorization check and your application SQL callback in one adapter-owned `SERIALIZABLE` PostgreSQL transaction. Before committing, it seals the authority used by the decision and records a durable receipt and outbox event atomically with the application change. This is a local, embedded TypeScript API. The Python, Go and Rust HTTP clients call the Sharing HTTP API. Their requests do **not** extend this SQL transaction across processes or provide a remote protected-write callback. ## What the callback may change [#what-the-callback-may-change] This API admits only a resource-wide action. A field-only grant cannot admit its raw SQL callback. The callback must advance the resource to the intent's `postVersion` while retaining its incarnation, ancestry, owner and sharing state. Changes to those authorization boundaries fail the postcondition and roll back. Use the [lifecycle API](/docs/sharing-postgres/lifecycle) for deletes and moves. For a declared field patch with before/after policy enforcement, use [managed updates](/docs/sharing-postgres/managed-updates). The application owns the SQL, input validation and meaning of the payload. Rolebook captures and hashes `payload` for durable idempotency; it does not map payload fields to columns, inspect arbitrary SQL for field safety, or enforce a managed field-level post-state policy. Resource/action authorization is not permission to treat opaque SQL as a field-mediated update. SQL remains trusted application code: confine the callback to the intended mutation and obey every participating source writer's revision and fence contract. Arbitrary SQL that bypasses that contract is not made safe by `SERIALIZABLE`. ## Bind the existing instances [#bind-the-existing-instances] Use the same `createPgExecutor(pool)` for the resource adapter and policy store, and configure the matching `createPostgresPolicyFence`. Pass the original PostgreSQL Sharing adapter and the `createVersionedSharing()` instance built with it. Reconstructed structural copies cannot supply transaction authority. Configure the resource adapter with both fences returned by `createPostgresLocalIdentityProjection()`: `lockEligibleSubjects` and `revalidateAuthorizationFacts`. Its `identity` resolver reads the complete local projection through the transaction. See [authorization fences](/docs/sharing-postgres/fences). ```ts import type { SharingResourceConfigurations, VersionedResourceSharing } from "@rolebook/sharing"; import { createPostgresLocalIdentityProjection, createPostgresProtectedWriteAdapter, type PostgresSharingAdapter, } from "@rolebook/sharing-postgres"; const projection = createPostgresLocalIdentityProjection({ table: ["app", "authz_identity_projection"], }); // These original instances were configured with the same checked executor, // policy fence and both projection fences described above. declare const sharingAdapter: PostgresSharingAdapter; declare const versionedSharing: VersionedResourceSharing; const protectedAdapter = createPostgresProtectedWriteAdapter({ adapter: sharingAdapter, sharing: versionedSharing, identity: projection.identity, environmentId: "production", authorityEpoch: "installation-epoch-1", journalPrefix: "app_authorization", maxLifetimeMs: 5_000, }); const scoped = protectedAdapter.forScope({ tenantId: "workspace_1", actor: { type: "user", id: "user_123" }, }); declare const incarnationId: string; declare const nextVersion: string; const intent = { resource: { type: "document", id: "document_1" }, incarnationId, action: "update", idempotencyKey: "rename-document_1-once", payload: { title: "New title" }, postVersion: nextVersion, }; const outcome = await scoped.withAuthorizedTransaction(intent, async (guard) => { const changed = await guard.executor.query( `UPDATE app.document SET title = $1, version = $2 WHERE tenant_id = $3 AND id = $4 AND version = $5`, ["New title", nextVersion, "workspace_1", "document_1", guard.resourceVersion], ); if (changed.rowCount !== 1) throw new Error("Update conflict"); return { version: nextVersion }; }); ``` The callback must return JSON-compatible data, including an explicit value rather than `undefined`. Every callback query uses `guard.executor` and must finish before the callback returns. The handle expires at callback completion, before authority sealing begins. Do not issue transaction control, use another executor, alter fence settings or perform external effects inside the callback. ## Complete local identity authority [#complete-local-identity-authority] The projection is application-owned, with a primary key on `(tenant_id, subject_type, id)`: | Column | PostgreSQL type | Meaning | | --- | --- | --- | | `tenant_id`, `subject_type`, `id` | `text NOT NULL` | Authorization namespace and actor identity. | | `eligible` | `boolean NOT NULL` | Whether the subject remains eligible. | | `revision` | `bigint NOT NULL` | Revision of the complete projection row. | | `assignments`, `groups` | `jsonb NOT NULL` | Complete arrays, including empty sets. | | `attributes` | `jsonb NOT NULL` | Complete policy-visible subject attributes. | | `expires_at` | nullable `timestamptz` | Earliest validity boundary of all represented facts. | Every relevant writer must update this row and advance its revision, including empty/nonempty group and assignment transitions. Facts in additional unfenced tables are outside this contract. The adapter makes no claim about freshness relative to an external identity provider. The scope may be an application authorization namespace; it need not represent a SaaS organization. The decision metadata records separate policy, tenant-role, sharing and identity/projection revisions. A `policyVersion` string alone is not the complete authority key. Expiry is checked in SQL against the advancing database clock at the common seal, not at an exact commit wall-clock instant. Ordinary Sharing test clocks do not override protected-write database time. ## Migrations and deployment ownership [#migrations-and-deployment-ownership] Run the journal migration through your application's migration owner before serving protected writes. It is repeatable and validates existing table shape; incompatible schemas fail closed. It is not run implicitly by adapter construction. Resource, policy and projection setup remain separate prerequisites. ```ts import { applyPostgresMigrations, createProtectedWriteMigrations, type ParameterizedSqlExecutor, } from "@rolebook/sharing-postgres"; declare const executor: ParameterizedSqlExecutor; await applyPostgresMigrations( executor, createProtectedWriteMigrations({ tablePrefix: "app_authorization" }), ); ``` ## Timeouts, retry and uncertain commits [#timeouts-retry-and-uncertain-commits] No transaction or callback is automatically retried. Preserve serialization (`40001`), deadlock (`40P01`) and timeout errors for application policy. A caught query failure still aborts the operation. The transaction deadline rejects late guarded SQL and bounds SQL statement/lock waits; cancellation of JavaScript work is cooperative through `guard.signal`. Pool acquisition and initial driver setup precede that deadline, and COMMIT follows it. Also configure the pool's `connectionTimeoutMillis` and a request deadline. For `COMMIT_OUTCOME_UNKNOWN`, call `scoped.lookupReceipt(theExactOriginalIntent)` on a fresh connection. A matching receipt proves the prior committed result. Absence alone does not prove an in-flight commit cannot succeed. An exact replay returns its durable receipt without invoking the callback; reuse of the key with a changed intent conflicts. Receipt lookup is a trusted server operation bound to the environment, namespace and actor, and does not replace request authentication. Retain receipts for the complete retry/reconciliation horizon. Purging one ends its durable replay guarantee. Operators own recovery policy, retention and dead-letter administration; these are not provided as console routes by this API. ## Deliver committed outbox events [#deliver-committed-outbox-events] `createPostgresProtectedWriteOutbox({ executor, tablePrefix, environmentId })` exposes `claim({ limit, leaseMs })` and `acknowledge(deliveryToken)` for a separate worker. Deliver after commit, deduplicate the stable `eventId` at the sink, and acknowledge only after successful delivery using the exact returned token. Delivery is at least once; an expired or superseded lease cannot acknowledge a later claim, and tokens are bound to the environment. The committed journal/outbox event is not automatically added to Sharing's existing `listAudit()` feed, the console's audit routes, or an external audit sink. Wire those consumers deliberately. Worker scheduling, delivery, retention and operational recovery remain application responsibilities. See the [API reference](/docs/sharing-postgres/api#protected-application-updates) for exact signatures and error types. The `@rolebook/sharing/internal/transaction-runtime` path is a first-party implementation boundary, not a supported application API. ## Scoped outcome lookup and worker recovery [#scoped-outcome-lookup-and-worker-recovery] For a server route that already knows the authenticated actor, tenant and original idempotency key, use the receipt factory with the opaque route from the protected-write adapter: ```ts import { createPostgresProtectedWriteAdapter, createPostgresProtectedWriteReceipts, createPostgresProtectedWriteOutbox, type ParameterizedSqlExecutor, } from "@rolebook/sharing-postgres"; declare const journalExecutor: ParameterizedSqlExecutor; declare const protectedWrites: ReturnType; // These values must come from authenticated server context, after application access checks. declare const authenticatedScope: { tenantId: string; actor: { type: string; id: string }; }; const receipts = createPostgresProtectedWriteReceipts({ receiptRoute: protectedWrites.receiptRoute(), }); const committedOutcome = await receipts.forScope(authenticatedScope).lookup({ idempotencyKey: "rename-document_1-once", }); const worker = createPostgresProtectedWriteOutbox({ executor: journalExecutor, tablePrefix: "app_authorization", environmentId: "production", }); const pending = await worker.inspectPending({ limit: 100 }); declare const deliver: (event: { eventId: string; kind: string; payload: unknown }) => Promise; for (const event of await worker.claim({ limit: 1, leaseMs: 30_000 })) { try { await deliver(event); // Destination durably accepts and deduplicates by environment/event ID. } catch { await worker.retry(event.deliveryToken, { delayMs: 5_000 }); continue; } const acknowledged = await worker.acknowledge(event.deliveryToken); // false means the lease was lost; delivery may be repeated. } ``` Key-only lookup reports the original committed result; it does not compare a new proposed payload. An empty, oversized, or NUL-bearing idempotency key is rejected before a read opens. `schemaVersion` is the stored metadata version, not a journal-table schema. A flat batch stays version 1. An enrolled batch of one update stays version 2. With admission `protected_batch_receipt_floor` 2, the default for every tenant and for an upgraded row, a multi-target enrolled batch stores version 2 from the UTF-16-first target. That one `hierarchy` block is evidence for its `links[0]` target only, not for the other result updates. Floor 3, set on the admission row after decoders and old writers are drained, records version 3: one `targets` entry per result update, each `hierarchy` block evidence for that target and not a capability. There is no top-level `hierarchy` and no separate control command. Select the entry whose resource matches the result update. Apply the admission migration first. If the receipt-floor column is missing, admission reads return `HIERARCHY_UNAVAILABLE` with reason `profile_mismatch`. Running it again leaves existing rows at floor 2. An old binary cannot enforce a column it does not know. A serialization failure while opening an enrolled batch is `HIERARCHY_UNAVAILABLE` / `serialization_conflict`. A floor outside 2 or 3, or a floor that changes at the final fence, is `HIERARCHY_UNAVAILABLE` / `protocol_floor`. An enrolled tenant passes the current gate in that checked read before any journal access: the adapter port, captured authority epoch, current admission and bootstrap, and whether this resource type is enrolled. A successful gate returns the stored outcome verbatim, or `undefined` when no row matches. A refused gate — missing port, epoch mismatch, quarantine, corrupt admission, or a type that is not enrolled — throws and does not read the journal, so the refusal discloses neither a receipt nor a miss. Use `lookupReceipt`, `lookupManagedReceipt` or `lookupManagedUpdatesReceipt` with the exact original intent for retry validation. `undefined` after a successful gate means not observed, not proof that an uncertain transaction cannot still commit. Never mint a new key solely because lookup is empty. Inspection is an oldest-pending snapshot (limit 1–1000), including leased rows and excluding delivered rows. It does not decode payloads, so a poison payload remains visible. Retry requires the current unexpired claim and a delay of 0–300000ms; it immediately invalidates the old token. Stale, expired, delivered and foreign-environment tokens return false. Generation counters also advance on retry, so they are not exact attempt counts. Restrict these operations to trusted workers/operators; they do not authenticate callers. A deferred retry appears as `leased` until its database deadline, even though the previous worker has released ownership. Delivery is at least once. ACK only after durable acceptance; destination effects must be idempotent by `(environmentId, eventId)`. Executor errors propagate. If a worker crashes or cannot release its lease, normal claim recovers after expiry. Size batches and leases to finish delivery before expiry; lease renewal is not provided. Do not hold business transactions during delivery. Receipts and all outbox rows are retained indefinitely, including delivered rows. Explicit quarantine/requeue is described below; deletion, scheduler and HTTP/console routes remain outside this API. Permanent failures remain pending unless explicitly quarantined. Exhausted generation counters remain visible but cannot be reclaimed; operators must investigate rather than reset fencing history. ## Quarantine and explicit operator recovery [#quarantine-and-explicit-operator-recovery] Stop and drain all old outbox workers before running the explicit protected-write migrations, then start only upgraded workers. The additive `_dead_v1` table leaves the original event and receipt schemas intact. Old workers do not consult quarantine state, so mixed-version delivery or rollback to old workers with active quarantines is unsupported. New worker operations fail closed when the side table is missing. Apply the existing migration API through the application's migration owner; construction does not migrate. PostgreSQL's generated migration step now ends in `:v1:quarantine-v1:relation-admission-v1:operator-history-v1`; SQLite validates and adds the new side-table definition. The PostgreSQL migration locks and requires all three journal relations to be ordinary permanent tables without inheritance in either direction, partitions, RLS, rewrite rules or user triggers. Foreign tables and views are rejected before shape DDL. The new step name makes runners that track applied names revalidate earlier installations. Trusted schema ownership remains required after migration; changing DDL afterwards is outside this runtime contract. The environment-wide operator below must be authenticated and authorized by your application. This uses an exact-event inspection lease so even a payload that normal claim cannot decode can be quarantined. It never steals an existing lease; allow that lease to expire first. ```ts import { createPostgresProtectedWriteOutbox, type ParameterizedSqlExecutor } from "@rolebook/sharing-postgres"; declare const executor: ParameterizedSqlExecutor; const operator = createPostgresProtectedWriteOutbox({ executor, tablePrefix: "app_authorization", environmentId: "production", }); declare const eventId: string; const lease = await operator.claimForInspection({ eventId, leaseMs: 30_000 }); if (lease) { const quarantine = await operator.quarantine(lease, { reason: "destination-rejected-event" }); // undefined means the lease is no longer eligible; inspect current state before proceeding. } const deadLetters = await operator.inspectDeadLetters({ limit: 100 }); // In a separate authorized recovery action, after resolving the cause: declare const approvedForRequeue: boolean; const selected = deadLetters.find((event) => event.eventId === eventId); if (approvedForRequeue && selected) { const requeued = await operator.requeue(selected.quarantineToken); // true makes the original event available for ordinary claim; it does not deliver it. } ``` Quarantine requires a current unexpired token and a nonblank 1–1024-character reason with no NUL; it advances the generation, clears the lease and persists the quarantine atomically. Never put credentials or whole payloads in the reason. Requeue requires the exact active quarantine token and advances the generation again. Old ACK, retry and operator tokens cannot act on later state. Foreign-environment tokens are rejected. Worker limits remain 1–1000 records and 1–300000ms leases. Quarantine reserves headroom for requeue and a subsequent claim; generations at or above 9223372036854775805 cannot be quarantined. Counters are never reset or wrapped. Dead-letter inspection omits payload decoding and returns immutable identity, kind, reason, time and token. It is a bounded oldest-active snapshot, not pagination or an authentication boundary. The side row retains the latest quarantine/requeue state per event; it is not a full history of operator actions; the separate [history log](#retained-operator-action-history) records successful post-upgrade transitions. Pending inspection excludes quarantined events; use dead-letter inspection for them. Neither operation changes or deletes the original payload or receipt. A crash before quarantine leaves ordinary lease expiry/reclaim in effect. A committed quarantine persists until explicit requeue; inspection recovers its token after a lost acknowledgment. An absent active quarantine is not proof of delivery. Serialization/busy/connection failures propagate without automatic replay. PostgreSQL can commit a normal claim's lease before payload decoding fails; SQLite rolls its claim transaction back. Inspection leasing must respect any remaining live lease in either case. Quarantine cannot recall an external delivery already in flight. Destinations must continue to deduplicate by `(environmentId, eventId)` across requeue cycles. Requeue does not repair malformed payloads: resolve the producer/schema/decoder or destination cause first. No payload-edit, scheduler, automatic retry policy, route/console integration, retention expiry or deletion is added. For callback-free single-resource deletion, use [managed deletion](/docs/sharing-postgres/managed-deletion). The raw update callback still cannot delete resources. ## Retained operator-action history [#retained-operator-action-history] After the explicit operator-history migration, every successful quarantine/requeue atomically appends a record to `_actions_v1`. An append failure rolls back the transition. Stale, foreign, expired and exhausted tokens do not create successful records. Original events and receipts remain unchanged. The log is append-only through the library API, not tamper-evident against database administrators; there is no pruning, failed-attempt log or administrative UI. Bind an optional `operator: { type, id }` when constructing the outbox worker. The factory copies this application-attested identity; authenticate and authorize it in the application first. Existing factories without an operator record `null`, never an inferred or authenticated actor. Both identity fields must be nonblank strings of at most 1024 characters with no NUL. `inspectOperatorActions({ eventId, limit, afterGeneration? })` returns immutable records for that event in the factory's environment. Limit is 1–1000. Records include stable `actionId`, `environmentId`, `eventId`, resulting decimal `generation`, `action`, nullable `operator`, nullable `reason` and ISO `recordedAt`. Requeue reasons are null. Times describe the transition inside the transaction, not exact COMMIT time. The exclusive cursor defaults to `"0"`; use the last returned generation for the next page. Pagination follows numeric generation, so clock changes cannot skip records. Gaps are normal. This is a live per-event traversal, not a frozen or cross-event feed. Malformed records fail closed; inspection does not decode the event payload. Stop/drain old operator binaries, run the explicit migration, then start upgraded workers only. The additive table retains previous schemas and data. History starts at this rollout: existing quarantines have no fabricated historical action. Their later requeue is recorded. An empty history cannot prove there were no pre-upgrade actions. Mixed-version operators can leave gaps and are unsupported. Record the rollout boundary in application operations records. ```ts import { createPostgresProtectedWriteOutbox, type ParameterizedSqlExecutor } from "@rolebook/sharing-postgres"; declare const executor: ParameterizedSqlExecutor; // Obtain this identity only after application authentication and operator authorization. declare const trustedOperator: { type: string; id: string }; declare const eventId: string; const worker = createPostgresProtectedWriteOutbox({ executor, tablePrefix: "app_authorization", environmentId: "production", operator: trustedOperator, }); const firstPage = await worker.inspectOperatorActions({ eventId, limit: 100 }); const last = firstPage.at(-1); if (last) { const nextPage = await worker.inspectOperatorActions({ eventId, limit: 100, afterGeneration: last.generation, }); } ``` ## Stored-text fidelity in managed operations [#stored-text-fidelity-in-managed-operations] Managed updates, batch entries, deletion pre-state and moves validate stored text before calling the application resource projection or evaluating policy. The check covers the complete configured projection, including keys, versions and policy attributes that are not writable patch fields. A value that the driver has shortened or otherwise changed fails closed; it is never silently normalized into a different policy value. Generated-write post-state and batch final reloads use the same loader. Rejection rolls back the business write and its receipt/event together. Exact retained receipt replay still occurs before current schema or authorization checks. PostgreSQL compares SQL string scalars returned as driver strings to independently queried UTF-8 hex of the same columns while holding the existing row/schema locks. The evidence preserves padded character values and default JSON scalar strings. Normal PostgreSQL text values are preserved; a configured lossy string decoder is rejected. PostgreSQL itself rejects embedded NUL text storage. Non-string driver values retain the existing scalar-codec and application projection contracts; this is not a new arbitrary-type codec. SQL evidence and the executor remain trusted: a custom executor that falsifies both values and their evidence cannot be verified by this guard. This is a **string-valued projection** guarantee. Custom parsers that turn SQL TEXT into null, objects or other non-string representations are outside it and remain trusted application configuration. The guard does not claim to validate arbitrary parser behavior. # @rolebook/sharing-sqlite API (/docs/sharing-sqlite/api) > Every export of @rolebook/sharing-sqlite and its /bun, /bun-query and /libsql entry points. Four entry points: `@rolebook/sharing-sqlite`, `@rolebook/sharing-sqlite/bun`, `@rolebook/sharing-sqlite/bun-query`, and `@rolebook/sharing-sqlite/libsql`. Signatures are checked against the built declarations. Start with the [SQLite adapter guide](/docs/sharing-sqlite). ## Adapter [#adapter] ### `createSqliteSharingAdapter` [#createsqlitesharingadapter] ```ts api="@rolebook/sharing-sqlite" function createSqliteSharingAdapter( options: CreateSqliteSharingAdapterOptions, ): SqliteSharingAdapter; ``` Creates the adapter for one application table. Validates the descriptor and `resourceColumns` before any SQL runs. ### `CreateSqliteSharingAdapterOptions` [#createsqlitesharingadapteroptions] ```ts api="@rolebook/sharing-sqlite" interface CreateSqliteSharingAdapterOptions { readonly executor: ParameterizedSqliteExecutor; readonly resource: SqliteResourceDescriptor; readonly clock?: SharingClock; readonly lockEligibleSubjects: SqliteEligibilityFence; readonly readEligibleSubjects?: SqliteEligibilityReader; readonly lockInvitationRecipient?: SqliteInvitationRecipientFence; readonly revalidateAuthorizationFacts?: SqliteAuthorizationFactFence; readonly groupSubjectTypes?: readonly string[]; readonly busyRetry?: ImmediateRetryOptions; readonly fencePolicy?: SqlitePolicyFence; readonly governanceGate?: GovernanceDirectGate; readonly governanceBinding?: GovernanceBinding; readonly pageIdentity?: SqlitePageIdentity; readonly groupGraph?: import("./group-graph-fence.js").SqliteGroupGraphOption; } ``` `executor`, `resource`, the required `lockEligibleSubjects`; optional `lockInvitationRecipient`, `revalidateAuthorizationFacts`, `groupSubjectTypes` (default `["team"]`), `busyRetry`, `fencePolicy`, and `clock`. Two options matter only to [`listAccessible()` and `listAccess()`](/docs/sharing/listing#what-a-consistent-page-requires), which read each page in one read-only transaction on a worker connection: - `readEligibleSubjects` is the evidence form of `lockEligibleSubjects`; see [`SqliteEligibilityReader`](#sqliteeligibilityreader). The first-party fences carry their own, so set it only beside a fence you wrote yourself. A custom fence without it makes every listing answer `identity_evidence_missing`. - `pageIdentity` names the identity adapter of the sharing instance and the local projection it answers from; see [`SqlitePageIdentity`](#sqlitepageidentity). Without it, the identity adapter must implement `resolvePagePrincipal`, or listings answer `identity_evidence_missing`. A malformed value throws a `TypeError` when the adapter is created. Listing also requires `executor` to be the worker-backed executor [`createBunSqliteQueryExecutor()`](#createbunsqlitequeryexecutor) returned, recognized by provenance and not by shape. An adapter built on any other executor, including the ones from `@rolebook/sharing-sqlite/bun` and `/libsql`, answers `capability_missing` for listings. This is the listing requirement only; other operations have their own executor requirements, described with each of them. An adapter `clock` does not apply to listing pages: they judge expiry by the database clock. With [versioned sharing](/docs/sharing/versioned), the policy store must be the one [`createSqlitePolicyStore()`](#createsqlitepolicystore) returned, created with this same executor object; a wrapped store or one on another executor answers `policy_evidence_missing`. `groupGraph` binds one nested-team profile: `teamType`, an explicit `identityStability`, and a transactional `directory`. SQLite has no row-share syntax; the directory is read inside the caller's `BEGIN IMMEDIATE` transaction. When a graph row exists and `groupGraph` is omitted, direct-only reads and writes refuse. Optional `integrity` is that deployment's bootstrap provider. When it is set, a read or mutation that finds structural corruption confirms the finding after the detecting transaction settles, with no user actor. A failed confirmation makes no quarantine claim. Build the commands with [`createSqliteGroupGraphControl()`](#createsqlitegroupgraphcontrol). Strict listing pages still require the worker executor [`createBunSqliteQueryExecutor()`](#createbunsqlitequeryexecutor); a graph command does not make another executor eligible for those pages. ### `SqliteSharingAdapter` [#sqlitesharingadapter] ```ts api="@rolebook/sharing-sqlite" interface SqliteSharingAdapter extends SharingAdapter, SettledRecordPruner { listAuditEvents( input: ListAuditEventsInput & { readonly incarnationId?: undefined; }, ): Promise; listAuditEvents(input: ListAuditEventsInput): Promise; listPendingInvitations( input: ListPendingInvitationsInput & { readonly incarnationId?: undefined; }, ): Promise; listPendingInvitations( input: ListPendingInvitationsInput, ): Promise; withLifecycleTransaction( operation: (transaction: ImmediateSqliteTransaction) => Promise, ): Promise; resourceDeletedInTransaction( transaction: ImmediateSqliteTransaction, input: DeleteSqliteResourceInTransactionInput, ): Promise; resourceMovedInTransaction( transaction: ImmediateSqliteTransaction, input: MoveSqliteResourceInTransactionInput, ): Promise; initializeResource( input: InitializeSqliteSharingResourceInput, ): Promise; initializeResourceInTransaction( executor: ImmediateSqliteTransaction, input: InitializeSqliteSharingResourceInput, ): Promise; } ``` A `SharingAdapter` and `SettledRecordPruner` with `withLifecycleTransaction`, the two `...InTransaction` lifecycle methods, and `initializeResource` / `initializeResourceInTransaction`. Its list reads are typed to return a value when no `incarnationId` is passed. ### `SqliteResourceDescriptor` [#sqliteresourcedescriptor] ```ts api="@rolebook/sharing-sqlite" interface SqliteResourceDescriptor { readonly resourceType: string; readonly table: string; readonly tenantColumn: string; readonly idColumn: string; readonly resourceVersionColumn: string; readonly sharingRevisionColumn?: string; readonly resourceFromRow: (row: Readonly>) => TrustedResource; readonly resourceVersion?: (row: Readonly>) => string; readonly resourceColumns?: readonly string[]; readonly sharingTablePrefix: string; readonly hierarchyControl?: { readonly prefix?: string; }; readonly governance?: { readonly tablePrefix: string; }; } ``` The application table (one unqualified name in `main`), its key and version columns, the snapshot callbacks, and the sharing table prefix. `hierarchyControl.prefix` names the hierarchy control profile (default `rolebook_control`) whose permanent tables in `main` this descriptor is immutably bound to; the resource migrations install them. ## Nested team commands [#nested-team-commands] SQLite graph commands run in one `BEGIN IMMEDIATE` transaction. There is no SQL row lock; the immediate transaction is the write exclusion. [`createSqliteGroupGraphControl()`](#createsqlitegroupgraphcontrol) builds the facade from the deployment policy, six action permissions, two distinct binding ids, and the bootstrap row descriptor. The branded bootstrap provider and the compiled command object stay inside that call. The facade has no `confirm` method. Structural confirmation is the adapter's later transaction when `groupGraph.integrity` is the `integrity` object this call returns. Listing pages stay on the worker executor and are unaffected by a graph command. [`hierarchyControlTables()`](#hierarchycontroltables) names the `main` control tables for a prefix. Resource migrations install that same profile when the descriptor sets `hierarchyControl`. [`createHierarchyControlMigrations()`](#createhierarchycontrolmigrations) installs the profile on its own. [`applyPolicyCatalogRegistration()`](#applypolicycatalogregistration) appends control prefixes to the policy catalog. SQLite has no SQL roles that separate control from the graph. Activation stores `control_configuration` as `sha256:` plus 64 hexadecimal characters. That digest is the canonical identity of the profile, team type, identity stability, bootstrap type, both binding ids, the six permissions, the graph-independent providers, and the first-party local projection. Provider order, and the order of each provider's fact paths and fact types, do not change it. A later command whose action map differs throws `HierarchyUnavailableError` with reason `profile_mismatch` and does not write the edge. ### `createSqliteGroupGraphControl` [#createsqlitegroupgraphcontrol] ```ts api="@rolebook/sharing-sqlite" function createSqliteGroupGraphControl(options: SqliteGroupGraphControlOptions): Readonly<{ tables: HierarchyControlTableNames; integrity: SqliteBootstrapIntegrity; facade: Readonly<{ activate(tenantId: string): Promise; link(tenantId: string, child: ResourceRef, parent: ResourceRef): Promise; unlink(tenantId: string, child: ResourceRef, parent: ResourceRef): Promise; repairUnlink(tenantId: string, child: ResourceRef, parent: ResourceRef): Promise; repairBatch(tenantId: string, start: boolean, limit: number): Promise; release(tenantId: string): Promise; }>; }>; ``` The command set matches the PostgreSQL control. `repairBatch`'s `limit` is an integer of at least 1. A Core denial is `status: "denied"` with the decision left intact. A structural problem is `status: "refused"`. An unavailable graph throws `HierarchyUnavailableError`. ```ts import { HierarchyUnavailableError, type PolicyStore } from "@rolebook/sharing"; import { createSqliteGroupGraphControl, createSqliteLocalIdentityProjection, type ParameterizedSqliteExecutor, } from "@rolebook/sharing-sqlite"; import type { RolebookPolicy } from "rolebook"; declare const executor: ParameterizedSqliteExecutor; declare const policy: RolebookPolicy; declare const policyStore: PolicyStore; declare const sharing: object; declare const identity: ReturnType; const graph = createSqliteGroupGraphControl({ executor, controlPrefix: "rolebook_control", teamType: "team", identityStability: "registry_incarnation", actor: { type: "user", id: "ada" }, policy, bootstrapType: "tenant_admin", actions: { activate: "tenant_admin:graph_activate", link: "tenant_admin:graph_link", unlink: "tenant_admin:graph_unlink", repairUnlink: "tenant_admin:graph_repair_unlink", heightRepair: "tenant_admin:graph_height_repair", release: "tenant_admin:graph_release", }, controlBindingId: "control-binding", normalBindingId: "graph-binding", providers: [ { id: "local", graphIndependent: true, factPaths: ["subject.attribute"], factTypes: ["attribute"], }, ], policyStore, sharing, identity, bootstrap: { policyStore: { tablePrefix: "rolebook" }, descriptor: { resourceType: "tenant_admin", table: "tenant_admin", tenantColumn: "workspace_id", idColumn: "id", versionColumn: "version", incarnationColumn: "incarnation", }, }, registry(tx, tenantId) { return { async readEndpoint(group) { const result = await tx.query<{ incarnation: string }>( "SELECT incarnation FROM team WHERE tenant_id = ? AND id = ?", [tenantId, group.id], ); const row = result.rows[0]; return row ? { present: true as const, incarnation: row.incarnation } : { present: false as const }; }, }; }, }); try { const outcome = await graph.facade.repairBatch("ws_456", true, 25); if (outcome.status === "denied") outcome.decision.code; if (outcome.status === "refused") outcome.refusal; if (outcome.status === "applied") outcome.progress?.phase; } catch (error) { if (error instanceof HierarchyUnavailableError) error.reason; } graph.tables.groupGraph; graph.integrity.descriptorDigest; ``` `executor` is the command connection. It is not a substitute for [`createBunSqliteQueryExecutor()`](#createbunsqlitequeryexecutor), which listing pages require. `controlPrefix` defaults to `rolebook_control` when omitted. The two binding ids are distinct opaque ids. Omit `providers` when the deployment declares no graph-independent fact paths. ### `SqliteGroupGraphControlOptions` [#sqlitegroupgraphcontroloptions] ```ts api="@rolebook/sharing-sqlite" interface SqliteGroupGraphControlOptions { readonly executor: ParameterizedSqliteExecutor; readonly teamType: string; readonly identityStability: "registry_incarnation" | "ids_never_reused"; readonly actor: ResourceRef; readonly policy: RolebookPolicy; readonly bootstrapType: string; readonly actions: { readonly activate: string; readonly link: string; readonly unlink: string; readonly repairUnlink: string; readonly heightRepair: string; readonly release: string; }; readonly controlBindingId: string; readonly normalBindingId: string; readonly providers?: readonly { readonly id: string; readonly graphIndependent: true; readonly factPaths: readonly string[]; readonly factTypes: readonly string[]; }[]; readonly controlPrefix?: string; readonly policyStore: PolicyStore; readonly sharing: object; readonly identity: ReturnType; readonly bootstrap: { readonly policyStore: { readonly tablePrefix: string; }; readonly descriptor: SqliteBootstrapRowDescriptor; }; registry(tx: ParameterizedSqliteExecutor, tenantId: string): GroupRegistryReader; } ``` `actor` is the control subject. A control actor whose groups include `teamType`, or a lineage fact, is `identity_unavailable`. `identity` is the object [`createSqliteLocalIdentityProjection()`](#createsqlitelocalidentityprojection) returns. ### `hierarchyControlTables` [#hierarchycontroltables] ```ts api="@rolebook/sharing-sqlite" function hierarchyControlTables(tablePrefix?: string): HierarchyControlTableNames; ``` The returned table fields are unqualified names in `main`. `profileId` is the canonical JSON of `["main", prefix]`. ### `createHierarchyControlMigrations` [#createhierarchycontrolmigrations] ```ts api="@rolebook/sharing-sqlite" function createHierarchyControlMigrations(options?: { readonly tablePrefix?: string; }): readonly ResourceSharingMigration[]; ``` These statements create the control tables in `main`, including the group-graph tables. Resource migrations install this same profile for a descriptor that sets `hierarchyControl`. ### `applyPolicyCatalogRegistration` [#applypolicycatalogregistration] ```ts api="@rolebook/sharing-sqlite" function applyPolicyCatalogRegistration(executor: ParameterizedSqliteExecutor, input: { readonly policyStore: SqliteQualifiedPolicyStoreConfig; readonly controlPrefixes: readonly string[]; readonly retry?: ImmediateRetryOptions; }): Promise<{ readonly appended: number; readonly catalogGeneration: string; }>; ``` ### `SqliteQualifiedPolicyStoreConfig` [#sqlitequalifiedpolicystoreconfig] ```ts api="@rolebook/sharing-sqlite" interface SqliteQualifiedPolicyStoreConfig { readonly tablePrefix: string; } ``` `tablePrefix` names the policy store whose catalog receives the control prefixes. `appended` is the number of prefixes this call added. `catalogGeneration` is the catalog generation after the write. ### `SqliteBootstrapIntegrity` [#sqlitebootstrapintegrity] ```ts api="@rolebook/sharing-sqlite" interface SqliteBootstrapIntegrity { readonly resourceType: string; readonly descriptorDigest: string; readonly profileId: string; readonly policyStoreId: string; } ``` `descriptorDigest` is the `sha256:` identity of the bootstrap row. Pass this object as `groupGraph.integrity` when the adapter confirms structural corruption after the detecting transaction. ### `createSqliteGroupGraphFacade` [#createsqlitegroupgraphfacade] ```ts api="@rolebook/sharing-sqlite" function createSqliteGroupGraphFacade(options: SqliteGroupGraphFacadeOptions): Readonly<{ activate(tenantId: string): Promise; link(tenantId: string, child: ResourceRef, parent: ResourceRef): Promise; unlink(tenantId: string, child: ResourceRef, parent: ResourceRef): Promise; repairUnlink(tenantId: string, child: ResourceRef, parent: ResourceRef): Promise; repairBatch(tenantId: string, start: boolean, limit: number): Promise; release(tenantId: string): Promise; }>; ``` The command set matches the PostgreSQL facade. `repairBatch`'s `limit` is an integer of at least 1. A Core denial is `status: "denied"` with the decision left intact. A structural problem is `status: "refused"`. An unavailable graph throws `HierarchyUnavailableError`. Build a new graph with [`createSqliteGroupGraphControl()`](#createsqlitegroupgraphcontrol). This function is the lower facade for a caller that already holds `tables` and an authority object. `busyRetry` bounds retries when the immediate transaction finds the database locked. ### `SqliteGroupGraphFacadeOptions` [#sqlitegroupgraphfacadeoptions] ```ts api="@rolebook/sharing-sqlite" interface SqliteGroupGraphFacadeOptions { readonly executor: ParameterizedSqliteExecutor; readonly tables: HierarchyControlTableNames; readonly teamType: string; readonly identityStability: "registry_incarnation" | "ids_never_reused"; readonly authority: SqliteGroupGraphAuthority; readonly busyRetry?: ImmediateRetryOptions; } ``` `executor` is the command connection. It is not a substitute for [`createBunSqliteQueryExecutor()`](#createbunsqlitequeryexecutor), which listing pages require. ### `SqliteGroupGraphAuthority` [#sqlitegroupgraphauthority] ```ts api="@rolebook/sharing-sqlite" interface SqliteGroupGraphAuthority { readonly actor: ResourceRef; readonly commands: GroupGraphCommands; readonly integrity: SqliteBootstrapIntegrity; readonly policyStore: PolicyStore; readonly sharing: object; readonly identity: ReturnType; registry(tx: ParameterizedSqliteExecutor, tenantId: string): GroupRegistryReader; } ``` `actor` is the control subject. `commands` is the compiled control object. `integrity` is the first-party bootstrap provider, and its profile id matches `tables`. `policyStore` is the store the versioned sharing instance reads, and `sharing` is that instance. `identity` is the object [`createSqliteLocalIdentityProjection()`](#createsqlitelocalidentityprojection) returns; the command reads it inside the immediate transaction and revalidates its facts. A control actor whose groups include `teamType`, or a lineage fact, is `identity_unavailable`. `registry` reads group endpoints in that same transaction. [`createSqliteGroupGraphControl()`](#createsqlitegroupgraphcontrol) compiles that provider and those commands from the policy, the six permissions, the binding ids, and the bootstrap descriptor. ### `SqliteGroupGraphOutcome` [#sqlitegroupgraphoutcome] ```ts api="@rolebook/sharing-sqlite" type SqliteGroupGraphOutcome = (GroupGraphApplyResult & { readonly progress?: GroupGraphRepairProgress; }) | { readonly status: "denied"; readonly decision: AuthorizationDecision; }; ``` `progress` is set by a repair batch. `denied` is the Core decision. ## Inherited access [#inherited-access] The supported way to switch on [inherited access](/docs/sharing/inheritance) (`sharing.inheritance/1`). ### `enableSqliteInheritedReads` [#enablesqliteinheritedreads] ```ts api="@rolebook/sharing-sqlite" function enableSqliteInheritedReads(options: EnableSqliteInheritedReadsOptions): void; ``` Enables inherited reads on every type of `definition` that sets `inheritance: "ancestors"`, replacing the internal readiness gate. Call it once, after `defineSharing` and before `createVersionedSharing`. Every option is read once and every adapter is validated before any is changed. It throws when an inheriting type is not on a first-party SQLite adapter or its adapter has no `pageIdentity`, when the inheriting types do not share one control profile (the bootstrap provider's), when the definition also holds a first-party type that does not inherit, when `identity` is not a first-party local identity projection, when the command map's types differ from the opted-in types, or when `configurationGeneration` does not bind this definition and command map. Once a Sharing instance is built from a definition that opts a type in, that type's storage refuses every tenant that is not enrolled (`not_enrolled`) on every read, listing, command, protected write and governed call (lifecycle writers that initialize, delete or move a resource are not refused); enroll a tenant before it uses the type. See [inherited access](/docs/sharing/inheritance). ### `EnableSqliteInheritedReadsOptions` [#enablesqliteinheritedreadsoptions] ```ts api="@rolebook/sharing-sqlite" interface EnableSqliteInheritedReadsOptions { readonly definition: SharingDefinition; readonly commands: HierarchyCommandsInput; readonly configurationGeneration: string; readonly authorityEpoch: string; readonly identity: ReturnType; readonly bootstrap: SqliteBootstrapIntegrity; } ``` `configurationGeneration` comes from `hierarchyConfigurationGeneration`. `identity` is the complete local identity projection; an enrolled tenant's reads resolve the actor from it in the read transaction and never consult the generic identity adapter. `bootstrap` is the profile's one bootstrap provider; pass the same object to the control facade. ### `createSqliteHierarchyControl` [#createsqlitehierarchycontrol] ```ts api="@rolebook/sharing-sqlite" function createSqliteHierarchyControl(options: CreateSqliteHierarchyControlOptions): SqliteInheritanceControl; ``` The actor-authorized hierarchy control facade. `forTenant({ tenantId, actor })` returns `enroll`, `activate`, `releaseQuarantine` and `repairHeights` (each needs the matching bootstrap action) and `structure` with `create`, `move` and `delete` (each needs the configured command permissions on the resources involved). Every action is one transaction decided by Rolebook; a non-applied outcome rolls back. It throws when the Sharing definition's opted-in types and the command map differ. ### `CreateSqliteHierarchyControlOptions` [#createsqlitehierarchycontroloptions] ```ts api="@rolebook/sharing-sqlite" interface CreateSqliteHierarchyControlOptions { readonly sharing: VersionedResourceSharing; readonly policy: RolebookPolicy; readonly commands: HierarchyCommandsInput; readonly bootstrap: SqliteBootstrapIntegrity; readonly authorityEpoch: string; readonly configurationGeneration: string; readonly immediateRetry?: ImmediateRetryOptions; } ``` Use the same `bootstrap`, `authorityEpoch` and `configurationGeneration` as the inherited read configuration. ### `SqliteInheritanceControl` [#sqliteinheritancecontrol] ```ts api="@rolebook/sharing-sqlite" interface SqliteInheritanceControl { forTenant(scope: { readonly tenantId: string; readonly actor: ResourceRef; }): { enroll(input: { readonly idempotencyKey: string; }): Promise; activate(input: { readonly idempotencyKey: string; }): Promise; releaseQuarantine(input: { readonly idempotencyKey: string; }): Promise; repairHeights(): Promise; readonly structure: ReturnType["structure"]; }; } ``` The facade `createSqliteHierarchyControl` returns. After the actor is authorized, `enroll` and `activate` answer `unlinked_resources`, on the same control transaction and before changing tenant state, while the tenant has a row of an inheriting type that the managed hierarchy does not place: existing resources are not adopted. ### `SqliteHierarchyControlResult` [#sqlitehierarchycontrolresult] ```ts api="@rolebook/sharing-sqlite" type SqliteHierarchyControlResult = HierarchyControlResult; ``` An actor control action's answer. Through this facade `enroll` and `activate` may also answer `unlinked_resources` with the first unplaced type, after the actor is authorized. ### `runSqliteHierarchyInventory` [#runsqlitehierarchyinventory] ```ts api="@rolebook/sharing-sqlite" function runSqliteHierarchyInventory(control: SqliteInheritanceControl, tenantId: string, batchSize?: number): Promise; ``` One bounded, resumable batch of the activation inventory for a tenant in `building`: call it until it answers `complete`, then `activate`. An operator job, not an actor command; it changes no authority. Activation refuses while any stored membership on a would-be inheriting scope carries an allow that would reach further. ### `createSqliteBootstrapIntegrity` [#createsqlitebootstrapintegrity] ```ts api="@rolebook/sharing-sqlite" function createSqliteBootstrapIntegrity(options: { readonly controlPrefix?: string; readonly policyStore: { readonly tablePrefix: string; }; readonly descriptor: SqliteBootstrapRowDescriptor; }): SqliteBootstrapIntegrity; ``` The profile's bootstrap integrity provider over the application table that holds each tenant's bootstrap row (the resource the bootstrap actions are checked on). Inherited reads prove the row in their own snapshot; commands lock it. ### `SqliteBootstrapRowDescriptor` [#sqlitebootstraprowdescriptor] ```ts api="@rolebook/sharing-sqlite" interface SqliteBootstrapRowDescriptor { readonly resourceType: string; readonly table: string; readonly tenantColumn: string; readonly idColumn: string; readonly versionColumn: string; readonly incarnationColumn: string; readonly fields?: readonly { readonly field: string; readonly column: string; readonly codec: "text" | "boolean" | "safe-integer"; readonly nullable?: boolean; }[]; } ``` Where the bootstrap row lives: its table and the tenant, id, version and incarnation columns, plus optional fields the bootstrap resource exposes to policy conditions. ### `HierarchyControlResult` [#hierarchycontrolresult] An actor control action's answer (`enrolled`, `already_enrolled`, `activated`, `inventory_incomplete`, `released`, `verifying`, `repairing`, `repaired`, `not_enrolled`, `denied`, `conflict`, `unlinked_resources`). `denied` and `conflict` are ordinary outcomes; tenant-level unavailability throws `HierarchyUnavailableError`. Declared by the control runtime this package bundles; it has no signature block here. ### `HierarchyControlJobResult` [#hierarchycontroljobresult] An operator job's answer. The inventory answers `progress` until it is `complete`. Declared by the control runtime this package bundles; it has no signature block here. ## Lifecycle [#lifecycle] ### `InitializeSqliteSharingResourceInput` [#initializesqlitesharingresourceinput] ```ts api="@rolebook/sharing-sqlite" interface InitializeSqliteSharingResourceInput { readonly tenantId: string; readonly resourceId: string; readonly owner: OwnerRef; readonly actor: ResourceRef; readonly occurredAt: Date; } ``` ### `InitializeSqliteSharingResourceResult` [#initializesqlitesharingresourceresult] ```ts api="@rolebook/sharing-sqlite" type InitializeSqliteSharingResourceResult = | "applied" | "already_initialized" | "identity_ineligible" | "owner_mismatch" | "group_owner" | "not_found"; ``` ### `DeleteSqliteResourceInTransactionInput` [#deletesqliteresourceintransactioninput] ```ts api="@rolebook/sharing-sqlite" interface DeleteSqliteResourceInTransactionInput extends SqliteLifecycleInput { readonly tenantId: string; readonly resourceId: string; readonly deleteResource: ( transaction: ImmediateSqliteTransaction, ) => Promise; } ``` A deletion and your `deleteResource` callback; see [lifecycle](/docs/sharing-sqlite/operations#lifecycle). ### `MoveSqliteResourceInTransactionInput` [#movesqliteresourceintransactioninput] ```ts api="@rolebook/sharing-sqlite" interface MoveSqliteResourceInTransactionInput extends SqliteLifecycleInput { readonly fromTenantId: string; readonly toTenantId: string; readonly resourceId: string; readonly resultingResourceVersion: string; readonly moveResource: ( transaction: ImmediateSqliteTransaction, ) => Promise; } ``` A move and your `moveResource` callback. ### `SqliteLifecycleApplicationResult` [#sqlitelifecycleapplicationresult] ```ts api="@rolebook/sharing-sqlite" type SqliteLifecycleApplicationResult = "applied" | "not_found" | "conflict"; ``` What your lifecycle callback returns. ### `SqliteLifecycleResult` [#sqlitelifecycleresult] ```ts api="@rolebook/sharing-sqlite" type SqliteLifecycleResult = | "applied" | "already_applied" | "not_found" | "conflict" | "identity_ineligible"; ``` What a lifecycle method returns. ## Fences [#fences] ### `SqliteEligibilityFence` [#sqliteeligibilityfence] ```ts api="@rolebook/sharing-sqlite" type SqliteEligibilityFence = (input: { readonly executor: ParameterizedSqliteExecutor; readonly tenantId: string; readonly subjects: readonly ResourceRef[]; readonly ownerCandidates?: readonly ResourceRef[]; }) => Promise; ``` Verifies tenant eligibility under the write lock; may refuse `ownerCandidates`. Only `true` counts. ### `SqliteEligibilityReader` [#sqliteeligibilityreader] ```ts api="@rolebook/sharing-sqlite" type SqliteEligibilityReader = (input: { readonly executor: ParameterizedSqliteExecutor; readonly tenantId: string; readonly subjects: readonly ResourceRef[]; readonly evaluatedAt: string; }) => Promise; ``` The evidence form of a `SqliteEligibilityFence`, used by listing pages. It gives the same answer from the same authoritative rows, read through `executor`, which is the page's read-only transaction; that connection refuses writes. Judge every time-dependent fact at `evaluatedAt`, the page's instant, and never by the database's later clock. `createSqliteMembershipEligibilityFence()` and `createSqliteLocalIdentityProjection().lockEligibleSubjects` carry their own reader, recognized by provenance. If you wrap one of them in a function of your own, the wrapper is a custom fence: pass a reader wrapped the same way as `readEligibleSubjects`. ### `SqliteEligibilityEvidence` [#sqliteeligibilityevidence] ```ts api="@rolebook/sharing-sqlite" interface SqliteEligibilityEvidence { readonly eligible: boolean; readonly expiryDependencies: readonly string[]; } ``` What a reader returns. `eligible` must be a boolean, and only `true` makes the subjects eligible; an actor it refuses receives an empty exhausted page. `expiryDependencies` lists every instant at which a time-sensitive fact behind the answer changes it: a membership or projection expiry, and equally the end of a refusing condition. Each is an ISO 8601 UTC instant with exactly three fractional digits; SQLite pages compare whole milliseconds. Leave it empty only when the answer depends on no time. The page seals all of them, and one that passes before the seal refuses the page with `expiry_crossed`. A boolean, a missing field, or a malformed instant is `identity_evidence_missing`, never a page. ### `createSqliteMembershipEligibilityFence` [#createsqlitemembershipeligibilityfence] ```ts api="@rolebook/sharing-sqlite" function createSqliteMembershipEligibilityFence( descriptor: SqliteMembershipEligibilityDescriptor, ): SqliteEligibilityFence; ``` A fence over an organization-member table, requiring exactly one row with the exact tenant and subject. It carries its own listing reader, which reads the same rows and declares no expiry, because row existence depends on no time. ### `SqliteMembershipEligibilityDescriptor` [#sqlitemembershipeligibilitydescriptor] ```ts api="@rolebook/sharing-sqlite" interface SqliteMembershipEligibilityDescriptor { readonly table: QualifiedIdentifier; readonly tenantColumn: string; readonly subjectIdColumn: string; readonly subjectType?: string; } ``` ### `SqliteInvitationRecipientFence` [#sqliteinvitationrecipientfence] ```ts api="@rolebook/sharing-sqlite" type SqliteInvitationRecipientFence = (input: { readonly executor: ParameterizedSqliteExecutor; readonly verification: InvitationRecipientFenceInput; }) => Promise; ``` ### `createSqliteEmailInvitationRecipientFence` [#createsqliteemailinvitationrecipientfence] ```ts api="@rolebook/sharing-sqlite" function createSqliteEmailInvitationRecipientFence( descriptor: SqliteEmailInvitationRecipientFenceDescriptor, ): SqliteInvitationRecipientFence; ``` Requires a verified email equal to the invitation's (the verification flag stored as the integer 1). ### `SqliteEmailInvitationRecipientFenceDescriptor` [#sqliteemailinvitationrecipientfencedescriptor] ```ts api="@rolebook/sharing-sqlite" interface SqliteEmailInvitationRecipientFenceDescriptor { readonly membershipTable: QualifiedIdentifier; readonly membershipTenantColumn: string; readonly membershipSubjectIdColumn: string; readonly userTable: QualifiedIdentifier; readonly userIdColumn: string; readonly userEmailColumn: string; readonly userEmailVerifiedColumn: string; readonly subjectType?: string; readonly emailNormalization?: "lower_trim" | "exact"; } ``` ### `SqliteAuthorizationFactFence` [#sqliteauthorizationfactfence] ```ts api="@rolebook/sharing-sqlite" type SqliteAuthorizationFactFence = (input: { readonly executor: ParameterizedSqliteExecutor; readonly tenantId: string; readonly facts: readonly TransactionalAuthorizationFact[]; }) => Promise; ``` `true` proceeds, `"conflict"` re-authorizes, anything else is `identity_ineligible`. ### `SqliteAuthorizationFactFenceResult` [#sqliteauthorizationfactfenceresult] ```ts api="@rolebook/sharing-sqlite" type SqliteAuthorizationFactFenceResult = boolean | "conflict"; ``` ### `createSqliteWorkspaceRoleAuthorizationFactFence` [#createsqliteworkspaceroleauthorizationfactfence] ```ts api="@rolebook/sharing-sqlite" function createSqliteWorkspaceRoleAuthorizationFactFence( descriptor: SqliteWorkspaceRoleAuthorizationFactDescriptor, ): SqliteAuthorizationFactFence; ``` Compares the exact tenant, subject, membership ID, and role behind mapped workspace assignments. ### `SqliteWorkspaceRoleAuthorizationFactDescriptor` [#sqliteworkspaceroleauthorizationfactdescriptor] ```ts api="@rolebook/sharing-sqlite" interface SqliteWorkspaceRoleAuthorizationFactDescriptor extends SqliteMembershipEligibilityDescriptor { readonly factType: string; readonly memberIdColumn: string; readonly roleColumn: string; } ``` ## Migrations [#migrations] ### `applyResourceSharingMigrations` [#applyresourcesharingmigrations] ```ts api="@rolebook/sharing-sqlite" function applyResourceSharingMigrations( executor: ParameterizedSqliteExecutor, descriptor: SqliteResourceDescriptor, retry?: ImmediateRetryOptions, ): Promise; ``` Validates and migrates one descriptor's schema in one retried `BEGIN IMMEDIATE` transaction. See [migrations](/docs/sharing-sqlite/migrations). ### `applyResourceSharingRollbackMigrations` [#applyresourcesharingrollbackmigrations] ```ts api="@rolebook/sharing-sqlite" function applyResourceSharingRollbackMigrations( executor: ParameterizedSqliteExecutor, descriptor: SqliteResourceDescriptor, options?: ResourceSharingRollbackOptions, retry?: ImmediateRetryOptions, ): Promise; ``` Checks the descriptor registry and drops sharing-owned state in one transaction; keeps audit unless `dropAudit`. ### `createResourceSharingMigrations` [#createresourcesharingmigrations] ```ts api="@rolebook/sharing-sqlite" function createResourceSharingMigrations( descriptor: SqliteResourceDescriptor, ): readonly ResourceSharingMigration[]; ``` The DDL a fresh database receives, for review. Do not run it yourself. ### `createResourceSharingRollbackMigrations` [#createresourcesharingrollbackmigrations] ```ts api="@rolebook/sharing-sqlite" function createResourceSharingRollbackMigrations( descriptor: SqliteResourceDescriptor, options?: ResourceSharingRollbackOptions, ): readonly ResourceSharingRollbackMigration[]; ``` The rollback steps with their data loss, for review. ### `ResourceSharingMigration` [#resourcesharingmigration] ```ts api="@rolebook/sharing-sqlite" interface ResourceSharingMigration { readonly name: string; readonly sql: string; } ``` ### `ResourceSharingRollbackMigration` [#resourcesharingrollbackmigration] ```ts api="@rolebook/sharing-sqlite" interface ResourceSharingRollbackMigration { readonly name: string; readonly sql: string; readonly dataLoss?: string; } ``` ### `ResourceSharingRollbackOptions` [#resourcesharingrollbackoptions] ```ts api="@rolebook/sharing-sqlite" interface ResourceSharingRollbackOptions { readonly dropAudit?: boolean; } ``` ### `sharingTables` [#sharingtables] ```ts api="@rolebook/sharing-sqlite" function sharingTables(descriptor: SqliteResourceDescriptor): SharingTableNames; ``` The sharing table names for a descriptor. ### `SharingTableNames` [#sharingtablenames] ```ts api="@rolebook/sharing-sqlite" interface SharingTableNames { readonly binding: string; readonly owner: string; readonly member: string; readonly invitation: string; readonly audit: string; readonly idempotency: string; readonly lifecycle: string; readonly revisionFloor: string; } ``` ### `quoteIdentifier` [#quoteidentifier] ```ts api="@rolebook/sharing-sqlite" function quoteIdentifier(identifier: QualifiedIdentifier): string; ``` Validates and double-quotes an identifier. ### `QualifiedIdentifier` [#qualifiedidentifier] ```ts api="@rolebook/sharing-sqlite" type QualifiedIdentifier = string | readonly string[]; ``` ## Policy store [#policy-store] ### `createSqlitePolicyStore` [#createsqlitepolicystore] ```ts api="@rolebook/sharing-sqlite" function createSqlitePolicyStore(options: CreateSqlitePolicyStoreOptions): PolicyStore; ``` A `PolicyStore` on SQLite, with busy retries. ### `CreateSqlitePolicyStoreOptions` [#createsqlitepolicystoreoptions] ```ts api="@rolebook/sharing-sqlite" interface CreateSqlitePolicyStoreOptions { readonly executor: ParameterizedSqliteExecutor; readonly tablePrefix?: string; readonly busyRetry?: ImmediateRetryOptions; } ``` `executor`, `tablePrefix` (default `rolebook`), `busyRetry`. ### `createSqlitePolicyFence` [#createsqlitepolicyfence] ```ts api="@rolebook/sharing-sqlite" function createSqlitePolicyFence(options?: { readonly tablePrefix?: string; }): SqlitePolicyFence; ``` The policy fence for `fencePolicy`. Use the store's `tablePrefix`. ### `SqlitePolicyFence` [#sqlitepolicyfence] ```ts api="@rolebook/sharing-sqlite" type SqlitePolicyFence = (input: { readonly executor: ParameterizedSqliteExecutor; readonly tenantId: string; readonly expectedPolicy: ExpectedPolicy; }) => Promise; ``` ### `applyPolicyStoreMigrations` [#applypolicystoremigrations] ```ts api="@rolebook/sharing-sqlite" function applyPolicyStoreMigrations( executor: ParameterizedSqliteExecutor, options?: { readonly tablePrefix?: string; readonly retry?: ImmediateRetryOptions; }, ): Promise; ``` Creates or validates the policy-store tables in one `BEGIN IMMEDIATE` transaction. ### `createPolicyStoreMigrations` [#createpolicystoremigrations] ```ts api="@rolebook/sharing-sqlite" function createPolicyStoreMigrations(options?: { readonly tablePrefix?: string; }): readonly ResourceSharingMigration[]; ``` The policy-store DDL, for review. ### `createPolicyStoreRollbackMigrations` [#createpolicystorerollbackmigrations] ```ts api="@rolebook/sharing-sqlite" function createPolicyStoreRollbackMigrations(options?: { readonly tablePrefix?: string; }): readonly ResourceSharingRollbackMigration[]; ``` The policy-store rollback steps. The first step refuses while the hierarchy policy catalog holds any registered descriptor; run every step in one transaction, as `applyPolicyStoreRollbackMigrations` does. ### `applyPolicyStoreRollbackMigrations` [#applypolicystorerollbackmigrations] ```ts api="@rolebook/sharing-sqlite" function applyPolicyStoreRollbackMigrations( executor: ParameterizedSqliteExecutor, options?: { readonly tablePrefix?: string; readonly retry?: ImmediateRetryOptions }, ): Promise; ``` Runs the guard and every drop in one `BEGIN IMMEDIATE` transaction. ### `policyStoreTables` [#policystoretables] ```ts api="@rolebook/sharing-sqlite" function policyStoreTables(tablePrefix?: string): PolicyStoreTableNames; ``` The policy-store table names for a prefix. ### `PolicyStoreTableNames` [#policystoretablenames] ```ts api="@rolebook/sharing-sqlite" interface PolicyStoreTableNames { readonly version: string; readonly active: string; readonly activation: string; readonly tenantRole: string; readonly tenantRoleRevision: string; readonly audit: string; } ``` ## Executor and transactions [#executor-and-transactions] ### `ParameterizedSqliteExecutor` [#parameterizedsqliteexecutor] ```ts api="@rolebook/sharing-sqlite" interface ParameterizedSqliteExecutor { query( sql: string, values?: readonly SqlValue[], ): Promise>; transaction( options: SqliteTransactionOptions, operation: (transaction: ParameterizedSqliteExecutor) => Promise, ): Promise; } ``` The executor seam: one-statement queries with `?` parameters, and immediate or deferred transactions. ### `SqliteTransactionOptions` [#sqlitetransactionoptions] ```ts api="@rolebook/sharing-sqlite" interface SqliteTransactionOptions { readonly behavior: "immediate" | "deferred"; } ``` ### `ImmediateSqliteTransaction` [#immediatesqlitetransaction] ```ts api="@rolebook/sharing-sqlite" type ImmediateSqliteTransaction = ParameterizedSqliteExecutor & { readonly [immediateTransaction]: true; }; ``` An executor branded as a `BEGIN IMMEDIATE` transaction. ### `SqlResult` [#sqlresult] ```ts api="@rolebook/sharing-sqlite" interface SqlResult { readonly rows: readonly TRow[]; readonly rowCount: number; } ``` ### `SqlRow` [#sqlrow] ```ts api="@rolebook/sharing-sqlite" type SqlRow = Readonly>; ``` ### `SqlValue` [#sqlvalue] ```ts api="@rolebook/sharing-sqlite" type SqlValue = string | number | bigint | null | Uint8Array; ``` ### `asImmediateSqliteTransaction` [#asimmediatesqlitetransaction] ```ts api="@rolebook/sharing-sqlite" function asImmediateSqliteTransaction( transaction: ParameterizedSqliteExecutor, ): ImmediateSqliteTransaction; ``` Compile-time assertion that a transaction your driver opened is `BEGIN IMMEDIATE`. ### `withImmediateRetry` [#withimmediateretry] ```ts api="@rolebook/sharing-sqlite" function withImmediateRetry( executor: ParameterizedSqliteExecutor, operation: (transaction: ImmediateSqliteTransaction) => Promise, options?: ImmediateRetryOptions, ): Promise; ``` Runs an idempotent unit of work in a busy-retried `BEGIN IMMEDIATE` transaction. ### `withImmediateTransaction` [#withimmediatetransaction] ```ts api="@rolebook/sharing-sqlite" function withImmediateTransaction( executor: ParameterizedSqliteExecutor, operation: (transaction: ImmediateSqliteTransaction) => Promise, options?: ImmediateRetryOptions, ): Promise; ``` Runs caller-owned application and sharing work in one busy-retried `BEGIN IMMEDIATE` transaction. ### `ImmediateRetryOptions` [#immediateretryoptions] ```ts api="@rolebook/sharing-sqlite" interface ImmediateRetryOptions { readonly attempts?: number; readonly wait?: (milliseconds: number) => Promise; readonly backoffMs?: (retry: number) => number; } ``` `attempts` (default 10, at most 100, including the first), `backoffMs` (0 to 1,000 ms), `wait`. ### `isRetryableBusyError` [#isretryablebusyerror] ```ts api="@rolebook/sharing-sqlite" function isRetryableBusyError(error: unknown): boolean; ``` True for `SQLITE_BUSY` and its extended codes and `SQLITE_LOCKED_SHAREDCACHE`, across drivers and `cause` chains. ## Errors [#errors] ### `InvalidSqliteCursorError` [#invalidsqlitecursorerror] ```ts api="@rolebook/sharing-sqlite" class InvalidSqliteCursorError extends InvalidCursorError { constructor(); } ``` A listing cursor that is not a non-empty string of at most 128 characters. An `InvalidCursorError`. ### `InvalidSqliteAuditCursorError` [#invalidsqliteauditcursorerror] ```ts api="@rolebook/sharing-sqlite" class InvalidSqliteAuditCursorError extends InvalidCursorError { constructor(message?: string); } ``` A refused audit cursor. An `InvalidCursorError`. ### `SqliteSharingRowError` [#sqlitesharingrowerror] ```ts api="@rolebook/sharing-sqlite" class SqliteSharingRowError extends Error { readonly code: "SQLITE_SHARING_ROW_INVALID"; readonly table: string; readonly reason: string; constructor(table: string, reason: string); } ``` An invitation, owner, or audit row that does not decode, or an audit cursor that cannot be issued. ### `SqliteLifecycleConflictError` [#sqlitelifecycleconflicterror] ```ts api="@rolebook/sharing-sqlite" class SqliteLifecycleConflictError extends Error { readonly code: "SQLITE_LIFECYCLE_CONFLICT"; constructor(message: string); } ``` A lifecycle postcondition failed; the transaction is rollback-only. ### `SqliteJournalModeError` [#sqlitejournalmodeerror] ```ts api="@rolebook/sharing-sqlite" class SqliteJournalModeError extends Error { readonly code: "SQLITE_JOURNAL_MODE_UNSUPPORTED"; constructor(); } ``` A file database is not in WAL mode (`SQLITE_JOURNAL_MODE_UNSUPPORTED`). ### `SqliteForeignKeysDisabledError` [#sqliteforeignkeysdisablederror] ```ts api="@rolebook/sharing-sqlite" class SqliteForeignKeysDisabledError extends Error { readonly code: "SQLITE_FOREIGN_KEYS_DISABLED"; constructor(); } ``` A write transaction found `PRAGMA foreign_keys` off. ### `PolicyStoreRowError` [#policystorerowerror] ```ts api="@rolebook/sharing-sqlite" class PolicyStoreRowError extends Error { readonly table: string; readonly reason: string; constructor(table: string, reason: string); } ``` A policy-store row that does not decode. `isPolicyStoreRowError` recognizes it. ## @rolebook/sharing-sqlite/bun [#rolebooksharing-sqlitebun] `import { ... } from "@rolebook/sharing-sqlite/bun"`. Typed structurally, so it never imports `bun:sqlite` and type-checks without bun types. ### `createBunSqliteExecutor` [#createbunsqliteexecutor] ```ts api="@rolebook/sharing-sqlite/bun" function createBunSqliteExecutor( database: BunSqliteDatabaseLike, options?: BunSqliteExecutorOptions, ): ParameterizedSqliteExecutor; ``` An executor over one bun:sqlite `Database` (or any synchronous driver of the same shape). It queues every statement and transaction on the connection, fails fast instead of deadlocking when code inside a transaction calls the outer executor, prepares a fresh statement for every call, enables foreign keys, and throws unless `busy_timeout` is 0. ### `BunSqliteExecutorOptions` [#bunsqliteexecutoroptions] ```ts api="@rolebook/sharing-sqlite/bun" interface BunSqliteExecutorOptions { readonly enableForeignKeys?: boolean; readonly allowBusyTimeout?: boolean; } ``` `enableForeignKeys` (default `true`) and `allowBusyTimeout` (default `false`). ### `BunSqliteDatabaseLike` [#bunsqlitedatabaselike] ```ts api="@rolebook/sharing-sqlite/bun" interface BunSqliteDatabaseLike { prepare(sql: string): BunSqliteStatementLike; readonly inTransaction: boolean; } ``` `prepare(sql)` must return a newly prepared statement on every call, never a cached one. ### `BunSqliteStatementLike` [#bunsqlitestatementlike] ```ts api="@rolebook/sharing-sqlite/bun" interface BunSqliteStatementLike { readonly columnNames: readonly string[]; all(...values: SqlValue[]): unknown[]; run(...values: SqlValue[]): { readonly changes: number | bigint; }; finalize?(): void; } ``` ## @rolebook/sharing-sqlite/bun-query [#rolebooksharing-sqlitebun-query] `import { ... } from "@rolebook/sharing-sqlite/bun-query"`. Bun only. The executor that [named authorized queries](/docs/sharing/authorized-queries) require. ### `createBunSqliteQueryExecutor` [#createbunsqlitequeryexecutor] ```ts api="@rolebook/sharing-sqlite/bun-query" function createBunSqliteQueryExecutor(options: { readonly filename: string; readonly maxConnections?: number; }): SqliteQueryExecutor; ``` Runs every connection in a library-owned Bun worker thread: one persistent worker per connection, each running a fixed module shipped in this package and receiving only SQL text and bound values. A synchronous bun:sqlite call cannot be stopped by a timer in the thread that runs it; here a query page's deadline answers at once while the page's worker is terminated, which takes effect when its SQLite call returns. `filename` is an absolute local path in canonical form (URIs, `:memory:`, relative paths and `//` or UNC network roots are refused), and `maxConnections` an integer from 1 to 32 (default 4). Invalid options throw `QueryConfigurationError`. Construction does no I/O; workers start when work needs them. The file must already exist with `PRAGMA encoding` UTF-8 and `PRAGMA journal_mode` WAL: a worker never creates, converts or migrates it, and any other encoding or journal mode fails with `QueryConfigurationError`. Each worker turns `PRAGMA foreign_keys` on and sets `PRAGMA synchronous = FULL`. It keeps the whole [`ParameterizedSqliteExecutor`](#parameterizedsqliteexecutor) contract: deferred and immediate transactions, sticky rollback after a caught SQL error, nested and finished transactions refused, and `SqliteCommitOutcomeUnknownError` for a `COMMIT` whose outcome is unknown. `query()` refuses transaction-control statements, and connection settings, `ATTACH` and temporary tables apply to one pooled connection only. One message is capped at 2 MiB of UTF-8 in each direction; an oversized request or result fails with `code: "QUERY_UNAVAILABLE"`, and a writing statement outside a transaction whose result is refused this way has still run. Pass the same object to `createSqliteSharingAdapter()`, `createSqlitePolicyStore()` and `createSqliteAuthorizedQueries()`. `createSqliteProtectedWriteAdapter()` accepts it too; see [on the worker executor](/docs/sharing-sqlite/protected-updates#on-the-worker-executor). ### `SqliteQueryExecutor` [#sqlitequeryexecutor] ```ts api="@rolebook/sharing-sqlite/bun-query" interface SqliteQueryExecutor extends ParameterizedSqliteExecutor { close(): Promise; readonly [sqliteQueryExecutor]: true; } ``` `[sqliteQueryExecutor]` is a compile-time brand; the query factory checks provenance against the executors this package created, not the shape. `close()` refuses new work, terminates the workers this executor owns and resolves once every exit is confirmed; when that takes longer than 1,000 ms it rejects with [`QueryCloseError`](#querycloseerror), and a later call waits on the same cleanup again. A caller whose `COMMIT`, or statement outside a transaction, was in flight gets `SqliteCommitOutcomeUnknownError`: a killed worker may have committed, so reconcile before retrying. Terminating a worker stops it only when the SQLite call it is in returns, so a statement that never returns keeps its connection slot and `close()` keeps rejecting. `QueryCloseError` is also exported here; its declaration is under [named authorized queries](#querycloseerror). ## @rolebook/sharing-sqlite/libsql [#rolebooksharing-sqlitelibsql] `import { createLibsqlExecutor } from "@rolebook/sharing-sqlite/libsql"`. Needs the optional peer `@libsql/client` `>=0.17.0 <1`. ### `createLibsqlExecutor` [#createlibsqlexecutor] ```ts api="@rolebook/sharing-sqlite/libsql" function createLibsqlExecutor(client: Client): ParameterizedSqliteExecutor; ``` An executor over a **local** `@libsql/client` (`file:` URL or `:memory:`). Throws a `TypeError` for a remote client. Binds integral numbers as integers and runs each query behind a schema read so result columns are named from the current schema. ## Protected application updates [#protected-application-updates] See [the protected and managed update guide](/docs/sharing-sqlite/protected-updates) for authority setup, transaction guarantees, recovery and supported schema boundaries. ### `createSqliteProtectedWriteAdapter` [#createsqliteprotectedwriteadapter] ```ts api="@rolebook/sharing-sqlite" function createSqliteProtectedWriteAdapter(options: CreateSqliteProtectedWriteAdapterOptions): Readonly<{ receiptRoute(): object; forScope(value: TenantContext): Readonly<{ withManagedMove(value: ManagedMoveIntent): Promise<{ readonly status: "committed" | "replayed"; readonly receipt: MutationReceipt; }>; lookupManagedMoveReceipt(value: ManagedMoveIntent): Promise; withManagedDelete(value: ManagedDeleteIntent): Promise<{ readonly status: "committed" | "replayed"; readonly receipt: MutationReceipt; }>; lookupManagedDeleteReceipt(value: ManagedDeleteIntent): Promise; withManagedUpdates(value: ManagedUpdateBatchIntent): Promise | Readonly<{ status: "committed"; receipt: Readonly<{ receiptId: `${string}-${string}-${string}-${string}-${string}`; result: { updates: { resource: ResourceRef; version: string; }[]; }; metadata: HierarchyAuthorizationDecisionMetadata | import("@rolebook/sharing").HierarchyBatchAuthorizationDecisionMetadata; sealedAt: string; }>; }> | Readonly<{ status: "committed"; receipt: Readonly<{ receiptId: `${string}-${string}-${string}-${string}-${string}`; result: { updates: { resource: ResourceRef; version: string; }[]; }; metadata: AuthorizationDecisionMetadata; sealedAt: string; }>; }>>; lookupManagedUpdatesReceipt(value: ManagedUpdateBatchIntent): Promise; withAuthorizedTransaction(value: ProtectedUpdateIntent, operation: (guard: ProtectedUpdateGuard) => Promise): Promise<{ readonly status: "committed" | "replayed"; readonly receipt: MutationReceipt; }>; withManagedUpdate(value: ManagedUpdateIntent): Promise<{ readonly status: "committed" | "replayed"; readonly receipt: MutationReceipt; }>; lookupManagedReceipt(value: ManagedUpdateIntent): Promise; lookupReceipt(value: ProtectedUpdateIntent): Promise; }>; }>; ``` ### `ProtectedWriteDeniedError` [#protectedwritedeniederror] ```ts api="@rolebook/sharing-sqlite" class ProtectedWriteDeniedError extends Error { readonly code = "PROTECTED_WRITE_DENIED"; constructor(); } ``` ### `ProtectedWritePostconditionError` [#protectedwritepostconditionerror] ```ts api="@rolebook/sharing-sqlite" class ProtectedWritePostconditionError extends Error { readonly code = "PROTECTED_WRITE_POSTCONDITION_FAILED"; constructor(); } ``` ### `ProtectedWriteRefusedError` [#protectedwriterefusederror] ```ts api="@rolebook/sharing-sqlite" class ProtectedWriteRefusedError extends Error { readonly code = "PROTECTED_WRITE_REFUSED"; readonly refusal: "hierarchy_not_leaf" | "hierarchy_cycle" | "ancestry_cap" | "hierarchy_edge_refused" | "hierarchy_exists"; constructor(refusal: ProtectedWriteRefusedError["refusal"]); } ``` An enrolled managed delete or move that every authorization check (the protected action on the target included) allowed, refused by the stored hierarchy: `hierarchy_not_leaf` (the resource has children), `hierarchy_cycle` (the destination is the resource or below it), `ancestry_cap` (the moved subtree would end below 16 ancestors), `hierarchy_edge_refused` (the policy does not allow that parent type) or `hierarchy_exists` (the destination is the current parent). Nothing was changed and no receipt was written. ### `ProtectedWriteTimeoutError` [#protectedwritetimeouterror] ```ts api="@rolebook/sharing-sqlite" class ProtectedWriteTimeoutError extends Error { readonly code = "PROTECTED_WRITE_TIMEOUT"; constructor(); } ``` ### `CreateSqliteProtectedWriteAdapterOptions` [#createsqliteprotectedwriteadapteroptions] ```ts api="@rolebook/sharing-sqlite" interface CreateSqliteProtectedWriteAdapterOptions { readonly adapter: SqliteSharingAdapter; readonly sharing: VersionedResourceSharing; readonly identity: TransactionalTenantIdentityResolver; readonly environmentId: string; readonly authorityEpoch: string; readonly journalPrefix: string; readonly maxLifetimeMs?: number; readonly managed?: ManagedWriteDescriptor; readonly managedMove?: SqliteManagedMoveDescriptor; readonly hierarchy?: { readonly control: SqliteInheritanceControl; readonly parentIdColumn?: string; }; } ``` `hierarchy` enables managed delete and managed move on hierarchy-enrolled tenants. `control` is the deployment's hierarchy control facade (`createSqliteHierarchyControl`), built from the same versioned Sharing instance passed as `sharing` (not another instance over the same adapters and store) and the same authority epoch and configuration generation as the adapters' inherited reads; anything else throws at construction. This adapter's `maxLifetimeMs` bounds the whole write; the control's own lifetime does not apply. When `managedMove` is also configured, a move is captured under each route's own mapping, so adding either option keeps every existing receipt key, and the flat descriptor applies only on a flat tenant. `parentIdColumn`, when the application keeps its own parent column, is rewritten by an enrolled move; it must be projected by `managed` and not be a patchable field. Without `hierarchy`, an enrolled delete or move refuses `HIERARCHY_UNAVAILABLE` / `enrolled`. See [managed deletion](/docs/sharing-sqlite/managed-deletion) and [managed moves](/docs/sharing-sqlite/managed-moves). ### `ProtectedUpdateGuard` [#protectedupdateguard] ```ts api="@rolebook/sharing-sqlite" interface ProtectedUpdateGuard { readonly signal: AbortSignal; readonly executor: ParameterizedSqliteExecutor; readonly resource: TrustedResource; readonly resourceVersion: string; readonly incarnationId: string; readonly metadata: AuthorizationDecisionMetadata | HierarchyAuthorizationDecisionMetadata; readonly payload: unknown; } ``` ### `ProtectedUpdateIntent` [#protectedupdateintent] ```ts api="@rolebook/sharing-sqlite" interface ProtectedUpdateIntent { readonly resource: ResourceRef; readonly action: string; readonly incarnationId: string; readonly idempotencyKey: string; readonly payload: unknown; readonly postVersion: string; } ``` ### `TransactionalTenantIdentityResolver` [#transactionaltenantidentityresolver] ```ts api="@rolebook/sharing-sqlite" interface TransactionalTenantIdentityResolver { resolvePrincipalInTransaction(input: { readonly executor: ParameterizedSqliteExecutor; readonly tenantId: string; readonly subject: ResourceRef; }): Promise<{ readonly principal: TenantPrincipal; readonly authority: "complete-local-projection"; readonly expiryDependencies: readonly number[]; readonly revisions: readonly AuthorityRevision[]; }>; } ``` ### `createSqliteLocalIdentityProjection` [#createsqlitelocalidentityprojection] ```ts api="@rolebook/sharing-sqlite" function createSqliteLocalIdentityProjection(options: { readonly table: QualifiedIdentifier; readonly groupSubjectTypes?: readonly string[]; }): { readonly identity: TransactionalTenantIdentityResolver & QueryIdentityResolver; readonly lockEligibleSubjects: SqliteEligibilityFence; readonly readEligibleSubjects: SqliteEligibilityReader; readonly revalidateAuthorizationFacts: SqliteAuthorizationFactFence; }; ``` `identity` also has `resolveQueryPrincipalInTransaction` (see [`QueryIdentityResolver`](#queryidentityresolver)) for [named authorized queries](/docs/sharing/authorized-queries). It returns the same complete local projection as `resolvePrincipalInTransaction`, but judges every expiry against the page's captured database time instead of sampling the clock again, and reports expiries as ISO 8601 millisecond instants. For [listing](/docs/sharing/listing#identity), `identity` is the `resolver` of [`SqlitePageIdentity`](#sqlitepageidentity). `lockEligibleSubjects` already carries its listing reader. `readEligibleSubjects` is that reader on its own, for an adapter whose `lockEligibleSubjects` wraps this projection's fence: pass it, wrapped the same way, as the adapter's `readEligibleSubjects`. It judges expiry at the page's instant and reports each eligible row's expiry. ### `SqlitePageIdentity` [#sqlitepageidentity] ```ts api="@rolebook/sharing-sqlite" interface SqlitePageIdentity { readonly source: TenantIdentityAdapter; readonly resolver: QueryIdentityResolver; } ``` Identity evidence for listing pages, passed as the adapter's `pageIdentity`. `source` is the exact identity adapter object the sharing instance is created with. `resolver` reads that identity's complete local projection through the page's transaction; use `createSqliteLocalIdentityProjection().identity`. Supplying both is your attestation that `source` answers from exactly that projection. Rolebook checks only that the sharing instance's identity is this same object. A sharing instance created with a different object, including a copy or a wrapper of `source`, does not match, and its listings need bracketed evidence from the identity adapter or answer `identity_evidence_missing`. The projection row and the adapter's eligibility authority are separate checks: a projection that says the actor is eligible does not override an eligibility fence that refuses the actor. ### `createSqliteProtectedWriteOutbox` [#createsqliteprotectedwriteoutbox] ```ts api="@rolebook/sharing-sqlite" function createSqliteProtectedWriteOutbox(options: { readonly executor: ParameterizedSqliteExecutor; readonly tablePrefix: string; readonly environmentId: string; readonly operator?: ProtectedWriteOperator; }): Readonly<{ claim(input: { readonly limit: number; readonly leaseMs: number; }): Promise; inspectPending(input: { readonly limit: number; }): Promise[]>; retry(token: ProtectedWriteOutboxClaim["deliveryToken"], input: { readonly delayMs: number; }): Promise; claimForInspection(input: { readonly eventId: string; readonly leaseMs: number; }): Promise<{ readonly environmentId: string; readonly eventId: string; readonly generation: string; } | undefined>; quarantine(token: ProtectedWriteOutboxClaim["deliveryToken"], input: { readonly reason: string; }): Promise<{ readonly environmentId: string; readonly eventId: string; readonly generation: string; } | undefined>; inspectOperatorActions(input: { readonly eventId: string; readonly limit: number; readonly afterGeneration?: string; }): Promise; inspectDeadLetters(input: { readonly limit: number; }): Promise; requeue(token: ProtectedWriteOutboxClaim["deliveryToken"]): Promise; acknowledge(token: ProtectedWriteOutboxClaim["deliveryToken"]): Promise; }>; ``` `inspectPending({ limit })` returns 1–1000 oldest pending rows, including leased rows, with `eventId`, `kind`, `generation` and `state`. It omits payload decoding and is a bounded snapshot, not pagination or a delivery watermark. A future retry delay also appears as `leased`. `retry(deliveryToken, { delayMs })` accepts 0–300000ms and only a current unexpired lease. It advances the fencing generation immediately, so the old ACK fails even during the delay. Stale, expired, delivered or foreign-environment claims return false; invalid bounds throw. Normal claim recovers expired leases after worker crashes. The generation is fencing metadata, not an authentication secret or exact attempt count; restrict inspection to trusted operators. Deduplicate destination effects by `(environmentId, eventId)`. Receipts and outbox rows are retained indefinitely. Explicit quarantine/requeue is available after the additive migration described below. No pruning, scheduler, HTTP route or console integration is provided. `claimForInspection({ eventId, leaseMs })` acquires one exact event's lease without decoding its payload. It cannot steal a live lease or claim a quarantined/delivered event; lease bounds are 1–300000ms. `quarantine(currentToken, { reason })` requires that current unexpired lease and a nonblank reason of 1–1024 characters without NUL. It returns a new quarantine token or `undefined` for an ineligible/stale/foreign claim. Quarantine advances the generation and suppresses delivery; it does not mark the event delivered or change its payload. `inspectDeadLetters({ limit })` returns 1–1000 oldest active quarantines without decoding payloads. `requeue(quarantineToken)` requires the exact active quarantine generation, advances it again and makes the event available for normal claim. It returns false for stale/foreign/already-requeued state. Invalid input throws. Quarantine requires generation below 9223372036854775805 to leave headroom for requeue and a subsequent claim; no operation wraps or resets the counter. These are trusted environment-wide operator methods, not authenticated tenant-user endpoints. They preserve at-least-once delivery and stable event IDs through recovery. Requeue leaves corrupt payloads corrupt; resolve the producer/decoder/destination problem before redelivery. **Migration required:** stop/drain old workers, explicitly run the protected-write migrations to add `_dead_v1`, then start only upgraded workers. Old binaries ignore quarantine and must not run concurrently. New worker paths fail closed if the table is absent. The original receipt and outbox schemas are unchanged. See [operator recovery](/docs/sharing-sqlite/protected-updates#quarantine-and-explicit-operator-recovery). `operator` is optional application-attested attribution copied at factory construction, not a credential or authorization bypass. Omitted identity records null. Each successful quarantine or requeue appends history atomically; append failure rolls back the transition. Failed/stale/foreign operations append nothing. Apply the explicit `_actions_v1` migration before using upgraded operator workers, and stop/drain old binaries. Existing factory calls remain compatible after migration. History starts at upgraded-worker rollout: prior transitions are not fabricated, and mixed-version operator execution cannot claim complete history. `inspectOperatorActions({ eventId, limit, afterGeneration? })` reads immutable successful actions for one exact event in the bound environment. Limit is an integer 1–1000. The exclusive cursor is `"0"` (default) or a canonical positive signed-64-bit decimal generation. Use the last returned generation for the next page. Numeric generation order is independent of timestamps; gaps are normal because claims/retries also advance fencing generations. This is live per-event pagination, not a frozen or cross-event feed. Corrupt returned records fail closed. Retention is indefinite; append-only is an API guarantee under trusted DB ownership, not tamper evidence against database administrators. See [operator history](/docs/sharing-sqlite/protected-updates#retained-operator-action-history). ### `ProtectedWriteOutboxClaim` [#protectedwriteoutboxclaim] ```ts api="@rolebook/sharing-sqlite" type ProtectedWriteOutboxClaim = OutboxClaim; ``` ### `IdempotencyConflictError` [#idempotencyconflicterror] ```ts api="@rolebook/sharing-sqlite" class IdempotencyConflictError extends Error { readonly code: "IDEMPOTENCY_CONFLICT"; constructor(); } ``` ### `MutationJournalRowError` [#mutationjournalrowerror] ```ts api="@rolebook/sharing-sqlite" class MutationJournalRowError extends Error { readonly code: "MUTATION_JOURNAL_CORRUPT"; constructor(cause: unknown); } ``` ### `MutationReceipt` [#mutationreceipt] ```ts api="@rolebook/sharing-sqlite" interface MutationReceipt { readonly receiptId: string; readonly result: unknown; readonly metadata: AuthorizationDecisionMetadata | HierarchyAuthorizationDecisionMetadata | HierarchyBatchAuthorizationDecisionMetadata; readonly sealedAt: string; } ``` `metadata.schemaVersion` is the stored metadata version, not a journal-table schema: 1 for a flat write, 2 for one enrolled target or a legacy multi-target batch, and 3 for an enrolled batch of 2–32 targets. A version-3 `hierarchy` block is evidence for its own target, not a capability. ### `createProtectedWriteMigrations` [#createprotectedwritemigrations] ```ts api="@rolebook/sharing-sqlite" function createProtectedWriteMigrations(options: { readonly tablePrefix: string; }): readonly ResourceSharingMigration[]; ``` ### `applyProtectedWriteMigrations` [#applyprotectedwritemigrations] ```ts api="@rolebook/sharing-sqlite" function applyProtectedWriteMigrations(executor: ParameterizedSqliteExecutor, options: { readonly tablePrefix: string; }): Promise; ``` ### `ManagedWriteDescriptor` [#managedwritedescriptor] ```ts api="@rolebook/sharing-sqlite" interface ManagedWriteDescriptor { readonly target: { readonly schema?: string; readonly table: string; readonly userColumns: readonly string[]; }; readonly fields: readonly ManagedWriteField[]; } ``` ### `ManagedWriteField` [#managedwritefield] ```ts api="@rolebook/sharing-sqlite" interface ManagedWriteField { readonly field: string; readonly column: string; readonly codec: "text" | "boolean" | "safe-integer"; readonly nullable?: boolean; } ``` ### `ManagedUpdateIntent` [#managedupdateintent] ```ts api="@rolebook/sharing-sqlite" interface ManagedUpdateIntent extends Omit { readonly expectedVersion: string; readonly patch: Readonly>; } ``` ### `SqliteCommitOutcomeUnknownError` [#sqlitecommitoutcomeunknownerror] ```ts api="@rolebook/sharing-sqlite" class SqliteCommitOutcomeUnknownError extends Error { readonly code = "COMMIT_OUTCOME_UNKNOWN"; constructor(cause: unknown); } ``` ### `ManagedUpdateBatchIntent` [#managedupdatebatchintent] ```ts api="@rolebook/sharing-sqlite" interface ManagedUpdateBatchIntent { readonly idempotencyKey: string; readonly updates: readonly Omit[]; } ``` An atomic batch of 1–32 distinct existing resources through one configured adapter in one tenant. Each update has the single-update fields except its idempotency key; the outer key binds the whole batch. Use `withManagedUpdates(intent)` and `lookupManagedUpdatesReceipt(intent)`. Input order is canonicalized by resource ID; reordered identical intent replays the same receipt. Create/delete/move and cross-adapter transactions are outside this contract. ### `createSqliteProtectedWriteReceipts` [#createsqliteprotectedwritereceipts] ```ts api="@rolebook/sharing-sqlite" function createSqliteProtectedWriteReceipts(options: { readonly receiptRoute: object; }): Readonly<{ forScope(scope: ReceiptLookupScope): Readonly<{ lookup(input: { readonly idempotencyKey: string; }): Promise; }>; }>; ``` Trusted server lookup of a committed outcome by key. `receiptRoute` is the opaque object from `createSqliteProtectedWriteAdapter(...).receiptRoute()`. It captures that adapter's resource type, journal prefix and environment. A missing, cloned or foreign route throws before any journal read. Bind tenant and actor from authenticated server context and enforce application access policy before calling `lookup`. Every query includes environment, tenant, actor type, actor ID and key. It returns an immutable receipt or `undefined`; absence does not prove rollback, including while a `COMMIT` may still be in flight. This does not validate a proposed retry payload: use the protected adapter’s exact-intent receipt lookup for that. Receipt access can expose sensitive historical business results. ### `ProtectedWriteDeadLetter` [#protectedwritedeadletter] ```ts api="@rolebook/sharing-sqlite" type ProtectedWriteDeadLetter = OutboxDeadLetter; ``` An immutable diagnostic record with `eventId`, `kind`, `reason`, ISO `quarantinedAt`, and `quarantineToken` (environment/event/generation). It contains no payload or receipt result. The underlying alias is an implementation type; applications use this exported type. Inspection returns only active quarantines and fails closed on inconsistent generation/identity evidence. The retained side row stores the latest quarantine/requeue state. The separate operator-action history retains successful transitions after the history upgrade. ### `ManagedDeleteIntent` [#manageddeleteintent] ```ts api="@rolebook/sharing-sqlite" interface ManagedDeleteIntent extends Omit { readonly expectedVersion: string; } ``` One callback-free deletion of an exact existing resource incarnation and version, using the configured managed descriptor. `withManagedDelete(intent)` authorizes the resource/action and atomically removes the business row and live sharing state while retaining lifecycle evidence, a receipt and one outbox event. `lookupManagedDeleteReceipt(intent)` recovers the original outcome; it does not authorize a replacement incarnation. See [Managed deletion](/docs/sharing-sqlite/managed-deletion). ### `ProtectedWriteOperator` [#protectedwriteoperator] ```ts api="@rolebook/sharing-sqlite" type ProtectedWriteOperator = OutboxOperator; ``` An optional application-attested `{ type, id }` identity copied and frozen at worker construction. Both fields are nonblank strings of at most 1024 characters without NUL. The library does not authenticate or authorize this identity. Omitted identity is recorded as null. ### `ProtectedWriteOperatorAction` [#protectedwriteoperatoraction] ```ts api="@rolebook/sharing-sqlite" type ProtectedWriteOperatorAction = OutboxOperatorAction; ``` An immutable retained successful-action record with `environmentId`, `eventId`, stable `actionId`, resulting decimal `generation`, `action` (`quarantine` or `requeue`), nullable `operator`, nullable `reason`, and ISO `recordedAt`. Requeue reasons are null. The timestamp describes the transition inside its transaction, not exact COMMIT time. The action ID is a digest identifier, not a signature. No receipt or event payload is included. ### `ManagedMoveIntent` [#managedmoveintent] ```ts api="@rolebook/sharing-sqlite" interface ManagedMoveIntent extends Omit { readonly expectedVersion: string; readonly sourceParent: ManagedParentExpectation; readonly destinationParent: ManagedParentExpectation; } ``` ### `ManagedParentExpectation` [#managedparentexpectation] ```ts api="@rolebook/sharing-sqlite" interface ManagedParentExpectation { readonly type?: string; readonly id: string; readonly incarnationId: string; readonly version: string; } ``` ### `ManagedParentField` [#managedparentfield] ```ts api="@rolebook/sharing-sqlite" interface ManagedParentField { readonly field: string; readonly column: string; readonly codec: "text" | "boolean" | "safe-integer"; readonly nullable?: boolean; } ``` ### `SqliteManagedMoveDescriptor` [#sqlitemanagedmovedescriptor] ```ts api="@rolebook/sharing-sqlite" interface SqliteManagedMoveDescriptor { readonly parentIdColumn: string; readonly parent: { readonly resourceType: string; readonly schema: string; readonly table: string; readonly tenantColumn: string; readonly idColumn: string; readonly versionColumn: string; readonly incarnationColumn: string; readonly expiresAtColumn?: string; readonly userColumns: readonly string[]; readonly fields: readonly ManagedParentField[]; }; readonly sourceAction: string; readonly destinationAction: string; } ``` ### `createSqliteProtectedWriteDeliveryWorker` [#createsqliteprotectedwritedeliveryworker] ```ts api="@rolebook/sharing-sqlite" function createSqliteProtectedWriteDeliveryWorker(options: OutboxDeliveryOptions & { readonly executor: ParameterizedSqliteExecutor; readonly tablePrefix: string; readonly environmentId: string; readonly operator?: ProtectedWriteOperator; }): OutboxDeliveryWorkerWithDiagnostics; ``` Creates the shared bounded delivery worker over this adapter's existing protected-write outbox. Apply explicit journal/operator-history migrations first. Operator identity is copied at construction as application-attested attribution; omitted identity remains null. No authentication, daemon, scheduler, actual sink service or payload/receipt mutation is added. One pass claims batchSize1–32 events, starts at most that many concurrent sinks after releasing the claim connection, and serializes exact-token settlements. Lease bounds are1–300000ms and callback timeout is1–leaseMs. Only explicit delivered results permit ACK. Caller-selected retry/quarantine, unknown outcomes, stale leases and ambiguous ACKs follow the [shared delivery contract](/docs/sharing/outbox-delivery). Cancellation prevents future queued settlements but cannot undo submitted DB work or external sink effects. A worker stays busy while abandoned sink work remains. No automatic retry occurs. The optional `diagnostics` option is forwarded to the shared worker unchanged and validated at construction; `diagnostics()` returns the worker-local, redacted snapshot described in [worker diagnostics](/docs/sharing/outbox-delivery#worker-diagnostics). ## Named authorized queries [#named-authorized-queries] A small, fixed set of named queries over the adapter's own resource table that return only the resource keys the actor is allowed. Bun only, because it requires the worker-backed executor. The contract, bounds and guarantees are in the [named authorized queries guide](/docs/sharing/authorized-queries). ### `createSqliteAuthorizedQueries` [#createsqliteauthorizedqueries] ```ts api="@rolebook/sharing-sqlite" function createSqliteAuthorizedQueries(options: CreateSqliteAuthorizedQueriesOptions): AuthorizedQueries; ``` Checks every capability without database I/O and throws `QueryConfigurationError` before serving a request: the original adapter on an executor made by [`createBunSqliteQueryExecutor()`](#createbunsqlitequeryexecutor) (checked by provenance, not by shape), with an enforced `fencePolicy` for the policy store of `sharing`, which must use that same executor object; a resolver with `resolveQueryPrincipalInTransaction`; and a registry whose table, tenant and ID columns equal the adapter's descriptor. `createBunSqliteExecutor()`, `createLibsqlExecutor()` and any other executor are refused here. One page is one read-only `BEGIN DEFERRED` transaction on one worker connection. `close()` drains this factory's pages and never closes the executor. ### `CreateSqliteAuthorizedQueriesOptions` [#createsqliteauthorizedqueriesoptions] ```ts api="@rolebook/sharing-sqlite" interface CreateSqliteAuthorizedQueriesOptions { readonly adapter: SqliteSharingAdapter; readonly sharing: VersionedResourceSharing; readonly identity: QueryIdentityResolver; readonly queries: readonly QueryDefinition[]; readonly listingCursorKey: string | Uint8Array | readonly (string | Uint8Array)[]; readonly environmentId: string; } ``` `queries` holds 1 to 64 definitions. `listingCursorKey` is one key or 1 to 8 keys: the first seals and every key opens, and there is no random default. `environmentId` matches `[A-Za-z][A-Za-z0-9_-]{0,63}` and is bound into every cursor. `identity` is usually `createSqliteLocalIdentityProjection().identity`. The shapes below are declared once in `@rolebook/sharing` and re-exported from this package and from `@rolebook/sharing-postgres`. Import them from the driver package: `@rolebook/sharing` does not export them from its root. ### `AuthorizedQueries` [#authorizedqueries] ```ts api="@rolebook/sharing/internal/transaction-runtime" interface AuthorizedQueries { forTenant(binding: QueryTenantBinding): TenantAuthorizedQueries; close(): Promise; } ``` The factory. `forTenant(binding)` captures the trusted binding synchronously and throws `QueryConfigurationError` when it is invalid. `close()` rejects new requests, ends the pages in flight and resolves once they have settled; when that takes longer than 1,000 ms it rejects with `QueryCloseError`, and a later call waits on the same cleanup again. ### `TenantAuthorizedQueries` [#tenantauthorizedqueries] ```ts api="@rolebook/sharing/internal/transaction-runtime" interface TenantAuthorizedQueries { query(request: QueryRequest): Promise; } ``` `query()` never throws for an operational failure: every failure is a coded `QueryResult`. ### `QueryTenantBinding` [#querytenantbinding] ```ts api="@rolebook/sharing/internal/transaction-runtime" interface QueryTenantBinding { readonly tenantId: string; readonly actor: ResourceRef; readonly context?: Readonly>; readonly sessionBinding: string; } ``` Trusted server facts, never client input. `context` is plain JSON within Core's context bounds (default `{}`) and may not contain `tenantId` or `sharingRevision`. `sessionBinding` is your session or authority incarnation, 1 to 128 UTF-16 units; it is bound into every cursor and never returned. ### `QueryRequest` [#queryrequest] ```ts api="@rolebook/sharing/internal/transaction-runtime" interface QueryRequest { readonly name: string; readonly filters?: readonly QueryPredicate[]; readonly limit?: number; readonly cursor?: string; } ``` `name` selects a registered query. `filters` is a conjunction (default none), `limit` an integer from 1 to 100 (default 25, not bound to the cursor), and `cursor` the previous page's `nextCursor`. ### `QueryPredicate` [#querypredicate] ```ts api="@rolebook/sharing/internal/transaction-runtime" type QueryPredicate = { readonly field: string; readonly op: "eq" | "gt" | "gte" | "lt" | "lte"; readonly value: QueryScalar; } | { readonly field: string; readonly op: "in"; readonly value: readonly QueryScalar[]; } | { readonly field: string; readonly op: "isNull"; readonly value: boolean; }; type QueryScalar = string | number | boolean; ``` `field` is a registered filter name and `op` one of its registered operators. `in` takes 1 to 32 distinct values of one type, ranges take integers or strings, and `isNull` is the only way to test for null. `QueryScalar` is not exported by name. ### `QueryResult` [#queryresult] ```ts api="@rolebook/sharing/internal/transaction-runtime" type QueryResult = { readonly ok: true; readonly page: { readonly items: readonly ResourceKey[]; readonly nextCursor?: string; readonly exhausted: boolean; readonly completion: "complete" | "budget_limited"; readonly evaluatedAt: number; readonly queryVersion: string; readonly schemaVersion: string; readonly consistency: "local-snapshot"; readonly traversal: "live"; }; } | { readonly ok: false; readonly code: QueryErrorCode; }; type QueryErrorCode = "INVALID_REQUEST" | "INVALID_CURSOR" | "CURSOR_STALE_RESTART" | "QUERY_UNAVAILABLE"; ``` `items` are resource keys only. `exhausted: true` comes with no `nextCursor`; otherwise `nextCursor` is present, even when `items` is empty. `evaluatedAt` is the page's database time in epoch milliseconds. `QueryErrorCode` is not exported by name. The codes are described in the [guide](/docs/sharing/authorized-queries#errors). ### `QueryDefinition` [#querydefinition] ```ts api="@rolebook/sharing/internal/transaction-runtime" interface QueryDefinition { readonly name: string; readonly version: string; readonly resourceType: string; readonly action: string; readonly schemaVersion: string; readonly table: string; readonly tenantColumn: string; readonly idColumn: string; readonly filters: Readonly>; readonly sort: QuerySort; } ``` One trusted, server-registered query. `table`, `tenantColumn` and `idColumn` must equal the adapter's resource descriptor. Names, versions and filter names match `[A-Za-z][A-Za-z0-9_-]{0,63}`; SQL identifiers are unqualified `[A-Za-z_][A-Za-z0-9_]{0,62}`. ### `FilterColumn` [#filtercolumn] ```ts api="@rolebook/sharing/internal/transaction-runtime" interface FilterColumn { readonly column: string; readonly type: ColumnType; readonly operators: readonly QueryFilterOperator[]; readonly disclosable: true; } type QueryFilterOperator = "eq" | "in" | "gt" | "gte" | "lt" | "lte" | "isNull"; ``` `operators` is non-empty and unique; range operators are invalid for `boolean`. `disclosable: true` attests that every subject who may run the query and receive this action's resources may learn the column's values by inference. `QueryFilterOperator` is not exported by name. ### `QuerySort` [#querysort] ```ts api="@rolebook/sharing/internal/transaction-runtime" interface QuerySort { readonly column: string; readonly type: ColumnType; readonly direction: "asc" | "desc"; readonly nulls: "first" | "last"; readonly disclosable: true; } ``` The one sort. Resource IDs always break ties, ascending in binary order, whatever `direction` is. ### `ColumnType` [#columntype] ```ts api="@rolebook/sharing/internal/transaction-runtime" type ColumnType = "integer" | "string" | "boolean"; ``` `integer` is a safe integer, `string` compares in binary UTF-8 order, and `boolean` sorts `false` before `true`. Every registered column may be nullable except the tenant and ID columns. ### `QueryIdentityResolver` [#queryidentityresolver] ```ts api="@rolebook/sharing/internal/transaction-runtime" interface QueryIdentityResolver { resolveQueryPrincipalInTransaction(input: { readonly executor: TExecutor; readonly tenantId: string; readonly subject: ResourceRef; readonly evaluatedAt: string; }): Promise; } interface QueryPrincipalResolution { readonly principal: TenantPrincipal; readonly authority: "complete-local-projection"; readonly expiryDependencies: readonly string[]; readonly revisions: readonly AuthorityRevision[]; } ``` Resolves the actor inside the page transaction. `evaluatedAt` is the page's captured database time (ISO 8601 UTC, milliseconds), and the resolver must judge every expiry against it. The local identity projection's `identity` implements it. `QueryPrincipalResolution` is not exported by name. ### `QueryConfigurationError` [#queryconfigurationerror] ```ts api="@rolebook/sharing/internal/transaction-runtime" class QueryConfigurationError extends Error { readonly code: "QUERY_CONFIGURATION_INVALID"; constructor(); } ``` Thrown by the factory and by `forTenant()` for an invalid or unsupported configuration or binding. Its message is fixed and it carries no cause. `instanceof` across separately bundled copies of `@rolebook/sharing` is not promised, so branch on `code`. ### `QueryCloseError` [#querycloseerror] ```ts api="@rolebook/sharing/internal/transaction-runtime" class QueryCloseError extends Error { readonly code: "QUERY_CLOSE_FAILED"; constructor(); } ``` `close()` could not confirm within 1,000 ms that every owned page had been cleaned up. Its message is fixed and it carries no cause. ## Governance attachment [#governance-attachment] Create a SQLite governance attachment once for a sharing resource configuration. Give its `adapterOptions` to the SQLite sharing adapter and its `attachment` to the sharing configuration. The governing-rule resolver receives both tenant and resource identifiers, preserving tenant isolation when resource IDs overlap. ### `createSqliteGovernanceAttachment` [#createsqlitegovernanceattachment] ```ts api="@rolebook/sharing-sqlite" function createSqliteGovernanceAttachment(options: SqliteGovernanceAttachmentOptions): SqliteGovernanceAttachmentBundle; ``` ### `SqliteGovernanceAdapterOptions` [#sqlitegovernanceadapteroptions] ```ts api="@rolebook/sharing-sqlite" interface SqliteGovernanceAdapterOptions { readonly governanceGate: GovernanceDirectGate; readonly governanceBinding: GovernanceBinding; readonly lockEligibleSubjects: SqliteEligibilityFence; readonly fencePolicy?: SqlitePolicyFence; } ``` ### `SqliteGovernanceAttachmentBundle` [#sqlitegovernanceattachmentbundle] ```ts api="@rolebook/sharing-sqlite" interface SqliteGovernanceAttachmentBundle { readonly attachment: GovernanceAttachment; readonly adapterOptions: SqliteGovernanceAdapterOptions; } ``` ### `SqliteGovernanceAttachmentOptions` [#sqlitegovernanceattachmentoptions] Bind the identity assignment table and group graph that this tenant uses. For a source the application does not use, declare `evidenceSources.identity` or `evidenceSources.groups` as `"none"`. If a required source is missing, governed decisions return `UNAVAILABLE`. With `groups: "none"`, governance cannot see anyone's teams: wherever a group holds any role on the resource (or on a parent the resource inherits from, or anywhere in the tenant when the resource passes access down), approvals and rejections cannot be confirmed and answer `UNKNOWN_REQUEST`, so such a request cannot complete. Bind a group graph to govern resources that teams hold roles on. Without a group graph, a request whose target is a group also cannot complete, because nobody's membership of that group can be seen: an approval or rejection from someone who would otherwise count answers `UNAVAILABLE`, and from anyone else `UNKNOWN_REQUEST`, as for a request that does not exist. ```ts api="@rolebook/sharing-sqlite" interface SqliteGovernanceAttachmentOptions { readonly executor: ParameterizedSqliteExecutor; readonly tablePrefix: string; readonly requestTtlMs: number; readonly restoreEpoch: string | (() => string | "pending" | "unavailable" | Promise); readonly governingRule: (tenantId: string, resourceId: string, command: GovernanceFoundationCommandKind, scope: SqliteGovernanceRuleScope) => GovernanceRuleSnapshot | "clear" | "unavailable" | Promise; readonly binding: GovernanceBinding; readonly eligibility: SqliteEligibilityFence; readonly policyFence?: SqlitePolicyFence; readonly policyStore?: PolicyStore; readonly policy: RolebookPolicy; readonly sharing: SqliteGovernanceSharingConfig; readonly groupGraph?: SqliteGovernanceGroupSource; readonly identityAssignmentTable?: string; readonly evidenceSources?: { readonly identity?: "none"; readonly groups?: "none"; }; readonly clock?: () => number; readonly outbox?: { readonly tablePrefix: string; readonly environmentId: string; }; } ``` ### `SqliteGovernanceSharingConfig` [#sqlitegovernancesharingconfig] ```ts api="@rolebook/sharing-sqlite" interface SqliteGovernanceSharingConfig { readonly resourceType: string; readonly memberRoles: Readonly>; readonly ownershipRole: string; readonly management: { readonly members: string; readonly ownership: string; }; readonly parents?: readonly GovernanceFoundationRef[]; readonly attributes?: Readonly>; readonly inheritingTypes?: readonly string[]; } ``` ## Access-change delivery [#access-change-delivery] The delivery cursor and queue behind [access-change webhooks](/docs/sharing/webhooks). ### `AccessChangeDeliveryError` [#accesschangedeliveryerror] ```ts api="@rolebook/sharing-sqlite" class AccessChangeDeliveryError extends Error { readonly code: AccessChangeDeliveryErrorCode; constructor(code: AccessChangeDeliveryErrorCode, message: string); } ``` Thrown when delivery storage returns a row that does not decode, or when a subscription is bound to another tenant. Each resource type is drained in its own transaction: a drain that fails on one resource type keeps what earlier ones queued, and a failed page queues nothing and leaves its cursor where it was. ### `applyAccessChangeDeliveryMigrations` [#applyaccesschangedeliverymigrations] ```ts api="@rolebook/sharing-sqlite" function applyAccessChangeDeliveryMigrations(executor: ParameterizedSqliteExecutor, options: { readonly tablePrefix: string; readonly resources: readonly SqliteResourceDescriptor[]; }): Promise; ``` Creates the delivery tables and, on each audit table of `resources`, the trigger that positions every new row, in one `BEGIN IMMEDIATE` transaction, and refuses an existing object whose stored definition differs. Each audit table's counter starts at its highest existing position. Never run automatically. ### `createAccessChangeDeliveryMigrations` [#createaccesschangedeliverymigrations] ```ts api="@rolebook/sharing-sqlite" function createAccessChangeDeliveryMigrations(options: { readonly tablePrefix: string; readonly resources: readonly SqliteResourceDescriptor[]; }): readonly ResourceSharingMigration[]; ``` The delivery table and trigger definitions, one object per step, for review. Apply them with `applyAccessChangeDeliveryMigrations`. ### `createSqliteAccessChangeDeliveryStore` [#createsqliteaccesschangedeliverystore] ```ts api="@rolebook/sharing-sqlite" function createSqliteAccessChangeDeliveryStore(options: { readonly executor: ParameterizedSqliteExecutor; readonly tablePrefix: string; readonly environmentId: string; readonly resources: readonly SqliteResourceDescriptor[]; }): AccessChangeDeliveryStore; ``` The SQLite delivery store over the audit tables of `resources`. Rows are drained in `delivery_seq` order, which the delivery trigger assigns from a counter that only grows, under the write lock the inserting transaction holds, and so is commit order. Every write retries `SQLITE_BUSY`. Bound to one `environmentId`. # SQLite adapter (/docs/sharing-sqlite) > @rolebook/sharing-sqlite: a driver-neutral SQLite storage adapter for local-first, edge, and desktop apps. `@rolebook/sharing-sqlite` gives the same guarantees as the [PostgreSQL adapter](/docs/sharing-postgres) on SQLite: tenant-scoped reads, fenced mutations, revision compare-and-increment, idempotency, audit, and fail-closed migrations, verified by the same [contract](/docs/sharing-testkit). It never imports a driver; thin executors ship for bun:sqlite (`@rolebook/sharing-sqlite/bun`) and local `@libsql/client` (`@rolebook/sharing-sqlite/libsql`), and better-sqlite3 or node:sqlite need a few lines. [Named authorized queries](/docs/sharing/authorized-queries) need the worker-backed Bun executor from `@rolebook/sharing-sqlite/bun-query`. Every mutation runs in `BEGIN IMMEDIATE`, which takes the database write lock before the first statement and holds it to commit. No other connection or process can commit in between, so the write lock is the fence: no row locks are needed. Requirements: SQLite 3.37 or later with JSON support (`RETURNING` needs 3.35, `STRICT` tables 3.37, and JSON is built in from 3.38), WAL mode for file databases, and foreign keys enabled on every connection. ## Set up with bun:sqlite [#set-up-with-bunsqlite] ```ts title="sharing.ts" import { Database } from "bun:sqlite"; import { trustedResource } from "rolebook"; import { applyResourceSharingMigrations, createSqliteMembershipEligibilityFence, createSqliteSharingAdapter, type SqliteResourceDescriptor, } from "@rolebook/sharing-sqlite"; import { createBunSqliteExecutor } from "@rolebook/sharing-sqlite/bun"; const database = new Database("app.db"); database.run("PRAGMA journal_mode = WAL"); const executor = createBunSqliteExecutor(database); // also runs PRAGMA foreign_keys = ON const projectTable = { resourceType: "project", table: "project", tenantColumn: "workspace_id", idColumn: "id", resourceVersionColumn: "version", sharingTablePrefix: "project", resourceColumns: ["visibility"], resourceFromRow: (row) => trustedResource( { type: "project", id: String(row.id) }, [{ type: "workspace", id: String(row.workspace_id) }], { visibility: String(row.visibility) }, ), } as const satisfies SqliteResourceDescriptor; await applyResourceSharingMigrations(executor, projectTable); export const projectAdapter = createSqliteSharingAdapter({ executor, resource: projectTable, lockEligibleSubjects: createSqliteMembershipEligibilityFence({ table: "member", // your organization-member table, for example Better Auth's tenantColumn: "organization_id", subjectIdColumn: "user_id", }), }); ``` The descriptor is the PostgreSQL one without SQL types: IDs are `TEXT` with BINARY collation, the application table is one unqualified table in `main`, and `sharingTablePrefix` is lowercase and globally unique. The row passed to `resourceFromRow` also carries the reserved aliases `__rolebook_sharing_revision` (and `__rolebook_resource_version` for an INTEGER version), read back as exact text. ## With libSQL [#with-libsql] ```ts import { createClient } from "@libsql/client"; import { createLibsqlExecutor } from "@rolebook/sharing-sqlite/libsql"; const client = createClient({ url: "file:app.db" }); await client.execute("PRAGMA journal_mode = WAL"); const executor = createLibsqlExecutor(client); ``` Remote libSQL (Turso, sqld) is **not supported**: `createLibsqlExecutor()` throws a `TypeError` for any client whose protocol is not `"file"`, before any statement runs. An embedded replica (a `file:` URL with a `syncUrl`) is a local client and is accepted, but it reads locally and can lag the primary: send sharing reads to the primary, or sync first, when a revocation must take effect immediately. ## Executors [#executors] A `ParameterizedSqliteExecutor` has two methods: `query(sql, values)` runs one statement with `?` parameters, and `transaction({ behavior }, operation)` runs `operation` on one connection between `BEGIN IMMEDIATE` (or `BEGIN DEFERRED`) and `COMMIT`, rolls back on error, keeps other callers off that connection, and rejects nested transactions. Values are strings, numbers, bigints, `null`, or `Uint8Array`. `createBunSqliteExecutor(database, options?)` accepts any synchronous driver with bun:sqlite's shape: `prepare(sql)` returning a **newly prepared** statement each call (never a cached one: a cached statement keeps the column names it first read, so after an `ALTER TABLE` it would label values with the wrong columns), plus `inTransaction`. For better-sqlite3: ```ts no-check import BetterSqlite3 from "better-sqlite3"; import { createBunSqliteExecutor } from "@rolebook/sharing-sqlite/bun"; const database = new BetterSqlite3("app.db"); database.pragma("busy_timeout = 0"); const executor = createBunSqliteExecutor({ prepare(sql) { const statement = database.prepare(sql); return { columnNames: statement.reader ? statement.columns().map((column) => column.name) : [], all: (...values) => statement.all(...values), run: (...values) => statement.run(...values), }; }, get inTransaction() { return database.inTransaction; }, }); ``` This block is not type-checked because better-sqlite3 is not a dependency of any Rolebook package. For node:sqlite, wrap `DatabaseSync` the same way with `statement.columns()` and `database.isTransaction`. | `createBunSqliteExecutor` option | Default | Meaning | | --- | --- | --- | | `enableForeignKeys` | `true` | Run `PRAGMA foreign_keys = ON` when the executor is created. | | `allowBusyTimeout` | `false` | Accept a connection whose `busy_timeout` is not 0. | One synchronous `Database` is one connection: open one connection (and executor) per concurrent writer. With several connections to one file in one process, keep `PRAGMA busy_timeout` at 0, because a synchronous busy wait blocks the event loop the lock holder needs; the adapter's busy retry waits asynchronously instead. The bun executor throws unless the timeout is 0; set `allowBusyTimeout` only for a connection alone in its process. Never open one file through two copies of SQLite in one process (for example bun:sqlite and libSQL): a closing connection of one copy can delete the WAL files the other still uses. ## WAL and foreign keys are required [#wal-and-foreign-keys-are-required] A file database must be in WAL mode (`PRAGMA journal_mode = WAL`; it persists in the file). In the rollback-journal modes, an open read on one connection makes another's `COMMIT` fail with `SQLITE_BUSY`, so migrations and every write transaction throw `SqliteJournalModeError` unless the mode is `wal`. In-memory databases are exempt. SQLite ignores foreign keys unless each connection enables them, and the live sharing tables rely on `ON DELETE CASCADE`: without enforcement a deleted resource leaves orphaned grants a later resource with the same ID would inherit. Every write transaction checks `PRAGMA foreign_keys` and throws `SqliteForeignKeysDisabledError` when it is off. Every connection that deletes or moves application rows must enable it too. The migration also installs a key guard trigger, `_rolebook_key_guard`, that refuses to change the `(tenant, id)` of an application row that still has sharing rows. Move resources through [`resourceMovedInTransaction()`](/docs/sharing-sqlite/operations#lifecycle). ## Next [#next] The migration runner, drift checks, rollback, and upgrades. BEGIN IMMEDIATE, busy retries, identity fences, teams, initialization, deletes, and moves. Every export of the three entry points. # Managed deletion (/docs/sharing-sqlite/managed-deletion) > Delete one authorized resource and its live sharing state in one local transaction. `withManagedDelete()` performs one generated, conditional business-row deletion. The same transaction authorizes the resource/action, removes its live sharing state, retains lifecycle evidence, seals the original authority dependencies and records one receipt and one outbox event. It uses the existing managed descriptor and complete local identity and policy fences from [protected updates](/docs/sharing-sqlite/protected-updates). ## Delete an exact incarnation [#delete-an-exact-incarnation] Configure a destructive action in the Sharing resource definition, such as `delete` mapped to `document:delete`, and grant that permission through your policy. The trusted server chooses this action for its deletion command; never accept an arbitrary action name from an untrusted request. Resource-wide authorization is required. A field-only grant cannot authorize deletion. ```ts import { createSqliteProtectedWriteAdapter, type ManagedDeleteIntent } from "@rolebook/sharing-sqlite"; // The configured instance includes a managed descriptor and complete local authority fences. declare const protectedAdapter: ReturnType; declare const incarnationId: string; declare const currentVersion: string; const scoped = protectedAdapter.forScope({ tenantId: "application_namespace", actor: { type: "user", id: "user_123" }, }); const intent = { resource: { type: "document", id: "document_1" }, action: "delete", incarnationId, idempotencyKey: "delete-document_1-once", expectedVersion: currentVersion, } satisfies ManagedDeleteIntent; const outcome = await scoped.withManagedDelete(intent); // On an uncertain COMMIT, use this exact intent in trusted server recovery. const recovered = await scoped.lookupManagedDeleteReceipt(intent); ``` The operation has no SQL callback, patch or post-version. Its result contains `deleted: true`, the resource reference, deleted incarnation and deleted resource version. The receipt metadata describes the authority used before deletion. Authorization happens before the expected-version comparison. Missing resources, wrong incarnations and denied actions fail closed. ## Atomic cleanup and retained evidence [#atomic-cleanup-and-retained-evidence] The adapter deletes only the matching namespace, resource ID, incarnation and version. It proves that the business row and all live owner, membership, invitation and sharing-idempotency rows are absent. The existing lifecycle code retains the revision floor, lifecycle outcome and audit for the deleted incarnation. The protected receipt and outbox event are retained independently of the deleted resource; there is exactly one protected event for this operation. The final seal follows all deletion and lifecycle DML. It revalidates policy, identity eligibility, complete group/assignment/absence facts and the **original** identity and membership expiry dependencies, including dependencies whose granting rows have just been removed. A failed seal rolls the deletion and its evidence back together. Validity is established at the final seal; this is not a promise about the exact physical commit timestamp. Resource ancestry must come from the locked, authoritative resource projection. Scoped assignments and group facts remain covered by the complete local identity fences after deletion. This API does not discover or fence arbitrary external ancestor tables or graph traversal dependencies. All participating writers must obey the existing revision/fence contract. ## Replay and recreation [#replay-and-recreation] The `managed.delete.v1` receipt binds the namespace, actor, key, resource, action, expected version, incarnation, authority epoch and configured descriptor digest. Reusing its key with changed intent conflicts. Exact replay returns the original receipt before current schema or authorization checks, without another delete or outbox event. This remains true after recreation or schema drift. Reinitializing a resource under the same ID creates a fresh incarnation and advances the retained sharing revision floor. A fresh request for the old incarnation cannot delete that replacement. A recovered receipt is historical outcome evidence, never permission to act on a replacement. A missing receipt does not prove that an in-flight or ambiguous commit cannot succeed. ## On a hierarchy-enrolled tenant [#on-a-hierarchy-enrolled-tenant] On a tenant whose hierarchy is enrolled (see [inherited access](/docs/sharing/inheritance)), the same `withManagedDelete()` runs through the hierarchy command engine, inside its own protected transaction, when the adapter is given the deployment's hierarchy control facade: ```ts import { createSqliteProtectedWriteAdapter, type SqliteInheritanceControl, } from "@rolebook/sharing-sqlite"; declare const options: Parameters[0]; declare const control: SqliteInheritanceControl; // from createSqliteHierarchyControl const protectedAdapter = createSqliteProtectedWriteAdapter({ ...options, hierarchy: { control } }); ``` Without `hierarchy`, an enrolled delete refuses `HIERARCHY_UNAVAILABLE` / `enrolled` after the current gate and before any journal lookup or effect. - **Leaves only.** A resource with any child refuses `PROTECTED_WRITE_REFUSED` / `hierarchy_not_leaf` and nothing changes. Delete a subtree bottom-up, one leaf per call; descendants are never orphaned. - **Authorization.** The protected action on the resource's inherited snapshot, plus the hierarchy command map: the type's `delete` and `management.members` on the resource, and the parent's `removeChild` and `management.members` (for a root, the bootstrap `rootPlacement`). Any denial, and a missing resource, is `PROTECTED_WRITE_DENIED`; a structural refusal is reported only after every check, the protected action included, allowed. - **Effects.** The business row, every live Sharing row, the revision floor, lifecycle record and audit, as on a flat tenant, then the resource's link; the parent path's subtree heights are repaired in the same transaction. - **Receipt.** Metadata version 2: the protected fields with the resource's pre-delete inherited evidence (its stored chain). The result and the `protected.delete.committed` event are unchanged. - **One final seal** covers the local identity, the inherited memberships the decisions relied on, and every decision read's `validUntil`; an expiry at or before it rolls everything back. - **Retry.** The journal lookup follows the hierarchy gate and precedes the first resource lock; a stored receipt returns verbatim. A `SQLITE_BUSY` reruns the whole attempt under the hierarchy control's retry policy, recapturing the clock, identity, evidence and seal. Exhaustion is `HIERARCHY_UNAVAILABLE` / `serialization_conflict`. ## Supported schema and transaction boundary [#supported-schema-and-transaction-boundary] Both checked local drivers, Bun SQLite and file-backed libSQL, use one `BEGIN IMMEDIATE` transaction, with no automatic retry on a flat tenant. Its writer lock stabilizes the schema and authority while cleanup and final sealing run. Main and temporary triggers are inspected. Remote libSQL and in-memory libSQL are outside the protected-write contract. Every live sharing, retained lifecycle and journal relation must also be an ordinary permanent table. PostgreSQL rejects inheritance and partitioning on all these relations; SQLite rejects views, virtual/shadow tables and temporary name shadows. The existing managed-target checks still apply. Deletion additionally rejects user triggers or rules on live sharing, retained lifecycle and journal tables, and rejects foreign keys into the target or its live sharing tables except the exact first-party tenant/resource cascade edges. SQLite retains its exact first-party resource-key guard. General application cascade graphs, including otherwise harmless extra referring tables, are deliberately unsupported in this slice. Application DDL and migrations are trusted. Run the adapter migrations and preserve their schema, constraints, defaults and collations. These checks restrict supported side effects; they are not a sandbox against a malicious database owner, privileged DDL, custom SQL functions or a false identity resolver. One local adapter/resource is supported. General creation, movement, batch deletion, cross-adapter transactions and public consistency tokens remain outside this API. # Managed same-tenant moves (/docs/sharing-sqlite/managed-moves) > Reparent one leaf resource using SQL-authoritative parent permissions in one transaction. `withManagedMove()` moves one existing leaf between two distinct root parents in the same namespace. The adapter reads both parents from one configured SQL table, checks the source remove and destination accept permissions, changes the child parent column and version, and advances its sharing revision. Owner, incarnation, direct memberships, invitations and previous sharing-idempotency records remain intact. This API requires the complete local identity and policy fences described in [protected updates](/docs/sharing-sqlite/protected-updates), plus the existing `managed` descriptor. The parent column belongs in the full child projection but must not be writable through ordinary managed patches. The application resource projection must return exactly the SQL parent as the child's immediate ancestor; the adapter checks this agreement before and after the move. ## Configure authoritative parents [#configure-authoritative-parents] ```ts import type { SqliteManagedMoveDescriptor } from "@rolebook/sharing-sqlite"; const managedMove = { parentIdColumn: "folder_id", parent: { resourceType: "folder", schema: "main", table: "folder", tenantColumn: "tenant_id", idColumn: "id", versionColumn: "version", incarnationColumn: "incarnation", userColumns: ["tenant_id", "id", "version", "incarnation", "enabled"], fields: [{ field: "enabled", column: "enabled", codec: "boolean" }], }, sourceAction: "remove", destinationAction: "accept", } satisfies SqliteManagedMoveDescriptor; ``` Pass `managedMove` to the protected adapter factory beside `managed`. Parent IDs, versions and incarnations use text columns. Map policy attributes explicitly with `text`, `boolean` or `safe-integer` codecs; nullable attributes require `nullable: true`. Enumerate every physical column in order in `userColumns`. Optional `expiresAtColumn` uses `INTEGER` Unix epoch milliseconds. The policy must declare `folder` as a root and the child as its immediate leaf. Parent permissions come from the complete fenced local identity assignments and groups. A parent type with its own Sharing membership configuration is unsupported and rejected. The adapter constructs parent resources directly from SQL, without a caller-provided parent projection. It checks whole-resource `folder:remove` and `folder:accept`; field-only allows do not suffice. Parent condition context contains the tenant ID, without an invented parent sharing revision. ## Move an exact incarnation [#move-an-exact-incarnation] ```ts import { createSqliteProtectedWriteAdapter, type ManagedMoveIntent } from "@rolebook/sharing-sqlite"; declare const adapter: ReturnType; const scoped = adapter.forScope({ tenantId: "namespace_1", actor: { type: "user", id: "alice" } }); const intent = { resource: { type: "document", id: "doc_1" }, action: "move", incarnationId: "document-incarnation", expectedVersion: "1", postVersion: "2", idempotencyKey: "move-doc_1-once", sourceParent: { id: "folder_a", incarnationId: "folder-a-incarnation", version: "1" }, destinationParent: { id: "folder_b", incarnationId: "folder-b-incarnation", version: "3" }, } satisfies ManagedMoveIntent; const outcome = await scoped.withManagedMove(intent); const recovered = await scoped.lookupManagedMoveReceipt(intent); ``` The trusted application chooses the child action mapped to its move command. Caller versions and incarnations are expectations checked against locked authoritative rows, not permission evidence. The child must be allowed both before and after movement. Both parent permissions, unchanged parent snapshots, policy and complete identity/group/absence facts are revalidated. Original parent, identity and membership expiry dependencies survive until the advancing final seal. Validity is established at that seal, not at the physical COMMIT timestamp. The generated conditional update and existing lifecycle bookkeeping run in the same owned transaction. Failed authorization, stale expectations, schema drift or a failed final seal rolls back the move, lifecycle audit, protected receipt and outbox event together. The result records the child version/incarnation/sharing revision and both parent version/incarnation tuples. ## On a hierarchy-enrolled tenant [#on-a-hierarchy-enrolled-tenant] On a tenant whose hierarchy is enrolled (see [inherited access](/docs/sharing/inheritance)), the stored hierarchy, not the application's parent column, is the ancestry Rolebook decides with. Give the protected adapter the deployment's hierarchy control facade and, if the application keeps one, its parent column: ```ts import { createSqliteProtectedWriteAdapter, type ManagedMoveIntent, type SqliteInheritanceControl, } from "@rolebook/sharing-sqlite"; declare const options: Parameters[0]; declare const control: SqliteInheritanceControl; // from createSqliteHierarchyControl const adapter = createSqliteProtectedWriteAdapter({ ...options, hierarchy: { control, parentIdColumn: "folder_id" }, }); const intent = { resource: { type: "folder", id: "folder_7" }, action: "move", incarnationId: "folder-7-incarnation", expectedVersion: "4", postVersion: "5", idempotencyKey: "move-folder_7-once", // A recursive type names its parent type; otherwise it defaults to the declared parent type. sourceParent: { type: "folder", id: "folder_a", incarnationId: "a-incarnation", version: "2" }, destinationParent: { type: "folder", id: "folder_b", incarnationId: "b-incarnation", version: "9" }, } satisfies ManagedMoveIntent; await adapter.forScope({ tenantId: "namespace_1", actor: { type: "user", id: "alice" } }).withManagedMove(intent); ``` The move runs through the hierarchy command engine inside the protected transaction. Without `hierarchy` it refuses `HIERARCHY_UNAVAILABLE` / `enrolled` after the current gate. The flat `managedMove` descriptor is not used on an enrolled tenant. - **Parents** are placed resources of the hierarchy. Each expectation's `version` is the parent's resource version and `incarnationId` its Sharing incarnation, compared on the stored bytes; the source must be the stored parent. A wrong source is rejected before the adapter looks up any parent by the source id the request names, so an existing and an absent id answer the same. A stale target, a stale parent or a wrong source is `PROTECTED_WRITE_POSTCONDITION_FAILED`. An omitted `type` is the moved type's declared parent type. - **Subtrees.** The resource moves with everything below it: its link is re-parented, heights are repaired on the old path and then the new one, and descendants follow the moved link. Stored memberships stay where they are; what changes is the ancestry the subtree inherits from. Members of the destination's ancestors gain inherited access to the moved subtree; the move proof constrains only the actor. - **Refusals** (only after every authorization check, the protected action included, allowed; with no effect): `PROTECTED_WRITE_REFUSED` with `hierarchy_cycle` (the destination is the resource or below it), `ancestry_cap` (the subtree would end below 16 ancestors), `hierarchy_edge_refused` (the policy does not allow that parent type) or `hierarchy_exists` (the destination is the current parent). A parent `type` outside the hierarchy command map is refused `hierarchy_edge_refused` before authorization: that answer depends only on the request and the configuration. - **Authorization.** The protected action on the resource before the move and again on its new chain; the type's `move` and `management.members` on the resource; `removeChild` on the source and `addChild` on the destination, each with that parent's `management.members`; and the move proof: for every permission of every type at or below the moved type, the actor must already hold an unrestricted allow at a common ancestor of both positions (with no common ancestor, also the bootstrap `rootPlacement`), and no actor role may carry a deny for those permissions. A move can never extend the actor's authority over the subtree. Any denial is `PROTECTED_WRITE_DENIED`. - **Effects and receipt.** The business row's version advances to `postVersion` (and `parentIdColumn` to the destination); key, incarnation, sharing revision, owner and members are unchanged. The receipt records metadata version 2 with the pre-move inherited evidence; the result and the `protected.move.committed` event name both parents and the unchanged sharing revision. Moves never cross tenants and never move to or from the root position (use `structure.move` of the control facade for that). - **One final seal** covers the local identity, the inherited memberships every decision relied on, and the pre- and post-move evidence. A `SQLITE_BUSY` reruns the whole attempt with fresh capture; exhaustion is `HIERARCHY_UNAVAILABLE` / `serialization_conflict`. ## Recovery and boundaries [#recovery-and-boundaries] The `managed.move.v1` receipt binds the complete intent, configured mappings and authority epoch. A changed intent with the same key conflicts. Exact replay recovers the historical receipt before current authorization or schema validation and never executes a second move. After an uncertain COMMIT use the exact-intent lookup; no receipt is not proof that an in-flight commit aborted. Historical receipt recovery never grants access to a replacement incarnation. Only one child, one namespace, one mapped root-parent table and one adapter-owned local transaction are supported. IDs are opaque within their resource types: equal child and parent IDs do not form a hierarchy cycle because these are distinct types. Same source/destination parent IDs are rejected. There is no create, subtree or multi-level move, batch move, cross-tenant/cross-adapter operation, remote authority, parent Sharing membership source or public consistency token in this API. Ordinary permanent tables and exact projections are required. Existing managed safeguards reject unsupported triggers, rules, generated columns, RLS, inheritance, partitioning, temporary shadows and cascade graphs where applicable. All participating writers must honor the identity/revision contract. SQL mapping is trusted server configuration; it is not accepted from the request. Before authorization, the move path compares driver-decoded parent and child TEXT against exact SQL bytes. A lossy driver value (including libSQL truncation at an embedded NUL) fails closed; the adapter never authorizes a shortened prefix. The common managed loader also applies this guard to updates, batches and deletion pre-state. SQLite validates encoded SQL bytes before raw driver reads using the database encoding. # SQLite migrations (/docs/sharing-sqlite/migrations) > The migration runner, drift policy, rollback, upgrades, and policy-store tables on SQLite. SQLite has no procedural SQL, so migrations are a function: `applyResourceSharingMigrations(executor, descriptor, retry?)` validates and applies the schema in **one** retried `BEGIN IMMEDIATE` transaction. SQLite DDL is transactional, so a failed check leaves the database exactly as it was. Run it on every deploy, before serving: there is no list of applied steps a later release could skip. ```ts import { applyPolicyStoreMigrations, applyResourceSharingMigrations, type ParameterizedSqliteExecutor, type SqliteResourceDescriptor, } from "@rolebook/sharing-sqlite"; declare const executor: ParameterizedSqliteExecutor; declare const projectTable: SqliteResourceDescriptor; await applyResourceSharingMigrations(executor, projectTable); await applyPolicyStoreMigrations(executor); // only for versioned sharing ``` `createResourceSharingMigrations(descriptor)` returns the DDL a fresh database receives, one statement per step, for review and schema snapshots. Do not run those statements yourself: `CREATE TABLE IF NOT EXISTS` would silently reuse a drifted table. ## What the runner does [#what-the-runner-does] 1. Requires the application table to be an ordinary table in `main` with `TEXT` tenant and ID columns and the resource-version column. 2. Binds `sharingTablePrefix` to this exact descriptor in `rolebook_sharing_descriptor_binding`. A prefix bound to another descriptor is rejected. 3. Reuses an existing unique, non-partial, BINARY-collated index on exactly `(tenant, id)` (a primary key qualifies) or creates one. 4. Validates every existing sharing table and the key guard, adds missing columns (the application's `rolebook_sharing_revision`, and columns added by later releases), creates missing tables, indexes, and the key guard, then validates everything again. All sharing tables are `STRICT`. Timestamps are `INTEGER` milliseconds since the Unix epoch. Column collations are probed once per changed table definition and cached in the binding table; clear its `collation_validation` entry to force a full probe. ## Drift policy [#drift-policy] Reruns verify existing objects and fail closed instead of reusing a drifted one: table kind (must be `STRICT`), columns and their types and nullability, BINARY collations on every `TEXT` column, primary keys, lookup indexes, the invitation recipient check, live foreign keys (`(tenant_id, resource_id)` to `(tenant, id)` with `ON DELETE CASCADE ON UPDATE CASCADE`), the revision column (`INTEGER NOT NULL` with a constant zero default), and the key guard trigger. Missing indexes and a missing guard are created. SQLite cannot alter a constraint in place, so repairing drift means rebuilding the table the documented SQLite way (create, copy, drop, rename) before rerunning. Drop `_rolebook_key_guard` first, in the same transaction as the rebuild, and rerun the migration right after: until it runs, deletions through the adapter refuse to start and nothing guards key changes. ## Upgrades handled by reruns [#upgrades-handled-by-reruns] A rerun adds, in place and without a rebuild: - `expires_at INTEGER` on the member table and `membership_expires_at INTEGER` on the invitation table (existing rows stay permanent); - `incarnation_id TEXT` on the owner and audit tables, its index, an identifier for every owner row, and (once) the attribution of earlier history by the lifecycle events of the time; - the key guard trigger and the revision-floor table, backfilled once; - `expected_sharing_revision INTEGER` on the lifecycle table; - `created_at INTEGER` on the idempotency table, stamping existing rows with the run's instant; - `policy_version` on the idempotency table, for versioned replays. A column already present with another type, or declared `NOT NULL`, is rejected before any DDL. After the key-guard upgrade, application code that changes an initialized resource's tenant or ID directly fails. The SQLite adapter always names `created_at` when it writes an idempotency record, so migrate before serving this release. Rolling upgrades: do not issue expiring grants or invitations until every instance runs a release with expiry. An older instance writes owner and audit rows without an incarnation identifier; its audit rows are never listed, and the next write through the new release (or a migration rerun) gives such an owner row an identifier. ## Rollback [#rollback] `applyResourceSharingRollbackMigrations(executor, descriptor, options?, retry?)` checks the retained descriptor registry, then drops sharing-owned state in one transaction: the key guard first, then the revision-floor, lifecycle, idempotency, invitation, member, and owner tables. `createResourceSharingRollbackMigrations(descriptor, options?)` lists those steps with their data loss. Audit history is kept unless `{ dropAudit: true }`, and the registry row is always kept, so retained audit history can never be rebound to another table. The application's revision column and `(tenant, id)` index are never dropped. Freeze sharing writes, export the sharing data, restore the old store, and verify access-list parity before running it. ## Policy-store tables [#policy-store-tables] `applyPolicyStoreMigrations(executor, { tablePrefix?, retry? })` creates the policy-version, activation, active-pointer, tenant-role, tenant-role revision, and policy-audit tables in one `BEGIN IMMEDIATE` transaction and fails closed on drift. `createPolicyStoreMigrations()` lists the DDL, `createPolicyStoreRollbackMigrations()` the drops, and `policyStoreTables(prefix)` the names. The default prefix is `rolebook`. Keep them in the same database file as the sharing tables. They also create a permanent policy header (protocol version, the store identity `["main", prefix]` and a catalog generation) and an append-only hierarchy catalog in `main`. Every store operation and the policy fence check the header first and refuse a `temp` shadow of any policy table; a store migrated before this release answers `HIERARCHY_UNAVAILABLE` (`policy_profile_mismatch`) until `applyPolicyStoreMigrations` runs again. An empty catalog is the normal flat state. `applyPolicyStoreRollbackMigrations(executor)` runs the rollback in one transaction; its first step refuses while the catalog holds any registered hierarchy descriptor. [`applyPolicyCatalogRegistration()`](/docs/sharing-sqlite/api#applypolicycatalogregistration) appends control prefixes to that catalog. [`hierarchyControlTables()`](/docs/sharing-sqlite/api#hierarchycontroltables) names the control tables, and [`createHierarchyControlMigrations()`](/docs/sharing-sqlite/api#createhierarchycontrolmigrations) installs them. [`createSqliteGroupGraphControl()`](/docs/sharing-sqlite/api#createsqlitegroupgraphcontrol) builds the graph commands for that prefix and stores the configuration as `sha256:` plus 64 hexadecimal characters. # SQLite concurrency, fences, and lifecycle (/docs/sharing-sqlite/operations) > BEGIN IMMEDIATE, busy retries, identity fences, teams, initialization, deletes, and moves on SQLite. ## Concurrency model [#concurrency-model] SQLite has one writer per database file. Every sharing mutation, initialization, and lifecycle transaction runs in `BEGIN IMMEDIATE`. Inside it the adapter re-reads the resource row, compares the expected resource version and sharing revision, runs the identity fences against the authoritative rows, writes, increments the revision with an exact compare, records the idempotency key and fingerprint, and appends the audit event. A mutation commits completely or not at all. Reads (`readAccess`, `readAccessBatch`) run in a deferred transaction: in WAL mode one consistent snapshot that never blocks a writer. `SQLITE_BUSY` (and its extended codes, plus `SQLITE_LOCKED_SHAREDCACHE`) means another connection holds the lock. The adapter retries the whole unit of work: `busyRetry.attempts` (default 10, at most 100, including the first) with capped, fully jittered backoff of 0 to `min(100, 5 x 2^(retry - 1))` ms; `backoffMs(retry)` (0 to 1,000 ms) and `wait(ms)` replace the schedule and the timer. `isRetryableBusyError()` recognizes bun:sqlite, better-sqlite3, libSQL, and node:sqlite error shapes, also wrapped in a `cause`. Retries are safe because every mutation is idempotent. Limits of the model: - Throughput is one writer per file. Keep transactions short and slow work (network calls, token delivery) outside them. - The identity fence holds only for identity tables in the same database file, or in a schema `ATTACH`ed on every writing connection. A remote identity API cannot be fenced; use subject-bound invitations. - Writers outside SQLite's locking (another file copy, a backup restore, a sync engine rewriting rows) are not serialized. - Without a `clock`, membership expiry uses the adapter process's clock and invitation expiry the SQLite host's `'now'`. | Guarantee | PostgreSQL | SQLite | | --- | --- | --- | | Mutation isolation | `SERIALIZABLE` plus row locks | `BEGIN IMMEDIATE`: one database-wide writer | | Retried errors | `40001`, `40P01`; 3 attempts, 50 ms cap | `SQLITE_BUSY*`, `SQLITE_LOCKED_SHAREDCACHE`; 10 attempts, 100 ms cap | | Remote server | supported | refused | | Resource ID types | `text` or `uuid` | `TEXT` only, BINARY collation | | Key changes outside a move | refused by `ON UPDATE RESTRICT` (`23001`) | refused by the key guard trigger | | Foreign keys | always enforced | per connection; writes refuse to run without them | | `lower_trim` email | Unicode-aware `LOWER` | ASCII-only `lower()` | ## Fences [#fences] The SQLite fences mirror the PostgreSQL ones and run under the write lock: ```ts import { createSqliteEmailInvitationRecipientFence, createSqliteMembershipEligibilityFence, createSqliteWorkspaceRoleAuthorizationFactFence, } from "@rolebook/sharing-sqlite"; import { BETTER_AUTH_WORKSPACE_MEMBER_AUTHORIZATION_FACT } from "@rolebook/sharing-better-auth"; const lockEligibleSubjects = createSqliteMembershipEligibilityFence({ table: "member", tenantColumn: "organization_id", subjectIdColumn: "user_id", }); const lockInvitationRecipient = createSqliteEmailInvitationRecipientFence({ membershipTable: "member", membershipTenantColumn: "organization_id", membershipSubjectIdColumn: "user_id", userTable: "user", userIdColumn: "id", userEmailColumn: "email", userEmailVerifiedColumn: "email_verified", }); const revalidateAuthorizationFacts = createSqliteWorkspaceRoleAuthorizationFactFence({ table: "member", tenantColumn: "organization_id", subjectIdColumn: "user_id", factType: BETTER_AUTH_WORKSPACE_MEMBER_AUTHORIZATION_FACT, memberIdColumn: "id", roleColumn: "role", }); ``` Every shipped fence matches identity rows in SQL and then compares the matched columns, read back as text, exactly in JavaScript: a `TEXT COLLATE NOCASE` or INTEGER identity column would otherwise match another spelling. A second matching row, a `NULL`, or a non-string value fails closed. The email fence's `lower_trim` uses SQLite's `lower(trim(...))`, which folds only ASCII letters: store addresses normalized, or use `exact`, when they may contain other letters. `revalidateAuthorizationFacts` decides the mutation after the eligibility fence: `true` proceeds, `"conflict"` rolls back and lets the sharing module re-authorize, anything else is `identity_ineligible`. Without it, a mutation carrying authorization facts fails closed and the adapter warns once. ### Teams on SQLite [#teams-on-sqlite] `@rolebook/teams` ships team fences for PostgreSQL only. With `withTeams()` on SQLite, configure team-aware fences that read your team tables in the adapter's transaction: - `lockEligibleSubjects` must verify that a team grant target is a team of the tenant and refuse any team listed in `ownerCandidates`; - `revalidateAuthorizationFacts` must check that every `rolebook.teams.team-member.v1` fact still matches a team-membership row, and that every `rolebook.teams.team-set.v1` fact equals `encodeTeamSet()` of the subject's teams read again, returning `"conflict"` when it does not. Membership facts whose subject has no team-set fact must be refused. The Teams package's SQLite contract suite (`packages/teams/tests/sqlite-contract.integration.test.ts`) shows SQLite equivalents. Run [`sharingTeamsContract`](/docs/sharing-testkit#teams-contract) against yours. Nested lineage is separate from those flat fences. Configure it with [`@rolebook/teams/sqlite`](/docs/teams/api#rolebookteamssqlite) and the adapter's `groupGraph` option, as in the [teams guide](/docs/teams#nested-lineage). Flat `withTeams()` stays the direct-membership wrapper. ## Lifecycle [#lifecycle] Create the application row and its owner in the same `BEGIN IMMEDIATE` transaction: ```ts import { withImmediateTransaction, type ParameterizedSqliteExecutor, type SqliteSharingAdapter } from "@rolebook/sharing-sqlite"; declare const executor: ParameterizedSqliteExecutor; declare const projectAdapter: SqliteSharingAdapter; const user = { type: "user", id: "user_123" }; const result = await withImmediateTransaction(executor, async (transaction) => { await transaction.query("INSERT INTO project (workspace_id, id, title, version) VALUES (?, ?, ?, 1)", [ "ws_456", "project_1", "Q3 launch", ]); return projectAdapter.initializeResourceInTransaction(transaction, { tenantId: "ws_456", resourceId: "project_1", owner: user, actor: user, occurredAt: new Date(), }); }); ``` `initializeResource()` opens its own transaction for existing resources. Results, the owner checks, and the revision-floor rule are those of the [PostgreSQL adapter](/docs/sharing-postgres/lifecycle#initializing-a-resource); the error is `SqliteLifecycleConflictError`. `asImmediateSqliteTransaction()` asserts that a transaction your driver opened is `BEGIN IMMEDIATE`. Deletes and moves go through `withLifecycleTransaction()` and `resourceDeletedInTransaction()` or `resourceMovedInTransaction()`, with exactly the PostgreSQL semantics: the callback performs a conditional change with the pre-version, a cross-tenant move keeps only the destination-eligible owner, a non-`applied` result or a failed postcondition throws `SqliteLifecycleConflictError` and marks the transaction rollback-only, and the standalone `resourceDeleted()` and `resourceMoved()` return `"unsupported"`. Callbacks must decide on `RETURNING` rows rather than change counts, because drivers disagree on whether change counts include cascades. Transactions handed to callbacks refuse transaction-control statements (`BEGIN`, `COMMIT`, `ROLLBACK`, `SAVEPOINT`, `RELEASE`). ## Reads, cursors, and audit [#reads-cursors-and-audit] Candidate cursors are ordered by the ID column with `COLLATE BINARY`; a cursor must be a non-empty string of at most 128 characters, or `listCandidates()` throws `InvalidSqliteCursorError`. IDs that cannot be issued as cursors (non-`TEXT` values, empty IDs, IDs over 128 UTF-16 units) are filtered in SQL before paging. No read uses `*`; without `resourceColumns`, an application-table read lists the table's current columns from the catalog in the same transaction. Audit pages, incarnations, event IDs, and row errors follow the PostgreSQL rules, with `InvalidSqliteAuditCursorError` for a refused audit cursor and `SqliteSharingRowError` for a row that does not decode. Pruning (`pruneSettledRecords()`) deletes each kind in its own `BEGIN IMMEDIATE` transaction. # Protected and managed updates (/docs/sharing-sqlite/protected-updates) > Local SQLite authorization, application updates and durable recovery in one owned transaction. `createSqliteProtectedWriteAdapter()` binds the original SQLite sharing adapter, VersionedSharing instance, policy store and checked local SQLite executor. Its scoped API supports a raw resource/action callback and a managed field patch. Both commit the application change, durable receipt and outbox event atomically in the same local database. This slice supports local SQLite through `createBunSqliteExecutor()` from `@rolebook/sharing-sqlite/bun` and `createLibsqlExecutor()` from `@rolebook/sharing-sqlite/libsql` with a local file-backed client. libSQL `:memory:` is unsupported because its transaction connection lifecycle does not preserve one database across transactions. Remote libSQL transports and caller-owned transactions are not accepted as equivalent authority. The worker-backed `createBunSqliteQueryExecutor()` from `@rolebook/sharing-sqlite/bun-query`, which [named authorized queries](/docs/sharing/authorized-queries) require, is accepted too; see [on the worker executor](#on-the-worker-executor) for how its lifetime, `COMMIT` outcome and receipts behave. Executors are recognised by the package's own record of the executors it made, never by their shape. Python, Go and Rust Sharing HTTP requests do not extend this transaction across processes. ## Bind local authority [#bind-local-authority] Use one checked executor for the original resource adapter and policy store. Configure the resource adapter's eligibility and authorization-fact fences with `createSqliteLocalIdentityProjection()`, and supply its `identity` to the protected adapter. The application-owned projection must represent the complete local identity, assignments, groups, attributes and their absence. Every writer updates the same revisioned row. This is local authoritative state, not a claim about an external identity provider's freshness. ```ts group=sqlite-managed import type { SharingResourceConfigurations, VersionedResourceSharing } from "@rolebook/sharing"; import { createSqliteLocalIdentityProjection, type SqliteSharingAdapter, type ParameterizedSqliteExecutor, applyProtectedWriteMigrations, createSqliteProtectedWriteAdapter, } from "@rolebook/sharing-sqlite"; declare const executor: ParameterizedSqliteExecutor; declare const sharingAdapter: SqliteSharingAdapter; declare const versionedSharing: VersionedResourceSharing; const projection = createSqliteLocalIdentityProjection({table:"authz_identity_projection"}); await applyProtectedWriteMigrations(executor, { tablePrefix: "app_authorization" }); const protectedAdapter = createSqliteProtectedWriteAdapter({ adapter: sharingAdapter, sharing: versionedSharing, identity: projection.identity, environmentId: "production", authorityEpoch: "installation-epoch-1", journalPrefix: "app_authorization", maxLifetimeMs: 5_000, managed: { target: { schema: "main", table: "document", userColumns: ["tenant_id", "id", "title", "visibility", "version", "rolebook_sharing_revision"], }, fields: [ { field: "title", column: "title", codec: "text" }, { field: "visibility", column: "visibility", codec: "text" }, ], }, }); ``` The example column list must match your table's actual catalog order, including migration-added columns. The adapter verifies the complete schema inside the owned transaction. Supported managed codecs are text, boolean and safe integer, with explicit nullable mappings. The actual SQLite storage class and value must match; affinity coercion is not permission to change a payload's meaning. Field names are flat and mappings cannot target identity/version/sharing columns. ## Choose the update contract [#choose-the-update-contract] `scoped.withAuthorizedTransaction(intent, callback)` requires a resource-wide action allow. The trusted callback uses `guard.executor` and advances to `postVersion`. Its opaque SQL is not field-mediated, even when the adapter also has a managed mapping. It must retain incarnation, owner, ancestry and sharing authority and obey participating writer contracts. `scoped.withManagedUpdate(intent)` has no SQL callback. It applies a captured patch with a compare-and-set on the expected version: ```ts group=sqlite-managed const scoped = protectedAdapter.forScope({ tenantId: "workspace_1", actor: { type: "user", id: "user_123" }, }); declare const incarnationId: string; declare const currentVersion: string; declare const nextVersion: string; const intent = { resource: { type: "document", id: "document_1" }, action: "update", incarnationId, expectedVersion: currentVersion, postVersion: nextVersion, idempotencyKey: "rename-document_1-once", patch: { title: "New title" }, }; const result = await scoped.withManagedUpdate(intent); ``` Every declared field must pass canonical policy checks against both the authoritative before row and a separate after-state SELECT. Field-only grants can allow a managed patch; a deny covering any declared field rejects the entire patch. The actual stored patch values, full target row change set and resulting version are checked. Read-only policy attributes come from the same trusted `resourceFromRow` projection as writable attributes. Normalize SQLite boolean 0/1 values explicitly in that projection. Unmapped integers outside JavaScript's safe range are supplied as exact decimal text instead of rounded numbers; mapped safe-integer values outside that range are rejected. Versions are opaque tokens, separate from the lifecycle incarnation. The expected version must match and the supplied post-version must be nonempty and different. No global ordering or protection against application version reuse is implied. Empty patches are invalid. An allowed all-no-op patch still authorizes every declared field, advances the version and records a receipt. ## SQLite transaction and clock semantics [#sqlite-transaction-and-clock-semantics] The adapter acquires `BEGIN IMMEDIATE` before reading authority. SQLite serializes writers at the database level; it does not provide PostgreSQL's row-lock concurrency. Independent connections may receive `SQLITE_BUSY` before application work. Neither raw callbacks nor managed updates are automatically retried. Bun leases its connection across asynchronous work; local libSQL owns a separate transaction connection. Both reject callback escape through the outer executor and close the transaction handle before commit. libSQL session-local TEMP objects are not a durable configuration mechanism. File-backed databases require WAL, foreign-key enforcement, full synchronous durability and bounded contention settings. Protected writes use the `main` database; attached databases and temporary targets are outside this slice. Durable journal operations explicitly address `main`, so temporary table names cannot divert a receipt or event. Expiry evidence uses validated integer epoch milliseconds and database-derived load/seal times. Equal expiry denies. The seal may share a millisecond with the load, but clock regression fails closed. The SQLite clock is millisecond resolution with no PostgreSQL microsecond parity claim. Synchronous SQLite statements cannot be preempted by a JavaScript timer: lifetime sealing prevents a late authorization from committing, while callback cancellation is cooperative. ## On the worker executor [#on-the-worker-executor] The worker executor runs each connection in its own worker thread. Build the resource adapter, the policy store and the protected-write adapter on the same executor object; a copy, a wrapper or a method taken from it is refused like any unchecked executor. A protected run is one `BEGIN IMMEDIATE` transaction on one worker. Authorization reads its facts inside that transaction, so a revocation committed by another worker or another process before `BEGIN IMMEDIATE` succeeds is seen. Inside the run the outer executor refuses calls, and a callback handle kept after the run rejects every call without reaching a worker. **Lifetime.** `maxLifetimeMs` runs from the opening of the transaction until `COMMIT` is sent to the worker. Because the application thread stays responsive while the worker runs SQL, the lifetime can elapse while a statement is running. When it elapses before `COMMIT` has been sent, `guard.signal` aborts, no further statement of the run is sent, and the transaction never commits. A running SQLite statement cannot be interrupted: the run waits for it to return, rolls the transaction back and only then rejects with `ProtectedWriteTimeoutError`, so that error can arrive later than `maxLifetimeMs` by the length of the running statement. The worker returns to the pool only once the rollback is confirmed; otherwise it is retired, which drops its connection and the transaction with it. **`COMMIT`.** Once `COMMIT` has been sent the lifetime no longer applies: - `COMMIT` succeeded: the run returns its normal result, even if `maxLifetimeMs` passed meanwhile; - `COMMIT` failed and the transaction is still open: it is rolled back and the failure is reported; - the worker was lost or the executor closed while `COMMIT` was in flight, or SQLite ended the transaction while `COMMIT` failed: `SqliteCommitOutcomeUnknownError` (`COMMIT_OUTCOME_UNKNOWN`), never a timeout, a denial or a claim of rollback. The expiry check and the dispatch of `COMMIT` are one step: either the lifetime runs out first and `COMMIT` is never sent, or `COMMIT` is sent and the lifetime can no longer settle the call. There is no commit timeout. A running SQLite statement cannot be interrupted, so a `COMMIT` that never returns leaves the call pending and its worker occupied until it returns, the worker is lost or the executor is closed. Resolve an unknown outcome after the fact with the exact-intent receipt lookup; do not assume either outcome. Running the same intent again with the same idempotency key is safe: it replays a committed receipt and runs the work only if nothing committed. **Receipts.** The application change, its receipt and its outbox event are written in one transaction and are all present or all absent after any failure, including the loss of the worker. A lookup that finds no receipt is not proof of a rollback while the `COMMIT` may still be in flight: a lookup can run on another worker when one is free, and then answer before the run that writes the receipt has finished. With `maxConnections: 1` it waits for the run holding the only connection, its `COMMIT` included. **Other failures.** A request or response over the executor's 2 MiB message cap inside a run fails the run with `QUERY_UNAVAILABLE` and rolls it back. If `ROLLBACK` fails or the worker dies before or during it, the caller receives the original error, the worker is retired and nothing commits. `executor.close()` during a run fails a run whose `COMMIT` was not sent, which never commits, and reports `SqliteCommitOutcomeUnknownError` for a run whose `COMMIT` was in flight. **Named queries.** A protected write waits for a free worker in arrival order, like any ordinary work, and holds it until its `COMMIT` ends. Query pages never wait: while every worker is busy, for example with long protected writes, a page answers `QUERY_UNAVAILABLE`. Size `maxConnections` for the writes and other work you expect at once plus the pages that must still be answered, and keep protected callbacks short. A page whose lease opened before a protected write committed keeps its snapshot and does not see the write. **Parity.** A protected run gives the same result here as on `createBunSqliteExecutor()` when every request and response fits the 2 MiB message cap and the result does not depend on the order in which concurrent runs obtain SQLite's write lock. The two differences: - a run with a request or response over 2 MiB fails and rolls back here, and would succeed on the synchronous executor; - one synchronous connection queues runs, while separate workers contend for SQLite's single write lock. Protected writes require `busy_timeout=0`, so a run whose `BEGIN IMMEDIATE` meets the lock held by another worker or connection fails at once with that `SQLITE_BUSY` error (`isRetryableBusyError()` recognises it). It fails whole: its callback or managed operation has not started and nothing of it is written. Protected runs are not retried automatically; retry with the same intent. With `maxConnections: 1` an executor's protected writes queue for its one worker in arrival order and never contend with each other; with more connections they can. Every worker connection is set to `synchronous=FULL` when its worker starts, replacements included, and the start verifies it with `busy_timeout=0`, foreign keys, WAL and UTF-8. Before its `BEGIN IMMEDIATE` every protected run reads `synchronous` and `busy_timeout` on the connection that will run it and fails with `CONSISTENCY_UNAVAILABLE`, without opening a transaction, unless they are FULL and 0. A setting changed through the executor's `query()` reaches one pooled connection only. With `synchronous=FULL` every commit through the worker executor waits for its WAL write to reach the disk. ## Recovery and schema boundaries [#recovery-and-schema-boundaries] Use `lookupReceipt(rawIntent)` or `lookupManagedReceipt(managedIntent)` after an uncertain commit. A matching durable receipt proves the recorded outcome. Absence alone is not permission to blindly replay an uncertain operation. An exact committed replay returns its stored receipt; a changed mapping or intent under the same key conflicts. `createSqliteProtectedWriteOutbox()` provides environment-bound claims and lease acknowledgements. Delivery is at least once; consumers deduplicate stable event IDs. Leases use database time. Environment identity is stored data and is copied when the database file is copied. Managed targets are ordinary permanent tables. The exact first-party key guard installed by Sharing migrations is supported; a same-name altered guard or another application/temporary trigger is rejected. Generated and automatically maintained columns are unsupported. Only version is exempt from the unchanged-column rule, and it must equal the declared post-version. The physical-row check proves nothing about other rows, tables or deferred triggers. Trusted schema and source-writer contracts remain required; this API is not an arbitrary SQL sandbox. ## Atomic managed batches [#atomic-managed-batches] `withManagedUpdates()` applies 1–32 updates to distinct existing resources through the same configured adapter and tenant scope. Each item uses the same field, incarnation and version checks as a single managed update. The batch shares one transaction and lifetime; final persisted-state and authority checks run after the last update. Any failure rolls back every update, the single receipt and its single outbox event. There is no per-item partial success. ```ts group=sqlite-managed import type { ManagedUpdateBatchIntent } from "@rolebook/sharing-sqlite"; declare const secondIncarnationId: string; declare const secondCurrentVersion: string; declare const secondNextVersion: string; const batchIntent: ManagedUpdateBatchIntent = { idempotencyKey: "rename-two-documents-once", updates: [ { resource: { type: "document", id: "document_1" }, action: "update", incarnationId, expectedVersion: currentVersion, postVersion: nextVersion, patch: { title: "First title" }, }, { resource: { type: "document", id: "document_2" }, action: "update", incarnationId: secondIncarnationId, expectedVersion: secondCurrentVersion, postVersion: secondNextVersion, patch: { title: "Second title" }, }, ], }; const batchOutcome = await scoped.withManagedUpdates(batchIntent); // After an uncertain commit, reconcile using the original complete batch intent: const recoveredBatch = await scoped.lookupManagedUpdatesReceipt(batchIntent); ``` Choose either the single-update or batch example for a given set of expected versions; do not apply the preceding single update first and then reuse its stale expected version in this batch. The receipt result contains `updates` entries with `resource` and resulting `version`, ordered by resource ID using ordinary UTF-16 comparison. One environment/tenant/actor-bound key covers the entire batch. Input order is canonicalized; reordered identical items replay the original receipt. A changed item, mapping or complete intent under that key conflicts. Missing receipt evidence does not prove rollback. `schemaVersion` is the stored metadata version, not a journal-table schema. A flat batch stays version 1. An enrolled batch of one update stays version 2. With admission `protected_batch_receipt_floor` 2, the default for every tenant and for an upgraded row, a multi-target enrolled batch stores version 2 from the UTF-16-first target. That one `hierarchy` block is evidence for its `links[0]` target only, not for the other result updates. Floor 3, set on the admission row after decoders and old writers are drained, records version 3: one `targets` entry per result update, each `hierarchy` block evidence for that target and not a capability. There is no top-level `hierarchy` and no separate control command. Select the entry whose resource matches the result update. Apply the admission migration first: a missing column is `profile_mismatch`. Running it again leaves existing rows at floor 2. An old binary cannot enforce a column it does not know. `SQLITE_BUSY` while opening an enrolled batch is `HIERARCHY_UNAVAILABLE` / `serialization_conflict`. A floor outside 2 or 3, or a floor that changes at the final fence, is `HIERARCHY_UNAVAILABLE` / `protocol_floor`. PostgreSQL acquires resource locks in deterministic resource-ID order; SQLite retains its single-writer transaction behavior. No automatic retry, cross-adapter transaction, create, delete or move operation is added. The existing local-authority and supported-driver limits still apply. ## Scoped outcome lookup and worker recovery [#scoped-outcome-lookup-and-worker-recovery] For a server route that already knows the authenticated actor, tenant and original idempotency key, use the receipt factory with the opaque route from the protected-write adapter: ```ts import { createSqliteProtectedWriteAdapter, createSqliteProtectedWriteReceipts, createSqliteProtectedWriteOutbox, type ParameterizedSqliteExecutor, } from "@rolebook/sharing-sqlite"; declare const journalExecutor: ParameterizedSqliteExecutor; declare const protectedWrites: ReturnType; // These values must come from authenticated server context, after application access checks. declare const authenticatedScope: { tenantId: string; actor: { type: string; id: string }; }; const receipts = createSqliteProtectedWriteReceipts({ receiptRoute: protectedWrites.receiptRoute(), }); const committedOutcome = await receipts.forScope(authenticatedScope).lookup({ idempotencyKey: "rename-document_1-once", }); const worker = createSqliteProtectedWriteOutbox({ executor: journalExecutor, tablePrefix: "app_authorization", environmentId: "production", }); const pending = await worker.inspectPending({ limit: 100 }); declare const deliver: (event: { eventId: string; kind: string; payload: unknown }) => Promise; for (const event of await worker.claim({ limit: 1, leaseMs: 30_000 })) { try { await deliver(event); // Destination durably accepts and deduplicates by environment/event ID. } catch { await worker.retry(event.deliveryToken, { delayMs: 5_000 }); continue; } const acknowledged = await worker.acknowledge(event.deliveryToken); // false means the lease was lost; delivery may be repeated. } ``` Key-only lookup reports the original committed result; it does not compare a new proposed payload. An empty, oversized, or NUL-bearing idempotency key is rejected before a read opens. An enrolled tenant passes the current gate in that checked read before any journal access: the adapter port, captured authority epoch, current admission and bootstrap, and whether this resource type is enrolled. A successful gate returns the stored outcome verbatim, or `undefined` when no row matches. A refused gate — missing port, epoch mismatch, quarantine, corrupt admission, or a type that is not enrolled — throws and does not read the journal, so the refusal discloses neither a receipt nor a miss. Use `lookupReceipt`, `lookupManagedReceipt` or `lookupManagedUpdatesReceipt` with the exact original intent for retry validation. `undefined` after a successful gate means not observed, not proof that an uncertain transaction cannot still commit, in particular while its `COMMIT` may still be in flight. Never mint a new key solely because lookup is empty. Inspection is an oldest-pending snapshot (limit 1–1000), including leased rows and excluding delivered rows. It does not decode payloads, so a poison payload remains visible. Retry requires the current unexpired claim and a delay of 0–300000ms; it immediately invalidates the old token. Stale, expired, delivered and foreign-environment tokens return false. Generation counters also advance on retry, so they are not exact attempt counts. Restrict these operations to trusted workers/operators; they do not authenticate callers. A deferred retry appears as `leased` until its database deadline, even though the previous worker has released ownership. Delivery is at least once. ACK only after durable acceptance; destination effects must be idempotent by `(environmentId, eventId)`. Executor errors propagate. If a worker crashes or cannot release its lease, normal claim recovers after expiry. Size batches and leases to finish delivery before expiry; lease renewal is not provided. Do not hold business transactions during delivery. Receipts and all outbox rows are retained indefinitely, including delivered rows. Explicit quarantine/requeue is described below; deletion, scheduler and HTTP/console routes remain outside this API. Permanent failures remain pending unless explicitly quarantined. Exhausted generation counters remain visible but cannot be reclaimed; operators must investigate rather than reset fencing history. ## Quarantine and explicit operator recovery [#quarantine-and-explicit-operator-recovery] Stop and drain all old outbox workers before running the explicit protected-write migrations, then start only upgraded workers. The additive `_dead_v1` table leaves the original event and receipt schemas intact. Old workers do not consult quarantine state, so mixed-version delivery or rollback to old workers with active quarantines is unsupported. New worker operations fail closed when the side table is missing. Apply the existing migration API through the application's migration owner; construction does not migrate. PostgreSQL's generated migration step now ends in `:v1:quarantine-v1:relation-admission-v1:operator-history-v1`; SQLite validates and adds the new side-table definition. The environment-wide operator below must be authenticated and authorized by your application. This uses an exact-event inspection lease so even a payload that normal claim cannot decode can be quarantined. It never steals an existing lease; allow that lease to expire first. ```ts import { createSqliteProtectedWriteOutbox, type ParameterizedSqliteExecutor } from "@rolebook/sharing-sqlite"; declare const executor: ParameterizedSqliteExecutor; const operator = createSqliteProtectedWriteOutbox({ executor, tablePrefix: "app_authorization", environmentId: "production", }); declare const eventId: string; const lease = await operator.claimForInspection({ eventId, leaseMs: 30_000 }); if (lease) { const quarantine = await operator.quarantine(lease, { reason: "destination-rejected-event" }); // undefined means the lease is no longer eligible; inspect current state before proceeding. } const deadLetters = await operator.inspectDeadLetters({ limit: 100 }); // In a separate authorized recovery action, after resolving the cause: declare const approvedForRequeue: boolean; const selected = deadLetters.find((event) => event.eventId === eventId); if (approvedForRequeue && selected) { const requeued = await operator.requeue(selected.quarantineToken); // true makes the original event available for ordinary claim; it does not deliver it. } ``` Quarantine requires a current unexpired token and a nonblank 1–1024-character reason with no NUL; it advances the generation, clears the lease and persists the quarantine atomically. Never put credentials or whole payloads in the reason. Requeue requires the exact active quarantine token and advances the generation again. Old ACK, retry and operator tokens cannot act on later state. Foreign-environment tokens are rejected. Worker limits remain 1–1000 records and 1–300000ms leases. Quarantine reserves headroom for requeue and a subsequent claim; generations at or above 9223372036854775805 cannot be quarantined. Counters are never reset or wrapped. Dead-letter inspection omits payload decoding and returns immutable identity, kind, reason, time and token. It is a bounded oldest-active snapshot, not pagination or an authentication boundary. The side row retains the latest quarantine/requeue state per event; it is not a full history of operator actions; the separate [history log](#retained-operator-action-history) records successful post-upgrade transitions. Pending inspection excludes quarantined events; use dead-letter inspection for them. Neither operation changes or deletes the original payload or receipt. A crash before quarantine leaves ordinary lease expiry/reclaim in effect. A committed quarantine persists until explicit requeue; inspection recovers its token after a lost acknowledgment. An absent active quarantine is not proof of delivery. Serialization/busy/connection failures propagate without automatic replay. PostgreSQL can commit a normal claim's lease before payload decoding fails; SQLite rolls its claim transaction back. Inspection leasing must respect any remaining live lease in either case. Quarantine cannot recall an external delivery already in flight. Destinations must continue to deduplicate by `(environmentId, eventId)` across requeue cycles. Requeue does not repair malformed payloads: resolve the producer/schema/decoder or destination cause first. No payload-edit, scheduler, automatic retry policy, route/console integration, retention expiry or deletion is added. For callback-free single-resource deletion, use [managed deletion](/docs/sharing-sqlite/managed-deletion). The raw update callback still cannot delete resources. ## Retained operator-action history [#retained-operator-action-history] After the explicit operator-history migration, every successful quarantine/requeue atomically appends a record to `_actions_v1`. An append failure rolls back the transition. Stale, foreign, expired and exhausted tokens do not create successful records. Original events and receipts remain unchanged. The log is append-only through the library API, not tamper-evident against database administrators; there is no pruning, failed-attempt log or administrative UI. Bind an optional `operator: { type, id }` when constructing the outbox worker. The factory copies this application-attested identity; authenticate and authorize it in the application first. Existing factories without an operator record `null`, never an inferred or authenticated actor. Both identity fields must be nonblank strings of at most 1024 characters with no NUL. `inspectOperatorActions({ eventId, limit, afterGeneration? })` returns immutable records for that event in the factory's environment. Limit is 1–1000. Records include stable `actionId`, `environmentId`, `eventId`, resulting decimal `generation`, `action`, nullable `operator`, nullable `reason` and ISO `recordedAt`. Requeue reasons are null. Times describe the transition inside the transaction, not exact COMMIT time. The exclusive cursor defaults to `"0"`; use the last returned generation for the next page. Pagination follows numeric generation, so clock changes cannot skip records. Gaps are normal. This is a live per-event traversal, not a frozen or cross-event feed. Malformed records fail closed; inspection does not decode the event payload. Stop/drain old operator binaries, run the explicit migration, then start upgraded workers only. The additive table retains previous schemas and data. History starts at this rollout: existing quarantines have no fabricated historical action. Their later requeue is recorded. An empty history cannot prove there were no pre-upgrade actions. Mixed-version operators can leave gaps and are unsupported. Record the rollout boundary in application operations records. ```ts import { createSqliteProtectedWriteOutbox, type ParameterizedSqliteExecutor } from "@rolebook/sharing-sqlite"; declare const executor: ParameterizedSqliteExecutor; // Obtain this identity only after application authentication and operator authorization. declare const trustedOperator: { type: string; id: string }; declare const eventId: string; const worker = createSqliteProtectedWriteOutbox({ executor, tablePrefix: "app_authorization", environmentId: "production", operator: trustedOperator, }); const firstPage = await worker.inspectOperatorActions({ eventId, limit: 100 }); const last = firstPage.at(-1); if (last) { const nextPage = await worker.inspectOperatorActions({ eventId, limit: 100, afterGeneration: last.generation, }); } ``` ## Stored-text fidelity in managed operations [#stored-text-fidelity-in-managed-operations] Managed updates, batch entries, deletion pre-state and moves validate stored text before calling the application resource projection or evaluating policy. The check covers the complete configured projection, including keys, versions and policy attributes that are not writable patch fields. A value that the driver has shortened or otherwise changed fails closed; it is never silently normalized into a different policy value. Generated-write post-state and batch final reloads use the same loader. Rejection rolls back the business write and its receipt/event together. Exact retained receipt replay still occurs before current schema or authorization checks. SQLite first reads ASCII-safe SQL hex/storage-class evidence and the main database encoding. It strictly validates UTF-8, UTF-16LE or UTF-16BE before fetching raw text, then compares the decoded value to the physical bytes. This prevents malformed encoded text from reaching native libSQL decoding. Valid Unicode and null/empty values remain supported. Embedded NUL is accepted when faithfully represented by the driver (Bun SQLite); local libSQL truncation is rejected. Literal BOM characters are not stripped by the fidelity validator. Database/driver transformations during a generated write still must satisfy the existing exact postcondition; they are not repaired. # Sharing testkit (/docs/sharing-testkit) > @rolebook/sharing-testkit: the security contract every sharing adapter must pass. `@rolebook/sharing-testkit` is the executable form of the [adapter contract](/docs/sharing/adapters). It returns named async test cases that you register with your own runner (Bun, Vitest, Jest, or another): the kit takes no runner dependency and opens no database. The memory, PGlite, PostgreSQL, and SQLite adapters all run it. ```ts import { test } from "bun:test"; import { sharingAdapterContract, type SharingAdapterContractFactory } from "@rolebook/sharing-testkit"; declare const createPostgresFixture: SharingAdapterContractFactory["create"]; for (const contract of sharingAdapterContract({ create: createPostgresFixture })) { test(contract.name, contract.run); } ``` ## The adapter contract [#the-adapter-contract] `sharingAdapterContract(factory)` returns 40 cases. Each case calls `factory.create()` for fresh storage and a fresh sharing instance. The fixture must: - use the exported `sharingAdapterContractSubjects`, `sharingAdapterContractTenants`, and `sharingAdapterContractProject`; - make `owner`, `editor`, `viewer`, and `invitee` eligible in `tenant_a` with empty tenant assignments, and every identity in `tenant_b` ineligible; - resolve each subject with the `attributes.email` exported for it, match email recipients by that address, and verify email recipients in the adapter's recipient fence against the same identity; - inject one clock into the adapter and `createSharing()`, starting at `2025-01-01T00:00:00.000Z`, and move it with `setNow()`; - implement `useNonBooleanFences()` and `useNonBooleanFactRevalidation()` by changing the callbacks the existing adapter holds, so the contract can prove that only a literal `true` passes a fence; - optionally supply `deleteApplicationResource()` (for adapters whose lifecycle seam verifies the application row is gone) and `seedInTenant()` (needed to catch an audit listing that ignores the tenant); - build `sharing` so that `listAccessible()` can read a [consistent page](/docs/sharing/listing#what-a-consistent-page-requires): the adapter implements `runConsistentPage` on a supported executor, its eligibility fence has evidence for pages, and the identity adapter supplies identity evidence. The listing cases call `listAccessible()` on the fixture's own instance, so a fixture without these fails them with `ACCESS_LISTING_UNAVAILABLE`. The cases cover tenant isolation at the module and adapter, no implicit workspace grant, self-promotion, ownership transfer and the single-owner invariant, invitation expiry, recipients, replay, and revocation, immediate revocation, concurrent single-winner acceptance, competing same-version mutations, lifecycle deletion and cross-tenant moves, non-boolean fence results failing closed, listing pagination and equality with `authorize()`, cursor rejection, time-limited memberships (eight cases), `describeAccess()`, `permissions()`, audit history paging and incarnations, and pruning (for adapters that offer `pruneSettledRecords()`; others get a one-time warning). The suite does not replace database-specific transaction, lock, foreign-key, and application lifecycle tests. ## Teams contract [#teams-contract] `sharingTeamsContract(factory)` checks the [team](/docs/teams) rules against an adapter whose identity is team-aware and whose fences understand teams. The fixture builds sharing with the canonical teams policy (`sharingTeamsContractRoles`), makes `sharingTeamsContractSubjects` eligible in `tenant_a` only, creates `design` and `marketing` in `tenant_a` and `research` in `tenant_b`, and implements `addTeamMember`, `removeTeamMember`, and `deleteTeam` against the authoritative team store. It is a separate suite, so adapters without team support keep running `sharingAdapterContract` unchanged. ## listAccess contract [#listaccess-contract] `sharingListAccessContract(factory)` takes the adapter contract's factory and checks [`listAccess()`](/docs/sharing/listing#everything-the-actor-can-do-by-type) over the adapter: ownership, direct and team memberships, a comment-only role, an assignment, a deny that removes every action, expiry, a pending and then an accepted invitation, and a second tenant, at limits 1 and 100, each page equal to what `permissions()` evaluates, plus cursor isolation from `listAccessible()`. Register its cases with your test runner the same way as `sharingAdapterContract`'s. Both `listAccess()` suites build their own sharing instances over the fixture's adapter, with identity adapters that supply bracketed evidence. The adapter itself must provide [consistent pages](/docs/sharing/listing#what-a-consistent-page-requires): it implements `runConsistentPage` on a supported executor, and its eligibility fence has evidence for pages. An adapter without the capability fails these cases. `sharingListAccessScopeContract(factory)` adds the page-consistency cases. It commits a change to storage while a page is open and requires the page to be the state before the change and the next page the state after it; it changes the actor's principal while a page is open and requires the page to be read again wholly under the new principal; and it requires expiry to be decided at the page's own instant, not the sharing module's clock. Passing these suites shows that the adapter you ran them against behaves this way under the schedules they contain, on the database and executor you used. It does not qualify a different executor, database version, or identity source, and a suite that was skipped or run against a substitute database shows nothing about the real one. ## Policy contracts [#policy-contracts] Three suites cover [versioned sharing](/docs/sharing/versioned): `policyVersionsContract` (13 cases) and `customRolesContract` (23 cases) on a `PolicyVersionsContractFixture` built with `createVersionedSharing()` (use `policyContractPolicies.v1` as the seed and `.v2` as the published draft), and `policyStoreContract` (21 cases) on any `PolicyStore`. Nine custom-role cases cover the atomic `customRoles.set` and seven store cases `writeTenantRoleSet`; both fail for a store that does not implement `writeTenantRoleSet`. One more store case requires `writeTenantRole` and `deleteTenantRole` to refuse an audit event any field of which fails `assertPolicyAuditEventFields`, writing nothing. The last policy-version case scopes `lookupExecution()` to its tenant for an actor eligible in two tenants. ## API [#api] `import { ... } from "@rolebook/sharing-testkit"`. Signatures are checked against the built declarations. ## Adapter contract [#adapter-contract] ### `sharingAdapterContract` [#sharingadaptercontract] ```ts api="@rolebook/sharing-testkit" function sharingAdapterContract( factory: SharingAdapterContractFactory, ): readonly SharingAdapterContractCase[]; ``` The 40 adapter cases, in a stable order with stable names; cases added later are appended. The last two cover [`lookupExecution()`](/docs/sharing/api#tenantsharing) and the adapter's `lookupMutationIdempotency`, and fail for an adapter without it: a committed command found with what a replay answers, a mismatch reported only to an actor who can see the resource, refusals before any read, a key recorded in one tenant not readable through another, no write by any lookup (including one for a resource or a tenant with no rows), and `not_found` after a record was pruned, deleted (standalone or through the lifecycle seam) or moved to another tenant. ### `sharingListAccessContract` [#sharinglistaccesscontract] ```ts api="@rolebook/sharing-testkit" function sharingListAccessContract( factory: SharingAdapterContractFactory, ): readonly SharingAdapterContractCase[]; ``` The `listAccess()` cases, over the same factory. A separate suite, so `sharingAdapterContract` keeps its cases and count. Each case builds its own sharing instance over the fixture's `adapter` and `now()`, seeds a world through `seed` (including a team membership) and `seedInTenant`, and requires every page to equal what `permissions()` evaluates, and `listAccess()` and `listAccessible()` cursors never to open as each other. The fixture's adapter must implement `runConsistentPage`; each case supplies its own identity evidence. ### `sharingListAccessScopeContract` [#sharinglistaccessscopecontract] ```ts api="@rolebook/sharing-testkit" function sharingListAccessScopeContract(factory: SharingListAccessScopeFactory): readonly { readonly name: string; run(): Promise; }[]; ``` The `listAccess()` scope cases: a tenant-wide identity grant of a non-first action on a resource with no sharing row for the actor, beside ownership, a direct membership, two granting teams, a resource-scoped assignment and a team deny of every action, at a fixed clock. Every backend must list the same resources with the same `allowed` maps and decision codes, and each entry must deep-equal `permissions()` on that backend. Nine cases in all. After the grant-source case: - Four cases commit one storage change while a page is open: a resource changed, a membership revoked, and a membership granted, each after hydration, and a resource that becomes a candidate after candidate selection. The open page must be the state before the change, and the next page the state after it. - One case changes the actor's principal while a page is open. The page must be read again wholly under the new principal. - One case requires membership expiry to be decided at the snapshot's own instant, never the sharing module's clock. - One case changes a principal fact from `null` to `NaN` while a page is open. Identity evidence is compared exactly, so the old page is not returned; the engine refuses the new value as a subject attribute, and the listing must answer `identity_evidence_missing`, never an empty page. - One case keeps changing the principal on every attempt and must answer `ACCESS_LISTING_UNAVAILABLE` with reason `changed` after three attempts, each with its own snapshot. The adapter must implement `runConsistentPage`. The cases' identity adapters supply bracketed evidence, so the fixture configures no identity of its own. ### `SharingListAccessScopeFactory` [#sharinglistaccessscopefactory] ```ts api="@rolebook/sharing-testkit" interface SharingListAccessScopeFactory { create(options: { readonly clock: SharingClock; }): Awaitable; } ``` ### `SharingListAccessScopeFixture` [#sharinglistaccessscopefixture] ```ts api="@rolebook/sharing-testkit" interface SharingListAccessScopeFixture { readonly adapter: SharingAdapter; seed(input: { readonly tenantId: string; readonly id: string; readonly owner: ResourceRef; readonly memberships?: readonly { readonly subject: ResourceRef; readonly role: string; readonly expiresAt?: Date; }[]; }): Awaitable; archive(input: { readonly tenantId: string; readonly id: string }): Awaitable; } ``` `archive` sets the resource's `archived` attribute (seeded `false`) to `true` and changes its version. The adapter must read the `clock` given to `create` wherever it reads the time itself, such as to leave out expired memberships; the contract keeps that clock fixed and drives the module's own clock. Storage whose seeded resources carry their tenant's workspace as their only ancestor, so a tenant-wide grant applies. Its fences must admit every subject in `tenant_a`. ### `SharingAdapterContractFactory` [#sharingadaptercontractfactory] ```ts api="@rolebook/sharing-testkit" interface SharingAdapterContractFactory { create(): Awaitable; } ``` ### `SharingAdapterContractFixture` [#sharingadaptercontractfixture] ```ts api="@rolebook/sharing-testkit" interface SharingAdapterContractFixture { readonly sharing: ResourceSharing; readonly adapter: SharingAdapter; readAudits(): Awaitable[]>; now(): Date; setNow(value: Date): void; seed(id?: string, memberships?: readonly SharingAdapterContractMembership[]): Awaitable; seedInTenant?(tenantId: string, id: string): Awaitable; revokeTenantEligibility(subject: SharingAdapterContractSubject): Awaitable; useNonBooleanFences(): Awaitable; useNonBooleanFactRevalidation(): Awaitable; deleteApplicationResource?(resourceId: string, transaction: unknown): Awaitable; storeSnapshot?(): Awaitable; grantTenantEligibility?(tenantId: string, subject: SharingAdapterContractSubject): Awaitable; moveApplicationResource?(input: { readonly resourceId: string; readonly toTenantId: string; readonly resultingResourceVersion: string; readonly transaction: unknown; }): Awaitable<"applied" | "conflict">; } ``` What `create()` returns: the sharing instance, adapter, seeding, clock, fence switches, and audit reads. Three optional members serve the lookup cases: `storeSnapshot()` (every row of every table, so each lookup is checked to write nothing at all; without it the cases compare the resource's revision, memberships and audit), and `moveApplicationResource()` with `grantTenantEligibility()` (so a real lifecycle move clears a source key on an adapter whose standalone `resourceMoved` is unsupported). The first-party SQLite and PostgreSQL fixtures supply all three. ### `SharingAdapterContractCase` [#sharingadaptercontractcase] ```ts api="@rolebook/sharing-testkit" interface SharingAdapterContractCase { readonly name: string; run(): Promise; } ``` A named case: register `run` with your runner. ### `SharingAdapterContractMembership` [#sharingadaptercontractmembership] ```ts api="@rolebook/sharing-testkit" interface SharingAdapterContractMembership { readonly subject: SharingAdapterContractSubject; readonly role: "editor" | "viewer"; readonly expiresAt?: Date; } ``` ### `SharingAdapterContractSubject` [#sharingadaptercontractsubject] ```ts api="@rolebook/sharing-testkit" interface SharingAdapterContractSubject { readonly type: string; readonly id: string; readonly attributes?: Readonly>; } ``` ### `sharingAdapterContractSubjects` [#sharingadaptercontractsubjects] ```ts api="@rolebook/sharing-testkit" const sharingAdapterContractSubjects: Readonly<{ owner: Readonly<{ type: "user"; id: "owner"; attributes: Readonly<{ email: "owner@example.test"; }>; }>; editor: Readonly<{ type: "user"; id: "editor"; attributes: Readonly<{ email: "editor@example.test"; }>; }>; viewer: Readonly<{ type: "user"; id: "viewer"; attributes: Readonly<{ email: "viewer@example.test"; }>; }>; invitee: Readonly<{ type: "user"; id: "invitee"; attributes: Readonly<{ email: "invitee@example.test"; }>; }>; outsider: Readonly<{ type: "user"; id: "outsider"; attributes: Readonly<{ email: "outsider@example.test"; }>; }>; projectionUser: Readonly<{ type: "user"; id: "shared_projection_id"; attributes: Readonly<{ email: "projection-user@example.test"; }>; }>; projectionService: Readonly<{ type: "service"; id: "shared_projection_id"; attributes: Readonly<{ email: "projection-service@example.test"; }>; }>; projectionUnrelated: Readonly<{ type: "user"; id: "unrelated_projection_id"; attributes: Readonly<{ email: "projection-unrelated@example.test"; }>; }>; }>; ``` The contract's subjects with their emails. ### `sharingAdapterContractTenants` [#sharingadaptercontracttenants] ```ts api="@rolebook/sharing-testkit" const sharingAdapterContractTenants: Readonly<{ primary: "tenant_a"; secondary: "tenant_b"; }>; ``` ### `sharingAdapterContractProject` [#sharingadaptercontractproject] ```ts api="@rolebook/sharing-testkit" const sharingAdapterContractProject: Readonly<{ type: "project"; id: "project_1"; }>; ``` ## Teams contract [#teams-contract-1] ### `sharingTeamsContract` [#sharingteamscontract] ```ts api="@rolebook/sharing-testkit" function sharingTeamsContract(factory: SharingTeamsContractFactory): readonly { readonly name: string; run(): Promise; }[]; ``` The team-rule cases. ### `SharingTeamsContractFactory` [#sharingteamscontractfactory] ```ts api="@rolebook/sharing-testkit" interface SharingTeamsContractFactory { create(): Awaitable; } ``` ### `SharingTeamsContractFixture` [#sharingteamscontractfixture] ```ts api="@rolebook/sharing-testkit" interface SharingTeamsContractFixture { readonly sharing: ResourceSharing; readonly adapter: SharingAdapter; seed( id: string, memberships?: readonly { readonly subject: ResourceRef; readonly role: string; }[], ): Awaitable; addTeamMember(team: ResourceRef, user: ResourceRef, tenantId?: string): Awaitable; removeTeamMember(team: ResourceRef, user: ResourceRef): Awaitable; deleteTeam(team: ResourceRef): Awaitable; } ``` ### `SharingTeamsContractRole` [#sharingteamscontractrole] ```ts api="@rolebook/sharing-testkit" type SharingTeamsContractRole = (typeof sharingTeamsContractRoles)[number]; ``` ### `sharingTeamsContractRoles` [#sharingteamscontractroles] ```ts api="@rolebook/sharing-testkit" const sharingTeamsContractRoles: readonly ["viewer", "editor", "manager", "blocked"]; ``` The canonical teams policy roles the fixture must use. ### `sharingTeamsContractSubjects` [#sharingteamscontractsubjects] ```ts api="@rolebook/sharing-testkit" const sharingTeamsContractSubjects: Readonly<{ owner: Readonly<{ type: "user"; id: "team_owner"; }>; alice: Readonly<{ type: "user"; id: "alice"; }>; bob: Readonly<{ type: "user"; id: "bob"; }>; carol: Readonly<{ type: "user"; id: "carol"; }>; }>; ``` ### `sharingTeamsContractTeams` [#sharingteamscontractteams] ```ts api="@rolebook/sharing-testkit" const sharingTeamsContractTeams: Readonly<{ design: Readonly<{ type: "team"; id: "design"; }>; marketing: Readonly<{ type: "team"; id: "marketing"; }>; research: Readonly<{ type: "team"; id: "research"; }>; }>; ``` ### `sharingTeamsContractTenants` [#sharingteamscontracttenants] ```ts api="@rolebook/sharing-testkit" const sharingTeamsContractTenants: Readonly<{ primary: "tenant_a"; secondary: "tenant_b"; }>; ``` ## Inherited-access contract [#inherited-access-contract] See [inherited access](/docs/sharing/inheritance). The PostgreSQL and SQLite adapters run `sharingInheritanceContract`; the memory adapter runs `sharingInheritanceRefusalContract`. ### `sharingInheritanceContract` [#sharinginheritancecontract] ```ts api="@rolebook/sharing-testkit" function sharingInheritanceContract(factory: SharingInheritanceContractFactory): readonly SharingInheritanceContractCase[]; ``` The inherited-access contract cases, each over fresh storage from `factory`: inherit from a parent and from a deeper ancestor, revoke on the parent, an explicit deny on the child, a move (document and subtree), parent membership expiry, a cross-tenant ancestor, cyclic and over-deep chains, `listAccessible`/`listAccess` parity with `authorize`, ownership never inheriting, a deny on an ancestor, owner recovery keeping an ancestor's deny, a mismatched definition refused, enrollment refusing unplaced resources, control actions refused to unauthorized actors, delete, an ancestor whose resource is gone, an impossible subtree height, and `describeAccess` deciding inspection before reading other members. The cases use only public Sharing APIs. ### `sharingInheritanceRefusalContract` [#sharinginheritancerefusalcontract] ```ts api="@rolebook/sharing-testkit" function sharingInheritanceRefusalContract(createAdapter: () => unknown): readonly SharingInheritanceContractCase[]; ``` For an adapter without an inherited read path, such as the memory adapter: `defineSharing` must refuse `inheritance: "ancestors"` on it, and refuse the recursive contract policy without the opt-in. ### `SharingInheritanceContractFactory` [#sharinginheritancecontractfactory] ```ts api="@rolebook/sharing-testkit" interface SharingInheritanceContractFactory { create(): Promise; } ``` Creates fresh storage with `tenant_a` and `tenant_b` enrolled and activated through the public hierarchy control facade, and `tenant_c` prepared but not enrolled. ### `SharingInheritanceContractFixture` [#sharinginheritancecontractfixture] ```ts api="@rolebook/sharing-testkit" interface SharingInheritanceContractFixture { readonly sharing: VersionedResourceSharing; create(tenantId: string, resource: Ref, parent: Ref | null): Promise; move(tenantId: string, resource: Ref, parent: Ref): Promise; corruptParent(tenantId: string, resource: Ref, parent: Ref): Promise; corruptHeight(tenantId: string, resource: Ref, height: number): Promise; removeOwnerRow(tenantId: string, resource: Ref): Promise; insertRawMembership(tenantId: string, scope: Ref, subject: Ref, role: string): Promise; insertUnplacedResource(tenantId: string, resource: Ref): Promise; delete(tenantId: string, resource: Ref): Promise; createAs(actor: Ref, tenantId: string, resource: Ref, parent: Ref | null): Promise; control(tenantId: string, actor: Ref): { enroll(input: { readonly idempotencyKey: string; }): Promise<{ readonly status: string; }>; activate(input: { readonly idempotencyKey: string; }): Promise<{ readonly status: string; }>; releaseQuarantine(input: { readonly idempotencyKey: string; }): Promise<{ readonly status: string; }>; repairHeights(): Promise<{ readonly status: string; }>; }; inventory(tenantId: string): Promise<{ readonly status: string; }>; sharingWith(change: (resources: typeof sharingInheritanceContractResources) => Record): Promise>; close(): Promise; } ``` `create`, `createAs`, `move` and `delete` go through the control facade's `structure` commands; `control` and `inventory` drive enrollment. `corruptParent`, `corruptHeight`, `removeOwnerRow`, `insertRawMembership` and `insertUnplacedResource` are raw-storage seams, bypassing the store's own constraints, for the fail-closed cases. `sharingWith` builds a second versioned instance over the same adapters. ### `SharingInheritanceContractCase` [#sharinginheritancecontractcase] ```ts api="@rolebook/sharing-testkit" interface SharingInheritanceContractCase { readonly name: string; run(): Promise; } ``` One named case. ### `sharingInheritanceContractPolicy` [#sharinginheritancecontractpolicy] ```ts api="@rolebook/sharing-testkit" summary const sharingInheritanceContractPolicy: unknown; ``` The contract policy: the bootstrap type `tenant_admin`, a recursive `folder` type and `document` below it, with folder viewer/editor roles that reach documents and a document role that denies `document:read`. ### `sharingInheritanceContractResources` [#sharinginheritancecontractresources] ```ts api="@rolebook/sharing-testkit" summary const sharingInheritanceContractResources: unknown; ``` The Sharing configuration of `folder` and `document`, both with `inheritance: "ancestors"`, without the adapter the factory supplies. ### `sharingInheritanceContractCommands` [#sharinginheritancecontractcommands] ```ts api="@rolebook/sharing-testkit" summary const sharingInheritanceContractCommands: unknown; ``` The hierarchy command map for the contract policy. ### `sharingInheritanceContractIdentityAssignments` [#sharinginheritancecontractidentityassignments] ```ts api="@rolebook/sharing-testkit" function sharingInheritanceContractIdentityAssignments(subject: Ref): readonly { readonly subject: Ref; readonly role: string; readonly scope: { readonly resource: Ref; readonly appliesTo: "self" | "descendants"; }; }[]; ``` The identity assignments the factory's local identity projection gives a subject in every contract tenant: `operator` holds the bootstrap role and structure rights on the roots `r1`, `r2` and `r3`; `carol` holds structure rights on `r2`'s subtree; everyone else holds none. ### `sharingInheritanceContractSubjects` [#sharinginheritancecontractsubjects] ```ts api="@rolebook/sharing-testkit" summary const sharingInheritanceContractSubjects: unknown; ``` `operator`, `alice`, `bob` and `carol`, all eligible in both tenants; only `operator` has identity assignments. ### `sharingInheritanceContractRoots` [#sharinginheritancecontractroots] ```ts api="@rolebook/sharing-testkit" summary const sharingInheritanceContractRoots: unknown; ``` The root folder IDs `r1`, `r2` and `r3` the operator's structure rights cover. ### `sharingInheritanceContractTenants` [#sharinginheritancecontracttenants] ```ts api="@rolebook/sharing-testkit" summary const sharingInheritanceContractTenants: unknown; ``` `tenant_a` and `tenant_b` (enrolled; `tenant_b` reuses `tenant_a`'s resource IDs so a tenant leak is visible) and `tenant_c` (never enrolled by the factory). ## Policy contracts [#policy-contracts-1] ### `policyVersionsContract` [#policyversionscontract] ```ts api="@rolebook/sharing-testkit" function policyVersionsContract( factory: PolicyVersionsContractFactory, ): readonly PolicyContractCase[]; ``` The 13 policy-version cases. ### `customRolesContract` [#customrolescontract] ```ts api="@rolebook/sharing-testkit" function customRolesContract( factory: PolicyVersionsContractFactory, ): readonly PolicyContractCase[]; ``` The 23 custom-role cases. ### `policyStoreContract` [#policystorecontract] ```ts api="@rolebook/sharing-testkit" function policyStoreContract( factory: PolicyStoreContractFactory, ): readonly PolicyContractCase[]; ``` The 21 `PolicyStore` cases. ### `PolicyContractCase` [#policycontractcase] ```ts api="@rolebook/sharing-testkit" interface PolicyContractCase { readonly name: string; run(): Promise; } ``` ### `PolicyVersionsContractFactory` [#policyversionscontractfactory] ```ts api="@rolebook/sharing-testkit" interface PolicyVersionsContractFactory { create(): Awaitable; } ``` ### `PolicyVersionsContractFixture` [#policyversionscontractfixture] ```ts api="@rolebook/sharing-testkit" interface PolicyVersionsContractFixture { readonly sharing: VersionedResourceSharing; readonly store: PolicyStore; readonly adapter: SharingAdapter; now(): Date; setNow(value: Date): void; seed( id?: string, memberships?: readonly { readonly subject: SharingAdapterContractSubject; readonly role: "editor" | "viewer" | CustomRoleLabel; }[], tenantId?: "tenant_a" | "tenant_c", ): Awaitable; beforeNextApply(hook: () => Promise): void; createPeer(): Promise>; setStoreUnavailable(unavailable: boolean): Awaitable; throwFromNextFence(): Awaitable; readAudits(): Awaitable[]>; } ``` ### `PolicyStoreContractFactory` [#policystorecontractfactory] ```ts api="@rolebook/sharing-testkit" interface PolicyStoreContractFactory { create(): Awaitable; } ``` ### `PolicyStoreContractFixture` [#policystorecontractfixture] ```ts api="@rolebook/sharing-testkit" interface PolicyStoreContractFixture { readonly store: PolicyStore; storeSnapshot?(): Awaitable; setCounters(input: { readonly generation?: string; readonly tenantRevisions?: Readonly>; }): Awaitable; failNextAudit(): Awaitable; } ``` ### `policyContractPolicies` [#policycontractpolicies] ```ts api="@rolebook/sharing-testkit" const policyContractPolicies: Readonly<{ v1: Readonly< import("rolebook").RolebookPolicy< string, import("rolebook").PolicyPermissionFromResources, import("rolebook").ResourceDefinitions > >; v2: Readonly< import("rolebook").RolebookPolicy< string, import("rolebook").PolicyPermissionFromResources, import("rolebook").ResourceDefinitions > >; }>; ``` The seed (`v1`) and draft (`v2`) policies the policy contracts expect. ## Protected-write correctness fixtures [#protected-write-correctness-fixtures] These supporting exports are used by the PostgreSQL [protected application update API](/docs/sharing-postgres/protected-updates). Metadata and fixtures alone do not authorize an application write. The supported wrapper is resource/action scoped; field-mediated post-state enforcement and application operational integration are separate contracts. ### `protectedWritePolicy` [#protectedwritepolicy] ```ts api="@rolebook/sharing-testkit" const protectedWritePolicy: Readonly, { readonly document: { readonly actions: readonly ["update"]; }; }>>; ``` Canonical document-update policy for the initial correctness corpus, with resource-wide editor, explicit deny and title-only roles. It is a test fixture, not a production protected-write wrapper. ### `protectedWriteDecisionFixtures` [#protectedwritedecisionfixtures] ```ts api="@rolebook/sharing-testkit" const protectedWriteDecisionFixtures: readonly [{ readonly id: "PW-ALLOW"; readonly roles: readonly ["editor"]; readonly scopeId: "document-a"; readonly allowed: true; }, { readonly id: "PW-NO-GRANT"; readonly roles: readonly []; readonly scopeId: "document-a"; readonly allowed: false; }, { readonly id: "PW-DENY-WINS"; readonly roles: readonly ["editor", "blocked"]; readonly scopeId: "document-a"; readonly allowed: false; }, { readonly id: "PW-WRONG-RESOURCE"; readonly roles: readonly ["editor"]; readonly scopeId: "document-b"; readonly allowed: false; }, { readonly id: "PW-FIELD-ONLY"; readonly roles: readonly ["title_editor"]; readonly scopeId: "document-a"; readonly allowed: false; }]; ``` Expected allow/deny cases for grants, explicit denies, wrong resources and field-only access. Field-only grants must never admit arbitrary resource-wide SQL. ### `protectedWriteHistoryRequirements` [#protectedwritehistoryrequirements] ```ts api="@rolebook/sharing-testkit" const protectedWriteHistoryRequirements: readonly ["completed revoke before new snapshot denies", "completed grant before new snapshot allows", "write before revoke may commit in a valid serial order", "concurrent sharing-path revision bump conflicts with seal", "expiry at or before advancing seal clock aborts", "failed seal rolls business, receipt, audit and outbox back together", "same intent key and different payload conflicts", "lost commit acknowledgement requires receipt reconciliation", "resource delete and recreate cannot reuse prior-incarnation authority", "policy and custom-role changes conflict with declared authority fences"]; ``` The required concurrency and recovery histories for protected-write adapters. The PostgreSQL resource/action wrapper has integration coverage for these histories; this exported checklist is not evidence that another adapter or a broader field-mediated contract passes them. ## Managed update correctness fixtures [#managed-update-correctness-fixtures] These shared cases exercise field allows, deny precedence, declared no-ops and before/after conditions across the SQL adapters. ### `managedWritePolicy` [#managedwritepolicy] ```ts api="@rolebook/sharing-testkit" const managedWritePolicy: Readonly, { readonly document: { readonly actions: readonly [ "update" ]; }; }>>; ``` ### `managedWriteDecisionFixtures` [#managedwritedecisionfixtures] ```ts api="@rolebook/sharing-testkit" const managedWriteDecisionFixtures: readonly [ { readonly id: "MW-FIELD-ALLOW"; readonly roles: readonly [ "title_editor" ]; readonly before: { readonly title: "before"; readonly visibility: "private"; }; readonly patch: { readonly title: "after"; }; readonly allowed: true; }, { readonly id: "MW-FIELD-DENY"; readonly roles: readonly [ "editor", "title_blocked" ]; readonly before: { readonly title: "before"; readonly visibility: "private"; }; readonly patch: { readonly title: "after"; }; readonly allowed: false; }, { readonly id: "MW-MIXED-PATCH"; readonly roles: readonly [ "title_editor" ]; readonly before: { readonly title: "before"; readonly visibility: "private"; }; readonly patch: { readonly title: "after"; readonly visibility: "public"; }; readonly allowed: false; }, { readonly id: "MW-POST-STATE-DENY"; readonly roles: readonly [ "private_editor" ]; readonly before: { readonly title: "before"; readonly visibility: "private"; }; readonly patch: { readonly visibility: "public"; }; readonly allowed: false; }, { readonly id: "MW-PRE-STATE-DENY"; readonly roles: readonly [ "private_editor" ]; readonly before: { readonly title: "before"; readonly visibility: "public"; }; readonly patch: { readonly visibility: "private"; }; readonly allowed: false; }, { readonly id: "MW-STABLE-STATE-ALLOW"; readonly roles: readonly [ "private_editor" ]; readonly before: { readonly title: "before"; readonly visibility: "private"; }; readonly patch: { readonly title: "after"; }; readonly allowed: true; }, { readonly id: "MW-NOOP-DENY"; readonly roles: readonly [ "editor", "title_blocked" ]; readonly before: { readonly title: "before"; readonly visibility: "private"; }; readonly patch: { readonly title: "before"; }; readonly allowed: false; }, { readonly id: "MW-UNDECLARED-DENY-IRRELEVANT"; readonly roles: readonly [ "editor", "title_blocked" ]; readonly before: { readonly title: "before"; readonly visibility: "private"; }; readonly patch: { readonly visibility: "public"; }; readonly allowed: true; }, { readonly id: "MW-RESOURCE-DENY-WINS"; readonly roles: readonly [ "title_editor", "blocked" ]; readonly before: { readonly title: "before"; readonly visibility: "private"; }; readonly patch: { readonly title: "after"; }; readonly allowed: false; } ]; ``` ## Document workload conformance [#document-workload-conformance] These exports describe the bounded `rolebook-66-local-sql-v1` correctness profile. They do not run a database or certify an adapter. The repository's file-backed Bun SQLite runner collects observations; `auditDocumentWorkload` compares them with expectations derived from `protectedWriteDecisionFixtures` and `managedWriteDecisionFixtures`, independently of the implementation's decisions. The profile includes five raw-write and nine managed-write cases, persisted row and receipt checks, callback counts, replay, conflicting intent, callback rollback, and stable-dataset listing at page sizes 1, 2, and 100. Listing must exhaust and match both the declared allowed IDs and individual authorization checks. A negative control deliberately injects a false allow and must fail admission. This is a local SQL correctness profile, not a benchmark or a competitive ranking. It assumes a complete local identity projection and no concurrent changes during listing. Local libSQL, PostgreSQL, HTTP, concurrent revocation, expiry races, lost acknowledgements, and outbox delivery are **unmodeled by this profile**; that does not mean the products lack those capabilities. Remote libSQL and libSQL in-memory protected writes are recorded separately as unsupported by the SQLite protected-write adapter. The full `protectedWriteHistoryRequirements` gate is not satisfied merely by passing this bounded profile. ### `documentWorkload` [#documentworkload] ```ts api="@rolebook/sharing-testkit" summary const documentWorkload: { readonly id: "rolebook-66-local-sql-v1"; // Additional manifest fields described below. }; ``` The signature above is abbreviated. The manifest contains `baseline` (the original fixture/profile source commit), `cases` (IDs, expected allowance, raw/managed kind, and before/after rows), `listing` (page sizes and expected IDs), `productUnsupported`, and `harnessUnmodeled`. The baseline identifies the profile's origin; it is not an attestation of the implementation revision currently tested. Record the actual source revision and report hashes with each run. Treat the manifest and its nested fixture-derived values as inputs; do not mutate them. ### `auditDocumentWorkload` [#auditdocumentworkload] ```ts api="@rolebook/sharing-testkit" function auditDocumentWorkload(evidence: DocumentEvidence): readonly string[]; ``` Returns an empty array only when every registered observation and listing is present exactly once and its checked outcomes and effects match the profile. Otherwise it returns diagnostic strings such as `FALSE_ALLOW:PW-NO-GRANT`, `CARDINALITY::`, `ROW:`, `RECEIPT:`, `LIST_COMPLETENESS:`, `REPLAY`, `CONFLICT`, or `ROLLBACK`. Unknown observations and unexpected listing sizes also fail admission. Treat any returned diagnostic as a failed gate; the array is not a score. This function accepts typed evidence, not unvalidated JSON, and does not independently observe or authenticate database effects. ```ts import { auditDocumentWorkload, type DocumentEvidence } from "@rolebook/sharing-testkit"; declare const evidence: DocumentEvidence; // Collected by your workload driver. const violations = auditDocumentWorkload(evidence); if (violations.length > 0) { throw new Error(`Conformance failed: ${violations.join(", ")}`); } ``` ### `DocumentObservation` [#documentobservation] ```ts api="@rolebook/sharing-testkit" interface DocumentObservation { readonly id: string; readonly status: string; readonly errorCode?: string; readonly row: Readonly>; readonly receipt: boolean; readonly callbackCalls: number; } ``` One write case's measured result. `id` identifies a registered fixture. The expected `status` is `committed` for allowed cases and `denied` for denied cases; a denied result also requires `errorCode: "PROTECTED_WRITE_DENIED"`. Other status or error values fail the oracle. `row` contains exactly the observed `title`, `visibility`, and `version`; `receipt` records whether lookup found a persisted receipt. `callbackCalls` counts actual raw-write callback invocations and is zero for managed writes. Do not substitute expected values for observed effects. ### `ListingObservation` [#listingobservation] ```ts api="@rolebook/sharing-testkit" interface ListingObservation { readonly pageSize: number; readonly ids: readonly string[]; readonly individuallyAllowed: readonly string[]; readonly exhausted: boolean; } ``` One complete traversal at `pageSize`. `ids` contains all listed resource IDs; `individuallyAllowed` contains IDs allowed by individual checks across every seeded document in the same stable dataset. Both must equal the manifest's expected set without duplicates. `exhausted` must be true; stopping at a page limit or losing a continuation cursor is not a complete result. ### `HistoryObservation` [#historyobservation] ```ts api="@rolebook/sharing-testkit" interface HistoryObservation { readonly replayStatus: string; readonly callbackCalls: number; readonly conflictCode: string; readonly rollbackCode: string; readonly rollbackRow: Readonly>; readonly rollbackReceipt: boolean; } ``` Records the bounded history checks: identical intent returns `replayed`, the raw callback runs once across the initial write, replay, and conflicting attempt, and conflicting payload reports `IDEMPOTENCY_CONFLICT`. The rollback case reports `INJECTED_CALLBACK_FAILURE`, preserves the original row, and has no receipt. These fields do not attest to lost-acknowledgement recovery or concurrent histories. ### `DocumentEvidence` [#documentevidence] ```ts api="@rolebook/sharing-testkit" interface DocumentEvidence { readonly observations: readonly DocumentObservation[]; readonly listings: readonly ListingObservation[]; readonly history: HistoryObservation; } ``` The complete typed input to `auditDocumentWorkload`: all write observations, one listing observation for each registered page size, and the bounded history observations. Keep failed cases in the evidence; omitting them cannot produce a passing result. Runtime metadata and source hashes belong in the surrounding report and are not verified by this interface or the oracle. ## Additive document lifecycle profile v2 [#additive-document-lifecycle-profile-v2] The `rolebook-66-document-v2` profile adds managed deletion and outbox recovery to all v1 expectations. It does not expand the underlying product contract. Its baseline is `a2650b656ebf2c0a86304968d6244ba237a91ae9`; keep actual source/patch hashes and runtime metadata in the report. It models five deletion outcomes: allow, no grant, deny precedence, field-only grant, and rollback after a rejected final fence. The collector runs one scenario across PostgreSQL, Bun SQLite and file-backed libSQL. Each driver must return actual persisted rows and counts; an adapter-authored boolean is not a substitute. Fixtures include owner, membership, invitation and command idempotency rows, a business row at version 1, and sharing revision 7 over floor 0. Deletion must clear live data while retaining exactly one protected receipt, event and deletion audit. Recreation uses the same resource key with a new incarnation; original intent replay must preserve the replacement and a fresh key with the old incarnation must fail closed. Retained revision floors must be valid canonical decimal strings. Recovery quarantines and requeues the same event, verifies newer delivery generations, and rejects nine obsolete/duplicate token operations. `staleEffects` contains full persisted outbox/dead-letter snapshots before and after each attempt, in addition to its returned result in `staleAccepted`. False returns with changed state fail admission. `recoveryState()` must return independent JSON-compatible snapshots, not mutable references shared with subsequent operations. Missing prerequisite commits, claims, quarantine tokens or records throw; an incomplete run never becomes admission. The auditor returns diagnostics and does not execute SQL or validate arbitrary untyped JSON. Its input is the complete typed evidence from a trusted harness. It requires the unchanged v1 oracle to pass as well. Neither profile establishes external sink exactly-once delivery, performance, concurrent revocation, expiry races, same-tenant moves or operator history. Invitation rows are cleanup fixtures; invitation workflows are not exercised. The SQL CLI profiles now report v2 IDs; historical v1 reports retain their original IDs. ### `documentLifecycleWorkload` [#documentlifecycleworkload] ```ts api="@rolebook/sharing-testkit" summary const documentLifecycleWorkload: unknown; ``` ### `collectDocumentLifecycleEvidence` [#collectdocumentlifecycleevidence] ```ts api="@rolebook/sharing-testkit" function collectDocumentLifecycleEvidence(driver: DocumentLifecycleDriver, prior: DocumentEvidence): Promise; ``` ### `auditDocumentLifecycleWorkload` [#auditdocumentlifecycleworkload] ```ts api="@rolebook/sharing-testkit" function auditDocumentLifecycleWorkload(e: DocumentLifecycleEvidence): readonly string[]; ``` ### `DocumentLifecycleState` [#documentlifecyclestate] ```ts api="@rolebook/sharing-testkit" interface DocumentLifecycleState { readonly row: Readonly> | null; readonly liveRows: number; readonly receipts: number; readonly events: number; readonly deletionAudits: number; readonly revisionFloor: string | null; } ``` ### `DocumentLifecycleEvidence` [#documentlifecycleevidence] ```ts api="@rolebook/sharing-testkit" interface DocumentLifecycleEvidence { readonly prior: DocumentEvidence; readonly deletions: readonly { readonly id: string; readonly status: string; readonly code: string; readonly before: DocumentLifecycleState; readonly after: DocumentLifecycleState; }[]; readonly recovery: { readonly receiptId: string; readonly receiptSame: boolean; readonly firstIds: readonly string[]; readonly recoveredIds: readonly string[]; readonly kind: string; readonly payloadSame: boolean; readonly firstGeneration: string; readonly recoveredGeneration: string; readonly deadEventIds: readonly string[]; readonly deadReason: string; readonly deadTokenSame: boolean; readonly pendingWhileDead: number; readonly claimsWhileDead: number; readonly requeued: boolean; readonly deadAfterRequeue: number; readonly staleEffects: Readonly>; readonly staleAccepted: Readonly>; readonly acknowledged: boolean; readonly claimsAfterAck: number; readonly replayStatus: string; readonly replayReceiptSame: boolean; readonly incarnationChanged: boolean; readonly oldIncarnationCode: string; readonly replacement: DocumentLifecycleState; }; } ``` ### `DocumentLifecycleDriver` [#documentlifecycledriver] ```ts api="@rolebook/sharing-testkit" interface DocumentLifecycleDriver { prepare(id: string, roles: readonly string[]): Promise; remove(input: DeleteInput): Promise<{ readonly status: string; readonly receipt: Receipt; }>; rollback(input: DeleteInput): Promise<{ readonly status: string; readonly receipt: Receipt; }>; lookup(input: DeleteInput): Promise; state(input: DeleteInput): Promise; recreate(input: DeleteInput): Promise; recoveryState(): Promise; worker: { claim(input: { limit: number; leaseMs: number; }): Promise; inspectPending(input: { limit: number; }): Promise; quarantine(token: Token, input: { reason: string; }): Promise; inspectDeadLetters(input: { limit: number; }): Promise; requeue(token: Token): Promise; acknowledge(token: Token): Promise; retry(token: Token, input: { delayMs: number; }): Promise; }; } ``` `DocumentLifecycleDriver` is the structural driver seam used by the collector. `DeleteInput` in these signatures denotes resource type/id, action, incarnation ID, idempotency key and expected version (all strings). `Receipt` requires `receiptId`; drivers retain their full receipts so replay equality checks all fields. `Token` contains environment ID, event ID and generation strings. `Claim` contains event ID, kind, payload and delivery token. These supporting aliases are internal; implement the exported interface against the public authority/outbox APIs. ## Additive document move and operator-history profile v3 [#additive-document-move-and-operator-history-profile-v3] `rolebook-66-document-v3` is tied to baseline `c25bd402fd7743d90b11c851960b075aba4768b1`. Its eight declared move cases cover child/source/destination permissions, destination deny, field-only child permission, post-state deny and a final-fence rollback. Expected outcomes are fixed by the corpus, not generated from the policy under test. Admission also requires every unchanged v1/v2 expectation through nested `prior` evidence. Versioned v1/v2 runners remain available; this profile uses a separate move/history entry point. The shared collector consumes actual persisted state from PostgreSQL, Bun SQLite or file-backed libSQL. State includes the child's parent/version/revision/title, original owner/direct grants and parent rows, unique receipt/event, move audit and lifecycle record. Failed moves preserve the full observed state. Replay returns the original receipt, a changed postVersion conflicts, and recovery preserves the same move event. Operator history uses two quarantine/requeue cycles: captured service attribution, then no attribution. The original run starts generation at `9007199254740992`; the mandatory second run starts at `9999999999999995` and crosses decimal digit length. Both use the same move/history corpus, with the second run in `boundary`. Drivers must keep persisted counters exact using SQL decimal-string projections rather than JavaScript Number conversion. Page sizes 1, 2 and 3 must exhaust the same four actions with exclusive string cursors. Stale attempts capture independent JSON-compatible snapshots of outbox, dead-letter and history rows before and after. Failed history append must roll back the complete quarantine transition. Operator identity is trusted caller attribution, not authentication. Returned timestamps are transition times, not an exact COMMIT-time guarantee. The oracle rejects missing/extra/mutated move and history observations, incorrect attribution/generation, changed retained payload, replay effects and stale mutations hidden behind false returns. It returns diagnostics for complete typed evidence; it is not a general JSON validator or an independent database observer. Missing collector prerequisites throw instead of producing an admitted partial result. The bounded profile excludes new worker pumps, consistency-token runtime, concurrent revocation/expiry races, cross-tenant or recursive moves and external sink exactly-once semantics. It measures no performance. Local evidence and unpublished artifacts do not close broader conformance requirements or establish a production rollout. `collectDocumentMoveRunEvidence` collects one driver-backed run. The outer `collectDocumentMoveEvidence` invokes the supplied run function for both declared ranges and adds prior v1/v2 evidence. `auditDocumentMoveWorkload` requires both exact ranges; a missing boundary run cannot pass. Boundary diagnostics use a `BOUNDARY:` prefix. Baseline c25bd40 had text-alias history ordering at the digit boundary; admission requires the separately recorded SDK correction, and original red evidence must remain distinguishable from combined verification. Evidence revision 2 supersedes the earlier v3 physical-history admission gap. `DocumentRecoverySnapshot` contains direct SQL observations, normalized independently from the history API. Every successful quarantine/requeue records its immediate physical prefix (1/2/3/4 rows), and final acknowledgement requires exactly four. Failed append requires zero rows; each stale phase requires its known prefix even when before and after are identical. Each physical row independently matches the expected identity, exact generation, action ID, action, attribution, reason and valid timestamp; a separate equality check ties those rows to API observations. Missing/extra/corrupt physical history therefore cannot pass merely because the API returns correct records. `transitionSnapshots` and `finalSnapshot` are mandatory. The SQL read orders by the qualified integer column and preserves decimal strings. ### `documentMoveWorkload` [#documentmoveworkload] ```ts api="@rolebook/sharing-testkit" summary const documentMoveWorkload: unknown; ``` ### `collectDocumentMoveEvidence` [#collectdocumentmoveevidence] ```ts api="@rolebook/sharing-testkit" function collectDocumentMoveEvidence(run: (initialGeneration: string) => Promise, prior: DocumentLifecycleEvidence): Promise; ``` ### `collectDocumentMoveRunEvidence` [#collectdocumentmoverunevidence] ```ts api="@rolebook/sharing-testkit" function collectDocumentMoveRunEvidence(driver: DocumentMoveDriver, initialGeneration: string): Promise; ``` ### `auditDocumentMoveWorkload` [#auditdocumentmoveworkload] ```ts api="@rolebook/sharing-testkit" function auditDocumentMoveWorkload(e: DocumentMoveEvidence): readonly string[]; ``` ### `DocumentMoveInput` [#documentmoveinput] ```ts api="@rolebook/sharing-testkit" interface DocumentMoveInput { readonly resource: { readonly type: string; readonly id: string; }; readonly action: string; readonly incarnationId: string; readonly idempotencyKey: string; readonly expectedVersion: string; readonly postVersion: string; readonly sourceParent: { readonly id: string; readonly incarnationId: string; readonly version: string; }; readonly destinationParent: { readonly id: string; readonly incarnationId: string; readonly version: string; }; } ``` ### `DocumentMoveState` [#documentmovestate] ```ts api="@rolebook/sharing-testkit" interface DocumentMoveState { readonly row: { readonly parentId: string; readonly version: string; readonly revision: string; readonly title: string; } | null; readonly owners: readonly unknown[]; readonly members: readonly unknown[]; readonly parents: readonly unknown[]; readonly receipts: readonly { readonly receiptId: string; readonly result: unknown; }[]; readonly events: readonly { readonly eventId: string; readonly receiptId: string; readonly kind: string; readonly payload: Readonly>; }[]; readonly audits: number; readonly lifecycle: number; } ``` ### `DocumentOperatorAction` [#documentoperatoraction] ```ts api="@rolebook/sharing-testkit" interface DocumentOperatorAction { readonly environmentId: string; readonly eventId: string; readonly actionId: string; readonly generation: string; readonly action: string; readonly operator: { readonly type: string; readonly id: string; } | null; readonly reason: string | null; readonly recordedAt: string; } ``` ### `DocumentMoveDriver` [#documentmovedriver] ```ts api="@rolebook/sharing-testkit" interface DocumentMoveDriver { prepare(id: string, roles: readonly string[]): Promise; move(input: DocumentMoveInput): Promise; rollback(input: DocumentMoveInput): Promise; state(input: DocumentMoveInput): Promise; lookup(input: DocumentMoveInput): Promise; setGeneration(eventId: string, generation: string): Promise; recoveryState(): Promise; failTransition(token: Token): Promise; readonly attributed: Worker; readonly unattributed: Worker; } ``` ### `DocumentMoveEvidence` [#documentmoveevidence] ```ts api="@rolebook/sharing-testkit" interface DocumentMoveEvidence extends DocumentMoveRunEvidence { readonly prior: DocumentLifecycleEvidence; readonly boundary: DocumentMoveRunEvidence; } ``` ### `DocumentMoveRunEvidence` [#documentmoverunevidence] ```ts api="@rolebook/sharing-testkit" interface DocumentMoveRunEvidence { readonly initialGeneration: string; readonly moves: readonly { readonly id: string; readonly input: DocumentMoveInput; readonly status: string; readonly code: string; readonly before: DocumentMoveState; readonly after: DocumentMoveState; }[]; readonly replay: { readonly status: string; readonly sameReceipt: boolean; readonly lookupSame: boolean; readonly conflictCode: string; readonly state: DocumentMoveState; }; readonly history: { readonly eventId: string; readonly transitionSnapshots: readonly DocumentRecoverySnapshot[]; readonly finalSnapshot: DocumentRecoverySnapshot; readonly actions: readonly DocumentOperatorAction[]; readonly pages: readonly { readonly pageSize: number; readonly actions: readonly DocumentOperatorAction[]; readonly exhausted: boolean; }[]; readonly stale: Readonly>; readonly failedTransition: { readonly code: string; readonly before: DocumentRecoverySnapshot; readonly after: DocumentRecoverySnapshot; }; readonly requeued: readonly boolean[]; readonly acknowledged: boolean; readonly claimsAfterAck: number; readonly finalState: DocumentMoveState; readonly finalActions: readonly DocumentOperatorAction[]; }; } ``` ### `DocumentRecoverySnapshot` [#documentrecoverysnapshot] ```ts api="@rolebook/sharing-testkit" interface DocumentRecoverySnapshot { readonly outbox: readonly unknown[]; readonly dead: readonly unknown[]; readonly history: readonly DocumentOperatorAction[]; } ``` `DocumentMoveDriver` is the structural scenario seam. Its internal `MoveResult` requires status and the full receipt (including receiptId/result). `Token` is an environment/event/generation triple. `Worker` combines the existing lifecycle worker operations with bounded `inspectOperatorActions`. Drivers use public authority/outbox APIs for operations and direct reads for persisted evidence. `setGeneration` and `failTransition` are fixture-only hooks for exact-counter and rollback cases; they must never become production worker behavior. # WorkOS (/docs/sharing-workos) > @rolebook/sharing-workos: WorkOS User Management as the source of users and membership, plus Directory Sync groups. `@rolebook/sharing-workos` resolves sharing principals from WorkOS User Management organization memberships and users, and lists a user's Directory Sync groups. It needs `@workos-inc/node` `>=11.0.0 <12`. ```ts import { WorkOS } from "@workos-inc/node"; import { createWorkOSDirectoryReader, createWorkOSIdentityAdapter } from "@rolebook/sharing-workos"; const workos = new WorkOS(process.env.WORKOS_API_KEY!); export const identity = createWorkOSIdentityAdapter({ directory: createWorkOSDirectoryReader(workos), }); ``` `createWorkOSDirectoryReader()` requests `userManagement.listOrganizationMemberships({ organizationId, userId, statuses: ["active"], limit: 2 })` and returns a membership only when the response holds exactly one record whose organization and user IDs both match. It projects the membership's primary role to its slug and keeps its status. Users are projected to `{ id, email, emailVerified }`. WorkOS 404 responses become absence; other errors propagate. ## Behaviour [#behaviour] - Only an `active` membership is eligible. `pending`, `inactive`, any other status, and a role without a slug resolve as ineligible, checked again after the server-side filter. - Only the primary `role` is mapped; additional `roles` are ignored, so the mapper and the authorization fact see exactly one slug a fence can compare. - Each resolution makes two calls (membership and user): the principal is ineligible unless the user still exists with the requested ID. `email` and `emailVerified` are exposed on `principal.attributes`, never to conditions. - **Email-bound invitations always fail closed.** WorkOS is remote, so its email state cannot be locked in the sharing transaction. Issue subject-bound invitations, which compare WorkOS's immutable user ID. - With a role mapper, principals carry `WORKOS_ORGANIZATION_MEMBER_AUTHORIZATION_FACT`. As with Clerk, fence it and the membership against a database-local projection you keep in step with WorkOS. ## Directory Sync groups [#directory-sync-groups] `listUserDirectoryGroups()` returns a frozen, deduplicated list of at most `MAX_DIRECTORY_GROUPS` (100) `{ id, name }` groups for one Directory Sync user within one organization: ```ts import { WorkOS } from "@workos-inc/node"; import { createWorkOSDirectoryGroupReader, listUserDirectoryGroups } from "@rolebook/sharing-workos"; const workos = new WorkOS(process.env.WORKOS_API_KEY!); const groups = await listUserDirectoryGroups({ directory: createWorkOSDirectoryGroupReader(workos), organizationId: "org_123", userId: "directory_user_123", // a Directory Sync user ID, not a User Management user ID }); ``` - The caller must bind the directory user to the principal it already resolved, from a mapping it stored (for example while processing Directory Sync events). Never accept a directory user ID from a client. - Every group must carry the explicit organization ID. A group from another organization or directory, a malformed record, conflicting names for one ID, or more than 100 groups rejects the whole call. A 404 on the first page reads as no groups. - **Directory Sync is eventually consistent.** Access derived from groups lags revocation until WorkOS processes the identity provider's change. Do not rely on directory groups alone where revocation must be immediate. - Directory groups are not wired into `@rolebook/teams`. To use them as teams, mirror the groups that carry access into application tables from Directory Sync events and point [`createSqlTeamDirectory()` and the team fences](/docs/teams#application-owned-tables) at them. Mind the bounds: teams allow 64 per subject, this listing 100. ## Listing accessible resources [#listing-accessible-resources] This adapter answers `authorize()`, `permissions()`, and commands. It does not implement `resolvePagePrincipal`, so on its own it supplies no identity evidence for [`listAccessible()` and `listAccess()`](/docs/sharing/listing#identity): those calls reject with `AccessListingUnavailableError` and the reason `identity_evidence_missing`. A WorkOS lookup cannot be read at the same point as a database page. To list, the sharing instance needs an identity adapter that resolves principals from a complete local identity projection in the same database as the sharing tables: eligibility, assignments, groups, and attributes. Name that adapter object and the projection in the storage adapter's `pageIdentity` option. The option is an attestation that the adapter passed to `createSharing()` answers from exactly that projection, so it must be an adapter that really reads the projection. Do not name this WorkOS adapter as the source of a projection it does not read. Keep the projection synchronized from WorkOS as authoritative data, and advance the row's revision on every change. A sharing instance has one identity adapter, so its checks and commands then use the projection as well. The alternative is an identity adapter of your own that implements `resolvePagePrincipal` over a source with a revision that never repeats and changes on every relevant change. See [identity for listing](/docs/sharing/listing#identity). ## What every identity adapter guarantees [#what-every-identity-adapter-guarantees] All three provider adapters are configurations of [`createWorkspaceIdentityAdapter()`](/docs/sharing/adapters#createworkspaceidentityadapter), so they enforce the same rules: - Every membership lookup receives the explicit organization (tenant) ID and user ID. There is no session or active-organization input. - Organization membership is eligibility only. No Rolebook assignment is emitted unless you supply `mapWorkspaceAssignments`, and then each mapped assignment must target the canonical subject, a role of at most 128 characters, the configured workspace resource type with the explicit tenant ID, and `appliesTo` `"self"` or `"descendants"`; anything else throws. - Records are copied (each field read once) before they are validated, so a cache-backed record cannot answer two checks differently. - The Rolebook subject is the canonical `{ type, id }` only (default type `"user"`, workspace resource type `"workspace"`). Profile data never reaches conditions. - Invitation matching requires an eligible principal in canonical form and rechecks current membership. - Provider organization invitations are never created or replaced: resource invitations are separate. - The member-removed handler validates and freezes the event for cleanup code. It is not an authorization fence: every sharing operation checks current membership. ## API [#api] `import { ... } from "@rolebook/sharing-workos"`. Signatures are checked against the built declarations. ## Identity [#identity] ### `createWorkOSIdentityAdapter` [#createworkosidentityadapter] ```ts api="@rolebook/sharing-workos" function createWorkOSIdentityAdapter( options: WorkOSIdentityAdapterOptions, ): TenantIdentityAdapter; ``` Builds the `TenantIdentityAdapter`. Always loads the user while resolving. ### `WorkOSIdentityAdapterOptions` [#workosidentityadapteroptions] ```ts api="@rolebook/sharing-workos" interface WorkOSIdentityAdapterOptions { readonly directory: WorkOSDirectoryReader; readonly subjectType?: string; readonly workspaceResourceType?: string; readonly mapWorkspaceAssignments?: (input: { readonly tenantId: string; readonly subject: ResourceRef; readonly member: WorkspaceMemberRecord; }) => readonly RoleAssignment[]; } ``` `directory` (required), `subjectType`, `workspaceResourceType`, `mapWorkspaceAssignments`. ### `createWorkOSDirectoryReader` [#createworkosdirectoryreader] ```ts api="@rolebook/sharing-workos" function createWorkOSDirectoryReader(client: WorkOSDirectoryClient): WorkOSDirectoryReader; ``` A reader over the WorkOS SDK's `userManagement`. ### `WorkOSDirectoryClient` [#workosdirectoryclient] ```ts api="@rolebook/sharing-workos" type WorkOSDirectoryClient = Pick; ``` ### `WorkOSDirectoryReader` [#workosdirectoryreader] ```ts api="@rolebook/sharing-workos" interface WorkOSDirectoryReader { getOrganizationMembership(input: { readonly organizationId: string; readonly userId: string; }): Promise; getUser(input: { readonly userId: string }): Promise; } ``` Exact membership and user lookups. ### `WorkOSOrganizationMembershipRecord` [#workosorganizationmembershiprecord] ```ts api="@rolebook/sharing-workos" interface WorkOSOrganizationMembershipRecord { readonly id: string; readonly organizationId: string; readonly userId: string; readonly role: string; readonly status: WorkOSOrganizationMembershipStatus; } ``` A membership projected to its primary role slug and status. ### `WorkOSOrganizationMembershipStatus` [#workosorganizationmembershipstatus] ```ts api="@rolebook/sharing-workos" type WorkOSOrganizationMembershipStatus = "active" | "inactive" | "pending"; ``` Only `active` is eligible. ### `WorkOSUserRecord` [#workosuserrecord] ```ts api="@rolebook/sharing-workos" interface WorkOSUserRecord { readonly id: string; readonly email: string; readonly emailVerified: boolean; } ``` ### `WORKOS_ORGANIZATION_MEMBER_AUTHORIZATION_FACT` [#workos_organization_member_authorization_fact] ```ts api="@rolebook/sharing-workos" const WORKOS_ORGANIZATION_MEMBER_AUTHORIZATION_FACT = "rolebook.workos.organization-member.v1"; ``` The fact type for the workspace-role fact fence. ### `createWorkOSMemberRemovedHandler` [#createworkosmemberremovedhandler] ```ts api="@rolebook/sharing-workos" function createWorkOSMemberRemovedHandler(input: { readonly onMemberRemoved: (event: WorkOSMemberRemovedEvent) => void | Promise; }): (event: WorkOSMemberRemovedEvent) => Promise; ``` Validates and freezes a translated `organization_membership.deleted` event for cleanup. ### `WorkOSMemberRemovedEvent` [#workosmemberremovedevent] ```ts api="@rolebook/sharing-workos" interface WorkOSMemberRemovedEvent { readonly organizationId: string; readonly userId: string; } ``` ## Directory Sync [#directory-sync] ### `listUserDirectoryGroups` [#listuserdirectorygroups] ```ts api="@rolebook/sharing-workos" function listUserDirectoryGroups(input: { readonly directory: WorkOSDirectoryGroupReader; readonly organizationId: string; readonly userId: string; }): Promise; ``` One Directory Sync user's groups within one organization, validated and bounded. ### `createWorkOSDirectoryGroupReader` [#createworkosdirectorygroupreader] ```ts api="@rolebook/sharing-workos" function createWorkOSDirectoryGroupReader( client: WorkOSDirectorySyncClient, ): WorkOSDirectoryGroupReader; ``` A reader over the SDK's `directorySync.listGroups`, following cursors explicitly. ### `WorkOSDirectorySyncClient` [#workosdirectorysyncclient] ```ts api="@rolebook/sharing-workos" type WorkOSDirectorySyncClient = Pick; ``` ### `WorkOSDirectoryGroupReader` [#workosdirectorygroupreader] ```ts api="@rolebook/sharing-workos" interface WorkOSDirectoryGroupReader { listDirectoryGroups(input: { readonly organizationId: string; readonly userId: string; }): Promise; } ``` ### `WorkOSDirectoryGroupRecord` [#workosdirectorygrouprecord] ```ts api="@rolebook/sharing-workos" interface WorkOSDirectoryGroupRecord { readonly id: string; readonly directoryId: string; readonly organizationId: string | null; readonly name: string; } ``` ### `DirectoryGroup` [#directorygroup] ```ts api="@rolebook/sharing-workos" interface DirectoryGroup { readonly id: string; readonly name: string; } ``` ### `MAX_DIRECTORY_GROUPS` [#max_directory_groups] ```ts api="@rolebook/sharing-workos" const MAX_DIRECTORY_GROUPS = 100; ``` The most groups one listing returns. ### `MAX_DIRECTORY_GROUP_NAME_LENGTH` [#max_directory_group_name_length] ```ts api="@rolebook/sharing-workos" const MAX_DIRECTORY_GROUP_NAME_LENGTH = 256; ``` The longest group name accepted. ### `WORKOS_MAX_PAGE_SIZE` [#workos_max_page_size] ```ts api="@rolebook/sharing-workos" const WORKOS_MAX_PAGE_SIZE = 100; ``` WorkOS's page maximum, used as the page size. # Storage and identity adapters (/docs/sharing/adapters) > The SharingAdapter and TenantIdentityAdapter contracts, the workspace identity factory, and the in-memory adapter. The sharing module talks to the outside world through two interfaces: a **storage adapter** per resource type (`SharingAdapter`) and one **identity adapter** (`TenantIdentityAdapter`). The first-party packages implement both; this page is for choosing between them and for writing your own. ## Storage adapters [#storage-adapters] | Adapter | Use | | --- | --- | | [`createPostgresSharingAdapter`](/docs/sharing-postgres) | Production on PostgreSQL. | | [`createSqliteSharingAdapter`](/docs/sharing-sqlite) | Production on SQLite: local-first, edge, desktop. | | `createMemorySharingAdapter` | Tests and fixtures only. | A `SharingAdapter` owns one concrete resource table's sharing state. Its methods: | Method | Contract | | --- | --- | | `readAccess` | One resource's authoritative snapshot: the trusted resource, its version, the sharing revision, the owner, memberships (only of `requestingPrincipals` when given), and the incarnation ID. Fences `requiredEligibleSubjects` in the same read. Leaves out expired memberships. | | `readAccessBatch` | The same for up to 200 resources in one consistent read; rejects more. | | `readInvitation` | One invitation by ID. | | `listPendingInvitations` | Unconsumed, unrevoked invitations in `(createdAt, id)` order, for the given incarnation, or `undefined` when it is no longer live. | | `listAuditEvents` | One page of the incarnation's audit events, newest first, with a raw cursor. | | `readMutationIdempotency` | Looks up a committed idempotency record without changing state. | | `applyMutation` | Applies one mutation atomically, conditional on the expected resource version and sharing revision, fencing eligible subjects, authorization facts, and (when fenced) the policy generation, with the audit event and idempotency record in the same commit. | | `listCandidates` | One page of candidate resource IDs for listing, with cursors; honours the narrowing hints. | | `resourceDeleted`, `resourceMoved` | Standalone lifecycle conveniences, or `"unsupported"`. | The details that matter for correctness: - **Eligibility is held, not just checked.** `requiredEligibleSubjects` names subjects whose current tenant eligibility the adapter must hold for the whole read or mutation. PostgreSQL does it with a `SERIALIZABLE` transaction and `FOR SHARE` row locks; SQLite with the write lock of `BEGIN IMMEDIATE`. - **Authorization facts.** A principal's `authorizationFacts` (mapped workspace roles, team memberships) travel with mutations as `requiredAuthorizationFacts`. An adapter must lock and compare every one in the transaction, and fail closed (`identity_ineligible`) when it has no fence for them. - **Fences fail closed.** A fence callback result counts as eligible only when it is literally `true`. - **Expiry.** Reads leave out memberships at or past `expiresAt`; grants and invitation consumption replace an expired row; `changeRole` keeps, sets, or clears the expiry; `revokeMember` deletes an expired row. - **Output is captured.** Pages and candidates must be plain records with at most 16 own data properties; accessors, class instances, and holes are `InvalidCandidatePageError`. Return frozen object literals. - **Cursors.** `listCandidates` must throw `InvalidCursorError` for anything but `undefined` or a non-empty string of at most 128 characters, and every non-exhausted page must return a usable, advancing `nextCursor`. - **Listing pages.** `listAccessible()` and `listAccess()` do not call `listCandidates` and `readAccessBatch` directly. They read each page through the optional `runConsistentPage`, which opens one snapshot, runs the candidate and hydration reads inside it, and seals every expiry the page depended on. The first-party adapters implement it, each on a specific executor. A custom adapter without it answers `capability_missing` for both listings. See [what a consistent page requires](/docs/sharing/listing#what-a-consistent-page-requires). - **Eligibility evidence for pages.** A page proves tenant eligibility inside its snapshot without locks, through a reader that returns `{ eligible, expiryDependencies }` from the same authority as the fence. `createPostgresMembershipEligibilityFence()` and `createSqliteMembershipEligibilityFence()` carry their own reader, as do the `lockEligibleSubjects` fences of the PostgreSQL and SQLite local identity projections. Every other fence needs a matching `readEligibleSubjects` on the adapter. That includes a fence you write yourself, a function that wraps one of the fences above, and the team fences from `createPostgresTeamFences()` and `createBetterAuthTeamFences()`, which carry no reader; see [listing with teams](/docs/teams#listing-with-teams). Without the evidence, listings answer `identity_evidence_missing`. Run [`@rolebook/sharing-testkit`](/docs/sharing-testkit) against any adapter you write: it is the executable form of this contract. ### The in-memory adapter [#the-in-memory-adapter] `createMemorySharingAdapter(options)` exists for the contract kit and local fixtures. It holds no transaction and takes no locks. Configure `fenceEligibleSubjects` to have it re-check eligibility at the points the PostgreSQL adapter locks it; without it, every supplied subject counts as eligible. Even fenced, the check is a re-read rather than a lock, so a concurrent revocation can still interleave. It is not a production adapter. ```ts import { createMemorySharingAdapter, type SharingClock } from "@rolebook/sharing"; import { trustedResource } from "rolebook"; const clock: SharingClock = { now: () => new Date("2026-11-01T00:00:00Z") }; const members = new Set(["user_123", "user_789"]); const projects = createMemorySharingAdapter({ clock, // pass the same clock to createSharing() fenceEligibleSubjects: ({ subjects }) => subjects.every((subject) => members.has(subject.id)), }); projects.seed({ tenantId: "ws_456", resourceId: "project_1", resource: trustedResource({ type: "project", id: "project_1" }, [{ type: "workspace", id: "ws_456" }]), owner: { type: "user", id: "user_123" }, memberships: [{ subject: { type: "user", id: "user_789" }, role: "viewer" }], }); ``` `seed()` starts a new incarnation and records a `resource.initialized` audit event; `readAudit()` returns every audit event; `advanceResourceVersion()` simulates an application change to the resource. Other options: `fenceInvitationRecipient` (required for email invitations), `revalidateAuthorizationFacts` (required for mutations authorized by mapped roles or teams), `groupSubjectTypes` (default `["team"]`), and `fencePolicy` for versioned sharing. Share one clock between the adapter and `createSharing()`: both check expiry. For `listAccessible()` and `listAccess()`, an adapter configured with `fenceEligibleSubjects` also needs `readEligibleSubjects`, the same answer as synchronous evidence (`{ eligible, expiryDependencies }`, judged at the `evaluatedAt` it is given). The identity adapter must supply identity evidence as well; the simplest way in a fixture is a synchronous `capturePagePrincipal`. See [listing page evidence](#listing-page-evidence). ## Identity adapters [#identity-adapters] A `TenantIdentityAdapter` answers two questions, always for an explicit tenant: ```ts import type { TenantIdentityAdapter, TenantPrincipal } from "@rolebook/sharing"; declare function isActiveMember(tenantId: string, userId: string): Promise; const identity: TenantIdentityAdapter = { async resolvePrincipal({ tenantId, subject }): Promise { const eligible = subject.type === "user" && (await isActiveMember(tenantId, subject.id)); return { eligible, subject: { type: subject.type, id: subject.id }, tenantScope: { type: "workspace", id: tenantId }, assignments: [], // workspace membership grants no private-resource access by itself }; }, async matchesInvitationRecipient({ principal, recipient }) { return ( principal.eligible === true && recipient.type === "subject" && recipient.subject.type === principal.subject.type && recipient.subject.id === principal.subject.id ); }, }; ``` `resolvePrincipal` returns a `TenantPrincipal`: | Field | Meaning | | --- | --- | | `eligible` | Whether the subject is a current member of exactly this tenant. | | `subject` | The canonical `{ type, id }`, plus optional attributes Rolebook conditions read. | | `tenantScope` | The tenant resource reference; its ID must equal the explicit tenant ID. | | `assignments` | Explicit workspace-scoped Rolebook assignments. Empty is the safe default. | | `authorizationFacts` | Provider facts behind those assignments or attributes, revalidated by the storage adapter in every mutation. Assignments require at least one subject-scoped fact. | | `attributes` | Application metadata. Never passed to conditions. | | `groups` | The subject's current flat group principals (teams), at most 64. | | `group` | `true` when the principal is itself a group, resolved as a grant or invitation target. | Never derive the tenant from a session's active organization: every lookup must use the explicit tenant ID. An identity adapter may throw; the module does not catch it, and the operation rejects. ### Listing page evidence [#listing-page-evidence] `resolvePrincipal` and `matchesInvitationRecipient` are all that `authorize()`, `permissions()`, and commands need. [`listAccessible()` and `listAccess()`](/docs/sharing/listing#identity) read each page at one coherent point and also need evidence that the principal belongs to that point. An identity adapter that works for `authorize()` does not qualify for listing on that basis. There are three ways to supply the evidence: - **A local projection, attested on the storage adapter.** The PostgreSQL and SQLite adapters take a `pageIdentity` option naming the identity adapter object given to `createSharing()` and the local identity projection it answers from. The page then reads the projection row inside its own transaction. The option is an attestation: that identity adapter must actually resolve principals from exactly that projection, complete with assignments, groups, attributes, and authorization facts. Naming an adapter that resolves from a remote provider, or a wrapper around one, as the source of a projection it does not read is a false attestation, and Rolebook cannot detect it. The projection has to be kept synchronized as authoritative data, with a revision that advances on every change. - **`resolvePagePrincipal`**, an optional method for a source outside the database. It returns the complete principal with an `epoch`, a `revision` that never repeats within the epoch and changes on every relevant change, and the expiry of every time-sensitive fact. Rolebook calls it before the page's snapshot opens and after the page was read and accepts the page only when both answers are identical. Implement it only over a source that really has such a revision. - **`capturePagePrincipal`**, an optional synchronous method for the in-memory adapter. It returns `{ principal, expiryDependencies }` from in-process state, judged at the `evaluatedAt` it is given, with no I/O. With none of these, listings reject with `AccessListingUnavailableError` and the reason `identity_evidence_missing`. ### `createWorkspaceIdentityAdapter` [#createworkspaceidentityadapter] The Better Auth, Clerk, and WorkOS adapters are configurations of one shared implementation, exported so you can build your own provider adapter with the same rules: ```ts import { createWorkspaceIdentityAdapter, type WorkspaceMemberRecord } from "@rolebook/sharing"; interface AppUser { readonly id: string; readonly email: string; readonly emailVerified: boolean; } declare function findMember(organizationId: string, userId: string): Promise; declare function findUser(userId: string): Promise; const identity = createWorkspaceIdentityAdapter({ authorizationFactType: "app.workspace-member.v1", getMember: ({ organizationId, userId }) => findMember(organizationId, userId), getUser: ({ userId }) => findUser(userId), snapshotUser: (user) => ({ id: user.id, email: user.email, emailVerified: user.emailVerified }), verifiedEmail: (user) => (user.emailVerified ? user.email : undefined), }); ``` - Every membership lookup receives the explicit tenant and subject IDs, and the returned record is copied (each field read once) before it is checked. - `mapWorkspaceAssignments` explicitly maps a provider role to workspace assignments; the default emits none. Mapped assignments must target the subject, a bounded role, and the tenant scope, or the factory throws. A `TransactionalAuthorizationFact` with the member ID and role accompanies them. - With `requireUser`, the user is also loaded while resolving, and the principal is ineligible unless it exists; otherwise the user is loaded only to match an email invitation. `principalAttributes` requires `requireUser`. - `snapshotUser` must return a new object: a throw, `undefined`, or the input itself counts as a missing user. A throwing `verifiedEmail` counts as no verified address. - Invitation matching requires `eligible === true`, the canonical subject, and current membership. Email recipients compare the verified address after normalization, both bounded by 320 characters. An adapter built with this factory, including the Better Auth, Clerk, and WorkOS adapters, has `resolvePrincipal` and `matchesInvitationRecipient` only. It supplies no [listing page evidence](#listing-page-evidence) on its own. `createWorkspaceMemberRemovedHandler({ provider, onMemberRemoved })` validates and freezes a provider's member-removal notification before your cleanup code sees it. It is cleanup only: current membership is still checked on every sharing operation. ## Identity and storage must agree [#identity-and-storage-must-agree] The identity adapter's answer is a preflight. The storage adapter's fences make it hold until commit: a membership removal either commits first and the mutation fails, or waits for the already-authorized mutation. That works only when the authoritative membership rows are in the **same database** as the sharing tables. A remote provider (Clerk, WorkOS) cannot be locked by your transaction: keep a database-local projection of memberships whose lifecycle you coordinate with removals, and point the fences at it. See the provider pages for details. # @rolebook/sharing API (/docs/sharing/api) > Every export of @rolebook/sharing, with its signature and behaviour. `import { ... } from "@rolebook/sharing"`. Signatures are checked against the package's built declarations. For concepts and usage, start at [Resource sharing](/docs/sharing). ## Creating sharing [#creating-sharing] ### `defineSharing` [#definesharing] ```ts api="@rolebook/sharing" function defineSharing< const TPolicy extends RolebookPolicy, const TResources extends SharingResourceConfigurations< PolicyRole, PolicyPermission >, >(input: { readonly policy: TPolicy; readonly resources: TResources; }): SharingDefinition; ``` Validates the catalog that maps storage labels to policy values, canonicalizes the policy as `definePolicy()` does, and freezes the result. Throws an `Error` for an unknown or non-lowercase resource type, an ownership or member role that is missing or at another scope, the ownership role listed as a member role, an empty `memberRoles` or `actions`, or an action or management permission that is not a concrete, declared permission of the type. `management.inspect` defaults to `management.members`. See [define and create](/docs/sharing/setup#definesharing). ### `createSharing` [#createsharing] ```ts api="@rolebook/sharing" function createSharing( options: CreateSharingOptions, ): ResourceSharingWithDiagnostics; ``` Creates the sharing module over the definition's exact policy, with one Rolebook authorizer. The definition is validated again. Options are captured once; throws for an invalid `mutationRetries`, `mutationBackoffMs`, `mutationWait`, `maxInvitationTtlMs`, or cursor key, and a `TypeError` for invalid `diagnostics`. The returned instance also has a synchronous, factory-local [`diagnostics()`](#sharingdiagnostics) snapshot. ### `CreateSharingOptions` [#createsharingoptions] ```ts api="@rolebook/sharing" interface CreateSharingOptions { readonly definition: SharingDefinition, TResources>; readonly identity: TenantIdentityAdapter; readonly invitationTokens: InvitationTokenProtector; readonly clock?: SharingClock; readonly ids?: SharingIdGenerator; readonly mutationRetries?: number; readonly mutationBackoffMs?: (retry: number) => number; readonly mutationWait?: (milliseconds: number) => Promise; readonly maxInvitationTtlMs?: number; readonly listingCursorKey?: string | Uint8Array | readonly (string | Uint8Array)[]; readonly inspection?: { readonly audit: InspectionAuditSink; readonly limiter: InspectionLimiter; }; readonly diagnostics?: SharingDiagnosticsOptions | undefined; readonly governance?: GovernanceAttachment; } ``` See [the options table](/docs/sharing/setup#createsharing). `mutationRetries` is an integer from 0 to 10 (default 3); `maxInvitationTtlMs` defaults to 30 days; `listingCursorKey` is one key or an ordered list of at most 8. `inspection` enables [`explain`](/docs/sharing/inspection); omit it to leave inspection disabled. When it is present, construction throws a `TypeError` unless `audit.append` and `limiter.acquire` are functions. `diagnostics` enables [operational diagnostics](#operational-diagnostics); omit it and every operation, promise and rejection is exactly as without it. ### `createVersionedSharing` [#createversionedsharing] ```ts api="@rolebook/sharing" function createVersionedSharing( options: CreateVersionedSharingOptions, ): Promise>; ``` Async constructor of sharing that evaluates the policy store's active policy and per-tenant custom roles. Refuses to start (`PolicyStoreError`) unless every adapter reports `policyFence: "enforced"`. See [policy versions](/docs/sharing/versioned). ### `CreateVersionedSharingOptions` [#createversionedsharingoptions] ```ts api="@rolebook/sharing" interface CreateVersionedSharingOptions< TResources extends SharingResourceConfigurations = SharingResourceConfigurations, > extends CreateSharingOptions { readonly policyStore: PolicyStore; readonly refreshIntervalMs?: number; readonly maxStalenessMs?: number; readonly seed?: "activate-if-empty" | "require-active"; readonly requiredPolicyRoles?: readonly string[]; readonly tenantCacheSize?: number; readonly monotonicNow?: () => number; readonly onSeedDrift?: (input: { readonly seedDigest: string; readonly activeDigest: string; readonly generation: string; }) => void; readonly onInternalError?: PolicyErrorReporter; } ``` `CreateSharingOptions` plus the policy store and freshness settings: `refreshIntervalMs` (100 to 60,000, default 5,000), `maxStalenessMs` (up to 300,000, default 30,000, clamped up to the refresh interval), `seed` (default `"activate-if-empty"`), `requiredPolicyRoles`, `tenantCacheSize` (1 to 65,536, default 1,024), `monotonicNow`, `onSeedDrift`, and `onInternalError`. ### `PolicyErrorReporter` [#policyerrorreporter] ```ts api="@rolebook/sharing" type PolicyErrorReporter = ( error: unknown, context: { readonly reason: PolicyUnavailableReason; readonly tenantId?: string; }, ) => void; ``` Receives the original error behind a `PolicyUnavailableError`, once per failed load, with the reason it was reported under. `tenantId` is present when the failure was loading that tenant's custom roles. A reporter that throws or rejects is ignored and cannot change the outcome. ### `VersionedResourceSharing` [#versionedresourcesharing] ```ts api="@rolebook/sharing" interface VersionedResourceSharing extends ResourceSharing { readonly policies: PolicyAdministration; readonly customRoles: CustomRoleAdministration; current(): ActivePolicyState; refresh(): Promise; } ``` `ResourceSharing` plus `policies` and `customRoles` administration, `current()` (the active policy state, synchronously) and `refresh()` (re-reads the pointer now). ### `VersionedResourceSharingWithDiagnostics` [#versionedresourcesharingwithdiagnostics] ```ts api="@rolebook/sharing" interface VersionedResourceSharingWithDiagnostics extends VersionedResourceSharing, SharingDiagnosticsSource {} ``` What `createVersionedSharing()` returns. One diagnostics recorder serves the instance for its whole lifetime: a policy activation, a tenant reload or a refresh never resets it. ### `ResourceSharing` [#resourcesharing] ```ts api="@rolebook/sharing" interface ResourceSharing { forTenant(context: TenantContext): TenantSharing; readonly inspectionEnabled?: boolean; } ``` The module: `forTenant(context)` returns a `TenantSharing` bound to one tenant and actor. `inspectionEnabled` is `true` exactly when the instance was created with a valid `inspection` configuration, and is fixed for the instance's lifetime. `createSharing()` and `createVersionedSharing()` always set it. Absent, as on an older structural implementation of the interface, it means disabled. ### `ResourceSharingWithDiagnostics` [#resourcesharingwithdiagnostics] ```ts api="@rolebook/sharing" interface ResourceSharingWithDiagnostics extends ResourceSharing, SharingDiagnosticsSource {} ``` What `createSharing()` returns. `ResourceSharing` itself is unchanged, so a structural or third-party implementation does not need `diagnostics()`. ### `TenantSharing` [#tenantsharing] ```ts api="@rolebook/sharing" interface TenantSharing { authorize>(input: { readonly resource: ResourceKey; readonly action: ActionFor; }): Promise; execute>(command: SharingCommand): Promise; readonly conditionalExecution?: true; lookupExecution?>(command: SharingCommand): Promise; readonly governance?: GovernedSharing; listAccessible>(input: { readonly type: TType; readonly action: ActionFor; readonly limit: number; readonly cursor?: string; }): Promise>; describeAccess>(input: { readonly resource: ResourceKey; }): Promise, TType>>; permissions>(input: { readonly resource: ResourceKey; }): Promise, TType>>; listAccess>(input: { readonly type: TType; readonly limit: number; readonly cursor?: string; }): Promise, TType>>; auditHistory>(input: { readonly resource: ResourceKey; readonly limit: number; readonly cursor?: string; }): Promise>; explain(input: { readonly resource: ResourceKey; readonly action: string; readonly subject?: ResourceRef; readonly field?: string; }): Promise; } ``` The tenant-scoped operations: [`authorize`](/docs/sharing/reads#authorize), [`execute`](/docs/sharing/commands), [`listAccessible`](/docs/sharing/listing), [`describeAccess`](/docs/sharing/reads#describeaccess), [`permissions`](/docs/sharing/reads#permissions), [`listAccess`](/docs/sharing/listing#everything-the-actor-can-do-by-type), [`auditHistory`](/docs/sharing/reads#audithistory), and [`explain`](/docs/sharing/inspection). The context is captured when the facade is created. `explain`'s input is not narrowed by the catalog's types; it is validated at run time, and an unknown type or action answers `INVALID_REQUEST`. `explain` and `listAccess` are required members. A `TenantSharing` built by hand, such as a wrapper or a test double, must add both and decide what each does, normally forwarding to the same bound tenant: `listAccess: (input) => tenant.listAccess(input)`. `conditionalExecution` is `true` on every tenant `createSharing()` and `createVersionedSharing()` build: their `execute` honours a command's [`expectedSharingRevision`](#sharingcommandprecondition). `@rolebook/server` and the Better Auth plugin run an HTTP `sharing.executeIfUnchanged` request only on a tenant whose `conditionalExecution` reads as exactly `true`. For any other tenant (one built by hand, a wrapper that rebuilds the object without the flag, or one from an older `@rolebook/sharing`) they answer 404 `UNKNOWN_OPERATION`, as a server without the operation does, and never call `execute`, so a runtime that would ignore the precondition never applies a conditional command unconditionally. In-process `execute()` calls do not consult the flag. A wrapper that spreads a tenant keeps the flag, and must then pass commands to `execute` unchanged. `lookupExecution(command)` reads what an earlier `execute` of the same command left in Sharing's idempotency record, and executes nothing: it never calls the adapter's `applyMutation`, and changes no membership, revision or audit event. Pass the command `execute` was given; its idempotency key, resource and every field the idempotency fingerprint covers bind the lookup, together with the tenant and actor of this facade. `expectedSharingRevision` does not. It runs the gates `execute` runs before a versioned instance replays a record: a configured resource type, a well-formed tenant and actor, and an actor the identity adapter resolves as a tenant member. The record is then read through the adapter's [`lookupMutationIdempotency`](#sharingadapter), a pure read: on the memory, SQLite and PostgreSQL adapters that read takes no lock a writer takes, runs on a read-only connection, and writes nothing, not even the bookkeeping a writer creates for a tenant or resource that has no rows yet. It does not take the replay's writer route, so on a tenant whose hierarchy enrollment has started it reads nothing and answers `refused` with `HIERARCHY_UNAVAILABLE`. Only that read is lock-free. The call as a whole may also resolve the actor through the identity adapter; on a versioned instance, load the tenant's policy, which reads the policy store (on SQLite in a `BEGIN IMMEDIATE` transaction, on PostgreSQL with `FOR SHARE` on the policy pointer); and, when the key holds another command's record, check the actor's access through `permissions`, which runs the membership fence (on PostgreSQL a `SELECT … FOR SHARE`). On PostgreSQL every read runs in a SERIALIZABLE transaction, so none of it runs on a hot standby. Nothing here writes. An access check that fails, as one does in a read-only PostgreSQL transaction, answers as one that denies: `not_found`, so an actor without access gets the same answer for another command's record as for an unused key in every case. As with a replay, an exact fingerprint match answers `committed` to the actor who committed the command even after that actor has lost access to the resource. Only `committed` proves anything; see [`SharingExecutionLookupResult`](#sharingexecutionlookupresult). `createSharing()` and `createVersionedSharing()` tenants have it when every resource adapter implements `lookupMutationIdempotency`, as the first-party adapters do; it is optional on the interface, so a tenant built by hand, over another adapter, or from an older `@rolebook/sharing` may not, and a wrapper that spreads a tenant keeps it. Its calls are not counted in the [diagnostics](#operational-diagnostics) snapshot. `governance` is the server-side façade on that tenant. Its six methods are `request(command)`, `approve(requestId)`, `reject(requestId)`, `cancel(requestId)`, `apply(requestId)`, and `resolve(requestId)`. Each returns precisely `{ status }`, where `status` is `PENDING`, `APPROVED`, `REJECTED`, `APPLIED`, `VOID`, `REFUSED`, `UNAVAILABLE`, or `UNKNOWN_REQUEST`. A transfer is authorized in one of two modes, and recipient acceptance is not required. A non-owner request requires a counted direct-owner sponsor. An owner request records payload-bound, non-counting owner consent and needs an independent eligible quorum. Direct `execute()` returns `GOVERNANCE_REQUIRED` whenever governance applies and does not bypass approval effects. ### `TenantContext` [#tenantcontext] ```ts api="@rolebook/sharing" interface TenantContext { readonly tenantId: string; readonly actor: ResourceRef; } ``` The explicit tenant ID and the authenticated actor. A malformed tenant or actor fails closed before any callback runs. ## Operational diagnostics [#operational-diagnostics] Optional, factory-local and redacted. With `diagnostics` set, each call to a `TenantSharing` method is observed exactly once, at the public boundary, after any versioned conversion (a `PolicyUnavailableError` that `execute` returns as `POLICY_UNAVAILABLE` is a returned `unavailable` result, not a rejection). A rejection is only classified `rejected`: the caller still receives the identical exception object, a synchronous throw stays synchronous, and a floating failed call is still exactly one unhandled rejection. Mutation retries and candidate scans are separate intermediate events and never count as final results. Durations come from a separately captured `performance.now`, never the sharing clock or `monotonicNow`; a faulty reading is `timing: "unavailable"`, never NaN, infinite or negative. Observations carry fixed enums and counts only: no tenant, actor, resource, role, action or query names, IDs, tokens, cursors, revisions, policy versions, decisions, traces, context, facts or exception text. The observer gets one call at a time from a later timer turn, as a plain function. Observations wait in a FIFO of at most `queueLimit`; the oldest drops first and drops are counted. A call that exceeds `observerTimeoutMs` is reported as timed out but never cancelled: it keeps the single slot until it settles, and there is no abort signal. Synchronous CPU work in the observer cannot be preempted in the same process, so the observer must return or yield promptly. A throwing or rejecting observer is counted as `failed` and changes nothing else. Calls the observer makes into the same instance are recorded and queued, never delivered recursively. At most one observation is delivered per timer turn, so a burst larger than `queueLimit` drops the oldest even when the observer resolves at once. The snapshot counters are updated before an observation is queued, so they still count every processed event when observations drop. The observer runs from a timer that this or another call scheduled, so ambient asynchronous context (`AsyncLocalStorage`, OpenTelemetry) may belong to an unrelated request; Rolebook does not detach it. Never add tenant, request, subject or trace identifiers from ambient context to an exported observation, and never treat that context as the event's attribution. The snapshot describes this instance in this process. It is not global or production health, not an authorization, admission, fencing or retry input, and it proves nothing about reachability, current permission, completeness or backlog. Counts saturate at `Number.MAX_SAFE_INTEGER`. See the [runbook](https://github.com/Amakinto-Labs/rolebook/blob/qa/docs/SHARING_DIAGNOSTICS.md). ```ts import { createSharing, type CreateSharingOptions } from "@rolebook/sharing"; declare const options: CreateSharingOptions; declare const metrics: { increment(name: string, labels: Record): void }; const sharing = createSharing({ ...options, diagnostics: { observe(observation) { if (observation.type === "operation") metrics.increment("rolebook.sharing.operation", { operation: observation.operation, result: observation.result, }); }, }, }); const snapshot = sharing.diagnostics(); snapshot.operations.authorize.rejected; ``` ### `SharingDiagnosticsOptions` [#sharingdiagnosticsoptions] ```ts api="@rolebook/sharing" interface SharingDiagnosticsOptions { readonly observe?: SharingObserver; readonly queueLimit?: number; readonly observerTimeoutMs?: number; } ``` Exactly these keys, as own enumerable data properties of a plain object; an accessor is rejected without being invoked, and `null`, unknown keys and symbols are rejected. `observe` is optional: without it the instance only counts. `queueLimit` is an integer 1–1024 (default 64); `observerTimeoutMs` an integer 1–60,000 (default 1,000), reporting only. Every failure is `TypeError("Invalid sharing diagnostics options")`. ### `SharingObserver` [#sharingobserver] ```ts api="@rolebook/sharing" type SharingObserver = (observation: SharingObservation) => void | PromiseLike; ``` Diagnostics only: nothing awaits it or uses its result. ### `SharingObservation` [#sharingobservation] ```ts api="@rolebook/sharing" type SharingObservation = | SharingOperationObservation | SharingRetryObservation | SharingScanObservation; ``` `sequence` is a local ordinal per instance; a gap means dropped observations. ### `SharingOperationObservation` [#sharingoperationobservation] ```ts api="@rolebook/sharing" interface SharingOperationObservation { readonly type: "operation"; readonly sequence: number; readonly operation: SharingOperationName; readonly settlement: "returned" | "rejected"; readonly result: SharingResultClass; readonly code: SharingResultCode | "unknown" | null; readonly timing: "measured" | "unavailable"; readonly durationMs: number | null; } ``` One settled public call. `code` is a known public code, `"unknown"` for a returned value this build does not recognise, or `null` for a page or a rejection. Classification reads only own data properties (`allowed`, `ok`, `code`, `resources`, `exhausted`) and never invokes a getter. A duration is an observation, not a performance bound. ### `SharingOperationName` [#sharingoperationname] ```ts api="@rolebook/sharing" type SharingOperationName = | "authorize" | "execute" | "listAccessible" | "listAccess" | "describeAccess" | "permissions" | "auditHistory" | "explain"; ``` ### `SharingResultClass` [#sharingresultclass] ```ts api="@rolebook/sharing" type SharingResultClass = | "allowed" | "denied" | "succeeded" | "refused" | "unavailable" | "page" | "unknown" | "rejected"; ``` `allowed` and `denied` exist only for `authorize`. `refused` is any other known `ok: false` code; `unavailable` is `POLICY_UNAVAILABLE`, `RATE_LIMITED` or `INSPECTION_UNAVAILABLE`. `unknown` is never read as an allow or a deny. `rejected` means the call threw or rejected; it mixes caller and input errors with operational faults, is not an authorization denial, and does not say which dependency failed. On a versioned instance an unusable policy is classified per method: `execute` returns `POLICY_UNAVAILABLE` (`unavailable`); `authorize`, `describeAccess`, `permissions` and `auditHistory` reject with `PolicyUnavailableError` (`rejected`); `listAccessible` and `listAccess` reject with it for a sticky or per-tenant failure and otherwise with `AccessListingUnavailableError` (`rejected`); `explain` returns `INSPECTION_UNAVAILABLE` (`unavailable`), a code that also covers limiter, audit, identity and deadline faults. A malformed context or request answers before any policy load. ### `SharingResultCode` [#sharingresultcode] ```ts api="@rolebook/sharing" type SharingResultCode = | SharingDecision["code"] | SharingMutationResult["code"] | AccessDescriptionResult["code"] | ResourcePermissionsResult["code"] | AuditHistoryResult["code"] | InspectionResult["code"]; ``` ### `SharingRetryObservation` [#sharingretryobservation] ```ts api="@rolebook/sharing" interface SharingRetryObservation { readonly type: "retry"; readonly sequence: number; readonly operation: "mutationRetry"; readonly reason: "revision-conflict"; readonly phase: "scheduled" | "backoff-failed" | "exhausted"; readonly retry: number; } ``` An intermediate event inside one `execute`, recorded where a revision conflict leads to another attempt. `scheduled`: retry number `retry` is next (its backoff pause first). `backoff-failed`: that pause threw or rejected, and `execute` rejects with the same exception. `exhausted`: every attempt conflicted (`retry` is the configured `mutationRetries`), and `execute` returns `CONFLICT`. ### `SharingScanObservation` [#sharingscanobservation] ```ts api="@rolebook/sharing" interface SharingScanObservation { readonly type: "scan"; readonly sequence: number; readonly operation: "candidateScan"; readonly listing: SharingScanListing; readonly status: SharingScanStatus; readonly scanned: number; readonly matched: number; readonly pages: number; } ``` One bounded candidate scan inside a listing page: candidates examined (exact), kept by the evaluator, and adapter candidate pages requested. A strict page that retries scans again, and each scan is its own event; an ineligible actor runs no scan. ### `SharingScanListing` [#sharingscanlisting] ```ts api="@rolebook/sharing" type SharingScanListing = "listAccessible" | "listAccess"; ``` ### `SharingScanStatus` [#sharingscanstatus] ```ts api="@rolebook/sharing" type SharingScanStatus = "exhausted" | "filled" | "scan-cap" | "partial" | "aborted"; ``` `exhausted`: the adapter reported no further candidates and every offered one was examined; it is the only completeness claim, and only for that scan. `filled`: the limit was reached. `scan-cap`: the 2,000-candidate examination cap was reached. `partial`: the scan stopped without either. `aborted`: the scan threw, and nothing from it was returned. Its `scanned` includes the candidate whose evaluation failed, and `pages` includes an adapter call that failed or returned a refused page, because both are counted before that work runs; `matched` counts only candidates kept before the failure. ### `SharingScanTotals` [#sharingscantotals] ```ts api="@rolebook/sharing" interface SharingScanTotals { readonly scans: Readonly>; readonly scanned: number; readonly matched: number; readonly pages: number; } ``` ### `SharingDiagnostics` [#sharingdiagnostics] ```ts api="@rolebook/sharing" interface SharingDiagnostics { readonly scope: "factory-local"; readonly enabled: boolean; readonly operations: Readonly< Record>> >; readonly mutationRetries: { readonly scheduled: number; readonly backoffFailed: number; readonly exhausted: number; }; readonly candidateScans: Readonly>; readonly timingUnavailable: number; readonly observation: { readonly status: "disabled" | "healthy" | "degraded" | "stalled"; readonly queueLimit: number; readonly queued: number; readonly outstanding: 0 | 1; readonly completed: number; readonly failed: number; readonly timedOut: number; readonly dropped: number; }; } ``` Frozen, recomputed on every call. `enabled` is `false` without `diagnostics`, and every count is then 0. `observation` describes observer delivery (observer faults), never operation results: `degraded` after a drop or a failed or timed-out call until a later call completes, `stalled` while a timed-out call still holds the slot. ### `SharingDiagnosticsSource` [#sharingdiagnosticssource] ```ts api="@rolebook/sharing" interface SharingDiagnosticsSource { diagnostics(): SharingDiagnostics; } ``` Synchronous and side-effect free; it never calls the observer. ## Definitions and typing [#definitions-and-typing] ### `SharingDefinition` [#sharingdefinition] ```ts api="@rolebook/sharing" interface SharingDefinition< TPolicy extends RolebookPolicy = RolebookPolicy, TResources extends SharingResourceConfigurations< PolicyRole, PolicyPermission > = SharingResourceConfigurations, PolicyPermission>, > { readonly policy: TPolicy; readonly resources: TResources; } ``` The frozen result of `defineSharing()`: the canonical policy and the resource catalog. ### `SharingResourceConfiguration` [#sharingresourceconfiguration] ```ts api="@rolebook/sharing" interface SharingResourceConfiguration< TRole extends string = string, TPermission extends string = string, TAdapter extends SharingAdapter = SharingAdapter, > { readonly memberRoles: Readonly>; readonly ownershipRole: TRole; readonly actions: Readonly>; readonly management: { readonly members: TPermission; readonly invitations: TPermission; readonly ownership: TPermission; readonly inspect?: TPermission; }; readonly adapter: TAdapter; readonly inheritance?: "ancestors"; } ``` One shareable resource type: member-role labels to policy roles, the ownership role, action labels to permissions, the management permissions, and its storage adapter. `inheritance: "ancestors"` opts the type in to [inherited access](/docs/sharing/inheritance): it is required for a `recursive` type or one below a recursive type, and only a first-party PostgreSQL or SQLite adapter accepts it. ### `SharingResourceConfigurations` [#sharingresourceconfigurations] ```ts api="@rolebook/sharing" type SharingResourceConfigurations< TRole extends string = string, TPermission extends string = string, > = Readonly>>; ``` The resource catalog: resource type to configuration. ### `PolicyRole` [#policyrole] ```ts api="@rolebook/sharing" type PolicyRole = TPolicy extends RolebookPolicy ? TRole : never; ``` The role names of a policy type. ### `PolicyPermission` [#policypermission] ```ts api="@rolebook/sharing" type PolicyPermission = TPolicy extends RolebookPolicy ? ConcretePermission : never; ``` The concrete permissions of a policy type (wildcards removed). ### `ResourceType` [#resourcetype] ```ts api="@rolebook/sharing" type ResourceType = keyof TResources & string; ``` The configured resource type names of a catalog. ### `RoleFor` [#rolefor] ```ts api="@rolebook/sharing" type RoleFor< TResources extends SharingResourceConfigurations, TType extends ResourceType, > = keyof TResources[TType]["memberRoles"] & string; ``` The member-role labels configured for one resource type. ### `ActionFor` [#actionfor] ```ts api="@rolebook/sharing" type ActionFor< TResources extends SharingResourceConfigurations, TType extends ResourceType, > = keyof TResources[TType]["actions"] & string; ``` The action labels configured for one resource type. ### `ResourceKey` [#resourcekey] ```ts api="@rolebook/sharing" interface ResourceKey { readonly type: TType; readonly id: string; } ``` A `{ type, id }` reference to a shareable resource. ## Commands and decisions [#commands-and-decisions] ### `SharingCommand` [#sharingcommand] ```ts api="@rolebook/sharing" type SharingCommand< TResources extends SharingResourceConfigurations, TType extends ResourceType = ResourceType, > = SharingCommandPrecondition & ( | { readonly kind: "grantRole"; readonly resource: ResourceKey; readonly subject: ResourceRef; readonly role: RoleFor | CustomRoleLabel; readonly expiresAt?: Date; readonly idempotencyKey: string; } | { readonly kind: "changeRole"; readonly resource: ResourceKey; readonly subject: ResourceRef; readonly role: RoleFor | CustomRoleLabel; readonly expiresAt?: Date | null; readonly idempotencyKey: string; } | { readonly kind: "revokeMember"; readonly resource: ResourceKey; readonly subject: ResourceRef; readonly idempotencyKey: string; } | { readonly kind: "transferOwnership"; readonly resource: ResourceKey; readonly to: OwnerRef; readonly formerOwnerRole?: RoleFor | CustomRoleLabel; readonly idempotencyKey: string; } | { readonly kind: "issueInvitation"; readonly resource: ResourceKey; readonly recipient: InvitationRecipient; readonly role: RoleFor | CustomRoleLabel; readonly expiresAt: Date; readonly membershipExpiresAt?: Date; readonly idempotencyKey: string; } | { readonly kind: "acceptInvitation"; readonly resource: ResourceKey; readonly token: string; readonly idempotencyKey: string; } | { readonly kind: "revokeInvitation"; readonly resource: ResourceKey; readonly invitationId: string; readonly idempotencyKey: string; } ); ``` The seven commands `execute()` accepts. Role fields take a configured label or a custom role label. Any command may carry a [`SharingCommandPrecondition`](#sharingcommandprecondition). See [commands](/docs/sharing/commands). ### `SharingCommandPrecondition` [#sharingcommandprecondition] ```ts api="@rolebook/sharing" interface SharingCommandPrecondition { readonly expectedSharingRevision?: string; } ``` With `expectedSharingRevision`, a command applies only while the resource's sharing revision is still that value. The revision is checked against the state the command was authorized on, and the write commits under that same revision, so a change that lands at any moment before the commit answers `SHARING_REVISION_CHANGED` and nothing changes. Authorization is decided first, so a caller who may not make the change gets the same refusal as without a precondition. A retry whose idempotency key already committed still answers `ALREADY_APPLIED`, since its own write moved the revision; the precondition is not part of the command's idempotency identity. A value that is not a 1 to 128 character string, a present `undefined` included, is refused as `NOT_FOUND_OR_DENIED`, never ignored: omit the key for an unconditional command. Over HTTP the precondition travels as its own operation; see [Conditional commands](/docs/http-api/http#conditional-commands). ### `SharingMutationResult` [#sharingmutationresult] ```ts api="@rolebook/sharing" type SharingMutationResult = { readonly ok: true; readonly code: "APPLIED" | "ALREADY_APPLIED"; readonly sharingRevision: string; readonly invitation?: { readonly id: string; readonly token: string; }; readonly policyVersion?: string; } | { readonly ok: false; readonly code: "NOT_FOUND_OR_DENIED" | "FORBIDDEN" | "NOT_TENANT_MEMBER" | "ROLE_NOT_ALLOWED" | "SELF_PROMOTION" | "OWNER_TRANSFER_REQUIRED" | "GROUP_CANNOT_OWN" | "MEMBER_ALREADY_EXISTS" | "INVITATION_EXPIRED" | "INVITATION_RECIPIENT_INVALID" | "INVITATION_UNAVAILABLE" | "INVITATION_RECIPIENT_MISMATCH" | "MEMBERSHIP_EXPIRY_INVALID" | "CONFLICT" | "SHARING_REVISION_CHANGED" | "POLICY_GENERATION_CHANGED" | "TENANT_ROLES_CHANGED" | "POLICY_UNAVAILABLE" | "HIERARCHY_UNAVAILABLE" | "DELEGATION_UNAVAILABLE" | "INHERITED_SCOPE_UNSUPPORTED" | "GOVERNANCE_REQUIRED"; }; ``` `execute()`'s answer: `APPLIED` or `ALREADY_APPLIED` with the sharing revision (plus the invitation token on an applied `issueInvitation`, and `policyVersion` on a versioned instance), or a stable failure code; see [result codes](/docs/sharing/commands#result-codes). ### `SharingExecutionLookupResult` [#sharingexecutionlookupresult] ```ts api="@rolebook/sharing" type SharingExecutionLookupResult = | { readonly status: "committed"; readonly result: { readonly ok: true; readonly code: "ALREADY_APPLIED"; readonly sharingRevision: string; readonly policyVersion?: string; }; } | { readonly status: "not_found" } | { readonly status: "different_command" } | { readonly status: "refused"; readonly code: Extract["code"]; }; ``` The answer of [`lookupExecution`](#tenantsharing). Only `committed` is proof of an outcome. - `committed`: this command, by this actor in this tenant, committed under this key. `result` is exactly what `execute` answers when it replays the record: `ALREADY_APPLIED`, the revision the commit produced and, on a versioned instance, the policy version stored with it. It never carries an invitation token. The fingerprint binds the record to the actor, so no other actor gets this answer. - `not_found`: no record of this key is readable for this resource in this tenant now. It is never proof that the command did not run. The record may have been pruned by [`pruneSettledRecords`](/docs/sharing/retention) (no sooner than `MIN_IDEMPOTENCY_RETENTION_MS`, one day, after the commit); it is removed with the resource by a delete, and at the source by a move of the resource to another tenant; and a command still running can commit after the lookup. It is also the answer for a record of another command when the actor has no access to the resource (`permissions` answers `NOT_FOUND_OR_DENIED`), so the lookup does not disclose that the resource exists. - `different_command`: the key is recorded for this resource under another fingerprint: another command, or this command by another actor. It is answered only to an actor `permissions` answers for the resource; when that check cannot run, the answer is `not_found`. It proves only that the key does not hold this command now: a record pruned and then reused by another command answers it too. - `refused`: no record was read. A command that does not capture answers the refusal `execute` gives it; an unknown resource type answers `NOT_FOUND_OR_DENIED`; an actor that is not a tenant member, or a malformed tenant or actor, `NOT_TENANT_MEMBER`; a versioned instance that cannot load the tenant's policy, `POLICY_UNAVAILABLE`; a tenant whose hierarchy enrollment has started, `HIERARCHY_UNAVAILABLE`. A `DelegationUnavailableError` or `InheritedScopeUnsupportedError` thrown while it reads answers `DELEGATION_UNAVAILABLE` or `INHERITED_SCOPE_UNSUPPORTED`, and any other `HierarchyUnavailableError` is thrown on, as from `execute`. ### `SharingDecision` [#sharingdecision] ```ts api="@rolebook/sharing" type SharingDecision = | { readonly allowed: true; readonly code: "ALLOWED"; readonly decision: AuthorizationDecision; } | { readonly allowed: false; readonly code: "NOT_FOUND_OR_DENIED" | "FORBIDDEN"; readonly decision?: AuthorizationDecision; }; ``` `authorize()`'s answer: `ALLOWED` with the Rolebook decision, `FORBIDDEN` (usually with the decision), or `NOT_FOUND_OR_DENIED` (never with one). ### `InvitationRecipient` [#invitationrecipient] ```ts api="@rolebook/sharing" type InvitationRecipient = InvitationRecipientSubject | InvitationRecipientEmail; ``` Who an invitation is for: an exact subject, or a verified email address. ### `InvitationRecipientSubject` [#invitationrecipientsubject] ```ts api="@rolebook/sharing" interface InvitationRecipientSubject { readonly type: "subject"; readonly subject: ResourceRef; } ``` An invitation bound to one immutable subject reference. ### `InvitationRecipientEmail` [#invitationrecipientemail] ```ts api="@rolebook/sharing" interface InvitationRecipientEmail { readonly type: "email"; readonly email: string; } ``` An invitation bound to an email address, at most `MAX_INVITATION_EMAIL_LENGTH` characters. Accepting it requires the identity adapter's verified-email match and the storage adapter's recipient fence. ## Reads [#reads] ### `AccessiblePage` [#accessiblepage] ```ts api="@rolebook/sharing" interface AccessiblePage { readonly resources: readonly AccessibleResource[]; readonly nextCursor?: string; readonly exhausted: boolean; readonly policyVersion?: string; } ``` One page of `listAccessible()`, read at [one coherent point](/docs/sharing/listing#what-one-page-guarantees). `nextCursor` is sealed and present until `exhausted`; a page may be empty and not exhausted. `policyVersion` is present on a versioned instance: the policy version the page was decided under. ### `AccessibleResource` [#accessibleresource] ```ts api="@rolebook/sharing" interface AccessibleResource { readonly resource: ResourceKey; readonly snapshot: TrustedResource; } ``` A listed resource key with the trusted snapshot Rolebook decided on. ### `AccessDescriptionResult` [#accessdescriptionresult] ```ts api="@rolebook/sharing" type AccessDescriptionResult = | { readonly ok: true; readonly code: "DESCRIBED"; readonly access: AccessDescription; } | { readonly ok: false; readonly code: "NOT_FOUND_OR_DENIED"; }; ``` `describeAccess()`'s answer: `DESCRIBED` with the description, or `NOT_FOUND_OR_DENIED`. ### `AccessDescription` [#accessdescription] ```ts api="@rolebook/sharing" interface AccessDescription { readonly resource: ResourceKey; readonly sharingRevision: string; readonly owner: SharingOwnership; readonly members: readonly AccessMember[]; readonly invitations?: readonly PendingInvitation[]; readonly inherited?: readonly InheritedAccessMember[]; readonly policyVersion?: string; } ``` Who has access: the owner, live members, and (when the actor may manage invitations) pending invitations, with the sharing revision of the snapshot. `inherited` is present only when the resource was read from an enrolled, activated hierarchy: the live memberships stored on its ancestors that apply to it, nearest first. ### `InheritedAccessMember` [#inheritedaccessmember] ```ts api="@rolebook/sharing" interface InheritedAccessMember { readonly from: ResourceRef; readonly depth: number; readonly subject: ResourceRef; readonly role: string; readonly roleUnavailable?: true; readonly expiresAt?: Date; } ``` One live membership stored on an ancestor: the ancestor it comes from, how many levels up it is (1 is the parent), the subject (individual or group) and the ancestor type's role label, with `roleUnavailable` for a retired custom role (it grants nothing). Show it as "editor, inherited from folder X". ### `AccessMember` [#accessmember] ```ts api="@rolebook/sharing" interface AccessMember { readonly subject: ResourceRef; readonly role: TRole | CustomRoleLabel; readonly roleUnavailable?: true; readonly createdAt: Date; readonly createdBy: ResourceRef; readonly expiresAt?: Date; } ``` One live membership: subject (individual or group), role label, `roleUnavailable` for an unavailable custom role, creation, and optional expiry. ### `PendingInvitation` [#pendinginvitation] ```ts api="@rolebook/sharing" interface PendingInvitation { readonly id: string; readonly recipient: InvitationRecipient; readonly role: TRole | CustomRoleLabel; readonly roleUnavailable?: true; readonly expiresAt: Date; readonly membershipExpiresAt?: Date; readonly createdAt: Date; readonly createdBy: ResourceRef; } ``` One pending invitation, without its token digest. ### `ResourcePermissionsResult` [#resourcepermissionsresult] ```ts api="@rolebook/sharing" type ResourcePermissionsResult = | { readonly ok: true; readonly code: "EVALUATED"; readonly permissions: ResourcePermissions; } | { readonly ok: false; readonly code: "NOT_FOUND_OR_DENIED"; }; ``` `permissions()`'s answer: `EVALUATED` with every action decided, or `NOT_FOUND_OR_DENIED`. ### `ResourcePermissions` [#resourcepermissions] ```ts api="@rolebook/sharing" interface ResourcePermissions { readonly resource: ResourceKey; readonly sharingRevision: string; readonly allowed: Readonly>; readonly decisions: Readonly>; readonly policyVersion?: string; } ``` Every configured action decided at one sharing revision: `allowed` (serializable booleans) and `decisions` (the Rolebook decisions). ### `AccessPage` [#accesspage] ```ts api="@rolebook/sharing" interface AccessPage { readonly resources: readonly ResourcePermissions[]; readonly nextCursor?: string; readonly exhausted: boolean; } ``` One page of `listAccess()`: the resources with at least one allowed action, in `listAccessible()`'s order, each the `ResourcePermissions` that `permissions()` builds from the same evaluator inputs. A page is read at [one coherent point](/docs/sharing/listing#what-one-page-guarantees) and sealed before it is returned. `nextCursor` is sealed under its own label and present until `exhausted`; a page may be empty and not exhausted. ### `AuditHistoryResult` [#audithistoryresult] ```ts api="@rolebook/sharing" type AuditHistoryResult = | { readonly ok: true; readonly code: "LISTED"; readonly page: AuditHistoryPage; } | { readonly ok: false; readonly code: "NOT_FOUND_OR_DENIED"; }; ``` `auditHistory()`'s answer: `LISTED` with one page, or `NOT_FOUND_OR_DENIED`. ### `AuditHistoryPage` [#audithistorypage] ```ts api="@rolebook/sharing" interface AuditHistoryPage { readonly resource: ResourceKey; readonly events: readonly AuditHistoryEvent[]; readonly nextCursor?: string; readonly exhausted: boolean; } ``` One page of audit events, newest first, with a sealed `nextCursor` until `exhausted`. ### `AuditHistoryEvent` [#audithistoryevent] ```ts api="@rolebook/sharing" type AuditHistoryEvent = Omit; ``` A `SharingAuditEvent` without the caller-chosen `idempotencyKey`. ## Inspection [#inspection] The types of [current-state inspection](/docs/sharing/inspection), `TenantSharing.explain()`. ### `InspectionResult` [#inspectionresult] ```ts api="@rolebook/sharing" type InspectionResult = | { readonly ok: true; readonly code: "EXPLAINED"; readonly explanation: InspectionEnvelope; } | { readonly ok: false; readonly code: InspectionError; }; ``` `explain()`'s answer, deeply frozen: `EXPLAINED` with a redacted explanation, or a fixed failure code with no message, cause, or partial trace. It is never a permission: do not authorize with it or cache it as a decision. ### `InspectionError` [#inspectionerror] ```ts api="@rolebook/sharing" type InspectionError = | "INVALID_REQUEST" | "INSPECTION_DISABLED" | "NOT_FOUND_OR_DENIED" | "TARGET_UNAVAILABLE" | "RATE_LIMITED" | "INSPECTION_UNAVAILABLE"; ``` Why `explain()` produced no explanation. `INVALID_REQUEST`: the input is not the exact bounded shape. `INSPECTION_DISABLED`: no `inspection` configuration. `NOT_FOUND_OR_DENIED`: the resource is missing or in another tenant, or the inspector is ineligible or not allowed the inspection permission. `TARGET_UNAVAILABLE`: the inspector was authorized but the target is absent or ineligible. `RATE_LIMITED`: the host limiter refused, or the instance already runs 32 inspections. `INSPECTION_UNAVAILABLE`: any operational fault, the deadline, or a failed audit append. See [errors](/docs/sharing/inspection#errors). ### `InspectionEnvelope` [#inspectionenvelope] ```ts api="@rolebook/sharing" interface InspectionEnvelope { readonly schema: "rolebook-inspection"; readonly version: 1; readonly inspectionId: string; readonly mode: "current-state"; readonly evaluatedAt: number; readonly resource: ResourceKey; readonly target: ResourceRef; readonly action: string; readonly field?: string; readonly sharingRevision: string; readonly policyVersion?: string; readonly policyDigest: string; readonly redactionVersion: 1; readonly capture: { readonly consistency: "captured-inputs"; }; readonly decision: InspectionDecision; } ``` One redacted current-state explanation. `inspectionId` is 128 random bits as 32 lowercase hex characters; `evaluatedAt` is the single sharing-clock reading in Unix milliseconds; `target` is the requested subject or the bound actor; `policyVersion` is present on a versioned instance; `policyDigest` is the SHA-256 of the effective policy's canonical JSON as 64 lowercase hex characters. `captured-inputs` is not a transaction-wide snapshot or a freshness token. See [the explanation](/docs/sharing/inspection#the-explanation). ### `InspectionDecision` [#inspectiondecision] ```ts api="@rolebook/sharing" interface InspectionDecision { readonly allowed: boolean; readonly code: DecisionCode; readonly permission: string; readonly matched?: { readonly effect: "allow" | "deny"; readonly role: string; readonly permission: string; readonly via?: ResourceRef; }; readonly trace: readonly { readonly outcome: "matched" | "not_matched"; readonly effect: "allow" | "deny"; readonly role: string; readonly permission: string; readonly via?: ResourceRef; readonly details: DecisionTraceDetails; }[]; readonly traceTruncated: boolean; readonly conditionTraceTruncated: boolean; } ``` The target decision, projected from the one Core `explain(request, { detail: "conditions" })` call that decided it. Core's free-text `reason` fields are omitted; `details` is Core's `DecisionTraceDetails` unchanged. `code` is `ALLOWED`, `EXPLICIT_DENY`, or `NOT_GRANTED`. Rule IDs are local to `policyDigest`, not durable grant IDs. ### `InspectionLimiter` [#inspectionlimiter] ```ts api="@rolebook/sharing" interface InspectionLimiter { acquire(input: { readonly tenantId: string; readonly actor: ResourceRef; readonly inspectionId: string; readonly signal: AbortSignal; }): Promise< | { readonly allowed: false; } | { readonly allowed: true; readonly release: () => void | Promise; } >; } ``` The host rate limiter, called before any resource, identity, or target load. Answer exactly `{ allowed: false }` or `{ allowed: true, release }`; any other shape is `INSPECTION_UNAVAILABLE`. `release` is called exactly once when the call's work settles. `signal` aborts at the deadline. See [the limiter contract](/docs/sharing/inspection#the-limiter). ### `InspectionAuditSink` [#inspectionauditsink] ```ts api="@rolebook/sharing" interface InspectionAuditSink { append( event: InspectionAuditEvent, options: { readonly signal: AbortSignal; }, ): Promise; } ``` The host audit sink. `append` must record the event durably, idempotently by `inspectionId`, before it resolves: no inspection detail is returned until it does. See [the audit contract](/docs/sharing/inspection#the-audit-sink). ### `InspectionAuditEvent` [#inspectionauditevent] ```ts api="@rolebook/sharing" interface InspectionAuditEvent { readonly schema: "rolebook-inspection-audit"; readonly version: 1; readonly inspectionId: string; readonly tenantId: string; readonly actor: ResourceRef; readonly resource: ResourceKey; readonly target: ResourceRef; readonly action: string; readonly field?: string; readonly evaluatedAt: number; readonly outcome: "explained" | "target_unavailable" | "unavailable"; readonly allowed?: boolean; readonly decisionCode?: DecisionCode; readonly policyDigest?: string; readonly redactionVersion: 1; } ``` The minimal record of one authorized inspection attempt. `allowed` and `decisionCode` appear only when `outcome` is `explained`. It never carries a trace, a fact, or a literal. ## Errors [#errors] ### `AccessibleListingError` [#accessiblelistingerror] ```ts api="@rolebook/sharing" class AccessibleListingError extends RangeError { readonly code: AccessibleListingErrorCode; constructor(code: AccessibleListingErrorCode, message: string); } ``` Thrown by `listAccessible()` and `listAccess()` for a request they cannot answer completely. A `RangeError` with a stable `code`; `listAccess()` has no action, so never `UNKNOWN_ACTION`. ### `AccessibleListingErrorCode` [#accessiblelistingerrorcode] ```ts api="@rolebook/sharing" type AccessibleListingErrorCode = | "INVALID_LIMIT" | "UNKNOWN_RESOURCE_TYPE" | "UNKNOWN_ACTION" | "TOO_MANY_ASSIGNMENTS"; ``` ### `InvalidCursorError` [#invalidcursorerror] ```ts api="@rolebook/sharing" class InvalidCursorError extends RangeError { readonly code: "INVALID_CURSOR"; constructor(message?: string); } ``` Thrown for a listing or audit cursor that does not open, and by adapters for a malformed raw cursor. A `RangeError` with `code: "INVALID_CURSOR"`; adapters may subclass it. ### `AccessListingUnavailableError` [#accesslistingunavailableerror] ```ts api="@rolebook/sharing" class AccessListingUnavailableError extends Error { readonly code: "ACCESS_LISTING_UNAVAILABLE"; readonly reason: AccessListingUnavailableReason; constructor(reason?: AccessListingUnavailableReason); } ``` Thrown by `listAccessible()` and `listAccess()` when no consistent page could be read in at most three attempts. No page, partial page, or weaker page is returned. `reason` is non-sensitive and can be branched on like `code`; the message names only the reason. The constructor's default reason is `changed`. See [when no consistent page can be read](/docs/sharing/listing#when-no-consistent-page-can-be-read). ### `AccessListingUnavailableReason` [#accesslistingunavailablereason] ```ts api="@rolebook/sharing" type AccessListingUnavailableReason = | "capability_missing" | "identity_evidence_missing" | "policy_evidence_missing" | "unrepresentable_identity" | "expiry_crossed" | "session_expired" | "snapshot_unavailable" | "changed"; ``` Why a listing was unavailable. It names a cause only, never a tenant, subject, resource ID, attribute, revision, or expiry value. `capability_missing`, `identity_evidence_missing`, and `policy_evidence_missing` end the call at once; the others are retried within the call's three attempts. ### `InvalidCandidatePageError` [#invalidcandidatepageerror] ```ts api="@rolebook/sharing" class InvalidCandidatePageError extends TypeError { readonly code: "INVALID_CANDIDATE_PAGE"; constructor(message: string); } ``` Thrown when an adapter violates its output contract (malformed page, events, or cursor). A `TypeError` with `code: "INVALID_CANDIDATE_PAGE"`: fix the adapter, do not retry. ### `AuditHistoryError` [#audithistoryerror] ```ts api="@rolebook/sharing" class AuditHistoryError extends RangeError { readonly code: AuditHistoryErrorCode; constructor(code: AuditHistoryErrorCode, message: string); } ``` Thrown by `auditHistory()` for an invalid limit or an unknown resource type. A `RangeError`. ### `AuditHistoryErrorCode` [#audithistoryerrorcode] ```ts api="@rolebook/sharing" type AuditHistoryErrorCode = "INVALID_LIMIT" | "UNKNOWN_RESOURCE_TYPE"; ``` ### `RetentionError` [#retentionerror] ```ts api="@rolebook/sharing" class RetentionError extends RangeError { readonly code: RetentionErrorCode; constructor(code: RetentionErrorCode, message: string); } ``` Thrown by `pruneSettledRecords()` for a request it will not run, before any delete. A `RangeError`. ### `RetentionErrorCode` [#retentionerrorcode] ```ts api="@rolebook/sharing" type RetentionErrorCode = | "INVALID_INPUT" | "INVALID_SCOPE" | "INVALID_LIMIT" | "INVALID_RETENTION" | "RETENTION_TOO_SHORT"; ``` ### `RetentionSchemaError` [#retentionschemaerror] ```ts api="@rolebook/sharing" class RetentionSchemaError extends Error { readonly code: "SCHEMA_NOT_UPGRADED"; constructor(message: string); } ``` Thrown by `pruneSettledRecords()` when the database is not ready to prune (missing `created_at`, its index, or on PostgreSQL its default). `code: "SCHEMA_NOT_UPGRADED"`. Run the adapter's migrations. ### `PolicyStoreError` [#policystoreerror] ```ts api="@rolebook/sharing" class PolicyStoreError extends Error { readonly code: PolicyStoreErrorCode; constructor(code: PolicyStoreErrorCode, message?: string); } ``` Thrown while constructing a versioned sharing instance; no instance is returned. ### `PolicyStoreErrorCode` [#policystoreerrorcode] ```ts api="@rolebook/sharing" type PolicyStoreErrorCode = | "INVALID_OPTIONS" | "ADAPTER_NOT_FENCED" | "SEED_INVALID" | "NO_ACTIVE_POLICY" | "ACTIVE_VERSION_INVALID"; ``` ### `PolicyUnavailableError` [#policyunavailableerror] ```ts api="@rolebook/sharing" class PolicyUnavailableError extends Error { readonly code: "POLICY_UNAVAILABLE"; readonly reason: PolicyUnavailableReason; constructor( reason: PolicyUnavailableReason, message?: PolicyUnavailableReason, options?: { readonly cause?: unknown; }, ); } ``` The active policy or a tenant's custom roles cannot be used. `execute()` maps it to `POLICY_UNAVAILABLE` and `explain()` to `INSPECTION_UNAVAILABLE`; the other tenant reads, `refresh()`, `policies.*` and `customRoles.*` reject with it, and the listings reject with it for a sticky or per-tenant failure (other policy state they cannot use inside their page snapshot is `AccessListingUnavailableError`). Some reasons are sticky until a new instance is constructed. The error that caused it, such as a store rejection, is kept as `cause`. ### `PolicyUnavailableReason` [#policyunavailablereason] ```ts api="@rolebook/sharing" type PolicyUnavailableReason = | "STORE_UNREACHABLE" | "STALE" | "INTERNAL_ERROR" | "CLOCK_FAULT" | "POINTER_INVALID" | "POINTER_REGRESSED" | "POINTER_DIGEST_MISMATCH" | "VERSION_INVALID" | "REVISION_REGRESSED" | "TENANT_ROLES_INVALID"; ``` `INTERNAL_ERROR` reports a failure that did not come from a store call, such as a fault while building a tenant's runtime. It is never served from the last good state: it fails closed at once, and it is not sticky, so the next operation loads again. A store that stays unreachable past `maxStalenessMs` reports `STORE_UNREACHABLE`. `STALE` means the instance knows the state it would decide under is superseded (a tenant's custom roles invalidated there by a `define` or `remove` that applied or an `execute` result `TENANT_ROLES_CHANGED`, or the active generation reported as no longer active by a publish `GENERATION_CONFLICT`, a custom-role generation conflict or `POLICY_GENERATION_CHANGED`) and every reload the operation ran, at most three, was overtaken by a further report there; it is not sticky. ### `PolicyAdministrationError` [#policyadministrationerror] ```ts api="@rolebook/sharing" class PolicyAdministrationError extends RangeError { readonly code: PolicyAdministrationErrorCode; constructor(code: PolicyAdministrationErrorCode, message: string); } ``` A policy-administration request refused before any read or write. A `RangeError`. ### `PolicyAdministrationErrorCode` [#policyadministrationerrorcode] ```ts api="@rolebook/sharing" type PolicyAdministrationErrorCode = | "INVALID_LIMIT" | "INVALID_CURSOR" | "INVALID_DIGEST" | "INVALID_TENANT" | "INVALID_AUDIT_EVENT"; ``` ### `isPolicyStoreRowError` [#ispolicystorerowerror] ```ts api="@rolebook/sharing" function isPolicyStoreRowError(error: unknown): boolean; ``` Whether an error is a first-party store's `PolicyStoreRowError` (a row that does not decode), recognized by its `name` so this package needs no database import. ### `HierarchyUnavailableError` [#hierarchyunavailableerror] ```ts api="@rolebook/sharing" class HierarchyUnavailableError extends Error { readonly reason: HierarchyUnavailableReason; readonly code: "HIERARCHY_UNAVAILABLE"; constructor(reason: HierarchyUnavailableReason, options?: { readonly cause?: unknown; }); } ``` A closed, tenant-level hierarchy refusal (R6 §7) with an exact `reason`. `execute`, `authorize`, `permissions` and strict listing pages rethrow it unchanged: it is never turned into a result, an ordinary denial or a retry. Over HTTP it is a 503 `HIERARCHY_UNAVAILABLE` with an allowlisted `reason`. ### `HierarchyUnavailableReason` [#hierarchyunavailablereason] ```ts api="@rolebook/sharing" type HierarchyUnavailableReason = "not_enrolled" | "enrolled" | "building" | "quarantined" | "epoch_mismatch" | "lifecycle_mismatch" | "protocol_floor" | "corrupt" | "barrier_missing" | "profile_unbound" | "profile_mismatch" | "budget_exhausted" | "policy_incompatible" | "unsupported_isolation" | "serialization_conflict" | "policy_identity_unresolved" | "policy_profile_mismatch" | "identity_unavailable" | "graph_quarantined" | "graph_corrupt" | "principal_cap" | "registry_unavailable" | "lineage_invalid" | "budget"; ``` Why a tenant's hierarchy is unavailable. [Inherited reads](/docs/sharing/inheritance) and the hierarchy control facade raise these, and storage adapters bound to a hierarchy control profile raise them too (for example `profile_unbound` before resource migrations are rerun). `not_enrolled` also answers a flat read of an opted-in type whose application-supplied ancestors include a recursive type. Nested-team lineage and the group-graph command facades raise the graph reasons. `graph_quarantined` means the group-graph admission is quarantined, which is separate from hierarchy `quarantined`. `graph_corrupt` means stored graph evidence is inconsistent. `principal_cap` means a resolution would pass 64 groups; it refuses the resolution and does not quarantine the graph. `registry_unavailable` means a group endpoint or its incarnation cannot be confirmed. `lineage_invalid` means lineage evidence failed validation. `budget` means a graph allocator or repair batch cannot continue, and is separate from hierarchy `budget_exhausted`. ### `isHierarchyUnavailableError` [#ishierarchyunavailableerror] ```ts api="@rolebook/sharing" function isHierarchyUnavailableError(error: unknown): error is HierarchyUnavailableError; ``` Narrows an unknown thrown value to `HierarchyUnavailableError`. ### `DelegationUnavailableError` [#delegationunavailableerror] ```ts api="@rolebook/sharing" class DelegationUnavailableError extends Error { readonly reason: DelegationUnavailableReason; readonly code: "DELEGATION_UNAVAILABLE"; constructor(reason: DelegationUnavailableReason); } ``` A closed refusal when delegable-scope evidence cannot be decided from complete, bounded evidence. `execute` answers it as the `DELEGATION_UNAVAILABLE` result. ### `DelegationUnavailableReason` [#delegationunavailablereason] ```ts api="@rolebook/sharing" type DelegationUnavailableReason = "evidence_incomplete" | "assignment_cap" | "unknown_role" | "evidence_pending"; ``` Why delegable-scope evidence was unavailable. ### `InheritedScopeUnsupportedError` [#inheritedscopeunsupportederror] ```ts api="@rolebook/sharing" class InheritedScopeUnsupportedError extends Error { readonly resourceType: string; readonly code: "INHERITED_SCOPE_UNSUPPORTED"; constructor(resourceType: string); } ``` Authority at an inherited scope that this path does not support. The protected-content prefix and hierarchy commands such as ownership transfer throw it before any effect. The protected write adapter does not: an inheriting enrolled type is classified and authorized through the locked inherited read. `execute` answers the error as the `INHERITED_SCOPE_UNSUPPORTED` result. ### `AdapterContractError` [#adaptercontracterror] ```ts api="@rolebook/sharing" class AdapterContractError extends Error { constructor(); } ``` Thrown when a storage adapter answers a rejection reason outside its closed contract. Such a reason used to become `OWNER_TRANSFER_REQUIRED`. ## Keys, clocks, and IDs [#keys-clocks-and-ids] ### `createHmacInvitationTokens` [#createhmacinvitationtokens] ```ts api="@rolebook/sharing" function createHmacInvitationTokens(key: string | Uint8Array): InvitationTokenProtector; ``` An `InvitationTokenProtector` that issues 32-byte random secrets and digests them with HMAC-SHA256. The key is a `generateInvitationTokenKey()` string or at least 32 random bytes as a `Uint8Array`, copied at construction; see [secret keys](/docs/sharing/setup#secret-keys). ### `generateInvitationTokenKey` [#generateinvitationtokenkey] ```ts api="@rolebook/sharing" function generateInvitationTokenKey(): string; ``` A new 32-byte random key in the checked `rbk1_` text form. ### `generateListingCursorKey` [#generatelistingcursorkey] ```ts api="@rolebook/sharing" function generateListingCursorKey(): string; ``` A new 32-byte random key in the same checked `rbk1_` form, for `listingCursorKey`. ### `InvitationTokenProtector` [#invitationtokenprotector] ```ts api="@rolebook/sharing" interface InvitationTokenProtector { issue(): { readonly secret: string; readonly digest: string; }; digest(secret: string): string; } ``` Issues an invitation secret with its digest, and digests a presented secret. ### `SharingClock` [#sharingclock] ```ts api="@rolebook/sharing" interface SharingClock { now(): Date; } ``` The wall clock the module and adapters use for expiry and timestamps. ### `systemClock` [#systemclock] ```ts api="@rolebook/sharing" const systemClock: SharingClock; ``` The default clock: `new Date()`. ### `SharingIdGenerator` [#sharingidgenerator] ```ts api="@rolebook/sharing" interface SharingIdGenerator { next(): string; } ``` Generates invitation and audit event IDs. ### `randomIdGenerator` [#randomidgenerator] ```ts api="@rolebook/sharing" const randomIdGenerator: SharingIdGenerator; ``` The default generator: `crypto.randomUUID()`. ## Identity [#identity] ### `TenantIdentityAdapter` [#tenantidentityadapter] ```ts api="@rolebook/sharing" interface TenantIdentityAdapter { resolvePagePrincipal?(input: { readonly tenantId: string; readonly subject: ResourceRef; }): Promise; capturePagePrincipal?(input: { readonly tenantId: string; readonly subject: ResourceRef; readonly evaluatedAt: string; }): PagePrincipalSnapshot; resolvePrincipal(input: { readonly tenantId: string; readonly subject: ResourceRef; }): Promise; matchesInvitationRecipient(input: { readonly tenantId: string; readonly principal: TenantPrincipal; readonly recipient: InvitationRecipient; }): Promise; } ``` Resolves a subject's eligibility, assignments, facts, and groups in an explicit tenant, and matches invitation recipients. See [identity adapters](/docs/sharing/adapters#identity-adapters). The two optional methods supply [identity evidence for listing pages](/docs/sharing/listing#identity). `resolvePagePrincipal` is for an external source with a non-repeating revision: Rolebook calls it before a page's snapshot opens and after the page was read, and accepts the page only when both answers match. Implement it only when the source has such a revision. `capturePagePrincipal` is for the in-memory adapter: it answers synchronously from in-process state, judged at `evaluatedAt`, and must not perform I/O, return a promise, or write. An identity adapter with neither needs the storage adapter's `pageIdentity` option. ### `PagePrincipalSnapshot` [#pageprincipalsnapshot] ```ts api="@rolebook/sharing" interface PagePrincipalSnapshot { readonly principal: TenantPrincipal; readonly expiryDependencies: readonly string[]; } ``` A complete principal captured at one instant, with the expiry of every time-sensitive fact as ISO 8601 UTC instants with exactly three fractional digits. What `capturePagePrincipal` returns. ### `PagePrincipalEvidence` [#pageprincipalevidence] ```ts api="@rolebook/sharing" interface PagePrincipalEvidence extends PagePrincipalSnapshot { readonly epoch: string; readonly revision: string; } ``` What `resolvePagePrincipal` returns. `revision` never repeats within `epoch` and changes on every relevant change, including a change that is later restored and a set going from empty to non-empty. `epoch` changes whenever the provider's store is restored or re-created. Equal values, timestamps, and ETags are not substitutes. ### `TenantPrincipal` [#tenantprincipal] ```ts api="@rolebook/sharing" interface TenantPrincipal { readonly eligible: boolean; readonly subject: Subject; readonly tenantScope: ResourceRef; readonly assignments: readonly RoleAssignment[]; readonly authorizationFacts?: readonly TransactionalAuthorizationFact[]; readonly attributes?: Readonly>; readonly groups?: readonly ResourceRef[]; readonly group?: boolean; } ``` What an identity adapter returns for one subject in one tenant. ### `TransactionalAuthorizationFact` [#transactionalauthorizationfact] ```ts api="@rolebook/sharing" interface TransactionalAuthorizationFact { readonly type: string; readonly tenantId: string; readonly subject: ResourceRef; readonly values: Readonly>; readonly group?: ResourceRef; } ``` A provider-owned fact behind an assignment or a group membership. The module transports it unchanged; the storage adapter locks and compares it inside the mutation transaction. `group` names the group it attests. ### `GroupPrincipalRef` [#groupprincipalref] ```ts api="@rolebook/sharing" type GroupPrincipalRef = ResourceRef & { readonly [groupPrincipalBrand]: true; }; ``` A reference branded as a flat group principal (a team). Build one with `groupPrincipal()`. ### `OwnerRef` [#ownerref] ```ts api="@rolebook/sharing" type OwnerRef = ResourceRef & { readonly [groupPrincipalBrand]?: never; }; ``` A reference that may own a resource. A `GroupPrincipalRef` does not satisfy it. ### `groupPrincipal` [#groupprincipal] ```ts api="@rolebook/sharing" function groupPrincipal(ref: ResourceRef): GroupPrincipalRef; ``` Brands a bounded `{ type, id }` as a group principal (a frozen copy). Throws `TypeError` otherwise. ### `createWorkspaceIdentityAdapter` [#createworkspaceidentityadapter] ```ts api="@rolebook/sharing" function createWorkspaceIdentityAdapter< TUser extends { readonly id: string; }, >(options: WorkspaceIdentityAdapterOptions): TenantIdentityAdapter; ``` The shared implementation behind the Better Auth, Clerk, and WorkOS adapters. See [`createWorkspaceIdentityAdapter`](/docs/sharing/adapters#createworkspaceidentityadapter). ### `WorkspaceIdentityAdapterOptions` [#workspaceidentityadapteroptions] ```ts api="@rolebook/sharing" interface WorkspaceIdentityAdapterOptions< TUser extends { readonly id: string; }, > { readonly authorizationFactType: string; readonly getMember: (input: { readonly organizationId: string; readonly userId: string; }) => Promise; readonly getUser: (input: { readonly userId: string }) => Promise; readonly snapshotUser: (user: TUser) => TUser | undefined; readonly verifiedEmail: (user: TUser) => string | undefined; readonly requireUser?: boolean | undefined; readonly principalAttributes?: | ((input: { readonly user: TUser; readonly member: WorkspaceMemberRecord; }) => Readonly>) | undefined; readonly subjectType?: string | undefined; readonly workspaceResourceType?: string | undefined; readonly mapWorkspaceAssignments?: | ((input: { readonly tenantId: string; readonly subject: ResourceRef; readonly member: WorkspaceMemberRecord; }) => readonly RoleAssignment[]) | undefined; readonly normalizeEmail?: ((email: string) => string) | undefined; } ``` The provider-specific parts: the fact type, exact membership and user lookups, user snapshot and verified-email functions, and optional `requireUser`, `principalAttributes`, `subjectType`, `workspaceResourceType`, `mapWorkspaceAssignments`, and `normalizeEmail`. ### `WorkspaceMemberRecord` [#workspacememberrecord] ```ts api="@rolebook/sharing" interface WorkspaceMemberRecord { readonly id: string; readonly organizationId: string; readonly userId: string; readonly role: string; } ``` The authority-bearing part of a provider membership: member ID, organization, user, role. ### `createWorkspaceMemberRemovedHandler` [#createworkspacememberremovedhandler] ```ts api="@rolebook/sharing" function createWorkspaceMemberRemovedHandler(input: { readonly provider: string; readonly onMemberRemoved: (event: WorkspaceMemberRemovedEvent) => void | Promise; }): (event: WorkspaceMemberRemovedEvent) => Promise; ``` Wraps a member-removal callback so it receives a validated, frozen event. Cleanup only: membership is still checked on every operation. ### `WorkspaceMemberRemovedEvent` [#workspacememberremovedevent] ```ts api="@rolebook/sharing" interface WorkspaceMemberRemovedEvent { readonly organizationId: string; readonly userId: string; } ``` A provider member-removal notification: organization and user IDs. ## Storage adapter contract [#storage-adapter-contract] What a storage adapter implements and exchanges with the module. See [storage adapters](/docs/sharing/adapters#storage-adapters). ### `SharingAdapter` [#sharingadapter] ```ts api="@rolebook/sharing" interface SharingAdapter { runConsistentPage?(input: ConsistentPageInput, operation: (page: ConsistentPage) => Promise): Promise; readonly policyFence?: "enforced"; readonly governanceGate?: GovernanceDirectGate; readonly governanceBinding?: GovernanceBinding; readAccess(input: { readonly tenantId: string; readonly resourceId: string; readonly requiredEligibleSubjects: readonly ResourceRef[]; readonly requestingPrincipals?: readonly ResourceRef[]; readonly hierarchy?: HierarchyReadRuntime; }): Promise; readAccessBatch(input: { readonly tenantId: string; readonly resourceIds: readonly string[]; readonly requiredEligibleSubjects: readonly ResourceRef[]; readonly requestingPrincipals?: readonly ResourceRef[]; readonly hierarchy?: HierarchyReadRuntime; }): Promise; readInvitation(input: { readonly tenantId: string; readonly resourceId: string; readonly invitationId: string; }): Promise; listPendingInvitations(input: { readonly tenantId: string; readonly resourceId: string; readonly incarnationId?: string; }): Promise; listAuditEvents(input: { readonly tenantId: string; readonly resourceId: string; readonly limit: number; readonly cursor?: string; readonly incarnationId?: string; }): Promise; readMutationIdempotency(input: ReadMutationIdempotencyRequest): Promise; lookupMutationIdempotency?(input: ReadMutationIdempotencyRequest): Promise; applyMutation(input: ApplyMutationRequest): Promise; listCandidates(input: { readonly tenantId: string; readonly principals: readonly ResourceRef[]; readonly includeAllTenantResources: boolean; readonly resourceIds: readonly string[]; readonly memberRoles?: readonly string[]; readonly cursor?: string; readonly limit: number; readonly hierarchy?: HierarchyReadRuntime; }): Promise; resourceDeleted(input: { readonly tenantId: string; readonly resourceId: string; readonly actor: ResourceRef; readonly idempotencyKey: string; readonly occurredAt: Date; }): Promise<"applied" | "already_applied" | "not_found" | "unsupported">; resourceMoved(input: { readonly fromTenantId: string; readonly toTenantId: string; readonly resourceId: string; readonly actor: ResourceRef; readonly idempotencyKey: string; readonly occurredAt: Date; }): Promise<"applied" | "already_applied" | "not_found" | "unsupported">; } ``` The storage contract for one resource type. `runConsistentPage` reads one [listing page](/docs/sharing/listing#what-one-page-guarantees) at one coherent point. It opens one snapshot, calls `operation` exactly once with a session whose candidate and hydration reads, principal, policy state, and `evaluatedAt` all belong to that snapshot, seals every live expiry the page depended on, and closes. It has a finite lifetime, its reads are sequential, and it never retries `operation`. Whatever it cannot establish throws `AccessListingUnavailableError` with a reason; it never returns a weaker page. The member is optional so that existing custom adapters still compile: an adapter without it makes `listAccessible()` and `listAccess()` answer `capability_missing`. Every first-party adapter implements it. `lookupMutationIdempotency` answers what `readMutationIdempotency` answers, as a pure read for [`lookupExecution`](#tenantsharing): it writes nothing (not even bookkeeping a writer would create for a tenant or resource with no rows yet), takes no write lock, and works on a read-only connection where the adapter supports one. A tenant whose hierarchy enrollment has started is refused with `HierarchyUnavailableError` (reason `enrolled`), never read flat. On PostgreSQL a tenant ID that cannot be a value of the tenant column answers `missing` without a transaction; any other tenant is probed first, so an enrolled tenant is refused whatever the resource ID, as on SQLite, and an alias spelling of an enrolled tenant (a non-canonical form of a uuid tenant ID) is refused with reason `profile_mismatch`, which `lookupExecution` throws on. `readMutationIdempotency` keeps the replay route: on SQLite and PostgreSQL it runs the writer barrier, which can create a tenant's barrier row. The member is optional; a tenant offers `lookupExecution` only when every resource adapter of its instance implements it. The memory, SQLite and PostgreSQL adapters do, and `sharingAdapterContract` fails for an adapter without it. ### `ConsistentPageInput` [#consistentpageinput] ```ts api="@rolebook/sharing" interface ConsistentPageInput { readonly tenantId: string; readonly subject: ResourceRef; readonly identity: TenantIdentityAdapter; readonly policyStore?: PolicyStore; } ``` What Rolebook asks an adapter to read one page for: the tenant, the actor whose principal the page resolves, the identity adapter the sharing instance was created with, and, on a versioned instance, the policy store whose state the page must read in its snapshot. ### `ConsistentPage` [#consistentpage] ```ts api="@rolebook/sharing" interface ConsistentPage { readonly evaluatedAt: string; readonly principal: TenantPrincipal; readonly policyState?: PagePolicyState; listCandidates: SharingAdapter["listCandidates"]; readAccessBatch: SharingAdapter["readAccessBatch"]; } ``` One page session. Its reads are sequential and see one snapshot, and every method throws once the callback has settled or the session has closed, so never retain it. `evaluatedAt` is the ISO 8601 UTC millisecond instant every expiry comparison of the page uses. `principal` is the actor's complete principal at the snapshot, which may be ineligible. `policyState` is present exactly when the input named a policy store. `readAccessBatch` returns every requested resource, projected to `requestingPrincipals` (required here), with memberships live at `evaluatedAt`; a requested resource that is missing or corrupt makes the call throw. It is narrower than the adapter's own method on `requiredEligibleSubjects`: the session proves eligibility only for its own actor. Requiring that actor reads nothing when the snapshot found it ineligible, and requiring any other subject throws `AccessListingUnavailableError` with `identity_evidence_missing`. ### `PagePolicyState` [#pagepolicystate] ```ts api="@rolebook/sharing" interface PagePolicyState { readonly pointer: ActivePolicyPointer; readonly version: StoredPolicyVersion | undefined; readonly tenantRoles: TenantCustomRoles; } ``` Versioned policy state as read inside a page's snapshot: the active pointer, the stored version it names, and the tenant's custom roles. ### `SharingAccessSnapshot` [#sharingaccesssnapshot] ```ts api="@rolebook/sharing" interface SharingAccessSnapshot { readonly tenantId: string; readonly resourceId: string; readonly resource: TrustedResource; readonly resourceVersion: string; readonly sharingRevision: string; readonly ownership: SharingOwnership; readonly memberships: readonly SharingMembership[]; readonly incarnationId?: string; } ``` One resource's authoritative state: the trusted snapshot, resource version, sharing revision, ownership, memberships, and incarnation ID. ### `SharingOwnership` [#sharingownership] ```ts api="@rolebook/sharing" interface SharingOwnership { readonly subject: ResourceRef; readonly createdAt: Date; readonly createdBy: ResourceRef; } ``` The owner and when and by whom ownership was recorded. ### `SharingMembership` [#sharingmembership] ```ts api="@rolebook/sharing" interface SharingMembership { readonly subject: ResourceRef; readonly role: string; readonly createdAt: Date; readonly createdBy: ResourceRef; readonly expiresAt?: Date; } ``` One membership: subject, role label, creation, optional expiry. ### `SharingInvitation` [#sharinginvitation] ```ts api="@rolebook/sharing" interface SharingInvitation { readonly id: string; readonly recipient: InvitationRecipient; readonly role: string; readonly tokenDigest: string; readonly expiresAt: Date; readonly createdAt: Date; readonly createdBy: ResourceRef; readonly consumedAt?: Date; readonly consumedBy?: ResourceRef; readonly revokedAt?: Date; readonly revokedBy?: ResourceRef; readonly membershipExpiresAt?: Date; } ``` A stored invitation: recipient, role, token digest, expiry, and its lifecycle timestamps. ### `SharingAuditEvent` [#sharingauditevent] ```ts api="@rolebook/sharing" interface SharingAuditEvent { readonly id: string; readonly tenantId: string; readonly resourceType: string; readonly resourceId: string; readonly actor: ResourceRef; readonly action: | "member.granted" | "member.role_changed" | "member.revoked" | "ownership.transferred" | "invitation.issued" | "invitation.consumed" | "invitation.revoked" | "resource.initialized" | "resource.deleted" | "resource.moved"; readonly subject?: ResourceRef; readonly invitationId?: string; readonly fromTenantId?: string; readonly toTenantId?: string; readonly occurredAt: Date; readonly idempotencyKey: string; readonly lineageDirect?: string; readonly lineageWitness?: string; } ``` One audit event, committed with the mutation it records. `lineageDirect` is the canonical JSON of every contributing direct group for an invitation issued or consumed under a nested-team profile. `lineageWitness` is the lineage witness encoding from that same subject fact. Flat events, and historical rows written before those fields existed, omit both. ### `AdapterMutation` [#adaptermutation] ```ts api="@rolebook/sharing" type AdapterMutation = | { readonly kind: "grantRole"; readonly subject: ResourceRef; readonly role: string; readonly expiresAt?: Date; } | { readonly kind: "changeRole"; readonly subject: ResourceRef; readonly role: string; readonly expiresAt?: Date | null; } | { readonly kind: "revokeMember"; readonly subject: ResourceRef; } | { readonly kind: "transferOwnership"; readonly to: ResourceRef; readonly formerOwnerRole?: string; } | { readonly kind: "issueInvitation"; readonly invitation: SharingInvitation; } | { readonly kind: "consumeInvitation"; readonly invitationId: string; readonly tokenDigest: string; readonly recipient: InvitationRecipient; readonly subject: ResourceRef; readonly consumedAt: Date; } | { readonly kind: "revokeInvitation"; readonly invitationId: string; readonly revokedAt: Date; readonly revokedBy: ResourceRef; }; ``` The storage-level form of a command, prepared by the module after authorization. ### `ApplyMutationRequest` [#applymutationrequest] ```ts api="@rolebook/sharing" interface ApplyMutationRequest { readonly tenantId: string; readonly resourceId: string; readonly expectedResourceVersion: string; readonly expectedSharingRevision: string; readonly actor: ResourceRef; readonly requiredEligibleSubjects: readonly ResourceRef[]; readonly requiredAuthorizationFacts?: readonly TransactionalAuthorizationFact[]; readonly mutation: AdapterMutation; readonly audit: SharingAuditEvent; readonly idempotencyKey: string; readonly idempotencyFingerprint: string; readonly expectedPolicy?: ExpectedPolicy; readonly policyVersion?: string; readonly reliedAuthorityExpiries?: readonly number[]; } ``` Everything `applyMutation` needs: expected version and revision, subjects and facts to fence, the mutation, its audit event, idempotency key and fingerprint, and, when versioned, the expected policy. ### `ApplyMutationResult` [#applymutationresult] ```ts api="@rolebook/sharing" type ApplyMutationResult = { readonly status: "applied"; readonly sharingRevision: string; readonly policyVersion?: string; } | { readonly status: "already_applied"; readonly sharingRevision: string; readonly policyVersion?: string; } | { readonly status: "conflict"; } | { readonly status: "not_found"; } | { readonly status: "invalid"; readonly reason: "last_owner" | "group_owner" | "member_exists" | "invitation_unavailable" | "invitation_recipient_mismatch" | "identity_ineligible" | "policy_generation_changed" | "tenant_roles_changed" | "policy_unfenced" | "hierarchy_unavailable" | "delegation_unavailable" | "inherited_scope_unsupported" | "governance_required"; }; ``` `applied`, `already_applied`, `conflict`, `not_found`, or `invalid` with a reason. ### `ReadMutationIdempotencyRequest` [#readmutationidempotencyrequest] ```ts api="@rolebook/sharing" interface ReadMutationIdempotencyRequest { readonly tenantId: string; readonly resourceId: string; readonly idempotencyKey: string; readonly idempotencyFingerprint: string; } ``` A lookup of a committed idempotency record by key and fingerprint. ### `ReadMutationIdempotencyResult` [#readmutationidempotencyresult] ```ts api="@rolebook/sharing" type ReadMutationIdempotencyResult = | { readonly status: "already_applied"; readonly sharingRevision: string; readonly policyVersion?: string; } | { readonly status: "conflict"; } | { readonly status: "missing"; }; ``` `already_applied`, `conflict` (another fingerprint), or `missing`. ### `AccessibleCandidate` [#accessiblecandidate] ```ts api="@rolebook/sharing" interface AccessibleCandidate { readonly resourceId: string; readonly cursor: string; } ``` One listing candidate: a resource ID and the cursor just after it. ### `AccessibleCandidatePage` [#accessiblecandidatepage] ```ts api="@rolebook/sharing" interface AccessibleCandidatePage { readonly candidates: readonly AccessibleCandidate[]; readonly nextCursor?: string; readonly exhausted: boolean; } ``` One page of candidates; non-exhausted pages carry an advancing `nextCursor`. ### `AuditEventPage` [#auditeventpage] ```ts api="@rolebook/sharing" interface AuditEventPage { readonly events: readonly SharingAuditEvent[]; readonly nextCursor?: string; readonly exhausted: boolean; } ``` One page of an adapter's audit events, newest first, with a raw cursor. ### `InvitationRecipientFenceInput` [#invitationrecipientfenceinput] ```ts api="@rolebook/sharing" interface InvitationRecipientFenceInput { readonly tenantId: string; readonly resourceId: string; readonly invitationId: string; readonly tokenDigest: string; readonly recipient: InvitationRecipient; readonly subject: ResourceRef; } ``` The exact recipient assertion an adapter checks while consuming an invitation, bound to the invitation, digest, tenant, resource, and accepting subject. ## Adapter helpers [#adapter-helpers] Shared by the module and every first-party adapter, so a custom adapter can apply exactly the same rules. ### `validOpaqueId` [#validopaqueid] ```ts api="@rolebook/sharing" function validOpaqueId(value: unknown): value is string; ``` Whether a value is a string of 1 to `MAX_OPAQUE_ID_LENGTH` (128) UTF-16 units. ### `validAuditEventId` [#validauditeventid] ```ts api="@rolebook/sharing" function validAuditEventId(value: unknown): value is string; ``` Whether a value is a valid audit event ID: 1 to `MAX_AUDIT_EVENT_ID_LENGTH` units whose JSON encoding fits the audit cursor budget. ### `sameRef` [#sameref] ```ts api="@rolebook/sharing" function sameRef(left: ResourceRef, right: ResourceRef): boolean; ``` Whether two references have the same `type` and `id`. ### `dedupeRefs` [#deduperefs] ```ts api="@rolebook/sharing" function dedupeRefs(refs: readonly ResourceRef[]): readonly ResourceRef[]; ``` Drops later duplicate references, keeping first-seen order (frozen). ### `captureRequestingPrincipals` [#capturerequestingprincipals] ```ts api="@rolebook/sharing" function captureRequestingPrincipals( principals: readonly ResourceRef[] | undefined, ): readonly ResourceRef[] | undefined | null; ``` Snapshots a read's `requestingPrincipals`: `undefined` when absent, `null` when malformed (adapters then answer an empty read), otherwise a deduplicated frozen list. ### `captureMemberRoleHint` [#capturememberrolehint] ```ts api="@rolebook/sharing" function captureMemberRoleHint(value: unknown): readonly string[] | undefined | null; ``` Snapshots `listCandidates.memberRoles`: `undefined` when absent, `null` when malformed (first-party adapters throw `RangeError`), otherwise a deduplicated frozen list. ### `missingFactFenceMessage` [#missingfactfencemessage] ```ts api="@rolebook/sharing" function missingFactFenceMessage( adapter: string, facts: readonly { readonly type: string; }[], hint?: string, ): string; ``` The operator message an adapter logs once when a mutation carries authorization facts but no fact fence is configured. The mutation still fails closed. ## In-memory adapter [#in-memory-adapter] ### `createMemorySharingAdapter` [#creatememorysharingadapter] ```ts api="@rolebook/sharing" function createMemorySharingAdapter( options?: CreateMemorySharingAdapterOptions, ): MemorySharingAdapter; ``` A deterministic in-memory adapter for tests and the contract kit. Not for production: it takes no locks. See [the in-memory adapter](/docs/sharing/adapters#the-in-memory-adapter). ### `CreateMemorySharingAdapterOptions` [#creatememorysharingadapteroptions] ```ts api="@rolebook/sharing" interface CreateMemorySharingAdapterOptions { readonly clock?: SharingClock; readonly fenceEligibleSubjects?: (input: { readonly tenantId: string; readonly subjects: readonly ResourceRef[]; }) => boolean | Promise; readonly readEligibleSubjects?: MemoryEligibilityReader; readonly fenceInvitationRecipient?: (input: InvitationRecipientFenceInput) => boolean; readonly groupSubjectTypes?: readonly string[]; readonly revalidateAuthorizationFacts?: (input: { readonly tenantId: string; readonly facts: readonly TransactionalAuthorizationFact[]; }) => boolean | Promise; readonly fencePolicy?: (input: { readonly tenantId: string; readonly expectedPolicy: ExpectedPolicy; }) => PolicyFenceResult; readonly governanceGate?: GovernanceDirectGate; readonly governanceBinding?: GovernanceBinding; } ``` `clock`, `fenceEligibleSubjects`, `readEligibleSubjects`, `fenceInvitationRecipient`, `groupSubjectTypes` (default `["team"]`), `revalidateAuthorizationFacts`, and `fencePolicy`. `readEligibleSubjects` is the evidence form of `fenceEligibleSubjects` for [listing pages](/docs/sharing/listing#tenant-eligibility). When `fenceEligibleSubjects` is configured without it, `listAccessible()` and `listAccess()` answer `identity_evidence_missing`; ordinary reads and mutations keep using `fenceEligibleSubjects`. ### `MemoryEligibilityReader` [#memoryeligibilityreader] ```ts api="@rolebook/sharing" type MemoryEligibilityReader = (input: { readonly tenantId: string; readonly subjects: readonly ResourceRef[]; readonly evaluatedAt: string; }) => MemoryEligibilityEvidence; ``` Answers synchronously whether every subject is eligible at `evaluatedAt`, the adapter clock's reading for the page. Judge by that instant; do not read a clock. ### `MemoryEligibilityEvidence` [#memoryeligibilityevidence] ```ts api="@rolebook/sharing" interface MemoryEligibilityEvidence { readonly eligible: boolean; readonly expiryDependencies: readonly string[]; } ``` `eligible` must be exactly a boolean. `expiryDependencies` lists every instant at which the answer could change on its own, as ISO 8601 UTC instants with exactly three fractional digits; it is empty only when the answer depends on no time. ### `MemorySharingAdapter` [#memorysharingadapter] ```ts api="@rolebook/sharing" interface MemorySharingAdapter extends SharingAdapter, SettledRecordPruner { seed(seed: MemorySharingSeed): void; readAudit(): readonly SharingAuditEvent[]; advanceResourceVersion(input: { readonly tenantId: string; readonly resourceId: string; readonly resource: TrustedResource; }): void; } ``` The memory adapter, with `seed()`, `readAudit()`, `advanceResourceVersion()`, and pruning. ### `MemorySharingSeed` [#memorysharingseed] ```ts api="@rolebook/sharing" interface MemorySharingSeed { readonly tenantId: string; readonly resourceId: string; readonly resource: TrustedResource; readonly owner: OwnerRef; readonly createdAt?: Date; readonly createdBy?: ResourceRef; readonly resourceVersion?: string; readonly memberships?: readonly Omit[]; } ``` A resource to place in the memory adapter, with its owner and optional memberships. ## Retention [#retention] See [retention and pruning](/docs/sharing/retention). ### `SettledRecordPruner` [#settledrecordpruner] ```ts api="@rolebook/sharing" interface SettledRecordPruner { pruneSettledRecords(input: PruneSettledRecordsInput): Promise; } ``` The pruning method of the first-party adapters. Not part of `SharingAdapter`. ### `PruneSettledRecordsInput` [#prunesettledrecordsinput] ```ts api="@rolebook/sharing" type PruneSettledRecordsInput = | PruneWithDefaultsInput | PruneIdempotencyInput | PruneInvitationsInput | PruneBothInput; ``` One pruning request: defaults for both kinds, or named kinds with their retentions. ### `PruneWithDefaultsInput` [#prunewithdefaultsinput] ```ts api="@rolebook/sharing" type PruneWithDefaultsInput = PruneSettledRecordsBase & { readonly kinds?: never; readonly idempotencyRetentionMs?: never; readonly invitationRetentionMs?: never; }; ``` Both kinds at their 30-day defaults. ### `PruneIdempotencyInput` [#pruneidempotencyinput] ```ts api="@rolebook/sharing" type PruneIdempotencyInput = PruneSettledRecordsBase & IdempotencyRetention & { readonly kinds: readonly ["idempotency"]; readonly invitationRetentionMs?: never; }; ``` Idempotency records only. ### `PruneInvitationsInput` [#pruneinvitationsinput] ```ts api="@rolebook/sharing" type PruneInvitationsInput = PruneSettledRecordsBase & InvitationRetention & { readonly kinds: readonly ["invitations"]; readonly idempotencyRetentionMs?: never; }; ``` Settled invitations only. ### `PruneBothInput` [#prunebothinput] ```ts api="@rolebook/sharing" type PruneBothInput = PruneSettledRecordsBase & IdempotencyRetention & InvitationRetention & { readonly kinds: | readonly ["idempotency", "invitations"] | readonly ["invitations", "idempotency"]; }; ``` Both kinds, each with its own retention. ### `RetentionScope` [#retentionscope] ```ts api="@rolebook/sharing" type RetentionScope = | { readonly tenantId: string; readonly allTenants?: never; } | { readonly allTenants: true; readonly tenantId?: never; }; ``` One tenant, or `{ allTenants: true }`. There is no implicit all. ### `SettledRecordKind` [#settledrecordkind] ```ts api="@rolebook/sharing" type SettledRecordKind = "idempotency" | "invitations"; ``` ### `PruneSettledRecordsResult` [#prunesettledrecordsresult] ```ts api="@rolebook/sharing" interface PruneSettledRecordsResult { readonly deleted: { readonly idempotency: number; readonly invitations: number; }; readonly exhausted: boolean; readonly cutoffs: { readonly idempotency?: Date; readonly invitations?: Date; }; } ``` Rows deleted per kind, whether the backlog is `exhausted`, and the cutoffs used. ### `PruneSettledRecordsRequest` [#prunesettledrecordsrequest] ```ts api="@rolebook/sharing" interface PruneSettledRecordsRequest { readonly tenantId: string | undefined; readonly idempotencyRetentionMs: number | undefined; readonly invitationRetentionMs: number | undefined; readonly limit: number; } ``` A validated, captured pruning request. ### `capturePruneSettledRecordsInput` [#captureprunesettledrecordsinput] ```ts api="@rolebook/sharing" function capturePruneSettledRecordsInput(input: unknown): PruneSettledRecordsRequest; ``` Validates and captures a pruning request, throwing `RetentionError` for anything invalid. ### `pruneCutoffs` [#prunecutoffs] ```ts api="@rolebook/sharing" function pruneCutoffs( request: PruneSettledRecordsRequest, now: number, ): { readonly idempotency?: Date; readonly invitations?: Date; }; ``` The cutoff instants for a captured request, measured back from `now`. ### `pruneResult` [#pruneresult] ```ts api="@rolebook/sharing" function pruneResult( request: PruneSettledRecordsRequest, cutoffs: PruneSettledRecordsResult["cutoffs"], deleted: { readonly idempotency: number; readonly invitations: number; }, ): PruneSettledRecordsResult; ``` Assembles a result: exhausted when every pruned kind deleted fewer rows than the limit. ### `invitationSettledBefore` [#invitationsettledbefore] ```ts api="@rolebook/sharing" function invitationSettledBefore(invitation: SharingInvitation, cutoff: Date): boolean; ``` Whether an invitation was consumed, revoked, or expired strictly before the cutoff. ### `DEFAULT_IDEMPOTENCY_RETENTION_MS` [#default_idempotency_retention_ms] ```ts api="@rolebook/sharing" const DEFAULT_IDEMPOTENCY_RETENTION_MS: number; ``` 30 days. ### `DEFAULT_INVITATION_RETENTION_MS` [#default_invitation_retention_ms] ```ts api="@rolebook/sharing" const DEFAULT_INVITATION_RETENTION_MS: number; ``` 30 days. ### `MIN_IDEMPOTENCY_RETENTION_MS` [#min_idempotency_retention_ms] ```ts api="@rolebook/sharing" const MIN_IDEMPOTENCY_RETENTION_MS = 86400000; ``` One day. ### `MIN_INVITATION_RETENTION_MS` [#min_invitation_retention_ms] ```ts api="@rolebook/sharing" const MIN_INVITATION_RETENTION_MS = 86400000; ``` One day. ### `MAX_RETENTION_MS` [#max_retention_ms] ```ts api="@rolebook/sharing" const MAX_RETENTION_MS = 3153600000000; ``` 100 years of 365 days. ### `MAX_PRUNE_BATCH` [#max_prune_batch] ```ts api="@rolebook/sharing" const MAX_PRUNE_BATCH = 1000; ``` The largest `limit` of one pruning call. ## Policy versions and custom roles [#policy-versions-and-custom-roles] See [policy versions and custom roles](/docs/sharing/versioned). ### `PolicyAdministration` [#policyadministration] ```ts api="@rolebook/sharing" interface PolicyAdministration { saveDraft(input: { readonly policy: RolebookPolicy; readonly label?: string; readonly actor: ResourceRef; }): Promise< | { readonly ok: true; readonly code: "SAVED" | "EXISTS"; readonly digest: string; } | { readonly ok: false; readonly code: | "POLICY_TOO_LARGE" | "POLICY_INVALID" | "RESERVED_ROLE_NAME" | "DEFINITION_INCOMPATIBLE" | "INVALID_ACTOR" | "INVALID_LABEL"; readonly reason?: string; } >; readVersion(input: { readonly digest: string }): Promise< | { readonly ok: true; readonly code: "FOUND"; readonly version: PolicyVersionSummary; readonly policy: Readonly; readonly active: boolean; } | { readonly ok: false; readonly code: "VERSION_NOT_FOUND" | "VERSION_CORRUPT"; } >; listVersions(input: { readonly limit: number; readonly cursor?: string }): Promise<{ readonly versions: readonly PolicyVersionSummary[]; readonly nextCursor?: string; }>; listActivations(input: { readonly limit: number; readonly cursor?: string }): Promise<{ readonly activations: readonly PolicyActivation[]; readonly nextCursor?: string; }>; diff(input: { readonly from: string | "active"; readonly to: string | "active" }): Promise< | { readonly ok: true; readonly code: "DIFFED"; readonly diff: PolicyDiff; } | { readonly ok: false; readonly code: "VERSION_NOT_FOUND" | "VERSION_CORRUPT"; } >; previewImpact(input: ImpactInput): Promise; previewCustomRoles(input: CustomRolePreviewInput): Promise; publish(input: { readonly digest: string; readonly expectedGeneration: string; readonly actor: ResourceRef; }): Promise< | { readonly ok: true; readonly code: "ACTIVATED"; readonly generation: string; readonly digest: string; } | { readonly ok: false; readonly code: "GENERATION_CONFLICT"; readonly activeGeneration: string; } | { readonly ok: false; readonly code: "ALREADY_ACTIVE"; readonly activeGeneration: string; } | { readonly ok: false; readonly code: | "VERSION_NOT_FOUND" | "VERSION_CORRUPT" | "DEFINITION_INCOMPATIBLE" | "INVALID_ACTOR" | "GENERATION_EXHAUSTED"; } >; } ``` Version administration: `saveDraft`, `readVersion`, `listVersions`, `listActivations`, `diff`, `previewImpact`, `previewCustomRoles`, `publish`. It records the actor but does not authorize it. ### `CustomRoleAdministration` [#customroleadministration] ```ts api="@rolebook/sharing" interface CustomRoleAdministration { list(input: { readonly tenantId: string }): Promise< | { readonly ok: true; readonly code: "LISTED"; readonly revision: string; readonly generation: string; readonly roles: readonly CustomRoleView[]; } | { readonly ok: false; readonly code: "INVALID_TENANT"; } >; define(input: { readonly tenantId: string; readonly resourceType: string; readonly name: CustomRoleLabel; readonly template: string; readonly rules: readonly PolicyRule[]; readonly expectedRevision: string; readonly actor: ResourceRef; }): Promise< | { readonly ok: true; readonly code: "DEFINED"; readonly revision: string; } | { readonly ok: false; readonly code: "CEILING_EXCEEDED"; readonly permissions: readonly string[]; } | { readonly ok: false; readonly code: "CUSTOM_ROLE_INVALID"; readonly reason: "name" | "rules" | "limits"; } | { readonly ok: false; readonly code: | "INVALID_TENANT" | "INVALID_ACTOR" | "UNKNOWN_RESOURCE_TYPE" | "TEMPLATE_UNKNOWN" | "TOO_MANY_CUSTOM_ROLES" | "CUSTOM_ROLE_NAME_RETIRED" | "REVISION_CONFLICT" | "GENERATION_CONFLICT" | "REVISION_EXHAUSTED"; } >; remove(input: { readonly tenantId: string; readonly resourceType: string; readonly name: CustomRoleLabel; readonly expectedRevision: string; readonly actor: ResourceRef; }): Promise< | { readonly ok: true; readonly code: "REMOVED"; readonly revision: string; } | { readonly ok: false; readonly code: | "INVALID_TENANT" | "INVALID_ACTOR" | "NOT_FOUND" | "REVISION_CONFLICT" | "REVISION_EXHAUSTED"; } >; set?(input: CustomRoleSetInput): Promise; } ``` Tenant custom roles: `list`, `define`, `remove`, and `set`. It records the actor but does not authorize it. `set` makes `roles` the tenant's complete set of live custom roles in one write. Its checks run in this order and the first failure answers, with nothing written: the input (`INVALID_TENANT`, `INVALID_ACTOR`, `INVALID_ROLES` for a value that is not an array of plain role records, `TOO_MANY_CUSTOM_ROLES` for more than `MAX_CUSTOM_ROLES_PER_TENANT` roles); then the stored roles, read in one consistent read: a revision other than `expectedRevision` is `REVISION_CONFLICT`, and any stored row that does not decode is `CUSTOM_ROLE_UNREADABLE`, naming it; then each role, in the order given, with the checks `define` makes before it reads the stored roles (resource type, name, a role named twice as `CUSTOM_ROLE_INVALID` with reason `duplicate`, template, rules, and the role on its own beside the base policy); then the rest of the stored roles: a role whose name is retired is `CUSTOM_ROLE_NAME_RETIRED`, and a result over `MAX_CUSTOM_ROLE_RECORDS_PER_TENANT` rows is `TOO_MANY_CUSTOM_ROLES`; then each role's template-derived rules, the whole set beside the base policy (`CUSTOM_ROLE_INVALID` with reason `limits` or `rules` and no role), and each role's template ceiling (`CEILING_EXCEEDED`). The limits are counted on the result, so a set that removes one role and adds another at the live limit applies, where a `define` of the addition alone is refused. A refusal about one role names it in `role`. Every role in the set gets these checks, including one that is already live and unchanged: an unchanged role that the active policy no longer admits (its template's ceiling narrowed, say) refuses the set. A live role the set does not name is removed: it is tombstoned, as by `remove`, so its name is retired. A role that is live with the same template and rules is not rewritten, and keeps its `definedAtRevision`, and so does a removed one; every role the set defines or replaces gets the new revision. A row that does not decode cannot be judged live or retired, so no set can say what keeping, replacing or omitting it would do: every set is refused `CUSTOM_ROLE_UNREADABLE` until the row is repaired in the database (`remove` does not help: it tombstones the row, and the tombstone still does not decode). Every change, one revision bump and one policy audit event per change (`custom_role.defined` or `custom_role.deleted`) are written by one [`writeTenantRoleSet`](#policystore) call, fenced on `expectedRevision` and on the generation the checks used: a `define`, `remove`, `set` or policy publish that commits between the set's reads and its write makes it answer `REVISION_CONFLICT` or `GENERATION_CONFLICT` and write nothing; it never interleaves with them. A set that changes nothing writes nothing and answers `UNCHANGED` with the revision it read; it holds no fence, so a change committed after that read is not reported. `set` is present only when the instance's policy store implements `writeTenantRoleSet`, as the memory, SQLite and PostgreSQL stores do. ### `CustomRoleSetInput` [#customrolesetinput] ```ts api="@rolebook/sharing" interface CustomRoleSetInput { readonly tenantId: string; readonly roles: readonly CustomRoleSetEntry[]; readonly expectedRevision: string; readonly expectedGeneration?: string; readonly actor: ResourceRef; } ``` One `set` call: the tenant, the complete desired set of live roles, the revision it was decided from, and the actor recorded on every change. With `expectedGeneration` (for example `list()`'s `generation`), the set answers `GENERATION_CONFLICT` and writes nothing unless it validates under exactly that generation; a present value that is not a string conflicts too. Before any role is checked, the named generation is compared with the store's active generation, not with the instance's cached view (which is reloaded when the store has moved on), so every refusal is computed under exactly the generation the caller named: after a publish through another instance the answer is `GENERATION_CONFLICT`, never a refusal computed under either policy. Without it, the set validates under whatever generation is active after its refresh. ### `CustomRoleSetEntry` [#customrolesetentry] ```ts api="@rolebook/sharing" interface CustomRoleSetEntry { readonly resourceType: string; readonly name: CustomRoleLabel; readonly template: string; readonly rules: readonly PolicyRule[]; } ``` One role of a set, as `define` takes it. ### `CustomRoleSetResult` [#customrolesetresult] ```ts api="@rolebook/sharing" type CustomRoleSetResult = | { readonly ok: true; readonly code: "SET" | "UNCHANGED"; readonly revision: string } | { readonly ok: false; readonly code: "CEILING_EXCEEDED"; readonly role: CustomRoleSetRoleRef; readonly permissions: readonly string[]; } | { readonly ok: false; readonly code: "CUSTOM_ROLE_INVALID"; readonly reason: "name" | "rules" | "limits" | "duplicate"; readonly role?: CustomRoleSetRoleRef; } | { readonly ok: false; readonly code: | "UNKNOWN_RESOURCE_TYPE" | "TEMPLATE_UNKNOWN" | "CUSTOM_ROLE_NAME_RETIRED" | "CUSTOM_ROLE_UNREADABLE"; readonly role: CustomRoleSetRoleRef; } | { readonly ok: false; readonly code: | "INVALID_TENANT" | "INVALID_ACTOR" | "INVALID_ROLES" | "TOO_MANY_CUSTOM_ROLES" | "REVISION_CONFLICT" | "GENERATION_CONFLICT" | "REVISION_EXHAUSTED"; }; ``` `SET` with the new revision, `UNCHANGED` with the revision read, or the first refusal. The store's `conflict`, and a `retired`, `not_found` or `too_many` that the checks above already ruled out at the revision read, answer `REVISION_CONFLICT`; nothing was written. ### `CustomRoleSetRoleRef` [#customrolesetroleref] ```ts api="@rolebook/sharing" interface CustomRoleSetRoleRef { readonly resourceType: string; readonly name: string; } ``` The role a `set` refusal is about. ### `ActivePolicyState` [#activepolicystate] ```ts api="@rolebook/sharing" interface ActivePolicyState { readonly generation: string; readonly digest: string; readonly label?: string; readonly confirmedAt: Date; readonly seedMatchesActive: boolean; } ``` The active generation, digest, label, when it was confirmed, and whether the code seed still matches. ### `ImpactInput` [#impactinput] ```ts api="@rolebook/sharing" type ImpactInput = { readonly candidate: string; readonly tenantId: string; } & ( | { readonly pairs: readonly { readonly subject: ResourceRef; readonly resource: ResourceKey; }[]; } | { readonly sample: { readonly subjects: readonly ResourceRef[]; readonly resourceType: string; readonly perSubjectLimit: number; }; } ); ``` Explicit subject and resource pairs, or a sample of subjects and a resource type. ### `ImpactChange` [#impactchange] ```ts api="@rolebook/sharing" interface ImpactChange { readonly subject: ResourceRef; readonly resource: ResourceKey; readonly label: string; readonly permission: string; readonly before: { readonly allowed: boolean; readonly code: string; }; readonly after: { readonly allowed: boolean; readonly code: string; }; } ``` One decision that changes between the active and the candidate policy. ### `ImpactResult` [#impactresult] ```ts api="@rolebook/sharing" type ImpactResult = | { readonly ok: true; readonly code: "PREVIEWED"; readonly active: { readonly generation: string; readonly digest: string; }; readonly candidate: { readonly digest: string; }; readonly exhaustive: boolean; readonly changes: readonly ImpactChange[]; readonly unevaluable: readonly { readonly subject: ResourceRef; readonly resource?: ResourceKey; readonly reason: "SUBJECT_INELIGIBLE" | "RESOURCE_NOT_FOUND"; }[]; readonly summary: { readonly pairsEvaluated: number; readonly grantsGained: number; readonly grantsLost: number; readonly subjectsGaining: number; readonly subjectsLosing: number; }; readonly customRolesLosingAvailability: readonly CustomRoleLabel[]; } | { readonly ok: false; readonly code: | "PREVIEW_TOO_LARGE" | "INVALID_PREVIEW_INPUT" | "VERSION_NOT_FOUND" | "VERSION_CORRUPT" | "DEFINITION_INCOMPATIBLE"; }; ``` The changes, the pairs that could not be evaluated, a summary, and custom roles losing availability. ### `CustomRolePreviewInput` [#customrolepreviewinput] ```ts api="@rolebook/sharing" interface CustomRolePreviewInput { readonly candidate: string; readonly limit: number; readonly cursor?: string; } ``` A candidate digest and a page of tenants. ### `CustomRolePreviewResult` [#customrolepreviewresult] ```ts api="@rolebook/sharing" type CustomRolePreviewResult = | { readonly ok: true; readonly code: "PREVIEWED"; readonly tenants: readonly { readonly tenantId: string; readonly roles: readonly { readonly resourceType: string; readonly name: CustomRoleLabel; readonly activeStatus: CustomRoleStatus; readonly candidateStatus: CustomRoleStatus; readonly permissionsAboveTemplate?: readonly string[]; }[]; }[]; readonly nextCursor?: string; } | { readonly ok: false; readonly code: "VERSION_NOT_FOUND" | "VERSION_CORRUPT" | "DEFINITION_INCOMPATIBLE"; }; ``` Per tenant, each custom role's status under the active and the candidate policy. ### `CustomRoleStatus` [#customrolestatus] ```ts api="@rolebook/sharing" type CustomRoleStatus = | "available" | "retired" | "template_missing" | "invalid" | "exceeds_template"; ``` ### `CustomRoleView` [#customroleview] ```ts api="@rolebook/sharing" interface CustomRoleView { readonly resourceType: string; readonly name: CustomRoleLabel; readonly template: string; readonly rules: readonly PolicyRule[]; readonly effectiveRules: readonly PolicyRule[]; readonly status: CustomRoleStatus; readonly permissionsAboveTemplate?: readonly string[]; readonly definedAtRevision: string; readonly createdAt: Date; readonly createdBy: ResourceRef; readonly updatedAt: Date; readonly updatedBy: ResourceRef; readonly deletedAt?: Date; } ``` One custom role as listed, with its status and, for `exceeds_template`, the permissions above it. ### `CustomRoleLabel` [#customrolelabel] ```ts api="@rolebook/sharing" type CustomRoleLabel = `custom:${string}`; ``` A `custom:` label. Valid names match `CUSTOM_ROLE_LABEL`. ### `policyDigest` [#policydigest] ```ts api="@rolebook/sharing" function policyDigest(policy: RolebookPolicy): string; ``` `sha256:` plus the hex SHA-256 of the policy's canonical JSON. The version label is excluded. ### `parseCounter` [#parsecounter] ```ts api="@rolebook/sharing" function parseCounter(value: unknown): bigint | undefined; ``` A decimal generation or revision as a `bigint`, or `undefined` when it is not a canonical counter within `MAX_POLICY_COUNTER`. ## Policy store [#policy-store] ### `PolicyStore` [#policystore] ```ts api="@rolebook/sharing" interface PolicyStore { readActivePointer(): Promise; readVersion(input: { readonly digest: string }): Promise; listVersions(input: { readonly limit: number; readonly cursor?: string }): Promise<{ readonly versions: readonly PolicyVersionSummary[]; readonly nextCursor?: string; }>; listActivations(input: { readonly limit: number; readonly cursor?: string }): Promise<{ readonly activations: readonly PolicyActivation[]; readonly nextCursor?: string; }>; saveVersion(input: { readonly version: StoredPolicyVersion; readonly audit: PolicyAuditEvent; }): Promise<"saved" | "exists">; activate(input: { readonly digest: string; readonly expectedGeneration: string; readonly activatedAt: Date; readonly activatedBy: ResourceRef; readonly audit: PolicyAuditEvent; }): Promise< | { readonly status: "activated"; readonly generation: string; } | { readonly status: "conflict"; readonly generation: string; } | { readonly status: "already_active"; readonly generation: string; } | { readonly status: "not_found"; } | { readonly status: "exhausted"; } >; readTenantRolesRevision(input: { readonly tenantId: string }): Promise; readTenantRoles(input: { readonly tenantId: string }): Promise; writeTenantRole(input: { readonly role: Omit; readonly expectedRevision: string; readonly expectedGeneration: string; readonly audit: PolicyAuditEvent; }): Promise< | { readonly status: "applied"; readonly revision: string; } | { readonly status: "conflict"; } | { readonly status: "generation_conflict"; } | { readonly status: "retired"; } | { readonly status: "too_many"; } | { readonly status: "exhausted"; } >; deleteTenantRole(input: { readonly tenantId: string; readonly resourceType: string; readonly name: CustomRoleLabel; readonly expectedRevision: string; readonly deletedAt: Date; readonly deletedBy: ResourceRef; readonly audit: PolicyAuditEvent; }): Promise< | { readonly status: "applied"; readonly revision: string; } | { readonly status: "conflict"; } | { readonly status: "not_found"; } | { readonly status: "exhausted"; } >; writeTenantRoleSet?(input: TenantRoleSetWrite): Promise< | { readonly status: "applied"; readonly revision: string } | { readonly status: "conflict" } | { readonly status: "generation_conflict" } | { readonly status: "retired" } | { readonly status: "not_found" } | { readonly status: "too_many" } | { readonly status: "exhausted" } >; listAudit(input: { readonly limit: number; readonly cursor?: string; readonly tenantId?: string; }): Promise<{ readonly events: readonly PolicyAuditEvent[]; readonly nextCursor?: string; }>; listTenantsWithCustomRoles(input: { readonly limit: number; readonly cursor?: string }): Promise<{ readonly tenantIds: readonly string[]; readonly nextCursor?: string; }>; } ``` The policy store contract: the active pointer, versions, activations, tenant custom roles, the policy audit, and tenant listing. `activate`, `writeTenantRole`, `deleteTenantRole`, and `writeTenantRoleSet` compare-and-swap. The first-party stores are `createPostgresPolicyStore`, `createSqlitePolicyStore`, and `createMemoryPolicyStore`; each implements the optional `writeTenantRoleSet`. `writeTenantRoleSet` applies several role changes as one write: every `define` (insert or replace a live role) and `remove` (tombstone a live role), one revision bump and every audit event commit in one transaction, or nothing does. It compares the active generation and then the tenant's revision before anything else, under the same locks `writeTenantRole` takes (on PostgreSQL the pointer `FOR SHARE` and the revision row `FOR UPDATE`; on SQLite one `BEGIN IMMEDIATE` transaction), so a concurrent role write or publish answers `generation_conflict` or `conflict`. Only then is a `define` of a tombstone `retired`, a `remove` of no live role `not_found`, and a result over the live or record limit `too_many`. Every defined role's `definedAtRevision` is the new revision; a removed role keeps its own, as `deleteTenantRole` leaves it. The SQLite and PostgreSQL stores decide every refusal before they create a tenant's first revision row, so any answer other than `applied` leaves the store exactly as it was. A store without it leaves `customRoles.set` absent; `policyStoreContract` in `@rolebook/sharing-testkit` fails for such a store. ### `TenantRoleSetWrite` [#tenantrolesetwrite] ```ts api="@rolebook/sharing" interface TenantRoleSetWrite { readonly tenantId: string; readonly define: readonly Omit[]; readonly remove: readonly { readonly resourceType: string; readonly name: CustomRoleLabel }[]; readonly expectedRevision: string; readonly expectedGeneration: string; readonly removedAt: Date; readonly removedBy: ResourceRef; readonly audit: readonly PolicyAuditEvent[]; } ``` One `writeTenantRoleSet` call. `removedAt` and `removedBy` are the tombstone time and actor of every removed role; `audit` holds one event per change. ### `assertTenantRoleSetWrite` [#asserttenantrolesetwrite] ```ts api="@rolebook/sharing" function assertTenantRoleSetWrite(input: TenantRoleSetWrite): void; ``` The input rules every store applies before it writes: a valid tenant id, at least one change, each `(resourceType, name)` at most once across both lists and a valid custom-role name, every defined role in the call's tenant, and exactly one audit event per change, each passing [`assertPolicyAuditEventFields`](#assertpolicyauditeventfields), naming that tenant, that change's resource type and role name as strings, and `custom_role.defined` for a definition or `custom_role.deleted` for a removal; every change must be matched by exactly one event. Nothing is written when a rule fails. An invalid tenant ID, on the call or on an event, throws `PolicyAdministrationError` with code `INVALID_TENANT`; any other invalid audit event field throws `PolicyAdministrationError` with code `INVALID_AUDIT_EVENT`; every other failure (no change, a role named twice, an invalid role name, a role or event in another tenant, an event that names no role change or matches no change, a change with no event) throws `TypeError`. ### `ActivePolicyPointer` [#activepolicypointer] ```ts api="@rolebook/sharing" interface ActivePolicyPointer { readonly generation: string; readonly digest: string | null; } ``` The active generation and digest; the digest is `null` exactly at generation `"0"`. ### `StoredPolicyVersion` [#storedpolicyversion] ```ts api="@rolebook/sharing" interface StoredPolicyVersion { readonly digest: string; readonly document: string; readonly label?: string; readonly createdAt: Date; readonly createdBy: ResourceRef; } ``` A stored version: digest, canonical document, optional label, creation. ### `PolicyVersionSummary` [#policyversionsummary] ```ts api="@rolebook/sharing" type PolicyVersionSummary = Omit; ``` A stored version without its document. ### `PolicyActivation` [#policyactivation] ```ts api="@rolebook/sharing" interface PolicyActivation { readonly generation: string; readonly digest: string; readonly activatedAt: Date; readonly activatedBy: ResourceRef; } ``` One activation: generation, digest, when, and by whom. ### `StoredCustomRole` [#storedcustomrole] ```ts api="@rolebook/sharing" interface StoredCustomRole { readonly tenantId: string; readonly resourceType: string; readonly name: CustomRoleLabel; readonly template: string; readonly rules: string; readonly definedAtRevision: string; readonly createdAt: Date; readonly createdBy: ResourceRef; readonly updatedAt: Date; readonly updatedBy: ResourceRef; readonly deletedAt?: Date; } ``` A stored custom role row, including tombstones. ### `UndecodableCustomRole` [#undecodablecustomrole] ```ts api="@rolebook/sharing" interface UndecodableCustomRole { readonly resourceType: string; readonly name: string; readonly undecodable: true; } ``` An identifiable custom-role row whose other columns do not decode. ### `TenantCustomRoles` [#tenantcustomroles] ```ts api="@rolebook/sharing" interface TenantCustomRoles { readonly revision: string; readonly roles: readonly (StoredCustomRole | UndecodableCustomRole)[]; } ``` A tenant's custom-role revision and every row, tombstones included. ### `ExpectedPolicy` [#expectedpolicy] ```ts api="@rolebook/sharing" interface ExpectedPolicy { readonly generation: string; readonly tenantRolesRevision: string; } ``` The generation and tenant-role revision a versioned mutation started under. ### `PolicyFenceResult` [#policyfenceresult] ```ts api="@rolebook/sharing" type PolicyFenceResult = true | "policy_generation_changed" | "tenant_roles_changed"; ``` `true`, or why a versioned mutation's policy no longer holds. ### `PolicyAuditEvent` [#policyauditevent] ```ts api="@rolebook/sharing" interface PolicyAuditEvent { readonly id: string; readonly tenantId?: string; readonly action: | "policy.version_saved" | "policy.activated" | "custom_role.defined" | "custom_role.deleted"; readonly digest?: string; readonly generation?: string; readonly resourceType?: string; readonly roleName?: string; readonly actor: ResourceRef; readonly occurredAt: Date; } ``` One policy-administration audit event. ### `createMemoryPolicyStore` [#creatememorypolicystore] ```ts api="@rolebook/sharing" function createMemoryPolicyStore(): MemoryPolicyStore; ``` An in-memory `PolicyStore` for tests, with a synchronous `fence` for the memory adapter. ### `MemoryPolicyStore` [#memorypolicystore] ```ts api="@rolebook/sharing" interface MemoryPolicyStore extends PolicyStore { fence(input: { readonly tenantId: string; readonly expectedPolicy: ExpectedPolicy; }): PolicyFenceResult; failWith(error: Error | undefined): void; readAudit(): readonly PolicyAuditEvent[]; setCounters(input: { readonly generation?: string; readonly tenantRevisions?: Readonly>; }): void; failNextAudit(): void; } ``` The memory store, with `fence`, `failWith`, `readAudit`, `setCounters`, and `failNextAudit`. ### `assertPolicyTenantId` [#assertpolicytenantid] ```ts api="@rolebook/sharing" function assertPolicyTenantId(tenantId: unknown): asserts tenantId is string; ``` Throws `PolicyAdministrationError` (`INVALID_TENANT`) unless the value is a valid opaque ID. ### `assertPolicyAuditEvent` [#assertpolicyauditevent] ```ts api="@rolebook/sharing" function assertPolicyAuditEvent(event: Pick): void; ``` Throws `PolicyAdministrationError` for an audit ID or tenant ID a policy cursor cannot carry. ### `assertPolicyAuditEventFields` [#assertpolicyauditeventfields] ```ts api="@rolebook/sharing" function assertPolicyAuditEventFields(event: PolicyAuditEvent): void; ``` Every field of a policy audit event: `assertPolicyAuditEvent`'s ID and tenant ID, a known `action`, an `actor` whose `type` and `id` are opaque IDs, an `occurredAt` that is a valid `Date`, and, when present, a `POLICY_DIGEST` `digest`, a `POLICY_GENERATION` `generation` of at most `MAX_POLICY_COUNTER`, and string `resourceType` and `roleName`. An invalid tenant ID throws `PolicyAdministrationError` with code `INVALID_TENANT`; any other invalid field, the ID included, throws `PolicyAdministrationError` with code `INVALID_AUDIT_EVENT`. `writeTenantRole`, `deleteTenantRole` and `assertTenantRoleSetWrite` apply it to every event, in the memory, SQLite and PostgreSQL stores, before anything is written. ### `assertPolicyDigest` [#assertpolicydigest] ```ts api="@rolebook/sharing" function assertPolicyDigest(digest: unknown): asserts digest is string; ``` Throws `PolicyAdministrationError` (`INVALID_DIGEST`) unless the value matches `POLICY_DIGEST`. ## Hierarchy command configuration [#hierarchy-command-configuration] The command map the hierarchy control facades of `@rolebook/sharing-postgres` and `@rolebook/sharing-sqlite` run. See [inherited access](/docs/sharing/inheritance). ### `defineHierarchyCommands` [#definehierarchycommands] ```ts api="@rolebook/sharing" function defineHierarchyCommands(policy: RolebookPolicy, graph: HierarchyTypeGraph, input: HierarchyCommandsInput): HierarchyCommands; ``` Validates a hierarchy command configuration against a policy and its hierarchy type graph and returns it frozen. Configured actions must be concrete, declared and distinct, and the bootstrap type is restricted. Validation alone enables nothing; the control facades validate the same map. ### `HierarchyCommandsInput` [#hierarchycommandsinput] ```ts api="@rolebook/sharing" interface HierarchyCommandsInput { readonly bootstrap: { readonly type: string; readonly actions: Readonly>; }; readonly types: Readonly>; } ``` The configuration `defineHierarchyCommands` validates: the bootstrap authority type with one action per `HierarchyBootstrapAction`, and the structural actions of each hierarchy type. ### `HierarchyCommands` [#hierarchycommands] ```ts api="@rolebook/sharing" interface HierarchyCommands { readonly bootstrap: HierarchyCommandsInput["bootstrap"]; readonly types: Readonly>; } ``` The validated, frozen configuration. ### `HierarchyTypeCommands` [#hierarchytypecommands] ```ts api="@rolebook/sharing" interface HierarchyTypeCommands { readonly delete: string; readonly move: string; readonly createChild?: string; readonly addChild?: string; readonly removeChild?: string; } ``` The actions that authorize deleting or moving a resource of a type, and creating, adding or removing its children. ### `HierarchyBootstrapAction` [#hierarchybootstrapaction] ```ts api="@rolebook/sharing" type HierarchyBootstrapAction = (typeof HIERARCHY_BOOTSTRAP_ACTIONS)[number]; ``` One bootstrap action name. ### `HIERARCHY_BOOTSTRAP_ACTIONS` [#hierarchy_bootstrap_actions] ```ts api="@rolebook/sharing" const HIERARCHY_BOOTSTRAP_ACTIONS: readonly [ "rootCreate", "rootPlacement", "enrollment", "activation", "quarantineRelease", "heightRepair" ]; ``` Every bootstrap action a configuration must map. ### `HierarchyTypeGraph` [#hierarchytypegraph] ```ts api="@rolebook/sharing" interface HierarchyTypeGraph { declared(type: string): boolean; parentOf(type: string): string | undefined; recursive(type: string): boolean; } ``` The immutable hierarchy type graph of a policy: which types it declares, each type's declared parent, and whether a type may nest under itself. Build it with `hierarchyTypeGraph`; it exposes no store, lock, issuer or control state. ### `hierarchyTypeGraph` [#hierarchytypegraph-1] ```ts api="@rolebook/sharing" function hierarchyTypeGraph(resources: Readonly>): HierarchyTypeGraph; ``` Builds the graph from a validated policy's resources. Pass the same policy to `defineHierarchyCommands`: `defineHierarchyCommands(policy, hierarchyTypeGraph(policy.resources), input)`. ### `HierarchyConfigurationError` [#hierarchyconfigurationerror] ```ts api="@rolebook/sharing" class HierarchyConfigurationError extends TypeError { constructor(message: string); } ``` Thrown by `defineHierarchyCommands` for an invalid configuration. ### `hierarchyConfigurationGeneration` [#hierarchyconfigurationgeneration] ```ts api="@rolebook/sharing" function hierarchyConfigurationGeneration(input: { readonly label: string; readonly definition: SharingDefinition; readonly commands: HierarchyCommandsInput; }): string; ``` The configuration generation of one inherited-access deployment: `` `${label}#cmd-${digest}` ``, where the digest binds the validated command map and each type's `management.members`. Pass the same value to the adapter's `enable…InheritedReads` and to its hierarchy control facade. The command types must be exactly the types with `inheritance: "ancestors"`. `label` is 1 to 48 characters of letters, digits, `.`, `_` and `-`; change it to force re-activation. ### `InheritanceConfigurationError` [#inheritanceconfigurationerror] ```ts api="@rolebook/sharing" class InheritanceConfigurationError extends TypeError { constructor(message: string); } ``` Thrown when the hierarchy command types and the opted-in types differ, or no type opted in. ## Limits [#limits] ### `MAX_OPAQUE_ID_LENGTH` [#max_opaque_id_length] ```ts api="@rolebook/sharing" const MAX_OPAQUE_ID_LENGTH = 128; ``` The longest tenant, resource, subject, idempotency, and cursor ID: 128 characters. ### `MAX_INVITATION_EMAIL_LENGTH` [#max_invitation_email_length] ```ts api="@rolebook/sharing" const MAX_INVITATION_EMAIL_LENGTH = 320; ``` The longest invitation email address: 320 characters. ### `MAX_GROUP_PRINCIPALS` [#max_group_principals] ```ts api="@rolebook/sharing" const MAX_GROUP_PRINCIPALS: typeof MAX_PRINCIPALS; ``` The most groups one principal may carry: Rolebook's `MAX_PRINCIPALS` (64). ### `MAX_ACCESS_BATCH_SIZE` [#max_access_batch_size] ```ts api="@rolebook/sharing" const MAX_ACCESS_BATCH_SIZE = 200; ``` The most resource IDs one `readAccessBatch` call accepts. ### `MAX_CANDIDATE_HINT_SIZE` [#max_candidate_hint_size] ```ts api="@rolebook/sharing" const MAX_CANDIDATE_HINT_SIZE = 256; ``` The most resource-scoped candidate hints, and member-role hints, one listing sends. ### `MAX_AUDIT_PAGE_LIMIT` [#max_audit_page_limit] ```ts api="@rolebook/sharing" const MAX_AUDIT_PAGE_LIMIT = 100; ``` The largest `limit` of `auditHistory()` and `listAuditEvents`. ### `MAX_AUDIT_CURSOR_LENGTH` [#max_audit_cursor_length] ```ts api="@rolebook/sharing" const MAX_AUDIT_CURSOR_LENGTH = 512; ``` The longest raw cursor `listAuditEvents` may issue or receive. ### `MAX_AUDIT_EVENT_ID_LENGTH` [#max_audit_event_id_length] ```ts api="@rolebook/sharing" const MAX_AUDIT_EVENT_ID_LENGTH = 256; ``` The longest audit event ID read back. ### `MAX_POLICY_CURSOR_LENGTH` [#max_policy_cursor_length] ```ts api="@rolebook/sharing" const MAX_POLICY_CURSOR_LENGTH: number; ``` The longest policy-store cursor a first-party store issues; longer input is rejected. ### `MAX_POLICY_DOCUMENT_BYTES` [#max_policy_document_bytes] ```ts api="@rolebook/sharing" const MAX_POLICY_DOCUMENT_BYTES = 1048576; ``` The largest stored policy document: 1 MiB. ### `MAX_POLICY_LABEL_LENGTH` [#max_policy_label_length] ```ts api="@rolebook/sharing" const MAX_POLICY_LABEL_LENGTH = 128; ``` The longest version label. ### `MAX_POLICY_PAGE_LIMIT` [#max_policy_page_limit] ```ts api="@rolebook/sharing" const MAX_POLICY_PAGE_LIMIT = 100; ``` The largest page of versions, activations, or policy audit. ### `MAX_CUSTOM_ROLES_PER_TENANT` [#max_custom_roles_per_tenant] ```ts api="@rolebook/sharing" const MAX_CUSTOM_ROLES_PER_TENANT = 32; ``` Available, exceeding, and invalid custom roles per tenant. ### `MAX_CUSTOM_ROLE_RECORDS_PER_TENANT` [#max_custom_role_records_per_tenant] ```ts api="@rolebook/sharing" const MAX_CUSTOM_ROLE_RECORDS_PER_TENANT = 256; ``` Custom-role rows per tenant, tombstones included. ### `MAX_CUSTOM_ROLE_RULES` [#max_custom_role_rules] ```ts api="@rolebook/sharing" const MAX_CUSTOM_ROLE_RULES = 64; ``` Operator rules on one custom role. ### `MAX_IMPACT_PAIRS` [#max_impact_pairs] ```ts api="@rolebook/sharing" const MAX_IMPACT_PAIRS = 200; ``` Pairs one impact preview evaluates. ### `MAX_IMPACT_SUBJECTS` [#max_impact_subjects] ```ts api="@rolebook/sharing" const MAX_IMPACT_SUBJECTS = 20; ``` Subjects one sampled impact preview takes. ### `MAX_IMPACT_CANDIDATES_PER_SUBJECT` [#max_impact_candidates_per_subject] ```ts api="@rolebook/sharing" const MAX_IMPACT_CANDIDATES_PER_SUBJECT = 50; ``` Candidate resources per sampled subject. ### `MAX_POLICY_COUNTER` [#max_policy_counter] ```ts api="@rolebook/sharing" const MAX_POLICY_COUNTER = 9223372036854775807n; ``` The largest generation or revision. ### `CUSTOM_ROLE_LABEL` [#custom_role_label] ```ts api="@rolebook/sharing" const CUSTOM_ROLE_LABEL: RegExp; ``` `/^custom:[a-z][a-z0-9_]{0,47}$/` ### `CUSTOM_POLICY_ROLE_PREFIX` [#custom_policy_role_prefix] ```ts api="@rolebook/sharing" const CUSTOM_POLICY_ROLE_PREFIX = "rolebook.custom."; ``` The reserved prefix of derived custom-role policy roles. Published policies may not use it. ### `POLICY_DIGEST` [#policy_digest] ```ts api="@rolebook/sharing" const POLICY_DIGEST: RegExp; ``` `/^sha256:[0-9a-f]{64}$/` ### `POLICY_GENERATION` [#policy_generation] ```ts api="@rolebook/sharing" const POLICY_GENERATION: RegExp; ``` `/^(0|[1-9][0-9]{0,18})$/`; callers also require the value to be at most `MAX_POLICY_COUNTER`. ## Decision metadata foundations [#decision-metadata-foundations] These supporting exports are used by the PostgreSQL [protected application update API](/docs/sharing-postgres/protected-updates). Metadata and fixtures alone do not authorize an application write. The supported wrapper is resource/action scoped; field-mediated post-state enforcement and application operational integration are separate contracts. ### `AuthorityRevision` [#authorityrevision] ```ts api="@rolebook/sharing" interface AuthorityRevision { readonly domain: "policy" | "tenantRoles" | "sharing" | "identityProjection" | "groupMembership"; /** Identifies the revision's scope (a resource for sharing, not a global counter). */ readonly scope: string; /** Decimal or source-owned revision; compare only within the same domain/scope/epoch. */ readonly revision: string; } ``` A revision in one authority domain and scope. Compare it only within that same domain, scope and authority epoch; a resource sharing revision is not a global checkpoint. ### `AchievedConsistency` [#achievedconsistency] ```ts api="@rolebook/sharing" type AchievedConsistency = { readonly mode: "consistentLocalSnapshot"; /** Opaque database snapshot identity, not an atLeast checkpoint. */ readonly snapshotId: string; readonly snapshotObservedAt: string; } | { readonly mode: "boundedStale"; readonly authorityReadAt: string; readonly maxAgeMs: number; }; ``` Describes the consistency actually established by the producer. A local snapshot ID is opaque evidence, not a reusable checkpoint. Bounded-stale evidence records the authority read time and maximum permitted age; it does not attest remote identity freshness. ### `AuthorizationDecisionMetadata` [#authorizationdecisionmetadata] ```ts api="@rolebook/sharing" interface AuthorizationDecisionMetadata { readonly schemaVersion: 1; readonly scopeId: string; readonly authorityEpoch: string; readonly policyVersion: string; readonly revisions: readonly AuthorityRevision[]; readonly evaluatedAt: string; readonly consistency: AchievedConsistency; } ``` Versioned internal/operator evidence for a decision. This is descriptive metadata, not a bearer capability, and must not be automatically serialized to untrusted clients. ### `ConsistencyUnavailableReason` [#consistencyunavailablereason] ```ts api="@rolebook/sharing" type ConsistencyUnavailableReason = "unsupported_mode" | "unsupported_isolation" | "dependency_unavailable" | "unmet_floor" | "incompatible_checkpoint" | "projection_expired"; ``` The reason requested consistency could not be established. These variants describe refusal conditions; their presence does not mean every consistency mode has an implementation. ### `ConsistencyUnavailableError` [#consistencyunavailableerror] ```ts api="@rolebook/sharing" class ConsistencyUnavailableError extends Error { readonly reason: ConsistencyUnavailableReason; readonly code: "CONSISTENCY_UNAVAILABLE"; constructor(reason: ConsistencyUnavailableReason); } ``` Reports `CONSISTENCY_UNAVAILABLE` with a structured reason. Callers must treat unavailable consistency as a refusal rather than falling back to a stale allow. ### `captureAuthorizationDecisionMetadata` [#captureauthorizationdecisionmetadata] ```ts api="@rolebook/sharing" function captureAuthorizationDecisionMetadata(value: unknown): AuthorizationDecisionMetadata; ``` Validates the version-one metadata contract, copies JSON-compatible values and freezes the captured evidence. Rejects malformed fields, unsupported domains, invalid timestamps and bounded-staleness evidence outside its permitted age window with a `TypeError`. It validates supplied evidence; it does not establish the authority of the producer. ### `compareBatchResource` [#comparebatchresource] ```ts api="@rolebook/sharing" function compareBatchResource(left: { readonly id: string; }, right: { readonly id: string; }): number; ``` UTF-16 code-unit order of resource ids. Batch capture, target locks, the stored result, version-3 targets and the decoder use this comparison. Locale and database collation do not. ### `compareAuthorityRevisionIdentity` [#compareauthorityrevisionidentity] ```ts api="@rolebook/sharing" function compareAuthorityRevisionIdentity(left: { readonly domain: string; readonly scope: string; }, right: { readonly domain: string; readonly scope: string; }): number; ``` UTF-16 order of `JSON.stringify([domain, scope])`, the order of a version-3 revision union. ### `decisionMetadataUtf8Bytes` [#decisionmetadatautf8bytes] ```ts api="@rolebook/sharing" function decisionMetadataUtf8Bytes(value: unknown): number; ``` Canonical UTF-8 size of decision metadata. The version-3 cap is this length, not a column's physical width. ### `HIERARCHY_BATCH_METADATA_MAX_BYTES` [#hierarchy_batch_metadata_max_bytes] ```ts api="@rolebook/sharing" const HIERARCHY_BATCH_METADATA_MAX_BYTES = 262144; ``` 256 KiB. 262,144 canonical UTF-8 bytes passes; 262,145 fails on both write and decode. ### `HierarchyBatchAuthorizationDecisionMetadata` [#hierarchybatchauthorizationdecisionmetadata] ```ts api="@rolebook/sharing" interface HierarchyBatchAuthorizationDecisionMetadata extends Omit { readonly schemaVersion: 3; readonly targets: readonly { readonly resource: { readonly type: string; readonly id: string; }; readonly hierarchy: HierarchyDecisionEvidence; }[]; } ``` Stored metadata version 3 for an enrolled batch of 2–32 targets. `schemaVersion` is a metadata version, not a journal-table schema. Each `hierarchy` block is evidence for its own target, not a capability. There is no top-level `hierarchy`. ### `captureHierarchyBatchDecisionMetadata` [#capturehierarchybatchdecisionmetadata] ```ts api="@rolebook/sharing" function captureHierarchyBatchDecisionMetadata(value: unknown): HierarchyBatchAuthorizationDecisionMetadata; ``` Captures metadata version 3. It checks nested version-2 evidence, canonical target and revision order, and the 256 KiB canonical UTF-8 cap. It does not read admission, policy, or the clock. A non-null `validUntil` is compared only with the stored `evaluatedAt`. ### `assertHierarchyBatchReceiptResult` [#asserthierarchybatchreceiptresult] ```ts api="@rolebook/sharing" function assertHierarchyBatchReceiptResult(result: unknown, metadata: HierarchyBatchAuthorizationDecisionMetadata): void; ``` Aligns a stored batch result with stored version-3 targets. It compares only those stored values. ### `assertSameProtectedAdmissionBundle` [#assertsameprotectedadmissionbundle] ```ts api="@rolebook/sharing" function assertSameProtectedAdmissionBundle(captured: HierarchyAdmissionRow, current: HierarchyAdmissionRow): void; ``` The final enrolled-batch admission fence. The batch-receipt floor, epoch, profile, and bootstrap authority must still equal the bundle captured before the first target effect. ### `OutboxDeliveryEvent` [#outboxdeliveryevent] ```ts api="@rolebook/sharing" interface OutboxDeliveryEvent { readonly environmentId: string; readonly eventId: string; readonly kind: string; readonly payload: unknown; } ``` Immutable sink envelope. Deduplicate external effects by environmentId/eventId; the trusted port supplies an immutable payload. ### `OutboxDeliveryToken` [#outboxdeliverytoken] ```ts api="@rolebook/sharing" interface OutboxDeliveryToken { readonly environmentId: string; readonly eventId: string; readonly generation: string; } ``` Exact environment/event/generation storage fence. It is not a sink deduplication key or authentication credential. ### `OutboxDeliveryClaim` [#outboxdeliveryclaim] ```ts api="@rolebook/sharing" interface OutboxDeliveryClaim { readonly eventId: string; readonly kind: string; readonly payload: unknown; readonly deliveryToken: OutboxDeliveryToken; } ``` Trusted committed event and current delivery token returned after the claim transaction releases its connection. ### `OutboxDeliveryPort` [#outboxdeliveryport] ```ts api="@rolebook/sharing" interface OutboxDeliveryPort { claim(input: { readonly limit: number; readonly leaseMs: number; }): Promise; acknowledge(token: OutboxDeliveryToken): Promise; retry(token: OutboxDeliveryToken, input: { readonly delayMs: number; }): Promise; quarantine(token: OutboxDeliveryToken, input: { readonly reason: string; }): Promise; } ``` Trusted storage interface used by the shared worker. Claim must release its transaction and return immutable payload snapshots; settlement methods must enforce exact current-token eligibility. First-party SQL outboxes implement this port. ### `OutboxDeliveryDecision` [#outboxdeliverydecision] ```ts api="@rolebook/sharing" type OutboxDeliveryDecision = { readonly status: "delivered"; } | { readonly status: "retry"; readonly delayMs: number; } | { readonly status: "quarantine"; readonly reason: string; } | { readonly status: "unresolved"; }; ``` Explicit caller policy. Only delivered permits ACK; retry delay is an integer0–300000ms; quarantine reason is nonblank, at most1024 characters, and contains no NUL. Exceptions, malformed decisions and unresolved outcomes cause no storage settlement. ### `OutboxDeliverySink` [#outboxdeliverysink] ```ts api="@rolebook/sharing" type OutboxDeliverySink = (event: OutboxDeliveryEvent, input: { readonly signal: AbortSignal; }) => Promise; ``` Caller-supplied sink invoked outside the claim transaction. The signal requests cooperative cancellation; external effects are not undone. Return a plain data decision and deduplicate by environment/event. ### `OutboxDeliveryOptions` [#outboxdeliveryoptions] ```ts api="@rolebook/sharing" interface OutboxDeliveryOptions { readonly batchSize: number; readonly leaseMs: number; readonly deliveryTimeoutMs: number; readonly deliver: OutboxDeliverySink; readonly diagnostics?: OutboxDeliveryDiagnosticsOptions | undefined; } ``` Required finite integer bounds: batchSize1–32, leaseMs1–300000, deliveryTimeoutMs1–leaseMs. Callback reference and options are captured at construction. `diagnostics` is optional; the PostgreSQL and SQLite facades forward it. ### `OutboxDeliveryOutcome` [#outboxdeliveryoutcome] ```ts api="@rolebook/sharing" type OutboxDeliveryOutcome = { readonly environmentId: string; readonly eventId: string; readonly generation: string; } & ({ readonly status: "acknowledged" | "retried" | "quarantined" | "stale"; } | { readonly status: "unresolved"; readonly reason: "sink-error" | "invalid-result" | "sink-unresolved" | "aborted" | "timeout" | "settlement-error"; }); ``` Frozen identity and status in claim order. Unresolved reasons describe uncertainty without raw exceptions or payloads. Stale means the original token was no longer eligible. An ambiguous ACK can already have committed. ### `OutboxDeliveryBatch` [#outboxdeliverybatch] ```ts api="@rolebook/sharing" interface OutboxDeliveryBatch { readonly stopped: boolean; readonly outcomes: readonly OutboxDeliveryOutcome[]; } ``` Frozen bounded per-pass report. stopped records cancellation/timeout; a previously submitted settlement may still have a known successful outcome. ### `OutboxDeliveryWorker` [#outboxdeliveryworker] ```ts api="@rolebook/sharing" interface OutboxDeliveryWorker { runOnce(input?: { readonly signal?: AbortSignal; }): Promise; } ``` One claim call per run, no refill/daemon/lease renewal. Overlapping runs reject before claiming, including while an abandoned sink is still pending. Sink calls are concurrent; settlements are serialized and check cancellation before submission. ### `createOutboxDeliveryWorker` [#createoutboxdeliveryworker] ```ts api="@rolebook/sharing" function createOutboxDeliveryWorker(options: OutboxDeliveryOptions & { readonly outbox: OutboxDeliveryPort; }): OutboxDeliveryWorkerWithDiagnostics; ``` Creates a bounded run-once worker over a trusted storage port. Claim errors throw a generic reconciliation error; no automatic retries or classifications are made. Database calls use executor time limits. Invalid `diagnostics` options throw a `TypeError` at construction. See [bounded delivery](/docs/sharing/outbox-delivery) for cancellation, late effects, queued settlement, diagnostics and source-compatible SQL facades. ### `OutboxDeliveryWorkerWithDiagnostics` [#outboxdeliveryworkerwithdiagnostics] ```ts api="@rolebook/sharing" interface OutboxDeliveryWorkerWithDiagnostics extends OutboxDeliveryWorker { diagnostics(): OutboxDeliveryDiagnostics; } ``` The value `createOutboxDeliveryWorker` and the PostgreSQL and SQLite delivery facades return; existing `OutboxDeliveryWorker` implementations are unaffected. `diagnostics()` is available with or without an observer and never changes run admission or settlement. `runOnce` resolves and rejects as without diagnostics: a failure rethrows the identical exception, and a floating rejected run is still an unhandled rejection. ### `OutboxDeliveryDiagnosticsOptions` [#outboxdeliverydiagnosticsoptions] ```ts api="@rolebook/sharing" interface OutboxDeliveryDiagnosticsOptions { readonly observe: OutboxDeliveryObserver; readonly queueLimit?: number; readonly observerTimeoutMs?: number; } ``` Optional observer configuration, validated and captured at construction. `queueLimit` is an integer 1–1024 and `observerTimeoutMs` an integer 1–60000; omitting either uses its default, while `null` or an unknown key throws. The defaults are configuration choices, not performance claims. ### `DEFAULT_OUTBOX_OBSERVER_QUEUE_LIMIT` [#default_outbox_observer_queue_limit] ```ts api="@rolebook/sharing" const DEFAULT_OUTBOX_OBSERVER_QUEUE_LIMIT: number; ``` 64 observations. ### `DEFAULT_OUTBOX_OBSERVER_TIMEOUT_MS` [#default_outbox_observer_timeout_ms] ```ts api="@rolebook/sharing" const DEFAULT_OUTBOX_OBSERVER_TIMEOUT_MS: number; ``` 1,000 ms. ### `OutboxDeliveryObserver` [#outboxdeliveryobserver] ```ts api="@rolebook/sharing" type OutboxDeliveryObserver = (observation: OutboxDeliveryObservation) => void | PromiseLike; ``` Called asynchronously after a run settles, at most one call at a time, as a plain function (`this` is undefined; bind a class method yourself) with the observation as its only argument. Throws, rejections and timeouts are counted, never propagated. A call counts as timed out once when the timer fires first or when its measured duration exceeded `observerTimeoutMs` at settlement, which is how synchronous overruns are counted. The timeout only reports: nothing cancels the call, and it keeps the single slot until it settles. Return or yield promptly; same-process code cannot preempt synchronous CPU work. ### `OutboxDeliveryObservation` [#outboxdeliveryobservation] ```ts api="@rolebook/sharing" interface OutboxDeliveryObservation { readonly type: "run"; readonly sequence: number; readonly result: OutboxDeliveryRunResult; readonly claimed: number; readonly acknowledged: number; readonly retried: number; readonly quarantined: number; readonly stale: number; readonly unresolved: number; readonly unresolvedReasons: Readonly>; } ``` Frozen per-run counts. No environment, event, tenant or subject identifier, generation, kind, payload, exception text or quarantine reason. `sequence` is a local per-worker ordinal; a gap means observations were dropped. `claimed` counts claims this pass processed; 0 after `claim-failed` does not prove that no lease was taken. ### `OutboxDeliveryRunResult` [#outboxdeliveryrunresult] ```ts api="@rolebook/sharing" type OutboxDeliveryRunResult = "completed" | "stopped" | "busy" | "invalid-input" | "claim-failed" | "claim-overflow"; ``` How one `runOnce` call ended on this worker. `claim-failed`: the claim call failed or returned a malformed batch, so leases may have committed. `claim-overflow`: the claim returned more than `batchSize` rows. `invalid-input`: the caller's input or signal was rejected before the claim. ### `OutboxDeliveryUnresolvedReason` [#outboxdeliveryunresolvedreason] ```ts api="@rolebook/sharing" type OutboxDeliveryUnresolvedReason = Extract["reason"]; ``` The six unresolved reasons of `OutboxDeliveryOutcome`. ### `OutboxDeliveryDiagnostics` [#outboxdeliverydiagnostics] ```ts api="@rolebook/sharing" interface OutboxDeliveryDiagnostics { readonly scope: "worker-local"; readonly worker: "idle" | "running" | "draining"; readonly detachedSinks: number; readonly delivery: "no-runs" | "clear" | "attention"; readonly lastRun: OutboxDeliveryObservation | null; readonly totals: { readonly runs: Readonly>; readonly claimed: number; readonly acknowledged: number; readonly retried: number; readonly quarantined: number; readonly stale: number; readonly unresolved: Readonly>; }; readonly observation: { readonly status: "disabled" | "healthy" | "degraded" | "stalled"; readonly queueLimit: number; readonly queued: number; readonly outstanding: 0 | 1; readonly completed: number; readonly failed: number; readonly timedOut: number; readonly dropped: number; }; } ``` Frozen snapshot of this worker instance only: not backlog size, database, sink or global production health. `delivery` reflects the last local run; `observation` reports observer trouble separately. Totals saturate at `Number.MAX_SAFE_INTEGER`. `observation.dropped`, `failed` and `timedOut` are lifetime totals for the worker and never reset, while `observation.status` returns to `healthy` after the next prompt, successful call. See [worker diagnostics](/docs/sharing/outbox-delivery#worker-diagnostics). ## Governed sharing [#governed-sharing] Governed sharing turns a sensitive membership or ownership command into a closed request lifecycle. Use `request` to record a command, `approve`, `reject`, or `cancel` to move the request, `apply` only after approval, and `resolve` to read its current outcome. A direct governed mutation returns `GOVERNANCE_REQUIRED`; it cannot bypass the approval and effect path. For a non-owner transfer, the request needs a counted direct-owner sponsor. For an owner transfer, the request writes a payload-bound, non-counting consent and needs an independent eligible quorum; the recipient does not accept the transfer separately. ### `createGovernanceRequestId` [#creategovernancerequestid] ```ts api="@rolebook/sharing" function createGovernanceRequestId(context: TenantContext): string; ``` Generate an opaque request ID from the requester’s authenticated tenant context before submitting a governed command. Keep the ID for retries and follow-up calls. ### `GOVERNANCE_PUBLIC_STATUSES` [#governance_public_statuses] ```ts api="@rolebook/sharing" const GOVERNANCE_PUBLIC_STATUSES: readonly [ "PENDING", "APPROVED", "REJECTED", "APPLIED", "VOID", "REFUSED", "UNAVAILABLE", "UNKNOWN_REQUEST" ]; ``` ### `GovernancePublicStatus` [#governancepublicstatus] ```ts api="@rolebook/sharing" type GovernancePublicStatus = GovernanceFoundationPublicStatus; ``` ### `GovernancePublicResult` [#governancepublicresult] ```ts api="@rolebook/sharing" interface GovernancePublicResult { readonly status: GovernancePublicStatus; } ``` ### `GovernanceSubject` [#governancesubject] ```ts api="@rolebook/sharing" interface GovernanceSubject { readonly type: string; readonly id: string; } ``` ### `GovernanceResource` [#governanceresource] ```ts api="@rolebook/sharing" interface GovernanceResource extends GovernanceSubject { readonly incarnation: string; } ``` ### `GovernanceMembershipPrior` [#governancemembershipprior] ```ts api="@rolebook/sharing" interface GovernanceMembershipPrior { readonly kind: "membership"; readonly membershipId: string; readonly role: string; readonly expiresAt: number | null; } ``` ### `GovernanceCommand` [#governancecommand] ```ts api="@rolebook/sharing" type GovernanceCommand = { readonly requestId: string; readonly resource: GovernanceResource; readonly target: GovernanceSubject; } & ({ readonly kind: "grantRole"; readonly role: string; readonly expiresAt: number | null; readonly prior: { readonly kind: "absent"; }; } | { readonly kind: "changeRole"; readonly role: string; readonly expiresAt: number | null; readonly prior: GovernanceMembershipPrior; } | { readonly kind: "revokeMember"; readonly prior: GovernanceMembershipPrior; } | { readonly kind: "transferOwnership"; readonly formerOwner: { readonly mode: "none"; } | { readonly mode: "role"; readonly role: string; }; readonly prior: { readonly kind: "ownership"; readonly owner: GovernanceSubject; readonly ownershipRevision: string; }; }); ``` ### `GovernedSharing` [#governedsharing] ```ts api="@rolebook/sharing" interface GovernedSharing { request(command: GovernanceCommand): Promise; approve(requestId: string): Promise; reject(requestId: string): Promise; cancel(requestId: string): Promise; apply(requestId: string): Promise; resolve(requestId: string): Promise; } ``` ### `GovernanceAttachment` [#governanceattachment] ```ts api="@rolebook/sharing" interface GovernanceAttachment { readonly binding: GovernanceBinding; readonly gate: GovernanceDirectGate; readonly requestTtlMs: number; run(context: TenantContext, work: (session: GovernanceSession) => Promise>): Promise; } ``` ### `GovernanceBinding` [#governancebinding] ```ts api="@rolebook/sharing" interface GovernanceBinding { readonly executor: object; readonly policyFence?: object; readonly identity: object; } ``` ### `GovernanceRuleSnapshot` [#governancerulesnapshot] ```ts api="@rolebook/sharing" interface GovernanceRuleSnapshot { readonly policyRevision: string; readonly tenantRoleRevision: string; readonly governanceRuleId: string; readonly governanceRuleRevision: string; readonly threshold: number; } ``` ## Access-change delivery [#access-change-delivery] Shared types for draining committed access changes into a delivery queue that `createOutboxDeliveryWorker` runs. See [access-change webhooks](/docs/sharing/webhooks). ### `ACCESS_CHANGE_ACTIONS` [#access_change_actions] ```ts api="@rolebook/sharing" const ACCESS_CHANGE_ACTIONS: readonly [ "member.granted", "member.role_changed", "member.revoked", "ownership.transferred", "invitation.issued", "invitation.consumed" ]; ``` The six audit actions delivered as access changes, in this order. Every other audit action (`invitation.revoked`, `resource.initialized`, `resource.deleted`, `resource.moved`) is never queued. ### `ACCESS_CHANGE_LIMITS` [#access_change_limits] ```ts api="@rolebook/sharing" const ACCESS_CHANGE_LIMITS: Readonly<{ maxDrainLimit: 1000; maxClaimLimit: 1000; maxLeaseMs: 300000; maxDelayMs: 300000; maxReasonLength: 1024; maxInspectLimit: 1000; maxPruneLimit: 1000; maxRetainMs: 31536000000; }>; ``` Bounds the storage adapters' delivery stores enforce: drain, claim, prune and inspection limits of 1–1000, leases and retry delays of at most 300000 ms, a delivered-entry retention of at most a year, and dead-letter reasons of at most 1024 characters. ### `accessChangeAction` [#accesschangeaction] ```ts api="@rolebook/sharing" function accessChangeAction(value: unknown): AccessChangeAction | undefined; ``` Returns the action when it is one of `ACCESS_CHANGE_ACTIONS`, otherwise `undefined`. ### `accessChangeDeliveryId` [#accesschangedeliveryid] ```ts api="@rolebook/sharing" function accessChangeDeliveryId(input: { readonly resourceType: string; readonly tenantId: string; readonly resourceId: string; readonly auditEventId: string; }): Promise; ``` The delivery ID of one access change: `evt_` and 32 lowercase hex characters of SHA-256 over the resource type, tenant, resource ID and audit event ID. The same audit event always gets the same ID, across retries, requeues and drains; the same audit event ID on another resource, tenant or type gets a different one. ### `captureAccessChangeEvent` [#captureaccesschangeevent] ```ts api="@rolebook/sharing" function captureAccessChangeEvent(value: unknown): AccessChangeEvent | undefined; ``` Validates an access change and copies exactly the allow-listed fields into a new frozen object. Unknown fields are dropped; a missing or malformed required field returns `undefined`. ### `validDeadLetterReason` [#validdeadletterreason] ```ts api="@rolebook/sharing" function validDeadLetterReason(value: unknown): value is string; ``` True for a non-blank string of at most 1024 characters without NUL. ### `validSubscriptionId` [#validsubscriptionid] ```ts api="@rolebook/sharing" function validSubscriptionId(value: unknown): value is string; ``` True for 1–64 characters of `A-Z a-z 0-9 . _ -`, starting with a letter or digit. ### `AccessChangeAction` [#accesschangeaction-1] ```ts api="@rolebook/sharing" type AccessChangeAction = (typeof ACCESS_CHANGE_ACTIONS)[number]; ``` One of `ACCESS_CHANGE_ACTIONS`. ### `AccessChangeClaim` [#accesschangeclaim] ```ts api="@rolebook/sharing" interface AccessChangeClaim extends OutboxDeliveryClaim { readonly kind: AccessChangeAction; readonly payload: AccessChangeEvent; readonly attempt: number; } ``` A leased queue entry. `eventId` is the delivery ID, `payload` the allow-listed event, and `attempt` counts claims of this entry, this one included. ### `AccessChangeDeadLetter` [#accesschangedeadletter] ```ts api="@rolebook/sharing" interface AccessChangeDeadLetter { readonly eventId: string; readonly kind?: AccessChangeAction; readonly resourceType: string; readonly resourceId: string; readonly attempts: number; readonly reason: string; readonly deadAt: string; readonly token: AccessChangeDeadLetterToken; } ``` One dead-lettered entry of the subscription's tenant, with the exact token (subscription, tenant, generation) `requeue` and `discardDeadLetter` need. It carries the attempt count and reason, never the payload; `kind` is absent when the stored entry did not decode. ### `AccessChangeDeadLetterToken` [#accesschangedeadlettertoken] ```ts api="@rolebook/sharing" interface AccessChangeDeadLetterToken extends OutboxDeliveryToken { readonly subscriptionId: string; readonly tenantId: string; } ``` A dead-lettered entry's subscription and exact current generation. ### `AccessChangeDeliveryPort` [#accesschangedeliveryport] ```ts api="@rolebook/sharing" interface AccessChangeDeliveryPort extends OutboxDeliveryPort { takeDeadLettered?(): readonly string[]; claim(input: { readonly limit: number; readonly leaseMs: number; }): Promise; } ``` One subscription's queue as an `OutboxDeliveryPort`, bound to its tenant, so `createOutboxDeliveryWorker` can run it. `claim` returns at most one entry per resource of that tenant: the oldest undelivered one, and only when it is not leased, not waiting for its retry time and not dead-lettered. Settlement needs a token this port issued, its current generation, and a lease that has not expired. ### `AccessChangeDeliveryStore` [#accesschangedeliverystore] ```ts api="@rolebook/sharing" interface AccessChangeDeliveryStore { readonly environmentId: string; readonly resourceTypes: readonly string[]; drain(input: { readonly subscriptionId: string; readonly tenantId: string; readonly limit: number; }): Promise; outbox(input: { readonly subscriptionId: string; readonly tenantId: string; }): AccessChangeDeliveryPort; pruneDelivered(input: { readonly subscriptionId: string; readonly tenantId: string; readonly retainMs: number; readonly limit: number; }): Promise; inspectDeadLetters(input: { readonly subscriptionId: string; readonly tenantId: string; readonly limit: number; }): Promise; requeue(token: AccessChangeDeadLetterToken): Promise; discardDeadLetter(token: AccessChangeDeadLetterToken): Promise; } ``` Delivery state kept apart from the audit tables: a tenant binding per subscription, a cursor per subscription and resource type, and a queue. `drain` reads at most `limit` audit rows of one tenant per resource type past the cursor, queues the access changes among them and advances the cursor past all of them in one transaction; a drain never updates or deletes an audit row. A subscription is bound to the tenant of its first drain, for every resource type; `drain` for another tenant throws, and `outbox` and `pruneDelivered` see only the bound tenant's entries. `pruneDelivered` deletes delivered entries older than `retainMs`; `discardDeadLetter` deletes one dead-lettered entry so its resource moves on. There is no order across resources. See [access-change webhooks](/docs/sharing/webhooks). ### `AccessChangeDeliveryErrorCode` [#accesschangedeliveryerrorcode] ```ts api="@rolebook/sharing" type AccessChangeDeliveryErrorCode = "invalid-row" | "tenant-bound" | "tenant-spelling" | "foreign-cluster" | "missing-origin" | "missing-privilege" | "source-conflict"; ``` Why a delivery store refused to continue, carried as `code` on the adapters' `AccessChangeDeliveryError`: a row that does not decode, a subscription bound to another tenant, a tenant ID that is not spelled as stored, PostgreSQL positions from another cluster, no recorded origin for a PostgreSQL audit table, a privilege the drain role, or the executor running `adoptCluster` or `rebaseline`, lacks (the message names the grant), or a resource type that another audit table already delivers under the same delivery prefix. ### `INVALID_ENTRY_REASON` [#invalid_entry_reason] ```ts api="@rolebook/sharing" const INVALID_ENTRY_REASON = "dead-lettered: the stored entry does not decode"; ``` The reason a store records when it dead-letters a claimed entry that does not decode or names another tenant. The rest of the batch is still handed out. ### `AccessChangeDrainResult` [#accesschangedrainresult] ```ts api="@rolebook/sharing" interface AccessChangeDrainResult { readonly enqueued: number; readonly caughtUp: boolean; } ``` How many entries one `drain` queued, and whether every resource type's scan returned fewer rows than the limit and no page was discarded because another drain moved the cursor first, or a concurrent rebaseline or halt intervened. ### `AccessChangeEvent` [#accesschangeevent] ```ts api="@rolebook/sharing" interface AccessChangeEvent { readonly id: string; readonly tenantId: string; readonly resourceType: string; readonly resourceId: string; readonly actor: AccessChangeRef; readonly action: AccessChangeAction; readonly subject?: AccessChangeRef; readonly invitationId?: string; readonly fromTenantId?: string; readonly toTenantId?: string; readonly occurredAt: string; } ``` One committed access change, restricted to the fields of the Sharing HTTP API's audit event. The audit row's idempotency key, incarnation and lineage are never copied, and invitation tokens are never stored in the audit table. ### `AccessChangeRef` [#accesschangeref] ```ts api="@rolebook/sharing" interface AccessChangeRef { readonly type: string; readonly id: string; } ``` An actor or subject as the audit row recorded it. # Named authorized queries (/docs/sharing/authorized-queries) > Registered, filtered and sorted queries over your own resource table that return only the keys the actor is allowed, checked in one database snapshot. `listAccessible()` pages through the resources sharing state can reach. A **named authorized query** instead filters and sorts your own resource table by columns you register, and returns only the resource keys the bound actor is allowed the query's action on. Every candidate is checked by the canonical Sharing and Rolebook decision inside the page's own database transaction: a row whose filter matched but whose check did not allow it is never returned. A page returns `{ type, id }` keys only, never application columns. Load what you show through your own tenant-scoped data path. | Database | Factory | Executor it requires | | --- | --- | --- | | PostgreSQL | `createPostgresAuthorizedQueries` from `@rolebook/sharing-postgres` | `createPgExecutor(pool)` | | SQLite, Bun only | `createSqliteAuthorizedQueries` from `@rolebook/sharing-sqlite` | `createBunSqliteQueryExecutor()` from `@rolebook/sharing-sqlite/bun-query` | Both factories take the adapter built with `fencePolicy`, the [`createVersionedSharing()`](/docs/sharing/versioned) instance whose policy store uses the adapter's executor, and a resolver with `resolveQueryPrincipalInTransaction`, such as the local identity projection's `identity`. The factories and their types come from the driver packages; `@rolebook/sharing` does not export them. The signatures are on the [PostgreSQL](/docs/sharing-postgres/api#named-authorized-queries) and [SQLite](/docs/sharing-sqlite/api#named-authorized-queries) API pages. This first delivery does not provide HTTP exposure, effective-subject or all-action queries, graph inheritance, ORM translation, application-column projection, multi-page frozen snapshots, remote identity or libSQL query profiles, or native UUID source keys. ## Register queries [#register-queries] Queries are trusted server code, registered once at construction: ```ts group=authorized-queries import type { SharingResourceConfigurations, VersionedResourceSharing } from "@rolebook/sharing"; import { createPostgresAuthorizedQueries, createPostgresLocalIdentityProjection, type PostgresSharingAdapter, type QueryDefinition, } from "@rolebook/sharing-postgres"; // Built with fencePolicy on a createPgExecutor executor. declare const adapter: PostgresSharingAdapter; // Its policy store uses the same executor. declare const sharing: VersionedResourceSharing; // A generated key from your secret store, the same on every instance. declare const queryCursorKey: string; const recentDocuments: QueryDefinition = { name: "recentDocuments", version: "v1", resourceType: "document", action: "read", schemaVersion: "s1", table: "document", // must equal the adapter's descriptor, unqualified tenantColumn: "tenant_id", idColumn: "id", filters: { status: { column: "status", type: "string", operators: ["eq", "in"], disclosable: true }, archived: { column: "archived", type: "boolean", operators: ["eq", "isNull"], disclosable: true }, }, sort: { column: "rank", type: "integer", direction: "desc", nulls: "last", disclosable: true }, }; const queries = createPostgresAuthorizedQueries({ adapter, sharing, identity: createPostgresLocalIdentityProjection({ table: "identity_projection" }).identity, queries: [recentDocuments], listingCursorKey: [queryCursorKey], // explicit: there is no random default environmentId: "orders-g1", // one logical dataset and cursor generation, see Cursors }); ``` A [`QueryDefinition`](/docs/sharing-postgres/api#querydefinition) names one resource type, one action and one table. Construction performs no database I/O and throws `QueryConfigurationError` (`QUERY_CONFIGURATION_INVALID`, a fixed message, no cause) for anything invalid or missing: - 1 to 64 queries with unique names, at most 16 filter names each, 64 KiB per definition and 1 MiB for the registry. Names, versions, schema versions, filter names and `environmentId` match `[A-Za-z][A-Za-z0-9_-]{0,63}`; `resourceType` and `action` must be configured in the sharing definition. - SQL identifiers are unqualified `[A-Za-z_][A-Za-z0-9_]{0,62}`, always quoted, never expressions, schema-qualified names or raw SQL. `table`, `tenantColumn` and `idColumn` must equal the adapter's resource descriptor for that type. - Each filter's `operators` is non-empty and unique. Range operators (`gt`, `gte`, `lt`, `lte`) are invalid for `boolean`. One column has one type across the filters, the sort and the key columns. - Every filter and the sort carry `disclosable: true`; a missing or `false` value is refused. - The adapter, the versioned sharing instance, its policy store and the executor must be the original first-party objects, with the adapter's policy fence enforced for that same policy store, and the resolver must have `resolveQueryPrincipalInTransaction`. `listingCursorKey` takes keys in the [secret key](/docs/sharing/setup#secret-keys) form, one or up to eight. The definitions are captured at construction; changing the objects afterwards changes nothing. ### `disclosable` is an attestation [#disclosable-is-an-attestation] `disclosable: true` is not a protection. Every subject who may run the query and receive this action's resources may learn the filtered and sorted column values by inference, through which items a filter returns and in what order, including columns the subject could not otherwise read. Register a separate query (or action) where those audiences differ. Rolebook does not infer field permissions. ## The source table and its indexes [#the-source-table-and-its-indexes] The source table is your own table, in the same database as the sharing, identity and policy tables. Your migrations must guarantee its contract, because a page proves only what it reads: - Non-null tenant and ID columns with `unique (tenant, id)`, and exactly one row per initialized resource of the type. A row without managed sharing state makes the page `QUERY_UNAVAILABLE`. - Every registered column stored as its declared type. Each fetched value is checked and nothing is coerced: a value outside the storage profile makes the page `QUERY_UNAVAILABLE`. Rows a filter excludes are never read, so they are never validated, and `CHECK` expressions are not proven. - IDs and strings follow the strict profile: at most 128 (IDs) or 512 (strings) UTF-16 units, valid Unicode, no C0 control character and no DEL. | Registered type | PostgreSQL column | SQLite value | | --- | --- | --- | | `integer` | `smallint`, `integer` or `bigint`; a value outside the JavaScript safe-integer range is unavailable, never rounded | an INTEGER in the safe-integer range | | `string` | `text` or `varchar` (not `char(n)`), compared under `COLLATE "C"` in a UTF8 database | TEXT, compared under `COLLATE BINARY` in a UTF-8 database | | `boolean` | `boolean` | an INTEGER that is exactly `0` or `1` | | tenant and ID | non-null `text` or `varchar`; native `uuid` is not supported | `TEXT NOT NULL` | A page scans in one total order: a null rank (nulls first or last as declared), then the sort value in the declared direction, then the resource ID ascending in binary order whatever the direction. Strings compare in binary UTF-8 order, never a locale collation, and `false` sorts before `true`. Pagination is keyset over that exact tuple, never an offset. Indexes are a deployment prerequisite for performance, never for correctness: a missing index changes neither the results nor the errors. Each query needs one index matching its tenant, sort and ID order with binary text collation. For `recentDocuments` above (`rank`, `desc`, nulls last) on PostgreSQL: ```sql CREATE INDEX document_by_rank ON document (tenant_id COLLATE "C", rank DESC NULLS LAST, id COLLATE "C"); ``` SQLite orders by an explicit null rank, `(column IS NULL)` for nulls last and `(column IS NOT NULL)` for nulls first, both ascending. For `nulls: "last"` with `direction: "asc"`: ```sql CREATE INDEX document_by_rank ON document (tenant_id, (rank IS NULL), rank, id); ``` For `direction: "desc"` declare the value column `DESC` (the null rank and the ID stay ascending); for nulls first use `(rank IS NOT NULL)`. On PostgreSQL add `COLLATE "C"` to a `string` sort column; on SQLite add `COLLATE BINARY` to one declared with another collation. Index the registered filters your workload needs, and confirm with `EXPLAIN` (PostgreSQL) or `EXPLAIN QUERY PLAN` (SQLite, with no `USE TEMP B-TREE FOR ORDER BY`) that the page statement uses the index. ## Run a page [#run-a-page] Bind a tenant facade from your trusted server path, then page with `nextCursor` until `exhausted`: ```ts group=authorized-queries import type { ResourceKey } from "@rolebook/sharing"; // Your authenticated session: the tenant, the actor and a session or authority incarnation. declare const session: { readonly tenantId: string; readonly userId: string; readonly authorityId: string; }; const tenant = queries.forTenant({ tenantId: session.tenantId, actor: { type: "user", id: session.userId }, context: {}, sessionBinding: session.authorityId, }); const keys: ResourceKey[] = []; let cursor: string | undefined; for (;;) { const result = await tenant.query({ name: "recentDocuments", filters: [ { field: "status", op: "in", value: ["open", "review"] }, { field: "archived", op: "eq", value: false }, ], limit: 50, ...(cursor === undefined ? {} : { cursor }), }); if (!result.ok) throw new Error(result.code); // see Errors below keys.push(...result.page.items); if (result.page.exhausted || result.page.nextCursor === undefined) break; cursor = result.page.nextCursor; } ``` `forTenant()` captures the binding synchronously and throws `QueryConfigurationError` when it is invalid. `tenantId` and `actor` come from your authenticated request path. `context` is trusted plain JSON within Core's context bounds (default `{}`), and may not set `tenantId` or `sharingRevision`. `sessionBinding` (1 to 128 UTF-16 units, no C0 control character or DEL) is your session or authority incarnation: it is bound into every cursor and never returned. A request is `{ name, filters?, limit?, cursor? }` with exactly those keys: - At most 16 KiB of UTF-8, depth 8 and 512 nodes. `filters` is a conjunction of at most 16 predicates, `[]` (match every tenant row) when omitted. A contradictory conjunction returns an empty exhausted page, not an error. - Each predicate is `{ field, op, value }` over a registered filter and one of its operators. `eq` takes one non-null value, `in` 1 to 32 distinct values of one type, ranges an integer or a string, and `isNull` a boolean (`false` selects non-null values). Null never matches `eq`, `in` or a range. The same field may have several predicates; an exact duplicate is refused. - Strings are at most 512 UTF-16 units with no C0 control character, DEL or unpaired surrogate, integers are safe integers, and nothing is converted between types. - `limit` is an integer from 1 to 100 (default 25). It is not bound to the cursor and may change between pages. Predicates are put in a canonical order, so reordering a conjunction or an `in` set produces the same cursor binding. No other equivalence is recognized. ## Results [#results] A result is either `{ ok: true, page }` or `{ ok: false, code }` (see [`QueryResult`](/docs/sharing-postgres/api#queryresult)). A page has `items`, `nextCursor` (when not exhausted), `exhausted`, `completion`, `evaluatedAt`, `queryVersion`, `schemaVersion`, `consistency: "local-snapshot"` and `traversal: "live"`. - `items` are the allowed keys in scan order, at most `limit` of them. - `exhausted: true` means the source proved it has nothing after the last candidate the page processed. Such a page has `completion: "complete"` and no `nextCursor`. - `exhausted: false` always comes with a `nextCursor`, even on an empty page: the scan stopped at the result limit or the candidate budget before it could prove the end. Continue with it; only an exhausted page ends the traversal. - `completion: "budget_limited"` means the 2,000-candidate budget stopped the page before it reached `limit` results or the end. `completion: "complete"` means it stopped on the result limit or the end. - `nextCursor` resumes after the last candidate the page processed, allowed or not, never after the last row it fetched, so no candidate is skipped. - `evaluatedAt` is the page's database time in epoch milliseconds. `queryVersion` and `schemaVersion` echo the registration. There are no totals, counts, denied IDs, matched rules, facts or raw filter and sort values in a result, and an error never echoes a value. ## Errors [#errors] `query()` never throws for an operational failure. Every failure is one of four fixed codes, with no detail and no partial page: | `code` | When | | --- | --- | | `INVALID_REQUEST` | The request is not a plain object of exactly the request keys, exceeds a bound, names an unknown query, filter or operator, has a value of the wrong type, a duplicate predicate or an invalid `limit`, or has a `cursor` that is not a string. | | `INVALID_CURSOR` | The cursor does not open: malformed, truncated or tampered, sealed for another environment, tenant or actor, under a key no longer configured, or in another format such as a listing cursor. Also an authenticated payload that is not a valid named-query cursor, or whose position does not fit the selected query's sort type. | | `CURSOR_STALE_RESTART` | The cursor is genuine but no longer applies: another query name, a changed query definition or version, another filter set, context or session binding, a changed effective policy (including a tenant custom role), or a lease that has expired or was issued later than this page's database time. Start again without a cursor. | | `QUERY_UNAVAILABLE` | The page could not be answered completely: the deadline passed, the factory is closing or already has 32 pages in flight, a connection or lease was not available, a serialization failure, schema drift or a value outside the storage profile, a source row without managed sharing state, an ineligible or expired actor, a check Core cannot make for the actor, or any other fault. A candidate the check denies is skipped, never a failure. | The request is validated first, then the cursor: its syntax, authentication and payload, then its fit with the query, filters, context and session binding. All of that happens before anything reaches the database, so a bad cursor is never sent to it. The cursor's policy and lease checks run inside the page transaction, after the policy is selected and before the actor is resolved. When several problems coexist, the first check that fails decides the code. ## Cursors [#cursors] A `nextCursor` is sealed with the same AES-256-GCM cursor engine as listing cursors, under its own format, `rolebook/named-query/v1`, with a key derived for that format alone. Treat it as opaque. - Every cursor is 10,980 characters whatever its position, so its length reveals nothing about denied candidates. - It is bound to the environment, tenant and actor (a mismatch is `INVALID_CURSOR`), and to the query, the normalized filters, the context, the session binding and the effective policy (a mismatch is `CURSOR_STALE_RESTART`). A policy change that only relabels the version does not stale it. A grant, a revocation or an expiry does not restart a traversal either: identity is resolved anew on every page. - Each cursor is a 15-minute lease from its page's database time. The next page compares it with its own database time, and a cursor issued later than that is stale too, so the database clocks that serve one traversal must agree. Every returned cursor gets a fresh lease; an old one is never extended. - `listingCursorKey` is a list: the first key seals, every key opens. To rotate, add the new key to every instance before any instance seals with it, then put it first, and keep the old key in the list for at least 15 minutes plus your clock skew. A cursor sealed under a removed key is `INVALID_CURSOR`. - After a session security change, change `sessionBinding` to invalidate the session's cursors. The current identity is checked on every page regardless. ### The continuation domain: `environmentId` [#the-continuation-domain-environmentid] `environmentId` is part of every cursor's authenticated data, together with the tenant and the actor. It names one logical dataset and one generation of continuation, not merely a deployment stage: factories that share the value and a key open each other's cursors, whichever first-party driver serves them. - Keep the same `environmentId` and keys across a driver switch, for example SQLite to PostgreSQL, only when existing cursors are meant to continue. Change it after a restore, a reseed or a cutover that should invalidate them. Removing a key from `listingCursorKey` also invalidates every cursor sealed under it. - The codes do not change. Another environment, a key that is no longer listed, another tenant or another actor is `INVALID_CURSOR`, decided before any database work. An authenticated cursor whose query, filters, context, session binding or profile no longer match is `CURSOR_STALE_RESTART`, also before any database work; one whose effective policy no longer matches, whose lease has expired, or that was issued later than the page's database time is `CURSOR_STALE_RESTART` from inside the page transaction, so the databases that serve one traversal need clocks that agree. - `environmentId` is not checked against anything in the database. It is the operator's statement that two deployments hold the same logical dataset: two unrelated databases configured with the same value and keys accept each other's cursors. Every page is authorized again, so the consequence is a wrong starting position, never a grant. - Matching digests establish compatible definitions, not identical data. Both drivers use the same `sql-binary-v1` order, so a page resumed on the other driver starts after the cursor's position; this is the same live traversal over independent snapshots, with no replication consistency and no frozen result set. **Provisioning and rotation.** Choose one `environmentId` per logical dataset and generation, and give it and the same `listingCursorKey` list to every instance that should continue the others' cursors. To rotate a key, add the new key to every instance, then list it first, and keep the old key listed for at least the 15-minute cursor lease plus your clock-skew allowance. ## What a page guarantees [#what-a-page-guarantees] - **Local snapshot** (`consistency: "local-snapshot"`). Everything a page reads from the database, policy, identity, candidates, memberships, ownership and resources, and every check share one transaction snapshot and one database `evaluatedAt`, which governs every expiry. The trusted `context` and `sessionBinding` you pass are application facts, not database state: context used for authority must come from your own trusted request path, and copying it into a request gives it no freshness. There is no claim about remote identity providers. - **Live traversal** (`traversal: "live"`). Pages are independent snapshots. Inserts, deletes and changed sort values between pages can repeat or omit items across a traversal; no multi-page snapshot is promised. Every returned item was allowed at its own page's snapshot, not later. - **Whole pages only.** A page that cannot be checked completely fails as a whole and never returns a partial result. A candidate is returned only when the canonical check allows it. It is skipped when the check denies it (an explicit deny or no grant) or when no binding can be built from its stored state, such as a membership whose role is no longer mapped (a retired custom role): that is the canonical denial, exactly as `authorize()` denies the resource and `listAccessible()` skips it. A check Core cannot make for the actor (an assignment with an unknown or mis-scoped role), an answer outside Core's valid decisions, a malformed or out-of-order candidate, or a missing resource makes the page `QUERY_UNAVAILABLE`, never an empty or shortened page. An ineligible actor is `QUERY_UNAVAILABLE` too, not an empty page. ## Bounds [#bounds] - **Deadline.** A page ends within 2,000 ms of a monotonic clock that starts before request validation, so validation, hashing, connection acquisition, the transaction, every read and check and cursor sealing all count. When it passes, the page answers `QUERY_UNAVAILABLE` at once and no result is produced afterwards. No deadline here is a hard real-time guarantee. - **Candidate budget.** A page checks at most 2,000 candidates, fetched in batches of at most 200, and stops at once at the result limit or the budget. - **Pages in flight.** At most 32 pages per factory, including pages whose caller already received `QUERY_UNAVAILABLE` but whose connection has not settled yet. A page beyond that is `QUERY_UNAVAILABLE`; nothing waits in a queue. - **No retries.** A timeout, a serialization failure or a busy connection is never retried. - **`close()`** rejects new requests, ends the pages in flight and waits up to 1,000 ms for them to settle, else rejects with `QueryCloseError` (`QUERY_CLOSE_FAILED`); a later call waits on the same cleanup again. ## PostgreSQL [#postgresql] - The adapter and the policy store use one original `createPgExecutor(pool)` executor. A page is one `SERIALIZABLE READ ONLY` transaction on one pool connection; pool acquisition counts against the deadline, and a connection that arrives late is discarded without `BEGIN`. - Before each statement the page sets `statement_timeout` and `lock_timeout` to the milliseconds left. A statement that ignores cancellation keeps its page slot and connection until it settles; the connection is then rolled back and discarded, never returned to the pool clean. - A page runs no DML or DDL. `close()` never closes your pool. - Tenant and ID columns must be `text` or `varchar`. Native `uuid` source keys are not supported by this first profile: an adapter with `resourceSqlType: "uuid"` is refused at construction, and a column found to be another type at page time makes the page `QUERY_UNAVAILABLE`. - The database must be UTF8, and the source must be an ordinary or partitioned table. ## SQLite [#sqlite] - Bun only. The adapter must be built on an executor from `createBunSqliteQueryExecutor()` (checked by provenance, not by shape), and the **same executor object** must build the adapter, the policy store and the query factory. `createBunSqliteExecutor()`, `createLibsqlExecutor()` and every other executor are refused for this API, because a synchronous SQLite call cannot be interrupted by a deadline; their other uses are unchanged. - The database file must already be UTF-8 and in WAL mode; the worker executor checks both and never converts a file. - A page is one query lease of the executor: a read-only `BEGIN DEFERRED` transaction on one worker connection, whose file snapshot is opened by `SELECT 1 FROM main.sqlite_schema LIMIT 1` before the page reads anything, then the database clock is read. It never commits. The table is always read from `main`. - A page never waits for a connection: when every connection of the executor is leased or busy, the page is `QUERY_UNAVAILABLE`. With less than 1 ms of the deadline left it does not ask for a lease. - A running SQLite statement cannot be interrupted. When the deadline passes the page answers at once and the executor terminates the worker that owns its connection, but that connection slot stays occupied until the statement returns and the worker's exit is confirmed; a replacement starts only then, when work needs one. - `queries.close()` drains this factory's pages and never closes the executor; `executor.close()` at shutdown owns the workers. - The same executor can also serve the [SQLite protected-write adapter](/docs/sharing-sqlite/protected-updates#on-the-worker-executor). A protected write is ordinary work: it waits for a free connection in arrival order and holds its worker from `BEGIN IMMEDIATE` to the end of its `COMMIT`, while a page never waits. Long protected writes can therefore make pages `QUERY_UNAVAILABLE`: size `maxConnections` for the writes and other work you expect at once plus the pages that must still be answered, and keep protected callbacks short. A page whose lease opened before a protected write committed on another worker keeps its snapshot and does not see that write; a page that starts after the commit does. ```ts import type { SharingResourceConfigurations, VersionedResourceSharing } from "@rolebook/sharing"; import { createSqliteAuthorizedQueries, createSqliteLocalIdentityProjection, type QueryDefinition, type SqliteSharingAdapter, } from "@rolebook/sharing-sqlite"; import { createBunSqliteQueryExecutor } from "@rolebook/sharing-sqlite/bun-query"; // One executor object for the adapter, the policy store and the query factory. const executor = createBunSqliteQueryExecutor({ filename: "/var/lib/app/app.db", maxConnections: 4 }); // Built with createSqliteSharingAdapter({ executor, fencePolicy, ... }). declare const adapter: SqliteSharingAdapter; // Its policy store is createSqlitePolicyStore({ executor }). declare const sharing: VersionedResourceSharing; declare const recentDocuments: QueryDefinition; declare const queryCursorKey: string; const queries = createSqliteAuthorizedQueries({ adapter, sharing, identity: createSqliteLocalIdentityProjection({ table: "identity_projection" }).identity, queries: [recentDocuments], listingCursorKey: [queryCursorKey], environmentId: "orders-g1", }); // At shutdown: await queries.close(); // drains this factory's pages await executor.close(); // terminates the workers ``` The worker executor itself is described under [`createBunSqliteQueryExecutor`](/docs/sharing-sqlite/api#createbunsqlitequeryexecutor). # @rolebook/sharing/checkpoints (/docs/sharing/checkpoints) > The exports of the opt-in consistency checkpoint entry point of @rolebook/sharing. `import { ... } from "@rolebook/sharing/checkpoints"`. An opt-in, server-side consistency foundation: checkpoint capture, comparable-floor registration, an authenticated token codec, and a bounded admission waiter. The main `@rolebook/sharing` API does not issue or consume checkpoint tokens on its own. A checkpoint is freshness evidence, never an authorization grant. An `admitted` result does not replace the normal authorization check, and a later protected write must prove the required floors again inside its own transaction. This foundation does not wire SQL `atLeast` reads, issue tokens from committed receipts, or provide an operational restore-safety protocol. Applications must handle `unavailable` results explicitly. Keep the codec's keys and trusted state on trusted servers. Signing keys hold 32 to 64 bytes of secret random data. Tokens expire within five minutes (`checkpointLimits.maxLifetimeMs`), and a positive wait has one deadline of at most five seconds (`checkpointLimits.maxWaitMs`). The initial profile supports policy, tenant-role, resource-sharing and principal-identity floors. Group-membership floors and tenant-list operations are not supported yet. ## Contract [#contract] `createCheckpointObservationRegistry()` records the application's trusted producer contracts. It cannot establish that a database snapshot or restore process is correct. Comparable revisions are canonical decimal integers, compared exactly. ### `captureCheckpointPayload` [#capturecheckpointpayload] ```ts api="@rolebook/sharing/checkpoints" function captureCheckpointPayload(value: unknown): CheckpointPayload; ``` ### `captureCheckpointContext` [#capturecheckpointcontext] ```ts api="@rolebook/sharing/checkpoints" function captureCheckpointContext(value: unknown): CheckpointContext; ``` ### `checkpointFloorKey` [#checkpointfloorkey] ```ts api="@rolebook/sharing/checkpoints" function checkpointFloorKey(floor: CheckpointFloor): string; ``` ### `canonicalCheckpointFloors` [#canonicalcheckpointfloors] ```ts api="@rolebook/sharing/checkpoints" function canonicalCheckpointFloors(value: readonly CheckpointFloor[]): readonly CheckpointFloor[]; ``` ### `checkpointCompatibility` [#checkpointcompatibility] ```ts api="@rolebook/sharing/checkpoints" function checkpointCompatibility(payload: CheckpointPayload, context: CheckpointContext): "compatible" | "incompatible_checkpoint" | "unsupported_mode"; ``` ### `createCheckpointObservationRegistry` [#createcheckpointobservationregistry] ```ts api="@rolebook/sharing/checkpoints" function createCheckpointObservationRegistry(context: CheckpointContext, registrations: readonly CheckpointProducerRegistration[]): CheckpointObservationRegistry; ``` ### `compareCheckpointFloors` [#comparecheckpointfloors] ```ts api="@rolebook/sharing/checkpoints" function compareCheckpointFloors(payload: CheckpointPayload, context: CheckpointContext, registry: CheckpointObservationRegistry, snapshot: CheckpointSnapshot, nowMs: number): CheckpointFloorComparison; ``` ### `checkpointLimits` [#checkpointlimits] ```ts api="@rolebook/sharing/checkpoints" const checkpointLimits: Readonly<{ encodedBytes: 8192; floors: 64; scopeBytes: 512; identifierBytes: 128; opaqueIdBytes: 256; opaqueIdCodeUnits: 128; maxDepth: 8; maxNodes: 1024; maxLifetimeMs: 300000; maxClockSkewMs: 30000; maxUnixMs: 253402300799999; maxWaitMs: 5000; maxStaleMs: 60000; }>; ``` ### `CheckpointAuthority` [#checkpointauthority] ```ts api="@rolebook/sharing/checkpoints" interface CheckpointAuthority { readonly application: string; readonly environment: string; readonly tenant: string; readonly authoritySet: string; readonly restoreEpoch: string; } ``` ### `CheckpointPrincipal` [#checkpointprincipal] ```ts api="@rolebook/sharing/checkpoints" interface CheckpointPrincipal { readonly type: string; readonly id: string; } ``` ### `CheckpointOperationScope` [#checkpointoperationscope] ```ts api="@rolebook/sharing/checkpoints" type CheckpointOperationScope = { readonly kind: "resource"; readonly resourceType: string; readonly resourceId: string; readonly incarnation: string; } | { readonly kind: "tenantList"; readonly resourceType: string; readonly listingDomain: string; }; ``` ### `CheckpointFloor` [#checkpointfloor] ```ts api="@rolebook/sharing/checkpoints" type CheckpointFloor = { readonly domain: "policy"; readonly scope: { readonly kind: "authorityPolicy"; }; readonly revision: string; } | { readonly domain: "tenantRoles"; readonly scope: { readonly kind: "tenantRoles"; }; readonly revision: string; } | { readonly domain: "sharing"; readonly scope: { readonly kind: "resourceSharing"; readonly resourceType: string; readonly resourceId: string; readonly incarnation: string; }; readonly revision: string; } | { readonly domain: "identityProjection"; readonly scope: { readonly kind: "principalProjection"; readonly projection: string; readonly principalType: string; readonly principalId: string; }; readonly revision: string; } | { readonly domain: "groupMembership"; readonly scope: { readonly kind: "groupMember"; readonly projection: string; readonly groupType: string; readonly groupId: string; readonly memberType: string; readonly memberId: string; }; readonly revision: string; }; ``` ### `CheckpointContext` [#checkpointcontext] ```ts api="@rolebook/sharing/checkpoints" interface CheckpointContext { readonly issuer: string; readonly audience: string; readonly authority: CheckpointAuthority; readonly principal: CheckpointPrincipal; readonly operationScope: CheckpointOperationScope; readonly profile: "local-authority-v1"; } ``` ### `CheckpointPayload` [#checkpointpayload] ```ts api="@rolebook/sharing/checkpoints" interface CheckpointPayload extends CheckpointContext { readonly schema: 1; readonly checkpointId: string; readonly issuedAtMs: number; readonly expiresAtMs: number; readonly floors: readonly CheckpointFloor[]; } ``` ### `CheckpointProducerRegistration` [#checkpointproducerregistration] ```ts api="@rolebook/sharing/checkpoints" type CheckpointProducerRegistration = CheckpointFloor extends infer F ? F extends { readonly domain: infer D; readonly scope: infer S; } ? D extends "groupMembership" ? never : { readonly producerId: string; readonly domain: D; readonly scope: S; } : never : never; ``` ### `CheckpointObservationRegistry` [#checkpointobservationregistry] ```ts api="@rolebook/sharing/checkpoints" interface CheckpointObservationRegistry { readonly [registryBrand]: true; } ``` ### `CheckpointObservation` [#checkpointobservation] ```ts api="@rolebook/sharing/checkpoints" interface CheckpointObservation { readonly producerId: string; readonly floor: CheckpointFloor; } ``` ### `CheckpointSnapshot` [#checkpointsnapshot] ```ts api="@rolebook/sharing/checkpoints" interface CheckpointSnapshot { readonly context: CheckpointContext; readonly mode: "consistentLocalSnapshot"; readonly snapshotId: string; readonly observedAtMs: number; readonly validUntilMs: number; readonly observations: readonly CheckpointObservation[]; } ``` ### `CheckpointFloorComparison` [#checkpointfloorcomparison] ```ts api="@rolebook/sharing/checkpoints" type CheckpointFloorComparison = { readonly status: "met"; } | { readonly status: "unmet"; } | { readonly status: "unavailable"; readonly reason: "unsupported_mode" | "incompatible_checkpoint" | "dependency_unavailable" | "projection_expired"; }; ``` ### `CheckpointContractError` [#checkpointcontracterror] ```ts api="@rolebook/sharing/checkpoints" class CheckpointContractError extends TypeError { readonly code: "INVALID_CHECKPOINT"; constructor(); } ``` ## Token codec [#token-codec] `createCheckpointCodec()` takes a trusted clock, issuer, audience, authority namespace, and leased keyring and restore-epoch state. `issue({ context, registry, snapshot, ttlMs })` derives floors from registered observations in one application-provided consistent snapshot. `verify()` authenticates a received token and checks the expected context, key state, epoch and time bounds. Keyring and epoch replacements through `replaceTrustedState()` need monotone generations. To revoke the last signing key, set `signingKeyId` to `null` and mark that key revoked, or remove it, in a newer generation. ### `createCheckpointCodec` [#createcheckpointcodec] ```ts api="@rolebook/sharing/checkpoints" function createCheckpointCodec(options: CheckpointCodecOptions): CheckpointCodec; ``` ### `CheckpointUnavailableReason` [#checkpointunavailablereason] ```ts api="@rolebook/sharing/checkpoints" type CheckpointUnavailableReason = "invalid_checkpoint" | "expired_checkpoint" | "incompatible_checkpoint" | "revoked_checkpoint" | "dependency_unavailable" | "epoch_unavailable" | "unsupported_mode" | "projection_expired" | "unmet_floor" | "waiter_capacity_exceeded" | "deadline_exceeded" | "cancelled"; ``` ### `CheckpointResult` [#checkpointresult] ```ts api="@rolebook/sharing/checkpoints" type CheckpointResult = { readonly status: "ok"; readonly value: T; } | { readonly status: "unavailable"; readonly reason: CheckpointUnavailableReason; }; ``` ### `CheckpointKey` [#checkpointkey] ```ts api="@rolebook/sharing/checkpoints" interface CheckpointKey { readonly issuer: string; readonly keyId: string; readonly algorithm: "HS256"; readonly state: "staged" | "signing" | "verify-only" | "revoked"; readonly notBeforeMs: number; readonly signUntilMs: number; readonly verifyUntilMs: number; readonly secret: Uint8Array; } ``` ### `CheckpointTrustedState` [#checkpointtrustedstate] ```ts api="@rolebook/sharing/checkpoints" interface CheckpointTrustedState { readonly keyring: { readonly generation: string; readonly observedAtMs: number; readonly expiresAtMs: number; readonly signingKeyId: string | null; readonly keys: readonly CheckpointKey[]; }; readonly epochLease: { readonly authority: Omit; readonly restoreEpoch: string; readonly generation: string; readonly observedAtMs: number; readonly expiresAtMs: number; }; } ``` ### `CheckpointCodecOptions` [#checkpointcodecoptions] ```ts api="@rolebook/sharing/checkpoints" interface CheckpointCodecOptions { readonly issuer: string; readonly audience: string; readonly authority: Omit; readonly now: () => number; readonly trustedState: CheckpointTrustedState; readonly clockSkewMs?: number; readonly maxInFlight?: number; readonly operationTimeoutMs?: number; } ``` ### `CheckpointIssueInput` [#checkpointissueinput] ```ts api="@rolebook/sharing/checkpoints" interface CheckpointIssueInput { readonly context: CheckpointContext; readonly registry: CheckpointObservationRegistry; readonly snapshot: CheckpointSnapshot; readonly ttlMs: number; } ``` ### `CheckpointCodec` [#checkpointcodec] ```ts api="@rolebook/sharing/checkpoints" interface CheckpointCodec { issue(input: CheckpointIssueInput): Promise>; verify(input: { readonly token: string; readonly expected: CheckpointContext; }): Promise>; replaceTrustedState(next: CheckpointTrustedState): void; } ``` ## Waiter [#waiter] `createCheckpointWaiter()` verifies before admission, before each retry and after a successful probe. Its trusted `probe` must prove all floors in one snapshot and release storage resources before settling. A zero `waitMs` makes one attempt under a separate bounded operation timeout. Process-local verification and admission limits reject excess work, and a timed-out or cancelled operation keeps its capacity until the underlying work actually settles. ### `createCheckpointWaiter` [#createcheckpointwaiter] ```ts api="@rolebook/sharing/checkpoints" function createCheckpointWaiter(options: CheckpointWaiterOptions): CheckpointWaiterWithDiagnostics; ``` ### `CheckpointWaiterClock` [#checkpointwaiterclock] ```ts api="@rolebook/sharing/checkpoints" interface CheckpointWaiterClock { now(): number; setTimeout(callback: () => void, milliseconds: number): unknown; clearTimeout(handle: unknown): void; } ``` ### `CheckpointProbeResult` [#checkpointproberesult] ```ts api="@rolebook/sharing/checkpoints" type CheckpointProbeResult = { readonly status: "met" | "unmet"; } | { readonly status: "unavailable"; readonly reason: CheckpointUnavailableReason; }; ``` ### `CheckpointWaiterOptions` [#checkpointwaiteroptions] ```ts api="@rolebook/sharing/checkpoints" interface CheckpointWaiterOptions { readonly verifier: { verify(input: { readonly token: string; readonly expected: CheckpointContext; }): Promise>; }; readonly probe: (checkpoint: CheckpointPayload, input: { readonly signal: AbortSignal; readonly remainingMs: number; }) => Promise; readonly clock?: CheckpointWaiterClock; readonly pollMs?: number; readonly operationTimeoutMs?: number; readonly limits?: { readonly total?: number; readonly tenant?: number; readonly principal?: number; readonly verification?: number; }; readonly diagnostics?: CheckpointWaiterDiagnosticsOptions | undefined; } ``` `diagnostics` is optional; see [waiter diagnostics](#waiter-diagnostics). Omitted, `run` is the original method and nothing is recorded except the live capacity counts. ### `CheckpointWaiterRequest` [#checkpointwaiterrequest] ```ts api="@rolebook/sharing/checkpoints" interface CheckpointWaiterRequest { readonly checkpoint: string; readonly context: CheckpointContext; readonly waitMs: number; readonly signal?: AbortSignal; } ``` ### `CheckpointAdmission` [#checkpointadmission] ```ts api="@rolebook/sharing/checkpoints" type CheckpointAdmission = { readonly status: "admitted"; } | { readonly status: "unavailable"; readonly reason: CheckpointUnavailableReason; }; ``` ### `CheckpointWaiter` [#checkpointwaiter] ```ts api="@rolebook/sharing/checkpoints" interface CheckpointWaiter { run(request: CheckpointWaiterRequest): Promise; } ``` ### `CheckpointWaiterWithDiagnostics` [#checkpointwaiterwithdiagnostics] ```ts api="@rolebook/sharing/checkpoints" interface CheckpointWaiterWithDiagnostics extends CheckpointWaiter { diagnostics(): CheckpointWaiterDiagnostics; } ``` What `createCheckpointWaiter()` returns. `CheckpointWaiter` itself is unchanged. ## Waiter diagnostics [#waiter-diagnostics] Optional and waiter-local. With `diagnostics` set, each `run` call is observed once, on its final public result, through a wrapper that returns the same admission object and rethrows the identical exception without awaiting the observer. `admitted` in an observation is freshness evidence that the floors were met, never an authorization allow. Durations use a separately captured `performance.now`, never the waiter `clock`, and are `timing: "unavailable"` when it faults. The observer, queue and timeout behave exactly as for [sharing diagnostics](/docs/sharing/api#operational-diagnostics): one call at a time, bounded FIFO with counted drops, report-only timeout that keeps the slot until settlement, no abort signal, and synchronous CPU work cannot be preempted. At most one observation is delivered per timer turn, so bursts can drop even with a fast observer; `totals` are updated before queueing and keep counting. Ambient asynchronous context in the observer may belong to another request: never attribute an observation to it or export identifiers read from it. ### `CheckpointWaiterDiagnosticsOptions` [#checkpointwaiterdiagnosticsoptions] ```ts api="@rolebook/sharing/checkpoints" interface CheckpointWaiterDiagnosticsOptions { readonly observe?: CheckpointWaitObserver; readonly queueLimit?: number; readonly observerTimeoutMs?: number; } ``` The same strict capture and ranges as `SharingDiagnosticsOptions`; every failure is `TypeError("Invalid checkpoint waiter diagnostics options")`, checked after every existing option. ### `CheckpointWaitObserver` [#checkpointwaitobserver] ```ts api="@rolebook/sharing/checkpoints" type CheckpointWaitObserver = (observation: CheckpointWaitObservation) => void | PromiseLike; ``` ### `CheckpointWaitObservation` [#checkpointwaitobservation] ```ts api="@rolebook/sharing/checkpoints" interface CheckpointWaitObservation { readonly type: "checkpoint"; readonly sequence: number; readonly operation: "checkpointWait"; readonly settlement: "returned" | "rejected"; readonly result: "admitted" | "unavailable" | "unknown" | "rejected"; readonly reason: CheckpointUnavailableReason | null; readonly timing: "measured" | "unavailable"; readonly durationMs: number | null; } ``` No token, context, authority, tenant, principal, floor, payload or exception text. ### `CheckpointWaiterDiagnostics` [#checkpointwaiterdiagnostics] ```ts api="@rolebook/sharing/checkpoints" interface CheckpointWaiterDiagnostics { readonly scope: "factory-local"; readonly enabled: boolean; readonly capacity: { readonly total: number; readonly verifying: number; }; readonly totals: { readonly admitted: number; readonly unavailable: Readonly>; readonly unknown: number; readonly rejected: number; }; readonly timingUnavailable: number; readonly observation: { readonly status: "disabled" | "healthy" | "degraded" | "stalled"; readonly queueLimit: number; readonly queued: number; readonly outstanding: 0 | 1; readonly completed: number; readonly failed: number; readonly timedOut: number; readonly dropped: number; }; } ``` `capacity` is read live and is only this waiter's aggregate occupancy: reserved probe slots and verifications in flight, including work that outlived its caller's deadline or cancellation and still holds capacity until it settles. Per-tenant and per-principal buckets and their keys never leave the waiter. Not admission state, a distributed limiter, or proof of freshness or reachability. # Commands (/docs/sharing/commands) > execute() and its seven commands, tenant.governance, idempotency, conflict retries, expiring memberships, and result codes. Every change to sharing state is a command passed to `execute()` on a tenant facade. The module authorizes it with Rolebook against current state, applies it in the storage adapter's transaction with an audit event, and returns a result. It never throws for an ordinary refusal. Whenever governance applies, that direct call returns `GOVERNANCE_REQUIRED` and does not bypass approval effects. Those commands go through the server-side [`tenant.governance`](#governance) façade. ```ts prelude=sharing const result = await tenant.execute({ kind: "grantRole", resource: { type: "project", id: projectId }, subject: { type: "user", id: "user_789" }, role: "editor", idempotencyKey: "grant-user_789-project_1", }); if (result.ok) { console.log(result.code, result.sharingRevision); // "APPLIED" | "ALREADY_APPLIED" } else { console.log(result.code); // for example "FORBIDDEN" or "NOT_TENANT_MEMBER" } ``` ## The commands [#the-commands] Every command names its `resource` (`{ type, id }`) and an `idempotencyKey`, an opaque string of 1 to 128 characters. Role labels are the configured member-role labels (or a [custom role](/docs/sharing/versioned#custom-roles) label on a versioned instance). | Command | Fields | Actor needs | | --- | --- | --- | | `grantRole` | `subject`, `role`, optional `expiresAt` | `management.members` | | `changeRole` | `subject`, `role`, optional `expiresAt` (`Date`, `null`, or omitted) | `management.members` | | `revokeMember` | `subject` | `management.members` | | `transferOwnership` | `to`, optional `formerOwnerRole` | `management.ownership`, and to be the current owner | | `issueInvitation` | `recipient`, `role`, `expiresAt`, optional `membershipExpiresAt` | `management.invitations` | | `acceptInvitation` | `token` | to match the invitation's recipient | | `revokeInvitation` | `invitationId` | `management.invitations` | Beyond the management permission, grants, changes, revocations, and invitations by anyone other than the owner are bounded by the [delegation ceiling](/docs/sharing/delegation): a manager can hand out, change, or take away only access it holds itself. ### Grant and change a role [#grant-and-change-a-role] `grantRole` creates a membership for a subject (a user, or a [team](/docs/teams)) who must be an eligible member of the tenant. A live membership already present is `MEMBER_ALREADY_EXISTS`; use `changeRole` to change it. `changeRole` replaces the role of an existing membership. Neither may target the actor itself (`SELF_PROMOTION`) or the current owner (`OWNER_TRANSFER_REQUIRED`). ### Revoke a member [#revoke-a-member] `revokeMember` deletes a membership. A successful commit is the linearization point: the next authorization and listing read the new state. Positive decisions are never cached by the module. ### Transfer ownership [#transfer-ownership] Only the current owner may transfer ownership, and only to an eligible individual: a group target is `GROUP_CANNOT_OWN`, and an actor that holds `management.ownership` without owning the resource is `OWNER_TRANSFER_REQUIRED`. With `formerOwnerRole`, the former owner keeps a permanent membership with that role; without it, the former owner keeps no membership. A former owner retrying its own committed transfer with the same idempotency key still gets `ALREADY_APPLIED`. ### Invitations [#invitations] `issueInvitation` creates an invitation to one recipient and returns its token **once**, on the `APPLIED` result: `result.invitation` is `{ id, token }`. Storage keeps only a keyed digest of the secret, so a replay of the same command reports `ALREADY_APPLIED` without a token. ```ts prelude=sharing const issued = await tenant.execute({ kind: "issueInvitation", resource: { type: "project", id: projectId }, recipient: { type: "subject", subject: { type: "user", id: "user_789" } }, role: "viewer", expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), idempotencyKey: "invite-user_789-project_1", }); if (issued.ok && issued.invitation) { const link = `https://app.example.com/invitations/${encodeURIComponent(issued.invitation.token)}`; } ``` - A recipient is `{ type: "subject", subject }` (bound to an immutable subject ID) or `{ type: "email", email }` (at most 320 characters, matched against the accepting user's verified address). Email recipients need a recipient fence in the storage adapter; some identity adapters refuse them. A malformed recipient is `INVITATION_RECIPIENT_INVALID`. - `expiresAt` must be after the clock's current time and at most `maxInvitationTtlMs` (30 days by default) ahead; otherwise `INVITATION_EXPIRED`. - Inviting yourself is `SELF_PROMOTION`. - The recipient need not be a workspace member yet. Resource invitations never create or replace an identity provider's organization invitation: complete the provider's own workspace invitation first, then accept the resource invitation as the signed-in member. `acceptInvitation` takes the token. The accepting actor must be an eligible tenant member that matches the recipient (`INVITATION_RECIPIENT_MISMATCH` otherwise). Expiry is checked after the identity lookup and again inside storage (`INVITATION_EXPIRED`). A wrong token, a consumed or revoked invitation, a missing resource, and an invitation whose creator no longer qualifies all answer the same `INVITATION_UNAVAILABLE`. Accepting an invitation you created is `SELF_PROMOTION`. Accepting as an existing member consumes the invitation and returns `APPLIED`, but never replaces the member's role: change roles with `changeRole`. An invitation addressed to a team is accepted by a current team member on the team's behalf, and the membership is the team's. `revokeInvitation` revokes a pending invitation by ID. ## Governance [#governance] `tenant.governance` is the server-side façade. It has six methods: `request(command)`, `approve(requestId)`, `reject(requestId)`, `cancel(requestId)`, `apply(requestId)`, and `resolve(requestId)`. Each returns precisely `{ status }`. `status` is `PENDING`, `APPROVED`, `REJECTED`, `APPLIED`, `VOID`, `REFUSED`, `UNAVAILABLE`, or `UNKNOWN_REQUEST`. Before calling `request`, import `createGovernanceRequestId` from `@rolebook/sharing` and call it with the requester’s authenticated tenant context. Put the returned ID in `command.requestId` and keep it for retries and later calls; the response contains only the status. A transfer uses one of two authorized modes. Recipient acceptance is not required. - A non-owner request requires a counted direct-owner sponsor. - An owner request records payload-bound, non-counting owner consent and needs an independent eligible quorum. Direct `execute()` returns `GOVERNANCE_REQUIRED` whenever governance applies. That result does not bypass approval effects. ## Idempotency [#idempotency] Every command carries an `idempotencyKey`. The adapter stores it with a fingerprint: a keyed digest of the actor, the tenant, and the command (the invitation secret is never part of it). Retrying the same command with the same key answers `ALREADY_APPLIED` with the sharing revision of the original commit. Reusing a key for a different command, or from a different actor, is `CONFLICT` once the command is otherwise authorized, returned after the first attempt without retries. On `createSharing()`, a retry is authorized against current state before it replays, with two exceptions that keep retries safe for commands that remove the actor's own access: a former owner retrying its `transferOwnership`, and a member retrying the `revokeMember` that un-shared its own team. A retried grant whose target has since left the tenant, or whose short expiry has since passed, still answers its original success. On [`createVersionedSharing()`](/docs/sharing/versioned), the actor's own committed key replays before validation and authorization, with the `policyVersion` of the original commit. A replay holds only while the idempotency record is kept. Records are pruned by [`pruneSettledRecords()`](/docs/sharing/retention) (30 days by default); after that a retry runs as a new command, re-authorized against current state. Choose a retention longer than every client's retry window. ### Looking up an outcome [#looking-up-an-outcome] A caller that lost the answer of an `execute` (its process stopped, or it gave up waiting) can read what Sharing recorded without running the command again: ```ts prelude=sharing declare const command: Parameters[0]; const found = await tenant.lookupExecution?.(command); if (found?.status === "committed") { // found.result is what a replay answers: ALREADY_APPLIED and the commit's revision. } ``` [`lookupExecution`](/docs/sharing/api#tenantsharing) takes the same command, executes nothing, and answers `committed`, `not_found`, `different_command`, or `refused`. Only `committed` proves an outcome: `not_found` is also the answer after the record was pruned, after the resource was deleted or moved to another tenant, and while the command may still be running. See [`SharingExecutionLookupResult`](/docs/sharing/api#sharingexecutionlookupresult). ## Conflict retries [#conflict-retries] A mutation is conditional on the resource version and sharing revision it was authorized against. When either changed (a concurrent revocation, ownership transfer, deletion, move, or authorization-fact change), the adapter reports a conflict, and `execute()` re-resolves the principal, re-reads the resource, and re-authorizes, up to `mutationRetries` more times (3 by default, at most 10), before returning `CONFLICT`. It pauses before each retry, never before the first attempt or after the last. The default pause is a whole number of milliseconds drawn uniformly from 0 to `min(50, 5 x 2^(retry - 1))`: at most 5, 10, 20, 40, then 50 ms, so writers that conflicted do not retry in lockstep. `mutationBackoffMs(retry)` replaces the schedule and must return a finite delay from 0 to 1,000 ms, or the command rejects with a `RangeError`. `mutationWait(ms)` replaces the timer. ```ts prelude=sharing import { createSharing } from "@rolebook/sharing"; const immediate = createSharing({ definition, identity, invitationTokens, mutationBackoffMs: () => 0, // retry conflicts immediately }); ``` ### Applying only at a revision you read [#applying-only-at-a-revision-you-read] A caller that showed someone the access it is about to change can make the command conditional on what was shown. With `expectedSharingRevision`, the command applies only while the resource's sharing revision is still that value: the write commits under the revision the command was authorized at, and a conflicted attempt re-reads, sees the moved revision, and answers `SHARING_REVISION_CHANGED` instead of retrying into a state nobody reviewed. The command's own earlier commit still replays as `ALREADY_APPLIED`, so a retry after a lost answer is safe. The precondition is not part of the idempotency fingerprint. ```ts prelude=sharing const read = await tenant.describeAccess({ resource: { type: "project", id: projectId } }); if (read.ok) { const result = await tenant.execute({ kind: "revokeMember", resource: { type: "project", id: projectId }, subject: { type: "user", id: "user_789" }, idempotencyKey: "revoke-user_789-reviewed", expectedSharingRevision: read.access.sharingRevision, }); if (!result.ok && result.code === "SHARING_REVISION_CHANGED") { // Access changed since it was read: read it again before asking once more. } } ``` ## Time-limited memberships [#time-limited-memberships] A membership may expire. `grantRole` takes an optional `expiresAt`; `issueInvitation` takes an optional `membershipExpiresAt` for the membership its acceptance creates (a contractor invited for a fixed period); `changeRole` takes `expiresAt` as a `Date` to set one, `null` to make the membership permanent, or nothing to keep the current expiry. Ownership never expires, and a `formerOwnerRole` membership is permanent. ```ts prelude=sharing await tenant.execute({ kind: "grantRole", resource: { type: "project", id: projectId }, subject: { type: "user", id: "contractor_9" }, role: "editor", expiresAt: new Date("2027-03-31T00:00:00Z"), idempotencyKey: "grant-contractor_9", }); ``` - An expiry that is not a valid `Date` (or `null` outside `changeRole`), that is not after the clock's current time, or a `membershipExpiresAt` not after the invitation's own `expiresAt` is `MEMBERSHIP_EXPIRY_INVALID`. - Expiry fields are part of the idempotency fingerprint, so a retry that differs only in expiry is `CONFLICT`. - A membership at or past its `expiresAt` grants nothing: every adapter read leaves it out, and the module skips it again when binding. The row stays until `grantRole` or an accepted invitation replaces it, `changeRole` reinstates it, or `revokeMember` deletes it. - Expiry is decided by the adapter's clock and re-checked by the module's clock, so a membership is gone as soon as either reaches its `expiresAt`. Expiry does not bump the sharing revision, so never key a decision cache on `sharingRevision` alone. - Because an expired membership is absent from every read, the delegation ceiling never sees it: revoking or changing an expired member needs no coverage of its old role. Do not issue expiring grants or invitations until every instance runs a version with expiry support: older code reads an expiring row as permanent. Before rolling back to such a version, revoke or make permanent every expiring membership and revoke every invitation that carries `membershipExpiresAt`. ## Result codes [#result-codes] A successful result is `{ ok: true, code: "APPLIED" | "ALREADY_APPLIED", sharingRevision }`, plus `invitation` on an applied `issueInvitation` and `policyVersion` on a versioned instance. | Code | Meaning | | --- | --- | | `NOT_FOUND_OR_DENIED` | The resource does not exist, the command is malformed, the type is not configured, or the actor has no relationship to the resource. | | `FORBIDDEN` | The actor has a relationship to the resource but Rolebook or the delegation ceiling refuses the command. | | `NOT_TENANT_MEMBER` | The actor or the target subject is not an eligible member of the tenant, or the tenant or actor ID is malformed. | | `ROLE_NOT_ALLOWED` | The role label (or `formerOwnerRole`) is not configured for the type, or names an unavailable custom role. | | `SELF_PROMOTION` | The actor targets its own membership, a team it belongs to, or its own invitation. | | `OWNER_TRANSFER_REQUIRED` | `grantRole`, `changeRole`, or `revokeMember` targets the current owner, or an actor allowed `management.ownership` that is not the current owner sends a `transferOwnership` whose key holds no record (its own committed transfer replays; a key recorded for another command or actor is `CONFLICT`). Without `management.ownership`, a transfer is `FORBIDDEN` or `NOT_FOUND_OR_DENIED`. | | `GROUP_CANNOT_OWN` | Ownership would go to a group. | | `MEMBER_ALREADY_EXISTS` | `grantRole` for a subject with a live membership. | | `INVITATION_EXPIRED` | The invitation's `expiresAt` is invalid when issued, or it has expired when accepted. | | `INVITATION_RECIPIENT_INVALID` | The recipient is malformed. | | `INVITATION_UNAVAILABLE` | The token does not open a pending invitation the actor may use. | | `INVITATION_RECIPIENT_MISMATCH` | The accepting actor is not the invitation's recipient. | | `MEMBERSHIP_EXPIRY_INVALID` | An expiry is malformed or not in the future. | | `CONFLICT` | Retries ran out, or the idempotency key was used for another command. | | `SHARING_REVISION_CHANGED` | The command's `expectedSharingRevision` is no longer the resource's sharing revision. Nothing was applied. | | `GOVERNANCE_REQUIRED` | Direct `execute()` when governance applies. The command is not applied, and the result does not bypass approval effects. | | `POLICY_GENERATION_CHANGED` | Versioned: the active policy changed after authorization. | | `TENANT_ROLES_CHANGED` | Versioned: the tenant's custom roles changed after authorization. | | `POLICY_UNAVAILABLE` | Versioned: the active policy cannot be used, or the adapter is not policy-fenced. | `NOT_FOUND_OR_DENIED` and `FORBIDDEN` are split on purpose: a caller with no relationship to a resource must not learn that it exists. See [denials and resource existence](/docs/sharing/delegation#denials-and-resource-existence). Handle the two alike when you only need "not allowed". Identity adapters may throw (for example a team directory that cannot answer). The module does not catch it: `execute()`, `authorize()`, and `listAccessible()` reject. Treat that as an application fault. # Delegation and denials (/docs/sharing/delegation) > The delegation ceiling, deny-carrying roles on groups, owner recovery, and how denials hide resource existence. Sharing grants are made by actors less trusted than the resource's owner: anyone the policy allows `management.members` or `management.invitations`. Without a bound, a manager could grant a second account a role stronger than its own and have that account promote it in return. The module therefore enforces a **delegation ceiling**. The current owner is exempt. ## The ceiling [#the-ceiling] - `grantRole`, `changeRole`, and `issueInvitation` to a role require the actor to **cover** every allow rule of that role's policy role, inherited roles included. A `type:*` wildcard expands to every action the type declares. - `changeRole` and `revokeMember` also require covering the member's **current** role, so a weaker manager can neither demote nor remove a stronger member. - Lifting a deny hands out the access it blocked. Every deny of the member's current role that the new role does not carry identically (all of them, for `revokeMember`) must be covered as if the actor were granting an unconditional allow of each permission it names. - A role, or a stored role label, that cannot be resolved is never covered. An allow rule is covered, for each concrete permission it names, by a rule-level test over the rules of every role the actor holds on the resource, through its own and its groups' assignments: 1. the actor holds an allow naming the permission (or its type's wildcard) that is unconditional and field-free, or that has exactly the granted rule's `where` and `fields`. An allow whose condition merely happens to hold right now never covers a broader grant; and 2. every deny the actor holds naming the permission is carried, identical in effect, permission, `where`, and `fields`, into the role being handed out, so the recipient is restricted exactly as the actor is. A permission on the resource's own type must also be allowed now by a real Rolebook decision for the actor on this resource, resource-wide and bound like the management check. A permission on a descendant type cannot be checked against this resource, so the rule-level test is all it gets. Anything not covered is `FORBIDDEN`. ## Groups, denies, and the owner [#groups-denies-and-the-owner] A deny on a group's membership reaches every current member of the group, the owner included. So that a less-trusted manager cannot lock the owner out of their own resource, granting, changing, or inviting a **group** to a role that carries any deny requires the actor to be the current owner (`FORBIDDEN` otherwise). An individual may still receive such a role from a manager who covers its allows. An invitation whose recipient does not resolve as a group when it is issued is judged again when a member accepts it on a group's behalf. The owner can always recover from a deny that reaches them anyway. When the current owner revokes or changes a membership, the management check is bound with ownership and the identity adapter's own assignments only, so no membership-derived deny applies, and the owner may revoke a deny-carrying membership of a group they belong to. Other owner commands, such as `transferOwnership`, still honor the deny until it is removed. Workspace assignments from the identity adapter are application policy, not sharing grants, and still apply. An actor may not grant, change, or invite a group it belongs to (`SELF_PROMOTION`). It may revoke its own group's membership when that role only allows, since that can only reduce its own access; revoking a role that carries a deny stays `SELF_PROMOTION`, except for the owner. ## Invitations follow their creator [#invitations-follow-their-creator] An invitation is a deferred grant by its creator. When it is first accepted, the creator is resolved again in the tenant and must still be eligible, still be allowed `management.invitations`, and still own the resource or satisfy the ceiling for the invited role, including the group-deny rule. Otherwise acceptance returns `INVITATION_UNAVAILABLE`, the same outcome as a revoked invitation. The creator's eligibility and relevant authorization facts are fenced in the acceptance's storage transaction alongside the acceptor's. An exact retry of an acceptance that already committed still replays as `ALREADY_APPLIED`. ## Denials and resource existence [#denials-and-resource-existence] `authorize()` and `execute()` answer a caller with no relationship to a resource exactly as they answer for a resource that does not exist, so tenant members cannot probe resource IDs through them (response timing aside). A caller who is not the owner, has no membership on the resource (directly or through a group), and holds none of its type's configured action or management permissions gets `NOT_FOUND_OR_DENIED`, whatever the command or Rolebook decision, including a fault in its own assignments such as `UNKNOWN_ROLE`. Accepting an invitation for a missing resource answers `INVITATION_UNAVAILABLE`, as a wrong token does. A caller who has a relationship, such as a viewer asking to edit or a member whose role carries a deny, already knows the resource exists and gets `FORBIDDEN`, with the Rolebook decision on `authorize()`. The inspecting reads ([`describeAccess()`, `permissions()`, `auditHistory()`](/docs/sharing/reads)) answer every refusal, including a missing or malformed resource, as `NOT_FOUND_OR_DENIED`. ## Assignment projection and the budget [#assignment-projection-and-the-budget] Sharing passes every assignment the identity adapter returns to Rolebook unchanged, then projects only the resource owner or the memberships belonging to the requesting principal and its groups. Unrelated members never consume the binding's budget. An unknown or corrupt role for the requesting principal still fails closed. A Rolebook binding accepts at most 256 assignments. Under the single-owner and single-membership storage invariants, a direct share adds one: 255 identity-adapter assignments plus the projected one succeeds, while 256 plus one fails closed with Rolebook's `INVALID_ASSIGNMENT` (reported by sharing as `FORBIDDEN` on resources the principal owns or is a member of, and as `NOT_FOUND_OR_DENIED` elsewhere). Applications that map workspace roles into assignments must stay within this combined budget. Governed approvals count a party the same way: the owner row, the party's memberships on the resource (and on its ancestors when the type inherits), and every identity assignment the governance identity source holds for the party, wherever it applies. A party over 256 is not counted as an approver, and its approval or rejection is answered `UNKNOWN_REQUEST`, like any party without standing. A rejection it recorded earlier stops holding the request, as if the party had lost its role, and an owner over 256 cannot consent to an ownership transfer. Two cases are stricter than the direct check. On a resource whose type passes access down, the delegation proof keeps one entry in reserve, so governance stops at 255. Under `evidenceSources.groups: "none"`, every identity assignment held by a group in the tenant counts as possibly the party's, because governance cannot see who belongs to the group. When they could carry a party over 256, a party that would otherwise count is answered `UNKNOWN_REQUEST` and nothing is recorded. A rejection, sponsor approval or owner consent that party already recorded keeps the request from applying until the count can be confirmed again. Once groups hold 256 identity assignments in a tenant, governance can confirm no party there, the owner included. Bind a group graph before that. Sharing does not filter identity-adapter assignments by resource, ancestry, `appliesTo`, or subject: Rolebook validates the whole collection before selecting the applicable ones, and filtering would weaken that fail-closed validation. # Resource sharing (/docs/sharing) > @rolebook/sharing: tenant-scoped membership, ownership, invitations, and audit, decided by Rolebook. Most products need more than workspace roles: a project shared with three people, a folder handed to a new owner, an invitation that expires, a contractor whose access ends on a date. `@rolebook/sharing` owns that layer. It manages per-resource membership, ownership transfer, resource invitations, revocation, audit events, and accessible-resource listing, and it delegates every final decision to a Rolebook authorizer built from the exact policy in its definition. ## The division of labour [#the-division-of-labour] | Layer | Owns | | --- | --- | | Identity provider (Better Auth, Clerk, WorkOS, your own) | Users, organizations or workspaces, workspace members and roles, workspace invitations. | | `@rolebook/sharing` | Per-resource ownership, memberships, resource invitations, audit, listing. | | Storage adapter (PostgreSQL, SQLite) | The sharing tables, locks, fences, and atomic commits in your own database. | | The Rolebook engine (`rolebook`) | Every allow or deny. | Workspace membership is **eligibility**, never access. A member of the workspace sees a private project only when they own it, hold a membership on it (directly or through a team), or hold a workspace role your identity adapter explicitly maps to Rolebook assignments. ## How a request is decided [#how-a-request-is-decided] For every operation, the module: 1. Captures the input as immutable data, with an explicit tenant ID and actor. 2. Asks the identity adapter whether the actor is an eligible member of that tenant, and for any mapped workspace assignments and current groups. 3. Asks the resource type's storage adapter for an authoritative snapshot of the resource, its owner, and the memberships of the actor and its groups, fencing the actor's eligibility in the same read. 4. Projects ownership and memberships into Rolebook assignments, binds them with the identity adapter's assignments, and asks Rolebook. 5. For a mutation, applies it in the storage adapter's transaction, conditional on the resource version and sharing revision it read, with an audit event in the same commit. A concurrent change produces a conflict, and the module re-runs the whole sequence. ## What you can ask [#what-you-can-ask] Beyond commands that change access, the module answers the questions your screens and jobs ask. Every access decision is made by the Rolebook engine; a database query only ever narrows candidates. | Question | Call | | --- | --- | | May the actor do this to this resource? | [`authorize()`](/docs/sharing/reads#authorize) | | What may the actor do to this resource, action by action? | [`permissions()`](/docs/sharing/reads#permissions) | | Who owns this resource, who are its members, which invitations are pending? | [`describeAccess()`](/docs/sharing/reads#describeaccess) | | Which resources of a type may the actor perform one action on? | [`listAccessible()`](/docs/sharing/listing) | | Which resources of a type may the actor do anything on, and what exactly? | [`listAccess()`](/docs/sharing/listing#everything-the-actor-can-do-by-type) | | Which rows of my own table, filtered and sorted my way, may the actor open? | [Named authorized queries](/docs/sharing/authorized-queries) | | Why can or can't a named subject do this, right now? | [`explain()`](/docs/sharing/inspection), opt-in | | Who changed access to this resource, and when? | [`auditHistory()`](/docs/sharing/reads#audithistory) | Every call runs in the named tenant under the bound actor's authority, and all but one answer about that actor. The exception is `explain()`, the opt-in privileged inspection: the actor must hold the resource's inspect permission, and the answer explains the subject named in the request. `describeAccess()` reports what is stored on one resource (its owner, members, and pending invitations); it does not enumerate everyone whom a workspace role, a group, or a condition would also allow. Each page of `listAccessible()` and `listAccess()` is consistent within the page. Its candidate scan, the principal, each examined resource, the policy runtime, and the instant used for every expiry comparison belong to one coherent read point, so both the entries and the `exhausted` flag describe a state that existed. Every page takes a fresh snapshot: a cursor records a position and does not freeze the result set across pages, and a page is not kept current after it returns. That depends on configuration. The storage adapter has to hold one snapshot for the page: the in-memory adapter holds its own, and a SQL adapter needs a supported executor, which is the package's checked executor on PostgreSQL and the worker-backed executor over a database file on SQLite. The identity source has to supply evidence for the same point. The identity adapters for Better Auth, Clerk, and WorkOS, and the `withTeams()` wrapper, answer from the provider and do not supply that evidence. For listing, the identity adapter you pass to `createSharing()` must itself resolve principals from a complete local identity projection in the same database, kept synchronized as authoritative data, and that same adapter object is named with the projection in the storage adapter's `pageIdentity` option; or it must be an adapter of your own that implements `resolvePagePrincipal` over a source with a non-repeating revision. See [listing page evidence](/docs/sharing/adapters#listing-page-evidence). When the configured adapter, executor, or identity source cannot provide a consistent page, the call rejects with `AccessListingUnavailableError` and a `reason`; it does not return a partial or weaker page. [Listing accessible resources](/docs/sharing/listing) has the requirements and the reasons. To give other services a plain Core check over HTTP, see the [decision service](/docs/decision-service); to serve these Sharing operations to a browser or an SDK, see the [HTTP API](/docs/http-api). ## Packages [#packages] | Package | Role | | --- | --- | | [`@rolebook/sharing`](/docs/sharing/setup) | The module, the adapter contracts, an in-memory adapter for tests. | | [`@rolebook/sharing-postgres`](/docs/sharing-postgres) | ORM-neutral PostgreSQL adapter: `SERIALIZABLE` transactions, row-lock fences, migrations. | | [`@rolebook/sharing-sqlite`](/docs/sharing-sqlite) | Driver-neutral SQLite adapter: `BEGIN IMMEDIATE` fencing, migrations, bun:sqlite and libSQL executors. | | [`@rolebook/sharing-better-auth`](/docs/sharing-better-auth) | Identity from Better Auth organizations. | | [`@rolebook/better-auth`](/docs/better-auth) | Drop-in Better Auth plugin: endpoints, migrations, client plugin, and React bindings. | | [`@rolebook/sharing-clerk`](/docs/sharing-clerk) | Identity from Clerk organizations. | | [`@rolebook/sharing-workos`](/docs/sharing-workos) | Identity from WorkOS User Management, plus Directory Sync groups. | | [`@rolebook/teams`](/docs/teams) | Team principals: flat directories, an identity wrapper, PostgreSQL fences, and an optional nested-lineage directory. | | [`@rolebook/sharing-testkit`](/docs/sharing-testkit) | The security contract every adapter must pass. | | [`@rolebook/http`, `server`, `client`](/docs/http-api) | The sharing operations over HTTP, plus signed [access-change webhooks](/docs/sharing/webhooks). | | [`@rolebook/react`](/docs/react) | Accessible React sharing components and headless state over `@rolebook/client`. | ## Invariants the module enforces [#invariants-the-module-enforces] - Every operation names its tenant explicitly. A session's active workspace is never tenancy evidence. Malformed tenant or actor IDs fail closed before any callback runs. - Resources are loaded by `(tenantId, resourceId)` from the storage adapter. A client-supplied ID of the right type is not provenance. - Ordinary member roles never include ownership. Only `transferOwnership` replaces the owner, atomically. - An actor cannot grant, change, or revoke its own membership, and a manager other than the owner can hand out only access it holds itself: the [delegation ceiling](/docs/sharing/delegation). - A denial does not confirm that a resource exists: a caller with no relationship to it gets the same answer as for a missing resource. - Invitation secrets are returned once. Storage keeps only a keyed digest, the recipient binding, expiry, and consumption or revocation state. - Sharing state changes and their audit events commit atomically. Access changes can be delivered to other systems after commit as signed [webhooks](/docs/sharing/webhooks); other consumers drain the audit table themselves. ## Read next [#read-next] The policy shape sharing needs, `defineSharing`, and `createSharing` options. Grants, role changes, revocation, ownership, invitations, and their result codes. `listAccessible()`, `listAccess()`, sealed cursors, and page consistency. Scoped roles, deny, revocation, and the grant, change, and revoke commands. Let documents inherit access from their folder chain on PostgreSQL or SQLite. Deliver signed HTTP notifications when memberships, ownership, or invitations change. An end-to-end guide on PostgreSQL or SQLite. Every export of `@rolebook/sharing`. # Inherited access (/docs/sharing/inheritance) > Let documents inherit access from their folder chain, with PostgreSQL or SQLite, opt-in per type and bounded. By default every shared resource is decided on its own memberships. With inherited access, a membership stored on a folder also applies to everything below it in the folder chain: grant Alice `editor` on a folder and she can edit its documents and subfolders, at any depth up to the bound. Inheritance is opt-in per resource type, served only by the first-party PostgreSQL and SQLite adapters, and only for a tenant whose hierarchy has been enrolled and activated. An application that does not opt in is unchanged. ## What inherits [#what-inherits] - A **membership** stored on an ancestor applies at that ancestor's scope (`descendants`), through the ancestor type's configured member role. A role's rules decide what reaches the descendant: a folder role needs a rule such as `document:read` to grant anything on a document. - **Ownership never inherits.** A folder's owner gains nothing over its contents from ownership. - **Deny wins.** A deny on an ancestor applies to every descendant, and an explicit deny on the descendant itself wins over an inherited allow. The owner's recovery (`revokeMember` and `changeRole` by the resource's own owner) leaves out only memberships stored on the resource itself; an ancestor's deny still binds the owner. - **Expiry** is judged at every scope with one instant per read. An expired ancestor membership, allow or deny, contributes nothing. - **Teams.** A team's membership on an ancestor applies to the team's members, as on the resource itself. The chain is read from the managed hierarchy relation in the same snapshot as the decision. The `ancestors` your resource descriptor returns are not used for an enrolled tenant. ## Bounds and what is not supported [#bounds-and-what-is-not-supported] - **Depth:** at most 16 ancestors (17 resources counting the target). A structure command refuses a placement that would exceed it, and a stored chain that exceeds it is refused, never shortened. - **Fail closed:** a missing, repeated, cyclic or cross-tenant chain row, a quarantined tenant, a stale policy or configuration generation, or an unusable local identity answers `HierarchyUnavailableError` (HTTP 503 `HIERARCHY_UNAVAILABLE`) with a typed `reason`. Nothing falls back to a flat decision. - **Adapters:** the memory adapter and custom adapters have no inherited read; `defineSharing` refuses `inheritance` on them. - **Flat tenants:** an opted-in type is never served on a tenant that is not enrolled. Once a Sharing instance is built from a definition that opts it in, every path refuses it there by type, before any lookup, replay, journal read or candidate scan: single reads, `describeAccess`, both listings, commands and protected writes throw `not_enrolled`; named queries answer `QUERY_UNAVAILABLE`, governed calls `UNAVAILABLE` and `explain` `INSPECTION_UNAVAILABLE`. Lifecycle writers that initialize, delete or move a resource are not refused. This holds whatever policy is active (recursion published later, or turned off) and whether or not `enable…InheritedReads` was called: on a flat tenant nothing proves a chain complete, or that a resource presented as a root is one. Enroll a tenant before it uses these types; keep types that must serve flat tenants out of the opt-in. This is deliberately stricter than the `sharing.inheritance/1` contract, which lets types that do not reach a recursive type keep their flat contract. - **Decide before launch:** opting in a type that already has resources stops service for every tenant that holds them: those tenants are not enrolled, and existing resources cannot be adopted into the hierarchy yet. Decide whether a type uses inheritance before it stores data. - **Storage serves one kind:** a Sharing instance claims each first-party adapter's storage (its executor and tables, not the adapter object) when it is constructed: inheriting for opted-in types, flat otherwise. Defining alone claims nothing, so a definition that fails or is discarded changes nothing. In a process, a storage serves inherited or flat access, not both: an instance whose claim conflicts with an earlier one throws at construction, whichever adapter object it uses, and `enable…InheritedReads` refuses storage already claimed flat. A definition that uses one storage for both kinds throws before claiming anything. The claim lasts for the process and is keyed by the executor object and the tables: two executors over one database, and other processes, are separate storages, so give every process the same definition. When a definition opts a type in, protected writers accept only the evaluating definition's own adapter for their type. - **One control profile, inheriting types only:** every inheriting type uses one hierarchy control profile, the bootstrap provider's, and `enable…InheritedReads` refuses a definition that also holds a non-inheriting type on a first-party adapter of the same engine. Put flat types in their own Sharing definition and instance, with their own control prefix. - **Existing resources are not adopted:** after the actor is authorized, `enroll` and `activate` answer `unlinked_resources`, before changing tenant state, while the tenant has a row of an inheriting type that the managed hierarchy does not place. The check runs on the control transaction, which holds the tenant's hierarchy barrier exclusively (on SQLite also the database write lock); Sharing takes no lock on your application tables. Enroll a tenant before it has such resources; migrating an existing tenant means recreating its resources through `structure.create` in a new tenant. - **Create rows and initialize them in one transaction:** for an inheriting type, insert the application row and initialize it in the same transaction (`withLifecycleTransaction` with `initializeResourceInTransaction` while the tenant is flat, `structure.create` once it is enrolled). Initialization takes the tenant barrier, so it either commits before `enroll` reads the tenant (and `enroll` answers `unlinked_resources`) or is refused after it and rolls the row back. Inserting the row in one transaction and initializing it in another is not supported for inheriting types: a row committed while `enroll` or `activate` runs may be missed, and its later initialization is refused on the enrolled tenant (or, if it committed while the tenant was still flat, it holds an owner row the hierarchy does not place). The next `activate` answers `unlinked_resources`. To recover, delete the application row. If a read has since quarantined the tenant, `activate` refuses `quarantined`: call `releaseQuarantine` while it answers `verifying`. When it answers `released` with state `active` the tenant is back. With state `building`, call `activate` (it binds the current policy and roles, and answers `inventory_incomplete`), run the inventory to completion, and call `activate` again; the inventory alone does not advance if the policy or the tenant's roles changed while the tenant was quarantined. - **Governed sharing is not supported with inherited access:** the governance attachment's admission does not carry the Sharing definition's inheritance binding. On an enrolled tenant every governed operation (request, approve, reject, cancel, apply, resolve) answers `UNAVAILABLE` before any governance state is read or written, on PostgreSQL and SQLite alike; internally the refusal is the tenant's lifecycle reason when it is not `active`, `policy_incompatible` otherwise. On a flat tenant an opted-in type refuses the same way (above). - **Reconfiguration (known operational limit):** after a policy publish or a change to a tenant's custom roles, the tenant must be activated again, and activation refuses while a stored membership on an inheriting scope carries an allow that reaches further; while the tenant is not `active` its membership writes are refused too. A role reaches when it allows any permission of an inheriting type that can lie below its scope; for a recursive type that includes the type itself (`folder:read` on a folder reaches its child folders). To recover a tenant holding such grants: (1) publish a policy, or edit the custom role, so that the stored grants allow nothing on an inheriting type (a custom role may keep only denies); (2) call `activate`, run the inventory to completion, and call `activate` again; (3) revoke every stored grant that will reach under the intended policy or role, whoever holds it (one left behind blocks step 5, and its revocation is then refused too), and record the ones to restore; (4) publish the intended policy, or edit the custom role back; (5) activate as in step 2; (6) grant the recorded ones again. Edit a reaching custom role; do not retire it: a membership whose role is retired cannot be revoked (`unknown_role`) and a retired role name cannot be reused. Plan configuration changes with this sequence; there is no bypass. - **Configuration changes:** the configuration generation binds the command map, the opted-in types and each type's member and ownership roles, public actions and management permissions (tenant custom roles are bound by the tenant's role revision instead). Changing any of them, publishing a policy, or changing a tenant's custom roles invalidates the activation, and inherited reads and membership writes refuse (`policy_incompatible`) until the tenant is activated again: `activate` re-enters `building`, the inventory runs, and `activate` completes. Activation still refuses while a stored membership on an inheriting scope carries an allow that reaches further, and while the tenant is not `active` its membership writes are refused too, so such a grant cannot be removed then. Remove reaching grants through the ordinary commands before changing the configuration, then re-activate and grant again. A definition that disagrees with the one the adapters were enabled with is refused the same way, on single reads, listings (empty or not), commands and their replays. Adding or removing an inheriting type for an activated tenant is not supported: `activate` refuses it with a `HierarchyUnavailableError` (usually `policy_incompatible`; a profile check may answer first) and leaves the admission and its progress unchanged. A membership command under a mismatched definition is refused `policy_incompatible` before the tenant's lifecycle state is considered, so a `building` tenant answers `policy_incompatible` rather than `building` to it. A protected write checks the lifecycle state first and may answer `building`; it reaches neither its journal nor its target either way. - **Identity:** an enrolled tenant's reads resolve the actor from the complete local identity projection (`createPostgresLocalIdentityProjection` or `createSqliteLocalIdentityProjection`) in the read transaction. The generic identity adapter is not consulted. Every inheriting adapter must be created with `pageIdentity`, whose `source` is the identity adapter the Sharing instance uses: an enabled adapter always resolves page identity in the snapshot, so a page from an instance with another identity adapter is refused (`identity_evidence_missing`). - **Ancestors must exist:** every ancestor's Sharing owner row is checked in the read's snapshot. The owner row references the application row with a cascading foreign key, so this proves the resource exists; on SQLite that holds only while `foreign_keys` is on for every connection that writes the application tables. Every stored subtree height must also satisfy the writers' rules (in range, above the link below, room for the depth above). A surviving link to a deleted resource is refused. - **Listings:** `listAccessible()` and `listAccess()` include inherited access exactly as single checks decide it. They need strict pages: the PostgreSQL adapter, or the SQLite worker executor (`createBunSqliteQueryExecutor`). Without them they refuse with `capability_missing`, as for flat tenants. - **`describeAccess()`** adds an `inherited` section. Inspection is decided first on the actor's own read, so an actor without access learns nothing. An allowed inspector's read then covers every subject's memberships on the chain, bounded at 4096 rows; a larger chain answers `budget_exhausted`, never a shorter list. Direct members and inherited ones are judged at the same instant, and pending invitations are fenced against a move or a sharing change after the read. The section lists every live membership on every ancestor, so an inspector of a document sees who holds roles on its folders, including roles whose rules do not reach the document; restrict `management.inspect` accordingly. A retired custom role on an ancestor is listed with `roleUnavailable: true` and grants nothing. - **Not yet supported on an enrolled tenant:** `explain` (privileged inspection) does not read the managed hierarchy, so it never answers from a flat read there; it fails closed with its fixed unavailable outcome. The HTTP `sharing.describeAccess` operation answers 503 `HIERARCHY_UNAVAILABLE` (`enrolled`) where it would return an inherited description, as before inherited reads were public, because the wire has no inherited section yet; an absent target or an actor who may not inspect still gets the ordinary `NOT_FOUND_OR_DENIED` answer (HTTP 200). Ownership transfer at an inheriting scope answers `INHERITED_SCOPE_UNSUPPORTED`. `auditHistory()` and `previewImpact()` refuse with `HierarchyUnavailableError` (`enrolled`). ## Enabling it [#enabling-it] The example uses SQLite; PostgreSQL has the same functions with a `Postgres` prefix (`enablePostgresInheritedReads`, `createPostgresHierarchyControl`, `runPostgresHierarchyInventory`, `createPostgresBootstrapIntegrity`). 1. **Policy.** Declare the bootstrap type that authorizes tenant-level hierarchy actions, a recursive folder type, and documents below folders. 2. **Configuration.** Set `inheritance: "ancestors"` on every inheriting type, and give each one hierarchy commands (who may create, move and delete). 3. **Storage.** Run the resource migrations (they install the hierarchy control relations), the policy store migrations, and the policy catalog registration for the control profile. Keep a bootstrap row per tenant in an application table and a local identity projection table. 4. **Wire it.** Compute the configuration generation, enable inherited reads on the adapters, create the versioned Sharing instance, then the hierarchy control facade. 5. **Per tenant.** An actor allowed the bootstrap actions enrolls the tenant, an operator job runs the activation inventory to completion, and the actor activates it. Then place resources with `structure.create` and `structure.move`. ```ts import { createHmacInvitationTokens, createVersionedSharing, defineSharing, type HierarchyCommandsInput, hierarchyConfigurationGeneration, type TenantIdentityAdapter, } from "@rolebook/sharing"; import { createSqliteBootstrapIntegrity, createSqliteHierarchyControl, createSqliteLocalIdentityProjection, createSqlitePolicyFence, createSqlitePolicyStore, createSqliteSharingAdapter, enableSqliteInheritedReads, hierarchyControlTables, type ParameterizedSqliteExecutor, runSqliteHierarchyInventory, type SqliteResourceDescriptor, } from "@rolebook/sharing-sqlite"; import { definePolicy } from "rolebook"; declare const executor: ParameterizedSqliteExecutor; declare const identity: TenantIdentityAdapter; declare const folderDescriptor: SqliteResourceDescriptor; declare const documentDescriptor: SqliteResourceDescriptor; declare const invitationKey: string; const policy = definePolicy({ resources: { tenant_admin: { actions: ["root_create", "root_place", "enroll", "activate", "release", "repair"], }, folder: { recursive: true, actions: ["read", "manage", "create", "add", "remove", "delete", "move"], }, document: { parent: "folder", actions: ["read", "edit", "manage", "delete", "move"] }, }, roles: { tenant_operator: { scope: "tenant_admin", rules: [{ effect: "allow", permission: "tenant_admin:*" }], }, folder_owner: { scope: "folder", rules: [ { effect: "allow", permission: "folder:*" }, { effect: "allow", permission: "document:*" }, ], }, folder_editor: { scope: "folder", rules: [ { effect: "allow", permission: "folder:read" }, { effect: "allow", permission: "document:read" }, { effect: "allow", permission: "document:edit" }, ], }, document_owner: { scope: "document", rules: [{ effect: "allow", permission: "document:*" }], }, document_viewer: { scope: "document", rules: [{ effect: "allow", permission: "document:read" }], }, }, }); const projection = createSqliteLocalIdentityProjection({ table: "identity_projection" }); const adapter = (resource: SqliteResourceDescriptor) => createSqliteSharingAdapter({ executor, resource, lockEligibleSubjects: projection.lockEligibleSubjects, fencePolicy: createSqlitePolicyFence(), pageIdentity: { source: identity, resolver: projection.identity }, }); const definition = defineSharing({ policy, resources: { folder: { adapter: adapter(folderDescriptor), memberRoles: { editor: "folder_editor" }, ownershipRole: "folder_owner", actions: { read: "folder:read" }, management: { members: "folder:manage", invitations: "folder:manage", ownership: "folder:manage" }, inheritance: "ancestors", }, document: { adapter: adapter(documentDescriptor), memberRoles: { viewer: "document_viewer" }, ownershipRole: "document_owner", actions: { read: "document:read", edit: "document:edit" }, management: { members: "document:manage", invitations: "document:manage", ownership: "document:manage", }, inheritance: "ancestors", }, }, }); const commands: HierarchyCommandsInput = { bootstrap: { type: "tenant_admin", actions: { rootCreate: "tenant_admin:root_create", rootPlacement: "tenant_admin:root_place", enrollment: "tenant_admin:enroll", activation: "tenant_admin:activate", quarantineRelease: "tenant_admin:release", heightRepair: "tenant_admin:repair", }, }, types: { folder: { delete: "folder:delete", move: "folder:move", createChild: "folder:create", addChild: "folder:add", removeChild: "folder:remove", }, document: { delete: "document:delete", move: "document:move" }, }, }; // One provider per control profile: the application table holding each tenant's bootstrap row. const bootstrap = createSqliteBootstrapIntegrity({ controlPrefix: hierarchyControlTables().prefix, policyStore: { tablePrefix: "rolebook" }, descriptor: { resourceType: "tenant_admin", table: "tenant_admin", tenantColumn: "workspace_id", idColumn: "id", versionColumn: "version", incarnationColumn: "incarnation", }, }); const configurationGeneration = hierarchyConfigurationGeneration({ label: "inherit-1", definition, commands, }); enableSqliteInheritedReads({ definition, commands, configurationGeneration, authorityEpoch: "epoch-1", identity: projection, bootstrap, }); const sharing = await createVersionedSharing({ definition, identity, invitationTokens: createHmacInvitationTokens(invitationKey), policyStore: createSqlitePolicyStore({ executor }), }); const control = createSqliteHierarchyControl({ sharing, policy, commands, bootstrap, authorityEpoch: "epoch-1", configurationGeneration, }); // Per tenant, by an actor the policy allows the bootstrap actions. const operator = control.forTenant({ tenantId: "t1", actor: { type: "user", id: "admin" } }); const enrolled = await operator.enroll({ idempotencyKey: "enroll-t1" }); if (enrolled.status !== "enrolled" && enrolled.status !== "already_enrolled") throw new Error(`enroll: ${enrolled.status}`); // Bounded batches: retry only while the inventory reports progress. let inventory = await runSqliteHierarchyInventory(control, "t1"); for (let batch = 0; inventory.status === "progress" && batch < 1000; batch += 1) inventory = await runSqliteHierarchyInventory(control, "t1"); if (inventory.status !== "complete") throw new Error(`inventory: ${inventory.status}`); const activated = await operator.activate({ idempotencyKey: "activate-t1" }); if (activated.status !== "activated") throw new Error(`activate: ${activated.status}`); ``` Activation is an authority change: it refuses while any stored membership on a would-be inheriting scope carries an allow that would reach further, so activate before granting on folders. (On a tenant that is not enrolled, opted-in types refuse every command, so there are no such grants to remove there.) Any later policy or configuration generation change makes inherited reads unavailable until the tenant is activated again. Once active, grants on folders go through the ordinary `execute` commands, and `describeAccess()` shows where inherited access comes from: ```ts no-check const described = await sharing .forTenant({ tenantId: "t1", actor }) .describeAccess({ resource: { type: "document", id: "d1" } }); // described.access.inherited: // [{ from: { type: "folder", id: "f1" }, depth: 1, subject: { type: "user", id: "alice" }, role: "editor" }] ``` ## Testing an adapter [#testing-an-adapter] `@rolebook/sharing-testkit` exports `sharingInheritanceContract(factory)`: inherit from a parent and from a deeper ancestor, revoke on the parent, an explicit deny on the child, a move to another parent, expiry of the parent membership, a cross-tenant ancestor, a cyclic chain and an over-deep chain, and listing parity. The PostgreSQL and SQLite adapters run it; the memory adapter runs `sharingInheritanceRefusalContract`, which checks that it refuses the option. # Current-state inspection (/docs/sharing/inspection) > explain(): why one subject is or is not allowed an action right now, for privileged inspectors, rate limited and audited. `explain({ resource, action, subject?, field? })` tells a privileged inspector, such as a support engineer or a workspace administrator, why one target subject is or is not allowed one configured action on one resource right now, optionally on one concrete field. It answers with the single Rolebook decision for that target, including the rule trace and the structured condition record, redacted to a fixed shape. Inspection is off by default. Every call is bounded, rate limited by a limiter you supply, and recorded by an audit sink you supply before any detail is returned. The answer is an explanation for a person to read, **never a permission**: authorize with [`authorize()`](/docs/sharing/reads#authorize). `explain` is on `TenantSharing`, and it is also served over HTTP by `@rolebook/server` and called by `@rolebook/client` and the Python SDK; see [Over HTTP](#over-http). ## Enabling inspection [#enabling-inspection] Pass `inspection: { audit, limiter }` to `createSharing()` or `createVersionedSharing()`: ```ts prelude=sharing group=inspection import { createSharing, type InspectionAuditEvent, type InspectionAuditSink, type InspectionLimiter, } from "@rolebook/sharing"; // Your own token buckets and append-only log: Rolebook ships neither. declare const buckets: { take(key: string, signal: AbortSignal): Promise; done(key: string): void; }; declare const inspectionLog: { // Inserts keyed by event.inspectionId; inserting the same ID again is a no-op. insertOnce(event: InspectionAuditEvent, signal: AbortSignal): Promise; }; const limiter: InspectionLimiter = { // Called before Rolebook loads anything: apply tenant and actor limits here. async acquire({ tenantId, actor, signal }) { const actorKey = JSON.stringify([tenantId, actor.type, actor.id]); if (!(await buckets.take(tenantId, signal)) || !(await buckets.take(actorKey, signal))) { return { allowed: false }; } return { allowed: true, release: () => buckets.done(actorKey) }; }, }; const audit: InspectionAuditSink = { // Resolve only once the event is durably recorded. async append(event, { signal }) { await inspectionLog.insertOnce(event, signal); }, }; const inspecting = createSharing({ definition, identity, invitationTokens, inspection: { audit, limiter }, }); inspecting.inspectionEnabled; // true ``` - Without `inspection`, every `explain()` call answers `INSPECTION_DISABLED` before it looks at its input, and `inspectionEnabled` is `false`. - With a valid configuration, `inspectionEnabled` is `true`. It is fixed for the instance's lifetime. - When `inspection` is present but is not an object, or `audit.append` or `limiter.acquire` is not a function, `createSharing()` throws a `TypeError` and `createVersionedSharing()` rejects with one. - The hooks are captured once at construction and called as methods of the objects you passed. ## Calling `explain` [#calling-explain] ```ts group=inspection const support = { type: "user", id: "support_1" } as const; const customer = { type: "user", id: "user_789" } as const; const result = await inspecting .forTenant({ tenantId, actor: support }) .explain({ resource: { type: "project", id: projectId }, action: "read", subject: customer }); if (result.ok) { const { decision, policyDigest, sharingRevision, evaluatedAt } = result.explanation; console.log(decision.allowed, decision.code, decision.matched?.role); } else { console.log(result.code); // for example "NOT_FOUND_OR_DENIED" or "RATE_LIMITED" } ``` The inspector is the actor the tenant handle is bound to. `subject` is the target whose decision is explained; leave it out to explain the inspector's own decision. ## Who may inspect [#who-may-inspect] The inspector must be allowed the resource type's `management.inspect` permission, which defaults to `management.members` (see [`defineSharing`](/docs/sharing/setup#definesharing)). It is the same permission that gates `describeAccess()` and `auditHistory()`. - The permission is selected once from the configuration and checked once, resource-wide (with no field), on the inspector's own binding. - There is no fallback: when an explicit `inspect` permission is denied, `members` is not tried. - Any valid answer other than `ALLOWED` (an explicit deny, no grant, or a fault in the inspector's own assignments, such as an unknown role) is `NOT_FOUND_OR_DENIED`. - A group can be neither the inspector nor the target. ## The request [#the-request] The input is bounded declarative data. It must be a plain object whose own enumerable data properties are exactly: | Key | Required | Value | | --- | --- | --- | | `resource` | yes | `{ type, id }` with no other key: a configured resource type and an opaque ID. | | `action` | yes | A configured action label of that resource type. | | `subject` | no | `{ type, id }` with no other key. Defaults to the bound actor. | | `field` | no | One concrete Core field path: at most 512 characters and 16 dot-separated segments, each a letter followed by up to 127 letters, digits, `_`, or `-`. No wildcards, and no `__proto__`, `prototype`, or `constructor` segment. | Anything else is `INVALID_REQUEST`, including: - an unknown key, a symbol key, an accessor, or a non-enumerable property; - an optional key present with the value `undefined`; - an array, number, boolean, or `null` anywhere in the input, or an object with a non-plain prototype; - a Proxy whose trap throws; - more than 8 KiB of serialized UTF-8 JSON, more than 32 values (objects and strings, the request itself included), or nesting deeper than 4 levels (the request object is level 1); - an unknown resource type or action, or a malformed field. A valid field that no rule allows is an explained denial, not `INVALID_REQUEST`. The caller cannot supply context, assignments, groups, a timestamp, a revision, or a policy selection: every input to the decision is read from your adapters. ## What happens, in order [#what-happens-in-order] The stages always run in this order, and each failure stops the call with one fixed code: 1. **Enabled check.** Without an `inspection` configuration: `INSPECTION_DISABLED`. The deadline starts right after this check. 2. **Capture and validation.** The input is copied once into a frozen request and validated against the resource catalog: `INVALID_REQUEST`. A handle bound to a malformed tenant or actor ID answers `NOT_FOUND_OR_DENIED` here. 3. **Inspection ID.** 128 fresh random bits. 4. **Instance slot.** One of the instance's 32 inspection slots, or `RATE_LIMITED`. 5. **Host limiter.** `limiter.acquire()`, or `RATE_LIMITED`. 6. **Runtime, inspector, and resource.** One runtime is pinned for the call. The identity adapter resolves the inspector, and the storage adapter reads the resource once, with every membership. That frozen state serves both the inspector's and the target's bindings. 7. **One clock reading.** The sharing clock is read once, after the resource and the inspector are captured. Both bindings decide membership expiry at that instant. 8. **Inspection permission.** The check described in [who may inspect](#who-may-inspect). 9. **Target.** Only now is the target resolved. Nothing about it is read before the inspector is authorized, and when it is the inspector, the frozen inspector principal is reused. 10. **One evaluation.** The target is evaluated exactly once, with Core `explain(request, { detail: "conditions" })`. `allowed`, `code`, and `matched` come from that one result, so without a `field` they match the Rolebook decision `authorize()` would reach for the target over the same state. 11. **Serialization.** The explanation is projected onto the redacted envelope. 12. **Audit.** `audit.append()` is called once, and the answer waits for it. ## The explanation [#the-explanation] A success is `{ ok: true, code: "EXPLAINED", explanation }`, deeply frozen. `explanation` is an [`InspectionEnvelope`](/docs/sharing/api#inspectionenvelope): | Field | Meaning | | --- | --- | | `schema`, `version`, `mode` | `"rolebook-inspection"`, `1`, `"current-state"`. | | `inspectionId` | 128 random bits as 32 lowercase hex characters, new for every attempt. The audit event carries the same ID. | | `evaluatedAt` | Unix milliseconds of the single sharing-clock reading. | | `resource`, `target`, `action`, `field?` | The validated request. `target` is the bound actor when `subject` was left out. | | `sharingRevision` | The opaque sharing revision the resource state was read at. | | `policyVersion?` | The runtime's evaluation version, present on a [versioned](/docs/sharing/versioned) instance. | | `policyDigest` | SHA-256 of the UTF-8 `canonicalPolicyJson` of the effective policy (custom roles included), as 64 lowercase hex characters. | | `redactionVersion` | `1`. | | `capture` | `{ consistency: "captured-inputs" }`; see [what it does not guarantee](#what-an-explanation-does-not-guarantee). | | `decision` | `allowed`, `code`, `permission`, `matched?`, `trace`, `traceTruncated`, `conditionTraceTruncated`. | `decision.code` is `ALLOWED`, `EXPLICIT_DENY`, or `NOT_GRANTED`. Each `trace` entry is `{ outcome, effect, role, permission, via?, details }`, and `details` is Core's `DecisionTraceDetails` unchanged: the rule ID, the rule's reason code, and the structured condition record with its logical operators, partial trees, skipped children, and truncation flags exactly as Core returned them. See [decisions](/docs/decisions) for how to read a Core trace. Rule IDs are local to `policyDigest`, not durable grant IDs. ### What is redacted [#what-is-redacted] The envelope is built from exact key lists, so nothing else can pass through: - Core's free-text `reason` fields are dropped. - Nothing in the envelope or the audit event carries a `where` literal, a field-pattern list, subject or resource attributes, context, an assignment list, an email, a token, or exception text. - When the serialized `EXPLAINED` result would exceed 2 MiB, the answer is `INSPECTION_UNAVAILABLE`, never a shortened trace. The size never changes the decision. ## Errors [#errors] A failure is `{ ok: false, code }` with no message, cause, or partial trace. | `code` | When | | --- | --- | | `INVALID_REQUEST` | The input is not the exact bounded shape above, names an unknown resource type or action, or has a malformed field. | | `INSPECTION_DISABLED` | The instance has no `inspection` configuration. | | `NOT_FOUND_OR_DENIED` | The resource is missing or in another tenant, the inspector is absent or ineligible, the bound context is malformed, the inspector's own stored membership can no longer be bound (for example a retired custom role), or the inspector is not allowed the inspection permission. | | `TARGET_UNAVAILABLE` | The inspector was authorized, but the identity adapter reports the target absent or `eligible: false`. | | `RATE_LIMITED` | The limiter answered `{ allowed: false }`, or 32 inspections are already running on this instance (the limiter is not called then). | | `INSPECTION_UNAVAILABLE` | Any operational fault: see below. | `NOT_FOUND_OR_DENIED` is one answer for every one of its causes. An inspector who is not allowed the inspection permission gets it whether or not the resource exists, so it reveals nothing, not even existence. `INSPECTION_UNAVAILABLE` covers: - a limiter, identity, storage, or policy-store callback that throws, rejects, or returns a malformed result, including a limiter answer that is not exactly one of the two shapes; - a principal, inspector or target, that resolves as another subject, in another tenant, or as a group; - a resource state with a membership that does not decode (the module never evaluates a partial list); - an invalid Core binding or decision code for the target (never reported as a denial), an inspector check whose answer is outside Core's contract or whose binding throws, or Core's internal fault reporter firing; - a failing random source or clock; - the 2 MiB ceiling; - the 5,000 ms deadline, or a deadline timer that cannot be scheduled; - an audit append that throws, rejects, does not return a promise, or resolves after the deadline. ## The limiter [#the-limiter] `limiter.acquire({ tenantId, actor, inspectionId, signal })` is how the host rate limits inspection. Rolebook enforces no rate of its own. - It runs after the request is validated and an instance slot is taken, and before any runtime, identity, storage, or target load. It is not called for `INVALID_REQUEST`, `INSPECTION_DISABLED`, a malformed bound context, or a full instance. - `actor` is the bound inspector, not yet authorized, so the limiter also counts attempts that will be denied. Apply both a tenant limit and an actor limit. - It must answer exactly `{ allowed: false }` or `{ allowed: true, release }`: a plain object whose only own properties are those enumerable data properties, with `release` a function. Anything else, a throw, or a rejection is `INSPECTION_UNAVAILABLE`. - `release` is called exactly once, as a method of that result, when the call's work settles. That includes a lease granted after the deadline already answered the caller. It may return a promise; a throw or rejection is contained and never changes the result. - `signal` aborts when the deadline passes. A reasonable starting point is a token bucket of 20 attempts per minute per actor and 100 per minute per tenant, with bursts of the same size. A deployment with several instances needs a shared limiter, or must state that its limits are per instance. ## The audit sink [#the-audit-sink] After the inspector is authorized, and only while the deadline remains, `audit.append(event, { signal })` is called exactly once: for an explanation, and also when the target turns out unavailable or the evaluation fails. No detail is returned until it resolves, and the library never appends again for that call. - `append` must record the event durably, and idempotently by `inspectionId`, before it resolves. - A rejected, throwing, or late append, or one that does not return a promise, is `INSPECTION_UNAVAILABLE`. - An append can commit after its deadline has passed, so deduplicate by `inspectionId`. Callers should not retry automatically. - Attempts that end before the inspector is authorized (`INVALID_REQUEST`, `INSPECTION_DISABLED`, `RATE_LIMITED`, `NOT_FOUND_OR_DENIED`, and faults before authorization) produce no event, and neither does an authorized attempt whose deadline passes before the append. Log denials in your own security channel if you need them. The event is an [`InspectionAuditEvent`](/docs/sharing/api#inspectionauditevent): | Field | Value | | --- | --- | | `schema`, `version` | `"rolebook-inspection-audit"`, `1`. | | `inspectionId` | The attempt's ID, as in the envelope. | | `tenantId`, `actor` | The bound tenant and inspector. | | `resource`, `target`, `action`, `field?` | The validated request. | | `evaluatedAt` | The single sharing-clock reading. | | `outcome` | `"explained"`, `"target_unavailable"`, or `"unavailable"`. | | `allowed?`, `decisionCode?` | The target decision's `allowed` and `code`, only when `outcome` is `"explained"`. | | `policyDigest?` | The effective policy digest. Optional in the type; the current implementation includes it on every event. | | `redactionVersion` | `1`. | The event never carries a trace, a fact, or a literal. ## Concurrency and the deadline [#concurrency-and-the-deadline] - One instance runs at most 32 inspections at once, shared by every `forTenant` handle and, on a versioned instance, across policy refreshes. A call beyond that is `RATE_LIMITED` without calling the limiter. - Each call has a 5,000 ms monotonic deadline that starts right after the enabled check. It is checked after the synchronous capture and after every awaited stage. Once it has passed, no further stage starts and the call answers `INSPECTION_UNAVAILABLE`. A deadline timer also answers the caller when it fires, and from then on no stage starts, even if the monotonic clock has not yet reached 5,000 ms. - The `signal` given to the limiter and the audit sink aborts at the deadline. Identity and storage reads take no signal and are not cancelled. - A call keeps its slot until its pending stage and its `release` settle, even after the caller has been answered. A hook that ignores the abort therefore holds its slot, and 32 abandoned calls make further calls `RATE_LIMITED` rather than piling up. - A synchronous Proxy trap or callback can still block the event loop, so the deadline is not a hard real-time bound. ## What an explanation does not guarantee [#what-an-explanation-does-not-guarantee] - **`captured-inputs` is not a snapshot.** The identity, policy, and storage reads happen one after another, each authoritative on its own, and their immutable combination is evaluated once. It is not a transaction-wide snapshot, not a freshness token, and not a guarantee that the decision still holds when the response arrives. Providers can change independently between reads, and a versioned instance keeps its existing [refresh bounds](/docs/sharing/versioned). A later call reloads everything, so it sees a revocation. - **It is never a permission.** Do not use an explanation to authorize anything, and do not cache it as a decision. Call `authorize()` for that. - **The digest identifies the policy, nothing else.** `policyDigest` names the effective policy snapshot that was evaluated. It proves nothing about the facts your adapters supplied or about your identity and storage providers. ## Over HTTP [#over-http] [`@rolebook/server`](/docs/http-api/server) serves `explain` as `POST {basePath}/v1/sharing.explain`. It is enabled only when the root's `inspectionEnabled` is `true` when the handler is created, which is the case for an instance created with `inspection`. The body is exactly the `explain` input; the tenant and the inspector come from the server's `getContext`, never from the body, and any other body key is refused. | Library result | HTTP status | Body | | --- | --- | --- | | `EXPLAINED` | 200 | `{ "ok": true, "code": "EXPLAINED", "explanation": { ... } }`, exactly as returned | | `INVALID_REQUEST` | 400 | `{ "error": { "code": "INVALID_REQUEST", "message": "Invalid request" } }` | | `INSPECTION_DISABLED`, `NOT_FOUND_OR_DENIED`, `TARGET_UNAVAILABLE` | 404 | `{ "error": { "code": "NOT_FOUND_OR_DENIED", "message": "Not found or denied" } }` | | `RATE_LIMITED` | 429 | `{ "error": { "code": "RATE_LIMITED", "message": "Rate limited" } }` | | `INSPECTION_UNAVAILABLE`, or anything thrown | 503 | `{ "error": { "code": "INSPECTION_UNAVAILABLE", "message": "Inspection unavailable" } }` | - A disabled server, a private denial, and an unavailable target are one identical 404: status, body, and headers. A disabled server answers it without reading the body and without calling the limiter, the audit sink, or `explain`. - The body may be at most 8 KiB; a longer one is the ordinary 413 `PAYLOAD_TOO_LARGE`, decided while reading and before parsing. - Every response of the operation carries `Cache-Control: no-store`. No body, query, or exception text is logged or echoed. [`@rolebook/client`](/docs/http-api/client#inspection) has `explain(input)`, and the Python SDK has `client.explain(resource, action, subject=..., field=...)`. Both return the narrowed [`HttpInspectionResult`](/docs/http-api/http#httpinspectionresult): the explanation, or `{ ok: false, code }` with `INVALID_REQUEST`, `NOT_FOUND_OR_DENIED`, `RATE_LIMITED`, or `INSPECTION_UNAVAILABLE`. Any other response, including a 404 or 200 body that is not exactly the contract, raises the client's ordinary error, and neither client retries an inspection. The Go and Rust SDKs do not call `sharing.explain` yet. ## Hand-built `TenantSharing` objects [#hand-built-tenantsharing-objects] `explain` is a required member of [`TenantSharing`](/docs/sharing/api#tenantsharing). Code that builds a `TenantSharing` object by hand, such as a wrapper or a test double, instead of getting one from `forTenant()` must add it and decide what it does: - forward explicitly to the same bound tenant: `explain: (input) => tenant.explain(input)`; - or deliberately disable it: `explain: async () => ({ ok: false, code: "INSPECTION_DISABLED" })`. In a security-sensitive wrapper, list the methods it exposes one by one rather than spreading the tenant object, so a method added later is not exposed before someone has reviewed it. Code that needs only a few operations should depend on a narrower type, for example `Pick, "authorize">`. The required method makes such objects complete; it is not the security boundary. That remains the `inspection` configuration, the permission check, the limiter and the audit sink. # Listing accessible resources (/docs/sharing/listing) > listAccessible() and listAccess(), consistent pages and what they require, sealed cursors, candidate pre-filters, and listing errors. `listAccessible({ type, action, limit, cursor })` returns the resources Rolebook allows the actor to act on, a page at a time: ```ts prelude=sharing import type { AccessibleResource } from "@rolebook/sharing"; const visible: AccessibleResource<"project">[] = []; let cursor: string | undefined; for (;;) { const page = await tenant.listAccessible({ type: "project", action: "read", limit: 50, ...(cursor === undefined ? {} : { cursor }), }); visible.push(...page.resources); // each: { resource: { type, id }, snapshot } if (page.exhausted || page.nextCursor === undefined) break; cursor = page.nextCursor; } ``` [`listAccess({ type, limit, cursor })`](#everything-the-actor-can-do-by-type) lists the resources on which the actor may do at least one thing, with every action's decision. Both calls read each page the same way, with the same guarantee, bounds, and errors; this page describes them together and then what differs. ## Pages can be empty and not exhausted [#pages-can-be-empty-and-not-exhausted] The storage adapter returns **candidates**, not decisions: resources the actor owns or is a member of (directly or through a team), resources named by resource-scoped assignments, and, when workspace assignments could grant the action, every tenant resource. The module hydrates the candidates in batches inside the page's snapshot and confirms every one with Rolebook, so a deny or a false condition never becomes a false allow. A bounded scan can therefore produce an **empty, non-exhausted** page when it reached only denied candidates. Continue with `nextCursor` until `exhausted` is `true`; only then does an empty result mean no more accessible resources remain. `limit` is an integer from 1 to 100. Each `listAccessible()` item carries the resource key and the trusted snapshot Rolebook decided on. On a [versioned instance](/docs/sharing/versioned) the page also carries the `policyVersion` it was decided under. ## What one page guarantees [#what-one-page-guarantees] Every page is read at one coherent point. A returned page is the canonical evaluation of a state that existed, in five respects: - **Candidates, including their absence.** The candidate reads and the hydration reads see one snapshot, so the returned entries, an empty page, `exhausted`, and the position `nextCursor` continues from are all facts of that snapshot. A change committed after the snapshot was taken does not alter the open page: a resource created afterwards is not in it, a resource deleted afterwards is still listed as it was, and a resource deleted and re-created under the same ID appears as the original. The next page sees the change. - **Identity and eligibility.** The actor's complete principal (eligibility, subject attributes, assignments, groups, and authorization facts) and the storage adapter's own tenant-eligibility answer belong to the same point as the data. - **Resource and sharing state.** Each examined resource's snapshot, ownership, and the memberships of the actor and its groups come from the snapshot. A candidate that is missing, duplicated, in another tenant, or undecodable inside it is corrupt data and refuses the page; it is never skipped. - **Policy.** One policy runtime decides the whole page. A versioned instance reads the active policy version and the tenant's custom roles inside the page's snapshot and decides under exactly that state. - **One evaluation time.** The page has one instant, `evaluatedAt`, read from the storage adapter's clock no later than the snapshot. Every membership and identity expiry of the page is compared with it, in SQL and in Rolebook alike. The sharing module's own `clock` is not used for a page. Before a page is returned it is **sealed**: the adapter reads its clock once more and checks that no expiry the page depended on has passed in the meantime. That covers every live membership projected for the actor and its groups on every examined resource, grants and denies alike, and every expiry the identity and eligibility evidence declared. A page whose dependency expired before the seal is not returned. A page that cannot be established this way rejects with [`AccessListingUnavailableError`](#when-no-consistent-page-can-be-read). There is no partial page and no fallback to a weaker read. The guarantee covers one page and ends when the page is sealed: - It is not a frozen traversal. Every call opens a fresh snapshot, and a cursor records only a position. With nothing changing between pages, a full traversal returns each qualifying resource exactly once; a resource gained, lost, or changed between pages may be missed or returned at its new state, never twice. - It is not kept fresh until your code acts on it. Access can change after the page returns, so a later read needs its own fresh check, and a listing is never authorization for a write. A check made before a write, whether a listing or a separate `authorize()` call, can be out of date when the write commits. Decide a write inside the transaction that performs it, with a [protected write](/docs/sharing-postgres/protected-updates), which reads the authoritative facts and commits the decision with the change. ## What a consistent page requires [#what-a-consistent-page-requires] Consistent pages depend on how the storage adapter and the identity adapter are configured. A configuration that cannot provide them is refused with a reason; it does not degrade. ### Storage [#storage] | Adapter | A page is | Requires | | --- | --- | --- | | In-memory | A copy of the tenant's resources taken in one synchronous turn, with the adapter clock | Nothing further for storage. See the identity and eligibility notes below. | | PostgreSQL | One `SERIALIZABLE READ ONLY` transaction on one connection | The adapter is built on the checked [`createPgExecutor(pool)`](/docs/sharing-postgres/api#createpgexecutor) executor, and the tenant and resource ID columns are `text`. | | SQLite | A read-only transaction on one worker connection over a file-backed WAL database | The adapter is built on the worker-backed [`createBunSqliteQueryExecutor()`](/docs/sharing-sqlite/api#createbunsqlitequeryexecutor) executor (Bun only). | These executors are recognized by provenance: the adapter checks that its executor is the object the named factory returned, not that it has the right shape. Any other executor answers `capability_missing`, including an executor you built yourself or wrapped, and the executors from `@rolebook/sharing-sqlite/bun` and `/libsql`, which do not supply the page snapshot. A PostgreSQL adapter with non-`text` tenant or resource ID columns answers the same. A custom [`SharingAdapter`](/docs/sharing/api#sharingadapter) provides pages by implementing the optional `runConsistentPage`; without it every listing answers `capability_missing`. These are the requirements of listing only. Other operations have their own documented executor and configuration requirements; [named authorized queries](/docs/sharing/authorized-queries) and [protected writes](/docs/sharing-postgres/protected-updates), for example, also require specific executors. ### Tenant eligibility [#tenant-eligibility] Every ordinary read fences the actor through the adapter's eligibility fence. A page proves the same authority inside its snapshot, read without locks and judged at `evaluatedAt`, together with every instant at which that answer could change on its own. - The first-party fences carry this evidence themselves: `createPostgresMembershipEligibilityFence` and `createPostgresLocalIdentityProjection().lockEligibleSubjects`, and their SQLite counterparts. They are recognized by provenance, so a function of your own that wraps one of them counts as a custom fence. - A custom `lockEligibleSubjects` needs a matching `readEligibleSubjects` on the adapter. It returns `{ eligible, expiryDependencies }` from the same authoritative rows, through the executor it is given, and must not lock or write. Without it every page answers `identity_evidence_missing`: a boolean fence does not say what time its answer depends on. Instants are ISO 8601 UTC with three fractional digits; the PostgreSQL adapter also accepts six. See the [PostgreSQL](/docs/sharing-postgres/api#postgreseligibilityreader) and [SQLite](/docs/sharing-sqlite/api#sqliteeligibilityreader) readers. - The in-memory adapter follows the same rule: when `fenceEligibleSubjects` is configured, configure `readEligibleSubjects` as well. It answers synchronously. Only `eligible: true` keeps the actor eligible. An actor the eligibility authority refuses receives an empty exhausted page, exactly as `authorize()` would deny it, whatever the identity adapter says. ### Identity [#identity] The actor's principal must demonstrably belong to the page's point. There are three ways to supply that evidence, and an identity adapter that offers none of them answers `identity_evidence_missing`. Do not assume that an identity adapter qualifies because it works for `authorize()`. The identity adapters in `@rolebook/sharing-better-auth`, `@rolebook/sharing-clerk` and `@rolebook/sharing-workos`, and a `withTeams()` wrapper from `@rolebook/teams`, offer no page method. To list, replace such an identity with one that answers exclusively from a local projection complete for everything it returns (with teams, every team fact too), and name that identity in `pageIdentity`. Naming the provider-backed identity, or `withTeams()` over it, beside a synchronized copy does not qualify: the attestation is that the named identity reads the projection and nothing else. The team fences from `@rolebook/teams` carry no `readEligibleSubjects` either, and adding one is not enough on its own; see [Teams](/docs/teams). **A local projection read inside the page (PostgreSQL and SQLite).** Keep the identity facts in a projection table in the same database, and tell the adapter which identity adapter answers from it: ```ts title="listing-identity.ts" group=page-identity import type { TenantIdentityAdapter } from "@rolebook/sharing"; import { createPostgresLocalIdentityProjection, createPostgresSharingAdapter, type ParameterizedSqlExecutor, type PostgresResourceDescriptor, } from "@rolebook/sharing-postgres"; declare const executor: ParameterizedSqlExecutor; // from createPgExecutor(pool) declare const projectTable: PostgresResourceDescriptor; // Your recipient matching, as for any identity adapter. declare const matchesInvitationRecipient: TenantIdentityAdapter["matchesInvitationRecipient"]; const projection = createPostgresLocalIdentityProjection({ table: ["app", "identity_projection"] }); // The identity adapter the sharing instance is created with. It answers from the projection only. export const identity: TenantIdentityAdapter = { async resolvePrincipal(input) { const resolved = await projection.identity.resolvePrincipalInTransaction({ executor, ...input }); return resolved.principal; }, matchesInvitationRecipient, }; export const projectAdapter = createPostgresSharingAdapter({ executor, resource: projectTable, lockEligibleSubjects: projection.lockEligibleSubjects, revalidateAuthorizationFacts: projection.revalidateAuthorizationFacts, // Attests that `identity` answers from exactly this projection. pageIdentity: { source: identity, resolver: projection.identity }, }); ``` `pageIdentity.source` must be the same object you pass to `createSharing({ identity })`; Rolebook compares object identity, so a copy or a wrapper does not match. Supplying it is your attestation that the adapter answers from that projection and nothing else: Rolebook reads the projection row inside the page and does not consult a remote provider behind it. The projection's `revision` must advance on every change to the row. The SQLite adapter takes the same option with `createSqliteLocalIdentityProjection()`. See [`PostgresPageIdentity`](/docs/sharing-postgres/api#postgrespageidentity) and [`SqlitePageIdentity`](/docs/sharing-sqlite/api#sqlitepageidentity). **Bracketed evidence from an external source.** An identity adapter whose source is outside the database implements `resolvePagePrincipal({ tenantId, subject })`. Rolebook calls it once before the snapshot opens and once after the page was read, and accepts the page only when both answers are identical. It returns the complete principal with: - `revision`: a value that never repeats within its `epoch` and changes on every relevant change, including a change that is later restored and a set going from empty to non-empty; - `epoch`: a value that changes whenever the provider's store is restored or re-created, so a restored store never reissues a pair that was already observed; - `expiryDependencies`: the expiry of every time-sensitive fact, as ISO 8601 UTC instants with exactly three fractional digits. At most 1,024. Timestamps, ETags, and "the two reads returned equal values" are not substitutes. Implement this method only when the provider really has such a revision; a provider without one cannot supply consistent pages on its own and needs a local projection. **A synchronous capture (in-memory adapter).** With `createMemorySharingAdapter()`, the identity adapter implements `capturePagePrincipal({ tenantId, subject, evaluatedAt })` and returns `{ principal, expiryDependencies }` synchronously from in-process state, judged at `evaluatedAt`. It runs in the same turn as the adapter's copy, so it must not perform I/O, return a promise, or write. An in-memory setup may use `resolvePagePrincipal` instead. In every case the principal must be complete and plain data. Evidence that is malformed (a principal for another subject or tenant, a missing eligibility, an assignment naming a role the policy lacks, a subject attribute the engine refuses) answers `identity_evidence_missing`. A principal that holds a value that cannot be compared exactly, such as a function, a `Map`, a class instance, an accessor, or a cycle, answers `unrepresentable_identity`. Neither is ever turned into an empty page. A well-formed principal that is simply not eligible is an ordinary empty exhausted page. ### Versioned policy [#versioned-policy] A [versioned instance](/docs/sharing/versioned) decides each page under the policy stored in the page's own snapshot, never under its cached runtime. That needs the first-party policy store for the same backend, created on the **same executor object** as the resource adapter (or, in memory, the original `createMemoryPolicyStore()`). A wrapped or decorated policy store, or one on another executor, answers `policy_evidence_missing`. So does stored state the instance would refuse to load, including a generation or custom-role revision older than one this instance has already served, which indicates a restored store. ## Sealed cursors [#sealed-cursors] An adapter's raw position is usually the ID of the last candidate it scanned, which can be a resource the actor was denied. A listing never returns it: `nextCursor` is the position sealed with AES-256-GCM, and a caller's `cursor` is opened before any identity or storage callback runs. - Every listing cursor is a base64url string of the same length (398 characters today; accept up to 512), whatever the position. - A `listAccessible()` cursor is bound to the tenant, the actor, the resource type, the action, and the permission the action maps to. Presenting it for anything else, or presenting a malformed, truncated, tampered, or longer cursor, rejects with `InvalidCursorError` (`INVALID_CURSOR`), and nothing derived from it reaches the adapter. - A cursor carries a position only. It holds no snapshot, no policy version, and no expiry: the next call reads a fresh page from that position, under the policy active then. Treat cursors as opaque. - Each instance seals with its own random key unless you configure `listingCursorKey`. Configure a shared key to page across processes, instances, restarts, and deploys; see [secret keys](/docs/sharing/setup#secret-keys). ## Errors [#errors] A request the module cannot answer completely rejects instead of returning a page: | Error | `code` | Cause | | --- | --- | --- | | `AccessibleListingError` | `INVALID_LIMIT` | `limit` is not an integer from 1 to 100, or the request is not a plain object of own data properties. | | `AccessibleListingError` | `UNKNOWN_RESOURCE_TYPE` | `type` is not a configured resource type. | | `AccessibleListingError` | `UNKNOWN_ACTION` | `action` is not an action label configured for that type. `listAccessible()` only. | | `InvalidCursorError` | `INVALID_CURSOR` | `cursor` is not a sealed cursor this instance can open for the same call and scope. | | `AccessListingUnavailableError` | `ACCESS_LISTING_UNAVAILABLE` | No consistent page could be read. See below. | | `AccessibleListingError` | `TOO_MANY_ASSIGNMENTS` | The eligible principal has more than `MAX_CANDIDATE_HINT_SIZE` (256) assignments, so its candidate query cannot be complete. | | `InvalidCandidatePageError` | `INVALID_CANDIDATE_PAGE` | The adapter returned malformed output, or a non-exhausted page without a usable advancing cursor. An adapter contract failure. | Limit, type, action, and cursor are validated in that order before any identity or storage callback runs, so a malformed request fails the same way for every actor. `AccessibleListingError` and `InvalidCursorError` extend `RangeError`: map them to a 4xx response when an HTTP layer forwards client-supplied values. `InvalidCandidatePageError` is a `TypeError` from a faulty adapter; treat it as an application fault. On a versioned instance that already refuses to serve, a listing rejects with `PolicyUnavailableError` before any page opens, as its other operations do. `authorize()` is different: an unknown type or action there is the uniform `NOT_FOUND_OR_DENIED` decision. Two outcomes are pages, not errors. An actor who is not eligible in the tenant, a group named as the actor, and a context whose tenant or actor is not a valid ID all receive an empty exhausted page. ### When no consistent page can be read [#when-no-consistent-page-can-be-read] `AccessListingUnavailableError` has `code: "ACCESS_LISTING_UNAVAILABLE"` and a `reason`. The reason names a cause only; neither it nor the message contains a tenant, subject, resource ID, attribute, revision, or expiry value. | `reason` | Meaning | Retrying | | --- | --- | --- | | `capability_missing` | The adapter or its executor cannot read a page at one coherent point. | Not until the configuration is fixed. | | `identity_evidence_missing` | No in-snapshot or bracketed identity evidence, no eligibility evidence, or that evidence is malformed. | Not until the configuration or the data is fixed. | | `policy_evidence_missing` | Versioned policy state could not be read in the page's snapshot, or was refused. | Not until the configuration or the store is fixed. | | `unrepresentable_identity` | Every attempt resolved a principal that cannot be compared exactly. | Not until identity answers are plain data. | | `expiry_crossed` | An expiry the page depended on passed before the page was sealed. | A later call can succeed. | | `session_expired` | The attempt did not finish within its 2-second deadline. | A later call can succeed. | | `snapshot_unavailable` | The snapshot could not be opened or held, the adapter is at its concurrent-page limit, or examined data is corrupt. | A later call can succeed, unless stored data is corrupt. | | `changed` | Bracketed identity evidence changed while the page was read, or the database chose the page's transaction as a serialization victim. | A later call can succeed. | One call makes at most three attempts, each with its own snapshot and its own deadline. The first three reasons end the call at once, because another attempt in the same call cannot change them. The others are retried. When every attempt fails, the call reports `unrepresentable_identity` only if every attempt was unrepresentable; otherwise it reports the last attempt's reason, with `changed` in place of an unrepresentable last attempt. Treat the error as an inability to answer, never as "no access": ```ts prelude=sharing import { AccessListingUnavailableError } from "@rolebook/sharing"; try { const page = await tenant.listAccessible({ type: "project", action: "read", limit: 50 }); console.log(page.resources.length); } catch (error) { if (!(error instanceof AccessListingUnavailableError)) throw error; // Not an empty list. Show a retry affordance, and alert on the configuration reasons. console.warn(`listing unavailable: ${error.reason}`); } ``` ### Over HTTP [#over-http] [`sharing.listAccessible`](/docs/http-api) answers this refusal with HTTP 503 and a fixed body. It is an expected outcome and is not reported to `onInternalError`: ```json { "error": { "code": "ACCESS_LISTING_UNAVAILABLE", "message": "Access listing unavailable", "reason": "session_expired" } } ``` `reason` is one of the eight values above and appears with this code only. `@rolebook/client` throws its own [`AccessListingUnavailableError`](/docs/http-api/client#accesslistingunavailableerror) with `code` and `reason`. The Python client raises `AccessListingUnavailableError`, the Go client returns `*AccessListingUnavailableError`, and the Rust client returns `Error::AccessListingUnavailable`; those three carry the status, the reason, and the message. All four refuse a response that pairs a `reason` with another code, or this code with no reason, as an unexpected response. `listAccess()` is a library call and has no HTTP operation. ## Bounds [#bounds] | Bound | Value | | --- | --- | | `limit` | 1 to 100 | | Candidates examined for one page | At most 2,000 | | Resources hydrated in one batch | At most 200 (`MAX_ACCESS_BATCH_SIZE`) | | Attempts in one call | At most 3 | | Deadline of one attempt | 2 seconds | | Page attempts open at once on one adapter instance | 32; one more answers `snapshot_unavailable` | | Identity expiry dependencies in one resolution | 1,024 | The deadline applies to each attempt, not to the call. It starts before the attempt's first evidence read, which for bracketed identity is the first `resolvePagePrincipal` call, and covers the snapshot, every read, the seal, and the commit. An attempt that cannot finish inside it is `session_expired`, never a shorter page, and a call can spend up to three such attempts. When denials are expected, the first batch asks for four times the limit, at least 20 and at most 200 candidates, and each further batch doubles up to 200. A scan that is mostly denied therefore reaches the 2,000-candidate bound in fewer reads than fixed small batches would need. This reduces round trips; it does not promise that a page finishes in time, and a scan that outlasts the deadline is refused. A plan that expects every candidate to be allowed asks only for what the page still needs. Batch size never changes which resources a successful page returns or where its cursor points. Because a larger batch hydrates and seals candidates beyond the last one returned, a corrupt or expiring row there can refuse a page that a smaller batch would not have reached. An open attempt holds one pooled connection and its snapshot on PostgreSQL, and one worker connection and its WAL snapshot on SQLite. Its slot among the 32 stays occupied until those resources have actually been released or discarded, which can be later than the deadline when a connection or a worker is slow to settle. Size the pool or `maxConnections` for the attempts you expect to be open at once beside your other work, and expect `snapshot_unavailable` or `session_expired` when it is too small. The limits are fixed admission bounds, not performance figures: measure page latency for your own data and load. ## Pre-filters [#pre-filters] Candidate queries carry hints that only ever narrow the candidates: - `memberRoles`: the member-role labels whose policy role (or a role it inherits) has a field-free allow for the requested permission or its `type:*` wildcard. A membership with another label cannot grant the action, so the adapter may skip resources reached only through such rows. - On the tenant-wide path, only resources with an ownership row qualify. The same holds for a resource named by a resource-scoped assignment: an application row that was never initialized for sharing is not a candidate, and neither listing returns it. The hints read stored role labels and row existence, never conditions, attributes, ancestry, or clocks, so SQL never decides access: Rolebook still evaluates every candidate, and an adapter that ignores the hints stays correct. When an unconditional, deny-free workspace grant is expected to allow every tenant resource, the module asks only for the number of results the page still needs. Conditional workspace grants still page the whole tenant and can return empty, non-exhausted pages. Rolebook conditions are deliberately not compiled into a SQL predicate: such a compiler would be a second evaluator with different failure semantics. To filter and sort by your own resource columns, register [named authorized queries](/docs/sharing/authorized-queries) on the PostgreSQL or SQLite adapter instead. ## Everything the actor can do, by type [#everything-the-actor-can-do-by-type] `TenantSharing.listAccess({ type, limit, cursor })` lists the resources of one type on which the bound actor has at least one configured action allowed. Each entry is the `.permissions` payload [`permissions()`](/docs/sharing/reads#permissions) builds from the same evaluator inputs: every configured action, allowed or not, its decision, the `sharingRevision`, and on a versioned instance the `policyVersion` of the page. ```ts prelude=sharing let cursor: string | undefined; do { const page = await tenant.listAccess({ type: "project", limit: 50, ...(cursor === undefined ? {} : { cursor }), }); for (const { resource, allowed } of page.resources) console.log(resource.id, allowed); cursor = page.nextCursor; } while (cursor !== undefined); ``` How it differs from `listAccessible({ type, action })`: - `listAccessible` answers one action. A resource on which only `comment` is allowed is not in `listAccessible({ action: "read" })`, and is in `listAccess`. - `listAccess` returns every action's decision for each resource, not the trusted snapshot. - Its cursor is sealed under its own label and bound to the tenant, the actor, and the type. A `listAccessible()` cursor given to `listAccess()`, or the reverse, rejects with `INVALID_CURSOR`, as does one from another tenant, actor, or type. - It has no `action`, so it never answers `UNKNOWN_ACTION`. Everything else is shared: the same order, the same [page guarantee](#what-one-page-guarantees) and [requirements](#what-a-consistent-page-requires), the same [bounds](#bounds), empty non-exhausted pages, the same errors, and an empty exhausted page for an ineligible actor. Candidates come from the union of the hints `listAccessible()` would use for each configured action, a superset filter only: every entry comes from the evaluation `permissions()` performs, and a resource with no allowed action is never returned. Each entry deep-equals the `.permissions` payload of `permissions()` for the same state and evaluation time. Across backends, compare the listed resources, `allowed` maps, and decision codes; a decision's `matched` attribution can follow membership order. The two calls can still differ in outcome when the evidence for a page is missing or cannot be represented: `permissions()` reads one resource without a page, so it can decide where `listAccess()` answers `AccessListingUnavailableError`. An empty page has no entry to carry a policy version, and an entry's version names the policy the page was decided under. `listAccess()` answers only for the bound actor. It is not a "who can access this resource" query and not a "what can this other person access" query. `listAccess` is a required member of [`TenantSharing`](/docs/sharing/api#tenantsharing). A `TenantSharing` built by hand, such as a wrapper or a test double, must add it and decide what it does, normally forwarding to the same bound tenant: `listAccess: (input) => tenant.listAccess(input)`. A wrapper that should not expose it must make it fail, never answer it for another tenant or actor. # Bounded outbox delivery (/docs/sharing/outbox-delivery) > Run one bounded delivery pass with explicit sink outcomes and fenced settlement. A delivery worker claims one batch of committed protected-write events and invokes a sink you supply. It runs once and returns; it starts no daemon, scheduler or network service. The sink runs after the claim has released its database transaction and connection. Delivery is **at least once**: the sink must deduplicate effects by `(environmentId, eventId)`, including after cancellation or an uncertain acknowledgement. Use `createPostgresProtectedWriteDeliveryWorker` or `createSqliteProtectedWriteDeliveryWorker` with the same executor, journal prefix and environment as the protected-write adapter. Apply its explicit protected-write migrations first, including operator history. Authenticate and authorize worker/operator access in your application. The optional `{ type, id }` operator is copied at construction as application-attested attribution; omitting it records null, never an invented actor. ## Explicit sink policy [#explicit-sink-policy] ```ts import { createPostgresProtectedWriteDeliveryWorker, type ParameterizedSqlExecutor } from "@rolebook/sharing-postgres"; import type { OutboxDeliveryEvent } from "@rolebook/sharing"; declare const executor: ParameterizedSqlExecutor; // Your sink implements deduplication and decides whether an outcome is known. declare function send(event: OutboxDeliveryEvent, signal: AbortSignal): Promise<"accepted" | "try-later" | "rejected" | "unknown">; const worker = createPostgresProtectedWriteDeliveryWorker({ executor, tablePrefix: "app_authorization", environmentId: "production", operator: { type: "service", id: "audit-delivery" }, batchSize: 8, leaseMs: 30_000, deliveryTimeoutMs: 10_000, async deliver(event, { signal }) { const outcome = await send(event, signal); if (outcome === "accepted") return { status: "delivered" }; if (outcome === "try-later") return { status: "retry", delayMs: 5_000 }; if (outcome === "rejected") return { status: "quarantine", reason: "sink-rejected-event" }; return { status: "unresolved" }; }, }); const report = await worker.runOnce(); ``` The worker never guesses retry/quarantine policy. A thrown sink exception, malformed result or explicit `unresolved` result causes no ACK, retry or quarantine. You may catch a sink error inside `deliver` and explicitly classify it if your application can establish the appropriate outcome. Only `delivered` permits ACK. A successful quarantine writes the existing durable operator history; ordinary ACK and retry do not fabricate operator-action records. No payload or receipt is rewritten. For local SQLite, the facade and contract are the same on Bun SQLite and local libSQL: ```ts import { createSqliteProtectedWriteDeliveryWorker, type ParameterizedSqliteExecutor } from "@rolebook/sharing-sqlite"; import type { OutboxDeliverySink } from "@rolebook/sharing"; declare const executor: ParameterizedSqliteExecutor; declare const deliver: OutboxDeliverySink; const worker = createSqliteProtectedWriteDeliveryWorker({ executor, tablePrefix: "app_authorization", environmentId: "production", batchSize: 4, leaseMs: 30_000, deliveryTimeoutMs: 10_000, deliver, }); const cancellation = new AbortController(); const report = await worker.runOnce({ signal: cancellation.signal }); ``` ## Bounds and outcomes [#bounds-and-outcomes] `batchSize` is an integer 1–32, `leaseMs` is 1–300000, and `deliveryTimeoutMs` is 1–`leaseMs`. All options and callback/port function references are captured at construction. Each pass makes one claim call, admits at most `batchSize` concurrent sink calls, and returns outcomes in claim order. There is no refill, prefetch or lease renewal. Retry delay is an integer 0–300000; quarantine reason is a nonblank string of at most 1024 characters without NUL. Results must be plain data. Sink calls are concurrent; database settlements are serialized within the pass to avoid the worker's own SQLite transactions contending. Queue time contributes to lease age. Every settlement uses the original exact lease token once. A stale/expired token reports `stale`; no automatic retry follows a database failure. Separate worker instances need an application-wide concurrency policy. The frozen report contains `stopped` and bounded `outcomes`. Each outcome includes environment, event ID and original generation, plus `acknowledged`, `retried`, `quarantined`, `stale`, or `unresolved`. Unresolved reasons distinguish `sink-error`, `invalid-result`, `sink-unresolved`, `aborted`, `timeout` and `settlement-error`. Reports contain no raw exceptions or payloads, and the worker logs nothing. Claim failure throws a generic reconciliation error: leases may have committed before the response failed. An ambiguous ACK likewise reports uncertainty even if storage committed. Do not infer either delivery or rollback from missing evidence. ## Cancellation and late effects [#cancellation-and-late-effects] Pass an `AbortSignal` to `runOnce`. A pre-aborted call claims nothing. Abort during claim waits for the database call to finish, then starts no sinks. During delivery, abort or a callback timeout signals cooperative cancellation and prevents new sink starts and future queued settlements. An already-submitted database settlement is still observed and reported; cancellation does not undo it. Database operations remain subject to the executor's own limits, not the sink timeout. The pass can return while an uncooperative sink still runs. Late fulfillment/rejection is observed, but cannot cause a later settlement. The same worker remains busy until every started sink and submitted settlement actually finishes, and rejects overlapping runs before claiming. A permanently unsettled sink leaves that worker busy permanently. The helper cannot forcibly cancel an external effect. Unreconciled claims can become replayable after lease expiry; sink deduplication is essential. ## Worker diagnostics [#worker-diagnostics] Every delivery worker, from `createOutboxDeliveryWorker` or either SQL facade, has `diagnostics()`, a frozen snapshot of that worker instance: whether it is `idle`, `running` or `draining` (a returned pass left a sink running, so new runs are refused), how its last run ended, cumulative counts per outcome and unresolved reason, and the state of an optional observer. It is local evidence, not backlog, database, sink or global production health, and it contains no identifiers or text. ```ts import { createOutboxDeliveryWorker, type OutboxDeliveryPort, type OutboxDeliverySink } from "@rolebook/sharing"; declare const outbox: OutboxDeliveryPort; declare const deliver: OutboxDeliverySink; declare const metrics: { count(name: string, value: number): void }; const worker = createOutboxDeliveryWorker({ outbox, deliver, batchSize: 8, leaseMs: 30_000, deliveryTimeoutMs: 10_000, diagnostics: { // Enums and counts only; called after the run, one call at a time. observe(run) { metrics.count(`outbox.run.${run.result}`, 1); metrics.count("outbox.unresolved", run.unresolved); }, queueLimit: 64, observerTimeoutMs: 1_000, }, }); await worker.runOnce(); const { worker: state, delivery, observation } = worker.diagnostics(); ``` The observer receives only the observation and is called as a plain function, so bind a class method yourself. It never runs inside `runOnce`, and its return value does not control a run's outcome, admission or settlement; `runOnce` resolves and rejects exactly as it would without diagnostics. A throw, a rejection or a call that outlives `observerTimeoutMs` is counted; a synchronous call that overruns is counted once when it returns, because no timer can fire during it. The timeout only reports: there is no cancellation signal, and a timed-out call keeps the single observer slot until it settles, while new observations wait in a queue of `queueLimit` (oldest dropped and counted). A stuck observer therefore shows as `observation.status: "stalled"` while delivery keeps running. Return or yield promptly (hand the counts to a buffer and return): code in the same process cannot preempt synchronous CPU work, so a CPU-bound observer delays everything on its event loop, delivery included. `delivery: "attention"` means the last local run ended other than `completed`, or any claimed event was retried, quarantined, stale or unresolved. `clear` means the last run completed with every claimed event acknowledged, including an empty run; it does not establish global health. `observation.dropped`, `failed` and `timedOut` are lifetime totals that never reset; `status` returns to `healthy` after the next prompt, successful call. Option objects accept only `observe`, `queueLimit` and `observerTimeoutMs`; `null` and unknown keys throw at construction. The defaults (64 observations, 1,000 ms) are configuration choices, not performance claims. `createPostgresProtectedWriteDeliveryWorker` and `createSqliteProtectedWriteDeliveryWorker` accept the same `diagnostics` option and forward it unchanged. The shared `createOutboxDeliveryWorker` accepts an equivalent trusted storage port for composition. Its port must return immutable claim payloads and release claim transactions before resolving. The first-party facades meet that contract. This helper provides no tenant-user route, administrative UI, retention/deletion policy or durable log of failed sink attempts. # Authorize, permissions, and inspection (/docs/sharing/reads) > authorize(), permissions(), describeAccess(), and auditHistory(). ## `authorize` [#authorize] `authorize({ resource, action })` decides one configured action label for the actor: ```ts prelude=sharing const decision = await tenant.authorize({ resource: { type: "project", id: projectId }, action: "update" }); if (decision.allowed) { decision.decision.matched; // the Rolebook rule that allowed it } else if (decision.code === "FORBIDDEN") { decision.decision?.code; // the Rolebook denial, for a caller who knows the resource exists } ``` | `code` | Meaning | | --- | --- | | `ALLOWED` | Rolebook allowed it; `decision` is the Rolebook decision. | | `FORBIDDEN` | The actor has a relationship to the resource and Rolebook denied it; `decision` is usually present. | | `NOT_FOUND_OR_DENIED` | The resource is missing, the type or action is not configured, the actor is not an eligible member, or the actor has no relationship to the resource. No `decision`. | The module asks the storage adapter for the memberships of the actor and its groups only (`requestingPrincipals`), so an adapter need not load every member of a widely shared resource to answer. ## `permissions` [#permissions] `permissions({ resource })` decides every configured action of the resource in one read, for a page that would otherwise call `authorize()` once per button. It resolves the principal once, reads once with the same projection `authorize()` uses, binds once, and checks each action, so every entry equals the `authorize()` answer for that action at the same sharing revision and instant. ```ts prelude=sharing const result = await tenant.permissions({ resource: { type: "project", id: projectId } }); if (result.ok) { const { allowed, decisions, sharingRevision } = result.permissions; // allowed: { read: true, update: true, delete: false }, one entry per configured action label } ``` `allowed` holds one boolean per configured action label, in configuration order, as a frozen null-prototype record of plain data: send it to a front end and gate controls on it there. `decisions` holds the Rolebook decision behind each entry. When at least one action is allowed, every action is reported. When none is (and for a missing resource, an ineligible actor, an unconfigured type, or malformed input) the answer is `{ ok: false, code: "NOT_FOUND_OR_DENIED" }`. Expiry does not bump the sharing revision, so `sharingRevision` alone must not key a decision cache: a cached answer can outlive a membership that expired at the same revision. ## `describeAccess` [#describeaccess] `describeAccess({ resource })` answers a share dialog: the owner, every live membership (individuals and groups alike, each with its role label and optional `expiresAt`), and the pending invitations without their token digests. ```ts prelude=sharing const result = await tenant.describeAccess({ resource: { type: "project", id: projectId } }); if (result.ok) { const { owner, members, invitations, sharingRevision } = result.access; for (const member of members) console.log(member.subject, member.role, member.expiresAt); } ``` - It requires `management.inspect`, which defaults to `management.members`. - `invitations` is present only when the actor is also allowed `management.invitations`, so a members-only manager never learns who was invited. Pending means issued and neither consumed, revoked, nor expired. - Ownership and memberships come from one storage snapshot at `sharingRevision`; the invitations are a second read and may observe a later revision. - Groups keep their own subject type (`team` by default) and are not expanded; compare `subject.type` with your group type to label them. - A membership whose label names an unavailable custom role carries `roleUnavailable: true`. - Every refusal (a missing resource, an ineligible actor, an unconfigured type, an actor without `inspect`, adapter output that fails the module's capture) is `NOT_FOUND_OR_DENIED`. An adapter that meets a stored invitation row it cannot decode may throw its own row error instead. ## `auditHistory` [#audithistory] Every mutation commits an audit event in the same transaction. `auditHistory({ resource, limit, cursor })` pages them, newest first by `(occurredAt, id)`, for an actor allowed `management.inspect`: ```ts prelude=sharing let cursor: string | undefined; do { const result = await tenant.auditHistory({ resource: { type: "project", id: projectId }, limit: 50, ...(cursor === undefined ? {} : { cursor }), }); if (!result.ok) break; for (const event of result.page.events) console.log(event.occurredAt, event.action, event.actor); cursor = result.page.exhausted ? undefined : result.page.nextCursor; } while (cursor !== undefined); ``` - `limit` is an integer from 1 to `MAX_AUDIT_PAGE_LIMIT` (100). - Each event is a frozen `AuditHistoryEvent`: a `SharingAuditEvent` without the caller-chosen `idempotencyKey`. Actions are `member.granted`, `member.role_changed`, `member.revoked`, `ownership.transferred`, `invitation.issued`, `invitation.consumed`, `invitation.revoked`, `resource.initialized`, `resource.deleted`, and `resource.moved`. An invitation issued or consumed under a nested-team profile also carries `lineageDirect` and `lineageWitness`. Flat events omit both. - `nextCursor` is present until `exhausted`. Like a listing cursor it is the adapter's position sealed with AES-256-GCM from the same `listingCursorKey`, under its own label, so an audit cursor never opens as a listing cursor or the reverse. It is bound to the tenant, the actor, the resource type, and the resource ID, and is always 1,423 characters. - A cursor dies with the event it points after: draining the audit table, or deleting and re-creating the resource under the same ID, makes the next call throw `InvalidCursorError`. Restart from the first page. - History covers the resource's **current incarnation** only. Every initialization of a key mints an opaque incarnation identifier, kept across ownership transfers and moves; events are stamped with it, and only events of the live incarnation are listed. After a deletion and re-creation under the same ID, the new resource's inspectors never see the earlier actors, grantees, or invitation IDs. - A deleted resource's history is reachable only by draining the table. Every other refusal is `NOT_FOUND_OR_DENIED`. | Error | `code` | Cause | | --- | --- | --- | | `AuditHistoryError` | `INVALID_LIMIT` | `limit` is not an integer from 1 to 100, or the request is not a plain object of own data properties. | | `AuditHistoryError` | `UNKNOWN_RESOURCE_TYPE` | `resource.type` is not a configured resource type. | | `InvalidCursorError` | `INVALID_CURSOR` | `cursor` does not open as an audit cursor for the same tenant, actor, and resource under a key this instance holds. | | `InvalidCandidatePageError` | `INVALID_CANDIDATE_PAGE` | The adapter returned a malformed page; an adapter contract failure. | These checks run on the captured request before any identity or storage callback. The cursor is opened before the resource ID is checked, so a malformed resource ID passed with a cursor throws `InvalidCursorError`. `auditHistory()` is a read for activity panels and compliance views, not a delivery mechanism. To send audit events elsewhere, drain the adapter's audit table from a job of your own. # Retention and pruning (/docs/sharing/retention) > Pruning settled idempotency records and invitations with pruneSettledRecords(). Two kinds of sharing rows otherwise only grow: the idempotency record every committed mutation writes, and invitations once they are consumed, revoked, or expired. The memory, PostgreSQL, and SQLite adapters each offer `pruneSettledRecords()` (the `SettledRecordPruner` interface) to delete them in bounded batches. Audit rows, lifecycle idempotency records, and revision floors are never pruned: audit rows are the access history, and a pruned revision floor could let a re-created resource repeat old revisions. Pruning is maintenance, not a sharing operation: it runs no authorization, writes no audit event, bumps no sharing revision, and never changes who has access. Call it only from trusted server code, such as one scheduled job, never from a user request. It is not part of `SharingAdapter`, so a third-party adapter need not implement it. ```ts import { DEFAULT_IDEMPOTENCY_RETENTION_MS, DEFAULT_INVITATION_RETENTION_MS, type SettledRecordPruner, } from "@rolebook/sharing"; declare const adapter: SettledRecordPruner; // a memory, PostgreSQL, or SQLite sharing adapter declare const log: { info(message: string, fields: Record): void }; const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); // Drain one kind at a time, and pause between batches to spread the write load. const retention = { idempotency: DEFAULT_IDEMPOTENCY_RETENTION_MS, // 30 days: keep it longer than any client's retry window invitations: DEFAULT_INVITATION_RETENTION_MS, // 30 days: the retention the app owner chose }; for (const kind of ["invitations", "idempotency"] as const) { let result; do { result = await adapter.pruneSettledRecords({ scope: { allTenants: true }, // or { tenantId }; there is no implicit "all" ...(kind === "idempotency" ? { kinds: ["idempotency"], idempotencyRetentionMs: retention.idempotency } : { kinds: ["invitations"], invitationRetentionMs: retention.invitations }), limit: 500, }); log.info("rolebook prune", { kind, cutoffs: result.cutoffs, deleted: result.deleted }); if (!result.exhausted) await sleep(250); } while (!result.exhausted); } ``` Run exactly one such job, for example one daily scheduled task rather than a timer in every replica: concurrent runners pick the same oldest rows, so on PostgreSQL they collide and retry, and on SQLite they wait for each other. Alert when no run has succeeded for a couple of days. ## The request [#the-request] - Either pass neither `kinds` nor a retention, and both kinds are pruned at their 30-day defaults (`DEFAULT_IDEMPOTENCY_RETENTION_MS`, `DEFAULT_INVITATION_RETENTION_MS`), or name `kinds` (`["idempotency"]`, `["invitations"]`, or both) and give a retention for each named kind and no other. Nothing falls back to a default by accident: a retention without `kinds`, or a named kind without its retention, is `INVALID_INPUT`, and a retention for a kind `kinds` leaves out is `INVALID_RETENTION`. - `PruneSettledRecordsInput` is a union of those shapes (`PruneWithDefaultsInput`, `PruneIdempotencyInput`, `PruneInvitationsInput`, `PruneBothInput`), so TypeScript refuses the same mistakes. Build `kinds` per branch as above: a `SettledRecordKind[]` read from configuration does not match a branch. - `scope` is `{ tenantId }` or `{ allTenants: true }`. To leave a tenant out, for example one under legal hold, prune tenant by tenant from your own tenant list. Prune or erase an offboarded tenant's rows before removing it from that list. - `limit` (1 to `MAX_PRUNE_BATCH`, 1,000) bounds the rows deleted per kind in one call, oldest first. Loop until `exhausted`. - Retentions are at least one day (`MIN_IDEMPOTENCY_RETENTION_MS`, `MIN_INVITATION_RETENTION_MS`) and at most `MAX_RETENTION_MS` (100 years). The cutoff is the adapter's clock (the database clock on PostgreSQL unless a `clock` is configured) minus the retention; `result.cutoffs` reports it. - A pending invitation that has not expired is never deleted, whatever the retention. - An unknown key, or an optional key present but `undefined`, is `INVALID_INPUT` rather than ignored. A call it will not run throws before anything is deleted. A bad request throws `RetentionError` (a `RangeError` with `code` `INVALID_INPUT`, `INVALID_SCOPE`, `INVALID_LIMIT`, `INVALID_RETENTION`, or `RETENTION_TOO_SHORT`): map it to a client error. A database not ready to prune throws `RetentionSchemaError` (an `Error` with code `SCHEMA_NOT_UPGRADED`): the idempotency table predates its `created_at` column, has a `created_at` of the wrong type, lacks a valid index for pruning, or on PostgreSQL has no `DEFAULT now()`. Running the adapter's migrations fixes a missing column, index or default; a wrong column type must be repaired explicitly first (a rerun rejects that drift), and on PostgreSQL an `INVALID` index left by a failed `CREATE INDEX CONCURRENTLY` must be dropped first. Alert an operator. Pruning leaves no record of its own. Log every call's scope, cutoffs, and counts from the job if you need evidence of retention. The SQL adapters delete each kind in its own transaction, so a call can throw after its idempotency batch committed; the next call simply continues. ## What pruning changes [#what-pruning-changes] - **Idempotency.** A retry whose record was pruned is no longer recognized: it runs as a new command, re-authorized against current state. A grant retried after a later revocation grants again; an ownership transfer retried after a transfer back moves ownership again. Keep the retention longer than every client's retry window, offline outboxes included. After pruning, one idempotency key can name two commits in the audit rows. - **Invitations.** On `createSharing()`, a retried acceptance replays as `ALREADY_APPLIED` only while both its invitation and its idempotency record are kept, and answers `INVITATION_UNAVAILABLE` once either is pruned. An expired invitation answers `INVITATION_EXPIRED` while its row is kept and `INVITATION_UNAVAILABLE` after, so offer "ask for a new invitation" on both codes. `createVersionedSharing()` replays from the idempotency record alone. Invitation rows hold recipient email addresses, so the invitation retention is also a data retention decision. Pruning is not an erasure mechanism: a pending invitation keeps its address until it expires and its retention passes (revoke it and prune to remove it sooner), the `issueInvitation` idempotency record holds a keyed digest of the command including the email and follows the idempotency retention, and audit rows keep actor and subject identifiers and are never pruned. ## For adapter authors [#for-adapter-authors] `capturePruneSettledRecordsInput` (returns a `PruneSettledRecordsRequest`), `pruneCutoffs`, `pruneResult`, and `invitationSettledBefore` are exported so a custom adapter implements `SettledRecordPruner` with exactly the same validation and rules. See the [API reference](/docs/sharing/api#retention). # Define and create (/docs/sharing/setup) > The policy roles sharing needs, defineSharing, createSharing options, and secret keys. ## The policy [#the-policy] Sharing reads its roles and permissions from an ordinary Rolebook policy. For each shareable resource type, declare at the resource's own scope: - an **ownership role** that the owner holds (usually `type:*`); - one or more **member roles** for ordinary members; - the resource actions members use (`read`, `update`); - three **management** actions: managing members, managing invitations, and transferring ownership. ```ts import { definePolicy } from "rolebook"; export const policy = definePolicy({ resources: { workspace: { actions: ["read"] }, project: { parent: "workspace", actions: ["read", "update", "delete", "manage_members", "manage_invitations", "transfer_ownership"], }, }, roles: { project_owner: { scope: "project", rules: [{ effect: "allow", permission: "project:*" }] }, project_manager: { scope: "project", inherits: ["project_editor"], rules: [ { effect: "allow", permission: "project:manage_members" }, { effect: "allow", permission: "project:manage_invitations" }, ], }, project_editor: { scope: "project", rules: [ { effect: "allow", permission: "project:read" }, { effect: "allow", permission: "project:update" }, ], }, project_viewer: { scope: "project", rules: [{ effect: "allow", permission: "project:read" }] }, }, }); ``` ## `defineSharing` [#definesharing] `defineSharing()` maps storage labels to policy values and validates the mapping against the policy: ```ts prelude=sharing import { defineSharing } from "@rolebook/sharing"; const projectSharing = defineSharing({ policy, resources: { project: { // Label stored in membership rows -> policy role. memberRoles: { viewer: "project_viewer", editor: "project_editor", manager: "project_manager" }, ownershipRole: "project_owner", // Action label used by authorize(), listAccessible(), and listAccess() -> permission. actions: { read: "project:read", update: "project:update", delete: "project:delete" }, management: { members: "project:manage_members", invitations: "project:manage_invitations", ownership: "project:transfer_ownership", // Optional: who may call describeAccess(), auditHistory(), and explain(). Defaults to members. inspect: "project:manage_members", }, adapter: projectAdapter, }, }, }); ``` It throws an `Error` when: - a resource type is not declared by the policy, or is not a lowercase label (`^[a-z][a-z0-9_]{0,127}$`); - the ownership role does not exist at that resource's scope, or is also listed as a member role; - a member role does not exist at that scope, or a member-role or action label is not a lowercase label; - there is no member role, no action, or no resource type at all; - an action or management permission is not a concrete, declared permission of that resource type. `defineSharing()` canonicalizes the policy the way `definePolicy()` does and freezes the whole catalog, so a later change to your objects cannot reach a sharing decision. The member-role labels are what membership rows store and what commands name (`role: "editor"`), so choose them as a stable storage vocabulary. ### Several resource types [#several-resource-types] One sharing instance can serve several resource types, each with its own roles, actions, and storage adapter. Use a separate adapter for every concrete table, even when two types share ID formats: the resource type selects the adapter and its valid labels. ```ts import { definePolicy } from "rolebook"; import { defineSharing, type SharingAdapter } from "@rolebook/sharing"; declare const projectAdapter: SharingAdapter; declare const folderAdapter: SharingAdapter; const managed = ["manage_members", "manage_invitations", "transfer_ownership"] as const; const multiTypePolicy = definePolicy({ resources: { project: { actions: ["view", ...managed] }, folder: { actions: ["browse", ...managed] }, }, roles: { project_owner: { scope: "project", rules: [{ effect: "allow", permission: "project:*" }] }, project_editor: { scope: "project", rules: [{ effect: "allow", permission: "project:view" }] }, folder_owner: { scope: "folder", rules: [{ effect: "allow", permission: "folder:*" }] }, folder_contributor: { scope: "folder", rules: [{ effect: "allow", permission: "folder:browse" }] }, }, }); const multiTypeDefinition = defineSharing({ policy: multiTypePolicy, resources: { project: { memberRoles: { editor: "project_editor" }, ownershipRole: "project_owner", actions: { view: "project:view" }, management: { members: "project:manage_members", invitations: "project:manage_invitations", ownership: "project:transfer_ownership", }, adapter: projectAdapter, }, folder: { memberRoles: { contributor: "folder_contributor" }, ownershipRole: "folder_owner", actions: { browse: "folder:browse" }, management: { members: "folder:manage_members", invitations: "folder:manage_invitations", ownership: "folder:transfer_ownership", }, adapter: folderAdapter, }, }, }); ``` ## `createSharing` [#createsharing] ```ts prelude=sharing import { createHmacInvitationTokens, createSharing } from "@rolebook/sharing"; const projects = createSharing({ definition, identity, invitationTokens: createHmacInvitationTokens(process.env.SHARING_INVITATION_KEY!), listingCursorKey: process.env.SHARING_LISTING_CURSOR_KEY!, }); const session = projects.forTenant({ tenantId: "ws_456", actor: { type: "user", id: "user_123" } }); const decision = await session.authorize({ resource: { type: "project", id: "project_1" }, action: "update" }); ``` | Option | Default | Meaning | | --- | --- | --- | | `definition` | required | The `defineSharing()` result (it is validated again). | | `identity` | required | The [`TenantIdentityAdapter`](/docs/sharing/adapters#identity-adapters) for your provider. | | `invitationTokens` | required | Protects invitation secrets; use `createHmacInvitationTokens(key)`. | | `clock` | system clock | `{ now(): Date }`. Share one clock with the storage adapter in tests. Listing pages decide expiry at the storage adapter's own instant, not this clock. | | `ids` | `crypto.randomUUID()` | `{ next(): string }` for invitation and audit event IDs. | | `mutationRetries` | `3` | Extra attempts after a revision conflict, an integer from 0 to 10. | | `mutationBackoffMs(retry)` | capped exponential backoff with full jitter | Pause before retry `retry` (1 for the first), 0 to 1,000 ms. | | `mutationWait(ms)` | a timer | Performs a positive pause; inject one for deterministic tests. | | `maxInvitationTtlMs` | 30 days | The longest invitation lifetime `issueInvitation` accepts. | | `listingCursorKey` | a random key per instance | Seals listing and audit cursors; a key or an ordered list of up to 8 keys to rotate. | | `inspection` | disabled | `{ audit, limiter }`: enables [current-state inspection](/docs/sharing/inspection). Both hooks must be functions, or construction throws a `TypeError`. | | `diagnostics` | omitted | `{ observe?, queueLimit?, observerTimeoutMs? }`: enables factory-local [operational diagnostics](/docs/sharing/api#operational-diagnostics). Omitted, no operation is instrumented. An invalid value throws `TypeError("Invalid sharing diagnostics options")`. | `createSharing()` returns a [`ResourceSharingWithDiagnostics`](/docs/sharing/api#resourcesharingwithdiagnostics): `{ forTenant(context), inspectionEnabled, diagnostics() }`. `diagnostics()` is a synchronous, frozen snapshot of this instance in this process; with `diagnostics` omitted it reports `enabled: false` and zero counts. Diagnostics are implemented but not yet released and not production-qualified. A `TenantContext` is `{ tenantId, actor }`: the explicit tenant and the authenticated actor reference. The returned [`TenantSharing`](/docs/sharing/api#tenantsharing) has `authorize`, `execute`, `listAccessible`, `describeAccess`, `permissions`, `listAccess`, `auditHistory`, and `explain`. ### What listing needs from this configuration [#what-listing-needs-from-this-configuration] `authorize()`, `permissions()`, and commands work with any conforming storage and identity adapter. [`listAccessible()` and `listAccess()`](/docs/sharing/listing) are stricter: each page is read at one coherent point, so the adapters you pass here must be able to supply one. Check three things when you assemble the instance: - **The storage adapter's executor.** PostgreSQL needs the checked `createPgExecutor(pool)` executor and `text` tenant and resource ID columns. SQLite needs the worker-backed `createBunSqliteQueryExecutor()` executor; the executors from `@rolebook/sharing-sqlite/bun` and `/libsql` do not supply the page snapshot. The executor is recognized by provenance, so a wrapped or hand-built one does not qualify. The in-memory adapter needs nothing further. - **Eligibility evidence.** The built-in membership and local-projection eligibility fences supply it. Any other fence, a custom `lockEligibleSubjects` (or, in memory, `fenceEligibleSubjects`) or the Teams fences from `createPostgresTeamFences()` and `createBetterAuthTeamFences()`, needs a matching `readEligibleSubjects` that reads the same authority. - **Identity evidence for `identity`.** Either the storage adapter's `pageIdentity` option names this exact `identity` object together with the local projection it answers from, or the identity adapter implements `resolvePagePrincipal` (an external source with a non-repeating revision) or, in memory, `capturePagePrincipal`. The Better Auth, Clerk and WorkOS identity adapters and `withTeams()` implement neither page method. To list, use an identity adapter that answers exclusively from a complete local projection and name it in `pageIdentity`; naming the provider-backed identity itself does not qualify. These are listing requirements; construction does not check them, and other operations have their own documented requirements. A configuration that lacks one of them rejects its listings with `AccessListingUnavailableError` and a `reason` (`capability_missing` or `identity_evidence_missing`); they never return a weaker page. [What a consistent page requires](/docs/sharing/listing#what-a-consistent-page-requires) has the details and an example. ## Secret keys [#secret-keys] `createHmacInvitationTokens(key)` digests invitation secrets with HMAC-SHA256, and `listingCursorKey` seals cursors with keys derived through HKDF-SHA256. Both need at least 32 bytes of secret random data, never a passphrase. Create a key once and store it as a secret: ```sh bun -e 'import { generateInvitationTokenKey } from "@rolebook/sharing"; console.log(generateInvitationTokenKey())' ``` A generated key is text of the form `rbk1_<32 random bytes as base64url><6-character check>`, used as its UTF-8 bytes. `generateListingCursorKey()` produces the same form, so one secret can back both. - A string key must be a generated key: its check must match. A passphrase, a hand-typed key, or a generated key with a changed character or surrounding whitespace throws at construction. - Any other random secret goes in as bytes: `Buffer.from(hexKey, "hex")`, or any `Uint8Array` of at least 32 bytes. Byte keys are only checked for length and for at least 8 distinct byte values, which catches placeholders, not weak secrets. - Keys are copied at construction; clearing your buffer later changes nothing. Only strings and `Uint8Array` (including `Buffer`) are accepted. - Keep the invitation key stable: a new key invalidates every outstanding invitation. To rotate cursor keys, pass `[newKey, oldKey]`: the first seals new cursors and every listed key opens old ones. - Without a `listingCursorKey`, each instance seals with its own random key, so cursors work only within the instance that issued them. Configure a shared key for several processes, or for paging across restarts. A random key already in use as a plain string (from an older release or `openssl rand`) no longer passes as a string. Keep it, and every outstanding invitation and cursor, with `new TextEncoder().encode(existingKey)`: a string has always been used as its UTF-8 bytes. Do not decode it from hex or base64, which changes the key. If the old key is a passphrase, generate a new key and re-issue outstanding invitations instead. ## Versioned policies [#versioned-policies] `createSharing()` evaluates the policy in its definition and never reads a store. To publish policy changes at runtime and give tenants custom roles, use [`createVersionedSharing()`](/docs/sharing/versioned) instead: it has the same tenant API plus policy and custom-role administration. Its listings read the active policy inside each page's snapshot, so create the policy store on the same executor object as the resource adapter and pass the store itself, not a wrapper; see [versioned policy](/docs/sharing/listing#versioned-policy). # Policy versions and custom roles (/docs/sharing/versioned) > createVersionedSharing(), the policy store, publishing, staleness bounds, impact previews, and tenant custom roles. `createSharing()` evaluates the policy in its definition. `createVersionedSharing()` instead loads the **active** policy from a policy store in your own database, lets operators publish new versions at runtime, and lets each tenant define **custom roles** within bounds you set. It returns the same tenant API plus `policies`, `customRoles`, `current()`, `refresh()`, and the same [`diagnostics()`](/docs/sharing/api#operational-diagnostics) snapshot as `createSharing()`. ```ts prelude=sharing import { createVersionedSharing, type PolicyStore } from "@rolebook/sharing"; // createPostgresPolicyStore(), createSqlitePolicyStore(), or createMemoryPolicyStore(). declare const policyStore: PolicyStore; // Every adapter in `definition` must be built with a policy fence (fencePolicy). const versioned = await createVersionedSharing({ definition, identity, invitationTokens, policyStore, refreshIntervalMs: 5_000, maxStalenessMs: 30_000, }); const state = versioned.current(); // { generation, digest, label?, confirmedAt, seedMatchesActive } const decision = await versioned .forTenant({ tenantId, actor }) .authorize({ resource: { type: "project", id: projectId }, action: "read" }); ``` It is async: it reads the active pointer (and seeds the store) before it returns. ## Options [#options] All of [`createSharing`'s options](/docs/sharing/setup#createsharing), plus: | Option | Default | Meaning | | --- | --- | --- | | `policyStore` | required | The [`PolicyStore`](/docs/sharing/api#policystore). | | `refreshIntervalMs` | `5000` | How old a confirmed pointer may be before an operation re-reads it. Integer, 100 to 60,000. | | `maxStalenessMs` | `30000` | How long a cached pointer may serve while the store is unreachable. Clamped up to the refresh interval, at most 300,000. | | `seed` | `"activate-if-empty"` | With an empty store, save and activate the code policy. `"require-active"` refuses to start instead (`NO_ACTIVE_POLICY`). | | `requiredPolicyRoles` | `[]` | Policy roles every published version must declare. | | `tenantCacheSize` | `1024` | Tenant runtimes kept, least recently used first out. Integer, 1 to 65,536. | | `monotonicNow` | `performance.now()` | Elapsed-time source for freshness only, never for stored timestamps. | | `onSeedDrift` | none | Called once, synchronously, the first time the active digest differs from the code seed. | Construction throws `PolicyStoreError`: `INVALID_OPTIONS`, `ADAPTER_NOT_FENCED` (an adapter does not report `policyFence: "enforced"`), `SEED_INVALID`, `NO_ACTIVE_POLICY`, or `ACTIVE_VERSION_INVALID`. ## Versions and generations [#versions-and-generations] A version's identity is a digest: `sha256:` plus 64 lowercase hex digits of the policy's [canonical JSON](/docs/api#canonicalpolicyjson), which excludes the version label. Activations are numbered by **generation**, a decimal string starting at `"1"`; an empty store is generation `"0"` with a null digest. Counters are compared as `BigInt` and stop at `9223372036854775807`. The code-defined policy is a seed. Once a version is active, the store wins: a later code change takes effect only through `policies.saveDraft()` and `policies.publish()`. `current().seedMatchesActive` reports drift. The evaluation version string is `":"`, or `":;tenant-roles:"` when the tenant has an available custom role. Decisions, mutation results, listings, access descriptions, and inspection explanations report it as `policyVersion`. ## Publishing [#publishing] ```ts prelude=sharing import { createVersionedSharing, type PolicyStore } from "@rolebook/sharing"; declare const versioned: Awaited>>; const operator = { type: "user", id: "operator_1" }; const draft = await versioned.policies.saveDraft({ policy, label: "add archive", actor: operator }); if (draft.ok) { const diff = await versioned.policies.diff({ from: "active", to: draft.digest }); const { generation } = versioned.current(); const published = await versioned.policies.publish({ digest: draft.digest, expectedGeneration: generation, actor: operator, }); // published.code: "ACTIVATED" | "GENERATION_CONFLICT" | "ALREADY_ACTIVE" | ... } ``` | Method | Does | | --- | --- | | `saveDraft({ policy, label?, actor })` | Validates and stores a canonical version under its digest. `SAVED` or `EXISTS`; refusals `POLICY_TOO_LARGE` (over 1 MiB), `POLICY_INVALID`, `RESERVED_ROLE_NAME` (a role starting `rolebook.custom.`), `DEFINITION_INCOMPATIBLE`, `INVALID_ACTOR`, `INVALID_LABEL`. | | `readVersion({ digest })` | The stored version, its policy, and whether it is active. | | `listVersions({ limit, cursor? })`, `listActivations(...)` | Paged history, newest first. | | `diff({ from, to })` | A [`PolicyDiff`](/docs/api#policydiff) between two digests or `"active"`. | | `previewImpact(input)` | Decisions that would change for given subject and resource pairs. | | `previewCustomRoles({ candidate, limit, cursor? })` | Which stored custom roles a draft would make unavailable. | | `publish({ digest, expectedGeneration, actor })` | Activates a version if the generation still matches: `ACTIVATED`, `GENERATION_CONFLICT`, `ALREADY_ACTIVE`, or a refusal. | `previewImpact` evaluates explicit `pairs` of subject and resource (at most 200), or a `sample` of up to 20 subjects and 50 candidate resources each, under both the active policy and the candidate, and reports the decisions that change, a summary, and custom roles that would lose availability. Whoever can call `policies.*` or `customRoles.*` can change every tenant's access. Rolebook records the `actor` in the policy audit but does not authorize it. Authenticate and authorize operators before calling these APIs, and never expose them to tenant users. ## Writes are fenced, reads are bounded [#writes-are-fenced-reads-are-bounded] Writes never commit under a generation that is no longer active. An adapter built with `fencePolicy` reports `policyFence: "enforced"` and, inside every mutation transaction, after the resource-revision compare, reads the active generation and the tenant's custom-role revision. When either differs from the values the command started with, the mutation returns `POLICY_GENERATION_CHANGED` or `TENANT_ROLES_CHANGED`. Requirements: - The policy-store tables live in the same database as the sharing tables of every fenced adapter. - The store and every fence use the same `tablePrefix`. - The fence reads only through the mutation transaction's executor. - Before the first `publish` (or custom-role `define`), every process that writes sharing state runs fenced adapters. A process left on an unfenced adapter can commit under a superseded policy, and Rolebook cannot detect it. Reads are pull-based with no timer. Each operation checks how long ago its runtime confirmed the active pointer, using `monotonicNow`. Older than `refreshIntervalMs`, it re-reads the pointer. While the store is unreachable, a cached pointer serves until `maxStalenessMs`; past that, `authorize()` and the other reads reject with `PolicyUnavailableError` and `execute()` returns `POLICY_UNAVAILABLE`, before any identity or storage callback. A read on another instance may therefore decide under the previous generation for at most the refresh interval plus its own duration. There is no strong-read mode. Once the store has told an instance that its active generation is no longer active (a publish `GENERATION_CONFLICT` naming a later generation, a custom-role generation conflict, or `POLICY_GENERATION_CHANGED`), that instance decides nothing under that generation, or any older one, until a pointer read that started after the report confirms it or installs a later one. A read already in flight at the report does not count and the refresh interval does not apply. While the store is unreachable in that state, operations fail with `STORE_UNREACHABLE`; when every refresh (at most three) is overtaken by a further report, the operation fails with `STALE`. A running instance never accepts a pointer that goes backwards, changes digest at the same generation, or fails to decode. Those failures are sticky (`POINTER_REGRESSED`, `POINTER_DIGEST_MISMATCH`, `POINTER_INVALID`, `VERSION_INVALID`) until the process constructs a new instance: restoring an older generation requires restarting every instance. A tenant whose custom-role rows are corrupt sticks at `TENANT_ROLES_INVALID` for that tenant only. Other `PolicyUnavailableError` reasons are `STORE_UNREACHABLE`, `STALE`, `INTERNAL_ERROR`, `CLOCK_FAULT`, and `REVISION_REGRESSED`. `INTERNAL_ERROR` is a fault that did not come from the store; it is never tolerated as staleness. After a custom-role `define` or `remove` applies, or an `execute` returns `TENANT_ROLES_CHANGED`, the instance never serves that tenant's earlier custom roles, not even while the store is unreachable; if every reload is overtaken by a further invalidation on the same instance, the operation fails closed with `STALE`. The original error is kept as the `cause` and passed to `onInternalError` when that option is set. ## Custom roles [#custom-roles] A custom role is a tenant-local member-role label `custom:`, matching `custom:[a-z][a-z0-9_]{0,47}` (`CUSTOM_ROLE_LABEL`). It is stored in the membership `role` column, disjoint from static labels. It names a **template**: one of the type's static member-role labels. The stored role carries every effective deny of the template's policy role, plus operator rules, and every operator allow must be held by the template for every concrete permission it names. ```ts prelude=sharing import type { createVersionedSharing } from "@rolebook/sharing"; declare const versioned: Awaited>>; const listed = await versioned.customRoles.list({ tenantId }); if (listed.ok) { const defined = await versioned.customRoles.define({ tenantId, resourceType: "project", name: "custom:reviewer", template: "editor", rules: [{ effect: "allow", permission: "project:read" }], expectedRevision: listed.revision, actor: { type: "user", id: "operator_1" }, }); } ``` `define` and `remove` compare-and-swap on the tenant's revision (`REVISION_CONFLICT` otherwise). `define` refuses with `CEILING_EXCEEDED` (with the permissions above the template), `CUSTOM_ROLE_INVALID` (`name`, `rules`, or `limits`), `UNKNOWN_RESOURCE_TYPE`, `TEMPLATE_UNKNOWN`, `TOO_MANY_CUSTOM_ROLES`, `CUSTOM_ROLE_NAME_RETIRED`, `GENERATION_CONFLICT`, or `REVISION_EXHAUSTED`. Limits: 32 custom roles per tenant, 256 records including tombstones, 64 operator rules per role. `set({ tenantId, roles, expectedRevision, actor })` makes `roles` the tenant's complete set of live custom roles in one write: every role gets `define`'s checks, the limits are counted on the result, a live role the set does not name is removed, and every change, one revision bump and the audit events commit together, fenced on `expectedRevision` and the active generation, or nothing is written. A concurrent `define`, `remove`, `set` or publish makes it answer `REVISION_CONFLICT` or `GENERATION_CONFLICT`. A set already in place answers `UNCHANGED` and writes nothing. It exists when the policy store implements `writeTenantRoleSet`, as the first-party stores do; see [`CustomRoleAdministration`](/docs/sharing/api#customroleadministration). A tenant with at least one available custom role is evaluated under a tenant policy: the active policy plus one derived role per available custom role. Grants, invitations, and evaluation then accept the label. | Situation | Status | Result | | --- | --- | --- | | Live role within its template | `available` | Grants and evaluation use it. | | Tombstone | `retired` | The name cannot be reused (`CUSTOM_ROLE_NAME_RETIRED`). | | Template label gone | `template_missing` | The role is unavailable. | | Rules no longer within the template | `exceeds_template` | The role is unavailable; Rolebook does not clamp it. | | A row that does not decode | `invalid` | That role is unavailable. | | Tenant-wide corruption | | Sticky `TENANT_ROLES_INVALID` for that tenant. | | A `custom:` label the tenant never defined | | The binding fails closed; only the owner's `revokeMember` removes it. | An unavailable role is absent from evaluation, so a membership that names it fails the binding closed rather than having its denies ignored. New grants, changes, and invitations to it are `ROLE_NOT_ALLOWED`; accepting an invitation to it is `INVITATION_UNAVAILABLE`; only the owner's recovery path can change or revoke such a membership. `describeAccess()` marks it `roleUnavailable: true`. ## Idempotent replays [#idempotent-replays] A versioned `execute()` replays the actor's own committed idempotency key before validation and authorization: the fingerprint binds actor, tenant, and command, and the answer is `ALREADY_APPLIED` with the `policyVersion` stored on the original commit. A since-deleted custom role or a lost management permission cannot turn a committed command into a refusal. The replay lasts only as long as the idempotency record; see [retention](/docs/sharing/retention). ## Testing without a database [#testing-without-a-database] `createMemoryPolicyStore()` is an in-memory `PolicyStore`. Pass its `fence` method as `fencePolicy` to `createMemorySharingAdapter()`, then pass the store and that adapter to `createVersionedSharing()`. It also has test seams: `failWith(error)`, `failNextAudit()`, `setCounters()`, and `readAudit()`. # Access-change webhooks (/docs/sharing/webhooks) > Notify other systems, with signed HTTP requests, when access to a resource changes. Rolebook can POST a signed JSON request to an endpoint you configure each time access to a resource changes. Delivery reads only committed audit rows, so a change is never announced before its transaction commits, and a rolled-back change is never announced at all. It runs outside the authorization transaction and never changes it. Delivery is **at least once**. The same change can arrive more than once (after a timeout, a lost acknowledgement or a requeue), always with the same `rolebook-webhook-id`. Receivers must drop duplicates by that ID. Rolebook does not claim exactly-once delivery. ## Events [#events] One request is sent for each audit event with one of these actions. Every other audit action (`invitation.revoked`, `resource.initialized`, `resource.deleted`, `resource.moved`) is not sent. | `type` | Sent when | | ----------------------- | --------------------------------------------- | | `member.granted` | A member is granted a role. | | `member.role_changed` | A member's role changes. | | `member.revoked` | A member is removed. | | `ownership.transferred` | Ownership moves to another subject. | | `invitation.issued` | An invitation is created. | | `invitation.consumed` | An invitation is accepted. | Audit rows written before the delivery migrations ran have no delivery position and are never sent. Delivery starts with the first change committed after them, whichever release wrote it. ## Payload [#payload] The body is JSON. `event` is exactly the Sharing HTTP API's [audit event](/docs/http-api/http) (`WireAuditEvent`); the body is built field by field from that allow-list, so an invitation token, a token digest, an idempotency key, incarnation or lineage data, and any field outside the allow-list are never sent. ```json { "id": "evt_5f0c1d7a9e2b4c6d8f0a1b2c3d4e5f60", "type": "invitation.issued", "environmentId": "production", "event": { "id": "audit_01", "tenantId": "org_123", "resourceType": "project", "resourceId": "project_42", "actor": { "type": "user", "id": "user_1" }, "action": "invitation.issued", "invitationId": "inv_7", "occurredAt": "2026-11-22T12:00:00.000Z" } } ``` `id` is stable for one audit event: `evt_` and 32 hex characters derived from the resource type, tenant, resource ID and audit event ID. Every retry and requeue sends the same bytes with the same `id`. `occurredAt` is the instant the sharing module stamped; it is not the delivery order (see [ordering](#ordering-and-duplicates)). ## Signature [#signature] Each request carries three headers: | Header | Value | | ---------------------------- | ------------------------------------------------------ | | `rolebook-webhook-id` | The body's `id`. | | `rolebook-webhook-timestamp` | When this attempt was signed, in Unix seconds. | | `rolebook-webhook-signature` | `v1=` and the lowercase hex HMAC-SHA-256 of the input. | The signed input is `..`, keyed by the UTF-8 bytes of the endpoint's secret. Secrets are 32–512 characters; both the sender and the verifier refuse shorter ones. The verifier accepts several secrets, and the signature header may carry several space-separated `v1=` values, so a receiver can accept the old and new secret while you rotate. The sender signs with one secret per endpoint. Verify with `verifyAccessChangeWebhook` from `@rolebook/http/webhooks`. Pass the raw body before any parsing, preferably as bytes: they are copied once, refused over 64 KiB, and decoded as strict UTF-8, so a byte sequence that does not decode, or a byte-order mark, is not silently rewritten. The verifier reads the body exactly once and returns the event it authenticated. It compares signatures in constant time and rejects a timestamp more than 300 seconds (configurable up to 3600) from the receiver's clock in either direction. ```ts import { verifyAccessChangeWebhook } from "@rolebook/http/webhooks"; declare const secret: string; declare const inbox: { /** Records the ID and applies the change in one transaction; false when the ID was recorded. */ applyOnce(id: string, change: { type: string; resourceId: string }): Promise; }; export async function receive(request: Request): Promise { const declared = Number(request.headers.get("content-length") ?? "0"); if (!Number.isFinite(declared) || declared > 64 * 1024) return new Response(null, { status: 413 }); const body = new Uint8Array(await request.arrayBuffer()); const result = await verifyAccessChangeWebhook({ secret, headers: request.headers, body }); if (!result.ok) return new Response(null, { status: 400 }); // At least once: the same id can arrive again, even concurrently. Record it and apply the // change atomically, so a duplicate or a crash between the two never applies it twice. await inbox.applyOnce(result.id, { type: result.webhook.type, resourceId: result.webhook.event.resourceId, }); return new Response(null, { status: 204 }); } ``` The failure reasons are `missing-header`, `malformed-header`, `stale-timestamp`, `invalid-signature` and `malformed-body`. Answer any 2xx status once the change is safely recorded; anything else is a failed attempt. A receiver that takes webhooks from several environments deduplicates on `environmentId` and `id` together. ## Storage [#storage] Delivery state lives in its own tables, apart from the audit tables: the tenant each subscription is bound to, a cursor per subscription and resource type, and a queue of entries. Draining never updates or deletes an audit row. Delivery writes to an audit table in only two places: the SQLite trigger below sets `delivery_seq` as a row is inserted, and the PostgreSQL operator action `rebaseline` clears every position after a logical restore. [Audit retention](/docs/sharing/retention) and the sealed `auditHistory()` cursors work exactly as before. A queued entry keeps its own copy of the allow-listed event, so retention may remove an audit row once every subscription has queued it. **An audit row removed before a subscription drained it is never sent to that subscription.** Delivery can fall behind (a receiver that is down does not stop draining, but a failing drain, a stopped worker, or on PostgreSQL a long-running transaction, does), so retention must keep audit rows until every subscription's cursor is past them, and should keep a margin on top. Run the migrations as the schema owner. **PostgreSQL.** `createResourceSharingMigrations` gives each audit table the column `delivery_xid` (`xid8`, defaulting to `pg_current_xact_id()`), in step `:audit-delivery-position`, and the index `_dpos_idx` on `(tenant_id, delivery_xid)`, in step `:audit-delivery-index`. The default is a function any role may call, so an application role that can insert audit rows needs no new privilege, and a process of the previous release keeps writing rows that will be delivered. Existing rows keep `NULL` and the table is not rewritten. The column step takes `ACCESS EXCLUSIVE` only for those catalog changes; the index step builds the index under `SHARE`, which lets reads continue and makes writes wait for the build. To avoid that pause on a large audit table, create the same index first with `CREATE INDEX CONCURRENTLY _dpos_idx ON (tenant_id, delivery_xid)`; the step then does nothing. `createAccessChangeDeliveryMigrations({ tablePrefix })` creates `_access_subscription_v1`, `_access_cursor_v1` and `_access_delivery_v1`. **SQLite.** `applyResourceSharingMigrations` adds the column `delivery_seq` and its index. `applyAccessChangeDeliveryMigrations(executor, { tablePrefix, resources })` creates the delivery tables, a per-audit-table position counter `_access_position_v1`, and on each audit table a trigger that gives every inserted row the counter's next value, overwriting any position its writer supplied. The trigger runs in the inserting transaction, under the database write lock, so positions follow commit order; it fires for a writer of any release; and because the counter only grows, deleting audit rows never makes a position be used twice. It reads the counter by its key and updates the new row by its primary key, so its cost does not grow with the table. The migration seeds each counter above the table's highest position and every cursor's, so reinstalling after a counter row was lost never reuses a position; an insert fails while its counter row is missing. Managed deletion and movement admit exactly this generated trigger on the audit table, and still refuse any other or altered trigger there. They hold the counter table to the same rules as the audit table: a permanent table in `main`, unshadowed, without triggers. A cursor records the audit table it reads. Two audit tables that expose the same resource type need stores with different delivery prefixes, and choosing them is the operator's responsibility. The store diagnoses a clash only per subscription: when a subscription's cursor for a resource type was recorded by a store over another audit table, a drain is refused with code `source-conflict`. When the two stores' first drains race, the conflict is reported at the latest on the next drain that reads a page. Two stores whose subscriptions never share an ID are not detected. **Upgrade order on SQLite:** an instance of an earlier release refuses managed deletes and moves once the trigger exists, so upgrade every instance first, then run `applyAccessChangeDeliveryMigrations`. The queue grows by one row per change and subscription. Each delivery pass deletes delivered entries older than `deliveredRetentionMs` (one day by default), at most `pruneLimit` per endpoint; `store.pruneDelivered` does the same on demand. Dead-lettered and undelivered entries are never pruned. ## Run it in your application [#run-it-in-your-application] `createWebhookDelivery` from `@rolebook/server/webhooks` validates everything at construction and throws `WebhookConfigurationError` before any storage or network call. Each `runOnce()` drains each endpoint's tenant into its queue, runs one bounded pass of the shared [outbox delivery worker](/docs/sharing/outbox-delivery), and prunes delivered entries. `run()` repeats passes until its signal aborts, and gives each pass's report to `onReport`: a stage that throws is listed in the endpoint's `failed` (`"drain"`, `"delivery"` or `"prune"`) and explained in `errors` (see [retries and dead letters](#retries-and-dead-letters)). A failed drain does not stop the delivery of entries already queued. ```ts import { createWebhookDelivery } from "@rolebook/server/webhooks"; import { createPostgresAccessChangeDeliveryStore, type ParameterizedSqlExecutor, type PostgresResourceDescriptor, } from "@rolebook/sharing-postgres"; declare const executor: ParameterizedSqlExecutor; declare const projects: PostgresResourceDescriptor; declare const crmSecret: string; declare const log: (report: unknown) => void; const store = createPostgresAccessChangeDeliveryStore({ executor, tablePrefix: "app", environmentId: "production", resources: [projects], }); const delivery = createWebhookDelivery({ store, endpoints: [ { id: "crm", tenantId: "org_123", url: "https://hooks.example.com/rolebook", secret: crmSecret }, ], }); const stop = new AbortController(); void delivery.run({ signal: stop.signal, intervalMs: 1_000, onReport: (report) => { if (report.endpoints.some((endpoint) => endpoint.failed)) log(report); }, }); ``` `createSqliteAccessChangeDeliveryStore` takes the same options with a SQLite executor. ### Configuration from environment variables [#configuration-from-environment-variables] `webhookDeliveryFromEnv({ env, store })` is the startup helper for a server process. It returns `undefined`, and nothing runs, when no `ROLEBOOK_WEBHOOK_*` variable is set. When any is set, the URL, secret and tenant are required and every value must validate, or it throws `WebhookConfigurationError`, naming the variable and never its value. `webhookConfigurationFromEnv` checks presence, format and the `ROLEBOOK_WEBHOOK_INTERVAL_MS` range. The other numeric ranges are checked when the delivery is built, and `webhookDeliveryFromEnv` reports those failures under the variable's name too. | Variable | Meaning | Default | | ----------------------------------------- | ------------------------------------------------ | ---------- | | `ROLEBOOK_WEBHOOK_URL` | Endpoint URL. Required. | | | `ROLEBOOK_WEBHOOK_SECRET` | HMAC secret, 32–512 characters. Required. | | | `ROLEBOOK_WEBHOOK_TENANT_ID` | The one tenant this endpoint receives. Required. | | | `ROLEBOOK_WEBHOOK_ENDPOINT_ID` | Subscription ID. | `default` | | `ROLEBOOK_WEBHOOK_MAX_ATTEMPTS` | Attempts before dead-letter, 1–1000. | `300` | | `ROLEBOOK_WEBHOOK_BACKOFF_BASE_MS` | First retry delay, 1–300000. | `1000` | | `ROLEBOOK_WEBHOOK_BACKOFF_CAP_MS` | Largest retry delay, up to 300000. | `300000` | | `ROLEBOOK_WEBHOOK_TIMEOUT_MS` | Whole-request deadline, 1–60000. | `10000` | | `ROLEBOOK_WEBHOOK_MAX_RESPONSE_BYTES` | Largest response body read, 0–1048576. | `65536` | | `ROLEBOOK_WEBHOOK_DELIVERED_RETENTION_MS` | How long a delivered entry is kept, 0–999999999. | `86400000` | | `ROLEBOOK_WEBHOOK_INTERVAL_MS` | Pause between passes, 10–600000. | `1000` | The environment ID is the store's, chosen where you build the store, not read from the environment. ```ts import { webhookDeliveryFromEnv } from "@rolebook/server/webhooks"; import type { AccessChangeDeliveryStore } from "@rolebook/sharing"; declare const store: AccessChangeDeliveryStore; declare const env: Readonly>; const configured = webhookDeliveryFromEnv({ env, store }); if (configured) { const stop = new AbortController(); void configured.delivery.run({ signal: stop.signal, intervalMs: configured.intervalMs }); } ``` ## Retries and dead letters [#retries-and-dead-letters] A 2xx response is a delivery. Every other outcome is a failed attempt: another status, a redirect, a response body over the cap, a timeout, or a network error. After failed attempt `n` the entry waits `min(cap, base × 2^(n−1))` milliseconds and is tried again. With the defaults that is 1 s, 2 s, 4 s, … up to 5 minutes, for 300 attempts: a receiver can be down for about a day before an entry is dead-lettered. The reason is a fixed code such as `dead-lettered after 300 attempts: http-503`; response bodies and exception messages are never stored. An attempt counts a claim, so a worker that crashes after claiming also uses one. A dead-lettered entry stays in the queue. It holds back the later changes of **its own resource**, so they are never delivered ahead of it, and it does not affect any other resource. List entries with `store.inspectDeadLetters({ subscriptionId, tenantId, limit })`. Fix the receiver and put one back with `store.requeue(entry.token)`, which restarts it with a fresh attempt count and the same `id`, or drop it with `store.discardDeadLetter(entry.token)`, which deletes it so the rest of its resource is delivered; that change is then never sent. A claimed entry whose stored copy no longer matches its own queue row (it does not decode, or names another tenant, resource or delivery ID) is dead-lettered on its own with the reason `dead-lettered: the stored entry does not decode`, under the same fence as any settlement, and the rest of the batch is delivered. The pass report lists those delivery IDs in `deadLettered`. Its listing has no `kind` when that is what failed to decode. `inspectDeadLetters`, `requeue` and `discardDeadLetter` are scoped to the subscription's tenant, and touch only an entry that is not leased. Each pass reports, per endpoint, the stages that threw (`failed`) and why (`errors`). A store refusal keeps its code (`foreign-cluster`, `missing-origin`, `tenant-bound`, `tenant-spelling`, `invalid-row`, `missing-privilege`, `source-conflict`) and message, including when it happened while claiming; anything else is `unexpected`, without its message. `run()` passes every report to `onReport`. Without one, it writes each failure to `console.warn` as a fixed sentence for its code (never the store's own message), at most once every ten minutes for the same endpoint, stage and code. ## Ordering and duplicates [#ordering-and-duplicates] - **Per resource, in commit order.** Changes to one resource are delivered one at a time, in the order their transactions committed. The next change of a resource is not sent until the previous one is acknowledged; a failing one is retried first, and a dead-lettered one blocks its resource until it is requeued or discarded. - **Across resources, no order.** That is the whole guarantee: there is no order across resources, resource types or the subscription as a whole. Different resources are delivered independently and concurrently, up to the batch size, so a later change to another resource can arrive first, including while an earlier change is waiting for a retry. - **Nothing skipped.** `occurred_at` is the module's clock, read before the transaction, so two transactions can commit in the opposite order of their timestamps. Delivery does not read by timestamp. On PostgreSQL each audit row records its transaction ID, and a drain reads only rows from transactions older than every transaction still running in the cluster, so a row committed later can never land behind the cursor. **An old open or prepared transaction anywhere in the cluster, in any database, holds back every audit row whose transaction ID is at or above its own, for every tenant and subscription, until it ends**; watch for old transactions (`pg_stat_activity.backend_xid`, `pg_prepared_xacts`). Sharing mutations write at most one access change per resource per transaction and update the resource's revision under `SERIALIZABLE`, so for one resource transaction-ID order is commit order. Rows of one transaction are paged by resource and event ID. On SQLite each audit row's position is assigned under the write lock its transaction holds until it commits. - **Duplicates.** A crash after the request but before the acknowledgement, a timeout after the receiver had already processed the request, or a requeue sends the same `id` again. A crash after claiming but before sending loses nothing: the lease expires and the entry is claimed again. A worker whose lease expired can no longer settle the entry; the next claim owns it. ### PostgreSQL positions belong to one cluster [#postgresql-positions-belong-to-one-cluster] Transaction IDs are local to a PostgreSQL cluster. The step that adds `delivery_xid` to an audit table also records, in `rolebook_access_delivery_origin`, one row for that table: the cluster's `system_identifier` and an epoch. Every drain, before it binds a subscription or reads a row, compares each of its resources' rows with the cluster it runs on, and refuses with code `foreign-cluster` when one differs. A drain that finds a position at or beyond the cluster's next transaction ID also refuses, and halts that subscription, so the refusal does not clear itself once the counter catches up. Entries already queued are still delivered while a drain refuses. A drain's queue transaction is SERIALIZABLE and rechecks the table's epoch and the subscription's halt. Under one delivery prefix, a rebaseline that commits alongside it makes it queue nothing. Under another prefix over the same audit table, a page read before that rebaseline can still be queued, but its cursor then belongs to an earlier epoch and starts again from changes committed afterwards on its next drain. Which action to take depends on how the database got where it is: | How | Identity | Counter | Action | | --- | --- | --- | --- | | Physical backup, promoted standby | kept | kept | none | | `pg_upgrade` | may change | kept | `store.adoptCluster()` | | `pg_dump` and `pg_restore`, logical replication | changes | not kept | `store.rebaseline()` | **Adopt** (`adoptCluster`) records this cluster for the store's audit tables and keeps every cursor and position. Use it only after `pg_upgrade` or a physical copy: a successful adopt does not prove the counter is continuous. It refuses, with code `foreign-cluster`, when any position is at or beyond the next transaction ID, and when any subscription is halted, because both mean a logical restore. **Rebaseline** (`rebaseline`) is for a logical restore. **Run it after the restore and before the application writes anything on the new cluster: a change written between the restore and the rebaseline is not delivered, or is delivered out of order.** For the store's audit tables, in one transaction, it: 1. Queues the outstanding restored changes, in their original order, of every subscription of the store's environment that exists at that moment, has drained the resource, and has a tenant the tenant column can hold. 2. Clears every audit row's position, for every tenant. 3. Advances the tables' epoch, so every cursor of an earlier epoch, in any store, starts again from changes committed afterwards. Queued entries and the ordinal that orders them are kept. 4. Records this cluster, and clears the halts of the store's environment. It returns what it did: - `subscriptions`: how many had at least one change queued. - `entries`: the changes queued. - `positionsCleared`: the audit rows whose position was cleared. - `rowsSkipped`: the restored access changes that did not decode, which are set aside and not queued. What this does not cover: - **Subscriptions that do not exist at the rebaseline**, including those of another environment or another store over the same tables. Changes committed before the rebaseline are delivered only to subscriptions that existed when it ran. A subscription created later starts from changes committed afterwards. - **Other stores' resources.** A store over other audit tables keeps refusing until it is rebaselined itself, and its refusal says so. - **A restore that did not carry the origin row** (`missing-origin`). A missing row usually means the migration role could not read `pg_control_system()`, on a database that was never restored: grant it and run the migration again. `rebaseline` refuses this case unless called with `force: true`, which is only for a real restore. - **The recorded epoch.** Forced, it records the table at an epoch above every epoch the prefix's cursors hold and above the current time in milliseconds. That is a large number, by design, so it never meets another prefix's cursors; do not reset it. - **Cursors at the newest epoch** are read from where they stand, so what they already passed is never queued again. - **Cursors at an older epoch** start again from the start of the table. Then the positions are cleared and the epoch advances, as in any rebaseline. If that is not acceptable, drain everything before the dump: 1. Stop writes. 2. Make sure no transaction that was open before the stop is still open or prepared (`pg_stat_activity`, `pg_prepared_xacts`). Committed changes behind such a transaction are not yet visible to a drain, so `caughtUp` can be true while they are still pending. 3. Drain every subscription until `caughtUp`. `rebaseline` returns `rebaselined: false` and changes nothing when the store's positions already belong to this cluster and no subscription is halted. Pass `force: true` to run it anyway; discarded and pruned entries are not brought back. Privileges, per action: | Action | Needs | | --- | --- | | Drain and deliver | `SELECT` on the audit tables and on `rolebook_access_delivery_origin`; `SELECT`, `INSERT`, `UPDATE` and `DELETE` on the three delivery tables; execute on `pg_control_system()` (granted to `PUBLIC` by default) | | `adoptCluster` | The above, plus `UPDATE` on `rolebook_access_delivery_origin` | | `rebaseline` | The above, plus `UPDATE` on the audit tables (it clears `delivery_xid`) and `INSERT` on `rolebook_access_delivery_origin` | | Sharing migration | Its usual privileges, plus execute on `pg_control_system()` and `INSERT` on `rolebook_access_delivery_origin` | Run the operator actions with the schema owner's executor. The drain runs on the primary. In a drain, every permission error is reported as `missing-privilege`, and the message names the grants a drain needs. That covers reading the cluster identity and the origin table, and every later step: the audit tables, the delivery tables and the queue transaction. `adoptCluster` and `rebaseline` also report `missing-privilege` when they cannot read the cluster identity, naming the grant, or lock and update the origin table, naming the grant and the schema owner's executor; their other permission errors, and those of the worker port's claim and settlement calls, surface as they are. If the migration role may not read `pg_control_system()` or insert into the origin table, the migration still succeeds but leaves the origin unrecorded, and delivery refuses with code `missing-origin` until the grant is made and the migration runs again. ## Outbound safety [#outbound-safety] - The URL is validated at startup: `https:` only, or `http:` for a loopback host (`localhost`, `127.0.0.0/8`, `[::1]`). URLs with credentials or a fragment are refused. - Redirects are not followed; a 3xx response is a failed attempt. - Each request has a deadline (`requestTimeoutMs`), and at most `maxResponseBytes` of the response body is read. - Secrets are never logged, returned by `describe()`, or included in reports or error messages. **The URL is an operator decision.** Nothing here blocks private or link-local addresses (such as `10.0.0.1` or `169.254.169.254`), loopback over `https:`, or a public name that resolves to a private address, and nothing pins the address at connect time. That is fine for a URL you configure yourself. Do not accept endpoint URLs from tenants unless every request leaves through an egress proxy or network policy that enforces which addresses may be reached. ## Tenant and environment isolation [#tenant-and-environment-isolation] A subscription is bound to the tenant of its first drain, for every resource type at once. A drain for another tenant throws (reported as `failed: ["drain"]`), and the worker port is bound to the endpoint's tenant: it claims only that tenant's entries, and the sender refuses, as a dead letter with reason `tenant-mismatch`, any entry whose event names another tenant. So reusing an endpoint ID for another tenant never sends the first tenant's changes to it. On PostgreSQL a drain also compares the tenant ID exactly as stored: where the tenant column is a `uuid`, another spelling of the same value (such as upper case) is refused with code `tenant-spelling`, so use the canonical lowercase form. Every subscription, cursor and queue row carries the store's environment ID; a store for another environment never claims, settles or requeues them, and the environment ID is part of every body and of the signed bytes. Give each environment its own audit tables: two environments that drain the same audit table each deliver its changes under their own environment ID. ## @rolebook/http/webhooks [#rolebookhttpwebhooks] The body, signature and verification helper. This entry has no runtime dependency on `@rolebook/sharing` and needs only Web Crypto. ### `serializeAccessChangeWebhook` [#serializeaccesschangewebhook] ```ts api="@rolebook/http/webhooks" function serializeAccessChangeWebhook(input: { readonly id: string; readonly environmentId: string; readonly event: unknown; }): string; ``` The exact request body for one access change. Only allow-listed fields are copied, in a fixed order, so the same input always gives the same string. Throws a `TypeError` for an event, delivery ID or environment ID that does not validate, or an action that is not an access change. ### `timingSafeEqualBytes` [#timingsafeequalbytes] ```ts api="@rolebook/http/webhooks" function timingSafeEqualBytes(left: Uint8Array, right: Uint8Array): boolean; ``` Constant-time comparison of two byte arrays; arrays of different lengths are unequal. ### `signAccessChangeWebhook` [#signaccesschangewebhook] ```ts api="@rolebook/http/webhooks" function signAccessChangeWebhook(input: { readonly secret: string; readonly id: string; readonly timestamp: number; readonly body: string; }): Promise; ``` The `rolebook-webhook-signature` value for one request: `v1=` and the hex HMAC-SHA-256 of `..`. Throws on a secret outside 32–512 characters or a negative timestamp. ### `verifyAccessChangeWebhook` [#verifyaccesschangewebhook] ```ts api="@rolebook/http/webhooks" function verifyAccessChangeWebhook(input: { readonly secret: string | readonly string[]; readonly headers: WebhookHeaderSource; readonly body: string | Uint8Array; readonly toleranceSeconds?: number; readonly now?: () => number; }): Promise; ``` Checks the signature against every given secret (1–8, for rotation) in constant time, the timestamp against `toleranceSeconds` (default 300, 1–3600) either side of `now`, the body size, and that the body is an allow-listed access change whose `id` matches the header. The body is read once: bytes are copied, size-checked and decoded as strict UTF-8; a string is used as given. Throws on invalid options; answers a failed check with `ok: false` and a reason. ### `WEBHOOK_ID_HEADER` [#webhook_id_header] ```ts api="@rolebook/http/webhooks" const WEBHOOK_ID_HEADER = "rolebook-webhook-id"; ``` Header carrying the stable delivery ID. ### `WEBHOOK_TIMESTAMP_HEADER` [#webhook_timestamp_header] ```ts api="@rolebook/http/webhooks" const WEBHOOK_TIMESTAMP_HEADER = "rolebook-webhook-timestamp"; ``` Header carrying the signing time in Unix seconds. ### `WEBHOOK_SIGNATURE_HEADER` [#webhook_signature_header] ```ts api="@rolebook/http/webhooks" const WEBHOOK_SIGNATURE_HEADER = "rolebook-webhook-signature"; ``` Header carrying one or more space-separated `v1=` signatures. ### `DEFAULT_WEBHOOK_TOLERANCE_SECONDS` [#default_webhook_tolerance_seconds] ```ts api="@rolebook/http/webhooks" const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300; ``` The verifier's default timestamp tolerance. ### `MAX_WEBHOOK_TOLERANCE_SECONDS` [#max_webhook_tolerance_seconds] ```ts api="@rolebook/http/webhooks" const MAX_WEBHOOK_TOLERANCE_SECONDS = 3600; ``` The largest `toleranceSeconds` the verifier accepts. ### `MIN_WEBHOOK_SECRET_LENGTH` [#min_webhook_secret_length] ```ts api="@rolebook/http/webhooks" const MIN_WEBHOOK_SECRET_LENGTH = 32; ``` Shortest secret the sender and verifier accept. ### `MAX_WEBHOOK_SECRET_LENGTH` [#max_webhook_secret_length] ```ts api="@rolebook/http/webhooks" const MAX_WEBHOOK_SECRET_LENGTH = 512; ``` Longest secret the sender and verifier accept. ### `MAX_WEBHOOK_BODY_BYTES` [#max_webhook_body_bytes] ```ts api="@rolebook/http/webhooks" const MAX_WEBHOOK_BODY_BYTES: number; ``` Bodies larger than this are refused by the verifier before parsing. ### `WireAccessChangeWebhook` [#wireaccesschangewebhook] ```ts api="@rolebook/http/webhooks" interface WireAccessChangeWebhook { readonly id: string; readonly type: AccessChangeAction; readonly environmentId: string; readonly event: WireAuditEvent; } ``` One request body. `event` is a `WireAuditEvent`. ### `ACCESS_CHANGE_WEBHOOK_TYPES` [#access_change_webhook_types] ```ts api="@rolebook/http/webhooks" const ACCESS_CHANGE_WEBHOOK_TYPES: readonly AccessChangeAction[]; ``` The six `type` values a body can have. ### `AccessChangeWebhookVerification` [#accesschangewebhookverification] ```ts api="@rolebook/http/webhooks" type AccessChangeWebhookVerification = { readonly ok: true; readonly id: string; readonly timestamp: number; readonly webhook: WireAccessChangeWebhook; } | { readonly ok: false; readonly reason: "missing-header" | "malformed-header" | "stale-timestamp" | "invalid-signature" | "malformed-body"; }; ``` The verifier's answer. ### `WebhookHeaderSource` [#webhookheadersource] ```ts api="@rolebook/http/webhooks" type WebhookHeaderSource = { get(name: string): string | null; } | Readonly>; ``` A `Headers` object or a plain record of header values; names are compared case-insensitively. ## @rolebook/server/webhooks [#rolebookserverwebhooks] The sender: configuration, URL checks, signing, retry policy and the drain-and-deliver loop. ### `webhookRetryDelayMs` [#webhookretrydelayms] ```ts api="@rolebook/server/webhooks" function webhookRetryDelayMs(attempt: number, baseMs: number, capMs: number): number; ``` The wait after failed attempt `attempt` (1-based): `min(capMs, baseMs × 2^(attempt−1))`. ### `validateWebhookUrl` [#validatewebhookurl] ```ts api="@rolebook/server/webhooks" function validateWebhookUrl(value: unknown, label?: string): string; ``` Validates and normalizes an endpoint URL: absolute, `https:` or loopback `http:`, no credentials, no fragment. The error message never echoes the value. ### `createWebhookDelivery` [#createwebhookdelivery] ```ts api="@rolebook/server/webhooks" function createWebhookDelivery(options: WebhookDeliveryOptions): WebhookDelivery; ``` Validates the options and returns the delivery loop. Throws `WebhookConfigurationError` before any storage or network call. ### `webhookConfigurationFromEnv` [#webhookconfigurationfromenv] ```ts api="@rolebook/server/webhooks" function webhookConfigurationFromEnv(env: Readonly>): WebhookEnvConfiguration | undefined; ``` Reads `ROLEBOOK_WEBHOOK_*`. Returns `undefined` when none is set; throws `WebhookConfigurationError` on a partial or malformed configuration. It checks presence, format and the `ROLEBOOK_WEBHOOK_INTERVAL_MS` range; the other numeric ranges are checked when the delivery is built (`createWebhookDelivery`, which `webhookDeliveryFromEnv` calls and whose errors it reports under the variable's name). ### `webhookDeliveryFromEnv` [#webhookdeliveryfromenv] ```ts api="@rolebook/server/webhooks" function webhookDeliveryFromEnv(input: { readonly env: Readonly>; readonly store: AccessChangeDeliveryStore; readonly fetch?: typeof fetch; }): { readonly delivery: WebhookDelivery; readonly intervalMs: number; } | undefined; ``` `webhookConfigurationFromEnv` followed by `createWebhookDelivery` with one endpoint. Returns `undefined` when webhooks are not configured. ### `WebhookEndpoint` [#webhookendpoint] ```ts api="@rolebook/server/webhooks" interface WebhookEndpoint { readonly id: string; readonly tenantId: string; readonly url: string; readonly secret: string; } ``` One receiver, bound to one tenant of the store's environment. ### `WebhookDeliveryOptions` [#webhookdeliveryoptions] ```ts api="@rolebook/server/webhooks" interface WebhookDeliveryOptions { readonly store: AccessChangeDeliveryStore; readonly endpoints: readonly WebhookEndpoint[]; readonly maxAttempts?: number; readonly backoffBaseMs?: number; readonly backoffCapMs?: number; readonly requestTimeoutMs?: number; readonly maxResponseBytes?: number; readonly batchSize?: number; readonly leaseMs?: number; readonly drainLimit?: number; readonly deliveredRetentionMs?: number; readonly pruneLimit?: number; readonly fetch?: typeof fetch; readonly now?: () => number; } ``` Delivery options; see the defaults in `WEBHOOK_DEFAULTS`. `leaseMs` must exceed `requestTimeoutMs` by more than one second. `deliveredRetentionMs` and `pruneLimit` bound how long delivered entries are kept and how many each pass deletes. ### `WebhookConfigurationError` [#webhookconfigurationerror] ```ts api="@rolebook/server/webhooks" class WebhookConfigurationError extends Error { constructor(message: string); } ``` Thrown for an invalid configuration. Messages name the option or variable, never its value. ### `WEBHOOK_DEFAULTS` [#webhook_defaults] ```ts api="@rolebook/server/webhooks" const WEBHOOK_DEFAULTS: Readonly<{ maxAttempts: 300; backoffBaseMs: 1000; backoffCapMs: 300000; requestTimeoutMs: 10000; maxResponseBytes: 65536; batchSize: 16; leaseMs: 60000; drainLimit: 100; deliveredRetentionMs: 86400000; pruneLimit: 100; intervalMs: 1000; }>; ``` Default option values. ### `WebhookEndpointReport` [#webhookendpointreport] ```ts api="@rolebook/server/webhooks" interface WebhookEndpointReport { readonly endpointId: string; readonly enqueued: number; readonly outcomes: readonly OutboxDeliveryOutcome[]; readonly pruned: number; readonly failed?: readonly WebhookStage[]; readonly errors?: readonly WebhookStageError[]; readonly deadLettered?: readonly string[]; } ``` One endpoint's result for one pass. `failed` lists the stages that threw, in order, and `errors` says why for each, as a `WebhookStageError`. `deadLettered` lists the delivery IDs the store set aside while claiming because their stored entry did not match its row. A failed drain does not stop delivery of entries already queued. ### `WebhookStage` [#webhookstage] ```ts api="@rolebook/server/webhooks" type WebhookStage = "drain" | "delivery" | "prune"; ``` A stage of one endpoint's pass, as listed in `WebhookEndpointReport.failed`. ### `WebhookStageError` [#webhookstageerror] ```ts api="@rolebook/server/webhooks" interface WebhookStageError { readonly stage: WebhookStage; readonly code: AccessChangeDeliveryErrorCode | "unexpected"; readonly message?: string; } ``` Why a stage failed. A store's `AccessChangeDeliveryError` keeps its `code` and message, which carry no row data; any other error is `unexpected`, without its message, which could hold driver or network details. ### `WebhookDeliveryReport` [#webhookdeliveryreport] ```ts api="@rolebook/server/webhooks" interface WebhookDeliveryReport { readonly endpoints: readonly WebhookEndpointReport[]; } ``` The result of one pass, one report per endpoint, in configuration order. ### `WebhookDelivery` [#webhookdelivery] ```ts api="@rolebook/server/webhooks" interface WebhookDelivery { runOnce(input?: { readonly signal?: AbortSignal; }): Promise; run(input: { readonly signal: AbortSignal; readonly intervalMs?: number; readonly onReport?: (report: WebhookDeliveryReport) => void | Promise; }): Promise; describe(): readonly { readonly id: string; readonly tenantId: string; readonly host: string; }[]; } ``` `runOnce` runs one pass and rejects when a pass is already running; `run` repeats passes until its signal aborts, gives each report to `onReport` (a reporter that throws does not stop the loop), and returns promptly when the signal aborts during a pass; `describe` lists endpoint IDs, tenants and hosts. ### `WEBHOOK_ENV` [#webhook_env] ```ts api="@rolebook/server/webhooks" const WEBHOOK_ENV: Readonly<{ url: "ROLEBOOK_WEBHOOK_URL"; secret: "ROLEBOOK_WEBHOOK_SECRET"; tenantId: "ROLEBOOK_WEBHOOK_TENANT_ID"; endpointId: "ROLEBOOK_WEBHOOK_ENDPOINT_ID"; maxAttempts: "ROLEBOOK_WEBHOOK_MAX_ATTEMPTS"; backoffBaseMs: "ROLEBOOK_WEBHOOK_BACKOFF_BASE_MS"; backoffCapMs: "ROLEBOOK_WEBHOOK_BACKOFF_CAP_MS"; requestTimeoutMs: "ROLEBOOK_WEBHOOK_TIMEOUT_MS"; maxResponseBytes: "ROLEBOOK_WEBHOOK_MAX_RESPONSE_BYTES"; deliveredRetentionMs: "ROLEBOOK_WEBHOOK_DELIVERED_RETENTION_MS"; intervalMs: "ROLEBOOK_WEBHOOK_INTERVAL_MS"; }>; ``` The environment variable names `webhookConfigurationFromEnv` reads. ### `WebhookEnvConfiguration` [#webhookenvconfiguration] ```ts api="@rolebook/server/webhooks" interface WebhookEnvConfiguration { readonly endpoint: WebhookEndpoint; readonly options: Omit; readonly intervalMs: number; } ``` An environment configuration whose presence, format and interval are checked; its other numeric ranges are checked by `createWebhookDelivery`. # Subjects, principals, and assignments (/docs/subjects-and-assignments) > Who is asking, which groups they act through, and which scoped roles apply. A binding is everything Rolebook needs to know about the caller for one request: the **subject**, its optional group **principals**, its role **assignments**, and request **context**. ```ts prelude=core const bound = authorizer.bind({ subject: { type: "user", id: "user_123", attributes: { mfa: true, suspended: false } }, principals: [{ type: "team", id: "design" }], assignments: [ { subject: { type: "team", id: "design" }, role: "workspace_editor", scope: { resource: { type: "workspace", id: "ws_456" }, appliesTo: "descendants" }, }, ], context: { requestId: "req_789", ipCountry: "NL" }, }); ``` A binding accepts exactly these four keys. An unknown key denies every check on it with `INVALID_REQUEST`, so map database rows to these fields rather than spreading them. ## Subject [#subject] A subject has a required `type` (a [policy name](/docs/policies#names)), an opaque application `id` (a non-empty string of up to 128 characters), and optional `attributes`. It never contains roles. - `attributes` is a plain object of informational facts. Conditions read them directly under the `subject` root: `subject.mfa`, not `subject.attributes.mfa`. - `type` and `id` are reserved fact names. An attribute named `type` or `id` cannot replace them. - A subject with any other key, a missing `type` or `id`, or unsafe values is denied with `INVALID_SUBJECT`. Unsafe values include an attribute key outside the [policy-name grammar](/docs/policies#names) (`_id`, `$ref`, a key with a space or a non-ASCII letter), a `Date` or other non-plain object, a string over 512 characters, more than 64 keys, or an `undefined` value. See [keys and values inside snapshots](/docs/limits#keys-and-values-inside-snapshots). Attributes are inputs you vouch for. Load them from the authenticated session or an authoritative store, never from the request body. ## Assignments [#assignments] An assignment gives one subject one role on one scope resource: ```ts import type { RoleAssignment } from "rolebook"; const assignment: RoleAssignment = { subject: { type: "user", id: "user_123" }, role: "workspace_editor", scope: { resource: { type: "workspace", id: "ws_456" }, appliesTo: "descendants", }, }; ``` - `subject` is a `{ type, id }` reference. An assignment applies when it names the bound subject or one of the binding's principals. - `role` must name a role in the policy. - `scope.resource.type` must equal the role's `scope`. - `scope.appliesTo` is `"self"` or `"descendants"`; see [assignment scope](/docs/roles-and-scopes#assignment-scope-self-or-descendants). Rolebook does not store assignments. Load the subject's current assignments for the tenant on every request, from the same authoritative source your application trusts for membership. ### The whole collection is validated [#the-whole-collection-is-validated] Rolebook validates the entire assignment collection before it filters assignments by subject or scope. One malformed entry, unknown role, or role/scope mismatch fails the binding closed, even when that entry belongs to another subject or would not apply to the resource being checked: | Problem | Code | | --- | --- | | Not an array, more than 256 entries, an entry with a missing or extra key, unsafe values | `INVALID_ASSIGNMENT` | | A role the policy does not define | `UNKNOWN_ROLE` | | A scope resource type that does not match the role's scope | `INVALID_ASSIGNMENT` | A corrupted assignment set is not a safe basis for any decision, so Rolebook refuses to decide rather than skip the bad entry. ## Group principals [#group-principals] `principals` lists flat groups, such as teams, that your application has established the subject belongs to. An assignment to any of them applies to the subject: ```ts prelude=core const decision = authorizer .bind({ subject: { type: "user", id: "alice" }, principals: [{ type: "team", id: "design" }], assignments: [ { subject: { type: "team", id: "design" }, role: "workspace_editor", scope: { resource: { type: "workspace", id: "ws_456" }, appliesTo: "descendants" }, }, ], }) .check({ permission: "project:update", resource: project }); // decision.matched?.via -> { type: "team", id: "design" } ``` - At most `MAX_PRINCIPALS` (64) principals, each a `{ type, id }` reference with the subject grammar, all distinct, none equal to the subject. Anything else denies with `INVALID_SUBJECT`. - Principals are flat. A principal is only compared with assignment subjects and is never expanded into further principals, so groups cannot nest. - Deny wins across every applicable assignment, whichever principal contributed it. - Conditions still read the bound subject's own facts, not the group's. - `matched.via` (and each trace entry's `via`) names the group whose assignment contributed the rule. A rule the subject holds directly is attributed to the subject, with no `via`, even when a group also holds it. Group membership is an input like any assignment. Load it from an authoritative, tenant-scoped source. The [teams package](/docs/teams) does this for sharing. ## Context [#context] `context` is an optional plain object of request facts, read by conditions under the `context` root (`context.ipCountry`). Decide for each value whether a client could have influenced it before you put it there: a header the client controls is not evidence. An explicit `undefined` at the top level (`context: undefined`) counts as omitted. An `undefined` value **inside** context, subject attributes, an assignment, or a resource is not JSON-like and denies, so omit optional values rather than setting them to `undefined`. ## Reusing a validated collection [#reusing-a-validated-collection] Every `bind()` deep-copies and validates the assignments it receives, which makes a decision independent of anything the caller does afterwards. When the same assignments are bound again and again, for example in one binding per resource, `prepareAssignments()` does the copy once: ```ts prelude=core import { prepareAssignments, type RoleAssignment, type TrustedResource } from "rolebook"; declare const assignments: readonly RoleAssignment<"workspace_editor">[]; declare const candidates: readonly TrustedResource[]; const prepared = prepareAssignments(assignments) ?? assignments; for (const resource of candidates) { const decision = authorizer .bind({ subject: { type: "user", id: "user_123" }, assignments: prepared }) .check({ permission: "project:read", resource }); } ``` The result is a frozen copy Rolebook produced. A later `bind()` reuses it instead of copying it, but still validates every entry and still enforces the assignment count and size budgets across reused and fresh entries together. `prepareAssignments()` returns `undefined` for a collection that would not bind, so the caller keeps its original value and `bind()` returns its usual closed decision: preparation is an optimisation and never decides a request. The [ACL recipe](/docs/recipes/acl) walks one tenant, three people, a direct grant, a deny, and a revocation on this binding model. # @rolebook/teams API (/docs/teams/api) > Every export of @rolebook/teams and its /sql, /better-auth, and /sqlite entry points. Four entry points: `@rolebook/teams`, `@rolebook/teams/sql` (needs `@rolebook/sharing-postgres` for its types and fences), `@rolebook/teams/better-auth`, and [`@rolebook/teams/sqlite`](#rolebookteamssqlite) (needs `@rolebook/sharing-sqlite`). The package root does not load the SQLite module. Signatures are checked against the built declarations. See the [teams guide](/docs/teams#nested-lineage). ## Identity [#identity] ### `withTeams` [#withteams] ```ts api="@rolebook/teams" function withTeams( identity: TenantIdentityAdapter, options: TeamIdentityOptions, ): TenantIdentityAdapter; ``` Wraps any `TenantIdentityAdapter` so eligible individuals carry their current teams (after the base adapter's own `groups`, capped at 64), one `TEAM_MEMBERSHIP_AUTHORIZATION_FACT` per team, and one `TEAM_SET_AUTHORIZATION_FACT` with the whole set. Teams are looked up only for a principal the base adapter found eligible. A base principal with assignments but no subject-scoped authorization fact is returned as ineligible. A subject of the team type resolves as a group principal when `teamExists` says so. A team invitation matches a current tenant member who is a current member of that team. Throws `TypeError` for an invalid option, and when `teamSetFactType` equals `authorizationFactType`. ### `withTeamLineage` [#withteamlineage] ```ts api="@rolebook/teams" function withTeamLineage(identity: TenantIdentityAdapter, source: TeamLineageSource): TenantIdentityAdapter; ``` Nested-team wrapper. Effective groups replace the flat team list for `source.teamType`. More than 64 merged groups throws `HierarchyUnavailableError` `principal_cap`. More than 256 raw assignments throws `budget_exhausted`. A failed resolution throws `HierarchyUnavailableError`; it is not an ordinary eligibility denial. Invitation acceptance uses the groups and the lineage fact already on the principal. Wrapping the same team type with `withTeams()` throws `TypeError`. A remote identity host does not qualify as `source`: the storage adapter recomputes the same resolution inside the write transaction. ### `TeamLineageSource` [#teamlineagesource] ```ts api="@rolebook/teams" interface TeamLineageSource { readonly profileId: string; readonly teamType: string; readonly identityStability: "registry_incarnation" | "ids_never_reused"; readonly workspaceResourceType?: string; teamExists(input: { readonly tenantId: string; readonly team: ResourceRef; }): Promise; readGraphToken(input: { readonly tenantId: string; }): Promise; resolve(input: { readonly tenantId: string; readonly subject: ResourceRef; }): Promise; } ``` `identityStability` is an explicit declaration. `teamIdsGloballyUnique` is a different flag and does not set this. `registry_incarnation` means the directory stores an incarnation that changes when a team id is created again. `ids_never_reused` means this deployment does not reuse team ids; the directory then has no incarnation column. `readGraphToken` returns the lifecycle generation from the same snapshot as `resolve`, or `"absent"` when the graph row is absent. `workspaceResourceType` defaults to `"workspace"`. ### `resolveTeamLineage` [#resolveteamlineage] ```ts api="@rolebook/teams" function resolveTeamLineage(input: Parameters[0]): Promise; ``` Resolves one subject's direct groups through a reader bound to one snapshot. `ok: true` carries `direct` (direct memberships) and `groups` (direct memberships plus ancestors). `ok: false` carries `cause` (`graph_quarantined`, `graph_corrupt`, `principal_cap`, `registry_unavailable`, `lineage_invalid`, `budget`, or `profile_unbound`). The function does not grant a permission and does not write. ### `TeamIdentityOptions` [#teamidentityoptions] ```ts api="@rolebook/teams" interface TeamIdentityOptions { readonly teams: TeamRegistry; readonly teamType?: string; readonly workspaceResourceType?: string; readonly authorizationFactType?: string; readonly teamSetFactType?: string; } ``` `teams` (a `TeamRegistry`), `teamType` (default `"team"`), `workspaceResourceType` (default `"workspace"`), `authorizationFactType`, and `teamSetFactType`. ## Directories [#directories] ### `TeamDirectory` [#teamdirectory] ```ts api="@rolebook/teams" interface TeamDirectory { teamsOf(input: { readonly tenantId: string; readonly subject: ResourceRef; }): Promise; } ``` Answers which teams a subject belongs to in exactly one tenant. Implementations return a bounded, deduplicated, frozen list; throw `TeamDirectoryError` for a malformed record, more than 64 teams, or a subject type they do not answer for; and answer `[]` for a team subject. ### `TeamRegistry` [#teamregistry] ```ts api="@rolebook/teams" interface TeamRegistry extends TeamDirectory { teamExists(input: { readonly tenantId: string; readonly team: ResourceRef }): Promise; } ``` A directory that can also confirm a team exists in a tenant, under exactly the ID `teamsOf()` reports. ### `TeamMemberDirectory` [#teammemberdirectory] ```ts api="@rolebook/teams" interface TeamMemberDirectory { membersOf(input: { readonly tenantId: string; readonly group: ResourceRef; readonly limit: number; readonly cursor?: string; }): Promise; } ``` Pages the individual subjects that are direct members of exactly one team in exactly one tenant, for impact counting: ordered by subject ID as exact strings in the database's binary order, `limit` an integer from 1 to 100 (otherwise `TeamDirectoryError` `INVALID_LIMIT`). Teams are flat: no team is returned and nothing is expanded. A team that does not exist in the tenant, or exists only in another tenant, gives an empty exhausted page. A malformed row fails the whole call with `TEAM_RECORD_INVALID`, as does a cursor that is not a valid opaque ID. A full traversal contains a subject exactly when `teamsOf()` for that subject reports the team. Identities are canonical text: the column's PostgreSQL text form (`::text`) under the binary `"C"` collation, deduplicated before the limit, for `text`, `varchar`, `citext`, `uuid` and integer columns. The `group` ID matches only the canonical spelling `teamsOf()` reports, so an alias such as `007` for `7` or an upper-case UUID gets an empty exhausted page, and only canonical member IDs are listed. Pages are live, not a timeless inverse of `teamsOf()` under churn. It enumerates direct directory membership, not effective eligibility or access, and its count is not an exact effective-impact count. `membersOf()` is PostgreSQL only: the SQL and Better Auth directories implement it, and there is no SQLite `membersOf()`. That limit applies to `membersOf()` only: [`listAccess()`](/docs/sharing/listing#everything-the-actor-can-do-by-type) is available on the memory, PostgreSQL, and SQLite adapters, under [its own requirements](/docs/sharing/listing#what-a-consistent-page-requires). It is a separate interface, so `TeamDirectory` and `TeamRegistry` implementations stay valid without it. It is a trusted server-side directory API, like `teamsOf()`, and **performs no authorization**: the caller must authorize the request. `nextCursor` is the last returned subject ID, **not sealed** and not bound to the tenant or team, so never accept it from an untrusted client. It is not a "who can access this resource" query. ### `TeamMembersPage` [#teammemberspage] ```ts api="@rolebook/teams" interface TeamMembersPage { readonly members: readonly ResourceRef[]; readonly nextCursor?: string; readonly exhausted: boolean; } ``` ### `TeamRef` [#teamref] ```ts api="@rolebook/teams" type TeamRef = GroupPrincipalRef; ``` A team principal: a `GroupPrincipalRef`, so ownership paths reject it at compile time. ### `resolveTeams` [#resolveteams] ```ts api="@rolebook/teams" function resolveTeams( directory: TeamDirectory, input: { readonly tenantId: string; readonly subject: ResourceRef; }, teamType?: string, ): Promise; ``` Calls a directory and validates its answer whatever the implementation: a dense array of at most 64 distinct references of the team type, none equal to the subject. Throws `TeamDirectoryError` otherwise. ### `teamRefsFromIds` [#teamrefsfromids] ```ts api="@rolebook/teams" function teamRefsFromIds(ids: readonly unknown[], teamType?: string): readonly TeamRef[]; ``` Validates raw team IDs into frozen, deduplicated `TeamRef`s, throwing `TeamDirectoryError` for a bad ID or more than 64. ### `TeamDirectoryError` [#teamdirectoryerror] ```ts api="@rolebook/teams" class TeamDirectoryError extends Error { readonly code: TeamDirectoryErrorCode; constructor(code: TeamDirectoryErrorCode, message: string); } ``` A team lookup that cannot be answered completely. It propagates out of sharing operations; treat it as an application fault. ### `TeamDirectoryErrorCode` [#teamdirectoryerrorcode] ```ts api="@rolebook/teams" type TeamDirectoryErrorCode = | "TEAM_RECORD_INVALID" | "TOO_MANY_TEAMS" | "UNSUPPORTED_SUBJECT_TYPE" | "INVALID_LIMIT"; ``` `INVALID_LIMIT` is thrown only by `membersOf()`. ## Principal sets [#principal-sets] ### `principalSet` [#principalset] ```ts api="@rolebook/teams" function principalSet(input: { readonly subject: ResourceRef; readonly teams: readonly ResourceRef[]; }): PrincipalSet; ``` The principal set for one request: `principals` for Rolebook's `bind()` and `requestingPrincipals` (subject first) for sharing reads. Throws for a malformed subject, a team equal to the subject, a repeated team, or more than 64 teams. ### `PrincipalSet` [#principalset-1] ```ts api="@rolebook/teams" interface PrincipalSet { readonly subject: ResourceRef; readonly principals: readonly TeamRef[]; readonly requestingPrincipals: readonly ResourceRef[]; } ``` ### `encodeTeamSet` [#encodeteamset] ```ts api="@rolebook/teams" function encodeTeamSet(teamIds: readonly string[]): string; ``` The canonical team-set encoding a fence compares: a JSON array of the distinct IDs in ascending UTF-16 code-unit order (`"[]"` for none). ## Constants [#constants] ### `TEAM_SUBJECT_TYPE` [#team_subject_type] ```ts api="@rolebook/teams" const TEAM_SUBJECT_TYPE = "team"; ``` The default team subject type. ### `TEAM_MEMBERSHIP_AUTHORIZATION_FACT` [#team_membership_authorization_fact] ```ts api="@rolebook/teams" const TEAM_MEMBERSHIP_AUTHORIZATION_FACT = "rolebook.teams.team-member.v1"; ``` The fact type for one team membership that may have authorized a mutation. ### `TEAM_SET_AUTHORIZATION_FACT` [#team_set_authorization_fact] ```ts api="@rolebook/teams" const TEAM_SET_AUTHORIZATION_FACT = "rolebook.teams.team-set.v1"; ``` The fact type for a subject's complete team set; its `values` are `teamType` and `teamIds`. ### `MAX_TEAMS_PER_SUBJECT` [#max_teams_per_subject] ```ts api="@rolebook/teams" const MAX_TEAMS_PER_SUBJECT: typeof MAX_GROUP_PRINCIPALS; ``` 64: Rolebook's principal cap. ## @rolebook/teams/sql [#rolebookteamssql] `import { ... } from "@rolebook/teams/sql"`: application-owned team tables, read through the `@rolebook/sharing-postgres` executor. ### `createSqlTeamDirectory` [#createsqlteamdirectory] ```ts api="@rolebook/teams/sql" function createSqlTeamDirectory( options: SqlTeamDirectoryOptions, ): TeamRegistry & TeamMemberDirectory; ``` A `TeamRegistry` and `TeamMemberDirectory` over application-owned team tables (default `DEFAULT_SQL_TEAM_TABLES`). Every lookup names the explicit tenant and subject. `membersOf()` joins a membership to its team on the membership tenant when the table has one, matches the team ID exactly, and orders subject IDs under the binary `"C"` collation; every value is a bound parameter. Throws `TypeError` when `member.tenantColumn` is missing without `teamIdsGloballyUnique: true`, or when `subjectType` equals `teamType`. ### `SqlTeamDirectoryOptions` [#sqlteamdirectoryoptions] ```ts api="@rolebook/teams/sql" interface SqlTeamDirectoryOptions { readonly executor: ParameterizedSqlExecutor; readonly tables?: SqlTeamTables; } ``` ### `SqlTeamTables` [#sqlteamtables] ```ts api="@rolebook/teams/sql" interface SqlTeamTables { readonly team: { readonly table: QualifiedIdentifier; readonly idColumn: string; readonly tenantColumn: string; }; readonly member: { readonly table: QualifiedIdentifier; readonly teamIdColumn: string; readonly subjectIdColumn: string; readonly tenantColumn?: string; }; readonly teamIdsGloballyUnique?: boolean; readonly subjectType?: string; readonly teamType?: string; } ``` Where teams and memberships live: tables, ID, tenant, and subject columns, `teamIdsGloballyUnique`, `subjectType` (default `"user"`), `teamType`. ### `DEFAULT_SQL_TEAM_TABLES` [#default_sql_team_tables] ```ts api="@rolebook/teams/sql" const DEFAULT_SQL_TEAM_TABLES: SqlTeamTables; ``` `team(tenant_id, id)` and `team_member(tenant_id, team_id, user_id)`. ### `createPostgresTeamFences` [#createpostgresteamfences] ```ts api="@rolebook/teams/sql" function createPostgresTeamFences(options: PostgresTeamFenceOptions): PostgresTeamFences; ``` Team-aware `lockEligibleSubjects` and `revalidateAuthorizationFacts` for `createPostgresSharingAdapter()`, composed with your own fences. See [fences](/docs/teams#fences-are-required). ### `PostgresTeamFenceOptions` [#postgresteamfenceoptions] ```ts api="@rolebook/teams/sql" interface PostgresTeamFenceOptions { readonly tables?: SqlTeamTables; readonly eligibility: PostgresEligibilityFence; readonly authorizationFacts?: PostgresAuthorizationFactFence; readonly warn?: (message: string) => void; readonly factType?: string; readonly teamSetFactType?: string; } ``` `eligibility` (required), `authorizationFacts`, `tables`, `warn` (default `console.warn`), `factType`, `teamSetFactType`. ### `PostgresTeamFences` [#postgresteamfences] ```ts api="@rolebook/teams/sql" interface PostgresTeamFences { readonly lockEligibleSubjects: PostgresEligibilityFence; readonly revalidateAuthorizationFacts: PostgresAuthorizationFactFence; } ``` Spread into `createPostgresSharingAdapter()` options. ### `createPostgresTeamLineageDirectory` [#createpostgresteamlineagedirectory] ```ts api="@rolebook/teams/sql" function createPostgresTeamLineageDirectory(tables: SqlTeamTables, options: { readonly identityStability: "registry_incarnation" | "ids_never_reused"; readonly incarnationColumn?: string; }): Readonly<{ readDirectTeams(input: { readonly executor: ParameterizedSqlExecutor; readonly tenantId: string; readonly subject: ResourceRef; readonly lock?: "share" | "none"; }): Promise; readEndpoint(input: { readonly executor: ParameterizedSqlExecutor; readonly tenantId: string; readonly group: ResourceRef; readonly lock?: "share" | "none"; }): Promise<{ present: false; incarnation?: never; } | { present: true; incarnation: null; } | { present: true; incarnation: string; }>; }>; ``` Transactional directory for a nested-team profile. Pass it as `groupGraph.directory` on `createPostgresSharingAdapter()`. `readDirectTeams` returns the configured individual type's direct teams, and returns `[]` for the configured team type. An unsupported third type throws `HierarchyUnavailableError` `lineage_invalid`. More than 64 distinct teams throws `principal_cap`. A malformed registry team id throws `registry_unavailable`. A driver error propagates unchanged. `lock: "share"` takes the membership-table share lock used inside a write. `lock: "none"` is the read-only snapshot and takes no row lock. `registry_incarnation` requires `incarnationColumn`. `ids_never_reused` rejects an incarnation column. `teamIdsGloballyUnique` does not imply `ids_never_reused`. `readEndpoint` answers whether that team id exists in the tenant. Under `registry_incarnation` the incarnation is the column text; a missing or empty incarnation is `{ present: false }`. ## @rolebook/teams/better-auth [#rolebookteamsbetter-auth] `import { ... } from "@rolebook/teams/better-auth"`: the same directory and fences over Better Auth's `team` and `teamMember` tables. ### `createBetterAuthTeamDirectory` [#createbetterauthteamdirectory] ```ts api="@rolebook/teams/better-auth" function createBetterAuthTeamDirectory( options: { readonly executor: ParameterizedSqlExecutor; } & BetterAuthTeamTableOptions, ): TeamRegistry & TeamMemberDirectory; ``` A team directory over Better Auth's tables. Never consults the active organization or team. It implements `membersOf()`: `team` carries the organization and `teamMember.teamId` references the team's globally unique ID, so one team's members are an exact, organization-scoped, ordered page. ### `createBetterAuthTeamFences` [#createbetterauthteamfences] ```ts api="@rolebook/teams/better-auth" function createBetterAuthTeamFences( options: Omit & BetterAuthTeamTableOptions, ): PostgresTeamFences; ``` `createPostgresTeamFences()` over Better Auth's tables. ### `betterAuthTeamTables` [#betterauthteamtables] ```ts api="@rolebook/teams/better-auth" function betterAuthTeamTables(options?: BetterAuthTeamTableOptions): SqlTeamTables; ``` The `SqlTeamTables` for Better Auth's `team` and `teamMember` tables, with `teamIdsGloballyUnique: true`. ### `BetterAuthTeamTableOptions` [#betterauthteamtableoptions] ```ts api="@rolebook/teams/better-auth" interface BetterAuthTeamTableOptions { readonly schema?: string; readonly teamTable?: string; readonly teamMemberTable?: string; readonly fields?: { readonly teamId?: string; readonly teamOrganizationId?: string; readonly memberTeamId?: string; readonly memberUserId?: string; }; readonly subjectType?: string; readonly teamType?: string; } ``` Optional `schema`, `teamTable`, `teamMemberTable`, `fields`, `subjectType`, and `teamType`. ## @rolebook/teams/sqlite [#rolebookteamssqlite] `import { ... } from "@rolebook/teams/sqlite"`. This entry loads `@rolebook/sharing-sqlite` and is not imported by the package root. SQLite has no roles; keep a single writer for the database before activating a graph. The directory reads direct memberships inside the caller's transaction. `BEGIN IMMEDIATE` is the write exclusion, so these methods take no `lock` argument. ### `SqliteTeamTables` [#sqliteteamtables] ```ts api="@rolebook/teams/sqlite" interface SqliteTeamTables { readonly teamTable: string; readonly memberTable: string; readonly teamIdColumn?: string; readonly memberTeamIdColumn?: string; readonly tenantColumn?: string; readonly memberTenantColumn?: string; readonly subjectIdColumn?: string; readonly subjectType?: string; readonly teamType?: string; readonly identityStability: "registry_incarnation" | "ids_never_reused"; readonly incarnationColumn?: string; } ``` `teamIdColumn` defaults to `id`. `memberTeamIdColumn` defaults to `team_id`, which is the membership column, not the team table's id column. `tenantColumn` and `memberTenantColumn` default to `tenant_id`. `subjectIdColumn` defaults to `user_id`. `subjectType` defaults to `"user"` and must differ from `teamType` (default `"team"`). `registry_incarnation` requires `incarnationColumn`. ### `createSqliteTeamLineageDirectory` [#createsqliteteamlineagedirectory] ```ts api="@rolebook/teams/sqlite" function createSqliteTeamLineageDirectory(tables: SqliteTeamTables): Readonly<{ readDirectTeams(input: { readonly executor: ParameterizedSqliteExecutor; readonly tenantId: string; readonly subject: ResourceRef; }): Promise; readEndpoint(input: { readonly executor: ParameterizedSqliteExecutor; readonly tenantId: string; readonly group: ResourceRef; }): Promise<{ present: false; incarnation?: never; } | { present: true; incarnation: null; } | { present: true; incarnation: string; }>; }>; ``` `readDirectTeams` returns the configured individual type's direct teams. It returns `[]` for the configured team type. An unsupported third type throws `HierarchyUnavailableError` `lineage_invalid`. More than 64 distinct teams throws `principal_cap`. A malformed registry team id throws `registry_unavailable`. A driver error propagates unchanged. `readEndpoint` confirms the team row in the named tenant. Pass the directory as `groupGraph.directory` on `createSqliteSharingAdapter()`, with the same `identityStability` and `teamType`. There is no SQLite `membersOf()`; direct membership pages stay on the PostgreSQL directories. # Teams (/docs/teams) > @rolebook/teams: flat, bounded team principals for sharing, with directories, an identity wrapper, and fences. Share a resource with a team and every current member inherits that access; remove someone from the team and their team-derived access ends on their next request, while a direct grant to them still applies. `@rolebook/teams` supplies the pieces: team directories for Better Auth's organization teams and for application-owned tables, the `withTeams()` identity wrapper, PostgreSQL fences, and an optional nested-lineage directory on [`/sql`](/docs/teams/api#createpostgresteamlineagedirectory) and [`/sqlite`](/docs/teams/api#rolebookteamssqlite). Flat `withTeams()` remains the default. ```ts prelude=sharing const owner = { type: "user", id: "owner_1" }; const alice = { type: "user", id: "alice" }; // Share "Brand Assets" with the Design team as editors. await sharing.forTenant({ tenantId, actor: owner }).execute({ kind: "grantRole", resource: { type: "project", id: "brand_assets" }, subject: { type: "team", id: "design" }, role: "editor", idempotencyKey: "share-brand-assets", }); const decision = await sharing .forTenant({ tenantId, actor: alice }) .authorize({ resource: { type: "project", id: "brand_assets" }, action: "update" }); decision.decision?.matched?.via; // { type: "team", id: "design" }: "editor through Design team" ``` ## Rules [#rules] - **Flat.** Teams contain individuals, never other teams. Rolebook compares principals with assignment subjects and never expands them. [Nested lineage](#nested-lineage) is a separate wrapper for one team type. - **Bounded.** At most `MAX_TEAMS_PER_SUBJECT` (64) teams per subject per tenant, Rolebook's `MAX_PRINCIPALS`. More, or a malformed team record, throws `TeamDirectoryError`: dropping a team silently could drop a deny. - **Tenant-scoped.** Every lookup takes an explicit tenant and subject; nothing comes from an active organization, active team, or session. - **Exact IDs.** A team matches only by the ID `teamsOf()` reports (for the SQL directories, the database's canonical text of the row's ID). Another spelling a `uuid`, `integer`, or case-insensitive column would coerce to the same team is refused as a target. - **Never actors, never owners.** A team resolves only as a grant or invitation target. `TeamRef` is branded so ownership paths reject it at compile time, the sharing module rejects it at runtime (`GROUP_CANNOT_OWN`), and the adapters reject it again (`group_owner`). - **No self-promotion.** An actor cannot grant, change, or invite a team it belongs to. It may un-share from its own team unless the team's role carries a deny. The owner may always remove such a deny. - **Denies on teams are the owner's.** Only the owner may grant, change, or invite a team to a role that carries a deny. Everything else follows the [delegation ceiling](/docs/sharing/delegation). - **Fenced.** Every team carries a `TEAM_MEMBERSHIP_AUTHORIZATION_FACT`, sent when that team holds a membership on the mutated resource or receives the invitation being accepted, and every principal carries one `TEAM_SET_AUTHORIZATION_FACT` with its complete team set, even an empty one. The fence rechecks membership under lock and reads the team set again in the write transaction; a changed set restarts the mutation, so a team joined after preflight, and any deny it carries, is accounted for. ## Wiring it up with Better Auth [#wiring-it-up-with-better-auth] Enable teams in Better Auth's organization plugin (`organization({ teams: { enabled: true } })`). The directory reads the plugin's `team` and `teamMember` tables through the same executor you give the PostgreSQL adapter: ```ts import { createSharing, defineSharing, type InvitationTokenProtector } from "@rolebook/sharing"; import { createBetterAuthIdentityAdapter, type BetterAuthDirectoryReader } from "@rolebook/sharing-better-auth"; import { createPostgresMembershipEligibilityFence, createPostgresSharingAdapter, type ParameterizedSqlExecutor, type PostgresResourceDescriptor, } from "@rolebook/sharing-postgres"; import { withTeams } from "@rolebook/teams"; import { createBetterAuthTeamDirectory, createBetterAuthTeamFences } from "@rolebook/teams/better-auth"; import type { RolebookPolicy } from "rolebook"; declare const executor: ParameterizedSqlExecutor; declare const projectTable: PostgresResourceDescriptor; declare const directory: BetterAuthDirectoryReader; declare const invitationTokens: InvitationTokenProtector; declare const policy: RolebookPolicy; const teams = createBetterAuthTeamDirectory({ executor, schema: "auth" }); const fences = createBetterAuthTeamFences({ schema: "auth", eligibility: createPostgresMembershipEligibilityFence({ table: ["auth", "member"], tenantColumn: "organizationId", subjectIdColumn: "userId", }), // authorizationFacts: createPostgresWorkspaceRoleAuthorizationFactFence({ ... }) when roles are mapped }); const projectAdapter = createPostgresSharingAdapter({ executor, resource: projectTable, ...fences }); const sharing = createSharing({ definition: defineSharing({ policy, resources: { project: { memberRoles: { editor: "project_editor" }, ownershipRole: "project_owner", actions: { update: "project:update" }, management: { members: "project:manage_members", invitations: "project:manage_invitations", ownership: "project:transfer_ownership", }, adapter: projectAdapter, }, }, }), identity: withTeams(createBetterAuthIdentityAdapter({ directory }), { teams }), invitationTokens, }); ``` Better Auth's `team` table is keyed by its primary key alone, so a team ID names one team across every organization; `betterAuthTeamTables()` declares `teamIdsGloballyUnique: true`. Defaults match Better Auth's names: `team(id, organizationId)` and `teamMember(teamId, userId)`. Pass `teamTable`, `teamMemberTable`, and `fields` if you renamed them, and add an index on `teamMember("userId")` if your schema lacks one. ## Application-owned tables [#application-owned-tables] Clerk Organizations have no teams, and other providers may not either. Keep your own tables and use the SQL directory from `@rolebook/teams/sql`: ```sql CREATE TABLE team ( tenant_id text NOT NULL, id text PRIMARY KEY, UNIQUE (tenant_id, id) ); CREATE TABLE team_member ( tenant_id text NOT NULL, team_id text NOT NULL, user_id text NOT NULL, PRIMARY KEY (team_id, user_id), FOREIGN KEY (tenant_id, team_id) REFERENCES team (tenant_id, id) ON DELETE CASCADE ); CREATE INDEX team_member_user_idx ON team_member (tenant_id, user_id); ``` ```ts import type { ParameterizedSqlExecutor, PostgresEligibilityFence } from "@rolebook/sharing-postgres"; import { createPostgresTeamFences, createSqlTeamDirectory, type SqlTeamTables } from "@rolebook/teams/sql"; declare const executor: ParameterizedSqlExecutor; declare const lockEligibleSubjects: PostgresEligibilityFence; const tables: SqlTeamTables = { team: { table: ["app", "team"], idColumn: "id", tenantColumn: "tenant_id" }, member: { table: ["app", "team_member"], teamIdColumn: "team_id", subjectIdColumn: "user_id", tenantColumn: "tenant_id", }, }; const teams = createSqlTeamDirectory({ executor, tables }); const fences = createPostgresTeamFences({ tables, eligibility: lockEligibleSubjects }); ``` `member.tenantColumn` ties each membership row to its team's tenant. Leave it out only when the team ID is unique across every tenant, and say so with `teamIdsGloballyUnique: true`; otherwise both builders throw a `TypeError`. Individuals default to subject type `"user"`; a directory asked about any other type throws `UNSUPPORTED_SUBJECT_TYPE` rather than answering no teams. ## Fences are required [#fences-are-required] Once identity is wrapped with `withTeams()`, the storage adapter **must** have team fences: `createPostgresTeamFences()` (or `createBetterAuthTeamFences()`) on PostgreSQL, or equivalent fences you write for [SQLite](/docs/sharing-sqlite/operations#teams-on-sqlite) and the memory adapter. Every mutation by a team-wrapped principal carries its team-set fact, so without a fact fence every such mutation fails closed with `NOT_TENANT_MEMBER`. The fences lock team rows `FOR SHARE` when a team is granted, recheck each team-membership fact by joining the membership to its team in the tenant, refuse membership facts without their subject's team-set fact, re-read the team set and return `"conflict"` when it changed, pass other facts to your existing fact fence (rejecting them without one, with a one-time `warn`), and refuse any team offered as an owner. Cost: one locked membership row per team that holds a membership on the mutated resource, plus one read of the actor's team set. ## Nested lineage [#nested-lineage] `withTeamLineage()` is a separate wrapper. It replaces the flat team list for one team type with the effective groups of a nested graph: a direct member of Design also receives Product when Design is linked under Product. Do not wrap that same team type with `withTeams()`. Direct membership stays in the membership table. `membersOf()` still pages those direct members and does not walk parents. On an enrolled PostgreSQL or SQLite tenant, the local identity projection carries eligibility, assignments, base facts, and groups of other types. Current membership of the configured team type comes from the transaction-local team directory and the graph in that snapshot, so the projection does not repeat the direct-team list. A same-team group carried from an earlier resolution, and a group-tagged fact for a team absent from this snapshot, does not add a member. A group the transaction explicitly retains stays. `withTeamLineage()` is standalone composition: it replaces that team type on the principal it returns and keeps the base principal's other groups. The SQL adapter qualifies the decision in the transaction. `subjectType` defaults to `"user"` and has to differ from `teamType` (default `"team"`). `readDirectTeams` returns the configured individual type's direct teams. It returns `[]` for the configured team type. An unsupported third type throws `HierarchyUnavailableError` `lineage_invalid`. `identityStability` is declared at the directory and again on the adapter's `groupGraph` option, as the same value. `registry_incarnation` stores an incarnation column and requires `incarnationColumn`. `ids_never_reused` means this deployment does not reuse team ids and rejects an incarnation column. `teamIdsGloballyUnique` does not select either value. PostgreSQL reads take `lock: "share"` inside a write (the membership table share lock) and `lock: "none"` on a read-only snapshot. SQLite reads run in the caller's `BEGIN IMMEDIATE` transaction and take no lock argument. Graph commands use that same choice of transaction. Build them with [`createPostgresGroupGraphControl()`](/docs/sharing-postgres/api#createpostgresgroupgraphcontrol) and [`createSqliteGroupGraphControl()`](/docs/sharing-sqlite/api#createsqlitegroupgraphcontrol). The lower PostgreSQL facade still accepts `serializableRetry`, and the lower SQLite facade still accepts `busyRetry`, when the caller already holds that facade's options. Strict SQLite listing pages still use the worker executor `createBunSqliteQueryExecutor()`; a graph command does not make another executor eligible for them. `readDirectTeams` returns at most 64 distinct teams. One more throws `HierarchyUnavailableError` `principal_cap`. A malformed registry team id is `registry_unavailable`. A database driver error propagates unchanged. `withTeamLineage` throws `principal_cap` when merged groups exceed 64, and `budget_exhausted` when the base principal carries more than 256 raw assignments. Flat team APIs still throw `TeamDirectoryError`. A graph command returns a Core denial as `status: "denied"` and leaves `decision` intact. A structural problem, such as a self-link, is `status: "refused"`. A resolution that cannot be completed throws `HierarchyUnavailableError` with a reason such as `graph_quarantined`, `lineage_invalid`, or `principal_cap`. `principal_cap` refuses the resolution and does not quarantine the graph. The command facade has no `confirm` method and no caller-selected authorizer. [`createPostgresGroupGraphControl()`](/docs/sharing-postgres/api#createpostgresgroupgraphcontrol) binds the compiled commands, the bootstrap provider, the policy store, the versioned sharing instance that reads that store, and the local identity projection. Optional `groupGraph.integrity` is that returned provider. When it is set, a read or mutation that finds structural corruption confirms the finding after the detecting transaction settles, and a failed confirmation makes no quarantine claim. ```ts import type { PostgresEligibilityFence, PostgresResourceDescriptor } from "@rolebook/sharing-postgres"; import { createPostgresSharingAdapter, type ParameterizedSqlExecutor } from "@rolebook/sharing-postgres"; import type { SqliteEligibilityFence, SqliteResourceDescriptor } from "@rolebook/sharing-sqlite"; import { createSqliteSharingAdapter, type ParameterizedSqliteExecutor } from "@rolebook/sharing-sqlite"; import { createPostgresTeamLineageDirectory, type SqlTeamTables } from "@rolebook/teams/sql"; import { createSqliteTeamLineageDirectory, type SqliteTeamTables } from "@rolebook/teams/sqlite"; declare const pg: ParameterizedSqlExecutor; declare const sqlite: ParameterizedSqliteExecutor; declare const lockEligibleSubjects: PostgresEligibilityFence; declare const sqliteEligibility: SqliteEligibilityFence; declare const projectTable: PostgresResourceDescriptor; declare const sqliteProject: SqliteResourceDescriptor; const postgresTables: SqlTeamTables = { team: { table: ["app", "team"], idColumn: "id", tenantColumn: "tenant_id" }, member: { table: ["app", "team_member"], teamIdColumn: "team_id", subjectIdColumn: "user_id", tenantColumn: "tenant_id", }, subjectType: "user", teamType: "team", }; const postgresDirectory = createPostgresTeamLineageDirectory(postgresTables, { identityStability: "registry_incarnation", incarnationColumn: "incarnation", }); const postgresAdapter = createPostgresSharingAdapter({ executor: pg, resource: projectTable, lockEligibleSubjects, groupGraph: { teamType: "team", identityStability: "registry_incarnation", directory: postgresDirectory, }, }); const sqliteTables: SqliteTeamTables = { teamTable: "team", memberTable: "team_member", subjectIdColumn: "user_id", subjectType: "service_account", teamType: "team", identityStability: "ids_never_reused", }; const sqliteDirectory = createSqliteTeamLineageDirectory(sqliteTables); const sqliteAdapter = createSqliteSharingAdapter({ executor: sqlite, resource: sqliteProject, lockEligibleSubjects: sqliteEligibility, groupGraph: { teamType: "team", identityStability: "ids_never_reused", directory: sqliteDirectory, }, }); const direct = await postgresDirectory.readDirectTeams({ executor: pg, tenantId: "ws_456", subject: { type: "user", id: "alice" }, lock: "none", }); const teamSubject = await sqliteDirectory.readDirectTeams({ executor: sqlite, tenantId: "ws_456", subject: { type: "team", id: "design" }, }); direct.length; teamSubject.length; postgresAdapter; sqliteAdapter; ``` ```ts import { HierarchyUnavailableError, type PolicyStore, type TenantIdentityAdapter } from "@rolebook/sharing"; import { createPostgresGroupGraphControl, createPostgresLocalIdentityProjection, type ParameterizedSqlExecutor, } from "@rolebook/sharing-postgres"; import { resolveTeamLineage, withTeamLineage, type TeamLineageSource } from "@rolebook/teams"; import type { RolebookPolicy } from "rolebook"; declare const identity: TenantIdentityAdapter; declare const source: TeamLineageSource; declare const executor: ParameterizedSqlExecutor; declare const policy: RolebookPolicy; declare const policyStore: PolicyStore; declare const sharing: object; declare const projection: ReturnType; const nested = withTeamLineage(identity, source); declare const lineageInput: Parameters[0]; const resolution = await resolveTeamLineage(lineageInput); if (resolution.ok) { resolution.direct; resolution.groups; } else { resolution.cause; } const graph = createPostgresGroupGraphControl({ executor, profile: { schema: "public", prefix: "rolebook_control" }, teamType: "team", identityStability: "registry_incarnation", actor: { type: "user", id: "ada" }, policy, bootstrapType: "tenant_admin", actions: { activate: "tenant_admin:graph_activate", link: "tenant_admin:graph_link", unlink: "tenant_admin:graph_unlink", repairUnlink: "tenant_admin:graph_repair_unlink", heightRepair: "tenant_admin:graph_height_repair", release: "tenant_admin:graph_release", }, controlBindingId: "control-binding", normalBindingId: "graph-binding", policyStore, sharing, identity: projection, bootstrap: { policyStore: { schema: "public", tablePrefix: "rolebook" }, descriptor: { resourceType: "tenant_admin", schema: "public", table: "tenant_admin", tenantColumn: "workspace_id", idColumn: "id", versionColumn: "version", incarnationColumn: "incarnation", }, }, registry() { return { async readEndpoint(group) { return group.id === "missing" ? { present: false as const } : { present: true as const, incarnation: "1" }; }, }; }, }); try { const outcome = await graph.facade.link( "ws_456", { type: "team", id: "design" }, { type: "team", id: "product" }, ); if (outcome.status === "denied") outcome.decision.allowed; if (outcome.status === "refused") outcome.refusal; if (outcome.status === "applied") outcome.effect; } catch (error) { if (error instanceof HierarchyUnavailableError) error.reason; } nested; graph.tables.names.groupGraph; ``` [`hierarchyControlTables()`](/docs/sharing-postgres/api#hierarchycontroltables) names the PostgreSQL control tables for a schema and prefix. [`hierarchyControlTables()`](/docs/sharing-sqlite/api#hierarchycontroltables) names the SQLite tables in `main`. Resource migrations install that same profile. SQLite construction is [`createSqliteGroupGraphControl()`](/docs/sharing-sqlite/api#createsqlitegroupgraphcontrol), with a table prefix instead of a schema. Activation stores the control configuration as `sha256:` plus 64 hexadecimal characters. Reordering graph-independent provider paths does not change that digest. A different action map is `profile_mismatch`. ## Directory failures throw [#directory-failures-throw] `TeamDirectoryError` (more than 64 teams, a malformed record, an unsupported subject type) propagates out of the operations that resolve the principal through this adapter, such as `authorize()` and `execute()`, as a rejected promise, even for resources the subject owns. It is an application data fault: catch it at your framework boundary, report it, and answer with a generic error. Listings behave differently with this adapter; see the next section. ## Listing with teams [#listing-with-teams] `withTeams()` returns an identity adapter with `resolvePrincipal` and `matchesInvitationRecipient`. That is all `authorize()` and commands need. [`listAccessible()` and `listAccess()`](/docs/sharing/listing#identity) also need evidence that the principal, teams included, belongs to the same point as the page, and the wrapper does not supply it. The identity adapter you pass to `createSharing()` supplies it in one of the [supported ways](/docs/sharing/listing#identity): - **A local identity projection** in the same database whose row carries the subject's teams in `groups`, named in the PostgreSQL or SQLite adapter's `pageIdentity` option. The identity adapter must then resolve principals from exactly that projection, so it cannot be the `withTeams()` wrapper over a provider, and the projection must be kept synchronized with your team store. - **Bracketed evidence:** an identity adapter of your own that implements `resolvePagePrincipal` over a source with a revision that never repeats and changes on every relevant change. - **A synchronous capture, with the in-memory adapter:** an identity adapter of your own that implements `capturePagePrincipal` and returns the complete principal, with its teams in `groups` and every expiry dependency, from in-process state in the same synchronous turn as the adapter's snapshot. It cannot await a directory or call a provider. Identity evidence is not enough on its own. `createPostgresTeamFences()` and `createBetterAuthTeamFences()` return an eligibility fence with no `readEligibleSubjects` twin, so a listing page also needs a `readEligibleSubjects` of your own that reads the same eligibility authority as the fence, inside the page. On a supported executor, a listing rejects with `AccessListingUnavailableError` and the reason `identity_evidence_missing` until both the identity evidence and that eligibility reader are in place. On an executor without listing pages (PGlite, or a custom PostgreSQL executor), it rejects with `capability_missing` first, before identity or eligibility is checked. ## Using teams with Rolebook directly [#using-teams-with-rolebook-directly] `principalSet()` builds the `principals` for Rolebook's `bind()` and the `requestingPrincipals` for sharing reads: ```ts import { createAuthorizer, type RoleAssignment, type RolebookPolicy, type TrustedResource } from "rolebook"; import { principalSet, type TeamDirectory } from "@rolebook/teams"; declare const directory: TeamDirectory; declare const policy: RolebookPolicy; declare const assignments: readonly RoleAssignment[]; declare const resource: TrustedResource; const subject = { type: "user", id: "alice" }; const teams = await directory.teamsOf({ tenantId: "ws_456", subject }); const { principals } = principalSet({ subject, teams }); const explanation = createAuthorizer(policy) .bind({ subject, principals, assignments }) .explain({ permission: "project:update", resource }); explanation.matched?.via; // the team whose assignment decided ``` ## Team members [#team-members] The SQL and Better Auth directories also implement [`TeamMemberDirectory`](/docs/teams/api#teammemberdirectory), a separate interface, so other directory implementations stay valid without it. `membersOf({ tenantId, group, limit, cursor })` pages the individual subjects that are direct members of exactly one team in exactly one tenant, ordered by subject ID in binary order, for impact counting: ```ts import type { ParameterizedSqlExecutor } from "@rolebook/sharing-postgres"; import { createBetterAuthTeamDirectory } from "@rolebook/teams/better-auth"; declare const executor: ParameterizedSqlExecutor; declare const tenantId: string; declare const teamId: string; const teams = createBetterAuthTeamDirectory({ executor, schema: "auth" }); let affected = 0; let cursor: string | undefined; do { const page = await teams.membersOf({ tenantId, group: { type: "team", id: teamId }, limit: 100, ...(cursor === undefined ? {} : { cursor }), }); affected += page.members.length; cursor = page.nextCursor; } while (cursor !== undefined); ``` Teams are flat, so no team is returned and nothing is expanded. An unknown team, or one of another tenant, gives an empty exhausted page; a malformed row fails the whole call with `TEAM_RECORD_INVALID`; a `limit` outside 1 to 100 throws `INVALID_LIMIT`. A subject is in the full traversal exactly when `teamsOf()` reports the team for it. It enumerates direct directory membership, not effective eligibility or access, so its count is not an exact count of the people a grant to the team affects. IDs are compared and listed in their canonical PostgreSQL text form: an alias of an existing team (`007` for `7`, an upper-case UUID) gets an empty page. `membersOf()` is PostgreSQL only: the SQL and Better Auth directories implement it, and there is no SQLite `membersOf()`. That limit applies to `membersOf()` only: `listAccess()` is available on the memory, PostgreSQL, and SQLite adapters, under [its own requirements](/docs/sharing/listing#what-a-consistent-page-requires). `membersOf()` **does not authorize**: like `teamsOf()`, it is a trusted server-side directory API, and the caller must authorize the request. Its `nextCursor` is the last returned subject ID, **not sealed** and bound to nothing, so never accept it from an untrusted client. It lists team membership only; it is not a "who can access this resource" query. ## Deleting a team [#deleting-a-team] When a team is deleted, `teamsOf()` stops returning it and `teamExists()` says it is gone, so its memberships grant nothing, its pending invitations can no longer be accepted, and it cannot be granted again. Its stale membership rows remain until you remove them with `revokeMember`. Nothing prevents a deleted team's ID from being reused, and a new team with the same ID in the same tenant would inherit the stale memberships: use random team IDs (Better Auth does), or revoke a team's memberships before deleting it. ## Testing [#testing] Run [`sharingTeamsContract()`](/docs/sharing-testkit#teams-contract) from `@rolebook/sharing-testkit` against your adapter with team-aware identity and fences. # Testing your integration (/docs/testing) > Table-driven policy tests, decision suites as JSON, explain-based debugging, sharing with the in-memory adapter, the adapter contracts, and testing providers for the decision service and offline snapshots. ## Test the policy as a table [#test-the-policy-as-a-table] A policy is data, and a check is a pure function of the policy, the binding, and the request, so policy tests need no database. Write one row per subject, action, and expected code, and assert both sides: who can, and who cannot. ```ts title="policy.test.ts" import { describe, expect, test } from "bun:test"; import { createAuthorizer, definePolicy, trustedResource, type DecisionCode } from "rolebook"; const policy = definePolicy({ resources: { workspace: { actions: ["read"] }, project: { parent: "workspace", actions: ["read", "update", "delete"] }, }, roles: { editor: { scope: "workspace", rules: [ { effect: "allow", permission: "project:read" }, { effect: "allow", permission: "project:update" }, { effect: "deny", permission: "project:update", where: { fact: "resource.archived", operator: "equals", value: true }, }, ], }, }, }); const project = (archived: boolean) => trustedResource({ type: "project", id: "p1" }, [{ type: "workspace", id: "w1" }], { archived }); const editor = createAuthorizer(policy).bind({ subject: { type: "user", id: "u1" }, assignments: [ { subject: { type: "user", id: "u1" }, role: "editor", scope: { resource: { type: "workspace", id: "w1" }, appliesTo: "descendants" }, }, ], }); const cases: readonly [string, "project:read" | "project:update" | "project:delete", boolean, DecisionCode][] = [ ["reads a project", "project:read", false, "ALLOWED"], ["updates a live project", "project:update", false, "ALLOWED"], ["cannot update an archived project", "project:update", true, "EXPLICIT_DENY"], ["cannot delete", "project:delete", false, "NOT_GRANTED"], ]; describe("editor", () => { for (const [name, permission, archived, code] of cases) { test(name, () => { expect(editor.check({ permission, resource: project(archived) }).code).toBe(code); }); } }); ``` Tips: - Assert the **code**, not only `allowed`: `NOT_GRANTED` and `INVALID_ASSIGNMENT` are both denials, but only one is the denial you meant. - Add a test for each deny and each condition with the fact present, absent, and of the wrong type. A missing fact makes a conditional deny fire. - Test that a role assigned on one workspace does not reach another workspace's resources. - Run `definePolicy()` in a test so a malformed policy fails CI rather than a deploy. - Review policy changes with [`diffPolicies()`](/docs/api#diffpolicies) and pin the expected diff in a test. ## Keep expected decisions as data [#keep-expected-decisions-as-data] The same table can live in a JSON file that people who do not write TypeScript can read and review. A suite in the `rolebook-core-fixtures` format holds policies and cases; each case names a policy, a binding, a resource, a request, and the decision you expect: ```json { "format": "rolebook-core-fixtures", "version": 1, "suiteId": "projects", "policies": [ { "id": "projects", "policy": { "resources": { "project": { "actions": ["read", "delete"] } }, "roles": { "viewer": { "scope": "project", "rules": [{ "effect": "allow", "permission": "project:read" }] } } } } ], "cases": [ { "id": "viewer-cannot-delete", "policyId": "projects", "binding": { "subject": { "type": "user", "id": "ada" }, "assignments": [ { "subject": { "type": "user", "id": "ada" }, "role": "viewer", "scope": { "resource": { "type": "project", "id": "q3_report" }, "appliesTo": "self" } } ] }, "resource": { "ref": { "type": "project", "id": "q3_report" }, "ancestors": [] }, "request": { "permission": "project:delete" }, "expect": { "allowed": false, "code": "NOT_GRANTED" } } ] } ``` The runner is a script in the Rolebook repository, not part of an installed package. From a checkout, after `bun run build`: ```sh bun .github/scripts/rolebook-cli.ts test suite.json bun .github/scripts/rolebook-cli.ts test --format json suite.json ``` It validates the whole file first, then evaluates every case in order through the public engine API (`definePolicy`, `trustedResource`, `createAuthorizer`, `bind`, `check`) and compares `allowed` and `code`. | Exit code | Meaning | | --- | --- | | `0` | Every case ran once and matched. | | `1` | Every case ran and at least one did not match. The report names each case and whether `allowed`, `code`, or both differed. | | `2` | The run did not complete: an invalid command line, an unreadable or malformed file, an unsupported `version`, an engine fault, or the deadline (`--timeout-ms`, 30 seconds by default, at most 60). | Bounds: one file holds 1 to 64 policies and 1 to 1,000 cases, is at most 4 MiB, and nests at most 32 levels. Every object is closed, so a misspelled key is an error and never ignored. `request` must not contain a `resource`; the case's `resource` wrapper supplies it. A script should check both the exit code and the report's `status`. A passing suite shows the engine's decision on the JSON you supplied. It does not show where those facts come from in production or that they are current. Keep secrets and real subject data out of identifiers and committed suites: identifiers appear in reports. ## Debug a denial with `explain` [#debug-a-denial-with-explain] `explain()` returns the rules evaluated, in order, with the one that decided: ```ts prelude=core const explanation = authorization.explain({ permission: "project:delete", resource: project }); console.log(explanation.code); // "NOT_GRANTED" console.table(explanation.trace.map(({ outcome, effect, role, permission }) => ({ outcome, effect, role, permission }))); ``` An empty trace with a validation code (`UNKNOWN_ROLE`, `INVALID_ASSIGNMENT`, `RESOURCE_MISMATCH`, `INVALID_REQUEST`, `INVALID_SUBJECT`) means the request never reached the rules: fix the input. See [evaluation order](/docs/evaluation). ## Test sharing without a database [#test-sharing-without-a-database] `createMemorySharingAdapter()` and `createMemoryPolicyStore()` run the whole sharing module in memory. Share one clock between the adapter and `createSharing()`, configure the eligibility fence from your test fixture, and seed resources: ```ts prelude=sharing import { createMemorySharingAdapter, createSharing, defineSharing, type SharingClock } from "@rolebook/sharing"; import { trustedResource } from "rolebook"; let now = new Date("2025-01-01T00:00:00.000Z"); const clock: SharingClock = { now: () => now }; const members = new Set(["owner_1", "user_789"]); const memory = createMemorySharingAdapter({ clock, fenceEligibleSubjects: ({ subjects }) => subjects.every((subject) => members.has(subject.id)), // The same answer as evidence for listing pages: membership here depends on no time. readEligibleSubjects: ({ subjects }) => ({ eligible: subjects.every((subject) => members.has(subject.id)), expiryDependencies: [], }), }); memory.seed({ tenantId: "ws_456", resourceId: "project_1", resource: trustedResource({ type: "project", id: "project_1" }, [{ type: "workspace", id: "ws_456" }]), owner: { type: "user", id: "owner_1" }, }); const testSharing = createSharing({ definition: defineSharing({ policy, resources: { project: { ...definition.resources.project, adapter: memory } } }), identity, invitationTokens, clock, mutationBackoffMs: () => 0, }); now = new Date("2025-01-02T00:00:00.000Z"); // move time for expiry tests ``` The in-memory adapter takes no locks: use it for module behaviour, not for concurrency guarantees. To test `listAccessible()` or `listAccess()` this way, the setup needs two more things, because each page is read at [one coherent point](/docs/sharing/listing#what-a-consistent-page-requires). An adapter with `fenceEligibleSubjects` also needs `readEligibleSubjects`, as above. And the test's identity adapter must supply [identity evidence](/docs/sharing/listing#identity). The simplest way in a fixture is `capturePagePrincipal({ tenantId, subject, evaluatedAt })`, returning `{ principal, expiryDependencies }` synchronously from the fixture's state; an adapter that implements `resolvePagePrincipal` with a real revision qualifies as well. Without them a listing rejects with `AccessListingUnavailableError` and the reason `identity_evidence_missing`, which is a setup problem and not an empty result. `authorize()`, `permissions()`, and commands need neither. ## Run the adapter contracts [#run-the-adapter-contracts] If you write or configure a storage adapter, run the [sharing testkit](/docs/sharing-testkit) against it: the 38-case adapter contract, the teams contract when you use teams, and the policy contracts when you use versioned sharing. The PostgreSQL package runs the adapter contract against PGlite in memory, and the SQLite package against bun:sqlite; both add database-specific concurrency suites of their own. Know what each run covers. PGlite is not the checked `createPgExecutor(pool)` executor and has no consistent-page capability, so the PostgreSQL package's PGlite run lists through a test-only stand-in for page reads. It exercises the adapter's reads and the listing scan; it says nothing about page consistency, locking, or concurrency on a real server. Those are covered by separate suites that run against a real PostgreSQL server, and against a file-backed SQLite database through the worker-backed executor. Do the same for your own adapter: run the contracts on the database and the executor you deploy, and add tests for your transactions, locks, and concurrent writers. A green run on a substitute database or a different executor does not qualify the production configuration. ## Test what you supply to the decision service and offline snapshots [#test-what-you-supply-to-the-decision-service-and-offline-snapshots] The [decision service](/docs/decision-service) and [offline snapshots](/docs/offline) evaluate with the engine, so your policy tests above already cover the rules. What needs its own tests is the code you plug in, because neither component can check that the facts it is given are complete: - **Authority providers.** Run each provider against its real source, with tenants that deliberately reuse user, team, and resource IDs. Assert that it returns every assignment including denies and group memberships, the complete ordered ancestry, `not_found` only for confirmed absence, and `unavailable` when the source cannot be read. Add a negative test for each property: a provider that drops a deny must fail your suite. - **Credential verifiers.** Test expiry, audience, issuer, revocation, and that a malformed header never reaches a successful result. - **Callers.** Test that your client treats a no-decision as a refusal to proceed and reports it as an availability problem, separately from `EXPLICIT_DENY` and `NOT_GRANTED`. - **Offline hosts.** Test the clock adapter against a set-back clock and a lost time anchor, and the state store against restore from backup and concurrent finalization. An in-memory counter or a plain file demonstrates the protocol; it does not qualify a host for enforcement. Other implementations that read the same wire formats can check their JSON admission against the shared byte fixtures exported as `@rolebook/scalars-p1/fixtures/p1-v1.json`. See [the P1 input profile](/docs/scalars-p1). ## End to end [#end-to-end] At the HTTP layer, test that each protected route returns 401 without a session, 403 for a denied subject, and the resource for an allowed one, using the real loaders. The checks inside are the same Rolebook calls your unit tests cover; the route tests prove the wiring: that the tenant, the subject, and the resource come from the session and the database, not from the request. # Trusted resources and ancestry (/docs/trusted-resources) > Resource snapshots with ancestry, and what they do and do not prove. Every check targets a `TrustedResource`: an immutable snapshot of one resource, its ordered ancestry, and the attributes conditions may read. ```ts import { trustedResource } from "rolebook"; const project = trustedResource( { type: "project", id: "project_1" }, [ { type: "workspace", id: "ws_456" }, // immediate parent first { type: "organization", id: "org_1" }, // root last ], { ownerId: "user_123", status: "draft" }, ); ``` `trustedResource(ref, ancestors = [], attributes = {})` deep-copies its input into a frozen, null-prototype snapshot. It throws an `Error` when the reference, the ancestry, or the attributes are malformed: a missing or empty ID, an extra key on a reference, more than 16 ancestors, or attribute values that are not JSON-like (an `undefined`, a `Date`, a class instance, a function, a cycle). ## Ancestry [#ancestry] `ancestors` is the complete chain from the immediate parent to the root, in the order the policy declares parents. At check time Rolebook verifies it against the policy: - `ref.type` must be the resource type of the requested permission. Checking `workspace:read` against a project is `RESOURCE_MISMATCH`. - Each ancestor's type must be the declared parent of the type before it, and the chain must end at a type with no parent. A project snapshot that stops at its workspace, when workspaces have an organization parent, is `RESOURCE_MISMATCH`. - A snapshot carries exactly `ref`, `ancestors`, and `attributes`. An extra key is `RESOURCE_MISMATCH`. Scoped assignments are matched against this chain. A `workspace_editor` assignment on `ws_456` with `appliesTo: "descendants"` applies to `project_1` only because `ws_456` is in the project's ancestry. ## What a snapshot proves, and what it does not [#what-a-snapshot-proves-and-what-it-does-not] `trustedResource()` validates structure, declared ancestry types, bounds, and immutability. It records no database provenance and no tenant ownership. An ancestor ID of the right type is caller-supplied data, not evidence that the resource really lives under that ancestor. Rolebook also accepts any value with the trusted-resource shape at check time: it snapshots and validates the value the same way. The name is a reminder of your responsibility, not a seal. Build every snapshot from authoritative data: 1. Load the resource by `(tenantId, resourceId)` through a query scoped to the authenticated tenant. 2. Build the ancestry from the stored parent links, not from IDs in the URL or the request body. 3. Copy only the attributes your policy reads, from the row you just loaded. A structurally valid resource from another tenant is still the wrong input, and Rolebook cannot tell. See [multi-tenant setup](/docs/multi-tenant). ## Attributes [#attributes] Attributes are the facts conditions read under the `resource` root: `resource.ownerId`, `resource.status`. `resource.type` and `resource.id` are reserved and always come from `ref`; an attribute cannot replace them. Keep attributes to what the policy needs. Snapshots are bounded (at most 1,024 values, 128 entries per array, 64 keys per object, 16 levels deep, 512 characters per string; see [limits](/docs/limits)), and oversized input throws in `trustedResource()` or denies at check time. Every attribute key follows the [policy-name grammar](/docs/policies#names): a key such as `_id` or `created at` throws here, and a `Date` value must be passed as a number or an ISO string (see [keys and values inside snapshots](/docs/limits#keys-and-values-inside-snapshots)). Map rows to exactly the attributes you need. A spread can carry `undefined` for a nullable column, which is not JSON-like and fails the snapshot, or a value the policy should never see. Omit an optional column rather than setting it to `undefined`. # What happens when (/docs/what-happens-when) > Scenario by scenario, what Rolebook does when an answer is lost, two writers collide, a receiver is down or the console and your application disagree. This page walks through the situations that matter when something goes wrong in the middle of a change: a lost answer, a crash, two writers at once, a receiver that is down. Each entry says what Rolebook does and what is left for you to do. It restates the reference pages and adds nothing to them; each section links to the page with the exact rules and their limits. Three principles run through every table: - **A committed change is not applied a second time.** While its idempotency record is kept, a retry of the same command answers from that record. The connector calls Sharing at most once for each change the console sends. - **An unproven outcome is reported as unknown.** When Rolebook cannot tell whether a change committed, it says so instead of guessing either way. - **A refused sharing change or role set writes no access state.** Memberships and custom roles either change as a whole or stay as they were. Bookkeeping can remain: the connector keeps a record of every command it refused, and a console policy publish refused part-way keeps its reserved number and any saved draft. ## A sharing change whose answer was lost [#a-sharing-change-whose-answer-was-lost] For code that calls `execute` itself. See [Idempotency](/docs/sharing/commands#idempotency) and [Looking up an outcome](/docs/sharing/commands#looking-up-an-outcome). The connector builds on the same idempotency record and `lookupExecution`, but never calls `execute` a second time; its own table is [further down](#the-console-sends-a-change-through-the-connector). | Situation | What Rolebook does | What you do | | --- | --- | --- | | Your process stopped, or gave up waiting, after calling `execute`. | The change committed together with its idempotency record, in one transaction, or has not committed. A call you stopped waiting for may still be running and commit later. | Retry the same command with the same `idempotencyKey`, or call `lookupExecution` with the same command to read the outcome without running anything. | | You retry the same command with the same key. | While the record is kept, it answers `ALREADY_APPLIED` with the revision of the original commit, and nothing is applied again. On `createSharing()` the retry is authorized against current state first, so an actor that lost access since can be refused (with two exceptions for commands that remove the actor's own access). On `createVersionedSharing()` the actor's own committed key replays before authorization. | Treat `ALREADY_APPLIED` as success. | | You reuse the key for a different command, or another actor uses it. | `CONFLICT`, without retries, once the command is otherwise authorized. | Use a new key for a new command. | | `lookupExecution` answers `committed`. | The record proves that exact command committed. The result is what a replay would answer. | Treat it as success. | | `lookupExecution` answers `not_found`. | Nothing is proven. This is also the answer after the record was pruned by retention, after the resource was deleted or moved to another tenant, and while the command may still be running. | Read the resource's current access, and send the command again if it is still needed. | | `lookupExecution` answers `different_command`. | The key holds another command now, or this command by another actor. It does not prove your command never committed: its record may have been pruned and the key reused. An actor without access to the resource gets `not_found` instead, so the lookup does not reveal that the resource exists. | Do not reuse that key. Read the resource's current access. | | `lookupExecution` answers `refused`. | Nothing was read. The command is malformed, the resource type is unknown, the actor is not a tenant member, the policy could not be loaded, or the tenant's hierarchy enrollment has started (`HIERARCHY_UNAVAILABLE`). | Fix the cause. For a tenant whose enrollment has started, the outcome cannot be read without executing: a retry with the same key replays a commit, but applies the command if it had not committed. | | The retry arrives after the record was pruned. | It runs as a new command, authorized against current state. | Keep retention longer than every client's retry window. See [Retention](/docs/sharing/retention). | `lookupExecution` is part of `TenantSharing`; the HTTP API does not expose it. ## Two writers change the same resource [#two-writers-change-the-same-resource] See [Conflict retries](/docs/sharing/commands#conflict-retries). | Situation | What Rolebook does | What you do | | --- | --- | --- | | Another change commits while yours is being authorized. | `execute` re-reads, re-authorizes and tries again, up to `mutationRetries` more times, then answers `CONFLICT`. | Retry later, or show the current state. | | You showed someone the access list, and it changed before they confirmed. | With `expectedSharingRevision`, the command answers `SHARING_REVISION_CHANGED` instead of applying to a state nobody reviewed. | Read the access again and ask again. | | A member is revoked while a change of theirs is in flight. | A mutation is conditional on the sharing revision it was authorized against. The revocation moves that revision, so their change is authorized again against the new state and refused. | Nothing. | ## Custom roles, one at a time or as a set [#custom-roles-one-at-a-time-or-as-a-set] See [Custom roles](/docs/sharing/versioned#custom-roles) and [`CustomRoleAdministration`](/docs/sharing/api#customroleadministration). | Situation | What Rolebook does | What you do | | --- | --- | --- | | You replace a tenant's roles with `customRoles.set`. | Every role gets the checks a single `define` makes, the limits are counted on the result, roles the set does not name are removed, and everything commits in one transaction with one revision bump and one audit event per change. | Nothing. | | One role in the set is invalid. | The whole set is refused. Nothing is written. | Fix that role and send the set again. | | The set is already in place. | `UNCHANGED`. Nothing is written, and no fence is held: a change committed right after that read is not reported. | Nothing. | | A `define`, `remove` or another `set` commits first. | `REVISION_CONFLICT`. Nothing is written. | List the roles again and resend against the new revision. | | A policy is published while the set is in flight. | `GENERATION_CONFLICT`. Nothing is written. Pass `expectedGeneration` from your listing to get this answer even when the publish went through another instance of your application. | List again and resend. | | A stored role row does not decode. | Every set is refused with `CUSTOM_ROLE_UNREADABLE`, naming the row, because Rolebook cannot tell whether that role is live or retired. | Repair the row in the database. | | A role's template was narrowed by a later policy. | The role's status becomes `exceeds_template` and it is left out of evaluation. Rolebook does not clamp the role. | Redefine the role within its template, or remove it. | | A membership names a role that is no longer available. | The binding fails closed. New grants, changes and invitations to that role are `ROLE_NOT_ALLOWED`; accepting an invitation to it is `INVITATION_UNAVAILABLE`. | Only the owner's recovery path can change or revoke that membership. | | A role is removed, then defined again under the same name. | `CUSTOM_ROLE_NAME_RETIRED`: a removed name cannot be reused. | Choose another name. | | A set at the 32-role limit removes one role and adds another. | It applies: the limit is counted on the result. | Nothing. | ## A policy is published [#a-policy-is-published] See [Versioned sharing](/docs/sharing/versioned#writes-are-fenced-reads-are-bounded). | Situation | What Rolebook does | What you do | | --- | --- | --- | | A new version is published while changes are running. | With fenced adapters (`fencePolicy`), every mutation re-reads the active generation and the tenant's custom-role revision inside its transaction. A change that started under the old policy answers `POLICY_GENERATION_CHANGED` or `TENANT_ROLES_CHANGED` and writes nothing. | Send the change again. | | Two publishes race. | `publish` activates a version only if the generation still matches. One wins; the other answers `GENERATION_CONFLICT`. | Publish again from the new active version if it is still wanted. | | Another instance has not seen the new version yet. | A read there may decide under the previous generation for at most `refreshIntervalMs` plus its own duration. Writes are not affected: the fence reads the stored generation in the write's transaction. | Choose a refresh interval you can accept. There is no strong-read mode. | | An instance is told its generation is no longer active. | It decides nothing under that generation, or an older one, until a fresh read of the active pointer confirms it or installs a later one. The refresh interval does not apply. | Nothing. | | The policy store is unreachable. | A cached policy serves until `maxStalenessMs`. After that, reads reject with `PolicyUnavailableError` and `execute` answers `POLICY_UNAVAILABLE`. | Restore the store. | | The active pointer goes backwards, changes digest at the same generation, or does not decode. | The failure is sticky for that instance (`POINTER_REGRESSED`, `POINTER_DIGEST_MISMATCH`, `POINTER_INVALID`, `VERSION_INVALID`). | Restoring an older generation requires restarting every instance. | | One process still runs an unfenced adapter. | It can commit under a superseded policy, and Rolebook cannot detect it. | Run fenced adapters in every process that writes sharing state before the first publish. | ## The console sends a change through the connector [#the-console-sends-a-change-through-the-connector] See [Connect to Rolebook Console](/docs/connect-to-rolebook-console), especially its [Failure behaviour](/docs/connect-to-rolebook-console#failure-behaviour) and [Limits](/docs/connect-to-rolebook-console#limits). The last column says what the console is expected to do with each answer. | Situation | What the connector does | What the console does | | --- | --- | --- | | The console is unreachable. | Your application keeps working: local reads and writes do not go through the connector. It reconnects with a growing delay, up to 60 seconds. Nothing is applied while disconnected. | Delivers again after the connection is back. | | The console refuses the connection (wrong key, wrong environment, replaced, wrong protocol version). | It stops reconnecting and emits `halted`. | Nothing: no command reaches the connector until it is started again. | | A command has a bad signature, another environment, or an unknown key. | It is refused before anything is recorded. | The command fails. | | A change that was never started arrives after its signed expiry. | `COMMAND_EXPIRED`. It never ran. | Issues a new command if the change is still wanted. | | A change whose Sharing call was already started or finished is delivered again after its expiry. | It answers from the recorded outcome (`ALREADY_APPLIED`, the recorded refusal, `Outcome unknown` or `BUSY`), not `COMMAND_EXPIRED`. | Records that outcome. | | The console is not enabled for that tenant. | `TENANT_NOT_ENABLED`. | Nothing until your application enables the tenant. | | The same change is delivered twice. | Sharing is called at most once per change. The exact envelope that delivered it gets `APPLIED` again from the same process within 10 minutes; any other delivery gets `ALREADY_APPLIED`. A duplicate that arrives while the first is still running answers `BUSY`. | Records the change as applied once. | | The same command ID arrives with different parameters. | `DUPLICATE_MISMATCH`. | The command fails. | | The connection drops after Sharing committed, before the answer was sent. | A redelivery answers from the cached result or the recorded outcome: `APPLIED` or `ALREADY_APPLIED`. | Redelivers the same command and records the answer. | | The Sharing call fails. | The change is recorded `unknown` and Sharing's own record is read at once: if it proves the commit, the answer is `ALREADY_APPLIED`; otherwise `Outcome unknown`. The change is never run again to find out. | Redelivers the same command ID, which reads Sharing's record again. If it stays unknown, the membership is checked and a new command issued if still needed. | | The process stops in the middle of the Sharing call. | Redeliveries answer `BUSY` while the call's owner could still be waiting. A sweep then records the change `unknown`, and from then each delivery reads Sharing's record as above. | Retries, then as above. | | The Sharing call takes longer than `commandTimeoutMs`. | The connector stops waiting and answers `Outcome unknown`. The call can still commit, even after a change with a higher sequence ran; a late commit is recorded and replaces `unknown`. | As for a failed call. | | An outcome can never be proven. | It stays `unknown` when the record was pruned, the resource was deleted or moved to another tenant, the key holds another command, the console principal changed or no longer resolves, the tenant's hierarchy enrollment has started, or Sharing has no `lookupExecution`. `command.lookup` reads only the connector's own receipts and never says a change did not commit. | Checks the membership and issues a new command with a new ID if the change is still needed. | | Sharing refuses the change (not allowed, role unknown, and so on). | The refusal is recorded and every later delivery gets the same refusal. | A new attempt is a new command ID. | | Sharing refuses for a reason that would pass on a retry (`POLICY_GENERATION_CHANGED`, `TENANT_ROLES_CHANGED`, `POLICY_UNAVAILABLE`, `HIERARCHY_UNAVAILABLE`, `DELEGATION_UNAVAILABLE`). | The answer is `INTERNAL` with that code as its message, and it is final for that command ID. | Issues a new command ID to try again. | | An earlier change has no final state yet. | Later changes answer `BUSY` until it has one: a change starts only after every lower sequence has a final state. | Retries. | | Too many commands at once. | Reads beyond 16 at a time answer `BUSY`. A connection that exceeds its pending limits is closed with code 4429. | Retries; commands dropped with the closed connection are redelivered. | | The tenant is disabled after a change committed. | The commit stays recorded, but its result is not released: `TENANT_NOT_ENABLED`. | Cannot confirm the change until the tenant is enabled again. | | An invitation is issued and token export is off. | `UNSUPPORTED_COMMAND` (reason `INVITATION_TOKENS_NOT_EXPORTED`), before anything is recorded. An invitation admitted by an instance with the option on answers `BUSY` with that reason on an instance with it off. | Invitations are unavailable for that application. | ### The console publishes a policy or sets custom roles [#the-console-publishes-a-policy-or-sets-custom-roles] These need `authorizeAdministration` in your application. Without it, the connector does not advertise either capability. | Situation | What the connector does | What the console does | | --- | --- | --- | | `authorizeAdministration` says no. | `UNSUPPORTED_COMMAND` (reason `NOT_AUTHORIZED`). Nothing is published and no role is written. A policy refused part-way keeps its reserved number and, if it was already saved, its draft and audit row. | The command fails. | | The administration check times out or throws. | `BUSY` for a timeout or a lost database race; otherwise `INTERNAL`, retryable. | Retries. | | The console sets a tenant's roles. | One `customRoles.set` call: all of it or none of it. Roles the console does not list stay exactly as they are. | Records the set. | | The role-set call fails or is given up on. | `Role set outcome unknown`, retryable. Sharing applied all of it or none of it. | Retries the same set. | | The set committed but could not be recorded. | `Role set applied, not recorded`, retryable. The retry finds the set in place and records it. | Retries the same set. | | A local role change lands after a set whose commit may have been lost. | The retry cannot tell its own commit from the local change, so it answers `STALE` (`ROLES_CHANGED`) unless the set is exactly in place. The local change is never overwritten. | Issues a new set revision. | | An older set revision arrives after a newer one. | `STALE`. | Nothing: the newer one stands. | | A local role change or policy publish commits between the connector's read and its call. | `BUSY`. Nothing is written. | Retries the same set. | | A role the console did not list is no longer valid under the active policy. | The set is refused, naming the role. | Lists that role (valid, or as unavailable so it is removed), or it is fixed locally. | | Two executors run the same set revision and both are refused cleanly. | Later retries of that set revision can answer `STALE` (`ROLES_CHANGED`) although nothing of it committed. It fails closed. | Issues a new set revision. | | A policy number below the active one, or below a reserved one, arrives. | Below the recorded active number: `STALE` without details. Otherwise, below a reserved number: `STALE` (`NEWER_POLICY`). The older policy is never published, even if the newer one was only reserved. | Nothing. | | Another hash arrives under a reserved policy number. | `STALE` (`NUMBER_RESERVED`). | The command fails. | | Another publish won the generation. | `STALE` (`GENERATION_CONFLICT`). The publish never overwrites a policy published after its reservation. | Publishes again if intended. | | The publish call fails or is given up on. | `Outcome unknown`. | Retries the same command, which confirms the policy if it is active. | | The policy was published but could not be recorded. | `Policy published, not recorded`, retryable. The retry finds it active and records it. | Retries the same publish. | | A policy was published locally after the console's. | A repeat of the console's publish answers `STALE` (`POLICY_CHANGED`). | Publishes again if intended. | | Your application's schema says `policySource: "code"`. | `POLICY_SOURCE_CODE`. | Console publishing is unavailable for that application. | | Two connector versions run against one state store. | Not supported: an older role set can be applied after a newer one. Stop the previous version's processes before starting the new one. | Nothing. | ### Audit copies [#audit-copies] See [Audit copies](/docs/connect-to-rolebook-console#audit-copies). | Situation | What the connector does | | --- | --- | | An audit event names a tenant the console is not enabled for. | It is quarantined and is not sent, also if the tenant is enabled later. | | An event is sent and the acknowledgement is lost. | It is sent again: delivery is at least once. | ## An access change is announced by webhook [#an-access-change-is-announced-by-webhook] See [Access-change webhooks](/docs/sharing/webhooks). | Situation | What Rolebook does | What you do | | --- | --- | --- | | A grant, role change, revocation, ownership transfer, or an invitation issued or accepted commits. | At least one signed request is sent to each endpoint, after the transaction committed. | Verify the signature and act on it. | | An invitation is revoked, or a resource is initialized, deleted or moved. | Nothing is sent: these audit actions have no webhook. | Use the audit log for them. | | A change is rolled back. | Nothing is sent. | Nothing. | | A change was committed before the delivery migrations ran. | It is never sent. Delivery starts with the first change committed after them. | Nothing. | | The receiver answers anything other than 2xx, redirects, times out or is unreachable. | The delivery is retried with a growing delay: 1 s, 2 s, 4 s, up to 5 minutes, for 300 attempts by default, about a day. | Fix the receiver. | | The receiver processed a request but its acknowledgement was lost. | The same request is sent again with the same `rolebook-webhook-id`. | Drop duplicates by that ID. | | A delivery runs out of attempts. | It becomes a dead letter. Later changes of **that resource** wait behind it; other resources are not affected. | List dead letters, then `requeue` one after fixing the receiver, or `discardDeadLetter` to skip that change for good. | | Two changes to one resource commit close together. | They are delivered one at a time, in commit order. | Nothing. | | Changes to different resources commit close together. | They are delivered independently and can arrive in either order. | Do not rely on an order across resources. | | A worker crashes after claiming a delivery. | The lease expires and the delivery is claimed again. Nothing is lost. | Nothing. | | A long-running or prepared transaction is open anywhere in the PostgreSQL cluster. | Deliveries of every later change wait until it ends, so nothing can be skipped. | Watch for old transactions. | | The database was upgraded with `pg_upgrade` and the cluster's identity changed. | New changes are not queued (`foreign-cluster`); entries already queued are still delivered. | Run `adoptCluster()`. | | The database was restored with `pg_dump` and `pg_restore`, or moved by logical replication. | New changes are not queued (`foreign-cluster`); entries already queued are still delivered. | Run `rebaseline()` after the restore and before the application writes anything. | | An endpoint ID is reused for another tenant. | The drain is refused. The first tenant's changes are never sent to the other. | Use one endpoint ID per tenant. | # Rolebook compared with Casbin, OpenFGA, Permit and SpiceDB (https://rolebook.dev/compare) Rolebook is a TypeScript authorization library that decides inside your application, from facts your server has already loaded. Pick the need closest to yours. - [Casbin: Move a Casbin role model and check it in shadow first](https://rolebook.dev/compare/casbin) ([Markdown](https://rolebook.dev/compare/casbin.md)) - [OpenFGA: Share a resource with a team in one command](https://rolebook.dev/compare/openfga) ([Markdown](https://rolebook.dev/compare/openfga.md)) - [Permit: Check individual fields inside a TypeScript request](https://rolebook.dev/compare/permit) ([Markdown](https://rolebook.dev/compare/permit.md)) - [SpiceDB: Authorize a PostgreSQL update in one transaction](https://rolebook.dev/compare/spicedb) ([Markdown](https://rolebook.dev/compare/spicedb.md)) [See how Rolebook fits into your application](https://rolebook.dev/how-it-works) # Rolebook vs Casbin: check a migration before you switch (https://rolebook.dev/compare/casbin) Rolebook fits when you run a Casbin role model and want to compare both systems on real checks before enforcement changes. Casbin's documentation describes a configurable model and a policy that its enforcer evaluates. [Casbin overview](https://casbin.apache.org/docs/overview/) ## Plan first, enforce later `@rolebook/migrate` plans a Rolebook policy and assignments from your Casbin model and policy, and never writes or switches enforcement itself. It accepts one exact role-based subset and refuses anything else with a reason. Each generated role is assigned only at the object it came from. ## Alice can read one document and write another In Casbin, Alice is an `editor` who may read `doc-1` and write `doc-2`. The plan gives her a read role at document 1 and a write role at document 2. So `document:read` on document 1 is `ALLOWED`, and `document:write` stays scoped to document 2, which makes it `NOT_GRANTED` on document 1. In shadow, Casbin keeps enforcing while you replay checks through Rolebook. The report counts the disagreements it observed on the comparable checks you supplied and keeps a bounded set of redacted examples. When to switch is your call. ## In the Rolebook docs - [Migrating from Casbin and role tables](https://rolebook.dev/docs/migrate) - [All comparison guides](https://rolebook.dev/compare) # Rolebook vs OpenFGA: share a resource with a team (https://rolebook.dev/compare/openfga) Rolebook fits when your teams live in Better Auth or your own tables and sharing with a team should be one command in your application. OpenFGA's documentation shows how to give a team's members access to an object through relationship tuples. [OpenFGA user groups](https://openfga.dev/docs/modeling/user-groups) ## A team is the subject of the grant `@rolebook/teams` reads a person's teams for one explicit tenant. A `grantRole` command with a team as its subject shares the resource with the team's current members. ## The Design team edits Brand Assets The owner grants team `design` the `editor` role on project `brand_assets`. Alice is in Design, so her update is allowed, and that decision's `matched.via` names the team. Your app can show "editor through Design team". If Alice leaves the team and that grant was her only source of access, her next check that reads the updated membership is no longer allowed. ## In the Rolebook docs - [Teams](https://rolebook.dev/docs/teams) - [Sharing commands](https://rolebook.dev/docs/sharing/commands) - [Decisions and explanations](https://rolebook.dev/docs/decisions) - [All comparison guides](https://rolebook.dev/compare) # Rolebook vs Permit: field-level checks in your request (https://rolebook.dev/compare/permit) Rolebook fits when a TypeScript request handler should decide field by field, in process, from facts your server has already loaded. Permit's documentation says permission checks go to a policy decision point, which Permit manages or you run inside your own infrastructure. [Permit PDP overview](https://docs.permit.io/concepts/pdp/overview/) ## The check is a function call Rolebook Core is a TypeScript library with no network or database dependency. Your server loads the resource through its own data path, wraps it with `trustedResource()` and calls `check()` in the same process. A rule can be limited to field paths, and a request names the field it touches. ## Maya changes a project title Maya's role allows `project:update` on the fields `title` and `metadata.*`. Your handler loads `project_1` and checks the field `title`, which is `ALLOWED`. The same check without a field is `NOT_GRANTED`, because a field-limited allow never grants a request for the whole resource. Rolebook returns each decision and your handler applies it to the data. ## In the Rolebook docs - [Conditions, facts and fields](https://rolebook.dev/docs/conditions-and-fields#fields) - [Evaluation order](https://rolebook.dev/docs/evaluation) - [Trusted resources](https://rolebook.dev/docs/trusted-resources) - [All comparison guides](https://rolebook.dev/compare) # Rolebook vs SpiceDB: authorize and update in one transaction (https://rolebook.dev/compare/spicedb) Rolebook fits when your application updates a row in PostgreSQL and the permission check should commit or roll back with that update. SpiceDB's schema documentation shows permissions computed from relations, including read access to a document through its parent folder. [SpiceDB schema language](https://authzed.com/docs/spicedb/concepts/schema) ## The check and the update share one transaction `createPostgresProtectedWriteAdapter()` runs one resource-wide action check and your SQL callback in a single `SERIALIZABLE` PostgreSQL transaction, and records a receipt and an outbox event with your change. It needs the PostgreSQL sharing adapter, versioned sharing and a local identity projection in the same database. Your SQL remains trusted application code. ## Renaming a document `user_123` renames `document_1` in `workspace_1`. If the initial action check refuses, your callback never runs. If it allows, your `UPDATE` must advance the row's version and keep its owner, ancestry and sharing state. The rename, its receipt and its outbox event commit atomically only if the final authority checks succeed. While that receipt is retained, an exact retry with the same idempotency key returns it without running the callback again. ## In the Rolebook docs - [Protected application updates](https://rolebook.dev/docs/sharing-postgres/protected-updates) - [PostgreSQL fences and transactions](https://rolebook.dev/docs/sharing-postgres/fences) - [Policy versions and custom roles](https://rolebook.dev/docs/sharing/versioned) - [All comparison guides](https://rolebook.dev/compare)