Quickback Docs

Cloudflare Access

Put Cloudflare Access in front of the Worker, a hostname, or a route group. The generated Worker verifies the Access JWT itself and maps the identity to a Better Auth user and role.

Set auth.cloudflareAccess to put Cloudflare Access in front of operator or staff routes. Inside an application's scope, the generated Worker authenticates the request only from the Cf-Access-Jwt-Assertion header, and verifies it on every request. It never trusts the header just because it is present.

quickback.config.ts
export default defineConfig({
  // ...
  auth: {
    cloudflareAccess: {
      teamDomain: 'acme.cloudflareaccess.com',
      aud: { env: 'CF_ACCESS_AUD' },
      hosts: ['ops.example.com'],
      roles: ['sysadmin'],
      serviceTokens: { '88bf3b6d86161464f6509f7219099e57.access': 'deploy-bot@example.com' },
    },
  },
});

Requires the cloudflare runtime, the better-auth auth provider, and the cloudflare-d1 database. Anything else is a compile error. Postgres is refused for now: the lane's user lookup carries no RLS claims, so under RLS it would find no user.

Every Access setting comes from quickback.config.ts or, for teamDomain and aud, from a Worker var named with { env }. None can come from the database or anything an admin can edit at runtime: whoever could change them could point the Worker at their own Access team. Both teamDomain and aud are required on every application, so the config can never be half-configured; an { env } var that is unset, or set without its partner, gives 500 CF_ACCESS_MISCONFIGURED on every request in scope, never a pass.

What the Worker verifies

For a request inside an application's scope:

  1. Cf-Access-Jwt-Assertion is present. Otherwise 401 CF_ACCESS_REQUIRED.
  2. The token is an application token (type: "app"), RS256-signed by a key in https://<teamDomain>/cdn-cgi/access/certs. iss equals https://<teamDomain>, aud contains the configured AUD tag, and exp is present and in the future. Otherwise 401 CF_ACCESS_INVALID.
  3. The identity maps to an existing Better Auth user, as described in Identity mapping. Otherwise 403 CF_ACCESS_UNMAPPED.
  4. The resulting userRole is in roles. Otherwise 403 CF_ACCESS_ROLE_NOT_ADMITTED.

aud is the application's AUD tag: 64 lowercase hex characters. A literal aud in any other format fails the compile. An { env } value is checked at request time: a value in any other format gives 500 CF_ACCESS_MISCONFIGURED.

The Worker caches the JWKS per isolate. It refetches on an unknown kid (at most once per 30 seconds) and once the cached set is 10 minutes old. Both cover Access key rotation.

Inside the scope, the Access assertion is the only credential:

  • A session cookie, a bearer JWT, or an API key does not authenticate the request. A refused assertion never falls back to them.
  • Better Auth's own routes, /auth/v1 and everything under it, get 403 CF_ACCESS_AUTH_ROUTE_REFUSED, whatever the assertion. They authenticate with Better Auth's session cookie, so they would be a second credential. This covers sign-in, get-session, and GET /auth/v1/token. Better Auth's admin-plugin routes (/auth/v1/admin/ban-user and the rest) are refused too. Quickback's own operator and roster routes are not under /auth/v1 since 0.72 (they are under /api/v1/operator and /api/v1/organization/roster), so they are ordinary routes here. Until 0.73.0, the deprecated aliases this project actually emits (/auth/v1/admin/list-organizations and siblings with cms.sysadmin or account.auth.admin, /auth/v1/organization/roster with auth.organizationRoster) are served to Access callers too.
  • The CMS and Account SPAs sign in through those Better Auth routes. Do not put their hostnames, or /auth/v1, inside an Access scope.

On success, ctx has authMethod: 'cloudflare-access', the user's userId, userRole, and user, plus ctx.cloudflareAccess: { type: 'user' | 'service-token', email?, commonName?, groups? }. An action can require it: access: { userRole: ['sysadmin'], authMethod: ['cloudflare-access'] } refuses the same sysadmin on a session cookie (authMethod).

The operator plane

The operator control plane (cms.sysadmin or account.auth.admin) lives under one prefix, /api/v1/operator (/api/v2/operator on contract v2). One paths application gates all of it:

cloudflareAccess: {
  teamDomain: 'acme.cloudflareaccess.com',
  aud: { env: 'CF_ACCESS_AUD' },
  paths: ['/api/v1/operator'],
  roles: ['appmanager', 'sysadmin'],
}

