@quickback-dev/cli 0.38.0 → 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 (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 +201 -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 +112 -3
  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 +201 -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 +112 -3
  109. package/src/skill/docs/stack/storage/using-r2.md +30 -10
@@ -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
@@ -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: