@quickback-dev/cli 0.34.3 → 0.39.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 (130) hide show
  1. package/dist/commands/compile.d.ts.map +1 -1
  2. package/dist/commands/compile.js +36 -2
  3. package/dist/commands/compile.js.map +1 -1
  4. package/dist/commands/compile.test.d.ts +2 -0
  5. package/dist/commands/compile.test.d.ts.map +1 -0
  6. package/dist/commands/compile.test.js +83 -0
  7. package/dist/commands/compile.test.js.map +1 -0
  8. package/dist/commands/create.js +15 -11
  9. package/dist/commands/create.js.map +1 -1
  10. package/dist/commands/migrations.d.ts +33 -0
  11. package/dist/commands/migrations.d.ts.map +1 -1
  12. package/dist/commands/migrations.js +41 -2
  13. package/dist/commands/migrations.js.map +1 -1
  14. package/dist/commands/migrations.test.d.ts +2 -0
  15. package/dist/commands/migrations.test.d.ts.map +1 -0
  16. package/dist/commands/migrations.test.js +67 -0
  17. package/dist/commands/migrations.test.js.map +1 -0
  18. package/dist/docs/content.d.ts.map +1 -1
  19. package/dist/docs/content.js +56 -26
  20. package/dist/docs/content.js.map +1 -1
  21. package/dist/examples/recruitment.tar.gz +0 -0
  22. package/dist/index.js +1 -1
  23. package/dist/lib/action-harvest.d.ts +48 -0
  24. package/dist/lib/action-harvest.d.ts.map +1 -0
  25. package/dist/lib/action-harvest.js +292 -0
  26. package/dist/lib/action-harvest.js.map +1 -0
  27. package/dist/lib/action-harvest.test.d.ts +2 -0
  28. package/dist/lib/action-harvest.test.d.ts.map +1 -0
  29. package/dist/lib/action-harvest.test.js +112 -0
  30. package/dist/lib/action-harvest.test.js.map +1 -0
  31. package/dist/lib/api-client.d.ts +10 -0
  32. package/dist/lib/api-client.d.ts.map +1 -1
  33. package/dist/lib/api-client.js +17 -1
  34. package/dist/lib/api-client.js.map +1 -1
  35. package/dist/lib/api-client.test.js +19 -0
  36. package/dist/lib/api-client.test.js.map +1 -1
  37. package/dist/lib/artifact-routing.d.ts +1 -0
  38. package/dist/lib/artifact-routing.d.ts.map +1 -1
  39. package/dist/lib/artifact-routing.js +15 -3
  40. package/dist/lib/artifact-routing.js.map +1 -1
  41. package/dist/lib/artifact-routing.test.js +12 -1
  42. package/dist/lib/artifact-routing.test.js.map +1 -1
  43. package/dist/lib/file-loader.d.ts +1 -0
  44. package/dist/lib/file-loader.d.ts.map +1 -1
  45. package/dist/lib/file-loader.js +34 -1
  46. package/dist/lib/file-loader.js.map +1 -1
  47. package/dist/lib/file-loader.test.js +28 -4
  48. package/dist/lib/file-loader.test.js.map +1 -1
  49. package/dist/lib/prepare-state-output.d.ts +8 -0
  50. package/dist/lib/prepare-state-output.d.ts.map +1 -0
  51. package/dist/lib/prepare-state-output.js +17 -0
  52. package/dist/lib/prepare-state-output.js.map +1 -0
  53. package/dist/lib/prepare-state-output.test.d.ts +2 -0
  54. package/dist/lib/prepare-state-output.test.d.ts.map +1 -0
  55. package/dist/lib/prepare-state-output.test.js +31 -0
  56. package/dist/lib/prepare-state-output.test.js.map +1 -0
  57. package/dist/skill/SKILL.md +4 -4
  58. package/dist/skill/agents/quickback-specialist/AGENT.md +3 -3
  59. package/dist/skill/docs/changelog.md +643 -0
  60. package/dist/skill/docs/compiler/config/agents.md +1 -1
  61. package/dist/skill/docs/compiler/config/auth.md +1 -1
  62. package/dist/skill/docs/compiler/config/index.md +8 -9
  63. package/dist/skill/docs/compiler/config/providers.md +3 -0
  64. package/dist/skill/docs/compiler/config/single-tenant.md +65 -73
  65. package/dist/skill/docs/compiler/definitions/access.md +40 -33
  66. package/dist/skill/docs/compiler/definitions/actions.md +1 -1
  67. package/dist/skill/docs/compiler/definitions/arrows.md +269 -0
  68. package/dist/skill/docs/compiler/definitions/diagnostics.md +136 -0
  69. package/dist/skill/docs/compiler/definitions/feature.md +3 -3
  70. package/dist/skill/docs/compiler/definitions/fga.md +314 -0
  71. package/dist/skill/docs/compiler/definitions/firewall.md +94 -7
  72. package/dist/skill/docs/compiler/definitions/permissions.md +145 -0
  73. package/dist/skill/docs/compiler/definitions/schema.md +8 -2
  74. package/dist/skill/docs/compiler/definitions/scopes.md +339 -0
  75. package/dist/skill/docs/compiler/definitions/views.md +66 -0
  76. package/dist/skill/docs/compiler/getting-started/template-blog.md +7 -7
  77. package/dist/skill/docs/compiler/getting-started/template-empty.md +1 -4
  78. package/dist/skill/docs/compiler/getting-started/templates.md +6 -6
  79. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/actions-api.md +2 -2
  80. package/dist/skill/docs/stack/account-ui/features/admin.md +1 -1
  81. package/dist/skill/docs/stack/account-ui/features/index.md +2 -2
  82. package/dist/skill/docs/stack/cms/connecting.md +17 -16
  83. package/dist/skill/docs/stack/cms/index.md +7 -7
  84. package/dist/skill/docs/stack/cms/schema-format.md +0 -2
  85. package/dist/skill/docs/stack/cms/schema-registry.md +0 -6
  86. package/dist/skill/docs/stack/cms/security.md +6 -6
  87. package/dist/skill/docs/stack/realtime/durable-objects.md +48 -7
  88. package/dist/skill/docs/stack/realtime/live-views.md +168 -0
  89. package/dist/skill/docs/stack/realtime/partyserver-rooms.md +22 -2
  90. package/dist/skill/docs/stack/storage/r2.md +112 -3
  91. package/dist/skill/docs/stack/storage/using-r2.md +30 -10
  92. package/dist/templates/registry.js +2 -2
  93. package/dist/templates/registry.js.map +1 -1
  94. package/package.json +1 -1
  95. package/src/examples/recruitment.tar.gz +0 -0
  96. package/src/skill/SKILL.md +4 -4
  97. package/src/skill/agents/quickback-specialist/AGENT.md +3 -3
  98. package/src/skill/docs/changelog.md +643 -0
  99. package/src/skill/docs/compiler/config/agents.md +1 -1
  100. package/src/skill/docs/compiler/config/auth.md +1 -1
  101. package/src/skill/docs/compiler/config/index.md +8 -9
  102. package/src/skill/docs/compiler/config/providers.md +3 -0
  103. package/src/skill/docs/compiler/config/single-tenant.md +65 -73
  104. package/src/skill/docs/compiler/definitions/access.md +40 -33
  105. package/src/skill/docs/compiler/definitions/actions.md +1 -1
  106. package/src/skill/docs/compiler/definitions/arrows.md +269 -0
  107. package/src/skill/docs/compiler/definitions/diagnostics.md +136 -0
  108. package/src/skill/docs/compiler/definitions/feature.md +3 -3
  109. package/src/skill/docs/compiler/definitions/fga.md +314 -0
  110. package/src/skill/docs/compiler/definitions/firewall.md +94 -7
  111. package/src/skill/docs/compiler/definitions/permissions.md +145 -0
  112. package/src/skill/docs/compiler/definitions/schema.md +8 -2
  113. package/src/skill/docs/compiler/definitions/scopes.md +339 -0
  114. package/src/skill/docs/compiler/definitions/views.md +66 -0
  115. package/src/skill/docs/compiler/getting-started/template-blog.md +7 -7
  116. package/src/skill/docs/compiler/getting-started/template-empty.md +1 -4
  117. package/src/skill/docs/compiler/getting-started/templates.md +6 -6
  118. package/src/skill/docs/compiler/targets/hono-api/using-the-api/actions-api.md +2 -2
  119. package/src/skill/docs/stack/account-ui/features/admin.md +1 -1
  120. package/src/skill/docs/stack/account-ui/features/index.md +2 -2
  121. package/src/skill/docs/stack/cms/connecting.md +17 -16
  122. package/src/skill/docs/stack/cms/index.md +7 -7
  123. package/src/skill/docs/stack/cms/schema-format.md +0 -2
  124. package/src/skill/docs/stack/cms/schema-registry.md +0 -6
  125. package/src/skill/docs/stack/cms/security.md +6 -6
  126. package/src/skill/docs/stack/realtime/durable-objects.md +48 -7
  127. package/src/skill/docs/stack/realtime/live-views.md +168 -0
  128. package/src/skill/docs/stack/realtime/partyserver-rooms.md +22 -2
  129. package/src/skill/docs/stack/storage/r2.md +112 -3
  130. package/src/skill/docs/stack/storage/using-r2.md +30 -10
