toip.tools

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/relayv0.1.0Source

Setup

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

ShellInstall
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.

TypeScriptImport
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.

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.

Example

Run a relay, and connect an endpoint to it.

TypeScriptsite/examples/snippets/relay.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);
ShellRun from the repository root
npx tsx --tsconfig site/tsconfig.json site/examples/snippets/relay.ts
OutputRecorded output
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.