@quickback-dev/cli 0.54.0 → 0.55.1

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 (95) hide show
  1. package/dist/commands/compile.d.ts.map +1 -1
  2. package/dist/commands/compile.js +41 -4
  3. package/dist/commands/compile.js.map +1 -1
  4. package/dist/commands/create.d.ts.map +1 -1
  5. package/dist/commands/create.js +5 -1
  6. package/dist/commands/create.js.map +1 -1
  7. package/dist/docs/content.d.ts.map +1 -1
  8. package/dist/docs/content.js +37 -22
  9. package/dist/docs/content.js.map +1 -1
  10. package/dist/index.js +1 -1
  11. package/dist/lib/action-harvest.d.ts +16 -1
  12. package/dist/lib/action-harvest.d.ts.map +1 -1
  13. package/dist/lib/action-harvest.js +21 -1
  14. package/dist/lib/action-harvest.js.map +1 -1
  15. package/dist/lib/action-harvest.test.js +122 -3
  16. package/dist/lib/action-harvest.test.js.map +1 -1
  17. package/dist/lib/api-client.d.ts +11 -0
  18. package/dist/lib/api-client.d.ts.map +1 -1
  19. package/dist/lib/api-client.js.map +1 -1
  20. package/dist/lib/artifact-routing.d.ts.map +1 -1
  21. package/dist/lib/artifact-routing.js +3 -0
  22. package/dist/lib/artifact-routing.js.map +1 -1
  23. package/dist/lib/compiler-floor.d.ts +39 -0
  24. package/dist/lib/compiler-floor.d.ts.map +1 -0
  25. package/dist/lib/compiler-floor.js +75 -0
  26. package/dist/lib/compiler-floor.js.map +1 -0
  27. package/dist/lib/compiler-floor.test.d.ts +2 -0
  28. package/dist/lib/compiler-floor.test.d.ts.map +1 -0
  29. package/dist/lib/compiler-floor.test.js +67 -0
  30. package/dist/lib/compiler-floor.test.js.map +1 -0
  31. package/dist/lib/compiler-stubs.d.ts +6 -0
  32. package/dist/lib/compiler-stubs.d.ts.map +1 -1
  33. package/dist/lib/compiler-stubs.js +8 -0
  34. package/dist/lib/compiler-stubs.js.map +1 -1
  35. package/dist/lib/file-loader.d.ts +45 -4
  36. package/dist/lib/file-loader.d.ts.map +1 -1
  37. package/dist/lib/file-loader.js +116 -19
  38. package/dist/lib/file-loader.js.map +1 -1
  39. package/dist/lib/file-loader.test.js +80 -4
  40. package/dist/lib/file-loader.test.js.map +1 -1
  41. package/dist/skill/SKILL.md +3 -1
  42. package/dist/skill/docs/changelog.md +66 -0
  43. package/dist/skill/docs/compiler/config/index.md +14 -1
  44. package/dist/skill/docs/compiler/config/providers.md +13 -9
  45. package/dist/skill/docs/compiler/definitions/access.md +134 -2
  46. package/dist/skill/docs/compiler/definitions/actions.md +22 -0
  47. package/dist/skill/docs/compiler/definitions/changesets.md +375 -0
  48. package/dist/skill/docs/compiler/definitions/feature-areas.md +189 -0
  49. package/dist/skill/docs/compiler/definitions/feature.md +33 -0
  50. package/dist/skill/docs/compiler/definitions/firewall.md +60 -1
  51. package/dist/skill/docs/compiler/definitions/guards.md +14 -0
  52. package/dist/skill/docs/compiler/definitions/index.md +28 -3
  53. package/dist/skill/docs/compiler/definitions/masking.md +8 -0
  54. package/dist/skill/docs/compiler/definitions/read.md +13 -0
  55. package/dist/skill/docs/compiler/definitions/schema.md +36 -1
  56. package/dist/skill/docs/compiler/definitions/scopes.md +23 -1
  57. package/dist/skill/docs/compiler/targets/hono-api/database/neon.md +27 -28
  58. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/batch-operations.md +2 -0
  59. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/errors.md +49 -17
  60. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/query-params.md +66 -0
  61. package/dist/skill/docs/stack/api-contract/index.md +136 -0
  62. package/dist/skill/docs/stack/realtime/durable-objects.md +7 -0
  63. package/dist/skill/docs/stack/realtime/index.md +22 -0
  64. package/dist/skill/docs/stack/realtime/live-views.md +56 -0
  65. package/dist/skill/docs/stack/realtime/using-realtime.md +53 -0
  66. package/dist/skill/docs/stack/webhooks/inbound.md +79 -0
  67. package/dist/skill/docs/stack/webhooks/outbound.md +33 -0
  68. package/package.json +1 -1
  69. package/src/skill/SKILL.md +3 -1
  70. package/src/skill/docs/changelog.md +66 -0
  71. package/src/skill/docs/compiler/config/index.md +14 -1
  72. package/src/skill/docs/compiler/config/providers.md +13 -9
  73. package/src/skill/docs/compiler/definitions/access.md +134 -2
  74. package/src/skill/docs/compiler/definitions/actions.md +22 -0
  75. package/src/skill/docs/compiler/definitions/changesets.md +375 -0
  76. package/src/skill/docs/compiler/definitions/feature-areas.md +189 -0
  77. package/src/skill/docs/compiler/definitions/feature.md +33 -0
  78. package/src/skill/docs/compiler/definitions/firewall.md +60 -1
  79. package/src/skill/docs/compiler/definitions/guards.md +14 -0
  80. package/src/skill/docs/compiler/definitions/index.md +28 -3
  81. package/src/skill/docs/compiler/definitions/masking.md +8 -0
  82. package/src/skill/docs/compiler/definitions/read.md +13 -0
  83. package/src/skill/docs/compiler/definitions/schema.md +36 -1
  84. package/src/skill/docs/compiler/definitions/scopes.md +23 -1
  85. package/src/skill/docs/compiler/targets/hono-api/database/neon.md +27 -28
  86. package/src/skill/docs/compiler/targets/hono-api/using-the-api/batch-operations.md +2 -0
  87. package/src/skill/docs/compiler/targets/hono-api/using-the-api/errors.md +49 -17
  88. package/src/skill/docs/compiler/targets/hono-api/using-the-api/query-params.md +66 -0
  89. package/src/skill/docs/stack/api-contract/index.md +136 -0
  90. package/src/skill/docs/stack/realtime/durable-objects.md +7 -0
  91. package/src/skill/docs/stack/realtime/index.md +22 -0
  92. package/src/skill/docs/stack/realtime/live-views.md +56 -0
  93. package/src/skill/docs/stack/realtime/using-realtime.md +53 -0
  94. package/src/skill/docs/stack/webhooks/inbound.md +79 -0
  95. package/src/skill/docs/stack/webhooks/outbound.md +33 -0
