Skip to content
clientdb

Search the docs

Find a page or section

Guides

Permissions

One file per model that says who may see and change what: read rules, restricted fields, write rules with field groups, server query rules and claims.

In a usual app, every API route checks permissions on its own: "is this user a member of this project?", "only admins may rename it". With clientdb there are no per-feature routes, so those checks live in one place instead: a permissions folder with one file per model.

It answers two questions for each model:

  • Who may read it? Each user's device only ever receives the rows their read rule allows. When the answer changes (someone joins a project, a todo turns private), clientdb adds or removes rows on their devices to match.
  • Who may change it, and how? Every write from a device is checked on your server against the create, update, delete and archive rules before it's saved. A refused write is undone on the user's screen.

Rules are written in TypeScript and typed against your models and relations, so todo.project.members autocompletes and a typo is a compile error. The examples use the todo app from the quick start, with one addition: each project has an invite code that only its admins receive.

src/sync/schema.ts
import { fromPrisma } from "@clientdb/prisma";
import { prismaModels } from "../generated/clientdb";

export const schema = fromPrisma(prismaModels, {
  omit: { User: ["passwordHash"] },
  models: {
    User: { load: "eager" },
    Project: { load: "eager", restricted: ["inviteCode"] },
    Member: { load: "eager" },
    Todo: { load: "eager" },
  },
});
export type Schema = typeof schema;

One file per model

A rule receives the row and $, the permission helpers: $.viewer.id is the signed-in user, and $.anyOf, $.and and the others combine conditions. Nothing is shared between files except what you import.

Conditions you reuse across models are defined once with defineRule, next to the model they're about. The row's type comes from the model name:

src/sync/permissions/project.ts
import { defineModelRules, defineRule } from "@clientdb/server";
import { $support } from "../claims";
import { schema } from "../schema";

export const isMember = defineRule(schema, "project", (project, $) => {
  return project.members.some((member) => {
    return member.userId.is($.viewer.id);
  });
});

export const isAdmin = defineRule(
  schema,
  "project",
  (project, $) => {
    return project.members.some((member) => {
      return $.and(member.userId.is($.viewer.id), member.role.is("admin"));
    });
  },
  { name: "project.admin" }, // optional: a readable, stable id for a widely shared condition
);

export const projectRules = defineModelRules(schema, "project", {
  read: {
    when: (project, $) => {
      return $.anyOf({ member: isMember(project), support: $support });
    },
    fields: {
      inviteCode: (project) => {
        return isAdmin(project);
      },
    },
  },
  create: {
    when: (project, $) => {
      return $.authenticated;
    },
  },
  update: {
    when: (project) => {
      return isAdmin(project);
    },
    fields: ["name", "inviteCode"],
  },
  archive: {
    when: (project) => {
      return isAdmin(project);
    },
  },
});

Other models import the conditions they need:

src/sync/permissions/todo.ts
import { defineModelRules } from "@clientdb/server";
import { schema } from "../schema";
import { isAdmin, isMember } from "./project";

export const todoRules = defineModelRules(schema, "todo", {
  read: (todo, $) => {
    return $.anyOf({
      shared: [todo.isPrivate.is(false), isMember(todo.project)],
      author: todo.authorId.is($.viewer.id),
      admin: isAdmin(todo.project),
    });
  },
  create: {
    when: (todo) => {
      return isMember(todo.project);
    },
    enforce: ($) => ({ authorId: $.viewer.id }),
  },
  update: [
    {
      fields: ["title", "done"],
      when: (todo) => {
        return isMember(todo.project);
      },
    },
    {
      fields: ["isPrivate"],
      when: (todo, $) => {
        return $.anyOf({ author: todo.authorId.is($.viewer.id), admin: isAdmin(todo.project) });
      },
    },
  ],
  delete: {
    when: (todo, $) => {
      return $.anyOf({ author: todo.authorId.is($.viewer.id), admin: isAdmin(todo.project) });
    },
  },
  // what server queries (`db.todo.query(…)`) may filter on, and the largest page
  query: {
    fields: { title: ["contains", "startsWith"], done: ["is"], createdAt: ["gte", "lt"] },
    maxLimit: 100,
  },
});
src/sync/permissions/member.ts
import { defineModelRules } from "@clientdb/server";
import { schema } from "../schema";
import { isAdmin, isMember } from "./project";

export const memberRules = defineModelRules(schema, "member", {
  read: (member) => {
    return isMember(member.project);
  },
  // no create rule: invitations are accepted by a server action, which writes the member row
  update: {
    when: (member) => {
      return isAdmin(member.project);
    },
    fields: ["role"],
  },
  delete: {
    when: (member, $) => {
      return $.anyOf({ admin: isAdmin(member.project), leaving: member.userId.is($.viewer.id) });
    },
  },
});
src/sync/permissions/comment.ts
import { defineModelRules } from "@clientdb/server";
import { schema } from "../schema";

