@quickback-dev/cli 0.66.16 → 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 (101) 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/SKILL.md +2 -2
  14. package/dist/skill/docs/api/actions.md +10 -9
  15. package/dist/skill/docs/api/errors.md +14 -3
  16. package/dist/skill/docs/api/openapi.md +1 -1
  17. package/dist/skill/docs/api/query-params.md +3 -3
  18. package/dist/skill/docs/configure/agents.md +1 -1
  19. package/dist/skill/docs/configure/auth.md +35 -37
  20. package/dist/skill/docs/configure/index.md +1 -1
  21. package/dist/skill/docs/define/access.md +16 -6
  22. package/dist/skill/docs/define/actions/defining.md +8 -1
  23. package/dist/skill/docs/define/actions/scoped-db.md +69 -8
  24. package/dist/skill/docs/define/changesets.md +8 -3
  25. package/dist/skill/docs/define/encryption.md +6 -3
  26. package/dist/skill/docs/define/fga.md +9 -4
  27. package/dist/skill/docs/define/firewall.md +15 -7
  28. package/dist/skill/docs/define/masking.md +1 -1
  29. package/dist/skill/docs/define/relationships.md +6 -3
  30. package/dist/skill/docs/define/schema.md +27 -2
  31. package/dist/skill/docs/define/scopes.md +27 -4
  32. package/dist/skill/docs/define/transitions.md +5 -0
  33. package/dist/skill/docs/define/views.md +9 -0
  34. package/dist/skill/docs/platform/api-contract/index.md +4 -2
  35. package/dist/skill/docs/platform/auth/api-keys.md +10 -1
  36. package/dist/skill/docs/platform/auth/jwt-optimization.md +38 -49
  37. package/dist/skill/docs/platform/auth/plugins/aws-ses.md +11 -4
  38. package/dist/skill/docs/platform/auth/plugins/index.md +7 -15
  39. package/dist/skill/docs/platform/auth/plugins/subscriptions.md +3 -3
  40. package/dist/skill/docs/platform/auth/security.md +2 -2
  41. package/dist/skill/docs/platform/auth/using-auth.md +2 -1
  42. package/dist/skill/docs/platform/database/neon.md +1 -1
  43. package/dist/skill/docs/platform/push/index.md +31 -23
  44. package/dist/skill/docs/platform/storage/r2.md +36 -4
  45. package/dist/skill/docs/platform/vector/embeddings.md +11 -76
  46. package/dist/skill/docs/platform/vector/index.md +1 -1
  47. package/dist/skill/docs/platform/vector/using-embeddings.md +10 -73
  48. package/dist/skill/docs/platform/webhooks/outbound.md +12 -8
  49. package/dist/skill/docs/tooling/cli.md +2 -2
  50. package/dist/skill/docs/tooling/cloud-compiler/authentication.md +1 -1
  51. package/dist/skill/docs/tooling/cloud-compiler/endpoints.md +2 -1
  52. package/dist/skill/docs/tooling/cloud-compiler/index.md +18 -3
  53. package/dist/skill/docs/tooling/cloud-compiler/local-compiler.md +7 -4
  54. package/dist/skill/docs/tooling/cloud-compiler/troubleshooting.md +1 -1
  55. package/dist/skill/docs/tooling/output.md +6 -2
  56. package/dist/skill/docs/ui/account/hooks.md +2 -2
  57. package/package.json +1 -1
  58. package/src/skill/SKILL.md +2 -2
  59. package/src/skill/docs/api/actions.md +10 -9
  60. package/src/skill/docs/api/errors.md +14 -3
  61. package/src/skill/docs/api/openapi.md +1 -1
  62. package/src/skill/docs/api/query-params.md +3 -3
  63. package/src/skill/docs/configure/agents.md +1 -1
  64. package/src/skill/docs/configure/auth.md +35 -37
  65. package/src/skill/docs/configure/index.md +1 -1
  66. package/src/skill/docs/define/access.md +16 -6
  67. package/src/skill/docs/define/actions/defining.md +8 -1
  68. package/src/skill/docs/define/actions/scoped-db.md +69 -8
  69. package/src/skill/docs/define/changesets.md +8 -3
  70. package/src/skill/docs/define/encryption.md +6 -3
  71. package/src/skill/docs/define/fga.md +9 -4
  72. package/src/skill/docs/define/firewall.md +15 -7
  73. package/src/skill/docs/define/masking.md +1 -1
  74. package/src/skill/docs/define/relationships.md +6 -3
  75. package/src/skill/docs/define/schema.md +27 -2
  76. package/src/skill/docs/define/scopes.md +27 -4
  77. package/src/skill/docs/define/transitions.md +5 -0
  78. package/src/skill/docs/define/views.md +9 -0
  79. package/src/skill/docs/platform/api-contract/index.md +4 -2
  80. package/src/skill/docs/platform/auth/api-keys.md +10 -1
  81. package/src/skill/docs/platform/auth/jwt-optimization.md +38 -49
  82. package/src/skill/docs/platform/auth/plugins/aws-ses.md +11 -4
  83. package/src/skill/docs/platform/auth/plugins/index.md +7 -15
  84. package/src/skill/docs/platform/auth/plugins/subscriptions.md +3 -3
  85. package/src/skill/docs/platform/auth/security.md +2 -2
  86. package/src/skill/docs/platform/auth/using-auth.md +2 -1
  87. package/src/skill/docs/platform/database/neon.md +1 -1
  88. package/src/skill/docs/platform/push/index.md +31 -23
  89. package/src/skill/docs/platform/storage/r2.md +36 -4
  90. package/src/skill/docs/platform/vector/embeddings.md +11 -76
  91. package/src/skill/docs/platform/vector/index.md +1 -1
  92. package/src/skill/docs/platform/vector/using-embeddings.md +10 -73
  93. package/src/skill/docs/platform/webhooks/outbound.md +12 -8
  94. package/src/skill/docs/tooling/cli.md +2 -2
  95. package/src/skill/docs/tooling/cloud-compiler/authentication.md +1 -1
  96. package/src/skill/docs/tooling/cloud-compiler/endpoints.md +2 -1
  97. package/src/skill/docs/tooling/cloud-compiler/index.md +18 -3
  98. package/src/skill/docs/tooling/cloud-compiler/local-compiler.md +7 -4
  99. package/src/skill/docs/tooling/cloud-compiler/troubleshooting.md +1 -1
  100. package/src/skill/docs/tooling/output.md +6 -2
  101. package/src/skill/docs/ui/account/hooks.md +2 -2
