@quickback-dev/cli 0.66.2 → 0.66.4

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 (84) hide show
  1. package/dist/commands/build.d.ts.map +1 -1
  2. package/dist/commands/build.js +11 -0
  3. package/dist/commands/build.js.map +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/skill/docs/api/actions.md +27 -3
  6. package/dist/skill/docs/api/batch-operations.md +4 -0
  7. package/dist/skill/docs/api/crud.md +57 -0
  8. package/dist/skill/docs/api/errors.md +1 -1
  9. package/dist/skill/docs/api/openapi.md +26 -6
  10. package/dist/skill/docs/api/query-params.md +19 -2
  11. package/dist/skill/docs/changelog/index.md +28 -0
  12. package/dist/skill/docs/configure/agents.md +2 -2
  13. package/dist/skill/docs/configure/auth.md +13 -0
  14. package/dist/skill/docs/configure/providers.md +2 -0
  15. package/dist/skill/docs/define/actions/defining.md +4 -1
  16. package/dist/skill/docs/define/firewall.md +1 -0
  17. package/dist/skill/docs/define/guards.md +7 -0
  18. package/dist/skill/docs/define/schema.md +5 -3
  19. package/dist/skill/docs/define/scopes.md +32 -0
  20. package/dist/skill/docs/platform/api-contract/index.md +36 -1
  21. package/dist/skill/docs/platform/auth/security.md +40 -15
  22. package/dist/skill/docs/platform/realtime/using-realtime.md +8 -0
  23. package/dist/skill/docs/platform/storage/r2.md +9 -6
  24. package/dist/skill/docs/platform/storage/using-r2.md +23 -8
  25. package/dist/skill/docs/tooling/cli.md +22 -6
  26. package/dist/skill/docs/tooling/output.md +9 -0
  27. package/dist/skill/docs/ui/account/features/admin.md +3 -1
  28. package/package.json +1 -1
  29. package/src/skill/docs/api/actions.md +27 -3
  30. package/src/skill/docs/api/batch-operations.md +4 -0
  31. package/src/skill/docs/api/crud.md +57 -0
  32. package/src/skill/docs/api/errors.md +1 -1
  33. package/src/skill/docs/api/openapi.md +26 -6
  34. package/src/skill/docs/api/query-params.md +19 -2
  35. package/src/skill/docs/changelog/index.md +28 -0
  36. package/src/skill/docs/configure/agents.md +2 -2
  37. package/src/skill/docs/configure/auth.md +13 -0
  38. package/src/skill/docs/configure/providers.md +2 -0
  39. package/src/skill/docs/define/actions/defining.md +4 -1
  40. package/src/skill/docs/define/firewall.md +1 -0
  41. package/src/skill/docs/define/guards.md +7 -0
  42. package/src/skill/docs/define/schema.md +5 -3
  43. package/src/skill/docs/define/scopes.md +32 -0
  44. package/src/skill/docs/platform/api-contract/index.md +36 -1
  45. package/src/skill/docs/platform/auth/security.md +40 -15
  46. package/src/skill/docs/platform/realtime/using-realtime.md +8 -0
  47. package/src/skill/docs/platform/storage/r2.md +9 -6
  48. package/src/skill/docs/platform/storage/using-r2.md +23 -8
  49. package/src/skill/docs/tooling/cli.md +22 -6
  50. package/src/skill/docs/tooling/output.md +9 -0
  51. package/src/skill/docs/ui/account/features/admin.md +3 -1
  52. package/dist/codex/AGENTS.md +0 -290
  53. package/dist/commands/codex.d.ts +0 -16
  54. package/dist/commands/codex.d.ts.map +0 -1
  55. package/dist/commands/codex.js +0 -159
  56. package/dist/commands/codex.js.map +0 -1
  57. package/dist/commands/compile.d.ts +0 -62
  58. package/dist/commands/compile.d.ts.map +0 -1
  59. package/dist/commands/compile.js +0 -830
  60. package/dist/commands/compile.js.map +0 -1
  61. package/dist/commands/compile.test.d.ts +0 -2
  62. package/dist/commands/compile.test.d.ts.map +0 -1
  63. package/dist/commands/compile.test.js +0 -150
  64. package/dist/commands/compile.test.js.map +0 -1
  65. package/dist/commands/init.d.ts +0 -6
  66. package/dist/commands/init.d.ts.map +0 -1
  67. package/dist/commands/init.js +0 -405
  68. package/dist/commands/init.js.map +0 -1
  69. package/dist/docs/content.d.ts +0 -7
  70. package/dist/docs/content.d.ts.map +0 -1
  71. package/dist/docs/content.js +0 -672
  72. package/dist/docs/content.js.map +0 -1
  73. package/dist/lib/helpers.d.ts +0 -39
  74. package/dist/lib/helpers.d.ts.map +0 -1
  75. package/dist/lib/helpers.js +0 -299
  76. package/dist/lib/helpers.js.map +0 -1
  77. package/dist/lib/sweep-stale.d.ts +0 -25
  78. package/dist/lib/sweep-stale.d.ts.map +0 -1
  79. package/dist/lib/sweep-stale.js +0 -179
  80. package/dist/lib/sweep-stale.js.map +0 -1
  81. package/dist/lib/sweep-stale.test.d.ts +0 -2
  82. package/dist/lib/sweep-stale.test.d.ts.map +0 -1
  83. package/dist/lib/sweep-stale.test.js +0 -130
  84. package/dist/lib/sweep-stale.test.js.map +0 -1
