Skip to main content
Complete reference for all types, interfaces, and functions in the Beltic TypeScript SDK.

Validation

validateDeveloperCredential

Validate a DeveloperCredential against the v1 JSON schema.
function validateDeveloperCredential(
  input: unknown
): ValidationResult<DeveloperCredential>

validateAgentCredential

Validate an AgentCredential against the v1 JSON schema.
function validateAgentCredential(
  input: unknown
): ValidationResult<AgentCredential>

isDeveloperCredential

Type guard to check if a credential is a DeveloperCredential.
function isDeveloperCredential(
  credential: unknown
): credential is DeveloperCredential

isAgentCredential

Type guard to check if a credential is an AgentCredential.
function isAgentCredential(
  credential: unknown
): credential is AgentCredential

isValidationSuccess

Type guard for validation result.
function isValidationSuccess<T>(
  result: ValidationResult<T>
): result is { ok: true; value: T; warnings: ValidationWarning[] }

Signing

signCredential

Sign a credential as a JWS token.
async function signCredential(
  credential: DeveloperCredential | AgentCredential,
  privateKey: CryptoKey,
  options: SignOptions
): Promise<string>

generateKeyPair

Generate a new Ed25519 or ES256 keypair.
async function generateKeyPair(
  algorithm: 'EdDSA' | 'ES256'
): Promise<{ privateKey: CryptoKey; publicKey: CryptoKey }>

exportPublicKey

Export a public key as JWK.
async function exportPublicKey(
  key: CryptoKey
): Promise<JsonWebKey>

importPublicKey

Import a public key from JWK.
async function importPublicKey(
  jwk: JsonWebKey,
  algorithm: 'EdDSA' | 'ES256'
): Promise<CryptoKey>

importPrivateKey

Import a private key from JWK.
async function importPrivateKey(
  jwk: JsonWebKey,
  algorithm: 'EdDSA' | 'ES256'
): Promise<CryptoKey>

importKeyFromPEM

Import a key from PEM format.
async function importKeyFromPEM(
  pem: string,
  algorithm: 'EdDSA' | 'ES256',
  options?: ImportKeyFromPEMOptions
): Promise<CryptoKey>

exportPrivateKeyToPEM

Export a private key to PEM format.
async function exportPrivateKeyToPEM(
  key: CryptoKey,
  options?: ExportKeyToPEMOptions
): Promise<string>

exportPublicKeyToPEM

Export a public key to PEM format.
async function exportPublicKeyToPEM(
  key: CryptoKey,
  options?: ExportKeyToPEMOptions
): Promise<string>

Verification

verifyCredential

Verify a JWS token’s signature and claims.
async function verifyCredential(
  token: string,
  options: VerifyOptions
): Promise<VerifiedCredential>

decodeToken

Decode a JWT without verification (for debugging).
function decodeToken(token: string): {
  header: JWSHeader;
  payload: JWTPayload;
  signature: string;
}

getCredentialType

Determine if a token is a developer or agent credential.
function getCredentialType(
  token: string
): 'developer' | 'agent' | null

Trust Chain

verifyAgentTrustChain

Verify complete agent trust chain with policies.
async function verifyAgentTrustChain(
  agentToken: string,
  options: TrustChainOptions
): Promise<TrustChainResult>

Status List

decodeStatusList

Decode a compressed Status List 2021 bitstring.
function decodeStatusList(encodedList: string): Uint8Array

isBitSet

Check if a bit is set in a bitstring.
function isBitSet(bitstring: Uint8Array, index: number): boolean

checkStatusList2021

Check credential status using Status List 2021.
async function checkStatusList2021(
  statusListUrl: string,
  statusListIndex: number
): Promise<CredentialStatus>

parseStatusEntry

Parse a credentialStatus object from a credential.
function parseStatusEntry(
  credentialStatus: unknown
): StatusList2021Entry | null

StatusListCache

