SDK library · Node only

# relay

Run a Node WebSocket mailbox for opaque sealed messages. The relay authenticates Ed25519 `did:key` clients and stores messages in SQLite until recipient acknowledgement or expiry. It sees sender, recipient, time, and message size.

`@toip-tools/relay` · v0.1.0 · [Source](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/relay/src/server.ts)

## Setup

Install the package from npm. It needs Node 22.13 or later, or a bundler for browser entry points.

Install:

```bash
npm install @toip-tools/relay
```

**Runtime:** Node 22.13 or later (it uses \`node:sqlite\`). Clients use \`RelayTransport\` from trust-core, in browsers or Node.

Import:

```ts
import { startRelay, type Relay, type RelayOptions } from "@toip-tools/relay";
```

## Usage

### Start a durable mailbox

Call `startRelay({ port, host, dbPath, publicUrl })` with an application-owned SQLite path. Use `port: 0` for an assigned local port and read the returned `port` and `url`. Set `publicUrl` to the exact externally reachable WebSocket URL when a proxy changes the address; clients sign that URL during authentication. The WebSocket route is `/v1`.

[`startRelay`](https://toip.tools/toolkit/relay/api/startRelay/) · [`RelayOptions`](https://toip.tools/toolkit/relay/api/RelayOptions/) · [`Relay`](https://toip.tools/toolkit/relay/api/Relay/)

### Bound recipient queues and observe acceptance

Override `limits` to cap messages per sender/recipient, total recipient messages, recipient bytes, authentication timeout, and the unacknowledged delivery window. Use `queued(did)` to count stored messages and `onStored` to observe each accepted message's metadata. A `live` acceptance still remains stored until the recipient acknowledges it.

[`RelayLimits`](https://toip.tools/toolkit/relay/api/RelayLimits/) · [`StoredMessage`](https://toip.tools/toolkit/relay/api/StoredMessage/) · [`MAX_MESSAGE_BYTES`](https://toip.tools/toolkit/relay/api/MAX_MESSAGE_BYTES/) · [`MAX_QUEUED_PER_RECIPIENT`](https://toip.tools/toolkit/relay/api/MAX_QUEUED_PER_RECIPIENT/)

## Example

Run a relay, and connect an endpoint to it.

site/examples/snippets/relay.ts:

```ts
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { startRelay } from "@toip-tools/relay";
import { Endpoint, RelayTransport, SystemClock, identityFromSeed } from "@toip-tools/trust-core";

const relay = await startRelay({
  port: 0, // any free port; 8787 is the repo's default
  host: "127.0.0.1",
  dbPath: join(mkdtempSync(join(tmpdir(), "relay-")), "relay.db"),
  log: (line) => console.log("[relay]", line),
});

const identity = identityFromSeed(crypto.getRandomValues(new Uint8Array(32)));
const transport = new RelayTransport({ url: relay.url, identity });
transport.onStatus((s) => console.log("relay status:", s));
transport.start();
const me = new Endpoint({ identity, transport, clock: new SystemClock() });

console.log(`${me.vid} uses ${relay.url}; ${transport.pending()} messages waiting to send`);
setTimeout(async () => {
  transport.stop();
  await relay.close();
}, 300);
```

Run from the repository root:

```bash
npx tsx --tsconfig site/tsconfig.json site/examples/snippets/relay.ts
```

Output:

```text
relay status: connecting
did:key:z6MkscDhUgBS3z1j4URFUu6nSfGKggkFNAmWMerzsstrxCTQ uses ws://127.0.0.1:57517/v1; 0 messages waiting to send
[relay] connected did:key:z6MkscDhUgBS…
relay status: connected
relay status: offline
```

## Lifecycle and persistence

- Await `Relay.close()` during shutdown. It stops the expiry interval, terminates sockets, closes the WebSocket server, and closes SQLite. The caller owns the database path, backup strategy, and deployment's TLS/proxy configuration.

- The queue survives a process restart when `dbPath` names a persistent file. Messages expire after `QUEUE_TTL_MS` (30 days); expiry runs at startup and hourly. Acknowledged messages are deleted.

- One active connection is retained per DID. A newer authenticated connection closes the previous one with WebSocket code 4002; clients should coordinate multiple tabs or processes using the same identity.

## Error handling

### `auth`

Protocol error frames report missing, repeated, or invalid authentication. An invalid signature closes the socket with code 4001; unauthenticated sockets also have a deadline.

Use the identity matching the claimed DID and sign the relay's fresh challenge with its exact public URL. Correct URL/proxy configuration before reconnecting.

### `queueFull`

A send is refused when any configured recipient queue limit would be exceeded. The error frame includes the send's `cid` when provided.

Retain the sealed message and retry after the recipient drains its mailbox. Trust-core's `RelayTransport` already retains these messages and schedules a retry.

### `malformed / tooLarge`

Bad JSON, unknown frames, invalid recipients, empty wire data, and oversized wire data are refused. Decoded messages may not exceed `MAX_MESSAGE_BYTES` (256 KiB).

Correct the frame or recipient and reduce oversized payloads before resending. Catch startup rejection separately for database or socket-listen failures.

### Limitations

- Hiding who talks to whom. The relay learns which DIDs connect, who messages whom, when and how much.

## API reference

Choose an entry point for the complete export list. Each export has a reference page with its signature, parameter types, return type, fields, and public methods where applicable.

- [`@toip-tools/relay`](https://toip.tools/toolkit/relay/api/)

  Node only · 8 exports

## Related

### Guides

- [Run a TSP relay: a mailbox for encrypted messages](https://toip.tools/guides/run-tsp-relay/)

### Built on

- [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/): Identities, signed and encrypted Trust Tasks over TSP, credentials, status lists and local policy.

### Used by these examples

- [Settle](https://toip.tools/examples/#settle): Conditional payments with shared control of escrow.
- [Shared To-Do](https://toip.tools/examples/#shared-todo): Private to-do lists for a household.
- [Tipline](https://toip.tools/examples/#tipline): A drop box that lets sources prove membership without revealing their identity.
- [Agora](https://toip.tools/examples/#agora): Anonymous forums with verified membership.
- [Agents](https://toip.tools/examples/#agents): AI agents with identities, spending limits, and accountable actions.

### Concepts

[Concepts](https://toip.tools/concepts/) explains the protocols behind relay; the [FAQ](https://toip.tools/faq/) covers install, runtimes and support.

---

This is the Markdown version of https://toip.tools/toolkit/relay/. An index of the documentation for AI assistants is at https://toip.tools/llms.txt.
