Anvil (broadcasting)
Clients
On this page
A client connects to ws://<host>/app/<ANVIL_APP_KEY>?protocol=7 (wss:// behind HTTPS) and receives
pusher:connection_established with its socket_id and activity_timeout (ANVIL_ACTIVITY_TIMEOUT). In
pusher-js and laravel-echo options: the key, the host as wsHost, the port as wsPort / wssPort, forceTLS
for https, enabledTransports: ["ws", "wss"], and the auth endpoint /broadcasting/auth with the CSRF token in
its headers. Events arrive as {"event": name, "channel": channel, "data": "<the event's JSON as a string>"}.
A browser's socket is accepted when its Origin is APP_URL's origin (its scheme, host and port; a path in
APP_URL does not count) or listed in ANVIL_ALLOWED_ORIGINS
(scheme, host and port compared exactly; non-web schemes such as capacitor://localhost can be listed) or in
CORS_ALLOWED_ORIGINS. null is accepted only when one of the two lists names it. Other origins get
pusher:error 4009 and a close with 4009. A socket without an Origin (a native app, a
server) is accepted: a socket carries no identity, so it gets public channels and the private channels it holds a
signature for. Under APP_ENV=local with a loopback APP_URL, the loopback names of APP_URL's origin
(localhost, 127.0.0.1, [::1], same port) count as that origin.
pusher:signin (user authentication) is answered with pusher:error 4009; the socket stays open.
Mobile apps and other clients#
A native app, a script or another backend connects to the same socket endpoint (it sends no Origin) and
authorizes private channels at POST /api/broadcasting/auth with Authorization: Bearer <token>, form fields or
JSON socket_id and channel_name, as the Pusher client libraries send them. The token is checked by the app's
stateless guards (a bearer-token guard such as Hallmark's hallmark, see API tokens), in registration
order, through auth::authenticate(&app, &mut parts, GuardSet::Stateless); the session and its cookie are never
read there.
- No valid token:
401 {"error":"Unauthenticated."}withWWW-Authenticate: Bearer. - A token without the ability
broadcasting(or*): the endpoint's uniform403 {"error":"Forbidden"}. - Otherwise the channel rules are the cookie endpoint's: the pattern's callback decides,
ctx.user_id()is the token's user,ctx.user::<User>()loads it andctx.principal()gives the principal (guard, credential, abilities). The answer is200 {"auth": "…"}. - The signature names the token by its key (
<guard>:token:<id>, such ashallmark:token:12), and expires after five minutes or when the token does, whichever comes first.
Flutter#
Flutter and Dart apps connect with the dart_pusher_channels
package, a Pusher protocol 7 client in pure Dart that takes a custom host, and sign in with Hallmark tokens over
http. examples/flutter-client is a complete app.
flutter pub add dart_pusher_channels http
Signing in. POST /api/tokens (see API tokens) answers 201 with the token; keep it in the
platform's secure storage (the flutter_secure_storage package, for example) rather than in plain preferences.
import 'dart:convert';
import 'package:dart_pusher_channels/dart_pusher_channels.dart';
import 'package:http/http.dart' as http;
final api = Uri.parse('https://app.example.com');
Future<String> signIn(String email, String password) async {
final res = await http.post(
api.resolve('/api/tokens'),
headers: {'Content-Type': 'application/json', 'Accept': 'application/json'},
body: jsonEncode({'email': email, 'password': password, 'device_name': 'Pixel 9'}),
);
if (res.statusCode != 201) throw Exception('sign-in failed: ${res.statusCode}');
return jsonDecode(res.body)['token'] as String;
}
Connecting. The key is the app's ANVIL_APP_KEY (set it in .env: the derived key changes with APP_KEY). In
production the socket is wss on the HTTPS host and port; in development it is ws on SERVER_PORT, and the
Android emulator reaches the development machine's 127.0.0.1 at 10.0.2.2 (ws://10.0.2.2:8000; Android refuses
plain http / ws unless the app's manifest allows cleartext traffic, which the example does in debug builds only).
final client = PusherChannelsClient.websocket(
options: PusherChannelsOptions.fromHost(
scheme: 'wss',
host: 'app.example.com',
port: 443,
key: 'your-anvil-app-key', // ANVIL_APP_KEY
),
connectionErrorHandler: (exception, trace, refresh) => refresh(),
);
Channels. Private and presence channels authorize at /api/broadcasting/auth with the bearer token; the
package's delegate posts socket_id and channel_name as form fields:
final authUrl = api.resolve('/api/broadcasting/auth');
final headers = {'Authorization': 'Bearer $token', 'Accept': 'application/json'};
final news = client.publicChannel('news');
final orders = client.privateChannel(
'private-orders.7',
authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPrivateChannel(
authorizationEndpoint: authUrl,
headers: headers,
onAuthFailed: onAuthFailed,
),
);
final room = client.presenceChannel(
'presence-rooms.1',
authorizationDelegate: EndpointAuthorizableChannelTokenAuthorizationDelegate.forPresenceChannel(
authorizationEndpoint: authUrl,
headers: headers,
onAuthFailed: onAuthFailed,
),
);
// The package reconnects after a close but does not subscribe again by itself: subscribe on every connection.
final channels = <Channel>[news, orders, room];
client.onConnectionEstablished.listen((_) {
for (final channel in channels) {
channel.subscribeIfNotUnsubscribed();
}
});
await client.connect();
Events arrive with their name and the event's JSON:
orders.bind(r'App\Events\OrderShipped').listen((event) {
final data = event.tryGetDataAsMap(); // {"order_id": 7, "tracking": "1Z999"}
});
Presence members. room.state?.members holds the members' ids, but the package drops the user_info of the
list that comes with the subscription; read it from the pusher:subscription_succeeded event's data, and follow
member_added / member_removed:
final names = <String, String>{};
room.whenSubscriptionSucceeded().listen((event) {
final hash = event.tryGetDataAsMap()?['presence']?['hash'] as Map? ?? {};
names
..clear()
..addAll({for (final e in hash.entries) '${e.key}': '${e.value['name']}'});
});
room.whenMemberAdded().listen((event) {
final data = event.tryGetDataAsMap()!;
names['${data['user_id']}'] = '${data['user_info']['name']}';
});
room.whenMemberRemoved().listen((event) => names.remove('${event.tryGetDataAsMap()!['user_id']}'));
Whispers (client events, on a registration with .whispers()): the other subscribers receive them with the
sender's user_id on a presence channel; the sender does not.
room.trigger(eventName: 'client-typing', data: {'typing': true});
room.bind('client-typing').listen((event) => print('${event.userId} is typing'));
Revocation and signing out. When the token is signed out or revoked elsewhere, the server closes the socket with
4200; the package reconnects, authorizing the channels again answers 401, and onAuthFailed gets the exception:
the app returns to its sign-in. Signing out on the device deletes the token:
void onAuthFailed(dynamic exception, StackTrace trace) {
if (exception is EndpointAuthorizableChannelTokenAuthorizationException &&
exception.response.statusCode == 401) {
// The token has ended: back to the sign-in.
}
}
Future<void> signOut() async {
await http.delete(api.resolve('/api/tokens/current'), headers: headers); // 204
await client.disconnect();
client.dispose();
}
Revocation#
A private subscription ends when the credential that authorized it ends. Every serving process listens to the app's
auth events (PubSub topic auth, see PubSub): signing out ends the
subscriptions authorized by that session's cookie endpoint requests; a password change or logout_other_devices
ends every credential of the user except the one named; a token its guard revokes ends the subscriptions it
authorized. The sockets holding such a subscription are closed with 4200 (the client reconnects at once and
authorizes its channels again, which now fails for the ended credential), and a signature made before the event
can no longer subscribe. That check also refuses a signature dated up to 30 seconds after the event, so a process
whose clock runs a little ahead cannot slip one through; the processes' clocks must agree (NTP). Each process
remembers the last 10,000 events for 15 minutes for that check, and refuses what it cannot check: a signature made
before the process started, before an event it forgot early (more than 10,000 events within 15 minutes), or before
the moment it started listening to them or fell behind them (its PubSub subscription lagged). When it falls
behind, it also closes every socket holding a subscription such a signature authorized with 4200, each at a random
moment within 30 seconds from the next second on, and at most once a minute (later lags join the next round), so
after a lag such a socket can keep its subscription for up to about 90 seconds (60 s for the per-minute limit plus
the 30 s spread). The clients authorize again and get new signatures.
Events are delivered at most once: a socket a lost event did not close lives at most ANVIL_MAX_CONNECTION_AGE
(24 hours by default), and a session that only expires (idle or absolute lifetime) sends no event, so its
subscriptions also end with the socket's age. Several processes need a shared PUBSUB_DRIVER for an event to reach
them all.