@quickback-dev/cli 0.72.4 → 0.72.7

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/index.js CHANGED
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import pc from "picocolors";
12
12
  // Version injected at build time by scripts/inject-version.ts
13
- const CLI_VERSION = "0.72.4";
13
+ const CLI_VERSION = "0.72.7";
14
14
  function getPackageVersion() {
15
15
  return CLI_VERSION;
16
16
  }
@@ -152,7 +152,30 @@ This does three things:
152
152
 
153
153
  The access tokens it issues carry the OAuth issuer (`BETTER_AUTH_URL` + `/auth/v1`, or `oauth.issuerUrl`) and the requested resource as audience — exactly what the generated middleware verifies — with or without `auth.jwt` and without needing `oauth.enabled`.
154
154
 
155
- The middleware accepts these tokens only while their Better Auth session (`sid`) is live, and builds the user's full context from it. A token whose audience is a scope kind's resource is the other lane: confined to one instance, no session — see [Instance-bound OAuth tokens](/define/scopes#instance-bound-oauth-tokens).
155
+ The middleware accepts these tokens only while their Better Auth session (`sid`) is live, and builds the user's context from it — but **not the session's organization**. A token whose audience is a scope kind's resource is the other lane: confined to one instance, no session — see [Instance-bound OAuth tokens](/define/scopes#instance-bound-oauth-tokens).
156
+
157
+ #### Workspace-bound tokens
158
+
159
+ With the organization plugin on, an ordinary OAuth token is bound to the workspace the user **consented in**, following Better Auth's own `postLogin.consentReferenceId` pattern:
160
+
161
+ 1. **Consent.** Better Auth evaluates `consentReferenceId` with the current session on `GET /oauth2/authorize` and again on `POST /oauth2/consent` (once to store the consent, then inside the `authorize()` call that mints the code). The generated hook returns `qborg:<organizationId>` for the session's `activeOrganizationId` when the user is a member of it. So a consent page with a workspace picker that calls `POST /auth/v1/organization/set-active` before `POST /oauth2/consent` binds the token to the picked workspace. Stored consent is per workspace: consent given in A is not reused in B.
162
+ 2. **Exchange and refresh.** Better Auth stores the reference on the code and every rotated refresh token. `customAccessTokenClaims` re-reads the member row at every code exchange and refresh and signs the organization into a `qb_org` claim. A removed membership fails the grant with `invalid_grant` before the refresh token rotates — the connector must reauthorize.
163
+ 3. **Use.** The middleware acts in `qb_org` (role re-read from the member table on every request, so a removal or role change applies immediately) and ignores the session's current `activeOrganizationId`. Switching workspaces in your app does not move a connector's token. The team is taken from the session only while the session is in that same organization.
164
+
165
+ A token without `qb_org` (no active workspace at consent, or minted before this behaviour) has **no organization authority**: `activeOrgId` is undefined and `roles` is `[]`. To let tokens minted earlier keep following the session's active organization while connectors re-consent, opt in to the legacy behaviour explicitly:
166
+
167
+ ```ts
168
+ auth: {
169
+ config: {
170
+ oauth: {
171
+ enabled: true,
172
+ orgBinding: "legacy-session", // default: "strict"
173
+ },
174
+ },
175
+ },
176
+ ```
177
+
178
+ `orgBinding` is read whenever the OAuth provider is active, including under `agents.mcp.requireAuth` without `oauth.enabled`. `"legacy-session"` only affects tokens **without** `qb_org`; a bound token always acts in its own organization. Under the default `"strict"`, existing connectors lose organization access until the user re-consents. In a split AS / resource-server setup the resource server reads `qb_org` from tokens the AS mints, so recompile the AS first. Instance-bound (scope-kind) tokens are unaffected, and a scope kind may not be named `qborg`.
156
179
 
157
180
  The full handshake a connector runs:
158
181
 
@@ -857,6 +857,24 @@ access and its `guards` must be declarative: a function there fails the build
857
857
  (`TENANCY_BATCH_ASYNC`), because it could await other I/O and let another
858
858
  request's writes interleave into the transaction.
859
859
 
860
+ ## Encrypted columns
861
+
862
+ `.encrypted()` and `q.secret()` columns on tenant tables behave as on the edge:
863
+ the same routes, masking, `ctx.crypto` and `ctx.unmask`. The object never holds
864
+ a key. On each request it forwards, the edge derives the organization's tenant
865
+ data keys from its DEK (`ENCRYPTION_KEK` and `org_data_keys` stay on the edge)
866
+ and hands them over with the request; the object uses them for that request
867
+ and stores ciphertext only, so its SQLite, backups and restore points never
868
+ hold plaintext. Tenant schedules, jobs and alarms carry no key: an encrypted
869
+ write there fails before any row is written. `.sealed()` is refused
870
+ (`TENANCY_UNSUPPORTED`). The key model, rotation and the one-off re-encrypt of
871
+ rows written before a column became `q.secret()`:
872
+ [Encryption → Encrypted columns in tenant tables](/define/encryption#encrypted-columns-in-tenant-tables).
873
+
874
+ The `ctx.unmask` reveal audit rides the object's outbox into `audit_events`,
875
+ like a tenant hard delete, when the project has the security-audit database;
876
+ without one it is not recorded.
877
+
860
878
  ## Hard deletes and the audit log
861
879
 
862
880
  The tenant Worker has no `AUDIT_DB`. A hard `DELETE` (single or batch) on a
@@ -1685,6 +1703,9 @@ name no target defines as a string var (`TENANCY_VARS_UNDECLARED`). Every other
1685
1703
  `lib/realtime` (needs the Broadcaster), `lib/security-audit` (needs the audit
1686
1704
  database) and `lib/auth` (Better Auth) do not run in the tenant Worker. Loading
1687
1705
  one there would drop its side effect silently, so the compiler guarantees:
1706
+ (When a tenant table has an [encrypted column](#encrypted-columns),
1707
+ `lib/encryption` and `lib/secrets` join this list: they are re-pointed at the
1708
+ tenant key runtime and refused where that fails.)
1688
1709
 
1689
1710
  - **Rewritten.** In tenant feature files and tenant queue handlers, a value
1690
1711
  import of `lib/realtime` or `lib/security-audit` is pointed at the tenant
@@ -2288,7 +2309,7 @@ organization's object before you apply that migration.
2288
2309
  | `REALTIME_RECIPIENT_PROVING_TABLE` | A recipients resolver's `recipient.scope` names a literal `provingTable` that is not one of the kind's proving tables (a relationship `from` of its roles). Any tenancy mode. |
2289
2310
  | `TENANCY_REALTIME_VIEW_ROOM` | A live view is rooted on a tenant table while a scope kind is tenant-backed. View rooms are not tenant-qualified yet. |
2290
2311
  | `TENANCY_LEGACY_SCOPE_TICKET` | `realtime.wsTicket` accepts supplied-scope principals (`acceptScope`) for a tenant room or a tenant-backed kind. A legacy scope claim carries no tenant, so its ticket cannot name a tenant room. |
2291
- | `TENANCY_UNSUPPORTED` | A tenant table declares `embeddings`, `namespace`, `owns`, an `.encrypted()` / `.sealed()` column, or a `q.storageKey()` column. |
2312
+ | `TENANCY_UNSUPPORTED` | A tenant table declares `embeddings`, `namespace`, `owns`, a `.sealed()` column, or a `q.storageKey()` column. `.encrypted()` and `q.secret()` are supported: see [Encrypted columns](#encrypted-columns). |
2292
2313
  | `TENANCY_TRIGGER_CROSS_OBJECT` | A tenant table's `sql:` trigger (body or `when:`) names a table outside its own object — a platform table, another partition kind, or a table no feature declares — or uses SQL the compiler does not model (a schema-qualified name, a CTE, a table-valued function other than `json_each` / `json_tree`, a statement keyword such as `DROP` / `PRAGMA`, unbalanced parentheses). Also a platform table's trigger that names a tenant table. Every violation is listed. |
2293
2314
  | `TENANCY_BACKUP` | `tenancy.backup.bucket` is not an UPPER_SNAKE binding name, or `every` is not `<n>m` / `<n>h` / `<n>d` of at least 15 minutes. |
2294
2315
  | `TENANCY_LOOKUP` | A lookup's table is not a tenant table, or its column is not a column of that table. |
@@ -937,6 +937,8 @@ export default defineAction({
937
937
 
938
938
  `column` is the property name when no other table has a secret column of that name, or `{ table, column }` (SQL table name + property name) — always accepted, and required for a shared name. The row must carry the column and its organization column; `null` unmasks to `null`.
939
939
 
940
+ On a tenant table ([`tenancy.isolation: 'durable-object'`](/configure/tenant-databases#encrypted-columns)) the same call opens the value with the tenant data key the edge carried on the request. A value written in plaintext before the column became `q.secret()` is returned as is; see [Encrypted columns in tenant tables](/define/encryption#encrypted-columns-in-tenant-tables) for the one-off re-encrypt.
941
+
940
942
  #### Reaching Better Auth tables (`authDb`)
941
943
 
942
944
  The scoped `db` is the **features** database. Better Auth tables never appear
@@ -132,6 +132,71 @@ export default feature('integrations', {
132
132
  | `q.secret()` | envelope ciphertext | nobody through a read path; action code through `ctx.unmask` |
133
133
  | `.sealed()` | client-sealed ciphertext | only a client holding a granted key — the server never can |
134
134
 
135
+ ## Encrypted columns in tenant tables
136
+
137
+ With [`tenancy.isolation: 'durable-object'`](/configure/tenant-databases), declare `.encrypted()` and `q.secret()` on a tenant table exactly as above. Routes, masking, `ctx.crypto` and `ctx.unmask` behave as on a single Worker. `.sealed()` stays edge-only and is refused on a tenant table (`TENANCY_UNSUPPORTED`).
138
+
139
+ The keys never move into the object:
140
+
141
+ - `ENCRYPTION_KEK` and `org_data_keys` stay on the edge Worker. The tenant Worker needs no secret and reads none.
142
+ - On every request it forwards, the edge derives the organization's **tenant data keys** — one per DEK version, HKDF-SHA-256 of that DEK with the organization id and version as context — and passes them to the object with the request. The object uses them for that request only and never writes them to its SQLite. Its database, its backups and its restore points hold ciphertext only.
143
+ - Values at rest look the same (`qbenc:2:<keyVersion>:…`, bound to organization + table + column), but a tenant ciphertext does not open with the edge DEK, and an edge ciphertext does not open in the object.
144
+ - Rotation is the envelope tier's. [`rotateOrgDataKey`](#rotating-an-organizations-dek) starts a new tenant key version and retired versions keep reading; [`rewrapOrgDataKeys`](#rotating-encryption_kek) changes nothing the object sees; deleting the organization's `org_data_keys` row shreds its tenant values too. Warm edge isolates hand out the previous key set for up to five minutes after a rotation; a value sealed under the new version in that window reads as `ENCRYPTION_UNREADABLE` from such an isolate until its cache refreshes.
145
+ - **Fail closed.** Tenant schedules, tenant jobs and alarms run without a forwarded request and carry no key: a write to an encrypted column there throws before any row is written, and nothing opens a value. Write and open encrypted tenant columns from actions and routes.
146
+ - Tenant feature files that import `lib/encryption` or `lib/secrets` are re-pointed at the tenant runtime. A shared `quickback/lib` helper that still reaches either from tenant code fails the build (`TENANCY_EDGE_IMPORT_IN_TENANT`), like `lib/realtime`. Platform tables with encrypted columns are unaffected: the edge keeps sealing and opening them with the organization DEK, and the tenant Worker never runs their files.
147
+
148
+ ### Moving an existing plaintext column to `q.secret()`
149
+
150
+ Rows written before the column became `q.secret()` hold plaintext. Reads return them unchanged (a value without the `qbenc:` prefix is plaintext), and `ctx.unmask` returns them as they are. Take a tenant table whose token column moved to `q.secret()`:
151
+
152
+ ```ts
153
+ // features/share_links/share_links.ts
154
+ import { feature, q } from "@quickback/compiler";
155
+
156
+ export default feature("share_links", {
157
+ columns: {
158
+ id: q.id(),
159
+ organizationId: q.scope("organization").index(),
160
+ label: q.text({ maxLength: 200 }).encrypted(),
161
+ token: q.secret({ maxLength: 200 }), // was q.text() — existing rows hold plaintext
162
+ ...q.audit(),
163
+ ...q.softDelete(),
164
+ },
165
+ read: { access: { roles: ["owner", "admin", "member"] } },
166
+ create: { access: { roles: ["owner", "admin"] } },
167
+ update: { access: { roles: ["owner", "admin"] } },
168
+ });
169
+ ```
170
+
171
+ Re-encrypt the old rows once by writing each value back through the chokepoint, which seals anything that is not already ciphertext:
172
+
173
+ {/* doc-compile: skip — imports the table declared in the previous fence; the gate compiles each fence as an isolated project. */}
174
+ ```ts
175
+ // features/share_links/actions/reencryptTokens.ts
176
+ import { z } from "zod";
177
+ import { eq } from "drizzle-orm";
178
+ import { defineAction, shareLinks } from "../.quickback/define-action";
179
+
180
+ export default defineAction({
181
+ description: "One-off: seal tokens written before the column was q.secret().",
182
+ path: "/share_links/reencrypt",
183
+ method: "POST",
184
+ input: z.object({}),
185
+ access: { roles: ["owner"] },
186
+ async execute({ db, ctx }) {
187
+ let sealed = 0;
188
+ for (const row of await db.select().from(shareLinks)) {
189
+ if (typeof row.token !== "string" || row.token.startsWith("qbenc:")) continue;
190
+ await db.update(shareLinks).set({ token: await ctx.unmask(row, "token") }).where(eq(shareLinks.id, row.id));
191
+ sealed++;
192
+ }
193
+ return { sealed };
194
+ },
195
+ });
196
+ ```
197
+
198
+ Run it once per organization (it runs in that organization's object), then delete the action. The same recipe works for an `.encrypted()` column and for single-Worker projects.
199
+
135
200
  ---
136
201
 
137
202
  # Sealed tier — end-to-end encryption
@@ -175,7 +175,7 @@ In request bodies a column that is not `.required()` is `.optional().nullable()`
175
175
 
176
176
  Every rule is enforced on the generated create, update, and batch routes, described in OpenAPI, and read by the CMS form from the [schema registry](/ui/admin/schema-format). A misspelled option (`maxlength`) is a compile error, not a silent no-op. `q.url()` takes `sqlName` and `maxLength` only.
177
177
 
178
- `q.secret()` is a write-only credential column — an API client secret, a webhook URL with an embedded token. It takes `sqlName`, `minLength`, `maxLength`, and `pattern`; it is encrypted at rest like `.encrypted()`, redacted on every read path for every role (owner included), and read server-side only through `ctx.unmask(row, column)`. The table needs a `q.scope('organization')` column. See [Secret columns](/define/encryption#secret-columns--qsecret).
178
+ `q.secret()` is a write-only credential column — an API client secret, a webhook URL with an embedded token. It takes `sqlName`, `minLength`, `maxLength`, and `pattern`; it is encrypted at rest like `.encrypted()`, redacted on every read path for every role (owner included), and read server-side only through `ctx.unmask(row, column)`. The table needs a `q.scope('organization')` column; it may be a [tenant table](/define/encryption#encrypted-columns-in-tenant-tables). See [Secret columns](/define/encryption#secret-columns--qsecret).
179
179
 
180
180
  `q.url()` is `q.text()` plus an absolute-`http(s)`-URL check at the validation edge, so `javascript:` / `data:` / `ftp:` URIs and free-form strings are rejected before they ever land in storage or get rendered in the CMS.
181
181
 
@@ -972,6 +972,41 @@ For a [tenant-backed kind](/configure/tenant-databases#tenant-backed-scope-kinds
972
972
  > Never call `/oauth2/revoke` for a bound refresh token. Better Auth treats any later use of a revoked refresh token — an app retry, two tabs racing a rotation — as replay and deletes **every** refresh token that user holds for the client, signing them out of all instances.
973
973
 
974
974
 
975
+ ### Instance liveness (`instance.live`)
976
+
977
+ By default an instance admits while its row exists and isn't soft-deleted. A status can end an instance too: a cancelled event should stop admitting its crew, but a relationship's `where` filters only the relationship's own row, and a crew row on a cancelled event is still a valid crew row. Declare the instance in its object form with a `live` predicate:
978
+
979
+ ```typescript
980
+ scopes: {
981
+ event: {
982
+ requestField: 'eventId',
983
+ instance: { table: 'events', live: { status: { notIn: ['cancelled', 'archived'] } } },
984
+ roles: { organizer: { via: 'organizerOf' }, attendee: { via: 'attendeeOf' } },
985
+ precedence: ['organizer', 'attendee'],
986
+ oauth: {},
987
+ },
988
+ },
989
+ ```
990
+
991
+ `live` maps columns of the instance table to one condition each, all of which must hold: `{ equals }`, `{ notEquals }`, `{ in: [...] }` or `{ notIn: [...] }`, with literal values. These are the operators an action's `access.record` uses. A NULL column satisfies no condition, so `notEquals` and `notIn` fail closed on a missing value. The string form (`instance: 'events'`) keeps working, and a kind without `live` compiles exactly as before.
992
+
993
+ A non-live instance denies with the same result as a missing one (`SCOPE_NOT_FOUND`, or no scope stamped), so the response doesn't reveal that the instance exists. The predicate is checked everywhere the instance is read:
994
+
995
+ - Tenant admission (`qb.admitScope` / `admitLocal`): authorize, code exchange, every refresh, every namespace request of a bound token or a relationship-lane session, ws-tickets, and `issueScopeGrant`.
996
+ - Edge OAuth admission for platform kinds.
997
+ - The namespace scope-claim refresh, including the reuse of a hydrated `ctx.<exposeAs>` row.
998
+ - `POST /scope/v1/enter` and `ctx.mintScope`.
999
+ - Server-grant reads and links (`readScopeGrantSubject`, `linkScopeGrantSubject`).
1000
+
1001
+ The access token already in flight keeps working until its TTL runs out (at most 180 seconds). The next refresh is denied, and so is the next namespace request, because each one re-runs admission.
1002
+
1003
+ Compile errors:
1004
+
1005
+ - `SCOPE_INSTANCE_LIVE_INVALID`: an empty `live`; a column the instance table doesn't declare; an operator other than the four; more than one operator on a column; an empty `in` / `notIn`; a `ctx.*` value; or a literal whose type doesn't match the column (text takes strings, integers take numbers, booleans take booleans). A wrong-typed literal would make `notEquals` always true, so it fails the build.
1006
+ - `SCOPE_INSTANCE_LIVE_UNBOUND`: the instance table has no organization column, or a role proves from a table with no organization column. Those paths never read the instance row, so they couldn't check liveness.
1007
+
1008
+ Org members who reach the namespace through a `{ roles: [...] }` lane aren't affected. They're admitted by their org role, not by the scope, so staff can still open a cancelled event.
1009
+
975
1010
  ### Server-issued grants (`issueScopeGrant`)
976
1011
 
977
1012
  Some principals prove themselves with a credential Better Auth does not know: a handout code staff give at the door, or a one-time exchange of a legacy event pass. Don't turn that credential into a Better Auth session. A one-time token transfers a full session, and creating a session row or verifying an email from server code writes auth tables and can link rows across organizations. Issue a bound grant instead.
@@ -1173,6 +1208,10 @@ ctx.scope?: Record<string, { id: string; roles?: string[]; subjectId?: string; [
1173
1208
  recheck?: Record<string, string | number | boolean | null | Array<string | number>>;
1174
1209
  };
1175
1210
  }>;
1211
+ instance?: string | { // the instance table; object form adds liveness (Literal = string | number | boolean)
1212
+ table: string;
1213
+ live?: Record<string, { equals: Literal } | { notEquals: Literal } | { in: Literal[] } | { notIn: Literal[] }>;
1214
+ };
1176
1215
  oauth?: { // instance-bound OAuth tokens
1177
1216
  resource?: string; // default BETTER_AUTH_URL + '/<kind>'
1178
1217
  accessTokenTtl?: number; // 1–180, default 180
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quickback-dev/cli",
3
- "version": "0.72.4",
3
+ "version": "0.72.7",
4
4
  "description": "CLI for Quickback — define your backend in TypeScript, compile to a fully wired Cloudflare Worker (or Bun / Node) with auth, database, migrations, security, CMS, and Account UI.",
5
5
  "author": "Kardoe Incorporated <paul@kardoe.com>",
6
6
  "license": "MIT",
@@ -152,7 +152,30 @@ This does three things:
152
152
 
153
153
  The access tokens it issues carry the OAuth issuer (`BETTER_AUTH_URL` + `/auth/v1`, or `oauth.issuerUrl`) and the requested resource as audience — exactly what the generated middleware verifies — with or without `auth.jwt` and without needing `oauth.enabled`.
154
154
 
155
- The middleware accepts these tokens only while their Better Auth session (`sid`) is live, and builds the user's full context from it. A token whose audience is a scope kind's resource is the other lane: confined to one instance, no session — see [Instance-bound OAuth tokens](/define/scopes#instance-bound-oauth-tokens).
155
+ The middleware accepts these tokens only while their Better Auth session (`sid`) is live, and builds the user's context from it — but **not the session's organization**. A token whose audience is a scope kind's resource is the other lane: confined to one instance, no session — see [Instance-bound OAuth tokens](/define/scopes#instance-bound-oauth-tokens).
156
+
157
+ #### Workspace-bound tokens
158
+
159
+ With the organization plugin on, an ordinary OAuth token is bound to the workspace the user **consented in**, following Better Auth's own `postLogin.consentReferenceId` pattern:
160
+
161
+ 1. **Consent.** Better Auth evaluates `consentReferenceId` with the current session on `GET /oauth2/authorize` and again on `POST /oauth2/consent` (once to store the consent, then inside the `authorize()` call that mints the code). The generated hook returns `qborg:<organizationId>` for the session's `activeOrganizationId` when the user is a member of it. So a consent page with a workspace picker that calls `POST /auth/v1/organization/set-active` before `POST /oauth2/consent` binds the token to the picked workspace. Stored consent is per workspace: consent given in A is not reused in B.
162
+ 2. **Exchange and refresh.** Better Auth stores the reference on the code and every rotated refresh token. `customAccessTokenClaims` re-reads the member row at every code exchange and refresh and signs the organization into a `qb_org` claim. A removed membership fails the grant with `invalid_grant` before the refresh token rotates — the connector must reauthorize.
163
+ 3. **Use.** The middleware acts in `qb_org` (role re-read from the member table on every request, so a removal or role change applies immediately) and ignores the session's current `activeOrganizationId`. Switching workspaces in your app does not move a connector's token. The team is taken from the session only while the session is in that same organization.
164
+
165
+ A token without `qb_org` (no active workspace at consent, or minted before this behaviour) has **no organization authority**: `activeOrgId` is undefined and `roles` is `[]`. To let tokens minted earlier keep following the session's active organization while connectors re-consent, opt in to the legacy behaviour explicitly:
166
+
167
+ ```ts
168
+ auth: {
169
+ config: {
170
+ oauth: {
171
+ enabled: true,
172
+ orgBinding: "legacy-session", // default: "strict"
173
+ },
174
+ },
175
+ },
176
+ ```
177
+
178
+ `orgBinding` is read whenever the OAuth provider is active, including under `agents.mcp.requireAuth` without `oauth.enabled`. `"legacy-session"` only affects tokens **without** `qb_org`; a bound token always acts in its own organization. Under the default `"strict"`, existing connectors lose organization access until the user re-consents. In a split AS / resource-server setup the resource server reads `qb_org` from tokens the AS mints, so recompile the AS first. Instance-bound (scope-kind) tokens are unaffected, and a scope kind may not be named `qborg`.
156
179
 
157
180
  The full handshake a connector runs:
158
181
 
@@ -857,6 +857,24 @@ access and its `guards` must be declarative: a function there fails the build
857
857
  (`TENANCY_BATCH_ASYNC`), because it could await other I/O and let another
858
858
  request's writes interleave into the transaction.
859
859
 
860
+ ## Encrypted columns
861
+
862
+ `.encrypted()` and `q.secret()` columns on tenant tables behave as on the edge:
863
+ the same routes, masking, `ctx.crypto` and `ctx.unmask`. The object never holds
864
+ a key. On each request it forwards, the edge derives the organization's tenant
865
+ data keys from its DEK (`ENCRYPTION_KEK` and `org_data_keys` stay on the edge)
866
+ and hands them over with the request; the object uses them for that request
867
+ and stores ciphertext only, so its SQLite, backups and restore points never
868
+ hold plaintext. Tenant schedules, jobs and alarms carry no key: an encrypted
869
+ write there fails before any row is written. `.sealed()` is refused
870
+ (`TENANCY_UNSUPPORTED`). The key model, rotation and the one-off re-encrypt of
871
+ rows written before a column became `q.secret()`:
872
+ [Encryption → Encrypted columns in tenant tables](/define/encryption#encrypted-columns-in-tenant-tables).
873
+
874
+ The `ctx.unmask` reveal audit rides the object's outbox into `audit_events`,
875
+ like a tenant hard delete, when the project has the security-audit database;
876
+ without one it is not recorded.
877
+
860
878
  ## Hard deletes and the audit log
861
879
 
862
880
  The tenant Worker has no `AUDIT_DB`. A hard `DELETE` (single or batch) on a
@@ -1685,6 +1703,9 @@ name no target defines as a string var (`TENANCY_VARS_UNDECLARED`). Every other
1685
1703
  `lib/realtime` (needs the Broadcaster), `lib/security-audit` (needs the audit
1686
1704
  database) and `lib/auth` (Better Auth) do not run in the tenant Worker. Loading
1687
1705
  one there would drop its side effect silently, so the compiler guarantees:
1706
+ (When a tenant table has an [encrypted column](#encrypted-columns),
1707
+ `lib/encryption` and `lib/secrets` join this list: they are re-pointed at the
1708
+ tenant key runtime and refused where that fails.)
1688
1709
 
1689
1710
  - **Rewritten.** In tenant feature files and tenant queue handlers, a value
1690
1711
  import of `lib/realtime` or `lib/security-audit` is pointed at the tenant
@@ -2288,7 +2309,7 @@ organization's object before you apply that migration.
2288
2309
  | `REALTIME_RECIPIENT_PROVING_TABLE` | A recipients resolver's `recipient.scope` names a literal `provingTable` that is not one of the kind's proving tables (a relationship `from` of its roles). Any tenancy mode. |
2289
2310
  | `TENANCY_REALTIME_VIEW_ROOM` | A live view is rooted on a tenant table while a scope kind is tenant-backed. View rooms are not tenant-qualified yet. |
2290
2311
  | `TENANCY_LEGACY_SCOPE_TICKET` | `realtime.wsTicket` accepts supplied-scope principals (`acceptScope`) for a tenant room or a tenant-backed kind. A legacy scope claim carries no tenant, so its ticket cannot name a tenant room. |
2291
- | `TENANCY_UNSUPPORTED` | A tenant table declares `embeddings`, `namespace`, `owns`, an `.encrypted()` / `.sealed()` column, or a `q.storageKey()` column. |
2312
+ | `TENANCY_UNSUPPORTED` | A tenant table declares `embeddings`, `namespace`, `owns`, a `.sealed()` column, or a `q.storageKey()` column. `.encrypted()` and `q.secret()` are supported: see [Encrypted columns](#encrypted-columns). |
2292
2313
  | `TENANCY_TRIGGER_CROSS_OBJECT` | A tenant table's `sql:` trigger (body or `when:`) names a table outside its own object — a platform table, another partition kind, or a table no feature declares — or uses SQL the compiler does not model (a schema-qualified name, a CTE, a table-valued function other than `json_each` / `json_tree`, a statement keyword such as `DROP` / `PRAGMA`, unbalanced parentheses). Also a platform table's trigger that names a tenant table. Every violation is listed. |
2293
2314
  | `TENANCY_BACKUP` | `tenancy.backup.bucket` is not an UPPER_SNAKE binding name, or `every` is not `<n>m` / `<n>h` / `<n>d` of at least 15 minutes. |
2294
2315
  | `TENANCY_LOOKUP` | A lookup's table is not a tenant table, or its column is not a column of that table. |
@@ -937,6 +937,8 @@ export default defineAction({
937
937
 
938
938
  `column` is the property name when no other table has a secret column of that name, or `{ table, column }` (SQL table name + property name) — always accepted, and required for a shared name. The row must carry the column and its organization column; `null` unmasks to `null`.
939
939
 
940
+ On a tenant table ([`tenancy.isolation: 'durable-object'`](/configure/tenant-databases#encrypted-columns)) the same call opens the value with the tenant data key the edge carried on the request. A value written in plaintext before the column became `q.secret()` is returned as is; see [Encrypted columns in tenant tables](/define/encryption#encrypted-columns-in-tenant-tables) for the one-off re-encrypt.
941
+
940
942
  #### Reaching Better Auth tables (`authDb`)
941
943
 
942
944
  The scoped `db` is the **features** database. Better Auth tables never appear
@@ -132,6 +132,71 @@ export default feature('integrations', {
132
132
  | `q.secret()` | envelope ciphertext | nobody through a read path; action code through `ctx.unmask` |
133
133
  | `.sealed()` | client-sealed ciphertext | only a client holding a granted key — the server never can |
134
134
 
135
+ ## Encrypted columns in tenant tables
136
+
137
+ With [`tenancy.isolation: 'durable-object'`](/configure/tenant-databases), declare `.encrypted()` and `q.secret()` on a tenant table exactly as above. Routes, masking, `ctx.crypto` and `ctx.unmask` behave as on a single Worker. `.sealed()` stays edge-only and is refused on a tenant table (`TENANCY_UNSUPPORTED`).
138
+
139
+ The keys never move into the object:
140
+
141
+ - `ENCRYPTION_KEK` and `org_data_keys` stay on the edge Worker. The tenant Worker needs no secret and reads none.
142
+ - On every request it forwards, the edge derives the organization's **tenant data keys** — one per DEK version, HKDF-SHA-256 of that DEK with the organization id and version as context — and passes them to the object with the request. The object uses them for that request only and never writes them to its SQLite. Its database, its backups and its restore points hold ciphertext only.
143
+ - Values at rest look the same (`qbenc:2:<keyVersion>:…`, bound to organization + table + column), but a tenant ciphertext does not open with the edge DEK, and an edge ciphertext does not open in the object.
144
+ - Rotation is the envelope tier's. [`rotateOrgDataKey`](#rotating-an-organizations-dek) starts a new tenant key version and retired versions keep reading; [`rewrapOrgDataKeys`](#rotating-encryption_kek) changes nothing the object sees; deleting the organization's `org_data_keys` row shreds its tenant values too. Warm edge isolates hand out the previous key set for up to five minutes after a rotation; a value sealed under the new version in that window reads as `ENCRYPTION_UNREADABLE` from such an isolate until its cache refreshes.
145
+ - **Fail closed.** Tenant schedules, tenant jobs and alarms run without a forwarded request and carry no key: a write to an encrypted column there throws before any row is written, and nothing opens a value. Write and open encrypted tenant columns from actions and routes.
146
+ - Tenant feature files that import `lib/encryption` or `lib/secrets` are re-pointed at the tenant runtime. A shared `quickback/lib` helper that still reaches either from tenant code fails the build (`TENANCY_EDGE_IMPORT_IN_TENANT`), like `lib/realtime`. Platform tables with encrypted columns are unaffected: the edge keeps sealing and opening them with the organization DEK, and the tenant Worker never runs their files.
147
+
148
+ ### Moving an existing plaintext column to `q.secret()`
149
+
150
+ Rows written before the column became `q.secret()` hold plaintext. Reads return them unchanged (a value without the `qbenc:` prefix is plaintext), and `ctx.unmask` returns them as they are. Take a tenant table whose token column moved to `q.secret()`:
151
+
152
+ ```ts
153
+ // features/share_links/share_links.ts
154
+ import { feature, q } from "@quickback/compiler";
155
+
156
+ export default feature("share_links", {
157
+ columns: {
158
+ id: q.id(),
159
+ organizationId: q.scope("organization").index(),
160
+ label: q.text({ maxLength: 200 }).encrypted(),
161
+ token: q.secret({ maxLength: 200 }), // was q.text() — existing rows hold plaintext
162
+ ...q.audit(),
163
+ ...q.softDelete(),
164
+ },
165
+ read: { access: { roles: ["owner", "admin", "member"] } },
166
+ create: { access: { roles: ["owner", "admin"] } },
167
+ update: { access: { roles: ["owner", "admin"] } },
168
+ });
169
+ ```
170
+
171
+ Re-encrypt the old rows once by writing each value back through the chokepoint, which seals anything that is not already ciphertext:
172
+
173
+ {/* doc-compile: skip — imports the table declared in the previous fence; the gate compiles each fence as an isolated project. */}
174
+ ```ts
175
+ // features/share_links/actions/reencryptTokens.ts
176
+ import { z } from "zod";
177
+ import { eq } from "drizzle-orm";
178
+ import { defineAction, shareLinks } from "../.quickback/define-action";
179
+
180
+ export default defineAction({
181
+ description: "One-off: seal tokens written before the column was q.secret().",
182
+ path: "/share_links/reencrypt",
183
+ method: "POST",
184
+ input: z.object({}),
185
+ access: { roles: ["owner"] },
186
+ async execute({ db, ctx }) {
187
+ let sealed = 0;
188
+ for (const row of await db.select().from(shareLinks)) {
189
+ if (typeof row.token !== "string" || row.token.startsWith("qbenc:")) continue;
190
+ await db.update(shareLinks).set({ token: await ctx.unmask(row, "token") }).where(eq(shareLinks.id, row.id));
191
+ sealed++;
192
+ }
193
+ return { sealed };
194
+ },
195
+ });
196
+ ```
197
+
198
+ Run it once per organization (it runs in that organization's object), then delete the action. The same recipe works for an `.encrypted()` column and for single-Worker projects.
199
+
135
200
  ---
136
201
 
137
202
  # Sealed tier — end-to-end encryption
@@ -175,7 +175,7 @@ In request bodies a column that is not `.required()` is `.optional().nullable()`
175
175
 
176
176
  Every rule is enforced on the generated create, update, and batch routes, described in OpenAPI, and read by the CMS form from the [schema registry](/ui/admin/schema-format). A misspelled option (`maxlength`) is a compile error, not a silent no-op. `q.url()` takes `sqlName` and `maxLength` only.
177
177
 
178
- `q.secret()` is a write-only credential column — an API client secret, a webhook URL with an embedded token. It takes `sqlName`, `minLength`, `maxLength`, and `pattern`; it is encrypted at rest like `.encrypted()`, redacted on every read path for every role (owner included), and read server-side only through `ctx.unmask(row, column)`. The table needs a `q.scope('organization')` column. See [Secret columns](/define/encryption#secret-columns--qsecret).
178
+ `q.secret()` is a write-only credential column — an API client secret, a webhook URL with an embedded token. It takes `sqlName`, `minLength`, `maxLength`, and `pattern`; it is encrypted at rest like `.encrypted()`, redacted on every read path for every role (owner included), and read server-side only through `ctx.unmask(row, column)`. The table needs a `q.scope('organization')` column; it may be a [tenant table](/define/encryption#encrypted-columns-in-tenant-tables). See [Secret columns](/define/encryption#secret-columns--qsecret).
179
179
 
180
180
  `q.url()` is `q.text()` plus an absolute-`http(s)`-URL check at the validation edge, so `javascript:` / `data:` / `ftp:` URIs and free-form strings are rejected before they ever land in storage or get rendered in the CMS.
181
181
 
@@ -972,6 +972,41 @@ For a [tenant-backed kind](/configure/tenant-databases#tenant-backed-scope-kinds
972
972
  > Never call `/oauth2/revoke` for a bound refresh token. Better Auth treats any later use of a revoked refresh token — an app retry, two tabs racing a rotation — as replay and deletes **every** refresh token that user holds for the client, signing them out of all instances.
973
973
 
974
974
 
975
+ ### Instance liveness (`instance.live`)
976
+
977
+ By default an instance admits while its row exists and isn't soft-deleted. A status can end an instance too: a cancelled event should stop admitting its crew, but a relationship's `where` filters only the relationship's own row, and a crew row on a cancelled event is still a valid crew row. Declare the instance in its object form with a `live` predicate:
978
+
979
+ ```typescript
980
+ scopes: {
981
+ event: {
982
+ requestField: 'eventId',
983
+ instance: { table: 'events', live: { status: { notIn: ['cancelled', 'archived'] } } },
984
+ roles: { organizer: { via: 'organizerOf' }, attendee: { via: 'attendeeOf' } },
985
+ precedence: ['organizer', 'attendee'],
986
+ oauth: {},
987
+ },
988
+ },
989
+ ```
990
+
991
+ `live` maps columns of the instance table to one condition each, all of which must hold: `{ equals }`, `{ notEquals }`, `{ in: [...] }` or `{ notIn: [...] }`, with literal values. These are the operators an action's `access.record` uses. A NULL column satisfies no condition, so `notEquals` and `notIn` fail closed on a missing value. The string form (`instance: 'events'`) keeps working, and a kind without `live` compiles exactly as before.
992
+
993
+ A non-live instance denies with the same result as a missing one (`SCOPE_NOT_FOUND`, or no scope stamped), so the response doesn't reveal that the instance exists. The predicate is checked everywhere the instance is read:
994
+
995
+ - Tenant admission (`qb.admitScope` / `admitLocal`): authorize, code exchange, every refresh, every namespace request of a bound token or a relationship-lane session, ws-tickets, and `issueScopeGrant`.
996
+ - Edge OAuth admission for platform kinds.
997
+ - The namespace scope-claim refresh, including the reuse of a hydrated `ctx.<exposeAs>` row.
998
+ - `POST /scope/v1/enter` and `ctx.mintScope`.
999
+ - Server-grant reads and links (`readScopeGrantSubject`, `linkScopeGrantSubject`).
1000
+
1001
+ The access token already in flight keeps working until its TTL runs out (at most 180 seconds). The next refresh is denied, and so is the next namespace request, because each one re-runs admission.
1002
+
1003
+ Compile errors:
1004
+
1005
+ - `SCOPE_INSTANCE_LIVE_INVALID`: an empty `live`; a column the instance table doesn't declare; an operator other than the four; more than one operator on a column; an empty `in` / `notIn`; a `ctx.*` value; or a literal whose type doesn't match the column (text takes strings, integers take numbers, booleans take booleans). A wrong-typed literal would make `notEquals` always true, so it fails the build.
1006
+ - `SCOPE_INSTANCE_LIVE_UNBOUND`: the instance table has no organization column, or a role proves from a table with no organization column. Those paths never read the instance row, so they couldn't check liveness.
1007
+
1008
+ Org members who reach the namespace through a `{ roles: [...] }` lane aren't affected. They're admitted by their org role, not by the scope, so staff can still open a cancelled event.
1009
+
975
1010
  ### Server-issued grants (`issueScopeGrant`)
976
1011
 
977
1012
  Some principals prove themselves with a credential Better Auth does not know: a handout code staff give at the door, or a one-time exchange of a legacy event pass. Don't turn that credential into a Better Auth session. A one-time token transfers a full session, and creating a session row or verifying an email from server code writes auth tables and can link rows across organizations. Issue a bound grant instead.
@@ -1173,6 +1208,10 @@ ctx.scope?: Record<string, { id: string; roles?: string[]; subjectId?: string; [
1173
1208
  recheck?: Record<string, string | number | boolean | null | Array<string | number>>;
1174
1209
  };
1175
1210
  }>;
1211
+ instance?: string | { // the instance table; object form adds liveness (Literal = string | number | boolean)
1212
+ table: string;
1213
+ live?: Record<string, { equals: Literal } | { notEquals: Literal } | { in: Literal[] } | { notIn: Literal[] }>;
1214
+ };
1176
1215
  oauth?: { // instance-bound OAuth tokens
1177
1216
  resource?: string; // default BETTER_AUTH_URL + '/<kind>'
1178
1217
  accessTokenTtl?: number; // 1–180, default 180