toip.tools

Quickstart

Create two identities, send a private message, and verify a credential. Four runnable examples, about ten minutes.

Before you start

You'll need Node 22.13 or later. Every part of this tutorial runs on your machine, including the relay, so you can start without creating an account or setting up a remote server.

In a new project, install the two libraries the tutorial uses and a TypeScript runner. Save each step's code as a .ts file and run it with npx tsx:

ShellA new project
mkdir hello-toip && cd hello-toip
npm init -y && npm pkg set type=module
npm install @toip-tools/trust-core @toip-tools/relay tsx
npx tsx 01-identities.ts

Or clone the repository, where the four steps are already written:

ShellFrom the source
git clone https://github.com/yourbuddyconner/toip-tools.git
cd toip-tools
npm install
npm install --prefix site

If you cloned, run the commands below from the repository root. The examples import libraries from packages/ using names such as @toip-tools/trust-core. The --tsconfig option points to the configuration that resolves those names to the local source.

Step 1: Create two identities

Alice and Bob each create a key pair. Their identifiers use did:key, which encodes the public key in the identifier itself. Anyone with the identifier can recover the public key without consulting a registry.

TypeScriptsite/examples/quickstart/01-identities.ts
// Step 1: two identities.
// Run from the repository root:
//   npx tsx --tsconfig site/tsconfig.json site/examples/quickstart/01-identities.ts
import { identityFromSeed, resolveDidKey, seedFrom } from "@toip-tools/trust-core";

const hex = (b: Uint8Array) => Buffer.from(b).toString("hex");

// An identity is a 32-byte seed. In an app, use random bytes:
//   identityFromSeed(crypto.getRandomValues(new Uint8Array(32)))
// Here a label makes the seed, so every run gives the same two DIDs.
const alice = identityFromSeed(seedFrom("quickstart/alice"));
const bob = identityFromSeed(seedFrom("quickstart/bob"));

console.log("Alice:", alice.did);
console.log("Bob:  ", bob.did);

// A did:key is its public key, written out. Anyone holding Bob's DID can get his keys from it,
// with no registry and no network call.
const keys = resolveDidKey(bob.did);
console.log("\nFrom Bob's DID alone:");
console.log("  signing key (Ed25519)   ", hex(keys.signingKey));
console.log("  encryption key (X25519) ", hex(keys.encryptionKey));

// The secret halves never leave the device that made them.
console.log("\nBob's own copy matches:", hex(keys.signingKey) === hex(bob.signingPublic) && hex(keys.encryptionKey) === hex(bob.encryptionPublic));

Run it from the repository root:

ShellTerminal
npx tsx --tsconfig site/tsconfig.json site/examples/quickstart/01-identities.ts
OutputRecorded output
Alice: did:key:z6MkfkozPjJQsb11Szt73tYJ4Aei2YtVxWTfXFYx7EK5WuZc
Bob:   did:key:z6MkoY1PFBAyArzd3VNEApZP3FVuMeydxTym4435r5zJ1aCu

From Bob's DID alone:
  signing key (Ed25519)    86f0824c87e296419f0fa86874a1b043fe48b9524bb7f38e91cd525b4206fa86
  encryption key (X25519)  f22e3a495e5a442377a9525865cef77d1dd6e84b8b3e99ab87aad85d8e045c34

Bob's own copy matches: true

The toolkit derives an X25519 encryption key from each Ed25519 signing key. One DID gives Alice what she needs to verify Bob's signatures and encrypt a message for him.

Step 2: Send a Trust Task

A Trust Task is a signed JSON document describing one interaction. It names the task type, issuer, recipient, timestamp, and payload. Alice's Endpoint wraps it in a signed, encrypted TSP Direct message for Bob. For now, they use a Bus: an in-memory transport that lets you inspect what the network sees.

TypeScriptsite/examples/quickstart/02-trust-task.ts
// Step 2: a signed, encrypted Trust Task from Alice to Bob, over an in-memory network.
// Run from the repository root:
//   npx tsx --tsconfig site/tsconfig.json site/examples/quickstart/02-trust-task.ts
import { Bus, Endpoint, SystemClock, identityFromSeed, seedFrom } from "@toip-tools/trust-core";

const short = (did: string) => `${did.slice(0, 14)}…${did.slice(-4)}`;
const clock = new SystemClock();

// The Bus delivers sealed bytes by DID and lets us watch the wire. Step 3 swaps it for the relay.
const bus = new Bus(clock);
const alice = new Endpoint({ identity: identityFromSeed(seedFrom("quickstart/alice")), transport: bus, clock });
const bob = new Endpoint({ identity: identityFromSeed(seedFrom("quickstart/bob")), transport: bus, clock });

// A message type is a URI you control, plus what a receiver demands of every message of that type.
const HELLO = {
  typeUri: "https://example.org/spec/quickstart/hello/0.1",
  isBearer: false, // addressed to one recipient, not usable by whoever holds it
  isProofRequired: true, // must carry the sender's signature
  isRecipientRequired: true,
  isIssuedAtRequired: true,
};

// Bob's handler runs only after the message decrypts, its signature verifies against the
// sender's DID, it is addressed to Bob, it is fresh, and it is not a replay.
bob.handle<{ text: string }, { reply: string }>(HELLO, (doc, { sender }) => {
  console.log(`Bob opened ${doc.type}`);
  console.log(`  from ${short(sender)}, signed with ${doc.proof?.cryptosuite}`);
  console.log(`  says: "${doc.payload.text}"`);
  return { reply: "Hi Alice. Your signature checks out." };
});

const answer = await alice.request<{ text: string }, { reply: string }>(bob.vid, HELLO, { text: "Hello Bob, it's Alice." });
console.log(`Alice got a reply of type ${answer.type.split("/spec/")[1]}`);
console.log(`  "${answer.payload.reply}"`);

// What anyone watching the network saw: who, to whom, how big. Not the contents.
console.log("\nOn the wire:");
for (const r of bus.records()) console.log(`  #${r.seq} ${short(r.from)} -> ${short(r.to)}  ${r.bytes} bytes  …${r.head.slice(-16)}`);

// Flip one bit of Alice's message and send it again. Bob's TSP layer refuses it before any handler runs.
const forged = bus.records()[0].raw.slice();
forged[forged.length - 40] ^= 0x01;
const rec = bus.send(alice.vid, bob.vid, forged);
await bus.settle();
console.log(`\nA copy with one bit flipped: refused (${rec.refused})`);

Run it from the repository root:

ShellTerminal
npx tsx --tsconfig site/tsconfig.json site/examples/quickstart/02-trust-task.ts
OutputRecorded output
Bob opened https://example.org/spec/quickstart/hello/0.1
  from did:key:z6Mkfk…WuZc, signed with eddsa-jcs-2022
  says: "Hello Bob, it's Alice."
Alice got a reply of type quickstart/hello/0.1#response
  "Hi Alice. Your signature checks out."

On the wire:
  #1 did:key:z6Mkfk…WuZc -> did:key:z6MkoY…1aCu  1038 bytes  …f7585c230a80430f
  #2 did:key:z6MkoY…1aCu -> did:key:z6Mkfk…WuZc  1122 bytes  …15a9315e8fec9b0d

A copy with one bit flipped: refused (tsp: notForThisReceiver: Error: tsp: signature verification failed)

Bob checks the sender's signature against Alice's DID. The network sees the two identifiers and the message sizes, but cannot read the contents. When the example tampers with a message, signature verification fails and Bob's handler never receives it.

Bob's reply is signed too, with #response appended to the task type. A handler can return new Refusal(code, message) to decline a request. That refusal travels back as a signed response, and request() throws a TaskError.

Step 3: Deliver a message while Bob is offline

Alice and Bob won't always be online together. A relay holds encrypted messages until the recipient connects and acknowledges delivery. Replace the Bus with RelayTransport to use that mailbox; the Trust Task handlers stay the same.

TypeScriptsite/examples/quickstart/03-relay.ts
// Step 3: the same kind of message over a real relay, to someone who is offline.
// Run from the repository root:
//   npx tsx --tsconfig site/tsconfig.json site/examples/quickstart/03-relay.ts
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { startRelay } from "@toip-tools/relay";
import { Endpoint, RelayTransport, SystemClock, identityFromSeed, seedFrom, type Identity } from "@toip-tools/trust-core";

const short = (did: string) => `${did.slice(0, 14)}…${did.slice(-4)}`;
const clock = new SystemClock();

