-
Notifications
You must be signed in to change notification settings - Fork 21
feat: add NeverBounce email verification for transactional emails #1499
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
evanjacobson
merged 6 commits into
main
from
improvement/neverbounce-email-verification
Mar 25, 2026
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
c2019bb
feat: add NeverBounce email verification for transactional emails
evanjacobson 31e2342
build: regenerate @kilocode/trpc types after email router changes
evanjacobson 07bc77f
fix: preserve admin provider routing and check provider results
evanjacobson c10a3f2
Merge branch 'main' into improvement/neverbounce-email-verification
evanjacobson 719bca8
fix: distinguish NeverBounce rejection from provider misconfiguration
evanjacobson 8c93ab0
Merge branch 'main' into improvement/neverbounce-email-verification
evanjacobson File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| import { captureMessage } from '@sentry/nextjs'; | ||
| import { verifyEmail } from '@/lib/email-neverbounce'; | ||
|
|
||
| jest.mock('@sentry/nextjs', () => ({ | ||
| captureMessage: jest.fn(), | ||
| })); | ||
|
|
||
| const mockCaptureMessage = captureMessage as jest.MockedFunction<typeof captureMessage>; | ||
|
|
||
| let mockApiKey: string | undefined = 'test-api-key'; | ||
|
|
||
| jest.mock('@/lib/config.server', () => ({ | ||
| get NEVERBOUNCE_API_KEY() { | ||
| return mockApiKey; | ||
| }, | ||
| })); | ||
|
|
||
| const mockFetch = jest.fn(); | ||
| global.fetch = mockFetch; | ||
|
|
||
| function mockNeverBounceResponse(result: string, status = 'success') { | ||
| mockFetch.mockResolvedValue({ | ||
| ok: true, | ||
| json: async () => ({ | ||
| status, | ||
| result, | ||
| flags: ['has_dns', 'has_dns_mx'], | ||
| suggested_correction: '', | ||
| execution_time: 100, | ||
| }), | ||
| }); | ||
| } | ||
|
|
||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| mockApiKey = 'test-api-key'; | ||
| }); | ||
|
|
||
| describe('verifyEmail', () => { | ||
| it('returns true when API key is not configured', async () => { | ||
| mockApiKey = undefined; | ||
| expect(await verifyEmail('test@example.com')).toBe(true); | ||
| expect(mockFetch).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('returns true for valid emails', async () => { | ||
| mockNeverBounceResponse('valid'); | ||
| expect(await verifyEmail('good@example.com')).toBe(true); | ||
| expect(mockCaptureMessage).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('returns false for invalid emails and reports to Sentry', async () => { | ||
| mockNeverBounceResponse('invalid'); | ||
| expect(await verifyEmail('bad@example.com')).toBe(false); | ||
| expect(mockCaptureMessage).toHaveBeenCalledWith( | ||
| 'Blocked email send to invalid address', | ||
| expect.objectContaining({ | ||
| level: 'info', | ||
| tags: { source: 'neverbounce', result: 'invalid' }, | ||
| }) | ||
| ); | ||
| }); | ||
|
|
||
| it('returns false for disposable emails', async () => { | ||
| mockNeverBounceResponse('disposable'); | ||
| expect(await verifyEmail('temp@mailinator.com')).toBe(false); | ||
| }); | ||
|
|
||
| it('returns true for catchall emails', async () => { | ||
| mockNeverBounceResponse('catchall'); | ||
| expect(await verifyEmail('anyone@catchall.com')).toBe(true); | ||
| }); | ||
|
|
||
| it('returns true for unknown emails', async () => { | ||
| mockNeverBounceResponse('unknown'); | ||
| expect(await verifyEmail('mystery@example.com')).toBe(true); | ||
| }); | ||
|
|
||
| it('returns true on HTTP error (fail-open)', async () => { | ||
| mockFetch.mockResolvedValue({ ok: false, status: 500 }); | ||
| expect(await verifyEmail('test@example.com')).toBe(true); | ||
| }); | ||
|
|
||
| it('returns true on network error (fail-open) and reports to Sentry', async () => { | ||
| mockFetch.mockRejectedValue(new Error('fetch failed')); | ||
| expect(await verifyEmail('test@example.com')).toBe(true); | ||
| expect(mockCaptureMessage).toHaveBeenCalledWith( | ||
| 'NeverBounce verification check failed', | ||
| expect.objectContaining({ level: 'warning' }) | ||
| ); | ||
| }); | ||
|
|
||
| it('returns true on non-success API status and reports to Sentry', async () => { | ||
| mockNeverBounceResponse('valid', 'auth_failure'); | ||
| expect(await verifyEmail('test@example.com')).toBe(true); | ||
| expect(mockCaptureMessage).toHaveBeenCalledWith( | ||
| 'NeverBounce API returned non-success status: auth_failure', | ||
| expect.objectContaining({ level: 'warning' }) | ||
| ); | ||
| }); | ||
|
|
||
| it('passes email and API key as query parameters', async () => { | ||
| mockNeverBounceResponse('valid'); | ||
| await verifyEmail('user@test.com'); | ||
| const calledUrl = new URL(mockFetch.mock.calls[0][0]); | ||
| expect(calledUrl.origin + calledUrl.pathname).toBe( | ||
| 'https://api.neverbounce.com/v4.2/single/check' | ||
| ); | ||
| expect(calledUrl.searchParams.get('key')).toBe('test-api-key'); | ||
| expect(calledUrl.searchParams.get('email')).toBe('user@test.com'); | ||
| }); | ||
|
|
||
| it('sets a 5-second timeout on the fetch call', async () => { | ||
| mockNeverBounceResponse('valid'); | ||
| await verifyEmail('user@test.com'); | ||
| const fetchOptions = mockFetch.mock.calls[0][1]; | ||
| expect(fetchOptions.signal).toBeDefined(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| import { NEVERBOUNCE_API_KEY } from '@/lib/config.server'; | ||
| import { captureMessage } from '@sentry/nextjs'; | ||
|
|
||
| type NeverBounceResult = 'valid' | 'invalid' | 'disposable' | 'catchall' | 'unknown'; | ||
|
|
||
| type NeverBounceResponse = { | ||
| status: string; | ||
| result: NeverBounceResult; | ||
| flags: string[]; | ||
| suggested_correction: string; | ||
| execution_time: number; | ||
| }; | ||
|
|
||
| const BLOCKED_RESULTS = new Set<NeverBounceResult>(['invalid', 'disposable']); | ||
evanjacobson marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| /** | ||
| * Returns true if the email is safe to send to, false if it should be skipped. | ||
| * If NeverBounce is not configured or the check fails, defaults to allowing the send. | ||
| */ | ||
| export async function verifyEmail(email: string): Promise<boolean> { | ||
| if (!NEVERBOUNCE_API_KEY) { | ||
| return true; | ||
| } | ||
|
|
||
| try { | ||
| const url = new URL('https://api.neverbounce.com/v4.2/single/check'); | ||
| url.searchParams.set('key', NEVERBOUNCE_API_KEY); | ||
| url.searchParams.set('email', email); | ||
|
|
||
| const response = await fetch(url, { signal: AbortSignal.timeout(5_000) }); | ||
| if (!response.ok) { | ||
| console.warn(`[neverbounce] API returned ${response.status} for ${email}, allowing send`); | ||
| return true; | ||
| } | ||
|
|
||
| const data: NeverBounceResponse = await response.json(); | ||
|
|
||
| if (data.status !== 'success') { | ||
| console.warn(`[neverbounce] API returned status=${data.status} for ${email}, allowing send`); | ||
| captureMessage(`NeverBounce API returned non-success status: ${data.status}`, { | ||
| level: 'warning', | ||
| tags: { source: 'neverbounce' }, | ||
| extra: { email, status: data.status }, | ||
| }); | ||
| return true; | ||
| } | ||
|
|
||
| if (BLOCKED_RESULTS.has(data.result)) { | ||
| captureMessage(`Blocked email send to ${data.result} address`, { | ||
| level: 'info', | ||
| tags: { source: 'neverbounce', result: data.result }, | ||
| extra: { email, flags: data.flags, suggested_correction: data.suggested_correction }, | ||
| }); | ||
| console.log(`[neverbounce] Blocked send to ${email}: result=${data.result}`); | ||
| return false; | ||
| } | ||
|
|
||
| return true; | ||
| } catch (error) { | ||
| const errorMessage = error instanceof Error ? error.message : String(error); | ||
| console.warn(`[neverbounce] Check failed for ${email}: ${errorMessage}, allowing send`); | ||
| captureMessage('NeverBounce verification check failed', { | ||
| level: 'warning', | ||
| tags: { source: 'neverbounce' }, | ||
| extra: { email, error: errorMessage }, | ||
| }); | ||
| return true; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -76,7 +76,30 @@ async function trySendEmail( | |
| return false; | ||
| } | ||
| try { | ||
| await sendEmail({ to: userEmail, templateName, templateVars, subjectOverride }); | ||
| const emailResult = await sendEmail({ | ||
| to: userEmail, | ||
| templateName, | ||
| templateVars, | ||
| subjectOverride, | ||
| }); | ||
|
|
||
| if (!emailResult.sent) { | ||
evanjacobson marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if (emailResult.reason === 'provider_not_configured') { | ||
| // Transient — credentials may be added later; remove idempotency guard so the next cron run can retry | ||
| await database | ||
| .delete(kiloclaw_email_log) | ||
| .where( | ||
| and( | ||
| eq(kiloclaw_email_log.user_id, userId), | ||
| eq(kiloclaw_email_log.email_type, emailType) | ||
| ) | ||
| ); | ||
| } | ||
| // For neverbounce_rejected the address is permanently invalid — keep the | ||
| // idempotency row so we don't re-verify on every sweep. | ||
|
Comment on lines
+98
to
+99
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This comment seems out of place? The code below it doesn't relate to it? |
||
| summary.emails_skipped++; | ||
| return false; | ||
| } | ||
| } catch (error) { | ||
| try { | ||
| await database | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.