Under the hood
Groups and routing
How read rules compile into groups, how rows and viewers are tagged, and which rules the compiler rejects (and why).
Under the hood
You don't need this page to use clientdb. It explains how things work inside, for when you're curious or debugging. The short version is How it works, in 5 pictures.
The engine never evaluates read rules once per user. Instead, when the engine is created, it turns every read rule from Permissions into three things:
- Group kinds, such as
project.membersandproject.admin. A group is one kind plus an anchor:project.members|<projectId>is "the members of this project". - Routing, per model: which groups a row belongs to, computed from the row's own data. For the todo app: a todo with
isPrivate: falsegoes toproject.members|<projectId>, and every todo goes touser|<authorId>andproject.admin|<projectId>. - Membership sources: which rows decide who is in which group. A
memberrow withuserId = Xandrole = "admin"puts user X inproject.members|<projectId>andproject.admin|<projectId>.
A row reaches a user exactly when the row's groups and the user's groups overlap.
todo T-2 { isPrivate: true, authorId: carol } ──route──▶ { user|carol, project.admin|launch }
Alice (member, admin) ──member──▶ { user|alice, project.members|launch, project.admin|launch } ✓ receives T-2
Bob (member) ──member──▶ { user|bob, project.members|launch } ✗ never sees itHow rules become groups
project.members.some((member) => { return member.userId.is($.viewer.id); })compiles to one group per project.- A filter on the membership row, such as
member.role.is("admin"), compiles to a separate group kind, so promotion and demotion are just a user joining or leaving a group. row.id.is($.viewer.id)androw.authorId.is($.viewer.id)compile to one group per user.- Filters on the viewer's own row (
$.viewer.row.email.in(["ada@acme.com"])) compile to groups computed from that row. $.publiccompiles to one group for everyone, and$.authenticatedto one for every signed-in user.- A claim compiles to one group per claim,
claim:support, which the session joins while the callback grants the claim. - Each label in
$.anyOf({ … })is one branch of the rule. Labels name branches inexplain(), in errors and in$.canRead(row, { except }); they don't change which groups exist. - A restricted field gets its own routing: the row records which of its groups may read each restricted field, and each user receives the row with only the fields their groups may read.
Print the compiled plan with:
import { compileAccess } from "@clientdb/server";
import { permissions } from "../src/sync/permissions";
console.log(compileAccess(permissions).explain());For the rules on the permissions page, it prints:
group kinds
user ← user
project.members ← member{userId=viewer} → project(projectId)
claim:support ← claim
project.admin ← member{userId=viewer, role="admin"} → project(projectId)
routing (row → groups)
project → project.members(id)
project → claim:support(*)
project.inviteCode → project.admin(id)
todo → project.members(project) if isPrivate=false
todo → user(authorId)
todo → project.admin(project)
comment → project.members(todo.project) if todo.isPrivate=false
…Group ids and names
Every group kind has an id, and every row and user is tagged with keys built from it, such as project.members|<projectId>.
- Without a name, the id comes from the condition's shape, for example
project.members{role∈["admin"]}. Identical conditions get the same id wherever you wrote them, so they share one group. - With a name,
defineRule(schema, "project", (project, $) => { … }, { name: "project.admin" })usesproject.adminas the id. It is readable inexplain(), in errors and in the client'sdb.$groups, and it doesn't reveal rule details such as role names to the client. - Ids are stored: with every synced row, in each user's memberships, in the snapshot cache and on every device. Renaming a name, or changing the shape of an unnamed condition, makes a new group kind on the next
engine.migrate(), which recomputes everyone's groups and re-routes the affected models. That runs online, but it isn't free. A fixed name avoids it when you only refactor how a rule is written.
Names are optional. Set one for conditions that many models share, like project membership and admin roles.
What this buys you
- Writes don't fan out per user. Each write appends one group-tagged entry to the log, however many people can read it.
- Delivery is a set overlap check, cheap enough to run for every connected device on every write.
- Access changes are exact. A membership row changing means one user joins or leaves a group; a row's groups changing means the row arrives on or leaves exactly the devices on either side. See When access changes.
- Bootstraps can be cached. A group's contents are the same for every member, so an optional
snapshotStoreholds them per (tenant, model, group), shared by all members, until any write touches the group.
Deny groups
With a block model (userId blocks blockedUserId), a user's todos can be withheld from the people they blocked:
read: (todo, $) => {
const blocked = todo.author.blocks.some((block) => {
return block.blockedUserId.is($.viewer.id);
});
return $.and($.not(blocked), isMember(todo.project));
},This compiles to a per-user deny tag: the row is withheld from blocked users even when another branch allows it. Blocking and unblocking remove the row from, or bring it back to, that user's devices. A deny must apply to the whole rule; the compiler checks this.
Explicit groups
For membership the rule language can't express, declare a group with your own membership function, in the groups option of definePermissions:
import { definePermissions } from "@clientdb/server";
import { schema } from "../schema";
import { memberRules } from "./member";
import { projectRules } from "./project";
import { todoRules } from "./todo";
import { userRules } from "./user";
const AUDITOR_EMAILS = (process.env.AUDITOR_EMAILS ?? "").split(",");
export const permissions = definePermissions(schema, [userRules, projectRules, memberRules, todoRules], {
groups: {
auditors: {
// the anchors this user belongs to: "*" for a group without one
members: async (viewer, db) => {
const user = await db.get("user", viewer);
return user && AUDITOR_EMAILS.includes(user.email as string) ? ["*"] : [];
},
// which writes change whose membership ("*" = every user)
affects: {
user: (row) => {
return row.id as string;
},
},
},
},
});Rules refer to a group by name with $.group, alone or anchored at a field of the row; definePermissions fails on a name it doesn't define:
read: (todo, $) => {
return $.anyOf({ member: isMember(todo.project), auditor: $.group("auditors") });
},
// anchored: members() returns project ids, and the rule says which one the row needs
read: (project, $) => {
return $.anyOf({ member: isMember(project), guest: $.group("guests", project.id) });
},What the compiler rejects
Every read rule must be routable. Rules are rejected with AccessCompileError when the engine is created if:
- A branch requires two separate memberships at once, for example member of the project and of another team, in one array or
$.and. That would need the overlap of two groups. Split it into separate$.anyOfbranches, or use an explicit group. - A comparison with the viewer is anything but equality with
$.viewer.id: noisNot($.viewer.id), no ordering. Filters on the viewer's own row must compare its fields with literals. - A membership row is filtered by something other than its own fields, or by values that depend on the viewer.
- A
$.notis anything but a whole-rule deny of a single membership condition, that is$.and($.not(…), $.anyOf({ … })).$.not($.public)and negated explicit groups are rejected too. - A read branch has no condition on the viewer, for example
todo.isPrivate.is(false)alone, or() => { return true; }. That would let every signed-in user read the row (on Prisma tables, every user of the app). Write$.and($.authenticated, todo.isPrivate.is(false))if that is what you mean, or$.publicto include anonymous sessions. A whole-rule deny counts as a condition; negating$.authenticatedis rejected. - One
nameis used for two different conditions. For example, a rule namedproject.adminreturning$.or(member.role.is("owner"), member.role.is("admin"))describes two membership paths under one name; writemember.role.in(["owner", "admin"])instead. Two rules with the samenamebut different bodies are rejected too. canRead()references form a cycle, or a relation is unknown.
Tip
Write rules have none of these limits: they are evaluated in the write's transaction, not routed.