@quickback-dev/cli 0.66.19 → 0.66.21

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 (44) hide show
  1. package/dist/commands/migrate.js +2 -2
  2. package/dist/commands/migrate.js.map +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/skill/SKILL.md +18 -0
  5. package/dist/skill/docs/api/actions.md +1 -1
  6. package/dist/skill/docs/api/errors.md +8 -0
  7. package/dist/skill/docs/api/query-params.md +2 -0
  8. package/dist/skill/docs/api/typescript.md +5 -1
  9. package/dist/skill/docs/configure/providers.md +5 -2
  10. package/dist/skill/docs/define/actions/defining.md +17 -7
  11. package/dist/skill/docs/define/actions/index.md +17 -2
  12. package/dist/skill/docs/define/actions/record-and-standalone.md +53 -0
  13. package/dist/skill/docs/define/actions/scoped-db.md +22 -1
  14. package/dist/skill/docs/define/changesets.md +24 -4
  15. package/dist/skill/docs/define/firewall.md +39 -0
  16. package/dist/skill/docs/define/relationships.md +9 -0
  17. package/dist/skill/docs/define/schema.md +34 -1
  18. package/dist/skill/docs/define/transitions.md +3 -1
  19. package/dist/skill/docs/define/triggers.md +2 -1
  20. package/dist/skill/docs/platform/database/neon.md +110 -30
  21. package/dist/skill/docs/platform/webhooks/inbound.md +20 -7
  22. package/dist/skill/docs/tooling/cli.md +28 -7
  23. package/dist/skill/docs/tooling/output.md +4 -2
  24. package/package.json +1 -1
  25. package/src/skill/SKILL.md +18 -0
  26. package/src/skill/docs/api/actions.md +1 -1
  27. package/src/skill/docs/api/errors.md +8 -0
  28. package/src/skill/docs/api/query-params.md +2 -0
  29. package/src/skill/docs/api/typescript.md +5 -1
  30. package/src/skill/docs/configure/providers.md +5 -2
  31. package/src/skill/docs/define/actions/defining.md +17 -7
  32. package/src/skill/docs/define/actions/index.md +17 -2
  33. package/src/skill/docs/define/actions/record-and-standalone.md +53 -0
  34. package/src/skill/docs/define/actions/scoped-db.md +22 -1
  35. package/src/skill/docs/define/changesets.md +24 -4
  36. package/src/skill/docs/define/firewall.md +39 -0
  37. package/src/skill/docs/define/relationships.md +9 -0
  38. package/src/skill/docs/define/schema.md +34 -1
  39. package/src/skill/docs/define/transitions.md +3 -1
  40. package/src/skill/docs/define/triggers.md +2 -1
  41. package/src/skill/docs/platform/database/neon.md +110 -30
  42. package/src/skill/docs/platform/webhooks/inbound.md +20 -7
  43. package/src/skill/docs/tooling/cli.md +28 -7
  44. package/src/skill/docs/tooling/output.md +4 -2
@@ -123,7 +123,9 @@ Semantics:
123
123
  - **`field: null`** declares a pure stamp transition (check-in/check-out
124
124
  style) — guards + stamps with no state column.
125
125
  - **`actx.now`**: every action's execute context now carries `now` — one ISO
