Architecture Overview
VaultSandbox is built on a zero-knowledge architecture that ensures email privacy while maintaining production-like testing fidelity. This page explains how the system works and why itβs designed this way.
System Components
Section titled βSystem ComponentsβVaultSandbox consists of three main components:
1. Backend (Gateway)
Section titled β1. Backend (Gateway)βA NestJS-based service that provides:
- Dynamic SMTP Server: Accepts inbound email on port 25 with full TLS support
- REST API: Manages inboxes, emails, and API keys
- Real-time Notifications: Server-Sent Events (SSE) for instant email delivery
- Email Authentication: SPF, DKIM, DMARC, and reverse DNS validation
- Cryptographic Operations: Message signing with ML-DSA-65 (Dilithium3)
Key Characteristic: The backend encrypts emails immediately upon receipt and never stores plaintext.
2. Frontend (Web UI)
Section titled β2. Frontend (Web UI)βAn Angular-based single-page application that provides:
- Inbox Management: Create, view, and delete inboxes
- Email Viewer: Rich HTML preview and header inspection
- Authentication Results: Visual display of SPF/DKIM/DMARC status
- Link Extraction: Automatic detection and testing of email links
- Client-side Decryption: All email decryption happens in the browser
Key Characteristic: The frontend generates encryption keypairs locally and decrypts emails in the browser.
3. Node.js Client SDK
Section titled β3. Node.js Client SDKβA developer-focused SDK for automated testing:
- Automatic Encryption: Transparent ML-KEM-768 keypair generation
- Smart Email Delivery: SSE-based real-time delivery or efficient polling
- Email Assertions: Helper methods for testing email content and authentication
- CI/CD Optimized: Designed for test automation and pipelines
Key Characteristic: Developers never interact with keys or encryptionβeverything is automatic.
Zero-Knowledge Security Model
Section titled βZero-Knowledge Security ModelβVaultSandbox implements a zero-knowledge architecture where the server cannot read your emails.
How It Works
Section titled βHow It Worksβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ Email Receipt Flow ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
1. Inbox Creation βββββββββββ βββββββββββ β Client β Generate ML-KEM-768 keypair β Server β β β (private key stays local) β β β β ββββββββββββββββββββββββββββββββ> β β β β Send public key only β β βββββββββββ βββββββββββ
2. Email Arrival βββββββββββ βββββββββββ β SMTP β Raw email arrives via SMTP β Server β β Sender β ββββββββββββββββββββββββββββββββ> β β β β (plaintext over TLS) β β βββββββββββ βββββββββββ
3. Immediate Encryption βββββββββββ β Server β β β β’ Parse email (headers, body, attachments) β β Parse | β’ Validate SPF, DKIM, DMARC β β Auth | β’ Encrypt with client's public key β β Enc. | β’ Sign with ML-DSA-65 server key β β Sign | β’ DISCARD PLAINTEXT β β Plain | βββββββββββ
4. Storage (Encrypted Only) βββββββββββ β Memory β β β Stored in RAM as Uint8Array: β[bytes] β β’ Encrypted payloads (binary) β[bytes] β β’ Cryptographic signature (binary) β[bytes] β βββββββββββ
5. Client Retrieval βββββββββββββ βββββββββββ β Client β Request encrypted email β Server β β β <ββββββββββββββββββββββββββββββββ β β β β Receive encrypted blob + sig βββββββββββ β β Verify | β β Decrypt | βββββββββββββCryptographic Details
Section titled βCryptographic DetailsβEncryption: Hybrid ML-KEM-768 + AES-256-GCM
Section titled βEncryption: Hybrid ML-KEM-768 + AES-256-GCMβ- Key Encapsulation: ML-KEM-768 (Kyber768) for quantum-safe key establishment.
- Symmetric Encryption: AES-256-GCM for email payload.
- Key Derivation: HKDF-SHA-512 with a salt derived from the ML-KEM ciphertext to derive a unique AES key from the shared secret.
Why Hybrid Encryption?
- ML-KEM-768 is quantum-resistant but not suitable for large payloads
- AES-256-GCM is fast and secure for bulk encryption
- Combined, they provide quantum-safe protection with excellent performance
Signatures: ML-DSA-65 (Dilithium3)
Section titled βSignatures: ML-DSA-65 (Dilithium3)βEvery encrypted email is signed by the gateway to ensure:
- Authenticity: The email came from the legitimate gateway.
- Integrity: The email hasnβt been tampered with.
- Non-repudiation: The gateway can prove it sent the email.
The signature covers the protocol version, algorithm suite, and email data, preventing any downgrade attacks.
Verification happens BEFORE decryption to prevent processing of tampered messages.
Security Guarantees
Section titled βSecurity Guaranteesβ| What the Server Knows | What the Server CANNOT Know |
|---|---|
| Email arrived | Email content |
| Sender address | Attachments |
| Recipient address | HTML/Text body |
| Email size (approx) | Extracted links |
| SPF/DKIM/DMARC result | Decryption keys |
| Timestamp | Private inbox keys |
Threat Model
Section titled βThreat ModelβVaultSandbox protects against:
- Data Breaches: Even if the server is compromised, emails remain encrypted
- Man-in-the-Middle (MITM): Signature verification detects tampering
- Future Quantum Attacks: ML-KEM-768 is quantum-resistant
VaultSandbox does NOT protect against:
- Client-side Compromise: If the clientβs private key is stolen, emails can be decrypted
- DNS Hijacking: Ensure your domainβs DNS is secure
- Compromised Send-side: VaultSandbox receives emails via standard SMTP; secure the sending application
Ephemeral Storage Design
Section titled βEphemeral Storage DesignβVaultSandbox is optimized for CI/CD pipelines with ephemeral, in-memory storage.
Why In-Memory?
Section titled βWhy In-Memory?β- Speed: No disk I/O bottlenecksβperfect for fast test suites
- Simplicity: No database to manage or backup
- Security: Data disappears on container restart
- CI Optimized: Each test run starts with a clean slate
Binary Storage Format
Section titled βBinary Storage FormatβEncrypted payloads are stored as raw binary Uint8Array fields in memory:
interface EncryptedPayload { v: 1; algs: { kem: 'ML-KEM-768'; sig: 'ML-DSA-65'; aead: 'AES-256-GCM'; kdf: 'HKDF-SHA-512' }; ct_kem: Uint8Array; // KEM ciphertext (raw bytes) nonce: Uint8Array; // 12-byte nonce aad: Uint8Array; // Additional authenticated data ciphertext: Uint8Array; // AES-GCM ciphertext with tag sig: Uint8Array; // ML-DSA signature server_sig_pk: Uint8Array; // Server signing public key}Memory Management
Section titled βMemory ManagementβVaultSandbox implements sophisticated memory management to prevent out-of-memory conditions:
Configurable Memory Limit
Section titled βConfigurable Memory Limitβ- Default: 500MB (
VSB_SMTP_MAX_MEMORY_MB) - Hard cap: Emails exceeding the total limit are rejected
- Tracks actual payload sizes (metadata + parsed + raw)
FIFO Eviction Policy
Section titled βFIFO Eviction PolicyβWhen memory limit is approached, the oldest emails are evicted first:
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ FIFO Eviction Flow ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
1. Email arrives (100KB) Current: 490MB / 500MB
2. Check: 490MB + 100KB > 500MB? Yes β Evict oldest emails
3. Evict oldest until space available [Email 1 - 2KB] β Tombstone β Free [Email 2 - 5KB] β Tombstone β Free ...
4. Store new email Current: 495MB / 500MBTombstone Pattern for O(1) Deletion:
- Instead of array shifts, evicted emails are marked as βtombstonesβ
- Encrypted payloads are removed, freeing ~99.9% of memory
- Metadata kept briefly for tracking consistency
- Hourly compaction removes tombstone entries entirely
Time-Based Eviction (Optional)
Section titled βTime-Based Eviction (Optional)β- Configure via
VSB_SMTP_MAX_EMAIL_AGE_SECONDS - Emails older than threshold are automatically evicted
- Supplements inbox TTL for additional cleanup
- Disabled by default (set to 0)
Data Lifecycle
Section titled βData LifecycleβTest Start β[Create Inbox] ββ> Inbox exists in RAM β[Email Arrives] ββ> Encrypted (Uint8Array), stored in RAM β Memory tracked, FIFO eviction if needed[Test Reads Email] ββ> Serialized to Base64URL, decrypted client-side β[Test Completes] β[Delete Inbox] ββ> Data removed from RAM, memory freed β(or)[Memory Pressure] ββ> Oldest emails evicted (FIFO) β(or)[Container Restart] ββ> All data wiped
Test EndRetention Policy
Section titled βRetention Policyβ- Default: Inboxes expire after a configurable TTL (time-to-live)
- Manual Cleanup: Delete inboxes explicitly via API/SDK
- Automatic Cleanup: Container restart wipes all data
- Memory-Based Eviction: Oldest emails evicted when memory limit reached
- Age-Based Eviction: Optional time-based cleanup for stale emails
Production-Like Email Validation
Section titled βProduction-Like Email ValidationβUnlike mocks, VaultSandbox validates emails exactly as a real email gateway would.
SMTP Protocol Compliance
Section titled βSMTP Protocol Complianceβ- Full TLS Support: Negotiates TLS with real certificates (ACME/Letβs Encrypt)
- SMTP Commands: Proper EHLO, MAIL FROM, RCPT TO, DATA handling
- Error Responses: Returns appropriate SMTP error codes
- Size Limits: Respects message size limits
Email Authentication
Section titled βEmail AuthenticationβVaultSandbox performs the same checks as Gmail, Outlook, and other major providers:
SPF (Sender Policy Framework)
Section titled βSPF (Sender Policy Framework)βValidates that the sending server is authorized to send from the senderβs domain.
Received from: mail.sender.com (192.0.2.1)Envelope From: noreply@sender.comSPF Record: v=spf1 ip4:192.0.2.1 -allResult: β
PASSDKIM (DomainKeys Identified Mail)
Section titled βDKIM (DomainKeys Identified Mail)βVerifies the cryptographic signature in the email headers.
DKIM-Signature: v=1; a=rsa-sha256; d=sender.com; s=default; ...Public Key: Retrieved from default._domainkey.sender.comResult: β
PASSDMARC (Domain-based Message Authentication)
Section titled βDMARC (Domain-based Message Authentication)βChecks alignment between SPF/DKIM and the From address.
DMARC Policy: v=DMARC1; p=reject; ...SPF: β
PASS (aligned)DKIM: β
PASS (aligned)Result: β
PASSReverse DNS (rDNS)
Section titled βReverse DNS (rDNS)βVerifies the sending serverβs hostname matches its IP.
Connecting IP: 192.0.2.1Reverse DNS: mail.sender.comForward Lookup: 192.0.2.1Result: β
MATCHWhy This Matters
Section titled βWhy This MattersβTesting with real authentication catches issues like:
- Misconfigured SPF records that cause emails to be rejected
- Missing DKIM signatures that reduce deliverability
- DMARC failures that send emails to spam
- Reverse DNS mismatches that trigger spam filters
These issues only appear when you test against a real email gateway.
Email Delivery Strategies
Section titled βEmail Delivery StrategiesβThe Node.js SDK supports two strategies for email delivery notification:
Server-Sent Events (SSE)
Section titled βServer-Sent Events (SSE)βReal-time, push-based delivery for instant notifications.
const inbox = await client.createInbox();
// Emails arrive instantly via SSEinbox.onNewEmail((email) => { console.log('New email:', email.subject);});Pros:
- Instant delivery (no polling delay)
- Efficient (no repeated HTTP requests)
- Deterministic tests (no sleep/wait logic)
Cons:
- Requires persistent connection
- May be blocked by some proxies/firewalls
Polling
Section titled βPollingβPull-based delivery with efficient change detection.
const inbox = await client.createInbox();
// Poll for new emailsconst email = await inbox.waitForEmail({ timeout: 30000, pollInterval: 2000, // Check every 2 seconds});Pros:
- Works in all network environments
- No persistent connection required
- Sync token-based (only fetches changes)
Cons:
- Slight delay based on poll interval
- More HTTP requests
Auto Strategy (Recommended)
Section titled βAuto Strategy (Recommended)βThe SDK automatically chooses the best strategy:
const client = new VaultSandboxClient({ url: 'https://mail.example.com', apiKey: 'your-api-key', strategy: 'auto', // Default});- Tries SSE first
- Falls back to polling if SSE fails
- Optimal for most use cases
Scalability Considerations
Section titled βScalability ConsiderationsβHorizontal Scaling
Section titled βHorizontal ScalingβVaultSandboxβs in-memory design makes horizontal scaling challenging:
- Each container has its own isolated storage
- Load balancers need sticky sessions for SSE connections
- Inboxes created on one container arenβt visible on others
For high-scale testing, deploy multiple isolated instances rather than scaling a single deployment.
Vertical Scaling
Section titled βVertical ScalingβVaultSandbox is optimized for vertical scaling:
- Increase RAM for more concurrent inboxes
- Increase CPU for faster encryption/decryption
- Increase network bandwidth for higher email throughput
Memory Management for Production
Section titled βMemory Management for ProductionβConfigure memory limits to prevent OOM conditions:
# Set maximum memory for email storage (default: 500MB)VSB_SMTP_MAX_MEMORY_MB=1024
# Optional: Auto-evict emails older than N secondsVSB_SMTP_MAX_EMAIL_AGE_SECONDS=3600Key behaviors:
- FIFO eviction automatically frees memory when limit approached
- Tombstone pattern ensures O(1) deletion performance
- Hourly compaction cleans up eviction metadata
Next Steps
Section titled βNext Stepsβ- Deployment Setup: Infrastructure, DNS, and TLS setup
- Docker Compose Setup: Deploy VaultSandbox
- Node.js Client: Integrate with your tests
- Security Details: Deep dive into encryption and security