@quickback-dev/cli 0.67.3 → 0.68.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 (53) 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 +56 -6
  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/batch-operations.md +19 -4
  14. package/dist/skill/docs/api/errors.md +35 -2
  15. package/dist/skill/docs/configure/index.md +4 -1
  16. package/dist/skill/docs/configure/providers.md +1 -0
  17. package/dist/skill/docs/define/access.md +2 -0
  18. package/dist/skill/docs/define/actions/scoped-db.md +5 -3
  19. package/dist/skill/docs/define/feature.md +2 -0
  20. package/dist/skill/docs/define/schema.md +21 -4
  21. package/dist/skill/docs/define/triggers.md +3 -0
  22. package/dist/skill/docs/define/validation.md +28 -2
  23. package/dist/skill/docs/platform/auth/api-keys.md +1 -1
  24. package/dist/skill/docs/platform/auth/device-auth.md +16 -1
  25. package/dist/skill/docs/platform/auth/security.md +22 -7
  26. package/dist/skill/docs/platform/database/neon.md +9 -2
  27. package/dist/skill/docs/platform/database/planetscale-postgres.md +1 -0
  28. package/dist/skill/docs/platform/database/using-d1.md +32 -0
  29. package/dist/skill/docs/tooling/cli.md +6 -3
  30. package/dist/skill/docs/tooling/output.md +3 -1
  31. package/dist/skill/docs/ui/account/features/admin.md +9 -0
  32. package/dist/skill/docs/ui/admin/schema-format.md +3 -1
  33. package/package.json +1 -1
  34. package/src/skill/docs/api/batch-operations.md +19 -4
  35. package/src/skill/docs/api/errors.md +35 -2
  36. package/src/skill/docs/configure/index.md +4 -1
  37. package/src/skill/docs/configure/providers.md +1 -0
  38. package/src/skill/docs/define/access.md +2 -0
  39. package/src/skill/docs/define/actions/scoped-db.md +5 -3
  40. package/src/skill/docs/define/feature.md +2 -0
  41. package/src/skill/docs/define/schema.md +21 -4
  42. package/src/skill/docs/define/triggers.md +3 -0
  43. package/src/skill/docs/define/validation.md +28 -2
  44. package/src/skill/docs/platform/auth/api-keys.md +1 -1
  45. package/src/skill/docs/platform/auth/device-auth.md +16 -1
  46. package/src/skill/docs/platform/auth/security.md +22 -7
  47. package/src/skill/docs/platform/database/neon.md +9 -2
  48. package/src/skill/docs/platform/database/planetscale-postgres.md +1 -0
  49. package/src/skill/docs/platform/database/using-d1.md +32 -0
  50. package/src/skill/docs/tooling/cli.md +6 -3
  51. package/src/skill/docs/tooling/output.md +3 -1
  52. package/src/skill/docs/ui/account/features/admin.md +9 -0
  53. package/src/skill/docs/ui/admin/schema-format.md +3 -1
@@ -161,7 +161,16 @@ The Drizzle column is the Postgres form; on SQLite/D1 the compiler lowers it. Th
161
161
 
162
162
  In request bodies a column that is not `.required()` is `.optional().nullable()` — omit it to leave it untouched, send `null` to clear it. `""` is not a blank: it is validated like any other value. `.required()` columns never accept `null`.
163
163
 
164
- `q.text()` and `q.url()` accept either a SQL-name string or an options object — `q.text({ sqlName: 'org_id', maxLength: 80 })`. `maxLength` adds `z.string().max(n)` at the validation edge; the SQL column stays `text` (D1 ignores `VARCHAR(n)` length anyway).
164
+ `q.text()` accepts either a SQL-name string or an options object — `q.text({ sqlName: 'org_id', maxLength: 80 })`. The options are the field-level rules:
165
+
166
+ | Option | Validation edge | Notes |
167
+ |--------|-----------------|-------|
168
+ | `minLength: n` | `z.string().min(n)` | `""` then fails like any other short value |
169
+ | `maxLength: n` | `z.string().max(n)` | The SQL column stays `text` (D1 ignores `VARCHAR(n)` length anyway) |
170
+ | `pattern: /re/` | `z.string().regex(/re/)` | Must be a regex literal, not a string or variable, so the compiler can emit it |
171
+ | `email: true` | `z.string().email()` | |
172
+
173
+ Every rule is enforced on the generated create, update, and batch routes, described in OpenAPI, and read by the CMS form from the [schema registry](/ui/admin/schema-format). A misspelled option (`maxlength`) is a compile error, not a silent no-op. `q.url()` takes `sqlName` and `maxLength` only.
165
174
 