@@ -137,7 +137,7 @@ Null-safe scope semantics make this safe (these apply **inside `all`/`any` group
137
137
 
138
138
  - A **scope** arm (`ctx.activeOrgId`, `ctx.activeTeamId`, `ctx.scope.*`) whose claim is **absent never binds `undefined`** (the classic 500 / "match every row" trap). In an `any` group an absent arm **drops**; if **every** arm drops, the group denies with `sql\`1 = 0\`` (the empty-guard) — never a full-table read. In an `all` group an absent required scope **denies** the group.
139
139
  - **An `any` group with an org arm tenant-binds its scope and relationship arms.** Beside `{ field: 'organizationId', equals: 'ctx.activeOrgId' }`, a `ctx.scope.*` arm, a `via:` arm, or a `{ permission }` arm is emitted as `scope-arm AND (organizationId = ctx.activeOrgId OR the caller has no org claim)`. A caller with **no** org claim (a scope-only or relationship principal) is unaffected; a caller who carries org B's membership *and* a scope claim or relationship row on an org-A instance cannot ride the scope arm into org A's rows. Owner arms (`ctx.userId`), team arms, and literal `in` lists are not tenant-bound. An org claim and a scope claim in one request are therefore always the same tenant — or the scope arm yields nothing.
140
- - Mark an arm `{ optional: true }` to **drop-instead-of-deny** when absent inside an `all` group (the teamless rest-of-org slice — `ctx.activeTeamId` is implicitly optional).
140
+ - Mark an arm `{ optional: true }` to **drop-instead-of-deny** when absent inside an `all` group (the teamless rest-of-org slice — `ctx.activeTeamId` is implicitly optional). An optional arm only drops while a **non-optional** tenant arm still bounds the query; a sole optional arm denies when its claim is absent, exactly like the team rule below.
141
141
  - **Owner** (`ctx.userId`) and **soft-delete** (`isNull deletedAt`) are always present / always AND'd — never relaxed.
142
142
 
143
143
  > **`ctx.activeTeamId` is implicitly optional only while another tenant arm
@@ -151,6 +151,12 @@ Null-safe scope semantics make this safe (these apply **inside `all`/`any` group
151
151
  > return no `WHERE` at all, and any authenticated caller would read every
152
152
  > tenant's rows.
153
153
  >
154
+ > The same rule holds for the flat array and for `all:` groups, for
155
+ > `{ optional: true }` arms, and for the Postgres RLS policy the compiler
156
+ > emits alongside the API firewall: a sole team or optional arm lowers to
157
+ > strict `team_id = <claim>` (a NULL claim matches no row), never
158
+ > `claim IS NULL OR …`.
159
+ >
154
160
  > This matters because `ctx.activeTeamId` is absent in ordinary
155
161
  > configurations: the Better Auth teams plugin is opt-in, and the external auth
156
162
  > provider does not supply the claim at all. Note that soft-delete and literal
@@ -223,17 +229,19 @@ WHERE sessions.organizationId = ?
223
229
  SELECT eventId FROM event_guests
224
230
  WHERE userId = ?
225
231
  AND status = 'confirmed'
226
- AND <event_guests' own firewall — tenant scope + soft-delete>
232
+ AND <event_guests' soft-delete predicates — NOT its tenant scope>
227
233
  )
228
234
  ```
229
235
 
230
236
  Key properties:
231
237
 
232
238
  - **Firewall stays the outermost AND.** A guest of an event in another tenant is still blocked by your tenant predicate. Relationship-based scoping never bypasses tenant isolation.
233
- - **The relationship table's own firewall is AND'd into the subquery.** Soft-deleting a `event_guests` row revokes access immediately; cross-tenant relationship rows can't grant access.
239
+ - **Only the relationship table's soft-delete predicates are AND'd into the subquery — not its tenant scope.** Soft-deleting an `event_guests` row revokes access immediately. The tenant scope is deliberately skipped: a guest of another tenant's event has no `activeOrgId` for it to match, so applying it would lock out exactly the callers relationships exist for. A relationship row is trusted because of two invariants instead:
240
+ 1. **FK integrity on `resource.column`.** Declare it as a foreign key (`eventId: q.text().references(() => ({ table: 'events', column: 'id' }))`). Creates, and any update that changes it, then check the target through its own firewall ([Foreign-Key Referential Checks](#foreign-key-referential-checks)) — a row can't name another tenant's instance.
241
+ 2. **Write-gating on the relationship table.** Whoever can create or edit its rows can confer the relationship, so gate its `create`/`update` access as tightly as the access it grants — and guard `resource.column` against update (`guards: { immutable: ['eventId'] }`) so an existing row can't be repointed at all.
234
242
  - **Anonymous callers fail closed.** `ctx.userId` is null-guarded; the subquery short-circuits to `WHERE 1 = 0` for unauthenticated requests.
235
243
  - **The relationship table must be tenant-scoped** (`firewall: { exception: true }` is rejected at compile time on relationship tables).
236
- - **The relationship table needs its own `defineTable`.** That `<event_guests' own firewall>` line in the SQL above is the table's generated firewall helper — a bare Drizzle export has none, so a `from:` table with no `export default defineTable(...)` is a compile error naming the table.
244
+ - **The relationship table needs its own `defineTable`.** That `<event_guests' soft-delete predicates>` line in the SQL above comes from the table's generated firewall helper — a bare Drizzle export has none, so a `from:` table with no `export default defineTable(...)` is a compile error naming the table.
237
245
 
238
246
  See [Access — relationships](/define/relationships#authzrelationships) for the full `authz.relationships` shape and role-binding patterns.
239
247
 
@@ -510,7 +518,7 @@ export default defineTable(records, {
510
518
 
511
519
  ### Foreign-Key Referential Checks
512
520
 
513
- Generated `POST /` and `POST /batch` handlers validate every foreign-key column against the **target table's** firewall before inserting. If a record references a row that the caller can't see (wrong org, soft-deleted, or non-existent), the request fails with:
521
+ Every generated write handler — `POST /`, `POST /batch`, `PATCH /:id`, `PATCH /batch`, `PUT /:id` (both its update and create paths), `PUT /batch`, and the root of a [changeset](/define/changesets) — validates foreign-key columns against the **target table's** firewall before writing. Creates check every FK in the body; updates check every FK whose value **changes** (a value equal to the stored one costs no query). If a record references a row that the caller can't see (wrong org, soft-deleted, or non-existent), the request fails with:
514
522
 
515
523
  ```json
516
524
  {
@@ -521,9 +529,9 @@ Generated `POST /` and `POST /batch` handlers validate every foreign-key column
521
529
  }
522
530
  ```
523
531
 
524
- This closes a cross-tenant injection vector: even if an attacker knows a foreign tenant's row ID, they cannot attach a child record to it, and they cannot trigger a cross-tenant cascade delete. The check uses the target table's `buildXFirewallConditions(ctx)` helper, so it honors whatever firewall predicates the target declared (organization, owner, team, custom). FKs to tables with `{ exception: true }` get a plain existence check (still verifies the row exists, doesn't tenant-scope it).
532
+ This closes a cross-tenant injection vector: even if an attacker knows a foreign tenant's row ID, they cannot attach a child record to it — at creation or by repointing an existing row later — and they cannot trigger a cross-tenant cascade delete. The check uses the target table's `buildXFirewallConditions(ctx)` helper, so it honors whatever firewall predicates the target declared (organization, owner, team, custom). FKs to tables with `{ exception: true }` get a plain existence check (still verifies the row exists, doesn't tenant-scope it).
525
533
 
526
- The check runs after guards but before the insert, so it appears as `layer: "validation"` in error responses. Status code is `400`, not `404` — returning `404` would leak existence of out-of-scope rows.
534
+ The check runs after guards but before the write, so it appears as `layer: "validation"` in error responses. Status code is `400`, not `404` — returning `404` would leak existence of out-of-scope rows.
527
535
 
528
536
  ### Pre-Record ID-Probe Defense
529
537
 
@@ -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
 
@@ -372,15 +373,24 @@ its scope arms](/define/firewall#allany-groups--null-safe-scope-semantics) autom
372
373
  ### Dropping the org claim on purpose
373
374
 
374
375
  Guest and crew clients that must never ride the user's org membership into a
375
- scope can mint an identity token without it:
376
+ scope mint an identity token with no active organization — the vanilla Better
377
+ Auth way, no flag:
376
378
 
377
379
  ```bash
378
- curl -X POST https://api.example.com/api/v1/token \
380
+ # clear the session's active org, then mint (Better Auth jwt plugin)
381
+ curl -X POST https://api.example.com/auth/v1/organization/set-active \
379
382
  -H "Cookie: <session>" -H "Content-Type: application/json" \
380
- -d '{ "dropOrg": true }'
383
+ -d '{ "organizationId": null }'
384
+ curl https://api.example.com/auth/v1/token -H "Cookie: <session>"
381
385
  # → { token } with no orgId / role claim; scope entry then proves only relationships
382
386
  ```
383
387
 
388
+ A session that never sets an active organization (a native guest app) mints
389
+ org-less tokens by construction. And an org member entering a **foreign**
390
+ tenant's instance is handled server-side: the namespace resolver re-evaluates
391
+ them through the relationship lanes and `/scope/v1/enter` drops the org
392
+ claims from the scope token, so no client-side drop is needed for that case.
393
+
384
394
  > The realtime [ws-ticket](/platform/realtime/durable-objects#namespace-backed-tickets-per-matched-lane) can authorize through this same namespace `via:`, issuing a per-matched-lane WebSocket ticket — so the socket gate and the REST gate stay identical.
385
395
 
386
396
  In every suppressed case the gate still authorizes the request; only the mint
@@ -608,7 +618,18 @@ within one mint cycle (**≤180s**). Re-prove by calling `ctx.mintScope` again
608
618
  (your own refresh endpoint does exactly that). The by-PK probe does **not** apply
609
619
  the relationship's tenant firewall (a sessionless principal has no
610
620
  `activeOrgId` yet — the proven row *is* what establishes scope), but matching by
611
- 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.
612
633
 
613
634
  ### 3. The scope-only token
614
635
 
@@ -670,6 +691,8 @@ The scope claim is trusted between proofs — it is never re-checked against the
670
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.
671
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.
672
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
+
673
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:
674
697
 
675
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) |
@@ -35,16 +37,16 @@ Scope-bearing tokens also carry `sct` (proof timestamp, unix seconds) and its mi
35
37
 
36
38
  ### Signing
37
39
 
38
- JWTs are signed with HMAC-SHA256 using your `BETTER_AUTH_SECRET` — the same secret you already set for Better Auth, so there is only one secret to manage.
40
+ JWTs are signed with Better Auth's `jwt` plugin keyring: an EdDSA (Ed25519) key pair the plugin stores in the `jwks` table, private key encrypted at rest with your `BETTER_AUTH_SECRET`. There is still only one secret to manage, and it is needed only to **sign** — verification uses the public key, so any worker (or external service) can verify a token from `GET /auth/v1/jwks` without holding the secret.
39
41
 
40
- The signing behaviour is configurable under [`auth.jwt`](/configure/auth) in `quickback.config.ts`: `secretEnv` isolates JWT signing from the Better Auth secret, `issuer` / `audience` add the matching claims, and `algorithm` is `'HS256'` (the only value currently supported).
42
+ The signing behaviour is configurable under [`auth.jwt`](/configure/auth) in `quickback.config.ts`: `issuer` / `audience` set the `iss` / `aud` claims every verifier pins (default `quickback:<project name>`), `expiresIn` sets the TTL, and `revocationCheck` adds sub-TTL revocation. The algorithm is always EdDSA — there is no knob.
41
43
 
42
44
  ```ts title="quickback.config.ts"
43
45
  auth: {
44
46
  jwt: {
45
47
  expiresIn: 180, // default — TTL in seconds
46
48
  revocationCheck: 'none', // default — 'kv' for sub-TTL revocation
47
- secretEnv: 'BETTER_AUTH_SECRET',
49
+ issuer: 'quickback:my-app', // default — quickback:<project name>
48
50
  },
49
51
  },
50
52
  ```
@@ -65,13 +67,14 @@ auth: {
65
67
  Validation steps (in generated `src/middleware/auth.ts`):
66
68
 
67
69
  1. Extract the `Authorization: Bearer <token>` header
68
- 2. Call `verifyJwt(token, BETTER_AUTH_SECRET)` from `src/lib/jwt.ts`
69
- 3. Decode header + payload, recompute the HMAC-SHA256 signature, and compare via `crypto.subtle.verify()` (constant-time — no timing-attack surface)
70
+ 2. Call `verifyJwt(token, env)` from `src/lib/jwt.ts`
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
- The Files worker (R2 uploads) performs the same verification using the shared secret — no network round-trip to the auth API for file operations.
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
 
76
79
  ---
77
80
 
@@ -95,11 +98,8 @@ When a user switches organizations, the JWT must be re-minted because `orgId` an
95
98
  // This happens automatically in the org switcher
96
99
  await authClient.organization.setActive({ organizationSlug: slug });
97
100
 
98
- // Fetch fresh JWT with new org context
99
- const res = await fetch('/api/v1/token', {
100
- method: 'POST',
101
- credentials: 'include',
102
- });
101
+ // Fetch a fresh JWT with the new org context — Better Auth's jwt plugin
102
+ const res = await fetch('/auth/v1/token', { credentials: 'include' });
103
103
  const { token } = await res.json();
104
104
  localStorage.setItem('bearer_token', token);
105
105
  ```
@@ -171,21 +171,25 @@ When a JWT expires or is invalid:
171
171
 
172
172
  ## Token Endpoint
173
173
 
174
- `POST /api/v1/token` mints a fresh JWT from the current session. This endpoint goes through normal auth middleware, so the user must have a valid session cookie.
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.
175
175
 
176
- **Session authentication is required — and enforced.** A request authenticated
177
- by a bearer JWT (or an API key / OAuth access token) is rejected with `401
178
- AUTH_SESSION_REQUIRED` ("Token refresh requires session authentication").
176
+ **Session authentication is required — and enforced.** The plugin gates the
177
+ endpoint on a Better Auth session (cookie or session-token bearer); a request
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)).
179
182
  This is deliberate: only the session path re-validates against Better Auth's
180
183
  session store on every request, so bans, member removals, role demotions, and
181
184
  sign-outs take effect immediately. If a JWT could mint its own replacement, a
182
185
  stolen or revoked token could roll a short-TTL JWT forever without ever
183
186
  re-validating — the TTL would bound nothing.
184
187
 
188
+ **No org claim on purpose.** The token carries the session's active organization. A client that must never ride the user's org membership into a [scope](/define/scopes) (a guest or crew app) clears it first — `authClient.organization.setActive({ organizationId: null })` — and mints; the token then carries no `orgId` / `role`. A foreign-tenant instance reached through `/scope/v1/enter` drops the org claims server-side regardless.
189
+
185
190
  **Request:**
186
191
  ```bash
187
- curl -X POST https://your-api.example.com/api/v1/token \
188
- -H "Content-Type: application/json" \
192
+ curl https://your-api.example.com/auth/v1/token \
189
193
  --cookie "better-auth.session_token=..."
190
194
  ```
191
195
 
@@ -254,15 +258,15 @@ await authClient.signOut();
254
258
  | Token theft (XSS) | 180-second default expiry bounds the exposure window; `expiresIn: 30` tightens it. `httpOnly` cookies protect the session. |
255
259
  | Token replay | Short expiry + `set-auth-token` rotation on session fallback |
256
260
  | Stale permissions | `revocationCheck: 'kv'` — server-side rejection within seconds of a ban, member removal, or role change |
257
- | Token forgery | HMAC-SHA256 signature verified with `BETTER_AUTH_SECRET` |
258
- | Timing attacks | `crypto.subtle.verify()` provides constant-time comparison |
261
+ | Token forgery | EdDSA signature verified against the keyring's public JWKS; only `EdDSA` is accepted (no alg confusion) |
262
+ | Timing attacks | Signature verification is constant-time (Web Crypto via jose) |
259
263
 
260
264
  ### Key Points
261
265
 
262
266
  - JWTs are a **performance optimization**, not a replacement for session auth
263
267
  - Session cookies remain the source of truth — JWTs are derived from them
264
268
  - If a JWT is lost, stolen, or cleared, the system gracefully falls back to cookie auth
265
- - No additional **secret** is needed — signing reuses your existing `BETTER_AUTH_SECRET`. Behaviour *is* configurable: see [`auth.jwt`](/configure/auth) for `expiresIn`, `revocationCheck`, `issuer`, `audience`, `secretEnv`, and `algorithm`
269
+ - No additional **secret** is needed — the keyring's private key is encrypted at rest with your existing `BETTER_AUTH_SECRET`, and verification needs only the public keys. Behaviour *is* configurable: see [`auth.jwt`](/configure/auth) for `expiresIn`, `revocationCheck`, `issuer`, and `audience`
266
270
  - The JWT contains no sensitive data beyond what's already in the auth context
267
271
 
268
272
  ---
@@ -275,45 +279,30 @@ The files worker (for Cloudflare R2 file uploads) also supports JWT authenticati
275
279
 
276
280
  ## Relation to Better Auth's JWT Plugin
277
281
 
278
- Quickback's JWT fast-path (documented above) is a **custom HMAC-SHA256 implementation**, separate from Better Auth's [`jwt` plugin](https://www.better-auth.com/docs/plugins/jwt). The distinction matters if you're comparing options.
279
-
280
- ### What Quickback ships by default
281
-
282
- - Custom HMAC-SHA256 JWTs minted by the compiled API at `POST /api/v1/token`
283
- - Payload includes `sub`, `orgId`, `role`, `userRole`, `email`, `name` — everything the middleware needs to reconstruct `AppContext` with zero DB queries
284
- - Signed with `BETTER_AUTH_SECRET`
285
- - Used by the generated auth middleware as a fast-path ahead of `getSession()`
282
+ Quickback's fast-path and Better Auth's [`jwt` plugin](https://www.better-auth.com/docs/plugins/jwt) are **one system**, not two token formats.
286
283
 
287
- ### What Better Auth's JWT plugin gives you (opt-in)
288
-
289
- Enable it with `plugins: ["jwt"]` in your auth config:
290
-
291
- ```ts
292
- auth: defineAuth("better-auth", {
293
- plugins: ["jwt"],
294
- }),
295
- ```
284
+ ### What the plugin owns
296
285
 
297
- You get:
298
- - JWKS endpoint at `/auth/v1/jwks` for asymmetric public-key verification by external services
299
- - BA's own `/auth/v1/token` endpoint (asymmetric-signed, EdDSA by default)
300
- - Standard OIDC-style claims via BA's `definePayload` hook
286
+ Whenever the project signs any JWT — an `auth.jwt` lane, [`authz.scopes`](/define/scopes), or [agent auth](/platform/auth/plugins/agent-auth) — the compiler enables the plugin automatically. It owns:
301
287
 
302
- ### Why Quickback doesn't use BA's plugin internally
288
+ - **The keyring** — the EdDSA key pair in the `jwks` table, private key encrypted at rest with `BETTER_AUTH_SECRET`.
289
+ - **`GET /auth/v1/jwks`** — the public keys. Any external service verifies Quickback tokens from here; nothing needs the secret.
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.
303
291
 
304
- Better Auth's `definePayload` hook only receives `{ user }`. It cannot embed the active organization context (`orgId`, org-member `role`) that Quickback's Firewall and Access layers need. Without that context in the JWT, the middleware would have to do a DB lookup per request — defeating the whole point of the fast-path.
292
+ ### What Quickback still mints
305
293
 
306
- ### When to enable BA's JWT plugin anyway
294
+ - **The session-path refresh** — `set-auth-token` on every session-authenticated call. Same claims, same key, signed through the plugin's exported signer. The plugin's own `set-auth-jwt` header is disabled so `getSession()` never doubles the member and tier lookups.
295
+ - **Scope tokens** — [`/scope/v1/enter`](/define/scopes), namespace resolvers, and sessionless scope-only mints carry a `scope` claim for principals that may have no Better Auth session at all. The plugin has no concept of those, so Quickback builds the payload and signs it with the plugin's key — one keyring, one verifier.
307
296
 
308
- Turn it on if **external services** need to verify tokens without sharing `BETTER_AUTH_SECRET` — e.g. a third-party worker that wants to confirm a user's identity via JWKS. The BA-issued tokens won't have Quickback's org context, so they're useful for identity assertions, not for hitting the Quickback API directly.
297
+ ### One verifier
309
298
 
310
- Enabling BA's plugin does **not** change how the compiled API authenticates requests — the middleware keeps using the custom HMAC JWT regardless.
299
+ `src/lib/jwt-verify.ts` — pure jose, no Better Auth import — verifies every token: `EdDSA` only, `iss` / `aud` pinned to the compile-time constants, JWKS cached per isolate and refetched at most once for an unknown `kid`. `src/lib/jwt.ts` wraps it for the API worker (loading the JWKS from the auth instance); the files worker uses it directly over the `jwks` table.
311
300
 
312
301
  ---
313
302
 
314
303
  ## Related
315
304
 
316
- - [Auth & JWT config](/configure/auth) — `auth.jwt` reference: `expiresIn`, `revocationCheck`, `issuer`, `audience`, `secretEnv`, `algorithm`
305
+ - [Auth & JWT config](/configure/auth) — `auth.jwt` reference: `expiresIn`, `revocationCheck`, `issuer`, `audience`
317
306
  - [Auth Overview](/platform/auth) — Setup and configuration
318
307
  - [Auth Security](/platform/auth/security) — Cookie security, rate limiting, CORS
319
308
  - [API Keys](/platform/auth/api-keys) — Programmatic API access
@@ -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 |
@@ -268,25 +268,15 @@ await fetch('/auth/v1/passkey/authenticate/verify', {
268
268
 
269
269
  ### JWT Plugin
270
270
 
271
- Better Auth's JWT plugin adds asymmetric-signed tokens and a JWKS endpoint for external services that need to verify user identity without sharing a shared secret.
272
-
273
- **Enable in config:**
274
-
275
- ```ts
276
- auth: defineAuth("better-auth", {
277
- plugins: ["jwt"],
278
- }),
279
- ```
271
+ Better Auth's JWT plugin owns the keyring every Quickback token is signed with. The compiler enables it automatically whenever the project signs JWTs — an `auth.jwt` lane, `authz.scopes`, or agent auth — so there is nothing to declare.
280
272
 
281
273
  **Endpoints:**
282
- - `GET /auth/v1/jwks` — public keys for verifying BA-issued tokens
283
- - `POST /auth/v1/token` — mint an asymmetric-signed JWT from the current session
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`, `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.
284
276
 
285
- > This is **separate from** Quickback's built-in JWT fast-path. Quickback's middleware already validates a custom HMAC-SHA256 JWT (with embedded org context) on every request — enabling the BA plugin does **not** change how the compiled API authenticates. See [JWT Optimization → Relation to Better Auth's JWT Plugin](/platform/auth/jwt-optimization#relation-to-better-auths-jwt-plugin) for the full comparison and when to use each.
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).
286
278
 
287
279
 
288
- **When to enable:** you have external services (non-Quickback workers, third-party integrations) that need to verify a user's identity via JWKS without holding `BETTER_AUTH_SECRET`. The BA-issued tokens won't carry Quickback's `orgId`/`role` claims, so they're for identity, not API access.
289
-
290
280
  ### API Keys
291
281
 
292
282
  Static, long-lived credentials for cron jobs, scripts, and machine-to-machine integrations. Better Auth's `apiKey` plugin is auto-included when you enable the organizations feature, so no explicit config is required for the standard B2B SaaS shape.
@@ -311,6 +301,8 @@ The header takes precedence when both are present. The query-param form lands in
311
301
  - `GET /auth/v1/api-key/list` — list keys for the current user
312
302
  - `POST /auth/v1/api-key/delete` — revoke a key
313
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
+
314
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.
315
307
 
316
308
  ### OAuth Provider (MCP-ready)
@@ -512,7 +504,7 @@ export const longSessionPlugin = {
512
504
 
513
505
  #### Out of scope
514
506
 
515
- - **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.)
516
508
  - **No conditional inclusion.** Every entry in `customPlugins` is always emitted. Gate environment-specific plugins inside the plugin file itself.
517
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.
518
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
  });
@@ -171,7 +171,7 @@ Quickback supports three bearer-token flavors alongside the standard browser ses
171
171
  |------------|---------|-------------|
172
172
  | Session cookie | Browser SPAs (CMS, Account, your app) | Better Auth session lookup |
173
173
  | Session-token bearer | API clients that grabbed `set-auth-token` | Better Auth `bearer` plugin |
174
- | JWT bearer | API clients that hit `/api/v1/token` | In-worker JWT fast-path (no DB hit) |
174
+ | JWT bearer | API clients that mint at `GET /auth/v1/token` | In-worker JWT fast-path (no DB hit) |
175
175
  | API-key bearer | Long-lived programmatic access | `apiKey` plugin / `x-api-key` / `?api_key=` |
176
176
 
177
177
  These match Better Auth's own framing of bearer tokens as **an alternative to cookies, not a supplement** — a request uses one or the other.
@@ -226,7 +226,7 @@ User-supplied options merge on top of the secure default, so any other [`bearer`
226
226
  | Browser extension injects a victim's session cookie into an attacker's bearer-authed API call | Cookie stripped when `Authorization` is present |
227
227
  | Multi-account user has cookies for two identities and uses bearer for the second | Bearer identity wins; no ambiguity in audit log |
228
228
  | MCP / agent flow exposed to ambient browser cookies | `/mcp` and agent-auth routes are bearer-only (cookies dropped entirely, see [Agent Auth](/platform/auth/plugins/agent-auth)) |
229
- | Alg-confusion / forged JWT (alg=none, HS384, RS256) | Verifier pins HS256; signature math rejects all non-matching algs uniformly with 401 |
229
+ | Alg-confusion / forged JWT (alg=none, HS256, RS256) | Verifier accepts only `EdDSA` against the keyring's public JWKS; every other alg is rejected uniformly with 401 |
230
230
 
231
231
  For a deeper walkthrough of the bearer flow itself, see the upstream [Better Auth bearer plugin docs](https://better-auth.com/docs/plugins/bearer).
232
232