@quickback-dev/cli 0.67.4 → 0.69.0

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 (47) hide show
  1. package/dist/commands/login.d.ts +10 -3
  2. package/dist/commands/login.d.ts.map +1 -1
  3. package/dist/commands/login.js +20 -9
  4. package/dist/commands/login.js.map +1 -1
  5. package/dist/index.js +1 -1
  6. package/dist/lib/action-harvest.d.ts.map +1 -1
  7. package/dist/lib/action-harvest.js +9 -2
  8. package/dist/lib/action-harvest.js.map +1 -1
  9. package/dist/lib/auth.d.ts +2 -1
  10. package/dist/lib/auth.d.ts.map +1 -1
  11. package/dist/lib/auth.js +2 -1
  12. package/dist/lib/auth.js.map +1 -1
  13. package/dist/skill/docs/api/actions.md +2 -0
  14. package/dist/skill/docs/api/batch-operations.md +19 -4
  15. package/dist/skill/docs/api/errors.md +36 -2
  16. package/dist/skill/docs/configure/providers.md +5 -2
  17. package/dist/skill/docs/define/access.md +2 -0
  18. package/dist/skill/docs/define/actions/scoped-db.md +14 -13
  19. package/dist/skill/docs/define/firewall.md +2 -1
  20. package/dist/skill/docs/define/triggers.md +36 -3
  21. package/dist/skill/docs/platform/auth/device-auth.md +16 -1
  22. package/dist/skill/docs/platform/auth/security.md +2 -0
  23. package/dist/skill/docs/platform/database/neon.md +52 -10
  24. package/dist/skill/docs/platform/database/planetscale-postgres.md +27 -0
  25. package/dist/skill/docs/platform/database/using-d1.md +32 -0
  26. package/dist/skill/docs/tooling/cli.md +6 -3
  27. package/dist/skill/docs/tooling/output.md +3 -1
  28. package/dist/skill/docs/tooling/troubleshooting.md +37 -0
  29. package/dist/skill/docs/ui/account/features/admin.md +9 -0
  30. package/package.json +1 -1
  31. package/src/skill/docs/api/actions.md +2 -0
  32. package/src/skill/docs/api/batch-operations.md +19 -4
  33. package/src/skill/docs/api/errors.md +36 -2
  34. package/src/skill/docs/configure/providers.md +5 -2
  35. package/src/skill/docs/define/access.md +2 -0
  36. package/src/skill/docs/define/actions/scoped-db.md +14 -13
  37. package/src/skill/docs/define/firewall.md +2 -1
  38. package/src/skill/docs/define/triggers.md +36 -3
  39. package/src/skill/docs/platform/auth/device-auth.md +16 -1
  40. package/src/skill/docs/platform/auth/security.md +2 -0
  41. package/src/skill/docs/platform/database/neon.md +52 -10
  42. package/src/skill/docs/platform/database/planetscale-postgres.md +27 -0
  43. package/src/skill/docs/platform/database/using-d1.md +32 -0
  44. package/src/skill/docs/tooling/cli.md +6 -3
  45. package/src/skill/docs/tooling/output.md +3 -1
  46. package/src/skill/docs/tooling/troubleshooting.md +37 -0
  47. package/src/skill/docs/ui/account/features/admin.md +9 -0
@@ -124,7 +124,8 @@ The body is inlined into `CREATE TRIGGER ... BEGIN <body> END`.
124
124
  - Bare `CASE ... END` expressions, including nested cases, are supported.
125
125
  For example: `SELECT CASE WHEN NEW.total < 0 THEN RAISE(ABORT, 'invalid total') END;`.
126
126
  That `END` closes the expression.
