@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,7 @@ On Postgres the RLS scope policy mirrors the firewall's `all`/`any` tree arm for
124
124
 
125
125
  - A `via:` arm lowers to `project_id IN (SELECT r.project_id FROM public.qb_rel_<relationship>() r)` — a `SECURITY DEFINER` helper that runs the same relationship lookup as the API (subject = the caller's claim, the `where:` literals, the related table's soft delete). The generated API calls the same helper for every relationship lookup on Postgres, so a caller with no active org gets the same rows from the API as the policy admits. `[org, { any: [owner, { via }] }]` becomes `org AND (owner OR project_id IN (…))`, never `org AND owner`. See [Relationship arms in SQL](/platform/database/neon#relationship-arms-in-sql).
126
126
  - A `{ permission }` arm expands exactly as the API expands it: relation leaves become `via:` helpers, arrows become `qb_arrow_…` helpers (a recursive arrow is a `maxDepth`-bounded closure; a relation-backed arrow returns the hop's rows whose FK is in the target relationship's `qb_rel_…` set).
127
- - Inside an `any` group that also has an org arm, the relationship, scope and principal arms are tenant-bound exactly where the API binds them — `(<arm> AND (organization_id = <active org> OR <no active org>))` — so an org-claiming caller never rides them into another org.
127
+ - Inside an `any` group that also has an org arm (at any depth — see Boolean groups below), the relationship, scope and principal arms are tenant-bound exactly where the API binds them — `(<arm> AND (organization_id = <active org> OR <no active org>))` — so an org-claiming caller never rides them into another org.
128
128
  - The soft-delete filter the API adds to a table carrying `deletedAt` reaches the policy too, as `deleted_at IS NULL OR public.in_soft_delete()` in `USING` only — see [the soft-delete lane](/platform/database/neon#the-soft-delete-lane).
129
129
  - Literals, literal `in` lists, and claims the Worker never writes into the transaction (`ctx.scope.<kind>.<subKey>`, area anchors like `ctx.event.id`, string `in` sets) stay API-only and lower to `true` — the policy has nothing to compare them against, and a literal conjunct would refuse status-changing updates.
130
130
 
@@ -147,6 +147,7 @@ Null-safe scope semantics make this safe (these apply **inside `all`/`any` group
147
147
 
148
148
  - A **scope** arm (`ctx.activeOrgId`, `ctx.activeTeamId`, `ctx.scope.*`) whose claim is **absent never binds `undefined`** (the classic 500 / "match every row" trap). In an `any` group an absent arm **drops**; if **every** arm drops, the group denies with `sql\`1 = 0\`` (the empty-guard) — never a full-table read. In an `all` group an absent required scope **denies** the group.
149
149
  - **An `any` group with an org arm tenant-binds its scope and relationship arms.** Beside `{ field: 'organizationId', equals: 'ctx.activeOrgId' }`, a `ctx.scope.*` arm, a `via:` arm, or a `{ permission }` arm is emitted as `scope-arm AND (organizationId = ctx.activeOrgId OR the caller has no org claim)`. A caller with **no** org claim (a scope-only or relationship principal) is unaffected; a caller who carries org B's membership *and* a scope claim or relationship row on an org-A instance cannot ride the scope arm into org A's rows. Owner arms (`ctx.userId`), team arms, and literal `in` lists are not tenant-bound. An org claim and a scope claim in one request are therefore always the same tenant — or the scope arm yields nothing.
150
+ The org arm does not have to be a direct child of the `any`: it is found at any depth, so the common "org AND audience filter" shape — `{ all: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }, { field: 'staffAudience', isNull: true }] }` beside the `via:` arms — binds them exactly as a top-level org arm would. The arm that requires the org equality on every path (directly, or through `all:` nesting) is already anchored and stays as written. If the group's org arms name **different** columns (`organizationId` in one, `workspaceId` in another) and there is an arm to bind, the compile fails: there is no single column to bind it to, and the compiler will not pick one.
150
151
  - Mark an arm `{ optional: true }` to **drop-instead-of-deny** when absent inside an `all` group (the teamless rest-of-org slice — `ctx.activeTeamId` is implicitly optional). An optional arm only drops while a **non-optional** tenant arm still bounds the query; a sole optional arm denies when its claim is absent, exactly like the team rule below.
151
152
  - **Owner** (`ctx.userId`) and **soft-delete** (`isNull deletedAt`) are always present / always AND'd — never relaxed.
152
153
 
@@ -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: