Guide · `@toip-tools/relay`, `@toip-tools/trust-core`

# Run a TSP relay: a mailbox for encrypted messages

Run a WebSocket mailbox that stores sealed TSP messages in SQLite until the recipient connects, survives restarts, and sees only metadata.

People and devices are rarely online at the same time. A relay holds encrypted messages for a recipient until it connects and acknowledges them. It can't read them: they are sealed to the recipient's key before they reach it.

To run one from the command line:

Terminal:

```bash
npx @toip-tools/relay
```

It listens on port 8787 and keeps its queue in `./relay.db`. Set `PORT`, `HOST`, `RELAY_DB` and `RELAY_PUBLIC_URL` to change that. The program below starts a relay in code instead, leaves a note for an offline recipient, restarts the relay on the same database, and delivers the note when the recipient connects.

## Before you start

You need Node 22.13 or later. In a new folder, install the packages and `tsx`, a TypeScript runner:

Terminal:

```bash
mkdir run-tsp-relay && cd run-tsp-relay
npm init -y && npm pkg set type=module
npm install @toip-tools/relay @toip-tools/trust-core tsx
```

## The code

Save this as `run-tsp-relay.ts`. It is the complete program; the site's checks run it on every build.

run-tsp-relay.ts:

```ts
// Run a TSP mailbox relay in Node: it stores sealed messages in SQLite until the recipient connects,
// survives a restart, and shows its operator only metadata.
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { startRelay, type StoredMessage } from "@toip-tools/relay";
import { Endpoint, RelayTransport, SystemClock, identityFromSeed, type Identity } from "@toip-tools/trust-core";

const clock = new SystemClock();
const dir = mkdtempSync(join(tmpdir(), "relay-guide-"));
const dbPath = join(dir, "relay.db"); // in production, a persistent file you back up

const short = (did: string) => `${did.slice(8, 16)}…`;
const options = {
  port: 0, // any free port; npx @toip-tools/relay defaults to 8787
  host: "127.0.0.1",
  dbPath,
  limits: { perSenderPerRecipient: 100 }, // at most 100 messages waiting from one sender to one recipient
  onStored: (m: StoredMessage) =>
    console.log(`[relay] ${short(m.from)} -> ${short(m.to)}: ${m.bytes} bytes, ${m.delivery}`),
};

function connect(identity: Identity, url: string) {
  const transport = new RelayTransport({ url, identity });
  const online = new Promise<void>((resolve) => transport.onStatus((s) => s === "connected" && resolve()));
  transport.start();
  return { transport, online, endpoint: new Endpoint({ identity, transport, clock }) };
}

const NOTE = {
  typeUri: "https://example.org/spec/notes/note/0.1",
  isBearer: false,
  isProofRequired: true,
  isRecipientRequired: true,
  isIssuedAtRequired: true,
};

const alice = identityFromSeed(crypto.getRandomValues(new Uint8Array(32)));
const bob = identityFromSeed(crypto.getRandomValues(new Uint8Array(32)));

// Alice connects and leaves a note for Bob, who is offline.
let relay = await startRelay(options);
console.log("Relay at", relay.url);
const a = connect(alice, relay.url);
await a.online;
console.log("Alice sent:", await a.endpoint.notify(bob.did, NOTE, { text: "Back at 6." }));
console.log("Waiting for Bob:", relay.queued(bob.did));
a.endpoint.close();
a.transport.stop();

// Restart the relay on the same database. The note is still there.
await relay.close();
relay = await startRelay(options);
console.log("Restarted; waiting for Bob:", relay.queued(bob.did));

// Bob connects (signing the relay's challenge with his did:key) and the relay delivers.
const b = connect(bob, relay.url);
const got = new Promise<string>((resolve) => b.endpoint.handle<{ text: string }, void>(NOTE, (doc) => resolve(doc.payload.text)));
await b.online;
console.log("Bob read:", await got);
await new Promise((r) => setTimeout(r, 100)); // Bob's acknowledgement reaches the relay, which deletes its copy
console.log("Waiting for Bob:", relay.queued(bob.did));

b.endpoint.close();
b.transport.stop();
await relay.close();
rmSync(dir, { recursive: true, force: true });
```

Run it:

Terminal:

```bash
npx tsx run-tsp-relay.ts
```

Output:

```text
Relay at ws://127.0.0.1:60693/v1
[relay] z6MkuaXR… -> z6MkpDnq…: 1020 bytes, queued
Alice sent: queued
Waiting for Bob: 1
Restarted; waiting for Bob: 1
Bob read: Back at 6.
Waiting for Bob: 0
```

Keys are random, so identifiers and sizes differ on each run. From a clone of the repository, run `npx tsx --tsconfig site/tsconfig.json site/examples/guides/run-tsp-relay.ts`, or read it in [`site/examples/guides/run-tsp-relay.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/site/examples/guides/run-tsp-relay.ts).

## How it works

- `startRelay` serves WebSockets at `/v1` and stores messages in SQLite with `node:sqlite`, which is why it needs Node 22.13 or later. `port: 0` picks a free port; read the real one from `relay.url`.
- Clients connect with `RelayTransport` from trust-core. Each one signs a fresh challenge from the relay with its `did:key`, bound to the relay's URL, so the relay knows which mailbox is whose.
- A message to a connected recipient goes out at once (`live`); otherwise it waits (`queued`). Either way the relay keeps it until the recipient acknowledges it, and deletes it then. Unacknowledged messages expire after 30 days.
- `onStored` shows what an operator can see for each message: sender, recipient, size and time. Never the contents.
- `limits` caps what one sender can queue for one recipient, and the total messages and bytes per recipient. A send over a limit is refused with `queueFull`; `RelayTransport` keeps the message and retries.

## Limits and production notes

- In production, run it behind TLS and set `RELAY_PUBLIC_URL` (or `publicUrl`) to the exact `wss://` URL clients use: the URL is part of what they sign.
- The relay learns who talks to whom, when, and how much. It delivers TSP Direct messages and does not implement TSP Routed mode.
- Keep one connection per DID. A newer connection for the same DID closes the older one.

## Related

### API used

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

[`RelayTransport`](https://toip.tools/toolkit/trust-core/api/RelayTransport/) · [`Endpoint`](https://toip.tools/toolkit/trust-core/api/Endpoint/)

### Libraries

- [`@toip-tools/relay`](https://toip.tools/toolkit/relay/): A WebSocket mailbox that stores and delivers encrypted TSP messages.
- [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/): Identities, signed and encrypted Trust Tasks over TSP, credentials, status lists and local policy.

### Concepts

- [The Trust Spanning Protocol](https://toip.tools/concepts/#tsp)

### More guides

- [Send an end-to-end encrypted message with TSP (the Trust Spanning Protocol)](https://toip.tools/guides/tsp-encrypted-message/)
- [Send Trust Tasks over LoRa radio](https://toip.tools/guides/trust-tasks-over-lora/)

---

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