Skip to main content

JavaScript/TypeScript SDK

Official JavaScript/TypeScript SDK for the Torvus Security Platform API.

Package: @torvus/api-client Version: v0.1.0-alpha (Foundation Complete) Repository: github.com/torvus-security/torvus


Installation​

npm install @torvus/api-client

Or with other package managers:

# Yarn
yarn add @torvus/api-client

# pnpm
pnpm add @torvus/api-client

Requirements: Node.js 16+ or modern browser


Quick Start​

import { TorvusClient } from '@torvus/api-client';

// Initialize client with your API key
const client = new TorvusClient({
apiKey: process.env.TORVUS_API_KEY!,
});

// Create a vault
const vault = await client.post('/v1/vaults', {
name: 'Personal Documents',
description: 'Important files',
check_in_frequency: 'weekly',
});

console.log(`Vault created with ID: ${vault.id}`);

// Get all vaults
const vaults = await client.get('/v1/vaults');
console.log(`You have ${vaults.data.length} vaults`);

// Update vault
await client.patch(`/v1/vaults/${vault.id}`, {
name: 'Updated Name',
});

// Delete vault
await client.delete(`/v1/vaults/${vault.id}`);

Authentication​

The SDK requires an API key which you can generate in your API Keys dashboard.

// Method 1: Pass API key directly
const client = new TorvusClient({
apiKey: 'sk_live_your_api_key_here',
});

// Method 2: Use environment variable (recommended)
const client = new TorvusClient({
apiKey: process.env.TORVUS_API_KEY!,
});

Best Practice: Store your API key in an environment variable:

export TORVUS_API_KEY="sk_live_your_api_key_here"

Configuration​

import { TorvusClient } from '@torvus/api-client';

const client = new TorvusClient({
// Required: Your API key
apiKey: 'sk_live_your_api_key_here',

// Optional: Override base URL (default: https://api.torvussecurity.com)
baseUrl: 'https://api.torvussecurity.com',

// Optional: Request timeout in milliseconds (default: 30000)
timeout: 30000,

// Optional: Max retries for 5xx errors (default: 3)
maxRetries: 3,

// Optional: Enable debug logging (default: false)
debug: false,

// Optional: Custom headers for all requests
headers: {
'X-Custom-Header': 'value',
},
});

Making Requests​

The SDK provides convenience methods for all HTTP verbs:

GET Request​

// List vaults
const vaults = await client.get('/v1/vaults');

// Get specific vault
const vault = await client.get('/v1/vaults/vault_123');

// With query parameters
const vaults = await client.get('/v1/vaults', {
params: {
limit: 10,
offset: 0,
},
});

POST Request​

// Create vault
const vault = await client.post('/v1/vaults', {
name: 'Personal Documents',
check_in_frequency: 'weekly',
});

// Add recipient
const recipient = await client.post('/v1/recipients', {
email: 'recipient@example.com',
name: 'John Doe',
relationship: 'spouse',
});

PATCH Request​

// Update vault
const updated = await client.patch('/v1/vaults/vault_123', {
name: 'Updated Name',
description: 'Updated description',
});

PUT Request​

// Replace vault (full update)
const replaced = await client.put('/v1/vaults/vault_123', {
name: 'Completely Replaced',
check_in_frequency: 'monthly',
description: 'New description',
});

DELETE Request​

// Delete vault
await client.delete('/v1/vaults/vault_123');

// Delete document
await client.delete('/v1/documents/doc_456');

Error Handling​

import { TorvusClient, TorvusApiError } from '@torvus/api-client';

const client = new TorvusClient({
apiKey: process.env.TORVUS_API_KEY!,
});

try {
const vault = await client.get('/v1/vaults/invalid_id');
} catch (error) {
if (error instanceof TorvusApiError) {
// Handle specific error types
if (error.isAuthenticationError()) {
console.error('Invalid API key');
} else if (error.isNotFoundError()) {
console.error('Vault not found');
} else if (error.isRateLimitError()) {
const retryAfter = error.details?.retryAfter;
console.error(`Rate limited. Retry after: ${retryAfter} seconds`);
} else if (error.isServerError()) {
console.error('Server error, please try again');
} else {
console.error(`API error: ${error.message} (${error.errorCode})`);
}

// Access error details
console.log('Status code:', error.statusCode);
console.log('Error code:', error.errorCode);
console.log('Request ID:', error.requestId);
console.log('Details:', error.details);
} else {
// Handle non-API errors
console.error('Unexpected error:', error);
}
}

