# AuthSocket WebSocket protocol

> For the complete documentation index, see [llms.txt](https://bsvblockchain.com/docs/llms.txt).

Look up the frames and events of AuthSocket, the Socket.IO protocol in which a client and a server prove their identity keys with BRC-103 and sign every application event.

import BlueTable from '/snippets/BlueTable.jsx';
import ProtocolGlance from '/snippets/ProtocolGlance.jsx';

AuthSocket wraps Socket.IO so that each connection starts with a BRC-103 (Mutual authentication between peers: each side proves control of its identity key, then signs its messages) handshake, and every application event is signed by its sender and verified by its receiver. Use this page to look up what a client and a server exchange, for example to build a client in another language or to debug a connection. For the handshake messages themselves, see [BRC-103 mutual authentication](https://bsvblockchain.com/docs/reference/http-apis/brc-103-mutual-auth/).

## At a glance

Select a fact to see its detail:

<ProtocolGlance
  title="AuthSocket"
  badge="WebSocket protocol"
  items={[
    { label: 'Transport', value: 'Socket.IO over ws or wss', detail: 'Standard Socket.IO framing. The events on this page are the application level events sent over it.' },
    { label: 'Authentication', value: 'BRC-103 on authMessage', detail: 'The handshake runs before any application event.', links: [{ label: 'BRC-103 mutual authentication', href: '/reference/http-apis/brc-103-mutual-auth/' }] },
    { label: 'Server', value: '@bsv/authsocket', detail: '`AuthSocketServer` wraps an HTTP server.' },
    { label: 'Client', value: '@bsv/authsocket-client', detail: '`AuthSocketClient` wraps socket.io-client.' },
    { label: 'Specification', value: 'AsyncAPI file', detail: 'The AsyncAPI file in ts-stack lists every channel and payload.', links: [{ label: 'authsocket-asyncapi.yaml', href: 'https://github.com/bsv-blockchain/ts-stack/blob/main/specs/messaging/authsocket-asyncapi.yaml' }] },
  ]}
/>

<BlueTable>

| Item | Value |
|------|-------|
| Transport | Socket.IO over `ws` or `wss` |
| Authentication | BRC-103, carried on the `authMessage` event |
| Server | `@bsv/authsocket` (`AuthSocketServer`) |
| Client | `@bsv/authsocket-client` (`AuthSocketClient`) |
| Specification | [AsyncAPI file in ts-stack](https://github.com/bsv-blockchain/ts-stack/blob/main/specs/messaging/authsocket-asyncapi.yaml) |

</BlueTable>

## Handshake

The handshake runs on the low level `authMessage` event. The `Peer` class of `@bsv/sdk` emits and receives these frames, so application code never uses the event directly.

### Initial request

The client emits an `initialRequest` frame on `authMessage` as soon as it needs to send its first event. The frame is unsigned. It carries the client's identity key (The compressed public key of a wallet, 66 hexadecimal characters, that identifies it to other peers), a nonce (A random value used once in an exchange, so that a replayed message can be told from a fresh one) and the certificates the client asks the server for. The fields are in [BRC-103 mutual authentication](https://bsvblockchain.com/docs/reference/http-apis/brc-103-mutual-auth/#initial-request).

### Initial response

The server answers on the same event with an `initialResponse` frame that carries its own identity key and nonce, the client's nonce echoed back, and a signature over the two nonces. The client treats the server as authenticated once the signature verifies. Set `expectedServerIdentityKey` on the client to accept only a known server. The fields are in [BRC-103 mutual authentication](https://bsvblockchain.com/docs/reference/http-apis/brc-103-mutual-auth/#initial-response).

### Certificate exchange

The server requests certificates only when it is created with the `requestedCertificates` option, a set of `certifiers` and certificate `types` with the fields wanted. The client answers with a `certificateResponse` frame. The option is an allowlist the SDK validates against. The connection callback does not receive the certificates, so the option does not authorize anything by itself. Authorize the verified identity key, or use an integration that exposes the certificates to your code.

## Events after the handshake

After the handshake, each application event is a BRC-103 `general` frame on `authMessage`, signed by the sender. The sections below describe that frame and the application events the MessageBox (A store-and-forward messaging service: it holds each message until its recipient reads it) server defines on top of AuthSocket. AuthSocket itself carries any event name with JSON data.

### Event envelope

The `payload` of a `general` frame is a JSON envelope with the Socket.IO event name and its data. The sender signs the payload together with the session nonces.

<BlueTable>

| Field | Description |
|-------|-------------|
| `messageType` | `general` |
| `version` | Protocol version string |
| `identityKey` | Identity key of the sender |
| `nonce` | Fresh random value from the sender, base64 |
| `yourNonce` | The nonce the sender last received from the other peer |
| `payload` | The envelope `{ "eventName": string, "data": any }` as an array of byte values |
| `signature` | DER signature of the sender, as an array of byte values |

</BlueTable>

The `data` member must be plain JSON. Values that are not JSON, negative zero, accessors, hidden or extra properties, sparse arrays and serialization hooks are rejected before the frame is signed.

### Authentication events

A client that could not send its identity key when the connection opened sends it afterwards. The server accepts the key for this socket and answers with a success event. The failure event is in [Failure events](#failure-events).

<BlueTable>

| Event | Direction | Data |
|-------|-----------|------|
| `authenticated` | Client to server | `{ identityKey }`, the identity key as 66 hexadecimal characters |
| `authenticationSuccess` | Server to client | `{ status: "success" }` |

</BlueTable>

### Room events

A room is the set of connections that receive the messages stored for one box of one recipient. Only an authenticated socket can join, and only the room of its own identity key. The room ID is `<recipientIdentityKey>-<messageBoxType>`. The refusal events are in [Failure events](#failure-events).

<BlueTable>

| Event | Direction | Data |
|-------|-----------|------|
| `joinRoom` | Client to server | The room ID, a string |
| `joinedRoom` | Server to client | `{ roomId }` |
| `leaveRoom` | Client to server | The room ID, a string |
| `leftRoom` | Server to client | `{ roomId }` |

</BlueTable>

### Message events

The client sends a message into a room, the server stores it, creating the box if it does not exist, and answers the sender, then pushes it to the recipient's connections that joined the room.

<BlueTable>

| Event | Direction | Data |
|-------|-----------|------|
| `sendMessage` | Client to server | `{ roomId, message: { messageId, recipient, body } }`. `messageId` is the deduplication key, so a message ID already stored is ignored, `recipient` an identity key and `body` a string |
| `sendMessageAck-{roomId}` | Server to sender | `{ status: "success", messageId }` after the message is stored |
| `sendMessage-{roomId}` | Server to recipient | `{ sender, messageId, body }` |

</BlueTable>

The push on `sendMessage-{roomId}` is best effort, so list the messages over the MessageBox HTTP API to be sure none is missed:

- It reaches only the sockets held by the server process that handled the send. A client joined on another process of a scaled out deployment does not receive it.
- It reaches at most `MESSAGE_BOX_WEBSOCKET_MAX_RECIPIENT_CONNECTIONS` connections of the recipient, the newest first.
- A message that carries a payment is never pushed, because the push cannot carry the payment. The recipient finds it when it lists its messages.
- A send the server refused is never pushed.

A message sent over HTTP is pushed on the same event. When the server charges for messages, a send over the socket gets an error acknowledgement with the code `ERR_PAYMENT_REQUIRES_AUTHFETCH`, and current clients repeat it over HTTP with `AuthFetch`.

## Failures and limits

### Failure events

The server reports a failure as an event to the socket that caused it.

<BlueTable>

| Event | Data | Cause |
|-------|------|-------|
| `authenticationFailed` | `{ reason }` | The identity key sent on `authenticated` is not valid |
| `joinFailed` | `{ roomId, reason, code }` | `joinRoom` was refused. `roomId` is missing when the room was absent or malformed |
| `leaveFailed` | `{ reason }` | `leaveRoom` failed |
| `messageFailed` | `{ reason }` | Processing a `sendMessage` failed |
| `paymentFailed` | `{ reason }` | A socket that is not authenticated tried to send a message |
| `sendMessageAck-{roomId}` | `{ status: "error", code }` | The send failed, for example because the server charges for messages |

</BlueTable>

The `code` of `joinFailed` tells whether to try again:

- `ERR_WEBSOCKET_ROOM_NOT_OWNED` and `ERR_WEBSOCKET_INVALID_ROOM` never succeed for that room.
- `ERR_WEBSOCKET_NOT_AUTHENTICATED`, `ERR_WEBSOCKET_ROOM_LIMIT` and `ERR_WEBSOCKET_CONTROL_RATE_LIMITED` can succeed on a later attempt.

### Connection security

- Socket.IO `connect` reports only that the transport is open. The identity of the server is proven by the handshake and by verified application events.
- The server runs its connection callback only after the identity proof, and before it dispatches the first event. Until the callback finishes, the peer is left out of broadcasts and of delivery by identity key.
- Each connection has its own `Peer` and its own nonces. A failure while authenticating or running a callback disconnects only that socket. The number of authentication messages pending per socket is limited, 32 by default (`maxPendingAuthMessages`).
- AuthSocket signs events and does not encrypt them. Use `wss` to keep them private on the network.

## Related articles

To learn more about mutual authentication and real-time messaging on the BSV blockchain, review these articles:

- [Service APIs overview](https://bsvblockchain.com/docs/reference/http-apis/)
- [BRC-103 mutual authentication](https://bsvblockchain.com/docs/reference/http-apis/brc-103-mutual-auth/)
- [Send messages with @bsv/message-box-client](https://bsvblockchain.com/docs/sdk/packages/message-box-client/)
- [Authenticate users with their wallet](https://bsvblockchain.com/docs/guides/identity-auth/)