@quickback-dev/cli 0.38.0 → 0.40.0

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 (109) 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.js +24 -24
  19. package/dist/docs/content.js.map +1 -1
  20. package/dist/examples/recruitment.tar.gz +0 -0
  21. package/dist/index.js +1 -1
  22. package/dist/lib/action-harvest.d.ts +48 -0
  23. package/dist/lib/action-harvest.d.ts.map +1 -0
  24. package/dist/lib/action-harvest.js +292 -0
  25. package/dist/lib/action-harvest.js.map +1 -0
  26. package/dist/lib/action-harvest.test.d.ts +2 -0
  27. package/dist/lib/action-harvest.test.d.ts.map +1 -0
  28. package/dist/lib/action-harvest.test.js +112 -0
  29. package/dist/lib/action-harvest.test.js.map +1 -0
  30. package/dist/lib/api-client.d.ts +10 -0
  31. package/dist/lib/api-client.d.ts.map +1 -1
  32. package/dist/lib/api-client.js +17 -1
  33. package/dist/lib/api-client.js.map +1 -1
  34. package/dist/lib/api-client.test.js +19 -0
  35. package/dist/lib/api-client.test.js.map +1 -1
  36. package/dist/lib/artifact-routing.d.ts +1 -0
  37. package/dist/lib/artifact-routing.d.ts.map +1 -1
  38. package/dist/lib/artifact-routing.js +15 -3
  39. package/dist/lib/artifact-routing.js.map +1 -1
  40. package/dist/lib/artifact-routing.test.js +12 -1
  41. package/dist/lib/artifact-routing.test.js.map +1 -1
  42. package/dist/lib/file-loader.d.ts +1 -0
  43. package/dist/lib/file-loader.d.ts.map +1 -1
  44. package/dist/lib/file-loader.js +34 -1
  45. package/dist/lib/file-loader.js.map +1 -1
  46. package/dist/lib/file-loader.test.js +28 -4
  47. package/dist/lib/file-loader.test.js.map +1 -1
  48. package/dist/lib/prepare-state-output.d.ts +8 -0
  49. package/dist/lib/prepare-state-output.d.ts.map +1 -0
  50. package/dist/lib/prepare-state-output.js +17 -0
  51. package/dist/lib/prepare-state-output.js.map +1 -0
  52. package/dist/lib/prepare-state-output.test.d.ts +2 -0
  53. package/dist/lib/prepare-state-output.test.d.ts.map +1 -0
  54. package/dist/lib/prepare-state-output.test.js +31 -0
  55. package/dist/lib/prepare-state-output.test.js.map +1 -0
  56. package/dist/skill/SKILL.md +1 -1
  57. package/dist/skill/docs/changelog.md +262 -0
  58. package/dist/skill/docs/compiler/config/agents.md +1 -1
  59. package/dist/skill/docs/compiler/config/auth.md +1 -1
  60. package/dist/skill/docs/compiler/config/index.md +8 -9
  61. package/dist/skill/docs/compiler/config/providers.md +3 -0
  62. package/dist/skill/docs/compiler/config/single-tenant.md +65 -73
  63. package/dist/skill/docs/compiler/definitions/access.md +40 -33
  64. package/dist/skill/docs/compiler/definitions/actions.md +1 -1
  65. package/dist/skill/docs/compiler/definitions/firewall.md +1 -1
  66. package/dist/skill/docs/compiler/definitions/schema.md +8 -2
  67. package/dist/skill/docs/compiler/getting-started/template-blog.md +7 -7
  68. package/dist/skill/docs/compiler/getting-started/template-empty.md +1 -4
  69. package/dist/skill/docs/compiler/getting-started/templates.md +6 -6
  70. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/actions-api.md +2 -2
  71. package/dist/skill/docs/stack/account-ui/features/admin.md +1 -1
  72. package/dist/skill/docs/stack/account-ui/features/index.md +2 -2
  73. package/dist/skill/docs/stack/cms/connecting.md +17 -16
  74. package/dist/skill/docs/stack/cms/index.md +7 -7
  75. package/dist/skill/docs/stack/cms/schema-format.md +0 -2
  76. package/dist/skill/docs/stack/cms/schema-registry.md +0 -6
  77. package/dist/skill/docs/stack/cms/security.md +6 -6
  78. package/dist/skill/docs/stack/realtime/durable-objects.md +5 -7
  79. package/dist/skill/docs/stack/storage/r2.md +142 -4
  80. package/dist/skill/docs/stack/storage/using-r2.md +30 -10
  81. package/dist/templates/registry.js +2 -2
  82. package/dist/templates/registry.js.map +1 -1
  83. package/package.json +1 -1
  84. package/src/examples/recruitment.tar.gz +0 -0
  85. package/src/skill/SKILL.md +1 -1
  86. package/src/skill/docs/changelog.md +262 -0
  87. package/src/skill/docs/compiler/config/agents.md +1 -1
  88. package/src/skill/docs/compiler/config/auth.md +1 -1
  89. package/src/skill/docs/compiler/config/index.md +8 -9
  90. package/src/skill/docs/compiler/config/providers.md +3 -0
  91. package/src/skill/docs/compiler/config/single-tenant.md +65 -73
  92. package/src/skill/docs/compiler/definitions/access.md +40 -33
  93. package/src/skill/docs/compiler/definitions/actions.md +1 -1
  94. package/src/skill/docs/compiler/definitions/firewall.md +1 -1
  95. package/src/skill/docs/compiler/definitions/schema.md +8 -2
  96. package/src/skill/docs/compiler/getting-started/template-blog.md +7 -7
  97. package/src/skill/docs/compiler/getting-started/template-empty.md +1 -4
  98. package/src/skill/docs/compiler/getting-started/templates.md +6 -6
  99. package/src/skill/docs/compiler/targets/hono-api/using-the-api/actions-api.md +2 -2
  100. package/src/skill/docs/stack/account-ui/features/admin.md +1 -1
  101. package/src/skill/docs/stack/account-ui/features/index.md +2 -2
  102. package/src/skill/docs/stack/cms/connecting.md +17 -16
  103. package/src/skill/docs/stack/cms/index.md +7 -7
  104. package/src/skill/docs/stack/cms/schema-format.md +0 -2
  105. package/src/skill/docs/stack/cms/schema-registry.md +0 -6
  106. package/src/skill/docs/stack/cms/security.md +6 -6
  107. package/src/skill/docs/stack/realtime/durable-objects.md +5 -7
  108. package/src/skill/docs/stack/storage/r2.md +142 -4
  109. package/src/skill/docs/stack/storage/using-r2.md +30 -10