@@ -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)
@@ -125,15 +125,31 @@ quickback check --watch # re-check on change (tsc --watch)
125
125
  ```
126
126
 
127
127
  Runs `tsc` over `quickback/tsconfig.json` — the config the compiler emits on
128
- every compile, which typechecks the tree you actually edit (actions, lib,
129
- table files) against the generated `.quickback/` typed helpers. No compile,
130
- no server: this is your editor's view of the source, on demand.
128
+ every compile, which typechecks the tree you actually edit against two
129
+ generated typing surfaces:
130
+
131
+ - **Action typing** — the per-feature `.quickback/define-action` helpers:
132
+ `record`, `ctx`, `input`, and the scoped `db` typed against your tables.
133
+ - **Definition typing** — `quickback/.quickback/compiler/`, a
134
+ declaration-file snapshot of the compiler's real `@quickback/compiler`
135
+ surface. `import { feature, q, defineTable, defineConfig } from
136
+ "@quickback/compiler"` resolves in table files and `quickback.config.ts`,
137
+ so a bad builder call or an unknown resource-config key is a type error at
138
+ the desk, not a compile-round-trip later.
139
+
140
+ No compile, no server: this is your editor's view of the source, on demand.
131
141
 
132
142
  Exit codes: `0` clean · `1` type errors · `2` setup missing. A fresh clone
133
143
  (or a project that has never compiled) exits `2` with a pointer at
134
- `quickback build`, which generates the tsconfig and helpers the check
135
- resolves against. Re-run `quickback build` after schema changes so the
136
- helpers track your tables.
144
+ `quickback build`, which generates the tsconfig, helpers, and compiler types
145
+ the check resolves against. Re-run `quickback build` after schema changes so
146
+ they track your tables.
147
+
148
+ Actions that still import a table from the authored feature file
149
+ (`import { tickets } from "../tickets"`) fail the check — the q-DSL feature
150
+ file has only a default export. Import the table from the typed helper
151
+ instead (`import { defineAction, tickets } from "../.quickback/define-action"`);
152
+ `quickback migrate helper-imports` rewrites the safe cases for you.
137
153
 
138
154
  ### Synchronize Managed Columns
139
155
 
@@ -44,6 +44,15 @@ src/
44
44
  ├── db.ts # Database instance middleware
45
45
  └── services.ts # Service injection middleware
46
46
 
47
+ # Authored-tree typing (regenerated on every compile, gitignored)
48
+ quickback/tsconfig.json # Typechecks the authored quickback/ tree (`quickback check`)
49
+ quickback/.quickback/
50
+ └── compiler/ # @quickback/compiler declaration snapshot — resolves
51
+ └── … # `import { feature, q, defineTable } from "@quickback/compiler"`
52
+ quickback/features/{feature}/
53
+ └── .quickback/
54
+ └── define-action.ts # Authored-tree twin of the typed helper below
55
+
47
56
  quickback/drizzle/
48
57
  ├── auth/ # Auth migrations (dual mode)
49
58
  │ ├── meta/
@@ -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:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quickback-dev/cli",
3
- "version": "0.66.2",
3
+ "version": "0.66.4",
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",
@@ -206,11 +206,35 @@ Raw SQL in action code is blocked by default at compile time. If you need it for
206
206
 
207
207
  Unsafe handlers often need to derive the tenant from somewhere other than the ambient request context — an inbound webhook reads it from a mailbox record, a cron job iterates over every organization, a background worker acts on behalf of a specific user. `unsafeDb.scopeTo({ organizationId?, userId?, teamId? })` returns a scoped db that applies the firewall with your explicit scope instead of `ctx`:
208
208
 
209
- ```typescript title="quickback/features/mail/actions/ingestInbound.ts"
210
- // Inbound mail webhook — PUBLIC + unsafe
209
+ ```typescript
210
+ // features/mail/mailboxes.ts
211
+ import { q } from "@quickback/compiler";
212
+
213
+ export const mailboxes = q.table("mailboxes", {
214
+ id: q.id(),
215
+ address: q.text().required(),
216
+ organizationId: q.text().required(),
217
+ });
218
+
219
+ // features/mail/messages.ts
220
+ import { q } from "@quickback/compiler";
221
+
222
+ export const messages = q.table("messages", {
223
+ id: q.id(),
224
+ mailboxId: q.text().required(),
225
+ body: q.text().required(),
226
+ organizationId: q.text().required(),
227
+ });
228
+
229
+ // features/mail/actions/ingestInbound.ts
230
+ // Inbound mail webhook — PUBLIC + unsafe. `mail` is a multi-table feature
231
+ // with no primary table, so its flat `.quickback/define-action` helper
232
+ // exports no tables — import them from their own table modules.
211
233
  import { z } from "zod";
212
234
  import { eq } from "drizzle-orm";
213
- import { defineAction, mailboxes, messages } from "../.quickback/define-action";
235
+ import { defineAction } from "../.quickback/define-action";
236
+ import { mailboxes } from "../mailboxes";
237
+ import { messages } from "../messages";
214
238
 
215
239
  export default defineAction({
216
240
  description: 'Ingest an inbound mail webhook.',
@@ -26,6 +26,10 @@ create: {
26
26
  POST /api/v1/{resource}/batch
27
27
  ```