Cache for Status List 2021 fetches.
class StatusListCache {
  constructor(ttl: number);
  fetch(url: string): Promise<Uint8Array>;
  clear(): void;
}

defaultStatusListCache

Shared status list cache instance.
const defaultStatusListCache: StatusListCache

HTTP Signing (Web Bot Auth)

signHttpRequest

Sign an HTTP request per RFC 9421.
async function signHttpRequest(
  request: HttpRequestInfo,
  options: HttpSignOptions
): Promise<HttpSignatureHeaders>

createSignedRequest

Create a fully signed HTTP request.
async function createSignedRequest(
  request: HttpRequestInfo,
  options: HttpSignOptions
): Promise<{ url: string; method: string; headers: Record<string, string>; body?: string }>

computeJwkThumbprint

Compute JWK thumbprint (RFC 7638).
function computeJwkThumbprint(jwk: JsonWebKey): string

computeContentDigest

Compute Content-Digest header value.
function computeContentDigest(body: Uint8Array | string): string

generateNonce

Generate a cryptographic nonce.
function generateNonce(): string

HTTP Verification

verifyHttpSignature

Verify HTTP message signature.
async function verifyHttpSignature(
  request: IncomingHttpRequest,
  options: HttpVerifyOptions
): Promise<HttpVerificationResult>

fetchKeyDirectory

Fetch a key directory from URL.
async function fetchKeyDirectory(url: string): Promise<KeyDirectory>

findKeyByThumbprint

Find a key in a directory by thumbprint.
function findKeyByThumbprint(
  directory: KeyDirectory,
  thumbprint: string
): JsonWebKey | undefined

createDefaultKeyResolver

Create a default key resolver for HTTP verification.
function createDefaultKeyResolver(): (
  signatureAgent: string,
  keyId: string
) => Promise<CryptoKey>

verifyContentDigest

Verify Content-Digest header.
function verifyContentDigest(
  body: Uint8Array | string,
  header: string
): boolean

clearKeyDirectoryCache

Clear the key directory cache.
function clearKeyDirectoryCache(): void

Key Directory

generateKeyDirectory

Generate a key directory JSON structure.
function generateKeyDirectory(
  options: GenerateDirectoryOptions
): KeyDirectory

signDirectoryResponse

Sign a key directory response.
async function signDirectoryResponse(
  directory: KeyDirectory,
  options: SignDirectoryOptions
): Promise<SignedDirectoryResponse>

generateWebBotAuthSetup

Generate complete Web Bot Auth setup.
async function generateWebBotAuthSetup(
  baseUrl?: string
): Promise<{
  privateKey: CryptoKey;
  publicKey: CryptoKey;
  thumbprint: string;
  directory: KeyDirectory;
  keyDirectoryUrl: string;
}>

isValidKeyDirectoryUrl

Validate a key directory URL.
function isValidKeyDirectoryUrl(url: string): boolean

Replay Protection

ReplayProtection

High-level replay protection wrapper.
class ReplayProtection {
  constructor(store: JtiStore);
  check(jti: string, exp: number): Promise<void>;
}

createReplayMiddleware

Create Express middleware for replay protection.
function createReplayMiddleware(
  store: JtiStore
): RequestHandler

withReplayProtection

Wrap a verification function with replay protection.
function withReplayProtection<T>(
  store: JtiStore,
  verifyFn: (token: string) => Promise<T>
): (token: string) => Promise<T>

InMemoryJtiStore

In-memory JTI store.
class InMemoryJtiStore implements JtiStore {
  constructor(ttlSeconds?: number);
  has(jti: string): Promise<boolean>;
  add(jti: string, exp: number): Promise<void>;
  cleanup(): Promise<void>;
}

checkReplay

Check for replay attack.
async function checkReplay(
  store: JtiStore,
  jti: string,
  exp: number
): Promise<void>

Content Integrity

computeContentHash

Compute hash of content.
function computeContentHash(
  content: Uint8Array,
  algorithm?: ContentHashAlgorithm
): Uint8Array