@@ -67,7 +67,7 @@ When both CMS and Account UI are enabled, the admin panel's profile page shows a
67
67
  cms: { domain: "cms.example.com", access: "admin" },
68
68
  ```
69
69
 
70
- With `access: "admin"`, non-admin users can't access the CMS at any layer: the link is hidden in Account UI, the SPA shell returns `403` before serving `index.html`, `/api/v1/schema` returns `403`, and the `custom_view` CRUD is locked to admins. See [CMS Connecting](/stack/cms/connecting#restrict-cms-access-to-admin-users-only) for the full enforcement model.
70
+ With `access: "admin"`, callers outside the platform control-plane roles can't access the CMS at any layer: the link is hidden in Account UI, the SPA shell returns `403` before serving `index.html`, `/api/v1/schema` returns `403`, and the `custom_view` CRUD is locked to `userRole: ["appmanager"]` (plus `sysadmin` when enabled). See [CMS Connecting](/stack/cms/connecting#restrict-cms-access-to-admin-users-only) for the full enforcement model.
71
71
 
72
72
  ## Related
73
73
 
@@ -196,7 +196,7 @@ ENABLE_ORGANIZATIONS=false
196
196
  ENABLE_ADMIN=false
197
197
  ```
198
198
 
199
- Simple email/password authentication for single-tenant apps.
199
+ Simple email/password authentication for apps that do not need advanced auth methods.
200
200
 
