# Ports and proxy

> Reach a server inside a sandbox over an authenticated WebSocket, and follow the ports it listens on.

Sandboxes are not reachable from the internet. To talk to a server running inside one, open a proxy socket with your API key. To share it with people, use its [preview URL](https://nanite.run/docs/preview-urls.md).

## Proxy a connection

```http
GET /v1/sandboxes/{name}/proxy    (Upgrade: websocket)
```

The socket carries one TCP connection, made from inside the sandbox. Send the target as the first message, within 10 seconds:

```json
{ "host": "localhost", "port": 8080 }
```

`host` is resolved inside the sandbox, so `localhost` is the sandbox itself. The answer is text:

```json
{ "status": "connected", "target": "localhost:8080" }
```

From then on, binary messages carry the bytes of the connection both ways. When either side closes, the socket closes. If the connection cannot be made, you get `{ "status": "error", "message": "..." }` and the socket closes.

A local port forward in Node, with the `ws` package:

```js
import net from "node:net";
import WebSocket, { createWebSocketStream } from "ws";

net
  .createServer((local) => {
    const ws = new WebSocket("wss://api.nanite.run/v1/sandboxes/agent-1/proxy", {
      headers: { Authorization: `Bearer ${process.env.NANITE_KEY}` },
    });
    ws.once("open", () => ws.send(JSON.stringify({ host: "localhost", port: 8080 })));
    ws.once("message", (answer) => {
      if (JSON.parse(answer.toString()).status !== "connected") return local.destroy();
      const remote = createWebSocketStream(ws);
      local.pipe(remote).pipe(local);
    });
  })
  .listen(8080);
```

An open proxy socket counts as use, so the sandbox stays running while it is open.

## Watch ports

```http
GET /v1/sandboxes/{name}/ports/watch    (Upgrade: websocket)
```

The first message lists the ports listening now:

```json
{
  "type": "port_list",
  "ports": [{ "type": "port_opened", "port": 3000, "address": "0.0.0.0", "pid": 412 }]
}
```

Then one message each time a port opens or closes:

```json
{ "type": "port_opened", "port": 8080, "address": "::", "pid": 530 }
{ "type": "port_closed", "port": 3000, "address": "0.0.0.0", "pid": 412 }
```

Use it to wait for a dev server to come up before you connect to it.
