@mikkelscheike/email-provider-links 1.6.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,605 +2,94 @@
2
2
  /**
3
3
  * Email Provider Links
4
4
  *
5
- * A TypeScript package that provides direct links to email providers
6
- * based on email addresses to streamline login and password reset flows.
5
+ * A clean, modern email provider detection library with:
6
+ * - 93+ verified email providers covering 180+ domains
7
+ * - Concurrent DNS detection for business domains
8
+ * - Zero runtime dependencies
9
+ * - Comprehensive error handling
10
+ * - Email alias normalization
7
11
  *
8
- * The package uses a two-tier detection system:
9
- * 1. Fast domain lookup against a JSON database of known providers
10
- * 2. DNS-based detection for custom business domains using MX/TXT record analysis
11
- *
12
- * @packageDocumentation
12
+ * @author Email Provider Links Team
13
+ * @license MIT
13
14
  */
14
15
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.RateLimit = void 0;
16
- exports.isValidEmail = isValidEmail;
17
- exports.extractDomain = extractDomain;
18
- exports.findEmailProvider = findEmailProvider;
19
- exports.getEmailProviderLink = getEmailProviderLink;
16
+ exports.DOMAIN_COUNT = exports.PROVIDER_COUNT = exports.detectProviderConcurrent = exports.loadProviders = exports.Config = exports.emailsMatch = exports.normalizeEmail = exports.getEmailProviderFast = exports.getEmailProviderSync = exports.getEmailProvider = void 0;
20
17
  exports.getSupportedProviders = getSupportedProviders;
21
18
  exports.isEmailProviderSupported = isEmailProviderSupported;
