@quickback-dev/cli 0.72.2 → 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.2";
13
+ const CLI_VERSION = "0.72.4";
14
14
  function getPackageVersion() {
15
15
  return CLI_VERSION;
16
16
  }
@@ -303,6 +303,70 @@ throw new ActionError("Not enough balance", "INSUFFICIENT_FUNDS", 400, { availab
303
303
 
304
304
  Constructor: `(message, code, statusCode = 400, details?)`. Do **NOT** throw Hono's `HTTPException` — it isn't unwrapped and surfaces as a 500 `ACTION_EXECUTION_FAILED`. Returning `c.json({...}, 400)` directly also works (the executor receives `c`).
305
305
 
306
+ ## Custom CMS pages (`definePage`)
307
+
308
+ Reach for a custom page before building a separate admin app. The CMS gives every table a list and record view. When the job is *working across two tables* (reconciling, matching, assigning, triaging), one `definePage()` file gives the operator a split-panel screen with drag-and-drop, scored match suggestions, and a button that runs a real action. You write no UI code.
309
+
310
+ Good fits: bank transactions ↔ ledger entries, applicants ↔ open roles, support tickets ↔ agents, imported rows ↔ existing records, invoices ↔ payments.
311
+
312
+ ```ts
313
+ // quickback/features/banking/pages/bank-reconciliation.ts
314
+ import { definePage } from "@quickback/compiler";
315
+
316
+ export default definePage({
317
+ slug: "bank-reconciliation", // lowercase, digits, hyphens
318
+ title: "Bank Reconciliation",
319
+ feature: "banking",
320
+ access: { roles: ["owner", "admin"] },
321
+ dataSources: {
322
+ bank: { table: "bankTransaction", defaultFilters: { status: "pending" }, displayColumns: ["date", "description", "amount"] },
323
+ ledger: { table: "ledgerEntry", defaultSort: { field: "date", order: "desc" }, displayColumns: ["date", "memo", "amount"] },
324
+ },
325
+ layout: {
326
+ type: "split-panel",
327
+ panels: [
328
+ { id: "bank", title: "Bank", dataSource: "bank", position: "left", features: ["drag-source"] },
329
+ { id: "ledger", title: "Ledger", dataSource: "ledger", position: "right", features: ["drop-target"] },
330
+ ],
331
+ },
332
+ matching: {
333
+ enabled: true,
334
+ confidenceThreshold: 0.5,
335
+ rules: [
336
+ { name: "Amount", weight: 0.5, condition: { left: "bank.amount", right: "ledger.amount", operator: "abs-equals" } },
337
+ { name: "Date", weight: 0.3, condition: { left: "bank.date", right: "ledger.date", operator: "within-days", value: 7 } },
338
+ { name: "Memo", weight: 0.2, condition: { left: "bank.description", right: "ledger.memo", operator: "fuzzy-match" } },
339
+ ],
340
+ },
341
+ pageActions: {
342
+ reconcile: {
343
+ table: "bankTransaction", action: "reconcile", label: "Reconcile",
344
+ confirm: "Match this transaction to the selected entry?",
345
+ inputMapping: { transactionId: "bank.$id", ledgerEntryId: "ledger.$id" },
346
+ },
347
+ },
348
+ });
349
+ ```
350
+
351
+ How to craft one:
352
+
353
+ 1. **Write the action first.** A page only *calls* actions; it never writes data itself. Define `actions/reconcile.ts` on the target table, with its own `access`, guards, and input schema, then map page fields into its input with `inputMapping` (`"<dataSource>.$<field>"`; `$id` is the record id). Dropping a row from the drag-source panel onto a row in the drop-target panel opens the first page action's dialog, with both records as context.
354
+ 2. **Narrow each panel.** `defaultFilters` (e.g. `status: "pending"`) keeps the panels to the work still to do, and `displayColumns` keeps them readable (the default is just `id`).
355
+ 3. **Weight the match rules to sum to 1.** Each weight and `confidenceThreshold` must be within 0–1. Operators: `abs-equals` (amounts with opposite signs), `within-days` (`value` = max days, default 7), `fuzzy-match` (word overlap). The score is the weighted average; suggestions below the threshold are hidden.
356
+ 4. **`access.roles` on a page only controls who sees it** (it's checked in the browser). Panels read through each table's normal list endpoint, and buttons call each action's endpoint, so the tables' Firewall/Access/Masking rules still decide what data comes back and what can change. Never rely on page `access` to hide data.
357
+
358
+ One page per file in `features/<feature>/pages/`; the compiler validates slugs, data-source references and weights at compile time. Only `split-panel` exists as a layout today. Details: `quickback docs ui/admin/pages`.
359
+
360
+ ## Clients that stay fast on slow networks
361
+
362
+ Each round trip costs ~150 ms on a slow phone connection. When you build or change the client that calls the API, count the requests it makes before the first useful paint:
363
+
364
+ - **One request per screen.** A screen that needs more than two lists gets a `defineBundle`, not several list calls (`quickback docs define/bundles`). Never fetch records one at a time in a loop from the client. Use `?include=` for parents, and a filtered list for children.
365
+ - **Start fetches in the route, not the component.** Fetch in the router's `loader` (TanStack Router: `loader: () => queryClient.ensureQueryData(...)`), so the request starts during navigation instead of after the component mounts. Set `defaultPreload: 'intent'` so hovering or focusing a link starts its code and data early.
366
+ - **Run independent awaits in parallel.** In actions and hooks, start unrelated lookups together with `Promise.all([...])`. Two sequential `await`s that don't depend on each other add a full round trip each time.
367
+ - **Link previews read only the HTML.** iMessage, Slack, and similar bots never run JavaScript. A prebuilt `apps.<name>` SPA must put its `<title>` and `og:*` meta tags in `index.html` itself.
368
+ - **Don't trust the User-Agent for routing.** Anyone can fake it, and it also matches Lighthouse. If bots really must get a different response, use Cloudflare's verified-bot signal: `request.cf.botManagement.verifiedBot` on Bot Management plans, or the `cf.client.bot` field in a WAF rule.
369
+
306
370
  ## Reaching auth tables (org members, users)
307
371
 
308
372
  The scoped feature `db` never includes Better Auth tables — that is by design.
@@ -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