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:
| Tier | Requests/Day | Requests/Minute |
|---|---|---|
| Free | 1,000 | 10 |
| Professional | 100,000 | 100 |
| Enterprise | 1,000,000 | 1,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:
- Your API key is correct and active
- You have internet connectivity
- 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ā
- Documentation: docs.torvussecurity.com
- API Reference: API Endpoints
- GitHub Issues: Report a bug
- Email: support@torvussecurity.com
Last Updated: October 13, 2025