201
201
  ### Maximum Security
202
202
 
@@ -256,7 +256,7 @@ import { setAppConfig } from '@/config/app';
256
256
 
257
257
  setAppConfig({
258
258
  features: {
259
- organizations: false, // Disable organizations
259
+ organizations: false, // Hide organization-management UI
260
260
  passkey: true, // Enable passkey
261
261
  },
262
262
  });
@@ -150,12 +150,12 @@ cms: { domain: "cms.example.com" }
150
150
 
151
151
  This adds a custom domain route to `wrangler.toml`. Both `api.example.com` and `cms.example.com` point to the same Worker. The compiler auto-configures hostname-based routing and cross-subdomain cookies.
152
152
 
153
- CMS access defaults to `access: "admin"` — only `user.role === "admin"` (the Better Auth platform-admin tier) can reach `/cms/*`. Non-admin authenticated users are redirected to `/account/profile`. The gate is enforced at multiple layers:
153
+ CMS access defaults to `access: "admin"` — only `user.role === "appmanager"` (the Better Auth platform control-plane tier) 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 multiple layers:
154
154
 
155
- - **Account UI** hides the "Go to CMS" button for non-admins.
156
- - **CMS SPA shell** — the Worker returns `403` (or redirects unauthenticated requests to login) before serving `index.html` to a non-admin. A non-admin who types the CMS URL directly cannot load the app.
157
- - **`/api/v1/schema`** returns `403 Admin access required` to non-admin callers, so schema metadata can't be scraped by hitting the API directly.
158
- - **`custom_view` routes** are gated on `userRole: ["admin"]` rather than org membership, so saved views can't be listed or modified without admin rights.
155
+ - **Account UI** hides the "Go to CMS" button for callers outside those roles.
156
+ - **CMS SPA shell** — the Worker returns `403` (or redirects unauthenticated requests to login) before serving `index.html` to a non-operator. A non-operator who types the CMS URL directly cannot load the app.
157
+ - **`/api/v1/schema`** returns `403 Platform operator access required` to callers outside those roles, so schema metadata can't be scraped by hitting the API directly.
158
+ - **`custom_view` routes** are gated on `userRole: ["appmanager"]` rather than org membership, so saved views can't be listed or modified without platform-control-plane rights.
159
159
  - **In-SPA gate** — if any earlier layer is bypassed, the SPA still redirects the user to `/account/profile`.
160
160
 
161
161
  Your resource API endpoints (the ones generated for your features) are unaffected — they continue to use the per-resource `read`, `create`, `update`, `delete`, and `upsert` access rules you defined.
@@ -168,30 +168,31 @@ cms: { access: "user" }
168
168
 
169
169
  See [Multi-Domain Architecture](/compiler/config/domains) for details on multi-domain routing.
170
170
 
171
- ## Multi-Tenant vs Single-Tenant
171
+ ## Default Org Mode vs Pinned Organization Mode
172
172
 
173
- The CMS supports two authentication modes depending on your project's organization configuration.
173
+ The CMS supports two organization flows depending on your project's config.
174
174
 
175
- ### Multi-Tenant (Default)
175
+ ### Default Org Mode
176
176
 
177
- In multi-tenant mode, the CMS gates access behind organization membership:
177
+ By default, the CMS gates access behind organization membership:
178
178
 
179
179
  1. User logs in via Better Auth session
180
180
  2. CMS fetches the user's organization memberships
181
181
  3. If the user belongs to multiple organizations, an **org selector** is displayed
182
182
  4. Once an org is selected, the user's role within that org determines their CMS permissions
183
183
 
184
- This is the default behavior for all Quickback projects.
184
+ This is the default behavior for Quickback projects with no pinned org.
185
185
 
186
- ### Single-Tenant Mode
186
+ ### Pinned Organization Mode
187
187
 
188
- When your project disables organizations (`features.organizations: false` in config), the compiler sets `singleTenant: true` in the schema registry. In this mode:
188
+ When your project sets `features.pinnedOrganizationId`, the CMS keeps org-backed auth but fixes the active org at runtime. In this mode:
189
189
 
