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.

---

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