@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.
@@ -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
@@ -97,9 +97,11 @@ interface ReadConfig {
97
97
  // and the HYPERDRIVE_CACHED binding. See Neon → Cached public reads.
98
98
  cache?: "hyperdrive";
99
99
 
100
- // Pagination defaults for collection reads.
101
- pageSize?: number; // Default page size (default: 50)
102
- maxPageSize?: number; // Hard cap (default: 100)
100
+ // Pagination for the collection GET and every view (one setting per
101
+ // resource). `?limit=` above maxPageSize is clamped to it; OpenAPI
102
+ // documents both. A pageSize above 100 raises the cap with it.
103
+ pageSize?: number; // Default `limit` (default: 50)
104
+ maxPageSize?: number; // Hard cap on `limit` (default: 100)
103
105
 
104
106
  // Named field projections. Each view has its own access and field list.
105
107
  views?: {
@@ -114,8 +116,8 @@ interface ReadConfig {
114
116
  interface ViewConfig {
115
117
  fields: string[]; // Columns returned by this view
116
118
  access?: Access; // Per-view access (falls back to read.access)
117
- pageSize?: number;
118
- maxPageSize?: number;
119
+ // No per-view pagination: read.pageSize / read.maxPageSize apply to every
120
+ // view, and a view-level copy is a compile error.
119
121
  }
120
122
  ```
121
123
 
@@ -99,7 +99,11 @@ before the stale-claim takeover, so a foreign caller can neither read nor
99
99
  overwrite your claim.
100
100
 
101
101
  **Unauthenticated requests carrying the header are rejected (400)** — an
102
- anonymous caller has no principal to bind the claim to. A PUBLIC standalone
102
+ anonymous caller has no principal to bind the claim to. Better Auth's own
103
+ routes (`/auth/v1/*` and `/cli/*`) are the exception: Better Auth
104
+ authenticates them itself, so the header is ignored there rather than
105
+ rejected, and a client can attach it to every write. The operator endpoints
106
+ mounted under the auth prefix still honor it. A PUBLIC standalone
103
107
  action may opt in explicitly:
104
108
 
105
109
  ```ts title="quickback/features/orders/actions/submitForm.ts"
@@ -110,6 +110,31 @@ Missing keys fall through to the built-in defaults from the vendored plugin (`sr
110
110
 
111
111
  > **Provider scope.** Overrides are only honored when `email.provider: 'aws-ses'`. The Cloudflare Email path uses the helper's own template pipeline and ignores `plugins.emailOtp.templates`.
112
112
 
113
+ ### OTP Message Headers
114
+
115
+ Every emailOTP send — default or custom template — carries two headers:
116
+
117
+ | Header | Value | Why |
118
+ |--------|-------|-----|
119
+ | `Auto-Submitted` | `auto-generated` | [RFC 3834](https://www.rfc-editor.org/rfc/rfc3834): machine mail, so vacation responders and ticketing systems don't reply to it. |
120
+ | `OTP-Token` | `"<otp>"; origin="<origin of APP_URL, else ACCOUNT_URL>"` | [draft-goto-otp-token](https://www.ietf.org/archive/id/draft-goto-otp-token-01.html): the code in machine-readable, origin-bound form, so a mail client can offer it only on the site that asked for it. Omitted when the origin is not `http(s)`. |
121
+
122
+ `OTP-Token` is an individual Internet-Draft, not a standard. Gmail's "Copy code" button currently finds codes heuristically, so keep the code near the top of both the HTML and text parts as well.
123
+
124
+ A template can add, replace or drop headers by returning `headers` next to `{ subject, html, text }`. A `null` value removes a default:
125
+
126
+ ```typescript
127
+ // quickback/email-templates/sign-in.ts — bind the code to the app the user signs in on
128
+ export default ({ otp, appName, appOrigin }: { otp: string; appName: string; appOrigin: string }) => ({
129
+ subject: `Sign in to ${appName}`,
130
+ html: `<p>Your code: <b>${otp}</b></p>`,
131
+ text: `Your code: ${otp}`,
132
+ headers: { 'OTP-Token': `"${otp}"; origin="${appOrigin}"` },
133
+ });
134
+ ```
135
+
136
+ (`appOrigin` here comes from a [`resolve-email-context` hook](/ui/account/hooks), which receives `env`.) Header names the sender owns — `From`, `To`, `Cc`, `Bcc`, `Reply-To`, `Subject`, `Date`, `Message-ID`, `MIME-Version`, `Content-*`, `Resent-*`, `Return-Path`, `Received`, `DKIM-Signature` — are ignored, and so is any value that is not one line of printable ASCII. A send with headers goes out through SES `SendRawEmail` (the simple `SendEmail` action cannot set them); sends without headers are unchanged.
137
+
113
138
  ## Configuration
114
139
 
115
140
  The compiler wires the plugin into `src/lib/auth.ts` automatically. The generated `getSESConfig(env)` maps environment to the vendored plugin's options:
@@ -878,6 +878,15 @@ for stub errors:
878
878
  | `Subrequest depth limit exceeded` | Not retried; logged as `durable_object.failed` |
879
879
  | anything else | Not retried; logged as `durable_object.failed` |
880
880
 
881
+ Every call into the Broadcaster (the publish including its one retry, the
882
+ live-view `seq` read, and in separate-Worker mode the service-binding fetch)
883
+ also races a **5-second deadline**. A stalled Broadcaster therefore costs the
884
+ emitting request at most 5 seconds, not the client's whole timeout, even
885
+ though the write has already committed. An expired call is logged like any other
886
+ failed publish (`durable_object.failed` for the inline stub), and the tenant
887
+ outbox treats it as retryable. If the
888
+ first attempt lands late, the publish id dedupes it.
889
+
881
890
  Every send carries one **publish id**, and a retry reuses it. The Broadcaster
882
891
  remembers its 64 most recent ids. When a retry arrives for a first attempt that
883
892
  actually landed (only the reply was lost), it is acknowledged without a second
@@ -330,6 +330,7 @@ dead letter queue) is identical across providers.
330
330
  ## See Also
331
331
 
332
332
  - [Inbound Webhooks](/platform/webhooks/inbound) — Receive webhooks from external services
333
+ - [MCP Events](/configure/agents#mcp-events) — ChatGPT subscriptions that ride this store and queue
333
334
  - [Queues](/platform/queues) — Background processing infrastructure
334
335
 
335
336
  ## Standard Webhooks signing
@@ -34,7 +34,7 @@ Each file has a single default export — an `async (entity, ctx) => ...` functi
34
34
  | `after-admin-user-create.ts` | `databaseHooks.user.create.after` (filtered) | `User` | `void` |
35
35
  | `before-invitation-create.ts` | `organizationHooks.beforeCreateInvitation` | `{ invitation, inviter, organization }` | `void \| { data?: Partial<Invitation> }` |
36
36
  | `resolve-oauth-context.ts` | OAuth bearer middleware | OAuth identity + session | Partial `AppContext` tenant fields |
37
- | `resolve-email-context.ts` | emailOTP `sendVerificationOTP` | `{ email, type, name }` | Extra fields merged into the email template context |
37
+ | `resolve-email-context.ts` | emailOTP `sendVerificationOTP` | `{ email, type, name, env }` | Extra fields merged into the email template context |
38
38
  | `before-auth-request.ts` | `hooks.before` (every auth endpoint) | `(ctx, env, { APIError })` | `void` — throw an `APIError` to refuse |
39
39
  | `after-auth-request.ts` | `hooks.after` (every auth endpoint) | `(ctx, env)` | `void` — failures are logged, never thrown |
40
40
 
@@ -178,7 +178,7 @@ add `quickback/hooks/resolve-email-context.ts`. The emailOTP send calls it for
178
178
  each recipient and **spreads the returned object into your email templates**.
179
179
 
180
180
  ```ts title="quickback/hooks/resolve-email-context.ts"
181
- export default async ({ email, type, name, db, schema, eq, and }) => {
181
+ export default async ({ email, type, name, env, db, schema, eq, and }) => {
182
182
  // Is this recipient a member of any organization?
183
183
  const [u] = await db.select({ id: schema.user.id })
184
184
  .from(schema.user).where(eq(schema.user.email, email)).limit(1);
@@ -208,6 +208,9 @@ Notes:
208
208
  fixed signature; convert a type to a [custom template](/platform/auth/plugins/aws-ses#per-type-template-overrides) to consume the extra context.
209
209
  - `db`, `schema`, `eq`, and `and` are passed in (the same Drizzle handle Better
210
210
  Auth uses) so you can look the recipient up without an import.
211
+ - `env` is the Worker's bindings, so the context can carry environment-specific
212
+ values — e.g. the origin a template binds its
213
+ [`OTP-Token` header](/platform/auth/plugins/aws-ses#otp-message-headers) to.
211
214
  - This is **not** a Better Auth `databaseHook` — it's consumed only by the
212
215
  emailOTP send, so it adds no signup/session latency.
213
216
 
@@ -120,7 +120,7 @@ export default defineConfig({
120
120
  ```
121
121
 
122
122
  When you run `quickback build`, the CLI:
123
- 1. Builds the CMS SPA from source and places assets in `src/apps/cms/`
123
+ 1. Copies the prebuilt CMS SPA into `src/apps/cms/` (the compiler ships one generic bundle; per-project settings reach it at serve time)
124
124
  2. Adds `[assets]` config to `wrangler.toml` with `run_worker_first = true`
125
125
  3. Generates Worker routing to serve the CMS SPA
126
126
 
@@ -139,8 +139,8 @@ This adds a custom domain route to `wrangler.toml`. Both `api.example.com` and `
139
139
  CMS access defaults to `access: "sysadmin"` — only `user.role === "sysadmin"` (the cross-tenant data-plane tier) can use `/cms/*`. Set `access: "member"` to also admit anyone holding an organization membership. `user.role === "appmanager"` opens the CMS in neither mode: it is the control-plane tier and belongs at `/account/admin`. The gate is enforced at multiple layers:
140
140
 
141
141
  - **Account UI** hides the "Go to CMS" button for callers outside those roles.
142
- - **CMS SPA shell** — the Worker returns `403` (or redirects unauthenticated requests to login) before serving `index.html` to a non-operator. A non-operator who types the CMS URL directly cannot load the app.
143
- - **`/api/v1/schema`** returns `403 Platform operator access required` to callers outside those roles, so schema metadata can't be scraped by hitting the API directly.
142
+ - **CMS SPA shell** — the Worker redirects unauthenticated requests to login. Sign-in is the only shell-level gate; the app itself is a generic bundle. For a caller `/api/v1/schema` would admit, the Worker also inlines the schema registry in the shell as a non-executing `<script type="application/json" id="__qb-cms-bootstrap">` block, so the CMS starts without fetching it. The block uses the same admission check as `/api/v1/schema`, so it never carries anything that route would refuse. With [Cloudflare Access](/configure/cloudflare-access), it is inlined only when `/api/v1/schema` needs no Access application or the same one the shell request passed. The CMS shell is served `Cache-Control: private, no-store`.
143
+ - **`/api/v1/schema`** returns `401 AUTH_MISSING` to anonymous callers `403 CMS_ACCESS_DENIED` (naming the role required) to signed-in callers outside those roles, and `403 MFA_REQUIRED` to an operator whose session lacks the second factor `auth.operatorMfa` demands, so schema metadata can't be scraped by hitting the API directly.
144
144
  - **`custom_view` routes** are gated on `userRole: ["appmanager"]` rather than org membership, so saved views can't be listed or modified without platform-control-plane rights.
145
145
  - **In-SPA screen** — a signed-in caller who isn't admitted is served the shell and shown a screen naming what they'd need. There is no wrong-role redirect.
146
146
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quickback-dev/cli",
3
- "version": "0.72.2",
3
+ "version": "0.72.4",
4
4
  "description": "CLI for Quickback — define your backend in TypeScript, compile to a fully wired Cloudflare Worker (or Bun / Node) with auth, database, migrations, security, CMS, and Account UI.",
5
5
  "author": "Kardoe Incorporated <paul@kardoe.com>",
6
6
  "license": "MIT",
@@ -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.