190
- - No org gate or org selector is shown
191
- - The user's role is read directly from `user.role` on the session
192
- - All data is unscoped (no `organizationId` filtering)
190
+ - No org selector is shown
191
+ - The org gate is bypassed because the active org is known up front
192
+ - The user's `roles` still come from membership in the pinned org
193
+ - Org-scoped data remains scoped by `organizationId`
193
194
 
194
- Single-tenant mode is useful for internal tools, personal projects, or apps that don't need multi-org isolation.
195
+ Pinned organization mode is useful for internal tools, blogs, and one-customer deployments that still want org-backed roles and schema conventions without runtime org switching.
195
196
 
196
197
  ## Next Steps
197
198
 
@@ -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.
@@ -107,7 +107,7 @@ attendee — their realtime socket now opens.
107
107
 
108
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.
109
109
 
110
- 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.
111
111
 
112
112
  | Mutation site | Auto-broadcast? | Why |
113
113
  |---|---|---|
@@ -121,14 +121,10 @@ The rule of thumb: if your code calls `db.insert(...)` / `scoped.insert(...)` di
121
121
 
122
122
  ## Generated Helper
123
123
 
124
- 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:
125
125
 
126
126
  ```typescript
127
- import { createRealtime } from '../lib/realtime';
128
-
129
- export const execute: ActionExecutor = async ({ db, ctx, input }) => {
130
- const realtime = createRealtime(ctx.env);
131
-
127
+ export const execute: ActionExecutor = async ({ db, ctx, input, realtime }) => {
132
128
  // After creating a record
133
129
  await realtime.insert('applications', newApplication, ctx.activeOrgId!);
134
130
 
@@ -142,6 +138,8 @@ export const execute: ActionExecutor = async ({ db, ctx, input }) => {
142
138
  };
143
139
  ```
144
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
+
145
143
  For explicit targeting, pass an object instead of the historical org string:
146
144
 