22
- exports.detectProviderByDNS = detectProviderByDNS;
23
- exports.getEmailProviderLinkWithDNS = getEmailProviderLinkWithDNS;
24
- const fs_1 = require("fs");
25
- const path_1 = require("path");
26
- const util_1 = require("util");
27
- const dns_1 = require("dns");
28
- // Convert Node.js callback-style DNS functions to Promise-based
29
- const resolveMxAsync = (0, util_1.promisify)(dns_1.resolveMx);
30
- const resolveTxtAsync = (0, util_1.promisify)(dns_1.resolveTxt);
31
- /**
32
- * Default timeout for DNS queries in milliseconds.
33
- */
34
- const DEFAULT_DNS_TIMEOUT = 5000; // 5 seconds
35
- /**
36
- * Rate limiting configuration for DNS queries.
37
- */
38
- const RATE_LIMIT_MAX_REQUESTS = 10; // Maximum requests per time window
39
- const RATE_LIMIT_WINDOW_MS = 60000; // Time window in milliseconds (1 minute)
40
- /**
41
- * Simple rate limiter to prevent excessive DNS queries.
42
- * Tracks request timestamps and enforces a maximum number of requests per time window.
43
- */
44
- class SimpleRateLimiter {
45
- constructor(maxRequests = RATE_LIMIT_MAX_REQUESTS, windowMs = RATE_LIMIT_WINDOW_MS) {
46
- this.maxRequests = maxRequests;
47
- this.windowMs = windowMs;
48
- this.requestTimestamps = [];
49
- }
50
- /**
51
- * Checks if a request is allowed under the current rate limit.
52
- * @returns true if request is allowed, false if rate limited
53
- */
54
- isAllowed() {
55
- const now = Date.now();
56
- // Remove old timestamps outside the current window
57
- this.requestTimestamps = this.requestTimestamps.filter(timestamp => now - timestamp < this.windowMs);
58
- // Check if we're under the limit
59
- if (this.requestTimestamps.length < this.maxRequests) {
60
- this.requestTimestamps.push(now);
61
- return true;
62
- }
63
- return false;
64
- }
65
- /**
66
- * Gets the current number of requests in the window.
67
- */
68
- getCurrentCount() {
69
- const now = Date.now();
70
- this.requestTimestamps = this.requestTimestamps.filter(timestamp => now - timestamp < this.windowMs);
71
- return this.requestTimestamps.length;
72
- }
73
- /**
74
- * Gets the time until the rate limit resets (when oldest request expires).
75
- * @returns milliseconds until reset, or 0 if not rate limited
76
- */
77
- getTimeUntilReset() {
78
- if (this.requestTimestamps.length === 0)
79
- return 0;
80
- const oldestTimestamp = Math.min(...this.requestTimestamps);
81
- const resetTime = oldestTimestamp + this.windowMs;
82
- const now = Date.now();
83
- return Math.max(0, resetTime - now);
84
- }
85
- }
86
- // Global rate limiter instance
87
- const dnsRateLimiter = new SimpleRateLimiter();
88
- /**
89
- * Creates a Promise that rejects after the specified timeout.
90
- *
91
- * @param ms - Timeout in milliseconds
92
- * @returns Promise that rejects with timeout error and a cleanup function
93
- * @internal
94
- */
95
- function createTimeout(ms) {
96
- let timeoutId;
97
- const promise = new Promise((_, reject) => {
98
- timeoutId = setTimeout(() => reject(new Error(`DNS query timeout after ${ms}ms`)), ms);
99
- });
100
- const cleanup = () => {
101
- if (timeoutId) {
102
- clearTimeout(timeoutId);
103
- }
104
- };
105
- return { promise, cleanup };
106
- }
107
- /**
108
- * Wraps a DNS query with a timeout.
109
- *
110
- * @param promise - The DNS query promise
111
- * @param timeoutMs - Timeout in milliseconds
112
- * @returns Promise that resolves with DNS result or rejects on timeout
113
- * @internal
114
- */
115
- function withTimeout(promise, timeoutMs) {
116
- const { promise: timeoutPromise, cleanup } = createTimeout(timeoutMs);
117
- return Promise.race([
118
- promise.finally(() => cleanup()), // Clean up timeout when original promise settles
119
- timeoutPromise
120
- ]);
121
- }
122
- // Load providers from external JSON file
123
- let EMAIL_PROVIDERS = [];
124
- // Performance optimization: Create a domain-to-provider Map for O(1) lookups
125
- let DOMAIN_TO_PROVIDER_MAP = new Map();
126
- /**
127
- * Builds a Map for fast domain-to-provider lookups.
128
- * This optimization improves lookup performance from O(n*m) to O(1)
129
- * where n = number of providers, m = average domains per provider.
130
- *
131
- * @internal
132
- */
133
- function buildDomainMap() {
134
- DOMAIN_TO_PROVIDER_MAP.clear();
135
- for (const provider of EMAIL_PROVIDERS) {
136
- for (const domain of provider.domains) {
137
- DOMAIN_TO_PROVIDER_MAP.set(domain.toLowerCase(), provider);
138
- }
139
- }
140
- }
141
- try {
142
- const providersPath = (0, path_1.join)(__dirname, '..', 'providers', 'emailproviders.json');
143
- const providersData = JSON.parse((0, fs_1.readFileSync)(providersPath, 'utf8'));
144
- EMAIL_PROVIDERS = providersData.providers;
145
- buildDomainMap(); // Build optimized lookup map
146
- }
147
- catch (error) {
148
- // Fallback to hardcoded providers if JSON file is not found
149
- console.warn('Could not load providers from JSON file, using fallback providers', error instanceof Error ? error.message : 'Unknown error');
150
- EMAIL_PROVIDERS = [
151
- {
152
- companyProvider: 'Google',
153
- loginUrl: 'https://accounts.google.com/signin',
154
- domains: ['gmail.com', 'googlemail.com']
155
- },
156
- {
157
- companyProvider: 'Microsoft',
158
- loginUrl: 'https://outlook.live.com/owa/',
159
- domains: ['outlook.com', 'hotmail.com', 'live.com', 'msn.com']
160
- },
161
- {
162
- companyProvider: 'Yahoo',
163
- loginUrl: 'https://login.yahoo.com/',
164
- domains: ['yahoo.com', 'yahoo.co.uk', 'yahoo.ca', 'yahoo.com.au', 'ymail.com', 'rocketmail.com']
165
- }
166
- ];
167
- buildDomainMap(); // Build optimized lookup map for fallback too
168
- }
169
- /**
170
- * Validates if a string is a valid email address using a basic regex pattern.
171
- *
172
- * @param email - The string to validate as an email address
173
- * @returns true if the string matches basic email format, false otherwise
174
- *
175
- * @example
176
- * ```typescript
177
- * isValidEmail('user@gmail.com'); // true
178
- * isValidEmail('invalid-email'); // false
179
- * isValidEmail('user@domain'); // false
180
- * ```
181
- *
182
- * @remarks
183
- * This uses a simple regex pattern that covers most common email formats.
184
- * It may not catch all edge cases defined in RFC 5322, but works for
185
- * standard email addresses.
186
- */
187
- function isValidEmail(email) {
188
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
189
- return emailRegex.test(email);
190
- }
191
- /**
192
- * Extracts the domain portion from an email address.
193
- *
194
- * @param email - The email address to extract the domain from
195
- * @returns The domain in lowercase, or null if the email is invalid
196
- *
197
- * @example
198
- * ```typescript
199
- * extractDomain('user@Gmail.com'); // 'gmail.com'
200
- * extractDomain('test@yahoo.co.uk'); // 'yahoo.co.uk'
201
- * extractDomain('invalid-email'); // null
202
- * ```
203
- *
204
- * @remarks
205
- * The domain is automatically normalized to lowercase for consistent matching.
206
- */
207
- function extractDomain(email) {
208
- if (!isValidEmail(email)) {
209
- return null;
210
- }
211
- const parts = email.split('@');
212
- return parts.length === 2 ? parts[1].toLowerCase() : null;
213
- }
214
- /**
215
- * Finds an email provider by matching the domain against the known providers database.
216
- * Uses an optimized Map for O(1) lookup performance.
217
- *
218
- * @param domain - The email domain to look up (e.g., 'gmail.com')
219
- * @returns The matching EmailProvider object, or null if not found
220
- *
221
- * @example
222
- * ```typescript
223
- * const provider = findEmailProvider('gmail.com');
224
- * console.log(provider?.companyProvider); // 'Gmail'
225
- * console.log(provider?.loginUrl); // 'https://mail.google.com/mail/'
226
- * ```
227
- *
228
- * @remarks
229
- * This function performs a case-insensitive O(1) lookup using a pre-built Map.
230
- * It only checks the predefined JSON database, not DNS records.
231
- * Performance optimized from O(n*m) to O(1) where n=providers, m=domains per provider.
232
- */
233
- function findEmailProvider(domain) {
234
- const normalizedDomain = domain.toLowerCase();
235
- return DOMAIN_TO_PROVIDER_MAP.get(normalizedDomain) || null;
236
- }
237
- /**
238
- * Gets email provider information and login URL for a given email address.
239
- * This is the basic/synchronous version that only checks predefined domains.
240
- *
241
- * @param email - The email address to analyze
242
- * @returns EmailProviderResult containing provider info and login URL
243
- *
244
- * @example
245
- * ```typescript
246
- * const result = getEmailProviderLink('user@gmail.com');
247
- * console.log(result.loginUrl); // 'https://mail.google.com/mail/'
248
- * console.log(result.provider?.companyProvider); // 'Gmail'
249
- * ```
250
- *
251
- * @remarks
252
- * This function only checks against the predefined JSON database of known domains.
253
- * It will NOT detect business domains that use major email providers (e.g.,
254
- * mycompany.com using Google Workspace). For comprehensive detection including
255
- * business domains, use {@link getEmailProviderLinkWithDNS} instead.
256
- *
257
- * **Limitations:**
258
- * - Only synchronous operation (no DNS lookups)
259
- * - Limited to domains in the JSON database
260
- * - Won't detect custom business domains
261
- * - No proxy service detection
262
- */
263
- function getEmailProviderLink(email) {
264
- const domain = extractDomain(email);
265
- if (!domain) {
266
- return {
267
- provider: null,
268
- email,
269
- loginUrl: null
270
- };
271
- }
272
- const provider = findEmailProvider(domain);
273
- return {
274
- provider,
275
- email,
276
- loginUrl: provider ? provider.loginUrl : null
277
- };
278
- }
279
- /**
280
- * Returns an array of all supported email providers.
281
- *
282
- * @returns A copy of the EMAIL_PROVIDERS array
283
- *
284
- * @example
285
- * ```typescript
286
- * const providers = getSupportedProviders();
287
- * console.log(providers.length); // 55+
288
- * console.log(providers[0].companyProvider); // 'Gmail'
289
- * ```
290
- *
291
- * @remarks
292
- * Returns a shallow copy to prevent external modification of the internal
293
- * providers array. The returned array includes both consumer email providers
294
- * (gmail.com, yahoo.com) and business email providers with DNS detection patterns.
19
+ exports.extractDomain = extractDomain;
20
+ exports.isValidEmail = isValidEmail;
21
+ // ===== PRIMARY API =====
22
+ // These are the functions 95% of users need
23
+ var api_1 = require("./api");
24
+ Object.defineProperty(exports, "getEmailProvider", { enumerable: true, get: function () { return api_1.getEmailProvider; } });
25
+ Object.defineProperty(exports, "getEmailProviderSync", { enumerable: true, get: function () { return api_1.getEmailProviderSync; } });
26
+ Object.defineProperty(exports, "getEmailProviderFast", { enumerable: true, get: function () { return api_1.getEmailProviderFast; } });
27
+ Object.defineProperty(exports, "normalizeEmail", { enumerable: true, get: function () { return api_1.normalizeEmail; } });
28
+ Object.defineProperty(exports, "emailsMatch", { enumerable: true, get: function () { return api_1.emailsMatch; } });
29
+ Object.defineProperty(exports, "Config", { enumerable: true, get: function () { return api_1.Config; } });
30
+ // ===== ADVANCED FEATURES =====
31
+ // Export utility functions for advanced use cases
32
+ var loader_1 = require("./loader");
33
+ Object.defineProperty(exports, "loadProviders", { enumerable: true, get: function () { return loader_1.loadProviders; } });
34
+ var concurrent_dns_1 = require("./concurrent-dns");
35
+ Object.defineProperty(exports, "detectProviderConcurrent", { enumerable: true, get: function () { return concurrent_dns_1.detectProviderConcurrent; } });
36
+ // ===== UTILITY FUNCTIONS =====
37
+ // Helper functions for common tasks
38
+ const loader_2 = require("./loader");
39
+ const api_2 = require("./api");
40
+ /**
41
+ * Get list of all supported email providers
42
+ * @returns Array of all email providers in the database
295
43
  */
