@quickback-dev/cli 0.66.15 → 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.
Files changed (37) hide show
  1. package/dist/index.js +1 -1
  2. package/dist/lib/action-harvest.d.ts.map +1 -1
  3. package/dist/lib/action-harvest.js +28 -7
  4. package/dist/lib/action-harvest.js.map +1 -1
  5. package/dist/skill/SKILL.md +2 -2
  6. package/dist/skill/docs/api/errors.md +0 -1
  7. package/dist/skill/docs/api/typescript.md +102 -4
  8. package/dist/skill/docs/configure/agents.md +1 -1
  9. package/dist/skill/docs/configure/auth.md +28 -34
  10. package/dist/skill/docs/define/actions/defining.md +23 -11
  11. package/dist/skill/docs/define/masking.md +13 -0
  12. package/dist/skill/docs/define/schema.md +4 -1
  13. package/dist/skill/docs/define/scopes.md +12 -3
  14. package/dist/skill/docs/index.md +2 -0
  15. package/dist/skill/docs/platform/auth/jwt-optimization.md +30 -47
  16. package/dist/skill/docs/platform/auth/plugins/index.md +4 -14
  17. package/dist/skill/docs/platform/auth/security.md +2 -2
  18. package/dist/skill/docs/platform/auth/using-auth.md +2 -1
  19. package/dist/skill/docs/platform/database/neon.md +1 -1
  20. package/dist/skill/docs/tooling/cloud-compiler/local-compiler.md +3 -1
  21. package/package.json +1 -1
  22. package/src/skill/SKILL.md +2 -2
  23. package/src/skill/docs/api/errors.md +0 -1
  24. package/src/skill/docs/api/typescript.md +102 -4
  25. package/src/skill/docs/configure/agents.md +1 -1
  26. package/src/skill/docs/configure/auth.md +28 -34
  27. package/src/skill/docs/define/actions/defining.md +23 -11
  28. package/src/skill/docs/define/masking.md +13 -0
  29. package/src/skill/docs/define/schema.md +4 -1
  30. package/src/skill/docs/define/scopes.md +12 -3
  31. package/src/skill/docs/index.md +2 -0
  32. package/src/skill/docs/platform/auth/jwt-optimization.md +30 -47
  33. package/src/skill/docs/platform/auth/plugins/index.md +4 -14
  34. package/src/skill/docs/platform/auth/security.md +2 -2
  35. package/src/skill/docs/platform/auth/using-auth.md +2 -1
  36. package/src/skill/docs/platform/database/neon.md +1 -1
  37. package/src/skill/docs/tooling/cloud-compiler/local-compiler.md +3 -1
@@ -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
@@ -114,7 +114,9 @@ another workspace's install is not necessarily available in the image. Keep
114
114
  (`apps/compiler/package.json` plus `packages/deploy-contract`); do not bypass a
115
115
  frozen-lockfile failure with an unlocked install. The compiler's
116
116
  `compiler-image-imports.test.ts` check also enforces this import boundary during
117
- `pnpm verify`.
117
+ `pnpm verify`. That command also builds Quickback's API and marketing site, so
118
+ you can catch their TypeScript and CSS build failures before triggering a
119
+ deployment. CI runs the same build checks.
118
120
 
119
121
  ### Container not starting
120
122
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quickback-dev/cli",
3
- "version": "0.66.15",
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)
@@ -42,8 +42,18 @@ Each resource table exposes:
42
42
  | `actions.<name>.Input` | The action's Zod input contract |
43
43
  | `actions.<name>.Output` | The declared Zod output contract, or `unknown` |
44
44
 
45
+ Column types follow the wire, not the storage: `q.bool()` and
46
+ `integer(..., { mode: "boolean" })` are `boolean`, `integer(..., { mode: "timestamp" })`
47
+ and `q.timestamp()` are ISO `string`, `q.json()` is `unknown`, enum columns
48
+ are literal unions, and nullable columns add `| null`.
49
+
45
50
  Primary and foreign keys are branded by default. That makes accidentally passing a candidate ID where a job ID is required a TypeScript error, while both values remain ordinary strings or numbers at runtime.
46
51
 
52
+ A column is a foreign key here by the same rule the CMS and `?include=` use:
53
+ a Drizzle `.references()`, an entry in the resource's `references:` map
54
+ (`{ vendorId: 'contact' }`), or the `<table>Id` naming convention when a
55
+ table of that name exists.
56
+
47
57
  ```typescript
48
58
  function loadJob(id: Api.jobs.Id) {}
49
59
 
@@ -57,6 +67,53 @@ At an untyped boundary, validate the value and cast it once:
57
67
  const jobId = routeParams.id as Api.jobs.Id;
58
68
  ```
59
69
 