147
145
  ```typescript
@@ -1,6 +1,35 @@
1
1
  # File Storage (R2)
2
2
 
3
- Quickback provides built-in file storage using Cloudflare R2, with role-based access control and a dedicated files worker for serving.
3
+ Quickback provides built-in file storage using Cloudflare R2.
4
+
5
+ ## Two modes
6
+
7
+ `defineFileStorage("cloudflare-r2")` has two modes:
8
+
9
+ - **Presign-only (default)** — emits just the `ctx.storage` signer (presigned
10
+ PUT/GET URLs straight to R2). **No new D1, no `/storage/v1/*` endpoints, no
11
+ files worker.** You compute keys and store file references in your own table.
12
+ This is the recommended path for most apps and the lightest way to add
13
+ uploads — see [Presigned uploads](#presigned-uploads-recommended).
14
+ - **Managed (`managed: true`)** — adds the turnkey subsystem on top: a FILES_DB
15
+ metadata database (buckets + objects), the `/storage/v1/*` upload/download/
16
+ manage endpoints, and a public files worker for serving. Opt in only when you
17
+ want buckets/objects handled for you instead of bringing your own media table.
18
+
19
+ ```ts
20
+ // Presign-only (default) — ctx.storage against a bucket, nothing else
21
+ defineFileStorage("cloudflare-r2", { bucketName: "my-app-media" })
22
+
23
+ // Managed subsystem — adds FILES_DB + /storage/v1/* + files worker
24
+ defineFileStorage("cloudflare-r2", { managed: true, bucketName: "my-app-files" })
25
+ ```
26
+
27
+ New projects can omit `bucketName` — it defaults to `<project>-media`, so the
28
+ only setup is `wrangler r2 bucket create <name>` once plus the R2 API-token
29
+ secrets. Existing projects set `bucketName` to a bucket they already have.
30
+
31
+ The sections below document the **managed** subsystem; for the default
32
+ presign-only path jump to [Presigned uploads](#presigned-uploads-recommended).
4
33
 
5
34
  ## Architecture
6
35
 
@@ -68,13 +97,21 @@ export default {
68
97
  | GET | `/bucket` | List buckets |
69
98
  | GET | `/bucket/:name` | Get bucket info |
70
99
  | DELETE | `/bucket/:name` | Delete bucket (must be empty) |
71
- | POST | `/object/:bucket/*path` | Upload file |
100
+ | POST | `/object/:bucket/*path` | Upload file (bytes through the Worker) |
101
+ | POST | `/presign/:bucket/*path` | **Presigned upload URL (bytes direct to R2)** |
102
+ | POST | `/confirm/:bucket/*path` | Confirm a presigned upload (reconcile size + etag) |
72
103
  | GET | `/object/:bucket/*path` | Download file |
73
104
  | HEAD | `/object/:bucket/*path` | Get file metadata |
74
105
  | DELETE | `/object/:bucket/*path` | Delete file (soft delete) |
75
106
  | GET | `/object` | List objects |
76
107
  | POST | `/url` | Get file URL for serving |
77
108
 
109
+ > For anything larger than a small image — video, audio, big PDFs — prefer the
110
+ > **presigned** path. The bytes go straight to R2, so you skip the Worker's
111
+ > request-body cap and don't burn Worker CPU streaming the upload. See
112
+ > [Presigned uploads](#presigned-uploads-recommended) below.
113
+
114
+
78
115
  ### Files Worker (files.yourdomain.com)
79
116
 
80
117
  | Method | Path | Auth Required |
@@ -145,6 +182,94 @@ Response:
145
182
  }
146
183
  ```
147
184
 
185
+ ## Presigned uploads (recommended)
186
+
187
+ Streaming bytes through the Worker (`POST /object`) is fine for small files, but
188
+ it puts every byte on the Worker's request path — subject to the body-size cap,
189
+ and billed as Worker CPU/duration. For media (video, audio, large PDFs), use a
190
+ **presigned URL**: the Worker runs all the access checks and hands back a
191
+ short-lived URL the client uploads to **directly**. The bytes never touch your
192
+ Worker.
193
+
194
+ ```bash
195
+ # 1. Ask the API to sign an upload URL (auth + bucket + role checks run here)
196
+ curl -X POST https://api.example.com/storage/v1/presign/videos/clip.mp4 \
197
+ -H "Authorization: Bearer <token>" \
198
+ -H "Content-Type: application/json" \
199
+ -d '{ "contentType": "video/mp4", "size": 73400320 }'
200
+
201
+ # Response:
202
+ # {
203
+ # "id": "obj_abc",
204
+ # "key": "org_abc/videos/clip.mp4",
205
+ # "uploadUrl": "https://<account>.r2.cloudflarestorage.com/...&X-Amz-Signature=...",
206
+ # "method": "PUT",
207
+ # "headers": { "Content-Type": "video/mp4" },
208
+ # "expiresAt": "2026-06-02T12:10:00.000Z"
209
+ # }
210
+
211
+ # 2. Upload the bytes straight to R2 (replay the returned headers verbatim)
212
+ curl -X PUT "<uploadUrl>" -H "Content-Type: video/mp4" --data-binary @clip.mp4
213
+
214
+ # 3. Confirm — reconciles the recorded size + etag against what actually landed
215
+ curl -X POST https://api.example.com/storage/v1/confirm/videos/clip.mp4 \
216
+ -H "Authorization: Bearer <token>"
217
+ ```
218
+
219
+ > If `contentType` is supplied at step 1 it is **bound into the signature** — the
220
+ > client MUST send exactly that `Content-Type` header on the PUT, or R2 rejects
221
+ > it. Omit it to let the client send any type.
222
+
223
+
224
+ ### Required secrets
225
+
226
+ Presigning uses R2's S3-compatible API, which needs an **R2 API token** — the
227
+ Workers bucket binding alone cannot presign. Create a token in the Cloudflare
228
+ dashboard (R2 → Manage API Tokens) and set:
229
+
230
+ ```bash
231
+ wrangler secret put R2_ACCOUNT_ID # your Cloudflare account id
232
+ wrangler secret put R2_ACCESS_KEY_ID # R2 API token access key id
233
+ wrangler secret put R2_SECRET_ACCESS_KEY # R2 API token secret
234
+ # Optional: wrangler secret put R2_S3_ENDPOINT # override the derived endpoint
235
+ ```
236
+
237
+ ### Signing from your own action
238
+
239
+ The same signer is exposed as `ctx.storage` inside any
240
+ [`defineAction`](/compiler/definitions/actions) — so you can author an upload endpoint that
241
+ runs your own access rules (org, team, relationship/scoped roles) and stores the
242
+ key in **your own table**, instead of the generic `buckets`/`objects` metadata:
243
+
244
+ ```typescript
245
+ export default defineAction({
246
+ path: '/event/:eventId/media/sign-upload',
247
+ method: 'POST',
248
+ input: z.object({ filename: z.string(), contentType: z.string() }),
249
+ access: { roles: ['admin', 'member', 'scope:event:attendee'] },
250
+ async execute({ input, ctx, db, storage }) {
251
+ // Tenant-scoped key — secure by construction
252
+ const key = `org/${ctx.activeOrgId}/event/${input.eventId}/${crypto.randomUUID()}-${input.filename}`;
253
+ const upload = await storage.signPutUrl(key, {
254
+ contentType: input.contentType,
255
+ expiresIn: 600,
256
+ });
257
+ await db.insert(images).values({ key, eventId: input.eventId /* … */ });
258
+ return { uploadUrl: upload.url, key, headers: upload.headers };
259
+ },
260
+ });
261
+ ```
262
+
263
+ `storage` exposes:
264
+
265
+ | Method | Returns | Use |
266
+ |--------|---------|-----|
267
+ | `signPutUrl(key, { contentType?, expiresIn? })` | `{ url, method, headers, key, expiresAt }` | Client uploads directly to R2 |
268
+ | `signGetUrl(key, { expiresIn?, downloadFilename? })` | `string` | Client downloads directly from R2 |
269
+
270
+ This is the supported replacement for streaming a raw binary body through an
271
+ action — the JSON body parser and its ~1 MiB cap stay on for every other route.
272
+
148
273
  ## Serving Files
149
274
 
150
275
  ### Public Files
@@ -177,11 +302,16 @@ When file storage is configured, the compiler generates:
177
302
 
178
303
  | File | Purpose |
179
304
  |------|---------|
180
- | `src/routes/storage.ts` | Storage API routes |
181
- | `src/files.ts` | Files database schema (buckets, objects) |
305
+ | `src/storage/routes.ts` | Storage API routes (upload, presign, confirm, download) |
306
+ | `src/storage/presign.ts` | R2 presigned-URL signer (`createPresigner`, backs `ctx.storage`) |
307
+ | `src/files/schema.ts` | Files database schema (buckets, objects) |
182
308
  | `cloudflare-workers/files/index.ts` | Files worker for serving |
183
309
  | `cloudflare-workers/files/wrangler.toml` | Files worker config |
184
310
 
311
+ The compiler also adds [`aws4fetch`](https://github.com/mhart/aws4fetch) to your
312
+ `package.json` (used by the presigner) and the R2 presign secrets to your
313
+ generated `CloudflareBindings` type.
314
+
185
315
  ## Deployment
186
316
 
187
317
  After compiling:
@@ -213,6 +343,14 @@ After compiling:
213
343
  wrangler deploy
214
344
  ```
215
345
 
346
+ 6. **Set the R2 presign secrets** (only if you use presigned uploads — see
347
+ [Presigned uploads](#presigned-uploads-recommended)):
348
+ ```bash
349
+ wrangler secret put R2_ACCOUNT_ID
350
+ wrangler secret put R2_ACCESS_KEY_ID
351
+ wrangler secret put R2_SECRET_ACCESS_KEY
352
+ ```
353
+
216
354
  ## Configuration Reference
217
355
 
218
356
  | 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: