@quickback-dev/cli 0.66.17 → 0.66.19

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 (97) 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/compiler-stubs.d.ts +29 -8
  10. package/dist/lib/compiler-stubs.d.ts.map +1 -1
  11. package/dist/lib/compiler-stubs.js +29 -16
  12. package/dist/lib/compiler-stubs.js.map +1 -1
  13. package/dist/lib/file-writer.d.ts +9 -0
  14. package/dist/lib/file-writer.d.ts.map +1 -1
  15. package/dist/lib/file-writer.js +30 -5
  16. package/dist/lib/file-writer.js.map +1 -1
  17. package/dist/skill/docs/api/actions.md +10 -9
  18. package/dist/skill/docs/api/errors.md +14 -2
  19. package/dist/skill/docs/api/openapi.md +1 -1
  20. package/dist/skill/docs/api/query-params.md +7 -4
  21. package/dist/skill/docs/configure/auth.md +8 -4
  22. package/dist/skill/docs/configure/index.md +1 -1
  23. package/dist/skill/docs/define/access.md +16 -6
  24. package/dist/skill/docs/define/actions/defining.md +8 -1
  25. package/dist/skill/docs/define/actions/scoped-db.md +69 -8
  26. package/dist/skill/docs/define/changesets.md +8 -3
  27. package/dist/skill/docs/define/encryption.md +6 -3
  28. package/dist/skill/docs/define/escape-hatches.md +2 -2
  29. package/dist/skill/docs/define/fga.md +9 -4
  30. package/dist/skill/docs/define/firewall.md +15 -7
  31. package/dist/skill/docs/define/masking.md +1 -1
  32. package/dist/skill/docs/define/relationships.md +6 -3
  33. package/dist/skill/docs/define/schema.md +265 -7
  34. package/dist/skill/docs/define/scopes.md +15 -1
  35. package/dist/skill/docs/define/transitions.md +5 -0
  36. package/dist/skill/docs/define/views.md +9 -0
  37. package/dist/skill/docs/platform/api-contract/index.md +4 -2
  38. package/dist/skill/docs/platform/auth/api-keys.md +10 -1
  39. package/dist/skill/docs/platform/auth/jwt-optimization.md +10 -4
  40. package/dist/skill/docs/platform/auth/plugins/aws-ses.md +11 -4
  41. package/dist/skill/docs/platform/auth/plugins/index.md +4 -2
  42. package/dist/skill/docs/platform/auth/plugins/subscriptions.md +3 -3
  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/docs/api/actions.md +10 -9
  59. package/src/skill/docs/api/errors.md +14 -2
  60. package/src/skill/docs/api/openapi.md +1 -1
  61. package/src/skill/docs/api/query-params.md +7 -4
  62. package/src/skill/docs/configure/auth.md +8 -4
  63. package/src/skill/docs/configure/index.md +1 -1
  64. package/src/skill/docs/define/access.md +16 -6
  65. package/src/skill/docs/define/actions/defining.md +8 -1
  66. package/src/skill/docs/define/actions/scoped-db.md +69 -8
  67. package/src/skill/docs/define/changesets.md +8 -3
  68. package/src/skill/docs/define/encryption.md +6 -3
  69. package/src/skill/docs/define/escape-hatches.md +2 -2
  70. package/src/skill/docs/define/fga.md +9 -4
  71. package/src/skill/docs/define/firewall.md +15 -7
  72. package/src/skill/docs/define/masking.md +1 -1
  73. package/src/skill/docs/define/relationships.md +6 -3
  74. package/src/skill/docs/define/schema.md +265 -7
  75. package/src/skill/docs/define/scopes.md +15 -1
  76. package/src/skill/docs/define/transitions.md +5 -0
  77. package/src/skill/docs/define/views.md +9 -0
  78. package/src/skill/docs/platform/api-contract/index.md +4 -2
  79. package/src/skill/docs/platform/auth/api-keys.md +10 -1
  80. package/src/skill/docs/platform/auth/jwt-optimization.md +10 -4
  81. package/src/skill/docs/platform/auth/plugins/aws-ses.md +11 -4
  82. package/src/skill/docs/platform/auth/plugins/index.md +4 -2
  83. package/src/skill/docs/platform/auth/plugins/subscriptions.md +3 -3
  84. package/src/skill/docs/platform/push/index.md +31 -23
  85. package/src/skill/docs/platform/storage/r2.md +36 -4
  86. package/src/skill/docs/platform/vector/embeddings.md +11 -76
  87. package/src/skill/docs/platform/vector/index.md +1 -1
  88. package/src/skill/docs/platform/vector/using-embeddings.md +10 -73
  89. package/src/skill/docs/platform/webhooks/outbound.md +12 -8
  90. package/src/skill/docs/tooling/cli.md +2 -2
  91. package/src/skill/docs/tooling/cloud-compiler/authentication.md +1 -1
  92. package/src/skill/docs/tooling/cloud-compiler/endpoints.md +2 -1
  93. package/src/skill/docs/tooling/cloud-compiler/index.md +18 -3
  94. package/src/skill/docs/tooling/cloud-compiler/local-compiler.md +7 -4
  95. package/src/skill/docs/tooling/cloud-compiler/troubleshooting.md +1 -1
  96. package/src/skill/docs/tooling/output.md +6 -2
  97. package/src/skill/docs/ui/account/hooks.md +2 -2
