# AccessNexus (npm: accessnexus) > Schema-first engine for Supabase. You describe tables, access rules (RLS), roles, > triggers and RPCs once in TypeScript (`accessnexus.schema.ts`); AccessNexus generates the > SQL migrations, Row-Level Security policies, triggers, Postgres functions and a typed > client SDK — with Supabase RLS best practices built in. This file is the complete > reference for AI coding agents. Package version: 0.4.4-next. Requires Node.js >= 20. ## How to read this file (index) Read "Mental model" and "Standard agent workflow" first; then only what the task needs: - Owner / public tables: §defineSchema + table, §policy.* builders, §Recipes (owner-only, public read). - Multi-tenant (orgs, teams, roles, invites): §definePermissions, §Multi-tenant building blocks, §trigger.* builders, §Recipes (multi-tenant, child of a tenant resource, required tenant column), §RLS rules agents must not break. - Changing a schema that already has data: §CLI reference (diff --against-db, migration), §Recipes (required column on a table with data). - Using the SDK in the app: §Generated SDK (errors: NOT_FOUND_OR_DENIED), §TanStack Query helpers. - Realtime / Edge Functions: §Realtime, §Edge Functions. - Testing RLS: §Testing RLS (accessnexus/testing, test-db), §How a denial shows. - An error code: §Troubleshooting by error code. ## Mental model (read first) - `accessnexus.schema.ts` is the single source of truth for the database. To add a table, column, policy, role rule, trigger or RPC: edit the schema, never SQL. - Everything under the output folders (default `generated/`) and the SDK files (`client.ts`, `types.ts`) is derived. Never hand-edit it — regenerate. - Every table gets Row-Level Security (ENABLE + FORCE). A table WITHOUT `policies` is deny-all for the API (anon and signed-in users get nothing; only the service role and SECURITY DEFINER code reach it) — `validate` warns `NO_POLICIES`. Every table the app reads or writes from the client needs policies. `enableRLS: false` turns RLS off (anyone with the anon key can read and write the table; `validate` warns `RLS_DISABLED`) — never use it unless the user asked for an open table. - `push` is the only command that touches the real database. Preview with `push --dry-run` and only push when the user asked for it. `push` refuses generated SQL that is out of date with the schema, and refuses pending migrations that drop tables/columns or change column types unless `--allow-destructive` is passed (ask the user first — that deletes data). It never runs the seed unless `--seed` is passed. - All commands are non-interactive when stdin is not a TTY, accept `--json`, and use exit codes 0 = ok, 1 = fixable error (read `error.hint`), 2 = AccessNexus bug. ## Standard agent workflow 1. Edit `accessnexus.schema.ts`. 2. `npx accessnexus validate --json` — fix every issue with `"severity": "error"` (each has `path` and `hint`); treat warnings as bugs unless deliberate (`RLS_DISABLED`, `PUBLIC_WRITE`, `USER_ROW_INSERT_OPEN`, `TENANT_PARENT_UNCHECKED`, ...). In manual mode TypeScript does not check column names inside `policy.*` / `definePermissions` (`policy.isOwner('usr_id')` compiles): `validate` does (`UNKNOWN_COLUMN`), so never skip it. 3. `npx accessnexus diff --json` — review the SQL that will change. Run it BEFORE generate: diff compares the schema with the files on disk, so right after `generate` it is empty. (`diff --check` exits 1 when generated files are stale; use it in CI.) 4. `npx accessnexus generate --json` — writes SQL + SDK; reports created/updated/unchanged. To review afterwards, use `git diff generated/`. 5. Before ANY push: `npx accessnexus diff --against-db --json` (or `push --dry-run --json`, which runs the same plan when a database URL is set). It rehearses the push against the live database in a rolled-back transaction and lists what would really change (tables, columns, policies, triggers, functions, grants) with `before`/`after`. Review `riskyChanges` with the user (volatility or `SET search_path` changes, widened policy roles, dropped policies, lost defaults, type changes, RLS disabled), plus `blockers` and `failed`. Then `npx accessnexus push --json` when asked. If `generate`/`diff`/`push` report `destructive` statements, tell the user what data would be lost; a rename should be a rename in the schema, not remove + add. New project: `npx accessnexus init --yes` (add `--no-introspect` to skip the database, or `--db-url ` to import existing tables, RLS policies and functions). In an empty folder `init --yes` first creates a minimal `package.json` (`"type": "module"`). ## Project files - `accessnexus.schema.ts` — `export default defineSchema({...})` (required). It may import sibling files (`import { cols } from './db/cols.js'`): schema, config and seed files are bundled with esbuild, which ships with accessnexus — no tsx/ts-node needed. The snippets here write relative imports with a `.js` extension (`'./accessnexus.schema.js'` resolves to `accessnexus.schema.ts`), which works with every `moduleResolution` (`bundler`, `node16`, `nodenext`); extensionless imports only typecheck under `bundler`. - `accessnexus.config.ts` — optional `export default defineConfig({...})` (paths, prefix). - `accessnexus.seed.ts` — optional `export default defineSeed(schema, {...})`. - `generated/migrations/` — `__init.sql`, `__changes.sql`, `.snapshot.json`. - `generated/policies/_rls.sql` (+ `generated/policies/realtime.sql` when the schema uses Realtime), `generated/triggers/
_triggers.sql`, `generated/rpcs/rpcs.sql`. - `supabase/functions/_shared/accessnexus.ts` (derived) and `supabase/functions//index.ts` (scaffolded once, then user code) when the schema declares Edge Functions. - `generated/sdk/` (or `output.sdk`) — `types.ts` + `client.ts` (derived, never edit). - The client wrapper `init` writes next to them (`index.ts`, or `server.ts` + `browser.ts` on Next.js) is YOUR file: `generate` never touches it; edit env var names freely. - Database URL for push/seed: `--url` (alias `--db-url`, the flag `init` uses), else `adapterOptions.dbUrlEnv`, else `ACCESSNEXUS_DB_URL`, `SUPABASE_DB_URL`, `DATABASE_URL` (`.env` and `.env.local` are loaded). For Supabase use the "Session pooler" connection string (Dashboard → Connect). - `push`/`seed` need the `pg` driver (optional peer dependency): `npm install -D pg`. - `push` must run as a role with BYPASSRLS — on Supabase the `postgres` user of the connection string. The generated SECURITY DEFINER helpers and the audit/soft-delete triggers rely on their owner bypassing RLS. ## defineSchema + table (manual mode) Columns are type strings; append `?` for nullable. The object form adds `default`, `unique`, `check`, `references`, `onDelete`. Table names and columns are lowercase snake_case (one leading `_` is allowed: `_internal`, `_pix_crc16`) and cannot be reserved SQL keywords (`order`, `user`, `group`, `limit`, ... → `orders`, `user_id`). `default` and `check` are RAW SQL, emitted verbatim: `default: 'now()'`, `default: '0'`, `default: 'false'`. A string or enum literal needs its own single quotes inside the JS string: `status: { type: "enum('todo','done')", default: "'todo'" }` — `default: 'todo'` would be `DEFAULT todo` (a column name) and `validate` reports `INVALID_DEFAULT`. ```ts // accessnexus.schema.ts import { defineSchema, policy, table, trigger } from 'accessnexus'; export default defineSchema({ profiles: table({ // Public profile only: the email stays in auth.users. Every signed-in user can read // this table, so never put private data (email, phone, address) in it. columns: { id: 'uuid', name: 'text', bio: 'text?', created_at: { type: 'timestamptz', default: 'now()' }, updated_at: 'timestamptz?', }, primaryKey: 'id', references: { id: 'auth.users.id' }, triggers: [trigger.updatedAt('updated_at')], policies: { select: policy.isAuthenticated(), // private columns? use policy.isOwner('id') insert: policy.isOwner('id'), update: policy.isOwner('id'), delete: policy.none(), }, }), posts: table({ columns: { id: 'uuid', author_id: 'uuid', title: 'text', status: "enum('draft','published')", tags: 'text[]?', deleted_at: 'timestamptz?', }, primaryKey: 'id', references: { author_id: 'profiles.id' }, indexes: [{ columns: ['author_id', 'status'] }], softDelete: 'deleted_at', policies: { // Soft-deleted rows stay readable through RLS: exclude them from the public branch // (see the soft-delete note under trigger.* builders). select: policy.any([ policy.isOwner('author_id'), policy.custom("status = 'published' AND deleted_at IS NULL"), ]), insert: policy.isOwner('author_id'), update: policy.isOwner('author_id'), delete: policy.isOwner('author_id'), }, }), }); ``` Column types: `uuid text varchar int smallint bigint serial float decimal numeric boolean json jsonb date timestamp timestamptz time text[] int[] uuid[]`, `numeric(p)` / `numeric(p,s)` (e.g. `'numeric(10,2)'`, no space) and `"enum('a','b')"`; add `?` for NULL. `float` is `DOUBLE PRECISION`; use `numeric(p,s)` for money. A `uuid` primary key defaults to `gen_random_uuid()`; a `bigint` one becomes an identity. Table options: `columns` (required), `primaryKey`, `compositePrimaryKey` (`['org_id', 'user_id']` → `PRIMARY KEY (org_id, user_id)`, instead of `primaryKey`; not with `softDelete`), `references` (`column: 'table.column'` or `'schema.table.column'`, e.g. `'auth.users.id'`), `onDelete` (per referencing column: `'cascade' | 'set null' | 'restrict' | 'no action'`), `policies` (`select`/`insert`/`update`/ `delete`), `triggers`, `indexes` (`{ columns, unique?, name? }`), `softDelete` (column; DELETE becomes `SET = NOW()` and the SDK hides deleted rows), `enableRLS` (only `false` matters: it turns RLS off and opens the table — never set it unless asked). Foreign keys default to `ON DELETE NO ACTION`: deleting a parent that still has children fails with a foreign key error. Say what should happen to the children: ```ts import { defineSchema, policy, table } from 'accessnexus'; export default defineSchema({ projects: table({ columns: { id: 'uuid', owner_id: 'uuid', name: 'text' }, primaryKey: 'id', references: { owner_id: 'auth.users.id' }, policies: { all: policy.isOwner('owner_id') }, // same rule for select/insert/update/delete }), tasks: table({ columns: { id: 'uuid', project_id: { type: 'uuid', references: 'projects.id', onDelete: 'cascade' }, // tasks go with the project assignee_id: 'uuid?', owner_id: 'uuid', }, primaryKey: 'id', references: { assignee_id: 'auth.users.id', owner_id: 'auth.users.id' }, onDelete: { assignee_id: 'set null' }, // table-level map works too policies: { select: policy.isOwner('owner_id'), insert: policy.isOwner('owner_id'), update: policy.isOwner('owner_id'), delete: policy.isOwner('owner_id') }, }), }); ``` `'set null'` needs a nullable column. `'cascade'` into a `softDelete` table is rejected (`CASCADE_INTO_SOFT_DELETE`): the soft delete would keep the children pointing at a deleted parent — use `'restrict'` and soft-delete the children first. Cascades run as the table owner (RLS does not stop them), so only cascade where deleting the parent should delete everything. ## Database mode (columns from Supabase types) If the project already has Supabase-generated `database.types.ts`, list only the tables to configure and omit `columns` (mode is detected when no table declares columns). AccessNexus then generates RLS, triggers, RPCs and the SDK, but no DDL migrations. ```ts import { defineSchema, policy, rpc } from 'accessnexus'; import type { Database } from './database.types.js'; export default defineSchema({ profiles: { policies: { // Each user reads only their own profile. Use policy.isAuthenticated() only when // the table holds no private columns (email, phone...): every account could list them. select: policy.isOwner('id'), update: policy.isOwner('id'), }, }, }, { rpcs: { get_stats: rpc() }, }); ``` ## policy.* builders One rule per operation. `select`/`delete` compile to `USING` (which rows are visible / deletable); `insert` to `WITH CHECK` (what may be written); `update` to `USING` (which rows may be targeted) plus an explicit `WITH CHECK` with the same rule (what the row may become), so an update can never move a row out of the rule. An operation without a rule is denied once the table has policies. String values in rules are quoted safely. `all` as a policies KEY applies one rule to all four operations; explicit keys override it: `policies: { all: policy.isOwner('user_id'), delete: policy.none() }`. It expands at definition time into the usual one-policy-per-operation (`_
_`, never `FOR ALL`), with the USING / WITH CHECK split above, and every `validate` warning applies per operation (`all: policy.public()` → `PUBLIC_WRITE` on insert/update/delete). A key set to `undefined` does not override — use `policy.none()` to block one operation. Not to be confused with the `policy.all([...])` combinator (AND of rules); both combine: `{ all: policy.all([a, b]) }`. Policy target role (`TO ...`): a `select` policy is granted `TO public` when some branch can be true for an anonymous visitor (`policy.public()`, `policy.custom(...)`, a column-to-column `matchesField`), else `TO authenticated`. Writes are `TO public` only when an explicit `policy.public()` decides them. The predicate always decides; you never set the role. ```ts import { policy } from 'accessnexus'; // (SELECT auth.uid()) IS NOT NULL export const signedIn = policy.isAuthenticated(); // TRUE — everyone, including anonymous visitors (use for reads only) export const everyone = policy.public(); // FALSE — nobody through the API (service role and triggers bypass) export const nobody = policy.none(); // (SELECT auth.uid()) = user_id — the column must be uuid export const owner = policy.isOwner('user_id'); // ((SELECT auth.jwt()) -> 'app_metadata' ->> 'role') = 'admin' — GLOBAL app role, see below export const platformAdmin = policy.hasRole('admin'); // org_id IN (membership via a SECURITY DEFINER helper on org_members) export const member = policy.belongsTo('org_id', { table: 'org_members', foreignKey: 'org_id', localKey: 'user_id', }); // same, restricted to members whose role column is admin or manager export const orgAdmin = policy.belongsTo('org_id', { table: 'org_members', foreignKey: 'org_id', localKey: 'user_id', where: { role: ['admin', 'manager'] }, }); // author_id = (SELECT auth.uid()) — either side may be a column or an auth call export const sameUser = policy.matchesField('author_id', 'auth.uid()'); // raw SQL predicate — always write (SELECT auth.uid()), never bare auth.uid() export const published = policy.custom("status = 'published'"); // OR / AND export const ownerOrPublished = policy.any([policy.isOwner('user_id'), published]); export const ownerAndUnlocked = policy.all([policy.isOwner('user_id'), policy.custom('locked = false')]); // USING = first rule; WITH CHECK = first AND second rule (the written row must pass both) export const editOwn = policy.withCheck(policy.isOwner('author_id'), policy.custom('edited = true')); // { mode: 'replace' }: WITH CHECK = second rule only (the row may leave the first rule) export const publishDraft = policy.withCheck( policy.all([policy.isOwner('author_id'), policy.custom("status = 'draft'")]), policy.all([policy.isOwner('author_id'), policy.custom("status IN ('draft', 'published')")]), { mode: 'replace' }, ); ``` `belongsTo(column)` without `through` checks `profiles.` of the current user (needs a `profiles` table with that column). Avoid it: it is only safe when users can NEVER write that column — no `insert` policy on profiles (create profiles from an auth trigger or the service role) and `trigger.lockColumns({ columns: ['org_id'] })` on profiles. Otherwise a user sets their own `profiles.org_id` to another tenant's id and joins it; `validate` rejects that with `BELONGS_TO_PROFILE_WRITABLE`. Use a membership table (`through`) instead. With `through`, the membership lookup is a generated `SECURITY DEFINER` function with `SET search_path = pg_catalog, public` (no RLS recursion, safe on the membership table itself). `policy.sharesTenant(column, { table, userColumn, tenantColumn })` — the row's user (`column`, a user id) shares at least one tenant with the current user; e.g. profiles visible to co-members: `select: policy.any([policy.isOwner('id'), policy.sharesTenant('id', { table: 'org_members', userColumn: 'user_id', tenantColumn: 'org_id' })])`. Generates a SECURITY DEFINER STABLE helper (like `belongsTo`): never write a membership subquery in `policy.custom` for this. Global vs tenant roles — pick the right one: - Role INSIDE an org/team/workspace ("org admins can delete"): store it in the membership table and use `{ scope: 'tenant', roles: ['admin'] }` in `definePermissions`, or `policy.belongsTo(col, { ..., where: { role: ['admin'] } })`. - Platform-wide role ("our staff can read the audit log"): `policy.hasRole('admin')` or a role array `['admin']` in `definePermissions`. Both read the JWT `app_metadata.role` claim, which only the server can set: `supabase.auth.admin.updateUserById(id, { app_metadata: { role: 'admin' } })` (service role) or a custom access token hook. The top-level JWT `role` claim is never used (it is the Postgres role `authenticated`). `validate` warns with `GLOBAL_ROLE_IN_TENANT_TABLE` when a table mixes both. ## definePermissions (centralized RBAC, multi-tenant) Actions map `read→select`, `create→insert`, `update→update`, `delete→delete`. Levels: `'public'`, `'*'` (any signed-in user), `'none'`, `'own'` (needs `ownerColumn`), a role array (GLOBAL app roles from `app_metadata.role`, see above), `{ scope: 'tenant' }` (member of the row's tenant, needs `tenant` and `tenantColumn`), `{ scope: 'tenant', roles: [...] }` (member with one of those roles, needs `tenant.roleColumn`), `{ any: [...] }` (OR), `{ all: [...] }` (AND, e.g. `delete: { any: [{ scope: 'tenant', roles: ['owner', 'admin'] }, { all: ['own', { scope: 'tenant', roles: ['member'] }] }] }`: members delete only their own rows, and a member demoted to viewer loses even that). Unknown roles throw at definition time. `all: ` fills every action without its own level (`{ ownerColumn: 'user_id', all: 'own', read: '*' }`); the write pins below apply to the expanded `create`/`update` as if written out. Writes are pinned by default (secure unless you opt out): - `create` also requires `ownerColumn = (SELECT auth.uid())` — nobody can create rows attributed to someone else. Opt out with `pinOwnerOnCreate: false` when others assign the owner column (e.g. a task's `assignee_id`); pin the real creator column yourself then. - `update`, and `create` when its level is not already tenant-scoped, also require that the user is a member of the row's (new) tenant — an owner cannot move a row into another org. Not applied to `create` when `tenantColumn` is `'id'` (the row is the tenant itself). Opt out with `pinTenant: false` for resources written by non-members (customers booking into a shop). ```ts import { definePermissions } from 'accessnexus'; export const permissions = definePermissions({ roles: ['owner', 'editor', 'viewer'], tenant: { table: 'team_members', userColumn: 'user_id', tenantColumn: 'team_id', roleColumn: 'role' }, resources: { documents: { ownerColumn: 'created_by', tenantColumn: 'team_id', read: { scope: 'tenant' }, create: { scope: 'tenant', roles: ['owner', 'editor'] }, // + created_by = auth.uid() update: { any: ['own', { scope: 'tenant', roles: ['owner'] }] }, // + stays in a team you belong to delete: { scope: 'tenant', roles: ['owner'] }, }, }, }); // On the table: policies: permissions.policiesFor('documents') // One rule: permissions.can('documents', 'update') export const documentPolicies = permissions.policiesFor('documents'); export const canUpdate = permissions.can('documents', 'update'); ``` ## trigger.* builders ```ts import { trigger } from 'accessnexus'; // BEFORE UPDATE: sets updated_at = NOW() export const touch = trigger.updatedAt('updated_at'); // BEFORE DELETE: sets deleted_at = NOW() and cancels the delete // (table option softDelete: 'deleted_at' adds this automatically) export const softDelete = trigger.softDelete('deleted_at'); // AFTER INSERT/UPDATE/DELETE: inserts into audit_log (see the audit-log recipe) export const audit = trigger.auditLog({ table: 'audit_log' }); // BEFORE UPDATE: API users cannot change these columns (RLS is row-level, not column-level) export const freezeOwner = trigger.lockColumns({ columns: ['owner_id', 'org_id'] }); // Lock every column except status/position, unless the SQL condition holds (NEW/OLD available) export const statusOnly = trigger.lockColumns({ name: 'assignee_scope', // needed when a table has two lockColumns triggers except: ['status', 'position'], unless: "EXISTS (SELECT 1 FROM org_members m WHERE m.org_id = OLD.org_id AND m.user_id = (SELECT auth.uid()) AND m.role = 'admin')", }); // Custom PL/pgSQL; events: before_/after_ + insert/update/delete; forEach: 'row' | 'statement' export const lowerEmail = trigger.custom({ name: 'lowercase_email', events: ['before_insert', 'before_update'], when: 'NEW.email IS NOT NULL', functionBody: 'NEW.email = lower(NEW.email); RETURN NEW;', }); // security: 'definer' runs as the owner and bypasses RLS — only for trusted side effects export const addCreator = trigger.custom({ name: 'add_creator_as_owner', events: ['after_insert'], security: 'definer', functionBody: "INSERT INTO public.team_members (team_id, user_id, role) VALUES (NEW.id, NEW.created_by, 'owner'); RETURN NEW;", writes: ['team_members'], // React Query: teams.create() also refreshes team_members }); // The last owner of a team cannot leave or be demoted; deleting the team still cascades. // SECURITY DEFINER, rows of the scope locked during the check; SQLSTATE 23514. export const keepOwner = trigger.keepAtLeastOne({ column: 'role', value: 'owner', scope: 'team_id', parent: 'teams.id' }); // Foreign keys ignore RLS: project_id must be a project of the SAME team (NULL allowed); 23503. export const sameTeam = trigger.sameTenant({ column: 'project_id', references: 'projects', tenantColumn: 'team_id' }); // assignee_id must be a member of the row's team (NULL allowed); 23503. export const assigneeIsMember = trigger.memberOfTenant({ column: 'assignee_id', tenant: { table: 'team_members', userColumn: 'user_id', tenantColumn: 'team_id' }, }); // On the profiles table: a row per new auth user (AFTER INSERT ON auth.users, definer, ON CONFLICT DO NOTHING). export const profileOnSignUp = trigger.onAuthUserCreated({ columns: { id: 'NEW.id', display_name: "split_part(NEW.email, '@', 1)" }, }); ``` `sameTenant` / `memberOfTenant` run as the writer (INVOKER): a row they cannot see counts as missing, so they never reveal other tenants' ids. `validate` warns `TENANT_PARENT_UNCHECKED` for a tenant row pointing at another tenant-scoped table without `sameTenant` on that column. `trigger.auditLog` and `trigger.softDelete` functions are `SECURITY DEFINER` with `SET search_path = pg_catalog, public` and schema-qualified targets: the audit table keeps `insert: policy.none()` (users cannot forge entries). A soft delete is authorized by the DELETE policy: the generated guard rejects any plain UPDATE by an API user that sets or clears the soft-delete column (so the UPDATE policy cannot be used to soft-delete or restore); restore rows with the service role or a `security: 'definer'` RPC. `trigger.lockColumns` raises SQLSTATE 42501 when a locked column changes (message `
. cannot be changed`, HINT `accessnexus:locked_column:
.`, so the SDK's `isLockedColumn(error)` tells it from an RLS denial); it never blocks the service role, SECURITY DEFINER code or columns kept by `trigger.updatedAt`. `updatedAt`, `lockColumns` and `trigger.custom` run as the writing user (INVOKER, RLS applies to what they read/write) unless `security: 'definer'`. In a definer body schema-qualify tables (`public.team_members`). Soft-deleted rows stay visible through RLS (only the SDK filters them). To hide them from raw API reads too, add the condition to `select`, e.g. `policy.all([policy.isOwner('author_id'), policy.custom('deleted_at IS NULL')])`. ## Multi-tenant building blocks (defineEnum, tenantInvitations) `defineEnum(name, values)` declares ONE Postgres enum shared by columns and RPCs (no casts between per-column `enum(...)` types). Register it in `defineSchema(tables, { enums: [e] })`; use `e.type` / `e.nullable` (the strings `'enum:'` / `'enum:?'`) as column types, RPC `args` and `returns.table` types. The SDK types it as a union and `Database['public'] ['Enums'][]`. RPC types may also be `'table.column'` (that column's type, enum union included). `validate`: `UNKNOWN_ENUM` for an undeclared name. `tenantInvitations({ tenant, tenantTable, tenantNameColumn?, roles, inviterRoles, requireConfirmedEmail? = true, table? = 'invitations', rpcNames? })` returns `{ table, rpcs }`: - table `invitations(id, , email, role, invited_by, created_at)`, unique (tenant, email). Policies: inviters (keys of `inviterRoles`) insert invites in their own name for the roles they may hand out, read and revoke their tenant's invites; the invitee (JWT e-mail) reads and declines theirs; nobody updates. - `accept_invitation(p_invitation uuid) → uuid` (definer): signed-in, e-mail confirmed (`auth.users.email_confirmed_at`), matching e-mail → joins with the invited role, consumes the invite, returns the tenant id. Errors: 42501 (anon / unconfirmed), P0002 (not found). - `my_invitations()` (definer, stable): the caller's invites with `tenant_name` (rename it with `tenantNameAlias: 'org_name'` to keep an existing RPC's result shape; they cannot read the tenant yet). ```ts import { defineEnum, defineSchema, policy, table, tenantInvitations } from 'accessnexus'; export const memberRole = defineEnum('member_role', ['owner', 'admin', 'member', 'viewer']); const invites = tenantInvitations({ tenant: { table: 'org_members', userColumn: 'user_id', tenantColumn: 'org_id', roleColumn: 'role' }, tenantTable: 'orgs', tenantNameColumn: 'name', roles: memberRole, inviterRoles: { owner: ['admin', 'member', 'viewer'], admin: ['member', 'viewer'] }, }); export default defineSchema({ orgs: table({ columns: { id: 'uuid', name: 'text' }, primaryKey: 'id', policies: { select: policy.isAuthenticated() } }), org_members: table({ columns: { id: 'uuid', org_id: 'uuid', user_id: 'uuid', role: { type: memberRole.type, default: "'member'" } }, primaryKey: 'id', references: { org_id: 'orgs.id', user_id: 'auth.users.id' }, indexes: [{ columns: ['org_id', 'user_id'], unique: true }], policies: { select: policy.isOwner('user_id'), insert: policy.none() }, }), invitations: invites.table, }, { enums: [memberRole], rpcs: { ...invites.rpcs } }); ``` A complete multi-tenant schema built from these pieces (and its RLS test suite) ships in the repository as `examples/saas-teams/` (it imports `'accessnexus'`: copy it as is). ## rpc (Postgres functions) Pass RPCs as the second argument of `defineSchema`. With a `body`, AccessNexus emits `CREATE OR REPLACE FUNCTION` (defaults: `plpgsql`, `SECURITY INVOKER`, volatile, pinned `search_path`, returns `void` when `returns` is omitted) and a typed `client.rpc.()`. `rpc({ args, returns })` without body only types the client (no SQL); `rpc()` is a marker for Database mode. `returns` is a column type, `'void'`, `{ table: { col: 'type', ... } }` (→ `RETURNS TABLE(...)`, SDK `Returns: { col: T; ... }[]` like `supabase gen types`; `'text?'` → `string | null`) or `{ setof: 'table_name' }` (→ `RETURNS SETOF table_name`, SDK `Returns: Row[]` of that table) / `{ setof: 'uuid' }` (a column type → `string[]`). Without `returns` the SDK type is `unknown`. Bad shapes are `INVALID_RPC_RETURNS`. Postgres cannot change a function's result type or argument names with `CREATE OR REPLACE`, so each generated function is preceded by a guard that `DROP FUNCTION`s it (no CASCADE) when they differ; an unchanged function is never dropped. It runs inside push's transaction: if a policy, view or function depends on it the DROP fails and nothing is applied (change the dependent first, or give the new version another name); the live plan reports it as a changed function (`returns`), not a drop. Changing argument types creates a new overload (the old one stays). `security: 'definer'` bypasses RLS — check `(SELECT auth.uid())` yourself (and reject anonymous callers). For definer RPCs AccessNexus revokes EXECUTE from `PUBLIC` and `anon` and grants it to `authenticated` and `service_role`; pass `allowAnon: true` to keep anon. Invoker RPCs keep Supabase's default (callable by `anon` and `authenticated`; RLS applies inside). `validate` warns `UNWRAPPED_AUTH_CALL` for a bare `auth.uid()` in a body. An argument is a type or `{ type, default }` with a raw SQL default (`args: { p_limit: { type: 'int', default: '20' } }` → `p_limit INTEGER DEFAULT 20`; callers may omit it, the client type marks it optional). After one argument with a default, every following one needs a default too (`INVALID_DEFAULT`). `volatility: 'volatile' | 'stable' | 'immutable'` (default volatile; `immutable: true` is an alias, a contradicting pair is `RPC_VOLATILITY_CONFLICT`). Declare read-only helpers used in RLS policies `'stable'`: a VOLATILE function in a policy is re-evaluated per row instead of once per query. `set: { row_security: 'off', work_mem: '64MB' }` emits `SET key = 'value'` (keys must be GUC names, values strings, `INVALID_FUNCTION_SET` otherwise). `search_path` is always pinned to `pg_catalog, public`; a different `set.search_path` is ignored (`SEARCH_PATH_PINNED` warning). `trigger.custom` accepts the same `set`. ```ts import { defineSchema, policy, rpc, table } from 'accessnexus'; export default defineSchema({ todos: table({ columns: { id: 'uuid', user_id: 'uuid', done: 'boolean' }, primaryKey: 'id', references: { user_id: 'auth.users.id' }, policies: { select: policy.isOwner('user_id'), insert: policy.isOwner('user_id'), update: policy.isOwner('user_id'), delete: policy.isOwner('user_id'), }, }), }, { rpcs: { count_open_todos: rpc({ returns: 'int', language: 'sql', body: 'SELECT count(*)::int FROM todos WHERE user_id = (SELECT auth.uid()) AND NOT done;', }), complete_all: rpc({ args: { p_user: 'uuid' }, body: 'UPDATE todos SET done = true WHERE user_id = p_user AND p_user = (SELECT auth.uid());', }), my_todo_counts: rpc({ returns: { table: { done: 'boolean', total: 'int' } }, // SDK: { done: boolean; total: number }[] language: 'sql', volatility: 'stable', body: 'SELECT done, count(*)::int FROM todos WHERE user_id = (SELECT auth.uid()) GROUP BY done;', }), open_todos: rpc({ returns: { setof: 'todos' }, // SDK: Row[] of todos language: 'sql', volatility: 'stable', body: 'SELECT * FROM todos WHERE user_id = (SELECT auth.uid()) AND NOT done;', }), reset_my_todos: rpc({ security: 'definer', // bypasses RLS: check the caller first body: `IF (SELECT auth.uid()) IS NULL THEN RAISE EXCEPTION 'sign in first' USING ERRCODE = '42501'; END IF; DELETE FROM public.todos WHERE user_id = (SELECT auth.uid());`, }), }, }); ``` ## Realtime (Postgres Changes, Broadcast, Presence) - Table option `realtime: true` adds the table to the `supabase_realtime` publication (push applies `generated/policies/realtime.sql`); `realtime: false` removes it; leaving the key out leaves the publication alone (dashboard settings survive). Realtime delivers a row change only to users whose SELECT policy shows the row. `{ replicaIdentity: 'full' }` only helps on `enableRLS: false` tables: with RLS, `old` holds just the primary key anyway. - Supabase does NOT apply RLS to DELETE events: every subscriber of a published table gets them, with the primary key only. Filters do not apply to DELETE either. - `defineSchema(tables, { channels: { : channel({...}) } })` declares PRIVATE Broadcast/Presence channels; each rule becomes an RLS policy on `realtime.messages` (`receive` = SELECT, `send` = INSERT), named `_rt___`. Push drops `_rt_*` policies the schema no longer declares and never touches others; `channels: {}` removes all of them. - `topic`: fixed (`'lobby'`) or prefix + one trailing parameter (`'project:{id}'`). With `table: 'projects'` the parameter is that table's primary key and EVERY rule also requires that the user can SELECT that row (checked as the user, so the table's RLS decides; a malformed key is denied, not an error). - Rules: `true` (any signed-in user), `false`/omitted/`policy.none()` (nobody), `policy.isAuthenticated()`, `policy.public()` (anon too), `policy.hasRole(role)`, `policy.custom(sql)` (`{param}` = topic parameter as text, `realtime.topic()` = whole topic), `policy.any`/`policy.all`. Row rules (`isOwner`, `belongsTo`, `matchesField`, `withCheck`) are rejected (`CHANNEL_RULE_NOT_SUPPORTED`). ```ts import { channel, defineSchema, policy, table } from 'accessnexus'; export default defineSchema({ projects: table({ columns: { id: 'uuid', owner_id: 'uuid', name: 'text' }, primaryKey: 'id', policies: { select: policy.isOwner('owner_id'), insert: policy.isOwner('owner_id') }, realtime: true, // client.projects.subscribe(...) }), }, { channels: { project_room: channel({ // client.channels.project_room(projectId) topic: 'project:{id}', table: 'projects', // only users who can read that project row broadcast: { receive: true, send: true }, presence: { receive: true, send: true }, }), announcements: channel({ // client.channels.announcements() topic: 'announcements', broadcast: { receive: policy.public(), send: policy.hasRole('admin') }, }), inbox: channel({ // client.channels.inbox(userId) topic: 'inbox:{user_id}', broadcast: { receive: policy.custom('{user_id} = (SELECT auth.uid())::text') }, }), }, }); ``` SDK: `client.
.subscribe(listener, { event?, filter?, onStatus? })` (realtime tables only) returns an unsubscribe function; `change` is typed from the row (`eventType`, `new`, `old` = primary key). `event: 'INSERT'|'UPDATE'|'DELETE'|'*'` narrows `change`. `filter` names exactly ONE column (Realtime limit): `{ project_id: id }` (eq), `{ status: ['a','b'] }` (in), `{ views: { gt: 10 } }` (`eq|neq|lt|lte|gt|gte|in`); two columns or `null` throw. `client.channels.(param)` returns the supabase-js `RealtimeChannel` created with `{ config: { private: true } }` — use `.on('broadcast'|'presence', ...)`, `.subscribe()`, `.send()`, `.track()`, `supabase.removeChannel(ch)`. A provider without `channel` throws. `init --db-url` imports published tables as `realtime: true` and lists (does not import) existing `realtime.messages` policies. ## Edge Functions (typed, validated handlers) `defineSchema(tables, { functions: { '': edgeFunction({ auth, input, output }) } })`. `generate` writes (folder `output.functions`, default `./supabase/functions`): - `_shared/accessnexus.ts` (DERIVED — never edit): per function `Input`, `Output` and a wrapper `(handler)` built on `withSupabase` from `npm:@supabase/server@1`: it rejects callers without the credential `auth` requires (401), answers CORS, requires POST + a JSON object of exactly the `input` fields (400 `invalid_json` / `invalid_input` with `issues[]`), then calls `handler(input, ctx, req)`. `ctx.supabase` runs AS THE CALLER (RLS applies); `ctx.supabaseAdmin` bypasses RLS (filter by `ctx.userClaims` yourself). Return the output (JSON; nothing → 204) or a `Response`; `throw new FunctionError(status, code, message)`; other exceptions → 500 with a generic message. - `/index.ts` scaffold, written ONCE when missing (answers 501); then it is the user's code. - `supabase/config.toml` (only if it exists): managed block `[functions.] verify_jwt = ...` (`false` only when `auth` accepts `'none'`); the rest of the file is untouched. Deploy with `supabase functions deploy` (push never deploys). - `auth`: `'user'` (default; signed-in JWT), `'publishable'`, `'secret'` (servers/cron), `'none'` (anyone — webhooks verifying their own signature; `validate` warns `EDGE_FUNCTION_PUBLIC`), or an array (`'none'` last). - `input`: field → column type (`'uuid'`, `'text?'`, `"enum('a','b')"`, `'varchar(20)'`, `'jsonb'`, `'int[]'`, ...; `?` = optional/nullable). `{}` = empty body. OMITTED = body left unread for the handler (`input` is undefined; read `await req.text()`, e.g. webhook signatures). - `output`: fields, one column type, or `'void'`; omitted = unknown. - Names: lowercase letters/digits joined by `-` or `_` (`invite-member`); SDK/wrapper name is camelCase (`inviteMember`). ```ts import { defineSchema, edgeFunction, policy, table } from 'accessnexus'; export default defineSchema({ invitations: table({ columns: { id: 'uuid', org_id: 'uuid', email: 'text' }, primaryKey: 'id', policies: { select: policy.isAuthenticated(), insert: policy.isAuthenticated() }, }), }, { functions: { 'invite-member': edgeFunction({ auth: 'user', input: { org_id: 'uuid', email: 'text', role: "enum('admin','member')", message: 'text?' }, output: { invitation_id: 'uuid' }, }), 'stripe-webhook': edgeFunction({ auth: 'none', output: 'void' }), // reads the raw body itself }, }); ``` Implement `supabase/functions/invite-member/index.ts`: `export default { fetch: inviteMember(async (input, ctx) => { ...; return { invitation_id } }) }` (import `{ FunctionError, inviteMember } from '../_shared/accessnexus.ts'`). SDK: `db.functions.inviteMember(input, { headers?, region? }?)` → `{ data: Output | null, error }` via `supabase.functions.invoke(name, { body, method: 'POST' })` (sends the user's JWT); on failure `await error.context.json()` is `{ error: { code, message, issues? } }`. React Query: `q.functions..query(input)` / `.mutation()` (invalidates every query). ## defineSeed ```ts // accessnexus.seed.ts — applied by `accessnexus seed` or `accessnexus push --seed` (never implicitly) import { defineSeed } from 'accessnexus'; import schema from './accessnexus.schema.js'; export default defineSeed(schema, { profiles: [ { id: '00000000-0000-0000-0000-000000000001', name: 'Admin' }, ], }); ``` Database mode: `defineSeed({ table: [rows] })`. Rows whose columns reference `auth.users.id` provision those users in `auth.users` (email confirmed) with a random, unknowable password — set `ACCESSNEXUS_SEED_PASSWORD` to log in as them locally. Seeding a hosted Supabase database (`*.supabase.co` / `*.supabase.com`) is refused without `--allow-remote-seed`. Seeds upsert by primary key, so re-running is safe. ## defineConfig ```ts // accessnexus.config.ts — every field optional import { defineConfig } from 'accessnexus'; export default defineConfig({ schema: './accessnexus.schema.ts', seed: './accessnexus.seed.ts', output: { dir: './generated', // base for the folders below migrations: './supabase/migrations', sdk: './src/lib/accessnexus', // where the app imports the client from functions: './supabase/functions', // Edge Functions (default; deployed by the Supabase CLI) }, naming: { policyPrefix: 'app' }, // policy names: _
_ generate: { sqlOnly: false, sdkOnly: false }, adapterOptions: { dbUrlEnv: 'SUPABASE_DB_URL', // env var push/seed read the DB URL from deterministic: true, // omit the "Generated at" header line reactQuery: true, // also emit /react-query.ts (TanStack Query v5) uuidGeneration: 'v7', // time-ordered uuid PKs via public.accessnexus_uuidv7() }, targets: { // push/seed --target staging: { adapter: 'supabase', adapterOptions: { dbUrlEnv: 'STAGING_DB_URL' } }, }, }); ``` `uuidGeneration: 'v7'`: migrations define `public.accessnexus_uuidv7()` (RFC 9562 UUIDv7: 48-bit millisecond timestamp, version 7, random tail) before the first table that uses it. EXECUTE is revoked from `PUBLIC` and `anon` (so PostgREST does not expose it to anonymous callers) and granted to `authenticated` and `service_role`; `anon` gets it only when a v7 table's insert policy lets anonymous users write. There is no `uuid_generate_v7()`. ## SupabaseAdapter (programmatic generation) Pure functions returning `{ path, content }`; the CLI uses them. Useful in tests. ```ts import { SupabaseAdapter } from 'accessnexus'; import schema from './accessnexus.schema.js'; const adapter = new SupabaseAdapter({ policyPrefix: 'accessnexus', deterministic: true }); const policies = adapter.generatePolicies(schema); //
_rls.sql const triggers = adapter.generateTriggers(schema); //
_triggers.sql const migration = adapter.generateMigrations(schema); // 001_initial.sql (full DDL) const rpcs = adapter.generateRpcs(schema); // rpcs.sql const sdk = adapter.generateClient(schema); // types.ts + client.ts (+ react-query.ts) export const files = [...policies, ...triggers, ...migration, ...rpcs, ...sdk].map((f) => f.path); ``` ## Generated SDK `createAccessNexusClient(supabase)` wraps a supabase-js client (`createClient`, or `createBrowserClient`/`createServerClient` from @supabase/ssr) with typed per-table accessors: `findMany(filter?, { columns?, include? })`, `findOne(filter, { columns?, include? })`, `findById(id, { columns?, include? })`, `create(row)`, `update(id, patch)`, `delete(id)` (a real DELETE; on soft-delete tables the trigger sets the column instead, so the DELETE policy decides), `updateOne(filter, patch, { columns? })`, `updateMany(filter, patch, { columns? })`, `deleteOne(filter, { columns? })`, `deleteMany(filter, { columns? })`, plus `rpc.(args)` and `auth`. Results are `{ data, error }` like supabase-js. Realtime tables also get `subscribe(...)` and declared channels `channels.(param)` (see Realtime above); declared Edge Functions are `functions.(input)` (see Edge Functions above). - NO SILENT DENIALS: `update(id)`, `delete(id)`, `updateOne` and `deleteOne` return `error.code === 'ACCESSNEXUS_NOT_FOUND_OR_DENIED'` (`{ code, message, details: { table, method, id | filter }, hint }`) when no row was changed — the row does not exist, or RLS hides it / does not let this user change it. `delete(id)` counts affected rows; on a softDelete table it checks the live row before and after (gone = deleted). Helpers exported by client.ts: `isNotFoundOrDenied(error)`, `isAccessDenied(error)` (that, or SQLSTATE 42501: INSERT/WITH CHECK rejected, definer RPC check), `isLockedColumn(error)` (trigger.lockColumns), `NOT_FOUND_OR_DENIED`. `updateMany`/`deleteMany` still return `[]` when nothing matches. - `updateOne` = `.update(patch).match(filter).select(columns).maybeSingle()`: one round trip — update by any unique column (`{ slug }`); more than one match is PGRST116 and nothing is written. `updateMany` returns `Row[]`. `deleteOne`/`deleteMany` return the deleted rows (DELETE ... RETURNING, so only rows the SELECT policy shows); on a softDelete table `deleteOne` returns the row as it was, `deleteMany` returns `[]` (the trigger turns the DELETE into an UPDATE). On softDelete tables all four touch live rows only. The filter is REQUIRED: keys must be columns and values their types, `{}` does not compile (`RowFilter`), and an empty filter (or all values `undefined`) throws `[AccessNexus]
.: the filter must name at least one column` before any request. - `findOne` = `.match(filter).maybeSingle()`, `findById` = `.eq(pk, id).maybeSingle()`: a missing/invisible row is `{ data: null, error: null }` (not an error); more than one `findOne` match is an error (PGRST116), so filter on a unique column. - `columns: ['id', 'name']` sends `select('id, name')` and types the rows as `Pick`; unknown column names do not compile. Empty array = `*`. - `include` embeds tables declared in `references` (combines with `columns`). - `auth` is typed as the provider's own `auth` (`TClient['auth']`), so `db.auth.signInWithOAuth(...)` typechecks. Name the client type with `AccessNexusClient>` (bare `AccessNexusClient` has `auth: unknown`). - `json`/`jsonb` are typed `Json` (exported; identical to Supabase's `Json`). Manual-mode row types are type aliases matching `supabase gen types` for the same table (assignable both ways); in Database mode Row/Insert/Update are your `Database['public']['Tables'][t]` types. RLS still applies: the SDK runs as the signed-in user. `
Create` types make nullable columns, columns with a `default` and an auto-generated (uuid/bigint) primary key optional; everything else is required. ```ts import { createClient } from '@supabase/supabase-js'; import { createAccessNexusClient } from './generated/sdk/client.js'; const db = createAccessNexusClient(createClient('https://xyz.supabase.co', 'public-anon-key')); export async function example(userId: string) { const { data: me } = await db.profiles.findById(userId); // null when missing const { data: owner } = await db.profiles.findOne({ email: 'owner@example.com' }, { columns: ['id', 'name'] }); const { data: projects } = await db.projects.findMany({ org_id: 'some-org-id' }, { include: { org: true } }); await db.profiles.update(userId, { name: 'New name' }); const { data: renamed } = await db.projects.updateOne({ id: 'some-project-id', org_id: 'some-org-id' }, { name: 'Renamed' }, { columns: ['id', 'name'] }); const { data: stats } = await db.rpc.get_org_dashboard({ p_org_id: 'some-org-id' }); return { me, owner, projects, renamed, stats }; } ``` ### TanStack Query helpers (adapterOptions.reactQuery: true) `generate` also writes `/react-query.ts` (needs `@tanstack/react-query` v5 in the app; same file in manual and Database mode). `createAccessNexusQueries(client, { queryClient? })`: - `q.
.findMany|findOne|findById(...)` → `queryOptions({ queryKey, queryFn })`, same args/generics as the client (`columns`/`include` narrow `data`). Use with `useQuery`, `useSuspenseQuery`, `prefetchQuery`, `getQueryData(opts.queryKey)`. - `q.
.create|update|delete|updateOne|updateMany|deleteOne|deleteMany()` → mutation options. Variables: `create(row)`, `update({ id, data })`, `delete(id)`, `updateOne|updateMany({ filter, data })`, `deleteOne|deleteMany(filter)`. - `q.rpc..query(args)` (read) / `q.rpc..mutation()` (write). - `queryFn`/`mutationFn` throw the Supabase error object as-is (PostgrestError: `code`, `message`); lists resolve to `[]`, findOne/findById to `null` when no visible row. - With `queryClient`, mutations invalidate on success: the table + tables that embed it via `include`; RPC mutations invalidate everything (`accessNexusKeys.all` = `['accessnexus']`). Without it, nothing is invalidated. Keys: `accessNexusKeys.
.all|list|one|byId`. - Extend by spreading: `useQuery({ ...q.tasks.findById(id), enabled: !!id })`. A spread `onSuccess` replaces the generated invalidation. ```tsx import { QueryClient, useMutation, useQuery } from '@tanstack/react-query'; import { createAccessNexusQueries } from './generated/sdk/react-query.js'; import { accessnexus } from './generated/sdk/index.js'; const q = createAccessNexusQueries(accessnexus, { queryClient: new QueryClient() }); const tasks = useQuery(q.tasks.findMany({ project_id: projectId }, { include: { project: true } })); const create = useMutation(q.tasks.create()); // RETURNS TABLE / SETOF rpcs: data is Row[] (never null) // realtime tables: refresh queries on every change (returns the unsubscribe) useEffect(() => q.tasks.invalidateOnChange({ filter: { project_id: projectId } }), [projectId]); ``` ## CLI reference `npx accessnexus [flags]`; `npx accessnexus --help` lists flags. Flags on every command: `--json` (one JSON object on stdout, nothing else; colors off — also for `help --json` and ` --help --json`), `--verbose` (debug + stack traces; same as `DEBUG=accessnexus`), `--config `. Unknown flags and commands are errors (with a did-you-mean hint), never ignored. Colors are disabled when stdout is not a TTY or `NO_COLOR` is set. - `init` — scaffold AccessNexus in any Node project (Next.js app/pages, Vite with any framework, CRA, or a plain Node/other project): schema (template or imported from the DB), `accessnexus.config.ts`, SDK wrappers reusing an existing Supabase client, a `accessnexus` npm script, and a AccessNexus block in `AGENTS.md` (plus a pointer in `CLAUDE.md` if present). Without a TTY it requires `--yes`. Flags: `--yes`/`-y`, `--src `, `--sdk ` (default `/lib/accessnexus`), `--prefix `, `--db-url `, `--no-introspect`, `--install` (install missing @supabase packages), `--force` (overwrite an existing schema), `--no-agents`. Re-running is safe: an existing schema is kept (unless `--force`) and the AGENTS.md block is replaced in place. With `--yes` in a folder without `package.json` it creates a minimal one. `--db-url` imports each policy without ever granting more than the database did: policies for non-API roles (`TO service_role`) are skipped, `TO authenticated` adds the signed-in check, RESTRICTIVE policies are AND-ed in, anon-only policies become a TODO (denied), and an operation with no applicable policy becomes `policy.none()`; a table whose RLS is off in the database gets an explicit `enableRLS: false` (with a comment) so `push` does not change it silently — remove it to lock the table. Over REST (no `--db-url`) RLS cannot be read: the imported tables have no policies, so `push` turns RLS on for all of them, and a table whose RLS was off becomes deny-all until you add policies (or `enableRLS: false`). Review the imported rules (comments name the source policy) and replace `policy.custom` with semantic builders where possible. The original database policies are still there after `init`: Postgres ORs permissive policies, so they would keep granting access. `push` therefore refuses with `FOREIGN_POLICIES` while a managed table has a policy not named `_
_`; once the imported rules are reviewed, ask the user, then `push --replace-foreign-policies` drops them in the push transaction. `--db-url` also imports exact column types (`numeric(10,2)`, enums as `enum(...)`, `text[]` / `int[]` / `uuid[]`), column defaults, composite primary keys (`compositePrimaryKey`), multi-column UNIQUE (as unique `indexes`), FKs to other schemas (`'auth.users.id'`) with their `ON DELETE`, RPC parameter defaults, RPC volatility (`volatility`) and function `SET` options (`set`, from `pg_proc.proconfig`), and user triggers as `trigger.custom` (timing, events, `FOR EACH`, `WHEN`, `SECURITY DEFINER`, `SET` options kept; `UPDATE OF cols` becomes a WHEN on those columns changing; trigger functions are always VOLATILE). Every imported function is re-created with `SET search_path = pg_catalog, public`: each one whose search_path changes (another value such as `'public'`, or none) gets a `// NOTE:` comment and is listed in `hardenedFunctions` (`--json`) — check its body schema-qualifies anything outside `public`. Function grants follow the EFFECTIVE privilege in the source (`has_function_privilege`, PUBLIC counts): a definer function anon could execute gets `allowAnon: true` + a `// NOTE:` and is listed in `anonExecutableFunctions` — show that list to the user: maintenance/admin functions exposed to anon need a deliberate keep/remove decision. One authenticated could not execute is still granted to authenticated (rpc() cannot express it): `// NOTE:` + `authenticatedGrantedFunctions`. Functions returning `TABLE(...)`, `SETOF ` or `SETOF ` import fully as `returns: { table }` / `{ setof }`. One whose result (`record`, composite, OUT params) or an argument (composite type, typed `'json'`) rpc() cannot express is emitted signature-only WITH its real `args` (typed client, no SQL; its SQL stays in your migrations) — never an empty `rpc()` when the function has arguments. What cannot be expressed is left as a `// WARNING:` comment in the schema, never dropped silently: triggers with arguments, disabled, INSTEAD OF / TRUNCATE-only or non-plpgsql ones; array/other types with no AccessNexus equivalent (imported as `text`); generated columns; multi-column FKs. Imported triggers are recreated as `_
_`: after `push` to the same database the original trigger would still exist and both would fire, so `push` refuses with `FOREIGN_TRIGGERS` until the user approves `--replace-foreign-triggers`. That flag drops the triggers only, never their functions; `keptTriggerFunctions` lists each with its `pg_depend` dependents (`orphaned: true` = nothing depends on it; dropping it is a manual, reviewed step). Enum columns get AccessNexus's own enum type (`
__enum`). - `validate` — load + check the schema, write nothing. Flags: `--schema `. `--against-db` (with `--url`/`--target`) also compiles everything push would run — raw `policy.custom`, `trigger.custom` bodies, RPC bodies, checks — in a rolled-back transaction; a rejection is an error `SQL_REJECTED` whose `path` is the schema item (`rpcs.`, `
.triggers[]`, `
.policies.`). - `generate` — write migrations, policies, triggers, RPCs and the SDK. Files that only differ in the `-- Generated at:` line are left untouched. `generate` and `diff` warn `NOT_NULL_COLUMN_ADDED` (in `warnings`) when a new migration adds a NOT NULL column without default to an existing table — push fails if it has rows (see the recipe). Flags: `--schema`, `--output ` (every output folder goes under ``, overriding the paths in `accessnexus.config.ts` — handy to preview into a scratch folder), `--sql-only`, `--sdk-only`, `--prefix `. - `diff` — what `generate` would change; writes nothing. Same flags + `--check` (exit 1 when anything is out of date). It compares the schema with the generated FILES, not the database; when a database URL is configured its result carries a `hint` pointing to `--against-db`. - `diff --against-db` — live change plan: connects (same `--url`/`--db-url`/env/`--target` resolution as `push`), takes the push advisory lock without waiting (`PUSH_LOCKED` if a push is running), BEGINs, snapshots the catalog of everything the schema manages, applies exactly what `generate` + `push` would apply (the SQL the current schema generates, through the push code path), snapshots again and ROLLs BACK. Nothing persists — no objects, no `accessnexus_migrations` rows. Foreign policies/triggers are dropped in the plan only with `--replace-foreign-policies` / `--replace-foreign-triggers` (as in push); without them they are reported in `blockers`. `--allow-destructive` likewise. `--check` exits 1 (`LIVE_DB_CHANGES`) when the database would change; a push Postgres would reject exits 1 (`PUSH_WOULD_FAIL`) with `failed: { file, message, sqlState, line, statement }` and the PARTIAL plan (what applies before the failure: `wouldApply`, `changes`). A pending migration adding a NOT NULL column without default to a table with rows is reported before Postgres fails: blocker `NOT_NULL_ON_NON_EMPTY_TABLE` with `details: { table, column, rows }`. - `push` — apply generated SQL in order migrations → rpcs → policies → triggers, tracked in `public.accessnexus_migrations`. The whole push (bookkeeping, foreign-policy drops and every file) runs in ONE transaction under an advisory lock: if anything fails, nothing from that push stays applied. (Exception: a migration that adds an enum value cannot use that value in the same push — Postgres forbids it inside a transaction; push the enum change first.) Re-running skips unchanged files and re-applies changed policy/trigger/RPC files; editing an applied migration is refused. Before touching the database it checks that the generated SQL matches the schema (`GENERATED_OUT_OF_DATE`) and that no pending migration destroys data (`DESTRUCTIVE_MIGRATION`), and that the role bypasses RLS when the SQL has SECURITY DEFINER helpers (`PUSH_ROLE_NO_BYPASSRLS`). It reads `pg_policies` for every table the schema manages and refuses (`FOREIGN_POLICIES`, nothing applied) while any policy there is not one AccessNexus generates (`_
_`); `--replace-foreign-policies` drops them in the same transaction. Same for triggers not named `_
_...` (`FOREIGN_TRIGGERS`, `--replace-foreign-triggers`). Prints a notice instead of waiting silently when another push holds the lock. Flags: `--url ` (alias `--db-url`), `--dry-run` (lists files and destructive statements; when a database URL is set it also rehearses the push of the files on disk like `diff --against-db` and returns that plan as `livePlan` — nothing persists), `--allow-destructive`, `--replace-foreign-policies`, `--replace-foreign-triggers`, `--seed` (also run the seed), `--allow-remote-seed`, `--output`, `--schema`, `--prefix`, `--adapter`, `--target`. - `migration discard` — drop the NEWEST migration when the database never applied it (checks `public.accessnexus_migrations` through `--url`/`--target`/env; without a database only with `--force`) and restore the snapshot to the state before it (the snapshot keeps a history). It does NOT regenerate the migration (`regenerated: null`). Derived files (SDK, policies, triggers, RPCs): when the schema already matches the restored state they are rewritten (`refreshed: [paths]`); otherwise the ones that changed together with the discarded migration (recorded in the snapshot as `derivedChanged`) are listed in `stale: [paths]` with a `hint` — revert the schema and run `generate`. `migration amend` = discard + generate, and reports the file it wrote in `regenerated` (`null` when the schema matches the restored state). Refuses with `MIGRATION_ALREADY_APPLIED`; `MIGRATION_HISTORY_MISSING` for snapshots from < 0.4.1. Use them to replace a pending migration (e.g. NOT NULL → nullable) instead of editing it. - `migration data ` — create `/data/__.sql`: a data migration YOU write (e.g. a backfill UPDATE). Push applies it once, in timestamp order with the schema migrations (so between the migration generated before it and the one after), inside the push transaction, recorded in `accessnexus_migrations` (immutable afterwards). Messages and plans name a migration `generate` has not written yet `__changes.sql`. - `test-db up | down` — a disposable local `supabase/postgres` in Docker (`--port` 55433, `--name`, `--image`), prepared for RLS tests (GoTrue-like `auth.uid()`/`auth.jwt()`, `auth.users.email_confirmed_at`, `realtime.messages`); `up --push` also pushes the schema. Waits until connections are stable (the image restarts Postgres after its init). Prints the URL. `DOCKER_NOT_FOUND`, `TEST_DB_PORT_IN_USE` (pick another `--port`), `TEST_DB_START_FAILED`. - `seed` — upsert seed rows. Flags: `--seed `, `--url` (alias `--db-url`), `--dry-run` (prints the SQL), `--allow-remote-seed`, `--schema`, `--prefix`, `--adapter`, `--target`. - `help [command]`, `version` (also `--version`). With `--json` both print one object. Database connections (`push`, `seed`, `diff --against-db`, `init --db-url`) give up after 10 s with `DB_CONNECTION_FAILED` instead of hanging; set `ACCESSNEXUS_DB_CONNECT_TIMEOUT=` to change it. Exit codes: `0` success; `1` user-fixable (bad flag, missing file, schema error, missing DB URL, unreachable DB, SQL rejected, stale output, destructive migration without `--allow-destructive`, failed seed); `2` internal error (a AccessNexus bug — rerun with `--verbose` and report the stack). ### --json output shapes Every result has `ok`, `command` and `version`. Failures add `error` (and keep any partial result fields, e.g. `issues`, `applied`). ```ts export interface SchemaIssue { severity: 'error' | 'warning'; code: string; // e.g. 'UNKNOWN_COLUMN' path: string; // e.g. 'posts.policies.update' message: string; hint?: string; // how to fix it } export interface ErrorResult { ok: false; command: string; version: string; error: { code: string; message: string; hint?: string; stack?: string /* --verbose */ }; issues?: SchemaIssue[]; // SCHEMA_VALIDATION_FAILED } export interface ValidateResult { ok: true; command: 'validate'; version: string; schemaPath: string; mode: 'manual' | 'database'; tables: Array<{ name: string; columns: number; primaryKey: string | null; rls: boolean; policies: string[]; triggers: Array<{ kind: string; name: string | null }>; realtime: boolean | null }>; rpcs: string[]; channels: string[]; functions: string[]; issues: SchemaIssue[]; // warnings only (errors make ok=false); with --against-db a rejection is SQL_REJECTED summary: { errors: number; warnings: number }; } export interface DestructiveStatement { file: string; // migration file line: number; kind: 'drop_table' | 'drop_column' | 'alter_column_type' | 'drop_type' | 'truncate'; sql: string; } export interface GenerateResult { ok: true; command: 'generate'; version: string; schemaPath: string; mode: 'manual' | 'database'; files: Array<{ path: string; category: 'migrations' | 'policies' | 'triggers' | 'rpcs' | 'sdk' | 'functions'; status: 'created' | 'updated' | 'unchanged' }>; destructive: DestructiveStatement[]; // in migrations written by this run summary: { created: number; updated: number; unchanged: number; files: number; tables: number }; warnings: SchemaIssue[]; } export interface DiffResult { ok: boolean; // false only with --check and pending changes (error.code GENERATED_OUT_OF_DATE) command: 'diff'; version: string; schemaPath: string; changed: boolean; destructive: DestructiveStatement[]; // in migrations generate would write summary: { added: number; modified: number; removed: number; renamed: number }; changes: Array<{ path: string; status: 'added' | 'modified' | 'removed'; diff: string }>; warnings: SchemaIssue[]; hint?: string; // set when a database URL is configured: use `diff --against-db` for the live plan } export type PlanKind = 'table' | 'column' | 'constraint' | 'index' | 'rls' | 'policy' | 'trigger' | 'function' | 'grant'; export interface PlanChange { kind: PlanKind; // 'public.notes' (table, rls) | 'public.notes.body' (column) | 'public.notes.' // | 'public.' | 'public.fn(uuid, text)' (function) | 'table public.notes' / 'function public.fn()' (grant) object: string; change: 'added' | 'removed' | 'modified' | 'renamed'; // renamed: an index under a new name (before.name → after.name), same definition before?: Record; // normalized catalog properties (absent when added) after?: Record; // (absent when removed) fields?: string[]; // modified: the properties that differ // properties per kind: // column: { type, notNull, default, identity, generated } (type via format_type, default via pg_get_expr) // constraint: { type, definition } index: { table, definition } rls: { enabled, forced } // policy: { command, permissive, roles: string[], using, withCheck } // trigger: { timing, events: string[], level, when, function, enabled } // function: { returns, language, volatility, securityDefiner, strict, config: string[], bodyHash, definition } // ('definition' = pg_get_functiondef, shown but not compared; a body change shows as 'bodyHash') // grant: { privileges: string[], effective: string[] } // privileges = literal ACL, e.g. 'anon=EXECUTE', 'PUBLIC=EXECUTE', 'authenticated=SELECT*' (* = WITH GRANT OPTION) // effective = what PUBLIC / anon / authenticated can really do (has_*_privilege), e.g. 'anon=EXECUTE' notes?: string[]; // grants: access path per role, e.g. 'anon EXECUTE: via PUBLIC → direct grant (no change in access)' } export interface RiskyChange { code: 'table_dropped' | 'column_dropped' | 'column_type_changed' | 'column_default_removed' | 'column_nullability_relaxed' | 'column_nullability_tightened' // existing nulls fail; old clients writing null break | 'rls_disabled' | 'policy_dropped' | 'policy_roles_widened' | 'policy_permissive_changed' | 'trigger_dropped' | 'function_dropped' | 'function_volatility_changed' | 'function_config_changed' | 'function_security_changed' | 'function_result_changed' // an RPC's result type/columns change: callers reading the old shape break | 'grant_widened' // PUBLIC/anon/authenticated gains EFFECTIVE access on an existing object | 'grant_narrowed'; // ... loses it (PUBLIC losing what anon and authenticated both keep is not flagged) kind: PlanKind; object: string; message: string; // e.g. 'function public.f() STABLE → VOLATILE' } export interface LivePlan { database: string; // redacted URL wouldApply: string[]; // files push would execute; with `failed`: those applied before the failure skipped: Array<{ path: string; reason: 'already_applied' | 'checksum_normalized' }>; droppedPolicies: ForeignPolicy[]; // only with --replace-foreign-policies droppedTriggers: ForeignTrigger[]; // only with --replace-foreign-triggers keptTriggerFunctions: KeptTriggerFunction[]; // functions of the dropped triggers: never dropped foreignPolicies: ForeignPolicy[]; foreignTriggers: ForeignTrigger[]; blockers: Array<{ code: string; message: string; hint?: string; details?: Record }>; // refusals the real push would stop at // (FOREIGN_POLICIES, FOREIGN_TRIGGERS, DESTRUCTIVE_MIGRATION, PUSH_ROLE_NO_BYPASSRLS, // NOT_NULL_ON_NON_EMPTY_TABLE with details { table, column, rows }): the push would apply nothing failed: null | { file: string | null; code: string; message: string; sqlState: string | null; line: number | null; statement: string | null; // the statement Postgres rejected (1-based line in file) }; // push would fail; `changes` then hold the partial plan up to it changed: boolean; summary: { added: number; modified: number; removed: number; renamed: number }; changes: PlanChange[]; riskyChanges: RiskyChange[]; persisted: false; // always: the rehearsal is rolled back } export interface DiffAgainstDbResult extends LivePlan { ok: boolean; // false with --check and changes (LIVE_DB_CHANGES) or when the push would fail (PUSH_WOULD_FAIL) command: 'diff'; version: string; schemaPath: string; againstDb: true; adapter: string; target: string | null; generatedUpToDate: boolean; // false: plan is from the schema; run generate before push warnings: SchemaIssue[]; } export interface PushResult { ok: true; command: 'push'; version: string; dryRun: boolean; adapter: string; target: string | null; plan: Array<{ category: string; files: string[] }>; destructive?: DestructiveStatement[]; // --dry-run: in all migration files foreignPolicies?: ForeignPolicy[] | null; // --dry-run: null when no database URL (not checked) foreignTriggers?: ForeignTrigger[] | null; // --dry-run: { schema, table, trigger, function } wouldRefuse?: boolean; // --dry-run: foreign policies/triggers without their --replace-* flag, or livePlan blockers/failed livePlan?: LivePlan | null; // --dry-run: rehearsal of the files on disk; null without a database URL (or unreachable) applied: string[]; droppedPolicies: ForeignPolicy[]; // --replace-foreign-policies droppedTriggers: ForeignTrigger[]; // --replace-foreign-triggers keptTriggerFunctions: KeptTriggerFunction[]; // --replace-foreign-triggers skipped: Array<{ path: string; reason: 'already_applied' | 'checksum_normalized' }>; seed: null | { path: string; status: 'applied' | 'skipped'; authUsers: number; durationMs?: number }; // only with --seed // on failure: error.code DESTRUCTIVE_MIGRATION adds destructive[]; GENERATED_OUT_OF_DATE adds // stale: Array<{ path: string; status: string }>; FOREIGN_POLICIES adds foreignPolicies[]; FOREIGN_TRIGGERS adds foreignTriggers[]; // PUSH_FAILED / MIGRATION_DRIFT: applied is [] (rolled back), rolledBack: string[] lists the files // that had run, PUSH_FAILED adds failed: string; a failed --seed keeps applied[] and seed.status 'failed' } export interface ForeignTrigger { schema: string; table: string; trigger: string; function: string; // the trigger function, regprocedure text, e.g. 'touch()' or 'audit.log_change()' } export interface KeptTriggerFunction { function: string; dependents: string[]; // pg_depend, e.g. 'trigger t on table other.events' (calls inside other bodies are not tracked) orphaned: boolean; // no dependents left } export interface ForeignPolicy { schema: string; table: string; policy: string; command: string; // SELECT | INSERT | UPDATE | DELETE | ALL permissive: boolean; // false = RESTRICTIVE } export interface SeedResult { ok: true; command: 'seed'; version: string; dryRun: boolean; seedPath: string; checksum: string; rows: number; authUsers: number; // auth.users rows the seed provisions applied: boolean; sql?: string; // --dry-run } export interface InitResult { ok: true; command: 'init'; version: string; status: 'initialized' | 'already_initialized'; framework?: string; schemaSource?: 'template' | 'database' | 'rest'; sdkPath?: string; policyPrefix?: string; installed?: string[]; // packages installed by --install files: Array<{ path: string; action: 'created' | 'updated' | 'skipped' }>; agents: null | { agentsMd: 'created' | 'updated' | 'unchanged'; claudeMd: 'updated' | 'unchanged' | 'absent' }; // --db-url: imported functions whose search_path generate pins to 'pg_catalog, public' // (from: the database value, null when it had none). name is `table.trigger` for triggers. hardenedFunctions?: Array<{ kind: 'rpc' | 'trigger'; name: string; from: string | null; to: string }>; // --db-url: definer functions anon could execute in the source (imported with allowAnon: true) anonExecutableFunctions?: string[]; // --db-url: definer functions authenticated could NOT execute (generate grants it anyway) authenticatedGrantedFunctions?: string[]; nextSteps?: string[]; } export interface HelpResult { // help --json, --help --json ok: true; command: 'help'; version: string; topic: string | null; // the command asked about, null for the overview commands: Array<{ name: string; summary: string; examples: string[]; flags: Array<{ name: string; kind: 'boolean' | 'string'; value?: string; description: string }>; }>; exitCodes: Record<'0' | '1' | '2', string>; docs: string; // path of this file } export interface VersionResult { ok: true; command: 'version'; version: string } ``` ## Recipes ### Required column on a table with data (e.g. a new tenant column) `ALTER TABLE ... ADD COLUMN x NOT NULL` fails on a table with rows (`generate`/`diff` warn `NOT_NULL_COLUMN_ADDED`; the live plan blocks with `NOT_NULL_ON_NON_EMPTY_TABLE` and the row count). Do it in steps, in ONE push: 1. Add the column nullable (`org_id: 'uuid?'`) and run `generate`. 2. `npx accessnexus migration data backfill_task_org` and write the backfill in the created file, e.g. `UPDATE public.tasks t SET org_id = (SELECT m.org_id FROM public.org_members m WHERE m.user_id = t.user_id LIMIT 1) WHERE t.org_id IS NULL;` (runs as the push user, RLS bypassed). 3. Make it required (`org_id: 'uuid'`) and run `generate` (a `SET NOT NULL` migration; `riskyChanges` shows `column_nullability_tightened` against a database that has the column). 4. `diff --against-db`, then `push`: nullable → backfill → NOT NULL apply in timestamp order. Already generated the NOT NULL migration and not pushed it? `npx accessnexus migration discard` (checks the database never applied it), change the schema, `generate` again — or change the schema first and run `migration amend` (discard + generate in one step). ### Workspace list for a user (orgs they belong to) With `orgs.read: { any: ['own', { scope: 'tenant' }] }` the creator keeps reading the org row even after being removed (`own`). List workspaces through memberships, not `orgs` alone: `db.org_members.findMany({ user_id: me }, { include: { org: true } })` (org_members needs a select policy that shows the user's own rows: `policy.isOwner('user_id')`). ### The invitee sees the org name before joining They cannot read `orgs` yet. Use `tenantInvitations({ ..., tenantNameColumn: 'name' })`: `db.rpc.my_invitations()` returns `{ id, org_id, tenant_name, role, created_at }[]`, and `db.rpc.accept_invitation({ p_invitation })` joins (see §Multi-tenant building blocks). ### Owner-only table (each user sees and edits only their rows) ```ts import { defineSchema, policy, table, trigger } from 'accessnexus'; export default defineSchema({ notes: table({ columns: { id: 'uuid', user_id: 'uuid', body: 'text', created_at: { type: 'timestamptz', default: 'now()' }, updated_at: 'timestamptz?', }, primaryKey: 'id', references: { user_id: 'auth.users.id' }, indexes: [{ columns: ['user_id'] }], triggers: [trigger.updatedAt('updated_at')], policies: { select: policy.isOwner('user_id'), insert: policy.isOwner('user_id'), update: policy.isOwner('user_id'), delete: policy.isOwner('user_id'), }, }), }); ``` ### Public read, authenticated write Anonymous visitors read published rows: the `select` rule has a branch that needs no user (`custom('published = true')`), so its policy is granted `TO public`. Writes stay signed-in only. Do not "fix" a read problem with `select: policy.public()` — that also exposes drafts. ```ts import { defineSchema, policy, table } from 'accessnexus'; export default defineSchema({ articles: table({ columns: { id: 'uuid', author_id: 'uuid', title: 'text', published: 'boolean' }, primaryKey: 'id', references: { author_id: 'auth.users.id' }, policies: { select: policy.any([policy.custom('published = true'), policy.isOwner('author_id')]), insert: policy.isOwner('author_id'), // signed in AND writing as themselves update: policy.isOwner('author_id'), delete: policy.isOwner('author_id'), }, }), }); ``` ### Multi-tenant with roles (teams) Roles live in the membership table (`team_members.role`). The team creator becomes its first owner through a `security: 'definer'` AFTER INSERT trigger on `teams` — not through an INSERT rule on `team_members`, which a creator removed by the other owners could replay to rejoin. Owners add anyone, editors may only add plain members (so nobody can promote themselves). `definePermissions` pins writes: `projects.created_by` must be the creator and a project can never move to a team the user is not in; `lockColumns` keeps who/where a row belongs fixed. ```ts import { definePermissions, defineSchema, policy, table, trigger } from 'accessnexus'; const permissions = definePermissions({ roles: ['owner', 'editor', 'member'], tenant: { table: 'team_members', userColumn: 'user_id', tenantColumn: 'team_id', roleColumn: 'role' }, resources: { teams: { ownerColumn: 'created_by', tenantColumn: 'id', // the row IS the tenant read: { any: ['own', { scope: 'tenant' }] }, // creator sees it before joining create: '*', // + created_by = auth.uid() update: { scope: 'tenant', roles: ['owner'] }, delete: { scope: 'tenant', roles: ['owner'] }, }, projects: { ownerColumn: 'created_by', tenantColumn: 'team_id', read: { scope: 'tenant' }, create: { scope: 'tenant', roles: ['owner', 'editor'] }, update: { any: ['own', { scope: 'tenant', roles: ['owner'] }] }, delete: { scope: 'tenant', roles: ['owner'] }, }, }, }); /** Current user is a member of the row's team (optionally with one of `roles`). */ function teamMember(roles?: string[]) { return policy.belongsTo('team_id', { table: 'team_members', foreignKey: 'team_id', localKey: 'user_id', ...(roles ? { where: { role: roles } } : {}), }); } export default defineSchema({ teams: table({ columns: { id: 'uuid', name: 'text', created_by: 'uuid' }, primaryKey: 'id', references: { created_by: 'auth.users.id' }, triggers: [ // The creator becomes the first owner (runs as the table owner, bypassing RLS) trigger.custom({ name: 'add_creator_as_owner', events: ['after_insert'], security: 'definer', functionBody: "INSERT INTO public.team_members (team_id, user_id, role) VALUES (NEW.id, NEW.created_by, 'owner'); RETURN NEW;", }), trigger.lockColumns({ columns: ['created_by'] }), ], policies: permissions.policiesFor('teams'), }), team_members: table({ columns: { id: 'uuid', team_id: 'uuid', user_id: 'uuid', role: "enum('owner','editor','member')" }, primaryKey: 'id', references: { team_id: 'teams.id', user_id: 'auth.users.id' }, onDelete: { team_id: 'cascade' }, // deleting a team removes its memberships indexes: [{ columns: ['team_id', 'user_id'], unique: true }], triggers: [trigger.lockColumns({ columns: ['team_id', 'user_id'] })], // owners change roles only policies: { // Own rows too: INSERT ... RETURNING (what the SDK's create does) must see the new row select: policy.any([teamMember(), policy.isOwner('user_id')]), insert: policy.any([ teamMember(['owner']), // owners add anyone policy.all([teamMember(['editor']), policy.custom("role = 'member'")]), // editors add members only ]), update: teamMember(['owner']), delete: policy.any([teamMember(['owner']), policy.isOwner('user_id')]), // owners remove, anyone leaves }, }), projects: table({ columns: { id: 'uuid', team_id: 'uuid', created_by: 'uuid', name: 'text' }, primaryKey: 'id', references: { team_id: 'teams.id', created_by: 'auth.users.id' }, onDelete: { team_id: 'cascade' }, triggers: [trigger.lockColumns({ columns: ['created_by', 'team_id'] })], policies: permissions.policiesFor('projects'), }), }); ``` App flow: `db.teams.create({ name, created_by: user.id })` — the creator is now an owner. Then owners add people with `db.team_members.create({ team_id, user_id, role })`. This direct add is fine here because co-members see nothing personal about each other. If co-members can read each other's profiles (email, name), switch to invitations — see "Visibility derived from sharing a tenant" in the RLS rules below. Trade-off: `teams.read` includes `'own'` so the creator can read the row the SDK's `create` returns (`INSERT ... RETURNING` is checked before the AFTER INSERT membership exists). A creator later removed from the team therefore still sees that one `teams` row (its name), never its projects or members. If the team name itself is sensitive, drop `'own'` from `read` and create teams with `db.teams.create(...)` ignoring the returned row (or through a `security: 'definer'` RPC that inserts and returns the id). ### Child of a tenant resource (tasks under projects) RLS checks each row against its OWN tenant column, and foreign keys are checked without RLS. So `tasks` needs its own `org_id` (denormalized, so `belongsTo` can check it), and something must keep `tasks.org_id` equal to the project's `org_id` — otherwise a member of org A can create a task in A that points at org B's project (probing B's ids, attaching rows that cascade with B's data). `validate` warns `TENANT_PARENT_UNCHECKED` when the guard is missing. Guard it with `trigger.sameTenant` (BEFORE INSERT/UPDATE) and freeze both columns: ```ts import { defineSchema, policy, table, trigger } from 'accessnexus'; const member = policy.belongsTo('org_id', { table: 'org_members', foreignKey: 'org_id', localKey: 'user_id' }); const memberPolicies = { select: member, insert: member, update: member, delete: member }; export default defineSchema({ orgs: table({ columns: { id: 'uuid', name: 'text' }, primaryKey: 'id', policies: { select: policy.belongsTo('id', { table: 'org_members', foreignKey: 'org_id', localKey: 'user_id' }) }, }), org_members: table({ columns: { id: 'uuid', org_id: 'uuid', user_id: 'uuid', role: "enum('admin','member')" }, primaryKey: 'id', references: { org_id: 'orgs.id', user_id: 'auth.users.id' }, indexes: [{ columns: ['org_id', 'user_id'], unique: true }], policies: { select: policy.isOwner('user_id') }, // writes: service role / definer RPCs only }), projects: table({ columns: { id: 'uuid', org_id: 'uuid', name: 'text' }, primaryKey: 'id', references: { org_id: 'orgs.id' }, triggers: [trigger.lockColumns({ columns: ['org_id'] })], policies: memberPolicies, }), tasks: table({ columns: { id: 'uuid', org_id: 'uuid', project_id: 'uuid', title: 'text' }, primaryKey: 'id', references: { org_id: 'orgs.id', project_id: 'projects.id' }, onDelete: { project_id: 'cascade' }, triggers: [ // Runs as the writing user (INVOKER): a project of another org is invisible // through RLS, so it is reported exactly like a project that does not exist (23503). trigger.sameTenant({ column: 'project_id', references: 'projects', tenantColumn: 'org_id' }), trigger.lockColumns({ name: 'lock_tenant', columns: ['org_id', 'project_id'] }), ], policies: memberPolicies, }), }); ``` The same applies to any deeper level (comments under tasks: check `tasks.org_id`). ### Let a user change only some columns RLS decides WHICH rows a user may update, never WHICH columns: `update: 'own'` on an assignee also lets them rewrite the title, the assignee or the tenant. Lock the rest with `trigger.lockColumns` (BEFORE UPDATE, compares OLD and NEW): ```ts import { defineSchema, policy, table, trigger } from 'accessnexus'; export default defineSchema({ tickets: table({ columns: { id: 'uuid', org_id: 'uuid', reporter_id: 'uuid', assignee_id: 'uuid?', title: 'text', status: { type: "enum('open','doing','done')", default: "'open'" }, }, primaryKey: 'id', references: { reporter_id: 'auth.users.id', assignee_id: 'auth.users.id' }, triggers: [ // Nobody re-attributes a ticket or moves it to another org trigger.lockColumns({ name: 'lock_identity', columns: ['reporter_id', 'org_id'] }), // The assignee may only change status; the reporter may change anything else trigger.lockColumns({ name: 'assignee_scope', except: ['status'], unless: 'OLD.reporter_id = (SELECT auth.uid())', }), ], policies: { select: policy.any([policy.isOwner('reporter_id'), policy.isOwner('assignee_id')]), insert: policy.isOwner('reporter_id'), update: policy.any([policy.isOwner('reporter_id'), policy.isOwner('assignee_id')]), delete: policy.isOwner('reporter_id'), }, }), }); ``` For a multi-step change that must stay consistent, prefer a `security: 'definer'` RPC that checks the caller and updates only what it should. ### Audit log `trigger.auditLog({ table })` inserts `(table_name, operation, old_data, new_data, changed_at)` into the audit table from a `SECURITY DEFINER` function, so the audit table needs exactly those columns (others nullable or defaulted) and should block API inserts with `policy.none()`. `validate` reports `AUDIT_TABLE_MISMATCH` (wrong columns, an error) and `AUDIT_INSERT_OPEN` (users could forge entries, a warning). ```ts import { defineSchema, policy, table, trigger } from 'accessnexus'; export default defineSchema({ invoices: table({ columns: { id: 'uuid', owner_id: 'uuid', amount: 'decimal' }, primaryKey: 'id', references: { owner_id: 'auth.users.id' }, triggers: [trigger.auditLog({ table: 'audit_log' })], policies: { select: policy.isOwner('owner_id'), insert: policy.isOwner('owner_id'), update: policy.isOwner('owner_id'), delete: policy.none(), }, }), audit_log: table({ columns: { id: 'bigint', table_name: 'text', operation: 'text', old_data: 'jsonb?', new_data: 'jsonb?', changed_at: { type: 'timestamptz', default: 'now()' }, }, primaryKey: 'id', policies: { select: policy.hasRole('admin'), // platform staff (app_metadata.role) insert: policy.none(), // only the trigger writes (SECURITY DEFINER) update: policy.none(), // append-only delete: policy.none(), }, }), }); ``` ## Testing RLS (accessnexus/testing) `npx accessnexus test-db up --push` starts a disposable `supabase/postgres` (Docker, port 55433) prepared for RLS tests and pushes the schema; `test-db down` removes it. Never point tests at a hosted project. Then, with `pg`: ```ts import pg from 'pg'; import { asAnon, asUser, affectedRows, expectDenied, sqlState } from 'accessnexus/testing'; const pool = new pg.Pool({ connectionString: 'postgres://postgres:postgres@127.0.0.1:55433/postgres' }); const ALICE = { id: '00000000-0000-4000-8000-000000000001', email: 'alice@test.dev' }; export async function checks() { // Fixtures as `postgres` (bypasses RLS): pool.query('INSERT ...'). await asUser(pool, ALICE, async (db) => { // Every check runs as the API user, in a transaction that is always rolled back. const insert = await sqlState(db, 'INSERT INTO notes (owner_id, body) VALUES ($1, $2)', [ALICE.id, 'x']); // 'ok' | '42501' | ... const hidden = await expectDenied(db, 'DELETE FROM notes WHERE owner_id <> $1', [ALICE.id]); // { denied: true, by: 'no_rows' } const changed = await affectedRows(db, 'UPDATE notes SET body = $1 WHERE owner_id = $2', ['y', ALICE.id]); return { insert, hidden, changed }; }); await asAnon(pool, async (db) => (await db.query('SELECT count(*) FROM notes')).rows); } ``` `asUser(pool, user, fn)` sets `ROLE authenticated` and `request.jwt.claims` (sub, email, `appRole` → `app_metadata.role`) like PostgREST. `sqlState` / `expectDenied` use savepoints, so one denied statement does not abort the test. `TEST_DB_STANDINS_SQL` is the preparation SQL (`auth.uid()`/`auth.jwt()` reading the claims, `auth.users.email_confirmed_at`, `authenticator` login, `realtime.messages`) for your own containers (run as `supabase_admin`). ## How a denial shows | Statement | RLS clause that refuses | What the caller gets | | --- | --- | --- | | INSERT | WITH CHECK | error 42501 (`new row violates row-level security policy`) | | UPDATE, row hidden by USING | USING | no error, 0 rows | | UPDATE, new row fails WITH CHECK | WITH CHECK | error 42501 | | DELETE, row hidden / not deletable | USING | no error, 0 rows | | SELECT | USING | the row is simply not returned | | `trigger.lockColumns` | trigger | error 42501, HINT `accessnexus:locked_column:.` | | same-tenant / membership triggers | trigger | error 23503 | | keepAtLeastOne | trigger | error 23514 | Test with `expectDenied` (both forms). In the app, the SDK turns the 0-row cases of `update`/`delete`/`updateOne`/`deleteOne` into `ACCESSNEXUS_NOT_FOUND_OR_DENIED`. ## RLS rules agents must not break - Every table reachable from the client has `policies`; use `policy.none()` for operations that must be blocked. Never "fix" a permission error by removing policies, adding `enableRLS: false` or using `policy.public()` for writes. - A tenant-scoped row that references another tenant-scoped row (tasks → projects) needs a same-tenant guard trigger (see "Child of a tenant resource"; `TENANT_PARENT_UNCHECKED`). - Never put private columns (email, phone) in a table whose `select` is `isAuthenticated()`/`public()`: on Supabase anyone can sign up and read them. - Never use `policy.public()` (or `'public'`) for insert/update/delete unless the user asked for anonymous writes (`validate` warns `PUBLIC_WRITE`). - A table keyed by the user id (`profiles.id` → `auth.users.id`) inserts with `policy.isOwner('id')`, never `isAuthenticated()` — that lets anyone create another user's row (`USER_ROW_INSERT_OPEN`). - Never write a bare `auth.uid()` / `auth.jwt()` in `policy.custom` or RPC bodies — always `(SELECT auth.uid())` (evaluated once per query instead of once per row). - `policy.isOwner` columns are `uuid`; reference `auth.users.id` or `profiles.id`. - Use `withCheck(using, check)` to add conditions on the written row; it keeps `using` in `WITH CHECK`. Only use `{ mode: 'replace' }` when the row may legitimately leave `using`. - Keep the write pins of `definePermissions` (`pinOwnerOnCreate`, `pinTenant`); disable one only for a concrete reason and pin the right column yourself. - Never let a member grant a role equal to or above their own: restrict inserts/updates of the membership table with `policy.custom("role IN (...)")` (see the multi-tenant recipe). - Visibility derived from sharing a tenant ("org mates can see my profile") is only private if joining a tenant needs the person's consent. If admins may insert any `user_id` into the membership table, anyone can create a tenant, add a stranger and read their data as a "co-member". In that case add people only through an accepted invitation (a `security: 'definer'` RPC that checks the invited, confirmed email) and set the membership table's `insert` to `policy.none()`; otherwise keep personal columns out of co-member reads. - Never add a "bootstrap" INSERT rule on the membership table ("the creator may add themselves as owner"): it stays valid forever, so a removed creator can rejoin. Add the first member with a `security: 'definer'` AFTER INSERT trigger on the tenant table. - RLS cannot restrict columns. Freeze owner/creator/tenant columns and limit what partial editors may change with `trigger.lockColumns`; an UPDATE rule never does it. - Org/team roles are tenant roles (`{ scope: 'tenant', roles }`), not `hasRole`. - The `select` rule must admit rows the user just inserted/updated: the SDK's `create` and `update` return the row (`INSERT/UPDATE ... RETURNING`), which fails with an RLS error otherwise. On a membership table, add `policy.isOwner('user_id')` to `select`. - Never use `belongsTo(col)` without `through` while users can write `profiles.` (`BELONGS_TO_PROFILE_WRITABLE`). - Membership checks go through `belongsTo` with `through` / `definePermissions` tenants — they compile to `SECURITY DEFINER` helpers with a pinned `search_path` that avoid RLS recursion. Do not re-implement them with `policy.custom` subqueries on the same table. (Trigger conditions such as `lockColumns({ unless })` are the exception: they are raw SQL run as the caller, outside any policy, so an `EXISTS` on the membership table is the way to write them — the membership table's own `select` policy still applies.) - `security: 'definer'` RPCs/triggers and the service role bypass RLS: check the caller inside. - Do not edit generated SQL to change behavior; change the schema and regenerate. Applied migrations are immutable — `push` refuses drift. ## Troubleshooting by error code - `SCHEMA_NOT_FOUND` — no schema at the path: create `accessnexus.schema.ts` (`npx accessnexus init --yes`), pass `--schema`, or set `schema` in `accessnexus.config.ts`. - `SCHEMA_NO_DEFAULT_EXPORT` — end the file with `export default defineSchema({...})`. - `SCHEMA_INVALID` — a builder rejected the definition (bad identifier, unknown reference, unknown role in definePermissions); the message names the table/field. - `SCHEMA_VALIDATION_FAILED` — see `issues[]`; fix each `path` as its `hint` says. Common codes: `UNKNOWN_COLUMN`, `UNKNOWN_TABLE`, `UNKNOWN_COLUMN_TYPE`, `OWNER_COLUMN_NOT_UUID`, `INVALID_POLICY_RULE` (wrote `'public'` instead of `policy.public()`), `UNKNOWN_POLICY_OPERATION` (`read`/`create` used as policy keys; `all` is valid), `INVALID_RPC_RETURNS` (`returns` not a type, `'void'`, `{ table }` or `{ setof }`), `EMPTY_COMBINATOR`, `MISSING_COLUMNS`, `AUDIT_TABLE_MISMATCH`, `RPC_IN_TABLES`, `INVALID_TRIGGER`, `RPC_VOLATILITY_CONFLICT` (`immutable` contradicts `volatility`: keep only `volatility`), `INVALID_FUNCTION_SET` (a `set` key that is not a GUC name, or a non-string value), `INVALID_REFERENCE`, `INVALID_IDENTIFIER`, `RESERVED_IDENTIFIER` (rename `order` → `orders`), `INVALID_PRIMARY_KEY` (`compositePrimaryKey` with fewer than two columns, together with `primaryKey`, or with `softDelete`), `UNKNOWN_TABLE_KEY` (typo such as `polices:`, or tables nested under a `tables:` key — pass them directly to `defineSchema`), `INVALID_ENUM_VALUE` (a `belongsTo` `where` value that is not in the membership column's enum, e.g. a misspelled role). `INVALID_DEFAULT` (`default` is raw SQL: write `"'todo'"`, not `'todo'`), `INVALID_ON_DELETE` (unknown action, no foreign key, or `'set null'` on a NOT NULL column), `CASCADE_INTO_SOFT_DELETE` (use `'restrict'`), `DUPLICATE_TRIGGER` (give a second `lockColumns`/`custom` trigger its own `name`), `BELONGS_TO_PROFILE_WRITABLE` (use `through`, or make `profiles.` server-written only), `RLS_DISABLED_WITH_POLICIES` (remove `enableRLS: false`). Warnings: `NO_POLICIES` (table is deny-all for the API — add policies if the client uses it), `RLS_DISABLED` (`enableRLS: false`: the table is open to the anon key), `TENANT_PARENT_UNCHECKED` (add the same-tenant guard trigger), `NO_PRIMARY_KEY`, `UNWRAPPED_AUTH_CALL` (bare `auth.uid()` in a custom policy or an RPC body), `PUBLIC_WRITE` (insert/update/delete open to anonymous visitors through `policy.public()`), `USER_ROW_INSERT_OPEN` (use `policy.isOwner('id')`), `AUDIT_INSERT_OPEN`, `GLOBAL_ROLE_IN_TENANT_TABLE`, `SCHEMA_EMPTY`. Realtime: errors `INVALID_REALTIME` (`realtime` must be true/false/{ replicaIdentity }), `INVALID_CHANNEL` (bad topic, unknown option, `table` without `{param}` or with a composite key, a `{placeholder}` that is not the topic parameter), `CHANNEL_RULE_NOT_SUPPORTED` (row rule in a channel: use `table` or `policy.custom`); warnings `REALTIME_NOT_READABLE` (published table without select policy: nobody receives), `REALTIME_RLS_DISABLED` (everyone receives every row), `REALTIME_REPLICA_FULL_WITH_RLS`, `CHANNEL_TABLE_NOT_READABLE` (nobody can join), `CHANNEL_PUBLIC_SEND`, `CHANNEL_CLOSED` (no rule). Edge Functions: errors `INVALID_EDGE_FUNCTION` (name, unknown option, bad `auth`, `input`/`output` shape, two names with the same camelCase), `TABLE_NAME_CLASH` (a table named `functions` or `channels` next to declared functions/channels); field types are `UNKNOWN_COLUMN_TYPE`; warning `EDGE_FUNCTION_PUBLIC` (`auth` accepts `'none'`). - `SCHEMA_LOAD_FAILED` / `CONFIG_LOAD_FAILED` / `SEED_LOAD_FAILED` — the file threw while running or imports a package that is not installed; fix the named file/import. - `MODULE_SYNTAX_ERROR` — TypeScript/syntax error at the location shown. `TS_LOADER_MISSING` — esbuild (a accessnexus dependency) is missing: reinstall with `npm install -D accessnexus`. - `CONFIG_NOT_FOUND` / `CONFIG_INVALID` — fix `--config` or the config's default export. - `UNKNOWN_COMMAND`, `UNKNOWN_FLAG`, `MISSING_FLAG_VALUE`, `INVALID_FLAG_VALUE`, `UNEXPECTED_ARGUMENT`, `INVALID_FLAGS` — follow the hint / `--help`. - `GENERATED_OUT_OF_DATE` — `diff --check` or `push` found generated files that do not match the schema: run `generate` (review `diff`), then retry. - `DESTRUCTIVE_MIGRATION` — a pending migration drops a table/column or changes a column type. Nothing was applied. If it is a rename, rename in the schema; otherwise confirm with the user (and a backup) before `push --allow-destructive`. - `NOTHING_TO_PUSH` — run `generate` first (or fix `--output`). - `DB_URL_MISSING` — pass `--url` or set `SUPABASE_DB_URL` (or `ACCESSNEXUS_DB_URL`/`DATABASE_URL`). - `PG_DRIVER_MISSING` — `push`, `seed` and `init --db-url` need it: `npm install -D pg`. - `PUSH_ROLE_NO_BYPASSRLS` — the connected role does not bypass RLS, which the generated SECURITY DEFINER helpers need. Nothing was applied. Connect as `postgres` (Supabase Session pooler string) or `ALTER ROLE BYPASSRLS` as a superuser. - `SEED_REMOTE_BLOCKED` — seeding a hosted Supabase project; use a local database or pass `--allow-remote-seed` if the project is disposable. - `DB_CONNECTION_FAILED` — wrong URL/password/network; for Supabase use the Session pooler string; local databases may need `?sslmode=disable`. A host that never answers fails after 10 s (`ACCESSNEXUS_DB_CONNECT_TIMEOUT=`). - `FOREIGN_POLICIES` — a table the schema manages has RLS policies AccessNexus did not generate (listed in the message and `foreignPolicies`). Nothing was applied. Permissive policies OR together, so they would keep granting access. Port any rule still needed into the schema, ask the user, then `push --replace-foreign-policies` (drops them in the push transaction). - `FOREIGN_TRIGGERS` — a table the schema manages has triggers AccessNexus did not generate (`foreignTriggers`). Nothing was applied. They would fire next to the generated ones (after `init --db-url`, the imported copy and the original both run). Port what is still needed (`trigger.custom`), ask the user, then `push --replace-foreign-triggers`. - `PUSH_FAILED` — Postgres rejected a file (message has the SQL error; `failed` names it). The whole push was rolled back: nothing from it is applied (`applied` is `[]`, `rolledBack` lists the files that had run). Fix the schema, `generate`, `push` again. - `PUSH_WOULD_FAIL` — `diff --against-db` rehearsed the push and Postgres rejected a file (`failed.file`, `failed.line`, `failed.statement`, `failed.message`, `failed.sqlState`; the partial plan shows what applied before it). Nothing was persisted. Fix the schema (or the database state) and plan again. - `NOT_NULL_ON_NON_EMPTY_TABLE` — a pending migration adds a NOT NULL column without default to a table with rows (`details.rows`): nullable → data migration backfill → NOT NULL (recipe "Required column on a table with data"); `migration discard` replaces an unpushed migration. - `MIGRATION_ALREADY_APPLIED` — `migration discard` refused: the database applied it; generate a new `__changes` migration instead. `MIGRATION_DISCARD_NEEDS_DB` — pass `--url`/`--target` (or `--force` if no environment ever applied it). `MIGRATION_HISTORY_MISSING` — the snapshot predates the history (< 0.4.1). `NO_MIGRATION_TO_DISCARD` — run `generate` first. - `DOCKER_NOT_FOUND` / `TEST_DB_PORT_IN_USE` / `TEST_DB_START_FAILED` — `test-db` needs Docker, a free `--port` (default 55433) and container `--name`; see `docker logs `. - `SQL_REJECTED` (validate --against-db issue) — Postgres rejected the SQL generated for `path`; fix that policy.custom / trigger.custom / rpc body / check. - `UNKNOWN_ENUM` — `'enum:'` without `defineSchema(..., { enums: [defineEnum(...)] })`. - `LIVE_DB_CHANGES` — `diff --against-db --check` found that push would change the database; the plan (`changes`, `riskyChanges`) is in the result. - `PUSH_LOCKED` — the live plan does not wait for a running push; retry when it finishes. - `MIGRATION_DRIFT` — an applied migration file was edited: restore it, change the schema, `generate` a new `__changes` migration. - `SEED_NOT_FOUND` / `SEED_EMPTY` / `SEED_FAILED` — create/fix `accessnexus.seed.ts`; seed after push. With `push --seed`, the SQL was already pushed when the seed fails. - `ADAPTER_NOT_FOUND` / `ADAPTER_AMBIGUOUS` / `ADAPTER_UNSUPPORTED` / `TARGET_NOT_FOUND` — only the `supabase` adapter exists. `TARGET_INVALID` — the named entry in `config.targets` has no `adapter`; add `adapter: 'supabase'` to it. - `INIT_NOT_INTERACTIVE` — add `--yes`. `INIT_NEEDS_INPUT` — pass the flag named in the hint. `INIT_DETECT_FAILED` — run init in the project root (the folder with package.json), or create one (`npm init -y`, or `init --yes` creates a minimal one). - `INTERNAL_ERROR` (exit 2) — a AccessNexus bug: rerun with `--verbose`, report the stack. ## Limits (v0.4.4-next) - Only the Supabase adapter exists. Database mode does not generate DDL migrations. - Index names come from their content (`idx_
_[_uniq]`); schemas from before 0.4.1 get one migration renaming the old position-based names (`ALTER INDEX ... RENAME`) and dropping foreign-key indexes a declared index already covers. - `tenantInvitations` grants by role lists; finer rules (seat limits, domains) need your own table or a wrapper RPC. `onAuthUserCreated` triggers live on `auth.users`: removing the builder does not drop them (drop the trigger by hand). - Edge Functions: push does not deploy them (`supabase functions deploy`); inputs are POST JSON only; outputs are typed, not validated at runtime; a removed function keeps its folder. - Realtime: Postgres Changes filters take one column; DELETE events are not RLS-filtered and `old` is the primary key only; channel topics have at most one trailing parameter; Broadcast payloads are untyped; channel policies apply to private channels only (turn off public Realtime access in the project settings). - Migrations are generated from snapshot diffs; renames are detected heuristically — read `diff` output before pushing destructive changes (`-- Destructive:` comments). - The live plan (`diff --against-db`) covers the managed tables and the functions the generated SQL defines or the managed triggers call; it does not snapshot other objects (enum types, extensions, unrelated schemas). It reflects what push does: an applied migration or an unchanged policy/trigger/RPC file is skipped, so drift made directly in the database after a push is not undone by push and does not show in the plan. - The rehearsal really executes the SQL inside a transaction: it takes the same locks as a push (brief ACCESS EXCLUSIVE locks on altered tables) until the ROLLBACK. - Identifiers are emitted unquoted: lowercase snake_case (one optional leading `_`), no reserved keywords. - RLS is row-level: it cannot restrict which columns an UPDATE changes — use `trigger.lockColumns` (see the recipe). - Foreign keys are `ON DELETE NO ACTION` unless `onDelete` says otherwise. - Each `enum(...)` column gets its own Postgres type (`
__enum`); cast between them in SQL (`v.role::text::org_members_role_enum`). - GRANT/REVOKE: `security: 'definer'` RPCs are not executable by `anon` unless `allowAnon`. Membership helpers are revoked from `PUBLIC`/`anon` and granted to `authenticated`; a helper used by a policy that also admits `anon` (`TO public`) is granted to `anon` too, which is safe because it returns false when `auth.uid()` is null. Invoker RPCs and tables keep Supabase's default grants. - More prose and examples: `node_modules/accessnexus/README.md`.