RolebookDocs

Access guardrails

@rolebook/guardrails: organization-wide policies that block, hold for approval, or notify on top of role decisions.

@rolebook/guardrails runs organization-wide policies after a Core decision. A policy can block an allowed request, hold it for human approval, or allow it and notify. Each policy is enforced, runs in monitor mode (evaluated and reported, never changing a decision), or stays a draft you only simulate. Recorded checks let you preview a policy’s impact on real traffic before you enforce it.

Guardrails only ever tighten. A request Core denies stays denied with its original code; an allowed request can become BLOCKED or APPROVAL_REQUIRED. No guardrail grants access a role does not give.

The package has no database, network or framework dependency. It ships in-memory stores for the approval queue and the decision log; a production deployment implements the two small store interfaces against its own database.

Not on npm yet

rolebook and @rolebook/guardrails are not on npm yet. The npm package named rolebook is an unrelated project, so do not install it.

Define policies

guardrails.ts
import { createGuardrails, type GuardrailPolicy } from "@rolebook/guardrails";

const prodDeploys: GuardrailPolicy = {
  id: "prod-deploys",
  name: "Production deploys need approval",
  status: "enforced",
  when: [
    { field: "principal", operator: "isAnyOf", values: ["team:platform"] },
    { field: "permission", operator: "matches", values: ["service:deploy", "environment:*"] },
    { field: "scope.environment", operator: "isAnyOf", values: ["production"] },
  ],
  effect: {
    type: "requireApproval",
    approvers: [{ type: "team", id: "security-oncall" }],
    requestTtlSeconds: 900, // a request waits 15 minutes for an answer
    grantTtlSeconds: 900, // an approval lets the subject repeat the check for 15 minutes
  },
  except: [
    {
      id: "sev1",
      label: "During a SEV1 incident",
      enabled: true,
      when: [{ field: "context.incident", operator: "isAnyOf", values: ["sev1"] }],
      notify: "#incidents",
    },
  ],
};

export const guardrails = createGuardrails({
  format: "rolebook.guardrails/1",
  policies: [prodDeploys],
});

createGuardrails() validates the document and compiles it; defineGuardrails() validates without compiling. Both throw GuardrailsError with code INVALID_GUARDRAILS and the path of the first problem.

A condition reads one field:

FieldReads
permission, actionThe requested permission (service:deploy) and the part after the colon (deploy).
resource.type, resource.id, resource.attributes.<name>The checked resource.
scope.<type>The ID of the resource itself or of its ancestor of that type. scope.environment matches a check on the environment or anything inside it. A resource with no ancestor of that type is outside every such scope.
subject.type, subject.id, subject.attributes.<name>The caller.
principalThe caller’s group principals (teams), as type:id.
context.<name>The bound request context.

isAnyOf and isNoneOf compare exact values. matches and notMatches compare strings with * as a wildcard, in linear time. lessThan and greaterThan compare one number. exists and notExists test presence. A multi-valued field (principal, an array attribute) matches isAnyOf and matches when any value does, and isNoneOf and notMatches when none does.

Unknown facts fail closed

All of a policy’s when conditions must hold. A condition whose answer is unknown counts as holding, so a gap in your request facts applies the guardrail rather than skipping it; the match is reported with uncertain: true. Exceptions loosen, so they apply only when every one of their conditions is known to hold. A comparison is unknown when the key is absent, when the value is not comparable (an object, null, or an array holding one), when its type matches none of the listed values (isAnyOf [1] against "1"), and when the whole bag is unavailable: decide() without principals or context, or a replayed record that dropped it.

exists and notExists answer presence instead, which is known for every key of a supplied bag. So rows exists AND rows > 500 skips a request without rows, where rows > 500 alone applies. scope.<type> is always known: core requires ancestry to the root, so an organization-level check is not inside any environment and scope.environment isAnyOf ["production"] is simply false there. A principal condition narrows a policy to those teams.

Precedence

