Skip to content

SDK Reference

The @clawdentity/sdk package provides the core TypeScript SDK for working with Clawdentity identities, signatures, and revocation.

Terminal window
pnpm add @clawdentity/sdk

The SDK handles AIT verification and PoP request signing:

  • AIT verification — verify registry-signed JWTs offline using cached public keys
  • PoP signing — generate X-Claw-* headers for outbound requests
  • PoP verification — validate inbound PoP signatures against AIT cnf keys
  • CRL verification — verify signed CRL JWTs

Manages local caching and refresh of the Certificate Revocation List:

  • Configurable refresh interval (default: DEFAULT_CRL_REFRESH_INTERVAL_MS = 300000, 5 min)
  • Maximum age before considered stale (default: DEFAULT_CRL_MAX_AGE_MS = 900000, 15 min)
  • Staleness policy via staleBehavior:
    • fail-open (default) — when stale, returns warnings but allows isRevoked() to return false (treats as not revoked)
    • fail-closed — when stale, throws AppError with code CRL_CACHE_STALE (status 503)
import { createCrlCache } from "@clawdentity/sdk";
const cache = createCrlCache({
fetchLatest: () => fetchCrlFromRegistry(),
staleBehavior: "fail-closed",
});
await cache.refreshIfStale();
const revoked = await cache.isRevoked(jti);

Tracks nonces for replay protection:

  • Default TTL: 5 minutes (DEFAULT_NONCE_TTL_MS = 300000)
  • Per-agent nonce tracking
  • Automatic expiry purge on each tryAcceptNonce call

Manages agent authentication tokens:

  • Token refresh using Claw + PoP headers
  • Automatic refresh decisions based on expiry metadata
  • Single-flight deduplication for concurrent refresh attempts

refreshAgentAuthWithClawProof(input) — Sends a PoP-signed refresh request to the registry and returns a new AgentAuthBundle.

const bundle = await refreshAgentAuthWithClawProof({
registryUrl: "https://registry.example.com",
ait: "<current-ait>",
secretKey: agentSecretKey,
refreshToken: currentBundle.refreshToken,
});

executeWithAgentAuthRefreshRetry(input) — Executes an operation with automatic auth refresh on 401 errors. Uses single-flight deduplication for the refresh call.

const result = await executeWithAgentAuthRefreshRetry({
key: "my-agent",
getAuth: () => loadBundle(),
refreshAuth: (auth) => refreshAgentAuthWithClawProof({ ... }),
persistAuth: (auth) => saveBundle(auth),
perform: (auth) => callApi(auth),
});

isRetryableAuthExpiryError(error) — Returns true if the error is an AppError with status 401.

CodeStatusDescription
AGENT_AUTH_REFRESH_INVALID400Refresh request is invalid
AGENT_AUTH_REFRESH_UNAUTHORIZED401Credentials invalid, revoked, or expired
AGENT_AUTH_REFRESH_CONFLICT409Refresh conflict, retry request
AGENT_AUTH_REFRESH_SERVER_ERROR503Registry server error
AGENT_AUTH_REFRESH_FAILEDvariesGeneric refresh failure
AGENT_AUTH_REFRESH_NETWORK503Network connectivity failure
AGENT_AUTH_REFRESH_INVALID_RESPONSE502Registry returned invalid payload

Structured error class with stable code values for deterministic error handling. Constructor takes a single options object.

import { AppError } from "@clawdentity/sdk";
throw new AppError({
code: "AGENT_NOT_FOUND",
message: "Agent does not exist",
status: 404,
});
FieldTypeDescription
codestringStable error code for programmatic handling
messagestringHuman-readable error message
statusnumberHTTP status code
detailsRecord<string, unknown>?Optional structured details
exposebooleanWhether to expose details in responses (defaults to true for status < 500)

Structured logging interface used across all Clawdentity services.

import { createLogger } from "@clawdentity/sdk";
const logger = createLogger({ service: "my-service" });

Interface for nonce replay detection:

import { createNonceCache } from "@clawdentity/sdk";
const cache = createNonceCache({ ttlMs: 5 * 60 * 1000 });

Options:

OptionTypeDefaultDescription
ttlMsnumber300000 (5 min)Time-to-live for each nonce entry
clock() => numberDate.nowCustom clock function for testing

Methods:

MethodReturnsDescription
tryAcceptNonce({ agentDid, nonce })NonceCacheResultAccept or reject a nonce (returns { accepted, seenAt, expiresAt })
purgeExpired()voidRemove all expired nonce entries

Constants exported from @clawdentity/sdk/http/constants:

ConstantValue
X_CLAW_TIMESTAMPX-Claw-Timestamp
X_CLAW_NONCEX-Claw-Nonce
X_CLAW_BODY_SHA256X-Claw-Body-SHA256
X_CLAW_PROOFX-Claw-Proof

Helper functions from @clawdentity/sdk/datetime:

FunctionSignatureDescription
nowIso()() => stringReturns the current time as an ISO-8601 string
addSeconds(value, seconds)(Date | string | number, number) => stringAdds seconds to a datetime value and returns ISO-8601
isExpired(expiresAt, reference?)(Date | string | number, Date | string | number?) => booleanReturns true if expiresAt <= reference (defaults to Date.now())

The SDK provides Hono middleware for building services:

  • createRequestContextMiddleware() — adds x-request-id tracking
  • createRequestLoggingMiddleware(logger) — structured request logging
  • createHonoErrorHandler(logger) — consistent error response formatting

The SDK builds on:

  • @noble/ed25519 — Ed25519 signature operations
  • jose — JWT handling (sign, verify, decode)
  • hono — HTTP framework middleware
  • zod — Runtime schema validation