Signed Principals
Short-lived Ed25519 tokens that carry a proven scope role for one instance, minted from a session or an instance-bound token and verified with no database read. The credential hot-path routes accept.
A signed principal is a short-lived token that says "user U holds role R on instance I of scope kind K, until T". The Worker mints it once, after the kind's own relationship proof. Any route that accepts it can then check it with a signature and a clock, without a database read or a Better Auth call.
Principals are the credential for hot-path routes: high-frequency endpoints that run ahead of the database, auth and services middleware.
Signed principals are not the same as delegated principals (auth.principals, ctx.principal). Delegated principals are non-account authority admitted by the normal auth middleware. Signed principals are minted from an existing session or instance-bound token, and only hot-path routes accept them.
Turn it on
Add principal to a scope kind that already declares oauth:
// quickback/quickback.config.ts (excerpt)
authz: {
relationships: {
memberOf: {
from: "workspace_members",
subject: { column: "memberUserId", equals: "ctx.userId" },
resource: { column: "workspaceId" },
where: { status: "active" },
},
},
scopes: {
workspace: {
requestField: "workspaceId",
roles: { member: { via: "memberOf" } },
oauth: {},
principal: { ttl: "10m" }, // default 15m, at most 12h
},
},
},principal takes one option:
| Option | Default | Meaning |
|---|---|---|
ttl | "15m" | Lifetime of a minted principal. Seconds (600) or "<n>s", "<n>m", "<n>h". Between 60 seconds and 12 hours. |
A project with no principal on any kind emits nothing new. No mint route, no keys, and no change to the generated output.
Requirements (compile errors)
| Code | Cause |
|---|---|
PRINCIPAL_KIND_NEEDS_OAUTH | The kind has no oauth. The mint runs the relationship check instance-bound tokens are issued on (admitScopeOAuth, including precedence and instance liveness). It also runs the ban and grant-revocation checks; see Mint. |
PRINCIPAL_PUBLIC_KEYS_UNDECLARED | QB_PRINCIPAL_PUBLIC_KEYS is not in bindings.vars, and a named environment has no worker.vars value either. The error shows the line to add. A project that supplies the keys out of band can declare the name in bindings.secrets instead. |
PRINCIPAL_PUBLIC_KEYS_INVALID | The declared value is not a JSON object of one to four kids, each mapped to a canonical base64url, 32-byte raw Ed25519 public key. |
PRINCIPAL_PROVIDER_UNSUPPORTED | The project is not Cloudflare runtime + cloudflare-d1 features database + Better Auth. Other stacks are refused until they are tested. |
PRINCIPAL_KIND_UNSUPPORTED | The kind is tenant-backed. Not supported yet. |
PRINCIPAL_TTL_INVALID | ttl is outside 60s–12h or not in a supported form. |
Keys
Principals are Ed25519 compact JWS tokens. The Worker reads two values:
| Name | Kind | Value |
|---|---|---|
QB_PRINCIPAL_SIGNING_KEY | secret | <kid>:<base64url PKCS#8 Ed25519 private key> |
QB_PRINCIPAL_PUBLIC_KEYS | var | JSON object of kid → base64url raw 32-byte public key. One to four keys. |
Both are in the generated boot guard. A Worker missing either one answers 503 at boot rather than failing on the first call. The worker also needs BETTER_AUTH_URL, which every principal's aud is bound to (see One key pair per environment).
QB_PRINCIPAL_SIGNING_KEYis a secret. It appears in the ops manifest's secret contract and in each named environment's required-secret inventory. Set it withquickback secrets pushorwrangler secret put.QB_PRINCIPAL_PUBLIC_KEYSis public. Declare it inquickback.config.ts, and the compiler writes it intowrangler.toml[vars]:
// quickback/quickback.config.ts (excerpt)
bindings: {
vars: { QB_PRINCIPAL_PUBLIC_KEYS: '{"2026-12":"<base64url raw Ed25519 public key>"}' },
},
// Named environments: one value per target.
environments: {
staging: { name: "app-staging", worker: { vars: { QB_PRINCIPAL_PUBLIC_KEYS: '{"stg-2026-12":"…"}' } } },
production: { name: "app", worker: { vars: { QB_PRINCIPAL_PUBLIC_KEYS: '{"prd-2026-12":"…"}' } } },
},The compiler checks the value's shape at compile time. The ops manifest lists the var under vars.required, and .dev.vars.example carries a commented # QB_PRINCIPAL_PUBLIC_KEYS= line. Leave it commented: wrangler dev already reads [vars], and an empty .dev.vars line would override the value with an empty string. The brokered deploy does not upload vars yet. Its manifest lists the var and carries a principal-keys-unsupported entry, so deploy a project with principals using wrangler deploy.
One key pair per environment
Give every environment (production, staging, preview, local) its own key pair. Never copy a signing key between environments.
A principal's aud is the Worker's BETTER_AUTH_URL, without a trailing slash, and verifiers refuse any other audience. A principal minted on staging is refused by production even when both publish the same public keys. The audience check is the backstop, not the boundary: a leaked staging signing key would still sign tokens with production's aud. When two environments publish the same QB_PRINCIPAL_PUBLIC_KEYS, the compile warns with PRINCIPAL_KEYS_SHARED_ACROSS_ENVIRONMENTS. A Worker without BETTER_AUTH_URL cannot mint or verify; both fail with PRINCIPAL_KEYS_MISCONFIGURED.
Generate a key pair per environment (Node 20+ or Bun):
const pair = await crypto.subtle.generateKey({ name: "Ed25519" }, true, ["sign", "verify"]) as CryptoKeyPair;
const b64u = (b: ArrayBuffer) => Buffer.from(b).toString("base64url");
const kid = "2026-12";
console.log(`QB_PRINCIPAL_SIGNING_KEY=${kid}:${b64u(await crypto.subtle.exportKey("pkcs8", pair.privateKey))}`);
console.log(`QB_PRINCIPAL_PUBLIC_KEYS=${JSON.stringify({ [kid]: b64u(await crypto.subtle.exportKey("raw", pair.publicKey)) })}`);The signer refuses to mint (500 PRINCIPAL_KEYS_MISCONFIGURED) if the signing kid is missing from QB_PRINCIPAL_PUBLIC_KEYS, or if the public key listed there does not match the private key. Every verifier would refuse such a principal, so the mint fails instead of handing it out. The reason goes to the log and never includes key material.
Rotation (two keys)
- Add the new public key next to the old one:
{"2026-12": "…", "2027-03": "…"}. Deploy. - Switch
QB_PRINCIPAL_SIGNING_KEYto the new kid. Deploy. New principals carry the new kid, and old ones still verify. - After the longest
ttlhas passed, remove the old public key.
Mint: POST /auth/v1/principal
POST /auth/v1/principal
Content-Type: application/json
Cookie: <session> # or Authorization: Bearer <instance-bound OAuth token>
{ "kind": "workspace", "instanceId": "ws_123" }{
"principal": "eyJhbGciOiJFZERTQSIs…",
"tokenType": "Bearer",
"kind": "workspace",
"instanceId": "ws_123",
"roles": ["member"],
"source": "session",
"expiresAt": 1765000000
}Two credentials can mint:
- A session (or a Quickback JWT):
source: "session". The kind's relationship proof runs once, here. - An instance-bound OAuth token for the same kind and instance:
source: "scope-token". The principal's roles never exceed the token's. A bound token reaches the mint path, and nothing else outside its instance's namespace.
Before the relationship check, the mint runs the checks that bound-token issuance and refresh run:
- Ban. A banned user (Better Auth admin
banned, with an unexpiredbanExpires) mints nothing, whichever credential they present. The check reads the user row, so a session or JWT issued before the ban is refused too. - Grant revocation. For a bound token, the mint reads the marker
revokeScopeGrantwrites. A token issued before the revocation mints nothing, even while it has not expired yet. A token issued after it mints normally.
API keys, MCP tokens, share links and OAuth tokens that are not instance-bound cannot mint (403 PRINCIPAL_MINT_CREDENTIAL_REFUSED). The body must be exactly { kind, instanceId }; instanceId uses A-Z a-z 0-9 . _ ~ -, at most 128 characters. The mint is rate-limited per user on the project-default update bucket. The response is Cache-Control: no-store.
| Status | Code | When |
|---|---|---|
| 400 | PRINCIPAL_MINT_INVALID_REQUEST | Body is not { kind, instanceId }, or kind has no principal. |
| 401 | PRINCIPAL_MINT_UNAUTHENTICATED | No session or bound token. |
| 403 | PRINCIPAL_MINT_CREDENTIAL_REFUSED | Any other credential type. |
| 403 | PRINCIPAL_MINT_BOUND_MISMATCH | A bound token for a different kind or instance. |
| 403 | PRINCIPAL_MINT_REFUSED | No relationship proves a role on that instance, or the instance does not exist. One answer for both, so the mint cannot be used to enumerate instance ids. The log carries which. |
| 403 | PRINCIPAL_ANON_PREFIX_RESERVED | The user id or the relationship row id starts with anon_. |
| 403 | PRINCIPAL_MINT_SUBJECT_UNSUPPORTED | The user id has characters outside A-Z a-z 0-9 . _ ~ - or is over 128 characters, so no verifier would accept it (a custom generateId). |
| 403 | PRINCIPAL_MINT_USER_BANNED | The user is banned or no longer exists. |
| 403 | PRINCIPAL_MINT_GRANT_REVOKED | The bound token was issued before revokeScopeGrant revoked its instance. Reauthorize. |
| 429 | RATE_LIMITED | Mint rate limit, with Retry-After. |
| 500 | PRINCIPAL_KEYS_MISCONFIGURED | See Keys. |
| 503 | PRINCIPAL_MINT_UNAVAILABLE | The ban, revocation or relationship check could not run, or the audit row could not be written (database error). |
Every successful mint writes a security-audit row before the token is returned: event_kind: 'principal_mint', the user as actor, the instance as target_record_id, and metadata naming the kind, roles, source, kid and expiry (never the token). If the row cannot be written, the mint fails with 503. Refused mints are logged with their reason and request id.
The token
Header: {"alg":"EdDSA","typ":"qb-principal+jwt","kid":"…"}. Claims:
| Claim | Value |
|---|---|
iss | quickback:<project name> |
aud | The Worker's BETTER_AUTH_URL, without a trailing slash |
sub | The user id, or the client's anon_ id on an access-code principal |
qb_scope | { kind, id, roles, subjectId }. subjectId is the conferring relationship row. |
qb_src | "session", "scope-token", or "code" (an access-code principal) |
qb_ep | Access-code principals only: the code epoch it was minted at. |
iat, exp | Seconds. exp - iat is the kind's ttl. |
nbf | Optional. The mint does not set it; when present, it is enforced. |
The verifier is a pure function, with no database and no Better Auth. It allows 60 seconds of clock leeway. It refuses:
- any
algother thanEdDSA, a wrongtyp, acritorb64header, or an unknownkid; - any segment that is not canonical base64url, so each token has exactly one spelling;
- an
audother than this Worker'sBETTER_AUTH_URL; - a lifetime over 12 hours, an
iatmore than 60 seconds in the future, or annbfthat is not an integer or is more than 60 seconds in the future; - an undeclared kind or role;
qb_src: "code"unless the kind declaresaccessCodes; a code principal must carry exactly the code role, ananon_<uuid>subject and a positiveqb_ep;qb_epon any other principal;- an
anon_subject on any other principal.
A verified principal becomes:
interface Principal {
subjectId: string; // sub
anonymous: boolean; // true only for access-code principals
kind: string;
instanceId: string;
roles: readonly string[];
source: "session" | "scope-token" | "code";
expiresAt: number;
epoch?: number; // access-code principals only (qb_ep)
}A principal never becomes ctx.userId, ctx.scope or a session. Only hot-path routes read it.
What a principal does not do
- Revocation of an issued principal is by expiry. Ban and
revokeScopeGrantstop new mints, but a principal already issued stays valid untilexp, even if the relationship row, the session or the bound token that minted it is removed first. Keepttlshort for kinds where removal must take effect quickly. Rotating the keys revokes every outstanding principal at once. - Ordinary routes do not accept it. CRUD, views, actions and namespaces ignore principals. Use the session or bound token there.
The anon_ prefix
anon_ is reserved for access-code subjects. When any scope kind declares principal:
- Better Auth refuses to create a user whose id starts with
anon_(user.createhook,PRINCIPAL_ANON_PREFIX_RESERVED), whatevergenerateIdreturns. - The mint and the access-code manage routes refuse a user or relationship row whose id starts with
anon_. generateWsTicketrefuses auserId, or an identity tag whose id, that starts withanon_.- The verifier accepts an
anon_subject only on aqb_src: "code"principal.
See also
- Hot-path routes, the routes that accept principals
- Access codes, principals for anonymous code holders
- Scopes, the relationship proof a principal carries
- Rate limits
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.
Access Codes
Let anyone holding a short code for one scope instance (a room, a session, an event screen) call that instance's hot-path routes, with a fixed role, no account, no database read, and revocation by rotating the code.