PermDock
CLI

powersync

permdock powersync generate compiles the policy's read grants into PowerSync Sync Streams, and verify checks that no stream syncs a row the policy denies.

permdock powersync generate [--out sync-config.yaml] [--check] [--policy <module>]
permdock powersync verify [--db-url-stdin] [--fixtures rls.fixtures.json] [--policy <module>]

generate writes an edition 3 Sync Streams file with one auto-subscribed stream per synced resource. Each stream's queries are the ways a user may read a row: one query per allow grant of the read permission, and one per role source of the membership table. The tables and memberships come from rls: rls.tables, and per scope its rls.memberships table, else its rls.membershipSources. That is the same database-mode mapping permdock rls generate reads.

// permdock.config.ts
export default {
  policy: "./src/policy.ts",
  rls: {
    authorize: "database",
    tables: { job: "jobs" },
    memberships: {
      scopes: {
        organization: {
          table: "organization_users",
          user: "user_id",
          role: [
            "tier",
            { through: "roles", on: { role_id: "id" }, column: "key" },
          ],
          columns: { organization: "organization_id" },
        },
      },
    },
  },
  powersync: { out: "sync-config.yaml" },
};
# Generated by permdock powersync generate from the policy. Do not edit.
config:
  edition: 3

streams:
  job:
    auto_subscribe: true
    queries:
      - "SELECT * FROM jobs WHERE jobs.organization_id IN (SELECT organization_users.organization_id FROM organization_users WHERE organization_users.user_id = auth.user_id() AND organization_users.tier IN ('admin'))"
      - "SELECT * FROM jobs WHERE jobs.organization_id IN (SELECT organization_users.organization_id FROM organization_users INNER JOIN roles ON roles.id = organization_users.role_id WHERE organization_users.user_id = auth.user_id() AND roles.key IN ('admin'))"
FlagValuesDefaultEffect
--outa pathpowersync.out, else sync-config.yamlWhere generate writes and what verify compares
checkflagoffgenerate: exit 1 when the file on disk is stale; write nothing. The command is permdock generate --check.
--db-url-stdinflagoffverify: read the connection string from stdin and run every stream query against that database per fixture (default DATABASE_URL, then SUPABASE_DB_URL)
--localflagoffverify: connect to the local Supabase stack, DB_URL from supabase status
--stacka namenoneverify: with --local, the named stack of this worktree
--fixturesa pathrls.fixtures, else rls.fixtures.jsonverify: the rls verify fixtures
--policya modulepolicy in the configThe module exporting policy

powersync also takes resources (the only resources that get a stream; a helper does not add one), action (default read), manifest (a path; none by default), tables (tables that are not resources) and memberLevel (per-member level).

Tier column plus role assignments

A plan tier on the membership row and role assignments in a second table are two membership sources of one scope. A generated column turns the tier into a role key, so the stream compares a column instead of mapping values:

alter table tenant_users add column tier_role text generated always as (
  case tier when 'business' then 'owner' end
) stored;
// permdock.config.ts
import { junctionMembershipSource } from "permdock/supabase";

export default {
  policy: "./src/policy.ts",
  rls: {
    authorize: "database",
    customRoles: true,
    tables: { job: "jobs" },
    membershipSources: [
      junctionMembershipSource({
        table: "tenant_users",
        scope: "tenant",
        id: "tenant_id",
        roles: "tier_role",
      }),
      junctionMembershipSource({
        table: "user_roles",
        scope: "tenant",
        id: "tenant_id",
        roles: { through: "roles", on: { role_id: "id" }, column: "key" },
      }),
    ],
  },
  powersync: { out: "sync-config.yaml", manifest: "permdock-manifest.json" },
};

With job.read granted to owner and levels own, team and all on job, generate writes one query per source for the declared role, then one per source and level for the tenant's custom roles (abridged):

# Generated by permdock powersync generate from the policy. Do not edit.
# Tables outside public must be in the powersync publication:
# alter publication powersync add table permdock.custom_role_includes, permdock.custom_role_permissions, permdock.user_roles;
config:
  edition: 3

