@quickback-dev/cli 0.50.8 → 0.51.1

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 (88) hide show
  1. package/dist/commands/compile.d.ts.map +1 -1
  2. package/dist/commands/compile.js +34 -19
  3. package/dist/commands/compile.js.map +1 -1
  4. package/dist/docs/content.js +22 -22
  5. package/dist/docs/content.js.map +1 -1
  6. package/dist/index.js +1 -1
  7. package/dist/lib/action-harvest.d.ts +35 -4
  8. package/dist/lib/action-harvest.d.ts.map +1 -1
  9. package/dist/lib/action-harvest.js +233 -50
  10. package/dist/lib/action-harvest.js.map +1 -1
  11. package/dist/lib/action-harvest.test.js +130 -2
  12. package/dist/lib/action-harvest.test.js.map +1 -1
  13. package/dist/lib/auth.d.ts +6 -0
  14. package/dist/lib/auth.d.ts.map +1 -1
  15. package/dist/lib/auth.js +18 -1
  16. package/dist/lib/auth.js.map +1 -1
  17. package/dist/lib/auth.test.d.ts +2 -0
  18. package/dist/lib/auth.test.d.ts.map +1 -0
  19. package/dist/lib/auth.test.js +19 -0
  20. package/dist/lib/auth.test.js.map +1 -0
  21. package/dist/lib/compile-next-steps.d.ts +4 -0
  22. package/dist/lib/compile-next-steps.d.ts.map +1 -0
  23. package/dist/lib/compile-next-steps.js +69 -0
  24. package/dist/lib/compile-next-steps.js.map +1 -0
  25. package/dist/lib/compile-next-steps.test.d.ts +2 -0
  26. package/dist/lib/compile-next-steps.test.d.ts.map +1 -0
  27. package/dist/lib/compile-next-steps.test.js +76 -0
  28. package/dist/lib/compile-next-steps.test.js.map +1 -0
  29. package/dist/lib/file-loader.d.ts.map +1 -1
  30. package/dist/lib/file-loader.js +1 -0
  31. package/dist/lib/file-loader.js.map +1 -1
  32. package/dist/lib/file-writer.d.ts +1 -1
  33. package/dist/lib/file-writer.d.ts.map +1 -1
  34. package/dist/lib/file-writer.js +20 -5
  35. package/dist/lib/file-writer.js.map +1 -1
  36. package/dist/lib/file-writer.test.d.ts +2 -0
  37. package/dist/lib/file-writer.test.d.ts.map +1 -0
  38. package/dist/lib/file-writer.test.js +90 -0
  39. package/dist/lib/file-writer.test.js.map +1 -0
  40. package/dist/lib/shell.test.d.ts +2 -0
  41. package/dist/lib/shell.test.d.ts.map +1 -0
  42. package/dist/lib/shell.test.js +39 -0
  43. package/dist/lib/shell.test.js.map +1 -0
  44. package/dist/skill/docs/changelog.md +515 -0
  45. package/dist/skill/docs/compiler/cloud-compiler/cli.md +16 -0
  46. package/dist/skill/docs/compiler/cloud-compiler/endpoints.md +4 -2
  47. package/dist/skill/docs/compiler/cloud-compiler/local-compiler.md +17 -5
  48. package/dist/skill/docs/compiler/config/auth.md +28 -4
  49. package/dist/skill/docs/compiler/config/index.md +271 -12
  50. package/dist/skill/docs/compiler/config/output.md +49 -3
  51. package/dist/skill/docs/compiler/config/providers.md +16 -5
  52. package/dist/skill/docs/compiler/config/variables.md +5 -0
  53. package/dist/skill/docs/compiler/definitions/access.md +7 -0
  54. package/dist/skill/docs/compiler/definitions/actions.md +156 -9
  55. package/dist/skill/docs/compiler/definitions/firewall.md +6 -1
  56. package/dist/skill/docs/compiler/definitions/rate-limit.md +11 -9
  57. package/dist/skill/docs/compiler/definitions/schema.md +12 -0
  58. package/dist/skill/docs/compiler/targets/hono-api/database/neon.md +357 -20
  59. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/index.md +7 -1
  60. package/dist/skill/docs/stack/account-ui/hooks.md +104 -1
  61. package/dist/skill/docs/stack/auth/plugins/aws-sns.md +20 -3
  62. package/dist/skill/docs/stack/cms/schema-format.md +4 -2
  63. package/dist/skill/docs/stack/cms/schema-registry.md +4 -2
  64. package/dist/skill/docs/stack/realtime/durable-objects.md +12 -7
  65. package/dist/skill/docs/stack/realtime/index.md +37 -7
  66. package/package.json +1 -1
  67. package/src/skill/docs/changelog.md +515 -0
  68. package/src/skill/docs/compiler/cloud-compiler/cli.md +16 -0
  69. package/src/skill/docs/compiler/cloud-compiler/endpoints.md +4 -2
  70. package/src/skill/docs/compiler/cloud-compiler/local-compiler.md +17 -5
  71. package/src/skill/docs/compiler/config/auth.md +28 -4
  72. package/src/skill/docs/compiler/config/index.md +271 -12
  73. package/src/skill/docs/compiler/config/output.md +49 -3
  74. package/src/skill/docs/compiler/config/providers.md +16 -5
  75. package/src/skill/docs/compiler/config/variables.md +5 -0
  76. package/src/skill/docs/compiler/definitions/access.md +7 -0
  77. package/src/skill/docs/compiler/definitions/actions.md +156 -9
  78. package/src/skill/docs/compiler/definitions/firewall.md +6 -1
  79. package/src/skill/docs/compiler/definitions/rate-limit.md +11 -9
  80. package/src/skill/docs/compiler/definitions/schema.md +12 -0
  81. package/src/skill/docs/compiler/targets/hono-api/database/neon.md +357 -20
  82. package/src/skill/docs/compiler/targets/hono-api/using-the-api/index.md +7 -1
  83. package/src/skill/docs/stack/account-ui/hooks.md +104 -1
  84. package/src/skill/docs/stack/auth/plugins/aws-sns.md +20 -3
  85. package/src/skill/docs/stack/cms/schema-format.md +4 -2
  86. package/src/skill/docs/stack/cms/schema-registry.md +4 -2
  87. package/src/skill/docs/stack/realtime/durable-objects.md +12 -7
  88. package/src/skill/docs/stack/realtime/index.md +37 -7
