RolebookDocs

rolebook/authoring

The exports of the optional authoring entry point - fact schemas, policy diagnostics, and fact validation.

import { ... } from "rolebook/authoring". An optional entry point with no peers: rolebook never imports it, so an application that does not use it does not load it. For usage, see Fact schemas.

Nothing on this page changes what check, enforce, or explain decide, and nothing here is a grant. Validation checks the shape of facts. It cannot prove they are fresh or where they came from.

Schemas

defineFactSchema

function defineFactSchema(input: unknown): FactSchema;

Validates, copies, normalizes, and deeply freezes a fact schema, and returns the schema handle. Throws a FactSchemaError for malformed input.

The input is snapshotted first, without running getters. A non-plain object, an accessor, a symbol key, a cycle, undefined, or a non-finite number fails the snapshot, as does going over a bound: 4096 nodes, 32 levels, 64 KiB of serialized UTF-8, 64 keys in an object (256 in facts), 128 array elements, or 512 characters in a string. A failed snapshot, or a header that is not exactly format, version, id, and facts, is one INVALID_SCHEMA diagnostic at the empty pointer. version must be 1; there is no interpretation of later versions.

After that, each declaration is checked, in sorted path order, and each bad one is one INVALID_SCHEMA diagnostic at /facts/<path>. A path is bad when it is not a fact path, when it redeclares subject.type, subject.id, resource.type, or resource.id, when its declaration is malformed, or when an ancestor of it is a reserved identity or is declared without object or json.

The returned handle’s facts are in sorted path order, with required always present. The other functions accept only handles that this copy of the module returned. A structurally identical object, including a handle that went through JSON.stringify, is not accepted: pass it through defineFactSchema again.

FactSchema

interface FactSchema {
  readonly format: "rolebook-fact-schema";
  readonly version: 1;
  readonly id: string;
  readonly facts: Readonly<
    Record<
      FactPath,
      {
        readonly types: readonly FactType[];
        readonly required: boolean;
      }
    >
  >;
}

The normalized, frozen schema. id is 1 to 64 ASCII characters: a letter, then letters, digits, _, or -. facts holds 0 to 256 declarations. The handle carries no brand property; its origin is tracked privately.

FactDeclaration

interface FactDeclaration {
  readonly types: readonly FactType[];
  readonly required?: boolean;
}

One declaration as written. types is a non-empty list of at most 6 distinct types. required defaults to false and concerns presence, not non-null: a required fact whose value is null passes when "null" is one of its types. A declaration accepts only these two keys.

FactType

type FactType =
  | "string"
  | "number"
  | "boolean"
  | "null"
  | "object"
  | "json"
  | {
      readonly array: "string" | "number" | "boolean" | "null" | "json";
    };
TypeA value matches when it is
"string", "number", "boolean"That JavaScript type. Numbers are finite.
"null"null.
"object"A plain object. Not an array, and not null.
{ array: T }An array whose every element matches T. { array: "json" } is any array.
"json"Any value. It must be the declaration’s only type.

A declaration has at most one array type. object and json do not declare their children: a path below them is known only when it is declared itself.

FactSchemaError

class FactSchemaError extends Error {
  readonly code: "INVALID_SCHEMA";
  readonly diagnostics: readonly Diagnostic[];
  readonly truncated: boolean;
  constructor(diagnostics: readonly Diagnostic[], truncated: boolean);
}

Thrown only by defineFactSchema. The message is always Invalid Rolebook fact schema; the frozen diagnostics say where. name is "FactSchemaError".

Policy checks

analyzePolicy

function analyzePolicy(policy: unknown, schema: FactSchema): PolicyAnalysis;

Calls definePolicy once on policy and analyses only that frozen result, so changing the input afterwards cannot hide a diagnostic. Never throws. A schema that is not a handle from defineFactSchema is one INVALID_SCHEMA diagnostic, and a policy definePolicy rejects is one INVALID_POLICY diagnostic, both at the empty pointer and without the error’s text.

Otherwise it visits roles in sorted name order and each role’s direct rules in order. Inherited rules are analysed once, in the role that defines them. For each rule it reports DUPLICATE_RULE when the rule’s canonical JSON equals an earlier rule of the same role, then walks the rule’s where, every node in order, whatever a runtime short circuit would skip. For each comparison it reports an undeclared left fact, then an undeclared fact-reference operand, as UNKNOWN_FACT, and, when both are known, an operand type problem as INCOMPATIBLE_OPERANDS or POSSIBLY_UNSUPPORTED_OPERANDS. The reserved identities are known strings without being declared.

