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-core` · v0.1.0 · [Source](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/trust-core/src/index.ts)

## Setup

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

Install:

```bash
npm install @toip-tools/trust-core
```

**Runtime:** Browsers and Node 22.

Import:

```ts
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.

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

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

[`RelayTransport`](https://toip.tools/toolkit/trust-core/api/RelayTransport/) · [`OutboxStore`](https://toip.tools/toolkit/trust-core/api/OutboxStore/) · [`Endpoint`](https://toip.tools/toolkit/trust-core/api/Endpoint/) · [`Delivery`](https://toip.tools/toolkit/trust-core/api/Delivery/)

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

[`issueCredential`](https://toip.tools/toolkit/trust-core/api/issueCredential/) · [`verifyCredential`](https://toip.tools/toolkit/trust-core/api/verifyCredential/) · [`checkStatus`](https://toip.tools/toolkit/trust-core/api/checkStatus/) · [`PersistentReplayGuard`](https://toip.tools/toolkit/trust-core/api/PersistentReplayGuard/) · [`ReplayStore`](https://toip.tools/toolkit/trust-core/api/ReplayStore/)

## Example

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

site/examples/snippets/trust-core.ts:

```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");
```

Run from the repository root:

```bash
npx tsx --tsconfig site/tsconfig.json site/examples/snippets/trust-core.ts
```

Output:

```text
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.

- [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/api/)

  Browser and Node · 63 exports

## Related

### Guides

- [Create a did:key and sign a JSON document in TypeScript](https://toip.tools/guides/did-key-sign-document/)
- [Issue and verify a W3C verifiable credential in TypeScript](https://toip.tools/guides/issue-verify-credential/)
- [Revoke a verifiable credential with a status list](https://toip.tools/guides/revoke-credential-status-list/)
- [Send an end-to-end encrypted message with TSP (the Trust Spanning Protocol)](https://toip.tools/guides/tsp-encrypted-message/)
- [Run a TSP relay: a mailbox for encrypted messages](https://toip.tools/guides/run-tsp-relay/)
- [Delegate bounded authority to an AI agent with mandates](https://toip.tools/guides/delegate-to-ai-agent/)
- [Keep a tamper-evident audit log with KERI key event logs](https://toip.tools/guides/tamper-evident-audit-log/)
- [Send Trust Tasks over LoRa radio](https://toip.tools/guides/trust-tasks-over-lora/)
- [Prove group membership with zero knowledge (Noir)](https://toip.tools/guides/zero-knowledge-membership/)

### Libraries that build on it

- [`@toip-tools/relay`](https://toip.tools/toolkit/relay/): A WebSocket mailbox that stores and delivers encrypted TSP messages.
- [`@toip-tools/web-vault`](https://toip.tools/toolkit/web-vault/): Browser storage for identity seeds and account data, encrypted with a passkey or passphrase.
- [`@toip-tools/mandates`](https://toip.tools/toolkit/mandates/): Revocable delegation with spending limits, policy checks, and approvals.
- [`@toip-tools/anon-membership`](https://toip.tools/toolkit/anon-membership/): Prove group membership and attribute requirements without revealing which member you are.
- [`@toip-tools/eventlog`](https://toip.tools/toolkit/eventlog/): KERI key histories and witnessed audit trails that make tampering detectable.
- [`@toip-tools/mesh-transport`](https://toip.tools/toolkit/mesh-transport/): Deliver TSP messages over LoRa radio or portable files when the internet is unavailable.

### Used by these examples

- [Settle](https://toip.tools/examples/#settle): Conditional payments with shared control of escrow.
- [Shared To-Do](https://toip.tools/examples/#shared-todo): Private to-do lists for a household.
- [Tipline](https://toip.tools/examples/#tipline): A drop box that lets sources prove membership without revealing their identity.
- [Agora](https://toip.tools/examples/#agora): Anonymous forums with verified membership.
- [Agents](https://toip.tools/examples/#agents): AI agents with identities, spending limits, and accountable actions.
- [Trail](https://toip.tools/examples/#trail): Verifiable audit trails for agents, devices, and services.
- [Capture](https://toip.tools/examples/#capture): Verifiable origins for photos and sensor readings.
- [Mesh](https://toip.tools/examples/#mesh): Trust Tasks beyond an internet connection.

### Concepts

[Concepts](https://toip.tools/concepts/) explains the protocols behind trust-core; the [FAQ](https://toip.tools/faq/) covers install, runtimes and support.

---

This is the Markdown version of https://toip.tools/toolkit/trust-core/. An index of the documentation for AI assistants is at https://toip.tools/llms.txt.