streams:
  job:
    auto_subscribe: true
    queries:
      - "SELECT * FROM jobs WHERE jobs.tenant_id IN (SELECT tenant_users.tenant_id FROM tenant_users WHERE tenant_users.user_id = auth.user_id() AND tenant_users.tier_role = 'owner')"
      - "SELECT * FROM jobs WHERE jobs.tenant_id IN (SELECT user_roles.tenant_id FROM user_roles INNER JOIN roles ON roles.id = user_roles.role_id WHERE user_roles.user_id = auth.user_id() AND roles.key = 'owner')"
      - 'SELECT * FROM jobs WHERE jobs.tenant_id IN (SELECT user_roles.tenant_id FROM user_roles INNER JOIN roles ON roles.id = user_roles.role_id INNER JOIN "permdock"."custom_role_permissions" AS cr ON cr.role = roles.key WHERE user_roles.user_id = auth.user_id() AND cr.tenant_id = user_roles.tenant_id AND cr.scope = ''tenant'' AND cr.permission = ''job.read'' AND cr.effect = ''allow'' AND cr.level = ''own'') AND jobs.owner_id = auth.user_id()'
  permdock_tenant_users:
    auto_subscribe: true
    queries:
      - "SELECT * FROM tenant_users WHERE tenant_users.user_id = auth.user_id()"
  permdock_user_roles:
    auto_subscribe: true
    queries:
      - "SELECT * FROM user_roles WHERE user_roles.user_id = auth.user_id()"
  permdock_permdock_user_roles:
    auto_subscribe: true
    queries:
      - 'SELECT * FROM "permdock"."user_roles" AS permdock_user_roles WHERE permdock_user_roles.user_id = auth.user_id()'

The custom-role tables and PermDock's global user_roles live in the permdock schema, which a for all tables in schema public publication leaves out. generate prints the statement and writes it into the file header; run it once:

alter publication powersync add table permdock.custom_role_includes, permdock.custom_role_permissions, permdock.user_roles;

Under the pg-delta workflow, when a file in the schema directory (supabase/schemas by default) creates the powersync publication, generate writes the statement to <schemaDir>/permdock/powersync_publication.sql instead, and the YAML header leaves it out. pg-delta diffs publication membership, so supabase db schema declarative sync adds the tables in a migration, and generate --check reports the file when the synced tables change. The publication stays yours:

supabase/schemas/public/powersync.sql
create publication powersync for tables in schema public;

The statement stays in the header when no schema file creates the publication, because the shadow load would fail on an alter of a publication it never created. It also stays there for a for all tables publication, which already holds every table and rejects add table, and under supabase.schemas: 'migra' or 'migrations'.

permdock.user_roles shares its name with public.user_roles, so it syncs as the device table permdock_user_roles.

Per-member level

Without memberLevel, every member of a tenant syncs every row their grants reach in it. For a tenant with 1M jobs that is 1M rows on each device. powersync.memberLevel narrows a resource's stream by a column on the member's membership row:

// permdock.config.ts
export default {
  powersync: {
    resources: ["job"],
    memberLevel: { job: { table: "tenant_users", column: "job_level" } },
  },
};

The resource declares the levels in code, as for custom roles:

job: resource(Job, {
  levels: { own: { owner_id: principal.id }, team: inTeam },
});
tenant_users.job_levelRows the device syncs
null or allEvery row the grants reach in the tenant
ownThe rows the own level's condition reaches
teamThe rows the team level's condition reaches
Any other valueNone

Each query of the stream gets one alternative per value, so the stream holds the union of the rows the member's level reaches. The table is the tenant scope's membership table: the one rls.memberships maps, or a membership source. Its disabledAt filter applies. A level the stream cannot express, such as an opaque condition, syncs nothing and generate warns. A resource that declares neither own nor team gets no stream.

The narrowing is deliberate under-sync: can() on the device still decides, and the app reads the rows outside the level from the server. generate writes the warning, and verify treats a granted row that no stream syncs as a note for that permission, whatever role the subject holds.

Local snapshot rows

generate also writes the streams a device needs to build the user's snapshot with localSnapshot, each named permdock_<table> and starting from the user's own rows:

  • permdock_<memberships table>: the user's membership rows (<user> = auth.user_id()) for each table in rls.memberships.
  • permdock_<source table>: the user's rows of each membership source of a scope rls.memberships does not map, and of the table its user reads through.
  • permdock_<global roles table>: the user's global-role rows from rls.roles, else permdock.user_roles in database mode.
  • permdock_<roles table>: the rows of each through roles table that one of the user's membership or global-role rows references. A through with several on columns matches on all of them, and the pair on the user column compares with auth.user_id(). The junction of roles: "many" (blockMembershipSource, membership_roles by default) is the exception: it lists every member of an organisation where the caller's membership is not disabled by the source's disabledAt column, and it skips a member whose own membership is disabled by the same column. It does not keep only user_id = auth.user_id(). Such a stream selects the key columns, the value column and an id built from every on pair as <key> || ':' || … || <value>, because PowerSync keys every row on id.
  • With rls.customRoles in database mode, the custom role tables, limited to rows with no tenant and rows of the user's tenants: the root scope's rls.memberships table, else each of its membership sources.

The hook's permdock_authz_version table stays in the database. generate does not add a stream for it, and it does not create a second version table. nativeRefresh compares the token's authz_ver with the row the app already has.