compilePolicy

function compilePolicy(policy: unknown, schema: FactSchema): CompilePolicyResult;

analyzePolicy, plus the compiled policy when there is no error. Warnings do not prevent it. The policy is the object definePolicy returned for the same input, so its canonicalPolicyJson is the same as defining it without a schema.

PolicyAnalysis

interface PolicyAnalysis {
  readonly ok: boolean;
  readonly diagnostics: readonly Diagnostic[];
  readonly truncated: boolean;
}

ok is false when there is any error, including one omitted after the 128-diagnostic cap. truncated is true when a diagnostic was omitted. The whole result is frozen.

CompilePolicyResult

type CompilePolicyResult =
  | {
      readonly ok: true;
      readonly policy: RolebookPolicy;
      readonly diagnostics: readonly Diagnostic[];
      readonly truncated: boolean;
    }
  | {
      readonly ok: false;
      readonly diagnostics: readonly Diagnostic[];
      readonly truncated: boolean;
    };

A failed result has no policy property.

Fact validation

validateFacts

function validateFacts(
  schema: FactSchema,
  facts: {
    readonly subject: Subject;
    readonly resource: TrustedResource;
    readonly context?: Readonly<Record<string, unknown>>;
  },
): ValidateFactsResult;

Checks a copy of the facts an application is about to bind against the schema. It performs no authorization, and a passing result is never a grant. Never throws.

It first captures subject, resource, and context once and validates them with Core’s own snapshot and shape rules, the same ones bind and check apply. Any structural fault, including an object with other keys, a malformed subject or trusted resource, an undefined value anywhere inside, or a value over Core’s limits, is one INVALID_FACTS diagnostic at the empty pointer. An omitted or undefined context is treated as absent.

Then, for each declared path in sorted order, it reads the fact the way Core does, through own properties of plain objects only. The reserved type and id come from the subject and the resource reference, never from the attribute bags. A required fact that does not resolve is MISSING_REQUIRED_FACT; a fact that resolves to a value no declared type matches is FACT_TYPE_MISMATCH. An optional fact that does not resolve passes. Undeclared properties pass and are not removed. Pointers are logical, such as /resource/ownerId for resource.ownerId, and not locations in the input.

ValidateFactsResult

interface ValidateFactsResult {
  readonly ok: boolean;
  readonly diagnostics: readonly Diagnostic[];
  readonly truncated: boolean;
}

The same shape and cap as PolicyAnalysis.

Diagnostics

Diagnostic

interface Diagnostic {
  readonly severity: "error" | "warning";
  readonly code: DiagnosticCode;
  readonly pointer: string;
  readonly message: string;
}

pointer is an RFC 6901 JSON Pointer relative to the operation’s input, not a line or column. message is a fixed sentence per code and never contains a path, literal, or value. Its wording may change between versions: key on code, severity, and pointer.

DiagnosticCode

type DiagnosticCode =
  | "INVALID_SCHEMA"
  | "INVALID_POLICY"
  | "UNKNOWN_FACT"
  | "INCOMPATIBLE_OPERANDS"
  | "POSSIBLY_UNSUPPORTED_OPERANDS"
  | "DUPLICATE_RULE"
  | "INVALID_FACTS"
  | "MISSING_REQUIRED_FACT"
  | "FACT_TYPE_MISMATCH";

Each code has one severity. POSSIBLY_UNSUPPORTED_OPERANDS and DUPLICATE_RULE are warnings; every other code is an error. See the code table.

toEditorDiagnostics

function toEditorDiagnostics(diagnostics: readonly Diagnostic[]): readonly EditorDiagnostic[];

Returns a fresh frozen copy of each diagnostic, in order, for an editor integration. It reads no source file and writes nothing. It checks its input without running getters: at most 128 entries, each with exactly the four diagnostic keys, a known code with that code’s severity, a valid JSON Pointer of at most 2048 characters, and a non-empty message of at most 160 characters. Anything else throws TypeError("Invalid diagnostics").

EditorDiagnostic

interface EditorDiagnostic {
  readonly pointer: string;
  readonly severity: "error" | "warning";
  readonly code: DiagnosticCode;
  readonly message: string;
}

The pointer is still a JSON Pointer into the policy, schema, or facts, not a source position. Mapping it to a line is the editor’s job.