@@ -149,7 +149,7 @@ Quickback ships seven reserved UPPERCASE markers. Six are real pseudo-roles hand
149
149
  | `AUTHENTICATED` | required | none | `ctx.authenticated === true` (a full session **or** a scope principal — the wrapper over `SESSION` ∪ `SCOPED`) |
150
150
  | `SESSION` | required | none | a full Better Auth session **only** — `ctx.authenticated && !ctx.principal && !ctx.scopePrincipal` |
151
151
  | `SCOPED` | required | none | a sessionless scope principal **only** — `ctx.authenticated && ctx.scopePrincipal === true` |
152
- | `USER` | required | resource firewall **must** scope by `userId` | `ctx.authenticated` AND (`ctx.userRole` is unset OR `ctx.userRole === "user"`) |
152
+ | `USER` | required | resource firewall **must** scope by `userId` | a real signed-in user — `ctx.authenticated` AND **not** a scope principal (`!ctx.scopePrincipal`) AND (`ctx.userRole` unset OR `=== "user"`). A sessionless scope caller does **not** satisfy `USER` (use `SCOPED` / `scope:<kind>:<role>`); `AUTHENTICATED` is the marker that admits both flavors. |
153
153
  | `ADMIN` | required | reserved legacy marker — compiler rejects it | `false` |
154
154
  | `SYSADMIN` | required | `cms: { sysadmin: true }` **must** be set on the project | `ctx.authenticated && ctx.userRole === "sysadmin"` |
155
155
 
@@ -328,9 +328,141 @@ type FieldCondition =
328
328
  | { greaterThanOrEqual: number };