A sync-config.yaml generated before this keeps filtering the junction on the caller's own user id, which PD102 reports. membership_roles is the exception to the user filter. The stream is every membership role in an organisation the caller belongs to, and the id is organization_id || ':' || user_id || ':' || role for every through.on pair.

A table outside public is read as "<schema>"."<table>" AS <name>, since Sync Streams need the schema in double quotes. The device table is <name>: the table's own name, or <schema>_<table> when another synced table has the same name. Every synced table outside public must be in the powersync publication; generate prints the alter publication statement and writes it as a comment at the top of the file, or as a schema file under pg-delta (see above).

With powersync.manifest set, generate writes localSnapshotManifest(policy) as JSON to that path, with a rows section naming those device tables and their columns (wire formats), so the app bundles the manifest without importing the policy. powerSyncSource(db, { manifest, user }) in permdock/react-native builds the snapshot from those tables (PowerSync source).

Tables that are not resources

powersync.tables adds a stream per table the policy has no resource for, such as a notification inbox or a file table. A stream holds the user's own rows (user, the user id column), the rows that point at a resource row the user reads (follow), or both. Each follow entry names the resource, the field that holds its id, and an optional match of column values for a table whose rows point at several resources. Its query is <field> IN (SELECT <id> FROM <resource table> WHERE …), one per query of the resource's own read grants:

powersync: {
  tables: {
    "public.notification_recipients": { user: "user_id" },
    "public.attachments": {
      user: "uploaded_by",
      follow: [
        { resource: "job", field: "subject_id", match: { subject_type: "job" } },
      ],
    },
  },
},
notification_recipients:
  auto_subscribe: true
  queries:
    - "SELECT * FROM notification_recipients WHERE notification_recipients.user_id = auth.user_id()"
attachments:
  auto_subscribe: true
  queries:
    - "SELECT * FROM attachments WHERE attachments.uploaded_by = auth.user_id()"
    - "SELECT * FROM attachments WHERE attachments.subject_id IN (SELECT jobs.id FROM jobs WHERE jobs.organization_id IN (SELECT organization_users.organization_id FROM organization_users WHERE organization_users.user_id = auth.user_id() AND organization_users.tier IN ('admin'))) AND attachments.subject_type = 'job'"

A followed resource whose read permission has a deny grant, or no grant that compiles, adds no query, and generate warns. A table whose stream would share a resource stream's name, or that names a column that is not an identifier, gets no stream. verify checks that a stream of only the user's own rows holds no other user's row; it has no fixtures for the rows a follow syncs.

What compiles

A query uses only IN (SELECT …), INNER JOIN, auth.user_id() and auth.parameter(…), the subset the Sync Streams compiler runs without EXISTS.

PolicyStream query
role(…, { on: '<scope>' })<row key> IN (SELECT <scope id> FROM <memberships> WHERE <user> = auth.user_id() AND <role> IN (…))
A role column through a roles tableThe same subquery with INNER JOIN <roles> ON …, comparing the roles table's key
Several role sourcesOne query per source
rls.membershipSources (tableMembershipSource, junctionMembershipSource)One query per source and role: <row key> IN (SELECT <id> FROM <source> WHERE <user> = auth.user_id() AND <role> = '…')
A tenant custom role (rls.customRoles, database mode, membership sources)One query per source and level, joining custom_role_permissions on the role key and cr.level, ANDed with the level's condition
levels on the resourceThe level's condition ANDed with the custom-role query of that level
sqlFunction(…, { twin }), with or without setThe twin's query
A role with for kindsAND <via> IN (…) in the subquery
A resource role (on: permissions.<resource>)The same subquery over rls.memberships.resource.<resource>
eq, ne, gt, gte, lt, lte, isNull, in, notIn literalsThe comparison on the row column
principal.id, principal.claims.<name>auth.user_id(), auth.parameter('<name>'); in a claim is IN (SELECT value FROM json_each(…))
orOne query per branch
inherit(<parent>.read, { through })<field> IN (SELECT <parent id> FROM <parent> WHERE …) per query of the parent's own read grants; one nested subquery per link hop
fieldsThe id and the listed columns instead of *

Everything else leaves the grant out of the stream, and generate prints why: a global role (no row filter), a custom role of a root scope that rls.memberships maps, not, contains, opaque and relation() conditions (they read the closure table), request context, approval, break-glass, validFrom / validUntil, and a memberships table or membership source with expiresAt (the sync service cannot compare with the current time). A custom role's deny rows, includes and shared roles do not change its stream: a row a custom-role deny removes still syncs, and can() on the device denies it. A resource whose read permission has any deny grant gets no stream, because a stream can only add rows. An inherit() grant follows at most 4 nested inherit() grants. It syncs nothing when the parent's permission has a deny grant or none of its grants compiles; a parent grant that does not compile leaves its rows out with an under-syncs warning. A restricted child row (restricted) is left out, as can() does. A resource with more than 32 queries gets no stream. A resource with no stream is listed as a comment at the end of the file.

