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

# Send an end-to-end encrypted message with TSP (the Trust Spanning Protocol)

Send a signed, end-to-end encrypted Trust Task with TSP Direct mode between two did:key identities, and see what the network sees.

The Trust Spanning Protocol (TSP), from the Trust over IP Foundation, is a message format for two parties identified by their identifiers (VIDs, here `did:key`s). Each message is signed by the sender and encrypted to the recipient, whatever carries it: a relay, a WebSocket, a radio, a USB stick.

This program sends a one-way message from Alice to Bob over an in-memory network that records every message, then shows what an observer saw and what happens to a message changed in transit.

## Before you start

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

Terminal:

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

## The code

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

tsp-encrypted-message.ts:

```ts
// Send an end-to-end encrypted, signed message with the Trust Spanning Protocol (TSP Direct mode),
// and see what the network sees.
import { Bus, Endpoint, SystemClock, identityFromSeed } from "@toip-tools/trust-core";

const clock = new SystemClock();
const random = () => crypto.getRandomValues(new Uint8Array(32));

// The Bus is an in-memory network that records every message. Swap in RelayTransport for a real one.
const network = new Bus(clock);
const alice = new Endpoint({ identity: identityFromSeed(random()), transport: network, clock });
const bob = new Endpoint({ identity: identityFromSeed(random()), transport: network, clock });

// A message type is a URI you choose, and what every message of that type must carry.
const CHAT = {
  typeUri: "https://example.org/spec/chat/message/0.1",
  isBearer: false, // bound to one recipient
  isProofRequired: true, // signed by the sender
  isRecipientRequired: true,
  isIssuedAtRequired: true,
};

// Bob's handler runs only after the message decrypts, the signature matches the sender's DID,
// it is addressed to Bob, it is recent, and it is not a replay.
const received = new Promise<string>((resolve) =>
  bob.handle<{ text: string }, void>(CHAT, (doc, { sender }) => resolve(`${doc.payload.text} (from ${sender === alice.vid ? "Alice" : sender})`)),
);

// notify() is one-way. Use request() when you want a signed reply.
const delivery = await alice.notify(bob.vid, CHAT, { text: "The key is under the blue pot." });
console.log("Delivery:", delivery);
console.log("Bob read:", await received);

// The network sees who wrote to whom, when, and how many bytes. Not the words.
const [wire] = network.records();
console.log(`On the wire: ${wire.from.slice(0, 16)}… -> ${wire.to.slice(0, 16)}…, ${wire.bytes} bytes`);
console.log("Plaintext visible on the wire:", Buffer.from(wire.raw).includes("blue pot"));

// Change one byte in transit and TSP refuses it before any handler runs.
const forged = wire.raw.slice();
forged[forged.length - 40] ^= 0x01;
const result = network.send(alice.vid, bob.vid, forged);
await network.settle();
console.log("A tampered copy:", result.refused ? `refused (${result.refused})` : "accepted");
```

Run it:

Terminal:

```bash
npx tsx tsp-encrypted-message.ts
```

Output:

```text
Delivery: live
Bob read: The key is under the blue pot. (from Alice)
On the wire: did:key:z6Mkt2JX… -> did:key:z6MkvSkG…, 1041 bytes
Plaintext visible on the wire: false
A tampered copy: refused (tsp: notForThisReceiver: Error: tsp: signature verification failed)
```

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/tsp-encrypted-message.ts`, or read it in [`site/examples/guides/tsp-encrypted-message.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/site/examples/guides/tsp-encrypted-message.ts).

## How it works

- An `Endpoint` wraps a JSON Trust Task document in a TSP Direct message: signed with the sender's Ed25519 key and sealed to the recipient's X25519 key with HPKE. The TSP implementation is the OpenVTC library `@openvtc/vti-tsp-js`.
- A message type is a plain object: it names the type (a URI you choose) and what the receiver demands of every message of that type: a proof, a recipient, a timestamp, and not a bearer token.
- Bob's handler runs only after the message decrypts, the signature matches the sender's DID, it is addressed to Bob, it is fresh, and it hasn't been seen before (replay protection).
- `notify()` is one-way and returns how it was delivered. `request()` waits for a signed reply; a handler can return `new Refusal(code, message)` to send a signed refusal instead.

## Limits and production notes

- TSP Direct mode hides contents, not metadata: the sender's and recipient's identifiers travel in clear, as do size and timing. These libraries use only Direct mode, not TSP Routed mode.
- The `Bus` is for tests and demos. For real delivery, use `RelayTransport` with a relay: see [Run a TSP relay](https://toip.tools/guides/run-tsp-relay/).

## Related

### API used

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

### Libraries

- [`@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)
- [Trust Tasks](https://toip.tools/concepts/#trust-tasks)

### More guides

- [Run a TSP relay: a mailbox for encrypted messages](https://toip.tools/guides/run-tsp-relay/)
- [Send Trust Tasks over LoRa radio](https://toip.tools/guides/trust-tasks-over-lora/)

---

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