@bernierllc/email-mitm-masking

中文文档
1.6.11发布于 2026/11/05SEE LICENSE IN LICENSETypeScriptCommonJS近 30 天下载 2072

Email masking and man-in-the-middle routing service for privacy-focused email communication

原始使用文档
文档目录30 节
  1. Installation
  2. Features
  3. Usage
  4. Basic Setup
  5. Create a Proxy Email Address
  6. Route Inbound Email (Webhook Handler)
  7. Route Outbound Email (Reply via Proxy)
  8. Proxy Lifecycle Management
  9. API Reference
  10. EmailMaskingService
  11. Configuration
  12. Environment Variables
  13. Database Schema
  14. proxy_addresses
  15. routing_audit
  16. masking_rules
  17. Security Considerations
  18. Integration Status
  19. Performance
  20. Error Handling
  21. Examples
  22. Per-Contact Masking
  23. Temporary Proxies
  24. Webhook Integration (SendGrid)
  25. Testing
  26. License
  27. Related Packages
  28. Dependencies
  29. Part of Suite
  30. Support

@bernierllc/email-mitm-masking

Email masking and man-in-the-middle routing service for privacy-focused email communication. Provides proxy email addresses that mask real user addresses while routing messages bidirectionally with full audit trail and lifecycle management.

Installation

npm install @bernierllc/email-mitm-masking

Features

  • 🔒 Privacy-First: Generate proxy email addresses to mask real user addresses
  • ↔️ Bidirectional Routing: Route emails both inbound (external → real) and outbound (real → external)
  • 🔄 Lifecycle Management: Create, activate, deactivate, expire, and revoke proxies
  • 📊 Audit Trail: Complete routing audit log for compliance and debugging
  • 🎯 Flexible Strategies: Support for per-user, per-contact, and per-conversation masking
  • ⏱️ TTL Support: Automatic expiration with configurable time-to-live
  • 📈 Usage Tracking: Monitor proxy usage and routing statistics
  • 🔒 Quota Enforcement: Prevent abuse with per-user proxy limits

Usage

Basic Setup

import { EmailMaskingService } from '@bernierllc/email-mitm-masking';

const service = new EmailMaskingService({
  proxyDomain: 'proxy.example.com',
  database: {
    host: 'localhost',
    port: 5432,
    database: 'email_masking',
    user: 'postgres',
    password: process.env.DB_PASSWORD
  },
  defaultTTL: 365,          // 365 days
  maxProxiesPerUser: 100,    // 100 proxies per user
  auditEnabled: true,        // Enable audit logging
  strategy: 'per-contact'    // Create one proxy per contact
});

await service.initialize();

Create a Proxy Email Address

// Create a basic proxy
const proxy = await service.createProxy(
  'user123',
  '[email protected]'
);

console.log(proxy.proxyEmail);
// Output: [email protected]

// Create proxy with custom TTL
const tempProxy = await service.createProxy(
  'user123',
  '[email protected]',
  {
    ttlDays: 30,  // Expires in 30 days
    externalEmail: '[email protected]',
    metadata: { source: 'signup-form', priority: 'high' }
  }
);

Route Inbound Email (Webhook Handler)

import express from 'express';

const app = express();

app.post('/webhooks/inbound-email', express.text({ type: '*/*' }), async (req, res) => {
  const { from, to, subject, text, html } = parseEmail(req.body);

  const result = await service.routeInbound(from, to, subject, text, html);

  if (result.success) {
    res.json({
      status: 'routed',
      to: result.routedTo,
      auditId: result.auditId
    });
  } else {
    res.status(400).json({
      status: 'failed',
      error: result.error
    });
  }
});

Route Outbound Email (Reply via Proxy)

async function sendReplyViaProxy(
  userId: string,
  userEmail: string,
  recipientEmail: string,
  message: string
) {
  const result = await service.routeOutbound(
    userId,
    userEmail,
    recipientEmail,
    {
      subject: 'Re: Your inquiry',
      text: message,
      html: `<p>${message}</p>`
    }
  );

  if (result.success) {
    console.log(`Reply sent via proxy: ${result.proxyUsed}`);
  } else {
    console.error(`Failed to send reply: ${result.error}`);
  }

  return result;
}

Proxy Lifecycle Management

// Create proxy with 30-day expiration
const proxy = await service.createProxy('user456', '[email protected]', {
  ttlDays: 30
});

