@quickback-dev/cli 0.66.11 → 0.66.12

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/deploy.d.ts.map +1 -1
  2. package/dist/commands/deploy.js +14 -0
  3. package/dist/commands/deploy.js.map +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/lib/api-client.d.ts +8 -0
  6. package/dist/lib/api-client.d.ts.map +1 -1
  7. package/dist/lib/api-client.js.map +1 -1
  8. package/dist/lib/deployment-target.d.ts +29 -0
  9. package/dist/lib/deployment-target.d.ts.map +1 -1
  10. package/dist/lib/deployment-target.js +26 -2
  11. package/dist/lib/deployment-target.js.map +1 -1
  12. package/dist/lib/deployment-target.test.js +37 -1
  13. package/dist/lib/deployment-target.test.js.map +1 -1
  14. package/dist/lib/migrations/drizzle.test.js +1 -1
  15. package/dist/lib/migrations/drizzle.test.js.map +1 -1
  16. package/dist/lib/migrations/plan.js +6 -0
  17. package/dist/lib/migrations/plan.js.map +1 -1
  18. package/dist/lib/migrations/postprocessors/better-auth-upgrade.d.ts +16 -5
  19. package/dist/lib/migrations/postprocessors/better-auth-upgrade.d.ts.map +1 -1
  20. package/dist/lib/migrations/postprocessors/better-auth-upgrade.js +32 -102
  21. package/dist/lib/migrations/postprocessors/better-auth-upgrade.js.map +1 -1
  22. package/dist/lib/migrations/postprocessors/index.d.ts.map +1 -1
  23. package/dist/lib/migrations/postprocessors/index.js +73 -1
  24. package/dist/lib/migrations/postprocessors/index.js.map +1 -1
  25. package/dist/lib/migrations/postprocessors/index.test.js +95 -0
  26. package/dist/lib/migrations/postprocessors/index.test.js.map +1 -1
  27. package/dist/lib/migrations/postprocessors/trigger-sql.d.ts +18 -0
  28. package/dist/lib/migrations/postprocessors/trigger-sql.d.ts.map +1 -1
  29. package/dist/lib/migrations/postprocessors/trigger-sql.js +63 -0
  30. package/dist/lib/migrations/postprocessors/trigger-sql.js.map +1 -1
  31. package/dist/lib/migrations/types.d.ts +1 -1
  32. package/dist/lib/migrations/types.d.ts.map +1 -1
  33. package/dist/lib/migrations/types.js +1 -0
  34. package/dist/lib/migrations/types.js.map +1 -1
  35. package/dist/skill/docs/define/actions/scoped-db.md +3 -0
  36. package/dist/skill/docs/define/schema.md +58 -6
  37. package/dist/skill/docs/define/triggers.md +143 -20
  38. package/dist/skill/docs/platform/auth/index.md +37 -16
  39. package/dist/skill/docs/platform/auth/plugins/subscriptions.md +25 -5
  40. package/dist/skill/docs/platform/database/neon.md +115 -18
  41. package/dist/skill/docs/platform/database/planetscale-postgres.md +3 -3
  42. package/dist/skill/docs/platform/storage/r2.md +75 -8
  43. package/dist/skill/docs/tooling/output.md +49 -5
  44. package/package.json +2 -1
  45. package/src/skill/docs/define/actions/scoped-db.md +3 -0
  46. package/src/skill/docs/define/schema.md +58 -6
  47. package/src/skill/docs/define/triggers.md +143 -20
  48. package/src/skill/docs/platform/auth/index.md +37 -16
  49. package/src/skill/docs/platform/auth/plugins/subscriptions.md +25 -5
  50. package/src/skill/docs/platform/database/neon.md +115 -18
  51. package/src/skill/docs/platform/database/planetscale-postgres.md +3 -3
  52. package/src/skill/docs/platform/storage/r2.md +75 -8
  53. package/src/skill/docs/tooling/output.md +49 -5
@@ -449,6 +449,20 @@ content-addressed `<idx>_quickback_rls_<hash>` migration, so one
449
449
  appends a new entry — recompiles with unchanged security append nothing. No
450
450
  manual SQL application step exists.
451
451
 
