Quickback Docs
Scopes

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.

Server code can mint an instance-bound OAuth grant for a principal without an interactive authorize step, for example after a guest redeems a handout code or exchanges a legacy event pass. This page covers the declared ceiling, the issue-then-consume flow, and the generated functions. Start at Scopes for the model.

Server-issued grants (issueScopeGrant)

Some principals prove themselves with a credential Better Auth does not know: a handout code staff give at the door, or a one-time exchange of a legacy event pass. Don't turn that credential into a Better Auth session. A one-time token transfers a full session, and creating a session row or verifying an email from server code writes auth tables and can link rows across organizations. Issue a bound grant instead.

The credential stays your application's own row. The compiler models no credential table; your action proves the credential and consumes it.

Declare the ceiling (oauth.serverGrant)

// quickback.config.ts (excerpt)
scopes: {
  event: {
    requestField: 'eventId',
    instance: 'events',
    roles: { attendee: { via: 'attendeeOf' }, invitee: { via: 'inviteeOf' }, applicant: { via: 'applicantOf' } },
    precedence: ['attendee', 'invitee', 'applicant'],
    oauth: {
      serverGrant: {
        roles: ['attendee', 'invitee', 'applicant'],                  // the exact ceiling
        project: {
          subject: { email: 'emailAtInvite', name: 'nameAtInvite' },  // identity, for resolving the user
          instance: ['status'],                                       // optional read-only instance columns
        },
      },
    },
  },
},

serverGrant works on both kinds of scope kind, with the same functions and the same guarantees:

  • Platform kinds (the default: the instance and subject rows live in the shared features database). The read and the link run against that database: cloudflare-d1, neon (connectionMode: 'http' or 'hyperdrive'), or planetscale-postgres.
  • Tenant-backed kinds (tenancy.isolation: 'durable-object'). The read and the link run inside the organization object.

One project uses one or the other. A serverGrant on a platform kind next to a tenant-backed kind fails the build (SCOPE_SERVER_GRANT_INVALID … SCOPE_SERVER_GRANT_MIXED). Server grants need the same runtime and providers as every instance-bound token (requirements); tenant-backed kinds need cloudflare-d1. A provider with no platform grant store fails the build with SCOPE_SERVER_GRANT_PROVIDER_UNSUPPORTED, naming the provider and connection mode.

The build fails with SCOPE_SERVER_GRANT_INVALID (naming the kind, the table or column, and the rule) unless:

  • every ceiling role is a role of the kind, and their relationships share one proving table, one user column (equals: 'ctx.userId') and one resource column, with literal where values only. The subject is admittable when it matches any ceiling role's where (their OR);
  • the proving and instance tables soft-delete, so a hard-deleted and re-added row can never reuse an id a credential names;
  • the user column and every projected column exist and are text columns (project.subject takes email and name);
  • the project has the security audit database (any PUBLIC, unsafe or hard-deleting route gives it one): every link writes an audit row;
  • platform kinds: the proving table has an organization column (q.scope('organization')), and the instance resolves to a separate organization-scoped table. A shared database holds every organization's rows, so the read and the link accept a subject only when its organization equals its instance's (row against row, as in instance tenant binding);
  • tenant-backed kinds: the kind is tenant-backed, so its instance and proving tables live in the organization object, unpartitioned, with the tenant column and server-generated ids.

A kind with serverGrant also refuses SCOPE_SERVER_GRANT_NAMESPACE_LEAK, on platform and tenant-backed kinds alike: every table a namespace of the kind claims, and every table owned by a feature with a standalone action under that namespace, must pin its rows to the instance (an arm on ctx.scope.<kind>, ctx.scope.<kind>.id or ctx.scope.<kind>.subjectId) or to organization members (an arm on ctx.activeOrgId). A server-granted token keeps the linked account's userId, so an owner-only table under the namespace would serve that account's rows of other instances. An organization arm is safe: an instance-bound token never carries an active organization or organization roles, even when its user is a member, so an organization-only table simply refuses it. That holds on a shared database too, where every organization's rows sit side by side: the arm compares with the caller's active organization, which a bound token never has. Every branch of an any: group must be pinned, and an all: group is as pinned as its safest arm: any: [owner, instance] is refused, any: [{ all: [owner, org] }, instance] passes. An organization arm marked optional: true pins nothing (it is dropped when the claim is absent), so all: [owner, { …org, optional: true }] is refused, and neither does an arm on ctx.tenantId.