// Use the proxy for routing...
await service.routeInbound(from, proxy.proxyEmail, subject);

// Deactivate when temporarily not needed
await service.deactivateProxy(proxy.id);

// Permanently revoke
await service.revokeProxy(proxy.id);

// Retrieve proxy details
const proxyDetails = await service.getProxyById(proxy.id);
console.log(proxyDetails.status); // 'revoked'

API Reference

EmailMaskingService

new EmailMaskingService(config)

Create a new email masking service instance.

Parameters:

  • config.proxyDomain (string, required): Domain for proxy addresses
  • config.database (DatabaseConfig, required): PostgreSQL connection config
  • config.defaultTTL (number, optional): Default TTL in days (0 = unlimited, default: 0)
  • config.maxProxiesPerUser (number, optional): Max proxies per user (0 = unlimited, default: 0)
  • config.auditEnabled (boolean, optional): Enable audit logging (default: true)
  • config.strategy ('per-user' | 'per-contact' | 'per-conversation', optional): Masking strategy (default: 'per-user')

initialize(): Promise<void>

Initialize the service, create database schema, and start cleanup jobs.

createProxy(userId, realEmail, options?): Promise<ProxyAddress>

Create a new proxy email address.

Parameters:

  • userId (string): User identifier
  • realEmail (string): Real user email address
  • options.ttlDays (number, optional): TTL in days
  • options.externalEmail (string, optional): External contact email
  • options.conversationId (string, optional): Conversation identifier
  • options.metadata (object, optional): Custom metadata

Returns: ProxyAddress object

routeInbound(from, to, subject, text?, html?): Promise<RoutingResult>

Route an inbound email from external sender to real address via proxy.

Parameters:

  • from (string): External sender address
  • to (string): Proxy email address
  • subject (string): Email subject
  • text (string, optional): Plain text body
  • html (string, optional): HTML body

Returns: RoutingResult with routing status and audit ID

routeOutbound(userId, realEmail, externalEmail, emailContent): Promise<RoutingResult>

Route an outbound email from real address to external recipient via proxy.

Parameters:

  • userId (string): User identifier
  • realEmail (string): Real user email address
  • externalEmail (string): External recipient address
  • emailContent.subject (string): Email subject
  • emailContent.text (string, optional): Plain text body
  • emailContent.html (string, optional): HTML body

Returns: RoutingResult with routing status and audit ID

deactivateProxy(proxyId): Promise<void>

Deactivate a proxy address (can be reactivated).

revokeProxy(proxyId): Promise<void>

Permanently revoke a proxy address.

getProxyById(proxyId): Promise<ProxyAddress | null>

Retrieve proxy details by ID.

shutdown(): Promise<void>

Cleanup resources and close database connection.

Configuration

Environment Variables

# EMAIL_MITM_MASKING Configuration
EMAIL_MASKING_PROXY_DOMAIN=proxy.example.com
EMAIL_MASKING_DB_HOST=localhost
EMAIL_MASKING_DB_PORT=5432
EMAIL_MASKING_DB_NAME=email_masking
EMAIL_MASKING_DB_USER=postgres
EMAIL_MASKING_DB_PASSWORD=secret
EMAIL_MASKING_DEFAULT_TTL=365           # Days (0 = unlimited)
EMAIL_MASKING_MAX_PROXIES_PER_USER=100  # Max per user (0 = unlimited)
EMAIL_MASKING_AUDIT_ENABLED=true        # Enable audit logging
EMAIL_MASKING_STRATEGY=per-contact      # per-user, per-contact, per-conversation

Database Schema

The service automatically creates the following PostgreSQL tables:

proxy_addresses

Stores proxy email address records with lifecycle management.

routing_audit

Audit trail for all routing decisions (when audit is enabled).

masking_rules

User-defined masking rules (reserved for future use).

See the plan file for complete schema definitions.

Security Considerations

  1. Secure Token Generation: Uses cryptographically secure random tokens for proxy addresses
  2. Email Validation: Validates proxy domain to prevent spoofing
  3. Quota Enforcement: Prevents abuse via per-user proxy limits
  4. Audit Trail: Complete audit log for compliance and debugging
  5. Status Validation: Checks proxy status before routing (active, expired, revoked)
  6. SQL Injection Protection: Uses parameterized queries throughout
  7. Privacy Guarantee: Real email addresses never exposed in external emails
  8. Automatic Cleanup: Hourly job expires old proxies automatically