28
28
 
29
+ With [`allowClientIds: true`](/api/crud#client-supplied-ids-optimistic-updates)
30
+ each record MAY carry a strategy-shaped `id`; records without one get
31
+ server-minted ids as usual.
32
+
29
33
  ### Request
30
34
 
31
35
  ```json
@@ -163,6 +163,62 @@ columns may be omitted or sent as `null`. An empty string is **not** a blank —
163
163
  `""` is validated like any other value (so it fails `q.url()`, `q.enum()`, and
164
164
  `q.int()`).
165
165
 
166
+ ### Client-supplied IDs (optimistic updates)
167
+
168
+ Set `allowClientIds: true` on the database config to let `POST /` and
169
+ `POST /batch` carry an **optional** `id`. The server inserts the supplied id;
170
+ omit it and the server mints one exactly as before. This is built for
171
+ optimistic updates — the client generates the id up front, renders
172
+ immediately, and every follow-up request can reference the record before the
173
+ `201` arrives.
174
+
175
+ {/* doc-compile: skip — config fragment */}
176
+ ```typescript
177
+ providers: {
178
+ database: defineDatabase("cloudflare-d1", {
179
+ generateId: "uuid",
180
+ allowClientIds: true,
181
+ }),
182
+ }
183
+ ```
184
+
185
+ ```
186
+ POST /jobs
187
+ Content-Type: application/json
188
+
189
+ {
190
+ "id": "550e8400-e29b-41d4-a716-446655440000",
191
+ "title": "Senior Engineer"
192
+ }
193
+ ```
194
+
195
+ The id must match the shape the active `generateId` strategy mints, so
196
+ client-generated and server-generated ids are indistinguishable in the table:
197
+
198
+ | `generateId` | Accepted shape | Client mints with |
199
+ |--------------|----------------|-------------------|
200
+ | `"uuid"` | UUID | `crypto.randomUUID()` |
201
+ | `"prefixed"` | `<prefix>_` + 32 hex chars (e.g. `job_550e8400…`) | `` `${prefix}_${crypto.randomUUID().replaceAll('-', '')}` `` |
202
+ | `"cuid"` | 24-char cuid2 | `createId()` from `@paralleldrive/cuid2` |
203
+ | `"nanoid"` | 21-char nanoid | `nanoid()` |
204
+ | `"short"` | 6 alphanumerics | matching `customAlphabet` call |
205
+
206
+ What breaks, and how:
207
+
208
+ - A malformed id is a `400 VALIDATION_ERROR` at the Zod boundary.
209
+ - An id that already exists is a `409` UNIQUE-constraint conflict — the row is
210
+ not touched. Retrying a create with the same id is therefore safe: the first
211
+ attempt wins, replays fail loudly. For retry-safety across *any* endpoint,
212
+ prefer the [`Idempotency-Key` header](/platform/api-contract#idempotency-key),
213
+ which replays the original response instead of erroring.
214
+ - The flag is ignored under `generateId: false` (ids are already
215
+ client-supplied and **required**) and under `"serial"` / numeric primary
216
+ keys (the database owns the id).
217
+
218
+ Guards do not apply to the id: it is compiler-managed, so it does not need to
219
+ appear in `guards.createable`. `PUT /:id` and `PATCH` are unchanged — the id
220
+ still comes from the URL, never the body.
221
+
166
222
  ### Response
167
223
 
168
224
  `201 Created`. The body is the **bare created record** — there is no `data`
@@ -187,6 +243,7 @@ wrapper:
187
243
  |--------|-------------|
188
244
  | `400` | Invalid field or missing required field |
189
245
  | `403` | User lacks permission to create records |
246
+ | `409` | Client-supplied `id` (with `allowClientIds: true`) already exists |
190
247
 
191
248
  ## Update Record
192
249
 
@@ -68,7 +68,7 @@ enough to triage or hand the response to an LLM agent without grepping logs:
68
68
  | `details` | object | Extension — layer-specific context (optional) |
69
69
  | `pointer` | string | Extension — first offending field for validation failures, e.g. `/stage` (optional) |
70
70
  | `hint` | string | Extension — actionable guidance for resolution (optional) |
71
- | `request` | object | Extension — method, URL, redacted body, and request ID. Auto-attached by the runtime so the error body is self-contained — bodies are capped at 4 KB and well-known sensitive keys (`password`, `token`, `secret`, `apiKey`, `otp`, `code`, `authorization`, …) are replaced with `"[REDACTED]"` |
71
+ | `request` | object | Extension — method, URL, redacted body, and request ID. Auto-attached by the runtime so the error body is self-contained — bodies are capped at 4 KB and well-known sensitive keys (`password`, `token`, `secret`, `apiKey`, `otp`, `code`, `authorization`, …) plus every credential field the compiler itself introduces (`sessionToken`, `eventSessionToken`, `scopeJwt`, `scopeToken`, `wsTicket`, `inviteToken`, `jwt`, `signature`, …) are replaced with `"[REDACTED]"` |
72
72
 
73
73
  The per-layer examples below are abbreviated to `detail` plus each layer's
74
74
  extension members — every real response also carries `type`, `title`,
@@ -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
 
@@ -241,9 +241,26 @@ This request:
241
241
  A resource can allowlist FK columns for **FK-graph embedding**, collapsing
242
242
  client-side N+1 fetches:
243
243
 
244
- ```ts title="quickback/features/orders/order-items.ts"
244
+ ```ts
245
+ // features/orders/orders.ts
245
246
  import { feature, q } from "@quickback/compiler";
246
- import { orders } from "../orders/orders";
247
+
248
+ export default feature("orders", {
249
+ columns: {
250
+ id: q.id(),
251
+ total: q.int().required(),
252
+ organizationId: q.scope("organization"),
253
+ ...q.audit(),
254
+ ...q.softDelete(),
255
+ },
256
+ // include is a read of the TARGET resource — embedding orders rows
257
+ // requires orders to declare its own read gate (fail-closed).
258
+ read: { access: { roles: ["member", "admin"] } },
259
+ });
260
+
261
+ // features/orders/order-items.ts
262
+ import { feature, q } from "@quickback/compiler";
263
+ import orders from "./orders";
247
264
 
248
265
  export default feature("orderItems", {
249
266
  columns: {
@@ -8,6 +8,20 @@ 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 — tenant binding and credential hygiene
12
+
13
+ Fixes from the attend-vip API security review. All are compiler changes;
14
+ recompile to pick them up.
15
+
16
+ - **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).
17
+ - **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.
18
+ - **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).
19
+ - **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).
20
+ - **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`, …).
21
+ - **`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).
22
+ - **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.
23
+ - **`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).
24
+
11
25
  ## Unreleased — the standard API shape
