@quickback-dev/cli 0.47.9 → 0.47.10

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.
@@ -163,6 +163,16 @@ bindings: {
163
163
  access: { resource: { feature: 'event-pages', table: 'eventPages', key: 'yjsRoomId' } },
164
164
  },
165
165
 
166
+ // Identity-gated room — the roomId IS the caller's own id, with no backing
167
+ // table. A per-user gateway / presence / inbox keyed on `ctx.userId`:
168
+ // auto-emits a gate at /realtime/user-gateway/* that 403s unless the room
169
+ // segment equals the authenticated user's id. Use `ctx.activeOrgId` for a
170
+ // per-org room. No DB query — it's a string compare against ctx.
171
+ {
172
+ name: 'UserGateway', className: 'UserGateway', from: 'lib/UserGateway',
173
+ access: { roomIdEquals: 'ctx.userId' },
174
+ },
175
+
166
176
  // Genuinely public room (no auth, no row lookup) — opt out explicitly.
167
177
  { name: 'PublicLobby', className: 'PublicLobby', from: 'lib/PublicLobby',
168
178
  access: 'public' },
@@ -176,6 +186,7 @@ What the compiler emits:
176
186
  - **`access: { resource: { feature, table } }`** — same gate, but the schema import + firewall alias are keyed off the pinned `table` instead of the feature name. Required when a feature owns more than one resourceful table; the access gate emit can't pick which table's firewall to query otherwise.
177
187
  - **`access: { resource: { feature, table, key } }`** — same gate, but it matches the roomId against `table.<key>` instead of `table.id`. Use it when the room is addressed by a unique non-PK column — e.g. a Yjs editor keyed by `event_pages.yjsRoomId` (`ns.idFromName(row.yjsRoomId)`). `key` defaults to `'id'`, so existing pins are unchanged. The compiler validates the column exists at compile time. `key` also works inside each multi-resource branch.
178
188
  - **Multi-resource form** — same gate but with a regex parser dispatching to per-kind firewall lookups. Unknown kinds 400 at the gate. Each `resources[kind].resource` accepts either form (string shorthand or `{ feature, table, key? }`).