// a comment is readable exactly when its todo is
export const commentRules = defineModelRules(schema, "comment", {
  read: (comment, $) => {
    return $.canRead(comment.todo);
  },
  create: {
    when: (comment, $) => {
      return $.canRead(comment.todo);
    },
    enforce: ($) => ({ authorId: $.viewer.id }),
  },
  delete: {
    when: (comment, $) => {
      return comment.authorId.is($.viewer.id);
    },
  },
});

user follows the same pattern: a user reads their own row and their teammates' (see the quick start). Finally, one file combines them:

src/sync/permissions/index.ts
import { definePermissions } from "@clientdb/server";
import { schema } from "../schema";
import { commentRules } from "./comment";
import { memberRules } from "./member";
import { projectRules } from "./project";
import { todoRules } from "./todo";
import { userRules } from "./user";

export const permissions = definePermissions(schema, [userRules, projectRules, memberRules, todoRules, commentRules]);

A module works too: definePermissions(schema, modelRules), after import * as modelRules from "./rules", takes every rule set it exports and ignores the rest (such as isMember).

definePermissions refuses two rule sets for one model, and rule sets or conditions built from another schema. Outside production it is also strict: a model with no read rule is an error that names it, so a new model can't silently stay off devices. Nothing is readable implicitly, not even a child that cascades from its parent: comment says $.canRead(comment.todo) itself. Mark models that never sync serverOnly in the schema, or pass { strict: false } to let models without a read rule simply not sync.

Rule shapes

RuleShapeMeaning
read(row, $) => conditionwhich viewers receive the row. Without it, the model never syncs
read{ when, fields: { inviteCode: (row, $) => condition } }the form for models with restricted fields
create{ when, enforce? }who may create rows; enforce lists fields that must equal a value
update{ when, fields }, or a list of themwho may change which fields (field groups)
delete{ when }who may delete rows
archive{ when }who may archive and unarchive rows of an archivable model
query{ fields, maxLimit }what server queries may filter on
validateasync ({ operation, before, after, viewer, db }) => message | nullany check, in the write's transaction; return a message to refuse
  • A missing write rule refuses that operation. No delete rule: nobody deletes from a device; your backend still can.
  • when must hold before and after the change, for updates, so nobody can move a row out of their reach or into someone else's.
  • enforce lists fields that must equal $.viewer.id or a literal: enforce: ($) => ({ authorId: $.viewer.id, status: "open" }), or enforce: { status: "open" } without the viewer. It applies to every row the viewer creates, and to updates that change those fields. A write with another value is refused with Forbidden, naming the field: todo.authorId must equal the viewer's id. Rules only check, they never fill anything in: the device sends authorId: db.$session.viewerId itself, so the right value shows at once.
  • validate is for what conditions can't express, such as "at most 50 todos per project". viewer is the viewer's id, and db.find(model, field, value) reads rows.

Update field groups

update takes a list of field groups, each with its own condition. In todoRules above, any member may change title and done; only the author or an admin may change isPrivate.

An update passes when every field it changes belongs to a group whose when holds, before and after the change. A member who isn't the author and changes done and isPrivate together is refused as a whole, and the error names isPrivate. updatedAt fields belong to every group. One group needs no list: update: { when, fields }.

Restricted fields

A read rule decides which rows a viewer receives. A restricted field narrows that for one field: the viewer receives the row when when holds, and the field's value only when its own rule holds too. Everyone else receives the row without it.

  • Declare the field restricted in the schema: .restricted() in TypeScript, restricted: ["inviteCode"] in fromPrisma.
  • Then the model's read rule takes the { when, fields } form, and every restricted field needs a rule there. Only restricted fields take one: a field rule on any other field is a type error.
  • On the client, a restricted field is typed T | undefined: project.inviteCode is undefined on a plain member's device.
  • Viewers who can't read a field can't change it either. A restricted field can't be a load key or appear in query.fields: looking rows up by it could reveal it.
  • A restricted field with no rule in fields is an error from definePermissions outside production, and reaches nobody in production.

When someone becomes an admin, the invite codes arrive on their devices; when they stop being one, the codes are removed.

Server queries

db.todo.query({ where, orderBy, limit }) asks the server for rows that aren't on the device (see Reading data). A model can only be queried when its rules say how:

  • fields lists the fields where may filter on, each with its operators: is, in, ranges (gt, gte, lt, lte), and on text contains, startsWith and endsWith. A query on another field or operator is refused with a QueryError that names it.
  • maxLimit is the largest page a query may ask for.
  • Results are still limited to rows the viewer may read, so query never widens access; it only says which searches are allowed.

Claims: facts about the session