When several enforced policies apply, block wins over requireApproval, which wins over notify. An applied exception turns that one policy into an allow. Every applied policy is listed in decision.enforced, and monitor-mode policies in decision.monitored.

Check requests

Wrap a Core authorizer. The wrapper captures the binding and each request once, as frozen copies with exactly the shape you passed, and gives that same copy to Core, to the guardrails and to onDecision. Input it cannot copy faithfully (an unknown key, an accessor, a malformed array) goes to Core unchanged, and if Core still allows it the check is denied with GUARDRAIL_ERROR, so wrapping never allows what Core alone would refuse. A binding without principals or context leaves them unknown to the guardrails, as in decide(); bind [] or {} when the caller truly has none. A Core denial keeps its own code; a Core call that throws, failing guardrails or a failing clock deny an allowed check with GUARDRAIL_ERROR. The wrapper keeps the authorizer’s role and permission types. Passing a function instead of a Guardrails value lets a running process swap the active set without rebuilding the authorizer.

check.ts
import {
  createApprovals,
  createGuardedAuthorizer,
  createMemoryApprovalStore,
  createMemoryDecisionLog,
  recordFrom,
} from "@rolebook/guardrails";
import {
  createAuthorizer,
  type RoleAssignment,
  type RolebookPolicy,
  type Subject,
  type TrustedResource,
} from "rolebook";

declare const policy: RolebookPolicy;
declare const subject: Subject;
declare const assignments: readonly RoleAssignment[];
declare const resource: TrustedResource;

const approvals = createApprovals({
  store: createMemoryApprovalStore(),
  guardrails,
  tenant: "acme", // required, from your trusted session
});
const decisionLog = createMemoryDecisionLog();

const guarded = createGuardedAuthorizer(createAuthorizer(policy), () => guardrails, {
  onDecision: (event) => decisionLog.append(recordFrom(event, { id: crypto.randomUUID() })),
});

const decision = guarded
  .bind({
    subject,
    principals: [{ type: "team", id: "platform" }],
    assignments,
    context: { incident: "none" },
  })
  .check(
    { permission: "service:deploy", resource },
    { grants: await approvals.grantsFor(subject) },
  );

if (decision.code === "APPROVAL_REQUIRED") {
  // Answer "pending"; nothing runs until someone approves and the caller checks again.
  await approvals.request({ decision, reason: "ship the fix" });
}
// Proceed only when decision.allowed (ALLOWED or APPROVED); decision.notify lists who to tell.
export const allowed = decision.allowed;

You can also call guardrails.decide() with a Core decision you already have. The checked permission is the decision’s own; pass the principals, field and context the Core check was bound with. decide() never throws: a fault, an unreadable input, an unknown input key, an invalid now or a decision whose allowed and code disagree returns GUARDRAIL_ERROR, which is a denial. A failing or rejected onDecision callback never changes a decision.

Approvals

  • request({ decision }) takes the subject, permission, field, resource and ancestry from the guarded decision, and the approvers and TTLs from the active policy. Every missing approval is checked before anything is written; a decision made under other terms fails with APPROVAL_STALE. Pass the decision straight from your server-side check.
  • One live pending request exists per tenant, operation and terms; concurrent retries share it.
  • approve() and reject() need the active policy to still have the request’s terms (APPROVAL_STALE) and an actor among that policy’s current approvers who is not the requester (SELF_APPROVAL). A removed approver can neither grant nor reject. The actor is copied once, so the identity authorized is the identity recorded.
  • Every read and change uses the store’s clock (store.now()), read under its lock for changes. A pending request whose expiresAt is not after it (or is unreadable) is expired. A policy edited while its request is being opened makes that open fail with APPROVAL_STALE, whether it would create a request or reuse one.
  • An approval is a grant for that exact operation, ancestry included. It lasts the active policy’s grantTtlSeconds, may be repeated until then and is not consumed. grantsFor() returns the ones live at the store’s time, at most 500, each stamped with that instant as readAt and noted, in this process, with a monotonic clock reading. check() estimates the store’s current time as readAt plus the monotonic time since and counts a grant only while expiresAt is after both that estimate and its own clock, so a host behind the store never extends a grant. A grant without the note (copied, serialized or from another process) never counts. The reading is taken before the store’s time is sampled, and two copies of the package in one process share the notes. An edit to the policy does not revoke grants already given.
  • Grants are server-side authority: load them with grantsFor(), never from a client. A malformed grant record is ignored on its own, without hiding valid ones.

