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.
An access code is a short string, such as SUMMIT26, that opens one instance of a scope kind to anyone who has it. The holder exchanges the code for a signed principal with an anon_ subject and one fixed role. That principal is accepted only by hot-path routes that name the role.
Use it for audiences that will never sign in: the people in a room voting on a poll, viewers of a live screen, attendees reacting to a talk.
A code is a weak credential. Anyone who sees it holds the role until it is rotated. Give the code role only what you would show the whole room.
A code principal's subjectId (anon_…) is chosen by the client and is free to mint: one device can join any number of times under new ids. Never treat it as identity, and never use it for one-person-one-vote. Return it only to the caller that holds the principal; never broadcast it to other clients, where it would let anyone act as that subject in your own logic.
Turn it on
Add accessCodes to a scope kind that already declares principal:
// 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" },
accessCodes: {
role: "audience", // the one role a code confers
manage: ["scope:workspace:member"], // who rotates, opens and closes it
ttl: "2h", // code-principal lifetime (default 2h, at most 12h)
join: { rateLimit: { perInstance: "300/10s", perAddress: "150/10s", perClient: "5/60s" } },
},
},
},
},| Option | Default | Meaning |
|---|---|---|
role | required | The role a code principal carries, as scope:<kind>:<role>. It must not be a role in roles: it has no relationship behind it. |
manage | required | scope:<kind>:<role> entries, from the kind's declared roles, that may manage the code. |
ttl | "2h" | Lifetime of a code principal. Same forms as principal.ttl, 60 seconds to 12 hours. |
join.rateLimit.perInstance | "300/10s" | Join attempts per instance, across every client. "<limit>/10s", "<limit>/60s", or { limit, period }. |
join.rateLimit.perAddress | half of perInstance, same period | Join attempts per client address (CF-Connecting-IP; an IPv6 address counts by its /64) per instance. Charged first, so one address cannot spend the whole instance budget. |
join.rateLimit.perClient | "5/60s" | Join attempts per client id per instance. |
A project with no accessCodes emits nothing new.
Set one more secret, at least 32 characters, per environment:
| Name | Kind | Value |
|---|---|---|
QB_ACCESS_CODE_PEPPER | secret | Random string. Codes are stored as HMAC-SHA256(pepper, kind, instance, code). |
It is in the boot guard, the ops manifest's secret contract and .dev.vars.example. A Worker whose pepper is missing or shorter than 32 characters answers every request 503 and logs which secret failed. Changing it invalidates every stored code; rotate each instance afterwards. The plain code is never stored or logged.
Where the state lives
- The authority is one row per instance in the
qb_access_codestable in the features database (its binding:featuresBinding, defaultDB; on a single database,binding), emitted only when a kind declaresaccessCodesand created by your normal migrations. Every manage op is one atomic statement on that row. - A projection of the row is written to the project's
KVnamespace underqb:ac:<kind>:<instanceId>. The join route and hot paths read only the projection (no database read), cached for 30 seconds.
So a change reaches every Cloudflare location within about 60 seconds: up to 30 seconds of the local cache plus KV propagation. Until then a location may still admit joins, or accept principals, under the previous state.
Requirements (compile errors)
| Code | Cause |
|---|---|
ACCESS_CODE_KIND_NEEDS_PRINCIPAL | The kind has no principal. |
ACCESS_CODE_ROLE_INVALID | role is not a plain role name. |
ACCESS_CODE_ROLE_DECLARED | role is also a declared relationship role of the kind. |
ACCESS_CODE_MANAGE_INVALID | manage is empty, or an entry is not scope:<kind>:<declared role>. |
ACCESS_CODE_TTL_INVALID | ttl is outside 60s–12h. |
ACCESS_CODE_RATE_LIMIT_INVALID | A period other than 10s or 60s, a bad limit, or any key other than perInstance / perAddress / perClient. |
ACCESS_CODE_TURNSTILE_UNSUPPORTED | join.turnstile. Not in this release. |
ACCESS_CODE_UPGRADE_UNSUPPORTED | upgradeFrom. Not in this release. |
Warning: ACCESS_CODE_JOIN_LIMIT_RAISED when perInstance allows more attempts per second than the default (30/s). It raises the guessing rate; see Guessing.
The role ceiling
The code role reaches hot-path routes that list it, and nothing else. The compiler refuses it anywhere else:
| Where | Code |
|---|---|
Resource read, CRUD, views, firewall, masking, FGA, namespaces, any other authz block | ACCESS_CODE_ROLE_OUTSIDE_CEILING |
An ordinary action (no hotPath: true) | ACCESS_CODE_ROLE_NEEDS_HOT_PATH |
| A realtime ticket gate or listener | ACCESS_CODE_ROLE_NOT_LISTENER |
A hot path whose path lacks :<requestField> | ACCESS_CODE_ROLE_INSTANCE_UNBOUND |
| A hot path with no rate limit | HOT_PATH_CODE_ROLE_NEEDS_RATE_LIMIT |
A hot path rate-limited by subject only, including an inherited project default | HOT_PATH_CODE_ROLE_SUBJECT_ONLY_RATE_LIMIT |
Feature and action files are scanned for the literal "scope:<kind>:<role>", so function-form access is caught too. A subject-only limit does not bound a code holder, who can mint any number of anon_ subjects, so declare key: ["subject", "instance"]. Both keys share the one limit: the instance counter counts every caller, so limit is what the whole instance may spend per period on that route, members and code holders together (see Hot-path rate limits). Size it for the room.
// quickback/features/workspaces/actions/livePing.ts
import { z } from "zod";
import { defineAction } from "../.quickback/define-hot-path-action";
export default defineAction({
description: "Record a reaction from anyone in the room.",
path: "/live/:workspaceId/ping",
method: "POST",
hotPath: true,
access: { roles: ["scope:workspace:member", "scope:workspace:audience"] },
rateLimit: { key: ["subject", "instance"], limit: 100, period: 60 },
input: z.object({ note: z.string().max(200).optional() }),
async execute({ params, principal }) {
// Returned only to this caller. Do not broadcast principal.subjectId to other clients.
return { workspaceId: params.workspaceId, anonymous: principal.anonymous };
},
});At runtime a code principal is also refused by every route the compiler did not mark as a hot path: CRUD and actions answer 401, and the principal mint does not accept it. It never sets ctx.userId, ctx.scope or a session, and Better Auth never sees it.
Manage: POST /auth/v1/access-codes/<op>
A signed-in caller (session or Quickback JWT) holding one of the manage roles on the instance manages its code. Before any change the route runs the checks the principal mint runs: the ban check, then the kind's relationship proof. Each change is applied to the database row, then projected. Manage routes read the KV projection only uncached, as a floor: never as the state to change.
| Op | Body | Effect |
|---|---|---|
rotate | { kind, instanceId, code? } | Sets a new code and raises the epoch, so every outstanding code principal stops working. Omit code to have a 10-character code generated (no 0 O 1 I L). Returns code once. A first rotate creates the code, open. |
open | { kind, instanceId, closesAt? } | Accepts joins. closesAt is unix seconds, at most a year ahead, or null. Without closesAt, a deadline still ahead is kept and one already passed is cleared. |
close | { kind, instanceId, revoke? } | Stops joins. Issued principals keep working until they expire, unless revoke: true, which also raises the epoch. Locations still holding the open state in cache admit joins for up to about 60 seconds; to cut off everyone at once, rotate or close with revoke. |
status | { kind, instanceId } | { configured, open, epoch, closesAt }. Never the code. Also writes the KV projection from the database row when it is missing or behind the row, which repairs a projection that failed or was lost. A current projection is not rewritten. |
The epoch is unix seconds. Each raise sets it to max(epoch + 1, now, published epoch + 1), so it never repeats or goes back. Concurrent changes are serialized by the database. After each KV write the row is re-read, and a newer row is written too, so KV ends on the newest row.
KV accepts about one write per second to the same key. A projection write that fails is retried 1.1 seconds later, up to three times, inside the request. A manage call can therefore take a few seconds when changes arrive back to back. It answers 200 only once the projection holds its change, or a newer one.
After a database restore, rotate
A database restored to an earlier point (D1 Time Travel, a backup) holds an older epoch than the KV projection. Writing that row to KV would re-accept every principal a rotation or revoke since cut off. Instead:
open,closewithoutrevoke, andstatusrefuse with 409ACCESS_CODE_STATE_REGRESSEDand leave KV unchanged. The refusal names both epochs and revs in the log.rotate, orclosewithrevoke: true, reads the published epoch and rev and sets the row above both. That publishes cleanly and recovers the instance.
After restoring the features database, rotate every instance that has a code.
POST /auth/v1/access-codes/rotate
Content-Type: application/json
Cookie: <session>
{ "kind": "workspace", "instanceId": "ws_123", "code": "summit-26" }{ "kind": "workspace", "instanceId": "ws_123", "configured": true, "open": true, "epoch": 1765000000, "closesAt": null, "code": "SUMMIT26" }Codes are case-insensitive and ignore spaces and hyphens: summit-26 and SUMMIT 26 are the same code. After that, a code is 8 to 64 of A-Z 0-9. A chosen code is also refused (ACCESS_CODE_TOO_WEAK) when it has fewer than 4 distinct characters, or is under 10 characters and all digits or all letters. Prefer generated codes; see Guessing.
Every change writes two security-audit rows (event_kind: 'access_code', the user as actor, the instance as target_record_id, the op). They are linked by metadata.changeId, an id the server mints per change and also stores on the database row as change_id. A caller-supplied x-request-id never links them; the inbound requestId is recorded beside it, and both are logged.
result: 'attempt', before the change. If it cannot be written, nothing changes (503ACCESS_CODE_UNAVAILABLE).- The outcome after the change:
successwith the resulting epoch, open state andclosesAt, orerrorwith the code (ACCESS_CODE_UNAVAILABLE,ACCESS_CODE_NOT_SET,ACCESS_CODE_NOT_PROPAGATED,ACCESS_CODE_STATE_REGRESSED).
An attempt with no outcome row means the Worker stopped mid-change; the database row's change_id says whether the change landed. The plain code is never in either row.
| Status | Code | When |
|---|---|---|
| 400 | ACCESS_CODE_MANAGE_INVALID_REQUEST | Body is not the op's fields, unknown kind, bad instanceId, closesAt or revoke. |
| 400 | ACCESS_CODE_FORMAT_INVALID | A chosen code is not 8–64 letters and digits after normalization. |
| 400 | ACCESS_CODE_TOO_WEAK | A chosen code fails the strength rules above. The reason names the rule, never the code. |
| 400 | INVALID_CONTENT_LENGTH | Content-Length is not a byte count. |
| 401 | ACCESS_CODE_MANAGE_UNAUTHENTICATED | No session or JWT. |
| 403 | ACCESS_CODE_MANAGE_CREDENTIAL_REFUSED | API key, OAuth or MCP token, share link. |
| 403 | ACCESS_CODE_MANAGE_REFUSED | No manage role on the instance, the instance does not exist, or the user is banned. One answer for all three; the log says which. |
| 403 | PRINCIPAL_ANON_PREFIX_RESERVED | The user id starts with anon_. |
| 404 | ACCESS_CODE_MANAGE_UNKNOWN_OP | An op other than the four above. |
| 409 | ACCESS_CODE_NOT_SET | open or close before the first rotate. |
| 409 | ACCESS_CODE_STATE_REGRESSED | The database row is behind the published projection: the database was restored. For open / close the row changed but KV did not. rotate (or close with revoke) to recover; see After a database restore. |
| 413 | PAYLOAD_TOO_LARGE | Body over 4 KiB. |
| 429 | RATE_LIMITED | Per-user limit on the project-default update bucket. |
| 500 | ACCESS_CODE_MISCONFIGURED | QB_ACCESS_CODE_PEPPER is missing or shorter than 32 characters. |
| 503 | ACCESS_CODE_UNAVAILABLE | The database, the relationship check, the published-state read (rotate, revoke) or the attempt audit write failed. Nothing changed. |
| 503 | ACCESS_CODE_NOT_PROPAGATED | The change is saved, but the KV projection could not be written after three tries, so joins and hot paths still see the old state. POST status for the instance to republish it. The body carries state (the saved row). For rotate it also carries newCode, the new code (Cache-Control: no-store): the row already holds it, so do not rotate again. The new code works once the projection is written; the old one works until then. |
Join: POST /auth/v1/access-codes/join
POST /auth/v1/access-codes/join
Content-Type: application/json
{ "kind": "workspace", "instanceId": "ws_123", "code": "summit 26", "clientId": "anon_6f1c2a4e-3b0d-4c2e-9a51-0d7f3c8e2b11" }{
"principal": "eyJhbGciOiJFZERTQSIs…",
"tokenType": "Bearer",
"kind": "workspace",
"instanceId": "ws_123",
"roles": ["audience"],
"source": "code",
"subjectId": "anon_6f1c2a4e-3b0d-4c2e-9a51-0d7f3c8e2b11",
"expiresAt": 1765007200
}clientId is anon_ followed by a lowercase UUID. Generate it once on the device and keep it; it becomes the principal's subject, so hot-path rate limits and audit rows follow the device. Send the principal as Authorization: Bearer <principal> to the hot paths that accept the code role. Join again before expiresAt.
The join route is mounted ahead of the database, auth and services middleware. It never reads or writes the database, creates no Better Auth user and no OAuth row, and writes no audit row. In order it:
- checks the body shape (400, no I/O);
- applies the per-address, then the per-instance, then the per-client rate limit (429), before any KV read or hashing. The address is
CF-Connecting-IP: an IPv4 address as is, an IPv6 address by its /64, an IPv4-mapped IPv6 address as IPv4. Without the header (no Cloudflare edge in front:wrangler dev, tests) every caller shares onenonebucket per instance, and an unparseable value shares oneinvalidbucket; - reads the code projection from KV (cached for 30 seconds) and computes one HMAC, whether or not a record exists;
- signs a principal:
sub=clientId, the code role only,qb_src: "code",qb_ep= the current epoch,aud=BETTER_AUTH_URL.
A wrong code, an instance with no code, a closed code and a passed closesAt all answer the same 401 body, so the route cannot be used to learn which instances exist. Each refusal is logged (access_code_join_refused) with the exact reason, kind, instance, client id and request id, never the submitted code. With EXPOSE_ERROR_STACK set (dev, preview), the reason is also in details.reason.
| Status | Code | When |
|---|---|---|
| 400 | ACCESS_CODE_INVALID_REQUEST | Body is not { kind, instanceId, code, clientId }, the kind has no access codes, or clientId is not anon_<uuid>. |
| 401 | ACCESS_CODE_INVALID | Wrong code, no code set, closed, or past closesAt. |
| 400 | INVALID_CONTENT_LENGTH | Content-Length is not a byte count. |
| 413 | PAYLOAD_TOO_LARGE | Body over 4 KiB. |
| 429 | ACCESS_CODE_RATE_LIMITED | Per-address, per-instance or per-client limit, with Retry-After. The log names which. |
| 500 | ACCESS_CODE_MISCONFIGURED | QB_ACCESS_CODE_PEPPER missing or short. |
| 500 | PRINCIPAL_KEYS_MISCONFIGURED | See Keys. |
| 503 | ACCESS_CODE_UNAVAILABLE | A rate-limit binding is not bound, or the KV read failed. |
Guessing and lockout
The client id is chosen by the client, so the per-client limit only protects honest clients from themselves. The per-instance limit is the bound on guessing. The per-address limit is always paired with the instance, never used alone, and is generous, because a venue can put thousands of phones behind one address. IPv6 addresses count by /64, because one subscriber usually holds a whole /64 and could otherwise rotate addresses within it.
Cloudflare rate limits count per location. An attacker who sends from many Cloudflare locations gets the per-instance budget at each of them, so the effective guess rate is the limit times the number of locations used. With the default 300 per 10 seconds (30/s) at, say, 300 locations, that is about 9,000 guesses per second against one instance, and each location needs at least two attacking addresses to spend its budget. Size codes for that:
| Code | Possibilities | Expected time to guess at 9,000/s | At one location (30/s) |
|---|---|---|---|
| Generated, 10 of 31 characters | ~8 × 10^14 (2^49) | ~1,400 years | — |
| Chosen, 8 letters and digits (random) | ~2.8 × 10^12 (2^41) | ~5 years | — |
| Chosen, 10 letters (random) | ~1.4 × 10^14 (2^47) | ~250 years | — |
| Chosen, 10 digits (random) | 10^10 (2^33) | ~6 days | ~5 years |
| A word, a name, an event slug | small | minutes | hours |
A chosen code is only as strong as it is random: the strength rules stop PINs and short words, not SUMMIT2026. Rotate codes when an event ends, and use generated codes for anything that matters. Raising perInstance raises every row's rate (the compiler warns with ACCESS_CODE_JOIN_LIMIT_RAISED).
Lockout. The same per-instance budget is shared by honest joins. A flood of wrong guesses can use it up and delay real joins on that instance until the window passes (10 or 60 seconds). The per-address limit, charged first, means one address can spend at most half of it, so a single host cannot lock an instance out alone; an attacker with many addresses still can. Instances do not affect each other. If joins are refused under attack, rotate does not help (the budget is per instance, not per code); wait for the window, or move the room to a new instance.
Revocation
Every code principal carries the epoch it was minted at (qb_ep). A hot path checks it against the instance's KV projection before running, and refuses one older than the projection's epoch with 401 PRINCIPAL_EPOCH_STALE. A principal newer than a location's cached projection is accepted: it was minted after a rotation that location has not seen yet. The check reads a 30-second cache, so a rotation takes effect everywhere within about 60 seconds.
| To | Do |
|---|---|
| Stop new joins, keep the room | close |
| Kick everyone holding the code | rotate (new code) or close with revoke: true |
| Revoke every principal on every instance | Rotate the principal keys |
Hot paths and the audit log
For a code principal, a hot path checks the role, then the instance, then the epoch, and charges its rate limit only once all three pass. A code holder calling a members-only route is refused (403) without spending the instance bucket members share, so it cannot lock them out. Every refusal of a code principal (wrong role, wrong instance, stale epoch, rate limit, body, validation) is logged (hot_path_refused) with the exact reason and request id, but not audited. An anonymous caller could otherwise turn refusals into an unbounded stream of audit rows. A refusal therefore costs a code holder no more than an invalid principal does. Successful calls are audited like any other, with the anon_ subject as actor; the route's mandatory instance-keyed limit bounds them.
If the route's rate-limit binding is missing at runtime, a code principal is refused with 503 HOT_PATH_RATE_LIMIT_UNAVAILABLE rather than let through unlimited. If KV cannot be read, the hot path answers 503 ACCESS_CODE_UNAVAILABLE.
Deploy
Access codes use the features database (qb_access_codes, applied by your normal migrations), the project KV namespace and RL_<limit>_<period> rate-limit bindings, all emitted into wrangler.toml. They need signed principals, whose public-key var the brokered deploy cannot upload yet, so deploy with wrangler deploy.
Not in this release
- Turnstile on join (
join.turnstile). - Upgrading a code principal to an account (
upgradeFrom). - Realtime tickets for code principals.
audit: "aggregate"for high-volume hot paths.
See also
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.
Arrows
Traverse a foreign key to inherit authority from a parent object — "you can see this row because you administer the organization it belongs to", or "because you control an ancestor in the tree". Declared once under authz.arrows, referenced from a permission, lowered to an FK-hop subquery or a bounded WITH RECURSIVE CTE.