UNPKG

txt-domain-verification

Version:

A production-ready Node.js package for verifying domain ownership through DNS TXT records with authoritative nameserver queries, security features, and comprehensive error handling.

235 lines (179 loc) โ€ข 6.46 kB
# txt-domain-verification A production-ready Node.js package for verifying domain ownership through DNS TXT records with authoritative nameserver queries, security features, and comprehensive error handling. ## ๐Ÿš€ New in v2.0.0 - **Authoritative Nameserver Queries**: Queries domain nameservers directly instead of relying on OS/ISP resolvers - **Secure Token Generation**: HMAC-based tokens with user binding and expiration - **Domain Normalization**: Handles punycode, casing, and trailing dots consistently - **Retry Logic**: Exponential backoff with configurable retry attempts - **Partial Propagation Detection**: Reports when verification records are still propagating - **TypeScript Support**: Full type definitions included - **Dual Build**: Both CommonJS and ESM modules supported ## ๐Ÿ”’ Security Features - **Fixed TXT Record Name**: Uses `_verify.example.com` for actual verification - **HMAC Tokens**: Cryptographically secure tokens bound to user, domain, and timestamp - **Token Expiration**: Configurable expiry (default: 72 hours) - **Single-Use Tokens**: Designed for one-time verification - **DNS-Only Verification**: No HTTP/HTTPS requests to prevent SSRF attacks ## ๐Ÿ“ฆ Installation ```bash npm install txt-domain-verification ``` ```bash yarn add txt-domain-verification ``` ```bash pnpm add txt-domain-verification ``` ```bash bun add txt-domain-verification ``` ## ๐Ÿ› ๏ธ Usage ### Basic Verification Flow ```javascript const { generateVerificationCode, verifyDomain, CONFIG, } = require('txt-domain-verification'); // 1. Generate verification code const verificationCode = generateVerificationCode( 'example.com', // Domain to verify 'your-secret-key', // Secret for HMAC 'user123', // User identifier 'AcmeCorp', // Business name (optional) '{{businessName}} Verification: {{token}}' // Custom format ); console.log(verificationCode.instructions); // Output: Please add the following TXT record to your DNS settings for example.com: // Name: _verify // Value: AcmeCorp Verification: eyJ0b2tlbiI6ImFiY2RlZiJ9... // 2. User adds TXT record to DNS // 3. Verify domain ownership const result = await verifyDomain('example.com', verificationCode.token); if (result.verified) { console.log('Domain verified successfully!'); } else if (result.partialPropagation) { console.log( `Partial propagation: ${result.successfulQueries}/${result.totalNameservers} nameservers responding` ); } ``` ### Advanced Verification with Options ```javascript const result = await verifyDomain( 'example.com', verificationCode.token, '_verify', // Custom verification prefix { maxRetries: 5, // Maximum retry attempts retryDelay: 2000, // Base delay between retries (ms) } ); console.log('Verification result:', { verified: result.verified, domain: result.domain, totalNameservers: result.totalNameservers, successfulQueries: result.successfulQueries, partialPropagation: result.partialPropagation, timestamp: result.timestamp, }); ``` ### Domain Normalization ```javascript const { normalizeDomain } = require('txt-domain-verification'); const normalized = normalizeDomain(' EXAMPLE.COM. '); console.log(normalized); // 'example.com' ``` ### Secure Token Generation ```javascript const { generateSecureToken } = require('txt-domain-verification'); const token = generateSecureToken( 'secret-key', 'user123', 'example.com', new Date() ); ``` ## ๐Ÿ”ง Configuration ```javascript const { CONFIG } = require('txt-domain-verification'); console.log(CONFIG); // { // VERIFICATION_PREFIX: '_verify', // TOKEN_EXPIRY_HOURS: 72, // MAX_RETRIES: 3, // RETRY_DELAY_MS: 1000, // DNS_TIMEOUT_MS: 10000, // MIN_NAMESERVERS_VERIFIED: 1 // } ``` ## ๐Ÿ“Š Verification Results The `verifyDomain` function returns detailed information about the verification process: ```javascript { verified: boolean, // Whether verification succeeded domain: string, // Normalized domain name attempt: number, // Current attempt number totalNameservers: number, // Total nameservers found successfulQueries: number, // Successfully queried nameservers failedQueries: number, // Failed nameserver queries matchingRecords: Array, // Records containing the token partialPropagation: boolean, // Whether some nameservers are still propagating nameserverResults: Array, // Detailed results from each nameserver timestamp: Date // When verification was performed } ``` ## ๐ŸŒ How It Works 1. **Nameserver Resolution**: Queries the domain's authoritative nameservers 2. **Direct DNS Queries**: Sends DNS queries directly to each nameserver 3. **Token Verification**: Checks TXT records for the secure verification token 4. **Propagation Detection**: Reports partial propagation status 5. **Retry Logic**: Implements exponential backoff for failed queries ## ๐Ÿงช Testing ```bash npm test npm run test:coverage ``` ## ๐Ÿ“ฆ Building ```bash npm run build ``` This creates both CommonJS (`dist/index.js`) and ESM (`dist/index.mjs`) builds. ## ๐Ÿ”„ Migration from v1.x ### Old API (Deprecated) ```javascript const { generateVerificationCode, verifyDomain, } = require('txt-domain-verification'); // Old: Random hex codes const result = generateVerificationCode('example.com', 'business'); const isVerified = await verifyDomain('example.com', result.formattedString); ``` ### New API (Recommended) ```javascript const { generateVerificationCode, verifyDomain, } = require('txt-domain-verification'); // New: Secure HMAC tokens const verificationCode = generateVerificationCode( 'example.com', 'your-secret-key', 'user123', 'business' ); const result = await verifyDomain('example.com', verificationCode.token); ``` ## ๐Ÿšจ Important Notes - **Secret Management**: Store your secret key securely (environment variables, secret management service) - **Token Expiry**: Tokens expire after 72 hours by default - **DNS Propagation**: Allow 5-60 minutes for DNS changes to propagate - **Nameserver Queries**: The library queries authoritative nameservers directly for accuracy - **Rate Limiting**: Implement rate limiting in your application for production use ## ๐Ÿ“„ License CC BY-SA ## ๐Ÿค Contributing Contributions are welcome! Please ensure all tests pass and add tests for new features. ## ๐Ÿ“š Examples See `example-new.js` for comprehensive usage examples.