189
+ - **`access: { roomIdEquals: 'ctx.userId' }`** — an **identity gate** for rooms with no backing table, where the roomId *is* the caller's own id. Emits `app.use('/realtime/<kebab>/*', …)` that 401s anonymous, 400s a missing segment, and 403s unless the decoded room segment equals `ctx.userId`. No schema import, no firewall, no DB query — a string compare against the server-resolved `ctx`. Use `'ctx.activeOrgId'` for a per-org room. This is the right gate for per-user gateways, presence, or inbox DOs keyed on `ns.idFromName(ctx.userId)`. Only `'ctx.userId'` and `'ctx.activeOrgId'` are accepted (validated at compile time); anything else is a build error. Distinct from `resource` because there's no row to firewall — it closes the cross-user hole that "no `access` declared" leaves open (any authenticated user could otherwise open another user's room via the catchall).
179
190
  - **`access: 'public'`** — `app.use('/realtime/<kebab>/*', …)` that just passes through. Use for anonymous game lobbies / public collab pads where the room itself is the unit of access.
180
191
  - **No `access` declared** — falls through to the catchall `/realtime/*` gate that just checks `ctx.authenticated`. (v0.11.1 behavior.)
181
192
 
@@ -189,6 +200,7 @@ If a room currently enforces access by hand inside `onConnect` / `onBeforeConnec
189
200
  2. **roomId is a unique non-PK column** (a slug, a `yjsRoomId`) → add `key`: `access: { resource: { feature, table, key: 'yjsRoomId' } }`.
190
201
  3. **one DO class serves several room kinds** (e.g. `conv-<id>` / `ticket-<id>`) → the multi-resource form with a `pattern` that captures the kind and id.
191
202
  4. **access depends on membership, not just tenant** (e.g. "is this user an attendee of the event that owns this page") → you do **not** need hand-written code. Declare the pinned table's firewall with a `via:` relationship; the gate runs the table's *full* `buildFirewallConditions`, relationship subqueries included.
203
+ 5. **roomId is the caller's own identity** (a per-user gateway/presence/inbox where the room *is* `ctx.userId`, with no backing table) → `access: { roomIdEquals: 'ctx.userId' }` (or `'ctx.activeOrgId'`). Do **not** enforce this inside the DO from request data — a Durable Object has no session and only sees client-settable headers, so trusting an `x-user-id` header lets any authenticated user open another user's room. The gate belongs at the Worker edge, which is exactly what this arm emits.
192
204
 
193
205
  The declarative gate runs the exact firewall the CRUD `GET /:id` handler enforces, with the same 401/403 semantics, *before* the WebSocket upgrade — so by the time `onConnect` fires the caller is already authorized. Dropping the hand-rolled check also closes a common gap: a room with no `access` block is reachable by **any** authenticated user who can guess a room id, regardless of tenant.
194
206
 
@@ -0,0 +1,78 @@
1
+ # Schedules (Cron)
2
+
3
+ `defineSchedule` is the trigger-side mirror of [`defineQueue`](/stack/queues). Drop a file in `services/schedules/` and the compiler emits a Worker `scheduled()` (cron) handler plus the matching `[triggers] crons` in `wrangler.toml` — no separate cron Worker, no hand-patching the generated entry.
4
+
5
+ ## Define a schedule
6
+
7
+ ```typescript
8
+ // services/schedules/sweepDigests.ts
9
+ import { defineSchedule } from "quickback";
10
+
11
+ export default defineSchedule({
12
+ name: "sweepDigests", // identifier + audit actor (system:cron-<name>)
13
+ cron: "* * * * *", // Cloudflare cron syntax
14
+ description: "Send pending unread-email digests",
15
+ execute: async ({ db, env, services }) => {
16
+ await runDigestSweep(db, env, services);
17
+ },
18
+ });
19
+ ```
20
+
21
+ One file per schedule under `services/schedules/*.ts`. Files prefixed with `_` are ignored. `name` must be a valid camelCase identifier (it's used as a generated symbol and the audit actor).
22
+
23
+ ## What the compiler emits
24
+
25
+ 1. **`scheduled(event, env, ctx)`** in the Worker's default export, dispatching to every schedule whose cron matches `event.cron`. Multiple schedules can share a cron; a failure in one is isolated from the others.
26
+ 2. **`[triggers] crons = [...]`** in `wrangler.toml` — one deduped, sorted list across all schedules.
27
+ 3. **`src/lib/schedules.ts`** — the generated runner. Regenerated on every `quickback compile`, so there's nothing to hand-maintain.
28
+
29
+ ## Execute context
30
+
31
+ | Field | Type | Notes |
32
+ |-------|------|-------|
33
+ | `db` | Drizzle instance | The same DB the queue handlers get |
34
+ | `env` | `CloudflareBindings` | All worker bindings |
35
+ | `services` | `Services` | The services layer (`createServices(env)`) |
36
+ | `cron` | `string` | The cron pattern that fired |
37
+ | `scheduledTime` | `number` | `event.scheduledTime` (ms epoch) |
38
+ | `withInternalContext` | helper | Opt into the `INTERNAL` trust zone for `roles: ['INTERNAL']`-gated rows |
39
+
40
+ ## Audit & trust
41
+
42
+ Cron runs are **server-internal**: there's no authenticated user, no request, no org scope. A fired tick gets a plain `db` (unscoped Drizzle) plus a `withInternalContext` helper:
43
+
44
+ ```typescript
45
+ execute: async ({ db, withInternalContext }) => {
46
+ // `db` here is unscoped — no firewall WHERE, no audit actor.
47
+
48
+ // Opt into the INTERNAL trust zone for cross-tenant work:
49
+ await withInternalContext(async ({ ctx, db, services }) => {
50
+ // ctx.internal = true, ctx.userId = "system:cron-<name>"
51
+ // audited writes are attributable to e.g. system:cron-sweepDigests
52
+ });
53
+ },
54
+ ```
55
+
56
+ `withInternalContext` builds a context with `internal: true` and `userId: "system:cron-<name>"`, so audited writes made through it are attributable to the schedule (e.g. `system:cron-sweepDigests`) and can reach `roles: ['INTERNAL']`-gated rows. Reach for it whenever the schedule legitimately operates across tenants.
57
+
58
+ ## Failure isolation
59
+
60
+ The generated `scheduled()` dispatcher runs every schedule whose cron matches `event.cron` concurrently (`Promise.all`), and each handler's errors are caught individually — one failing schedule logs `[Cron] Schedule error` and the others still run to completion. A cron with no registered handler logs `[Cron] No schedule registered` and returns.
61
+
62
+ ## Cron syntax
63
+
64
+ Standard Cloudflare cron (`minute hour day-of-month month day-of-week`):
65
+
66
+ | Pattern | Runs |
67
+ |---------|------|
68
+ | `* * * * *` | every minute |
69
+ | `0 * * * *` | top of every hour |
70
+ | `0 0 * * *` | daily at 00:00 UTC |
71
+ | `*/5 * * * *` | every 5 minutes |
72
+
73
+ See Cloudflare's [Cron Triggers](https://developers.cloudflare.com/workers/configuration/cron-triggers/) docs for the full grammar and limits.
74
+
75
+ ## See also
76
+
77
+ - [Queues](/stack/queues) — the async-message counterpart (`defineQueue`)
78
+ - [Triggers](/compiler/definitions/triggers) — row-level lifecycle hooks (distinct from cron)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quickback-dev/cli",
3
- "version": "0.47.9",
3
+ "version": "0.47.10",
4
4
  "description": "CLI for Quickback — define your backend in TypeScript, compile to a fully wired Cloudflare Worker (or Bun / Node) with auth, database, migrations, security, CMS, and Account UI.",
5
5
  "author": "Kardoe Incorporated <paul@kardoe.com>",
6
6
  "license": "MIT",
@@ -2,6 +2,34 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ### Realtime: identity-gated Durable Object rooms (`roomIdEquals`)
6
+
7
+ Per-user Durable Object entrypoints (gateway / presence / inbox) can now declare
8
+ an identity gate on the binding — `access: { roomIdEquals: 'ctx.userId' }` (or
9
+ `'ctx.activeOrgId'`). The compiler emits a Worker-edge gate at
10
+ `/realtime/<kebab>/*` that 401s anonymous callers, 400s a missing segment, and
11
+ 403s unless the decoded room segment equals the server-resolved `ctx` id — a
12
+ string compare with no backing table or DB query. See
13
+ [PartyServer rooms → Per-room authorization](/stack/realtime/partyserver-rooms).
14
+
15
+ - Closes the cross-user hole that "no `access` declared" leaves open: a per-user
16
+ room without a gate falls through to the authenticated-only catchall, so any
17
+ authenticated user could open another user's room by guessing the id.
18
+ - The gate lives at the edge, not in the DO — a Durable Object has no session
19
+ and only sees client-settable headers, so it must never re-authorize from
20
+ request data (trusting an `x-user-id` header was the original spoof hole).
21
+ - Only `'ctx.userId'` and `'ctx.activeOrgId'` are accepted; anything else is a
22
+ compile-time error (fail-closed Zod + generator validation).
23
+
24
+ ### OAuth provider: spurious authorization-server warning silenced by default
25
+
26
+ The generated `oauthProvider({...})` now emits
27
+ `silenceWarnings: { oauthAuthServerConfig: true }` by default. The compiler
28
+ always serves the `/.well-known/oauth-authorization-server` discovery route when
29
+ the provider is enabled, so `@better-auth/oauth-provider`'s
30
+ "please ensure … exists" boot warning was always spurious. Override or extend it
31
+ via `plugins.oauthProvider.silenceWarnings`.
32
+
5
33
  ### `defineSchedule` — cron jobs from a single source
6
34
 
7
35
  Declare a cron schedule in `services/schedules/*.ts` and the compiler emits the
@@ -84,21 +84,30 @@ quickback compile --no-sync-config
84
84
 
85
85
  ## Optional Fields
86
86
 
87
+ Every optional top-level key the config accepts is listed below. You never have to memorize them — after your first compile, the [discoverable options block](#discoverable-options-block) lists each one (minus the ones you've set) right inside your `quickback.config.ts`. This table is the human reference; follow the links for detailed pages.
88
+
87
89
  | Field | Type | Description |
88
90
  |-------|------|-------------|
89
- | `features` | `object` | Feature flags such as `pinnedOrganizationId` — see [Pinned Organization Mode](/compiler/config/single-tenant) |
90
- | `build` | `object` | Build options (`outputDir`, `packageManager`, `dependencies`) |
91
- | `compiler` | `object` | Compiler options — `features.auditFields: false` disables audit field injection project-wide; `migrations.renames` provides rename hints for headless CI; `securityContracts` tunes the route/SQL invariants checker |
92
- | `openapi` | `object` | OpenAPI spec generation (`generate`, `publish`, `docs: 'scalar' \| 'swagger'` for an in-browser API reference) — see [OpenAPI](/compiler/targets/hono-api/using-the-api/openapi) |
93
- | `schemaRegistry` | `object` | Schema registry generation for the CMS (enabled by default, `{ generate: false }` to disable) — see [Schema Registry](/stack/cms/schema-registry) |
94
- | `etag` | `object` | ETag caching for GET responses (enabled by default, `{ enabled: false }` to disable) — see [Caching & ETags](/compiler/targets/hono-api/using-the-api/caching) |
95
- | `cms` | `boolean \| object` | Embed CMS in compiled Worker — see [CMS](/stack/cms) |
96
- | `account` | `boolean \| object` | Embed Account UI in compiled Worker — see [Account UI](/stack/account-ui) |
91
+ | `domain` | `string` | Primary custom domain (auto-inferred from `cms`/`account`/`api` domains if unset) — see [Domains](/compiler/config/domains) |
92
+ | `api` | `object` | Dedicated hostname for the feature API surface (`/api/v1/*`); additive alias — see [Domains](/compiler/config/domains) |
93
+ | `auth` | `object` | App-level auth settings (`roleHierarchy`, `jwt`, `loginUrl`/`profileUrl`, `domain`) — see [Access](/compiler/definitions/access#role-hierarchy) |
94
+ | `authz` | `object` | Relationship-based authorization (`relationships`, `roles`, `permissions`, `arrows`) — see [Permissions](/compiler/definitions/permissions) |
97
95
  | `trustedOrigins` | `string[]` | CORS trusted origins for cross-domain auth |
98
- | `domain` | `string` | Primary API domain (auto-inferred from custom domains if not set) |
99
- | `dev` | `object` | Local development settings (`port`) |
100
- | `auth` | `object` | App-level auth settings (`roleHierarchy`) — see [Access](/compiler/definitions/access#role-hierarchy) |
101
- | `email` | `object` | Email delivery config (`provider`, `from`, `fromName`) |
96
+ | `features` | `object` | Feature flags such as `organizations` / `pinnedOrganizationId` — see [Pinned Organization Mode](/compiler/config/single-tenant) |
97
+ | `cms` | `boolean \| object` | Embed CMS in compiled Worker (`domain`, `access`, `sysadmin`) — see [CMS](/stack/cms) |
98
+ | `account` | `boolean \| object` | Embed Account UI in compiled Worker (`domain`, `name`, `auth.*`, branding) — see [Account UI](/stack/account-ui) |
99
+ | `apps` | `object` | Mount hand-authored SPAs on their own hostname or path prefix — see [Domains](/compiler/config/domains) |
100
+ | `agents` | `boolean \| object` | AI/agent discovery surface (`robots.txt`, `llms.txt`, MCP, OAuth discovery) — see [Agents](/compiler/config/agents) |
101
+ | `security` | `object \| false` | HTTP response security headers (CSP, HSTS, COOP/COEP, Referrer/Permissions-Policy) — see [Security Headers](/compiler/config/security) |
102
+ | `openapi` | `object` | OpenAPI spec generation (`generate`, `publish`, `docs: 'scalar' \| 'swagger'`, `types`) — see [OpenAPI](/compiler/targets/hono-api/using-the-api/openapi) |
103
+ | `schemaRegistry` | `object` | Schema registry generation for the CMS (`{ generate: false }` to disable) — see [Schema Registry](/stack/cms/schema-registry) |
104
+ | `etag` | `object` | ETag caching for GET responses (`{ enabled: false }` to disable) — see [Caching & ETags](/compiler/targets/hono-api/using-the-api/caching) |
105
+ | `email` | `object` | Email delivery config (`provider`, `from`, `fromName`, `region`) — see [Email Configuration](#email-configuration) |
106
+ | `bindings` | `object` | Extra Cloudflare bindings (durable objects, queues, R2, services, `vars`, AI) — see [Bindings](/compiler/config/bindings) |
107
+ | `compiler` | `object` | Compiler internals — `features.auditFields: false`, `migrations.renames` (headless CI), `securityContracts`, `injectId`, `routes` |
108
+ | `build` | `object` | Build options (`outputDir`, `packageManager`, `dependencies`) — see [Custom Dependencies](#custom-dependencies) |
109
+ | `dev` | `object` | Local development settings (`port`, `api`, `cms`, `account`, `hostnames`) — see [Variables](/compiler/config/variables) |
110
+ | `preset` | `string` | Inherit defaults from a named preset |
102
111
 
103
112
  ## Custom Dependencies
104
113
 
@@ -79,17 +79,18 @@ export type Candidate = typeof candidates.$inferSelect;
79
79
  > A table **without** `defineTable()` is a supporting table — used internally by actions or handlers, but never exposed as its own API endpoint. See [Internal Tables](/compiler/definitions/schema#internal-tables-no-routes) for details.
80
80
 
81
81
 
82
- ## The Four Security Layers
82
+ ## The Five Security Layers
83
83
 
84
- Every API request passes through four security layers, in order:
84
+ Every API request passes through five security layers, in order:
85
85
 
86
86
  ```
87
- Request → Firewall → Access → Guards → Masking → Response
88
- │ │ │ │
89
- │ │ │ └── Hide sensitive fields
90
- │ │ └── Block field modifications
91
- │ └── Check roles & conditions
92
- └── Isolate data by owner/org/team
87
+ Request → Rate Limit → Firewall → Access → Guards → Masking → Response
88
+ │ │ │ │ │
89
+ │ │ │ │ └── Hide sensitive fields
90
+ │ │ │ └── Block field modifications
91
+ │ │ └── Check roles & conditions
92
+ │ └── Isolate data by owner/org/team
93
+ └── Cap requests per user / op
93
94
  ```
94
95
 
95
96
  > **Security Applies Everywhere**
@@ -154,25 +155,44 @@ masking: {
154
155
 
155
156
  [Learn more about Masking →](/compiler/definitions/masking)
156
157
 
158
+ ### 5. Rate Limiting (Request Caps)
159
+
160
+ Rate limiting caps **how often** an operation can be called, backed by Cloudflare's native Rate Limiting binding — no extra storage, no third-party libraries. Unlike the other four layers, it's applied to **every resource by default** (read `1000/60s`, writes `200/60s`) and runs first, before any data is touched.
161
+
162
+ ```typescript
163
+ rateLimit: {
164
+ delete: { limit: 5, period: 60 }, // tighter than the 200/60s default
165
+ },
166
+ // read / create / update keep shipped defaults
167
+ ```
168
+
169
+ Override per-op, per-resource, or project-wide; set `false` at any scope to opt out. Limits are keyed by `<resource>:<op>:<userId>` (falling back to client IP for anonymous callers), and over-cap requests get a `429` with `Retry-After`.
170
+
171
+ [Learn more about Rate Limiting →](/compiler/definitions/rate-limit)
172
+
157
173
  ## How They Work Together
158
174
 
159
175
  **Scenario:** An interviewer requests `GET /candidates/cnd_123`
160
176
 
161
- 1. **Firewall** checks: Is candidate `cnd_123` in the user's organization?
177
+ 1. **Rate Limit** checks: Is this user under their `read` cap on `candidates`?
178
+ - Yes → Continue
179
+ - No → 429 Too Many Requests (with `Retry-After`)
180
+
181
+ 2. **Firewall** checks: Is candidate `cnd_123` in the user's organization?
162
182
  - Yes → Continue
163
183
  - No → 404 Not Found (as if it doesn't exist)
164
184
 
165
- 2. **Access** checks: Can interviewers perform GET?
185
+ 3. **Access** checks: Can interviewers perform GET?
166
186
  - Yes → Continue
167
187
  - No → 403 Forbidden
168
188
 
169
- 3. **Guards** don't apply to GET (they're for writes)
189
+ 4. **Guards** don't apply to GET (they're for writes)
170
190
 
171
- 4. **Masking** applies: User is an `interviewer`, not `recruiter` or `hiring-manager`
191
+ 5. **Masking** applies: User is an `interviewer`, not `recruiter` or `hiring-manager`
172
192
  - Email: `jane@company.com` → `j***@c******.com`
173
193
  - Phone: `555-123-4567` → `******4567`
174
194
 
175
- 5. **Response** sent with masked data
195
+ 6. **Response** sent with masked data
176
196
 
177
197
  ## Locked Down by Default
178
198
 
@@ -183,13 +203,14 @@ Quickback is **secure by default**. Nothing is accessible until you explicitly a
183
203
  | Firewall | AUTO | Auto-detects from `organization_id`/`user_id` columns. Only configure for exceptions. |
184
204
  | Access | DENIED | Explicitly define `access` rules with roles |
185
205
  | Guards | LOCKED | Explicitly list `createable`, `updatable` fields |
206
+ | Rate Limit | ON | Applied to every resource (read 1000/60s, write 200/60s). Override or set `false` to opt out. |
186
207
  | Actions | BLOCKED | Explicitly define `access` for each action |
187
208
 
188
209
  **You must deliberately open each door.** This prevents accidental data exposure.
189
210
 
190
211
  ## Other Resource Options
191
212
 
192
- Beyond the four security layers, `defineTable` accepts a handful of declarative hints that shape the generated API and the CMS without touching your security posture.
213
+ Beyond the five security layers, `defineTable` accepts a handful of declarative hints that shape the generated API and the CMS without touching your security posture.
193
214
 
194
215
  | Option | What it does | Full reference |
195
216
  |---|---|---|
@@ -212,6 +233,7 @@ All options are optional — omit them and Quickback uses sensible defaults (aut
212
233
  3. [Access](/compiler/definitions/access) — Configure read and write permissions
213
234
  4. [Guards](/compiler/definitions/guards) — Control field modifications
214
235
  5. [Masking](/compiler/definitions/masking) — Hide sensitive data
215
- 6. [Views](/compiler/definitions/views) — Column-level security
216
- 7. [Validation](/compiler/definitions/validation) — Field validation rules
217
- 8. [Actions](/compiler/definitions/actions) — Add custom business logic
236
+ 6. [Rate Limit](/compiler/definitions/rate-limit) — Per-operation request caps
237
+ 7. [Views](/compiler/definitions/views) — Column-level security
238
+ 8. [Validation](/compiler/definitions/validation) — Field validation rules
239
+ 9. [Actions](/compiler/definitions/actions) — Add custom business logic
@@ -10,6 +10,7 @@
10
10
  | [Storage](/stack/storage) | KV, R2 | Sessions, cache, files |
11
11
  | [Realtime](/stack/realtime) | Durable Objects | WebSocket for live updates |
12
12
  | [Queues](/stack/queues) | Cloudflare Queues | Background jobs, webhook delivery |
13
+ | [Schedules](/stack/schedules) | Cron Triggers | `defineSchedule` cron jobs, server-internal |
13
14
  | [Vector & AI](/stack/vector) | Workers AI | Embeddings, semantic search |
14
15
  | [Webhooks](/stack/webhooks) | Hono + Queues | Signed inbound, retried outbound |
15
16
  | [Quickback CMS](/stack/cms) | Embedded SPA | Schema-driven admin UI |
@@ -35,6 +36,11 @@
35
36
  │ │ Queues │ │ Better Auth │ │
36
37
  │ │ (Background)│ │ (Email OTP, Passkeys, etc.) │ │
37
38
  │ └─────────────┘ └─────────────────────────────────┘ │
39
+ │ │
40
+ │ ┌─────────────┐ │
41
+ │ │ Schedules │ │
42
+ │ │ (Cron) │ │
43
+ │ └─────────────┘ │
38
44
  └─────────────────────────────────────────────────────────────┘
39
45
  ```
40
46
 
@@ -163,6 +163,16 @@ bindings: {
163
163
  access: { resource: { feature: 'event-pages', table: 'eventPages', key: 'yjsRoomId' } },
164
164
  },
165
165
 
166
+ // Identity-gated room — the roomId IS the caller's own id, with no backing
167
+ // table. A per-user gateway / presence / inbox keyed on `ctx.userId`:
168
+ // auto-emits a gate at /realtime/user-gateway/* that 403s unless the room
169
+ // segment equals the authenticated user's id. Use `ctx.activeOrgId` for a
170
+ // per-org room. No DB query — it's a string compare against ctx.
171
+ {
172
+ name: 'UserGateway', className: 'UserGateway', from: 'lib/UserGateway',
173
+ access: { roomIdEquals: 'ctx.userId' },
174
+ },
175
+
166
176
  // Genuinely public room (no auth, no row lookup) — opt out explicitly.
167
177
  { name: 'PublicLobby', className: 'PublicLobby', from: 'lib/PublicLobby',
168
178
  access: 'public' },
@@ -176,6 +186,7 @@ What the compiler emits:
176
186
  - **`access: { resource: { feature, table } }`** — same gate, but the schema import + firewall alias are keyed off the pinned `table` instead of the feature name. Required when a feature owns more than one resourceful table; the access gate emit can't pick which table's firewall to query otherwise.
177
187
  - **`access: { resource: { feature, table, key } }`** — same gate, but it matches the roomId against `table.<key>` instead of `table.id`. Use it when the room is addressed by a unique non-PK column — e.g. a Yjs editor keyed by `event_pages.yjsRoomId` (`ns.idFromName(row.yjsRoomId)`). `key` defaults to `'id'`, so existing pins are unchanged. The compiler validates the column exists at compile time. `key` also works inside each multi-resource branch.
178
188
  - **Multi-resource form** — same gate but with a regex parser dispatching to per-kind firewall lookups. Unknown kinds 400 at the gate. Each `resources[kind].resource` accepts either form (string shorthand or `{ feature, table, key? }`).
189
+ - **`access: { roomIdEquals: 'ctx.userId' }`** — an **identity gate** for rooms with no backing table, where the roomId *is* the caller's own id. Emits `app.use('/realtime/<kebab>/*', …)` that 401s anonymous, 400s a missing segment, and 403s unless the decoded room segment equals `ctx.userId`. No schema import, no firewall, no DB query — a string compare against the server-resolved `ctx`. Use `'ctx.activeOrgId'` for a per-org room. This is the right gate for per-user gateways, presence, or inbox DOs keyed on `ns.idFromName(ctx.userId)`. Only `'ctx.userId'` and `'ctx.activeOrgId'` are accepted (validated at compile time); anything else is a build error. Distinct from `resource` because there's no row to firewall — it closes the cross-user hole that "no `access` declared" leaves open (any authenticated user could otherwise open another user's room via the catchall).
179
190
  - **`access: 'public'`** — `app.use('/realtime/<kebab>/*', …)` that just passes through. Use for anonymous game lobbies / public collab pads where the room itself is the unit of access.
180
191
  - **No `access` declared** — falls through to the catchall `/realtime/*` gate that just checks `ctx.authenticated`. (v0.11.1 behavior.)
181
192
 
@@ -189,6 +200,7 @@ If a room currently enforces access by hand inside `onConnect` / `onBeforeConnec
189
200
  2. **roomId is a unique non-PK column** (a slug, a `yjsRoomId`) → add `key`: `access: { resource: { feature, table, key: 'yjsRoomId' } }`.
190
201
  3. **one DO class serves several room kinds** (e.g. `conv-<id>` / `ticket-<id>`) → the multi-resource form with a `pattern` that captures the kind and id.
191
202
  4. **access depends on membership, not just tenant** (e.g. "is this user an attendee of the event that owns this page") → you do **not** need hand-written code. Declare the pinned table's firewall with a `via:` relationship; the gate runs the table's *full* `buildFirewallConditions`, relationship subqueries included.
203
+ 5. **roomId is the caller's own identity** (a per-user gateway/presence/inbox where the room *is* `ctx.userId`, with no backing table) → `access: { roomIdEquals: 'ctx.userId' }` (or `'ctx.activeOrgId'`). Do **not** enforce this inside the DO from request data — a Durable Object has no session and only sees client-settable headers, so trusting an `x-user-id` header lets any authenticated user open another user's room. The gate belongs at the Worker edge, which is exactly what this arm emits.
192
204
 
193
205
  The declarative gate runs the exact firewall the CRUD `GET /:id` handler enforces, with the same 401/403 semantics, *before* the WebSocket upgrade — so by the time `onConnect` fires the caller is already authorized. Dropping the hand-rolled check also closes a common gap: a room with no `access` block is reachable by **any** authenticated user who can guess a room id, regardless of tenant.
194
206
 
@@ -39,7 +39,25 @@ One file per schedule under `services/schedules/*.ts`. Files prefixed with `_` a
39
39
 
40
40
  ## Audit & trust
41
41
 
42
- Cron runs are **server-internal**: there's no authenticated user. The execute context runs with `ctx.internal = true` and an audit actor of **`system:cron-<name>`**, so any audited writes are attributable to the schedule that made them (e.g. `system:cron-sweepDigests`). Use `withInternalContext` when the schedule legitimately operates across tenants and needs to touch `INTERNAL`-gated resources.
42
+ Cron runs are **server-internal**: there's no authenticated user, no request, no org scope. A fired tick gets a plain `db` (unscoped Drizzle) plus a `withInternalContext` helper:
43
+
44
+ ```typescript
45
+ execute: async ({ db, withInternalContext }) => {
46
+ // `db` here is unscoped — no firewall WHERE, no audit actor.
47
+
48
+ // Opt into the INTERNAL trust zone for cross-tenant work:
49
+ await withInternalContext(async ({ ctx, db, services }) => {
50
+ // ctx.internal = true, ctx.userId = "system:cron-<name>"
51
+ // audited writes are attributable to e.g. system:cron-sweepDigests
52
+ });
53
+ },
54
+ ```
55
+
56
+ `withInternalContext` builds a context with `internal: true` and `userId: "system:cron-<name>"`, so audited writes made through it are attributable to the schedule (e.g. `system:cron-sweepDigests`) and can reach `roles: ['INTERNAL']`-gated rows. Reach for it whenever the schedule legitimately operates across tenants.
57
+
58
+ ## Failure isolation
59
+
60
+ The generated `scheduled()` dispatcher runs every schedule whose cron matches `event.cron` concurrently (`Promise.all`), and each handler's errors are caught individually — one failing schedule logs `[Cron] Schedule error` and the others still run to completion. A cron with no registered handler logs `[Cron] No schedule registered` and returns.
43
61
 
44
62
  ## Cron syntax
45
63