329
329
  ```
330
330
 
331
+ ## Centrally defined access rules
332
+
333
+ Instead of repeating the same `roles: [...]` expression across every feature, define it **once** in `authz.roles` and reference it by name everywhere. This is the recommended way to manage access as your app grows: one source of truth per rule, changed in one place.
334
+
335
+ Named roles (and named gates, tenant anchors, scope kinds) can be declared at **two levels**:
336
+ at root `authz` in `quickback.config.ts` (visible everywhere), or inside a
337
+ [feature area](/compiler/definitions/feature-areas)'s `_area.ts` (visible to that area's
338
+ subtree only — a feature outside the area referencing the name is a compile error, and root
339
+ `authz` bodies may reference root-declared names only). Declare each name in exactly one
340
+ place: re-declaring an inherited name is a compile error.
341
+
342
+ ```typescript
343
+ // quickback.config.ts — define ONCE
344
+ export default defineConfig({
345
+ // ...providers...
346
+ authz: {
347
+ roles: {
348
+ // Compose from BA roles, pseudo-roles, and other named rules:
349
+ staff: { roles: ['admin', 'member'] },
350
+ // Boolean combinators:
351
+ eventStaff: { or: [{ roles: ['staff'] }, { via: 'organizerOf' }] },
352
+ // Relationship-backed (see below):
353
+ attendee: { via: 'attendeeOf' },
354
+ },
355
+ },
356
+ });
357
+ ```
358
+
359
+ ```typescript
360
+ // any feature — REFERENCE by bare name
361
+ export default defineTable(agendaItems, {
362
+ read: { access: { roles: ['eventStaff'] } },
363
+ update: { access: { roles: ['eventStaff'] } },
364
+ });
365
+
366
+ // actions.ts
367
+ checkIn: { access: { roles: ['eventStaff', 'attendee'] }, /* ... */ },
368
+ ```
369
+
370
+ ### Rule shapes
371
+
372
+ Each entry in `authz.roles` is one of four shapes:
373
+
374
+ | Shape | Meaning |
375
+ |---|---|
376
+ | `{ roles: ['admin', 'member'] }` | Composition — matches any of the listed roles (BA, pseudo, or other named rules) |
377
+ | `{ or: [ruleA, ruleB] }` | Matches if **any** sub-rule matches |
378
+ | `{ and: [ruleA, ruleB] }` | Matches only if **all** sub-rules match |
379
+ | `{ via: 'relationshipName' }` | Caller proves a declared relationship — see [Relationship-based authorization](#relationship-based-authorization) below |
380
+
381
+ Rules compose freely — a rule may reference another rule by name (cycles are a compile error).
382
+
383
+ ### Where references resolve
384
+
385
+ A named rule works in the `roles: [...]` array of every access surface. The compiler expands it at build time:
386
+
387
+ | Surface | |
388
+ |---|---|
389
+ | `crud.*.access` | ✓ |
390
+ | `read.access` / `read.views.*.access` | ✓ |
391
+ | `masking.<field>.show` | ✓ for role/composite rules; relationship (`via`) rules refused at compile (v1) |
392
+ | `actions.<name>.access` | ✓ |
393
+ | `realtime.requiredRoles` | ✓ — relationship arms fail closed at the WS handshake and are enforced by the row-stream firewall |
394
+
395
+ Names that **aren't** declared in `authz.roles` — Better Auth roles, pseudo-roles like `AUTHENTICATED` — pass through untouched, so you can mix named rules and raw roles in the same array.
396
+
397
+ ### Beyond roles: named permissions
398
+
399
+ For access that traverses the data graph (FK hops, SpiceDB-style permission composition), see [`authz.permissions` + `authz.arrows`](/compiler/definitions/permissions) — the same define-once-reference-by-name model, one level richer than `authz.roles`.
400
+
401
+ ## Named gates (`authz.rules`)
402
+
403
+ `authz.roles` centralizes the *who*. A **gate** (`authz.rules.<name>`) bundles a full access rule — *who* + an optional row predicate (`record:`) + optional [firewall lanes](/compiler/definitions/firewall#named-gate-references-rule) — under ONE name, declared once:
404
+
405
+ ```typescript
406
+ // quickback.config.ts
407
+ authz: {
408
+ tenants: { org: { column: 'organizationId', equals: 'ctx.activeOrgId' } },
409
+ rules: {
410
+ // who + record: "org staff, but only rows still active"
411
+ activeStaff: {
412
+ who: { roles: ['member', 'admin', 'owner'] },
413
+ record: { status: { equals: 'active' } },
414
+ },
415
+ // who + firewall: an org-OR-event-scope row gate, declared ONCE
416
+ eventRow: {
417
+ who: { roles: ['owner', 'admin', 'member'] },
418
+ firewall: [{ any: [
419
+ { tenant: 'org' },
420
+ { field: 'eventId', equals: 'ctx.scope.event' },
421
+ ] }],
422
+ },
423
+ },
424
+ }
425
+ ```
426
+
427
+ ```typescript
428
+ // any feature — the gate name works like a role name
429
+ export default defineTable(eventLinks, {
430
+ firewall: [{ rule: 'eventRow' }], // firewall stamp
431
+ read: { access: { roles: ['eventRow'] } }, // access stamp
432
+ });
433
+ ```
434
+
435
+ ### The two-stamp contract
436
+
437
+ One shared name, two independent stamps — **a single reference never applies both**:
438
+
439
+ - An **access-position reference** (the bare name in any `roles: [...]` array) applies the gate's `who` + `record` arms **only**. It expands exactly like an inline rule: a who-only gate splices as the flat role list; a who+record gate as `{ and: [who, { record }] }`.
440
+ - A **firewall reference** (`firewall: [{ rule: '<name>' }]`) applies the gate's `firewall` lanes **only**, spliced into the resource's top-level AND array. The `who` of a gate referenced only from `firewall:` is **not consulted** — that is the documented contract, not a silent drop. Firewall-who is legitimately *wider* than access-who (e.g. the firewall admits scope-token holders to rows while read access stays staff-only).
441
+
442
+ Both directions are enforced fail-closed at compile time:
443
+
444
+ | You wrote | Compiler says |
445
+ |---|---|
446
+ | Access reference to a firewall-bearing gate, but the resource's `firewall:` doesn't reference it | **Error** — the row lanes would silently not apply |
447
+ | `firewall: [{ rule }]` naming a gate with no `firewall` arm | **Error** — a who/record-only gate would splice zero lanes |
448
+ | A firewall-bearing gate referenced from an **action's** access or from `masking.show` | **Error, unconditional** — no firewall array exists at those sites (nested `show.or` / `show.and` arms included) |
449
+ | A who-less (firewall-only) gate referenced from an access position | **Error** — row lanes can't masquerade as a who-grant |
450
+ | A gate's `record:` field is not a column of the referencing table | **Error, per reference** — a missing field evaluates against `undefined` at runtime (`notEquals`/`notIn` would silently *grant*) |
451
+ | A spliced gate's firewall lane filters on a column the stamped table doesn't have | **Error, per reference** — the lane could never scope rows there |
452
+
453
+ ### Naming rules
454
+
455
+ Rule names share the reference namespace with roles, so the compiler rejects (at declaration time) a rule name that collides with an `authz.roles` entry, a reserved/provider role, **any scoped-role name** (bare sugar like `attendee` or the canonical `scope:<kind>:<role>` spelling), or a name containing `+` or `:` (the `scope:` prefix always means a token-verified scope principal — a colon-named rule could capture references meant for one).
456
+
457
+ Inside `authz.roles` / gate `who` bodies, `+` hierarchy sugar is banned — write the expanded list (`['member', 'admin', 'owner']`), because `+` expansion runs at resource sites only and a `member+` inside a body would silently never match. Roles may not reference rules (the dependency arrow is one-way), and gates never nest.
458
+
459
+ ### Typo safety
460
+
461
+ A `roles: [...]` name that matches nothing declared is fail-closed at runtime (it never grants) but historically silent. The compiler now emits a warning-level `AUTHZ_UNKNOWN_ROLE_NAME` diagnostic for any name that is not a provider/hierarchy role, pseudo-role, scoped role, or declared role/rule — a typo'd gate name is visible at compile time without breaking projects that use dynamic auth-provider role names. The heuristic runs only for projects that use the authz naming system (any of `authz.roles`, `authz.rules`, or `authz.scopes` declared); projects outside it keep the pre-existing silent-passthrough behavior for dynamic role names.
462
+
331
463
  ## Relationship-based authorization
332
464
 
333
- Beyond Better Auth roles (org membership, user-table role) and pseudo-roles, Quickback supports **relationship-based authorization roles** — names that bind to a declared relationship between the caller and a resource. Use these when access should follow a domain-table membership ("user is a confirmed guest of this event") rather than an org/admin gate.
465
+ Beyond Better Auth roles (org membership, user-table role) and pseudo-roles, Quickback supports **relationship-based authorization roles** — names that bind to a declared relationship between the caller and a resource. Use these when access should follow a domain-table membership ("user is a confirmed guest of this event") rather than an org/admin gate. These are the `{ via: '...' }` rule shape from [Centrally defined access rules](#centrally-defined-access-rules) above.
334
466
 
335
467
  ### `authz.relationships`
336
468
 
@@ -168,6 +168,8 @@ namespace parameters.
168
168
  | `unsafe` | No | Unsafe raw DB mode. Object config (`reason`, `adminOnly`, `crossTenant`, `targetScope`). |
169
169
  | `transition` | No | State-machine policy enforcing the from/to pair (record-based actions). See [Transitions](#transition-state-machine-policy) |
170
170
  | `bulkVariant` | No | Auto-generate a `POST /:resource/batch/{action}` route alongside the per-record route (record-based actions). See [Bulk Variant](#bulk-variant) |
171
+ | `webhook` | No | Standalone only. Compile-declared inbound signature verification (`standard-webhooks`, `hmac-sha256`, or `aws-sns`) that runs on the raw bytes **before** parse/access — see [Inbound webhooks](/stack/webhooks/inbound) |
172
+ | `idempotency` | No | `'dedupe'` — PUBLIC-action opt-in for the `Idempotency-Key` header with dedupe-only semantics (duplicate ⇒ `409` reference; the cached body is never served to a second caller). Standalone actions with a **static** path only (a `:param` path is a compile error — the allowlist matches literal request paths) and the action's access must admit `PUBLIC`. Authenticated routes accept the header automatically — see [API contract](/stack/api-contract) |
171
173
  | `cms` | No | Pass-through metadata blob for CMS surfaces |
172
174
 
173
175
  `execute` must be an `async (ctx) => { … }` arrow function. `async function`
@@ -378,6 +380,20 @@ GET /reports/summary
378
380
  POST /webhooks/stripe
379
381
  ```
