@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.
- package/dist/commands/build.d.ts.map +1 -1
- package/dist/commands/build.js +26 -20
- package/dist/commands/build.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/lib/action-harvest.d.ts +3 -2
- package/dist/lib/action-harvest.d.ts.map +1 -1
- package/dist/lib/action-harvest.js +3 -2
- package/dist/lib/action-harvest.js.map +1 -1
- package/dist/lib/compiler-stubs.d.ts +29 -8
- package/dist/lib/compiler-stubs.d.ts.map +1 -1
- package/dist/lib/compiler-stubs.js +29 -16
- package/dist/lib/compiler-stubs.js.map +1 -1
- package/dist/lib/file-writer.d.ts +9 -0
- package/dist/lib/file-writer.d.ts.map +1 -1
- package/dist/lib/file-writer.js +30 -5
- package/dist/lib/file-writer.js.map +1 -1
- package/dist/skill/docs/api/actions.md +10 -9
- package/dist/skill/docs/api/errors.md +14 -2
- package/dist/skill/docs/api/openapi.md +1 -1
- package/dist/skill/docs/api/query-params.md +7 -4
- package/dist/skill/docs/configure/auth.md +8 -4
- package/dist/skill/docs/configure/index.md +1 -1
- package/dist/skill/docs/define/access.md +16 -6
- package/dist/skill/docs/define/actions/defining.md +8 -1
- package/dist/skill/docs/define/actions/scoped-db.md +69 -8
- package/dist/skill/docs/define/changesets.md +8 -3
- package/dist/skill/docs/define/encryption.md +6 -3
- package/dist/skill/docs/define/escape-hatches.md +2 -2
- package/dist/skill/docs/define/fga.md +9 -4
- package/dist/skill/docs/define/firewall.md +15 -7
- package/dist/skill/docs/define/masking.md +1 -1
- package/dist/skill/docs/define/relationships.md +6 -3
- package/dist/skill/docs/define/schema.md +265 -7
- package/dist/skill/docs/define/scopes.md +15 -1
- package/dist/skill/docs/define/transitions.md +5 -0
- package/dist/skill/docs/define/views.md +9 -0
- package/dist/skill/docs/platform/api-contract/index.md +4 -2
- package/dist/skill/docs/platform/auth/api-keys.md +10 -1
- package/dist/skill/docs/platform/auth/jwt-optimization.md +10 -4
- package/dist/skill/docs/platform/auth/plugins/aws-ses.md +11 -4
- package/dist/skill/docs/platform/auth/plugins/index.md +4 -2
- package/dist/skill/docs/platform/auth/plugins/subscriptions.md +3 -3
- package/dist/skill/docs/platform/push/index.md +31 -23
- package/dist/skill/docs/platform/storage/r2.md +36 -4
- package/dist/skill/docs/platform/vector/embeddings.md +11 -76
- package/dist/skill/docs/platform/vector/index.md +1 -1
- package/dist/skill/docs/platform/vector/using-embeddings.md +10 -73
- package/dist/skill/docs/platform/webhooks/outbound.md +12 -8
- package/dist/skill/docs/tooling/cli.md +2 -2
- package/dist/skill/docs/tooling/cloud-compiler/authentication.md +1 -1
- package/dist/skill/docs/tooling/cloud-compiler/endpoints.md +2 -1
- package/dist/skill/docs/tooling/cloud-compiler/index.md +18 -3
- package/dist/skill/docs/tooling/cloud-compiler/local-compiler.md +7 -4
- package/dist/skill/docs/tooling/cloud-compiler/troubleshooting.md +1 -1
- package/dist/skill/docs/tooling/output.md +6 -2
- package/dist/skill/docs/ui/account/hooks.md +2 -2
- package/package.json +1 -1
- package/src/skill/docs/api/actions.md +10 -9
- package/src/skill/docs/api/errors.md +14 -2
- package/src/skill/docs/api/openapi.md +1 -1
- package/src/skill/docs/api/query-params.md +7 -4
- package/src/skill/docs/configure/auth.md +8 -4
- package/src/skill/docs/configure/index.md +1 -1
- package/src/skill/docs/define/access.md +16 -6
- package/src/skill/docs/define/actions/defining.md +8 -1
- package/src/skill/docs/define/actions/scoped-db.md +69 -8
- package/src/skill/docs/define/changesets.md +8 -3
- package/src/skill/docs/define/encryption.md +6 -3
- package/src/skill/docs/define/escape-hatches.md +2 -2
- package/src/skill/docs/define/fga.md +9 -4
- package/src/skill/docs/define/firewall.md +15 -7
- package/src/skill/docs/define/masking.md +1 -1
- package/src/skill/docs/define/relationships.md +6 -3
- package/src/skill/docs/define/schema.md +265 -7
- package/src/skill/docs/define/scopes.md +15 -1
- package/src/skill/docs/define/transitions.md +5 -0
- package/src/skill/docs/define/views.md +9 -0
- package/src/skill/docs/platform/api-contract/index.md +4 -2
- package/src/skill/docs/platform/auth/api-keys.md +10 -1
- package/src/skill/docs/platform/auth/jwt-optimization.md +10 -4
- package/src/skill/docs/platform/auth/plugins/aws-ses.md +11 -4
- package/src/skill/docs/platform/auth/plugins/index.md +4 -2
- package/src/skill/docs/platform/auth/plugins/subscriptions.md +3 -3
- package/src/skill/docs/platform/push/index.md +31 -23
- package/src/skill/docs/platform/storage/r2.md +36 -4
- package/src/skill/docs/platform/vector/embeddings.md +11 -76
- package/src/skill/docs/platform/vector/index.md +1 -1
- package/src/skill/docs/platform/vector/using-embeddings.md +10 -73
- package/src/skill/docs/platform/webhooks/outbound.md +12 -8
- package/src/skill/docs/tooling/cli.md +2 -2
- package/src/skill/docs/tooling/cloud-compiler/authentication.md +1 -1
- package/src/skill/docs/tooling/cloud-compiler/endpoints.md +2 -1
- package/src/skill/docs/tooling/cloud-compiler/index.md +18 -3
- package/src/skill/docs/tooling/cloud-compiler/local-compiler.md +7 -4
- package/src/skill/docs/tooling/cloud-compiler/troubleshooting.md +1 -1
- package/src/skill/docs/tooling/output.md +6 -2
- package/src/skill/docs/ui/account/hooks.md +2 -2
package/dist/lib/file-writer.js
CHANGED
|
@@ -4,15 +4,40 @@
|
|
|
4
4
|
* Writes generated files to disk with smart merge strategies.
|
|
5
5
|
*/
|
|
6
6
|
import { promises as fs } from 'fs';
|
|
7
|
-
import {
|
|
7
|
+
import { dirname, resolve, sep } from 'path';
|
|
8
8
|
import { pathExists, runWithLimit } from './async-utils.js';
|
|
9
9
|
const WRITE_CONCURRENCY = 16;
|
|
10
|
+
/**
|
|
11
|
+
* Resolve a compiler-returned path inside `baseDir`, refusing absolute paths,
|
|
12
|
+
* `..`/`.` segments, and anything that resolves outside it. File paths come
|
|
13
|
+
* from a server response, so they are untrusted input (audit 021 M6).
|
|
14
|
+
*
|
|
15
|
+
* A local port of the compiler's `resolveWithinBase` (runner/paths.ts): the
|
|
16
|
+
* CLI and compiler deliberately share no code, so keep the two in step.
|
|
17
|
+
*/
|
|
18
|
+
export function resolveWithinOutputDir(baseDir, rawPath) {
|
|
19
|
+
const cleaned = String(rawPath).replace(/\\/g, '/').trim();
|
|
20
|
+
if (!cleaned || cleaned.startsWith('/') || /^[a-zA-Z]:\//.test(cleaned)) {
|
|
21
|
+
throw new Error(`Refusing to write generated file with an absolute or empty path: ${rawPath}`);
|
|
22
|
+
}
|
|
23
|
+
const segments = cleaned.replace(/^\.\//, '').split('/').filter(Boolean);
|
|
24
|
+
if (segments.length === 0 || segments.some((s) => s === '.' || s === '..')) {
|
|
25
|
+
throw new Error(`Refusing to write generated file with a path traversal: ${rawPath}`);
|
|
26
|
+
}
|
|
27
|
+
const base = resolve(baseDir);
|
|
28
|
+
const fullPath = resolve(base, segments.join('/'));
|
|
29
|
+
if (!fullPath.startsWith(base + sep)) {
|
|
30
|
+
throw new Error(`Refusing to write generated file outside ${base}: ${rawPath}`);
|
|
31
|
+
}
|
|
32
|
+
return fullPath;
|
|
33
|
+
}
|
|
10
34
|
/**
|
|
11
35
|
* Write generated files to disk (overwrites all)
|
|
12
36
|
*/
|
|
13
37
|
export async function writeFiles(outputDir, files) {
|
|
14
|
-
|
|
15
|
-
|
|
38
|
+
// Resolve every path before writing any, so one bad path writes nothing.
|
|
39
|
+
const resolved = files.map((file) => ({ file, fullPath: resolveWithinOutputDir(outputDir, file.path) }));
|
|
40
|
+
await runWithLimit(resolved, WRITE_CONCURRENCY, async ({ file, fullPath }) => {
|
|
16
41
|
const fileDir = dirname(fullPath);
|
|
17
42
|
// Ensure directory exists
|
|
18
43
|
await fs.mkdir(fileDir, { recursive: true });
|
|
@@ -31,8 +56,8 @@ export async function writeFiles(outputDir, files) {
|
|
|
31
56
|
* - Config files: Overwrite
|
|
32
57
|
*/
|
|
33
58
|
export async function writeFilesWithMerge(outputDir, files) {
|
|
34
|
-
|
|
35
|
-
|
|
59
|
+
const resolved = files.map((file) => ({ file, fullPath: resolveWithinOutputDir(outputDir, file.path) }));
|
|
60
|
+
await runWithLimit(resolved, WRITE_CONCURRENCY, async ({ file, fullPath }) => {
|
|
36
61
|
const fileDir = dirname(fullPath);
|
|
37
62
|
// Ensure directory exists
|
|
38
63
|
await fs.mkdir(fileDir, { recursive: true });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-writer.js","sourceRoot":"","sources":["../../src/lib/file-writer.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,IAAI,CAAC;AACpC,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"file-writer.js","sourceRoot":"","sources":["../../src/lib/file-writer.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,IAAI,CAAC;AACpC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AAC7C,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAS5D,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAE7B;;;;;;;GAOG;AACH,MAAM,UAAU,sBAAsB,CAAC,OAAe,EAAE,OAAe;IACrE,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;IAC3D,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QACxE,MAAM,IAAI,KAAK,CAAC,oEAAoE,OAAO,EAAE,CAAC,CAAC;IACjG,CAAC;IACD,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CA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AgB;gBAC5B,GAAG,SAAS,CAAC,gBAAgB;aAC9B;YACD,oBAAoB,EAAE;gBACpB,GAAG,QAAQ,CAAC,oBAAoB;gBAChC,GAAG,SAAS,CAAC,oBAAoB;aAClC;YACD,sEAAsE;YACtE,kEAAkE;YAClE,mEAAmE;YACnE,mEAAmE;YACnE,GAAG,CAAC,QAAQ,CAAC,SAAS,IAAI,SAAS,CAAC,SAAS;gBAC3C,CAAC,CAAC;oBACE,SAAS,EAAE;wBACT,GAAG,QAAQ,CAAC,SAAS;wBACrB,GAAG,SAAS,CAAC,SAAS;qBACvB;iBACF;gBACH,CAAC,CAAC,EAAE,CAAC;YACP,OAAO,EAAE;gBACP,GAAG,SAAS,CAAC,OAAO;gBACpB,GAAG,QAAQ,CAAC,OAAO;aACpB;YACD,cAAc,EAAE,QAAQ,CAAC,cAAc,IAAI,SAAS,CAAC,cAAc;SACpE,CAAC;QAEF,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IACzC,CAAC;IAAC,MAAM,CAAC;QACP,wCAAwC;QACxC,OAAO,UAAU,CAAC;IACpB,CAAC;AACH,CAAC"}
|
|
@@ -121,19 +121,20 @@ Same format as record-based actions. The difference is no record lookup or firew
|
|
|
121
121
|
### Security Flow
|
|
122
122
|
|
|
123
123
|
1. **Authentication** — Required (401)
|
|
124
|
-
2. **Organization check** — For org-scoped resources, user must have an active organization (403)
|
|
124
|
+
2. **Organization check** — For org-scoped resources, user must have an active organization (403). Uppercase pseudo-roles (`PUBLIC`, `AUTHENTICATED`, …) skip this check — not the firewall in step 4
|
|
125
125
|
3. **Access** — Role-based check (403)
|
|
126
|
-
4. **Scoped DB** — The `db` passed to the handler
|
|
126
|
+
4. **Scoped DB** — The `db` passed to the handler applies each table's firewall, the same `WHERE` its CRUD routes use
|
|
127
127
|
5. **Input validation** — Zod schema validation (400)
|
|
128
128
|
|
|
129
129
|
### Scoped Database
|
|
130
130
|
|
|
131
|
-
All actions (both standalone and record-based) receive a **scoped `db`**
|
|
131
|
+
All actions (both standalone and record-based) receive a **scoped `db`** that applies each table's generated firewall — org, owner, team, scope, and `via:` arms plus the soft-delete filter — exactly as CRUD does:
|
|
132
132
|
|
|
133
|
-
-
|
|
134
|
-
-
|
|
135
|
-
-
|
|
136
|
-
|
|
133
|
+
- `SELECT` / `UPDATE` / `DELETE` get the table's firewall `WHERE`, AND-merged with yours.
|
|
134
|
+
- `INSERT` stamps every claim column the firewall binds (`organizationId`, `ownerId`, …) from context.
|
|
135
|
+
- A caller without a claim the table's firewall requires reads and writes nothing there; an `INSERT` fails with 403 `FIREWALL_CLAIM_MISSING`. The action's `db` type rejects such tables at compile time when its `access` can't guarantee the claim.
|
|
136
|
+
|
|
137
|
+
Full semantics: [Scoped Database](/define/actions/scoped-db).
|
|
137
138
|
|
|
138
139
|
#### `userId` vs `ownerId` on feature tables
|
|
139
140
|
|
|
@@ -157,10 +158,10 @@ Better Auth's own internal tables (`session`, `account`, `member`, `passkey`, `s
|
|
|
157
158
|
```typescript
|
|
158
159
|
// Your handler receives a scoped db — no manual filtering needed
|
|
159
160
|
execute: async ({ db, ctx, input }) => {
|
|
160
|
-
// This query automatically includes
|
|
161
|
+
// This query automatically includes the applications firewall (e.g. organizationId = ?) AND deletedAt IS NULL
|
|
161
162
|
const items = await db.select().from(applications).where(eq(applications.stage, 'interview'));
|
|
162
163
|
|
|
163
|
-
// Inserts automatically
|
|
164
|
+
// Inserts automatically stamp the firewall's claim columns (e.g. organizationId)
|
|
164
165
|
await db.insert(applications).values({ candidateId: input.candidateId, jobId: input.jobId, stage: 'applied' });
|
|
165
166
|
|
|
166
167
|
return items;
|
|
@@ -16,7 +16,7 @@ The generated API returns structured error responses with consistent fields acro
|
|
|
16
16
|
| `405` | Method Not Allowed | The path is a real route, but not for this verb — the response carries an `Allow` header listing the methods it does accept |
|
|
17
17
|
| `409` | Conflict | Unique constraint hit, or a duplicate [`Idempotency-Key`](/platform/api-contract#idempotency-key) still in flight |
|
|
18
18
|
| `412` | Precondition Failed | `If-Match` revision mismatch — [changesets](/define/changesets) and plain single-record `PATCH`/`PUT`/`DELETE` |
|
|
19
|
-
| `422` | Unprocessable | `Idempotency-Key` reused with a different request or principal |
|
|
19
|
+
| `422` | Unprocessable | `Idempotency-Key` reused with a different request or principal, or a stored encrypted value will not decrypt (`ENCRYPTION_UNREADABLE`) |
|
|
20
20
|
| `428` | Precondition Required | `If-Match` sent where it can't anchor: no revision column, a batch endpoint (single-resource precondition), or the POST changeset variant |
|
|
21
21
|
| `429` | Too Many Requests | Rate limit exceeded |
|
|
22
22
|
| `500` | Internal Error | Uncaught throw — generic body, full error server-side |
|
|
@@ -94,7 +94,7 @@ Missing or invalid authentication tokens.
|
|
|
94
94
|
| Code | Description |
|
|
95
95
|
|------|-------------|
|
|
96
96
|
| `AUTH_MISSING` | No Authorization header provided |
|
|
97
|
-
| `AUTH_INVALID_TOKEN` | Token is malformed or invalid |
|
|
97
|
+
| `AUTH_INVALID_TOKEN` | Token is malformed or invalid — including a Quickback-minted JWT that no longer verifies (rotated key, tampered, revoked). Presented-and-bad is always `401`, never treated as no credential |
|
|
98
98
|
| `AUTH_EXPIRED` | Token has expired |
|
|
99
99
|
| `AUTH_RATE_LIMITED` | Too many auth attempts |
|
|
100
100
|
| `AUTH_REVOCATION_UNAVAILABLE` | **503, retryable.** Only with [`revocationCheck: 'kv'`](/configure/auth#revocationcheck-none--kv--token-revocation-strategy): the bearer's signature verified, but its revocation state could not be read (KV binding missing or unreachable), so it was not trusted. Retry, or authenticate with a session cookie |
|
|
@@ -124,6 +124,13 @@ Firewall filtering is transparent — the query is scoped by `WHERE organization
|
|
|
124
124
|
| `FIREWALL_USER_ISOLATION` | Record belongs to another user |
|
|
125
125
|
| `FIREWALL_SOFT_DELETED` | Record has been soft deleted |
|
|
126
126
|
|
|
127
|
+
Inside an action, an `INSERT` through the [scoped `db`](/define/actions/scoped-db)
|
|
128
|
+
into a table whose firewall requires a claim the caller does not carry (no
|
|
129
|
+
`activeOrgId` for an org-scoped table, say) fails with **403**
|
|
130
|
+
`FIREWALL_CLAIM_MISSING`, `layer: "action"`, and
|
|
131
|
+
`details: { table, column, claim }` — the row is never written into whatever
|
|
132
|
+
tenant the body named.
|
|
133
|
+
|
|
127
134
|
For security-hardened deployments, set `firewallErrorMode: 'hide'` at the **top
|
|
128
135
|
level of the resource definition** (not inside `firewall:` — it was lifted off
|
|
129
136
|
when `firewall` became a predicate array) to return opaque **404 Not Found**
|
|
@@ -225,9 +232,14 @@ Surfaced when a SQL write fails *post-validation* — most often a `NOT NULL` or
|
|
|
225
232
|
| `DB_UNIQUE_VIOLATION` | 409 | Unique constraint hit |
|
|
226
233
|
| `DB_INSERT_FAILED` | 500 | INSERT failed for an unrecognized reason |
|
|
227
234
|
| `DB_UPDATE_FAILED` | 500 | UPDATE failed for an unrecognized reason |
|
|
235
|
+
| `ENCRYPTION_UNREADABLE` | 422 | A stored [`.encrypted()`](/define/encryption) value will not decrypt |
|
|
228
236
|
|
|
229
237
|
The `details.column` field is only present when the driver's error message identified the offending column (SQLite/D1 do; some PG variants don't).
|
|
230
238
|
|
|
239
|
+
`ENCRYPTION_UNREADABLE` always carries `details: { table, column, id }` — the
|
|
240
|
+
row whose stored ciphertext is malformed or was not written under the caller's
|
|
241
|
+
organization key. Rewriting the field repairs the row.
|
|
242
|
+
|
|
231
243
|
## Batch Errors
|
|
232
244
|
|
|
233
245
|
Batch operations can return:
|
|
@@ -23,7 +23,7 @@ The generated spec documents every route the compiler produces:
|
|
|
23
23
|
- Views
|
|
24
24
|
- Actions (including standalone actions)
|
|
25
25
|
- Auth routes (`/api/auth/**`)
|
|
26
|
-
- Storage
|
|
26
|
+
- Storage and webhook routes (when configured)
|
|
27
27
|
|
|
28
28
|
Each endpoint includes request/response schemas derived from your Drizzle column types, access control metadata, and error responses.
|
|
29
29
|
|
|
@@ -89,7 +89,7 @@ currently wired into the emitted route.
|
|
|
89
89
|
- `count` — number of records returned on this page
|
|
90
90
|
- `page` / `pageSize` — derived from `?offset=` and `?limit=`
|
|
91
91
|
- `hasMore` — whether more rows exist in the queried direction. Without `?total=true` it comes from a `limit + 1` over-fetch probe, so it never lies on a final page that exactly fills the limit; with `?total=true` it is page arithmetic (`page < totalPages`).
|
|
92
|
-
- `nextCursor` / `prevCursor` —
|
|
92
|
+
- `nextCursor` / `prevCursor` — keyset cursors; pass them back as `?starting_after=` and `?ending_before=`. Treat them as opaque, but they are encoded, not encrypted: they carry the boundary row's sort-key values. Either can be `null` — including when the sort includes a [masked](/define/masking) column the caller may sort by (`query.roles`) but not see (`show.roles`); page with `?offset=` in that case.
|
|
93
93
|
- `total` / `totalPages` — present **only** when the request passed `?total=true` (see below)
|
|
94
94
|
|
|
95
95
|
There is no `limit` or `offset` member in `pagination`.
|
|
@@ -133,7 +133,10 @@ When the multi-sort format is detected (comma or `-` prefix), the `order` parame
|
|
|
133
133
|
|
|
134
134
|
A client-supplied `?sort=` naming an unknown column — or one outside a view's
|
|
135
135
|
`query.sortable` — returns `400`, for the same reason unknown filters do: rows
|
|
136
|
-
would come back in some other order that reads as the requested one.
|
|
136
|
+
would come back in some other order that reads as the requested one. Array
|
|
137
|
+
columns, and `q.decimal()` columns on D1 (stored as `TEXT`, so they would sort
|
|
138
|
+
as strings), are never sortable — see
|
|
139
|
+
[Decimals, dates, 64-bit integers, and arrays](/define/schema#decimals-dates-64-bit-integers-and-arrays). A view's
|
|
137
140
|
own `defaultSort` fallback is config, not caller input, and is never rejected.
|
|
138
141
|
|
|
139
142
|
## Field Selection
|
|
@@ -231,8 +234,8 @@ This request:
|
|
|
231
234
|
| `search` | LIST, VIEW | Search text across all text columns |
|
|
232
235
|
| `field=value` | LIST, VIEW | Filter by exact match |
|
|
233
236
|
| `field.op=value` | LIST, VIEW | Filter with operator (gt, gte, lt, lte, ne, like, in) |
|
|
234
|
-
| `starting_after` | LIST, VIEW |
|
|
235
|
-
| `ending_before` | LIST, VIEW |
|
|
237
|
+
| `starting_after` | LIST, VIEW | Keyset cursor (from `nextCursor`) — rows strictly after the boundary |
|
|
238
|
+
| `ending_before` | LIST, VIEW | Keyset cursor (from `prevCursor`) — rows strictly before the boundary |
|
|
236
239
|
| `include` | LIST, VIEW, GET | FK-graph embedding (allowlisted — see below) |
|
|
237
240
|
| `fields[<fk>]` | LIST, VIEW, GET | Sparse fields for an embedded include target |
|
|
238
241
|
|
|
@@ -62,7 +62,7 @@ Those two knobs — `expiresIn` and `revocationCheck` — cover the vast majorit
|
|
|
62
62
|
1. The browser SPA gets a JWT via the `set-auth-token` response header on every authenticated call.
|
|
63
63
|
2. On subsequent requests the SPA sends `Authorization: Bearer <jwt>`.
|
|
64
64
|
3. The auth middleware's **fast-path** verifies the signature only — no DB query, no session lookup. `AppContext` is reconstructed from JWT claims.
|
|
65
|
-
4. If
|
|
65
|
+
4. If no JWT is present, the middleware falls back to session auth. If a JWT **this project minted** fails to verify (rotated key, expired, tampered, revoked), the request is refused with `401 AUTH_INVALID_TOKEN` / `AUTH_EXPIRED` — never downgraded to "unauthenticated" — so clients can re-mint on 401 alone.
|
|
66
66
|
5. After successful session auth, a fresh JWT is minted and returned via `set-auth-token`. The cycle continues.
|
|
67
67
|
|
|
68
68
|
The fast-path is intentionally stateless: it trusts the claims for the full TTL. **Stolen or pre-revocation tokens are valid until they expire.** That's the trade-off the fast-path makes — and the reason `expiresIn` and `revocationCheck` are the two most-tuned knobs below: the first bounds the window, the second shrinks it to seconds.
|
|
@@ -89,6 +89,8 @@ Default `quickback:<project name>` — a compile-time constant, so every worker
|
|
|
89
89
|
|
|
90
90
|
Set this when other services need to distinguish JWTs minted by this Worker from other issuers. The compiler bakes the issuer into both the mint side (added to claims) and the verify side (rejects tokens with mismatched `iss`).
|
|
91
91
|
|
|
92
|
+
It must differ from the OAuth provider's issuer (`oauth.issuerUrl`, default `BETTER_AUTH_URL` + `/auth/v1`) — the middleware tells a Quickback token from an OAuth access token by `iss`, so the compiler rejects an issuer equal to the OAuth one, or any URL whose path is the auth base path.
|
|
93
|
+
|
|
92
94
|
### `audience?: string` — `aud` claim
|
|
93
95
|
|
|
94
96
|
Default `quickback:<project name>` (the same constant as `issuer`).
|
|
@@ -102,8 +104,10 @@ Both knobs are gone. Tokens are signed with Better Auth's JWKS keyring (EdDSA),
|
|
|
102
104
|
### `GET /auth/v1/token` — mint an identity JWT
|
|
103
105
|
|
|
104
106
|
Better Auth's jwt plugin endpoint. Session-authenticated callers (cookie or
|
|
105
|
-
session-token bearer) mint a short-lived JWT carrying `sub`, `sid`, `orgId`,
|
|
107
|
+
session-token bearer) mint a short-lived JWT carrying `sub`, `sid`, `ict`, `orgId`,
|
|
106
108
|
`role`, `userRole`, `tiers`, `email`, `name`, plus the pinned `iss` / `aud`.
|
|
109
|
+
An `x-api-key` cannot mint here — it stands in for a session only on
|
|
110
|
+
`GET /auth/v1/get-session`.
|
|
107
111
|
Two invariants:
|
|
108
112
|
|
|
109
113
|
- **`orgId` is only ever signed beside a membership `role`**, and the verifier
|
|
@@ -123,7 +127,7 @@ Default `'none'`.
|
|
|
123
127
|
|
|
124
128
|
| Value | Behavior | Cost per verify |
|
|
125
129
|
|---|---|---|
|
|
126
|
-
| `'none'` | No revocation check. Stolen / pre-revocation tokens valid until TTL expires (scope claims: until the carry-forward cap). Use a low `expiresIn` to bound the replay window. | 0 |
|
|
130
|
+
| `'none'` | No revocation check. Stolen / pre-revocation tokens valid until TTL expires (scope claims: until the carry-forward cap; org / role claims riding a scope token: until their identity proof `ict` passes the same cap — `/scope/v1/enter` and the refresh never restart it). Use a low `expiresIn` to bound the replay window. | 0 |
|
|
127
131
|
| `'kv'` | Fast-path checks per-principal revocation timestamps in the project's existing `KV` binding before trusting a verified token. Fails closed: an unreadable store means the bearer is not trusted. | 2+ KV reads (~5-15ms, edge-cached) |
|
|
128
132
|
|
|
129
133
|
`'kv'` (**Cloudflare runtime only**) keeps the fast-path stateless against the auth DB (still 0 D1 queries). There is nothing extra to provision — entries ride the `KV` binding every project already has, prefixed `qbrev:` and self-expiring after the maximum token lifetime, so the store never accumulates.
|
|
@@ -132,7 +136,7 @@ A token is rejected when its mint timestamp (`iat`/`iatMs`, or the scope claim's
|
|
|
132
136
|
|
|
133
137
|
| Key | Revokes | Written automatically on |
|
|
134
138
|
|---|---|---|
|
|
135
|
-
| `qbrev:sid:<sessionId>` | every JWT minted from one Better Auth session (tokens carry the minting session as `sid`) | `POST /sign-out` and `POST /revoke-session` (Better Auth endpoint hooks) — a lost device's token dies with its session while the user's other devices keep theirs |
|
|
139
|
+
| `qbrev:sid:<sessionId>` | every JWT minted from one Better Auth session (tokens carry the minting session as `sid` — including scope tokens from `/scope/v1/enter`, namespace mints and their refreshes) | `POST /sign-out` and `POST /revoke-session` (Better Auth endpoint hooks) — a lost device's token dies with its session while the user's other devices keep theirs |
|
|
136
140
|
| `qbrev:user:<userId>` | every JWT for the user | user ban (`databaseHooks.user.update.after` — flipping `banned` stamps the key and, when outbound webhooks are enabled, emits a `user.banned` event); `revoke-sessions`, `revoke-other-sessions`, `change-password` with `revokeOtherSessions`, and `delete-user` (endpoint hooks). Call `revokeUserTokens` for custom flows |
|
|
137
141
|
| `qbrev:member:<userId>:<orgId>` | the user's org-membership claims | member removal / role change (Better Auth `organizationHooks`) |
|
|
138
142
|
| `qbrev:scope:<userId>:<kind>:<id>` | the user's carried scope claim | UPDATE/DELETE of a scope-conferring relationship row (audit-wrapper chokepoint + the single DELETE route) |
|
|
@@ -135,7 +135,7 @@ export default defineConfig({
|
|
|
135
135
|
|
|
136
136
|
`routes` is atomic across every surface: feature routes move to `/api/v2/*`,
|
|
137
137
|
Better Auth to `/auth/v2/*`, realtime to `/broadcast/v2`, and generated
|
|
138
|
-
OpenAPI, MCP tool calls, OAuth discovery, `llms.txt`, schema
|
|
138
|
+
OpenAPI, MCP tool calls, OAuth discovery, `llms.txt`, schema routes,
|
|
139
139
|
and dedicated-domain shortcuts follow. When CMS or Account is enabled Quickback
|
|
140
140
|
bakes those paths into the SPA build and injects them at runtime. Quickback
|
|
141
141
|
does not expose a mixed v1/v2 URL surface from one compiled Worker.
|
|
@@ -208,6 +208,8 @@ Quickback ships seven reserved UPPERCASE markers. Six are real pseudo-roles hand
|
|
|
208
208
|
|
|
209
209
|
You can mix pseudo-roles with real roles in the same list — they're OR'd together.
|
|
210
210
|
|
|
211
|
+
Pseudo-roles skip the Access layer's active-organization precondition — they do **not** skip the Firewall. Row scoping still comes from each table's firewall, in CRUD routes and inside an action's scoped `db` alike: an `AUTHENTICATED` caller with no active org reads nothing from an org-scoped table. See [Scoped Database](/define/actions/scoped-db).
|
|
212
|
+
|
|
211
213
|
#### `PUBLIC` — unauthenticated access
|
|
212
214
|
|
|
213
215
|
Use `roles: ["PUBLIC"]` for public-facing endpoints like contact forms, public listings, or webhooks. Skips both the auth gate and the role check.
|
|
@@ -441,17 +443,25 @@ declaratively (`roles`, `userRole`, `record`, `or`, `and`).
|
|
|
441
443
|
|
|
442
444
|
### Collection routes honour `access.record` too
|
|
443
445
|
|
|
444
|
-
`GET /`, the per-view lists,
|
|
445
|
-
|
|
446
|
-
return a row the caller could not `GET` one at a time:
|
|
446
|
+
`GET /`, the per-view lists, `?total`, `?search`, view aggregations, and the
|
|
447
|
+
generated MCP list tool fold the same arms into the query's `WHERE`, arm for
|
|
448
|
+
arm, so a list can never return a row the caller could not `GET` one at a time:
|
|
447
449
|
|
|
448
450
|
- Each `or` arm whose role / `userRole` gates admit the caller contributes its
|
|
449
451
|
`record` predicates as one AND-group; the groups are OR'd together.
|
|
450
|
-
-
|
|
451
|
-
|
|
452
|
+
- A [relationship-role](/define/relationships) arm contributes
|
|
453
|
+
`<resource.column> IN (<relationship subquery>)` — only rows the caller is
|
|
454
|
+
related to — and an [`fga`](/define/fga#filtering-a-collection-by-an-fga-relation)
|
|
455
|
+
arm contributes membership in the caller's `ListObjects` id set. Both compose
|
|
456
|
+
with `record:` siblings like any other arm; neither lifts the constraint.
|
|
457
|
+
- An admitted arm with **no** `record` block (and no relationship / `fga`
|
|
458
|
+
arm) lifts the constraint for the whole list (that arm would admit every
|
|
459
|
+
row on `GET /:id` as well).
|
|
452
460
|
- A `$ctx.` value that is absent for the caller (no `activeOrgId`, no
|
|
453
461
|
`scope`) makes that arm unsatisfiable — it denies, never matches.
|
|
454
|
-
- A predicate on a column the table does not
|
|
462
|
+
- A `record:` predicate on a column the table does not declare, or a
|
|
463
|
+
relationship whose `resource.column` the table does not declare, is a
|
|
464
|
+
**compile error** — the list could never be filtered by it.
|
|
455
465
|
- No admitted arm at all → `403` from the role gate, as before.
|
|
456
466
|
|
|
457
467
|
`POST /batch` runs the same per-record check single `POST` does
|
|
@@ -118,7 +118,14 @@ evaluates project code. The output contract feeds OpenAPI and
|
|
|
118
118
|
**Every action input must produce a schema.** A failed harvest fails the
|
|
119
119
|
compile, naming the exact action, whether
|
|
120
120
|
bundling or evaluation failed, and the underlying local error. Output remains
|
|
121
|
-
optional.
|
|
121
|
+
optional. A successful harvest reports its denominator —
|
|
122
|
+
`✔ Resolved 12 of 12 action input schema(s)`.
|
|
123
|
+
|
|
124
|
+
The count covers the action files **you wrote**. Actions the compiler generates
|
|
125
|
+
from a table's [`transitions:`](/define/transitions) have no file in your tree,
|
|
126
|
+
so the CLI never harvests them: they take no input, and the compiler emits
|
|
127
|
+
their strict schema (`{ "type": "object", "properties": {},
|
|
128
|
+
"additionalProperties": false }`) itself.
|
|
122
129
|
|
|
123
130
|
**Why it fails instead of degrading.** The compiler's static fallback parser
|
|
124
131
|
reads your Zod as text and can only produce `type` and `properties`. It never
|
|
@@ -2,16 +2,61 @@
|
|
|
2
2
|
|
|
3
3
|
## Scoped Database
|
|
4
4
|
|
|
5
|
-
All actions receive a **scoped `db`**
|
|
5
|
+
All actions receive a **scoped `db`** that applies each table's **firewall** —
|
|
6
|
+
the same generated `WHERE` clause the table's CRUD routes use:
|
|
7
|
+
|
|
8
|
+
| Operation | What the scoped `db` adds |
|
|
9
|
+
|-----------|---------------------------|
|
|
10
|
+
| `SELECT` | the table's firewall (org / owner / team / scope / `via:` arms) AND soft-delete filter |
|
|
11
|
+
| `UPDATE` / `DELETE` | the same firewall `WHERE`, AND-merged with yours |
|
|
12
|
+
| `INSERT` | every required claim column the firewall binds (e.g. `organizationId` from `ctx.activeOrgId`), overwriting any value you passed |
|
|
13
|
+
|
|
14
|
+
It is not a guess from column names. `any:` groups, `optional` arms, scope
|
|
15
|
+
(`ctx.scope.*`) and `via:` relationship arms, the null-claim deny, the
|
|
16
|
+
`cms.sysadmin` cross-tenant escape, and `firewall: { exception: true }` all
|
|
17
|
+
behave exactly as they do on CRUD — including custom per-table predicates such
|
|
18
|
+
as `{ field: 'linkedUserId', equals: 'ctx.userId' }`.
|
|
19
|
+
|
|
20
|
+
**Access decides whether the handler runs; the firewall still decides which
|
|
21
|
+
rows it touches.** An action admitted by an uppercase marker (`PUBLIC`,
|
|
22
|
+
`AUTHENTICATED`, `SCOPED`, …) skips the Access layer's active-org
|
|
23
|
+
precondition, but not the firewall: a caller without the claim a table's
|
|
24
|
+
firewall requires reads and writes **nothing** in that table (`1 = 0`), and an
|
|
25
|
+
`INSERT` into it fails with **403 `FIREWALL_CLAIM_MISSING`** rather than
|
|
26
|
+
landing in whatever tenant the request body named.
|
|
27
|
+
|
|
28
|
+
- **Scope principals** reach rows through the table's `ctx.scope.*` arms, as on CRUD.
|
|
29
|
+
- **Delegated principals** named in a table's [`databaseAccess`](#delegated-principals-and-databaseaccess) lane keep the soft-delete filter; their row bound is the lane's RLS policy.
|
|
30
|
+
- **Tables with no `defineTable`** (Better Auth tables, bare Drizzle tables) get column rules instead — `organizationId = ctx.activeOrgId`, `ownerId = ctx.userId`, `teamId = ctx.activeTeamId` (team only narrows when another rule binds), plus `deletedAt IS NULL` — and a missing claim denies.
|
|
31
|
+
|
|
32
|
+
### Caught at compile time
|
|
33
|
+
|
|
34
|
+
The action's `db` is typed against its own `access`. A table whose firewall
|
|
35
|
+
requires a claim that some caller your `access` admits may lack — an
|
|
36
|
+
`AUTHENTICATED` or `PUBLIC` action reading an org-scoped table, a
|
|
37
|
+
`scope:<kind>:<role>` action reading a table with no `ctx.scope.<kind>` arm —
|
|
38
|
+
is a `tsc` error on the `from(...)`, `insert(...)`, `update(...)` or
|
|
39
|
+
`delete(...)` call, instead of a query that silently matches nothing:
|
|
40
|
+
|
|
41
|
+
```text
|
|
42
|
+
Property '"QUICKBACK: this action's access admits callers that lack a claim this
|
|
43
|
+
table's firewall requires … Fix: require an org role, add a scope or relationship
|
|
44
|
+
access arm that supplies the claim, or declare the action unsafe and use unsafeDb"'
|
|
45
|
+
is missing in type …
|
|
46
|
+
```
|
|
6
47
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
48
|
+
Every alternative in `access` is checked on its own:
|
|
49
|
+
`or: [{ roles: ['member'] }, { roles: ['scope:application:applicant'] }]` may read a table whose firewall is
|
|
50
|
+
`any: [org arm, ctx.scope.application arm]`, because each lane satisfies one arm.
|
|
51
|
+
A record action's own table is always accepted — the route loaded `record`
|
|
52
|
+
through its firewall. Tables with no `defineTable`, subqueries and raw `sql`
|
|
53
|
+
sources are not gated. Anchored actions get the same treatment for reads:
|
|
54
|
+
`select().from(t)` only accepts tables in the anchor's reach.
|
|
13
55
|
|
|
14
|
-
|
|
56
|
+
Not gated at the type level: joins (`leftJoin(t)` and friends) and `$count` —
|
|
57
|
+
both still go through the runtime firewall rules above (`$count` is scoped;
|
|
58
|
+
a joined table is not re-filtered, so join only through foreign keys you own).
|
|
59
|
+
`db.with(...)` is blocked outright.
|
|
15
60
|
|
|
16
61
|
```typescript
|
|
17
62
|
async execute({ db, ctx, input }) {
|
|
@@ -232,6 +277,22 @@ predicate in the `WHERE` (for example,
|
|
|
232
277
|
|
|
233
278
|
Actions that need to bypass scoped DB filters (for example, platform-level support operations) can enable unsafe mode.
|
|
234
279
|
|
|
280
|
+
`unsafe` is the only sanctioned way around the scoped `db`. The compiler warns
|
|
281
|
+
when a non-`unsafe` action — or a file it imports from the feature's `lib/`,
|
|
282
|
+
the project's `lib/`, `hooks/` or `plugins/` (relative or `~/` imports) —
|
|
283
|
+
reaches a raw database handle instead:
|
|
284
|
+
|
|
285
|
+
- `c.get('db')`
|
|
286
|
+
- a database binding off the environment (`env.DB`, `c.env.HYPERDRIVE`, …)
|
|
287
|
+
- a drizzle driver import (`drizzle-orm/d1`, `drizzle-orm/postgres-js`, …)
|
|
288
|
+
- `auth.$context` (Better Auth's adapter)
|
|
289
|
+
- the action's own `unsafeDb`
|
|
290
|
+
|
|
291
|
+
Each warning names the file, line, and handle. It is a warning for now and
|
|
292
|
+
becomes a compile error in a future minor; declare `unsafe` (or
|
|
293
|
+
`firewall: { exception: true }` for a deliberately unscoped action) if the
|
|
294
|
+
access is intentional.
|
|
295
|
+
|
|
235
296
|
Use object form for explicit policy and mandatory audit metadata:
|
|
236
297
|
|
|
237
298
|
```typescript
|
|
@@ -396,9 +396,14 @@ placeholders must be mapped `payload` keys; an unresolvable placeholder is a
|
|
|
396
396
|
compile error, and a null placeholder value at runtime skips the push
|
|
397
397
|
(fail-closed — nobody gets a blank notification).
|
|
398
398
|
|
|
399
|
-
Fan-out: a scope-keyed delivery
|
|
400
|
-
|
|
401
|
-
|
|
399
|
+
Fan-out: a scope-keyed delivery reaches devices carrying the
|
|
400
|
+
instance-bound scope role tag `scope:<kind>:<instance>#<role>` for each
|
|
401
|
+
`scope:<kind>:<role>` in the profile's roles, where the room placeholder is
|
|
402
|
+
that kind's `requestField` (org roles on a scope room reach no device — they
|
|
403
|
+
are never stamped on subscriptions). An `organizationId` + `userIdFrom`
|
|
404
|
+
delivery targets that user's devices only while they hold one of the profile's
|
|
405
|
+
org roles in that organization, resolved from membership at send time. A
|
|
406
|
+
profile whose roles can reach no device is a compile error. Delivery
|
|
402
407
|
rides the `PUSH_FANOUT_QUEUE` after commit — at-least-once, best-effort,
|
|
403
408
|
never rolling back the changeset. A delivery that resolves to no audience
|
|
404
409
|
pushes to nobody, mirroring the ws broadcast lane exactly.
|
|
@@ -25,11 +25,14 @@ That one modifier changes what a database breach means: a leaked D1 backup, expo
|
|
|
25
25
|
|
|
26
26
|
- **`org_data_keys`** — one row per organization holding a random 256-bit data key (DEK), stored **wrapped** under the `ENCRYPTION_KEK` worker secret. Created lazily on the org's first encrypted write.
|
|
27
27
|
- **Write path** — every write (CRUD routes, batch routes, and `db.insert`/`db.update` inside your actions) flows through the same chokepoint, which AES-256-GCM-encrypts the column before anything else sees it. Audit snapshots, webhook payloads, and realtime deltas therefore carry ciphertext by construction.
|
|
28
|
-
- **
|
|
28
|
+
- **Plaintext in, from clients** — CRUD, batch, and changeset request bodies reject a value that starts with `qbenc:` (400). Clients send plaintext; the `qbenc:` prefix is reserved for stored ciphertext. Action code can still write `ctx.crypto.encrypt()` output directly — the chokepoint passes ciphertext through untouched.
|
|
29
|
+
- **Read path** — generated routes decrypt behind the firewall and then apply masking, so authorized callers see plaintext and everyone else sees the redaction — never ciphertext. A stored value that will not decrypt fails the request with `422` [`ENCRYPTION_UNREADABLE`](/api/errors), naming the table, column, and row id — never a silent `null`.
|
|
29
30
|
- **`ctx.crypto`** — explicit `await ctx.crypto.decrypt(value)` / `ctx.crypto.encrypt(value)` for action code that processes the field server-side (building a manifest, sending an email). Scoped to the caller's active organization. `ctx.crypto` is only hydrated for authenticated requests — inside schedules, queue consumers, email handlers, and `PUBLIC` actions it is undefined. There, import the primitives directly: `import { encryptValue, decryptValue } from '../lib/encryption'` and call `decryptValue(env, db, organizationId, stored)`. Writes through the `withInternalContext` handle still encrypt automatically.
|
|
30
31
|
- **Boot guard** — a project with encrypted columns refuses to serve without `ENCRYPTION_KEK` (503 `MISSING_ENV`), instead of silently storing plaintext.
|
|
31
32
|
|
|
32
|
-
Values at rest look like `qbenc:1:<keyVersion>:<iv>:<ciphertext>` — the prefix makes accidental plaintext detectable, and the embedded key version
|
|
33
|
+
Values at rest look like `qbenc:1:<keyVersion>:<iv>:<ciphertext>` — the prefix makes accidental plaintext detectable, and the embedded key version is recorded for future key rotation. Rotation is not built yet: every value is written and read under the org's single current DEK.
|
|
34
|
+
|
|
35
|
+
Each wrapped DEK is bound to its organization (AES-GCM additional data), so a wrapped key copied into another org's `org_data_keys` row fails to unwrap. Rows written before this binding are still read and are rewrapped the first time they load (on D1; on Neon the request connection has no `UPDATE` on `org_data_keys`, so legacy rows stay in the older format until a service-role pass).
|
|
33
36
|
|
|
34
37
|
## Setup
|
|
35
38
|
|
|
@@ -54,7 +57,7 @@ Encrypted columns **may** appear in view projections and responses — they decr
|
|
|
54
57
|
|
|
55
58
|
## Per-organization keys: blast radius and crypto-shredding
|
|
56
59
|
|
|
57
|
-
Each organization's data is encrypted under its own DEK, so one compromised key never exposes another tenant. Deleting an org's `org_data_keys` row makes every encrypted value it
|
|
60
|
+
Each organization's data is encrypted under its own DEK, so one compromised key never exposes another tenant. Deleting an org's `org_data_keys` row makes every encrypted value it wrote unreadable **with the current `ENCRYPTION_KEK`** — provided no copy of that wrapped key survives elsewhere (database backups, point-in-time restore, exports). Shredding is a manual, service-role delete today; there is no generated shred or rotation endpoint. After a delete, the next encrypted write for that org creates a fresh DEK, and reads of the old values fail with `ENCRYPTION_UNREADABLE`.
|
|
58
61
|
|
|
59
62
|
## What this tier does and doesn't claim
|
|
60
63
|
|
|
@@ -5,10 +5,10 @@
|
|
|
5
5
|
compiled to Drizzle. It turns
|
|
6
6
|
|
|
7
7
|
```
|
|
8
|
-
feature(name, { columns, indexes, unique, ...rest })
|
|
8
|
+
feature(name, { columns, indexes, unique, check, ...rest })
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
into `q.table(name, columns, { indexes, unique })` plus `defineTable(name, rest)`,
|
|
11
|
+
into `q.table(name, columns, { indexes, unique, check })` plus `defineTable(name, rest)`,
|
|
12
12
|
passing every other key through verbatim. Both forms produce byte-identical output.
|
|
13
13
|
|
|
14
14
|
`defineTable()` is **not deprecated**. It is the layer underneath, and it is what you
|
|
@@ -178,17 +178,22 @@ export default feature('jobs', {
|
|
|
178
178
|
});
|
|
179
179
|
```
|
|
180
180
|
|
|
181
|
-
|
|
181
|
+
The `fga` arm composes with its siblings exactly like any other access arm —
|
|
182
|
+
each `or` arm that admits the caller contributes a filter, and the filters are
|
|
183
|
+
OR'd:
|
|
182
184
|
|
|
183
185
|
| Access shape | Collection behavior |
|
|
184
186
|
| --- | --- |
|
|
185
187
|
| `{ fga }` | Always filter to the FGA-authorized ids. |
|
|
186
188
|
| `{ or: [{ roles }, { fga }] }` | If the role arm passes, return all firewall-scoped rows (no FGA filter); otherwise filter to the authorized ids. |
|
|
187
189
|
| `{ and: [{ roles }, { fga }] }` | If the role arm fails, return an empty page; otherwise filter to the authorized ids. |
|
|
190
|
+
| `{ or: [{ roles, record }, { fga }] }` | Rows matching the `record:` predicate **or** the authorized ids — the `record:` sibling is never dropped. |
|
|
188
191
|
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
+
Nesting depth and the number of `fga` arms are unrestricted. The `object`
|
|
193
|
+
template must be `"<type>:{<idColumn>}"` with `idColumn` a declared column of
|
|
194
|
+
the table — anything else is a **compile error** (it could not be mapped back
|
|
195
|
+
to rows). For shapes you'd rather filter yourself, enumerate ids with
|
|
196
|
+
`POST /fga/v1/list-objects`.
|
|
192
197
|
|
|
193
198
|
**The cap.** The authorized id set is bounded by `authz.fga.listObjects.maxIds`
|
|
194
199
|
(default **1000**). If a caller's authorized set exceeds the cap, the collection
|
|
@@ -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'
|
|
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
|
-
- **
|
|
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'
|
|
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
|
-
|
|
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
|
|
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). A [self-reference](/define/schema#self-references) (`parentId: q.text().references('self')`) is checked against the table's own firewall the same way.
|
|
525
533
|
|
|
526
|
-
The check runs after guards but before the
|
|
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
|
|
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
|
|