Issue before consume

A handout code yields exactly one thing: a grant for its own event, with the exact subject row and the declared ceiling. Never a session, a cookie, a pass, or a link to any account but the subject's own. The action runs these steps in order:

#StepWritesA failure here
1Precheck the credential (your platform row: not revoked, not expired, the right subject).noneinvalid
2readScopeGrantSubject: the live instance, the live admittable subject, its identity columns and current link, read in one snapshot (the features database for a platform kind, the organization object for a tenant-backed one).nonedenied / unavailable
3Resolve the subject's user with vanilla Better Auth: the current link if that user exists; else by email, applying the squatting guard; else auth.api.createUser (no password, no session).maybe a passwordless unverified userconflict / unavailable
4linkScopeGrantSubject: one conditional write re-checks the subject and writes the link only if it is unlinked (or still names the one user step 3 proved gone), exactly one row, plus an audit row.link + auditconflict / denied / unavailable
5issueScopeGrant: fresh exact admission, a hashed 120 s grant row. The code is not returned yet.grant rowdenied / unavailable
6Consume your credential with one conditional write (UPDATE … WHERE id = ? AND revoked_at IS NULL AND expires_at > ? … RETURNING id).credential spentlost
7Return the grant code only if step 6 returned exactly one row. Otherwise discardScopeGrant(auth, code) and answer the uniform invalid error.grant row deleted—

Nothing before step 6 spends the credential, so any failure there (a held tenant, a transient error, a revocation, a declined guest, a cancelled event) leaves it redeemable. Two redeemers racing one code both reach step 6; one consume wins and returns its grant, the other discards its own. If the consume's outcome is unknown (the database call threw), discard the grant and answer 503: a retry then finds the code spent, the same "burned, staff reissue" outcome as a crash after the consume.

import { createAuth } from '../lib/auth';
import { readScopeGrantSubject, linkScopeGrantSubject, issueScopeGrant, discardScopeGrant } from '../lib/scope-oauth';

// Inside the handout action, AFTER step 1 proved the code row `cred`. A platform kind:
const ids = { kind: 'event', instanceId: cred.eventId, subjectId: cred.guestId };
const read = await readScopeGrantSubject(env, ids);          // { status: 'ok', subject, instance } | denied | unavailable
// …step 3 resolves userId (and `replaces`, the observed link, when that user is gone)…
const link = await linkScopeGrantSubject(auth, { env, ...ids, userId, replaces });
const { code, expiresIn } = await issueScopeGrant(auth, {
  env, userId, kind: 'event', instanceId: cred.eventId, subjectId: cred.guestId,
  roles: ['attendee', 'invitee', 'applicant'],                 // exactly the declared serverGrant ceiling
  clientId, codeChallenge, codeChallengeMethod: 'S256', redirectUri,
});
// …step 6: consume `cred` with one conditional write; `won` = the rows it returned…
if (won.length !== 1) { await discardScopeGrant(auth, code); /* uniform invalid */ }
c.header('Cache-Control', 'no-store');
return { code, expiresIn };

A tenant-backed kind adds the routing hint and the epoch: ids carries tenantHint: cred.organizationId (the organization on the credential row, passed to issueScopeGrant too), the read returns tenantId and epoch, and the link takes epoch: read.epoch. On a platform kind both are refused with an error, so a call written for one shape never runs silently on the other: tenantHint (on any of the three) throws SCOPE_GRANT_TENANT_HINT_UNSUPPORTED, and epoch throws SCOPE_GRANT_EPOCH_UNSUPPORTED.

