Skip to content

VaultSandboxClient API

The VaultSandboxClient is the main entry point for interacting with the VaultSandbox Gateway. It handles authentication, inbox creation, and provides utility methods for managing inboxes.

new VaultSandboxClient(config: ClientConfig)

Creates a new VaultSandbox client instance.

Configuration options for the client.

interface ClientConfig {
url: string;
apiKey: string;
strategy?: 'sse' | 'polling' | 'auto';
pollingInterval?: number;
maxRetries?: number;
retryDelay?: number;
retryOn?: number[];
sseReconnectInterval?: number;
sseMaxReconnectAttempts?: number;
}
PropertyTypeRequiredDefaultDescription
urlstringYes-Gateway URL (e.g., https://smtp.vaultsandbox.com)
apiKeystringYes-Your API authentication key
strategy'sse' | 'polling' | 'auto'No'auto'Email delivery strategy
pollingIntervalnumberNo2000Polling interval in milliseconds
maxRetriesnumberNo3Maximum retry attempts for HTTP requests
retryDelaynumberNo1000Base delay in milliseconds between retries
retryOnnumber[]No[408, 429, 500, 502, 503, 504]HTTP status codes that trigger a retry
sseReconnectIntervalnumberNo5000Initial delay before SSE reconnection (ms)
sseMaxReconnectAttemptsnumberNo10Maximum SSE reconnection attempts
import { VaultSandboxClient } from '@vaultsandbox/client';
const client = new VaultSandboxClient({
url: 'https://smtp.vaultsandbox.com',
apiKey: process.env.VAULTSANDBOX_API_KEY,
strategy: 'auto',
maxRetries: 5,
retryDelay: 2000,
});

Creates a new email inbox with automatic key generation and encryption setup.

createInbox(options?: CreateInboxOptions): Promise<Inbox>
  • options (optional): Configuration for the inbox
interface CreateInboxOptions {
ttl?: number;
emailAddress?: string;
}
PropertyTypeDescription
ttlnumberTime-to-live for the inbox in seconds (min: 60, max: 604800, default: server’s defaultTtl)
emailAddressstringRequest a specific email address (max 254 chars, e.g., [email protected])

Promise<Inbox> - The created inbox instance

// Create inbox with default settings
const inbox = await client.createInbox();
console.log(inbox.emailAddress);
// Create inbox with custom TTL (1 hour)
const inbox = await client.createInbox({ ttl: 3600 });
// Request specific email address
const inbox = await client.createInbox({
emailAddress: '[email protected]',
});
  • ApiError - API-level error (invalid request, permission denied)
  • NetworkError - Network connection failure
  • InboxAlreadyExistsError - Requested email address is already in use

Deletes all inboxes associated with the current API key. Useful for cleanup in test environments.

deleteAllInboxes(): Promise<number>

Promise<number> - Number of inboxes deleted

const deleted = await client.deleteAllInboxes();
console.log(`Deleted ${deleted} inboxes`);

Use this in test cleanup to avoid orphaned inboxes:

afterAll(async () => {
const deleted = await client.deleteAllInboxes();
if (deleted > 0) {
console.log(`Cleaned up ${deleted} orphaned inboxes`);
}
});

Deletes a specific inbox by its email address.

deleteInbox(emailAddress: string): Promise<void>
  • emailAddress: The email address of the inbox to delete
await client.deleteInbox('[email protected]');

Retrieves information about the VaultSandbox Gateway server.

getServerInfo(): Promise<ServerInfo>

Promise<ServerInfo> - Server information object

interface ServerInfo {
serverSigPk: string;
algs: {
kem: string;
sig: string;
aead: string;
kdf: string;
};
context: string;
maxTtl: number;
defaultTtl: number;
sseConsole: boolean;
allowedDomains: string[];
}
PropertyTypeDescription
serverSigPkstringBase64URL-encoded server signing public key for ML-DSA-65
algsobjectCryptographic algorithms supported by the server
algs.kemstringKey encapsulation mechanism (e.g., ML-KEM-768)
algs.sigstringDigital signature algorithm (e.g., ML-DSA-65)
algs.aeadstringAuthenticated encryption (e.g., AES-256-GCM)
algs.kdfstringKey derivation function (e.g., HKDF-SHA-512)
contextstringContext string for the encryption scheme
maxTtlnumberMaximum time-to-live for inboxes in seconds
defaultTtlnumberDefault time-to-live for inboxes in seconds
sseConsolebooleanWhether the server SSE console is enabled
allowedDomainsstring[]List of domains allowed for inbox creation
const info = await client.getServerInfo();
console.log(`Encryption: ${info.algs.kem}`);
console.log(`Max TTL: ${info.maxTtl}s, Default TTL: ${info.defaultTtl}s`);
console.log(`Allowed domains: ${info.allowedDomains.join(', ')}`);

Validates the API key with the server.

checkKey(): Promise<boolean>

Promise<boolean> - true if the API key is valid

const isValid = await client.checkKey();
if (!isValid) {
throw new Error('Invalid API key');
}

Useful for verifying configuration before running tests:

beforeAll(async () => {
const client = new VaultSandboxClient({
url: process.env.VAULTSANDBOX_URL,
apiKey: process.env.VAULTSANDBOX_API_KEY,
});
const isValid = await client.checkKey();
if (!isValid) {
throw new Error('VaultSandbox API key is invalid');
}
});

Monitors multiple inboxes simultaneously and emits events when new emails arrive.

monitorInboxes(inboxes: Inbox[]): InboxMonitor
  • inboxes: Array of inbox instances to monitor

InboxMonitor - Event emitter for inbox monitoring

const inbox1 = await client.createInbox();
const inbox2 = await client.createInbox();
const monitor = client.monitorInboxes([inbox1, inbox2]);
monitor.on('email', (inbox, email) => {
console.log(`New email in ${inbox.emailAddress}: ${email.subject}`);
});
// Later, stop monitoring
monitor.unsubscribe();

See InboxMonitor API for more details.


Exports an inbox’s data and encryption keys for backup or sharing. The exported data includes sensitive key material and should be treated as confidential.

exportInbox(inboxOrEmail: Inbox | string): ExportedInboxData
  • inboxOrEmail: Inbox instance or email address to export

ExportedInboxData - Serializable inbox data including keys

interface ExportedInboxData {
version: number; // Export format version (currently 1)
emailAddress: string;
inboxHash: string;
expiresAt: string; // ISO 8601 timestamp
serverSigPk: string; // ML-DSA-65 public key (base64url)
secretKey: string; // ML-KEM-768 secret key (base64url)
exportedAt: string; // ISO 8601 timestamp
}
const inbox = await client.createInbox();
const exportedData = client.exportInbox(inbox);
// Save for later use (treat as sensitive!)
console.log(JSON.stringify(exportedData));

Exported data contains private encryption keys. Store securely and never commit to version control.


Imports a previously exported inbox, restoring all data and encryption keys.

importInbox(data: ExportedInboxData): Promise<Inbox>
  • data: Previously exported inbox data

Promise<Inbox> - The imported inbox instance

const exportedData = JSON.parse(savedInboxData);
const inbox = await client.importInbox(exportedData);
console.log(`Imported inbox: ${inbox.emailAddress}`);
// Use inbox normally
const emails = await inbox.listEmails();
  • InboxAlreadyExistsError - Inbox is already imported in this client
  • InvalidImportDataError - Import data is invalid or corrupted
  • ApiError - Server rejected the import (inbox may not exist)

Exports an inbox to a JSON file on disk.

async exportInboxToFile(inboxOrEmail: Inbox | string, filePath: string): Promise<void>
  • inboxOrEmail: Inbox instance or email address to export
  • filePath: Path where the JSON file will be written
const inbox = await client.createInbox();
// Export to file
await client.exportInboxToFile(inbox, './backup/inbox.json');
console.log('Inbox exported to ./backup/inbox.json');

Imports an inbox from a JSON file.

importInboxFromFile(filePath: string): Promise<Inbox>
  • filePath: Path to the exported inbox JSON file

Promise<Inbox> - The imported inbox instance

// Import from file
const inbox = await client.importInboxFromFile('./backup/inbox.json');
console.log(`Imported inbox: ${inbox.emailAddress}`);
// Monitor for new emails
const subscription = inbox.onNewEmail((email) => {
console.log(`New email: ${email.subject}`);
});
  • Test reproducibility across runs
  • Sharing inboxes between environments
  • Manual testing workflows
  • Debugging production issues

Closes the client, terminates any active SSE or polling connections, and cleans up resources.

close(): Promise<void>
const client = new VaultSandboxClient({ url, apiKey });
try {
const inbox = await client.createInbox();
// Use inbox...
} finally {
await client.close();
}

Always close the client when done, especially in long-running processes:

let client;
beforeAll(() => {
client = new VaultSandboxClient({ url, apiKey });
});
afterAll(async () => {
if (client) {
await client.close();
}
});

Here’s a complete example showing typical client usage:

import { VaultSandboxClient } from '@vaultsandbox/client';
async function main() {
// Create client
const client = new VaultSandboxClient({
url: process.env.VAULTSANDBOX_URL,
apiKey: process.env.VAULTSANDBOX_API_KEY,
strategy: 'auto',
maxRetries: 5,
});
try {
// Verify API key
const isValid = await client.checkKey();
if (!isValid) {
throw new Error('Invalid API key');
}
// Get server info
const info = await client.getServerInfo();
console.log(`Connected to VaultSandbox (default TTL: ${info.defaultTtl}s)`);
// Create inbox
const inbox = await client.createInbox();
console.log(`Created inbox: ${inbox.emailAddress}`);
// Export for later use
await client.exportInboxToFile(inbox, './inbox-backup.json');
// Wait for email
const email = await inbox.waitForEmail({
timeout: 30000,
subject: /Test/,
});
console.log(`Received: ${email.subject}`);
// Clean up
await inbox.delete();
// Delete any other orphaned inboxes
const deleted = await client.deleteAllInboxes();
console.log(`Cleaned up ${deleted} total inboxes`);
} finally {
// Always close the client
await client.close();
}
}
main().catch(console.error);