toip.tools

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/mandatesv0.1.0Source

Setup

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

ShellInstall
npm install @toip-tools/mandates

Runtime: Browsers and Node.

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

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.

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.

Example

An owner lets a camera sign photos in California only. The engine decides each action.

TypeScriptsite/examples/snippets/mandates.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(" "));
}
ShellRun from the repository root
npx tsx --tsconfig site/tsconfig.json site/examples/snippets/mandates.ts
OutputRecorded output
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.

Bundled assets