@@ -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
 
@@ -82,7 +82,7 @@ A few mechanics to know:
82
82
  - **Column names** default to snake_case of the JS key — `organizationId` ↔ `organization_id`, `salaryMin` ↔ `salary_min`. Pass a positional argument to override: `q.text('custom_name')`.
83
83
  - **`q.id()`** emits `text('id').primaryKey()` with a provider-driven app-layer default.
84
84
  - **`.required()` / `.optional()`** control NOT NULL. Chain before or after `.default(x)`.
85
- - **References:** `q.text().required().references(() => other.id, { onDelete: 'cascade' })`. An FK declares a *pointer*, not ownership — when the child rows are a **composition** of one root (junctions, phones/emails, line items), also declare [`owns`](/define/changesets) on the root to generate the atomic aggregate write path. `other` must be a **feature table in the same database**.
85
+ - **References:** `q.text().required().references(() => other.id, { onDelete: 'cascade' })`, or `.references('self')` for a column pointing at another row of the same table (see [Self-references](#self-references)). An FK declares a *pointer*, not ownership — when the child rows are a **composition** of one root (junctions, phones/emails, line items), also declare [`owns`](/define/changesets) on the root to generate the atomic aggregate write path. `other` must be a **feature table in the same database**.
86
86
 
87
87
  > **Never FK Better Auth tables**
88
88
  >
@@ -103,7 +103,7 @@ A few mechanics to know:
103
103
  > `authz.relationships` `subject: { column: 'userId', equals: 'ctx.userId' }` does not need, and must not create, a SQL FK. See [Relationships](/define/relationships). To query Better Auth tables, use `c.get("authDb")` from an action — see [Scoped DB](/define/actions/scoped-db#reaching-better-auth-tables-authdb).
104
104
 
105
105
 
106
- - **Indexes:** column-level `.index()` or table-level `indexes` / `unique` as a third arg to `q.table(name, cols, { indexes, unique })`. With `feature()`, pass `indexes` and `unique` as top-level keys alongside `columns` — the sugar forwards them into the same `q.table` opts.
106
+ - **Indexes and constraints:** column-level `.index()` / `.unique()` / `.check(expr)`, or table-level `indexes` / `unique` / `check` as a third arg to `q.table(name, cols, { indexes, unique, check })`. With `feature()`, pass `indexes`, `unique` and `check` as top-level keys alongside `columns` — the sugar forwards them into the same `q.table` opts. See [Constraints](#constraints--check-and-unique).
107
107
 
108
108
  ### Column Types
109
109
 
@@ -112,14 +112,21 @@ A few mechanics to know:
112
112
  | `q.text()` | `text(...)` | `z.string()` |
113
113
  | `q.url()` | `text(...)` | `z.string().url()` |
114
114
  | `q.int()` | `integer(...)` | `z.number().int()` |
115
+ | `q.bigint()` | `bigint(..., { mode: 'number' })` | `z.number().int()` within ±(2^53 − 1) |
116
+ | `q.smallint()` | `smallint(...)` | `z.number().int()` within −32768..32767 |
117
+ | `q.decimal({ precision, scale })` | `numeric(..., { precision, scale })` | decimal string within precision/scale |
115
118
  | `q.bool()` | `boolean(...)` | `z.boolean()` |
116
119
  | `q.uuid()` | `uuid(...)` | `z.string().uuid()` |
117
120
  | `q.timestamp()` | `timestamp(...)` (converted to SQLite `text` on sqlite targets) | `z.coerce.date()` |
121
+ | `q.date()` | `date(...)` | `z.iso.date()` (`YYYY-MM-DD`) |
118
122
  | `q.json()` | `jsonb(...)` | `z.unknown()` (or the type you pass in) |
119
123
  | `q.enum(['a','b'])` | `text(..., { enum: [...] })` | `z.enum([...])` |
120
124
  | `q.id()` | `text('id').primaryKey()` | `z.string()` |
121
125
  | `q.scope(kind)` | `text(...).notNull()` | `z.string()` |
122
126
  | `q.stamp({ fromScope, claim })` | `text(...).notNull()` (nullable with `optional: true`) | `z.string().optional()` |
127
+ | `.array()` on `q.text()` / `q.enum()` / `q.int()` / `q.uuid()` | `text(...).array()` etc. | `z.array(<element>)` |
128
+
129
+ The Drizzle column is the Postgres form; on SQLite/D1 the compiler lowers it. The next section has the per-dialect storage for the exact-numeric, date, and array types.
123
130
 
124
131
  In request bodies a column that is not `.required()` is `.optional().nullable()` — omit it to leave it untouched, send `null` to clear it. `""` is not a blank: it is validated like any other value. `.required()` columns never accept `null`.
125
132
 
@@ -135,6 +142,60 @@ auto-injection may keep the same `createId()` call site and back it with a
135
142
  file-local `crypto.randomUUID()` polyfill so schema-generation sandboxes do not
136
143
  depend on project `node_modules`.
137
144
 
145
+ ### Decimals, dates, 64-bit integers, and arrays
146
+
147
+ Each of these has native Postgres DDL. SQLite has no equivalent type, so on D1 the compiler lowers it to a storage class that keeps the value exact, and the wire format is the same on both dialects:
148
+
149
+ | Builder | Postgres | SQLite / D1 | Wire value | Rejected with 400 |
150
+ |---------|----------|-------------|------------|-------------------|
151
+ | `q.decimal({ precision: 12, scale: 2 })` | `numeric(12, 2)` | `TEXT` | string, `"1234.50"` | more than `precision − scale` integer digits or `scale` fraction digits, JSON numbers, exponents |
152
+ | `q.date()` | `date` | `TEXT` (`YYYY-MM-DD`) | string, `"2026-03-31"` | impossible dates (`2026-02-30`), any time or zone part |
153
+ | `q.bigint()` | `bigint` | `INTEGER` | number | non-integers, anything outside ±(2^53 − 1) |
154
+ | `q.smallint()` | `smallint` | `INTEGER` | number | anything outside −32768..32767 |
155
+ | `q.text().array()`, `q.enum([...]).array()`, `q.int().array()`, `q.uuid().array()` | `text[]`, `text[]`, `integer[]`, `uuid[]` | `TEXT` holding JSON | JSON array | non-arrays, and any element the scalar would reject (`q.enum(["a"]).array()` refuses `["b"]`) |
156
+
157
+ ```typescript
158
+ import { feature, q } from "@quickback/compiler";
159
+
160
+ export default feature("invoices", {
161
+ columns: {
162
+ id: q.id(),
163
+ number: q.text({ maxLength: 40 }).required(),
164
+ total: q.decimal({ precision: 12, scale: 2 }).required().filterable("eq"),
165
+ taxRate: q.decimal({ precision: 6, scale: 5 }).optional(),
166
+ issuedOn: q.date().required().filterable("range"),
167
+ amountCents: q.bigint().required(),
168
+ lineCount: q.smallint().default(1).required(),
169
+ labels: q.text().array().default([]).required(),
170
+ channels: q.enum(["web", "phone", "store"]).array().optional(),
171
+ organizationId: q.scope("organization"),
172
+ ...q.audit(),
173
+ },
174
+ read: { access: { roles: ["owner", "admin", "member"] } },
175
+ create: { access: { roles: ["owner", "admin"] } },
176
+ update: { access: { roles: ["owner", "admin"] } },
177
+ delete: { access: { roles: ["owner", "admin"] }, mode: "hard" },
178
+ });
179
+ ```
180
+
181
+ - **Decimals are strings**, so no value passes through a float. Send `"19.9"` and the API stores and returns `"19.90"`: the value is padded to `scale` digits and leading zeros are dropped, which is how Postgres prints `numeric(p,s)`. D1 stores that same canonical text, so both dialects return identical strings. `precision` (1–1000) and `scale` (0–`precision`) must be number literals, or the compile fails.
182
+ - **Dates have no time zone.** A `q.date()` value is never converted, so `"2026-03-31"` is the same day for every caller. Use `q.timestamp()` for an instant.
183
+ - **`q.bigint()` values are JSON numbers, and are capped at ±(2^53 − 1).** Past that, a JSON number can't hold an exact integer, and D1 returns every `INTEGER` as a JS number. The cap still takes a cents column past $90 trillion, where `q.int()` (Postgres `integer`) stops at about $21.4 million. Values written to a Postgres `bigint` outside the API beyond 2^53 will read back rounded.
184
+ - **Defaults are checked at compile time** against the same rules, because nothing re-validates a DDL default. `q.smallint().default(40000)` fails the compile. A decimal default must already be in canonical form, so write `.default("0.00")` for scale 2, not `"0"`.
185
+ - **`.array()`** works on `q.text()`, `q.enum()`, `q.int()`, and `q.uuid()`, and must be written once. `.default([])` gives Postgres `'{}'` and D1 `'[]'`. An array column can't declare `.references()`: Postgres has no foreign keys over array elements, so use a join table.
186
+
187
+ What you can query depends on the type. The compiler refuses the rest at compile time, and the list endpoint refuses them at runtime too:
188
+
189
+ | Type | `?search=` | `.filterable()` | `?sort=` |
190
+ |------|------------|-----------------|----------|
191
+ | `q.decimal` on Postgres | no | `eq`, `in`, `range` | yes |
192
+ | `q.decimal` on D1 | no | `eq`, `in` (the filter value is canonicalized, so `?total=19.9` matches `"19.90"`) | no. It is `TEXT` there, so both sorting and range filters would compare strings. |
193
+ | `q.date` | no | `eq`, `in`, `range` | yes (`YYYY-MM-DD` sorts correctly on both dialects) |
194
+ | `q.bigint`, `q.smallint` | no | `eq`, `in`, `range` | yes |
195
+ | `.array()` | no | no | no |
196
+
197
+ `.searchable()` and `.filterable("like")` are text-only. Masks that format strings (`email`, `phone`, `partial`, and the rest) are refused on `q.bigint()`, `q.smallint()`, and array columns; use `redact` or `custom` there. Decimal and date values are strings, so every mask type works on them. `.defaultNow()` is only accepted on `q.timestamp()`.
198
+
138
199
  ### q.scope() — tenant scope columns
139
200
 
140
201
  `q.scope(kind)` is the canonical way to declare a column that holds a tenant-scope value (org / owner / team). It compiles to `text(...).notNull()` like a regular required text column, plus metadata that the compiler reads to:
@@ -217,6 +278,125 @@ For one-off overrides on a specific column, pass an explicit name as the positio
217
278
  organizationId: q.scope('organization', { sqlName: 'org_id' }), // SQL name: 'org_id'
218
279
  ```
219
280
 
281
+ ### Constraints — CHECK and unique
282
+
283
+ Declare CHECK constraints on a column or on the `feature()` config, and unique
284
+ constraints as `unique` entries. They compile to Drizzle's `check()`,
285
+ `uniqueIndex()` and `unique()`, so drizzle-kit writes the DDL into the
286
+ migration on both dialects.
287
+
288
+ ```typescript
289
+ // quickback/features/line_items/line_items.ts
290
+ import { feature, q } from '@quickback/compiler';
291
+
292
+ export default feature('line_items', {
293
+ columns: {
294
+ id: q.id(),
295
+ sku: q.text().required(),
296
+ quantity: q.int().required().check('> 0'),
297
+ unitPriceCents: q.int().required().check('>= 0'),
298
+ productId: q.text().optional(),
299
+ serviceId: q.text().optional(),
300
+ organizationId: q.scope('organization'),
301
+ ...q.audit(),
302
+ ...q.softDelete(),
303
+ },
304
+ check: [
305
+ // exactly one of productId / serviceId
306
+ { name: 'line_items_one_target', sql: '(product_id IS NULL) <> (service_id IS NULL)' },
307
+ ],
308
+ unique: [
309
+ { columns: ['organizationId', 'sku'], whereNotDeleted: true },
310
+ ],
311
+ read: { access: { roles: ['member'] } },
312
+ create: { access: { roles: ['member'] } },
313
+ update: { access: { roles: ['member'] } },
314
+ delete: { access: { roles: ['admin'] } },
315
+ });
316
+ ```
317
+
318
+ | Declaration | DDL |
319
+ |-------------|-----|
320
+ | `quantity: q.int().check('> 0')` | `CONSTRAINT "line_items_quantity_check" CHECK ("quantity" > 0)` |
321
+ | `check: [{ name, sql }]` | `CONSTRAINT "<name>" CHECK (<sql>)` |
322
+ | `unique: [{ columns }]` | `CREATE UNIQUE INDEX …` |
323
+ | `unique: [{ columns, where: '…' }]` | `CREATE UNIQUE INDEX … WHERE …` (a partial unique index) |
324
+ | `unique: [{ columns, whereNotDeleted: true }]` | `CREATE UNIQUE INDEX … WHERE "deleted_at" IS NULL` |
325
+ | `unique: [{ columns, nullsNotDistinct: true }]` | `CONSTRAINT … UNIQUE NULLS NOT DISTINCT (…)`. Postgres 15+ only. |
326
+
327
+ **How the SQL is written.** Column-level `.check(expr)` is appended to the
328
+ quoted physical column name, as `"<column>" <expr>`. Write only what follows
329
+ the column: `'> 0'`, `"IN ('draft', 'open')"`, `'BETWEEN 1 AND 5'`. The
330
+ table-level `sql` and the unique `where` are complete expressions over the
331
+ **physical (snake_case) column names**: `product_id`, not `productId`.
332
+
333
+ **Nothing is translated per dialect.** The SQL must be valid for your
334
+ database. `num_nonnulls(a, b, c) = 1` works on Postgres only. On D1, write
335
+ `(a IS NOT NULL) + (b IS NOT NULL) + (c IS NOT NULL) = 1`. An invalid
336
+ expression fails when the migration is applied, not at compile time.
337
+
338
+ **Names.** A column check is named `<table>_<column>_check`. A table-level
339
+ check needs an explicit `name` that matches `/^[A-Za-z_][A-Za-z0-9_]*$/`. The
340
+ name can be at most 63 characters, because Postgres truncates longer
341
+ identifiers. It must also differ from every other check, unique and index name
342
+ on the table. A column takes one `.check()`: combine conditions with `AND`,
343
+ or use a table-level check.
344
+
345
+ **Compile errors instead of silent drops.** The compiler reads these options
346
+ from source, and it fails the compile on any of the following:
347
+
348
+ - a value that isn't a literal
349
+ - an unknown key
350
+ - `where` together with `whereNotDeleted`
351
+ - `nullsNotDistinct` on a partial unique
352
+ - `whereNotDeleted` on a table without `...q.softDelete()`
353
+ - `nullsNotDistinct` in a SQLite/D1 project, since SQLite always treats NULLs
354
+ as distinct
355
+
356
+ **Enforced by the database.** CHECK is not part of the request validator. A
357
+ violating write reaches the database and comes back as
358
+ `400 DB_CHECK_VIOLATION` naming the constraint. A unique collision comes back
359
+ as `409 DB_UNIQUE_VIOLATION`. See [Errors](/api/errors). Mirror a check at the
360
+ edge (e.g. `maxLength`) when you want a field-level validation message
361
+ instead.
362
+
363
+ The Postgres-only options, as a fragment:
364
+
365
+ ```typescript
366
+ // Postgres (Neon / PlanetScale Postgres) only
367
+ check: [{ name: 'contacts_one_channel', sql: 'num_nonnulls(email, phone, address) = 1' }],
368
+ unique: [{ columns: ['organizationId', 'externalRef'], nullsNotDistinct: true }],
369
+ ```
370
+
371
+ #### Unique constraints and soft delete
372
+
373
+ A soft-deleted row is still a row. A plain unique on `(organizationId, sku)`
374
+ keeps counting it, so after `DELETE /line_items/:id` the same SKU can't be
375
+ created again. The insert returns `409 DB_UNIQUE_VIOLATION` against a row the
376
+ caller can no longer see. Column-level `.unique()` has the same problem.
377
+
378
+ On a soft-delete table, make the unique **partial**. `whereNotDeleted: true`
379
+ adds `WHERE "deleted_at" IS NULL`, using the table's actual soft-delete column
380
+ under your naming convention. Uniqueness then holds among live rows only, and
381
+ a deleted value can be reused. Restoring a soft-deleted row whose value a live
382
+ row has since taken fails with a unique violation. That is the correct
383
+ outcome, because the two rows would otherwise collide.
384
+
385
+ **ON CONFLICT.** Generated CRUD, `PUT` and batch upsert don't use `ON
386
+ CONFLICT`: they look the row up by id and then insert or update, so partial
387
+ uniques need nothing from them. An action that upserts against a partial unique
388
+ with Drizzle's `onConflictDoUpdate` / `onConflictDoNothing` must repeat the
389
+ predicate as `targetWhere`. Postgres and SQLite only match a partial index to
390
+ a conflict target that carries its `WHERE`:
391
+
392
+ ```typescript
393
+ await db.insert(lineItems).values(row).onConflictDoUpdate({
394
+ target: [lineItems.organizationId, lineItems.sku],
395
+ targetWhere: sql`"deleted_at" IS NULL`,
396
+ set: { quantity: row.quantity },
397
+ });
398
+ ```
399
+
220
400
  ## Drizzle interop
221
401
 
222
402
  If you have an existing Drizzle schema you're bringing forward — or need a dialect-specific column option `q` doesn't expose — use `pgTable` / `sqliteTable` / `mysqlTable` directly:
@@ -339,6 +519,29 @@ quickback/
339
519
  - Tables without a default export are internal (no routes, used for joins/relations)
340
520
  - Route paths are derived from filenames: `applications.ts` → `/api/v1/applications`
341
521
 
522
+ ### Table files are declarative
523
+
524
+ Everything above `export default defineTable(...)` becomes part of the generated
525
+ `schema.ts`, which migration and auth-schema tooling **load** during a compile.
526
+ So the compiler only accepts declarative code there, and fails the compile
527
+ naming the file and line otherwise:
528
+
529
+ - **Imports** from `drizzle-orm` / `drizzle-orm/*`, `@quickback/compiler`, or
530
+ another table file (`./other-table`, `../<feature>/<table>`). `import type`
531
+ may come from anywhere — it is erased.
532
+ - **Top-level statements**: imports, `type` / `interface` declarations, `const`
533
+ / `let` bindings, and `export { … }` lists.
534
+ - **Expressions** built from literals, your imports and bindings, and `Date`,
535
+ `Math`, `JSON`, `Number`, `String`, `Boolean`, `crypto`. Callbacks such as
536
+ `.references(() => …)`, `$defaultFn(() => …)` and the index callback
537
+ `(t) => [...]` follow the same rule; their bodies may hold `const`s and a
538
+ `return`.
539
+
540
+ Not allowed: `require`, `process`, `globalThis`, dynamic `import()`, function
541
+ declarations, loops, assignments, and `constructor` / `prototype` access.
542
+ Logic belongs in an [action](/define/actions); the `defineTable(...)` config
543
+ itself is not affected.
544
+
342
545
  ### defineTable vs defineResource
343
546
 
344
547
  - **`defineTable`** — The standard function for defining tables with generated API routes
@@ -617,8 +820,10 @@ The platform provides the pieces for an explicit policy:
617
820
  `onDelete: 'cascade'` for same-database ownership, and orchestrate
618
821
  cross-database records, R2 objects, and external systems from an explicit
619
822
  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
823
+ - **Encrypted data** — deleting an organization's wrapped DEK makes its
824
+ envelope-encrypted fields unreadable, provided no backup or export still
825
+ holds that row ([crypto-shredding](/define/encryption#per-organization-keys-blast-radius-and-crypto-shredding)
826
+ is a manual, service-role delete). Sealed deployments should
622
827
  include their vault grants, recovery records, and key versions in the same
623
828
  reviewed offboarding workflow.
624
829
 
@@ -828,6 +1033,56 @@ Do this even when a column name appears obvious, such as `sessionId` beside a
828
1033
  relationship might be missing; it is not enough evidence to silently invent
829
1034
  one. CMS-ready schemas state the relationship explicitly.
830
1035
 
1036
+ ### Self-references
1037
+
1038
+ A column that points at another row of the **same** table — a parent folder,
1039
+ the version a document replaces — uses `.references('self')`. It targets the
1040
+ table's own `id`:
1041
+
1042
+ ```typescript
1043
+ // quickback/features/folders/folders.ts
1044
+ import { feature, q } from '@quickback/compiler';
1045
+
1046
+ export default feature('folders', {
1047
+ columns: {
1048
+ id: q.id(),
1049
+ name: q.text().required(),
1050
+ parentId: q.text().optional().references('self', { onDelete: 'set null' }),
1051
+ organizationId: q.scope('organization'),
1052
+ ...q.audit(),
1053
+ ...q.softDelete(),
1054
+ },
1055
+ read: { access: { roles: ['member'] } },
1056
+ create: { access: { roles: ['member'] } },
1057
+ update: { access: { roles: ['member'] } },
1058
+ });
1059
+ ```
1060
+
1061
+ `() => folders.id` cannot work here: inside `feature()` there is no `folders`
1062
+ binding. In the [two-export form](#qtable--definetable--the-expanded-form)
1063
+ the binding exists, but a bare `() => folders.id` inside its own initializer
1064
+ is a TypeScript cycle (TS7022/TS7024) in your editor and in `quickback check`.
1065
+ Either use `'self'` there too, or annotate the thunk's return type the way
1066
+ Drizzle does: `.references((): AnyQuickbackColumn => folders.id)`, with
1067
+ `type AnyQuickbackColumn` imported from `@quickback/compiler`. All three
1068
+ spellings generate the same schema.
1069
+
1070
+ A self-reference is a normal FK everywhere else:
1071
+
1072
+ - **Writes** check it through the table's **own** firewall, like any
1073
+ [FK referential check](/define/firewall#foreign-key-referential-checks): a
1074
+ row can't point at another tenant's row or a soft-deleted one. `null`
1075
+ detaches the row.
1076
+ - **Reads** resolve the parent's display label (`parent_label` on
1077
+ `GET /:id` and the list) through the same firewall, and the CMS renders the column as a picker over the same
1078
+ table.
1079
+ - **Cycles are not refused.** A row may point at itself, and A → B → A passes
1080
+ too: each write checks one hop. If your data must stay a tree, enforce that
1081
+ in an [action](/define/actions) or a [trigger](/define/triggers).
1082
+ - A batch create checks parents that exist **before** the batch. A record
1083
+ can't name a sibling from the same batch as its parent; create the parent
1084
+ first.
1085
+
831
1086
  The legacy resource-level `references: { vendorId: "contact" }` map can override
832
1087
  schema-registry target metadata for an alias, but it does not create a database
833
1088
  foreign key. Prefer `.references(() => contacts.id)` whenever the target is a
@@ -837,7 +1092,7 @@ rows live in `AUTH_DB`, outside the feature database.
837
1092
 
838
1093
  ## Input Hints
839
1094
 
840
- Control how the CMS renders form inputs for specific columns. By default the CMS infers the control from the column itself — `q.timestamp()` → date-time picker, `q.bool()` → checkbox, `q.int()` → number, `q.enum()` → select, `q.url()` → URL input, `q.json()` → textarea, and name patterns for plain text (`*Url`, `*Notes`, `email`). The registry carries the q column `kind`, so this works on SQLite too, where every timestamp is `text` at the SQL layer. `inputHints` overrides the inference:
1095
+ Control how the CMS renders form inputs for specific columns. By default the CMS infers the control from the column itself — `q.timestamp()` → date-time picker, `q.date()` → date picker, `q.bool()` → checkbox, `q.int()` / `q.bigint()` / `q.smallint()` → number, `q.decimal()` → text (so the exact string is sent), `q.enum()` → select, `q.url()` → URL input, `q.json()` → textarea, and name patterns for plain text (`*Url`, `*Notes`, `email`). The registry carries the q column `kind`, so this works on SQLite too, where every timestamp is `text` at the SQL layer. The CMS has no editor for `.array()` columns yet. `inputHints` overrides the inference:
841
1096
 
842
1097
  {/* doc-compile: skip — one-key excerpt: the fence is the `inputHints` map only, with firewall/guards/crud already elided to `// ...`. This page's whole-file examples are the `feature()` and `q.table()`+`defineTable()` forms at the top, which the gate does compile. */}
843
1098
  ```typescript
@@ -914,7 +1169,8 @@ create a database foreign-key constraint. On Neon, use
914
1169
  for fully qualified cross-schema or composite constraints that cannot be
915
1170
  declared alongside a table. The ordered source and target column tuples must
916
1171
  have equal arity, and the referenced target tuple must have a matching unique
917
- or primary-key constraint before the foreign key migration runs.
1172
+ or primary-key constraint before the foreign key migration runs. A partial
1173
+ unique (`where` / `whereNotDeleted`) does not qualify as an FK target.
918
1174
 
919
1175
  Use these constraints for relational integrity only. Authorization, pass
920
1176
  consumption, state transitions, and other business logic belong in the API
@@ -981,7 +1237,9 @@ export const jobs = pgTable('jobs', {
981
1237
  |---------|--------|------------|
982
1238
  | Boolean | `integer({ mode: 'boolean' })` | `boolean()` |
983
1239
  | JSON | `text({ mode: 'json' })` with D1 JSON functions and `->` / `->>` operators | `jsonb()` or `json()` with PostgreSQL JSON indexing |
984
- | Arrays | Relational child rows or JSON arrays (`json_each`) | Native arrays, relational rows, or JSONB |
1240
+ | Arrays | `.array()` lowers to JSON text; also relational child rows or JSON arrays (`json_each`) | `.array()` is a native `T[]`; also relational rows or JSONB |
1241
+ | Exact decimal | `q.decimal()` lowers to `TEXT` (not sortable or range-filterable) | `numeric(p, s)` |
1242
+ | Date | `q.date()` lowers to `TEXT` `YYYY-MM-DD` | `date` |
985
1243
  | Auto-increment | `integer().primaryKey()` | `serial()` |
986
1244
  | UUID | `text()` | `uuid()` |
987
1245
 
@@ -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