computeContentHashB64

Compute base64url-encoded hash of content.
function computeContentHashB64(
  content: Uint8Array,
  algorithm?: ContentHashAlgorithm
): string

verifyContentHash

Verify content against hash.
function verifyContentHash(
  content: Uint8Array,
  hash: Uint8Array,
  algorithm?: ContentHashAlgorithm
): boolean

createHashClaim

Create a hash claim for embedding in credentials.
function createHashClaim(
  content: Uint8Array,
  algorithm?: ContentHashAlgorithm
): HashClaim

verifyHashClaim

Verify a hash claim.
function verifyHashClaim(
  content: Uint8Array,
  claim: HashClaim
): boolean

computeCredentialBindingHash

Compute hash for credential binding.
function computeCredentialBindingHash(
  credential: object
): string

verifyCredentialBinding

Verify credential binding hash.
function verifyCredentialBinding(
  credential: object,
  expectedHash: string
): boolean

Hash Chains

CredentialChain

Credential hash chain for auditing.
class CredentialChain {
  add(credential: object, token: string): ChainEntry;
  getProof(): ChainProof;
  verify(): boolean;
  get length(): number;
}

computeChainHash

Compute hash for chain entry.
function computeChainHash(
  credentialHash: Uint8Array,
  previousHash: Uint8Array | null
): Uint8Array
Verify a single chain link.
function verifyChainLink(
  entry: ChainEntry,
  previousEntry: ChainEntry | null
): boolean

verifyChainIntegrity

Verify entire chain integrity.
function verifyChainIntegrity(entries: ChainEntry[]): boolean

serializeChainEntry

Serialize a chain entry for storage.
function serializeChainEntry(entry: ChainEntry): SerializedChainEntry

deserializeChainEntry

Deserialize a chain entry.
function deserializeChainEntry(
  serialized: SerializedChainEntry
): ChainEntry

Multi-Signature

MultiSigCredential

Credential with multiple signatures.
class MultiSigCredential {
  constructor(credential: object);
  addSignature(
    privateKey: CryptoKey,
    signerId: string,
    options: SignOptions
  ): Promise<void>;
  getSignatures(): SignatureEntry[];
  verifyAll(
    keyResolver: MultiSigKeyResolver
  ): Promise<MultiSigVerificationResult>;
}

addSignature

Add signature to multi-sig credential.
async function addSignature(
  credential: MultiSigCredential,
  privateKey: CryptoKey,
  signerId: string,
  options: SignOptions
): Promise<void>

verifyMultiSignatures

Verify all signatures on a multi-sig credential.
async function verifyMultiSignatures(
  credential: MultiSigCredential,
  keyResolver: MultiSigKeyResolver
): Promise<MultiSigVerificationResult>

Audit Logging

AuditLogger

Audit logger with pluggable handlers.
class AuditLogger {
  addHandler(handler: AuditHandler): void;
  log(event: AuditEvent): void;
}

getAuditLogger

Get the global audit logger.
function getAuditLogger(): AuditLogger | undefined

setAuditLogger

Set the global audit logger.
function setAuditLogger(logger: AuditLogger): void

ConsoleAuditHandler

Log audit events to console.
class ConsoleAuditHandler implements AuditHandler {
  handle(event: AuditEvent): void;
}

InMemoryAuditHandler

Store audit events in memory.
class InMemoryAuditHandler implements AuditHandler {
  readonly events: AuditEvent[];
  handle(event: AuditEvent): void;
  clear(): void;
}

serializeAuditEvent

Serialize an audit event for storage.
function serializeAuditEvent(event: AuditEvent): SerializedAuditEvent

deserializeAuditEvent

Deserialize an audit event.
function deserializeAuditEvent(
  serialized: SerializedAuditEvent
): AuditEvent

eventToJson

Convert audit event to JSON string.
function eventToJson(event: AuditEvent): string

Cloud Signers