tenant is required and comes from your trusted session: one tenant’s requests, answers and grants never reach another’s, even in a shared store with repeated resource IDs. Ancestry alone does not separate queues. Load an actor’s principals from that same tenant.

An ApprovalStore makes each method atomic and supplies the time: now() for reads, and the time read after its lock for changes. open(key, create, isLive) gets or creates the pending request for key, calling create(now) under the lock. update(id, change) calls change(row, now) under a lock on the row and writes its result. list() keeps query.tenant, judges status at query.at and filters live grants before applying limit. createMemoryApprovalStore({ clock }) is for tests, demos and single-process deployments.

Impact previews

Record checks with recordFrom() into any DecisionLog (createMemoryDecisionLog() is a bounded ring buffer), then replay a draft against a window:

preview.ts
import { simulateGuardrail } from "@rolebook/guardrails";

const since = new Date(Date.now() - 7 * 86_400_000);
const until = new Date();
const records = await decisionLog.read({ since, until, limit: 50_000 });
export const impact = simulateGuardrail({ ...prodDeploys, status: "draft" }, records, {
  since,
  until,
  truncated: records.length === 50_000,
  history: await approvals.list({ policyId: prodDeploys.id }),
});
// impact.matched, impact.byEffect.requireApproval, impact.samples, impact.matchesPerDay

The simulation treats the policy as enforced whatever its status, counts only checks Core allowed (the only ones a guardrail can change), and writes nothing.

Decision records hold subject, resource and context attributes so conditions can be replayed. Pass keep: { subjectAttributes: false } (or resourceAttributes, context) to recordFrom() to drop what you must not keep, and apply your own retention. The record lists what it dropped, so a condition on a dropped bag, even exists, replays as unknown and the match as uncertain. matchesPerDay divides by the window’s actual length.

Limits

At most 256 policies, 16 conditions per policy or exception, 64 values per condition, 8 exceptions and 32 approvers per policy. TTLs are whole seconds from 60 to 30 days. See GUARDRAIL_LIMITS.

guardrailsDigest() returns a sha256: content address over the canonical JSON of a validated set, so two processes can confirm they run the same version. Key order does not matter and an empty except list equals none; the order of array entries does. Validation reads each property once from its descriptor and refuses accessors and sparse arrays.

The package imports node:crypto, so it is not offered for a browser bundle. Its own tests run on Bun; no packed Node fixture exercises it yet.

API reference

ApprovalActor

interface ApprovalActor {
  readonly subject: ResourceRef;
  readonly principals?: readonly ResourceRef[];
}

ApprovalQuery

interface ApprovalQuery {
  readonly status?: ApprovalStatus;
  readonly subject?: ResourceRef;
  readonly policyId?: string;
  readonly limit?: number;
}

ApprovalRequest

interface ApprovalRequest extends GuardedOperation {
  readonly id: string;
  readonly tenant: string;
  readonly key: string;
  readonly policyId: string;
  readonly revision?: number;
  readonly terms: string;
  readonly status: ApprovalStatus;
  readonly approvers: readonly ResourceRef[];
  readonly reason?: string;
  readonly createdAt: string;
  readonly expiresAt: string;
  readonly grantTtlSeconds: number;
  readonly resolution?: {
    readonly by: ResourceRef;
    readonly at: string;
    readonly comment?: string;
    readonly grantExpiresAt?: string;
  };
}

ApprovalStatus

type ApprovalStatus = "pending" | "approved" | "rejected" | "cancelled" | "expired";

ApprovalStore