A claim is a fact about the signed-in session that isn't a row, such as "has an active support login". Declare it once, in a file the server and the client both import:

src/sync/claims.ts
import { declareClaim } from "@clientdb/schema";

export const $support = declareClaim("support");
  • Your session callback grants it: claims: [$support(isOnShift)] (the claim is granted when the argument is true, the default).
  • A rule uses it as a condition anywhere: alone, in $.anyOf, $.and and $.or. In projectRules above, support staff read every project.
  • The client asks for it: db.$session.hasClaim($support).

clientdb checks the session again on every request, and on a live connection every few minutes. When the callback stops granting a claim, the rows readable only through it leave that device. See Permission recipes.

The rule language

Fully typed through your relations:

ExpressionMeaning
row.field.is(value), .is($.viewer.id)equality
.isNot(value), .in([…]), .notIn([…])comparisons with literals
.isNull(), .notNull()null checks
row.flag, row.flag.is(false)a boolean field used directly, or its negation
row.relation.fieldfollows to-one relations: todo.project.name
row.collection.some((child) => { … })a matching child row exists: project.members.some(…)
$.anyOf({ label: condition, other: [a, b] })"or" with labeled branches; an array means all of its conditions must hold
$.and(a, b), $.or(a, b)unlabeled "and" and "or"
$staff (a claim)the session holds the claim
$.authenticatedevery signed-in viewer
$.publiceveryone, anonymous visitors included
$.canRead(row.relation)the related row's own read rule: $.canRead(comment.todo). Works in read and write rules; see below
$.canRead(row.relation, { except: ["admin"] })that read rule without some labeled branches or named rules
defineRule(schema, "project", (project, $) => { … }, { name })a reusable condition, called as isMember(todo.project)
$.named("project.member", condition)gives a condition a stable, readable id, as defineRule's name does
$.viewer.row.fieldthe viewer's own fields: $.viewer.row.email.is("…")
$.group("auditors"), $.group("guests", todo.projectId)an explicit group
$.not(condition)only for deny rules

The labels in $.anyOf show up in explain() and in errors, so a refused write says which branches failed:

Text
Forbidden: todo.delete (author: no, admin: no)

Reading like the parent

$.canRead(row) holds when the viewer may read that row under its own model's read rule. It takes a row reached from the rule's row: a relation (comment.todo, comment.todo.project), a row inside some(), or the rule's row itself, which suits write rules ($.canRead(comment): the writer must be able to read what they write).

A read rule that is exactly $.canRead(parent) makes each row readable by whoever can read its parent:

TypeScript
read: (comment, $) => {
  return $.canRead(comment.todo);
},

The engine stores such rows with their parent's access. When the parent's access changes, for example when a todo with 2,000 comments becomes private, the children are re-tagged in bulk, one UPDATE … RETURNING per level, and users who lose the todo lose its comments with it. A child with restricted fields, a rule with except, or a rule that adds conditions ($.and($.canRead(comment.todo), …)) still works; its rows are routed one by one instead.

$.canRead is independent of onDelete: "cascade": a cascading child needs a read rule like any other model, and a child that doesn't cascade can read like its parent too.

Why some read rules are rejected

clientdb has to know, for every change, which users should receive it, without running your rules once per user. So read rules must describe access in terms of who the user is related to: a project they're a member of, a todo they wrote, their own user row, a claim they hold. Rules are checked when the server starts; a rule that can't be turned into "these users may see this row" fails right away with AccessCompileError and a message that says why, instead of leaking data later.

Write rules have no such limit: they run on the server for each write, so they can check anything.

The full list of rejected shapes, and how clientdb turns rules into deliveries, is in Under the hood: groups and routing.

Every signed-in user, and anonymous visitors

Every read branch needs a condition on the viewer. A rule like read: (todo) => { return todo.isPrivate.is(false); } would let every signed-in user of the app read every public todo, so it is a compile error. Say so explicitly when that is what you mean:

TypeScript
read: (todo, $) => {
  return $.and($.authenticated, todo.isPrivate.is(false)); // any signed-in user, never anonymous
},

$.public includes anonymous visitors too. When your session callback returns null and the handler sets anonymous: true, the request gets an anonymous, read-only session that sees only $.public rows. Without anonymous: true, null is answered with 401.

Deny rules

$.not is only for rules that withhold a row whatever else allows it, such as a block list: $.and($.not(blockedByViewer), isMember(todo.project)). See Deny lists. Everywhere else, negate a field with .is(false).

Testing your rules

compileAccess(permissions).explain() prints how clientdb understood your rules, branch labels included. To check what each user actually receives and which writes are refused, see Testing. clientdb's own test suite checks the engine against a reference implementation of the rules: after any sequence of changes, every simulated user must hold exactly what the rules allow.