LocalSigner

Local key signer.
class LocalSigner implements CloudSigner {
  constructor(privateKey: CryptoKey, algorithm: 'EdDSA' | 'ES256');
  sign(data: Uint8Array): Promise<Uint8Array>;
  getInfo(): SignerInfo;
}

createLocalSigner

Create a local signer.
function createLocalSigner(
  privateKey: CryptoKey,
  algorithm: 'EdDSA' | 'ES256'
): LocalSigner

signWithSigner

Sign data with any signer.
async function signWithSigner(
  signer: CloudSigner,
  data: Uint8Array
): Promise<Uint8Array>

AwsKmsSigner

AWS KMS signer.
class AwsKmsSigner implements CloudSigner {
  constructor(options: AwsKmsSignerOptions);
  sign(data: Uint8Array): Promise<Uint8Array>;
  getInfo(): SignerInfo;
}

Selective Disclosure (SD-JWT)

createSdJwt

Create a selective disclosure JWT.
async function createSdJwt(
  credential: object,
  privateKey: CryptoKey,
  options: CreateSdJwtOptions
): Promise<SDJwt>

createPresentation

Create a presentation from SD-JWT with selected disclosures.
function createPresentation(
  sdJwt: SDJwt,
  disclosedPaths: string[],
  options?: CreatePresentationOptions
): string

verifySdJwt

Verify an SD-JWT presentation.
async function verifySdJwt(
  presentation: string,
  options: VerifySdJwtOptions
): Promise<SdJwtVerificationResult>

createDisclosure

Create a disclosure for a claim.
function createDisclosure(
  salt: string,
  claimName: string,
  claimValue: unknown
): Disclosure

decodeDisclosure

Decode a disclosure from base64url.
function decodeDisclosure(encoded: string): Disclosure

compactSdJwt

Compact an SD-JWT to string format.
function compactSdJwt(sdJwt: SDJwt): string

Canonicalization

canonicalize

Canonicalize a JSON object (RFC 8785).
function canonicalize(obj: unknown): Uint8Array

canonicalizeToString

Canonicalize to string.
function canonicalizeToString(obj: unknown): string

computeCanonicalHash

Compute hash of canonical form.
function computeCanonicalHash(
  obj: unknown,
  algorithm?: ContentHashAlgorithm
): Uint8Array

computeCanonicalHashB64

Compute base64url hash of canonical form.
function computeCanonicalHashB64(
  obj: unknown,
  algorithm?: ContentHashAlgorithm
): string

verifyCanonicalHash

Verify canonical hash.
function verifyCanonicalHash(
  obj: unknown,
  hash: Uint8Array,
  algorithm?: ContentHashAlgorithm
): boolean

Error Sanitization

sanitizeMessage

Sanitize an error message for external use.
function sanitizeMessage(message: string): string

sanitizeDetails

Sanitize error details.
function sanitizeDetails(details: unknown): unknown

getPublicMessage

Get safe public message from error.
function getPublicMessage(error: Error): string

createSanitizedError

Create a sanitized error for API responses.
function createSanitizedError(error: Error): SanitizedError

sanitizeException

Sanitize any exception.
function sanitizeException(error: unknown): SanitizedError

Input Validation

validateTokenInput

Validate a JWT token string.
function validateTokenInput(token: string): void

validateDid

Validate a DID string.
function validateDid(did: string): void

validateKid

Validate a key ID string.
function validateKid(kid: string): void

validateUrl

Validate a URL string.
function validateUrl(url: string): void

validateCredentialStructure

Validate credential structure.
function validateCredentialStructure(
  credential: unknown,
  options?: ValidateCredentialStructureOptions
): void

validateAlgorithm

Validate signature algorithm.
function validateAlgorithm(algorithm: string): void

validateBase64url

Validate base64url string.
function validateBase64url(value: string): void

Error Classes

BelticError

Base error class.
class BelticError extends Error {
  code: string;
}

