@inixiative/permissions
v0.30.0
Published
RBAC, ABAC and ReBAC in one check over your own records, with entitlements and delegates; the app passes one schema map: its @inixiative/field-map maps, the supplied maps, bridges, polymorphism and rules
Maintainers
Readme
@inixiative/permissions
One of the inixiative building blocks. Stop rediscovering what you need to build. See all the projects.
One check, over your own data, that covers:
- RBAC: roles as table grants. Tokens and integrations act for their owner, capped at a role or, with
full, holding the owner's permissions whole. - ReBAC: relationship walks (
{ rel, action }) over your schema's relations, polymorphic owners included. - ABAC: conditions on the record and on the rows the call supplies, such as who is acting (
{ rule },actor:<Model>). - RuBAC: rules as data: every condition is a serializable
@inixiative/json-rulesrule, positive by design (validateActionRulerefuses the rest), the same AST everywhere it appears. - Delegation (entitlements): attenuated grants a holder passes on (copied, narrowed, lowered, never widened), each re-checked live at every link of its chain and at every tenant boundary it crosses.
It decides on your own records: the checks walk them through the one schema map you pass (your models' relations and foreign keys as @inixiative/field-map maps, the polymorphic models' kinds, and the rules), reached through a loadMany you provide. There is no separate authorization store and no relationship tuples to sync. Nothing in it imports a database layer: the makeHydrator helper walks your field map layer by layer and calls your loadMany, which is also where caching goes. The core is small enough to read, and it depends only on json-rules, field-map and lodash-es; the optional helpers for delegation and hydration sit outside it. MIT licensed.
Everything you configure it with is plain JSON: the schema's rules, role grants, entitlements, Permissions. So
they can live in your database, be composed like any other data, and be authored at runtime. A
tenant can manage its own rules and roles instead of you writing one per tenant, and nothing is a
config file shipped on deploy. validateActionRule checks a stored rule before you persist it.
Why this one
- No second store. A check reads the records you already have. There is no authorization service to run, no relationship tuples to dual-write, no consistency tokens, nothing to reconcile, so nothing drifts.
- Rules are data, down to one record. The schema, role grants, entitlements and per-record rules are all JSON. A tenant can write a rule on one of its own records, validated before it is saved, and it can only widen access. Policy grows per tenant instead of being one global document someone else has to edit.
- Delegation that stays honest. Every entitlement is backed by whoever granted it. Every check asks again whether that grantor still allows the action on that record, up the whole chain and across tenant boundaries. Demote anyone in the chain and what they handed on stops on the next request, with nothing to clean up.
- Granting is checked by the same rules. A role hands on only what it could do itself on every record the grant reaches; a held entitlement is handed on as a copy or a narrowing, while its granter still holds the action at that anchor. No separate admin policy to keep in step.
- Change the rules, not the data. What an action means and what implies what are read at check time, so changing them never means migrating or re-checking stored grants.
- Positive by design. No deny rules: you narrow by composing a stricter rule (
all), so there is no deny-versus-allow conflict, and a validated rule never passes because something wasn't loaded. - Small enough to read. A compact core that runs in your process, with json-rules and lodash-es as its only dependencies.
| | This library | SpiceDB, OpenFGA, Permify | Cedar / AVP | Oso Cloud | Cerbos | OPA | |---|---|---|---|---|---|---| | Decides on your own rows, no second store | Yes | No, tuple store you sync | Entities passed per request | Fact store you sync | Attributes passed per request | Data pushed to it | | Rules are JSON data | Yes | DSL (OpenFGA's model is JSON) | DSL (JSON form exists) | Polar | YAML | Rego | | A tenant writes a rule on one record | Yes, can only widen | Parameters per tuple; logic is global | Template-linked policies | Facts per record; logic is global | No | Not built in | | Delegation re-checked against its grantor at every use | Yes | No | No | No | No | Not built in | | Grant-time check from the same rules | Yes | No | No | No | n/a | No | | Lists "what can I read" as a query | 1.0, end of 2026 | Id lists | Experimental | Yes | Yes | Partial evaluation | | Runs in your process | Yes | No | Cedar yes, AVP hosted | No | Service or sidecar | Sidecar or library | | Size | A small library you can read | Service | Library and service | Service | Service or sidecar | Sidecar or library |
The full comparison, with sources for every cell and where the others are ahead: COMPARISON.md.
Core and helpers
The code is split the same way you can use it:
src/core: the algebra,check, the permix, entitlements, the grant check and validation. This is the library. It never imports a helper, and a test keeps it that way.src/helpers: optional building blocks on top of the core. Delegation (delegate,capAtRole,installPermissions,permixOf,wellFormedEntitlements) resolves a token's or integration's permissions from its owner's. Hydration (makeHydrator) loads a record with the relations a check walks.
Want your own delegation model or your own loading? Skip the helpers and call check with a permix you set up and a record you loaded.
Vocabulary
The nouns are below. The verbs, one per operation with the name that says the action, are in
docs/VERBS.md; a test fails when an export is missing from it.
| Word | Means |
|---|---|
| resource | a model of one of your field maps, named map:Model with the model spelled as its field map spells it (db:Organization, crm:Account); a record is one row of it. Every model of a map in fieldMaps that is not supplied is a resource: nothing lists them, and a relation the app does not want loaded says so on the field (/// @permissions(hydrate: false)) |
| action | a verb on a resource, defined by the schema (own, manage, operate, read, or your own) |
| schema map | the one object every entry point takes: the field maps (fieldMaps), the polymorphismRegistries, the bridges, and the rules (permissions) |
| schema | the rules of the schema map (permissions): per resource, the rule (ActionRule) that decides each action: a grant, a relation walk, a condition, or a combination |
| grant | an entry a role gives: actions on a resource or one record ({ resource, id?, actions }); the grants a permix holds are its table |
| entitlement | an entry given beyond a role: actions on a resource, from an anchor, with an optional where, backed by whoever granted it |
| anchor | the record an entitlement acts from, reached from the entitled record along path |
| permissions | what the actor acts from, as data: groups of entries, a group with an owner being entitlements backed by that owner (Permissions) |
| owner | the record a delegate acts for (a user, a membership, an organization, another delegate), whose permissions back its entitlements |
| delegate | a token or integration that acts from its owner's permissions: full, capped at a ceiling, entitlements, or a mix |
| full | the owner's permissions, whole and live |
| ceiling | the action a delegate's role maps to; the owner's grants are kept at it (capAtRole) |
| supplied bridge | a json-rules bridge with no join (no on): its far model's row is given to each check in its bridgeData, and rules on the models it starts from read it |
| supplied model | the far end of a supplied bridge (actor:User), read by rules as <map>:<Model>.<column> |
| supplied map | a field map a supplied bridge ends in (an app's actor map: who is acting), or one joined by key from a supplied map (sec, joined from actor:User) |
| permix | the installed form of a holder's permissions that check reads |
| pseudo record | the would-be row a create or a grant is checked on; the rows built for it below the anchor, with keys and parents but no ids, are stand-ins |
Permission algebra (ActionRule)
type ActionRule =
| string // rbac: delegate to another action on the same resource
| { rel: string; action: string } // rebac: walk a relation, then check `action` on the target
| { rel: string; arrayOperator: 'any'; condition: ActionRule } // rebac across a list: some item passes
| { rule: Condition } // abac: a json-rules predicate over the record and its supplied rows (`actor:<Model>`)
| { any: ActionRule[] } // OR
| { all: ActionRule[] } // AND
| boolean // terminal: `true` allows, `false` denies
| null; // terminal deny, as is an action the schema does not nameA SchemaMap is { fieldMaps, polymorphismRegistries?, bridges?, permissions }, one object, so the
data shape and the rules cannot be passed mismatched:
fieldMaps: every field map, by map name ({ db: prismaMap, actor: actorMap }): the maps of the records the app loads and walks, and the supplied maps alike.polymorphismRegistries: by map name, each value one map's registry by model name, the axes of each false-polymorphic model (PolymorphismRegistry; see Polymorphic rules).bridges: one list of json-rules bridges between models of different maps. A joined bridge is crossed by arel(see Bridges); a supplied bridge, one with no join, says whose row each check is given (see Supplied maps).permissions: the schema, mapping a resource to{ actions: { name → ActionRule } }.
Nothing else marks a map as supplied: a map is supplied when a supplied bridge ends in it, or a
joined bridge joins it to a supplied map. A map that starts a supplied bridge or is named in
permissions holds records, and is never taken as supplied. Every model of a map that is not
supplied is a resource.
A resource is named map:Model everywhere: in permissions keys, subject.resource, grants,
anchors, entitlements, bridgeData keys and bridge endpoints. It is json-rules' endpoint key, the model
spelled as its field map spells it (db:User, actor:User), so there is no table renaming a
resource to its model. A name with no map: throws. A relation leads to the model of its own map:
db:User and actor:User are two models.
Writing a schema
Action names are yours: the engine imposes no vocabulary. The own/manage/read chain below
is illustrative; use whatever your roles grant. The map holds the field maps, then the rules:
import { Operator } from '@inixiative/json-rules';
import type { SchemaMap } from '@inixiative/permissions';
// written by `bunx field-map generate` after `prisma generate`
import { prismaMap } from './generated/prismaMap.gen';
const schemaMap: SchemaMap = {
fieldMaps: { db: prismaMap },
permissions: {
'db:Organization': {
actions: {
own: null, // terminal: granted only via permix (roles) or row rules
manage: 'own', // delegation chain: own ⊇ manage ⊇ read
read: 'manage',
},
},
'db:Membership': {
actions: {
read: { any: [{ rel: 'user', action: 'read' }, { rel: 'organization', action: 'read' }] },
leave: { rel: 'user', action: 'operate' }, // your own row: a walk to your own user entry
manage: { rel: 'organization', action: 'manage' },
},
},
'db:Document': {
actions: {
read: {
any: [
{ rule: { field: 'isPublic', operator: Operator.equals, value: true } }, // abac guard
{ rel: 'organization', action: 'read' }, // rebac: walk the relation
],
},
manage: { rel: 'organization', action: 'manage' },
},
},
},
};rel accepts dot-paths for multi-hop walks: { rel: 'space.organization', action: 'own' } chains
through record.space.organization, resolving each hop's model from the schema map.
Rules built from the data shape (the kind rules of a polymorphic model) need the map before it has rules, so such a map is built in two steps; see Polymorphic rules.
Records may also carry a permissionRules JSON field (action → ActionRule): a per-record rule (a
condition, a relation walk or both), so one record can take a rule its model's schema doesn't. check merges a row
rule additively (OR) with the schema rule, so per-record overrides can widen but never revoke.
check validates a row rule before merging it: one that isn't positive, that delegates back to
its own action (a cycle), or that reads outside the relation lens,
makes the check throw: a stored rule that is refused is a fault to fix, not a rule to skip. Validate
a stored row rule with validateActionRule(rule, { schemaMap, resource, action, rowRules }) before
persisting it, so the author hears about it then: that one call reports everything the check
refuses.
More rules for a record: additionalRules
A row rule opens one record. An app may have other places a rule comes from: a tenant that opens every record it owns, say. The library does not know what a tenant is, so the app hands it the rules:
const check = makeRebacCheck(schemaMap, {
additionalRules: (resource, record) => rulesTheOwnersOf(record).map((rules) => rules[resource]),
});Each entry is a rule set shaped like permissionRules (action → ActionRule). The function is
asked for every record the walk reaches. check ORs each rule with the schema rule and the record's
own rule, so it only widens, and it cannot add an action the schema lacks. Each rule is validated
before it is merged, exactly as a row rule is. makeRebacPaths and makeCanGrantEntitlement
take the same option. Validate each rule with validateActionRule before the app saves it, giving
the other rule sets that reach the record so a cycle through them is caught:
validateActionRule(rule, {
schemaMap,
resource: 'db:Document',
action: 'read',
rowRules: document.permissionRules,
additionalRules: [tenantRules], // each a rule set, `action → ActionRule`
});
// { ok, errors }: the shape and positivity, a delegation back to `read`, and every read outside the lensCrossing a list: some item passes
A { rel, action } walk is to-one and never crosses a list. A rule that turns on a row in a list
(you may chat when you are one of the conversation's participants) uses its own arm:
'db:Conversation': {
actions: {
isParticipant: {
rel: 'participants', // one list relation of this resource, no dots
arrayOperator: 'any', // the only operator
condition: { // an ActionRule, judged on each item as the item's own resource
all: [
{ rule: { field: 'leftAt', operator: 'equals', value: null } },
{ any: [
{ rel: 'member.fanUser', action: 'operate' },
{ rel: 'member.staffUser', action: 'operate' },
] },
],
},
},
chat: { all: ['create', 'isParticipant'] },
},
},
'db:Message': { actions: { read: { rel: 'conversation', action: 'isParticipant' } } },The arm passes when condition passes on some item. Inside condition a string is an action on
the item's resource, rel walks from the item, and { rule } reads the item, so the item's model
is a resource in the map (it needs no actions of its own). A record below the list reaches it by
delegating, as db:Message.read does; rel in the arm is the list field alone.
When to reach for it. Whenever access to a record turns on one of its child rows, and the record holds no key to walk up:
Membership: you are one of the conversation's participants (above).
A junction table: a resource is attached to many projects, and whoever can read one of those projects reads the resource. The role or entitlement stays on the project; the resource's rule goes down to the junction rows and up from each to its project.
model IntegrationResource { /// @permissions(down: [project.organization]) projects ProjectIntegrationResource[] }'db:IntegrationResource': { actions: { read: { rel: 'projects', arrayOperator: 'any', condition: { rel: 'project', action: 'read' } }, }, },db:Project.readwalks on to the organization here, so the declared path isproject.organization.
When the record holds the key itself (a message's conversationId), use a plain rel; this arm
is only for the direction a to-one walk cannot go.
The shape is json-rules' array condition, { field, arrayOperator, condition }, with field
renamed rel because the list is a relation walked through the table. The third key is
condition and not rule: in this language rule always holds a json-rules condition, and one
key with two meanings is what validateActionRule would have to guess at.
The list is declared in the Prisma schema, on the list field, and the map carries it:
model Conversation {
/// @permissions(down: [member.fanUser.user, member.staffUser.user])
participants ConversationParticipant[]
}down is a flat list of dotted paths from an item. Each names a leaf by its full path, and
everything above a leaf loads with it; down: [] loads the items and nothing under them. Each
segment is a to-one relation that owns its foreign key and leads to a resource in the map. The
item model has exactly one foreign key back to the parent (an implicit many-to-many has none and
is refused), and a path may not start back up that key. A list that is not declared is never
crossed.
- What loads, and what doesn't. A declared list is part of its parent's row:
loadManyis asked for the parents with theirdown, and returns each row holding every item, each item holding the row on every declared path (in a Prisma app, onefindManywith the includeprismaIncludeOfDowngives). Wherever that row is reached, as the record you pass or as a parent of it, it carries the same list. The hydrator reads nothing more under an item and keeps of each item only its columns and the declared paths: none of its other parents, no second list, nothing above the rows on a declared path. That is what "one jump down" means, and it is why loading never backtracks into the record it came from. - One jump in the engine too. An item's view holds no list, so a list arm met under an item finds nothing whatever the record holds, and a bridge hop under an item denies.
- A column an item does not carry fails. A rule over a column the item came back without (a
select, a projection) never passes: a rule names the value that is there (status equals 'active'), withexistsbeside any comparison with a path, and a null check needs the item's key to exist beside it (all: [id exists, leftAt equals null]). - Why only
any. Every other array operator (all,none,atMost,exactly,empty,notEmpty,atLeast) holds on a list with no rows or counts rows, so it would pass on a record whose list was never loaded, or pass for nobody in particular. They are refused by name (codearrayOperator). Aconditionthat never walks into the table (true, or a bare{ rule }on the item) is "the list is not empty" under another spelling; write conditions that reach a person. - A list never passes on a stand-in. The pseudo record a grant is checked on has no lists:
pseudoRecordsBelowAnchorbuilds keys and parents, never items, and awherecannot set one (only scalar values are copied, see Granting one). So nobody grants "participant of every conversation in the brand"; a grant that rests on the list is anchored where a real list is (the conversation itself, or a record below it). - Entitlements under an item work as anywhere: one held on a membership row makes its holder
count where that member is a participant, because a delegate of the participant is the
participant wherever a rule walks to them. Whoever granted it is judged on the same item, so it
stops when the member leaves. In the grant check's first pass nothing met under an item counts
(
grantsBelowis about rows above the granted record, and an item is not one), so the outcome never turns on whether a loader hands the same object to an item and to a parent. pathsreports one admission per admitting item, merged when equal, and the list arm is never pure delegation:reachableFromandcapAtRoledo not pass through it.
Declare what the rule walks. validateSchemaMap and the run time agree on what a declaration
must carry: every relation a rule walks or reads under an item, followed through the actions the
walk lands on, is inside a declared path. A check refuses a schema that breaks this on first use,
the way it refuses a negated rule, so it cannot go unnoticed in an app that never runs
validateSchemaMap. In the example operate on a membership is { rel: 'user', action: 'operate' },
so the leaves are member.fanUser.user and member.staffUser.user: three segments.
Why the stricter reading. With only member.fanUser declared, the walk still passes for a person
whose table holds an id-keyed grant of operate on their own membership row, because the table
answers before the rule is walked. It denies for a person whose operate comes through the rule
(db:User.own), and for a grantor judged the same way, although the same action on the same row
passes when the row is hydrated from above. One action answering two ways by how its row was
reached is the under-hydration the hydrator exists to remove, and the library cannot see tables
from a schema. So the declaration follows the rule. To load less, say less in the rule: an action
the table alone answers (self: null, granted by id on the membership row) needs only
member.fanUser, and validates with two segments.
Rules outside the schema are judged against the declaration too: see where the lens runs.
The check engine
import { engineGlobals } from '@inixiative/json-rules';
import { makeRebacCheck, type SchemaMap } from '@inixiative/permissions';
// the one schemaMap the walk reads: the models' relations and foreign keys (an @inixiative/field-map
// FieldMap, as `field-map generate` writes it), the polymorphic models' kinds, and the rules
const schemaMap: SchemaMap = { fieldMaps: { db: prismaMap }, polymorphismRegistries: { db: polymorphismRegistry }, permissions };
// the field a record's grants are keyed by: `id` unless set (`uuid`, `_id`, `ID`…), once, at boot
engineGlobals.set('permissions.idField', 'uuid');
const check = makeRebacCheck(schemaMap);
check(permix, { resource: 'db:Membership', record }, 'manage');
// string → permix grant or schema delegation; { rel } walks `record.organization` (or a bridge,
// see below); { rule } evals json-rules over the record and its supplied rows (actor:<Model>); any/all compose. A data loop denies; a rule naming itself throws.The first check judges the map whole and freezes permissions and bridges, so the answer it
gave holds for every later check; the field maps are the app's and are not frozen.
There is no self arm. Identity lives in the table. The actor's table holds grants on its own
user row like any other, so acting on your own row is { rel: 'user', action }: the walk reaches the hydrated
record.user and checks action there, through the delegation chain and custom user actions alike.
A person, or a full delegate of one, holds own on its user; a narrowed delegate (a token holding only read on its
user) fails a write arm on its own row; a row without its user loaded is denied, never guessed
from the foreign key. validateActionRule rejects self.
The check takes a subject, { resource, record, bridgeData? }, rather than a bare record; bridgeData is the
supplemental rows that back cross-source bridge hops and the supplied rows (below). A
subject.resource with no map: throws. makeRebacCheck is generic over the resource key
(default string). Pass your resource union and the map's permissions keys and
subject.resource both enforce it, so your own types need no casts:
type Resource = 'db:Organization' | 'db:Membership' | 'db:Document';
const check = makeRebacCheck<Resource>(schemaMap); // map: SchemaMap<Resource>
// now `schemaMap.permissions` is keyed by Resource, and `subject.resource: Resource`: a typo is a compile error.Cycle detection knows a row by its key (identityKeyOfRow: the engine id field, else the model's
id columns, with its resource), else by the object, so an id-less record never produces a false
"cycle", and a true self/mutual delegation
(read: 'read') throws instead of overflowing the stack. A loop made by data (a relation
walked back to a row already on the walk, as a linked hydration cycle can be) denies instead. The key includes the table being
walked, so an entitlement's owner revisiting the same node is not a cycle. A loop built from grant
data (two holders owning each other's entitlements) is not a schema bug and does not throw: the
back edge contributes nothing, and only a chain that reaches a real grant allows.
Every path: makeRebacPaths
check answers whether anything admits and stops at the first thing that does. To know which
entitlements admitted, for routing a use, charging it or explaining it, run the same walk without
stopping:
const paths = makeRebacPaths(schemaMap, { limit: 20 });
paths(permix, { resource: 'db:Space', record: space }, 'read');
// [[['d-from-b', 'b']], [['d-from-c', 'c']]]Each entry of the result is one way the check is admitted: the chains of entitlement refs it
stands on, holder first. A grant held directly is [[]] and nothing admitting is []. An all
that needs two delegated branches is one admission with two chains. Give an entitlement a ref
(the app's id for its row) to see it in a chain; one without a ref is null in its chain, so a
delegated link never reads as a grant held directly. Two rows alike but for their ref are both
reported.
- One way in is reported once, however many walks reach it (an entitlement holding
readandownwherereaddelegates toownis one admission). - The order is deterministic but not meaningful. It is the walk's, not the setup order; sort by what your routing needs (Kingdom sorts by the row's age).
pathsis non-empty exactly whencheckis true. They share one walk.pathskeeps walking past an admission, so a loop it reaches thatchecknever did adds nothing instead of throwing; a schema loop still throws incheck.- The limit bounds the result, not the walk. More than
limitadmissions (default 20) throwsPathLimitError; stacked diamonds double the count at each layer. A walk that finds few admissions costs what a denyingcheckcosts today.
Supplied maps: data the call gives (who is acting, for one)
The library has no notion of an actor. An app says whose rows each check is given by declaring
supplied bridges in bridges: json-rules bridges with no join (no on). The far model of a
supplied bridge is a supplied model; each check is given its row in bridgeData, keyed
<map>:<Model> as the joined bridges' far rows are. A { rule } reads it as
<map>:<Model>.<column>, and on along its relations and to-one bridges
(actor:User.org.plan, actor:User.sec:Posture.managed). An app with no supplied bridges reads
none; an app with several reads them all alike.
The first endpoint says which rules read the row. { fieldMap: 'db' } (json-rules 4.7) names only
a map: every model of db. { fieldMap: 'db', model: 'Document' } names one model. The second
endpoint is the supplied model:
// the app's own actor map: which kind is acting, and each kind's own columns
const actor: FieldMap = {
models: {
Acting: { fields: { model: { kind: 'enum', type: 'ActingKind' } } },
User: { fields: { id: { kind: 'scalar', type: 'String' } } },
Token: { fields: { id: { kind: 'scalar', type: 'String' } } },
},
enums: { ActingKind: ['User', 'Token', 'Internal'] },
};
// a security tool's devices, joined to the actor by its id
const sec: FieldMap = { models: { Device: { fields: { userId: str, risk: str } } } };
const schemaMap: SchemaMap = {
fieldMaps: { db: prismaMap, actor, sec },
polymorphismRegistries: { db: polymorphismRegistry },
bridges: [
// supplied: every model of `db` reads the row of `actor:Acting`, `actor:User` and `actor:Token`
...['Acting', 'User', 'Token'].map((model) => ({
endpoints: [{ fieldMap: 'db' }, { fieldMap: 'actor', model }],
cardinality: 'oneToOne',
})),
// joined, from a supplied model: `sec` is a supplied map, its rows found by key
{
endpoints: [{ fieldMap: 'actor', model: 'User', on: 'id' }, { fieldMap: 'sec', model: 'Device', on: 'userId' }],
cardinality: 'oneToMany',
},
],
permissions,
};
check(permix, {
resource: 'db:Document',
record: document,
bridgeData: { 'actor:Acting': [{ model: 'User' }], 'actor:User': [user], 'sec:Device': devices },
}, 'read');A supplied map is a field map a supplied bridge ends in (actor), or one joined by key from a
supplied map (sec, joined from actor:User). A map that starts a supplied bridge or is named in
permissions holds records, and is never taken as supplied. validateSchemaMap reports each of
these, and a check throws the first:
- A rule reads a supplied model only if a supplied bridge starts from its model or its map. A
rule on
crm:Accountthat readsactor:User.idis a read outside the lens until a second supplied bridge,[{ fieldMap: 'crm' }, { fieldMap: 'actor', model: 'User' }], is declared. A bridge fromdb:Documentalone gives the row todb:Document, not todb:Organization. - A supplied bridge does not end in a map of records: "a bridge between
every model of dbandactor:Userhas no join, so its far end is supplied, butactorholds records (it has rules, or starts a supplied bridge): no chain leads from a supplied row into the records". - A supplied map is not joined to a map of records: "a bridge between
actor:Useranddb:Dochas one end supplied: no chain leads from a supplied row into the records". - A supplied bridge ends in a declared field map: "… ends in the map
nope, which is not infieldMaps".
What the check does with a supplied row:
- The call gives one row of each supplied model; the rest are found by key. The far end of a
joined bridge from a supplied model (
sec:Device) is not given one row:bridgeDataholds its rows, and the bridge finds them by key. - It is read at the row the rule is on. A
{ rule }reads it from the record it is checked on, never under a relation (org.actor:User.idis refused), and awherenever reads it. - The engine fills it; a record never brings its own. Before each
{ rule }the check runs json-rules'recordWithBridgeData, with the joined rows indexed once per check: any key a row carries naming a supplied model is dropped, and the rows frombridgeDataare put on. A row not given is absent, and a rule reading it fails. - A supplied bridge is never crossed by a
{ rel, action }walk ({ rel: 'actor:User', action }is refused). The library makes no bridge of its own from a resource to a supplied model: only the supplied bridges declared give a rule a row. - A list on a supplied row is crossed with the list arm:
{ rel: 'actor:User.sec:Device', arrayOperator: 'any', condition }, its own list relations too (actor:User.groups). An item is a supplied row with no actions, so its condition holds{ rule }s inanyandall, read in the item's own lens. - A match needs
existson its field (R-2026-11-21-07), since two missing values match:ruleFieldEqualsPath('ownerId', 'actor:User.id')isall: [ownerId exists, ownerId equals actor:User.id]. A comparison with a literal needs none. - Typed. A model a supplied map lacks, a read off the end of its relations and bridges, a model reached twice on one chain and an enum value outside its enum are refused.
- Stored rules too. A row's
permissionRulesor anadditionalRulesentry that is not positive, loops or reads outside the lens throws, as the schema's would.
A null check: the row is there, and the column is empty
A null check also holds where the value is missing: a record that came back without the column, a
relation that is not loaded, a supplied row the call did not give. So equals null (and in with
null) is accepted only beside an exists on the key of the row it reads, in the same { rule }
(Aron, 2026-11-22: "row exists and key is null is another valid check"); a bare one is refused.
The key is the engine's id field (permissions.idField).
// a token with no role
{ rule: { all: [{ field: 'id', operator: 'exists' }, { field: 'role', operator: 'equals', value: null }] } }
// through a relation: the organization is loaded, and not deleted
{ rule: { all: [{ field: 'org.id', operator: 'exists' }, { field: 'org.deletedAt', operator: 'equals', value: null }] } }
// on a supplied row: a token is acting, and it has no parent
{ rule: { all: [{ field: 'actor:Token.id', operator: 'exists' }, { field: 'actor:Token.parentId', operator: 'equals', value: null }] } }The same gate judges the schema's rules, a row's permissionRules, additionalRules and an
entitlement's where. Another column of the row does not stand in for its key: a grant's stand-in
record carries foreign keys and never its own key (pseudoRecordsOfEntitlement leaves it off, whatever the
where requires and even where a foreign key is the key), so a rule resting on an empty column cannot
be granted over many records. Give the column an explicit value when that grant is needed.
What the key proves is that the row is there, not that it came back whole. A check reads a
hydrated record, which carries every column and every to-one relation its lens shows; a caller that
hands in a row without a column, or names a to-one relation where its foreign key is meant
(organization equals null on a record whose organization was not loaded), still reads that as
null. Check the foreign key (organizationId), and never a key inside a JSON column, which has no
row of its own.
Polymorphic rules: the fan-out
The standard shape of a polymorphic check (R-2026-11-19-15): fan out over the kinds, each branch
checking its own kind first, every rule positive, every match checking its field exists. A kind with no row
(default, Internal) is named by its kind alone. makeKindRules({ fieldMaps, polymorphismRegistries, bridges })
builds them, reading the kinds from those three tables: a resource's polymorphic axis
(polymorphismRegistries, by map name then model), or a supplied model's enum field
('actor:Acting', 'model'), a supplied model being the far end of a supplied bridge in bridges.
A kind the tables do not have throws when the rule is built.
The builders read the data shape, so they take the tables before there are rules (a whole schema
map is fine to pass); the rules they return then go into permissions:
import { makeKindRules, ruleFieldEqualsPath, type SchemaMap } from '@inixiative/permissions';
const shape = {
fieldMaps: { db: prismaMap, actor },
polymorphismRegistries: { db: polymorphismRegistry }, // your false-polymorphism registry, by model name
bridges: actorBridges, // the supplied bridges to `actor:Acting`, `actor:User`, `actor:Token`
} satisfies Omit<SchemaMap, 'permissions'>;
const kind = makeKindRules(shape);
// one branch per kind of a side, each checking its own kind first; a kind left out denies
kind.ruleForEachKind('db:Token', 'ownerModel', {
Organization: { rel: 'organization', action: 'manage' },
User: ruleFieldEqualsPath('userId', 'actor:User.id'),
default: true, // a kind with no row: its kind check is the whole branch
});
// the same action through each kind's own relation (the registry's foreign key)
kind.ruleActionThroughEachKind('db:Token', 'ownerModel', 'manage');
// kind membership, on a resource's side and on a supplied model
kind.ruleKindIsOneOf('db:Token', 'ownerModel', ['Organization', 'Space']);
kind.ruleKindIsOneOf('actor:Acting', 'model', ['Token', 'User']);
// a fan-out over who is acting
kind.ruleForEachKind('actor:Acting', 'model', { Internal: true, User: ruleFieldEqualsPath('ownerId', 'actor:User.id') });
const schemaMap: SchemaMap = {
...shape,
permissions: {
'db:Token': { actions: { manage: kind.ruleActionThroughEachKind('db:Token', 'ownerModel', 'manage') } },
},
};A resource's side takes an optional path prefix ('integration.') for a side on a related row.
They return ordinary ActionRules: validation, the walk and the builder see plain rules. The walk
infers no kind check on a { rel } hop; under the full owner chain a Space-owned row also carries
its organization, and only an explicit branch says which kinds may walk it.
Bridges (cross-source rel walks)
A rel can cross a bridge: a cross-source edge between two field maps (see
@inixiative/json-rules). The map holds one list of
bridges, and each is classified by its join and its ends:
- No join: a supplied bridge. Its far model's row is given to each check in
bridgeDataand read by a{ rule }; it is never crossed by arel(see Supplied maps). - Joined, neither end supplied: crossed by a
relfrom a record. Each endpoint names its key withon. - Joined, both ends supplied: read by a
{ rule }from a supplied row, its far rows found by key. - Joined, one end supplied: refused on first use and by
validateSchemaMap("has one end supplied"), so no chain leads from a supplied row into the records.
Both ends of a crossed bridge are resources, named map:Model:
const schemaMap: SchemaMap = {
fieldMaps: { db: prismaMap },
bridges: [{
endpoints: [
{ fieldMap: 'crm', model: 'Account', on: 'id' },
{ fieldMap: 'db', model: 'User', on: 'accountId' },
],
cardinality: 'oneToMany',
}],
permissions: {
'db:User': { actions: { read: { rel: 'crm:Account', action: 'own' } } },
'crm:Account': { actions: { own: null } },
},
};Bridges don't hydrate (they aren't FK relations). The join key is a scalar on the record
(User.accountId); pass the far rows as subject.bridgeData (keyed map:Model, the indexBridges
shape) and the engine builds the lookup itself. A resource whose map is not in fieldMaps is allowed in
permissions only as the far end of such a bridge, and nothing its rules read is checked. A far
row absent from subject.bridgeData denies the walk, whatever the far action is, an rbac grant on the far id included:
check(permix, {
resource: 'db:User',
record: { id: 'u1', accountId: 'acc1' },
bridgeData: { 'crm:Account': [{ id: 'acc1', tier: 'gold' }] },
}, 'read');The permix wrapper
import { createPermissions } from '@inixiative/permissions';
const permix = createPermissions<'read' | 'manage' | 'own'>();
await permix.setup([{ resource: 'db:Organization', id: 'o1', actions: { own: true } }]);
permix.check('db:Organization', 'own', 'o1'); // trueHolds the holder's role-derived grants (keyed by resource / resource:id), its entitlements and a
superadmin bypass; who is acting comes in the check's bridgeData. App code populates it from roles and entitlements (hydration
stays app-side); the check engine reads it back through the PermixLike slice.
Entitlements
A grant says what a role holds. An entitlement says what a holder (a token, a membership, an
integration) was given beyond its role: an action, on a resource, from an anchor, with an
optional where. It is installed with the permissions of whoever granted it, bound once per setup
call because the grantor is on the holder's row, never in the entitlement:
const o1 = createPermissions();
await o1.setup({ resource: 'db:Organization', id: 'o1', actions: { own: true } });
await permix.setup(
[
// manage space s1 (and what is under it)
{ resource: 'db:Space', anchor: { resource: 'db:Space', id: 's1' }, actions: { manage: true } },
// manage the slack integrations of s1
{
resource: 'db:Integration',
anchor: { resource: 'db:Space', id: 's1', path: 'space' },
where: { field: 'provider', operator: Operator.equals, value: 'slack' },
actions: { manage: true },
},
],
{ owner: o1 },
);Entitlements never enter the table. The engine consults them at a node only after the table and
the schema rule both miss, with the record in hand. An entitlement answers an action when it holds
that action or one that implies it by pure delegation (reachableFrom): manage answers read
where read delegates up to manage. One applies when all three hold:
- Its
anchoris reached along itspath.anchor.pathnames the relations from the record up to the anchor ('space.organization'); the hydrated record at the end of the path is the anchor (its resource and id). Only the anchor's id is fixed: a record that moves inside the anchor stays reached, one that moves out stops. The path picks the side when a record hangs from two parents of one model (targetOrganization, notsourceOrganization), so a relation the path does not name never counts, and a path through a list relation reaches nothing. A record anchored at itself has no path. The action is checked on the record, never asked of the anchor. A polymorphic step admits every kind that carries its keys. A polymorphic record carries the ids of everything above it, soorganizationon an integration admits each kind whose registry columns (schemaMap.polymorphismRegistries) holdorganizationId: the organization's own, a space's, a member's, a space member's. The step passes when the record is one of those kinds; thewherenarrows them (ownerModel equals Organizationis the organization's own;ownerModel in [...]keeps the kinds it names). A side is a different axis, sotargetOrganizationreaches what an organization received and never what it sent. whereholds. Thewhereis plain json-rules over the record at that node,fieldandpathboth starting there and free to climb hydrated parents (space.organizationId). Whatever referred to the holder (its own id, its user) is written in as a literal when the grant is made. Awhereis positive (json-rulesvalidateRule(where, { positive: true })): no negation,isEmpty,notExists,if/then/else, array or aggregate rule, so it never passes on what is not loaded; "no value" isequals nullbeside anexistson the row's key (below).where: falseis awherethat fails, not its absence;where: nullis refused at setup.- The grantor is still in control. The owner's permissions, walked from this very record through
the normal schema, allow the action being asked, not the one held: a
manageentitlement whose grantor is down toreadstill answersread, and every owner up a chain is asked the same action. That is the only tenancy check and it is live: a space moved to another org stops reaching the grantor on the next request, no fetch. The record's schema guards run inside that walk, and a{ rule }met there still sees the request's actor asactor:<Model>. A holder can never exceed its owner on the same record and action; owners nest (token ← membership ← org) because an owner's permissions carry its own entitlements.
setup refuses an entitlement without an owner, a where without a anchor, an anchor on
another resource without a path or on its own resource with one, an id beside a
anchor (a single row is where: { field: 'id', … }), a non-boolean action, where: null, a
malformed or non-positive rule, or a grantsBelow that is not true or sits beside a where, before touching any state; entitlementProblem(entry) names the
problem (or returns null), so stored entries can be filtered before they are installed. An entitlement the holder already holds from the same owner (identical, or the same with fewer actions) is a no-op; two alike but for their ref or their grantsBelow are two rows; coversEntitlement(held, entry) and withoutRedundantEntitlements(entries) apply the same rule to a list before it is stored. replace: true clears entitlements with the table. getJSON
carries grants only. Tenancy is as live as the owner's grants are id-keyed: an owner's permissions with a
resource-wide grant, or the superadmin flag, short-circuits before any walk.
Granting one
A grant is an action, and grant time mirrors read time through the same check. Build the grant check with the same map as the rebac check, build the entry's pseudo records from the hydrated anchor, and ask of each:
const canGrantEntitlement = makeCanGrantEntitlement(schemaMap);
const entry = {
resource: 'db:Integration',
anchor: { resource: 'db:Space', id: 's1', path: 'space' },
where: { field: 'provider', operator: 'equals', value: 'slack' },
actions: { manage: true },
};
const pseudoRecords = pseudoRecordsOfEntitlement(schemaMap, entry, await hydrate('db:Space', space)); // null: malformed
pseudoRecords?.every((record) => canGrantEntitlement(writer, entry, record)); // every Slack integration of s1?Passing on a held entitlement narrowed. A delegated grant keeps every condition of the held
where and may add conditions beside them, never rewriting one: a narrower list is
all[ id in [A], id in [A, B] ], the held in kept whole. delegatedWhere(held, ...added) builds
it: all of the added conditions, then the held where's conjuncts, flat (a held all is spread,
never nested; one conjunct comes back alone). The grant check reads a narrowing as "every held
conjunct is among the entry's", in any order; build it with delegatedWhere:
delegatedWhere(slack, general); // { all: [general, slack] }
delegatedWhere({ all: [slack, team] }, general); // { all: [general, slack, team] }No negative rules. A check throws when any rule of the schema, or a rule passed to it, is one
validateActionRule refuses, negated ones (notEquals, notIn, …) included; the schema is judged
whole on first use, so it throws for every caller, a superadmin too. The same first use refuses
a schema that reads outside the relation lens, and
freezes it. A record's own permissionRules that are not positive are ignored, as before. A negated rule passes on a field the record lacks, so in
the grant walk, where every field the pseudo record lacks is unknown, it granted what the writer
cannot do. Run validateSchemaMap and write rules positively (role in ['member', 'guest'], not
role notIn ['owner', 'admin']).
pseudoRecordsOfEntitlement first refuses a malformed entry (null), by the rules setup applies
at install, so validity and the grant are one check before saving. It then builds the pseudo
records of entry.resource from the anchor down the path
(pseudoRecordsBelowAnchor(schemaMap, resource, path, anchorResource, anchor, where?), also exported for
a record you are about to create, narrowed by its where the same way). The writer must pass on
every pseudo record it returns.
What a pseudo record holds:
- Keys and parents from the path. At each step: the foreign keys whose values the parent knows, and the parent attached under the relation. Ids below the anchor are unknown.
- One record per polymorphic kind. A polymorphic step gives one record for each kind whose foreign keys the step uses, each with its owner row built from the rows above the anchor, along every relation that leads there.
- Only the kinds the
whereallows. Thewhere's root leaves (thewhereitself, or each leaf of its topall; nothing nested) on the first step's kind field with a literalvalueare checked on each record's kind, and a kind a leaf fails is dropped (ownerModel in [Organization, Space]keeps those two). No other leaf drops a record: dropping one loosens the grant, so only the kind, which every real record of that kind shares, may do it. - The values the
whererequires on the record's own columns. Each root leaf that is an exactequals(equals nullgivesnull) is copied onto the record: scalar values only, on fields that are not relations or lists, so awherenever puts a row or a list on a pseudo record. A field two root leaves require with different values is left unknown, since no record holds both and the order of conjuncts must not decide a grant. Anequalson a Json column or a scalar list is refused at grant time; write such a condition on a scalar field. - Never its own key. A pseudo record is not a row that is there, so a rule that asks its key to exist (a null check, above) fails on it.
- The path wins. A foreign key the path knows overrides the same key required by the
where, so awherecannot move the record out from under its anchor. A foreign key the path leaves unknown keeps the value thewhererequires, and the rules still walk the relation.
Below the record itself, a stand-in takes a value from the where only on a pseudo field (next).
The result is null when no kind is left, the anchor row is not the entry's, or the path does not
end at the anchor's model through to-one relations. A self anchor is the anchor row itself.
Pseudo fields: fields a where may set on a stand-in. The stand-ins
pseudoRecordsBelowAnchor builds between the record and its anchor carry keys and parents and
nothing else, so a rule that reads a type field on one of them (integrationResource.kind equals
'channel') finds it unknown and the grant is refused, however exactly the where requires it.
Annotate the field in the Prisma schema:
model IntegrationResource {
/// @permissions(pseudoField: true)
kind String
/// @permissions(pseudoField: true)
enabled Boolean
}When an entry's where has a root leaf <the entry's path down to that stand-in>.<field> equals
<literal>, the stand-in is built with that value. "Every channel of integration i1" is then one
row, anchored at the integration by integrationResource.integration, where
integrationResource.kind equals 'channel' and integrationResource.enabled equals true, and the
surface model needs no copied resourceKind column.
- What it means. "A grant may give this field's value for records it has not seen." It is
sound because the leaf stays on the stored row: it is required of every copy, and at read it is
judged on the real record the anchor path walks. A pseudo field adds no authority; it lets the
grant check believe, for the stand-in, what the
wherewill enforce. - Its limits. Root conjuncts only (a leaf inside
anyis not true of every record it lets through); a literalequalsonly, with a scalar value; only on the entry's own path, at any depth; only stand-ins strictly below the anchor, each built fresh, so the anchor and the rows above it are real and never written. The path wins: keys, the parent and a polymorphic kind are set after the pseudo fields. Two leaves requiring different values of one field fill nothing, in either order. Under a list item nothing is filled. - Where it is refused, when the map is first used: an id (the map's
isId, or the field named bypermissions.idField; a hand-built map that carries neither is not caught), a relation key, a discriminator, a list, a relation, and any scalar but String, Int and Boolean (so dates, Json, Float, Decimal, BigInt, Bytes). Enums are allowed. The value istrueor the key is absent. The value's type is not checked against the field: a mistyped value gives a refused or a dead row.
@permissions(...) is read strictly. Three keys: hydrate: false on a relation, down:
[...] on a list relation, pseudoField: true on a scalar. On first use of a map every annotation
on a resource's model is read, and an unknown key, an empty annotation, a malformed value, or
down beside hydrate: false throws. field-map keeps a malformed value without complaint (down:
a.b arrives as a string, pseudoField: yes as 'yes'), so a typo would otherwise be a silently
missing list or pseudo field. Annotations on models that are not resources are not read.
canGrantEntitlement judges each pseudo record in two passes:
- The writer's table, and what it holds outright above the granted record. Its table (its
role), given no
bridgeData, takes each action on the pseudo record. An entitlement also counts here, as a role on its record would, when all of these hold: it is markedgrantsBelow: true; it has nowhere; and the walk meets it on a real row above the granted record (below). (A delegate's permissions capped at a ceiling, fromdelegate, is permissions entries too.) A field the pseudo record does not carry fails every positive leaf, so a writer whose authority reads a field thewhereleaves open is refused. A rule that needs an actor (actor:User.id exists, an id compared toactor:User.id) never passes: who the writer is is not authority that can be handed on. A null check never passes either: a stand-in carries the keys on its path, never its ownid, so a writer whose authority rests on an empty column grants it on the one record it anchors at, not over many. Rules are positive (validateActionRulerefuses the rest), which is what makes a pass on the pseudo record hold for every record thewhereadmits. - One held entitlement. Failing that, the entry is one entitlement the writer holds, passed on
whole: the same
resourceand anchor (resource, id, path); each granted action one it holds or reaches by pure delegation (a bare action name, alone or an arm of a top-levelany: holdingmanagegrantsreadwhenreadis{ any: ['manage', …] }); itswherecopied or narrowed (every condition of the heldwhere, meaning itself or each child of its topall, among the entry's); and whoever granted the held one still takes each granted action on the pseudo record, so a copy needs its granter to still hold the action at that anchor. That liveness walk asks the anchor and the action at every link and consults nowhere: awherevaries too much to prove on a pseudo record, so it is judged by its structure alone, and a value thewhererequires that the pseudo record leaves unknown (id in [A, B]) passes on at any depth. A granter whose only live route is limited by awheretherefore counts as live for records outside it; reads still apply everywhereon the chain they walk, so a copy installed under its writer admits no more than that chain. Held entitlements never combine: to pass on two, grant two.
An entitlement that grants below it. The first pass counts three things: the writer's role;
an entitlement the writer holds on a record above the granted one, with no where, marked
grantsBelow; and, behind each such entitlement, whoever granted it, judged by the same three.
A member that holds operate on its own member row this way grants over its own integrations; a
holder of manage on space s1 this way grants manage on the integrations of s1 (before, it
could pass on only a copy of manage on s1).
- Above the granted record means the hydrated rows the entry's anchor row holds under to-one
relations that own their key, followed up, plus the anchor row itself when the entry sits under
it by a path. An entitlement met anywhere else never counts: on a pseudo record below the
anchor, on a row reached through a relation that does not own its key or across a bridge, or on
the granted record itself (a self-anchored entry's pseudo record is the granted row). So held
entitlements still never combine, and one is still never re-anchored (held on the integrations
of o1, never granted for the one integration i1) or stretched to an action that needs more than
it (
readon s1 never grants a rule-gatedrenameon s1). - No
where, at every depth. A heldwherewould be read on today's anchor row and then left out of the grant: holdingmanageon s1where label = draftwould grantmanageon the integrations of s1 while s1 is a draft, and the new row, backed by someone else, would keep admitting after s1 stops being one. A row with awhereis handed on only by the second pass, which keeps every held condition. The same holds for the granter behind a counted row, and the granter behind that. - The mark, and why it is a positive one. The library sees a
where; it does not see a lens or any other limit the app keeps on a stored row. The app setsgrantsBelow: trueonly on a row nothing narrows (in template and Kingdom: no lens). A row without the mark never counts in the first pass, at any depth, so an app that forgets the mark gets the refusal it had before, never a grant that drops a lens. A lensed row is handed on by the second pass, where the lens composes along the chain at read. A copy may carry the mark even when the row it copies does not: it still grants nothing below, because the owner behind it is unmarked and the mark is asked at every depth. WritegrantsBelow: trueor leave the key out; any other value makes the row malformed, andwellFormedEntitlementsdrops a malformed row. The mark is no part of what the entry grants: only the grant check's first pass reads it.setupkeeps it, a marked row and its unmarked twin are two rows, and neither makes the other redundant.
reachableFrom(schemaMap, resource, action) is that pure-delegation walk: the actions on resource
whose holding grants action (itself included). capAtRole keeps a delegate's entries at its
ceiling by it.
Permissions evaluates every rule with exact strings (json-rules string.caseInsensitive and
string.fuzzy off), whatever the app sets globally, so grant time and read time always agree; a
leaf that wants case-insensitivity says so itself, and such a leaf never narrows.
An action's rule is ReBAC (walks to parents) plus ABAC ({ rule } conditions on the record,
conditions on actor:<Model>, who acts). Granting checks both on the pseudo record, with no actor, so a
rule that needs an actor never grants; at read time the holder's check walks the writer's table on the real
record with the request's actor. A holder of a granted action reaches no further than its writer
would on that record.
// assign: high roles need own, others need manage
assign: {
any: [
{ all: [{ rule: { field: 'role', operator: 'in', value: ['owner', 'admin'] } }, 'own'] },
{ all: [{ rule: { field: 'role', operator: 'in', value: ['member', 'viewer'] } }, 'manage'] },
],
}
// An admin (manage) grants assign; its holder assigns member-role records, never owners.
// db:Token.create: { all: [{ rule: { field: 'actor:User.id', operator: 'exists' } }, 'operate'] }
// No one grants db:Token.create: the grant check has no actor, so the person-only rule never passes.Helper: delegation, full or specified
A delegate (a token, an integration) acts from its owner's permissions (a user, a member, an organization, another delegate). The library resolves what those permissions become; the app loads the owner's rows and decides who may make what. Permissions are data:
type Permissions = { entries: PermissionEntry[]; owner?: Permissions }[];A group without owner is role grants; a group with one is entitlements, backed by the
permissions of whoever granted them. installPermissions(permix, permissions) sets each group up
in order, building every owner's permix from its own permissions; permixOf(permissions) returns
a fresh permix with the permissions installed. An owner reached more than once in one install is
built once when it is the same Permissions object, so build each owner's permissions once and
reuse the object: two delegates of one owner, or the two sides of a diamond, then share it. An
owner reached again while it is still being built is a loop in the data; that edge backs nothing.
const permissions = delegate(schemaMap, ownerPermissions, {
full: row.full,
ceiling: row.ceiling,
entitlements: wellFormedEntitlements(row.entitlements),
});
const permix = await permixOf(permissions);fullis the only way through whole. A full delegate's permissions are its owner's, the owner's own entitlements included.- A ceiling never carries entitlements. Without
full, the owner's role grants are kept at the ceiling and its entitlement groups are dropped.capAtRole(schemaMap, entry, ceiling)keeps actionxon the entry's resource when the ceiling (the action the delegate's role maps to) reachesxby pure delegation (reachableFrom) and the entry holds something that does:ownatoperatekeepsoperateandreadwherereaddelegates tooperateandoperatetomanagetoown;readatoperatestaysread; an entry on a resource without the ceiling action is dropped. No role ladder: the schema's chain is the only order. A conditional action is not held. - A delegate's own entitlements are backed by its owner's permissions and re-checked live like any other: an owner that loses the action takes the entitlement with it.
- Silence never widens. No
full, no ceiling and no entitlements is the empty permissions.
Delegates chain: a token on an integration of a member is delegate(schemaMap, delegate(schemaMap,
member, integration), token). A full token on a full integration is the member's permissions; a
ceiling anywhere on the chain caps what is below it and drops the entitlements above it; a token's
entitlements are backed by the integration's permissions, whatever that resolved to.
The library resolves full; who may set it is the app's policy, written as an action in its
schema (a delegateFull action on the owner, say, checked before the row is saved). The columns a
delegate model needs:
| Column | Holds |
|---|---|
| full | boolean: the owner's permissions whole |
| ceiling (or a role the app maps to its action) | the action the owner's role grants are kept at, or none |
| entitlements | stored entitlement entries, filtered by wellFormedEntitlements before resolving |
wellFormedEntitlements(value) keeps the entries of a stored value setup would accept, without
the redundant ones; anything but an array is none.
Tenant boundaries
The library has no notion of a tenant. A boundary is whatever junction rows your app turns into tables, and there are two kinds:
- Acting for a tenant (membership). A member of an organization holds a role at the
organization: table entries on
db:Organization, installed from the membership row. Whatever the schema lets the organization's role reach, the member reaches. - A tenant passing on actions on its own resources (delegation, licensing). A distributor that licenses its products to an organization does not give the organization a role at the distributor. It gives it entitlements on its products, anchored at the distributor and owned by the distributor's table, installed from the license row. The organization then passes them on to its members the same way, as entitlements owned by the organization.
Pick by asking whose behalf the action is on. If the holder acts as the tenant, it's a membership. If the tenant hands out actions on things it owns, it's an entitlement owned by the tenant.
What keeps a boundary closed:
- The owner re-walk is the crossing check. At every read, each entitlement's owner must still allow the asked action on the record, through the normal walk, at every link of the chain. Revoke the license, demote the owner, or cut any link, and everything downstream of it stops at once.
- The anchor is the last mile. An entitlement reaches only records under its anchor, so a record moved to another tenant, even one the owner also controls, is out of reach.
- Junction rows are written under an action on the granting side. An agent that issues licenses writes the license row under an action the schema gives it on the distributor. The license's entit