The caller's account is never an input. userId comes only from the subject read: the subject's own link or identity columns. The handout action must not read ctx.userId, cookies or a bearer, and no request field names a user. A caller signed in as some other account gets exactly what an anonymous caller gets, and is never linked. Call auth.api.createUser with no headers, so no session is consulted.

Squatting guard. An account found by the subject's email that is unverified and has a self-set credential (a password or a passkey) is refused (409 AUTH_EMAIL_UNPROVEN_ACCOUNT) unless the auth database proves it (a verified email, or a member row), or the subject read shows the subject already linked to exactly that user. Apply the guard to the winner of a lost create race too. The user clears it by verifying their email.

Because the code row usually belongs to an anonymous caller, the scoped db (which stamps the caller as the writer) refuses its writes. Declare unsafe: { reason, crossTenant: false } and consume through the features handle directly (createDb(env.DB) on D1, createServiceDb(env) on Postgres, where an anonymous caller's claims satisfy no policy); see Scoped database.

The four functions

FunctionDoesReturns
readScopeGrantSubject(env, { kind, instanceId, subjectId, tenantHint? })Platform kind: the instance and subject rows in the features database, in one transaction; an ok answer (subject, identity, instance projections) comes from one statement. Tenant-backed kind: the tenant read (qb.scopeGrantRead). Writes nothing.{ status: 'ok', subject: { email, name, linkedUserId, matchedRoles }, instance } (tenant-backed: plus tenantId and epoch), or denied / unavailable with a code
linkScopeGrantSubject(auth, { env, kind, instanceId, subjectId, tenantHint?, epoch?, userId, replaces?, requestId? })One conditional link with an audit row (event_kind: 'scope_grant_link', metadata { actorType: 'credential-mediated', userId, purpose: 'scope-grant-link', kind, instanceId, subjectId, requestId }, never a code or email). replaces is accepted only when that user no longer exists in the auth database. Tenant-backed: the tenant link (qb.scopeGrantLink) in one transaction; epoch is required and is the read's (a restore in between denies). Platform: see below.linked, conflict, denied or unavailable
issueScopeGrant(auth, { … })Admits and stores a single-use grant code (below).{ code, expiresIn }; throws on refusal
discardScopeGrant(auth, code)Consumes an unreturned code. A code already redeemed or expired is ignored.—

Routing (tenant-backed kinds): the tenant comes from the kind's lookup. tenantHint (the organization your action read from the credential row) is used only while the lookup has no row; a lookup that disagrees (SCOPE_GRANT_TENANT_MISMATCH) or is ambiguous (SCOPE_GRANT_TENANT_AMBIGUOUS) refuses. The tenant object checks that its own tenant, the instance row's and the subject row's all agree, so a wrong hint admits nobody. A platform kind has nothing to route: the subject's and the instance's organization columns must agree, checked in the same statement that reads or links. None of these functions is an HTTP endpoint.

Calling one with a kind that declares no serverGrant throws SCOPE_GRANT_NOT_DECLARED, and an id outside A-Z a-z 0-9 . _ ~ - throws SCOPE_GRANT_INVALID_ID (platform kinds): both are bugs in the calling action, not outcomes. On a platform kind every refusal is also logged as one JSON line (scope_grant.read_denied, scope_grant.link_denied, scope_grant.link_conflict, scope_grant.read_unavailable, scope_grant.link_unavailable) with the code, kind, instance, subject, request id and the rule that refused it, never an email or a credential.

Map the outcomes onto the action's response, disclosing conflict and denied only after step 1 proved the credential:

ClassMeaningResponseCredential
invalidunknown, expired or revoked credential; consume lost404 (uniform)not spent, or already spent
conflictemail collision, unproven account, subject linked to another live user409not spent
deniedsubject or instance not admittable or deleted, admission refused403 / 409not spent
unavailabletenant held, restoring, moving; transient RPC / auth / database error (FEATURES_DB_UNAVAILABLE, AUTH_DB_UNAVAILABLE); the audit row could not be written (SCOPE_GRANT_AUDIT_UNAVAILABLE on D1, FEATURES_DB_UNAVAILABLE on Postgres, where the link and the audit row fail together); unknown consume outcome503 + Retry-Afternot spent (unknown consume: see above)

Set Cache-Control: no-store on every grant response. The Idempotency-Key middleware never stores a no-store body, for any caller, so a retried key re-runs the action instead of replaying a grant code. Never log the credential, the grant code, the verifier or emails, and key rate limits on a hash of the code.

Platform kinds: atomicity and the audit row

The platform link never reads and then writes. linkScopeGrantSubject runs, in one transaction, statements in order (D1: one db.batch; Neon over HTTP: one db.batch, Neon's non-interactive transaction; Hyperdrive: one db.transaction):

  1. UPDATE <proving table> SET <user column> = :userId WHERE id = :subjectId AND <resource column> = :instanceId AND deleted_at IS NULL AND <admittable> AND <organization column> IS NOT NULL AND EXISTS (SELECT 1 FROM <instance table> WHERE id = :instanceId AND deleted_at IS NULL AND <live> AND <organization column> = <the subject's>) AND (<user column> IS NULL OR <user column> = :replaces) RETURNING id
  2. the instance row, and the subject row, re-read in the same transaction.

The WHERE is the whole re-check, evaluated against the rows as they are when the statement commits, so a change after the read (the guest declined, the event cancelled or moved to another organization, another user linked first) makes the update change nothing. The re-reads classify the refusal without another round trip: no live instance is SCOPE_NOT_FOUND, no admittable subject is SCOPE_GRANT_SUBJECT_DENIED, a subject already linked to userId is linked (nothing written, nothing audited), and any other link is SCOPE_GRANT_LINK_CONFLICT. Of two concurrent links for one unlinked subject, exactly one changes a row. On Postgres (READ COMMITTED) the second UPDATE waits on the first one's row lock, then re-evaluates its WHERE against the committed row, which is no longer unlinked.

Where the audit row goes depends on the provider.

  • Postgres (neon, planetscale-postgres). audit.events lives in the same database, so the link and its audit row are one statement: WITH linked AS (UPDATE … RETURNING id, <organization column>) INSERT INTO audit.events (…) SELECT … FROM linked. The audit row exists exactly when the link wrote, carries the linked row's organization, and commits or rolls back with it. There is no revert path: if the audit insert fails, the link never happened and the call answers unavailable (FEATURES_DB_UNAVAILABLE, with the database's reason in the scope_grant.link_unavailable log line).
  • D1. The audit row goes to the security audit database (AUDIT_DB), a separate D1 database no batch can reach, so it is appended right after the link commits. If that append fails, the link is reverted by one conditional update that only undoes this call's own write (… SET <user column> = :replaces WHERE id = :subjectId AND <user column> = :userId), the call answers unavailable (SCOPE_GRANT_AUDIT_UNAVAILABLE), and the credential is still unspent: no link stands without its audit row. If the revert fails too, the error log line scope_grant.audit_lost (kind, instance, subject, user and request id) is the only record of that link.

Which handle, on Postgres. Every statement of the read and the link runs on the service lane (createServiceDb). The caller is anonymous and the user being linked holds no relationship until the link commits, so no caller claims could satisfy the proving table's tenant policy, and audit.events admits only the service marker. The statements are fixed: their WHERE is the whole rule above (this instance, live, admittable, not soft-deleted, the subject's organization equal to the live instance's), the same rule D1, which has no RLS, relies on. Admission in issueScopeGrant and at every refresh still runs as the user, through the relationship's SECURITY DEFINER helper.

A platform kind has no epoch. The tenant epoch fences a restore of the organization object between the read and the link. A platform link never trusts the read, because every condition is re-evaluated by the update itself, so a stale read can only make the link refuse. A database restore (D1 Time Travel, a Postgres point-in-time restore) rewinds the whole features database, links included, and every refresh re-runs admission against the restored rows.

issueScopeGrant

issueScopeGrant refuses (throws) unless all of these hold:

  • The kind declares oauth, and resource (if given) is the kind's resource.
  • The client is admin-created with skip_consent, lists urn:quickback:params:oauth:grant-type:scope-grant in its grant_types, and has redirectUri among its redirect URIs.
  • The scopes are at most ['offline_access'] (the default): a bound grant carries no API scopes, so openid and anything an action forwards (such as admin) are refused. If the client registered scopes, they must include the requested ones.
  • The user exists, is not banned, and passes the kind's admission probe for instanceId.
  • For a platform kind that declares oauth.serverGrant: roles is exactly its ceiling (SCOPE_GRANT_CEILING_MISMATCH), and tenantHint and provingTable are refused (SCOPE_GRANT_TENANT_HINT_UNSUPPORTED).
  • For a tenant-backed kind: the kind declares oauth.serverGrant and roles is exactly its ceiling; the tenant resolves from the kind's lookup, or from tenantHint while the lookup has no row (a disagreeing hint refuses, and tenantHint on any other kind refuses); and the grant names the table subjectId lives in (provingTable, filled in from the ceiling).

roles and subjectId are mandatory server-authorized limits, proved by the action's credential check. Never forward them from client input. The role list is an allowed set, not a snapshot: an invitee or applicant may become an attendee after RSVP or staff approval, but cannot acquire an organizer role outside that set. Admission probes only those roles and the exact subject row before issuing, redeeming, or refreshing. The code and every rotated refresh grant retain this ceiling; replacing or cancelling the guest row cannot fall back to another relationship held by the same user. Bound REST and realtime requests also restrict rechecks to the token's current roles and subject. Refresh after an authorized role transition to receive the new role.

The app redeems the code at the token endpoint with its PKCE verifier:

POST /auth/v1/oauth2/token
grant_type=urn:quickback:params:oauth:grant-type:scope-grant
&code=<code>&code_verifier=<verifier>&client_id=<id>&redirect_uri=<uri>

It gets the same bound access and refresh tokens as the authorize flow, with the same qb_scope claim and confinement. Refreshes re-run admission as usual.

Redemption checks everything before it spends the code: it finds the code without consuming it, checks the client, its trust, the redirect URI, the PKCE verifier, the user and the ban, runs exact admission for the stored reference (503 temporarily_unavailable with the code intact when the tenant cannot answer, invalid_grant when it denies), and only then consumes exactly the row it checked (Better Auth's consumeVerificationValue: of concurrent redeemers, one wins). The token is issued after that, and its claims re-run admission once more. A revocation that lands between the two admissions burns the code and issues nothing (a window of milliseconds, fail closed).

The code:

  • is single-use; a failed redemption (wrong verifier, redirect or client, admission refused or unavailable) does not consume it, so the correct request can still redeem it until it expires;
  • expires after 120 seconds;
  • is stored only as a SHA-256 hash, in the verification table;
  • redeems only with the same client_id and redirect_uri and a code_verifier matching the challenge;
  • is refused with unauthorized_client if, between issuance and redemption, the client lost skip_consent or dropped the grant type.

No Better Auth session is created and emailVerified is never touched.

It is not an authorization_code because oauthProvider redeems those only against the live session that authorized them, and this path must not create one. The grant goes through oauthProvider's own extension-grant dispatch and issueTokens, so token format, refresh rotation, and revocation are unchanged.

issueScopeGrant is a server-side primitive; there is no HTTP endpoint for it. The calling action proves the credential, and that proof is the whole security boundary. Make the credential single-use or short-lived, compare it in constant time, and give the action its own rateLimit (for example rateLimit: { limit: 5, period: 60 }) so a handout code cannot be guessed. The bucket is keyed on the caller's userId. A caller without one, which is the usual case for a PUBLIC handout action, is keyed on cf-connecting-ip, falling back to one shared anon bucket when that header is absent. See how requests are keyed. An IP bucket does not stop a distributed guesser, so keep handout codes long and single-use as well. A PUBLIC action without one is flagged by ACTION_PUBLIC_WITHOUT_RATELIMIT.

On this page