Policy and roles
Name every action once, say which roles may do it, what agents may do on their own, and which actions signed-out visitors may call.
The policy is one object of plain data. Convex functions, the consent page and the browser read the same object, so they cannot disagree.
import { definePolicy } from '@lupinum/better-convex-functions/policy'
export const policy = definePolicy({
actions: [
'projects.list',
'projects.create',
'projects.rename',
'projects.archive',
'projects.summarize',
'clients.create',
'members.list',
'pages.read',
'pages.edit',
],
roles: {
owner: ['*'],
member: [
'projects.list',
'projects.create',
'projects.rename',
'projects.summarize',
'clients.create',
'members.list',
'pages.*',
],
viewer: ['projects.list', 'members.list', 'pages.read'],
},
scopes: {
'projects:read': { label: 'See your projects.', actions: ['projects.list'] },
'projects:write': {
label: 'Create, rename and archive projects. Archiving waits for your approval.',
actions: ['projects.create', 'projects.rename', 'projects.archive'],
},
'pages:write': {
label: 'Edit pages. Publishing waits for your approval.',
actions: ['pages.edit'],
},
},
agents: {
'projects.create': 'allow',
'projects.rename': 'allow',
'projects.archive': 'approve',
// Drafts are fine; publishing waits for a person.
'pages.edit': (input) => (input.status === 'published' ? 'approve' : 'allow'),
'clients.create': 'deny',
},
// Besides the person the agent acts for, an owner of the organization may decide.
approvers: { 'projects.archive': ['owner'] },
public: ['pages.read'],
})The fields
| Field | What it says |
|---|---|
actions | Every action of the application. A name that is not in this list is a type error everywhere else |
roles | What each role may do. '*', 'projects.*' and exact names match |
scopes | What a person grants an AI host, with the text the consent page shows |
agents | What an agent may do on its own: 'allow', 'approve' or 'deny'. Without an entry, a query is 'allow' and a call that changes data is 'approve' |
approvers | Roles in the call's tenant that may decide an agent's request, besides the person it acts for. { roles, sharedRows: true } adds the other tenant of rows the agent changes |
public | Actions that signed-out visitors may call. Row rules still decide which rows they see |
Roles come from your data. roleOf in defineFunctions returns the role of a
user in one tenant, or null without a membership. A role name that is not a
key of roles allows nothing, also names such as toString or __proto__.
roleOf and user get a context that only reads: they decide, they do not
change data.
A call whose input names no tenant gets its role from roleOf(ctx, user, null):
the role a person has outside any tenant. null refuses the call, unless its
action is public. What every signed-in person may do (create an organization,
list their own organizations) is a role too, for example signedIn:
roles: {
signedIn: ['organizations.create', 'organizations.list'],
owner: ['*'],
member: ['projects.create', 'projects.rename'],
},roleOf: async (ctx, user, tenant) => {
if (tenant === null) return 'signedIn'
// the membership lookup for a tenant
},An application with one workspace and no tenant tables returns the member's role
for null, and the library checks it on every call, so no handler has to. Answer
null for a tenant you do not handle, so a tenant table added later cannot
inherit the workspace role:
roleOf: async (ctx, user, tenant) => (tenant === null ? user.role : null),How one call is decided
A call is allowed when every layer allows it:
- Role. The caller's role where the call acts allows the action: the
role in the tenant the input names, or, when it names none, the role outside
any tenant (
roleOf(ctx, user, null)). No role refuses the call. A public action skips this layer. The row rules then check every row the call touches. - Scope (agents only). One of the scopes the person granted includes the action.
- Agent rule (agents only).
allowruns the call,approveholds it for a person,denyrefuses it. An action without a rule runs when it only reads (a query) and waits for a person when it changes data (a mutation, an action or an internal mutation). So a write action you add to a scope later never runs on its own until you give it'allow'.
A person never needs approval. The rules in agents hold only for agents.
An agent rule can read the call's input. If the function throws, for example
on input it did not expect, the call waits for a person. A query cannot wait,
so its agent rule must be 'allow' or 'deny'; 'approve' on a query is an
error when the module loads.
Public actions and visitors
A visitor is a caller without a session. A visitor reaches only the actions in
public. Every other action fails with NOT_SIGNED_IN. In a public operation,
ctx.actor can be { kind: 'visitor' }, so the type makes you handle it
before you read ctx.actor.user.
import { v } from 'convex/values'
import { mutation, query } from './functions'
/** Anyone may read a published page. The index condition matches the publicRead rule. */
export const published = query({
action: 'pages.read',
args: { organizationId: v.id('organizations'), slug: v.string() },
returns: v.union(v.null(), v.object({ title: v.string(), body: v.string() })),
handler: async (ctx, { organizationId, slug }) => {
const page = await ctx.db
.query('pages')
.withIndex('by_org_status_slug', (q) =>
q.eq('organizationId', organizationId).eq('status', 'published').eq('slug', slug),
)
.unique()
return page && { title: page.title, body: page.body }
},
})
export const edit = mutation({
action: 'pages.edit',
// `pages` has an anyOf rule, so the call names its tenant itself.
args: {
organizationId: v.id('organizations'),
pageId: v.id('pages'),
body: v.string(),
status: v.union(v.literal('draft'), v.literal('published')),
},
returns: v.null(),
tool: {
name: 'edit_page',
description: 'Change the text of a page. Keep it a draft, or publish it.',
},
plan: async (ctx, { pageId, status }) => ({
summary: `${status === 'published' ? 'Publish' : 'Edit'} the page "${(await ctx.db.get(pageId))?.title}".`,
}),
handler: async (ctx, { pageId, body, status }) => {
await ctx.db.patch(pageId, { body, status })
return null
},
})Check a permission in the browser
can(policy, action, role) gives the same answer as the server for a person
with that role. Use it to hide a button. It is not a security check: the
operation checks again.
Import it, definePolicy and consentScopes from
@lupinum/better-convex-functions/policy in code the browser loads. That
entry imports nothing from Convex's server code; the root entry does.
import { can, type RoleOf } from '@lupinum/better-convex-functions/policy'
import { policy } from '../../convex/policy'
export type Role = RoleOf<typeof policy>
/** Shows the archive button only to roles that may archive. */
export function canArchive(role: Role | null) {
return can(policy, 'projects.archive', role)
}The role itself comes from your data, for example a query that returns the user's organizations with their role in each.
Scopes and consent
consentScopes(policy) turns scopes into the list that the MCP OAuth profile
expects. Pass it to oauth.mcp.scopes in createBetterConvexAuth, as in
Start here. A host sees
only the tools whose actions its granted scopes include.
A scope is a ceiling. It never adds a permission that the person's role does not have.