70
+ ### Auth references
71
+
72
+ Columns that point at a Better Auth principal are branded too, even though
73
+ those tables are not part of your project: tenant scopes (`q.scope('organization')`,
74
+ `q.scope('owner')`, `q.scope('team')`), the audit stamps (`createdBy`,
75
+ `modifiedBy`, `deletedBy`), and any `.references('user' | 'organization' | 'team')`
76
+ column.
77
+
78
+ ```typescript
79
+ declare const job: Api.jobs.Row;
80
+
81
+ job.organizationId; // Qb.OrganizationId
82
+ job.createdBy; // Qb.UserId | null
83
+
84
+ function notify(userId: Qb.UserId) {}
85
+ notify(job.organizationId); // TypeScript error — an org id is not a user id
86
+ ```
87
+
88
+ ## Masked columns
89
+
90
+ [Masking](/define/masking) rewrites a column's value for callers outside its
91
+ `show.roles`. A plain `string` type would promise a value the runtime does not
92
+ deliver, so tables with masking rules take a `Role` type parameter on their
93
+ read shapes: `Row<Role>`, `ListResponse<Role>`, `columns.<name><Role>`, and
94
+ `views.<name>.Item<Role>` / `Response<Role>`. Writes (`Insert`, `Update`) are
95
+ unchanged — clients send real values.
96
+
97
+ ```typescript
98
+ // jobs.ts: masking: { internalNotes: { type: 'redact', show: { roles: ['admin'] } } }
99
+ declare const anyone: Api.jobs.Row; // Role defaults to never
100
+ declare const admin: Api.jobs.Row<"admin">;
101
+ declare const member: Api.jobs.Row<"member">;
102
+
103
+ anyone.internalNotes; // Qb.Masked<string> | null — may be redacted
104
+ admin.internalNotes; // string | null — revealed
105
+ member.internalNotes; // Qb.Masked<string> | null
106
+ ```
107
+
108
+ `Qb.Masked<T>` is a brand on the wire primitive: it is still assignable to
109
+ `T` (a masked email is meant to be rendered), but it is not `T`, so a
110
+ function that requires the real value cannot silently accept the default row.
111
+ Name the role you fetched with to get the revealed type; a union role
112
+ (`Row<"member" | "admin">`) yields `T | Qb.Masked<T>`.
113
+
114
+ `show: { or: 'owner' }` reveals by record ownership, which no type parameter
115
+ can see, so those columns stay `Masked` for every role outside `show.roles`.
116
+
60
117
  ## Reading collections
61
118
 
62
119
  List and view responses share one envelope: rows under `data`, pagination
@@ -82,7 +139,19 @@ aggregations }` with no rows or pagination.
82
139
 
83
140
  ## Declaring action outputs
84
141
 
85
- Add an optional `output` Zod schema to make an action end-to-end typed:
142
+ Add an optional `output` Zod schema to make an action end-to-end typed. An
143
+ action that returns a row of a resource table declares it with `row(<table>)`
144
+ from the feature's helper — its `Output` is that table's `Row`, and OpenAPI
145
+ references the table's component:
146
+
147
+ ```typescript
148
+ import { defineAction, row, applications } from "../.quickback/define-action";
149
+
150
+ // Output = Api.applications.Row
151
+ output: row(applications)
152
+ ```
153
+
154
+ For any other shape, write the schema out:
86
155
 
87
156
  {/* doc-compile: skip — project-config prerequisite: the `recruiter+` gate needs `recruiter` in `auth.roleHierarchy`, and the gate compiles every fence against one fixed harness config whose roles are member/admin/owner. The file is otherwise whole. */}
88
157
 
@@ -106,7 +175,34 @@ export default defineAction({
106
175
  });
107
176
  ```
108
177
 