@@ -21,7 +21,7 @@ The CMS generates its entire UI from your Quickback definitions. Define a table
21
21
  - **Embedded in your Worker** — Set `cms: true` in config. The CMS is served as static assets from the same Cloudflare Worker as your API — same origin, no CORS, auth cookies work naturally.
22
22
  - **Dual view modes** — Table browse mode for navigation and Data Table mode for spreadsheet-style editing.
23
23
  - **Role-based access** — Owner, admin, and member roles with live switching. CRUD buttons hidden when unauthorized.
24
- - **Multi-tenant & single-tenant** — Org-scoped access by default, with single-tenant mode for simpler projects.
24
+ - **Multi-tenant & fixed-org** — Org-scoped access by default, with pinned-organization mode for simpler deployments.
25
25
  - **Inline spreadsheet editing** — Excel/Google Sheets-like editing with keyboard navigation (arrows, Tab, Enter, Escape).
26
26
  - **FK typeahead** — Server-side search for foreign key fields with debounced queries and keyboard navigation.
27
27
  - **Field masking** — Email, phone, SSN, and redaction patterns applied per role. Masked fields show a lock icon.
@@ -109,14 +109,14 @@ cms: { domain: "cms.example.com" }
109
109
 
110
110
  This adds a custom domain route to `wrangler.toml`. Both domains serve the same Worker — `api.example.com` for the API, `cms.example.com` for the CMS. The compiler also auto-infers a unified `quickback.example.com` domain where everything is available. See [Multi-Domain Architecture](/compiler/config/domains).
111
111
 
112
- ### Access gate (admin-only by default)
112
+ ### Access gate (platform-control-plane by default)
113
113
 
