@quickback-dev/cli 0.66.17 → 0.66.18

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 (91) hide show
  1. package/dist/commands/build.d.ts.map +1 -1
  2. package/dist/commands/build.js +26 -20
  3. package/dist/commands/build.js.map +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/lib/action-harvest.d.ts +3 -2
  6. package/dist/lib/action-harvest.d.ts.map +1 -1
  7. package/dist/lib/action-harvest.js +3 -2
  8. package/dist/lib/action-harvest.js.map +1 -1
  9. package/dist/lib/file-writer.d.ts +9 -0
  10. package/dist/lib/file-writer.d.ts.map +1 -1
  11. package/dist/lib/file-writer.js +30 -5
  12. package/dist/lib/file-writer.js.map +1 -1
  13. package/dist/skill/docs/api/actions.md +10 -9
  14. package/dist/skill/docs/api/errors.md +14 -2
  15. package/dist/skill/docs/api/openapi.md +1 -1
  16. package/dist/skill/docs/api/query-params.md +3 -3
  17. package/dist/skill/docs/configure/auth.md +8 -4
  18. package/dist/skill/docs/configure/index.md +1 -1
  19. package/dist/skill/docs/define/access.md +16 -6
  20. package/dist/skill/docs/define/actions/defining.md +8 -1
  21. package/dist/skill/docs/define/actions/scoped-db.md +69 -8
  22. package/dist/skill/docs/define/changesets.md +8 -3
  23. package/dist/skill/docs/define/encryption.md +6 -3
  24. package/dist/skill/docs/define/fga.md +9 -4
  25. package/dist/skill/docs/define/firewall.md +15 -7
  26. package/dist/skill/docs/define/masking.md +1 -1
  27. package/dist/skill/docs/define/relationships.md +6 -3
  28. package/dist/skill/docs/define/schema.md +27 -2
  29. package/dist/skill/docs/define/scopes.md +15 -1
  30. package/dist/skill/docs/define/transitions.md +5 -0
  31. package/dist/skill/docs/define/views.md +9 -0
  32. package/dist/skill/docs/platform/api-contract/index.md +4 -2
  33. package/dist/skill/docs/platform/auth/api-keys.md +10 -1
  34. package/dist/skill/docs/platform/auth/jwt-optimization.md +10 -4
  35. package/dist/skill/docs/platform/auth/plugins/aws-ses.md +11 -4
  36. package/dist/skill/docs/platform/auth/plugins/index.md +4 -2
  37. package/dist/skill/docs/platform/auth/plugins/subscriptions.md +3 -3
  38. package/dist/skill/docs/platform/push/index.md +31 -23
  39. package/dist/skill/docs/platform/storage/r2.md +36 -4
  40. package/dist/skill/docs/platform/vector/embeddings.md +11 -76
  41. package/dist/skill/docs/platform/vector/index.md +1 -1
  42. package/dist/skill/docs/platform/vector/using-embeddings.md +10 -73
  43. package/dist/skill/docs/platform/webhooks/outbound.md +12 -8
  44. package/dist/skill/docs/tooling/cli.md +2 -2
  45. package/dist/skill/docs/tooling/cloud-compiler/authentication.md +1 -1
  46. package/dist/skill/docs/tooling/cloud-compiler/endpoints.md +2 -1
  47. package/dist/skill/docs/tooling/cloud-compiler/index.md +18 -3
  48. package/dist/skill/docs/tooling/cloud-compiler/local-compiler.md +7 -4
  49. package/dist/skill/docs/tooling/cloud-compiler/troubleshooting.md +1 -1
  50. package/dist/skill/docs/tooling/output.md +6 -2
  51. package/dist/skill/docs/ui/account/hooks.md +2 -2
  52. package/package.json +1 -1
  53. package/src/skill/docs/api/actions.md +10 -9
  54. package/src/skill/docs/api/errors.md +14 -2
  55. package/src/skill/docs/api/openapi.md +1 -1
  56. package/src/skill/docs/api/query-params.md +3 -3
  57. package/src/skill/docs/configure/auth.md +8 -4
  58. package/src/skill/docs/configure/index.md +1 -1
  59. package/src/skill/docs/define/access.md +16 -6
  60. package/src/skill/docs/define/actions/defining.md +8 -1
  61. package/src/skill/docs/define/actions/scoped-db.md +69 -8
  62. package/src/skill/docs/define/changesets.md +8 -3
  63. package/src/skill/docs/define/encryption.md +6 -3
  64. package/src/skill/docs/define/fga.md +9 -4
  65. package/src/skill/docs/define/firewall.md +15 -7
  66. package/src/skill/docs/define/masking.md +1 -1
  67. package/src/skill/docs/define/relationships.md +6 -3
  68. package/src/skill/docs/define/schema.md +27 -2
  69. package/src/skill/docs/define/scopes.md +15 -1
  70. package/src/skill/docs/define/transitions.md +5 -0
  71. package/src/skill/docs/define/views.md +9 -0
  72. package/src/skill/docs/platform/api-contract/index.md +4 -2
  73. package/src/skill/docs/platform/auth/api-keys.md +10 -1
  74. package/src/skill/docs/platform/auth/jwt-optimization.md +10 -4
  75. package/src/skill/docs/platform/auth/plugins/aws-ses.md +11 -4
  76. package/src/skill/docs/platform/auth/plugins/index.md +4 -2
  77. package/src/skill/docs/platform/auth/plugins/subscriptions.md +3 -3
  78. package/src/skill/docs/platform/push/index.md +31 -23
  79. package/src/skill/docs/platform/storage/r2.md +36 -4
  80. package/src/skill/docs/platform/vector/embeddings.md +11 -76
  81. package/src/skill/docs/platform/vector/index.md +1 -1
  82. package/src/skill/docs/platform/vector/using-embeddings.md +10 -73
  83. package/src/skill/docs/platform/webhooks/outbound.md +12 -8
  84. package/src/skill/docs/tooling/cli.md +2 -2
  85. package/src/skill/docs/tooling/cloud-compiler/authentication.md +1 -1
  86. package/src/skill/docs/tooling/cloud-compiler/endpoints.md +2 -1
  87. package/src/skill/docs/tooling/cloud-compiler/index.md +18 -3
  88. package/src/skill/docs/tooling/cloud-compiler/local-compiler.md +7 -4
  89. package/src/skill/docs/tooling/cloud-compiler/troubleshooting.md +1 -1
  90. package/src/skill/docs/tooling/output.md +6 -2
  91. package/src/skill/docs/ui/account/hooks.md +2 -2
@@ -278,7 +278,7 @@ masking: {
278
278
  }
