API Reference
Complete TypeScript SDK API reference with types, interfaces, and function signatures.
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 DeveloperCredentialisAgentCredential
Type guard to check if a credential is an AgentCredential.
function isAgentCredential(
credential: unknown
): credential is AgentCredentialisValidationSuccess
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' | nullTrust 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): Uint8ArrayisBitSet
Check if a bit is set in a bitstring.
function isBitSet(bitstring: Uint8Array, index: number): booleancheckStatusList2021
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 | nullStatusListCache
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: StatusListCacheHTTP 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): stringcomputeContentDigest
Compute Content-Digest header value.
function computeContentDigest(body: Uint8Array | string): stringgenerateNonce
Generate a cryptographic nonce.
function generateNonce(): stringHTTP 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 | undefinedcreateDefaultKeyResolver
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
): booleanclearKeyDirectoryCache
Clear the key directory cache.
function clearKeyDirectoryCache(): voidKey Directory
generateKeyDirectory
Generate a key directory JSON structure.
function generateKeyDirectory(
options: GenerateDirectoryOptions
): KeyDirectorysignDirectoryResponse
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): booleanReplay 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
): RequestHandlerwithReplayProtection
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
): Uint8ArraycomputeContentHashB64
Compute base64url-encoded hash of content.
function computeContentHashB64(
content: Uint8Array,
algorithm?: ContentHashAlgorithm
): stringverifyContentHash
Verify content against hash.
function verifyContentHash(
content: Uint8Array,
hash: Uint8Array,
algorithm?: ContentHashAlgorithm
): booleancreateHashClaim
Create a hash claim for embedding in credentials.
function createHashClaim(
content: Uint8Array,
algorithm?: ContentHashAlgorithm
): HashClaimverifyHashClaim
Verify a hash claim.
function verifyHashClaim(
content: Uint8Array,
claim: HashClaim
): booleancomputeCredentialBindingHash
Compute hash for credential binding.
function computeCredentialBindingHash(
credential: object
): stringverifyCredentialBinding
Verify credential binding hash.
function verifyCredentialBinding(
credential: object,
expectedHash: string
): booleanHash 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
): Uint8ArrayverifyChainLink
Verify a single chain link.
function verifyChainLink(
entry: ChainEntry,
previousEntry: ChainEntry | null
): booleanverifyChainIntegrity
Verify entire chain integrity.
function verifyChainIntegrity(entries: ChainEntry[]): booleanserializeChainEntry
Serialize a chain entry for storage.
function serializeChainEntry(entry: ChainEntry): SerializedChainEntrydeserializeChainEntry
Deserialize a chain entry.
function deserializeChainEntry(
serialized: SerializedChainEntry
): ChainEntryMulti-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 | undefinedsetAuditLogger
Set the global audit logger.
function setAuditLogger(logger: AuditLogger): voidConsoleAuditHandler
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): SerializedAuditEventdeserializeAuditEvent
Deserialize an audit event.
function deserializeAuditEvent(
serialized: SerializedAuditEvent
): AuditEventeventToJson
Convert audit event to JSON string.
function eventToJson(event: AuditEvent): stringCloud 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'
): LocalSignersignWithSigner
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
): stringverifySdJwt
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
): DisclosuredecodeDisclosure
Decode a disclosure from base64url.
function decodeDisclosure(encoded: string): DisclosurecompactSdJwt
Compact an SD-JWT to string format.
function compactSdJwt(sdJwt: SDJwt): stringCanonicalization
canonicalize
Canonicalize a JSON object (RFC 8785).
function canonicalize(obj: unknown): Uint8ArraycanonicalizeToString
Canonicalize to string.
function canonicalizeToString(obj: unknown): stringcomputeCanonicalHash
Compute hash of canonical form.
function computeCanonicalHash(
obj: unknown,
algorithm?: ContentHashAlgorithm
): Uint8ArraycomputeCanonicalHashB64
Compute base64url hash of canonical form.
function computeCanonicalHashB64(
obj: unknown,
algorithm?: ContentHashAlgorithm
): stringverifyCanonicalHash
Verify canonical hash.
function verifyCanonicalHash(
obj: unknown,
hash: Uint8Array,
algorithm?: ContentHashAlgorithm
): booleanError Sanitization
sanitizeMessage
Sanitize an error message for external use.
function sanitizeMessage(message: string): stringsanitizeDetails
Sanitize error details.
function sanitizeDetails(details: unknown): unknowngetPublicMessage
Get safe public message from error.
function getPublicMessage(error: Error): stringcreateSanitizedError
Create a sanitized error for API responses.
function createSanitizedError(error: Error): SanitizedErrorsanitizeException
Sanitize any exception.
function sanitizeException(error: unknown): SanitizedErrorInput Validation
validateTokenInput
Validate a JWT token string.
function validateTokenInput(token: string): voidvalidateDid
Validate a DID string.
function validateDid(did: string): voidvalidateKid
Validate a key ID string.
function validateKid(kid: string): voidvalidateUrl
Validate a URL string.
function validateUrl(url: string): voidvalidateCredentialStructure
Validate credential structure.
function validateCredentialStructure(
credential: unknown,
options?: ValidateCredentialStructureOptions
): voidvalidateAlgorithm
Validate signature algorithm.
function validateAlgorithm(algorithm: string): voidvalidateBase64url
Validate base64url string.
function validateBase64url(value: string): voidError 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: 300MAX_TOKEN_LENGTH
const MAX_TOKEN_LENGTH: 1_000_000Validation Patterns
const DID_PATTERN: RegExp
const KID_PATTERN: RegExp
const URL_PATTERN: RegExp
const BASE64URL_PATTERN: RegExp
const CREDENTIAL_ID_PATTERN: RegExp