@bernierllc/email-domain-verification
v1.0.0
Published
Programmatic domain setup and DNS management for production email sending with multi-provider support
Downloads
72
Readme
@bernierllc/email-domain-verification
Programmatic domain setup and DNS management for production email sending with multi-provider support.
Overview
The Email Domain Verification package provides comprehensive programmatic domain setup and DNS record management for production email sending. It supports multiple email service providers (SendGrid, Mailgun, AWS SES), manages SPF/DKIM/DMARC records, monitors domain health, and provides NeverAdmin UI integration for domain management workflows.
Features
- Multi-Provider Support: SendGrid, Mailgun, AWS SES
- DNS Record Generation: SPF, DKIM, DMARC, MX records
- DKIM Key Management: Automatic keypair generation and DNS configuration
- DNS Propagation Monitoring: Track DNS propagation across multiple nameservers
- Health Monitoring: Automated health checks with cron scheduling
- Verification History: Complete audit trail of domain verification events
- NeverHub Integration: Event publishing and service discovery
- NeverAdmin UI: Admin panels for domain management
Installation
npm install @bernierllc/email-domain-verificationDependencies
This package requires the following @bernierllc packages:
@bernierllc/email-sender-manager- Email provider integration patterns@bernierllc/crypto-utils- DKIM keypair generation@bernierllc/logger- Structured logging@bernierllc/neverhub-adapter- Service discovery and event bus
Usage
Basic Setup
import { EmailDomainVerificationService } from '@bernierllc/email-domain-verification';
import { Logger } from '@bernierllc/logger';
// Initialize service
const logger = new Logger({ context: 'email-verification' });
const service = new EmailDomainVerificationService({ logger });
await service.initialize();
// Setup domain verification
const result = await service.setupDomain({
domain: 'example.com',
provider: 'sendgrid',
providerCredentials: {
apiKey: process.env.SENDGRID_API_KEY!
},
dkim: {
enabled: true,
selector: 'default',
keySize: 2048
},
spf: {
enabled: true,
strict: true
},
dmarc: {
enabled: true,
policy: 'quarantine',
reportEmail: '[email protected]'
}
});
if (result.success) {
console.log('DNS records to configure:');
result.dnsRecords.forEach(record => {
console.log(`${record.type}: ${record.host} -> ${record.value}`);
});
if (result.dkimConfig) {
console.log('DKIM Private Key (store securely):', result.dkimConfig.privateKey);
}
}Check DNS Propagation
// Check if DNS records have propagated
const propagationResults = await service.checkPropagation(
'example.com',
result.dnsRecords
);
propagationResults.forEach(result => {
console.log(`${result.record.type}: ${result.propagationPercentage}% propagated`);
if (result.propagated && result.valuesMatch) {
console.log('✓ Record fully propagated and values match');
}
});Verify Domain with Provider
// Verify domain with email provider
const verificationResult = await service.verifyDomain(
'example.com',
'sendgrid',
{ apiKey: process.env.SENDGRID_API_KEY! }
);
if (verificationResult.success) {
console.log('Domain verified successfully!');
// Health monitoring starts automatically
}Monitor Domain Health
// Get current domain health
const health = await service.getDomainHealth('example.com');
console.log(`Domain: ${health.domain}`);
console.log(`Status: ${health.verificationStatus}`);
console.log(`Healthy: ${health.healthy}`);
if (health.warnings && health.warnings.length > 0) {
console.log('Warnings:', health.warnings);
}Verification History
// Get verification history
const history = service.getVerificationHistory('example.com', 10);
history.forEach(entry => {
console.log(`[${entry.timestamp}] ${entry.eventType}: ${entry.details}`);
});Provider-Specific Examples
SendGrid
const result = await service.setupDomain({
domain: 'example.com',
provider: 'sendgrid',
providerCredentials: {
apiKey: process.env.SENDGRID_API_KEY!
},
dkim: { enabled: true, keySize: 2048 },
spf: { enabled: true, strict: true },
dmarc: {
enabled: true,
policy: 'quarantine',
reportEmail: '[email protected]'
}
});Mailgun
const result = await service.setupDomain({
domain: 'example.com',
provider: 'mailgun',
providerCredentials: {
apiKey: process.env.MAILGUN_API_KEY!,
smtpPassword: process.env.MAILGUN_SMTP_PASSWORD!
},
dkim: { enabled: true, keySize: 2048 },
spf: { enabled: true },
dmarc: { enabled: true, policy: 'none' }
});AWS SES
const result = await service.setupDomain({
domain: 'example.com',
provider: 'ses',
providerCredentials: {
region: 'us-east-1',
accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!
},
dkim: { enabled: true, keySize: 2048 },
spf: { enabled: true },
dmarc: { enabled: true, policy: 'quarantine' }
});Configuration
Environment Variables
# Email Domain Verification Configuration
EMAIL_DOMAIN_VERIFICATION_HEALTH_CHECK_INTERVAL="0 */6 * * *"
EMAIL_DOMAIN_VERIFICATION_DNS_TIMEOUT=30000
EMAIL_DOMAIN_VERIFICATION_PROPAGATION_THRESHOLD=80
# Provider API Keys (optional - can be passed per-domain)
SENDGRID_API_KEY=""
MAILGUN_API_KEY=""
AWS_SES_REGION=""
AWS_SES_ACCESS_KEY_ID=""
AWS_SES_SECRET_ACCESS_KEY=""
# NeverHub Configuration (optional)
NEVERHUB_API_URL=""
NEVERHUB_API_KEY=""Constructor Options
const service = new EmailDomainVerificationService({
logger: customLogger,
neverhub: customNeverHub,
healthCheckInterval: '0 */6 * * *' // Cron expression
});API Reference
EmailDomainVerificationService
setupDomain(config: DomainConfig): Promise<DomainVerificationResult>
Setup domain verification for an email provider. Generates DNS records, DKIM keypairs, and registers with the provider.
Parameters:
config.domain- Domain name (e.g., 'example.com')config.provider- Email provider ('sendgrid', 'mailgun', 'ses')config.providerCredentials- Provider API credentialsconfig.dkim- DKIM configurationconfig.spf- SPF configurationconfig.dmarc- DMARC configuration
Returns: Domain verification result with DNS records to configure
checkPropagation(domain: string, records: DNSRecord[]): Promise<DNSPropagationResult[]>
Check DNS propagation status for domain records across multiple nameservers.
Parameters:
domain- Domain namerecords- DNS records to check
Returns: Propagation results for each record
verifyDomain(domain: string, provider: EmailProvider, credentials: object): Promise<DomainVerificationResult>
Verify domain with email provider. Starts health monitoring if verification succeeds.
Parameters:
domain- Domain nameprovider- Email providercredentials- Provider API credentials
Returns: Verification result
getDomainHealth(domain: string): Promise<DomainHealthStatus>
Get current domain health status.
Parameters:
domain- Domain name
Returns: Health status with record details
getVerificationHistory(domain: string, limit?: number): VerificationHistoryEntry[]
Get verification history for domain.
Parameters:
domain- Domain namelimit- Maximum number of entries (default: 50)
Returns: History entries
stopHealthMonitoring(domain: string): void
Stop automated health monitoring for domain.
Parameters:
domain- Domain name
shutdown(): Promise<void>
Cleanup resources and stop all health monitoring jobs.
Integration Status
- Logger: integrated - All verification events, DNS propagation checks, and health monitoring logged
- Docs-Suite: ready - TypeDoc format, complete API reference
- NeverHub: required - Event publishing for domain verification lifecycle
- NeverAdmin: required - Admin UI components for domain management
NeverHub Events
Events Published:
domain.verification.initiated- Domain verification setup starteddomain.propagation.checked- DNS propagation check completeddomain.verification.completed- Verification with provider completeddomain.health.unhealthy- Health check detected issues
Events Subscribed:
email.domain.required- Email service requests domain verificationmonitoring.health.check- System-wide health check triggered
TypeScript Support
This package is written in TypeScript and includes complete type definitions.
import {
EmailDomainVerificationService,
DomainConfig,
DomainVerificationResult,
DNSRecord,
DKIMConfig,
VerificationStatus
} from '@bernierllc/email-domain-verification';Error Handling
The package provides structured error types:
import {
DomainVerificationError,
DNSPropagationError,
ProviderAPIError,
InvalidDomainError
} from '@bernierllc/email-domain-verification';
try {
await service.setupDomain(config);
} catch (error) {
if (error instanceof InvalidDomainError) {
console.error('Invalid domain:', error.message);
} else if (error instanceof DNSPropagationError) {
console.error('DNS propagation failed:', error.message);
// Retryable error
}
}Testing
# Run tests
npm test
# Run tests once
npm run test:run
# Run with coverage
npm run test:coverageBuilding
# Build TypeScript to JavaScript
npm run build
# Clean dist directory
npm run cleanLinting
# Lint source code
npm run lintLicense
Copyright (c) 2025 Bernier LLC. All rights reserved.
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.
Related Packages
- @bernierllc/email-sender-manager - Email sending orchestration
- @bernierllc/crypto-utils - Cryptographic utilities
- @bernierllc/logger - Structured logging
- @bernierllc/neverhub-adapter - Service discovery
- @bernierllc/email-suite - Complete email management system
