@quickback-dev/cli 0.66.3 → 0.66.5

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 (65) hide show
  1. package/dist/index.js +1 -1
  2. package/dist/skill/docs/api/errors.md +1 -1
  3. package/dist/skill/docs/api/openapi.md +26 -6
  4. package/dist/skill/docs/changelog/index.md +31 -0
  5. package/dist/skill/docs/configure/agents.md +2 -2
  6. package/dist/skill/docs/configure/auth.md +17 -3
  7. package/dist/skill/docs/define/access.md +29 -6
  8. package/dist/skill/docs/define/firewall.md +1 -0
  9. package/dist/skill/docs/define/guards.md +16 -11
  10. package/dist/skill/docs/define/scopes.md +33 -0
  11. package/dist/skill/docs/platform/api-contract/index.md +36 -1
  12. package/dist/skill/docs/platform/auth/security.md +40 -15
  13. package/dist/skill/docs/platform/realtime/using-realtime.md +8 -0
  14. package/dist/skill/docs/platform/storage/r2.md +9 -6
  15. package/dist/skill/docs/platform/storage/using-r2.md +23 -8
  16. package/dist/skill/docs/ui/account/features/admin.md +3 -1
  17. package/package.json +1 -1
  18. package/src/skill/docs/api/errors.md +1 -1
  19. package/src/skill/docs/api/openapi.md +26 -6
  20. package/src/skill/docs/changelog/index.md +31 -0
  21. package/src/skill/docs/configure/agents.md +2 -2
  22. package/src/skill/docs/configure/auth.md +17 -3
  23. package/src/skill/docs/define/access.md +29 -6
  24. package/src/skill/docs/define/firewall.md +1 -0
  25. package/src/skill/docs/define/guards.md +16 -11
  26. package/src/skill/docs/define/scopes.md +33 -0
  27. package/src/skill/docs/platform/api-contract/index.md +36 -1
  28. package/src/skill/docs/platform/auth/security.md +40 -15
  29. package/src/skill/docs/platform/realtime/using-realtime.md +8 -0
  30. package/src/skill/docs/platform/storage/r2.md +9 -6
  31. package/src/skill/docs/platform/storage/using-r2.md +23 -8
  32. package/src/skill/docs/ui/account/features/admin.md +3 -1
  33. package/dist/codex/AGENTS.md +0 -290
  34. package/dist/commands/codex.d.ts +0 -16
  35. package/dist/commands/codex.d.ts.map +0 -1
  36. package/dist/commands/codex.js +0 -159
  37. package/dist/commands/codex.js.map +0 -1
  38. package/dist/commands/compile.d.ts +0 -62
  39. package/dist/commands/compile.d.ts.map +0 -1
  40. package/dist/commands/compile.js +0 -830
  41. package/dist/commands/compile.js.map +0 -1
  42. package/dist/commands/compile.test.d.ts +0 -2
  43. package/dist/commands/compile.test.d.ts.map +0 -1
  44. package/dist/commands/compile.test.js +0 -150
  45. package/dist/commands/compile.test.js.map +0 -1
  46. package/dist/commands/init.d.ts +0 -6
  47. package/dist/commands/init.d.ts.map +0 -1
  48. package/dist/commands/init.js +0 -405
  49. package/dist/commands/init.js.map +0 -1
  50. package/dist/docs/content.d.ts +0 -7
  51. package/dist/docs/content.d.ts.map +0 -1
  52. package/dist/docs/content.js +0 -672
  53. package/dist/docs/content.js.map +0 -1
  54. package/dist/lib/helpers.d.ts +0 -39
  55. package/dist/lib/helpers.d.ts.map +0 -1
  56. package/dist/lib/helpers.js +0 -299
  57. package/dist/lib/helpers.js.map +0 -1
  58. package/dist/lib/sweep-stale.d.ts +0 -25
  59. package/dist/lib/sweep-stale.d.ts.map +0 -1
  60. package/dist/lib/sweep-stale.js +0 -179
  61. package/dist/lib/sweep-stale.js.map +0 -1
  62. package/dist/lib/sweep-stale.test.d.ts +0 -2
  63. package/dist/lib/sweep-stale.test.d.ts.map +0 -1
  64. package/dist/lib/sweep-stale.test.js +0 -130
  65. package/dist/lib/sweep-stale.test.js.map +0 -1
@@ -45,15 +45,15 @@ The CLI evaluates only the schema declarations in an isolated local bundle and c
45
45
 
46
46
  ## Configuration
47
47
 
48
- Both generation and publishing default to `true`. You can control them independently in `quickback.config.ts`:
48
+ Generation defaults to `true`; publishing defaults to **`'authenticated'`**. You can control them independently in `quickback.config.ts`:
49
49
 
50
50
  ```typescript
51
51
  export default defineConfig({
52
52
  name: "my-app",
53
53
  // ...
54
54
  openapi: {
55
- generate: true, // write the spec into src/apps/__quickback/spec/
56
- publish: true, // serve GET /openapi.json at runtime
55
+ generate: true, // write the spec into src/apps/__quickback/spec/
56
+ publish: "authenticated", // serve GET /openapi.json to signed-in callers (default)
57
57
  },
58
58
  });
59
59
  ```
