A TypeScript-native, Zanzibar-style relationship-based authorization (ReBAC) engine — every release gated by a live differential against OpenFGA and SpiceDB.
You describe a permission model, store relationships (tuples) — who relates how to what — and ask check / list questions. It runs in-process: a check is a ~microsecond function call, not a network round-trip, and the engine bundles to ~28KB minified (~8KB gzip) for Cloudflare Workers and the edge (measured).
- In-process / edge. No server, no network hop — a check is a local function call (~3µs direct, ~17µs for a wide fan-out).
- TypeScript-native. The model is code, authored with a typed builder; queries are type-checked against it.
- Trustworthy by construction. Every release is proven by a five-way differential against OpenFGA, SpiceDB, a Datalog oracle, and an independent reference evaluator — plus property tests and fuzzing. See TRUST.md.
- AI-authored, verification-first. This library was written by an AI coding agent under human direction, with no line-by-line human review — and the methodology assumes exactly that: the correctness claim rests on agreement with live external engines (OpenFGA, SpiceDB) that the author didn't write, behind a mechanically-enforced oracle firewall, mutation-tested so the suite can't just mirror the implementation. TRUST.md states the full provenance, what the checks do and don't cover, and where residual risk concentrates — read it and judge whether that risk profile fits your use case.
New to relationship-based authorization? Read ReBAC & tuples first. Otherwise, start here.
The same honesty that governs correctness applies to fit. Choose @zanzibar-ts/core
when your checks happen inside one app or Worker (in-process, function-call latency, zero extra
infrastructure), you deploy to the edge (Workers + D1), and you want the model in TypeScript —
type-checked against your queries and versioned with your code.
Prefer a hosted/standalone engine (OpenFGA, SpiceDB, and friends) when many services in several languages need one authorization source of truth over the network, you need a Watch/changefeed stream (deliberately not offered), or your tuple data needs horizontally-scaled dedicated storage beyond what your process or a D1 database holds.
The two paths stay connected: the model IR is OpenFGA's JSON, and
@zanzibar-ts/dsl lowers OpenFGA DSL text
directly — so you can start in-process and migrate to a hosted engine later (or arrive from one)
without remodeling.
npm install @zanzibar-ts/core # Node / BunExperimenting inside a clone of this repo instead?
apps/examples/already has the packages wired up — drop amy-experiment.test.tsthere (any docs example pastes straight in) and runnpx vitest run --project playgroundfrom the repo root. Every example on this page runs in CI against the published surface.
Define a model, create an in-memory engine, write a relationship, and check it — end to end. Anne is
a member of the eng group, and the eng group is a viewer of the readme, so anne can view the
readme:
import { deepStrictEqual as assertEquals } from 'node:assert/strict';
import { defineModel } from '@zanzibar-ts/core/model';
import { createEngine } from '@zanzibar-ts/core';
// 1. Define the model — types and how permissions are derived. Checked by `tsc`.
const authz = defineModel((t) => ({
user: t.type(),
group: t.type({
// a group's members are users, or members of nested groups
member: t.assign('user', 'group#member'),
}),
document: t.type({
// a viewer is anyone assigned directly, OR a member of an assigned group
viewer: t.assign('user', 'group#member'),
}),
}));
// 2. Create an engine (in-memory by default).
const engine = createEngine(authz);
// 3. Write relationships.
await engine.write([
{ object: 'group:eng', relation: 'member', subject: 'user:anne' },
{ object: 'document:readme', relation: 'viewer', subject: 'group:eng#member' },
]);
// 4. Check. A decision is a Result VALUE — it never throws for "deny".
const decision = await engine.check({
object: 'document:readme',
relation: 'viewer',
subject: 'user:anne',
});
assertEquals(decision, { ok: true, value: true }); // ✅ anne views the readme via group:eng#memberThat is the whole loop. The rest of this page expands each piece.
The examples alias Node's
deepStrictEqualtoassertEqualsonly so they double as runnable tests — it is not part of@zanzibar-ts/core. In your own code you'd branch on the returnedResult(see Checking) instead of asserting.
defineModel((t) => schema) builds and validates a model with the same engine used everywhere
else, so an invalid model throws at definition time (a setup fault) with the dangling reference
named. The toolkit t gives you the building blocks of a relation:
| Combinator | Meaning | OpenFGA term |
|---|---|---|
t.assign('user', 'group#member') |
directly assignable: a user, or a group's members |
[this] |
t.from('editor') |
reuse another relation on the same object | computed userset |
t.arrow('parent', 'viewer') |
follow parent to another object, check viewer there |
tuple-to-userset |
t.or(a, b, …) |
union — granted if any child grants | union |
t.and(a, b, …) |
intersection — granted only if every child grants | intersection |
t.butNot(base, sub) |
exclusion — granted by base unless also sub |
difference |
t.with('user', 'cond') |
a conditioned grant (ABAC; see below) | [user with cond] |
An assign reference is one of three forms: 'user' (a type), 'group#member' (a relation on a
type — a "userset"), or 'user:*' (a wildcard — everyone of that type).
Because group.member lists 'group#member' among its own assignable types, groups nest
arbitrarily — a member of a member group is a member, resolved transitively. The
ReBAC & tuples concept shows a two-level nesting check
end to end, and the GitHub roles recipe nests teams the
same way.
Putting the computed (from) and arrow combinators together gives the canonical document model — a
viewer is anyone assigned directly, or an editor, or a viewer of the parent folder:
import { deepStrictEqual as assertEquals } from 'node:assert/strict';
import { defineModel } from '@zanzibar-ts/core/model';
import { createEngine } from '@zanzibar-ts/core';
const authz = defineModel((t) => ({
user: t.type(),
folder: t.type({ viewer: t.assign('user') }),
document: t.type({
parent: t.assign('folder'),
editor: t.assign('user'),
viewer: t.or(
t.assign('user'), // direct grants
t.from('editor'), // editors can also view
t.arrow('parent', 'viewer'), // inherit from the parent folder
),
}),
}));
const engine = createEngine(authz);
await engine.write([
{ object: 'document:readme', relation: 'parent', subject: 'folder:handbook' },
{ object: 'folder:handbook', relation: 'viewer', subject: 'user:carol' },
]);
// carol is a viewer of the parent folder, so she inherits view on the document:
assertEquals(
await engine.check({ object: 'document:readme', relation: 'viewer', subject: 'user:carol' }),
{ ok: true, value: true },
);check returns a Result: { ok: true, value } for a decision, { ok: false, error } for an
error category. It never throws for a decision, so "deny" ({ ok: true, value: false }) and
"couldn't decide" ({ ok: false, error: '…' }) stay distinct and explicit. Read it by branching on
ok:
import { deepStrictEqual as assertEquals } from 'node:assert/strict';
import { defineModel } from '@zanzibar-ts/core/model';
import { createEngine } from '@zanzibar-ts/core';
const engine = createEngine(
defineModel((t) => ({
user: t.type(),
document: t.type({ viewer: t.assign('user') }),
})),
);
const decision = await engine.check({
object: 'document:readme',
relation: 'viewer',
subject: 'user:anne',
});
// No tuple was written, so anne is denied — a decision, not an error:
assertEquals(decision, { ok: true, value: false });
if (decision.ok && decision.value) throw new Error('unreachable');listObjects answers "what can this subject access?" and listUsers answers "who can access
this?". Both return a Result of string references.
import { deepStrictEqual as assertEquals } from 'node:assert/strict';
import { defineModel } from '@zanzibar-ts/core/model';
import { createEngine } from '@zanzibar-ts/core';
const engine = createEngine(
defineModel((t) => ({
user: t.type(),
document: t.type({ viewer: t.assign('user'), editor: t.assign('user') }),
})),
);
await engine.write([
{ object: 'document:readme', relation: 'viewer', subject: 'user:anne' },
{ object: 'document:readme', relation: 'editor', subject: 'user:bob' },
]);
// Which documents can anne view?
assertEquals(
await engine.listObjects({ subject: 'user:anne', type: 'document', relation: 'viewer' }),
{ ok: true, value: ['document:readme'] },
);
// Who can edit the readme?
assertEquals(
await engine.listUsers({ object: 'document:readme', relation: 'editor', userType: 'user' }),
{ ok: true, value: ['user:bob'] },
);Where listUsers gives you the flattened set of users, expand gives you the structure: how
object#relation is composed, one level deep — the natural shape for a permissions panel ("shared
with anne, and everyone in eng; editors can also view"). The tree mirrors OpenFGA's Expand: direct
subjects appear as a leaf-users node, and computed/arrow branches appear as pointers
(leaf-computed / leaf-ttu) you can expand further on demand:
import { deepStrictEqual as assertEquals } from 'node:assert/strict';
import { defineModel } from '@zanzibar-ts/core/model';
import { createEngine } from '@zanzibar-ts/core';
const engine = createEngine(
defineModel((t) => ({
user: t.type(),
group: t.type({ member: t.assign('user', 'group#member') }),
document: t.type({
editor: t.assign('user'),
viewer: t.or(t.assign('user', 'group#member'), t.from('editor')),
}),
})),
);
await engine.write([
{ object: 'document:readme', relation: 'viewer', subject: 'user:anne' },
{ object: 'document:readme', relation: 'viewer', subject: 'group:eng#member' },
{ object: 'document:readme', relation: 'editor', subject: 'user:bob' },
]);
assertEquals(await engine.expand({ object: 'document:readme', relation: 'viewer' }), {
ok: true,
value: {
kind: 'union',
children: [
// the direct grants — a whole userset and a concrete user (sorted):
{ kind: 'leaf-users', users: ['group:eng#member', 'user:anne'] },
// a POINTER to the editor branch — expand `document:readme#editor` to resolve it:
{ kind: 'leaf-computed', userset: 'document:readme#editor' },
],
},
});The tree is deliberately shallow (OpenFGA-shaped): pointers are not auto-resolved, so one call stays cheap on a deep model and you choose how far to walk.
A relationship can carry a condition: a CEL expression
over per-request values, so the grant holds only while the condition is true. Conditions are
declared with the standalone condition helper and referenced by name from t.with(type, name):
import { deepStrictEqual as assertEquals } from 'node:assert/strict';
import { condition, defineModel } from '@zanzibar-ts/core/model';
import { createEngine } from '@zanzibar-ts/core';
const authz = defineModel(
(t) => ({
user: t.type(),
document: t.type({
// viewers are granted only while the grant has not expired
viewer: t.assign(t.with('user', 'unexpired')),
}),
}),
{
conditions: {
unexpired: condition('now < expiry', { now: 'timestamp', expiry: 'timestamp' }),
},
},
);
const engine = createEngine(authz);
await engine.write([
{
object: 'document:readme',
relation: 'viewer',
subject: 'user:anne',
condition: { name: 'unexpired', context: { expiry: '2026-12-31T00:00:00Z' } },
},
]);
// Pass the runtime value(s) the condition needs as `context`:
assertEquals(
await engine.check({
object: 'document:readme',
relation: 'viewer',
subject: 'user:anne',
context: { now: '2026-06-08T00:00:00Z' }, // before expiry → allow
}),
{ ok: true, value: true },
);
// After expiry → deny (a decision, still not an error):
assertEquals(
await engine.check({
object: 'document:readme',
relation: 'viewer',
subject: 'user:anne',
context: { now: '2027-01-01T00:00:00Z' },
}),
{ ok: true, value: false },
);
// Omitting a required parameter (`now`) is an ERROR, not a silent deny:
assertEquals(
await engine.check({ object: 'document:readme', relation: 'viewer', subject: 'user:anne' }),
{ ok: false, error: 'condition_error' },
);A missing required parameter is an error, not a silent deny — the check returns
{ ok: false, error: 'condition_error' }, distinct from { ok: true, value: false }, so a
misconfigured caller is observable rather than silently denied.
The condition language is a bounded CEL subset: scalars, comparison, arithmetic, logic, and
timestamp()/duration(). List/map literals, in, regex and string methods (matches,
startsWith), field/member access (request.x), and macros are deliberately fenced — a model
using them is rejected at definition time rather than mis-evaluated. (Migrating an OpenFGA caveat
that uses those? Reshape it into the subset by passing the extracted scalar as a parameter.) The
full subset and the trust story are in Caveats & ABAC.
Because the model is authored with defineModel, queries are type-checked against it: the
object/type must be a declared type and the relation must exist on that type. A typo is a
compile error, not a runtime surprise:
// ✗ does not compile: 'viewerr' is not a relation of `document`
await engine.check({ object: 'document:readme', relation: 'viewerr', subject: 'user:anne' });When you need to know why a check allowed or denied, explain returns the decision plus the
resolution path the engine walked — the same Result shape, with a structured Explanation value.
formatExplanation renders it for a log or a debug panel:
import { deepStrictEqual as assertEquals } from 'node:assert/strict';
import { defineModel } from '@zanzibar-ts/core/model';
import { createEngine, formatExplanation } from '@zanzibar-ts/core';
const engine = createEngine(
defineModel((t) => ({
user: t.type(),
group: t.type({ member: t.assign('user', 'group#member') }),
document: t.type({ viewer: t.assign('user', 'group#member') }),
})),
);
await engine.write([
{ object: 'group:eng', relation: 'member', subject: 'user:anne' },
{ object: 'document:readme', relation: 'viewer', subject: 'group:eng#member' },
]);
const explained = await engine.explain({
object: 'document:readme',
relation: 'viewer',
subject: 'user:anne',
});
if (explained.ok) {
assertEquals(explained.value.decision, true);
console.log(formatExplanation(explained.value));
// ALLOW document:readme#viewer @ user:anne
// · group:eng#member @ user:anne → allow
// · document:readme#viewer @ user:anne → allow
}The path is the sequence of sub-checks the engine evaluated (indented by hop depth), each tagged with how it resolved — freshly computed, a memo hit, or fenced by a cycle.
- How-to recipes — protect an HTTP route · GitHub-style repo roles · time-bound access · multi-tenant isolation · write tuples on resource create · migrate an OpenFGA DSL model
- Concepts — ReBAC & tuples · coming from OpenFGA / SpiceDB · the consistency model · caveats & ABAC
- Reference — errors ·
benchmarks & bundle size · the API itself is documented as
JSDoc on the curated
core/mod.tssurface (your editor shows it on hover).
The quickstart uses the default in-memory store. On Cloudflare Workers, back the engine with the D1
store (import { D1Store } from '@zanzibar-ts/core/store/d1') for durable, multi-tenant storage with
consistency tokens. See the
Deploy to Cloudflare Workers + D1 guide, the
multi-tenant recipe, and the
consistency concept.
- Limits & gotchas — what
@zanzibar-ts/coredeliberately does not do, and the behaviours that surprise newcomers. - Error reference — every error category and how decisions vs failures are surfaced.
- TRUST.md — provenance (AI-authored, verification-first), how correctness is proven, and its honest limits.
- SECURITY.md — reporting a vulnerability. LICENSE — MIT.
- CONTRIBUTING.md — setup, the gate, and what makes a great correctness report. CHANGELOG.md — release history.
- AGENTS.md — orientation for AI agents (using the library, or working on the repo); llms.txt — a single-load doc index for LLMs.