@quickback-dev/cli 0.52.1 → 0.54.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.
- package/dist/commands/push.d.ts +20 -0
- package/dist/commands/push.d.ts.map +1 -0
- package/dist/commands/push.js +144 -0
- package/dist/commands/push.js.map +1 -0
- package/dist/commands/push.test.d.ts +2 -0
- package/dist/commands/push.test.d.ts.map +1 -0
- package/dist/commands/push.test.js +76 -0
- package/dist/commands/push.test.js.map +1 -0
- package/dist/docs/content.d.ts.map +1 -1
- package/dist/docs/content.js +20 -10
- package/dist/docs/content.js.map +1 -1
- package/dist/index.js +7 -1
- package/dist/index.js.map +1 -1
- package/dist/lib/file-loader.d.ts.map +1 -1
- package/dist/lib/file-loader.js +6 -2
- package/dist/lib/file-loader.js.map +1 -1
- package/dist/skill/SKILL.md +1 -0
- package/dist/skill/docs/changelog.md +68 -0
- package/dist/skill/docs/compiler/config/index.md +1 -1
- package/dist/skill/docs/compiler/config/providers.md +2 -0
- package/dist/skill/docs/compiler/definitions/access.md +29 -5
- package/dist/skill/docs/compiler/definitions/actions.md +2 -0
- package/dist/skill/docs/compiler/definitions/scopes.md +10 -4
- package/dist/skill/docs/stack/push/index.md +290 -0
- package/dist/skill/docs/stack/realtime/durable-objects.md +1 -1
- package/dist/skill/docs/stack/realtime/index.md +3 -1
- package/dist/skill/docs/stack/realtime/live-views.md +1 -1
- package/dist/skill/docs/stack/realtime/named-invalidations.md +147 -0
- package/dist/skill/docs/stack/realtime/using-realtime.md +1 -0
- package/package.json +1 -1
- package/src/skill/SKILL.md +1 -0
- package/src/skill/docs/changelog.md +68 -0
- package/src/skill/docs/compiler/config/index.md +1 -1
- package/src/skill/docs/compiler/config/providers.md +2 -0
- package/src/skill/docs/compiler/definitions/access.md +29 -5
- package/src/skill/docs/compiler/definitions/actions.md +2 -0
- package/src/skill/docs/compiler/definitions/scopes.md +10 -4
- package/src/skill/docs/stack/push/index.md +290 -0
- package/src/skill/docs/stack/realtime/durable-objects.md +1 -1
- package/src/skill/docs/stack/realtime/index.md +3 -1
- package/src/skill/docs/stack/realtime/live-views.md +1 -1
- package/src/skill/docs/stack/realtime/named-invalidations.md +147 -0
- package/src/skill/docs/stack/realtime/using-realtime.md +1 -0
|
@@ -56,7 +56,7 @@ delete: { access: { roles: ["owner"] } }, // owner only (no +)
|
|
|
56
56
|
The `+` suffix expands at compile time — `"member+"` becomes `["member", "admin", "owner"]` in the generated code. You can mix hierarchical and exact roles: `roles: ["member+", "finance"]` expands to `["member", "admin", "owner", "finance"]`.
|
|
57
57
|
|
|
58
58
|
- Roles without `+` are exact matches (no expansion)
|
|
59
|
-
- Pseudo-roles / reserved markers (`PUBLIC`, `AUTHENTICATED`, `USER`, `ADMIN`, `SYSADMIN`) cannot use the `+` suffix — they're terminal markers
|
|
59
|
+
- Pseudo-roles / reserved markers (`PUBLIC`, `AUTHENTICATED`, `SESSION`, `SCOPED`, `USER`, `ADMIN`, `SYSADMIN`) cannot use the `+` suffix — they're terminal markers
|
|
60
60
|
- Using `+` with a role not in the hierarchy throws a compile error
|
|
61
61
|
- Using `+` without configuring `auth.roleHierarchy` throws a compile error
|
|
62
62
|
|
|
@@ -141,12 +141,14 @@ When `roles` and `userRole` both appear in a single `Access` node, they're combi
|
|
|
141
141
|
|
|
142
142
|
### Pseudo-roles
|
|
143
143
|
|
|
144
|
-
Quickback ships
|
|
144
|
+
Quickback ships seven reserved UPPERCASE markers. Six are real pseudo-roles handled directly by the compiler; `ADMIN` is retained only as a reserved legacy marker so the compiler can fail loudly with migration guidance. The casing carries the boundary: UPPERCASE = compiler-owned marker, lowercase = real role from a plugin's table (e.g. `members.role` from the org plugin).
|
|
145
145
|
|
|
146
146
|
| Role | Auth gate | Compile-time requirement | Runtime check |
|
|
147
147
|
|------|-----------|-------------------------|---------------|
|
|
148
148
|
| `PUBLIC` | bypassed | none — explicit opt-in for unauthenticated access | always passes (auth skipped) |
|
|
149
|
-
| `AUTHENTICATED` | required | none | `ctx.authenticated === true` |
|
|
149
|
+
| `AUTHENTICATED` | required | none | `ctx.authenticated === true` (a full session **or** a scope principal — the wrapper over `SESSION` ∪ `SCOPED`) |
|
|
150
|
+
| `SESSION` | required | none | a full Better Auth session **only** — `ctx.authenticated && !ctx.principal && !ctx.scopePrincipal` |
|
|
151
|
+
| `SCOPED` | required | none | a sessionless scope principal **only** — `ctx.authenticated && ctx.scopePrincipal === true` |
|
|
150
152
|
| `USER` | required | resource firewall **must** scope by `userId` | `ctx.authenticated` AND (`ctx.userRole` is unset OR `ctx.userRole === "user"`) |
|
|
151
153
|
| `ADMIN` | required | reserved legacy marker — compiler rejects it | `false` |
|
|
152
154
|
| `SYSADMIN` | required | `cms: { sysadmin: true }` **must** be set on the project | `ctx.authenticated && ctx.userRole === "sysadmin"` |
|
|
@@ -194,15 +196,37 @@ export default defineTable(listings, {
|
|
|
194
196
|
});
|
|
195
197
|
```
|
|
196
198
|
|
|
197
|
-
#### `AUTHENTICATED` — any
|
|
199
|
+
#### `AUTHENTICATED` — any authenticated caller (the wrapper)
|
|
198
200
|
|
|
199
|
-
Use `roles: ["AUTHENTICATED"]` for endpoints that any logged-in
|
|
201
|
+
Use `roles: ["AUTHENTICATED"]` for endpoints that any logged-in caller can hit, regardless of role or org membership. No plugin context required.
|
|
200
202
|
|
|
201
203
|
```typescript
|
|
202
204
|
// Public events feed — any signed-in user can list/read; anonymous gets 401
|
|
203
205
|
read: { access: { roles: ["AUTHENTICATED"] } }
|
|
204
206
|
```
|
|
205
207
|
|
|
208
|
+
`AUTHENTICATED` is the **wrapper over two auth flavors** — it admits both a full Better Auth session **and** a sessionless scope principal (a scope-token holder, e.g. an event attendee who isn't an org member; see [Scopes](/compiler/definitions/scopes)). It excludes only *external delegated* principals (`ctx.principal`, admitted via `principals:`). When you need to distinguish the two flavors, use `SESSION` or `SCOPED` below; when either is fine, use `AUTHENTICATED`.
|
|
209
|
+
|
|
210
|
+
#### `SESSION` — a full session only
|
|
211
|
+
|
|
212
|
+
Use `roles: ["SESSION"]` when a route must admit **only** a full Better Auth session and **not** a sessionless scope principal. This is `AUTHENTICATED` minus scope-token callers.
|
|
213
|
+
|
|
214
|
+
```typescript
|
|
215
|
+
// Account settings — a real logged-in user, never a scope-token attendee
|
|
216
|
+
read: { access: { roles: ["SESSION"] } }
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
#### `SCOPED` — a scope principal only
|
|
220
|
+
|
|
221
|
+
Use `roles: ["SCOPED"]` for a route that is specifically for **sessionless scope-token callers** (a principal-only surface — e.g. a shared event link or kiosk token with no account). It admits any scope principal regardless of *which* scope; for a **specific** scoped role, use the `scope:<kind>:<role>` form instead (e.g. `scope:event:attendee` — see [Scopes](/compiler/definitions/scopes)).
|
|
222
|
+
|
|
223
|
+
```typescript
|
|
224
|
+
// Principal-only event surface — a scope token, no account required
|
|
225
|
+
read: { access: { roles: ["SCOPED"] } }
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
> **Firewall coherence:** if an access surface admits a scope caller (`SCOPED` or a `scope:<kind>:<role>` role) but the resource firewall can't filter that caller, the compiler **fails the build** — the caller would reach the handler yet see zero rows (a silent `200 + []`). Give the firewall a way to filter them: a `ctx.scope.<kind>` arm inside an `{ any: [...] }` group (compose org **or** scope — see [Firewall](/compiler/definitions/firewall)), a `via:` relationship, or `firewall: [{ exception: true }]`.
|
|
229
|
+
|
|
206
230
|
#### `USER` — per-user records
|
|
207
231
|
|
|
208
232
|
Use `roles: ["USER"]` for resources where each user only sees their own records. **Requires the firewall to scope by `userId`** — the role marker is the access half of the pair, the firewall is the row-filter half.
|
|
@@ -1311,6 +1311,8 @@ table-level generated transition actions. See **[Transitions](/compiler/definiti
|
|
|
1311
1311
|
|
|
1312
1312
|
## After-commit hooks
|
|
1313
1313
|
|
|
1314
|
+
> For typed realtime *"this changed — refresh"* signals, use [`invalidates`](/stack/realtime/named-invalidations) — it rides this same after-commit model but delivers a versioned, targeted frame to subscribers.
|
|
1315
|
+
|
|
1314
1316
|
Secondary effects — activity feeds, notification nudges, cache warmers — must
|
|
1315
1317
|
never roll back or delay the primary write. Instead of hand-wrapping each leg
|
|
1316
1318
|
in `try/catch` + `executionCtx.waitUntil`, declare named `afterCommit` hooks:
|
|
@@ -535,10 +535,16 @@ primary key + the `where:` filter keeps it bounded and fail-closed.
|
|
|
535
535
|
nothing else. There is **no user identity**: the auth middleware builds a context
|
|
536
536
|
with **`ctx.userId` undefined**, so every user-, org-, and owner-gated path
|
|
537
537
|
**fails closed automatically** (an owner firewall compares against `undefined`
|
|
538
|
-
→ matches nothing; org-role gates see empty `ctx.roles`).
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
`
|
|
538
|
+
→ matches nothing; org-role gates see empty `ctx.roles`). `AUTHENTICATED`
|
|
539
|
+
**admits** a scope principal past the auth gate — it's the wrapper over session
|
|
540
|
+
*and* scope callers (see [Access → Pseudo-roles](/compiler/definitions/access),
|
|
541
|
+
where `SESSION` and `SCOPED` distinguish the two) — but a user/org/owner
|
|
542
|
+
**firewall** then filters it to **zero rows** (no `ctx.userId`, no `ctx.activeOrgId`),
|
|
543
|
+
so it reaches nothing it shouldn't. `USER` is likewise gate-permissive but
|
|
544
|
+
firewall-excluded: it mandates a `userId` scope the principal can't satisfy. To
|
|
545
|
+
serve a scope principal actual rows, use `scope:<kind>:<role>` gates +
|
|
546
|
+
`ctx.scope.<kind>` firewall arms (or `SCOPED` to admit any scope-token caller as
|
|
547
|
+
a tier).
|
|
542
548
|
|
|
543
549
|
Everything downstream — REST firewall, masking, scoped-role access, the realtime
|
|
544
550
|
ws-ticket — then treats the sessionless attendee **identically** to a
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
# Web Push
|
|
2
|
+
|
|
3
|
+
Quickback's push pillar emits a self-contained Web Push delivery module into your project when you set `push.provider: 'web-push'`. The helper handles VAPID JWT signing (RFC 8292), aes128gcm payload encryption (RFC 8291), HTTP delivery to the push service, and 404/410 cleanup — using only `crypto.subtle` and `fetch`. No `web-push` npm package, no Node polyfills, runs unchanged in Cloudflare Workers, Bun, and Deno.
|
|
4
|
+
|
|
5
|
+
APNs is planned as a second provider. The helper signature is shared, so most code that calls `sendPush` today will keep working.
|
|
6
|
+
|
|
7
|
+
## What you get
|
|
8
|
+
|
|
9
|
+
- **`enqueuePushFanout(queue, target, payload, opts?)`** — the primary send surface. Takes a declarative audience (`{ userIds }`, `{ targetTags }`, `{ targetRoles }`, `{ all: true }`) or an explicit subscription list, and routes between inline delivery and queue fan-out.
|
|
10
|
+
- **`sendPush(subscription, payload, vapid)`** — single-recipient delivery. Returns `{ status: 'sent' | 'gone' | 'failed', statusCode, ... }`.
|
|
11
|
+
- **`sendPushBulk(subscriptions, payload, vapid, opts?)`** — in-request fan-out with a default concurrency cap of 8 (Workers subrequest-budget friendly).
|
|
12
|
+
- **`vapidFromEnv(env)`** — assembles the `VapidConfig` from `VAPID_PUBLIC_KEY` / `VAPID_PRIVATE_KEY` / `VAPID_SUBJECT`.
|
|
13
|
+
- **A generated queue consumer** — resolves declarative targets against `push_subscriptions` server-side and delivers chunks of up to 250 recipients per invocation, with automatic 404/410 cleanup.
|
|
14
|
+
- **`quickback push generate-keys [--out <file>]`** — mints a VAPID keypair in the right format. With `--out`, the private key is written to a `0600` file and never printed.
|
|
15
|
+
- **CMS + Account SPA bundles** automatically carry `VITE_QUICKBACK_VAPID_PUBLIC_KEY` (and `vapidPublicKey` on `window.__QUICKBACK_RUNTIME`) so `pushManager.subscribe({ applicationServerKey })` works without extra plumbing.
|
|
16
|
+
|
|
17
|
+
## Quickstart
|
|
18
|
+
|
|
19
|
+
### 1. Mint a VAPID keypair
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
quickback push generate-keys --out .vapid-private-key
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
The public key prints to the terminal; the private key goes only into the file (mode `0600`). Load it into a Wrangler secret and delete the file:
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
npx wrangler secret put VAPID_PRIVATE_KEY < .vapid-private-key
|
|
29
|
+
rm .vapid-private-key
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Avoid `echo "<key>" | wrangler secret put …` — that writes the private key into your shell history. Without `--out`, the key prints once to the terminal and `wrangler secret put` prompts for an interactive paste.
|
|
33
|
+
|
|
34
|
+
The private key is minted **only once**. Losing it means re-subscribing every user.
|
|
35
|
+
|
|
36
|
+
### 2. Configure `quickback.config.ts`
|
|
37
|
+
|
|
38
|
+
```typescript
|
|
39
|
+
push: {
|
|
40
|
+
provider: 'web-push',
|
|
41
|
+
vapidPublicKey: 'BEl62iUYgUivxIkv69yViEuiBIa-Ib9-SkvMeAtA3LFgDzkrxZJjSgSnfckjBJuBkr3qBUYIHBQFLXYp5Nksh8U',
|
|
42
|
+
vapidPrivateKey: 'env:VAPID_PRIVATE_KEY',
|
|
43
|
+
vapidSubject: 'mailto:notifications@example.com',
|
|
44
|
+
defaultSchema: true,
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
`env:VAPID_PRIVATE_KEY` is the convention for "resolve from `wrangler secret put` at runtime" — a **literal private key in config is a compile error**, and the scalar is never written into `wrangler.toml` or any committed file. The worker refuses to boot (503 with an explicit missing-var list) until all three VAPID vars are present.
|
|
49
|
+
|
|
50
|
+
The public key is not a secret. Keep it literal in config so it can be baked into the CMS/Account SPA bundles — an `env:`-referenced public key can't be resolved at compile time, so nothing is baked and your subscribe UI has to source it some other way.
|
|
51
|
+
|
|
52
|
+
### 3. The `push_subscriptions` table
|
|
53
|
+
|
|
54
|
+
With `push.defaultSchema: true`, the compiler injects a hardened, owner-scoped `push_subscriptions` resource:
|
|
55
|
+
|
|
56
|
+
- **INTERNAL-only reads** — the crypto fields (`endpoint`, `p256dh`, `auth`) never leave the worker via any HTTP path. A `views.mine` projection exposes only `id`, `userAgent`, `lastSeenAt`, `createdAt` for "Your devices" UIs.
|
|
57
|
+
- **Owner firewall** — `owner_id` is auto-stamped on create; user A can never read or delete user B's subscription.
|
|
58
|
+
- **Create-time validation** — the endpoint must be `https:` (the worker POSTs VAPID-signed requests at that URL, so an arbitrary endpoint is an SSRF primitive), `p256dh` must decode to a 65-byte uncompressed P-256 point, and `auth` to a 16-byte secret. The `https:` check is not the whole SSRF story: at send time the push sender additionally rejects any endpoint whose host resolves to a private, link-local, loopback, `localhost`, or `.internal` address. Together — **https + a non-public-host block** — this narrows the SSRF surface; treat it as defense-in-depth, not a guarantee that SSRF is impossible.
|
|
59
|
+
- **Proven identity tags** — a `tags` column is stamped **server-side** from `ctx` (`user:<id>`, `role:<name>`, and — only when the request carries a scoped token — `scope:<kind>:<subject>`, the same dialect realtime tickets use). Client-supplied tags are ignored: they drive fan-out targeting. A normal session-cookie subscribe therefore stamps `user:` and `role:` but no `scope:` tag; see [Targeting](#targeting).
|
|
60
|
+
- **Rate limit + cap** — creates are limited to 10/minute per caller, and only the newest 10 live subscriptions per user are kept (older rows are soft-deleted, so a user's new device always works).
|
|
61
|
+
|
|
62
|
+
This create-time hardening (endpoint/key validation, server-side tag stamping, the per-user cap) runs in JS before/after-insert hooks that fire **only on audit-wrapped writes** — the REST create path and actions. The normal browser subscribe is REST, so it's fully covered; but raw-SQL writes, queue/cron inserts, or direct INTERNAL-context inserts into `push_subscriptions` bypass all of it. Don't hand-insert subscription rows expecting the guards to apply.
|
|
63
|
+
|
|
64
|
+
Declaring your own `push_subscriptions` table while `defaultSchema: true` is set is a compile error — pick one owner for the schema.
|
|
65
|
+
|
|
66
|
+
If you roll your own (write it in canonical `pgTable` form; the compiler transforms per target dialect), keep the same security stance and column names — the generated fan-out consumer resolves targets against `endpoint` / `p256dh` / `auth` / `ownerId` / `tags` / `deletedAt`:
|
|
67
|
+
|
|
68
|
+
```typescript
|
|
69
|
+
import { pgTable, text, timestamp } from "drizzle-orm/pg-core";
|
|
70
|
+
import { defineTable } from "@quickback/compiler";
|
|
71
|
+
|
|
72
|
+
export const pushSubscriptions = pgTable("push_subscriptions", {
|
|
73
|
+
id: text("id").primaryKey(),
|
|
74
|
+
endpoint: text("endpoint").notNull().unique(),
|
|
75
|
+
p256dh: text("p256dh").notNull(),
|
|
76
|
+
auth: text("auth").notNull(),
|
|
77
|
+
ownerId: text("owner_id").notNull(), // user-scoped firewall auto-detected
|
|
78
|
+
tags: text("tags"), // JSON array of proven identity tags
|
|
79
|
+
userAgent: text("user_agent"),
|
|
80
|
+
lastSeenAt: timestamp("last_seen_at", { withTimezone: true }),
|
|
81
|
+
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
|
82
|
+
deletedAt: timestamp("deleted_at", { withTimezone: true }),
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
export default defineTable(pushSubscriptions, {
|
|
86
|
+
read: {
|
|
87
|
+
// Crypto fields never leave the worker — even the owning user can't
|
|
88
|
+
// enumerate their own subscriptions via the API. A compromised session
|
|
89
|
+
// must not be able to leak the user's other devices.
|
|
90
|
+
access: { roles: ['INTERNAL'] },
|
|
91
|
+
views: {
|
|
92
|
+
mine: {
|
|
93
|
+
fields: ['id', 'userAgent', 'lastSeenAt', 'createdAt'],
|
|
94
|
+
access: { roles: ['USER'] },
|
|
95
|
+
},
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
crud: {
|
|
99
|
+
create: { access: { roles: ['USER'] } },
|
|
100
|
+
delete: { access: { roles: ['USER'] }, mode: 'soft' },
|
|
101
|
+
},
|
|
102
|
+
});
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
See [Access — INTERNAL pseudo-role](/compiler/definitions/access) for the full security stance.
|
|
106
|
+
|
|
107
|
+
### 4. Subscribe from the browser (DIY for now)
|
|
108
|
+
|
|
109
|
+
Quickback does not yet generate a service worker or subscribe UI — this half is yours. Two pieces:
|
|
110
|
+
|
|
111
|
+
**A minimal `sw.js`** (serve it from your app's origin root):
|
|
112
|
+
|
|
113
|
+
```javascript
|
|
114
|
+
self.addEventListener('push', (event) => {
|
|
115
|
+
const data = event.data?.json() ?? {};
|
|
116
|
+
event.waitUntil(
|
|
117
|
+
self.registration.showNotification(data.title ?? 'Notification', {
|
|
118
|
+
body: data.body,
|
|
119
|
+
icon: data.icon,
|
|
120
|
+
tag: data.tag,
|
|
121
|
+
data, // url + your structured data, read back in notificationclick
|
|
122
|
+
}),
|
|
123
|
+
);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
self.addEventListener('notificationclick', (event) => {
|
|
127
|
+
event.notification.close();
|
|
128
|
+
const url = event.notification.data?.url;
|
|
129
|
+
if (url) event.waitUntil(clients.openWindow(url));
|
|
130
|
+
});
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
**Subscribe + register with the API:**
|
|
134
|
+
|
|
135
|
+
```typescript
|
|
136
|
+
import { api } from './api-client';
|
|
137
|
+
|
|
138
|
+
async function subscribeToPush() {
|
|
139
|
+
await navigator.serviceWorker.register('/sw.js');
|
|
140
|
+
const reg = await navigator.serviceWorker.ready;
|
|
141
|
+
const sub = await reg.pushManager.subscribe({
|
|
142
|
+
userVisibleOnly: true,
|
|
143
|
+
// Baked at compile time; also available as
|
|
144
|
+
// window.__QUICKBACK_RUNTIME.vapidPublicKey on served SPA shells.
|
|
145
|
+
applicationServerKey: import.meta.env.VITE_QUICKBACK_VAPID_PUBLIC_KEY,
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
// The subscription object exposes endpoint + base64url-encoded keys.
|
|
149
|
+
const json = sub.toJSON() as { endpoint: string; keys: { p256dh: string; auth: string } };
|
|
150
|
+
|
|
151
|
+
await api.post('/push_subscriptions', {
|
|
152
|
+
endpoint: json.endpoint,
|
|
153
|
+
p256dh: json.keys.p256dh,
|
|
154
|
+
auth: json.keys.auth,
|
|
155
|
+
userAgent: navigator.userAgent,
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Don't send a `tags` field — the server stamps it from the session and ignores anything the client supplies.
|
|
161
|
+
|
|
162
|
+
### 5. Send from an action
|
|
163
|
+
|
|
164
|
+
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`:
|
|
165
|
+
|
|
166
|
+
```typescript
|
|
167
|
+
// features/events/actions/publish.ts
|
|
168
|
+
import { z } from "zod";
|
|
169
|
+
import { defineAction } from "../.quickback/define-action";
|
|
170
|
+
import { enqueuePushFanout } from "../../../lib/web-push";
|
|
171
|
+
|
|
172
|
+
export default defineAction({
|
|
173
|
+
description: "Publish an event and notify admins.",
|
|
174
|
+
input: z.object({}),
|
|
175
|
+
access: { roles: ["owner", "admin"] },
|
|
176
|
+
async execute({ record, env, effects }) {
|
|
177
|
+
// ...your committed write happens here...
|
|
178
|
+
|
|
179
|
+
// After-commit: notify every subscribed admin.
|
|
180
|
+
effects.enqueue("push:eventPublished", () =>
|
|
181
|
+
enqueuePushFanout(
|
|
182
|
+
env.PUSH_FANOUT_QUEUE!,
|
|
183
|
+
{ targetRoles: ["admin"] },
|
|
184
|
+
{
|
|
185
|
+
title: record.name,
|
|
186
|
+
body: "Event published — tap to review",
|
|
187
|
+
url: `https://app.example.com/events/${record.id}`,
|
|
188
|
+
tag: `event-${record.id}`,
|
|
189
|
+
},
|
|
190
|
+
),
|
|
191
|
+
);
|
|
192
|
+
|
|
193
|
+
return { published: true };
|
|
194
|
+
},
|
|
195
|
+
});
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
The declarative form enqueues **one small message**; the generated queue consumer resolves the audience against `push_subscriptions` inside the server-internal trust zone and fans out delivery chunks. Subscription crypto never enters your action code.
|
|
199
|
+
|
|
200
|
+
Target by `{ targetRoles }` or `{ userIds }` — these match the `role:<name>` and `user:<id>` tags that **every** subscription carries, because they're stamped from `ctx` on a normal session-cookie subscribe. `{ targetTags: ['scope:events:e9'] }` only matches subscriptions created inside a scoped context (see the note under [Targeting](#targeting)); against ordinary session-created rows it selects nobody.
|
|
201
|
+
|
|
202
|
+
### Targeting
|
|
203
|
+
|
|
204
|
+
`enqueuePushFanout` speaks the same identity-tag dialect as [realtime targeting](/stack/realtime/durable-objects). For the common browser subscribe flow, reach for `{ targetRoles }` or `{ userIds }` first — those tags are stamped on every session-created subscription:
|
|
205
|
+
|
|
206
|
+
| Target | Selects |
|
|
207
|
+
|---|---|
|
|
208
|
+
| `{ targetRoles: ['admin'] }` | Rows whose tags include `role:admin` (any listed role) |
|
|
209
|
+
| `{ userIds: ['u1', 'u2'] }` | Subscriptions owned by those users |
|
|
210
|
+
| `{ all: true }` | Every live subscription — broadcast must be this explicit |
|
|
211
|
+
| `{ targetTags: ['scope:events:e9'] }` | Rows whose stamped tags include ANY listed tag — **but `scope:*` tags exist only on scoped-token subscribes** (see note below); against session-created rows this selects nobody |
|
|
212
|
+
| `{ targetTags: [...], targetRoles: [...] }` | Rows matching BOTH arms (AND across arms, union within) |
|
|
213
|
+
| `{ subscriptions: [...] }` | An explicit list you already hold |
|
|
214
|
+
|
|
215
|
+
Selection is **fail-closed**: an empty array selects *nobody* (nothing is enqueued), and a target with no arms at all throws — accidental broadcast is structurally impossible. Tags are proven at subscribe time from `ctx`; clients cannot forge their way into an audience.
|
|
216
|
+
|
|
217
|
+
> **`scope:<kind>:<subject>` tags need a scoped token.** `ctx.scope` is populated *only* from a verified scoped-JWT claim — the same relationship-derived scope the [realtime pillar](/stack/realtime/durable-objects) uses. A normal browser subscribe authenticated with a session cookie stamps only `user:<id>` and `role:<name>`; it **never** stamps a `scope:*` tag. Because targeting is fail-closed, a `{ targetTags: ['scope:events:e9'] }` fan-out over session-created subscriptions silently delivers to **nobody**. Scope targeting works only if your app subscribes users from within a scoped context; otherwise select by role or user id.
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
With an explicit `{ subscriptions }` list, passing `opts.vapid` (via `vapidFromEnv(env)`) lets lists at or under `push.fanout.threshold` (default 500) deliver **inline** with per-recipient results; larger lists chunk onto the queue.
|
|
221
|
+
|
|
222
|
+
## Notifications API payload
|
|
223
|
+
|
|
224
|
+
```typescript
|
|
225
|
+
{
|
|
226
|
+
title: 'Your invite is ready',
|
|
227
|
+
body: 'Tap to RSVP for The Summit',
|
|
228
|
+
url: 'https://attend.vip/rsvp/abc123', // click destination
|
|
229
|
+
icon: 'https://attend.vip/icon-192.png', // 192px PNG
|
|
230
|
+
tag: 'invite-abc123', // collapse with existing notif of same tag
|
|
231
|
+
data: { eventId, guestId }, // arbitrary structured data
|
|
232
|
+
topic: 'invites', // push-service collapse key
|
|
233
|
+
ttl: 86400, // seconds; default push.defaultTtl (86400)
|
|
234
|
+
urgency: 'high', // very-low | low | normal | high; default push.defaultUrgency
|
|
235
|
+
}
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
The browser's service worker decides what to do with the data (see the `sw.js` above).
|
|
239
|
+
|
|
240
|
+
### Masking does not cover push payloads
|
|
241
|
+
|
|
242
|
+
Push payloads are an egress channel the [masking pillar](/compiler/definitions/masking) does **not** see. Masking applies to API reads — a payload you build in an action ships exactly what you put in it, to every device in the audience. Before putting a field in `title`/`body`/`data`, ask whether every targeted recipient is allowed to see it unmasked. Prefer notification-shaped summaries plus a `url` — let the click-through fetch the details through the API, where firewall, access, and masking all apply.
|
|
243
|
+
|
|
244
|
+
## Status semantics
|
|
245
|
+
|
|
246
|
+
| `result.status` | When | Action |
|
|
247
|
+
|---|---|---|
|
|
248
|
+
| `sent` | HTTP 200/201/202 from push service | Done. `messageId` (from `Location` header) optionally available. |
|
|
249
|
+
| `gone` | HTTP 404 or 410 | Subscription is permanently dead — soft-delete it. |
|
|
250
|
+
| `failed` | Other 4xx/5xx, or network error | Caller decides whether to retry. `retryAfter` populated if the service returned a `Retry-After` header. |
|
|
251
|
+
|
|
252
|
+
Treat `gone` as authoritative. Once a push service returns 410, the endpoint will never work again. The generated queue consumer soft-deletes `gone` rows automatically; only inline `sendPush`/`sendPushBulk` callers need to handle it themselves.
|
|
253
|
+
|
|
254
|
+
## Queue fan-out
|
|
255
|
+
|
|
256
|
+
Fan-out above the Workers subrequest budget runs through Cloudflare Queues. The compiler wires everything when `push.provider` is set:
|
|
257
|
+
|
|
258
|
+
- **Producer** — a `[[queues.producers]]` binding (`PUSH_FANOUT_QUEUE`) that `enqueuePushFanout` writes to, in batches of ≤100.
|
|
259
|
+
- **Consumer** — a `push-fanout` branch in the unified `src/queue-consumer.ts` dispatcher, with `max_batch_size: 1` so each ≤250-recipient chunk gets its own invocation. Declarative targets arrive as one `resolve` message; the consumer reads `push_subscriptions` (server-internal trust zone), applies the fail-closed tag match, and re-enqueues `send` chunks.
|
|
260
|
+
- **Per-recipient handling** — one bad endpoint doesn't doom the chunk, and `gone` results are soft-deleted in the same invocation.
|
|
261
|
+
- **Dead letter queue** — after 3 retries, failed chunks land on `<queue>-dlq` and are logged **by count only**: fan-out payloads carry subscription crypto and must never hit logs.
|
|
262
|
+
|
|
263
|
+
Tune via `push.fanout.{threshold, chunkSize, queueName, maxConcurrency}` — defaults 500 / 250 / `{name}-push-fanout` / 5. `chunkSize` is hard-capped at 250 (~25% of the subrequest budget, ~62KB message size).
|
|
264
|
+
|
|
265
|
+
## Browser support
|
|
266
|
+
|
|
267
|
+
- ✅ Chrome (Android, desktop) via FCM
|
|
268
|
+
- ✅ Firefox (Android, desktop) via Mozilla autopush
|
|
269
|
+
- ✅ Edge (desktop) via Windows Push Notification Service
|
|
270
|
+
- ✅ Safari iOS 16.4+ — **only inside installed PWAs** (Add to Home Screen). Apple's push endpoints have known quirks around payload size and TTL semantics; test on real hardware.
|
|
271
|
+
- ❌ Safari macOS — partial support; the helper works but iOS PWA is the supported path.
|
|
272
|
+
|
|
273
|
+
## Privacy posture
|
|
274
|
+
|
|
275
|
+
Push subscription rows contain endpoints that uniquely identify a user's browser instance. Quickback's defaults treat them as personal data:
|
|
276
|
+
|
|
277
|
+
- **`read.access: { roles: ['INTERNAL'] }`** on the table — no public CRUD path, even for the owning user. Compromised sessions cannot enumerate the user's other devices.
|
|
278
|
+
- **`views.mine`** projection exposes only `id`, `userAgent`, `lastSeenAt`, `createdAt` — never the cryptographic material — for "Your devices" UIs.
|
|
279
|
+
- **`VAPID_PRIVATE_KEY`** is wrangler-secret-only; a literal scalar in config is a compile error.
|
|
280
|
+
- **Declarative targeting** keeps subscription crypto out of action code entirely — the audience resolves inside the queue consumer.
|
|
281
|
+
- **410 cleanup** is automatic in the queue consumer, so dead subscription rows don't accumulate.
|
|
282
|
+
|
|
283
|
+
GDPR Article 32 maps cleanly: push endpoints are restricted to those who need them (the worker code that sends), not anyone who could read the table via the API.
|
|
284
|
+
|
|
285
|
+
## References
|
|
286
|
+
|
|
287
|
+
- [RFC 8030](https://datatracker.ietf.org/doc/html/rfc8030) — Generic Event Delivery Using HTTP Push
|
|
288
|
+
- [RFC 8291](https://datatracker.ietf.org/doc/html/rfc8291) — Message Encryption for Web Push (aes128gcm)
|
|
289
|
+
- [RFC 8292](https://datatracker.ietf.org/doc/html/rfc8292) — VAPID for Web Push
|
|
290
|
+
- [Web Push Protocol — MDN](https://developer.mozilla.org/en-US/docs/Web/API/Push_API)
|
|
@@ -72,7 +72,7 @@ providers: {
|
|
|
72
72
|
}
|
|
73
73
|
```
|
|
74
74
|
|
|
75
|
-
That tells `/broadcast/v1/ws-ticket` to authenticate with Better Auth, run the declared gate against `body.eventId`, and mint a short-lived ticket scoped to the resolved `events:<id>` lane. See [Realtime → Enabling Realtime](/stack/realtime#enabling-realtime) for the full per-arm semantics; all three forms fail closed at compile time (ambiguous names living in two vocabularies, missing `auth.roleHierarchy` for `+`, missing `authz.fga`, unknown FGA type/relation, missing organization column, non-tenant-scoped `scopeTable`).
|
|
75
|
+
That tells `/broadcast/v1/ws-ticket` (the broadcast surface tracks `contract.version`, so `/broadcast/v2/ws-ticket` on contract-v2 projects) to authenticate with Better Auth, run the declared gate against `body.eventId`, and mint a short-lived ticket scoped to the resolved `events:<id>` lane. See [Realtime → Enabling Realtime](/stack/realtime#enabling-realtime) for the full per-arm semantics; all three forms fail closed at compile time (ambiguous names living in two vocabularies, missing `auth.roleHierarchy` for `+`, missing `authz.fga`, unknown FGA type/relation, missing organization column, non-tenant-scoped `scopeTable`).
|
|
76
76
|
|
|
77
77
|
### Namespace-backed tickets (per-matched-lane)
|
|
78
78
|
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Quickback ships **two parallel realtime primitives**, both backed by Cloudflare Durable Objects:
|
|
4
4
|
|
|
5
|
-
- **`/broadcast/v1/*` — server fan-out.** One DO instance per subscription scope. Postgres-changes events from CRUD routes plus custom broadcast events flow out to every subscriber, with role filtering and per-role field masking applied. Best for "tell every client in this shared scope that something changed." The scope can be an organization, a specific user, or a compiler-resolved resource key like `events:evt_123`. Documented on this page.
|
|
5
|
+
- **`/broadcast/v1/*` — server fan-out.** One DO instance per subscription scope. Postgres-changes events from CRUD routes plus custom broadcast events flow out to every subscriber, with role filtering and per-role field masking applied. Best for "tell every client in this shared scope that something changed." The scope can be an organization, a specific user, or a compiler-resolved resource key like `events:evt_123`. The `/broadcast/v1` version segment tracks `contract.version` — contract-v2 projects mount the same surface at `/broadcast/v2` (no hidden v1 alias). Documented on this page. For **typed, targeted "this changed — refresh" signals** fired from an action after commit (with optional per-recipient narrowing), see [Named invalidations](/stack/realtime/named-invalidations).
|
|
6
6
|
- **`/realtime/<binding>/<room-id>` — bidirectional rooms.** One DO instance per room (per document, per interview, per game). Client↔client messages, presence, and CRDT-friendly state. Use these for collaborative editing. See [PartyServer rooms](/stack/realtime/partyserver-rooms).
|
|
7
7
|
|
|
8
8
|
Both share the same auth model and ride on the same compiled worker; they solve different problems.
|
|
@@ -154,4 +154,6 @@ missing organization column fails the build with an actionable message.
|
|
|
154
154
|
|
|
155
155
|
- **[Durable Objects Setup](/stack/realtime/durable-objects)** — Broadcaster configuration, wrangler bindings, event formats, masking, and custom namespaces
|
|
156
156
|
- **[Using Realtime](/stack/realtime/using-realtime)** — Subscribing to `/broadcast/v1/*`: WebSocket connection, ticket auth, client-side handling
|
|
157
|
+
- **[Named Invalidations](/stack/realtime/named-invalidations)** — Typed, targeted "this changed — refresh" signals fired from actions after commit, with optional per-recipient narrowing
|
|
158
|
+
- **[Live Views](/stack/realtime/live-views)** — Keep an open view's full join-surface (root + related children) live with hybrid-delta updates and resync-on-reconnect
|
|
157
159
|
- **[PartyServer Rooms](/stack/realtime/partyserver-rooms)** — Per-room collab via `/realtime/<binding>/<room-id>`: presence, live notes, room IDs
|
|
@@ -94,7 +94,7 @@ function PersonDetail({ personId }: { personId: string }) {
|
|
|
94
94
|
Under the hood `useView` uses a **subscribe-then-snapshot** flow so no change
|
|
95
95
|
slips through the gap between reading the surface and the socket going live:
|
|
96
96
|
|
|
97
|
-
1. Requests a **view-scoped ws-ticket** (`POST /broadcast/v1/ws-ticket` with
|
|
97
|
+
1. Requests a **view-scoped ws-ticket** (`POST /broadcast/v1/ws-ticket` — `/broadcast/v2/ws-ticket` on contract-v2 projects — with
|
|
98
98
|
`{ view, rootId }`) — gated by the same root firewall as the read endpoint —
|
|
99
99
|
and opens a WebSocket scoped to `view:<view>:<rootId>`.
|
|
100
100
|
2. Once the socket is open, fetches the full surface via
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
# Named Invalidations
|
|
2
|
+
|
|
3
|
+
CRUD broadcasts tell every subscriber in a scope *"a row changed."* **Named invalidations** let an action say something precise and typed: *"the mobile bundle for event `evt_1` changed — reason `document.created`"* — so clients invalidate exactly the right query or cache, and only the intended audience is notified.
|
|
4
|
+
|
|
5
|
+
They ride the same `/broadcast/v{n}` channel as CRUD broadcasts (see [Using realtime](/stack/realtime/using-realtime)), but they are:
|
|
6
|
+
|
|
7
|
+
- **Typed** — the event, its payload shape, and a contract `version` are declared once in a registry.
|
|
8
|
+
- **Named + versioned** — clients listen for a stable `wireName` (e.g. `event.mobile-bundle.changed`) and branch on a `reason`.
|
|
9
|
+
- **Targeted** — a **delivery profile** sets the maximum audience (a scope room + roles); an optional **recipient resolver** narrows it further, fail-closed.
|
|
10
|
+
- **After-commit + best-effort** — fired from inside an action's `execute`, only if the write commits.
|
|
11
|
+
|
|
12
|
+
## Enable
|
|
13
|
+
|
|
14
|
+
Set `realtime: true` on the database provider and add a registry file under `services/realtime/`:
|
|
15
|
+
|
|
16
|
+
```typescript
|
|
17
|
+
// quickback.config.ts
|
|
18
|
+
database: defineDatabase("cloudflare-d1", { realtime: true }),
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## 1. The registry — `defineRealtime`
|
|
22
|
+
|
|
23
|
+
Declare the typed events. Each event has a `wireName` (what clients subscribe to), a contract `version`, one or more named **variants** (a `reason` + a **strict** Zod `payload`), and the **delivery profiles** it is allowed to use.
|
|
24
|
+
|
|
25
|
+
```typescript
|
|
26
|
+
// services/realtime/attend.ts
|
|
27
|
+
import { z } from "zod";
|
|
28
|
+
import { defineRealtime, defineRealtimeDelivery } from "@quickback/compiler";
|
|
29
|
+
|
|
30
|
+
export const attendRealtime = defineRealtime({
|
|
31
|
+
name: "attend",
|
|
32
|
+
events: {
|
|
33
|
+
mobileBundleChanged: {
|
|
34
|
+
wireName: "event.mobile-bundle.changed", // clients listen for this
|
|
35
|
+
version: 1, // contract version (baked into every frame)
|
|
36
|
+
variants: {
|
|
37
|
+
documentCreated: {
|
|
38
|
+
reason: "document.created", // clients branch on this
|
|
39
|
+
payload: z.object({ eventId: z.string(), documentId: z.string() }).strict(),
|
|
40
|
+
},
|
|
41
|
+
},
|
|
42
|
+
deliveries: ["selectedEvent", "documentWatchers"], // allow-list; profiles defined in steps 2 & 3
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
The `payload` must be a **strict** Zod object — its keys are the projection boundary: only declared keys ever reach the wire. `version` and `reason` are reserved contract fields; a payload key named `version` or `reason` is rejected at compile time.
|
|
49
|
+
|
|
50
|
+
## 2. Delivery profiles — `defineRealtimeDelivery`
|
|
51
|
+
|
|
52
|
+
A profile is the **maximum audience** for an invalidation — a scope room plus the roles allowed to receive it. `access.roles` is required and non-empty (a profile is the ceiling, so *who* is not optional — fail-closed).
|
|
53
|
+
|
|
54
|
+
```typescript
|
|
55
|
+
// The event room, attendees + admins.
|
|
56
|
+
export const selectedEvent = defineRealtimeDelivery({
|
|
57
|
+
target: { scopeKeyFrom: "events:{eventId}" }, // the room; {eventId} resolves from the payload
|
|
58
|
+
access: { roles: ["member", "admin"] },
|
|
59
|
+
});
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
`target` is either a **scope room** (`scopeKeyFrom: "events:{eventId}"` — the `{...}` columns resolve from the invalidation payload/meta) or the **account lane** (`{ organizationId, userIdFrom }`). Fail-closed: if a template column can't be resolved at runtime, the frame goes to **nobody** — never a full-room fan-out.
|
|
63
|
+
|
|
64
|
+
## 3. Recipient narrowing — `defineRealtimeRecipients` (optional)
|
|
65
|
+
|
|
66
|
+
To deliver to *specific* people rather than the whole room+roles audience, attach a recipient resolver. It runs **post-commit on the firewalled db** and returns **identities** (never raw tags). Quickback intersects `scope ∩ roles ∩ recipient-tags` — a resolver can only **narrow**, never widen. Fail-closed: a throw or `[]` delivers to **nobody**.
|
|
67
|
+
|
|
68
|
+
```typescript
|
|
69
|
+
import { defineRealtimeRecipients } from "@quickback/compiler";
|
|
70
|
+
|
|
71
|
+
export const documentWatchers = defineRealtimeDelivery({
|
|
72
|
+
target: { scopeKeyFrom: "events:{eventId}" },
|
|
73
|
+
access: { roles: ["member", "admin"] },
|
|
74
|
+
recipients: defineRealtimeRecipients({
|
|
75
|
+
input: z.object({ eventId: z.string() }).strict(), // projected from payload/meta
|
|
76
|
+
resolve: async ({ db, input, recipient }) => [
|
|
77
|
+
recipient.user("usr_1"), // a specific user
|
|
78
|
+
recipient.scope({ kind: "team", subjectId: input.eventId }), // everyone with a scope
|
|
79
|
+
],
|
|
80
|
+
}),
|
|
81
|
+
});
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The resolver gets `{ db, input, recipient }` — the scoped (firewalled) db, the projected `input`, and a `recipient` builder (`recipient.user(id)` / `recipient.scope({ kind, subjectId })`). It sees only what the acting caller could see. Resolved identities beyond a safety cap are truncated with a warning; malformed returns are dropped.
|
|
85
|
+
|
|
86
|
+
## 4. Firing from an action — `invalidates`
|
|
87
|
+
|
|
88
|
+
Bind events + profiles on the action, then call the handle inside `execute`. The binding accepts the **symbol-ref** form (imported registry members) or the string-name form:
|
|
89
|
+
|
|
90
|
+
```typescript
|
|
91
|
+
// features/events/actions/createDocument.ts
|
|
92
|
+
import { z } from "zod";
|
|
93
|
+
import { defineAction } from "../.quickback/define-action";
|
|
94
|
+
import { attendRealtime, selectedEvent, documentWatchers } from "../../../services/realtime/attend";
|
|
95
|
+
|
|
96
|
+
export default defineAction({
|
|
97
|
+
path: "/events/:eventId/documents",
|
|
98
|
+
method: "POST",
|
|
99
|
+
input: z.object({ documentId: z.string() }),
|
|
100
|
+
access: { roles: ["admin", "owner"] },
|
|
101
|
+
invalidates: {
|
|
102
|
+
bundle: { event: attendRealtime.mobileBundleChanged, delivery: selectedEvent },
|
|
103
|
+
watchers: { event: attendRealtime.mobileBundleChanged, delivery: documentWatchers },
|
|
104
|
+
},
|
|
105
|
+
async execute({ input, invalidate }) {
|
|
106
|
+
// invalidate.<binding>.<variant>(payload, meta?)
|
|
107
|
+
invalidate!.bundle.documentCreated({ eventId: "evt_1", documentId: input.documentId });
|
|
108
|
+
invalidate!.watchers.documentCreated({ eventId: "evt_1", documentId: input.documentId });
|
|
109
|
+
return { success: true };
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Each `invalidate.<binding>.<variant>(payload)` call queues **one** after-commit frame. Works on every action kind — standalone, per-record (`/:id`), bulk (`/batch`), and namespace-hoisted.
|
|
115
|
+
|
|
116
|
+
## Delivery semantics
|
|
117
|
+
|
|
118
|
+
- **After-commit, best-effort.** Calls queue frames that fire only after `execute` returns successfully; a `throw` or a `dryRun` discards them (they ride the after-commit effects collector). A rolled-back batch record fires nothing.
|
|
119
|
+
- **Fail-closed targeting.** An unresolvable scope room or a missing recipient set delivers to nobody — never a broad fan-out.
|
|
120
|
+
- **Projection.** The frame payload is projected to the variant's declared keys; undeclared fields never reach the wire.
|
|
121
|
+
- **Contract fields.** `version` and `reason` are baked from the registry and always present.
|
|
122
|
+
|
|
123
|
+
## The wire frame
|
|
124
|
+
|
|
125
|
+
Clients receive a broadcast frame on `/broadcast/v{n}` (the version tracks `contract.version`):
|
|
126
|
+
|
|
127
|
+
```jsonc
|
|
128
|
+
{
|
|
129
|
+
"type": "broadcast",
|
|
130
|
+
"event": "event.mobile-bundle.changed", // the wireName
|
|
131
|
+
"payload": {
|
|
132
|
+
"version": 1, // contract version → negotiation
|
|
133
|
+
"reason": "document.created", // what changed → what to refresh
|
|
134
|
+
"eventId": "evt_1",
|
|
135
|
+
"documentId": "doc_9"
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Subscribe to the `wireName`, use `version` for contract negotiation, and branch on `reason` to decide which query/cache to invalidate. Role gating (`targetRoles`) and — when a recipient resolver is used — identity narrowing (`targetTags`) are applied by the Broadcaster before the frame reaches any socket; the client just receives the frames meant for it.
|
|
141
|
+
|
|
142
|
+
## Related
|
|
143
|
+
|
|
144
|
+
- [Using realtime](/stack/realtime/using-realtime) — the `/broadcast` channel these frames ride.
|
|
145
|
+
- [Durable Objects](/stack/realtime/durable-objects) — how `scopeKeyFrom` rooms and the broadcast frame formats work.
|
|
146
|
+
- [Scopes](/compiler/definitions/scopes) — how scope identities (attendees, vendors) are established and carried.
|
|
147
|
+
- [Actions](/compiler/definitions/actions) — the `execute` handler and the after-commit effects model.
|
|
@@ -8,6 +8,7 @@ Open a WebSocket connection to the realtime worker:
|
|
|
8
8
|
|
|
9
9
|
```typescript
|
|
10
10
|
const ws = new WebSocket("wss://api.yourdomain.com/broadcast/v1/websocket");
|
|
11
|
+
// Note: /broadcast/v1 tracks contract.version — use /broadcast/v2 on contract-v2 projects.
|
|
11
12
|
```
|
|
12
13
|
|
|
13
14
|
## Authentication
|