@quickback-dev/cli 0.70.31 → 0.70.38
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 +12 -0
- package/dist/commands/build.d.ts.map +1 -1
- package/dist/commands/build.js +69 -1
- package/dist/commands/build.js.map +1 -1
- package/dist/commands/deploy.d.ts +9 -0
- package/dist/commands/deploy.d.ts.map +1 -1
- package/dist/commands/deploy.js +20 -2
- package/dist/commands/deploy.js.map +1 -1
- package/dist/commands/migrate-data.d.ts +12 -0
- package/dist/commands/migrate-data.d.ts.map +1 -0
- package/dist/commands/migrate-data.js +134 -0
- package/dist/commands/migrate-data.js.map +1 -0
- package/dist/commands/migrate.d.ts.map +1 -1
- package/dist/commands/migrate.js +11 -0
- package/dist/commands/migrate.js.map +1 -1
- package/dist/commands/secrets.d.ts +27 -0
- package/dist/commands/secrets.d.ts.map +1 -0
- package/dist/commands/secrets.js +186 -0
- package/dist/commands/secrets.js.map +1 -0
- package/dist/index.js +23 -3
- package/dist/index.js.map +1 -1
- package/dist/lib/access-manifest-diff.d.ts +87 -0
- package/dist/lib/access-manifest-diff.d.ts.map +1 -0
- package/dist/lib/access-manifest-diff.js +331 -0
- package/dist/lib/access-manifest-diff.js.map +1 -0
- package/dist/lib/artifact-routing.d.ts.map +1 -1
- package/dist/lib/artifact-routing.js +3 -0
- package/dist/lib/artifact-routing.js.map +1 -1
- package/dist/lib/compiler-stubs.d.ts +2 -0
- package/dist/lib/compiler-stubs.d.ts.map +1 -1
- package/dist/lib/compiler-stubs.js +2 -0
- package/dist/lib/compiler-stubs.js.map +1 -1
- package/dist/lib/file-loader.d.ts +6 -0
- package/dist/lib/file-loader.d.ts.map +1 -1
- package/dist/lib/file-loader.js +17 -0
- package/dist/lib/file-loader.js.map +1 -1
- package/dist/lib/ops-manifest.d.ts +76 -0
- package/dist/lib/ops-manifest.d.ts.map +1 -0
- package/dist/lib/ops-manifest.js +94 -0
- package/dist/lib/ops-manifest.js.map +1 -0
- package/dist/lib/release-and-pin.d.ts +34 -0
- package/dist/lib/release-and-pin.d.ts.map +1 -0
- package/dist/lib/release-and-pin.js +71 -0
- package/dist/lib/release-and-pin.js.map +1 -0
- package/dist/lib/shell.d.ts +4 -1
- package/dist/lib/shell.d.ts.map +1 -1
- package/dist/lib/shell.js +8 -3
- package/dist/lib/shell.js.map +1 -1
- package/dist/skill/docs/api/actions.md +2 -0
- package/dist/skill/docs/api/batch-operations.md +18 -4
- package/dist/skill/docs/api/crud.md +62 -0
- package/dist/skill/docs/api/errors.md +17 -2
- package/dist/skill/docs/configure/auth.md +49 -2
- package/dist/skill/docs/configure/bindings.md +15 -0
- package/dist/skill/docs/configure/domains.md +4 -0
- package/dist/skill/docs/configure/index.md +29 -11
- package/dist/skill/docs/configure/tenancy.md +117 -0
- package/dist/skill/docs/define/access.md +19 -0
- package/dist/skill/docs/define/actions/access.md +76 -0
- package/dist/skill/docs/define/actions/defining.md +156 -1
- package/dist/skill/docs/define/actions/scoped-db.md +236 -9
- package/dist/skill/docs/define/areas.md +46 -0
- package/dist/skill/docs/define/authz-roles.md +10 -0
- package/dist/skill/docs/define/diagnostics.md +263 -0
- package/dist/skill/docs/define/encryption.md +32 -0
- package/dist/skill/docs/define/guards.md +13 -0
- package/dist/skill/docs/define/masking.md +77 -3
- package/dist/skill/docs/define/rate-limit.md +3 -3
- package/dist/skill/docs/define/schema.md +148 -7
- package/dist/skill/docs/define/scopes.md +79 -0
- package/dist/skill/docs/define/transitions.md +39 -0
- package/dist/skill/docs/define/views.md +77 -3
- package/dist/skill/docs/platform/api-contract/index.md +4 -0
- package/dist/skill/docs/platform/auth/jwt-optimization.md +2 -0
- package/dist/skill/docs/platform/auth/plugins/aws-ses.md +4 -3
- package/dist/skill/docs/platform/auth/using-auth.md +6 -0
- package/dist/skill/docs/platform/database/d1.md +47 -0
- package/dist/skill/docs/platform/database/data-migrations.md +109 -0
- package/dist/skill/docs/platform/database/read-replication.md +142 -7
- package/dist/skill/docs/platform/payments/one-off-checkout.md +6 -1
- package/dist/skill/docs/platform/push/index.md +2 -0
- package/dist/skill/docs/platform/realtime/partyserver-rooms.md +95 -9
- package/dist/skill/docs/platform/storage/using-r2.md +135 -19
- package/dist/skill/docs/start/deploy.md +38 -0
- package/dist/skill/docs/tooling/cli.md +120 -0
- package/dist/skill/docs/tooling/cloud-compiler/troubleshooting.md +13 -13
- package/dist/skill/docs/tooling/output.md +70 -2
- package/package.json +1 -1
- package/src/skill/docs/api/actions.md +2 -0
- package/src/skill/docs/api/batch-operations.md +18 -4
- package/src/skill/docs/api/crud.md +62 -0
- package/src/skill/docs/api/errors.md +17 -2
- package/src/skill/docs/configure/auth.md +49 -2
- package/src/skill/docs/configure/bindings.md +15 -0
- package/src/skill/docs/configure/domains.md +4 -0
- package/src/skill/docs/configure/index.md +29 -11
- package/src/skill/docs/configure/tenancy.md +117 -0
- package/src/skill/docs/define/access.md +19 -0
- package/src/skill/docs/define/actions/access.md +76 -0
- package/src/skill/docs/define/actions/defining.md +156 -1
- package/src/skill/docs/define/actions/scoped-db.md +236 -9
- package/src/skill/docs/define/areas.md +46 -0
- package/src/skill/docs/define/authz-roles.md +10 -0
- package/src/skill/docs/define/diagnostics.md +263 -0
- package/src/skill/docs/define/encryption.md +32 -0
- package/src/skill/docs/define/guards.md +13 -0
- package/src/skill/docs/define/masking.md +77 -3
- package/src/skill/docs/define/rate-limit.md +3 -3
- package/src/skill/docs/define/schema.md +148 -7
- package/src/skill/docs/define/scopes.md +79 -0
- package/src/skill/docs/define/transitions.md +39 -0
- package/src/skill/docs/define/views.md +77 -3
- package/src/skill/docs/platform/api-contract/index.md +4 -0
- package/src/skill/docs/platform/auth/jwt-optimization.md +2 -0
- package/src/skill/docs/platform/auth/plugins/aws-ses.md +4 -3
- package/src/skill/docs/platform/auth/using-auth.md +6 -0
- package/src/skill/docs/platform/database/d1.md +47 -0
- package/src/skill/docs/platform/database/data-migrations.md +109 -0
- package/src/skill/docs/platform/database/read-replication.md +142 -7
- package/src/skill/docs/platform/payments/one-off-checkout.md +6 -1
- package/src/skill/docs/platform/push/index.md +2 -0
- package/src/skill/docs/platform/realtime/partyserver-rooms.md +95 -9
- package/src/skill/docs/platform/storage/using-r2.md +135 -19
- package/src/skill/docs/start/deploy.md +38 -0
- package/src/skill/docs/tooling/cli.md +120 -0
- package/src/skill/docs/tooling/cloud-compiler/troubleshooting.md +13 -13
- package/src/skill/docs/tooling/output.md +70 -2
|
@@ -83,7 +83,7 @@ server-minted ids as usual.
|
|
|
83
83
|
- **201** — All records created successfully
|
|
84
84
|
- **207** — Partial success (some errors, some successes)
|
|
85
85
|
|
|
86
|
-
`POST /batch` uses
|
|
86
|
+
`POST /batch` uses one bulk `INSERT`, so `meta.transactional` is `true` on every provider — the database guarantees the insert is atomic regardless of the `failFast` flag. On D1 a wide batch is sliced to stay under the [bind limit](#database-bind-limits) and the slices run in one `db.batch()`, which D1 commits atomically.
|
|
87
87
|
|
|
88
88
|
Fields applied automatically to each record:
|
|
89
89
|
- ID generation (UUID, prefixed, etc.)
|
|
@@ -208,7 +208,7 @@ Note: Batch delete uses an `ids` array (not `records`).
|
|
|
208
208
|
}
|
|
209
209
|
```
|
|
210
210
|
|
|
211
|
-
`DELETE /batch` issues
|
|
211
|
+
`DELETE /batch` issues one bulk `UPDATE … WHERE id IN (...)` (soft delete) or `DELETE … WHERE id IN (...)` (hard delete), so `meta.transactional` is `true` on every provider regardless of `failFast`. On D1 the id list is sliced under the [bind limit](#database-bind-limits) and the slices run in one atomic `db.batch()`.
|
|
212
212
|
|
|
213
213
|
**Hard delete**: Returns objects with only the `id` field (record data is deleted).
|
|
214
214
|
|
|
@@ -318,8 +318,8 @@ transport with Neon's hyperdrive mode.
|
|
|
318
318
|
| `PATCH /batch` (update) | cloudflare-d1, neon over http (Cloudflare default) | `true` | `false` | Fail-fast loop without rollback — the driver has no `db.transaction`. Records before the failure stay committed. |
|
|
319
319
|
| `PUT /batch` (upsert) | tx-supporting (postgres, neon over websocket/hyperdrive, planetscale-postgres) | `true` | `true` | Bulk insert + per-record update share one transaction. Any failure rolls back both. |
|
|
320
320
|
| `PUT /batch` (upsert) | cloudflare-d1, neon over http (Cloudflare default) | `true` | `false` | Bulk insert commits; per-record update loop is fail-fast without rollback. |
|
|
321
|
-
| `POST /batch` (create) | (any) | (any) | `true` |
|
|
322
|
-
| `DELETE /batch` | (any) | (any) | `true` |
|
|
321
|
+
| `POST /batch` (create) | (any) | (any) | `true` | One bulk `INSERT` — atomic at the DB level. On D1, slices under the bind limit commit together via `db.batch()`. |
|
|
322
|
+
| `DELETE /batch` | (any) | (any) | `true` | One bulk `UPDATE` (soft) or `DELETE` (hard) — atomic at the DB level. On D1, slices under the bind limit commit together via `db.batch()`. |
|
|
323
323
|
| [Changeset](/define/changesets) (`application/vnd.quickback.changeset+json`) | tx-supporting (postgres, neon over websocket/hyperdrive, planetscale-postgres) | n/a | `true` | Root op + every child op share one transaction; any op failure rolls back the whole changeset. |
|
|
324
324
|
| [Changeset](/define/changesets) | cloudflare-d1, neon over http (Cloudflare default) | n/a | `false` | Deterministic parent-first fail-fast — the first op failure stops the changeset; already-applied ops stay committed (a consistent, independently-authorized prefix). |
|
|
325
325
|
|
|
@@ -370,6 +370,20 @@ The default maximum batch size is **100 records**. Requests exceeding the limit
|
|
|
370
370
|
}
|
|
371
371
|
```
|
|
372
372
|
|
|
373
|
+
### Database bind limits
|
|
374
|
+
|
|
375
|
+
Every batch route builds statements whose size grows with the request — `WHERE id IN (...)` over the submitted ids, or a multi-row `INSERT` binding every column of every row. Drivers cap the bound parameters a single statement may carry:
|
|
376
|
+
|
|
377
|
+
| Provider | Bound parameters per statement |
|
|
378
|
+
|----------|-------------------------------|
|
|
379
|
+
| `cloudflare-d1` (and local Miniflare/workerd) | 100 |
|
|
380
|
+
| `neon`, `planetscale-postgres` | 65535 |
|
|
381
|
+
| other SQLite drivers | 32766 |
|
|
382
|
+
|
|
383
|
+
The generated handlers never exceed the cap. Id lists and insert rows are sliced to fit (ids in slices of 80, leaving room for the firewall's scope binds; insert rows by `floor(80 / columns)`), and on drivers that offer `db.batch()` — D1 included — the slices run in one atomic batch, so `meta.transactional` stays honest. A full `maxBatchSize` request on D1 therefore succeeds for any table width; on Postgres a 100-record batch is always a single statement. The runtime lives in the generated `src/lib/sql-binds.ts` (`selectInChunks`, `insertInChunks`), and the budget constant `MAX_SQL_BINDS` is the provider's cap — reuse it in hand-written actions that take id lists.
|
|
384
|
+
|
|
385
|
+
The body must carry its array under the documented key. A `POST`/`PATCH`/`PUT /batch` without a `records` array, or a `DELETE /batch` without `ids`, is rejected with 400 `VALIDATION_INVALID_INPUT` naming the missing field — never a 200 that wrote nothing.
|
|
386
|
+
|
|
373
387
|
## Configuration
|
|
374
388
|
|
|
375
389
|
Batch operations inherit access control from their corresponding write operation. You can override per-batch settings:
|
|
@@ -289,6 +289,67 @@ where the id is **required** on `POST /`, `POST /batch` and a changeset
|
|
|
289
289
|
the id. `PUT /:id` and `PATCH` are unchanged — the id still comes from the
|
|
290
290
|
URL, never the body.
|
|
291
291
|
|
|
292
|
+
### Row-token idempotency
|
|
293
|
+
|
|
294
|
+
An offline or flaky client retries creates. `allowClientIds` makes a retry
|
|
295
|
+
fail loudly (`409`); a **row token** makes it succeed with the row the first
|
|
296
|
+
attempt wrote. Declare the token column on the table:
|
|
297
|
+
|
|
298
|
+
{/* doc-compile: skip — needs `allowClientIds: true` on the database config, which the docs gate's fixed harness config does not set. Compiled by tests/output-matrix/fixtures/race-safe-writes. */}
|
|
299
|
+
```typescript
|
|
300
|
+
// features/rsvps/rsvps.ts
|
|
301
|
+
import { feature, q } from "@quickback/compiler";
|
|
302
|
+
|
|
303
|
+
export default feature("rsvps", {
|
|
304
|
+
columns: {
|
|
305
|
+
id: q.id(),
|
|
306
|
+
clientMutationId: q.text({ maxLength: 64 }).optional().unique(),
|
|
307
|
+
eventId: q.text().required(),
|
|
308
|
+
guestName: q.text().required(),
|
|
309
|
+
organizationId: q.scope("organization"),
|
|
310
|
+
...q.audit(),
|
|
311
|
+
...q.softDelete(),
|
|
312
|
+
},
|
|
313
|
+
idempotency: { rowToken: "clientMutationId", clientId: { column: "id", pattern: "uuid" } },
|
|
314
|
+
read: { access: { roles: ["member"] } },
|
|
315
|
+
create: { access: { roles: ["member"] } },
|
|
316
|
+
});
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
On `POST /` and `POST /batch`:
|
|
320
|
+
|
|
321
|
+
- A create whose `clientMutationId` is already stored on a row the caller can
|
|
322
|
+
see **replays that row**: `200`, header `Idempotent-Replayed: true`, the
|
|
323
|
+
stored (masked) record as the body. Nothing runs — no insert, no trigger
|
|
324
|
+
hooks, no realtime frame, no embedding job, no after-commit effect.
|
|
325
|
+
- A create that races its own retry is arbitrated by the database: the unique
|
|
326
|
+
constraint on the token (or the primary key, when the client mints the id)
|
|
327
|
+
refuses the second INSERT, and that request replays the winner instead of
|
|
328
|
+
answering `409`.
|
|
329
|
+
- The same client id under a **different** token, or the same token with a
|
|
330
|
+
different id, is `409 IDEMPOTENCY_ROW_CONFLICT`.
|
|
331
|
+
- `POST /batch` returns replayed rows in `success` next to the created ones,
|
|
332
|
+
and inserts only the new ones; a token repeated inside one batch is a
|
|
333
|
+
per-record `400 IDEMPOTENCY_TOKEN_REPEATED`.
|
|
334
|
+
- A create with no token is an ordinary create.
|
|
335
|
+
|
|
336
|
+
Compile-time rules (fail closed): the token column must exist, be a text
|
|
337
|
+
column the client may create (in `guards.createable` when guards are
|
|
338
|
+
declared), and be covered by a non-partial unique constraint — unless
|
|
339
|
+
`clientId` is declared, in which case the primary key arbitrates and the
|
|
340
|
+
client must resend the same id on retry. `clientId.column` must be the
|
|
341
|
+
primary key, `clientId.pattern` must name the project's `generateId` strategy
|
|
342
|
+
(`uuid`, `cuid` / `cuid2`, `nanoid`, `prefixed`, `short`), and the database
|
|
343
|
+
config must accept client ids (`allowClientIds: true`).
|
|
344
|
+
|
|
345
|
+
**Row token vs `Idempotency-Key`.** The
|
|
346
|
+
[`Idempotency-Key` header](/platform/api-contract#idempotency-key) is per
|
|
347
|
+
**request**: it caches one response for 24 hours, bound to the principal that
|
|
348
|
+
sent it, on any write endpoint. A row token is per **row**: it is stored in
|
|
349
|
+
the table, never expires, and replays across sessions, devices and
|
|
350
|
+
principals that can read the row. Use the header for "don't do this request
|
|
351
|
+
twice"; use a row token for "this client-side record exists exactly once".
|
|
352
|
+
|
|
292
353
|
### Response
|
|
293
354
|
|
|
294
355
|
`201 Created`. The body is the **bare created record** — there is no `data`
|
|
@@ -314,6 +375,7 @@ wrapper:
|
|
|
314
375
|
| `400` | Invalid field or missing required field |
|
|
315
376
|
| `403` | User lacks permission to create records |
|
|
316
377
|
| `409` | Client-supplied `id` (with `allowClientIds: true`) already exists |
|
|
378
|
+
| `409` | `IDEMPOTENCY_ROW_CONFLICT` — a [row token](#row-token-idempotency) or client id already belongs to a different record |
|
|
317
379
|
|
|
318
380
|
## Update Record
|
|
319
381
|
|
|
@@ -14,9 +14,9 @@ The generated API returns structured error responses with consistent fields acro
|
|
|
14
14
|
| `403` | Forbidden | Access denied (wrong role, condition failed) or firewall blocked it |
|
|
15
15
|
| `404` | Not Found | Firewall blocked the record on a resource that set `firewallErrorMode: 'hide'` (or the route doesn't exist) |
|
|
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
|
-
| `409` | Conflict | Unique constraint hit,
|
|
17
|
+
| `409` | Conflict | Unique constraint hit, a duplicate [`Idempotency-Key`](/platform/api-contract#idempotency-key) still in flight, a [row token](/api/crud#row-token-idempotency) that belongs to a different record (`IDEMPOTENCY_ROW_CONFLICT`), or a transition that lost a race (`ACCESS_TRANSITION_LOST`, see [Transitions](/define/transitions#concurrency-the-guard-is-in-the-update)) |
|
|
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, or a stored encrypted value will not decrypt (`ENCRYPTION_UNREADABLE`) |
|
|
19
|
+
| `422` | Unprocessable | `Idempotency-Key` reused with a different request or principal, or a stored encrypted value will not decrypt (`ENCRYPTION_UNREADABLE`), or a write carried a platform-managed JSON key (`JSON_KEY_RESTRICTED`) |
|
|
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. Also `DB_WRITE_OUTCOME_UNKNOWN`: a write passed the configured [`queryTimeoutMs`](/configure/providers#database-options) and may still have committed |
|
|
@@ -198,6 +198,8 @@ Access violations return **403 Forbidden** when the user's role doesn't match th
|
|
|
198
198
|
| `ACCESS_OWNERSHIP_REQUIRED` | User must own the record |
|
|
199
199
|
| `ACCESS_NO_ORG` | No active organization set |
|
|
200
200
|
| `ACCESS_KEY_SCOPE_REQUIRED` | A [scoped API key](/platform/auth/api-keys#scopes) does not cover this route and method. `details.required` lists the scope that would admit it (empty outside the API base, which scoped keys never reach); `details.current` is the key's scopes |
|
|
201
|
+
| `ENTITLEMENT_REQUIRED` | An action's [`requires:`](/define/actions/defining#json-key-writes-and-requires) JSON key did not hold for the record. `details: { column, key }`. Checked before `execute` |
|
|
202
|
+
| `ACCESS_NO_ARM` | The action declares [`access.arms`](/define/actions/access#arms-conditioned-on-input-accessarms) and no arm's `when` matches the validated input |
|
|
201
203
|
|
|
202
204
|
### Guards (400)
|
|
203
205
|
|
|
@@ -236,6 +238,19 @@ guard failure is reported per record (207, or `BATCH_FAIL_FAST_STOPPED` under
|
|
|
236
238
|
| `GUARD_FIELD_IMMUTABLE` | Field cannot be modified after creation |
|
|
237
239
|
| `GUARD_SYSTEM_MANAGED` | System field (createdAt, modifiedAt, etc.) |
|
|
238
240
|
|
|
241
|
+
### Platform-managed JSON keys (422)
|
|
242
|
+
|
|
243
|
+
A body that sets a `platform` key of a [`q.json(schema, { keys })`](/define/schema#per-key-write-authority-keys) column answers **422 `JSON_KEY_RESTRICTED`** (`layer: "guards"`). `details.fields` names each key as `<column>.<key>`. The response is the same on POST, PATCH, PUT, the batch routes (the whole request is refused), and changeset ops. An action whose write changes a platform key without a grant gets the same code and status, with `details: { table, column, keys }`.
|
|
244
|
+
|
|
245
|
+
```json
|
|
246
|
+
{
|
|
247
|
+
"status": 422,
|
|
248
|
+
"code": "JSON_KEY_RESTRICTED",
|
|
249
|
+
"layer": "guards",
|
|
250
|
+
"details": { "fields": { "settings.beta": "is platform-managed — not writable through settings on this route" } }
|
|
251
|
+
}
|
|
252
|
+
```
|
|
253
|
+
|
|
239
254
|
### Malformed record id (400)
|
|
240
255
|
|
|
241
256
|
Record routes (`GET`/`PATCH`/`PUT`/`DELETE /:id`, the changeset `PATCH`, and
|
|
@@ -163,7 +163,7 @@ A token is rejected when its mint timestamp (`iat`/`iatMs`, or the scope claim's
|
|
|
163
163
|
| Key | Revokes | Written automatically on |
|
|
164
164
|
|---|---|---|
|
|
165
165
|
| `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 |
|
|
166
|
-
| `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 |
|
|
166
|
+
| `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); the **target** (`body.userId`) of the admin plugin's `/admin/set-role`, `/admin/remove-user`, `/admin/update-user`, and `/admin/revoke-user-sessions`; and every [`ctx.auth`](/define/actions/scoped-db#ctxauth--better-auth-users-and-members-org-bound) write. Call `revokeUserTokens` for custom flows |
|
|
167
167
|
| `qbrev:member:<userId>:<orgId>` | the user's org-membership claims | member removal / role change (Better Auth `organizationHooks`) |
|
|
168
168
|
| `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) |
|
|
169
169
|
|
|
@@ -177,7 +177,7 @@ Semantics worth knowing:
|
|
|
177
177
|
- **Fails closed:** a missing binding, a failed read, or a corrupt entry means the token's revocation state is *unknown* — and an unknown bearer is not authenticated. The caller gets `503 AUTH_REVOCATION_UNAVAILABLE` (RFC 9457, retryable). Recovery is a **separate cookie-only request**: a request carrying `Authorization` has its cookie stripped before session auth, so within that one request there is nothing left to fall back to. Reads are never silently skipped, because the outage that hides a revocation is exactly the moment this check exists for.
|
|
178
178
|
- **Availability coupling:** the flip side of the above. Bearer-token auth now depends on KV being readable. Alert on `AUTH_REVOCATION_UNAVAILABLE`; a sustained rate means the binding is missing on some deployment target, or KV is degraded. Every named environment must declare `bindings.kv` — the compiler rejects a target that doesn't.
|
|
179
179
|
- **Eventual consistency:** KV propagates cross-PoP in ~60s. "Immediate" means seconds at the writing location, bounded-seconds globally — still far inside the 15-minute carry-forward cap that bounds revocation without this check.
|
|
180
|
-
- **Writes stay best-effort:** the *stamps* are written after the authorization change has already committed (the ban row, the removed membership, the deleted conferring row). A failed stamp does not fail that write — the DB state is the durable cut. It is only the *read* side that fails closed.
|
|
180
|
+
- **Writes stay best-effort:** the *stamps* are written after the authorization change has already committed (the ban row, the removed membership, the deleted conferring row). A failed stamp does not fail that write — the DB state is the durable cut. It is only the *read* side that fails closed. The exception is [`ctx.auth`](/define/actions/scoped-db#ctxauth--better-auth-users-and-members-org-bound): your action asked for the change, so a stamp that cannot be written fails the action with `503 AUTH_REVOCATION_UNAVAILABLE` rather than letting it report success with live tokens.
|
|
181
181
|
- **Coverage gap:** batch *hard* deletes don't return rows through the chokepoint; call `revokeScopeTokens` explicitly if you bulk-hard-delete conferring rows.
|
|
182
182
|
|
|
183
183
|
## Defaults when the JWT surface is enabled
|
|
@@ -203,6 +203,53 @@ missing field falls back to its hardcoded value:
|
|
|
203
203
|
|
|
204
204
|
`auth: { organizationRoster: { access: { roles: ['member'] } } }` emits `GET /auth/v1/organization/roster`, the active organization's members (`id`, `name`, `email`, `image`, `role`). Better Auth's `list-members` needs a session; this works on the JWT bearer. See [Listing organization members](/platform/auth/using-auth#listing-organization-members).
|
|
205
205
|
|
|
206
|
+
## `auth.claims` — link rows to the account that verifies their email
|
|
207
|
+
|
|
208
|
+
A row addressed to someone by email before they have an account — a guest list, an invitation, a pre-registered attendee — should belong to that account once it exists. Declare the link and the compiler emits it as a Better Auth database hook:
|
|
209
|
+
|
|
210
|
+
```ts title="quickback.config.ts"
|
|
211
|
+
auth: {
|
|
212
|
+
claims: [
|
|
213
|
+
{ table: 'guests', emailColumn: 'emailAtInvite', userColumn: 'linkedUserId', when: 'emailVerified' },
|
|
214
|
+
],
|
|
215
|
+
},
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
On the named event the hook runs one UPDATE per claim: rows of `table` whose `emailColumn` equals the account's email (case-insensitive) and whose `userColumn` is still `NULL` get the user id. Soft-deleted rows are never linked.
|
|
219
|
+
|
|
220
|
+
| `when` | Fires on |
|
|
221
|
+
|---|---|
|
|
222
|
+
| `emailVerified` | the update that verifies the account's email, and the creation of an account that is already verified (social, email-OTP, or magic-link sign-in) |
|
|
223
|
+
| `userCreated` | account creation |
|
|
224
|
+
| `signIn` | every new session |
|
|
225
|
+
|
|
226
|
+
**Only a verified email links**, whatever `when` says. A claim keyed on an unverified address would let anyone who typed the victim's email at sign-up take their rows, so `userCreated` and `signIn` skip an unverified account. A failed link is logged and never blocks sign-up or sign-in.
|
|
227
|
+
|
|
228
|
+
The compiler checks the claim against the table and refuses to compile when the table is not a q-authored feature table with a `q.id()` key, when either column is missing, when `emailColumn` is encrypted (ciphertext cannot be matched), or when `userColumn` is `NOT NULL`, a scope or stamp column, or encrypted. Claims run on the Cloudflare runtime with Better Auth, over D1 or Postgres (the service lane).
|
|
229
|
+
|
|
230
|
+
The link is a compiler-owned write: it stamps `modifiedBy: 'system:auth-claims'` and fires no realtime event, webhook, or trigger. It is generated code, so it needs none of your project code (auth hooks cannot import it).
|
|
231
|
+
|
|
232
|
+
### Backfill — rows that predate the account
|
|
233
|
+
|
|
234
|
+
The hook only sees accounts as they verify. For rows created after their account already existed, call `ctx.auth.claims.backfill()` from an action:
|
|
235
|
+
|
|
236
|
+
```ts title="features/guests/actions/backfillClaims.ts"
|
|
237
|
+
import { z } from "zod";
|
|
238
|
+
import { defineAction } from "../.quickback/define-action";
|
|
239
|
+
|
|
240
|
+
export default defineAction({
|
|
241
|
+
description: "Link guest rows to verified accounts.",
|
|
242
|
+
path: "/claims/backfill",
|
|
243
|
+
input: z.object({ dryRun: z.boolean().optional(), cursor: z.string().nullable().optional() }),
|
|
244
|
+
access: { roles: ["owner", "admin"] },
|
|
245
|
+
async execute({ ctx, input }) {
|
|
246
|
+
return ctx.auth.claims.backfill({ dryRun: input.dryRun, cursor: input.cursor ?? null });
|
|
247
|
+
},
|
|
248
|
+
});
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
It returns `{ dryRun, results: [{ table, userColumn, scanned, matched, linked }], cursor }`. Each call scans up to `limit` rows (default 500, at most 5000); call again with the returned `cursor` until it is `null`. `dryRun: true` reports matches without writing. An org-bound caller scans only its active organization's rows (and nothing from a claim table without an organization column); an operator — a caller whose platform role is one of the admin plugin's `adminRoles` — scans every row. Matches are looked up through Better Auth's adapter and must be verified accounts.
|
|
252
|
+
|
|
206
253
|
## `auth.loginUrl` — external sign-in for consumer Workers
|
|
207
254
|
|
|
208
255
|
When a Quickback Worker doesn't host its own Account SPA — e.g. an internal-app mesh where one Worker on the parent domain owns identity (`auth.example.com`) and other Workers share cookies — the compiler-emitted CMS access gate needs to redirect unauthenticated visitors to the central sign-in surface, not the local `/account/login` (which doesn't exist there).
|
|
@@ -137,6 +137,7 @@ Each in-worker DO entry accepts:
|
|
|
137
137
|
| `migrationTag` | `qb-do-${className}` | Wrangler migration tag. Stable across regenerations — **never remove or rename a deployed tag**, or wrangler will reject the deploy. |
|
|
138
138
|
| `useSqlite` | `true` | SQLite-backed DO storage. Set to `false` for the legacy KV-backed mode. |
|
|
139
139
|
| `scriptName` | — | Cross-worker only. Mutually exclusive with `from`. |
|
|
140
|
+
| `access` | — | Per-room gate for the auto-mounted `/realtime/<binding>/<roomId>`: `{ resource }` / `{ resources, roomId }` (firewalled row lookup), `{ roomIdEquals }`, or `'public'`. The resource-backed forms take `roles` (who may connect) and `writeRoles` (who may mutate; everyone else connects read-only), independent of the table's CRUD access. See [PartyServer Rooms](/platform/realtime/partyserver-rooms#room-roles). |
|
|
140
141
|
|
|
141
142
|
Where the class file lives: in-worker DO classes go under `quickback/lib/` or `quickback/features/<feature>/lib/` so they survive every compile (the rest of `src/` is wiped). Both copy verbatim into the generated `src/` tree.
|
|
142
143
|
|
|
@@ -227,6 +228,20 @@ Set the value out-of-band — it lands in Cloudflare's encrypted secret store:
|
|
|
227
228
|
wrangler secret put WEBHOOK_SIGNING_SECRET
|
|
228
229
|
```
|
|
229
230
|
|
|
231
|
+
Every build also writes the whole contract to `reports/ops.manifest.json`:
|
|
232
|
+
your declared secrets plus the ones your providers imply (`BETTER_AUTH_SECRET`,
|
|
233
|
+
social-login credentials, R2 presign keys, `ENCRYPTION_KEK`, Neon's
|
|
234
|
+
`DATABASE_URL`), with which ones the boot guard enforces. It also writes a
|
|
235
|
+
`.dev.vars.example` template for `wrangler dev`. To compare a deployed target
|
|
236
|
+
against the contract, or to set its values from a dotenv file:
|
|
237
|
+
|
|
238
|
+
```bash
|
|
239
|
+
quickback secrets check --env production # exit 1 on missing or undeclared secrets
|
|
240
|
+
quickback secrets push --env production # from .env.production, values over stdin
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
See [Check and Push Secrets](/tooling/cli#check-and-push-secrets).
|
|
244
|
+
|
|
230
245
|
> `secrets` records a **contract**, not a value. The schema rejects any inline value key, so a real secret can never be pasted into committed config. Use [`vars`](#vars) for non-secret values that are safe to commit.
|
|
231
246
|
|
|
232
247
|
|
|
@@ -244,6 +244,10 @@ When the project generates exactly **one** hostname, `domain: "api-dev.attend.vi
|
|
|
244
244
|
|
|
245
245
|
The compile fails, naming the config path to fix, when an environment leaves a generated hostname unclaimed, claims a key the top level does not generate, or claims a hostname another target already owns.
|
|
246
246
|
|
|
247
|
+
A target that [`extends`](/platform/database/d1#inheriting-from-another-target-extends)
|
|
248
|
+
another never inherits its `domain` / `domains`. Hostnames are always claimed
|
|
249
|
+
per target, so two targets can never end up owning the same custom domain.
|
|
250
|
+
|
|
247
251
|
### The unified hostname per target
|
|
248
252
|
|
|
249
253
|
Each target names its own all-in-one host with `domains.primary` — the host where every surface coexists and `/` redirects to `/cms/`:
|
|
@@ -316,15 +316,24 @@ export default defineConfig({
|
|
|
316
316
|
|
|
317
317
|
These are merged into the generated `package.json` alongside Quickback's own dependencies. Run `npm install` after compiling to install them.
|
|
318
318
|
|
|
319
|
-
|
|
320
|
-
not install project dependencies at compile time. A hosted complete compile
|
|
321
|
-
fails if a declared dependency is missing from that image, because its
|
|
319
|
+
Hosted complete compiles run a
|
|
322
320
|
[Worker bundle check](/tooling/cloud-compiler/troubleshooting#complete-compile-wrangler-bundle-failed)
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
321
|
+
that bundles the generated Worker with these dependencies. Packages the
|
|
322
|
+
compiler image already has resolve from the image. Any other declared package
|
|
323
|
+
is installed from the public npm registry for that compile, at the range you
|
|
324
|
+
declared, before the check runs:
|
|
325
|
+
|
|
326
|
+
- Each entry must be a registry package at a semver range or dist-tag
|
|
327
|
+
(`"^4.5.0"`, `"latest"`). `file:`, `git`, URL, `npm:` alias, and
|
|
328
|
+
`workspace:` specifiers are rejected.
|
|
329
|
+
- Install scripts never run, and the compile can reach only the npm registry,
|
|
330
|
+
read-only.
|
|
331
|
+
- Peer dependencies the image already provides (React, ProseMirror, …) resolve
|
|
332
|
+
to the image's copy, so the bundle never carries two of them.
|
|
333
|
+
- If the install fails, the compile fails and names the packages. Type-only
|
|
334
|
+
`@types/*` packages are never installed and never block it.
|
|
335
|
+
|
|
336
|
+
These packages are preinstalled in the image, so they skip the install:
|
|
328
337
|
|
|
329
338
|
| Use | Packages |
|
|
330
339
|
|-----|----------|
|
|
@@ -336,9 +345,7 @@ hosted complete compiles out of the box:
|
|
|
336
345
|
| Utilities | `@paralleldrive/cuid2`, `nanoid`, `aws4fetch`, `postal-mime`, `qrcode` |
|
|
337
346
|
|
|
338
347
|
The bundle check resolves these at the image's versions — keep your declared
|
|
339
|
-
ranges compatible with them.
|
|
340
|
-
project's installed dependencies or request that the dependency be added to
|
|
341
|
-
the compiler image.
|
|
348
|
+
ranges compatible with them.
|
|
342
349
|
|
|
343
350
|
## Headless Migration Rename Hints
|
|
344
351
|
|
|
@@ -510,6 +517,17 @@ export default defineConfig({
|
|
|
510
517
|
|
|
511
518
|
If `signature.required: true` and no key is available, compilation fails with a clear error message (or warning in `failMode: "warn"`).
|
|
512
519
|
|
|
520
|
+
`failMode` also governs the [schema and config diagnostics](/define/diagnostics#schema-and-config-codes):
|
|
521
|
+
`"warn"` downgrades `SCHEMA_UNDECLARED_FK` to a warning for a migration window.
|
|
522
|
+
|
|
523
|
+
Every compile also emits `reports/access-manifest.json` — per route and Durable
|
|
524
|
+
Object gate, the roles, `userRole`, scope lanes and firewall arms (each with a
|
|
525
|
+
`tenantBound` flag), plus trusted origins per environment. Commit it and run
|
|
526
|
+
`quickback build --diff quickback/reports/access-manifest.json` in CI to fail on
|
|
527
|
+
any access widening. See [Output → Access Manifest](/tooling/output#access-manifest).
|
|
528
|
+
|
|
529
|
+
`failMode: "warn"` also downgrades the [source-analysis diagnostics](/define/diagnostics#source-codes) (`ACTION_RAW_DB_WITHOUT_UNSAFE`, `ACTION_AUTH_DB_WRITE`, `ENV_UNDECLARED`, `TEMPLATE_UNESCAPED`) from compile errors to warnings. Use it as a migration window, not a resting state.
|
|
530
|
+
|
|
513
531
|
## Hostname architecture
|
|
514
532
|
|
|
515
533
|
A modern Quickback project runs on **one Cloudflare Worker** that serves multiple URL surfaces. Everything lives under a single unified backend hostname — `config.domain`, or the first `providers.runtime.config.routes` custom domain. For larger deployments, you can opt-in to **dedicated hostnames** for specific surfaces — they're additive aliases, never replacements.
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# Tenant Purge
|
|
2
|
+
|
|
3
|
+
`tenancy.purge` gives operator actions a `ctx.tenancy.purge(organizationId, { dryRun })`
|
|
4
|
+
that erases one organization's data. You don't keep the table list. The
|
|
5
|
+
compiler derives it from the firewall, so a table added next month is covered
|
|
6
|
+
on the next compile.
|
|
7
|
+
|
|
8
|
+
```ts title="quickback/quickback.config.ts"
|
|
9
|
+
import { defineConfig, defineRuntime, defineDatabase, defineAuth, defineFileStorage } from "@quickback/compiler";
|
|
10
|
+
|
|
11
|
+
export default defineConfig({
|
|
12
|
+
name: "events-app",
|
|
13
|
+
template: "hono",
|
|
14
|
+
features: { organizations: true },
|
|
15
|
+
providers: {
|
|
16
|
+
runtime: defineRuntime("cloudflare"),
|
|
17
|
+
database: defineDatabase("cloudflare-d1"),
|
|
18
|
+
auth: defineAuth("better-auth", { plugins: { organization: true, admin: true } }),
|
|
19
|
+
fileStorage: defineFileStorage("cloudflare-r2", { bucketName: "events-app-media" }),
|
|
20
|
+
},
|
|
21
|
+
bindings: {
|
|
22
|
+
r2Buckets: [{ binding: "MEDIA", bucketName: "events-app-media" }],
|
|
23
|
+
},
|
|
24
|
+
tenancy: {
|
|
25
|
+
purge: { auth: true, storage: true },
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Add `keep` for tables a purge must leave alone — billing ledgers you are
|
|
31
|
+
required to retain, for example:
|
|
32
|
+
|
|
33
|
+
```ts no-compile
|
|
34
|
+
tenancy: {
|
|
35
|
+
purge: { auth: true, storage: true, keep: ["billing_*"] },
|
|
36
|
+
},
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
| Option | Default | Effect |
|
|
40
|
+
|---|---|---|
|
|
41
|
+
| `auth` | `false` | Also remove the organization, its members and its invitations through Better Auth's adapter (model names, not raw SQL — the same three deletes Better Auth's own `deleteOrganization` runs). Needs the organization plugin. |
|
|
42
|
+
| `storage` | `true` | Delete every R2 object a purged row's [`q.storageKey`](/define/schema#qstoragekey--r2-object-keys-the-compiler-owns) column references. |
|
|
43
|
+
| `keep` | `[]` | Table-name globs (`*`, `?`) to leave untouched. |
|
|
44
|
+
|
|
45
|
+
## Calling it
|
|
46
|
+
|
|
47
|
+
`ctx.tenancy` exists only in actions whose access **requires** a `userRole`:
|
|
48
|
+
a node with `userRole`, an `and` with such an arm, or an `or` whose every arm
|
|
49
|
+
has one. Reading `ctx.tenancy` anywhere else fails the compile
|
|
50
|
+
(`TENANCY_ACCESS`) and is typed `never`.
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
// quickback/features/tenants/actions/purgeTenant.ts
|
|
54
|
+
import { z } from "zod";
|
|
55
|
+
import { defineAction } from "../.quickback/define-action";
|
|
56
|
+
|
|
57
|
+
export default defineAction({
|
|
58
|
+
description: "Purge one organization's data.",
|
|
59
|
+
path: "/tenants/purge",
|
|
60
|
+
method: "POST",
|
|
61
|
+
input: z.object({ organizationId: z.string(), dryRun: z.boolean() }),
|
|
62
|
+
access: { userRole: ["sysadmin"] },
|
|
63
|
+
async execute({ ctx, input }) {
|
|
64
|
+
return ctx.tenancy.purge(input.organizationId, { dryRun: input.dryRun });
|
|
65
|
+
},
|
|
66
|
+
});
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`dryRun` is required. Pass `true` to count and `false` to delete. The result:
|
|
70
|
+
|
|
71
|
+
```json
|
|
72
|
+
{
|
|
73
|
+
"organizationId": "org_abc",
|
|
74
|
+
"dryRun": true,
|
|
75
|
+
"tables": { "media": 12, "events": 3 },
|
|
76
|
+
"objects": 12,
|
|
77
|
+
"refusedObjects": 0,
|
|
78
|
+
"kept": ["billing_accounts"],
|
|
79
|
+
"auth": { "organization": 1, "members": 4, "invitations": 0 }
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## What it deletes, in order
|
|
84
|
+
|
|
85
|
+
1. **Objects.** For each purged table with a storage key, it collects the
|
|
86
|
+
org's keys and deletes them through the column's R2 binding. A key that is
|
|
87
|
+
not under its own row's prefix is counted in `refusedObjects` and never
|
|
88
|
+
deleted, so a tampered row cannot make the purge delete another tenant's
|
|
89
|
+
object. Objects go first so that a failed delete leaves the rows in place
|
|
90
|
+
for a retry.
|
|
91
|
+
2. **Rows.** It deletes the organization's rows from every table whose
|
|
92
|
+
firewall carries a conjunctive organization arm (`q.scope("organization")`,
|
|
93
|
+
or `{ field, equals: 'ctx.activeOrgId' }`). This includes soft-deleted rows.
|
|
94
|
+
Tables are ordered from their foreign keys, so each child is deleted before
|
|
95
|
+
the table it references.
|
|
96
|
+
3. **Better Auth** (`auth: true`): members, invitations, then the
|
|
97
|
+
organization.
|
|
98
|
+
|
|
99
|
+
The purge does not touch tables outside that set. That covers owner-scoped
|
|
100
|
+
tables, `exception` tables, tables reached only through a non-organization
|
|
101
|
+
scope, the audit and webhook databases, and the managed `FILES_DB`. Give a
|
|
102
|
+
table an organization column if a tenant's purge should cover it.
|
|
103
|
+
|
|
104
|
+
## What the compiler refuses
|
|
105
|
+
|
|
106
|
+
| Code | Cause |
|
|
107
|
+
|---|---|
|
|
108
|
+
| `TENANCY_PURGE_KEEP_UNMATCHED` | A `keep` glob matches no organization-firewalled table (usually a typo). |
|
|
109
|
+
| `TENANCY_PURGE_EXTERNAL_FK` | A table the purge leaves behind (kept, or with no organization firewall) references a purged table without `onDelete: 'cascade'` or `'set null'`. Deleting the parent would violate the key. |
|
|
110
|
+
| `TENANCY_PURGE_KEEP_CASCADE` | A kept table references a purged one with `onDelete: 'cascade'`, so the purge would empty it anyway. |
|
|
111
|
+
| `TENANCY_PURGE_CYCLE` | Foreign keys among purged tables form a cycle. There is no order to delete them in. |
|
|
112
|
+
| `TENANCY_PURGE_ORG_COLUMNS` | A table is firewalled by two different organization columns. |
|
|
113
|
+
| `TENANCY_PURGE_AUTH` | `auth: true` without the Better Auth organization plugin. |
|
|
114
|
+
| `TENANCY_PURGE_PROVIDER` | The database is not `cloudflare-d1`. On Postgres the request handle is RLS-scoped to the caller, so a purge would see none of the target tenant's rows. Postgres support is not built yet. |
|
|
115
|
+
|
|
116
|
+
The purge writes no security-audit row of its own. Log the call from your
|
|
117
|
+
action if you need one.
|
|
@@ -200,6 +200,13 @@ delete: { access: { userRole: ['appmanager'] } },
|
|
|
200
200
|
|
|
201
201
|
When `roles` and `userRole` both appear in a single `Access` node, they're combined with AND — the user must satisfy both. Use `or:` to express "one or the other".
|
|
202
202
|
|
|
203
|
+
A `userRole` operator acting on **one** tenant's data — not every tenant's —
|
|
204
|
+
uses the [operator lane](/define/actions/scoped-db#operator-lane-operator):
|
|
205
|
+
`access: { userRole: ['sysadmin'] }` plus `operator: { target: { table, by } }`.
|
|
206
|
+
The action's `db` is scoped to the target's organization and every call is
|
|
207
|
+
audited against that tenant. `operator:` is only legal on a `userRole`-only
|
|
208
|
+
access lane.
|
|
209
|
+
|
|
203
210
|
`userRole` doesn't expand with the `+` hierarchy suffix — user-table roles are flat (typically just `"user"`, `"appmanager"`, and `"sysadmin"`). If you've added custom user-table roles via Better Auth, list them explicitly.
|
|
204
211
|
|
|
205
212
|
### Pseudo-roles
|
|
@@ -459,6 +466,11 @@ the access layer); set
|
|
|
459
466
|
[`firewallErrorMode: 'hide'`](/define/firewall) to return an
|
|
460
467
|
opaque 404 instead.
|
|
461
468
|
|
|
469
|
+
Actions add one step: an action declaring
|
|
470
|
+
[`access.arms`](/define/actions/access#arms-conditioned-on-input-accessarms)
|
|
471
|
+
is checked against the union of its arms in steps 2–4, then — after input
|
|
472
|
+
validation — against the one arm its validated input selects.
|
|
473
|
+
|
|
462
474
|
Function-form access (`access: async (ctx, record) => ...`) is opaque to
|
|
463
475
|
the pre-record phase and always passes there; it's fully evaluated post-record.
|
|
464
476
|
It is accepted on `create` / `update` / `delete`, where the generated route
|
|
@@ -530,6 +542,13 @@ access: {
|
|
|
530
542
|
| `$ctx.user.email` | `string` | User's email address |
|
|
531
543
|
| `$ctx.{property}` | `any` | Any custom context property |
|
|
532
544
|
|
|
545
|
+
Inside an action's `execute`, `ctx` also carries
|
|
546
|
+
[`ctx.is(name)`](/define/actions/access#asking-a-named-role-in-the-body-ctxis)
|
|
547
|
+
(when `authz.roles` is declared),
|
|
548
|
+
[`ctx.self`](/define/scopes#ctxself--the-callers-own-row) (when a scoped role
|
|
549
|
+
declares `self`), and — under a namespace — `ctx.lane` / `ctx.lanes`
|
|
550
|
+
([lane recording](/define/areas#recording-every-matched-lane--lanes-all)).
|
|
551
|
+
|
|
533
552
|
## Function-Based Access
|
|
534
553
|
|
|
535
554
|
For complex access logic that can't be expressed declaratively, use a function:
|
|
@@ -94,6 +94,82 @@ access: {
|
|
|
94
94
|
}
|
|
95
95
|
```
|
|
96
96
|
|
|
97
|
+
### Arms conditioned on input (`access.arms`)
|
|
98
|
+
|
|
99
|
+
Some actions admit different callers depending on *what* they ask for: anyone
|
|
100
|
+
on the site may post a normal notice, but an urgent one is staff-only. Declaring
|
|
101
|
+
the wide rule and narrowing inside `execute` lets the two drift. Declare the
|
|
102
|
+
arms instead:
|
|
103
|
+
|
|
104
|
+
{/* doc-compile: skip — `siteStaff` is an authz.roles name declared in quickback.config.ts; the isolated fence cannot declare it. The whole project compiles in tests/output-matrix/fixtures/refs-access-self. */}
|
|
105
|
+
```typescript
|
|
106
|
+
export default defineAction({
|
|
107
|
+
description: "Post a notice; urgent notices are staff-only.",
|
|
108
|
+
path: "/site/:siteId/notices",
|
|
109
|
+
input: z.object({ urgency: z.enum(["normal", "urgent"]), body: z.string().max(2000) }),
|
|
110
|
+
access: {
|
|
111
|
+
arms: [
|
|
112
|
+
{ when: { "input.urgency": "urgent" }, roles: ["siteStaff"] },
|
|
113
|
+
{ roles: ["AUTHENTICATED"] }, // default arm — no `when`, last
|
|
114
|
+
],
|
|
115
|
+
},
|
|
116
|
+
async execute({ input }) { /* … */ },
|
|
117
|
+
});
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
- **The first arm whose `when` holds decides.** No other arm can admit the
|
|
121
|
+
request, so an urgent notice from a non-staff caller is a 403 even though the
|
|
122
|
+
default arm would have let them post a normal one. An input that matches no
|
|
123
|
+
arm (every arm has a `when` and none holds) is **403 `ACCESS_NO_ARM`**.
|
|
124
|
+
- **`when` reads validated input only.** Keys are `'input.<field>'` naming a
|
|
125
|
+
field of the action's inline `z.object` (an unknown field is a compile
|
|
126
|
+
error). A value is a literal (equality; `null` = absent), or one of
|
|
127
|
+
`{ equals }`, `{ notEquals }`, `{ in: [...] }`, `{ notIn: [...] }`. Several
|
|
128
|
+
keys must all hold.
|
|
129
|
+
- **Each arm body is an ordinary access rule** — `roles` (named rules,
|
|
130
|
+
pseudo-roles, `scope:<kind>:<role>`), `userRole`, `or`/`and`, and on
|
|
131
|
+
record-based actions `record:` (a state miss is 409, as for plain access).
|
|
132
|
+
- A `when`-less arm anywhere but last is a compile error (it would make the
|
|
133
|
+
arms after it unreachable), and `when` outside an `arms` entry is rejected
|
|
134
|
+
rather than ignored.
|
|
135
|
+
|
|
136
|
+
**Ordering.** The route runs: auth gate → input validation → the **union** of
|
|
137
|
+
all arms as the ordinary access check (pre-record role gate; on record actions
|
|
138
|
+
the record fetch and post-record check) → **arm selection on the validated
|
|
139
|
+
input** → evaluation of the selected arm → refs → `execute`. The union check
|
|
140
|
+
keeps the ID-probe protection of plain access; the selected arm is the
|
|
141
|
+
decision. On a [bulk variant](/define/actions/record-and-standalone#bulk-variant) the batch
|
|
142
|
+
shares one input, so one arm is selected for the batch and every record must
|
|
143
|
+
satisfy it.
|
|
144
|
+
|
|
145
|
+
**Relationship arms** (a role defined `via:` a relationship, like `siteStaff`
|
|
146
|
+
above) are decided from the lanes the namespace gate proved on this request
|
|
147
|
+
(`ctx.lanes`), never by a fresh query. They are legal only on a standalone
|
|
148
|
+
action whose namespace lists that relationship in `via:` **and** declares
|
|
149
|
+
[`lanes: 'all'`](/define/areas#recording-every-matched-lane--lanes-all); anywhere
|
|
150
|
+
else (record-based actions included) the compiler refuses the arm. FGA arms
|
|
151
|
+
are refused in arms.
|
|
152
|
+
|
|
153
|
+
### Asking a named role in the body (`ctx.is`)
|
|
154
|
+
|
|
155
|
+
When the body must branch on a role — show staff everything, show others their
|
|
156
|
+
own rows — ask the declared rule instead of re-deriving it:
|
|
157
|
+
|
|
158
|
+
```typescript
|
|
159
|
+
async execute({ ctx, db }) {
|
|
160
|
+
if (ctx.is("siteStaff")) { /* … */ }
|
|
161
|
+
}
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
`ctx.is(name)` is generated from [`authz.roles`](/define/authz-roles): `name`
|
|
165
|
+
is typed as the union of declared names (a typo is a `tsc` error), and each
|
|
166
|
+
name is expanded exactly as it is in `access.roles`, so the body and the gates
|
|
167
|
+
cannot disagree. It evaluates against the request's current context — a
|
|
168
|
+
sysadmin passes, pseudo-roles and `scope:<kind>:<role>` work, and a `via:` arm
|
|
169
|
+
is true only when a namespace gate with `lanes: 'all'` recorded that lane on
|
|
170
|
+
this request. `ctx.is` never queries; outside such a namespace a `via:` arm is
|
|
171
|
+
false.
|
|
172
|
+
|
|
97
173
|
### Function Access
|
|
98
174
|
|
|
99
175
|
For complex logic, use an access function:
|