Skip to content

TypeScript SDK

The official VeraID TypeScript SDK provides a type-safe client for managing credentials, monitoring AI agent usage, enforcing budgets, and detecting prompt injection attacks. It includes built-in retry logic, rate limit handling, and integration wrappers for popular AI frameworks.

Installation

Terminal window
npm install @veraid/sdk

Quick Start

import { VeraIDClient } from '@veraid/sdk';
const veraid = new VeraIDClient({
apiKey: process.env.VERAID_API_KEY,
agentId: process.env.VERAID_AGENT_ID,
});
// Fetch a credential
const dbUrl = await veraid.getCredential('production-db-url');
console.log('Connected to:', dbUrl.value);

Initialization

Create a client instance with your API key and optional configuration:

import { VeraIDClient } from '@veraid/sdk';
const veraid = new VeraIDClient({
apiKey: 'kd_live_your_api_key',
agentId: 'id_agent123', // Required for AI agent features
baseUrl: 'https://app.veraid.io', // Optional, defaults to production
debug: false, // Optional, enables verbose logging
retryAttempts: 3, // Optional, default: 3
timeout: 30000, // Optional, request timeout in ms
});

Credential Management

getCredential

Fetch a single credential by name.

const credential = await veraid.getCredential('aws-access-key');
console.log(credential.name); // 'aws-access-key'
console.log(credential.value); // 'AKIAIOSFODNN7EXAMPLE'
console.log(credential.expiresAt); // '2026-06-19T00:00:00Z'

Parameters:

ParameterTypeRequiredDescription
namestringYesName of the credential to fetch

Returns: Promise<Credential>

interface Credential {
name: string;
value: string;
expiresAt: string | null;
scopes: string[];
metadata: Record<string, unknown>;
}

listCredentials

List all credentials available to the current identity.

const credentials = await veraid.listCredentials();
for (const cred of credentials) {
console.log(`${cred.name}: expires ${cred.expiresAt ?? 'never'}`);
}

Returns: Promise<Credential[]>


Budget Management

getBudgetStatus

Retrieve the current budget status for the AI agent.

const budget = await veraid.getBudgetStatus();
console.log(`Budget: $${budget.used} / $${budget.limit} (${budget.percentUsed}%)`);
console.log(`Status: ${budget.status}`); // 'OK' | 'WARNING' | 'CRITICAL' | 'EXCEEDED'
console.log(`Projected: $${budget.projectedSpend}`);

Returns: Promise<BudgetStatus>

interface BudgetStatus {
limit: number;
used: number;
percentUsed: number;
status: 'OK' | 'WARNING' | 'CRITICAL' | 'EXCEEDED';
period: 'daily' | 'weekly' | 'monthly';
projectedSpend: number;
resetAt: string;
}

checkBudget

Check if a specific cost can be accommodated within the remaining budget. Use this before making an expensive AI call.

const canProceed = await veraid.checkBudget(2.50);
if (canProceed.allowed) {
// Proceed with the AI call
const response = await openai.chat.completions.create({...});
} else {
console.log(`Budget exceeded: ${canProceed.reason}`);
// Fall back to a cheaper model or queue for later
}

Parameters:

ParameterTypeRequiredDescription
costnumberYesEstimated cost in USD

Returns: Promise<BudgetCheck>

interface BudgetCheck {
allowed: boolean;
remainingBudget: number;
reason: string | null;
}

Usage Tracking

recordUsage

Record token and cost usage for an AI agent request. Call this after each AI API call to maintain accurate usage tracking.

await veraid.recordUsage({
promptTokens: 1250,
completionTokens: 847,
totalTokens: 2097,
cost: 0.063,
model: 'gpt-4',
latency: 2340,
metadata: {
taskType: 'ticket-triage',
ticketId: 'TICKET-4521',
},
});

Parameters:

ParameterTypeRequiredDescription
usageUsageRecordYesUsage data to record
interface UsageRecord {
promptTokens: number;
completionTokens: number;
totalTokens: number;
cost: number;
model: string;
latency?: number;
toolCalls?: string[];
metadata?: Record<string, unknown>;
}

Returns: Promise<void>


Prompt Security

checkInjection

Analyze a prompt for potential injection attacks. Returns a risk assessment with details about detected threats.

const result = await veraid.checkInjection(userPrompt);
if (result.isInjection) {
console.error(`Injection detected: ${result.category}`);
console.error(`Confidence: ${result.confidence}`);
console.error(`Details: ${result.explanation}`);
// Block the request or sanitize the input
} else {
// Proceed with the prompt
}

Parameters:

