RolebookDocs

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, 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 instead. Choose how decisions run compares the two, and the security model 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

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.

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

RouteBody
POST /v1/scopes/{scopeId}/decisions:checkCheckEnvelope: one check
POST /v1/scopes/{scopeId}/decisions:checkBatchBatchEnvelope: 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 <token>. 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.

caller.ts
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<Decision | NoDecision>;

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

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:

ResultMeaningOutcome
{ kind: "complete", bytes }The raw bytes of one AuthorityDocument, at most 1 MiBEvaluated when the document is valid and fresh
{ kind: "not_found" }The subject or resource is confirmed absent403 subject_or_resource_unavailable
{ kind: "unavailable" }, or a throwThe source could not be read503 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; sourceRevision is opaque evidence and not an ordering token or a write fence.

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.

Statuserror
400malformed_input, unsupported_profile, unsupported_model, unsupported_freshness
401unauthenticated
403forbidden, subject_or_resource_unavailable
404, 405route_not_found, method_not_allowed
413, 415request_too_large, unsupported_media
429scope_busy
500internal_fault
503service_busy, authentication_unavailable, authority_unavailable, authority_invalid, configuration_changed, clock_unavailable
504deadline_exceeded

Core’s validation codes map to authority_invalid, because the caller’s request already passed preflight; see how engine codes map. A decision is an observation at the decision point, not a transaction fence for a later write.

Limits

BudgetValue
Request body, single and batch64 KiB and 256 KiB
Policy and authority document1 MiB each
Overall deadline, single and batch2 seconds and 5 seconds
Authentication, and each provider call500 ms and 1 second
Concurrent requests per service instance32, then service_busy
Concurrent requests per scope, within that instance8, then scope_busy
Concurrent provider calls per scope, within that instance8, then scope_busy
Provider calls of one batch at once4, started in input order
maxFactAgeMs0 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

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.

API reference

createDecisionService

function createDecisionService(config: DecisionServiceConfig): DecisionService;

AuthorityDocument

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

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

type AuthorityLoadResult = {
  readonly kind: "complete";
  readonly bytes: Uint8Array;
} | {
  readonly kind: "not_found";
} | {
  readonly kind: "unavailable";
};

AuthorityProvider

interface AuthorityProvider {
  load(input: AuthorityLoadInput): Promise<AuthorityLoadResult>;
}

BatchEnvelope

interface BatchEnvelope extends EnvelopeHeader {
  readonly checks: readonly {
    readonly id: string;
    readonly check: CheckItem;
  }[];
}

BatchResponse

type BatchResponse = {
  readonly kind: "batch";
  readonly requestId: string;
  readonly results: readonly {
    readonly id: string;
    readonly result: Decision | NoDecision;
  }[];
} | (NoDecision & {
  readonly requestId: string;
});

CheckEnvelope

interface CheckEnvelope extends EnvelopeHeader {
  readonly check: CheckItem;
}

CheckItem

interface CheckItem {
  readonly subject: Ref;
  readonly resource: Ref;
  readonly action: string;
  readonly field?: string;
}

Clock

interface Clock {
  wallNowMs(): number;
  monotonicNowMs(): number;
}

CoreBindInput

type CoreBindInput = BindInput;

CoreTrustedResource

type CoreTrustedResource = TrustedResource;

CredentialGrant

interface CredentialGrant {
  readonly credentialId: string;
  readonly actorId: string;
  readonly scopeId: string;
  readonly operations: readonly GrantOperation[];
  readonly subjectSelector: SubjectSelector;
}

CredentialIdentity

interface CredentialIdentity {
  readonly credentialId: string;
  readonly actorId: string;
}

CredentialVerifier

interface CredentialVerifier {
  verify(input: {
    readonly authorization: string | undefined;
    readonly signal: AbortSignal;
    readonly deadlineMonotonicMs: number;
  }): Promise<CredentialIdentity | null>;
}

Decision

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

type DecisionCode = "ALLOWED" | "EXPLICIT_DENY" | "NOT_GRANTED";

DecisionService

interface DecisionService {
  fetch(request: Request): Promise<Response>;
  replaceRegistry(next: Registry): void;
  close(): Promise<void>;
}

DecisionServiceConfig

interface DecisionServiceConfig {
  readonly clock: Clock;
  readonly randomBytes: (length: number) => Uint8Array;
  readonly credentialVerifier: CredentialVerifier;
  readonly initialRegistry: Registry;
  readonly onDiagnostic?: (event: DiagnosticEvent) => void;
}

DiagnosticEvent

interface DiagnosticEvent {
  readonly requestId: string;
  readonly error: ErrorCode;
  readonly category: string;
  readonly profileId?: string;
}

ErrorCode

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

type GrantOperation = "check" | "check_batch";

NoDecision

interface NoDecision {
  readonly kind: "no_decision";
  readonly error: ErrorCode;
}

Ref

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

Registry

interface Registry {
  readonly grants: readonly CredentialGrant[];
  readonly scopes: readonly ScopeDeployment[];
}

ScopeDeployment

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

type SingleResponse = (Decision | NoDecision) & {
  readonly requestId: string;
};

SubjectSelector

type SubjectSelector = {
  readonly kind: "bound";
  readonly subject: Ref;
} | {
  readonly kind: "any_in_scope";
};