279
279
  ```
280
280
 
281
- `query` is a single role gate that covers `?filter`, `?sort`, and `?search` uniformly. When omitted, it inherits from `show.roles` — "if you can see it, you can query it" — which is the right shape for almost all PII.
281
+ `query` is a single role gate that covers `?filter`, `?sort`, `?search`, and [view aggregations](/define/views#constraints-compile-time) uniformly, evaluated per caller with the same role rule as access (org roles, `scope:<kind>:<role>`, pseudo-roles). When omitted, it inherits from `show.roles` — "if you can see it, you can query it" — which is the right shape for almost all PII. Sorting by a masked column you may query but not see returns `null` pagination cursors (a cursor encodes the boundary row's sort values); `?offset=` paging still works. An aggregation over a masked column the caller may not query returns `"(suppressed)"`; `groupBy` / `min` / `max` on a masked column additionally require every role that can reach the view to be a query role, at build time.
282
282
 
283
283
  A view can opt back in for a higher-privileged role pair by listing the column in its own `query.{filterable,searchable,sortable}` allowlist. The compiler validates at build time that the view's access roles intersect the masking `query.roles` (or `show.roles` when `query` is omitted), so the opt-in can never reach a caller who'd see the value masked.
284
284
 
@@ -69,6 +69,9 @@ export default defineConfig({
69
69
  >
70
70
  > ```typescript
71
71
  > // features/conversations/conversation_members.ts