During the compatibility window, each known Quickback operation must satisfy the most specific Access application on both its legacy path and its canonical path, whichever entry point the caller uses. A rule on /auth/v1/admin keeps protecting old callers; a rule on /api/v1/operator/organizations/<id>/members also protects legacy member mutations for that organization. Neither policy replaces the other. Counterparts are operation-specific: GET list and POST create are distinct, as are PUT set-member and DELETE remove-member. HEAD follows the matching GET operation. The roster and email-readiness aliases are mapped too; unrelated routes do not inherit a whole old or new prefix. The same application selected on both paths is checked once; distinct applications are checked separately even if they share an AUD.

The Worker receives one assertion header. If the two applications have different AUDs, that assertion must satisfy both; different teams cannot share one valid issuer. Identity and effective role mappings must also agree, or the request returns 403 CF_ACCESS_POLICY_CONFLICT. Use one application covering both prefixes with consistent mappings, or reconcile the policies before migrating callers. Moving to the canonical route does not bypass a policy on its legacy counterpart.

Legacy member mutations trim organizationId and userId through the same helper used for policy targeting. GET aliases use the same Hono query accessor as their redirect, including duplicate query parameters. Canonical route IDs retain whitespace. Policy paths and request paths compare equivalent percent-encoded segments once; an encoded slash stays within its ID segment, and double encoding remains distinct. Invalid percent encoding in a configured path is a compile error, as are overlapping applications that become equally specific after this canonicalization.

When auth.cloudflareAccess is configured and the operator routes are emitted, the compile warns unless an application covers that prefix on every hostname (a paths application or a whole-Worker one). A hosts-only application leaves the routes reachable on the other hostnames.

The Account SPA's admin screens call these routes from the browser. Behind Access, the browser needs Access's CF_Authorization cookie for that path, so the Access application at the edge must cover the same path on the API hostname.

Scope

