RolebookDocs

@rolebook/http

The wire contract of the sharing HTTP API: operations, codecs, schemas, and OpenAPI.

@rolebook/http defines the 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 and @rolebook/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

SHARING_OPERATIONS

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. sharing.executeIfUnchanged was appended later, so every earlier operation keeps its position; see Conditional commands.

SharingOperation

type SharingOperation = (typeof SHARING_OPERATIONS)[number];

isSharingOperation

function isSharingOperation(value: string): value is SharingOperation;

Whether a string names an operation.

SharingCommandOperation

type SharingCommandOperation = Extract<
  SharingOperation,
  "sharing.execute" | "sharing.executeIfUnchanged"
>;

isCommandOperation

function isCommandOperation(operation: SharingOperation): operation is SharingCommandOperation;

Whether an operation applies a command: sharing.execute or sharing.executeIfUnchanged.

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

const OPERATION_KEYS: Readonly<Record<SharingOperation, readonly string[]>>;

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

const DEFAULT_MAX_BODY_BYTES = 65536;

The default request body limit: 64 KiB.

Server codecs

decodeRequestBody

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

type DecodeResult =
  | {
      readonly ok: true;
      readonly input: Readonly<Record<string, unknown>>;
    }
  | {
      readonly ok: false;
      readonly issues: readonly WireIssue[];
    };

reviveCommandDates

function reviveCommandDates(command: unknown): unknown;

Revives expiresAt and membershipExpiresAt when they are RFC 3339 strings; every other value is kept as it arrived.

serializeResult

function serializeResult(
  operation: SharingOperation,
  result: unknown,
  input: Readonly<Record<string, unknown>>,
): 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

encodeRequestBody

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

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

function reviveResult(operation: SharingOperation, json: unknown): unknown;

Revives the timestamps of a wire result into Dates for the operations that carry them. Throws TypeError for an invalid date.

parseRfc3339

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

openApiDocument

function openApiDocument(): Record<string, unknown>;

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

SCHEMAS

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 schemas (ExplainRequest, ExplainResult, InspectionEnvelope, InspectionDecision, InspectionTraceEntry, InspectionRuleCondition, InspectionConditionResult, InspectionConditionNode, and the fixed failure bodies ExplainInvalidRequest, ExplainNotFoundOrDenied, ExplainRateLimited, ExplainUnavailable).

SharingSchemaName

type SharingSchemaName = keyof typeof SCHEMAS;

The name of one schema in SCHEMAS.

REQUEST_SCHEMA_NAMES

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

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

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

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

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

POST {basePath}/v1/sharing.explain carries TenantSharing.explain, 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:

StatusBody
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

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: 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 and the Python SDK’s explain return it.

Wire types

WireSharingDecision

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

type WireResourcePermissionsResult<TAction extends string = string, TType extends string = string> =
  | {
      readonly ok: true;
      readonly code: "EVALUATED";
      readonly permissions: WireResourcePermissions<TAction, TType>;
    }
  | {
      readonly ok: false;
      readonly code: "NOT_FOUND_OR_DENIED";
    };

sharing.permissions’ result.

WireResourcePermissions

interface WireResourcePermissions<TAction extends string = string, TType extends string = string> {
  readonly resource: ResourceKey<TType>;
  readonly sharingRevision: string;
  readonly allowed: Readonly<Record<TAction, boolean>>;
  readonly decisions: Readonly<Record<TAction, WireDecision>>;
}

Every action decided: allowed booleans and decisions reduced to { allowed }.

WireDecision

interface WireDecision {
  readonly allowed: boolean;
}

A decision reduced to { allowed }.

WireAccessDescriptionResult

type WireAccessDescriptionResult<TRole extends string = string, TType extends string = string> =
  | {
      readonly ok: true;
      readonly code: "DESCRIBED";
      readonly access: WireAccessDescription<TRole, TType>;
    }
  | {
      readonly ok: false;
      readonly code: "NOT_FOUND_OR_DENIED";
    };

sharing.describeAccess’ result.

WireAccessDescription

interface WireAccessDescription<TRole extends string = string, TType extends string = string> {
  readonly resource: ResourceKey<TType>;
  readonly sharingRevision: string;
  readonly owner: WireOwnership;
  readonly members: readonly WireAccessMember<TRole>[];
  readonly invitations?: readonly WirePendingInvitation<TRole>[];
}

WireAccessMember

interface WireAccessMember<TRole extends string = string> {
  readonly subject: WireRef;
  readonly role: TRole;
  readonly createdAt: WireDateTime;
  readonly createdBy: WireRef;
  readonly expiresAt?: WireDateTime;
}

WireOwnership

interface WireOwnership {
  readonly subject: WireRef;
  readonly createdAt: WireDateTime;
  readonly createdBy: WireRef;
}

WirePendingInvitation

interface WirePendingInvitation<TRole extends string = string> {
  readonly id: string;
  readonly recipient: InvitationRecipient;
  readonly role: TRole;
  readonly expiresAt: WireDateTime;
  readonly membershipExpiresAt?: WireDateTime;
  readonly createdAt: WireDateTime;
  readonly createdBy: WireRef;
}

WireAccessiblePage

interface WireAccessiblePage<TType extends string = string> {
  readonly resources: readonly WireAccessibleResource<TType>[];
  readonly nextCursor?: string;
  readonly exhausted: boolean;
}

sharing.listAccessible’s result.

WireAccessibleResource

interface WireAccessibleResource<TType extends string = string> {
  readonly resource: ResourceKey<TType>;
}

A listed resource: { resource } only, no snapshot.

WireAuditHistoryResult

type WireAuditHistoryResult<TType extends string = string> =
  | {
      readonly ok: true;
      readonly code: "LISTED";
      readonly page: WireAuditHistoryPage<TType>;
    }
  | {
      readonly ok: false;
      readonly code: "NOT_FOUND_OR_DENIED";
    };

sharing.auditHistory’s result.

WireAuditHistoryPage

interface WireAuditHistoryPage<TType extends string = string> {
  readonly resource: ResourceKey<TType>;
  readonly events: readonly WireAuditEvent[];
  readonly nextCursor?: string;
  readonly exhausted: boolean;
}

WireAuditEvent

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

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

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

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

interface WireRef {
  readonly type: string;
  readonly id: string;
}

A { type, id } reference.

WireDateTime

type WireDateTime = string;

An RFC 3339 string from toISOString().

WireError

interface WireError {
  readonly error: {
    readonly code: Exclude<WireErrorCode, "ACCESS_LISTING_UNAVAILABLE" | "HIERARCHY_UNAVAILABLE">;
    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. It has exactly one of three shapes, and the Error schema in 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. 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 could be read:

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

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.

WIRE_ACCESS_LISTING_UNAVAILABLE_REASONS

const WIRE_ACCESS_LISTING_UNAVAILABLE_REASONS: readonly WireAccessListingUnavailableReason[];

Every WireAccessListingUnavailableReason. The server sends a reason only when it is in this list.

WireHierarchyUnavailableReason

type WireHierarchyUnavailableReason = HierarchyUnavailableReason;

The reason of a HIERARCHY_UNAVAILABLE error: the tenant-level cause of HierarchyUnavailableError in @rolebook/sharing.

WIRE_HIERARCHY_UNAVAILABLE_REASONS

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

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.

WireIssue

interface WireIssue {
  readonly path: string;
  readonly message: string;
}

WIRE_ERROR_CODES

const WIRE_ERROR_CODES: readonly WireErrorCode[];

Every WireErrorCode.