ParameterTypeRequiredDescription
promptstringYesThe prompt to analyze

Returns: Promise<InjectionResult>

interface InjectionResult {
isInjection: boolean;
confidence: number; // 0.0 to 1.0
category: string | null; // 'jailbreak' | 'data_exfil' | 'prompt_leak' | 'role_hijack'
explanation: string | null;
}

guardPrompt

A convenience method that checks for injection and throws an error if one is detected. Use this as a guard at the beginning of your prompt processing pipeline.

try {
const safePrompt = await veraid.guardPrompt(userPrompt);
// safePrompt is the original prompt, returned only if safe
const response = await openai.chat.completions.create({
model: 'gpt-4',
messages: [{ role: 'user', content: safePrompt }],
});
} catch (error) {
if (error instanceof VeraIDInjectionError) {
console.error(`Blocked: ${error.category} (${error.confidence})`);
// Return a safe response to the user
}
}

Parameters:

ParameterTypeRequiredDescription
promptstringYesThe prompt to guard

Returns: Promise<string> (the original prompt if safe)

Throws: VeraIDInjectionError if injection is detected


Analytics

getStats

Retrieve usage statistics for the AI agent over a specified time period.

const stats = await veraid.getStats('7d');
console.log(`Total requests: ${stats.totalRequests}`);
console.log(`Total cost: $${stats.totalCost}`);
console.log(`Average latency: ${stats.averageLatency}ms`);
console.log(`Injections blocked: ${stats.injectionsBlocked}`);

Parameters:

ParameterTypeRequiredDescription
periodstringYesTime period: 1h, 24h, 7d, 30d, 90d

Returns: Promise<AgentStats>

interface AgentStats {
totalRequests: number;
totalTokens: number;
totalCost: number;
averageLatency: number;
averageCostPerRequest: number;
injectionsBlocked: number;
budgetUtilization: number;
topModels: Array<{ model: string; requests: number; cost: number }>;
topTools: Array<{ tool: string; invocations: number }>;
}

OpenAI Integration

The SDK provides a wrapper for the OpenAI client that automatically monitors all API calls, tracks token usage and costs, checks budgets, and detects prompt injection.

import OpenAI from 'openai';
import { VeraIDClient } from '@veraid/sdk';
import { wrapOpenAI } from '@veraid/sdk/openai';
const veraid = new VeraIDClient({
apiKey: process.env.VERAID_API_KEY,
agentId: process.env.VERAID_AGENT_ID,
});
const openai = wrapOpenAI(new OpenAI(), veraid);
// All calls are now automatically monitored
const response = await openai.chat.completions.create({
model: 'gpt-4',
messages: [{ role: 'user', content: 'Summarize this document...' }],
});
// Usage is automatically recorded:
// - Token counts (prompt + completion)
// - Cost estimate based on model pricing
// - Latency
// - Budget check before each call
// - Prompt injection detection on user messages

The wrapper intercepts:

FeatureBehavior
Budget checkVerifies budget availability before each API call
Usage recordingAutomatically records tokens, cost, and latency after each call
Injection detectionScans user messages for prompt injection before sending to OpenAI
Error handlingCaptures and reports errors to VeraID for anomaly tracking

Error Handling

The SDK provides typed error classes for different failure modes:

import {
VeraIDClient,
VeraIDError,
VeraIDAuthError,
VeraIDRateLimitError,
VeraIDBudgetExceededError,
VeraIDInjectionError,
} from '@veraid/sdk';
try {
const credential = await veraid.getCredential('my-secret');
} catch (error) {
if (error instanceof VeraIDAuthError) {
console.error('Invalid API key');
} else if (error instanceof VeraIDRateLimitError) {
console.error(`Rate limited. Retry after ${error.retryAfter}s`);
} else if (error instanceof VeraIDBudgetExceededError) {
console.error(`Budget exceeded: ${error.limit} / ${error.used}`);
} else if (error instanceof VeraIDInjectionError) {
console.error(`Injection: ${error.category} (${error.confidence})`);
} else if (error instanceof VeraIDError) {
console.error(`VeraID error: ${error.message}`);
}
}

Environment Variables

The SDK reads the following environment variables as defaults:

VariableDescriptionRequired
VERAID_API_KEYAPI key for authenticationYes
VERAID_AGENT_IDAgent identity ID (for AI agent features)For agent features
VERAID_BASE_URLBase URL override (default: https://app.veraid.io)No
VERAID_DEBUGEnable debug logging (true / false)No
Terminal window
export VERAID_API_KEY="kd_live_your_api_key"
export VERAID_AGENT_ID="id_agent123"
export VERAID_DEBUG="false"