@quickback-dev/cli 0.40.2 → 0.47.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 (107) hide show
  1. package/dist/commands/claude.d.ts.map +1 -1
  2. package/dist/commands/claude.js +8 -0
  3. package/dist/commands/claude.js.map +1 -1
  4. package/dist/commands/compile.d.ts.map +1 -1
  5. package/dist/commands/compile.js +13 -2
  6. package/dist/commands/compile.js.map +1 -1
  7. package/dist/commands/compile.test.js +26 -21
  8. package/dist/commands/compile.test.js.map +1 -1
  9. package/dist/commands/create.js +6 -9
  10. package/dist/commands/create.js.map +1 -1
  11. package/dist/commands/login.d.ts.map +1 -1
  12. package/dist/commands/login.js +0 -9
  13. package/dist/commands/login.js.map +1 -1
  14. package/dist/commands/start.d.ts.map +1 -1
  15. package/dist/commands/start.js +6 -7
  16. package/dist/commands/start.js.map +1 -1
  17. package/dist/commands/whoami.d.ts.map +1 -1
  18. package/dist/commands/whoami.js +0 -4
  19. package/dist/commands/whoami.js.map +1 -1
  20. package/dist/docs/content.d.ts.map +1 -1
  21. package/dist/docs/content.js +22 -32
  22. package/dist/docs/content.js.map +1 -1
  23. package/dist/index.js +1 -1
  24. package/dist/lib/api-client.d.ts +0 -12
  25. package/dist/lib/api-client.d.ts.map +1 -1
  26. package/dist/lib/api-client.js +0 -10
  27. package/dist/lib/api-client.js.map +1 -1
  28. package/dist/lib/api-client.test.js +13 -8
  29. package/dist/lib/api-client.test.js.map +1 -1
  30. package/dist/lib/auth.d.ts +0 -1
  31. package/dist/lib/auth.d.ts.map +1 -1
  32. package/dist/lib/auth.js.map +1 -1
  33. package/dist/lib/compiler-stubs.d.ts +12 -0
  34. package/dist/lib/compiler-stubs.d.ts.map +1 -1
  35. package/dist/lib/compiler-stubs.js +18 -0
  36. package/dist/lib/compiler-stubs.js.map +1 -1
  37. package/dist/lib/file-loader.d.ts +14 -0
  38. package/dist/lib/file-loader.d.ts.map +1 -1
  39. package/dist/lib/file-loader.js +63 -9
  40. package/dist/lib/file-loader.js.map +1 -1
  41. package/dist/skill/SKILL.md +76 -6
  42. package/dist/skill/docs/changelog.md +278 -0
  43. package/dist/skill/docs/compiler/cloud-compiler/authentication.md +1 -2
  44. package/dist/skill/docs/compiler/cloud-compiler/cli.md +7 -8
  45. package/dist/skill/docs/compiler/config/agents.md +49 -1
  46. package/dist/skill/docs/compiler/config/auth.md +20 -5
  47. package/dist/skill/docs/compiler/config/security.md +46 -0
  48. package/dist/skill/docs/compiler/definitions/access.md +1 -1
  49. package/dist/skill/docs/compiler/definitions/actions.md +46 -4
  50. package/dist/skill/docs/compiler/definitions/diagnostics.md +88 -57
  51. package/dist/skill/docs/compiler/definitions/scopes.md +11 -3
  52. package/dist/skill/docs/compiler/getting-started/full-example.md +5 -3
  53. package/dist/skill/docs/compiler/getting-started/index.md +7 -7
  54. package/dist/skill/docs/compiler/getting-started/patterns.md +39 -5
  55. package/dist/skill/docs/compiler/getting-started/template-blog.md +65 -44
  56. package/dist/skill/docs/compiler/getting-started/template-cloudflare.md +4 -5
  57. package/dist/skill/docs/compiler/getting-started/template-empty.md +7 -1
  58. package/dist/skill/docs/compiler/getting-started/templates.md +6 -6
  59. package/dist/skill/docs/compiler/targets/hono-api/using-the-api/openapi.md +23 -0
  60. package/dist/skill/docs/stack/account-ui/features/passwordless.md +4 -10
  61. package/dist/skill/docs/stack/account-ui/hooks.md +24 -1
  62. package/dist/skill/docs/stack/auth/plugins/aws-ses.md +0 -7
  63. package/dist/skill/docs/stack/auth/plugins/index.md +36 -39
  64. package/dist/templates/registry.d.ts +0 -12
  65. package/dist/templates/registry.d.ts.map +1 -1
  66. package/dist/templates/registry.js +0 -42
  67. package/dist/templates/registry.js.map +1 -1
  68. package/package.json +1 -1
  69. package/src/skill/SKILL.md +76 -6
  70. package/src/skill/docs/changelog.md +278 -0
  71. package/src/skill/docs/compiler/cloud-compiler/authentication.md +1 -2
  72. package/src/skill/docs/compiler/cloud-compiler/cli.md +7 -8
  73. package/src/skill/docs/compiler/config/agents.md +49 -1
  74. package/src/skill/docs/compiler/config/auth.md +20 -5
  75. package/src/skill/docs/compiler/config/security.md +46 -0
  76. package/src/skill/docs/compiler/definitions/access.md +1 -1
  77. package/src/skill/docs/compiler/definitions/actions.md +46 -4
  78. package/src/skill/docs/compiler/definitions/diagnostics.md +88 -57
  79. package/src/skill/docs/compiler/definitions/scopes.md +11 -3
  80. package/src/skill/docs/compiler/getting-started/full-example.md +5 -3
  81. package/src/skill/docs/compiler/getting-started/index.md +7 -7
  82. package/src/skill/docs/compiler/getting-started/patterns.md +39 -5
  83. package/src/skill/docs/compiler/getting-started/template-blog.md +65 -44
  84. package/src/skill/docs/compiler/getting-started/template-cloudflare.md +4 -5
  85. package/src/skill/docs/compiler/getting-started/template-empty.md +7 -1
  86. package/src/skill/docs/compiler/getting-started/templates.md +6 -6
  87. package/src/skill/docs/compiler/targets/hono-api/using-the-api/openapi.md +23 -0
  88. package/src/skill/docs/stack/account-ui/features/passwordless.md +4 -10
  89. package/src/skill/docs/stack/account-ui/hooks.md +24 -1
  90. package/src/skill/docs/stack/auth/plugins/aws-ses.md +0 -7
  91. package/src/skill/docs/stack/auth/plugins/index.md +36 -39
  92. package/dist/commands/init.d.ts +0 -6
  93. package/dist/commands/init.d.ts.map +0 -1
  94. package/dist/commands/init.js +0 -405
  95. package/dist/commands/init.js.map +0 -1
  96. package/dist/lib/sweep-stale.d.ts +0 -25
  97. package/dist/lib/sweep-stale.d.ts.map +0 -1
  98. package/dist/lib/sweep-stale.js +0 -179
  99. package/dist/lib/sweep-stale.js.map +0 -1
  100. package/dist/lib/sweep-stale.test.d.ts +0 -2
  101. package/dist/lib/sweep-stale.test.d.ts.map +0 -1
  102. package/dist/lib/sweep-stale.test.js +0 -130
  103. package/dist/lib/sweep-stale.test.js.map +0 -1
  104. package/dist/skill/docs/stack/auth/plugins/combo-auth.md +0 -74
  105. package/dist/skill/docs/stack/auth/plugins/upgrade-anonymous.md +0 -155
  106. package/src/skill/docs/stack/auth/plugins/combo-auth.md +0 -74
  107. package/src/skill/docs/stack/auth/plugins/upgrade-anonymous.md +0 -155