126
- timestamp per invocation. Prefer it over `new Date().toISOString()`.
126
+ timestamp per invocation. Prefer it over `new Date().toISOString()`. It
127
+ writes into a `q.timestamp()` column as-is, on every database and every
128
+ `db` handle — see [Column types](/define/schema#decimals-dates-64-bit-integers-and-arrays).
127
129
 
128
130
  ### On a feature-area route
129
131
 
@@ -372,5 +372,6 @@ execute: async ({ db, effects }) => {
372
372
 
373
373
  Effects enqueued by an `execute` that later throws are dropped. The context
374
374
  also carries `now` — one ISO timestamp per invocation; prefer it over
375
- `new Date().toISOString()`.
375
+ `new Date().toISOString()`. See [Column types](/define/schema#decimals-dates-64-bit-integers-and-arrays) for
376
+ writing it into a `q.timestamp()` column.
376
377
 
@@ -42,11 +42,16 @@ so an extra database silently splits the bootstrap: the roles look right in
42
42
  separating. Two apps means two Neon projects, not two databases.
43
43
 
44
44
  Mixing providers — for example D1 for auth with Neon for features — is not
45
- supported. The per-service config form is rejected at compile time:
45
+ supported. The per-service config form is a type error under `quickback check`
46
+ (the config type has no `auth` / `features` keys) and is rejected at compile
47
+ time:
46
48
 
47
49
  ```
48
- providers.database service-map form is not supported in v2.
49
- Configure one database provider; auth and feature data use the same database.
50
+ providers.database service-map form is not supported in v2 ({ auth, features } is the retired v1 shape).
51
+ Configure ONE database provider — auth and feature data share it:
52
+ database: defineDatabase("cloudflare-d1", { ... }) or database: { name: "neon", config: { ... } }.
53
+ On D1, auth keeps its own database by default (splitDatabases: true);
54
+ name the bindings with authBinding / featuresBinding.
50
55
  ```
51
56
 
52
57
  ## Configuration
@@ -599,8 +604,12 @@ WITH CHECK (
599
604
 
600
605
  ### The soft-delete lane
601
606
 
602
- `deleted_at IS NULL` keeps soft-deleted rows out of every caller's reach. On its
603
- own it also blocks the delete that put them there.
607
+ `deleted_at IS NULL` keeps soft-deleted rows out of every caller's reach. It is
608
+ in the scope policy of every table that carries `deleted_at`, exactly where the
609
+ API firewall adds its own `isNull(deletedAt)` — including a `firewall: [...]`
610
+ array that never mentions `deletedAt` (declare a predicate on `deletedAt`
611
+ yourself to take it over). On its own it also blocks the delete that put them
612
+ there.
604
613
 
605
614
  PostgreSQL applies a SELECT-applicable policy's `USING` expression to the **new**
606
615
  row of an `UPDATE`, not only the existing one, whenever the statement reads the
@@ -819,6 +828,17 @@ USING (owner_id = auth.user_id())
819
828
  WITH CHECK (owner_id = auth.user_id());
820
829
  ```
821
830
 
831
+ **Relationship-scoped** (`{ field: 'projectId', via: 'projectMemberOf' }`) — see
832
+ [Relationship arms in SQL](#relationship-arms-in-sql):
833
+
834
+ ```sql
835
+ CREATE POLICY "tasks_scope" ON "app"."tasks" FOR ALL TO quickback
836
+ USING (organization_id = public.get_active_org_id()
837
+ AND project_id IN (SELECT r.project_id FROM public.qb_rel_project_member_of() r))
838
+ WITH CHECK (organization_id = public.get_active_org_id()
839
+ AND project_id IN (SELECT r.project_id FROM public.qb_rel_project_member_of() r));
840
+ ```
841
+
822
842
  **Exception tables** (`firewall: [{ exception: true }]`) — no scope predicate,
823
843
  so the restrictive deny-anon policy is the only fence left:
824
844
 
@@ -827,6 +847,77 @@ CREATE POLICY "categories_all" ON "app"."categories" FOR ALL TO quickback
827
847
  USING (true) WITH CHECK (true);
828
848
  ```
829
849
 
850
+ ### Relationship arms in SQL
851
+
852
+ Every relationship lookup is enforced by the database, and the generated API
853
+ reads through the same place. Each declared relationship gets one helper,
854
+ emitted in the RLS migration ahead of the policies that call it:
855
+
856
+ ```sql
857
+ CREATE OR REPLACE FUNCTION public.qb_rel_project_member_of()
858
+ RETURNS SETOF "app"."project_members"
859
+ LANGUAGE sql STABLE SECURITY DEFINER SET search_path = ''
860
+ AS $$
861
+ SELECT a.*
862
+ FROM "app"."project_members" a
863
+ WHERE a."user_id" = auth.user_id()
864
+ AND a."deleted_at" IS NULL
865
+ $$;
866
+ ALTER FUNCTION public.qb_rel_project_member_of() OWNER TO quickback_owner;
867
+ REVOKE ALL ON FUNCTION public.qb_rel_project_member_of() FROM PUBLIC;
868
+ GRANT EXECUTE ON FUNCTION public.qb_rel_project_member_of() TO quickback;
869
+ ```
870
+
871
+ The scope policy calls it as
872
+ `"project_id" IN (SELECT r."project_id" FROM public.qb_rel_project_member_of() r)`,
873
+ and so does the generated API: a firewall `via:` arm, a relationship-role access
874
+ check, the action resolver's match row, the `/scope/v1/enter` probe and the
875
+ ws-ticket probe all read the caller's relationship rows from the helper, never
876
+ from the relationship table under its own policy.
877
+
878
+ - **Same lookup as D1.** The body is the relationship subquery the API runs on
879
+ D1: the subject column against the caller's claim, the `where:` literals
880
+ (SQL-quoted), and the related table's soft-delete filter — the API's
881
+ `skipTenantScopes` body. Multi-hop (`hops`) relationships join the same chain
882
+ and return the first hop's rows.
883
+ - **Why `SECURITY DEFINER`.** Under the relationship table's own policy the
884
+ lookup would recurse for a relationship that reads the table it protects
885
+ (`projectMemberOf` on `project_members`), and the table's tenant scope would
886
+ zero a caller with no active org — the case the API skips on purpose. The
887
+ helper runs as `quickback_owner`, which reads the related table through one
888
+ `<table>_quickback_owner_read` policy (`FOR SELECT TO quickback_owner USING (true)`).
889
+ Feature tables `FORCE ROW LEVEL SECURITY`, so the owner needs it; it grants
890
+ nothing new — an owner can always lift `FORCE` on its own table — and the
891
+ runtime role `quickback` is not a member of `quickback_owner`.
892
+ - **Locked down.** `search_path = ''` and fully-qualified names; `EXECUTE` is
893
+ revoked from `PUBLIC` and granted to `quickback` only. The caller comes from
894
+ the transaction's claims, so a lookup on the service handle (no caller)
895
+ returns nothing.
896
+ - **Evaluated once per statement.** The helper takes no arguments, so
897
+ `col IN (SELECT … FROM helper() r)` is an uncorrelated subquery — one hashed
898
+ subplan per statement, the same InitPlan discipline as the claim helpers. A
899
+ per-row `helper(row.col)` call could never be inlined.
900
+ - **Returns the table's own rows.** One helper serves every projection a lookup
901
+ needs (the resource column, the tenant columns the action resolver stamps,
902
+ scope sub-keys), and `CREATE OR REPLACE` stays valid as the table's columns
903
+ change. A helper whose relationship now returns a different table is dropped
904
+ first — with the generated policies that call it, which the same migration
905
+ re-creates.
906
+ - **Tenant binding.** Beside an org arm in an `any:` group the arm becomes
907
+ `(project_id IN (SELECT …) AND (organization_id = <active org> OR <no active org>))`
908
+ — exactly where the API applies the same binding.
909
+ - **Permissions.** A `{ permission }` arm expands as the API expands it; arrow
910
+ hops become `qb_arrow_…` helpers (recursive arrows are a `maxDepth`-bounded
911
+ closure that re-checks the tenant on every row), called by the API too.
912
+ - **Still API-only.** Literal status filters (a conjunct would refuse
913
+ status-changing updates, because PostgreSQL checks an UPDATE's new row against
914
+ the read policy) and claims the Worker never writes into the transaction —
915
+ `ctx.scope.<kind>.<subKey>`, area anchors such as `ctx.event.id`, and
916
+ relationships whose `subject` binds one. These lower to `true` in the policy,
917
+ and the API keeps the table query for such a relationship.
918
+
919
+ Helpers no compile references any more are dropped at the end of the migration.
920
+
830
921
  ### Helper functions
831
922
 
832
923
  | Function | Purpose |
@@ -963,31 +1054,20 @@ is a compile error everywhere, not a Neon-only concern.
963
1054
 
964
1055
  ### How the read is served
965
1056
 
966
- On **Neon**, a via-relationship reachability predicate cannot be expressed as an
967
- RLS policy — the correlated multi-hop join reaches across intermediate tables
968
- that each `FORCE ROW LEVEL SECURITY`, so caller-claims RLS would deny the attendee
969
- to *zero* rows before the app-layer WHERE ever runs. Quickback resolves this by
970
- routing that resource's **read** handlers through the service-role handle
971
- (`createServiceDb(c.env)`) instead of the caller-claims client. RLS stops denying,
972
- and the compiled `buildFirewallConditions(...)` reachability WHERE — the exact
973
- same clause D1 uses — becomes the **sole** row filter.
974
-
975
- This is the D1 trust model, applied to Neon for exactly these reads: the
976
- application layer is the firewall, and RLS is a coarse tenant backstop that steps
977
- aside where it cannot express the grant. It is surgical and fail-closed:
978
-
979
- - Only the affected resource's reads swap handles. **Org / owner / team reads keep
980
- caller claims + the RLS backstop** — they resolve to policies RLS *can* express.
981
- - The swap is gated on a non-empty firewall carrying the reachability predicate;
982
- a service-handle read with no WHERE is a compile error (it would return every
983
- tenant's rows). Fail closed.
984
- - It applies to the **collection `GET /`, `GET /:id`, and views** alike. **Writes
985
- are unchanged** — creates/updates/deletes keep caller claims and the RLS
986
- backstop.
987
-
988
- The **same config compiles identically on D1**, where there is no RLS to bypass:
989
- the read handlers keep `c.get('db')` and the app-layer reachability WHERE was
990
- already the whole story.
1057
+ Reads keep the **caller-claims** handle and the full RLS backstop, on Neon as
1058
+ everywhere else. The reachability WHERE (`buildFirewallConditions(...)`) and the
1059
+ resource's scope policy both call the relationship's
1060
+ [helper](#relationship-arms-in-sql), which walks the hop chain without the
1061
+ intermediate tables' tenant policies — so an attendee with no active org gets
1062
+ exactly their reachable rows, from the API and from the database alike.
1063
+
1064
+ Earlier releases routed these reads through the service-role handle
1065
+ (`createServiceDb`) instead, because the multi-hop join read the intermediate
1066
+ tables under their own tenant scopes and came back empty. That bypassed RLS for
1067
+ the whole read; the routing is gone.
1068
+
1069
+ The **same config compiles identically on D1**: the read handlers keep
1070
+ `c.get('db')`, and the app-layer reachability WHERE runs the join directly.
991
1071
 
992
1072
  ## Webhooks on Neon
993
1073
 
@@ -352,23 +352,36 @@ provider signed, never over re-serialised JSON.
352
352
  {/* doc-compile: skip — excerpt: `decryptValue` and the `connections` table live in the generated project; the fence shows the shape only. */}
353
353
  ```ts title="quickback/features/comms/actions/resendEvents.ts"
354
354
  import { z } from "zod";
355
- import { defineAction } from "../.quickback/define-action";
355
+ import { eq } from "drizzle-orm";
356
+ import { defineAction, ActionError } from "../.quickback/define-action";
356
357
  import { decryptValue } from "../../../../src/lib/encryption";
358
+ import { connections } from "../connections";
357
359
 
358
360
  export default defineAction({
359
361
  description: "Per-org Resend events — secret lives on the connection row",
360
- path: "/resend/events/:orgId",
362
+ path: "/resend/events/:connectionId",
361
363
  method: "POST",
362
364
  access: { roles: ["PUBLIC"] },
365
+ // A webhook carries no session, so no org claim: the scoped `db` reads
366
+ // nothing from an org-scoped table. Look the org up with `unsafeDb`, then
367
+ // pin every later query to it with `scopeTo`. `crossTenant: false` — the
368
+ // default (true) requires a sysadmin session and would 403 every delivery.
369
+ unsafe: { reason: "Resend webhook — tenant resolved from the connection row", crossTenant: false },
363
370
  rawBody: true,
364
371
  input: z.object({ type: z.string(), data: z.record(z.unknown()) }),
365
- execute: async ({ c, env, db, rawBody, input }) => {
366
- const orgId = c.req.param("orgId");
367
- const row = await db.query.connections.findFirst({ where: (t, { eq }) => eq(t.organizationId, orgId) });
372
+ execute: async ({ c, env, unsafeDb, rawBody, input }) => {
373
+ const [conn] = await unsafeDb.select().from(connections)
374
+ .where(eq(connections.id, c.req.param("connectionId")));
375
+ if (!conn) throw new ActionError("Unknown connection", "NOT_FOUND", 404);
376
+
368
377
  // ctx.crypto is hydrated for authenticated requests only — a PUBLIC
369
378
  // action reads an .encrypted() column through decryptValue directly.
370
- const secret = await decryptValue(env, db, orgId, row.signingSecret);
371
- // verify `rawBody` + the provider's signature headers with `secret`; throw a 401 ActionError on failure
379
+ const secret = await decryptValue(env, unsafeDb, conn.organizationId, conn.signingSecret);
380
+ // verify `rawBody` + the provider's signature headers with `secret`;
381
+ // throw a 401 ActionError on failure — BEFORE touching any tenant data.
382
+
383
+ const db = unsafeDb.scopeTo({ organizationId: conn.organizationId });
384
+ // every query on `db` now carries that org's firewall; inserts are stamped with it
372
385
  return { ok: true, type: input.type };
373
386
  },
374
387
  });
@@ -135,7 +135,29 @@ generated typing surfaces:
135
135
  surface. `import { feature, q, defineTable, defineConfig } from
136
136
  "@quickback/compiler"` resolves in table files and `quickback.config.ts`,
137
137
  so a bad builder call or an unknown resource-config key is a type error at
138
- the desk, not a compile-round-trip later.
138
+ the desk, not a compile-round-trip later. `services/` files' `import {
139
+ defineQueue } from "quickback"` resolves to the same surface, and provider
140
+ entries type-check in both forms the build accepts — `defineDatabase(...)`
141
+ or the literal `{ name: "neon", config: { … } }`.
142
+
143
+ The check resolves imports the way the build does, so a clean check is not
144
+ undone by the compile:
145
+
146
+ - **Named table imports from feature files** —
147
+ `import { mailboxes } from "../../mailboxes/mailboxes"` in an action, a
148
+ `lib/` file, or a queue handler. A `feature()` file has only a default
149
+ export; the build points that path at the generated table module, and
150
+ `quickback/.quickback/feature-tables.d.ts` gives the check the same named
151
+ export, typed from the generated schema.
152
+ - **Queue handlers' dynamic imports** — `await import("./features/…")` is
153
+ written against the generated `src/` (the handler body is inlined into
154
+ `src/queue-consumer.ts`); the tsconfig's `rootDirs` resolves it there too.
155
+ - **Service handler contexts** — queue, schedule and email handlers get the
156
+ `db`, `env` and `services` the generated runners pass them: your project's
157
+ Drizzle handle, `CloudflareBindings` and `Services`
158
+ (`quickback/.quickback/service-runtime.d.ts`). A wrong column on a
159
+ `db.select()` result or an undeclared binding is a check error, as it is in
160
+ the build.
139
161
 
140
162
  No compile, no server: this is your editor's view of the source, on demand.
141
163
 
@@ -145,11 +167,10 @@ Exit codes: `0` clean · `1` type errors · `2` setup missing. A fresh clone
145
167
  the check resolves against. Re-run `quickback build` after schema changes so
146
168
  they track your tables.
147
169
 
148
- Actions that still import a table from the authored feature file
149
- (`import { tickets } from "../tickets"`) fail the check — the q-DSL feature
150
- file has only a default export. Import the table from the typed helper
151
- instead (`import { defineAction, tickets } from "../.quickback/define-action"`);
152
- `quickback migrate helper-imports` rewrites the safe cases for you.
170
+ Within a feature, the single helper import
171
+ (`import { defineAction, tickets } from "../.quickback/define-action"`) is
172
+ still the tidier form; `quickback migrate helper-imports` rewrites the safe
173
+ cases for you.
153
174
 
154
175
  ### Synchronize Managed Columns
155
176
 
@@ -190,7 +211,7 @@ quickback migrate helper-imports [--dry-run] # single typed helper import
190
211
 
191
212
  ```ts
192
213
  import { defineAction } from "../.quickback/define-action";
193
- import { applications } from "../applications"; // resolves to the authored file
214
+ import { applications } from "../applications"; // second import, same feature
194
215
  ```
195
216
 
196
217
  — to the single typed import the helpers are designed for:
@@ -50,8 +50,10 @@ src/
50
50
  # Authored-tree typing (regenerated on every compile, gitignored)
51
51
  quickback/tsconfig.json # Typechecks the authored quickback/ tree (`quickback check`)
52
52
  quickback/.quickback/
53
- └── compiler/ # @quickback/compiler declaration snapshot — resolves
54
- └── … # `import { feature, q, defineTable } from "@quickback/compiler"`
53
+ ├── compiler/ # @quickback/compiler declaration snapshot — resolves
54
+ │ └── … # `import { feature, q, defineTable } from "@quickback/compiler"`
55
+ ├── feature-tables.d.ts # Named table exports of feature() files, typed from the generated schema
56
+ └── service-runtime.d.ts # db / env / services types for queue, schedule and email handlers (when any exist)
55
57
  quickback/features/{feature}/
56
58
  └── .quickback/
57
59
  └── define-action.ts # Authored-tree twin of the typed helper below
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quickback-dev/cli",
3
- "version": "0.66.19",
3
+ "version": "0.66.21",
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",
@@ -264,9 +264,27 @@ The action context's `db` is a Drizzle wrapper that:
264
264
  - **Does** route soft-delete `delete()` calls to a `deletedAt` / `deletedBy` UPDATE.
265
265
  - **Does** auto-populate scope columns on `insert`: any `q.scope()` column (and firewall-declared org/owner/team columns) is filled from ctx — `organizationId` ← `ctx.activeOrgId`, `ownerId` ← `ctx.userId`, etc. Audit fields (`createdAt`/`createdBy`/`modifiedAt`/`modifiedBy`) are hard-stamped by the audit wrapper; caller-supplied values for them are dropped.
266
266
  - **Does NOT** fill ordinary business columns — anything that isn't a scope or audit column is exactly what you pass to `.values({...})`.
267
+ - **Refuses** Drizzle's relational API (`db.query.<table>.findFirst/findMany`, `with:`) — it can't be firewalled, so it's a compile error. Use `db.select()` joins.
267
268
 
268
269
  For unscoped writes (cross-tenant support, platform admin), use the `unsafe:` object form on the action — it forces an audit reason and gates on platform admin role.
269
270
 
271
+ ## Relationships between tables
272
+
273
+ There is no Drizzle `relations()` in feature code — never author or generate it. Relationships are:
274
+
275
+ | Shape | Declare |
276
+ |---|---|
277
+ | Belongs-to (post → author) | `authorId: q.text().required().references(() => users.id)` — DB constraint, `Id` type brand, CMS typeahead + labels. Cross-feature target: `import users from "../users/users"`. |
278
+ | Embed the parent on reads | `read: { include: ["authorId"] }` → `GET /posts?include=authorId` (top-level `included` map, depth 1, target's access/firewall/masking apply) |
279
+ | Owned children (order → line items) | `owns: { lineItems: { table: "orderLineItems", fk: "orderId" } }` — atomic nested writes via changesets |
280
+ | Embed owned children on reads | `read: { include: ["lineItems"] }` → `GET /orders/:id?include=lineItems` |
281
+ | Non-owned has-many (user → posts) | FK on the child only; clients call `GET /posts?userId=…` (or `defineBundle` for many lists in one trip). No inline embed. |
282
+ | Value object with no identity (address) | `q.json()` |
283
+
284
+ Never `.references()` a Better Auth id (`userId`, `organizationId`, `memberId`) — auth rows live in `AUTH_DB`. `include` targets must have role-only `read.access` (record-aware targets are a compile error), so don't add every FK by reflex.
285
+
286
+ Details: `quickback docs define/schema` (References), `quickback docs define/read` (Aggregate Reads), `quickback docs define/changesets`.
287
+
270
288
  ## Error handling in actions
271
289
 
272
290
  To return a clean 4xx from an action, throw `ActionError` — the route handler catches it by name and returns `{ error, code, details }` with your status:
@@ -243,7 +243,7 @@ export default defineAction({
243
243
  access: { roles: ['PUBLIC'] },
244
244
  unsafe: {
245
245
  reason: 'Inbound mail webhook — tenant derived from mailbox record',
246
- targetScope: 'organization',
246
+ crossTenant: false, // the default (true) requires a sysadmin session — an anonymous webhook would 403
247
247
  },
248
248
  input: z.object({ mailboxId: z.string(), body: z.string() }),
249
249
  async execute({ unsafeDb, input }) {
@@ -123,6 +123,7 @@ Firewall filtering is transparent — the query is scoped by `WHERE organization
123
123
  | `FIREWALL_ORG_ISOLATION` | Record belongs to a different organization |
124
124
  | `FIREWALL_USER_ISOLATION` | Record belongs to another user |
125
125
  | `FIREWALL_SOFT_DELETED` | Record has been soft deleted |
126
+ | `FIREWALL_WRITE_DENIED` | A create would land a row outside the caller's firewall (see [Firewall on write](/define/firewall#firewall-on-write)); also a Postgres RLS refusal (`42501`) |
126
127
 
127
128
  Inside an action, an `INSERT` through the [scoped `db`](/define/actions/scoped-db)
128
129
  into a table whose firewall requires a claim the caller does not carry (no
@@ -131,6 +132,13 @@ into a table whose firewall requires a claim the caller does not carry (no
131
132
  `details: { table, column, claim }` — the row is never written into whatever
132
133
  tenant the body named.
133
134
 
135
+ An `INSERT` through the scoped `db` whose row would land outside the table's
136
+ firewall (a project the caller has no relationship to) fails with **403**
137
+ `FIREWALL_WRITE_DENIED`, `layer: "firewall"` — the same Problem the CRUD create
138
+ paths return, and the one a Postgres RLS refusal (`42501`) inside an action maps
139
+ to. A `.prepare()`d insert into such a table is refused with **400**
140
+ `FIREWALL_WRITE_CHECK_UNSUPPORTED`.
141
+
134
142
  For security-hardened deployments, set `firewallErrorMode: 'hide'` at the **top
135
143
  level of the resource definition** (not inside `firewall:` — it was lifted off
136
144
  when `firewall` became a predicate array) to return opaque **404 Not Found**
@@ -42,6 +42,8 @@ It is never dropped:
42
42
  | `?status=open` on a view whose `query.filterable` omits `status` | `400` — `Field "status" is not filterable on this view` |
43
43
  | `?title.matches=x` (no such operator) | `400` — `Unknown filter operator "matches"` |
44
44
  | `?ssn=123` where `ssn` is masked for your role | `400` — see [Masking](/define/masking) |
45
+ | `?resolvedAt.gte=yesterday` on a Postgres timestamp column | `400` — `"yesterday" is not an ISO 8601 timestamp` |
46
+ | `?resolvedAt.like=2026` on a Postgres timestamp column | `400` — use `eq`, `ne`, `gt`, `gte`, `lt`, `lte` or `in` |
45
47
 
46
48
  Silently dropping a predicate would return **every row the firewall allows**
47
49
  while still reading as a scoped list — a typo'd or join-table field turns a
@@ -44,7 +44,8 @@ Each resource table exposes:
44
44
 
45
45
  Column types follow the wire, not the storage: `q.bool()` and
46
46
  `integer(..., { mode: "boolean" })` are `boolean`, `integer(..., { mode: "timestamp" })`
47
- and `q.timestamp()` are ISO `string`, `q.json()` is `unknown`, enum columns
47
+ and `q.timestamp()` are ISO `string`, `q.json()` is `unknown` unless it is given a
48
+ [value schema](/define/schema#typed-json-columns), enum columns
48
49
  are literal unions, and nullable columns add `| null`.
49
50
 
50
51
  Primary and foreign keys are branded by default. That makes accidentally passing a candidate ID where a job ID is required a TypeScript error, while both values remain ordinary strings or numbers at runtime.
@@ -149,6 +150,9 @@ import { defineAction, row, applications } from "../.quickback/define-action";
149
150
 
150
151
  // Output = Api.applications.Row
151
152
  output: row(applications)
153
+
154
+ // Nested works too: Output = { application: Api.applications.Row; created: boolean }
155
+ output: z.object({ application: row(applications), created: z.boolean() })
152
156
  ```
153
157
 
154
158
  For any other shape, write the schema out:
@@ -74,8 +74,11 @@ registered provider; MySQL is not supported.
74
74
  One database provider per app: auth tables and feature tables always share the
75
75
  selected database. On either Postgres provider, Better Auth uses its PostgreSQL/Drizzle adapter
76
76
  in the same Postgres database as your features; on `cloudflare-d1`, both use
77
- D1. A per-service map (`database: { auth: ..., features: ... }`) is rejected at
78
- compile time — mixed database providers are not supported.
77
+ D1. A per-service map (`database: { auth: ..., features: ... }`) is not part
78
+ of the config type (`quickback check` flags it) and is rejected at compile
79
+ time — mixed database providers are not supported. On D1, auth still gets its
80
+ own database by default (`splitDatabases: true`); `authBinding` and
81
+ `featuresBinding` name the two bindings.
79
82
 
80
83
  ```typescript
81
84
  import { defineDatabase } from "@quickback/compiler";
@@ -74,10 +74,11 @@ export default defineAction({
74
74
  > the **feature**, not the whole project: a table owned by another feature is
75
75
  > not re-exported here.
76
76
  >
77
- > Prefer this single import over the older
78
- > `import { applications } from "../applications"` — that path resolves to
79
- > your authored file at edit time, which has no named export and none of the
80
- > injected columns. The helper files are regenerated on every compile; keep
77
+ > Prefer this single import over the older two-import form with
78
+ > `import { applications } from "../applications"`. That form still builds
79
+ > and typechecks — `quickback check` resolves a named import from a
80
+ > `feature()` file to the generated table, as the build does — it is just one
81
+ > import more. The helper files are regenerated on every compile; keep
81
82
  > `quickback/features/*/.quickback/` in `.gitignore` (new projects get this
82
83
  > automatically).
83
84
 
@@ -154,7 +155,10 @@ nothing under that substitution — see
154
155
  `output:` is optional, and omitting it degrades quietly: the operation's
155
156
  OpenAPI success response becomes `{}` and
156
157
  `Api.<feature>.actions.<action>.Output` becomes `unknown`. The compile still
157
- succeeds — it warns, naming how many actions are affected.
158
+ succeeds, but it warns, naming how many actions are affected. Every compile
159
+ emits the warning, validation compiles included. It skips actions whose
160
+ response the compiler owns: `responseType: 'file'` or `'stream'`, bundles, and
161
+ transitions without an `execute`.
158
162
 
159
163
  **An action that returns a row declares it with `row(<table>)`**, imported
160
164
  from the same helper as `defineAction`. **Any other shape is a literal Zod
@@ -166,6 +170,9 @@ import { defineAction, row, tickets } from "../.quickback/define-action";
166
170
  // Returns one ticket: Output = Api.tickets.Row, OpenAPI = the Tickets component.
167
171
  output: row(tickets)
168
172
 
173
+ // row() composes: nest it in an envelope, make it nullable, or put it in an array.
174
+ output: z.object({ ticket: row(tickets), previous: row(tickets).nullable(), related: z.array(row(tickets)) })
175
+
169
176
  // Any other shape — write it out.
170
177
  output: z.object({
171
178
  tickets: z.array(z.object({ id: z.string(), name: z.string(), priceCents: z.number() })),
@@ -177,8 +184,10 @@ output: z.object({ tickets: z.array(createSelectSchema(ticketTypes)) })
177
184
 
178
185
  `row(table)` is compiler-recognised: the harvester records which table it
179
186
  was handed, and the compiler resolves that to the table's `Row` type in
180
- `quickback.gen.ts` and to its resource component in OpenAPI (the table must
181
- be a `defineTable()` resource — anything else is a compile error). At
187
+ `quickback.gen.ts` and to its resource component in OpenAPI — wherever it
188
+ appears in the output: bare, as an object property, under `.nullable()`, or
189
+ as array items (the table must be a `defineTable()` resource — anything else
190
+ is a compile error). At
182
191
  runtime it is a real Zod object built from the table's columns.
183
192
 
184
193
  The harvest substitutes inert proxies for table modules, so anything that
@@ -220,6 +229,7 @@ namespace parameters.
220
229
  |--------|----------|-------------|
221
230
  | `description` | Yes | Human-readable description of the action |
222
231
  | `input` | Yes | Zod schema for request validation |
232
+ | `query` | No | Non-GET only. An inline `z.object({...})` of query-string parameters, validated apart from the JSON body and passed to `execute` as `query`. See [Query parameters on non-GET actions](/define/actions/record-and-standalone#query-parameters-on-non-get-actions) |
223
233
  | `output` | No | Portable Zod schema for the JSON success response. Generates action output types and constrains `execute`'s result. |
224
234
  | `access` | Yes | Access control (roles, record conditions, or function) |
225
235
  | `execute` | Yes | Inline async arrow function (`async (ctx) => { … }`) |
@@ -166,10 +166,25 @@ Fail-closed, one rule:
166
166
  The compile fails if the named action is missing, bound to a different table,
167
167
  the wrong shape (create needs a standalone `path:` equal to the collection URL;
168
168
  update/delete need a record-based action with no `path:`), declares a
169
- conflicting `method`, is already mapped to another verb, or the table also
170
- declares `owns` (changeset dispatch lives on the stock handler). `read.action`
169
+ conflicting `method`, or is already mapped to another verb. `read.action`
171
170
  is not supported.
172
171
 
172
+ ### Mapping a verb on an `owns` root
173
+
174
+ A table that declares [`owns`](/define/changesets) can map `create` or `update`
175
+ too. The action is then the only write path for that verb:
176
+
177
+ - A request to that verb with `Content-Type: application/vnd.quickback.changeset+json`
178
+ gets a `415`. It doesn't bypass the action, and the action's `input` doesn't
179
+ silently drop the child ops.
180
+ - OpenAPI documents only `application/json` for that operation. The unmapped
181
+ verb keeps its changeset lane.
182
+ - The changeset engine is still generated, so the action can take child
183
+ changes in its own `input` and delegate the aggregate write to
184
+ [`apply<Singular>Changeset`](/define/changesets#calling-it-from-authored-code)
185
+ (set `singular:` on the root if the default name reads wrong).
186
+ The root's crud access, guards and firewall still run inside it.
187
+
173
188
  ## The rest of this section
174
189
 
175
190
  - **[Defining actions](/define/actions/defining)** — the action file, its configuration options, protected fields, and refs
@@ -224,6 +224,16 @@ with a mounted prefix, two more forms apply:
224
224
  An action's `access:` and `anchor:` may reference vocabulary declared by an ancestor area —
225
225
  and never vocabulary of an area the feature is not inside (compile error).
226
226
 
227
+ A standalone path under a feature's own collection, like `path: "/users/:id/likes"`, is still
228
+ standalone. It binds to nothing, so there is no record fetch. Read `:id` yourself and check it
229
+ through the scoped `db`. If you want the record fetched and firewalled for you, drop `path:`
230
+ and write a record-based action.
231
+
232
+ A standalone path may not land on a route the compiler already mounts. That includes a record
233
+ action with the same name (`actions/users/likes.ts` → `POST /users/:id/likes`) and the
234
+ generated CRUD routes (`GET /users/:id`). Parameter names don't matter to the router, so
235
+ `/users/:userId/likes` collides too. Either case is a compile error naming both routes.
236
+
227
237
  ### Feature-area transition adapter
228
238
 
229
239
  A record [state transition](/define/transitions) normally lives on a
@@ -420,3 +430,46 @@ imply "this writes data" — it's the right method whenever the request body is
420
430
  load-bearing. Use the response shape (`responseType: "json"`, or just the data
421
431
  your handler returns) to convey read semantics; HTTP method choice is about
422
432
  input transport, not action intent.
433
+
434
+ ### Query parameters on non-GET actions
435
+
436
+ A POST, PUT, PATCH or DELETE action can take query-string parameters as well as
437
+ its JSON body. Declare them with `query:`. They are validated apart from
438
+ `input` and passed to `execute` as `query`. This also works when the body is a
439
+ bare array:
440
+
441
+ ```typescript
442
+ // features/journal-entries/actions/bulkCreate.ts — POST /bulk/journal-entries?expand=lines
443
+ import { z } from "zod";
444
+ import { defineAction } from "../.quickback/define-action";
445
+
446
+ export default defineAction({
447
+ description: "Create journal entries in bulk; ?expand=lines includes their lines.",
448
+ method: "POST",
449
+ path: "/bulk/journal-entries",
450
+ input: z.array(z.object({ memo: z.string().optional() })),
451
+ query: z.object({
452
+ expand: z.enum(["lines"]).optional(),
453
+ limit: z.coerce.number().int().max(100).optional(),
454
+ }),
455
+ access: { roles: ["admin"] },
456
+ async execute({ input, query }) {
457
+ // query is { expand?: "lines", limit?: number } — fully typed.
458
+ return { count: input.length, expand: query.expand ?? null };
459
+ },
460
+ });
461
+ ```
462
+
463
+ Each property is documented as an `in: query` parameter in `openapi.json`, so
464
+ it also shows up in `api-types.gen.ts`, in `quickback.gen.ts` as
465
+ `actions.<name>.Query`, and on the MCP tool. A bad value is a `400`, the same
466
+ as a bad body.
467
+
468
+ Rules, all checked at compile time:
469
+
470
+ - `query` must be an inline `z.object({...})` built from `z` and literals. The compiler converts it to JSON Schema itself.
471
+ - Not on GET actions. Their `input` already comes from the query string.
472
+ - Not together with `bulkVariant`.
473
+
474
+ Query values arrive as strings, and repeated keys become arrays. Use
475
+ `z.coerce.number()` / `z.coerce.boolean()` for typed primitives.
@@ -9,7 +9,22 @@ the same generated `WHERE` clause the table's CRUD routes use:
9
9
  |-----------|---------------------------|
10
10
  | `SELECT` | the table's firewall (org / owner / team / scope / `via:` arms) AND soft-delete filter |
11
11
  | `UPDATE` / `DELETE` | the same firewall `WHERE`, AND-merged with yours |
12
- | `INSERT` | every required claim column the firewall binds (e.g. `organizationId` from `ctx.activeOrgId`), overwriting any value you passed |
12
+ | `INSERT` | every required claim column the firewall binds (e.g. `organizationId` from `ctx.activeOrgId`), overwriting any value you passed — then, where those stamps can't guarantee the row passes the firewall (a `via:` / `{ permission }` / literal / `any:` arm), the [firewall-on-write check](/define/firewall#firewall-on-write): every row of `.values(row)` or `.values([rows])` must pass the table's firewall, or nothing is written and the action answers **403 `FIREWALL_WRITE_DENIED`** |
13
+ | `INSERT … onConflictDoUpdate` / `onConflictDoNothing` | the insert branch runs the same firewall-on-write check; the conflict update gets the firewall AND-merged into `setWhere` — a conflict with a row the caller can't update (another tenant's id) is a no-op, never an overwrite |
14
+
15
+ The firewall is set on the builder when you call `.from()` / `.set()` /
16
+ `.delete()`, so every executor gets it: `await`, `.all()`, `.get()`,
17
+ `.values()`, `.run()`, `.execute()`, `.prepare()`, and the builder embedded as
18
+ a subquery (`inArray(col, db.select(...).from(t))`). The firewall-on-write
19
+ check on an `INSERT` is async, so it runs when the insert executes — on
20
+ `await`, on any executor, and ahead of `db.batch([...])`. A `.prepare()`d
21
+ insert into a table that needs the check is refused (`FIREWALL_WRITE_CHECK_UNSUPPORTED`):
22
+ it would run later with nothing to check it.
23
+
24
+ The same refusal comes back from Postgres itself when an `INSERT` reaches the
25
+ database outside the caller's firewall (RLS `42501`): the action route maps it
26
+ to the same **403 `FIREWALL_WRITE_DENIED`** Problem, never a generic action
27
+ failure — so D1 and Postgres answer alike.
13
28
 
14
29
  It is not a guess from column names. `any:` groups, `optional` arms, scope
15
30
  (`ctx.scope.*`) and `via:` relationship arms, the null-claim deny, the
@@ -277,6 +292,12 @@ predicate in the `WHERE` (for example,
277
292
 
278
293
  Actions that need to bypass scoped DB filters (for example, platform-level support operations) can enable unsafe mode.
279
294
 
295
+ `unsafeDb` and a raw `createDb()` handle are **unchecked by design**: no
296
+ firewall `WHERE`, no claim stamping, no firewall-on-write check. On Postgres a
297
+ non-cross-tenant `unsafeDb` still runs under the caller's RLS claims, so an
298
+ insert the policy refuses comes back as 403 `FIREWALL_WRITE_DENIED`; on D1 it
299
+ lands. That is the point of the escape hatch — and why it is audited.
300
+
280
301
  `unsafe` is the only sanctioned way around the scoped `db`. The compiler warns
281
302
  when a non-`unsafe` action — or a file it imports from the feature's `lib/`,
282
303
  the project's `lib/`, `hooks/` or `plugins/` (relative or `~/` imports) —