@@ -61,10 +61,30 @@ export default defineConfig({
61
61
  | Option | Default | Description |
62
62
  |--------|---------|-------------|
63
63
  | `generate` | `true` | Write `openapi.json` into `src/apps/__quickback/spec/` during compilation |
64
- | `publish` | `true` | Serve the spec at `GET /openapi.json` (requires `generate: true`) |
64
+ | `publish` | `'authenticated'` | Who may fetch the spec at runtime — see the gate table below (requires `generate: true`) |
65
65
  | `docs` | `false` | Mount an interactive API browser at `GET /docs` — `"scalar"`, `"swagger"`, or `false` |
66
66
 
67
- Omitting the `openapi` key entirely is equivalent to `generate: true, publish: true, docs: false`.
67
+ Omitting the `openapi` key entirely is equivalent to `generate: true, publish: 'authenticated', docs: false`.
68
+
69
+ ### The publish gate
70
+
71
+ The spec hands a caller the complete route inventory, every action's input
72
+ schema, custom action names, and the role vocabulary — exactly the
73
+ reconnaissance an authorization probe needs. So the gate is **authenticated by
74
+ default**, and it covers every surface that reveals the same information, never
75
+ just `/openapi.json`:
76
+
77
+ | `publish` | `/openapi.json`, `/asyncapi.json`, `/docs`, `/llms.txt`, `/.well-known/api-catalog` |
78
+ |-----------|------------------------------------------------------------------------------------|
79
+ | `'authenticated'` (default; also `undefined`) | Any signed-in caller; anonymous → `401` |
80
+ | `'admin'` | `appmanager` / `sysadmin` only; other signed-in callers → `403` |
81
+ | `'public'` (also `true`) | Anyone — opt in for anonymous MCP / agent discovery |
82
+ | `false` | Route not mounted (`/docs` is skipped too) |
83
+
84
+ The OAuth / agent-auth discovery documents under `/.well-known/` stay public
85
+ regardless — RFC 8414 / 9728 clients must read them before they hold a
86
+ credential — and `/robots.txt` is public by nature. `/mcp` carries its own
87
+ authentication.
68
88
 
69
89
  ### Generate only (no runtime route)
70
90
 
@@ -105,7 +125,7 @@ openapi: {
105
125
 
106
126
  Both UIs are loaded from CDN in a generated static HTML route — **no npm package is added to your project, no Hono middleware is installed, and the runtime bundle stays the same size**. The flag is purely compile-time: it toggles whether a `/docs` route is emitted.
107
127
 
108
- Requires `publish: true` (the default). When `publish` is off, `/docs` is silently skipped — there's no spec for it to read.
128
+ Requires `publish` not to be `false`. `/docs` inherits the same gate as the spec (`'authenticated'` by default) so the browser page never 401s on its own data source; when `publish: false`, `/docs` is silently skipped — there's no spec for it to read.
109
129
 
110
130
  ## Usage with tools
111
131
 
@@ -8,6 +8,37 @@ The current release series. Older entries are archived by version range:
8
8
  - [v0.20 – v0.29](/changelog/v0.2x)
9
9
  - [v0.18 and earlier](/changelog/v0.1x)
10
10
 
11
+ ## Unreleased — delete rows reach after-write consumers
12
+
13
+ - **Every delete statement now carries `.returning()`** ([#414](https://github.com/paulstenhouse/quickback-compiler/issues/414)). The single-record soft delete, the single-record hard delete, and the batch hard delete emitted no `RETURNING`, so on D1 the write result carried no rows and the audit-wrapper chokepoint had nothing to hand to its consumers: `afterDelete` trigger hooks never ran, live-view deltas were not emitted, and the scope-revocation and SEALED hard-delete audit-snapshot taps were skipped on those paths. Recompile to pick it up; response shapes are unchanged.
14
+
15
+ ## Unreleased — scope enter tenant drop
16
+
17
+ - **`/scope/v1/enter` mints a relationship-only token for a foreign-tenant instance** (follow-up to [#391](https://github.com/paulstenhouse/quickback-compiler/issues/391)). When the relationship's `from` table carries an organization column, the proven row's tenant is compared with `ctx.activeOrgId`; on a mismatch the token carries no `orgId` / `role`. Previously such a token was harmless (the tenant-bound firewall and resolver refused it) but still persisted the foreign org beside the scope. See [scopes](/define/scopes#per-matched-lane-minting-forging-safety).
18
+ - **The shipped access evaluator and the compiler's reference copy are parity-tested** — `access-evaluator-parity.test.ts` runs both through one behavioural table (roles, principals, `userRole`, every `record:` condition, `or` / `and` nesting, collection predicates), so a fix that lands in one copy and not the other fails a test instead of drifting.
19
+
20
+ ## Unreleased — access-evaluator hardening
21
+
22
+ - **`access.record` is enforced on collection reads and batch-create** ([#394](https://github.com/paulstenhouse/quickback-compiler/issues/394)). `GET /`, per-view lists, and the MCP list tool fold each admitted arm's `record:` predicates into the query `WHERE`; `POST /batch` checks every input record the way single `POST` does. The `AUTHZ_RECORD_PREDICATE_NOT_ON_LIST` warning is retired because the list now honours the predicate. See [access](/define/access#collection-routes-honour-accessrecord-too).
23
+ - **The access evaluator denies instead of throwing** ([#354](https://github.com/paulstenhouse/quickback-compiler/issues/354)). A `$ctx.` path with a missing intermediate resolves to undefined (403, not 500), and `equals` / `notEquals` deny when either side is absent instead of matching `undefined === undefined`.
24
+ - **Function-form `read.access` is a compile error** ([#353](https://github.com/paulstenhouse/quickback-compiler/issues/353)) instead of emitting `const getAccess = undefined` into `GET /:id`.
25
+ - **Dependency overrides land in the key your package manager reads** ([#359](https://github.com/paulstenhouse/quickback-compiler/issues/359)): `overrides` for npm and bun, `pnpm.overrides` for pnpm, `resolutions` for yarn — so the lodash security pin is no longer silently inert off npm.
26
+ - **Top-level `rateLimit` is accepted by the config schema** ([#180](https://github.com/paulstenhouse/quickback-compiler/issues/180)); it was typed and consumed but rejected by the strict validator.
27
+
28
+ ## Unreleased — tenant binding and credential hygiene
29
+
30
+ Fixes from the attend-vip API security review. All are compiler changes;
31
+ recompile to pick them up.
32
+
33
+ - **Namespaces / scopes are tenant-bound** ([#391](https://github.com/paulstenhouse/quickback-compiler/issues/391)). A `{ roles }` / `{ team }` bulk-grant lane only applies when the hydrated instance belongs to `ctx.activeOrgId`; otherwise the caller falls through to the relationship lanes with no org roles. Inside an `any` firewall group with an org arm, scope / `via:` / permission arms are tenant-bound. Every mint (`/scope/v1/enter`, namespace `mintScope`, `/api/v1/token`) signs `orgId` only beside a membership `role`, the verifier ignores an unpaired `orgId`, and `POST /api/v1/token { dropOrg: true }` is a native privilege drop. See [scopes](/define/scopes#the-bulk-grant-lane-is-tenant-bound).
34
+ - **Admin plugin honours the declared roles** ([#199](https://github.com/paulstenhouse/quickback-compiler/issues/199)). `plugins.admin.adminRoles` and `roles` are emitted verbatim; a narrowed `appmanager` stays narrowed, and an un-honourable declaration is a compile error.
35
+ - **Better Auth rate limiting is durable on Workers** ([#404](https://github.com/paulstenhouse/quickback-compiler/issues/404)). `rateLimit.storage` defaults to `"database"` on Cloudflare (a `rateLimit` table is added — expect one migration), and every credential door (sign-up, password reset, email / phone OTP, magic link, two-factor, device flow) ships with a per-route rule; `customRules` merge on top. See [auth security](/platform/auth/security#rate-limiting).
36
+ - **Presigned uploads enforce `maxFileSize` / `allowedTypes`** ([#405](https://github.com/paulstenhouse/quickback-compiler/issues/405)). `storage.signPutUrl` now requires `contentLength`; size and type are signed headers (`Content-Length`, `Content-Type`) the PUT must replay, and the declared limits are checked before a URL is minted. **Breaking for authored presign actions:** pass `contentLength`. See [using R2](/platform/storage/using-r2#presigned-uploads-with-ctxstorage).
37
+ - **Auth catch blocks are generic in production** ([#406](https://github.com/paulstenhouse/quickback-compiler/issues/406)). `/auth/v1/*` and `/api/v1/token` 500s carry the underlying message only under `EXPOSE_ERROR_STACK`; the error-body redaction list now includes the compiler's own credential fields (`sessionToken`, `eventSessionToken`, `scopeJwt`, `wsTicket`, …).
38
+ - **`openapi.publish` defaults to `'authenticated'` and gates every discovery surface** ([#407](https://github.com/paulstenhouse/quickback-compiler/issues/407)). `/openapi.json`, `/asyncapi.json`, `/docs`, `/llms.txt`, and `/.well-known/api-catalog` share one gate. **Breaking:** a project that relied on the anonymous default must set `publish: 'public'`. See [OpenAPI](/api/openapi#the-publish-gate).
39
+ - **No shared `'default'` realtime room** ([#408](https://github.com/paulstenhouse/quickback-compiler/issues/408)). Org-less callers get a ticket bound to their own user room; org-less emits are skipped; a target naming no room is refused.
40
+ - **`contract.redirects`** ([#409](https://github.com/paulstenhouse/quickback-compiler/issues/409)). Declarative same-origin path redirects (`/api/v2/*` → `/api/v1/*`, 308 by default), emitted right after the CORS mount so they survive every compile. See [API contract](/platform/api-contract#redirects--keep-answering-an-old-prefix).
41
+
11
42
  ## Unreleased — the standard API shape
12
43
 
13
44
  ### BREAKING: `contract.version` is retired
@@ -9,10 +9,10 @@ When `agents` is enabled (the default), the Worker serves:
9
9
  | Route | What it is |
10
10
  |-------|-----------|
11
11
  | `GET /robots.txt` | AI-bot policy with the [Cloudflare Content Signals](https://developers.cloudflare.com/bots/concepts/content-signals/) preamble and explicit `Allow:` rules for GPTBot, ClaudeBot, PerplexityBot, Google-Extended, CCBot, Applebot-Extended, Bytespider, MistralAI, Cohere, DuckAssist. |
12
- | `GET /llms.txt` | Agent-facing summary of the API — project name, authentication, resource list, endpoint conventions — derived from your own config. |
12
+ | `GET /llms.txt` | Agent-facing summary of the API — project name, authentication, resource list, endpoint conventions — derived from your own config. Follows the [`openapi.publish`](/api/openapi#the-publish-gate) gate (`'authenticated'` by default) because it enumerates the same route inventory as the spec. |
13
13
  | `GET /.well-known/oauth-protected-resource` | [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) metadata declaring this Worker as a protected resource. |
14
14
  | `GET /.well-known/oauth-authorization-server` | [RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414) authorization-server metadata. When the `oauthProvider` plugin is enabled it **delegates to Better Auth's real OAuth 2.1 surface** (`/oauth2/authorize`, `/oauth2/token`, `/oauth2/register` dynamic client registration, PKCE); otherwise it advertises only the truthful token-mint subset. |
15
- | `GET /.well-known/api-catalog` | [RFC 9727](https://datatracker.ietf.org/doc/html/rfc9727) catalog linking at `/openapi.json`. |
15
+ | `GET /.well-known/api-catalog` | [RFC 9727](https://datatracker.ietf.org/doc/html/rfc9727) catalog linking at `/openapi.json`. Same [`openapi.publish`](/api/openapi#the-publish-gate) gate as the spec. |
16
16
  | `GET /.well-known/mcp.json` | MCP Server Card — discoverable metadata for the MCP server below. |
17
17
  | `POST /mcp` | Auto-generated MCP-over-HTTP server. One tool per OpenAPI operation, JWT auth forwarded through the same middleware as the REST API. |
18
18
 
@@ -53,7 +53,7 @@ Quickback ships its own custom HMAC-SHA256 JWT (not Better Auth's JWT plugin) so
53
53
  The short version, before the knob-by-knob detail:
54
54
 
55
55
  - **Default: 180-second TTL, auto-refreshed.** Every authenticated call returns a fresh token via the `set-auth-token` header, so the low TTL is invisible to logged-in users. The worst-case window for a stolen or pre-revocation token is 3 minutes — and you can shrink it to 30 seconds with one config line.
56
- - **Need revocation faster than the TTL?** Set [`revocationCheck: 'kv'`](#revocationcheck-none--kv--token-revocation-strategy). Revoked tokens are rejected within seconds; revocation stamps are written automatically on user ban, org-member removal, role change, and changes to scope-conferring relationship rows.
56
+ - **Need revocation faster than the TTL?** Set [`revocationCheck: 'kv'`](#revocationcheck-none--kv--token-revocation-strategy). Revoked tokens are rejected within seconds; revocation stamps are written automatically on sign-out and session revocation (per session), on password change with `revokeOtherSessions`, account deletion, user ban, org-member removal, role change, and changes to scope-conferring relationship rows. Long-lived tokens are therefore safe to pair with it: a remote "sign out everywhere" kills a lost device's bearer.
57
57
 
58
58
  Those two knobs — `expiresIn` and `revocationCheck` — cover the vast majority of deployments. The honest residual for the strictest threat models: the KV check revokes per-principal (not per-session) and propagates cross-PoP in ~60s. It **fails closed** — if KV can't be read, the bearer isn't trusted and a bearer-only caller gets a retryable `503`, so enabling it ties bearer availability to KV. If you need per-session kill semantics, set `expiresIn: 30` for a hard 30-second ceiling — and [tell us about your use case](https://github.com/kardoe/quickback/issues); an opaque-session mode is under consideration.
59
59
 
@@ -102,6 +102,19 @@ auth: { jwt: { secretEnv: 'CUSTOM_JWT_SECRET' } }
102
102
 
103
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.
104
104
 
105
+ ### `POST /api/v1/token` — mint an identity JWT
106
+
107
+ Session-authenticated callers (cookie or session-token bearer) mint a short-lived
108
+ JWT carrying `sub`, `orgId`, `role`, `userRole`, `email`, `name`. Two invariants:
109
+
110
+ - **`orgId` is only ever signed beside a membership `role`**, and the verifier
111
+ ignores an `orgId` claim that arrives without one — so a token can never be a
112
+ 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
+
105
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.
106
119
 
107
120
  ### `algorithm?: 'HS256'`
@@ -123,11 +136,12 @@ A token is rejected when its mint timestamp (`iat`/`iatMs`, or the scope claim's
123
136
 
124
137
  | Key | Revokes | Written automatically on |
125
138
  |---|---|---|
126
- | `qbrev:user:<userId>` | every JWT for the user | user ban (`databaseHooks.user.update.after` — flipping `banned` stamps the key and, when outbound webhooks are enabled, emits a `user.banned` event). Call `revokeUserTokens` for custom flows (revoke-all, etc.) |
139
+ | `qbrev:sid:<sessionId>` | every JWT minted from one Better Auth session (tokens carry the minting session as `sid`) | `POST /sign-out` and `POST /revoke-session` (Better Auth endpoint hooks) — a lost device's token dies with its session while the user's other devices keep theirs |
140
+ | `qbrev:user:<userId>` | every JWT for the user | user ban (`databaseHooks.user.update.after` — flipping `banned` stamps the key and, when outbound webhooks are enabled, emits a `user.banned` event); `revoke-sessions`, `revoke-other-sessions`, `change-password` with `revokeOtherSessions`, and `delete-user` (endpoint hooks). Call `revokeUserTokens` for custom flows |
127
141
  | `qbrev:member:<userId>:<orgId>` | the user's org-membership claims | member removal / role change (Better Auth `organizationHooks`) |
128
142
  | `qbrev:scope:<userId>:<kind>:<id>` | the user's carried scope claim | UPDATE/DELETE of a scope-conferring relationship row (audit-wrapper chokepoint + the single DELETE route) |
129
143
 
130
- `src/lib/jwt-revocation.ts` exports `revokeUserTokens` / `revokeMemberTokens` / `revokeScopeTokens` for explicit calls from actions. A rejected token falls through to session auth, which re-checks membership and re-mints — an active legitimate session recovers transparently.
144
+ `src/lib/jwt-revocation.ts` exports `revokeUserTokens` / `revokeSessionTokens` / `revokeMemberTokens` / `revokeScopeTokens` for explicit calls from actions. A rejected token falls through to session auth, which re-checks membership and re-mints — an active legitimate session recovers transparently.
131
145
 
132
146
  Semantics worth knowing:
133
147
 
@@ -413,12 +413,35 @@ opaque 404 instead.
413
413
 
414
414
  Function-form access (`access: async (ctx, record) => ...`) is opaque to
415
415
  the pre-record phase and always passes there; it's fully evaluated post-record.
416
-
417
- Collection routes (`GET /`, `POST /batch`, and the generated MCP list tool)
418
- stop at step 2: there is no record to evaluate, so `access.record` is **not**
419
- applied to a list — row scoping on a list is the [firewall's](/define/firewall)
420
- job. Don't use an unsatisfiable predicate (`record: { id: { equals: "never" } }`)
421
- to hide a resource; it still lists. To give a resource no read surface, omit
416
+ It is accepted on `create` / `update` / `delete`, where the generated route
417
+ references it at runtime. It is **not** accepted as `read.access`: the
418
+ generated `GET /:id` route serialises the read tree inline, so a function
419
+ there is a compile error naming the resource. Express read rules
420
+ declaratively (`roles`, `userRole`, `record`, `or`, `and`).
421
+
422
+ ### Collection routes honour `access.record` too
423
+
424
+ `GET /`, the per-view lists, and the generated MCP list tool fold the same
425
+ `record:` predicates into the query's `WHERE`, arm for arm, so a list can never
426
+ return a row the caller could not `GET` one at a time:
427
+
428
+ - Each `or` arm whose role / `userRole` gates admit the caller contributes its
429
+ `record` predicates as one AND-group; the groups are OR'd together.
430
+ - An admitted arm with **no** `record` block lifts the constraint for the
431
+ whole list (that arm would admit every row on `GET /:id` as well).
432
+ - A `$ctx.` value that is absent for the caller (no `activeOrgId`, no
433
+ `scope`) makes that arm unsatisfiable — it denies, never matches.
434
+ - A predicate on a column the table does not have yields no rows.
435
+ - No admitted arm at all → `403` from the role gate, as before.
436
+
437
+ `POST /batch` runs the same per-record check single `POST` does
438
+ (`record:` against each input body), and rejects the offending records
439
+ individually in the batch `errors` array.
440
+
441
+ Row scoping by tenant is still the [firewall's](/define/firewall) job; an
442
+ unsatisfiable predicate (`record: { id: { equals: "__never__" } }`) now hides
443
+ every row on every read surface, which is a legitimate way to give a resource
444
+ a get-only or write-only surface. To give it no read surface at all, omit
422
445
  `read` — no list, get, batch, or MCP route is emitted.
423
446
 
424
447
  ## Context Variables
@@ -129,6 +129,7 @@ firewall: {
129
129
  Null-safe scope semantics make this safe (these apply **inside `all`/`any` groups**, opt-in via the new syntax):
130
130
 
131
131
  - A **scope** arm (`ctx.activeOrgId`, `ctx.activeTeamId`, `ctx.scope.*`) whose claim is **absent never binds `undefined`** (the classic 500 / "match every row" trap). In an `any` group an absent arm **drops**; if **every** arm drops, the group denies with `sql\`1 = 0\`` (the empty-guard) — never a full-table read. In an `all` group an absent required scope **denies** the group.
132
+ - **An `any` group with an org arm tenant-binds its scope and relationship arms.** Beside `{ field: 'organizationId', equals: 'ctx.activeOrgId' }`, a `ctx.scope.*` arm, a `via:` arm, or a `{ permission }` arm is emitted as `scope-arm AND (organizationId = ctx.activeOrgId OR the caller has no org claim)`. A caller with **no** org claim (a scope-only or relationship principal) is unaffected; a caller who carries org B's membership *and* a scope claim or relationship row on an org-A instance cannot ride the scope arm into org A's rows. Owner arms (`ctx.userId`), team arms, and literal `in` lists are not tenant-bound. An org claim and a scope claim in one request are therefore always the same tenant — or the scope arm yields nothing.
132
133
  - Mark an arm `{ optional: true }` to **drop-instead-of-deny** when absent inside an `all` group (the teamless rest-of-org slice — `ctx.activeTeamId` is implicitly optional).
133
134
  - **Owner** (`ctx.userId`) and **soft-delete** (`isNull deletedAt`) are always present / always AND'd — never relaxed.
134
135
 
@@ -67,17 +67,22 @@ guards: {
67
67
  |------|------------------|
68
68
  | `createable` | Fields allowed in create (POST) request body |
69
69
  | `updatable` | Fields allowed in update (PATCH) request body |
70
- | `protected` | Fields blocked from direct writes; the named actions are documentation, not enforcement (see below) |
71
- | `immutable` | Fields allowed on create, blocked on all generic updates (actions can still write them) |
72
-
73
- > **Guards bind the generic CRUD surface, not actions.** `createable`,
74
- > `updatable`, `immutable`, and `protected` are enforced by the generated
75
- > `validateCreate` / `validateUpdate`, which only the CRUD, batch, and changeset
76
- > routes call. An action handler writes through a scoped `db` with no field-level
77
- > checks, so it can write any column — including an `immutable` one, and including
78
- > a `protected` one not listed in that field's action names. Treat the names in
79
- > `protected` as intent you are documenting, and keep the enforcement in the
80
- > action's own access rules.
70
+ | `protected` | Fields blocked from direct writes; writable only by the actions named for them |
71
+ | `immutable` | Fields allowed on create, then never written again — by CRUD, batch, changeset, **or actions** |
72
+
73
+ > **Guards bind actions too.** `createable` and `updatable` shape the CRUD
74
+ > request bodies. `immutable` and `protected` are additionally enforced against
75
+ > your action handlers at **compile time**: the compiler scans each action bound
76
+ > to the table for `db.update(<table>).set({ … })` / `db.insert(<table>).values({ … })`
77
+ > and refuses an `immutable` column in any update, or a `protected` column
78
+ > written by an action that is not in its list — with an error naming the action,
79
+ > the column, and the fix. The two tiers are therefore distinct: `immutable` is
80
+ > written once at create and never again; if a column needs an action to change
81
+ > it, it is `protected`, mapped to that action.
82
+ >
83
+ > The scan sees object-literal payloads only. A spread (`.set({ ...input })`) or
84
+ > a variable payload (`.set(patch)`) is not analysed, so keep guarded columns out
85
+ > of such payloads yourself — that is the documented residual.
81
86
 
82
87
 
83
88
  **Combining lists:**
@@ -347,6 +347,39 @@ so it can only ever carry the role the caller actually proved this request.
347
347
 
348
348
  - A **multi-lane `via:`** (e.g. `via: ['attendeeOf', 'organizerOf']`) mints the matched lane's role — `attendeeOf` → `scope.event.roles = ['attendee']`, `organizerOf` → `['organizer']`. The resolver records which lane opened the gate, so there is no ambiguity.
349
349
  - A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) mints **no** scope role — it opens the gate via the caller's org role without proving a relationship. The gate passes; the caller carries their org role, not a minted scope role.
350
+ - **The org claim is only ever signed beside a membership role.** Every mint site — `/scope/v1/enter`, the namespace resolver, `/api/v1/token` — writes `orgId` into the token only when a membership `role` accompanies it, and the auth middleware ignores an `orgId` claim that arrives without a `role`. A relationship-promoted tenant (the in-request `ctx.activeOrgId` stamped from the proven row so the firewall resolves) is never persisted as a bare tenant grant.
351
+ - **`/scope/v1/enter` drops the org claims for a foreign-tenant instance.** When the relationship's `from` table carries an organization column, the enter route reads it off the proven row (the same row the probe already fetched — no extra query) and compares it with `ctx.activeOrgId`. A mismatch — an org-B member entering an org-A event — mints the token **without** `orgId` / `role`: a relationship-only principal, exactly the state the namespace resolver gives the same caller. The caller keeps their org seat for org-B requests by using their session or a plain `/api/v1/token`; the scope token is for the scope. A `from` table with no organization column (a global reference relationship) leaves the claim untouched.
352
+
353
+ ### The bulk-grant lane is tenant-bound
354
+
355
+ An org role is only good **inside the caller's own org**. When the namespace
356
+ hydrates a shared resource whose table carries an organization column (the
357
+ `loads` / `exposeAs` target), the resolver checks that the requested instance
358
+ belongs to `ctx.activeOrgId` *before* honouring a `{ roles }` / `{ team }`
359
+ lane. If it does not — an org-B admin entering an org-A event — the lane does
360
+ not apply: the caller is re-evaluated through the relationship lanes as a
361
+ **relationship-only principal**, with `ctx.roles = []` and the in-request tenant
362
+ re-stamped from the proven row (exactly the state a caller with no org seat
363
+ gets). No relationship → `403`. Any `ctx.roles`-based check in the action then
364
+ fails for them, scoped-db inserts stamp the *instance's* org, and the
365
+ namespace re-mint carries no org claim.
366
+
367
+ Multi-target namespaces (lanes that hydrate *different* tables) hydrate nothing
368
+ for a role caller, so there is nothing to bind there — put the tenant check in
369
+ the firewall of each table instead (an org arm in an [`any` group tenant-binds
370
+ its scope arms](/define/firewall#allany-groups--null-safe-scope-semantics) automatically).
371
+
372
+ ### Dropping the org claim on purpose
373
+
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:
376
+
377
+ ```bash
378
+ curl -X POST https://api.example.com/api/v1/token \
379
+ -H "Cookie: <session>" -H "Content-Type: application/json" \
380
+ -d '{ "dropOrg": true }'
381
+ # → { token } with no orgId / role claim; scope entry then proves only relationships
382
+ ```
350
383
 
351
384
  > 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.
352
385
 
@@ -115,11 +115,14 @@ export default defineAction({
115
115
 
116
116
  ## One axis: routes
117
117
 
118
- `contract` has a single key. It selects the URL prefix and nothing else.
118
+ `contract.routes` is the one behavioural axis. It selects the URL prefix and
119
+ nothing else. (`contract.redirects`, below, adds same-origin path redirects —
120
+ it changes no behaviour of the canonical routes.)
119
121
 
120
122
  | Key | Controls | Default |
121
123
  |---|---|---|
122
124
  | `routes` | The URL prefix, and nothing else | `'v1'` |
125
+ | `redirects` | Same-origin path redirects, emitted natively | none |
123
126
 
124
127
  A project with no `contract` block serves `/api/v1`. Set `routes: "v2"` to
125
128
  serve `/api/v2` instead — the behavior is identical either way.
@@ -176,6 +179,38 @@ service, so an older CLI gets the same output.
176
179
  | Auth base | `/auth/v1` | `/auth/v2` |
177
180
  | Realtime base | `/broadcast/v1` | `/broadcast/v2` |
178
181
 
182
+ ### `redirects` — keep answering an old prefix
183
+
184
+ A project that keeps `routes: "v1"` can still answer an older `/api/v2/*`
185
+ prefix by declaring the redirect — as config, not as a hand-edit of the
186
+ generated `src/index.ts` that the next compile clobbers:
187
+
188
+ {/* doc-compile: skip — config fragment, not a compilable project */}
189
+ ```typescript
190
+ contract: {
191
+ routes: "v1",
192
+ redirects: [
193
+ { from: "/api/v2/*", to: "/api/v1/*" }, // 308 by default
194
+ { from: "/auth/v2/*", to: "/auth/v1/*" },
195
+ { from: "/broadcast/v2/*", to: "/broadcast/v1/*" },
196
+ { from: "/legacy/health", to: "/health", status: 301 },
197
+ ],
198
+ }
199
+ ```
200
+
201
+ - `from` / `to` are **paths** — they must start with `/` and can never be a
202
+ full URL or a `//host` form, so a rule cannot become an open redirect. The
203
+ emitted `Location` is always same-origin.
204
+ - A trailing `/*` makes a **prefix** rule: it matches the bare prefix and
205
+ everything under it, and carries the remainder across (`/api/v2/events/7`
206
+ → `/api/v1/events/7`). `from` and `to` must both end with `/*` or neither.
207
+ - The query string is preserved; `status` is `308` (method + body preserving)
208
+ by default, or `301` / `302` / `307`.
209
+ - Rules are validated at compile time (self-redirects and prefix loops are
210
+ rejected) and emitted right after the CORS mount, ahead of auth, so
211
+ preflights still get their headers and every later layer sees canonical
212
+ paths only.
213
+
179
214
  ## Machine-readable contract
180
215
 
181
216
  - `GET /openapi.json` — OpenAPI 3.1: Problem responses, cursor params,
@@ -89,28 +89,53 @@ auth: defineAuth("better-auth", {
89
89
  enabled: true,
90
90
  window: 60, // 60 second window
91
91
  max: 100, // 100 requests per IP per window
92
+ storage: "database", // default on Cloudflare Workers — see below
92
93
  customRules: {
94
+ // Merged ON TOP of the built-in per-route rules (same path → yours wins)
93
95
  "/sign-in/email": { window: 60, max: 10 },
94
- "/sign-in/social": { window: 60, max: 10 },
95
- "/device/init": { window: 60, max: 5 },
96
- "/device/poll": { window: 60, max: 30 },
97
- "/device/token": { window: 60, max: 10 },
98
96
  }
99
97
  }
100
98
  })
101
99
  ```
102
100
 
103
- ### Custom Rules by Endpoint
104
-
105
- Set different limits based on endpoint sensitivity:
106
-
107
- | Endpoint Type | Recommended Limit | Reasoning |
108
- |---------------|-------------------|-----------|
109
- | Sign-in | 10/min per IP | Prevent credential stuffing |
110
- | Device codes | 5/min per IP | Prevent device code enumeration |
111
- | Token exchange | 10/min per IP | Prevent token brute-force |
112
- | Polling | 30/min per IP | Allow reasonable polling (every 2s) |
113
- | General API | 100/min per IP | Balance abuse prevention and usability |
101
+ ### Counter storage
102
+
103
+ Better Auth's own default keeps the counters in **process memory**. On
104
+ Cloudflare Workers that memory is per-isolate and per-colo, so counters reset
105
+ constantly and are bypassed by spreading requests across edges — an in-memory
106
+ limiter is decorative on the target runtime. The compiler therefore defaults
107
+ `rateLimit.storage` to **`"database"`** on Cloudflare: counters live in the auth
108
+ database (Better Auth adds a `rateLimit` table through the normal schema
109
+ generation, so a recompile produces the migration). On bun / node — one
110
+ long-lived process — the default is `"memory"`.
111
+
112
+ | `storage` | Where counters live | Use when |
113
+ |-----------|---------------------|----------|
114
+ | `"database"` | Auth database (`rateLimit` table) | Cloudflare Workers (default there) |
115
+ | `"memory"` | Process memory | Single long-lived process (bun / node default) |
116
+
117
+ ### Built-in rules for every credential door
118
+
119
+ The compiler always emits a per-route rule for **every** credential endpoint
120
+ Better Auth mounts — not just password sign-in — so an OTP verify door (a
121
+ 6-digit, 10<sup>6</sup>-space code) is never left under the 100/min general
122
+ limit. Your `customRules` **merge on top**: declare a path to change its limit,
123
+ or add paths for project plugins.
124
+
125
+ | Route(s) | Default | Reasoning |
126
+ |----------|---------|-----------|
127
+ | `/sign-in/email`, `/sign-in/username`, `/sign-in/social`, `/sign-in/anonymous` | 10/min per IP | Credential stuffing |
128
+ | `/sign-up/email` | 5/min per IP | Account-creation abuse |
129
+ | `/forget-password`, `/request-password-reset`, `/reset-password` | 5/min per IP | Reset-token brute force, mail bombing |
130
+ | `/sign-in/email-otp`, `/email-otp/send-verification-otp`, `/email-otp/verify-email`, `/email-otp/check-verification-otp`, `/email-otp/reset-password`, `/email-otp/request-password-reset` | 5/min per IP | OTP brute force + mail bombing |
131
+ | `/send-verification-email`, `/verify-email`, `/sign-in/magic-link`, `/magic-link/verify` | 5–10/min per IP | Link/token brute force |
132
+ | `/phone-number/send-otp`, `/phone-number/verify`, `/phone-number/request-password-reset`, `/phone-number/reset-password` | 5/min per IP | SMS OTP brute force + SMS cost |
133
+ | `/two-factor/send-otp`, `/two-factor/verify-otp`, `/two-factor/verify-totp`, `/two-factor/verify-backup-code` | 5/min per IP | Second-factor brute force |
134
+ | `/device/init` / `/device/poll` / `/device/token` | 5 / 30 / 10 per min per IP | Device-code enumeration, polling, token exchange |
135
+ | Everything else under `/auth/v1` | `max` (100/min per IP) | General abuse prevention |
136
+
137
+ Set an edge rate-limit binding as well for defence in depth
138
+ ([`rateLimit`](/define/rate-limit)) — the two layers are independent.
114
139
 
115
140
  ### Why Per-IP?
116
141
 
@@ -184,6 +184,14 @@ Events can target a specific user lane. Only that user receives the broadcast
184
184
 
185
185
  Each WebSocket connection is attached to exactly one resolved scope: `scopeKey`, `organizationId`, or `userId`. Users can only subscribe to the scope stamped into their ws ticket, enforced during authentication and ticket minting.
186
186
 
187
+ There is **no shared fallback room**. A signed-in caller with no active
188
+ organization (a self-registered account, an attendee-only account, external
189
+ crew) gets a non-scoped ticket bound to their **own user room**
190
+ (`user-<userId>`), so the only frames it can ever receive are ones addressed to
191
+ that user. Emits from a request with no `ctx.activeOrgId` and no resource scope
192
+ are skipped rather than delivered somewhere every org-less subscriber could
193
+ read, and a broadcast target that names no room is refused.
194
+
187
195
  ## Reconnection
188
196
 
189
197
  WebSocket connections can drop due to network issues. Implement reconnection logic in your client — note that you need to fetch a fresh ticket on each reconnect since tickets expire after 60 seconds:
@@ -290,7 +290,7 @@ curl -X POST https://api.example.com/storage/v1/presign/videos/clip.mp4 \
290
290
  # "key": "org_abc/videos/clip.mp4",
291
291
  # "uploadUrl": "https://<account>.r2.cloudflarestorage.com/...&X-Amz-Signature=...",
292
292
  # "method": "PUT",
293
- # "headers": { "Content-Type": "video/mp4" },
293
+ # "headers": { "Content-Length": "73400320", "Content-Type": "video/mp4" },
294
294
  # "expiresAt": "2026-06-02T12:10:00.000Z"
295
295
  # }
296
296
 
@@ -302,9 +302,11 @@ curl -X POST https://api.example.com/storage/v1/confirm/videos/clip.mp4 \
302
302
  -H "Authorization: Bearer <token>"
303
303
  ```
304
304
 
305
- > If `contentType` is supplied at step 1 it is **bound into the signature** — the
306
- > client MUST send exactly that `Content-Type` header on the PUT, or R2 rejects
307
- > it. Omit it to let the client send any type.
305
+ > The `size` and `contentType` from step 1 are **bound into the signature** as
306
+ > `Content-Length` and `Content-Type` — the client MUST replay the returned
307
+ > `headers` verbatim on the PUT, or R2 rejects it. That is what makes
308
+ > `maxFileSize` and `allowedTypes` real limits on the object that lands, not
309
+ > just on the request that asked for a URL.
308
310
 
309
311
 
310
312
  ### Required secrets
@@ -336,13 +338,14 @@ export default defineAction({
336
338
  description: 'Issue a presigned R2 upload URL for a media file on an event.',
337
339
  path: '/event/:eventId/media/sign-upload',
338
340
  method: 'POST',
339
- input: z.object({ filename: z.string(), contentType: z.string() }),
341
+ input: z.object({ filename: z.string(), contentType: z.string(), size: z.number().int().nonnegative() }),
340
342
  access: { roles: ['admin', 'member', 'scope:event:attendee'] },
341
343
  async execute({ input, ctx, db, storage }) {
342
344
  // Tenant-scoped key — secure by construction
343
345
  const key = `org/${ctx.activeOrgId}/event/${input.eventId}/${crypto.randomUUID()}-${input.filename}`;
344
346
  const upload = await storage.signPutUrl(key, {
345
347
  contentType: input.contentType,
348
+ contentLength: input.size,
346
349
  expiresIn: 600,
347
350
  });
348
351
  await db.insert(images).values({ key, eventId: input.eventId /* … */ });
@@ -355,7 +358,7 @@ export default defineAction({
355
358
 
356
359
  | Method | Returns | Use |
357
360
  |--------|---------|-----|
358
- | `signPutUrl(key, { contentType?, expiresIn? })` | `{ url, method, headers, key, expiresAt }` | Client uploads directly to R2 |
361
+ | `signPutUrl(key, { contentLength, contentType?, expiresIn? })` | `{ url, method, headers, key, expiresAt }` | Client uploads directly to R2 — size (and type) are signed and checked against `maxFileSize` / `allowedTypes` |
359
362
  | `signGetUrl(key, { expiresIn?, downloadFilename? })` | `string` | Client downloads directly from R2 |
360
363
 
361
364
  This is the supported replacement for streaming a raw binary body through an
@@ -92,11 +92,15 @@ export default defineAction({
92
92
  description: "Sign a direct-to-R2 upload URL and record the object key on the media row.",
93
93
  path: "/media/sign-upload",
94
94
  method: "POST",
95
- input: z.object({ filename: z.string(), contentType: z.string() }),
95
+ input: z.object({ filename: z.string(), contentType: z.string(), size: z.number().int().nonnegative() }),
96
96
  access: { roles: ["member"] },
97
97
  async execute({ input, ctx, db, storage }) {
98
98
  const key = `org/${ctx.activeOrgId}/${crypto.randomUUID()}-${input.filename}`;
99
- const upload = await storage.signPutUrl(key, { contentType: input.contentType, expiresIn: 600 });
99
+ const upload = await storage.signPutUrl(key, {
100
+ contentType: input.contentType, // bound into the signature
101
+ contentLength: input.size, // required — bound into the signature, checked against maxFileSize
102
+ expiresIn: 600,
103
+ });
100
104
  await db.insert(media).values({ key /* … */ });
101
105
  return { uploadUrl: upload.url, key, headers: upload.headers };
102
106
  },
@@ -107,17 +111,28 @@ export default defineAction({
107
111
  # 1. Ask your action for a signed URL (your auth/roles run here)
108
112
  curl -X POST https://api.example.com/api/v1/media/sign-upload \
109
113
  -H "Authorization: Bearer <token>" -H "Content-Type: application/json" \
110
- -d '{ "filename": "report.pdf", "contentType": "application/pdf" }'
111
- # → { "uploadUrl": "https://<account>.r2.cloudflarestorage.com/...&X-Amz-Signature=...", "key": "...", "headers": { "Content-Type": "application/pdf" } }
114
+ -d '{ "filename": "report.pdf", "contentType": "application/pdf", "size": 48213 }'
115
+ # → { "uploadUrl": "https://<account>.r2.cloudflarestorage.com/...&X-Amz-Signature=...", "key": "...", "headers": { "Content-Length": "48213", "Content-Type": "application/pdf" } }
112
116
 
113
117
  # 2. Upload the bytes straight to R2 (replay the returned headers verbatim)
114
118
  curl -X PUT "<uploadUrl>" -H "Content-Type: application/pdf" --data-binary @report.pdf
115
119
  ```
116
120
 
117
- `storage.signPutUrl(key, { contentType?, expiresIn?, bucket? })` returns
118
- `{ url, method, headers, key, expiresAt }`; `storage.signGetUrl(key, { expiresIn?, downloadFilename?, bucket? })`
119
- returns a presigned GET URL. Pass `bucket` to target a bucket other than the
120
- configured default.
121
+ `storage.signPutUrl(key, { contentLength, contentType?, expiresIn?, bucket? })`
122
+ returns `{ url, method, headers, key, expiresAt }`;
123
+ `storage.signGetUrl(key, { expiresIn?, downloadFilename?, bucket? })` returns a
124
+ presigned GET URL. Pass `bucket` to target a bucket other than the configured
125
+ default.
126
+
127
+ **The size and type are signed, and the declared limits are enforced.**
128
+ `contentLength` is required: it is checked against `fileStorage.maxFileSize`
129
+ (the presign is refused above it) and bound into the signature as the
130
+ `Content-Length` header, so the URL cannot upload a different size than the
131
+ action approved. `contentType` is bound the same way, and when the project
132
+ declares `fileStorage.allowedTypes` it is required and must be on the list. A
133
+ PUT that does not replay the returned `headers` verbatim is rejected by R2. A
134
+ project that declares neither limit gets no ceiling and no allowlist — the
135
+ signature is still size-bound.
121
136
 
122
137
  Presigning needs an R2 API token — set the `R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID`,
123
138
  and `R2_SECRET_ACCESS_KEY` secrets. A [browser deploy](/start/deploy-browser)
@@ -45,7 +45,9 @@ These run on `/auth/v1/admin/*`, emitted by Quickback because Better Auth's orga
45
45
 
46
46
  The admin panel is restricted to platform roles on the Better Auth user record: **`appmanager`** (the control plane) and **`sysadmin`** (which adds cross-tenant data access on top). Everyone else is redirected away from `/admin`.
47
47
 
48
- > **`role: "admin"` is not a platform role.** The compiler seeds the admin plugin with `adminRoles: ["appmanager", "sysadmin"]`, so a user set to `"admin"` passed the UI guard and then got `403` from every admin API call — an operator who looked promoted and could not act. Removed in v0.62; migrate those rows to `"appmanager"`.
48
+ > **`role: "admin"` is not a platform role.** By default the compiler seeds the admin plugin with `adminRoles: ["appmanager", "sysadmin"]`, so a user set to `"admin"` passed the UI guard and then got `403` from every admin API call — an operator who looked promoted and could not act. Removed in v0.62; migrate those rows to `"appmanager"`.
49
+ >
50
+ > A project that declares `plugins: { admin: { adminRoles, roles } }` gets **exactly** that: the declared `adminRoles` list and role → access-controller map are emitted verbatim (`appmanager: userAc` narrows the provisioning operator to no admin API at all; `adminRoles: ["sysadmin"]` keeps set-role / impersonate / ban for `sysadmin` only). The compiler never re-widens a declared role, and refuses a declaration it cannot honour.
49
51
 
50
52
 
51
53
  To grant operator access to a user: