@quickback-dev/cli 0.48.0 → 0.50.0

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.
Files changed (31) hide show
  1. package/dist/commands/compile.d.ts.map +1 -1
  2. package/dist/commands/compile.js +13 -2
  3. package/dist/commands/compile.js.map +1 -1
  4. package/dist/commands/migrations.d.ts +10 -0
  5. package/dist/commands/migrations.d.ts.map +1 -1
  6. package/dist/commands/migrations.js +113 -79
  7. package/dist/commands/migrations.js.map +1 -1
  8. package/dist/commands/migrations.test.js +96 -1
  9. package/dist/commands/migrations.test.js.map +1 -1
  10. package/dist/docs/content.js +9 -9
  11. package/dist/docs/content.js.map +1 -1
  12. package/dist/index.js +1 -1
  13. package/dist/skill/docs/changelog.md +84 -0
  14. package/dist/skill/docs/compiler/config/providers.md +23 -2
  15. package/dist/skill/docs/compiler/definitions/actions.md +12 -2
  16. package/dist/skill/docs/compiler/definitions/encryption.md +2 -0
  17. package/dist/skill/docs/compiler/definitions/schema.md +2 -0
  18. package/dist/skill/docs/compiler/targets/hono-api/database/neon.md +306 -35
  19. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/batch-operations.md +14 -8
  20. package/dist/skill/docs/stack/realtime/durable-objects.md +143 -4
  21. package/dist/skill/docs/stack/webhooks/outbound.md +23 -0
  22. package/package.json +1 -1
  23. package/src/skill/docs/changelog.md +84 -0
  24. package/src/skill/docs/compiler/config/providers.md +23 -2
  25. package/src/skill/docs/compiler/definitions/actions.md +12 -2
  26. package/src/skill/docs/compiler/definitions/encryption.md +2 -0
  27. package/src/skill/docs/compiler/definitions/schema.md +2 -0
  28. package/src/skill/docs/compiler/targets/hono-api/database/neon.md +306 -35
  29. package/src/skill/docs/compiler/targets/hono-api/using-the-api/batch-operations.md +14 -8
  30. package/src/skill/docs/stack/realtime/durable-objects.md +143 -4
  31. package/src/skill/docs/stack/webhooks/outbound.md +23 -0
@@ -6,10 +6,25 @@ Neon provides serverless PostgreSQL that works with Cloudflare Workers via HTTP
6
6
 
7
7
  - **Full PostgreSQL** — Advanced queries, joins, PostGIS, full-text search
8
8
  - **Database-level security** — RLS policies enforce access even if the API is bypassed