Integration Status

  • Logger: integrated - Structured logging for all operations
  • Docs-Suite: ready - Complete API documentation with TypeDoc
  • NeverHub: not-applicable - Service package, NeverHub integration optional

Performance

  • Proxy Creation: ~50ms (including database insert)
  • Routing Lookup: ~10ms (indexed queries)
  • Audit Logging: ~5ms (when enabled)
  • Cleanup Job: Runs hourly, processes expired proxies in bulk

Error Handling

All methods return structured results:

interface RoutingResult {
  success: boolean;
  routedTo?: string;
  proxyUsed?: string;
  direction: 'inbound' | 'outbound';
  error?: string;
  auditId?: string;
}

Example error handling:

const result = await service.routeInbound(from, to, subject);

if (!result.success) {
  switch (result.error) {
    case 'Proxy address not found':
      // Handle unknown proxy
      break;
    case 'Proxy is inactive':
      // Handle inactive proxy
      break;
    case 'Proxy expired':
      // Handle expired proxy
      break;
    default:
      // Handle other errors
  }
}

Examples

Per-Contact Masking

const service = new EmailMaskingService({
  proxyDomain: 'proxy.example.com',
  database: dbConfig,
  strategy: 'per-contact'
});

// Each user-contact pair gets a unique proxy
const proxy1 = await service.createProxy('user1', '[email protected]', {
  externalEmail: '[email protected]'
});

const proxy2 = await service.createProxy('user1', '[email protected]', {
  externalEmail: '[email protected]'
});

// Different proxies for different contacts
console.log(proxy1.proxyEmail !== proxy2.proxyEmail); // true

Temporary Proxies

// Create proxy that expires in 7 days
const tempProxy = await service.createProxy('user123', '[email protected]', {
  ttlDays: 7,
  metadata: { purpose: 'one-time-signup' }
});

// After 7 days, inbound routing will fail
// Cleanup job will mark it as expired

Webhook Integration (SendGrid)

app.post('/webhooks/sendgrid', express.json(), async (req, res) => {
  const { from, to, subject, text, html } = req.body;

  const result = await service.routeInbound(from, to, subject, text, html);

  res.status(result.success ? 200 : 400).json(result);
});

Testing

# Run tests
npm test

# Run tests with coverage
npm run test:coverage

# Run tests once (CI mode)
npm run test:run

License

Copyright (c) 2025 Bernier LLC

This file is licensed to the client under a limited-use license. The client may use and modify this code only within the scope of the project it was delivered for. Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.

Dependencies

Part of Suite

Support

For issues and questions, please refer to the main BernierLLC tools repository.

版本与发布记录

@bernierllc/email-mitm-masking 共发布 27 个版本,首次发布于 2025/11/11;过去 12 个月发布了 27 个版本。

版本发布日期距今
1.6.11latest2026/11/053 天前
1.6.102026/11/053 天前
1.6.92026/10/2415 天前
1.6.82026/10/2316 天前
1.6.72026/10/1920 天前
1.6.62026/10/021 个月前

关于 @bernierllc/email-mitm-masking 的常见问题

@bernierllc/email-mitm-masking 是什么?

Email masking and man-in-the-middle routing service for privacy-focused email communication

如何安装 @bernierllc/email-mitm-masking?

在项目目录运行 npm install @bernierllc/email-mitm-masking,或使用 pnpm add / yarn add / bun add。

@bernierllc/email-mitm-masking 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@bernierllc/email-mitm-masking 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@bernierllc/email-mitm-masking 可以商用吗?

@bernierllc/email-mitm-masking 使用 SEE LICENSE IN LICENSE 许可。许可条款写在包内的独立文件中,请阅读该文件确认可否商用。以上为概括,不构成法律意见,请以许可原文为准。

@bernierllc/email-mitm-masking 的下载量有多少?

根据 npm 官方下载统计,@bernierllc/email-mitm-masking 在 2026/10/08 – 2026/11/06 这 30 天内被下载 2,072 次,日均约 69 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@bernierllc/email-mitm-masking 还在维护吗?

最新版本 1.6.11 发布于 2026/11/05(3 天前);至今共发布 27 个版本,其中过去 12 个月发布了 27 个;首次发布于 2025/11/11。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。