tutorials
How to add role-based access to a shared team inbox
October 28, 2026

A shared inbox where everyone can do everything is fine for two people and a liability for ten. The moment a contractor can send as your company or read billing replies, you need real access control, not hidden buttons.
Role-based access is one of the things that separates a toy shared mailbox from a real one; the features a self-hosted team inbox should have puts it alongside the rest of the list, and for teams in regulated environments the reasons regulated teams self-host their email explains why owning the audit trail matters even more.
What does role-based access for a shared inbox actually require?
It requires two separate decisions on every request: what the person is allowed to do, and which inbox they are allowed to do it to. These are orthogonal. A support lead might be an admin on support@ and have zero access to careers@. If you collapse them into one global "role" column, you will rebuild the whole thing the first time a client asks for an inbox a junior agent should not see.
So model two axes:
- Roles (a strict ladder):
viewer < agent < admin. A higher role implies every lower role's actions. This answers "what can they do". - Grants (per inbox): a row that says "this user has this role on this inbox". This answers "which mail can they touch".
Everything below builds those two axes by hand on Cloudflare D1 and Workers, routes every action through a single gate, then shows the mistakes that quietly break naive implementations. At the end, if you would rather not own this code, Tinbox ships exactly this model.
How do I design the roles so they do not sprawl?
Keep the ladder tiny and make it strict, so rank comparison replaces a tangle of if checks. Three roles cover the vast majority of shared-inbox teams:
// roles.ts: the whole authorization vocabulary in one file.
/** Logical roles, low -> high. The index IS the rank. */
export type Role = "viewer" | "agent" | "admin";
const ROLE_RANK: Record<Role, number> = { viewer: 0, agent: 1, admin: 2 };
/** Actions, each mapped to the MINIMUM role that may perform it. */
export type Action = "read" | "draft" | "reply" | "archive" | "manage_grants";
const ACTION_MIN_ROLE: Record<Action, Role> = {
read: "viewer", // see threads, messages, attachments
draft: "agent", // write a reply draft
reply: "agent", // actually send a reply
archive: "agent", // archive a thread
manage_grants: "admin", // invite, grant, revoke on this inbox
};
export function roleSatisfies(have: Role, need: Role): boolean {
return ROLE_RANK[have] >= ROLE_RANK[need];
}
Two design rules earn their keep here. First, the ladder is structural: you never write if (role === "admin" || role === "agent"), you compare ranks. Adding a role later is a one-line table edit, not a search-and-replace across the codebase. Second, anything that does not fit a ladder (a marketer who can send newsletters but is otherwise just an agent) does not become a new role. It becomes a separate additive capability, which we cover near the end. Roles that try to encode every special case are how you end up with agent_plus_newsletter_no_billing.
How do I store grants per inbox in D1?
Use a grants table keyed by user and inbox, with the role on the row. The inbox scope lives in the row, not in the role string.
-- schema.sql
CREATE TABLE grants (
user_id TEXT NOT NULL,
inbox_id TEXT NOT NULL,
role TEXT NOT NULL CHECK (role IN ('viewer','agent','admin')),
created_at INTEGER NOT NULL,
PRIMARY KEY (user_id, inbox_id)
);
-- The hot path is "what role does THIS user have on THIS inbox", so the
-- composite primary key already indexes it. Add the reverse for admin UIs
-- that list everyone on an inbox.
CREATE INDEX grants_by_inbox ON grants (inbox_id, role);
A user with no row for an inbox has no access to it at all. That is the default-deny you want: access is something you explicitly grant, never something a user has until you remember to take it away.
How do I write the one access gate every action calls?
Put the entire decision in a single async function and call it at the top of every handler. There must be no side door that reads mail without going through it.
// authorize.ts
import { eq, and } from "drizzle-orm";
import { grants } from "./schema";
export interface AuthResult {
ok: boolean;
role: Role | null;
reason?: "no_grant" | "insufficient_role";
}
export async function authorize(
db: D1Database,
userId: string,
inboxId: string,
action: Action,
): Promise<AuthResult> {
const row = await db
.prepare("SELECT role FROM grants WHERE user_id = ? AND inbox_id = ?")
.bind(userId, inboxId)
.first<{ role: Role }>();
if (!row) return { ok: false, role: null, reason: "no_grant" };
const need = ACTION_MIN_ROLE[action];
if (!roleSatisfies(row.role, need)) {
return { ok: false, role: row.role, reason: "insufficient_role" };
}
return { ok: true, role: row.role };
}
Now wire it into a handler. The critical detail: the userId comes from the authenticated session, and the action is fixed by the route. Neither is taken from the request body.
// POST /inboxes/:inboxId/reply
app.post("/inboxes/:inboxId/reply", async (c) => {
const userId = c.get("session").userId; // from auth, not the body
const inboxId = c.req.param("inboxId");
const auth = await authorize(c.env.DB, userId, inboxId, "reply");
if (!auth.ok) {
return c.json({ error: "forbidden", reason: auth.reason }, 403);
}
const { body } = await c.req.json<{ body: string }>();
await sendReply(c.env, inboxId, body);
return c.json({ ok: true });
});
A viewer hitting this route gets a clean failure, and the failure mode is explicit enough to debug:
{ "error": "forbidden", "reason": "insufficient_role" }
That reason field matters in practice. "Forbidden" with no detail sends you on a 30-minute hunt; no_grant versus insufficient_role tells you immediately whether the user was never invited to the inbox or just lacks the rank for this one action.
What are the mistakes that quietly break inbox RBAC?
These are the bugs that pass code review and surface in production.
Trusting a role from the request body. This is the cardinal sin:
// WRONG: the client decides its own role.
const { role } = await c.req.json();
if (role === "admin") { /* ... */ }
Anyone with curl sends {"role":"admin"} and owns your inbox. The caller's role must be looked up server-side from the grants table, keyed by the authenticated user id. The client never names its own role for an action.
Letting role assignment skip the gate. The endpoint that changes roles is itself an action (manage_grants, admin-only). If you forget to authorize it, an agent promotes themselves:
// POST /inboxes/:inboxId/grants
app.post("/inboxes/:inboxId/grants", async (c) => {
const userId = c.get("session").userId;
const inboxId = c.req.param("inboxId");
const auth = await authorize(c.env.DB, userId, inboxId, "manage_grants");
if (!auth.ok) return c.json({ error: "forbidden" }, 403);
const { targetUserId, role } = await c.req.json<{ targetUserId: string; role: Role }>();
await c.env.DB
.prepare("INSERT OR REPLACE INTO grants (user_id, inbox_id, role, created_at) VALUES (?,?,?,?)")
.bind(targetUserId, inboxId, role, Date.now())
.run();
return c.json({ ok: true });
});
Locking yourself out of an inbox. If the last admin can demote or remove themselves, the inbox becomes unmanageable: nobody can ever grant access again. Guard it:
async function ensureNotLastAdmin(db: D1Database, inboxId: string, userId: string) {
const { count } = await db
.prepare("SELECT COUNT(*) AS count FROM grants WHERE inbox_id = ? AND role = 'admin'")
.bind(inboxId)
.first<{ count: number }>();
if (count <= 1) {
throw new Error("cannot remove the last admin of an inbox");
}
}
Forgetting attachments. A thread might be gated, but the signed URL that serves an attachment often is not, because it lives on a different route. An attachment must never be more accessible than the message it belongs to. Route attachment fetches through the same authorize(..., "read") check against the inbox the attachment's message belongs to.
Hiding buttons and calling it done. Disabling a "Reply" button in the UI for viewers is good UX and zero security. The server check is the only one that counts. Build the gate first, then hide buttons for polish.
How do I handle the cases a role ladder cannot express?
Add a second, additive axis: capabilities. Some permissions are not "more powerful versions of read", so they do not belong on the ladder. The classic example is sending a newsletter: a marketer might be otherwise just an agent, but allowed to dispatch campaigns from the inbox, while a senior support admin is not.
// capabilities.ts: orthogonal, additive verbs granted explicitly.
export type Capability = "newsletter:send" | "api:send";
// A capabilities table mirrors grants: (user_id, inbox_id, capability).
// authorizeCapability() checks for the row directly, bypassing the role ladder.
export async function authorizeCapability(
db: D1Database, userId: string, inboxId: string, cap: Capability,
): Promise<boolean> {
const row = await db
.prepare("SELECT 1 FROM capabilities WHERE user_id = ? AND inbox_id = ? AND capability = ?")
.bind(userId, inboxId, cap)
.first();
return !!row;
}
Roles stay a clean ladder; capabilities handle the exceptions. Resisting the urge to fold every exception into a new role is what keeps the model legible after a year.
There is usually a third axis too, above the inbox: an organization level that decides who can configure the deployment itself (manage users, domains, API keys, billing). That is separate from "can read support@'s mail" and is worth keeping orthogonal for the same reason. If you are designing the whole stack, see how to design a D1 schema for an email inbox for where these tables sit relative to threads and messages.
Or skip all of this: role-based access in Tinbox
If you would rather not own three authorization tables, a gate, and the edge cases above, this is exactly the model Tinbox ships. It runs entirely on your own Cloudflare account (D1 plus Workers), and the two-axis design is already wired through every API path, so there is no side door to forget.
In Settings -> People you assign roles and group people into teams:
- Org roles form the ladder
owner > admin > manager > user, gating who can configure the deployment, with additive product areas (Lists, Developer API) for the marketer-versus-developer split. - Per-inbox grants decide which mail each person sees, with roles
viewer < agent < admin, exactly as above. - Teams let you grant a whole group access to an inbox at once, so onboarding a new support hire is one click, not a per-inbox grant loop.
Every read, draft, reply, and attachment fetch funnels through one authorize() call, and org-config actions through authorizeOrgAction(), so an attachment is never more reachable than the message it belongs to. Inviting a member scopes them to a specific inbox with a specific role from the start:
# Deploy the whole stack, RBAC included, on your own Cloudflare account.
npx tinbox init example.com
Then open Settings -> People, invite a teammate to an inbox, and pick their role. No tables to migrate, no gate to audit. If you also want an AI agent acting inside these boundaries, the same grants apply: see letting an AI agent send email without it going rogue for how a send tool stays inside its permissions. And if you are weighing a hosted shared-inbox product against owning it, the self-hosted shared inbox comparison lays out the tradeoffs.
The roles, grants, and capabilities live in your D1 database, readable and exportable, not behind a vendor's admin panel.
Deploy this yourself: npx tinbox init <domain>. The People and roles settings, and the authorize() gate behind them, are documented in the Tinbox docs under access control.
Frequently asked questions
What roles does a shared team inbox actually need?
Three are enough for most teams: viewer (read threads, no sending), agent (read, draft, reply, archive), and admin (everything plus inviting and revoking people). Keep the role list a strict ladder where a higher role implies every lower role's actions, then add fine-grained capabilities (like newsletter:send) separately for the handful of cases roles cannot express.
What is the difference between roles and per-inbox grants?
Roles answer what a person can do (read vs reply vs manage). Grants answer which inboxes they can touch at all. They are orthogonal: a person can be an admin on support@ and have no access to billing@ whatsoever. Model them as two separate axes so you can change one without rewriting the other.
Where should the access check live?
Server-side, in one function every action calls before doing work: authorize(db, user, inboxId, action). The client may hide buttons for UX, but the only check that counts runs on your Worker or API before it reads a message or sends a reply. A hidden button is not access control.
How do I stop a user from escalating their own role?
Never accept the role from the request body when performing an action. Look the caller's role up from the database keyed by their authenticated user id. Only an admin-gated endpoint may write roles, and it should refuse to let the last admin demote themselves so an inbox cannot be locked out.
Can I add role-based access to a shared inbox without building it myself?
Yes. Tinbox ships a two-axis RBAC model (org roles plus per-inbox grants, with teams for group access) and exposes it in Settings -> People. You assign roles in the UI and every API path is already routed through one authorize gate. Deploy it with npx tinbox init <domain>.