Memberships with disabledAt compile to IS NULL filters in membership checks and custom-role levels. A permission listed in rls.suspension.memberships.keep omits that filter. The user's own membership rows and their referenced roles are filtered too, unless a kept permission needs suspended membership metadata for the local snapshot. This does not make expiresAt supported.

Verify

verify compiles the policy again and fails when sync-config.yaml differs. With --db-url-stdin, it runs each fixture of a synced permission: the stream queries with the subject's id against the database, and can() in process with the row's organization active, since a stream holds rows of every organization the user belongs to. A row a stream syncs and the policy denies is a mismatch and exits 1. A row the policy grants and no stream syncs is a mismatch too, unless generate warned for that permission and a role the subject holds, or for the level of a custom role it holds; then it is a note: the app reads it from the server. A fixture row without the resource's id is a note. can() in verify has no relation source, so a row an inherit() stream syncs and can() denies is a note, not a mismatch. The database must hold the fixture rows, memberships and custom-role rows, as for rls verify --db-url-stdin.

For a non-resource table in powersync.tables, use { subject, table, row, expected } instead of an action fixture. table is the exact configured table name, row.id identifies the synced row, and expected is required (granted or denied). These fixtures may share a file with action fixtures for powersync verify; keep them in a separate file when rls verify also reads the action fixtures.

[
  {
    "subject": { "id": "u1" },
    "table": "attachments",
    "row": { "id": "a1", "parent_id": "j1", "kind": "job" },
    "expected": "granted"
  }
]

verify checks the union of the table's own-user rule and its follow rules. A follow rule must match every configured match field; its parent must exist in the database and pass the resource's configured action in can(), with the parent's organization active. Missing parents and mismatched kinds grant no access. The expected outcome must agree with that access, and the table stream must sync exactly the granted fixture rows. Unknown or omitted table streams and rows without id fail verification. Parent checks have the same no-relation-source limit as resource checks. Fixture validation lives in the CLI loader; there is no separate fixture JSON Schema under the package's schemas/ directory.

For a role, tenant or claim change, use { subject, after, stream?, expected: "changed" }. after holds the subject's new tenant, roles, memberships or claims. verify runs each stream that reads a changed claim, or only stream, once with the claims before and once with the claims after. It fails when the two row sets are equal, and when a row synced after the change is one the policy denies the changed subject. A fixture where no stream reads a changed claim fails too.

[
  {
    "subject": { "id": "u1", "claims": { "team_ids": ["A"] } },
    "after": { "claims": { "team_ids": ["B"] } },
    "expected": "changed"
  }
]

With a database, verify also reads pg_publication_tables: each synced table outside public that the powersync publication leaves out is a PD058 mismatch. A database with no powersync publication is a note.

verify passes a fixture's subject.claims to auth.parameter() and fails when a permdock_* stream syncs another user's rows. It compares the powersync.manifest file as JSON.

permdock doctor reports PD058 when sync-config.yaml or the manifest is stale or missing, when the config does not compile to Sync Streams, and for each membership source of a synced scope that has no stream form.

A stream that reads a token claim keeps the claims its connection started with, so a role or tenant change reaches it only after the app refreshes the session and reconnects. generate and verify print a PD084 line per such stream, the generated file names them in its header, and permdock doctor reports PD084. nativeRefresh does the refresh and the reconnect.

Side effects

What each command may change; side effects explains each one.

CommandSide effects
permdock powersync verifydatabase:read

Why

  • Suspension is a row change. disabledAt IS NULL can be re-evaluated when a membership changes; expiry needs a clock, which Sync Streams cannot compare. Kept permissions retain suspended memberships without widening other permissions' queries.

  • Under-sync, never over-sync. A device keeps synced rows offline, so a row the policy denies must never reach it. Every grant that does not compile is left out, deny grants drop the stream, and the server still decides every request (threat model). Tenant custom roles are the one exception: their deny rows live in a table the tenant edits, so a stream cannot subtract them, and the device applies them in can().

  • The database-mode tables, not the token. The sync service evaluates the queries when a row or membership changes, so a membership change re-syncs without a new token. A jwt-mode memberships claim is not compiled; it is planned.

  • One file, checked in. generate --check, verify and PD058 all compare the same bytes, so CI fails before a stale file is deployed.

  • Followed rows need their own fixtures. An attachment has no permission action of its own. Checking its parent with can() independently of the generated stream catches leaked child rows and wrong polymorphic kinds, rather than treating a stream query as proof of access.

Last updated on

On this page