# BRC-103 mutual authentication

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

Look up the messages of the BRC-103 handshake and of the signed requests and responses that follow it, as carried over HTTP (BRC-104) and Socket.IO.

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

BRC-103 (Peer-to-peer mutual authentication and certificate exchange) is the protocol in which two peers prove to each other that they control their identity keys (The compressed public key of a wallet, 66 hexadecimal characters, that identifies it to other peers), and then sign every message they exchange. MessageBox and AuthSocket use it. Use this page to look up its messages, for example to build a client or a server in another language.

> BRC-31 Authrite is a separate protocol, not another name for BRC-103.

## At a glance

Select a fact to see its detail:

<ProtocolGlance
  title="BRC-103"
  badge="Mutual authentication"
  items={[
    { label: 'Message format', value: 'JSON AuthMessage', detail: 'Every message is a JSON `AuthMessage`. The examples on this page use version `0.1`.' },
    { label: 'Transports', value: 'HTTP and Socket.IO', detail: 'BRC-104 binds the protocol to HTTP. Socket.IO carries the same messages as frames.', links: [{ label: 'AuthSocket WebSocket protocol', href: '/reference/http-apis/authsocket/' }, { label: 'BRC-104', href: 'https://bsv.brc.dev/peer-to-peer/0104' }] },
    { label: 'Handshake', value: 'POST /.well-known/auth', detail: 'The initial request and the initial response, before any signed message.' },
    { label: 'Implementations', value: '@bsv/sdk and two wrappers', detail: '`Peer` and `AuthFetch` in @bsv/sdk, `@bsv/auth-express-middleware` for Express servers, and `@bsv/authsocket` for Socket.IO.' },
    { label: 'Specifications', value: 'BRC-103, BRC-104, AsyncAPI', detail: 'BRC-103 defines the protocol. The AsyncAPI file in ts-stack lists the channels and payloads.', links: [{ label: 'BRC-103', href: 'https://bsv.brc.dev/peer-to-peer/0103' }, { label: 'BRC-104', href: 'https://bsv.brc.dev/peer-to-peer/0104' }, { label: 'brc103-mutual-auth.yaml', href: 'https://github.com/bsv-blockchain/ts-stack/blob/main/specs/auth/brc103-mutual-auth.yaml' }] },
  ]}
/>

<BlueTable>

