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:
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:
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 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:
npx tsx run-tsp-relay.ts
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.
How it works
startRelayserves WebSockets at/v1and stores messages in SQLite withnode:sqlite, which is why it needs Node 22.13 or later.port: 0picks a free port; read the real one fromrelay.url.- Clients connect with
RelayTransportfrom trust-core. Each one signs a fresh challenge from the relay with itsdid: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. onStoredshows what an operator can see for each message: sender, recipient, size and time. Never the contents.limitscaps what one sender can queue for one recipient, and the total messages and bytes per recipient. A send over a limit is refused withqueueFull;RelayTransportkeeps the message and retries.
Limits and production notes
- In production, run it behind TLS and set
RELAY_PUBLIC_URL(orpublicUrl) to the exactwss://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.