Quickback Docs

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:

OptionDefaultMeaning
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)

CodeCause
PRINCIPAL_KIND_NEEDS_OAUTHThe 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_UNDECLAREDQB_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_INVALIDThe 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_UNSUPPORTEDThe project is not Cloudflare runtime + cloudflare-d1 features database + Better Auth. Other stacks are refused until they are tested.
PRINCIPAL_KIND_UNSUPPORTEDThe kind is tenant-backed. Not supported yet.
PRINCIPAL_TTL_INVALIDttl is outside 60s–12h or not in a supported form.

Keys

Principals are Ed25519 compact JWS tokens. The Worker reads two values:

NameKindValue
QB_PRINCIPAL_SIGNING_KEYsecret<kid>:<base64url PKCS#8 Ed25519 private key>
QB_PRINCIPAL_PUBLIC_KEYSvarJSON 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_KEY is a secret. It appears in the ops manifest's secret contract and in each named environment's required-secret inventory. Set it with quickback secrets push or wrangler secret put.
  • QB_PRINCIPAL_PUBLIC_KEYS is public. Declare it in quickback.config.ts, and the compiler writes it into wrangler.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)

  1. Add the new public key next to the old one: {"2026-12": "…", "2027-03": "…"}. Deploy.
  2. Switch QB_PRINCIPAL_SIGNING_KEY to the new kid. Deploy. New principals carry the new kid, and old ones still verify.
  3. After the longest ttl has 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 unexpired banExpires) 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 revokeScopeGrant writes. 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.

StatusCodeWhen
400PRINCIPAL_MINT_INVALID_REQUESTBody is not { kind, instanceId }, or kind has no principal.
401PRINCIPAL_MINT_UNAUTHENTICATEDNo session or bound token.
403PRINCIPAL_MINT_CREDENTIAL_REFUSEDAny other credential type.
403PRINCIPAL_MINT_BOUND_MISMATCHA bound token for a different kind or instance.
403PRINCIPAL_MINT_REFUSEDNo 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.
403PRINCIPAL_ANON_PREFIX_RESERVEDThe user id or the relationship row id starts with anon_.
403PRINCIPAL_MINT_SUBJECT_UNSUPPORTEDThe 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).
403PRINCIPAL_MINT_USER_BANNEDThe user is banned or no longer exists.
403PRINCIPAL_MINT_GRANT_REVOKEDThe bound token was issued before revokeScopeGrant revoked its instance. Reauthorize.
429RATE_LIMITEDMint rate limit, with Retry-After.
500PRINCIPAL_KEYS_MISCONFIGUREDSee Keys.
503PRINCIPAL_MINT_UNAVAILABLEThe 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:

ClaimValue
issquickback:<project name>
audThe Worker's BETTER_AUTH_URL, without a trailing slash
subThe 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_epAccess-code principals only: the code epoch it was minted at.
iat, expSeconds. exp - iat is the kind's ttl.
nbfOptional. 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 alg other than EdDSA, a wrong typ, a crit or b64 header, or an unknown kid;
  • any segment that is not canonical base64url, so each token has exactly one spelling;
  • an aud other than this Worker's BETTER_AUTH_URL;
  • a lifetime over 12 hours, an iat more than 60 seconds in the future, or an nbf that is not an integer or is more than 60 seconds in the future;
  • an undeclared kind or role;
  • qb_src: "code" unless the kind declares accessCodes; a code principal must carry exactly the code role, an anon_<uuid> subject and a positive qb_ep;
  • qb_ep on 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 revokeScopeGrant stop new mints, but a principal already issued stays valid until exp, even if the relationship row, the session or the bound token that minted it is removed first. Keep ttl short 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.create hook, PRINCIPAL_ANON_PREFIX_RESERVED), whatever generateId returns.
  • The mint and the access-code manage routes refuse a user or relationship row whose id starts with anon_.
  • generateWsTicket refuses a userId, or an identity tag whose id, that starts with anon_.
  • The verifier accepts an anon_ subject only on a qb_src: "code" principal.

See also

On this page