Error Type Helpers​

The TorvusApiError class provides helper methods for common error types:

error.isAuthenticationError(); // 401 - Invalid API key
error.isAuthorizationError(); // 403 - Insufficient permissions
error.isNotFoundError(); // 404 - Resource not found
error.isRateLimitError(); // 429 - Rate limit exceeded
error.isServerError(); // 5xx - Server error
error.isClientError(); // 4xx - Client error

Automatic Retry Logic​

The SDK automatically retries requests that fail with 5xx server errors using exponential backoff:

  • Retry attempts: 3 by default (configurable via maxRetries)
  • Backoff strategy: Exponential (1s, 2s, 4s, 8s, etc.)
  • Retried status codes: 500, 501, 502, 503, 504
// Configure custom retry behavior
const client = new TorvusClient({
apiKey: process.env.TORVUS_API_KEY!,
maxRetries: 5, // Retry up to 5 times
});

Note: 4xx client errors (except 429 rate limits) are not retried, as these typically indicate incorrect request data.


Debug Logging​

Enable debug mode to log all requests and responses:

const client = new TorvusClient({
apiKey: process.env.TORVUS_API_KEY!,
debug: true, // Logs all requests, responses, and retries
});

// Console output example:
// [Torvus SDK] POST /v1/vaults
// [Torvus SDK] Request body: { "name": "Test Vault" }
// [Torvus SDK] Response 201 from /v1/vaults
// [Torvus SDK] Retry attempt 1/3 for GET /v1/vaults/vault_123

Advanced Usage​

Access Underlying Axios Instance​

For advanced use cases, access the underlying Axios instance:

const axiosInstance = client.axiosInstance;

// Add custom interceptors
axiosInstance.interceptors.request.use((config) => {
// Modify request before sending
console.log('Request:', config.method, config.url);
return config;
});

axiosInstance.interceptors.response.use((response) => {
// Handle response
console.log('Response:', response.status);
return response;
});

Custom Request Configuration​

// Custom request with advanced options
const response = await client.request({
method: 'GET',
url: '/v1/vaults',
params: { limit: 10 },
headers: { 'X-Custom-Header': 'value' },
timeout: 5000,
});

TypeScript Support​

The SDK is written in TypeScript and includes complete type definitions:

import type {
TorvusClientConfig,
AxiosRequestConfig
} from '@torvus/api-client';

// Type-safe configuration
const config: TorvusClientConfig = {
apiKey: process.env.TORVUS_API_KEY!,
timeout: 60000,
maxRetries: 5,
debug: false,
};

const client = new TorvusClient(config);

// Type-safe request configuration
const requestConfig: AxiosRequestConfig = {
params: { limit: 10 },
timeout: 5000,
};

const vaults = await client.get('/v1/vaults', requestConfig);

Complete Example​

Here's a complete example demonstrating a typical workflow:

import { TorvusClient, TorvusApiError } from '@torvus/api-client';

async function main() {
// Initialize client
const client = new TorvusClient({
apiKey: process.env.TORVUS_API_KEY!,
debug: false,
});

try {
// 1. Create a vault
console.log('Creating vault...');
const vault = await client.post('/v1/vaults', {
name: 'Family Documents',
description: 'Important family files',
check_in_frequency: 'monthly',
});
console.log(`āœ“ Vault created: ${vault.id}`);

// 2. Add a recipient
console.log('Adding recipient...');
const recipient = await client.post('/v1/recipients', {
email: 'recipient@example.com',
name: 'Jane Doe',
relationship: 'spouse',
});
console.log(`āœ“ Recipient added: ${recipient.id}`);

// 3. List all vaults
console.log('Fetching vaults...');
const vaults = await client.get('/v1/vaults');
console.log(`āœ“ Found ${vaults.data.length} vaults`);

// 4. Update vault
console.log('Updating vault...');
const updated = await client.patch(`/v1/vaults/${vault.id}`, {
description: 'Updated description',
});
console.log(`āœ“ Vault updated: ${updated.name}`);

// 5. Check in
console.log('Performing check-in...');
const checkin = await client.post('/v1/check-ins', {
vault_id: vault.id,
});
console.log(`āœ“ Check-in completed. Next: ${checkin.next_check_in}`);

console.log('\nāœ… All operations completed successfully!');
} catch (error) {
if (error instanceof TorvusApiError) {
console.error(`āŒ API Error: ${error.message}`);
console.error(` Status: ${error.statusCode}`);
console.error(` Code: ${error.errorCode}`);
console.error(` Request ID: ${error.requestId}`);
} else {
console.error('āŒ Unexpected error:', error);
}
process.exit(1);
}
}