12
26
 
13
27
  ### BREAKING: `contract.version` is retired
@@ -94,6 +108,20 @@ the broadcast URL. They match on `qbframe`, read `data` / `qbseq`, and take
94
108
  `/broadcast/v1` or `/broadcast/v2` from the injected runtime config — the
95
109
  same prefixes the worker actually mounts.
96
110
 
111
+ ### `allowClientIds` — optional client-supplied ids on create
112
+
113
+ `providers.database.config.allowClientIds: true` lets `POST /` and
114
+ `POST /batch` carry an **optional** `id`, built for optimistic updates: the
115
+ client mints the id up front (`crypto.randomUUID()` under
116
+ `generateId: 'uuid'`), renders immediately, and the server inserts that id —
117
+ or mints one when it is omitted, exactly as before. The id is shape-locked at
118
+ the Zod boundary to the active `generateId` strategy's format (400 on
119
+ mismatch, 409 on collision), guards stay on (the id is compiler-managed and
120
+ exempt from `createable`), and OpenAPI `<R>Create` schemas plus the client
121
+ `Insert` types advertise it as optional. A no-op under `generateId: false`
122
+ (ids stay client-supplied and **required**) and `'serial'` / numeric PKs.
123
+ See [Client-supplied IDs](/api/crud#client-supplied-ids-optimistic-updates).
124
+
97
125
  ## v0.65.x — August 16, 2026
98
126
 
99
127
  ### Passkeys no longer silently degrade to `rpID: 'localhost'`
@@ -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
 
@@ -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'`