9
- - **Serverless** — HTTP connection mode for Cloudflare Workers
10
- - **Neon Authorize** — JWT-based RLS via the `auth.user_id()` function
9
+ - **Serverless** — HTTP connection mode (`@neondatabase/serverless`) for Cloudflare Workers
10
+ - **Worker-scoped RLS** — the Worker verifies each caller, then writes the trusted user/org/team context into transaction-local Postgres settings that RLS policies read (see [How Worker-scoped RLS works](#how-worker-scoped-rls-works))
11
11
  - **Better Auth integration** — Works seamlessly with the Quickback auth provider
12
12
 
13
+ ## One database for auth and features
14
+
15
+ Quickback uses a single database provider per app. On Neon, Better Auth tables
16
+ and feature tables live in the same Postgres database: Better Auth runs on its
17
+ PostgreSQL/Drizzle adapter, and everything connects through one `DATABASE_URL`.
18
+ There is no `AUTH_DATABASE_URL`, and split-database mode is a D1-only option.
19
+
20
+ Mixing providers — for example D1 for auth with Neon for features — is not
21
+ supported. The per-service config form is rejected at compile time:
22
+
23
+ ```
24
+ providers.database service-map form is not supported in v2.
25
+ Configure one database provider; auth and feature data use the same database.
26
+ ```
27
+
13
28
  ## Configuration
14
29
 
15
30
  ```typescript title="quickback/quickback.config.ts"
@@ -33,40 +48,150 @@ export default defineConfig({
33
48
  | Mode | Best for | How it works |
34
49
  |------|----------|--------------|
35
50
  | **HTTP** | Cloudflare Workers, edge functions | Stateless HTTP queries via `@neondatabase/serverless` |
36
- | **WebSocket** | Node.js, Bun | Persistent WebSocket connection for lower latency |
37
- | **Auto** (default) | Mixed environments | Detects runtime and picks the best mode |
51
+ | **WebSocket** | Node.js, Bun | Persistent WebSocket connection (`drizzle-orm/neon-serverless`) |
52
+ | **Auto** (default) | Mixed environments | Detects runtime: `http` on `cloudflare`, `websocket` on Node/Bun |
53
+
54
+ On the Cloudflare runtime, `auto` resolves to **HTTP** — this is the mode the
55
+ rest of this page assumes. The generated Worker uses `@neondatabase/serverless`
56
+ over HTTP; there is no Hyperdrive binding.
57
+
58
+ > HTTP mode is the fully-featured path. WebSocket mode gets real interactive
59
+ > transactions (see [Batch transactions](#batch-transactions)), but it does
60
+ > **not** support webhooks, cross-tenant `unsafe` actions, or `.encrypted()` /
61
+ > `.sealed()` columns — each of those is a fail-closed compile error under
62
+ > `connectionMode: 'websocket'` because the WebSocket db client does not emit the
63
+ > service-role handle they depend on. Use HTTP mode (the Cloudflare default) for
64
+ > the full capability surface.
65
+
38
66
 
39
67
  ## Environment variables
40
68
 
69
+ Three connection points, each read by a different tool:
70
+
71
+ | Where | File / store | Read by |
72
+ |-------|--------------|---------|
73
+ | Migrations (local/CI) | `.env` | `drizzle-kit` |
74
+ | `wrangler dev` (local Worker) | `.dev.vars` | Wrangler |
75
+ | Production Worker | `wrangler secret put` | The deployed Worker |
76
+
77
+ The compiler emits `.env.neon.example` and `.dev.vars.example` as templates,
78
+ and gitignores `.dev.vars` so local secrets are never committed.
79
+
41
80
  ```bash
42
- # For Cloudflare Workers
43
- npx wrangler secret put DATABASE_URL
44
- # Paste: postgresql://user:pwd@ep-xxx.region.neon.tech/db?sslmode=require
81
+ # Migrations read .env — copy the template and fill it in:
82
+ cp .env.neon.example .env
83
+ # .env holds:
84
+ # DATABASE_URL — pooled quickback (runtime) role URL
85
+ # DATABASE_MIGRATION_URL — unpooled quickback_admin role URL (optional)
86
+
87
+ # wrangler dev reads .dev.vars (NOT .env) — copy the template:
88
+ cp .dev.vars.example .dev.vars # gitignored; holds DATABASE_URL + BETTER_AUTH_SECRET
89
+
90
+ # Production: secrets live in Worker secrets, never in files:
91
+ npx wrangler secret put DATABASE_URL # pooled quickback role URL
92
+ npx wrangler secret put BETTER_AUTH_SECRET
93
+ ```
94
+
95
+ `DATABASE_URL` is the only connection string the Worker needs at runtime — auth
96
+ and feature queries share it. `DATABASE_MIGRATION_URL` is used **only** by
97
+ `drizzle-kit`: the generated `drizzle.config.ts` reads
98
+ `process.env.DATABASE_MIGRATION_URL ?? process.env.DATABASE_URL`, so migrations
99
+ run as the privileged `quickback_admin` role when it is set and fall back to
100
+ `DATABASE_URL` when it is not. Never deploy `DATABASE_MIGRATION_URL` to the
101
+ Worker.
102
+
103
+ <Callout>
104
+ The generated setup uses three Postgres roles: `quickback_owner` (NOLOGIN object
105
+ owner for the app/auth schemas), `quickback_admin` (migration/setup actor — use
106
+ its unpooled URL for `DATABASE_MIGRATION_URL`), and `quickback` (the Worker
107
+ runtime role, the **only** deployed DB role — use its pooled URL for
108
+ `DATABASE_URL`). The first generated migration bootstraps these roles as
109
+ NOLOGIN; enable login and set passwords before use. Full walkthrough in the
110
+ generated `docs/neon-setup.md`.
111
+ </Callout>
112
+
113
+ ## Better Auth schema generation
114
+
115
+ `src/auth/schema.ts` is owned by the Better Auth CLI. The generated `build`
116
+ script regenerates it before typechecking:
45
117
 
46
- # For local development (.env)
47
- DATABASE_URL=postgresql://user:pwd@ep-xxx.region.neon.tech/db?sslmode=require
118
+ ```bash
119
+ npm run build # runs auth:schema, then tsc
48
120
  ```
49
121
 
122
+ `auth:schema` expands to:
123
+
124
+ ```bash
125
+ npx better-auth generate --config ./src/lib/auth.ts --output ./src/auth/schema.ts --yes \
126
+ && node scripts/quickback-qualify-auth-schema.mjs
127
+ ```
128
+
129
+ The qualifier script adjusts the CLI output for Postgres schema placement.
130
+ Don't hand-edit `src/auth/schema.ts` — regenerate it instead.
131
+
50
132
  ## Migrations
51
133
 
52
- Neon uses PostgreSQL migrations, distinct from D1's SQLite migrations:
134
+ Neon uses PostgreSQL migrations, distinct from D1's SQLite migrations. One
135
+ Drizzle journal covers auth tables, feature tables, indexes, FK/cascade
136
+ semantics, and the RLS layer:
53
137
 
54
138
  ```bash
55
139
  quickback compile # generates migrations under quickback/drizzle/
56
- npm run db:migrate # applies them — schema AND the RLS layer
140
+ npm run db:migrate # applies schema AND the RLS layer, in order
57
141
  ```
58
142
 
59
143
  The RLS layer (helper functions, policies, triggers) rides the same
60
- journaled migration set as your schema (v0.45+): the compiler appends a
144
+ journaled migration set as your schema: the compiler appends a
61
145
  content-addressed `<idx>_quickback_rls_<hash>` migration, so one
62
146
  `db:migrate` applies everything in order. The RLS migration is idempotent
63
147
  (`DROP POLICY IF EXISTS` + re-create) and only a *changed* security config
64
148
  appends a new entry — recompiles with unchanged security append nothing. No
65
- manual SQL application step exists anymore.
149
+ manual SQL application step exists.
150
+
151
+ ## How Worker-scoped RLS works
152
+
153
+ Quickback does **not** send browser or mobile clients directly to Neon, and it
154
+ does **not** use Neon Authorize / a JWKS endpoint. Clients authenticate with the
155
+ Cloudflare Worker; the Worker verifies the Better Auth session or API key, runs
156
+ the access checks, and then performs the database call as a trusted proxy.
157
+
158
+ For every feature-table query, the generated database client opens a Neon HTTP
159
+ batch (an implicit transaction) whose **first** statement writes the verified
160
+ caller context into transaction-local Postgres settings:
161
+
162
+ ```sql
163
+ -- Injected by the Worker as the batch's first statement (is_local = true):
164
+ SELECT
165
+ set_config('quickback.service_role', '', true),
166
+ set_config('request.jwt.claim.sub', 'usr_123', true),
167
+ set_config('request.jwt.claim.org_id', 'org_abc', true),
168
+ set_config('request.jwt.claim.team_id', '', true);
169
+ ```
170
+
171
+ RLS policies read those settings through Quickback-defined helper functions —
172
+ there is no external JWT verification and no persisted session state in the
173
+ database. `auth.user_id()` is a compiler-generated shim, not a Neon Authorize
174
+ function:
175
+
176
+ ```sql
177
+ -- Generated by Quickback (granted to the quickback runtime role):
178
+ CREATE OR REPLACE FUNCTION auth.user_id()
179
+ RETURNS TEXT AS $$
180
+ SELECT NULLIF(current_setting('request.jwt.claim.sub', true), '')
181
+ $$ LANGUAGE SQL STABLE SET search_path = public;
182
+ ```
183
+
184
+ Because the settings are transaction-local (`set_config(..., true)`), they
185
+ apply only to the current batch and never leak between requests. If the Worker
186
+ never stamps a user id, `auth.user_id()` returns `NULL` and the restrictive
187
+ `deny_anon` policy blocks the query — fail closed.
66
188
 
67
189
  ## Row Level Security
68
190
 
69
- Quickback emits RLS policies from your `firewall` and `access` config. The Neon target uses Neon Authorize's `auth.user_id()` JWT claim function (the Supabase target uses `auth.uid()` instead — same pattern, different function).
191
+ Quickback emits RLS policies from your `firewall` and `access` config. Neon's
192
+ policies read the transaction-local claims described above via `auth.user_id()`
193
+ and the `get_active_org_id()` / `has_any_role()` helpers (the Supabase target
194
+ uses `auth.uid()` instead — same pattern, different function).
70
195
 
71
196
  ```typescript
72
197
  firewall: [
@@ -77,11 +202,15 @@ firewall: [
77
202
  ```sql
78
203
  CREATE POLICY "documents_select" ON documents FOR SELECT
79
204
  USING (
80
- organization_id = get_active_org_id()
81
- AND (has_any_role(ARRAY['admin']) OR user_id = auth.user_id())
205
+ organization_id = public.get_active_org_id()
206
+ AND (public.is_admin() OR user_id = auth.user_id())
82
207
  );
83
208
  ```
84
209
 
210
+ Every feature table also gets a restrictive `deny_anon` policy (blocks queries
211
+ with no stamped user id) and a `service_role` policy (admits Worker-internal
212
+ contexts — see [Background jobs and cross-tenant actions](#background-jobs-and-cross-tenant-actions)).
213
+
85
214
  ### Firewall patterns
86
215
 
87
216
  **Organization-scoped:**
@@ -109,29 +238,140 @@ CREATE POLICY "categories_all" ON categories FOR ALL TO authenticated USING (tru
109
238
 
110
239
  | Function | Purpose |
111
240
  |----------|---------|
112
- | `get_active_org_id()` | Returns the user's active organization from `user_sessions` |
113
- | `has_any_role(roles[])` | Checks if the user has any specified role |
241
+ | `auth.user_id()` | Reads the verified user id from the transaction-local `request.jwt.claim.sub` setting |
242
+ | `get_active_org_id()` | Reads the request-scoped org from the transaction-local `request.jwt.claim.org_id` setting |
243
+ | `get_active_team_id()` | Reads the request-scoped team from `request.jwt.claim.team_id` (teams mode) |
244
+ | `has_any_role(roles[])` | Checks if the user has any specified role in the request org |
114
245
  | `has_org_role(role)` | Checks for a single specific role |
115
- | `is_org_member()` | Checks org membership |
116
- | `is_owner(owner_id)` | Checks record ownership |
246
+ | `is_org_member()` | Checks org membership in the request org |
247
+ | `is_owner(owner_id)` | Checks record ownership against `auth.user_id()` |
248
+ | `is_admin()` | Checks the `auth.admins` table (admin mode) |
249
+
250
+ All helpers are TEXT-typed to match Better Auth's prefixed ids (`org_abc123`).
251
+ The request org/team scope is passed by the Worker **per transaction**, not read
252
+ from a persisted mirror. There is no compiler-owned `user_sessions` table and no
253
+ session hook that syncs the active organization into the database — switching to
254
+ "no org" simply means the Worker stamps an empty `request.jwt.claim.org_id`, and
255
+ SQL-side access is revoked immediately. Fail closed.
256
+
257
+ The only compiler-owned support tables the RLS layer reads live in
258
+ `src/db/rls-support.schema.ts`: a `profiles` table (populated by the
259
+ `sync_profile_display_name()` trigger and protected by the `profiles_*`
260
+ policies) and, when admin/sysadmin helpers are emitted, an `admins` table (read
261
+ by `is_admin()` / `is_sysadmin()`). Better Auth's own `sessions` table may still
262
+ carry an `active_organization_id`, but Quickback RLS never reads it.
263
+
264
+ RLS coverage includes Better Auth's own tables — including those the compiler
265
+ force-enables (organization, admin, `apikeys`; plus the OAuth/agent table
266
+ families when those surfaces are on, locked to service-role only).
267
+
268
+ ## Background jobs and cross-tenant actions
269
+
270
+ Some code runs with no HTTP request and therefore no caller claims: queue
271
+ consumers, cron schedules, and cross-tenant `unsafe` actions. These acquire the
272
+ **service-role handle** `createServiceDb(env)` from the generated `src/db`
273
+ index. Instead of caller claims, it sets `quickback.service_role = 'true'` (with
274
+ all request claims cleared) — the same marker the Better Auth adapter's
275
+ transactions use. Every feature table carries a `<table>_service_role` RLS
276
+ policy that admits exactly that context, so background work can reach rows
277
+ across tenants while the request-scoped `createDb()` client stays caller-scoped.
278
+
279
+ The service-role marker is only ever set by Worker-internal chokepoints
280
+ (`createServiceDb`, the Better Auth adapter) — it is never derived from request
281
+ input. Unsafe actions keep their mandatory audit contract: cross-tenant writes
282
+ still land audit events (the `audit` Postgres schema), unchanged from D1.
283
+
284
+ ## Webhooks on Neon
285
+
286
+ Webhooks are supported on Neon over HTTP. The store (`webhook_events`,
287
+ `webhook_endpoints`, `webhook_deliveries`) lives in a dedicated `webhooks`
288
+ Postgres schema of the **same** database — following the `audit` schema
289
+ precedent — so there is no separate `WEBHOOKS_DB` binding.
290
+
291
+ - Set `webhooksBinding` to enable webhooks. On Neon its value is a pure enable
292
+ flag (no D1 binding is emitted); the queue names stay provider-neutral.
293
+ - The D1-only keys `webhooksDatabaseId` and `webhooksDatabaseName` are rejected
294
+ at compile time — they name a D1 database that cannot exist on Neon.
295
+ - The webhook store is Worker-internal (endpoint signing secrets live there):
296
+ every table in the `webhooks` schema has RLS enabled with a single
297
+ service-role-only policy, so only `createWebhooksDb()` (which wraps
298
+ `createServiceDb`) can touch it. Route handlers gate access at the app layer
299
+ (`requireOrgMember` / endpoint-ownership checks) before querying.
300
+ - Webhooks require `connectionMode: 'http'`.
301
+
302
+ ## Encryption on Neon
303
+
304
+ The encryption pillar — `.encrypted()` (envelope) and `.sealed()` /
305
+ `q.vaultRef()` (sealed) columns — is supported on Neon over HTTP. The
306
+ `org_data_keys` and seal-vault tables fold into the single journaled migration
307
+ set, and the encryption RLS section rides the journaled RLS migration:
308
+ `org_data_keys` gets org-scoped RLS (the envelope DEK path needs caller claims),
309
+ and the vault spine is locked to service-role-only. The seal chokepoints
310
+ acquire `createServiceDb`.
311
+
312
+ Both tiers require `connectionMode: 'http'`; under WebSocket mode they are a
313
+ fail-closed compile error.
314
+
315
+ ## Batch transactions
316
+
317
+ Whether a batch handler (`PATCH /batch`, `DELETE /batch`, …) is truly atomic
318
+ depends on the connection mode, and the response advertises the guarantee via
319
+ `meta.transactional`:
320
+
321
+ | Mode | `meta.transactional` | Behavior |
322
+ |------|----------------------|----------|
323
+ | Neon HTTP (Cloudflare default) | `false` | Fail-fast per-record loop, no rollback — `drizzle-orm/neon-http` has no interactive transactions, so this matches D1's semantics honestly |
324
+ | Neon WebSocket (Node/Bun) | `true` | `db.transaction()` wraps the loop; any failure rolls back every write in the batch |
325
+
326
+ `drizzle-orm/neon-http` throws "No transactions support in neon-http driver" at
327
+ runtime, so the HTTP path deliberately treats batches like D1 (fail-fast,
328
+ non-transactional) rather than emitting code that would 500 on every failed
329
+ batch. Honest advertisement over runtime surprises.
330
+
331
+ ## Capability limits (fail closed)
332
+
333
+ Anything not yet ported to Postgres is a compile-time error on Neon, never
334
+ silently-broken output:
335
+
336
+ - **Managed file storage** (`fileStorage` with `managed: true`) is rejected — its
337
+ metadata store is a D1 database. Use presign-only R2 (the default, without
338
+ `managed`), which is provider-neutral and works on Neon today.
339
+ - **The Better Auth `subscriptions` plugin** is rejected until it gets
340
+ provider-aware db acquisition and a Postgres dialect schema.
341
+ - **Raw `sqliteTable` interop sources** on a Postgres target are rejected — write
342
+ child tables with `pgTable` (see [below](#raw-drizzle-interop-tables-must-use-pg-core)).
343
+ - **WebSocket mode** rejects webhooks, cross-tenant `unsafe` actions, and
344
+ encrypted/sealed columns (see the [connection modes](#connection-modes)
345
+ callout).
346
+
347
+ Mixed database providers (e.g. D1 auth + Neon features) remain unsupported.
348
+
349
+ ## Deploying
350
+
351
+ The generated `deploy` script runs migrations, then ships the Worker:
352
+
353
+ ```bash
354
+ npm run deploy # runs db:migrate (drizzle-kit) then wrangler deploy
355
+ ```
356
+
357
+ Before the first deploy, put the runtime secrets in Worker secrets and make sure
358
+ the Worker's KV namespace (used by Better Auth for sessions and JWT revocation)
359
+ is provisioned:
117
360
 
118
- All helpers are TEXT-typed to match Better Auth's prefixed ids
119
- (`org_abc123`). The `user_sessions` table the org helpers read is
120
- compiler-owned migration state (`src/db/rls-support.schema.ts`), created by
121
- the journaled migrations and kept in sync automatically: generated Better
122
- Auth session hooks mirror the session's active organization (and team) into
123
- it on every session create/update. Switching to "no org" revokes SQL-side
124
- access — fail closed.
361
+ ```bash
362
+ npx wrangler secret put DATABASE_URL # pooled quickback role URL
363
+ npx wrangler secret put BETTER_AUTH_SECRET
364
+ ```
125
365
 
126
- RLS coverage includes Better Auth's own tables — including those the
127
- compiler force-enables (organization, admin, `apikeys`; plus the OAuth/agent
128
- table families when those surfaces are on, locked to service-role only).
366
+ The generated Neon client fails fast at boot if `DATABASE_URL` is missing, so a
367
+ misconfigured deploy surfaces immediately rather than on the first query.
129
368
 
130
- ## Setting up Neon Authorize
369
+ > Live runtime smoke testing against a deployed Neon Worker is still being brought
370
+ > up; the compile/typecheck/migrate path is verified end-to-end (including
371
+ > executing the generated Postgres migrations under pglite), but treat a first
372
+ > production deploy as you would any new stack — exercise auth, a CRUD flow, and a
373
+ > batch write before relying on it.
131
374
 
132
- 1. Open **Project Settings → Authorize** in the Neon console
133
- 2. Add your JWKS URL: `https://your-api.example.com/auth/v1/.well-known/jwks.json`
134
- 3. The `auth.user_id()` function will return the authenticated user's ID from the JWT
135
375
 
136
376
  ## Generated files
137
377
 
@@ -141,11 +381,42 @@ quickback/drizzle/
141
381
  ├── 0001_quickback_rls_<hash>.sql # journaled RLS layer (content-addressed)
142
382
  └── meta/_journal.json # one journal covers both
143
383
  src/
384
+ ├── db/index.ts # createDb / createServiceDb (claim-scoped clients)
144
385
  ├── db/schema.ts # Drizzle schema barrel
145
- ├── db/rls-support.schema.ts # user_sessions + RLS support tables
386
+ ├── db/rls-support.schema.ts # profiles (+ admins) — RLS support tables
146
387
  └── auth/schema.ts # Better Auth schema (owned by the BA CLI)
388
+ .env.neon.example # migration connection strings (copy to .env)
389
+ .dev.vars.example # wrangler dev secrets (copy to .dev.vars)
390
+ docs/neon-setup.md # role bootstrap + deploy walkthrough
147
391
  ```
148
392
 
393
+ ## Raw Drizzle interop tables must use `pg-core`
394
+
395
+ Internal child tables authored as raw Drizzle (a table file with **no**
396
+ `export default defineTable(...)`) are not dialect-translated by the
397
+ compiler — on Neon they must be written with `pgTable` from
398
+ `drizzle-orm/pg-core`. A `sqliteTable` interop source on a Postgres target
399
+ is a **compile-time error**: the mechanical sqlite→pg rewrite would leave
400
+ SQLite-shaped audit columns (`text` ISO strings instead of `timestamptz`,
401
+ which the RLS audit triggers stamp) and SQLite-only column options in the
402
+ Postgres schema.
403
+
404
+ ```typescript
405
+ // quickback/features/interviews/interview_scores.ts
406
+ // @quickback-internal — child table, no CRUD routes
407
+ import { integer, pgTable, text } from 'drizzle-orm/pg-core';
408
+
409
+ export const interviewScores = pgTable('interview_scores', {
410
+ id: text('id').primaryKey(),
411
+ interviewId: text('interview_id').notNull(),
412
+ rating: integer('rating').notNull(),
413
+ });
414
+ ```
415
+
416
+ Tables **with** `defineTable(...)` are unaffected — existing `sqliteTable`
417
+ sources with a resource config still compile to the Postgres dialect
418
+ automatically.
419
+
149
420
  ## When to choose Neon vs D1
150
421
 
151
422
  | Factor | Neon | D1 |
@@ -255,20 +255,26 @@ Set `"failFast": true` to stop on the first error:
255
255
 
256
256
  ## Transactional Semantics
257
257
 
258
- The behavior of `failFast: true` depends on whether your database provider
259
- supports transactions. The response's `meta.transactional` flag tells you
260
- which guarantee you actually got — inspect it in clients that care about
261
- rollback.
258
+ The behavior of `failFast: true` depends on whether your database provider —
259
+ and, for Neon, its **connection mode** — supports interactive transactions.
260
+ The response's `meta.transactional` flag tells you which guarantee you
261
+ actually got — inspect it in clients that care about rollback.
262
+
263
+ Neon is transactional **only over websocket** (`connectionMode: 'websocket'`,
264
+ the default on Node/Bun runtimes). Over HTTP — the default on Cloudflare
265
+ Workers — the `drizzle-orm/neon-http` driver has no `db.transaction()` (it
266
+ throws at runtime), so Neon-over-HTTP batches behave exactly like D1:
267
+ fail-fast per-record loop, `meta.transactional: false`.
262
268
 
263
269
  ### Per-Provider Matrix
264
270
 
265
271
  | Endpoint | Provider | `failFast` | `meta.transactional` | Behavior |
266
272
  |----------|----------|-----------|----------------------|----------|
267
- | `PATCH /batch` (update) | neon (Postgres via Hyperdrive) | `true` | `true` | `db.transaction()` wraps the per-record loop. Any failure rolls back ALL writes in the batch. |
273
+ | `PATCH /batch` (update) | tx-supporting (postgres, neon over websocket) | `true` | `true` | `db.transaction()` wraps the per-record loop. Any failure rolls back ALL writes in the batch. |
268
274
  | `PATCH /batch` (update) | (any) | `false` | `false` | Per-record loop, partial success. Each record commits independently. |
269
- | `PATCH /batch` (update) | cloudflare-d1 | `true` | `false` | Fail-fast loop without rollback — D1 has no `db.transaction`. Records before the failure stay committed. |
270
- | `PUT /batch` (upsert) | tx-supporting | `true` | `true` | Bulk insert + per-record update share one transaction. Any failure rolls back both. |
271
- | `PUT /batch` (upsert) | cloudflare-d1 | `true` | `false` | Bulk insert commits; per-record update loop is fail-fast without rollback. |
275
+ | `PATCH /batch` (update) | cloudflare-d1, neon over http (Cloudflare default) | `true` | `false` | Fail-fast loop without rollback — the driver has no `db.transaction`. Records before the failure stay committed. |
276
+ | `PUT /batch` (upsert) | tx-supporting (postgres, neon over websocket) | `true` | `true` | Bulk insert + per-record update share one transaction. Any failure rolls back both. |
277
+ | `PUT /batch` (upsert) | cloudflare-d1, neon over http (Cloudflare default) | `true` | `false` | Bulk insert commits; per-record update loop is fail-fast without rollback. |
272
278
  | `POST /batch` (create) | (any) | (any) | `true` | Single bulk `INSERT` — atomic at the DB level. |
273
279
  | `DELETE /batch` | (any) | (any) | `true` | Single bulk `UPDATE` (soft) or `DELETE` (hard) — atomic at the DB level. |
274
280
 
@@ -245,9 +245,16 @@ await realtime.broadcast('screening-complete', {
245
245
  applicationId: 'app_123',
246
246
  candidateId: 'cnd_456',
247
247
  stage: 'interview'
248
- }, ctx.activeOrgId!);
248
+ }, ctx.activeOrgId!, {
249
+ targetRoles: ['AUTHENTICATED'],
250
+ });
249
251
  ```
250
252
 
253
+ **Every send needs an audience.** Delivery is fail-closed: a broadcast whose
254
+ `targetRoles` is omitted or empty reaches **nobody**. "Everyone in the room" is
255
+ spelled explicitly — `targetRoles: ['AUTHENTICATED']` (any authenticated
256
+ subscriber) or `['PUBLIC']`.
257
+
251
258
  Broadcasts:
252
259
  ```json
253
260
  {
@@ -268,7 +275,8 @@ Target a specific user instead of the entire organization:
268
275
  ```typescript
269
276
  // Only this user receives the notification
270
277
  await realtime.insert('notifications', newNotification, ctx.activeOrgId!, {
271
- userId: ctx.userId
278
+ userId: ctx.userId,
279
+ targetRoles: ['AUTHENTICATED'],
272
280
  });
273
281
 
274
282
  // Notify a hiring manager of a new application
@@ -276,10 +284,16 @@ await realtime.broadcast('application-received', {
276
284
  applicationId: 'app_123',
277
285
  jobId: 'job_789'
278
286
  }, ctx.activeOrgId!, {
279
- userId: hiringManagerId
287
+ userId: hiringManagerId,
288
+ targetRoles: ['AUTHENTICATED'],
280
289
  });
281
290
  ```
282
291
 
292
+ `userId` targeting matches the **socket identity** — the Better Auth user id, or
293
+ the synthetic `scope:<subjectId>` principal for sessionless scope connections. If
294
+ the same person can connect through either door, prefer
295
+ [identity-tag targeting](#identity-tag-targeting) — one send reaches both.
296
+
283
297
  ## Role-Based Filtering
284
298
 
285
299
  Limit which roles receive a broadcast using `targetRoles`:
@@ -296,7 +310,132 @@ await realtime.update('applications', newRecord, oldRecord, ctx.activeOrgId!, {
296
310
  });
297
311
  ```
298
312
 
299
- If `targetRoles` is not specified, all authenticated subscribers in the chosen scope receive the broadcast.
313
+ **Fail-closed (v0.48+):** an omitted or empty `targetRoles` delivers to
314
+ **nobody** — there is no implicit "everyone" fallback. To reach every
315
+ authenticated subscriber in the scope, say so explicitly with
316
+ `targetRoles: ['AUTHENTICATED']`. UPPERCASE pseudo-roles (`PUBLIC`,
317
+ `AUTHENTICATED`, `USER`, `SYSADMIN`) are evaluated exactly as the REST access
318
+ evaluator does.
319
+
320
+ > **Migrating from pre-0.48:** custom `realtime.broadcast(...)` /
321
+ > `realtime.insert(...)` calls that omitted `targetRoles` used to fan out to
322
+ > everyone; they now silently deliver to nobody. Audit every manual send and add
323
+ > an explicit audience.
324
+
325
+ ## Identity-Tag Targeting
326
+
327
+ Every connection carries **identity tags**, proven at ticket mint and signed
328
+ into the ticket (never client-supplied):
329
+
330
+ - `user:<userId>` — every Better Auth caller
331
+ - `scope:<kind>:<subjectId>` — when a scope subject is proven, on **either**
332
+ door: a sessionless scope principal's verified claim, or a Better Auth caller
333
+ whose matched relationship lane maps to a scope kind with
334
+ `subject: 'supplied' | 'both'`. Both doors stamp the **identical** tag (the
335
+ subject row's id), which is the point.
336
+
337
+ Target them with `targetTags`:
338
+
339
+ ```typescript
340
+ // ONE send reaches this guest whether they're connected via their Better Auth
341
+ // session or a sessionless scope link — no per-identity double-send.
342
+ await realtime.broadcast('chat.frame', payload, { scopeKey }, {
343
+ targetTags: [`scope:guest:${guestId}`],
344
+ targetRoles: ['AUTHENTICATED'],
345
+ });
346
+
347
+ // Reach a person under either identity explicitly (deduped per socket):
348
+ await realtime.broadcast('rsvp.updated', payload, { scopeKey }, {
349
+ targetTags: [`scope:guest:${guestId}`, `user:${linkedUserId}`],
350
+ targetRoles: ['AUTHENTICATED'],
351
+ });
352
+ ```
353
+
354
+ Semantics:
355
+
356
+ - Delivery is the **deduplicated union** of the runtime's indexed tag lookup
357
+ (`getWebSockets(tag)`) — no attachment scan, and a dual-identity socket
358
+ matches once.
359
+ - `targetTags` **replaces the `userId` identity arm** when present; the
360
+ scope/org bind and the `targetRoles` audience still apply on top.
361
+ - **Fail-closed:** `targetTags: []` delivers to nobody.
362
+ - Tags are **immutable** for a socket's lifetime (a Workers hibernation-tag
363
+ constraint) — an identity change requires a reconnect.
364
+ - Limits: at most 10 tags per connection, 256 characters per tag. The mint
365
+ rejects violations; it never truncates.
366
+
367
+ ## Authorization Lease
368
+
369
+ The 60-second ws-ticket is verified once, at upgrade — but Durable Object
370
+ hibernation keeps sockets alive indefinitely. Without a lease, a ban, member
371
+ removal, or subject revocation (say, an organizer cancelling a guest) would
372
+ never affect an already-connected socket. The lease closes that gap:
373
+
374
+ - At upgrade, the connection stores `authExpiresAt = ticket.iat + lease`
375
+ (default **15 minutes**).
376
+ - The fan-out **skips expired connections** — they receive nothing — and closes
377
+ them with code **4401** so the client knows to re-ticket rather than blindly
378
+ reconnect. Inbound messages (even pings) are enforced the same way.
379
+ - Renewal happens at mint: `POST /broadcast/v1/ws-ticket` re-runs the full
380
+ authorization gate (session validity, revocation checks, relationship /
381
+ scope-claim probes), so a revoked principal simply can't obtain a renewal
382
+ ticket. Revocation propagates within one lease period with no polling.
383
+
384
+ Configure it on the realtime transport:
385
+
386
+ ```typescript
387
+ providers: {
388
+ database: {
389
+ config: {
390
+ realtime: {
391
+ enabled: true,
392
+ lease: '15m', // default; also '900s', '1h', or a number of seconds
393
+ // lease: false // disable (discouraged — reopens the revocation gap)
394
+ },
395
+ },
396
+ },
397
+ }
398
+ ```
399
+
400
+ The lease must be at least 60 seconds (the handshake-ticket TTL).
401
+
402
+ ### In-place renewal (`reauth`)
403
+
404
+ Instead of reconnecting every lease period, a client can renew in place: mint a
405
+ fresh ticket and send it over the open socket.
406
+
407
+ ```typescript
408
+ // On a timer comfortably inside the lease (e.g. every 10 min for a 15m lease):
409
+ const { wsTicket } = await mintTicket(); // POST /broadcast/v1/ws-ticket
410
+ ws.send(JSON.stringify({ type: 'reauth', ticket: wsTicket }));
411
+
412
+ ws.onmessage = (event) => {
413
+ const msg = JSON.parse(event.data);
414
+ if (msg.type === 'reauth_ok') {
415
+ scheduleNextRenewal(msg.authExpiresAt); // lease extended, roles refreshed
416
+ }
417
+ if (msg.type === 'error' && msg.code === 'REAUTH_FAILED') {
418
+ // Ticket invalid/expired — mint a fresh one and retry before the lease lapses.
419
+ }
420
+ };
421
+
422
+ ws.onclose = (event) => {
423
+ if (event.code === 4401) {
424
+ // Lease expired or identity drift: mint a fresh ticket and reconnect.
425
+ reconnectWithFreshTicket();
426
+ }
427
+ };
428
+ ```
429
+
430
+ Renewal is **strict**: the fresh ticket must carry the same `userId`,
431
+ `scopeKey`/`organizationId`, and the **exact same tag set** as the live socket
432
+ (tags are immutable). A renewal that matches extends the lease and refreshes
433
+ `role`/`roles` in place — live permission changes without socket churn. One
434
+ that doesn't closes the socket with 4401: reconnect fresh.
435
+
436
+ Clients that never send `reauth` still work — their socket is closed with 4401
437
+ once per lease and normal reconnect logic (with a fresh ticket) re-runs the
438
+ full gate. The lease is the server-side invariant either way.
300
439
 
301
440
  ## Per-Role Field Masking
302
441
 
@@ -275,6 +275,29 @@ database: defineDatabase("cloudflare-d1", {
275
275
 
276
276
  This generates the webhook database schema, routes, queue consumer, and all supporting code.
277
277
 
278
+ ### On Neon (Postgres)
279
+
280
+ Webhooks are supported on the `neon` provider too. `webhooksBinding` acts as a
281
+ pure enable flag — there is no separate webhooks database. The webhook tables
282
+ live in a dedicated `webhooks` Postgres schema of your single Neon database,
283
+ created by the standard drizzle migration set, and are locked down by an RLS
284
+ policy so only the Worker's internal service-role handle can touch them:
285
+
286
+ ```typescript
287
+ database: defineDatabase("neon", {
288
+ connectionMode: "http", // required for webhooks
289
+ webhooksBinding: "WEBHOOKS_DB", // enable flag; no D1 binding is emitted
290
+ // queue names stay configurable on any provider:
291
+ webhooksQueueName: "my-app-webhooks-queue",
292
+ webhooksDlqName: "my-app-webhooks-dlq",
293
+ })
294
+ ```
295
+
296
+ The D1-only keys `webhooksDatabaseId` / `webhooksDatabaseName` are rejected at
297
+ compile time on Neon, and webhooks require `connectionMode: 'http'` (the
298
+ Cloudflare default). Queue wiring (`WEBHOOKS_QUEUE`, the consumer, and the
299
+ dead letter queue) is identical across providers.
300
+
278
301
  ## See Also
279
302
 
280
303
  - [Inbound Webhooks](/stack/webhooks/inbound) — Receive webhooks from external services
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quickback-dev/cli",
3
- "version": "0.48.0",
3
+ "version": "0.50.0",
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",