Keys setThe application covers
neither hosts nor pathsevery request the Worker serves
hostsrequests whose hostname is in the list (exact, case-insensitive; one trailing . on the request's Host is ignored)
pathsrequests whose path equals a prefix or sits below it (/api/v1/ops covers /api/v1/ops/*, not /api/v1/opsx)
bothrequests matching a host and a path

Pass an array to declare several applications. When more than one covers a request, the most specific wins, as Access resolves it at the edge. Declaration order does not matter.

  1. hosts and paths, longest matching path prefix first
  2. paths only, longest matching path prefix first
  3. hosts only
  4. neither (the whole Worker)

A paths-only application covers its paths on every hostname, including a hosts application's hostname. Two applications that cover the same host and path prefix at the same tier fail the compile.

The tier decides before prefix length: a hosts + paths application beats a paths-only one on its host even when the paths-only prefix is longer (h.acme.com + /a wins over /a/b/c on h.acme.com). Cloudflare's edge may resolve overlapping applications differently, so do not rely on this ordering: give overlapping applications distinct paths, or keep the edge and the config to one application per route.

A hosts-scoped application covers only those hostnames. The same routes on the Worker's other hostnames stay reachable through the normal cookie, bearer, and API-key lanes. If a route must never be reachable without Access, scope it by paths, or cover the whole Worker.

A host in hosts that the config does not claim never reaches the Access check. The host allowlist 404s it first.

Identity mapping

Access identities map to existing Better Auth users. Nothing is provisioned. Create the user first, and set user.role (admin plugin) unless groups supplies the role.

People

Access puts the IdP email in the email claim. The Worker looks up the user with that email (lowercased). The claim is only as trustworthy as the identity provider behind the Access policy: an IdP that lets users set their own email can sign in as any account. Allow only IdPs that verify email ownership. It refuses the user if the account's email is not verified (emailVerified), or if the user is banned. Without the verification check, anyone who pre-registers an unverified account with a colleague's address would inherit that colleague's Access identity. userRole is the user's user.role (default 'user'), and it must be in roles.

Groups

Set groups to take the role from the IdP instead of user.role:

cloudflareAccess: {
  teamDomain: 'acme.cloudflareaccess.com',
  aud: 'd8a1f0c7e2b3a4958677d8e9f0a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3',
  paths: ['/api/v1/staff'],
  roles: ['admin', 'sysadmin'],
  groups: { 'it-admins': 'sysadmin', 'event-staff': 'admin' },
}

The Worker reads groups from the token's custom.groups claim. Access includes it only when you add groups as a custom OIDC claim or SAML attribute on the identity provider. The first groups entry the caller holds, in declaration order, sets userRole. A group key that is all digits ('42') fails the compile, because JavaScript enumerates integer-like keys first and would reorder the priority. Every groups value must also be in roles, or the compile fails. When groups is set, a caller who holds none of the listed groups, or whose token lacks the claim, is refused with 403. Access trims custom claims to about 1 KB, so keep group names short.

With groups, whoever administers groups in your identity provider controls these roles. The custom claim is best-effort, and Access may trim it. Use groups only with an IdP where users cannot edit their own group membership or attributes.

Service tokens

A request with CF-Access-Client-Id and CF-Access-Client-Secret reaches the Worker with a token that has no email. Its common_name is the Client ID (<id>.access) and its sub is empty. Map each Client ID to the email of the Better Auth user it acts as:

serviceTokens: { '88bf3b6d86161464f6509f7219099e57.access': 'deploy-bot@example.com' },

The token then authenticates as that user, and the user's user.role must be in roles. Unlisted Client IDs, and a common_name that does not end in .access, are refused. Keys in serviceTokens must have that form, or the compile fails. The email-verification check does not apply, because the mapping is your own config. groups does not apply to service tokens.

Organizations

Access carries no active-organization selection. With features.pinnedOrganizationId, an Access caller who is a member of the pinned org gets activeOrgId and the member role (expanded through auth.roleHierarchy). Without a pinned org, an Access caller has no active org. userRole gates and the sysadmin bypass still apply.

Per-environment values

teamDomain and aud each accept { env: 'VAR_NAME' }. The Worker reads the var at request time, so every named environment can point at its own Access team from one bundle. This is how a client's own Access fronts their private deployment:

quickback.config.ts
export default defineConfig({
  // ...
  auth: {
    cloudflareAccess: {
      teamDomain: { env: 'CF_ACCESS_TEAM' },
      aud: { env: 'CF_ACCESS_AUD' },
      paths: ['/api/v1/staff'],
      roles: ['admin'],
    },
  },
  environments: {
    'client-a': {
      domains: { api: 'api.client-a.example' },
      worker: {
        vars: {
          CF_ACCESS_TEAM: 'client-a.cloudflareaccess.com',
          CF_ACCESS_AUD: '4714c1358e65fe4b408ad6d432a5f878f08194bdb4752441fd56faefa9b2b6f2',
        },
      },
    },
  },
});

An unset var, or a team domain that is not <team>.cloudflareaccess.com, gives 500 CF_ACCESS_MISCONFIGURED. It never gives a pass.

Browser requests and CSRF

Access adds the assertion to every browser request that carries its CF_Authorization cookie, so the credential is ambient. A request from a person passes this check:

Request carriesAccepted when
Origin (any method, reads included)it equals the request's own origin, or is an exact https:// origin listed in BETTER_AUTH_URL or the CF_ACCESS_TRUSTED_ORIGINS Worker var
no Origin, Sec-Fetch-Site (mutations only)Sec-Fetch-Site is same-origin or none
neither headeralways: a non-browser caller such as cloudflared access curl

Anything else gets 403 CSRF_ORIGIN_REJECTED. Service-token requests skip this check. Refusing reads too means a page on another origin cannot read Access-gated data with the user's credential, whatever CORS headers the response would have carried.

  • CF_ACCESS_TRUSTED_ORIGINS is a comma-separated list of exact https:// origins, set per environment. It is empty by default, which fails closed. Use it for a browser app on another host that calls the API inside the Access scope, such as an Access-fronted console Worker that proxies the API. Its pages run with the user's Access credential, so list only origins Access itself fronts.
  • The compile-time trustedOrigins (and the derived domains) are not trusted here: the bundle is shared by every environment. EXTRA_APP_HOSTS is not trusted either, although Better Auth and CORS trust it.
  • An untrusted sibling subdomain is refused, even though the browser reports it same-site. It carries CF_Authorization too.
  • http:// origins never pass, and neither do loopback hosts (localhost, 127.x, [::1], [::], IPv4-mapped loopback), even as https://. An empty or null Origin is refused.

Operator MFA

auth.operatorMfa downgrades operator sessions that lack a second factor. It does not apply to the Access lane. Enforce MFA in the Access policy instead.

Setting up the Access application

  1. In Zero Trust, create a self-hosted application for the hostname (and path) you scoped.
  2. Copy its Application Audience (AUD) tag into aud.
  3. Set teamDomain to your team domain, <team>.cloudflareaccess.com.
  4. For machines, create a service token and add a Service Auth policy. Then map its Client ID in serviceTokens.

Native browser applications (opt in)

Set browser: true on an Access application and set features.pinnedOrganizationId to an existing organization. This mode is for a custom browser application whose employees authenticate through Access alone. The Account SPA still uses Better Auth session APIs; use an Access-aware custom account/team surface with the existing roster and ctx.auth operations. Nothing changes for applications without browser: true.

quickback.config.ts
export default defineConfig({
  // Keep your existing Cloudflare + D1 + Better Auth providers.
  features: { organizations: true, pinnedOrganizationId: 'org_studio' },
  auth: {
    cloudflareAccess: {
      teamDomain: { env: 'CF_ACCESS_TEAM' },
      aud: { env: 'CF_ACCESS_AUD' },
      hosts: ['studio.example.com'],
      roles: ['user'],
      browser: true,
      excludePaths: ['/auth/v1/oauth2/token', '/auth/v1/oauth2/register', '/mcp', '/.well-known'],
    },
  },
});

The native browser lane requires HTTPS, an existing verified, nonbanned user, and live membership in the pinned organization. Mapped service tokens cannot create a browser identity in this mode. No users or memberships are automatically provisioned. roles remains the platform user-role admission list; data permissions still come from organization membership.

GET /api/v1/auth/context returns a no-store projection: authMethod, identityType, safe user fields (id, email, name), organization (id, name, slug, role), browser (id, expiresAt in Unix seconds), and logoutUrl. It never returns an assertion or a session credential. Use this endpoint instead of Better Auth's get-session and organization selection APIs. Pinned mode needs no organization switcher.

The Worker creates a real Better Auth session, binds it to the verified Access user, policy and organization, and keeps its credential inside an encrypted, Secure, HttpOnly, host-only browser cookie. That cookie cannot authenticate any request on its own. Every native request revalidates the Access assertion, user and membership, and checks the session store. Verified Access browser activity refreshes a live session according to Better Auth's configured update-age policy; connector bearer traffic cannot refresh that browser session. A revoked session is refused; a subsequent fresh browser binding requires another Access-authenticated request. ctx.authMethod stays cloudflare-access; ctx.browser proves the human browser context, with its real id also available as ctx.sessionId. ctx.browser.expiresAt is bounded by both the assertion and session expiry. Do not replace these checks with a client-provided user or session ID.

Actions may combine their existing organization-role rules with authMethod: ['cloudflare-access']. In browser mode the lane refuses service tokens; outside browser mode that auth method alone is not a human-only rule. Retain row firewalls and use ctx.auth for organization-bound member operations. Encryption uses the existing authenticated-context middleware. Realtime tickets carry the verified absolute authorization expiry into the existing socket lease cap; renewal requires fresh admission. App membership removal takes effect on the next request/renewal, while an existing socket remains bounded by its authorization lease/expiry. Access or IdP policy revocation follows the Access application's own session policy and is not instantaneous app revocation.

OAuth without a second app login

Browser mode narrowly bridges GET/HEAD /auth/v1/oauth2/authorize, GET/HEAD /auth/v1/oauth2/public-client and POST /auth/v1/oauth2/consent to the provider's existing authorization engine with the verified internal session. Existing client, redirect, PKCE, consent, audience, scope and refresh/revocation validation still applies. Other Better Auth session, password and token-mint routes remain refused inside the scope. Internal session cookies and token headers from authorization responses are not exposed to the browser.

Noninteractive code exchange/refresh, discovery, DCR and MCP clients must run outside the Access scope. excludePaths is an explicit list of path-prefix exceptions to this application's Access lane, with the same segment-boundary matching as paths. It requires browser: true; it is not an authentication grant: ordinary route authentication and signature checks still run. Configure the edge's Access applications/policies to match these exceptions too. Never exclude an entire browser API or add cookie/bearer fallback on a protected path. For an endpoint used by both browsers and OAuth clients, give the browser a separate protected route that reuses the same domain implementation, or use a separate integration hostname.

POST /api/v1/auth/logout revokes the internal session and clears the binding cookie, then returns { url: '/cdn-cgi/access/logout' }. Clear application/query/storage caches before navigating there. Existing ordinary OAuth grants tied to that session can no longer refresh. A user, membership or Access identity change must also clear client caches; do not persist data keyed only by organization.

Custom Worker entrypoints

If an authored Worker returns documents before calling the generated app, protect those responses too. The generated src/lib/cloudflare-access-browser.ts exports authenticateAccessBrowserRequest(request, env, executionCtx?), returning { context, headers }. It uses the same configured application selection, verifier, live user/membership lookup and browser binding. Forward its Set-Cookie response headers. On a typed refusal forward error.status/error.code and any clearing cookie in error.headers; never fall back to a session. The helper refuses excluded paths and unconfigured applications. It is emitted as a disabled compatibility stub when browser mode is off so an authored entrypoint can import it behind a feature flag.

Generated APIs already perform this check in middleware; do not authenticate them twice in a wrapper. Do not copy the helper's private credentials, return the full context as JSON, or hand-parse Access headers in application code. Only the context endpoint's documented projection is suitable for the browser.

On this page