// A mailbox relay on a free port. It stores sealed messages until their recipient collects them.
const dir = mkdtempSync(join(tmpdir(), "quickstart-relay-"));
const relay = await startRelay({ port: 0, host: "127.0.0.1", dbPath: join(dir, "relay.db") });
console.log(`Relay listening at ${relay.url}`);

// Each device signs in to the relay as its own did:key, by signing a challenge.
function connect(identity: Identity) {
  const transport = new RelayTransport({ url: relay.url, identity });
  const online = new Promise<void>((resolve) => transport.onStatus((s) => s === "connected" && resolve()));
  transport.start();
  return { transport, online };
}

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

const aliceId = identityFromSeed(seedFrom("quickstart/alice"));
const bobId = identityFromSeed(seedFrom("quickstart/bob"));

// Alice comes online. Bob doesn't.
const a = connect(aliceId);
const alice = new Endpoint({ identity: aliceId, transport: a.transport, clock });
await a.online;
console.log(`Alice connected as ${short(alice.vid)}`);

// notify() is one-way: no reply expected, so it works when Bob is away.
const delivery = await alice.notify(bobId.did, NOTE, { text: "Dinner at 7? Bring the bread." });
console.log(`Alice sent a note: ${delivery}. Waiting at the relay for Bob: ${relay.queued(bobId.did)}`);

// Later, Bob comes online and collects it.
const b = connect(bobId);
const bob = new Endpoint({ identity: bobId, transport: b.transport, clock });
const received = new Promise<string>((resolve) => {
  bob.handle<{ text: string }, void>(NOTE, (doc, { sender }) => resolve(`from ${short(sender)}: "${doc.payload.text}"`));
});
await b.online;
console.log(`Bob connected as ${short(bob.vid)}`);
console.log(`Bob opened a note ${await received}`);

// Bob acknowledges after his handler finishes; then the relay deletes its copy.
await new Promise((r) => setTimeout(r, 100));
console.log(`Waiting at the relay for Bob: ${relay.queued(bobId.did)}`);
console.log("The relay saw who wrote to whom, when, and how many bytes. It could not read the note.");

alice.close();
bob.close();
a.transport.stop();
b.transport.stop();
await relay.close();
rmSync(dir, { recursive: true, force: true });

Run it from the repository root:

ShellTerminal
npx tsx --tsconfig site/tsconfig.json site/examples/quickstart/03-relay.ts
OutputRecorded output
Relay listening at ws://127.0.0.1:57514/v1
Alice connected as did:key:z6Mkfk…WuZc
Alice sent a note: queued. Waiting at the relay for Bob: 1
Bob connected as did:key:z6MkoY…1aCu
Bob opened a note from did:key:z6Mkfk…WuZc: "Dinner at 7? Bring the bread."
Waiting at the relay for Bob: 0
The relay saw who wrote to whom, when, and how many bytes. It could not read the note.

Each device authenticates by signing a challenge from the relay. The relay uses node:sqlite; Node may print an ExperimentalWarning when it starts.

To host a relay, run npm start --workspace packages/relay behind TLS. Set RELAY_PUBLIC_URL to the exact URL clients use: that URL is part of the authentication challenge they sign.

Step 4: Present a credential, then revoke it

A community garden issues Bob a membership credential: a signed statement in the W3C Verifiable Credentials shape, linked to an entry in the garden's status list. Bob sends it to Alice in a Trust Task. She checks the garden's signature, confirms the credential belongs to Bob, and checks whether it has been revoked.

TypeScriptsite/examples/quickstart/04-credentials.ts
// Step 4: a credential, presented in a Trust Task, verified, then revoked.
// Run from the repository root:
//   npx tsx --tsconfig site/tsconfig.json site/examples/quickstart/04-credentials.ts
import {
  Bus,
  Endpoint,
  StatusList,
  SystemClock,
  checkStatus,
  identityFromSeed,
  issueCredential,
  seedFrom,
  verifyCredential,
  type Credential,
} from "@toip-tools/trust-core";

const short = (did: string) => `${did.slice(0, 14)}…${did.slice(-4)}`;
const clock = new SystemClock();

// A third party: a community garden that vouches for its members.
const garden = identityFromSeed(seedFrom("quickstart/garden"));
const aliceId = identityFromSeed(seedFrom("quickstart/alice"));
const bobId = identityFromSeed(seedFrom("quickstart/bob"));

