Skip to content
clientdb

Search the docs

Find a page or section

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:

  1. Group kinds, such as project.members and project.admin. A group is one kind plus an anchor: project.members|<projectId> is "the members of this project".
  2. Routing, per model: which groups a row belongs to, computed from the row's own data. For the todo app: a todo with isPrivate: false goes to project.members|<projectId>, and every todo goes to user|<authorId> and project.admin|<projectId>.
  3. Membership sources: which rows decide who is in which group. A member row with userId = X and role = "admin" puts user X in project.members|<projectId> and project.admin|<projectId>.

A row reaches a user exactly when the row's groups and the user's groups overlap.

Text
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 it

How 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) and row.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.
  • $.public compiles to one group for everyone, and $.authenticated to 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 in explain(), 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:

scripts/explain.ts
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:

Text
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" }) uses project.admin as the id. It is readable in explain(), in errors and in the client's db.$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 snapshotStore holds 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:

TypeScript
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:

src/sync/permissions/index.ts
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:

TypeScript
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 $.anyOf branches, or use an explicit group.
  • A comparison with the viewer is anything but equality with $.viewer.id: no isNot($.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 $.not is 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 $.public to include anonymous sessions. A whole-rule deny counts as a condition; negating $.authenticated is rejected.
  • One name is used for two different conditions. For example, a rule named project.admin returning $.or(member.role.is("owner"), member.role.is("admin")) describes two membership paths under one name; write member.role.in(["owner", "admin"]) instead. Two rules with the same name but 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.