@zanii/mandate-verify-core
v0.4.0
Published
Pure verification engine. It receives a signed mandate, an action request, a status list, and **server-injected** policy/context; it returns a decision. It does no database, HTTP or filesystem access. Supply the server clock explicitly through `now` for d
Readme
verify-core
Pure verification engine. It receives a signed mandate, an action request, a
status list, and server-injected policy/context; it returns a decision. It
does no database, HTTP or filesystem access. Supply the server clock explicitly through now for deterministic evaluation.
Usage
import { verifyMandate } from '#verify-core';
const result = verifyMandate({
mandate,
request: {
...action,
periodCount: usage.count,
periodAmount: { value: '125.00', currency: 'AED' },
},
statusList,
issuerPublicKey,
pins: {
trustedIssuers: configuredTrustedIssuers,
maxStatusAgeSeconds: 300,
allowPrincipalMismatch: false,
},
delegationChain: [],
approvals: [],
now: new Date(),
});The production API does not accept pins, now, usage, a delegation chain, a
status list, certification status, receipt IDs, or a raw mandate from the caller.
Store loads server state and calls verifyMandate; caller attempts to send
those fields are rejected with 400 UNSUPPORTED_FIELD. V1 has no certification
or receipt adapter, so a mandate that requires either fails closed.
Result
{
verdict: 'allow' | 'deny' | 'review' | 'error',
reasons: [{ code, severity, message, details? }],
checks: [{ code, ok, severity }],
status: { status, listId, version, index },
evaluatedAt: '...'
}deny: at least one hard failure.review: no hard failure, at least one soft failure.error: malformed input or an evaluation exception.
allow is returned only when every check passes. Soft failures do not authorize. Configure trusted issuer identities independently of the candidate mandate: an empty or missing trusted-root configuration denies authorization. A valid self-contained did:key signature establishes key possession, not permission. Use the signature-only primitives when authorization policy is not being evaluated.
Main checks
Schema and version; issuer key resolution; signature; issuer trust; agent and principal binding; validity window; status list presence, issuer, reference, signature, freshness, version, index, and bit; actions; resources; amount and count limits; data class; jurisdiction; time window; approvals; delegation; certification; evidence/receipts; regulator supervision.
Regulator supervision. Pass supervisionStatus: { trusted, asOf, suspended, reason, scope },
resolved by the caller from a verified @zanii/status-feed 0.3.0 feed (activeSuspensions,
suspensionFor). A suspension denies with SUPERVISION_SUSPENDED. With
pins.requireSupervision: true, missing, untrusted or stale status (older than
pins.supervisionMaxAgeSeconds, default 300) denies with SUPERVISION_UNVERIFIED: fail closed.
Without the pin and without a status, the verdict is unchanged.
Any action, any business
These optional constraint fields are evaluated when present; mandates without them decide exactly as before.
| Field | Effect | Reason codes |
|---|---|---|
| deniedActions, deniedResources (patterns), deniedDataClasses | A match is always a hard deny, even when actions/resources allow it. An unknown request data class gives review. | ACTION_DENIED, RESOURCE_DENIED, DATA_CLASS_DENIED, DATA_CLASS_UNKNOWN |
| maxCount.period: minute \| hour | UTC calendar windows counted by the server, like day/month. | COUNT_LIMIT_EXCEEDED, PERIOD_COUNT_UNKNOWN |
| approvalAbove: { amount?, count?, riskTier?, approvals?, approver?, minAcr? } | Above any limit (an unknown amount, count or vocabulary tier counts as above) the request needs approval through the same flow as requiredApprovals: review, or deny when pins.requireApproval is true. | APPROVAL_*, SEPARATION_OF_DUTIES |
| revocation.maxStatusAgeSeconds | The mandate's own status freshness budget; status is then always required. Validity above 7 days is accepted only with it and only up to pins.maxValidityDays (1 to 365). | STATUS_STALE, STATUS_MISSING, VALIDITY_EXCEEDS_POLICY |
| conditions: [{ type, params? }] | Checked by condition providers. | CONDITION_PROVIDER_MISSING, CONDITION_NOT_MET, CONDITION_ERROR |
Conditions use async providers, { [type]: async ({ mandate, request, condition, now }) => ({ ok, reason?, evidence? }) }:
import { verifyMandateAsync } from '#verify-core';
const result = await verifyMandateAsync({ ...options, conditionProviders, conditionTimeoutMs: 2000 });
// result.conditions: [{ index, type, ok, code?, reason?, evidence? }]Providers run only after schema and signature checks pass. A missing provider,
ok: false, a throw, a malformed result or a timeout (default 2000 ms) denies.
The synchronous verifyMandate accepts precomputed conditionResults from
evaluateConditions; each result is bound to the exact signed condition (index,
type and canonical params). Without results a conditioned mandate is denied.
The request fields dataSubject, counterpartyDid, dataRegion, destination
and transferSafeguard (strings, at most 512 characters) pass through to providers.
approvalAbove.riskTier triggers for actions whose vocabulary tier ranks above
the given tier, and for free action names with no tier. The default server
configuration (packages/config) sets requireApproval: true, so through
POST /v1/verify a missing approval is a deny; the operation flow holds the
action for review instead.
Delegation keeps every restriction: a child must cover each parent deny, keep
each parent condition, keep an approvalAbove that is at least as strict, keep
the same count period, and keep a freshness budget no weaker than the parent's.
inheritParentRestrictions copies parent denies, conditions and the freshness
budget into child issuance input.
Delegation
validateDelegationChain lives in src/delegation.js. It checks that the child
scope is a subset of the parent: actions, resources, amount/period, count/period,
jurisdictions, data classes, time window, required approvals, certification
level/scope, evidence confidence, expiry, depth, and the parent signature. It is
exported separately for tests and for callers that want to validate a chain
without a full request.
Supply root-to-nearest-parent entries as { mandate, statusList } with each parent's signed status envelope and independently configured root trust. Every link binds the parent ID, authorized child issuer, validity, depth and exact logical status-list reference. Numeric status claims, per-item key overrides and chains embedded in the action request do not establish authority. Supported references are the logical list ID or its urn:zanii:status: encoding; arbitrary URI suffixes do not bind a list. Stable-DID parent/status keys can be resolved through server-owned resolveMandatePublicKey and resolveStatusPublicKey pin callbacks; request- or artifact-supplied callbacks are not trusted context.
Root passports
verifyPassport checks an agent's mandate all the way up to a root authority (for example a
free zone), offline. The root signs one passport mandate to the firm's issuer DID. The firm then
issues its own tree (company, role, release, instance) with ordinary delegation, so it never
needs the root to sign anything else.
import { verifyPassport } from '#verify-core';
const result = verifyPassport({
passport, // signed by rootDid, agent = the firm's issuer DID, delegation allowed
passportStatusList, // the root's signed status list
rootDid,
mandate, // the agent instance's mandate
statusList,
delegationChain, // the firm's chain, top first: [{ mandate, statusList }, ...]
request: { agentDid, action, resource },
});It denies when the passport is not from rootDid (PASSPORT_ROOT_UNTRUSTED), is not a root
(PASSPORT_NOT_ROOT), names a different issuer (PASSPORT_ISSUER_MISMATCH), does not allow
issuing (PASSPORT_NOT_DELEGABLE), or when the firm's top mandate exceeds it
(PASSPORT_SCOPE_EXCEEDED). Then it runs verifyMandate twice: the passport against the
request with the root as the only trusted issuer (reasons tagged scope: 'passport'), and the
firm's chain with the firm's issuer as the only trusted issuer. Revoking any level, from the
passport down to the instance, denies everything below it. Budgets on the passport cannot be
counted offline, so they give review, not allow.
Offline trust bundles
createOfflineTrustBundle in #db reads an initialized control store and exports
one root-to-leaf chain. It does not sign a new snapshot or mint an authorization.
The latest signed status for every artifact must already satisfy the producer's
freshness bound. verifyOfflineTrustBundle is pure: it performs no database,
filesystem, HTTP, clock mutation, usage, reservation, or approval operation.
import { createOfflineTrustBundle } from '#db';
import { verifyOfflineTrustBundle } from '#verify-core';
const bundle = await createOfflineTrustBundle({
store: controlStore,
mandateId,
maxStatusAgeSeconds: 25,
});
const result = verifyOfflineTrustBundle({
bundle,
request: { agentDid, action: 'supplier.read', resource: 'supplier:one' },
trustAnchors: configuredAnchors,
statusCheckpoints: durableCheckpoints,
maxStatusAgeSeconds: 25,
now: new Date(),
});Version 1 format
The JSON object has format: "zanii-offline-trust-bundle", a manifest, public
issuerKeys, and mandates. The manifest binds the root issuer DID,
bundleVersion: 1, createdAt, and contentHash. The hash is SHA-256 over the
canonical bundle with manifest.contentHash removed. Each mandates entry has:
artifact: the exact signed mandate JSON string from the control store;statusEnvelope: the exact signed status JSON string, including its proof andvalidFrom/validUntilwindow.
Entries are root-to-leaf and contain the leaf as well as every parent and parent status. Public issuer history preserves key ID, DID, purpose, verification method, activation, retirement, compromise, and creation timestamps. Private JWK parameters and signing keys are never exported. The bundle contains no trust anchors, trusted-issuer list, verifier pins, usage, approval, or dispatch policy. Its content hash detects modification; it is not a signature and does not make bundle metadata or key history trustworthy.
Caller-owned trust and status checkpoints
trustAnchors is mandatory caller configuration, never bundle input:
const configuredAnchors = [{
issuerDid: 'did:example:issuer',
keys: [{
purpose: 'mandate', // or "status"
verificationMethod: 'did:example:issuer#keyhist_...',
publicKey: configuredPublicJwk,
activatedAt: '...',
retiredAt: null,
compromisedAt: null,
}],
}];Every mandate and status proof must match a configured key for its exact issuer,
purpose, verification method, and artifact-time key-history window. The root
issuer must be explicitly anchored. A valid signature from an unknown issuer,
or a key copied from bundle.issuerKeys, does not establish trust. Stable-DID
chains need configured key resolution for each signing issuer; delegation still
has to prove parent-agent authority from the trusted root.
Optional statusCheckpoints are caller-durable high-water records with issuer,
listId, version, and hash. Older snapshots deny with STATUS_ROLLBACK;
different bytes at an accepted version deny with STATUS_EQUIVOCATION. Results
return one checkpoint per issuer/list only for fresh, authenticated snapshots,
including a fresh revoked snapshot that correctly denies. Persist those records
atomically outside the verifier. Stale or unauthenticated results return no new
checkpoint. Deduplication across a chain does not remove any parent's separate
signature, status, freshness, or delegation checks.
What an offline verdict proves, and does not prove
The verifier checks the manifest hash, every mandate/status signature against
caller anchors, schema and expiry, full chain IDs, parent-agent authority,
cycles, maximum depth, scope attenuation, each parent's fresh signed status,
leaf status, action/resource scope, and static request constraints. Verdicts are
allow, deny, or review with machine-readable reasons. Malformed input and
core evaluation errors fail closed as deny.
Every result has offline: true and dispatchPermit: false. notEstablished
always reports that later revocation and operation-bound dispatch authorization
were not established. An offline allow is a static evaluation under fresh
signed status at evaluatedAt; it is not a reusable permit, a reservation, an
approval release, a spend, or evidence of an external outcome.
Count quotas, day/month amount quotas, and applicable required approvals add
DYNAMIC_STATE_UNAVAILABLE and prevent allow (normally producing review
when all static checks pass). Certification and required-receipt state are also
unavailable offline. Caller-supplied period usage, approval IDs, and receipt IDs
are ignored rather than treated as authoritative. dynamicState identifies the
missing requirements. Transaction-scoped static amount checks and mandates with
no dynamic requirements can still produce offline allow. Current quotas,
approvals, reservations, and dispatch require the authoritative service inside
the connected deployment boundary.
Test
node --test "tests/verify.test.js" "tests/delegation.test.js" "tests/passport.test.js"Releases
- 0.4.0 (unreleased): regulator supervision check (
supervisionStatus,pins.requireSupervision), new reason codesSUPERVISION_SUSPENDEDandSUPERVISION_UNVERIFIEDin all four SDKs. Additive. - 0.3.0:
verifyPassportchecks an agent's mandate offline through the firm's own tree up to a root authority (see "Root passports"). Additive; every 0.2.0 export is unchanged. - 0.2.0: first public release.