@@ -17,6 +17,11 @@ and feature tables live in the same Postgres database: Better Auth runs on its
17
17
  PostgreSQL/Drizzle adapter, and everything connects through one `DATABASE_URL`.
18
18
  There is no `AUTH_DATABASE_URL`, and split-database mode is a D1-only option.
19
19
 
20
+ In Hyperdrive mode the same one-database rule holds, but the Worker connection
21
+ comes exclusively from `env.HYPERDRIVE.connectionString`: feature queries and
22
+ Better Auth share the generated database helpers. `DATABASE_URL` is then a
23
+ compiler/migration input, not a deployed Worker secret.
24
+
20
25
  Mixing providers — for example D1 for auth with Neon for features — is not
21
26
  supported. The per-service config form is rejected at compile time:
22
27
 
@@ -70,9 +75,149 @@ transactions (see [Interactive transactions](#interactive-transactions)).
70
75
  > that need transactions should use `connectionMode: 'hyperdrive'`.
71
76
 
72
77
 
78
+ ## Named Cloudflare deployment environments
79
+
80
+ Neon Hyperdrive projects can declare isolated Worker targets under
81
+ `providers.database.environments`. A logical `dev` / `prod` pair on a project
82
+ named `attend-v2` deploys through Wrangler as `attend-v2-dev` and
83
+ `attend-v2-prod`:
84
+
85
+ ```typescript title="quickback/quickback.config.ts"
86
+ export default defineConfig({
87
+ name: "attend-v2",
88
+ email: { provider: "cloudflare", from: "hello@attend.vip" },
89
+ bindings: {
90
+ secrets: [
91
+ { name: "EVENT_PASS_HMAC_PEPPER_V1", required: true },
92
+ ],
93
+ },
94
+ providers: {
95
+ runtime: defineRuntime("cloudflare"),
96
+ database: {
97
+ name: "neon",
98
+ config: {
99
+ connectionMode: "hyperdrive",
100
+ hyperdrive: { id: "ffffffffffffffffffffffffffffffff" },
101
+ },
102
+ environments: {
103
+ dev: {
104
+ branch: "dev",
105
+ worker: {
106
+ env: "dev",
107
+ workersDev: true,
108
+ previewUrls: false,
109
+ vars: {
110
+ ENVIRONMENT: "dev",
111
+ BETTER_AUTH_URL: "https://attend-v2-dev.example.workers.dev",
112
+ },
113
+ requiredSecrets: [
114
+ "BETTER_AUTH_SECRET",
115
+ "EVENT_PASS_HMAC_PEPPER_V1",
116
+ ],
117
+ bindings: {
118
+ hyperdrive: {
119
+ id: "11111111111111111111111111111111",
120
+ localConnectionString: "postgresql://quickback:dev-only@127.0.0.1:5432/attend_v2",
121
+ },
122
+ kv: { id: "22222222222222222222222222222222" },
123
+ rateLimits: {
124
+ RL_200_60: "61001200",
125
+ RL_1000_60: "61002000",
126
+ },
127
+ sendEmail: { name: "EMAIL" },
128
+ },
129
+ },
130
+ },
131
+ prod: {
132
+ branch: "production",
133
+ worker: {
134
+ env: "prod",
135
+ workersDev: true,
136
+ previewUrls: false,
137
+ vars: {
138
+ ENVIRONMENT: "prod",
139
+ BETTER_AUTH_URL: "https://attend-v2-prod.example.workers.dev",
140
+ },
141
+ requiredSecrets: [
142
+ "BETTER_AUTH_SECRET",
143
+ "EVENT_PASS_HMAC_PEPPER_V1",
144
+ ],
145
+ bindings: {
146
+ hyperdrive: { id: "33333333333333333333333333333333" },
147
+ kv: { id: "44444444444444444444444444444444" },
148
+ rateLimits: {
149
+ RL_200_60: "62001200",
150
+ RL_1000_60: "62002000",
151
+ },
152
+ sendEmail: { name: "EMAIL" },
153
+ },
154
+ },
155
+ },
156
+ },
157
+ },
158
+ auth: defineAuth("better-auth"),
159
+ },
160
+ });
161
+ ```
162
+
163
+ Wrangler bindings and variables are non-inheritable. Quickback therefore emits
164
+ the generated vars, required-secret declaration, Hyperdrive, KV, rate-limit,
165
+ and Cloudflare Email blocks inside **every** `[env.<name>]` target. The base
166
+ Worker carries no deployable stateful binding and has `workers_dev = false` /
167
+ `preview_urls = false`, so a bare deploy cannot accidentally point at shared or
168
+ placeholder state.
169
+
170
+ The environment contract is intentionally exact and fails closed:
171
+
172
+ - `workersDev: true` and `previewUrls: false` must be explicit for each target.
173
+ - The auth provider must currently be Better Auth. External auth needs a
174
+ non-inheritable service binding, so it remains rejected until named targets
175
+ can require an explicit per-environment service-binding override.
176
+ - Hyperdrive and KV IDs must be real 32-character Cloudflare resource IDs and
177
+ cannot be reused between environments.
178
+ - Named environments must include a logical `dev` target. It is selected by
179
+ `npm run dev` and must own a `bindings.hyperdrive.localConnectionString`.
180
+ Quickback emits that
181
+ development-only URL only inside its named Hyperdrive block and rejects it
182
+ on every other target, so `prod` always resolves its deployed connection
183
+ from the remote Hyperdrive ID.
184
+ - `rateLimits` must contain exactly the binding names generated by the current
185
+ feature set, with account-unique integer namespace IDs. Add or remove a rate
186
+ limit and the next compile tells you which override changed.
187
+ - `requiredSecrets` must exactly match the generated runtime inventory:
188
+ `BETTER_AUTH_SECRET`, a custom `auth.jwt.secretEnv` when configured,
189
+ `ENCRYPTION_KEK` when envelope-encrypted columns are present, and every
190
+ custom secret declared with `required: true`. It also includes the shared
191
+ `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` credentials when generated
192
+ Better Auth code uses SES, SNS, or AWS-backed anonymous-account upgrades;
193
+ every enabled social provider's `AUTH_<PROVIDER>_CLIENT_ID` and
194
+ `AUTH_<PROVIDER>_CLIENT_SECRET`; plus the configured R2
195
+ account/access/secret env names when presigned uploads are enabled. Values
196
+ remain out of source control; set them with
197
+ `wrangler secret put <NAME> --env dev` (and again for `prod`).
198
+ - Include `sendEmail: { name: "EMAIL" }` when the generated runtime uses
199
+ Cloudflare Email Service; omit it when email is not generated.
200
+ - Every source of a generated top-level custom route is currently rejected for
201
+ named targets: `providers.runtime.config.routes`, `domain`, CMS/Account/Admin
202
+ domains, `auth.domain`, `api.domain`, and hostname-mounted app domains and
203
+ aliases. Quickback will add explicit per-environment route overrides before
204
+ opening that gate.
205
+
206
+ Generated `npm run dev` selects the `dev` target (`wrangler dev --env dev`).
207
+ Quickback omits the bare `deploy` script for named-environment projects and
208
+ generates explicit `npm run deploy:dev` / `npm run deploy:prod` scripts. Each
209
+ maps to its configured Wrangler environment. Apply that branch's migrations
210
+ first; migrations intentionally remain a separate target-owned step.
211
+
212
+ Projects that omit `environments` retain the existing `wrangler.toml` and
213
+ package scripts byte-for-byte. Named environments are currently restricted to
214
+ Neon with `connectionMode: "hyperdrive"` and Better Auth; Quickback rejects
215
+ other providers or partial binding sets instead of emitting a Worker that can
216
+ deploy but fail at runtime.
217
+
73
218
  ## Environment variables
74
219
 
75
- Three connection points, each read by a different tool:
220
+ HTTP mode has three connection points, each read by a different tool:
76
221
 
77
222
  | Where | File / store | Read by |
78
223
  |-------|--------------|---------|
@@ -106,6 +251,41 @@ run as the privileged `quickback_admin` role when it is set and fall back to
106
251
  `DATABASE_URL` when it is not. Never deploy `DATABASE_MIGRATION_URL` to the
107
252
  Worker.
108
253
 
254
+ ### Hyperdrive runtime credentials
255
+
256
+ With `connectionMode: "hyperdrive"`, do not deploy `DATABASE_URL` to the
257
+ Worker. Configure the `HYPERDRIVE` binding with query caching disabled and keep
258
+ `DATABASE_URL` / `DATABASE_MIGRATION_URL` only in the compiler or CI
259
+ environment for Drizzle schema generation and migrations. Better Auth and
260
+ feature queries both use Hyperdrive at runtime, eliminating a second direct
261
+ Neon connection lane.
262
+
263
+ For local `wrangler dev` without named environments, set
264
+ `providers.database.config.hyperdrive.localConnectionString` to a local or
265
+ development-only Postgres URL. With named environments, put it on the target
266
+ selected by the generated local dev script instead:
267
+
268
+ ```typescript
269
+ environments: {
270
+ dev: {
271
+ worker: {
272
+ bindings: {
273
+ hyperdrive: {
274
+ id: "11111111111111111111111111111111",
275
+ localConnectionString: "postgresql://quickback:dev-only@127.0.0.1:5432/attend_v2",
276
+ },
277
+ },
278
+ },
279
+ },
280
+ }
281
+ ```
282
+
283
+ Quickback requires the logical `dev` target, rejects the top-level local
284
+ override when named environments exist, and rejects `localConnectionString`
285
+ on staging or production targets. Wrangler uses this field only for local
286
+ development; deployed Workers obtain their
287
+ connection string from the Hyperdrive configuration identified by `id`.
288
+
109
289
  <Callout>
110
290
  The generated setup uses three Postgres roles: `quickback_owner` (NOLOGIN object
111
291
  owner for the app/auth schemas), `quickback_admin` (migration/setup actor — use
@@ -126,26 +306,48 @@ database-level `CREATE` even as a no-op and previously forced every migrate
126
306
  back onto the owner credential. (A change to the **security/RLS config** appends
127
307
  a new `quickback_rls` migration that re-runs the role bootstrap, so re-point
128
308
  `DATABASE_MIGRATION_URL` at the owner credential for that one apply.)
309
+
310
+ Each security migration first removes direct `PUBLIC` and `quickback` runtime
311
+ privileges from the Drizzle schema, journal table, journal sequences, and
312
+ database-level `CREATE`, then restores the migration role's capability. The
313
+ audit schema/table likewise revoke prior direct grants before restoring only
314
+ runtime schema usage + table `INSERT` and admin forensic access. Reapplying a
315
+ migration therefore converges privilege drift instead of merely adding grants.
129
316
  </Callout>
130
317
 
131
318
  ## Better Auth schema generation
132
319
 
133
- `src/auth/schema.ts` is owned by the Better Auth CLI. The generated `build`
134
- script regenerates it before typechecking:
320
+ `src/auth/schema.ts` is a compiler-owned artifact derived with the Better Auth
321
+ CLI during `quickback compile`. The generated `build` script is deliberately
322
+ read-only with respect to generated source:
135
323
 
136
324
  ```bash
137
- npm run build # runs auth:schema, then tsc
325
+ quickback compile # regenerates src/auth/schema.ts and the project output
326
+ npm run build # runs tsc only; does not rewrite generated files
138
327
  ```
139
328
 
140
- `auth:schema` expands to:
329
+ For schema-generator diagnostics, the explicit `auth:schema` command expands
330
+ to:
141
331
 
142
332
  ```bash
143
333
  npx better-auth generate --config ./src/lib/auth.ts --output ./src/auth/schema.ts --yes \
144
334
  && node scripts/quickback-qualify-auth-schema.mjs
145
335
  ```
146
336
 
337
+ The `better-auth` executable comes from the `auth` devDependency in the
338
+ generated `package.json` — that's the Better Auth CLI package (the
339
+ `better-auth` runtime package ships no bin).
340
+
147
341
  The qualifier script adjusts the CLI output for Postgres schema placement.
148
- Don't hand-edit `src/auth/schema.ts` — regenerate it instead.
342
+ `auth:schema` produces the intermediate Better Auth output and may remove
343
+ Quickback's generated-file envelope. Do not commit that intermediate file;
344
+ rerun `quickback compile` to restore the canonical project bytes. Don't
345
+ hand-edit `src/auth/schema.ts`.
346
+
347
+ Recompiling also replaces previously generated `package.json` lifecycle
348
+ commands with their current definitions. An existing project whose `build`
349
+ script still runs `auth:schema` therefore converges to the TypeScript-only
350
+ build, while unrelated custom scripts remain intact.
149
351
 
150
352
  ## Migrations
151
353
 
@@ -166,6 +368,22 @@ content-addressed `<idx>_quickback_rls_<hash>` migration, so one
166
368
  appends a new entry — recompiles with unchanged security append nothing. No
167
369
  manual SQL application step exists.
168
370
 
371
+ Quickback also dependency-orders Drizzle's standalone constraint replacements.
372
+ When a composite unique or primary key and its consuming foreign key are both
373
+ replaced, the generated migration drops the dependent foreign key first, drops
374
+ and recreates the referenced key, then recreates the foreign key. This avoids
375
+ Postgres `2BP01` dependency failures without `CASCADE` and without requiring a
376
+ hand-edited migration. Already-correct migrations remain byte-identical.
377
+
378
+ Cross-schema and composite relationships that cannot live in one generated
379
+ Drizzle schema may be declared with
380
+ [`compiler.migrations.foreignKeys`](/compiler/config#neon-foreign-key-migrations).
381
+ Quickback appends them to that same content-addressed migration after the
382
+ schema tables and target unique keys exist. Declarations are deterministic and
383
+ replay-safe: an existing constraint must match exactly, while existing orphan
384
+ rows fail the `VALIDATE CONSTRAINT` step. Foreign keys enforce integrity only;
385
+ keep authorization and business state transitions in the API action layer.
386
+
169
387
  ## How Worker-scoped RLS works
170
388
 
171
389
  Quickback does **not** send browser or mobile clients directly to Neon, and it
@@ -173,9 +391,10 @@ does **not** use Neon Authorize / a JWKS endpoint. Clients authenticate with the
173
391
  Cloudflare Worker; the Worker verifies the Better Auth session or API key, runs
174
392
  the access checks, and then performs the database call as a trusted proxy.
175
393
 
176
- For every feature-table query, the generated database client opens a Neon HTTP
177
- batch (an implicit transaction) whose **first** statement writes the verified
178
- caller context into transaction-local Postgres settings:
394
+ For every feature-table query, the generated database client opens a
395
+ claims-scoped transaction (an implicit Neon HTTP batch or a Hyperdrive
396
+ transaction) whose **first** statement writes the verified caller context into
397
+ transaction-local Postgres settings:
179
398
 
180
399
  ```sql
181
400
  -- Injected by the Worker as the batch's first statement (is_local = true):
@@ -183,7 +402,13 @@ SELECT
183
402
  set_config('quickback.service_role', '', true),
184
403
  set_config('request.jwt.claim.sub', 'usr_123', true),
185
404
  set_config('request.jwt.claim.org_id', 'org_abc', true),
186
- set_config('request.jwt.claim.team_id', '', true);
405
+ set_config('request.jwt.claim.team_id', '', true),
406
+ set_config('quickback.principal.type', '', true),
407
+ set_config('quickback.principal.actor_type', '', true),
408
+ set_config('quickback.principal.actor_id', '', true),
409
+ set_config('quickback.principal.session_id', '', true),
410
+ set_config('quickback.principal.family_id', '', true),
411
+ set_config('quickback.principal.claims', '{}', true);
187
412
  ```
188
413
 
189
414
  RLS policies read those settings through Quickback-defined helper functions —
@@ -202,7 +427,16 @@ $$ LANGUAGE SQL STABLE SET search_path = public;
202
427
  Because the settings are transaction-local (`set_config(..., true)`), they
203
428
  apply only to the current batch and never leak between requests. If the Worker
204
429
  never stamps a user id, `auth.user_id()` returns `NULL` and the restrictive
205
- `deny_anon` policy blocks the query — fail closed.
430
+ `deny_anon` policy blocks the query unless a verified delegated principal is
431
+ present — fail closed. Account requests explicitly clear all principal fields;
432
+ delegated requests explicitly clear the account/org/team fields.
433
+
434
+ An API key's organization metadata is only a candidate scope. Before the
435
+ middleware stamps it into `AppContext`, the generated Neon membership lookup
436
+ opens a request-scoped database handle with the verified API-key owner as
437
+ `userId` and the candidate organization as `orgId`, then requires the member
438
+ row to match both values. A missing or RLS-denied row clears organization and
439
+ role authority.
206
440
 
207
441
  ## Row Level Security
208
442
 
@@ -226,8 +460,72 @@ USING (
226
460
  ```
227
461
 
228
462
  Every feature table also gets a restrictive `deny_anon` policy (blocks queries
229
- with no stamped user id) and a `service_role` policy (admits Worker-internal
230
- contexts — see [Background jobs and cross-tenant actions](#background-jobs-and-cross-tenant-actions)).
463
+ with neither a stamped user id nor a delegated principal) and a `service_role`
464
+ policy (admits Worker-internal contexts — see
465
+ [Background jobs and cross-tenant actions](#background-jobs-and-cross-tenant-actions)).
466
+
467
+ ### Delegated principal RLS (contract v2)
468
+
469
+ Delegated principals require Cloudflare + Neon Hyperdrive. Their proof hook
470
+ returns only a digest and receives no database handle. Quickback then runs one
471
+ lookup under an internal lookup-only principal whose RLS policy admits only the
472
+ configured table row matching `credentialDigest`, plus any configured active
473
+ status condition. The generated unique lookup index is content-addressed: a
474
+ changed table, digest column, or definition drops the prior logical index and
475
+ creates the exact replacement. Names are hash-suffixed to avoid collisions and
476
+ remain inside PostgreSQL's 63-byte identifier limit.
477
+
478
+ After the lookup, the normal request database handle carries the resolved
479
+ principal type, actor, optional session/family, and JSON claims in the same
480
+ transaction-local preamble shown above. RLS reads them with:
481
+
482
+ | Function | Purpose |
483
+ |----------|---------|
484
+ | `get_principal_type()` | Exact configured type such as `event_delegate` |
485
+ | `get_principal_actor_id()` | Stable delegated actor id |
486
+ | `get_principal_session_id()` | Optional session id |
487
+ | `get_principal_family_id()` | Optional session-family id |
488
+ | `get_principal_claim(name)` | One configured string claim such as `eventId` or `personId` |
489
+
490
+ Generated request types are a closed union of the configured principal names,
491
+ literal actor types, exact session shape, and configured claim keys. The Neon
492
+ database context uses the same resolved union plus separate compiler-internal
493
+ `__credential_lookup__:<type>` variants. Lookup-only authority therefore
494
+ cannot appear in an action `AppContext`, and a delegated action context cannot
495
+ carry account/org/team/membership fields.
496
+
497
+ `resource.databaseAccess` emits operation-specific, RLS-only policies for
498
+ authored actions and support tables. It does not mount generic routes or
499
+ OpenAPI operations. Every authorization path must include at least one
500
+ SQL-lowerable record equality; any unbounded OR arm or principal/role-only leaf
501
+ fails compilation. This lets an organization account lane and a disjoint
502
+ event/person delegated lane share a table without weakening either:
503
+
504
+ ```typescript
505
+ databaseAccess: {
506
+ select: {
507
+ or: [
508
+ {
509
+ roles: ["AUTHENTICATED"],
510
+ record: { organizationId: { equals: "$ctx.activeOrgId" } },
511
+ },
512
+ {
513
+ principals: ["event_delegate"],
514
+ record: {
515
+ eventId: { equals: "$ctx.principal.claims.eventId" },
516
+ personId: { equals: "$ctx.principal.claims.personId" },
517
+ },
518
+ },
519
+ ],
520
+ },
521
+ }
522
+ ```
523
+
524
+ Postgres combines the record comparisons inside each arm with AND. Restrictive
525
+ per-operation principal fences also cap every permissive policy, so a public,
526
+ firewall-exception, or old permissive policy cannot admit the wrong principal
527
+ type. The action still owns all application behavior; these policies only
528
+ constrain which rows its caller-scoped `db` or transaction may touch.
231
529
 
232
530
  ### Firewall patterns
233
531
 
@@ -489,7 +787,24 @@ providers: {
489
787
  ```
490
788
 
491
789
  The compiler emits the `[[hyperdrive]]` wrangler binding pointing at your Neon
492
- **direct** connection string.
790
+ **direct** connection string. Its request-scoped postgres.js client uses
791
+ `max: 5`, disables prepared statements, and skips type-fetch round trips — the
792
+ small client pool bounds origin connections per Worker isolate while
793
+ Hyperdrive owns the shared connection pool.
794
+
795
+ > Postgres authorizes `SELECT … FOR UPDATE` as both a read and a write: the row
796
+ > must pass its `SELECT` **and** `UPDATE` policies. This matters for delegated
797
+ > principals because Quickback emits a restrictive update fence for every table.
798
+ > A principal with `databaseAccess.select` but no matching
799
+ > `databaseAccess.update` can read an eligible row, but cannot lock it with
800
+ > `.for("update")`.
801
+ >
802
+ > Keep read-only eligibility and reference-table lookups as ordinary scoped
803
+ > selects. Lock the mutable grant, capacity, or redemption row that the action is
804
+ > authorized to update. If an action legitimately must lock another table,
805
+ > declare a narrowly bounded `databaseAccess.update` rule for that principal;
806
+ > do not broaden or bypass the generated principal fence.
807
+
493
808
 
494
809
  **Security is preserved, unchanged.** The verified caller claims run as the
495
810
  first transaction-local statement inside the transaction (the same
@@ -525,23 +840,45 @@ Mixed database providers (e.g. D1 auth + Neon features) remain unsupported.
525
840
 
526
841
  ## Deploying
527
842
 
528
- The generated `deploy` script runs migrations, then ships the Worker:
843
+ For an unnamed target, the generated `deploy` script runs migrations, then
844
+ ships the Worker:
529
845
 
530
846
  ```bash
531
847
  npm run deploy # runs db:migrate (drizzle-kit) then wrangler deploy
532
848
  ```
533
849
 
534
- Before the first deploy, put the runtime secrets in Worker secrets and make sure
535
- the Worker's KV namespace (used by Better Auth for sessions and JWT revocation)
536
- is provisioned:
850
+ HTTP mode reads `DATABASE_URL` in the Worker, so set both runtime secrets before
851
+ its first deploy:
537
852
 
538
853
  ```bash
539
854
  npx wrangler secret put DATABASE_URL # pooled quickback role URL
540
855
  npx wrangler secret put BETTER_AUTH_SECRET
541
856
  ```
542
857
 
543
- The generated Neon client fails fast at boot if `DATABASE_URL` is missing, so a
544
- misconfigured deploy surfaces immediately rather than on the first query.
858
+ The generated HTTP client fails fast at boot if `DATABASE_URL` is missing.
859
+
860
+ Hyperdrive mode gets its runtime connection string from the `HYPERDRIVE`
861
+ binding and must **not** receive a Worker `DATABASE_URL` secret. Its
862
+ `DATABASE_URL` / `DATABASE_MIGRATION_URL` values remain local or CI migration
863
+ inputs only. Set `BETTER_AUTH_SECRET` and any other exact generated secret
864
+ inventory, then deploy:
865
+
866
+ ```bash
867
+ npx wrangler secret put BETTER_AUTH_SECRET
868
+ npm run deploy
869
+ ```
870
+
871
+ Named Hyperdrive targets intentionally omit the bare `deploy` script and keep
872
+ the base Worker non-deployable. Apply the target branch's migrations, set each
873
+ secret with `--env dev` or `--env prod`, then use an explicit target:
874
+
875
+ ```bash
876
+ npx wrangler secret put BETTER_AUTH_SECRET --env dev
877
+ npm run deploy:dev
878
+
879
+ npx wrangler secret put BETTER_AUTH_SECRET --env prod
880
+ npm run deploy:prod
881
+ ```
545
882
 
546
883
  > Live runtime smoke testing against a deployed Neon Worker is still being brought
547
884
  > up; the compile/typecheck/migrate path is verified end-to-end (including
@@ -4,12 +4,18 @@ When you run `quickback compile`, Quickback generates a complete REST API from y
4
4
 
5
5
  ## Base URL
6
6
 
7
- All generated endpoints are served under `/api/v1/`:
7
+ Generated endpoints use the contract selected in `quickback.config.ts`. The
8
+ backward-compatible default is `/api/v1/`; projects with
9
+ `contract: { version: "v2" }` use `/api/v2/` (and `/auth/v2/` for Better Auth):
8
10
 
9
11
  ```
10
12
  https://your-api.com/api/v1/{resource}
11
13
  ```
12
14
 
15
+ The examples below show the default v1 contract. Replace `/api/v1` with
16
+ `/api/v2` when the project selects v2. The generated OpenAPI document is the
17
+ authoritative path list for the compiled project.
18
+
13
19
  The resource name is derived from the filename: `jobs.ts` → `/api/v1/jobs`.
14
20
 
15
21
  ## Endpoint Overview
@@ -1,6 +1,6 @@
1
1
  # Auth Hooks
2
2
 
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.
3
+ Quickback discovers project-level auth hooks at `quickback/hooks/`. Most `before-`/`after-` lifecycle hooks wire directly into [Better Auth's `databaseHooks`](https://www.better-auth.com/docs/concepts/database#database-hooks); `before-email-otp-activate.ts` is a narrower compiler-owned atomic ceremony, and the `resolve-*` hooks are trusted server resolvers called from generated middleware (OAuth) or the email send. 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
 
@@ -11,6 +11,7 @@ quickback/
11
11
  hooks/
12
12
  after-user-create.ts
13
13
  before-user-create.ts
14
+ before-email-otp-activate.ts
14
15
  after-session-create.ts
15
16
  after-admin-user-create.ts
16
17
  resolve-oauth-context.ts
@@ -25,6 +26,7 @@ Each file has a single default export — an `async (entity, ctx) => ...` functi
25
26
  |--------------------------------|-----------------------------------|----------|---------------------------------|
26
27
  | `before-user-create.ts` | `databaseHooks.user.create.before` | `User` | `void \| { data?: Partial<User> }` |
27
28
  | `after-user-create.ts` | `databaseHooks.user.create.after` | `User` | `void` |
29
+ | `before-email-otp-activate.ts` | Atomic email-OTP activation before `user.update` | `{ userId, email, user }` | `void \| false` |
28
30
  | `after-session-create.ts` | `databaseHooks.session.create.after` | `Session` | `void` |
29
31
  | `after-admin-user-create.ts` | `databaseHooks.user.create.after` (filtered) | `User` | `void` |
30
32
  | `resolve-oauth-context.ts` | OAuth bearer middleware | OAuth identity + session | Partial `AppContext` tenant fields |
@@ -34,6 +36,100 @@ Each file has a single default export — an `async (entity, ctx) => ...` functi
34
36
 
35
37
  Filenames outside this set are a hard compile-time error so a typo never silently disables a hook. Add events by extending [`apps/compiler/src/parser/hooks.ts`](https://github.com/paulstenhouse/quickback-compiler) (and the matching CLI mirror).
36
38
 
39
+ ## Atomic email-OTP activation
40
+
41
+ Use `before-email-otp-activate.ts` when an existing dormant account must pass
42
+ project business rules before email verification and session creation become
43
+ durable. Quickback owns the transaction and identity proof; your API hook owns
44
+ the business decision.
45
+
46
+ This surface is deliberately explicit and narrow. It requires all of:
47
+
48
+ - `contract.version: "v2"`
49
+ - Cloudflare Workers
50
+ - one Neon database using `connectionMode: "hyperdrive"`
51
+ - the Better Auth `emailOtp` plugin with effective `disableSignUp: true`
52
+ - `atomicAuthRoutes: ["emailOtpSignIn"]`
53
+ - `quickback/hooks/before-email-otp-activate.ts`
54
+
55
+ ```ts title="quickback/quickback.config.ts"
56
+ providers: {
57
+ runtime: defineRuntime("cloudflare"),
58
+ database: defineDatabase("neon", {
59
+ connectionMode: "hyperdrive",
60
+ hyperdrive: { id: "your-hyperdrive-id" },
61
+ }),
62
+ auth: defineAuth("better-auth", {
63
+ plugins: { emailOtp: { disableSignUp: true } },
64
+ atomicAuthRoutes: ["emailOtpSignIn"],
65
+ }),
66
+ }
67
+ ```
68
+
69
+ The hook receives the proven, pre-update user identity and the transaction-bound
70
+ full application database:
71
+
72
+ ```ts title="quickback/hooks/before-email-otp-activate.ts"
73
+ import { and, eq } from "drizzle-orm";
74
+
75
+ export default async function beforeEmailOtpActivate(
76
+ { userId, email, user },
77
+ { db, schema, atomicRoute },
78
+ ) {
79
+ // user.emailVerified is authoritatively false here. Keep event/pass/status
80
+ // policy in this project API hook; Quickback supplies only the ceremony.
81
+ if (atomicRoute !== "emailOtpSignIn" || user.emailVerified !== false) return false;
82
+
83
+ const [candidate] = await db
84
+ .select({ id: schema.admissions.id })
85
+ .from(schema.admissions)
86
+ .where(and(
87
+ eq(schema.admissions.userId, userId),
88
+ eq(schema.admissions.email, email),
89
+ ))
90
+ .limit(1);
91
+
92
+ if (!candidate) return false;
93
+ // Any business writes performed through db remain in this same transaction.
94
+ }
95
+ ```
96
+
97
+ For the exact `POST <auth-base>/sign-in/email-otp` request, the generated
98
+ Worker opens one `createServiceDb(env).transaction(...)`, builds Better Auth
99
+ with its Drizzle adapter bound to `tx`, and supplies that same `tx` as both
100
+ `db` and `authDb`. After OTP validation, Quickback proves the target by reading
101
+ the normalized request email through the transaction-bound Better Auth adapter.
102
+ Only a matching user whose authoritative `emailVerified` value is `false`
103
+ reaches the hook.
104
+
105
+ The generated `user.update.before` wrapper imports and invokes the semantic
106
+ hook exactly once. Its `db` / `authDb` values retain the transaction's real
107
+ Drizzle `select` type, so hooks can declare a narrow
108
+ `Pick<DatabaseInstance, "select">` contract without casts.
109
+
110
+ The hook runs in `databaseHooks.user.update.before`, before Better Auth takes
111
+ the user update lock. That preserves the project's business lock order; a
112
+ session-create hook would take the user lock first and can deadlock with an
113
+ issuance path that locks application rows before the user.
114
+
115
+ The transaction commits only after the verification update and session insert
116
+ succeed. A denied activation, a non-ok response after activation begins, or any
117
+ 5xx response throws a private rollback sentinel, so OTP consumption, hook
118
+ writes, user verification, and session creation roll back together. Invalid OTP
119
+ 4xx responses that never begin activation are not converted to exceptions, so
120
+ Better Auth's attempt counter still commits. Already-verified users do not rerun
121
+ the dormant-account hook. OTP sending and every other auth route remain outside
122
+ this transaction. The atomic wrapper preserves Better Auth's original handler
123
+ before decorating the auth object, so non-atomic session, account, and plugin
124
+ requests are forwarded exactly once instead of re-entering the wrapper.
125
+
126
+ Return `false` for an expected policy denial. The compiler short-circuits Better
127
+ Auth with a private error and maps the rolled-back ceremony to a generic 403;
128
+ it never lets Better Auth continue to session creation after a false return.
129
+ Unexpected throws are operational failures: the generated handler rolls back,
130
+ emits only the metadata event `auth.atomic_email_otp_operational_rollback`, and
131
+ returns a generic 503 without raw error content.
132
+
37
133
  ## OAuth context resolver
38
134
 
39
135
  First-class MCP OAuth validates the access token and live Better Auth session
@@ -124,6 +220,12 @@ type HookCtx = {
124
220
 
125
221
  `authDb` is the load-bearing piece: hooks must write to the auth DB via Drizzle directly. See the [CSRF caveat](#csrf-caveat-server-side-org-create) below. `authSchema` is the namespace export of the generated auth schema module; destructure the tables you need.
126
222
 
223
+ The atomic email-OTP hook additionally receives `db` (the transaction-bound
224
+ full application Drizzle client), `schema` (the full generated application
225
+ schema), and `atomicRoute: "emailOtpSignIn"`. In a single-database Neon project,
226
+ `db` and `authDb` are the same transaction handle; the two schema namespaces
227
+ make project and Better Auth tables explicit.
228
+
127
229
  ## Writing hooks: use built-ins where possible
128
230
 
129
231
  Hook source files are evaluated by the Better Auth schema-generation step at compile time, which runs in a stripped-down sandbox that **does not see your project's `node_modules`**. A hook that imports `@paralleldrive/cuid2`, `nanoid`, or any other third-party package will fail compile with a "module not found" error during the auth-schema-generation step — even if the package is installed and runs fine in the deployed Worker.
@@ -146,6 +248,7 @@ What happens when a hook throws is the #1 thing that bites people:
146
248
  | Hook | Throw effect |
147
249
  |-----------------------|------------------------------------------------------------------------------|
148
250
  | `before-user-create` | Signup aborts. The user is **not** created. Throw a typed error to gate. |
251
+ | `before-email-otp-activate` | The entire atomic ceremony rolls back: OTP consumption, hook writes, verification update, and session insert. |
149
252
  | `after-user-create` | The user **is** created (the BA insert already committed). Any derived rows your hook started writing become orphans. |
150
253
  | `after-session-create`| Same as above — the session row exists; partial writes leak. |
151
254