@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.
- package/dist/commands/migrate.js +2 -2
- package/dist/commands/migrate.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/skill/SKILL.md +18 -0
- package/dist/skill/docs/api/actions.md +1 -1
- package/dist/skill/docs/api/errors.md +8 -0
- package/dist/skill/docs/api/query-params.md +2 -0
- package/dist/skill/docs/api/typescript.md +5 -1
- package/dist/skill/docs/configure/providers.md +5 -2
- package/dist/skill/docs/define/actions/defining.md +17 -7
- package/dist/skill/docs/define/actions/index.md +17 -2
- package/dist/skill/docs/define/actions/record-and-standalone.md +53 -0
- package/dist/skill/docs/define/actions/scoped-db.md +22 -1
- package/dist/skill/docs/define/changesets.md +24 -4
- package/dist/skill/docs/define/firewall.md +39 -0
- package/dist/skill/docs/define/relationships.md +9 -0
- package/dist/skill/docs/define/schema.md +34 -1
- package/dist/skill/docs/define/transitions.md +3 -1
- package/dist/skill/docs/define/triggers.md +2 -1
- package/dist/skill/docs/platform/database/neon.md +110 -30
- package/dist/skill/docs/platform/webhooks/inbound.md +20 -7
- package/dist/skill/docs/tooling/cli.md +28 -7
- package/dist/skill/docs/tooling/output.md +4 -2
- package/package.json +1 -1
- package/src/skill/SKILL.md +18 -0
- package/src/skill/docs/api/actions.md +1 -1
- package/src/skill/docs/api/errors.md +8 -0
- package/src/skill/docs/api/query-params.md +2 -0
- package/src/skill/docs/api/typescript.md +5 -1
- package/src/skill/docs/configure/providers.md +5 -2
- package/src/skill/docs/define/actions/defining.md +17 -7
- package/src/skill/docs/define/actions/index.md +17 -2
- package/src/skill/docs/define/actions/record-and-standalone.md +53 -0
- package/src/skill/docs/define/actions/scoped-db.md +22 -1
- package/src/skill/docs/define/changesets.md +24 -4
- package/src/skill/docs/define/firewall.md +39 -0
- package/src/skill/docs/define/relationships.md +9 -0
- package/src/skill/docs/define/schema.md +34 -1
- package/src/skill/docs/define/transitions.md +3 -1
- package/src/skill/docs/define/triggers.md +2 -1
- package/src/skill/docs/platform/database/neon.md +110 -30
- package/src/skill/docs/platform/webhooks/inbound.md +20 -7
- package/src/skill/docs/tooling/cli.md +28 -7
- package/src/skill/docs/tooling/output.md +4 -2
|
@@ -121,9 +121,9 @@ to `"v2"` only if you also want the `/api/v2` prefix.
|
|
|
121
121
|
id — an unresolvable parent lid is a pointer-carrying **400**, never a
|
|
122
122
|
silent re-parent onto the root.
|
|
123
123
|
- `Prefer: return=minimal` omits `root` from the response. v1 representation
|
|
124
|
-
is **root-row-only** (re-read through the root's masking) —
|
|
125
|
-
|
|
126
|
-
|
|
124
|
+
is **root-row-only** (re-read through the root's masking) — read the
|
|
125
|
+
aggregate back with `?include=<ownsRelation>` (see [read → Aggregate
|
|
126
|
+
Reads](/define/read#aggregate-reads)).
|
|
127
127
|
|
|
128
128
|
### Headers
|
|
129
129
|
|
|
@@ -430,7 +430,22 @@ it; `meta.transactional` reports the actual guarantee (same contract as
|
|
|
430
430
|
The engine is exported per root as `apply<Singular>Changeset` — the seam
|
|
431
431
|
authored actions delegate through when they still need residue logic
|
|
432
432
|
(preconditions, server-side transforms, notifications) around the aggregate
|
|
433
|
-
write
|
|
433
|
+
write.
|
|
434
|
+
|
|
435
|
+
`<Singular>` comes from the table name with a trailing `s` dropped, so
|
|
436
|
+
`projects` gives `applyProjectChangeset`. For a name that rule gets wrong,
|
|
437
|
+
declare `singular:` on the root to add a correctly named export:
|
|
438
|
+
|
|
439
|
+
```ts
|
|
440
|
+
// journalEntries would otherwise only export applyJournalEntrieChangeset
|
|
441
|
+
singular: "journalEntry", // adds applyJournalEntryChangeset
|
|
442
|
+
owns: { /* ... */ },
|
|
443
|
+
```
|
|
444
|
+
|
|
445
|
+
The default name is still exported, so existing imports keep working.
|
|
446
|
+
`singular` must be camelCase, and it's a compile error on a table that doesn't
|
|
447
|
+
declare `owns`.
|
|
448
|
+
|
|
434
449
|
|
|
435
450
|
{/* doc-compile: skip — the fence imports `../projects.changeset`, a module the compiler only generates for a root that declares `owns`, which this fence does not carry, so the import cannot resolve. `description` / `input` / `access` are elided to `// ...` on purpose — the point is the delegation seam. */}
|
|
436
451
|
```ts title="quickback/features/projects/actions/importBoard.ts"
|
|
@@ -450,6 +465,11 @@ export default defineAction({
|
|
|
450
465
|
});
|
|
451
466
|
```
|
|
452
467
|
|
|
468
|
+
This is also how a root that maps `create.action` or `update.action` writes its
|
|
469
|
+
children: the mapped verb has no changeset media type of its own (it answers
|
|
470
|
+
`415`), so its action delegates here. See
|
|
471
|
+
[Mapping a verb on an `owns` root](/define/actions#mapping-a-verb-on-an-owns-root).
|
|
472
|
+
|
|
453
473
|
**There is no trusted mode.** The auth assertion, cross-tenant guard, and the
|
|
454
474
|
root's own pre-record access gate are the helper's first statements — an
|
|
455
475
|
authored action whose action-level access is looser than the root's crud
|
|
@@ -118,6 +118,16 @@ type FirewallConfig = ReadonlyArray<FirewallPredicate>;
|
|
|
118
118
|
firewallErrorMode?: 'reveal' | 'hide';
|
|
119
119
|
```
|
|
120
120
|
|
|
121
|
+
An `equals` value that doesn't start with `ctx.` is a **literal**: `{ field: 'visibility', equals: 'studio' }` emits `eq(table.visibility, "studio")`. Like any status filter it is enforced by the API only — in Postgres RLS a literal arm lowers to `true`, so `any: [studio, { all: [private, owner] }]` keeps its OR shape instead of hardening into an owner-only policy.
|
|
122
|
+
|
|
123
|
+
On Postgres the RLS scope policy mirrors the firewall's `all`/`any` tree arm for arm, and the **database enforces relationship arms too**:
|
|
124
|
+
|
|
125
|
+
- A `via:` arm lowers to `project_id IN (SELECT r.project_id FROM public.qb_rel_<relationship>() r)` — a `SECURITY DEFINER` helper that runs the same relationship lookup as the API (subject = the caller's claim, the `where:` literals, the related table's soft delete). The generated API calls the same helper for every relationship lookup on Postgres, so a caller with no active org gets the same rows from the API as the policy admits. `[org, { any: [owner, { via }] }]` becomes `org AND (owner OR project_id IN (…))`, never `org AND owner`. See [Relationship arms in SQL](/platform/database/neon#relationship-arms-in-sql).
|
|
126
|
+
- A `{ permission }` arm expands exactly as the API expands it: relation leaves become `via:` helpers, arrows become `qb_arrow_…` helpers (a recursive arrow is a `maxDepth`-bounded closure).
|
|
127
|
+
- Inside an `any` group that also has an org arm, the relationship, scope and principal arms are tenant-bound exactly where the API binds them — `(<arm> AND (organization_id = <active org> OR <no active org>))` — so an org-claiming caller never rides them into another org.
|
|
128
|
+
- The soft-delete filter the API adds to a table carrying `deletedAt` reaches the policy too, as `deleted_at IS NULL OR public.in_soft_delete()` in `USING` only — see [the soft-delete lane](/platform/database/neon#the-soft-delete-lane).
|
|
129
|
+
- Literals, literal `in` lists, and claims the Worker never writes into the transaction (`ctx.scope.<kind>.<subKey>`, area anchors like `ctx.event.id`, string `in` sets) stay API-only and lower to `true` — the policy has nothing to compare them against, and a literal conjunct would refuse status-changing updates.
|
|
130
|
+
|
|
121
131
|
The top-level array is AND'd together. `firewallErrorMode` lives at the resource top level — it's a presentation-layer choice (403 vs 404), not a query-shape one.
|
|
122
132
|
|
|
123
133
|
## Boolean groups: `all` / `any`
|
|
@@ -516,6 +526,35 @@ export default defineTable(records, {
|
|
|
516
526
|
});
|
|
517
527
|
```
|
|
518
528
|
|
|
529
|
+
### Firewall on write
|
|
530
|
+
|
|
531
|
+
A create may not land a row the caller could not read. When a firewall's
|
|
532
|
+
admission isn't guaranteed by the values a create stamps — a `via:` or
|
|
533
|
+
`{ permission }` arm (a task in a project you have no relationship to), a
|
|
534
|
+
literal or `in` arm, any `any:` group — every create path (`POST /`,
|
|
535
|
+
`POST /batch`, the create side of `PUT /:id` and `PUT /batch`, and a changeset's
|
|
536
|
+
root and owned-child inserts) evaluates the table's own firewall against the new
|
|
537
|
+
row before inserting it — and so does an action's [scoped `db`](/define/actions/scoped-db)
|
|
538
|
+
on every `insert(...).values(...)` (single row or array, and the insert branch
|
|
539
|
+
of an upsert) — and refuses with:
|
|
540
|
+
|
|
541
|
+
```json
|
|
542
|
+
{
|
|
543
|
+
"error": "Record would be outside your firewall",
|
|
544
|
+
"code": "FIREWALL_WRITE_DENIED",
|
|
545
|
+
"layer": "firewall"
|
|
546
|
+
}
|
|
547
|
+
```
|
|
548
|
+
|
|
549
|
+
Status `403`. The verdict is the same on D1 and Postgres: it is the table's
|
|
550
|
+
generated `buildFirewallConditions` — the same WHERE every read applies —
|
|
551
|
+
evaluated over the candidate row. (On Postgres the RLS policy would refuse the
|
|
552
|
+
row anyway; a refusal that still reaches the database maps to the same Problem,
|
|
553
|
+
never a raw `42501` — in a CRUD route or an action.) Firewalls made only of
|
|
554
|
+
stamped `ctx.*` equalities and `isNull` skip the check — the stamps already
|
|
555
|
+
guarantee admission. An action's `unsafeDb` and a raw `createDb()` handle are
|
|
556
|
+
unchecked by design (see [Unsafe Mode](/define/actions/scoped-db#unsafe-mode)).
|
|
557
|
+
|
|
519
558
|
### Foreign-Key Referential Checks
|
|
520
559
|
|
|
521
560
|
Every generated write handler — `POST /`, `POST /batch`, `PATCH /:id`, `PATCH /batch`, `PUT /:id` (both its update and create paths), `PUT /batch`, and the root of a [changeset](/define/changesets) — validates foreign-key columns against the **target table's** firewall before writing. Creates check every FK in the body; updates check every FK whose value **changes** (a value equal to the stored one costs no query). If a record references a row that the caller can't see (wrong org, soft-deleted, or non-existent), the request fails with:
|
|
@@ -96,6 +96,15 @@ export default defineConfig({
|
|
|
96
96
|
>
|
|
97
97
|
> Adding `defineTable` does not force a public API onto the join table — gate or omit its
|
|
98
98
|
> `read` / `crud` blocks as you would any other table. What it supplies is the firewall.
|
|
99
|
+
>
|
|
100
|
+
> The `from:` table may also be the table that consumes the relationship — e.g.
|
|
101
|
+
> `projectMemberOf = { from: 'projectMembers', … }` used as `{ field: 'projectId', via: 'projectMemberOf' }`
|
|
102
|
+
> on `projectMembers` itself ("see the members of projects I belong to"). The subquery then
|
|
103
|
+
> calls the module's own firewall with `skipTenantScopes`, which returns before any `via:`
|
|
104
|
+
> arm is built, so it cannot recurse. On Postgres the API and the database both read the
|
|
105
|
+
> relationship through a `SECURITY DEFINER` helper (`public.qb_rel_<relationship>()`) that reads
|
|
106
|
+
> the relationship table without its own policy, so neither can recurse — see
|
|
107
|
+
> [Relationship arms in SQL](/platform/database/neon#relationship-arms-in-sql).
|
|
99
108
|
|
|
100
109
|
|
|
101
110
|
### Using relationship-roles in resources
|
|
@@ -119,7 +119,7 @@ A few mechanics to know:
|
|
|
119
119
|
| `q.uuid()` | `uuid(...)` | `z.string().uuid()` |
|
|
120
120
|
| `q.timestamp()` | `timestamp(...)` (converted to SQLite `text` on sqlite targets) | `z.coerce.date()` |
|
|
121
121
|
| `q.date()` | `date(...)` | `z.iso.date()` (`YYYY-MM-DD`) |
|
|
122
|
-
| `q.json()` | `jsonb(...)` | `z.unknown()
|
|
122
|
+
| `q.json()` / `q.json(z.object({...}))` | `jsonb(...)` | `z.unknown()`, or the value schema you pass in — see [Typed JSON columns](#typed-json-columns) |
|
|
123
123
|
| `q.enum(['a','b'])` | `text(..., { enum: [...] })` | `z.enum([...])` |
|
|
124
124
|
| `q.id()` | `text('id').primaryKey()` | `z.string()` |
|
|
125
125
|
| `q.scope(kind)` | `text(...).notNull()` | `z.string()` |
|
|
@@ -136,6 +136,38 @@ In request bodies a column that is not `.required()` is `.optional().nullable()`
|
|
|
136
136
|
|
|
137
137
|
`q.id()` emits a plain text primary key. Actual ID assignment at insert time is driven by the provider's `generateId` setting. This keeps q's output decoupled from any specific ID library.
|
|
138
138
|
|
|
139
|
+
#### Typed JSON columns
|
|
140
|
+
|
|
141
|
+
Pass `q.json()` a Zod schema to give the column's value a shape. A table file may import `{ z }` from `zod` for this:
|
|
142
|
+
|
|
143
|
+
```typescript title="quickback/features/journal-entries/journal-entries.ts"
|
|
144
|
+
import { feature, q } from "@quickback/compiler";
|
|
145
|
+
import { z } from "zod";
|
|
146
|
+
|
|
147
|
+
export default feature("journalEntries", {
|
|
148
|
+
columns: {
|
|
149
|
+
id: q.id(),
|
|
150
|
+
organizationId: q.scope("organization"),
|
|
151
|
+
autocatResult: q.json(z.object({ method: z.string(), confidence: z.number().min(0).max(1) })).optional(),
|
|
152
|
+
applications: q.json(z.array(z.object({ invoiceId: z.string(), amount: z.string() }))).optional(),
|
|
153
|
+
raw: q.json().optional(),
|
|
154
|
+
...q.audit(),
|
|
155
|
+
...q.softDelete(),
|
|
156
|
+
},
|
|
157
|
+
read: { access: { roles: ["member"] } },
|
|
158
|
+
create: { access: { roles: ["admin"] } },
|
|
159
|
+
});
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
The schema validates create and update bodies (and changeset ops), and its JSON Schema types the column in `openapi.json`, `api-types.gen.ts`, `quickback.gen.ts` and the MCP tools. A bare `q.json()` stays `unknown` there. Storage doesn't change: the column is `jsonb` on Postgres and JSON text on SQLite/D1.
|
|
163
|
+
|
|
164
|
+
The schema must be written inline from `z` and literals, because the compiler copies it into the generated routes and converts it to JSON Schema itself. These are compile errors:
|
|
165
|
+
|
|
166
|
+
- a reference to another binding: `q.json(Shape)`, or `z.object({ a: Shape })`
|
|
167
|
+
- a callback such as `.refine(...)` or `.transform(...)`
|
|
168
|
+
- using `z` anywhere else in the table file
|
|
169
|
+
- importing anything from `zod` other than `{ z }`
|
|
170
|
+
|
|
139
171
|
For `generateId: "cuid"`, there is one important nuance: import-capable runtime
|
|
140
172
|
paths can emit real `createId()` usage, but compiler-managed schema
|
|
141
173
|
auto-injection may keep the same `createId()` call site and back it with a
|
|
@@ -180,6 +212,7 @@ export default feature("invoices", {
|
|
|
180
212
|
|
|
181
213
|
- **Decimals are strings**, so no value passes through a float. Send `"19.9"` and the API stores and returns `"19.90"`: the value is padded to `scale` digits and leading zeros are dropped, which is how Postgres prints `numeric(p,s)`. D1 stores that same canonical text, so both dialects return identical strings. `precision` (1–1000) and `scale` (0–`precision`) must be number literals, or the compile fails.
|
|
182
214
|
- **Dates have no time zone.** A `q.date()` value is never converted, so `"2026-03-31"` is the same day for every caller. Use `q.timestamp()` for an instant.
|
|
215
|
+
- **Timestamps are ISO strings on the wire, on both dialects.** On D1, `q.timestamp()` is `text` holding the ISO string. On Postgres it is `timestamptz`. The column accepts a `Date` or an ISO string on write, and its TypeScript type is `Date | string`. Reads come back as a `Date`, which serializes as the same ISO `Z` string. Because Drizzle uses one type for reads and writes, a read is also typed `Date | string` even though it is always a `Date` at runtime — wrap it as `new Date(row.dueAt)` before calling `Date` methods such as `.getTime()` (a breaking type change for Postgres projects written against the earlier `Date`-only type). So `.set({ archivedAt: now })` works and typechecks on either database, on every handle: the scoped `db`, `unsafeDb`, and a raw `createDb()`. Postgres feature schemas import this column's `timestamp` from the generated `src/lib/pg-timestamp.ts` instead of `drizzle-orm/pg-core`. Its SQL type and migrations are unchanged. Filter values for a Postgres timestamp column must parse as a timestamp, or the request returns `400`.
|
|
183
216
|
- **`q.bigint()` values are JSON numbers, and are capped at ±(2^53 − 1).** Past that, a JSON number can't hold an exact integer, and D1 returns every `INTEGER` as a JS number. The cap still takes a cents column past $90 trillion, where `q.int()` (Postgres `integer`) stops at about $21.4 million. Values written to a Postgres `bigint` outside the API beyond 2^53 will read back rounded.
|
|
184
217
|
- **Defaults are checked at compile time** against the same rules, because nothing re-validates a DDL default. `q.smallint().default(40000)` fails the compile. A decimal default must already be in canonical form, so write `.default("0.00")` for scale 2, not `"0"`.
|
|
185
218
|
- **`.array()`** works on `q.text()`, `q.enum()`, `q.int()`, and `q.uuid()`, and must be written once. `.default([])` gives Postgres `'{}'` and D1 `'[]'`. An array column can't declare `.references()`: Postgres has no foreign keys over array elements, so use a join table.
|
|
@@ -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
|
|
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
|
|
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.
|
|
603
|
-
|
|
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
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
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 {
|
|
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/:
|
|
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,
|
|
366
|
-
const
|
|
367
|
-
|
|
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,
|
|
371
|
-
// verify `rawBody` + the provider's signature headers with `secret`;
|
|
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
|
-
|
|
149
|
-
(`import { tickets } from "
|
|
150
|
-
|
|
151
|
-
|
|
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"; //
|
|
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
|
-
|
|
54
|
-
|
|
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
|