// The garden keeps a status list: one bit per credential it has issued. A set bit means revoked.
const statusList = new StatusList();
const slot = statusList.allocate();

const membership = issueCredential(garden, clock, {
  type: ["VerifiableCredential", "MembershipCredential"],
  credentialSubject: { id: bobId.did, memberOf: "Riverside Community Garden", plot: "B-12" },
  validUntil: new Date(clock.now() + 365 * 24 * 3600_000).toISOString(),
  credentialStatus: { type: "BitstringStatusListEntry", statusListIndex: slot, statusListCredential: `${garden.did}#status` },
});
console.log(`The garden issued Bob a ${membership.type[1]}, signed with ${membership.proof?.cryptosuite}.`);

// The garden publishes its signed list wherever verifiers can fetch it. Here, a variable.
let published = statusList.sign(garden, clock);

// Alice lends tools to garden members. She checks the credential Bob presents.
const bus = new Bus(clock);
const alice = new Endpoint({ identity: aliceId, transport: bus, clock });
const bob = new Endpoint({ identity: bobId, transport: bus, clock });

const BORROW = {
  typeUri: "https://example.org/spec/quickstart/borrow/0.1",
  isBearer: false,
  isProofRequired: true,
  isRecipientRequired: true,
  isIssuedAtRequired: true,
};

alice.handle<{ tool: string; credential: Credential }, { lent: boolean; why: string }>(BORROW, async (doc, { sender }) => {
  const vc = doc.payload.credential;
  const check = await verifyCredential(vc, clock);
  if (!check.ok) return { lent: false, why: `credential ${check.failure}` };
  if (vc.issuer !== garden.did) return { lent: false, why: "not issued by the garden" };
  if (vc.credentialSubject.id !== sender) return { lent: false, why: "credential is about someone else" };
  const status = await checkStatus(published, vc.credentialStatus!.statusListIndex, garden.did, clock);
  if (!status.signatureValid) return { lent: false, why: "status list not signed by the garden" };
  if (status.revoked) return { lent: false, why: "membership revoked" };
  return { lent: true, why: `member of ${vc.credentialSubject.memberOf}` };
});

async function ask(tool: string, credential: Credential) {
  const r = await bob.request<{ tool: string; credential: Credential }, { lent: boolean; why: string }>(alice.vid, BORROW, { tool, credential });
  console.log(`  Bob asks for the ${tool}: ${r.payload.lent ? "lent" : "refused"} (${r.payload.why})`);
}

console.log(`\nBob (${short(bobId.did)}) asks Alice (${short(aliceId.did)}):`);
await ask("wheelbarrow", membership);

// Change one claim and the issuer's signature no longer matches.
await ask("shears", { ...membership, credentialSubject: { ...membership.credentialSubject, plot: "A-01" } });

// The garden revokes Bob's membership: set his bit, sign the list again, publish it.
statusList.revoke(slot);
published = statusList.sign(garden, clock);
console.log("\nThe garden revokes slot", slot, "and publishes a new list.");
await ask("wheelbarrow", membership);

Run it from the repository root:

ShellTerminal
npx tsx --tsconfig site/tsconfig.json site/examples/quickstart/04-credentials.ts
OutputRecorded output
The garden issued Bob a MembershipCredential, signed with eddsa-jcs-2022.

Bob (did:key:z6MkoY…1aCu) asks Alice (did:key:z6Mkfk…WuZc):
  Bob asks for the wheelbarrow: lent (member of Riverside Community Garden)
  Bob asks for the shears: refused (credential signatureInvalid)

The garden revokes slot 0 and publishes a new list.
  Bob asks for the wheelbarrow: refused (membership revoked)

Alice verifies the credential using the garden's trusted DID and its latest signed status list. The list can be hosted anywhere; its signature lets her detect changes. In the example, altering a claim invalidates the credential, and updating one status bit revokes Bob's membership.

Keep building

You created identities, exchanged signed and encrypted messages, delivered one through a relay, and verified a revocable credential. The relay handled delivery; Alice and Bob checked the messages and claims themselves.

  • Understand the protocols in Concepts, with diagrams and links to the specifications.
  • Find your next building block in the toolkit: try delegation or verifiable audit trails.
  • See a complete app in Settle, where Trust Tasks coordinate conditional payments. Start it with npm run settle.
  • Run all four steps at once from site/ with npm install and npm run quickstart.