@quickback-dev/cli 0.47.9 → 0.47.11

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.
@@ -1,6 +1,6 @@
1
1
  # Auth Hooks
2
2
 
3
- Quickback discovers project-level auth hooks at `quickback/hooks/` and wires them into [Better Auth's `databaseHooks`](https://www.better-auth.com/docs/concepts/database#database-hooks). Use them for post-signup bootstrap, signup gating, and other lifecycle work.
3
+ Quickback discovers project-level auth hooks at `quickback/hooks/`. The `before-`/`after-` lifecycle hooks wire into [Better Auth's `databaseHooks`](https://www.better-auth.com/docs/concepts/database#database-hooks); the `resolve-*` hooks are trusted server resolvers called from generated middleware (OAuth) or the email send, not databaseHooks. Use them for post-signup bootstrap, signup gating, tenant resolution, and per-recipient email context.
4
4
 
5
5
  The classic case is multi-tenant: when `account.auth.organizations: true` is set, a freshly signed-up user has no `activeOrganizationId`, so every authenticated `/api/v1/*` returns `403 ORG_REQUIRED`. An `after-user-create` hook can auto-provision a personal workspace + member row so the next request just works.
6
6
 
@@ -13,6 +13,8 @@ quickback/
13
13
  before-user-create.ts
14
14
  after-session-create.ts
15
15
  after-admin-user-create.ts
16
+ resolve-oauth-context.ts
17
+ resolve-email-context.ts
16
18
  ```
17
19
 
18
20
  Each file has a single default export — an `async (entity, ctx) => ...` function. The filename determines which Better Auth event the hook fires on.
@@ -26,6 +28,7 @@ Each file has a single default export — an `async (entity, ctx) => ...` functi
26
28
  | `after-session-create.ts` | `databaseHooks.session.create.after` | `Session` | `void` |
27
29
  | `after-admin-user-create.ts` | `databaseHooks.user.create.after` (filtered) | `User` | `void` |
28
30
  | `resolve-oauth-context.ts` | OAuth bearer middleware | OAuth identity + session | Partial `AppContext` tenant fields |
31
+ | `resolve-email-context.ts` | emailOTP `sendVerificationOTP` | `{ email, type, name }` | Extra fields merged into the email template context |
29
32
 
30
33
  `after-admin-user-create.ts` is a **virtual event** — it wires into the same Better Auth `user.create.after` slot as the generic `after-user-create.ts`, but the compiler wraps the call in a runtime filter on the BA context path so it only fires when the row was created via the admin plugin's `POST /admin/create-user` endpoint. Use it for first-time-user provisioning (welcome email, default org assignment) without inspecting `_baCtx?.context?.path` by hand. The generic `after-user-create.ts` still runs for every signup, including admin-created ones.
31
34
 
@@ -53,6 +56,49 @@ The returned object is merged into the standard `AppContext`. The compiler
53
56
  always preserves the validated `authenticated`, `userId`, and `user` fields,
54
57
  so this hook cannot replace the OAuth identity.
55
58
 
59
+ ## Email context resolver
60
+
61
+ Better Auth routes OTP emails by **type** (`sign-in`, `email-verification`,
62
+ `forget-password`), not by audience, and a template only receives fixed
63
+ `appName` / `appUrl` / `supportEmail`. When you need **per-recipient** context —
64
+ a branded palette for organizers vs. attendees, a plan tier, a locale —
65
+ add `quickback/hooks/resolve-email-context.ts`. The emailOTP send calls it for
66
+ each recipient and **spreads the returned object into your email templates**.
67
+
68
+ ```ts title="quickback/hooks/resolve-email-context.ts"
69
+ export default async ({ email, type, name, db, schema, eq, and }) => {
70
+ // Is this recipient a member of any organization?
71
+ const [u] = await db.select({ id: schema.user.id })
72
+ .from(schema.user).where(eq(schema.user.email, email)).limit(1);
73
+ const isOrgMember = u
74
+ && (await db.select({ id: schema.member.id })
75
+ .from(schema.member).where(eq(schema.member.userId, u.id)).limit(1)).length > 0;
76
+
77
+ return { audience: isOrgMember ? "organizer" : "attendee" };
78
+ };
79
+ ```
80
+
81
+ Your [email template](/stack/auth/plugins/aws-ses#per-type-template-overrides) then reads the extra field:
82
+
83
+ ```ts title="quickback/email-templates/sign-in.ts"
84
+ export default ({ otp, appName, audience }) => ({
85
+ subject: `Your ${appName} code`,
86
+ html: renderOtp({ otp, theme: audience === "organizer" ? "eggplant" : "blue" }),
87
+ text: `Your code is ${otp}`,
88
+ });
89
+ ```
90
+
91
+ Notes:
92
+
93
+ - **Fail-open.** If the hook throws, the context falls back to `{}` and the OTP
94
+ still sends — a hook bug can never lock users out of sign-in.
95
+ - **Spread into user templates only.** The packaged default templates have a
96
+ fixed signature; convert a type to a [custom template](/stack/auth/plugins/aws-ses#per-type-template-overrides) to consume the extra context.
97
+ - `db`, `schema`, `eq`, and `and` are passed in (the same Drizzle handle Better
98
+ Auth uses) so you can look the recipient up without an import.
99
+ - This is **not** a Better Auth `databaseHook` — it's consumed only by the
100
+ emailOTP send, so it adds no signup/session latency.
101
+
56
102
  ## ctx shape
57
103
 
58
104
  Every hook receives `(entity, ctx)`:
@@ -10,6 +10,7 @@
10
10
  | [Storage](/stack/storage) | KV, R2 | Sessions, cache, files |
11
11
  | [Realtime](/stack/realtime) | Durable Objects | WebSocket for live updates |
12
12
  | [Queues](/stack/queues) | Cloudflare Queues | Background jobs, webhook delivery |
13
+ | [Schedules](/stack/schedules) | Cron Triggers | `defineSchedule` cron jobs, server-internal |
13
14
  | [Vector & AI](/stack/vector) | Workers AI | Embeddings, semantic search |
14
15
  | [Webhooks](/stack/webhooks) | Hono + Queues | Signed inbound, retried outbound |
15
16
  | [Quickback CMS](/stack/cms) | Embedded SPA | Schema-driven admin UI |
@@ -35,6 +36,11 @@
35
36
  │ │ Queues │ │ Better Auth │ │
36
37
  │ │ (Background)│ │ (Email OTP, Passkeys, etc.) │ │
37
38
  │ └─────────────┘ └─────────────────────────────────┘ │
39
+ │ │
40
+ │ ┌─────────────┐ │
41
+ │ │ Schedules │ │
42
+ │ │ (Cron) │ │
43
+ │ └─────────────┘ │
38
44
  └─────────────────────────────────────────────────────────────┘
39
45
  ```
40
46
 
@@ -163,6 +163,16 @@ bindings: {
163
163
  access: { resource: { feature: 'event-pages', table: 'eventPages', key: 'yjsRoomId' } },
164
164
  },
165
165
 
166
+ // Identity-gated room — the roomId IS the caller's own id, with no backing
167
+ // table. A per-user gateway / presence / inbox keyed on `ctx.userId`:
168
+ // auto-emits a gate at /realtime/user-gateway/* that 403s unless the room
169
+ // segment equals the authenticated user's id. Use `ctx.activeOrgId` for a
170
+ // per-org room. No DB query — it's a string compare against ctx.
171
+ {
172
+ name: 'UserGateway', className: 'UserGateway', from: 'lib/UserGateway',
173
+ access: { roomIdEquals: 'ctx.userId' },
174
+ },
175
+
166
176
  // Genuinely public room (no auth, no row lookup) — opt out explicitly.
167
177
  { name: 'PublicLobby', className: 'PublicLobby', from: 'lib/PublicLobby',
168
178
  access: 'public' },
@@ -176,6 +186,7 @@ What the compiler emits:
176
186
  - **`access: { resource: { feature, table } }`** — same gate, but the schema import + firewall alias are keyed off the pinned `table` instead of the feature name. Required when a feature owns more than one resourceful table; the access gate emit can't pick which table's firewall to query otherwise.
177
187
  - **`access: { resource: { feature, table, key } }`** — same gate, but it matches the roomId against `table.<key>` instead of `table.id`. Use it when the room is addressed by a unique non-PK column — e.g. a Yjs editor keyed by `event_pages.yjsRoomId` (`ns.idFromName(row.yjsRoomId)`). `key` defaults to `'id'`, so existing pins are unchanged. The compiler validates the column exists at compile time. `key` also works inside each multi-resource branch.
178
188
  - **Multi-resource form** — same gate but with a regex parser dispatching to per-kind firewall lookups. Unknown kinds 400 at the gate. Each `resources[kind].resource` accepts either form (string shorthand or `{ feature, table, key? }`).
189
+ - **`access: { roomIdEquals: 'ctx.userId' }`** — an **identity gate** for rooms with no backing table, where the roomId *is* the caller's own id. Emits `app.use('/realtime/<kebab>/*', …)` that 401s anonymous, 400s a missing segment, and 403s unless the decoded room segment equals `ctx.userId`. No schema import, no firewall, no DB query — a string compare against the server-resolved `ctx`. Use `'ctx.activeOrgId'` for a per-org room. This is the right gate for per-user gateways, presence, or inbox DOs keyed on `ns.idFromName(ctx.userId)`. Only `'ctx.userId'` and `'ctx.activeOrgId'` are accepted (validated at compile time); anything else is a build error. Distinct from `resource` because there's no row to firewall — it closes the cross-user hole that "no `access` declared" leaves open (any authenticated user could otherwise open another user's room via the catchall).
179
190
  - **`access: 'public'`** — `app.use('/realtime/<kebab>/*', …)` that just passes through. Use for anonymous game lobbies / public collab pads where the room itself is the unit of access.
180
191
  - **No `access` declared** — falls through to the catchall `/realtime/*` gate that just checks `ctx.authenticated`. (v0.11.1 behavior.)
181
192
 
@@ -189,6 +200,7 @@ If a room currently enforces access by hand inside `onConnect` / `onBeforeConnec
189
200
  2. **roomId is a unique non-PK column** (a slug, a `yjsRoomId`) → add `key`: `access: { resource: { feature, table, key: 'yjsRoomId' } }`.
190
201
  3. **one DO class serves several room kinds** (e.g. `conv-<id>` / `ticket-<id>`) → the multi-resource form with a `pattern` that captures the kind and id.
191
202
  4. **access depends on membership, not just tenant** (e.g. "is this user an attendee of the event that owns this page") → you do **not** need hand-written code. Declare the pinned table's firewall with a `via:` relationship; the gate runs the table's *full* `buildFirewallConditions`, relationship subqueries included.
203
+ 5. **roomId is the caller's own identity** (a per-user gateway/presence/inbox where the room *is* `ctx.userId`, with no backing table) → `access: { roomIdEquals: 'ctx.userId' }` (or `'ctx.activeOrgId'`). Do **not** enforce this inside the DO from request data — a Durable Object has no session and only sees client-settable headers, so trusting an `x-user-id` header lets any authenticated user open another user's room. The gate belongs at the Worker edge, which is exactly what this arm emits.
192
204
 
193
205
  The declarative gate runs the exact firewall the CRUD `GET /:id` handler enforces, with the same 401/403 semantics, *before* the WebSocket upgrade — so by the time `onConnect` fires the caller is already authorized. Dropping the hand-rolled check also closes a common gap: a room with no `access` block is reachable by **any** authenticated user who can guess a room id, regardless of tenant.
194
206
 
@@ -39,7 +39,25 @@ One file per schedule under `services/schedules/*.ts`. Files prefixed with `_` a
39
39
 
40
40
  ## Audit & trust
41
41
 
42
- Cron runs are **server-internal**: there's no authenticated user. The execute context runs with `ctx.internal = true` and an audit actor of **`system:cron-<name>`**, so any audited writes are attributable to the schedule that made them (e.g. `system:cron-sweepDigests`). Use `withInternalContext` when the schedule legitimately operates across tenants and needs to touch `INTERNAL`-gated resources.
42
+ Cron runs are **server-internal**: there's no authenticated user, no request, no org scope. A fired tick gets a plain `db` (unscoped Drizzle) plus a `withInternalContext` helper:
43
+
44
+ ```typescript
45
+ execute: async ({ db, withInternalContext }) => {
46
+ // `db` here is unscoped — no firewall WHERE, no audit actor.
47
+
48
+ // Opt into the INTERNAL trust zone for cross-tenant work:
49
+ await withInternalContext(async ({ ctx, db, services }) => {
50
+ // ctx.internal = true, ctx.userId = "system:cron-<name>"
51
+ // audited writes are attributable to e.g. system:cron-sweepDigests
52
+ });
53
+ },
54
+ ```
55
+
56
+ `withInternalContext` builds a context with `internal: true` and `userId: "system:cron-<name>"`, so audited writes made through it are attributable to the schedule (e.g. `system:cron-sweepDigests`) and can reach `roles: ['INTERNAL']`-gated rows. Reach for it whenever the schedule legitimately operates across tenants.
57
+
58
+ ## Failure isolation
59
+
60
+ The generated `scheduled()` dispatcher runs every schedule whose cron matches `event.cron` concurrently (`Promise.all`), and each handler's errors are caught individually — one failing schedule logs `[Cron] Schedule error` and the others still run to completion. A cron with no registered handler logs `[Cron] No schedule registered` and returns.
43
61
 
44
62
  ## Cron syntax
45
63