@quickback-dev/cli 0.70.31 → 0.70.40

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 (127) hide show
  1. package/dist/commands/build.d.ts +12 -0
  2. package/dist/commands/build.d.ts.map +1 -1
  3. package/dist/commands/build.js +69 -1
  4. package/dist/commands/build.js.map +1 -1
  5. package/dist/commands/deploy.d.ts +9 -0
  6. package/dist/commands/deploy.d.ts.map +1 -1
  7. package/dist/commands/deploy.js +20 -2
  8. package/dist/commands/deploy.js.map +1 -1
  9. package/dist/commands/migrate-data.d.ts +12 -0
  10. package/dist/commands/migrate-data.d.ts.map +1 -0
  11. package/dist/commands/migrate-data.js +134 -0
  12. package/dist/commands/migrate-data.js.map +1 -0
  13. package/dist/commands/migrate.d.ts.map +1 -1
  14. package/dist/commands/migrate.js +11 -0
  15. package/dist/commands/migrate.js.map +1 -1
  16. package/dist/commands/secrets.d.ts +27 -0
  17. package/dist/commands/secrets.d.ts.map +1 -0
  18. package/dist/commands/secrets.js +186 -0
  19. package/dist/commands/secrets.js.map +1 -0
  20. package/dist/index.js +23 -3
  21. package/dist/index.js.map +1 -1
  22. package/dist/lib/access-manifest-diff.d.ts +87 -0
  23. package/dist/lib/access-manifest-diff.d.ts.map +1 -0
  24. package/dist/lib/access-manifest-diff.js +331 -0
  25. package/dist/lib/access-manifest-diff.js.map +1 -0
  26. package/dist/lib/artifact-routing.d.ts.map +1 -1
  27. package/dist/lib/artifact-routing.js +3 -0
  28. package/dist/lib/artifact-routing.js.map +1 -1
  29. package/dist/lib/compiler-stubs.d.ts +2 -0
  30. package/dist/lib/compiler-stubs.d.ts.map +1 -1
  31. package/dist/lib/compiler-stubs.js +2 -0
  32. package/dist/lib/compiler-stubs.js.map +1 -1
  33. package/dist/lib/file-loader.d.ts +6 -0
  34. package/dist/lib/file-loader.d.ts.map +1 -1
  35. package/dist/lib/file-loader.js +17 -0
  36. package/dist/lib/file-loader.js.map +1 -1
  37. package/dist/lib/ops-manifest.d.ts +76 -0
  38. package/dist/lib/ops-manifest.d.ts.map +1 -0
  39. package/dist/lib/ops-manifest.js +94 -0
  40. package/dist/lib/ops-manifest.js.map +1 -0
  41. package/dist/lib/release-and-pin.d.ts +34 -0
  42. package/dist/lib/release-and-pin.d.ts.map +1 -0
  43. package/dist/lib/release-and-pin.js +71 -0
  44. package/dist/lib/release-and-pin.js.map +1 -0
  45. package/dist/lib/shell.d.ts +4 -1
  46. package/dist/lib/shell.d.ts.map +1 -1
  47. package/dist/lib/shell.js +8 -3
  48. package/dist/lib/shell.js.map +1 -1
  49. package/dist/skill/docs/api/actions.md +2 -0
  50. package/dist/skill/docs/api/batch-operations.md +18 -4
  51. package/dist/skill/docs/api/crud.md +62 -0
  52. package/dist/skill/docs/api/errors.md +17 -2
  53. package/dist/skill/docs/configure/auth.md +49 -2
  54. package/dist/skill/docs/configure/bindings.md +15 -0
  55. package/dist/skill/docs/configure/domains.md +4 -0
  56. package/dist/skill/docs/configure/index.md +29 -11
  57. package/dist/skill/docs/configure/tenancy.md +117 -0
  58. package/dist/skill/docs/define/access.md +19 -0
  59. package/dist/skill/docs/define/actions/access.md +76 -0
  60. package/dist/skill/docs/define/actions/defining.md +156 -1
  61. package/dist/skill/docs/define/actions/scoped-db.md +236 -9
  62. package/dist/skill/docs/define/areas.md +46 -0
  63. package/dist/skill/docs/define/authz-roles.md +10 -0
  64. package/dist/skill/docs/define/diagnostics.md +263 -0
  65. package/dist/skill/docs/define/encryption.md +32 -0
  66. package/dist/skill/docs/define/guards.md +13 -0
  67. package/dist/skill/docs/define/masking.md +77 -3
  68. package/dist/skill/docs/define/rate-limit.md +3 -3
  69. package/dist/skill/docs/define/schema.md +148 -7
  70. package/dist/skill/docs/define/scopes.md +79 -0
  71. package/dist/skill/docs/define/transitions.md +39 -0
  72. package/dist/skill/docs/define/views.md +77 -3
  73. package/dist/skill/docs/platform/api-contract/index.md +4 -0
  74. package/dist/skill/docs/platform/auth/jwt-optimization.md +2 -0
  75. package/dist/skill/docs/platform/auth/plugins/aws-ses.md +4 -3
  76. package/dist/skill/docs/platform/auth/using-auth.md +6 -0
  77. package/dist/skill/docs/platform/database/d1.md +47 -0
  78. package/dist/skill/docs/platform/database/data-migrations.md +109 -0
  79. package/dist/skill/docs/platform/database/read-replication.md +142 -7
  80. package/dist/skill/docs/platform/payments/one-off-checkout.md +6 -1
  81. package/dist/skill/docs/platform/push/index.md +2 -0
  82. package/dist/skill/docs/platform/realtime/partyserver-rooms.md +95 -9
  83. package/dist/skill/docs/platform/storage/using-r2.md +135 -19
  84. package/dist/skill/docs/start/deploy.md +38 -0
  85. package/dist/skill/docs/tooling/cli.md +120 -0
  86. package/dist/skill/docs/tooling/cloud-compiler/troubleshooting.md +13 -13
  87. package/dist/skill/docs/tooling/output.md +70 -2
  88. package/package.json +1 -1
  89. package/src/skill/docs/api/actions.md +2 -0
  90. package/src/skill/docs/api/batch-operations.md +18 -4
  91. package/src/skill/docs/api/crud.md +62 -0
  92. package/src/skill/docs/api/errors.md +17 -2
  93. package/src/skill/docs/configure/auth.md +49 -2
  94. package/src/skill/docs/configure/bindings.md +15 -0
  95. package/src/skill/docs/configure/domains.md +4 -0
  96. package/src/skill/docs/configure/index.md +29 -11
  97. package/src/skill/docs/configure/tenancy.md +117 -0
  98. package/src/skill/docs/define/access.md +19 -0
  99. package/src/skill/docs/define/actions/access.md +76 -0
  100. package/src/skill/docs/define/actions/defining.md +156 -1
  101. package/src/skill/docs/define/actions/scoped-db.md +236 -9
  102. package/src/skill/docs/define/areas.md +46 -0
  103. package/src/skill/docs/define/authz-roles.md +10 -0
  104. package/src/skill/docs/define/diagnostics.md +263 -0
  105. package/src/skill/docs/define/encryption.md +32 -0
  106. package/src/skill/docs/define/guards.md +13 -0
  107. package/src/skill/docs/define/masking.md +77 -3
  108. package/src/skill/docs/define/rate-limit.md +3 -3
  109. package/src/skill/docs/define/schema.md +148 -7
  110. package/src/skill/docs/define/scopes.md +79 -0
  111. package/src/skill/docs/define/transitions.md +39 -0
  112. package/src/skill/docs/define/views.md +77 -3
  113. package/src/skill/docs/platform/api-contract/index.md +4 -0
  114. package/src/skill/docs/platform/auth/jwt-optimization.md +2 -0
  115. package/src/skill/docs/platform/auth/plugins/aws-ses.md +4 -3
  116. package/src/skill/docs/platform/auth/using-auth.md +6 -0
  117. package/src/skill/docs/platform/database/d1.md +47 -0
  118. package/src/skill/docs/platform/database/data-migrations.md +109 -0
  119. package/src/skill/docs/platform/database/read-replication.md +142 -7
  120. package/src/skill/docs/platform/payments/one-off-checkout.md +6 -1
  121. package/src/skill/docs/platform/push/index.md +2 -0
  122. package/src/skill/docs/platform/realtime/partyserver-rooms.md +95 -9
  123. package/src/skill/docs/platform/storage/using-r2.md +135 -19
  124. package/src/skill/docs/start/deploy.md +38 -0
  125. package/src/skill/docs/tooling/cli.md +120 -0
  126. package/src/skill/docs/tooling/cloud-compiler/troubleshooting.md +13 -13
  127. package/src/skill/docs/tooling/output.md +70 -2