296
44
  function getSupportedProviders() {
297
- return [...EMAIL_PROVIDERS];
45
+ const { providers } = (0, loader_2.loadProviders)();
46
+ return [...providers]; // Return a copy to prevent external mutations
298
47
  }
299
48
  /**
300
- * Checks if an email address uses a supported email provider.
301
- *
302
- * @param email - The email address to check
303
- * @returns true if the provider is supported, false otherwise
304
- *
305
- * @example
306
- * ```typescript
307
- * isEmailProviderSupported('user@gmail.com'); // true
308
- * isEmailProviderSupported('user@unknown.com'); // false
309
- * ```
310
- *
311
- * @remarks
312
- * This is a convenience function that uses {@link getEmailProviderLink} internally.
313
- * It only checks predefined domains, not DNS-based detection. For business
314
- * domain support checking, you would need to use {@link getEmailProviderLinkWithDNS}.
49
+ * Check if an email provider is supported
50
+ * @param email - Email address to check
51
+ * @returns true if the provider is supported
315
52
  */
316
53
  function isEmailProviderSupported(email) {
317
- const result = getEmailProviderLink(email);
54
+ const result = (0, api_2.getEmailProviderSync)(email);
318
55
  return result.provider !== null;
319
56
  }
320
57
  /**
321
- * Detects proxy services that obscure the actual email provider by analyzing MX records.
322
- *
323
- * @param mxRecords - Array of MX records from DNS lookup
324
- * @returns The name of the detected proxy service, or null if none detected
325
- *
326
- * @internal
327
- * @remarks
328
- * This function checks MX record patterns against known proxy/CDN services.
329
- * When a proxy is detected, it means we cannot determine the actual email
330
- * provider behind the proxy service. Currently detects:
331
- * - Cloudflare Email Routing
332
- * - CloudFront (AWS)
333
- * - Fastly
334
- * - MaxCDN
335
- * - KeyCDN
336
- * - Mailgun proxy configurations
337
- * - SendGrid proxy configurations
338
- *
339
- * @example
340
- * ```typescript
341
- * const mxRecords = [{ exchange: 'isaac.mx.cloudflare.net', priority: 10 }];
342
- * const proxy = detectProxyService(mxRecords);
343
- * console.log(proxy); // 'Cloudflare'
344
- * ```
58
+ * Extract domain from email address
59
+ * @param email - Email address
60
+ * @returns Domain portion or null if invalid
345
61
  */