interface ApprovalStore {
  now(): Promise<Date>;
  open(key: string, create: (now: Date) => ApprovalRequest, isLive: (row: ApprovalRequest, now: Date) => boolean): Promise<ApprovalRequest>;
  get(id: string): Promise<ApprovalRequest | undefined>;
  list(query: ApprovalStoreQuery): Promise<readonly ApprovalRequest[]>;
  update(id: string, change: (current: ApprovalRequest, now: Date) => ApprovalRequest): Promise<ApprovalRequest | undefined>;
}

Approvals

interface Approvals {
  request(input: {
    readonly decision: GuardedDecision;
    readonly reason?: string;
  }): Promise<readonly ApprovalRequest[]>;
  approve(input: {
    readonly requestId: string;
    readonly actor: ApprovalActor;
    readonly comment?: string;
  }): Promise<ApprovalRequest>;
  reject(input: {
    readonly requestId: string;
    readonly actor: ApprovalActor;
    readonly comment?: string;
  }): Promise<ApprovalRequest>;
  cancel(input: {
    readonly requestId: string;
    readonly actor: ApprovalActor;
  }): Promise<ApprovalRequest>;
  get(requestId: string): Promise<ApprovalRequest | undefined>;
  list(query?: ApprovalQuery): Promise<readonly ApprovalRequest[]>;
  grantsFor(subject: ResourceRef): Promise<readonly ApprovalGrant[]>;
  canApprove(request: ApprovalRequest, actor: ApprovalActor): boolean;
}

ApprovalsOptions

interface ApprovalsOptions {
  readonly store: ApprovalStore;
  readonly guardrails: Guardrails | (() => Guardrails);
  readonly tenant: string;
  readonly ids?: () => string;
}

createApprovals

function createApprovals(options: ApprovalsOptions): Approvals;

createMemoryApprovalStore

function createMemoryApprovalStore(options?: {
  readonly clock?: () => Date;
}): ApprovalStore & {
  readonly size: number;
};

medianApprovalWaitSeconds

function medianApprovalWaitSeconds(requests: readonly ApprovalRequest[]): number | undefined;

DecisionLog

interface DecisionLog {
  append(record: DecisionRecord): void | Promise<void>;
  read(query: {
    readonly since: Date;
    readonly until: Date;
    readonly limit: number;
  }): Promise<readonly DecisionRecord[]>;
}

DecisionRecord

interface DecisionRecord {
  readonly id: string;
  readonly at: string;
  readonly subject: Subject;
  readonly principals: readonly ResourceRef[];
  readonly permission: string;
  readonly field?: string;
  readonly resource: TrustedResource;
  readonly context: Readonly<Record<string, unknown>>;
  readonly dropped?: readonly DroppedFacts[];
  readonly coreAllowed: boolean;
  readonly code: GuardedDecisionCode;
  readonly enforced: readonly string[];
  readonly monitored: readonly string[];
}

RecordOptions

interface RecordOptions {
  readonly id: string;
  readonly keep?: {
    readonly subjectAttributes?: boolean;
    readonly resourceAttributes?: boolean;
    readonly context?: boolean;
  };
}

createMemoryDecisionLog

function createMemoryDecisionLog(capacity?: number): DecisionLog & {
  readonly size: number;
};

recordFrom

function recordFrom(event: GuardedCheckEvent, options: RecordOptions): DecisionRecord;

GuardrailsErrorCode

type GuardrailsErrorCode = "INVALID_GUARDRAILS" | "APPROVAL_NOT_FOUND" | "APPROVAL_NOT_PENDING" | "APPROVAL_EXPIRED" | "NOT_AN_APPROVER" | "SELF_APPROVAL" | "NOT_THE_REQUESTER" | "NOTHING_TO_APPROVE" | "APPROVAL_STALE";

defineGuardrailPolicy

function defineGuardrailPolicy(value: unknown): GuardrailPolicy;

defineGuardrails

function defineGuardrails(value: unknown): GuardrailSet;

GUARDRAIL_LIMITS