@@ -0,0 +1,109 @@
1
+ # Data Migrations
2
+
3
+ Schema migrations change the **shape** of your tables, and Drizzle generates
4
+ them for you. Data migrations change the **rows**: a backfill, a repair, a
5
+ one-time move. You write them as ordinary TypeScript under
6
+ `quickback/migrations/data/`, and `quickback migrate data` runs them inside the
7
+ deployed Worker for one environment.
8
+
9
+ ```ts title="quickback/migrations/data/2026-10-21-archive-stale-drafts.ts"
10
+ import { defineDataMigration } from "@quickback/compiler";
11
+ import { and, eq, isNull } from "drizzle-orm";
12
+ import { projects } from "../../db/schema";
13
+
14
+ export default defineDataMigration({
15
+ id: "2026-10-21-archive-stale-drafts",
16
+ databases: ["DB"],
17
+ description: "Archive draft projects that never got a budget",
18
+ async run({ db, dryRun, log }) {
19
+ const stale = await db
20
+ .select({ id: projects.id })
21
+ .from(projects)
22
+ .where(and(eq(projects.status, "draft"), isNull(projects.budget)));
23
+ log(`${stale.length} stale draft project(s)`);
24
+ if (dryRun) return;
25
+ for (const row of stale) {
26
+ await db.update(projects).set({ status: "archived" }).where(eq(projects.id, row.id));
27
+ }
28
+ },
29
+ });
30
+ ```
31
+
32
+ Declare who may run them. There is no default role:
33
+
34
+ {/* doc-compile: skip — excerpt of the top-level `dataMigrations` key; the rest of `defineConfig` is unchanged. */}
35
+ ```ts title="quickback/quickback.config.ts"
36
+ dataMigrations: {
37
+ access: { userRole: ["sysadmin"] },
38
+ },
39
+ ```
40
+
41
+ Then deploy and run:
42
+
43
+ ```bash
44
+ quickback deploy --env staging
45
+ quickback migrate data --env staging # dry run: logs, writes nothing
46
+ quickback migrate data --env staging --apply # writes, records the id
47
+ ```
48
+
49
+ ## The definition
50
+
51
+ | Field | |
52
+ | --- | --- |
53
+ | `id` | Ledger key, as a string literal. It runs once per environment. Ids run in sorted order, so start them with a date. |
54
+ | `databases` | Database bindings the migration touches (`["DB"]`). `db` is the first one, and `dbs[binding]` gives each. On D1 with split databases, the auth binding (`AUTH_DB`) is also allowed. |
55
+ | `description` | Shown by `quickback migrate data`. |
56
+ | `run({ db, dbs, env, dryRun, log })` | The work. `log()` lines (up to 500) go to the CLI and the ledger row. |
57
+
58
+ The compiler reads `id` and `databases` statically. A computed id, an unknown
59
+ binding, a duplicate id, or a missing `run` is a compile error that names the
60
+ file. From `@quickback/compiler` you may import only `defineDataMigration` (and
61
+ types). Relative imports resolve against the generated tree the same way they
62
+ do in action files, so `../../db/schema` is the generated schema barrel.
63
+
64
+ ## Guarantees
65
+
66
+ - **Dry run by default.** Without `--apply`, the runner calls
67
+ `run({ dryRun: true })`, and every write method on the handle (`insert`,
68
+ `update`, `delete`, `batch`, `run`, `execute`, `transaction`) throws. A
69
+ migration that forgets to check `dryRun` fails loudly instead of writing.
70
+ - **Once per environment.** Each target's features database has its own
71
+ `_qb_data_migrations` ledger. Before `run` starts, `--apply` claims the id
72
+ with a single conflict-free `INSERT`, so two concurrent applies cannot both
73
+ run. An applied id answers `409 DATA_MIGRATION_ALREADY_APPLIED`.
74
+ - **Failures are recorded and retryable.** A thrown error marks the row
75
+ `failed`, with the message and log. The next `quickback migrate data` re-runs
76
+ it.
77
+ - **No implied transaction.** D1 has no transactions across statements, so
78
+ write migrations that are safe to re-run after a partial failure. Select
79
+ what still needs changing, as in the example above.
80
+ - **Audited.** When the project has the audit wrapper, writes are stamped
81
+ `system:data-migration-<id>`, and the ledger row records the operator's
82
+ user id. With [release stamping](/start/deploy#release-stamps) on, it also
83
+ records the release that applied the migration.
84
+
85
+ ## Why it runs in the Worker
86
+
87
+ The runner is a route the compiler mounts at
88
+ `/api/v1/system/data-migrations`, gated to `dataMigrations.access.userRole`.
89
+ It is not a local script, and it is not a separate Wrangler entrypoint. The
90
+ Worker is the one place where both database families are reachable through the
91
+ bindings the app itself uses. Code outside a Worker cannot run JavaScript
92
+ against a D1 binding, and a Postgres database behind Hyperdrive is only
93
+ reachable from inside the Worker. The runner uses the same service handle as
94
+ cron and queue handlers: `drizzle(env.DB)` on D1, and the service-role
95
+ `createServiceDb(env)` on Neon and PlanetScale, where the ledger lives in the
96
+ `app` schema behind a service-role-only RLS policy. Your machine needs only an
97
+ operator's bearer token, never database credentials.
98
+
99
+ Each request must finish within the Worker's request limits. Split very large
100
+ backfills into several migrations, or make one resumable: a failed run can be
101
+ re-applied, and it picks up whatever rows still match.
102
+
103
+ ## The CLI
104
+
105
+ `quickback migrate data` finds the route and each target's API hostname in
106
+ `reports/ops.manifest.json`. See the
107
+ [CLI reference](/tooling/cli#run-data-migrations) for every flag. It refuses
108
+ to run when the deployed Worker does not know a migration the build declares,
109
+ because that means the current build is not deployed yet.
@@ -39,7 +39,7 @@ Every response carries the session's bookmark:
39
39
 
40
40
  ```http
41
41
  HTTP/1.1 200 OK
42
- x-d1-bookmark: 00000085-0000000a-00004e6e-9d8f2c1b
42
+ x-d1-bookmark: 0000007b-0000b26e-00001538-0c3e87bb37b3db5cc52eedb93cd3b96b
43
43
  x-d1-served-by: WEUR;primary=false
44
44
  ```
45
45
 
@@ -48,12 +48,16 @@ consistency across requests: it never reads an older version of the database
48
48
  than the one it last saw, and it sees its own writes. A client that ignores
49
49
  the header gets eventual consistency on reads only — the same thing any
50
50
  replicated database gives an un-sessioned reader — and still gets fresh
51
- reads inside every write. Both headers are CORS-exposed so browser code can
52
- read them.
51
+ reads inside every write. All three headers (`x-d1-bookmark`,
52
+ `x-d1-served-by`, `x-d1-fallback`) are CORS-exposed so browser code can read
53
+ them.
53
54
 
54
55
  `x-d1-served-by` is for verifying a rollout: it is set only when D1 reports
55
- where the session ran (`meta.served_by_region` / `served_by_primary`), which
56
- is every remote request and never `wrangler dev`.
56
+ where the session ran (`meta.served_by_region` / `served_by_primary`). D1
57
+ attaches that to `all()` / `run()` / `batch()` results on remote databases and
58
+ never under `wrangler dev` — and not to `raw()`, which is how Drizzle runs most
59
+ selects, so a read-only request often carries no `x-d1-served-by` even in
60
+ production.
57
61
 
58
62
  ### Echo the bookmark from your client
59
63
 
@@ -74,8 +78,8 @@ One variable per browser tab or app session is enough. Sending a bookmark
74
78
  from a different session is harmless: D1 only guarantees the new session is
75
79
  at least as fresh as the bookmark.
76
80
 
77
- Only a well-formed bookmark (four 8-hex groups, as D1 issues them) continues
78
- a session. Any other header value is ignored and the request starts
81
+ Only a well-formed bookmark (three 8-hex groups and a hash group, as D1
82
+ issues them) continues a session. Any other header value is ignored and the request starts
79
83
  `first-unconstrained`, so a stale or hand-edited header can never fail a
80
84
  query.
81
85
 
@@ -88,6 +92,137 @@ readReplication: { header: "x-bookmark" },
88
92
  The name must be a valid HTTP header token. It is matched case-insensitively
89
93
  on the way in and emitted lowercase.
90
94
 
95
+ ### Replica → primary fallback
96
+
97
+ A replica may not have the row another user wrote a moment ago, so a `GET`
98
+ for it can come back not-found from the replica even though the primary has
99
+ it. The generated worker retries those reads once on the primary:
100
+
101
+ | First response (`GET` / `HEAD` only) | Retried on the primary? |
102
+ |----------------------------|--------------------------|
103
+ | `404`, or `403 FIREWALL_NOT_FOUND` (the firewall's default `errorMode: 'reveal'` answer for a row it cannot see) | Yes, once |
104
+ | a read continued from a client bookmark whose replica did not catch up within `bookmarkWaitMs` (below) | Yes, once — whatever the handler answered |
105
+ | any `5xx`, including `503 DB_TIMEOUT` | Yes, once |
106
+ | anything else (`2xx`, `304`, other `4xx`) | No |
107
+ | any status, when the session started `first-primary` or D1 reported the primary served it | No |
108
+ | any status under `wrangler dev` (D1 never reports where it served) | No |
109
+
110
+ The retried response carries `x-d1-fallback: primary`, the primary session's
111
+ bookmark, and the first attempt's `x-request-id`:
112
+
113
+ ```http
114
+ HTTP/1.1 200 OK
115
+ x-d1-fallback: primary
116
+ x-d1-bookmark: 0000007b-0000b26f-00000002-9b1d0e4a2f7c4c1e8d3a6b5f0c2e7d91
117
+ x-request-id: 3f0c…
118
+ ```
119
+
120
+ Details worth knowing:
121
+
122
+ - **One retry, never a loop.** The retry is marked inside the worker (an
123
+ object identity, not a header), so no client can trigger or suppress it,
124
+ and a retried request is never retried again.
125
+ - **The whole request runs twice.** The worker re-dispatches the request
126
+ through every middleware; Hono middleware cannot re-run downstream
127
+ handlers on its own. The retry does not count against the CRUD rate
128
+ limiter a second time; a custom `GET` action's own rate limit does count
129
+ both passes. Error logs from the first pass are kept — that is how you see
130
+ replica errors.
131
+ - **Genuine not-founds pay twice.** A `GET` for a row that exists nowhere
132
+ costs a replica read and a primary read. That is bounded at 2×.
133
+ - **Only not-found and errors.** A stale list (`200` with yesterday's rows)
134
+ is not detected; echo the bookmark, and adopt the bookmark from realtime
135
+ frames (below), to avoid it.
136
+ - **When D1 says nothing.** Drizzle's selects return no `served_by` metadata,
137
+ so after a not-found or 5xx with none, the worker asks D1 once per isolate
138
+ (`select 1`) whether it reports `served_by` at all. Remote D1 does;
139
+ `wrangler dev` does not, so local development never retries.
140
+
141
+ ### Bounding the wait for a bookmark
142
+
143
+ A `GET` that carries a bookmark starts its session at that bookmark, and D1
144
+ holds the first query until the replica has caught up to it. Cloudflare
145
+ documents no bound on replica lag, so without a cap that wait lasts until
146
+ [`queryTimeoutMs`](/platform/database/using-d1#backend-stalls) fires — seconds,
147
+ with the fallback only after.
148
+
149
+ `bookmarkWaitMs` caps it. When the session's first statement has not completed
150
+ within that many milliseconds, the read is abandoned and re-served from the
151
+ primary (`x-d1-fallback: primary`) — never stale, and never more than about
152
+ `bookmarkWaitMs` slower than going to the primary directly:
153
+
154
+ ```typescript
155
+ database: defineDatabase("cloudflare-d1", {
156
+ queryTimeoutMs: 5000,
157
+ readReplication: { bookmarkWaitMs: 300 }, // the default
158
+ }),
159
+ ```
160
+
161
+ - **Default 300 ms**, clamped to `queryTimeoutMs` when that is lower. An
162
+ explicit value must be a positive integer no larger than `queryTimeoutMs`.
163
+ - **Only bookmark reads.** `first-unconstrained` reads (no bookmark) and
164
+ everything on the primary keep the normal `queryTimeoutMs`.
165
+ - **Only the first statement.** Once one statement on the session has
166
+ answered, the replica is at least at the bookmark; later statements in the
167
+ same request are bounded by `queryTimeoutMs` alone. The cap covers every
168
+ statement form, including the `raw()` reads Drizzle uses for selects and
169
+ `batch()`.
170
+ - **No client-visible error.** The abandoned replica read never reaches the
171
+ client when the primary answers; if the primary retry also fails, the
172
+ client gets that failure (`503 DB_TIMEOUT` and so on) as usual. The worker
173
+ logs a `D1_REPLICA_WAIT` warning (plus the first pass's error line) each
174
+ time, so you can count them in Workers Logs.
175
+
176
+ **Tuning.** Set it a little above your observed p95 replica lag. Too low and
177
+ reads that would have been served by a replica a moment later go to the
178
+ primary instead (correct, just slower and more primary load); too high and a
179
+ lagging replica costs that much latency before the fallback. Count
180
+ `D1_REPLICA_WAIT` events and `x-d1-fallback` responses to judge it.
181
+
182
+ ### Realtime frames carry the writer's bookmark
183
+
184
+ A client that refetches over HTTP when a realtime frame arrives holds its
185
+ *own* bookmark, which predates the write that caused the frame — so the
186
+ refetch can land on a replica that has not seen that write yet. With
187
+ `readReplication` on and [realtime](/platform/realtime) enabled, every
188
+ `postgres_changes`, `broadcast` and `view_changes` frame sent while handling a
189
+ request carries that request's D1 bookmark, read when the frame is sent (after
190
+ the write; frames sent from `waitUntil` after the response included):
191
+
192
+ ```json
193
+ {
194
+ "specversion": "1.0",
195
+ "type": "dev.quickback.my-app.projects.insert",
196
+ "qbframe": "postgres_changes",
197
+ "qbd1bookmark": "0000007b-0000b26f-00000002-9b1d0e4a2f7c4c1e8d3a6b5f0c2e7d91",
198
+ "data": { "table": "projects", "eventType": "INSERT", "new": { "id": "prj_…" } }
199
+ }
200
+ ```
201
+
202
+ `qbd1bookmark` is a CloudEvents extension attribute, named like the other
203
+ `qb*` attributes (CloudEvents requires lowercase alphanumeric names). It is
204
+ absent on frames sent outside a request — schedules, queues, email handlers,
205
+ Durable Objects — and on projects without `readReplication`. It is never row
206
+ data: masking and audience targeting are unchanged.
207
+
208
+ On any frame carrying `qbd1bookmark`, set your stored bookmark to the
209
+ lexicographic max of the two before refetching. D1 bookmarks sort
210
+ oldest-to-newest as plain strings:
211
+
212
+ {/* doc-compile: skip — client-side frame handler; `bookmark` is the same variable as the fetch wrapper above. */}
213
+ ```typescript
214
+ socket.addEventListener("message", (event) => {
215
+ const frame = JSON.parse(event.data);
216
+ const theirs = frame.qbd1bookmark;
217
+ if (typeof theirs === "string" && (!bookmark || theirs > bookmark)) bookmark = theirs;
218
+ // …then refetch with api(), which sends the adopted bookmark.
219
+ });
220
+ ```
221
+
222
+ Server code can read the current request's bookmark the same way the realtime
223
+ helper does: `currentD1Bookmark()` from `src/db` returns it (or `null` outside
224
+ a request).
225
+
91
226
  ## What stays on the primary
92
227
 
93
228
  Only the per-request features `db` rides the session. These keep their own
@@ -95,6 +95,7 @@ the worker entry, and that same entry exports the `queue()` consumer.
95
95
  ```ts title="quickback/features/orders/actions/startCheckout.ts"
96
96
  import { z } from "zod";
97
97
  import { and, eq } from "drizzle-orm";
98
+ // quickback-allow ACTION_RAW_DB_WITHOUT_UNSAFE: the fulfilment webhook handler below has no caller to scope to
98
99
  import { drizzle } from "drizzle-orm/d1";
99
100
  import { defineAction, orders } from "../.quickback/define-action";
100
101
  import { onWebhookEvent } from "../../../lib/webhooks";
@@ -151,6 +152,7 @@ onWebhookEvent("stripe:checkout.session.completed", async (ctx) => {
151
152
  // session unpaid and settle later on async_payment_succeeded.
152
153
  if (session.payment_status !== "paid") return;
153
154
 
155
+ // quickback-allow ACTION_RAW_DB_WITHOUT_UNSAFE: webhook handler, no principal — the WHERE pins the row
154
156
  const db = drizzle(ctx.env.DB);
155
157
  const marked = await db
156
158
  .update(orders)
@@ -181,7 +183,10 @@ happens on Stripe's domain, and the next thing your Worker hears is the webhook.
181
183
  > `ctx.env` instead — exactly as the bundled subscription handlers do. That
182
184
  > client is **unfiltered**: the `where` clause is the only thing keeping the
183
185
  > write on one row, which is why it matches on the id Stripe echoed back and on
184
- > `status = "unpaid"`.
186
+ > `status = "unpaid"`. Because the handler lives in an action file, the raw
187
+ > client is a compile error (`ACTION_RAW_DB_WITHOUT_UNSAFE`) unless it is
188
+ > excused: the two `quickback-allow` comments name that decision and its reason
189
+ > ([Diagnostics → source codes](/define/diagnostics#source-codes)).
185
190
 
186
191
 
187
192
  ## Idempotency is not optional
@@ -171,6 +171,8 @@ Don't send a `tags` field — the server stamps it from the session and ignores
171
171
 
172
172
  Sends ride the **after-commit effects phase**, so a rolled-back write never notifies anyone and `dryRun` sends nothing. Enqueue the fan-out from inside `execute`:
173
173
 
174
+ {/* doc-compile: skip — needs the `push` config from step 2, which declares the PUSH_FANOUT_QUEUE binding (without it ENV_UNDECLARED fires, correctly). The same action compiles with that config in tests/output-matrix/fixtures/push. */}
175
+
174
176
  ```typescript
175
177
  // features/events/actions/publish.ts
176
178
  import { z } from "zod";
@@ -86,7 +86,7 @@ The compiler emits the `[[durable_objects.bindings]]` block, the `[[migrations]]
86
86
 
87
87
  ## Connect from the client
88
88
 
89
- The `partysocket` package handles reconnection, buffering, and resilience. The `party` field is the kebab-cased binding name (`INTERVIEW_ROOM` → `interview-room`); the `room` field is any opaque ID.
89
+ The `partysocket` package handles reconnection, buffering, and resilience. The `party` field is the kebab-cased binding name (`INTERVIEW_ROOM` → `interview-room`); the `room` field is an opaque ID that must be **URL-safe as stored** (letters, digits, `-`, `_`, `.`, `~`, and `:` for the multi-resource form). The gates refuse a percent-encoded room segment with `404` rather than decode it: PartyServer names the Durable Object from the raw segment, so decoding would authorise one id (`ab`) while opening another (`a%62`). Generate room ids (and `key` column values) from a URL-safe alphabet; cuid2, nanoid and UUIDs all qualify.
90
90
 
91
91
  ```ts
92
92
  import PartySocket from 'partysocket';
@@ -109,7 +109,7 @@ socket.send(JSON.stringify({ type: 'note', body: 'asked about tenure' }));
109
109
 
110
110
  ## Authentication
111
111
 
112
- The auto-mounted middleware is **secure by default** — anonymous WebSocket upgrades are rejected with `401 Unauthorized` before `partyserverMiddleware` sees the request. The four auth mechanisms the rest of the worker honors all unlock connections:
112
+ The auto-mounted middleware is **secure by default** — anonymous WebSocket upgrades are rejected with `401 Unauthorized` before `partyserverMiddleware` sees the request. A path with an empty segment (`/realtime//interview-room/abc`) is refused with `404` first, because PartyServer would route it to the same room while it matched none of the per-room gates below. The four auth mechanisms the rest of the worker honors all unlock connections:
113
113
 
114
114
  - session cookie
115
115
  - `Authorization: Bearer <jwt>`
@@ -118,7 +118,7 @@ The auto-mounted middleware is **secure by default** — anonymous WebSocket upg
118
118
 
119
119
  (For the hand-written mount form below, you can also accept signed `?ws_ticket=` query params using the same issuer the Broadcaster exposes at `/broadcast/v1/ws-ticket`.)
120
120
 
121
- The default gate only checks **whether** the caller is authenticated, not whether they're allowed in *this* room. For per-room authorization, the `access` field on the binding lets the compiler emit a path-scoped gate that runs your existing resource firewall + `read.access` pipeline before the WebSocket upgrade — no hand-written code, same status semantics as `GET /api/v1/<resource>/:id`.
121
+ The default gate only checks **whether** the caller is authenticated, not whether they're allowed in *this* room. For per-room authorization, the `access` field on the binding lets the compiler emit a path-scoped gate that runs your existing resource firewall before the WebSocket upgrade — no hand-written code, same status semantics as `GET /api/v1/<resource>/:id`. Who may connect and who may write are declared on the binding itself with `roles` and `writeRoles` ([Room roles](#room-roles)); without them the gate falls back to the table's CRUD `read.access`.
122
122
 
123
123
  ### Per-room authorization via `access`
124
124
 
@@ -158,10 +158,15 @@ bindings: {
158
158
 
159
159
  // Room keyed by a unique non-PK column. A Yjs page editor is
160
160
  // addressed by `event_pages.yjsRoomId`, not the row id — `key` tells the
161
- // gate which column the roomId matches.
161
+ // gate which column the roomId matches. `roles` / `writeRoles` declare
162
+ // the room's own audience, independent of the table's CRUD read access.
162
163
  {
163
164
  name: 'PageRoom', className: 'PageRoom', from: 'lib/PageRoom',
164
- access: { resource: { feature: 'event-pages', table: 'eventPages', key: 'yjsRoomId' } },
165
+ access: {
166
+ resource: { feature: 'event-pages', table: 'eventPages', key: 'yjsRoomId' },
167
+ roles: ['admin', 'member'], // who may connect
168
+ writeRoles: ['admin'], // who may edit; members connect read-only
169
+ },
165
170
  },
166
171
 
167
172
  // Identity-gated room — the roomId IS the caller's own id, with no backing
@@ -183,7 +188,7 @@ bindings: {
183
188
 
184
189
  What the compiler emits:
185
190
 
186
- - **`access: { resource: 'chats' }`** — `app.use('/realtime/chat/*', …)` that 401s anonymous, parses the URL segment as a row id, queries `chats` with the resource's `buildFirewallConditions(ctx)` and `eq(chats.id, rowId)`, and 403s when the row is invisible to the caller (out-of-org, soft-deleted, etc.). The DO's `onLoad` / `onConnect` then runs only for rows the user can already read.
191
+ - **`access: { resource: 'chats' }`** — `app.use('/realtime/chat/*', …)` that 401s anonymous, runs the role gate (the binding's `roles`, or the table's `read.access` when `roles` is omitted) before any query, parses the URL segment as a row id, queries `chats` with the resource's `buildFirewallConditions(ctx)` and `eq(chats.id, rowId)`, and 403s when the row is invisible to the caller (out-of-org, soft-deleted, etc.). The DO's `onLoad` / `onConnect` then runs only for rows the caller's firewall admits.
187
192
  - **`access: { resource: { feature, table } }`** — same gate, but the schema import + firewall alias are keyed off the pinned `table` instead of the feature name. Required when a feature owns more than one resourceful table; the access gate emit can't pick which table's firewall to query otherwise.
188
193
  - **`access: { resource: { feature, table, key } }`** — same gate, but it matches the roomId against `table.<key>` instead of `table.id`. Use it when the room is addressed by a unique non-PK column — e.g. a Yjs editor keyed by `event_pages.yjsRoomId` (`ns.idFromName(row.yjsRoomId)`). `key` defaults to `'id'`, so existing pins are unchanged. The compiler validates the column exists at compile time. `key` also works inside each multi-resource branch.
189
194
  - **Multi-resource form** — same gate but with a regex parser dispatching to per-kind firewall lookups. Unknown kinds 400 at the gate. Each `resources[kind].resource` accepts either form (string shorthand or `{ feature, table, key? }`).
@@ -191,7 +196,73 @@ What the compiler emits:
191
196
  - **`access: 'public'`** — `app.use('/realtime/<kebab>/*', …)` that just passes through. Use for anonymous game lobbies / public collab pads where the room itself is the unit of access.
192
197
  - **No `access` declared** — falls through to the catchall `/realtime/*` gate that just checks `ctx.authenticated`.
193
198
 
194
- Compile-time validation: every `resource` / `resources[].resource` value is checked against the project's feature names so typos surface as build errors, not as runtime 400s on the first WS upgrade. The string shorthand requires the feature to have exactly one resourceful table; multi-table features must use the long form `{ feature, table }` to pin a specific table. When `key` is set, the column is checked against the pinned table's schema.
199
+ Every gate above compares the room segment exactly as it appears in the URL; a segment containing `%` is a `404` before any lookup (see [Connect from the client](#connect-from-the-client)).
200
+
201
+ Compile-time validation: every `resource` / `resources[].resource` value is checked against the project's feature names so typos surface as build errors, not as runtime 400s on the first WS upgrade. The string shorthand requires the feature to have exactly one resourceful table; multi-table features must use the long form `{ feature, table }` to pin a specific table. When `key` is set, the column is checked against the pinned table's schema. The resource-backed `access` objects are strict: an unknown key (a misspelled `writeRole`) is a build error, never an ignored narrowing.
202
+
203
+ ### Room roles
204
+
205
+ A resource-backed room declares its own audience, independent of the backing table:
206
+
207
+ ```ts
208
+ access: {
209
+ resource: { feature: 'event-pages', table: 'eventPages', key: 'yjsRoomId' },
210
+ roles: ['admin', 'member', 'scope:event:staff'], // connect (read)
211
+ writeRoles: ['admin', 'scope:event:staff'], // mutate
212
+ },
213
+ ```
214
+
215
+ - **`roles`** gates the WebSocket upgrade. When declared it **replaces** the table's CRUD `read.access` in the gate, so you can narrow (or widen) the room without touching who may read the table. The table's firewall still runs: tenant isolation is not a role decision, and a caller still has to see the row.
216
+ - **`writeRoles`** gates mutations. Everyone `roles` admits may connect; callers outside `writeRoles` connect **read-only**. A writer has to be able to connect, so list writers in both: when both are role lists, a `writeRoles` entry that `roles` doesn't admit is a build error.
217
+
218
+ Both take the same role vocabulary as [resource access](/define/access): org roles, the `role+` hierarchy, pseudo-roles (`AUTHENTICATED`, `SESSION`, `SCOPED`, `SYSADMIN`), scoped roles (`scope:<kind>:<role>`, or their sugar), and declared [`authz.roles`](/define/authz-roles). They're lowered by the same expansion step as `read.access`, so `member+` means the same thing in a room and on a CRUD route. A role list is sugar for `{ roles: [...] }`; the object form adds `userRole` and `or` / `and`:
219
+
220
+ ```ts
221
+ roles: { or: [{ roles: ['admin'] }, { userRole: ['appmanager'] }] },
222
+ ```
223
+
224
+ Refused at compile time, all fail-closed: an empty list, `PUBLIC` (use `access: 'public'`), `record:` predicates (put row conditions in the firewall), and anything that lowers to a `relationship:` or `fga:` arm. `roles` / `writeRoles` are accepted only on the resource-backed forms — `roomIdEquals` and `'public'` rooms have no row to firewall.
225
+
226
+ **How writes are enforced.** The gate evaluates `writeRoles` and forwards the verdict to the Durable Object as `x-quickback-room-access: write | read` (inbound copies are stripped; see [Who connected](#who-connected)). The compiler then re-exports the room class from `src/index.ts` through `withRoomWriteAccess` (`src/lib/realtime-room-access.ts`), which turns the verdict into a connection tag (tags survive hibernation) and refuses a reader's mutations:
227
+
228
+ | Room class | Reader connection |
229
+ |---|---|
230
+ | Yjs (`YServer` / `withYjs` from `y-partyserver` 2.x) | `isReadOnly(connection)` is `true`: document updates are refused, sync and awareness keep working. Custom messages never reach `onCustomMessage`. |
231
+ | Any other PartyServer room | Messages never reach `onMessage`. |
232
+ | Either kind, over HTTP (`onRequest`) | `GET`, `HEAD` and `OPTIONS` pass; any other method gets `403` unless the request carries the `write` verdict. |
233
+
234
+ To accept some reader messages (presence pings, cursors), define `onReadOnlyMessage(connection, message)` on the room; otherwise they're dropped. The HTTP counterpart is `onReadOnlyRequest(request)`, which receives a reader's unsafe request instead of the `403`. Anything other than an explicit `write` verdict is read-only, so a missing header fails closed. DO RPC methods called from an action are not affected; server code that calls the room with `stub.fetch()` directly (bypassing the Worker gate) sets `x-quickback-room-access: write` itself. The writer verdict is stored as a connection tag, so it uses one of PartyServer's tag slots: a write-gated room can return at most 8 tags of its own from `getConnectionTags` (10 per connection, including the connection id and the writer tag). A room that overrides `isReadOnly` keeps its own answer for writers; readers are always read-only. Use `isRoomWriter(connection)` from `src/lib/realtime-room-access.ts` if the room needs the verdict itself.
235
+
236
+ **The room id is masked for non-writers.** When a room with `writeRoles` is keyed by a non-PK column (`key`), that column is masked (`'redact'`) for everyone outside `writeRoles` on every read path masking covers: `GET /`, `GET /:id`, views, and auto-CRUD realtime emits. Through those generated read surfaces, a caller cannot learn a room id it cannot write to. Values your own code returns or sends are not covered: an action that returns the row, or a hand-written broadcast that includes the column, needs its own projection. The binding owns that column's audience, so a hand-written `masking.<key>` on the table is a build error, and `writeRoles` must then be a plain role list (masking audiences can't express `userRole` or `or` / `and`). A reader who is not a writer therefore needs the room id delivered some other way; rooms keyed by the row id (no `key`) mask nothing, because the id is the row's identity on every surface.
237
+
238
+ The backing table declares nothing about the room — no masking on `yjsRoomId`, and its `read.access` can stay as wide as CRUD needs:
239
+
240
+ ```ts
241
+ // quickback/features/event-pages/event-pages.ts
242
+ import { feature, q } from "@quickback/compiler";
243
+
244
+ export default feature("eventPages", {
245
+ columns: {
246
+ id: q.id(),
247
+ title: q.text().required(),
248
+ yjsRoomId: q.text().required().unique(),
249
+ organizationId: q.scope("organization"),
250
+ ...q.audit(),
251
+ ...q.softDelete(),
252
+ },
253
+ read: { access: { roles: ["member", "admin"] } },
254
+ create: { access: { roles: ["admin"] } },
255
+ update: { access: { roles: ["admin"] } },
256
+ });
257
+ ```
258
+
259
+ **Omitting them warns.** A resource-backed room with no `roles` (gated on the table's CRUD `read.access`) or no `writeRoles` (every admitted caller may write) compiles with a warning:
260
+
261
+ ```
262
+ [quickback:authz] AUTHZ_ROOM_ACCESS_INHERITED: realtime room "PageRoom" declares no access.roles or access.writeRoles: …
263
+ ```
264
+
265
+ See [Diagnostics](/define/diagnostics#authz-codes).
195
266
 
196
267
  ### Who connected
197
268
 
@@ -202,6 +273,7 @@ Every upgrade that passes the gate reaches the Durable Object with the caller's
202
273
  | `x-quickback-user-id` | `ctx.userId` |
203
274
  | `x-quickback-org-id` | `ctx.activeOrgId`, when the session has an active organization |
204
275
  | `x-quickback-roles` | `ctx.roles` joined with `,` |
276
+ | `x-quickback-room-access` | `write` or `read` — only on rooms whose binding declares `writeRoles` ([Room roles](#room-roles)) |
205
277
 
206
278
  Read them in `onConnect(connection, ctx)` or `onBeforeConnect(request)` from `ctx.request.headers` / `request.headers`. A display name or avatar is not stamped; look it up from the user id if the room needs one.
207
279
 
@@ -247,13 +319,27 @@ Add `y-partyserver` and `yjs` to `build.dependencies` alongside `partyserver`. T
247
319
 
248
320
  ```ts
249
321
  import { YServer } from 'y-partyserver';
322
+ import * as Y from 'yjs';
250
323
 
251
324
  export class DocumentRoom extends YServer {
252
- // Yjs doc lives on `this.doc`; sync protocol is automatic.
253
- // Override `onLoad()` / `onSave()` to persist to R2 / KV / your DB.
325
+ static options = { hibernate: true };
326
+
327
+ // The Yjs doc lives on `this.document` (a Y.Doc). There is no `this.doc` —
328
+ // reading it returns undefined and throws on first use.
329
+ // Sync protocol is automatic; override `onLoad()` / `onSave()` to persist.
330
+ async onSave() {
331
+ await this.ctx.storage.put('doc', Y.encodeStateAsUpdate(this.document));
332
+ }
333
+
334
+ async onLoad() {
335
+ const saved = await this.ctx.storage.get<Uint8Array>('doc');
336
+ if (saved) Y.applyUpdate(this.document, saved);
337
+ }
254
338
  }
255
339
  ```
256
340
 
341
+ With `writeRoles` on the binding, readers of a `YServer` room are read-only through `isReadOnly` with no code in the class ([Room roles](#room-roles)).
342
+
257
343
  ## Why this and not the Broadcaster
258
344
 
259
345
  The Broadcaster is a one-DO-per-org fan-out. It can't shard by document, and it doesn't model client→client messages. PartyServer's per-room model is the right primitive for collab; the Broadcaster's per-org model is the right primitive for "tell everyone in this org that X happened." Run both.