72
+ > import { sqliteTable, text } from 'drizzle-orm/sqlite-core';
73
+ > import { defineTable } from '@quickback/compiler';
74
+ >
72
75
  > export const conversation_members = sqliteTable('conversation_members', {
73
76
  > id: text('id').primaryKey(),
74
77
  > userId: text('user_id').notNull(),
@@ -105,7 +108,7 @@ Resource definitions reference declared roles by name in `roles: [...]` arrays e
105
108
  |---|---|---|
106
109
  | `firewall:` `via:` predicate | ✓ Supported | Subquery composes as outermost AND |
107
110
  | `crud.*.access` `roles: ['guest']` | ✓ Supported | Inline async lookup per request |
108
- | `read.access` / `read.views.*.access` `roles: ['guest']` | ✓ Supported | Same inline path |
111
+ | `read.access` / `read.views.*.access` `roles: ['guest']` | ✓ Supported | `GET /:id`: same inline path. Collections (`GET /`, views, `?total`, `?search`, aggregations, MCP list): rows filtered by `<resource.column> IN (<relationship subquery>)`, OR'd with sibling arms. The table must declare `resource.column`, and multi-hop (`hops`) relationships are refused here — scope those with a firewall `via:` |
109
112
  | **Standalone** `actions.<name>.access` `roles: ['guest']` | ✓ Supported | Inline gate; the surface exposes `resource.column` as a path param or input field |
110
113
  | **Record-based** `actions.<name>.access` `roles: ['guest']` | ✓ Supported | Inline lookup uses the already-loaded, firewalled record |
111
114
  | Namespace `via` lanes | ✓ Supported | Hoisted middleware resolves once and can hydrate `ctx.<exposeAs>` |
@@ -145,12 +148,12 @@ authz: {
145
148
  The resolver:
146
149
 
147
150
  1. **Cheap in-memory role check** first — `ctx.roles?.includes('admin')` and friends. If the caller has a qualifying role, this short-circuits and no DB queries fire for the access gate.
148
- 2. **Firewall-gated relationship match** if the role check failed — `SELECT { organizationId, teamId } FROM guests WHERE userId=ctx.userId AND eventId=input.eventId AND status='confirmed'` with the `guests` table's full firewall AND-applied. If neither role nor relationship qualifies → 403.
151
+ 2. **Firewall-gated relationship match** if the role check failed — `SELECT { organizationId, teamId } FROM guests WHERE userId=ctx.userId AND eventId=input.eventId AND status='confirmed'` with the `guests` table's soft-delete predicates AND-applied — **not** its tenant scope (a cross-tenant attendee has no `activeOrgId` to match; see [Firewall — relationships](/define/firewall#relationship-based-scoping-via) for the two invariants that make the row trustworthy instead: FK integrity on `resource.column`, and write-gating on the relationship table). If neither role nor relationship qualifies → 403.
149
152
  3. **Tenant stamping from the matched row** — for any tenant column the `from` table carries (`organizationId`, `teamId`), the resolver stamps `ctx.activeOrgId ??= matchedRow.organizationId` (and similar for team). This is **in-memory mutation of the request-scoped ctx only** — no JWT remint, no session-record write, no persistent grant.
150
153
  4. **Firewall-gated load of the loaded resource** — `SELECT * FROM events WHERE id = :eventId AND buildEventsFirewallConditions(ctx, db)`. The events firewall is applied as normal; it succeeds for attendees because tenant was just stamped from the relationship row.
151
154
  5. Assigns the loaded row to `ctx.event` for the action body.
152
155
 
153
- **No firewall bypass anywhere.** Both queries run with their respective tables' full firewalls. The relationship row's existence is the proof that the caller is authorized; its tenant columns are the source of the stamped claim.
156
+ **What each query enforces.** The relationship match applies the `from` table's soft-delete only; the loaded resource runs under its full firewall, bound to the tenant stamped from the matched row — so a relationship row can only open an instance in its own tenant. The relationship row's existence is the proof that the caller is authorized; its tenant columns are the source of the stamped claim. That makes the row's integrity load-bearing: declare `resource.column` as a foreign key and guard it against update (`guards: { immutable: ['eventId'] }`), and gate who may write the relationship table as tightly as the access it confers.
154
157
 
155
158
  ### Conditional tenant preconditions
156
159
 
@@ -339,6 +339,29 @@ quickback/
339
339
  - Tables without a default export are internal (no routes, used for joins/relations)
340
340
  - Route paths are derived from filenames: `applications.ts` → `/api/v1/applications`
341
341
 
342
+ ### Table files are declarative
343
+
344
+ Everything above `export default defineTable(...)` becomes part of the generated
345
+ `schema.ts`, which migration and auth-schema tooling **load** during a compile.
346
+ So the compiler only accepts declarative code there, and fails the compile
347
+ naming the file and line otherwise:
348
+
349
+ - **Imports** from `drizzle-orm` / `drizzle-orm/*`, `@quickback/compiler`, or
350
+ another table file (`./other-table`, `../<feature>/<table>`). `import type`
351
+ may come from anywhere — it is erased.
352
+ - **Top-level statements**: imports, `type` / `interface` declarations, `const`
353
+ / `let` bindings, and `export { … }` lists.
354
+ - **Expressions** built from literals, your imports and bindings, and `Date`,
355
+ `Math`, `JSON`, `Number`, `String`, `Boolean`, `crypto`. Callbacks such as
356
+ `.references(() => …)`, `$defaultFn(() => …)` and the index callback
357
+ `(t) => [...]` follow the same rule; their bodies may hold `const`s and a
358
+ `return`.
359
+
360
+ Not allowed: `require`, `process`, `globalThis`, dynamic `import()`, function
361
+ declarations, loops, assignments, and `constructor` / `prototype` access.
362
+ Logic belongs in an [action](/define/actions); the `defineTable(...)` config
363
+ itself is not affected.
364
+
342
365
  ### defineTable vs defineResource
343
366
 
344
367
  - **`defineTable`** — The standard function for defining tables with generated API routes
@@ -617,8 +640,10 @@ The platform provides the pieces for an explicit policy:
617
640
  `onDelete: 'cascade'` for same-database ownership, and orchestrate
618
641
  cross-database records, R2 objects, and external systems from an explicit
619
642
  offboarding action or queued job.
620
- - **Encrypted data** — envelope-encrypted fields support per-organization
621
- crypto-shredding by deleting the wrapped DEK. Sealed deployments should
643
+ - **Encrypted data** — deleting an organization's wrapped DEK makes its
644
+ envelope-encrypted fields unreadable, provided no backup or export still
645
+ holds that row ([crypto-shredding](/define/encryption#per-organization-keys-blast-radius-and-crypto-shredding)
646
+ is a manual, service-role delete). Sealed deployments should
622
647
  include their vault grants, recovery records, and key versions in the same
623
648
  reviewed offboarding workflow.
624
649
 
@@ -349,6 +349,7 @@ so it can only ever carry the role the caller actually proved this request.
349
349
  - A **bulk-grant lane** (`{ roles: [...] }` or `{ team: true }`) mints **no** scope role — it opens the gate via the caller's org role without proving a relationship. The gate passes; the caller carries their org role, not a minted scope role.
350
350
  - **The org claim is only ever signed beside a membership role.** Every mint site — `/scope/v1/enter`, the namespace resolver, `/api/v1/token` — writes `orgId` into the token only when a membership `role` accompanies it, and the auth middleware ignores an `orgId` claim that arrives without a `role`. A relationship-promoted tenant (the in-request `ctx.activeOrgId` stamped from the proven row so the firewall resolves) is never persisted as a bare tenant grant.
351
351
  - **`/scope/v1/enter` drops the org claims for a foreign-tenant instance.** When the relationship's `from` table carries an organization column, the enter route reads it off the proven row (the same row the probe already fetched — no extra query) and compares it with `ctx.activeOrgId`. A mismatch — an org-B member entering an org-A event — mints the token **without** `orgId` / `role`: a relationship-only principal, exactly the state the namespace resolver gives the same caller. The caller keeps their org seat for org-B requests by using their session or a plain `/api/v1/token`; the scope token is for the scope. A `from` table with no organization column (a global reference relationship) leaves the claim untouched.
352
+ - **Every mint tenant-binds the instance.** A relationship row is matched without tenant scoping (a cross-tenant attendee has no `activeOrgId`), so the row alone can't prove which tenant's instance it names. When the relationship's `from` table carries an organization column, every site that mints from a relationship row — `/scope/v1/enter`, [`ctx.mintScope`](#sessionless-scope-mint--ctxmintscope), and this namespace resolver (the in-memory stamp **and** the `mintScope` token) — also loads the **instance** row, through its own firewall with tenant scopes stripped so soft-delete still applies, and grants the role only when the instance's organization equals the proving row's. A row created in org B naming org A's event proves nothing about org A and grants nothing; a deleted instance grants nothing. (The namespace gate itself still passes on the proven row; the caller just carries no scope for the foreign instance.) The instance table is the target of the relationship's `resource.column` foreign key, or — when that column isn't a declared FK — the one table whose firewall pins its primary key to `ctx.scope.<kind>` (`{ field: 'id', equals: 'ctx.scope.event' }`). If neither resolves, the compiler warns: declare the FK so the instance can be bound. A `from` table with no organization column has no tenant to compare, so it gets no binding.
352
353
 
353
354
  ### The bulk-grant lane is tenant-bound
354
355
 
@@ -617,7 +618,18 @@ within one mint cycle (**≤180s**). Re-prove by calling `ctx.mintScope` again
617
618
  (your own refresh endpoint does exactly that). The by-PK probe does **not** apply
618
619
  the relationship's tenant firewall (a sessionless principal has no
619
620
  `activeOrgId` yet — the proven row *is* what establishes scope), but matching by
620
- primary key + the `where:` filter keeps it bounded and fail-closed.
621
+ primary key + the `where:` filter + the table's soft-delete guard keeps it
622
+ bounded and fail-closed: a soft-deleted row confers nothing.
623
+
624
+ The row names the instance, so the mint tenant-binds it exactly like
625
+ [`/scope/v1/enter`](#per-matched-lane-minting-forging-safety): when the
626
+ relationship's `from` table carries an organization column, the instance must be
627
+ live (not soft-deleted) and belong to the **row's** organization, or the mint
628
+ throws `ScopeMintError`. A guest row created in org B that names org A's event
629
+ (`eventId` is often a plain text column, and rows written by authored actions or
630
+ imports skip the CRUD foreign-key check) mints nothing for org A's event. The
631
+ documented flow is unaffected — the comparison is row vs instance, never vs the
632
+ caller, who has no tenant at all.
621
633
 
622
634
  ### 3. The scope-only token
623
635
 
@@ -679,6 +691,8 @@ The scope claim is trusted between proofs — it is never re-checked against the
679
691
  - **The TTL** (default 180s, `auth.jwt.expiresIn`, clamped ≤180s on scope-bearing tokens) bounds an *idle* client: a token that stops being used dies within one TTL.
680
692
  - **The carry-forward cap** (15 minutes) bounds an *active* client: the rolling refresh re-signs the claim on every authed call, but only while its proof timestamp (stamped exclusively by the proven mint sites) is younger than the cap. The cap is applied **per scope kind** — a kind whose own proof is past it is dropped from the re-signed claim, so re-proving one relationship cannot roll another forward. Past the cap the refresh refuses, the token expires, and the next `enter` (or namespace-route mint) re-probes the relationship — which won't re-mint a revoked role.
681
693
 
694
+ - **Org claims ride the same cap.** A scope token minted from a bearer JWT re-signs that bearer's `orgId` / `role` / `userRole` / `tiers` — claims the scope probe never re-checks. They carry their own proof time, `ict`, stamped only where they are read from the database (the session path, `GET /auth/v1/token`) and copied verbatim by `enter`, namespace mints and the refresh. Once `ict` is past the cap — or absent, on a token from before `ict` existed — the re-signed token drops them and keeps only the scope claim; the org grant comes back when the client next authenticates with its session. Every scope token also carries `sid`, so signing out (`qbrev:sid`) revokes it.
695
+
682
696
  So removing a guest/staff row takes effect within **cap + one TTL** for a client that keeps polling, and within one TTL once it goes idle. Two ways to tighten that:
683
697
 
684
698
  - **`auth.jwt.revocationCheck: 'kv'`** (Cloudflare runtime) — sub-TTL revocation: updating or deleting a conferring relationship row stamps a revocation timestamp in KV, and the bearer fast-path rejects a carried scope claim whose proof is at or before it — no same-second gap. Each kind is compared against **its own** proof time (`sctMs` on the entry; tokens without one fall back to the token-level `sct`/`sctMs`), so a mint of one kind can't carry a revoked kind past its marker. Neither the refresh nor a re-mint ever substitutes its own clock for a proof it didn't take. The check fails closed — a scope claim whose revocation state can't be read is not trusted either. See [auth config](/configure/auth).
@@ -79,6 +79,11 @@ name), ride the same OpenAPI/security-contract pipeline, and delete cleanly:
79
79
  **an explicit `actions/<name>.ts` file always wins** (the compiler warns about
80
80
  the shadowed transitions entry).
81
81
 
82
+ Generated transitions take no request input. Their OpenAPI request body and
83
+ MCP tool schema are the compiler's own strict empty object, and they are
84
+ outside the CLI's [local action-schema harvest](/define/actions/defining#local-action-schema-harvest)
85
+ — which only covers action files that exist in your tree.
86
+
82
87
  ## Action-level extensions
83
88
 
84
89
  All new keys are optional — a plain `{ field, fromTo, to|via }` transition
@@ -347,6 +347,15 @@ the metric from the user's filters would surprise.
347
347
  masking rule, otherwise the aggregation is rejected. (A `sum(salary)`
348
348
  leaks structure across the masked set even when the row payload is
349
349
  redacted.)
350
+ - `groupBy`, `min` and `max` return the column's **raw values** (bucket keys,
351
+ extremes), so on a masked column they need more than an overlap: the view's
352
+ access must be a plain `roles` list and **every** role in it must be in
353
+ `masking.<col>.query.roles` (`show.roles` when `query` is omitted).
354
+ Otherwise the build fails — narrow the view, or use `count` /
355
+ `count_distinct`.
356
+ - At request time every aggregation over a masked column is also gated **per
357
+ caller**: a caller whose roles may not query the column gets
358
+ `"(suppressed)"` for that aggregation, whatever the view's roles are.
350
359
  - Aggregation names cannot collide with the reserved response fields
351
360
  `data`, `pagination`, `view`.
352
361
  - No raw SQL `expr:` form. Column references only — declare a generated
@@ -64,8 +64,10 @@ List endpoints accept an opaque keyset cursor alongside classic
64
64
  | `?ending_before=<cursor>` | rows strictly before the boundary (backward) |
65
65
  | `?total=true` | opt into a counted total |
66
66
 
67
- `pagination.nextCursor` / `prevCursor` carry the boundaries. Cursors are
68
- opaque — never parse them.
67
+ `pagination.nextCursor` / `prevCursor` carry the boundaries. Treat cursors as
68
+ opaque — never parse them — but they are encoded, not encrypted: they carry the
69
+ boundary row's sort values, so both are `null` when the sort includes a masked
70
+ column the caller may sort by but not see ([query params](/api/query-params)).
69
71
 
70
72
  ## Idempotency-Key
71
73
 
@@ -12,4 +12,13 @@ Create API keys from [Account UI](/ui/account/features/api-keys) (`/api-keys`, l
12
12
  QUICKBACK_API_KEY=your_api_key quickback build
13
13
  ```
14
14
 
15
- API keys are validated by the same `/internal/validate` endpoint as session tokens. See [Authentication](/tooling/cloud-compiler/authentication) for details.
15
+ The compiler validates the key by calling the Quickback API's Better Auth `GET /auth/v1/get-session` with it. See [Authentication](/tooling/cloud-compiler/authentication) for details.
16
+
17
+ ## What a key can reach
18
+
19
+ In a generated project an `x-api-key` authenticates two things:
20
+
21
+ - **Your API** (`/api/*`) — the auth middleware verifies the key and resolves its owner's role in the organization named by the key's `metadata.organizationId`.
22
+ - **`GET /auth/v1/get-session`** — the one Better Auth endpoint where a key stands in for its owner's session (the key-validation "whoami").
23
+
24
+ Every other Better Auth endpoint ignores the header and answers as for an unauthenticated caller: a key cannot mint an identity JWT (`GET /auth/v1/token`), list sessions, create or manage keys, change the user, register a passkey, or act on organizations. Those need a real session.
@@ -22,9 +22,11 @@ The JWT encodes everything needed for auth middleware:
22
22
  | Claim | Description |
23
23
  |-------|-------------|
24
24
  | `sub` | User ID |
25
+ | `sid` | Better Auth session the token was minted from — carried by scope mints and the rolling refresh too, so [`qbrev:sid`](/configure/auth#revocationcheck-none--kv--token-revocation-strategy) revokes every token descended from a signed-out session |
25
26
  | `orgId` | Active organization ID |
26
27
  | `role` | Organization membership role (`owner`, `admin`, `member`) |
27
28
  | `userRole` | Global user role (when admin panel is enabled) |
29
+ | `ict` | Identity proof time (unix seconds) — when `orgId` / `role` / `userRole` / `tiers` were last read from the database. Stamped only by the session-path mint and `GET /auth/v1/token`; carried verbatim by `/scope/v1/enter`, namespace mints and the rolling refresh, which drop those claims once `ict` is older than the 15-minute carry-forward cap (or absent). See [Scopes](/define/scopes#revocation--ttl) |
28
30
  | `email` | User email |
29
31
  | `name` | User display name |
30
32
  | `iat` | Issued-at timestamp (unix **seconds**, the standard claim) |
@@ -68,8 +70,9 @@ Validation steps (in generated `src/middleware/auth.ts`):
68
70
  2. Call `verifyJwt(token, env)` from `src/lib/jwt.ts`
69
71
  3. Verify the EdDSA signature with jose against the keyring's public JWKS — cached per isolate, refetched at most once when a token names an unknown `kid` (key rotation). Only `EdDSA` is accepted, so alg-confusion is rejected by construction, and `iss` / `aud` are pinned to the compile-time constants
70
72
  4. Check `exp` against the current time
71
- 5. On success: hydrate `AppContext` from claims (`sub`, `orgId`, `role`, `userRole`, `email`, `name`) — no DB query
72
- 6. On failure (bad signature, expired, malformed): **silently fall back** to Better Auth's session cookie auth; if that succeeds, mint a fresh JWT and return it in the `set-auth-token` response header
73
+ 5. On success: hydrate `AppContext` from claims (`sub`, `sid`, `orgId`, `role`, `userRole`, `email`, `name`) — no DB query
74
+ 6. On failure for a token **this project minted** (rotated key, expired, tampered, revoked — recognised by the pinned `iss`, or the legacy HS256 shape): **`401`** with `AUTH_INVALID_TOKEN` (`AUTH_EXPIRED` when `exp` has passed) and `WWW-Authenticate: Bearer error="invalid_token"`. No fall-through: a presented-and-bad credential is never treated as no credential, so clients can key "drop the cached token and re-mint" on 401 alone. A foreign JWT (an OAuth access token — same keyring, OAuth issuer) falls through to its own verifier — which is why [`auth.jwt.issuer`](/configure/auth#issuer-string--iss-claim) may never equal the OAuth issuer (compile error). A token that *verifies* but is not one this lane admits (a session user's scope token on a project without `auth.jwt`) is a good credential, not a bad one: it falls through to session auth
75
+ 7. With no JWT at all: fall back to Better Auth's session cookie auth; if that succeeds, mint a fresh JWT and return it in the `set-auth-token` response header
73
76
 
74
77
  The Files worker (R2 uploads) runs the same verifier (`src/lib/jwt-verify.ts`) over the public keys it reads from the `jwks` table — no shared secret, no network round-trip to the auth API for file operations.
75
78
 
@@ -168,11 +171,14 @@ When a JWT expires or is invalid:
168
171
 
169
172
  ## Token Endpoint
170
173
 
171
- `GET /auth/v1/token` — Better Auth's jwt plugin — mints a fresh JWT from the current session. Present only when `auth.jwt` is declared; the claims come from the compiler-emitted `resolveIdentityClaims` (`sid`, `orgId` beside the raw membership `role`, `userRole`, `tiers`, `email`, `name`, pinned `iss` / `aud`), and the TTL is your [`auth.jwt.expiresIn`](/configure/auth#expiresin-number--ttl-in-seconds) — the same value the session-path refresh uses. There is no Quickback-generated `/api/v1/token` any more.
174
+ `GET /auth/v1/token` — Better Auth's jwt plugin — mints a fresh JWT from the current session. Present only when `auth.jwt` is declared; the claims come from the compiler-emitted `resolveIdentityClaims` (`sid`, `ict`, `orgId` beside the raw membership `role`, `userRole`, `tiers`, `email`, `name`, pinned `iss` / `aud`), and the TTL is your [`auth.jwt.expiresIn`](/configure/auth#expiresin-number--ttl-in-seconds) — the same value the session-path refresh uses. There is no Quickback-generated `/api/v1/token` any more.
172
175
 
173
176
  **Session authentication is required — and enforced.** The plugin gates the
174
177
  endpoint on a Better Auth session (cookie or session-token bearer); a request
175
178
  authenticated by a bearer JWT, an API key, or an OAuth access token gets `401`.
179
+ An `x-api-key` stands in for its owner's session on exactly one Better Auth
180
+ endpoint — `GET /auth/v1/get-session` — and nowhere else under `/auth/v1/*`
181
+ (see [API Keys](/platform/auth/api-keys)).
176
182
  This is deliberate: only the session path re-validates against Better Auth's
177
183
  session store on every request, so bans, member removals, role demotions, and
178
184
  sign-outs take effect immediately. If a JWT could mint its own replacement, a
@@ -281,7 +287,7 @@ Whenever the project signs any JWT — an `auth.jwt` lane, [`authz.scopes`](/def
281
287
 
282
288
  - **The keyring** — the EdDSA key pair in the `jwks` table, private key encrypted at rest with `BETTER_AUTH_SECRET`.
283
289
  - **`GET /auth/v1/jwks`** — the public keys. Any external service verifies Quickback tokens from here; nothing needs the secret.
284
- - **`GET /auth/v1/token`** — mints an identity JWT for the current session (cookie or session-token bearer). Its claims come from the compiler-emitted `resolveIdentityClaims` in `src/lib/auth.ts`: `sid`, `orgId` beside the **raw** membership `role`, `userRole`, `tiers`, `email`, `name`, and the pinned `iss` / `aud` — the same shape the middleware mints on the session path. Present only when `auth.jwt` is declared; otherwise the path is disabled and the keyring exists for scope and agent tokens alone.
290
+ - **`GET /auth/v1/token`** — mints an identity JWT for the current session (cookie or session-token bearer). Its claims come from the compiler-emitted `resolveIdentityClaims` in `src/lib/auth.ts`: `sid`, `ict`, `orgId` beside the **raw** membership `role`, `userRole`, `tiers`, `email`, `name`, and the pinned `iss` / `aud` — the same shape the middleware mints on the session path. Present only when `auth.jwt` is declared; otherwise the path is disabled and the keyring exists for scope and agent tokens alone.
285
291
 
286
292
  ### What Quickback still mints
287
293
 
@@ -74,21 +74,28 @@ interface Input {
74
74
  supportEmail?: string;
75
75
  }
76
76
 
77
+ // `name` is whatever the user typed at sign-up — escape every value you put in HTML.
78
+ const esc = (v: string) =>
79
+ v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
80
+ .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
81
+
77
82
  export default function welcomeTemplate({ otp, name, appName, appUrl }: Input) {
78
83
  const greeting = name ? `Hi ${name},` : 'Hi,';
79
84
  return {
80
85
  subject: `Welcome to ${appName} — set your password`,
81
86
  html: `
82
- <h1>Welcome to ${appName}</h1>
83
- <p>${greeting} your account is ready. Use this code to set your password and sign in:</p>
84
- <p style="font-size:32px;letter-spacing:8px"><b>${otp}</b></p>
85
- <p>Visit <a href="${appUrl}/set-password">${appUrl}/set-password</a> to finish setup.</p>
87
+ <h1>Welcome to ${esc(appName)}</h1>
88
+ <p>${esc(greeting)} your account is ready. Use this code to set your password and sign in:</p>
89
+ <p style="font-size:32px;letter-spacing:8px"><b>${esc(otp)}</b></p>
90
+ <p>Visit <a href="${esc(appUrl)}/set-password">${esc(appUrl)}/set-password</a> to finish setup.</p>
86
91
  `,
87
92
  text: `${greeting}\n\nYour ${appName} code: ${otp}\n\nFinish setup at ${appUrl}/set-password`,
88
93
  };
89
94
  }
90
95
  ```
91
96
 
97
+ Template inputs arrive **unescaped** — `name` in particular is user-controlled. The built-in templates HTML-escape every interpolation; an override must do the same, or a sign-up name like `<a href=…>` renders as live markup in the recipient's inbox.
98
+
92
99
  Recognized keys:
93
100
 
94
101
  | Key | When it fires |
@@ -272,7 +272,7 @@ Better Auth's JWT plugin owns the keyring every Quickback token is signed with.
272
272
 
273
273
  **Endpoints:**
274
274
  - `GET /auth/v1/jwks` — the public keys. External services verify Quickback tokens from here without holding any secret.
275
- - `GET /auth/v1/token` — mint an identity JWT for the current session (cookie or session-token bearer). Carries the same claims the middleware mints: `sid`, `orgId` beside the raw `role`, `userRole`, `tiers`, `email`, `name`. TTL is `auth.jwt.expiresIn` (default 180 s). Present only when `auth.jwt` is declared.
275
+ - `GET /auth/v1/token` — mint an identity JWT for the current session (cookie or session-token bearer). Carries the same claims the middleware mints: `sid`, `ict`, `orgId` beside the raw `role`, `userRole`, `tiers`, `email`, `name`. TTL is `auth.jwt.expiresIn` (default 180 s). Present only when `auth.jwt` is declared.
276
276
 
277
277
  > The keyring is one system with Quickback's fast-path, not a second token format: identity tokens, the session-path refresh, and scope tokens are all EdDSA-signed with the same key and checked by the same verifier. See [JWT Optimization → Relation to Better Auth's JWT Plugin](/platform/auth/jwt-optimization#relation-to-better-auths-jwt-plugin).
278
278
 
@@ -301,6 +301,8 @@ The header takes precedence when both are present. The query-param form lands in
301
301
  - `GET /auth/v1/api-key/list` — list keys for the current user
302
302
  - `POST /auth/v1/api-key/delete` — revoke a key
303
303
 
304
+ These need a real session (cookie or session-token bearer). Under `/auth/v1/*` a key authenticates only `GET /auth/v1/get-session`; every other Better Auth endpoint ignores `x-api-key`, so a leaked key cannot mint JWTs, manage keys, or act on organizations. See [API Keys](/platform/auth/api-keys).
305
+
304
306
  Keys can carry organization context via `metadata.organizationId` — when set, the auth middleware looks up the user's role in that org and populates `ctx.roles` accordingly, so a single key inherits the same firewall + access scope as the user who created it.
305
307
 
306
308
  ### OAuth Provider (MCP-ready)
@@ -502,7 +504,7 @@ export const longSessionPlugin = {
502
504
 
503
505
  #### Out of scope
504
506
 
505
- - **No schema generation.** If your plugin needs database tables, declare them as a Quickback feature — the compiler does not run schema introspection on custom plugins.
507
+ - **No schema generation.** If your plugin needs database tables or extra fields, declare them as a Quickback feature. The compiler never loads project-local plugin files while it generates the auth schema, so a plugin's `schema` is not read. A referenced plugin whose source declares a `schema` gets a compile warning. (Bare-specifier plugins are loaded, from the compiler's pinned dependencies — never from anything your project uploads — so a package the compiler bundles, such as `better-auth/plugins`, still contributes its schema.)
506
508
  - **No conditional inclusion.** Every entry in `customPlugins` is always emitted. Gate environment-specific plugins inside the plugin file itself.
507
509
  - **No name collision check against the named registry.** Duplicate registration is a Better Auth runtime concern, not a compile-time one — don't reach for `customPlugins` to override a named plugin's options; use the object form on `plugins` instead.
508
510
 
@@ -287,9 +287,9 @@ Everything under `src/` is generated — change tiers in `quickback.config.ts` a
287
287
  import { q, defineTable } from "@quickback/compiler";
288
288
 
289
289
  export const projects = q.table("projects", {
290
- id: q.uuid("id").primaryKey(),
291
- owner_id: q.uuid("owner_id").notNull(),
292
- name: q.text("name").notNull(),
290
+ id: q.id(),
291
+ ownerId: q.scope("owner"),
292
+ name: q.text().required(),
293
293
  ...q.audit(),
294
294
  ...q.softDelete(),
295
295
  });
@@ -6,7 +6,7 @@ APNs is planned as a second provider. The helper signature is shared, so most co
6
6
 
7
7
  ## What you get
8
8
 
9
- - **`enqueuePushFanout(queue, target, payload, opts?)`** — the primary send surface. Takes a declarative audience (`{ userIds }`, `{ targetTags }`, `{ targetRoles }`, `{ all: true }`) or an explicit subscription list, and routes between inline delivery and queue fan-out.
9
+ - **`enqueuePushFanout(queue, target, payload, opts?)`** — the primary send surface. Takes a declarative audience (`{ organizationId, targetRoles? }`, `{ userIds }`, `{ targetTags }`, `{ all: true }`) or an explicit subscription list, and routes between inline delivery and queue fan-out.
10
10
  - **`sendPush(subscription, payload, vapid)`** — single-recipient delivery. Returns `{ status: 'sent' | 'gone' | 'failed', statusCode, ... }`.
11
11
  - **`sendPushBulk(subscriptions, payload, vapid, opts?)`** — in-request fan-out with a default concurrency cap of 8 (Workers subrequest-budget friendly).
12
12
  - **`vapidFromEnv(env)`** — assembles the `VapidConfig` from `VAPID_PUBLIC_KEY` / `VAPID_PRIVATE_KEY` / `VAPID_SUBJECT`.
@@ -56,7 +56,7 @@ With `push.defaultSchema: true`, the compiler injects a hardened, owner-scoped `
56
56
  - **INTERNAL-only reads** — the crypto fields (`endpoint`, `p256dh`, `auth`) never leave the worker via any HTTP path. A `views.mine` projection exposes only `id`, `userAgent`, `lastSeenAt`, `createdAt` for "Your devices" UIs.
57
57
  - **Owner firewall** — `owner_id` is auto-stamped on create; user A can never read or delete user B's subscription.
58
58
  - **Create-time validation** — the endpoint must be `https:` (the worker POSTs VAPID-signed requests at that URL, so an arbitrary endpoint is an SSRF primitive), `p256dh` must decode to a 65-byte uncompressed P-256 point, and `auth` to a 16-byte secret. The `https:` check is not the whole SSRF story: at send time the push sender additionally rejects any endpoint whose host resolves to a private, link-local, loopback, `localhost`, or `.internal` address. Together — **https + a non-public-host block** — this narrows the SSRF surface; treat it as defense-in-depth, not a guarantee that SSRF is impossible.
59
- - **Proven identity tags** — a `tags` column is stamped **server-side** from `ctx` (`user:<id>`, `role:<name>`, and — only when the request carries a scoped token — `scope:<kind>:<subject>`, the same dialect realtime tickets use). Client-supplied tags are ignored: they drive fan-out targeting. A normal session-cookie subscribe therefore stamps `user:` and `role:` but no `scope:` tag; see [Targeting](#targeting).
59
+ - **Proven identity tags** — a `tags` column is stamped **server-side** from `ctx`: `user:<id>`, and — only when the request carries a scoped token — `scope:<kind>:<subject>` plus one `scope:<kind>:<instance>#<role>` per scope role the verified claim grants (the same dialect realtime tickets use). Client-supplied tags are ignored: they drive fan-out targeting. **Org roles are never stamped** — a device is user-owned, and org audiences are resolved from live membership at send time; see [Targeting](#targeting).
60
60
  - **Rate limit + cap** — creates are limited to 10/minute per caller, and only the newest 10 live subscriptions per user are kept (older rows are soft-deleted, so a user's new device always works).
61
61
 
62
62
  This create-time hardening (endpoint/key validation, server-side tag stamping, the per-user cap) runs in JS before/after-insert hooks that fire **only on audit-wrapped writes** — the REST create path and actions. The normal browser subscribe is REST, so it's fully covered; but raw-SQL writes, queue/cron inserts, or direct INTERNAL-context inserts into `push_subscriptions` bypass all of it. Don't hand-insert subscription rows expecting the guards to apply.
@@ -181,22 +181,27 @@ export default defineAction({
181
181
  description: "Publish an event and notify admins.",
182
182
  input: z.object({}),
183
183
  access: { roles: ["owner", "admin"] },
184
- async execute({ record, env, effects }) {
184
+ async execute({ record, ctx, env, effects }) {
185
185
  // ...your committed write happens here...
186
186
 
187
- // After-commit: notify every subscribed admin.
188
- effects.enqueue("push:eventPublished", () =>
189
- enqueuePushFanout(
190
- env.PUSH_FANOUT_QUEUE!,
191
- { targetRoles: ["admin"] },
192
- {
193
- title: record.name,
194
- body: "Event published — tap to review",
195
- url: `https://app.example.com/events/${record.id}`,
196
- tag: `event-${record.id}`,
197
- },
198
- ),
199
- );
187
+ // After-commit: notify this organization's admins (owners too, via
188
+ // auth.roleHierarchy). The scope is on the send — resolved from
189
+ // membership when the queue consumer runs, never from the device.
190
+ const organizationId = ctx.activeOrgId;
191
+ if (organizationId) {
192
+ effects.enqueue("push:eventPublished", () =>
193
+ enqueuePushFanout(
194
+ env.PUSH_FANOUT_QUEUE!,
195
+ { organizationId, targetRoles: ["admin"] },
196
+ {
197
+ title: record.name,
198
+ body: "Event published — tap to review",
199
+ url: `https://app.example.com/events/${record.id}`,
200
+ tag: `event-${record.id}`,
201
+ },
202
+ ),
203
+ );
204
+ }
200
205
 
201
206
  return { published: true };
202
207
  },
@@ -205,24 +210,27 @@ export default defineAction({
205
210
 
206
211
  The declarative form enqueues **one small message**; the generated queue consumer resolves the audience against `push_subscriptions` inside the server-internal trust zone and fans out delivery chunks. Subscription crypto never enters your action code.
207
212
 
208
- Target by `{ targetRoles }` or `{ userIds }` — these match the `role:<name>` and `user:<id>` tags that **every** subscription carries, because they're stamped from `ctx` on a normal session-cookie subscribe. `{ targetTags: ['scope:events:e9'] }` only matches subscriptions created inside a scoped context (see the note under [Targeting](#targeting)); against ordinary session-created rows it selects nobody.
213
+ Target an organization with `{ organizationId, targetRoles? }` or specific people with `{ userIds }` — both work for every subscription, because they resolve against the row's owner rather than a stamped claim.
209
214
 
210
215
  ### Targeting
211
216
 
212
- `enqueuePushFanout` speaks the same identity-tag dialect as [realtime targeting](/platform/realtime/durable-objects). For the common browser subscribe flow, reach for `{ targetRoles }` or `{ userIds }` first — those tags are stamped on every session-created subscription:
217
+ A declarative target names **exactly one** audience:
213
218
 
214
219
  | Target | Selects |
215
220
  |---|---|
216
- | `{ targetRoles: ['admin'] }` | Rows whose tags include `role:admin` (any listed role) |
221
+ | `{ organizationId: 'org_1' }` | Devices of every current member of that organization |
222
+ | `{ organizationId: 'org_1', targetRoles: ['admin'] }` | Devices of that org's members holding a listed role — `auth.roleHierarchy`-expanded, so an `owner` satisfies `'admin'` |
223
+ | `{ organizationId: 'org_1', targetRoles: [...], userIds: [...] }` | The same, narrowed to those users |
217
224
  | `{ userIds: ['u1', 'u2'] }` | Subscriptions owned by those users |
225
+ | `{ targetTags: ['scope:event:e9#attendee'] }` | Rows whose stamped tags include ANY listed tag — **`scope:*` tags exist only on scoped-token subscribes** (see note below) |
218
226
  | `{ all: true }` | Every live subscription — broadcast must be this explicit |
219
- | `{ targetTags: ['scope:events:e9'] }` | Rows whose stamped tags include ANY listed tag — **but `scope:*` tags exist only on scoped-token subscribes** (see note below); against session-created rows this selects nobody |
220
- | `{ targetTags: [...], targetRoles: [...] }` | Rows matching BOTH arms (AND across arms, union within) |
221
227
  | `{ subscriptions: [...] }` | An explicit list you already hold |
222
228
 
223
- Selection is **fail-closed**: an empty array selects *nobody* (nothing is enqueued), and a target with no arms at all throws — accidental broadcast is structurally impossible. Tags are proven at subscribe time from `ctx`; clients cannot forge their way into an audience.
229
+ **Org audiences are resolved at send time.** The queue consumer reads the organization's Better Auth membership when it resolves the fan-out (one query; on D1 through the `AUTH_DB` binding), filters by role, and delivers to those members' devices. A member who is demoted or removed stops receiving on the very next send, and one organization's roles never reach another organization's members — a user who is an admin in one org and a member in another is an admin only for the first. `targetRoles` is **only** valid beside `organizationId`: a role without an organization has no tenant, so `{ targetRoles }` alone is a type error and throws at runtime. The `organizationId` arm needs the Better Auth `organization` plugin; without it the target throws.
224
230
 
225
- > **`scope:<kind>:<subject>` tags need a scoped token.** `ctx.scope` is populated *only* from a verified scoped-JWT claim — the same relationship-derived scope the [realtime pillar](/platform/realtime/durable-objects) uses. A normal browser subscribe authenticated with a session cookie stamps only `user:<id>` and `role:<name>`; it **never** stamps a `scope:*` tag. Because targeting is fail-closed, a `{ targetTags: ['scope:events:e9'] }` fan-out over session-created subscriptions silently delivers to **nobody**. Scope targeting works only if your app subscribes users from within a scoped context; otherwise select by role or user id.
231
+ Selection is **fail-closed**: an empty array selects *nobody* (nothing is enqueued), a target with no arm throws, and arms do not combine (`{ userIds, targetTags }` throws) — accidental broadcast is structurally impossible. Tags are proven at subscribe time from `ctx`; clients cannot forge their way into an audience.
232
+
233
+ > **`scope:*` tags need a scoped token.** `ctx.scope` is populated *only* from a verified scoped-JWT claim — the same relationship-derived scope the [realtime pillar](/platform/realtime/durable-objects) uses. A normal browser subscribe authenticated with a session cookie stamps only `user:<id>`; it **never** stamps a `scope:*` tag. Because targeting is fail-closed, a `{ targetTags: ['scope:event:e9#attendee'] }` fan-out over session-created subscriptions delivers to **nobody**. Scope tags — identity and role alike — are frozen at subscribe (re-subscribing refreshes them), so a scope role revoked afterwards keeps matching until then; org roles have no such window because they are never stamped.
226
234
 
227
235
 
228
236
  With an explicit `{ subscriptions }` list, passing `opts.vapid` (via `vapidFromEnv(env)`) lets lists at or under `push.fanout.threshold` (default 500) deliver **inline** with per-recipient results; larger lists chunk onto the queue.
@@ -155,7 +155,7 @@ export default {
155
155
 
156
156
  | Method | Endpoint | Description |
157
157
  |--------|----------|-------------|
158
- | POST | `/bucket` | Create a bucket |
158
+ | POST | `/bucket` | Create a bucket (`allowedMimeTypes` must be a subset of `allowedTypes`) |
159
159
  | GET | `/bucket` | List buckets |
160
160
  | GET | `/bucket/:name` | Get bucket info |
161
161
  | DELETE | `/bucket/:name` | Delete bucket (must be empty) |
@@ -201,6 +201,14 @@ POST /storage/v1/bucket
201
201
  `readScope: "public"` is the default for listing photos and avatars. Switch to
202
202
  `organization` or `user` only when a signed-in session must gate the GET.
203
203
 
204
+ A bucket can also set `fileSizeLimit` and `allowedMimeTypes`. Both **narrow**
205
+ the project-wide `maxFileSize` / `allowedTypes`; neither can widen them.
206
+ `allowedMimeTypes` entries outside the project's `allowedTypes` are rejected
207
+ with `400` `VALIDATION_INVALID_INPUT`, listing the offenders in
208
+ `details.disallowed`. Bucket rows written before that check existed are
209
+ intersected with `allowedTypes` at upload and presign time, so a widened list
210
+ has no effect.
211
+
204
212
  ### Scope Options
205
213
 
206
214
  | Scope | Read Behavior | Write Behavior |
@@ -317,8 +325,9 @@ curl -X POST https://api.example.com/storage/v1/confirm/videos/clip.mp4 \
317
325
  > The `size` and `contentType` from step 1 are **bound into the signature** as
318
326
  > `Content-Length` and `Content-Type` — the client MUST replay the returned
319
327
  > `headers` verbatim on the PUT, or R2 rejects it. That is what makes
320
- > `maxFileSize` and `allowedTypes` real limits on the object that lands, not
321
- > just on the request that asked for a URL.
328
+ > `maxFileSize` and `allowedTypes` (and a bucket's narrower `fileSizeLimit` /
329
+ > `allowedMimeTypes`) real limits on the object that lands, not just on the
330
+ > request that asked for a URL.
322
331
 
323
332
 
324
333
  ### Required secrets
@@ -424,6 +433,25 @@ The files worker:
424
433
  > trusted as minted.
425
434
 
426
435
 
436
+ ### Response headers
437
+
438
+ Uploaded bytes are attacker-controlled, and the API origin shares cookies with
439
+ the CMS and Account apps. So every stored object — from `GET`/`HEAD
440
+ /storage/v1/object/...` and from the files worker alike — is served with one
441
+ header policy:
442
+
443
+ | Header | Value |
444
+ |--------|-------|
445
+ | `X-Content-Type-Options` | `nosniff` |
446
+ | `Content-Security-Policy` | `default-src 'none'; sandbox` |
447
+ | `Content-Disposition` | `inline` for `image/jpeg`, `image/png`, `image/gif`, `image/webp`, `image/avif`; otherwise `attachment; filename="…"; filename*=UTF-8''…` |
448
+
449
+ An SVG, HTML, XML, or PDF upload therefore **downloads** when opened directly
450
+ instead of rendering on your domain. `<img src>` embedding is unaffected —
451
+ subresource loads ignore `Content-Disposition` and the document CSP. The
452
+ filename is the last segment of the object key, RFC 6266-encoded. If you need
453
+ to display PDFs inline, render them from a separate, cookie-less origin.
454
+
427
455
  ## Generated Files
428
456
 
429
457
  When file storage is configured, the compiler generates:
@@ -432,6 +460,7 @@ When file storage is configured, the compiler generates:
432
460
  |------|---------|
433
461
  | `src/storage/routes.ts` | Storage API routes (upload, presign, confirm, download) |
434
462
  | `src/storage/presign.ts` | R2 presigned-URL signer (`createPresigner`, backs `ctx.storage`) |
463
+ | `src/lib/object-headers.ts` | `objectHeaders()` — the serving-header policy shared by the storage routes and the files worker |
435
464
  | `src/files/schema.ts` | Files metadata schema (buckets, objects) — `sqliteTable` on D1, a `files` Postgres schema otherwise |
436
465
  | `src/files/index.ts` | `createFilesDb` — the D1 binding handle, or the Postgres service-lane handle |
437
466
  | `drizzle.files.config.ts` | Second migration target — **D1 only** |
@@ -536,7 +565,7 @@ cd cloudflare-workers/files && npx wrangler deploy --env dev
536
565
  | `binding` | `string` | `R2_BUCKET` | R2 bucket binding name (managed mode) |
537
566
  | `filesBinding` | `string` | `FILES_DB` | Files metadata D1 binding (managed mode, `cloudflare-d1` only — Postgres uses the `files` schema of the single database and emits no binding) |
538
567
  | `maxFileSize` | `number \| string` | 10MB | Max upload size — bytes or `"100mb"` (managed mode) |
539
- | `allowedTypes` | `string[]` | Images only | Allowed MIME types (managed mode) |
568
+ | `allowedTypes` | `string[]` | Images only | Allowed MIME types (managed mode). The ceiling for every bucket: a bucket's `allowedMimeTypes` must be a subset. |
540
569
  | `publicDomain` | `string` | - | Custom domain for files worker (managed mode) |
541
570
 
542
571
  ### How the size limit is enforced
@@ -564,5 +593,8 @@ Both paths answer `413` with the actual and permitted byte counts.
564
593
  read scope never implies a public write.
565
594
  - **Serve security**: Public prefix = URL is the capability. Session-gated
566
595
  paths re-check membership on every GET. Signed GET expires.
596
+ - **Content safety**: Every served object carries `nosniff` and a sandboxing
597
+ CSP; only raster images are `inline`, everything else is an `attachment`
598
+ ([Response headers](#response-headers)).
567
599
  - **Soft deletes**: Files are marked deleted in metadata but retained in R2
568
600
  - **Tenant isolation**: All files are prefixed with organization ID