109
- The generated feature helper checks `execute` against the declared output. The CLI harvests both schemas locally without invoking `execute`; the resulting contract feeds `quickback.gen.ts`, OpenAPI, and `api-types.gen.ts`.
178
+ The generated feature helper checks `execute` against the declared output at
179
+ compile time, and the generated route **parses the result through it at
180
+ runtime** (`output.parse(result)`) before responding. The declared type is
181
+ therefore the wire truth, not an annotation: keys the schema does not declare
182
+ are stripped, and a result that does not satisfy the schema is a 500 rather
183
+ than a silently different payload. This holds for `allowRawSql` actions too —
184
+ the raw query is unchecked, but what leaves the action is not. Actions with
185
+ `responseType: 'stream'` or `'file'` return their result untouched.
186
+
187
+ The CLI harvests both schemas locally without invoking `execute`; the resulting contract feeds `quickback.gen.ts`, OpenAPI, and `api-types.gen.ts`.
188
+
189
+ ## Types are not transport
190
+
191
+ `quickback.gen.ts` is `import type` only: it describes the API, it does not
192
+ call it. A hand-rolled `fetch` still returns `any`, and nothing checks that
193
+ the URL you typed exists. For a client whose route table is the contract, use
194
+ `api-types.gen.ts` with [`openapi-fetch`](https://openapi-ts.dev/openapi-fetch/):
195
+ paths, methods, parameters, and response bodies are checked at the call site,
196
+ and both artifacts come from the same compiler model, so they cannot drift
197
+ from each other.
198
+
199
+ ```typescript
200
+ import createClient from "openapi-fetch";
201
+ import type { paths } from "../api-types.gen";
202
+
203
+ const api = createClient<paths>({ baseUrl: "https://api.example.com" });
204
+ const { data } = await api.GET("/api/v1/jobs/{id}", { params: { path: { id } } });
205
+ ```
110
206
 
111
207
  ## Configuration
112
208
 
@@ -119,7 +215,9 @@ export default defineConfig({
119
215
  });
120
216
  ```
121
217
 
122
- Use a custom path, fan out identical copies to colocated apps, disable branding, or turn the artifact off:
218
+ Use a custom path, fan out identical copies to colocated apps (a monorepo
219
+ sibling such as `../packages/shared/src/quickback.gen.ts` is allowed; absolute
220
+ paths are not), disable branding, or turn the artifact off:
123
221
 
124
222
  ```typescript
125
223
  export default defineConfig({
@@ -138,7 +236,7 @@ export default defineConfig({
138
236
  | `true` or omitted | Write `quickback.gen.ts` |
139
237
  | `false` | Do not emit the first-party type tree |
140
238
  | `"src/lib/quickback.gen.ts"` | Write to one custom path |
141
- | `["quickback.gen.ts", "apps/web/src/quickback.gen.ts"]` | Fan out identical copies |
239
+ | `["quickback.gen.ts", "../packages/shared/src/quickback.gen.ts"]` | Fan out identical copies, including outside the project |
142
240
  | `{ output, brandIds: false }` | Configure paths and use structural IDs |
143
241
 
144
242
  `api-types.gen.ts` remains available through `openapi.types` for `openapi-fetch` and third-party OpenAPI tools. The two artifacts are independent: disabling OpenAPI types does not disable the first-party tree.
@@ -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
@@ -149,32 +149,44 @@ OpenAPI success response becomes `{}` and
149
149
  `Api.<feature>.actions.<action>.Output` becomes `unknown`. The compile still
150
150
  succeeds — it warns, naming how many actions are affected.
151
151
 
152
- **Declare the output shape as a literal Zod schema.** Do not derive it from a
153
- table:
152
+ **An action that returns a row declares it with `row(<table>)`**, imported
153
+ from the same helper as `defineAction`. **Any other shape is a literal Zod
154
+ schema.** Do not derive a schema from a table yourself:
154
155
 
155
156
  ```typescript
156
- // Silently produces an EMPTY contract — do not do this.
157
- output: z.object({ tickets: z.array(createSelectSchema(ticketTypes)) })
157
+ import { defineAction, row, tickets } from "../.quickback/define-action";
158
158
 
159
- // Documents the response.
159
+ // Returns one ticket: Output = Api.tickets.Row, OpenAPI = the Tickets component.
160
+ output: row(tickets)
161
+
162
+ // Any other shape — write it out.
160
163
  output: z.object({
161
164
  tickets: z.array(z.object({ id: z.string(), name: z.string(), priceCents: z.number() })),
162
165
  })
166
+
167
+ // Silently produces an EMPTY contract — do not do this.
168
+ output: z.object({ tickets: z.array(createSelectSchema(ticketTypes)) })
163
169
  ```
164
170
 
171
+ `row(table)` is compiler-recognised: the harvester records which table it
172
+ was handed, and the compiler resolves that to the table's `Row` type in
173
+ `quickback.gen.ts` and to its resource component in OpenAPI (the table must
174
+ be a `defineTable()` resource — anything else is a compile error). At
175
+ runtime it is a real Zod object built from the table's columns.
176
+
165
177
  The harvest substitutes inert proxies for table modules, so anything that
166
178
  derives a schema by enumerating a table's columns — `createSelectSchema` and
167
179
  every equivalent — enumerates **zero** columns. It does not throw. It returns a
168
180
  valid, empty object schema, which is then published as the documented success
169
181
  response. The compiler warns when a declared `output:` resolves to an empty
170
182
  object, but the warning is the only signal; the compile passes and the spec
171
- looks fine.
183
+ looks fine. `row()` exists so you never need that derivation.
172
184
 
173
- The proxy substitution has one exception, and it is not a supported escape
174
- hatch: a table module that also contains a `z.object(...)` is bundled and
175
- evaluated for real, so a derivation in that file happens to work. Whether it
176
- works depends on unrelated content in the table file — declare the shape
177
- instead.
185
+ **A declared `output:` is enforced.** The generated route parses `execute`'s
186
+ result through it before responding, so the published contract is what
187
+ actually leaves the action: undeclared keys are stripped, and a result that
188
+ does not satisfy the schema is a 500. See
189
+ [Declaring action outputs](/api/typescript#declaring-action-outputs).
178
190
 
179
191
  **`output` describes the success path only.** Error responses never pass
180
192
  through it: throw