# toip.tools: the complete documentation > toip.tools documents @toip-tools, TypeScript libraries on npm for building Trust over IP applications: Ed25519 did:key identities, signed and end-to-end encrypted messages over the Trust Spanning Protocol (TSP), Trust Tasks, W3C VC-shaped credentials with status lists, delegation mandates for AI agents, KERI key event logs, COSE signing, zero-knowledge group membership, and Trust Tasks over LoRa radio. It is an independent project, unaffiliated with the Trust over IP Foundation. - Install from npm: `npm install @toip-tools/trust-core`; every other library builds on it. All packages are at version 0.1.0, ES modules with TypeScript declarations. - Needs Node 22.13 or later. Browser entry points work through a bundler; the relay is Node only. - Identities are Ed25519 `did:key` (and `did:keri` in eventlog). There is no resolver for other DID methods. - TSP is used in Direct mode only, through the OpenVTC library `@openvtc/vti-tsp-js`. - Every page has a Markdown version: add `index.md` to its URL. All of the docs in one file: https://toip.tools/llms-full.txt - Source: https://github.com/yourbuddyconner/toip-tools This file is generated from the site's pages at build time. Each page below is wrapped in a element naming its URL. # Documentation Build with TypeScript libraries for identities, private messages, credentials, delegation, and verifiable logs. Start with the [Quickstart](https://toip.tools/quickstart/) for a complete trust exchange. Use the [SDK reference](https://toip.tools/toolkit/) for imports, examples, and public API declarations, or [Concepts](https://toip.tools/concepts/) for the protocols behind them. ## Setup You'll need Node 22.13 or later. Install the libraries you use from npm. Each is a separate package under `@toip-tools`; start with trust-core, which every other library builds on: Terminal: ```bash npm install @toip-tools/trust-core ``` Add others as you need them, for example `@toip-tools/relay` for a message relay, `@toip-tools/mandates` for delegation, or `@toip-tools/eventlog` for verifiable logs. The [SDK reference](https://toip.tools/toolkit/) lists all of them. The packages are ES modules with TypeScript declarations, and work in Node and, through a bundler, in browsers. To run this site's examples, or to change the libraries, clone the repository instead. Build the packages after installing: Work from the source: ```bash git clone https://github.com/yourbuddyconner/toip-tools.git cd toip-tools npm install npm install --prefix site npm run build ``` From the repository root, run a signed, encrypted request and response over an in-memory transport: Run the trust-core example: ```bash npx tsx --tsconfig site/tsconfig.json site/examples/snippets/trust-core.ts ``` Run all four Quickstart steps, including a local relay and credential revocation: Run the Quickstart: ```bash npm run quickstart --prefix site ``` For coding assistants ## Ask your AI assistant Assistants write better code with the documentation in front of them. Paste this prompt into yours, then describe what you're building. Prompt: ```text I'm building with the @toip-tools TypeScript libraries (on npm, Node 22.13 or later). Before writing code, read https://toip.tools/llms-full.txt: it holds their documentation, guides and Trust Task reference. Use only the exports and options it documents, install packages as @toip-tools/, and tell me if something I ask for isn't supported. My task: ``` [llms-full.txt](https://toip.tools/llms-full.txt) · all docs in one Markdown file · [llms.txt](https://toip.tools/llms.txt) · an index · [JSON indexes](https://toip.tools/api/) · packages, exports and Trust Tasks ## Guides Short how-tos, each one complete program you can run: - [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/) - [Sign and verify COSE messages in TypeScript](https://toip.tools/guides/sign-cose/) - [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/) ## Work from the source The root [`package.json`](https://github.com/yourbuddyconner/toip-tools/blob/main/package.json) lists the libraries in `packages/` and applications in `projects/` as npm workspaces. Installing at the root links local package names such as `@toip-tools/trust-core`, `@toip-tools/mandates`, and `@toip-tools/mesh-transport`. To build an application in this repository, add it to the root workspace list and declare each library it uses as a dependency matching its package manifest. The current [trust-core version](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/trust-core/package.json) is `0.1.0`. Run `npm install` from the root after changing those manifests, then `npm run build` to create the packages' `dist/` JavaScript and type declarations. Standard package imports use those build outputs; the `@toip-tools/source` export condition selects TypeScript source for development. The standalone site examples instead resolve package names through [`site/tsconfig.json`](https://github.com/yourbuddyconner/toip-tools/blob/main/site/tsconfig.json). Its `paths` map public imports to local source; pass that configuration to `tsx` as shown above. Subpath imports, such as `@toip-tools/mesh-transport/sim`, have explicit mappings. These paths apply to this checkout only; in your own project, install the packages from npm. ## Next steps - [Quickstart](https://toip.tools/quickstart/): create identities, exchange Trust Tasks, and verify credentials. - [Guides](https://toip.tools/guides/): one task each, such as signing with a did:key or running a relay. - [FAQ](https://toip.tools/faq/): Trust over IP, TSP, runtimes, and how this project relates to the ToIP Foundation. - [SDK reference](https://toip.tools/toolkit/): choose a library and look up its public API. - [Trust Task reference](https://toip.tools/spec/): inspect the message types used by the applications. - [Examples](https://toip.tools/examples/): run complete applications and read their designs. # 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`: A new project: ```bash 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: From the source: ```bash 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/`](https://github.com/yourbuddyconner/toip-tools/tree/main/packages) using names such as `@toip-tools/trust-core`. The `--tsconfig` option points to [the configuration](https://github.com/yourbuddyconner/toip-tools/blob/main/site/tsconfig.json) 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. site/examples/quickstart/01-identities.ts: ```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: Terminal: ```bash npx tsx --tsconfig site/tsconfig.json site/examples/quickstart/01-identities.ts ``` Output: ```text 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. site/examples/quickstart/02-trust-task.ts: ```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: Terminal: ```bash npx tsx --tsconfig site/tsconfig.json site/examples/quickstart/02-trust-task.ts ``` Output: ```text 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. site/examples/quickstart/03-relay.ts: ```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((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((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: Terminal: ```bash npx tsx --tsconfig site/tsconfig.json site/examples/quickstart/03-relay.ts ``` Output: ```text 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. site/examples/quickstart/04-credentials.ts: ```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: Terminal: ```bash npx tsx --tsconfig site/tsconfig.json site/examples/quickstart/04-credentials.ts ``` Output: ```text 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](https://toip.tools/concepts/), with diagrams and links to the specifications. - Find your next building block in [the toolkit](https://toip.tools/toolkit/): try [delegation](https://toip.tools/toolkit/mandates/) or [verifiable audit trails](https://toip.tools/toolkit/eventlog/). - See a complete app in [Settle](https://toip.tools/examples/#settle), where [Trust Tasks](https://toip.tools/spec/settle/escrow/attest/0.1/) coordinate conditional payments. Start it with `npm run settle`. - Run all four steps at once from `site/` with `npm install` and `npm run quickstart`. # Concepts Identity, messaging, credentials, governance, and proofs: what each does and how this toolkit uses it. Each section links to its specifications. For the communities behind them and their different implementation choices, see the [ecosystem guide](https://toip.tools/ecosystem/). ## Decentralized identifiers An identifier you control, with keys others can verify. A decentralized identifier (DID) identifies a person, organization, or device without requiring an account at a central provider. It resolves to a document containing verification keys and, depending on the method, other information. Those keys let others check signatures and establish encrypted communication. The toolkit starts with `did:key`, which encodes the public key in the identifier itself. Resolution needs no network or registry. The tradeoff is a fixed key: if it is lost or compromised, you need a new identifier. This makes `did:key` useful for tutorials and short-lived identities. Other approaches support key rotation. KERI, described below, records changes in a key-event history so an identifier can keep its identity as its keys change. *A did:key is its public key, written out. A KERI identifier (AID) is a digest of its first event, which already commits to the next key.* ### In this toolkit [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/) · [`@toip-tools/eventlog`](https://toip.tools/toolkit/eventlog/) - **Fixed-key identities.** Create Ed25519 `did:key` identities with `identityFromSeed` and resolve them offline with `resolveDidKey`. - **Key histories.** Eventlog creates KERI identifiers as `did:keri:` and resolves them from their key-event logs. **Scope** Other DID methods are not supported by these resolvers. **Read the source** - [W3C Decentralized Identifiers (DIDs) v1.0](https://www.w3.org/TR/did-1.0/) - [The did:key method (W3C CCG draft)](https://w3c-ccg.github.io/did-key-spec/) ## Verifiable credentials and status lists A claim you can carry, verify, and revoke. A verifiable credential is a signed statement from an *issuer* about a *subject*: "Bob is a member of the Riverside Community Garden." The *holder* keeps it and presents it when needed. A *verifier* checks the signature and decides whether the issuer is an authority it accepts for that claim. The issuer can revoke a credential by updating a signed status list. Each credential points to a bit in that list. A verifier retrieves a current copy, checks its signature, and reads the bit. One list covers many credentials, so the request does not identify which credential is being checked. Verification can happen without asking the issuer about the holder's visit. *The issuer makes the claim, the holder presents it, and the verifier checks it against an issuer it trusts.* ### In this toolkit [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/) · [`@toip-tools/mandates`](https://toip.tools/toolkit/mandates/) - **Issue and verify.** `issueCredential` and `verifyCredential` use the W3C Verifiable Credentials 2.0 shape with `eddsa-jcs-2022` Data Integrity proofs. - **Delegate authority.** Mandates builds delegation chains from these credentials. **Scope** The signed `StatusList` format is inspired by the W3C Bitstring Status List but is not format-compatible. **Read the source** - [W3C Verifiable Credentials Data Model v2.0](https://www.w3.org/TR/vc-data-model-2.0/) - [W3C Bitstring Status List](https://www.w3.org/TR/vc-bitstring-status-list/) - [W3C Data Integrity EdDSA Cryptosuites](https://www.w3.org/TR/vc-di-eddsa/) ## The Trust Spanning Protocol Private, authenticated messages that can travel over different transports. The Trust Spanning Protocol (TSP) provides ToIP's messaging layer. In the Direct mode used here, a message names its sender and recipient with verifiable identifiers (VIDs), encrypts its payload with authenticated HPKE, and carries the sender's signature. The recipient checks that signature before processing the contents. This separates message security from delivery. A relay, radio link, or portable file can carry the same protected message. The carrier can delay or drop it, but cannot read its encrypted payload or alter it without detection. In *Direct* mode, which this toolkit uses, both VIDs travel in the clear, so a carrier learns who is talking to whom. The specification also defines *Routed* and *Nested* modes that provide additional metadata protection through intermediaries. *What each part of a Direct-mode TSP message reveals. The landing page shows a real one, byte for byte.* ### In this toolkit [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/) · [`@toip-tools/relay`](https://toip.tools/toolkit/relay/) · [`@toip-tools/mesh-transport`](https://toip.tools/toolkit/mesh-transport/) - **Direct messages.** Trust-core uses `@openvtc/vti-tsp-js` over an in-memory `Bus` or the WebSocket relay. - **Radio delivery.** Mesh transport carries the same messages, replacing visible identifiers with short address tags on the air. **Scope** Communication starts with a Direct message. The invitation handshake and Routed mode are not implemented here. **Read the source** - [ToIP Trust Spanning Protocol specification](https://trustoverip.github.io/tswg-tsp-specification/) - [RFC 9180: Hybrid Public Key Encryption](https://www.rfc-editor.org/rfc/rfc9180) - [OpenVTC, whose TypeScript TSP library this toolkit uses](https://github.com/OpenVTC) ## Trust Tasks A shared message format for the work parties do together. A Trust Task describes one interaction: issuing an endorsement, requesting community membership, or approving a payment. Each uses the same document envelope: an `id`, a specification URI as its `type`, an `issuer`, a `recipient`, timing fields, a payload, and a proof when required. A response uses the same type with `#response` appended. Before dispatching a document to a handler, the receiver checks freshness, replay history, required proofs, and payload validity. The public registry at trusttasks.org catalogs specifications for many interactions, from community membership to voting. A specification defines an interaction; check separately whether an implementation exists. *Every Trust Task in this toolkit is signed by its issuer, and every response by its responder, refusals included.* ### In this toolkit [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/) - **Send and handle.** `Endpoint` builds, signs, encrypts, and checks Trust Tasks using the OpenVTC libraries, then dispatches them to registered handlers. - **Define interactions.** This repository's types use the `https://toip.tools/spec/` namespace. The [task reference](https://toip.tools/spec/) documents each one. **Read the source** - [Trust Tasks registry](https://trusttasks.org/) - [ToIP Trust Tasks task force](https://github.com/trustoverip/dtgwg-trust-tasks-tf) ## Trust registries and governance Decide whose claims you accept, and under what rules. A valid signature tells you which key signed a claim. You still need to decide whether to accept that signer as an authority. For a garden membership credential, that means knowing the garden's DID and trusting it to vouch for members. A governance framework records those decisions: who may issue which credentials, how members join and leave, and how disputes are resolved. A trust registry makes a key question answerable by software: *is this DID authorized to issue this kind of credential?* These rules belong to the community operating the system. A shared credential format does not determine who may join, who can delegate authority, or how decisions can be challenged. *Governance turns 'this key signed it' into 'this is an authority for this claim'.* ### In this toolkit [`@toip-tools/anon-membership`](https://toip.tools/toolkit/anon-membership/) · [`@toip-tools/mandates`](https://toip.tools/toolkit/mandates/) · [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/) - **Accepted issuers.** Anonymous membership uses `AcceptPolicy` to pin issuers. [Shared To-Do](https://toip.tools/examples/#shared-todo) checks rosters signed by the list's own key. - **Delegated authority.** Mandates checks a chain of credentials leading back to a principal. - **Local decisions.** Trust-core's `Policies` runs Rego policy on the party's own device. **Scope** There is no general trust-registry library in this toolkit yet. **Read the source** - [Trust over IP Foundation](https://trustoverip.org/) - [The ToIP model: technology, governance, and ecosystems](https://trustoverip.org/toip-model/) ## KERI key event logs and witnesses Rotate keys while keeping a verifiable identity history. KERI (Key Event Receipt Infrastructure) records how an identifier's keys change. For the identifiers used here, the AID is a digest of an *inception* event that lists the initial keys and commits to the next ones. Rotation reveals those pre-committed keys. Someone who steals only the current key cannot substitute their own next keys. Signed events form the key event log (KEL). *Witnesses* sign receipts for the first version of each event they accept. If a controller presents conflicting histories, *watchers* can compare witness records and produce evidence of *duplicity*. The log also lets a verifier check an older signature against the keys that were valid when it was made. *Each event commits to the next key before it is needed. Witnesses make a forked history detectable.* ### In this toolkit [`@toip-tools/eventlog`](https://toip.tools/toolkit/eventlog/) - **Verifiable key histories.** Write KERI 1.0 logs with Ed25519 or P-256 keys, witnesses, and watchers. Interoperability tests verify the logs with KERIpy 1.3.6. - **Audit trails.** The toolkit adds its own signed logs, called *trails*. A key rotation seals the open trails. **Scope** Delegated identifiers, weighted thresholds, and KERI 2.0 are unsupported and rejected. **Read the source** - [KERI specification (ToIP)](https://trustoverip.github.io/kswg-keri-specification/) - [CESR specification (ToIP)](https://trustoverip.github.io/kswg-cesr-specification/) - [KERIpy, the reference implementation](https://github.com/WebOfTrust/keripy) ## Selective disclosure and zero-knowledge membership Prove a required fact while keeping the underlying record private. Presenting a full credential reveals all its claims, and repeated presentations can link a holder's activity. *Selective disclosure* lets a holder reveal chosen claims. *Zero-knowledge proofs* can establish a statement, such as "I am a current employee" or "I am over 18", without disclosing the underlying credential or record. A membership proof is one application: a person shows they belong to an accepted group without revealing their membership record. The verifier still needs rules for which issuers, group roots, and proof systems it accepts. *Group membership in zero knowledge: the verifier checks a signed root and a nullifier, and never sees the leaf.* ### In this toolkit [`@toip-tools/anon-membership`](https://toip.tools/toolkit/anon-membership/) - **Membership proofs.** Prove membership in one of up to four groups and check attribute requirements. - **Repeat participation.** A scope-specific nullifier lets a verifier recognize the same membership without learning which record it is. - **Disclosure scope.** Field-level credential disclosure with BBS or SD-JWT is not implemented. **Experimental cryptography** The library uses Noir and Barretenberg's UltraHonk in a mode **designed to be zero-knowledge**. Its authors found no published proof of that property, and Noir is not yet intended for production use. **Read the source** - [Noir](https://noir-lang.org/) - [Barretenberg (in Aztec's repository)](https://github.com/AztecProtocol/aztec-packages) - [Semaphore, an earlier design for anonymous group signalling](https://github.com/semaphore-protocol/semaphore) # Frequently asked questions Short answers about Trust over IP, TSP, the libraries, and how this project relates to the Trust over IP Foundation. ## What is Trust over IP? Trust over IP (ToIP) is an architecture for digital trust from the [Trust over IP Foundation](https://trustoverip.org/). It pairs technology (verifiable identifiers and their keys, the Trust Spanning Protocol for messages between them, and tasks such as issuing and checking credentials) with governance: the rules an ecosystem sets for who is trusted for what. The [ToIP model](https://trustoverip.org/toip-model/) separates that shared architecture from the independently run ecosystems that use it. The [Concepts](https://toip.tools/concepts/) page explains each layer. ## What is the Trust Spanning Protocol (TSP)? TSP is a ToIP [specification](https://trustoverip.github.io/tswg-tsp-specification/) for messages between verifiable identifiers (VIDs). Each message is signed by its sender and encrypted for its recipient with HPKE, whatever transport carries it. In Direct mode, which these libraries use, the sender and recipient identifiers travel in clear; the specification's Routed and Nested modes add metadata protection through intermediaries. The libraries use the OpenVTC TypeScript implementation, `@openvtc/vti-tsp-js`. See [Send an end-to-end encrypted message with TSP](https://toip.tools/guides/tsp-encrypted-message/). ## What is a Trust Task? A Trust Task is a signed JSON document describing one interaction, such as a request for a quote, a membership credential presentation or an approval. Every one uses the same envelope: an `id`, a specification URI as its `type`, an `issuer`, a `recipient`, a timestamp, a payload and a proof. A response uses the same type with `#response` appended. The framework comes from the [ToIP Trust Tasks task force](https://github.com/trustoverip/dtgwg-trust-tasks-tf); the types defined in this repository use the `https://toip.tools/spec/` namespace and are listed in the [Trust Task reference](https://toip.tools/spec/). ## Is toip.tools part of the Trust over IP Foundation? No. toip.tools and the `@toip-tools` libraries are an independent project, unaffiliated with the Trust over IP Foundation. They implement published specifications (ToIP's TSP, KERI and Trust Tasks, W3C DIDs, Verifiable Credentials and Data Integrity, and IETF COSE and CBOR) and build on the OpenVTC TypeScript libraries. The project began at the [Internet Identity Workshop](https://internetidentityworkshop.com/) in November 2026. To work on the specifications themselves, see [Contribute](https://toip.tools/get-involved/). ## How do I install the libraries? Every library is a separate package on npm under `@toip-tools`, at version 0.1.0. Start with trust-core, which the others build on: `npm install @toip-tools/trust-core`. Add the others as you need them, for example `@toip-tools/relay`, `@toip-tools/mandates` or `@toip-tools/eventlog`. The packages are ES modules with TypeScript declarations. The [Quickstart](https://toip.tools/quickstart/) installs two of them in a new project and runs four examples. ## Which Node.js version do I need? Node 22.13 or later. The relay stores its queue with `node:sqlite`, which needs it; the guides, the quickstart and this site's checks run on Node 22. ## Do the libraries work in the browser? Most do, through a bundler. Each library's runtime: - `@toip-tools/trust-core`: Browsers and Node 22. - `@toip-tools/relay`: Node 22.13 or later (it uses `node:sqlite`). Clients use `RelayTransport` from trust-core, in browsers or Node. - `@toip-tools/cose`: Browsers and Node. The main entry has no Node-only imports. - `@toip-tools/web-vault`: Browsers. Tests run in Node with stand-ins for storage and the authenticator. - `@toip-tools/mandates`: Browsers and Node. - `@toip-tools/anon-membership`: Node and browsers, proving in a Web Worker. Proving takes about 0.15 s on an Apple M1 Max; phones aren't measured. - `@toip-tools/eventlog`: Browsers and Node. A file store and an HTTP witness are in the Node entry. - `@toip-tools/mesh-transport`: Browsers and Node. The `/gwmp`, `/detect` and `/node` entry points are Node only. ## Which DID methods are supported? trust-core creates and resolves Ed25519 `did:key` identifiers, offline, with no registry. `@toip-tools/eventlog` creates KERI identifiers, written `did:keri:`, and resolves them from their key event logs. There is no resolver for other DID methods. ## Do I need a server, an account or a blockchain? No. A `did:key` identity is 32 random bytes made on the device, and verifying a signature needs only the DID. To deliver messages to someone who is offline, run the relay (`npx @toip-tools/relay`); for tests and demos, the in-memory `Bus` needs nothing. One example application, Settle, uses a Solana escrow, but the libraries don't. ## Are the libraries ready for production? They are at version 0.1.0: expect changes between releases, and pin versions. Each library's page lists what it doesn't do. The zero-knowledge library, `@toip-tools/anon-membership`, is experimental cryptography: its proof system's zero-knowledge mode is designed to be zero-knowledge, and Noir says it is not yet for production use. Report problems in the [issue tracker](https://github.com/yourbuddyconner/toip-tools/issues). ## What license are the libraries under? The Apache License 2.0 (`Apache-2.0`), as stated in each package's `package.json` and the repository's [LICENSE](https://github.com/yourbuddyconner/toip-tools/blob/main/LICENSE) file. ## How do I use these docs with an AI coding assistant? Point it at [llms.txt](https://toip.tools/llms.txt) for an index, or [llms-full.txt](https://toip.tools/llms-full.txt) for all the documentation in one Markdown file. Every page also has a Markdown version at `index.md` under its address, and the [machine-readable indexes](https://toip.tools/api/) list every package, export, Trust Task type and example as JSON. ## How do I report a security problem? Use GitHub's [security page for the repository](https://github.com/yourbuddyconner/toip-tools/security), or open an [issue](https://github.com/yourbuddyconner/toip-tools/issues) if the problem is not sensitive. The same contacts are in [/.well-known/security.txt](https://toip.tools/.well-known/security.txt). # Guides Short how-tos, each answering one question with one complete program you can run. Every guide installs the published packages from npm and runs with Node 22.13 or later. The programs are checked on every build of this site, and the output shown is recorded from a real run. New to the libraries? Start with the [Quickstart](https://toip.tools/quickstart/). - [Create a did:key and sign a JSON document in TypeScript](https://toip.tools/guides/did-key-sign-document/): Generate an Ed25519 did:key, sign a JSON document with a Data Integrity proof, and verify it from the DID alone. - [Issue and verify a W3C verifiable credential in TypeScript](https://toip.tools/guides/issue-verify-credential/): Issue a credential in the W3C VC 2.0 shape with a Data Integrity proof, then check its proof, issuer, subject and validity window. - [Revoke a verifiable credential with a status list](https://toip.tools/guides/revoke-credential-status-list/): Give each credential a bit in a signed status list, revoke by setting the bit and re-signing, and check status as a verifier. - [Send an end-to-end encrypted message with TSP (the Trust Spanning Protocol)](https://toip.tools/guides/tsp-encrypted-message/): Send a signed, end-to-end encrypted Trust Task with TSP Direct mode between two did:key identities, and see what the network sees. - [Run a TSP relay: a mailbox for encrypted messages](https://toip.tools/guides/run-tsp-relay/): Run a WebSocket mailbox that stores sealed TSP messages in SQLite until the recipient connects, survives restarts, and sees only metadata. - [Delegate bounded authority to an AI agent with mandates](https://toip.tools/guides/delegate-to-ai-agent/): Give an AI agent a signed mandate with allowed actions, spending limits, one-time approvals and revocation, and decide each action against it. - [Keep a tamper-evident audit log with KERI key event logs](https://toip.tools/guides/tamper-evident-audit-log/): Write an append-only, witnessed audit log under a KERI identifier, rotate keys with pre-rotation, and detect an edited entry offline. - [Sign and verify COSE messages in TypeScript](https://toip.tools/guides/sign-cose/): Sign COSE\_Sign1 messages over deterministic CBOR with Ed25519 or a non-extractable WebCrypto P-256 key, and verify them against trusted keys. - [Send Trust Tasks over LoRa radio](https://toip.tools/guides/trust-tasks-over-lora/): Send a signed, encrypted Trust Task over LoRa with no internet: compacted, fragmented into radio frames, acknowledged and reassembled. - [Prove group membership with zero knowledge (Noir)](https://toip.tools/guides/zero-knowledge-membership/): Prove membership in a group without saying which member, with a Noir circuit and UltraHonk proofs, and count one voice per member with nullifiers. Looking for a whole application? See the [examples](https://toip.tools/examples/). Looking up one function? Search the [SDK reference](https://toip.tools/toolkit/). Guide · `@toip-tools/trust-core` # Create a did:key and sign a JSON document in TypeScript Generate an Ed25519 did:key, sign a JSON document with a Data Integrity proof, and verify it from the DID alone. A `did:key` is a decentralized identifier that *is* its public key, written out. There is nothing to register and nothing to look up: anyone holding the DID can check your signatures. That makes it the quickest way to give a person, device or service a verifiable identity. This program creates one from 32 random bytes, signs a small JSON document, and verifies the signature. It then changes one field to show that verification fails. ## 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 did-key-sign-document && cd did-key-sign-document npm init -y && npm pkg set type=module npm install @toip-tools/trust-core tsx ``` ## The code Save this as `did-key-sign-document.ts`. It is the complete program; the site's checks run it on every build. did-key-sign-document.ts: ```ts // Create a did:key identity, sign a JSON document with it, and verify the signature from the DID alone. import { SystemClock, identityFromSeed, resolveDidKey, signDocument, verifyDocument } from "@toip-tools/trust-core"; const clock = new SystemClock(); // A did:key identity is 32 random bytes. Keep the seed secret: whoever holds it can sign as you. const seed = crypto.getRandomValues(new Uint8Array(32)); const me = identityFromSeed(seed); console.log("DID:", me.did); // The DID encodes the Ed25519 public key, so anyone can recover it without a registry or network call. const { signingKey } = resolveDidKey(me.did); console.log("Public key from the DID:", Buffer.from(signingKey).toString("hex")); // signDocument adds a W3C Data Integrity proof (eddsa-jcs-2022). The document's issuer must be the signer's DID. interface Receipt { issuer: string; kind: string; item: string; cents: number; proof?: { type: string; cryptosuite: string } } const receipt = signDocument({ issuer: me.did, kind: "receipt", item: "bike tune-up", cents: 4500 }, me, clock); console.log("Proof:", receipt.proof?.type, receipt.proof?.cryptosuite); // Anyone can verify it: the proof names the key, and the key is in the DID. const check = await verifyDocument(receipt, clock); console.log("Valid:", check.valid); // Change one field and the signature no longer matches. const altered = await verifyDocument({ ...receipt, cents: 450 }, clock); console.log("Valid after changing the price:", altered.valid, `(${altered.failure})`); ``` Run it: Terminal: ```bash npx tsx did-key-sign-document.ts ``` Output: ```text DID: did:key:z6MkoMDtsgSyN7GBcCQN5UmnNDe3tP57hKu3B9m4J8m7TsSh Public key from the DID: 842d44221b776a19de0d74b4e41d6aa69a7753f16c3f53c89037ab0f3c724e0a Proof: DataIntegrityProof eddsa-jcs-2022 Valid: true Valid after changing the price: false (signatureInvalid) ``` 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/did-key-sign-document.ts`, or read it in [`site/examples/guides/did-key-sign-document.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/site/examples/guides/did-key-sign-document.ts). ## How it works - `identityFromSeed` turns a 32-byte seed into an Ed25519 key pair, its `did:key` identifier, and a derived X25519 key for encryption. The seed is the secret: store it as you would a password hash's key, not in source code. - `resolveDidKey` decodes the public key from the DID itself, with no network access. This is what a verifier does. - `signDocument` adds a W3C Data Integrity proof with the `eddsa-jcs-2022` cryptosuite: the document is canonicalized with JCS (RFC 8785) and signed with Ed25519. The document's `issuer` must be the signer's DID; the proof's `verificationMethod` points at the key inside that DID. - `verifyDocument` recomputes the canonical form and checks the signature, allowing five minutes of clock skew on the proof's creation time. It returns `{ valid, failure }` rather than throwing. ## Limits and production notes - A `did:key` can't rotate its key. If the seed leaks, you need a new identifier. For identifiers that outlive their keys, see the [KERI audit log guide](https://toip.tools/guides/tamper-evident-audit-log/). - Only Ed25519 `did:key` identifiers are supported. There is no resolver for other DID methods. - `seedFrom(label)` hashes a label into a seed. It is for repeatable demos and tests: a guessable label gives a guessable key. ## Related ### API used [`identityFromSeed`](https://toip.tools/toolkit/trust-core/api/identityFromSeed/) · [`resolveDidKey`](https://toip.tools/toolkit/trust-core/api/resolveDidKey/) · [`signDocument`](https://toip.tools/toolkit/trust-core/api/signDocument/) · [`verifyDocument`](https://toip.tools/toolkit/trust-core/api/verifyDocument/) · [`SystemClock`](https://toip.tools/toolkit/trust-core/api/SystemClock/) ### 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 - [Decentralized identifiers](https://toip.tools/concepts/#dids) ### More guides - [Issue and verify a W3C verifiable credential in TypeScript](https://toip.tools/guides/issue-verify-credential/) - [Send an end-to-end encrypted message with TSP (the Trust Spanning Protocol)](https://toip.tools/guides/tsp-encrypted-message/) Guide · `@toip-tools/trust-core` # Issue and verify a W3C verifiable credential in TypeScript Issue a credential in the W3C VC 2.0 shape with a Data Integrity proof, then check its proof, issuer, subject and validity window. A verifiable credential is a signed statement by an issuer about a subject: "this DID holds a BSc from this university". The holder keeps it and shows it when asked; the verifier checks it without calling the issuer. This program issues a degree credential from one `did:key` to another, prints it, and runs four presentations through a verifier: the real one, the same credential presented by someone else, a copy with the degree changed, and one the graduate signed themselves. ## 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 issue-verify-credential && cd issue-verify-credential npm init -y && npm pkg set type=module npm install @toip-tools/trust-core tsx ``` ## The code Save this as `issue-verify-credential.ts`. It is the complete program; the site's checks run it on every build. issue-verify-credential.ts: ```ts // Issue a W3C verifiable credential (VC Data Model 2.0 shape) and verify it: proof, issuer, subject and validity. import { SystemClock, identityFromSeed, issueCredential, verifyCredential, type Credential } from "@toip-tools/trust-core"; const clock = new SystemClock(); const random = () => crypto.getRandomValues(new Uint8Array(32)); const university = identityFromSeed(random()); const graduate = identityFromSeed(random()); // The issuer signs a claim about a subject. issueCredential sets @context, id, issuer and validFrom. const diploma = issueCredential(university, clock, { type: ["VerifiableCredential", "DegreeCredential"], credentialSubject: { id: graduate.did, degree: "BSc Computer Science", year: 2026 }, validUntil: new Date(clock.now() + 5 * 365 * 86_400_000).toISOString(), }); console.log(JSON.stringify({ ...diploma, proof: { ...diploma.proof, proofValue: "…" } }, null, 2)); // A verifier checks the proof and validity window, then decides whether it trusts this issuer for this claim. const trustedIssuers = new Set([university.did]); async function accept(vc: Credential, holder: string): Promise { const check = await verifyCredential(vc, clock); if (!check.ok) return `rejected: ${check.failure}`; if (!trustedIssuers.has(vc.issuer)) return "rejected: unknown issuer"; if (vc.credentialSubject.id !== holder) return "rejected: credential is about someone else"; return `accepted: ${vc.credentialSubject.degree}`; } console.log("\nThe graduate presents it:", await accept(diploma, graduate.did)); console.log("Someone else presents it:", await accept(diploma, identityFromSeed(random()).did)); const inflated = { ...diploma, credentialSubject: { ...diploma.credentialSubject, degree: "PhD Computer Science" } }; console.log("With the degree changed:", await accept(inflated, graduate.did)); const selfIssued = issueCredential(graduate, clock, { type: ["VerifiableCredential", "DegreeCredential"], credentialSubject: { id: graduate.did, degree: "PhD" } }); console.log("Signed by the graduate:", await accept(selfIssued, graduate.did)); ``` Run it: Terminal: ```bash npx tsx issue-verify-credential.ts ``` Output: ```text { "@context": [ "https://www.w3.org/ns/credentials/v2" ], "id": "urn:uuid:94282ecf-f355-42be-9290-31d4689f0f12", "type": [ "VerifiableCredential", "DegreeCredential" ], "issuer": "did:key:z6MkmXDyCnbW5QgPYp4TVrGG7NVCVi3Zz951rZ83fS7CRMpb", "validFrom": "2026-11-07T09:56:37.441Z", "validUntil": "2031-11-06T09:56:37.439Z", "credentialSubject": { "id": "did:key:z6MkqUzDpEdVRhm2YLwZ3kwEWUWLGMyV73fWA6py1yuVWcx6", "degree": "BSc Computer Science", "year": 2026 }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "created": "2026-11-07T09:56:37.441Z", "verificationMethod": "did:key:z6MkmXDyCnbW5QgPYp4TVrGG7NVCVi3Zz951rZ83fS7CRMpb#z6MkmXDyCnbW5QgPYp4TVrGG7NVCVi3Zz951rZ83fS7CRMpb", "proofPurpose": "assertionMethod", "proofValue": "…" } } The graduate presents it: accepted: BSc Computer Science Someone else presents it: rejected: credential is about someone else With the degree changed: rejected: signatureInvalid Signed by the graduate: rejected: unknown issuer ``` 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/issue-verify-credential.ts`, or read it in [`site/examples/guides/issue-verify-credential.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/site/examples/guides/issue-verify-credential.ts). ## How it works - `issueCredential` fills in `@context` (`https://www.w3.org/ns/credentials/v2`), a `urn:uuid` id, the issuer's DID and `validFrom`, then signs the whole credential with an `eddsa-jcs-2022` Data Integrity proof. - `verifyCredential` checks the proof, that the proof's key belongs to the `issuer`, and the `validFrom`/`validUntil` window. It returns `{ ok: true }` or `{ ok: false, failure }`, where `failure` is one of `signatureInvalid`, `issuerMismatch`, `malformedProof`, `notYetValid` or `expired`. - A valid signature only says *who* made the claim. Deciding whether that issuer is an authority for it is your policy: here, a set of trusted issuer DIDs. - Comparing `credentialSubject.id` with the holder only means something if the holder proved control of that DID. In practice, compare it with the authenticated sender of the message that carried the credential, as the [quickstart's step 4](https://toip.tools/quickstart/#credentials) does over TSP. ## Limits and production notes - Credentials have one issuer and one proof. JSON-LD contexts are not processed or validated, and other proof formats (VC-JWT, SD-JWT, BBS) are not supported. - Revocation is a separate check: see [Revoke a credential with a status list](https://toip.tools/guides/revoke-credential-status-list/). ## Related ### API used [`issueCredential`](https://toip.tools/toolkit/trust-core/api/issueCredential/) · [`verifyCredential`](https://toip.tools/toolkit/trust-core/api/verifyCredential/) · [`Credential`](https://toip.tools/toolkit/trust-core/api/Credential/) · [`CredentialCheck`](https://toip.tools/toolkit/trust-core/api/CredentialCheck/) ### 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 - [Verifiable credentials and status lists](https://toip.tools/concepts/#credentials) ### More guides - [Revoke a verifiable credential with a status list](https://toip.tools/guides/revoke-credential-status-list/) - [Create a did:key and sign a JSON document in TypeScript](https://toip.tools/guides/did-key-sign-document/) Guide · `@toip-tools/trust-core` # Revoke a verifiable credential with a status list Give each credential a bit in a signed status list, revoke by setting the bit and re-signing, and check status as a verifier. Credentials are checked offline, so an issuer can't take one back by deleting a database row. Instead it publishes a signed list with one bit per credential it has issued. A verifier fetches the latest list, checks the issuer's signature, and reads the credential's bit. One list covers many credentials, so fetching it doesn't tell the issuer which credential is being checked, or where. ## 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 revoke-credential-status-list && cd revoke-credential-status-list npm init -y && npm pkg set type=module npm install @toip-tools/trust-core tsx ``` ## The code Save this as `revoke-credential-status-list.ts`. It is the complete program; the site's checks run it on every build. revoke-credential-status-list.ts: ```ts // Revoke a verifiable credential with a signed status list: one bit per credential, published by the issuer. import { StatusList, SystemClock, checkStatus, identityFromSeed, issueCredential, verifyCredential, type Credential } from "@toip-tools/trust-core"; const clock = new SystemClock(); const random = () => crypto.getRandomValues(new Uint8Array(32)); const gym = identityFromSeed(random()); const member = identityFromSeed(random()); // The issuer keeps one list for many credentials (1024 by default) and gives each credential a slot. const list = new StatusList(); const slot = list.allocate(); const pass = issueCredential(gym, clock, { type: ["VerifiableCredential", "MembershipCredential"], credentialSubject: { id: member.did, plan: "monthly" }, credentialStatus: { type: "BitstringStatusListEntry", statusListIndex: slot, statusListCredential: `${gym.did}#status` }, }); // The issuer signs the list and publishes it anywhere verifiers can fetch it: a web server, a relay, a file. let published = list.sign(gym, clock); // A verifier checks the credential, then the list: signed by the same issuer, and the credential's bit clear. async function check(vc: Credential): Promise { const proof = await verifyCredential(vc, clock); if (!proof.ok) return `invalid (${proof.failure})`; const status = await checkStatus(published, vc.credentialStatus!.statusListIndex, vc.issuer, clock); if (!status.signatureValid) return "status list not signed by the issuer"; return status.revoked ? `revoked (list is ${status.ageSeconds}s old)` : `valid (list is ${status.ageSeconds}s old)`; } console.log(`Slot ${slot}:`, await check(pass)); // To revoke: set the bit, sign the list again, publish the new copy. list.revoke(slot); published = list.sign(gym, clock); console.log(`Slot ${slot} after revocation:`, await check(pass)); // Someone in the middle swaps in an all-clear bitstring to un-revoke the pass. The issuer's signature catches it. published = { ...published, bits: new StatusList().sign(gym, clock).bits }; console.log("With a tampered list:", await check(pass)); ``` Run it: Terminal: ```bash npx tsx revoke-credential-status-list.ts ``` Output: ```text Slot 0: valid (list is 0s old) Slot 0 after revocation: revoked (list is 0s old) With a tampered list: status list not signed by the issuer ``` 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/revoke-credential-status-list.ts`, or read it in [`site/examples/guides/revoke-credential-status-list.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/site/examples/guides/revoke-credential-status-list.ts). ## How it works - `StatusList` holds the bits (1024 by default). `allocate()` gives a new credential its slot, which goes in the credential's `credentialStatus.statusListIndex`. - `sign(issuer, clock)` produces the publishable document: the bits in base64url, the issuer, a timestamp and a Data Integrity proof. Publish it wherever verifiers can fetch it. - `checkStatus(list, index, expectedIssuer, clock)` returns `signatureValid` (signed by the expected issuer), `revoked` (the bit), and `ageSeconds`, so you can refuse a list that is too old. - To revoke, call `revoke(slot)`, sign again and publish the new copy. Anyone holding an old copy still sees the old answer, which is why the age matters. ## Limits and production notes - The list document is this library's own format, modeled on the W3C Bitstring Status List; credentials reference it with a `BitstringStatusListEntry`. It is not a W3C `BitstringStatusListCredential`, and other verifiers won't read it. - The list isn't compressed. A 1024-entry list is 128 bytes of bits. - For delegation, `@toip-tools/mandates` has a `StatusRegistry` that enforces how fresh a list must be: see [the mandates guide](https://toip.tools/guides/delegate-to-ai-agent/). ## Related ### API used [`StatusList`](https://toip.tools/toolkit/trust-core/api/StatusList/) · [`checkStatus`](https://toip.tools/toolkit/trust-core/api/checkStatus/) · [`isRevokedIn`](https://toip.tools/toolkit/trust-core/api/isRevokedIn/) · [`StatusListDoc`](https://toip.tools/toolkit/trust-core/api/StatusListDoc/) · [`issueCredential`](https://toip.tools/toolkit/trust-core/api/issueCredential/) ### 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 - [Verifiable credentials and status lists](https://toip.tools/concepts/#credentials) ### More guides - [Issue and verify a W3C verifiable credential in TypeScript](https://toip.tools/guides/issue-verify-credential/) - [Delegate bounded authority to an AI agent with mandates](https://toip.tools/guides/delegate-to-ai-agent/) 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((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/) Guide · `@toip-tools/relay`, `@toip-tools/trust-core` # Run a TSP relay: a mailbox for encrypted messages Run a WebSocket mailbox that stores sealed TSP messages in SQLite until the recipient connects, survives restarts, and sees only metadata. People and devices are rarely online at the same time. A relay holds encrypted messages for a recipient until it connects and acknowledges them. It can't read them: they are sealed to the recipient's key before they reach it. To run one from the command line: Terminal: ```bash npx @toip-tools/relay ``` It listens on port 8787 and keeps its queue in `./relay.db`. Set `PORT`, `HOST`, `RELAY_DB` and `RELAY_PUBLIC_URL` to change that. The program below starts a relay in code instead, leaves a note for an offline recipient, restarts the relay on the same database, and delivers the note when the recipient connects. ## Before you start You need Node 22.13 or later. In a new folder, install the packages and `tsx`, a TypeScript runner: Terminal: ```bash mkdir run-tsp-relay && cd run-tsp-relay npm init -y && npm pkg set type=module npm install @toip-tools/relay @toip-tools/trust-core tsx ``` ## The code Save this as `run-tsp-relay.ts`. It is the complete program; the site's checks run it on every build. run-tsp-relay.ts: ```ts // Run a TSP mailbox relay in Node: it stores sealed messages in SQLite until the recipient connects, // survives a restart, and shows its operator only metadata. import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { startRelay, type StoredMessage } from "@toip-tools/relay"; import { Endpoint, RelayTransport, SystemClock, identityFromSeed, type Identity } from "@toip-tools/trust-core"; const clock = new SystemClock(); const dir = mkdtempSync(join(tmpdir(), "relay-guide-")); const dbPath = join(dir, "relay.db"); // in production, a persistent file you back up const short = (did: string) => `${did.slice(8, 16)}…`; const options = { port: 0, // any free port; npx @toip-tools/relay defaults to 8787 host: "127.0.0.1", dbPath, limits: { perSenderPerRecipient: 100 }, // at most 100 messages waiting from one sender to one recipient onStored: (m: StoredMessage) => console.log(`[relay] ${short(m.from)} -> ${short(m.to)}: ${m.bytes} bytes, ${m.delivery}`), }; function connect(identity: Identity, url: string) { const transport = new RelayTransport({ url, identity }); const online = new Promise((resolve) => transport.onStatus((s) => s === "connected" && resolve())); transport.start(); return { transport, online, endpoint: new Endpoint({ identity, transport, clock }) }; } const NOTE = { typeUri: "https://example.org/spec/notes/note/0.1", isBearer: false, isProofRequired: true, isRecipientRequired: true, isIssuedAtRequired: true, }; const alice = identityFromSeed(crypto.getRandomValues(new Uint8Array(32))); const bob = identityFromSeed(crypto.getRandomValues(new Uint8Array(32))); // Alice connects and leaves a note for Bob, who is offline. let relay = await startRelay(options); console.log("Relay at", relay.url); const a = connect(alice, relay.url); await a.online; console.log("Alice sent:", await a.endpoint.notify(bob.did, NOTE, { text: "Back at 6." })); console.log("Waiting for Bob:", relay.queued(bob.did)); a.endpoint.close(); a.transport.stop(); // Restart the relay on the same database. The note is still there. await relay.close(); relay = await startRelay(options); console.log("Restarted; waiting for Bob:", relay.queued(bob.did)); // Bob connects (signing the relay's challenge with his did:key) and the relay delivers. const b = connect(bob, relay.url); const got = new Promise((resolve) => b.endpoint.handle<{ text: string }, void>(NOTE, (doc) => resolve(doc.payload.text))); await b.online; console.log("Bob read:", await got); await new Promise((r) => setTimeout(r, 100)); // Bob's acknowledgement reaches the relay, which deletes its copy console.log("Waiting for Bob:", relay.queued(bob.did)); b.endpoint.close(); b.transport.stop(); await relay.close(); rmSync(dir, { recursive: true, force: true }); ``` Run it: Terminal: ```bash npx tsx run-tsp-relay.ts ``` Output: ```text Relay at ws://127.0.0.1:60693/v1 [relay] z6MkuaXR… -> z6MkpDnq…: 1020 bytes, queued Alice sent: queued Waiting for Bob: 1 Restarted; waiting for Bob: 1 Bob read: Back at 6. Waiting for Bob: 0 ``` 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/run-tsp-relay.ts`, or read it in [`site/examples/guides/run-tsp-relay.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/site/examples/guides/run-tsp-relay.ts). ## How it works - `startRelay` serves WebSockets at `/v1` and stores messages in SQLite with `node:sqlite`, which is why it needs Node 22.13 or later. `port: 0` picks a free port; read the real one from `relay.url`. - Clients connect with `RelayTransport` from trust-core. Each one signs a fresh challenge from the relay with its `did:key`, bound to the relay's URL, so the relay knows which mailbox is whose. - A message to a connected recipient goes out at once (`live`); otherwise it waits (`queued`). Either way the relay keeps it until the recipient acknowledges it, and deletes it then. Unacknowledged messages expire after 30 days. - `onStored` shows what an operator can see for each message: sender, recipient, size and time. Never the contents. - `limits` caps what one sender can queue for one recipient, and the total messages and bytes per recipient. A send over a limit is refused with `queueFull`; `RelayTransport` keeps the message and retries. ## Limits and production notes - In production, run it behind TLS and set `RELAY_PUBLIC_URL` (or `publicUrl`) to the exact `wss://` URL clients use: the URL is part of what they sign. - The relay learns who talks to whom, when, and how much. It delivers TSP Direct messages and does not implement TSP Routed mode. - Keep one connection per DID. A newer connection for the same DID closes the older one. ## Related ### API used [`startRelay`](https://toip.tools/toolkit/relay/api/startRelay/) · [`RelayOptions`](https://toip.tools/toolkit/relay/api/RelayOptions/) · [`RelayLimits`](https://toip.tools/toolkit/relay/api/RelayLimits/) · [`StoredMessage`](https://toip.tools/toolkit/relay/api/StoredMessage/) · [`Relay`](https://toip.tools/toolkit/relay/api/Relay/) [`RelayTransport`](https://toip.tools/toolkit/trust-core/api/RelayTransport/) · [`Endpoint`](https://toip.tools/toolkit/trust-core/api/Endpoint/) ### Libraries - [`@toip-tools/relay`](https://toip.tools/toolkit/relay/): A WebSocket mailbox that stores and delivers encrypted TSP messages. - [`@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) ### More guides - [Send an end-to-end encrypted message with TSP (the Trust Spanning Protocol)](https://toip.tools/guides/tsp-encrypted-message/) - [Send Trust Tasks over LoRa radio](https://toip.tools/guides/trust-tasks-over-lora/) Guide · `@toip-tools/mandates`, `@toip-tools/trust-core` # Delegate bounded authority to an AI agent with mandates Give an AI agent a signed mandate with allowed actions, spending limits, one-time approvals and revocation, and decide each action against it. An agent that can act for you needs limits it can't talk its way past: which actions, with whom, how much each time and per week. A **mandate** is a signed credential that says exactly that. Anyone can check an action against it, on their own, and get a decision with reasons. This program gives a shopping agent a mandate, then decides five purchases and a revoked one: an allowed purchase, a merchant outside the list, one over the per-purchase limit that the owner approves, one that would break the weekly budget, and one after revocation. ## Before you start You need Node 22.13 or later. In a new folder, install the packages and `tsx`, a TypeScript runner: Terminal: ```bash mkdir delegate-to-ai-agent && cd delegate-to-ai-agent npm init -y && npm pkg set type=module npm install @toip-tools/mandates @toip-tools/trust-core tsx ``` ## The code Save this as `delegate-to-ai-agent.ts`. It is the complete program; the site's checks run it on every build. delegate-to-ai-agent.ts: ```ts // Delegate bounded authority to an AI agent with a mandate: which actions, which merchants, how much per // purchase and per week. Every action gets a decision (allow, escalate or deny) with reasons in plain words. import { MandateEngine, SpendLedger, StatusRegistry, approve, explain, issueMandate, registerProfile, staticStatusResolver, type Action, } from "@toip-tools/mandates"; import { SystemClock, identityFromSeed } from "@toip-tools/trust-core"; const clock = new SystemClock(); const random = () => crypto.getRandomValues(new Uint8Array(32)); const owner = identityFromSeed(random()); const agent = identityFromSeed(random()); // A profile is the action vocabulary: what an action of each type must say. Roots must constrain type and spend. registerProfile({ id: "shopping/1", actions: { "shopping/buy": { required: ["merchant", "item"] } }, rootRequires: ["type", "spend:budget"] }); // The owner signs a mandate for the agent. Amounts are integer units: here, cents. const status = new StatusRegistry(owner, clock); // the owner's revocation list const mandate = issueMandate(owner, clock, { subject: agent.did, validUntil: new Date(clock.now() + 30 * 86_400_000).toISOString(), status: status.allocate(), profile: "shopping/1", constraints: { actions: { attr: "type", anyOf: ["shopping/buy"] }, merchants: { attr: "merchant", anyOf: ["grocer.example", "pharmacy.example"] }, perPurchase: { attr: "spend", max: "5000" }, perWeek: { attr: "spend", budget: "15000", period: "P7D" }, }, delegation: { maxDepth: 0 }, // the agent may not delegate further escalation: { approvable: ["perPurchase"], approvalTtlSeconds: 600 }, // the owner may approve a bigger purchase revocation: { maxAgeSeconds: 3600 }, // verifiers need a status list less than an hour old }); const engine = await MandateEngine.load(); const ledger = new SpendLedger(); // what the agent has spent, per mandate const words = { name: (did: string) => (did === owner.did ? "Sam" : "the shopping agent"), units: (cents: string, attr: string) => (attr === "spend" ? `$${(Number(cents) / 100).toFixed(2)}` : cents), label: (dimension: string) => ({ perPurchase: "per purchase", perWeek: "per week" })[dimension], noun: "this purchase", }; async function attempt(merchant: string, item: string, cents: number, approvals = [] as ReturnType[]) { const action: Action = { type: "shopping/buy", profile: "shopping/1", id: crypto.randomUUID(), actor: agent.did, at: clock.iso(), attrs: { merchant, item, spend: String(cents) }, }; const decision = await engine.decide({ chain: [mandate], presenter: agent.did, action, approvals, state: { mandate: mandate.id, spent: ledger.spent(mandate.id, clock.now()) }, status: staticStatusResolver([status.sign()]), clock, }); console.log(`${item} at ${merchant}, $${(cents / 100).toFixed(2)}: ${decision.outcome}`); console.log(` ${explain(decision, words).join(" ")}`); // Allowed: reserve the spend before paying, so two purchases can't both take the last of the budget. if (decision.outcome === "allow") ledger.tryReserve(mandate, action.id, action.attrs.spend, clock.now(), action.type); return { action, decision }; } await attempt("grocer.example", "groceries", 4200); await attempt("casino.example", "chips", 2000); const { action } = await attempt("pharmacy.example", "allergy medicine", 6500); // The owner approves that one purchase, and only that one. const approval = approve(owner, clock, { chain: [mandate], action, ttlSeconds: 600 }); const retry = await engine.decide({ chain: [mandate], presenter: agent.did, action, approvals: [approval], usedApprovals: (id) => ledger.approvalUsed(id), state: { mandate: mandate.id, spent: ledger.spent(mandate.id, clock.now()) }, status: staticStatusResolver([status.sign()]), clock, }); console.log(`With Sam's approval: ${retry.outcome}`); ledger.tryReserve(mandate, action.id, action.attrs.spend, clock.now(), action.type); ledger.markApprovalUsed(approval.id); await attempt("grocer.example", "more groceries", 4900); // the weekly budget has $43.00 left // Revoke the mandate: the agent is stopped as soon as verifiers see the new list. status.revoke(mandate.credentialStatus); await attempt("grocer.example", "milk", 300); ``` Run it: Terminal: ```bash npx tsx delegate-to-ai-agent.ts ``` Output: ```text groceries at grocer.example, $42.00: allow This purchase is within every limit of the chain from Sam to the shopping agent. chips at casino.example, $20.00: deny The merchant “casino.example” isn't one Sam allowed the shopping agent (merchants). This purchase can't go ahead. allergy medicine at pharmacy.example, $65.00: escalate $65.00 is more than the $50.00 per purchase that Sam allowed the shopping agent. Sam can approve this purchase. With Sam's approval: allow more groceries at grocer.example, $49.00: deny Spending $49.00 would bring the spending in the last 7 days to $156.00, over the $150.00 budget that Sam allowed the shopping agent (per week). This purchase can't go ahead. milk at grocer.example, $3.00: deny Sam has revoked the mandate to the shopping agent. This purchase can't go ahead. ``` 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/delegate-to-ai-agent.ts`, or read it in [`site/examples/guides/delegate-to-ai-agent.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/site/examples/guides/delegate-to-ai-agent.ts). ## How it works - A profile (`registerProfile`) is the action vocabulary: here one action type, `shopping/buy`, which must name a merchant and an item. Every action also carries `spend`, in integer units. - `issueMandate` signs the constraints: `anyOf` sets for the action type and merchant, `max` per purchase, and a rolling `budget` over seven days (`P7D`). It also says how many more links may follow, which failures the owner may approve, and how fresh the revocation list must be. - `MandateEngine.decide` checks the signature, validity window and revocation status, then evaluates the constraints with a Rego policy compiled to WebAssembly. It returns `allow`, `escalate` or `deny` with reasons, and every decision carries the policy's hash. - `escalate` means only approvable limits failed. The owner signs an `approve` for that exact action (it is bound to the action's hash), and the engine allows it once. Record used approvals so they can't be replayed. - `SpendLedger.tryReserve` checks the budget and reserves in one step before you pay, so two purchases can't both take the last of it. `explain` turns reasons into sentences. ## Limits and production notes - The engine decides; your code enforces. Check for `allow` and reserve the spend before the agent acts. - A delegate can pass on a narrower mandate with `delegate()`: every link can only narrow its parent, and a widening is refused without signing anything. - Spending totals come from your ledger, not from the engine. Persist the ledger and the status registry (`save()`), and publish the signed status list where verifiers fetch it. ## Related ### API used [`issueMandate`](https://toip.tools/toolkit/mandates/api/issueMandate/) · [`MandateEngine`](https://toip.tools/toolkit/mandates/api/MandateEngine/) · [`SpendLedger`](https://toip.tools/toolkit/mandates/api/SpendLedger/) · [`StatusRegistry`](https://toip.tools/toolkit/mandates/api/StatusRegistry/) · [`approve`](https://toip.tools/toolkit/mandates/api/approve/) · [`explain`](https://toip.tools/toolkit/mandates/api/explain/) · [`registerProfile`](https://toip.tools/toolkit/mandates/api/registerProfile/) · [`staticStatusResolver`](https://toip.tools/toolkit/mandates/api/staticStatusResolver/) · [`delegate`](https://toip.tools/toolkit/mandates/api/delegate/) ### Libraries - [`@toip-tools/mandates`](https://toip.tools/toolkit/mandates/): Revocable delegation with spending limits, policy checks, and approvals. - [`@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 - [Verifiable credentials and status lists](https://toip.tools/concepts/#credentials) - [Trust registries and governance](https://toip.tools/concepts/#governance) ### More guides - [Keep a tamper-evident audit log with KERI key event logs](https://toip.tools/guides/tamper-evident-audit-log/) - [Revoke a verifiable credential with a status list](https://toip.tools/guides/revoke-credential-status-list/) Guide · `@toip-tools/eventlog`, `@toip-tools/trust-core` # Keep a tamper-evident audit log with KERI key event logs Write an append-only, witnessed audit log under a KERI identifier, rotate keys with pre-rotation, and detect an edited entry offline. An ordinary log can be edited by whoever runs it. A tamper-evident log can't be changed quietly: every entry is signed and chained, independent witnesses receipt the first version they see, and anyone can verify a copy offline. This program creates a KERI identifier for a service, appends three audit entries (waiting for a witness receipt on the one that matters), rotates its keys, exports a bundle and verifies it. Then it rewrites one entry and verifies again. ## Before you start You need Node 22.13 or later. In a new folder, install the packages and `tsx`, a TypeScript runner: Terminal: ```bash mkdir tamper-evident-audit-log && cd tamper-evident-audit-log npm init -y && npm pkg set type=module npm install @toip-tools/eventlog @toip-tools/trust-core tsx ``` ## The code Save this as `tamper-evident-audit-log.ts`. It is the complete program; the site's checks run it on every build. tamper-evident-audit-log.ts: ```ts // Keep a tamper-evident audit log under a KERI identifier: signed entries, witness receipts, key rotation // with pre-rotation, and an offline bundle anyone can verify. Editing an entry afterwards is detected. import { Controller, MemoryStore, Witness, coldKeysFromSeed, ed25519Signer, exportBundle, localWitnessClient, signerFromIdentity, verifyBundle } from "@toip-tools/eventlog"; import { SystemClock, identityFromSeed } from "@toip-tools/trust-core"; const clock = new SystemClock(); const random = () => crypto.getRandomValues(new Uint8Array(32)); const service = identityFromSeed(random()); // Two independent witnesses. Each receipts the first version of every event it sees. const witnesses = [1, 2].map(() => new Witness({ signer: ed25519Signer(random()), store: new MemoryStore(), clock })); const clients = witnesses.map(localWitnessClient); // Incept a KERI identifier (AID). The cold keys are tomorrow's keys: only their digest is published now. const controller = await Controller.incept({ hot: [signerFromIdentity(service)], cold: coldKeysFromSeed(random(), "service"), witnesses: witnesses.map((w) => w.aid), bt: 1, // events need a receipt from at least one witness bind: service, // links the AID to the service's did:key store: new MemoryStore(), clock, }); console.log("AID:", controller.aid); // A trail is an append-only log owned by the AID. Each entry is a signed header committing to a private body. const trail = await controller.openTrail("admin/actions"); await trail.append({ kind: "user/role-changed", body: { user: "dana", from: "viewer", to: "admin", by: "ops-bot" } }); await trail.append({ kind: "export/started", body: { table: "customers", rows: 1204 } }); // For entries that matter, wait for a witness receipt before acting. await trail.appendWitnessed({ kind: "key/deleted", body: { key: "backup-2025" } }, clients); await controller.rotate(); // switch to the pre-committed keys; the old key can no longer extend the trail await controller.publish(clients); // witnesses receipt everything they haven't seen // Export everything needed to check the log offline, including the entry bodies, and verify it. const bundle = await exportBundle(controller.store, controller.aid, { bodies: "all" }); const check = await verifyBundle(bundle, { expectDid: service.did }); console.log("Bundle verifies:", check.ok); for (const e of check.trails[0].entries) console.log(` #${e.s} ${e.t} ${e.kind || "(trail opened)"}: ${e.status}`); // Quietly rewrite history: change who granted admin. The body no longer matches the digest its entry signed. const edited = structuredClone(bundle); const body = edited.trails[0].bodies!.find((b) => b.user === "dana")!; body.by = "nobody"; const after = await verifyBundle(edited, { expectDid: service.did }); console.log("After editing an entry:", after.ok, after.problems.map((p) => `${p.code}: ${p.message}`)); ``` Run it: Terminal: ```bash npx tsx tamper-evident-audit-log.ts ``` Output: ```text AID: EDKhARiiy2xaTIASYxHuLvkZTkQBOv6Cs0HPDFBeEmPg Bundle verifies: true #0 tin (trail opened): valid #1 ten user/role-changed: valid #2 ten export/started: valid #3 ten key/deleted: valid After editing an entry: false [ 'bodyMismatch: body of entry 1 does not match its SAID' ] ``` 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/tamper-evident-audit-log.ts`, or read it in [`site/examples/guides/tamper-evident-audit-log.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/site/examples/guides/tamper-evident-audit-log.ts). ## How it works - `Controller.incept` creates a KERI identifier (an AID) and its key event log. The KEL's events are KERI 1.0; the package's tests hand them to KERIpy 1.3.6, which computes the same key state. - Pre-rotation: inception publishes only a digest of the *next* keys (`cold`). `rotate()` switches to them, so someone who steals today's key still can't take over the identifier. - A trail is an audit log owned by the AID. Each entry is a small signed header that commits to a private body by its digest. Rotation seals every open trail at its head, so a retired key can't extend it. - `appendWitnessed` waits until enough witnesses (`bt`) have receipted the entry. Witnesses receipt the first version they see at each position, so two different histories can't both collect receipts. - `exportBundle` packs the KEL, the trails, the receipts and the chosen bodies; `verifyBundle` checks all of it offline and returns problems instead of throwing. Here it reports `bodyMismatch` for the edited entry. ## Limits and production notes - Trails are this project's own format, built from KERI's rules and CESR primitives; no other KERI implementation reads them. The KEL itself is plain KERI. - Use persistent stores in production: `JsonFileStore` from `@toip-tools/eventlog/node`, and witnesses run by parties other than the writer. - Delegated identifiers, weighted thresholds and KERI 2.0 are not supported. ## Related ### API used [`Controller`](https://toip.tools/toolkit/eventlog/api/Controller/) · [`Witness`](https://toip.tools/toolkit/eventlog/api/Witness/) · [`MemoryStore`](https://toip.tools/toolkit/eventlog/api/MemoryStore/) · [`coldKeysFromSeed`](https://toip.tools/toolkit/eventlog/api/coldKeysFromSeed/) · [`ed25519Signer`](https://toip.tools/toolkit/eventlog/api/ed25519Signer/) · [`signerFromIdentity`](https://toip.tools/toolkit/eventlog/api/signerFromIdentity/) · [`localWitnessClient`](https://toip.tools/toolkit/eventlog/api/localWitnessClient/) · [`exportBundle`](https://toip.tools/toolkit/eventlog/api/exportBundle/) · [`verifyBundle`](https://toip.tools/toolkit/eventlog/api/verifyBundle/) ### Libraries - [`@toip-tools/eventlog`](https://toip.tools/toolkit/eventlog/): KERI key histories and witnessed audit trails that make tampering detectable. - [`@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 - [KERI key event logs and witnesses](https://toip.tools/concepts/#keri) ### More guides - [Delegate bounded authority to an AI agent with mandates](https://toip.tools/guides/delegate-to-ai-agent/) - [Create a did:key and sign a JSON document in TypeScript](https://toip.tools/guides/did-key-sign-document/) Guide · `@toip-tools/cose` # Sign and verify COSE messages in TypeScript Sign COSE\_Sign1 messages over deterministic CBOR with Ed25519 or a non-extractable WebCrypto P-256 key, and verify them against trusted keys. COSE (CBOR Object Signing and Encryption, RFC 9052) is the compact, binary counterpart of JOSE. A COSE\_Sign1 message is a few dozen bytes plus its payload, which suits sensors, radio links, QR codes and anything else where bytes count. This program signs one sensor reading with two kinds of key, verifies both against a table of trusted keys, then shows a tampered message and a signature by an untrusted key both failing. ## 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 sign-cose && cd sign-cose npm init -y && npm pkg set type=module npm install @toip-tools/cose tsx ``` ## The code Save this as `sign-cose.ts`. It is the complete program; the site's checks run it on every build. sign-cose.ts: ```ts // Sign and verify COSE_Sign1 messages (RFC 9052) over deterministic CBOR, with an Ed25519 seed and with a // non-extractable P-256 WebCrypto key. Runs in Node and in browsers. import { ALG, decodeCbor, encodeCbor, seedSigner, signCose1, verifyCose1, webCryptoSigner, type KeyLookup, type PublicKey } from "@toip-tools/cose"; const kid = (s: string) => new TextEncoder().encode(s); // Two signers: an Ed25519 key from a 32-byte seed, and a P-256 key that WebCrypto never lets you export. const sensor = seedSigner(crypto.getRandomValues(new Uint8Array(32)), kid("sensor-7")); const pair = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]); const gateway = await webCryptoSigner(pair, kid("gateway-1")); console.log("Algorithms:", sensor.alg, "(Ed25519),", gateway.alg, "(ESP256)"); // The payload is CBOR: compact and deterministic, so the same reading always encodes to the same bytes. const reading = encodeCbor({ v: 1, kind: "temp", milliC: 21_375, at: 1_762_416_000 }); const fromSensor = await signCose1(reading, sensor, { contentType: "application/cbor" }); const fromGateway = await signCose1(reading, gateway, { contentType: "application/cbor" }); console.log("Message sizes:", fromSensor.length, "and", fromGateway.length, "bytes"); // The verifier decides which keys it trusts. The kid in the message is only a hint for finding one. const trusted = new Map([["sensor-7", sensor.publicKey], ["gateway-1", gateway.publicKey]]); const lookup: KeyLookup = async (id) => { const key = id && trusted.get(new TextDecoder().decode(id)); return key ? [key] : []; }; const allowedAlgs = [ALG.Ed25519, ALG.ESP256, ALG.ES256]; for (const [who, msg] of [["sensor", fromSensor], ["gateway", fromGateway]] as const) { const r = await verifyCose1(msg, lookup, { allowedAlgs }); console.log(`From the ${who}:`, r.ok ? decodeCbor(r.value.payload) : r.failure); } // One flipped bit in the payload, and verification fails. Use the payload only when ok is true. const tampered = fromSensor.slice(); tampered[tampered.length - 70] ^= 0x01; const r = await verifyCose1(tampered, lookup, { allowedAlgs }); console.log("Tampered:", r.ok ? "verified" : r.failure); // A message signed by a key you don't trust fails too, whatever kid it claims. const stranger = seedSigner(crypto.getRandomValues(new Uint8Array(32)), kid("sensor-7")); const spoofed = await verifyCose1(await signCose1(reading, stranger), lookup, { allowedAlgs }); console.log("Signed by an unknown key claiming sensor-7:", spoofed.ok ? "verified" : spoofed.failure); ``` Run it: Terminal: ```bash npx tsx sign-cose.ts ``` Output: ```text Algorithms: -19 (Ed25519), -9 (ESP256) Message sizes: 136 and 137 bytes From the sensor: { v: 1, at: 1762416000, kind: 'temp', milliC: 21375 } From the gateway: { v: 1, at: 1762416000, kind: 'temp', milliC: 21375 } Tampered: signatureInvalid Signed by an unknown key claiming sensor-7: signatureInvalid ``` 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/sign-cose.ts`, or read it in [`site/examples/guides/sign-cose.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/site/examples/guides/sign-cose.ts). ## How it works - `encodeCbor` writes RFC 8949 Core Deterministic Encoding, so the same value always gives the same bytes. `decodeCbor` insists on that form by default. - `seedSigner` signs with Ed25519 from a 32-byte seed (algorithm `-19`). `webCryptoSigner` wraps a WebCrypto key pair; generated with `extractable: false`, the private key never leaves WebCrypto. A P-256 key signs as ESP256 (`-9`) unless you ask for ES256 (`-7`). - `verifyCose1` takes a `KeyLookup`: you map the message's key ID to keys you already trust. The key ID is only a hint; a message signed by any other key fails. - Pass an explicit `allowedAlgs` list, and use the payload only when `result.ok` is true. Failures are values: `malformed`, `algNotAllowed`, `keyMismatch`, `signatureInvalid` and the WebAuthn checks. ## Limits and production notes - Detached payloads and critical headers are refused as malformed. - `webAuthnSigner` signs with a passkey (algorithm `-65600`); verify those messages with an explicit `webauthnOrigins` list. - The tests reproduce the COSE working group's Ed25519 example byte for byte and verify RFC 9052's ES256 example. ## Related ### API used [`signCose1`](https://toip.tools/toolkit/cose/api/signCose1/) · [`verifyCose1`](https://toip.tools/toolkit/cose/api/verifyCose1/) · [`seedSigner`](https://toip.tools/toolkit/cose/api/seedSigner/) · [`webCryptoSigner`](https://toip.tools/toolkit/cose/api/webCryptoSigner/) · [`encodeCbor`](https://toip.tools/toolkit/cose/api/encodeCbor/) · [`decodeCbor`](https://toip.tools/toolkit/cose/api/decodeCbor/) · [`KeyLookup`](https://toip.tools/toolkit/cose/api/KeyLookup/) · [`ALG`](https://toip.tools/toolkit/cose/api/ALG/) · [`webAuthnSigner`](https://toip.tools/toolkit/cose/api/webAuthnSigner/) ### Libraries - [`@toip-tools/cose`](https://toip.tools/toolkit/cose/): Deterministic CBOR and COSE\_Sign1, with Ed25519, P-256, WebCrypto and passkey signers. ### Concepts - [Decentralized identifiers](https://toip.tools/concepts/#dids) ### More guides - [Send Trust Tasks over LoRa radio](https://toip.tools/guides/trust-tasks-over-lora/) - [Create a did:key and sign a JSON document in TypeScript](https://toip.tools/guides/did-key-sign-document/) Guide · `@toip-tools/mesh-transport`, `@toip-tools/trust-core` # Send Trust Tasks over LoRa radio Send a signed, encrypted Trust Task over LoRa with no internet: compacted, fragmented into radio frames, acknowledged and reassembled. LoRa radios carry a few hundred bytes at a time over kilometers, with no internet. `@toip-tools/mesh-transport` carries TSP over them: the same signed, encrypted Trust Tasks an `Endpoint` sends over a relay, so a field sensor or a door lock can check a credential offline. This program runs on the package's simulated radio, so it needs no hardware: a sensor sends a soil-moisture reading to a base station, which answers with a signed reply. ## Before you start You need Node 22.13 or later. In a new folder, install the packages and `tsx`, a TypeScript runner: Terminal: ```bash mkdir trust-tasks-over-lora && cd trust-tasks-over-lora npm init -y && npm pkg set type=module npm install @toip-tools/mesh-transport @toip-tools/trust-core tsx ``` ## The code Save this as `trust-tasks-over-lora.ts`. It is the complete program; the site's checks run it on every build. trust-tasks-over-lora.ts: ```ts // Send a signed, encrypted Trust Task over LoRa radio, with no internet and no relay. This runs on the // simulated radio from @toip-tools/mesh-transport/sim; real radios use the same MeshTransport. import { MeshTransport, plans, regions } from "@toip-tools/mesh-transport"; import { SimMedium, VirtualScheduler } from "@toip-tools/mesh-transport/sim"; import { Endpoint, ctt1, identityFromSeed } from "@toip-tools/trust-core"; const random = () => crypto.getRandomValues(new Uint8Array(32)); const sensor = identityFromSeed(random()); const base = identityFromSeed(random()); // A simulated LoRa channel: US915, 250-byte frames, and the US airtime budget. const scheduler = new VirtualScheduler(); const medium = new SimMedium({ scheduler, seed: 1 }); const radio = { setting: plans["us915-a"].tx, mtu: 250, budget: regions.us915 }; const sensorMesh = new MeshTransport({ identities: [sensor], links: [medium.node("sensor", radio)], scheduler, random: () => 0.5 }); const baseMesh = new MeshTransport({ identities: [base], links: [medium.node("base", radio)], scheduler, random: () => 0.5 }); medium.connect("sensor", "base"); // in range of each other // The Endpoint is the same one you'd use over a relay. CTT1 is a compact CBOR body that decodes to the // identical signed document, so the Data Integrity proof still verifies. const compact = (mesh: MeshTransport) => (to: string) => (mesh.supportsCompact(to) ? ctt1 : undefined); const sensorEndpoint = new Endpoint({ identity: sensor, transport: sensorMesh, clock: scheduler, bodyCodecFor: compact(sensorMesh) }); const baseEndpoint = new Endpoint({ identity: base, transport: baseMesh, clock: scheduler, bodyCodecFor: compact(baseMesh) }); const READING = { typeUri: "https://example.org/spec/field/reading/0.1", isBearer: false, isProofRequired: true, isRecipientRequired: true, isIssuedAtRequired: true, }; baseEndpoint.handle<{ soilMoisture: number }, { stored: boolean }>(READING, (doc, { sender }) => { console.log(`Base station got ${doc.payload.soilMoisture}% from ${sender === sensor.did ? "the sensor" : sender}`); return { stored: true }; }); try { await sensorMesh.start(); await baseMesh.start(); sensorMesh.addContact(base.did); // a did:key resolves locally: no lookup over the air baseMesh.addContact(sensor.did); // run() advances the simulated radio's clock while the request waits for its signed reply. const reply = await scheduler.run( sensorEndpoint.request<{ soilMoisture: number }, { stored: boolean }>(base.did, READING, { soilMoisture: 31 }, { timeoutMs: 60_000 }), ); console.log("Reply:", reply.payload, "signed by the base:", reply.issuer === base.did); const frames = medium.records(); console.log(`${frames.length} radio frames in both directions, ${frames.reduce((n, f) => n + f.bytes.length, 0)} bytes on the air, largest ${Math.max(...frames.map((f) => f.bytes.length))} bytes`); } finally { sensorEndpoint.close(); baseEndpoint.close(); await sensorMesh.stop(); await baseMesh.stop(); } ``` Run it: Terminal: ```bash npx tsx trust-tasks-over-lora.ts ``` Output: ```text Base station got 31% from the sensor Reply: { stored: true } signed by the base: true 5 radio frames in both directions, 763 bytes on the air, largest 250 bytes ``` 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/trust-tasks-over-lora.ts`, or read it in [`site/examples/guides/trust-tasks-over-lora.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/site/examples/guides/trust-tasks-over-lora.ts). ## How it works - `MeshTransport` implements trust-core's `Transport`, so the `Endpoint`, the message type and the handler are the same as over a relay. The bytes the base station opens are exactly the TSP bytes the sensor sealed. - CTT1 (`ctt1`, in trust-core) is a compact CBOR body that decodes to the identical document, so the Data Integrity proof still verifies. - The TSP envelope names both identifiers in clear, so it never goes on the air. A packet carries the encrypted parts and a fresh 4-byte tag that only the recipient can match to the sender. - Packets are cut into frames no larger than the link's MTU (250 bytes here), acknowledged with a bitmap, and only the missing fragments are resent. A scheduler keeps each link inside its airtime budget (10% of channel time in the US region profile). - `VirtualScheduler.run()` advances simulated time while the request waits. Real radio adapters run in real time and don't need it. ## Limits and production notes - No sealed Trust Task fits in one 250-byte frame; two frames is the floor. - Adapters for real hardware: a LoRaWAN gateway's packet forwarder (`GwmpServer`, Node), a RAK3172 in LoRa P2P mode (`RakP2PLink`), and USB or Web Serial ports. See the [library page](https://toip.tools/toolkit/mesh-transport/). ## Related ### API used [`MeshTransport`](https://toip.tools/toolkit/mesh-transport/api/MeshTransport/) · [`plans`](https://toip.tools/toolkit/mesh-transport/api/plans/) · [`regions`](https://toip.tools/toolkit/mesh-transport/api/regions/) [`Endpoint`](https://toip.tools/toolkit/trust-core/api/Endpoint/) · [`ctt1`](https://toip.tools/toolkit/trust-core/api/ctt1/) ### Libraries - [`@toip-tools/mesh-transport`](https://toip.tools/toolkit/mesh-transport/): Deliver TSP messages over LoRa radio or portable files when the internet is unavailable. - [`@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 - [Send an end-to-end encrypted message with TSP (the Trust Spanning Protocol)](https://toip.tools/guides/tsp-encrypted-message/) - [Sign and verify COSE messages in TypeScript](https://toip.tools/guides/sign-cose/) Guide · `@toip-tools/anon-membership`, `@toip-tools/trust-core` # Prove group membership with zero knowledge (Noir) Prove membership in a group without saying which member, with a Noir circuit and UltraHonk proofs, and count one voice per member with nullifiers. Sometimes the verifier should learn only "this is one of our members", not which one: a whistleblower, a union vote, a forum for licensed nurses. A zero-knowledge membership proof says exactly that. A *nullifier* tied to a scope lets the verifier notice the same member twice in that scope, still without learning who it is. This program enrolls three members with an issuer, has two of them vote, has one vote again, and shows that someone who never enrolled can't produce a proof. ## Before you start You need Node 22.13 or later. In a new folder, install the packages and `tsx`, a TypeScript runner: Terminal: ```bash mkdir zero-knowledge-membership && cd zero-knowledge-membership npm init -y && npm pkg set type=module npm install @toip-tools/anon-membership @toip-tools/trust-core tsx ``` ## The code Save this as `zero-knowledge-membership.ts`. It is the complete program; the site's checks run it on every build. zero-knowledge-membership.ts: ```ts // Prove "I am a member of this group" with a zero-knowledge proof (Noir, UltraHonk), without saying which // member. A scoped nullifier lets the verifier count one voice per member, still without knowing who. import { GroupIssuer, MembershipProver, MembershipVerifier, NullifierBook, acceptMembership, dayOf, enroll, initHashing, memberSecret, membershipInputs, messageOf, scopeOf, treeFromRoot, } from "@toip-tools/anon-membership"; import { Bus, Endpoint, SystemClock, identityFromSeed } from "@toip-tools/trust-core"; await initHashing(); const clock = new SystemClock(); const bus = new Bus(clock); const random = () => crypto.getRandomValues(new Uint8Array(32)); // The issuer (a union, say) keeps the group and decides who may enroll. const union = identityFromSeed(random()); const roster = new Set(); const issuer = new GroupIssuer({ identity: union, clock, name: "members" }); issuer.serve(new Endpoint({ identity: union, transport: bus, clock }), (did) => roster.has(did)); // Each member enrolls a commitment to a secret derived from their own seed. The issuer never sees the secret. const members = [random(), random(), random()].map((seed) => ({ seed, id: identityFromSeed(seed) })); for (const m of members) { roster.add(m.id.did); await enroll(new Endpoint({ identity: m.id, transport: bus, clock }), union.did, issuer.groupId, memberSecret(m.seed, issuer.groupId)); } const { root, snapshot } = issuer.publish(); // a signed root for today const prover = await MembershipProver.create(); const verifier = await MembershipVerifier.create(); const book = new NullifierBook(undefined, { prefix: "Member" }); // labels distinct members "Member A", "Member B", … const scope = scopeOf("survey/v1", union.did, "strike-vote-2026"); // one voice per member in this scope async function vote(seed: Uint8Array, choice: string) { const signal = messageOf("survey/v1", { choice }); // the proof is bound to this exact message const secret = memberSecret(seed, issuer.groupId); const tree = treeFromRoot(root, snapshot); // checks the snapshot against the signed root const { statement, witness } = membershipInputs({ secret, groups: [{ group: issuer.groupId, tree }], scope, signal, today: dayOf(clock.now()) }); const proof = await prover.prove(statement, witness); const r = await acceptMembership(proof, { policy: { groups: [{ group: issuer.groupId, issuer: union.did }], vkHashes: verifier.vkHashes(), maxEpochAge: 3, minSize: 3 }, logs: { [issuer.groupId]: issuer.log() }, verifier, scope, signal, clock, }); if (!r.ok) return console.log(`"${choice}": refused (${r.reason})`); const { label, first } = book.label(issuer.groupId, scope, r.nullifier); console.log(`"${choice}": a member voted (${label}${first ? "" : ", again: count it once"}); proof ${JSON.stringify(proof).length} bytes`); } await vote(members[1].seed, "yes"); await vote(members[2].seed, "no"); await vote(members[1].seed, "yes"); // same member, same scope: same nullifier // Someone who never enrolled can't build a proof for the group. try { await vote(random(), "yes"); } catch (e) { console.log("An outsider:", (e as Error).message); } await prover.destroy(); // the prover and verifier hold worker threads until destroyed await verifier.destroy(); ``` Run it: Terminal: ```bash npx tsx zero-knowledge-membership.ts ``` Output: ```text "yes": a member voted (Member A); proof 20274 bytes "no": a member voted (Member B); proof 20274 bytes "yes": a member voted (Member A, again: count it once); proof 20274 bytes An outsider: not a member: no group holds this secret's leaf ``` 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/zero-knowledge-membership.ts`, or read it in [`site/examples/guides/zero-knowledge-membership.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/site/examples/guides/zero-knowledge-membership.ts). ## How it works - Each member derives a secret from their own seed and enrolls only a commitment to it, over a TSP Trust Task. The issuer adds it to a Merkle tree (depth 20, up to about a million members) and signs one root per day. - The member proves, in a Noir circuit, that their commitment is in a tree under a signed root, and outputs a nullifier: a hash of their secret and the scope. The proof is bound to the exact message (`signal`). - `acceptMembership` checks the proof, the issuer's signed roots, how old the root may be (`maxEpochAge`), the smallest acceptable group (`minSize`), and the scope and signal. `NullifierBook` gives each distinct nullifier a stable label. - Proofs use UltraHonk from Barretenberg in its zero-knowledge mode. The proving setup data is bundled: nothing is downloaded when proving or verifying. ## Limits and production notes - This is experimental cryptography. UltraHonk's zero-knowledge mode is *designed* to be zero-knowledge; the package README knows of no published proof that it is, and Noir says it is not yet for production use. - In a browser, prove in a Web Worker with `@toip-tools/anon-membership/worker`, and serve the page cross-origin isolated (`Cross-Origin-Opener-Policy: same-origin`, `Cross-Origin-Embedder-Policy: require-corp`) for multithreaded proving. The package's tests prove and verify in Chromium. - A small group gives little anonymity: set `minSize` to what your users need. ## Related ### API used [`GroupIssuer`](https://toip.tools/toolkit/anon-membership/api/GroupIssuer/) · [`MembershipProver`](https://toip.tools/toolkit/anon-membership/api/MembershipProver/) · [`MembershipVerifier`](https://toip.tools/toolkit/anon-membership/api/MembershipVerifier/) · [`acceptMembership`](https://toip.tools/toolkit/anon-membership/api/acceptMembership/) · [`NullifierBook`](https://toip.tools/toolkit/anon-membership/api/NullifierBook/) · [`membershipInputs`](https://toip.tools/toolkit/anon-membership/api/membershipInputs/) · [`enroll`](https://toip.tools/toolkit/anon-membership/api/enroll/) · [`memberSecret`](https://toip.tools/toolkit/anon-membership/api/memberSecret/) · [`scopeOf`](https://toip.tools/toolkit/anon-membership/api/scopeOf/) · [`messageOf`](https://toip.tools/toolkit/anon-membership/api/messageOf/) ### Libraries - [`@toip-tools/anon-membership`](https://toip.tools/toolkit/anon-membership/): Prove group membership and attribute requirements without revealing which member you are. - [`@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 - [Selective disclosure and zero-knowledge membership](https://toip.tools/concepts/#zk) ### More guides - [Issue and verify a W3C verifiable credential in TypeScript](https://toip.tools/guides/issue-verify-credential/) - [Delegate bounded authority to an AI agent with mandates](https://toip.tools/guides/delegate-to-ai-agent/) # SDK reference Usage guides and API documentation for every public package entry point. New to the SDK? Follow [Setup](https://toip.tools/docs/#setup) and the [Quickstart](https://toip.tools/quickstart/). This reference covers 16 modules and 525 exports from the current source. Every library is on npm as `@toip-tools/`, for example `npm install @toip-tools/trust-core`. To change the libraries themselves, [work from the source](https://toip.tools/docs/#workspace). ## Libraries [trust-core](https://toip.tools/toolkit/trust-core/) · [relay](https://toip.tools/toolkit/relay/) · [web-vault](https://toip.tools/toolkit/web-vault/) · [mandates](https://toip.tools/toolkit/mandates/) · [anon-membership](https://toip.tools/toolkit/anon-membership/) · [cose](https://toip.tools/toolkit/cose/) · [eventlog](https://toip.tools/toolkit/eventlog/) · [mesh-transport](https://toip.tools/toolkit/mesh-transport/) Use the libraries from the repository. [Setup instructions](https://toip.tools/docs/#setup) 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. API reference · Browser and Node # @toip-tools/trust-core 63 public exports. Module import: ```ts import { type BodyCodec, type BodyContext, BodyError } from "@toip-tools/trust-core"; ``` ## Functions - [`canonicalJson`](https://toip.tools/toolkit/trust-core/api/canonicalJson/) JSON Canonicalization Scheme (RFC 8785) — the byte form eddsa-jcs-2022 and - [`checkStatus`](https://toip.tools/toolkit/trust-core/api/checkStatus/) - [`decodeBody`](https://toip.tools/toolkit/trust-core/api/decodeBody/) Reads a body of any known format, choosing by its first byte. - [`encodeBody`](https://toip.tools/toolkit/trust-core/api/encodeBody/) The body for \`doc\`: \`codec\`'s form when it has one that carries \`doc\` exactly, otherwise JSON. - [`fromB64u`](https://toip.tools/toolkit/trust-core/api/fromB64u/) - [`fromUtf8`](https://toip.tools/toolkit/trust-core/api/fromUtf8/) - [`identityFromSeed`](https://toip.tools/toolkit/trust-core/api/identityFromSeed/) Builds an Ed25519 did:key identity and derives its X25519 encryption keys. - [`isRevokedIn`](https://toip.tools/toolkit/trust-core/api/isRevokedIn/) - [`issueCredential`](https://toip.tools/toolkit/trust-core/api/issueCredential/) Creates and signs a VC-shaped credential with a fresh UUID and the issuer's DID. - [`memoryReplayStore`](https://toip.tools/toolkit/trust-core/api/memoryReplayStore/) A store in memory: survives a new guard, not a new process. - [`openItem`](https://toip.tools/toolkit/trust-core/api/openItem/) Opens the item as \`me\`. - [`ourSpec`](https://toip.tools/toolkit/trust-core/api/ourSpec/) A spec in our own namespace. - [`resealText`](https://toip.tools/toolkit/trust-core/api/resealText/) New text under the item's existing key, for the same readers. - [`resolveDidKey`](https://toip.tools/toolkit/trust-core/api/resolveDidKey/) Resolves an Ed25519 did:key locally and derives its X25519 public key without network access. - [`sealItem`](https://toip.tools/toolkit/trust-core/api/sealItem/) - [`seedFrom`](https://toip.tools/toolkit/trust-core/api/seedFrom/) Derives a reproducible seed by hashing a label with SHA-256. - [`signDocument`](https://toip.tools/toolkit/trust-core/api/signDocument/) Signs a JSON object with an eddsa-jcs-2022 Data Integrity proof. - [`toB64u`](https://toip.tools/toolkit/trust-core/api/toB64u/) base64url without padding, using only APIs present in browsers and Node. - [`utf8`](https://toip.tools/toolkit/trust-core/api/utf8/) - [`verifyCredential`](https://toip.tools/toolkit/trust-core/api/verifyCredential/) Checks a credential's proof and validity window. - [`verifyDocument`](https://toip.tools/toolkit/trust-core/api/verifyDocument/) Verifies a document's Data Integrity proof, allowing five minutes of clock skew. ## Classes - [`BodyError`](https://toip.tools/toolkit/trust-core/api/BodyError/) Why a body could not be read, in the TSP binding's failure terms. - [`Bus`](https://toip.tools/toolkit/trust-core/api/Bus/) An in-memory network that delivers bytes by receiver VID, and lets the UI tap every message. - [`CoarseClock`](https://toip.tools/toolkit/trust-core/api/CoarseClock/) A clock that rounds every reading down to \`granularityMs\` (default one hour), so documents and - [`DemoClock`](https://toip.tools/toolkit/trust-core/api/DemoClock/) A manually advanced clock, so tests are deterministic. - [`Endpoint`](https://toip.tools/toolkit/trust-core/api/Endpoint/) Sends and receives Trust Task documents as real TSP Direct messages. - [`KnowledgeLog`](https://toip.tools/toolkit/trust-core/api/KnowledgeLog/) - [`PersistentReplayGuard`](https://toip.tools/toolkit/trust-core/api/PersistentReplayGuard/) - [`Policies`](https://toip.tools/toolkit/trust-core/api/Policies/) Rego policies compiled to one WebAssembly bundle with \`opa build -t wasm\`, evaluated locally. - [`Refusal`](https://toip.tools/toolkit/trust-core/api/Refusal/) A handler returns this to refuse a request. - [`RelayTransport`](https://toip.tools/toolkit/trust-core/api/RelayTransport/) - [`StatusList`](https://toip.tools/toolkit/trust-core/api/StatusList/) - [`SystemClock`](https://toip.tools/toolkit/trust-core/api/SystemClock/) - [`TaskError`](https://toip.tools/toolkit/trust-core/api/TaskError/) ## Interfaces - [`BodyCodec`](https://toip.tools/toolkit/trust-core/api/BodyCodec/) - [`BodyContext`](https://toip.tools/toolkit/trust-core/api/BodyContext/) - [`Clock`](https://toip.tools/toolkit/trust-core/api/Clock/) Where every component gets the time. - [`Credential`](https://toip.tools/toolkit/trust-core/api/Credential/) - [`CredentialBody`](https://toip.tools/toolkit/trust-core/api/CredentialBody/) - [`Fact`](https://toip.tools/toolkit/trust-core/api/Fact/) What one agent has learned about another, and how. - [`Identity`](https://toip.tools/toolkit/trust-core/api/Identity/) One agent's keys. - [`OutboxItem`](https://toip.tools/toolkit/trust-core/api/OutboxItem/) - [`OutboxStore`](https://toip.tools/toolkit/trust-core/api/OutboxStore/) Where the outbox survives a restart. - [`ReplayRecord`](https://toip.tools/toolkit/trust-core/api/ReplayRecord/) - [`ReplayStore`](https://toip.tools/toolkit/trust-core/api/ReplayStore/) Where the record lives. - [`SealedText`](https://toip.tools/toolkit/trust-core/api/SealedText/) - [`StatusListDoc`](https://toip.tools/toolkit/trust-core/api/StatusListDoc/) A signed revocation list: one bit per credential index. - [`Traffic`](https://toip.tools/toolkit/trust-core/api/Traffic/) One message this endpoint sent or received, for an inspector. - [`Transport`](https://toip.tools/toolkit/trust-core/api/Transport/) - [`WireRecord`](https://toip.tools/toolkit/trust-core/api/WireRecord/) One message on the simulated network, as an observer sees it, plus what its recipient opened. ## Types - [`CredentialCheck`](https://toip.tools/toolkit/trust-core/api/CredentialCheck/) - [`Delivery`](https://toip.tools/toolkit/trust-core/api/Delivery/) Delivery of sealed TSP bytes between VIDs. - [`Handler`](https://toip.tools/toolkit/trust-core/api/Handler/) - [`RelayStatus`](https://toip.tools/toolkit/trust-core/api/RelayStatus/) ## Constants - [`ctt1`](https://toip.tools/toolkit/trust-core/api/ctt1/) CTT1, format 0x01 (mesh design §8.1). - [`CTT1_FORMAT`](https://toip.tools/toolkit/trust-core/api/CTT1_FORMAT/) - [`CTT1_KEYS`](https://toip.tools/toolkit/trust-core/api/CTT1_KEYS/) Object keys written as their index. - [`CTT1_PREFIXES`](https://toip.tools/toolkit/trust-core/api/CTT1_PREFIXES/) String prefixes written as \`\[index, rest\]\`. - [`CTT1_STRINGS`](https://toip.tools/toolkit/trust-core/api/CTT1_STRINGS/) Whole strings written as their index. - [`JSON_FORMAT`](https://toip.tools/toolkit/trust-core/api/JSON_FORMAT/) - [`jsonBody`](https://toip.tools/toolkit/trust-core/api/jsonBody/) The binding's standard JSON body, byte for byte what \`packTrustTask\` seals. - [`MAX_WIRE_BYTES`](https://toip.tools/toolkit/trust-core/api/MAX_WIRE_BYTES/) The relay's per-message limit. - [`OUR_SPEC_BASE`](https://toip.tools/toolkit/trust-core/api/OUR_SPEC_BASE/) Signatures and source documentation are generated from [`packages/trust-core/src/index.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/trust-core/src/index.ts). 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/relay` · v0.1.0 · [Source](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/relay/src/server.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/relay ``` **Runtime:** Node 22.13 or later (it uses \`node:sqlite\`). Clients use \`RelayTransport\` from trust-core, in browsers or Node. Import: ```ts 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`. [`startRelay`](https://toip.tools/toolkit/relay/api/startRelay/) · [`RelayOptions`](https://toip.tools/toolkit/relay/api/RelayOptions/) · [`Relay`](https://toip.tools/toolkit/relay/api/Relay/) ### 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. [`RelayLimits`](https://toip.tools/toolkit/relay/api/RelayLimits/) · [`StoredMessage`](https://toip.tools/toolkit/relay/api/StoredMessage/) · [`MAX_MESSAGE_BYTES`](https://toip.tools/toolkit/relay/api/MAX_MESSAGE_BYTES/) · [`MAX_QUEUED_PER_RECIPIENT`](https://toip.tools/toolkit/relay/api/MAX_QUEUED_PER_RECIPIENT/) ## Example Run a relay, and connect an endpoint to it. site/examples/snippets/relay.ts: ```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); ``` Run from the repository root: ```bash npx tsx --tsconfig site/tsconfig.json site/examples/snippets/relay.ts ``` Output: ```text 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. - [`@toip-tools/relay`](https://toip.tools/toolkit/relay/api/) Node only · 8 exports ## Related ### Guides - [Run a TSP relay: a mailbox for encrypted messages](https://toip.tools/guides/run-tsp-relay/) ### Built on - [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/): Identities, signed and encrypted Trust Tasks over TSP, credentials, status lists and local policy. ### 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. ### Concepts [Concepts](https://toip.tools/concepts/) explains the protocols behind relay; the [FAQ](https://toip.tools/faq/) covers install, runtimes and support. API reference · Node only # @toip-tools/relay 8 public exports. Module import: ```ts import { MAX_MESSAGE_BYTES, MAX_QUEUED_PER_RECIPIENT, QUEUE_TTL_MS } from "@toip-tools/relay"; ``` ## Functions - [`startRelay`](https://toip.tools/toolkit/relay/api/startRelay/) Opens a SQLite-backed WebSocket mailbox at \`/v1\` and starts listening for authenticated clients. ## Interfaces - [`Relay`](https://toip.tools/toolkit/relay/api/Relay/) - [`RelayLimits`](https://toip.tools/toolkit/relay/api/RelayLimits/) - [`RelayOptions`](https://toip.tools/toolkit/relay/api/RelayOptions/) - [`StoredMessage`](https://toip.tools/toolkit/relay/api/StoredMessage/) What the relay learns about one message it stores. ## Constants - [`MAX_MESSAGE_BYTES`](https://toip.tools/toolkit/relay/api/MAX_MESSAGE_BYTES/) - [`MAX_QUEUED_PER_RECIPIENT`](https://toip.tools/toolkit/relay/api/MAX_QUEUED_PER_RECIPIENT/) - [`QUEUE_TTL_MS`](https://toip.tools/toolkit/relay/api/QUEUE_TTL_MS/) Signatures and source documentation are generated from [`packages/relay/src/server.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/relay/src/server.ts). SDK library · Browser and Node # cose Encode deterministic CBOR and sign attached-payload COSE\_Sign1 messages with asynchronous Ed25519, P-256, WebCrypto, or WebAuthn signers. Verification returns a result union for malformed or cryptographically invalid messages. `@toip-tools/cose` · v0.1.0 · [Source](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/cose/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/cose ``` **Runtime:** Browsers and Node. The main entry has no Node-only imports. Import: ```ts import { encodeCbor, decodeCbor, Tagged } from "@toip-tools/cose"; ``` ## Usage ### Encode and decode deterministic CBOR Pass plain objects to `encodeCbor` for text-key maps; use `Map` for integer or mixed keys and `Tagged` for CBOR tags. `decodeCbor` checks deterministic encoding by default. Set `useMaps: true` when every map must remain a `Map`; use `strict: false` only when your input contract accepts other well-formed CBOR encodings. [`encodeCbor`](https://toip.tools/toolkit/cose/api/encodeCbor/) · [`decodeCbor`](https://toip.tools/toolkit/cose/api/decodeCbor/) · [`Tagged`](https://toip.tools/toolkit/cose/api/Tagged/) · [`DecodeCborOptions`](https://toip.tools/toolkit/cose/api/DecodeCborOptions/) ### Sign bytes and verify trusted candidate keys Create `seedSigner(seed, kid)` or await `webCryptoSigner(pair, kid)`, then call `signCose1(payload, signer, options)`. At verification, supply an explicit algorithm allowlist and a `KeyLookup` that returns trusted keys for the `kid` and algorithm. Consume `result.value.payload` only when `result.ok` is true. If using `externalAad`, both sides must supply the same bytes. [`seedSigner`](https://toip.tools/toolkit/cose/api/seedSigner/) · [`webCryptoSigner`](https://toip.tools/toolkit/cose/api/webCryptoSigner/) · [`signCose1`](https://toip.tools/toolkit/cose/api/signCose1/) · [`verifyCose1`](https://toip.tools/toolkit/cose/api/verifyCose1/) · [`KeyLookup`](https://toip.tools/toolkit/cose/api/KeyLookup/) ### Use a passkey for signing Construct `webAuthnSigner` with the registered credential ID, relying-party ID, public key, and key ID. Each signature requests a WebAuthn assertion with user verification. Verify algorithm `-65600` with an explicit `webauthnOrigins` allowlist; successful verification includes origin and authenticator flags in `value.webauthn`. [`webAuthnSigner`](https://toip.tools/toolkit/cose/api/webAuthnSigner/) · [`verifyCose1`](https://toip.tools/toolkit/cose/api/verifyCose1/) · [`WebAuthnInfo`](https://toip.tools/toolkit/cose/api/WebAuthnInfo/) · [`ALG`](https://toip.tools/toolkit/cose/api/ALG/) ## Example A sensor signs a reading as COSE\_Sign1 over deterministic CBOR; anyone with its key verifies it. site/examples/snippets/cose.ts: ```ts import { decodeCbor, encodeCbor, seedSigner, verifyCose1, signCose1 } from "@toip-tools/cose"; const seed = crypto.getRandomValues(new Uint8Array(32)); const sensor = seedSigner(seed, new TextEncoder().encode("sensor-7#0")); // alg -19, Ed25519 const reading = encodeCbor({ v: 1, kind: "temp", milliC: 21_375, at: 1_762_416_000 }); const signed = await signCose1(reading, sensor, { contentType: "application/cbor" }); const result = await verifyCose1(signed, async () => [sensor.publicKey], { allowedAlgs: [-19] }); if (result.ok) console.log("verified", decodeCbor(result.value.payload), `${signed.length} bytes`); else console.log("refused:", result.failure); ``` Run from the repository root: ```bash npx tsx --tsconfig site/tsconfig.json site/examples/snippets/cose.ts ``` Output: ```text verified { v: 1, at: 1762416000, kind: 'temp', milliC: 21375 } 138 bytes ``` ## Lifecycle and persistence - The package does not persist keys or provide a signer disposal method. Own seed storage, WebCrypto key persistence, and the trusted mapping from key IDs to public keys. A key ID is a lookup hint, not a trust decision. - Keep external AAD alongside the protocol context needed to reproduce it; it is bound into the signature but not transmitted in the COSE message. Detached payloads and critical headers are unsupported. ## Error handling ### `malformed / algNotAllowed` `verifyCose1` returns `ok: false` for bad COSE structure, unsupported critical headers or detached payloads, and algorithms outside the supported or configured set. Reject the message. Update an allowlist only after deciding that the algorithm is permitted by your protocol. ### `keyMismatch / signatureInvalid` `keyMismatch` means lookup produced no key of the required curve; `signatureInvalid` means no suitable candidate verified. Check trusted key history and key ID mapping. Verify AAD agreement; never accept the payload merely because it decoded. ### `webauthnChallenge / webauthnOrigin / webauthnFlags` Passkey verification fails if the challenge/type, allowed origin or RP hash, or required user-presence/user-verification flags do not match. Correct registration and origin configuration or obtain a fresh assertion. Keep origin checks enabled. Catch WebAuthn prompt failures and `KeyLookup` exceptions separately; those can reject the promise. ### `CBOR decoding exception` Strict `decodeCbor` throws for noncanonical encoding, duplicate or unordered keys, invalid UTF-8, unsupported values, and trailing bytes. Catch decoding exceptions at input boundaries. Relax strictness only when the surrounding format allows it. ### Limitations - Detached payloads and critical headers. They are refused as malformed. ## 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/cose`](https://toip.tools/toolkit/cose/api/) Browser and Node · 24 exports ## Related ### Guides - [Sign and verify COSE messages in TypeScript](https://toip.tools/guides/sign-cose/) ### Used by these examples - [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 cose; the [FAQ](https://toip.tools/faq/) covers install, runtimes and support. API reference · Browser and Node # @toip-tools/cose 24 public exports. Module import: ```ts import { ALG, type AsyncSigner, type CoseAlg } from "@toip-tools/cose"; ``` ## Functions - [`curveOf`](https://toip.tools/toolkit/cose/api/curveOf/) - [`decodeCbor`](https://toip.tools/toolkit/cose/api/decodeCbor/) - [`encodeCbor`](https://toip.tools/toolkit/cose/api/encodeCbor/) - [`seedSigner`](https://toip.tools/toolkit/cose/api/seedSigner/) An Ed25519 signer from a 32-byte seed. - [`signCose1`](https://toip.tools/toolkit/cose/api/signCose1/) - [`sigStructure`](https://toip.tools/toolkit/cose/api/sigStructure/) The bytes a COSE\_Sign1 signature covers: \`\["Signature1", protected, external\_aad, payload\]\`. - [`verifyCose1`](https://toip.tools/toolkit/cose/api/verifyCose1/) - [`webAuthnSigner`](https://toip.tools/toolkit/cose/api/webAuthnSigner/) A passkey as a signer (alg -65600). - [`webCryptoSigner`](https://toip.tools/toolkit/cose/api/webCryptoSigner/) A signer from a WebCrypto key pair: Ed25519, or ECDSA P-256. ## Classes - [`Tagged`](https://toip.tools/toolkit/cose/api/Tagged/) A wrapper class for representing a CBOR tag with an arbitrary nested value. ## Interfaces - [`AsyncSigner`](https://toip.tools/toolkit/cose/api/AsyncSigner/) A key that may not give up its secret: WebCrypto, WebAuthn, a secure element, or a seed. - [`CoseVerified`](https://toip.tools/toolkit/cose/api/CoseVerified/) - [`DecodeCborOptions`](https://toip.tools/toolkit/cose/api/DecodeCborOptions/) - [`PublicKey`](https://toip.tools/toolkit/cose/api/PublicKey/) - [`SignOptions`](https://toip.tools/toolkit/cose/api/SignOptions/) - [`VerifyOptions`](https://toip.tools/toolkit/cose/api/VerifyOptions/) - [`WebAuthnInfo`](https://toip.tools/toolkit/cose/api/WebAuthnInfo/) ## Types - [`CoseAlg`](https://toip.tools/toolkit/cose/api/CoseAlg/) Ed25519 (-19), ESP256 (-9), EdDSA (-8), ES256 (-7), and the private-use WebAuthn-wrapped ES256 (-65600). - [`CoseFailure`](https://toip.tools/toolkit/cose/api/CoseFailure/) - [`Curve`](https://toip.tools/toolkit/cose/api/Curve/) - [`KeyLookup`](https://toip.tools/toolkit/cose/api/KeyLookup/) Finds the keys that may have signed: for a device, its current key and, around a rotation, the previous one. - [`VerifyResult`](https://toip.tools/toolkit/cose/api/VerifyResult/) - [`WebAuthnGet`](https://toip.tools/toolkit/cose/api/WebAuthnGet/) \`navigator.credentials.get\`, or a stand-in for tests. ## Constants - [`ALG`](https://toip.tools/toolkit/cose/api/ALG/) Signatures and source documentation are generated from [`packages/cose/src/index.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/cose/src/index.ts). SDK library · Browser # web-vault Seal browser account seeds and named blobs using a passkey's PRF output or a passphrase-derived AES-GCM key. Unlocked seeds and keys are available to application code in memory; storage encryption does not make the running tab a protected execution environment. `@toip-tools/web-vault` · v0.1.0 · [Source](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/web-vault/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/web-vault ``` **Runtime:** Browsers. Tests run in Node with stand-ins for storage and the authenticator. Import: ```ts import { createVault, PasskeyUnsupported } from "@toip-tools/web-vault"; ``` ## Usage ### Create, unlock, and back up an account Create one vault per app prefix with `createVault({ prefix, rpName })`. Call `createAccount(name, { kind: 'passkey' })`; handle `PasskeyUnsupported` with an explicit passphrase flow. After reload, select an entry from `accounts()` and call `unlock(account, passphrase?)`. Store `backupCode(unlocked)` securely; restore by checking `seedFromBackup(code)` and passing the resulting seed to `createAccount` with new protection. [`createVault`](https://toip.tools/toolkit/web-vault/api/createVault/) · [`VaultConfig`](https://toip.tools/toolkit/web-vault/api/VaultConfig/) · [`Unlocked`](https://toip.tools/toolkit/web-vault/api/Unlocked/) · [`PasskeyUnsupported`](https://toip.tools/toolkit/web-vault/api/PasskeyUnsupported/) ### Persist account data and non-extractable keys Use the vault's `writeJson`/`readJson` for structured data and `writeBlob`/`readBlob` for bytes. Blob names use lowercase letters, digits, and dashes; `seed`, `accounts`, and `keys` are reserved. Use `putCryptoKey`/`getCryptoKey` for browser `CryptoKey` objects in IndexedDB. For a legacy account with a clear seed, call `protect` before relying on sealed writes. [`Vault`](https://toip.tools/toolkit/web-vault/api/Vault/) · [`Account`](https://toip.tools/toolkit/web-vault/api/Account/) · [`Protection`](https://toip.tools/toolkit/web-vault/api/Protection/) ## Example In a browser: keep an account's identity seed sealed by a passkey, with a passphrase fallback. Typechecked, not run: it needs a browser. site/examples/snippets/web-vault.ts: ```ts import { PasskeyUnsupported, createVault } from "@toip-tools/web-vault"; import { identityFromSeed } from "@toip-tools/trust-core"; const vault = createVault({ prefix: "garden", rpName: "Community Garden" }); export async function signUp(name: string, passphrase: string) { try { return await vault.createAccount(name, { kind: "passkey" }); // Touch ID, Windows Hello, a security key } catch (e) { if (!(e instanceof PasskeyUnsupported)) throw e; return await vault.createAccount(name, { kind: "passphrase", passphrase }); } } export async function signInAgain() { const [account] = vault.accounts(); const unlocked = await vault.unlock(account); // the passkey prompt const me = identityFromSeed(unlocked.seed); await vault.writeJson(unlocked, "credentials", []); // sealed under the same key, bound to this account return { me, backup: vault.backupCode(unlocked) }; // show once; it restores the account elsewhere } ``` ## Lifecycle and persistence - The vault keeps accounts unlocked until `lockAll()` or reload. `lockAll()` clears its internal map; it does not erase seeds or keys retained in application variables. Release those references when locking the UI. - Account records and blobs use localStorage; CryptoKeys use the IndexedDB database `.keys`. Choose a distinct prefix per app on an origin. The vault closes its own IndexedDB connections after transactions. - Await `removeAccount(id)` for attempted CryptoKey cleanup as well as immediate localStorage removal. IndexedDB cleanup failures are swallowed by this method. Removing local records does not delete the authenticator's passkey. A seed backup restores the identity, not saved blobs or separate CryptoKeys. ## Error handling ### `PasskeyUnsupported` Passkey creation or unlocking throws when the authenticator provides no usable PRF secret. `passkeysAvailable()` checks basic browser/domain support, not PRF capability. Offer passphrase protection when creating an account. Distinguish unsupported PRF from user cancellation or other WebAuthn failures. ### `Unlock or blob-open exception` Wrong protection produces an unlock error. `readBlob` and sealed `readJson` throw when data is altered, belongs to another account/name, or cannot decrypt; a missing blob returns `null`. Preserve the stored record for recovery and request valid protection. Do not silently overwrite unreadable data. `readState` deliberately returns `null` for both missing and unreadable state. ### `Validation / storage exception` Invalid prefixes or blob names, a passphrase shorter than eight characters, and writing byte blobs before protection throw. Browser storage and IndexedDB operations can also fail. Validate user input, protect legacy accounts, and report persistence failures. A `null` result from `seedFromBackup` means the code has the wrong prefix or does not decode to a 32-byte seed. ### Limitations - Signing with the passkey itself. The seed is unsealed in memory while the account is open. ## 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/web-vault`](https://toip.tools/toolkit/web-vault/api/) Browser · 10 exports ## Related ### Built on - [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/): Identities, signed and encrypted Trust Tasks over TSP, credentials, status lists and local policy. ### Used by these examples - [Settle](https://toip.tools/examples/#settle): Conditional payments with shared control of escrow. - [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. - [Capture](https://toip.tools/examples/#capture): Verifiable origins for photos and sensor readings. ### Concepts [Concepts](https://toip.tools/concepts/) explains the protocols behind web-vault; the [FAQ](https://toip.tools/faq/) covers install, runtimes and support. API reference · Browser # @toip-tools/web-vault 10 public exports. Module import: ```ts import { type Account, createVault, type Lock } from "@toip-tools/web-vault"; ``` ## Functions - [`createVault`](https://toip.tools/toolkit/web-vault/api/createVault/) Creates a browser account vault with its own storage namespace and unlocked-account cache. - [`passkeysAvailable`](https://toip.tools/toolkit/web-vault/api/passkeysAvailable/) Whether this browser can make passkeys at all. ## Classes - [`PasskeyUnsupported`](https://toip.tools/toolkit/web-vault/api/PasskeyUnsupported/) ## Interfaces - [`Account`](https://toip.tools/toolkit/web-vault/api/Account/) - [`Sealed`](https://toip.tools/toolkit/web-vault/api/Sealed/) - [`Unlocked`](https://toip.tools/toolkit/web-vault/api/Unlocked/) An account whose key is in memory: what a tab needs to act for it. - [`VaultConfig`](https://toip.tools/toolkit/web-vault/api/VaultConfig/) ## Types - [`Lock`](https://toip.tools/toolkit/web-vault/api/Lock/) - [`Protection`](https://toip.tools/toolkit/web-vault/api/Protection/) - [`Vault`](https://toip.tools/toolkit/web-vault/api/Vault/) Signatures and source documentation are generated from [`packages/web-vault/src/index.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/web-vault/src/index.ts). SDK library · Browser and Node # mandates Issue constrained delegation credentials and evaluate actions against a chain using the bundled OPA policy. Decisions are `allow`, `escalate`, or `deny`; the caller remains responsible for enforcing the decision, reserving spend, and recording approval use. `@toip-tools/mandates` · v0.1.0 · [Source](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mandates/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/mandates ``` **Runtime:** Browsers and Node. Import: ```ts import { issueMandate, delegate, narrows } from "@toip-tools/mandates"; ``` ## Usage ### Issue and narrow a delegation chain Create a `StatusRegistry` per issuer, allocate a status entry, and call `issueMandate` with a registered profile, constraints, validity, and delegation limits. A leaf subject can call `delegate(parentChain, identity, clock, options)` to tighten inherited constraints or add new dimensions. Check whether the result contains `mandate` or `problems`; nothing is signed when narrowing fails. Use `checkChain` before accepting a received chain. [`StatusRegistry`](https://toip.tools/toolkit/mandates/api/StatusRegistry/) · [`issueMandate`](https://toip.tools/toolkit/mandates/api/issueMandate/) · [`delegate`](https://toip.tools/toolkit/mandates/api/delegate/) · [`MandateEngine`](https://toip.tools/toolkit/mandates/api/MandateEngine/) · [`registerProfile`](https://toip.tools/toolkit/mandates/api/registerProfile/) ### Decide and reserve an action Load `MandateEngine` once and call `decide` with the root-first chain, presenter DID, action, clock, status resolver, and leaf spend statement. Inspect `outcome` before acting. After `allow`, use `SpendLedger.tryReserve` for an atomic check/reservation of the leaf's own budgets; persist the ledger before performing the external action. Release a reservation only when the action failed before anything moved. [`MandateEngine`](https://toip.tools/toolkit/mandates/api/MandateEngine/) · [`defaultEngine`](https://toip.tools/toolkit/mandates/api/defaultEngine/) · [`SpendLedger`](https://toip.tools/toolkit/mandates/api/SpendLedger/) · [`Decision`](https://toip.tools/toolkit/mandates/api/Decision/) · [`staticStatusResolver`](https://toip.tools/toolkit/mandates/api/staticStatusResolver/) · [`httpStatusResolver`](https://toip.tools/toolkit/mandates/api/httpStatusResolver/) ### Present authority and handle approval Use `present` to sign a presentation with the exact action hash, chain, counterparty audience, approvals, and optional status hints. At the counterparty, call `verifyPresentation` with the authenticated transport sender and your own DID. For `escalate`, obtain `approve` from the designated chain issuer, reevaluate the exact action, and record consumed approval IDs in the ledger. Pass `usedApprovals` when calling `decide` to reject reuse. [`present`](https://toip.tools/toolkit/mandates/api/present/) · [`actionHash`](https://toip.tools/toolkit/mandates/api/actionHash/) · [`approve`](https://toip.tools/toolkit/mandates/api/approve/) · [`verifyApproval`](https://toip.tools/toolkit/mandates/api/verifyApproval/) · [`MandateEngine`](https://toip.tools/toolkit/mandates/api/MandateEngine/) · [`SpendLedger`](https://toip.tools/toolkit/mandates/api/SpendLedger/) ## Example An owner lets a camera sign photos in California only. The engine decides each action. site/examples/snippets/mandates.ts: ```ts import { MandateEngine, StatusRegistry, explain, issueMandate, staticStatusResolver, type Action } from "@toip-tools/mandates"; import { SystemClock, identityFromSeed, seedFrom } from "@toip-tools/trust-core"; const clock = new SystemClock(); const owner = identityFromSeed(seedFrom("example/photo-desk")); const camera = identityFromSeed(seedFrom("example/camera")); const status = new StatusRegistry(owner, clock); const mandate = issueMandate(owner, clock, { subject: camera.did, validUntil: new Date(clock.now() + 7 * 86_400_000).toISOString(), status: status.allocate(), profile: "capture/1", constraints: { actions: { attr: "type", anyOf: ["capture/sign-media"] }, where: { attr: "location", within: ["geo:us/ca/*"], when: ["capture/sign-media"] }, }, delegation: { maxDepth: 0 }, escalation: { approvable: ["where"], approvalTtlSeconds: 600 }, revocation: { maxAgeSeconds: 86_400 }, }); const photo = (location: string): Action => ({ type: "capture/sign-media", profile: "capture/1", id: crypto.randomUUID(), actor: camera.did, at: clock.iso(), attrs: { spend: "0", device: camera.did, media: "sha256:2c26b46b", mediaType: "image/jpeg", location }, }); const engine = await MandateEngine.load(); for (const where of ["geo:us/ca/sf", "geo:us/ny/nyc"]) { const d = await engine.decide({ chain: [mandate], presenter: camera.did, action: photo(where), status: staticStatusResolver([status.sign()]), clock }); console.log(where, d.outcome, explain(d, { name: (did) => (did === owner.did ? "Daily Planet photo desk" : "Dana's camera"), noun: "this photo" }).join(" ")); } ``` Run from the repository root: ```bash npx tsx --tsconfig site/tsconfig.json site/examples/snippets/mandates.ts ``` Output: ```text geo:us/ca/sf allow This photo is within every limit of the chain from Daily Planet photo desk to Dana's camera. geo:us/ny/nyc escalate The location “geo:us/ny/nyc” is outside what Daily Planet photo desk allowed Dana's camera (where). Daily Planet photo desk can approve this photo. ``` ## Lifecycle and persistence - Persist `StatusRegistry.save()` and `SpendLedger.save()` after changes and restore them through their constructors. Re-sign and publish status lists frequently enough for the strictest applicable freshness limit; status resolvers do not publish lists for you. - The engine loads bundled policy WASM from disk in Node or fetches it in a browser; you may supply bytes to `MandateEngine.load`. Retain decisions with their policy hash and inputs when reproducible audit records are needed. No explicit engine disposal API is exposed. - `verifyPresentation` checks approval signatures and bindings but has no `usedApprovals` option. The counterparty must enforce single use separately if required. Spend statements are supplied state, not an independently reconciled balance. ## Error handling ### `delegate: problems` Delegation returns `problems` for broken linkage, malformed dimensions, or widening instead of issuing a child credential. Inspect each reason's code, link, and dimension; revise constraints or obtain a new parent mandate. `issueMandate` instead throws for malformed root input. ### `status.unavailable / status.stale / status.revoked` Decision reasons identify missing, old, or revoked status. Invalid signatures or list ownership produce `status.wrongIssuer`. Refresh from the issuer and retry verification when appropriate. Revocation and structural failures cannot be cleared by an approval. ### `budget.exceeded / approval.used / approval.wrongAction` The engine reports policy reasons in decisions; `tryReserve` returns budget reasons without reserving on failure. Approval checks bind to one exact action and track reuse only when supplied that state. Require `allow`, reserve successfully before acting, and persist approval consumption. Use `explain` to present reason codes; do not treat `escalate` as authorization. ## 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/mandates`](https://toip.tools/toolkit/mandates/api/) Browser and Node · 76 exports ### Bundled assets - `@toip-tools/mandates/policy.wasm` — [source asset](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mandates/policy/policy.wasm) ## Related ### Guides - [Delegate bounded authority to an AI agent with mandates](https://toip.tools/guides/delegate-to-ai-agent/) ### Built on - [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/): Identities, signed and encrypted Trust Tasks over TSP, credentials, status lists and local policy. ### Used by these examples - [Agents](https://toip.tools/examples/#agents): AI agents with identities, spending limits, and accountable actions. - [Capture](https://toip.tools/examples/#capture): Verifiable origins for photos and sensor readings. ### Concepts [Concepts](https://toip.tools/concepts/) explains the protocols behind mandates; the [FAQ](https://toip.tools/faq/) covers install, runtimes and support. API reference · Browser and Node # @toip-tools/mandates 76 public exports. Module import: ```ts import { type Action, actionHash, type Approval } from "@toip-tools/mandates"; ``` ## Functions - [`actionHash`](https://toip.tools/toolkit/mandates/api/actionHash/) SHA-256 of an action's JCS form. - [`approve`](https://toip.tools/toolkit/mandates/api/approve/) Signs an approval of \`action\` under \`chain\`, valid from now for \`ttlSeconds\`. - [`defaultEngine`](https://toip.tools/toolkit/mandates/api/defaultEngine/) The engine with the bundled policy, loaded once. - [`delegate`](https://toip.tools/toolkit/mandates/api/delegate/) Issues a child of the chain's leaf, signed by the leaf's subject. - [`denyApproval`](https://toip.tools/toolkit/mandates/api/denyApproval/) - [`explain`](https://toip.tools/toolkit/mandates/api/explain/) One sentence per reason, then one for the outcome. - [`getProfile`](https://toip.tools/toolkit/mandates/api/getProfile/) - [`grantApproval`](https://toip.tools/toolkit/mandates/api/grantApproval/) - [`hasSentence`](https://toip.tools/toolkit/mandates/api/hasSentence/) - [`httpStatusResolver`](https://toip.tools/toolkit/mandates/api/httpStatusResolver/) Fetches signed lists over HTTP: GET \`${base}/${encodeURIComponent(did)}\` for list "did#…", as the - [`isPattern`](https://toip.tools/toolkit/mandates/api/isPattern/) Exact, or ending in ".\*" or "/\*", with no other "\*". - [`isRevoked`](https://toip.tools/toolkit/mandates/api/isRevoked/) Whether \`list\` revokes \`mandate\`. - [`issueMandate`](https://toip.tools/toolkit/mandates/api/issueMandate/) Signs a root mandate. - [`isUnits`](https://toip.tools/toolkit/mandates/api/isUnits/) A decimal integer string from 0 to 2^53 − 1. - [`jcsHash`](https://toip.tools/toolkit/mandates/api/jcsHash/) SHA-256 of the JCS form of any JSON value, as "sha256:\". - [`linkFacts`](https://toip.tools/toolkit/mandates/api/linkFacts/) - [`mandateHash`](https://toip.tools/toolkit/mandates/api/mandateHash/) SHA-256 of a mandate's JCS form, proof included. - [`narrows`](https://toip.tools/toolkit/mandates/api/narrows/) Whether \`child\` narrows \`parent\`, with the bundled policy. - [`notifyRevoked`](https://toip.tools/toolkit/mandates/api/notifyRevoked/) - [`present`](https://toip.tools/toolkit/mandates/api/present/) Signs a presentation by \`holder\`, the leaf's subject. - [`registerProfile`](https://toip.tools/toolkit/mandates/api/registerProfile/) Adds an action vocabulary. - [`requestApproval`](https://toip.tools/toolkit/mandates/api/requestApproval/) - [`sendMandate`](https://toip.tools/toolkit/mandates/api/sendMandate/) - [`serveMandateTasks`](https://toip.tools/toolkit/mandates/api/serveMandateTasks/) Mounts a handler for each callback given. - [`staticStatusResolver`](https://toip.tools/toolkit/mandates/api/staticStatusResolver/) Lists already in hand, e.g. - [`verifyApproval`](https://toip.tools/toolkit/mandates/api/verifyApproval/) Checks an approval for \`action\` under \`chain\` (§9.2). ## Classes - [`MandateEngine`](https://toip.tools/toolkit/mandates/api/MandateEngine/) - [`SpendLedger`](https://toip.tools/toolkit/mandates/api/SpendLedger/) - [`StatusRegistry`](https://toip.tools/toolkit/mandates/api/StatusRegistry/) One signed revocation list per issuer, with id "\#status". ## Interfaces - [`Action`](https://toip.tools/toolkit/mandates/api/Action/) - [`Approval`](https://toip.tools/toolkit/mandates/api/Approval/) - [`ApprovalDenyPayload`](https://toip.tools/toolkit/mandates/api/ApprovalDenyPayload/) - [`ApprovalGrantPayload`](https://toip.tools/toolkit/mandates/api/ApprovalGrantPayload/) - [`ApprovalRequestPayload`](https://toip.tools/toolkit/mandates/api/ApprovalRequestPayload/) - [`DecideInput`](https://toip.tools/toolkit/mandates/api/DecideInput/) - [`Decision`](https://toip.tools/toolkit/mandates/api/Decision/) - [`DelegateOptions`](https://toip.tools/toolkit/mandates/api/DelegateOptions/) - [`ExplainOptions`](https://toip.tools/toolkit/mandates/api/ExplainOptions/) - [`IssuePayload`](https://toip.tools/toolkit/mandates/api/IssuePayload/) - [`LinkFacts`](https://toip.tools/toolkit/mandates/api/LinkFacts/) One link as the policy sees it: verified facts, no signatures. - [`MandateSubject`](https://toip.tools/toolkit/mandates/api/MandateSubject/) - [`MandateTaskHandlers`](https://toip.tools/toolkit/mandates/api/MandateTaskHandlers/) - [`PolicyInput`](https://toip.tools/toolkit/mandates/api/PolicyInput/) The policy's input (§8.5). - [`PolicyOutput`](https://toip.tools/toolkit/mandates/api/PolicyOutput/) - [`Presentation`](https://toip.tools/toolkit/mandates/api/Presentation/) - [`Profile`](https://toip.tools/toolkit/mandates/api/Profile/) An action vocabulary. - [`Reason`](https://toip.tools/toolkit/mandates/api/Reason/) - [`Requirements`](https://toip.tools/toolkit/mandates/api/Requirements/) - [`RevokedPayload`](https://toip.tools/toolkit/mandates/api/RevokedPayload/) - [`SpendEntry`](https://toip.tools/toolkit/mandates/api/SpendEntry/) - [`SpendLedgerState`](https://toip.tools/toolkit/mandates/api/SpendLedgerState/) - [`SpendStatement`](https://toip.tools/toolkit/mandates/api/SpendStatement/) - [`StatusEntry`](https://toip.tools/toolkit/mandates/api/StatusEntry/) - [`StatusRegistryState`](https://toip.tools/toolkit/mandates/api/StatusRegistryState/) - [`StatusResolver`](https://toip.tools/toolkit/mandates/api/StatusResolver/) ## Types - [`AttrValue`](https://toip.tools/toolkit/mandates/api/AttrValue/) - [`Constraint`](https://toip.tools/toolkit/mandates/api/Constraint/) - [`IssueOptions`](https://toip.tools/toolkit/mandates/api/IssueOptions/) - [`Mandate`](https://toip.tools/toolkit/mandates/api/Mandate/) - [`Op`](https://toip.tools/toolkit/mandates/api/Op/) - [`Outcome`](https://toip.tools/toolkit/mandates/api/Outcome/) - [`Period`](https://toip.tools/toolkit/mandates/api/Period/) - [`SpecPolicy`](https://toip.tools/toolkit/mandates/api/SpecPolicy/) - [`Units`](https://toip.tools/toolkit/mandates/api/Units/) A decimal integer string, at most 2^53 − 1. ## Constants - [`APPROVAL_DENY`](https://toip.tools/toolkit/mandates/api/APPROVAL_DENY/) Approver → delegate. - [`APPROVAL_GRANT`](https://toip.tools/toolkit/mandates/api/APPROVAL_GRANT/) Approver → delegate. - [`APPROVAL_REQUEST`](https://toip.tools/toolkit/mandates/api/APPROVAL_REQUEST/) Delegate → approver. - [`CAPTURE_1`](https://toip.tools/toolkit/mandates/api/CAPTURE_1/) Owner-to-device delegation for projects/capture (agents design §16.3). - [`DEFAULT_REQUIREMENTS`](https://toip.tools/toolkit/mandates/api/DEFAULT_REQUIREMENTS/) - [`MANDATE_ISSUE`](https://toip.tools/toolkit/mandates/api/MANDATE_ISSUE/) Delegator → delegate: a new mandate, with the chain above it. - [`MANDATE_REVOKED`](https://toip.tools/toolkit/mandates/api/MANDATE_REVOKED/) Delegator → delegate: a revocation notice, with the newly signed list. - [`OPS`](https://toip.tools/toolkit/mandates/api/OPS/) - [`PERIODS`](https://toip.tools/toolkit/mandates/api/PERIODS/) - [`POLICY_ID`](https://toip.tools/toolkit/mandates/api/POLICY_ID/) - [`REASON_CODES`](https://toip.tools/toolkit/mandates/api/REASON_CODES/) Every reason code this library produces. - [`SETTLE_1`](https://toip.tools/toolkit/mandates/api/SETTLE_1/) The Settle action vocabulary (agents design §7.4). Signatures and source documentation are generated from [`packages/mandates/src/index.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mandates/src/index.ts). SDK library · Browser and Node # anon-membership Prove membership in one of up to four groups with scoped nullifiers and signal binding. UltraHonk's mode is designed to be zero-knowledge; this is experimental cryptography, and the package README states that Noir is not yet for production use. `@toip-tools/anon-membership` · v0.1.0 · [Source](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/anon-membership/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/anon-membership ``` **Runtime:** Node and browsers, proving in a Web Worker. Proving takes about 0.15 s on an Apple M1 Max; phones aren't measured. Import: ```ts import { GroupIssuer, enroll, ENROLL } from "@toip-tools/anon-membership"; ``` ## Usage ### Enroll members and publish signed roots Await `initHashing()` before constructing trees or computing membership hashes. Create a `GroupIssuer`, register its admission callback with `serve`, and let members derive a per-group `memberSecret` and call `enroll`. Publish a signed root and snapshot once per epoch after enrollment changes. Enrollment after an epoch's publication becomes usable under a later published root. [`initHashing`](https://toip.tools/toolkit/anon-membership/api/initHashing/) · [`GroupIssuer`](https://toip.tools/toolkit/anon-membership/api/GroupIssuer/) · [`memberSecret`](https://toip.tools/toolkit/anon-membership/api/memberSecret/) · [`enroll`](https://toip.tools/toolkit/anon-membership/api/enroll/) · [`ENROLL`](https://toip.tools/toolkit/anon-membership/api/ENROLL/) ### Build and prove the verifier's statement Rebuild a snapshot with `treeFromRoot`, then call `membershipInputs` with the member secret, ordered groups, verifier-agreed scope and signal, current day, and any required leaf fields/predicates. Reuse a `MembershipProver` from `create()` for successive `prove` calls. In a browser, use the `/worker` entry's `MembershipWorkerClient` and `serveMembershipWorker` to keep proving off the page thread. [`treeFromRoot`](https://toip.tools/toolkit/anon-membership/api/treeFromRoot/) · [`membershipInputs`](https://toip.tools/toolkit/anon-membership/api/membershipInputs/) · [`scopeOf`](https://toip.tools/toolkit/anon-membership/api/scopeOf/) · [`messageOf`](https://toip.tools/toolkit/anon-membership/api/messageOf/) · [`dayOf`](https://toip.tools/toolkit/anon-membership/api/dayOf/) · [`MembershipProver`](https://toip.tools/toolkit/anon-membership/api/MembershipProver/) ### Accept a proof and enforce nullifier policy Create a `MembershipVerifier` with accepted artifacts. Call `acceptMembership` with pinned group issuers and verification-key hashes, verified-policy settings, fetched root logs, and a scope/signal you computed independently. It checks root history, freshness, anonymity-set size, statement, and proof. After acceptance, use `NullifierBook.has`/`label` for duplicate or rate-limit handling; acceptance itself does not record nullifier use. [`MembershipVerifier`](https://toip.tools/toolkit/anon-membership/api/MembershipVerifier/) · [`acceptMembership`](https://toip.tools/toolkit/anon-membership/api/acceptMembership/) · [`AcceptPolicy`](https://toip.tools/toolkit/anon-membership/api/AcceptPolicy/) · [`NullifierBook`](https://toip.tools/toolkit/anon-membership/api/NullifierBook/) ## Example A newsroom learns "a current employee of Acme sent this" and nothing about which one. site/examples/snippets/anon-membership.ts: ```ts import { GroupIssuer, MembershipProver, MembershipVerifier, NullifierBook, acceptMembership, dayOf, enroll, initHashing, memberSecret, membershipInputs, messageOf, scopeOf, treeFromRoot, } from "@toip-tools/anon-membership"; import { Bus, Endpoint, SystemClock, identityFromSeed, seedFrom } from "@toip-tools/trust-core"; await initHashing(); const clock = new SystemClock(); const bus = new Bus(clock); const acme = identityFromSeed(seedFrom("example/acme")); const walletSeed = seedFrom("example/employee-wallet"); const employee = identityFromSeed(walletSeed); const newsroom = identityFromSeed(seedFrom("example/newsroom")); // The issuer keeps the group and signs one root per day. It never learns a member's secret. const issuer = new GroupIssuer({ identity: acme, clock, name: "employees" }); issuer.serve(new Endpoint({ identity: acme, transport: bus, clock }), (did) => did === employee.did); // The member enrolls a commitment to a secret derived from their wallet seed. const secret = memberSecret(walletSeed, issuer.groupId); await enroll(new Endpoint({ identity: employee, transport: bus, clock }), acme.did, issuer.groupId, secret); const { root, snapshot } = issuer.publish(); // Proving: membership, a nullifier for this story, bound to this message. const scope = scopeOf("tipline/v1", newsroom.did, "story-41"); const signal = messageOf("tipline/v1", { kind: "tip", body: "sha256:9f86d081" }); const tree = treeFromRoot(root, snapshot); // checks the snapshot against the signed root const { statement, witness } = membershipInputs({ secret, groups: [{ group: issuer.groupId, tree }], scope, signal, today: dayOf(clock.now()) }); const prover = await MembershipProver.create(); const proof = await prover.prove(statement, witness); // The newsroom accepts or refuses, and counts distinct sources by nullifier. const verifier = await MembershipVerifier.create(); const r = await acceptMembership(proof, { policy: { groups: [{ group: issuer.groupId, issuer: acme.did }], vkHashes: verifier.vkHashes(), maxEpochAge: 3, minSize: 1 }, logs: { [issuer.groupId]: issuer.log() }, verifier, scope, signal, clock, }); const book = new NullifierBook(); if (r.ok) console.log("accepted:", book.label(issuer.groupId, scope, r.nullifier)); else console.log("refused:", r.reason); await prover.destroy(); // the prover and verifier hold worker threads until destroyed await verifier.destroy(); ``` Run from the repository root: ```bash npx tsx --tsconfig site/tsconfig.json site/examples/snippets/anon-membership.ts ``` Output: ```text accepted: { label: 'Source A', first: true } ``` ## Lifecycle and persistence - Reuse warmed prover/verifier instances and await their `destroy()` methods when finished to free Barretenberg resources. For a worker client, await `destroy()` to free its backends and terminate the worker. Browser threading depends on cross-origin isolation; otherwise proving uses one thread. - Persist `GroupIssuer.state()`, member secrets and recorded leaf fields, root logs, snapshots, and `NullifierBook.state()` where continuity matters. The issuer defaults to retaining 30 recent snapshots; its state also contains member DIDs and commitments and needs access controls. - The bundled CRS avoids third-party CRS downloads at proving time; artifacts still need to be packaged and served by the app. Pin verification keys out of band. Changing a circuit or acceptance policy requires coordinating member and verifier inputs. ## Error handling ### `MembershipError` `membershipInputs` or `prove` throws when the member is absent or the witness fails membership, validity, predicates, or rate-limit constraints. Check the published snapshot, enrollment leaf fields, current day, and message index. Refresh membership data rather than retrying the same unsatisfiable witness. ### `VerifyResult: malformed / unknownCircuit / statementMismatch / proofInvalid` Low-level `MembershipVerifier.verify` returns `ok: false` for proof shape, unpinned artifact identity, an unexpected statement, or failed cryptographic verification. Reject the proof and preserve the reason for diagnostics. Do not replace a pinned key or expected statement with values supplied by the prover. ### `Acceptance: stale / tooSmall / scope / signal / equivocation` `acceptMembership` can reject a cryptographically valid proof on policy grounds. `equivocation` includes two conflicting signed roots as evidence. Refresh roots for staleness, require the configured minimum set size, and recompute context locally. Preserve equivocation evidence and refuse that acceptance; use the full `AcceptReason` union for remaining failures. ### Limitations - Selective disclosure of individual credential fields (BBS+, SD-JWT). This is group membership only. ## 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/anon-membership`](https://toip.tools/toolkit/anon-membership/api/) Browser and Node · 93 exports - [`@toip-tools/anon-membership/worker`](https://toip.tools/toolkit/anon-membership/api/worker/) Browser · 2 exports ## Related ### Guides - [Prove group membership with zero knowledge (Noir)](https://toip.tools/guides/zero-knowledge-membership/) ### Built on - [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/): Identities, signed and encrypted Trust Tasks over TSP, credentials, status lists and local policy. ### Used by these examples - [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. ### Concepts [Concepts](https://toip.tools/concepts/) explains the protocols behind anon-membership; the [FAQ](https://toip.tools/faq/) covers install, runtimes and support. API reference · Browser and Node # @toip-tools/anon-membership 93 public exports. Module import: ```ts import { type Acceptance, acceptMembership, type AcceptPolicy } from "@toip-tools/anon-membership"; ``` ## Functions - [`acceptMembership`](https://toip.tools/toolkit/anon-membership/api/acceptMembership/) Decides whether a membership proof is acceptable: the circuit is pinned, the groups are the - [`bundledCrs`](https://toip.tools/toolkit/anon-membership/api/bundledCrs/) The CRS bundled in artifacts/crs.json, enough points for every compiled circuit. - [`checkRootLog`](https://toip.tools/toolkit/anon-membership/api/checkRootLog/) Checks a group's root log, oldest first: each document signed by \`expectedIssuer\`, one group, - [`checkStatement`](https://toip.tools/toolkit/anon-membership/api/checkStatement/) Throws if the statement can't be a public input of the circuit. - [`commitmentOf`](https://toip.tools/toolkit/anon-membership/api/commitmentOf/) H(1, secret, groupId). - [`dayFromIso`](https://toip.tools/toolkit/anon-membership/api/dayFromIso/) - [`dayOf`](https://toip.tools/toolkit/anon-membership/api/dayOf/) Days since 1970-01-01 UTC. - [`decodeLeaf`](https://toip.tools/toolkit/anon-membership/api/decodeLeaf/) - [`decodeMembershipCode`](https://toip.tools/toolkit/anon-membership/api/decodeMembershipCode/) The secret, or null for a typo or a code made for another group. - [`decodeStatement`](https://toip.tools/toolkit/anon-membership/api/decodeStatement/) - [`deriveSecret`](https://toip.tools/toolkit/anon-membership/api/deriveSecret/) toField(HMAC-SHA256(seed, utf8(info))). - [`encodeLeaf`](https://toip.tools/toolkit/anon-membership/api/encodeLeaf/) - [`encodeMembershipCode`](https://toip.tools/toolkit/anon-membership/api/encodeMembershipCode/) Crockford base32 of the 31-byte secret and a 2-byte checksum over (groupId, secret), in groups of 4. - [`encodeStatement`](https://toip.tools/toolkit/anon-membership/api/encodeStatement/) - [`enroll`](https://toip.tools/toolkit/anon-membership/api/enroll/) Member side: sends the commitment for \`groupId\` and checks the leaf the issuer recorded. - [`epochIndex`](https://toip.tools/toolkit/anon-membership/api/epochIndex/) The epoch's index: periods since 1970. - [`epochOf`](https://toip.tools/toolkit/anon-membership/api/epochOf/) - [`fieldFromBytes`](https://toip.tools/toolkit/anon-membership/api/fieldFromBytes/) \`toField(SHA-256(bytes))\`: agora's f(bytes). - [`fieldFromBytes32`](https://toip.tools/toolkit/anon-membership/api/fieldFromBytes32/) Reads 32 bytes, big-endian. - [`fieldFromHex`](https://toip.tools/toolkit/anon-membership/api/fieldFromHex/) Reads \`fieldToHex\`'s form. - [`fieldToBytes`](https://toip.tools/toolkit/anon-membership/api/fieldToBytes/) 32 bytes, big-endian. - [`fieldToHex`](https://toip.tools/toolkit/anon-membership/api/fieldToHex/) "0x" and 64 lowercase hex digits, big-endian. - [`findEquivocation`](https://toip.tools/toolkit/anon-membership/api/findEquivocation/) Two validly signed, different roots of one group with the same seq or epoch, if \`docs\` holds any. - [`groupFieldOf`](https://toip.tools/toolkit/anon-membership/api/groupFieldOf/) The group id as the circuit sees it: f(utf8(groupId)), as agora's design writes it. - [`groupIdOf`](https://toip.tools/toolkit/anon-membership/api/groupIdOf/) "\#\". - [`hash`](https://toip.tools/toolkit/anon-membership/api/hash/) Agora's name for the same hash. - [`initHashing`](https://toip.tools/toolkit/anon-membership/api/initHashing/) Loads Barretenberg's WebAssembly once, for hashing. - [`isoFromDay`](https://toip.tools/toolkit/anon-membership/api/isoFromDay/) - [`leafHash`](https://toip.tools/toolkit/anon-membership/api/leafHash/) H(4, commitment, schemaId, validUntilDay, registeredDay, attrs\[0\], attrs\[1\], attrs\[2\], attrs\[3\]). - [`loadArtifacts`](https://toip.tools/toolkit/anon-membership/api/loadArtifacts/) The committed artifacts for a depth. - [`memberSecret`](https://toip.tools/toolkit/anon-membership/api/memberSecret/) One secret per group, so the same person's commitments in two groups differ. - [`membershipInputs`](https://toip.tools/toolkit/anon-membership/api/membershipInputs/) Finds the member's leaf in one of the groups and builds the statement and witness to prove. - [`messageOf`](https://toip.tools/toolkit/anon-membership/api/messageOf/) toField(SHA-256(JCS(\["anon-membership/v1/message", app, value\]))). - [`nodeHash`](https://toip.tools/toolkit/anon-membership/api/nodeHash/) - [`nullifierOf`](https://toip.tools/toolkit/anon-membership/api/nullifierOf/) H(2, secret, scope, k). - [`parseMembershipProof`](https://toip.tools/toolkit/anon-membership/api/parseMembershipProof/) Checks the shape of a proof that arrived from elsewhere. - [`plainLeaf`](https://toip.tools/toolkit/anon-membership/api/plainLeaf/) A leaf with no attributes that never expires: tipline's case, where the root itself is the revocation. - [`poseidon2`](https://toip.tools/toolkit/anon-membership/api/poseidon2/) Poseidon2 over BN254 as Noir's \`Poseidon2::hash(inputs, inputs.length)\` (noir-lang/poseidon v0.4.0). - [`rootDocHash`](https://toip.tools/toolkit/anon-membership/api/rootDocHash/) Hex SHA-256 of the JCS of the signed root document. - [`sameStatement`](https://toip.tools/toolkit/anon-membership/api/sameStatement/) Equal as public inputs: trailing "any" predicates are the same as missing ones. - [`scopeOf`](https://toip.tools/toolkit/anon-membership/api/scopeOf/) toField(SHA-256(JCS(\["anon-membership/v1/scope", app, ...parts\]))). - [`simpleStatement`](https://toip.tools/toolkit/anon-membership/api/simpleStatement/) Defaults that make a statement mean "a current member of this group": tipline's case. - [`snapshotMatches`](https://toip.tools/toolkit/anon-membership/api/snapshotMatches/) - [`toField`](https://toip.tools/toolkit/anon-membership/api/toField/) The first 31 bytes of a 32-byte digest, big-endian. - [`treeFromRoot`](https://toip.tools/toolkit/anon-membership/api/treeFromRoot/) Rebuilds the tree from a snapshot and checks it against the signed root: hash, root, length and size. - [`verifyPath`](https://toip.tools/toolkit/anon-membership/api/verifyPath/) True if \`leaf\` at \`path.index\` with \`path.siblings\` gives \`root\`. - [`vkHashOf`](https://toip.tools/toolkit/anon-membership/api/vkHashOf/) - [`whyUnsatisfied`](https://toip.tools/toolkit/anon-membership/api/whyUnsatisfied/) Why a witness can't satisfy a statement, or null. - [`zeroHashes`](https://toip.tools/toolkit/anon-membership/api/zeroHashes/) Z\[0\] = 0, Z\[i+1\] = H(3, Z\[i\], Z\[i\]), for i up to \`depth\`. ## Classes - [`GroupIssuer`](https://toip.tools/toolkit/anon-membership/api/GroupIssuer/) Runs one group: enrolls members, removes leavers, and signs one root per epoch in a hash chain. - [`GroupTree`](https://toip.tools/toolkit/anon-membership/api/GroupTree/) A fixed-depth, sparse Poseidon2 Merkle tree of leaves. - [`MembershipError`](https://toip.tools/toolkit/anon-membership/api/MembershipError/) Thrown when the witness can't satisfy the statement: not a member, expired, an unmet predicate, and so on. - [`MembershipProver`](https://toip.tools/toolkit/anon-membership/api/MembershipProver/) - [`MembershipVerifier`](https://toip.tools/toolkit/anon-membership/api/MembershipVerifier/) - [`NullifierBook`](https://toip.tools/toolkit/anon-membership/api/NullifierBook/) Turns nullifiers into stable labels, "Source A", "Source B", …, per (group, scope), in order of first sight. ## Interfaces - [`AcceptPolicy`](https://toip.tools/toolkit/anon-membership/api/AcceptPolicy/) What a verifier accepts. - [`BackendOptions`](https://toip.tools/toolkit/anon-membership/api/BackendOptions/) - [`CircuitArtifacts`](https://toip.tools/toolkit/anon-membership/api/CircuitArtifacts/) - [`Crs`](https://toip.tools/toolkit/anon-membership/api/Crs/) Setup data for proving and verifying: uncompressed BN254 G1 points (64 bytes each) and the G2 point. - [`Enrollment`](https://toip.tools/toolkit/anon-membership/api/Enrollment/) What the member's side gets back, decoded. - [`EnrollRequest`](https://toip.tools/toolkit/anon-membership/api/EnrollRequest/) - [`EnrollResponse`](https://toip.tools/toolkit/anon-membership/api/EnrollResponse/) - [`GroupIssuerState`](https://toip.tools/toolkit/anon-membership/api/GroupIssuerState/) - [`GroupRoot`](https://toip.tools/toolkit/anon-membership/api/GroupRoot/) A signed group root. - [`Leaf`](https://toip.tools/toolkit/anon-membership/api/Leaf/) What the issuer puts in the tree for one member. - [`LeafJson`](https://toip.tools/toolkit/anon-membership/api/LeafJson/) - [`MembershipInputsOptions`](https://toip.tools/toolkit/anon-membership/api/MembershipInputsOptions/) - [`MembershipProof`](https://toip.tools/toolkit/anon-membership/api/MembershipProof/) A proof in a JSON-safe form, as it travels. - [`MerklePath`](https://toip.tools/toolkit/anon-membership/api/MerklePath/) A leaf's index and its siblings, leaf level first. - [`NullifierBookState`](https://toip.tools/toolkit/anon-membership/api/NullifierBookState/) - [`ProveProgress`](https://toip.tools/toolkit/anon-membership/api/ProveProgress/) - [`Statement`](https://toip.tools/toolkit/anon-membership/api/Statement/) The public half of a proof. - [`StatementJson`](https://toip.tools/toolkit/anon-membership/api/StatementJson/) - [`Witness`](https://toip.tools/toolkit/anon-membership/api/Witness/) The private half. ## Types - [`Acceptance`](https://toip.tools/toolkit/anon-membership/api/Acceptance/) - [`AcceptReason`](https://toip.tools/toolkit/anon-membership/api/AcceptReason/) - [`CrsSource`](https://toip.tools/toolkit/anon-membership/api/CrsSource/) Where the prover gets its CRS. - [`Depth`](https://toip.tools/toolkit/anon-membership/api/Depth/) - [`Field`](https://toip.tools/toolkit/anon-membership/api/Field/) An element of BN254's scalar field Fr, the native field of Noir on Barretenberg. - [`LeafFields`](https://toip.tools/toolkit/anon-membership/api/LeafFields/) - [`Predicate`](https://toip.tools/toolkit/anon-membership/api/Predicate/) - [`RootLogCheck`](https://toip.tools/toolkit/anon-membership/api/RootLogCheck/) - [`ScopePart`](https://toip.tools/toolkit/anon-membership/api/ScopePart/) One part of a scope: a string, an integer, or a field (written as hex). - [`VerifyResult`](https://toip.tools/toolkit/anon-membership/api/VerifyResult/) ## Constants - [`CIRCUIT_ID`](https://toip.tools/toolkit/anon-membership/api/CIRCUIT_ID/) The circuit the library proves with. - [`DAY_SECONDS`](https://toip.tools/toolkit/anon-membership/api/DAY_SECONDS/) - [`DEPTH`](https://toip.tools/toolkit/anon-membership/api/DEPTH/) The compiled circuit's depth. - [`ENROLL`](https://toip.tools/toolkit/anon-membership/api/ENROLL/) ourSpec("anon-membership/enroll"): member DID → issuer, request and response. - [`FIELD_MODULUS`](https://toip.tools/toolkit/anon-membership/api/FIELD_MODULUS/) - [`MAX_LIMIT`](https://toip.tools/toolkit/anon-membership/api/MAX_LIMIT/) Rate-limit indexes are below this. - [`NEVER_EXPIRES`](https://toip.tools/toolkit/anon-membership/api/NEVER_EXPIRES/) The largest day number, for leaves that never expire. - [`PROOF_SYSTEM`](https://toip.tools/toolkit/anon-membership/api/PROOF_SYSTEM/) UltraHonk in its zero-knowledge mode, with a Poseidon2 transcript. - [`TAG`](https://toip.tools/toolkit/anon-membership/api/TAG/) Domain tags, the first input of each hash. Signatures and source documentation are generated from [`packages/anon-membership/src/index.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/anon-membership/src/index.ts). API reference · Browser # @toip-tools/anon-membership/worker 2 public exports. Module import: ```ts import { MembershipWorkerClient, serveMembershipWorker } from "@toip-tools/anon-membership/worker"; ``` ## Functions - [`serveMembershipWorker`](https://toip.tools/toolkit/anon-membership/api/worker/serveMembershipWorker/) Call once at the top of a worker script. ## Classes - [`MembershipWorkerClient`](https://toip.tools/toolkit/anon-membership/api/worker/MembershipWorkerClient/) The page's side of a worker running serveMembershipWorker. Signatures and source documentation are generated from [`packages/anon-membership/src/worker.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/anon-membership/src/worker.ts). SDK library · Browser and Node # eventlog Maintain a signed key-event log and content-addressed trails with rotations, witness receipts, and duplicity evidence. The main entry is browser-safe; file persistence and Node HTTP helpers are exported from `@toip-tools/eventlog/node`. `@toip-tools/eventlog` · v0.1.0 · [Source](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/eventlog/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/eventlog ``` **Runtime:** Browsers and Node. A file store and an HTTP witness are in the Node entry. Import: ```ts import { Controller, Trail, MemoryStore } from "@toip-tools/eventlog"; ``` ## Usage ### Create a controller and append a witnessed trail entry Choose hot signers, commit future keys using `coldKeysFromSeed` or explicit next-key digests, and call `Controller.incept` with a store and clock. Open a trail with `openTrail(purpose)`. Use `appendWitnessed` when an external action must wait for receipts; ordinary `append` only signs and stores locally. Publish to witness clients and inspect missing receipts and evidence. [`Controller`](https://toip.tools/toolkit/eventlog/api/Controller/) · [`coldKeysFromSeed`](https://toip.tools/toolkit/eventlog/api/coldKeysFromSeed/) · [`Trail`](https://toip.tools/toolkit/eventlog/api/Trail/) · [`MemoryStore`](https://toip.tools/toolkit/eventlog/api/MemoryStore/) · [`httpWitnessClient`](https://toip.tools/toolkit/eventlog/api/httpWitnessClient/) ### Rotate keys and recover a log Call `Controller.rotate` with the committed future signers or retained cold keys. Rotation seals trail heads automatically. For recovery, `cutAfter` cuts later trail entries, and `supersede` can replace interaction events with a rotation. Persist newly active signers from `signers()` securely. Passing `next: []` abandons the identifier and prevents further controller events. [`Controller`](https://toip.tools/toolkit/eventlog/api/Controller/) · [`RotateOptions`](https://toip.tools/toolkit/eventlog/api/RotateOptions/) · [`nextKeyDigest`](https://toip.tools/toolkit/eventlog/api/nextKeyDigest/) · [`keyQb64`](https://toip.tools/toolkit/eventlog/api/keyQb64/) ### Verify history and disclose selected content Run `verifyKel` and `verifyTrail` on received history, then inspect problems and witness status. Use `checkTrailRef` with a witness client to verify a referenced entry, or `verifySignature` to distinguish a valid signature from its current/retired and anchored status. Export selected bodies or entries with `exportBundle` and verify received bundles with `verifyBundle`. A `Watcher` can ingest first-seen copies and poll witnesses for conflicting histories. [`verifyKel`](https://toip.tools/toolkit/eventlog/api/verifyKel/) · [`verifyTrail`](https://toip.tools/toolkit/eventlog/api/verifyTrail/) · [`checkTrailRef`](https://toip.tools/toolkit/eventlog/api/checkTrailRef/) · [`verifySignature`](https://toip.tools/toolkit/eventlog/api/verifySignature/) · [`exportBundle`](https://toip.tools/toolkit/eventlog/api/exportBundle/) · [`verifyBundle`](https://toip.tools/toolkit/eventlog/api/verifyBundle/) · [`Watcher`](https://toip.tools/toolkit/eventlog/api/Watcher/) ## Example An agent keeps a witnessed audit trail under a KERI identifier; a reviewer verifies the bundle. site/examples/snippets/eventlog.ts: ```ts import { Controller, MemoryStore, Witness, coldKeysFromSeed, ed25519Signer, exportBundle, localWitnessClient, signerFromIdentity, verifyBundle } from "@toip-tools/eventlog"; import { SystemClock, identityFromSeed, seedFrom } from "@toip-tools/trust-core"; const clock = new SystemClock(); const agent = identityFromSeed(seedFrom("example/agent")); const witnesses = [1, 2].map((n) => new Witness({ signer: ed25519Signer(seedFrom(`example/witness/${n}`)), store: new MemoryStore(), clock })); const controller = await Controller.incept({ hot: [signerFromIdentity(agent)], // signs today cold: coldKeysFromSeed(seedFrom("example/agent/rotation"), "agent"), // pre-rotation: tomorrow's keys, committed now witnesses: witnesses.map((w) => w.aid), bt: 1, bind: agent, // links the AID to the agent's did:key store: new MemoryStore(), clock, }); const clients = witnesses.map(localWitnessClient); const trail = await controller.openTrail("agent/actions"); await trail.append({ kind: "agent/tool-call", body: { tool: "search", query: "bike shops near me" } }); await trail.appendWitnessed({ kind: "agent/payment", body: { to: "did:key:z6Mk…", cents: 4500 } }, clients); // before paying: wait for a receipt await controller.rotate(); // new keys; every open trail is sealed at its head await controller.publish(clients); // witnesses receipt everything they haven't seen const bundle = await exportBundle(controller.store, controller.aid); const check = await verifyBundle(bundle, { expectDid: agent.did }); console.log(check.ok ? "bundle verifies" : check.problems); ``` Run from the repository root: ```bash npx tsx --tsconfig site/tsconfig.json site/examples/snippets/eventlog.ts ``` Output: ```text bundle verifies ``` ## Lifecycle and persistence - Persist logs, bodies, receipts, and evidence through a `LogStore`. `MemoryStore.dump()` can be restored through its constructor, but it is not durable by itself. Node's `JsonFileStore` batches writes; call `flush()` or `close()` at shutdown to write pending changes. - Keep cold-key material separate from current hot keys. `Controller.load` re-verifies stored logs; supplying hot keys supports appending and interacting, while rotation additionally needs committed future signers or matching cold keys. - `Trail.close()` records a signed end-of-trail event. It is a protocol operation, not a resource cleanup call. `Watcher.poll()` is caller-driven; own and cancel any application polling timer and close HTTP servers/file stores that you create. ## Error handling ### `WitnessError` `appendWitnessed` throws if fewer than `max(1, bt)` witness receipts are held. The newly appended entry remains in the local log, pending. Do not perform the dependent external action. Inspect `details.missing`, retry publishing the existing entry, and reconcile its receipt state instead of appending a duplicate action. ### `Problem: unsupported / signatureInvalid / notWitnessed` Verification reports structured problems with a code, message, and optional log/sequence location. Unsupported protocol features are identified separately from invalid signatures or missing witness thresholds. Check result problems before accepting history. Fetch missing receipts or use a compatible implementation for unsupported features; do not bypass signature checks. ### `SubmitResult: duplicity / unknownController / clockSkew / invalid` Witness submission can refuse history and may return receipts for messages accepted before the refusal. Duplicity may include the first-seen conflicting stream. Retain valid partial receipts and conflicting evidence. Supply the controller KEL before its trails, correct clock skew, and investigate conflicts before acting. `Controller.publish` collects such failures in its report. ## 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/eventlog`](https://toip.tools/toolkit/eventlog/api/) Browser and Node · 133 exports - [`@toip-tools/eventlog/node`](https://toip.tools/toolkit/eventlog/api/node/) Node only · 3 exports ## Related ### Guides - [Keep a tamper-evident audit log with KERI key event logs](https://toip.tools/guides/tamper-evident-audit-log/) ### Built on - [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/): Identities, signed and encrypted Trust Tasks over TSP, credentials, status lists and local policy. ### Used by these examples - [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. ### Concepts [Concepts](https://toip.tools/concepts/) explains the protocols behind eventlog; the [FAQ](https://toip.tools/faq/) covers install, runtimes and support. API reference · Browser and Node # @toip-tools/eventlog 133 public exports. Module import: ```ts import { aidDid, aidOfDid, aidOfDidKey } from "@toip-tools/eventlog"; ``` ## Functions - [`aidDid`](https://toip.tools/toolkit/eventlog/api/aidDid/) The DID we use for an AID. - [`aidOfDid`](https://toip.tools/toolkit/eventlog/api/aidOfDid/) - [`aidOfDidKey`](https://toip.tools/toolkit/eventlog/api/aidOfDidKey/) - [`anchoredIn`](https://toip.tools/toolkit/eventlog/api/anchoredIn/) Where a digest is anchored: KEL seals {d}, and trail entries' \`a\` or \`x\`. - [`attachmentsOf`](https://toip.tools/toolkit/eventlog/api/attachmentsOf/) The CESR text of a message's attachments. - [`bindingDigest`](https://toip.tools/toolkit/eventlog/api/bindingDigest/) The binding's digest: Blake3-256 of JCS of the document with its proof. - [`bindingSeal`](https://toip.tools/toolkit/eventlog/api/bindingSeal/) - [`buildIcp`](https://toip.tools/toolkit/eventlog/api/buildIcp/) - [`buildIxn`](https://toip.tools/toolkit/eventlog/api/buildIxn/) - [`buildRct`](https://toip.tools/toolkit/eventlog/api/buildRct/) - [`buildRot`](https://toip.tools/toolkit/eventlog/api/buildRot/) - [`buildTcl`](https://toip.tools/toolkit/eventlog/api/buildTcl/) - [`buildTen`](https://toip.tools/toolkit/eventlog/api/buildTen/) - [`buildTin`](https://toip.tools/toolkit/eventlog/api/buildTin/) - [`buildTrc`](https://toip.tools/toolkit/eventlog/api/buildTrc/) A receipt or endorsement of a trail message. - [`checkBody`](https://toip.tools/toolkit/eventlog/api/checkBody/) - [`checkTrailRef`](https://toip.tools/toolkit/eventlog/api/checkTrailRef/) Checks a trailRef {i, s, d} against a witness: fetches the entry, its receipts and the controller's KEL, and verifies them. - [`coldKeysFromSeed`](https://toip.tools/toolkit/eventlog/api/coldKeysFromSeed/) Key set j is HKDF-SHA256(seed, salt "zk-toip/eventlog", info "\ API reference · Node only # @toip-tools/eventlog/node 3 public exports. Module import: ```ts import { JsonFileStore, serveHttp, startWitness } from "@toip-tools/eventlog/node"; ``` ## Functions - [`serveHttp`](https://toip.tools/toolkit/eventlog/api/node/serveHttp/) - [`startWitness`](https://toip.tools/toolkit/eventlog/api/node/startWitness/) Starts a witness as a Node HTTP service, keeping its logs in a JSON file. ## Classes - [`JsonFileStore`](https://toip.tools/toolkit/eventlog/api/node/JsonFileStore/) Signatures and source documentation are generated from [`packages/eventlog/src/node/index.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/eventlog/src/node/index.ts). SDK library · Browser and Node # mesh-transport Carry sealed TSP bytes through simulated or LoRa links and courier bundles using trust-core's `Transport` contract. Simulation tests cover delivery and adapters; the README still identifies real-radio limits, sync-word format, and turnaround timing as assumptions to verify on hardware. `@toip-tools/mesh-transport` · v0.1.0 · [Source](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mesh-transport/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/mesh-transport ``` **Runtime:** Browsers and Node. The \`/gwmp\`, \`/detect\` and \`/node\` entry points are Node only. Import: ```ts import { MeshTransport, MeshGateway, ChallengeBeacon } from "@toip-tools/mesh-transport"; ``` ## Usage ### Run a Trust Task over simulated radio Import `SimMedium` from `/sim`, create a `VirtualScheduler`, connect named nodes, and construct `MeshTransport` with local identities and links. Start it and pass it to trust-core's `Endpoint`; advance virtual time with `scheduler.run(requestPromise)`. Select trust-core's `ctt1` body codec only when `supportsCompact(peer)` is true, and size request deadlines using `suggestedTimeoutMs`. [`MeshTransport`](https://toip.tools/toolkit/mesh-transport/api/MeshTransport/) · [`VirtualScheduler`](https://toip.tools/toolkit/mesh-transport/api/VirtualScheduler/) · [`plans`](https://toip.tools/toolkit/mesh-transport/api/plans/) · [`regions`](https://toip.tools/toolkit/mesh-transport/api/regions/) · [`MeshOptions`](https://toip.tools/toolkit/mesh-transport/api/MeshOptions/) ### Configure a real link and diagnose delivery Choose matching regional/channel plans for both ends. Import `RakP2PLink` from `/rak` with a `/serial` Web Serial port or `/node` serial wrapper; Node's `/node` or `/gwmp` entry provides `GwmpServer` for a gateway packet forwarder. Monitor link state, mesh `onEvent`, and `stats()`. A GWMP link is not ready to send until the gateway has sent PULL\_DATA, even though `open()` resolves. [`Link`](https://toip.tools/toolkit/mesh-transport/api/Link/) · [`LinkState`](https://toip.tools/toolkit/mesh-transport/api/LinkState/) · [`plans`](https://toip.tools/toolkit/mesh-transport/api/plans/) · [`MeshEvent`](https://toip.tools/toolkit/mesh-transport/api/MeshEvent/) · [`MeshStats`](https://toip.tools/toolkit/mesh-transport/api/MeshStats/) · [`AirtimeBudget`](https://toip.tools/toolkit/mesh-transport/api/AirtimeBudget/) ### Hand messages to a gateway or courier Create `MeshGateway` with a mesh identity, relay transport, and custody store, then call `start()`. A custody receipt means the gateway or its relay outbox has responsibility, not that the recipient opened the task. For manual delivery, export pending messages with `mesh.exportBundle({ sealTo: courierDid })`, open them with `openBundle(bytes, courier)`, and pass items to `postBundle` through a relay. [`MeshGateway`](https://toip.tools/toolkit/mesh-transport/api/MeshGateway/) · [`GatewayStore`](https://toip.tools/toolkit/mesh-transport/api/GatewayStore/) · [`exportBundle`](https://toip.tools/toolkit/mesh-transport/api/exportBundle/) · [`openBundle`](https://toip.tools/toolkit/mesh-transport/api/openBundle/) · [`postBundle`](https://toip.tools/toolkit/mesh-transport/api/postBundle/) ## Example A signed, encrypted Trust Task crosses a simulated radio link, with no relay. site/examples/snippets/mesh-transport.ts: ```ts import { MeshTransport, plans, regions } from "@toip-tools/mesh-transport"; import { SimMedium, VirtualScheduler } from "@toip-tools/mesh-transport/sim"; import { Endpoint, ctt1, identityFromSeed, ourSpec, seedFrom } from "@toip-tools/trust-core"; // Demo seeds make identities repeatable. Real devices need securely generated seeds. const guest = identityFromSeed(seedFrom("mesh-example/guest")); const door = identityFromSeed(seedFrom("mesh-example/door")); const scheduler = new VirtualScheduler(); const medium = new SimMedium({ scheduler, seed: 1 }); const radio = { setting: plans["us915-a"].tx, mtu: 250, budget: regions.us915 }; // Fixed radio jitter makes the simulation's scheduling repeatable. const guestMesh = new MeshTransport({ identities: [guest], links: [medium.node("guest", radio)], scheduler, random: () => 0.5, }); const doorMesh = new MeshTransport({ identities: [door], links: [medium.node("door", radio)], scheduler, random: () => 0.5, }); medium.connect("guest", "door"); // Both radios are in range; the default is no loss. // Endpoint still signs and seals the request. CTT1 compacts its signed body; // MeshTransport fragments the sealed envelope and reassembles it at the door. const guestEndpoint = new Endpoint({ identity: guest, transport: guestMesh, clock: scheduler, bodyCodecFor: (to) => guestMesh.supportsCompact(to) ? ctt1 : undefined, }); const doorEndpoint = new Endpoint({ identity: door, transport: doorMesh, clock: scheduler, bodyCodecFor: (to) => doorMesh.supportsCompact(to) ? ctt1 : undefined, }); const CHECK = ourSpec("example/door/check"); doorEndpoint.handle<{ challenge: string }, { accepted: boolean }>(CHECK, (doc) => ({ accepted: doc.payload.challenge === "9f3a", })); try { await guestMesh.start(); await doorMesh.start(); // Resolve the peer's did:key locally. The first packet introduces the sender. guestMesh.addContact(door.did); doorMesh.addContact(guest.did); // run() advances virtual radio timers while the request waits for its reply. // Real radio adapters use real time; they do not need VirtualScheduler.run(). const reply = await scheduler.run(guestEndpoint.request<{ challenge: string }, { accepted: boolean }>( door.did, CHECK, { challenge: "9f3a" }, { timeoutMs: 60_000 }, )); console.log("Challenge accepted:", reply.payload.accepted); console.log("Reply signed by the door:", reply.issuer === door.did); console.log("Every radio frame fits the MTU:", medium.records().every((frame) => frame.bytes.length <= radio.mtu)); } finally { guestEndpoint.close(); doorEndpoint.close(); await guestMesh.stop(); await doorMesh.stop(); } ``` Run from the repository root: ```bash npx tsx --tsconfig site/tsconfig.json site/examples/snippets/mesh-transport.ts ``` Output: ```text Challenge accepted: true Reply signed by the door: true Every radio frame fits the MTU: true ``` ## Lifecycle and persistence - Call `Endpoint.close()` to detach its application receiver, stop `ChallengeBeacon` and `MeshGateway` timers/handlers, then await `MeshTransport.stop()` to cancel mesh timers, unsubscribe link listeners, and close owned links. Gateway stop does not stop the mesh or relay transport; stop those separately. - Contacts, outbox, and gateway custody records default to memory. Supply durable stores, or Node's `/node` file stores, to retain routing/introduction and delivery state across restarts. Pair the endpoint with a persistent replay guard when duplicate execution must survive reboot. - Keep queued and custody items until your application's reconciliation policy resolves them. Check `pending()` and receipt/application responses; a transport return value is not proof that an external action occurred. Hardware adapters require deployment verification; Bluetooth, RNode link behavior, DOWN/PUBLIC delivery, and reliable-link mode are not implemented. ## Error handling ### `Delivery: undelivered / queued` `post` returns `undelivered` for unusable local identities, unsplittable or mismatched TSP envelopes, unresolved recipients without a gateway, oversized packets, or explicit delivery refusal. Unconfirmed transmissions can remain `queued` for retry. Check local identity/contact keys, packet size, route, and link state. Use transport events and application replies to distinguish refusal from a message still awaiting delivery. ### `MeshEvent: dropped` Drop reasons include `regulatory`, `send-failed`, `incomplete`, `signature`, and `intro-refused`; counts appear in `stats().dropped`. Investigate airtime/channel configuration and hardware errors for send failures, loss/MTU for incomplete packets, and peer keys/admission policy for signature or introduction failures. Never bypass airtime limits to force a retry. ### `Bundle-open exception` `openBundle` throws for malformed/truncated bundles or a sealed bundle without the correct courier identity. `postBundle` reports counts of accepted and refused items. Keep the original bundle, use the intended courier key, and inspect refused counts before considering the handoff complete. ### Limitations - Hiding where you are. A transmitting radio can be located. - Large payloads: a radio frame holds about 250 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/mesh-transport`](https://toip.tools/toolkit/mesh-transport/api/) Browser and Node · 70 exports - [`@toip-tools/mesh-transport/sim`](https://toip.tools/toolkit/mesh-transport/api/sim/) Browser and Node · 9 exports - [`@toip-tools/mesh-transport/serial`](https://toip.tools/toolkit/mesh-transport/api/serial/) Browser and Node · 3 exports - [`@toip-tools/mesh-transport/rak`](https://toip.tools/toolkit/mesh-transport/api/rak/) Browser and Node · 2 exports - [`@toip-tools/mesh-transport/gwmp`](https://toip.tools/toolkit/mesh-transport/api/gwmp/) Node only · 5 exports - [`@toip-tools/mesh-transport/detect`](https://toip.tools/toolkit/mesh-transport/api/detect/) Node only · 6 exports - [`@toip-tools/mesh-transport/node`](https://toip.tools/toolkit/mesh-transport/api/node/) Node only · 18 exports ## Related ### Guides - [Send Trust Tasks over LoRa radio](https://toip.tools/guides/trust-tasks-over-lora/) ### Built on - [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/): Identities, signed and encrypted Trust Tasks over TSP, credentials, status lists and local policy. ### Used by these examples - [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 mesh-transport; the [FAQ](https://toip.tools/faq/) covers install, runtimes and support. API reference · Browser and Node # @toip-tools/mesh-transport 70 public exports. Module import: ```ts import { ackMac, addressTag, AirtimeBudget } from "@toip-tools/mesh-transport"; ``` ## Functions - [`ackMac`](https://toip.tools/toolkit/mesh-transport/api/ackMac/) An ACK's MAC, under k(R→S). - [`addressTag`](https://toip.tools/toolkit/mesh-transport/api/addressTag/) The 4-byte address tag of a packet from S to R, under k(S→R). - [`custodyMessage`](https://toip.tools/toolkit/mesh-transport/api/custodyMessage/) What a gateway signs in a custody receipt. - [`decodeFrame`](https://toip.tools/toolkit/mesh-transport/api/decodeFrame/) - [`decodePacket`](https://toip.tools/toolkit/mesh-transport/api/decodePacket/) - [`encodeFrame`](https://toip.tools/toolkit/mesh-transport/api/encodeFrame/) - [`encodePacket`](https://toip.tools/toolkit/mesh-transport/api/encodePacket/) - [`estimate`](https://toip.tools/toolkit/mesh-transport/api/estimate/) Frames and airtime (frames plus one ACK) to send a packet once over \`link\`. - [`exportBundle`](https://toip.tools/toolkit/mesh-transport/api/exportBundle/) - [`fragment`](https://toip.tools/toolkit/mesh-transport/api/fragment/) Cuts a packet into DATA frames of at most \`mtu\` bytes. - [`joinTsp`](https://toip.tools/toolkit/mesh-transport/api/joinTsp/) - [`keyHint`](https://toip.tools/toolkit/mesh-transport/api/keyHint/) H(Ed25519 key)\[0..8\], naming a door or gateway in its beacons and VIA packets. - [`loraAirtimeMs`](https://toip.tools/toolkit/mesh-transport/api/loraAirtimeMs/) Semtech's time-on-air formula, explicit header, CRC on. - [`maxBytesUnder`](https://toip.tools/toolkit/mesh-transport/api/maxBytesUnder/) The largest payload (up to 255 bytes) whose airtime is at most \`ms\`. - [`memoryContacts`](https://toip.tools/toolkit/mesh-transport/api/memoryContacts/) - [`memoryGatewayStore`](https://toip.tools/toolkit/mesh-transport/api/memoryGatewayStore/) - [`memoryOutbox`](https://toip.tools/toolkit/mesh-transport/api/memoryOutbox/) - [`openBundle`](https://toip.tools/toolkit/mesh-transport/api/openBundle/) The messages in a bundle. - [`openRoute`](https://toip.tools/toolkit/mesh-transport/api/openRoute/) - [`openSender`](https://toip.tools/toolkit/mesh-transport/api/openSender/) - [`packetId`](https://toip.tools/toolkit/mesh-transport/api/packetId/) pid = H(packet)\[0..4\]. - [`pairKeys`](https://toip.tools/toolkit/mesh-transport/api/pairKeys/) k(me→peer) and k(peer→me), from one X25519 agreement. - [`planMtu`](https://toip.tools/toolkit/mesh-transport/api/planMtu/) The MTU a plan really allows: its own, capped by the largest frame under the dwell limit. - [`postBundle`](https://toip.tools/toolkit/mesh-transport/api/postBundle/) Posts every message through a relay transport signed in as the courier. - [`readVidForm`](https://toip.tools/toolkit/mesh-transport/api/readVidForm/) - [`receiptMac`](https://toip.tools/toolkit/mesh-transport/api/receiptMac/) The MAC of a receipt with status 0 or 2, under k(R→S). - [`receiptTag`](https://toip.tools/toolkit/mesh-transport/api/receiptTag/) A RECEIPT's tag, under k(R→S). - [`sealRoute`](https://toip.tools/toolkit/mesh-transport/api/sealRoute/) A VIA's route block for the gateway: both VIDs, sealed to it. - [`sealSender`](https://toip.tools/toolkit/mesh-transport/api/sealSender/) An INTRO's sealed sender: HPKE base mode to R, bound to the packet's \`enc\`. - [`splitTsp`](https://toip.tools/toolkit/mesh-transport/api/splitTsp/) The parts of a TSP message. - [`tspSignatureValid`](https://toip.tools/toolkit/mesh-transport/api/tspSignatureValid/) Checks the TSP signature, so a mesh node can drop forgeries and tag collisions before delivery. - [`vidForm`](https://toip.tools/toolkit/mesh-transport/api/vidForm/) \`0x01 ‖ key\` for an Ed25519 did:key, otherwise \`0x02 ‖ length ‖ UTF-8\`. ## Classes - [`AirtimeBudget`](https://toip.tools/toolkit/mesh-transport/api/AirtimeBudget/) A sliding-window airtime ledger. - [`ChallengeBeacon`](https://toip.tools/toolkit/mesh-transport/api/ChallengeBeacon/) - [`LinkEvents`](https://toip.tools/toolkit/mesh-transport/api/LinkEvents/) A small helper for adapters: listener sets for frames and state. - [`MeshGateway`](https://toip.tools/toolkit/mesh-transport/api/MeshGateway/) - [`MeshTransport`](https://toip.tools/toolkit/mesh-transport/api/MeshTransport/) - [`VirtualScheduler`](https://toip.tools/toolkit/mesh-transport/api/VirtualScheduler/) Virtual time. ## Interfaces - [`AirtimePolicy`](https://toip.tools/toolkit/mesh-transport/api/AirtimePolicy/) A link's airtime budget: a sliding window with a ceiling, and a per-frame cap (dwell time). - [`BeaconInfo`](https://toip.tools/toolkit/mesh-transport/api/BeaconInfo/) - [`BundleItem`](https://toip.tools/toolkit/mesh-transport/api/BundleItem/) - [`ChannelPlan`](https://toip.tools/toolkit/mesh-transport/api/ChannelPlan/) - [`Contact`](https://toip.tools/toolkit/mesh-transport/api/Contact/) - [`ContactStore`](https://toip.tools/toolkit/mesh-transport/api/ContactStore/) - [`GatewayStore`](https://toip.tools/toolkit/mesh-transport/api/GatewayStore/) - [`Link`](https://toip.tools/toolkit/mesh-transport/api/Link/) - [`LinkInfo`](https://toip.tools/toolkit/mesh-transport/api/LinkInfo/) - [`LoRaSetting`](https://toip.tools/toolkit/mesh-transport/api/LoRaSetting/) LoRa time on air, channel plans and region rules (design §12, §14.4). - [`MeshOptions`](https://toip.tools/toolkit/mesh-transport/api/MeshOptions/) - [`MeshOutboxItem`](https://toip.tools/toolkit/mesh-transport/api/MeshOutboxItem/) - [`MeshOutboxStore`](https://toip.tools/toolkit/mesh-transport/api/MeshOutboxStore/) - [`MeshStats`](https://toip.tools/toolkit/mesh-transport/api/MeshStats/) - [`ReceivedFrame`](https://toip.tools/toolkit/mesh-transport/api/ReceivedFrame/) - [`RelayLike`](https://toip.tools/toolkit/mesh-transport/api/RelayLike/) Anything that posts to the internet relay: a RelayTransport signed in as the gateway. - [`Scheduler`](https://toip.tools/toolkit/mesh-transport/api/Scheduler/) Where the mesh gets time and timers. - [`TspParts`](https://toip.tools/toolkit/mesh-transport/api/TspParts/) - [`ViaArrival`](https://toip.tools/toolkit/mesh-transport/api/ViaArrival/) What a gateway gets for each VIA packet that names it. ## Types - [`Frame`](https://toip.tools/toolkit/mesh-transport/api/Frame/) - [`LinkState`](https://toip.tools/toolkit/mesh-transport/api/LinkState/) - [`MeshEvent`](https://toip.tools/toolkit/mesh-transport/api/MeshEvent/) - [`Packet`](https://toip.tools/toolkit/mesh-transport/api/Packet/) - [`PacketKind`](https://toip.tools/toolkit/mesh-transport/api/PacketKind/) - [`TrafficClass`](https://toip.tools/toolkit/mesh-transport/api/TrafficClass/) ## Constants - [`FRAME_HEADER`](https://toip.tools/toolkit/mesh-transport/api/FRAME_HEADER/) - [`MAX_FRAGMENTS`](https://toip.tools/toolkit/mesh-transport/api/MAX_FRAGMENTS/) - [`plans`](https://toip.tools/toolkit/mesh-transport/api/plans/) - [`realScheduler`](https://toip.tools/toolkit/mesh-transport/api/realScheduler/) - [`regions`](https://toip.tools/toolkit/mesh-transport/api/regions/) - [`US915_DOWN`](https://toip.tools/toolkit/mesh-transport/api/US915_DOWN/) - [`US915_UP`](https://toip.tools/toolkit/mesh-transport/api/US915_UP/) 904.6 MHz: the stock US915 gateway's 500 kHz receive channel. Signatures and source documentation are generated from [`packages/mesh-transport/src/index.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mesh-transport/src/index.ts). API reference · Browser and Node # @toip-tools/mesh-transport/sim 9 public exports. Module import: ```ts import { type GilbertElliott, type LossReason, RegulatoryViolation } from "@toip-tools/mesh-transport/sim"; ``` ## Classes - [`RegulatoryViolation`](https://toip.tools/toolkit/mesh-transport/api/sim/RegulatoryViolation/) Thrown when a link breaks its airtime rules. - [`SimLink`](https://toip.tools/toolkit/mesh-transport/api/sim/SimLink/) - [`SimMedium`](https://toip.tools/toolkit/mesh-transport/api/sim/SimMedium/) - [`VirtualScheduler`](https://toip.tools/toolkit/mesh-transport/api/sim/VirtualScheduler/) Virtual time. ## Interfaces - [`GilbertElliott`](https://toip.tools/toolkit/mesh-transport/api/sim/GilbertElliott/) Bursty loss: a two-state Markov chain per directed pair, stepped once per frame. - [`SimRadioParams`](https://toip.tools/toolkit/mesh-transport/api/sim/SimRadioParams/) - [`SimRecord`](https://toip.tools/toolkit/mesh-transport/api/sim/SimRecord/) ## Types - [`LossReason`](https://toip.tools/toolkit/mesh-transport/api/sim/LossReason/) - [`SimFault`](https://toip.tools/toolkit/mesh-transport/api/sim/SimFault/) Signatures and source documentation are generated from [`packages/mesh-transport/src/sim.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mesh-transport/src/sim.ts). API reference · Browser and Node # @toip-tools/mesh-transport/serial 3 public exports. Module import: ```ts import { type SerialPortLike, webSerialPort, type WebSerialPortLike } from "@toip-tools/mesh-transport/serial"; ``` ## Functions - [`webSerialPort`](https://toip.tools/toolkit/mesh-transport/api/serial/webSerialPort/) A Web Serial port (Chrome and Edge, after a user gesture) as a SerialPortLike. ## Interfaces - [`SerialPortLike`](https://toip.tools/toolkit/mesh-transport/api/serial/SerialPortLike/) The serial port every serial radio adapter uses (design §14.6, §19.1). - [`WebSerialPortLike`](https://toip.tools/toolkit/mesh-transport/api/serial/WebSerialPortLike/) The parts of a Web Serial \`SerialPort\` we use. Signatures and source documentation are generated from [`packages/mesh-transport/src/serial.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mesh-transport/src/serial.ts). API reference · Browser and Node # @toip-tools/mesh-transport/rak 2 public exports. Module import: ```ts import { p2pCommand, RakP2PLink } from "@toip-tools/mesh-transport/rak"; ``` ## Functions - [`p2pCommand`](https://toip.tools/toolkit/mesh-transport/api/rak/p2pCommand/) \`AT+P2P=freq:SF:bandwidth code:coding rate code:preamble:power\`. ## Classes - [`RakP2PLink`](https://toip.tools/toolkit/mesh-transport/api/rak/RakP2PLink/) Signatures and source documentation are generated from [`packages/mesh-transport/src/rak.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mesh-transport/src/rak.ts). API reference · Node only # @toip-tools/mesh-transport/gwmp 5 public exports. Module import: ```ts import { GWMP, GwmpLink, GwmpServer } from "@toip-tools/mesh-transport/gwmp"; ``` ## Functions - [`txpkFor`](https://toip.tools/toolkit/mesh-transport/api/gwmp/txpkFor/) The txpk for one frame under a plan's transmit setting. ## Classes - [`GwmpLink`](https://toip.tools/toolkit/mesh-transport/api/gwmp/GwmpLink/) - [`GwmpServer`](https://toip.tools/toolkit/mesh-transport/api/gwmp/GwmpServer/) ## Interfaces - [`RxPk`](https://toip.tools/toolkit/mesh-transport/api/gwmp/RxPk/) ## Constants - [`GWMP`](https://toip.tools/toolkit/mesh-transport/api/gwmp/GWMP/) Signatures and source documentation are generated from [`packages/mesh-transport/src/gwmp.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mesh-transport/src/gwmp.ts). API reference · Node only # @toip-tools/mesh-transport/detect 6 public exports. Module import: ```ts import { detectRadios, KissDecoder, kissEncode } from "@toip-tools/mesh-transport/detect"; ``` ## Functions - [`detectRadios`](https://toip.tools/toolkit/mesh-transport/api/detect/detectRadios/) - [`kissEncode`](https://toip.tools/toolkit/mesh-transport/api/detect/kissEncode/) A KISS frame: FEND, command, escaped data, FEND. - [`listenForGateways`](https://toip.tools/toolkit/mesh-transport/api/detect/listenForGateways/) Listens for PULL\_DATA on a UDP port for \`ms\`: each gateway's EUI and address. - [`probeSerial`](https://toip.tools/toolkit/mesh-transport/api/detect/probeSerial/) Works out what is on one serial port. ## Classes - [`KissDecoder`](https://toip.tools/toolkit/mesh-transport/api/detect/KissDecoder/) ## Types - [`RadioDetection`](https://toip.tools/toolkit/mesh-transport/api/detect/RadioDetection/) Signatures and source documentation are generated from [`packages/mesh-transport/src/detect.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mesh-transport/src/detect.ts). API reference · Node only # @toip-tools/mesh-transport/node 18 public exports. Module import: ```ts import { detectRadios, fileContacts, fileGatewayStore } from "@toip-tools/mesh-transport/node"; ``` ## Functions - [`detectRadios`](https://toip.tools/toolkit/mesh-transport/api/node/detectRadios/) - [`fileContacts`](https://toip.tools/toolkit/mesh-transport/api/node/fileContacts/) - [`fileGatewayStore`](https://toip.tools/toolkit/mesh-transport/api/node/fileGatewayStore/) A gateway's custody record in a JSON file: survives restarts, so a resent VIA is never posted twice. - [`fileOutbox`](https://toip.tools/toolkit/mesh-transport/api/node/fileOutbox/) - [`fileReplayStore`](https://toip.tools/toolkit/mesh-transport/api/node/fileReplayStore/) - [`jsonFile`](https://toip.tools/toolkit/mesh-transport/api/node/jsonFile/) One JSON file, written whole and atomically (to a temporary file, then renamed). - [`kissEncode`](https://toip.tools/toolkit/mesh-transport/api/node/kissEncode/) A KISS frame: FEND, command, escaped data, FEND. - [`listenForGateways`](https://toip.tools/toolkit/mesh-transport/api/node/listenForGateways/) Listens for PULL\_DATA on a UDP port for \`ms\`: each gateway's EUI and address. - [`listSerialPorts`](https://toip.tools/toolkit/mesh-transport/api/node/listSerialPorts/) Serial ports, with a hint at the board family from the USB vendor id (never the firmware). - [`mockSerialPort`](https://toip.tools/toolkit/mesh-transport/api/node/mockSerialPort/) The same wrapper over serialport's mock binding, for trying adapters without hardware. - [`nodeSerialPort`](https://toip.tools/toolkit/mesh-transport/api/node/nodeSerialPort/) A USB serial port through the "serialport" package. - [`probeSerial`](https://toip.tools/toolkit/mesh-transport/api/node/probeSerial/) Works out what is on one serial port. - [`txpkFor`](https://toip.tools/toolkit/mesh-transport/api/node/txpkFor/) The txpk for one frame under a plan's transmit setting. ## Classes - [`GwmpLink`](https://toip.tools/toolkit/mesh-transport/api/node/GwmpLink/) - [`GwmpServer`](https://toip.tools/toolkit/mesh-transport/api/node/GwmpServer/) - [`KissDecoder`](https://toip.tools/toolkit/mesh-transport/api/node/KissDecoder/) ## Types - [`RadioDetection`](https://toip.tools/toolkit/mesh-transport/api/node/RadioDetection/) ## Constants - [`GWMP`](https://toip.tools/toolkit/mesh-transport/api/node/GWMP/) Signatures and source documentation are generated from [`packages/mesh-transport/src/node.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mesh-transport/src/node.ts). # Trust Task reference Explore 55 message types used by the toolkit and its apps. Each page explains the interaction, identifies the sender and recipient, and shows the payload declared in the code. A Trust Task's `type` is the URI of its specification. Types defined here use `https://toip.tools/spec//0.1`, so the URI also leads to its reference page. These are project-specific definitions, separate from the public [Trust Tasks registry](https://trusttasks.org/). Types are declared with `ourSpec("")` from [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/). These pages are generated from the source and accompanying notes at build time. ## Settle: conditional payments Invoices, terms, escrow, attestations, disputes, rulings and receipts between a payer, a payee, an attester, an arbiter and a processor. Used by [Settle](https://toip.tools/examples/#settle). - [`settle/arbiter/ruling`](https://toip.tools/spec/settle/arbiter/ruling/0.1/) The arbiter sends its signed ruling on a disputed payment, with the evidence it relied on and its own outcome signature. - [`settle/checkout/start`](https://toip.tools/spec/settle/checkout/start/0.1/) A payer who opens a payment link sends the link back to its issuer and asks for an invoice under the link's conditions. - [`settle/escrow/attest`](https://toip.tools/spec/settle/escrow/attest/0.1/) The attester named in the terms sends a signed claim that the work is complete or not complete, with an optional note. - [`settle/escrow/dispute`](https://toip.tools/spec/settle/escrow/dispute/0.1/) The payer or the payee sends a signed dispute with a reason. - [`settle/escrow/hold`](https://toip.tools/spec/settle/escrow/hold/0.1/) On a dispute, the arbiter signs a hold that pushes back the escrow's reclaim deadline, so the payer can't wait out the deadline before a ruling. - [`settle/escrow/opened`](https://toip.tools/spec/settle/escrow/opened/0.1/) After the escrow opens on-chain, the payer announces it with the terms, both acceptances, the escrow address and the opening transaction signature. - [`settle/escrow/settled`](https://toip.tools/spec/settle/escrow/settled/0.1/) After it submits the resolve transaction, the processor tells everyone the escrow settled, with the transaction signature, the payee's share and the evidence hash. - [`settle/escrow/sign`](https://toip.tools/spec/settle/escrow/sign/0.1/) A party sends its signature over an escrow outcome (how much of the price goes to the payee), with the evidence the outcome rests on. - [`settle/payment/receipt`](https://toip.tools/spec/settle/payment/receipt/0.1/) After settlement, the payee sends the payer a signed receipt credential (SettlePaymentReceipt). - [`settle/payment/request`](https://toip.tools/spec/settle/payment/request/0.1/) The payee sends an invoice to the payer. - [`settle/payment/terms/accept`](https://toip.tools/spec/settle/payment/terms/accept/0.1/) The payee returns the agreed terms with its own signed acceptance. - [`settle/payment/terms/propose`](https://toip.tools/spec/settle/payment/terms/propose/0.1/) The payer sends the full terms document with its own signed acceptance. - [`settle/processor/log`](https://toip.tools/spec/settle/processor/log/0.1/) Anyone can ask the processor for its transparency log. Request and response. - [`settle/processor/submit`](https://toip.tools/spec/settle/processor/submit/0.1/) A party sends the processor a partly signed transaction: an escrow open, reclaim or claim. Request and response. ## Shared To-Do: a list without a server Joining, membership, signed operations, rosters and catching up. Used by [Shared To-Do](https://toip.tools/examples/#shared-todo). - [`todo/ack`](https://toip.tools/spec/todo/ack/0.1/) A new member sends the admin a signed acknowledgement credential (TodoListMembershipAcknowledgement) after accepting the welcome. - [`todo/join`](https://toip.tools/spec/todo/join/0.1/) A device holding an invitation asks the inviting admin to join the list, with the invitation code, the list's DID and a display name. - [`todo/join-refused`](https://toip.tools/spec/todo/join-refused/0.1/) The admin tells a joiner why it won't admit them: the invitation is unknown, used or expired, the joiner is already a member, or this device doesn't run the list. - [`todo/leave`](https://toip.tools/spec/todo/leave/0.1/) A member who isn't the admin tells the list's admins they are leaving. - [`todo/op`](https://toip.tools/spec/todo/op/0.1/) A member who adds, edits, checks, unchecks or deletes an item sends the signed operation, with their membership credential, to every other current member. - [`todo/roster`](https://toip.tools/spec/todo/roster/0.1/) The admin sends the list's newly signed roster after someone joins or is removed. - [`todo/sync`](https://toip.tools/spec/todo/sync/0.1/) A device sends one page of a list's history: the current signed roster, up to 100 operations, and the membership credentials those operations need. - [`todo/sync-request`](https://toip.tools/spec/todo/sync-request/0.1/) On start and on reconnect, a device asks one other current member (a different one each time) for everything it holds for a list. - [`todo/welcome`](https://toip.tools/spec/todo/welcome/0.1/) The admin admits a joiner. ## Mandates: delegation and approval Issuing and revoking mandates, and asking a principal to approve one action. From [`@toip-tools/mandates`](https://toip.tools/toolkit/mandates/). - [`mandates/approval/deny`](https://toip.tools/spec/mandates/approval/deny/0.1/) The approver tells the delegate it refused a pending request, with an optional reason. - [`mandates/approval/grant`](https://toip.tools/spec/mandates/approval/grant/0.1/) The approver returns a signed approval for a pending request. - [`mandates/approval/request`](https://toip.tools/spec/mandates/approval/request/0.1/) A delegate asks an approver to allow one action its mandate chain doesn't allow by itself. - [`mandates/issue`](https://toip.tools/spec/mandates/issue/0.1/) A delegator sends its delegate a new mandate, with the chain of mandates above it. - [`mandates/revoked`](https://toip.tools/spec/mandates/revoked/0.1/) A delegator tells its delegate that a mandate was revoked, with the mandate's id and the delegator's newly signed status list. ## Trail: witnesses and disclosure Submitting events to witnesses, querying logs, disclosing bundles and reporting duplicity. From [`@toip-tools/eventlog`](https://toip.tools/toolkit/eventlog/). - [`trail/disclose`](https://toip.tools/spec/trail/disclose/0.1/) A log's controller sends a reader a bundle: the KEL, the chosen trails with the bodies picked for this reader, and the DID bindings. Request and response. - [`trail/duplicity`](https://toip.tools/spec/trail/duplicity/0.1/) Whoever catches duplicity sends the evidence to someone who relies on the log: two conflicting signed versions at the same position, from the controller or from a witness. Request and response. - [`trail/head`](https://toip.tools/spec/trail/head/0.1/) A watcher or verifier asks a witness for the head of a log: the latest receipt that witness signed. Request and response. - [`trail/query`](https://toip.tools/spec/trail/query/0.1/) A watcher or verifier asks a witness for a log's messages and receipts, optionally for a range of sequence numbers. Request and response. - [`trail/witness/receipts`](https://toip.tools/spec/trail/witness/receipts/0.1/) A log's controller passes each witness the receipts the other witnesses signed, so every witness ends up holding every receipt. Request and response. - [`trail/witness/submit`](https://toip.tools/spec/trail/witness/submit/0.1/) A log's controller sends a witness KEL events or trail messages to witness. Request and response. ## Anonymous membership: enrollment A member enrolls a commitment with a group's issuer. From [`@toip-tools/anon-membership`](https://toip.tools/toolkit/anon-membership/). - [`anon-membership/enroll`](https://toip.tools/spec/anon-membership/enroll/0.1/) A member's wallet, from the member's own DID, sends a group's issuer a commitment to its secret for that group, optionally with a credential. Request and response. ## agents - [`agents/control`](https://toip.tools/spec/agents/control/0.1/) The principal controls an agent: pause, resume or stop it, ask it to disclose its audit trail, or revoke a mandate the agent issued to a sub-agent. - [`agents/job/decline`](https://toip.tools/spec/agents/job/decline/0.1/) The worker turns a job down, with a reason in words. - [`agents/job/deliver`](https://toip.tools/spec/agents/job/deliver/0.1/) The worker hands over the work: a git commit, or a note for a physical task. - [`agents/job/offer`](https://toip.tools/spec/agents/job/offer/0.1/) A hiring agent offers a job: what to do, the category, the most it will pay, how the payment is released (by an attester such as CI, or by the hirer), the dispute window, the deadline, and the hirer's passport. - [`agents/job/quote`](https://toip.tools/spec/agents/job/quote/0.1/) The worker answers an offer with a signed Settle payment link for the job, under the job's conditions. - [`agents/job/refused`](https://toip.tools/spec/agents/job/refused/0.1/) The worker's check of the hirer's mandate failed, so it won't take the job. - [`agents/job/watch`](https://toip.tools/spec/agents/job/watch/0.1/) The hirer tells the attester what to check before it attests the work complete: for a code job, the repository and the test command to run. - [`agents/report`](https://toip.tools/spec/agents/report/0.1/) An agent tells its principal something in words, with optional references to jobs, payments or trail entries. - [`agents/task`](https://toip.tools/spec/agents/task/0.1/) A principal or a delegating agent gives an agent work in words. ## agora - [`agora/demo/issue`](https://toip.tools/spec/agora/demo/issue/0.1/) In the demo only, a member asks a demo issuer (a nursing board, a city) for the credential that later gates their forums, such as a registered-nurse license with its claims. Request and response. - [`agora/group/leave`](https://toip.tools/spec/agora/group/leave/0.1/) A member asks a registrar to take their leaf out of a group. Request and response. - [`agora/group/receipt`](https://toip.tools/spec/agora/group/receipt/0.1/) A member asks a registrar for a signed receipt that they are in a group, to restore their membership on a new device from a backup code. Request and response. ## mesh-demo - [`mesh-demo/door/open`](https://toip.tools/spec/mesh-demo/door/open/0.1/) A guest asks a door to open, with no internet. Request and response. ## tipline - [`tipline/message`](https://toip.tools/spec/tipline/message/0.1/) A reply or a follow-up in a tip's conversation, in either direction. - [`tipline/proof/present`](https://toip.tools/spec/tipline/proof/present/0.1/) The source answers a proof request with a fresh membership proof bound to the challenge. - [`tipline/proof/request`](https://toip.tools/spec/tipline/proof/request/0.1/) The drop box asks a source for a fresh membership proof, for example against a newer group root, with a challenge to bind it to. - [`tipline/thread/request`](https://toip.tools/spec/tipline/thread/request/0.1/) A source who kept nothing comes back with their tip code and asks the drop box to resend the conversation. - [`tipline/tip/chunk`](https://toip.tools/spec/tipline/tip/chunk/0.1/) One piece of one attachment, sent after the submit. - [`tipline/tip/receipt`](https://toip.tools/spec/tipline/tip/receipt/0.1/) The drop box tells the source whether the tip was verified or rejected, and why, and asks again for any chunks that didn't arrive. - [`tipline/tip/submit`](https://toip.tools/spec/tipline/tip/submit/0.1/) A source sends a tip from a fresh DID made from their tip code: the story it's for, the text, a list of attachments, and a zero-knowledge proof that they belong to the organization's group. # agents/control https://toip.tools/spec/agents/control/0.1 The principal controls an agent: pause, resume or stop it, ask it to disclose its audit trail, or revoke a mandate the agent issued to a sub-agent. - **Sent**: principal → agent - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/agents/src/protocol/tasks.ts:12`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/protocol/tasks.ts#L12) as `CONTROL` - **Handled in**: [`projects/agents/src/guard/guard.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/guard/guard.ts), [`projects/agents/src/roles/principal.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/roles/principal.ts) - **Design**: [10.1 Types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/docs/design.md#101-types) in `projects/agents/docs/design.md` ## Payload projects/agents/src/protocol/tasks.ts:77: ```ts export interface Control { op: ControlOp; /** For "revoke": a mandate this agent issued. */ mandate?: string; } ``` ## Notes revoke is our addition to the design's table: only the agent that issued a mandate signs its status list, so the principal asks that agent to revoke it. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/agents/control/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # agents/job/decline https://toip.tools/spec/agents/job/decline/0.1 The worker turns a job down, with a reason in words. - **Sent**: worker → hiring agent - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/agents/src/protocol/tasks.ts:8`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/protocol/tasks.ts#L8) as `JOB_DECLINE` - **Handled in**: [`projects/agents/src/guard/guard.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/guard/guard.ts), [`projects/agents/src/roles/principal.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/roles/principal.ts) - **Design**: [10.1 Types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/docs/design.md#101-types) in `projects/agents/docs/design.md` ## Payload projects/agents/src/protocol/tasks.ts:44: ```ts export interface JobDecline { job: string; reason: string; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/agents/job/decline/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # agents/job/deliver https://toip.tools/spec/agents/job/deliver/0.1 The worker hands over the work: a git commit, or a note for a physical task. The attester checks it and attests on Settle. - **Sent**: worker → hiring agent and attester - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/agents/src/protocol/tasks.ts:11`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/protocol/tasks.ts#L11) as `JOB_DELIVER` - **Handled in**: [`projects/agents/src/roles/ci.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/roles/ci.ts), [`projects/agents/src/guard/guard.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/guard/guard.ts), [`projects/agents/src/roles/courier.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/roles/courier.ts) - **Design**: [10.1 Types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/docs/design.md#101-types) in `projects/agents/docs/design.md` ## Payload projects/agents/src/protocol/tasks.ts:70: ```ts export interface JobDeliver { job: string; termsHash: string; deliverable: Deliverable; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/agents/job/deliver/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # agents/job/offer https://toip.tools/spec/agents/job/offer/0.1 A hiring agent offers a job: what to do, the category, the most it will pay, how the payment is released (by an attester such as CI, or by the hirer), the dispute window, the deadline, and the hirer's passport. With a mandate presentation attached, the worker can check the hirer is allowed to spend that much on that category before it quotes. - **Sent**: hiring agent → worker (a person's party or another agent) - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/agents/src/protocol/tasks.ts:6`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/protocol/tasks.ts#L6) as `JOB_OFFER` - **Handled in**: [`projects/agents/src/guard/guard.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/guard/guard.ts), [`projects/agents/src/roles/principal.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/roles/principal.ts), [`projects/agents/src/roles/courier.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/roles/courier.ts) - **Design**: [10.1 Types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/docs/design.md#101-types) in `projects/agents/docs/design.md` ## Payload projects/agents/src/protocol/tasks.ts:19: ```ts export interface JobOffer { job: string; title: string; description: string; category: string; /** The most the hirer offers, in units. */ maxUnits: string; release: Release; disputeWindowDays: number; deliverable: "git" | "note"; /** For code jobs: where to push the work (a git URL or a local path in the demo). */ repo?: string; deadline: string; hirerName: string; passport: Credential; /** A presentation of the agents/job/offer action. */ presentation?: Presentation; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/agents/job/offer/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # agents/job/quote https://toip.tools/spec/agents/job/quote/0.1 The worker answers an offer with a signed Settle payment link for the job, under the job's conditions. The hirer's guard checks the quote matches the offer before anything is paid. - **Sent**: worker → hiring agent - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/agents/src/protocol/tasks.ts:7`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/protocol/tasks.ts#L7) as `JOB_QUOTE` - **Handled in**: [`projects/agents/src/guard/guard.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/guard/guard.ts), [`projects/agents/src/roles/principal.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/roles/principal.ts) - **Design**: [10.1 Types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/docs/design.md#101-types) in `projects/agents/docs/design.md` ## Payload projects/agents/src/protocol/tasks.ts:38: ```ts export interface JobQuote { job: string; link: PaymentLink; note?: string; } ``` ## Notes A quote that doesn't match its job (a higher price, another release rule) is refused with a quote.mismatch reason that no approval can override. That is how the demo's prompt-injected quote is stopped. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/agents/job/quote/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # agents/job/refused https://toip.tools/spec/agents/job/refused/0.1 The worker's check of the hirer's mandate failed, so it won't take the job. The payload lists the decision's reasons. - **Sent**: worker → hiring agent - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/agents/src/protocol/tasks.ts:9`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/protocol/tasks.ts#L9) as `JOB_REFUSED` - **Handled in**: [`projects/agents/src/guard/guard.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/guard/guard.ts), [`projects/agents/src/roles/principal.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/roles/principal.ts) - **Design**: [10.1 Types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/docs/design.md#101-types) in `projects/agents/docs/design.md` ## Payload projects/agents/src/protocol/tasks.ts:49: ```ts export interface JobRefused { job: string; link?: string; reasons: string[]; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/agents/job/refused/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # agents/job/watch https://toip.tools/spec/agents/job/watch/0.1 The hirer tells the attester what to check before it attests the work complete: for a code job, the repository and the test command to run. - **Sent**: hiring agent → attester (CI in the demo) - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/agents/src/protocol/tasks.ts:10`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/protocol/tasks.ts#L10) as `JOB_WATCH` - **Handled in**: [`projects/agents/src/roles/ci.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/roles/ci.ts), [`projects/agents/src/guard/guard.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/guard/guard.ts) - **Design**: [10.1 Types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/docs/design.md#101-types) in `projects/agents/docs/design.md` ## Payload projects/agents/src/protocol/tasks.ts:62: ```ts export interface JobWatch { job: string; termsHash: string; check: CiCheck; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/agents/job/watch/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # agents/report https://toip.tools/spec/agents/report/0.1 An agent tells its principal something in words, with optional references to jobs, payments or trail entries. - **Sent**: agent → principal - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/agents/src/protocol/tasks.ts:13`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/protocol/tasks.ts#L13) as `REPORT` - **Handled in**: [`projects/agents/src/guard/guard.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/guard/guard.ts), [`projects/agents/src/roles/principal.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/roles/principal.ts) - **Design**: [10.1 Types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/docs/design.md#101-types) in `projects/agents/docs/design.md` ## Payload projects/agents/src/protocol/tasks.ts:83: ```ts export interface Report { text: string; refs?: Record; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/agents/report/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # agents/task https://toip.tools/spec/agents/task/0.1 A principal or a delegating agent gives an agent work in words. It becomes the first message of the agent's model loop. - **Sent**: principal or delegating agent → agent - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/agents/src/protocol/tasks.ts:15`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/protocol/tasks.ts#L15) as `TASK` - **Handled in**: [`projects/agents/src/guard/guard.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/guard/guard.ts), [`projects/agents/src/roles/principal.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/src/roles/principal.ts) - **Design**: [10.1 Types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/docs/design.md#101-types) in `projects/agents/docs/design.md` Source documentation: “A delegator or principal gives an agent work in words (our addition: the design passes the task as the first user message).” ## Payload projects/agents/src/protocol/tasks.ts:88: ```ts export interface TaskMessage { text: string; } ``` ## Notes Our addition: the design passes the task as the model's first user message without a Trust Task. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/agents/task/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # agora/demo/issue https://toip.tools/spec/agora/demo/issue/0.1 In the demo only, a member asks a demo issuer (a nursing board, a city) for the credential that later gates their forums, such as a registered-nurse license with its claims. - **Sent**: member → demo issuer - **Kind**: Request and response. The response's type is `https://toip.tools/spec/agora/demo/issue/0.1#response`. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/agora/src/protocol/specs.ts:8`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agora/src/protocol/specs.ts#L8) as `DEMO_ISSUE` - **Handled in**: [`projects/agora/src/issuers/issuers.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agora/src/issuers/issuers.ts) - **Design**: [7.6 Trust Task types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agora/docs/design.md#76-trust-task-types) in `projects/agora/docs/design.md` Source documentation: “member DID → demo issuer: { credentialType, claims } → { credential }. Dev only.” ## Payload projects/agora/src/protocol/specs.ts:14: ```ts export interface DemoIssueRequest { credentialType: string; claims: Record; } ``` ## Notes A real issuer issues credentials its own way. Agora only needs the credential afterwards, to enroll. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/agora/demo/issue/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # agora/group/leave https://toip.tools/spec/agora/group/leave/0.1 A member asks a registrar to take their leaf out of a group. - **Sent**: member → registrar - **Kind**: Request and response. The response's type is `https://toip.tools/spec/agora/group/leave/0.1#response`. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/agora/src/protocol/specs.ts:12`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agora/src/protocol/specs.ts#L12) as `GROUP_LEAVE` - **Handled in**: [`projects/agora/src/registrar/registrar.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agora/src/registrar/registrar.ts) - **Design**: [7.6 Trust Task types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agora/docs/design.md#76-trust-task-types) in `projects/agora/docs/design.md` Source documentation: “member DID → registrar: { group } → { removed: true }.” ## Payload A payload declaration is not available on this page. Follow the source links above for the handler's requirements. ## Notes The request carries { group }; the answer is { removed: true }. The leaf is gone from the next published root. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/agora/group/leave/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # agora/group/receipt https://toip.tools/spec/agora/group/receipt/0.1 A member asks a registrar for a signed receipt that they are in a group, to restore their membership on a new device from a backup code. - **Sent**: member → registrar - **Kind**: Request and response. The response's type is `https://toip.tools/spec/agora/group/receipt/0.1#response`. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/agora/src/protocol/specs.ts:10`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agora/src/protocol/specs.ts#L10) as `GROUP_RECEIPT` - **Handled in**: [`projects/agora/src/registrar/registrar.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agora/src/registrar/registrar.ts) - **Design**: [7.6 Trust Task types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agora/docs/design.md#76-trust-task-types) in `projects/agora/docs/design.md` Source documentation: “member DID → registrar: { group } → a signed agora/group-receipt for the sender, if they're a member.” ## Payload A payload declaration is not available on this page. Follow the source links above for the handler's requirements. ## Response payload projects/agora/src/protocol/documents.ts:207: ```ts /** The receipt a registrar keeps for a member, and sends only to them (design §7.6). */ export interface GroupReceipt { type: "agora/group-receipt"; issuer: string; issuedAt: string; group: string; subject: string; index: number; leaf: { commitment: string; schemaId: string; validUntilDay: number; registeredDay: number; attrs: string[] }; /** The credential's plain values per slot, so the member's client can explain the gate in words. */ values: Record; proof?: unknown; } ``` ## Notes The request carries { group }. The registrar answers only if the sender is a member. Joining and rotating use anon-membership/enroll instead. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/agora/group/receipt/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # anon-membership/enroll https://toip.tools/spec/anon-membership/enroll/0.1 A member's wallet, from the member's own DID, sends a group's issuer a commitment to its secret for that group, optionally with a credential. The issuer's admit() decides whether that DID may join; if so, the issuer appends the commitment as a leaf in the group's tree. It answers with the leaf's index, the first epoch whose root will hold it, and the leaf, which the wallet checks. - **Sent**: member's wallet → group issuer - **Kind**: Request and response. The response's type is `https://toip.tools/spec/anon-membership/enroll/0.1#response`. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`packages/anon-membership/src/issuer.ts:12`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/anon-membership/src/issuer.ts#L12) as `ENROLL` - **Handled in**: [`packages/anon-membership/src/issuer.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/anon-membership/src/issuer.ts) - **Design**: [7.1 Message types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/docs/design.md#71-message-types) in `projects/tipline/docs/design.md` ## Payload packages/anon-membership/src/issuer.ts:14: ```ts export interface EnrollRequest { group: string; commitment: string; /** Anything the issuer's admit() needs to decide and to fill the leaf's attributes, such as a credential. */ credential?: unknown; /** The member asks to replace a leaf they already have, with a new commitment (a rotation). admit() decides. (Additive.) */ replace?: boolean; } ``` ## Response payload packages/anon-membership/src/issuer.ts:31: ```ts export interface EnrollResponse { group: string; index: number; /** The first epoch whose root will hold the leaf. */ firstEpoch: string; leaf: LeafJson; } ``` ### Types it uses packages/anon-membership/src/issuer.ts:23: ```ts export interface LeafJson { commitment: string; schemaId: string; validUntilDay: number; registeredDay: number; attrs: string[]; } ``` ## Notes Refusals: unknownGroup, badRequest (the commitment isn't a field element) and notAdmitted. The design's table leaves out the optional credential and the leaf in the response. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/anon-membership/enroll/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # mandates/approval/deny https://toip.tools/spec/mandates/approval/deny/0.1 The approver tells the delegate it refused a pending request, with an optional reason. - **Sent**: approver (a principal) → delegate (an agent) - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`packages/mandates/src/tasks.ts:21`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mandates/src/tasks.ts#L21) as `APPROVAL_DENY` - **Handled in**: [`packages/mandates/src/tasks.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mandates/src/tasks.ts) - **Design**: [9.3 The exchange](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/docs/design.md#93-the-exchange) in `projects/agents/docs/design.md` Source documentation: “Approver → delegate.” ## Payload packages/mandates/src/tasks.ts:45: ```ts export interface ApprovalDenyPayload { request: string; reason?: string; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/mandates/approval/deny/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # mandates/approval/grant https://toip.tools/spec/mandates/approval/grant/0.1 The approver returns a signed approval for a pending request. The receiver checks that the sender signed it over the action's hash, then passes it to the decision. - **Sent**: approver (a principal) → delegate (an agent) - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`packages/mandates/src/tasks.ts:19`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mandates/src/tasks.ts#L19) as `APPROVAL_GRANT` - **Handled in**: [`packages/mandates/src/tasks.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mandates/src/tasks.ts) - **Design**: [9.3 The exchange](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/docs/design.md#93-the-exchange) in `projects/agents/docs/design.md` Source documentation: “Approver → delegate.” ## Payload packages/mandates/src/tasks.ts:41: ```ts export interface ApprovalGrantPayload { request: string; approval: Approval; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/mandates/approval/grant/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # mandates/approval/request https://toip.tools/spec/mandates/approval/request/0.1 A delegate asks an approver to allow one action its mandate chain doesn't allow by itself. The request carries the action, its hash, the chain, the decision and, optionally, the delegate's own justification. The receiver checks that the action matches its hash and that the chain verifies for the sender. - **Sent**: delegate (an agent) → approver (its principal) - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`packages/mandates/src/tasks.ts:17`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mandates/src/tasks.ts#L17) as `APPROVAL_REQUEST` - **Handled in**: [`packages/mandates/src/tasks.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mandates/src/tasks.ts) - **Design**: [9.3 The exchange](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/docs/design.md#93-the-exchange) in `projects/agents/docs/design.md` Source documentation: “Delegate → approver.” ## Payload packages/mandates/src/tasks.ts:31: ```ts export interface ApprovalRequestPayload { request: string; action: Action; actionHash: string; chain: Mandate[]; decision: Decision; /** The delegate's words (a model's, for an agent). Show them as such. */ justification?: string; expiresAt: string; } ``` ## Notes The answer is a separate one-way mandates/approval/grant or mandates/approval/deny. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/mandates/approval/request/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # mandates/issue https://toip.tools/spec/mandates/issue/0.1 A delegator sends its delegate a new mandate, with the chain of mandates above it. The receiver checks that the sender issued the mandate and that the whole chain verifies and only narrows. With a status resolver, it checks the chain's status lists too. - **Sent**: delegator (a principal, or an agent delegating to a sub-agent) → delegate - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`packages/mandates/src/tasks.ts:13`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mandates/src/tasks.ts#L13) as `MANDATE_ISSUE` - **Handled in**: [`packages/mandates/src/tasks.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mandates/src/tasks.ts) - **Design**: [10.1 Types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/docs/design.md#101-types) in `projects/agents/docs/design.md` Source documentation: “Delegator → delegate: a new mandate, with the chain above it.” ## Payload packages/mandates/src/tasks.ts:23: ```ts export interface IssuePayload { mandate: Mandate; chain: Mandate[]; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/mandates/issue/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # mandates/revoked https://toip.tools/spec/mandates/revoked/0.1 A delegator tells its delegate that a mandate was revoked, with the mandate's id and the delegator's newly signed status list. The receiver checks the sender signed the list, then checks its own mandate against it. - **Sent**: delegator → delegate - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`packages/mandates/src/tasks.ts:15`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mandates/src/tasks.ts#L15) as `MANDATE_REVOKED` - **Handled in**: [`packages/mandates/src/tasks.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mandates/src/tasks.ts) - **Design**: [10.1 Types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/docs/design.md#101-types) in `projects/agents/docs/design.md` Source documentation: “Delegator → delegate: a revocation notice, with the newly signed list.” ## Payload packages/mandates/src/tasks.ts:27: ```ts export interface RevokedPayload { mandate: string; statusList: StatusListDoc; } ``` ### Types it uses packages/trust-core/src/statusList.ts:8: ```ts /** A signed revocation list: one bit per credential index. Our own format, after the W3C Bitstring Status List. */ export interface StatusListDoc { id: string; type: "status-list"; issuer: string; issuedAt: string; length: number; bits: string; proof?: Proof; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/mandates/revoked/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # mesh-demo/door/open https://toip.tools/spec/mesh-demo/door/open/0.1 A guest asks a door to open, with no internet. The request carries a guest pass (a credential the building issued) and the nonce from the door's signed challenge beacon, so the signed request can't be replayed later. The door checks the pass offline: its signature, that the sender holds it, that it's for this door, the cached revocation list and its age, and the time window. It answers open or refused, with a reason. - **Sent**: guest → door - **Kind**: Request and response. The response's type is `https://toip.tools/spec/mesh-demo/door/open/0.1#response`. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/mesh/src/door.ts:23`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/mesh/src/door.ts#L23) as `DOOR_OPEN` - **Handled in**: [`projects/mesh/src/door.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/mesh/src/door.ts) - **Design**: [4.2 The MVP demo](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/mesh/docs/design.md#42-the-mvp-demo) in `projects/mesh/docs/design.md` Source documentation: “Request \`{credential, challenge}\`, response \`{open, reason?}\` (design §16).” ## Payload projects/mesh/src/door.ts:25: ```ts export interface DoorRequest { credential: GuestPass; /** The beacon's nonce, base64url. Signing the request signs it with the pass key. */ challenge: string; } ``` ## Response payload projects/mesh/src/door.ts:31: ```ts export interface DoorAnswer { open: boolean; reason?: string; } ``` ## Notes It travels over LoRa in the CTT1 compact form: about 670 bytes on the air in 3 frames, against about 2.1 KB as JSON. The mesh-demo/ prefix marks it as the demo's own type. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/mesh-demo/door/open/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # settle/arbiter/ruling https://toip.tools/spec/settle/arbiter/ruling/0.1 The arbiter sends its signed ruling on a disputed payment, with the evidence it relied on and its own outcome signature. Each party runs its policy on the ruling and, if the policy allows, signs the same outcome. The processor logs the ruling and counts the arbiter's signature toward the threshold. - **Sent**: arbiter → payer's party, payee's party and processor - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/settle/src/protocol/specs.ts:14`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/protocol/specs.ts#L14) as `ARBITER_RULING` - **Handled in**: [`projects/settle/src/agents/party.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/agents/party.ts), [`projects/settle/src/agents/roles.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/agents/roles.ts) - **Design**: [7. The Trust Tasks](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/docs/design.md#7-the-trust-tasks) in `projects/settle/docs/design.md` ## Payload projects/settle/src/agents/messages.ts:27: ```ts export interface RulingPayload { ruling: Ruling; evidence: Evidence; signature: OutcomeSignature; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/settle/arbiter/ruling/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # settle/checkout/start https://toip.tools/spec/settle/checkout/start/0.1 A payer who opens a payment link sends the link back to its issuer and asks for an invoice under the link's conditions. The payee checks that the link is its own, unchanged and not archived, then sends a settle/payment/request with those conditions. - **Sent**: payer's party → payee's party (the link's issuer) - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/settle/src/protocol/specs.ts:24`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/protocol/specs.ts#L24) as `CHECKOUT_START` - **Handled in**: [`projects/settle/src/agents/party.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/agents/party.ts) - **Design**: [17. The app: platform, parties, payment links (2026-11-06)](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/docs/design.md#17-the-app-platform-parties-payment-links-2026-11-06) in `projects/settle/docs/design.md` Source documentation: “A payer opening a payment link asks the payee for an invoice under the link's conditions.” ## Payload As the handler declares it, in projects/settle/src/agents/party.ts: ```ts { link: PaymentLink; checkout: string; name?: string } ``` ### Types it uses projects/settle/src/agents/party.ts:63: ```ts /** * A payment link (design §17): the payee's signed offer to anyone who opens it. It travels in the URL, * so a checkout page can check who issued it and what it promises without asking any server. */ export interface PaymentLink { type: "settle/payment-link"; issuer: string; id: string; /** The payee's own name for itself. */ name: string; title: string; units: string; /** Who confirms the work is done: the payer itself, or a named third party. */ release: "payer-confirms" | "attester-confirms"; attester?: string; attesterName?: string; disputeWindowDays: number; credentials: Credential[]; created: string; proof?: unknown; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/settle/checkout/start/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # settle/escrow/attest https://toip.tools/spec/settle/escrow/attest/0.1 The attester named in the terms sends a signed claim that the work is complete or not complete, with an optional note. The payer, the payee and the arbiter verify it and record it as input to their release policies. - **Sent**: attester → payer's party, payee's party and arbiter - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/settle/src/protocol/specs.ts:11`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/protocol/specs.ts#L11) as `ESCROW_ATTEST` - **Handled in**: [`projects/settle/src/agents/party.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/agents/party.ts), [`projects/settle/src/agents/roles.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/agents/roles.ts) - **Design**: [7. The Trust Tasks](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/docs/design.md#7-the-trust-tasks) in `projects/settle/docs/design.md` ## Payload projects/settle/src/protocol/documents.ts:113: ```ts export interface Attestation { type: "settle/attestation"; issuer: string; termsHash: string; claim: "complete" | "not-complete"; note?: string; at: string; proof?: unknown; } ``` ## Notes The attester can be the payer, with the link option payer-confirms. The design mentions photos sealed to the parties; the code carries only an optional note. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/settle/escrow/attest/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # settle/escrow/dispute https://toip.tools/spec/settle/escrow/dispute/0.1 The payer or the payee sends a signed dispute with a reason. The arbiter records it and signs a hold, so the payer can't reclaim before a ruling. The other party records it, and the processor logs it by role and hash. - **Sent**: payer's or payee's party → arbiter, the other party and processor - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/settle/src/protocol/specs.ts:13`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/protocol/specs.ts#L13) as `ESCROW_DISPUTE` - **Handled in**: [`projects/settle/src/agents/roles.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/agents/roles.ts), [`projects/settle/src/agents/party.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/agents/party.ts) - **Design**: [7. The Trust Tasks](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/docs/design.md#7-the-trust-tasks) in `projects/settle/docs/design.md` ## Payload projects/settle/src/protocol/documents.ts:127: ```ts export interface Dispute { type: "settle/dispute"; issuer: string; termsHash: string; reason: string; at: string; proof?: unknown; } ``` ## Notes The design lists the arbiter and the other party. The code also sends it to the processor. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/settle/escrow/dispute/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # settle/escrow/hold https://toip.tools/spec/settle/escrow/hold/0.1 On a dispute, the arbiter signs a hold that pushes back the escrow's reclaim deadline, so the payer can't wait out the deadline before a ruling. The processor checks the arbiter's signature against the escrow's arbiter key and submits the hold on-chain. - **Sent**: arbiter → processor - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/settle/src/protocol/specs.ts:17`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/protocol/specs.ts#L17) as `ESCROW_HOLD` - **Handled in**: [`projects/settle/src/agents/roles.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/agents/roles.ts) - **Design**: [16. Security review and escrow program v2 (2026-11-06)](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/docs/design.md#16-security-review-and-escrow-program-v2-2026-11-06) in `projects/settle/docs/design.md` Source documentation: “The arbiter's signed hold, so a disputed escrow can't be reclaimed before a ruling (sent to the processor to submit).” ## Payload projects/settle/src/agents/messages.ts:46: ```ts export interface HoldPayload { escrow: Address; until: string; signature: string; } ``` ## Notes Added by the security review. The table in design section 7 doesn't list it. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/settle/escrow/hold/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # settle/escrow/opened https://toip.tools/spec/settle/escrow/opened/0.1 After the escrow opens on-chain, the payer announces it with the terms, both acceptances, the escrow address and the opening transaction signature. The payee checks the escrow on-chain, field by field. The attester and the arbiter accept it only if it comes from the payer, carries both acceptances and matches the chain. The processor records it in its transparency log. - **Sent**: payer's party → payee's party, attester, arbiter and processor - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/settle/src/protocol/specs.ts:10`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/protocol/specs.ts#L10) as `ESCROW_OPENED` - **Handled in**: [`projects/settle/src/agents/party.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/agents/party.ts), [`projects/settle/src/agents/roles.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/agents/roles.ts) - **Design**: [7. The Trust Tasks](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/docs/design.md#7-the-trust-tasks) in `projects/settle/docs/design.md` ## Payload projects/settle/src/agents/messages.ts:21: ```ts export interface OpenedPayload { terms: Terms; acceptances: Acceptance[]; escrow: Address; transaction: string; } ``` ## Notes The design says the payer or the processor sends it. In the code only the payer does. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/settle/escrow/opened/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # settle/escrow/settled https://toip.tools/spec/settle/escrow/settled/0.1 After it submits the resolve transaction, the processor tells everyone the escrow settled, with the transaction signature, the payee's share and the evidence hash. Each party confirms the settlement against the chain. The payee then sends the payer a receipt. - **Sent**: processor → payer's party, payee's party and arbiter - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/settle/src/protocol/specs.ts:15`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/protocol/specs.ts#L15) as `ESCROW_SETTLED` - **Handled in**: [`projects/settle/src/agents/party.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/agents/party.ts) - **Design**: [7. The Trust Tasks](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/docs/design.md#7-the-trust-tasks) in `projects/settle/docs/design.md` ## Payload projects/settle/src/agents/messages.ts:32: ```ts export interface SettledPayload { termsHash: string; escrow: Address; transaction: string; payeeUnits: string; evidenceHash: string; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/settle/escrow/settled/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # settle/escrow/sign https://toip.tools/spec/settle/escrow/sign/0.1 A party sends its signature over an escrow outcome (how much of the price goes to the payee), with the evidence the outcome rests on. The processor collects these and submits the on-chain resolve once enough distinct allowed keys sign the same outcome. When the payee sends one to the payer, it asks for a release or a refund, which the payer checks against its policy. - **Sent**: payer's or payee's party → processor, and the payer's party when the payee asks for a release or refund - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/settle/src/protocol/specs.ts:12`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/protocol/specs.ts#L12) as `ESCROW_SIGN` - **Handled in**: [`projects/settle/src/agents/roles.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/agents/roles.ts), [`projects/settle/src/agents/party.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/agents/party.ts) - **Design**: [7. The Trust Tasks](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/docs/design.md#7-the-trust-tasks) in `projects/settle/docs/design.md` ## Payload projects/settle/src/agents/base.ts:80: ```ts /** The signed outcome a party sends the processor (design §7, escrow/sign). */ export interface OutcomeSignature { termsHash: string; escrow: Address; payeeUnits: string; evidence: Evidence; signer: Address; signature: string; } ``` ## Notes The arbiter's outcome signature travels inside settle/arbiter/ruling instead. The design's escrow/release/request type is not separate in the code: the payee's escrow/sign to the payer takes its place. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/settle/escrow/sign/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # settle/payment/receipt https://toip.tools/spec/settle/payment/receipt/0.1 After settlement, the payee sends the payer a signed receipt credential (SettlePaymentReceipt). It ties together the terms hash, the escrow address, the settlement transaction, the amount paid and the purpose. The payer verifies it and keeps it. - **Sent**: payee's party → payer's party - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/settle/src/protocol/specs.ts:18`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/protocol/specs.ts#L18) as `PAYMENT_RECEIPT` - **Handled in**: [`projects/settle/src/agents/party.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/agents/party.ts) - **Design**: [7. The Trust Tasks](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/docs/design.md#7-the-trust-tasks) in `projects/settle/docs/design.md` ## Payload packages/trust-core/src/credentials.ts:12: ```ts export interface Credential { "@context": string[]; id: string; type: string[]; issuer: string; validFrom: string; validUntil?: string; credentialSubject: { id: string; [k: string]: unknown }; credentialStatus?: { type: "BitstringStatusListEntry"; statusListIndex: number; statusListCredential: string }; proof?: Proof; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/settle/payment/receipt/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # settle/payment/request https://toip.tools/spec/settle/payment/request/0.1 The payee sends an invoice to the payer. It carries the price, the purpose, a new payment key bound to the payee's DID, and the payee's credentials. The payer checks the key binding and the credentials and records the invoice. If the invoice answers one of its own checkouts, the payer then proposes terms without a click. - **Sent**: payee's party → payer's party - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/settle/src/protocol/specs.ts:7`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/protocol/specs.ts#L7) as `PAYMENT_REQUEST` - **Handled in**: [`projects/settle/src/agents/party.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/agents/party.ts) - **Design**: [7. The Trust Tasks](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/docs/design.md#7-the-trust-tasks) in `projects/settle/docs/design.md` ## Payload projects/settle/src/agents/messages.ts:7: ```ts export interface OfferPayload { payment: string; purpose: string; units: string; payee: TermsParty; credentials: Credential[]; /** The payee's own name for itself (shown to people, never trusted). */ name?: string; /** Set when the invoice answers a checkout from a payment link. */ link?: string; checkout?: string; /** The release conditions the payment link fixed; the payee accepts only terms that use them. */ conditions?: { attester: string; disputeWindowDays: number }; } ``` ## Notes The payee also sends it in reply to settle/checkout/start. Then the payload has link, checkout and conditions set. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/settle/payment/request/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # settle/payment/terms/accept https://toip.tools/spec/settle/payment/terms/accept/0.1 The payee returns the agreed terms with its own signed acceptance. The payer checks that the terms are the ones it proposed and that the payee signed them. It then opens the escrow through the processor. - **Sent**: payee's party → payer's party - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/settle/src/protocol/specs.ts:9`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/protocol/specs.ts#L9) as `TERMS_ACCEPT` - **Handled in**: [`projects/settle/src/agents/party.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/agents/party.ts) - **Design**: [7. The Trust Tasks](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/docs/design.md#7-the-trust-tasks) in `projects/settle/docs/design.md` ## Payload As the handler declares it, in projects/settle/src/agents/party.ts: ```ts { terms: Terms; acceptance: Acceptance } ``` ### Types it uses projects/settle/src/protocol/documents.ts:71: ```ts export interface Terms { type: "settle/terms"; version: 1; payment: string; purpose: string; payer: Party; payee: Party & { credentials: Credential[] }; arbiter: { did: string; key: Address }; amount: { mint: Address; units: string; display: string }; conditions: { policy: "settle/policies/attested-completion/1"; attester: string; disputeWindowSeconds: number }; /** The processor's facilitator fee: `units` = max(price × bps, minUnits), funded on top of the price, paid on every outcome. */ fee: { bps: number; minUnits: string; units: string; account: Address; to: string }; threshold: number; refundAfter: number; } ``` projects/settle/src/protocol/documents.ts:94: ```ts /** A party's signature on the terms, as its own small document bound to the terms hash. */ export interface Acceptance { type: "settle/acceptance"; issuer: string; termsHash: string; proof?: unknown; } ``` ## Notes The design says the payload is the terms with both proofs. The code sends the terms and the payee's acceptance only. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/settle/payment/terms/accept/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # settle/payment/terms/propose https://toip.tools/spec/settle/payment/terms/propose/0.1 The payer sends the full terms document with its own signed acceptance. The payee checks the terms against its invoice and its limits: price, purpose, token, arbiter, fee, threshold, reclaim deadline, payment-link conditions and the payer's key binding. If everything checks out, it accepts. - **Sent**: payer's party → payee's party - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/settle/src/protocol/specs.ts:8`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/protocol/specs.ts#L8) as `TERMS_PROPOSE` - **Handled in**: [`projects/settle/src/agents/party.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/agents/party.ts) - **Design**: [7. The Trust Tasks](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/docs/design.md#7-the-trust-tasks) in `projects/settle/docs/design.md` ## Payload As the handler declares it, in projects/settle/src/agents/party.ts: ```ts { terms: Terms; acceptance: Acceptance } ``` ### Types it uses projects/settle/src/protocol/documents.ts:71: ```ts export interface Terms { type: "settle/terms"; version: 1; payment: string; purpose: string; payer: Party; payee: Party & { credentials: Credential[] }; arbiter: { did: string; key: Address }; amount: { mint: Address; units: string; display: string }; conditions: { policy: "settle/policies/attested-completion/1"; attester: string; disputeWindowSeconds: number }; /** The processor's facilitator fee: `units` = max(price × bps, minUnits), funded on top of the price, paid on every outcome. */ fee: { bps: number; minUnits: string; units: string; account: Address; to: string }; threshold: number; refundAfter: number; } ``` projects/settle/src/protocol/documents.ts:94: ```ts /** A party's signature on the terms, as its own small document bound to the terms hash. */ export interface Acceptance { type: "settle/acceptance"; issuer: string; termsHash: string; proof?: unknown; } ``` ## Notes The design says either side may propose. In the code only the payer does. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/settle/payment/terms/propose/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # settle/processor/log https://toip.tools/spec/settle/processor/log/0.1 Anyone can ask the processor for its transparency log. The reply holds every entry (openings, signatures, disputes, rulings, holds and settlements, recorded as roles and hashes) and the processor's signed head. - **Sent**: anyone → processor - **Kind**: Request and response. The response's type is `https://toip.tools/spec/settle/processor/log/0.1#response`. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/settle/src/protocol/specs.ts:22`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/protocol/specs.ts#L22) as `PROCESSOR_LOG` - **Handled in**: [`projects/settle/src/agents/roles.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/agents/roles.ts) - **Design**: [9. Arbitration, transparency, privacy](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/docs/design.md#9-arbitration-transparency-privacy) in `projects/settle/docs/design.md` Source documentation: “Request/response: the processor's transparency log.” ## Payload As the handler declares it, in projects/settle/src/agents/roles.ts: ```ts Record ``` ## Response payload As the handler declares it, in projects/settle/src/agents/roles.ts: ```ts { entries: LogEntry[]; head: LogHead } ``` ### Types it uses projects/settle/src/protocol/log.ts:11: ```ts export interface LogEntry { seq: number; at: string; kind: "opened" | "signature" | "dispute" | "ruling" | "hold" | "settled"; termsHash: string; detail: Record; prev: string; hash: string; } ``` projects/settle/src/protocol/log.ts:21: ```ts export interface LogHead { type: "settle/log-head"; issuer: string; size: number; head: string; at: string; proof?: unknown; } ``` ## Notes The demo and tests send it. The web app reads the same log over HTTP at /api/log. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/settle/processor/log/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # settle/processor/submit https://toip.tools/spec/settle/processor/submit/0.1 A party sends the processor a partly signed transaction: an escrow open, reclaim or claim. The processor checks that it holds one Settle instruction that uses the processor's key only for fees and rent, and, for an open, that it matches terms both parties signed. Then it co-signs as fee payer and submits it. - **Sent**: payer's or payee's party → processor - **Kind**: Request and response. The response's type is `https://toip.tools/spec/settle/processor/submit/0.1#response`. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/settle/src/protocol/specs.ts:20`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/protocol/specs.ts#L20) as `PROCESSOR_SUBMIT` - **Handled in**: [`projects/settle/src/agents/roles.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/src/agents/roles.ts) - **Design**: [15. Implementation notes (2026-11-06)](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/docs/design.md#15-implementation-notes-2026-11-06) in `projects/settle/docs/design.md` Source documentation: “Request/response: a partially signed transaction the processor co-signs as fee payer and submits.” ## Payload projects/settle/src/agents/messages.ts:39: ```ts export interface SubmitPayload { transaction: string; /** For an open: the terms and both acceptances, which the processor checks before paying for anything. */ terms?: Terms; acceptances?: Acceptance[]; } ``` ## Response payload projects/settle/src/agents/messages.ts:45: ```ts export type SubmitResult = { ok: boolean; signature?: string; error?: string }; ``` ## Notes Design section 7 says every Settle task is one-way. This one is request/response. A refusal comes back as { ok: false, error }. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/settle/processor/submit/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # tipline/message https://toip.tools/spec/tipline/message/0.1 A reply or a follow-up in a tip's conversation, in either direction. - **Sent**: source or drop box → the other - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/tipline/src/protocol/messages.ts:14`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/src/protocol/messages.ts#L14) as `MESSAGE` - **Handled in**: [`projects/tipline/src/agents/inbox.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/src/agents/inbox.ts), [`projects/tipline/src/agents/source.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/src/agents/source.ts) - **Design**: [7.1 Message types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/docs/design.md#71-message-types) in `projects/tipline/docs/design.md` ## Payload projects/tipline/src/protocol/messages.ts:89: ```ts export interface MessagePayload { tipId: string; /** Unique per message, so a resent thread doesn't show a message twice. */ id: string; text: string; /** Set when the drop box resends the thread: who first wrote this message, and when (to the hour). */ from?: "source" | "dropbox"; at?: string; padding?: string; } ``` ## Notes When the drop box resends a thread, each message says who first wrote it and when, to the hour. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/tipline/message/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # tipline/proof/present https://toip.tools/spec/tipline/proof/present/0.1 The source answers a proof request with a fresh membership proof bound to the challenge. - **Sent**: source's tip DID → drop box - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/tipline/src/protocol/messages.ts:17`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/src/protocol/messages.ts#L17) as `PROOF_PRESENT` - **Handled in**: [`projects/tipline/src/agents/inbox.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/src/agents/inbox.ts), [`projects/tipline/src/agents/source.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/src/agents/source.ts) - **Design**: [7.1 Message types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/docs/design.md#71-message-types) in `projects/tipline/docs/design.md` ## Payload projects/tipline/src/protocol/messages.ts:113: ```ts export interface ProofPresentPayload { tipId: string; challenge: string; membership: MembershipProof; padding?: string; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/tipline/proof/present/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # tipline/proof/request https://toip.tools/spec/tipline/proof/request/0.1 The drop box asks a source for a fresh membership proof, for example against a newer group root, with a challenge to bind it to. - **Sent**: drop box → source's tip DID - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/tipline/src/protocol/messages.ts:16`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/src/protocol/messages.ts#L16) as `PROOF_REQUEST` - **Handled in**: [`projects/tipline/src/agents/inbox.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/src/agents/inbox.ts), [`projects/tipline/src/agents/source.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/src/agents/source.ts) - **Design**: [7.1 Message types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/docs/design.md#71-message-types) in `projects/tipline/docs/design.md` ## Payload projects/tipline/src/protocol/messages.ts:105: ```ts export interface ProofRequestPayload { tipId: string; challenge: string; /** The story the tip was for, so a source who kept nothing knows which proof to make. */ story: string; padding?: string; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/tipline/proof/request/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # tipline/thread/request https://toip.tools/spec/tipline/thread/request/0.1 A source who kept nothing comes back with their tip code and asks the drop box to resend the conversation. - **Sent**: source's tip DID → drop box - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/tipline/src/protocol/messages.ts:15`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/src/protocol/messages.ts#L15) as `THREAD_REQUEST` - **Handled in**: [`projects/tipline/src/agents/inbox.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/src/agents/inbox.ts), [`projects/tipline/src/agents/source.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/src/agents/source.ts) - **Design**: [7.1 Message types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/docs/design.md#71-message-types) in `projects/tipline/docs/design.md` ## Payload projects/tipline/src/protocol/messages.ts:100: ```ts export interface ThreadRequestPayload { tipId: string; padding?: string; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/tipline/thread/request/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # tipline/tip/chunk https://toip.tools/spec/tipline/tip/chunk/0.1 One piece of one attachment, sent after the submit. Dummy chunks pad the count, so the number of messages doesn't reveal the files' sizes. - **Sent**: source's tip DID → drop box - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/tipline/src/protocol/messages.ts:12`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/src/protocol/messages.ts#L12) as `CHUNK` - **Handled in**: [`projects/tipline/src/agents/inbox.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/src/agents/inbox.ts), [`projects/tipline/src/agents/source.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/src/agents/source.ts) - **Design**: [7.1 Message types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/docs/design.md#71-message-types) in `projects/tipline/docs/design.md` ## Payload projects/tipline/src/protocol/messages.ts:53: ```ts export interface ChunkPayload { tipId: string; /** An attachment id, or "pad" for a dummy chunk. */ attachment: string; index: number; count: number; data: string; padding?: string; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/tipline/tip/chunk/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # tipline/tip/receipt https://toip.tools/spec/tipline/tip/receipt/0.1 The drop box tells the source whether the tip was verified or rejected, and why, and asks again for any chunks that didn't arrive. - **Sent**: drop box → source's tip DID - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/tipline/src/protocol/messages.ts:13`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/src/protocol/messages.ts#L13) as `RECEIPT` - **Handled in**: [`projects/tipline/src/agents/inbox.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/src/agents/inbox.ts), [`projects/tipline/src/agents/source.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/src/agents/source.ts) - **Design**: [7.1 Message types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/docs/design.md#71-message-types) in `projects/tipline/docs/design.md` ## Payload projects/tipline/src/protocol/messages.ts:81: ```ts export interface ReceiptPayload { tipId: string; status: "verified" | "rejected"; reason?: ReceiptReason; missing?: { attachment: string; index: number }[]; padding?: string; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/tipline/tip/receipt/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # tipline/tip/submit https://toip.tools/spec/tipline/tip/submit/0.1 A source sends a tip from a fresh DID made from their tip code: the story it's for, the text, a list of attachments, and a zero-knowledge proof that they belong to the organization's group. The proof is bound to this drop box, story and tip, and its nullifier lets the inbox recognize the same source again without knowing who they are. - **Sent**: source's tip DID → drop box (the journalist's inbox) - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/tipline/src/protocol/messages.ts:11`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/src/protocol/messages.ts#L11) as `SUBMIT` - **Handled in**: [`projects/tipline/src/agents/inbox.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/src/agents/inbox.ts), [`projects/tipline/src/agents/source.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/src/agents/source.ts) - **Design**: [7.1 Message types](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/docs/design.md#71-message-types) in `projects/tipline/docs/design.md` ## Payload projects/tipline/src/protocol/messages.ts:41: ```ts export interface SubmitPayload { v: 1; tipId: string; story: string; body: TipBody; attachments: AttachmentInfo[]; /** Sealed chunk messages that follow, dummy ones included. */ chunks: number; membership: MembershipProof; padding: string; } ``` ## Notes Every source message is padded to one fixed size, so its length says nothing about its content. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/tipline/tip/submit/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # todo/ack https://toip.tools/spec/todo/ack/0.1 A new member sends the admin a signed acknowledgement credential (TodoListMembershipAcknowledgement) after accepting the welcome. The admin verifies it and records that the member acknowledged. - **Sent**: new member's device → admin's device - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/shared-todo/src/todo/specs.ts:7`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/src/todo/specs.ts#L7) as `ACK` - **Handled in**: [`projects/shared-todo/src/todo/device.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/src/todo/device.ts) - **Design**: [4.3 Messages](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/docs/design.md#43-messages) in `projects/shared-todo/docs/design.md` ## Payload As the handler declares it, in projects/shared-todo/src/todo/device.ts: ```ts { acknowledgement: Credential } ``` ### Types it uses packages/trust-core/src/credentials.ts:12: ```ts export interface Credential { "@context": string[]; id: string; type: string[]; issuer: string; validFrom: string; validUntil?: string; credentialSubject: { id: string; [k: string]: unknown }; credentialStatus?: { type: "BitstringStatusListEntry"; statusListIndex: number; statusListCredential: string }; proof?: Proof; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/todo/ack/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # todo/join https://toip.tools/spec/todo/join/0.1 A device holding an invitation asks the inviting admin to join the list, with the invitation code, the list's DID and a display name. The admin checks the code, adds the member to a newly signed roster and issues a membership credential, or refuses. - **Sent**: joining device → inviting admin's device - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/shared-todo/src/todo/specs.ts:4`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/src/todo/specs.ts#L4) as `JOIN` - **Handled in**: [`projects/shared-todo/src/todo/device.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/src/todo/device.ts) - **Design**: [4.3 Messages](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/docs/design.md#43-messages) in `projects/shared-todo/docs/design.md` ## Payload As the handler declares it, in projects/shared-todo/src/todo/device.ts: ```ts { code: string; list: string; name: string } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/todo/join/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # todo/join-refused https://toip.tools/spec/todo/join-refused/0.1 The admin tells a joiner why it won't admit them: the invitation is unknown, used or expired, the joiner is already a member, or this device doesn't run the list. The joiner records the reason against its pending join. - **Sent**: admin's device → joining device - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/shared-todo/src/todo/specs.ts:6`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/src/todo/specs.ts#L6) as `JOIN_REFUSED` - **Handled in**: [`projects/shared-todo/src/todo/device.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/src/todo/device.ts) - **Design**: [4.3 Messages](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/docs/design.md#43-messages) in `projects/shared-todo/docs/design.md` ## Payload As the handler declares it, in projects/shared-todo/src/todo/device.ts: ```ts { list: string; reason: string } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/todo/join-refused/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # todo/leave https://toip.tools/spec/todo/leave/0.1 A member who isn't the admin tells the list's admins they are leaving. The admin's device removes them and sends a newly signed roster. - **Sent**: member's device → every admin's device - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/shared-todo/src/todo/specs.ts:12`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/src/todo/specs.ts#L12) as `LEAVE` - **Handled in**: [`projects/shared-todo/src/todo/device.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/src/todo/device.ts) - **Design**: [4.3 Messages](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/docs/design.md#43-messages) in `projects/shared-todo/docs/design.md` ## Payload As the handler declares it, in projects/shared-todo/src/todo/device.ts: ```ts { list: string } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/todo/leave/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # todo/op https://toip.tools/spec/todo/op/0.1 A member who adds, edits, checks, unchecks or deletes an item sends the signed operation, with their membership credential, to every other current member. Each device checks it against the roster, the credential and the policy before applying it. - **Sent**: author's device → every other current member's device - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/shared-todo/src/todo/specs.ts:8`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/src/todo/specs.ts#L8) as `OP` - **Handled in**: [`projects/shared-todo/src/todo/device.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/src/todo/device.ts) - **Design**: [4.3 Messages](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/docs/design.md#43-messages) in `projects/shared-todo/docs/design.md` ## Payload projects/shared-todo/src/todo/device.ts:64: ```ts export interface OpMessage { op: Op; membership?: Credential; } ``` ### Types it uses projects/shared-todo/src/todo/ops.ts:11: ```ts /** * One change to the list, signed by its author. It is separate from the message that carries it, * so anyone can forward it and it still proves who wrote it (design 4.4). */ export interface Op { id: string; type: "todo/op"; list: string; issuer: string; kind: OpKind; itemId: string; at: string; text?: string; sealed?: SealedText; readers?: string[]; membershipId: string; proof?: Proof; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/todo/op/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # todo/roster https://toip.tools/spec/todo/roster/0.1 The admin sends the list's newly signed roster after someone joins or is removed. A device adopts a roster only if the list's key signed it, its version is higher, and it keeps every earlier removal. - **Sent**: admin's device → every current member's device, and once to a member just removed - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/shared-todo/src/todo/specs.ts:9`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/src/todo/specs.ts#L9) as `ROSTER` - **Handled in**: [`projects/shared-todo/src/todo/device.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/src/todo/device.ts) - **Design**: [4.3 Messages](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/docs/design.md#43-messages) in `projects/shared-todo/docs/design.md` ## Payload As the handler declares it, in projects/shared-todo/src/todo/device.ts: ```ts { roster: RosterDoc } ``` ### Types it uses projects/shared-todo/src/todo/roster.ts:23: ```ts /** * The list's signed record of who is in it (design v2 §4.4). Only the list's key signs it, * every change bumps `version`, and a removal is never undone. */ export interface RosterDoc { type: "todo/roster"; issuer: string; list: string; name: string; version: number; issuedAt: string; members: RosterMember[]; proof?: Proof; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/todo/roster/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # todo/sync https://toip.tools/spec/todo/sync/0.1 A device sends one page of a list's history: the current signed roster, up to 100 operations, and the membership credentials those operations need. The receiver adopts the roster as it would any roster and checks each operation as if it had arrived on its own. - **Sent**: member's device → member's device - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/shared-todo/src/todo/specs.ts:11`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/src/todo/specs.ts#L11) as `SYNC` - **Handled in**: [`projects/shared-todo/src/todo/device.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/src/todo/device.ts) - **Design**: [4.3 Messages](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/docs/design.md#43-messages) in `projects/shared-todo/docs/design.md` ## Payload projects/shared-todo/src/todo/device.ts:70: ```ts /** One page of a list's history, in a welcome follow-up or a sync reply. */ interface HistoryPage { list: string; roster: RosterDoc; memberships: Record; ops: Op[]; page: number; last: boolean; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/todo/sync/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # todo/sync-request https://toip.tools/spec/todo/sync-request/0.1 On start and on reconnect, a device asks one other current member (a different one each time) for everything it holds for a list. The receiver answers with todo/sync pages if the requester is a current member. - **Sent**: member's device → one other current member's device - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/shared-todo/src/todo/specs.ts:10`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/src/todo/specs.ts#L10) as `SYNC_REQUEST` - **Handled in**: [`projects/shared-todo/src/todo/device.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/src/todo/device.ts) - **Design**: [4.9 Catching up](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/docs/design.md#49-catching-up) in `projects/shared-todo/docs/design.md` ## Payload As the handler declares it, in projects/shared-todo/src/todo/device.ts: ```ts { list: string } ``` ## Notes The answer is a separate one-way todo/sync, not a response. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/todo/sync-request/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # todo/welcome https://toip.tools/spec/todo/welcome/0.1 The admin admits a joiner. It sends the list's name, the joiner's membership credential and the current signed roster. The joiner verifies all three and replies with todo/ack. The list's history follows as todo/sync pages. - **Sent**: admin's device → joining device - **Kind**: One-way. No response is expected; any answer is a separate message. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`projects/shared-todo/src/todo/specs.ts:5`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/src/todo/specs.ts#L5) as `WELCOME` - **Handled in**: [`projects/shared-todo/src/todo/device.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/src/todo/device.ts) - **Design**: [4.3 Messages](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/docs/design.md#43-messages) in `projects/shared-todo/docs/design.md` ## Payload As the handler declares it, in projects/shared-todo/src/todo/device.ts: ```ts { listName: string; membership: Credential; roster: RosterDoc } ``` ### Types it uses projects/shared-todo/src/todo/roster.ts:23: ```ts /** * The list's signed record of who is in it (design v2 §4.4). Only the list's key signs it, * every change bumps `version`, and a removal is never undone. */ export interface RosterDoc { type: "todo/roster"; issuer: string; list: string; name: string; version: number; issuedAt: string; members: RosterMember[]; proof?: Proof; } ``` packages/trust-core/src/credentials.ts:12: ```ts export interface Credential { "@context": string[]; id: string; type: string[]; issuer: string; validFrom: string; validUntil?: string; credentialSubject: { id: string; [k: string]: unknown }; credentialStatus?: { type: "BitstringStatusListEntry"; statusListIndex: number; statusListCredential: string }; proof?: Proof; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/todo/welcome/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # trail/disclose https://toip.tools/spec/trail/disclose/0.1 A log's controller sends a reader a bundle: the KEL, the chosen trails with the bodies picked for this reader, and the DID bindings. The reader verifies the bundle and reviews the entries, and replies with an empty object. - **Sent**: log controller (for example an agent) → reader (for example the agent's principal) - **Kind**: Request and response. The response's type is `https://toip.tools/spec/trail/disclose/0.1#response`. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`packages/eventlog/src/tasks.ts:16`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/eventlog/src/tasks.ts#L16) as `disclose` - **Handled in**: [`packages/eventlog/src/tasks.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/eventlog/src/tasks.ts) - **Design**: [12.1 \`projects/agents\` (the main consumer)](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/trail/docs/design.md#121-projectsagents-the-main-consumer) in `projects/trail/docs/design.md` ## Payload As the handler declares it, in packages/eventlog/src/tasks.ts: ```ts { bundle: Bundle } ``` ## Response payload As the handler declares it, in packages/eventlog/src/tasks.ts: ```ts Record ``` ### Types it uses packages/eventlog/src/verify.ts:130: ```ts export interface Bundle { kel: string; trails: { id: Qb64; stream: string; bodies?: Body[] }[]; bindings: DidBinding[]; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/trail/disclose/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # trail/duplicity https://toip.tools/spec/trail/duplicity/0.1 Whoever catches duplicity sends the evidence to someone who relies on the log: two conflicting signed versions at the same position, from the controller or from a witness. The evidence proves itself against the controller's KEL. The receiver replies with an empty object. - **Sent**: whoever caught it (a watcher, controller or verifier) → a party that relies on the log - **Kind**: Request and response. The response's type is `https://toip.tools/spec/trail/duplicity/0.1#response`. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`packages/eventlog/src/tasks.ts:17`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/eventlog/src/tasks.ts#L17) as `duplicity` - **Handled in**: [`packages/eventlog/src/tasks.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/eventlog/src/tasks.ts) - **Design**: [10.2 Evidence](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/trail/docs/design.md#102-evidence) in `projects/trail/docs/design.md` ## Payload As the handler declares it, in packages/eventlog/src/tasks.ts: ```ts { evidence: StoredEvidence } ``` ## Response payload As the handler declares it, in packages/eventlog/src/tasks.ts: ```ts Record ``` ### Types it uses packages/eventlog/src/store.ts:56: ```ts /** Evidence as JSON: its two messages as CESR text. */ export interface StoredEvidence extends Omit { a: string; b: string; } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/trail/duplicity/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # trail/head https://toip.tools/spec/trail/head/0.1 A watcher or verifier asks a witness for the head of a log: the latest receipt that witness signed. Watchers compare heads to catch forks and truncated bundles. - **Sent**: watcher or verifier → witness - **Kind**: Request and response. The response's type is `https://toip.tools/spec/trail/head/0.1#response`. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`packages/eventlog/src/tasks.ts:15`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/eventlog/src/tasks.ts#L15) as `head` - **Handled in**: [`packages/eventlog/src/tasks.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/eventlog/src/tasks.ts) - **Design**: [10.3 Watchers](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/trail/docs/design.md#103-watchers) in `projects/trail/docs/design.md` ## Payload As the handler declares it, in packages/eventlog/src/tasks.ts: ```ts { logId: Qb64 } ``` ## Response payload As the handler declares it, in packages/eventlog/src/tasks.ts: ```ts { receipt: string | null } ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/trail/head/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # trail/query https://toip.tools/spec/trail/query/0.1 A watcher or verifier asks a witness for a log's messages and receipts, optionally for a range of sequence numbers. The witness returns them as a CESR text stream. - **Sent**: watcher or verifier → witness - **Kind**: Request and response. The response's type is `https://toip.tools/spec/trail/query/0.1#response`. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`packages/eventlog/src/tasks.ts:14`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/eventlog/src/tasks.ts#L14) as `query` - **Handled in**: [`packages/eventlog/src/tasks.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/eventlog/src/tasks.ts) - **Design**: [10.3 Watchers](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/trail/docs/design.md#103-watchers) in `projects/trail/docs/design.md` ## Payload As the handler declares it, in packages/eventlog/src/tasks.ts: ```ts { logId: Qb64; from?: number; to?: number } ``` ## Response payload As the handler declares it, in packages/eventlog/src/tasks.ts: ```ts { stream: string } ``` ## Notes Qb64 is a string: a CESR primitive in its text form. ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/trail/query/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # trail/witness/receipts https://toip.tools/spec/trail/witness/receipts/0.1 A log's controller passes each witness the receipts the other witnesses signed, so every witness ends up holding every receipt. The witness stores them and replies with an empty object. - **Sent**: log controller → witness - **Kind**: Request and response. The response's type is `https://toip.tools/spec/trail/witness/receipts/0.1#response`. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`packages/eventlog/src/tasks.ts:13`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/eventlog/src/tasks.ts#L13) as `receipts` - **Handled in**: [`packages/eventlog/src/tasks.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/eventlog/src/tasks.ts) - **Design**: [9.3 Getting receipts around](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/trail/docs/design.md#93-getting-receipts-around) in `projects/trail/docs/design.md` ## Payload As the handler declares it, in packages/eventlog/src/tasks.ts: ```ts { stream: string } ``` ## Response payload As the handler declares it, in packages/eventlog/src/tasks.ts: ```ts Record ``` ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/trail/witness/receipts/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # trail/witness/submit https://toip.tools/spec/trail/witness/submit/0.1 A log's controller sends a witness KEL events or trail messages to witness. The witness verifies each one, keeps the first version it sees at each position, and returns receipts. If it refuses, it says why, and on duplicity it returns the version it saw first. - **Sent**: log controller → witness - **Kind**: Request and response. The response's type is `https://toip.tools/spec/trail/witness/submit/0.1#response`. - **Envelope**: Signed by the issuer, addressed to one recipient, timestamped, and encrypted in a TSP Direct message. The signature and recipient binding prevent its use as a bearer token. - **Defined in**: [`packages/eventlog/src/tasks.ts:12`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/eventlog/src/tasks.ts#L12) as `submit` - **Handled in**: [`packages/eventlog/src/tasks.ts`](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/eventlog/src/tasks.ts) - **Design**: [9.2 What it does](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/trail/docs/design.md#92-what-it-does) in `projects/trail/docs/design.md` ## Payload As the handler declares it, in packages/eventlog/src/tasks.ts: ```ts { stream: string } ``` ## Response payload packages/eventlog/src/client.ts:6: ```ts export type SubmitResult = | { ok: true; receipts: string } /** `receipts` holds receipts for messages before the refused one. (Additive.) */ | { ok: false; refusal: Refusal; problems: Problem[]; firstSeen?: string; receipts?: string }; ``` ## Notes The same operation is also served over HTTP (witnessHttpHandler). ## Document envelope Every Trust Task uses this envelope. Replace `payload` with the structure shown above. Shape of a document of this type: ```json { "id": "urn:uuid:…", "type": "https://toip.tools/spec/trail/witness/submit/0.1", "issuer": "did:key:… (the sender)", "recipient": "did:key:… (the receiver)", "issuedAt": "2026-11-06T18:00:00.000Z", "payload": { … }, "proof": { "type": "DataIntegrityProof", "cryptosuite": "eddsa-jcs-2022", "verificationMethod": "did:key:…#…", "proofPurpose": "assertionMethod", "proofValue": "z…" } } ``` # Examples Explore the toolkit through payments, private collaboration, anonymous speech, and agent delegation. Each project has a written design; working examples include commands to run them locally. **Working** projects run and have tests. **Being built** projects have a design and an implementation in progress. **Design only** projects are proposals ready to build. Set up the repository once: ```bash git clone https://github.com/yourbuddyconner/toip-tools.git cd toip-tools npm install ``` ## Settle Working Conditional payments with shared control of escrow. A customer pays through a link, and stablecoins wait in a Solana escrow until two of the payer, payee, and arbiter sign to move them. Signed Trust Tasks coordinate each step. Before signing, each party's device checks the payment's Rego policy. ### What it shows - A Trust Task vocabulary for a real protocol: invoices, terms, attestations, disputes, rulings, receipts. - Identity off-chain, fresh keys on-chain, bound together by credentials only the parties see. - Passkey-sealed keys in the browser, and operators who sign in with their own key instead of a password. Built on [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/), [`@toip-tools/relay`](https://toip.tools/toolkit/relay/) and [`@toip-tools/web-vault`](https://toip.tools/toolkit/web-vault/). Message reference: [`settle/…` Trust Tasks](https://toip.tools/spec/#settle). ### Run it The whole network and the web app, on a local Solana cluster: ```bash npm run settle ``` Run the terminal demo: ```bash npm run demo --workspace projects/settle ``` The app in a real browser, with screenshots: ```bash npm run e2e --workspace projects/settle ``` ![Settle's hosted checkout: Joe's Plumbing, verified, asks 120.00 USDC to fix a kitchen sink, and explains that the money goes into an escrow nobody can empty alone.](https://toip.tools/img/settle-checkout.jpg) *Hosted checkout for a payment link.* ![A released payment: payer and payee seals are checked, the arbiter's is empty, and an activity list shows each signed step from invoice to receipt.](https://toip.tools/img/settle-released.jpg) *Two signatures release the funds. The activity log records each Trust Task.* ![The operator view of a dispute: the payer reported no hot water, and the arbiter is ruling 180 of 300 USDC to the plumber, with reasons.](https://toip.tools/img/settle-arbiter.jpg) *An arbiter signs a split ruling, preserving the decision as evidence.* Read Settle's [README](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/README.md) and [design](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/settle/docs/design.md), or browse [its source](https://github.com/yourbuddyconner/toip-tools/tree/main/projects/settle). ## Shared To-Do Working Private to-do lists for a household. Each person and list has its own key and DID, created on the device. The list signs membership credentials, and members exchange signed changes in encrypted TSP messages. Every device verifies a change before applying it; the relay handles delivery without reading the list. ### What it shows - Identity, credentials, and encrypted messaging in a small collaborative app. - Invitations, roles, removal, and private items sealed to chosen readers. - Offline outboxes and catching up from other members, through a relay that can't read anything. Built on [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/) and [`@toip-tools/relay`](https://toip.tools/toolkit/relay/). Message reference: [`todo/…` Trust Tasks](https://toip.tools/spec/#todo). ### Run it The relay on ws://localhost:8787 and the app on http://localhost:5181: ```bash npm run dev ``` Read Shared To-Do's [README](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/README.md) and [design](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/shared-todo/docs/design.md), or browse [its source](https://github.com/yourbuddyconner/toip-tools/tree/main/projects/shared-todo). ## Tipline Working A drop box that lets sources prove membership without revealing their identity. A source shows a journalist that they belong to an organization, shares documents, and continues the conversation using a fresh DID for the tip. A code written on paper lets them return without keeping the conversation on their device. ### What it shows - Zero-knowledge group membership in the browser. - Counting distinct sources by nullifier without knowing any of them. Built on [`@toip-tools/anon-membership`](https://toip.tools/toolkit/anon-membership/), [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/), [`@toip-tools/relay`](https://toip.tools/toolkit/relay/) and [`@toip-tools/web-vault`](https://toip.tools/toolkit/web-vault/). ### Run it The organization, the source app, the journalist's inbox and the relay, each on its own localhost origin: ```bash npm run tipline ``` Run the terminal demo: ```bash npm run demo --workspace projects/tipline ``` The demo in a real browser, checking the source leaves nothing behind: ```bash npm run e2e --workspace projects/tipline ``` Read Tipline's [README](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/README.md) and [design](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/tipline/docs/design.md), or browse [its source](https://github.com/yourbuddyconner/toip-tools/tree/main/projects/tipline). ## Agora Working Anonymous forums with verified membership. A forum can require a nursing license to post, or district residency to vote, without asking members to reveal their identity. Each membership has one pseudonym per forum; the membership proofs keep those pseudonyms from being linked across forums. ### What it shows - Credential-gated anonymity with attribute predicates. - One vote per person with secret ballots. - A signed, append-only feed the host can't quietly rewrite. Built on [`@toip-tools/anon-membership`](https://toip.tools/toolkit/anon-membership/), [`@toip-tools/eventlog`](https://toip.tools/toolkit/eventlog/), [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/), [`@toip-tools/relay`](https://toip.tools/toolkit/relay/) and [`@toip-tools/web-vault`](https://toip.tools/toolkit/web-vault/). ### Run it Issuers, the forum host and the web app on http://localhost:4320: ```bash npm run agora ``` Run the twelve-step terminal demo: ```bash npm run demo --workspace projects/agora ``` Members, a non-member and a reader, in a real browser: ```bash npm run e2e --workspace projects/agora ``` Read Agora's [README](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agora/README.md) and [design](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agora/docs/design.md), or browse [its source](https://github.com/yourbuddyconner/toip-tools/tree/main/projects/agora). ## Agents Working AI agents with identities, spending limits, and accountable actions. A person or company gives an agent a revocable mandate. As it hires people and other agents through Settle, a guard checks every payment and message against that mandate chain. A signed audit trail lets the principal review what happened. ### What it shows - Delegation that only narrows, checked by both the agent's guard and its counterparties. - Escalation to a human for one exact action. - Audit trails an agent can't quietly rewrite. Built on [`@toip-tools/mandates`](https://toip.tools/toolkit/mandates/), [`@toip-tools/eventlog`](https://toip.tools/toolkit/eventlog/), [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/) and [`@toip-tools/relay`](https://toip.tools/toolkit/relay/). ### Run it The principal's console and the courier's view on http://localhost:4330: ```bash npm run agents ``` Run the terminal demo with scripted models: ```bash npm run demo --workspace projects/agents ``` Run with Claude; requires ANTHROPIC\_API\_KEY: ```bash npm run demo --workspace projects/agents -- --live ``` Read Agents's [README](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/README.md) and [design](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/agents/docs/design.md), or browse [its source](https://github.com/yourbuddyconner/toip-tools/tree/main/projects/agents). ## Trail Working Verifiable audit trails for agents, devices, and services. A local network of witnesses and watchers makes log tampering visible in a web explorer. The demo walks through forged edits, conflicting histories, dishonest witnesses, and recovery from a stolen key. ### What it shows - KERI key event logs with pre-rotation and witnesses, verified by KERIpy. - Duplicity detection by watchers. Built on [`@toip-tools/eventlog`](https://toip.tools/toolkit/eventlog/) and [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/). ### Run it Four witnesses, two watchers and the explorer on http://localhost:4340: ```bash npm run trail ``` Run the terminal demo, including tampering and recovery: ```bash npm run demo --workspace projects/trail ``` The explorer through all ten steps in a real browser: ```bash npm run e2e --workspace projects/trail ``` Read Trail's [README](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/trail/README.md) and [design](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/trail/docs/design.md), or browse [its source](https://github.com/yourbuddyconner/toip-tools/tree/main/projects/trail). ## Capture Working Verifiable origins for photos and sensor readings. Devices sign captures with their own keys, and edits extend a signed history. A browser verifier checks the device, the capture's time interval, and which image tiles remain unchanged after redaction. ### What it shows - Non-exportable WebCrypto device keys, protected by passkeys or passphrases. - Owner-to-device mandates. - Key histories that keep old captures verifiable after a rotation. Built on [`@toip-tools/cose`](https://toip.tools/toolkit/cose/), [`@toip-tools/eventlog`](https://toip.tools/toolkit/eventlog/), [`@toip-tools/mandates`](https://toip.tools/toolkit/mandates/), [`@toip-tools/web-vault`](https://toip.tools/toolkit/web-vault/) and [`@toip-tools/mesh-transport`](https://toip.tools/toolkit/mesh-transport/). ### Run it The camera, editor, verifier and sensor dashboard on http://localhost:4350, with witnesses and simulated sensors: ```bash npm run capture ``` One more sensor, sending signed readings over the simulated LoRa radio: ```bash npm run sensor --workspace projects/capture ``` Capture, a blur edit and verification in a real browser with a fake camera: ```bash npm run e2e --workspace projects/capture ``` Read Capture's [README](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/capture/README.md) and [design](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/capture/docs/design.md), or browse [its source](https://github.com/yourbuddyconner/toip-tools/tree/main/projects/capture). ## Mesh Working Trust Tasks beyond an internet connection. Three simulator demos verify a door pass offline, forward a Settle attestation through a radio gateway, and deliver a sealed bundle by hand. A visualizer shows the frames, retries, and airtime. Real-radio bring-up and Bluetooth LE remain future work. ### What it shows - Compact Trust Tasks with every proof intact. - Random-looking address tags instead of DIDs on the air. - Gateways that hand exact TSP bytes to the relay. Built on [`@toip-tools/mesh-transport`](https://toip.tools/toolkit/mesh-transport/), [`@toip-tools/cose`](https://toip.tools/toolkit/cose/) and [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/). ### Run it The radio visualizer on http://localhost:4360: a field map, frames in flight, airtime meters: ```bash npm run mesh ``` Run all three demos on the simulated radio: ```bash npm run demo --workspace projects/mesh ``` Checks a LoRa gateway or RAK3172 is talking to you (see HARDWARE.md): ```bash npm run mesh --workspace projects/mesh -- doctor ``` Read Mesh's [README](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/mesh/README.md) and [design](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/mesh/docs/design.md), or browse [its source](https://github.com/yourbuddyconner/toip-tools/tree/main/projects/mesh). ## Commons Design only Everyday tools for an apartment building and its households. The design brings guest passes, shared expenses, maintenance requests, votes, and noticeboards under one identity per person. The building and its households form nested communities with their own roles. ### What it shows - Nested communities and roles. - Many small apps sharing one identity and one trust core. Built on [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/) and [`@toip-tools/relay`](https://toip.tools/toolkit/relay/). ### Build status The design is ready for an implementation. Read it below, or [help build it](https://toip.tools/get-involved/#propose). Read Commons's [README](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/commons/README.md) and [design](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/commons/docs/design.md), or browse [its source](https://github.com/yourbuddyconner/toip-tools/tree/main/projects/commons). ## Community Rides Design only A proposal for ride sharing within a local community. The community vouches for its members, and riders and drivers verify those claims directly. Built around the OpenVTC libraries and applicable registry specifications, the design traces what each party learns at every step. ### What it shows - Registry Trust Tasks alongside your own. - What each party learns, step by step. Designed using the [OpenVTC](https://github.com/OpenVTC) TypeScript libraries directly. ### Build status The design is ready for an implementation. Read it below, or [help build it](https://toip.tools/get-involved/#propose). Read Community Rides's [README](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/community-rides/README.md) and [design](https://github.com/yourbuddyconner/toip-tools/blob/main/projects/community-rides/docs/design.md), or browse [its source](https://github.com/yourbuddyconner/toip-tools/tree/main/projects/community-rides). # Ecosystem ToIP, First Person, OpenVTC, and the P2P Trust Stack are connected communities and projects. They have different scopes, architectures, and implementation choices. Start with the architecture ## Coming from ToIP? The [Trust over IP Foundation](https://trustoverip.org/) develops an architecture for digital trust, pairing technology with governance. Its model leaves ecosystems in control of their own implementations. A ToIP specification, a network built around it, and a software package implementing it are different things. That distinction matters here. You can use TSP without adopting a particular community model, use KERI for key histories without deploying a complete agent stack, or implement Trust Tasks over different transports. The [ToIP model](https://trustoverip.org/toip-model/) makes room for that diversity. ### Read the choices, not just the names. Two projects can use “agent,” “community,” or “trust task” and still differ in who holds keys, how messages move, and how authority is checked. [Compare the implementation choices](https://toip.tools/ecosystem/#choices) The names you'll encounter | Name | What it contributes | Start here | | --- | --- | --- | | ToIP | Architecture, governance frameworks, and protocol specifications. | [The model](https://trustoverip.org/toip-model/) · [TSP](https://trustoverip.github.io/tswg-tsp-specification/) | | First Person | A network vision centered on personhood and real trust relationships. | [The network vision](https://toip.tools/ecosystem/#first-person) | | OpenVTC / VTI | Agent and community services, applications, and protocol libraries. | [The service approach](https://toip.tools/ecosystem/#openvtc) | | P2P Trust Stack | TrustStackers' integrated agent stack with libp2p networking. | [The agent approach](https://toip.tools/ecosystem/#p2p) | | KERI / WebOfTrust | Key-event histories, pre-rotation, witnesses, and supporting implementations. | [The key-history approach](https://toip.tools/ecosystem/#keri) | | DIF / DIDComm | Decentralized identity engineering and a distinct messaging protocol family. | [The messaging approach](https://toip.tools/ecosystem/#dif) | | W3C DIDs / VCs | Shared identifier and credential data models used across projects. | [DIDs](https://www.w3.org/TR/did-1.0/) · [Credentials](https://www.w3.org/TR/vc-data-model-2.0/) | | Trust Tasks | A ToIP task framework and registry of interaction specifications. | [The task vocabulary](https://toip.tools/ecosystem/#trust-tasks) | Different starting points ## What each approach emphasizes These perspectives overlap. People contribute across communities, and one system can combine several of them. The differences below describe documented design choices, rather than fixed camps. Network vision ### First Person How do real relationships become verifiable? The First Person Project starts with people and their relationships. Its white paper proposes personhood credentials issued within an ecosystem, relationship credentials exchanged between people, and a network built from those connections. The First Person Network is the intended network; the First Person Cooperative is the governance body proposed in the paper. Neither name identifies a single software distribution. [Read the First Person white paper](https://www.firstperson.network/white-paper) Service infrastructure ### OpenVTC & VTI How do agents and communities operate? OpenVTC contains several projects. Its Rust Verifiable Trust Infrastructure implementation provides VTA services for keys and authority, and VTC services for community membership and credentials. The separate VTI specification defines their composition, trust contexts, and client authority. OpenVTC also publishes TypeScript protocol libraries. This toolkit uses those libraries; it does not deploy the full VTI service architecture. [VTI implementation](https://github.com/OpenVTC/verifiable-trust-infrastructure) · [VTI specification](https://trustoverip.github.io/dtgwg-vti-spec/) · [TypeScript TSP library](https://github.com/OpenVTC/vta-browser-plugin/tree/main/packages/tsp-js) Integrated agent stack ### P2P Trust Stack What does a complete peer agent need? TrustStackers' implementation brings identity, an encrypted keystore, TSP messaging, relationship ceremonies, communities, and an application API into one Node.js stack. Its documented choices include `did:peer:4` and `did:scid:vh`, libp2p transport, and a structured local policy interpreter. That is a specific implementation of related ideas, with different APIs and deployment assumptions from OpenVTC or this toolkit. [Read the P2P Trust Stack README](https://github.com/TrustStackers/p2p-trust-stack) · [Policy implementation](https://github.com/TrustStackers/p2p-trust-stack/blob/main/packages/core/src/services/local-policy-engine.ts) Key-event architecture ### KERI & WebOfTrust How does an identity survive changes to its keys? KERI starts with verifiable key history: an identifier's signed events record key establishment and rotation, while witnesses and watchers help expose conflicting histories. KERIpy, in the WebOfTrust organization, is an implementation. The KERI specification is developed within ToIP. It addresses an identity foundation that other systems can build on; it does not prescribe every application, transport, or community rule. [KERI specification](https://trustoverip.github.io/kswg-keri-specification/) · [KERIpy](https://github.com/WebOfTrust/keripy) Identity engineering & messaging ### DIF & DIDComm How do identity agents exchange messages? The Decentralized Identity Foundation develops specifications and reference implementations across decentralized identity. DIDComm is one of its messaging efforts: encrypted messages, routing, and higher-level interactions built around DIDs. DIDComm and TSP are distinct protocols. Sharing DIDs or an application goal does not make their messages interchangeable. This toolkit currently uses TSP. [Explore DIF](https://identity.foundation/) · [DIDComm specification](https://identity.foundation/didcomm-messaging/spec/v2.1/) Interaction specifications ### Trust Tasks What work are the parties agreeing to do? The Trust Tasks effort under ToIP's Decentralized Trust Graph Working Group defines a JSON task framework and a registry of specifications. Tasks describe interactions; delivery is a separate concern. A task can travel over different transports. A registry entry also does not establish that a particular agent implements it. This site's [task reference](https://toip.tools/spec/) documents the project-specific types used here. [Framework and registry source](https://github.com/trustoverip/dtgwg-trust-tasks-tf) · [Browse the registry](https://trusttasks.org/) Where the differences matter ## Compare decisions, not labels | Decision | This toolkit | Other approaches | | --- | --- | --- | | Identity | `did:key` for messaging; KERI histories in the event-log library. | The P2P Trust Stack supports `did:peer:4` and `did:scid:vh`. KERI models identity through a key-event history. | | Messaging | TSP Direct over a WebSocket relay, an in-memory bus, or the mesh transport. | The P2P Trust Stack integrates libp2p. DIDComm defines another message protocol, independently of its delivery transport. | | Authority | Credential-based mandates and local Rego policy checks. | The P2P Trust Stack has its own policy interpreter. VTI specifies authority within trust contexts and client enrollment. | | Deployment | Separate libraries and example apps for browsers and Node. | TrustStackers documents a Node-only agent stack. OpenVTC's VTI implementation runs Rust services and clients. | These comparisons describe the sources linked above. Shared protocol names are not an interoperability result: this toolkit has not been tested against the P2P Trust Stack. Where we fit ## An independent place to experiment. toip.tools is a collection of TypeScript libraries and runnable examples. It uses OpenVTC's TSP and Trust Tasks libraries, W3C-shaped credentials, and its own application protocols. The relay, mandates, anonymous membership proofs, and audit trails reflect choices made in this repository. Use it to explore those choices in code. For the architecture behind another project, start with that project's documentation. [Try the toolkit](https://toip.tools/quickstart/) · [Read the source](https://github.com/yourbuddyconner/toip-tools) # Machine-readable docs Everything on this site, in forms that AI assistants, search engines and scripts can read directly. For coding assistants ## Ask your AI assistant Assistants write better code with the documentation in front of them. Paste this prompt into yours, then describe what you're building. Prompt: ```text I'm building with the @toip-tools TypeScript libraries (on npm, Node 22.13 or later). Before writing code, read https://toip.tools/llms-full.txt: it holds their documentation, guides and Trust Task reference. Use only the exports and options it documents, install packages as @toip-tools/, and tell me if something I ask for isn't supported. My task: ``` [llms-full.txt](https://toip.tools/llms-full.txt) · all docs in one Markdown file · [llms.txt](https://toip.tools/llms.txt) · an index · [JSON indexes](https://toip.tools/api/) · packages, exports and Trust Tasks ## llms.txt [`/llms.txt`](https://toip.tools/llms.txt) follows the [llms.txt proposal](https://llmstxt.org/): a short summary and a list of the most useful pages, each linked to its Markdown version. [`/llms-full.txt`](https://toip.tools/llms-full.txt) holds the documentation, quickstart, concepts, FAQ, every guide, every library guide, the API export lists and the Trust Task reference, concatenated as Markdown with real code. Both are generated at build time from the same pages as the HTML, so they can't drift from it. ## Markdown version of every page Add `index.md` to any page's address for the same content as clean Markdown: headings, prose, code blocks with their language, and absolute links. Each HTML page also names its twin in a `` tag, and documentation pages have a **Copy page as Markdown** button. Terminal: ```bash curl https://toip.tools/guides/run-tsp-relay/index.md ``` ## JSON indexes - **[`/api/libraries.json`](https://toip.tools/api/libraries.json)**: Every package: name, version, description, install command, runtimes, entry points, and each export with its kind, one-line summary and reference page. Also its documentation, npm and source URLs. - **[`/api/specs.json`](https://toip.tools/api/specs.json)**: Every Trust Task type: URI, purpose, sender, receiver, kind (one-way or request and response), the payload and response types as declared in the code, and links to its definition and design. - **[`/api/examples.json`](https://toip.tools/api/examples.json)**: Every example project: status, what it shows, the libraries it uses, and the commands that run it. ## Feeds and crawling - [`/sitemap.xml`](https://toip.tools/sitemap.xml) lists every page, with the date its sources last changed. - [`/robots.txt`](https://toip.tools/robots.txt) allows every crawler, AI crawlers included. - [`/releases.xml`](https://toip.tools/releases.xml) is an Atom feed of library releases; the [releases page](https://toip.tools/releases/) shows the same changelogs. - Pages carry JSON-LD structured data: `TechArticle`, `SoftwareSourceCode`, `FAQPage` and `BreadcrumbList`.