rolebook
Every export of the rolebook package, with its signature and behaviour.
import { ... } from "rolebook". The Hono middleware is a separate entry point,
rolebook/middleware/hono. The optional authoring checks are another,
rolebook/authoring. Signatures on this page are checked against the package’s built
declarations.
Policies
definePolicy
function definePolicy<
const R extends ResourceDefinitions,
const Roles extends Record<
string,
RoleDefinition<string, PolicyPermissionFromResources<R>, ResourceNames<R>>
>,
>(policy: {
readonly version?: string;
readonly resources: R & CheckedResources<R>;
readonly roles: Roles & CheckedRoles<Roles, PolicyPermissionFromResources<R>, ResourceNames<R>>;
}): Readonly<RolebookPolicy<RoleNames<Roles>, PolicyPermissionFromResources<R>, R>>; Validates, canonicalizes, compiles, and deeply freezes a policy, and returns the frozen canonical
policy. The type parameters infer the literal resource, action, and role names, so rule permissions,
role scopes, parent names, and inherited role names are checked at compile time. Throws a
PolicyError for a malformed or inconsistent policy, or one over a limit. The error
extends Error, its message starts with Invalid Rolebook policy:, and it carries a stable code
and a location (resource, role, rule, condition) naming where the problem is.
The returned object’s compiled form and shared authorizer are cached by identity: define a policy once and reuse it. See Policies.
diffPolicies
function diffPolicies(from: RolebookPolicy, to: RolebookPolicy): PolicyDiff; Returns the structural difference between two policies as a frozen PolicyDiff. Both
inputs are compiled first, so an invalid policy throws the same PolicyError as definePolicy(). Names in
added and removed lists are sorted. Rule changes compare direct rules as a multiset of canonical
rule JSON, and effective (inherited plus direct) rules separately.
canonicalPolicyJson
function canonicalPolicyJson(policy: RolebookPolicy): string; The deterministic serialization of a policy’s meaning: the compiled policy without its version
label, every object’s keys sorted by UTF-16 code unit, arrays in their order, no whitespace. Two
policies with equal canonical JSON evaluate identically. Throws the same Error as definePolicy()
for an invalid policy. @rolebook/sharing digests this string to identify policy versions.
canonicalValueJson
function canonicalValueJson(value: unknown): string; The same writer applied to an already validated JSON-like value: null, a boolean, a finite number, a
string, a dense array, or a plain object. Object keys are sorted. Throws a TypeError for anything
else, including undefined, a non-finite number, a function, an accessor property, a cycle, or a
non-plain object. It never calls toJSON.
Authorizers
createAuthorizer
function createAuthorizer<
TRole extends string,
TPermission extends string,
TResources extends ResourceDefinitions = ResourceDefinitions,
>(
policy: RolebookPolicy<TRole, TPermission, TResources>,
options?: AuthorizerOptions,
): Authorizer<TRole, RequestPermission<TPermission, TResources>>; Compiles the policy (or reuses its cached compilation) and returns a frozen Authorizer.
Without options.onInternalError, the authorizer is shared per policy object: calling
createAuthorizer(policy) again returns the same instance. With a reporter, each call returns a new
authorizer, still on the cached compilation. Throws like definePolicy() for an invalid policy.
check
function check<
TRole extends string,
TPermission extends string,
TResources extends ResourceDefinitions = ResourceDefinitions,
>(
policy: RolebookPolicy<TRole, TPermission, TResources>,
request: AuthorizationRequest<TRole, RequestPermission<TPermission, TResources>>,
): AuthorizationDecision; One-shot form of createAuthorizer(policy).bind(binding).check(request), taking the binding and the
check fields in one object. Never throws for malformed runtime input. A request with any key other
than the binding keys and permission, resource, field is INVALID_REQUEST.
enforce
function enforce<
TRole extends string,
TPermission extends string,
TResources extends ResourceDefinitions = ResourceDefinitions,
>(
policy: RolebookPolicy<TRole, TPermission, TResources>,
request: AuthorizationRequest<TRole, RequestPermission<TPermission, TResources>>,
): AuthorizationDecision; One-shot enforce: returns the allowed decision, or throws AuthorizationError
carrying the denial.
explain
function explain<
TRole extends string,
TPermission extends string,
TResources extends ResourceDefinitions = ResourceDefinitions,
>(
policy: RolebookPolicy<TRole, TPermission, TResources>,
request: AuthorizationRequest<TRole, RequestPermission<TPermission, TResources>>,
options?: ExplainOptions,
): DecisionExplanation; One-shot explain: the decision plus a bounded trace of evaluated rules. options is inspected
only after the request snapshot is fixed. See Decisions.
prepareAssignments
function prepareAssignments<TRole extends string>(
value: readonly RoleAssignment<TRole>[],
): readonly RoleAssignment<TRole>[] | undefined;
function prepareAssignments(value: unknown): readonly RoleAssignment[] | undefined; Validates and deep-freezes an assignment collection once, so repeated bindings over the same
principal reuse the copy instead of making a new one per bind(). Passing the result to bind() is
equivalent to passing the original: every entry is still validated, and the assignment count and node
budgets still apply across reused and fresh entries together. Returns undefined for a collection
that would not bind; keep your original value then and let bind() return its usual closed decision.
See reusing a validated collection.
trustedResource
function trustedResource(
ref: ResourceRef,
ancestors?: readonly ResourceRef[],
attributes?: Readonly<Record<string, unknown>>,
): TrustedResource; Creates a deeply frozen, caller-attested resource snapshot. ancestors defaults to [] and
attributes to {}. Throws an Error when the reference, ancestry, or attributes are malformed or
over the snapshot limits. It records no provenance: load every input authoritatively. See
trusted resources.
Errors
AuthorizationError
class AuthorizationError extends Error {
readonly decision: AuthorizationDecision;
constructor(decisionResult: AuthorizationDecision);
} Thrown by every enforce() on a denial. name is "AuthorizationError", message is the decision’s
reason, and decision is the full denial. Test for it with instanceof.
PolicyError
class PolicyError extends Error {
readonly code: PolicyErrorCode;
readonly location: PolicyErrorLocation;
constructor(message: string, code: PolicyErrorCode, location?: PolicyErrorLocation);
} Thrown by definePolicy(), createAuthorizer(), and every other entry point that compiles a
policy. name is "PolicyError". The message starts with Invalid Rolebook policy: and ends with
the location when one applies, such as (role "member", rule 1). Branch on code, not on the
message text.
PolicyErrorCode
type PolicyErrorCode =
| "MALFORMED_POLICY"
| "MALFORMED_RESOURCE"
| "MALFORMED_ROLE"
| "MALFORMED_RULE"
| "MALFORMED_CONDITION"
| "TOO_MANY_ROLES"
| "TOO_MANY_RULES"
| "COMPILED_LIMIT_EXCEEDED"; The stable classification of a policy error. The MALFORMED_* codes name the part of the policy
that is invalid. The other three report a limit.
PolicyErrorLocation
interface PolicyErrorLocation {
readonly resource?: string;
readonly role?: string;
readonly rule?: number;
readonly condition?: string;
} Where in the policy the error was raised. Each field is present only when it applies. rule is the
zero-based index of the rule in its role, and condition is a JSON Pointer from /where.
Constants
MAX_PRINCIPALS
const MAX_PRINCIPALS: 64; The most group principals one binding may carry beside its subject.
Authorizer types
Authorizer
interface Authorizer<TRole extends string = string, TPermission extends string = string> {
bind(input: BindInput<TRole>): BoundAuthorizer<TPermission>;
check(request: AuthorizationRequest<TRole, TPermission>): AuthorizationDecision;
enforce(request: AuthorizationRequest<TRole, TPermission>): AuthorizationDecision;
explain(
request: AuthorizationRequest<TRole, TPermission>,
options?: ExplainOptions,
): DecisionExplanation;
} bind() snapshots and validates a binding once and returns a BoundAuthorizer.
A binding that fails validation still returns a bound authorizer, whose every check returns the
binding’s denial. check, enforce, and explain are the one-shot forms.
BoundAuthorizer
interface BoundAuthorizer<TPermission extends string = string> {
check(request: CheckRequest<TPermission>): AuthorizationDecision;
enforce(request: CheckRequest<TPermission>): AuthorizationDecision;
explain(request: CheckRequest<TPermission>, options?: ExplainOptions): DecisionExplanation;
} Checks against one binding. check never throws for malformed input; enforce throws
AuthorizationError on denial; explain adds a trace. See Decisions.
AuthorizerOptions
interface AuthorizerOptions {
readonly onInternalError?: InternalErrorReporter;
} InternalErrorReporter
type InternalErrorReporter = (
error: unknown,
context: {
readonly permission: string;
},
) => void; Called when evaluation itself throws. The decision is still a closed INVALID_REQUEST. The reporter
runs synchronously and cannot influence the decision; a throw or a rejected promise from it is
ignored, and returned promises are not awaited. It is not called for ordinary malformed input.
BindInput
interface BindInput<TRole extends string = string> {
readonly subject: Subject;
readonly principals?: readonly ResourceRef[];
readonly assignments: readonly RoleAssignment<TRole>[];
readonly context?: Readonly<Record<string, unknown>>;
} The binding: see subjects, principals, and assignments. Only these
keys are accepted. principals and context may be omitted or undefined.
CheckRequest
interface CheckRequest<TPermission extends string = string> {
readonly permission: TPermission;
readonly resource: TrustedResource;
readonly field?: string;
} One check: a concrete permission, a trusted resource of that permission’s type, and an optional field
path. An omitted and an undefined field both mean a resource-wide check.
AuthorizationRequest
interface AuthorizationRequest<TRole extends string = string, TPermission extends string = string>
extends BindInput<TRole>,
CheckRequest<TPermission> {} A binding and a check in one object, for the one-shot functions.
Decision types
AuthorizationDecision
interface AuthorizationDecision {
readonly allowed: boolean;
readonly code: DecisionCode;
readonly reason: string;
readonly permission: string;
readonly policyVersion?: string;
readonly matched?: MatchedRule;
} The frozen result of every check. permission is empty when the requested permission was not a
string of at most 257 characters. policyVersion is present when the policy has a version.
matched is present on ALLOWED and EXPLICIT_DENY.
DecisionCode
type DecisionCode =
| "ALLOWED"
| "INVALID_REQUEST"
| "INVALID_SUBJECT"
| "INVALID_ASSIGNMENT"
| "UNKNOWN_ROLE"
| "RESOURCE_MISMATCH"
| "EXPLICIT_DENY"
| "NOT_GRANTED"; See decision codes and evaluation order.
MatchedRule
interface MatchedRule {
readonly effect: "allow" | "deny";
readonly role: string;
readonly permission: string;
readonly via?: ResourceRef;
} The rule that decided. role is the role that defines the rule (for an inherited rule, the inherited
role). permission is the rule’s permission, which may be a wildcard. via names the group principal
whose assignment contributed the rule; it is absent when the subject holds the rule directly.
ExplainOptions
interface ExplainOptions {
readonly detail?: "conditions";
} Only a runtime object whose single own enumerable data property is detail: "conditions" selects
condition detail. Every other value keeps the rule-only explanation.
ConditionTraceResult
type ConditionTraceResult = true | false | "unknown"; ConditionTraceReasonCode
type ConditionTraceReasonCode =
| "SATISFIED"
| "UNSATISFIED"
| "MISSING_FACT"
| "MISSING_OPERAND_FACT"
| "UNSUPPORTED_OPERANDS"; RuleTraceReasonCode
type RuleTraceReasonCode =
| "PERMISSION_MISMATCH"
| "FIELD_MISMATCH"
| "CONDITION_FALSE"
| "CONDITION_UNKNOWN_ALLOW"
| "CONDITION_UNKNOWN_DENY"
| "MATCHED"; ConditionTraceLeaf
interface ConditionTraceLeaf {
readonly kind: "leaf";
readonly path: string;
readonly operator: ValueOperator | "exists";
readonly fact: FactPath;
readonly operandFact?: FactPath;
readonly operandEvaluated?: boolean;
readonly result: ConditionTraceResult;
readonly reasonCode: ConditionTraceReasonCode;
} ConditionTraceLogical
interface ConditionTraceLogical {
readonly kind: "logical";
readonly path: string;
readonly operator: "all" | "any" | "none" | "not";
readonly result: ConditionTraceResult;
readonly children: readonly ConditionTraceNode[];
readonly skippedChildren: number;
readonly childrenTruncated: boolean;
} ConditionTraceNode
type ConditionTraceNode = ConditionTraceLeaf | ConditionTraceLogical; RuleConditionTrace
type RuleConditionTrace =
| { readonly status: "absent" }
| {
readonly status: "not_evaluated";
readonly reasonCode: "PERMISSION_MISMATCH" | "FIELD_MISMATCH";
}
| {
readonly status: "evaluated";
readonly result: ConditionTraceResult;
readonly tree?: ConditionTraceNode;
readonly truncated: boolean;
}; DecisionTraceDetails
interface DecisionTraceDetails {
readonly ruleId: string;
readonly reasonCode: RuleTraceReasonCode;
readonly condition: RuleConditionTrace;
} ruleId is the defining role and rule index in the compiled policy snapshot, such as reader:0.
It is not stable across rule reordering and it is not an assignment id.
DecisionExplanation
interface DecisionExplanation extends AuthorizationDecision {
readonly trace: readonly DecisionTraceEntry[];
readonly traceTruncated: boolean;
readonly conditionTraceTruncated?: boolean;
readonly optionsRejected?: true;
} conditionTraceTruncated is present only when condition detail was accepted. optionsRejected is
present, and true, only when explain() received an options value it does not accept; the
explanation is then rule-only and the decision is unaffected.
DecisionTraceEntry
interface DecisionTraceEntry {
readonly outcome: "matched" | "not_matched";
readonly effect: "allow" | "deny";
readonly role: string;
readonly permission: string;
readonly reason: string;
readonly via?: ResourceRef;
readonly details?: DecisionTraceDetails;
} One evaluated rule. The trace lists denies before allows and stops at the first match; it holds at
most 64 entries. details is present on every retained rule when condition detail was accepted,
and absent otherwise.
Policy types
RolebookPolicy
interface RolebookPolicy<
TRole extends string = string,
TPermission extends string = string,
TResources extends ResourceDefinitions = ResourceDefinitions,
> {
readonly version?: string;
readonly resources: TResources;
readonly roles: Record<TRole, RoleDefinition<TRole, TPermission>>;
} ResourceDefinition
interface ResourceDefinition<TAction extends string = string, TParent extends string = string> {
readonly actions: readonly TAction[];
readonly parent?: TParent;
readonly recursive?: true;
} recursive: true lets resources of the type nest under resources of the same type. It is the only
accepted value; omit the key otherwise. See Recursive resource types.
ResourceDefinitions
type ResourceDefinitions = Record<string, ResourceDefinition>; RoleDefinition
interface RoleDefinition<
TRole extends string = string,
TPermission extends string = string,
TScope extends string = string,
> {
readonly scope: TScope;
readonly inherits?: readonly TRole[];
readonly rules: readonly PolicyRule<TPermission>[];
} PolicyRule
interface PolicyRule<TPermission extends string = string> {
readonly effect: "allow" | "deny";
readonly permission: TPermission;
readonly where?: PolicyCondition;
readonly fields?: readonly string[];
} PolicyCondition
type PolicyCondition =
| {
readonly fact: FactPath;
readonly operator: ValueOperator;
readonly value: ConditionValue;
}
| {
readonly fact: FactPath;
readonly operator: "exists";
readonly value?: boolean;
}
| {
readonly all: readonly PolicyCondition[];
}
| {
readonly any: readonly PolicyCondition[];
}
| {
readonly none: readonly PolicyCondition[];
}
| {
readonly not: PolicyCondition;
}; See conditions.
ValueOperator
type ValueOperator =
| "equals"
| "notEquals"
| "oneOf"
| "noneOf"
| "contains"
| "containsAll"
| "sizeEquals"
| "startsWith"
| "endsWith"
| "lessThan"
| "lessThanOrEqual"
| "greaterThan"
| "greaterThanOrEqual"; ConditionValue
type ConditionValue = PolicyLiteral | FactReference; PolicyLiteral
type PolicyLiteral =
| null
| boolean
| number
| string
| readonly PolicyLiteral[]
| ({
readonly [key: string]: PolicyLiteral;
} & {
readonly fact?: never;
}); A literal object cannot have a fact key. That key is reserved for a
FactReference, and the compiler rejects it in a literal at any depth.
FactPath
type FactPath = `subject.${string}` | `resource.${string}` | `context.${string}`; FactReference
interface FactReference {
readonly fact: FactPath;
} A condition operand that reads another fact, such as { fact: "subject.id" }. It must be an object
with exactly the fact key.
PermissionFromResources
type PermissionFromResources<R extends ResourceDefinitions> = {
[K in keyof R & string]: `${K}:${R[K]["actions"][number] & string}`;
}[keyof R & string]; Every concrete resource:action a resource map declares.
PolicyPermissionFromResources
type PolicyPermissionFromResources<R extends ResourceDefinitions> =
| PermissionFromResources<R>
| {
[K in keyof R & string]: `${K}:*`;
}[keyof R & string]; Every permission a rule may name: the concrete permissions plus one resource:* wildcard per type.
ConcretePermission
type ConcretePermission<TPermission extends string> = TPermission extends `${string}:*`
? never
: TPermission; Removes wildcards from a permission union.
RequestPermission
type RequestPermission<
TPermission extends string,
TResources extends ResourceDefinitions = ResourceDefinitions,
> = string extends keyof TResources
? ConcretePermission<TPermission>
: PermissionFromResources<TResources> | ConcretePermission<TPermission>; The permissions a request may name: every declared concrete permission, never a wildcard.
PolicyDiff
interface PolicyDiff {
readonly identical: boolean;
readonly version?: {
readonly from?: string;
readonly to?: string;
};
readonly resources: {
readonly added: readonly string[];
readonly removed: readonly string[];
readonly changed: readonly ResourceDefinitionChange[];
};
readonly roles: {
readonly added: readonly string[];
readonly removed: readonly string[];
readonly changed: readonly RoleDefinitionChange[];
};
} identical is true when the canonical policy JSON of both sides is equal. version is present only
when the labels differ; an absent side means no label.
ResourceDefinitionChange
interface ResourceDefinitionChange {
readonly resourceType: string;
readonly actionsAdded: readonly string[];
readonly actionsRemoved: readonly string[];
readonly parent?: {
readonly from?: string;
readonly to?: string;
};
readonly recursive?: {
readonly from?: true;
readonly to?: true;
};
} parent is present only when the parent changed; an absent side means no parent. recursive is
present only when the recursive flag changed; an absent side means the type is not recursive.
Turning the flag on changes which resources an assignment can reach, so a diff that only toggles it
is still not identical.
RoleDefinitionChange
interface RoleDefinitionChange {
readonly role: string;
readonly scope?: {
readonly from: string;
readonly to: string;
};
readonly inheritsAdded: readonly string[];
readonly inheritsRemoved: readonly string[];
readonly rulesAdded: readonly PolicyRule[];
readonly rulesRemoved: readonly PolicyRule[];
readonly rulesReordered: boolean;
readonly effectiveRulesAdded: readonly PolicyRule[];
readonly effectiveRulesRemoved: readonly PolicyRule[];
} scope is present only when the scope changed. rulesReordered is true when the direct rules are the
same multiset in a different order. The effectiveRules* lists compare inherited plus direct rules.
Subjects and resources
Subject
interface Subject {
readonly type: string;
readonly id: string;
readonly attributes?: Readonly<Record<string, unknown>>;
} ResourceRef
interface ResourceRef {
readonly type: string;
readonly id: string;
} A { type, id } reference with exactly those keys. type is a policy name; id is an opaque string
of 1 to 128 characters.
RoleAssignment
interface RoleAssignment<TRole extends string = string> {
readonly subject: ResourceRef;
readonly role: TRole;
readonly scope: {
readonly resource: ResourceRef;
readonly appliesTo: "self" | "descendants";
};
} TrustedResource
interface TrustedResource {
readonly ref: ResourceRef;
readonly ancestors: readonly ResourceRef[];
readonly attributes: Readonly<Record<string, unknown>>;
} Build it with trustedResource(). The type proves shape only, not provenance.