Access
Roles are defined in code (defineRoles) and assigned through the auth user’s roles; with organizations, also per membership, and ctx.user.roles holds both, while ctx.organization.id is the organization the request works in. Rules decide per operation (list, read, create, update, delete), per field (role-based, never per record) and per row (filters, like RLS).
Defaults
Section titled “Defaults”- A project that passes
rolestoresolveAccessis default deny: an operation without a rule needs the capability<resource>.<action>(listusesread), so admin’s*still passes. A field without a rule follows its resource. - A project without roles (the single-admin case) is default allow.
defaultAccess: 'allow'together withrolesis an explicit opt-in. PrintaccessWarnings(options)at startup.- Every request needs a token, unless the roles define
anonymous. - An API function without
rolesor acapabilityis closed the same way: with roles, only a caller holding*may call it.
Capabilities
Section titled “Capabilities”A role is a list of capabilities, <resource|area>.<action>[.<scope>]: orders.read, orders.update.own, costs.read (an area, for field rules), *.read or *. An entry may also be an object that limits capabilities to fields, rows or both:
defineRoles<'orders' | 'products'>({ sales: ['orders.read.own', 'orders.create', 'products.read'], erp_sync: [{ 'products.read': ['sku', 'price', 'stock'] }, { 'products.update': ['stock'] }], reseller: [{ 'products.read': { fields: ['sku', 'name', 'price'], filter: 'published = true' } }],})- Scopes:
.owngives the records whose.owner()field holds the user’s id, and.teamthose owned by the users thatteamOfreturns for them, a function given asdefineRoles(roles, { teamOf: (user) => ids }). A scoped capability on a resource without.owner()fails the request. A resource aSettingsblock shows is each person’s own for every role,*included: its records are always limited to the caller’s. - Fields (
['sku', 'price'], orfieldsin an object) are an allowlist: for<resource>.read,.createor.update, the role reads or writes only the fields listed, so a column added later stays hidden from it until someone lists it. Key columns are always there, because records are addressed by them. A plain capability ('products.read') still means every field. - Filter is AIP-160 text, like a filter an access rule returns. It narrows the rows of the capability, together with
.ownor.teamwhen the capability has one. - A limit names one resource, never
*, and fields go withread,createorupdateonly;defineRolesrefuses anything else. At startup the server refuses a field the resource does not have, a filter that does not fit it, and a limit on a name that is not a resource.
A field is readable when the role’s list allows it and the field’s own rule passes. Field lists take effect through the roles the server gets (the roles export of config/roles.ts, resolveAccess(source, ctx, { roles })), for every resource whatever its rules. A filter is the capability’s row filter, so like .own it applies where the capability decides: an operation without a rule, or a rule built with roles.can(...).
Several roles add up. A user gets every field one of their roles lists (all of them when a role holds the plain capability) and the rows any of their roles allows. Fields and rows add up separately: someone holding both erp_sync and reseller above reads name on unpublished products too. With Better Auth a session acts with one active role at a time, so this only comes up with an authenticator that hands out several.
Wildcards in has, can and holds
Section titled “Wildcards in has, can and holds”A wildcard in a role grants everything it stands for: *.read reads every resource, except those that hold secrets and take only named grants. What a check asks for is different, so the checks take wildcards in one place only:
roles.has(user, 'vms.update')androles.can('vms.update')ask for one capability, in any scope or limit the role holds it. They refuse a wildcard, at compile time and when called, sincevms.*would pass for a role holding onlyvms.read: ask for each capability instead.roles.holds(user, 'vms.*')asks for all of it, in every row and field: a role holding*orvms.*passes, one holdingvms.read,*.read,vms.update.ownor avms.updatelimited to fields or rows does not. A scope asks for those rows at least:orders.read.ownpasses for a role holdingorders.read.own,orders.reador*.read. API functions’capabilityis checked this way.
Resources that need named grants
Section titled “Resources that need named grants”A resource with .explicitGrants() is left out of wildcards over resources: only * itself and capabilities that name it, such as webhook_subscriptions.read or webhook_subscriptions.*, grant it, never *.read or *.*. A role written as “read everything” then reads nothing of it. The webhook resources are such resources, since their URLs and secrets let whoever reads them call the receivers. Mark a resource of your own this way when its records hold secrets.
defineRoles({ admin: ['*'], viewer: ['*.read'], // reads no webhook subscription integrations: ['*.read', 'webhook_subscriptions.*', 'webhook_deliveries.read', 'webhook_deliveries.update'],})Anonymous access
Section titled “Anonymous access”The role anonymous is what a request without a token acts as. A project without it answers such requests 401, as always.
anonymous: [{ 'products.read': { fields: ['name', 'slug', 'price', 'image'], filter: 'published = true' } }],- It reads listed fields, and creates them through a public form only. Each entry names one resource,
readorcreatewithout a scope, and its fields;defineRolesrefuses other capabilities, wildcards,.ownand.team, and a capability without a field list, so nothing becomes public by accident, a new column included. Acreateis used by the resource’s public forms alone, behind their rate limit and bot check: everywhere else it does not exist. - No token, not a bad one. A request without an
Authorizationheader is served as a caller holding only this role, in no organization. A header with anything but a valid, unexpired token is still a401.jwtAuthenticatorand the authenticator of the app’s sign-in tell the two apart; an authenticator of your own throwsMissingCredentials(from@protobase/server) for a request without a credential to do the same. - Only its capabilities open anything. The capability is ANDed into a resource’s access rule, so a rule that allows everyone (
read: () => true) ordefaultAccess: 'allow'never lets an anonymous caller in on its own. - The resources API and
/api/metaonly. Lists, records,:search,:seekand the aggregates of what the role reads, with filters, sorts andfieldschecked as for everyone: an unlisted field is refused like an unknown one. A resource it cannot read is a404; a write, or another operation it may not do on a resource it reads, is a401that asks for a token, acreateit holds for a form included./api/metadescribes what it reads, for the admin app./api/openapi.json,/api/docs, batch writes, API functions, the assistant and the file cleanup still need a token. A file field it reads comes with its link, as for anyone. - A tenant-scoped resource (
.tenant) cannot be in it, since an anonymous caller works in no organization; the server refuses to start. - Reading has no rate limit of its own: put a proxy or CDN in front of a public API to limit and cache requests. Public forms limit their submissions.
Browsing the admin app
Section titled “Browsing the admin app”With an anonymous role that reads a resource, GET /api/auth/status says "anonymous": true, and the admin app opens for someone who is not signed in instead of the sign-in page: the sidebar, lists, displays, filters and record pages of what the role reads, read-only, with the views and pages of the role anonymous (a view .forRoles(['anonymous']) is theirs alone). The sidebar has a Sign in button where the profile menu would be. It opens the sign-in route, /-/sign-in, a page of its own: the browser’s Back, or Continue without signing in, returns to browsing, and signing in comes back to the page it was opened from. Signing out returns to browsing. A link for the sign-in steps, such as a password reset, still opens its page. An anonymous role that only creates, for public forms, leaves the app behind sign-in.
Use cases
Section titled “Use cases”One shop’s catalog, read by its staff, by the warehouse system and by web store visitors. CI typechecks and tests the file:
import { defineRoles, f, resource } from '@protobase/schema'
// A shop's catalog, read by its staff, by the warehouse system and by visitors of the web store, who sign in to nothing.
export const roles = defineRoles<'products' | 'costs'>({ admin: ['*'], editor: ['products.read', 'products.create', 'products.update'], buyer: ['products.read', 'costs.read'], // The warehouse system reads three columns and changes one. A column added later stays hidden from it. erp_sync: [{ 'products.read': ['sku', 'price', 'stock'] }, { 'products.update': ['stock'] }], // Requests without a token: what the web store shows, of published products only. anonymous: [{ 'products.read': { fields: ['name', 'slug', 'price', 'image'], filter: 'published = true' } }],})
/** shop.products */export const products = resource('products') .table('shop.products') .fields({ id: f.integer().readOnly().filterable().sortable().dbDefault(), sku: f.text().filterable().sortable(), name: f.text().filterable().sortable(), slug: f.text().filterable(), price: f.decimal({ precision: 10, scale: 2 }).filterable().sortable(), // Whoever reads products, only roles holding `costs.read` see what one costs the shop. cost_price: f.decimal({ precision: 10, scale: 2 }).access({ read: roles.can('costs.read') }), stock: f.integer().filterable(), image: f.file().accept(['image/*']).public().optional(), published: f.boolean().default(false).filterable(), }) .primaryKey((r) => r.id) .search((r) => [r.name, r.sku])A public storefront catalog
Section titled “A public storefront catalog”The web store lists products without signing in:
curl 'https://shop.example.com/api/v1/products?order_by=name&page_size=20'Each item has id, name, slug, price and image, of published products only: a draft’s URL is a 404. filter=cost_price < 10 or order_by=stock is a 400, worded as an unknown field, and a PATCH without a token is a 401. The staff sign in as before and see what their roles allow. A column added to shop.products later, such as a supplier, stays off the store until it is added to the list.
An integration limited to some columns
Section titled “An integration limited to some columns”erp_sync is a role for a system: a user with that role, and a token for it (issueToken). It reads sku, price and stock of every product and writes only stock; a PATCH with price is a 400, as for a field it cannot see, and cost_price is not in its responses. A role that only uses the API needs no view: views shape the admin app, while what a caller may see and do is decided here.
Field rules or field lists
Section titled “Field rules or field lists”A field rule goes from the field to the roles: cost_price above is hidden from every role that reads products but those holding costs.read. Use it for the few sensitive columns of a resource that many roles read, such as a screening result (f.text().access({ read: roles.can('screening.read') })). A field list goes from the role to the fields: use it for a role that should see only some columns, such as an integration or anonymous visitors, so a new column stays hidden from it. When both apply, a field needs both.
A field that shows what another resource holds, such as a summary of a project’s invoices, can follow who reads that resource: a field rule gets ctx.holds(capability), which is true when one of the caller’s roles holds the capability on every row and field, such as invoices.read but not invoices.read.own or a limited one. A wildcard over resources such as *.read does not count, as on a resource with .explicitGrants(); without roles, it gives what an operation without a rule gets.
invoiced: f.decimal({ precision: 12, scale: 2 }).readOnly().access({ read: (ctx) => ctx.holds?.('invoices.read') ?? false })Write-only fields
Section titled “Write-only fields”A role writes a field it cannot read only when the field’s own create or update rule allows it: f.text().access({ read: roles.is('loop'), create: roles.is('admin'), update: roles.is('admin') }) lets admin set a value only loop reads. A write rule the field follows from its resource never does, so hiding a field from a role does not let everyone who updates the resource overwrite it. The value is in no response, history, export or webhook of the writer, and no reveal shows it to them. /meta gives the writer the field marked writeOnly: true, sensitive and neither filterable nor sortable, and keeps it in the view’s record sections and field hints only, so the admin app edits it only where a section of the layout names it: as a password-style input to type a new value in, with no stored value or eye to reveal one, never kept in a form’s unsaved changes, and nowhere on the read view. The record’s permissions.fields lists it as edit where the writer may update it. A file field, or the field a resource orders its records by (.position()), is never write-only, and no reorder orders by a write-only field.
Records that belong to another
Section titled “Records that belong to another”A record often belongs to another one through a relation, such as an operation to the VM it runs on, and who may write it follows from who may change that VM. .parent((r) => r.vm_id, 'update') says so: writing an operation needs update on the record vm_id points at, 'read' needing only to see it, as for a comment on a ticket. A member below may run operations on their own VMs only, with no rule of your own:
import { defineRoles, f, resource } from '@protobase/schema'
// Virtual machines and the operations run on them: a member creates an operation only on a VM they may update.
export const roles = defineRoles<'vms' | 'operations'>({ admin: ['*'], member: ['vms.read', 'vms.update.own', 'operations.read', 'operations.create'],})
/** virt.vms, each owned by the user who made it. */export const vms = resource('vms') .table('virt.vms') .fields({ id: f.integer().readOnly().filterable().dbDefault(), name: f.text().filterable(), owner_id: f.text().readOnly().filterable(), }) .primaryKey((r) => r.id) .owner((r) => r.owner_id)
/** virt.operations: writing one needs `update` on the VM its `vm_id` points at. */export const operations = resource('operations') .table('virt.operations') .fields({ id: f.integer().readOnly().filterable().dbDefault(), vm_id: f.relation('vms').filterable(), kind: f.enum(['start', 'stop', 'reboot']), }) .primaryKey((r) => r.id) .parent((r) => r.vm_id, 'update')- Every write is checked. Creating a record checks the parent it names; changing it, the parent it points at and the one it moves to; deleting and undeleting it, the parent it points at. So a record cannot be created under an allowed parent and then moved under another. It holds for
/api/v1and its batches, and for everything that writes through them: forms, API functions and the assistant. - The caller’s own rules decide. The parent is read as the caller would read it, with its tenant, row filters, soft delete and record-level rules; for
update, also its update row filter and record-level update rule, given an empty input. A parent the caller cannot see, may not update, that is soft deleted or does not exist gets the same403as a refused create (You may not create this operations record), and nothing is written: the answer does not tell which VM ids exist. - One column, to a key of one field.
A relation of several columns cannot be a parent: the config does not load with one. The server does not start with a parent resource the app does not have.A resource whose key has several fields cannot be a parent: the server does not start with one. - A null relation checks nothing. A relation set by a column default or a trigger is checked from the record as written.
updatefollows the parent’s own parents, so with VMs under.parent((r) => r.folder_id, 'update')an operation needs update on the VM’s folder too. A write that would put a record under itself, or under a cycle already in the data, is refused. Areadparent is followed only as far as reading it does (below).readalso narrows every read. With.parent((r) => r.channel_id, 'read'), a caller reads only the messages of channels they read: lists,:searchand:seek, their counts, facets, charts and aggregates, a get (404outside, as for a row filter), relation labels, history, comments and reveals, through/api/v1, its batches and MCP, and the deliveries of a subscription that runs as a role. The parent is read with the caller’s own tenant, row filter and soft delete there, and its ownreadparents, so a channel whose members are listed in amember_idsJSON field with the read rulewhere.or(where.eq('kind', 'public'), where.has('member_ids', ctx.user.id))keeps its messages to its members, and taking someone offmember_idshides them on the next read. A message with a nullchannel_idnames no channel and stays visible under its own rules, so a message with two nullable parents,channel_idordirect_message_id, keeps to the one it names.- One indexed subquery. The narrowing is
channel_id in (select id from channels where <the caller's channel filter>)ANDed into the child’s query (channel_id is null or ...for a nullable relation), so the scan guard needs an index onchannel_idand indexes serving the columns of the parent’s row filter, such as a GIN index onmember_ids, andprotobase doctornames a missing index on the relation. - A parent whose read rule reads the record hides its children. Such a rule is no filter a query can hold, so a caller whose read rule on the parent needs the record, or who cannot read the parent resource, reads only the children with a null relation.
A child under a parent whose read rule reads the record cannot be read because checking the parent per record is not implemented. Make the parent’s read rule return a row filter instead. A resource that is its own parent, such as a folder tree, is checked one level up: a folder needs its parent folder readable, and that folder is read with its otherreadparents too. So a reply under.parent((r) => r.thread_id, 'read')and.parent((r) => r.channel_id, 'read')whosechannel_idis null keeps to the channel of the message it answers.A record of a tree cannot keep to every ancestor because a transitive parent check is not implemented. - Across organizations, the session’s own only.
A list across organizations cannot read a resource with a The server warns at startup and lists the session’s organization alone.readparent beyond the session’s own organization because resolving the parent in each organization is not implemented. - Several parents are each checked with their own access, also two of one resource, such as a transfer that reads its
source_vm_idand updates itstarget_vm_id. - The parent is locked until the write commits (
FOR NO KEY UPDATE), so a VM handed to someone else or deleted at the same moment is waited for and checked again. That is the cost: writes of records under one parent, and through anupdateparent under one ancestor, run one after another. The server’s database role needsUPDATEon the parent’s table to take the lock. Two writes that lock the same records in opposite orders, such as two batches writing under VM A then B and B then A, can deadlock: Postgres rolls one back, which answers409and writes nothing, and the client sends it again. - The record page and
/api/metacount the check, so the admin app offers no Edit or Delete the server would refuse./api/sb/rest/v1does not use Protobase’s access rules at all, so this check is not part of it.
Related records in filters
Section titled “Related records in filters”A list’s filter can reach through other records with related(field, resource.key, (subfilter)). It may do only what the caller could do in two steps, listing resource with the subfilter and then filtering with in(field, ...), so it never tells a row or field they cannot read.
- The caller’s list of
resource. The term is one more condition on the read, and its subquery is that list: their tenant, row filter, soft delete andreadparents there. The outer list’s own tenant and row filter stay, so a term can only remove rows.show_deletedreaches the outer rows only. - The caller’s fields. The subfilter and
keyare checked against the resource as the caller sees it, so a hidden, sensitive or write-only field is refused like an unknown one, andsearch("text")in a subfilter reads only the search fields they read. - Nothing about what they cannot list. A resource that does not exist, one they cannot list, one whose
readorlistrule reads the record, a tenant-scoped one for a caller without a tenant, a wrongkey, and fields that do not point at one resource all answer the same400Unknown field. A term in the wrong place or over the limits is refused before any of that is looked at. - The session’s own organization. A term reads that organization alone, and a list across organizations with a term falls back to it too.
A link record the caller reads can narrow a list by a record they cannot read: with related(project_id, memberships.project_id), a ticket matches through a membership of a project hidden from them, because they could read that membership and that ticket anyway. Going through projects instead, related(project_id, projects.id), keeps to the projects they read. total_size_estimate comes from the planner’s statistics of the whole table, as on any list.
A list under a record, /objectives/40/tasks, is stricter, since its address names one record: the parent is read first as the caller would read it, and a parent they cannot read answers the same 404 as one that does not exist.
Only a read of the API resolves related(): access rules, role filters and the other places a filter is stored refuse it. related() in rules is not implemented.
Lists across organizations
Section titled “Lists across organizations”With organizations, a session works in one organization and a .tenant resource shows only its rows. A resource whose tenant is declared with across: 'memberships' lists the rows of every organization the person is a member of instead, so one list shows, say, their apps in each:
export const apps = resource('apps') .table('platform.apps') .fields({ id: f.uuid().filterable(), organization_id: f.relation('organizations').filterable(), name: f.text() }) .primaryKey((r) => r.id) .tenant((r) => r.organization_id, { across: 'memberships' })- Lists only. A list,
:searchand:seek, their counts, facets, charts, groups, map and exports read across; the labels and photos they bring are read as their own resource lists, so across when it is declared so too. Reading one record, revealing a field, its history and comments, and every write (creates, updates, deletes, batches, imports and uploads) stay in the organization the session works in: a record of another one is a404there, and a create sets the session’s organization, as before. - Each organization with the person’s role there. The rows of another organization are read with the role the person would act with there after a switch: the session’s active role when they hold it there, globally or as a member, else their first role there. Its row filters apply to its rows only. An organization where that role cannot list the resource is left out, and so is one where it reads fewer of the resource’s fields than the session’s role, since the list shows the same fields for every row.
- Members only. An organization someone enters with a global role, without being a member, is not read across; the session’s own organization always is. An outside app’s token, such as an MCP client’s, reads its own organization alone.
- The tenant field is a filter. The list has it as any other field, so
organization_id = "...", a facet or a column picks organizations. A caller who cannot read the tenant field lists their own organization alone. To open the sidebar entry on the current organization, which the person can then clear, see The current organization. - Rows of another organization are read-only in the list. Their
permissionssayupdate: falseanddelete: false. The admin app opens one by switching the session to its organization first: a record page the session’s organization does not have looks the record up across the lists, for a resource with a key of one filterable field, so the page and everything on it are read in the record’s own organization. - Where the memberships come from. The authenticator of the app’s sign-in (
auth) reads them from the store, once per request that lists across organizations. An authenticator of your own gives them as the session’smemberships, a function answering[{ tenant, roles }], and must answer only organizations the person is a member of. Without it, as withauthenticate: { jwksUrl }instead ofauth, a list reads the session’s organization alone.
Rules that read the record
Section titled “Rules that read the record”A rule that reads its record, such as read: (ctx, record) => record.owner_id === ctx.user.id, is checked against the stored row wherever one record is read or written: a get, a reveal, history, comments, and every update and delete. The resolver calls each rule once without the record to learn whether it needs one; reading the record then, even as record?.status or through a default parameter, counts.
A list cannot run such a rule on each row without breaking its pages and counts, so a caller for whom the read or list rule reads the record may not list: a list, :search, :seek, their counts, aggregates, charts and map, exports, the labels of the records other lists point at, and the assistant’s and MCP’s list tool answer 403, and a blocked delete does not name the resource. An explicit list rule beside such a read is refused too, since nothing proves it is as narrow. A caller whose verdict does not depend on the record, such as an admin under ctx.user.roles.includes('admin') || record.owner_id === ctx.user.id, lists as usual. To list, write the rule as a row filter, which a get and a list apply alike:
.access({ read: (ctx) => where.eq('owner_id', ctx.user.id) })/api/v1 and what is built on it; /api/sb/rest/v1 and its realtime use the tables’ grants and RLS policies only.
Restricted model and row filters
Section titled “Restricted model and row filters”resolveAccess returns everything a request may do. Use restrictModel(model, access) for everything user-facing (checking filters and sorts, queries, OpenAPI, /meta): hidden fields are gone, so they cannot be referenced, searched, sorted or leaked. Key columns always stay, because records are addressed by them.
Row filters (access.rowFilter) are a separate thing. They come from the access rules (.own, .team, filters of capabilities, returned filters), are checked against the full model because they may use hidden or non-filterable columns, and are ANDed into queries by the server.