@quickback-dev/cli 0.66.16 → 0.66.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import pc from "picocolors";
12
12
  // Version injected at build time by scripts/inject-version.ts
13
- const CLI_VERSION = "0.66.16";
13
+ const CLI_VERSION = "0.66.17";
14
14
  function getPackageVersion() {
15
15
  return CLI_VERSION;
16
16
  }
@@ -329,7 +329,7 @@ Three things block a working local loop that aren't obvious from the docs:
329
329
 
330
330
  1. **`BETTER_AUTH_SECRET` must be in `.dev.vars`.** The worker refuses to serve with an explicit `503 MISSING_ENV` without it. Create `.dev.vars` next to `wrangler.toml`: `BETTER_AUTH_SECRET=<any long random string>`.
331
331
  2. **Auth cookies are Secure + origin-checked.** When testing with curl, capture the `Set-Cookie` from sign-in and pass it back manually, AND send a trusted `Origin:` header (e.g. `Origin: http://localhost:8787`) on auth POSTs or Better Auth's CSRF check rejects them.
332
- 3. **Set an active organization before minting a JWT.** `POST /api/v1/token` exchanges the session for a JWT; if the session has no active org, the token carries no org roles and every org-scoped endpoint 403s. Call `POST /auth/v1/organization/set-active` (body: `{"organizationId": "..."}`) first.
332
+ 3. **Set an active organization before minting a JWT.** `GET /auth/v1/token` (Better Auth's jwt plugin) exchanges the session for a JWT; if the session has no active org, the token carries no org roles and every org-scoped endpoint 403s. Call `POST /auth/v1/organization/set-active` (body: `{"organizationId": "..."}`) first.
333
333
 
334
334
  ```bash
335
335
  # sign up → sign in (capture cookie) → set active org → mint JWT → call API
@@ -340,7 +340,7 @@ curl -i -X POST http://localhost:8787/auth/v1/sign-in/email -H "Content-Type: ap
340
340
  # → copy better-auth.session_token from Set-Cookie into $COOKIE
341
341
  curl -X POST http://localhost:8787/auth/v1/organization/set-active -H "Content-Type: application/json" \
342
342
  -H "Origin: http://localhost:8787" -H "Cookie: $COOKIE" -d '{"organizationId":"<org-id>"}'
343
- curl -X POST http://localhost:8787/api/v1/token -H "Cookie: $COOKIE"
343
+ curl http://localhost:8787/auth/v1/token -H "Origin: http://localhost:8787" -H "Cookie: $COOKIE"
344
344
  ```
345
345
 
346
346
  ---
@@ -97,7 +97,6 @@ Missing or invalid authentication tokens.
97
97
  | `AUTH_INVALID_TOKEN` | Token is malformed or invalid |
98
98
  | `AUTH_EXPIRED` | Token has expired |
99
99
  | `AUTH_RATE_LIMITED` | Too many auth attempts |
100
- | `AUTH_SESSION_REQUIRED` | The endpoint requires session (cookie) authentication — returned by `POST /api/v1/token` when called with a JWT, API key, or OAuth bearer, so a stolen or revoked token can't mint its own replacement |
101
100
  | `AUTH_REVOCATION_UNAVAILABLE` | **503, retryable.** Only with [`revocationCheck: 'kv'`](/configure/auth#revocationcheck-none--kv--token-revocation-strategy): the bearer's signature verified, but its revocation state could not be read (KV binding missing or unreachable), so it was not trusted. Retry, or authenticate with a session cookie |
102
101
 
103
102
  ### Firewall (403)
@@ -117,7 +117,7 @@ MCP clients pass their credentials through the standard `Authorization: Bearer <
117
117
  Mint a JWT from an authenticated session:
118
118
 
119
119
  ```bash
120
- curl -X POST https://my-api.example.com/api/v1/token \
120
+ curl https://my-api.example.com/auth/v1/token \
121
121
  -H "Cookie: better-auth.session_token=..." \
122
122
  -H "Content-Type: application/json"
123
123
  ```
@@ -10,7 +10,7 @@ export default defineConfig({
10
10
  jwt: {
11
11
  expiresIn: 60,
12
12
  issuer: 'my-api',
13
- // audience, secretEnv, algorithm, revocationCheck...
13
+ // audience, revocationCheck...
14
14
  },
15
15
  },
16
16
  });
@@ -22,14 +22,14 @@ Lowest-to-highest privilege list. Lets access rules use `'role+'` shorthand to m
22
22
 
23
23
  ## `auth.jwt` — JWT bearer-token fast-path
24
24
 
25
- Quickback ships its own custom HMAC-SHA256 JWT (not Better Auth's JWT plugin) so it can embed `orgId` and `role` claims the fast-path needs to reconstruct `AppContext` without a database round-trip. The signing secret is shared with Better Auth (`BETTER_AUTH_SECRET`) by default — users only manage one secret.
25
+ Quickback's JWT is signed with Better Auth's `jwt` plugin keyring — an EdDSA key pair in the `jwks` table, enabled automatically whenever the project signs tokens — and carries the `orgId`, raw `role`, `tiers`, and scope claims the fast-path needs to reconstruct `AppContext` without a database round-trip. The identity token is also available from the plugin's own `GET /auth/v1/token`; scope tokens are Quickback's, signed with the same key. See [Relation to Better Auth's JWT Plugin](/platform/auth/jwt-optimization#relation-to-better-auths-jwt-plugin).
26
26
 
27
27
  > **This JWT surface is opt-in**
28
28
  >
29
- > Quickback emits this custom JWT surface only when `auth.jwt` is present. Omit
30
- > it and the generated output has no generic `/api/v1/token` endpoint, no
31
- > identity JWT mint, and no Bearer-JWT instructions in `llms.txt` or RFC 8414
32
- > discovery metadata. Better Auth cookie and signed session-token bearer
29
+ > Quickback emits this JWT surface only when `auth.jwt` is present. Omit it and
30
+ > the generated output has no identity JWT mint (Better Auth's `GET /auth/v1/token`
31
+ > is disabled), no JWT fast-path, and no Bearer-JWT instructions in `llms.txt` or
32
+ > RFC 8414 discovery metadata. Better Auth cookie and signed session-token bearer
33
33
  > authentication remain available.
34
34
  >
35
35
  > **Scopes are the exception.** A project that declares
@@ -71,6 +71,11 @@ The fast-path is intentionally stateless: it trusts the claims for the full TTL.
71
71
 
72
72
  Default `180` (3 minutes).
73
73
 
74
+ Applies to **every** identity mint: Better Auth's `GET /auth/v1/token` (the
75
+ compiler emits it as the plugin's `expirationTime`) and the session-path
76
+ refresh alike, so a project on `expiresIn: 604800` gets 7-day tokens from both.
77
+ Scope-bearing tokens are clamped to 180 s regardless — see [Scopes](/define/scopes).
78
+
74
79
  Lowering this shrinks the worst-case window where a stolen / pre-revocation token still works. Browser SPAs auto-refresh via `set-auth-token` on every authed call, so a low TTL is invisible to logged-in users; only stale server-to-server bearer tokens feel it.
75
80
 
76
81
  ```ts
@@ -80,46 +85,37 @@ auth: { jwt: { expiresIn: 3600 } } // 1h — longer-lived tokens for CLI / CI
80
85
 
81
86
  ### `issuer?: string` — `iss` claim
82
87
 
83
- Default omitted.
88
+ Default `quickback:<project name>` — a compile-time constant, so every worker that verifies (API, files) and the plugin's `GET /auth/v1/token` agree without any env plumbing.
84
89
 
85
90
  Set this when other services need to distinguish JWTs minted by this Worker from other issuers. The compiler bakes the issuer into both the mint side (added to claims) and the verify side (rejects tokens with mismatched `iss`).
86
91
 
87
92
  ### `audience?: string` — `aud` claim
88
93
 
89
- Default omitted.
94
+ Default `quickback:<project name>` (the same constant as `issuer`).
90
95
 
91
96
  Set this when this Worker's JWTs are consumed by a sibling service that should reject tokens minted for a different audience. Same mint-and-verify treatment as `issuer`.
92
97
 
93
- ### `secretEnv?: string` — signing secret env var
94
-
95
- Default `'BETTER_AUTH_SECRET'`.
96
-
97
- Override this if you want JWT signing isolated from the Better Auth secret (e.g. rotating one without invalidating the other).
98
-
99
- ```ts
100
- auth: { jwt: { secretEnv: 'CUSTOM_JWT_SECRET' } }
101
- ```
98
+ ### `secretEnv` / `algorithm` — removed
102
99
 
103
- The compiler emits `c.env.CUSTOM_JWT_SECRET` (or `process.env.CUSTOM_JWT_SECRET` on Bun/Node) in the auth middleware's verify and mint sites and the `/api/v1/token` endpoint.
100
+ Both knobs are gone. Tokens are signed with Better Auth's JWKS keyring (EdDSA), whose private key is encrypted at rest with `BETTER_AUTH_SECRET` — there is no separate signing secret to name and no algorithm to choose. Declaring either key is a compile error that points here. Verification needs only the public keys (`GET /auth/v1/jwks`), so no worker holds a secret just to verify.
104
101
 
105
- ### `POST /api/v1/token` — mint an identity JWT
102
+ ### `GET /auth/v1/token` — mint an identity JWT
106
103
 
107
- Session-authenticated callers (cookie or session-token bearer) mint a short-lived
108
- JWT carrying `sub`, `orgId`, `role`, `userRole`, `email`, `name`. Two invariants:
104
+ Better Auth's jwt plugin endpoint. Session-authenticated callers (cookie or
105
+ session-token bearer) mint a short-lived JWT carrying `sub`, `sid`, `orgId`,
106
+ `role`, `userRole`, `tiers`, `email`, `name`, plus the pinned `iss` / `aud`.
107
+ Two invariants:
109
108
 
110
109
  - **`orgId` is only ever signed beside a membership `role`**, and the verifier
111
110
  ignores an `orgId` claim that arrives without one — so a token can never be a
112
111
  bare tenant grant.
113
- - **`{ "dropOrg": true }`** in the JSON body mints a token with **no** org
114
- claim: a privilege drop for guest / crew clients that prove
115
- [scopes](/define/scopes) by relationship and must not carry the user's org
116
- membership into them.
117
-
118
- > **Note:** the files-worker (separate Worker for R2 access) still reads `BETTER_AUTH_SECRET` directly. If you override `secretEnv`, set both env vars to the same value or the files worker's JWT verification will fall back to DB session lookup. Threading `secretEnv` through the files worker is on the roadmap.
119
-
120
- ### `algorithm?: 'HS256'`
112
+ - **The org claim follows the session's active organization.** A guest or crew
113
+ client that must not carry the user's org membership into a
114
+ [scope](/define/scopes) clears it first (`organization.setActive` with
115
+ `organizationId: null`) and mints; a session that never sets one mints
116
+ org-less tokens by construction. The former `{ "dropOrg": true }` body flag
117
+ is gone with the generated `/api/v1/token` route.
121
118
 
122
- Only `HS256` is supported in 0.10.14. `RS256` (asymmetric, public-key verify / private-key sign) is on the roadmap.
123
119
 
124
120
  ### `revocationCheck?: 'none' | 'kv'` — token revocation strategy
125
121
 
@@ -162,10 +158,8 @@ missing field falls back to its hardcoded value:
162
158
  | Field | Default |
163
159
  |---|---|
164
160
  | `expiresIn` | 180 |
165
- | `issuer` | omitted |
166
- | `audience` | omitted |
167
- | `secretEnv` | `'BETTER_AUTH_SECRET'` |
168
- | `algorithm` | `'HS256'` |
161
+ | `issuer` | `quickback:<project name>` |
162
+ | `audience` | `quickback:<project name>` |
169
163
  | `revocationCheck` | `'none'` |
170
164
 
171
165
  ## Tuning recommendations
@@ -372,15 +372,24 @@ its scope arms](/define/firewall#allany-groups--null-safe-scope-semantics) autom
372
372
  ### Dropping the org claim on purpose
373
373
 
374
374
  Guest and crew clients that must never ride the user's org membership into a
375
- scope can mint an identity token without it:
375
+ scope mint an identity token with no active organization — the vanilla Better
376
+ Auth way, no flag:
376
377
 
377
378
  ```bash
378
- curl -X POST https://api.example.com/api/v1/token \
379
+ # clear the session's active org, then mint (Better Auth jwt plugin)
380
+ curl -X POST https://api.example.com/auth/v1/organization/set-active \
379
381
  -H "Cookie: <session>" -H "Content-Type: application/json" \
380
- -d '{ "dropOrg": true }'
382
+ -d '{ "organizationId": null }'
383
+ curl https://api.example.com/auth/v1/token -H "Cookie: <session>"
381
384
  # → { token } with no orgId / role claim; scope entry then proves only relationships
382
385
  ```
383
386
 
387
+ A session that never sets an active organization (a native guest app) mints
388
+ org-less tokens by construction. And an org member entering a **foreign**
389
+ tenant's instance is handled server-side: the namespace resolver re-evaluates
390
+ them through the relationship lanes and `/scope/v1/enter` drops the org
391
+ claims from the scope token, so no client-side drop is needed for that case.
392
+
384
393
  > The realtime [ws-ticket](/platform/realtime/durable-objects#namespace-backed-tickets-per-matched-lane) can authorize through this same namespace `via:`, issuing a per-matched-lane WebSocket ticket — so the socket gate and the REST gate stay identical.
385
394
 
386
395
  In every suppressed case the gate still authorizes the request; only the mint
@@ -35,16 +35,16 @@ Scope-bearing tokens also carry `sct` (proof timestamp, unix seconds) and its mi
35
35
 
36
36
  ### Signing
37
37
 
38
- JWTs are signed with HMAC-SHA256 using your `BETTER_AUTH_SECRET` — the same secret you already set for Better Auth, so there is only one secret to manage.
38
+ JWTs are signed with Better Auth's `jwt` plugin keyring: an EdDSA (Ed25519) key pair the plugin stores in the `jwks` table, private key encrypted at rest with your `BETTER_AUTH_SECRET`. There is still only one secret to manage, and it is needed only to **sign** — verification uses the public key, so any worker (or external service) can verify a token from `GET /auth/v1/jwks` without holding the secret.
39
39
 
40
- The signing behaviour is configurable under [`auth.jwt`](/configure/auth) in `quickback.config.ts`: `secretEnv` isolates JWT signing from the Better Auth secret, `issuer` / `audience` add the matching claims, and `algorithm` is `'HS256'` (the only value currently supported).
40
+ The signing behaviour is configurable under [`auth.jwt`](/configure/auth) in `quickback.config.ts`: `issuer` / `audience` set the `iss` / `aud` claims every verifier pins (default `quickback:<project name>`), `expiresIn` sets the TTL, and `revocationCheck` adds sub-TTL revocation. The algorithm is always EdDSA — there is no knob.
41
41
 
42
42
  ```ts title="quickback.config.ts"
43
43
  auth: {
44
44
  jwt: {
45
45
  expiresIn: 180, // default — TTL in seconds
46
46
  revocationCheck: 'none', // default — 'kv' for sub-TTL revocation
47
- secretEnv: 'BETTER_AUTH_SECRET',
47
+ issuer: 'quickback:my-app', // default — quickback:<project name>
48
48
  },
49
49
  },
50
50
  ```
@@ -65,13 +65,13 @@ auth: {
65
65
  Validation steps (in generated `src/middleware/auth.ts`):
66
66
 
67
67
  1. Extract the `Authorization: Bearer <token>` header
68
- 2. Call `verifyJwt(token, BETTER_AUTH_SECRET)` from `src/lib/jwt.ts`
69
- 3. Decode header + payload, recompute the HMAC-SHA256 signature, and compare via `crypto.subtle.verify()` (constant-time — no timing-attack surface)
68
+ 2. Call `verifyJwt(token, env)` from `src/lib/jwt.ts`
69
+ 3. Verify the EdDSA signature with jose against the keyring's public JWKS — cached per isolate, refetched at most once when a token names an unknown `kid` (key rotation). Only `EdDSA` is accepted, so alg-confusion is rejected by construction, and `iss` / `aud` are pinned to the compile-time constants
70
70
  4. Check `exp` against the current time
71
71
  5. On success: hydrate `AppContext` from claims (`sub`, `orgId`, `role`, `userRole`, `email`, `name`) — no DB query
72
72
  6. On failure (bad signature, expired, malformed): **silently fall back** to Better Auth's session cookie auth; if that succeeds, mint a fresh JWT and return it in the `set-auth-token` response header
73
73
 
74
- The Files worker (R2 uploads) performs the same verification using the shared secret — no network round-trip to the auth API for file operations.
74
+ The Files worker (R2 uploads) runs the same verifier (`src/lib/jwt-verify.ts`) over the public keys it reads from the `jwks` table — no shared secret, no network round-trip to the auth API for file operations.
75
75
 
76
76
  ---
77
77
 
@@ -95,11 +95,8 @@ When a user switches organizations, the JWT must be re-minted because `orgId` an
95
95
  // This happens automatically in the org switcher
96
96
  await authClient.organization.setActive({ organizationSlug: slug });
97
97
 
98
- // Fetch fresh JWT with new org context
99
- const res = await fetch('/api/v1/token', {
100
- method: 'POST',
101
- credentials: 'include',
102
- });
98
+ // Fetch a fresh JWT with the new org context — Better Auth's jwt plugin
99
+ const res = await fetch('/auth/v1/token', { credentials: 'include' });
103
100
  const { token } = await res.json();
104
101
  localStorage.setItem('bearer_token', token);
105
102
  ```
@@ -171,21 +168,22 @@ When a JWT expires or is invalid:
171
168
 
172
169
  ## Token Endpoint
173
170
 
174
- `POST /api/v1/token` mints a fresh JWT from the current session. This endpoint goes through normal auth middleware, so the user must have a valid session cookie.
171
+ `GET /auth/v1/token` — Better Auth's jwt plugin — mints a fresh JWT from the current session. Present only when `auth.jwt` is declared; the claims come from the compiler-emitted `resolveIdentityClaims` (`sid`, `orgId` beside the raw membership `role`, `userRole`, `tiers`, `email`, `name`, pinned `iss` / `aud`), and the TTL is your [`auth.jwt.expiresIn`](/configure/auth#expiresin-number--ttl-in-seconds) — the same value the session-path refresh uses. There is no Quickback-generated `/api/v1/token` any more.
175
172
 
176
- **Session authentication is required — and enforced.** A request authenticated
177
- by a bearer JWT (or an API key / OAuth access token) is rejected with `401
178
- AUTH_SESSION_REQUIRED` ("Token refresh requires session authentication").
173
+ **Session authentication is required — and enforced.** The plugin gates the
174
+ endpoint on a Better Auth session (cookie or session-token bearer); a request
175
+ authenticated by a bearer JWT, an API key, or an OAuth access token gets `401`.
179
176
  This is deliberate: only the session path re-validates against Better Auth's
180
177
  session store on every request, so bans, member removals, role demotions, and
181
178
  sign-outs take effect immediately. If a JWT could mint its own replacement, a
182
179
  stolen or revoked token could roll a short-TTL JWT forever without ever
183
180
  re-validating — the TTL would bound nothing.
184
181
 
182
+ **No org claim on purpose.** The token carries the session's active organization. A client that must never ride the user's org membership into a [scope](/define/scopes) (a guest or crew app) clears it first — `authClient.organization.setActive({ organizationId: null })` — and mints; the token then carries no `orgId` / `role`. A foreign-tenant instance reached through `/scope/v1/enter` drops the org claims server-side regardless.
183
+
185
184
  **Request:**
186
185
  ```bash
187
- curl -X POST https://your-api.example.com/api/v1/token \
188
- -H "Content-Type: application/json" \
186
+ curl https://your-api.example.com/auth/v1/token \
189
187
  --cookie "better-auth.session_token=..."
190
188
  ```
191
189
 
@@ -254,15 +252,15 @@ await authClient.signOut();
254
252
  | Token theft (XSS) | 180-second default expiry bounds the exposure window; `expiresIn: 30` tightens it. `httpOnly` cookies protect the session. |
255
253
  | Token replay | Short expiry + `set-auth-token` rotation on session fallback |
256
254
  | Stale permissions | `revocationCheck: 'kv'` — server-side rejection within seconds of a ban, member removal, or role change |
257
- | Token forgery | HMAC-SHA256 signature verified with `BETTER_AUTH_SECRET` |
258
- | Timing attacks | `crypto.subtle.verify()` provides constant-time comparison |
255
+ | Token forgery | EdDSA signature verified against the keyring's public JWKS; only `EdDSA` is accepted (no alg confusion) |
256
+ | Timing attacks | Signature verification is constant-time (Web Crypto via jose) |
259
257
 
260
258
  ### Key Points
261
259
 
262
260
  - JWTs are a **performance optimization**, not a replacement for session auth
263
261
  - Session cookies remain the source of truth — JWTs are derived from them
264
262
  - If a JWT is lost, stolen, or cleared, the system gracefully falls back to cookie auth
265
- - No additional **secret** is needed — signing reuses your existing `BETTER_AUTH_SECRET`. Behaviour *is* configurable: see [`auth.jwt`](/configure/auth) for `expiresIn`, `revocationCheck`, `issuer`, `audience`, `secretEnv`, and `algorithm`
263
+ - No additional **secret** is needed — the keyring's private key is encrypted at rest with your existing `BETTER_AUTH_SECRET`, and verification needs only the public keys. Behaviour *is* configurable: see [`auth.jwt`](/configure/auth) for `expiresIn`, `revocationCheck`, `issuer`, and `audience`
266
264
  - The JWT contains no sensitive data beyond what's already in the auth context
267
265
 
268
266
  ---
@@ -275,45 +273,30 @@ The files worker (for Cloudflare R2 file uploads) also supports JWT authenticati
275
273
 
276
274
  ## Relation to Better Auth's JWT Plugin
277
275
 
278
- Quickback's JWT fast-path (documented above) is a **custom HMAC-SHA256 implementation**, separate from Better Auth's [`jwt` plugin](https://www.better-auth.com/docs/plugins/jwt). The distinction matters if you're comparing options.
279
-
280
- ### What Quickback ships by default
281
-
282
- - Custom HMAC-SHA256 JWTs minted by the compiled API at `POST /api/v1/token`
283
- - Payload includes `sub`, `orgId`, `role`, `userRole`, `email`, `name` — everything the middleware needs to reconstruct `AppContext` with zero DB queries
284
- - Signed with `BETTER_AUTH_SECRET`
285
- - Used by the generated auth middleware as a fast-path ahead of `getSession()`
276
+ Quickback's fast-path and Better Auth's [`jwt` plugin](https://www.better-auth.com/docs/plugins/jwt) are **one system**, not two token formats.
286
277
 
287
- ### What Better Auth's JWT plugin gives you (opt-in)
288
-
289
- Enable it with `plugins: ["jwt"]` in your auth config:
290
-
291
- ```ts
292
- auth: defineAuth("better-auth", {
293
- plugins: ["jwt"],
294
- }),
295
- ```
278
+ ### What the plugin owns
296
279
 
297
- You get:
298
- - JWKS endpoint at `/auth/v1/jwks` for asymmetric public-key verification by external services
299
- - BA's own `/auth/v1/token` endpoint (asymmetric-signed, EdDSA by default)
300
- - Standard OIDC-style claims via BA's `definePayload` hook
280
+ Whenever the project signs any JWT — an `auth.jwt` lane, [`authz.scopes`](/define/scopes), or [agent auth](/platform/auth/plugins/agent-auth) — the compiler enables the plugin automatically. It owns:
301
281
 
302
- ### Why Quickback doesn't use BA's plugin internally
282
+ - **The keyring** — the EdDSA key pair in the `jwks` table, private key encrypted at rest with `BETTER_AUTH_SECRET`.
283
+ - **`GET /auth/v1/jwks`** — the public keys. Any external service verifies Quickback tokens from here; nothing needs the secret.
284
+ - **`GET /auth/v1/token`** — mints an identity JWT for the current session (cookie or session-token bearer). Its claims come from the compiler-emitted `resolveIdentityClaims` in `src/lib/auth.ts`: `sid`, `orgId` beside the **raw** membership `role`, `userRole`, `tiers`, `email`, `name`, and the pinned `iss` / `aud` — the same shape the middleware mints on the session path. Present only when `auth.jwt` is declared; otherwise the path is disabled and the keyring exists for scope and agent tokens alone.
303
285
 
304
- Better Auth's `definePayload` hook only receives `{ user }`. It cannot embed the active organization context (`orgId`, org-member `role`) that Quickback's Firewall and Access layers need. Without that context in the JWT, the middleware would have to do a DB lookup per request — defeating the whole point of the fast-path.
286
+ ### What Quickback still mints
305
287
 
306
- ### When to enable BA's JWT plugin anyway
288
+ - **The session-path refresh** — `set-auth-token` on every session-authenticated call. Same claims, same key, signed through the plugin's exported signer. The plugin's own `set-auth-jwt` header is disabled so `getSession()` never doubles the member and tier lookups.
289
+ - **Scope tokens** — [`/scope/v1/enter`](/define/scopes), namespace resolvers, and sessionless scope-only mints carry a `scope` claim for principals that may have no Better Auth session at all. The plugin has no concept of those, so Quickback builds the payload and signs it with the plugin's key — one keyring, one verifier.
307
290
 
308
- Turn it on if **external services** need to verify tokens without sharing `BETTER_AUTH_SECRET` — e.g. a third-party worker that wants to confirm a user's identity via JWKS. The BA-issued tokens won't have Quickback's org context, so they're useful for identity assertions, not for hitting the Quickback API directly.
291
+ ### One verifier
309
292
 
310
- Enabling BA's plugin does **not** change how the compiled API authenticates requests — the middleware keeps using the custom HMAC JWT regardless.
293
+ `src/lib/jwt-verify.ts` — pure jose, no Better Auth import — verifies every token: `EdDSA` only, `iss` / `aud` pinned to the compile-time constants, JWKS cached per isolate and refetched at most once for an unknown `kid`. `src/lib/jwt.ts` wraps it for the API worker (loading the JWKS from the auth instance); the files worker uses it directly over the `jwks` table.
311
294
 
312
295
  ---
313
296
 
314
297
  ## Related
315
298
 
316
- - [Auth & JWT config](/configure/auth) — `auth.jwt` reference: `expiresIn`, `revocationCheck`, `issuer`, `audience`, `secretEnv`, `algorithm`
299
+ - [Auth & JWT config](/configure/auth) — `auth.jwt` reference: `expiresIn`, `revocationCheck`, `issuer`, `audience`
317
300
  - [Auth Overview](/platform/auth) — Setup and configuration
318
301
  - [Auth Security](/platform/auth/security) — Cookie security, rate limiting, CORS
319
302
  - [API Keys](/platform/auth/api-keys) — Programmatic API access
@@ -268,24 +268,14 @@ await fetch('/auth/v1/passkey/authenticate/verify', {
268
268
 
269
269
  ### JWT Plugin
270
270
 
271
- Better Auth's JWT plugin adds asymmetric-signed tokens and a JWKS endpoint for external services that need to verify user identity without sharing a shared secret.
272
-
273
- **Enable in config:**
274
-
275
- ```ts
276
- auth: defineAuth("better-auth", {
277
- plugins: ["jwt"],
278
- }),
279
- ```
271
+ Better Auth's JWT plugin owns the keyring every Quickback token is signed with. The compiler enables it automatically whenever the project signs JWTs — an `auth.jwt` lane, `authz.scopes`, or agent auth — so there is nothing to declare.
280
272
 
281
273
  **Endpoints:**
282
- - `GET /auth/v1/jwks` — public keys for verifying BA-issued tokens
283
- - `POST /auth/v1/token` — mint an asymmetric-signed JWT from the current session
284
-
285
- > This is **separate from** Quickback's built-in JWT fast-path. Quickback's middleware already validates a custom HMAC-SHA256 JWT (with embedded org context) on every request — enabling the BA plugin does **not** change how the compiled API authenticates. See [JWT Optimization → Relation to Better Auth's JWT Plugin](/platform/auth/jwt-optimization#relation-to-better-auths-jwt-plugin) for the full comparison and when to use each.
274
+ - `GET /auth/v1/jwks` — the public keys. External services verify Quickback tokens from here without holding any secret.
275
+ - `GET /auth/v1/token` — mint an identity JWT for the current session (cookie or session-token bearer). Carries the same claims the middleware mints: `sid`, `orgId` beside the raw `role`, `userRole`, `tiers`, `email`, `name`. TTL is `auth.jwt.expiresIn` (default 180 s). Present only when `auth.jwt` is declared.
286
276
 
277
+ > The keyring is one system with Quickback's fast-path, not a second token format: identity tokens, the session-path refresh, and scope tokens are all EdDSA-signed with the same key and checked by the same verifier. See [JWT Optimization → Relation to Better Auth's JWT Plugin](/platform/auth/jwt-optimization#relation-to-better-auths-jwt-plugin).
287
278
 
288
- **When to enable:** you have external services (non-Quickback workers, third-party integrations) that need to verify a user's identity via JWKS without holding `BETTER_AUTH_SECRET`. The BA-issued tokens won't carry Quickback's `orgId`/`role` claims, so they're for identity, not API access.
289
279
 
290
280
  ### API Keys
291
281
 
@@ -171,7 +171,7 @@ Quickback supports three bearer-token flavors alongside the standard browser ses
171
171
  |------------|---------|-------------|
172
172
  | Session cookie | Browser SPAs (CMS, Account, your app) | Better Auth session lookup |
173
173
  | Session-token bearer | API clients that grabbed `set-auth-token` | Better Auth `bearer` plugin |
174
- | JWT bearer | API clients that hit `/api/v1/token` | In-worker JWT fast-path (no DB hit) |
174
+ | JWT bearer | API clients that mint at `GET /auth/v1/token` | In-worker JWT fast-path (no DB hit) |
175
175
  | API-key bearer | Long-lived programmatic access | `apiKey` plugin / `x-api-key` / `?api_key=` |
176
176
 
177
177
  These match Better Auth's own framing of bearer tokens as **an alternative to cookies, not a supplement** — a request uses one or the other.
@@ -226,7 +226,7 @@ User-supplied options merge on top of the secure default, so any other [`bearer`
226
226
  | Browser extension injects a victim's session cookie into an attacker's bearer-authed API call | Cookie stripped when `Authorization` is present |
227
227
  | Multi-account user has cookies for two identities and uses bearer for the second | Bearer identity wins; no ambiguity in audit log |
228
228
  | MCP / agent flow exposed to ambient browser cookies | `/mcp` and agent-auth routes are bearer-only (cookies dropped entirely, see [Agent Auth](/platform/auth/plugins/agent-auth)) |
229
- | Alg-confusion / forged JWT (alg=none, HS384, RS256) | Verifier pins HS256; signature math rejects all non-matching algs uniformly with 401 |
229
+ | Alg-confusion / forged JWT (alg=none, HS256, RS256) | Verifier accepts only `EdDSA` against the keyring's public JWKS; every other alg is rejected uniformly with 401 |
230
230
 
231
231
  For a deeper walkthrough of the bearer flow itself, see the upstream [Better Auth bearer plugin docs](https://better-auth.com/docs/plugins/bearer).
232
232
 
@@ -26,7 +26,8 @@ app.get('/api/me', async (c) => {
26
26
  return c.json({
27
27
  userId: ctx.userId, // Better Auth user id
28
28
  user: ctx.user, // { id, email, name }
29
- roles: ctx.roles, // org member roles: ['owner' | 'admin' | 'member']
29
+ roles: ctx.roles, // every role the caller satisfies (hierarchy-expanded, plus tier roles)
30
+ orgRole: ctx.orgRole, // the raw membership role: 'owner' | 'admin' | 'member' | custom
30
31
  });
31
32
  });
32
33
  ```
@@ -217,7 +217,7 @@ The environment contract is intentionally exact and fails closed:
217
217
  feature set, with account-unique integer namespace IDs. Add or remove a rate
218
218
  limit and the next compile tells you which override changed.
219
219
  - `requiredSecrets` must exactly match the generated runtime inventory:
220
- `BETTER_AUTH_SECRET`, a custom `auth.jwt.secretEnv` when configured,
220
+ `BETTER_AUTH_SECRET`,
221
221
  `ENCRYPTION_KEK` when envelope-encrypted columns are present, and every
222
222
  custom secret declared with `required: true`. It also includes the shared
223
223
  `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` credentials when generated
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quickback-dev/cli",
3
- "version": "0.66.16",
3
+ "version": "0.66.17",
4
4
  "description": "CLI for Quickback — define your backend in TypeScript, compile to a fully wired Cloudflare Worker (or Bun / Node) with auth, database, migrations, security, CMS, and Account UI.",
5
5
  "author": "Kardoe Incorporated <paul@kardoe.com>",
6
6
  "license": "MIT",
@@ -329,7 +329,7 @@ Three things block a working local loop that aren't obvious from the docs:
329
329
 
330
330
  1. **`BETTER_AUTH_SECRET` must be in `.dev.vars`.** The worker refuses to serve with an explicit `503 MISSING_ENV` without it. Create `.dev.vars` next to `wrangler.toml`: `BETTER_AUTH_SECRET=<any long random string>`.
331
331
  2. **Auth cookies are Secure + origin-checked.** When testing with curl, capture the `Set-Cookie` from sign-in and pass it back manually, AND send a trusted `Origin:` header (e.g. `Origin: http://localhost:8787`) on auth POSTs or Better Auth's CSRF check rejects them.
332
- 3. **Set an active organization before minting a JWT.** `POST /api/v1/token` exchanges the session for a JWT; if the session has no active org, the token carries no org roles and every org-scoped endpoint 403s. Call `POST /auth/v1/organization/set-active` (body: `{"organizationId": "..."}`) first.
332
+ 3. **Set an active organization before minting a JWT.** `GET /auth/v1/token` (Better Auth's jwt plugin) exchanges the session for a JWT; if the session has no active org, the token carries no org roles and every org-scoped endpoint 403s. Call `POST /auth/v1/organization/set-active` (body: `{"organizationId": "..."}`) first.
333
333
 
334
334
  ```bash
335
335
  # sign up → sign in (capture cookie) → set active org → mint JWT → call API
@@ -340,7 +340,7 @@ curl -i -X POST http://localhost:8787/auth/v1/sign-in/email -H "Content-Type: ap
340
340
  # → copy better-auth.session_token from Set-Cookie into $COOKIE
341
341
  curl -X POST http://localhost:8787/auth/v1/organization/set-active -H "Content-Type: application/json" \
342
342
  -H "Origin: http://localhost:8787" -H "Cookie: $COOKIE" -d '{"organizationId":"<org-id>"}'
343
- curl -X POST http://localhost:8787/api/v1/token -H "Cookie: $COOKIE"
343
+ curl http://localhost:8787/auth/v1/token -H "Origin: http://localhost:8787" -H "Cookie: $COOKIE"
344
344
  ```
345
345
 
346
346
  ---
@@ -97,7 +97,6 @@ Missing or invalid authentication tokens.
97
97
  | `AUTH_INVALID_TOKEN` | Token is malformed or invalid |
98
98
  | `AUTH_EXPIRED` | Token has expired |
99
99
  | `AUTH_RATE_LIMITED` | Too many auth attempts |
100
- | `AUTH_SESSION_REQUIRED` | The endpoint requires session (cookie) authentication — returned by `POST /api/v1/token` when called with a JWT, API key, or OAuth bearer, so a stolen or revoked token can't mint its own replacement |
101
100
  | `AUTH_REVOCATION_UNAVAILABLE` | **503, retryable.** Only with [`revocationCheck: 'kv'`](/configure/auth#revocationcheck-none--kv--token-revocation-strategy): the bearer's signature verified, but its revocation state could not be read (KV binding missing or unreachable), so it was not trusted. Retry, or authenticate with a session cookie |
102
101
 
103
102
  ### Firewall (403)
@@ -117,7 +117,7 @@ MCP clients pass their credentials through the standard `Authorization: Bearer <
117
117
  Mint a JWT from an authenticated session:
118
118
 
119
119
  ```bash
120
- curl -X POST https://my-api.example.com/api/v1/token \
120
+ curl https://my-api.example.com/auth/v1/token \
121
121
  -H "Cookie: better-auth.session_token=..." \
122
122
  -H "Content-Type: application/json"
123
123
  ```
@@ -10,7 +10,7 @@ export default defineConfig({
10
10
  jwt: {
11
11
  expiresIn: 60,
12
12
  issuer: 'my-api',
13
- // audience, secretEnv, algorithm, revocationCheck...
13
+ // audience, revocationCheck...
14
14
  },
15
15
  },
16
16
  });
@@ -22,14 +22,14 @@ Lowest-to-highest privilege list. Lets access rules use `'role+'` shorthand to m
22
22
 
23
23
  ## `auth.jwt` — JWT bearer-token fast-path
24
24
 
25
- Quickback ships its own custom HMAC-SHA256 JWT (not Better Auth's JWT plugin) so it can embed `orgId` and `role` claims the fast-path needs to reconstruct `AppContext` without a database round-trip. The signing secret is shared with Better Auth (`BETTER_AUTH_SECRET`) by default — users only manage one secret.
25
+ Quickback's JWT is signed with Better Auth's `jwt` plugin keyring — an EdDSA key pair in the `jwks` table, enabled automatically whenever the project signs tokens — and carries the `orgId`, raw `role`, `tiers`, and scope claims the fast-path needs to reconstruct `AppContext` without a database round-trip. The identity token is also available from the plugin's own `GET /auth/v1/token`; scope tokens are Quickback's, signed with the same key. See [Relation to Better Auth's JWT Plugin](/platform/auth/jwt-optimization#relation-to-better-auths-jwt-plugin).
26
26
 
27
27
  > **This JWT surface is opt-in**
28
28
  >
29
- > Quickback emits this custom JWT surface only when `auth.jwt` is present. Omit
30
- > it and the generated output has no generic `/api/v1/token` endpoint, no
31
- > identity JWT mint, and no Bearer-JWT instructions in `llms.txt` or RFC 8414
32
- > discovery metadata. Better Auth cookie and signed session-token bearer
29
+ > Quickback emits this JWT surface only when `auth.jwt` is present. Omit it and
30
+ > the generated output has no identity JWT mint (Better Auth's `GET /auth/v1/token`
31
+ > is disabled), no JWT fast-path, and no Bearer-JWT instructions in `llms.txt` or
32
+ > RFC 8414 discovery metadata. Better Auth cookie and signed session-token bearer
33
33
  > authentication remain available.
34
34
  >
35
35
  > **Scopes are the exception.** A project that declares
@@ -71,6 +71,11 @@ The fast-path is intentionally stateless: it trusts the claims for the full TTL.
71
71
 
72
72
  Default `180` (3 minutes).
73
73
 
74
+ Applies to **every** identity mint: Better Auth's `GET /auth/v1/token` (the
75
+ compiler emits it as the plugin's `expirationTime`) and the session-path
76
+ refresh alike, so a project on `expiresIn: 604800` gets 7-day tokens from both.
77
+ Scope-bearing tokens are clamped to 180 s regardless — see [Scopes](/define/scopes).
78
+
74
79
  Lowering this shrinks the worst-case window where a stolen / pre-revocation token still works. Browser SPAs auto-refresh via `set-auth-token` on every authed call, so a low TTL is invisible to logged-in users; only stale server-to-server bearer tokens feel it.
75
80
 
76
81
  ```ts
@@ -80,46 +85,37 @@ auth: { jwt: { expiresIn: 3600 } } // 1h — longer-lived tokens for CLI / CI
80
85
 
81
86
  ### `issuer?: string` — `iss` claim
82
87
 
83
- Default omitted.
88
+ Default `quickback:<project name>` — a compile-time constant, so every worker that verifies (API, files) and the plugin's `GET /auth/v1/token` agree without any env plumbing.
84
89
 
85
90
  Set this when other services need to distinguish JWTs minted by this Worker from other issuers. The compiler bakes the issuer into both the mint side (added to claims) and the verify side (rejects tokens with mismatched `iss`).
86
91
 
87
92
  ### `audience?: string` — `aud` claim
88
93
 
89
- Default omitted.
94
+ Default `quickback:<project name>` (the same constant as `issuer`).
90
95
 
91
96
  Set this when this Worker's JWTs are consumed by a sibling service that should reject tokens minted for a different audience. Same mint-and-verify treatment as `issuer`.
92
97
 
93
- ### `secretEnv?: string` — signing secret env var
94
-
95
- Default `'BETTER_AUTH_SECRET'`.
96
-
97
- Override this if you want JWT signing isolated from the Better Auth secret (e.g. rotating one without invalidating the other).
98
-
99
- ```ts
100
- auth: { jwt: { secretEnv: 'CUSTOM_JWT_SECRET' } }
101
- ```
98
+ ### `secretEnv` / `algorithm` — removed
102
99
 
103
- The compiler emits `c.env.CUSTOM_JWT_SECRET` (or `process.env.CUSTOM_JWT_SECRET` on Bun/Node) in the auth middleware's verify and mint sites and the `/api/v1/token` endpoint.
100
+ Both knobs are gone. Tokens are signed with Better Auth's JWKS keyring (EdDSA), whose private key is encrypted at rest with `BETTER_AUTH_SECRET` — there is no separate signing secret to name and no algorithm to choose. Declaring either key is a compile error that points here. Verification needs only the public keys (`GET /auth/v1/jwks`), so no worker holds a secret just to verify.
104
101
 
105
- ### `POST /api/v1/token` — mint an identity JWT
102
+ ### `GET /auth/v1/token` — mint an identity JWT
106
103
 
107
- Session-authenticated callers (cookie or session-token bearer) mint a short-lived
108
- JWT carrying `sub`, `orgId`, `role`, `userRole`, `email`, `name`. Two invariants:
104
+ Better Auth's jwt plugin endpoint. Session-authenticated callers (cookie or
105
+ session-token bearer) mint a short-lived JWT carrying `sub`, `sid`, `orgId`,
106
+ `role`, `userRole`, `tiers`, `email`, `name`, plus the pinned `iss` / `aud`.
107
+ Two invariants:
109
108
 
110
109
  - **`orgId` is only ever signed beside a membership `role`**, and the verifier
111
110
  ignores an `orgId` claim that arrives without one — so a token can never be a
112
111
  bare tenant grant.
113
- - **`{ "dropOrg": true }`** in the JSON body mints a token with **no** org
114
- claim: a privilege drop for guest / crew clients that prove
115
- [scopes](/define/scopes) by relationship and must not carry the user's org
116
- membership into them.
117
-
118
- > **Note:** the files-worker (separate Worker for R2 access) still reads `BETTER_AUTH_SECRET` directly. If you override `secretEnv`, set both env vars to the same value or the files worker's JWT verification will fall back to DB session lookup. Threading `secretEnv` through the files worker is on the roadmap.
119
-
120
- ### `algorithm?: 'HS256'`
112
+ - **The org claim follows the session's active organization.** A guest or crew
113
+ client that must not carry the user's org membership into a
114
+ [scope](/define/scopes) clears it first (`organization.setActive` with
115
+ `organizationId: null`) and mints; a session that never sets one mints
116
+ org-less tokens by construction. The former `{ "dropOrg": true }` body flag
117
+ is gone with the generated `/api/v1/token` route.
121
118
 
122
- Only `HS256` is supported in 0.10.14. `RS256` (asymmetric, public-key verify / private-key sign) is on the roadmap.
123
119
 
124
120
  ### `revocationCheck?: 'none' | 'kv'` — token revocation strategy
125
121
 
@@ -162,10 +158,8 @@ missing field falls back to its hardcoded value:
162
158
  | Field | Default |
163
159
  |---|---|
164
160
  | `expiresIn` | 180 |
165
- | `issuer` | omitted |
166
- | `audience` | omitted |
167
- | `secretEnv` | `'BETTER_AUTH_SECRET'` |
168
- | `algorithm` | `'HS256'` |
161
+ | `issuer` | `quickback:<project name>` |
162
+ | `audience` | `quickback:<project name>` |
169
163
  | `revocationCheck` | `'none'` |
170
164
 
171
165
  ## Tuning recommendations
@@ -372,15 +372,24 @@ its scope arms](/define/firewall#allany-groups--null-safe-scope-semantics) autom
372
372
  ### Dropping the org claim on purpose
373
373
 
374
374
  Guest and crew clients that must never ride the user's org membership into a
375
- scope can mint an identity token without it:
375
+ scope mint an identity token with no active organization — the vanilla Better
376
+ Auth way, no flag:
376
377
 
377
378
  ```bash
378
- curl -X POST https://api.example.com/api/v1/token \
379
+ # clear the session's active org, then mint (Better Auth jwt plugin)
380
+ curl -X POST https://api.example.com/auth/v1/organization/set-active \
379
381
  -H "Cookie: <session>" -H "Content-Type: application/json" \
380
- -d '{ "dropOrg": true }'
382
+ -d '{ "organizationId": null }'
383
+ curl https://api.example.com/auth/v1/token -H "Cookie: <session>"
381
384
  # → { token } with no orgId / role claim; scope entry then proves only relationships
382
385
  ```
383
386
 
387
+ A session that never sets an active organization (a native guest app) mints
388
+ org-less tokens by construction. And an org member entering a **foreign**
389
+ tenant's instance is handled server-side: the namespace resolver re-evaluates
390
+ them through the relationship lanes and `/scope/v1/enter` drops the org
391
+ claims from the scope token, so no client-side drop is needed for that case.
392
+
384
393
  > The realtime [ws-ticket](/platform/realtime/durable-objects#namespace-backed-tickets-per-matched-lane) can authorize through this same namespace `via:`, issuing a per-matched-lane WebSocket ticket — so the socket gate and the REST gate stay identical.
385
394
 
386
395
  In every suppressed case the gate still authorizes the request; only the mint
@@ -35,16 +35,16 @@ Scope-bearing tokens also carry `sct` (proof timestamp, unix seconds) and its mi
35
35
 
36
36
  ### Signing
37
37
 
38
- JWTs are signed with HMAC-SHA256 using your `BETTER_AUTH_SECRET` — the same secret you already set for Better Auth, so there is only one secret to manage.
38
+ JWTs are signed with Better Auth's `jwt` plugin keyring: an EdDSA (Ed25519) key pair the plugin stores in the `jwks` table, private key encrypted at rest with your `BETTER_AUTH_SECRET`. There is still only one secret to manage, and it is needed only to **sign** — verification uses the public key, so any worker (or external service) can verify a token from `GET /auth/v1/jwks` without holding the secret.
39
39
 
40
- The signing behaviour is configurable under [`auth.jwt`](/configure/auth) in `quickback.config.ts`: `secretEnv` isolates JWT signing from the Better Auth secret, `issuer` / `audience` add the matching claims, and `algorithm` is `'HS256'` (the only value currently supported).
40
+ The signing behaviour is configurable under [`auth.jwt`](/configure/auth) in `quickback.config.ts`: `issuer` / `audience` set the `iss` / `aud` claims every verifier pins (default `quickback:<project name>`), `expiresIn` sets the TTL, and `revocationCheck` adds sub-TTL revocation. The algorithm is always EdDSA — there is no knob.
41
41
 
42
42
  ```ts title="quickback.config.ts"
43
43
  auth: {
44
44
  jwt: {
45
45
  expiresIn: 180, // default — TTL in seconds
46
46
  revocationCheck: 'none', // default — 'kv' for sub-TTL revocation
47
- secretEnv: 'BETTER_AUTH_SECRET',
47
+ issuer: 'quickback:my-app', // default — quickback:<project name>
48
48
  },
49
49
  },
50
50
  ```
@@ -65,13 +65,13 @@ auth: {
65
65
  Validation steps (in generated `src/middleware/auth.ts`):
66
66
 
67
67
  1. Extract the `Authorization: Bearer <token>` header
68
- 2. Call `verifyJwt(token, BETTER_AUTH_SECRET)` from `src/lib/jwt.ts`
69
- 3. Decode header + payload, recompute the HMAC-SHA256 signature, and compare via `crypto.subtle.verify()` (constant-time — no timing-attack surface)
68
+ 2. Call `verifyJwt(token, env)` from `src/lib/jwt.ts`
69
+ 3. Verify the EdDSA signature with jose against the keyring's public JWKS — cached per isolate, refetched at most once when a token names an unknown `kid` (key rotation). Only `EdDSA` is accepted, so alg-confusion is rejected by construction, and `iss` / `aud` are pinned to the compile-time constants
70
70
  4. Check `exp` against the current time
71
71
  5. On success: hydrate `AppContext` from claims (`sub`, `orgId`, `role`, `userRole`, `email`, `name`) — no DB query
72
72
  6. On failure (bad signature, expired, malformed): **silently fall back** to Better Auth's session cookie auth; if that succeeds, mint a fresh JWT and return it in the `set-auth-token` response header
73
73
 
74
- The Files worker (R2 uploads) performs the same verification using the shared secret — no network round-trip to the auth API for file operations.
74
+ The Files worker (R2 uploads) runs the same verifier (`src/lib/jwt-verify.ts`) over the public keys it reads from the `jwks` table — no shared secret, no network round-trip to the auth API for file operations.
75
75
 
76
76
  ---
77
77
 
@@ -95,11 +95,8 @@ When a user switches organizations, the JWT must be re-minted because `orgId` an
95
95
  // This happens automatically in the org switcher
96
96
  await authClient.organization.setActive({ organizationSlug: slug });
97
97
 
98
- // Fetch fresh JWT with new org context
99
- const res = await fetch('/api/v1/token', {
100
- method: 'POST',
101
- credentials: 'include',
102
- });
98
+ // Fetch a fresh JWT with the new org context — Better Auth's jwt plugin
99
+ const res = await fetch('/auth/v1/token', { credentials: 'include' });
103
100
  const { token } = await res.json();
104
101
  localStorage.setItem('bearer_token', token);
105
102
  ```
@@ -171,21 +168,22 @@ When a JWT expires or is invalid:
171
168
 
172
169
  ## Token Endpoint
173
170
 
174
- `POST /api/v1/token` mints a fresh JWT from the current session. This endpoint goes through normal auth middleware, so the user must have a valid session cookie.
171
+ `GET /auth/v1/token` — Better Auth's jwt plugin — mints a fresh JWT from the current session. Present only when `auth.jwt` is declared; the claims come from the compiler-emitted `resolveIdentityClaims` (`sid`, `orgId` beside the raw membership `role`, `userRole`, `tiers`, `email`, `name`, pinned `iss` / `aud`), and the TTL is your [`auth.jwt.expiresIn`](/configure/auth#expiresin-number--ttl-in-seconds) — the same value the session-path refresh uses. There is no Quickback-generated `/api/v1/token` any more.
175
172
 
176
- **Session authentication is required — and enforced.** A request authenticated
177
- by a bearer JWT (or an API key / OAuth access token) is rejected with `401
178
- AUTH_SESSION_REQUIRED` ("Token refresh requires session authentication").
173
+ **Session authentication is required — and enforced.** The plugin gates the
174
+ endpoint on a Better Auth session (cookie or session-token bearer); a request
175
+ authenticated by a bearer JWT, an API key, or an OAuth access token gets `401`.
179
176
  This is deliberate: only the session path re-validates against Better Auth's
180
177
  session store on every request, so bans, member removals, role demotions, and
181
178
  sign-outs take effect immediately. If a JWT could mint its own replacement, a
182
179
  stolen or revoked token could roll a short-TTL JWT forever without ever
183
180
  re-validating — the TTL would bound nothing.
184
181
 
182
+ **No org claim on purpose.** The token carries the session's active organization. A client that must never ride the user's org membership into a [scope](/define/scopes) (a guest or crew app) clears it first — `authClient.organization.setActive({ organizationId: null })` — and mints; the token then carries no `orgId` / `role`. A foreign-tenant instance reached through `/scope/v1/enter` drops the org claims server-side regardless.
183
+
185
184
  **Request:**
186
185
  ```bash
187
- curl -X POST https://your-api.example.com/api/v1/token \
188
- -H "Content-Type: application/json" \
186
+ curl https://your-api.example.com/auth/v1/token \
189
187
  --cookie "better-auth.session_token=..."
190
188
  ```
191
189
 
@@ -254,15 +252,15 @@ await authClient.signOut();
254
252
  | Token theft (XSS) | 180-second default expiry bounds the exposure window; `expiresIn: 30` tightens it. `httpOnly` cookies protect the session. |
255
253
  | Token replay | Short expiry + `set-auth-token` rotation on session fallback |
256
254
  | Stale permissions | `revocationCheck: 'kv'` — server-side rejection within seconds of a ban, member removal, or role change |
257
- | Token forgery | HMAC-SHA256 signature verified with `BETTER_AUTH_SECRET` |
258
- | Timing attacks | `crypto.subtle.verify()` provides constant-time comparison |
255
+ | Token forgery | EdDSA signature verified against the keyring's public JWKS; only `EdDSA` is accepted (no alg confusion) |
256
+ | Timing attacks | Signature verification is constant-time (Web Crypto via jose) |
259
257
 
260
258
  ### Key Points
261
259
 
262
260
  - JWTs are a **performance optimization**, not a replacement for session auth
263
261
  - Session cookies remain the source of truth — JWTs are derived from them
264
262
  - If a JWT is lost, stolen, or cleared, the system gracefully falls back to cookie auth
265
- - No additional **secret** is needed — signing reuses your existing `BETTER_AUTH_SECRET`. Behaviour *is* configurable: see [`auth.jwt`](/configure/auth) for `expiresIn`, `revocationCheck`, `issuer`, `audience`, `secretEnv`, and `algorithm`
263
+ - No additional **secret** is needed — the keyring's private key is encrypted at rest with your existing `BETTER_AUTH_SECRET`, and verification needs only the public keys. Behaviour *is* configurable: see [`auth.jwt`](/configure/auth) for `expiresIn`, `revocationCheck`, `issuer`, and `audience`
266
264
  - The JWT contains no sensitive data beyond what's already in the auth context
267
265
 
268
266
  ---
@@ -275,45 +273,30 @@ The files worker (for Cloudflare R2 file uploads) also supports JWT authenticati
275
273
 
276
274
  ## Relation to Better Auth's JWT Plugin
277
275
 
278
- Quickback's JWT fast-path (documented above) is a **custom HMAC-SHA256 implementation**, separate from Better Auth's [`jwt` plugin](https://www.better-auth.com/docs/plugins/jwt). The distinction matters if you're comparing options.
279
-
280
- ### What Quickback ships by default
281
-
282
- - Custom HMAC-SHA256 JWTs minted by the compiled API at `POST /api/v1/token`
283
- - Payload includes `sub`, `orgId`, `role`, `userRole`, `email`, `name` — everything the middleware needs to reconstruct `AppContext` with zero DB queries
284
- - Signed with `BETTER_AUTH_SECRET`
285
- - Used by the generated auth middleware as a fast-path ahead of `getSession()`
276
+ Quickback's fast-path and Better Auth's [`jwt` plugin](https://www.better-auth.com/docs/plugins/jwt) are **one system**, not two token formats.
286
277
 
287
- ### What Better Auth's JWT plugin gives you (opt-in)
288
-
289
- Enable it with `plugins: ["jwt"]` in your auth config:
290
-
291
- ```ts
292
- auth: defineAuth("better-auth", {
293
- plugins: ["jwt"],
294
- }),
295
- ```
278
+ ### What the plugin owns
296
279
 
297
- You get:
298
- - JWKS endpoint at `/auth/v1/jwks` for asymmetric public-key verification by external services
299
- - BA's own `/auth/v1/token` endpoint (asymmetric-signed, EdDSA by default)
300
- - Standard OIDC-style claims via BA's `definePayload` hook
280
+ Whenever the project signs any JWT — an `auth.jwt` lane, [`authz.scopes`](/define/scopes), or [agent auth](/platform/auth/plugins/agent-auth) — the compiler enables the plugin automatically. It owns:
301
281
 
302
- ### Why Quickback doesn't use BA's plugin internally
282
+ - **The keyring** — the EdDSA key pair in the `jwks` table, private key encrypted at rest with `BETTER_AUTH_SECRET`.
283
+ - **`GET /auth/v1/jwks`** — the public keys. Any external service verifies Quickback tokens from here; nothing needs the secret.
284
+ - **`GET /auth/v1/token`** — mints an identity JWT for the current session (cookie or session-token bearer). Its claims come from the compiler-emitted `resolveIdentityClaims` in `src/lib/auth.ts`: `sid`, `orgId` beside the **raw** membership `role`, `userRole`, `tiers`, `email`, `name`, and the pinned `iss` / `aud` — the same shape the middleware mints on the session path. Present only when `auth.jwt` is declared; otherwise the path is disabled and the keyring exists for scope and agent tokens alone.
303
285
 
304
- Better Auth's `definePayload` hook only receives `{ user }`. It cannot embed the active organization context (`orgId`, org-member `role`) that Quickback's Firewall and Access layers need. Without that context in the JWT, the middleware would have to do a DB lookup per request — defeating the whole point of the fast-path.
286
+ ### What Quickback still mints
305
287
 
306
- ### When to enable BA's JWT plugin anyway
288
+ - **The session-path refresh** — `set-auth-token` on every session-authenticated call. Same claims, same key, signed through the plugin's exported signer. The plugin's own `set-auth-jwt` header is disabled so `getSession()` never doubles the member and tier lookups.
289
+ - **Scope tokens** — [`/scope/v1/enter`](/define/scopes), namespace resolvers, and sessionless scope-only mints carry a `scope` claim for principals that may have no Better Auth session at all. The plugin has no concept of those, so Quickback builds the payload and signs it with the plugin's key — one keyring, one verifier.
307
290
 
308
- Turn it on if **external services** need to verify tokens without sharing `BETTER_AUTH_SECRET` — e.g. a third-party worker that wants to confirm a user's identity via JWKS. The BA-issued tokens won't have Quickback's org context, so they're useful for identity assertions, not for hitting the Quickback API directly.
291
+ ### One verifier
309
292
 
310
- Enabling BA's plugin does **not** change how the compiled API authenticates requests — the middleware keeps using the custom HMAC JWT regardless.
293
+ `src/lib/jwt-verify.ts` — pure jose, no Better Auth import — verifies every token: `EdDSA` only, `iss` / `aud` pinned to the compile-time constants, JWKS cached per isolate and refetched at most once for an unknown `kid`. `src/lib/jwt.ts` wraps it for the API worker (loading the JWKS from the auth instance); the files worker uses it directly over the `jwks` table.
311
294
 
312
295
  ---
313
296
 
314
297
  ## Related
315
298
 
316
- - [Auth & JWT config](/configure/auth) — `auth.jwt` reference: `expiresIn`, `revocationCheck`, `issuer`, `audience`, `secretEnv`, `algorithm`
299
+ - [Auth & JWT config](/configure/auth) — `auth.jwt` reference: `expiresIn`, `revocationCheck`, `issuer`, `audience`
317
300
  - [Auth Overview](/platform/auth) — Setup and configuration
318
301
  - [Auth Security](/platform/auth/security) — Cookie security, rate limiting, CORS
319
302
  - [API Keys](/platform/auth/api-keys) — Programmatic API access
@@ -268,24 +268,14 @@ await fetch('/auth/v1/passkey/authenticate/verify', {
268
268
 
269
269
  ### JWT Plugin
270
270
 
271
- Better Auth's JWT plugin adds asymmetric-signed tokens and a JWKS endpoint for external services that need to verify user identity without sharing a shared secret.
272
-
273
- **Enable in config:**
274
-
275
- ```ts
276
- auth: defineAuth("better-auth", {
277
- plugins: ["jwt"],
278
- }),
279
- ```
271
+ Better Auth's JWT plugin owns the keyring every Quickback token is signed with. The compiler enables it automatically whenever the project signs JWTs — an `auth.jwt` lane, `authz.scopes`, or agent auth — so there is nothing to declare.
280
272
 
281
273
  **Endpoints:**
282
- - `GET /auth/v1/jwks` — public keys for verifying BA-issued tokens
283
- - `POST /auth/v1/token` — mint an asymmetric-signed JWT from the current session
284
-
285
- > This is **separate from** Quickback's built-in JWT fast-path. Quickback's middleware already validates a custom HMAC-SHA256 JWT (with embedded org context) on every request — enabling the BA plugin does **not** change how the compiled API authenticates. See [JWT Optimization → Relation to Better Auth's JWT Plugin](/platform/auth/jwt-optimization#relation-to-better-auths-jwt-plugin) for the full comparison and when to use each.
274
+ - `GET /auth/v1/jwks` — the public keys. External services verify Quickback tokens from here without holding any secret.
275
+ - `GET /auth/v1/token` — mint an identity JWT for the current session (cookie or session-token bearer). Carries the same claims the middleware mints: `sid`, `orgId` beside the raw `role`, `userRole`, `tiers`, `email`, `name`. TTL is `auth.jwt.expiresIn` (default 180 s). Present only when `auth.jwt` is declared.
286
276
 
277
+ > The keyring is one system with Quickback's fast-path, not a second token format: identity tokens, the session-path refresh, and scope tokens are all EdDSA-signed with the same key and checked by the same verifier. See [JWT Optimization → Relation to Better Auth's JWT Plugin](/platform/auth/jwt-optimization#relation-to-better-auths-jwt-plugin).
287
278
 
288
- **When to enable:** you have external services (non-Quickback workers, third-party integrations) that need to verify a user's identity via JWKS without holding `BETTER_AUTH_SECRET`. The BA-issued tokens won't carry Quickback's `orgId`/`role` claims, so they're for identity, not API access.
289
279
 
290
280
  ### API Keys
291
281
 
@@ -171,7 +171,7 @@ Quickback supports three bearer-token flavors alongside the standard browser ses
171
171
  |------------|---------|-------------|
172
172
  | Session cookie | Browser SPAs (CMS, Account, your app) | Better Auth session lookup |
173
173
  | Session-token bearer | API clients that grabbed `set-auth-token` | Better Auth `bearer` plugin |
174
- | JWT bearer | API clients that hit `/api/v1/token` | In-worker JWT fast-path (no DB hit) |
174
+ | JWT bearer | API clients that mint at `GET /auth/v1/token` | In-worker JWT fast-path (no DB hit) |
175
175
  | API-key bearer | Long-lived programmatic access | `apiKey` plugin / `x-api-key` / `?api_key=` |
176
176
 
177
177
  These match Better Auth's own framing of bearer tokens as **an alternative to cookies, not a supplement** — a request uses one or the other.
@@ -226,7 +226,7 @@ User-supplied options merge on top of the secure default, so any other [`bearer`
226
226
  | Browser extension injects a victim's session cookie into an attacker's bearer-authed API call | Cookie stripped when `Authorization` is present |
227
227
  | Multi-account user has cookies for two identities and uses bearer for the second | Bearer identity wins; no ambiguity in audit log |
228
228
  | MCP / agent flow exposed to ambient browser cookies | `/mcp` and agent-auth routes are bearer-only (cookies dropped entirely, see [Agent Auth](/platform/auth/plugins/agent-auth)) |
229
- | Alg-confusion / forged JWT (alg=none, HS384, RS256) | Verifier pins HS256; signature math rejects all non-matching algs uniformly with 401 |
229
+ | Alg-confusion / forged JWT (alg=none, HS256, RS256) | Verifier accepts only `EdDSA` against the keyring's public JWKS; every other alg is rejected uniformly with 401 |
230
230
 
231
231
  For a deeper walkthrough of the bearer flow itself, see the upstream [Better Auth bearer plugin docs](https://better-auth.com/docs/plugins/bearer).
232
232
 
@@ -26,7 +26,8 @@ app.get('/api/me', async (c) => {
26
26
  return c.json({
27
27
  userId: ctx.userId, // Better Auth user id
28
28
  user: ctx.user, // { id, email, name }
29
- roles: ctx.roles, // org member roles: ['owner' | 'admin' | 'member']
29
+ roles: ctx.roles, // every role the caller satisfies (hierarchy-expanded, plus tier roles)
30
+ orgRole: ctx.orgRole, // the raw membership role: 'owner' | 'admin' | 'member' | custom
30
31
  });
31
32
  });
32
33
  ```
@@ -217,7 +217,7 @@ The environment contract is intentionally exact and fails closed:
217
217
  feature set, with account-unique integer namespace IDs. Add or remove a rate
218
218
  limit and the next compile tells you which override changed.
219
219
  - `requiredSecrets` must exactly match the generated runtime inventory:
220
- `BETTER_AUTH_SECRET`, a custom `auth.jwt.secretEnv` when configured,
220
+ `BETTER_AUTH_SECRET`,
221
221
  `ENCRYPTION_KEK` when envelope-encrypted columns are present, and every
222
222
  custom secret declared with `required: true`. It also includes the shared
223
223
  `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` credentials when generated