What it demonstrates
- Email Routing - Routes emails to agents based on email addresses (e.g.,
agent+id@domain.com) - Secure Reply Routing - HMAC-signed headers for secure reply flows
- Email Parsing - Uses PostalMime to parse incoming emails
- Auto-Reply - Automatically responds to incoming emails with loop prevention
- State Management - Tracks email count and stores recent emails
- Security Tests - Comprehensive test suite including attack bypass attempts
Server Implementation
src/index.ts
Email Routing Strategies
1. Secure Reply Routing (Recommended for Replies)
Uses HMAC-signed headers to securely route email replies:- HMAC-SHA256 signatures prevent header forgery
- Timestamp validation prevents replay attacks
- Constant-time comparison prevents timing attacks
2. Address-Based Routing
Routes based on email address patterns:- With sub-addresses:
localpart+subaddress@domain.comโagentName: "localpart", agentId: "subaddress" - Without sub-addresses:
localpart@domain.comโagentName: defaultAgentName, agentId: "localpart"
3. Catch-All Routing
Routes all emails to a single agent:Composing Resolvers
Auto-Reply with Loop Prevention
The agent detects auto-replies to prevent infinite loops:Secure Reply Flow
When sending outbound emails, the agent signs headers:Testing
Automated Test Suite
Manual Testing
basic, unicode, long-subject, multiline, special-chars
Running the Example
1
Install dependencies
2
Configure secret
Update For production, use Wrangler secrets:
wrangler.jsonc with a unique secret:3
Start development server
4
Run tests
Deployment
1
Set production secret
2
Deploy
3
Configure email routing
In Cloudflare Dashboard:
- Go to
https://dash.cloudflare.com/<account-id>/<domain>/email/routing/routes - Add routing rules to point to your worker
4
Send emails
Send emails to addresses like:
support@yourdomain.comโ EmailAgent with ID โsupportโEmailAgent+urgent@yourdomain.comโ EmailAgent with ID โurgentโ
Security Tests
The test suite includes 15 attack scenarios:- Forged headers without signature
- Random/fake signatures
- Expired signatures
- Future timestamps
- Malformed timestamps
- SQL injection payloads
- Path traversal attempts
- Header injection (newlines)
- Unicode normalization attacks
- Case manipulation
- Long payload DoS attempts
- Null byte injection
npm run test:security
Related Examples
GitHub Webhook
Handle webhooks with signature verification
x402 Payments
HTTP payment gating with automatic payment
Workflows
Multi-step workflows with approval gates
Email Guide
In-depth guide to email routing