@quickback-dev/cli 0.72.3 → 0.72.6

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.3";
13
+ const CLI_VERSION = "0.72.6";
14
14
  function getPackageVersion() {
15
15
  return CLI_VERSION;
16
16
  }
@@ -14,7 +14,7 @@ When `agents` is enabled (the default), the Worker serves:
14
14
  | `GET /.well-known/oauth-authorization-server` | [RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414) authorization-server metadata. When the `oauthProvider` plugin is enabled it **delegates to Better Auth's real OAuth 2.1 surface** (`/oauth2/authorize`, `/oauth2/token`, `/oauth2/register` dynamic client registration, PKCE); otherwise it advertises only the truthful token-mint subset. |
15
15
  | `GET /.well-known/api-catalog` | [RFC 9727](https://datatracker.ietf.org/doc/html/rfc9727) catalog linking at `/openapi.json`. Same [`openapi.publish`](/api/openapi#the-publish-gate) gate as the spec. |
16
16
  | `GET /.well-known/mcp.json` | MCP Server Card — discoverable metadata for the MCP server below. |
17
- | `POST /mcp` | Auto-generated MCP-over-HTTP server. One tool per OpenAPI operation, JWT auth forwarded through the same middleware as the REST API. |
17
+ | `POST /mcp` | Auto-generated MCP-over-HTTP server. One tool per OpenAPI operation, JWT auth forwarded through the same middleware as the REST API. With [`agents.mcp.events`](#mcp-events), also the event catalogue and webhook subscriptions ChatGPT's MCP Events use. |
18
18
  | `POST <path>` + `GET /.well-known/oauth-protected-resource<path>` | One per [named MCP server](#named-mcp-servers) (`agents.mcp.servers`) — a curated tool set with its own OAuth resource URL. |
19
19
 
20
20
  ## Default behavior
@@ -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
 
@@ -260,7 +283,9 @@ export default defineConfig({
260
283
  | `name` | No | Server title (`serverInfo.title`). Defaults to `<project> (<key> MCP)`; `serverInfo.name` is `<project>-<key>`. |
261
284
  | `instructions` | No | Returned from `initialize` as the server's `instructions`. |
262
285
  | `requireAuth` | No | Challenge anonymous callers with `401`. Defaults to `agents.mcp.requireAuth`. Setting it on any server force-enables `oauthProvider` + `bearer`, without changing the default `/mcp` challenge. |
286
+ | `lane` | No | `'staff'` (default) or `'attendee'`. An attendee server runs every request with no organization and no org roles, and confines OAuth tokens to its own audience. See [Attendee servers](#attendee-servers). |
263
287
  | `publicUrl` | No | A vanity URL for the server — see [below](#public-urls-on-a-vanity-host). |
288
+ | `events` | No | Event names from the [`agents.mcp.events`](#mcp-events) catalogue this server lists and accepts subscriptions for. Omitted: the server serves no events. An unknown name fails the compile. |
264
289
 
265
290
  The selection is fixed at compile time. A tool name or group the generated API doesn't have **fails the compile** with a suggestion (`unknown tool "events__selfRsvp". Did you mean "agenda_items__selfRsvp"?`), and so does a selection that ends up empty or an override for an unselected tool.
266
291
 
@@ -340,9 +365,36 @@ These fail the compile:
340
365
  - a tool `ui` naming an undeclared resource
341
366
  - a resource that no tool references
342
367
 
343
- > An access token minted for a named server is accepted anywhere this Worker accepts its own OAuth tokens, exactly like a `/mcp` token: the curated list decides what the model is offered, not what the token can reach. Every call still runs the full security pipeline.
368
+ > On a staff server (the default), an access token minted for a named server is accepted anywhere this Worker accepts its own OAuth tokens, exactly like a `/mcp` token: the curated list decides what the model is offered, not what the token can reach. Every call still runs the full security pipeline. To confine a server's tokens, make it an [attendee server](#attendee-servers).
344
369
 
345
370
 
371
+ ### Attendee servers
372
+
373
+ Set `lane: 'attendee'` on a server whose callers act only through a relationship to one record (an event's guests, a project's clients) and must never bring their organization role with them:
374
+
375
+ ```ts title="quickback.config.ts"
376
+ agents: {
377
+ mcp: {
378
+ servers: {
379
+ guest: {
380
+ path: '/guest/mcp',
381
+ lane: 'attendee',
382
+ tools: { include: ['agenda_items__listMyAgenda', 'agenda_items__selfRsvp'] },
383
+ },
384
+ },
385
+ },
386
+ },
387
+ ```
388
+
389
+ Two rules apply, enforced by a middleware that runs right after authentication, so after every credential lane and after the `resolve-oauth-context` hook. Nothing later can raise the lane again.
390
+
391
+ 1. **No organization authority on the server.** Every request on it runs with `activeOrgId`, `activeTeamId`, `roles`, `orgRole` and `tierRoles` cleared and `userRole: 'user'`. That covers the MCP request itself and every tool it dispatches. It applies however the caller authenticated (OAuth, session bearer, JWT or API key). The context also carries `ctx.mcpLane = 'attendee'`. Scoped roles (`scope:<kind>:<role>`) are resolved per request from the path, so they are the only authority an attendee server's tools see. A staff member who is also an event guest gets exactly a guest's access there.
392
+ 2. **OAuth tokens are confined by audience.** A token minted for the attendee server's URL (its path URL or its `publicUrl`) is refused with `401 invalid_token` everywhere else: `/api`, `/mcp` and other named servers. A token minted for any other audience is refused on the attendee server. That `401` names the server's protected-resource metadata, so a client can re-authorize for the right resource. A token whose `aud` lists both kinds keeps its staff authority on staff surfaces and is lowered on the attendee server.
393
+
394
+ Tool calls are tied to their server by the internal request object the MCP dispatcher builds, not by a header. A request from outside the Worker can't claim to be one. Instance-bound tokens ([Instance-bound OAuth tokens](/define/scopes#instance-bound-oauth-tokens)) are already confined to their instance and are left as they are.
395
+
396
+ Projects without an attendee server compile byte-identically.
397
+
346
398
  ### Public URLs on a vanity host
347
399
 
348
400
  `publicUrl` serves the same server at a second URL on a host of your choosing, e.g. `https://mcp.attend.vip/guest`:
@@ -397,8 +449,133 @@ curl -X POST https://my-api.example.com/mcp \
397
449
 
398
450
  The server speaks the **Streamable HTTP** MCP transport — JSON-RPC 2.0 over `POST`. A plain `GET /mcp` returns the server info document for sanity checks.
399
451
 
452
+ Two protocol revisions are served on the same endpoint:
453
+
454
+ | Revision | How a client negotiates |
455
+ |----------|-------------------------|
456
+ | `2026-07-28` | `server/discover` (no handshake), then `io.modelcontextprotocol/protocolVersion` in every request's `_meta`. Results carry `resultType: "complete"`, the server identity in `_meta`, and `ttlMs` / `cacheScope` on catalogue results. |
457
+ | `2025-03-26` | `initialize` / `notifications/initialized`. Results keep their historical shape. |
458
+
459
+ A `_meta` version outside that list is refused with JSON-RPC error `-32022` and `data.supported`. ChatGPT requires the `2026-07-28` revision for [MCP Events](#mcp-events).
460
+
400
461
  The MCP route does **not** emit its own CORS headers. The Worker's existing `cors()` middleware applies uniformly, so browser-origin access is governed by the same allowlist as the rest of the API (`auth.trustedOrigins` + the deploy origin). Server-to-server clients (Claude Desktop, Cursor, MCP Inspector) connect with a Bearer token and don't need browser CORS at all. If you want a browser-based MCP client (ChatGPT, Claude.ai) to connect cross-origin, add its origin to `auth.trustedOrigins` like any other web client.
401
462
 
463
+ ## MCP Events
464
+
465
+ ChatGPT's **MCP Events** lets a user say "watch this project for new tasks and open a draft for each one": ChatGPT subscribes through your MCP server, you POST a signed webhook to its callback when the event fires, and the chat acts on it. `agents.mcp.events` builds the catalogue and the subscription endpoints; the generated Worker does the rest.
466
+
467
+ Requires outbound webhooks — `webhooksBinding` on the database provider — because subscriptions and deliveries live in the webhooks store and ride the webhooks queue. The compile fails without it.
468
+
469
+ ```ts title="quickback.config.ts"
470
+ import { defineConfig } from '@quickback/compiler';
471
+
472
+ export default defineConfig({
473
+ name: 'my-api',
474
+ // …
475
+ agents: {
476
+ mcp: {
477
+ events: {
478
+ // Resource events: <table>.created / .updated / .deleted from every
479
+ // write through the audit-wrapped db. Table jsNames, as in feature().
480
+ resources: ['tasks', 'comments'],
481
+ // Custom events your own code emits with emitMcpEvent().
482
+ custom: {
483
+ 'build.finished': {
484
+ description: 'A build finished and its artefacts can be downloaded.',
485
+ filters: { project_id: { description: 'Only builds of this project.' } },
486
+ payloadSchema: {
487
+ type: 'object',
488
+ properties: { project_id: { type: 'string' }, build_id: { type: 'string' }, status: { type: 'string' } },
489
+ required: ['project_id', 'build_id', 'status'],
490
+ },
491
+ },
492
+ },
493
+ // Subscription lifetime bounds (ms). Defaults: 15 min / 24 h / 7 days.
494
+ ttl: { minMs: 900_000, defaultMs: 86_400_000, maxMs: 604_800_000 },
495
+ },
496
+ },
497
+ },
498
+ });
499
+ ```
500
+
501
+ ### The catalogue
502
+
503
+ `events/list` returns one definition per event with `inputSchema` (the filters a subscription may set) and `payloadSchema` (the delivered `data`). It is access-filtered like `tools/list`.
504
+
505
+ **Resource events.** Each table in `resources` gets `<table>.created`, `<table>.updated` and `<table>.deleted`:
506
+
507
+ - **Gate.** The table's `read.access`. A caller who cannot list the table does not see its events and cannot subscribe to them.
508
+ - **Filters.** `id` plus every foreign-key column (`projectId`, `documentId`, …). The filter values are compared as strings against the written row.
509
+ - **Scope.** The table must be organization- or owner-scoped; a subscription created inside organization `org_1` receives only `org_1` rows, and an owner-scoped subscription receives only the subscriber's rows. A table with neither column fails the compile.
510
+ - **Payload.** `{ id, operation, <scope column>, <foreign keys…> }` — a summary, never the row. The receiving agent reads the record with the table's get tool, so masking and access apply exactly as on REST. A soft delete arrives as `<table>.deleted`.
511
+ - **Source.** The audit-wrapped `db` chokepoint, after the write commits: CRUD routes, actions, cron, queue and email handlers all count. Inside `db.transaction()` the occurrences wait for the commit and are dropped on rollback. The write must use `.returning()` — without rows there is no id to send, so the generated CRUD routes emit and a bare `db.delete(...)` does not.
512
+
513
+ **Custom events.** Keyed by name (`<noun>.<verb>`, lowercase). Every `filters` entry becomes an optional string argument matched against the same-named field of the emitted `data`. The gate is "any authenticated caller". A custom name that equals a resource event fails the compile.
514
+
515
+ ### Emitting a custom event
516
+
517
+ {/* doc-compile: skip — imports the generated lib, which only exists inside a compiled project */}
518
+ ```ts
519
+ import { emitMcpEvent } from '../lib/mcp-events';
520
+
521
+ // Exactly one scope, like emitWebhookEvent: the organization the subscriber
522
+ // was in when they subscribed, or the owning user. An unscoped emit throws.
523
+ await emitMcpEvent(
524
+ 'build.finished',
525
+ { project_id: build.projectId, build_id: build.id, status: 'passed' },
526
+ { organizationId: ctx.activeOrgId! },
527
+ env,
528
+ );
529
+ ```
530
+
531
+ The name must be declared under `custom`; the data must satisfy your `payloadSchema` (the compiler does not check it at runtime). The function returns the number of subscriptions the occurrence was queued for.
532
+
533
+ ### Subscription lifecycle
534
+
535
+ | Method | Behaviour |
536
+ |--------|-----------|
537
+ | `events/subscribe` | Validates the event, arguments, `delivery.url` (https, public — the same [anti-SSRF policy](/platform/webhooks/outbound#url-validation-anti-ssrf) as webhook endpoints) and `delivery.secret` (`whsec_` + 24–64 base64 bytes). Verifies the callback with a signed challenge, then stores or refreshes the subscription. Returns `{ id, refreshBefore, cursor: null, truncated: false }`. |
538
+ | `events/unsubscribe` | Deletes the matching subscription. Idempotent. |
539
+
540
+ - **Identity** is `(principal, callback URL, event, arguments)`; the `id` is derived from it and arguments are canonicalised, so re-subscribing refreshes instead of duplicating. The principal is the authenticated user, or the delegated principal on a `principals:` lane.
541
+ - **Verification** POSTs `{ "type": "verification", "challenge": "…" }` signed with the new secret and expects a `2xx` `{ "challenge": "…" }` echo. A successful verification is cached per (principal, URL) for 7 days. A failure returns JSON-RPC error `-32015` with `data.reason` (`challenge_failed`, `timeout`, `connection_refused`, `http_4xx`, `http_5xx`, `http_3xx`).
542
+ - **Lifetime.** `ttlMs` is clamped into `[minMs, maxMs]`; an omitted `ttlMs` gets `defaultMs`; `ttlMs: null` gets `maxMs`. `refreshBefore` is never `null` — a subscription always expires, and delivery stops when it does. ChatGPT refreshes by calling `events/subscribe` again before `refreshBefore`; the refresh re-runs the access gate, which is where revoked access is caught.
543
+ - **Secret rotation.** A refresh with a new secret signs the next 10 minutes of deliveries with both secrets, space-separated.
544
+ - **No replay.** `cursor` is always `null`; events missed while a subscription was expired are not recoverable.
545
+
546
+ Other errors: `-32602` invalid params, `-32023` unknown event or subscription (`data.kind`), `-32024` not authenticated or no active organization for an organization-scoped event, `-32026` a delivery mode other than `webhook` (`data.feature: "deliveryMode"`).
547
+
548
+ ### Delivery
549
+
550
+ One event per request, signed in the [Standard Webhooks](https://www.standardwebhooks.com) format with the subscription's secret:
551
+
552
+ | Header | Value |
553
+ |--------|-------|
554
+ | `webhook-id` | The body's `eventId` (`evt_…`), stable across retries |
555
+ | `webhook-timestamp` | Signing time, Unix seconds — fresh per attempt |
556
+ | `webhook-signature` | `v1,<base64 HMAC-SHA256>`, two entries during a rotation window |
557
+ | `X-MCP-Subscription-Id` | The `id` from `events/subscribe` |
558
+
559
+ ```json
560
+ {
561
+ "eventId": "evt_8f3c…",
562
+ "name": "tasks.created",
563
+ "timestamp": "2026-10-29T12:05:00.000Z",
564
+ "data": { "id": "tsk_42", "operation": "created", "organizationId": "org_1", "projectId": "prj_7" },
565
+ "cursor": null
566
+ }
567
+ ```
568
+
569
+ Deliveries are `webhook_deliveries` rows (`endpoint_id` is the subscription id) processed by the webhooks queue consumer, with the same backoff as [outbound webhooks](/platform/webhooks/outbound#delivery-and-retry). Differences from endpoint deliveries:
570
+
571
+ - A body over 256 KiB is not sent; the delivery is marked `failed`.
572
+ - `410` revokes the subscription; `413` and any redirect fail the delivery without retry.
573
+ - The destination is re-checked against the anti-SSRF policy before every attempt, and redirects are never followed.
574
+
575
+ ### Limits
576
+
577
+ Polling and streaming delivery, replay cursors, and the draft's `gap` / `terminated` control envelopes are not implemented. Access revoked mid-lifetime is enforced at the next refresh, so the subscription TTL bounds the window — shorten `ttl.maxMs` if that window matters.
578
+
402
579
  ## Verification
403
580
 
404
581
  After you deploy, scan both the REST and MCP surfaces:
@@ -669,6 +669,13 @@ loaded table's firewall) and the per-lane scope refresh run against tenant
669
669
  SQLite exactly as on a single Worker. A namespace request costs one RPC (the
670
670
  forward) plus, for a session caller, one lookup read in D1.
671
671
 
672
+ A forwarded [share-link principal](/define/fga#landing-on-a-record-action)
673
+ is routed the same way, by the instance id in the path. The gate admits it
674
+ only for the link's own scope instance, in the object of the link's
675
+ organization, on a route that admits links of its object type (the landing);
676
+ it holds no roles and proves no lane, and `ctx.lane` is `'link'`. Anywhere
677
+ else under the prefix the request runs as the caller the link replaced.
678
+
672
679
  A claimed table's [legacy forward](/define/areas#keeping-the-old-url-legacy)
673
680
  (`legacy`) is not a namespace route. The edge routes its old URL
674
681
  (`/api/v1/locations`) by **active organization**, exactly as it routed the
@@ -850,6 +857,24 @@ access and its `guards` must be declarative: a function there fails the build
850
857
  (`TENANCY_BATCH_ASYNC`), because it could await other I/O and let another
851
858
  request's writes interleave into the transaction.
852
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
+
853
878
  ## Hard deletes and the audit log
854
879
 
855
880
  The tenant Worker has no `AUDIT_DB`. A hard `DELETE` (single or batch) on a
@@ -1678,6 +1703,9 @@ name no target defines as a string var (`TENANCY_VARS_UNDECLARED`). Every other
1678
1703
  `lib/realtime` (needs the Broadcaster), `lib/security-audit` (needs the audit
1679
1704
  database) and `lib/auth` (Better Auth) do not run in the tenant Worker. Loading
1680
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.)
1681
1709
 
1682
1710
  - **Rewritten.** In tenant feature files and tenant queue handlers, a value
1683
1711
  import of `lib/realtime` or `lib/security-audit` is pointed at the tenant
@@ -2175,24 +2203,63 @@ applies the same check to every operation.
2175
2203
  With [`authz.fga`](/define/fga), `fga_tuples` is a table of every organization's
2176
2204
  object. It is not in the platform D1.
2177
2205
 
2178
- - `ctx.fga` (`check`, `listObjects`, `expand`, `read`, `write`) exists in the
2179
- actions of tenant features. It reads and writes that organization's tuples
2180
- in the object, for a caller who is a member of the organization. A delete
2181
- is visible to the next check.
2206
+ - `ctx.fga` (`check`, `listObjects`, `expand`, `read`, `write`, and
2207
+ [`share`](/define/fga#minting-from-an-action-ctxfgashare) with link
2208
+ sharing) exists in the actions of tenant features, for every principal the
2209
+ edge admitted to the object: a member whose active organization it is, a
2210
+ caller a [namespace](#tenant-namespaces) lane proved with no organization
2211
+ seat, a share-link principal. The object is the organization. A delete is
2212
+ visible to the next check.
2182
2213
  - The edge hydrates no `ctx.fga`. It forwards `/fga/v1/*` to the caller's
2183
2214
  organization object, like a tenant route (no organization: `400 TENANT_REQUIRED`).
2184
2215
  - Tuples never cross organizations. Two organizations can hold tuples for the
2185
2216
  same object id, and each sees only its own.
2217
+ - `access: { fga }` arms are allowed on tenant tables: their reads, views,
2218
+ writes and record actions run in the object, where the gate finds the
2219
+ tuples. A platform table, a partitioned feature, a room binding and
2220
+ `realtime.wsTicket` still cannot carry one.
2221
+
2222
+ ### Share links
2223
+
2224
+ [Link subjects](/define/fga#link-subjects-linkid) work tenant-local: a link's
2225
+ row in `fga_share_links` and its tuple live in the organization object, next
2226
+ to the object they protect, and the lifecycle triggers (object delete or
2227
+ move, parent delete, fresh insert) run there, in the tenant migration set.
2228
+ The edge keeps the share router (`/share/v1/open`, `exchange`, `link`) and the
2229
+ `x-share-token` / `qb_share` middleware, and resolves a credential in two
2230
+ steps:
2231
+
2232
+ 1. The token's stored hash is looked up in the compiler-owned hashed lookup
2233
+ `__fgaShareLink` (`tenancy.lookups` semantics: the platform D1 holds
2234
+ `HMAC(TENANT_LOOKUP_KEY, "__fgaShareLink\0<hash>")`, a hash of a hash;
2235
+ `TENANT_LOOKUP_KEY` becomes a required secret). The lookup converges
2236
+ after the minting object's next response, like every lookup.
2237
+ 2. One command, `qb.shareLinkResolve`, runs in that object: the row by hash
2238
+ or id, live, its tuple still present, a `scope:<kind>:<role>` creator
2239
+ re-proven against the relationship row (one row, this organization), and
2240
+ the `fields` projection of the object. The `org` creator edge (Better
2241
+ Auth membership) is proven on the edge. A cookie carries the organization
2242
+ id, so a cookie request routes with no lookup.
2243
+
2244
+ The link principal is forwarded like any other; the tenant Worker applies it
2245
+ only on a route whose access has an `fga` arm for the link's object type and
2246
+ runs every other route as the caller it replaced. Inside the object the token
2247
+ is stored as `SHA-256(token)`: the object holds no secret, and a 256-bit
2248
+ random token needs no key. Signed `user:*` share tokens do not exist in this
2249
+ mode (`POST /fga/v1/share` on a `user:*` relation is `400`, a `GET
2250
+ /share/v1/<token>` with one is `404`); `user:*` tuples remain writable with
2251
+ `ctx.fga`. The link resource tables must be tenant tables.
2186
2252
 
2187
2253
  These shapes are refused, because each would read or write tuples from
2188
2254
  somewhere other than the organization object:
2189
2255
 
2190
2256
  | Code | Cause |
2191
2257
  |---|---|
2192
- | `TENANCY_FGA_SHARING` | `authz.fga.sharing` is set. Share tokens and links are opened on the edge without a session. You can still write a `user:*` tuple with `ctx.fga` in a tenant action, but only members of that organization can read it: `/fga/v1` needs a signed-in member, and platform actions have no `ctx.fga`. A public page must read the app's own tables instead, such as a share-token table. |
2258
+ | `TENANCY_FGA_SHARING` | `authz.fga.sharing` is set but the model declares no `link` subjects. Signed `user:*` tokens are verified on the edge against tuples it does not hold. Declare `type link` and list it on the shared relations. |
2193
2259
  | `TENANCY_FGA_MEMBERSHIP` | `authz.fga.membership` is set. Those tuples are written from Better Auth hooks on the edge. Write the tuples from a tenant action instead. |
2194
- | `TENANCY_FGA_ACCESS_ARM` | A table, action, room binding or `realtime.wsTicket` declares an `access: { fga }` arm. Call `ctx.fga.check(...)` in a tenant action instead. |
2260
+ | `TENANCY_FGA_ACCESS_ARM` | A platform table, a partitioned feature's table, a standalone action, a room binding or `realtime.wsTicket` declares an `access: { fga }` arm. Only a tenant table's reads, views, writes and record actions are gated in the organization object. Call `ctx.fga.check(...)` in a tenant action instead. |
2195
2261
  | `TENANCY_FGA_MIXED` | A platform feature's action, or an action in a [partitioned](#partitions) feature, reads `ctx.fga`. A partition object's database holds no tuples. |
2262
+ | `TENANCY_LOOKUP` | `tenancy.lookups.__fgaShareLink` is declared by the project; the name is compiler-owned. |
2196
2263
 
2197
2264
  Moving to `'durable-object'` does not copy the tuples already in the features
2198
2265
  D1. `fga_tuples` leaves the platform schema, so the next generated D1
@@ -2242,7 +2309,7 @@ organization's object before you apply that migration.
2242
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. |
2243
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. |
2244
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. |
2245
- | `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). |
2246
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. |
2247
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. |
2248
2315
  | `TENANCY_LOOKUP` | A lookup's table is not a tenant table, or its column is not a column of that table. |
@@ -2257,7 +2324,7 @@ organization's object before you apply that migration.
2257
2324
  | `TENANCY_TENANT_WORKER_CHANGED` | A deployed edge (per the existing `wrangler.toml`) would bind a different tenant Worker than it does now. See [Two Workers](#two-workers). |
2258
2325
  | `TENANCY_ENVIRONMENT_WORKER` / `TENANCY_ENVIRONMENT_SHARED` / `TENANCY_ENVIRONMENT_BACKUP` | A named environment has no `tenantWorker.name`, shares a tenant Worker or backup bucket with another target, or names a tenant Worker like an edge or files Worker. A target that does not deploy as the project `name` reuses the single-target tenant Worker or bucket. A Worker takes a reserved `<name>-unselected`, `<name>-files-unselected` or `<name>-tenant-unselected` placeholder name. `backupBucketName` is missing while `tenancy.backup` is set, or set while it is not. See [Named environments](#named-environments). |
2259
2326
  | `TENANCY_PURGE_DO` / `TENANCY_CHANGES` / `TENANCY_FGA` | `tenancy.purge`, `changes`, or a top-level `fga` block (declare it at `authz.fga`) together with `isolation: 'durable-object'`. |
2260
- | `TENANCY_FGA_SHARING` / `TENANCY_FGA_MEMBERSHIP` / `TENANCY_FGA_ACCESS_ARM` / `TENANCY_FGA_MIXED` | An FGA shape that would reach tuples from outside the organization object. See [FGA](#fga). |
2327
+ | `TENANCY_FGA_SHARING` / `TENANCY_FGA_MEMBERSHIP` / `TENANCY_FGA_ACCESS_ARM` / `TENANCY_FGA_MIXED` | An FGA shape that would reach tuples from outside the organization object: sharing without `link` subjects, derived membership, an `fga` arm off a tenant table, `ctx.fga` off the organization object. See [FGA](#fga). |
2261
2328
 
2262
2329
 
2263
2330
  ### Fence a result job to an authorization epoch
@@ -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
@@ -609,7 +609,9 @@ Hydration is **per matched lane**: each lane fills `ctx.<its own exposeAs>` from
609
609
 
610
610
  The gate stamps **`ctx.lane`** on every request it admits: the lane that let
611
611
  the caller in — a relationship lane's name, `'roles'` for a `{ roles }` lane,
612
- `'team'` for `{ team: true }`. The bulk-grant role check runs before the
612
+ `'team'` for `{ team: true }`, `'link'` for a
613
+ [share link](/define/fga#landing-on-a-record-action) landing on its own
614
+ instance. The bulk-grant role check runs before the
613
615
  relationship probes and short-circuits them, so an org admin who is *also* a
614
616
  named organizer is admitted as `'roles'`, and nothing records the organizer
615
617
  relationship. A body that needs to know ("may this admin also act as the
@@ -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`.
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