# Any device: the WebSocket connection

A device can share its connection by speaking one WebSocket to the relay, in any language that has a WebSocket client and plain sockets: an Android app, a script, a router's own program. It carries JSON text messages and binary data messages, and the relay treats such a device as any other: the same admission, the same states, and bytes counted only where a buyer's request enters the network. It is a preview: no device outside Coronium has run on it yet. Calls go to https://supply.coronium.ai.

## Needs

- A device enrolled as in [enrolment](/guides/device-enrol.md), steps 1 to 4, which gives `deviceId`, `deviceSecret` and `relay`; or, where the operator opened them, [enrolment by token](/guides/device-tokens.md), where the device makes its own id and secret.
- Outbound TCP to `relay`, TLS 1.3 and no inbound port. On Android that is Android 10 or later, and a foreground service with its notification while it shares.

## Steps

1. Open `wss://<relay>/v1/device`, with `relay` exactly as enrolment gave it, host and port. Send the secret on the upgrade as `Authorization: Bearer <deviceSecret>`; a client that cannot set a header sends it as `secret` in hello instead, never in both. A refused upgrade answers an HTTP status with a JSON body of `code`, `cause` and `fix`: 404 `not_found` for another path, 405 `method_not_allowed` for a method other than `GET`, 401 `bad_credential` for an `Authorization` header that is not `Bearer` and 64 lowercase hex digits, 431 `bad_upgrade` for a head that is too long, and 400 `bad_upgrade` for anything else. A secret of the right form that is wrong, and an id the relay does not know, pass the upgrade: hello is answered with a `bye` (step 6).

2. Send hello, and nothing more until the answer:

```json
{"t":"hello","device":"<deviceId>","agent":"myapp/1.0","maxStreams":8}
```

The answer is a welcome, `{"t":"welcome","window":<bytes>,"keepalive":<seconds>}`, or a `bye` (step 6).

3. Serve each open. The relay sends `{"t":"open","s":<stream>,"host":"<name or address>","port":<port>}`. Resolve a name on the device, check every address it gives and refuse a blocked one (below), connect to the address you checked, then answer `{"t":"opened","s":<stream>}`, or `{"t":"close","s":<stream>,"code":"<code>"}` with `target_blocked`, `dns_failed`, `connect_refused`, `connect_timeout` or `unreachable`. A stream beyond `maxStreams` is answered `too_many_streams`.

4. Carry the bytes. A binary message is the stream id as an unsigned big-endian integer, `00000001` for stream 1, then the data, in both directions. Each direction of a stream may send up to `window` bytes before the other side grants more with `{"t":"credit","s":<stream>,"bytes":<count>}`: grant credit for what you wrote to the target, and send no more than the relay granted you. When the target closes its side send `{"t":"end","s":<stream>}`; when the relay sends `end`, close your side of the target connection. `close` ends a stream at once, either way. A message for a stream that ended is ignored.

5. Answer `{"t":"ping"}` with `{"t":"pong"}`. If nothing arrives for three times `keepalive`, close and connect again.

6. Read every `bye`: `{"t":"bye","code":"..","cause":"..","fix":"..","retryAfter":<seconds>}`. Show `cause` and `fix` to the device's owner, wait `retryAfter` plus a random part up to the same again, then connect again. After a connection lost without a `bye`, wait a random time that doubles with each failure in a row. `bad_message` means a message broke the rules below; `replaced` means a second copy runs with the same id; `bad_credential` means the secret is not this device's. `unknown_id` with a short `retryAfter` means a device enrolled a moment ago has not reached the relay yet, so connect again after it; a withdrawn device's `unknown_id` waits the long hold below.

<!-- facts:begin websocket.limits -->

A text message is at most 1024 bytes. A binary message carries at most 16384 bytes of data after its stream id; more is sent as several messages. `maxStreams` is at most 1024 streams. The upgrade request's head is at most 4096 bytes. A `bye` whose cause must be fixed first says `retryAfter` 900 seconds.
<!-- facts:end websocket.limits -->

Strict input: a text message is one JSON object, with no field its type lacks, no field twice and whole numbers only; anything else ends the connection with `bad_message`. A message type the device does not know, it ignores.

## What a device refuses

Answer `close` `target_blocked`, without connecting, for an address in any of these ranges, given as `host` or found by resolving it: `0.0.0.0/8`, `10.0.0.0/8`, `100.64.0.0/10`, `127.0.0.0/8`, `169.254.0.0/16`, `172.16.0.0/12`, `192.168.0.0/16`, `224.0.0.0/4`, `240.0.0.0/4`, `::`, `::1`, `fc00::/7`, `fe80::/10`, `ff00::/8`, `64:ff9b:1::/48`, and an IPv4 address of those ranges inside `::ffff:0:0/96`, `::/96`, `64:ff9b::/96` or `2002::/16`. The relay refuses such an address itself as well, but a device must not rely on it.

## Read, stop and withdraw

- Read the device's state with its own secret, in the folder of `coronium-device.json` from enrolment. The header goes to curl on its standard input and is kept in no file:

```sh
umask 077
SUPPLY=${SUPPLY:-https://supply.coronium.ai}
cd "${CORONIUM_DIR:-$HOME/coronium}" || exit
jq -r '"Authorization: Bearer \(.deviceSecret)"' coronium-device.json | curl -sS -H @- "$SUPPLY/app/api/devices/$(jq -r .deviceId coronium-device.json)/self" | jq '{deviceId, state, reason, relay}'
```

Expect the device's `state`, one of those in [device states](/guides/device-states.md), and `relay`. Safe to repeat: yes. Signed in, `GET /app/api/devices` lists every device of the account with `status` and `state`.

- Stop sharing by closing the WebSocket, and start again by opening it: the device keeps its id and its secret. `paused` and `private` are the account's own choices, made by a person in the [farmer portal](/farmer); a device's secret cannot undo them.

- Withdraw for good with the device's own secret, only with its owner's word:

```sh
umask 077
SUPPLY=${SUPPLY:-https://supply.coronium.ai}
cd "${CORONIUM_DIR:-$HOME/coronium}" || exit
jq -r '"Authorization: Bearer \(.deviceSecret)"' coronium-device.json | curl -sS -H @- -H 'Content-Type: application/json' -d '{"confirm": true}' "$SUPPLY/app/api/devices/$(jq -r .deviceId coronium-device.json)/self/withdraw"
```

Or signed in, as the account: `POST /app/api/devices/<deviceId>/withdraw` with `{"confirm": true}`, as [update, stop, remove and withdraw](/guides/device-lifecycle.md) shows. Then the relay refuses the device's hello with `unknown_id`.