127
- - To reject a write: `SELECT RAISE(ABORT, 'message');`
127
+ - To reject a write: `SELECT RAISE(ABORT, 'message');` — prefix the message
128
+ to choose the [response status](#rejection-status).
128
129
  - SQL triggers are the only transactional option on D1, which has no
129
130
  `db.transaction()`.
130
131
 
@@ -170,7 +171,8 @@ VALUES (NEW."id" || ':ins', NEW."id", NEW."organization_id", auth.user_id());`,
170
171
  - `IF … END IF`, `LOOP … END LOOP` and nested `BEGIN … END` blocks are
171
172
  ordinary statements here and are accepted.
172
173
  - To reject a write: `RAISE EXCEPTION 'message';` (SQLSTATE `P0001`). The
173
- whole statement rolls back.
174
+ whole statement rolls back. Prefix the message to choose the
175
+ [response status](#rejection-status).
174
176
  - Functions are **`SECURITY INVOKER`** and run with a pinned
175
177
  `search_path = "app", public, pg_catalog`. That is the security contract:
176
178
  a cross-table write from your trigger is still subject to RLS and grants,
@@ -187,6 +189,33 @@ VALUES (NEW."id" || ':ins', NEW."id", NEW."organization_id", auth.user_id());`,
187
189
  suffix, so two long trigger names that differ only past the cut stay
188
190
  distinct instead of silently truncating onto each other.
189
191
 
192
+ ### Rejection status
193
+
194
+ A `sql:` rejection reaches the API as a database error. To answer the client
195
+ with a 4xx instead of a 500, **start** the message with a documented prefix
196
+ and a code of uppercase letters, digits and underscores:
197
+
198
+ | Message | Response |
199
+ |---|---|
200
+ | `QB_TRIGGER_REJECTED:<CODE>: <message>` | 422 `TRIGGER_REJECTED` |
201
+ | `QB_TRIGGER_FORBIDDEN:<CODE>: <message>` | 403 `TRIGGER_REJECTED` |
202
+ | anything else | 500 — the write path's ordinary failure (`DB_*_FAILED`, or `ACTION_EXECUTION_FAILED` in an action) |
203
+
204
+ ```sql
205
+ -- D1
206
+ SELECT RAISE(ABORT, 'QB_TRIGGER_FORBIDDEN:GUEST_CROSS_TENANT: event belongs to another organization');
207
+ -- Postgres
208
+ RAISE EXCEPTION 'QB_TRIGGER_REJECTED:EMAIL_LOCKED: email is fixed once linked';
209
+ ```
210
+
211
+ `<CODE>` lands in `details.code` and `<message>` is the response's error text,
212
+ so put nothing in either that the caller may not see. The mapping applies on
213
+ every write path: CRUD routes, batch, actions, changesets and the SEALED
214
+ routes. Use
215
+ `FORBIDDEN` for authorization refusals such as cross-tenant references, and
216
+ `REJECTED` for data rules. An unprefixed `RAISE` cannot be told apart from
217
+ any other driver failure, so it stays a 500.
218
+
190
219
  ### Soft-delete mapping
191
220
 
192
221
  On soft-delete tables (the default), `*Delete` events map to the
@@ -237,7 +266,8 @@ an [action](/define/actions/scoped-db#reaching-better-auth-tables-authdb).
237
266
 
238
267
  - **`before*` hooks are synchronous.** Return a partial object to merge
239
268
  into the write payload, or throw to reject — the write never executes and
240
- the request gets a structured `TRIGGER_REJECTED` (422) error. Audit
269
+ the request gets a structured `TRIGGER_REJECTED` (422) error on every
270
+ write path (CRUD, batch, actions, changesets). Audit
241
271
  fields (`createdBy`, `modifiedAt`, …) are re-stamped after hooks run and
242
272
  cannot be forged. A `before*` hook gets `values`, the pending write, and
243
273
  never the stored row: nothing is read before the write. Destructuring `row`
@@ -248,6 +278,9 @@ an [action](/define/actions/scoped-db#reaching-better-auth-tables-authdb).
248
278
  write's promise resolves. They may be `async`. A throw surfaces as
249
279
  `TRIGGER_AFTER_FAILED` (500) with `details.committed: true` — the row was
250
280
  already persisted (no transactions on D1), so clients must not blind-retry.
281
+ The hook's error message is logged; the response's error text is the
282
+ generic `After-trigger failed` unless the worker sets
283
+ [`EXPOSE_ERROR_STACK`](/api/errors#exposing-error-details-in-dev--staging).
251
284
  - Handlers must be **inline arrow/function expressions**. Imports they
252
285
  reference are hoisted into the generated registry (`src/lib/trigger-hooks.ts`)
253
286
  with relative paths rewritten from the table file — including dynamic
@@ -7,8 +7,23 @@ The Quickback CLI uses the [OAuth 2.0 Device Authorization Grant](https://datatr
7
7
  1. CLI requests a device code from the API
8
8
  2. User sees a code in the terminal (e.g., `AUL8-H93S`)
9
9
  3. User visits the approval URL and enters the code
10
- 4. CLI polls for approval and exchanges for a session token
10
+ 4. CLI polls `POST /auth/v1/device/token` until the code is approved; the response's `access_token` is a **signed** bearer token
11
+ 5. CLI calls `POST /cli/exchange` with that token to fetch user and session details
11
12
 
12
13
  This flow works in SSH sessions, containers, and WSL where browser redirects aren't possible.
13
14
 
15
+ ## Token signing
16
+
17
+ Better Auth's device-flow token endpoint creates a session and returns its raw session token. Quickback's generated auth config [requires signed bearer tokens](/platform/auth/security#requiresignature-true-is-the-secure-default), so a raw token would be unusable. When `deviceAuthorization` is enabled, the compiler emits an `after` hook on `/device/token` that signs `access_token` with `BETTER_AUTH_SECRET` before the response leaves Better Auth. The rest of the response (`token_type`, `expires_in`, `scope`) and the `Cache-Control: no-store` header are unchanged, and errors such as `authorization_pending` pass through as-is. The signing call comes from `better-call` (the same helper Better Auth's bearer plugin verifies with), so the generated `package.json` declares `better-call` at the exact version Better Auth depends on whenever `deviceAuthorization` is enabled.
18
+
19
+ The generated `POST /cli/exchange` route only **validates** a signed token. It doesn't sign anything:
20
+
21
+ | Request | Response |
22
+ |---------|----------|
23
+ | `Authorization: Bearer <signed token>` for a live session | `200` with `access_token` (the same signed token), `token_type`, `expires_in`, `session`, `user` |
24
+ | `Authorization: Bearer <unsigned token>` | `401 { "error": "invalid_token", "error_description": "A signed bearer token is required; the device-flow token endpoint already returns one." }` |
25
+ | Missing header, bad signature, or expired session | `401 invalid_token` |
26
+
27
+ `/cli/exchange` is reachable without authentication, so it must not sign tokens. If it did, anyone holding a raw session token from a database read, backup, or log could turn it into a working bearer token.
28
+
14
29
  See [CLI Reference](/tooling/cli#login) for usage details.
@@ -283,6 +283,7 @@ Quickback configures the Better Auth `bearer` plugin with `requireSignature: tru
283
283
  - The session token Better Auth emits via the `set-auth-token` response header is **signed server-side** with `BETTER_AUTH_SECRET`.
284
284
  - Unsigned bearer tokens are **rejected** at the plugin layer before any session lookup happens.
285
285
  - A session token leaked via a proxy access log, a browser dev-tools panel, or a misrouted `Referer` header **cannot** be replayed as a bearer token by an attacker — they would need the signing secret to forge a valid signature.
286
+ - With `deviceAuthorization` enabled, the device-flow token endpoint (`/device/token`) returns its session token **already signed**, and the generated `POST /cli/exchange` only validates signed tokens. No generated route signs a token a caller hands it (see [Device Authorization](/platform/auth/device-auth#token-signing)).
286
287
 
287
288
  Better Auth's own default for this option is `false`. Quickback overrides it on the secure side. JWT bearers and agent-auth bearers are independently signed and unaffected by this setting.
288
289
 
@@ -305,6 +306,7 @@ User-supplied options merge on top of the secure default, so any other [`bearer`
305
306
  | Threat | Mitigation |
306
307
  |--------|-----------|
307
308
  | Stolen session-token bearer replayed against the API | `requireSignature: true` blocks unsigned values |
309
+ | Raw session token (database read, backup, log) turned into a signed bearer by an endpoint that signs on request | `/device/token` signs at issue; `/cli/exchange` refuses unsigned tokens with 401 and never signs |
308
310
  | Browser extension injects a victim's session cookie into an attacker's bearer-authed API call | Cookie stripped when `Authorization` is present |
309
311
  | Multi-account user has cookies for two identities and uses bearer for the second | Bearer identity wins; no ambiguity in audit log |
310
312
  | MCP / agent flow exposed to ambient browser cookies | `/mcp` and agent-auth routes are bearer-only (cookies dropped entirely, see [Agent Auth](/platform/auth/plugins/agent-auth)) |
@@ -203,6 +203,9 @@ placeholder state.
203
203
  The environment contract is intentionally exact and fails closed:
204
204
 
205
205
  - `workersDev: true` and `previewUrls: false` must be explicit for each target.
206
+ - `worker.placement` (`{ mode }` or `{ region }`) sets that target's
207
+ [placement](/configure/providers#runtime-options); without it, the top-level
208
+ `providers.runtime.config.placement` is emitted for the target.
206
209
  - Each target declares its own `name` (the Wrangler worker name) and no two
207
210
  share one. It is the deployed script's identity — Durable Object state and
208
211
  the migration ledger belong to it — so it is never derived. An existing
@@ -339,8 +342,10 @@ connection string from the Hyperdrive configuration identified by `id`.
339
342
  > its unpooled URL for `DATABASE_MIGRATION_URL`), and `quickback` (the Worker
340
343
  > runtime role, the **only** deployed DB role — use its pooled URL for
341
344
  > `DATABASE_URL`). The first generated migration bootstraps these roles as
342
- > NOLOGIN; enable login and set passwords before use. Full walkthrough in the
343
- > generated `docs/neon-setup.md`.
345
+ > NOLOGIN; enable login and set passwords before use. It also gives `quickback`
346
+ > `statement_timeout`, `idle_in_transaction_session_timeout` and (PostgreSQL 17+)
347
+ > `transaction_timeout` — see [Worker-role timeouts](/platform/database/planetscale-postgres#worker-role-timeouts).
348
+ > Full walkthrough in the generated `docs/neon-setup.md`.
344
349
  >
345
350
  > Run the **first** `db:migrate` with your database owner credential (Neon's
346
351
  > `neondb_owner`) — that bootstrap run also grants `quickback_admin` everything
@@ -525,6 +530,11 @@ SELECT
525
530
  set_config('quickback.principal.claims', '{}', true);
526
531
  ```
527
532
 
533
+ On Hyperdrive the values are not bound parameters: each is hex-encoded and
534
+ decoded in SQL (`convert_from(decode('…', 'hex'), 'UTF8')`), so the preamble is
535
+ a single parameterless statement that shares a message with `BEGIN` and the SQL
536
+ text can never contain a claim value verbatim.
537
+
528
538
  RLS policies read those settings through Quickback-defined helper functions —
529
539
  there is no external JWT verification and no persisted session state in the
530
540
  database. `auth.user_id()` is a compiler-generated shim, not a Neon Authorize
@@ -560,6 +570,16 @@ masking. RLS exists so that a bug in a custom route, or a handle that escaped
560
570
  its scope, cannot cross a tenant, resurrect a soft-deleted row, or read another
561
571
  owner's row. It is the floor under the application, not a second application.
562
572
 
573
+ **Who RLS backstops.** The request database handle stamps caller claims only
574
+ for callers the policies can key on: a signed-in **account** (`ctx.userId`) and
575
+ a **delegated principal** (whose `databaseAccess` lane is enforced only here).
576
+ Every other caller — a `PUBLIC` door, a sessionless scope principal such as an
577
+ event pass — runs on the service lane, and the generated app firewall scopes
578
+ each of its queries, exactly as on D1. Without that, those callers would read
579
+ nothing: no policy recognises an anonymous or scope-only caller, so a pass
580
+ holder's namespace gate and a scope mint's relationship lookup both came back
581
+ empty.
582
+
563
583
  Quickback lowers your `firewall` config — and only your `firewall` config —
564
584
  into policies that read the transaction-local claims described above through
565
585
  `auth.user_id()`, `get_active_org_id()`, `get_active_team_id()`, `get_scope()`
@@ -940,7 +960,7 @@ stamps the active organization, and policies compare against that stamp.
940
960
  `is_admin()` is no part of that gate either. Enabling the admin plugin does
941
961
  **not** widen any scope policy: "admin" is a role, and a scope policy is the
942
962
  firewall predicate, full stop. An admin's cross-tenant read goes through the
943
- API on the service lane — an `unsafe: { crossTenant: true }` action stamps
963
+ API on the service lane — an `unsafe` action stamps
944
964
  `quickback.service_role`, which `<table>_service_role` admits — not by SQL
945
965
  re-deriving admin from `auth.admins`. Older databases carry the previous
946
966
  `(public.is_admin() OR (…))` form until the new security migration replaces
@@ -979,8 +999,8 @@ and existing counter rows are preserved.
979
999
 
980
1000
  ## Background jobs and cross-tenant actions
981
1001
 
982
- Some code runs with no HTTP request and therefore no caller claims: queue
983
- consumers, cron schedules, and cross-tenant `unsafe` actions. These acquire the
1002
+ Some code runs with no HTTP request and therefore no caller claims — queue
1003
+ consumers, cron schedules — and `unsafe` actions opt out of them. These acquire the
984
1004
  **service-role handle** `createServiceDb(env)` from the generated `src/db`
985
1005
  index. Instead of caller claims, it sets `quickback.service_role = 'true'` (with
986
1006
  all request claims cleared) — the same marker the Better Auth adapter's
@@ -990,7 +1010,9 @@ across tenants while the request-scoped `createDb()` client stays caller-scoped.
990
1010
 
991
1011
  The service-role marker is only ever set by Worker-internal chokepoints
992
1012
  (`createServiceDb`, the Better Auth adapter) — it is never derived from request
993
- input. Unsafe actions keep their mandatory audit contract: cross-tenant writes
1013
+ input. Every `unsafe` action gets this handle as `unsafeDb`, `crossTenant`
1014
+ or not, so it reads what it would read on D1 — RLS does not narrow it to the
1015
+ caller. Unsafe actions keep their mandatory audit contract: cross-tenant writes
994
1016
  still land audit events (the `audit` Postgres schema), unchanged from D1.
995
1017
 
996
1018
  ## Reads through a user-anchored relationship
@@ -1213,10 +1235,30 @@ providers: {
1213
1235
  ```
1214
1236
 
1215
1237
  The compiler emits the `[[hyperdrive]]` wrangler binding pointing at your Neon
1216
- **direct** connection string. Its request-scoped postgres.js client uses
1217
- `max: 5`, disables prepared statements, and skips type-fetch round trips — the
1218
- small client pool bounds origin connections per Worker isolate while
1219
- Hyperdrive owns the shared connection pool.
1238
+ **direct** connection string. Each Worker invocation (request, queue batch,
1239
+ cron, inbound email) opens **one** lease pool of up to five single-connection
1240
+ postgres.js clients, shared by every `createDb` / `createServiceDb` call in it
1241
+ — the request db, Better Auth, idempotency, the audit writer. Statements are
1242
+ **prepared** (Cloudflare's guidance for postgres.js on Hyperdrive, which caches
1243
+ named prepared statements; an unprepared statement costs an extra
1244
+ parameter-describe round trip) and type-fetch round trips are skipped;
1245
+ Hyperdrive owns the origin pool.
1246
+
1247
+ Every single statement runs as one **pipelined claims transaction** on a leased
1248
+ connection: `BEGIN` plus the claims preamble travel as one message, then the
1249
+ statement, then `COMMIT`, all written before anything is awaited. That is one
1250
+ round trip once the statement is prepared on that connection and three while it
1251
+ is cold — down from six. It fails closed by construction: a preamble that
1252
+ errors after `BEGIN` aborts the transaction so the statement is refused rather
1253
+ than run unscoped, and a failed statement turns the pipelined `COMMIT` into
1254
+ `ROLLBACK`.
1255
+
1256
+ The pool closes when the invocation ends, after its `waitUntil` work
1257
+ (deferred audit writes, after-commit effects) settles. A client that is never
1258
+ closed leaves its backends mid-transaction, holding Hyperdrive origin
1259
+ connections until Postgres times them out. Code outside an invocation — a
1260
+ Durable Object, a test — gets a fresh pool per `createDb` call and owns
1261
+ closing it.
1220
1262
 
1221
1263
  > Postgres authorizes `SELECT … FOR UPDATE` as both a read and a write: the row
1222
1264
  > must pass its `SELECT` **and** `UPDATE` policies. This matters for delegated
@@ -79,6 +79,23 @@ ALTER ROLE quickback_admin LOGIN PASSWORD '<strong-admin-password>';
79
79
  ALTER ROLE quickback LOGIN PASSWORD '<strong-password>';
80
80
  ```
81
81
 
82
+ ### Worker-role timeouts
83
+
84
+ The role bootstrap sets three timeouts on `quickback`, so a Worker invocation
85
+ that dies mid-transaction cannot hold a connection (and its locks) open:
86
+
87
+ | Setting | Value | Ends |
88
+ |---|---|---|
89
+ | `statement_timeout` | `30s` | a runaway statement |
90
+ | `idle_in_transaction_session_timeout` | `15s` | an open transaction the Worker stopped talking to |
91
+ | `transaction_timeout` | `60s` | any transaction older than that, including one stuck mid-statement waiting on the client — PostgreSQL 17+ only |
92
+
93
+ Each is set only when the role does not already carry it, so a value you set
94
+ with `ALTER ROLE quickback SET …` survives every later migration. Existing
95
+ databases get them from the next appended `quickback_rls` migration, applied
96
+ with the setup-owner credential. If the applying user cannot alter the role,
97
+ the migration skips them with a `NOTICE`; set them as the owner instead.
98
+
82
99
  ### SQL role vs connection username
83
100
 
84
101
  PlanetScale routes a connection to a branch by a suffix on the username. The
@@ -136,6 +153,10 @@ binding = "HYPERDRIVE"
136
153
  id = "ffffffffffffffffffffffffffffffff"
137
154
  ```
138
155
 
156
+ Each Worker invocation shares one postgres.js client across every database
157
+ handle it opens and closes it when the invocation ends — see
158
+ [Neon → Interactive transactions](/platform/database/neon#interactive-transactions) for the details.
159
+
139
160
  ## No `DATABASE_URL` Worker secret
140
161
 
141
162
  Feature queries and Better Auth both read `env.HYPERDRIVE.connectionString`.
@@ -164,6 +185,12 @@ carrying `localConnectionString`. Since every environment runs the same
164
185
  bundle, a target that shares another target's Hyperdrive id shares its
165
186
  database — the compiler requires each one to declare its own.
166
187
 
188
+ Set `providers.runtime.config.placement: { region: "aws:us-east-2" }` (your
189
+ branch's region) so the Worker runs next to the database — every statement is
190
+ several round-trips, so Worker-to-database distance dominates latency. A target
191
+ whose branch lives elsewhere overrides it with
192
+ `environments.<name>.worker.placement`.
193
+
167
194
  ## What is shared with Neon, and what is not
168
195
 
169
196
  Shared — read the Neon page for the detail, it is the same generated output:
@@ -33,6 +33,38 @@ Migrations are generated by the compiler using `drizzle-kit generate`. Apply the
33
33
  npx wrangler d1 migrations apply my-db
34
34
  ```
35
35
 
36
+ ## Backend stalls
37
+
38
+ D1 statements occasionally wait tens of seconds in Cloudflare's backend
39
+ queue (a noisy neighbour on the shared execution queue — not your workload),
40
+ and the D1 binding has no deadline or `AbortSignal` of its own. Because every
41
+ query runs through generated code, the deadline is a config option rather than
42
+ something you wrap by hand:
43
+
44
+ ```ts
45
+ database: defineDatabase("cloudflare-d1", {
46
+ queryTimeoutMs: 5000,
47
+ }),
48
+ ```
49
+
50
+ With it set, every D1 handle the compiler emits — the scoped `db`, the unsafe
51
+ `db`, the Better Auth adapter, cron / queue / email runners, the files and
52
+ audit databases — races each statement against the deadline:
53
+
54
+ | Statement | Response | Client should |
55
+ |-----------|----------|---------------|
56
+ | Read (`SELECT`, `WITH`, `EXPLAIN`, `PRAGMA`) | `503 DB_TIMEOUT` | Retry. The read had no side effects |
57
+ | Write (anything else, and any `batch` containing a write) | `500 DB_WRITE_OUTCOME_UNKNOWN` | Re-read the record, then decide. The statement was **not** cancelled on the backend and may still commit |
58
+
59
+ Each timeout also logs one structured line —
60
+ `{ level: "error", event: "DB_DEADLINE", binding, kind, ms, sql }` (SQL
61
+ truncated to 200 chars). Workers Logs indexes the JSON fields, so in the
62
+ dashboard or `wrangler tail --format json` filter on `event = "DB_DEADLINE"`
63
+ and group by `binding` / `kind` to track stalls over time. The response the
64
+ client saw carries the same `binding` in `details`. Unset, nothing changes: no wrapper is emitted and queries are
65
+ unbounded, as before. The option is D1-only; Postgres drivers carry their own
66
+ statement timeouts. `withSession()` handles pass through unbounded.
67
+
36
68
  ## Related
37
69
 
38
70
  - [D1 Setup](/platform/database/d1) — Bindings and wrangler config
@@ -312,9 +312,12 @@ Uses the [OAuth 2.0 Device Authorization Grant](https://datatracker.ietf.org/doc
312
312
  1. The CLI requests a one-time device code from the Quickback API.
313
313
  2. A code is displayed in your terminal (e.g., `AUL8-H93S`).
314
314
  3. Your browser opens to the Quickback account page where you approve the code.
315
- 4. The CLI detects approval and exchanges it for a session token.
316
- 5. If you belong to one organization, it's auto-selected. If you have multiple, you choose one.
317
- 6. Credentials are stored locally.
315
+ 4. The CLI detects approval: the API's device-flow token endpoint (`POST /auth/v1/device/token`) returns a **signed** bearer token.
316
+ 5. The CLI sends that token to `POST /cli/exchange`, which validates it and returns your user and session details.
317
+ 6. If you belong to one organization, it's auto-selected. If you have multiple, you choose one.
318
+ 7. Credentials are stored locally.
319
+
320
+ The token endpoint signs the session token before returning it, so the token the CLI receives already works as a bearer token. `/cli/exchange` only validates tokens that are already signed. It refuses an unsigned token with `401 invalid_token` and never signs one. A raw session token, for example one read from the database or a log, therefore can't be turned into a working bearer token. That is the protection the `bearer` plugin's `requireSignature: true` default provides (see [Auth security](/platform/auth/security#requiresignature-true-is-the-secure-default)).
318
321
 
319
322
  ```
320
323
  $ quickback login
@@ -454,9 +454,11 @@ When the `deviceAuthorization` plugin is enabled:
454
454
  ```
455
455
  src/
456
456
  └── routes/
457
- └── cli-auth.ts # Device auth flow endpoints
457
+ └── cli.ts # POST /cli/exchange (validates a signed device-flow token)
458
458
  ```
459
459
 
460
+ `src/lib/auth.ts` also gets an `after` hook that signs the `/device/token` response's `access_token`. See [Device Authorization](/platform/auth/device-auth#token-signing).
461
+
460
462
  ## Database Schemas
461
463
 
462
464
  ### Dual Database Mode (D1 default)
@@ -107,6 +107,43 @@ Quickback now adds a D1-specific safety pass around Drizzle-generated migrations
107
107
 
108
108
  If `quickback build` now fails with a D1 replay error, treat that as a real migration problem instead of a deploy-time surprise. The generated SQL needs manual intervention or a schema change that Drizzle can express more safely.
109
109
 
110
+ ### Postgres: column "…" cannot be cast automatically
111
+
112
+ On Postgres providers (`neon`, `planetscale-postgres`), Drizzle emits a column
113
+ type change as a bare `ALTER COLUMN … SET DATA TYPE`, which Postgres refuses
114
+ when no implicit cast exists — for example when the `text` audit columns of a
115
+ pre-0.68 journal become `timestamptz`. In a newly generated migration,
116
+ Quickback rewrites a change to a timestamp, date/time, numeric, boolean,
117
+ `uuid`, or `json`/`jsonb` type as `SET DATA TYPE <type> USING "<col>"::<type>`,
118
+ so existing rows convert in place. It drops the column's old default first when
119
+ the same migration sets or drops it afterwards; a default is never removed
120
+ otherwise.
121
+
122
+ Changes to length-limited types (`varchar(n)`, `char(n)`, `bit(n)`) and arrays
123
+ stay bare: an explicit cast would silently truncate values the bare statement
124
+ rejects. Add `USING` by hand if you need one there.
125
+
126
+ Existing migrations are never rewritten. If an earlier compiler generated a
127
+ type-change migration that fails with this error, it never applied — `npm run
128
+ db:migrate` runs pending migrations in one transaction, and a failure records
129
+ nothing in `drizzle.__drizzle_migrations`. Fix it in one of two ways:
130
+
131
+ - **It is the newest migration:** delete that `.sql` file, its
132
+ `meta/NNNN_snapshot.json`, and its `meta/_journal.json` entry, then rebuild
133
+ to regenerate it.
134
+ - **Later migrations follow it:** edit the failing statement in place before
135
+ applying it. Add `USING "<col>"::<type>` and, if the column has a default
136
+ that cannot be cast, a `DROP DEFAULT` statement before it:
137
+
138
+ ```sql
139
+ ALTER TABLE "app"."events" ALTER COLUMN "created_at" DROP DEFAULT;
140
+ --> statement-breakpoint
141
+ ALTER TABLE "app"."events" ALTER COLUMN "created_at" SET DATA TYPE timestamp with time zone USING "created_at"::timestamp with time zone;
142
+ ```
143
+
144
+ The drizzle migrator does not compare hashes of applied migrations, and a
145
+ recompile hands the edited file back unchanged.
146
+
110
147
  ### Recompile changed the comments at the top of an old migration
111
148
 
112
149
  A recompile hands every existing migration back byte-for-byte, including the
@@ -48,6 +48,15 @@ The admin panel is restricted to platform roles on the Better Auth user record:
48
48
  > **`role: "admin"` is not a platform role.** By default the compiler seeds the admin plugin with `adminRoles: ["appmanager", "sysadmin"]`. Migrate rows with `role: "admin"` to `"appmanager"`.
49
49
  >
50
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.
51
+ >
52
+ > **`adminRoles` order is ascending privilege, and it is a ceiling.** `adminRoles[i]` is tier `i + 1`; every other role (`user`, project-custom roles) is tier 0. With the defaults, `appmanager` is 1 and `sysadmin` is 2; a comma-separated `role` ranks at its highest member. Better Auth's admin plugin alone lets any role holding `user:set-role` grant any role that exists, so the generated `src/lib/auth.ts` adds a `hooks.before` role ceiling that returns `403 ROLE_CEILING` when:
53
+ >
54
+ > - `set-role`, `create-user` or `update-user` requests a role ranked above the caller's.
55
+ > - `set-role`, `update-user`, `ban-user`, `remove-user`, `set-user-password`, `revoke-user-session(s)` or `impersonate-user` targets a user ranked above the caller.
56
+ >
57
+ > Equal tier is allowed, so an appmanager can still make another appmanager (the example below). Only a `sysadmin` can grant `sysadmin`.
58
+ >
59
+ > `set-organization-member` refuses to seat its caller with `403 OPERATOR_SELF_SEAT`: operators are never seated by their own control-plane calls.
51
60
 
52
61
 
53
62
  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.67.4",
3
+ "version": "0.69.0",
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",
@@ -201,6 +201,8 @@ Cross-tenant unsafe actions are generated with:
201
201
 
202
202
  Without unsafe mode, `unsafeDb` is `undefined`.
203
203
 
204
+ On Postgres providers `unsafeDb` is the service-role handle for every unsafe action, so row-level security does not narrow it to the caller — the same reach as on D1. See the [provider note](/define/actions/scoped-db#unsafe-mode).
205
+
204
206
  Raw SQL in action code is blocked by default at compile time. If you need it for a specific action, set `allowRawSql: true` on that action explicitly.
205
207
 
206
208
  ### Explicit scope with `unsafeDb.scopeTo`
@@ -212,6 +212,15 @@ Note: Batch delete uses an `ids` array (not `records`).
212
212
 
213
213
  **Hard delete**: Returns objects with only the `id` field (record data is deleted).
214
214
 
215
+ If the bulk statement itself fails, the error is classified like every other
216
+ write — a constraint hit reports its `DB_*` code (for example
217
+ `DB_FOREIGN_KEY_VIOLATION`, 400), anything else `DB_DELETE_FAILED` (500); see
218
+ [Database errors](/api/errors#database). With `failFast: true` that
219
+ error is the response, at its own status. Otherwise it is repeated in `errors`
220
+ for every id that passed the existence and access checks, and the response is
221
+ `207`. The raw database message reaches `details.reason` only when
222
+ `EXPOSE_ERROR_STACK` is set.
223
+
215
224
  ## Batch Upsert
216
225
 
217
226
  ```
@@ -264,17 +273,23 @@ Set `"failFast": true` to stop on the first error:
264
273
 
265
274
  ```json
266
275
  {
267
- "error": "Batch failed at index 1",
276
+ "detail": "Batch stopped at first error (fail-fast mode)",
268
277
  "layer": "validation",
269
- "code": "BATCH_FAILFAST_STOPPED",
278
+ "code": "BATCH_FAIL_FAST_STOPPED",
270
279
  "details": {
271
280
  "failedAt": 1,
272
- "reason": "Database insert failed",
273
- "errorDetails": { "reason": "UNIQUE constraint failed" }
281
+ "applied": true,
282
+ "reason": "Duplicate value",
283
+ "errorDetails": { "column": "email", "columns": ["email"], "fields": { "email": "Already taken" } }
274
284
  }
275
285
  }
276
286
  ```
277
287
 
288
+ `details.reason` here is the failing record's error message, and
289
+ `details.errorDetails` its `details`. A database fallback
290
+ (`DB_INSERT_FAILED` / `DB_UPDATE_FAILED`) has no `details` unless
291
+ `EXPOSE_ERROR_STACK` is set — see [Errors](/api/errors#database).
292
+
278
293
  ## Transactional Semantics
279
294
 
280
295
  The behavior of `failFast: true` depends on whether your database provider —
@@ -19,7 +19,8 @@ The generated API returns structured error responses with consistent fields acro
19
19
  | `422` | Unprocessable | `Idempotency-Key` reused with a different request or principal, or a stored encrypted value will not decrypt (`ENCRYPTION_UNREADABLE`) |
20
20
  | `428` | Precondition Required | `If-Match` sent where it can't anchor: no revision column, a batch endpoint (single-resource precondition), or the POST changeset variant |
21
21
  | `429` | Too Many Requests | Rate limit exceeded |
22
- | `500` | Internal Error | Uncaught throw — generic body, full error server-side |
22
+ | `500` | Internal Error | Uncaught throw — generic body, full error server-side. Also `DB_WRITE_OUTCOME_UNKNOWN`: a write passed the configured [`queryTimeoutMs`](/configure/providers#database-options) and may still have committed |
23
+ | `503` | Service Unavailable | **Retryable.** `AUTH_REVOCATION_UNAVAILABLE`, or `DB_TIMEOUT` — a read passed the configured D1 deadline |
23
24
 
24
25
  ## Error Response Format — RFC 9457 Problem Details
25
26
 
@@ -324,10 +325,36 @@ form can show the conflict inline. `details.column` is the first of them.
324
325
  | `DB_RELATIONSHIP_MISMATCH` | 400 | A referenced row does not match the required parent column |
325
326
  | `DB_INSERT_FAILED` | 500 | INSERT failed for an unrecognized reason |
326
327
  | `DB_UPDATE_FAILED` | 500 | UPDATE failed for an unrecognized reason |
328
+ | `DB_DELETE_FAILED` | 500 | DELETE (or soft-delete UPDATE) failed for an unrecognized reason |
329
+ | `DB_TIMEOUT` | 503 | **Retryable.** A read passed [`queryTimeoutMs`](/configure/providers#database-options) (D1 only). The read had no side effects; retry. `details: { binding }` |
330
+ | `DB_WRITE_OUTCOME_UNKNOWN` | 500 | A write passed `queryTimeoutMs`. D1 does not cancel the statement, so it may still commit after the response. **Re-read the record before retrying** — a blind retry can double-apply. `details: { binding, outcome: 'unknown' }` |
327
331
  | `ENCRYPTION_UNREADABLE` | 422 | A stored [`.encrypted()`](/define/encryption) value will not decrypt |
332
+ | `TRIGGER_REJECTED` | 422 / 403 | A [before-trigger](/define/triggers#rejection-status) refused the write; nothing was persisted. `layer: "trigger"`, `details.code` for a prefixed `sql:` rejection |
328
333
 
329
334
  The `details.column` field is only present when the driver's error message identified the offending column (SQLite/D1 do; some PG variants don't).
330
335
 
336
+ The same classification applies to every write path — single-record create,
337
+ update, `PUT` and delete, the batch endpoints (including `DELETE /batch`, which
338
+ reports these `DB_*` codes per id, or as the `failFast` response), bulk
339
+ actions, and changesets.
340
+
341
+ `DB_INSERT_FAILED`, `DB_UPDATE_FAILED` and `DB_DELETE_FAILED` are the fallback
342
+ for a failure that matches no known constraint. The raw driver message (D1 or
343
+ Postgres text, which can name tables, columns, and SQL fragments) is always
344
+ logged with `console.error`, and the production body carries no `details`:
345
+
346
+ ```json
347
+ {
348
+ "detail": "Update failed",
349
+ "layer": "database",
350
+ "code": "DB_UPDATE_FAILED",
351
+ "hint": "Database rejected the update. Check server logs for the underlying error."
352
+ }
353
+ ```
354
+
355
+ The raw message appears as `details.reason` only when the worker runs with
356
+ [`EXPOSE_ERROR_STACK`](#exposing-error-details-in-dev--staging) set.
357
+
331
358
  `ENCRYPTION_UNREADABLE` always carries `details: { table, column, id }` — the
332
359
  row whose stored ciphertext is malformed, was not written under the caller's
333
360
  organization key, was copied from another column or table, or names a key
@@ -476,4 +503,11 @@ When set, the global 500 and `ACTION_EXECUTION_FAILED` bodies forward
476
503
  the underlying error message plus `details.cause` (cause-chain
477
504
  message), `details.frames` (top three stack frames with absolute paths
478
505
  sanitized to basename + line number), and `details.stack` (the full
479
- unsanitized stack trace). Leave it unset in production.
506
+ unsanitized stack trace). The same switch adds `details.reason` (the raw
507
+ error message) to the database fallbacks (`DB_INSERT_FAILED`,
508
+ `DB_UPDATE_FAILED`, `DB_DELETE_FAILED`), `ACCESS_AUDIT_LOG_FAILED`, the
509
+ `INTERNAL_ERROR` bodies of the auth handler and the operator `/admin/*`
510
+ routes, and uses the raw message as the `TRIGGER_AFTER_FAILED` error text.
511
+ Without it, none of those bodies carry anything derived from the thrown
512
+ error. `1` and `true` turn it on; any other value leaves it off. Leave it
513
+ unset in production.
@@ -19,7 +19,8 @@ providers: {
19
19
  | Option | Type | Description |
20
20
  |--------|------|-------------|
21
21
  | `compatibilityDate` | `string` | Emits Cloudflare `compatibility_date` in `wrangler.toml`. |
22
- | `placement.mode` | `"smart" \| "standard"` | Emits Cloudflare's `[placement]` block. |
22
+ | `placement.mode` | `"smart" \| "standard"` | Emits Cloudflare's `[placement]` block. Mutually exclusive with `placement.region`. |
23
+ | `placement.region` | `string` | Placement hint, `"<cloud>:<region>"` (e.g. `"aws:us-east-2"`): runs the Worker next to a single-region database instead of next to the user. Set it to your Postgres region. Any other `placement` key is a compile error. Named environments emit it per target; override with `environments.<name>.worker.placement`. |
23
24
  | `observability.enabled` | `boolean` | Emits top-level Workers Logs persistence under `[observability]`. |
24
25
  | `observability.headSamplingRate` | `number` | Top-level Workers Logs sample rate from `0` to `1`. |
25
26
  | `observability.logs.enabled` | `boolean` | Emits `[observability.logs]`. |
@@ -106,8 +107,9 @@ single Postgres database with no bindings or split mode (see
106
107
  | `allowClientIds` | `boolean` | `false` | Accept an optional client-supplied `id` on create, shaped like the `generateId` strategy — see [Client-supplied IDs](/api/crud#client-supplied-ids-optimistic-updates). Ignored under `generateId: false` (ids are already client-supplied and required) and `"serial"` / numeric PKs |
107
108
  | `validateIdParams` | `boolean` | `true` | Check a record route's `:id` against the table's id format and answer `400 INVALID_ID` before any database work — see [Malformed ids](/api/crud#malformed-ids-400-invalid_id). **Set `false` if any table holds rows whose ids don't match the current `generateId` shape** (the strategy changed after rows were written, imported data, ids hand-minted by actions): with the check on, those rows answer 400 instead of the row. Tables whose format the compiler can't know (`generateId: false`, an authored id default) are never checked |
108
109
  | `namingConvention` | `string` | `"snake_case"` | Column naming convention |
109
- | `usePlurals` | `boolean` | `false` | Pluralize auth table names (e.g. `user` vs `users`) |
110
+ | `usePlurals` | `boolean` | `false` (`true` on Neon / PlanetScale Postgres) | Pluralize auth table names (e.g. `user` vs `users`). The default differs by provider — porting a D1 project to Postgres, set `usePlurals: false` explicitly to keep its table names |
110
111
  | `splitDatabases` | `boolean` | `true` | Separate auth and features databases (D1 only) |
112
+ | `queryTimeoutMs` | `number` | — | Per-statement deadline for every D1 query the generated code runs (CRUD, actions, the auth adapter, cron/queue/email runners, files, audit). Unset = no deadline. D1 only — the Postgres drivers have their own timeout options. Past the deadline a read answers `503 DB_TIMEOUT` and a write `500 DB_WRITE_OUTCOME_UNKNOWN`; see [Backend stalls](/platform/database/using-d1#backend-stalls) and [Database errors](/api/errors#database-constraint-errors). The statement is **not** cancelled on the backend |
111
113
  | `authBinding` | `string` | `"AUTH_DB"` | Binding name for auth database |
112
114
  | `featuresBinding` | `string` | `"DB"` | Binding name for features database |
113
115
  | `databaseId` | `string` | — | D1 database ID for the features database (used in generated wrangler.toml) |
@@ -131,6 +133,7 @@ single Postgres database with no bindings or split mode (see
131
133
  | `hyperdrive.id` | `string` | — | Required Cloudflare Hyperdrive configuration ID when `connectionMode: "hyperdrive"` |
132
134
  | `hyperdrive.localConnectionString` | `string` | — | Optional local-only Postgres connection used by Wrangler dev |
133
135
  | `pooled` | `boolean` | `true` | Use the pooled Neon connection string (recommended for Workers) |
136
+ | `usePlurals` | `boolean` | `true` | Auth table names (`users`, `members`, …). **The D1 default is `false`** — a project moving from D1 must set `usePlurals: false` to keep `user`, `member`, … |
134
137
 
135
138
  The Worker connects through a single `DATABASE_URL` secret — auth and feature
136
139
  queries share it. See [Neon](/platform/database/neon) for
@@ -373,6 +373,8 @@ read: { access: { roles: ["SYSADMIN"] } }
373
373
 
374
374
  This separation exists so Better Auth admin-plugin powers (user management, impersonation, org creation) and DB-admin powers (cross-tenant data inspection) stay decoupled. A user can have `user.role === 'appmanager'` without DB-level cross-tenant access; a user can have `user.role === 'sysadmin'` without org-membership context. See [CMS Configuration](/configure#cms-configuration) for the `cms.sysadmin` flag, the cross-tenant `/auth/v1/admin/list-organizations` endpoint, and the SPA's "All organizations" sentinel.
375
375
 
376
+ The boundary is enforced, not just conventional. Better Auth's admin plugin on its own lets any role holding `user:set-role` grant any role that exists, so the compiler emits a role-ceiling `hooks.before` entry (`enforceAdminRoleCeiling` in `src/lib/auth.ts`): an appmanager cannot assign `sysadmin` — to itself or anyone — nor ban, remove, reset the password of, or revoke the sessions of a sysadmin. Those calls return `403 ROLE_CEILING`. Tiers follow the admin plugin's `adminRoles` order, lowest privilege first; see [Account admin → Access Control](/ui/account/features/admin#access-control).
377
+
376
378
  #### Mixing pseudo-roles with real roles
377
379
 
378
380
  Pseudo-roles and lowercase real roles compose with OR:
@@ -123,7 +123,9 @@ the lookup is gated and typed again:
123
123
  export default defineAction({
124
124
  path: '/invite/enter-event',
125
125
  access: { roles: ['PUBLIC'] },
126
- unsafe: true,
126
+ // crossTenant: false — `unsafe: true` means crossTenant + adminOnly, which
127
+ // requires a sysadmin session and 403s an anonymous caller.
128
+ unsafe: { reason: 'Invite door — tenant resolved from the invite token', crossTenant: false },
127
129
  async execute({ unsafeDb, input }) {
128
130
  const [token] = await unsafeDb.select().from(inviteTokens).where(eq(inviteTokens.code, input.code));
129
131
  if (!token) throw new ActionError('Invalid invite', 'INVITATION_INVALID_OR_EXPIRED', 404);
@@ -425,18 +427,17 @@ Unsafe cross-tenant actions are generated with:
425
427
  - sysadmin gate (`ctx.userRole === "sysadmin"`)
426
428
  - mandatory audit logging on deny/success/error
427
429
 
428
- **Provider note (Neon):** `unsafe.enabled` controls app-layer scoped-query
429
- bypass, while `unsafe.crossTenant` controls database-layer RLS bypass. An
430
- unsafe action with `crossTenant: false` receives a raw Drizzle handle backed by
431
- the request database, so the caller's organization or delegated-principal
432
- claims remain active—including inside `db.transaction()`. Its code must still
433
- provide every intended scope predicate explicitly.
434
-
435
- Only an action with `crossTenant: true` acquires the dedicated service-role
436
- handle (`createServiceDb`). That handle sets the `quickback.service_role`
437
- transaction marker instead of caller claims, and generated RLS grants it an
438
- explicit per-table bypass policy. The sysadmin guard and mandatory audit log
439
- therefore protect the same boundary that receives the RLS bypass. The
430
+ **Provider note (Neon, PlanetScale Postgres):** `unsafeDb` is the
431
+ service-role handle (`createServiceDb`, wrapped by the audit writer) for
432
+ **every** unsafe action, `crossTenant: true` or `false` — the same reach as on
433
+ D1. It sets the `quickback.service_role` transaction marker instead of caller
434
+ claims, and generated RLS grants that marker an explicit per-table policy. So
435
+ RLS does not narrow `unsafeDb` to the caller: a `PUBLIC` door's token lookup
436
+ finds the row, and a roster join over `member` sees every member. The action's
437
+ own checks — and `unsafeDb.scopeTo(...)` — govern, exactly as on D1.
438
+
439
+ `crossTenant` decides the gate, not the handle: `crossTenant: true` adds the
440
+ sysadmin guard and mandatory audit log described above. The
440
441
  audit-logging contract is otherwise identical to D1. On Cloudflare, both HTTP
441
442
  and Hyperdrive are supported. Hyperdrive is the recommended lane when an unsafe
442
443
  action also needs an interactive transaction. The deprecated Node/Bun WebSocket