346
- function detectProxyService(mxRecords) {
347
- const proxyPatterns = [
348
- { service: 'Cloudflare', patterns: ['mxrecord.io', 'mxrecord.mx', 'cloudflare'] },
349
- { service: 'CloudFront', patterns: ['cloudfront.net'] },
350
- { service: 'Fastly', patterns: ['fastly.com'] },
351
- { service: 'MaxCDN', patterns: ['maxcdn.com'] },
352
- { service: 'KeyCDN', patterns: ['keycdn.com'] },
353
- { service: 'Mailgun Proxy', patterns: ['mailgun.org', 'mg.', 'mailgun'] },
354
- { service: 'SendGrid Proxy', patterns: ['sendgrid.net', 'sendgrid.com'] }
355
- ];
356
- for (const mxRecord of mxRecords) {
357
- const exchange = mxRecord.exchange.toLowerCase();
358
- for (const proxyService of proxyPatterns) {
359
- for (const pattern of proxyService.patterns) {
360
- if (exchange.includes(pattern.toLowerCase())) {
361
- return proxyService.service;
362
- }
363
- }
364
- }
62
+ function extractDomain(email) {
63
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
64
+ if (!emailRegex.test(email)) {
65
+ return null;
365
66
  }
366
- return null;
67
+ return email.split('@')[1]?.toLowerCase() || null;
367
68
  }
368
69
  /**
369
- * Performs DNS-based detection for custom business domains using MX and TXT record analysis.
370
- * This function is used internally by {@link getEmailProviderLinkWithDNS} but can also be
371
- * called directly to analyze domain email configuration.
372
- *
373
- * @param domain - The domain to analyze (e.g., 'mycompany.com')
374
- * @param timeoutMs - Optional timeout for DNS queries in milliseconds (default: 5000ms)
375
- * @returns Promise resolving to DNSDetectionResult with provider info or proxy detection
376
- *
377
- * @example
378
- * ```typescript
379
- * const result = await detectProviderByDNS('microsoft.com');
380
- * console.log(result.provider?.companyProvider); // 'Microsoft 365 (Business)'
381
- * console.log(result.detectionMethod); // 'mx_record'
382
- * ```
383
- *
384
- * @remarks
385
- * **Detection Algorithm:**
386
- * 1. Checks rate limiting (max 10 requests per minute)
387
- * 2. Performs MX record lookup for the domain
388
- * 3. Checks if MX records match known proxy services (Cloudflare, etc.)
389
- * 4. If proxy detected, returns null provider with proxy info
390
- * 5. Otherwise, matches MX records against business email provider patterns
391
- * 6. If no MX match, falls back to TXT record analysis (SPF records, etc.)
392
- * 7. Returns the first matching provider or null if none found
393
- *
394
- * **Rate Limiting:**
395
- * - Maximum 10 DNS requests per 60-second window
396
- * - Rate limit exceeded returns error with retry information
397
- * - Prevents abuse and excessive DNS queries
398
- *
399
- * **Provider Patterns Checked:**
400
- * - Google Workspace: aspmx.l.google.com, aspmx2.googlemail.com, etc.
401
- * - Microsoft 365: *.protection.outlook.com, *.outlook.com
402
- * - ProtonMail: mail.protonmail.ch, mailsec.protonmail.ch
403
- * - FastMail: *.messagingengine.com
404
- * - And many others...
405
- *
406
- * **Error Handling:**
407
- * DNS lookup failures are caught and the function gracefully falls back
408
- * to the next detection method or returns null if all methods fail.
70
+ * Validate email format
71
+ * @param email - Email address to validate
72
+ * @returns true if valid format
409
73
  */
410
- async function detectProviderByDNS(domain, timeoutMs = DEFAULT_DNS_TIMEOUT) {
411
- const normalizedDomain = domain.toLowerCase();
412
- // Check rate limiting
413
- if (!dnsRateLimiter.isAllowed()) {
414
- const retryAfter = Math.ceil(dnsRateLimiter.getTimeUntilReset() / 1000);
415
- throw new Error(`Rate limit exceeded. DNS queries limited to ${RATE_LIMIT_MAX_REQUESTS} requests per minute. Try again in ${retryAfter} seconds.`);
416
- }
417
- // Get providers that support custom domain detection
418
- const customDomainProviders = EMAIL_PROVIDERS.filter(provider => provider.customDomainDetection &&
419
- (provider.customDomainDetection.mxPatterns || provider.customDomainDetection.txtPatterns));
420
- // Try MX record detection first with timeout
421
- try {
422
- const mxRecords = await withTimeout(resolveMxAsync(normalizedDomain), timeoutMs);
423
- // Check for proxy services first
424
- const proxyService = detectProxyService(mxRecords);
425
- if (proxyService) {
426
- return {
427
- provider: null,
428
- detectionMethod: 'proxy_detected',
429
- proxyService
430
- };
431
- }
432
- for (const provider of customDomainProviders) {
433
- if (provider.customDomainDetection?.mxPatterns) {
434
- for (const mxRecord of mxRecords) {
435
- const exchange = mxRecord.exchange.toLowerCase();
436
- for (const pattern of provider.customDomainDetection.mxPatterns) {
437
- if (exchange.includes(pattern.toLowerCase())) {
438
- return {
439
- provider,
440
- detectionMethod: 'mx_record'
441
- };
442
- }
443
- }
444
- }
445
- }
446
- }
447
- }
448
- catch (error) {
449
- // MX lookup failed, continue to TXT records
450
- }
451
- // Try TXT record detection with timeout
452
- try {
453
- const txtRecords = await withTimeout(resolveTxtAsync(normalizedDomain), timeoutMs);
454
- const flatTxtRecords = txtRecords.flat();
455
- for (const provider of customDomainProviders) {
456
- if (provider.customDomainDetection?.txtPatterns) {
457
- for (const txtRecord of flatTxtRecords) {
458
- const record = txtRecord.toLowerCase();
459
- for (const pattern of provider.customDomainDetection.txtPatterns) {
460
- if (record.includes(pattern.toLowerCase())) {
461
- return {
462
- provider,
463
- detectionMethod: 'txt_record'
464
- };
465
- }
466
- }
467
- }
468
- }
469
- }
470
- }
471
- catch (error) {
472
- // TXT lookup failed
473
- }
474
- return {
475
- provider: null,
476
- detectionMethod: null
477
- };
74
+ function isValidEmail(email) {
75
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
76
+ return emailRegex.test(email);
478
77
  }
479
78
  /**
480
- * Enhanced email provider detection with automatic DNS-based custom domain detection.
481
- * This is the recommended function for most use cases as it provides comprehensive
482
- * detection coverage including business domains and proxy services.
483
- *
484
- * @param email - The email address to analyze
485
- * @param timeoutMs - Optional timeout for DNS queries in milliseconds (default: 5000ms)
486
- * @returns Promise resolving to EmailProviderResult with provider info and detection method
487
- *
488
- * @example
489
- * ```typescript
490
- * // Consumer email (fast domain match)
491
- * const gmail = await getEmailProviderLinkWithDNS('user@gmail.com');
492
- * console.log(gmail.provider?.companyProvider); // 'Gmail'
493
- * console.log(gmail.detectionMethod); // 'domain_match'
494
- *
495
- * // Business domain (DNS detection)
496
- * const business = await getEmailProviderLinkWithDNS('user@mycompany.com');
497
- * console.log(business.provider?.companyProvider); // 'Google Workspace' (if detected)
498
- * console.log(business.detectionMethod); // 'mx_record'
499
- *
500
- * // Proxied domain (proxy detection)
501
- * const proxied = await getEmailProviderLinkWithDNS('user@proxied-domain.com');
502
- * console.log(proxied.provider); // null
503
- * console.log(proxied.proxyService); // 'Cloudflare'
504
- * console.log(proxied.detectionMethod); // 'proxy_detected'
505
- * ```
506
- *
507
- * @remarks
508
- * **Detection Hierarchy (in order):**
509
- * 1. **Domain Match**: Fast lookup against predefined domains (gmail.com, yahoo.com, etc.)
510
- * 2. **DNS MX Records**: Analyzes mail exchange records for business email providers
511
- * 3. **DNS TXT Records**: Checks SPF and verification records as fallback
512
- * 4. **Proxy Detection**: Identifies when domains are behind CDN/proxy services
513
- *
514
- * **Supported Detection Cases:**
515
- * - ✅ Consumer emails: gmail.com, yahoo.com, outlook.com, etc.
516
- * - ✅ Business domains: Google Workspace, Microsoft 365, ProtonMail Business, etc.
517
- * - ✅ Proxy services: Cloudflare, CloudFront, Fastly, etc.
518
- * - ✅ International providers: QQ Mail, NetEase, Yandex, etc.
519
- *
520
- * **Performance:**
521
- * - Fast for known consumer domains (synchronous JSON lookup)
522
- * - Additional DNS lookup time for unknown domains (~100-500ms)
523
- * - Graceful degradation if DNS lookups fail
524
- *
525
- * **Error Handling:**
526
- * - Invalid email addresses return null provider
527
- * - DNS lookup failures are caught and don't throw errors
528
- * - Network timeouts gracefully fall back to null detection
529
- *
530
- * **Use Cases:**
531
- * - Password reset flows ("Check your Gmail inbox")
532
- * - Login form enhancements (direct links to email providers)
533
- * - Email client detection for support purposes
534
- * - Business domain analysis for enterprise features
79
+ * Library metadata
535
80
  */
536
- async function getEmailProviderLinkWithDNS(email, timeoutMs = DEFAULT_DNS_TIMEOUT) {
537
- const domain = extractDomain(email);
538
- if (!domain) {
539
- return {
540
- provider: null,
541
- email,
542
- loginUrl: null
543
- };
544
- }
545
- // First try standard domain matching
546
- const provider = findEmailProvider(domain);
547
- if (provider) {
548
- return {
549
- provider,
550
- email,
551
- loginUrl: provider.loginUrl,
552
- detectionMethod: 'domain_match'
553
- };
554
- }
555
- // If no direct match, try DNS-based detection for custom domains
556
- const dnsResult = await detectProviderByDNS(domain, timeoutMs);
557
- if (dnsResult.provider) {
558
- return {
559
- provider: dnsResult.provider,
560
- email,
561
- loginUrl: dnsResult.provider.loginUrl,
562
- detectionMethod: dnsResult.detectionMethod || 'mx_record'
563
- };
564
- }
565
- // Handle proxy detection case
566
- if (dnsResult.detectionMethod === 'proxy_detected') {
567
- return {
568
- provider: null,
569
- email,
570
- loginUrl: null,
571
- detectionMethod: 'proxy_detected',
572
- proxyService: dnsResult.proxyService
573
- };
574
- }
575
- return {
576
- provider: null,
577
- email,
578
- loginUrl: null
579
- };
580
- }
81
+ exports.PROVIDER_COUNT = 93;
82
+ exports.DOMAIN_COUNT = 178;
581
83
  /**
582
- * Rate limiting configuration constants and utilities.
583
- * @public
84
+ * Default export for convenience
584
85
  */
585
- exports.RateLimit = {
586
- MAX_REQUESTS: RATE_LIMIT_MAX_REQUESTS,
587
- WINDOW_MS: RATE_LIMIT_WINDOW_MS,
588
- SimpleRateLimiter,
589
- /**
590
- * Gets the current rate limiter instance for inspection or testing.
591
- * @internal
592
- */
593
- getCurrentLimiter: () => dnsRateLimiter
594
- };
595
- // Default export for convenience
596
86
  exports.default = {
597
- getEmailProviderLink,
598
- getEmailProviderLinkWithDNS,
599
- detectProviderByDNS,
600
- isValidEmail,
601
- extractDomain,
602
- findEmailProvider,
603
- getSupportedProviders,
604
- isEmailProviderSupported,
605
- RateLimit: exports.RateLimit
87
+ getEmailProvider: api_2.getEmailProvider,
88
+ getEmailProviderSync: api_2.getEmailProviderSync,
89
+ getEmailProviderFast: api_2.getEmailProviderFast,
90
+ normalizeEmail: api_2.normalizeEmail,
91
+ emailsMatch: api_2.emailsMatch,
92
+ Config: api_2.Config,
93
+ PROVIDER_COUNT: exports.PROVIDER_COUNT,
94
+ DOMAIN_COUNT: exports.DOMAIN_COUNT
606
95
  };