Instance-bound OAuth Tokens
Issue OAuth access tokens bound to one scope instance — requirements, requesting a token, subject precedence, revocation, instance liveness, and migrating from earlier scope tokens.
Set oauth on a scope kind to issue OAuth access tokens bound to one instance of that kind — one event, one vendor, one client. This page covers the compile requirements, requesting and revoking a token, and migrating from the removed scope-token API. Server-minted grants are on Server-issued Grants.
Instance-bound OAuth tokens
Set oauth on a scope kind to issue OAuth access tokens bound to one instance of that kind. The holder reaches that instance's namespace routes and nothing else: no other instance, no org seat, no user-level routes. Use it for principals who should never hold a full session — an event guest, a vendor contact, a client contact.
// quickback.config.ts
authz: {
relationships: {
attendeeOf: { from: 'guests', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { status: 'confirmed' } },
},
scopes: {
event: {
requestField: 'eventId',
roles: { attendee: { via: 'attendeeOf' } },
oauth: {}, // resource: BETTER_AUTH_URL + '/event', 180s access tokens
},
},
namespaces: {
eventScope: { prefix: '/event/:eventId', via: ['attendeeOf'] },
},
}The mechanism is per kind. event, vendor, and client are three kinds with three resources; nothing in it is specific to events.
Requirements (compile errors)
-
The project runs on the Cloudflare runtime with one of the providers the lane is proven on:
Provider Status cloudflare-d1supported, tenant-backed kinds included neon,connectionMode: 'http'(the Cloudflare default) or'hyperdrive'supported (how admission reads under RLS) planetscale-postgres(Hyperdrive)supported, the same generated code as Neon Hyperdrive neon,connectionMode: 'websocket'SCOPE_OAUTH_PROVIDER_UNSUPPORTED: that db index has no claim-scoped handle and no service-role handleany other database SCOPE_OAUTH_PROVIDER_UNSUPPORTED, naming the providera runtime other than cloudflareSCOPE_OAUTH_RUNTIME_UNSUPPORTED, naming the runtimeTenant-backed kinds admit inside Durable Objects, so they need
cloudflare-d1. A tenant-backed kind on another provider is refused withSCOPE_OAUTH_PROVIDER_UNSUPPORTED. -
The auth provider has
oauth: { enabled: true }. -
Admission is a role's relationship, proven for the signed-in user (
subject.equals: 'ctx.userId'). -
A kind with two or more roles declares
precedence, listing each of them exactly once (SCOPE_OAUTH_PRECEDENCE_REQUIRED,SCOPE_OAUTH_PRECEDENCE_INVALID). The kind's namespacevialanes list their relationships in the same order (SCOPE_PRECEDENCE_LANE_CONFLICT).precedenceon a kind withoutoauthis an error. -
A namespace's prefix has the kind's
requestFieldas its first parameter (/event/:eventId). Those prefixes are the only paths a bound token reaches. -
accessTokenTtlis 1–180 seconds (default 180). A JWT access token can't be revoked before it expires. -
resource, when set, is an absolutehttp(s)URL with no fragment, unique across kinds, and not an ordinary OAuth audience: not the origin,/mcp, a named MCP server's path, or anoauth.audiencesentry. A kind namedmcpis refused for the same reason. -
No two OAuth kinds share a
requestField. -
No route outside the kind's namespaces mounts under their prefixes. That covers feature and table mounts, root standalone actions, and built-in routes such as
/api/v1/system/…and/api/v1/schema. A feature namedeventmounts CRUD at/api/v1/event/:id, inside/event/:eventId, so it is an error next to aneventkind withoauth. -
Every namespace whose first parameter is the kind's
requestFieldgates on at least one of the kind's relationships in itsvia. A namespace on:eventIdthat only admits{ roles: [...] }is an error, because bound tokens would reach it. -
plugins.oauthProvider.postLogin,customAccessTokenClaims,resources, andresourceSeedModeare generated; setting them is an error.refreshTokenReuseIntervaldefaults to30and must stay above0. A DPoP-bound grant (the client sent aDPoPproof when it redeemed or authorized) is the exception: after each rotation the old refresh token stays replayable until it expires, so a native app that lost a rotation answer can resend it later and get the same answer, instead of revoking every grant the user holds. The proof must come from the bound key, and revocation deletes the rows, so there is nothing left to replay. -
With
tenancy.isolation: 'durable-object', a kind whose relationship tables and instance table all live in one organization object is tenant-backed: authorize, code exchange, refresh,issueScopeGrant, its namespace routes and its ws-tickets all admit inside that object (qb.admitScope/admitLocal), and none of them reads the platform D1. Grants pin the tenant and its authorization epoch (qb2:references,qb_scopewithv: 2,tenantId,epoch,provingTable), andctx.oauth.boundTocarriestenantIdandepoch. The kind's namespace runs in the tenant Worker, routed by the tenant the token pins (Tenant namespaces). It needstenancy.lookups.<kind>on the instance table's primary key, noself, and no relationshiphops— each refused permanently for tenant tables, under its own code. A kind that reads a tenant table but can't be tenant-backed fails the build with the missing requirements. Every other scope kind, and relationship-backed access on platform features, must keep its tables on the platform (TENANCY_ADMISSION_DEPENDENCY).
Request a token
Only trusted clients get bound tokens: clients an admin created with skip_consent: true. Dynamic client registration can't set skip_consent (Better Auth rejects it), so an MCP connector that registered itself gets unauthorized_client. Register the guest app once from server code, signed in as an admin:
await createAuth(env).api.adminCreateOAuthClient({
headers, // an admin's session
body: {
client_name: 'Guest app',
redirect_uris: ['https://guest.example.com/callback'],
token_endpoint_auth_method: 'none', // public client, PKCE
grant_types: ['authorization_code', 'refresh_token'],
response_types: ['code'],
skip_consent: true,
scope: 'offline_access',
},
});The client sends the kind's resource and the instance in RFC 9396 authorization_details:
GET /auth/v1/oauth2/authorize?response_type=code&client_id=<id>&redirect_uri=<uri>
&code_challenge=<S256>&code_challenge_method=S256&state=<state>
&scope=offline_access
&resource=https://api.example.com/event
&authorization_details=[{"type":"event","id":"evt_123"}]A caller without a session is sent to the login page first; authorization_details rides the signed query and is checked when authorize resumes. Then POST /auth/v1/oauth2/token exchanges the code as usual. Request offline_access to get a refresh token.
Issuance fails closed:
| Request | Result |
|---|---|
No authorization_details, malformed JSON, more than one entry, wrong type, empty id | invalid_request |
authorization_details without a kind resource | invalid_request |
| A kind resource plus any other resource | invalid_target |
openid in scope (it adds the userinfo audience) | invalid_scope |
An instance id outside A-Z a-z 0-9 . _ ~ - | invalid_request |
A client that is not admin-created with skip_consent | unauthorized_client |
| A banned user, or no relationship to the instance | access_denied, no code |
The relationship and the ban state are re-checked at the code exchange and at every refresh: removing the guest row or banning the user fails the next refresh with invalid_grant. Admission probes the relationship for the signed-in user, with instance tenant binding.
The access token carries the proven entry in a qb_scope claim, beside the standard OAuth claims:
{ "aud": "https://api.example.com/event", "sub": "<user id>",
"qb_scope": { "kind": "event", "id": "evt_123", "roles": ["attendee"], "subjectId": "gst_42" } }A sign-in session created for this authorization is deleted when the code is exchanged. A session counts as created for it when that request created the session (its createdAt is no earlier than the request, and the response sets its cookie) and the request carries the bound authorization: the signed oauth_query (email OTP, password, passkey), a social callback's server context, or, on /magic-link/verify and /verify-email (its auto sign-in), a callbackURL that is the bound authorize URL. The guest holds only the bound access and refresh tokens. A session the user already had (staff signed in to the CMS or Account) is never deleted, and neither are its ordinary OAuth tokens: verifying an email while signed in, or a callbackURL on any other endpoint (/get-session, /update-user, /update-session), marks nothing, and re-setting the cookie of an existing session never marks it.
Subject precedence
A user can hold several roles on one instance through different rows: a crew member who is also a confirmed guest. A token binds one subject, so a kind with two or more roles declares which row wins:
// quickback.config.ts
authz: {
relationships: {
crewOf: { from: 'event_roles', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { role: 'crew' } },
attendeeOf: { from: 'guests', subject: { column: 'linkedUserId', equals: 'ctx.userId' }, resource: { column: 'eventId' }, where: { status: 'confirmed' } },
},
scopes: {
event: {
requestField: 'eventId',
roles: { crew: { via: 'crewOf' }, attendee: { via: 'attendeeOf' } },
precedence: ['crew', 'attendee'], // most authoritative first
oauth: {},
},
},
namespaces: {
eventScope: { prefix: '/event/:eventId', via: ['crewOf', 'attendeeOf'] }, // same order
},
}At authorize, exchange and refresh, admission walks the roles in this order:
- The first role with any matching row chooses the subject. If that role matches two rows (two confirmed guest rows for the same user and event), admission is refused. Neither row is picked at random.
- Every later role is checked against that same row only: same table, same id. Duplicate rows on a later role are ignored. They can't add roles to the chosen row, so they don't refuse anything.
- The token carries only the roles that same row proves, and its sub-keys. It never unions roles from different rows.
A refresh can pick a different row if the first one was removed, but only for the same instance. An exact issueScopeGrant ceiling never does: that grant stays on its own row and roles. The rule is the same for every OAuth kind, including one with a single role.
A kind with one role needs no precedence.
Breaking: before precedence, a user who matched several roles was admitted with all of them, under whichever row matched last. Kinds with two or more roles now fail to compile until they declare the order. Also new, and fail-closed for every OAuth kind: when the role that chooses the subject matches two rows for one user and instance, the user used to be admitted with whichever row the database returned first. Now nobody is admitted until the duplicate row is removed.
What the token reaches
The auth middleware owns any bearer whose aud names a kind resource. It verifies it against the JWKS locally, with no session lookup and no sid check: once the session row is gone, refreshed tokens carry sid: null. Then:
audmust be exactly the kind's resource. An array audience is401.qb_scopemust name that kind and an instance id. A bad signature, expiry, or a missing claim is401— never a fall-through to another lane.- The request path must be under one of the kind's namespace prefixes for the same instance (
/api/v1/event/evt_123/…).evt_456,evt_1234, an encoded segment,/api/v1/me, CRUD routes,/mcp, and the operator endpoints are403. - One exception:
POST /broadcast/v1/ws-ticket, when the realtime ticket'srequestFieldis the kind's. The mint then issues a ticket for this instance only, intersecting the token's currently proven roles with the configured ticket gate's relationship lanes. The ticket identifies only the exact scope subject, without account-wide user identity (details). Every other broadcast path is403. - The kind's prefixes are every namespace whose first parameter is its
requestField. Each namespace gate checks again that a bound token names its own kind and its own:param, and returns403otherwise. - Issuance reads
resource,authorization_details, andclient_idfrom the request Better Auth is authorizing (the GET query, the POST form body, or the verifiedoauth_queryon resume), never from other parts of the raw request. A non-stringoauth_queryisinvalid_request. - With
auth.jwt.revocationCheck: 'kv', the user-level revocation key applies, so a ban or sign-out-everywhere stamp rejects the token before it expires.
The verifier caches the JWKS per isolate, refetches only for an unknown kid, and accepts only asymmetric algorithms.
The request then runs as a relationship-only principal:
{
authenticated: true,
authMethod: 'oauth',
userId: '<sub>',
activeOrgId: undefined,
roles: [], // no org roles
scope: { event: { id: 'evt_123', roles: ['attendee'], subjectId: 'gst_42' } },
oauth: { clientId, scopes, resource, boundTo: { kind: 'event', id: 'evt_123' } },
}The namespace gate re-proves the relationship on every request, as it does for any signed-in caller, so a removed guest loses access immediately on namespace routes. The project's resolve-oauth-context.ts hook does not run for bound tokens.
Confinement is per route and instance, for every lane. A table the namespace claims is pinned to the URL instance: the gate stamps the instance id, and the table's firewall ANDs <instance column> = <id> for bound tokens, relationship lanes and org members alike. The exception is a claimed table with no instance arm (only an owner arm, say): it serves the user's own rows from other instances through this instance's routes, and the compile warns CLAIMED_TABLE_UNPINNED. Give every claimed table one instance-scoped firewall arm, such as { field: 'eventId', equals: 'ctx.scope.event' }.
A claimed table's legacy forward does not widen this: it refuses an instance-bound token and every caller without an active organization (403 LEGACY_ORG_REQUIRED), and it only forwards into an instance of the caller's own organization.
Ordinary OAuth tokens (MCP clients, audience = origin or /mcp) are unchanged: they still need a live session — at use and at every refresh, see Grant lifetime — and get the user's full context.
Revoke one instance
Call revokeScopeGrant, or remove the relationship. Both stop the next refresh; the access token in flight dies within its TTL. Other instances keep refreshing.
revokeScopeGrant is race-free against a refresh in flight, on every provider. Better Auth's adapter runs without transactions, so the call cannot find and delete the refresh rows atomically; a refresh that rotated a row between the find and the delete would otherwise write a successor the revoke never saw. Instead:
- It writes a revocation marker (a
verificationrowqb-scope-revoked:<kind>:<instanceId>:<userId>, value{ revokedAt }) before it finds any row. - It finds and deletes the grant's refresh rows.
- Every bound refresh answer, after its new row is written, re-reads the marker. If one exists and the presented refresh row is gone or was created no later than
revokedAt, the answer becomesinvalid_grantand its tokens are never delivered. The refusal is logged asscope_oauth.refresh_revoked(SCOPE_GRANT_REVOKED, kind, instance, user, the rule).
Either that re-read sees the marker, or the new row was written before the marker and so before the find, which deletes it. A rotation replay is checked the same way. A revoke that failed after writing its marker still refuses every row it missed, for as long as the marker lives (30 days, the default refresh-token lifetime).
- Same second: refresh rows store
createdAtin whole seconds. A grant issued in the same second as a revocation of that user and instance is refused at its first refresh (fail closed); the client authorizes again. - Custom token storage: the presented row is found by the default storage (SHA-256). With a custom
storeTokens,prefixorformatRefreshToken, every bound refresh of a revoked (user, instance) is refused while the marker lives.
Bound refresh tokens outlive sessions by design, so user-wide revocation drops them explicitly. These delete every bound refresh token the user holds:
/revoke-sessionsand/revoke-other-sessions(the Account devices page)/change-passwordwithrevokeOtherSessions: true/reset-password,/email-otp/reset-password,/phone-number/reset-password, over HTTP or from server code (auth.api.resetPassword)/admin/ban-user,/admin/revoke-user-sessions,/admin/remove-user,/admin/set-user-password
Revoking one session (/revoke-session, /admin/revoke-user-session) leaves bound grants alone. They don't depend on any session, and the session that started a flow is already deleted after the exchange.
import { createAuth } from '../lib/auth';
import { revokeScopeGrant } from '../lib/scope-oauth';
await revokeScopeGrant(createAuth(env), { userId, kind: 'event', instanceId: 'evt_123' });For a tenant-backed kind, pass the organization the grant pins as well: { userId, kind, instanceId, tenantId }. It is required for those kinds and refused for others.
Never call /oauth2/revoke for a bound refresh token. Better Auth treats any later use of a revoked refresh token — an app retry, two tabs racing a rotation — as replay and deletes every refresh token that user holds for the client, signing them out of all instances.
Instance liveness (instance.live)
By default an instance admits while its row exists and isn't soft-deleted. A status can end an instance too: a cancelled event should stop admitting its crew, but a relationship's where filters only the relationship's own row, and a crew row on a cancelled event is still a valid crew row. Declare the instance in its object form with a live predicate:
scopes: {
event: {
requestField: 'eventId',
instance: { table: 'events', live: { status: { notIn: ['cancelled', 'archived'] } } },
roles: { organizer: { via: 'organizerOf' }, attendee: { via: 'attendeeOf' } },
precedence: ['organizer', 'attendee'],
oauth: {},
},
},live maps columns of the instance table to one condition each, all of which must hold: { equals }, { notEquals }, { in: [...] } or { notIn: [...] }, with literal values. These are the operators an action's access.record uses. A NULL column satisfies no condition, so notEquals and notIn fail closed on a missing value. The string form (instance: 'events') keeps working, and a kind without live compiles exactly as before.
A non-live instance denies with the same result as a missing one (SCOPE_NOT_FOUND, or no scope stamped), so the response doesn't reveal that the instance exists. The predicate is checked everywhere the instance is read:
- Tenant admission (
qb.admitScope/admitLocal): authorize, code exchange, every refresh, every namespace request of a bound token or a relationship-lane session, ws-tickets, andissueScopeGrant. - Edge OAuth admission for platform kinds.
- The namespace scope-claim refresh, including the reuse of a hydrated
ctx.<exposeAs>row. - Server-grant reads and links (
readScopeGrantSubject,linkScopeGrantSubject).
The access token already in flight keeps working until its TTL runs out (at most 180 seconds). The next refresh is denied, and so is the next namespace request, because each one re-runs admission.
Compile errors:
SCOPE_INSTANCE_LIVE_INVALID: an emptylive; a column the instance table doesn't declare; an operator other than the four; more than one operator on a column; an emptyin/notIn; actx.*value; or a literal whose type doesn't match the column (text takes strings, integers take numbers, booleans take booleans). A wrong-typed literal would makenotEqualsalways true, so it fails the build.SCOPE_INSTANCE_LIVE_UNBOUND: the instance table has no organization column, or a role proves from a table with no organization column. Those paths never read the instance row, so they couldn't check liveness.
Org members who reach the namespace through a { roles: [...] } lane aren't affected. They're admitted by their org role, not by the scope, so staff can still open a cancelled event.
Migrating to instance-bound OAuth tokens
Instance-bound OAuth tokens are the only way to carry a scope across requests. Scope roles, relationships, namespaces, and every pillar that reads ctx.scope.<kind> are unchanged; only how the caller obtains the scope changed.
Steps, per kind:
- Add
oauth: {}to the kind, and enableoauth: { enabled: true }on the auth provider. Check the requirements: a namespace whose first parameter is the kind'srequestField(/event/:eventId), and no other route mounted under it. - Register the client app once as a trusted client (
adminCreateOAuthClientwithskip_consent: true), as in Request a token. - In the client, run the authorization-code flow:
resource=<kind resource>andauthorization_details=[{"type":"event","id":"<eventId>"}], plusoffline_accessfor a refresh token. Send the access token asAuthorization: Bearer …on the instance's namespace routes, and refresh with the refresh token. - Move every call the scoped principal makes under the kind's namespace prefix. A bound token reaches only
/api/v1/<prefix>/<instance>/…; CRUD routes answer403. Realtime works throughPOST /broadcast/v1/ws-ticketfor the bound instance. - Give accountless principals a Better Auth user (for example a passwordless user created by your invite action, signing in with email OTP) so they can sign in once and authorize — or prove their credential in an action and issue a grant with
issueScopeGrant.
Removed
These scope-token minting paths are gone. Each config or code that used them fails the build with SCOPE_MINT_REMOVED; the message names the exact field or file and links to Instance-bound OAuth tokens.
| Removed | Fails the build at |
|---|---|
POST /scope/v1/enter | — (emitted automatically before; the route no longer exists) |
Namespace mintScope (in authz.namespaces or an area's _area.ts) | authz.namespaces.<name>.mintScope, or features/<area>/_area.ts: mintScope |
Namespace acceptScope | authz.namespaces.<name>.acceptScope, or features/<area>/_area.ts: acceptScope |
ctx.mintScope(...) in an action or a feature lib/ file | features/<feature>/<file> |
Role subject: 'supplied' | 'both' | authz.scopes.<kind>.roles.<role>.subject |
Role self.by.subject | authz.scopes.<kind>.roles.<role>.self.by.subject |
For example:
SCOPE_MINT_REMOVED: authz.namespaces.eventScope.mintScope — Namespace scope-token minting (`mintScope`) was removed. Drop it and issue instance-bound OAuth tokens: add `oauth: {}` to the scope kind; the namespace gate re-proves the relationship on every request. See https://docs.quickback.dev/define/scopes#instance-bound-oauth-tokensWith them went self.by.subject, the scope-only token lane in the auth middleware, ws-tickets issued off a scope-only claim, the session ticket's matching scope:<kind>:<rowId> tag, and the scope:<kind>:<subjectId> audit actor for scope-only writes. subject: 'user' (the default) is still accepted; omit it.
Instance-bound OAuth tokens run on cloudflare-d1, Neon (http or hyperdrive) and PlanetScale Postgres (requirements). Where they are refused (Neon websocket), a scope kind has no bearer token: callers reach it through a namespace, whose gate proves the relationship and refreshes ctx.scope.<kind> on every request for a signed-in user.
Scopes & Capability Grants
Let non-org principals (event attendees, shuttle drivers, vendors) reach a narrow slice of your data through a relationship-derived scope, proven for the signed-in user and carried in an instance-bound OAuth token — with least-privilege scoped roles enforced across every pillar.
Server-issued Grants
Mint an instance-bound grant from server code with issueScopeGrant — the oauth.serverGrant ceiling, issue-before-consume, the four functions, atomicity and the audit row.