166
175
  `q.url()` is `q.text()` plus an absolute-`http(s)`-URL check at the validation edge, so `javascript:` / `data:` / `ftp:` URIs and free-form strings are rejected before they ever land in storage or get rendered in the CMS.
167
176
 
@@ -526,7 +535,7 @@ Default to `feature()`. Drop to Drizzle only when:
526
535
 
527
536
  Features in the same project may mix freely — Quickback dispatches per feature — so one interop table doesn't force the rest of the project off `feature()`.
528
537
 
529
- One dialect rule: interop files **without** a `defineTable(...)` default export (internal child tables) are not dialect-translated — author them in the target database's dialect. On Postgres providers (`neon`, `planetscale-postgres`), a `sqliteTable` interop source without `defineTable` is a compile-time error; write it with `pgTable` from `drizzle-orm/pg-core` instead. Sources **with** `defineTable(...)` keep compiling across dialects automatically.
538
+ One dialect rule: interop files **without** a `defineTable(...)` default export (internal child tables) are not dialect-translated — author them in the target database's dialect. On Postgres providers (`neon`, `planetscale-postgres`), a `sqliteTable` interop source without `defineTable` is a compile-time error; write it with `pgTable` from `drizzle-orm/pg-core` instead. Sources **with** `defineTable(...)` keep compiling across dialects automatically. On Postgres, managed audit timestamps a `sqliteTable` source declares in the SQLite shape (`createdAt` / `modifiedAt` / `deletedAt` as `text`) are emitted as `timestamptz`, the same as every other Postgres table; API responses still carry the same ISO-8601 string.
530
539
 
531
540
  ### Drizzle Column Types
532
541
 
@@ -706,7 +715,7 @@ Opt out of audit injection entirely with `compiler.features.auditFields: false`
706
715
 
707
716
  The scoped `db` injected into actions stamps these four columns for you. A handle built directly from `createDb()` does not — that's the documented escape hatch for system writes, sessionless principals, and broad reads the scoped wrapper over-narrows.
708
717
 
