Tenant-backed Scope Kinds
Scope kinds whose admission runs inside the organization Durable Object — requirements, qb.admitScope, server-issued grants, tenant namespaces and namespace actions.
An instance-bound OAuth scope kind whose admission program reads one organization object is tenant-backed: its admission, grants and namespace routes run inside that organization's Durable Object and never read the platform D1. This page covers which kinds qualify and how their routes and actions run. Start at Database per Tenant for the model.
Tenant-backed scope kinds
An instance-bound OAuth kind (authz.scopes.<kind>.oauth) whose whole
admission program reads one organization object is tenant-backed: its
admission, its namespaces and its tickets run in that object, and its tables
never exist in the platform D1. Every compile decides this from the
requirements in Which kinds can be tenant-backed;
there is no switch. A tenant-backed kind gets this identity contract:
- Pinned grant references. An instance-bound OAuth grant stores
qb2:<kind>:<tenantId>:<instanceId>:<mode>:<epoch>[:<ceiling>]instead of<kind>:<id>.modeisdiscover(the authorize flow: any of the kind's roles) orexact(issueScopeGrant: only the URI-encoded{ roles, subjectId, provingTable }ceiling). A reference parses only in its one canonical spelling. An exact reference withoutprovingTablefails refresh withinvalid_grant(reauthorize); the table is never guessed. An older unpinned grant for the kind fails refresh withinvalid_grant, so the user reauthorizes. The compiler never guesses a tenant for it. - Where the tenant comes from. At authorize it comes from the kind's
lookup (
tenancy.lookups.<kind>), never from the caller's active organization or the request. If the lookup matches several organizations, the request fails withinvalid_request. If it has no row yet, the request fails withtemporarily_unavailable(retry).issueScopeGrantalso accepts atenantHint, the organization that trusted server code read from the credential row. The hint is used only while the lookup has no row. A lookup that disagrees with it refuses. Once issued, a grant always routes to its pinned tenant, even if the lookup changes later. - Authorization epoch. The grant pins the tenant's
authorization epoch, read with the
qb.epochtenant command. Every code exchange and refresh compares it with the current epoch. After a restore they differ, and the grant fails withinvalid_grant, so the user signs in again. - v2 claims. The
qb_scopeclaim gainsv: 2,tenantIdandepoch(andprovingTablefrom admission). The bound lane refuses a token for a tenant-backed kind without them (401).ctx.oauth.boundTobecomes{ kind, id, tenantId, epoch }, and the edge routes the request toboundTo.tenantId. It never uses a lookup oractiveOrgIdfor that token. - Revocation. For a tenant-backed kind,
revokeScopeGrantrequires thetenantIdthe grant pins. It deletes the user's pinned grants for that instance in both modes, at every epoch and under any tenant. Instance ids are collision-resistant, so this also catches a grant pinned through a wrong hint. User-wide revocation (ban, sign-out everywhere) deletes the kind's pinned and unpinned grants. - Kind names.
qb2is reserved as a scope kind name in every project. A tenant-backed kind's name must be an identifier, because it is a segment of its grant references. - Realtime. Rooms on tenant tables become
t1:<tenant>:<key>, and the kind's identity tags becomet1:<tenant>:scope:<kind>:<provingTable>:<subjectId>. See Durable Objects → Tenant rooms. - Id contract. The kind's instance table and each role's proving table
need server-generated, collision-resistant ids across every tenant object.
The build fails with
TENANCY_ADMISSION_ID_STRATEGYwhen the table hasgenerateId: false | 'short' | 'serial',allowClientIds: true, or a numeric primary key.
Which kinds can be tenant-backed
The compiler plans each scope kind's admission program: the instance read plus one probe per role, in the kind's declared precedence. An OAuth kind can run that program, and every other path it has, inside its tenant object only when all of these hold. The first three are permanent: those paths never run in a tenant object. A kind reading a tenant table that misses any of them fails the build with each missing requirement under its own code:
| Code | Requirement |
|---|---|
TENANCY_LEGACY_SCOPE_ENTER | The kind declares oauth. A tenant-backed kind is admitted only through instance-bound OAuth; a kind without oauth has no tenant-pinned admission path. |
TENANCY_ADMISSION_SELF | No role declares self: { table }. The ctx.self recheck runs on every edge action route. |
TENANCY_ADMISSION_HOPS | No role proves through a relationship with hops. Tenant admission proves the relationship's own table. |
TENANCY_ADMISSION_MIXED_PLACEMENT | Every table the kind reads (instance, relationship tables and hops, self.table) lives in the tenant object. None on the platform. |
TENANCY_ADMISSION_PARTITIONED | None of them lives in a partition. |
TENANCY_ADMISSION_UNRESOLVED_INSTANCE | The instance table resolves to exactly one table. Set authz.scopes.<kind>.instance. |
TENANCY_ADMISSION_TENANT_COLUMN | The instance table and every proving table have an organization column. |
TENANCY_ADMISSION_LOOKUP | tenancy.lookups.<kind> indexes the instance table's primary key: { table: '<instance>', column: '<pk>' }. |
TENANCY_ADMISSION_SQL_HELPER | No role proves through a SQL helper (Postgres). |
Every error lists all the violations at once. A kind that meets them all is tenant-backed in every compile.
Tenant admission (qb.admitScope)
For a tenant-backed kind, the edge never reads the kind's tables. Every
admission (authorize, code exchange, refresh, issueScopeGrant, the bound
ws-ticket mint) goes through the generated dispatcher src/lib/scope-admission.ts.
Platform kinds keep their D1 evaluator there. A tenant-backed kind sends one
qb.admitScope command to the pinned tenant. The object
runs admitLocal (src/tenant/scope-admission.ts) in one synchronous SQLite
read, under the restore permit:
- The request's epoch must equal the permit's epoch (
SCOPE_EPOCH). - The instance row, read through its own firewall with tenant scopes stripped
(soft deletes still apply), must exist once and belong to this tenant
(
SCOPE_NOT_FOUND). - Each role is probed in precedence order, with the same
predicates the D1 evaluator uses. An exact ceiling probes only its own roles
on its own proving table, with
id = subjectId. A row whose organization is not the tenant never matches, even if it was copied in. - The first role with any match chooses the subject
(provingTable, id). Two rows on that role deny the admission (SCOPE_AMBIGUOUS). Every later role probes only the chosen row, so a later role's duplicate rows never deny. The reply carries only that subject's roles and sub-keys, plusprovingTable. It never unions roles across subjects.
The edge checks every reply field against the request: kind, instance,
tenant, epoch, known roles on one proving table, the ceiling's subject, roles
and table, and declared sub-keys only. A reply that disagrees is treated as
unavailable, never as an admission. Errors map like this:
| Outcome | At authorize | At code exchange / refresh | ws-ticket (bound or session) |
|---|---|---|---|
| denied | access_denied | invalid_grant | 403 |
| unavailable (archived, purged, restoring, migrating, unreachable) | temporarily_unavailable (503) | temporarily_unavailable (503) | 503 TENANT_ADMISSION_UNAVAILABLE |
The admission policy (kinds, precedence, predicates, sub-keys) is part of the
command fingerprint, so two Workers built from different policies refuse each
other. Adding qb.admitScope does not change the RPC version: the fingerprint
covers the whole command registry. So while the two Workers deploy, an edge
on the previous build gets unavailable (TENANT_COMMAND_FINGERPRINT_MISMATCH)
from every command, qb.epoch included, until it is deployed too. Bound
tokens of tenant-backed kinds answer temporarily_unavailable in that window.
Nothing is admitted from a mismatched registry. The tenant bundle imports no Better Auth, no drizzle-orm/d1 and no
scope-oauth. None of these paths reads the platform D1.
Server-issued grants
A tenant-backed kind that declares
oauth.serverGrant
gets two more commands. They are reached only through the generated
readScopeGrantSubject and linkScopeGrantSubject (in src/lib/scope-oauth.ts),
which the edge action calls with the subject its own credential row names;
no edge code reads or writes the guest table itself. (A platform kind reads
and links in the shared features database instead, with no commands and no epoch;
see Platform kinds.
A project cannot mix the two: SCOPE_SERVER_GRANT_MIXED.)
qb.scopeGrantReadselects the instance row and the subject row inside one synchronous transaction: object tenant = instance tenant column = subject tenant column, subject resource column = the instance id, neither row soft-deleted, the subject admittable (the OR of the ceiling roles'where). It writes nothing.qb.scopeGrantLinkre-runs those checks, returnsunchangedwhen the subject is already linked to the user, and otherwise runs one conditionalUPDATE … SET <user column> = :userId WHERE <all of the above> AND (<user column> IS NULL OR <user column> = :replaces) RETURNING id. Anything but exactly one row isSCOPE_GRANT_LINK_CONFLICT(still live, linked to someone else) orSCOPE_GRANT_SUBJECT_DENIED, with nothing written. On a link it puts the audit row (event_kind: 'scope_grant_link', acredential-mediatedactor envelope) in the object's outbox in the same transaction; the edge drains it toaudit_events. The request's epoch must equal the permit's: a restore between the read and the link denies.
Routing follows the kind's lookup; the action's tenantHint (the
organization on its credential row) is used only while the lookup has no
row, and the object's own equality checks make a wrong hint admit nobody.
While the object is held, archived, restoring, moving or migrating, both
commands answer unavailable, so the action answers 503 and its credential
is untouched: nothing spends it before the action's own consume, after
issueScopeGrant. Like qb.admitScope, adding these commands does not
change the RPC version: the command fingerprint covers them (and the
server-grant program), so a split deploy refuses before any write.
Tenant namespaces
A namespace (authz.namespaces.<name>) whose relationship lanes, loads
tables and claimed routes all live in the organization object runs in the
tenant Worker. Claimed routes are the standalone actions whose path is under
its prefix and the generated table routers mounted there. The edge mounts a
forwarder at the prefix. The tenant Worker mounts the namespace's gate file
(src/routes/__namespace-<name>.routes.ts) and, behind it, every route the
namespace claims. A tenant feature's action under the prefix may sit outside
its feature's own path (TENANCY_ROOT_ACTION doesn't apply to it).
Actions at a table route
A tenant feature's standalone action may also sit under one of its own tables'
routes, outside the feature's path. The usual case is a
mapped create: create: { action } on
clientInvoiceLines makes the action occupy POST /client-invoice-lines,
while the feature's path is /client-invoices. The edge forwards that path to
the organization's object, and the tenant Worker mounts the feature's
root-actions router (<feature>-root-actions.routes.ts), so the action runs in
the object with the same gates as on a shared edge. A path under no table
route of the feature, and any root path on a
partitioned feature, is still TENANCY_ROOT_ACTION.
The edge routes a namespace request by the prefix's first :param, through
the tenant-backed kind whose requestField it is:
| Caller | Tenant |
|---|---|
| Instance-bound token of the kind | The tenant it pins (ctx.oauth.boundTo.tenantId). No lookup. A token for another instance: 403. |
| Anyone else | tenancy.lookups.<kind> for the id. Several organizations: 409 TENANT_AMBIGUOUS. No row: the same 403 ACCESS_ROLE_REQUIRED the gate gives a caller who proves no lane, so an unknown id and an id you can't reach look alike. A new instance is indexed after its write, so it can answer that 403 briefly; retry. A failed lookup read: 503 TENANT_UNAVAILABLE. |
The edge matches the prefix on the percent-decoded path Hono routes on, and
the bound-token confinement uses the same path, so an encoded variant
(/api/v1/%65vent/…) is routed and confined exactly like the plain one. A
request that reaches the namespace mount but matches no namespace is 404; it
never falls through to active-organization routing. An encoded / (%2F)
stays encoded and is never an instance id. The caller's active organization
never routes a namespace request. A caller
whose active organization is a different one loses its organization seat and
its organization and team roles before the request is forwarded. Inside the
object, an organization firewall arm then matches only a member of this
organization; everyone else gets the rows their relationship proves.
In the object, the gate re-proves an instance-bound token with admitLocal,
the same program qb.admitScope runs. It uses the raw tenant SQLite, the
request's restore permit epoch, and the token's exact subject and proving
table. No RPC and no D1 read. The token's tenant must be the object's, and
its epoch the permit's: a token issued before a restore gets 403, so the
user reauthorizes. A session caller passes a lane only as the subject
admission would choose: after the lane matches, the gate runs admitLocal in
discover mode and requires the same row. So the kind's precedence decides,
and two rows on the choosing role deny (403), exactly as at authorize. Then the relationship lanes, loads hydration (through the
loaded table's firewall) and the per-lane scope refresh run against tenant
SQLite exactly as on a single Worker. A namespace request costs one RPC (the
forward) plus, for a session caller, one lookup read in D1.
A forwarded share-link principal
is routed the same way, by the instance id in the path. The gate admits it
only for the link's own scope instance, in the object of the link's
organization, on a route that admits links of its object type (the landing);
it holds no roles and proves no lane, and ctx.lane is 'link'. Anywhere
else under the prefix the request runs as the caller the link replaced.
A claimed table's legacy forward
(legacy) is not a namespace route. The edge routes its old URL
(/api/v1/locations) by active organization, exactly as it routed the
table before the claim: a caller with no organization gets 400 TENANT_REQUIRED
at the edge, and the organization object is always the caller's own, so the
§2a strip never applies. The forward runs in the tenant Worker
(src/routes/__legacy-<feature>.routes.ts, mounted beside the namespace),
requires ctx.activeOrgId === ctx.tenantId, reads the instance and any row from
tenant SQLite, and dispatches in-process to the namespace route: no second RPC.
A namespace that can't run in one place fails the build:
| Code | Cause |
|---|---|
TENANCY_NAMESPACE_SPLIT | Its lanes, loads tables or claimed routes mix tenant and platform. |
TENANCY_NAMESPACE_PARTITIONED | One of them is in a partition object. |
TENANCY_NAMESPACE_UNROUTED | It runs in tenant objects, but its :param is no scope kind's requestField, or a platform kind's, so a request can't name its organization. |
Edge namespace actions
A tenant namespace's routes run in the tenant Worker, which has no env
bindings, secrets or Better Auth. An action under the prefix that needs them
(presigning an R2 upload, creating a Better Auth user, sending email) declares
edge: true. It keeps its URL and runs on the edge Worker:
import { z } from "zod";
import { defineAction, ActionError } from "../.quickback/define-action";
import { callTenantJob } from "../../../lib/tenants";
export default defineAction({
description: "A presigned upload URL for one event.",
path: "/event/:eventId/upload-url",
method: "POST",
edge: true,
input: z.object({ filename: z.string().min(1).max(200) }),
access: { roles: ["scope:event:staff", "scope:event:attendee"] },
async execute({ ctx, env, input }) {
const eventId = ctx.admittedInstance?.kind === "event" ? ctx.admittedInstance.id : undefined;
if (!eventId || !ctx.tenantId) throw new ActionError("No admitted event", "BAD_REQUEST", 400);
// Tenant data only through a result job, in the tenant the gate admitted.
const res = await callTenantJob<{ name: string }>(env, ctx.tenantId, { type: "event.name", eventId }, "event-name:" + crypto.randomUUID());
if (res.status !== "ok") throw new ActionError("Try again shortly", "EVENT_UNAVAILABLE", 503);
return { url: await presign(env.UPLOAD_SIGNING_KEY, `${ctx.tenantId}/${eventId}/${input.filename}`), event: res.result.name };
},
});The edge mounts these actions at the namespace prefix ahead of the forwarder,
each behind a gate on its own route. Every other route under the prefix is
forwarded as before. The gate reads no table. One qb.admitScope in the
instance's tenant decides:
| Caller | Admission |
|---|---|
| Instance-bound token of the kind | Exact admission of its subject in the tenant and epoch it pins. A revoked subject, or a token issued before a restore, gets 403. A token for another instance gets 403. |
| Session | The tenant from tenancy.lookups.<kind>, never the active organization, then discover admission under that tenant's current epoch: the namespace's relationship lanes, chosen by the kind's precedence. |
Session, { roles } lane | A member of that organization holding one of the lane's roles, when the tenant confirms the instance exists there and the user proves no row (SCOPE_NO_ROLE). Members of other organizations never qualify. |
Every denial, including an unknown or not-yet-indexed id, is the namespace's
403 ACCESS_ROLE_REQUIRED. A tenant that can't answer is 503 with
Retry-After, never a denial. On success ctx.tenantId is the admitted
tenant and ctx.admittedInstance is { kind, id } for the admitted instance.
This routing metadata grants no scoped roles. Relationship admission also sets
ctx.scope.<kind> to the admitted entry (id, roles, subjectId,
provingTable); the organization-role lane clears that scope entry. A caller who isn't a member of that organization loses its
organization seat and roles, as on forwarded requests. Then the action's own
access runs against that ctx.
An edge action is a platform action:
- It lives in a platform feature. A feature with no tables is simplest. The
file location doesn't change its URL. In a tenant feature the build fails
with
TENANCY_EDGE_ACTION_PLACEMENT. - Its
dbis the platform D1. It reads tenant data through result jobs called withctx.tenantId. Naming a tenant table, or importing a tenant feature's module, fails the build (TENANCY_ADMISSION_DEPENDENCY). - The namespace's
loadshydration never runs on the edge. Readingctx.<exposeAs>fails the build (TENANCY_EDGE_ACTION_CTX). Usectx.scope.<kind>, or read the row with a result job. - Its path must be under a tenant namespace's prefix
(
TENANCY_EDGE_ACTION_NAMESPACE). Withoutedge: true, a platform action there splits the namespace (TENANCY_NAMESPACE_SPLIT).
Security notes:
- The gate proves the caller holds a role on the instance when the request
starts. A result job runs later, with system rights, in a separate
transaction. A revocation can land between the two. When a write must be
authorized atomically with the authorization, recheck the subject inside the
job (its message carries
ctx.scope.<kind>.subjectId), or keep the write in a tenant action behind the tenant gate. - The job's tenant must be
ctx.tenantId. Never use an id from the request (TENANCY_JOB_CALL_TENANT_SOURCE). Scope any job input by the admitted instance (ctx.scope.<kind>.id). - Each request costs one
qb.admitScopeRPC, plus a lookup read and aqb.epochRPC for a session caller.
In shared mode (no isolation: 'durable-object'), edge has no effect. The
namespace already runs on the edge.
Tenant Table Placement
Which tables move into per-organization Durable Objects, which stay on the platform D1, lookup indexes, and partitions.
Files, Embeddings and Deletes in Tenant Databases
Managed files, embeddings, hard deletes and the audit log when every organization has its own Durable Object database.