@quickback-dev/cli 0.72.3 → 0.72.4

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.4";
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
@@ -260,7 +260,9 @@ export default defineConfig({
260
260
  | `name` | No | Server title (`serverInfo.title`). Defaults to `<project> (<key> MCP)`; `serverInfo.name` is `<project>-<key>`. |
261
261
  | `instructions` | No | Returned from `initialize` as the server's `instructions`. |
262
262
  | `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. |
263
+ | `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
264
  | `publicUrl` | No | A vanity URL for the server — see [below](#public-urls-on-a-vanity-host). |
265
+ | `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
266
 
265
267
  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
268
 
@@ -340,9 +342,36 @@ These fail the compile:
340
342
  - a tool `ui` naming an undeclared resource
341
343
  - a resource that no tool references
342
344
 
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.
345
+ > 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
346
 
345
347
 
348
+ ### Attendee servers
349
+
350
+ 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:
351
+
352
+ ```ts title="quickback.config.ts"
353
+ agents: {
354
+ mcp: {
355
+ servers: {
356
+ guest: {
357
+ path: '/guest/mcp',
358
+ lane: 'attendee',
359
+ tools: { include: ['agenda_items__listMyAgenda', 'agenda_items__selfRsvp'] },
360
+ },
361
+ },
362
+ },
363
+ },
364
+ ```
365
+
366
+ 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.
367
+
368
+ 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.
369
+ 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.
370
+
371
+ 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.
372
+
373
+ Projects without an attendee server compile byte-identically.
374
+
346
375
  ### Public URLs on a vanity host
347
376
 
348
377
  `publicUrl` serves the same server at a second URL on a host of your choosing, e.g. `https://mcp.attend.vip/guest`:
@@ -397,8 +426,133 @@ curl -X POST https://my-api.example.com/mcp \
397
426
 
398
427
  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
428
 
429
+ Two protocol revisions are served on the same endpoint:
430
+
431
+ | Revision | How a client negotiates |
432
+ |----------|-------------------------|
433
+ | `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. |
434
+ | `2025-03-26` | `initialize` / `notifications/initialized`. Results keep their historical shape. |
435
+
436
+ 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).
437
+
400
438
  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
439
 
440
+ ## MCP Events
441
+
442
+ 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.
443
+
444
+ 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.
445
+
446
+ ```ts title="quickback.config.ts"
447
+ import { defineConfig } from '@quickback/compiler';
448
+
449
+ export default defineConfig({
450
+ name: 'my-api',
451
+ // …
452
+ agents: {
453
+ mcp: {
454
+ events: {
455
+ // Resource events: <table>.created / .updated / .deleted from every
456
+ // write through the audit-wrapped db. Table jsNames, as in feature().
457
+ resources: ['tasks', 'comments'],
458
+ // Custom events your own code emits with emitMcpEvent().
459
+ custom: {
460
+ 'build.finished': {
461
+ description: 'A build finished and its artefacts can be downloaded.',
462
+ filters: { project_id: { description: 'Only builds of this project.' } },
463
+ payloadSchema: {
464
+ type: 'object',
465
+ properties: { project_id: { type: 'string' }, build_id: { type: 'string' }, status: { type: 'string' } },
466
+ required: ['project_id', 'build_id', 'status'],
467
+ },
468
+ },
469
+ },
470
+ // Subscription lifetime bounds (ms). Defaults: 15 min / 24 h / 7 days.
471
+ ttl: { minMs: 900_000, defaultMs: 86_400_000, maxMs: 604_800_000 },
472
+ },
473
+ },
474
+ },
475
+ });
476
+ ```
477
+
478
+ ### The catalogue
479
+
480
+ `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`.
481
+
482
+ **Resource events.** Each table in `resources` gets `<table>.created`, `<table>.updated` and `<table>.deleted`:
483
+
484
+ - **Gate.** The table's `read.access`. A caller who cannot list the table does not see its events and cannot subscribe to them.
485
+ - **Filters.** `id` plus every foreign-key column (`projectId`, `documentId`, …). The filter values are compared as strings against the written row.
486
+ - **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.
487
+ - **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`.
488
+ - **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.
489
+
490
+ **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.
491
+
492
+ ### Emitting a custom event
493
+
494
+ {/* doc-compile: skip — imports the generated lib, which only exists inside a compiled project */}
495
+ ```ts
496
+ import { emitMcpEvent } from '../lib/mcp-events';
497
+
498
+ // Exactly one scope, like emitWebhookEvent: the organization the subscriber
499
+ // was in when they subscribed, or the owning user. An unscoped emit throws.
500
+ await emitMcpEvent(
501
+ 'build.finished',
502
+ { project_id: build.projectId, build_id: build.id, status: 'passed' },
503
+ { organizationId: ctx.activeOrgId! },
504
+ env,
505
+ );
506
+ ```
507
+
508
+ 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.
509
+
510
+ ### Subscription lifecycle
511
+
512
+ | Method | Behaviour |
513
+ |--------|-----------|
514
+ | `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 }`. |
515
+ | `events/unsubscribe` | Deletes the matching subscription. Idempotent. |
516
+
517
+ - **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.
518
+ - **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`).
519
+ - **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.
520
+ - **Secret rotation.** A refresh with a new secret signs the next 10 minutes of deliveries with both secrets, space-separated.
521
+ - **No replay.** `cursor` is always `null`; events missed while a subscription was expired are not recoverable.
522
+
523
+ 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"`).
524
+
525
+ ### Delivery
526
+
527
+ One event per request, signed in the [Standard Webhooks](https://www.standardwebhooks.com) format with the subscription's secret:
528
+
529
+ | Header | Value |
530
+ |--------|-------|
531
+ | `webhook-id` | The body's `eventId` (`evt_…`), stable across retries |
532
+ | `webhook-timestamp` | Signing time, Unix seconds — fresh per attempt |
533
+ | `webhook-signature` | `v1,<base64 HMAC-SHA256>`, two entries during a rotation window |
534
+ | `X-MCP-Subscription-Id` | The `id` from `events/subscribe` |
535
+
536
+ ```json
537
+ {
538
+ "eventId": "evt_8f3c…",
539
+ "name": "tasks.created",
540
+ "timestamp": "2026-10-29T12:05:00.000Z",
541
+ "data": { "id": "tsk_42", "operation": "created", "organizationId": "org_1", "projectId": "prj_7" },
542
+ "cursor": null
543
+ }
544
+ ```
545
+
546
+ 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:
547
+
548
+ - A body over 256 KiB is not sent; the delivery is marked `failed`.
549
+ - `410` revokes the subscription; `413` and any redirect fail the delivery without retry.
550
+ - The destination is re-checked against the anti-SSRF policy before every attempt, and redirects are never followed.
551
+
552
+ ### Limits
553
+
554
+ 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.
555
+
402
556
  ## Verification
403
557
 
404
558
  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
@@ -2175,24 +2182,63 @@ applies the same check to every operation.
2175
2182
  With [`authz.fga`](/define/fga), `fga_tuples` is a table of every organization's
2176
2183
  object. It is not in the platform D1.
2177
2184
 
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.
2185
+ - `ctx.fga` (`check`, `listObjects`, `expand`, `read`, `write`, and
2186
+ [`share`](/define/fga#minting-from-an-action-ctxfgashare) with link
2187
+ sharing) exists in the actions of tenant features, for every principal the
2188
+ edge admitted to the object: a member whose active organization it is, a
2189
+ caller a [namespace](#tenant-namespaces) lane proved with no organization
2190
+ seat, a share-link principal. The object is the organization. A delete is
2191
+ visible to the next check.
2182
2192
  - The edge hydrates no `ctx.fga`. It forwards `/fga/v1/*` to the caller's
2183
2193
  organization object, like a tenant route (no organization: `400 TENANT_REQUIRED`).
2184
2194
  - Tuples never cross organizations. Two organizations can hold tuples for the
2185
2195
  same object id, and each sees only its own.
2196
+ - `access: { fga }` arms are allowed on tenant tables: their reads, views,
2197
+ writes and record actions run in the object, where the gate finds the
2198
+ tuples. A platform table, a partitioned feature, a room binding and
2199
+ `realtime.wsTicket` still cannot carry one.
2200
+
2201
+ ### Share links
2202
+
2203
+ [Link subjects](/define/fga#link-subjects-linkid) work tenant-local: a link's
2204
+ row in `fga_share_links` and its tuple live in the organization object, next
2205
+ to the object they protect, and the lifecycle triggers (object delete or
2206
+ move, parent delete, fresh insert) run there, in the tenant migration set.
2207
+ The edge keeps the share router (`/share/v1/open`, `exchange`, `link`) and the
2208
+ `x-share-token` / `qb_share` middleware, and resolves a credential in two
2209
+ steps:
2210
+
2211
+ 1. The token's stored hash is looked up in the compiler-owned hashed lookup
2212
+ `__fgaShareLink` (`tenancy.lookups` semantics: the platform D1 holds
2213
+ `HMAC(TENANT_LOOKUP_KEY, "__fgaShareLink\0<hash>")`, a hash of a hash;
2214
+ `TENANT_LOOKUP_KEY` becomes a required secret). The lookup converges
2215
+ after the minting object's next response, like every lookup.
2216
+ 2. One command, `qb.shareLinkResolve`, runs in that object: the row by hash
2217
+ or id, live, its tuple still present, a `scope:<kind>:<role>` creator
2218
+ re-proven against the relationship row (one row, this organization), and
2219
+ the `fields` projection of the object. The `org` creator edge (Better
2220
+ Auth membership) is proven on the edge. A cookie carries the organization
2221
+ id, so a cookie request routes with no lookup.
2222
+
2223
+ The link principal is forwarded like any other; the tenant Worker applies it
2224
+ only on a route whose access has an `fga` arm for the link's object type and
2225
+ runs every other route as the caller it replaced. Inside the object the token
2226
+ is stored as `SHA-256(token)`: the object holds no secret, and a 256-bit
2227
+ random token needs no key. Signed `user:*` share tokens do not exist in this
2228
+ mode (`POST /fga/v1/share` on a `user:*` relation is `400`, a `GET
2229
+ /share/v1/<token>` with one is `404`); `user:*` tuples remain writable with
2230
+ `ctx.fga`. The link resource tables must be tenant tables.
2186
2231
 
2187
2232
  These shapes are refused, because each would read or write tuples from
2188
2233
  somewhere other than the organization object:
2189
2234
 
2190
2235
  | Code | Cause |
2191
2236
  |---|---|
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. |
2237
+ | `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
2238
  | `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. |
2239
+ | `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
2240
  | `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. |
2241
+ | `TENANCY_LOOKUP` | `tenancy.lookups.__fgaShareLink` is declared by the project; the name is compiler-owned. |
2196
2242
 
2197
2243
  Moving to `'durable-object'` does not copy the tuples already in the features
2198
2244
  D1. `fga_tuples` leaves the platform schema, so the next generated D1
@@ -2257,7 +2303,7 @@ organization's object before you apply that migration.
2257
2303
  | `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
2304
  | `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
2305
  | `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). |
2306
+ | `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
2307
 
2262
2308
 
2263
2309
  ### Fence a result job to an authorization epoch
@@ -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
@@ -237,9 +237,13 @@ authz: {
237
237
  enabled: true,
238
238
  // Default link lifetime in seconds. Required (> 0) when the table masks a column.
239
239
  ttlSeconds: 86400,
240
- // Every type a link can point at names its table. `fields` is the landing projection.
240
+ // Every type a link can point at names its table. `fields` is the optional landing projection.
241
241
  resources: { doc: { table: 'docs', fields: ['id', 'title'] } },
242
- links: { cookieTtlSeconds: 900, rateLimitPerMinute: 60 },
242
+ links: {
243
+ cookieTtlSeconds: 900,
244
+ // Never per IP by default: failed lookups capped for the whole surface, reads per link.
245
+ rateLimit: { failed: { key: 'global', limit: 600, period: 60 }, success: { key: 'link', limit: 600, period: 3600 } },
246
+ },
243
247
  },
244
248
  },
245
249
  }
@@ -251,7 +255,7 @@ Mint, list and revoke on the FGA API:
251
255
  POST /fga/v1/share { "object": "doc:d1", "relation": "viewer", "ttlSeconds": 3600 }
252
256
  → 201 { id: "lnk_…", token, url, expiresAt }
253
257
  url = https://api.acme.dev/share/v1/open#share=<token>
254
- GET /fga/v1/share/links?object=doc:d1 → { links: [{ id, relation, scope, expiresAt, active }] }
258
+ GET /fga/v1/share/links?object=doc:d1 → { links: [{ id, relation, scope, expiresAt, active, createdVia, … }] } (never a token or URL)
255
259
  POST /fga/v1/share/revoke { "id": "lnk_…" }
256
260
  ```
257
261
 
@@ -270,12 +274,69 @@ gets 403. Minting needs that permission through a real membership role — a
270
274
  sysadmin without one can revoke links but not mint them.
271
275
 
272
276
  **The creator is an edge.** A link is honoured only while the user who minted
273
- it is still a member of the link's organization whose **current** role holds
274
- `share:create`. Every resolution reads that role from Better Auth; nothing is
275
- stored. Remove the creator from the organization, or move them to a role
276
- without `share:create`, and every link they minted stops working — and with it
277
- every request that was admitted only through those links. Restore the role and
278
- the links work again (revoke them to end them for good).
277
+ it can still share. Which edge is recorded in the row's `created_via`:
278
+
279
+ | `created_via` | The link lives while |
280
+ | --- | --- |
281
+ | `org` | `created_by` is a member of the link's organization whose **current** role holds `share:create` (read from Better Auth on every resolution, never stored). |
282
+ | `scope:<kind>:<role>` | `created_by` still proves that scope role on the link's scope instance: the relationship probe the scope gate runs returns exactly one row, in the link's organization. |
283
+
284
+ Remove the creator from the organization, move them to a role without
285
+ `share:create`, or soft-delete their relationship row, and every link they
286
+ minted stops working — and with it every request that was admitted only through
287
+ those links. Restore the role or the row and the links work again (revoke them
288
+ to end them for good). The routes above always record `org` (they are gated on
289
+ `share:create`); `ctx.fga.share` records whichever edge the caller has.
290
+
291
+ #### Minting from an action: `ctx.fga.share`
292
+
293
+ The FGA routes gate on a Better Auth organization role. When the people who
294
+ share are not organization members — event crew admitted through a
295
+ [scope role](/define/scopes), say — mint from an action instead. The action's
296
+ `access` decides who may call; `ctx.fga.share` does the same work as the
297
+ routes (one implementation, `src/lib/fga/share-links.ts`) and records the
298
+ creator edge:
299
+
300
+ {/* doc-compile: skip — action body over the generated ctx.fga.share client */}
301
+ ```ts
302
+ export default defineAction({
303
+ path: '/event/:eventId/agenda-items/share', method: 'POST',
304
+ input: z.object({ id: z.string(), kind: z.enum(['participants', 'kitchen']) }),
305
+ access: { roles: ['member+', 'scope:event:organizer'] },
306
+ async execute({ input, ctx }) {
307
+ const relation = input.kind === 'kitchen' ? 'kitchen_viewer' : 'participant_viewer';
308
+ // { id, token, url, object, relation, scope, expiresAt, restrict, createdVia } — token and url once.
309
+ return ctx.fga.share.mint({ object: 'agenda_item:' + input.id, relation, ttlSeconds: 86_400 });
310
+ },
311
+ });
312
+ ```
313
+
314
+ | Call | Returns |
315
+ | --- | --- |
316
+ | `mint({ object, relation, ttlSeconds?, restrict? })` | `{ id, token, url, object, relation, scope, expiresAt, restrict, createdVia }`. The token and URL exist only here. |
317
+ | `list({ object? })` | `[{ id, object, relation, scope, restrict, expiresAt, revokedAt, active, createdAt, createdBy, createdVia }]` — never a token or URL. |
318
+ | `revoke({ id })` | `{ id, revoked: true }`. Sets `revoked_at` and deletes the link's tuples. |
319
+ | `revokeByToken(token)` | Same, for a client that still holds the token (hashed and looked up, never stored). |
320
+
321
+ `ctx.fga.share` exists wherever `ctx.fga` does. The creator edge is chosen at
322
+ mint, in this order, and the mint is refused when neither applies:
323
+
324
+ 1. The caller holds a role with `share:create` in the link's organization
325
+ (`ctx.activeOrgId`) — `created_via = 'org'`.
326
+ 2. The object is scope-placed and `ctx.scope.<kind>` names **that** instance
327
+ with a user-provable role of the kind (first in precedence order) —
328
+ `created_via = 'scope:<kind>:<role>'`. A crew member of event A cannot
329
+ mint for event B's rows, and an org-level object has no scope edge.
330
+
331
+ Errors surface as action errors (`application/problem+json`, `layer:
332
+ 'action'`):
333
+
334
+ | Code | Status | When |
335
+ | --- | --- | --- |
336
+ | `FGA_LINK_INPUT` | 400 | Malformed `object`, a relation that does not list `link`, a bad `ttlSeconds` (a masked table's cap applies) or `restrict`. |
337
+ | `FGA_LINK_CREATOR` | 403 | No creator edge: no `share:create` role here and no scope role on the object's instance, or a sessionless principal. |
338
+ | `FGA_LINK_NOT_FOUND` | 404 | The object is not live in this organization (also a target deleted during the mint); an unknown link id or token on revoke. |
339
+ | `FGA_LINK_PRINCIPAL` | 403 | A link principal called `mint`, `list` or `revoke`. |
279
340
 
280
341
  #### Opening a link
281
342
 
@@ -289,10 +350,14 @@ the links work again (revoke them to end them for good).
289
350
  cannot plant a cookie). The exchange sets a short-lived `HttpOnly` cookie
290
351
  `qb_share` holding a signed link id — never the token — and the page moves
291
352
  to the clean URL `/share/v1/link`.
292
- An IP that has spent its failed-lookup budget is refused (429) before any
293
- hash or database query; valid lookups never spend budget.
294
- 2. `GET /share/v1/link` re-checks the link's tuple and returns `{ link, record }`:
295
- what the link grants and the `resources.<type>.fields` projection of its
353
+ Once the failed-lookup budget is spent, a further guess is answered 429;
354
+ valid lookups never spend it and never wait behind it (see
355
+ [Rate limits](#rate-limits)).
356
+ 2. `GET /share/v1/link` re-checks the link's tuple and returns what the link
357
+ grants plus one of two things: `{ link, landing: { method, path } }` when
358
+ `resources.<type>.landing` names a record action for the link's relation
359
+ (see [Landing on a record action](#landing-on-a-record-action)), else
360
+ `{ link, record }` with the `resources.<type>.fields` projection of the
296
361
  object (never a soft-deleted row). A signed-in visitor sees it too.
297
362
  3. Every later request carries the cookie. API clients send the token in the
298
363
  `x-share-token` header instead.
@@ -382,16 +447,142 @@ instance:
382
447
  `?include=` on the object's own routes still see the link's organization:
383
448
  they are joined to the shared row by foreign key.
384
449
 
450
+ **Which columns.** The compiler reads the object table's id, organization and
451
+ scope columns itself, for q-DSL and raw-drizzle tables alike:
452
+
453
+ | Column | q-DSL table | Raw-drizzle table (`sqliteTable`) |
454
+ | --- | --- | --- |
455
+ | id | `q.id()` | the column with `.primaryKey()` |
456
+ | organization | `q.scope('organization')` | the firewall's organization arm (`{ field: 'organizationId', equals: 'ctx.activeOrgId' }`), else the auto-detected isolation column when no firewall is written |
457
+ | scope | `q.scope('event')` | the `{ field: 'eventId', equals: 'ctx.scope.event' }` firewall arm |
458
+
459
+ An `any:` firewall (`organizationId = ctx.activeOrgId` **or** `eventId =
460
+ ctx.scope.event`) is read the same way tenancy reads it: the table is
461
+ organization-scoped and event-placed. A scope arm on the primary key (`{ field:
462
+ 'id', equals: 'ctx.scope.event' }`) marks the instance table itself, not a
463
+ placement. Override the reading per type when a table spells things
464
+ differently; a name may be the JS property or the SQL column, and `scope: null`
465
+ pins an org-level placement on a table that also carries a scope arm:
466
+
467
+ {/* doc-compile: skip — fragment of authz.fga.sharing */}
468
+ ```ts
469
+ resources: {
470
+ agenda_item: { table: 'agendaItems' }, // read from meta + firewall
471
+ sheet: { table: 'sheets', orgColumn: 'tenantRef', scope: { kind: 'event', column: 'evtId' } },
472
+ note: { table: 'notes', scope: null }, // org-level, even with a scope arm
473
+ }
474
+ ```
475
+
385
476
  Compile errors:
386
477
 
387
478
  - A type with `link` relations and no `sharing.resources.<type>` entry.
388
- - A `resources.<type>.table` without a `q.scope('organization')` column.
479
+ - A `resources.<type>.table` with no organization column the compiler can
480
+ read (no `q.scope('organization')`, no organization firewall arm, no
481
+ auto-detected isolation column) and no `orgColumn`; an `idColumn`,
482
+ `orgColumn` or `scope.column` naming a column the table does not have; a
483
+ `scope.kind` of `organization`, `owner` or `team`; two placement scopes on
484
+ one table without a `scope` override.
389
485
  - A table that declares `masking` while `sharing.ttlSeconds` is unset or 0 —
390
486
  every link to personal data must expire. At mint, `ttlSeconds: 0` or a value
391
487
  above `sharing.ttlSeconds` is a 400 for those types.
392
488
  - `link` relations without `sharing.enabled`, or without the Better Auth
393
489
  organization plugin.
394
490
 
491
+ #### Landing on a record action
492
+
493
+ A projection is one row's columns. A roster, a kitchen sheet, a report is a
494
+ **record action** on the object's table — a join, an aggregate, a masked
495
+ rendering — and a link can land on one. Declare the landing per relation:
496
+
497
+ {/* doc-compile: skip — fragment of authz.fga.sharing */}
498
+ ```ts
499
+ resources: {
500
+ agenda_item: {
501
+ table: 'agendaItems',
502
+ landing: { participant_viewer: 'participants', kitchen_viewer: 'kitchen' },
503
+ },
504
+ }
505
+ ```
506
+
507
+ {/* doc-compile: skip — action body; listParticipants is the app's own reader */}
508
+ ```ts
509
+ // features/agenda-items/actions/participants.ts — link-only: staff keep their own roster route.
510
+ export default defineAction({
511
+ description: 'Participant roster of a shared activity',
512
+ method: 'GET',
513
+ input: z.object({}),
514
+ access: { fga: { relation: 'participant_viewer', object: 'agenda_item:{id}' } },
515
+ async execute({ record, ctx, db }) {
516
+ // ctx.link.relation says which link opened this; ctx.scope.event is the object's event.
517
+ return listParticipants(db, record);
518
+ },
519
+ });
520
+ ```
521
+
522
+ `GET /share/v1/link` then answers
523
+ `{ link, landing: { method: 'GET', path: '/api/v1/event/evt_1/agenda-items/ai_9/participants' } }`
524
+ — the concrete URL, with the object id and the link's scope instance filled
525
+ in. The client makes **that** request with the same credential (cookie or
526
+ `x-share-token`), so the record action's own pipeline runs: the link marker,
527
+ the table firewall (the scope lock), the `fga` arm, masking and audit. The
528
+ landing never executes the action in-process. A relation without a landing
529
+ falls back to `fields`; `fields` and `landing` may coexist and the landing
530
+ wins for its relations.
531
+
532
+ When the table is claimed by a [namespace](/define/areas) (its `path` sits
533
+ under the prefix, as `/event/:eventId/agenda-items` does), the landing runs
534
+ behind the namespace gate. The gate admits a link principal only when the
535
+ link's scope is the namespace's kind and the instance in the path
536
+ (`link.scope` is `{ kind: 'event', id: 'evt_1' }` for `/event/evt_1/…`), in
537
+ tenant mode the link's organization is the object's, and the matched route
538
+ admits links of the link's object type — the landing, or another route with
539
+ an `fga` arm for that type. It passes with `ctx.lane = 'link'`, no roles and
540
+ no scope role; the gate's `loads` hydration still runs (`ctx.event`), through
541
+ the loaded table's firewall evaluated with the link's organization for that
542
+ one pinned read. A link minted for another instance, or with no scope
543
+ instance, gets the gate's `403 ACCESS_ROLE_REQUIRED`, the same answer as a
544
+ caller who proves no lane. On every other route under the prefix the
545
+ credential is dropped and the request runs as the caller it replaced
546
+ (anonymous: `401`).
547
+
548
+ Compile errors: the landing names something that is not a record action on
549
+ the type's table (a standalone action never runs as a link principal); the
550
+ action's access has no `fga` arm for exactly that type and relation (an arm
551
+ for another relation does not count); the relation does not list `link`; or
552
+ the table's `path` has a parameter other than the scope kind's
553
+ `requestField` (`:eventId`), which a link cannot supply.
554
+
555
+ #### Rate limits
556
+
557
+ Two keyed policies guard the share surface, under `sharing.links.rateLimit`.
558
+ Neither is keyed on the client IP by default: a venue puts hundreds of people
559
+ behind one NAT, and a guessed token is always a new key.
560
+
561
+ | Policy | Counts | Default | Keys |
562
+ | --- | --- | --- | --- |
563
+ | `failed` | Failed token lookups (header, exchange, open). A valid lookup never spends it. Spent, a `global` key caps what guesses are answered with (429, nothing more spent) until the window turns — a valid link never waits behind someone else's guesses; a spent `ip` key is refused before any hash or database query, since that address is the guesser. | `{ key: 'global', limit: 600, period: 60 }` | `global`, `ip` |
564
+ | `success` | Requests a resolved link serves: the exchange, the landing, every cookie or header request. | `{ key: 'link', limit: 600, period: 3600 }` | `link`, `global`, `ip` |
565
+
566
+ A `period` of 10 or 60 seconds runs on a Cloudflare rate-limit binding
567
+ (provisioned by the compiler, fixed at deploy). Any other period runs as a
568
+ fixed window on the project's `KV` binding (`qbrl:fga-share:…` keys, self
569
+ expiring). Set a policy to `false` to drop it, or `rateLimit: false` for both.
570
+ `rateLimitPerMinute` (the old per-IP budget) still compiles, with a warning.
571
+ A missing binding or `KV` makes the policy a no-op, like every other rate
572
+ limit. Over the cap: `429 AUTH_RATE_LIMITED` with `details.policy` and the
573
+ window.
574
+
575
+ At runtime the var or secret `FGA_SHARE_RATE_POLICY` overrides either policy
576
+ without a build — JSON of the same shape, e.g.
577
+ `{"success":{"key":"link","limit":100,"period":3600}}` or `{"failed":false}`.
578
+ An overridden policy runs on `KV` whatever its period; a malformed value
579
+ changes nothing.
580
+
581
+ **CORS.** The generated CORS preflight pins no header list, so a browser on a
582
+ share origin (`share.acme.dev` calling `api.acme.dev`) is allowed to send
583
+ `x-share-token`: the preflight mirrors the requested headers. Nothing to
584
+ configure.
585
+
395
586
  #### Restricted links
396
587
 
397
588
  Add `restrict` at mint to also require a signed-in user:
@@ -560,15 +751,21 @@ erroring). The DSL accepts `#` comments.
560
751
  - With [database per tenant](/configure/tenant-databases#fga)
561
752
  (`tenancy.isolation: 'durable-object'`), tuples live in each organization's
562
753
  object. `ctx.fga` works in tenant actions and `/fga/v1` is forwarded there.
563
- `sharing`, `membership` and `access: { fga }` arms are not supported yet.
564
-
565
- - Link sharing requires compiler-managed table metadata. Scoped link sharing
566
- also requires a managed organization-scoped parent, resolved through
567
- `authz.scopes.<kind>.instance` or the existing unambiguous scope-instance
568
- FK/firewall mapping. An unresolved or ambiguous parent fails compilation
569
- with an actionable mapping error. This requirement applies to link sharing,
570
- not unrelated `q.scope()` columns. Multiple placement scopes on one shared
571
- table are currently rejected.
754
+ Link subjects are supported tenant-local (the link row and its tuple live in
755
+ the object; the edge resolves through a hashed lookup and one command; the
756
+ stored token hash is `SHA-256(token)` there) and `access: { fga }` arms are
757
+ allowed on tenant tables; signed `user:*` share tokens and `membership`
758
+ are not supported. See [Share links](/configure/tenant-databases#share-links).
759
+
760
+ - Scoped link sharing requires an organization-scoped parent (the scope
761
+ instance table), resolved through `authz.scopes.<kind>.instance` or the
762
+ existing unambiguous scope-instance FK/firewall mapping. The parent may be
763
+ a q-DSL or a raw-drizzle table; its columns are read the same way as the
764
+ object's (see [Placement](#placement-two-locks)). An unresolved or
765
+ ambiguous parent fails compilation with an actionable mapping error. This
766
+ requirement applies to link sharing, not unrelated `q.scope()` columns.
767
+ Multiple placement scopes on one shared table are rejected unless
768
+ `resources.<type>.scope` picks one.
572
769
  - Apply the generated trigger migration before serving link routes. Object
573
770
  deletion (soft or hard), identity/organization/scope reassignment, and parent
574
771
  deletion remove the affected links and tuples. Restoring a soft-deleted row