114
- CMS access defaults to `access: "admin"` — only `user.role === "admin"` (the user-table role from Better Auth's admin plugin) can reach `/cms/*`. Non-admin authenticated users are redirected to `/account/profile`. The gate is enforced at **four layers** — defense in depth:
114
+ CMS access defaults to `access: "admin"` — only `user.role === "appmanager"` (the user-table platform control-plane role) can reach `/cms/*`. When `cms.sysadmin: true`, `user.role === "sysadmin"` is also admitted. Other authenticated users are redirected to `/account/profile`. The gate is enforced at **four layers** — defense in depth:
115
115
 
116
- 1. **Account UI link** — the "Go to CMS" button is hidden for non-admins.
117
- 2. **CMS SPA shell** — the Worker returns `403 Admin access required` before serving `index.html` to a non-admin. Unauthenticated requests are redirected to the login page.
118
- 3. **`/api/v1/schema`** — the CMS metadata endpoint checks `ctx.userRole === "admin"` and returns `403` otherwise.
119
- 4. **`custom_view` routes** — the CMS-internal saved-views table is gated on `userRole: ["admin"]` (see the [`userRole` access primitive](/compiler/definitions/access#userrole)) rather than org membership.
116
+ 1. **Account UI link** — the "Go to CMS" button is hidden for callers outside those roles.
117
+ 2. **CMS SPA shell** — the Worker returns `403 Platform operator access required` before serving `index.html` to a non-operator. Unauthenticated requests are redirected to the login page.
118
+ 3. **`/api/v1/schema`** — the CMS metadata endpoint checks `ctx.userRole === "appmanager"` (and admits `sysadmin` when enabled) and returns `403` otherwise.
119
+ 4. **`custom_view` routes** — the CMS-internal saved-views table is gated on `userRole: ["appmanager"]` (see the [`userRole` access primitive](/compiler/definitions/access#userrole)) rather than org membership.
120
120
 
121
121
  Your resource API endpoints (`/api/v1/<resource>`) are **not** affected — they continue to use the per-resource `read`, `create`, `update`, `delete`, and `upsert` access rules you defined.
122
122
 
@@ -11,7 +11,6 @@ interface SchemaRegistry {
11
11
  generatedAt: string;
12
12
  generatedBy: string;
13
13
  version: string;
14
- singleTenant?: boolean;
15
14
  features: Record<string, string[]>;
16
15
  tables: Record<string, TableMeta>;
17
16
  tablesByFeature: Record<string, string[]>;
@@ -26,7 +25,6 @@ interface SchemaRegistry {
26
25
  | `generatedAt` | ISO 8601 timestamp of when the registry was generated |
27
26
  | `generatedBy` | Always `"quickback-compiler"` |
28
27
  | `version` | Compiler version string |
29
- | `singleTenant` | When `true`, project has no organization layer (single-tenant mode) |
30
28
  | `features` | Map of feature name to array of source file names |
31
29
  | `tables` | Map of camelCase table name to full table metadata |
32
30
  | `tablesByFeature` | Map of feature name to array of table names in that feature |
@@ -24,7 +24,6 @@ The top-level structure of `schema-registry.json`:
24
24
  "generatedAt": "2026-02-14T06:26:53.554Z",
25
25
  "generatedBy": "quickback-compiler",
26
26
  "version": "1.0.0",
27
- "singleTenant": false,
28
27
  "features": { ... },
29
28
  "tables": { ... },
30
29
  "tablesByFeature": { ... },
@@ -39,7 +38,6 @@ The top-level structure of `schema-registry.json`:
39
38
  | `generatedAt` | `string` | ISO timestamp of generation |
40
39
  | `generatedBy` | `string` | Always `"quickback-compiler"` |
41
40
  | `version` | `string` | Compiler version used |
42
- | `singleTenant` | `boolean?` | When `true`, no organization layer |
43
41
  | `features` | `Record<string, string[]>` | Feature name to file list mapping |
44
42
  | `tables` | `Record<string, TableMeta>` | Table name to full metadata |
45
43
  | `tablesByFeature` | `Record<string, string[]>` | Feature name to table name list |
@@ -210,10 +208,6 @@ When features include `definePage()` files (in `features/{name}/pages/`), the co
210
208
 
211
209
  The CMS reads these fields to render custom pages in the sidebar and route to the page renderer. See [Custom Pages](/stack/cms/pages) for the full `definePage()` API.
212
210
 
213
- ## Single-Tenant Mode
214
-
215
- When `singleTenant` is `true` in the registry (set when the project config has `features.organizations: false`), the CMS skips the organization gate and reads the user's role directly from `user.role` on the session instead of from organization membership.
216
-
217
211
  ## Next Steps
218
212
 
219
213
  - **[Connecting](/stack/cms/connecting)** — Demo mode vs. live mode setup
@@ -2,20 +2,20 @@
2
2
 
3
3
  The CMS respects all four Quickback security layers. Every UI element — buttons, form fields, table columns, action menus — adapts based on the current user's role and the security rules defined in your feature files.
4
4
 
5
- ## CMS Access (admin-only by default)
5
+ ## CMS Access (platform-control-plane by default)
6
6
 
7
- The CMS is restricted to Better Auth platform admins (`user.role === "admin"`) by default — non-admin authenticated users are redirected to `/account/profile`. To allow any authenticated user, opt out explicitly:
7
+ The CMS is restricted to Better Auth platform control-plane users (`user.role === "appmanager"`) by default. If `cms.sysadmin: true` is enabled, `user.role === "sysadmin"` is also admitted. Other authenticated users are redirected to `/account/profile`. To allow any authenticated user, opt out explicitly:
8
8
 
9
9
  ```typescript
10
10
  cms: { access: "user" }
11
11
  ```
12
12
 
13
- Under the default `access: "admin"`, the compiler emits server-side gates on every CMS-facing surface so a non-admin can't reach the CMS even by bypassing the SPA:
13
+ Under the default `access: "admin"`, the compiler emits server-side gates on every CMS-facing surface so a non-operator can't reach the CMS even by bypassing the SPA:
14
14
 
15
15
  1. **Account UI** — the "Go to CMS" button is hidden.
16
- 2. **CMS SPA shell** — the Worker checks `ctx.userRole === "admin"` before serving `index.html`. Unauthenticated requests are redirected to login; authenticated non-admins get `403 Admin access required`.
17
- 3. **`/api/v1/schema`** — the CMS metadata endpoint returns `403` to non-admins.
18
- 4. **`custom_view` routes** — the CMS-internal saved-views table uses `userRole: ["admin"]` (see [`userRole`](/compiler/definitions/access#userrole-vs-roles)), so saved views can't be read or modified from outside the CMS by non-admin accounts.
16
+ 2. **CMS SPA shell** — the Worker checks `ctx.userRole === "appmanager"` before serving `index.html`. When `cms.sysadmin: true`, sysadmins are also admitted. Unauthenticated requests are redirected to login; authenticated non-operators get `403 Platform operator access required`.
17
+ 3. **`/api/v1/schema`** — the CMS metadata endpoint returns `403` to callers outside those roles.
18
+ 4. **`custom_view` routes** — the CMS-internal saved-views table uses `userRole: ["appmanager"]` (and, when `cms.sysadmin: true`, also admits `sysadmin`), so saved views can't be read or modified from outside the CMS by non-operator accounts.
19
19
  5. **In-SPA gate** — if any earlier layer is bypassed, the SPA still redirects the user to `/account/profile`.
20
20
 
21
21
  Your resource API endpoints keep whatever `read`, `create`, `update`, `delete`, or `upsert` access rules you defined — they're the app's data API and unaffected by the CMS gate.
@@ -60,11 +60,54 @@ providers: {
60
60
 
61
61
  That tells `/broadcast/v1/ws-ticket` to authenticate with Better Auth, verify the `attendee` relationship role against `body.eventId`, and mint a short-lived ticket scoped to the resolved `events:<id>` lane.
62
62
 
63
+ ### Namespace-backed tickets (per-matched-lane)
64
+
65
+ The single-`role` form above authorizes the ticket through **one** relationship.
66
+ When the room is gated by an [authz namespace](/compiler/definitions/scopes#mintscope-mint-the-scope-token-from-the-namespace-resolver)
67
+ with a **multi-lane `via:`** — e.g. an event reachable by attendees, organizers,
68
+ contractors, *and* org admins — point the ticket at the namespace instead, and it
69
+ authorizes through the namespace's full `via` (per-matched-lane):
70
+
71
+ ```typescript
72
+ realtime: {
73
+ wsTicket: {
74
+ namespace: "eventScope", // authorize via this namespace's full multi-lane `via`
75
+ requestField: "eventId",
76
+ scopeTable: "events",
77
+ },
78
+ },
79
+ ```
80
+
81
+ `/broadcast/v1/ws-ticket` now runs the **same first-match-wins gate** the
82
+ namespace uses, and issues the ticket for whichever lane matched:
83
+
84
+ | Caller matched via | Ticket role |
85
+ |---|---|
86
+ | `attendeeOf` (relationship lane) | `attendee` |
87
+ | `organizerOf` | `organizer` |
88
+ | `contractorOf` | `contractor` |
89
+ | `{ roles: ["admin","owner"] }` (bulk lane) | the caller's **org/membership roles** — no scope role |
90
+
91
+ This closes the gap where the single-`role` form denied (`403`) an org admin who
92
+ could legitimately reach the room through the bulk lane but isn't a confirmed
93
+ attendee — their realtime socket now opens.
94
+
95
+ > **`scopeTable` must be tenant-scoped.** Before minting, the route loads the
96
+ > `scopeTable` row by `requestField` through *its own firewall* — so a ticket can
97
+ > only target a room whose resource resolves under the caller's tenant (an org-A
98
+ > admin requesting an org-B `eventId` gets `403`, not a cross-tenant socket). Because
99
+ > the room *is* the data — there is no firewall between a ticket and a Durable
100
+ > Object room — the compiler **rejects at build time** a namespace-backed
101
+ > `wsTicket` whose `scopeTable` has `firewall: { exception: true }` or a non-tenant
102
+ > (literal-only) firewall with no org/owner/team isolation. Use a tenant-scoped
103
+ > `scopeTable`.
104
+
105
+
63
106
  ## When auto-broadcast fires (and when you call it manually)
64
107
 
65
108
  Quickback emits auto-broadcasts in **only one place**: the generated CRUD route handlers (`POST /` create, `PATCH /:id` update, `DELETE /:id` delete) for resources with `realtime.enabled` (or covered by `dbConfig.realtime: true`'s project-level default). Those handlers wrap each successful write with a `realtime.insert / update / delete` call before responding.
66
109
 
67
- Everywhere else — action handlers, queue consumers, scheduled jobs, custom Hono routes — you broadcast manually via the `createRealtime(env)` helper described below.
110
+ Everywhere else — action handlers, queue consumers, scheduled jobs, custom Hono routes — you broadcast manually. In action handlers on realtime-enabled projects, Quickback now injects a typed `realtime` helper directly into `execute(...)`; outside actions you still call `createRealtime(env)` yourself.
68
111
 
69
112
  | Mutation site | Auto-broadcast? | Why |
70
113
  |---|---|---|
@@ -78,14 +121,10 @@ The rule of thumb: if your code calls `db.insert(...)` / `scoped.insert(...)` di
78
121
 
79
122
  ## Generated Helper
80
123
 
81
- The `createRealtime()` factory provides convenient methods for both Postgres Changes (CRUD events) and custom broadcasts:
124
+ Action handlers on realtime-enabled projects receive a typed `realtime` param. The underlying `createRealtime()` factory still powers it and remains the API to use from queues, cron jobs, and other non-action code:
82
125
 
83
126
  ```typescript
84
- import { createRealtime } from '../lib/realtime';
85
-
86
- export const execute: ActionExecutor = async ({ db, ctx, input }) => {
87
- const realtime = createRealtime(ctx.env);
88
-
127
+ export const execute: ActionExecutor = async ({ db, ctx, input, realtime }) => {
89
128
  // After creating a record
90
129
  await realtime.insert('applications', newApplication, ctx.activeOrgId!);
91
130
 
@@ -99,6 +138,8 @@ export const execute: ActionExecutor = async ({ db, ctx, input }) => {
99
138
  };
100
139
  ```
101
140
 
141
+ `env` is also typed in action handlers, so custom bindings like R2, D1, Queues, Durable Objects, and auth env vars no longer need `(env as any)` casts.
142
+
102
143
  For explicit targeting, pass an object instead of the historical org string:
103
144
 
104
145
  ```typescript
@@ -0,0 +1,168 @@
1
+ # Live Views
2
+
3
+ A **live view** is a named *surface*: a root row plus the related data a screen
4
+ shows around it — forward foreign-key display values and reverse-FK child
5
+ collections. When a client subscribes to a live view, the open surface stays
6
+ whole in realtime: any write to the root row **or** a related row that shares a
7
+ foreign key is pushed as a `view_changes` delta the client splices in place.
8
+
9
+ This is the difference from table-level [`postgres_changes`](/stack/realtime/using-realtime)
10
+ broadcasts, which are single-row, single-table. A person-detail screen that
11
+ shows a `people` row plus rows from a normalized `phone_numbers` table would
12
+ otherwise have to stitch together separate per-table events and figure out that
13
+ a `phone_numbers` insert with `personId = X` belongs to the person it has open.
14
+ Live views do that mapping for you.
15
+
16
+ > Live views ride the realtime Broadcaster. You must have realtime enabled
17
+ > (`providers.database.config.realtime: true`). Declaring a view without
18
+ > realtime is a compile-time error.
19
+
20
+ ## Defining a view
21
+
22
+ Views live in `services/views/<name>.ts`:
23
+
24
+ ```typescript
25
+ // services/views/person-detail.ts
26
+ import { defineView } from 'quickback';
27
+
28
+ export default defineView({
29
+ name: 'person-detail',
30
+ root: 'people',
31
+ include: [
32
+ { relation: 'companyId' }, // forward FK → company display value
33
+ { relation: 'phone_numbers' }, // reverse FK → phoneNumbers[] collection
34
+ ],
35
+ });
36
+ ```
37
+
38
+ - **`root`** — the table the surface is keyed by. Must be a `defineTable`
39
+ resource (its firewall + read access gate the surface).
40
+ - **`include[].relation`** — a forward-FK column on the root (`companyId`), or
41
+ the name of a child table that references the root (`phone_numbers`). The
42
+ compiler auto-detects the direction from the foreign-key graph; pass
43
+ `kind: 'forward' | 'reverse'` to disambiguate.
44
+ - **`as`** — the response key the related data is spliced under. Defaults to a
45
+ derived name: forward strips a trailing `Id` (`companyId` → `company`),
46
+ reverse uses the child table name (`phone_numbers` → `phoneNumbers`).
47
+ - **`fields`** — optional column projection on the included table.
48
+
49
+ The materialized surface looks like:
50
+
51
+ ```jsonc
52
+ {
53
+ "id": "person_123",
54
+ "name": "Ada Lovelace",
55
+ "email": "ad***@example.com", // masked per the people table's masking config
56
+ "company": "Analytical Engines", // forward display value
57
+ "phoneNumbers": [ // reverse-FK child collection
58
+ { "id": "ph_1", "number": "+1..." }
59
+ ]
60
+ }
61
+ ```
62
+
63
+ Every included table is read through **its own** `firewall` and `masking` — a
64
+ subscriber only ever sees related rows they're already allowed to read, masked
65
+ exactly as they would be on a normal read.
66
+
67
+ ## Reading a surface
68
+
69
+ The compiler generates a read endpoint per view:
70
+
71
+ ```http
72
+ GET /api/v1/views/person-detail/person_123
73
+ → { "data": { ...surface }, "seq": 7 }
74
+ ```
75
+
76
+ `seq` is the surface's current monotonic sequence — the client uses it to detect
77
+ dropped deltas. A `404` is returned when the caller can't read the root row
78
+ (indistinguishable from "doesn't exist", closing the id-probe channel).
79
+
80
+ ## Subscribing (client)
81
+
82
+ The built-in CMS and Account SPAs ship a `useView` hook:
83
+
84
+ ```tsx
85
+ import { useView } from '~/lib/realtime/use-view';
86
+
87
+ function PersonDetail({ personId }: { personId: string }) {
88
+ const { data, connected, loading } = useView('person-detail', personId);
89
+ // `data` stays live: editing the person merges into the root; adding a phone
90
+ // appends to data.phoneNumbers; deleting one removes it — no refetch.
91
+ }
92
+ ```
93
+
94
+ Under the hood `useView` uses a **subscribe-then-snapshot** flow so no change
95
+ slips through the gap between reading the surface and the socket going live:
96
+
97
+ 1. Requests a **view-scoped ws-ticket** (`POST /broadcast/v1/ws-ticket` with
98
+ `{ view, rootId }`) — gated by the same root firewall as the read endpoint —
99
+ and opens a WebSocket scoped to `view:<view>:<rootId>`.
100
+ 2. Once the socket is open, fetches the full surface via
101
+ `GET /api/v1/views/<view>/:rootId`. Deltas arriving during that fetch are
102
+ **buffered**, then replayed after the snapshot applies (the route reads the
103
+ `seq` baseline *before* materializing, so the snapshot is at least as fresh
104
+ as `seq`, and replay is idempotent — collections key by row `id`).
105
+ 3. Applies `view_changes` deltas in place (the **hybrid-delta** model):
106
+ - `target: 'root'` + `UPDATE` → shallow-merge into the surface root
107
+ - `target: 'root'` + `DELETE` → surface cleared
108
+ - `target: 'collection'` → append / replace-by-key / remove-by-key on `data[as]`
109
+ - `delta.resync` → refetch the surface (the stricter-child path above)
110
+ 4. Tracks `seq`. A gap (`seq !== last + 1`) or a WebSocket reconnect triggers a
111
+ full **resync** — the safety net that heals any dropped delta (Cloudflare D1
112
+ has no transactions, so emit is best-effort by design). If the server can't
113
+ read the baseline it returns `seq: null`; the client then adopts the first
114
+ delta's `seq` instead of treating it as `0`, so a transient read error never
115
+ spirals into a resync loop. Overlapping resyncs are token-guarded so a slow
116
+ earlier fetch can't clobber a newer surface.
117
+
118
+ To subscribe from a custom client, request a ticket with `{ view, rootId }` and
119
+ connect to `…/broadcast/v1/websocket?ws_ticket=<ticket>`. Messages are:
120
+
121
+ ```jsonc
122
+ {
123
+ "type": "view_changes",
124
+ "view": "person-detail",
125
+ "rootId": "person_123",
126
+ "seq": 8,
127
+ "delta": { "target": "collection", "op": "INSERT", "as": "phoneNumbers",
128
+ "key": "ph_2", "row": { "id": "ph_2", "number": "+1..." } }
129
+ }
130
+ ```
131
+
132
+ ## How changes are captured
133
+
134
+ Deltas are emitted from the **write chokepoint** — the same wrapper that injects
135
+ audit fields wraps every `db.insert/update/delete`. Because CRUD routes *and*
136
+ action handlers write through that db, both emit deltas; there's no separate
137
+ hook to wire. A write taps its result and, when it used `.returning()`, fans a
138
+ delta to each affected surface. Soft deletes (an `UPDATE` that sets `deletedAt`)
139
+ are emitted as `DELETE` so the row leaves the surface.
140
+
141
+ ## Security
142
+
143
+ - The **subscribe gate** reuses the view materializer: a ticket is only minted
144
+ when the caller can read the root row.
145
+ - Each included table's `firewall` + `masking` apply on both the initial
146
+ materialize and the live deltas (masking is applied per subscriber role at
147
+ fanout), so the two are consistent.
148
+ - **Stricter-child guard.** When a reverse-FK child's firewall is *stricter*
149
+ than the root's (e.g. an owner-scoped note under an org-scoped person), the
150
+ raw child row is **never broadcast**. Instead the server emits a *resync
151
+ signal* and the client refetches the surface through the materializer, which
152
+ applies the child's own firewall per subscriber. Row-bearing deltas are sent
153
+ only when the child is no stricter than the root.
154
+ - **Masking fails closed.** A mask type the Broadcaster can't replicate —
155
+ notably `type: 'custom'`, whose function is stripped during codegen — is
156
+ fully redacted (`[REDACTED]`) in deltas rather than passed through.
157
+ - **Projection parity.** An include's `fields` projection is applied to deltas
158
+ too, so a delta never carries a column the surface deliberately omits.
159
+
160
+ ## v1 limitations
161
+
162
+ - **Depth-1 includes only.** Nested includes are a compile-time error — flatten
163
+ the surface or split into multiple views.
164
+ - **Forward includes** (e.g. a company name on a person) are materialized into
165
+ the surface and refreshed on resync, but a change to the *referenced parent*
166
+ does not push a live delta — it surfaces on the next resync/reconnect.
167
+ - **Writes without `.returning()`** (and raw action writes that don't return
168
+ rows) don't push a live delta; resync-on-reconnect heals the surface.
@@ -155,6 +155,14 @@ bindings: {
155
155
  access: { resource: { feature: 'interactions', table: 'interactions' } },
156
156
  },
157
157
 
158
+ // Room keyed by a unique non-PK column (v0.36+). A Yjs page editor is
159
+ // addressed by `event_pages.yjsRoomId`, not the row id — `key` tells the
160
+ // gate which column the roomId matches.
161
+ {
162
+ name: 'PageRoom', className: 'PageRoom', from: 'lib/PageRoom',
163
+ access: { resource: { feature: 'event-pages', table: 'eventPages', key: 'yjsRoomId' } },
164
+ },
165
+
158
166
  // Genuinely public room (no auth, no row lookup) — opt out explicitly.
159
167
  { name: 'PublicLobby', className: 'PublicLobby', from: 'lib/PublicLobby',
160
168
  access: 'public' },
@@ -166,11 +174,23 @@ What the compiler emits:
166
174
 
167
175
  - **`access: { resource: 'chats' }`** — `app.use('/realtime/chat/*', …)` that 401s anonymous, parses the URL segment as a row id, queries `chats` with the resource's `buildFirewallConditions(ctx)` and `eq(chats.id, rowId)`, and 403s when the row is invisible to the caller (out-of-org, soft-deleted, etc.). The DO's `onLoad` / `onConnect` then runs only for rows the user can already read.
168
176
  - **`access: { resource: { feature, table } }`** — same gate, but the schema import + firewall alias are keyed off the pinned `table` instead of the feature name. Required when a feature owns more than one resourceful table; the access gate emit can't pick which table's firewall to query otherwise.
169
- - **Multi-resource form** — same gate but with a regex parser dispatching to per-kind firewall lookups. Unknown kinds 400 at the gate. Each `resources[kind].resource` accepts either form (string shorthand or `{ feature, table }`).
177
+ - **`access: { resource: { feature, table, key } }`** — same gate, but it matches the roomId against `table.<key>` instead of `table.id`. Use it when the room is addressed by a unique non-PK column — e.g. a Yjs editor keyed by `event_pages.yjsRoomId` (`ns.idFromName(row.yjsRoomId)`). `key` defaults to `'id'`, so existing pins are unchanged. The compiler validates the column exists at compile time. `key` also works inside each multi-resource branch.
178
+ - **Multi-resource form** — same gate but with a regex parser dispatching to per-kind firewall lookups. Unknown kinds 400 at the gate. Each `resources[kind].resource` accepts either form (string shorthand or `{ feature, table, key? }`).
170
179
  - **`access: 'public'`** — `app.use('/realtime/<kebab>/*', …)` that just passes through. Use for anonymous game lobbies / public collab pads where the room itself is the unit of access.
171
180
  - **No `access` declared** — falls through to the catchall `/realtime/*` gate that just checks `ctx.authenticated`. (v0.11.1 behavior.)
172
181
 
173
- Compile-time validation: every `resource` / `resources[].resource` value is checked against the project's feature names so typos surface as build errors, not as runtime 400s on the first WS upgrade. The string shorthand requires the feature to have exactly one resourceful table; multi-table features must use the long form `{ feature, table }` to pin a specific table.
182
+ Compile-time validation: every `resource` / `resources[].resource` value is checked against the project's feature names so typos surface as build errors, not as runtime 400s on the first WS upgrade. The string shorthand requires the feature to have exactly one resourceful table; multi-table features must use the long form `{ feature, table }` to pin a specific table. When `key` is set, the column is checked against the pinned table's schema.
183
+
184
+ ### Migrating a hand-rolled `onConnect` room to a declarative gate
185
+
186
+ If a room currently enforces access by hand inside `onConnect` / `onBeforeConnect` — typically because the room sits on a multi-table feature and an earlier compiler refused the ambiguous string shorthand — you can almost always replace it with a declarative `access` block. The decision is just "what is the roomId?":
187
+
188
+ 1. **roomId is a table's row id** → `access: { resource: { feature, table } }`.
189
+ 2. **roomId is a unique non-PK column** (a slug, a `yjsRoomId`) → add `key`: `access: { resource: { feature, table, key: 'yjsRoomId' } }`.
190
+ 3. **one DO class serves several room kinds** (e.g. `conv-<id>` / `ticket-<id>`) → the multi-resource form with a `pattern` that captures the kind and id.
191
+ 4. **access depends on membership, not just tenant** (e.g. "is this user an attendee of the event that owns this page") → you do **not** need hand-written code. Declare the pinned table's firewall with a `via:` relationship; the gate runs the table's *full* `buildFirewallConditions`, relationship subqueries included.
192
+
193
+ The declarative gate runs the exact firewall the CRUD `GET /:id` handler enforces, with the same 401/403 semantics, *before* the WebSocket upgrade — so by the time `onConnect` fires the caller is already authorized. Dropping the hand-rolled check also closes a common gap: a room with no `access` block is reachable by **any** authenticated user who can guess a room id, regardless of tenant.
174
194
 
175
195
  ### Hand-written mount with `onBeforeConnect`
176
196
 
@@ -68,13 +68,21 @@ export default {
68
68
  | GET | `/bucket` | List buckets |
69
69
  | GET | `/bucket/:name` | Get bucket info |
70
70
  | DELETE | `/bucket/:name` | Delete bucket (must be empty) |
71
- | POST | `/object/:bucket/*path` | Upload file |
71
+ | POST | `/object/:bucket/*path` | Upload file (bytes through the Worker) |
72
+ | POST | `/presign/:bucket/*path` | **Presigned upload URL (bytes direct to R2)** |
73
+ | POST | `/confirm/:bucket/*path` | Confirm a presigned upload (reconcile size + etag) |
72
74
  | GET | `/object/:bucket/*path` | Download file |
73
75
  | HEAD | `/object/:bucket/*path` | Get file metadata |
74
76
  | DELETE | `/object/:bucket/*path` | Delete file (soft delete) |
75
77
  | GET | `/object` | List objects |
76
78
  | POST | `/url` | Get file URL for serving |
77
79
 
80
+ > For anything larger than a small image — video, audio, big PDFs — prefer the
81
+ > **presigned** path. The bytes go straight to R2, so you skip the Worker's
82
+ > request-body cap and don't burn Worker CPU streaming the upload. See
83
+ > [Presigned uploads](#presigned-uploads-recommended) below.
84
+
85
+
78
86
  ### Files Worker (files.yourdomain.com)
79
87
 
80
88
  | Method | Path | Auth Required |
@@ -145,6 +153,94 @@ Response:
145
153
  }
146
154
  ```
147
155
 
156
+ ## Presigned uploads (recommended)
157
+
158
+ Streaming bytes through the Worker (`POST /object`) is fine for small files, but
159
+ it puts every byte on the Worker's request path — subject to the body-size cap,
160
+ and billed as Worker CPU/duration. For media (video, audio, large PDFs), use a
161
+ **presigned URL**: the Worker runs all the access checks and hands back a
162
+ short-lived URL the client uploads to **directly**. The bytes never touch your
163
+ Worker.
164
+
165
+ ```bash
166
+ # 1. Ask the API to sign an upload URL (auth + bucket + role checks run here)
167
+ curl -X POST https://api.example.com/storage/v1/presign/videos/clip.mp4 \
168
+ -H "Authorization: Bearer <token>" \
169
+ -H "Content-Type: application/json" \
170
+ -d '{ "contentType": "video/mp4", "size": 73400320 }'
171
+
172
+ # Response:
173
+ # {
174
+ # "id": "obj_abc",
175
+ # "key": "org_abc/videos/clip.mp4",
176
+ # "uploadUrl": "https://<account>.r2.cloudflarestorage.com/...&X-Amz-Signature=...",
177
+ # "method": "PUT",
178
+ # "headers": { "Content-Type": "video/mp4" },
179
+ # "expiresAt": "2026-06-02T12:10:00.000Z"
180
+ # }
181
+
182
+ # 2. Upload the bytes straight to R2 (replay the returned headers verbatim)
183
+ curl -X PUT "<uploadUrl>" -H "Content-Type: video/mp4" --data-binary @clip.mp4
184
+
185
+ # 3. Confirm — reconciles the recorded size + etag against what actually landed
186
+ curl -X POST https://api.example.com/storage/v1/confirm/videos/clip.mp4 \
187
+ -H "Authorization: Bearer <token>"
188
+ ```
189
+
190
+ > If `contentType` is supplied at step 1 it is **bound into the signature** — the
191
+ > client MUST send exactly that `Content-Type` header on the PUT, or R2 rejects
192
+ > it. Omit it to let the client send any type.
193
+
194
+
195
+ ### Required secrets
196
+
197
+ Presigning uses R2's S3-compatible API, which needs an **R2 API token** — the
198
+ Workers bucket binding alone cannot presign. Create a token in the Cloudflare
199
+ dashboard (R2 → Manage API Tokens) and set:
200
+
201
+ ```bash
202
+ wrangler secret put R2_ACCOUNT_ID # your Cloudflare account id
203
+ wrangler secret put R2_ACCESS_KEY_ID # R2 API token access key id
204
+ wrangler secret put R2_SECRET_ACCESS_KEY # R2 API token secret
205
+ # Optional: wrangler secret put R2_S3_ENDPOINT # override the derived endpoint
206
+ ```
207
+
208
+ ### Signing from your own action
209
+
210
+ The same signer is exposed as `ctx.storage` inside any
211
+ [`defineAction`](/compiler/definitions/actions) — so you can author an upload endpoint that
212
+ runs your own access rules (org, team, relationship/scoped roles) and stores the
213
+ key in **your own table**, instead of the generic `buckets`/`objects` metadata:
214
+
215
+ ```typescript
216
+ export default defineAction({
217
+ path: '/event/:eventId/media/sign-upload',
218
+ method: 'POST',
219
+ input: z.object({ filename: z.string(), contentType: z.string() }),
220
+ access: { roles: ['admin', 'member', 'scope:event:attendee'] },
221
+ async execute({ input, ctx, db, storage }) {
222
+ // Tenant-scoped key — secure by construction
223
+ const key = `org/${ctx.activeOrgId}/event/${input.eventId}/${crypto.randomUUID()}-${input.filename}`;
224
+ const upload = await storage.signPutUrl(key, {
225
+ contentType: input.contentType,
226
+ expiresIn: 600,
227
+ });
228
+ await db.insert(images).values({ key, eventId: input.eventId /* … */ });
229
+ return { uploadUrl: upload.url, key, headers: upload.headers };
230
+ },
231
+ });
232
+ ```
233
+
234
+ `storage` exposes:
235
+
236
+ | Method | Returns | Use |
237
+ |--------|---------|-----|
238
+ | `signPutUrl(key, { contentType?, expiresIn? })` | `{ url, method, headers, key, expiresAt }` | Client uploads directly to R2 |
239
+ | `signGetUrl(key, { expiresIn?, downloadFilename? })` | `string` | Client downloads directly from R2 |
240
+
241
+ This is the supported replacement for streaming a raw binary body through an
242
+ action — the JSON body parser and its ~1 MiB cap stay on for every other route.
243
+
148
244
  ## Serving Files
149
245
 
150
246
  ### Public Files
@@ -177,11 +273,16 @@ When file storage is configured, the compiler generates:
177
273
 
178
274
  | File | Purpose |
179
275
  |------|---------|
180
- | `src/routes/storage.ts` | Storage API routes |
181
- | `src/files.ts` | Files database schema (buckets, objects) |
276
+ | `src/storage/routes.ts` | Storage API routes (upload, presign, confirm, download) |
277
+ | `src/storage/presign.ts` | R2 presigned-URL signer (`createPresigner`, backs `ctx.storage`) |
278
+ | `src/files/schema.ts` | Files database schema (buckets, objects) |
182
279
  | `cloudflare-workers/files/index.ts` | Files worker for serving |
183
280
  | `cloudflare-workers/files/wrangler.toml` | Files worker config |
184
281
 
282
+ The compiler also adds [`aws4fetch`](https://github.com/mhart/aws4fetch) to your
283
+ `package.json` (used by the presigner) and the R2 presign secrets to your
284
+ generated `CloudflareBindings` type.
285
+
185
286
  ## Deployment
186
287
 
187
288
  After compiling:
@@ -213,6 +314,14 @@ After compiling:
213
314
  wrangler deploy
214
315
  ```
215
316
 
317
+ 6. **Set the R2 presign secrets** (only if you use presigned uploads — see
318
+ [Presigned uploads](#presigned-uploads-recommended)):
319
+ ```bash
320
+ wrangler secret put R2_ACCOUNT_ID
321
+ wrangler secret put R2_ACCESS_KEY_ID
322
+ wrangler secret put R2_SECRET_ACCESS_KEY
323
+ ```
324
+
216
325
  ## Configuration Reference
217
326
 
218
327
  | Option | Type | Default | Description |
@@ -4,28 +4,48 @@ Cloudflare R2 provides S3-compatible object storage for file uploads in the Quic
4
4
 
5
5
  ## Upload Flow
6
6
 
7
- The generated API provides a two-step upload process:
7
+ The generated API provides a two-step **presigned** upload — the file bytes go
8
+ directly to R2 and never stream through your Worker:
8
9
 
9
- 1. **Request a presigned URL** — Client calls the upload endpoint to get a time-limited URL
10
- 2. **Upload directly to R2** — Client uploads the file directly to R2 (bypasses your Worker)
11
- 3. **Store the reference** — The API records the file metadata in D1
10
+ 1. **Request a presigned URL** — Client calls `/storage/v1/presign/...`; the
11
+ Worker runs auth + bucket + role checks and returns a time-limited URL
12
+ 2. **Upload directly to R2** — Client `PUT`s the bytes to R2 (bypasses your Worker)
13
+ 3. **Confirm** — `/storage/v1/confirm/...` reconciles the recorded size + etag
12
14
 
13
15
  ```bash
14
- # 1. Request presigned upload URL
15
- curl -X POST https://api.example.com/api/v1/files/upload \
16
+ # 1. Request a presigned upload URL
17
+ curl -X POST https://api.example.com/storage/v1/presign/documents/report.pdf \
16
18
  -H "Authorization: Bearer <token>" \
17
19
  -H "Content-Type: application/json" \
18
- -d '{"filename": "report.pdf", "contentType": "application/pdf"}'
20
+ -d '{ "contentType": "application/pdf", "size": 248000 }'
19
21
 
20
22
  # Response:
21
- # { "uploadUrl": "https://bucket.r2.cloudflarestorage.com/...", "fileId": "file_abc123" }
22
-
23
- # 2. Upload directly to R2 using the presigned URL
23
+ # {
24
+ # "id": "obj_abc123",
25
+ # "key": "org_abc/documents/report.pdf",
26
+ # "uploadUrl": "https://<account>.r2.cloudflarestorage.com/...&X-Amz-Signature=...",
27
+ # "method": "PUT",
28
+ # "headers": { "Content-Type": "application/pdf" },
29
+ # "expiresAt": "2026-06-02T12:10:00.000Z"
30
+ # }
31
+
32
+ # 2. Upload directly to R2 using the presigned URL (replay the returned headers)
24
33
  curl -X PUT "<uploadUrl>" \
25
34
  -H "Content-Type: application/pdf" \
26
35
  --data-binary @report.pdf
36
+
37
+ # 3. Confirm the upload
38
+ curl -X POST https://api.example.com/storage/v1/confirm/documents/report.pdf \
39
+ -H "Authorization: Bearer <token>"
27
40
  ```
28
41
 
42
+ Presigning needs an R2 API token — set the `R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID`,
43
+ and `R2_SECRET_ACCESS_KEY` secrets. See [R2 Setup → Presigned uploads](/stack/storage/r2#presigned-uploads-recommended).
44
+
45
+ For uploads that should land in **your own table** (with your own access rules),
46
+ sign the URL from inside a `defineAction` via `ctx.storage` — see
47
+ [Signing from your own action](/stack/storage/r2#signing-from-your-own-action).
48
+
29
49
  ## Download Flow
30
50
 
31
51
  Files are served through your Worker with security checks applied:
@@ -82,9 +82,9 @@ export const TEMPLATE_REGISTRY = {
82
82
  // api-minimal-bun also hidden alongside the other bun templates.
83
83
  "blog-cloudflare": {
84
84
  name: "Blog / CMS Starter",
85
- description: "Single-tenant blog with public pages, admin-only editing, deployed to Cloudflare Workers",
85
+ description: "Blog/CMS starter with a pinned organization id, public pages, and admin-only editing on Cloudflare Workers",
86
86
  category: "api",
87
- tags: ["blog", "cms", "single-tenant", "cloudflare", "d1"],
87
+ tags: ["blog", "cms", "pinned-organization", "cloudflare", "d1"],
88
88
  author: "quickback",
89
89
  version: "1.0.0",
90
90
  includes: ["betterauth", "d1", "hono", "drizzle"],