380
382
 
383
+ Paths are absolute (`/...`). Inside a [feature area](/compiler/definitions/feature-areas)
384
+ with a mounted prefix, two more forms apply:
385
+
386
+ - **Relative** — `path: './tasks/add'` resolves against the area's prefix
387
+ (`/project/:projectId/tasks/add`). Plain descending segments only; `.` / `..` segments are
388
+ rejected at compile time.
389
+ - **Self-gated** — an absolute path *outside* the area's prefix opts the action out of the
390
+ area's admission gate and MUST carry `route: 'self'` (fail-closed; the marker is rejected
391
+ where it would be dead). The action is then gated solely by its own `access:` and listed in
392
+ `quickback/authz-manifest.json`.
393
+
394
+ An action's `access:` and `anchor:` may reference vocabulary declared by an ancestor area —
395
+ and never vocabulary of an area the feature is not inside (compile error).
396
+
381
397
  ### Example: AI Chat with Streaming
382
398
 
383
399
  ```typescript
@@ -507,6 +523,12 @@ access: {
507
523
  }
508
524
  ```
509
525
 
526
+ If the same role expression shows up on more than one action or resource, define it once in `authz.roles` and reference it by name — see [Centrally defined access rules](/compiler/definitions/access#centrally-defined-access-rules).
527
+
528
+ [Named gates](/compiler/definitions/access#named-gates-authzrules) (`authz.rules`) also work in an action's `roles: [...]` array — a who-only gate expands as its `who`, a who+`record` gate as `{ and: [who, { record }] }` (the record predicate is evaluated against the bound record, exactly like an inline `access.record`). Function-form `access` is opaque to the rewrite and is left untouched.
529
+
530
+ **A firewall-bearing gate on an action is a compile error.** An action has no firewall array — there is no row query for the gate's lanes to constrain before execution — so the compiler refuses rather than letting the row lanes silently not apply. The escape hatch: split the gate into a who-rule referenced from the action plus a firewall-only gate stamped on the owning resource's `firewall:`.
531
+
510
532
  ### Public Access
511
533
 
512
534
  Use `roles: ["PUBLIC"]` for unauthenticated endpoints (contact forms, webhooks, public APIs). Every invocation is **mandatory audit logged** with IP address, input, result, and timing.
@@ -0,0 +1,375 @@
1
+ # Changesets — aggregate writes
2
+
3
+ A **changeset** writes a parent row and its owned relations — junction
4
+ memberships, normalized phones/emails, line items — in **one request**,
5
+ replacing the hand-rolled multi-table action. You declare the one fact the
6
+ compiler was missing — which relations are **compositions** (owned by this
7
+ root) vs **references** (independent entities) — and the compiler generates
8
+ the whole write path.
9
+
10
+ Changesets are a **contract v2** capability (`contract: { version: "v2" }`).
11
+ Declaring `owns` on a v1-pinned project is a compile error.
12
+
13
+ ## Declaring the boundary — `owns`
14
+
15
+ ```ts title="quickback/features/projects/projects.ts"
16
+ export default feature("projects", {
17
+ // ...columns, firewall, guards, masking, read...
18
+ create: { access: { roles: ["admin", "owner"] } },
19
+ update: { access: { roles: ["admin", "owner"] } },
20
+
21
+ owns: {
22
+ tasks: {
23
+ table: "tasks", // camelCase table name — a defineTable in this project
24
+ fk: "projectId", // FK on the CHILD pointing at this root's PK
25
+ refs: { // client-supplied pointers at INDEPENDENT entities
26
+ assigneeId: "people",
27
+ reviewerId: "people", // nullable refs may be omitted or null
28
+ },
29
+ inherit: ["organizationId"], // parent columns copied onto every inserted child
30
+ owns: { // grandchildren — structural nesting, depth-capped
31
+ checklist: { table: "taskChecklistItems", fk: "taskId", inherit: ["organizationId"] },
32
+ },
33
+ },
34
+ },
35
+ });
36
+ ```
37
+
38
+ | Key | Meaning |
39
+ |---|---|
40
+ | `table` | The owned child — **must** be a `defineTable`/`feature()` in the project. String literal, never an identifier. Auth tables can never be owned. |
41
+ | `fk` | The spine: the child column pointing at this root. **Compiler-stamped** on inserts; a client-supplied value is rejected. |
42
+ | `refs` | Columns pointing at independent entities. Client-supplied, **existence-checked inside the caller's tenant** (the referenced table's firewall is ANDed) — on inserts **and** patches. The referenced row is never written through. |
43
+ | `inherit` | Tenant/denorm columns copied verbatim from the (firewall-verified) parent row onto every inserted child. Compiler-stamped; client values rejected. |
44
+ | `owns` | Nested owned relations. Max 3 levels of nesting (the aggregate spans at most 4 tables). |
45
+
46
+ A child's [`q.stamp`](/compiler/definitions/schema#qstamp--proven-principal-identity-columns) identity columns are a **fourth, disjoint** source, sitting alongside `fk`/`inherit`/`refs`. On a changeset **insert** the engine stamps them from the **caller's proven scope claim** (`ctx.scope.<kind>.<claim>`) — *not* from the parent row — but only when the caller is a scope-only principal; an org-admitted caller keeps their client value (org-firewall-bounded). The contrast is exact: `inherit` copies **tenant** columns from the firewall-verified *parent*, `q.stamp` copies **identity** from the proven *token*. A required claim absent on a scope principal fails the op with **403** — emitted *before* the ref-existence checks, so a claim-less caller cannot probe which rows exist. A `refs` key may not alias a `q.stamp` column (a column is compiler-stamped **or** a client ref, never both). On a changeset **patch** op the stamp column is **immutable** — a client value for it is rejected (400) like any systemManaged column, matching the plain update path. Because the stamp lives inside the changeset handler, a **keyed** (`Idempotency-Key`) replay neither re-writes nor re-stamps; a keyless retry re-writes and re-stamps.
47
+
48
+ **Owning a relation is not a write grant.** Every changeset op is admitted by
49
+ the **child table's own crud declaration**: `insert` requires `create:` on the
50
+ child, `patch` requires `update:`, `delete` requires `delete:` (soft mode only
51
+ in v1) — each with its own `access`. There is no per-relation access override:
52
+ access is declared exactly once, on the child.
53
+
54
+ ### `routes: false` — changeset admission without a raw route
55
+
56
+ Widening a child's access for changeset use must not silently open its raw
57
+ CRUD surface. The `create`, `update`, and `delete` op configs accept
58
+ `routes: false` (`upsert`/`put` does not): the access stays declared (it is
59
+ the changeset admission gate) while the raw HTTP route — and its
60
+ auto-promoted batch variant — is never mounted, documented, or counted in
61
+ the operations manifest.
62
+
63
+ ```ts title="quickback/features/projects/tasks.ts"
64
+ update: { access: { roles: ["member", "admin", "owner"] }, routes: false },
65
+ ```
66
+
67
+ ## The wire contract
68
+
69
+ One blessed path — **RFC 5789 media-type dispatch** on the routes you already
70
+ have. No subpath.
71
+
72
+ - `PATCH /api/v2/<resource>/:id` with
73
+ `Content-Type: application/vnd.quickback.changeset+json` — apply a changeset
74
+ to an existing root. Plain `application/json` keeps the flat-column PATCH.
75
+ - `POST /api/v2/<resource>` with the same media type — create the root and its
76
+ children in one changeset.
77
+
78
+ ```jsonc
79
+ // PATCH /api/v2/projects/prj_1 (Content-Type: application/vnd.quickback.changeset+json)
80
+ {
81
+ "patch": { "name": "Renamed" }, // sparse ROOT patch (optional)
82
+ "tasks": {
83
+ "insert": [
84
+ {
85
+ "lid": "t1", // client correlation id
86
+ "title": "Ship it",
87
+ "assigneeId": "per_9", // ref — tenant-checked
88
+ "checklist": { "insert": [{ "label": "QA pass" }] } // grandchild, FKs onto t1's minted id
89
+ }
90
+ ],
91
+ "patch": [{ "id": "tsk_2", "state": "done" }],
92
+ "delete": ["tsk_3"]
93
+ }
94
+ }
95
+ ```
96
+
97
+ ```jsonc
98
+ // Response
99
+ {
100
+ "success": true,
101
+ "root": { "id": "prj_1", "name": "Renamed", /* masked through the root's masking */ },
102
+ "created": { "t1": "tsk_9a…", "/tasks/insert/0/checklist/insert/0": "tci_44…" },
103
+ "meta": { "ops": 4, "transactional": false }
104
+ }
105
+ ```
106
+
107
+ - Inserts/patches apply parent-first (document order); deletes apply
108
+ children-first.
109
+ - `lid` correlates a minted id in `created`; entries without a `lid` key on
110
+ their JSON Pointer. A nested insert's FK comes from its parent op's minted
111
+ id — an unresolvable parent lid is a pointer-carrying **400**, never a
112
+ silent re-parent onto the root.
113
+ - `Prefer: return=minimal` omits `root` from the response. v1 representation
114
+ is **root-row-only** (re-read through the root's masking) — nested aggregate
115
+ reads are the phase-2 `?include=` reader; use [`defineView`
116
+ includes](/compiler/definitions/read) today.
117
+
118
+ ### Headers
119
+
120
+ | Header | Behavior |
121
+ |---|---|
122
+ | `If-Match` | Optimistic concurrency against the **root revision** — the root's `updatedAt` (or the injected `modifiedAt` audit column). Accepted value forms: `W/"<revision>"`, `"<revision>"`, or the bare revision value, where `<revision>` is the raw value of the revision column as returned in the root row. **Do not echo `GET /:id`'s `ETag` header into `If-Match`** — that ETag is the contract layer's body-hash ETag, not this revision, and will always **412**. Compared inside the transaction; mismatch → **412**. Every accepted changeset touches the revision. A root with no revision column answers `If-Match` with **428 PRECONDITION_UNSUPPORTED** — never silently ignored; the POST variant always answers 428 (no pre-existing revision to match). |
123
+ | `Idempotency-Key` | The standard write-retry key. Claims are principal-scoped — a replayed key from a different principal is a 422, never a cached-body leak. |
124
+ | `Prefer` | `return=representation` (default) or `return=minimal`. |
125
+
126
+ ### Errors
127
+
128
+ RFC 9457 `application/problem+json`. The failing op is identified by a JSON
129
+ Pointer in the `pointer` extension (`/tasks/insert/0/assigneeId`). On
130
+ **non-transactional providers** the error also carries an `ops` extension
131
+ listing the outcomes of ops applied before the failure — the honest committed
132
+ prefix. On **transactional providers** the rollback erased every applied op,
133
+ so the error carries **no `ops` extension** (advertising rolled-back ids would
134
+ point clients at rows that no longer exist). **Outcome entries carry only
135
+ `{ pointer, status, id? }` — never child field values** (v1 deliberately
136
+ withholds nested child representation, so errors cannot become an
137
+ unmasked-child side channel).
138
+
139
+ ## The security model — "owning a relation is not a backdoor"
140
+
141
+ The **root op** runs the root table's full single-record gate stack, in order:
142
+ auth → cross-tenant guard → the root's own `update` (PATCH) / `create` (POST)
143
+ access — **always, including child-only bodies; there is no child-only bypass
144
+ lane** → firewall fetch (reveal → 403 / hide → 404, byte-consistent with the
145
+ plain handler) → `requireSelf` → root body schema + ownership guard + guards.
146
+ The POST variant runs the root's full create pipeline (org validation, FK
147
+ existence checks, defaults/computed, ownership stamping).
148
+
149
+ Every **child op** then pays:
150
+
151
+ 1. **Admission** — declared relation, declared op kind (unknown keys are 400s).
152
+ 2. **The child's own access** — the pre-record role gate runs **before any row
153
+ fetch** (no 404-vs-403 ID probing under the aggregate); `record:`
154
+ predicates are evaluated against the fetched row on patch/delete and
155
+ against the submitted input on insert.
156
+ 3. **systemManaged rejection** — client data carrying `fk`, any `inherit`
157
+ column, or an ownership column is **rejected** with the op's pointer, never
158
+ stripped or stamped-over. (The child's *plain-CRUD* guards are unaffected —
159
+ a junction may keep its FK createable for its raw route; the same field in
160
+ a changeset op is rejected because the changeset supplies it structurally.)
161
+ 4. **The child's column body schema** — q-authored children pay the same Zod
162
+ types/enums/lengths backstop their plain POST/PATCH enforces (strict,
163
+ guards-aware, with the compiler-stamped columns omitted). Drizzle-authored
164
+ children have no Zod on their plain routes either, so none applies here —
165
+ parity, not an omission.
166
+ 5. **The child's guards** — `createable`/`updatable` validation.
167
+ 6. **The child's firewall** — every patch/delete WHERE is
168
+ `spine FK = parent id AND child firewall AND id`, same-feature or
169
+ cross-feature alike. Inserts derive tenant columns only from the
170
+ firewall-verified parent row.
171
+ 7. **Tenant-scoped `refs` checks** — each non-null ref must exist inside the
172
+ referenced table's firewall, on **inserts and patches alike** (re-pointing
173
+ a ref pays the same check; only columns present in the op's data are
174
+ checked).
175
+ 8. **Server-minted child ids** — a client-supplied child primary key on an
176
+ insert is rejected (like the plain POST's strict body schema), unless the
177
+ project is configured for client-provided ids (`generateId: false`).
178
+
179
+ Child `delete` ops stamp the **fixed `deletedAt`** audit column — exactly what
180
+ the plain DELETE route stamps (the audit wrapper then auto-stamps
181
+ `deletedBy`). An `isNull` firewall arm on any other column (e.g.
182
+ `archivedAt`) is a read-scoping predicate, never the soft-delete stamp.
183
+
184
+ Compile-time, fail-closed (everything throws, nothing normalizes silently):
185
+
186
+ - **Per-arm tenant coverage**: every column arm of the child's *resolved*
187
+ firewall — including **every branch of an `any:` OR** — must be satisfiable
188
+ by `fk`/`inherit`. Covering one arm of an OR is not coverage. This runs over
189
+ the post-expansion firewall, so lanes spliced from
190
+ [`authz.rules`](/compiler/definitions/access#centrally-defined-access-rules)
191
+ gates and `{ tenant }` anchors are checked too.
192
+ - Children firewalled through a **subquery arm** (`via:`, `{ permission }`,
193
+ arrows) cannot be owned in v1 — even when the arm arrives through a gate
194
+ splice.
195
+ - `refs` keys must be **disjoint** from `{fk} ∪ inherit ∪ ownership columns` —
196
+ a column is either compiler-stamped or a client ref, never both (blocks
197
+ ownership-column injection through a ref).
198
+ - **Relationship / FGA access arms are compile errors** on the changeset lane
199
+ — on the root's `update`/`create` access and on every admitted child op's
200
+ access. Those arms are decided by inline route code the changeset engine
201
+ does not emit in v1; rather than silently widen (or silently 403) the gate,
202
+ the compiler refuses. Use roles/record predicates, or keep the write in an
203
+ authored action. (Function-form access is refused for the same reason.)
204
+ - **Envelope-encrypted roots cannot ride the changeset in v1** — the response
205
+ path does not run the decrypt-then-mask prepare helper, so the returned root
206
+ would carry sealed ciphertext. The compiler refuses rather than degrade
207
+ silently. (Sealed-mode columns are unaffected — plain routes return those
208
+ as-is too.)
209
+ - **Relation names `insert`, `patch`, `delete`, and `lid` are rejected** —
210
+ the wire parser reserves those payload keys, so such a relation would be
211
+ silently unreachable on the wire.
212
+ - One aggregate root per table, acyclic graph, bounded depth, declared child
213
+ ops only, soft-delete children only, contract v2 only.
214
+
215
+ ## `afterCommit` — emit a realtime signal after the changeset commits
216
+
217
+ A changeset that must notify live views declares **`afterCommit`** on the
218
+ aggregate root — a declarative broadcast, **not** a hand-rolled
219
+ `try { realtime.* } catch {}` tail. It fires **one aggregate-level CloudEvent**
220
+ strictly **after** the transaction commits, riding the existing
221
+ [named-invalidation / Broadcaster egress](/stack/realtime/named-invalidations)
222
+ (so it inherits the CloudEvents envelope + AsyncAPI description for free).
223
+
224
+ ```ts title="quickback/features/travel/lodging-reservations.ts"
225
+ export default defineTable(lodgingReservations, {
226
+ // ...firewall / read / crud ...
227
+ owns: { occupants: { table: "lodgingReservationGuests", fk: "reservationId",
228
+ inherit: ["eventId", "organizationId"] } },
229
+ afterCommit: {
230
+ broadcast: {
231
+ travelChanged: {
232
+ event: "attendRealtime.mobileBundleChanged.travelUpdated", // registry.event.variant
233
+ delivery: "thisEvent", // MUST be in the event's `deliveries` allowlist
234
+ payload: {
235
+ eventId: "root.eventId", // a committed root column
236
+ reservationId: "rootId", // the root pk
237
+ occupantIds: "affectedIds", // ids of child rows touched this changeset
238
+ },
239
+ },
240
+ },
241
+ },
242
+ });
243
+ ```
244
+
245
+ - **One event per aggregate**, not one per touched child. The payload carries
246
+ an **affected-ids / changed-paths** roll-up derived from the applied ops
247
+ (`affectedIds` = child ids, `changedPaths` = JSON pointers) — **ids and
248
+ pointers only, never child field values**.
249
+ - **`delivery` is required and fail-closed.** The audience lives on a named
250
+ [delivery profile](/stack/realtime/named-invalidations); it must appear in the
251
+ referenced event's `deliveries` allowlist. There is **no default selection**,
252
+ so an event permitting a narrow AND a wide room can never silently fan a
253
+ changeset frame to the wider one.
254
+ - **Payload sources:** `root.<col>` (a committed root column), `rootId`,
255
+ `affectedIds`, `changedPaths`. Every payload key the variant declares must be
256
+ mapped; unknown sources / undeclared keys are compile errors.
257
+ - **Best-effort:** a broadcast failure never rolls back the committed changeset
258
+ (`console.warn`, dispatched on `waitUntil`).
259
+ - **Root-row frame:** `afterCommit: { realtime: true }` additionally emits the
260
+ root row (postgres_changes-style) on the table's own `realtime` room. The row
261
+ rides unmasked **with the table's `MASKING_CONFIG`** so the Broadcaster masks
262
+ per-subscriber-role at fanout — the same discipline plain CRUD realtime uses.
263
+
264
+ ### Fail-closed disclosure gates
265
+
266
+ Because a broadcast payload is **not** masked at fanout (only the root-row frame
267
+ is), afterCommit fails the build rather than leak:
268
+
269
+ - A **masked `root.<col>`** may ride a broadcast only to a role-only delivery
270
+ whose roles ⊆ the column's unmask roles (same app-role namespace). A
271
+ **scope-keyed** delivery or an **empty unmask set** (`show: { or: 'owner' }`)
272
+ **always** throws.
273
+ - **`affectedIds` / `rootId` / `changedPaths`** carry firewalled row IDs
274
+ (existence/enumeration). They may ride a scope-keyed delivery (bounded to one
275
+ scope-instance room); a role-only / org-wide delivery throws unless you
276
+ acknowledge with `disclosesChildIds: true`.
277
+
278
+ ### `q.scope` verified vs `q.stamp` proven — the "stamp then emit" rule
279
+
280
+ When a changeset [stamps a proven identity](/compiler/definitions/schema#qstamp--proven-principal-identity-columns)
281
+ and then emits it, the two features compose on one write path:
282
+
283
+ | | `q.scope('<kind>')` | `q.stamp({ fromScope, claim })` |
284
+ |---|---|---|
285
+ | Purpose | tenant isolation column | proven-principal **identity** column |
286
+ | Firewall arm? | **yes** — it is the tenant WHERE | **never** |
287
+ | Verified how? | firewall re-verifies on read/patch/delete | token provenance (un-spoofable) |
288
+ | Phrase | "**stamp AND verify**" | "stamp AND **prove**" |
289
+ | Safe to broadcast? | to the matching scope-keyed room | **only** to an audience ⊆ the stamping scope kind |
290
+
291
+ A `q.stamp` identity column (e.g. `guestId`) sourced via `root.<col>` is
292
+ **audience-gated like `affectedIds`** (05×06 integration): the delivery must be
293
+ scope-keyed to the **same scope kind** that stamped it, else the build fails —
294
+ unless you acknowledge with **`disclosesStampedIdentity: true`**. A stamp is
295
+ un-spoofable, not un-*sensitive*: provenance is not audience clearance.
296
+
297
+ ### Idempotency — at-least-once
298
+
299
+ afterCommit is **at-least-once**, exactly as idempotent as the write it rides.
300
+ A retry carrying the **same `Idempotency-Key`** neither re-writes nor re-emits
301
+ (the middleware returns the cached response before the handler runs). A
302
+ **keyless** retry re-runs the whole handler → re-writes **and** re-emits. Callers
303
+ that need single-delivery must send an `Idempotency-Key`.
304
+
305
+ ### No-tx: "row written ⇏ event fired"
306
+
307
+ On a no-tx provider (D1 / neon-http), a mid-changeset failure **throws** before
308
+ the success path, so **no frames emit** for the partially-applied prefix —
309
+ `meta.transactional: false` is the only guarantee signal. A **fully-successful**
310
+ no-tx changeset **does** emit, still with `transactional: false`. Never assume
311
+ "row written ⇒ event fired"; `meta.transactional` is the contract.
312
+
313
+ > **Deferred out of v1:** embedding reindex on the changeset lane, `notify`
314
+ > (device push — a WS broadcast is not an APNs/web-push delivery), and lifting
315
+ > `afterCommit` onto plain tables/actions. The compiler still **warns** when an
316
+ > `owns` root/child declares `realtime` **without** `afterCommit`, or declares
317
+ > `embeddings`, so a silent asymmetry can't be enabled unknowingly.
318
+
319
+ ## Atomicity — honest, per provider
320
+
321
+ The whole changeset runs inside `db.transaction()` when the provider supports
322
+ it; `meta.transactional` reports the actual guarantee (same contract as
323
+ [batch operations](/compiler/targets/hono-api/using-the-api/batch-operations)):
324
+
325
+ | Provider | transactional | Behavior |
326
+ |---|---|---|
327
+ | postgres / supabase / neon (websocket / hyperdrive) / libsql / better-sqlite3 / bun-sqlite | `true` | One transaction; any op failure rolls back the root op and every child op |
328
+ | cloudflare-d1, neon over http (the Cloudflare default) | `false` | Deterministic parent-first **fail-fast**: the first failure stops the changeset; ops already applied stay committed (a consistent prefix — each was independently authorized) |
329
+
330
+ ## Calling it from authored code
331
+
332
+ The engine is exported per root as `apply<Singular>Changeset` — the seam
333
+ authored actions delegate through when they still need residue logic
334
+ (preconditions, server-side transforms, notifications) around the aggregate
335
+ write:
336
+
337
+ ```ts title="quickback/features/projects/actions/importBoard.ts"
338
+ // Action files are compiled into the feature directory, next to the
339
+ // generated module — the relative import resolves at runtime.
340
+ import { applyProjectChangeset } from "../projects.changeset";
341
+
342
+ export default defineAction({
343
+ // ...description, input, access...
344
+ execute: async ({ db, ctx, input }) => {
345
+ // precondition / transform residue …
346
+ const result = await applyProjectChangeset(db, ctx, input.projectId, input.changes);
347
+ // notify / respond …
348
+ return result;
349
+ },
350
+ });
351
+ ```
352
+
353
+ **There is no trusted mode.** The auth assertion, cross-tenant guard, and the
354
+ root's own pre-record access gate are the helper's first statements — an
355
+ authored action whose action-level access is looser than the root's crud
356
+ access still pays the root's declared authorization when it delegates. The
357
+ HTTP handler is a thin wrapper over the same helper (parse + Problem-Details
358
+ rendering only).
359
+
360
+ ## Standards mapping
361
+
362
+ | Changeset concept | Grounded in |
363
+ |---|---|
364
+ | Media-type dispatch on PATCH | RFC 5789 (the media type selects patch semantics) |
365
+ | `lid` correlation + op list | JMAP `/set` creation ids, JSON:API `lid` |
366
+ | Root-revision `If-Match` | JMAP state tokens, RFC 9110 preconditions |
367
+ | Pointer-carrying errors | RFC 9457 Problem Details + RFC 6901 JSON Pointer |
368
+ | Nested relation ops | SCIM PATCH (typed sub-resources) |
369
+
370
+ ## What stays phase 2
371
+
372
+ Full-document `replace` diff sugar (and its `key:` reconciliation field), the
373
+ `application/json-patch+json` representation, cross-branch `$lid` references,
374
+ nested `Prefer: return=representation`, `?include=` aggregate reads, and
375
+ find-or-create roots by business key (`conflictTarget`).