452
+ ### The default index set
453
+
454
+ Indexes are Drizzle's, not the security migration's: the compiler writes the
455
+ default set (tenant composite, FK columns, filtered columns, view-sortable
456
+ columns) into the schema source, so drizzle-kit generates and diffs them under
457
+ `<table>_<column>_idx` names. See
458
+ [The default index set](/define/schema#the-default-index-set) for the rules and
459
+ the `...q.indexes(t)` placeholder.
460
+
461
+ Older projects also carry `idx_<table>_<column>` copies the security migration
462
+ used to create. Those are dropped in the security migration's trailing
463
+ "retired indexes" section, which the journal runs after the schema migration
464
+ that created the replacements. Only `idx_*` names are dropped.
465
+
452
466
  Quickback also dependency-orders Drizzle's standalone constraint replacements.
453
467
  When a composite unique or primary key and its consuming foreign key are both
454
468
  replaced, the generated migration drops the dependent foreign key first, drops
@@ -530,15 +544,25 @@ owner's row. It is the floor under the application, not a second application.
530
544
  Quickback lowers your `firewall` config — and only your `firewall` config —
531
545
  into policies that read the transaction-local claims described above through
532
546
  `auth.user_id()`, `get_active_org_id()`, `get_active_team_id()`, `get_scope()`
533
- and the `get_principal_*()` helpers. Each feature table gets exactly four
534
- policies:
547
+ and the `get_principal_*()` helpers. Each feature table gets exactly three
548
+ policies, plus a fourth only where a delegated-principal lane is declared:
535
549
 
536
550
  | Policy | Kind | What it does |
537
551
  |--------|------|--------------|
538
- | `<table>_deny_anon` | RESTRICTIVE `FOR ALL` | Blocks any query carrying neither a stamped user id, nor a verified delegated/scope principal, nor the service marker |
552
+ | `<table>_deny_anon` | RESTRICTIVE `FOR ALL` | Blocks any query carrying neither a stamped user id, nor the service marker — nor, on a table with a delegated lane, a verified delegated/scope principal |
539
553
  | `<table>_service_role` | permissive `FOR ALL` | Admits Worker-internal contexts — see [Background jobs and cross-tenant actions](#background-jobs-and-cross-tenant-actions) |
540
- | `<table>_principal_fence` | RESTRICTIVE `FOR ALL` | Caps every permissive policy, so no policy can broaden a request that carries the wrong principal type |
541
- | `<table>_scope` | permissive `FOR ALL` | The firewall scope predicate. `USING` also requires `deleted_at IS NULL` on soft-deletable tables; `WITH CHECK` is the scope predicate alone, so a row can be soft-deleted but never resurrected |
554
+ | `<table>_scope` | permissive `FOR ALL` | The firewall scope predicate. On a soft-deletable table `USING` also requires `deleted_at IS NULL OR public.in_soft_delete()` — see [The soft-delete lane](#the-soft-delete-lane); `WITH CHECK` is the scope predicate alone, so a row can be soft-deleted but never resurrected |
555
+ | `<table>_principal_fence` | RESTRICTIVE `FOR ALL` | **Only on tables with a `databaseAccess` lane or `access.principals`.** Caps every permissive policy, so no policy can broaden a request that carries the wrong principal type |
556
+
557
+ The fence is per-lane, not per-table, because on a table no principal can reach
558
+ it would read `get_principal_type() IS NULL` — blocking every principal, which
559
+ is exactly what leaving them out of `deny_anon` already does. Two policies for
560
+ one outcome; the compiler emits neither.
561
+
562
+ Every helper call inside a policy predicate is emitted as `(SELECT …)`. The
563
+ claims are transaction-local and stamped before the statement, so PostgreSQL
564
+ hoists the call into an **InitPlan** and evaluates it once per statement instead
565
+ of once per scanned row.
542
566
 
543
567
  ```typescript
544
568
  firewall: [
@@ -552,13 +576,41 @@ ON "app"."documents" FOR ALL
552
576
  TO quickback
553
577
  USING (
554
578
  organization_id = public.get_active_org_id()
555
- AND deleted_at IS NULL
579
+ AND (deleted_at IS NULL OR public.in_soft_delete())
556
580
  )
557
581
  WITH CHECK (
558
582
  organization_id = public.get_active_org_id()
559
583
  );
560
584
  ```
561
585
 
586
+ ### The soft-delete lane
587
+
588
+ `deleted_at IS NULL` keeps soft-deleted rows out of every caller's reach. On its
589
+ own it also blocks the delete that put them there.
590
+
591
+ PostgreSQL applies a SELECT-applicable policy's `USING` expression to the **new**
592
+ row of an `UPDATE`, not only the existing one, whenever the statement reads the
593
+ relation — which any `UPDATE … WHERE` does. The new row of a soft delete has
594
+ `deleted_at` set, so a bare `deleted_at IS NULL` refuses the statement with
595
+ `42501`, including the generated `DELETE` route's own write. Moving the filter to
596
+ a `FOR SELECT` policy does not help, and neither does dropping `RETURNING`: the
597
+ check follows the filter wherever it goes.
598
+
599
+ So the filter carries a lane. `public.in_soft_delete()` reads the
600
+ transaction-local `quickback.soft_delete` marker, and the generated write
601
+ chokepoint sets it for **exactly** the statement whose payload stamps
602
+ `deletedAt` — the same condition that stamps the audit columns. It is a
603
+ one-shot token: the claims preamble carries it into that statement's
604
+ transaction and clears it, so the next statement of the same request runs
605
+ without it.
606
+
607
+ It is the same trust model as the service marker: Worker-set, never derived from
608
+ request input. And it is narrower — it exempts the soft-delete filter and
609
+ nothing else. Tenancy, ownership and scope stay ANDed beside it, so a statement
610
+ inside the window still cannot cross a tenant; `WITH CHECK` never carries the
611
+ lane, so it cannot land a row the firewall rejects; and the emitted statement
612
+ keeps `deleted_at IS NULL` in its own `WHERE`, so it cannot resurrect one.
613
+
562
614
  Exception tables (`firewall: [{ exception: true }]`) keep their permissive
563
615
  `<table>_all` policy, and SYSTEM tables — idempotency keys, the webhook store,
564
616
  Better Auth rate-limit counters, subscriptions, file metadata — stay
@@ -593,7 +645,8 @@ have to call still refuses them, and anything reaching the database outside a
593
645
  generated route holds a caller-scoped handle whose tenant is already fenced.
594
646
 
595
647
  The compiler enforces the shape at compile time. `QB-RLS-SCOPE-POLICY` requires
596
- all four policies, requires a tenant/owner/scope predicate in the scope policy's
648
+ the three policies (and the fence wherever a delegated lane exists — and only
649
+ there), requires a tenant/owner/scope predicate in the scope policy's
597
650
  `USING` clause, and **fails the build if any policy body calls `has_any_role`**.
598
651
  Opt out with `compiler.securityContracts.rls.requireScopePolicy: false` —
599
652
  `requireCrudPolicies` is the pre-016 name for the same key and is still honoured.
@@ -622,11 +675,14 @@ The retired names include the per-verb auth-table policies
622
675
  dropped, so an upgraded database converges on the narrower set rather than
623
676
  keeping a wider policy nobody emits any more.
624
677
 
625
- One leftover worth knowing: the redundant `idx_<table>_<column>` index the
626
- compiler used to infer alongside an index your schema already declared is no
627
- longer emitted, but an append-only security migration does not drop an index an
628
- older journal created. New databases get one index; existing ones keep the
629
- duplicate until you drop it yourself.
678
+ **Indexes are rebuilt once.** The compiler used to infer `idx_<table>_<column>`
679
+ indexes in the security migration, alongside the `<table>_<column>_idx` indexes
680
+ Drizzle generates from the schema. Drizzle now owns the whole default set, so
681
+ the schema migration creates the drizzle-managed index and the security
682
+ migration that follows it in the journal drops the compiler-owned copy — the two
683
+ overlap for the length of one `db:migrate` run and nothing is ever left
684
+ unindexed. Only `idx_*` names are dropped; a drizzle-managed index is never
685
+ touched. See [the default index set](#the-default-index-set).
630
686
 
631
687
  ### Delegated principal RLS
632
688
 
@@ -717,7 +773,7 @@ tenant predicate can never match), but it means a `databaseAccess` arm is never
717
773
  a place to write a restriction. A row that satisfies the arm is reachable even
718
774
  when the table firewall would not have matched it, and even when it is
719
775
  soft-deleted. Write the restriction in `firewall`; the restrictive
720
- `<table>_deny_anon` and `<table>_principal_fence` policies are the only arms
776
+ `<table>_deny_anon` and, where a lane is declared, `<table>_principal_fence` are the only arms
721
777
  that cap every lane. The fence also means a table admits a principal type only
722
778
  where its `access` (or its lane) names that type — a `ctx.principal.claims.*`
723
779
  firewall arm on a table whose access names no principal is unreachable.
@@ -937,6 +993,34 @@ precedent — so there is no separate `WEBHOOKS_DB` binding.
937
993
  (`requireOrgMember` / endpoint-ownership checks) before querying.
938
994
  - Webhooks require `connectionMode: 'http'`.
939
995
 
996
+ ## Managed file storage on Neon
997
+
998
+ `fileStorage: { managed: true }` is supported on `http` and `hyperdrive`. The
999
+ file metadata (`buckets`, `objects`) lives in a dedicated `files` Postgres
1000
+ schema of the **same** database — the `webhooks` precedent again — so there is
1001
+ no `FILES_DB` binding, no second drizzle config and no second migration target.
1002
+
1003
+ - The tables ride the project's single journal, reached through the
1004
+ `src/db/schema.ts` barrel.
1005
+ - Column shapes are 1:1 with the D1 version so no `/storage/v1/*` body changes:
1006
+ ISO-8601 date strings, JSON-encoded role and MIME lists, the same object keys
1007
+ and the same soft-delete column. The one divergence is numeric width —
1008
+ `size` and `file_size_limit` are `bigint`, because a Postgres `integer` would
1009
+ cap objects at 2 GiB.
1010
+ - The store is a SYSTEM table: RLS is enabled and forced with a single
1011
+ service-role policy, so only `createFilesDb()` (which wraps `createServiceDb`)
1012
+ can read or write it. There is no caller-scope policy and no role arm —
1013
+ public-versus-private file access is decided by the `/storage/v1/*` routes and
1014
+ the file-serving Worker before the handle is used, exactly as it was against
1015
+ the D1 binding.
1016
+ - The **file-serving Worker reads the same database over the same transport**:
1017
+ a `HYPERDRIVE` binding on Hyperdrive projects, or the same `DATABASE_URL`
1018
+ secret on HTTP projects — set on that Worker too. Never a mix of the two.
1019
+ - `connectionMode: 'websocket'` is rejected: it emits no `createServiceDb`.
1020
+
1021
+ See [File Storage](/platform/storage/r2) for the endpoints, bucket scopes and
1022
+ deployment steps.
1023
+
940
1024
  ## Encryption on Neon
941
1025
 
942
1026
  The encryption pillar — `.encrypted()` (envelope) and `.sealed()` /
@@ -1070,11 +1154,18 @@ Hyperdrive's connection pool.
1070
1154
  Anything not yet ported to Postgres is a compile-time error on Neon, never
1071
1155
  silently-broken output:
1072
1156
 
1073
- - **Managed file storage** (`fileStorage` with `managed: true`) is rejected — its
1074
- metadata store is a D1 database. Use presign-only R2 (the default, without
1075
- `managed`), which is provider-neutral and works on Neon today.
1076
- - **The Better Auth `subscriptions` plugin** is rejected until it gets
1077
- provider-aware db acquisition and a Postgres dialect schema.
1157
+ - **Managed file storage with `connectionMode: 'websocket'`** is rejected: the
1158
+ websocket db index emits no `createServiceDb`, and both `createFilesDb` and
1159
+ the file-serving Worker wrap that handle. Managed storage is supported on
1160
+ `http` and `hyperdrive` — the buckets/objects metadata lives in a `files`
1161
+ schema of this same database (one journal, no `FILES_DB` binding). See
1162
+ [File Storage](/platform/storage/r2).
1163
+ - **The Better Auth `subscriptions` plugin** is supported. Its table is created
1164
+ as `auth.subscriptions` in the same journal as everything else and is a SYSTEM
1165
+ table — service-role only, like the webhook store — because entitlement state
1166
+ is written by the Stripe queue consumer and the admin endpoints and read by
1167
+ tier-role resolution, all of which run on the internal service lane. Rejected
1168
+ on **WebSocket mode**, which emits no `createServiceDb`.
1078
1169
  - **Raw `sqliteTable` interop sources** on a Postgres target are rejected — write
1079
1170
  child tables with `pgTable` (see [below](#raw-drizzle-interop-tables-must-use-pg-core)).
1080
1171
  - **WebSocket mode** (deprecated) rejects webhooks, cross-tenant `unsafe`
@@ -1084,6 +1175,12 @@ silently-broken output:
1084
1175
 
1085
1176
  Mixed database providers (e.g. D1 auth + Neon features) remain unsupported.
1086
1177
 
1178
+ Table [`triggers`](/define/triggers) are supported in **both** lanes here. A
1179
+ `sql:` body is PL/pgSQL and lowers to a `SECURITY INVOKER` function plus its
1180
+ trigger in the `app` schema, so a cross-table write from a trigger stays
1181
+ subject to RLS and grants. Bodies are never translated between dialects — a
1182
+ SQLite `RAISE(ABORT, ...)` on this provider is a compile error.
1183
+
1087
1184
  ## Deploying
1088
1185
 
1089
1186
  ### Projects with no custom domain
@@ -181,9 +181,9 @@ never silently-broken output:
181
181
 
182
182
  | Feature | Status |
183
183
  |---------|--------|
184
- | Managed file storage (`managed: true`) | rejected — the file-metadata store is a D1 database |
185
- | Better Auth `subscriptions` plugin | rejected — its schema and db acquisition are D1-only |
186
- | Generated SQL triggers | not emitted on Postgres |
184
+ | 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 |
185
+ | Better Auth `subscriptions` plugin | supported — `auth.subscriptions` in the same journal, service-role only ([Subscriptions](/platform/auth/plugins/subscriptions#where-the-table-lives)) |
186
+ | Generated SQL triggers (`sql:`) | supported — PL/pgSQL bodies, `SECURITY INVOKER` (see [Triggers](/define/triggers)) |
187
187
  | `webhooksDatabaseId` / `webhooksDatabaseName` | rejected — D1-only keys; webhook tables live in the `webhooks` schema of the same database |
188
188
  | `connectionMode` of `'http'` or `'websocket'` | rejected — no such driver for this provider |
189
189
 
@@ -11,11 +11,23 @@ Quickback provides built-in file storage using Cloudflare R2.
11
11
  files worker.** You compute keys and store file references in your own table.
12
12
  Use this when you already have a media table and only need to sign large or
13
13
  confidential transfers — see [Presigned uploads](#presigned-uploads).
14
- - **Managed (`managed: true`)** — adds the turnkey subsystem on top: a FILES_DB
15
- metadata database (buckets + objects), the `/storage/v1/*` upload/download/
14
+ - **Managed (`managed: true`)** — adds the turnkey subsystem on top: a
15
+ metadata store (buckets + objects), the `/storage/v1/*` upload/download/
16
16
  manage endpoints, and a files worker for serving. Use this for listing photos,
17
17
  avatars, and other files that should be **public-if-you-have-the-link**.
18
18
 
19
+ Managed mode works on every database provider. Where the metadata lives depends
20
+ on which one you chose:
21
+
22
+ | Database | Metadata store | Migrations |
23
+ |---|---|---|
24
+ | `cloudflare-d1` | A second D1 database, bound as `FILES_DB` | Its own `drizzle.files.config.ts` and migration folder |
25
+ | `neon`, `planetscale-postgres` | A `files` schema in the **same** Postgres database as auth and feature data — no extra database, no binding | The project's single journal |
26
+
27
+ Nothing above the store moves: ids, object keys, JSON-encoded role and MIME
28
+ lists, ISO-8601 timestamps and soft deletion are identical, so every
29
+ `/storage/v1/*` request and response body is the same on both.
30
+
19
31
  ```ts
20
32
  // Presign-only (default) — ctx.storage against a bucket, nothing else
21
33
  defineFileStorage("cloudflare-r2", { bucketName: "my-app-media" })
@@ -117,7 +129,7 @@ export default {
117
129
  managed: true,
118
130
  binding: 'R2_BUCKET',
119
131
  bucketName: 'my-app-files',
120
- filesBinding: 'FILES_DB',
132
+ filesBinding: 'FILES_DB', // cloudflare-d1 only; ignored on Postgres
121
133
  maxFileSize: 10 * 1024 * 1024, // 10MB
122
134
  allowedTypes: ['image/jpeg', 'image/png', 'image/webp'],
123
135
  },
@@ -127,7 +139,7 @@ export default {
127
139
  ```
128
140
 
129
141
  > `managed: true` is what turns on everything on this page — the `/storage/v1/*`
130
- > routes, the files worker, and the `FILES_DB` metadata database. Without it R2
142
+ > routes, the files worker, and the metadata store. Without it R2
131
143
  > file storage is **presign-only**: the compiler signs requests against the
132
144
  > bucket by name and emits **no** bucket binding into `wrangler.toml`, so
133
145
  > `binding` and `filesBinding` are ignored and `env.R2_BUCKET` is `undefined`
@@ -379,6 +391,17 @@ https://files.yourdomain.com/public/org_abc/listings/3f2a…-hero.jpg
379
391
  Store that URL on the listing row. Send it to the public listing page. This is
380
392
  the right model for property photos, avatars, and shareable media.
381
393
 
394
+ No session is required, but the request is not unconditional: the files worker
395
+ looks the key up in the metadata store and serves bytes only when a live
396
+ (not soft-deleted) object exists in a bucket whose `readScope` is `public`.
397
+ Anything else is a **404**, not a 403 — an anonymous caller must not be able to
398
+ probe for private keys. So a soft-deleted public object stops being served, and
399
+ a key that merely *starts with* `public/` proves nothing on its own.
400
+
401
+ Public responses still carry `Cache-Control: public, max-age=31536000,
402
+ immutable`, so a CDN or browser that already has the bytes keeps them. Soft
403
+ deletion is not a revocation mechanism for something already fetched.
404
+
382
405
  ### Session-gated private files
383
406
 
384
407
  Private files require a valid Better Auth session cookie:
@@ -409,7 +432,9 @@ When file storage is configured, the compiler generates:
409
432
  |------|---------|
410
433
  | `src/storage/routes.ts` | Storage API routes (upload, presign, confirm, download) |
411
434
  | `src/storage/presign.ts` | R2 presigned-URL signer (`createPresigner`, backs `ctx.storage`) |
412
- | `src/files/schema.ts` | Files database schema (buckets, objects) |
435
+ | `src/files/schema.ts` | Files metadata schema (buckets, objects) — `sqliteTable` on D1, a `files` Postgres schema otherwise |
436
+ | `src/files/index.ts` | `createFilesDb` — the D1 binding handle, or the Postgres service-lane handle |
437
+ | `drizzle.files.config.ts` | Second migration target — **D1 only** |
413
438
  | `cloudflare-workers/files/index.ts` | Files worker for serving |
414
439
  | `cloudflare-workers/files/wrangler.toml` | Files worker config |
415
440
 
@@ -428,15 +453,20 @@ After compiling:
428
453
  wrangler r2 bucket create my-app-files
429
454
  ```
430
455
 
431
- 2. **Create the files database:**
456
+ 2. **Create the files database** — `cloudflare-d1` only. On Postgres the
457
+ metadata lives in the `files` schema of the database you already have:
432
458
  ```bash
433
459
  wrangler d1 create my-app-files
434
460
  ```
435
461
 
436
462
  3. **Run migrations:**
437
463
  ```bash
464
+ # cloudflare-d1
438
465
  wrangler d1 migrations apply my-app-files --local
439
466
  wrangler d1 migrations apply my-app-files --remote
467
+
468
+ # Postgres — the files schema is in the project's single journal
469
+ npm run db:migrate
440
470
  ```
441
471
 
442
472
  4. **Deploy the API:**
@@ -450,6 +480,18 @@ After compiling:
450
480
  wrangler deploy
451
481
  ```
452
482
 
483
+ `quickback deploy` ships the API Worker only and then prints this command —
484
+ managed file storage is two deployed Workers, and having shipped one but not
485
+ the other is a real state worth seeing.
486
+
487
+ On Postgres the files worker reads the **same** database over the **same**
488
+ transport as the API Worker: a `HYPERDRIVE` binding (already in its
489
+ `wrangler.toml`), or a `DATABASE_URL` secret you must also set on this
490
+ Worker:
491
+ ```bash
492
+ cd cloudflare-workers/files && wrangler secret put DATABASE_URL # HTTP only
493
+ ```
494
+
453
495
  6. **Set the R2 presign secrets** only if you use signed PUT/GET. Public-bucket
454
496
  uploads through `POST /object` do not need them. See
455
497
  [Presigned uploads](#presigned-uploads):
@@ -459,15 +501,40 @@ After compiling:
459
501
  wrangler secret put R2_SECRET_ACCESS_KEY
460
502
  ```
461
503
 
504
+ ### Named environments deploy two Workers per target
505
+
506
+ A project with [named environments](/configure/domains) must name the files
507
+ Worker for every target. It is never derived: the script name is the deployed
508
+ identity, and Wrangler's `routes` key is inheritable, so a shared
509
+ `<project>-files` default would let `deploy --env dev` replace production's file
510
+ server and take its hostname.
511
+
512
+ ```ts
513
+ environments: {
514
+ dev: { name: 'app-dev', filesWorker: { name: 'app-files-dev', domain: 'files-dev.example.com' }, /* … */ },
515
+ prod: { name: 'app', filesWorker: { name: 'app-files', domain: 'files.example.com' }, /* … */ },
516
+ }
517
+ ```
518
+
519
+ The compile fails with the config path to fix when a target omits it, or when
520
+ two targets claim the same Worker name or hostname. Omitting
521
+ `filesWorker.domain` emits `routes = []` — the explicit workers.dev-only
522
+ opt-out. The files Worker reuses that environment's R2 bucket and database
523
+ bindings; it does not declare its own.
524
+
525
+ ```bash
526
+ cd cloudflare-workers/files && npx wrangler deploy --env dev
527
+ ```
528
+
462
529
  ## Configuration Reference
463
530
 
464
531
  | Option | Type | Default | Description |
465
532
  |--------|------|---------|-------------|
466
- | `managed` | `boolean` | `false` | Opt into the FILES_DB subsystem + `/storage/v1/*` + files worker. Off = presign-only. |
533
+ | `managed` | `boolean` | `false` | Opt into the metadata store + `/storage/v1/*` + files worker. Off = presign-only. |
467
534
  | `bucketName` | `string` | `<project>-media` | R2 bucket the signer targets (override per-call with `signPutUrl(key, { bucket })`) |
468
535
  | `presign` | `object` | - | Env-var name overrides: `{ accountIdEnv, accessKeyIdEnv, secretAccessKeyEnv, endpointEnv }` |
469
536
  | `binding` | `string` | `R2_BUCKET` | R2 bucket binding name (managed mode) |
470
- | `filesBinding` | `string` | `FILES_DB` | Files metadata D1 binding (managed mode) |
537
+ | `filesBinding` | `string` | `FILES_DB` | Files metadata D1 binding (managed mode, `cloudflare-d1` only — Postgres uses the `files` schema of the single database and emits no binding) |
471
538
  | `maxFileSize` | `number \| string` | 10MB | Max upload size — bytes or `"100mb"` (managed mode) |
472
539
  | `allowedTypes` | `string[]` | Images only | Allowed MIME types (managed mode) |
473
540
  | `publicDomain` | `string` | - | Custom domain for files worker (managed mode) |
@@ -288,18 +288,62 @@ src/
288
288
 
289
289
  ### File Storage (R2)
290
290
 
291
- When `fileStorage` is configured:
291
+ When `fileStorage` is configured, presign-only mode emits just the signer:
292
292
 
293
293
  ```
294
294
  src/
295
- └── routes/
296
- └── storage.ts # File upload/download endpoints
295
+ └── storage/
296
+ └── presign.ts # R2 presigned-URL signer (backs ctx.storage)
297
+ ```
298
+
299
+ `managed: true` adds the API routes, the metadata schema and a **second
300
+ deployed Worker** with its own `wrangler.toml`:
301
+
302
+ ```
303
+ src/
304
+ ├── routes/storage.ts # File upload/download endpoints
305
+ └── files/
306
+ ├── schema.ts # buckets + objects
307
+ └── index.ts # createFilesDb
308
+ cloudflare-workers/
309
+ └── files/ # SECOND Worker — deployed separately
310
+ ├── index.ts # public + session-gated file serving
311
+ └── wrangler.toml # its own name, bindings and routes
312
+ ```
313
+
314
+ `cloudflare-workers/**` is included in the generated `tsconfig.json`, so
315
+ `npm run typecheck` covers both entrypoints.
316
+
317
+ Where the metadata lives, and therefore what else is emitted, depends on the
318
+ database provider:
319
+
320
+ | Provider | Metadata store | Extra output |
321
+ |---|---|---|
322
+ | `cloudflare-d1` | A second D1 database bound as `FILES_DB` | `drizzle.files.config.ts` + `quickback/drizzle/files/` |
323
+ | `neon`, `planetscale-postgres` | A `files` schema in the same Postgres database | none — the tables ride the single journal at `quickback/drizzle/` |
324
+
325
+ ```
297
326
  quickback/drizzle/
298
- └── files/ # File metadata migrations
327
+ └── files/ # File metadata migrations — cloudflare-d1 only
299
328
  ├── meta/
300
329
  └── 0000_*.sql
301
330
  ```
302
331
 
332
+ Under named environments the second Worker needs its own identity, declared per
333
+ target and never derived — a shared default would make `deploy --env dev`
334
+ overwrite production's file server, and Wrangler's inheritable `routes` would
335
+ take its hostname with it:
336
+
337
+ ```ts
338
+ environments: {
339
+ dev: { name: 'app-dev', filesWorker: { name: 'app-files-dev', domain: 'files-dev.example.com' }, /* … */ },
340
+ prod: { name: 'app', filesWorker: { name: 'app-files', domain: 'files.example.com' }, /* … */ },
341
+ }
342
+ ```
343
+
344
+ Omitting `filesWorker.domain` emits `routes = []` for that target — the explicit
345
+ workers.dev-only opt-out, so it cannot inherit a sibling's hostname.
346
+
303
347
  ### Webhooks
304
348
 
305
349
  When webhooks are enabled:
@@ -462,7 +506,7 @@ The CLI loads migration meta JSON from one location only — `<project>/quickbac
462
506
 
463
507
  - `quickback/drizzle/auth/meta/`
464
508
  - `quickback/drizzle/features/meta/`
465
- - `quickback/drizzle/files/meta/`
509
+ - `quickback/drizzle/files/meta/` (cloudflare-d1 managed file storage)
466
510
  - `quickback/drizzle/webhooks/meta/`
467
511
  - `quickback/drizzle/audit/meta/`
468
512
  - `quickback/drizzle/meta/` (single-database mode)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quickback-dev/cli",
3
- "version": "0.66.11",
3
+ "version": "0.66.12",
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",
@@ -47,6 +47,7 @@
47
47
  },
48
48
  "dependencies": {
49
49
  "@modelcontextprotocol/sdk": "^1.11.0",
50
+ "zod": "^3.25.76",
50
51
  "esbuild": "^0.27.2",
51
52
  "ora": "^9.0.0",
52
53
  "picocolors": "^1.0.0",
@@ -149,6 +149,9 @@ restriction: a row that satisfies the arm is reachable even when the table
149
149
  firewall would not have matched it, and even when it is soft-deleted.
150
150
  Restrictions belong in `firewall`. The restrictive `<table>_deny_anon` and
151
151
  `<table>_principal_fence` policies remain the only arms that cap every lane.
152
+ (The fence is emitted precisely because this table declares a lane; a table
153
+ with no `databaseAccess` and no `access.principals` gets neither the fence nor
154
+ the principal arm of `deny_anon`, which blocks every principal just the same.)
152
155
 
153
156
  ### What the compiler refuses, and why
154
157
 
@@ -636,19 +636,71 @@ The six audit/soft-delete columns are **overwritten** by the runtime wrapper —
636
636
  `id` (when `generateId` is not `false`) is **rejected at the edge** instead: it is omitted from the `.strict()` Zod body schema, so a body carrying it is a `400 VALIDATION_ERROR`, and the guards `createable` allow-list backstops that. Nothing overwrites `id` at the insert — the Zod/guards boundary is the protection. Under
637
637
  [`allowClientIds: true`](/api/crud#client-supplied-ids-optimistic-updates) a strategy-shaped `id` is accepted on create only.
638
638
 
639
- ## Auto-Indexes
639
+ ## The default index set
640
640
 
641
- The compiler injects performance-critical indexes you'd otherwise have to author by hand. The pass runs after audit-field injection (so `deletedAt` is present) and is idempotent — if you already declared a matching index it's left alone.
641
+ Drizzle owns every index in a Quickback project. The compiler writes a default
642
+ set into your schema source before drizzle-kit reads it, so the indexes are
643
+ generated, diffed and dropped by the same journal as your tables — there is no
644
+ second emitter putting indexes in the security migration.
645
+
646
+ The pass runs after audit-field injection (so `deletedAt` and `createdAt` are
647
+ present) and is idempotent.
642
648
 
643
649
  | Trigger | Index | Why |
644
650
  |---------|-------|-----|
645
- | Tenant column (`organizationId` / `organisationId` / `userId`) + `deletedAt` | Composite `(<isolation_col>, deletedAt)` | Every list query filters by isolation AND `deletedAt IS NULL` — a composite index lets D1/SQLite prune both predicates in one btree walk. |
651
+ | Tenant column (`organizationId` / `organisationId` / `userId`) + `deletedAt` | Composite `(<isolation_col>, deletedAt)` | Every list query filters by isolation AND `deletedAt IS NULL` — a composite index lets the planner prune both predicates in one btree walk. |
646
652
  | Any FK column (`.references(() => other.id)`) | Single-column `(<fk_col>)` | SQLite/D1 don't auto-index FK columns, and the generated FK existence checks read by id on the parent. |
647
- | Any column that appears in a view's `read.query.sortable` allowlist (or `defaultSort`) | Single-column `(<col>)` | Sort scans go through an index instead of a full-table scan. |
653
+ | A filtered column — anything named `*status*` or `*type*`, the boolean flags (`isActive`, `isDefault`, …) and the date columns (`createdAt`, `startDate`, `endDate`, `expiresAt`, …) | Single-column `(<col>)` | These are what list endpoints filter and order on. |
654
+ | Any column in a view's `read.query.sortable` allowlist (or `defaultSort`) | Single-column `(<col>)` | Sort scans go through an index instead of a full-table scan. |
655
+
656
+ Entries are named `<table>_<col>_idx` (or `<table>_<col1>_<col2>_idx` for a
657
+ composite) and emitted into the table's Drizzle extras callback. The `index`
658
+ import is added to your schema's `drizzle-orm/<dialect>-core` import line if it
659
+ isn't already there.
660
+
661
+ ### Coverage — what suppresses a default index
662
+
663
+ A default index is skipped when a **non-partial** index already has its columns
664
+ as a **leading prefix**. So the tenant composite `(organizationId, deletedAt)`
665
+ suppresses a bare `(organizationId)` index, and an index you author yourself
666
+ suppresses the default on the same columns:
667
+
668
+ - **Leading prefix wins.** `(organizationId, deletedAt, status)` covers
669
+ `(organizationId)` and `(organizationId, deletedAt)`, but not `(status)` —
670
+ `status` is not a leading column.
671
+ - **Unique counts.** A `uniqueIndex` on the same leading columns serves the same
672
+ lookups, so it suppresses the non-unique default.
673
+ - **Partial covers nothing.** An index with `.where(...)` may exclude the rows
674
+ the default index exists for, so it never suppresses one.
675
+ - **Order modifiers are ignored.** `.on(t.status.desc())` still covers
676
+ `(status)`.
677
+
678
+ ### `...q.indexes(t)` — placing the defaults yourself
679
+
680
+ In a **Drizzle interop** table you can declare exactly where the default set
681
+ lands, the same way `...q.audit()` declares the audit columns:
682
+
683
+ {/* doc-compile: skip — illustrative fragment; the columns object is elided so the placeholder is the whole point. */}
684
+ ```typescript
685
+ import { pgTable, uniqueIndex } from "drizzle-orm/pg-core";
686
+ import { q } from "@quickback/compiler";
687
+
688
+ export const invoices = pgTable("invoices", {
689
+ // …columns
690
+ }, (t) => ({
691
+ ...q.indexes(t),
692
+ invoices_number_unique: uniqueIndex("invoices_number_unique").on(t.number),
693
+ }));
694
+ ```
648
695
 
649
- Indexes are emitted into the table's Drizzle extras callback (`(t) => ({ ... })`) and named `<table>_<col>_idx` (or `<table>_<col1>_<col2>_idx` for the composite). The `index` import is added to your schema's `drizzle-orm/<dialect>-core` import line if it isn't already there.
696
+ The spread is expanded in place at compile time into literal
697
+ `index(...).on(...)` entries and disappears from the emitted schema. Without it
698
+ the same entries are appended to the end of the callback and a compile warning
699
+ points you here — the emitted schema is identical either way.
650
700
 
651
- You can opt out of any auto-injected index by declaring your own with the same name or column set — the injector treats both as already-present and skips.
701
+ Tables authored with the `q` DSL (`feature()` / `q.table()`) don't take the
702
+ placeholder: the compiler writes their index callback, and `q.<col>().index()`
703
+ and `q.table(…, { indexes })` are the authoring controls there.
652
704
 
653
705
  ## Ownership Fields
654
706