main();

Environment Variables​

The SDK respects the following environment variables:

# API key (alternative to passing in constructor)
TORVUS_API_KEY=sk_live_your_api_key_here

# API base URL (for testing/development)
TORVUS_API_BASE_URL=https://api-sandbox.torvussecurity.com

Rate Limiting​

The API enforces rate limits based on your tier:

TierRequests/DayRequests/Minute
Free1,00010
Professional100,000100
Enterprise1,000,0001,000

When rate limited (HTTP 429), the SDK throws a TorvusApiError with isRateLimitError() returning true. The error details include a retryAfter field indicating seconds to wait.

Example: Handle rate limiting with exponential backoff:

async function withRateLimitRetry<T>(
fn: () => Promise<T>,
maxRetries = 3
): Promise<T> {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (error) {
if (error instanceof TorvusApiError && error.isRateLimitError()) {
const retryAfter = (error.details?.retryAfter || 1) * 1000;
console.log(`Rate limited. Waiting ${retryAfter}ms before retry...`);
await new Promise(resolve => setTimeout(resolve, retryAfter));
} else {
throw error;
}
}
}
throw new Error('Max retry attempts exceeded');
}

// Usage
const vaults = await withRateLimitRetry(() => client.get('/v1/vaults'));

Testing​

Unit Testing​

For unit testing, you can mock the SDK using Jest or other testing frameworks:

import { TorvusClient, TorvusApiError } from '@torvus/api-client';
import { jest } from '@jest/globals';

// Mock the entire module
jest.mock('@torvus/api-client');

describe('My Service', () => {
it('should create a vault', async () => {
const mockClient = new TorvusClient({ apiKey: 'test_key' });
const mockPost = jest.spyOn(mockClient, 'post')
.mockResolvedValue({
id: 'vault_test123',
name: 'Test Vault',
});

const result = await mockClient.post('/v1/vaults', { name: 'Test Vault' });

expect(result.id).toBe('vault_test123');
expect(mockPost).toHaveBeenCalledWith('/v1/vaults', { name: 'Test Vault' });
});
});

Browser Usage​

The SDK works in modern browsers with bundlers like Webpack, Vite, or Rollup:

import { TorvusClient } from '@torvus/api-client';

const client = new TorvusClient({
apiKey: 'sk_live_your_api_key_here',
});

const vaults = await client.get('/v1/vaults');
console.log('Vaults:', vaults);

Security Note: Never expose your API key in client-side code. For browser applications, use a backend proxy to make API calls.


Troubleshooting​

TypeScript Errors​

If you encounter TypeScript errors, ensure you're using TypeScript 4.5+:

npm install --save-dev typescript@latest

Network Errors​

If requests fail with network errors, check:

  1. Your API key is correct and active
  2. You have internet connectivity
  3. Firewall settings allow requests to api.torvussecurity.com

Module Resolution​

If imports fail, ensure your tsconfig.json includes:

{
"compilerOptions": {
"moduleResolution": "node",
"esModuleInterop": true
}
}

Roadmap​

v0.1.0 (Current)​

  • āœ… Core HTTP client with error handling
  • āœ… Automatic retries with exponential backoff
  • āœ… TypeScript support with full type definitions
  • āœ… Debug logging

v0.2.0 (Planned)​

  • ā³ High-level resource methods (e.g., client.vaults.create())
  • ā³ Pagination helper utilities
  • ā³ Webhook signature verification
  • ā³ File upload/download helpers
  • ā³ Request caching
  • ā³ Rate limit tracking

v1.0.0 (Stable Release)​

  • ā³ Production-ready with 100% test coverage
  • ā³ Complete OpenAPI coverage
  • ā³ Performance benchmarks
  • ā³ Comprehensive documentation

Support​


Last Updated: October 13, 2025