| Item | Value |
|------|-------|
| Message format | JSON `AuthMessage`, with the protocol version in `version` (`0.1` in the examples) |
| Transports | HTTP, bound by BRC-104 (The standard that binds BRC-103 to HTTP), and Socket.IO |
| Handshake endpoint | `POST /.well-known/auth` over HTTP, the `authMessage` event over Socket.IO |
| Implementations | `@bsv/sdk` (`Peer` and `AuthFetch`), `@bsv/auth-express-middleware`, `@bsv/authsocket` |
| Specifications | [BRC-103](https://bsv.brc.dev/peer-to-peer/0103), [BRC-104](https://bsv.brc.dev/peer-to-peer/0104) and an [AsyncAPI file in ts-stack](https://github.com/bsv-blockchain/ts-stack/blob/main/specs/auth/brc103-mutual-auth.yaml) |

</BlueTable>

## Handshake messages

The handshake takes two messages, and a third exchange when a peer asks for certificates. Over HTTP, where BRC-104 (The standard that binds BRC-103 to HTTP) binds the protocol, each message is the JSON body of a request or response at `/.well-known/auth`, with no authentication headers. Over Socket.IO each message is a frame on the `authMessage` event, as described in [AuthSocket WebSocket protocol](https://bsvblockchain.com/docs/reference/http-apis/authsocket/).

### Initial request

The peer that starts the exchange sends an `initialRequest` message. It is unsigned, and it has no `nonce`, `payload` or `signature` member.

<BlueTable>

| Field | Description |
|-------|-------------|
| `version` | Protocol version string |
| `messageType` | `initialRequest` |
| `identityKey` | Identity key of the sender |
| `initialNonce` | A random nonce (A random value used once in an exchange, so that a replayed message can be told from a fresh one) of the sender, base64 |
| `requestedCertificates` | The certificates the sender asks the other peer for, or an empty set |

</BlueTable>

```json
{
  "version": "0.1",
  "messageType": "initialRequest",
  "identityKey": "IDENTITY_KEY",
  "initialNonce": "INITIAL_NONCE",
  "requestedCertificates": { "certifiers": [], "types": {} }
}
```

Replace `IDENTITY_KEY` with the identity key of the sender and `INITIAL_NONCE` with a new random nonce, base64 encoded.

### Initial response

The receiver answers with an `initialResponse` message. It creates its own nonce and echoes the nonce it received. The initiator verifies the signature, and then treats the receiver as authenticated.

<BlueTable>

| Field | Description |
|-------|-------------|
| `version` | Protocol version string |
| `messageType` | `initialResponse` |
| `identityKey` | Identity key of the receiver |
| `initialNonce` | The nonce the receiver created |
| `yourNonce` | The `initialNonce` of the request, echoed |
| `signature` | DER signature of the receiver over the two nonces, as an array of byte values |
| `requestedCertificates` | The certificates the receiver asks for, or an empty set |
| `certificates` | Optional. Certificates the receiver shares right away |

</BlueTable>

### Certificate exchange

A peer that sets `requestedCertificates` asks for BRC-52 (Identity certificates, whose fields are encrypted one by one so a holder can reveal only some of them) certificates. The set has two members, `certifiers` and `types`. `certifiers` lists the public keys of the certifiers it accepts, and `types` maps each certificate type ID to the field names it wants. The other peer answers with a `certificateResponse` message that carries a list of verifiable certificates, each with the keys to read only the fields it chose to reveal.

The verifier checks the signature of the certifier before it accepts a field, and treats a certificate as revoked when its `revocationOutpoint` is spent.

## Signed messages after the handshake

Once both peers are authenticated, each message is a `general` message signed by its sender. Over HTTP the signature and the nonces travel in headers. Over Socket.IO they are fields of the frame.

### General message

<BlueTable>

| Field | Description |
|-------|-------------|
| `version` | Protocol version string |
| `messageType` | `general` |
| `identityKey` | Identity key of the sender |
| `nonce` | A fresh random value from the sender, base64 |
| `yourNonce` | The nonce the sender last received from the other peer, base64 |
| `payload` | The signed application data, as an array of byte values |
| `signature` | DER signature of the sender, as an array of byte values |

</BlueTable>

### Request headers and signature

Each HTTP request after the handshake carries these headers:

<BlueTable>

| Header | Description |
|--------|-------------|
| `x-bsv-auth-version` | Protocol version |
| `x-bsv-auth-identity-key` | Identity key of the client |
| `x-bsv-auth-nonce` | A fresh nonce from the client, base64 |
| `x-bsv-auth-your-nonce` | The last nonce of the server, base64 |
| `x-bsv-auth-request-id` | A random 32 byte value, base64 |
| `x-bsv-auth-signature` | ECDSA signature, hexadecimal DER |

</BlueTable>

The signature covers, in this order:

1. The request ID, 32 bytes.
2. The method, the path and the query string, each with its length. An empty query string is written as length `-1`.
3. The number of headers, then each header as a length and name followed by a length and value, sorted by name. Only three kinds of header are signed: every `x-bsv-*` header except `x-bsv-auth-*`, `content-type` without its parameters, and `authorization`.
4. The length of the body, `-1` when there is none, then the body.

Lengths are variable length integers.

### Response headers and signature

The server answers with the same six headers. They carry its own identity key, a fresh nonce of its own, and the last nonce of the client in `x-bsv-auth-your-nonce`. The signature covers the request ID, the status code, the headers and the body.

The headers signed in a response are the `x-bsv-*` headers except `x-bsv-auth-*`, and `authorization`. Everything else, such as `location`, `set-cookie` and `content-type`, is not signed.

## Errors and security

The Express middleware returns the errors below, and the signatures leave some request data unprotected.

### HTTP error responses

The Express middleware answers a request that fails authentication with one of these:

<BlueTable>

| Status | Code | Cause |
|--------|------|-------|
| `401` | `UNAUTHORIZED` or `ERR_AUTH_FAILED` | The request has no authentication headers, or they are not valid |
| `408` | `CERTIFICATE_TIMEOUT` | The server waited 30 seconds for certificates and none arrived |
| `500` | `ERR_RESPONSE_SIGNING_FAILED` or `ERR_INTERNAL_SERVER_ERROR` | The server could not sign its response, or failed in another way |

</BlueTable>

With the option `allowUnauthenticated: true`, a request without headers goes through, and the identity key the application sees is `unknown`.

### What the signature does not cover

- A nonce is not a single use token on its own. Keep the session state the SDK relies on, and make the protected operations of your application idempotent.
- The signature of the initial response covers the two nonces and nothing else. The certificate request and any certificates in that response can be changed in transit. Disclose no plaintext and authorize no side effect from a certificate request callback.
- `requestedCertificates` is an allowlist, not a statement that every listed type or field was supplied. Grant access only on the certificates you received and validated after the handshake.
- The request signature does not cover the scheme and host, cookies, forwarding headers or other standard headers. Fix the expected host at a trusted edge, never pick a tenant from metadata the signature omits, and put every value that decides authorization in a signed `x-bsv-*` or `authorization` header. Use separate server identity keys for hosts that are separate principals.
- BRC-103 signs messages and does not encrypt them. Add transport encryption such as TLS to hide message contents, lengths and frequency on the network.

## Related articles

To learn more about mutual authentication on the BSV blockchain, review these articles:

- [Service APIs overview](https://bsvblockchain.com/docs/reference/http-apis/)
- [AuthSocket WebSocket protocol](https://bsvblockchain.com/docs/reference/http-apis/authsocket/)
- [Authenticate users with their wallet](https://bsvblockchain.com/docs/guides/identity-auth/)