toip.tools

SDK library · Browser and Node

trust-core

Build signed Trust Task requests, credentials, and sealed messages around an Ed25519 did:key identity. Endpoint sends TSP Direct envelopes; sender and recipient metadata remain visible to a direct transport or relay.

@toip-tools/trust-corev0.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/trust-core

Runtime: Browsers and Node 22.

TypeScriptImport
import { identityFromSeed, seedFrom, resolveDidKey } from "@toip-tools/trust-core";

Usage

Send a request and register its handler

Create an identity with identityFromSeed from a securely generated 32-byte seed, choose a clock, and provide a Transport. Construct an Endpoint for each identity, register handle(spec, handler), then call request(to, spec, payload). The response is a Trust Task document: read its payload. Return a Refusal from a handler to send a signed task error; return undefined for no response.

Connect through a mailbox relay

Construct RelayTransport({ url, identity, outbox }), call start(), and pass it to Endpoint. The URL must match the relay's advertised authentication URL exactly. Observe onStatus and inspect pending() for local outbox state. notify returns a delivery status; queued means the transport retained or handed off the message, while only a request response confirms application processing.

Verify a credential and retain replay protection

Use issueCredential to sign VC-shaped claims and verifyCredential to check their proof and validity window. Check revocation separately with checkStatus. For an endpoint that must remember executed requests across restarts, supply PersistentReplayGuard backed by a durable ReplayStore; await ready() to observe initialization failures before serving traffic.

Example

Two endpoints exchange a signed, encrypted Trust Task over the in-memory Bus.

TypeScriptsite/examples/snippets/trust-core.ts
import { Bus, Endpoint, Refusal, SystemClock, identityFromSeed, ourSpec } from "@toip-tools/trust-core";

const clock = new SystemClock();
const bus = new Bus(clock);
const random = () => crypto.getRandomValues(new Uint8Array(32));
const shop = new Endpoint({ identity: identityFromSeed(random()), transport: bus, clock });
const customer = new Endpoint({ identity: identityFromSeed(random()), transport: bus, clock });

// ourSpec("x") is https://toip.tools/spec/x/0.1: signed, addressed, timestamped.
const QUOTE = ourSpec("example/quote");

shop.handle<{ item: string }, { cents: number }>(QUOTE, (doc) =>
  doc.payload.item === "bike tune-up" ? { cents: 4500 } : new Refusal("unknownItem", `no price for ${doc.payload.item}`),
);

const reply = await customer.request<{ item: string }, { cents: number }>(shop.vid, QUOTE, { item: "bike tune-up" });
console.log(reply.payload.cents, "signed by", reply.issuer === shop.vid ? "the shop" : "someone else");
ShellRun from the repository root
npx tsx --tsconfig site/tsconfig.json site/examples/snippets/trust-core.ts
OutputRecorded output
4500 signed by the shop

Lifecycle and persistence

  • Keep identity seeds and secret keys in application-managed protected storage. seedFrom(label) is deterministic and intended for reproducible identities; it does not add entropy to a guessable label.

  • Call Endpoint.close() to detach its receiver, clear request timers, and reject pending requests with TaskError code closed. Stop a separately owned RelayTransport with stop() and invoke unsubscribe callbacks from status or clock subscriptions.

  • Relay outboxes and endpoint replay records are in memory unless you supply stores. Persist both where restarts must retain pending sends and duplicate-execution history; a replay guard's finite capacity can evict records.

Error handling

TaskError: timeout / undelivered / closed

A request rejects when its reply deadline expires, the destination cannot be resolved or reached, or the endpoint closes. A queued message may still arrive after a timeout.

Catch TaskError and inspect code. Reconcile uncertain outcomes before issuing a new action; use a longer per-request timeoutMs for slow transports.

TaskError: proofInvalid / remote refusal code

An invalid response proof rejects with proofInvalid; signed task errors reject with the remote payload's code, including unsupportedType for an unregistered request type.

Reject untrusted responses and register the correct spec handler. Treat application refusal codes according to the receiving service's contract.

CredentialCheck: ok false

Credential verification reports signatureInvalid, issuerMismatch, malformedProof, notYetValid, or expired through failure.

Branch on ok before using claims. Obtain a valid credential or correct clock/issuer configuration; proof validity alone does not establish revocation status or application authorization.

Limitations

  • Resolving DID methods other than Ed25519 did:key. There is no resolver and no network lookup.

  • Keys that must stay in WebCrypto or a secure element. The libraries need raw key bytes.

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.