const GUARDRAIL_LIMITS: Readonly<{
  policies: 256;
  conditions: 16;
  values: 64;
  exceptions: 8;
  approvers: 32;
  text: 256;
  description: 1024;
  refId: 128;
  minTtlSeconds: 60;
  maxTtlSeconds: number;
}>;

GUARDRAILS_FORMAT

const GUARDRAILS_FORMAT = "rolebook.guardrails/1";

GuardrailsError

class GuardrailsError extends Error {
  readonly code: GuardrailsErrorCode;
  constructor(code: GuardrailsErrorCode, message: string);
}

guardrailsDigest

function guardrailsDigest(set: GuardrailSet): string;

isGuardrailField

function isGuardrailField(value: unknown): boolean;

GuardedAuthorizerOptions

interface GuardedAuthorizerOptions {
  readonly onDecision?: (event: GuardedCheckEvent) => unknown;
  readonly clock?: () => Date;
}

GuardedBoundAuthorizer

interface GuardedBoundAuthorizer<TPermission extends string = string> {
  check(request: CheckRequest<TPermission>, options?: {
    readonly grants?: readonly ApprovalGrant[];
  }): GuardedDecision;
}

GuardedCheckEvent

interface GuardedCheckEvent {
  readonly at: string;
  readonly subject: Subject;
  readonly principals?: readonly ResourceRef[];
  readonly permission: string;
  readonly field?: string;
  readonly resource: TrustedResource;
  readonly context?: Readonly<Record<string, unknown>>;
  readonly decision: GuardedDecision;
}

Guardrails

interface Guardrails {
  readonly set: GuardrailSet;
  decide(input: GuardrailInput): GuardedDecision;
}

createGuardedAuthorizer

function createGuardedAuthorizer<TRole extends string, TPermission extends string>(authorizer: Authorizer<TRole, TPermission>, guardrails: Guardrails | (() => Guardrails), options?: GuardedAuthorizerOptions): {
  bind(input: BindInput<TRole>): GuardedBoundAuthorizer<TPermission>;
};

createGuardrails

function createGuardrails(value: GuardrailSet | unknown): Guardrails;

GuardrailImpact

interface GuardrailImpact {
  readonly policyId: string;
  readonly scanned: number;
  readonly considered: number;
  readonly matched: number;
  readonly byEffect: Readonly<Record<GuardrailMatchEffect, number>>;
  readonly uncertain: number;
  readonly distinctSubjects: number;
  readonly matchesPerDay: number;
  readonly medianApprovalWaitSeconds?: number;
  readonly samples: readonly ImpactSample[];
  readonly truncated: boolean;
}

ImpactSample

interface ImpactSample {
  readonly recordId: string;
  readonly at: string;
  readonly subject: ResourceRef;
  readonly permission: string;
  readonly resource: ResourceRef;
  readonly effect: GuardrailMatchEffect;
  readonly uncertain: boolean;
}

SimulateOptions

interface SimulateOptions {
  readonly since: Date;
  readonly until: Date;
  readonly sampleLimit?: number;
  readonly truncated?: boolean;
  readonly history?: readonly ApprovalRequest[];
}

simulateGuardrail

function simulateGuardrail(value: GuardrailPolicy | unknown, records: readonly DecisionRecord[], options: SimulateOptions): GuardrailImpact;

DroppedFacts

type DroppedFacts = "subjectAttributes" | "resourceAttributes" | "context" | "principals";

ApprovalStoreQuery

interface ApprovalStoreQuery extends ApprovalQuery {
  readonly tenant: string;
  readonly at: string;
  readonly grantLiveAt?: string;
}

GuardrailStatus

type GuardrailStatus = "enforced" | "monitor" | "draft";

GuardrailField

type GuardrailField = "permission" | "action" | "resource.type" | "resource.id" | `resource.attributes.${string}` | `scope.${string}` | "subject.type" | "subject.id" | `subject.attributes.${string}` | "principal" | `context.${string}`;

GuardrailOperator

type GuardrailOperator = "isAnyOf" | "isNoneOf" | "matches" | "notMatches" | "exists" | "notExists" | "lessThan" | "greaterThan";