709
- Those writes still land in audit-managed tables. A Drizzle insert that omits `createdAt` / `modifiedAt` gets the insert time (Postgres `DEFAULT now()`; on SQLite the column's `$defaultFn`), but nothing fills `createdBy` / `modifiedBy` — they stay `NULL`. On SQLite the managed timestamps also carry a DDL default of the unix epoch (so `ALTER TABLE ADD COLUMN` works on populated tables), so **raw SQL** that omits them does not fail on `NOT NULL` — it silently persists `1970-01-01T00:00:00.000Z`, which reads as a real timestamp everywhere downstream.
718
+ Those writes still land in audit-managed tables. A Drizzle insert that omits `createdAt` / `modifiedAt` gets the insert time (Postgres `DEFAULT now()`; on SQLite the column's `$defaultFn`), but on SQLite nothing fills `createdBy` / `modifiedBy` — they stay `NULL`. (On Postgres the database's audit triggers fill them — see [How auto-injection works](#how-auto-injection-works-two-layers).) On SQLite the managed timestamps also carry a DDL default of the unix epoch (so `ALTER TABLE ADD COLUMN` works on populated tables), so **raw SQL** that omits them does not fail on `NOT NULL` — it silently persists `1970-01-01T00:00:00.000Z`, which reads as a real timestamp everywhere downstream.
710
719
 
711
720
  Spread the stamp instead of hand-writing four columns at each call site:
712
721
 
@@ -756,6 +765,14 @@ The scoped `db` an action receives types every managed key as `?: never` on `.in
756
765
 
757
766
  The runtime layer **hard-stamps** every audit field on every write, so the audit log can never be forged by a crafted request body or by a client echoing a row back into a PATCH.
758
767
 
768
+ On Postgres the RLS migration adds a database-side backstop: `BEFORE INSERT` / `BEFORE UPDATE` triggers on every feature table (`public.set_audit_fields_on_insert()` / `_on_update()`). They set `created_at` / `modified_at` to the database's `now()` and apply the same actor rule as the wrapper — the actor column always names whoever did the write:
769
+
770
+ - a verified caller (`auth.user_id()`) always wins, so no request can write someone else's id;
771
+ - with no verified caller — a `scope:` principal, a delegated principal, the service lane, a `system:` actor — the actor the Worker already stamped is kept;
772
+ - only a write that carries no actor at all (raw SQL) gets `system:<database role>`.
773
+
774
+ `created_at` / `created_by` never change on update.
775
+
759
776
  Because the value would be discarded anyway, the generated `db` handle refuses it at the type level: on the scoped `db`, `.insert().values()` types `createdAt` / `modifiedAt` / `createdBy` / `modifiedBy` / `deletedAt` / `deletedBy` as `?: never`, and `.update().set()` types the audit quartet plus `deletedBy` the same way. Supplying one is a **compile error** — not a silent discard.
760
777
 
761
778
  ```ts
@@ -771,7 +788,7 @@ Drop the keys and let the wrapper write them from `ctx.userId` and the actual wr
771
788
 
772
789
  One deliberate exception: `.set({ deletedAt: ... })` **is** allowed on update — that assignment is the soft-delete signal, and the stored value is normalized to the write moment and the verified caller. The raw `unsafeDb` handle an `unsafe:` action receives is unwrapped Drizzle and carries none of these type fences.
773
790
 
774
- What the caller is responsible for: the domain fields. (`id` auto-fills via the column's `$defaultFn` — `q.id()` and injected ids both carry one.)
791
+ What the caller is responsible for: the domain fields. (`id` auto-fills via the column's `$defaultFn` — `q.id()` and injected ids both carry one, and the typed `db` treats `id` as optional on insert for every id strategy except `serial` and `false`.)
775
792
 
776
793
  What the caller does *not* need to set: `id`, the scope column, or any of the audit fields, ever.
777
794
 
@@ -248,6 +248,9 @@ an [action](/define/actions/scoped-db#reaching-better-auth-tables-authdb).
248
248
  write's promise resolves. They may be `async`. A throw surfaces as
249
249
  `TRIGGER_AFTER_FAILED` (500) with `details.committed: true` — the row was
250
250
  already persisted (no transactions on D1), so clients must not blind-retry.
251
+ The hook's error message is logged; the response's error text is the
252
+ generic `After-trigger failed` unless the worker sets
253
+ [`EXPOSE_ERROR_STACK`](/api/errors#exposing-error-details-in-dev--staging).
251
254
  - Handlers must be **inline arrow/function expressions**. Imports they
252
255
  reference are hoisted into the generated registry (`src/lib/trigger-hooks.ts`)
253
256
  with relative paths rewritten from the table file — including dynamic
@@ -27,7 +27,33 @@ If validation fails, the API returns a `400 Bad Request` with details about whic
27
27
 
28
28
  See [Actions](/define/actions) for the full action definition reference.
29
29
 
30
- > **Planned: Field-Level Validation**
30
+ ## Column Constraints
31
+
32
+ Field-level rules live on the column, not in a separate block. `q.text({ minLength, maxLength, pattern, email })`, `q.enum([...])`, `q.url({ maxLength })` and the numeric column types carry their constraints into the Zod schema of every generated create, update, and batch route, into the OpenAPI document, and into the CMS form. See [Schema](/define/schema#column-types) for the full list.
33
+
34
+ A raw Drizzle table (`sqliteTable` / `pgTable` wrapped in `defineTable`) has no column-level rules. Validate those in a [`triggers.beforeInsert` / `beforeUpdate`](/define/triggers) handler that throws, or convert the table to `q.table()`.
35
+
36
+ ```typescript
37
+ // features/agendaGroups/agendaGroups.ts
38
+ import { feature, q } from '@quickback/compiler';
39
+
40
+ export default feature('agendaGroups', {
41
+ columns: {
42
+ id: q.id(),
43
+ name: q.text({ maxLength: 200 }).required(),
44
+ selectionRule: q.enum(['one', 'multi']).default('one').required(),
45
+ organizationId: q.scope('organization'),
46
+ ...q.audit(),
47
+ ...q.softDelete(),
48
+ },
49
+ read: { access: { roles: ['member'] } },
50
+ create: { access: { roles: ['member'] } },
51
+ update: { access: { roles: ['member'] } },
52
+ delete: { access: { roles: ['member'] }, mode: 'soft' },
53
+ });
54
+ ```
55
+
56
+ > **There is no `validation:` key**
31
57
  >
32
- > Field-level validation rules in `defineTable()` (e.g., `minLength`, `maxLength`, `enum`) are planned for a future release. Today, use Zod schemas in actions for input validation, and rely on your Drizzle schema constraints (`.notNull()`, column types) for database-level enforcement.
58
+ > A top-level `validation: { field: { maxLength, enum } }` block on `defineTable()` is a compile error, as is any other key the compiler does not understand. Earlier compilers let unknown keys through silently, so a `validation:` block looked like it limited a field while the generated routes accepted anything. Move each rule onto its column.
33
59
 
@@ -97,4 +97,4 @@ When the admin plugin bans a user, every API key they own stops working: the API
97
97
 
98
98
  ## Rate limit
99
99
 
100
- Better Auth rate limits each key using the auth config's `rateLimit.window` (seconds) and `rateLimit.max` — 100 requests per 60 seconds by default. The limit is on unless that block sets `enabled: false`. Over the limit the API answers `429 AUTH_RATE_LIMITED`. The values are stamped on each key when it is created, so a change applies to new keys only.
100
+ Better Auth rate limits each key using the auth config's `rateLimit.window` (seconds) and `rateLimit.max` — 100 requests per 60 seconds by default. The limit is always on. It counts per key, so `rateLimit.enabled: false` (which turns off the per-IP limiter) doesn't affect it. Over the limit the API answers `429 AUTH_RATE_LIMITED`. The values are stamped on each key when it is created, so a change applies to new keys only.
@@ -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.
@@ -183,6 +183,19 @@ long-lived process — the default is `"memory"`.
183
183
  | `"database"` | Auth database (`rateLimit` table) | Cloudflare Workers (default there) |
184
184
  | `"memory"` | Process memory | Single long-lived process (bun / node default) |
185
185
 
186
+ The table exists whenever `storage` is `"database"`, even with `enabled: false`,
187
+ so switching the limiter off or back on needs no migration.
188
+
189
+ ### Client IP
190
+
191
+ Better Auth reads the client IP from `x-forwarded-for` by default, which a
192
+ Worker doesn't receive. Without an IP every caller shares one bucket per path,
193
+ and a single client could use up a sign-in limit for everyone. On Cloudflare
194
+ the compiler therefore emits
195
+ `advanced.ipAddress.ipAddressHeaders: ['cf-connecting-ip']`. Cloudflare sets
196
+ that header at the edge, and clients can't override it. Set
197
+ `advanced.ipAddress.ipAddressHeaders` yourself to use different headers.
198
+
186
199
  ### Built-in rules for every credential door
187
200
 
188
201
  The compiler always emits a per-route rule for **every** credential endpoint
@@ -220,16 +233,16 @@ Set an edge rate-limit binding as well for defence in depth
220
233
 
221
234
  ### Disabling Rate Limiting
222
235
 
223
- Not recommended, but you can disable for testing:
224
-
225
236
  ```ts
226
- rateLimit: {
227
- enabled: process.env.NODE_ENV === 'production',
228
- window: 60,
229
- max: 1000, // Higher limit for development
230
- }
237
+ rateLimit: { enabled: false }
231
238
  ```
232
239
 
240
+ The compiler emits `enabled: false` explicitly. Better Auth would otherwise
241
+ fall back to `enabled: isProduction`. Disabling makes sense when many real
242
+ users share one IP, such as everyone on an event venue's Wi-Fi. It turns off
243
+ only the per-IP limiter. The [per-key API key limit](/platform/auth/api-keys)
244
+ stays on.
245
+
233
246
  ---
234
247
 
235
248
  ## Bearer Tokens and Cookie Precedence
@@ -270,6 +283,7 @@ Quickback configures the Better Auth `bearer` plugin with `requireSignature: tru
270
283
  - The session token Better Auth emits via the `set-auth-token` response header is **signed server-side** with `BETTER_AUTH_SECRET`.
271
284
  - Unsigned bearer tokens are **rejected** at the plugin layer before any session lookup happens.
272
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)).
273
287
 
274
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.
275
289
 
@@ -292,6 +306,7 @@ User-supplied options merge on top of the secure default, so any other [`bearer`
292
306
  | Threat | Mitigation |
293
307
  |--------|-----------|
294
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 |
295
310
  | Browser extension injects a victim's session cookie into an attacker's bearer-authed API call | Cookie stripped when `Authorization` is present |
296
311
  | Multi-account user has cookies for two identities and uses bearer for the second | Bearer identity wins; no ambiguity in audit log |
297
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)) |
@@ -709,7 +709,10 @@ touched. See [the default index set](#the-default-index-set).
709
709
 
710
710
  ### Delegated principal RLS
711
711
 
712
- Delegated principals require Cloudflare + Neon Hyperdrive. Their proof hook
712
+ Delegated principals require Cloudflare + Postgres over Hyperdrive: Neon with
713
+ `connectionMode: "hyperdrive"`, or
714
+ [PlanetScale Postgres](/platform/database/planetscale-postgres), which emits the
715
+ same lookup policies and lanes. Their proof hook
713
716
  returns only a digest and receives no database handle. Quickback then runs one
714
717
  lookup under an internal lookup-only principal whose RLS policy admits only the
715
718
  configured table row matching `credentialDigest`, plus any configured active
@@ -1435,7 +1438,11 @@ source. A child table with no `crud` config soft-deletes by default, so
1435
1438
 
1436
1439
  Tables **with** `defineTable(...)` are unaffected — existing `sqliteTable`
1437
1440
  sources with a resource config still compile to the Postgres dialect
1438
- automatically.
1441
+ automatically. Managed audit timestamps declared in the SQLite shape
1442
+ (`createdAt` / `modifiedAt` / `deletedAt` as `text`) are emitted as
1443
+ `timestamptz`, like every other Postgres table — the audit wrapper and the RLS
1444
+ audit triggers both stamp timestamps, not strings. API responses carry the same
1445
+ ISO-8601 string as on D1.
1439
1446
 
1440
1447
  ## When to choose Neon vs D1
1441
1448
 
@@ -197,6 +197,7 @@ never silently-broken output:
197
197
  | Managed file storage (`managed: true`) | **supported** — metadata lives in a `files` schema of the same database; the file-serving Worker binds the same Hyperdrive config |
198
198
  | Better Auth `subscriptions` plugin | supported — `auth.subscriptions` in the same journal, service-role only ([Subscriptions](/platform/auth/plugins/subscriptions#where-the-table-lives)) |
199
199
  | Generated SQL triggers (`sql:`) | supported — PL/pgSQL bodies, `SECURITY INVOKER` (see [Triggers](/define/triggers)) |
200
+ | Delegated principals (`auth.principals`, `resource.databaseAccess`) | supported — the same lookup policy, `<table>_principal_scope` / `<table>_principal_fence` lanes and middleware as Neon Hyperdrive ([Delegated principal RLS](/platform/database/neon#delegated-principal-rls)) |
200
201
  | `webhooksDatabaseId` / `webhooksDatabaseName` | rejected — D1-only keys; webhook tables live in the `webhooks` schema of the same database |
201
202
  | `connectionMode` of `'http'` or `'websocket'` | rejected — no such driver for this provider |
202
203
 
@@ -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)
@@ -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:
@@ -430,9 +430,11 @@ interface ValidationRule {
430
430
  | `enum` | `q.enum([...])`, or `text(..., { enum: [...] })` in raw Drizzle — the CMS renders a select |
431
431
  | `url` | `q.url()` — the CMS renders a `url` input; the API accepts only absolute `http(s)` URLs (so not `""`, `javascript:` or `data:`) |
432
432
  | `maxLength` | `q.text({ maxLength })` / `q.url({ maxLength })` |
433
+ | `minLength` | `q.text({ minLength })` |
434
+ | `email` | `q.text({ email: true })` — the CMS renders an `email` input |
433
435
  | `integer` | `q.int()`, `q.bigint()`, `q.smallint()` — whole numbers only |
434
436
  | `min` / `max` | `q.bigint()` (±2^53−1, the JSON-safe range) and `q.smallint()` (−32768…32767), inclusive |
435
- | `pattern` | `q.decimal({ precision, scale })` — the regex source the decimal string must match |
437
+ | `pattern` | `q.text({ pattern: /re/ })` (regex source only; flags are not carried) and `q.decimal({ precision, scale })` — the regex source the value must match |
436
438
  | `minLength` / `email` | Only when the enforced Zod carries `.min(n)` / `.email()`; no q column kind emits them today |
437
439
 
438
440
  Columns with no constraints have no entry. Optional fields left blank in the CMS form are omitted from the request body rather than sent as `""` — the API accepts an optional field being absent, not empty.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quickback-dev/cli",
3
- "version": "0.67.3",
3
+ "version": "0.68.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",
@@ -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,35 @@ 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 |
328
332
 
329
333
  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
334
 
335
+ The same classification applies to every write path — single-record create,
336
+ update, `PUT` and delete, the batch endpoints (including `DELETE /batch`, which
337
+ reports these `DB_*` codes per id, or as the `failFast` response), bulk
338
+ actions, and changesets.
339
+
340
+ `DB_INSERT_FAILED`, `DB_UPDATE_FAILED` and `DB_DELETE_FAILED` are the fallback
341
+ for a failure that matches no known constraint. The raw driver message (D1 or
342
+ Postgres text, which can name tables, columns, and SQL fragments) is always
343
+ logged with `console.error`, and the production body carries no `details`:
344
+
345
+ ```json
346
+ {
347
+ "detail": "Update failed",
348
+ "layer": "database",
349
+ "code": "DB_UPDATE_FAILED",
350
+ "hint": "Database rejected the update. Check server logs for the underlying error."
351
+ }
352
+ ```
353
+
354
+ The raw message appears as `details.reason` only when the worker runs with
355
+ [`EXPOSE_ERROR_STACK`](#exposing-error-details-in-dev--staging) set.
356
+
331
357
  `ENCRYPTION_UNREADABLE` always carries `details: { table, column, id }` — the
332
358
  row whose stored ciphertext is malformed, was not written under the caller's
333
359
  organization key, was copied from another column or table, or names a key
@@ -476,4 +502,11 @@ When set, the global 500 and `ACTION_EXECUTION_FAILED` bodies forward
476
502
  the underlying error message plus `details.cause` (cause-chain
477
503
  message), `details.frames` (top three stack frames with absolute paths
478
504
  sanitized to basename + line number), and `details.stack` (the full
479
- unsanitized stack trace). Leave it unset in production.
505
+ unsanitized stack trace). The same switch adds `details.reason` (the raw
506
+ error message) to the database fallbacks (`DB_INSERT_FAILED`,
507
+ `DB_UPDATE_FAILED`, `DB_DELETE_FAILED`), `ACCESS_AUDIT_LOG_FAILED`, the
508
+ `INTERNAL_ERROR` bodies of the auth handler and the operator `/admin/*`
509
+ routes, and uses the raw message as the `TRIGGER_AFTER_FAILED` error text.
510
+ Without it, none of those bodies carry anything derived from the thrown
511
+ error. `1` and `true` turn it on; any other value leaves it off. Leave it
512
+ unset in production.
@@ -163,7 +163,10 @@ bypass it.
163
163
  short-lived event session. It requires both of:
164
164
 
165
165
  - the Cloudflare runtime
166
- - Neon with `connectionMode: "hyperdrive"`
166
+ - Postgres over Cloudflare Hyperdrive — [Neon](/platform/database/neon) with
167
+ `connectionMode: "hyperdrive"`, or
168
+ [PlanetScale Postgres](/platform/database/planetscale-postgres) (Hyperdrive
169
+ is its only transport)
167
170
 
168
171
  Each principal type owns an exact Authorization scheme. `Bearer` is reserved
169
172
  for Quickback account authentication, including case variants, and two
@@ -108,6 +108,7 @@ single Postgres database with no bindings or split mode (see
108
108
  | `namingConvention` | `string` | `"snake_case"` | Column naming convention |
109
109
  | `usePlurals` | `boolean` | `false` | Pluralize auth table names (e.g. `user` vs `users`) |
110
110
  | `splitDatabases` | `boolean` | `true` | Separate auth and features databases (D1 only) |
111
+ | `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
112
  | `authBinding` | `string` | `"AUTH_DB"` | Binding name for auth database |
112
113
  | `featuresBinding` | `string` | `"DB"` | Binding name for features database |
113
114
  | `databaseId` | `string` | — | D1 database ID for the features database (used in generated wrangler.toml) |
@@ -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:
@@ -168,7 +168,8 @@ async execute({ db, ctx, input }) {
168
168
 
169
169
  ### Delegated principals and `databaseAccess`
170
170
 
171
- On a Cloudflare + Neon Hyperdrive project, an action can admit a
171
+ On a Cloudflare project with Postgres over Hyperdrive (Neon `connectionMode:
172
+ "hyperdrive"` or PlanetScale Postgres), an action can admit a
172
173
  configured delegated principal with `access.principals`:
173
174
 
174
175
  ```typescript
@@ -222,7 +223,7 @@ organization, and no membership roles, so the table's ordinary firewall
222
223
  predicate — `organizationId = ctx.activeOrgId` — can never match for it. The
223
224
  lane is the row rule that CAN: the principal's own verified claims.
224
225
 
225
- {/* doc-compile: skip — provider prerequisite: `resource.databaseAccess` compiles only on Cloudflare + Neon `connectionMode: "hyperdrive"` (RLS + transaction-local claims), and the gate's harness is D1. The file is otherwise whole and compiles on a Neon project. */}
226
+ {/* doc-compile: skip — provider prerequisite: `resource.databaseAccess` compiles only on Cloudflare + Postgres over Hyperdrive (Neon `connectionMode: "hyperdrive"` or PlanetScale Postgres; RLS + transaction-local claims), and the gate's harness is D1. The file is otherwise whole and compiles on either. */}
226
227
  ```typescript
227
228
  // features/attendance/attendanceEvidence.ts
228
229
  import { q, defineTable } from '@quickback/compiler';
@@ -325,7 +326,8 @@ so a field such as `eventId: text("event-id")` is safe. Unknown fields fail the
325
326
  compile. Application-only values — `userRole`, functions, request/body fields —
326
327
  stay at the action access layer; the compiler refuses them rather than
327
328
  pretending PostgreSQL can evaluate them. The feature is rejected outside
328
- Cloudflare + Neon Hyperdrive because no other target can guarantee
329
+ Cloudflare + Postgres over Hyperdrive (Neon or PlanetScale Postgres) because no
330
+ other target can guarantee
329
331
  request-scoped Postgres claims.
330
332
 
331
333
  > **Upgrading.** The four per-operation `<table>_database_<op>` policies are
@@ -41,6 +41,8 @@ feature("name", {
41
41
  });
42
42
  ```
43
43
 
44
+ That is the complete key set. Any other top-level key is a compile error naming the key and the list above, so a misspelling or a key from another tool can't ride through as a silent no-op.
45
+
44
46
  | You want | Key | Page |
45
47
  |---|---|---|
46
48
  | Tenant isolation, role gates, field and value control | `firewall`, `read`/`create`/`update`/`delete`, `guards`, `masking` | [Security](/define/security) |
@@ -161,7 +161,16 @@ The Drizzle column is the Postgres form; on SQLite/D1 the compiler lowers it. Th
161
161
 
162
162
  In request bodies a column that is not `.required()` is `.optional().nullable()` — omit it to leave it untouched, send `null` to clear it. `""` is not a blank: it is validated like any other value. `.required()` columns never accept `null`.
163
163
 
164
- `q.text()` and `q.url()` accept either a SQL-name string or an options object — `q.text({ sqlName: 'org_id', maxLength: 80 })`. `maxLength` adds `z.string().max(n)` at the validation edge; the SQL column stays `text` (D1 ignores `VARCHAR(n)` length anyway).
164
+ `q.text()` accepts either a SQL-name string or an options object — `q.text({ sqlName: 'org_id', maxLength: 80 })`. The options are the field-level rules:
165
+
166
+ | Option | Validation edge | Notes |
167
+ |--------|-----------------|-------|
168
+ | `minLength: n` | `z.string().min(n)` | `""` then fails like any other short value |
169
+ | `maxLength: n` | `z.string().max(n)` | The SQL column stays `text` (D1 ignores `VARCHAR(n)` length anyway) |
170
+ | `pattern: /re/` | `z.string().regex(/re/)` | Must be a regex literal, not a string or variable, so the compiler can emit it |
171
+ | `email: true` | `z.string().email()` | |
172
+
173
+ Every rule is enforced on the generated create, update, and batch routes, described in OpenAPI, and read by the CMS form from the [schema registry](/ui/admin/schema-format). A misspelled option (`maxlength`) is a compile error, not a silent no-op. `q.url()` takes `sqlName` and `maxLength` only.
165
174
 
166
175
  `q.url()` is `q.text()` plus an absolute-`http(s)`-URL check at the validation edge, so `javascript:` / `data:` / `ftp:` URIs and free-form strings are rejected before they ever land in storage or get rendered in the CMS.
167
176
 
@@ -526,7 +535,7 @@ Default to `feature()`. Drop to Drizzle only when:
526
535
 
527
536
  Features in the same project may mix freely — Quickback dispatches per feature — so one interop table doesn't force the rest of the project off `feature()`.
528
537
 
529
- One dialect rule: interop files **without** a `defineTable(...)` default export (internal child tables) are not dialect-translated — author them in the target database's dialect. On Postgres providers (`neon`, `planetscale-postgres`), a `sqliteTable` interop source without `defineTable` is a compile-time error; write it with `pgTable` from `drizzle-orm/pg-core` instead. Sources **with** `defineTable(...)` keep compiling across dialects automatically.
538
+ One dialect rule: interop files **without** a `defineTable(...)` default export (internal child tables) are not dialect-translated — author them in the target database's dialect. On Postgres providers (`neon`, `planetscale-postgres`), a `sqliteTable` interop source without `defineTable` is a compile-time error; write it with `pgTable` from `drizzle-orm/pg-core` instead. Sources **with** `defineTable(...)` keep compiling across dialects automatically. On Postgres, managed audit timestamps a `sqliteTable` source declares in the SQLite shape (`createdAt` / `modifiedAt` / `deletedAt` as `text`) are emitted as `timestamptz`, the same as every other Postgres table; API responses still carry the same ISO-8601 string.
530
539
 
531
540
  ### Drizzle Column Types
532
541
 
@@ -706,7 +715,7 @@ Opt out of audit injection entirely with `compiler.features.auditFields: false`
706
715
 
707
716
  The scoped `db` injected into actions stamps these four columns for you. A handle built directly from `createDb()` does not — that's the documented escape hatch for system writes, sessionless principals, and broad reads the scoped wrapper over-narrows.
708
717
 
709
- Those writes still land in audit-managed tables. A Drizzle insert that omits `createdAt` / `modifiedAt` gets the insert time (Postgres `DEFAULT now()`; on SQLite the column's `$defaultFn`), but nothing fills `createdBy` / `modifiedBy` — they stay `NULL`. On SQLite the managed timestamps also carry a DDL default of the unix epoch (so `ALTER TABLE ADD COLUMN` works on populated tables), so **raw SQL** that omits them does not fail on `NOT NULL` — it silently persists `1970-01-01T00:00:00.000Z`, which reads as a real timestamp everywhere downstream.
718
+ Those writes still land in audit-managed tables. A Drizzle insert that omits `createdAt` / `modifiedAt` gets the insert time (Postgres `DEFAULT now()`; on SQLite the column's `$defaultFn`), but on SQLite nothing fills `createdBy` / `modifiedBy` — they stay `NULL`. (On Postgres the database's audit triggers fill them — see [How auto-injection works](#how-auto-injection-works-two-layers).) On SQLite the managed timestamps also carry a DDL default of the unix epoch (so `ALTER TABLE ADD COLUMN` works on populated tables), so **raw SQL** that omits them does not fail on `NOT NULL` — it silently persists `1970-01-01T00:00:00.000Z`, which reads as a real timestamp everywhere downstream.
710
719
 
711
720
  Spread the stamp instead of hand-writing four columns at each call site:
712
721
 
@@ -756,6 +765,14 @@ The scoped `db` an action receives types every managed key as `?: never` on `.in
756
765
 
757
766
  The runtime layer **hard-stamps** every audit field on every write, so the audit log can never be forged by a crafted request body or by a client echoing a row back into a PATCH.
758
767
 
768
+ On Postgres the RLS migration adds a database-side backstop: `BEFORE INSERT` / `BEFORE UPDATE` triggers on every feature table (`public.set_audit_fields_on_insert()` / `_on_update()`). They set `created_at` / `modified_at` to the database's `now()` and apply the same actor rule as the wrapper — the actor column always names whoever did the write:
769
+
770
+ - a verified caller (`auth.user_id()`) always wins, so no request can write someone else's id;
771
+ - with no verified caller — a `scope:` principal, a delegated principal, the service lane, a `system:` actor — the actor the Worker already stamped is kept;
772
+ - only a write that carries no actor at all (raw SQL) gets `system:<database role>`.
773
+
774
+ `created_at` / `created_by` never change on update.
775
+
759
776
  Because the value would be discarded anyway, the generated `db` handle refuses it at the type level: on the scoped `db`, `.insert().values()` types `createdAt` / `modifiedAt` / `createdBy` / `modifiedBy` / `deletedAt` / `deletedBy` as `?: never`, and `.update().set()` types the audit quartet plus `deletedBy` the same way. Supplying one is a **compile error** — not a silent discard.
760
777
 
761
778
  ```ts
@@ -771,7 +788,7 @@ Drop the keys and let the wrapper write them from `ctx.userId` and the actual wr
771
788
 
772
789
  One deliberate exception: `.set({ deletedAt: ... })` **is** allowed on update — that assignment is the soft-delete signal, and the stored value is normalized to the write moment and the verified caller. The raw `unsafeDb` handle an `unsafe:` action receives is unwrapped Drizzle and carries none of these type fences.
773
790
 
774
- What the caller is responsible for: the domain fields. (`id` auto-fills via the column's `$defaultFn` — `q.id()` and injected ids both carry one.)
791
+ What the caller is responsible for: the domain fields. (`id` auto-fills via the column's `$defaultFn` — `q.id()` and injected ids both carry one, and the typed `db` treats `id` as optional on insert for every id strategy except `serial` and `false`.)
775
792
 
776
793
  What the caller does *not* need to set: `id`, the scope column, or any of the audit fields, ever.
777
794
 
@@ -248,6 +248,9 @@ an [action](/define/actions/scoped-db#reaching-better-auth-tables-authdb).
248
248
  write's promise resolves. They may be `async`. A throw surfaces as
249
249
  `TRIGGER_AFTER_FAILED` (500) with `details.committed: true` — the row was
250
250
  already persisted (no transactions on D1), so clients must not blind-retry.
251
+ The hook's error message is logged; the response's error text is the
252
+ generic `After-trigger failed` unless the worker sets
253
+ [`EXPOSE_ERROR_STACK`](/api/errors#exposing-error-details-in-dev--staging).
251
254
  - Handlers must be **inline arrow/function expressions**. Imports they
252
255
  reference are hoisted into the generated registry (`src/lib/trigger-hooks.ts`)
253
256
  with relative paths rewritten from the table file — including dynamic