-
Notifications
You must be signed in to change notification settings - Fork 4
Add optional Resend delivery event logging #198
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
Merged
Changes from 3 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
dbd5ead
feat(shared): persist Resend delivery events
aspiers 1a9c922
feat(auth): receive signed Resend webhooks
aspiers 2bf9af4
docs(auth): document Resend webhook setup
aspiers f54524a
fix(auth): keep Resend monitoring explicitly optional
aspiers 8048eb0
fix(auth): log Resend events without persistence
aspiers c78b4e5
test(shared): surface database cleanup failures
aspiers def61ec
fix(auth): include subjects in Resend event logs
aspiers fb49dae
fix(auth): configure trusted proxies before middleware
aspiers c2055a8
docs(auth): clarify Resend is an optional provider
aspiers 54f2d0b
style(auth): order Resend webhook imports
aspiers 58a1e12
refactor(auth): normalize email delivery logs
aspiers fc369fe
fix(auth): filter account-wide Resend webhooks
aspiers 6bfa3db
fix(auth): redact OTPs from delivery logs
aspiers fd50cf0
style(auth): simplify OTP redaction regex
aspiers fa9e740
chore(ci): document safe internal HTTP URLs
aspiers d275b33
feat(auth): log Resend email open events
aspiers 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| --- | ||
| 'ePDS': minor | ||
| --- | ||
|
|
||
| Resend delivery events can now be measured against the sign-in code lifetime. | ||
|
|
||
| **Affects:** Operators | ||
|
|
||
| **Operators:** Register `https://<AUTH_HOSTNAME>/webhooks/resend` for the `email.sent`, `email.delivered`, `email.delivery_delayed`, `email.bounced`, and `email.failed` events, then set `RESEND_WEBHOOK_SECRET` to the endpoint's `whsec_...` signing secret. Delivery counts and latency statistics are exposed under `resendDelivery` in the authenticated `/metrics` response; the receiver remains disabled when the secret is unset. |
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
159 changes: 159 additions & 0 deletions
159
packages/auth-service/src/__tests__/resend-webhook.test.ts
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,159 @@ | ||
| import { afterEach, beforeEach, describe, expect, it } from 'vitest' | ||
| import { EpdsDb } from '@certified-app/shared' | ||
| import express from 'express' | ||
| import * as fs from 'node:fs' | ||
| import * as os from 'node:os' | ||
| import * as path from 'node:path' | ||
| import { randomUUID } from 'node:crypto' | ||
| import { Webhook } from 'svix' | ||
| import { createResendWebhookRouter } from '../routes/resend-webhook.js' | ||
|
|
||
| const WEBHOOK_SECRET = `whsec_${Buffer.from('test-webhook-secret').toString( | ||
| 'base64', | ||
| )}` | ||
|
|
||
| let db: EpdsDb | ||
| let dbPath: string | ||
|
|
||
| beforeEach(() => { | ||
| dbPath = path.join(os.tmpdir(), `resend-webhook-${randomUUID()}.sqlite`) | ||
| db = new EpdsDb(dbPath) | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| db.close() | ||
| for (const suffix of ['', '-wal', '-shm']) { | ||
| try { | ||
| fs.unlinkSync(dbPath + suffix) | ||
| } catch (err) { | ||
| if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err | ||
| } | ||
| } | ||
| }) | ||
|
|
||
| function makeEvent(type = 'email.sent'): Record<string, unknown> { | ||
| return { | ||
| type, | ||
| created_at: '2026-07-14T10:00:00.000Z', | ||
| data: { | ||
| email_id: 'resend-email-123', | ||
| to: ['person@example.com'], | ||
| from: 'ePDS <login@example.org>', | ||
| subject: 'Your sign-in code', | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| async function postWebhook( | ||
| event: Record<string, unknown>, | ||
| options: { | ||
| svixId?: string | ||
| validSignature?: boolean | ||
| includeHeaders?: boolean | ||
| } = {}, | ||
| ): Promise<{ status: number; json: Record<string, unknown> }> { | ||
| const app = express() | ||
| app.use(createResendWebhookRouter(db, WEBHOOK_SECRET)) | ||
| const server = app.listen(0) | ||
|
|
||
| try { | ||
| server.unref() | ||
| const port = await new Promise<number>((resolve, reject) => { | ||
| server.once('error', reject) | ||
| server.once('listening', () => { | ||
| const address = server.address() | ||
| if (typeof address === 'object' && address) resolve(address.port) | ||
| else reject(new Error('Failed to resolve ephemeral port')) | ||
| }) | ||
| }) | ||
|
|
||
| const payload = JSON.stringify(event) | ||
| const svixId = options.svixId ?? 'msg_test_123' | ||
| const timestamp = new Date() | ||
| const signature = | ||
| options.validSignature === false | ||
| ? 'v1,invalid' | ||
| : new Webhook(WEBHOOK_SECRET).sign(svixId, timestamp, payload) | ||
|
|
||
| const headers: Record<string, string> = { | ||
| 'Content-Type': 'application/json', | ||
| } | ||
| if (options.includeHeaders !== false) { | ||
| headers['svix-id'] = svixId | ||
| headers['svix-timestamp'] = String(Math.floor(timestamp.getTime() / 1000)) | ||
| headers['svix-signature'] = signature | ||
| } | ||
|
|
||
| const response = await fetch(`http://127.0.0.1:${port}/webhooks/resend`, { | ||
| method: 'POST', | ||
| headers, | ||
| body: payload, | ||
| }) | ||
| return { | ||
| status: response.status, | ||
| json: (await response.json()) as Record<string, unknown>, | ||
| } | ||
| } finally { | ||
| await new Promise<void>((resolve) => { | ||
| server.close(() => { | ||
| resolve() | ||
| }) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| describe('Resend webhook receiver', () => { | ||
| it('verifies, persists, and acknowledges a delivery event', async () => { | ||
| const result = await postWebhook(makeEvent('email.delivered')) | ||
|
|
||
| expect(result).toEqual({ | ||
| status: 200, | ||
| json: { received: true, duplicate: false }, | ||
| }) | ||
| expect(db.getResendEmailEvents('resend-email-123')).toMatchObject([ | ||
| { | ||
| svixId: 'msg_test_123', | ||
| eventType: 'email.delivered', | ||
| recipients: ['person@example.com'], | ||
| }, | ||
| ]) | ||
| }) | ||
|
|
||
| it('acknowledges a Svix retry without inserting it twice', async () => { | ||
| const first = await postWebhook(makeEvent(), { svixId: 'msg_retry' }) | ||
| const retry = await postWebhook(makeEvent(), { svixId: 'msg_retry' }) | ||
|
|
||
| expect(first.json.duplicate).toBe(false) | ||
| expect(retry).toEqual({ | ||
| status: 200, | ||
| json: { received: true, duplicate: true }, | ||
| }) | ||
| expect(db.getResendEmailEvents('resend-email-123')).toHaveLength(1) | ||
| }) | ||
|
|
||
| it('rejects an invalid signature before persisting the payload', async () => { | ||
| const result = await postWebhook(makeEvent(), { validSignature: false }) | ||
|
|
||
| expect(result.status).toBe(400) | ||
| expect(result.json).toEqual({ error: 'Invalid webhook signature' }) | ||
| expect(db.getResendEmailEvents('resend-email-123')).toHaveLength(0) | ||
| }) | ||
|
|
||
| it('rejects a request without the required Svix headers', async () => { | ||
| const result = await postWebhook(makeEvent(), { includeHeaders: false }) | ||
|
|
||
| expect(result).toEqual({ | ||
| status: 400, | ||
| json: { error: 'Invalid webhook request' }, | ||
| }) | ||
| expect(db.getResendEmailEvents('resend-email-123')).toHaveLength(0) | ||
| }) | ||
|
|
||
| it('rejects signed event types that are not used for delivery metrics', async () => { | ||
| const result = await postWebhook(makeEvent('email.opened')) | ||
|
|
||
| expect(result.status).toBe(400) | ||
| expect(result.json).toEqual({ error: 'Invalid webhook payload' }) | ||
| expect(db.getResendEmailEvents('resend-email-123')).toHaveLength(0) | ||
| }) | ||
| }) |
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
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.