GuardrailScalar

type GuardrailScalar = string | number | boolean;

GuardrailCondition

type GuardrailCondition = {
  readonly field: GuardrailField;
  readonly operator: "isAnyOf" | "isNoneOf";
  readonly values: readonly GuardrailScalar[];
} | {
  readonly field: GuardrailField;
  readonly operator: "matches" | "notMatches";
  readonly values: readonly string[];
} | {
  readonly field: GuardrailField;
  readonly operator: "exists" | "notExists";
} | {
  readonly field: GuardrailField;
  readonly operator: "lessThan" | "greaterThan";
  readonly values: readonly [
    number
  ];
};

GuardrailEffect

type GuardrailEffect = {
  readonly type: "block";
  readonly message?: string;
} | {
  readonly type: "requireApproval";
  readonly approvers: readonly ResourceRef[];
  readonly requestTtlSeconds: number;
  readonly grantTtlSeconds: number;
} | {
  readonly type: "notify";
  readonly target: string;
};

GuardrailException

interface GuardrailException {
  readonly id: string;
  readonly label?: string;
  readonly enabled: boolean;
  readonly when: readonly GuardrailCondition[];
  readonly notify?: string;
}

GuardrailPolicy

interface GuardrailPolicy {
  readonly id: string;
  readonly name: string;
  readonly description?: string;
  readonly status: GuardrailStatus;
  readonly revision?: number;
  readonly when: readonly GuardrailCondition[];
  readonly effect: GuardrailEffect;
  readonly except?: readonly GuardrailException[];
}

GuardrailSet

interface GuardrailSet {
  readonly format: "rolebook.guardrails/1";
  readonly policies: readonly GuardrailPolicy[];
}

GuardedOperation

interface GuardedOperation {
  readonly subject: ResourceRef;
  readonly permission: string;
  readonly field?: string;
  readonly resource: ResourceRef;
  readonly ancestors: readonly ResourceRef[];
}

ApprovalGrant

interface ApprovalGrant extends GuardedOperation {
  readonly requestId: string;
  readonly policyId: string;
  readonly approvedBy: ResourceRef;
  readonly expiresAt: string;
  readonly readAt: string;
}

GuardrailInput

interface GuardrailInput {
  readonly decision: AuthorizationDecision;
  readonly subject: Subject;
  readonly principals?: readonly ResourceRef[];
  readonly field?: string;
  readonly resource: TrustedResource;
  readonly context?: Readonly<Record<string, unknown>>;
  readonly grants?: readonly ApprovalGrant[];
  readonly now?: Date;
}

GuardrailMatchEffect

type GuardrailMatchEffect = "block" | "requireApproval" | "notify" | "exception";

GuardrailMatch

interface GuardrailMatch {
  readonly policyId: string;
  readonly revision?: number;
  readonly effect: GuardrailMatchEffect;
  readonly uncertain: boolean;
  readonly exceptionId?: string;
  readonly approvedBy?: {
    readonly requestId: string;
    readonly approver: ResourceRef;
  };
}

PendingApproval

interface PendingApproval {
  readonly policyId: string;
  readonly revision?: number;
  readonly approvers: readonly ResourceRef[];
  readonly requestTtlSeconds: number;
  readonly grantTtlSeconds: number;
}

GuardedDecisionCode

type GuardedDecisionCode = Exclude<DecisionCode, "ALLOWED"> | "ALLOWED" | "APPROVED" | "BLOCKED" | "APPROVAL_REQUIRED" | "GUARDRAIL_ERROR";

GuardedDecision

interface GuardedDecision {
  readonly allowed: boolean;
  readonly code: GuardedDecisionCode;
  readonly reason: string;
  readonly permission: string;
  readonly decision: AuthorizationDecision;
  readonly enforced: readonly GuardrailMatch[];
  readonly monitored: readonly GuardrailMatch[];
  readonly approvals?: readonly PendingApproval[];
  readonly operation?: GuardedOperation;
  readonly notify: readonly string[];
  readonly message?: string;
}