Realtime Authorization
Who receives a realtime event — namespace-backed tickets, instance-bound OAuth tokens, role filtering, identity tags, the authorization lease, and per-role masking.
How the realtime broadcaster decides who may connect and which events and fields each connection receives. Start at Durable Objects Setup to enable realtime.
Namespace-backed tickets (per-matched-lane)
The single-role form in Enabling Realtime authorizes the ticket through one relationship.
When the room is gated by an authz namespace
with a multi-lane via: — e.g. an event reachable by attendees, organizers,
contractors, and org admins — point the ticket at the namespace instead, and it
authorizes through the namespace's full via (per-matched-lane):
realtime: {
wsTicket: {
namespace: "eventScope", // authorize via this namespace's full multi-lane `via`
requestField: "eventId",
scopeTable: "events",
},
},/broadcast/v1/ws-ticket now runs the same first-match-wins gate the
namespace uses, and issues the ticket for whichever lane matched:
| Caller matched via | Ticket roles | Ticket scopeRoles |
|---|---|---|
attendeeOf (relationship lane) | attendee | scope:event:attendee |
organizerOf | organizer | scope:event:organizer |
contractorOf | contractor | scope:event:contractor |
{ roles: ["admin","owner"] } (bulk lane) | the caller's org/membership roles | none — no scope role |
scopeRoles holds the proven roles qualified with their kind. The Broadcaster
matches scope:<kind>:<role> audiences and masking show-roles only against
it, never against roles. Every lane that proves a scope role signs it — the
namespace lanes, the tenant session lane, and instance-bound OAuth tickets.
When two kinds share the requestField, each
contributes its own scope:<kind>:<role> entry.
This closes the gap where the single-role form denied (403) an org admin who
could legitimately reach the room through the bulk lane but isn't a confirmed
attendee — their realtime socket now opens.
wsTicket.namespace may also name a namespace declared by a
feature area (_area.ts). This is the one
deliberate exception to the rule that root config never references area-declared
names: namespace-identity wiring attaches the area's complete gate (its full
lane set) and constructs no new grant, so it cannot widen what the area declared.
Such consumers are listed in quickback/authz-manifest.json under the owning area.
scopeTable must be tenant-scoped. Before minting, the route loads the
scopeTable row by requestField through its own firewall — so a ticket can
only target a room whose resource resolves under the caller's tenant (an org-A
admin requesting an org-B eventId gets 403, not a cross-tenant socket). Because
the room is the data — there is no firewall between a ticket and a Durable
Object room — the compiler rejects at build time a namespace-backed or
FGA-gated wsTicket whose scopeTable has firewall: { exception: true } or a
non-tenant (literal-only) firewall with no org/owner/team isolation. (The
org-membership form binds by the organization column directly, so it requires
that column instead.) Use a tenant-scoped scopeTable.
Instance-bound OAuth tokens
A caller holding only an instance-bound OAuth token can mint a ticket when the ticket's requestField is the requestField of a scope kind with oauth (for example both eventId). The bound token reaches POST /broadcast/v1/ws-ticket and no other broadcast path, and the mint is confined to the token's own instance:
- The body's
requestFieldmust equal the token'sqb_scope.id. Any other instance is403, even one the user has a relationship to. - The mint rechecks the exact subject's current admission and intersects the token's roles with the configured ticket gate. Invitee/applicant roles do not enter an attendee/crew-only room.
- The ticket has no organization or account-wide identity:
scopeKey: '<scopeTable>:<id>', syntheticuserId: 'scope:<kind>:<subjectId>', and only that scope identity tag. It cannot receive account-user-targeted orUSER-audience frames. - View tickets (
{ view, rootId }) and the personal fallback room are refused.
Every fresh ticket mint rechecks admission, so a removed guest cannot mint another ticket. Renewal needs a fresh ticket to extend authorization. The mint reads the clock before that admission check and checks the remaining lifetime again after it, so a slow admission never moves the 180-second cap later, and a ticket with no lifetime left is 403. For a tenant-backed kind the recheck runs in the pinned tenant object (qb.admitScope) for the token's exact subject and proving table, and a tenant that cannot answer is 503 TENANT_ADMISSION_UNAVAILABLE. The handshake ticket lasts at most 60 seconds and never beyond the source token expiry. The established socket cannot deliver after the source token expires (at most 180 seconds), even when ordinary leases are disabled; expiry closes it on traffic or the coalesced lease alarm. A bound token of a kind on a different requestField gets 403 from the mint.
Role-Based Filtering
Limit which roles receive a broadcast using targetRoles:
// Only hiring managers and recruiters receive this broadcast
await realtime.insert('applications', application, ctx.activeOrgId!, {
targetRoles: ['hiring-manager', 'recruiter']
});
// Interviewers only see applications assigned to them
await realtime.update('applications', newRecord, oldRecord, ctx.activeOrgId!, {
targetRoles: ['hiring-manager']
});Fail-closed: an omitted or empty targetRoles delivers to
nobody — there is no implicit "everyone" fallback. To reach every
authenticated subscriber in the scope, say so explicitly with
targetRoles: ['AUTHENTICATED']. UPPERCASE pseudo-roles (PUBLIC,
AUTHENTICATED, USER, SYSADMIN) are evaluated exactly as the REST access
evaluator does.
Address scope roles in their qualified form. scope:<kind>:<role> reaches only
sockets whose ticket proved that role of that kind:
// Event organizers and the org's owners — not a booth's organizers.
await realtime.update('locations', newRow, oldRow, { scopeKey: 'events:' + newRow.eventId }, {
targetRoles: ['owner', 'scope:event:organizer', 'scope:event:organizer_full'],
});A bare name matches org membership roles and, as deprecated legacy behavior, a scope ticket's bare role names from any kind.
Migrating from pre-0.48: custom
realtime.broadcast(...)/realtime.insert(...)calls that omittedtargetRolesused to fan out to everyone; they now silently deliver to nobody. Audit every manual send and add an explicit audience.
Identity-Tag Targeting
Every connection carries identity tags, proven at ticket mint and signed into the ticket (never client-supplied):
user:<userId>— full Better Auth sessions and ordinary OAuth callers; never an instance-bound OAuth credentialscope:<kind>:<subjectId>— an instance-bound OAuth credential's exact subject (the subject row's id).
Target them with targetTags:
// Reach this guest whether they're connected through their Better Auth session
// (user tag) or an instance-bound token (scope tag) — deduped per socket:
await realtime.broadcast('rsvp.updated', payload, { scopeKey }, {
targetTags: [`scope:guest:${guestId}`, `user:${linkedUserId}`],
targetRoles: ['AUTHENTICATED'],
});Semantics:
- Delivery is the deduplicated union of the runtime's indexed tag lookup
(
getWebSockets(tag)) — no attachment scan, and a dual-identity socket matches once. targetTagsreplaces theuserIdidentity arm when present; the scope/org bind and thetargetRolesaudience still apply on top.- Fail-closed:
targetTags: []delivers to nobody. - Tags are immutable for a socket's lifetime (a Workers hibernation-tag constraint) — an identity change requires a reconnect.
- Limits: at most 10 tags per connection, 256 characters per tag. The mint rejects violations; it never truncates.
Authorization Lease
The 60-second ws-ticket is verified once, at upgrade — but Durable Object hibernation keeps sockets alive indefinitely. Without a lease, a ban, member removal, or subject revocation (say, an organizer cancelling a guest) would never affect an already-connected socket. The lease closes that gap:
- At upgrade, the connection stores
authExpiresAt = ticket.iat + lease(default 15 minutes). - The fan-out skips expired connections — they receive nothing — and closes them with code 4401 so the client knows to re-ticket rather than blindly reconnect. Inbound messages are enforced the same way. Heartbeat pings are answered by the runtime without waking the object (see Heartbeats), so they no longer carry the enforcement. Instead, a Durable Object alarm sweeps idle sockets. Sweeps are coalesced into 60-second buckets, so an idle socket is closed up to a minute after its lease lapses, and a room wakes at most once per bucket in which some lease lapses.
- Renewal happens at mint:
POST /broadcast/v1/ws-ticketre-runs the full authorization gate (session validity, revocation checks, relationship / scope-claim probes), so a revoked principal simply can't obtain a renewal ticket. Revocation propagates within one lease period with no polling.
Configure it on the realtime transport:
providers: {
database: {
config: {
realtime: {
enabled: true,
lease: '15m', // default; also '900s', '1h', or a number of seconds
// lease: false // disable (discouraged — reopens the revocation gap)
},
},
},
}The configured lease must be at least 60 seconds (the handshake-ticket TTL).
Instance-bound OAuth tickets recheck relationship admission on every mint and intersect the current roles with the configured ticket gate's relationship lanes. A namespace that admits attendee and crew relationships does not issue room tickets to invitee or applicant roles declared elsewhere on the same scope kind. Org-role, team, and FGA grants require full account authority and cannot authorize a bound credential.
A bound ticket identifies only scope:<kind>:<subjectId>: both its synthetic
userId and its sole identity tag use that value. It never carries
user:<accountId> and cannot receive account-targeted frames through tags or
userId. USER audiences exclude these exact-subject credentials;
AUTHENTICATED still matches, and so does a scope:<kind>:<role> audience
naming one of their admitted roles (the ticket's scopeRoles). Full sessions
keep their account identity and USER behavior.
Their handshake expiry and socket authorization lease cannot outlive the source access token (at most 180 seconds), even with lease: false. Revoked relationships cannot mint another ticket; after the cap, the next delivery or inbound message closes the socket with 4401 without delivering data. Renewal requires a fresh admitted ticket.
In-place renewal (reauth)
Instead of reconnecting every lease period, a client can renew in place: mint a fresh ticket and send it over the open socket.
// On a timer comfortably inside the lease (e.g. every 10 min for a 15m lease):
const { wsTicket } = await mintTicket(); // POST /broadcast/v1/ws-ticket
ws.send(JSON.stringify({ type: 'reauth', ticket: wsTicket }));
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg.type === 'reauth_ok') {
scheduleNextRenewal(msg.authExpiresAt); // lease extended, roles refreshed
}
if (msg.type === 'error' && msg.code === 'REAUTH_FAILED') {
// Ticket invalid/expired — mint a fresh one and retry before the lease lapses.
}
};
ws.onclose = (event) => {
if (event.code === 4401) {
// Lease expired or identity drift: mint a fresh ticket and reconnect.
reconnectWithFreshTicket();
}
};Renewal is strict: the fresh ticket must carry the same userId,
scopeKey/organizationId, and the exact same tag set as the live socket
(tags are immutable). A renewal that matches extends the lease and refreshes
role/roles/scopeRoles in place — live permission changes without socket
churn; a renewal that drops a scope role drops its audiences and reveals at
once. One
that doesn't closes the socket with 4401: reconnect fresh.
Clients that never send reauth still work — their socket is closed with 4401
once per lease and normal reconnect logic (with a fresh ticket) re-runs the
full gate. The lease is the server-side invariant either way.
Per-Role Field Masking
Apply different field masking based on the subscriber's role using maskingConfig:
await realtime.insert('candidates', newCandidate, ctx.activeOrgId!, {
maskingConfig: {
phone: { type: 'phone', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },
email: { type: 'email', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },
resumeUrl: { type: 'redact', show: { roles: ['owner', 'hiring-manager', 'recruiter'] } },
},
});How masking works:
- Each subscriber receives a payload masked according to their role
- Roles in the
show.rolesarray see unmasked values - All other roles see the masked version
- A
scope:<kind>:<role>entry reveals only to a socket whose ticket proved that role of that kind - A bare entry never reveals to a scope ticket (its bare roles are scope names; REST tests
ctx.roles) - A socket with no roles sees every rule masked
- Each distinct masking variant (the subscriber's role sets — bare and scope — plus whether they own the row) is built and serialized once per publish and reused for every subscriber in that variant — a room of 1,000 members holding three role sets serializes three frames, not 1,000
Available mask types:
| Type | Example Output |
|---|---|
email | j***@y*********.com |
phone | ******4567 |
ssn | *****6789 |
creditCard | **** **** **** 1111 |
name | J*** |
redact | [REDACTED] |
Owner-Based Masking
Show unmasked data to the record owner:
maskingConfig: {
phone: {
type: 'phone',
show: { roles: ['hiring-manager'], or: 'owner' } // Hiring manager OR owner sees unmasked
},
}Durable Objects Setup
Broadcaster configuration, wrangler bindings, event formats, and custom event namespaces. Authorization (tickets, leases, per-role masking) and rooms and delivery have their own pages.
Rooms, Delivery and Scaling
Tenant rooms, the broadcaster architecture, delivery and failure handling, heartbeats, and scaling a room.