RolebookDocs

Listing accessible resources

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:

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 }) 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

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 the page also carries the policyVersion it was decided under.

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. 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, which reads the authoritative facts and commits the decision with the change.

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

AdapterA page isRequires
In-memoryA copy of the tenant’s resources taken in one synchronous turn, with the adapter clockNothing further for storage. See the identity and eligibility notes below.
PostgreSQLOne SERIALIZABLE READ ONLY transaction on one connectionThe adapter is built on the checked createPgExecutor(pool) executor, and the tenant and resource ID columns are text.
SQLiteA read-only transaction on one worker connection over a file-backed WAL databaseThe adapter is built on the worker-backed 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 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 and protected writes, for example, also require specific executors.

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 and SQLite 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

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.

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:

listing-identity.ts
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 and 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

A versioned instance 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

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.

Errors

A request the module cannot answer completely rejects instead of returning a page:

ErrorcodeCause
AccessibleListingErrorINVALID_LIMITlimit is not an integer from 1 to 100, or the request is not a plain object of own data properties.
AccessibleListingErrorUNKNOWN_RESOURCE_TYPEtype is not a configured resource type.
AccessibleListingErrorUNKNOWN_ACTIONaction is not an action label configured for that type. listAccessible() only.
InvalidCursorErrorINVALID_CURSORcursor is not a sealed cursor this instance can open for the same call and scope.
AccessListingUnavailableErrorACCESS_LISTING_UNAVAILABLENo consistent page could be read. See below.
AccessibleListingErrorTOO_MANY_ASSIGNMENTSThe eligible principal has more than MAX_CANDIDATE_HINT_SIZE (256) assignments, so its candidate query cannot be complete.
InvalidCandidatePageErrorINVALID_CANDIDATE_PAGEThe 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

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.

reasonMeaningRetrying
capability_missingThe adapter or its executor cannot read a page at one coherent point.Not until the configuration is fixed.
identity_evidence_missingNo 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_missingVersioned policy state could not be read in the page’s snapshot, or was refused.Not until the configuration or the store is fixed.
unrepresentable_identityEvery attempt resolved a principal that cannot be compared exactly.Not until identity answers are plain data.
expiry_crossedAn expiry the page depended on passed before the page was sealed.A later call can succeed.
session_expiredThe attempt did not finish within its 2-second deadline.A later call can succeed.
snapshot_unavailableThe 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.
changedBracketed 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”:

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

sharing.listAccessible answers this refusal with HTTP 503 and a fixed body. It is an expected outcome and is not reported to onInternalError:

{
  "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 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

BoundValue
limit1 to 100
Candidates examined for one pageAt most 2,000
Resources hydrated in one batchAt most 200 (MAX_ACCESS_BATCH_SIZE)
Attempts in one callAt most 3
Deadline of one attempt2 seconds
Page attempts open at once on one adapter instance32; one more answers snapshot_unavailable
Identity expiry dependencies in one resolution1,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

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 on the PostgreSQL or SQLite adapter instead.

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() 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.

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 and requirements, the same 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. 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.