ValidationError

Validation error with detailed issues.
class ValidationError extends BelticError {
  issues: ValidationErrorDetail[];
  byPath(): Map<string, ValidationErrorDetail[]>;
  format(): string;
}

SignatureError

Signature verification error.
class SignatureError extends BelticError {
  step: SignatureErrorStep;
  code: string;
}

TrustChainError

Trust chain verification error.
class TrustChainError extends BelticError {
  step: TrustChainErrorStep;
  agentCredential?: Partial<AgentCredential>;
  developerCredential?: Partial<DeveloperCredential>;
}

PolicyViolationError

Policy violation error.
class PolicyViolationError extends BelticError {
  violations: PolicyViolation[];
  hasType(type: string): boolean;
}

ReplayDetectedError

Replay attack detected.
class ReplayDetectedError extends BelticError {
  jti: string;
  firstSeen: Date;
}

InputValidationError

Input validation error.
class InputValidationError extends BelticError {
  field: string;
}

CanonicalizationError

Canonicalization error.
class CanonicalizationError extends BelticError {}

ContentIntegrityError

Content integrity error.
class ContentIntegrityError extends BelticError {}

ChainIntegrityError

Chain integrity error.
class ChainIntegrityError extends BelticError {}

MultiSigError

Multi-signature error.
class MultiSigError extends BelticError {}

CloudSignerError

Cloud signer error.
class CloudSignerError extends BelticError {}

SDJwtError

SD-JWT error.
class SDJwtError extends BelticError {}

Types

SignOptions

interface SignOptions {
  alg: 'EdDSA' | 'ES256';
  issuerDid: string;
  subjectDid: string;
  keyId?: string;
  audience?: string;
}

VerifyOptions

interface VerifyOptions {
  keyResolver: KeyResolver;
  expectedIssuer?: string;
  expectedAudience?: string;
  allowedAlgorithms?: ('EdDSA' | 'ES256')[];
}

TrustChainOptions

interface TrustChainOptions {
  keyResolver: KeyResolver;
  fetchDeveloperCredential: (id: string) => Promise<string>;
  checkStatus?: StatusChecker;
  policy?: TrustPolicy;
}

TrustPolicy

interface TrustPolicy {
  minKybTier?: 'tier_1' | 'tier_2' | 'tier_3';
  minPromptInjectionScore?: number;
  minPiiLeakageScore?: number;
  minToolAbuseScore?: number;
  minHarmRefusalScore?: number;
  minVerificationLevel?: 'self_attested' | 'beltic_verified' | 'third_party_verified';
  prohibitedDataCategories?: string[];
}

HttpRequestInfo

interface HttpRequestInfo {
  method: string;
  url: string;
  headers?: Record<string, string>;
  body?: Uint8Array | string;
}

HttpSignOptions

interface HttpSignOptions {
  privateKey: CryptoKey;
  keyId: string;
  keyDirectoryUrl: string;
  components?: SignableComponent[];
  expiresIn?: number;
}

AuditEvent

interface AuditEvent {
  type: AuditEventType;
  timestamp: Date;
  credentialId?: string;
  action: string;
  actor?: string;
  details: Record<string, unknown>;
}

Constants

ALLOWED_ALGORITHMS

const ALLOWED_ALGORITHMS: readonly ['EdDSA', 'ES256']

PROHIBITED_ALGORITHMS

const PROHIBITED_ALGORITHMS: readonly ['none', 'HS256', 'HS384', 'HS512']

MAX_CLOCK_SKEW_SECONDS

const MAX_CLOCK_SKEW_SECONDS: 300

MAX_TOKEN_LENGTH

const MAX_TOKEN_LENGTH: 1_000_000

Validation Patterns

const DID_PATTERN: RegExp
const KID_PATTERN: RegExp
const URL_PATTERN: RegExp
const BASE64URL_PATTERN: RegExp
const CREDENTIAL_ID_PATTERN: RegExp

See Also