From 7c14b51333e5cf85fb51b02919d3842c3440a7d1 Mon Sep 17 00:00:00 2001 From: Christopher Vagnetoft Date: Wed, 13 Mar 2024 12:40:59 +0100 Subject: [PATCH] Added docs on WebSocket support --- doc/WebSockets.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 doc/WebSockets.md diff --git a/doc/WebSockets.md b/doc/WebSockets.md new file mode 100644 index 0000000..13dc7a7 --- /dev/null +++ b/doc/WebSockets.md @@ -0,0 +1,36 @@ +# Websockets with Mercureact + +Enable WebSockets by adding the `websocket` handler to a http listener. + +```javascript +const conn = new WebSocket("wss:///.well-known/mercure?token=" + jwt + "&topic=/product/420"); +conn.onmessage = function (message) { + const update = JSON.parse(message); + // do something with update.data, update.topic[] and update.event +}; + +``` + +## Security + +WebSockets are more difficult to secure than SSEs, which means some tricks will have to be applied. + +Right now that means in-band authentication. This works alongside and identical to anonymous susbcriptions for SSE events. Additionally, tokens and topics are not parsed from the URL at the moment. See below for how to handle auth and subscriptions. + +## Protocol + +The client sends plaintext (for now) consisting of a verb (command) and arguments. Arguments containing spaces must be quoted, and special characters escaped. + +To authenticate, the client should send `auth` followed by a space and the JWT token. If the server has disabled anonymous subscriptions, this MUST be the first message sent when connected, and the client will be disconnected if authentication fails. + +To subscribe, the client sends `subscribe` followed by a space-separated list of topics. + +To unsubscribe, the client sends `unsubscribe` followed by a space-separated list of topics. + +### Responses + +All messages from the server are JSON frames. + +The server will respond with `{"ok":true}` if the command was accepted, and `{"ok":false}` otherwise. + +Events are sent with the keys `event`, `topic` and `data`.