@@ -11,7 +11,7 @@ When `agents` is enabled (the default), the Worker serves:
11
11
  | `GET /robots.txt` | AI-bot policy with the [Cloudflare Content Signals](https://developers.cloudflare.com/bots/concepts/content-signals/) preamble and explicit `Allow:` rules for GPTBot, ClaudeBot, PerplexityBot, Google-Extended, CCBot, Applebot-Extended, Bytespider, MistralAI, Cohere, DuckAssist. |
12
12
  | `GET /llms.txt` | Agent-facing summary of the API — project name, authentication, resource list, endpoint conventions — derived from your own config. |
13
13
  | `GET /.well-known/oauth-protected-resource` | [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) metadata declaring this Worker as a protected resource. |
14
- | `GET /.well-known/oauth-authorization-server` | [RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414) metadata pointing at the sign-in and token endpoints. |
14
+ | `GET /.well-known/oauth-authorization-server` | [RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414) authorization-server metadata. When the `oauthProvider` plugin is enabled it **delegates to Better Auth's real OAuth 2.1 surface** (`/oauth2/authorize`, `/oauth2/token`, `/oauth2/register` dynamic client registration, PKCE); otherwise it advertises only the truthful token-mint subset. |
15
15
  | `GET /.well-known/api-catalog` | [RFC 9727](https://datatracker.ietf.org/doc/html/rfc9727) catalog linking at `/openapi.json`. |
16
16
  | `GET /.well-known/mcp.json` | MCP Server Card — discoverable metadata for the MCP server below. |
17
17
  | `POST /mcp` | Auto-generated MCP-over-HTTP server. One tool per OpenAPI operation, JWT auth forwarded through the same middleware as the REST API. |
@@ -57,6 +57,19 @@ export default defineConfig({
57
57
  });
58
58
  ```
59
59
 
60
+ `mcp` also accepts an object for an authenticated-only MCP surface:
61
+
62
+ ```ts title="quickback.config.ts"
63
+ export default defineConfig({
64
+ // …
65
+ agents: {
66
+ mcp: { requireAuth: true }, // /mcp challenges anonymous callers → interactive OAuth
67
+ },
68
+ });
69
+ ```
70
+
71
+ See [Interactive OAuth](#interactive-oauth-requireauth) below.
72
+
60
73
  ## The MCP server
61
74
 
62
75
  ### Tools
@@ -90,6 +103,41 @@ curl -X POST https://my-api.example.com/api/v1/token \
90
103
  -H "Content-Type: application/json"
91
104
  ```
92
105
 
106
+ ### Interactive OAuth (`requireAuth`)
107
+
108
+ Statically pasting a Bearer token works, but it isn't how an MCP connector wants to authenticate — it expects to **launch a sign-in flow**. By default `/mcp` serves an anonymous session (the access-filtered public tool list), and a connector that never sees an auth challenge never offers to sign in. Set `agents.mcp.requireAuth: true` to turn `/mcp` into an authenticated-only endpoint:
109
+
110
+ ```ts title="quickback.config.ts"
111
+ export default defineConfig({
112
+ // …
113
+ agents: { mcp: { requireAuth: true } },
114
+ });
115
+ ```
116
+
117
+ This does three things:
118
+
119
+ 1. **Force-enables the `oauthProvider` + `bearer` Better Auth plugins** — so `/oauth2/authorize`, `/oauth2/token`, and `/oauth2/register` ([RFC 7591](https://datatracker.ietf.org/doc/html/rfc7591) dynamic client registration) exist for a connector to discover, with PKCE.
120
+ 2. **Challenges unauthenticated `/mcp` requests** with `401` and a `WWW-Authenticate: Bearer resource_metadata="…/.well-known/oauth-protected-resource"` header ([RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) §5.1). This is the signal MCP connectors use to start OAuth.
121
+ 3. **Makes the root `/.well-known/oauth-authorization-server` doc delegate to Better Auth's real metadata**, so discovery resolves to working `/oauth2/*` endpoints instead of a hand-rolled stub.
122
+
123
+ The full handshake a connector runs:
124
+
125
+ ```text
126
+ POST /mcp (no token)
127
+ → 401 + WWW-Authenticate: resource_metadata="…/.well-known/oauth-protected-resource"
128
+ GET /.well-known/oauth-protected-resource → authorization_servers: [<origin>]
129
+ GET /.well-known/oauth-authorization-server → authorize/token/register + PKCE
130
+ POST /oauth2/register → dynamic client registration
131
+ GET /oauth2/authorize?code_challenge=… → redirect to your Account login → consent
132
+ POST /oauth2/token (code + code_verifier) → access token
133
+ POST /mcp (Bearer access token) → authenticated tool list
134
+ ```
135
+
136
+ The login and consent screens are served by your [Account SPA](/stack/account-ui) (`ACCOUNT_URL/login`, `ACCOUNT_URL/consent`), so users sign in with whatever methods you already enabled (Google, GitHub, email, passkey). No connector-specific configuration is required — adding the server URL is enough.
137
+
138
+ > `requireAuth` removes anonymous public-tool access over `/mcp`. Use it when the MCP surface is meant for authenticated users; leave it off (the default) for servers that expose genuinely public tools.
139
+
140
+
93
141
  ### Connecting clients
94
142
 
95
143
  **Claude Desktop** — add to `~/Library/Application Support/Claude/claude_desktop_config.json`:
@@ -81,12 +81,27 @@ Default `'none'`.
81
81
 
82
82
  | Value | Behavior | Cost per verify |
83
83
  |---|---|---|
84
- | `'none'` | No revocation check. Stolen tokens valid until TTL expires. Use a low `expiresIn` to bound the replay window. | 0 |
85
- | `'kv'` | Fast-path consults a denylist KV namespace before accepting the token. Banning a user / revoking sessions writes the user's `sub` to the denylist. | 1 KV read (~5-15ms, edge-cached) |
84
+ | `'none'` | No revocation check. Stolen / pre-revocation tokens valid until TTL expires (scope claims: until the carry-forward cap). Use a low `expiresIn` to bound the replay window. | 0 |
85
+ | `'kv'` | Fast-path checks per-principal revocation timestamps in the project's existing `KV` binding before trusting a verified token. | 2+ KV reads (~5-15ms, edge-cached) |
86
86
 
87
- The `'kv'` path keeps the fast-path stateless against the auth DB (still 0 D1 queries) — KV reads on Workers are an order of magnitude cheaper than a D1 round trip *and* give sub-second revocation.
87
+ `'kv'` (v0.45+, **Cloudflare runtime only**) keeps the fast-path stateless against the auth DB (still 0 D1 queries). There is nothing extra to provision — entries ride the `KV` binding every project already has, prefixed `qbrev:` and self-expiring after the maximum token lifetime, so the store never accumulates.
88
88
 
89
- > **`'kv'` is deferred to 0.10.15.** Setting `'kv'` in 0.10.14 errors at compile time so the migration path is explicit; the schema accepts it now so users can author their final config today.
89
+ A token is rejected when its mint timestamp (`iat`, or `sct` for the relationship-scope claim) predates the stored timestamp for any principal key it rides on:
90
+
91
+ | Key | Revokes | Written automatically on |
92
+ |---|---|---|
93
+ | `qbrev:user:<userId>` | every JWT for the user | user ban (`databaseHooks.user.update.after` — flipping `banned` stamps the key and, when outbound webhooks are enabled, emits a `user.banned` event). Call `revokeUserTokens` for custom flows (revoke-all, etc.) |
94
+ | `qbrev:member:<userId>:<orgId>` | the user's org-membership claims | member removal / role change (Better Auth `organizationHooks`) |
95
+ | `qbrev:scope:<userId>:<kind>:<id>` | the user's carried scope claim | UPDATE/DELETE of a scope-conferring relationship row (audit-wrapper chokepoint + the single DELETE route) |
96
+
97
+ `src/lib/jwt-revocation.ts` exports `revokeUserTokens` / `revokeMemberTokens` / `revokeScopeTokens` for explicit calls from actions. A rejected token falls through to session auth, which re-checks membership and re-mints — an active legitimate session recovers transparently.
98
+
99
+ Semantics worth knowing:
100
+
101
+ - **Revoke-on-touch for scopes:** any update or delete of a conferring row stamps the revocation, without evaluating whether the change actually ended the relationship. A false positive just forces a cheap re-prove (`/scope/v1/enter` or a minting namespace route).
102
+ - **Fails open:** a missing binding or KV outage skips the check (logged) — revocation degrades to the TTL / carry-forward-cap bound rather than locking every bearer out.
103
+ - **Eventual consistency:** KV propagates cross-PoP in ~60s. "Immediate" means seconds at the writing location, bounded-seconds globally — still far inside the 15-minute carry-forward cap that bounds revocation without this check.
104
+ - **Coverage gap:** batch *hard* deletes don't return rows through the chokepoint; call `revokeScopeTokens` explicitly if you bulk-hard-delete conferring rows.
90
105
 
91
106
  ## Defaults preserve 0.10.13 behavior
92
107
 
@@ -106,7 +121,7 @@ Adding the `auth.jwt` block without setting any field is a no-op vs. the 0.10.13
106
121
  - **B2C SaaS, mostly browser traffic:** keep defaults. The 180s TTL + auto-refresh model just works.
107
122
  - **Pentest engagement / enterprise compliance:** set `expiresIn: 30`. Tokens stay invisible to logged-in users (auto-refreshed every authed call) but stolen-token windows shrink to 30s.
108
123
  - **CLI-heavy / long-running CI tokens:** `expiresIn: 3600` for one-hour bearer tokens. Pair with `issuer` / `audience` if multiple services consume the same JWT.
109
- - **Need immediate revocation:** wait for 0.10.15's `revocationCheck: 'kv'`. Or, today, drop TTL to ~30s — same effect with bounded delay.
124
+ - **Need immediate revocation:** set `revocationCheck: 'kv'` (Cloudflare runtime). Or drop TTL to ~30s — similar effect with bounded delay and zero KV reads.
110
125
 
111
126
  ## `auth.loginUrl` / `auth.profileUrl` — external sign-in for consumer Workers
112
127
 
@@ -225,6 +225,52 @@ security: {
225
225
 
226
226
  The compiler encodes the wire syntax (which differs from CSP — values use `()`, not space-separated tokens, with bareword `self` and quoted URLs).
227
227
 
228
+ ## Custom response headers
229
+
230
+ `security.headers` sets arbitrary response headers on every response, alongside the managed security headers. Keys are header names; values are static strings or templates that interpolate per-deploy Worker env vars via the `{{env.VAR_NAME}}` token.
231
+
232
+ ```ts title="quickback.config.ts"
233
+ security: {
234
+ headers: {
235
+ // Stamp the deployed build identity. Read from Worker vars at runtime,
236
+ // so the value tracks whatever you inject at deploy time.
237
+ 'X-Server-Version': '{{env.SERVER_VERSION}}+{{env.SERVER_BUILD}}',
238
+
239
+ // Static value — always emitted.
240
+ 'X-Powered-By': 'Quickback',
241
+ },
242
+ }
243
+ ```
244
+
245
+ The canonical use case is exposing a build/version identity on every response so clients (`curl -I`, mobile apps, dashboards) can read the running build without a body request — and so you can detect drift between what's deployed and what git/CF report.
246
+
247
+ ### Omit-if-unset
248
+
249
+ A header whose value references env vars is emitted **only when every referenced var is set** (non-`undefined`, non-empty string) at runtime. A version header on a Worker that forgot to inject the var simply doesn't appear — never `X-Server-Version: undefined`. Static headers (no `{{env…}}`) are always emitted.
250
+
251
+ The value is read from `c.env` per request, so you don't declare these vars at compile time — inject them as Worker vars (`[vars]` in `wrangler.toml`, or `--var` at deploy) and the header picks them up.
252
+
253
+ ### Generated middleware
254
+
255
+ For the config above, the compiler appends this to the security-headers middleware — no post-compile patching:
256
+
257
+ ```ts
258
+ // Custom response headers (security.headers).
259
+ {
260
+ const v0 = (c.env as unknown as Record<string, string | undefined>)["SERVER_VERSION"];
261
+ const v1 = (c.env as unknown as Record<string, string | undefined>)["SERVER_BUILD"];
262
+ if (v0 != null && v0 !== '' && v1 != null && v1 !== '') {
263
+ c.header("X-Server-Version", `${v0}+${v1}`);
264
+ }
265
+ }
266
+ c.header("X-Powered-By", "Quickback");
267
+ ```
268
+
269
+ ### Rules
270
+
271
+ - **Header names** must be valid HTTP field tokens. Names already managed by a dedicated `security` field — `Content-Security-Policy`, `Strict-Transport-Security`, `X-Frame-Options`, `X-Content-Type-Options`, `Cross-Origin-Opener-Policy`/`-Embedder-Policy`/`-Resource-Policy`, `Referrer-Policy`, `Permissions-Policy` — are rejected; use that field instead so the two emitters don't race.
272
+ - **Only `{{env.VAR_NAME}}`** interpolation is supported (`VAR_NAME` is a valid env-var identifier). A malformed token (`{{env.FOO}`, `{{ENV.FOO}}`) is a compile-time error rather than leaking literal braces into the wire header.
273
+
228
274
  ## Compile-time lint rules
229
275
 
230
276
  The compiler walks the resolved config and emits warnings (or errors) for known footguns. Errors block compile; warnings print to stderr.
@@ -159,7 +159,7 @@ For org-scoped tables, `PUBLIC` routes still filter by organization. Since the u
159
159
  GET /api/v1/listings?organizationId=org_abc123
160
160
  ```
161
161
 
162
- The firewall WHERE clause is always enforced. If no `organizationId` is provided, the API returns a `400` with code `ORG_REQUIRED`.
162
+ The firewall WHERE clause is always enforced. If no `organizationId` is provided, the API returns a `403` with code `ORG_REQUIRED`.
163
163
 
164
164
  ```typescript
165
165
  // Public listing page — anyone can browse, but scoped to an org
@@ -517,7 +517,7 @@ Use `$ctx` to reference the current user's context:
517
517
  access: {
518
518
  record: {
519
519
  ownerId: { equals: "$ctx.userId" },
520
- orgId: { equals: "$ctx.orgId" }
520
+ organizationId: { equals: "$ctx.activeOrgId" }
521
521
  }
522
522
  }
523
523
  ```
@@ -790,7 +790,7 @@ import type { Auth } from "better-auth";
790
790
  interface ActionExecutorParams {
791
791
  db: DrizzleDB; // Scoped database (auto-applies org/owner/soft-delete filters)
792
792
  unsafeDb?: DrizzleDB; // Unscoped database (only available when unsafe mode is enabled)
793
- ctx: AppContext; // User context (userId, roles, orgId)
793
+ ctx: AppContext; // User context (userId, roles, activeOrgId, activeTeamId, userRole)
794
794
  record?: TRecord; // The record (record-based only, undefined for standalone)
795
795
  input: TInput; // Validated input from Zod schema
796
796
  services: TServices; // Configured integrations (billing, notifications, etc.)
@@ -884,6 +884,45 @@ always reflects the real actor and the real moment.
884
884
  the parameter is typed as optional. `whereTransition` extends `whereRecord`
885
885
  with the transition's "from" precondition for transition actions.
886
886
 
887
+ #### Reaching Better Auth tables (`authDb`)
888
+
889
+ The scoped `db` only sees your feature tables. To read Better Auth tables —
890
+ users, organizations, members — use the auth database connection from the
891
+ Hono context plus the generated `lib/org-access.ts` helper:
892
+
893
+ ```typescript
894
+ // features/projects/actions/assign.ts — validate a userId is an org member
895
+ import { z } from "zod";
896
+ import { eq } from "drizzle-orm";
897
+ import { ActionError } from "@quickback/compiler";
898
+ import { defineAction } from "../.quickback/define-action";
899
+ import { getOrgMemberRole } from "../../../lib/org-access";
900
+ import { projects } from "../projects";
901
+
902
+ export default defineAction({
903
+ description: "Assign a project to an org member",
904
+ input: z.object({ assigneeId: z.string() }),
905
+ access: { roles: ["member", "admin"] },
906
+ async execute({ db, record, input, ctx, c, whereRecord }) {
907
+ // getOrgMemberRole(authDb, userId, organizationId) → role string | null
908
+ const role = await getOrgMemberRole(c.get("authDb"), input.assigneeId, ctx.activeOrgId!);
909
+ if (!role) {
910
+ throw new ActionError("Assignee is not a member of this organization", "NOT_A_MEMBER", 400);
911
+ }
912
+ const [updated] = await db
913
+ .update(projects)
914
+ .set({ assigneeId: input.assigneeId })
915
+ .where(whereRecord!(projects))
916
+ .returning();
917
+ return updated;
918
+ },
919
+ });
920
+ ```
921
+
922
+ `c.get("authDb")` is the Drizzle connection to the auth database (in dual-DB
923
+ mode it's a separate D1 from your features). For richer queries, import the
924
+ auth schema tables from `../../../auth/schema` and query `authDb` directly.
925
+
887
926
  ## HTTP API Reference
888
927
 
889
928
  ### Request Format
@@ -953,7 +992,7 @@ async execute({ ctx, record, input, c }) {
953
992
  **Option 2: Throw an ActionError**
954
993
 
955
994
  ```typescript
956
- import { ActionError } from "@quickback/types";
995
+ import { ActionError } from "@quickback/compiler";
957
996
 
958
997
  async execute({ ctx, record, input }) {
959
998
  if (record.stage === 'hired') {
@@ -965,7 +1004,10 @@ async execute({ ctx, record, input }) {
965
1004
  }
966
1005
  ```
967
1006
 
968
- The `ActionError` constructor signature is `(message, code, statusCode, details?)`.
1007
+ The `ActionError` constructor signature is `(message, code, statusCode = 400, details?)`. The compile step rewrites the `@quickback/compiler` import to the generated runtime class (`src/lib/types.ts`), and the route handler catches it by name and returns `{ error, code, details }` with your `statusCode`.
1008
+
1009
+ > Do **not** throw Hono's `HTTPException` from an action — the route handler doesn't unwrap it, so it surfaces as an unhandled **500 ACTION_EXECUTION_FAILED**. Use `ActionError` (or return `c.json(...)` directly) for clean 4xx responses.
1010
+
969
1011
 
970
1012
  ## Protected Fields
971
1013
 
@@ -19,54 +19,46 @@ a stable, greppable **code**:
19
19
  [quickback:authz] AUTHZ_EMPTY_PERMISSION: permission "event:locked" can never be satisfied — it requires organizerOf AND its negation simultaneously.
20
20
  at resource=sessions authz.permissions["event:locked"]
21
21
  hint: Remove the contradictory arm, or split into separate permissions.
22
+ override: authz: { analyzer: { allow: [{ check: 'AUTHZ_EMPTY_PERMISSION', target: 'event:locked', reason: '<why this is acceptable>' }] } }
22
23
  ```
23
24
 
24
25
  The first line stays greppable (`[quickback:<channel>] CODE: message`); the
25
- source location and fix hint render on continuation lines.
26
+ source location, fix hint, and — for promoted errors — the exact override
27
+ recipe render on continuation lines.
26
28
 
27
- ## Warn by default, opt-in strict
29
+ ## Errors vs warnings (v0.47+)
28
30
 
29
- The analyzer is **warn-by-default, compile-continues**. This is deliberate:
30
- the analyzer runs on the shared compiler that serves every project, so a new
31
- check must never break an existing build on upgrade. In the default path
32
- every diagnostic — *including* the one check authored at `error` severity
33
- (the capability ceiling) — is rendered as a warning line and the compile
34
- proceeds.
31
+ The checks split into two tiers:
35
32
 
36
- Set **`QUICKBACK_AUTHZ_STRICT=true`** to promote every `warn` to `error`.
37
- Under strict mode the compile **fails** (throws an aggregate error listing the
38
- codes) if any diagnostic is — after promotion — an error. `info` lines
39
- (the pushdown-cost report) stay informational and never fail a build.
33
+ - **Promoted (compile errors).** A trip is a *definite misconfiguration* —
34
+ never a legitimate config. These fail the build by default. Each one can be
35
+ explicitly accepted per finding via
36
+ [`authz.analyzer.allow`](#the-override-surface).
37
+ - **Heuristic (warnings) and reports (info).** Advisory findings where a
38
+ legitimate config could trip the detector. These print and the compile
39
+ continues. Set **`QUICKBACK_AUTHZ_STRICT=true`** to promote these warnings
40
+ to errors as well (overridden findings stay warnings even under strict —
41
+ an override is an explicit, reasoned acceptance).
40
42
 
41
- ```bash
42
- # warn-only (default): prints diagnostics, compile succeeds
43
- quickback compile
44
-
45
- # strict: any warn or error fails the compile
46
- QUICKBACK_AUTHZ_STRICT=true quickback compile
47
- ```
48
-
49
- > The analyzer is compile-time only — zero runtime blast radius. A defect in
50
- > the analyzer itself is caught and downgraded to a single warning in the
51
- > default path, so an analyzer bug can never take down an otherwise-valid
52
- > compile. (Strict mode re-raises, because there the throw is the intended
53
- > hard failure.)
43
+ The analyzer remains compile-time only — zero runtime blast radius. A defect
44
+ in the analyzer *itself* is caught and downgraded to a single warning, so an
45
+ analyzer bug can never take down an otherwise-valid compile. Only real
46
+ findings fail builds.
54
47
 
55
48
  ## Authz codes
56
49
 
57
- These read the permission graph projected from the policy IR. All are `warn`
58
- severity (so `info` for the pushdown report) **except** the capability ceiling,
59
- which is authored as `error`.
50
+ These read the permission graph projected from the policy IR and run on every
51
+ compile.
60
52
 
61
- | Code | Severity | What it catches |
53
+ | Code | Tier | What it catches |
62
54
  |---|---|---|
63
- | `AUTHZ_EMPTY_PERMISSION` | warn | A permission that can never be satisfied — e.g. `allOf(a, not(a))`, which requires a fact and its negation at the same AND-level. |
55
+ | `AUTHZ_EMPTY_PERMISSION` | **error** | A permission that can never be satisfied — `allOf(a, not(a))`, a fact and its exact negation at the same AND-level. The detector is conservative (exact-leaf contradictions only), so a trip is structurally unsatisfiable. |
56
+ | `AUTHZ_CAPABILITY_CEILING` | **error** | A resource's firewall grants a `scope:<kind>:<role>` role read access **beyond its capability profile** — either the role has no profile at all, or the profile doesn't list this resource. The M0.2 pillar guarantee. |
64
57
  | `AUTHZ_SHADOWED_ARM` | warn | An `anyOf` arm subsumed by a broader arm: a leaf `X` and an `allOf(X, …)` in the same union — the narrower arm can never widen the result. |
65
- | `AUTHZ_UNREACHABLE_ROLE` | warn | A scoped role declared under `authz.scopes` with **no grant profile** — it can authorize no read, action, or channel, so it's dead config. |
66
- | `AUTHZ_UNREACHABLE_VIEW` | warn | A grant's `read` names a `resource:view` whose resource has no firewall — no role can reach that view. |
67
- | `AUTHZ_PUSHDOWN_COST` | info | Per-permission report: how many SQL subqueries the permission lowers to, plus the max recursive-CTE depth (from recursive arrows). Advisory, never fails a build. |
68
- | `AUTHZ_CAPABILITY_CEILING` | **error** | A resource's firewall grants a `scope:<kind>:<role>` role read access **beyond its capability profile** — either the role has no profile at all, or the profile doesn't list this resource. |
69
- | `AUTHZ_NOT_OVER_RESOURCE` | warn | A `not` whose operand resolves to a **resource (SQL) site** — `NOT EXISTS` over a nullable join can silently pass (the null-trap). The analyzer resolves the operand's site from its leaves, so it fires even when the lowering left the site unset. |
58
+ | `AUTHZ_UNREACHABLE_ROLE` | warn | A scoped role declared under `authz.scopes` with **no grant profile** — it can authorize no read, action, or channel. Dead config, deny-safe. |
59
+ | `AUTHZ_UNREACHABLE_VIEW` | warn | A grant's `read` names a `resource:view` whose resource has no firewall — no role can reach that view. (A reachability proxy — heuristic by design.) |
60
+ | `AUTHZ_NOT_OVER_RESOURCE` | warn | A `not` whose operand resolves to a **resource (SQL) site** — `NOT EXISTS` over a nullable join can silently pass (the null-trap). The site resolution is conservative, so this stays advisory. |
61
+ | `AUTHZ_PUSHDOWN_COST` | info | Per-permission report: how many SQL subqueries the permission lowers to, plus the max recursive-CTE depth. Advisory, never fails a build. |
70
62
 
71
63
  A few codes are reserved in the diagnostic enum for the milestones that emit
72
64
  them and don't fire on a shipped config today: `AUTHZ_UNBOUNDED_RECURSION`
@@ -76,38 +68,78 @@ error raised at config validation, before the analyzer runs),
76
68
 
77
69
  ### The capability ceiling
78
70
 
79
- The one `error`-severity authz check. It is the M0.2 deliverable that backs
80
- [scope grant profiles](/compiler/definitions/scopes): a scoped role is
81
- deny-by-default and may touch only what its `grants` profile lists. The
82
- analyzer walks every resource firewall, follows each `{ permission }` arm
83
- into the permission graph to find the scope roles it references, and fails the
84
- build (in strict mode) if a resource grants a scope role access the profile
85
- doesn't cover. In the default path it warns loudly. This is what makes the
86
- grant profile the single auditable manifest of what an external principal can
87
- see.
71
+ The check that backs [scope grant profiles](/compiler/definitions/scopes): a
72
+ scoped role is deny-by-default and may touch only what its `grants` profile
73
+ lists. The analyzer walks every resource firewall, follows each
74
+ `{ permission }` arm into the permission graph to find the scope roles it
75
+ references, and **fails the build** if a resource grants a scope role access
76
+ the profile doesn't cover. This is what makes the grant profile the single
77
+ auditable manifest of what an external principal can see.
88
78
 
89
79
  ## Authn codes
90
80
 
91
- Four **structural authentication** checks — proving properties over the
92
- generated route + credential surface rather than the authz policy:
81
+ Five **structural authentication** checks — proving properties over the
82
+ generated route + credential surface rather than the authz policy. All are
83
+ promoted (compile errors):
93
84
 
94
- | Code | Severity | What it catches |
85
+ | Code | Tier | What it catches |
95
86
  |---|---|---|
96
- | `AUTHN_ROUTE_COVERAGE` | warn | A route that reaches data with an **unclassified** auth gate and isn't declared `PUBLIC` — the signup / flag-gap bug class (data delivered to an unauthenticated ctx). |
97
- | `AUTHN_SECRET_CONSISTENCY` | error | A credential's mint site and verify site don't share key / issuer / audience — every minted token would fail verification (the ws-ticket "401 on every upgrade" trap). |
98
- | `AUTHN_CREDENTIAL_DELIVERY` | error | A fire-and-forget credential send (the OTP-email shape) not anchored to `waitUntil` / `await` — the Worker may drop the promise and never deliver (the OTP-500 bug class). |
99
- | `AUTHN_CLAIM_PROVENANCE` | error | An identity `ctx` field written from **request input** rather than a credential verifier — client-asserted identity, which is forbidden. |
100
- | `AUTHN_SURFACE_INVARIANT` | warn / error | A surface contract breach: an `/mcp` or agent route not gated bearer-only (warn), or an `INTERNAL`-gated route mounted on an HTTP-reachable surface (error). |
87
+ | `AUTHN_ROUTE_COVERAGE` | **error** | A route that reaches data with an **unclassifiable** auth gate and isn't declared `PUBLIC` — the signup / flag-gap bug class (data delivered to an unauthenticated ctx). Fires only on a gate the compiler cannot classify; zero-FP by construction. |
88
+ | `AUTHN_SURFACE_INVARIANT` | **error** | A surface contract breach: an `/mcp` or agent route not gated bearer-only, or an `INTERNAL`-gated route mounted on an HTTP-reachable surface. |
89
+ | `AUTHN_SECRET_CONSISTENCY` | **error** | A credential's mint site and verify site don't share key / issuer / audience — every minted token would fail verification (the ws-ticket "401 on every upgrade" trap). |
90
+ | `AUTHN_CREDENTIAL_DELIVERY` | **error** | A fire-and-forget credential send (the OTP-email shape) not anchored to `waitUntil` / `await` — the Worker may drop the promise and never deliver (the OTP-500 bug class). |
91
+ | `AUTHN_CLAIM_PROVENANCE` | **error** | An identity `ctx` field written from **request input** rather than a credential verifier — client-asserted identity, which is forbidden. Unprovable provenance also fails (fail closed). |
101
92
 
102
93
  These check definitions are **wired and fully unit-tested**, but their inputs
103
94
  — the per-route and per-credential metadata (`RouteNode` / `MintSite` /
104
95
  `VerifySite` / `ClaimWrite`) — are not yet emitted by the route, middleware,
105
96
  and credential generators. Until those generators emit that metadata the
106
97
  analyzer runs the authn checks against **empty** route/credential graphs, so
107
- they are effectively no-ops on a real compile. The check logic needs no change
108
- when the metadata lands — the route/credential coverage activates the moment
109
- the generators emit it. The authz / permission-graph checks above run
110
- unconditionally today, because the policy IR is always present.
98
+ they are effectively no-ops on a real compile. The severity contract is
99
+ locked in now: they fail builds the moment they can fire. (The emitted route
100
+ surface is separately guarded today by the IR's unbound-route invariant — a
101
+ hard error that predates this promotion and owns that surface; one subject,
102
+ one error.)
103
+
104
+ ## The override surface
105
+
106
+ Every promoted finding can be explicitly accepted — per finding, with a
107
+ required reason:
108
+
109
+ ```ts
110
+ authz: {
111
+ analyzer: {
112
+ allow: [
113
+ {
114
+ check: 'AUTHZ_CAPABILITY_CEILING',
115
+ target: 'sessions/scope:event:organizer',
116
+ reason: 'organizer grant profile lands with the v2 rollout (TICKET-123)',
117
+ },
118
+ ],
119
+ },
120
+ }
121
+ ```
122
+
123
+ An entry downgrades the exact `(check, target)` finding back to a warning
124
+ that cites the reason. The rendered error prints the exact recipe — copy the
125
+ `check` and `target` from it. Target formats:
126
+
127
+ | Check | `target` format |
128
+ |---|---|
129
+ | `AUTHZ_EMPTY_PERMISSION` | the permission name — `event:locked` |
130
+ | `AUTHZ_CAPABILITY_CEILING` | `<resource>/scope:<kind>:<role>` — `sessions/scope:event:organizer` |
131
+ | `AUTHN_ROUTE_COVERAGE`, `AUTHN_SURFACE_INVARIANT` | `<METHOD> <path>` — `GET /mcp` |
132
+ | `AUTHN_SECRET_CONSISTENCY`, `AUTHN_CREDENTIAL_DELIVERY` | the credential kind — `ws-ticket` |
133
+ | `AUTHN_CLAIM_PROVENANCE` | the ctx field — `ctx.userId` |
134
+
135
+ Guard rails, all compile errors:
136
+
137
+ - `check` must be a **promoted** id — unknown ids and keep-warn ids (there is
138
+ nothing to override) are rejected at config validation.
139
+ - `reason` is required and non-empty: overrides are self-documenting.
140
+ - An `allow` entry that matches **no current finding** is a *dead override*
141
+ and fails the compile — fix or remove the stale entry. Override lists can
142
+ never silently outlive the problems they suppressed.
111
143
 
112
144
  ## Reading the pushdown-cost report
113
145
 
@@ -133,4 +165,3 @@ not an error, but worth a look.
133
165
  profiles the capability-ceiling check enforces.
134
166
  - [Firewall](/compiler/definitions/firewall) — the `{ permission }` arms the
135
167
  ceiling check follows into the permission graph.
136
- ```
@@ -56,7 +56,7 @@ The server probes **every declared role** for the proposed instance (one DB touc
56
56
  "scope": { "event": { "id": "evt_123", "roles": ["attendee", "shuttleDriver"], "shuttleId": "shA" } }
57
57
  ```
58
58
 
59
- The client sends that JWT as `Authorization: Bearer …` on subsequent requests. The auth middleware verifies the signature and sets `ctx.scope` — **no DB**. The claim is carried forward on every authed call (rolling refresh) until you `enter` a different instance.
59
+ The client sends that JWT as `Authorization: Bearer …` on subsequent requests. The auth middleware verifies the signature and sets `ctx.scope` — **no DB**. The claim is carried forward on every authed call (rolling refresh) for up to **15 minutes from the last actual relationship proof** — the mint stamps a proof timestamp (`sct`) that the refresh carries forward verbatim and checks against the carry-forward cap. Past the cap the refresh stops, the token expires within one TTL, and the client re-proves via `enter` (or any namespace route that mints) to restart the window.
60
60
 
61
61
  > **Invariant:** the client only *proposes* the instance id (from the URL). The server proves membership before signing. No client-asserted scope is ever trusted.
62
62
 
@@ -311,13 +311,21 @@ forge a scope role — the guard, not the flag, is the gate.
311
311
 
312
312
  ### TTL and best-effort semantics
313
313
 
314
- - **TTL is the scope-token TTL** — `auth.jwt.expiresIn` (default 180s), **clamped to a hard ≤180s ceiling** at the mint site. A longer-lived scope token would widen the post-revocation replay window past the spec bound, so the clamp is non-negotiable.
314
+ - **TTL is the scope-token TTL** — `auth.jwt.expiresIn` (default 180s), **clamped to a hard ≤180s ceiling** at every signing site that emits a scope claim: both proven mints (`/scope/v1/enter`, the namespace resolver) *and* the middleware's rolling refresh. A longer-lived scope token would widen the post-revocation replay window past the spec bound, so the clamp is non-negotiable — an `auth.jwt.expiresIn` above the ceiling applies to plain tokens but never survives into a scope-bearing one.
315
315
  - **The mint is gated by the same proven-relationship guard as the in-memory stamp.** It runs *after* the gate has granted access, reading the instance id from the proven path param (`:eventId`) — never from request input — so the minted `scope:<kind>:<role>` is backed by exactly the proof `/scope/v1/enter` requires. The token is **byte-identical** to one `/scope/v1/enter` would produce: same shared mint helper, same carry-forward of any *other* verified scope kinds already on the incoming token (the freshly-proven kind takes precedence; siblings survive the re-mint).
316
316
  - **The mint is best-effort.** A mint failure (e.g. a missing signing secret) **never fails the request** — the in-memory stamp already authorized it; the caller simply doesn't receive a refreshed token on that response and can fall back to `/scope/v1/enter`.
317
317
 
318
318
  ## Revocation & TTL
319
319
 
320
- The scope claim is trusted for the JWT TTL (default 180s, `auth.jwt.expiresIn`) — identical to how `orgId` / `role` claims already behave. Removing a guest/staff row takes effect within one TTL (the next `enter` won't re-mint the role). Immediate revocation (`auth.jwt.revocationCheck: 'kv'`) is on the roadmap.
320
+ The scope claim is trusted between proofs — it is never re-checked against the database while it rides. Two bounds keep that window finite:
321
+
322
+ - **The TTL** (default 180s, `auth.jwt.expiresIn`, clamped ≤180s on scope-bearing tokens) bounds an *idle* client: a token that stops being used dies within one TTL.
323
+ - **The carry-forward cap** (15 minutes) bounds an *active* client: the rolling refresh re-signs the claim on every authed call, but only while the claim's proof timestamp (`sct`, stamped exclusively by the proven mint sites) is younger than the cap. Past it the refresh refuses, the token expires, and the next `enter` (or namespace-route mint) re-probes the relationship — which won't re-mint a revoked role.
324
+
325
+ So removing a guest/staff row takes effect within **cap + one TTL** for a client that keeps polling, and within one TTL once it goes idle. Two ways to tighten that:
326
+
327
+ - **`auth.jwt.revocationCheck: 'kv'`** (v0.45+, Cloudflare runtime) — sub-TTL revocation: updating or deleting a conferring relationship row stamps a revocation timestamp in KV, and the bearer fast-path rejects a carried scope claim whose proof (`sct`) predates it. See [auth config](/compiler/config/auth).
328
+ - **`via` arms** — for tables where any caching is too wide, gate with a `via` arm instead of a bare `ctx.scope.<kind>` arm: `via` emits a live subquery against the relationship table on every request, immune to a stale claim entirely.
321
329
 
322
330
  ## Reference
323
331
 
@@ -60,10 +60,12 @@ export default feature('candidates', {
60
60
  // WRITE OPERATIONS
61
61
  create: { access: { roles: ['hiring-manager', 'recruiter'] } },
62
62
  update: { access: { roles: ['hiring-manager', 'recruiter'] } },
63
- delete: { access: { roles: ['hiring-manager'] }, mode: 'hard' },
63
+ delete: { access: { roles: ['hiring-manager'] }, mode: 'soft' },
64
64
  });
65
65
  ```
66
66
 
67
+ > `mode: 'hard'` is also available, but hard deletes erase the row — so they require the security-audit pipeline. On D1 that means setting `auditDatabaseId` on the database provider config (the compiler errors with setup instructions if it's missing).
68
+
67
69
  > Prefer the explicit two-export form (or interop with existing Drizzle schemas)? See [feature() — single-export sugar](/compiler/definitions/feature) and [Schema: choosing between `q` and Drizzle](/compiler/definitions/schema#choosing-between-q-and-drizzle). All forms compile identically; mix freely per file.
68
70
 
69
71
  ---
@@ -75,7 +77,7 @@ Run `quickback compile` and Quickback generates production-ready code.
75
77
  ### Security Helpers
76
78
 
77
79
  ```typescript title="src/features/candidates/candidates.resource.ts"
78
- import { eq, and } from 'drizzle-orm';
80
+ import { eq, and, isNull } from 'drizzle-orm';
79
81
  import { candidates } from './schema';
80
82
  import type { AppContext } from '../../lib/types';
81
83
  import { masks } from '../../lib/masks';
@@ -213,7 +215,7 @@ export function maskCandidates<T extends Record<string, any>>(
213
215
  export const CRUD_ACCESS = {
214
216
  create: { access: { roles: ['hiring-manager', 'recruiter'] } },
215
217
  update: { access: { roles: ['hiring-manager', 'recruiter'] } },
216
- delete: { access: { roles: ['hiring-manager'] }, mode: 'hard' },
218
+ delete: { access: { roles: ['hiring-manager'] }, mode: 'soft' },
217
219
  };
218
220
 
219
221
  // Views configuration (read pipeline)
@@ -25,11 +25,11 @@ Both paths scaffold the same project:
25
25
  - Working example feature with full security configuration (when you pick `todos`/`blog`/`saas`)
26
26
 
27
27
  **Available templates:**
28
- - `cloudflare` — Cloudflare Workers + D1 + Better Auth, bare scaffold (free)
29
- - `todos` — Working CRUD example with masking + actions (free)
30
- - `blog` — Single-tenant blog, PUBLIC reads, admin writes (free)
31
- - `empty` — Cloudflare scaffold, no example features (free)
32
- - `saas` — Full B2B SaaS with orgs, R2 file storage, webhooks (pro)
28
+ - `cloudflare` — Cloudflare Workers + D1 + Better Auth, bare scaffold
29
+ - `todos` — Working CRUD example with masking + actions
30
+ - `blog` — Single-tenant blog, PUBLIC reads, admin writes
31
+ - `empty` — Cloudflare scaffold, no example features
32
+ - `saas` — Full B2B SaaS with orgs, R2 file storage, webhooks
33
33
 
34
34
  ## File Structure
35
35
 
@@ -153,12 +153,12 @@ After `quickback compile` and `npm run dev`, your API is running locally. Open a
153
153
 
154
154
  ```bash
155
155
  # 1. Create a user account
156
- curl -X POST http://localhost:8787/api/auth/sign-up/email \
156
+ curl -X POST http://localhost:8787/auth/v1/sign-up/email \
157
157
  -H "Content-Type: application/json" \
158
158
  -d '{"email": "admin@example.com", "password": "securepassword123", "name": "Admin"}'
159
159
 
160
160
  # 2. Sign in and get a session token
161
- curl -X POST http://localhost:8787/api/auth/sign-in/email \
161
+ curl -X POST http://localhost:8787/auth/v1/sign-in/email \
162
162
  -H "Content-Type: application/json" \
163
163
  -d '{"email": "admin@example.com", "password": "securepassword123"}'
164
164
  # → Response includes a session token in Set-Cookie header