> Markdown version of https://tuna.am/en/docs/guides/client-protocol/. Documentation index: [llms.txt](https://tuna.am/en/llms.txt), full text in one file: [llms-full.txt](https://tuna.am/en/llms-full.txt). Any page is available as Markdown: append `.md` to its URL without the trailing slash.

# Client protocol

To work with tunnels from code, we have [ready-made SDKs](https://tuna.am/en/docs/guides/install/sdk.md), so start there. If there is no SDK for your language, tell us in the [Telegram chat](https://telegram.me/+Kgbtt0_gJwI5ZmEy) or at <info@tuna.am>, and we will add it. If you can't wait, there are two fallbacks:

* write a client yourself from this specification;
* run [tuna-tiny](https://tuna.am/en/docs/guides/install/install-tiny.md) from your application as a separate process and read its events as JSON (`--log-format json`).

The specification describes what a client sends to the API and to the node and how it must react to responses. The [Go SDK](https://tuna.am/en/docs/guides/install/sdk/go.md) and tuna-tiny follow it.

How a connection works:

1. The client requests a tunnel: `POST https://api.tuna.am/v1/connect`.
2. The API returns the node address, a one-time SSH password and the public tunnel address.
3. The client connects to the node over SSH and sets up a standard remote forward (`tcpip-forward`).
4. The node opens a `forwarded-tcpip` channel for every incoming connection, and the client proxies it to the local service.

## Versions

The client sends the protocol version in the `client_version` field of the `/v1/connect` request.

| Version | What it added                                                    |
| ------- | ---------------------------------------------------------------- |
| 1       | Base protocol: `/v1/connect`, SSH to the node                    |
| 2       | Client keepalive, node events `terminate` and `session_expiring` |

The current version is 2. A version above the one the server supports gets `426 UpgradeRequired`.

## Connecting: `POST /v1/connect`

Authentication is an [API key](https://my.tuna.am/api_keys?lang=en) with the `tunnels:connect` permission in the `token` field of the request body.

Request fields:

| Field                                  | Meaning                                                                                                  |
| -------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `token`                                | API key                                                                                                  |
| `client_version`                       | `2`                                                                                                      |
| `client_name`                          | `<client>/<version>`, for example `my-sdk/1.2.0`                                                         |
| `sdk_version`                          | SDK version, if the client is built on an SDK and `client_name` holds the application name               |
| `protocol`                             | `http` or `tcp`                                                                                          |
| `subdomain`, `domain`, `port_or_alias` | reserved subdomain, custom domain or port, if you need a permanent address                               |
| `proxy_protocol`                       | TCP: PROXY protocol version, `1` or `2`; `0` or no field means off                                       |
| `cidr_allow_list`, `cidr_deny_list`    | TCP: arrays of subnets the node allows or rejects                                                        |
| `forwards_to`                          | local address the client shows to the user; display only                                                 |
| `tunnel_session_id`                    | tunnel session ID from the previous response; `""` on the first connection, but the field is always sent |

Response fields the client needs:

| Field               | What to do with it                                                       |
| ------------------- | ------------------------------------------------------------------------ |
| `tunnel_session_id` | keep it in memory, replacing the previous value                          |
| `address`           | node `host:port` for SSH                                                 |
| `token`             | SSH password for the node; an opaque string, do not parse it             |
| `token_expires_at`  | the password is valid for connecting to the node until this moment       |
| `host_keys`         | accepted node host keys                                                  |
| `public_url`        | public address for the user: `https://<domain>` or `tcp://<host>:<port>` |
| `banner`            | text for the user, if not empty: for example, about a new client version |

## Tunnel session

A session keeps the public tunnel address across reconnects.

* One ID is one public address. A process with several tunnels holds several sessions.
* The ID lives only in memory and is overwritten from every response. There is no need to compare, parse or save it to disk: a new process run starts with an empty ID.
* Every retry of `/v1/connect` after a dropped connection carries the latest ID. The server then keeps the name and port, closes the session's previous tunnel and, if the client could not reach the previous node, assigns another one.
* An unsuitable ID (expired, someone else's, different protocol, invalid format) is not an error: the server silently opens a new session and returns its ID.
* A session lives while its last tunnel is active or was closed no more than 5 minutes ago. If the user or an administrator closed the tunnel, the session ends immediately.
* The ID is not a secret and authorizes nothing: the server checks ownership by the key.

## Connecting to the node

1. TCP to `address`. The connect and handshake timeout is 10 s. There is no point in waiting longer: on retry, the server assigns another node.
2. SSH: user `tuna`, password is `token` from the response, the host key is checked against `host_keys`.
3. Keepalive (below), right after the handshake.
4. `tcpip-forward` on `127.0.0.1:0`. The node opens a `forwarded-tcpip` channel for every incoming connection, and the client proxies it to the local service.
5. Event channel (below), right after `tcpip-forward`, without delaying the tunnel.

The node replies to `tcpip-forward` with the assigned port, and `forwarded-tcpip` carries the same address and port: SSH libraries match the channel to the forward by this pair. Apart from a single `session` event channel, the node rejects all channels with `administratively prohibited`.

## Keepalive

Every 5 s the client sends a global request with `want_reply` and a name of the form `keepalive@…`. `keepalive@openssh.com` and its equivalents in SSH libraries work. No reply for 15 s means the connection is dead: close SSH and go to `/v1/connect` with the current session ID. The node closes the session of a client that has sent no keepalive for 30 s.

Keepalive starts before `tcpip-forward`: the reply to that request may not come either, and without keepalive the client would hang on a node that accepted SSH and went silent.

If the library's built-in keepalive does not wait for a reply or does not exist, the client sends `{"type":"ping"}` to the event channel and waits for `{"type":"pong"}` at the same intervals. The node counts this as a keepalive.

## Event channel

The client opens a `session` channel and sends `exec` with the `events` command and `want_reply`. The node replies with success and writes events to the channel, one JSON line per event:

```json
{"type":"session_expiring","expires_in":300}
{"type":"terminate","reason":"deleted"}

```

* The client skips unknown `type` values and fields: events are added without a protocol version change.
* After `terminate`, the node closes the channel, waits up to 2 s for the client to close its side and drops the connection. The client closes the channel as soon as it has read the event.
* There is one event channel per connection. The node rejects a second `session` channel. Any other `exec` command, as well as `shell` and `subsystem`, gets a failure reply and the channel is closed.
* Open the channel with a timeout and do not block the tunnel on it: the node may not reply. In that case the client does not learn why the tunnel was closed and simply reconnects after the connection drops.

If no event channel is open, the node sends events as global requests `tunnel-terminate@tuna` (with `want_reply`, the client replies `true`) and `session-expiring@tuna`. The payloads are `{"reason": "..."}` and `{"expires_in": <seconds>}`.

### `terminate`

The server closed the tunnel; the reason is in the `reason` field:

| `reason`        | What to do                                                                                                           |
| --------------- | -------------------------------------------------------------------------------------------------------------------- |
| `deleted`       | the user deleted the tunnel; exit                                                                                    |
| `suspended`     | the account or tunnel is suspended; exit                                                                             |
| `session_limit` | the plan's session time limit is reached; exit                                                                       |
| `reconnect`     | the tunnel was replaced by a new connection of the same session, for example a second process with the same ID; exit |
| anything else   | exit                                                                                                                 |

### `session_expiring`

`expires_in` seconds are left until the plan's session time limit. The client warns the user.

## Errors and retries

API errors come as JSON: the code in the `code` field, the text in `error`. Permanent codes are not retried, and the tunnel ends:

`BadRequest`, `Unauthorized`, `Forbidden`, `NotFound`, `PaymentRequired`, `UpgradeRequired`.

* `Tunnel already active` is a regular `400 BadRequest`: another process holds the name. No special handling is needed.
* A 4xx without JSON (HTML from a load balancer, wrong API address) before the first successful connection is a permanent error, except `408` and `429`. After that it is temporary: a load balancer may answer `404` while loading a route, and a long-running client must not exit because of it.
* All other errors and network failures are retried. `503` comes with `Retry-After` in seconds: respect it, but with a cap (5 minutes in the SDK), since a proxy along the way may send a whole day. Between retries, use an exponential pause from 1 to 15 s with random jitter.

## Closing the tunnel

Closing the tunnel listener (like `net.Listener.Close`) does not drop accepted connections. The client stops accepting new channels and reconnecting but keeps SSH open while at least one accepted connection is open.

Accept new `forwarded-tcpip` channels after closing and close them immediately, rather than leaving them unread: in most SSH libraries an unread channel stalls the whole connection.

Do not send `cancel-tcpip-forward`: the node ends the whole session on it.
