RolebookDocs

@rolebook/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 for the contract, status codes, and CSRF rules.

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

declare const sharing: ResourceSharing<SharingResourceConfigurations>;
declare function getContext(request: Request): Promise<TenantContext | undefined>;

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:

import { type Context, Hono } from "hono";
import { createSharingHonoHandler } from "@rolebook/server/hono";
import type { ResourceSharing, SharingResourceConfigurations, TenantContext } from "@rolebook/sharing";

declare const sharing: ResourceSharing<SharingResourceConfigurations>;
type AppEnv = { Variables: { tenantContext: TenantContext | undefined } };

const app = new Hono<AppEnv>();
app.all(
  "/api/sharing/*",
  createSharingHonoHandler({
    basePath: "/api/sharing",
    sharing,
    getContext: (context: Context<AppEnv>) => context.get("tenantContext"),
  }),
);

With Next.js, in app/api/sharing/[...rolebook]/route.ts:

import { createSharingRouteHandlers } from "@rolebook/server/next";
import type { ResourceSharing, SharingResourceConfigurations, TenantContext } from "@rolebook/sharing";

declare const sharing: ResourceSharing<SharingResourceConfigurations>;
declare function getContext(request: Request): Promise<TenantContext | undefined>;

export const { POST, OPTIONS } = createSharingRouteHandlers({ basePath: "/api/sharing", sharing, getContext });

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

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

createSharingHandler

function createSharingHandler<TResources extends SharingResourceConfigurations>(
  options: SharingHandlerOptions<TResources>,
): (request: Request) => Promise<Response>;

A (request: Request) => Promise<Response> serving every operation under {basePath}/v1/.

SharingHandlerOptions

interface SharingHandlerOptions<
  TResources extends SharingResourceConfigurations = SharingResourceConfigurations,
> {
  readonly sharing: ResourceSharing<TResources>;
  readonly getContext: (
    request: Request,
  ) => TenantContext | undefined | Promise<TenantContext | undefined>;
  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

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

createSharingHonoHandler

function createSharingHonoHandler<
  TResources extends SharingResourceConfigurations,
  E extends Env = Env,
>(options: SharingHonoOptions<TResources, E>): (context: Context<E>) => Promise<Response>;

The handler as a Hono handler: getContext and onInternalError receive the Hono context.

SharingHonoOptions

interface SharingHonoOptions<
  TResources extends SharingResourceConfigurations = SharingResourceConfigurations,
  E extends Env = Env,
> extends Omit<SharingHandlerOptions<TResources>, "getContext" | "onInternalError"> {
  readonly getContext: (
    context: Context<E>,
  ) => TenantContext | undefined | Promise<TenantContext | undefined>;
  readonly onInternalError?: (error: unknown, context: Context<E>) => void;
}

@rolebook/server/next

createSharingRouteHandlers

function createSharingRouteHandlers<TResources extends SharingResourceConfigurations>(
  options: SharingHandlerOptions<TResources>,
): {
  readonly POST: (request: Request) => Promise<Response>;
  readonly OPTIONS: (request: Request) => Promise<Response>;
};

Frozen { POST, OPTIONS } route handlers for a Next.js App Router catch-all route.

@rolebook/server/core

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.

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<SharingResourceConfigurations>;
declare function sessionContext(request: Request): Promise<TenantContext | undefined>;

const core = createSharingCore({ sharing });
const allowed = new Set<string>(["https://app.example.com"]);

async function serve(request: Request, name: string): Promise<Response> {
  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

function createSharingCore<R extends SharingResourceConfigurations = SharingResourceConfigurations>(o: SharingCoreOptions<R>): 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

interface SharingCoreOptions<R extends SharingResourceConfigurations = SharingResourceConfigurations> {
  sharing: ResourceSharing<R>;
  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

interface SharingCore {
  readonly inspectionEnabled: boolean;
  readonly maxBodyBytes: number;
  run(input: SharingOperationInput): Promise<Response>;
}

SharingOperationInput

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

function createResponseHeaders(): Headers;

The fixed non-CORS headers: cache-control: no-store and x-content-type-options: nosniff.

csrfAllowed

function csrfAllowed(request: Request, allowed: ReadonlySet<string>): boolean;

True for a same-origin request, an Origin in allowed, or a request with no browser signal.

isJsonContentType

function isJsonContentType(value: string | null): boolean;

True for application/json with no charset other than utf-8.

errorResponse

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

const EXPLAIN_MAX_BODY_BYTES = 8192;

The sharing.explain body limit in bytes, unless maxBodyBytes is smaller.