RolebookDocs

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 instance over HTTP:

PackageRole
@rolebook/httpThe wire contract: operation names, JSON shapes, request decoding, result serialization, client codecs, and an OpenAPI 3.1 document.
@rolebook/serverA web-standard (request: Request) => Promise<Response> handler, with Hono and Next.js adapters.
@rolebook/clientA typed fetch client for browsers and other services.

Sharing API or decision service?

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 instead. The two are independent handlers with separate routes, media types, and authentication, and you can run both. Choose how decisions run compares them.

Serve it

server.ts
import { createSharingHandler } from "@rolebook/server";
import type { ResourceSharing, SharingResourceConfigurations, TenantContext } from "@rolebook/sharing";

declare const sharing: ResourceSharing<SharingResourceConfigurations>;
declare function sessionFor(request: Request): Promise<{ workspaceId: string; userId: string } | undefined>;

export const sharingHandler = createSharingHandler({
  basePath: "/api/sharing",
  sharing,
  async getContext(request): Promise<TenantContext | undefined> {
    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

client.ts
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

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

OperationBody keys copiedResult
sharing.authorizeresource, action{ allowed, code }
sharing.permissionsresourcepermissions, or { ok: false, code }
sharing.describeAccessresourceaccess description, or { ok: false, code }
sharing.listAccessibletype, action, limit, cursor{ resources, nextCursor?, exhausted }
sharing.auditHistoryresource, limit, cursoraudit page, or { ok: false, code }
sharing.executecommandmutation result
sharing.explainresource, action, subject, field{ ok: true, code: "EXPLAINED", explanation }
sharing.executeIfUnchangedcommand, expectedSharingRevisionmutation result

Other body keys are dropped, except by sharing.explain, which refuses them (see Inspection). sharing.execute and sharing.executeIfUnchanged revive RFC 3339 expiresAt and membershipExpiresAt values back into Dates 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). 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

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.

StatusCodeWhen
400INVALID_REQUESTThe 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).
400INVALID_CURSORA listing or audit cursor does not open.
400INVALID_LIMIT, UNKNOWN_RESOURCE_TYPE, UNKNOWN_ACTION, TOO_MANY_ASSIGNMENTSA listing request cannot be answered.
400INVALID_LIMIT, UNKNOWN_RESOURCE_TYPEAn audit request cannot be answered.
401UNAUTHENTICATEDgetContext returned undefined.
403CSRFThe origin check failed.
404UNKNOWN_OPERATIONThe 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).
405METHOD_NOT_ALLOWEDThe method is not POST. (A CORS preflight OPTIONS from a configured origin is answered instead.)
413PAYLOAD_TOO_LARGEThe body is longer than maxBodyBytes.
415UNSUPPORTED_MEDIA_TYPEThe content type is not JSON.
503ACCESS_LISTING_UNAVAILABLEsharing.listAccessible only: no consistent page could be read. The body carries a reason.
500INTERNALAny 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

sharing.listAccessible reads each page at one coherent point. When the server cannot establish one, it answers HTTP 503 with a fixed message and one of eight reasons:

{
  "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, 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. The reason never contains a tenant, subject, or resource value. @rolebook/client 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

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

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.

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.